code
stringlengths
1
13.8M
library(onls) DNase1 <- subset(DNase, Run == 1) DNase1$density <- sapply(DNase1$density, function(x) rnorm(1, x, 0.1 * x)) mod1 <- onls(density ~ Asym/(1 + exp((xmid - log(conc))/scal)), data = DNase1, start = list(Asym = 3, xmid = 0, scal = 1)) mod1 x <- c(0, 10, 20, 30, 40, 50, 60, 70, 80, 85, 90, 95, 100, 105) y <- c(4.14, 8.52, 16.31, 32.18, 64.62, 98.76, 151.13, 224.74, 341.35, 423.36, 522.78, 674.32, 782.04, 920.01) DAT <- data.frame(x, y) mod4 <- onls(y ~ b1 * 10^(b2 * x/(b3 + x)), data = DAT, start = list(b1 = 1, b2 = 5, b3 = 100)) coef(mod4) deviance_o(mod4) mod5 <- onls(y ~ b1 * 10^(b2 * x/(b3 + x)), data = DAT, start = list(b1 = 1, b2 = 5, b3 = 100), extend = c(0, 0)) check_o(mod5) x <- 1:100 y <- x^2 set.seed(123) y <- sapply(y, function(a) rnorm(1, a, 0.1 * a)) DAT <- data.frame(x, y) mod6 <- onls(y ~ x^a, data = DAT, start = list(a = 1)) mod6 mod7 <- onls(y ~ x^a, data = DAT, start = list(a = 10), window = 17) mod7 plot(mod1) plot(mod1, xlim = c(0, 1), ylim = c(0, 1)) summary(mod1) coef(mod1) vcov(mod1) predict(mod1, newdata = data.frame(conc = 6)) confint(mod1) residuals(mod1) fitted(mod1) deviance(mod1) logLik(mod1) residuals_o(mod1) deviance_o(mod1) logLik_o(mod1) x0(mod1) y0(mod1) plot(mod1) plot(mod1, xlim = c(0, 0.25), ylim = c(0, 0.25))
specInfo <- read.csv("sample-data.csv") specFiltered <- subset(data, nutr >= "5") outFile <- tempfile(fileext=".csv") write.csv(specFiltered, file=outFile, row.names=FALSE)
setClass(Class = "PT.Nested.Design", representation = representation(nested.space = "numeric", no.complex = "numeric"), contains = "PT.Design") setMethod( f="initialize", signature="PT.Nested.Design", definition=function(.Object, region, spacing, nested.space = numeric(0), no.complex = numeric(0), design.axis, plus.sampling, path = character(0), ...){ filenames <- character(0) file.index <- numeric(0) if(length(path) > 0){ filenames <- get.shapefile.names(path) file.index <- 1 } [email protected] <- region [email protected] <- plus.sampling .Object@spacing <- spacing [email protected] <- nested.space [email protected] <- no.complex [email protected] <- design.axis .Object@path <- path .Object@filenames <- filenames [email protected] <- file.index validObject(.Object) return(.Object) } ) setValidity("PT.Nested.Design", function(object){ if(length(object@path) > 1){ return("You must only specify one path. All transect shapefiles must be in the same folder.") } nested.space <- [email protected] if(length(nested.space) > 0){ if(any(!as.integer(nested.space) == nested.space)){ return("The nested space value should be an integer specifying how many point in the main grid are between each nested point.") } } if(any(ifelse([email protected] != 0, TRUE, FALSE))){ warning("Only a design axis of 0 is currently implemented, other values will be ignored at present.", call. = FALSE, immediate. = TRUE) } if(length([email protected]) == 0 & length([email protected]) == 0){ return("A value must be supplied for either nested.space or no.complex.") } return(TRUE) } ) setMethod( f="generate.transects", signature="PT.Nested.Design", definition=function(object, region = NULL, index = NULL, silent = FALSE){ if(is.null(region) | class(region) != "Region"){ region <- [email protected] region <- get(region, pos = 1) warning("Obtaining region object from the global environment.", call. = FALSE, immediate. = TRUE) } if(length(object@path) == 0){ read.from.file = FALSE }else if(length(object@path) > 0){ read.from.file = TRUE } if(read.from.file){ stop("Cannot currently load surveys of this type from file.") return(NULL) }else{ if(length([email protected]) > 0){ strata.names <- [email protected] strata.no <- length([email protected]) }else{ strata.names <- [email protected] strata.no <- 1 } if(length(object@spacing) != strata.no){ if(length(object@spacing) > 1){ warning("Number of spacing values not equal to number of strata. Using first value only.", immediate. = TRUE, call. = FALSE) } object@spacing <- rep(object@spacing[1], strata.no) } nested = FALSE if(length([email protected]) > 0){ nested = TRUE if(strata.no != length([email protected])){ [email protected] <- rep([email protected][1], strata.no) if(!silent){ warning("The number of nested space values did not match the number of strata. Only the first value will be used.", call. = FALSE, immediate. = TRUE) } } }else{ if(strata.no != length([email protected])){ [email protected] <- rep([email protected][1], strata.no) if(!silent){ warning("The number of no.complex values did not match the number of strata. Only the first value will be used.", call. = FALSE, immediate. = TRUE) } } } for (strat in seq(along = region@coords)) { spacing <- object@spacing[strat] start.x <- region@box[["xmin"]] + runif(1, 0, spacing) start.y <- region@box[["ymin"]] + runif(1, 0, spacing) x.vals <- seq(start.x, region@box[["xmax"]], by = spacing) y.vals <- seq(start.y, region@box[["ymax"]], by = spacing) temp.coords <- expand.grid(x.vals, y.vals) names(temp.coords) <- c("x","y") to.keep <- in.polygons(region@coords[[strat]], pts = temp.coords, boundary = TRUE) gridpoints <- temp.coords[to.keep, ] to.discard <- in.polygons(region@gaps[[strat]], pts = gridpoints, boundary = TRUE) gridpoints <- gridpoints[!to.discard,] gridpoints$strata <- rep(strata.names[strat], nrow(gridpoints)) if(nested){ no.point.space <- [email protected][strat] nested.spacing <- no.point.space*spacing start.x.offset <- sample(0:(no.point.space-1), 1, prob = rep(1/(no.point.space), (no.point.space))) start.y.offset <- sample(0:(no.point.space-1), 1, prob = rep(1/(no.point.space), (no.point.space))) nested.start.x <- start.x + start.x.offset*spacing nested.start.y <- start.y + start.y.offset*spacing nested.x.vals <- seq(nested.start.x, region@box[["xmax"]], by = nested.spacing) nested.y.vals <- seq(nested.start.y, region@box[["ymax"]], by = nested.spacing) nested.temp.coords <- expand.grid(nested.x.vals, nested.y.vals) names(nested.temp.coords) <- c("x","y") to.keep <- in.polygons(region@coords[[strat]], pts = nested.temp.coords, boundary = TRUE) nested.gridpoints <- nested.temp.coords[to.keep, ] to.discard <- in.polygons(region@gaps[[strat]], pts = nested.gridpoints, boundary = TRUE) nested.gridpoints <- nested.gridpoints[!to.discard,] }else{ index <- sample(1:nrow(gridpoints), [email protected][strat]) nested.gridpoints <- gridpoints[index,] } nested.gridpoints$strata <- rep(strata.names[strat], nrow(nested.gridpoints)) gridpoints <- cbind(gridpoints, ID = 1:nrow(gridpoints)) duplicate.ID <- merge(gridpoints, nested.gridpoints, by = c("x","y"))$ID gridpoints <- gridpoints[!gridpoints$ID %in% duplicate.ID,] ID.col <- which(names(gridpoints) == "ID") gridpoints <- gridpoints[,-ID.col] gridpoints$ac.simple <- rep(TRUE, nrow(gridpoints)) nested.gridpoints$ac.simple <- rep(FALSE, nrow(nested.gridpoints)) all.gridpoints <- rbind(gridpoints, nested.gridpoints) if (strat == 1) { transects <- all.gridpoints } else{ transects <- rbind(transects, all.gridpoints) } } } sampler.info <- data.frame(ID = 1:nrow(transects), X = transects$x, Y = transects$y, region = transects$strata, ac.simple = transects$ac.simple, effort = rep(1, nrow(transects))) point.transect <- new(Class = "Point.Transect", region = region, sampler.info = sampler.info) return(point.transect) } )
library("quanteda.textmodels") pdf(file = tempfile(".pdf"), width = 10, height = 10) test_that("test textplot_scale1d wordfish in the most basic way", { wf <- textmodel_wordfish(dfm(tokens(data_corpus_irishbudget2010)), dir = c(6, 5)) expect_false(identical(textplot_scale1d(wf, sort = TRUE), textplot_scale1d(wf, sort = FALSE))) expect_silent(textplot_scale1d(wf, sort = TRUE, groups = quanteda::docvars(data_corpus_irishbudget2010, "party"))) expect_silent(textplot_scale1d(wf, sort = FALSE, groups = quanteda::docvars(data_corpus_irishbudget2010, "party"))) expect_silent( textplot_scale1d(wf, doclabels = apply(quanteda::docvars(data_corpus_irishbudget2010, c("name", "party")), 1, paste, collapse = " ")) ) p1 <- textplot_scale1d(wf, margin = "features", sort = TRUE) p2 <- textplot_scale1d(wf, margin = "features", sort = FALSE) p1$plot_env <- NULL p2$plot_env <- NULL expect_equal(p1, p2, check.environment = FALSE) }) test_that("test textplot_scale1d wordscores in the most basic way", { mt <- dfm(tokens(data_corpus_irishbudget2010)) ws <- quanteda.textmodels::textmodel_wordscores(mt, c(rep(NA, 4), -1, 1, rep(NA, 8))) pr <- suppressWarnings(predict(ws, mt, force = TRUE)) ca <- quanteda.textmodels::textmodel_ca(mt) expect_false(identical(textplot_scale1d(pr, sort = TRUE), textplot_scale1d(pr, sort = FALSE))) expect_silent(textplot_scale1d(pr, sort = TRUE, groups = quanteda::docvars(data_corpus_irishbudget2010, "party"))) expect_silent(textplot_scale1d(pr, sort = FALSE, groups = quanteda::docvars(data_corpus_irishbudget2010, "party"))) expect_silent(textplot_scale1d(pr, doclabels = apply(quanteda::docvars(data_corpus_irishbudget2010, c("name", "party")), 1, paste, collapse = " "))) expect_silent(textplot_scale1d(ca)) expect_silent(textplot_scale1d(ca, groups = quanteda::docvars(data_corpus_irishbudget2010, "party"))) p1 <- textplot_scale1d(ws, margin = "features", sort = TRUE) p2 <- textplot_scale1d(ws, margin = "features", sort = FALSE) p1$plot_env <- NULL p2$plot_env <- NULL expect_equal(p1, p2, check.environment = FALSE) expect_error( textplot_scale1d(ws, margin = "documents"), "This margin can only be run on a predicted wordscores object" ) expect_error( suppressWarnings(textplot_scale1d(predict(ws), margin = "features")), "This margin can only be run on a fitted wordscores object" ) }) dev.off()
dml <- function(x,tail,scale=1,log=FALSE, second.type=FALSE){ stopifnot(tail > 0, tail <= 1, scale > 0) if (length(tail) > 1){ stop("length(tail) must be 1.") } if(log == TRUE & any(x <= 0)) { stop("For x <= 0 the density is zero. You schould not use log = T") } ind <- which(x <= 0) x[ind] <- 0 if (second.type==FALSE) { y <- dml1(x,tail,scale) } else { y <- dml2(x/scale,tail)/scale } y[ind] <- 0 if (!log) {return(y)} else { stopifnot(all(y != 0)) return(log(y)) } } dml1 <- function(t,tail,scale=1,log=FALSE) { ml <- (t^(tail-1)/(scale^tail))*mlf(-(t/scale)^tail, tail, tail, 1) if (log) { ml <- log(ml) } return(ml) } dml2 <- function(u,tail) { gamma <- (cos(pi*tail/2))^(1/tail) h <- (1/tail)*u^(-1-1/tail)*stabledist::dstable(x = u^(-1/tail), alpha = tail, beta = 1, gamma = gamma, delta = 0, pm = 1) } pml <- function(q, tail, scale=1, second.type=FALSE, lower.tail=TRUE, log.p=FALSE) { stopifnot(tail > 0, tail <= 1, scale > 0) ind <- which(q <= 0) q[ind] <- 1 q <- q/scale if (!second.type){ p <- pml1(q,tail) } else { p <- pml2(q,tail) } if (!lower.tail) { p <- 1-p } if (log.p) { p <- log(p) } p[ind] <- 0 return(p) } pml1 <- function(q,tail) { p <- 1 - mlf(-(q)^tail,tail,1,1) } pml2 <- function(q,tail) { gamma <- (cos(pi*tail/2))^(1/tail) p <- stabledist::pstable(q^(-1/tail), alpha=tail, beta=1, gamma=gamma, delta=0, pm=1, lower.tail = FALSE) } qml <- function(p, tail, scale=1, second.type=FALSE, lower.tail=TRUE, log.p=FALSE) { stopifnot(tail > 0, tail <= 1, scale > 0, p >= 0, p <= 1) if (log.p) { p <- exp(p) } if (!lower.tail) { p <- 1-p } if (!second.type) { q <- qml1(p, tail, scale) } else { q <- scale * qml2(p, tail) } q[p == 0] <- 0 return(q) } qml1 <- function(p,tail,scale=1) { x <- numeric(length(p)) for (i in seq_along(p)) { qml_p <- function(t) {pml(exp(t),tail,scale) - p[i]} x[i] <- stats::uniroot(qml_p, interval = c(log(10^-14),log(100)), extendInt="yes", tol = 1e-14)$root } return(exp(x)) } qml2 <- function(p, tail){ gamma <- (cos(pi*tail/2))^(1/tail) q <- stabledist::qstable(p, alpha=tail, beta=1, gamma=gamma, delta=0, pm=1, lower.tail=FALSE)^(-tail) } rml <- function(n,tail,scale=1, second.type=FALSE){ stopifnot(tail > 0, tail <= 1, scale > 0, is.numeric(n), length(n) == 1) if (!second.type){ x <- scale * rml1(n,tail) } else { x <- scale * rml2(n,tail) } return(x) } rml1 <- function(n, tail){ if (tail == 1) return(stats::rexp(n)) gamma <- (cos(pi*tail/2))^(1/tail) y <- stabledist::rstable(n, alpha=tail, beta=1, gamma=gamma, delta=0, pm=1) x <- stats::rexp(n) y * x^(1/tail) } rml2 <- function(n, tail){ gamma <- (cos(pi*tail/2))^(1/tail) stabledist::rstable(n, alpha=tail, beta=1, gamma=gamma, delta=0, pm=1)^(-tail) }
censbnd <- function(lambda,p,crate,rootint=c(0.1,1000)) { eqn<-function(M,lambda,p,crate) { lhs=p*((1-exp(-M*lambda))/lambda) sum(lhs)-M*crate } uniroot(eqn,rootint,lambda=lambda,p,crate=crate) }
FV_pre_quad=function(data,years=10){ n=years u=mean(data) u2=mean(data^2) final_value=n+(n*(n+1)/2)*u+(n*(n+1)/4) *(1+(2*n-1)/3)*u2 return(final_value) }
MakeRelationshipExtended <- function(ped, counseland.id){ iid <- ped[,"indID"] fid <- ped[,"fatherID"] mid <- ped[,"motherID"] gender <- ped[,"gender"] relationship <- rep(0,nrow(ped)) current.id <- counseland.id indiv <- iid == current.id relationship[indiv] <- 1 sibs <- NULL nep <- NULL spouse.id <- NULL potent.spouse.id <- NULL if (sum(indiv)!=0){ if (fid[indiv] !=0 ){ relationship[iid == fid[indiv]] <- 4 sibs <- c(sibs, which(fid == fid[indiv] & !indiv)) } if (mid[indiv]!=0 ){ relationship[iid == mid[indiv]] <- 4 sibs <- c(sibs, which(mid == mid[indiv] & !indiv)) } if (length(unique(sibs))!=0){ relationship[unique(sibs)] <- 2 for (i in 1:length(unique(sibs))){ nep <- c(nep,which(fid==iid[unique(sibs)[i]]|mid==iid[unique(sibs)[i]])) relationship[iid==fid[unique(sibs)[i]] | iid==mid[unique(sibs)[i]] ] <- 4 } if (sum(nep)!=0) relationship[unique(nep)] <- 5 } } if(sum(indiv)!=0){ if (gender[indiv]==0){ relationship[mid==iid[indiv]] <- 3 child <- which(mid==iid[indiv]) if (sum(child)!=0){ spouse.id <- unique(fid[child]) if (sum(spouse.id)!=0){ for (i in 1:length(spouse.id)){ relationship[iid==spouse.id[i]] <- 6 } } } }else { relationship[fid==iid[indiv]] <- 3 child <- which(fid==iid[indiv]) if (sum(child)!=0){ spouse.id <- unique(mid[child]) if (sum(spouse.id)!=0){ for ( i in 1:length(spouse.id)){ relationship[iid==spouse.id[i]] <- 6 } } } } } gcid <- is.element(fid, iid[relationship==3]) | is.element(mid, iid[relationship==3]) relationship[gcid] <- 15 if (sum(gcid)!=0) { child.spouse.id <- unique(c(fid[gcid],mid[gcid])) if (sum(child.spouse.id)!=0){ for ( i in 1:length(child.spouse.id)){ csid <- iid==child.spouse.id[i] if (sum(csid)!=0){ if (relationship[csid]==0) relationship[csid] <- 14 } } } } current.fid <- fid[indiv] current.mid <- mid[indiv] indiv <- iid==current.fid if(sum(indiv, na.rm=TRUE)!=0) { if (fid[indiv]!=0){ relationship[iid==fid[indiv]] <- 8 relationship[fid==fid[indiv] & !indiv] <- 9 } if (mid[indiv]!=0){ relationship[iid==mid[indiv]] <- 8 relationship[mid==mid[indiv] & !indiv] <- 9 } cid <- is.element(fid, iid[relationship==9]) | is.element(mid, iid[relationship==9]) relationship[cid] <- 10 } indiv <- iid==current.mid if(sum(indiv, na.rm=TRUE)!=0){ if (fid[indiv] != 0){ relationship[iid==fid[indiv]] <- 11 relationship[fid==fid[indiv] & !indiv] <- 12 } if (mid[indiv] !=0){ relationship[iid==mid[indiv]] <- 11 relationship[mid==mid[indiv] & !indiv] <- 12 } cid <- is.element(fid, iid[relationship==12]) | is.element(mid, iid[relationship==12]) relationship[cid] <- 13 } if (sum(nep)!=0) potent.spouse.id <- unique(c(fid[nep],mid[nep])) if (sum(potent.spouse.id)!=0){ for ( i in 1:length(potent.spouse.id)){ indiv <- iid==potent.spouse.id[i] if (sum(indiv)!=0){ if (relationship[indiv]==0){ relationship[indiv] <- 7 } } } } cousin <- which(relationship==10 | relationship == 13) if (sum(cousin)!=0) { uncle.spouse.id <- unique(c(fid[cousin],mid[cousin])) if (sum(uncle.spouse.id)!=0){ for ( i in 1:length(uncle.spouse.id)){ indiv <- iid==uncle.spouse.id[i] if (sum(indiv)!=0){ if (relationship[indiv]==0){ relationship[indiv] <- 16 } } } } } return(relationship) }
context("(de)serialization of PCA models") test_that("PCA models can be serialized and unserialized correctly", { models <- list() for (whiten in c(FALSE, TRUE)) { for (transform_input in c(FALSE, TRUE)) { model <- cuda_ml_pca( iris[1:4], n_components = 3, whiten = whiten, transform_input = transform_input ) models <- append(models, list(model)) } } for (model in models) { actual_inv_transform <- callr::r( function(model_state, expected_components, expected_expl_var, expected_expl_var_ratio, expected_sg_vals, expected_m, expected_tf_data, whiten) { library(cuda.ml) library(testthat) stopifnot(has_cuML()) model <- cuda_ml_unserialize(model_state) expect_equal(model$components, expected_components) expect_equal(model$explained_variance, expected_expl_var) expect_equal( model$explained_variance_ratio, expected_expl_var_ratio ) expect_equal(model$singular_values, expected_sg_vals) expect_equal(model$mean, expected_m) expect_equal(model$transformed_data, expected_tf_data) if (!is.null(model$transformed_data) && !whiten) { cuda_ml_inverse_transform(model, model$transformed_data) } else { NULL } }, args = list( model_state = cuda_ml_serialize(model), expected_components = model$components, expected_expl_var = model$explained_variance, expected_expl_var_ratio = model$explained_variance_ratio, expected_sg_vals = model$singular_values, expected_m = model$mean, expected_tf_data = model$transformed_data, whiten = whiten ) ) if (!is.null(model$transformed_data) && !whiten) { expected_inv_transform <- cuda_ml_inverse_transform( model, model$transformed_data ) expect_equal(expected_inv_transform, actual_inv_transform) } else { succeed() } } })
test_that("Simple colours convert", { expect_equal(colourName("red"), "red") expect_equal(colourName(" expect_equal(colourName(" expect_equal(colourName(" expect_equal(colourName(" expect_equal(colourName(" })
gpb.interprete <- function(model, data, idxset, num_iteration = NULL) { tree_dt <- gpb.model.dt.tree(model = model, num_iteration = num_iteration) num_class <- model$.__enclos_env__$private$num_class tree_interpretation_dt_list <- vector(mode = "list", length = length(idxset)) pred_mat <- t( model$predict( data = data[idxset, , drop = FALSE] , num_iteration = num_iteration , predleaf = TRUE ) ) leaf_index_dt <- data.table::as.data.table(x = pred_mat) leaf_index_mat_list <- lapply( X = leaf_index_dt , FUN = function(x) matrix(x, ncol = num_class, byrow = TRUE) ) tree_index_mat_list <- lapply( X = leaf_index_mat_list , FUN = function(x) { matrix(seq_len(length(x)) - 1L, ncol = num_class, byrow = TRUE) } ) for (i in seq_along(idxset)) { tree_interpretation_dt_list[[i]] <- single.row.interprete( tree_dt = tree_dt , num_class = num_class , tree_index_mat = tree_index_mat_list[[i]] , leaf_index_mat = leaf_index_mat_list[[i]] ) } return(tree_interpretation_dt_list) } single.tree.interprete <- function(tree_dt, tree_id, leaf_id) { single_tree_dt <- tree_dt[tree_index == tree_id, ] leaf_dt <- single_tree_dt[leaf_index == leaf_id, .(leaf_index, leaf_parent, leaf_value)] node_dt <- single_tree_dt[!is.na(split_index), .(split_index, split_feature, node_parent, internal_value)] feature_seq <- character(0L) value_seq <- numeric(0L) leaf_to_root <- function(parent_id, current_value) { value_seq <<- c(current_value, value_seq) if (!is.na(parent_id)) { this_node <- node_dt[split_index == parent_id, ] feature_seq <<- c(this_node[["split_feature"]], feature_seq) leaf_to_root( parent_id = this_node[["node_parent"]] , current_value = this_node[["internal_value"]] ) } } leaf_to_root( parent_id = leaf_dt[["leaf_parent"]] , current_value = leaf_dt[["leaf_value"]] ) return( data.table::data.table( Feature = feature_seq , Contribution = diff.default(value_seq) ) ) } multiple.tree.interprete <- function(tree_dt, tree_index, leaf_index) { interp_dt <- data.table::rbindlist( l = mapply( FUN = single.tree.interprete , tree_id = tree_index , leaf_id = leaf_index , MoreArgs = list( tree_dt = tree_dt ) , SIMPLIFY = FALSE , USE.NAMES = TRUE ) , use.names = TRUE ) interp_dt <- interp_dt[, .(Contribution = sum(Contribution)), by = "Feature"] interp_dt[, abs_contribution := abs(Contribution)] data.table::setorder( x = interp_dt , -abs_contribution ) interp_dt[, abs_contribution := NULL] return(interp_dt) } single.row.interprete <- function(tree_dt, num_class, tree_index_mat, leaf_index_mat) { tree_interpretation <- vector(mode = "list", length = num_class) for (i in seq_len(num_class)) { next_interp_dt <- multiple.tree.interprete( tree_dt = tree_dt , tree_index = tree_index_mat[, i] , leaf_index = leaf_index_mat[, i] ) if (num_class > 1L) { data.table::setnames( x = next_interp_dt , old = "Contribution" , new = paste("Class", i - 1L) ) } tree_interpretation[[i]] <- next_interp_dt } if (num_class == 1L) { tree_interpretation_dt <- tree_interpretation[[1L]] } else { tree_interpretation_dt <- Reduce( f = function(x, y) { merge(x, y, by = "Feature", all = TRUE) } , x = tree_interpretation ) for (j in 2L:ncol(tree_interpretation_dt)) { data.table::set( x = tree_interpretation_dt , i = which(is.na(tree_interpretation_dt[[j]])) , j = j , value = 0.0 ) } } return(tree_interpretation_dt) }
eggers.test = function(x) { x = x if (x$k < 10) { warning(paste("Your meta-analysis contains k =", x$k, "studies. Egger's test may lack the statistical power to detect bias when the number of studies is small (i.e., k<10).")) } if (class(x)[1] %in% c("meta", "metabin", "metagen", "metacont", "metacor", "metainc", "metaprop")) { eggers = meta::metabias(x, k.min = 3, method = "linreg") intercept = as.numeric(eggers$estimate[1]) %>% round(digits = 3) se = as.numeric(eggers$estimate[2]) LLCI = intercept - 1.96 * se %>% round(digits = 1) ULCI = intercept + 1.96 * se %>% round(digits = 1) CI = paste(LLCI, "-", ULCI, sep = "") t = as.numeric(eggers$statistic) %>% round(digits = 3) df = as.numeric(eggers$parameters) p = as.numeric(eggers$p.value) %>% round(digits = 5) df = data.frame(Intercept = intercept, ConfidenceInterval = CI, t = t, p = p) row.names(df) = "Egger's test" } else { stop("x must be of type 'metabin', 'metagen', 'metacont', 'metainc' or 'metaprop'") } return(df) }
computeLeafOrder<-function ( merging, dbg=0 ) { m<-dim(merging)[1] if (dbg) printVar(m) n<-m+1 if (dbg) printVar(m) lifo<-rep(0,m) lifoIdx<-0 ordering<-rep(0,n) oi<-1 if (dbg) cat(sprintf('pushing %d\n',m)) lifoIdx<-lifoIdx+1 lifo[lifoIdx]<-m while (lifoIdx>0) { clstr<-lifo[lifoIdx] lifoIdx<-lifoIdx-1 if (dbg) cat(sprintf('popping %d\n',clstr)) if (clstr<0) { if (dbg) cat(sprintf(' -> %d\n',oi)) ordering[-clstr]<-oi oi<-oi+1 } else { for (i in 2:1) { subclstr<-merging[clstr,i] if (dbg) cat(sprintf('pushing %d\n',subclstr)) lifoIdx<-lifoIdx+1 lifo[lifoIdx]<-subclstr } } } if (dbg) printVar(ordering) return(ordering) }
`p1p2.c` <- function (typ,p1,p2) switch (typ, b = p1p2.c.b(p1,p2), l = p1p2.c.l(p1,p2), v = p1p2.c.v(p1,p2), h = p1p2.c.h(p1,p2) )
"dgev" <- function(x, xi = 1, mu = 0, sigma = 1) { tmp <- (1 + (xi * (x - mu))/sigma) (as.numeric(tmp > 0) * (tmp^(-1/xi - 1) * exp( - tmp^(-1/xi))))/ sigma } "dgpd" <- function(x, xi, mu = 0, beta = 1) { (beta^(-1)) * (1 + (xi * (x - mu))/beta)^((-1/xi) - 1) } "pgev" <- function(q, xi = 1, mu = 0, sigma = 1) { exp( - (1 + (xi * (q - mu))/sigma)^(-1 /xi)) } "pgpd" <- function(q, xi, mu = 0, beta = 1) { (1 - (1 + (xi * (q - mu))/beta)^(-1 /xi)) } "qgev" <- function(p, xi = 1, mu = 0, sigma = 1) { mu + (sigma/xi) * (( - logb(p))^( - xi) - 1) } "qgpd" <- function(p, xi, mu = 0, beta = 1) { mu + (beta/xi) * ((1 - p)^( - xi) - 1) } "rgev" <- function(n, xi = 1, mu = 0, sigma = 1) { mu - (sigma * (1 - ( - logb(runif(n)))^( - xi)))/xi } "rgpd" <- function(n, xi, mu = 0, beta = 1) { mu + (beta/xi) * ((1 - runif(n))^( - xi) - 1) }
KdCov = function(x,y, sigma){ n <- nrow(as.matrix(x)) if (length(y)!=n) stop( "x and y must be the same size") x=sqrt(2-2*exp(-as.matrix(dist(as.matrix(x),diag=TRUE, upper=TRUE))/sigma)) y <- as.matrix(dist(as.matrix(y),diag=TRUE, upper=TRUE)) y[which(y!=0)]=1 return(dcov(x,y)) }
parallel.ade <- function(vars, vnames=NULL, data=NULL, group=NULL, ylim=NULL , xlab=NULL, ylab=NULL, main=NULL, alpha = NULL, col=NULL, tcol=NULL, bgcol=NULL, lcol=NULL, scale=FALSE, desc=FALSE, means=TRUE, legendon='top', wall=0){ if(any(par('mfg')!=c(1,1,1,1)) & any(par('mai') < c(1.02, 0.82, 0.82, 0.42))){ maidiff<-rep(0, 4) norm<-c(1.02, 0.82, 0.82, 0.42) maidiff[par('mai')<norm]<- norm[par('mai')<norm] - par('mai')[par('mai')<norm] par(mai=par('mai')+maidiff) } oldpar<-par(no.readonly =TRUE) oldpar<-oldpar[-which(names(oldpar)%in%c('usr', 'plt', 'pin', 'fin', 'fig', 'mfg', 'mfcol', 'mfrow', 'omd', 'omi', 'oma'))] on.exit(par(oldpar)) if(is.list(vars)){ x<- vars[[1]] data<-as.data.frame(x) newvars<-NULL for(i in 1:length(vars)){ eval(parse(text=paste("data$var_",i,"<-vars[[i]]", sep=''))) newvars<-c(newvars, paste("var_",i, sep='')) } data$groupmy<-group vars<-newvars if(!is.null(group)) group<-'groupmy' } for(i in 1:length(vars)){ data<- subset(data, !is.na(eval(parse(text=paste(vars[i], sep=''))))) } if (is.null(vnames)) vnames <- vars if(!is.null(group)) gg<- eval(parse(text=paste("data$",group, sep=''))) if(!is.null(group)) ggf<-eval(parse(text=paste("data$",group, sep=''))) if(!is.null(group)) ggf<-as.factor(ggf) if(!is.null(group)) gg<-as.numeric(gg) if(is.null(tcol) & wall==0) tcol<-1 if(is.null(tcol) & wall!=0) tcol<-rgb(0.1,0.1,0.25) if(is.null(bgcol) & wall==0) bgcol<-1 if(is.null(bgcol) & wall!=0) bgcol<-' if(is.null(alpha)){ alpha<-0.25 if(wall==0) alpha<-1 } M<-NULL for(i in 1:length(vars)){ M<-cbind(M, eval(parse(text=paste("data$",vars[i], sep='')))) } runlines<-function(alcol, mcol=tcol, plot=TRUE){ M<-NULL for(i in 1:length(vars)){ M<-cbind(M, eval(parse(text=paste("data$",vars[i], sep='')))) } rbc2 <-alcol if(scale){ if(is.null(group)) yr<-range(M, na.rm=TRUE) if(!is.null(group)) yr<-range(M[(!is.na(gg)), ], na.rm=TRUE) for(i in 1:length(vars)){ if(is.null(group)) M[ , i]<-(M[, i]/(range(M[,i], na.rm=TRUE)[2]-range(M[,i], na.rm=TRUE)[1]))-(range(M[,i], na.rm=TRUE)[1]/(range(M[,i], na.rm=TRUE)[2]-range(M[,i], na.rm=TRUE)[1])) if(!is.null(group)) M[ , i]<-(M[, i]/(range(M[(!is.na(gg)),i], na.rm=TRUE)[2]-range(M[(!is.na(gg)),i], na.rm=TRUE)[1]))-(range(M[(!is.na(gg)),i], na.rm=TRUE)[1]/(range(M[(!is.na(gg)),i], na.rm=TRUE)[2]-range(M[(!is.na(gg)),i], na.rm=TRUE)[1])) ylim=(ylim/(ylim[2]-ylim[1]))-(ylim[1]/(ylim[2]-ylim[1])) } } d<-dim(M) x<-1:dim(M)[2] if(is.null(group)){ if(is.null(col)) rbc<-rainbow(dim(M)[1], start=0.2, end=0, alpha=alpha) if(!is.null(col)) rbc<-rep(col, round(d[1]/length(col))+1 ) o<-order(as.numeric(M[,1] ), decreasing = desc) M<-M[o,] } if(!is.null(group)){ if(is.null(col)) col <- a.getcol.ade(nlevels(ggf)) if(!is.null(col)){ rbc<- a.alpha.ade(col, alpha) rbc2<-a.alpha.ade(col, 1) } o<-order(as.numeric(gg), decreasing = F) M<-M[o,] gg<-gg[o] } if(!is.null(group)) if(min(gg, na.rm=TRUE)==0) gg<-gg+1 if(plot){ for(i in 1:(dim(M)[2]-1)){ for(j in 1:dim(M)[1]){ if(is.null(group)) segments(i,M[j,i],(i+1),M[j,(i+1)], col=rbc[j]) if(!is.null(group)) segments(i,M[j,i],(i+1),M[j,(i+1)], col=rbc[gg[j]]) } if(means){ if(is.null(group) & is.null(lcol)) segments(i,mean(M[,i], na.rm=TRUE),(i+1),mean(M[,(i+1)], na.rm=TRUE), col=mcol, lwd=2) if(is.null(group) & !is.null(lcol)) segments(i,mean(M[,i], na.rm=TRUE),(i+1),mean(M[,(i+1)], na.rm=TRUE), col=lcol, lwd=2) if(!is.null(group)){ for(k in 1:length(rbc)){ MD<-cbind(M, gg) x<-levels(factor(gg))[k] MD<-as.data.frame(MD) MD<-subset(MD, gg==x ) segments(i,mean(MD[,i], na.rm=TRUE),(i+1),mean(MD[,(i+1)], na.rm=TRUE), col=a.alpha.ade(a.coladd.ade(rbc[k], -75), 1), lwd=3) } } } abline(v=i, col=alcol) } } if(is.null(group)) yrange<-range(M, na.rm=TRUE) if(!is.null(group)) yrange<-range(M[(!is.na(gg)), ], na.rm=TRUE) if(plot) abline(v=(i+1), col=alcol) return(list(rbc2, yrange[1], yrange[2])) } if(wall==0){ par(col.axis=tcol) par(col.lab=tcol) par(col.main=tcol) if(!is.null(ylim)) yrange<-ylim xrange<-c(1, length(vars)) out<-runlines(a.coladd.ade(bgcol, -50), tcol, plot=FALSE) rbc2<-out[[1]] if(is.null(ylim)) yrange<-c(out[[2]], out[[3]]) yrange[2]<-yrange[2]+yrange[2]/10 plot(0, 0 , xlim=xrange, ylim=yrange, axes=FALSE, xlab=xlab, ylab=ylab, main=main, col=rgb(1,1,1,0)) axis(2 , at=pretty(c(yrange[1],yrange[2])) , col.ticks=bgcol) a1<-axis(1, at=1:length(vars), labels=vnames, col.ticks=bgcol) runlines(bgcol) if(!is.null(group)) legend(legendon, legend=levels(ggf), text.col=tcol, box.col=bgcol, fill=rbc2, border=bgcol, yjust=0.425, horiz=TRUE, bg=rgb(1,1,1, 0.99)) box(col=bgcol) } if(wall==1){ par(col.axis=tcol) par(col.lab=tcol) par(col.main=tcol) if(!is.null(ylim)) yrange=ylim xrange<-c(1, length(vars)) out<-runlines(a.coladd.ade(bgcol, -50), tcol, plot=FALSE) rbc2<-out[[1]] if(is.null(ylim)) yrange<-c(out[[2]], out[[3]]) yrange[2]<-yrange[2]+yrange[2]/10 plot(0, 0 , xlim=xrange, ylim=yrange, axes=FALSE, xlab=xlab, ylab=ylab, main=main, col=rgb(1,1,1,0)) polygon( c(par('usr')[c(1,1,2,2)]), par('usr')[c(3,4,4,3)], col=bgcol, border=FALSE) a2<-axis(2 , at=pretty(c(yrange[1],yrange[2])) , col.ticks=bgcol) a1<-axis(1, at=1:length(vars), labels=vnames, col.ticks=bgcol) abline(v=a1, h=a2, lty=1, col=rgb(1,1,1), lwd=1) runlines(rgb(1,1,1), tcol) if(!is.null(group)) legend(legendon, legend=levels(ggf), text.col=tcol, box.col=rgb(1,1,1), fill=rbc2, border=tcol, box.lwd=2, horiz=TRUE, bg=bgcol) box(col=rgb(1,1,1)) } if(wall==2){ par(col.axis=tcol) par(col.lab=tcol) par(col.main=tcol) if(!is.null(ylim)) yrange=ylim xrange<-c(1, length(vars)) out<-runlines(a.coladd.ade(bgcol, -50), tcol, plot=FALSE) rbc2<-out[[1]] if(is.null(ylim)) yrange<-c(out[[2]], out[[3]]) yrange[2]<-yrange[2]+yrange[2]/10 plot(0, 0 , xlim=xrange, ylim=yrange, axes=FALSE, xlab=xlab, ylab=ylab, main=main, col=rgb(1,1,1,0)) a2<-axis(2 , at=pretty(c(yrange[1],yrange[2])) , col.ticks=bgcol) a1<-axis(1, at=1:length(vars), labels=vnames, col.ticks=bgcol) abline(v=a1, h=a2, lty=1, col=bgcol, lwd=1) runlines(bgcol, tcol) if(!is.null(group)) legend(legendon, legend=levels(ggf), text.col=tcol, box.col=a.coladd.ade(bgcol, -75), fill=rbc2, border=a.coladd.ade(bgcol, -75), box.lwd=1, horiz=TRUE, bg=rgb(1,1,1)) box(col=a.coladd.ade(bgcol, -75)) } if(wall==3){ par(col.axis=tcol) par(col.lab=tcol) par(col.main=tcol) if(!is.null(ylim)) yrange=ylim xrange<-c(1, length(vars)) out<-runlines(a.coladd.ade(bgcol, -50), tcol, plot=FALSE) rbc2<-out[[1]] if(is.null(ylim)) yrange<-c(out[[2]], out[[3]]) yrange[2]<-yrange[2]+yrange[2]/10 plot(0, 0 , ylim=yrange, axes=FALSE, xlab=xlab, ylab=ylab, main=main, xlim=xrange, col=rgb(1,1,1,0)) polygon( c(par('usr')[c(1,1,2,2)]), par('usr')[c(3,4,4,3)], col=bgcol, border=FALSE) a1<-axis(1, at=1:length(vars), labels=vnames, col.ticks=bgcol) a2<-axis(2 , at=pretty(c(yrange[1],yrange[2])) , col.ticks=bgcol) abline(v=a1, h=a2, lty=1, col=a.coladd.ade(bgcol, -50), lwd=1) out<-runlines(a.coladd.ade(bgcol, -50), tcol, plot=TRUE) if(!is.null(group)) legend(legendon, legend=levels(ggf), text.col=tcol, fill=rbc2, box.col=a.coladd.ade(bgcol, -75), border=a.coladd.ade(bgcol, -75), box.lwd=1, horiz=TRUE, bg=rgb(1,1,1)) box(col=a.coladd.ade(bgcol, -75)) } if(wall==4){ par(col.axis=tcol) par(col.lab=tcol) par(col.main=rgb(1,1,1)) par(font=2) if(!is.null(ylim)) yrange=ylim xrange<-c(1, length(vars)) out<-runlines(a.coladd.ade(bgcol, -50), tcol, plot=FALSE) rbc2<-out[[1]] if(is.null(ylim)) yrange<-c(out[[2]], out[[3]]) yrange[2]<-yrange[2]+yrange[2]/10 plot(0, 0 , xlim=xrange, ylim=yrange, axes=FALSE, xlab='', ylab='', main='', col=rgb(1,1,1,0)) polygon( c(par('usr')[c(1,1,2,2)]), par('usr')[c(3,4,4,3)], col=bgcol, border=FALSE) a2<-axis(2 , at=pretty(c(yrange[1],yrange[2])) , col.ticks=bgcol) a1<-axis(1, at=1:length(vars), labels=vnames, col.ticks=bgcol) abline(v=a1, h=a2, lty=1, col=rgb(1,1,1), lwd=1) par(xpd=TRUE) polygon(a.glc(side=c(2,2,4,4), line=c(0,0,0,0)), a.glc(side=3, line=c(0, 2.75, 2.75, 0)), col=tcol, border=rgb(1,1,1)) if(!is.null(ylab)) if(ylab!='' & ylab!=' ') polygon( a.glc(side=2, line=c(3.5, 3.5, 2, 2)), a.glc(side=c(1, 3, 3, 1), line=0), col=bgcol, border=rgb(1,1,1)) if(!is.null(xlab)) if(xlab!='' & xlab!=' ') polygon( a.glc(side=c(2, 2, 4, 4), line=0), a.glc(side=1, line=c(4, 2.5, 2.5, 4)), col=bgcol, border=rgb(1,1,1)) text(a.glc(side=0), a.glc(side=3, line=1), labels=main, cex = 1.25, font=2, col=rgb(1,1,1), adj=c(0.5,0)) text(a.glc(side=0), a.glc(side=1, line=3.5), labels=xlab, cex = 1.1, font=2, col=tcol, adj=c(0.5,0)) text(a.glc(side=2, line=2.5), a.glc(side=5), labels=ylab, cex = 1.1, font=2, col=tcol, adj=c(0.5,0), srt=90) par(xpd=FALSE) box(col=rgb(1,1,1)) runlines(rgb(1,1,1), tcol) if(!is.null(group)) legend(legendon, legend=levels(ggf), text.col=rgb(1,1,1), fill=rbc2, box.col=rgb(1,1,1), border=rgb(1,1,1), lty=0,box.lwd=1, pt.cex=2, col=rbc2, horiz=TRUE, bg=tcol, text.width=max(strwidth(levels(ggf),font = 2))) box(col=rgb(1,1,1)) } if(wall==5){ par(col.axis=tcol) par(col.lab=tcol) par(col.main=tcol) par(font=2) newmai<-rep(0, 4) oldmai<-par('mai') if(oldmai[2]<1) newmai[2]<- 1 - oldmai[2] if(oldmai[3]>0.75 & oldmai[3]<=0.82) newmai[3]<- 0.75-oldmai[3] if(oldmai[4]>0.25 & oldmai[4]<=0.42) newmai[4]<- 0.25-oldmai[4] par(mai=(oldmai+newmai)) if(!is.null(ylim)) yrange=ylim xrange<-c(1, length(vars)) out<-runlines(a.coladd.ade(bgcol, -50), tcol, plot=FALSE) rbc2<-out[[1]] if(is.null(ylim)) yrange<-c(out[[2]], out[[3]]) yrange[2]<-yrange[2]+yrange[2]/10 plot(0, 0 , xlim=xrange, ylim=yrange, axes=FALSE, xlab='', ylab='', main='', col=rgb(1,1,1,0)) a2<-axis(2 , at=pretty(c(yrange[1],yrange[2])) , col.ticks=bgcol) a1<-axis(1, at=1:length(vars), labels=vnames, col.ticks=bgcol) abline(v=a1, h=a2, lty=1, col=rgb(1,1,1), lwd=1) par(xpd=TRUE) polygon(a.glc(side=2, line=c(4.25, 4.25, 0, 0)), a.glc(side=3, line=c(0.6, 3, 3, 0.6)), col=bgcol, border=tcol) polygon(a.glc(side=c(2,2,4,4), line=c(0,0,0,0)), a.glc(side=3, line=c(0.6, 3, 3, 0.6)), col=rgb(1,1,1,0), border=tcol) polygon(a.glc(side=4, line=c(0, 0 ,0.6, 0.6)), a.glc(side=3, line=c(0.6, 3, 3, 0.6)), col=bgcol, border=tcol) polygon(a.glc(side=2, line=c(4.25, 4.25 ,3.65, 3.65)), a.glc(side=c(1,3,3,1), line=c(2.6, 0.6, 0.6, 2.6)), col=bgcol, border=tcol) polygon(a.glc(side=4, line=c(0, 0 ,0.6, 0.6)), a.glc(side=c(1, 3, 3, 1), line=0), col=bgcol, border=tcol) polygon(a.glc(side=2, line=c(4.25, 4.25, 0, 0)), a.glc(side=1, line=c(2.6, 4.5, 4.5, 2.6)), col=bgcol, border=tcol) polygon(a.glc(side=c(2, 2, 4, 4), line=0), a.glc(side=1, line=c(2.6, 4.5, 4.5, 2.6)), col=rgb(1,1,1,0), border=tcol) polygon(a.glc(side=4, line=c(0, 0, 0.6, 0.6)), a.glc(side=1, line=c(2.6, 4.5, 4.5, 2.6)), col=bgcol, border=tcol) text(a.glc(side=0), a.glc(side=3, line=1.5), labels=main, cex = 1.25, font=2, col=tcol, adj=c(0.5,0)) text(a.glc(side=0), a.glc(side=1, line=3.75), labels=xlab, cex = 1.1, font=2, col=tcol, adj=c(0.5,0)) text(a.glc(side=2, line=2.5), a.glc(side=5), labels=ylab, cex = 1.1, font=2, col=tcol, adj=c(0.5,0), srt=90) par(xpd=FALSE) box(col=rgb(1,1,1)) runlines(tcol, tcol) if(!is.null(group)) legend(legendon, legend=levels(ggf), text.col=tcol, fill=rbc2, box.col=tcol, border=tcol, lty=0,box.lwd=1, pt.cex=2, col=rbc2, horiz=TRUE, bg=rgb(1,1,1), text.width=max(strwidth(levels(ggf),font = 2))) box(col=tcol) } if(wall==6){ par(col.axis=tcol) par(col.lab=tcol) par(col.main=tcol) if(!is.null(ylim)) yrange=ylim xrange<-c(1, length(vars)) out<-runlines(a.coladd.ade(bgcol, -50), tcol, plot=FALSE) rbc2<-out[[1]] if(is.null(ylim)) yrange<-c(out[[2]], out[[3]]) yrange[2]<-yrange[2]+yrange[2]/10 plot(0, 0 , xlim=xrange, ylim=yrange, axes=FALSE, xlab=xlab, ylab=ylab, main=main, col=rgb(1,1,1,0)) polygon( c(par('usr')[c(1,1,2,2)]), par('usr')[c(3,4,4,3)], col=bgcol, border=NA) a2<-axis(2 , at=pretty(c(yrange[1],yrange[2])) , col.ticks=a.coladd.ade(bgcol, -35), lwd.ticks=3) a2<-axis(2 , at=pretty(c(yrange[1],yrange[2])) , col.ticks=rgb(1,1,1), lwd.ticks=1) a1<-axis(1, at=1:length(vars), labels=vnames, col.ticks=a.coladd.ade(bgcol, -35), lwd.ticks=3) a1<-axis(1, at=1:length(vars), labels=vnames, col.ticks=rgb(1,1,1), lwd.ticks=1) abline(v=a1, h=a2, lty=1, col=a.coladd.ade(bgcol, -35), lwd=3) abline(v=a1, h=a2, lty=1, col=rgb(1,1,1), lwd=1) runlines(rgb(1,1,1), tcol) if(!is.null(group)) legend(legendon, legend=levels(ggf), text.col=tcol, box.col=rgb(1,1,1), fill=rbc2, border=tcol, box.lwd=3, horiz=TRUE, bg=bgcol) if(!is.null(group)) legend(legendon, legend=levels(ggf), text.col=tcol, box.col=a.coladd.ade(bgcol, -35), fill=rbc2, border=tcol, box.lwd=1, horiz=TRUE, bg=rgb(0,0,0,0)) box(lwd=3, col=rgb(1,1,1)) box(lwd=1, col=a.coladd.ade(bgcol, -35)) } }
raw2temp <-function(raw,E=1,OD=1,RTemp=20,ATemp=RTemp,IRWTemp=RTemp,IRT=1,RH=50, PR1=21106.77,PB=1501,PF=1,PO=-7340,PR2=0.012545258, ATA1=0.006569, ATA2=0.01262, ATB1=-0.002276, ATB2=-0.00667, ATX=1.9) { emiss.wind<-1-IRT refl.wind<-0 h2o<-(RH/100)*exp(1.5587+0.06939*(ATemp)-0.00027816*(ATemp)^2+0.00000068455*(ATemp)^3) tau1<-ATX*exp(-sqrt(OD/2)*(ATA1+ATB1*sqrt(h2o)))+(1-ATX)*exp(-sqrt(OD/2)*(ATA2+ATB2*sqrt(h2o))) tau2<-ATX*exp(-sqrt(OD/2)*(ATA1+ATB1*sqrt(h2o)))+(1-ATX)*exp(-sqrt(OD/2)*(ATA2+ATB2*sqrt(h2o))) raw.refl1<-PR1/(PR2*(exp(PB/(RTemp+273.15))-PF))-PO raw.refl1.attn<-(1-E)/E*raw.refl1 raw.atm1<-PR1/(PR2*(exp(PB/(ATemp+273.15))-PF))-PO raw.atm1.attn<-(1-tau1)/E/tau1*raw.atm1 raw.wind<-PR1/(PR2*(exp(PB/(IRWTemp+273.15))-PF))-PO raw.wind.attn<-emiss.wind/E/tau1/IRT*raw.wind raw.refl2<-PR1/(PR2*(exp(PB/(RTemp+273.15))-PF))-PO raw.refl2.attn<-refl.wind/E/tau1/IRT*raw.refl2 raw.atm2<-PR1/(PR2*(exp(PB/(ATemp+273.15))-PF))-PO raw.atm2.attn<-(1-tau2)/E/tau1/IRT/tau2*raw.atm2 raw.obj<-(raw/E/tau1/IRT/tau2-raw.atm1.attn-raw.atm2.attn-raw.wind.attn-raw.refl1.attn-raw.refl2.attn) temp.C<-PB/log(PR1/(PR2*(raw.obj+PO))+PF)-273.15 temp.C }
QuantoAmerPutLSM <- function(Spot=1, sigma=0.2, n=1000, m=365, Strike=1.1, r=0.06, dr=0.0, mT=1, Spot2=1, sigma2=0.2, r2=0.0, dr2=0.0, rho=0){ covmat <- matrix(c(1,rho,rho,1), ncol=2) GBM1<-matrix(NA, nrow=n, ncol=m) GBM2<-matrix(NA, nrow=n, ncol=m) GBMD<-matrix(NA, nrow=m, ncol=2) for(i in 1:n) { GBMD<-rmvnorm(m, mean=c(0,0), sigma=covmat) GBM1[i,]<-Spot*exp(cumsum(((r-dr)*(mT/m)-0.5*sigma*sigma*(mT/m))+(sigma*(sqrt(mT/m))*GBMD[,1]))) GBM2[i,]<-Spot2*exp(cumsum(((r2-dr2)*(mT/m)-0.5*sigma2*sigma2*(mT/m))+(sigma2*(sqrt(mT/m))*GBMD[,2]))) } X<-ifelse(GBM1<Strike,GBM1,NA) CFL1<-matrix(pmax(0,Strike-GBM1), nrow=n, ncol=m) CFL<-CFL1*GBM2 Xsh<-X[,-m] X2sh<-Xsh*Xsh G<-ifelse(GBM1<Strike,GBM2,NA) Gsh<-G[,-m] G2sh<-Gsh*Gsh H<-Xsh*Gsh Y1<-CFL*exp(-1*r*(mT/m)) Y2<-cbind((matrix(NA, nrow=n, ncol=m-1)), Y1[,m]) CV<-matrix(NA, nrow=n, ncol=m-1) try(for(i in (m-1):1) { reg1<-lm(Y2[,i+1]~Xsh[,i]+X2sh[,i]+Gsh[,i]+G2sh[,i]+H[,i]) mat1<-cbind(matrix(reg1$coefficients)[1,1], matrix(reg1$coefficients)[2,1], matrix(reg1$coefficients)[3,1], matrix(reg1$coefficients)[4,1], matrix(reg1$coefficients)[5,1], matrix(reg1$coefficients)[6,1]) mat2<-(ifelse(is.na(mat1),0,mat1)) CV[,i]<-(mat2[1,1])+((mat2[1,2])*Xsh[,i])+((mat2[1,3])*X2sh[,i])+((mat2[1,4])*Gsh[,i])+((mat2[1,5])*G2sh[,i])+((mat2[1,6])*H[,i]) CV[,i]<-(ifelse(is.na(CV[,i]),0,CV[,i])) Y2[,i]<-ifelse(CFL[,i]>CV[,i], Y1[,i], Y2[,i+1]*exp(-1*r*(mT/m))) } , silent = TRUE) CV<-ifelse(is.na(CV),0,CV) CVp<-cbind(CV, (matrix(0, nrow=n, ncol=1))) POF<-ifelse(CVp>CFL,0,CFL) FPOF<-firstValueRow(POF) dFPOF<-matrix(NA, nrow=n, ncol=m) for(i in 1:m) { dFPOF[,i]<-FPOF[,i]*exp(-1*mT/m*r*i) } PRICE<-mean(rowSums(dFPOF)) res<- list(price=(PRICE), Spot, Strike, sigma, n, m, r, dr, mT, Spot2, sigma2, r2, dr2, rho) class(res)<-"QuantoAmerPut" return(res) }
source("ESEUR_config.r") pal_col=rainbow(2) fit_contract=function(df, col_str) { fp_mod=nls(l_Management ~ SSlogis(Project_size, a, b, c), data=df) pred=predict(fp_mod, newdata=data.frame(Project_size=x_range)) lines(x_range/1e3, exp(pred), col=col_str) } ah=read.csv(paste0(ESEUR_dir, "projects/ahonen2015.csv.xz"), as.is=TRUE) ah$l_Management=log(ah$Management) fp=subset(ah, Contract == "FP") tm=subset(ah, Contract == "TM") plot(1, type="n", log="xy", xlim=range(ah$Project_size)/1e3, ylim=range(ah$Management), xlab="Effort (thousand hours)", ylab="Management (percentage)\n") points(fp$Project_size/1e3, fp$Management, col=pal_col[1]) points(tm$Project_size/1e3, tm$Management, col=pal_col[2]) legend(x="bottomright", legend=c("Fixed-price", "Time-and-materials"), bty="n", fill=pal_col, cex=1.2) x_range=exp(seq(0, log(max(ah$Project_size)), by=0.1)) fit_contract(fp, pal_col[1]) fit_contract(tm, pal_col[2])
miniusloglik.ce.xt.logis <- function(dat, pars) { mu=pars[1] npars=length(pars) sigma=exp(pars[npars]) beta.vec=pars[2:(npars-1)] failure.dat=dat$failure.dat aux.inf=dat$aux.inf xt.obj=dat$xt.obj wts.mat=aux.inf$wts.mat npts.vec=aux.inf$npts.vec x.val=xt.obj$x.val npts=xt.obj$npts n=xt.obj$n para.vec=kronecker(beta.vec,rep(1,npts)) para.mat=kronecker(t(para.vec),rep(1,n)) beta.xt.mat=para.mat*x.val tmp.mat=kronecker(rep(1,npars-2),diag(npts)) sum.beta.xt.mat=beta.xt.mat%*%tmp.mat sum.beta.xt.mat=exp(sum.beta.xt.mat) int.g.beta.xt=rowSums(wts.mat*sum.beta.xt.mat) g.beta.xt=as.vector(sum.beta.xt.mat)[1:n+n*(npts.vec-1)] delta=failure.dat[,"delta"] zz=(log(int.g.beta.xt)-mu)/sigma ff=dlogis(zz)/(int.g.beta.xt*sigma) FF=plogis(zz) ll=delta*log(g.beta.xt*ff)+(1-delta)*log(1-FF) res=(-1)*sum(ll) return(res) }
gen_ar1blocks = function(phi, sigma2, n_total, n_block, scale = 10, title = NULL, seed = 135, ...){ set.seed(seed) ar = NULL for (i in (1:(n_total / n_block))) { xt = gen_ar1(N = n_block * scale, phi = phi, sigma2 = sigma2) x0 = xt[(n_block*(scale-1))] xt = xt[(n_block*(scale-1)+1): (n_block*scale)] ar = c(ar, xt) } if (is.null(title)){ title = "Simulated AR(1) Blocks Process" } ar = gts(ar, data_name = title) return(ar) } gen_nswn = function(n_total, title = NULL, seed = 135, ...){ set.seed(seed) wn = NULL for (i in (1:n_total)){ y = rnorm(n = 1, mean = 0, sd = sqrt(i)) wn = c(wn, y) } if (is.null(title)){ title = "Simulated Non-Stationary White Noise Process" } wn = gts(wn, data_name = title) return(wn) } gen_bi = function(sigma2, n_total, n_block, title = NULL, seed = 135, ...){ set.seed(seed) bi = NULL for (i in (1:(n_total / n_block))){ x = rnorm(n = 1, mean = 0, sd = sqrt(sigma2)) bi = c(bi, rep(x, n_block)) } if (is.null(title)){ title = "Simulated Bias-Instability Process" } bi = gts(bi, data_name = title) return(bi) }
VARB.Boot <- function(x,p,nb=200,type="const") { n <- nrow(x); k <- ncol(x) var1 <- VAR.est(x,p,type) b <- var1$coef e <- sqrt( (n-p) / ( (n-p)-ncol(b)))*var1$resid var2 <- VARB.est(x,p,type) bb <- var2$coef eb <- sqrt( (n-p) / ( (n-p)-ncol(b)))*var2$resid mat <- matrix(0,nrow=k,ncol=ncol(b)) matb <- matrix(0,nrow=k,ncol=ncol(b)) for(i in 1:nb) { es <- resamp(e) xs <- VAR.ys(x,b,p,es,type) bs <- VAR.est(xs,p,type)$coef mat <- mat + bs/nb es <- resamp(eb) xs <- VARB.ys(x,bb,p,es,type) bs <- VARB.est(xs,p,type)$coef matb <- matb + bs/nb } bias <- mat - b bs <- VAR.adjust(b,bias,p,type); colnames(bs) <- VAR.names(x,p,type) es <- VAR.resid(x,bs,var1$zmat,p); colnames(es) <- rownames(b) biasb <- matb - bb bsb <- VAR.adjust(bb,biasb,p,type); colnames(bs) <- VAR.names(x,p,type) esb <- VAR.resid(x,bs,var1$zmat,p); colnames(es) <- rownames(b) sigu <- t(es) %*% es / ( (n-p) -k*p -1) return(list(coef=bs,coefb=bsb,resid=es,residb=esb,sigu=sigu,Bias=bias)) }
"irf.svarest" <- function(x, impulse=NULL, response=NULL, n.ahead=10, ortho=TRUE, cumulative=FALSE, boot=TRUE, ci=0.95, runs=100, seed=NULL, ...){ if(!(class(x)=="svarest")){ stop("\nPlease provide an object of class 'svarest', generated by 'SVAR()'.\n") } y.names <- colnames(x$var$y) if(is.null(impulse)){ impulse <- y.names } else { impulse <- as.vector(as.character(impulse)) if(any(!(impulse %in% y.names))) { stop("\nPlease provide variables names in impulse\nthat are in the set of endogenous variables.\n") } impulse <- subset(y.names, subset = y.names %in% impulse) } if(is.null(response)){ response <- y.names } else { response <- as.vector(as.character(response)) if(any(!(response %in% y.names))){ stop("\nPlease provide variables names in response\nthat are in the set of endogenous variables.\n") } response <- subset(y.names, subset = y.names %in% response) } irs <- .irf(x = x, impulse = impulse, response = response, y.names = y.names, n.ahead = n.ahead, ortho = ortho, cumulative = cumulative) Lower <- NULL Upper <- NULL if(boot){ ci <- as.numeric(ci) if((ci <= 0)|(ci >= 1)){ stop("\nPlease provide a number between 0 and 1 for the confidence interval.\n") } ci <- 1 - ci BOOT <- .boot(x = x, n.ahead = n.ahead, runs = runs, ortho = ortho, cumulative = cumulative, impulse = impulse, response = response, ci = ci, seed = seed, y.names = y.names) Lower <- BOOT$Lower Upper <- BOOT$Upper } result <- list(irf=irs, Lower=Lower, Upper=Upper, response=response, impulse=impulse, ortho=ortho, cumulative=cumulative, runs=runs, ci=ci, boot=boot, model = class(x)) class(result) <- "varirf" return(result) }
setGeneric("otu_table", function(object, taxa_are_rows, errorIfNULL=TRUE){ standardGeneric("otu_table") }) setMethod("otu_table", "phyloseq", function(object, errorIfNULL=TRUE){ access(object, "otu_table", errorIfNULL) }) setMethod("otu_table", "otu_table", function(object, errorIfNULL=TRUE){ return(object) }) setMethod("otu_table", "matrix", function(object, taxa_are_rows){ otutab <- new("otu_table", object, taxa_are_rows=taxa_are_rows) if(taxa_are_rows){ if(is.null(rownames(otutab))){ rownames(otutab) <- paste("sp", 1:nrow(otutab), sep="") } if(is.null(colnames(otutab))){ colnames(otutab) <- paste("sa", 1:ncol(otutab), sep="") } } else { if(is.null(rownames(otutab))){ rownames(otutab) <- paste("sa",1:nrow(otutab),sep="") } if(is.null(colnames(otutab))){ colnames(otutab) <- paste("sp",1:ncol(otutab),sep="") } } return(otutab) }) setMethod("otu_table", "data.frame", function(object, taxa_are_rows){ otu_table(as(object, "matrix"), taxa_are_rows) }) setMethod("otu_table", "ANY", function(object, errorIfNULL=TRUE){ access(object, "otu_table", errorIfNULL) }) taxa_sums <- function(x){ x <- otu_table(x) if( taxa_are_rows(x) ){ rowSums(x) } else { colSums(x) } } sample_sums <- function(x){ x <- otu_table(x) if( taxa_are_rows(x) ){ colSums(x) } else { rowSums(x) } }
test.interactivePlot <- function() { testPlot = function(x, which = "all", ...) { plot.1 <<- function(x, ...) plot(x, ...) plot.2 <<- function(x, ...) acf(x, ...) plot.3 <<- function(x, ...) hist(x, ...) plot.4 <<- function(x, ...) qqnorm(x, ...) interactivePlot(x, choices = c("Series Plot", "ACF", "Histogram", "QQ Plot"), plotFUN = c("plot.1", "plot.2", "plot.3", "plot.4"), which = which, ...) invisible() } par(mfrow = c(2, 2), cex = 0.7) testPlot(rnorm(500)) par(mfrow = c(2, 1), cex = 0.7) testPlot(rnorm(500), which = c(1, 2)) return() }
skip_if_not_installed("cli") cli::test_that_cli(configs = c("plain", "ansi"), "can style strings with cli", { expect_snapshot({ mark_emph("foo") mark_strong("foo") mark_code("foo") mark_q("foo") mark_pkg("foo") mark_fn("foo") mark_arg("foo") mark_kbd("foo") mark_key("foo") mark_file("foo") mark_path("foo") mark_email("foo") mark_url("foo") mark_var("foo") mark_envvar("foo") mark_field("foo") mark_cls("foo") mark_cls(c("foo", "bar")) }) }) cli::test_that_cli(configs = c("plain", "ansi"), "can format strings with cli", { expect_snapshot({ format_emph("foo") format_strong("foo") format_code("foo") format_q("foo") format_pkg("foo") format_fn("foo") format_arg("foo") format_kbd("foo") format_key("foo") format_file("foo") format_path("foo") format_email("foo") format_url("foo") format_var("foo") format_envvar("foo") format_field("foo") format_cls("foo") format_cls(c("foo", "bar")) }) }) cli::test_that_cli(configs = c("plain", "ansi"), "styled strings may contain `{` syntax", { expect_snapshot({ mark_emph("{foo {}") format_message(mark_emph("{foo {}")) }) }) cli::test_that_cli(configs = c("plain", "ansi"), "can apply ANSI styles with cli", { expect_snapshot({ col_black("foo") col_blue("foo") col_cyan("foo") col_green("foo") col_magenta("foo") col_red("foo") col_white("foo") col_yellow("foo") col_grey("foo") col_silver("foo") col_none("foo") bg_black("foo") bg_blue("foo") bg_cyan("foo") bg_green("foo") bg_magenta("foo") bg_red("foo") bg_white("foo") bg_yellow("foo") bg_none("foo") style_dim("foo") style_blurred("foo") style_bold("foo") style_hidden("foo") style_inverse("foo") style_italic("foo") style_strikethrough("foo") style_underline("foo") style_no_dim("foo") style_no_blurred("foo") style_no_bold("foo") style_no_hidden("foo") style_no_inverse("foo") style_no_italic("foo") style_no_strikethrough("foo") style_no_underline("foo") style_reset("foo") style_no_colour("foo") style_no_bg_colour("foo") }) }) cli::test_that_cli("can create symbols with cli", { expect_snapshot({ symbol_info() symbol_cross() symbol_tick() symbol_bullet() symbol_arrow() symbol_alert() }) }) cli::test_that_cli("can create ANSI symbols with cli", { expect_snapshot({ ansi_info() ansi_cross() ansi_tick() ansi_bullet() ansi_arrow() ansi_alert() }) }) cli::test_that_cli("can format messages", { expect_snapshot({ format_error(c("Header", "i" = "Bullet.")) format_warning(c("Header", "i" = "Bullet.")) format_message(c("Header", "i" = "Bullet.")) }) }) cli::test_that_cli("formatters restore strings", { expect_true(is_bare_character(format_error("foo"))) expect_true(is_bare_character(format_warning("foo"))) expect_true(is_bare_character(format_message("foo"))) }) cli::test_that_cli(configs = c("plain", "ansi"), "cli_escape() conditionally escapes `{`", { expect_snapshot({ format_error(cli_escape("{")) }) })
LL_CRE = function(par,y,z,x,w,group,rule,verbose=1){ if(length(par) != ncol(x)+ncol(w)+3 && length(par) != ncol(x)+ncol(w)+2) stop("Number of parameters incorrect") alpha = par[1:ncol(w)] beta = par[ncol(w)+1:ncol(x)] sigma = par["sigma"] delta = par["delta"] rho = ifelse("rho" %in% names(par), par["rho"], 0) Omega = rule$Omega v = rule$v Weight = rule$Weight r = rule$r N = length(group)-1 obs = length(y) wa = as.vector(w %*% alpha) xb = as.vector(x %*% beta) d = 2*z - 1 Li = rep(0, N) for(h in 1:length(r)){ lamh = exp(xb + sqrt(2)*sigma*r[h]) ix = (z==1) Pz = rep(1, obs) Pz[ix] = dpois(y[ix], lamh[ix]) Pz_prod = as.vector(groupProd(Pz, group)) sumk = rep(0, N) for(k in 1:length(v)){ q = wa + sqrt(2)*delta*rho*r[h] + sqrt(2*(1-rho^2))*delta*v[k] Phi = pnorm(d*q) Phi_prod = as.vector(groupProd(Phi, group)) sumk = sumk + Omega[k]*Phi_prod } Li = Li + Weight[h] * Pz_prod * sumk } Li = pmax(Li, 1e-100) LL = sum(log(Li/pi)) if(verbose>=1){ writeLines(paste("==== Iteration ", tmp.env$iter, ": LL=",round(LL,digits=5)," =====", sep="")) print(round(par,digits=3)) } tmp.env$iter = tmp.env$iter + 1 if(is.na(LL) || !is.finite(LL)){ if(verbose>=2) writeLines("NA or infinite likelihood, will try others") LL = -1e300 } if(tmp.env$iter==1) tmp.env$initLL = LL return (LL) } Gradient_CRE = function(par,y,z,x,w,group,rule,variance=F,verbose=1){ if(length(par) != ncol(x)+ncol(w)+3 && length(par) != ncol(x)+ncol(w)+2) stop("Number of parameters incorrect") alpha = par[1:ncol(w)] beta = par[ncol(w)+1:ncol(x)] sigma = par["sigma"] delta = par["delta"] rho = ifelse("rho" %in% names(par), par["rho"], 0) N = length(group)-1 obs = length(y) Omega = rule$Omega v = rule$v Weight = rule$Weight r = rule$r wa = as.vector(w %*% alpha) xb = as.vector(x %*% beta) d = 2*z - 1 w_ext = cbind(w,delta=0,rho=0) x_ext = cbind(x,sigma=0) colnames(w_ext) = c(paste0("w",1:ncol(w)),"delta","rho") colnames(x_ext) = c(paste0("x",1:ncol(x)),"sigma") Li = rep(0, N) sumH_alp = matrix(0, N, ncol(w_ext)) sumH_beta = matrix(0, N, ncol(x_ext)) colnames(sumH_alp) = colnames(w_ext) colnames(sumH_beta) = colnames(x_ext) a1 = sqrt(2)*rho a2 = sqrt(2*(1-rho^2)) a3 = sqrt(2)*delta a4 = sqrt(2/(1-rho^2))*rho*delta b1 = sqrt(2)*delta*rho b2 = sqrt(2*(1-rho^2))*delta for(h in 1:length(r)){ lamh = exp(xb + sqrt(2)*sigma*r[h]) ix = (z==1) Pz = rep(1, obs) Pz[ix] = dpois(y[ix], lamh[ix]) Pz_prod = as.vector(groupProd(Pz, group)) zyl = rep(0, obs) zyl[ix] = y[ix] - lamh[ix] sumK_beta = rep(0, N) sumT_beta = matVecProdSum(x_ext, sqrt(2)*r[h], zyl, group) sumK_alp = matrix(0, N, ncol(w_ext)) for(k in 1:length(v)){ dq = d * (b1*r[h] + b2*v[k] + wa) phi = dnorm(dq) Phi = pnorm(dq) Phi_prod = as.vector(groupProd(Phi, group)) sumK_beta = sumK_beta + Omega[k]*Phi_prod sumT_alp = matVecProdSum(w_ext,c(a1*r[h] + a2*v[k], a3*r[h] - a4*v[k]), d*phi/Phi, group) sumK_alp = sumK_alp + matVecProd(sumT_alp, Omega[k]*Phi_prod) } Li = Li + Weight[h] * Pz_prod * sumK_beta sumH_alp = sumH_alp + matVecProd(sumK_alp, Weight[h] * Pz_prod) sumH_beta = sumH_beta + matVecProd(sumT_beta, Weight[h]*Pz_prod*sumK_beta) } Li = pmax(Li, 1e-100) dLogLi = matVecProd(cbind(sumH_alp, sumH_beta), 1/Li) colnames(dLogLi) = c(colnames(sumH_alp), colnames(sumH_beta)) dLogLi = dLogLi[, c(paste0("w",1:ncol(w)),paste0("x",1:ncol(x)),names(par[(ncol(x)+ncol(w)+1):length(par)]))] colnames(dLogLi) = names(par) gradient = colSums(dLogLi) if(variance){ if(verbose>=1){ writeLines("----Converged, the gradient at optimum:") print(round(gradient,digits=3)) } LL = sum(log(Li/pi)) var = solve(crossprod(dLogLi)) return (list(LL=LL, g=gradient, var=var, I=crossprod(dLogLi))) } if(verbose>=2){ writeLines("----Gradient:") print(round(gradient,digits=3)) } if(any(is.na(gradient) | !is.finite(gradient))){ if(verbose>=2) writeLines("NA or infinite gradient, reset to all -1") gradient = rep(-1, length(gradient)) } return (gradient) } Partial_CRE = function(res,w,xnames,rule,intercept=F){ wnames = colnames(w) par = res$estimates[, 1] alpha = par[1:length(wnames)] beta = par[length(wnames)+1:length(xnames)] sigma = par["sigma"] delta = par["delta"] rho = ifelse("rho" %in% names(par), par["rho"], 0) com = xnames[xnames %in% wnames & xnames!="(Intercept)"] if(intercept){ xunq = c("(Intercept)", xnames[!xnames %in% wnames]) wunq = c("(Intercept)", wnames[!wnames %in% xnames]) } else { xunq = xnames[!xnames %in% wnames] wunq = wnames[!wnames %in% xnames] } Omega = rule$Omega v = rule$v wa = as.vector(w %*% alpha) w_ext = cbind(w,delta=0,sigma=0,rho=0) obs = nrow(w) A = rep(0, obs) B = rep(0, obs) dA = matrix(0, obs, ncol(w_ext)) dB = matrix(0, obs, ncol(w_ext)) for(h in 1:length(v)){ q = sqrt(2)*delta*v[h] + rho*sigma*delta + wa phi = dnorm(q) Phi = pnorm(q) A = A + Omega[h] * phi B = B + Omega[h] * Phi ext = c(sqrt(2)*v[h]+rho*sigma, rho*delta, sigma*delta) phi_dq = matVecProdSum(w_ext, ext, Omega[h]*phi, numeric(0)) dA = dA - matVecProd(phi_dq, q) dB = dB + phi_dq } ratio = A/B Gw = mean(ratio) * alpha Gx = beta G = Gw[com]+Gx[com] if(length(wunq)>0) G = c(G, Gw[wunq]) if(length(xunq)>0) G = c(G, Gx[xunq]) names(G) = c(com, wunq, xunq) Jw_1 = mean(ratio) * cbind(diag(length(alpha)), matrix(0,length(alpha),3)) nmr = dA - matVecProd(dB, A/B) frac = matVecProd(nmr, 1/B) Jw_2 = outer(alpha, colMeans(frac)) Jw = Jw_1 + Jw_2 Jw = cbind(Jw[, 1:(ncol(Jw)-3)], matrix(0,length(alpha),length(beta)), Jw[, tail(1:ncol(Jw), 3)]) rownames(Jw) = wnames Jx = cbind(matrix(0,length(beta),length(alpha)), diag(length(beta)), matrix(0,length(beta),3)) rownames(Jx) = xnames J = Jx[com, ] + Jw[com, ] if(length(wunq)>0) J = rbind(J, Jw[wunq,]) if(length(xunq)>0) J = rbind(J, Jx[xunq,]) rownames(J) = c(com, wunq, xunq) colnames(J) = c(wnames,xnames,tail(colnames(w_ext), 3)) J = cbind(J[,1:(ncol(J)-3)], J[, tail(names(par), 3)]) se = sqrt(diag(J %*% res$var %*% t(J))) z = G/se p = 1 - pchisq(z^2, 1) pe = cbind(estimates=G,se=se,z=z,p=p) return (pe) } CRE = function(sel_form, out_form, id, data=NULL, par=NULL, par_files=NULL, delta=1, max_delta=3, sigma=1, max_sigma=3, rho=0, lower=c(rho=-1), upper=c(rho=1), method='L-BFGS-B',H=c(10,10),psnH=20,prbH=20,accu=1e4,reltol=1e-8,verbose=0,tol_gtHg=Inf){ ord = order(id) data = data[ord,] id = id[ord] group = c(0,cumsum(table(as.integer(factor(id))))) rule1 = gauss.quad(H[1], "hermite") rule2 = gauss.quad(H[2], "hermite") rule = list(Weight=rule1$weights, r=rule1$nodes, Omega=rule2$weights, v=rule2$nodes) mf = model.frame(sel_form, data=data, na.action=NULL, drop.unused.levels=T) z = model.response(mf, "numeric") w = model.matrix(attr(mf, "terms"), data=mf) mf2 = model.frame(out_form, data=data, na.action=NULL, drop.unused.levels=T) y = model.response(mf2, "numeric") x = model.matrix(attr(mf2, "terms"), data=mf2) if(length(id)!=nrow(w) || length(id)!=nrow(x)) stop("Error: id and w or x length don't match, potentially due to removal of data points with missing values!") if(is.null(par)){ if(length(par_files)==2){ writeLines("========Loading initial parameters from estimated models=======") load(par_files$sel, .GlobalEnv) sel_est = res$estimates[,1] load(par_files$out, .GlobalEnv) out_est = res$estimates[,1] par = c(sel_est[-length(sel_est)], out_est, sel_est[length(sel_est)], rho=rho) } else { writeLines("========Initializing outcome equation parameters===========") psn_re = PoissonRE(out_form, id=id[!is.na(y)], data=data[!is.na(y),], sigma=sigma, max_sigma=max_sigma, H=psnH, method='BFGS',reltol=reltol,verbose=verbose-1) writeLines("========Initializing selection equation parameters=========") probit = ProbitRE(sel_form, id=id, data=data, delta=delta, max_delta=max_delta, method='BFGS',H=prbH,reltol=reltol,verbose=verbose-1) sel_est = probit$estimates[,1] out_est = psn_re$estimates[,1] par = c(sel_est[-length(sel_est)], out_est, sel_est[length(sel_est)], rho=rho) } } tmp.env <<- new.env() tmp.env$iter = 1 tmp.env$initLL = -Inf tmp.env$begin = Sys.time() if(method=="L-BFGS-B"){ lb = rep(-Inf, length(par)) names(lb) = names(par) ub = rep(Inf, length(par)) names(ub) = names(par) lb[match(names(lower), names(lb))] = lower ub[match(names(upper), names(ub))] = upper if(verbose>=2){ writeLines("Lower and upper bounds, and initial values:") print(lb) print(ub) print(par) } res = optim(par=par, fn=LL_CRE, gr=Gradient_CRE, method="L-BFGS-B", control=list(factr=accu,fnscale=-1), lower=lb, upper=ub, y=y, z=z, x=x, w=w, group=group,rule=rule,verbose=verbose) } else { res = optim(par=par, fn=LL_CRE, gr=Gradient_CRE, method="BFGS", control=list(reltol=reltol,fnscale=-1), y=y, z=z, x=x, w=w, group=group,rule=rule,verbose=verbose) } gvar = Gradient_CRE(res$par,y,z,x,w,group,rule,variance=T,verbose=verbose-1) res$LL = gvar$LL res$AIC = -2*res$LL + 2 * length(res$par) res$BIC = -2*res$LL + log(length(z)) * length(res$par) res$var = gvar$var res$g = gvar$g res$gtHg = matrix(res$g, nrow=1) %*% res$var %*% matrix(res$g, ncol=1) if(any(is.na(res$g) | !is.finite(res$g)) | res$gtHg>tol_gtHg){ par['rho'] = runif(1,-1,1) writeLines(paste("====Failed to converge gtHg =", res$gtHg, ", trying rho =", par['rho'], ", current gradient shown below====")) print(res$g) return (CRE(sel_form, out_form, id, data=data, par=par, par_files=par_files, delta=delta, max_delta=max_delta, sigma=sigma, max_sigma=max_sigma, lower=lower, upper=upper, method=method,H=H,psnH=psnH,prbH=prbH,accu=accu,reltol=reltol,verbose=verbose,tol_gtHg=tol_gtHg)) } res$se = sqrt(diag(res$var)) res$z = res$par/res$se res$p = 1 - pchisq(res$z^2, 1) if('delta' %in% names(res$par) && res$par['delta']<0){ res$par['delta'] = -res$par['delta'] if('rho' %in% names(res$par)) res$par['rho'] = -res$par['rho'] } if('sigma' %in% names(res$par) && res$par['sigma']<0){ res$par['sigma'] = -res$par['sigma'] if('rho' %in% names(res$par)) res$par['rho'] = -res$par['rho'] } res$estimates = cbind(estimates=res$par,se=res$se,z=res$z,p=res$p) res$partial = Partial_CRE(res,w,colnames(x),rule) wavg = t(colMeans(w)) res$partialAvgObs = Partial_CRE(res,wavg,colnames(x),rule) res$iter = tmp.env$iter res$input = list(sel_form=sel_form, out_form=out_form, par=par, par_files=par_files, delta=delta, max_delta=max_delta, sigma=sigma, max_sigma=max_sigma, rho=rho, lower=lower, upper=upper, method=method,H=H,psnH=psnH,prbH=prbH,accu=accu,reltol=reltol,verbose=verbose,tol_gtHg=tol_gtHg) writeLines(paste0("\n *** Estimation of CRE model finished, LL=",res$LL," ***")) print(res$estimates) print(Sys.time()-tmp.env$begin) res$scgrad=tryCatch(solve(chol(gvar$I),gvar$g), error=function(e)e) if('numeric' %in% class(res$scgrad)[1]) { max_grad = round(max(abs(res$scgrad)), digits=3) max_grad_var = names(which.max(abs(res$scgrad))) if(verbose>=1) writeLines(paste0('Max absolute scaled gradient: ', max_grad, ' on ', paste(max_grad_var, collapse=', '))) } else { writeLines('Error occured while computing scaled gradient, details below:') print(res$scgrad) } writeLines(paste0('Convergence criterion gtHg: ', round(res$gtHg, digits=6))) rm(tmp.env) return (res) }
plot.coef.dfrr<-function(x,select=NULL,ask.hit.return=TRUE,...){ coefs<-x attr(coefs,"dfrr_fit")->dfrr_fit attr(coefs,"standardized")->standardized attr(coefs,"pc.coefs")->return.principal.components time<-seq(dfrr_fit$range[1],dfrr_fit$range[2],length.out = 100) basis<-basis(dfrr_fit) E<-t(fda::eval.basis(time,basis)) if(return.principal.components){ if(standardized) yval<-dfrr_fit$Theta_std%*%E else yval<-dfrr_fit$Theta%*%E }else{ if(standardized) yval<-dfrr_fit$B_std%*%E else yval<-dfrr_fit$B%*%E } if(is.null(select)) select<-1:nrow(yval) if(standardized) nus<-dfrr_fit$nus_std/sum(dfrr_fit$nus_std) else nus<-dfrr_fit$nus/sum(dfrr_fit$nus) plotnames<-if(return.principal.components) paste0("PC ",select) else paste0("Reg.Coef. ",dfrr_fit$varnames[select]) for(i in 1:length(select)){ if(return.principal.components){ variance_explained<-round(nus[select[i]]*100,digits = 2) if(variance_explained<=0) return() } if(ask.hit.return){ invisible(readline(prompt="Hit <Returen> to see next plot:")) } lbl<-plotnames[i] if(standardized) lbl<-paste0("Standardized ",lbl) if(return.principal.components){ variance_explained<-round(nus[select[i]]*100,digits = 2) if(variance_explained<=0) return() lbl<-paste0(lbl," (",round(nus[select[i]]*100,digits = 2),"%)") } value<-yval[select[i],] plot(time,value,'l',main=lbl,...) } }
test_that("basic formatting", { expect_equal(n_perc(mtcars$cyl == 6), "7 (21.88\\%)") expect_equal(n_perc0(mtcars$cyl == 6), "7 (22)") expect_equal(perc_n(mtcars$cyl == 6), paste0("21.88\\% (n = ", nrow(mtcars), ")")) })
library(caper) for(f in dir('../../R', full=TRUE)) (source(f)) par(mfrow=c(2,2), mar=c(3,3,1,1), mgp=c(2,0.7,0)) plot(c(0,13),c(0,10), typ="n", bty="n", xaxt="n",yaxt="n", xlab="", ylab="", xaxs="i",yaxs="i") lines(c(0,7), c(5,8.5)) lines(c(0,7), c(5,1.5)) lines(c(3.5,7), c(3.25,5)) polygon(c(7,10,10), y=c(8.5,10,7)) polygon(c(7,10,10), y=c(5,6.5,3.5)) polygon(c(7,10,10), y=c(1.5,3,0)) points( c(0.5,1.5) +0.5, c(5,5), cex=1, col=1:2) points(c(7.5,8.5)+0.5, c(8.5,8.5), cex=1, col=1:2) points(c(4,5)+0.5, c(3.25,3.25), cex=1.5, col=1:2) points(c(7.5,8.5)+0.5, c(5,5), cex=1.5, col=1:2) points(c(7.5,8.5)+0.5, c(1.5,1.5), cex=2, col=1:2) rect(11 - c(.3,.2,.1), c(0,3.5,7), 11 + c(.3,.2,.1) , c(3,6.5,10)) rect(12 - c(.3,.2,.1), c(0,3.5,7), 12 + c(.3,.2,.1) , c(3,6.5,10), border="red") par(usr=c(0,1,0,1)); text(0.1,0.9, cex=2,"a") dat <- data.frame(x = rnorm(120, mean= rep(2:4, each=40), sd=0.5), y = rnorm(120, mean= rep(2:4, each=40), sd=0.5), tx = gl(3,40)) plot(y~x, col=unclass(tx), data=dat, xaxt="n", xlab="", ylab="") axis(1, col.axis="red") abline(lm(y~x, data=dat)) for(sub in split(dat, dat$tx)) abline(lm(y~x, data=sub), col=unclass(sub$tx)[1], lty=2) plot(c(0,13),c(0,10), typ="n", bty="n", xaxt="n",yaxt="n", xlab="", ylab="", xaxs="i",yaxs="i") lines(c(0,7), c(5,8.5)) lines(c(0,7), c(5,1.5)) lines(c(3.5,7), c(3.25,5)) polygon(c(7,10,10), y=c(8.5,10,7)) polygon(c(7,10,10), y=c(5,6.5,3.5)) polygon(c(7,10,10), y=c(1.5,3,0)) points(c(0.5,1.5)+0.5, c(5,5), cex=1, col=1:2) points(c(7.5,8.5)+0.5, c(8.5,8.5), cex=1, col=1:2) points(c(4,5)+0.5, c(3.25,3.25), cex=c(1,1.5), col=1:2) points(c(7.5,8.5)+0.5, c(5,5), cex=c(1,1.5), col=1:2) points(c(7.5,8.5)+0.5, c(1.5,1.5), cex=c(1,2), col=1:2) polygon(11 + c(-0,-0.1,0.1,0), c(3,0,0,3)) polygon(12 + c(-0.2,-0.3,0.3,0.2), c(3,0,0,3), border="red") polygon(11 + c(-0,-0.1,0.1,0), c(6.5,3.5,3.5,6.5)) polygon(12 + c(-0.1,-0.2,0.2,0.1), c(6.5,3.5,3.5,6.5), border="red") polygon(11 + c(-0,-0.1,0.1,0), c(10,7.5,7.5,10)) polygon(12 + c(-0.0,-0.1,0.1,0.), c(10,7.5,7.5,10), border="red") par(usr=c(0,1,0,1)); text(0.1,0.9, cex=2, "b") dat <- data.frame(x = rnorm(120, mean= rep(2:4, each=40), sd=0.5), tx = gl(3,40)) dat$y <- dat$x - rnorm(120, mean= rep(0:2, each=40), sd=0.5) plot(y~x, col=unclass(tx), data=dat, xaxt="n", xlab="", ylab="") axis(1, col.axis="red") abline(lm(y~x, data=dat)) for(sub in split(dat, dat$tx)) abline(lm(y~x, data=sub), col=unclass(sub$tx)[1], lty=2) phy <- read.tree(text='(((B:2,A:2):1,D:3):1,(C:1,E:1):3);') dat <- data.frame(taxa=c("A","B","C","D","E"), n.species=c(5,9,12,1,13), mass=c(4.1,4.5,5.9,3.0,6.0)) cdat <- comparative.data(data=dat, phy=phy, names.col="taxa") print(cdat) data(perissodactyla) (perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial)) (perissoFull <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial, na.omit=FALSE)) na.omit(perisso) comparative.data(perissodactyla.tree, perissodactyla.data, Binomial, scope= log.female.wt ~ log.gestation.length) na.omit(perissoFull, scope=log.female.wt ~ log.gestation.length + Territoriality) subset(perissoFull, subset=! is.na(Territoriality)) subset(perissoFull, subset=log.female.wt > 5.5, select=c(log.female.wt, log.gestation.length)) horses <- grep('Equus', perissoFull$phy$tip.label) perissoFull[horses,] perissoFull[horses, 2:3] z <- structure(list(edge = structure(c(11L, 15L, 18L, 18L, 15L, 16L, 16L, 11L, 12L, 13L, 13L, 19L, 19L, 12L, 14L, 14L, 17L, 17L, 15L, 18L, 1L, 2L, 16L, 3L, 4L, 12L, 13L, 5L, 19L, 6L, 7L, 14L, 8L, 17L, 9L, 10L), .Dim = c(18L, 2L)), edge.length = c(5.723, 2.186, 1.09, 1.09, 0.627, 2.649, 2.649, 1.049, 1.411, 6.54, 5.538, 1.001, 1.001, 1.863, 6.088, 4.777, 1.312, 1.312), tip.label = c("t8", "t6", "t4", "t10", "t9", "t5", "t7", "t1", "t3", "t2"), Nnode = 9L), .Names = c("edge", "edge.length", "tip.label", "Nnode"), class = "phylo", order = "cladewise") V <- VCV.array(z) ec <- rep('grey50', 18) ec[c(1,5,7)] <- 'red' ec[c(8,14)] <- 'blue' plot(z, no.margin=TRUE, cex=0.6, label.offset=0.3, edge.col=ec) internal <- z$edge[,2] > 10 vlines <- 9 * c(0, 0.5, 1, 1.5) zz <- z layout(matrix(c(1:9), ncol=3)) par(mar=c(0,0.5,2,0.5)) cx <- 0.8 ln <- 0.5 xl <- c(0,15) pvals <- c(1.4, 0.5) ec <- ifelse(internal,'red', 'grey30') dd <- ifelse(lower.tri(V) | upper.tri(V), V * pvals[1], V) ddh <- as.phylo(hclust(dist(dd))) plot(ddh, edge.col = 'red', x.lim=xl, label.offset=0.2) mtext(bquote(lambda == .(pvals[1])), side=3, cex=cx, line=ln) abline(v=vlines, lty=2, col='grey') plot(z, edge.col=ec, x.lim=xl, label.offset=0.2) abline(v=vlines, lty=2, col='grey') mtext(expression(lambda == 1), side=3, cex=cx, line=ln) dd <- ifelse(lower.tri(V) | upper.tri(V), V * pvals[2], V) ddh <- as.phylo(hclust(dist(dd))) plot(ddh, edge.col = 'red', x.lim=xl, label.offset=0.2) mtext(bquote(lambda == .(pvals[2])), side=3, cex=cx, line=ln) abline(v=vlines, lty=2, col='grey') pvals <- c(1.2, 0.5) dd <- V ^ pvals[1] ddh <- as.phylo(hclust(dist(dd))) plot(ddh, edge.col = 'red', x.lim=xl, label.offset=0.2) mtext(bquote(delta == .(pvals[1])), side=3, cex=cx, line=ln) abline(v=vlines, lty=2, col='grey') plot(z, edge.col='red', x.lim=xl, label.offset=0.2) abline(v=vlines, lty=2, col='grey') mtext(expression(delta == 1), side=3, cex=cx, line=ln) dd <- V ^ pvals[2] ddh <- as.phylo(hclust(dist(dd))) plot(ddh, edge.col='red', x.lim=xl, label.offset=0.2) mtext(bquote(delta == .(pvals[2])), cex=cx, line=ln) abline(v=vlines, lty=2, col='grey') pvals <- c(1.2, 0.0) ec <- ifelse(internal,'red', 'grey30') zz$edge.length <- z$edge.length^pvals[1] plot(zz, edge.col = 'red', x.lim=xl, label.offset=0.2) mtext(bquote(kappa == .(pvals[1])), side=3, cex=cx, line=ln) abline(v=vlines, lty=2, col='grey') plot(z, edge.col='red', x.lim=xl, label.offset=0.2) abline(v=vlines, lty=2, col='grey') mtext(expression(kappa == 1), side=3, cex=cx, line=ln) zz$edge.length <- z$edge.length^pvals[2] plot(zz, edge.col='red', x.lim=xl, label.offset=0.2) mtext(bquote(kappa == .(pvals[1])), cex=cx, line=ln) abline(v=vlines, lty=2, col='grey') data(shorebird) shorebird <- comparative.data(shorebird.tree, shorebird.data, Species, vcv=TRUE) mod <- pgls(log(Egg.Mass) ~ log(M.Mass), shorebird) print(mod) summary(mod) data(shorebird) shorebird <- comparative.data(shorebird.tree, shorebird.data, Species, vcv=TRUE, vcv.dim=3) mod <- pgls(log(Egg.Mass) ~ log(M.Mass), shorebird, lambda='ML') summary(mod) mod.l <- pgls.profile(mod, 'lambda') mod.d <- pgls.profile(mod, 'delta') mod.k <- pgls.profile(mod, 'kappa') plot(mod.l); plot(mod.d); plot(mod.k) par(mar=c(4.5,3,1,1), mfrow=c(1,3), mgp=c(1.8,0.8,0), tcl=-0.2) plot(mod.l); plot(mod.d); plot(mod.k) par(mfrow=c(2,2), mar=c(3,3,1,1), mgp=c(2,0.7,0), tcl=-0.2) plot(mod) mod1 <- pgls(log(Egg.Mass) ~ log(M.Mass) * log(F.Mass), shorebird) anova(mod1) mod2 <- pgls(log(Egg.Mass) ~ log(M.Mass) + log(F.Mass), shorebird) mod3 <- pgls(log(Egg.Mass) ~ log(M.Mass) , shorebird) mod4 <- pgls(log(Egg.Mass) ~ 1, shorebird) anova(mod1, mod2, mod3, mod4) AIC(mod1, mod2, mod3, mod4) data(shorebird) shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass) shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass) shorebird.data$lgF.Mass <- log(shorebird.data$F.Mass) shorebird <- comparative.data(shorebird.tree, shorebird.data, Species) crunchMod <- crunch(lgEgg.Mass ~ lgF.Mass + lgM.Mass, data=shorebird) summary(crunchMod) perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial) brunchMod <- brunch(log.female.wt ~ Territoriality, data=perisso) caic.table(brunchMod) bwd <- rep(1,15) bwd[c(5,6,11,12,9,13,14,15)] <- 3 plot(perisso$phy, 'cladogram', use.edge.length=FALSE, label.offset=0.4, show.node=TRUE, cex=0.7, show.tip=FALSE, x.lim=c(0,12), no.margin=TRUE, edge.width=bwd) points(rep(8.25,9), 1:9, pch=ifelse(perisso$data$Terr=='Yes', 1,19)) text(rep(8.5,9), 1:9, perisso$phy$tip.label, font=3, adj=0) data(IsaacEtAl) primates <- comparative.data(primates.tree, primates.data, binomial, na.omit=FALSE) primatesBodySize <- macrocaic(species.rich ~ body.mass, data=primates) summary(primatesBodySize) data(BritishBirds) BritishBirds <- comparative.data(BritishBirds.tree, BritishBirds.data, binomial) redPD <- phylo.d(BritishBirds, binvar=Red_list) par(mar=c(3,3,2,1), mgp=c(1.8,0.8,0), tcl=-0.3) plot(density(redPD$Permutations$random, bw=0.5), main='', xlim=c(10,55), col='blue', xlab='Sum of character change') lines(density(redPD$Permutations$brownian,bw=0.5), col='red') abline(v=redPD$Parameters$Observed) abline(v=redPD$Parameters$Observed, col='grey') abline(v=redPD$Parameters$MeanRandom, col='blue') abline(v=redPD$Parameters$MeanBrownian, col='red') with(redPD$Parameters, axis(3, at=c(MeanBrownian, Observed, MeanRandom), labels=c(0, round(redPD$DEstimate,2),1), mgp=c(1.5,0.7,0.25))) mtext(expression(italic(D)==phantom(x)), side=3, at=25, line=1.2) data(BritishBirds) BritishBirds <- comparative.data(BritishBirds.tree, BritishBirds.data, binomial) redPhyloD <- phylo.d(BritishBirds, binvar=Red_list) print(redPhyloD) par(mfrow=c(2,3)) shorebird <- comparative.data(shorebird.tree, shorebird.data, Species) crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird) caic.diagnostics(crunchMod) shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass) shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass) shorebird <- comparative.data(shorebird.tree, shorebird.data, Species) crunchMod2 <- crunch(lgEgg.Mass ~ lgM.Mass, data=shorebird) caic.diagnostics(crunchMod2) par(mfrow=c(2,3), mar=c(3,3,1,1), mgp=c(2,0.7,0), tcl=-0.2) shorebird <- comparative.data(shorebird.tree, shorebird.data, Species) crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird) x <- caic.diagnostics(crunchMod) crunchMod2 <- crunch(lgEgg.Mass ~ lgM.Mass, data=shorebird) x <- caic.diagnostics(crunchMod2) data(shorebird) shorebird <- comparative.data(shorebird.tree, shorebird.data, Species) crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird) caic.diagnostics(crunchMod) crunchModRobust <- caic.robust(crunchMod) caic.diagnostics(crunchModRobust, outlier=2) par(mfrow=c(2,3), mar=c(3,3,1,1), mgp=c(2,0.7,0), tcl=-0.2) data(shorebird) shorebird <- comparative.data(shorebird.tree, shorebird.data, Species) crunchMod <- crunch(Egg.Mass ~ M.Mass, data=shorebird) x <-caic.diagnostics(crunchMod) crunchModRobust <- caic.robust(crunchMod) x <-caic.diagnostics(crunchModRobust, outlier=2) data(shorebird) shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass) shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass) shorebird.data$lgF.Mass <- log(shorebird.data$F.Mass) shorebird <- comparative.data(shorebird.tree, shorebird.data, Species) crunchMod <- crunch(lgEgg.Mass ~ lgF.Mass + lgM.Mass, data=shorebird) par(mfrow=c(2,2)) plot(crunchMod) par(mfrow=c(2,2), mar=c(3,3,2,1), mgp=c(2,0.7,0), tcl=-0.2) data(shorebird) crunchMod <- crunch(lgEgg.Mass ~ lgF.Mass + lgM.Mass, data=shorebird) plot(crunchMod) shorebird.data$lgEgg.Mass <- log(shorebird.data$Egg.Mass) shorebird.data$lgM.Mass <- log(shorebird.data$M.Mass) shorebird.data$lgF.Mass <- log(shorebird.data$F.Mass) shorebird <- comparative.data(shorebird.tree, shorebird.data, Species) cMod1 <- crunch(lgEgg.Mass ~ lgM.Mass * lgF.Mass, data=shorebird) cMod2 <- crunch(lgEgg.Mass ~ lgM.Mass + lgF.Mass, data=shorebird) cMod3 <- crunch(lgEgg.Mass ~ lgM.Mass , data=shorebird) anova(cMod1, cMod2, cMod3) AIC(cMod1, cMod2, cMod3) data(syrphidae) syrphidae <- comparative.data(phy=syrphidaeTree, dat=syrphidaeRich, names.col=genus) summary(fusco.test(syrphidae, rich=nSpp)) summary(fusco.test(syrphidae, tipsAsSpecies=TRUE)) data(BritishBirds) BritishBirds.cm <- clade.matrix(BritishBirds.tree) redListSpecies <- with(BritishBirds.data, binomial[Red_list==1]) obs <- pd.calc(BritishBirds.cm, redListSpecies, method="TBL") rand <- pd.bootstrap(BritishBirds.cm, ntips=length(redListSpecies), rep=1000, method="TBL") plot(density(rand), main='Total branch length for random sets of 32 species.') abline(v=obs, col='red') tree <- read.tree(text="((((A:1,B:1):1.5,C:2.5):0.5,(D:0.6,E:0.6):2.4):0.5,((F:1.9,G:1.9):0.8,(H:1.6,I:1.6):1.1):0.8):0.2;") clmat <- clade.matrix(tree) tips <- c("A","C","D","E","G","H") par(mfrow=c(2,3), mar=rep(1,4)) tip.col <- rep('grey', length=length(tree$tip.label)) tip.col[c(1,3,4,5,7,8)] <- 'black' cl <- rep('black', length=length(tree$edge.length)) cl[c(1,2,3,4,6,7,8,9,10,11,13,14,15)] <- 'red' plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl) text(0.2,8.5, "TBL", cex=1.2, adj=c(0,0)) cl <- rep('black', length=length(tree$edge.length)) cl[c(3,4,6,8,9,11,14,13,15)] <- 'red' plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl) text(0.2,8.5, "UEH", cex=1.2, adj=c(0,0)) cl <- rep('black', length=length(tree$edge.length)) cl[c(1,2,7,10)] <- 'red' plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl) text(0.2,8.5, "SBL", cex=1.2, adj=c(0,0)) cl <- rep('black', length=length(tree$edge.length)) cl[c(4,6,8,9,13,15)] <- 'red' plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl) text(0.2,8.5, "TIP", cex=1.2, adj=c(0,0)) tips <- c("A","C") tip.col <- rep('grey', length=length(tree$tip.label)) tip.col[c(1,3)] <- 'black' cl <- rep('black', length=length(tree$edge.length)) cl[c(3,4,6)] <- 'red' plot(tree, label.offset=0.1, cex=1.2, tip.color=tip.col, x.lim=3.8, edge.col=cl) text(0.2,8.5, "MST", cex=1.2, adj=c(0,0)) par(mar=c(3,3,1,1)) plot(density(rand), main='', xlab= 'TBL values for red listed British birds.') abline(v=obs, col='red') data(IsaacEtAl) primates.cm <- clade.matrix(primates.tree) primateED <- ed.calc(primates.cm) str(primateED) plot(density(primateED$spp$ED)) with(primateED, spp[spp$ED == max(spp$ED),]) par(mfrow=c(1,3), mar=c(0,0,0,0), mgp=c(2,0.7,0)) edDemo <- ed.calc(clmat) edge.col <- rep('gray30', 16) edge.col[c(1,2,6)] <- 'red' edge.col[10:12] <- 'blue' xx <- plot(tree, show.tip.label=FALSE, x.lim=c(0,4),y.lim=c(0.6,9.4), edge.col=edge.col, edge.width=2, no.margin=TRUE) edgeLab <- with(edDemo$branch, paste(len, '/' , nSp)) [tree$edge[,2]] edgelabels(edgeLab, 1:16, adj=c(0.5,-0.3), frame='none', col='gray30', cex=0.7) edgeLab <- edDemo$branch$ED[tree$edge[,2]] edgelabels(sprintf("%0.2f", edgeLab), 1:16, adj=c(0.5,1.3), frame='none', col=edge.col, cex=0.9) tipLab <- with(edDemo$spp, sprintf("%0.2f", ED)) tipCol <- rep('gray30', 9) tipCol[c(3,6)] <- c('red','blue') tiplabels(text=tipLab, adj=c(-0.25,0.5), frame='none', col=tipCol) par(usr=c(0,1,0,1)) text(0.1, 0.9, "a)", cex=1.2) par(mar=c(3,3,1,1)) plot(density(primateED$spp$ED), main='', xlab='Species ED score') edMax <- max(primateED$spp$ED) arrows(edMax, 0.04, edMax, 0.01, col='red', len=0.1) par(usr=c(0,1,0,1), mar=c(0,0,0,0)) text(0.1, 0.9, "b)", cex=1.2) maxSpp <- which(primateED$spp$ED == edMax) xx <- which(rowSums(primates.cm$clade.matrix[,maxSpp])> 0) edgeCol <- rep('grey30', length(primates.tree$edge.length)) edgeCol[match(xx, primates.tree$edge[,2])] <- 'red' plot(primates.tree, show.tip=FALSE, no.margin=TRUE, edge.col=edgeCol) par(usr=c(0,1,0,1)) text(0.1, 0.9, "c)", cex=1.2) set.seed(2345) basicTree <- growTree(b=1, d=0, halt=20, grain=Inf) extendTree <- growTree(b=1, d=0, halt=20, extend.proportion=1, grain=Inf) timeLimit <- growTree(b=1, d=0, halt=expression(clade.age>=3), grain=0.01) extinctTree <- growTree(b=1, d=0.1, halt=expression(nExtinctTip>=3), extend.proportion=1, grain=Inf) densityDependence <- growTree(b=expression(2/nExtantTip), d=0, halt=50, grain=Inf) increasingExtinction <- growTree(b=1, d=expression(0.2 * clade.age), halt=50) par(mfrow=c(2,3), mar=c(1.5,0.5,0,0.5), tcl=-0.2, mgp=c(1,0.5,0), cex.axis=0.8) plot(basicTree$phy , root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"a)") plot(extendTree$phy , root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"b)") plot(timeLimit$phy , root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"c)") plot(extinctTree$phy, root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"d)") plot(densityDependence$phy, root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"e)") plot(increasingExtinction$phy, root.edge=TRUE); axis(1); par(usr=c(0,1,0,1)); text(0.1,0.06,"f)") set.seed(421) mammalMeans <- c(logBodyMass=5.48, logLitterSize=0.69) simpleBrownian <- growTree(halt=100, ct.start=mammalMeans, extend.proportion=1, grain=Inf) mammalVar <- c(10, 0.44) varBrownian <- growTree(halt=100, ct.start=mammalMeans, ct.var=mammalVar, extend.proportion=1, grain=Inf) mammalCovar <- matrix(c(10,-0.65, -0.65, 0.44), ncol=2) covarBrownian <- growTree(halt=100, ct.start=mammalMeans, ct.var=mammalCovar, extend.proportion=1, grain=Inf) par(mfrow=c(1,3), mar=c(2.5,2.5,0.5,0.5), tcl=-0.2, mgp=c(1.5,0.5,0), cex.axis=0.8) stips <- simpleBrownian$data vtips <- varBrownian$data cvtips <- covarBrownian$data lims <- sapply( rbind(stips, vtips,cvtips)[, c('logBodyMass','logLitterSize')], range) plot(logBodyMass ~ logLitterSize, data=stips, xlim=lims[,2], ylim=lims[,1]) plot(logBodyMass ~ logLitterSize, data=vtips, xlim=lims[,2], ylim=lims[,1]) plot(logBodyMass ~ logLitterSize, data=cvtips, xlim=lims[,2], ylim=lims[,1]) flight <- matrix(c(0,0.1,0.001,0), ncol=2) flightNames <- c('ter','fly') dimnames(flight) <- list(flightNames, flightNames) trophic <- matrix(c(0,0.2,0.01,0.2,0,0.1,0,0.05,0), ncol=3) trophNames <- c('herb','omni','carn') dimnames(trophic) <- list(trophNames, trophNames) discTraits <- list(flight=flight, trophic=trophic) discreteTree <- growTree(halt=60, dt=discTraits, extend.proportion=1, grain=Inf) par(mar=c(0,0,0,0), tcl=-0.2, mgp=c(1,0.5,0), cex.axis=0.8) plot(discreteTree$phy, show.tip=FALSE) lastPP <- get("last_plot.phylo", envir = .PlotPhyloEnv) traitsByNode <- with(discreteTree, rbind( cbind(node=phy$tip.label, data[, c('flight','trophic')]), node.data[, c('node','flight','trophic')])) traitsByNode <- traitsByNode[match(1:199, traitsByNode$node), ] with(lastPP, points(xx + 0.06, yy, pch=21, col=unclass(traitsByNode$flight), xpd=NA, cex=0.6)) with(lastPP, points(xx + 0.12, yy, pch=22, col=unclass(traitsByNode$trophic), xpd=NA, cex=0.6)) set.seed(95132) bLatency <- expression((0.2 *lin.age)/(0.1 + lin.age)) dSenesce <- expression(lin.age * 0.02) halt <- expression(nExtantTip >= 60) latencyTree <- growTree(b=bLatency, d=dSenesce, halt=halt, grain=0.01) traitMean <- c(logBodyMass=5.48) traitVar <- c(logBodyMass=10) bLatTrait <- expression(((0.2 + ((5.48 - logBodyMass)/25))*lin.age)/(0.1 + lin.age)) latTraitTree <- growTree(b=bLatTrait, d=dSenesce, halt=halt, ct.start=traitMean, ct.var=traitVar, grain=0.01) par(mfrow=c(2,2), mar=c(2.5,2.5,1,1), tcl=-0.2, mgp=c(1.5,0.5,0), cex.axis=0.8) curve(0.02*x, xlim=c(0,20), ylab='Rate', xlab="Lineage age") curve(((0.2 + ((5.48 - 5.48)/25))*x)/(0.1 + x), add=TRUE, col='red') curve(((0.2 + ((5.48 - 3.48)/25))*x)/(0.1 + x), add=TRUE, col='red', lty=2) curve(((0.2 + ((5.48 - 7.48)/25))*x)/(0.1 + x), add=TRUE, col='red', lty=2) plot(latencyTree$phy, no.margin=TRUE, cex=0.8) plot(latTraitTree$phy, no.margin=TRUE, cex=0.8, show.tip=FALSE) traitMean <- c(logBodyMass=5.48) traitVar <- c(logBodyMass=10) inherit <- list(logBodyMass=expression(logBodyMass * c(0.8, 1.2))) inheritTree <- growTree(b=1, halt=40, ct.start=traitMean, ct.var=traitVar, inheritance=inherit, grain=Inf, extend.proportion=1) rNames <- c("AB", "A", "B") regions <- list(region = matrix(c(0, 0.05, 0.05, 0.1, 0,0,0.1,0,0), ncol=3, dimnames=list(rNames,rNames))) extinct <- expression(ifelse(region == "AB", 0.0001, 0.01)) spec <- list(regA_spec = expression(ifelse(region == "AB" | region == "A", 1, 0)), regB_spec = expression(ifelse(region == "AB" | region == "B", 0.5, 0))) inherit <- list(region = expression(if(winnerName=="regB_spec" && region[1] == "AB") c("B","A") else region), region = expression(if(winnerName=="regA_spec" && region[1] == "AB") c("A","B") else region)) biogeogTree <- growTree(b=spec, d=extinct, halt=80, inherit=inherit, dt.rates=regions, inf.rates="quiet", grain=Inf) epochTree <- growTree(halt=100, output.lineages=TRUE, grain=Inf) epochTree2 <- growTree(d=5, halt=expression(nExtantTip==20), linObj=epochTree, output.lineages=TRUE, grain=Inf) epochTree3 <- growTree(linObj=epochTree2, halt=100, grain=Inf) par(mfrow=c(1,3), mar=c(1,1,1,1)) depth <- VCV.array(inheritTree$phy)[1,1] plot(inheritTree$phy, no.margin=TRUE, cex=0.8, show.tip=FALSE, root.edge=TRUE, x.lim=c(0,depth*1.1)) rightEdge <- depth*1.05 tips <- seq_along(inheritTree$phy$tip.label) bm <- inheritTree$data$logBodyMass sc <- max(bm) / (depth*0.04) rect(rightEdge - 5.48/sc, 0 , rightEdge + 5.48/sc, max(tips)+1, col='grey80', border=NA) arrows(rightEdge-bm/sc, tips, rightEdge+bm/sc, tips, code=0, col='red', xpd=NA, lwd=2, lend=2) plot(biogeogTree$phy, edge.col= unclass(biogeogTree$data$region), show.tip.label=FALSE, root.edge=TRUE) plot(epochTree3$phy, show.tip.label=FALSE) data(perissodactyla) perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial) perissoCM <- clade.matrix(perisso$phy) str(perissoCM) perissoCM$clade.matrix data(perissodactyla) perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial) clade.members(15, perisso$phy) clade.members(15, perisso$phy, tip.labels=TRUE) clade.members(15, perisso$phy, tip.labels=TRUE, include.nodes=TRUE) str(clade.members.list(perisso$phy)) str(clade.members.list(perisso$phy, tip.labels=TRUE)) data(perissodactyla) perisso <- comparative.data(perissodactyla.tree, perissodactyla.data, Binomial) str(VCV.array(perisso$phy)) str(VCV.array(perisso$phy, dim=3))
invisible(NULL) NULL
roxy_tag_parse.roxy_tag_inherit <- function(x) tag_inherit(x) roxy_tag_rd.roxy_tag_inherit <- function(x, base_path, env) { rd_section_inherit(x$val$source, list(x$val$fields)) } roxy_tag_parse.roxy_tag_inheritParams <- function(x) tag_value(x) roxy_tag_rd.roxy_tag_inheritParams <- function(x, base_path, env) { rd_section_inherit(x$val, list("params")) } roxy_tag_parse.roxy_tag_inheritDotParams <- function(x) { tag_two_part(x, "source", "args", required = FALSE, markdown = FALSE) } roxy_tag_rd.roxy_tag_inheritDotParams <- function(x, base_path, env) { rd_section_inherit_dot_params(x$val$source, x$val$args) } roxy_tag_parse.roxy_tag_inheritSection <- function(x) tag_name_description(x) roxy_tag_rd.roxy_tag_inheritSection <- function(x, base_path, env) { rd_section_inherit_section(x$val$name, x$val$description) } rd_section_inherit <- function(source, fields) { stopifnot(is.character(source), is.list(fields)) stopifnot(!anyDuplicated(source)) stopifnot(length(source) == length(fields)) rd_section("inherit", list(source = source, fields = fields)) } merge.rd_section_inherit <- function(x, y, ...) { stopifnot(identical(class(x), class(y))) dedup <- collapse( c(x$value$source, y$value$source), c(x$value$fields, y$value$fields), function(x) Reduce(union, x) ) rd_section("inherit", list(source = dedup$key, fields = dedup$value)) } format.rd_section_inherit <- function(x, ...) NULL rd_section_inherit_section <- function(source, title) { stopifnot(is.character(source), is.character(title)) stopifnot(length(source) == length(title)) rd_section("inherit_section", list(source = source, title = title)) } format.rd_section_inherit_section <- function(x, ...) NULL merge.rd_section_inherit_section <- function(x, y, ...) { stopifnot(identical(class(x), class(y))) rd_section_inherit_section(c(x$value$source, y$value$source), c(x$value$title, y$value$title)) } rd_section_inherit_dot_params <- function(source, args) { stopifnot(is.character(source), is.character(args)) stopifnot(length(source) == length(args)) rd_section("inherit_dot_params", list(source = source, args = args)) } format.rd_section_inherit_dot_params <- function(x, ...) NULL merge.rd_section_inherit_dot_params <- function(x, y, ...) { stopifnot(identical(class(x), class(y))) rd_section_inherit_dot_params(c(x$value$source, y$value$source), c(x$value$args, y$value$args)) } topics_process_inherit <- function(topics, env) { inherits <- function(type) { function(x) x$inherits_from(type) } topics$topo_apply(inherits("return"), inherit_field, roxy_name = "return", rd_name = "value") topics$topo_apply(inherits("title"), inherit_field, "title") topics$topo_apply(inherits("description"), inherit_field, "description") topics$topo_apply(inherits("details"), inherit_field, "details") topics$topo_apply(inherits("seealso"), inherit_field, "seealso") topics$topo_apply(inherits("references"), inherit_field, "references") topics$topo_apply(inherits("examples"), inherit_field, "examples") topics$topo_apply(inherits("author"), inherit_field, "author") topics$topo_apply(inherits("source"), inherit_field, "source") topics$topo_apply(function(x) x$inherits_section_from(), inherit_section) topics$topo_apply(inherits("sections"), inherit_sections) topics$topo_apply(inherits("params"), inherit_params) topics$apply(inherit_dot_params, env = env) invisible() } inherit_params <- function(topic, topics) { inheritors <- topic$inherits_from("params") if (length(inheritors) == 0) { return() } documented <- get_documented_params(topic) needed <- topic$get_value("formals") missing <- setdiff(needed, documented) if (length(missing) == 0) { warn(paste0( "Topic '", topic$get_name(), "': ", "no parameters to inherit with @inheritParams" )) return() } for (inheritor in inheritors) { inherited <- find_params(inheritor, topics) matches <- map_chr(missing, match_param, names(inherited)) new_match <- !is.na(matches) if (!any(new_match)) { next } topic$add( rd_section( "param", setNames(inherited[matches[new_match]], missing[new_match]) ) ) missing <- missing[!new_match] } } inherit_dot_params <- function(topic, topics, env) { inheritors <- topic$get_value("inherit_dot_params") if (is.null(inheritors)) return() funs <- lapply(inheritors$source, function(x) eval(parse(text = x), envir = env)) args <- map2(funs, inheritors$args, select_args_text) docs <- lapply(inheritors$source, find_params, topics = topics) arg_matches <- function(args, docs) { doc_args <- str_split(names(docs), ", ?") match <- map_lgl(doc_args, function(x) x %in% args) docs[match] } docs_selected <- unlist(map2(args, docs, arg_matches)) documented <- get_documented_params(topic) non_documented_params <- setdiff(names(docs_selected), documented) docs_selected <- docs_selected[non_documented_params] src <- inheritors$source dest <- map_chr(src, resolve_qualified_link) from <- paste0("\\code{\\link[", dest, "]{", src, "}}", collapse = ", ") arg_names <- paste0("\\code{", names(docs_selected), "}") args <- paste0(" \\item{", arg_names, "}{", docs_selected, "}", collapse = "\n") rd <- paste0( "\n", " Arguments passed on to ", from, "\n", " \\describe{\n", args, "\n", " }" ) topic$add(rd_section("param", c("..." = rd))) } get_documented_params <- function(topic, only_first = FALSE) { documented <- names(topic$get_value("param")) if (length(documented) > 0) { documented <- strsplit(documented, ",") if (only_first) documented <- map_chr(documented, 1) else documented <- unlist(documented) } documented[documented == "\\dots"] <- "..." documented } find_params <- function(name, topics) { topic <- get_rd(name, topics) if (is.null(topic)) { return() } params <- topic_params(topic) if (is.null(params)) return() param_names <- str_trim(names(params)) param_names[param_names == "\\dots"] <- "..." individual_names <- strsplit(param_names, ",\\s*") reps <- map_int(individual_names, length) setNames(rep.int(params, reps), unlist(individual_names)) } topic_params <- function(x) UseMethod("topic_params") topic_params.Rd <- function(x) { arguments <- get_tags(x, "\\arguments") if (length(arguments) != 1) { return(list()) } items <- get_tags(arguments[[1]], "\\item") values <- map_chr(items, function(x) rd2text(x[[2]])) params <- map_chr(items, function(x) rd2text(x[[1]])) setNames(values, params) } topic_params.RoxyTopic <- function(x) { x$get_value("param") } inherit_sections <- function(topic, topics) { current_secs <- topic$get_value("section")$title for (inheritor in topic$inherits_from("sections")) { inheritor <- get_rd(inheritor, topics) if (is.null(inheritor)) { return() } sections <- find_sections(inheritor) needed <- !(sections$title %in% current_secs) if (!any(needed)) next topic$add( rd_section_section(sections$title[needed], sections$content[needed]) ) } } inherit_section <- function(topic, topics) { sections <- topic$get_value("inherit_section") sources <- sections$source titles <- sections$title for (i in seq_along(sources)) { inheritor <- get_rd(sources[[i]], topics) if (is.null(inheritor)) { return() } new_section <- find_sections(inheritor) selected <- new_section$title %in% titles[[i]] if (sum(selected) != 1) { warning( "Can't find section '", titles[[i]], "' in ?", sources[[i]], call. = FALSE ) } topic$add( rd_section_section(new_section$title[selected], new_section$content[selected]) ) } } find_sections <- function(topic) { if (inherits(topic, "Rd")) { tag <- get_tags(topic, "\\section") titles <- map_chr(map(tag, 1), rd2text) contents <- map_chr(map(tag, 2), rd2text) list(title = titles, content = contents) } else { topic$get_value("section") } } inherit_field <- function(topic, topics, rd_name, roxy_name = rd_name) { if (topic$has_section(rd_name)) return() for (inherit_from in topic$inherits_from(roxy_name)) { inherit_topic <- get_rd(inherit_from, topics) if (is.null(inherit_topic)) { next } inheritee <- find_field(inherit_topic, rd_name) if (is.null(inheritee)) next topic$add(rd_section(rd_name, inheritee)) return() } } find_field <- function(topic, field_name) { if (inherits(topic, "Rd")) { tag <- get_tags(topic, paste0("\\", field_name)) if (length(tag) == 0) return() value <- tag[[1]] attr(value, "Rd_tag") <- NULL str_trim(rd2text(value)) } else { topic$get_value(field_name) } } get_rd <- function(name, topics) { if (has_colons(name)) { parsed <- parse_expr(name) pkg <- as.character(parsed[[2]]) fun <- as.character(parsed[[3]]) tweak_links(get_rd_from_help(pkg, fun), package = pkg) } else { rd_name <- topics$find_filename(name) if (identical(rd_name, NA_character_)) { warn(paste0("Can't find help topic '", name, "' in current package")) } topics$get(rd_name) } } get_rd_from_help <- function(package, alias) { if (!is_installed(package)) { warn(paste0("Can't find package '", package, "'")) return() } help <- eval(expr(help(!!alias, !!package))) if (length(help) == 0) { warn(paste0("Can't find help topic '", alias, "' in '", package, "' package")) return() } internal_f("utils", ".getHelpFile")(help) } match_param <- function(needle, haystack) { if (needle %in% haystack) { return(needle) } if (substr(needle, 1, 1) == ".") { if (needle %in% paste0(".", haystack)) { return(substr(needle, 2, nchar(needle))) } } else { if (paste0(".", needle) %in% haystack) { return(paste0(".", needle)) } } NA }
.arsa_control <- list( cool = 0.5, tmin = 0.0001, swap_to_inversion = .5, try_multiplier = 100, reps = 1L, verbose = FALSE ) seriate_dist_arsa <- function(x, control = NULL) { param <- .get_parameters(control, .arsa_control) A <- as.matrix(x) N <- ncol(A) NREPS <- as.integer(param$reps) IPERM <- integer(N) D <- double(N * N) U <- integer(N) S <- integer(N) T <- integer(NREPS * N) SB <- integer(N) ZBEST <- double(1) ret <- .Fortran( "arsa", N, A, as.numeric(param$cool), as.numeric(param$tmin), NREPS, IPERM, D, U, S, T, SB, ZBEST, as.numeric(param$swap_to_insertion), as.numeric(param$try_multiplier), as.integer(param$verbose), PACKAGE = "seriation" ) o <- ret[[6]] names(o) <- labels(x)[o] if (all(o == 0)) { o <- 1:N warning( "ARSA has returned an invalid permutation vector! Check the supplied dissimilarity matrix." ) } o } .bb_control <- list(eps = 1e-7, verbose = FALSE) seriate_dist_bburcg <- function(x, control = NULL) { param <- .get_parameters(control, .bb_control) A <- as.matrix(x) N <- ncol(A) X <- integer(N) Q <- integer(N) D <- integer(N * N * N) DD <- integer(N * N * N) S <- integer(N) UNSEL <- integer(N) ret <- .Fortran("bburcg", N, A, param$eps, X, Q, D, DD, S, UNSEL, param$verbose) o <- ret[[4]] names(o) <- labels(x)[o] o } seriate_dist_bbwrcg <- function(x, control = NULL) { param <- .get_parameters(control, .bb_control) A <- as.matrix(x) N <- ncol(A) X <- integer(N) Q <- integer(N) D <- double(N * N * N) DD <- double(N * N * N) S <- integer(N) UNSEL <- integer(N) ret <- .Fortran("bbwrcg", N, A, param$eps, X, Q, D, DD, S, UNSEL, param$verbose) o <- ret[[4]] names(o) <- labels(x)[o] o } set_seriation_method( "dist", "ARSA", seriate_dist_arsa, "Minimize the linear seriation criterion using simulated annealing (Brusco et al, 2008).\ncontrol parameters:\n - cool (cooling rate)\n - tmin (minimum temperature)\n - swap_to_inversion (proportion of swaps to inversions for local neighborhood search)\n - try_multiplier (local search tries per temperature; multiplied with the number of objects)\n - reps (repeat the algorithm with random initialization)\n", control = .arsa_control ) set_seriation_method( "dist", "BBURCG", seriate_dist_bburcg, "Minimize the unweighted row/column gradient by branch-and-bound (Brusco and Stahl 2005). This is only feasible for a relatively small number of objects.", control = .bb_control ) set_seriation_method( "dist", "BBWRCG", seriate_dist_bbwrcg, "Minimize the weighted row/column gradient by branch-and-bound (Brusco and Stahl 2005). This is only feasible for a relatively small number of objects.", control = .bb_control )
context("Testing new_storage_location()") root_name <- paste0("test_new_storate_location_", openssl::sha1(x = as.character(Sys.time()))) root <- tempdir() hash <- openssl::sha1(x = root_name) path <- paste0(hash, ".h5") endpoint <- Sys.getenv("FDP_endpoint") storage_root_url <- new_storage_root(root = root, local = TRUE, endpoint = endpoint) test_that("new entry in storage_location returns API URL", { expect_true(grepl("storage_location", new_storage_location(path = path, hash = hash, public = TRUE, storage_root_url = storage_root_url, endpoint = endpoint))) }) test_that("existing entry in storage_location returns API URL", { expect_true(grepl("storage_location", new_storage_location(path = path, hash = hash, public = TRUE, storage_root_url = storage_root_url, endpoint = endpoint))) })
setPolicyValues <- function(network, ...) { policyValues <- list(...) for (i in names(policyValues)) { network[["nodePolicyValues"]][[i]] <- policyValues[[i]] } network }
"ctenocidaris.nutrix"
createImageSeq <- function (moviepath='Movies', imagepath='ImageSequences', x=1920, y=1080, fps=15, nsec=2, start=NULL, stop=NULL, ext='MTS', libavpath='avconv', exiftoolpath='exiftool', pythonpath='python', verbose=FALSE, logfile=FALSE) { if (is.null(moviepath)) { moviepath = 'NULL' } if (is.null(imagepath)) { imagepath = 'NULL' } if (is.null(x)) { x = 'NULL' } if (is.null(y)) { y = 'NULL' } if (is.null(fps)) { fps = 'NULL' } if (is.null(nsec)) { nsec = 'NULL' } if (is.null(start)) { start = 'NULL' } if (is.null(stop)) { stop = 'NULL' } if (is.null(ext)) { ext = list('NULL') } if (is.null(verbose)) { verbose = 'NULL' } if (is.null(logfile)) { logfile = 'NULL' } system(paste( pythonpath, system.file("python", "createImageSeq.py", package = "trackdem"), "-moviepath", moviepath, "-imagepath", imagepath, "-x", x, "-y", y, "-fps", fps, "-nsec", nsec, "-start", start, "-stop", stop, "-ext", paste(ext, collapse=' '), "-libavpath", libavpath, "-exiftoolpath", exiftoolpath, "-verbose", verbose, "-logfile", logfile )) } loadImages <- function (dirPictures,filenames=NULL,nImages=1:30, xranges=NULL,yranges=NULL) { if (is.null(dirPictures)) { dirPictures <- getwd() } if (is.null(filenames)) { allFiles <- list.files(path=dirPictures) allFiles <- allFiles[nImages] } else {filenames <- filenames[nImages]} im1 <- png::readPNG(file.path(dirPictures,allFiles[1])) if (length(dim(im1)) == 2) { im1 <- array(im1,dim=c(nrow(im1),ncol(im1),1)) } nc <- dim(im1)[3] if (is.null(xranges)) xranges <- 1:dim(im1)[2] if (is.null(yranges)) yranges <- 1:dim(im1)[1] im1 <- im1[yranges,xranges,,drop=FALSE] allFullImages <- structure(vapply(seq_along(nImages), function(x) { im <- png::readPNG(file.path(dirPictures, allFiles[x])) if (length(dim(im)) == 2) im <- array(im,dim=c(nrow(im),ncol(im),1)) im <- im[yranges,xranges,] }, numeric(prod(dim(im1)))), dim=c(dim(im1),length(nImages))) if (dim(allFullImages)[3] == 3) { } else if (dim(allFullImages)[3] == 4) { if (all(allFullImages[,,4,] == 1)) { warning("Color channel 4 (for transparency) is safely ignored as all values equaled 1.") } else { warning("Color channel 4 (for transparency) is ignored. Note that not all values equaled 1.") } allFullImages <- allFullImages[,,1:3,] } else if (dim(allFullImages)[3] == 1) { warning("Only 1 color channel detected (grey scale image).") } else { stop("Wrong number of color channels; only 1 and 3 color layers are supported.") } attr(allFullImages,"settings") <- list(nImages=nImages) attr(allFullImages, "class") <- c('TrDm','colorimage','array') attr(allFullImages, "originalDirec") <- dirPictures return(allFullImages) } createBackground <- function(colorimages,method='mean') { if(!is.TrDm(colorimages)){ stop("Input does not appear to be of the class \"TrDm\"") } if (method == 'mean') { if (dim(colorimages)[3] == 3) { A <- cb(colorimages[,,1,], colorimages[,,2,], colorimages[,,3,], dim(colorimages[,,1,]), array(0,dim=dim(colorimages[,,,1]))) } else if (dim(colorimages)[3] == 1) { A <- cb1(colorimages[,,1,], dim(colorimages[,,1,]), array(0,dim=dim(colorimages[,,,1]))) } } else if (method == 'powerroot') { A <- array(NA,dim=dim(colorimages)[1:3]) for (i in 1:dim(colorimages)[3]) { A[,,i] <- apply(colorimages[,,i,],c(1,2),function(x) mean(x^50)^(1/50)) } } else if (method == 'filter') { if (dim(colorimages)[3] == 3) { rst <- cb(colorimages[,,1,], colorimages[,,2,], colorimages[,,3,], dim(colorimages[,,1,]), array(0,dim=dim(colorimages[,,,1]))) } else if (dim(colorimages)[3] == 1) { rst <- cb1(colorimages[,,1,], dim(colorimages[,,1,]), array(0,dim=dim(colorimages[,,,1]))) } class(rst) <- class(colorimages) subs <- aperm(subtractBackground(bg=rst,colorimages),c(1,2,4,3)) class(subs) <- class(colorimages) attributes(subs) <- attributes(colorimages) if (dim(colorimages)[3] == 3) { SDs <- cb(subs[,,1,]^2, subs[,,2,]^2, subs[,,3,]^2, dim(subs[,,1,]),array(0,dim=dim(colorimages[,,1,]))) * dim(colorimages)[4]/(dim(colorimages)[4]-1) SD <- sqrt(SDs[,,1]^2+SDs[,,2]^2+SDs[,,3]^2) } else if (dim(colorimages)[3] == 1) { SDs <- cb1(subs[,,1,]^2, dim(subs[,,1,]),array(0,dim=dim(colorimages[,,1,]))) * dim(colorimages)[4]/(dim(colorimages)[4]-1) SD <- sqrt(SDs[,,1]^2) } Threshold <- { stats::optimize(function(a,i1){ t1 <- (i1 > a) sum((i1[t1]-mean(i1[t1]))^2)+ sum((i1[!t1]-mean(i1[!t1]))^2) } ,c(0,max(SD)),i1=c(SD))$min } rst[(SD>Threshold)] <- NA A <- array(0,c(dim(colorimages)[1:3])) for (i in 1:dim(colorimages)[3]) { r <- raster::raster(rst[,,i],xmx=ncol(rst),ymx=nrow(rst)) f1 <- raster::focal(r,w=matrix(1,31,31), fun=function(x){ raster::modal(x,na.rm=TRUE) }, NAonly=TRUE) while((!all(is.finite(f1@data@values)))|any(is.na(f1@data@values))) { f1@data@values[!is.finite(f1@data@values)] <- NA f1 <- raster::focal(f1,w=matrix(1,31,31), fun=function(x){ raster::modal(x,na.rm=TRUE) }, NAonly=TRUE,pad=TRUE) } A[,,i] <- matrix(f1[,,1],ncol=ncol(colorimages), nrow=nrow(colorimages),byrow=TRUE) } } else {stop('No valid method for creating background')} class(A) <- c('TrDm','colorimage','array') attr(A,"originalImages") <- deparse(substitute(colorimages)) attr(A,"originalDirec") <- attributes(colorimages)$originalDirec attr(A,"settings") <- c(attributes(colorimages)$settings, list(BgMethod=method)) return(A) } subtractBackground <- function (bg,colorimages=NULL) { if(is.null(colorimages)) { colorimages <- get(attributes(bg)$originalImages, envir=.GlobalEnv) } if(!is.TrDm(bg)) { ch1 <- all(dim(bg)[1:3] == dim(colorimages)[1:3]) ch2 <- length(dim(bg)) %in% 3:4 ch3 <- TRUE if (length(dim(bg)) == 4) ch3 <- dim(bg)[4] == dim(colorimages)[4] if (!all(ch1,ch2,ch3)) { stop(paste("Input does not appear to be of the class \"TrDm\"", "and has wrong dimensions.")) } else { message(paste("Input does not appear to be of the class \"TrDm\" but", "has the correct dimensions and is therefore used.")) } } if (length(dim(bg)) == 3) { sbg <- array(NA,dim=dim(colorimages)) for (i in 1:(dim(colorimages)[3])) { sbg[,,i,] <- sb(colorimages[,,i,], bg[,,i], dim(colorimages[,,i,]), array(0,dim=dim(colorimages))) } } else if (length(dim(bg)) == 4) { sbg <- array(NA,dim=dim(colorimages)) for (i in 1:(dim(colorimages)[3])) { sbg[,,i,] <- sb2(colorimages[,,i,], bg[,,i,], dim(colorimages[,,i,]), array(0,dim=dim(colorimages))) } } else {stop("Wrong dimensions for background image.")} attr(sbg,"background") <- deparse(substitute(bg)) attr(sbg,"originalImages") <- attributes(bg)$originalImages attr(sbg,"originalDirec") <- attributes(bg)$originalDirec attr(sbg,"settings") <- attributes(bg)$settings class(sbg) <- c('TrDm','sbg','array') return(sbg) } identifyParticles <- function (sbg,threshold=-0.1,pixelRange=NULL, qthreshold=NULL,select='dark', colorimages=NULL,autoThres=FALSE, perFrame=FALSE,frames=NULL) { if(!is.TrDm(sbg)){ stop("Input does not appear to be of the class \"TrDm\"") } if(is.null(colorimages)) { colorimages <- get(attributes(sbg)$originalImages, envir=.GlobalEnv) } namesbg <- deparse(substitute(sbg)) tmp <- attributes(sbg) sbg <- aperm(sbg, c(1,2,4,3)) attributes(sbg)$background <- tmp$background attributes(sbg)$originalImages <- tmp$originalImages attributes(sbg)$originalDirec <- tmp$originalDirec attributes(sbg)$settings <- tmp$settings cat("\t Particle Identification: ") n <- 1:dim(sbg)[3] nc <- dim(sbg)[4] cat("\r \t Particle Identification: Thresholding (1 of 5) ", " ") if (length(threshold) == 1) {threshold <- rep(threshold,nc)} if (autoThres) { cat("\r \t Particle Identification: Automated thresholding (1 of 5) ", " ") if (is.null(frames)) { frames <- n } threshold <- calcAutoThres(sbg[,,frames,,drop=FALSE],perFrame=perFrame) } if (!is.null(qthreshold)) { A <- array(NA,dim=dim(sbg)) for (i in 1:nc) { A[,,,i] <- structure(vapply(seq_len(dim(sbg)[3]), function(x) sbg[,,x,i] < stats::quantile(sbg[,,x,i],qthreshold), numeric(prod(dim(sbg[,,1,1])))),dim=dim(sbg)[1:3]) } } else { if (select == 'dark') { A <- structure(vapply(seq_along(threshold), function(x) sbg[,,,x] < threshold[x], numeric(prod(dim(sbg[,,,1])))), dim=dim(sbg)) } else if (select == 'light') { A <- structure(vapply(seq_along(threshold), function(x) sbg[,,,x] > threshold[x], numeric(prod(dim(sbg[,,,1])))), dim=dim(sbg)) } else if (select == 'both') { A <- structure(vapply(seq_along(threshold), function(x) sbg[,,,x] > threshold[x] | sbg[,,,x] < -threshold[x], numeric(prod(dim(sbg[,,,1])))), dim=dim(sbg)) } else {stop("Invalid selection, choose 'dark', 'light' or 'both' ")} } sumRGB <- apply(A,c(2,3),rowSums) sumRGB <- sumRGB > 0 cat("\r \t Particle Identification: Labeling (2 out of 5) ", " ") A <- array(NA,dim=dim(sumRGB)) for (i in n) { A[,,i] <- .Call('ccl',sumRGB[,,i],PACKAGE='trackdem') } cat("\r \t Particle Identification: Size filtering (3 out of 5) ", " ") if (!is.null(pixelRange)) { for (i in n) { allLabels <- tabulate(as.vector(A[,,i]),nbins=max(A[,,i])) allLabels <- allLabels[allLabels > 0] names(allLabels) <- sort(unique(as.numeric(A[,,i])))[-1] inc <- allLabels >= pixelRange[1] & allLabels <= pixelRange[2] A[,,i] [!A[,,i] %in% names(inc[inc==TRUE])] <- 0 } } cat("\r \t Particle Identification: Particle statistics (4 out of 5) ", " ") dA <- dim(A[,,1]) totalPart <- apply(A,3,function(x) length(unique(c(x)))-1) if (all(totalPart == 0)) { cat("\n") stop(c("\n \t No particle detected in any of the frames. ", "Try different thresholds? \n")) } if (any(totalPart == 0)) { warning(c("\n \t No particle detected in at least one of the frames. You will run into problems with particle tracking. Try different thresholds? \n")) } shape.index <- function(a,p) { n <- trunc(sqrt(a)) m <- a - n^2 minp <- rep(0,length(m)) for (ii in 1:length(m)){ if (m[ii]==0) minp[ii] <- 4*n[ii] if (n[ii]^2<a[ii] & a[ii]<=n[ii]*(1+n[ii])) minp[ii] <- 4 * n[ii] + 2 if (a[ii] > n[ii]*(1+n[ii])) minp[ii] <- 4 * n[ii] + 4 } return(p/minp) } particleStats <- matrix(NA,nrow=sum(totalPart),ncol=15) colnames(particleStats) <- c('patchID','n.cell','n.core.cell', 'n.edges.perimeter', 'n.edges.internal','perim.area.ratio', 'shape.index', 'frac.dim.index','core.area.index', paste0('mu',c('R','G','B')),'x','y','frame') for (i in n) { if (totalPart[i] > 0) { if (i == 1) loc <- 1:totalPart[i] if (i > 1) { cum <- sum(totalPart[1:(i-1)])+1 loc <- cum:(cum+totalPart[i]-1) } IDs <- sort(as.numeric(stats::na.omit(unique(c(A[,,i])))))[-1] particleStats[loc,1:5] <- .Call('projectedPS',A[,,i],IDs, PACKAGE='trackdem') particleStats[loc,paste0('mu',c('R','G','B'))] <- as.matrix(extractMean( particleStats[loc,'patchID'], colorimages=colorimages[,,,i], images=A[,,i],ncolors=nc)) coords <- getCoords(m=A[,,i],d=dA) ind <- A[,,i] > 0 particleStats[loc,'x'] <- tapply(coords[,2],A[,,i][ind],mean) particleStats[loc,'y'] <- tapply(coords[,1],A[,,i][ind],mean) particleStats[loc,'frame'] <- i } } particleStats[,'perim.area.ratio'] <- particleStats[,'n.edges.perimeter'] / particleStats[,'n.cell'] particleStats[,'shape.index'] <- shape.index(particleStats[,'n.cell'], particleStats[,'n.edges.perimeter']) particleStats[,'frac.dim.index'] <- (2 * log(0.25 * particleStats[,'n.edges.perimeter'])) / log(particleStats[,'n.cell']) particleStats[,'core.area.index'] <- particleStats[,'n.core.cell'] / particleStats[,'n.cell'] particleStats <- as.data.frame(particleStats) cat("\r \t Particle Identification: Finalizing (5 out of 5) ", " \n ") attr(particleStats,"images") <- A attr(particleStats, "class") <- c("TrDm","particles","data.frame") attr(particleStats,"threshold") <- threshold attr(particleStats,"background") <- attributes(sbg)$background attr(particleStats,"originalImages") <- attributes(sbg)$originalImages attr(particleStats,"originalDirec") <- attributes(sbg)$originalDirec attr(particleStats,"subtractedImages") <- namesbg attr(particleStats,"settings") <- c(attributes(sbg)$settings, list(threshold=threshold, pixelRange=pixelRange, qthreshold=qthreshold, select=select, autoThres=autoThres, perFrame=perFrame, frames=frames)) attr(particleStats,"nn") <- FALSE return(particleStats) } calcAutoThres <- function(sbg,perFrame=FALSE){ ncolours <- dim(sbg)[4] nframes <- dim(sbg)[3] f <- function(a){ t1 <- (i1 > a) sum((i1[t1]-mean(i1[t1]))^2) + sum((i1[!t1]-mean(i1[!t1]))^2) } if (perFrame) { pp <- array(0,c(nframes,ncolours)) for (j in 1:nframes) { for (i in 1:ncolours) { i1 <- c(sbg[,,j,i]) pp[j,i] <- stats::optimize(function(a) { t1 <- (i1 > a) + 1 sum((i1[t1==1]-mean(i1[t1==1]))^2) + sum((i1[t1==2]-mean(i1[t1==2]))^2) }, range(i1))$min } } } else { pp <- numeric(ncolours) for (i in 1:ncolours) { i1 <- c(sbg[,,,i]) pp[i] <- stats::optimize(f,range(i1))$min } } return(pp) } findThreshold <- function (images,frame=1,colorimages=NULL) { if(is.null(colorimages)) { colorimages <- get(attributes(images)$originalImages, envir=.GlobalEnv) } thr <- runThreshold(frame,images,colorimages) return(thr) } runThreshold <- function(frame,images,colorimages,ui,server) { shiny::runApp( list(ui=shiny::fluidPage( shiny::titlePanel(paste0("Find threshold for particle detection")), shiny::fluidRow( shiny::column(3, 'The graph on the right shows the original image that can be used to zoom, by drawing a polygon. Bottom graphs show the original image (left) and a binary image (right) in which all particles are either labeled as zero (white), or as one (black). Set whether particles are light or dark compared to the background. Use the slider to find the best threshold, that results in all focal particles being labeled as one, and all background pixels labeld as zero. When finished, click on "Done".', align='left',offset=0), shiny::column(2, shiny::actionButton("stop", "Done"), shiny::br(),shiny::br(), shiny::radioButtons("select", shiny::h5("Select:"), choices = list("Dark particles" = 1, "Light particles" = 2, "Both" = 3),selected = 1), shiny::radioButtons("ch", shiny::h5("Color channel:"), choices = list("Red" = 1, "Green" = 2, "Blue" = 3),selected = 1)), shiny::column(5, shiny::h5('Choose region of interest to zoom (slower for larger images).'), shiny::plotOutput("plot3",brush = shiny::brushOpts(id="plot3_brush", resetOnNew = TRUE,clip=TRUE))) ), shiny::hr(), shiny::fluidRow( shiny::column(12,shiny::sliderInput("obs", "Threshold:", min=-0.3,max=0.3,value=0,step=0.005,width='1000px', )) ), shiny::fluidRow( shiny::column(6, shiny::plotOutput("plot2")), shiny::column(6 ,shiny::plotOutput("plot1")) ) ), server=function(input, output) { ranges <- shiny::reactiveValues(x=NULL,y=NULL) coords <- shiny::reactiveValues(x=NULL,y=NULL) output$plot3 <- shiny::renderPlot(suppressWarnings(graphics::plot(colorimages,frame=frame))) shiny::observe({ brush <- input$plot3_brush if (!is.null(brush)) { ranges$x <- floor(c(brush$xmin, brush$xmax) * ncol(colorimages)) ranges$y <- nrow(colorimages) - floor(c(brush$ymin, brush$ymax) * nrow(colorimages)) } else { ranges$x <- c(1,ncol(colorimages)) ranges$y <- c(nrow(colorimages),1) } coords$x <- ranges$x / ncol(colorimages) coords$y <- 1 - (ranges$y / nrow(colorimages)) }) output$plot2 <- shiny::renderPlot({ im <- colorimages[c(min(ranges$y):max(ranges$y)), c(min(ranges$x):max(ranges$x)),,frame,drop=FALSE] im <- array(im,dim=c(dim(im)[1:3])) im <- raster::brick(im) suppressWarnings(raster::plotRGB(im,scale=1,asp=nrow(im)/ncol(im))) }) shiny::observe({ if (input$select == 1) { if (input$ch == 1) { m <- t(apply(images[,,1,frame] < input$obs,2,rev)) } if (input$ch == 2) { m <- t(apply(images[,,2,frame] < input$obs,2,rev)) } if (input$ch == 3) { m <- t(apply(images[,,3,frame] < input$obs,2,rev)) } } else if (input$select == 2) { if (input$ch == 1) { m <- t(apply(images[,,1,frame] > input$obs,2,rev)) } if (input$ch == 2) { m <- t(apply(images[,,2,frame] > input$obs,2,rev)) } if (input$ch == 3) { m <- t(apply(images[,,3,frame] > input$obs,2,rev)) } } else if (input$select == 3) { if (input$ch == 1) { m <- t(apply((images[,,1,frame] > input$obs) | (images[,,1,frame] < -input$obs),2,rev)) } if (input$ch == 2) { m <- t(apply((images[,,2,frame] > input$obs) | (images[,,2,frame] < -input$obs),2,rev)) } if (input$ch == 3) { m <- t(apply((images[,,3,frame] > input$obs) | (images[,,3,frame] < -input$obs),2,rev)) } } output$plot1 <- shiny::renderPlot(graphics::image(m, xlab='',ylab='',xaxt='n',yaxt='n', col=c('white','black'), xlim=coords$x, ylim=coords$y)) }) shiny::observeEvent(input$stop, shiny::stopApp({ input$obs })) } )) } findPixelRange <- function (colorimages,frame=1) { invisible(runPixelRange(frame,colorimages)) } runPixelRange <- function(frame,colorimages,ui,server) { shiny::runApp( list(ui=shiny::fluidPage( shiny::titlePanel(paste0("Find particle size range for particle detection")), shiny::fluidRow( shiny::column(3, 'The graph on the right shows the original image that can be used to zoom, by drawing a polygon. Bottom graph shows the zoomed image. Draw a polygon on this image and see its size in pixels. By drawing polygons over both the smallest and largest particles of interest, an appropriate range can be found. When finished, click on "Done".', align='left',offset=0), shiny::column(2, shiny::actionButton("stop", "Done"), shiny::br(),shiny::br()), shiny::column(5, shiny::h5('Choose region of interest to zoom (slower for larger images).'), shiny::plotOutput("plot3",brush = shiny::brushOpts(id="plot3_brush", resetOnNew = TRUE,clip=TRUE))) ), shiny::hr(), shiny::fluidRow( shiny::column(6, shiny::h3('Zoomed image'), shiny::plotOutput("plot2",brush = shiny::brushOpts(id="plot2_brush", resetOnNew = TRUE,clip=TRUE))), shiny::column(6, shiny::verbatimTextOutput("info")) ) ), server=function(input, output) { ranges <- shiny::reactiveValues(x=NULL,y=NULL) coords <- shiny::reactiveValues(x=NULL,y=NULL) output$plot3 <- shiny::renderPlot(suppressWarnings(graphics::plot(colorimages,frame=frame))) shiny::observe({ brush <- input$plot3_brush if (!is.null(brush)) { ranges$x <- floor(c(brush$xmin, brush$xmax) * ncol(colorimages)) ranges$y <- nrow(colorimages) - floor(c(brush$ymin, brush$ymax) * nrow(colorimages)) } else { ranges$x <- c(1,ncol(colorimages)) ranges$y <- c(nrow(colorimages),1) } coords$x <- ranges$x / ncol(colorimages) coords$y <- 1 - (ranges$y / nrow(colorimages)) }) output$plot2 <- shiny::renderPlot({ im <- colorimages[c(min(ranges$y):max(ranges$y)), c(min(ranges$x):max(ranges$x)),,frame,drop=FALSE] im <- array(im,dim=c(dim(im)[1:3])) im <- raster::brick(im) suppressWarnings(raster::plotRGB(im,scale=1,asp=nrow(im)/ncol(im))) }) output$info <- shiny::renderText({ x <- abs(diff(ranges$x)) * abs(input$plot2_brush$xmin-input$plot2_brush$xmax) y <- abs(diff(ranges$y)) * abs(input$plot2_brush$ymin-input$plot2_brush$ymax) paste0("Area: \n", round(x), ' by ',round(y),' = ',round(y*x),' pixels.') }) shiny::observeEvent(input$stop, shiny::stopApp({ })) } )) }
DAISIE_sim_core_constant_rate <- function( time, mainland_n, pars, nonoceanic_pars, hyper_pars, area_pars ) { timeval <- 0 totaltime <- time testit::assert(length(pars) == 5 || length(pars) == 10) testit::assert(is.null(area_pars) || are_area_pars(area_pars)) if (pars[4] == 0 && nonoceanic_pars[1] == 0) { stop("Island has no species and the rate of colonisation is zero. Island cannot be colonised.") } nonoceanic_sample <- DAISIE_nonoceanic_spec( prob_samp = nonoceanic_pars[1], prob_nonend = nonoceanic_pars[2], mainland_n = mainland_n) maxspecID <- mainland_n island_spec <- c() stt_table <- matrix(ncol = 4) colnames(stt_table) <- c("Time", "nI", "nA", "nC") spec_tables <- DAISIE_spec_tables(stt_table, totaltime, timeval, nonoceanic_sample, island_spec) stt_table <- spec_tables$stt_table mainland_spec <- spec_tables$mainland_spec island_spec <- spec_tables$island_spec lac <- pars[1] mu <- pars[2] K <- pars[3] gam <- pars[4] laa <- pars[5] num_spec <- length(island_spec[, 1]) num_immigrants <- length(which(island_spec[, 4] == "I")) while (timeval < totaltime) { rates <- update_rates( timeval = timeval, totaltime = totaltime, gam = gam, laa = laa, lac = lac, mu = mu, hyper_pars = hyper_pars, area_pars = area_pars, K = K, num_spec = num_spec, num_immigrants = num_immigrants, mainland_n = mainland_n, extcutoff = NULL, island_ontogeny = 0, sea_level = 0 ) testit::assert(are_rates(rates)) timeval_and_dt <- calc_next_timeval( max_rates = rates, timeval = timeval ) timeval <- timeval_and_dt$timeval if (timeval <= totaltime) { rates <- update_rates( timeval = timeval, totaltime = totaltime, gam = gam, laa = laa, lac = lac, mu = mu, hyper_pars = hyper_pars, area_pars = area_pars, K = K, num_spec = num_spec, num_immigrants = num_immigrants, mainland_n = mainland_n, extcutoff = NULL, island_ontogeny = 0, sea_level = 0 ) testit::assert(are_rates(rates)) possible_event <- DAISIE_sample_event_constant_rate( rates = rates ) updated_state <- DAISIE_sim_update_state_constant_rate( timeval = timeval, totaltime = totaltime, possible_event = possible_event, maxspecID = maxspecID, mainland_spec = mainland_spec, island_spec = island_spec, stt_table = stt_table ) island_spec <- updated_state$island_spec maxspecID <- updated_state$maxspecID stt_table <- updated_state$stt_table num_spec <- length(island_spec[, 1]) num_immigrants <- length(which(island_spec[, 4] == "I")) } } stt_table <- rbind( stt_table, c( 0, stt_table[nrow(stt_table), 2], stt_table[nrow(stt_table), 3], stt_table[nrow(stt_table), 4] ) ) island <- DAISIE_create_island( stt_table = stt_table, totaltime = totaltime, island_spec = island_spec, mainland_n = mainland_n) ordered_stt_times <- sort(island$stt_table[, 1], decreasing = TRUE) testit::assert(all(ordered_stt_times == island$stt_table[, 1])) return(island) }
library(renz) context("Linearized integrated MM equation") test_that('int.MM() works properly', { a <-int.MM(data = sE.progress(So = 10, time = 5, Km = 4, Vm = 50)[, c(1,3)]) expect_is(a, 'list') expect_equal(length(a), 2) expect_equivalent(a$parameters[1], 3.686) expect_equivalent(a$parameters[2], 48.303) expect_is(a$data, 'data.frame') expect_equal(dim(a$data), c(15,4)) })
library(testthat) library(rgeos) setScale() context("Translate Points") test_that("translate points", { p = readWKT("POINT(1 1)") mp = readWKT("MULTIPOINT(1 1, 2 2, 3 3, 4 4, 5 5)") gcp1 = readWKT("GEOMETRYCOLLECTION( POINT(1 1), POINT(2 2), POINT(3 3), POINT(4 4), POINT(5 5))") gcp2 = readWKT("GEOMETRYCOLLECTION( POINT(1 1), POINT(2 2), MULTIPOINT(3 3, 4 4, 5 5))") gcp3 = readWKT("GEOMETRYCOLLECTION( POINT(1 1), POINT(2 2), MULTIPOINT(3 3, 4 4),POINT(5 5))") gcp4 = readWKT("GEOMETRYCOLLECTION( MULTIPOINT(1 1, 2 2), MULTIPOINT(3 3, 4 4, 5 5))") gcp5 = readWKT("GEOMETRYCOLLECTION( MULTIPOINT(1 1, 2 2), MULTIPOINT(3 3, 4 4),POINT(5 5))") spp = SpatialPoints(list(x=1,y=1)) spmp = SpatialPoints(list(x=1:5,y=1:5)) rownames(spp@coords) = c("1") expect_that( identical(p,spp), is_true()) expect_that( identical(spp, translate(spp)), is_true()) rownames(spmp@coords) = c("1","1","1","1","1") expect_that( identical(mp,spmp), is_true() ) expect_that( identical(spmp,translate(spmp)), is_true()) rownames(spmp@coords) = c("1","2","3","4","5") expect_that( identical(gcp1,spmp), is_true() ) expect_that( identical(spmp,translate(spmp)), is_true()) rownames(spmp@coords) = c("1","2","3","3","3") expect_that( identical(gcp2,spmp), is_true() ) expect_that( identical(spmp,translate(spmp)), is_true()) rownames(spmp@coords) = c("1","2","3","3","4") expect_that( identical(gcp3,spmp), is_true() ) expect_that( identical(spmp,translate(spmp)), is_true()) rownames(spmp@coords) = c("1","1","2","2","2") expect_that( identical(gcp4,spmp), is_true() ) expect_that( identical(spmp,translate(spmp)), is_true()) rownames(spmp@coords) = c("1","1","2","2","3") expect_that( identical(gcp5,spmp), is_true() ) expect_that( identical(spmp,translate(spmp)), is_true()) expect_that( identical(p, translate(p) ), is_true()) expect_that( identical(mp, translate(mp) ), is_true()) expect_that( identical(gcp1, translate(gcp1) ), is_true()) expect_that( identical(gcp2, translate(gcp2) ), is_true()) expect_that( identical(gcp3, translate(gcp3) ), is_true()) expect_that( identical(gcp4, translate(gcp4) ), is_true()) expect_that( identical(gcp5, translate(gcp5) ), is_true()) })
NULL modify_header <- function(x, update = NULL, ..., text_interpret = c("md", "html"), quiet = NULL, stat_by = NULL) { updated_call_list <- c(x$call_list, list(modify_header = match.call())) quiet <- quiet %||% get_theme_element("pkgwide-lgl:quiet") %||% FALSE text_interpret <- match.arg(text_interpret) if (!is.null(stat_by)) { lifecycle::deprecate_warn( "1.3.6", "gtsummary::modify_header(stat_by=)", details = glue("Use `all_stat_cols(FALSE) ~ {stat_by}` instead.")) lst_stat_by <- list(rlang::new_formula(lhs = expr(all_stat_cols(FALSE)), rhs = stat_by)) if (is.null(update) || rlang::is_list(update)) { update <- c(lst_stat_by, update) } else if (!rlang::is_list(update)) { update <- c(lst_stat_by, list(update)) } } update <- .combine_update_and_dots(x, update, ...) if (is.null(update) && identical(quiet, FALSE)) .modify_no_selected_vars(x) if (is.null(update)) { return(x) } df_info_tibble <- .info_tibble(x) update <- update %>% imap( ~ expr(ifelse(!is.na(!!.x), glue(!!.x), NA_character_)) %>% eval_tidy( data = df_info_tibble %>% filter(column %in% .y) %>% as.list() %>% discard(is.na) ) ) x <- modify_table_styling( x, columns = names(update), label = unlist(update), text_interpret = as.character(text_interpret), hide = FALSE ) x$call_list <- updated_call_list x } modify_footnote <- function(x, update = NULL, ..., abbreviation = FALSE, text_interpret = c("md", "html"), quiet = NULL) { updated_call_list <- c(x$call_list, list(modify_footnote = match.call())) if (!inherits(x, "gtsummary")) { stop("Argument `x=` must be an object with 'gtsummary' class", call. = FALSE) } quiet <- quiet %||% get_theme_element("pkgwide-lgl:quiet") %||% FALSE x <- .update_table_styling(x) update <- .combine_update_and_dots(x, {update}, ...) if (identical(quiet, FALSE) && rlang::is_empty(update)) .modify_no_selected_vars(x) if (is.null(update)) { return(x) } footnote_column_name <- ifelse(abbreviation == TRUE, "footnote_abbrev", "footnote") df_info_tibble <- .info_tibble(x) update <- update %>% imap( ~ expr(ifelse(!is.na(!!.x), glue(!!.x), NA_character_)) %>% eval_tidy( data = df_info_tibble %>% filter(column %in% .y) %>% as.list() %>% discard(is.na) ) ) if (abbreviation == FALSE) { x <- modify_table_styling( x, columns = names(update), footnote = unlist(update), text_interpret = text_interpret ) } else if (abbreviation == TRUE) { x <- modify_table_styling( x, columns = names(update), footnote_abbrev = unlist(update), text_interpret = text_interpret ) } x$call_list <- updated_call_list x } modify_spanning_header <- function(x, update = NULL, ..., text_interpret = c("md", "html"), quiet = NULL) { updated_call_list <- c(x$call_list, list(modify_spanning_header = match.call())) if (!inherits(x, "gtsummary")) { stop("Argument `x=` must be an object with 'gtsummary' class", call. = FALSE) } quiet <- quiet %||% get_theme_element("pkgwide-lgl:quiet") %||% FALSE x <- .update_table_styling(x) update <- .combine_update_and_dots(x, {update}, ...) if (identical(quiet, FALSE) && rlang::is_empty(update)) .modify_no_selected_vars(x) if (is.null(update)) { return(x) } df_info_tibble <- .info_tibble(x) update <- update %>% imap( ~ expr(ifelse(!is.na(!!.x), glue(!!.x), NA_character_)) %>% eval_tidy( data = df_info_tibble %>% filter(column %in% .y) %>% as.list() %>% discard(is.na) ) ) x <- modify_table_styling( x, columns = names(update), spanning_header = unlist(update), text_interpret = text_interpret ) x$call_list <- updated_call_list x } modify_caption <- function(x, caption, text_interpret = c("md", "html")) { if (!inherits(x, "gtsummary")) abort("`x=` must be class 'gtsummary'.") if (!rlang::is_string(caption)) abort("`caption=` must be a string.") text_interpret <- match.arg(text_interpret) updated_call_list <- c(x$call_list, list(modify_caption = match.call())) caption <- .info_tibble(x) %>% filter(.data$column == "label") %>% with(glue(caption)) %>% as.character() x$table_styling$caption <- caption attr(x$table_styling$caption, "text_interpret") <- text_interpret x$call_list <- updated_call_list x } show_header_names <- function(x = NULL, include_example = TRUE, quiet = NULL) { quiet <- quiet %||% get_theme_element("pkgwide-lgl:quiet") %||% FALSE if (!inherits(x, "gtsummary")) { stop("Pass a 'gtsummary' object in `x=` to print current column names and headers.") } df_cols <- x$table_styling$header %>% filter(.data$hide == FALSE) %>% select(.data$column, .data$label) if (identical(quiet, FALSE) && isTRUE(include_example)) { cat("\n") cli_alert_info("As a usage guide, the code below re-creates the current column headers.") block <- mutate(df_cols, formula = glue(" {column} = {shQuote(label)}")) %>% pull(.data$formula) %>% paste0("", collapse = ",\n") %>% { glue("modify_header(\n{.}\n)") } cli_code(block) } if (identical(quiet, FALSE)) { knitr::kable(df_cols, col.names = c("Column Name", "Column Header"), format = "pandoc") %>% print() } return(invisible(df_cols)) } .modify_no_selected_vars <- function(x) { paste( "No columns were selected.", "Use {.code quiet = TRUE} to supress these messages." ) %>% stringr::str_wrap() %>% cli_alert_info() show_header_names(x) } .info_tibble <- function(x) { if (inherits(x, c("tbl_summary", "tbl_svysummary")) && is.null(x$df_by)) { return( x$meta_data %>% dplyr::slice(1) %>% pluck("df_stats", 1) %>% select(any_of(c("N_obs", "N_unweighted"))) %>% dplyr::slice(1) %>% dplyr::rename(N = .data$N_obs) %>% full_join( select(x$table_styling$header, .data$column), by = character() ) ) } if (inherits(x, c("tbl_summary", "tbl_svysummary", "tbl_continuous")) && !is.null(x$df_by)) { return( x$table_styling$header %>% select(.data$column) %>% full_join( x$df_by %>% select(any_of(c("N", "N_unweighted"))) %>% distinct(), by = character() ) %>% left_join( x$df_by %>% select( column = .data$by_col, level = .data$by_chr, any_of(c("n", "p", "n_unweighted", "p_unweighted")) ), by = "column" ) ) } df_new_cols <- x[names(x) %in% c("N", "N_event", "n")] %>% tibble::as_tibble() if (ncol(df_new_cols) == 0) { return(x$table_styling$header %>% select(.data$column)) } if (!"n" %in% names(df_new_cols) && "N" %in% names(df_new_cols)) { df_new_cols <- mutate(df_new_cols, n = .data$N) } x$table_styling$header %>% select(.data$column) %>% bind_cols(df_new_cols) } .combine_update_and_dots <- function(x, update, ...) { dots <- rlang::dots_list(...) if (!is.null(update) && !rlang::is_list(update)) { update <- list(update) } .formula_list_to_named_list( x = c(update, dots), var_info = x$table_styling$header$column, arg_name = "... or update", type_check = chuck(type_check, "is_string_or_na", "fn"), type_check_msg = chuck(type_check, "is_string_or_na", "msg") ) }
fredr_source_releases <- function(source_id, ..., limit = NULL, offset = NULL, order_by = NULL, sort_order = NULL, realtime_start = NULL, realtime_end = NULL) { check_dots_empty(...) check_not_null(source_id, "source_id") user_args <- capture_args( realtime_start = realtime_start, realtime_end = realtime_end, source_id = source_id, limit = limit, offset = offset, order_by = order_by, sort_order = sort_order ) fredr_args <- list( endpoint = "source/releases" ) do.call(fredr_request, c(fredr_args, user_args)) }
expected <- eval(parse(text="-34.9710571817686")); test(id=0, code={ argv <- eval(parse(text="list(structure(c(-3.02896519757699, -2.37177231827064, -2.49295252901048, -2.99672420295655, -2.59773735414265, -2.26026537208028, -2.74080517809177, -3.785668787425, -2.80120311135215, -2.57773983108655, -5.06092522358575, -2.25629807618983), .Names = c(\"1\", \"3\", \"5\", \"7\", \"9\", \"11\", \"13\", \"15\", \"17\", \"19\", \"21\", \"23\")))")); do.call(`sum`, argv); }, o=expected);
oxcalSumSim <- function(timeframe_begin, timeframe_end, n, stds, date_distribution = c("equidist", "uniform")) { if (!(length(stds) %in% c(1, n))) { stop("Please give either one stds for all dates or a vector of stds of n length.") } date_distribution <- match.arg(date_distribution) if (date_distribution == "equidist") { cal_dates <- seq(timeframe_begin, timeframe_end, by = ( (timeframe_end - timeframe_begin) / n) ) } else { date_range <- seq(timeframe_begin, timeframe_end) cal_dates <- sample(date_range, n, replace = T) } script <- oxcal_Sum(R_Simulate(cal_dates, stds)) result_file <- executeOxcalScript(script) result <- readOxcalOutput(result_file) cleanupOxcalFiles(result_file) RVAL <- parseOxcalOutput(result,first=TRUE,only.R_Date=FALSE)[[1]] RVAL }
summary.nplr <- function(object, ...){ pars <- unlist(getPar(object)) pars[-1] <- format(pars[-1], digits = 6, scientific = TRUE) goodness <- getGoodness(object) gof <- format(goodness$gof, digits = 6, scientific = TRUE) wgof <- format(goodness$wgof, digits = 6, scientific = TRUE) errors <- t(getStdErr(object)) auc <- format(getAUC(object), digits = 6) infl <- as.numeric(getInflexion(object)) inflpt <- cbind.data.frame( xInfl = format(infl[1], digits = 6), yInfl = format(infl[2], digits = 6) ) estim <- getEstimates(object, .5) interv <- sprintf("[%s | %s]", format(estim$x.025, digits = 6, scientific = TRUE), format(estim$x.975, digits = 6, scientific = TRUE) ) ic50 <- format(estim$x, digits = 6, scientific = TRUE) IC50 <- cbind(IC50 = ic50, "[95%]" = interv) nplrVersion <- as.character(packageVersion("nplr")) nplrDate <- as.character(packageDescription("nplr")["Date"]) Rversion <- as.character(version["version.string"]) out <- cbind.data.frame(t(pars), GOF = gof, weightedGOF = wgof, errors, auc, inflpt, "Log10(IC50)" = log10(estim$x), IC50, "date (Y-m-d)" = format(Sys.Date(), "%Y-%m-%d"), "nplr version" = sprintf("%s (%s)",nplrVersion, nplrDate), "R version" = gsub("R version ", "", Rversion) ) out <- data.frame(summary = t(out)) colnames(out) <- 'value' print(out) }
"getLightDiff" <- function(theta, x, kinscal, kmat, jvec,fixedkmat=FALSE, kinscalspecial = list(), kinscalspecialspec = list(), lightregimespec = list()) { depkIn <- lightregimespec$depkIn br <- lightregimespec$lightBreaks br <- append(br, tail(x,1) ) inten <- lightregimespec$intensity depkin <- as.logical(depkIn) dimk <- ncol(kmat) theta1 <- theta theta1[which(depkin)] <- 0 K1 <- fillK(theta1, kinscal, kmat, fixedkmat, kinscalspecial, kinscalspecialspec,nocolsums=TRUE) eigenlijk1 <- eigen(K1, only.values = F) V1 <- eigenlijk1$vectors gamma1 <- solve(V1) k1 <- -eigenlijk1$values cat("eigen dark", k1, "\n") theta2 <- theta theta2[which(depkin)] <- theta[which(depkin)] * inten K2 <- fillK(theta2, kinscal, kmat, fixedkmat, kinscalspecial, kinscalspecialspec, nocolsums=TRUE) eigenlijk2 <- eigen(K2, only.values = F) V2 <- eigenlijk2$vectors gamma2 <- solve(V2) k2 <- -eigenlijk2$values cat("eigen light", k2, "\n") A <- matrix(nrow = dimk, ncol = dimk) break2 <- 0 for(i in 1:(length(br))) { break1 <- break2 + 1 break2 <- which(x >= br[i])[1] if(is.na(break2)) break2 <- length(x) if(break1 > break2) break if(break2 < length(x)) break2 <- break2 - 1 cat("times are from", break1, "to", break2,"\n") xtemp <- x[break1:break2] if(i %% 2 != 0) { k <- k1 V <- V1 gamma <- gamma1 } else { k <- k2 V <- V2 gamma <- gamma2 } if(i > 1) { finalcon <- c.tempA[nrow(c.tempA),] } else finalcon <- jvec finalcon <- finalcon/max(finalcon) cat("finalcon", finalcon, "\n") gamma <- gamma %*% finalcon for(j in 1:dimk) A[j, ] <- V[ ,j] * gamma[j] c.temp <- calcC(k, xtemp) c.temp <- c.temp %*% A if(i == 1) c.tempA <- c.temp else c.tempA <- rbind(c.tempA, c.temp) } c.tempA }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) run_bg = function(expr) { args = c("--vanilla", "-q") expr_c = deparse(substitute(expr)) expr_c = paste(expr_c, collapse = "\n") pid = sys::r_background(c(args, "-e", expr_c), std_out = TRUE, std_err = TRUE) return(pid) } library(RestRserve) app = Application$new() calc_fib = function(n) { if (n < 0L) stop("n should be >= 0") if (n == 0L) return(0L) if (n == 1L || n == 2L) return(1L) x = rep(1L, n) for (i in 3L:n) { x[[i]] = x[[i - 1]] + x[[i - 2]] } return(x[[n]]) } fib_handler = function(.req, .res) { n = as.integer(.req$parameters_query[["n"]]) if (length(n) == 0L || is.na(n)) { raise(HTTPError$bad_request()) } .res$set_body(as.character(calc_fib(n))) .res$set_content_type("text/plain") } app$add_get(path = "/fib", FUN = fib_handler) request = Request$new(path = "/fib", parameters_query = list(n = 10)) response = app$process_request(request) cat("Response status:", response$status) cat("Response body:", response$body) yaml_file = system.file("examples", "openapi", "openapi.yaml", package = "RestRserve") app$add_openapi(path = "/openapi.yaml", file_path = yaml_file) app$add_swagger_ui(path = "/doc", path_openapi = "/openapi.yaml", use_cdn = TRUE)
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(metapower) my_power <- mpower(effect_size = .2, study_size = 20, k = 10, i2 = .50, es_type = "d") print(my_power) plot_mpower(my_power) str(my_power$power_range) (my_homogen_power <- homogen_power(effect_size = .25, study_size = 20, k = 30,i2 = .50, es_type = "d")) plot_homogen_power(my_homogen_power) my_subgroup_power <- subgroup_power(n_groups = 2, effect_sizes = c(.2,.5), study_size = 20, k = 30, i2 = .5, es_type = "d") print(my_subgroup_power) plot_subgroup_power(my_subgroup_power)
profkern<-function(dendat,h,N,Q,cvol=TRUE,ccen=TRUE,cfre=FALSE,kernel="epane", compoinfo=FALSE,trunc=3,threshold=0.0000001,sorsa="crc",hw=NULL) { if (kernel=="gauss") h<-h*trunc hnum<-length(h) hrun<-1 while (hrun<=hnum){ hcur<-h[hrun] if (sorsa=="crc") curtree<-profkernCRC(dendat,hcur,N,Q,kernel=kernel,compoinfo=compoinfo, trunc=trunc,threshold=threshold,hw=hw) else curtree<-profkernC(dendat,hcur,N,Q) if (hrun==1){ if (hnum==1){ treelist<-curtree } else{ treelist=list(curtree) } } else{ treelist=c(treelist,list(curtree)) } hrun<-hrun+1 } return(treelist) }
est.net = function(Y, lambda, nruns = 50, rank = "optimal", algtype = "brunet", changepoints = NULL) { Y = as.matrix(Y) if (rank == "optimal"){ n.rank = opt.rank(Y, nruns, algtype) } else { n.rank = rank print(paste("User defined rank:", n.rank)) } if(!is.null(changepoints)){ changepoints = c(0, changepoints, nrow(Y)) Y.split = list() for(i in 1:(length(changepoints) - 1)){ indices = (changepoints[i] + 1):changepoints[i + 1] Y.split[[i]] = Y[indices, ] } Y = Y.split } else if(is.null(changepoints)){ Y = list(Y) } output = list() for(j in 1:length(Y)){ print(paste("Estimating stationary block", j)) nmf.output = nmf(Y[[j]], method = algtype, rank = n.rank, nrun = nruns) cons.matrix = nmf.output@consensus if (length(lambda) == 1){ if (lambda > 1){ hc.out = hclust(dist(cons.matrix)) ct.out = cutree(hc.out, lambda) matr.fact = matrix(nrow = lambda, ncol = nrow(cons.matrix)) for (i in 1:lambda){ matr.fact[i,] = ct.out == i } matr.fact = matr.fact*1 adj.matrix = t(matr.fact) %*% matr.fact diag(adj.matrix) = 0 colnames(adj.matrix) = rownames(adj.matrix) = colnames(cons.matrix) } else if (lambda <= 1 && lambda >=0){ cons.matrix[cons.matrix > lambda] = 1 cons.matrix[cons.matrix <= lambda] = 0 adj.matrix = cons.matrix diag(adj.matrix) = 0 } } else if (length(lambda) > 1){ if (all(lambda > 1)){ hc.out = hclust(dist(cons.matrix)) adj.matrix = list() for (i in 1:length(lambda)){ ct.out = cutree(hc.out, lambda[i]) matr.fact = matrix(nrow = lambda[i], ncol = nrow(cons.matrix)) for (j in 1:lambda[i]){ matr.fact[j,] = ct.out == j } matr.fact = matr.fact*1 curr.adj.matrix = t(matr.fact) %*% matr.fact diag(curr.adj.matrix) = 0 colnames(curr.adj.matrix) = rownames(curr.adj.matrix) = colnames(cons.matrix) adj.matrix[[i]] = curr.adj.matrix } } else if (all(lambda <= 1 && lambda >= 0)){ adj.matrix = list() for (i in 1:length(lambda)){ curr.adj.matrix = cons.matrix curr.adj.matrix[curr.adj.matrix > lambda[i]] = 1 curr.adj.matrix[curr.adj.matrix <= lambda[i]] = 0 diag(curr.adj.matrix) = 0 adj.matrix[[i]] = curr.adj.matrix } } } if (length(Y) == 1){ output = adj.matrix } else if (length(Y) > 1){ output[[j]] = adj.matrix } } return(output) }
print.univariateTable <- function(x,...){ sx <- summary(x,...) print(sx) invisible(sx) }
CompareManyTs <- function (list.of.ts, burn = 0, type = "l", gap = 0, boxes = TRUE, thin = 1, labels = NULL, same.scale = TRUE, ylim = NULL, refline = NULL, color = NULL, ...) { add.refline <- function(refline, i) { if (is.null(refline)) return() if (length(refline) == 1) y <- refline else y <- refline[i] abline(h = y, lty = 3) } stopifnot(is.list(list.of.ts)) for (i in 1:length(list.of.ts)) { if (is.data.frame(list.of.ts[[i]])) { list.of.ts[[i]] <- as.matrix(list.of.ts[[i]]) } else { list.of.ts[[i]] <- as.array(list.of.ts[[i]]) } } stopifnot(all(sapply(list.of.ts, is.array))) ngroups <- length(list.of.ts) ndim <- sapply(list.of.ts, function(x) length(dim(x))) stopifnot(all(ndim == ndim[1])) if (ndim[1] == 3) { dim <- dim(list.of.ts[[1]]) for (i in 1:ngroups) { list.of.ts[[i]] <- matrix(aperm(list.of.ts[[i]], c(1, 3, 2)), nrow = dim[1]) } } if (burn > 0) { for (i in 1:ngroups) { list.of.ts[[i]] <- list.of.ts[[i]][-(1:burn), ] } } nvars <- ncol(list.of.ts[[1]]) nobs <- nrow(list.of.ts[[1]]) stopifnot(all(sapply(list.of.ts, ncol) == nvars)) stopifnot(all(sapply(list.of.ts, nrow) == nobs)) nrows <- max(1, floor(sqrt(nvars))) ncols <- ceiling(nvars/nrows) index <- thin * (1:floor(nobs/thin)) for (i in 1:ngroups) { list.of.ts[[i]] <- list.of.ts[[i]][index, , drop = FALSE] } nobs <- length(index) if (is.null(color)) { color <- 1:ngroups } if (!is.null(ylim)) { same.scale <- TRUE } if (is.null(ylim)) { ylim <- range(sapply(list.of.ts, range, na.rm = TRUE)) } opar <- par(mfrow = c(nrows, ncols), mar = rep(gap/2, 4), oma = c(4, 4, 4, 4)) on.exit(par(opar)) m <- 0 for (j in 1:nrows) { for (k in 1:ncols) { m <- m + 1 if (m > nvars) { plot(index, rep(ylim, len = nobs), type = "n", axes = FALSE) } else { if (same.scale == FALSE) { ylim <- range(sapply(list.of.ts, function(x) range(x[, m]))) } plot(index, list.of.ts[[1]][, m], axes = FALSE, type = "n", ylim = ylim, ...) for (group in 1:ngroups) { lines(index, list.of.ts[[group]][, m], type = type, col = color[group], lty = group) } if (is.null(labels)) { labels <- colnames(list.of.ts[[1]]) } if (!is.null(labels)) { text(min(index), max(ylim), labels[m], pos = 4) } add.refline(refline, m) if (boxes) { box() } } if (j == nrows & IsOdd(k)) { axis(1, xpd = NA, ...) } else if (j == 1 & IsEven(k)) { axis(3, xpd = NA, ...) } if (k == 1 & same.scale == TRUE & IsOdd(j)) axis(2, xpd = NA, ...) else if (k == ncols & same.scale == TRUE & IsEven(j)) axis(4, xpd = NA, ...) } } }
dotPlot <- function(x, fact=NULL, vertical=FALSE, at=1, key=NULL, pch=20, col=fadeColor('black', '66'), cex=1.5, add=FALSE, axes=TRUE, xlim=NULL, ylim=NULL, ...){ skipOut <- FALSE if(!is.null(fact[1])){ if(!is.null(key[1])){ uFact <- key } else { uFact <- unique(fact) } n <- length(uFact) if(length(at) == 1){ at <- 1:n } dataR <- range(x) atR <- range(at) if(!vertical){ if(is.null(xlim[1])){ xlim <- dataR } if(is.null(ylim[1])){ ylim <- atR + c(-1,1)*diff(atR)/7 } } else { if(is.null(xlim[1])){ xlim <- atR + c(-1,1)*diff(atR)/7 } if(is.null(ylim[1])){ ylim <- dataR } } if(length(pch) == 1){ pch <- rep(pch, length(at)) } if(length(col) == 1){ col <- rep(col, length(at)) } if(length(cex) == 1){ cex <- rep(cex, length(at)) } dotPlot(x[fact == uFact[1]], vertical=vertical, at=at[1], axes=axes, add=add, pch=pch[1], col=col[1], cex=cex[1], xlim=xlim, ylim=ylim, ...) for(i in 2:n){ dotPlot(x[fact == uFact[i]], vertical=vertical, at=at[i], add=TRUE, pch=pch[i], col=col[i], cex=cex[i], axes=FALSE) } if(axes & !add){ if(vertical){ graphics::axis(1, at=at, labels=uFact) } else { graphics::axis(2, at=at, labels=uFact) } } skipOut=TRUE } y <- rep(at[1], length(x)) if(vertical & !skipOut){ if(add){ graphics::points(y,x, pch=pch[1], col=col[1], cex=cex[1], ...) } else { if(is.null(xlim[1])){ xlim <- at[1]+c(-1,1) } if(is.null(ylim[1])){ ylim <- range(x) } graphics::plot(y,x,axes=FALSE,xlim=xlim, ylim=ylim, pch=pch[1], col=col[1], cex=cex[1], ...) } } else if(!skipOut){ if(add){ graphics::points(x,y, pch=pch[1], col=col[1], cex=cex[1], ...) } else { if(is.null(ylim[1])){ ylim <- at[1]+c(-1,1) } if(is.null(xlim[1])){ xlim <- range(x) } graphics::plot(x,y,axes=FALSE,xlim=xlim, ylim=ylim, pch=pch[1], col=col[1], cex=cex[1], ...) } } if(axes & !add & is.null(fact[1])){ graphics::axis(vertical+1) } }
sedRamp<- function (dat,srstart=0.01,srend=0.05,genplot=T,verbose=T) { if(verbose) cat("\n----- APPLY RAMPING SEDIMENTATION RATE MODEL TO CONVERT TIME TO STRATIGRAPHY -----\n") dat <- data.frame(dat) npts <- length(dat[,1]) if(verbose) cat(" * Number of points in stratigraphic series=", npts,"\n") dtt <- dat[2:npts,1]-dat[1:(npts-1),1] if((min(dtt)-max(dtt)) != 0) { cat("\n**** ERROR: sampling interval is not uniform.\n") stop("**** TERMINATING NOW!") } dt=dtt[1] if(verbose) cat(" * Sample interval=", dt,"\n") srstep=(srend-srstart)/(npts-1) sedrate <- srstart + srstep*( (1:npts)-1 ) depth <- cumsum(dt*sedrate) depth <- depth - min(depth) out <- as.data.frame(cbind(depth,dat[,2])) if(genplot) { par(mfrow=c(2,1)) plot(dat, cex=.5,xlab="Time",ylab="Value",main="Time Series",bty="n") lines(dat) plot(out, cex=.5,xlab="Space",ylab="Value",main="Modeled Stratigraphic Series",bty="n") lines(out) } return(out) }
corpage <- tabItem(tabName = "cor", h2("Precision of a correlation coefficient"), "Enter the correlation coefficient you expect. To estimate the confidence interval width from a number of events, enter the number of events in 'Number of events'. To estimate the number of observations required to get a confidence interval width of X, enter the width in 'Confidence interval width'.", h4("Please enter the following"), sliderInput("cor_r", "Correlation coefficient", value = 0, min = -1, max = 1, step = .01), selectInput("cor_method", label = "Type of correlation coefficient", choices = c("Pearson" = "pearson", "Kendall" = "kendall", "Spearman" = "spearman"), selected = "pearson"), h4("Please enter one of the following"), uiOutput("cor_resetable_input"), actionButton("cor_reset_input", "Reset 'Number of observations' or 'Confidence interval width'"), h4("Results"), verbatimTextOutput("cor_out"), tableOutput("cor_tab"), "Code to replicate in R:", verbatimTextOutput("cor_code"), h4("References"), "Bonett DG, and Wright TA (2000) Sample size requirements for estimating Pearson, Kendall and Spearman correlations. ", tags$i("Psychometrika"), " 65:23-28", tags$a(href = "https://doi.org/10.1007/BF02294183","doi:10.1007/BF02294183") ) cor_fn <- function(input, code = FALSE){ if(is.na(input$cor_n) & is.na(input$cor_ciwidth)) { cat("Awaiting 'number of observations' or 'confidence interval width'") } else { z <- ifelse(is.na(input$cor_n), paste0(", conf.width = ", input$cor_ciwidth), paste0(", n = ", input$cor_n)) x <- paste0("prec_cor(r = ", input$cor_r, z, ", conf.level = ", input$conflevel, ", method = '", input$cor_method, "')") if(code){ cat(x) } else { eval(parse(text = x)) } } }
scale_fill_matcha_d <- function(){ggplot2::scale_fill_manual(values = c("
cor_to_spcor <- function(cor = NULL, cov = NULL, tol = .Machine$double.eps^(2 / 3)) { cor <- .get_cor(cor, cov) if (is.null(cov)) { stop("Covariance matrix (or vector of SD of variables) needs to be passed for semi-partial correlations.") } else { if (!is.matrix(cov)) { cov <- cor_to_cov(cor, sd = cov) } inverted <- .invert_matrix(cov, tol = tol) out <- -cov2cor(inverted) / sqrt(diag(cov)) / sqrt(abs(diag(inverted) - t(t(inverted^2) / diag(inverted)))) } diag(out) <- 1 out }
library(ggplot2) library(data.table) library(doremi) set.seed(1) knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.align="center", fig.width = 5, fig.height = 5, comment = " ) time <- 0:90 exc <- rep(c(0,1,0),c(11,30,50)) set.seed(123) variable <- generate.panel.1order(time = time, excitation = exc, tau = 5, nind = 1, intranoise = 1) plot(variable) est_result <- analyze.1order(data = variable, input = "excitation", time = "time", signal = "signal", dermethod = "gold", derparam = 13) plot(est_result)+ ggplot2::geom_line(data = variable,aes(time,signalraw,color = "underlying model"))+ ggplot2::labs(y = "", title = "estimation of first order\n differential equation parameters") set.seed(123) variable2 <- generate.panel.2order(time = time, excitation = exc, period = 30, y0 = 0, xi = 0.1, nind = 1, intranoise = 0.8) plot(variable2) est_result2 <- analyze.2order(variable2, input = "excitation", time = "time", signal = "signal", dermethod = "glla", derparam = 14) plot(est_result2)+ ggplot2::geom_line(data = variable2,aes(time,signalraw,color = "underlying model"))+ ggplot2::labs(color = "", y = "", title = "estimation of second order \ndifferential equation parameters") time <- seq(0,100,0.1) exc <- as.numeric(time >= 10 & time <= 40) variable <- generate.1order(time = time, excitation = exc, y0 = 0, tau = 10, k = 1) ggplot2::ggplot(data = as.data.table(variable)) + ggplot2::ggtitle( "First order differential equation solution")+ ggplot2::geom_line(ggplot2::aes(t,y, colour = "variable"))+ ggplot2::geom_line(ggplot2::aes(t,exc, colour = "Excitation"),size = 1.5)+ ggplot2::geom_hline(yintercept=0.63*max(variable$y), linetype="dashed", colour = "gray")+ ggplot2::geom_hline(yintercept=0.37*max(variable$y), linetype="dashed", colour = "gray")+ ggplot2::geom_vline(xintercept=variable$t[variable$y==max(variable$y)], colour = "gray")+ ggplot2::geom_vline(xintercept=50, colour = "gray")+ ggplot2::geom_vline(xintercept=19, colour = "gray")+ ggplot2::geom_vline(xintercept=10, colour = "gray")+ ggplot2::annotate("segment", x = 10, xend = 19, y = -0.1, yend = -0.1, colour = "dark green", size = 1)+ ggplot2::annotate("text", x = 15, y = -0.2, label = "tau", parse = TRUE, colour = "dark green")+ ggplot2::annotate("segment", x = 40, xend = 50, y = -0.1, yend = -0.1, colour = "dark green", size = 1)+ ggplot2::annotate("text", x = 45, y = -0.2, label = "tau", parse = TRUE, colour = "dark green")+ ggplot2::annotate("text", x = 75, y = 0.7, label = "63% diff. max and eq. value", colour = "gray")+ ggplot2::annotate("text", x = 75, y = 0.3*max(variable$y), label = "37% diff. max and eq. value", colour = "gray")+ ggplot2::labs(x = "Time (arb. unit)", y = "variable (arb. unit)", colour = "Legend")+ ggplot2::theme_bw() + ggplot2::theme(legend.position = "top", plot.title = ggplot2::element_text(hjust = 0.5)) time <- 0:130 excitation <- c(rep(0,30),rep(1,50),rep(0,51)) variable <- generate.2order(time = time, excitation = excitation, xi = 0.2, period = 15, k = 1) ggplot2::ggplot(variable)+ ggplot2::ggtitle( "Second order differential equation solution")+ ggplot2::geom_line(aes(t,y,color = "variable"))+ ggplot2::geom_line(aes(time,excitation,color = "excitation"))+ ggplot2::geom_vline(xintercept=80, colour = "gray")+ ggplot2::annotate("text", x = 100, y = 1, label = "DLO", parse = TRUE, colour = "gray")+ ggplot2::labs(x = "Time (arb. unit)", y = "variable (arb. unit)", colour = "Legend")+ ggplot2::theme_bw() + ggplot2::theme(legend.position = "top", plot.title = ggplot2::element_text(hjust = 0.5))
unnest. <- function(.df, ..., keep_empty = FALSE, .drop = TRUE, names_sep = NULL, names_repair = "unique") { UseMethod("unnest.") } unnest..tidytable <- function(.df, ..., keep_empty = FALSE, .drop = TRUE, names_sep = NULL, names_repair = "unique") { vec_assert(.drop, logical(), 1) dots <- enquos(...) data_names <- names(.df) list_bool <- map_lgl.(.df, is.list) if (length(dots) == 0) { dots <- syms(data_names[list_bool]) } else { dots <- tidyselect_syms(.df, ...) } if (.drop) { keep_cols <- data_names[!list_bool] } else { keep_cols <- data_names[data_names %notin% as.character(dots)] } if (keep_empty) { .df <- mutate_lapply(.df, as.character(dots), keep_empty_prep) } unnest_data <- map.(dots, ~ unnest_col(.df, .x, names_sep)) unnest_nrow <- list_sizes(unnest_data) if (!length(vec_unique(unnest_nrow)) == 1) { abort("unnested data contains different row counts") } rep_vec <- list_sizes(pull.(.df, !!dots[[1]])) if (length(keep_cols) > 0) { keep_df <- .df[, ..keep_cols] keep_df <- keep_df[vec_rep_each(1:.N, rep_vec)] result_df <- bind_cols.(keep_df, unnest_data, .name_repair = names_repair) } else { result_df <- bind_cols.(unnest_data, .name_repair = names_repair) } result_df } unnest..data.frame <- function(.df, ..., keep_empty = FALSE, .drop = TRUE, names_sep = NULL, names_repair = "unique") { .df <- as_tidytable(.df) unnest.( .df, ..., keep_empty = keep_empty, .drop = .drop, names_sep = names_sep, names_repair = names_repair ) } unnest_col <- function(.df, col = NULL, names_sep = NULL) { .l <- pull.(.df, !!col) null_bool <- map_lgl.(.l, is.null) .check_data <- .l[!null_bool][[1]] is_vec <- is.atomic(.check_data) && !is.matrix(.check_data) if (is_vec) { result_df <- tidytable(!!col := do.call("c", .l)) } else { result_df <- bind_rows.(.l) } if (!is.null(names_sep)) { names(result_df) <- paste(as_name(col), names(result_df), sep = names_sep) } result_df } keep_empty_prep <- function(.l) { null_bool <- map_lgl.(.l, is.null) if (!any(null_bool)) return(.l) .check_data <- .l[!null_bool][[1]] is_vec <- is.atomic(.check_data) && !is.matrix(.check_data) if (is_vec) { .replace <- NA } else { null_df <- vec_slice(.check_data, 1) vec_slice(null_df, 1) <- NA .replace <- list(null_df) } replace_na.(.l, .replace) } globalVariables("..keep_cols")
NMreadSection <- function(file=NULL, lines=NULL, text=NULL, section, return="text", keepEmpty=FALSE, keepName=TRUE, keepComments=TRUE, asOne=TRUE, simplify=TRUE, cleanSpaces=FALSE, ...){ if(missing(section)||is.null(section)){ section="." asOne=FALSE simplify=FALSE keepName.arg <- keepName keepName=TRUE } else { section <- toupper(section) } res <- NMextractText(file=file, lines=lines, text=text, section=section, char.section="\\$", return=return, keepEmpty=keepEmpty, keepName=keepName, keepComments=keepComments, asOne=asOne, simplify=simplify, cleanSpaces=cleanSpaces, type="mod", ...) if(section=="."){ names(res) <- unlist( lapply(res,function(x) sub("\\$([^ ]+)","\\1",strsplit(x[1]," ")[[1]][1])) ) res2 <- lapply(unique(names(res)),function(x)do.call(c,res[names(res)==x])) names(res2) <- unique(names(res)) res2 <- lapply(res2,function(x){names(x) <- NULL x} ) if(keepName.arg==FALSE){ names.res2 <- names(res2) res2 <- lapply(1:length(res2),function(x)sub(paste0(" *\\$",names.res2[x]," *"),"",res2[[x]])) names(res2) <- names.res2 } res <- res2 } res } NMgetSection <- function(...){ .Deprecated("NMreadSection") NMreadSection(...) }
compute_tol <- function (graph, depth, msg_new, msg_old) { heads <- as.integer(head_of(graph, E(graph))) tails <- as.integer(tail_of(graph, E(graph))) tol <- 0 for (i in 1:length(heads)) { key_dir <- paste(c(heads[i], tails[i]), collapse="") key_rev <- paste(c(tails[i], heads[i]), collapse="") tol <- max( tol, max(0, abs(stats::na.omit(msg_new$A[[key_dir]] - msg_old$A[[key_dir]]))), max(0, abs(stats::na.omit(msg_new$A[[key_rev]] - msg_old$A[[key_rev]]))), max(0, abs(stats::na.omit(msg_new$E[[key_dir]] - msg_old$E[[key_dir]]))), max(0, abs(stats::na.omit(msg_new$E[[key_rev]] - msg_old$E[[key_rev]]))), stats::na.omit(abs(msg_new$B[[key_dir]] - msg_old$B[[key_dir]])), stats::na.omit(abs(msg_new$B[[key_rev]] - msg_old$B[[key_rev]])), stats::na.omit(abs(msg_new$D[[key_dir]] - msg_old$D[[key_dir]])), stats::na.omit(abs(msg_new$D[[key_rev]] - msg_old$D[[key_rev]])) ) } return (tol) }
boxcoxtype <- function(formula,random = ~1, k=3,trials=1, data,find.in.range = c(-2,2), s = 20, plot.opt=1,random.distribution='np',...) { call <- match.call() N <- NROW(data) weights= rep(trials, N) data$weights <- weights S <- 0:s lam <- find.in.range[1] + (find.in.range[2] - find.in.range[1]) * S/s loglik <- rep(0, s+1 ) mform <- strsplit(as.character(random)[2], "\\|")[[1]] mform <- gsub(" ", "", mform) for (t in 1:(s+1) ) { if (length(mform) == 1) { fit <- try(alldist( formula = formula,random = formula(random), k=k,weights = weights,data = data, family=binomial(link=boxcoxpower(lam[t])), verbose=FALSE, plot.opt = 0)) if (class(fit) == "try-error") { cat("boxcoxtype failed using lambda=", lam[t], ". Hint: specify another range of lambda values and try again.") return() } loglik[t] <- -1/2*(fit$disparity) }else { fit <- try(allvc( formula = formula,random = formula(random), k=k,weights = weights,data = data, family=binomial(link=boxcoxpower(lam[t])), verbose=FALSE, plot.opt = 0)) if (class(fit) == "try-error") { cat("boxcoxtype failed using lambda=", lam[t], ". Hint: specify another range of lambda values and try again.") return() } loglik[t] <- -1/2*(fit$disparity) } } max.result <- which.max(loglik) maxloglik<-max(loglik) lambda.max <- lam[max.result] if (length(mform) == 1) { fit <- alldist(formula =formula,random = formula(random), k=k, weights=weights, data = data, family=binomial(link=boxcoxpower(lambda.max )), verbose=FALSE, random.distribution = random.distribution, plot.opt = 0) }else {fit <- allvc(formula =formula,random = formula(random), k=k, weights=weights, data = data, family=binomial(link=boxcoxpower(lambda.max )), verbose=FALSE, random.distribution = random.distribution, plot.opt = 0) } if(k==1){coef<-fit$coefficients }else{ coef<-fit$coefficients[1:abs(length(fit$coefficients)-length(fit$mass.points))]} ylim1 = range(loglik, maxloglik) ml <- paste("Maximum profile log-likelihood:",round(maxloglik) , "at lambda=", lambda.max, "\n") if (plot.opt==1){ graphics::plot(lam, loglik, type = "l", xlab = expression(lambda), ylab = "Profile log-likelihood", ylim = ylim1,col="green", main=ml) plims <- graphics::par("usr") y0 <- plims[3] graphics::segments(lambda.max, y0, lambda.max, maxloglik, lty = 1,col="red") cat("Maximum Profile Log-likelihood:", maxloglik, "at lambda=", lambda.max, "\n") } aic<- fit$disparity+2*(length(coef)+2*k) bic<-fit$disparity+log(N)*(length(coef)+2*k) result <- list(coef=coef,fit=fit, All.lam=lam, profile.loglik = loglik, lastfit = list(fit), objective = maxloglik, Maximum = lambda.max,y0=y0,ml=ml, "kind"=5, ylim1=ylim1, aic = aic, bic = bic) class(result)<-"boxcoxmix" return(result) } boxcoxpower <- function(Lambda=0) { linkfun <- function(mu){ if(Lambda==0) log(mu/(1-mu)) else (((mu/(1-mu))^Lambda)-1)/Lambda} linkinv <- function(eta) { if(Lambda==0) plogis(eta) else (((1+Lambda*eta)^(-1/Lambda))+1)^(-1)} mu.eta<- function(eta) { if(Lambda==0) ifelse(abs(eta)>30,.Machine$double.eps, exp(eta)/(1+exp(eta))^2) else pmax(((1+Lambda*eta)^((1/Lambda)-1))/((1+Lambda*eta)^(1/Lambda)+1)^2, .Machine$double.eps)} valideta <- function(eta) TRUE link <-paste("boxcoxpower(",Lambda,")", sep="") structure(list(linkfun = linkfun, linkinv = linkinv, mu.eta = mu.eta, valideta = valideta, name = link), class = "link-glm") } binomial <- function (link = boxcoxpower(0)) { linktemp <- substitute(link) if (!is.character(linktemp)) linktemp <- deparse(linktemp) okLinks <- c("logit", "probit", "cloglog", "cauchit", "log", "boxcoxpower") if (linktemp %in% okLinks) stats <- make.link(linktemp) else if (is.character(link)) { stats <- make.link(link) linktemp <- link } else { if(inherits(link, "link-glm")) { stats <- link if(!is.null(stats$name)) linktemp <- stats$name } else { stop(gettextf('link "%s" not available for binomial family; available links are %s', linktemp, paste(sQuote(okLinks), collapse =", ")), domain = NA) } } variance <- function(mu) mu * (1 - mu) validmu <- function(mu) all(is.finite(mu)) && all(mu>0 &mu<1) dev.resids <- stats::binomial()$dev.resids aic <- function(y, n, mu, wt, dev) { m <- if(any(n > 1)) n else wt -2*sum(ifelse(m > 0, (wt/m), 0)* dbinom(round(m*y), round(m), mu, log=TRUE)) } initialize <- expression({ if (NCOL(y) == 1) { if (is.factor(y)) y <- y != levels(y)[1L] n <- rep.int(1, nobs) y[weights == 0] <- 0 if (any(y < 0 | y > 1)) stop("y values must be 0 <= y <= 1") mustart <- (weights * y + 0.5)/(weights + 1) m <- weights * y if(any(abs(m - round(m)) > 1e-3)) warning("non-integer } else if (NCOL(y) == 2) { if(any(abs(y - round(y)) > 1e-3)) warning("non-integer counts in a binomial glm!") n <- y[, 1] + y[, 2] y <- ifelse(n == 0, 0, y[, 1]/n) weights <- weights * n mustart <- (n * y + 0.5)/(n + 1) } else stop("for the 'binomial' family, y must be a vector of 0 and 1\'s\nor a 2 column matrix where col 1 is no. successes and col 2 is no. failures") }) simfun <- function(object, nsim) { ftd <- fitted(object) n <- length(ftd) ntot <- n*nsim wts <- object$prior.weights if (any(wts %% 1 != 0)) stop("cannot simulate from non-integer prior.weights") if (!is.null(m <- object$model)) { y <- model.response(m) if(is.factor(y)) { yy <- factor(1+rbinom(ntot, size = 1, prob = ftd), labels = levels(y)) split(yy, rep(seq_len(nsim), each = n)) } else if(is.matrix(y) && ncol(y) == 2) { yy <- vector("list", nsim) for (i in seq_len(nsim)) { Y <- rbinom(n, size = wts, prob = ftd) YY <- cbind(Y, wts - Y) colnames(YY) <- colnames(y) yy[[i]] <- YY } yy } else rbinom(ntot, size = wts, prob = ftd)/wts } else rbinom(ntot, size = wts, prob = ftd)/wts } structure(list(family = "binomial", link = linktemp, linkfun = stats$linkfun, linkinv = stats$linkinv, variance = variance, dev.resids = dev.resids, aic = aic, mu.eta = stats$mu.eta, initialize = initialize, validmu = validmu, valideta = stats$valideta, simulate = simfun), class = "family") }
Persisters <- R6::R6Class( "Persisters", public = list( persisters = list(), name = "FileSystem", initialize = function(persisters = list(), name = "FileSystem") { self$persisters <- persisters self$name <- name private$persister_get() } ), private = list( persister_get = function() { if (!self$name %in% 'FileSystem') { stop(sprintf("The requested VCR cassette persister (%s) is not registered.", self$name), call. = FALSE) } self$persisters <- switch(self$name, FileSystem = FileSystem) } ) ) persister_fetch <- function(x = "FileSystem", file_name) { per <- Persisters$new(name = x) per <- per$persisters per$new(file_name = file_name) }
context("LVar") library(aglm) test_that("getLVarMatForOneVec()'s outputs are correct.", { expect_equal(getLVarMatForOneVec(1:3)$dummy_mat, matrix(c(1, 0, 1), 3, 1)) expect_equal(getLVarMatForOneVec(c(1, 1.5, 2, 2.3, 3), breaks=1:3)$dummy_mat, matrix(c(1, 0.5, 0, 0.3, 1), 5, 1)) expect_equal(getLVarMatForOneVec(c(1, 1.5, 2, 2.3, 3), breaks=c(0, 1.8, 4))$dummy_mat, matrix(c(0.8, 0.3, 0.2, 0.5, 1.2), 5, 1)) }) createX <- function(nobs, nvar_numeric, seed=12345) { set.seed(seed) nobs <- nobs data <- list() if (nvar_numeric > 0) for (i in 1:nvar_numeric) data[[paste0("Num", i)]] <- rnorm(nobs) return(data.frame(data)) } test_that("Check newInput() for L-Variable", { x <- newInput(createX(10, 1), use_LVar=TRUE) expect_equal(x@vars_info[[1]]$id, 1) expect_equal(x@vars_info[[1]]$data_column_idx, 1) expect_equal(x@vars_info[[1]]$type, "quan") expect_equal(x@vars_info[[1]]$use_linear, TRUE) expect_equal(x@vars_info[[1]]$use_UD, FALSE) expect_equal(x@vars_info[[1]]$use_OD, FALSE) expect_equal(x@vars_info[[1]]$use_LV, TRUE) expect_true(is.null(x@vars_info[[1]]$OD_info)) expect_true(is.null(x@vars_info[[1]]$UD_info)) expect_true(!is.null(x@vars_info[[1]]$LV_info)) mat_num <- getDesignMatrix(x) expect_equal(mat_num[,1], x@data[,1]) ncol <- dim(getLVarMatForOneVec(mat_num[,1])$dummy_mat)[2] + 1 expect_equal(dim(mat_num), c(10, ncol)) bins_list <- list(c(0, 1, 2)) x <- newInput(createX(10, 1), use_LVar=TRUE, bins_list=bins_list) expect_equal(x@vars_info[[1]]$LV_info$breaks, bins_list[[1]]) })
setGeneric("vox_offset", function(object) standardGeneric("vox_offset")) setMethod("vox_offset", "nifti", function(object) object@"vox_offset") setMethod("vox_offset", "anlz", function(object) object@"vox_offset") setGeneric("vox_offset<-", function(object, value) standardGeneric("vox_offset<-")) setMethod("vox_offset<-", signature(object="nifti"), function(object, value) { if ( "vox_offset" %in% slotNames(object) ){ object@"vox_offset" <- value audit.trail(object) <- niftiAuditTrailEvent(object, "modification", match.call(), paste("vox_offset <-", value)) } else { warning("vox_offset is not in slotNames of object") } return(object) }) setMethod("vox_offset<-", signature(object="anlz"), function(object, value) { if ( "vox_offset" %in% slotNames(object) ){ object@"vox_offset" <- value } else { warning("vox_offset is not in slotNames of object") } return(object) }) setGeneric("vox.offset", function(object) standardGeneric("vox.offset")) setMethod("vox.offset", "nifti", function(object) object@"vox_offset") setMethod("vox.offset", "anlz", function(object) object@"vox_offset") setGeneric("vox.offset<-", function(object, value) standardGeneric("vox.offset<-")) setMethod("vox.offset<-", signature(object="nifti"), function(object, value) { if ( "vox_offset" %in% slotNames(object) ){ object@"vox_offset" <- value audit.trail(object) <- niftiAuditTrailEvent(object, "modification", match.call(), paste("vox_offset <-", value)) } else { warning("vox_offset is not in slotNames of object") } return(object) }) setMethod("vox.offset<-", signature(object="anlz"), function(object, value) { if ( "vox_offset" %in% slotNames(object) ){ object@"vox_offset" <- value } else { warning("vox_offset is not in slotNames of object") } return(object) })
"Rad.cov" <- function(x1, x2=NULL, p = 1, m = NA, with.log = TRUE, with.constant = TRUE, C = NA, marginal = FALSE, derivative = 0) { if (marginal) { return(rep(0, nrow(x1))) } if (!is.matrix(x1)) x1 <- as.matrix(x1) if( is.null( x2)){ x2<- x1 } if (!is.matrix(x2)) x2 <- as.matrix(x2) d <- ncol(x1) n1 <- nrow(x1) n2 <- nrow(x2) if (is.na(m)) { m <- (d + p)/2 } else { p <- 2 * m - d } if (p < 0) { stop(" p is negative (m possibly too small)") } par <- c(p/2, ifelse((d%%2 == 0) & (with.log), 1, 0)) rbf.constant <- ifelse(with.constant, radbas.constant(m, d), 1) if (is.na(C[1])) { temp <- .Fortran("radbas", PACKAGE="fields", nd = as.integer(d), x1 = as.double(x1), n1 = as.integer(n1), x2 = as.double(x2), n2 = as.integer(n2), par = as.double(par), k = as.double(rep(0, n1 * n2))) return(rbf.constant * matrix(temp$k, ncol = n2, nrow = n1)) } else { if (derivative == 0) { C <- as.matrix(C) n3 <- ncol(C) temp <- .Fortran("multrb",PACKAGE="fields", nd = as.integer(d), x1 = as.double(x1), n1 = as.integer(n1), x2 = as.double(x2), n2 = as.integer(n2), par = as.double(par), c = as.double(C), n3 = as.integer(n3), h = as.double(rep(0, n1 * n3)), work = as.double(rep(0, n2)))$h return(rbf.constant * matrix(temp, nrow = n1, ncol = n3)) } else { if (ncol(C) > 1) { stop("Can only evaluate derivatives on one spline fit") } temp <- .Fortran("mltdrb", PACKAGE="fields", nd = as.integer(d), x1 = as.double(x1), n1 = as.integer(n1), x2 = as.double(x2), n2 = as.integer(n2), par = as.double(par), c = as.double(C), h = as.double(rep(0, n1 * d)), work = as.double(rep(0, n2)))$h return(rbf.constant * matrix(temp, nrow = n1, ncol = d)) } } stop("should not get here!") }
latex.ftable <- function(object, ..., style=c("ftableX", "array", "ftable"), quote=FALSE, digits=getOption("digits")) { style <- match.arg(style) result <- unclass(object) rv <- attr(object, "row.vars") n.row.vars <- length(rv) dimrv <- sapply(rv, length) rg <-rep(dimrv[n.row.vars], prod(dimrv[-n.row.vars])) if (!is.null(list(...)$rgroup)) row.names(object) <- 1:nrow(object) cv <- attr(object, "col.vars") n.col.vars <- length(cv) dimcv <- sapply(cv, length) cg <-rep(dimcv[n.col.vars], prod(dimcv[-n.col.vars])) dimobj <- dim(object) switch(style, ftableX={ r <- format(object, ..., quote = quote, digits = digits) latex(r, n.cgroup=c(n.row.vars+1, cg), n.rgroup=c(n.col.vars+1, rg), ...) }, array={ latex(object) }, ftable={ r <- format(object, ..., quote = quote, digits = digits) latex(r) } ) } if (FALSE) { ft31 <- ftable(Titanic, row.vars = 3:1, col.vars = 4) write.ftable(ft31, quote = FALSE) write.ftable(ft31, quote = FALSE, method="row.compact") write.ftable(ft31, quote = FALSE, method="col.compact") write.ftable(ft31, quote = FALSE, method="compact") latex(ft31, style="ftable") latex(ft31, style="ftableX") latex(ft31, style="ftableX", rgroup=c("","A","B","C","D")) latex(ft31, style="array") latex(ft31) ft13 <- ftable(Titanic, row.vars = 1, col.vars = 4:2) write.ftable(ft13, quote = FALSE) write.ftable(ft13, quote = FALSE, method="row.compact") write.ftable(ft13, quote = FALSE, method="col.compact") write.ftable(ft13, quote = FALSE, method="compact") latex(ft13, style="ftableX", cgroup=c("","A","B","C","D")) latex(ft13, style="ftableX") latex(ft13, style="ftable") latex(ft13, style="array") }
test_that("illegal initializations are rejected", { expect_silent(ConstModVar$new("const", "GBP", 42.5)) expect_error(ConstModVar$new(42,42,42), class="description_not_string") expect_error(ConstModVar$new("const",42,42), class="units_not_string") expect_error(ConstModVar$new("const","GBP","42"), class="const_not_numeric") }) test_that("properties are correct", { lue <- ConstModVar$new("lue", "GBP", 42) expect_false(lue$is_expression()) expect_false(lue$is_probabilistic()) }) test_that("it has correct distribution name", { lue <- ConstModVar$new("lue", "GBP", 42) expect_identical(lue$distribution(), "Const(42)") }) test_that("const values are returned", { x <- ConstModVar$new("const", "GBP", 42) expect_equal(x$mean(),42) expect_equal(x$SD(),0) expect_equal(x$mode(),42) expect_error(x$quantile(probs=c(0.25,NA,0.75)), class="probs_not_defined") expect_error(x$quantile(probs=c(0.25,"A",0.75)), class="probs_not_numeric") expect_error(x$quantile(probs=c(-0.25,0.75)), class="probs_out_of_range") expect_equal(x$quantile(probs=c(0.22)),42) }) test_that("set and get function as expected", { x <- ConstModVar$new("y", "GBP", 42) expect_intol(x$get(), 42, 0.01) expect_error(x$set(TRUE), class="what_not_character") expect_error(x$set("red"), class="what_not_supported") expect_silent(x$set()) expect_silent(x$set("expected")) expect_intol(x$get(), 42, 0.01) S <- vector(mode="numeric", length=1000) for (i in 1:1000) { x$set() S[i] <- x$get() } expect_intol(mean(S), 42, 0.1) expect_intol(sd(S), 0, 0.01) }) test_that("set('value') works as expected", { x <- ConstModVar$new("x", "GBP", 42) expect_equal(x$get(), 42) x$set("value", 7) expect_equal(x$get(), 7) expect_equal(x$mean(), 42) })
xmastreeshape <- function(year = 2018, language = c("english", "spanish", "catalan"), shape = c("piramidal", "oval", "vshaped", "round", "columnar"), nballs = 15, ballscolor = NULL, seed = NULL) { if (!inherits(year, c("numeric", "integer")) || length(year) != 1L) stop("'year' must be a number") language <- match.arg(language) shape <- match.arg(shape) if (!inherits(nballs, c("numeric", "integer")) || length(nballs) != 1L || nballs < 0) stop("'nballs' must be a non negative integer") if(!is.null(ballscolor) & (anyNA(ballscolor) || !all(ballscolor %in% grDevices::colors()))) stop("'ballscolor' must be NULL or valid R color(s)") if(!is.null(seed) & (is.na(seed) || !is(seed, "numeric"))) stop("'seed' must be numeric or NULL") if (!is.null(seed)) set.seed(seed) newwindow() xmin <- -3 xmax <- 3 ymin <- -2 ymax <- 4 np <- 1000 u <- runif(np, xmin, xmax) v <- runif(np, ymin, ymax) plot(c(xmin, xmax), c(ymin, ymax), type = "n", asp = 1, axes = F, xlab = "", ylab = "") h <- - 0.5 polygon(c(xmin, xmin, xmax, xmax), c(ymin, h, h, ymin), border = NA, col = "azure2") polygon(c(xmin, xmin, xmax, xmax), c(h, ymax, ymax, h), border = NA, col = "darkblue") d <- (xmax - xmin) / 100 x0 <- seq(xmin + d, xmax - d, by = 0.01) lines(x0, h + rnorm(length(x0), 0, 0.05), type = "l", lwd = 3, col = "blue4") plottrunk() if (is.null(ballscolor)) ballscolor <- c("cornflowerblue", "blue", "darkgoldenrod1", "darkmagenta", "yellow", "violet", "red", "darkorchid1", "gold1") switch(shape, piramidal = plotTreePiramidal(nballs = nballs, ballscolor = ballscolor), oval = plotTreeOval(nballs = nballs, ballscolor = ballscolor), vshaped = plotTreeVshaped(nballs = nballs, ballscolor = ballscolor), round = plotTreeRound(nballs = nballs, ballscolor = ballscolor), columnar = plotTreeColumnar(nballs = nballs, ballscolor = ballscolor)) for(i in 1:40) { snow(np = 20, x0 = xmin, x1 = xmax, y0 = ymin, y1 = ymax) Sys.sleep(0.1) } Sys.sleep(0.5) mess <- switch(language, english = "Happy ", spanish = "Feliz ", catalan = "Bon ") myvfont <- c("serif", "bold") text(x = 0, y = 3, labels = paste0(mess, year, "!"), vfont = myvfont, cex = 2, col = "red") Sys.sleep(1) text(x = 0, y = 2.1, labels = "R", srt = 15, vfont = myvfont, cex = 3, col = "gold") }
ms_plan <- R6::R6Class("ms_plan", inherit=ms_object, public=list( initialize=function(token, tenant=NULL, properties=NULL) { self$type <- "plan" private$api_type <- "planner/plans" super$initialize(token, tenant, properties) }, list_tasks=function(filter=NULL, n=Inf) { private$make_basic_list("tasks", filter, n) }, get_task=function(task_title=NULL, task_id=NULL) { assert_one_arg(task_title, task_id, msg="Supply exactly one of task title or ID") if(!is.null(task_id)) { res <- call_graph_endpoint(self$token, file.path("planner/tasks", task_id)) ms_plan_task$new(self$token, self$tenant, res) } else { tasks <- self$list_tasks(filter=sprintf("title eq '%s'", task_title)) if(length(tasks) != 1) stop("Invalid task title", call.=FALSE) tasks[[1]] } }, list_buckets=function(filter=NULL, n=Inf) { private$make_basic_list("buckets", filter, n) }, get_bucket=function(bucket_name=NULL, bucket_id=NULL) { assert_one_arg(bucket_name, bucket_id, msg="Supply exactly one of bucket name or ID") if(!is.null(bucket_id)) { res <- call_graph_endpoint(self$token, file.path("planner/buckets", bucket_id)) ms_plan_bucket$new(self$token, self$tenant, res) } else { buckets <- self$list_buckets(filter=sprintf("name eq '%s'", bucket_name)) if(length(buckets) != 1) stop("Invalid bucket name", call.=FALSE) buckets[[1]] } }, get_details=function() { do_operation("details") }, print=function(...) { name <- paste0("<Plan for ", self$properties$title, ">\n") cat(name) cat("---\n") cat(format_public_methods(self)) invisible(self) } ))
loclda <- function(x, ...) UseMethod("loclda") loclda.default <- function(x, grouping, weight.func = function(x) 1/exp(x), k = nrow(x), weighted.apriori = TRUE, ...) { cl <- match.call() cl[[1]] <- as.name("loclda") structure(list(learn = x, grouping = grouping, lev = levels(grouping), weight.func = weight.func, k = k, weighted.apriori = weighted.apriori, call = cl), class = "loclda") } loclda.formula <- function(formula, data = NULL, ..., subset, na.action = na.fail) { m <- match.call(expand.dots = FALSE) m$... <- NULL m[[1]] <- as.name("model.frame") m <- eval.parent(m) Terms <- attr(m, "terms") grouping <- model.response(m) x <- model.matrix(Terms, m) xint <- match("(Intercept)", colnames(x), nomatch = 0) if (xint > 0) x <- x[, -xint, drop = FALSE] res <- loclda(x, grouping, ...) res$terms <- Terms cl <- match.call() cl[[1]] <- as.name("loclda") res$call <- cl res$contrasts <- attr(x, "contrasts") res$xlevels <- .getXlevels(Terms, m) res$na.action <- attr(m, "na.action") res } loclda.matrix <- function (x, grouping, ..., subset, na.action = na.fail) { if (!missing(subset)){ x <- x[subset, , drop = FALSE] grouping <- grouping[subset] } if (!missing(na.action)) { dfr <- na.action(structure(list(g = grouping, x = x), class = "data.frame")) grouping <- dfr$g x <- dfr$x } res <- loclda.default(x, grouping, ...) cl <- match.call() cl[[1]] <- as.name("loclda") res$call <- cl res } loclda.data.frame <- function (x, ...) { res <- loclda.matrix(structure(data.matrix(x), class = "matrix"), ...) cl <- match.call() cl[[1]] <- as.name("loclda") res$call <- cl res } predict.loclda <- function(object, newdata,...) { weighted <- function (z, Z, y, weight.func, k, weighted.apriori) { unique.y <- sort(unique(y)) Zn <- kronecker(rep(1, nrow(Z)), t(z)) - Z distances <- sqrt(rowSums(Zn^2)) Knn <- sort(distances)[k] indic <- distances <= Knn kdist <- distances[indic] / Knn weighted <- sapply(kdist, weight.func) y <- y[indic] Z <- Z[indic, , drop = FALSE] indic2 <- y %in% (unique.y[table(y) > 1]) y <- y[indic2] weighted <- weighted[indic2] if (is.vector(Z)) Z <- matrix(Z, ncol = 1) Z <- Z[indic2, , drop = FALSE] apriori.table <- sapply(unique.y, function(x) sum(weighted[y == x])) apriori.table <- apriori.table / sum(weighted) if (!weighted.apriori) { indic3 <- apriori.table != 0 apriori.table [indic3] <- 1/sum (indic3) } return(list(y = y, Weights = weighted, X = Z, apriori = apriori.table)) } cov.pooled <- function (X, y, Weights) { y <- as.numeric(y) hilfe <- unique(y) if (is.vector(X)) X <- matrix(X, ncol = 1) cov.vecs <- sapply(hilfe, function(r){ temp <- y == r cov.wt(matrix(X[temp, ], ncol = ncol(X)), wt = Weights[temp])$cov }) if(ncol(X) == 1) cov.vecs <- matrix(cov.vecs, nrow = 1) ni <- sapply(hilfe, function(r) sum(y == r)) cov.vecs <- cov.vecs %*% diag(ni, nrow = length(ni)) 1 / (nrow(X) - length(hilfe)) * matrix(rowSums(cov.vecs), nrow = ncol(X)) } mu.weighted <- function (X, unique.y, y2, Weights, i) { if (is.vector(X)) X <- matrix(X, ncol = 1) temp <- y2 == unique.y[i] Xnow <- X[temp, , drop = FALSE] Wnow <- Weights[temp] as.vector(t(Wnow) %*% Xnow / sum(Wnow)) } ML <- function (x, X, y, y2, Weights, apriori) { unique.y <- sort(unique(y)) sigma <- cov.pooled(X = X, y = y2, Weights = Weights) sigma <- solve(sigma, tol = 1e-100) mu.distances <- rep (Inf, length (unique.y)) posterior.loglik <- -mu.distances for (i in seq(along=posterior.loglik)[apriori!= 0]) { mu <- mu.weighted(X = X, unique.y = unique.y, y2 = y2, Weights = Weights, i = i) temp <- x - mu mu.distances[i] <- drop (crossprod (temp)) posterior.loglik[i] <-(-1/2) * t(temp) %*% sigma %*% (temp) + log (apriori[i]) } names (posterior.loglik) <- names (mu.distances) <- as.character(unique.y) c (mu.distances, posterior.loglik) } llda <- function (x, learn, y, weight.func, k, weighted.apriori) { Weighted <- weighted(z = x, Z = learn, y = y, weight.func = weight.func, k = k, weighted.apriori = weighted.apriori) ML(x = x, X = Weighted$X, y = y, y2 = Weighted$y, Weights = Weighted$Weights, apriori = Weighted$apriori) } if (!inherits(object, "loclda")) stop("object not of class", " 'loclda'") if (!is.null(Terms <- object$terms)) { if (missing(newdata)) newdata <- model.frame(object) else { newdata <- model.frame(as.formula(delete.response(Terms)), newdata, na.action = function(x) x, xlev = object$xlevels) } x <- model.matrix(delete.response(Terms), newdata, contrasts = object$contrasts) xint <- match("(Intercept)", colnames(x), nomatch = 0) if (xint > 0) x <- x[, -xint, drop = FALSE] } else { if (missing(newdata)){ if (!is.null(sub <- object$call$subset)) newdataa <- eval.parent(parse( text = paste(deparse(object$call$x, backtick = TRUE), "[", deparse(sub, backtick = TRUE), ",]"))) else newdata <- eval.parent(object$call$x) if (!is.null(nas <- object$call$na.action)) newdata <- eval(call(nas, newdata)) } if (is.null(dim(newdata))) dim(newdata) <- c(1, length(newdata)) x <- as.matrix(newdata) } werte <- t(apply(x, 1, llda, learn = object$learn, y = object$grouping, weight.func = object$weight.func, k = object$k, weighted.apriori = object$weighted.apriori)) object.levels <- object$lev indic4 <- seq (along = object.levels) mu.distances <- werte[,indic4] posterior.loglik <- werte[,-indic4] if (nrow (newdata) == 1) { mu.distances <- matrix (mu.distances, nrow = 1) posterior.loglik <- matrix (posterior.loglik, nrow = 1) } posterior <- exp (posterior.loglik) classes <- factor(max.col(posterior), levels = indic4, labels = object.levels) dim.posterior <- dim (posterior) all.zero <- logical (dim.posterior[1]) for (i in seq (along = classes)) if (all (posterior.loglik[i,] < log(1e-150))) { classes[i] <- object.levels[which.min(mu.distances[i,])] all.zero[i] <- TRUE } all.zero <- which (all.zero) posterior <- apply (posterior, 1, function (x) if(sum(x) != 0) x <- x/sum(x) else x <- rep (1/dim.posterior[2], dim.posterior[2]) ) result <- list(class = classes, posterior = t(posterior), all.zero = all.zero) return(result) } print.loclda <- function (x, ...) { cat("Call:\n") print(x$call, ...) cat("\nWeighting function:\n") print (x$weight.func, ...) cat("\nNumber of next neighbours that will be used for prediction:\n") print(x$k, ...) cat("\nUsage of weighted a priori probabilities:\n") print(x$weighted.apriori, ...) invisible(x) }
context("Checking rm_repeated_characters") test_that("rm_repeated_characters is removing/replacing character strings",{ x <- "aaaahahahahaha that was a good joke peep and pepper and pepe" expect_equal( rm_repeated_characters(x), "that was a good joke peep and pepper and" ) }) test_that("rm_repeated_characters is extracting repeated character strings",{ x <- "aaaahahahahaha that was a good joke peep and pepper and pepe" expect_equal( rm_repeated_characters(x, extract=TRUE), structure(list(c("aaaahahahahaha", "pepe")), class = c("extracted", "list")) ) })
"% description(x) <- descr return(x) } "% for(n in names(annot)){ annotation(x)[n] <- as.character(annot[n]) } return(x) } "%@%" <- function(x,nm){ nm <- substitute(nm) if(typeof(nm)=="symbol"){ nm <- deparse(nm) } else { nm <- eval.parent(nm) } attr(x,nm) } "%@%<-" <- function(x,nm,value){ nm <- substitute(nm) if(typeof(nm)=="symbol"){ nm <- deparse(nm) } else { nm <- eval.parent(nm) } attr(x,nm) <- value return(invisible(x)) }
.fixupGFortranStdout <- function() { old <- Sys.getenv("GFORTRAN_STDOUT_UNIT") if (nzchar(old) && old == "-1") { Sys.unsetenv("GFORTRAN_STDOUT_UNIT") TRUE } else FALSE } .fixupGFortranStderr <- function() { old <- Sys.getenv("GFORTRAN_STDERR_UNIT") if (nzchar(old) && old == "-1") { Sys.unsetenv("GFORTRAN_STDERR_UNIT") TRUE } else FALSE } system <- function(command, intern = FALSE, ignore.stdout = FALSE, ignore.stderr = FALSE, wait = TRUE, input = NULL, show.output.on.console = TRUE, minimized = FALSE, invisible = TRUE, timeout = 0) { if(!is.logical(intern) || is.na(intern)) stop("'intern' must be TRUE or FALSE") if(!is.logical(ignore.stdout) || is.na(ignore.stdout)) stop("'ignore.stdout' must be TRUE or FALSE") if(!is.logical(ignore.stderr) || is.na(ignore.stderr)) stop("'ignore.stderr' must be TRUE or FALSE") if(!is.logical(wait) || is.na(wait)) stop("'wait' must be TRUE or FALSE") if(!is.logical(show.output.on.console) || is.na(show.output.on.console)) stop("'show.output.on.console' must be TRUE or FALSE") if(!is.logical(minimized) || is.na(minimized)) stop("'minimized' must be TRUE or FALSE") if(!is.logical(invisible) || is.na(invisible)) stop("'invisible' must be TRUE or FALSE") stdout <- ifelse(ignore.stdout, FALSE, "") stderr <- ifelse(ignore.stderr, FALSE, "") f <- "" if (!is.null(input)) { f <- tempfile() on.exit(unlink(f)) writeLines(input, f) } if (intern) { flag <- 3L if(stdout == "") stdout <- TRUE if(!ignore.stderr && .Platform$GUI == "Rgui") stderr <- TRUE } else { flag <- if (wait) ifelse(show.output.on.console, 2L, 1L) else 0L } if (invisible) flag <- 20L + flag else if (minimized) flag <- 10L + flag if (.fixupGFortranStdout()) on.exit(Sys.setenv(GFORTRAN_STDOUT_UNIT = "-1"), add = TRUE) if (.fixupGFortranStderr()) on.exit(Sys.setenv(GFORTRAN_STDERR_UNIT = "-1"), add = TRUE) .Internal(system(command, as.integer(flag), f, stdout, stderr, timeout)) } system2 <- function(command, args = character(), stdout = "", stderr = "", stdin = "", input = NULL, env = character(), wait = TRUE, minimized = FALSE, invisible = TRUE, timeout = 0) { if(!is.logical(wait) || is.na(wait)) stop("'wait' must be TRUE or FALSE") if(!is.logical(minimized) || is.na(minimized)) stop("'minimized' must be TRUE or FALSE") if(!is.logical(invisible) || is.na(invisible)) stop("'invisible' must be TRUE or FALSE") command <- paste(c(shQuote(command), env, args), collapse = " ") if(is.null(stdout)) stdout <- FALSE if(is.null(stderr)) stderr <- FALSE if(length(stdout) != 1L) stop("'stdout' must be of length 1") if(length(stderr) != 1L) stop("'stderr' must be of length 1") if (!is.null(input)) { f <- tempfile() on.exit(unlink(f)) writeLines(input, f) } else f <- stdin flag <- if (isTRUE(stdout) || isTRUE(stderr)) 3L else if (wait) ifelse(identical(stdout, "") || identical(stderr, ""), 2L, 1L) else 0L if (invisible) flag <- 20L + flag else if (minimized) flag <- 10L + flag if (.fixupGFortranStdout()) on.exit(Sys.setenv(GFORTRAN_STDOUT_UNIT = "-1"), add = TRUE) if (.fixupGFortranStderr()) on.exit(Sys.setenv(GFORTRAN_STDERR_UNIT = "-1"), add = TRUE) .Internal(system(command, flag, f, stdout, stderr, timeout)) } shell <- function(cmd, shell, flag = "/c", intern = FALSE, wait = TRUE, translate = FALSE, mustWork = FALSE, ...) { if(missing(shell)) { shell <- Sys.getenv("R_SHELL") if(!nzchar(shell)) shell <- Sys.getenv("COMSPEC") } if(missing(flag) && any(!is.na(pmatch(c("bash", "tcsh", "sh"), basename(shell))))) flag <- "-c" cmd0 <- cmd if(translate) cmd <- chartr("/", "\\", cmd) if(!is.null(shell)) cmd <- paste(shell, flag, cmd) res <- system(cmd, intern = intern, wait = wait | intern, show.output.on.console = wait, ...) if(!intern && res && !is.na(mustWork)) if(mustWork) if(res == -1L) stop(gettextf("'%s' could not be run", cmd0), domain = NA) else stop(gettextf("'%s' execution failed with error code %d", cmd0, res), domain = NA) else if(res == -1L) warning(gettextf("'%s' could not be run", cmd0), domain = NA) else warning(gettextf("'%s' execution failed with error code %d", cmd0, res), domain = NA) if(intern) res else invisible(res) } shell.exec <- function(file) .Internal(shell.exec(file)) Sys.which <- function(names) .Internal(Sys.which(as.character(names)))
context("Test 14: direct vector computation of AFF xbar") test_that("make computeAFFMean produce errors", { x1 <- c(1, "a", 3) expect_error(computeAFFMean(x1), "x contains non-numeric") x2 <- c(1, NA, 3) expect_error(computeAFFMean(x2), "contains NA") x3 <- c(1, NaN, 3) expect_error(computeAFFMean(x3), "contains NA") x4 <- c(1, Inf, 4) expect_error(computeAFFMean(x4), "contains non-finite") x5 <- c(1, 2, 4) expect_error(computeAFFMean(x5, eta=NA), "not a finite") expect_error(computeAFFMean(x5, eta=NULL), "is NULL") expect_error(computeAFFMean(x5, eta=0), NA) expect_error(computeAFFMean(x5, eta=1), NA) expect_error(computeAFFMean(x5, eta=0.9), NA) expect_error(computeAFFMean(x5, eta=-0.1), "not in range") expect_error(computeAFFMean(x5, eta=1.1), "not in range") }) test_that("check computeAFFMean works", { eta1 <- 0.01 x <- c(1, 2, 3, 4) m2 <- x[1] + x[2] w2 <- 2 Delta2 <- x[1] Omega2 <- 1 xbarderiv2 <- (Delta2*w2 - m2*Omega2)/(w2*w2) xbar1 <- x[1] xbarderiv1 <- 0 lderiv2 <- 2*(xbar1 - x[2]) * xbarderiv1 lambda2 <- 1 xbar2 <- m2/w2 w3 <- 3 Omega3 <- 3 m3 <- 6 Delta3 <- 4 xbarderiv3 <- (Delta3*w3 - m3*Omega3)/(w3*w3) xbar2 <- (1+2)/2 lderiv3 <- 2*(xbar2 - x[3]) * xbarderiv2 lambda3 <- lambda2 - eta1 * lderiv3 w4 <- w3 * lambda3 + 1 Omega4 <- Omega3 * lambda3 + w3 m4 <- m3 * lambda3 + x[4] Delta4 <- Delta3 * lambda3 + m3 xbarderiv4 <- (Delta4*w4 - m4*Omega4)/(w4*w4) xbar3 <- m3/w3 lderiv4 <- 2*(xbar3 - x[4]) * xbarderiv3 lambda4 <- lambda3 - eta1 * lderiv4 xbar4 <- m4/w4 expect_equal(computeAFFMean(x, eta=eta1), xbar4) })
library(tidymodels) library(sessioninfo) library(testthat) set.seed(455) folds <- vfold_cv(mtcars, v = 5) simple_rec <- recipe(mpg ~ ., data = mtcars) form <- mpg ~ . spline_rec <- recipe(mpg ~ ., data = mtcars) %>% step_normalize(all_predictors()) %>% step_bs(disp, deg_free = tune()) lm_mod <- linear_reg() %>% set_engine("lm") knn_mod <- nearest_neighbor(mode = "regression", neighbors = tune()) %>% set_engine("kknn") knn_mod_two <- nearest_neighbor(mode = "regression", neighbors = tune("K"), weight_func = tune()) %>% set_engine("kknn") get_coefs <- function(x) { x %>% extract_fit_parsnip() %>% tidy() } verb <- FALSE g_ctrl <- control_grid(verbose = verb, save_pred = TRUE, extract = get_coefs) b_ctrl <- control_bayes(verbose = verb, save_pred = TRUE, extract = get_coefs) mt_spln_lm <- workflow() %>% add_recipe(spline_rec) %>% add_model(lm_mod) mt_spln_knn <- workflow() %>% add_recipe(spline_rec) %>% add_model(knn_mod) mt_knn <- workflow() %>% add_recipe(simple_rec) %>% add_model(knn_mod) set.seed(8825) mt_spln_lm_grid <- tune_grid(mt_spln_lm, resamples = folds, control = g_ctrl) set.seed(8825) mt_spln_lm_bo <- tune_bayes( mt_spln_lm, resamples = folds, iter = 3, control = b_ctrl ) set.seed(8825) mt_spln_knn_grid <- tune_grid( mt_spln_knn, resamples = folds, grid = grid_regular(parameters(mt_spln_knn)), control = g_ctrl ) set.seed(8825) mt_spln_knn_bo <- tune_bayes(mt_spln_knn, resamples = folds, iter = 3, control = b_ctrl) set.seed(8825) mt_spln_knn_bo_sep <- tune_bayes(knn_mod_two, spline_rec, resamples = folds, iter = 3, control = b_ctrl) set.seed(8825) mt_knn_grid <- tune_grid(mt_knn, resamples = folds, control = g_ctrl) set.seed(8825) mt_knn_bo <- tune_bayes(mt_knn, resamples = folds, iter = 3, control = b_ctrl) save( list = grep("^mt_", ls(), value = TRUE), file = test_path("test_objects.RData"), version = 2, compress = "xz" ) data(two_class_dat, package = "modeldata") set.seed(7898) data_folds <- vfold_cv(two_class_dat, repeats = 5) two_class_rec <- recipe(Class ~ ., data = two_class_dat) %>% step_normalize(A, B) knn_model <- nearest_neighbor( mode = "classification", neighbors = tune("K"), weight_func = tune(), dist_power = tune("exponent") ) %>% set_engine("kknn") two_class_wflow <- workflow() %>% add_recipe(two_class_rec) %>% add_model(knn_model) two_class_set <- parameters(two_class_wflow) %>% update(K = neighbors(c(1, 50))) %>% update(exponent = dist_power(c(1 / 10, 2))) set.seed(2494) two_class_grid <- two_class_set %>% grid_max_entropy(size = 10) class_metrics <- metric_set(roc_auc, accuracy, kap, mcc) knn_results <- tune_grid( two_class_wflow, resamples = data_folds, grid = two_class_grid, metrics = class_metrics ) knn_set <- two_class_set knn_gp <- tune:::fit_gp(collect_metrics(knn_results), knn_set, "accuracy", control_bayes() ) saveRDS( knn_results, file = testthat::test_path("knn_results.rds"), version = 2, compress = "xz" ) saveRDS( two_class_set, file = testthat::test_path("knn_set.rds"), version = 2, compress = "xz" ) saveRDS( two_class_grid, file = testthat::test_path("knn_grid.rds"), version = 2, compress = "xz" ) saveRDS( knn_set, file = testthat::test_path("knn_set.rds"), version = 2, compress = "xz" ) saveRDS( knn_gp, file = testthat::test_path("knn_gp.rds"), version = 2, compress = "xz" ) svm_model <- svm_poly( mode = "classification", cost = tune(), degree = tune("%^* scale_factor = tune() ) %>% set_engine("kernlab") two_class_wflow <- workflow() %>% add_recipe(two_class_rec) %>% add_model(svm_model) two_class_set <- parameters(two_class_wflow) %>% update(cost = cost(c(-10, 4))) set.seed(2494) two_class_grid <- two_class_set %>% grid_max_entropy(size = 5) class_only <- metric_set(accuracy, kap, mcc) svm_results <- tune_grid( two_class_wflow, resamples = data_folds, grid = two_class_grid, metrics = class_only, control = control_grid(save_pred = TRUE) ) saveRDS( svm_results, file = testthat::test_path("svm_results.rds"), version = 2, compress = "xz" ) two_class_reg_grid <- two_class_set %>% grid_regular(levels = c(5, 4, 2)) svm_reg_results <- tune_grid( two_class_wflow, resamples = data_folds, grid = two_class_reg_grid, metrics = class_only, control = control_grid(save_pred = TRUE) ) saveRDS( svm_reg_results, file = testthat::test_path("svm_reg_results.rds"), version = 2, compress = "xz" ) set.seed(7898) data_folds <- vfold_cv(mtcars, repeats = 2) base_rec <- recipe(mpg ~ ., data = mtcars) %>% step_normalize(all_predictors()) disp_rec <- base_rec %>% step_bs(disp, degree = tune(), deg_free = tune()) %>% step_bs(wt, degree = tune("wt degree"), deg_free = tune("wt df")) lm_model <- linear_reg(mode = "regression") %>% set_engine("lm") cars_wflow <- workflow() %>% add_recipe(disp_rec) %>% add_model(lm_model) cars_set <- cars_wflow %>% parameters %>% update(degree = degree_int(1:2)) %>% update(deg_free = deg_free(c(2, 10))) %>% update(`wt degree` = degree_int(1:2)) %>% update(`wt df` = deg_free(c(2, 10))) set.seed(255) cars_grid <- cars_set %>% grid_regular(levels = c(3, 2, 3, 2)) rcv_results <- tune_grid( cars_wflow, resamples = data_folds, grid = cars_grid, control = control_grid(verbose = FALSE, save_pred = TRUE) ) saveRDS( rcv_results, file = testthat::test_path("rcv_results.rds"), version = 2, compress = "xz" ) set.seed(6735) folds <- vfold_cv(mtcars, v = 3) rec <- recipe(mpg ~ ., data = mtcars) mod <- linear_reg() %>% set_engine("lm") lm_resamples <- fit_resamples(mod, rec, folds) lm_resamples saveRDS( lm_resamples, file = testthat::test_path("lm_resamples.rds"), version = 2, compress = "xz" ) set.seed(7898) folds <- vfold_cv(mtcars, v = 2) rec <- recipe(mpg ~ ., data = mtcars) %>% step_normalize(all_predictors()) %>% step_ns(disp, deg_free = tune()) mod <- linear_reg(mode = "regression") %>% set_engine("lm") wflow <- workflow() %>% add_recipe(rec) %>% add_model(mod) set.seed(2934) lm_bayes <- tune_bayes(wflow, folds, initial = 4, iter = 3) saveRDS( lm_bayes, file = testthat::test_path("lm_bayes.rds"), version = 2, compress = "xz" ) sessioninfo::session_info() if (!interactive()) { q("no") }
bvecpost <- function(object) { if (object[["model"]][["tvp"]]) { object <- .bvectvpalg(object) } else { object <- .bvecalg(object) } k <- NCOL(object[["data"]][["Y"]]) p <- object[["model"]][["endogen"]][["lags"]] s <- 0 tt <- NROW(object[["data"]][["Y"]]) r <- object[["model"]][["rank"]] if (!is.null(object[["posteriors"]][["sigma"]][["lambda"]])) { sigma_lambda <- matrix(diag(NA_real_, k), k * k, object[["model"]][["iterations"]]) sigma_lambda[which(lower.tri(diag(1, k))), ] <- object[["posteriors"]][["sigma"]][["lambda"]] sigma_lambda[which(upper.tri(diag(1, k))), ] <- object[["posteriors"]][["sigma"]][["lambda"]] object[["posteriors"]][["sigma"]][["lambda"]] <- sigma_lambda rm(sigma_lambda) } A0 <- NULL if (object[["model"]][["structural"]]) { pos <- which(lower.tri(diag(1, k))) draws <- object[["model"]][["iterations"]] if (is.list(object$posteriors[["a0"]])) { if ("coeffs" %in% names(object[["posteriors"]][["a0"]])) { if (object[["model"]][["tvp"]]) { A0[["coeffs"]] <- matrix(diag(1, k), k * k * tt, object[["model"]][["iterations"]]) A0[["coeffs"]][rep(0:(tt - 1) * k * k, each = length(pos)) + rep(pos, tt), ] <- object[["posteriors"]][["a0"]][["coeffs"]] } else { A0[["coeffs"]] <- matrix(diag(1, k), k * k, object[["model"]][["iterations"]]) A0[["coeffs"]][rep(0:(draws - 1) * k * k, each = length(pos)) + pos ] <- object[["posteriors"]][["a0"]][["coeffs"]] } } if ("sigma" %in% names(object[["posteriors"]][["a0"]])) { A0[["sigma"]] <- matrix(0, k * k, object[["model"]][["iterations"]]) A0[["sigma"]][pos, ] <- object[["posteriors"]][["a0"]][["sigma"]] } if ("lambda" %in% names(object[["posteriors"]][["a0"]])) { A0[["lambda"]] <- matrix(diag(1, k), k * k, object[["model"]][["iterations"]]) A0[["lambda"]][pos, ] <- object[["posteriors"]][["a0"]][["lambda"]] A0[["lambda"]][-pos, ] <- NA_real_ } } else { A0 <- matrix(diag(1, k), k * k, object[["model"]][["iterations"]]) A0[pos, ] <- object[["posteriors"]][["a0"]] } } tsp_temp <- stats::tsp(object[["data"]][["Y"]]) w <- stats::ts(as.matrix(object[["data"]][["W"]][, 1:k]), class = c("mts", "ts", "matrix")) stats::tsp(w) <- tsp_temp dimnames(w)[[2]] <- dimnames(object[["data"]][["W"]])[[2]][1:k] m <- 0 if (!is.null(object[["model"]][["exogen"]])) { m <- length(object[["model"]][["exogen"]][["variables"]]) w_x <- stats::ts(as.matrix(object[["data"]][["W"]][, k + 1:m]), class = c("mts", "ts", "matrix")) stats::tsp(w_x) <- tsp_temp dimnames(w_x)[[2]] <- dimnames(object[["data"]][["W"]])[[2]][k + 1:m] } else { w_x <- NULL } if (!is.null(object[["model"]][["deterministic"]][["restricted"]])) { n_r <- length(object[["model"]][["deterministic"]][["restricted"]]) w_d <- stats::ts(as.matrix(object[["data"]][["W"]][, k + m + 1:n_r]), class = c("mts", "ts", "matrix")) stats::tsp(w_d) <- tsp_temp dimnames(w_d)[[2]] <- dimnames(object[["data"]][["W"]])[[2]][k + m + n_r] } else { w_d <- NULL } x <- NULL x_x <- NULL x_d <- NULL if (!is.null(object[["data"]][["X"]])) { if (!is.null(object[["model"]][["endogen"]])) { if (object[["model"]][["endogen"]][["lags"]] > 1) { x <- stats::ts(as.matrix(object[["data"]][["X"]][, 1:(k * (p - 1))]), class = c("mts", "ts", "matrix")) stats::tsp(x) <- tsp_temp dimnames(x)[[2]] <- dimnames(object[["data"]][["X"]])[[2]][1:(k * (p - 1))] } } if (!is.null(object[["model"]][["exogen"]])) { s <- object[["model"]][["exogen"]][["lags"]] x_x <- stats::ts(as.matrix(object[["data"]][["X"]][, k * (p - 1) + 1:(m * s)]), class = c("mts", "ts", "matrix")) stats::tsp(x_x) <- tsp_temp dimnames(x_x)[[2]] <- dimnames(object[["data"]][["X"]])[[2]][(k * (p - 1)) + 1:(m * s)] } if (!is.null(object[["model"]][["deterministic"]][["unrestricted"]])) { n_ur <- length(object[["model"]][["deterministic"]][["unrestricted"]]) x_d <- stats::ts(as.matrix(object[["data"]][["X"]][, k * (p - 1) + m * s + 1:n_ur]), class = c("mts", "ts", "matrix")) stats::tsp(x_d) <- tsp_temp dimnames(x_d)[[2]] <- dimnames(object[["data"]][["X"]])[[2]][k * (p - 1) + m * s + 1:n_ur] } } object <- bvec(y = object[["data"]][["Y"]], w = w, w_x = w_x, w_d = w_d, alpha = object[["posteriors"]][["alpha"]], beta = object[["posteriors"]][["beta"]], beta_x = object[["posteriors"]][["beta_x"]], beta_d = object[["posteriors"]][["beta_d"]], Pi = NULL, Pi_x = NULL, Pi_d = NULL, x = x, x_x = x_x, x_d = x_d, r = r, A0 = A0, Gamma = object[["posteriors"]][["gamma"]], Upsilon = object[["posteriors"]][["upsilon"]], C = object[["posteriors"]][["c"]], Sigma = object[["posteriors"]][["sigma"]], data = NULL, exogen = NULL) return(object) }
simulate.ergmm<-function(object, nsim=1, seed=NULL,...){ extraneous.argcheck(...) old.seed <- .save_set_seed(seed) l<-list() for(i in seq_len(nsim)){ iter<-floor(runif(1,1,object[["control"]][["sample.size"]]+1)) l[[i]]<-sim.1.ergmm(object[["model"]],object[["sample"]][[iter]],object[["prior"]]) } .restore_set_seed(old.seed) if(nsim > 1){ l <- list(formula = object[["model"]][["formula"]], networks = l, stats = NULL, coef=NULL) attr(l,"class")<-"network.list" }else{ l <- l[[1]] } return(l) } simulate.ergmm.model<-function(object,nsim=1,seed=NULL,par,prior=list(),...){ extraneous.argcheck(...) old.seed <- .save_set_seed(seed) l<-list() for(i in seq_len(nsim)){ l[[i]]<-sim.1.ergmm(object,par,prior) } .restore_set_seed(old.seed) if(nsim==1) return(l[[1]]) else{ attr(l,"class")<-"network.list" return(l) } } sim.1.ergmm<-function(model,par,prior=list()){ nv<-network.size(model[["Yg"]]) mypar<-par if(length(model[["X"]])>0 && is.null(mypar[["beta"]])) mypar[["beta"]]<-rnorm(length(model[["X"]]),prior[["beta.mean"]],sqrt(prior[["beta.var"]])) if(model[["d"]]>0 && is.null(mypar[["Z"]])){ if(model[["G"]]>0){ if(is.null(mypar[["Z.mean"]])) mypar[["Z.mean"]]<-matrix(rnorm(model[["G"]]*model[["d"]],0,sqrt(prior[["Z.mean.var"]])),nrow=model[["G"]]) if(is.null(mypar[["Z.K"]])) mypar[["Z.K"]]<-sample(seq_len(model[["G"]]),nv,replace=TRUE) } if(is.null(mypar[["Z.var"]])) mypar[["Z.var"]]<-prior[["Z.var"]]*prior[["Z.var.df"]]/rchisq(max(model[["G"]],1),prior[["Z.var.df"]]) mypar[["Z"]]<-matrix(rnorm(nv*model[["d"]], if(model[["G"]]>0) mypar[["Z.mean"]][mypar[["Z.K"]],] else 0, if(model[["G"]]>0) mypar[["Z.var"]][mypar[["Z.K"]]] else mypar[["Z.var"]] ),nrow=nv) } if(model[["sociality"]] && is.null(mypar[["sociality"]])){ if(is.null(mypar[["sociality.var"]])) mypar[["sociality.var"]]<-with(prior,sociality.var*sociality.var.df/rchisq(1,sociality.var.df)) model[["sociality"]]<-rnorm(nv,0,sqrt(mypar[["sociality.var"]])) } if(model[["sender"]] && is.null(mypar[["sender"]])){ if(is.null(mypar[["sender.var"]])) mypar[["sender.var"]]<-with(prior,sender.var*sender.var.df/rchisq(1,sender.var.df)) mypar[["sender"]]<-rnorm(nv,0,sqrt(mypar[["sender.var"]])) } if(model[["receiver"]] && is.null(mypar[["receiver"]])){ if(is.null(mypar[["receiver.var"]])) mypar[["receiver.var"]]<-with(prior,receiver.var*receiver.var.df/rchisq(1,receiver.var.df)) mypar[["receiver"]]<-rnorm(nv,0,sqrt(mypar[["receiver.var"]])) } if(model[["dispersion"]] && is.null(mypar[["dispersion"]])){ mypar[["dispersion"]]<-with(prior,dispersion*dispersion.df/rchisq(1,dispersion.df)) } eta<-ergmm.eta(model,mypar) sm<-rsm.fs[[model[["familyID"]]]](eta,dispersion=mypar[["dispersion"]],fam.par=model[["fam.par"]]) if(!has.loops(model[["Yg"]])) diag(sm)<-0 net<-with(model,as.network.matrix(sm,matrix.type="adjacency", directed=is.directed(Yg), loops=has.loops(Yg))) if(!is.null(model[["response"]])) net<-set.edge.value(net,model[["response"]],sm) attr(net,"ergmm.par")<-mypar net }
"test.W" <- function(Y, nb, xy, MEM.autocor = c("all", "positive", "negative"), f = NULL, ...) { .Deprecated(new = "listw.select", package = "adespatial", msg = "This function is now deprecated. Please try the new 'listw.select' function.") mycall <- pairlist(...) res <- list() MEM.autocor <- match.arg(MEM.autocor) if (!(is.null(f))) { nbdist <- nbdists(nb, as.matrix(xy)) if (!(is.null(mycall))) { param <- expand.grid(as.list(mycall)) m1 <- match(names(param), names(formals(f))) for (i in 1:nrow(param)) { formals(f)[m1] <- unclass(param[i,]) res[[i]] <- scores.listw(nb2listw( nb, style = "B", glist = lapply(nbdist, f), zero.policy = TRUE ), MEM.autocor = MEM.autocor) } } else { res[[1]] <- scores.listw(nb2listw(nb, style = "B", glist = lapply(nbdist, f)), MEM.autocor = MEM.autocor) } } else { res[[1]] <- scores.listw(nb2listw(nb, style = "B"), MEM.autocor = MEM.autocor) } res2 <- lapply(res, function(x) ortho.AIC( Y = Y, X = x, ord.var = TRUE )) if (!(is.null(mycall))) { res3 <- data.frame(AICc = unlist(lapply(res2, function(x) min(x[[1]], na.rm = TRUE))), NbVar = unlist(lapply(res2, function(x) which.min(x[[1]])))) res3 <- cbind(param, res3) } else{ res3 <- data.frame(AICc = unlist(lapply(res2, function(x) min(x[[1]], na.rm = TRUE))), NbVar = unlist(lapply(res2, function(x) which.min(x[[1]])))) } thebest <- which.min(res3$AICc) cat (paste("\n\nAICc for the null model:", res2[[thebest]]$AICc0, "\n")) cat ("\nBest spatial model:\n") print(res3[thebest,]) return(list(all = res3, best = list(MEM = res[[thebest]], AIC = res2[[thebest]]))) }
test_that("translate_Vensim_graph_func() returns the expected object", { test_equation <- "WITHLOOKUP(Price,([(0,10)-(50,100)],(5,100),(10,73),(15,57),(20,45),(25,35),(30,28),(35,22),(40,18),(45,14),(50,10)))" actual_obj <- translate_Vensim_graph_func(test_equation) expected_obj <- list( input = "Price", graph_fun = approxfun( x = seq(5, 50, 5), y = c(100, 73, 57, 45, 35, 28, 22, 18, 14, 10), method = "linear", yleft = 100, yright = 10)) comparison_result <- all.equal(actual_obj, expected_obj, check.environment = FALSE) expect_equal(comparison_result, TRUE) }) test_that("translate_graph_func() returns the expected object", { test_gf_xml <- xml2::read_xml(' <root> <doc1 xmlns = "http://docs.oasis-open.org/xmile/ns/XMILE/v1.0"> <aux name="demand price schedule"> <eqn>Price</eqn> <gf> <xscale min="5" max="50"/> <yscale min="0" max="2"/> <ypts>100,73,57,45,35,28,22,18,14,10</ypts> </gf> </aux> </doc1> </root>')%>% xml2::xml_find_first(".//d1:gf") actual_obj <- translate_graph_func(test_gf_xml) expected_obj <- approxfun( x = seq(5, 50, 5), y = c(100, 73, 57, 45, 35, 28, 22, 18, 14, 10), method = "linear", yleft = 100, yright = 10) comparison_result <- all.equal(actual_obj, expected_obj) expect_equal(comparison_result, TRUE) })
write_out_table<-function(table,table_name,outdir, relevant_table_columns){ if(!"id" %in% relevant_table_columns){ relevant_table_columns<-c(relevant_table_columns, "id") } if(!"table_name" %in% relevant_table_columns){ relevant_table_columns<-c(relevant_table_columns, "id", "table_name") } if(!any(c("id", "table_name") %in% names(table))){ PEcAn.logger::logger.severe("table provided doesn't have a table_name or id column or both. ") } table<-table[ , (relevant_table_columns)] write.table(table, file=paste(outdir,"/query_of_",table_name ,sep=""),row.names = FALSE,sep="|") }
NULL library(grid) library(gridBase) c_gpar <- function(gp, ...){ x <- list(...) do.call(gpar, c(gp, x[!names(x) %in% names(gp)])) } lo <- function (rown, coln, nrow, ncol, cellheight = NA, cellwidth = NA , treeheight_col, treeheight_row, legend, main = NULL, sub = NULL, info = NULL , annTracks, annotation_legend , fontsize, fontsize_row, fontsize_col, gp = gpar()){ annotation_colors <- annTracks$colors row_annotation <- annTracks$annRow annotation <- annTracks$annCol gp0 <- gp coln_height <- unit(10, "bigpts") if(!is.null(coln)){ longest_coln = which.max(nchar(coln)) coln_height <- coln_height + unit(1.1, "grobheight", textGrob(coln[longest_coln], rot = 90, gp = c_gpar(gp, fontsize = fontsize_col))) } rown_width <- rown_width_min <- unit(10, "bigpts") if(!is.null(rown)){ longest_rown = which.max(nchar(rown)) rown_width <- rown_width_min + unit(1.2, "grobwidth", textGrob(rown[longest_rown], gp = c_gpar(gp, fontsize = fontsize_row))) } gp = c_gpar(gp, fontsize = fontsize) if( !is_NA(legend) ){ longest_break = which.max(nchar(as.character(legend))) longest_break = unit(1.1, "grobwidth", textGrob(as.character(legend)[longest_break], gp = gp)) min_lw = unit(1.1, "grobwidth", textGrob("-00.00", gp = gp)) longest_break = max(longest_break, min_lw) title_length = unit(1.1, "grobwidth", textGrob("Scale", gp = c_gpar(gp0, fontface = "bold"))) legend_width = unit(12, "bigpts") + longest_break * 1.2 legend_width = max(title_length, legend_width) } else{ legend_width = unit(0, "bigpts") } .annLegend.dim <- function(annotation, fontsize){ longest_ann <- unlist(lapply(annotation, names)) longest_ann <- longest_ann[which.max(nchar(longest_ann))] annot_legend_width = unit(1, "grobwidth", textGrob(longest_ann, gp = gp)) + unit(10, "bigpts") annot_legend_title <- names(annotation)[which.max(nchar(names(annotation)))] annot_legend_title_width = unit(1, "grobwidth", textGrob(annot_legend_title, gp = c_gpar(gp, fontface = "bold"))) max(annot_legend_width, annot_legend_title_width) + unit(5, "bigpts") } if( !is_NA(annotation) ){ annot_height = unit(ncol(annotation) * (8 + 2) + 2, "bigpts") } else{ annot_height = unit(0, "bigpts") } if ( !is_NA(row_annotation) ) { row_annot_width = unit(ncol(row_annotation) * (8 + 2) + 2, "bigpts") } else { row_annot_width = unit(0, "bigpts") } annot_legend_width <- if( annotation_legend && !is_NA(annotation_colors) ){ .annLegend.dim(annotation_colors, fontsize) }else unit(0, "bigpts") treeheight_col = unit(treeheight_col, "bigpts") + unit(5, "bigpts") treeheight_row = unit(treeheight_row, "bigpts") + unit(5, "bigpts") main_height <- if(!is.null(main)) unit(1, "grobheight", main) + unit(20, "bigpts") else unit(0, "bigpts") sub_height <- if(!is.null(sub)) unit(1, "grobheight", sub) + unit(10, "bigpts") else unit(0, "bigpts") if( !is.null(info) ){ info_height <- unit(1, "grobheight", info) + unit(20, "bigpts") info_width <- unit(1, "grobwidth", info) + unit(10, "bigpts") }else{ info_height <- unit(0, "bigpts") info_width <- unit(0, "bigpts") } if(is.na(cellwidth)){ matwidth = unit(1, "npc") - rown_width - legend_width - row_annot_width - treeheight_row - annot_legend_width } else{ matwidth = unit(cellwidth * ncol, "bigpts") } if(is.na(cellheight)){ matheight = unit(1, "npc") - treeheight_col - annot_height - main_height - coln_height - sub_height - info_height if( is.na(cellwidth) && !is.null(rown) ){ cellheight <- convertHeight(unit(1, "grobheight", rectGrob(0,0, matwidth, matheight)), "bigpts", valueOnly = T) / nrow fontsize_row <- convertUnit(min(unit(fontsize_row, 'points'), unit(0.6*cellheight, 'bigpts')), 'points') rown_width <- rown_width_min + unit(1.2, "grobwidth", textGrob(rown[longest_rown], gp = c_gpar(gp0, fontsize = fontsize_row))) matwidth <- unit(1, "npc") - rown_width - legend_width - row_annot_width - treeheight_row - annot_legend_width } } else{ matheight = unit(cellheight * nrow, "bigpts") } unique.name <- vplayout(NULL) lo <- grid.layout(nrow = 7, ncol = 6 , widths = unit.c(treeheight_row, row_annot_width, matwidth, rown_width, legend_width, annot_legend_width) , heights = unit.c(main_height, treeheight_col, annot_height, matheight, coln_height, sub_height, info_height)) hvp <- viewport( name=paste('aheatmap', unique.name, sep='-'), layout = lo) pushViewport(hvp) vplayout('mat') cellwidth = convertWidth(unit(1, "npc"), "bigpts", valueOnly = T) / ncol cellheight = convertHeight(unit(1, "npc"), "bigpts", valueOnly = T) / nrow upViewport() height <- as.numeric(convertHeight(sum(lo$height), "inches")) width <- as.numeric(convertWidth(sum(lo$width), "inches")) mindim = min(cellwidth, cellheight) return( list(width=width, height=height, vp=hvp, mindim=mindim, cellwidth=cellwidth, cellheight=cellheight) ) } draw_dendrogram = function(hc, horizontal = T){ .draw.dendrodram <- function(hc, ...){ ( opar <- par(plt = gridPLT(), new = TRUE) ) on.exit(par(opar)) if( getOption('verbose') ) grid.rect(gp = gpar(col = "blue", lwd = 2)) if( !is(hc, 'dendrogram') ) hc <- as.dendrogram(hc) plot(hc, horiz=!horizontal, xaxs="i", yaxs="i", axes=FALSE, leaflab="none", ...) } if(!horizontal) pushViewport( viewport(x=0,y=0,width=0.9,height=1,just=c("left", "bottom")) ) else pushViewport( viewport(x=0,y=0.1,width=1,height=0.9,just=c("left", "bottom")) ) on.exit(upViewport()) .draw.dendrodram(hc) } draw_matrix = function(matrix, border_color, txt = NULL, gp = gpar()){ n = nrow(matrix) m = ncol(matrix) x = (1:m)/m - 1/2/m y = (1:n)/n - 1/2/n if( !is.null(txt) ) txt[is.na(txt)] <- '' for(i in 1:m){ grid.rect(x = x[i], y = y, width = 1/m, height = 1/n, gp = gpar(fill = matrix[,i], col = border_color)) if( !is.null(txt) ){ grid.text(label=txt[, i], x=x[i], y=y, rot=0, check.overlap= FALSE, default.units= 'npc', gp=gp, ) } } } draw_colnames = function(coln, gp = gpar()){ m = length(coln) width <- m * unit(1, "grobwidth", textGrob(coln[i <- which.max(nchar(coln))], gp = gp)) width <- as.numeric(convertWidth(width, "inches")) gwidth <- as.numeric(convertWidth(unit(1, 'npc'), "inches")) y <- NULL if( gwidth < width ){ rot <- 270 vjust <- 0.5 hjust <- 0 y <- unit(1, 'npc') - unit(5, 'bigpts') }else{ rot <- 0 vjust <- 0.5 hjust <- 0.5 } if( is.null(y) ){ height <- unit(1, "grobheight", textGrob(coln[i], vjust = vjust, hjust = hjust, rot=rot, gp = gp)) y <- unit(1, 'npc') - height } x = (1:m)/m - 1/2/m grid.text(coln, x = x, y = y, vjust = vjust, hjust = hjust, rot=rot, gp = gp) } draw_rownames = function(rown, gp = gpar()){ n = length(rown) y = (1:n)/n - 1/2/n grid.text(rown, x = unit(5, "bigpts"), y = y, vjust = 0.5, hjust = 0, gp = gp) } draw_legend = function(color, breaks, legend, gp = gpar()){ height = min(unit(1, "npc"), unit(150, "bigpts")) pushViewport(viewport(x = 0, y = unit(1, "npc"), just = c(0, 1), height = height)) legend_pos = (legend - min(breaks)) / (max(breaks) - min(breaks)) breaks = (breaks - min(breaks)) / (max(breaks) - min(breaks)) h = breaks[-1] - breaks[-length(breaks)] grid.rect(x = 0, y = breaks[-length(breaks)], width = unit(10, "bigpts"), height = h, hjust = 0, vjust = 0, gp = gpar(fill = color, col = " grid.text(legend, x = unit(12, "bigpts"), y = legend_pos, hjust = 0, gp = gp) upViewport() } convert_annotations = function(annotation, annotation_colors){ x <- sapply(seq_along(annotation), function(i){ a = annotation[[i]] b <- attr(a, 'color') if( is.null(b) ) b = annotation_colors[[names(annotation)[i]]] if(class(a) %in% c("character", "factor")){ a = as.character(a) if ( FALSE && length(setdiff(names(b), a)) > 0){ stop(sprintf("Factor levels on variable %s do not match with annotation_colors", names(annotation)[i])) } b[match(a, names(b))] } else{ a = cut(a, breaks = 100) ccRamp(b, 100)[a] } }) colnames(x) <- names(annotation) return(x) } draw_annotations = function(converted_annotations, border_color, horizontal=TRUE){ n = ncol(converted_annotations) m = nrow(converted_annotations) if( horizontal ){ x = (1:m)/m - 1/2/m y = cumsum(rep(8, n)) - 4 + cumsum(rep(2, n)) for(i in 1:m){ grid.rect(x = x[i], unit(y[n:1], "bigpts"), width = 1/m, height = unit(8, "bigpts"), gp = gpar(fill = converted_annotations[i, ], col = border_color)) } }else{ x = cumsum(rep(8, n)) - 4 + cumsum(rep(2, n)) y = (1:m)/m - 1/2/m for (i in 1:m) { grid.rect(x = unit(x[1:n], "bigpts"), y=y[i], width = unit(8, "bigpts"), height = 1/m, gp = gpar(fill = converted_annotations[i,] , col = border_color)) } } } draw_annotation_legend = function(annotation_colors, border_color, gp = gpar()){ y = unit(1, "npc") text_height = convertHeight(unit(1, "grobheight", textGrob("FGH", gp = gp)), "bigpts") for(i in names(annotation_colors)){ grid.text(i, x = 0, y = y, vjust = 1, hjust = 0, gp = c_gpar(gp, fontface = "bold")) y = y - 1.5 * text_height acol <- annotation_colors[[i]] if( attr(acol, 'afactor') ){ sapply(seq_along(acol), function(j){ grid.rect(x = unit(0, "npc"), y = y, hjust = 0, vjust = 1, height = text_height, width = text_height, gp = gpar(col = border_color, fill = acol[j])) grid.text(names(acol)[j], x = text_height * 1.3, y = y, hjust = 0, vjust = 1, gp = gp) y <<- y - 1.5 * text_height }) } else{ yy = y - 4 * text_height + seq(0, 1, 0.01) * 4 * text_height h = 4 * text_height * 0.02 grid.rect(x = unit(0, "npc"), y = yy, hjust = 0, vjust = 1, height = h, width = text_height, gp = gpar(col = " txt = c(tail(names(acol),1), head(names(acol))[1]) yy = y - c(0, 3) * text_height grid.text(txt, x = text_height * 1.3, y = yy, hjust = 0, vjust = 1, gp = gp) y = y - 4.5 * text_height } y = y - 1.5 * text_height } } vplayout <- function () { graphic.name <- NULL .index <- 0L function(x, y, verbose = getOption('verbose') ){ if( is.null(x) ){ .index <<- .index + 1L graphic.name <<- paste0("AHEATMAP.VP.", .index) return(graphic.name) } name <- NULL if( !is.numeric(x) ){ name <- paste(graphic.name, x, sep='-') if( !missing(y) && is(y, 'viewport') ){ y$name <- name return(pushViewport(y)) } if( !is.null(tryViewport(name, verbose=verbose)) ) return() switch(x , main={x<-1; y<-3;} , ctree={x<-2; y<-3;} , cann={x<-3; y<-3;} , rtree={x<-4; y<-1;} , rann={x<-4; y<-2;} , mat={x<-4; y<-3;} , rnam={x<-4; y<-4;} , leg={x<-4; y<-5;} , aleg={x<-4; y<-6;} , cnam={x<-5; y<-3;} , sub={x<-6; y<-3;} , info={x<-7; y<-3;} , stop("aheatmap - invalid viewport name") ) } if( verbose ) message("vp - create ", name) pushViewport(viewport(layout.pos.row = x, layout.pos.col = y, name=name)) } } vplayout <- vplayout() gfile <- function(filename, width, height, ...){ r = regexpr("\\.[a-zA-Z]*$", filename) if(r == -1) stop("Improper filename") ending = substr(filename, r + 1, r + attr(r, "match.length")) f = switch(ending, pdf = function(x, ...) pdf(x, ...), svg = function(x, ...) svg(x, ...), png = function(x, ...) png(x, ...), jpeg = function(x, ...) jpeg(x, ...), jpg = function(x, ...) jpeg(x, ...), tiff = function(x, ...) tiff(x, compression = "lzw", ...), bmp = function(x, ...) bmp(x, ...), stop("File type should be: pdf, svg, png, bmp, jpg, tiff") ) args <- c(list(filename), list(...)) if( !missing(width) ){ args$width <- as.numeric(width) args$height <- as.numeric(height) if( !ending %in% c('pdf','svg') && is.null(args[['res']]) ){ args$units <- "in" args$res <- 300 } } do.call('f', args) } d <- function(x){ if( is.character(x) ) x <- rmatrix(dim(x)) nvp <- 0 on.exit(upViewport(nvp), add=TRUE) lo <- grid.layout(nrow = 4, ncol = 3) hvp <- viewport( name=basename(tempfile()), layout = lo) pushViewport(hvp) nvp <- nvp + 1 pushViewport(viewport(layout.pos.row = 2, layout.pos.col = 1)) nvp <- nvp + 1 w = convertWidth(unit(1, "npc"), "bigpts", valueOnly = T) / 10 h = convertHeight(unit(1, "npc"), "bigpts", valueOnly = T) / 10 grid.rect() upViewport() nvp <- nvp - 1 pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 2)) nvp <- nvp + 1 pushViewport( viewport(x=0,y=0,width=0.9,height=0.9,just=c("left", "bottom")) ) nvp <- nvp + 1 ( opar <- par(plt = gridPLT(), new = TRUE) ) on.exit(par(opar), add=TRUE) hc <- hclust(dist(x)) plot(as.dendrogram(hc), xaxs="i", yaxs="i", axes=FALSE, leaflab="none") invisible(basename(tempfile())) } heatmap_motor = function(matrix, border_color, cellwidth, cellheight , tree_col, tree_row, treeheight_col, treeheight_row , filename=NA, width=NA, height=NA , breaks, color, legend, txt = NULL , annTracks, annotation_legend=TRUE , new=TRUE, fontsize, fontsize_row, fontsize_col , main=NULL, sub=NULL, info=NULL , verbose=getOption('verbose') , gp = gpar()){ annotation_colors <- annTracks$colors row_annotation <- annTracks$annRow annotation <- annTracks$annCol writeToFile <- !is.na(filename) if( writeToFile ){ gfile(filename) on.exit(dev.off()) } vpp <- current.vpPath_patched() if( is.null(vpp) ){ if( verbose ) message("Detected path: [ROOT]") mf <- par('mfrow') new <- if( !identical(mf, c(1L,1L)) ){ if( verbose ) message("Detected mfrow: ", mf[1], " - ", mf[2], ' ... MIXED') opar <- grid.base.mix(trace=verbose>1) on.exit( grid.base.mix(opar) ) FALSE } else{ if( verbose ){ message("Detected mfrow: ", mf[1], " - ", mf[2]) message("Honouring ", if( missing(new) ) "default " ,"argument `new=", new, '` ... ' , if( new ) "NEW" else "OVERLAY") } new } }else{ if( verbose ) message("Detected path: ", vpp) if( missing(new) ){ if( verbose ) message("Missing argument `new` ... OVERLAY") new <- FALSE }else if( verbose ) message("Honouring argument `new=", new, '` ... ' , if( new ) "NEW" else "OVERLAY") } if( new ){ if( verbose ) message("Call: plot.new") plot.new() } mainGrob <- if( !is.null(main) && !is.grob(main) ) textGrob(main, gp = c_gpar(gp, fontsize = 1.2 * fontsize, fontface="bold")) subGrob <- if( !is.null(sub) && !is.grob(sub) ) textGrob(sub, gp = c_gpar(gp, fontsize = 0.8 * fontsize)) infoGrob <- if( !is.null(info) && !is.grob(info) ){ grobTree(gList(rectGrob(gp = gpar(fill = "grey80")) ,textGrob(paste(info, collapse=" | "), x=unit(5, 'bigpts'), y=0.5, just='left', gp = c_gpar(gp, fontsize = 0.8 * fontsize)))) } glo = lo(coln = colnames(matrix), rown = rownames(matrix), nrow = nrow(matrix), ncol = ncol(matrix) , cellwidth = cellwidth, cellheight = cellheight , treeheight_col = treeheight_col, treeheight_row = treeheight_row , legend = legend , annTracks = annTracks, annotation_legend = annotation_legend , fontsize = fontsize, fontsize_row = fontsize_row, fontsize_col = fontsize_col , main = mainGrob, sub = subGrob, info = infoGrob, gp = gp) if( writeToFile ){ if( verbose ) message("Compute size for file graphic device") m <- par('mar') if(is.na(height)) height <- glo$height if(is.na(width)) width <- glo$width dev.off() if( verbose ) message("Resize file graphic device to: ", width, " - ", height) gfile(filename, width=width, height=height) if( new ){ if( verbose ) message("Call again plot.new") op <- par(mar=c(0,0,0,0)) plot.new() par(op) } if( verbose ) message("Push again top viewport") pushViewport(glo$vp) if( verbose ) grid.rect(width=unit(glo$width, 'inches'), height=unit(glo$height, 'inches'), gp = gpar(col='blue')) } mindim <- glo$mindim if(mindim < 3) border_color = NA if (!is_NA(tree_col) && treeheight_col != 0){ vplayout('ctree') draw_dendrogram(tree_col, horizontal = T) upViewport() } if(!is_NA(tree_row) && treeheight_row !=0){ vplayout('rtree') draw_dendrogram(tree_row, horizontal = F) upViewport() } fontsize_row <- convertUnit(min(unit(fontsize_row, 'points'), unit(0.6*glo$cellheight, 'bigpts')), 'points') fontsize_col <- convertUnit(min(unit(fontsize_col, 'points'), unit(0.6*glo$cellwidth, 'bigpts')), 'points') vplayout('mat') draw_matrix(matrix, border_color, txt = txt, gp = gpar(fontsize = fontsize_row)) upViewport() if(length(colnames(matrix)) != 0){ vplayout('cnam') draw_colnames(colnames(matrix), gp = c_gpar(gp, fontsize = fontsize_col)) upViewport() } if(length(rownames(matrix)) != 0){ vplayout('rnam') draw_rownames(rownames(matrix), gp = c_gpar(gp, fontsize = fontsize_row)) upViewport() } if( !is_NA(annotation) ){ vplayout('cann') draw_annotations(annotation, border_color) upViewport() } if ( !is_NA(row_annotation) ) { vplayout('rann') draw_annotations(row_annotation, border_color, horizontal=FALSE) upViewport() } if( annotation_legend && !is_NA(annotation_colors) ){ vplayout('aleg') draw_annotation_legend(annotation_colors, border_color, gp = c_gpar(gp, fontsize = fontsize)) upViewport() } if(!is_NA(legend)){ vplayout('leg') draw_legend(color, breaks, legend, gp = c_gpar(gp, fontsize = fontsize)) upViewport() } if(!is.null(mainGrob)){ vplayout('main') grid.draw(mainGrob) upViewport() } if(!is.null(subGrob)){ vplayout('sub') grid.draw(subGrob) upViewport() } if(!is.null(infoGrob)){ vplayout('info') grid.draw(infoGrob) upViewport() } upViewport() NULL } generate_breaks = function(x, n, center=NA){ if( missing(center) || is_NA(center) ) seq(min(x, na.rm = T), max(x, na.rm = T), length.out = n + 1) else{ n2 <- ceiling((n+0.5)/2) M <- max(abs(center - min(x, na.rm = TRUE)), abs(center - max(x, na.rm = TRUE))) lb <- seq(center-M, center, length.out = n2) rb <- seq(center, center+M, length.out = n2) c(lb, rb[-1]) } } scale_vec_colours = function(x, col = rainbow(10), breaks = NA){ return(col[as.numeric(cut(x, breaks = breaks, include.lowest = T))]) } scale_colours = function(mat, col = rainbow(10), breaks = NA){ mat = as.matrix(mat) return(matrix(scale_vec_colours(as.vector(mat), col = col, breaks = breaks), nrow(mat), ncol(mat), dimnames = list(rownames(mat), colnames(mat)))) } cutheight <- function(x, n){ if( n <=1 ) return( attr(x, 'height') ) res <- NULL .heights <- function(subtree, n){ if( is.leaf(subtree) ) return() if (!(K <- length(subtree))) stop("non-leaf subtree of length 0") for( k in 1:K){ res <<- c(res, attr(subtree[[k]], 'height')) } if( length(res) < n ){ for( k in 1:K){ .heights(subtree[[k]], n) } } } .heights(x, n) res <- sort(res, decreasing=TRUE) res[n-1] } cutdendro <- function(x, n){ if( n <= 1 ) return(x) x <- dendrapply(x, function(n){ attr(n, 'id') <- digest(attributes(n)) n }) h <- cutheight(x, n) cfx <- cut(x, h) ids <- sapply(cfx$lower, function(sub) attr(sub, 'id')) dts <- c(lty=2, lwd=1.2, col=8) a <- dendrapply(x, function(node){ a <- attributes(node) if( a$id %in% ids || (!is.leaf(node) && any(c(attr(node[[1]], 'id'), attr(node[[2]], 'id')) %in% ids)) ) attr(node, 'edgePar') <- dts node }) } as_treedef <- function(x, ...){ res <- if( is(x, 'hclust') ) list(dendrogram=as.dendrogram(x), dist.method=x$dist.method, method=x$method) else list(dendrogram=x, ...) class(res) <- "aheatmap_treedef" res } rev.aheatmap_treedef <- function(x){ x$dendrogram <- rev(x$dendrogram) x } is_treedef <- function(x) is(x, 'aheatmap_treedef') isLogical <- function(x) isTRUE(x) || identical(x, FALSE) subset2orginal_idx <- function(idx, subset){ if( is.null(subset) || is.null(idx) ) idx else{ res <- subset[idx] attr(res, 'subset') <- idx res } } cluster_mat = function(mat, param, distfun, hclustfun, reorderfun, na.rm=TRUE, subset=NULL, verbose = FALSE){ parg <- deparse(substitute(param)) Rowv <- if( is(param, 'hclust') || is(param, 'dendrogram') ){ res <- as_treedef(param) if( !is.null(subset) ){ warning("Could not directly subset dendrogram/hclust object `", parg ,"`: using subset of the dendrogram's order instead.") param <- order.dendrogram(res$dendrogram) }else return(res) }else if( is(param, 'silhouette') ){ si <- sortSilhouette(param) param <- attr(si, 'iOrd') } if( is.integer(param) && length(param) > 1 ){ if( !is.null(subset) ) param <- order(match(subset, param)) param }else{ param <- if( is.integer(param) ) param else if( is.null(param) || isLogical(param) ) rowMeans(mat, na.rm=na.rm) else if( is.numeric(param) ){ if( !is.null(subset) ) param <- param[subset] param }else if( is.character(param) || is.list(param) ){ if( length(param) == 0 ) stop("aheatmap - Invalid empty character argument `", parg, "`.") if( is.null(names(param)) ){ if( length(param) > 3 ){ warning("aheatmap - Only using the three first elements of `", parg, "` for distfun and hclustfun respectively.") param <- param[1:3] } n.allowed <- c('distfun', 'hclustfun', 'reorderfun') names(param) <- head(n.allowed, length(param)) } if( 'distfun' %in% names(param) ) distfun <- param[['distfun']] if( 'hclustfun' %in% names(param) ) hclustfun <- param[['hclustfun']] if( 'reorderfun' %in% names(param) ) reorderfun <- param[['reorderfun']] TRUE }else stop("aheatmap - Invalid value for argument `", parg, "`. See ?aheatmap.") d <- if( isString(distfun) ){ distfun <- distfun[1] corr.methods <- c("pearson", "kendall", "spearman") av <- c("correlation", corr.methods, "euclidean", "maximum", "manhattan", "canberra", "binary", "minkowski") i <- pmatch(distfun, av) if( is_NA(i) ) stop("aheatmap - Invalid dissimilarity method, must be one of: ", str_out(av, Inf)) distfun <- av[i] if(distfun == "correlation") distfun <- 'pearson' if(distfun %in% corr.methods){ if( verbose ) message("Using distance method: correlation (", distfun, ')') d <- dist(1 - cor(t(mat), method = distfun)) attr(d, 'method') <- distfun d }else{ if( verbose ) message("Using distance method: ", distfun) dist(mat, method = distfun) } }else if( is(distfun, "dist") ){ if( verbose ) message("Using dist object: ", distfun) distfun }else if( is.function(distfun) ){ if( verbose ) message("Using custom dist function") distfun(mat) }else stop("aheatmap - Invalid dissimilarity function: must be a character string, an object of class 'dist', or a function") hc <- if( is.character(hclustfun) ){ av <- c('ward', 'single', 'complete', 'average', 'mcquitty', 'median', 'centroid') i <- pmatch(hclustfun, av) if( is.na(i) ) stop("aheatmap - Invalid clustering method, must be one of: ", paste("'", av, "'", sep='', collapse=', ')) hclustfun <- av[i] if( verbose ) message("Using clustering method: ", hclustfun) hclust(d, method=hclustfun) }else if( is.function(hclustfun) ) hclustfun(d) else stop("aheatmap - Invalid clustering function: must be a character string or a function") dh <- as.dendrogram(hc) if( is.integer(param) ) dh <- cutdendro(dh, param) else if( is.numeric(param) && length(param)==nrow(mat) ) dh <- reorderfun(dh, param) as_treedef(dh, dist.method=hc$dist.method, method=hc$method) } } scale_mat = function(x, scale, na.rm=TRUE){ av <- c("none", "row", "column", 'r1', 'c1') i <- pmatch(scale, av) if( is_NA(i) ) stop("scale argument shoud take values: 'none', 'row' or 'column'") scale <- av[i] switch(scale, none = x , row = { x <- sweep(x, 1L, rowMeans(x, na.rm = na.rm), check.margin = FALSE) sx <- apply(x, 1L, sd, na.rm = na.rm) sweep(x, 1L, sx, "/", check.margin = FALSE) } , column = { x <- sweep(x, 2L, colMeans(x, na.rm = na.rm), check.margin = FALSE) sx <- apply(x, 2L, sd, na.rm = na.rm) sweep(x, 2L, sx, "/", check.margin = FALSE) } , r1 = sweep(x, 1L, rowSums(x, na.rm = na.rm), '/', check.margin = FALSE) , c1 = sweep(x, 2L, colSums(x, na.rm = na.rm), '/', check.margin = FALSE) ) } .Rd.seed <- new.env() round.pretty <- function(x, min=2){ if( is.null(x) ) return(NULL) n <- 0 y <- round(sort(x), n) if( all(diff(y)==0) ) return( round(x, min) ) while( any(diff(y)==0) ){ n <- n+1 y <- round(sort(x), n) } dec <- max(min,n) round(x, dec) } generate_annotation_colours = function(annotation, annotation_colors, seed=TRUE){ if( is_NA(annotation_colors) ){ annotation_colors = list() } if( length(annotation_colors) > 0L && length(annotation_colors) <= length(annotation) && is.null(names(annotation_colors)) ){ names(annotation_colors) <- head(names(annotation), length(annotation_colors)) } count = 0 annotationLevels <- list() anames <- names(annotation) sapply(seq_along(annotation), function(i){ a <- annotation[[i]] if( class(annotation[[i]]) %in% c("character", "factor")){ a <- if( is.factor(a) ) levels(a) else unique(a) count <<- count + nlevels(a) if( !is.null(anames) && anames[i]!='' ) annotationLevels[[anames[i]]] <<- unique(c(annotationLevels[[anames[i]]], a)) else annotationLevels <<- c(annotationLevels, list(a)) }else annotationLevels <<- c(annotationLevels, annotation[i]) }) annotation <- annotationLevels factor_colors = hcl(h = seq(1, 360, length.out = max(count+1,20)), 100, 70) rs <- RNGseed() on.exit({ .Rd.seed$.Random.seed <- getRNG() RNGseed(rs) }) if( !is.null(.Rd.seed$.Random.seed) ) setRNG(.Rd.seed$.Random.seed) if( isTRUE(seed) ){ setRNG(c(401L, 0L, 0L)) set.seed(12345, 'default', 'default') } factor_colors <- sample(factor_colors) res_colors <- list() for(i in 1:length(annotation)){ ann <- annotation[[i]] aname <- names(annotation)[i] acol_def <- res_colors[[aname]] if( !is.null(acol_def) ) next; acol <- annotation_colors[[aname]] if( is.null(acol) ){ res_colors[[aname]] <- if( class(annotation[[i]]) %in% c("character", "factor")){ lev <- ann ind = 1:length(lev) acol <- setNames(factor_colors[ind], lev) factor_colors = factor_colors[-ind] acol[which(is.na(names(acol)))] <- NA acol } else{ h = round(runif(1) * 360) rg <- range(ann, na.rm=TRUE) if( rg[1] == rg[2] ) rg <- sort(c(0, rg[1])) setNames(rev(sequential_hcl(2, h, l = c(50, 95))), round.pretty(rg)) } }else{ acol <- if( length(acol) == 1 && grepl("^\\$", acol) ) annotation_colors[[substr(acol, 2, nchar(acol))]] else if( !is.numeric(ann) ){ local({ lev <- ann { nl <- length(lev) acol <- ccPalette(acol, nl) if( is.null(names(acol)) ) names(acol) <- lev c(acol_def, acol) } }) }else{ acol <- ccPalette(acol) if( is.null(names(acol)) ) names(acol) <- round.pretty(seq(min(ann, na.rm=TRUE), max(ann, na.rm=TRUE), length.out=length(acol))) acol } if( !is.null(acol) ) res_colors[[aname]] <- acol } attr(res_colors[[aname]], 'afactor') <- !is.numeric(ann) } res_colors[names(annotation)[!duplicated(names(annotation))]] } generate_dimnames <- function(x, n, ref){ if( is_NA(x) ) NULL else if( length(x) == n ) x else if( identical(x, 1) || identical(x, 1L) ) 1L:n else if( isString(x) ){ regexp <- "^/(.+)/([0-9]+)?$" if( grepl(regexp, x) ){ x <- str_match(x, regexp) p <- x[1,2] n <- if( x[1, 3] != '' ) as.numeric(x[1, 2]) else 2L s <- str_match(ref, p)[, n] ifelse(is.na(s), ref, s) } else paste(x, 1L:n, sep='') } else stop("aheatmap - Invalid row/column label. Possible values are:" , " NA, a vector of correct length, value 1 (or 1L) or single character string.") } .make_annotation <- function(x, ord=NULL){ if( !is.data.frame(x) ){ x <- if( is(x, 'ExpressionSet') ) Biobase::pData(x) else if( is.factor(x) || is.character(x) ) data.frame(Factor=x) else if( is.numeric(x) ) data.frame(Variable=x) else stop("aheatmap - Invalid annotation argument `", substitute(x), "`: must be a data.frame, a factor or a numeric vector") } if( !is.null(ord) ) x <- x[ord, , drop = F] x } renderAnnotations <- function(annCol, annRow, annotation_colors, verbose=getOption('verbose')){ annotation <- list() if( is_NA(annotation_colors) ) annotation_colors <- list() nc <- length(annCol) nr <- length(annRow) flag <- function(x, f){ if( missing(f) ) attr(x, 'flag') else{ attr(x, 'flag') <- f; x} } if( !is_NA(annCol) ) annotation <- c(annotation, sapply(as.list(annCol), flag, 'col', simplify=FALSE)) if( !is_NA(annRow) ) annotation <- c(annotation, sapply(as.list(annRow), flag, 'row', simplify=FALSE)) if( length(annotation) == 0 ) return( list(annCol=NA, annRow=NA, colors=NA) ) n <- names(annotation) xnames <- paste('X', 1:length(annotation), sep='') if( is.null(n) ) names(annotation) <- xnames else names(annotation)[n==''] <- xnames[n==''] if( !is.null(cnames <- names(annotation_colors)) ){ m <- str_match(cnames, "^@([^{]+)\\{([^}]+)\\}") apply(m, 1L, function(x){ if( is_NA(x[1]) ) return() acol <- annotation_colors[[x[1]]] if( x[2] != x[3] ){ annotation[[x[3]]] <<- annotation[[x[2]]] annotation[[x[2]]] <<- NULL if( !is_NA(acol) ) annotation_colors[[x[3]]] <<- acol annotation_colors[[x[1]]] <<- NULL } }) } if( verbose ) message("Generate column annotation colours") annotation_colors <- generate_annotation_colours(annotation, annotation_colors) if( verbose > 2 ){ message(" print(annotation_colors) message(" } res <- list() lapply(seq_along(annotation), function(i){ aname <- names(annotation)[i] acol <- annotation_colors[[aname]] if( is.null(acol) ) stop("aheatmap - No color was defined for annotation '", aname, "'.") attr(annotation[[i]], 'color') <- acol if( flag(annotation[[i]]) == 'col' ) res$annCol <<- c(res$annCol, annotation[i]) else res$annRow <<- c(res$annRow, annotation[i]) }) res$annCol <- if( !is.null(res$annCol) ) convert_annotations(res$annCol, annotation_colors) else NA res$annRow <- if( !is.null(res$annRow) ) convert_annotations(res$annRow, annotation_colors) else NA res$colors <- annotation_colors res } specialAnnotation <- local({ .empty <- list(list(), list()) .cache <- .empty function(margin, name, fun, clear=FALSE){ if( isTRUE(clear) ){ if( nargs() > 1L ) stop("Invalid call: no other argument can be passed when `clear=TRUE`") .cache <<- .empty return() } if( missing(name) && missing(fun) ){ return(.cache[[margin]]) }else if( is.list(name) ){ .cache[[margin]] <<- c(.cache[[margin]], name) }else if( missing(fun) ){ return(.cache[[margin]][[name]]) }else{ .cache[[margin]][[name]] <<- fun } } }) subset_index <- function(x, margin, subset){ if( is.null(subset) ) return( NULL ) n <- dim(x)[margin] dn <- dimnames(x)[[margin]] dt <- if( margin == 1L ) "rows" else "columns" so <- deparse(substitute(subset)) if( length(subset) == 0 ) stop("Invalid empty subset object `", so, "`") subIdx <- if( is.logical(subset) ){ if( length(subset) != n ){ if( n %% length(subset) == 0 ) subset <- rep(subset, n / length(subset)) else stop("Invalid length for logical subset argument `", so, "`: number of ", dt, " [" , n, "] is not a multiple of subset length [",length(subset),"].") } which(subset) } else if( is.integer(subset) || is.character(subset) ){ if( length(subset) > n ) stop("Invalid too long integer/character subset argument `", so , "`: length must not exceed the number of ", dt, " [", n, "].") if( anyDuplicated(subset) ) warning("Duplicated index or name in subset argument `", so, "`.") if( is.character(subset) ){ if( is.null(dn) ) stop("Could not subset the ", dt, " with a character subset argument `", so, "`: no " , if( margin == 1L ) "rownames" else "colnames" , " are available.") msubset <- match(subset, dn) nas <- is.na(msubset) if( any(nas) ){ warning("Mismatch in character subset argument `", so ,"`: Could not find ", sum(nas), " out of ", length(subset), " names (" , paste("'", head(subset[nas], 5), "'", sep='', collapse=', ') , if( sum(nas) > 5 ) ", ... ", ").") msubset <- msubset[!nas] } subset <- msubset } subset }else stop("Invalid subset argument `", so, "`: should be a logical, integer or character vector.") sort(subIdx) } aheatmap = function(x , color = '-RdYlBu2:100' , breaks = NA, border_color=NA, cellwidth = NA, cellheight = NA, scale = "none" , Rowv=TRUE, Colv=TRUE , revC = identical(Colv, "Rowv") || is_NA(Rowv) || (is.integer(Rowv) && length(Rowv) > 1) || is(Rowv, 'silhouette') , distfun = "euclidean", hclustfun = "complete", reorderfun = function(d,w) reorder(d,w) , treeheight = 50 , legend = TRUE, annCol = NA, annRow = NA, annColors = NA, annLegend = TRUE , labRow = NULL, labCol = NULL , subsetRow = NULL, subsetCol = NULL , txt = NULL , fontsize=10, cexRow = min(0.2 + 1/log10(nr), 1.2), cexCol = min(0.2 + 1/log10(nc), 1.2) , filename = NA, width = NA, height = NA , main = NULL, sub = NULL, info = NULL , verbose=getOption('verbose'), gp = gpar()){ ol <- lverbose(verbose) on.exit( lverbose(ol) ) if( is(x, 'ExpressionSet') ){ requireNamespace('Biobase') if( isTRUE(annCol) ) annCol <- atrack(x) x <- Biobase::exprs(x) } mat <- x if( !is.null(txt) ){ if( !all(dim(mat), dim(x)) ){ stop("Incompatible data and text dimensions: arguments x and txt must have the same size.") } } res <- list() if( length(treeheight) == 1 ) treeheight <- c(treeheight, treeheight) treeheight_row <- treeheight[1] treeheight_col <- treeheight[2] if( !is.null(subsetRow) ){ if( verbose ) message("Compute row subset indexes") subsetRow <- subset_index(mat, 1L, subsetRow) } if( !is.null(subsetCol) ){ if( verbose ) message("Compute column subset indexes") subsetCol <- subset_index(mat, 2L, subsetCol) } if( is.null(labRow) && is.null(rownames(mat)) ) labRow <- 1L if( !is.null(labRow) ){ if( verbose ) message("Process labRow") rownames(mat) <- generate_dimnames(labRow, nrow(mat), rownames(mat)) } if( is.null(labCol) && is.null(colnames(mat)) ) labCol <- 1L if( !is.null(labCol) ){ if( verbose ) message("Process labCol") colnames(mat) <- generate_dimnames(labCol, ncol(mat), colnames(mat)) } if( !is.null(subsetRow) ){ mat <- mat[subsetRow, ] } if( !is.null(subsetCol) ){ mat <- mat[, subsetCol] } tree_row <- if( !is_NA(Rowv) ){ if( verbose ) message("Cluster rows") if( isReal(Rowv) ){ treeheight_row <- Rowv Rowv <- TRUE } cluster_mat(mat, Rowv , distfun=distfun, hclustfun=hclustfun , reorderfun=reorderfun, subset=subsetRow , verbose = verbose) } else NA if( identical(Rowv, FALSE) || !is_treedef(tree_row) ) treeheight_row <- 0 tree_col <- if( !is_NA(Colv) ){ if( identical(Colv,"Rowv") ){ if( ncol(mat) != nrow(mat) ) stop("aheatmap - Colv='Rowv' but cannot treat columns and rows symmetrically: input matrix is not square.") treeheight_col <- treeheight_row tree_row }else{ if( isReal(Colv) ){ treeheight_col <- Colv Colv <- TRUE } if( verbose ) message("Cluster columns") cluster_mat(t(mat), Colv , distfun=distfun, hclustfun=hclustfun , reorderfun=reorderfun, subset=subsetCol , verbose = verbose) } } else NA if( identical(Colv, FALSE) || !is_treedef(tree_col) ) treeheight_col <- 0 if( !is_NA(tree_row) ){ if( revC ){ if( verbose ) message("Reverse row clustering") tree_row <- rev(tree_row) } if( is_treedef(tree_row) ){ res$Rowv <- tree_row$dendrogram res$rowInd <- order.dendrogram(tree_row$dendrogram) if( length(res$rowInd) != nrow(mat) ) stop("aheatmap - row dendrogram ordering gave index of wrong length (", length(res$rowInd), ")") } else{ res$rowInd <- tree_row tree_row <- NA } }else if( revC ){ res$rowInd <- nrow(mat):1L } res$rowInd <- subset2orginal_idx(res$rowInd, subsetRow) if( !is.null(res$rowInd) ){ if( !is.integer(res$rowInd) || length(res$rowInd) != nrow(mat) ) stop("aheatmap - Invalid row ordering: should be an integer vector of length nrow(mat)=", nrow(mat)) if( verbose ) message("Order rows") subInd <- attr(res$rowInd, 'subset') ri <- if( is.null(subInd) ) res$rowInd else subInd mat <- mat[ri, , drop=FALSE] if( !is.null(txt) ) txt <- txt[ri, , drop = FALSE] } if( !is_NA(tree_col) ){ if( is_treedef(tree_col) ){ res$Colv <- tree_col$dendrogram res$colInd <- order.dendrogram(tree_col$dendrogram) if( length(res$colInd) != ncol(mat) ) stop("aheatmap - column dendrogram ordering gave index of wrong length (", length(res$colInd), ")") }else{ res$colInd <- tree_col tree_col <- NA } } res$colInd <- subset2orginal_idx(res$colInd, subsetCol) if( !is.null(res$colInd) ){ if( !is.integer(res$colInd) || length(res$colInd) != ncol(mat) ) stop("aheatmap - Invalid column ordering: should be an integer vector of length ncol(mat)=", ncol(mat)) if( verbose ) message("Order columns") subInd <- attr(res$colInd, 'subset') ci <- if( is.null(subInd) ) res$colInd else subInd mat <- mat[, ci, drop=FALSE] if( !is.null(txt) ) txt <- txt[, ci, drop = FALSE] } if( isTRUE(info) || is.character(info) ){ if( verbose ) message("Compute info") if( !is.character(info) ) info <- NULL linfo <- NULL if( is_treedef(tree_row) && !is.null(tree_row$dist.method) ) linfo <- paste("rows:", tree_row$dist.method, '/', tree_row$method) if( is_treedef(tree_col) && !is.null(tree_col$dist.method) ) linfo <- paste(linfo, paste(" - cols:", tree_col$dist.method, '/', tree_col$method)) info <- c(info, linfo) } if( is_treedef(tree_col) ) tree_col <- tree_col$dendrogram if( is_treedef(tree_row) ) tree_row <- tree_row$dendrogram if( verbose ) message("Scale matrix") mat = as.matrix(mat) mat = scale_mat(mat, scale) color <- ccRamp(color) if( is_NA(breaks) || isNumber(breaks) ){ if( verbose ) message("Generate breaks") cbreaks <- if( isNumber(breaks) ) breaks else NA breaks = generate_breaks(as.vector(mat), length(color), center=cbreaks) } if( isTRUE(legend) ){ if( verbose ) message("Generate data legend breaks") legend = grid.pretty(range(as.vector(breaks))) } else { legend = NA } mat = scale_colours(mat, col = color, breaks = breaks) annotation_legend <- annLegend annotation_colors <- annColors annCol_processed <- atrack(annCol, order=res$colInd, .SPECIAL=specialAnnotation(2L), .DATA=amargin(x,2L), .CACHE=annRow) annRow_processed <- atrack(annRow, order=res$rowInd, .SPECIAL=specialAnnotation(1L), .DATA=amargin(x,1L), .CACHE=annCol) specialAnnotation(clear=TRUE) annTracks <- renderAnnotations(annCol_processed, annRow_processed , annotation_colors = annotation_colors , verbose=verbose) nr <- nrow(mat); nc <- ncol(mat) res$vp <- heatmap_motor(mat, border_color = border_color, cellwidth = cellwidth, cellheight = cellheight , treeheight_col = treeheight_col, treeheight_row = treeheight_row, tree_col = tree_col, tree_row = tree_row , filename = filename, width = width, height = height, breaks = breaks, color = color, legend = legend , annTracks = annTracks, annotation_legend = annotation_legend , txt = txt , fontsize = fontsize, fontsize_row = cexRow * fontsize, fontsize_col = cexCol * fontsize , main = main, sub = sub, info = info , verbose = verbose , gp = gp) invisible(res) } grid.base.mix <- function(opar, trace = getOption('verbose')){ if( !missing(opar) ){ if( !is.null(opar) ){ if( trace ) message("grid.base.mix - restore") upViewport(2) par(opar) } return(invisible()) } if( trace ) message("grid.base.mix - init") if( trace ) grid.rect(gp=gpar(lwd=40, col="blue")) opar <- par(xpd=NA) if( trace ) grid.rect(gp=gpar(lwd=30, col="green")) if( trace ) message("grid.base.mix - plot.new") plot.new() if( trace ) grid.rect(gp=gpar(lwd=20, col="black")) vps <- baseViewports() pushViewport(vps$inner) if( trace ) grid.rect(gp=gpar(lwd=10, col="red")) pushViewport(vps$figure) if( trace ) grid.rect(gp=gpar(lwd=3, col="yellow")) opar } if( FALSE ){ testmix <- function(){ opar <- mixplot.start(FALSE) profplot(curated$data$model, curated$fits[[1]]) mixplot.add(TRUE) basismarker(curated$fits[[1]], curated$data$markers) mixplot.end() par(opar) } dd <- function(d, horizontal = TRUE, ...){ grid.rect(gp = gpar(col = "blue", lwd = 2)) opar <- par(plt = gridPLT(), new = TRUE) on.exit(par(opar)) plot(d, horiz=horizontal, xaxs="i", yaxs="i", axes=FALSE, leaflab="none", ...) } toto <- function(new=FALSE){ library(RGraphics) set.seed(123456) x <- matrix(runif(30*20), 30) x <- crossprod(x) d <- as.dendrogram(hclust(dist(x))) if( new ) plot.new() lo <- grid.layout(nrow=2, ncol=2) pushViewport(viewport(layout=lo)) pushViewport(viewport(layout.pos.row = 2, layout.pos.col = 1)) dd(d) upViewport() pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 2)) dd(d, FALSE) upViewport() pushViewport(viewport(layout.pos.row = 2, layout.pos.col = 2)) grid.imageGrob(nrow(x), ncol(x), x) upViewport() popViewport() stop("END toto") } test <- function(){ pdf('aheatmap.pdf') try(v <- consensusmap(res, color='grey:100', Colv=2L, verbose=TRUE)) dev.off() } test2 <- function(){ op <- par(mfrow=c(1,2)) on.exit(par(op)) try(v <- consensusmap(res, verbose=TRUE)) try(v <- consensusmap(res, color='grey:100', Colv=2L, verbose=TRUE)) } testsw <- function(file=TRUE){ if(file ){ pdf('asweave.pdf', width=20, height=7) on.exit(dev.off()) } opar <- par(mfrow=c(1,2)) coefmap(res, tracks=NA, verbose=TRUE) coefmap(res, Colv = 'euclidean', Rowv='max', verbose=TRUE) par(opar) } testvp <- function(file=TRUE){ if(file ){ pdf('avp.pdf', width=20, height=7) on.exit(dev.off()) } plot.new() lo <- grid.layout(nrow=1, ncol=2) pushViewport(viewport(layout=lo)) pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 1)) basismap(res, Colv='eucl', verbose=TRUE) upViewport() pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 2)) coefmap(res, tracks=NA, verbose=TRUE) upViewport() popViewport() } }
transformRateMatrix <- function(rateData, rate=NULL) { V <- rateData$Vmat if(is.null(rate)) { rate <- c(rep(1,length(rateData$Vmat))) } else { rate <- rate } nV <- length(rate) if(length(rate) != length(rateData$Vmat)){stop("The number of rates defined differs from the number of rate matrices")} v1 <- V[[1]] rateMats <- vector(mode="list", length = nV) retMat <- matrix(0, nrow = dim(v1)[1], ncol = dim(v1)[2]) for(i in 1:nV) { rateMats[[i]] <- rate[i] * V[[i]] retMat <- retMat + rateMats[[i]] } return(retMat)}
RDS.SS.estimates <- function(rds.data,outcome.variable,N=NULL,subset=NULL, number.ss.samples.per.iteration=500,number.ss.iterations=5, control=control.rds.estimates(), hajek=TRUE,empir.lik=TRUE,to.factor=FALSE){ se <- substitute(subset) subset <- eval(se,rds.data,parent.frame()) if(length(outcome.variable) == 1){ result <- RDS.estimates.local( rds.data=rds.data, outcome.variable=outcome.variable, N=N, subset=subset, number.ss.samples.per.iteration=number.ss.samples.per.iteration, number.ss.iterations=number.ss.iterations, control=control, hajek=hajek, empir.lik=empir.lik, weight.type="Gile's SS", to.factor=to.factor) } else { result <- lapply(outcome.variable,function(g){ RDS.estimates.local( rds.data=rds.data, outcome.variable=g, N=N, subset=subset, number.ss.samples.per.iteration=number.ss.samples.per.iteration, number.ss.iterations=number.ss.iterations, control=control, hajek=hajek, empir.lik=empir.lik, weight.type="Gile's SS", to.factor=to.factor) }) names(result) <- outcome.variable } return(result) }
caralloc = function(xmat,carwt,p,tol) { if (!is.matrix(xmat)) xmat = as.matrix(xmat) n = nrow(xmat) result = rbinom(n,1,0.5) if (n > 1) { for (j in 2:n) { matchx = apply(xmat[1:(j-1),,drop=FALSE],1, function(x,xrow) { as.numeric(x == xrow) }, xmat[j,] ) sumsofar = matchx %*% (2*result[1:(j-1)] - 1) imbalance1 = crossprod (abs(sumsofar + 1) , carwt) imbalance0 = crossprod (abs(sumsofar - 1) , carwt) if (imbalance1 < imbalance0 & imbalance0 >= tol) result[j] = rbinom(1,1,p) if (imbalance0 < imbalance1 & imbalance1 >= tol) result[j] = rbinom(1,1,1-p) } } result }
viz_thickforest <- function(x, group = NULL, type = "standard", method = "FE", study_labels = NULL, summary_label = NULL, confidence_level = 0.95, col = "Blues", summary_col = col, tick_col = "firebrick", text_size = 3, xlab = "Effect", x_limit = NULL, x_trans_function = NULL, x_breaks = NULL, annotate_CI = FALSE, study_table = NULL, summary_table = NULL, table_headers = NULL, table_layout = NULL) { viz_forest(x, group = group, type = type, variant = "thick", method = method, study_labels = study_labels, summary_label = summary_label, confidence_level = confidence_level, col = col, summary_col = summary_col, tick_col = tick_col, text_size = text_size, xlab = xlab, x_limit = x_limit, x_trans_function = x_trans_function, x_breaks = NULL, annotate_CI = annotate_CI, study_table = study_table, summary_table = summary_table, table_headers = table_headers, table_layout = table_layout) }
expected <- eval(parse(text="list(c(\"<none>\", \"- M.user:Temp\", \"+ Soft\"), c(\"Df\", \"Deviance\", \"AIC\"))")); test(id=0, code={ argv <- eval(parse(text="list(structure(c(NA, 1, 2, 5.65604443125997, 8.44399377410362, 5.49523049516867, 71.3540021461976, 72.1419514890413, 75.1931882101063), .Dim = c(3L, 3L), .Dimnames = list(c(\"<none>\", \"- M.user:Temp\", \"+ Soft\"), c(\"Df\", \"Deviance\", \"AIC\"))))")); do.call(`dimnames`, argv); }, o=expected);
sandwich.cv <- function(object, sampling.attr, k=10, type="shp", ssh.id.col=NULL, reporting.id.col=NULL, ssh.weights=NULL){ if (type == "shp"){ sampling.lyr = object[[1]] ssh.lyr = object[[2]] reporting.lyr = object[[3]] if (st_geometry_type(sampling.lyr, by_geometry=FALSE) != "POINT"){ stop("Geometry type of the sampling layer should be POINT.") } if (st_geometry_type(ssh.lyr, by_geometry=FALSE) != "POLYGON" & st_geometry_type(ssh.lyr, by_geometry=FALSE) != "MULTIPOLYGON"){ stop("Geometry type of the SSH layer should be POLYGON or MULTIPOLYGON.") } if (st_geometry_type(reporting.lyr, by_geometry=FALSE) != "POLYGON" & st_geometry_type(reporting.lyr, by_geometry=FALSE) != "MULTIPOLYGON"){ stop("Geometry type of the reporting layer should be POLYGON or MULTIPOLYGON.") } if (!is.element(sampling.attr, names(sampling.lyr))){ stop("Attribute name not found in the sampling layer.") } sampling.lyr$index = 1:nrow(sampling.lyr) folds = createFolds(sampling.lyr$index, k=k) rmse = 0 for(i in 1:k){ val = lapply(folds[i], function(ind, dat) dat[ind,], dat=sampling.lyr) val = st_as_sf(as.data.frame(val)) dev = lapply(list(unique(unlist(folds[-i]))), function(ind, dat) dat[ind,], dat=sampling.lyr) dev = st_as_sf(as.data.frame(dev)) object_dev = list(dev, ssh.lyr, reporting.lyr) out = sandwich.model(object_dev, sampling.attr, type)$object val.join = suppressMessages(st_join(val, out)) st_geometry(val.join) = NULL val.join = as.data.frame(val.join) new.attr.name = paste(names(folds)[i], sampling.attr, sep=".") dif = (val.join[new.attr.name] - val.join$mean)[[new.attr.name]] rmse[i] = sqrt(mean(dif^2)) } rmse.mean = mean(rmse) rmse.mean} else if (type == "txt"){ sampling_ssh = object[[1]] reporting_ssh = object[[2]] if (!ssh.id.col %in% names(sampling_ssh) | is.null(ssh.id.col)){ stop("Column name ssh.id.col not exists in the file linking sampling and SSH layers.") } if (!all(ssh.weights[[2]] %in% names(reporting_ssh)) | is.null(ssh.weights)){ stop("Some columns in ssh.weights not exist in the file linking reporting and SSH layers.") } if (!all(sort(ssh.weights[[1]]) == sort(unique(sampling_ssh[[ssh.id.col]])))){ stop("ssh.weights not matches with the values in column ssh.id.col") } if (!is.element(sampling.attr, names(sampling_ssh))){ stop("Attribute name not found in the file linking sampling and SSH layers.") } sampling_ssh$index = 1:nrow(sampling_ssh) folds = createFolds(sampling_ssh$index, k=k) rmse = 0 for(i in 1:k){ val = lapply(folds[i], function(ind, dat) dat[ind,], dat=sampling_ssh)[[1]] dev = lapply(list(unique(unlist(folds[-i]))), function(ind, dat) dat[ind,], dat=sampling_ssh)[[1]] object_dev = list(dev, reporting_ssh) out = sandwich.model(object_dev, sampling.attr, type, ssh.id.col, ssh.weights)$object val.join = merge(val, out, reporting.id.col, all.x=TRUE) dif = (val.join[sampling.attr] - val.join$mean)[[sampling.attr]] rmse[i] = sqrt(mean(dif^2)) } rmse.mean = mean(rmse) rmse.mean} }
plot.qbpca <- function(x, xlab='Index', ylab='r', pch=c(1,8), col=c(4,2), ...) { if (!inherits(x, 'qbpca')) stop("Use this function only with 'qbpca' class!") plot(x$obs, ylim=c(-1,1), xlab=xlab, ylab=ylab, pch=pch[1], col=col[1], ...) points(x$var.rb, col=col[2], pch=pch[2]) legend('bottomleft', c('r', 'r.rb'), pch=pch, col=col, title='legend') }
hypervolume_permute <- function(name, hv1, hv2, n = 50, cores = 1, verbose = TRUE) { exists_cluster = TRUE if(cores > 1 & getDoParWorkers() == 1) { cl = makeCluster(cores) clusterEvalQ(cl, { library(hypervolume) }) registerDoParallel(cl) exists_cluster = FALSE } dir.create(file.path('./Objects', name)) if(verbose) { pb = progress_bar$new(total = n) } foreach(i = 1:n, .combine = c) %dopar% { combined_data = rbind(hv1@Data, hv2@Data) perm_idx = sample(1:nrow(combined_data), nrow(hv1@Data)) h1 = copy_param_hypervolume(hv1, combined_data[perm_idx,], name = "hv1") h2 = copy_param_hypervolume(hv2, combined_data[-1 * perm_idx,], name = "hv2") subdir = file.path("./Objects", name, paste0("permutation", as.character(i))) dir.create(subdir) name1 = paste0(h1@Name, '.rds') name2 = paste0(h2@Name, '.rds') saveRDS(h1, file.path('./Objects', name, paste0("permutation", as.character(i)), name1)) saveRDS(h2, file.path('./Objects', name, paste0("permutation", as.character(i)), name2)) if(verbose) { pb$tick() } } if(!exists_cluster) { stopCluster(cl) registerDoSEQ() } return(file.path(getwd(), 'Objects', name)) }
tajima.K <- function(DNAbin, prop = TRUE){ res <- mean(dist.dna(DNAbin, model="N")) if(prop) res <- res/dim(DNAbin)[2] res }
NULL local_testthat_assign <- function(x, values, envir = parent.frame()) { exist <- exists(x, envir = envir) if (exist) { old_value <- envir[[x]] withr::defer(assign(x, old_value, envir = envir), envir = envir) } else { withr::defer(rm(list = x, envir = envir), envir = envir) } assign(x, values, envir = envir) } local_testthat_tolerances <- function(tolerances = c(1e-4, 1e-2, 1e-1), envir = parent.frame()) { local_testthat_assign("lowtol", tolerances[1], envir = envir) local_testthat_assign("midtol", tolerances[2], envir = envir) local_testthat_assign("hitol", tolerances[3], envir = envir) } local_bru_options_set <- function(..., .reset = FALSE, envir = parent.frame()) { old_opt <- bru_options_get(include_default = FALSE) withr::defer(bru_options_set(old_opt, .reset = TRUE), envir = envir) bru_options_set(..., .reset = .reset) invisible(old_opt) } local_set_PROJ6_warnings <- function(proj4 = FALSE, thin = TRUE, envir = parent.frame()) { withr::local_options( list( "rgdal_show_exportToProj4_warnings" = if (!proj4) { "none" } else if (thin) { "thin" } else { "all" } ), .local_envir = envir ) requireNamespace("rgdal", quietly = TRUE) if (fm_has_PROJ6()) { old1 <- rgdal::get_rgdal_show_exportToProj4_warnings() withr::defer( rgdal::set_rgdal_show_exportToProj4_warnings(old1), envir = envir ) rgdal::set_rgdal_show_exportToProj4_warnings(proj4) old2 <- rgdal::get_thin_PROJ6_warnings() withr::defer( rgdal::set_thin_PROJ6_warnings(old2), envir = envir ) rgdal::set_thin_PROJ6_warnings(thin) } } local_get_rgdal_options <- function() { requireNamespace("rgdal", quietly = TRUE) list( option_rgdal_show_exportToProj4_warnings = getOption("rgdal_show_exportToProj4_warnings"), rgdal_show_exportToProj4_warnings = rgdal::get_rgdal_show_exportToProj4_warnings(), thin_PROJ6_warnings = rgdal::get_thin_PROJ6_warnings() ) } local_disable_PROJ6_warnings <- function(envir = parent.frame()) { local_set_PROJ6_warnings(proj4 = FALSE, thin = TRUE, envir = envir) } local_basic_intercept_testdata <- function() { set.seed(123) data.frame( Intercept = 1, y = rnorm(100) ) } local_basic_fixed_effect_testdata <- function() { set.seed(123) cbind( local_basic_intercept_testdata(), data.frame(x1 = rnorm(100)) ) } local_mrsea_convert <- function(x, use_km = FALSE) { if (!use_km) { crs_m <- fm_crs_set_lengthunit(x$mesh$crs, "m") x$mesh <- fm_spTransform(x$mesh, crs_m) x$samplers <- sp::spTransform(x$samplers, crs_m) x$samplers$weight <- x$samplers$weight * 1000 x$points <- sp::spTransform(x$points, crs_m) x$boundary <- sp::spTransform(x$boundary, crs_m) x$covar <- sp::spTransform(x$covar, crs_m) x$points$Effort <- x$points$Effort * 1000 x$points$mid.x <- x$points$mid.x * 1000 x$points$mid.y <- x$points$mid.y * 1000 x$points$start.x <- x$points$start.x * 1000 x$points$start.y <- x$points$start.y * 1000 x$points$end.x <- x$points$end.x * 1000 x$points$end.y <- x$points$end.y * 1000 x$points$distance <- x$points$distance * 1000 x$samplers$Effort <- x$samplers$Effort * 1000 x$samplers$mid.x <- x$samplers$mid.x * 1000 x$samplers$mid.y <- x$samplers$mid.y * 1000 } x } local_bru_safe_inla <- function(multicore = FALSE, quietly = TRUE, envir = parent.frame()) { if (requireNamespace("INLA", quietly = TRUE)) { old_threads <- INLA::inla.getOption("num.threads") withr::defer( INLA::inla.setOption(num.threads = old_threads), envir ) old_fmesher_timeout <- INLA::inla.getOption("fmesher.timeout") withr::defer( INLA::inla.setOption(fmesher.timeout = old_fmesher_timeout), envir ) INLA::inla.setOption(fmesher.timeout = 30) } if (!multicore) { local_bru_options_set(num.threads = "1:1", envir = envir) } testthat::skip_if_not(bru_safe_inla(multicore = multicore, quietly = quietly)) } local_bru_testthat_setup <- function(envir = parent.frame()) { local_disable_PROJ6_warnings(envir = envir) local_testthat_tolerances(envir = envir) local_bru_options_set( control.compute = list(dic = FALSE, waic = FALSE), inla.mode = "experimental", envir = envir ) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(ROCR) table <- data.frame(group = c("Contingency ratios", "Discrete covariation measures", "Information retrieval measures", "Performance in ROC space", "Absolute scoring performance", "Cost measures"), measure = c("error rate, accuracy, sensitivity, specificity, true/false positive rate, fallout, miss, precision, recall, negative predictive value, prediction-conditioned fallout/miss.", "Phi/Matthews correlation coefficient, mutual information, Chi-squared test statistic, odds ratio", "F-measure, lift, precision-recall break-even point", "ROC convex hull, area under the ROC curve", "calibration error, mean cross-entropy, root mean-squared error", "expected cost, explicit cost")) knitr::kable(table, caption = "***Table 1:**Performance measures in the ROCR package*", col.names = c("",""), align = "l") data(ROCR.hiv) predictions <- ROCR.hiv$hiv.svm$predictions labels <- ROCR.hiv$hiv.svm$labels pred <- prediction(predictions, labels) pred perf <- performance(pred, "tpr", "fpr") perf plot(perf, avg="threshold", spread.estimate="boxplot") data(ROCR.hiv) pp.unnorm <- ROCR.hiv$hiv.svm$predictions ll <- ROCR.hiv$hiv.svm$labels v <- unlist(pp.unnorm) pp <- lapply(pp.unnorm, function(run) {approxfun(c(min(v), max(v)), c(0,1))(run)}) par(mfrow=c(1,4)) pred<- prediction(pp, ll) perf <- performance(pred, "tpr", "fpr") plot(perf, avg= "threshold", colorize=TRUE, lwd= 3, coloraxis.at=seq(0,1,by=0.2),) plot(perf, col="gray78", add=TRUE) plot(perf, avg= "threshold", colorize=TRUE, colorkey=FALSE,lwd= 3,,add=TRUE) mtext(paste0("(a)"), side = 3, adj = 0.01,line = 1) perf <- performance(pred, "acc") plot(perf, avg= "vertical", spread.estimate="boxplot", lwd=3,col='blue', show.spread.at= seq(0.1, 0.9, by=0.1),) mtext(paste0("(b)"), side = 3, adj = 0.01,line = 1) plot(performance(pred, "cal", window.size= 10), avg="vertical",) mtext(paste0("(c)"), side = 3, adj = 0.01,line = 1) plot(0,0,type="n", xlim= c(0,1), ylim=c(0,7), xlab="Cutoff", ylab="Density",) mtext(paste0("(d)"), side = 3, adj = 0.01,line = 1) for (runi in 1:length(pred@predictions)) { lines(density(pred@predictions[[runi]][pred@labels[[runi]]=="-1"]), col= "red") lines(density(pred@predictions[[runi]][pred@labels[[runi]]=="1"]), col="green") } perf <- performance(pred, "tpr", "fpr") plot(perf, avg= "threshold", colorize=TRUE, lwd= 3, main= "With ROCR you can produce standard plots\nlike ROC curves ...") plot(perf, lty=3, col="grey78", add=TRUE) perf <- performance(pred, "prec", "rec") plot(perf, avg= "threshold", colorize=TRUE, lwd= 3, main= "... Precision/Recall graphs ...") plot(perf, lty=3, col="grey78", add=TRUE) perf <- performance(pred, "sens", "spec") plot(perf, avg= "threshold", colorize=TRUE, lwd= 3, main="... Sensitivity/Specificity plots ...") plot(perf, lty=3, col="grey78", add=TRUE) perf <- performance(pred, "lift", "rpp") plot(perf, avg= "threshold", colorize=TRUE, lwd= 3, main= "... and Lift charts.") plot(perf, lty=3, col="grey78", add=TRUE) data(ROCR.xval) predictions <- ROCR.xval$predictions labels <- ROCR.xval$labels length(predictions) pred <- prediction(predictions, labels) perf <- performance(pred,'tpr','fpr') plot(perf, colorize=TRUE, lwd=2, main='ROC curves from 10-fold cross-validation') plot(perf, avg='vertical', spread.estimate='stderror', lwd=3,main='Vertical averaging + 1 standard error', col='blue') plot(perf, avg='horizontal', spread.estimate='boxplot', lwd=3, main='Horizontal averaging + boxplots', col='blue') plot(perf, avg='threshold', spread.estimate='stddev', lwd=2, main='Threshold averaging + 1 standard deviation', colorize=TRUE) plot(perf, print.cutoffs.at=seq(0,1,by=0.2), text.cex=0.8, text.y=lapply(as.list(seq(0,0.5,by=0.05)), function(x) { rep(x,length([email protected][[1]])) } ), col= as.list(terrain.colors(10)), text.col= as.list(terrain.colors(10)), points.col= as.list(terrain.colors(10)), main= "Cutoff stability") perf <- performance(pred,"pcmiss","lift") plot(perf, colorize=TRUE, print.cutoffs.at=seq(0,1,by=0.1), text.adj=c(1.2,1.2), avg="threshold", lwd=3, main= "You can freely combine performance measures ...")
GaussianMatrix <- function(N, M) { return( matrix( rnorm(N * M ), M,N ) ) }
check.norms <- function(y, nice.output = TRUE){ R <- sort(unique(y)) K <- length(R) n <-matrix(0,K,1) for (i in 1:K){ n[i] <- sum(y==R[i]) } N <- length(y) if (min(y)<=0) { adjust <- abs(min(y) - 1) y <- y + adjust R <- R + adjust } else { adjust <- 0 } A1 <- rbind(R,1) A2 <- matrix(c(1,-1),1,2) meany <- exp(A2%*%log(A1%*%n)) -adjust g0 <- n g1 <- log(A1%*%n) G0 <- diag(K) G1 <- solve(diag(c(A1%*%g0),length(A1%*%g0),length(A1%*%g0)))%*%A1%*%G0 G2 <- diag(c(exp(A2%*%g1)),length(exp(A2%*%g1)),length(exp(A2%*%g1)))%*%A2%*%G1 Gmean <-G2 Vmean <- Gmean%*%diag(c(n),length(n),length(n))%*%t(Gmean)-Gmean%*%(n%*%t(n)/N)%*%t(Gmean) Se.mean <- sqrt(Vmean) lomeany <- meany - 1.96*Se.mean upmeany <- meany + 1.96*Se.mean A1 <- rbind(R,R^2,1,1) A2 <- diag(c(2,1,1,-1)) A2[4,3] <- 1 A2[1,3] <- -1 A3 <- matrix(c(-1,0,1,0,0,1,0,-1),2,4) A4 <- matrix(c(.5,-0.5),1,2) sdy <- exp(A4 %*% log (A3 %*% exp(A2 %*% log(A1 %*% n)))) g0 <- n g1 <- log(A1%*%n) g2 <- exp(A2%*%log(A1%*%n)) g3 <- log (A3 %*% exp(A2 %*% log(A1 %*% n))) G0 <- diag(K) G1 <- solve(diag(c(A1%*%g0),length(A1%*%g0),length(A1%*%g0)))%*%A1%*%G0 G2 <- diag(c(exp(A2%*%g1)),length(exp(A2%*%g1)),length(exp(A2%*%g1)))%*%A2%*%G1 G3 <- solve(diag(c(A3%*%g2),length(A3%*%g2),length(A3%*%g2)))%*%A3%*%G2 G4 <- diag(c(exp(A4%*%g3)),length(exp(A4%*%g3)),length(exp(A4%*%g3)))%*%A4%*%G3 Gsd <-G4 Vsd <- Gsd%*%diag(c(n),length(n),length(n))%*%t(Gsd)-Gsd%*%(n%*%t(n)/N)%*%t(Gsd) Se.sd <- sqrt(Vsd) losdy <- sdy - 1.96*Se.sd upsdy <- sdy + 1.96*Se.sd A1 <- t(cbind(diag(K),rep(1,K),rep(1,K))) A2 <- direct.sum(diag(K), t(c(1,-1))) A3 <- direct.sum(rbind(R, R^2, rep(1, K), rep(1, K)), matrix(R)) A4 <- direct.sum(matrix(c(1,2,0,0,0,0,0,1,0,0,0,0,0,0,1,-1,-1,0,1,-1),5,4),diag(K)) A5 <- direct.sum(matrix(1), cbind(-1,1), cbind(1,-1), diag(K)) A6 <- matrix(c(1,rep(0,K),-1/2, rep(1,K)-3/2, 1/2, rep(1,K)-1/2,rbind(rep(0,K),diag(K))),K+1, K+3) A7 <- cbind(rep(-1,K), diag(K)) Zy <- A7%*%exp(A6%*%log(A5%*%exp(A4%*%log(A3%*%exp(A2%*%log(A1%*%n)))))) g0 <- n g1 <- log(A1%*%n) g2 <- exp(A2%*%log(A1%*%n)) g3 <- log(A3%*%exp(A2%*%log(A1%*%n))) g4 <- exp(A4%*%log(A3%*%exp(A2%*%log(A1%*%n)))) g5 <- log(A5%*%exp(A4%*%log(A3%*%exp(A2%*%log(A1%*%n))))) g6 <- exp(A6%*%log(A5%*%exp(A4%*%log(A3%*%exp(A2%*%log(A1%*%n)))))) G0 <- diag(K) G1 <- solve(diag(c(A1%*%g0),length(A1%*%g0),length(A1%*%g0)))%*%A1%*%G0 G2 <- diag(c(exp(A2%*%g1)),length(exp(A2%*%g1)),length(exp(A2%*%g1)))%*%A2%*%G1 G3 <- solve(diag(c(A3%*%g2),length(A3%*%g2),length(A3%*%g2)))%*%A3%*%G2 G4 <- diag(c(exp(A4%*%g3)),length(exp(A4%*%g3)),length(exp(A4%*%g3)))%*%A4%*%G3 G5 <- solve(diag(c(A5%*%g4),length(A5%*%g4),length(A5%*%g4)))%*%A5%*%G4 G6 <- diag(c(exp(A6%*%g5)),length(exp(A6%*%g5)),length(exp(A6%*%g5)))%*%A6%*%G5 G7 <- A7 %*% G6 GZy <-G7 VZy <- GZy%*%diag(c(n),length(n),length(n))%*%t(GZy)-GZy%*%(n%*%t(n)/N)%*%t(GZy)-GZy%*%(n%*%t(n)/N)%*%t(GZy) Se.Zy <- sqrt(diag(VZy)) loZy <- Zy - 1.96*Se.Zy upZy <- Zy + 1.96*Se.Zy A1 <- rbind(R,R^2,rep(1,K),rep(1,K)) A2 <- matrix(c(2,0,0,1,0,0,1,0,0,0,0,0,0,0,1,-1,0,1,-1,-1),5,4) A3 <- matrix(c(-1,0,0,1,0,0,0,1,0,0,0,1,0,-1,0),3,5) A4 <- matrix(c(1/2,0,-1/2,0,0,1),2,3) A5 <- cbind(seq(-1.75,1.75,.50),rep(1,8)) Sty <- A5 %*% exp (A4 %*% log ( A3 %*% exp ( A2 %*% log ( A1 %*% n )))) -adjust g0 <- n g1 <- log(A1%*%n) g2 <- exp(A2%*%log(A1%*%n)) g3 <- log(A3%*%exp(A2%*%log(A1%*%n))) g4 <- exp(A4%*%log(A3%*%exp(A2%*%log(A1%*%n)))) G0 <- diag(K) G1 <- solve(diag(c(A1%*%g0),length(A1%*%g0),length(A1%*%g0)))%*%A1%*%G0 G2 <- diag(c(exp(A2%*%g1)),length(exp(A2%*%g1)),length(exp(A2%*%g1)))%*%A2%*%G1 G3 <- solve(diag(c(A3%*%g2),length(A3%*%g2),length(A3%*%g2)))%*%A3%*%G2 G4 <- diag(c(exp(A4%*%g3)),length(exp(A4%*%g3)),length(exp(A4%*%g3)))%*%A4%*%G3 G5 <- A5 %*% G4 GSty <-G5 VSty <- GSty%*%diag(c(n),length(n),length(n))%*%t(GSty)-GSty%*%(n%*%t(n)/N)%*%t(GSty) Se.Sty <- sqrt(diag(VSty)) loSty <- Sty - 1.96*Se.Sty upSty <- Sty + 1.96*Se.Sty A1 <- matrix(1,K+1,K) A1[upper.tri(A1,diag=FALSE)] <- 0 A2 <- cbind(diag(K),rep(-1,K)) A3 <- matrix(0,K,K) for (i in 0:K) { i + 1 A3[i,i-1] <- 50 A3[i,i] <- 50 } Pry <- A3%*%exp(A2%*%log(A1%*%n)) g0 <- n g1 <- log(A1%*%n) g2 <- exp(A2%*%log(A1%*%n)) G0 <- diag(K) G1 <- solve(diag(c(A1%*%g0),length(A1%*%g0),length(A1%*%g0)))%*%A1%*%G0 G2 <- diag(c(exp(A2%*%g1)),length(exp(A2%*%g1)),length(exp(A2%*%g1)))%*%A2%*%G1 G3 <- A3 %*% G2 GPry <-G3 VPry <- GPry%*%diag(c(n),length(n),length(n))%*%t(GPry)-GPry%*%(n%*%t(n)/N)%*%t(GPry) Se.Pry <- sqrt(diag(VPry)) loPry <- Pry - 1.96*Se.Pry upPry <- Pry + 1.96*Se.Pry if (nice.output){ output.matrix.mean. <- matrix(NA, 1, 4) output.matrix.mean.[, 1] <- format(formatC(round(meany,3), digits = 3, format = "f"), width = 7, justify = "right") output.matrix.mean.[, 2] <- format(paste("(",formatC(round(Se.mean, 3), digits = 3, format = "f"),")", sep = ""), width = 7, justify = "right") output.matrix.mean.[, 3] <- format(formatC(round(lomeany,3), digits = 3, format = "f"), width = 7, justify = "right") output.matrix.mean.[, 4] <- format(formatC(round(upmeany,3), digits = 3, format = "f"), width = 7, justify = "right") dimnames(output.matrix.mean.) <- list("", c("Mean","SE", "lo", "up")) output.matrix.mean. <- noquote(output.matrix.mean.) output.matrix.sd. <- matrix(NA, 1, 4) output.matrix.sd.[, 1] <- format(formatC(round(sdy,3), digits = 3, format = "f"), width = 7, justify = "right") output.matrix.sd.[, 2] <- format(paste("(",formatC(round(Se.sd, 3), digits = 3, format = "f"),")", sep = ""), width = 7, justify = "right") output.matrix.sd.[, 3] <- format(formatC(round(losdy,3), digits = 3, format = "f"), width = 7, justify = "right") output.matrix.sd.[, 4] <- format(formatC(round(upsdy,3), digits = 3, format = "f"), width = 7, justify = "right") dimnames(output.matrix.sd.) <- list("", c("SD","SE", "lo", "up")) output.matrix.sd. <- noquote(output.matrix.sd.) output.matrix.Zy. <- matrix(NA, K, 4) output.matrix.Zy.[, 1] <- format(formatC(round(Zy,3), digits = 3, format = "f"), width = 7,justify = "right") output.matrix.Zy.[, 2] <- format(paste("(",formatC(round(Se.Zy, 3), digits = 3, format = "f"),")", sep = ""), width = 7, justify = "right") output.matrix.Zy.[, 3] <- format(formatC(round(loZy,3), digits = 3, format = "f"), width = 7,justify = "right") output.matrix.Zy.[, 4] <- format(formatC(round(upZy,3), digits = 3, format = "f"), width = 7,justify = "right") dimnames(output.matrix.Zy.) <- list(R-adjust, c("Zscores","SE", "lo", "up")) output.matrix.Zy. <- noquote(output.matrix.Zy.) output.matrix.Sty. <- matrix(NA, 8, 4) output.matrix.Sty.[, 1] <- format(formatC(round(Sty,3), digits = 3, format = "f"), width = 7,justify = "right") output.matrix.Sty.[, 2] <- format(paste("(",formatC(round(Se.Sty, 3), digits = 3, format = "f"),")", sep = ""), width = 7, justify = "right") output.matrix.Sty.[, 3] <- format(formatC(round(loSty,3), digits = 3, format = "f"), width = 7,justify = "right") output.matrix.Sty.[, 4] <- format(formatC(round(upSty,3), digits = 3, format = "f"), width = 7,justify = "right") dimnames(output.matrix.Sty.) <- list(c("1-2","2-3","3-4","4-5","5-6","6-7","7-8","8-9"), c("Stanines","SE", "lo", "up")) output.matrix.Sty. <- noquote(output.matrix.Sty.) output.matrix.Pry. <- matrix(NA, K, 4) output.matrix.Pry.[, 1] <- format(formatC(round(Pry,3), digits = 3, format = "f"), width = 7,justify = "right") output.matrix.Pry.[, 2] <- format(paste("(",formatC(round(Se.Pry, 3), digits = 3, format = "f"),")", sep = ""), width = 7, justify = "right") output.matrix.Pry.[, 3] <- format(formatC(round(loPry,3), digits = 3, format = "f"), width = 7,justify = "right") output.matrix.Pry.[, 4] <- format(formatC(round(upPry,3), digits = 3, format = "f"), width = 7,justify = "right") dimnames(output.matrix.Pry.) <- list(R-adjust, c("Percentiles","SE", "lo", "up")) output.matrix.Pry. <- noquote(output.matrix.Pry.) } else { output.matrix.mean. <- matrix(NA, 1, 4) output.matrix.mean.[, 1] <- meany output.matrix.mean.[, 2] <- Se.mean output.matrix.mean.[, 3] <- lomeany output.matrix.mean.[, 4] <- upmeany dimnames(output.matrix.mean.) <- list("", c("Mean","SE", "lo", "up")) output.matrix.sd. <- matrix(NA, 1, 4) output.matrix.sd.[, 1] <- sdy output.matrix.sd.[, 2] <- Se.sd output.matrix.sd.[, 3] <- losdy output.matrix.sd.[, 4] <- upsdy dimnames(output.matrix.sd.) <- list("", c("SD","SE", "lo", "up")) output.matrix.Zy. <- matrix(NA, K, 4) output.matrix.Zy.[, 1] <- Zy output.matrix.Zy.[, 2] <- Se.Zy output.matrix.Zy.[, 3] <- loZy output.matrix.Zy.[, 4] <- upZy dimnames(output.matrix.Zy.) <- list(R-adjust, c("Zscores","SE", "lo", "up")) output.matrix.Sty. <- matrix(NA, 8, 4) output.matrix.Sty.[, 1] <- Sty output.matrix.Sty.[, 2] <- Se.Sty output.matrix.Sty.[, 3] <- loSty output.matrix.Sty.[, 4] <- upSty dimnames(output.matrix.Sty.) <- list(c("1-2","2-3","3-4","4-5","5-6","6-7","7-8","8-9"), c("Stanines","SE", "lo", "up")) output.matrix.Pry. <- matrix(NA, K, 4) output.matrix.Pry.[, 1] <- Pry output.matrix.Pry.[, 2] <- Se.Pry output.matrix.Pry.[, 3] <- loPry output.matrix.Pry.[, 4] <- upPry dimnames(output.matrix.Pry.) <- list(R-adjust, c("Percentiles","SE", "lo", "up")) } return(list(mean = output.matrix.mean., sd = output.matrix.sd., z = output.matrix.Zy., sta9 = output.matrix.Sty., perc = output.matrix.Pry.)) }
CircleCI <- R6Class( "CircleCI", inherit = CI, public = list( get_branch = function() { Sys.getenv("CIRCLE_BRANCH") }, get_tag = function() { Sys.getenv("CIRCLE_TAG") }, is_tag = function() { self$get_tag() != "" }, get_slug = function() { sprintf( "%s/%s", Sys.getenv("CIRCLE_PROJECT_USERNAME"), Sys.getenv("CIRCLE_PROJECT_REPONAME") ) }, get_build_number = function() { paste0("CircleCI build ", self$get_env("CIRCLE_BUILD_NUM")) }, get_build_url = function() { Sys.getenv("CIRCLE_BUILD_URL") }, get_commit = function() { Sys.getenv("CIRCLE_COMMIT") }, can_push = function(name) { TRUE }, get_env = function(env) { Sys.getenv(env) }, is_env = function(env, value) { self$get_env(env) == value }, has_env = function(env) { self$get_env(env) != "" }, on_circle = function() { TRUE } ) )
fisher.test <- function(x, y = NULL, workspace = 200000, hybrid = FALSE, hybridPars = c(expect = 5, percent = 80, Emin = 1), control = list(), or = 1, alternative = "two.sided", conf.int = TRUE, conf.level = 0.95, simulate.p.value = FALSE, B = 2000) { DNAME <- deparse(substitute(x)) METHOD <- "Fisher's Exact Test for Count Data" if(is.data.frame(x)) x <- as.matrix(x) if(is.matrix(x)) { if(any(dim(x) < 2L)) stop("'x' must have at least 2 rows and columns") if(!is.numeric(x) || any(x < 0) || anyNA(x)) stop("all entries of 'x' must be nonnegative and finite") if(!is.integer(x)) { xo <- x x <- round(x) if(any(x > .Machine$integer.max)) stop("'x' has entries too large to be integer") if(!identical(TRUE, (ax <- all.equal(xo, x)))) warning(gettextf("'x' has been rounded to integer: %s", ax), domain = NA) storage.mode(x) <- "integer" } } else { if(is.null(y)) stop("if 'x' is not a matrix, 'y' must be given") if(length(x) != length(y)) stop("'x' and 'y' must have the same length") DNAME <- paste(DNAME, "and", deparse(substitute(y))) OK <- complete.cases(x, y) x <- as.factor(x[OK]) y <- as.factor(y[OK]) if((nlevels(x) < 2L) || (nlevels(y) < 2L)) stop("'x' and 'y' must have at least 2 levels") x <- table(x, y) } con <- list(mult = 30) con[names(control)] <- control if((mult <- as.integer(con$mult)) < 2) stop("'mult' must be integer >= 2, typically = 30") nr <- nrow(x) nc <- ncol(x) have.2x2 <- (nr == 2) && (nc == 2) if(have.2x2) { alternative <- char.expand(alternative, c("two.sided", "less", "greater")) if(length(alternative) > 1L || is.na(alternative)) stop("alternative must be \"two.sided\", \"less\" or \"greater\"") if(!((length(conf.level) == 1L) && is.finite(conf.level) && (conf.level > 0) && (conf.level < 1))) stop("'conf.level' must be a single number between 0 and 1") if(!missing(or) && (length(or) > 1L || is.na(or) || or < 0)) stop("'or' must be a single number between 0 and Inf") } PVAL <- NULL if(!have.2x2) { if(simulate.p.value) { sr <- rowSums(x) sc <- colSums(x) x <- x[sr > 0, sc > 0, drop = FALSE] nr <- as.integer(nrow(x)) nc <- as.integer(ncol(x)) if (is.na(nr) || is.na(nc) || is.na(nr * nc)) stop("invalid nrow(x) or ncol(x)", domain = NA) if(nr <= 1L) stop("need 2 or more non-zero row marginals") if(nc <= 1L) stop("need 2 or more non-zero column marginals") METHOD <- paste(METHOD, "with simulated p-value\n\t (based on", B, "replicates)") STATISTIC <- -sum(lfactorial(x)) tmp <- .Call(C_Fisher_sim, rowSums(x), colSums(x), B) almost.1 <- 1 + 64 * .Machine$double.eps PVAL <- (1 + sum(tmp <= STATISTIC/almost.1)) / (B + 1) } else if(hybrid) { if(!is.null(nhP <- names(hybridPars)) && !identical(nhP, c("expect", "percent", "Emin"))) stop("names(hybridPars) should be NULL or be identical to the default's") stopifnot(is.double(hypp <- as.double(hybridPars)), length(hypp) == 3L, hypp[1] > 0, hypp[3] >= 0, 0 <= hypp[2], hypp[2] <= 100) PVAL <- .Call(C_Fexact, x, hypp, workspace, mult) METHOD <- paste(METHOD, sprintf("hybrid using asym.chisq. iff (exp=%g, perc=%g, Emin=%g)", hypp[1], hypp[2], hypp[3])) } else { PVAL <- .Call(C_Fexact, x, c(-1, 100, 0), workspace, mult) } RVAL <- list(p.value = max(0, min(1, PVAL))) } else { if(hybrid) warning("'hybrid' is ignored for a 2 x 2 table") m <- sum(x[, 1L]) n <- sum(x[, 2L]) k <- sum(x[1L, ]) x <- x[1L, 1L] lo <- max(0L, k - n) hi <- min(k, m) NVAL <- c("odds ratio" = or) support <- lo : hi logdc <- dhyper(support, m, n, k, log = TRUE) dnhyper <- function(ncp) { d <- logdc + log(ncp) * support d <- exp(d - max(d)) d / sum(d) } mnhyper <- function(ncp) { if(ncp == 0) return(lo) if(ncp == Inf) return(hi) sum(support * dnhyper(ncp)) } pnhyper <- function(q, ncp = 1, upper.tail = FALSE) { if(ncp == 1) { return(if(upper.tail) phyper(x - 1, m, n, k, lower.tail = FALSE) else phyper(x, m, n, k)) } if(ncp == 0) { return(as.numeric(if(upper.tail) q <= lo else q >= lo)) } if(ncp == Inf) { return(as.numeric(if(upper.tail) q <= hi else q >= hi)) } sum(dnhyper(ncp)[if(upper.tail) support >= q else support <= q]) } if(is.null(PVAL)) { PVAL <- switch(alternative, less = pnhyper(x, or), greater = pnhyper(x, or, upper.tail = TRUE), two.sided = { if(or == 0) as.numeric(x == lo) else if(or == Inf) as.numeric(x == hi) else { relErr <- 1 + 10 ^ (-7) d <- dnhyper(or) sum(d[d <= d[x - lo + 1] * relErr]) } }) RVAL <- list(p.value = PVAL) } mle <- function(x) { if(x == lo) return(0) if(x == hi) return(Inf) mu <- mnhyper(1) if(mu > x) uniroot(function(t) mnhyper(t) - x, c(0, 1))$root else if(mu < x) 1 / uniroot(function(t) mnhyper(1/t) - x, c(.Machine$double.eps, 1))$root else 1 } ESTIMATE <- c("odds ratio" = mle(x)) if(conf.int) { ncp.U <- function(x, alpha) { if(x == hi) return(Inf) p <- pnhyper(x, 1) if(p < alpha) uniroot(function(t) pnhyper(x, t) - alpha, c(0, 1))$root else if(p > alpha) 1 / uniroot(function(t) pnhyper(x, 1/t) - alpha, c(.Machine$double.eps, 1))$root else 1 } ncp.L <- function(x, alpha) { if(x == lo) return(0) p <- pnhyper(x, 1, upper.tail = TRUE) if(p > alpha) uniroot(function(t) pnhyper(x, t, upper.tail = TRUE) - alpha, c(0, 1))$root else if(p < alpha) 1 / uniroot(function(t) pnhyper(x, 1/t, upper.tail = TRUE) - alpha, c(.Machine$double.eps, 1))$root else 1 } CINT <- switch(alternative, less = c(0, ncp.U(x, 1 - conf.level)), greater = c(ncp.L(x, 1 - conf.level), Inf), two.sided = { alpha <- (1 - conf.level) / 2 c(ncp.L(x, alpha), ncp.U(x, alpha)) }) attr(CINT, "conf.level") <- conf.level } RVAL <- c(RVAL, list(conf.int = if(conf.int) CINT, estimate = ESTIMATE, null.value = NVAL)) } structure(c(RVAL, alternative = alternative, method = METHOD, data.name = DNAME), class = "htest") }
find_random_slopes <- function(x) { random_slopes <- vector(mode = "list") forms <- find_formula(x, verbose = FALSE) random_slopes$random <- .extract_random_slopes(forms$random) random_slopes$zero_inflated_random <- .extract_random_slopes(forms$zero_inflated_random) random_slopes <- .compact_list(random_slopes) if (.is_empty_object(random_slopes)) { NULL } else { random_slopes } } .extract_random_slopes <- function(fr) { if (is.null(fr)) { return(NULL) } if (!is.list(fr)) fr <- list(fr) random_slope <- lapply(fr, function(forms) { if (grepl("(.*)\\|(.*)\\|(.*)", .safe_deparse(forms))) { pattern <- "(.*)\\|(.*)\\|(.*)" } else { pattern <- "(.*)\\|(.*)" } pattern <- gsub(pattern, "\\1", .safe_deparse(forms)) re <- all.vars(forms) re[sapply(re, function(x) { grepl(x, pattern, fixed = TRUE) })] }) unique(unlist(.compact_list(random_slope))) }
library(vtreat) dTrainC <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6),y=c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE), stringsAsFactors = FALSE) treatmentsC <- designTreatmentsC(dTrainC,colnames(dTrainC),'y',TRUE) scoreColsToPrint <- c('origName','varName','code','rsq','sig','extraModelDegrees') print(treatmentsC$scoreFrame[,scoreColsToPrint]) vmap <- as.list(treatmentsC$scoreFrame$origName) names(vmap) <- treatmentsC$scoreFrame$varName print(vmap['x_catB']) aggregate(sig~origName,data=treatmentsC$scoreFrame,FUN=min) library(vtreat) dTrainN <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6),y=as.numeric(c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE)), stringsAsFactors = FALSE) treatmentsN <- designTreatmentsN(dTrainN,colnames(dTrainN),'y') print(treatmentsN$scoreFrame[,scoreColsToPrint]) library(vtreat) dTrainZ <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6), stringsAsFactors = FALSE) treatmentsZ <- designTreatmentsZ(dTrainZ,colnames(dTrainZ)) print(treatmentsZ$scoreFrame[, c('origName','varName','code','extraModelDegrees')]) dTrainN <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6),y=as.numeric(c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE)), stringsAsFactors = FALSE) treatmentsN <- designTreatmentsN(dTrainN,colnames(dTrainN),'y', codeRestriction = c('lev', 'catN', 'clean', 'isBAD'), verbose=FALSE) print(treatmentsN$scoreFrame[,scoreColsToPrint]) dTreated = prepare(treatmentsN, dTrainN, codeRestriction = c('lev','clean', 'isBAD')) head(dTreated) dTrainN <- data.frame(x=c('a','a','a','b','b',NA), z=c(1,2,3,4,NA,6),y=as.numeric(c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE)), stringsAsFactors = FALSE) treatmentsN <- designTreatmentsN(dTrainN,colnames(dTrainN),'y', codeRestriction = c('lev', 'catN', 'clean', 'isBAD'), verbose=FALSE) print(treatmentsN$scoreFrame[,scoreColsToPrint]) pruneSig <- 1.0 vScoreFrame <- treatmentsN$scoreFrame varsToUse <- vScoreFrame$varName[(vScoreFrame$sig<=pruneSig)] print(varsToUse) origVarNames <- sort(unique(vScoreFrame$origName[vScoreFrame$varName %in% varsToUse])) print(origVarNames) dTreated = prepare(treatmentsN, dTrainN, varRestriction = varsToUse) head(dTreated) origVarNames <- sort(unique(vScoreFrame$origName[vScoreFrame$varName %in% varsToUse])) print(origVarNames) origVarSigs <- vScoreFrame[vScoreFrame$varName %in% varsToUse,] aggregate(sig~origName,data=origVarSigs,FUN=min)