code
stringlengths
1
13.8M
Trunkpoint <- function(B, K, pvalues) { trunks <- matrix(0,ncol=K, nrow=B+1) trunks[,1] <- -log(pvalues[,1]) if(K==1) return(trunks) for(j in 2:K) { trunks[,j] <- trunks[,j-1]+(-log(pvalues[,j])) } return(trunks) }
defIconFunction <- JS("function(icon){ if (!$.isEmptyObject(icon)) { return L.icon(icon); } else { return L.icon(); } }") awesomeIconFunction <- JS("function(icon){ if (!$.isEmptyObject(icon)) { if (!icon.prefix) { icon.prefix = icon.library; } return L.AwesomeMarkers.icon(icon); } else { return L.AwesomeMarkers.icon(); } }") propsToHTML <- function(props, elem = NULL, elem.attrs = NULL) { if (!(inherits(props, "list") || (class(props) == "character")) || length(props) < 1 ) { stop("props needs to to be a list/vector of character strings with at least one element") } if (!is.null(elem.attrs) && (!inherits(elem.attrs, "list") || length(elem.attrs) < 1 || is.null(names(elem.attrs)))) { stop("If elem.attrs is provided, then it needs to be a named list with atleast one element") } JS(sprintf( "function(feature){return \"%s\" + L.Util.template(\"%s\",feature.properties); + \"%s\";}", if (!is.null(elem) && !elem == "") sprintf("<%s%s>", elem, if (!is.null(elem.attrs)) paste(sapply(names(elem.attrs), function(attr) sprintf(" %s=\"%s\"", attr, elem.attrs[[attr]])), collapse = " ") else "" ) else "", if (length(props) > 1) paste(stringr::str_replace(props, "(.*)", "{\\1}"), collapse = ", ") else props, if (!is.null(elem) && !elem == "") sprintf("</%s>", elem) else "" )) } propstoHTMLTable <- function(props = NULL, table.attrs = NULL, drop.na = TRUE) { if (!is.null(table.attrs) && (!inherits(table.attrs, "list") || length(table.attrs) < 1 || is.null(names(table.attrs)))) { stop("If table.attrs is provided, then it needs to be a named list with at least one element") } if (!is.null(props) && length(props) >= 1) JS(sprintf( "function(feature){ return '<table%s><caption>Properties</caption><tbody style=\"font-size:x-small\">' + ( $.isEmptyObject(feature.properties) ? '' : L.Util.template(\"%s\",feature.properties) )+ \"</tbody></table>\"; }", if (!is.null(table.attrs)) paste(sapply(names(table.attrs), function(attr) sprintf(" %s=\"%s\"", attr, table.attrs[[attr]])), collapse = " ") else "", paste(stringr::str_replace(props, "(.*)", "<tr><td><b>\\1</b></td><td>{\\1}</td></tr>"), collapse = "") )) else JS(sprintf( "function(feature){ return '<table%s><caption>Properties</caption><tbody style=\"font-size:x-small\">' + ( function(props) { var rws = ''; $.each(props, function (k, v) { if ( %s ||(v !== null && typeof v !== \"undefined\")) { rws = rws.concat(\"<tr><td><b>\"+k+\"</b></td><td>\"+ ((v !== null && typeof v !== \"undefined\") ? v : '') + \"</td></tr>\"); } }); return rws; })(feature.properties) + \"</tbody></table>\";}", if (!is.null(table.attrs)) paste(sapply(names(table.attrs), function(attr) sprintf(" %s=\"%s\"", attr, table.attrs[[attr]])), collapse = " ") else "", if (drop.na) "false" else "true" )) }
NULL if( 0 == 1 ) { library(jsonlite ) spectra <- getSpectraInTimeExample() directory <- tempdir() saveSpectra( spectra , directory ) experimentName <- getExperimentName( spectra ) file <- file.path( directory , paste0( experimentName , ".txt") ) spectraRead <- readSpectra( file ) unlink( directory ) identical( spectra , spectraRead ) identical( str( spectra ) , str( spectraRead ) ) identical( ( spectra@spectra ) , ( spectraRead@spectra ) ) all.equal( ( spectra@spectra ) , ( spectraRead@spectra ) ) spectra@spectra[ 1:3 , 1:5 ] spectraRead@spectra[ 1:3 , 1:5 ] plot( spectra ) plot( spectraRead ) identical( ( spectra@startTime ) , ( spectraRead@startTime ) ) x= spectra y = spectraRead testIdenticalS4 <- function( x , y ){ objectClass <- class( x ) class( object ) } file <- filePath unlink( directory ) object <- spectra directory precision = 32 } saveSpectra <- function( object , directory , precision = 32 ) { objectAsList <- convertS4ToList( object ) experimentName <- getExperimentName( object ) fileName <- paste0( experimentName , ".txt" ) filePath <- file.path( directory , fileName ) testJSON <- toJSON( objectAsList , force=TRUE, auto_unbox=TRUE, pretty=FALSE , digits = I(precision) ) cat( testJSON , file = filePath ) return( filePath ) } readSpectra <- function( file ){ objectAsList <- read_json(path = file , simplifyVector = TRUE ) objectAsListFormat <- objectAsList startTime <- objectAsList$startTime startTimeFormat <- as.POSIXct( startTime ) objectAsListFormat[[ "startTime" ]] <- startTimeFormat objectAsSpectraInTime <- convertListToS4( objectAsListFormat , "SpectraInTime" ); return( objectAsSpectraInTime ) }
Network <- R6::R6Class(classname = "Network", portable = TRUE, cloneable = FALSE, lock_class = FALSE, lock_objects = FALSE, class = FALSE, public = list( initialize = function(params, driveCube, patchReleases, migrationMale, migrationFemale, migrationBatch = NULL, directory, verbose = TRUE){ if(length(patchReleases) != params$nPatch){ stop("length of patchReleases must equal number of patches in params!") } private$parameters = params private$nPatch = params$nPatch private$patches = vector(mode="list",length=private$nPatch) private$simTime = params$simTime private$sampTime = params$sampTime private$driveCube = driveCube private$directory = directory private$runID = params$runID private$migrationMale = migrationMale private$migrationFemale = migrationFemale private$migrationBatch = migrationBatch private$mMoveMat = matrix(data = 0, nrow = private$driveCube$genotypesN, ncol = private$nPatch, dimnames = list(private$driveCube$genotypesID, NULL)) private$fMoveArray = array(data = 0, dim = c(private$driveCube$genotypesN, private$driveCube$genotypesN, private$nPatch), dimnames = list(private$driveCube$genotypesID, private$driveCube$genotypesID, NULL)) private$patchReleases = patchReleases for(i in 1:private$nPatch){ if(verbose){cat("initializing patch: ", i, " of ", private$nPatch, "\n")} private$patches[[i]] = Patch$new(patchID = i, genotypesID = driveCube$genotypesID, timeAq = params$timeAq, numPatches = private$nPatch, adultEQ = params$AdPopEQ[i], larvalEQ = params$Leq[i], muAq = params$muAq, alpha = params$alpha[i], adultRatioF = params$AdPopRatio_F[i, ], adultRatioM = params$AdPopRatio_M[i, ], larvalRatio = params$LarPopRatio[i, ], eggReleases = patchReleases[[i]]$eggReleases, maleReleases = patchReleases[[i]]$maleReleases, femaleReleases = patchReleases[[i]]$femaleReleases, matedFemaleReleases = patchReleases[[i]]$matedFemaleReleases ) private$patches[[i]]$set_NetworkPointer(self) } if(!all(dir.exists(directory))){ for(f in directory){suppressWarnings(dir.create(f))} } else { dirFiles = list.files(path = directory) if(length(dirFiles)>0){ if(verbose){ cat("warning: ", length(dirFiles), " files found in the output directory; please move files to avoid being overwritten\n", sep="") } } } } ), private = list( parameters = NULL, patches = NULL, nPatch = NULL, simTime = NULL, sampTime = NULL, driveCube = NULL, tNow = 2L, runID = numeric(1), directory = NULL, conADM = NULL, conADF = NULL, migrationMale = NULL, migrationFemale = NULL, migrationBatch = NULL, mMoveMat = NULL, fMoveArray = NULL, patchReleases = NULL ) ) get_timeAq_Network <- function(stage = NULL){ if(is.null(stage)){ return(sum(private$parameters$timeAq)) } else { return(private$parameters$timeAq[[stage]]) } } Network$set(which = "public",name = "get_timeAq", value = get_timeAq_Network,overwrite = TRUE ) get_beta_Network <- function(){return(private$parameters$beta)} Network$set(which = "public",name = "get_beta", value = get_beta_Network,overwrite = TRUE ) get_muAd_Network <- function(){return(private$parameters$muAd)} Network$set(which = "public",name = "get_muAd", value = get_muAd_Network,overwrite = TRUE ) get_muAq_Network <- function(){return(private$parameters$muAq)} Network$set(which = "public",name = "get_muAq", value = get_muAq_Network,overwrite = TRUE ) get_alpha_Network <- function(ix){return(private$parameters$alpha[ix])} Network$set(which = "public",name = "get_alpha", value = get_alpha_Network,overwrite = TRUE ) get_drivecubeindex_Network <- function(fG=NULL,mG=NULL,oG=NULL){ if(is.null(fG)){fG = 1:private$driveCube$genotypesN} if(is.null(mG)){mG = 1:private$driveCube$genotypesN} if(is.null(oG)){oG = 1:private$driveCube$genotypesN} return(private$driveCube$ih[fG,mG,oG]) } Network$set(which = "public",name = "get_drivecubeindex", value = get_drivecubeindex_Network,overwrite = TRUE ) get_tau_Network <- function(fG=NULL,mG=NULL,oG=NULL){ if(is.null(fG)){fG = 1:private$driveCube$genotypesN} if(is.null(mG)){mG = 1:private$driveCube$genotypesN} if(is.null(oG)){oG = 1:private$driveCube$genotypesN} return(private$driveCube$tau[fG,mG,oG]) } Network$set(which = "public",name = "get_tau", value = get_tau_Network,overwrite = TRUE ) get_genotypesID_Network <- function(){return(private$driveCube$genotypesID)} Network$set(which = "public",name = "get_genotypesID", value = get_genotypesID_Network,overwrite = TRUE ) get_genotypesN_Network <- function(){return(private$driveCube$genotypesN)} Network$set(which = "public",name = "get_genotypesN", value = get_genotypesN_Network,overwrite = TRUE ) get_eta_Network <- function(fIdx){return(private$driveCube$eta[fIdx, ])} Network$set(which = "public",name = "get_eta", value = get_eta_Network,overwrite = TRUE ) get_phi_Network <- function(){return(private$driveCube$phi)} Network$set(which = "public",name = "get_phi", value = get_phi_Network,overwrite = TRUE ) get_omega_Network <- function(){return(private$driveCube$omega)} Network$set(which = "public",name = "get_omega", value = get_omega_Network,overwrite = TRUE ) get_xiF_Network <- function(){return(private$driveCube$xiF)} Network$set(which = "public",name = "get_xiF", value = get_xiF_Network,overwrite = TRUE ) get_xiM_Network <- function(){return(private$driveCube$xiM)} Network$set(which = "public",name = "get_xiM", value = get_xiM_Network,overwrite = TRUE ) get_s_Network <- function(){return(private$driveCube$s)} Network$set(which = "public",name = "get_s", value = get_s_Network,overwrite = TRUE ) get_nPatch_Network <- function(){return(private$nPatch)} Network$set(which = "public",name = "get_nPatch", value = get_nPatch_Network,overwrite = TRUE ) get_conM_Network <- function(){return(private$conADM)} Network$set(which = "public",name = "get_conADM", value = get_conM_Network,overwrite = TRUE ) get_conF_Network <- function(){return(private$conADF)} Network$set(which = "public",name = "get_conADF", value = get_conF_Network,overwrite = TRUE ) get_tNow_Network <- function(){return(private$tNow)} Network$set(which = "public",name = "get_tNow", value = get_tNow_Network,overwrite = TRUE ) get_patchReleases_Network <- function(patch, sex = "M"){ switch(sex, M = {return(private$patchReleases[[patch]]$maleReleases)}, F = {return(private$patchReleases[[patch]]$femaleReleases)}, Egg = {return(private$patchReleases[[patch]]$eggReleases)}, mF = {return(private$patchReleases[[patch]]$matedFemaleReleases)} ) } Network$set(which = "public",name = "get_patchReleases", value = get_patchReleases_Network,overwrite = TRUE )
loo.cv <- function(mod, nsim=100, bias.corr=FALSE){ if(!is.element(class(mod)[1], c("lm", "glm"))) stop("mod must be an lm or glm object since leave-one-out cross-validation is only reliable when the observations are independent.") y <- mod$model[,1] n <- length(y) if(n > sum(!is.na(y))) stop("y must not contain missing values") logpostminusi.yi <- numeric(n) lppdji <- matrix(ncol=n, nrow=n) lppdj <- numeric(n) family <- mod$family$family if(is.null(family)) family <- "gaussian" link <- mod$family$link if(is.null(link)) { ilink <- "identity" link <- "identity" } if(link=="identity") ilink <- "identity" if(link=="log") ilink <- "exp" if(link=="logit") ilink <- "plogis" for(i in 1:n){ dataminusi <- mod$model[-i,] if(class(dataminusi)!="data.frame"){ dataminusi <- data.frame(dataminusi) names(dataminusi) <- names(mod$model) } modminusi <- update(mod, data=dataminusi) bsimminusi <- sim(modminusi, n.sim=nsim) predi <- numeric(nsim) predj <- numeric(nsim) Xmat <- model.matrix(mod)[i,] for(r in 1:nsim) predi[r] <- eval(parse(text=ilink))(Xmat%*%bsimminusi@coef[r,]) if(family=="gaussian"|family=="Gaussian"){ logpostminusi.yi[i] <- log(sum(dnorm(y[i], predi, bsimminusi@sigma))/nsim) if(bias.corr){ for(j in 1:n){ Xmatj <- model.matrix(mod)[j,] for(r in 1:nsim) predj[r] <- eval(parse(text=ilink))(Xmatj%*%bsimminusi@coef[r,]) lppdji[i,j] <- log(sum(dnorm(y[j], predj, bsimminusi@sigma))/nsim) } } } if(family=="binomial"|family=="Binomial"){ if(length(dim(y))>1) N <- apply(y, 1, sum) else N <- rep(1, n) if(length(dim(y))>1) y <- y[,1] logpostminusi.yi[i] <- log(sum(dbinom(y[i], prob=predi, size=N[i]))/nsim) if(bias.corr){ for(j in 1:n){ Xmatj <- model.matrix(mod)[j,] for(r in 1:nsim) predj[r] <- eval(parse(text=ilink))(Xmatj%*%bsimminusi@coef[r,]) lppdji[i,j] <- log(sum(dbinom(y[j], prob=predj, size=N[j]))/nsim) } } } if(family=="poisson"|family=="Poisson"){ logpostminusi.yi[i] <- log(sum(dpois(y[i], predi))/nsim) if(bias.corr){ for(j in 1:n){ Xmatj <- model.matrix(mod)[j,] for(r in 1:nsim) predj[r] <- eval(parse(text=ilink))(Xmatj%*%bsimminusi@coef[r,]) lppdji[i,j] <- log(sum(dpois(y[j], predj))/nsim) } } } } lppd_loo.cv <- sum(logpostminusi.yi) lppd_cloo.cv <- NULL bsim <- sim(mod, n.sim=nsim) predorig <- matrix(ncol=nsim, nrow=n) if(family=="gaussian"|family=="Gaussian"){ for(r in 1:nsim) predorig[,r] <- eval(parse(text=ilink))(model.matrix(mod)%*%bsim@coef[r,]) for(j in 1:n) { lppdj[j] <- log((1/nsim) * sum(dnorm(y[j], predorig[j,], bsim@sigma))) } } if(family=="binomial"|family=="Binomial"){ for(r in 1:nsim) predorig[,r] <- eval(parse(text=ilink))(model.matrix(mod)%*%bsim@coef[r,]) for(j in 1:n) { lppdj[j] <- log((1/nsim) * sum(dbinom(y[j], prob=predorig[j,], size=N[j]))) } } if(family=="poisson"|family=="Poisson"){ for(r in 1:nsim) predorig[,r] <- eval(parse(text=ilink))(model.matrix(mod)%*%bsim@coef[r,]) for(j in 1:n) { lppdj[j] <- log((1/nsim) * sum(dpois(y[j], predorig[j,]))) } } if(bias.corr) lppdminusi_quer <- sum(apply(lppdji, 1, sum))/n lppd <- sum(lppdj) if(bias.corr) b <-lppd-lppdminusi_quer if(bias.corr) lppd_cloo.cv <- lppd_loo.cv+b itscale <- -2*ifelse(bias.corr, lppd_cloo.cv, lppd_loo.cv) peff <- lppd - ifelse(bias.corr, lppd_cloo.cv, lppd_loo.cv) return(list(LOO.CV=lppd_loo.cv, bias.corrected.LOO.CV=lppd_cloo.cv, minus2times_lppd=itscale,est.peff=peff)) }
isColour <- function(x) return(length(setdiff(x,colors()))==0)
hasAttributes = function(obj, attribute.names) { isSubset(attribute.names, getAttributeNames(obj)) }
context("Export html report") path_name <- getwd() file_name <- "testthat_expreport.html" file_dir <- file.path(path_name, file_name) test_that("test overall exp report function", { skip_on_cran() expect_error(ExpReport(mtcars$mpg, Template = NULL, Target = "gear", label = NULL, theme = "Default", op_file = file_name, op_dir = path_name, sc = 2, sn = 2, Rc = 4)) expect_error(ExpReport(mtcars$mpg, Template = NULL, Target = "gear", label = NULL, op_dir = path_name, sc = 2, sn = 2, Rc = 4)) if (file.exists(file_dir)) file.remove(file_dir) })
ma_r_order2 <- function(k, N = NULL, r = NULL, rho = NULL, var_r = NULL, var_r_c = NULL, ma_type = c("bb", "ic", "ad"), sample_id = NULL, citekey = NULL, moderators = NULL, moderator_type = "simple", construct_x = NULL, construct_y = NULL, construct_order = NULL, data = NULL, control = control_psychmeta(), ...){ .dplyr.show_progress <- options()$dplyr.show_progress .psychmeta.show_progress <- psychmeta.show_progress <- options()$psychmeta.show_progress if(is.null(psychmeta.show_progress)) psychmeta.show_progress <- TRUE options(dplyr.show_progress = psychmeta.show_progress) call <- match.call() warn_obj1 <- record_warnings() ma_type <- match.arg(ma_type, c("bb", "ic", "ad"), several.ok = TRUE) control <- control_psychmeta(.psychmeta_ellipse_args = list(...), .control_psychmeta_arg = control) conf_level <- control$conf_level cred_level <- control$cred_level conf_method <- control$conf_method cred_method <- control$cred_method var_unbiased <- control$var_unbiased hs_override <- control$hs_override if(hs_override){ conf_method <- cred_method <- "norm" var_unbiased <- FALSE } formal_args <- formals(ma_r_order2) for(i in names(formal_args)) if(i %in% names(call)) formal_args[[i]] <- NULL call_full <- as.call(append(as.list(call), formal_args)) if(!is.null(data)){ data <- as.data.frame(data, stringsAsFactors = FALSE) k <- match_variables(call = call_full[[match("k", names(call_full))]], arg = k, arg_name = "k", data = data) if(deparse(substitute(N))[1] != "NULL") N <- match_variables(call = call_full[[match("N", names(call_full))]], arg = N, arg_name = "N", data = data) if(deparse(substitute(r))[1] != "NULL") r <- match_variables(call = call_full[[match("r", names(call_full))]], arg = r, arg_name = "r", data = data) if(deparse(substitute(rho))[1] != "NULL") rho <- match_variables(call = call_full[[match("rho", names(call_full))]], arg = rho, arg_name = "rho", data = data) if(deparse(substitute(var_r))[1] != "NULL") var_r <- match_variables(call = call_full[[match("var_r", names(call_full))]], arg = var_r, arg_name = "var_r", data = data) if(deparse(substitute(var_r_c))[1] != "NULL") var_r_c <- match_variables(call = call_full[[match("var_r_c", names(call_full))]], arg = var_r_c, arg_name = "var_r_c", data = data) if(deparse(substitute(sample_id))[1] != "NULL") sample_id <- match_variables(call = call_full[[match("sample_id", names(call_full))]], arg = sample_id, arg_name = "sample_id", data = data) if(deparse(substitute(citekey))[1] != "NULL") citekey <- match_variables(call = call_full[[match("citekey", names(call_full))]], arg = citekey, arg_name = "citekey", data = data) if(deparse(substitute(moderators))[1] != "NULL") moderators <- match_variables_df({{moderators}}, data = as_tibble(data, .name_repair = "minimal"), name = deparse(substitute(moderators))) if(deparse(substitute(construct_x))[1] != "NULL") construct_x <- match_variables(call = call_full[[match("construct_x", names(call_full))]], arg = construct_x, arg_name = "construct_x", data = data) if(deparse(substitute(construct_y))[1] != "NULL") construct_y <- match_variables(call = call_full[[match("construct_y", names(call_full))]], arg = construct_y, arg_name = "construct_y", data = data) } valid_r <- filter_r_bar(r_bar_vec = r, k_vec = k) if (all(!valid_r)) { stop("No valid correlations and/or numbers of studies provided", call. = FALSE) } if (sum(!valid_r) > 0) { if (sum(!valid_r) == 1) { warning(sum(!valid_r), " invalid correlation and/or number of studies detected: Offending entry has been removed", call. = FALSE) } else { warning(sum(!valid_r), " invalid correlations and/or numbers of studies detected: Offending entries have been removed", call. = FALSE) } } if(!is.null(moderators)){ moderator_names <- list(all = colnames(moderators), cat = colnames(moderators), noncat = colnames(moderators)) moderator_names <- lapply(moderator_names, function(x) if(length(x) == 0){NULL}else{x}) moderator_levels <- lapply(as_tibble(moderators, .name_repair = "minimal"), function(x){ lvls <- levels(x) if(is.null(lvls)) lvls <- levels(factor(x)) lvls }) names(moderator_levels) <- colnames(moderators) moderators <- as.data.frame(moderators, stringsAsFactors = FALSE) }else{ moderator_names <- list(all = NULL, cat = NULL, noncat = NULL) moderator_levels <- NULL } if (!is.null(construct_order)) { if (any(duplicated(construct_order))) { warning("Each element of 'construct_order' must have a unique value: First occurence of each value used", call. = FALSE) construct_order <- construct_order[!duplicated(construct_order)] } if (!is.null(construct_x) | !is.null(construct_y)) { keep_construct <- as.character(construct_order) %in% c(as.character(construct_x), as.character(construct_y)) if (any(!keep_construct)) { warning("'construct_order' contained invalid construct names: Invalid names removed", call. = FALSE) } construct_order <- construct_order[keep_construct] } if (!is.null(construct_x) & !is.null(construct_y)) { valid_r <- valid_r & construct_x %in% construct_order & construct_y %in% construct_order } else { if (!is.null(construct_x)) { valid_r <- valid_r & construct_x %in% construct_order } if (!is.null(construct_y)) { valid_r <- valid_r & construct_y %in% construct_order } } if (all(!valid_r)) { stop("No valid construct combinations provided", call. = FALSE) } } inputs <- list(k = k, N = N, r = r, rho = rho, var_r = var_r, var_r_c = var_r_c, sample_id = sample_id, citekey = citekey, moderators = moderators, construct_x = construct_x, construct_y = construct_y, conf_level = conf_level, cred_level = cred_level, cred_method = cred_method, var_unbiased = var_unbiased, data = data) dat_var <- c("sample_id", "citekey", "construct_x", "construct_y", "moderators", "k", "N", "r", "rho", "var_r", "var_r_c") dat <- NULL for(v in dat_var){ if(!is.null(inputs[[v]])){ if(v == "moderators"){ moderators <- inputs[[v]] }else{ if(v != "construct_x" & v != "construct_y"){ if(is.null(dat)){ dat <- data.frame(inputs[[v]], stringsAsFactors = FALSE) }else{ dat <- data.frame(dat, inputs[[v]], stringsAsFactors = FALSE) } colnames(dat)[ncol(dat)] <- v } } }else{ if(v == "moderators"){ moderator_matrix <- NULL } } } if(is.null(dat$N)) dat$N <- NA bb_req <- c("k", "r", "var_r") ic_req <- c("k", "rho", "var_r_c") ad_req <- c("k", "r", "rho", "var_r") nonnull <- lapply(inputs, function(x) !is.null(x)) nonnull <- names(nonnull)[unlist(nonnull)] do_bb <- all(bb_req %in% nonnull) & "bb" %in% ma_type do_ic <- all(ic_req %in% nonnull) & "ic" %in% ma_type do_ad <- all(ad_req %in% nonnull) & "ad" %in% ma_type if("bb" %in% ma_type & !do_bb) stop("For bare-bones meta-analyses, the following data arguments must be supplied: ", paste(bb_req, collapse = ", "), call. = FALSE) if("ic" %in% ma_type & !do_ic) stop("For individual-correction meta-analyses, the following data arguments must be supplied: ", paste(ic_req, collapse = ", "), call. = FALSE) if("ad" %in% ma_type & !do_ad) stop("For artifact-distribution, the following data arguments must be supplied: ", paste(ad_req, collapse = ", "), call. = FALSE) out <- ma_wrapper(es_data = dat, es_type = "r", ma_type = "r_order2", ma_fun = .ma_r_order2, moderator_matrix = moderators, moderator_type = moderator_type, cat_moderators = TRUE, construct_x = construct_x, construct_y = construct_y, construct_order = construct_order, ma_arg_list = append(inputs, list(do_bb = do_bb, do_ic = do_ic, do_ad = do_ad, ma_metric = "r")), moderator_levels = moderator_levels, moderator_names = moderator_names) neg_var_r_order2 <- sum(unlist(map(out$meta_tables, function(x) x$barebones$var_r_bar < 0)), na.rm = TRUE) neg_var_rho_ic_order2 <- sum(unlist(map(out$meta_tables, function(x) x$individual_correction$var_rho_bar < 0)), na.rm = TRUE) neg_var_rho_ad_order2 <- sum(unlist(map(out$meta_tables, function(x) x$artifact_distribution$var_rho_bar < 0)), na.rm = TRUE) default_print <- if(do_ic){ "ic" }else if(do_ad){ "ad" }else if(do_bb){ "bb" } out <- bind_cols(analysis_id = 1:nrow(out), out) attributes(out) <- append(attributes(out), list(call_history = list(call), inputs = inputs, ma_methods = c("bb", "ic", "ad")[c(do_bb, do_ic, do_ad)], ma_metric = "r_order2", default_print = default_print, warnings = clean_warning(warn_obj1 = warn_obj1, warn_obj2 = record_warnings()), fyi = record_fyis(es_metric = "r_order2", neg_var_r_order2 = neg_var_r_order2, neg_var_rho_ic_order2 = neg_var_rho_ic_order2, neg_var_rho_ad_order2 = neg_var_rho_ad_order2))) out <- namelists.ma_psychmeta(ma_obj = out) class(out) <- c("ma_psychmeta", class(out)) options(psychmeta.show_progress = .psychmeta.show_progress) options(dplyr.show_progress = .dplyr.show_progress) out } .ma_r_order2 <- function(data, type = "all", run_lean = FALSE, ma_arg_list){ conf_level <- ma_arg_list$conf_level cred_level <- ma_arg_list$cred_level conf_method <- ma_arg_list$conf_method cred_method <- ma_arg_list$cred_method var_unbiased <- ma_arg_list$var_unbiased ma_metric <- ma_arg_list$ma_metric k <- data$k N <- data$N if(ma_metric == "r"){ r <- data$r rho <- data$rho var_r <- data$var_r var_r_c <- data$var_r_c }else{ r <- data$d rho <- data$delta var_r <- data$var_d var_r_c <- data$var_d_c } do_bb <- ma_arg_list$do_bb do_ic <- ma_arg_list$do_ic do_ad <- ma_arg_list$do_ad if((type == "all" | type == "bb") & do_bb){ out_bb <- .ma_r_order2_bb(data = data, k_vec = k, N_vec = N, r_vec = r, var_r_vec = var_r, conf_level = conf_level, cred_level = cred_level, cred_method = cred_method, conf_method = conf_method, var_unbiased = var_unbiased, run_lean = run_lean, ma_metric = ma_metric) }else{ out_bb <- NULL } if((type == "all" | type == "ic") & do_ic){ out_ic <- .ma_r_order2_ic(data = data, k_vec = k, N_vec = N, rho_vec = rho, var_r_c_vec = var_r_c, conf_level = conf_level, cred_level = cred_level, cred_method = cred_method, conf_method = conf_method, var_unbiased = var_unbiased, run_lean = run_lean, ma_metric = ma_metric) }else{ out_ic <- NULL } if((type == "all" | type == "ad") & do_ad){ out_ad <- .ma_r_order2_ad(data = data, k_vec = k, N_vec = N, r_vec = r, rho_vec = rho, var_r_vec = var_r, conf_level = conf_level, cred_level = cred_level, cred_method = cred_method, conf_method = conf_method, var_unbiased = var_unbiased, run_lean = run_lean, ma_metric = ma_metric) }else{ out_ad <- NULL } list(meta = list(barebones = out_bb$meta, individual_correction = out_ic$meta, artifact_distribution = out_ad$meta), escalc = list(barebones = out_bb$escalc, individual_correction = out_ic$escalc, artifact_distribution = out_ad$escalc)) } .ma_r_order2_bb <- function(data = NULL, k_vec = NULL, N_vec = NULL, r_vec = NULL, var_r_vec = NULL, conf_level = .95, cred_level = .8, conf_method = "t", cred_method = "t", var_unbiased = TRUE, run_lean = FALSE, ma_metric = "r"){ arg_list <- list(k_vec = k_vec, N_vec = N_vec, r_vec = r_vec, var_r_vec = var_r_vec) check_null <- !unlist(lapply(arg_list, is.null)) if(all(!check_null)){ length_vec <- unlist(lapply(arg_list, length)) if(any(length_vec[1] != length_vec[-1])) stop("Vector arguments have inconsistent numbers of elements") } var_e_vec <- var_r_vec / k_vec wt_vec <- 1 / var_e_vec mean_r <- wt_mean(x = r_vec, wt = wt_vec) var_r <- wt_var(x = r_vec, wt = wt_vec, unbiased = var_unbiased) var_e <- wt_mean(x = var_e_vec, wt = wt_vec) var_res <- var_r - var_e sd_r <- var_r^.5 sd_e <- var_e^.5 sd_res <- var_res^.5 sd_r[is.na(sd_r)] <- sd_e[is.na(sd_e)] <- sd_res[is.na(sd_res)] <- 0 if(run_lean){ dat <- NULL }else{ if(ma_metric == "r"){ dat <- data.frame(yi = r_vec, vi = var_e_vec, r = r_vec, var_r = var_r_vec, k = k_vec, var_e = var_e_vec, weight = wt_vec, residual = r_vec - mean_r, stringsAsFactors = FALSE) }else if(ma_metric == "d"){ dat <- data.frame(yi = r_vec, vi = var_e_vec, d = r_vec, var_d = var_r_vec, k = k_vec, var_e = var_e_vec, weight = wt_vec, residual = r_vec - mean_r, stringsAsFactors = FALSE) } if(any(colnames(data) == "original_order")) dat <- cbind(original_order = data$original_order, dat) class(dat) <- c("escalc", "data.frame") } L <- sum(!is.na(wt_vec)) k <- sum(k_vec[!is.na(wt_vec) & !is.na(r_vec)]) N <- sum(N_vec[!is.na(wt_vec)]) conf_int <- confidence(mean = mean_r, sd = sd_r, k = k, conf_level = conf_level, conf_method = conf_method) cred_int <- credibility(mean = mean_r, sd = sd_res, cred_level = cred_level, k = k, cred_method = cred_method) conf_int <- setNames(c(conf_int), colnames(conf_int)) cred_int <- setNames(c(cred_int), colnames(cred_int)) se_r_bar <- sd_r / sqrt(k) prop_var <- var_e / var_r rel_r <- 1 - ifelse(prop_var > 1, 1, prop_var) if(ma_metric == "r"){ meta <- as.data.frame(t(c(L = L, k = k, N = N, mean_r_bar = mean_r, var_r_bar = var_r, var_e = var_e, var_r_bar_res = var_res, sd_r_bar = sd_r, se_r_bar = se_r_bar, sd_e = sd_e, sd_r_bar_res = sd_res, conf_int, cred_int, percent_var = prop_var * 100, rel_r = rel_r, `cor(r, error)` = sqrt(ifelse(prop_var > 1, 1, prop_var)))), stringsAsFactors = FALSE) class(meta) <- c("ma_table", class(meta)) attributes(meta) <- append(attributes(meta), list(ma_type = "r_bb_order2")) }else if(ma_metric == "d"){ meta <- as.data.frame(t(c(L = L, k = k, N = N, mean_d_bar = mean_r, var_d_bar = var_r, var_e = var_e, var_d_bar_res = var_res, sd_d_bar = sd_r, se_d_bar = se_r_bar, sd_e = sd_e, sd_d_bar_res = sd_res, conf_int, cred_int, percent_var = prop_var * 100, rel_d = rel_r, `cor(d, error)` = sqrt(ifelse(prop_var > 1, 1, prop_var)))), stringsAsFactors = FALSE) class(meta) <- c("ma_table", class(meta)) attributes(meta) <- append(attributes(meta), list(ma_type = "d_bb_order2")) } list(meta = meta, escalc = dat) } .ma_r_order2_ic <- function(data = NULL, k_vec = NULL, N_vec = NULL, rho_vec = NULL, var_r_c_vec = NULL, conf_level = .95, cred_level = .8, conf_method = "t", cred_method = "t", var_unbiased = TRUE, run_lean = FALSE, ma_metric = "r"){ arg_list <- list(k_vec = k_vec, N_vec = N_vec, rho_vec = rho_vec, var_r_c_vec = var_r_c_vec) check_null <- !unlist(lapply(arg_list, is.null)) if(all(!check_null)){ length_vec <- unlist(lapply(arg_list, length)) if(any(length_vec[1] != length_vec[-1])) stop("Vector arguments have inconsistent numbers of elements") } var_e_vec <- var_r_c_vec / k_vec wt_vec <- 1 / var_e_vec mean_rho <- wt_mean(x = rho_vec, wt = wt_vec) var_r_c <- wt_var(x = rho_vec, wt = wt_vec, unbiased = var_unbiased) var_e <- wt_mean(x = var_e_vec, wt = wt_vec) var_rho <- var_r_c - var_e sd_r_c <- var_r_c^.5 sd_e <- var_e^.5 sd_rho <- var_rho^.5 sd_r_c[is.na(sd_r_c)] <- sd_e[is.na(sd_e)] <- sd_rho[is.na(sd_rho)] <- 0 if(run_lean){ dat <- NULL }else{ if(ma_metric == "r"){ dat <- data.frame(yi = rho_vec, vi = var_e_vec, rho = rho_vec, var_r_c = var_r_c_vec, k = k_vec, var_e = var_e_vec, weight = wt_vec, residual = rho_vec - mean_rho, stringsAsFactors = FALSE) }else if(ma_metric == "d"){ dat <- data.frame(yi = rho_vec, vi = var_e_vec, delta = rho_vec, var_d_c = var_r_c_vec, k = k_vec, var_e = var_e_vec, weight = wt_vec, residual = rho_vec - mean_rho, stringsAsFactors = FALSE) } if(any(colnames(data) == "original_order")) dat <- cbind(original_order = data$original_order, dat) class(dat) <- c("escalc", "data.frame") } L <- sum(!is.na(wt_vec)) k <- sum(k_vec[!is.na(wt_vec) & !is.na(rho_vec)]) N <- sum(N_vec[!is.na(wt_vec)]) conf_int <- confidence(mean = mean_rho, sd = sd_r_c, k = k, conf_level = conf_level, conf_method = conf_method) cred_int <- credibility(mean = mean_rho, sd = sd_rho, cred_level = cred_level, k = k, cred_method = cred_method) conf_int <- setNames(c(conf_int), colnames(conf_int)) cred_int <- setNames(c(cred_int), colnames(cred_int)) se_rho_bar <- sd_r_c / sqrt(k) prop_var <- var_e / var_r_c rel_rho <- 1 - ifelse(prop_var > 1, 1, prop_var) if(ma_metric == "r"){ meta <- as.data.frame(t(c(L = L, k = k, N = N, mean_rho_bar = mean_rho, var_rho_bar = var_r_c, var_e = var_e, var_rho_bar_res = var_rho, sd_rho_bar = sd_r_c, se_rho_bar = se_rho_bar, sd_e = sd_e, sd_rho_bar_res = sd_rho, conf_int, cred_int, percent_var = prop_var * 100, rel_rho = rel_rho, `cor(rho, error)` = sqrt(ifelse(prop_var > 1, 1, prop_var)))), stringsAsFactors = FALSE) class(meta) <- c("ma_table", class(meta)) attributes(meta) <- append(attributes(meta), list(ma_type = "r_ad_order2")) }else if(ma_metric == "d"){ meta <- as.data.frame(t(c(L = L, k = k, N = N, mean_delta_bar = mean_rho, var_delta_bar = var_r_c, var_e = var_e, var_delta_bar_res = var_rho, sd_delta_bar = sd_r_c, se_delta_bar = se_rho_bar, sd_e = sd_e, sd_delta_bar_res = sd_rho, conf_int, cred_int, percent_var = prop_var * 100, rel_delta = rel_rho, `cor(delta, error)` = sqrt(ifelse(prop_var > 1, 1, prop_var)))), stringsAsFactors = FALSE) class(meta) <- c("ma_table", class(meta)) attributes(meta) <- append(attributes(meta), list(ma_type = "d_ic_order2")) } list(meta = meta, escalc = dat) } .ma_r_order2_ad <- function(data = NULL, k_vec = NULL, N_vec = NULL, r_vec = NULL, rho_vec = NULL, var_r_vec = NULL, conf_level = .95, cred_level = .8, conf_method = "t", cred_method = "t", var_unbiased = TRUE, run_lean = FALSE, ma_metric = "r"){ arg_list <- list(k_vec = k_vec, N_vec = N_vec, r_vec = r_vec, rho_vec = rho_vec, var_r_vec = var_r_vec) check_null <- !unlist(lapply(arg_list, is.null)) if(all(!check_null)){ length_vec <- unlist(lapply(arg_list, length)) if(any(length_vec[1] != length_vec[-1])) stop("Vector arguments have inconsistent numbers of elements") } var_e_vec <- (rho_vec / r_vec)^2 * (var_r_vec / k_vec) wt_vec <- 1 / var_e_vec mean_rho <- wt_mean(x = rho_vec, wt = wt_vec) var_r_c <- wt_var(x = rho_vec, wt = wt_vec, unbiased = var_unbiased) var_e <- wt_mean(x = var_e_vec, wt = wt_vec) var_rho <- var_r_c - var_e sd_r_c <- var_r_c^.5 sd_e <- var_e^.5 sd_rho <- var_rho^.5 sd_r_c[is.na(sd_r_c)] <- sd_e[is.na(sd_e)] <- sd_rho[is.na(sd_rho)] <- 0 if(run_lean){ dat <- NULL }else{ if(ma_metric == "r"){ dat <- data.frame(yi = rho_vec, vi = var_e_vec, rho = rho_vec, k = k_vec, var_e = var_e_vec, weight = wt_vec, residual = rho_vec - mean_rho, stringsAsFactors = FALSE) }else if(ma_metric == "d"){ dat <- data.frame(yi = rho_vec, vi = var_e_vec, delta = rho_vec, k = k_vec, var_e = var_e_vec, weight = wt_vec, residual = rho_vec - mean_rho, stringsAsFactors = FALSE) } if(any(colnames(data) == "original_order")) dat <- cbind(original_order = data$original_order, dat) class(dat) <- c("escalc", "data.frame") } L <- sum(!is.na(wt_vec)) k <- sum(k_vec[!is.na(wt_vec)]) N <- sum(N_vec[!is.na(wt_vec)]) conf_int <- confidence(mean = mean_rho, sd = sd_r_c, k = k, conf_level = conf_level, conf_method = conf_method) cred_int <- credibility(mean = mean_rho, sd = sd_rho, cred_level = cred_level, k = k, cred_method = cred_method) conf_int <- setNames(c(conf_int), colnames(conf_int)) cred_int <- setNames(c(cred_int), colnames(cred_int)) se_rho_bar <- sd_r_c / sqrt(k) prop_var <- var_e / var_r_c rel_rho <- 1 - ifelse(prop_var > 1, 1, prop_var) if(ma_metric == "r"){ meta <- as.data.frame(t(c(L = L, k = k, N = N, mean_rho_bar = mean_rho, var_rho_bar = var_r_c, var_e = var_e, var_rho_bar_res = var_rho, sd_rho_bar = sd_r_c, se_rho_bar = se_rho_bar, sd_e = sd_e, sd_rho_bar_res = sd_rho, conf_int, cred_int, percent_var = prop_var * 100, rel_rho = rel_rho, `cor(rho, error)` = sqrt(ifelse(prop_var > 1, 1, prop_var)))), stringsAsFactors = FALSE) class(meta) <- c("ma_table", class(meta)) attributes(meta) <- append(attributes(meta), list(ma_type = "r_ad_order2")) }else if(ma_metric == "d"){ meta <- as.data.frame(t(c(L = L, k = k, N = N, mean_delta_bar = mean_rho, var_delta_bar = var_r_c, var_e = var_e, var_delta_bar_res = var_rho, sd_delta_bar = sd_r_c, se_delta_bar = se_rho_bar, sd_e = sd_e, sd_delta_bar_res = sd_rho, conf_int, cred_int, percent_var = prop_var * 100, rel_delta = rel_rho, `cor(delta, error)` = sqrt(ifelse(prop_var > 1, 1, prop_var)))), stringsAsFactors = FALSE) class(meta) <- c("ma_table", class(meta)) attributes(meta) <- append(attributes(meta), list(ma_type = "d_ad_order2")) } list(meta = meta, escalc = dat) } .ma_r_order2_bb_boot <- function(data, i, ma_arg_list){ data <- data[i,] out <- .ma_r_order2(data = data, type = "bb", run_lean = TRUE, ma_arg_list = ma_arg_list) unlist(out$meta$barebones) } .ma_r_order2_ic_boot <- function(data, i, ma_arg_list){ data <- data[i,] out <- .ma_r_order2(data = data, type = "ic", run_lean = TRUE, ma_arg_list = ma_arg_list) unlist(out$meta$individual_correction) } .ma_r_order2_ad_boot <- function(data, i, ma_arg_list){ data <- data[i,] out <- .ma_r_order2(data = data, type = "ad", run_lean = TRUE, ma_arg_list = ma_arg_list) unlist(out$meta$artifact_distribution) }
context("multi") test_that("default", { tagmu <- multiInput( inputId = "MY_ID", label = "Fruits :", choices = c("Banana", "Blueberry", "Cherry", "Coconut", "Grapefruit", "Kiwi", "Lemon", "Lime", "Mango", "Orange", "Papaya"), selected = "Banana", width = "350px" ) expect_is(tagmu, "shiny.tag") expect_length(htmltools::findDependencies(tagmu), 2) expect_identical(htmltools::findDependencies(tagmu)[[2]]$script, "multi.min.js") expect_true(htmltools::tagHasAttribute(tagmu$children[[2]], "id")) expect_identical(htmltools::tagGetAttribute(tagmu$children[[2]], "id"), "MY_ID") }) test_that("updateMultiInput", { session <- as.environment(list( sendInputMessage = function(inputId, message) { session$lastInputMessage = list(id = inputId, message = message) }, sendCustomMessage = function(type, message) { session$lastCustomMessage <- list(type = type, message = message) }, sendInsertUI = function(selector, multiple, where, content) { session$lastInsertUI <- list(selector = selector, multiple = multiple, where = where, content = content) }, onFlushed = function(callback, once) { list(callback = callback, once = once) } )) shinyWidgets:::updateMultiInput(session = session, inputId = "MY_ID", choices = letters) msgmu <- session$lastInputMessage expect_length(msgmu, 2) expect_identical(msgmu$id, "MY_ID") expect_is(msgmu$message$options, "character") })
{ repo_root <- file.path(tempdir(), "miniCRAN", Sys.Date()) if (file.exists(repo_root)) unlink(repo_root, recursive = TRUE) dir.create(repo_root, recursive = TRUE, showWarnings = FALSE) revolution <- MRAN("2014-10-15") if (!is.online(revolution, tryHttp = FALSE)) { revolution <- sub("^https://", "http://", revolution) } rvers <- "3.1" pkgs <- c("chron", "adaptivetau") types <- intersect( set_test_types(), c("source", "win.binary", "mac.binary") ) names(types) <- types pdb <- list() pkgList <- list() } test_that("sample repo is setup correctly", { skip_if_offline(revolution) pdb <<- lapply(types, pkgAvail, repos = revolution, Rversion = rvers, quiet = TRUE) expect_type(pdb, "list") pkgList <<- lapply(types, function(type) { pkgDep(pkg = pkgs, type = types[type], availPkgs = pdb[[type]], repos = revolution, suggests = FALSE, Rversion = rvers) }) expect_type(pkgList, "list") z <- .createSampleRepo(path = repo_root, MRAN = revolution, Rversion = rvers) expect_type(z, "character") expect_equal(unname(pkgAvail(repo_root, quiet = TRUE)[, "Package"]), sort(pkgs)) }) pkgsAdd <- c("forecast") pkg_type <- names(types)[1] for (pkg_type in names(types)) { skip_if_not_installed("mockr") test_that(sprintf( "addPackage downloads %s files and rebuilds PACKAGES file", pkg_type), { skip_on_cran() skip_if_offline(revolution) pkgListAdd <- pkgDep(pkgsAdd, availPkgs = pdb[[pkg_type]], repos = revolution, type = pkg_type, suggests = FALSE, Rversion = rvers) prefix <- repoPrefix(pkg_type, Rversion = rvers) mockr::with_mock( download_packages = mock_download_packages, write_packages = mock_write_packages, .env = "miniCRAN", { addPackage(pkgListAdd, path = repo_root, repos = revolution, type = pkg_type, quiet = TRUE, Rversion = rvers) }) expect_true( .checkForRepoFiles(repo_root, pkgListAdd, prefix) ) expect_true( file.exists(file.path(repo_root, prefix, "PACKAGES.gz")) ) expect_true( all( pkgListAdd %in% pkgAvail(repo_root, type = pkg_type, Rversion = rvers, quiet = TRUE)[, "Package"] ) ) }) } pkgsAddLocal <- c("MASS") for (pkg_type in names(types)) { skip_if_not_installed("mockr") test_that( sprintf("addLocalPackage copies %s files and rebuilds PACKAGES", pkg_type), { skip_on_cran() skip_if_offline(revolution) tmpdir <- file.path(tempdir(), "miniCRAN", "local", pkg_type) expect_true(dir.create(tmpdir, recursive = TRUE, showWarnings = FALSE)) tmpdir <- normalizePath(tmpdir) expect_true(dir.exists(tmpdir)) on.exit(unlink(tmpdir, recursive = TRUE), add = TRUE) mockr::with_mock( download_packages = mock_download_packages, write_packages = mock_write_packages, .env = "miniCRAN", { res <- download_packages( pkgsAddLocal, destdir = tmpdir, type = pkg_type, available = pkgAvail(revolution, pkg_type, rvers), contriburl = contribUrl(revolution, pkg_type, rvers), quiet = TRUE) }) f <- res[, 2] expect_true( file.copy(from = f, to = file.path(tmpdir, "MASS_7.3-0.tar.gz")) ) expect_equal(length(list.files(tmpdir)), 2) mockr::with_mock( download_packages = mock_download_packages, write_packages = mock_write_packages, .env = "miniCRAN", { addLocalPackage(pkgs = pkgsAddLocal, pkgPath = tmpdir, path = repo_root, type = pkg_type, quiet = TRUE, Rversion = rvers) }) prefix <- repoPrefix(pkg_type, Rversion = rvers) expect_true( .checkForRepoFiles(repo_root, pkgsAddLocal, prefix) ) expect_true( file.exists(file.path(repo_root, prefix, "PACKAGES.gz")) ) expect_true( all( pkgsAddLocal %in% pkgAvail(repo_root, type = pkg_type, Rversion = rvers)[, "Package"] ) ) }) } MRAN_mirror <- MRAN("2015-01-01") if (!is.online(MRAN_mirror, tryHttp = FALSE)) { MRAN_mirror <- sub("^https://", "http://", revolution) } pkg_type <- names(types)[1] for (pkg_type in names(types)) { test_that( sprintf("updatePackages downloads %s files and builds PACKAGES", pkg_type), { skip_on_cran() skip_if_offline(MRAN_mirror) prefix <- repoPrefix(pkg_type, Rversion = rvers) suppressWarnings( old <- oldPackages(path = repo_root, repos = MRAN_mirror, type = pkg_type, Rversion = rvers, quiet = FALSE) ) expect_true(nrow(old) >= 10) expect_true(nrow(old) <= 12) expect_equal(ncol(old), 4) expect_true( all( rownames(old) %in% c("adaptivetau", "BH", "digest", "forecast", "Hmisc", "mvtnorm", "RColorBrewer", "RcppArmadillo", "reshape2", "timeDate", "timeSeries", "tis") ) ) mockr::with_mock( download_packages = mock_download_packages, write_packages = mock_write_packages, .env = "miniCRAN", { updatePackages(path = repo_root, repos = MRAN_mirror, type = pkg_type, ask = FALSE, quiet = TRUE, Rversion = rvers) }) updateVers <- getPkgVersFromFile( list.files(file.path(repo_root, prefix)) ) expect_true( .checkForRepoFiles(repo_root, pkgList[[pkg_type]], prefix) ) expect_true( file.exists(file.path(repo_root, prefix, "PACKAGES.gz")) ) mockr::with_mock( download_packages = mock_download_packages, write_packages = mock_write_packages, .env = "miniCRAN", { old <- oldPackages(path = repo_root, repos = MRAN_mirror, type = pkg_type, Rversion = rvers) }) expect_equal(nrow(old), 0) expect_equal(ncol(old), 4) }) } pkg_type <- names(types)[3] for (pkg_type in names(types)) { test_that( sprintf("checkVersions() finds out-of-date %s packages", pkg_type), { skip_on_cran() skip_if_offline(MRAN_mirror) oldVersions <- list(package = c("acepack"), version = c("1.3-2")) if (pkg_type != "source") { expect_error( mockr::with_mock( download_packages = mock_download_packages, write_packages = mock_write_packages, .env = "miniCRAN", { addOldPackage(oldVersions[["package"]], path = repo_root, vers = oldVersions[["version"]], repos = MRAN_mirror, type = pkg_type) }) ) } else { mockr::with_mock( download_packages = mock_download_packages, write_packages = mock_write_packages, .env = "miniCRAN", { addOldPackage(oldVersions[["package"]], path = repo_root, vers = oldVersions[["version"]], repos = MRAN_mirror, type = pkg_type) }) files <- suppressWarnings( checkVersions(path = repo_root, type = pkg_type)[[pkg_type]] ) expect_true( all(file.exists(files)) ) pkgs <- sapply(strsplit(basename(files), "_"), "[[", 1) dupes <- pkgs[duplicated(pkgs)] expect_true( all(dupes == oldVersions[["package"]]) ) } }) }
context("addwmfs") test_that("test it",{ set.seed(101) sig<-matrix(.8,5,5) diag(sig)<-1 lents<-50 dat1<-t(copy_rmvnorm(lents,mean=rep(0,5),sigma=sig)) dat2<-t(copy_rmvnorm(lents,mean=rep(0,5),sigma=sig)) dat<-rbind(dat1,dat2) times<-1:lents dat<-cleandat(dat,times,clev=1)$cdat coords<-data.frame(Y=rep(0,10),X=1:10) method<-"coh.sig.fast" clustobj<-clust(dat,times,coords,method,nsurrogs = 100) res<-addwmfs(clustobj) expect_equal(class(res),c("clust","list")) expect_equal(res$dat,dat) expect_equal(res$times,times) expect_equal(res$coords,coords) expect_equal(names(res$methodspecs),c("method","tsrange","nsurrogs", "scale.min","scale.max.input","sigma","f0", "weighted","sigthresh")) expect_equal(diag(res$adj),rep(NA*numeric(1),10)) expect_true(isSymmetric(res$adj)) expect_equal(class(res$clusters),"list") h<-sapply(FUN=length,X=res$clusters) expect_equal(h,rep(10,length(h))) expect_equal(res$clusters[[1]],rep(1,10)) expect_equal(class(res$modres),"list") expect_equal(length(res$modres),length(res$clusters)) expect_equal(class(res$modres[[1]]),"list") expect_equal(names(res$modres[[1]]),c("totQ","modQ","nodeQ")) expect_equal(class(res$mns),"list") expect_equal(length(res$mns),length(res$clusters)) expect_equal(dim(res$mns[[1]]),c(1,lents)) expect_equal(dim(res$mns[[2]]),c(2,lents)) expect_equal(as.vector(res$mns[[1]]),apply(FUN=mean,X=dat,MARGIN=2)) expect_equal(class(res$wmfs),"list") expect_equal(length(res$wmfs),length(res$clusters)) expect_equal(class(res$wmfs[[1]]),"list") expect_equal(class(res$wmfs[[2]]),"list") expect_equal(length(res$wmfs[[1]]),1) expect_equal(length(res$wmfs[[2]]),2) expect_equal(class(res$wmfs[[1]][[1]]),c("wmf","tts","list")) expect_equal(class(res$wmfs[[2]][[1]]),c("wmf","tts","list")) expect_equal(class(res$wmfs[[2]][[2]]),c("wmf","tts","list")) h<-res$wmfs h[[1]][[1]]<-Mod(h[[1]][[1]]$values[20:30,20:30]) h[[2]][[2]]<-Mod(h[[2]][[2]]$values[20:30,20:30]) h[[2]][[1]]<-Mod(h[[2]][[1]]$values[20:30,20:30]) expect_known_value(h,file="../vals/addwmfs_testval_01",update=FALSE) })
write_pin <- "pin_write" <- function (name, L) { n <- nchar(name) if (substring(name, n - 3, n) == ".pin") file_name <- name else file_name <- paste(name, ".pin", sep = "") cat(" date(), "\n", file = file_name, sep = "") for (i in 1:length(L)) { x <- L[[i]] if (data.class(x) == "numeric") cat(" append = TRUE) if (data.class(x) == "matrix") { cat(" write.table(L[[i]], col.names = FALSE, row.names = FALSE, quote = FALSE, file = file_name, append = TRUE) cat("\n", file = file_name, append = TRUE) } } } if (FALSE) { dir <- "/usr/local/src/admb/examples/admb/" dir <- "/usr/local/src/admb/examples/admb-re/" setwd(dir) L <- list.files(pattern="^[a-zA-Z_]+$") source("/home/ben/lib/R/pkgs/r2admb/pkg/R/admb-funs.R") for (i in seq_along(L)) { setwd(file.path(dir,L[i])) tpls <- gsub(".tpl","",list.files(pattern=".tpl")) for (j in seq_along(tpls)) { cat(L[i],tpls[j],"\n") invisible(read_tpl(tpls[j])$info) } } } write_dat <- "dat_write" <- function (name, L, append=FALSE) { n <- nchar(name) file_name <- if (tools::file_ext(name) == ".dat") { name } else paste(name, "dat", sep = ".") cat(" date(), "\n", file = file_name, sep = "", append=append) for (i in 1:length(L)) { x <- L[[i]] dc <- data.class(x) if (dc=="numeric") { cat(" append = TRUE) } else { if (dc == "matrix") { cat(" write.table(L[[i]], , col.names = FALSE, row.names = FALSE, quote = FALSE, file = file_name, append = TRUE) cat("\n", file = file_name, append = TRUE) } else { stop(paste("can't handle data type '",dc,"' (variable ",names(L)[i],")",sep="")) } } } }
context('Testing Partial Bezier method - Default functionality') test_that("Corset - class integer", { x <- (10:-10) * 1000 + 900 cx <- corset(x, 'bezier') expect_equal(cx, structure( c( 10900, 9900.00000007557, 8900.00013318376, 7900.00942515128, 6900.17527289219, 5901.5470523811, 4908.44164218709, 3932.7991060351, 2998.75458831863, 2143.42276607584, 1410.27393341064, 835.558123716945, 433.720226866372, 190.251586701415, 67.0376845734304, 17.572955128162, 3.01768988067312, 0.267738415328761, 0.00720697194150919, 1.07663847305169e-05, 0 ), class = c("numeric", "corset") )) }) test_that("Corset - class numerical", { x <- (10:-10) * 1000 + 900.5 cx <- corset(x, 'bezier') expect_equal(cx, structure( c( 10900.5, 9900.50000007531, 8900.50013282933, 7900.5094058349, 6900.67499118534, 5902.04508131027, 4908.93306977887, 3933.27252272791, 2999.19082769556, 2143.79812139593, 1410.56798267365, 835.762443124609, 433.842558264714, 190.312476994603, 67.0616655220961, 17.5798873366339, 3.01898729437346, 0.267862606323573, 0.00721054739351973, 1.07720550895473e-05, 0 ), class = c("numeric", "corset") )) }) test_that("Corset - class ts", { x <- ts((10:-10) * 1000 + 900.5) cx <- corset(x, 'bezier') expect_equal(cx, structure( c( 10900.5, 9900.50000007531, 8900.50013282933, 7900.5094058349, 6900.67499118534, 5902.04508131027, 4908.93306977887, 3933.27252272791, 2999.19082769556, 2143.79812139593, 1410.56798267365, 835.762443124609, 433.842558264714, 190.312476994603, 67.0616655220961, 17.5798873366339, 3.01898729437346, 0.267862606323573, 0.00721054739351973, 1.07720550895473e-05, 0 ), .Tsp = c(1, 21, 1), class = c("ts", "corset") )) }) test_that("Corset - class forecast ", { skip_on_cran() if ('forecast' %in% installed.packages()) { set.seed(0) rx <- rnorm(100, 0.5) x <- forecast::forecast(rx) cx <- corset(x, 'bezier') expect_equal(x$mean, cx$mean) expect_equal(x$upper, cx$upper) expect_equal(as.numeric(cx$lower[1, 1]), 0.180826494051395) expect_equal(as.numeric(cx$lower[1, 2]), 0) } }) test_that("Corset - class gts/hts ", { if ('hts' %in% installed.packages()) { set.seed(6) rh <- ts(replicate(5, rnorm(10) + 15:6)) htseg <- hts::hts(rh, nodes = list(1, 5)) x <- hts::forecast.gts(htseg, h = 10, method = "bu", fmethod = "arima") cx <- corset(x, 'bezier') expect_equal(cx, structure( list( bts = structure( c( 3.80515800186062, 2.66996675440457, 1.64601324968342, 0.864152651943784, 0.370660223314166, 0.12098227038375, 0.0261780272598394, 0.00273824728401341, 5.01079348960876e-05, 0, 8.2074129608038, 8.2074129608038, 8.2074129608038, 8.2074129608038, 8.2074129608038, 8.2074129608038, 8.2074129608038, 8.2074129608038, 8.2074129608038, 8.2074129608038, 5.43966764122182, 5.43966764122182, 5.43966764122182, 5.43966764122182, 5.43966764122182, 5.43966764122182, 5.43966764122182, 5.43966764122182, 5.43966764122182, 5.43966764122182, 3.28817121759491, 2.20088700981897, 1.25811185523255, 0.594059725254644, 0.221312450756648, 0.059960514225786, 0.0100663824045864, 0.000724759292237971, 6.83776460170098e-06, 0, 5.30728795135891, 4.42653859168677, 3.54635425900036, 2.67302379748065, 1.83193309462167, 1.07949126101059, 0.495294444070853, 0.14319111445892, 0.0136170500840911, 0 ), .Dim = c(10L, 5L), .Dimnames = list( NULL, c("Series 1", "Series 2", "Series 3", "Series 4", "Series 5") ), .Tsp = c(11, 20, 1), class = c("mts", "ts", "matrix") ), histy = structure( c( 15.2696059820375, 13.3700145859607, 13.8686598276523, 13.7271955171152, 11.0241876417677, 10.3680251769925, 7.69079570179147, 8.73862193071141, 7.04487298737499, 4.9516027998788, 16.7278510904457, 12.8214002609775, 13.6532067110969, 11.6314335082964, 10.4004453564552, 10.0546051654574, 10.7076774254494, 6.90562702442171, 6.71071817550361, 8.2074129608038, 15.5187490065016, 12.5950820641597, 15.0148644801591, 10.8118416629749, 11.1903808075881, 8.83026408994545, 8.96191844055564, 10.3542042609769, 8.39342625937317, 5.43966764122182, 14.3285406164292, 14.4924385547309, 11.8206094838239, 10.9412825480884, 12.1379026130001, 9.83973471509903, 9.63049312664994, 9.61695970239454, 6.80650017148123, 4.39220815745928, 14.114835872298, 13.5676657010407, 12.578376140606, 11.8295059368048, 11.2458109372263, 9.25425221514964, 8.7260558667396, 9.82457894065461, 7.0142337398516, 6.1880427434525 ), .Dim = c(10L, 5L), .Dimnames = list( NULL, c("Series 1", "Series 2", "Series 3", "Series 4", "Series 5") ), .Tsp = c(1, 10, 1), class = c("mts", "ts", "matrix") ), labels = structure( list( `Level 0` = "Total", `Level 1` = "A", `Level 2` = c("Series 1", "Series 2", "Series 3", "Series 4", "Series 5") ), .Names = c("Level 0", "Level 1", "Level 2") ), method = "bu", fmethod = "arima", nodes = structure(list( `Level 1` = 1, `Level 2` = 5 ), .Names = c("Level 1", "Level 2")) ), .Names = c("bts", "histy", "labels", "method", "fmethod", "nodes"), class = c("hts", "gts", "corset") )) } }) test_that("Corset - class mts / ts / matrix ", { set.seed(1) x <- ts(replicate(10, rnorm(10))) cx <- corset(x, 'bezier') expect_equal(cx, structure( c( 0, 0.183643324222082, 0.406324908596249, 1.59528080213779, 0.524879035976907, 0.459419447612894, 0.487429052428485, 0.738324705129217, 0.575781351653492, 0, 1.51178116845085, 0.687674018218684, 0.360850956619705, 0.323082890517881, 1.12493091814311, 0.380572138873008, 0.448191742072224, 0.943836210685299, 0.821221195098089, 0.593901321217509, 0.918977371608218, 0.782136300731067, 0.38224081886771, 0.259904956133021, 0.61982574789471, 0.140534808033911, 0.0756637491727551, 0.0590980602249591, 0.14561771219714, 0.417941560199702, 1.35867955152904, 0.546246765720715, 0.387671611559369, 0.127145168363187, 0.0607687588966947, 0.0594504041189091, 0.151520999434904, 0.374349885190298, 1.10002537198388, 0.763175748457544, 0, 0.167503277081711, 0.696963375404737, 0.556663198673657, 0.271969244778273, 0.261080394093053, 0.36458196213683, 0.768532924515416, 0.475804073176413, 0.881107726454215, 0.398105880367068, 0.222304404264301, 0.341119691424425, 0.587126071369814, 1.43302370170104, 1.98039989850586, 0.621658361859357, 0.361802155811226, 0.569719627442413, 0, 2.40161776050478, 0.968277887243452, 0.689739362450777, 0.261904345313247, 0.196007467055641, 0.266850231229406, 0.462353389058745, 1.46555486156289, 0.153253338211898, 2.17261167036215, 0.475509528899663, 0.28413708010971, 0.610726353489055, 0.185273629068083, 0.134606149977445, 0.291446235517463, 0.0731548644618042, 0.0460956635550376, 0.0743413241516641, 0, 0, 0.236467718442192, 1.1780869965732, 0.468220006356377, 0.593946187628422, 0.332950371213518, 1.06309983727636, 0.388518324722054, 0.370018809916288, 0.267098790772231, 0, 1.20786780598317, 1.16040261569495, 0.700213649514998, 1.58683345454085, 0.606693390507465, 0.310433200318828, 0.0925549298407398, 0.00815056171076708, 0 ), .Dim = c(10L, 10L), .Dimnames = list( NULL, c( "Series 1", "Series 2", "Series 3", "Series 4", "Series 5", "Series 6", "Series 7", "Series 8", "Series 9", "Series 10" ) ), .Tsp = c(1, 10, 1), class = c("mts", "ts", "matrix", "corset") )) }) context('Testing Partial Bezier method - Arbitrary Boundaries') test_that("Corset - class ts", { set.seed(5) x <- ts(rnorm(100, 0, 100)) cx <- corset(x, 'bezier', -1:-100, 1:100) expect_equal(cx, structure( c( -1, 0.116355561650003, 0.446763772739703, 0.175819736032893,-0.801898984746453, -1.91179744989519, -2.66386194768088, -3.04367880585556,-3.36899382262208, -3.96130290835408, -4.92242392902421, -6.0990315721542,-7.17675476627002, -7.81261584959876, -7.74386792458096, -6.85003725878387,-5.16897198062792, -2.87651648621779, -0.240983094437187, 2.4360772673997, 4.88055980231127, 6.89564130179517, 8.39053335500758, 9.38253945115316, 9.97315188164403, 10.3054011077149, 10.5144762817728, 10.6853106589919, 10.8286945711816, 10.8819630384343, 10.7329486284096, 10.2589675928995, 9.36836953009315, 8.03201258134622, 6.29589124015804, 4.27258547030935, 2.11590866790679, -0.0121660404779003, -1.97193544185891, -3.66561354017109,-5.04266487690025, -6.09243257030006, -6.82951243239837, -7.27869794428105,-7.4650603140028, -7.41163303047681, -7.14362408619008, -6.69548694655501,-6.11644339324667, -5.47125697907849, -4.8355078462602, -4.28716698176686,-3.89780446337383, -3.72668631270837, -3.81943717445594, -4.21062295113822,-4.92757298027625, -11.2609070203049, -6.40909282197963, 23.3275293545762,-11.2808835535356, -13.5935006061775, -57.8370418961854, 49.6361539030152,-20.1449011603232, -21.4062212246861, -21.7944061053414, -21.1349222963359,-19.3571337821455, -16.5200673165984, -12.8179499890403, -8.56169543105297, 34.7028452022099, 3.23678425979233, 41.3531289671798, -15.5348476625379, 8.27695105001458, 9.25545854149017, 9.55121171700127, -56.2885069825959, 49.8416165001331, 8.67921864379581, 8.24498505721885, -2.40828727364371, 67.5684475314084, -71.0309605053391, 4.93379861007474, -47.3432012196463,-7.57725566667704, -52.1840056478283, 13.3602788943686, 20.4674734179506, 27.7947583359108, 32.2113196764886, 29.7584850218978, 17.7296481083232,-34.6583813698718, -54.0189250004419, -18.2555593266753, -5.92996499937566 ), .Tsp = c(1, 100, 1), class = c("ts", "corset") )) })
load(file.path("..", "testdata", "rec_with_table_test_data.RData")) test_that("labels are properly applied to random variables", { variables$variable <- sapply(variables$variable, trimws) var_names <- as.character(unique(names(cchs2001Standard))) max_num_of_vars <- length(names(cchs2001Standard)) list_of_vars_to_check <- sample(1:max_num_of_vars, floor(max_num_of_vars) / 2, replace = TRUE) labeled2001 <- set_data_labels(cchs2001Standard, variable_details, variables) for (var_name_index in (list_of_vars_to_check)) { first <- as.character(get_label(labeled2001[[var_names[[var_name_index]]]])) second <- as.character(variables[ variables$variable == var_names[[var_name_index]], "label"]) expect_equal(first, second) } })
tornadoes <- function(...) { check4pkg('rgdal') url <- 'https://www.spc.noaa.gov/gis/svrgis/zipped/1950-2019-torn-aspath.zip' tornadoes_GET(url, ...) readshp(file.path(torn_cache$cache_path_get(), tornadoes_basename)) } tornadoes_GET <- function(url, ...) { bp <- torn_cache$cache_path_get() torn_cache$mkdir() if (!is_tornadoes(file.path(bp, tornadoes_basename))) { fp <- file.path(bp, "tornadoes.zip") cli <- crul::HttpClient$new(url, opts = list(...)) res <- cli$get(disk = fp) res$raise_for_status() unzip(fp, exdir = bp) } else { cache_mssg(bp) } } is_tornadoes <- function(x){ if (identical(list.files(x), character(0))) { FALSE } else { all(list.files(x) %in% tornadoes_files) } } tornadoes_basename <- "1950-2019-torn-aspath" readshp <- function(x) { rgdal::readOGR(dsn = path.expand(x), layer = tornadoes_basename, stringsAsFactors = FALSE) } tornadoes_files <- paste0(tornadoes_basename, c(".dbf", ".prj", ".shp", ".shx", ".cpg"))
add_arc_layer <- function(deckgl, id = "arc-layer", data = NULL, properties = list(), ...) { add_layer(deckgl, "ArcLayer", id, data, properties, ...) }
meshRatio <- function(design){ X <- as.matrix(design) n <- dim(X)[1] dimension <- dim(X)[2] if ( n < dimension ){ stop('Warning : the number of points is lower than the dimension') } if ( min(X)<0 || max(X)>1 ){ warning("The design is rescaling into the unit cube [0,1]^d.") M <- apply(X,2,max) m <- apply(X,2,min) for (j in 1:dim(X)[2]){ X[,j] <- (X[,j]-m[j])/(M[j]-m[j]) } } DistanceMax <- -1.0E30 DistanceMin <- 1.0E30 for (i in 1:(n-1)) { DistMin <- 1.0E30 DistMax <- -1.0E30 for (k in 1 : n){ if (i != k){ Dist <- 0 for (j in 1 : dimension){ Dist <- Dist + (X[i,j] -X[k,j])*(X[i,j] - X[k,j]) } if (Dist > DistMax){ DistMax <- Dist; } if (Dist < DistMin){ DistMin <- Dist; } } } if (DistanceMax < DistMin){ DistanceMax <- DistMin } if (DistanceMin > DistMin){ DistanceMin <- DistMin } } ratio <- sqrt(DistanceMax/DistanceMin) return(ratio) }
sample_group <- function(group,status_orginal,imputed_altern_status_vec) { p_group <- sample(group) status <- ifelse(p_group==group,status_orginal,imputed_altern_status_vec) while(sum(status[p_group==0])<2 | sum(status[p_group==1])<2) { p_group<-sample(group) status <- ifelse(p_group==group,status_orginal,imputed_altern_status_vec) } return(p_group) } konp_2_sample<-function(time,status,group,n_perm,n_impu = 1) { if (all(unique(status)!= c(0,1)) & all(unique(status)!= c(1,0)) & all(unique(status)!= 1) & all(unique(status)!= 0)) { stop ("ERROR - status vecotr must contain 0 or 1 only\n") } if (length(unique(group)) != 2) { stop ("ERROR - there should be exactly 2 treatment groups\n") } if (class(time) != "numeric" & class(time) != "integer") { stop ("ERROR - time class sould be numeric or integer\n") } if (length(time) != length(group) | length(time) != length(status)) { stop ("ERROR - Vectors time, group and status must be in the same length\n") } if (sum(is.na(time))+ sum(is.na(status)) +sum(is.na(group))>0) { stop ("ERROR - time or status or group has NA's in the vector\n") } if (n_perm%%1 != 0 | n_perm<1) { stop ("ERROR - n_perm must be a natural number\n") } if (n_impu%%1 != 0 | n_impu<1) { stop ("ERROR - n_impu must be a natural number\n") } group_ex <- rep(NA,length(group)) group_unq <- unique(group) group_ex[group==group_unq[1]] <- 0 group_ex[group==group_unq[2]] <- 1 group <- group_ex if (sum(status[group==0])<2 | sum(status[group==1])<2) { stop ("ERROR - Data must have at least two events in each groups in order to preform test\n") } if (min(time)<=0) { stop ("ERROR - the time vector has negative or zero values\n") } n<-length(time) fit <- survival::survfit(survival::Surv(time[group==0], status[group==0]) ~ 1) s0 <- c(1,fit$surv) time0 <- c(0,fit$time) fit <- survival::survfit(survival::Surv(time[group==1], status[group==1]) ~ 1) s1 <- c(1,fit$surv) time1 <- c(0,fit$time) M <- Inf max_ev_0 <- max(time[group==0 & status==1]) max_ev_1 <- max(time[group==1 &status==1]) max_obs_0 <- max(time[group==0]) max_obs_1 <- max(time[group==1]) max_0 <- ifelse(max_ev_0==max_obs_0,M,max_ev_0) max_1 <- ifelse(max_ev_1==max_obs_1,M,max_ev_1) tau <- min(max_0,max_1) test_stat_list <- hhgsurv_test_stat(s0 = s0,s1 = s1,time0 = time0,time1 = time1,time = time,delta = status, trt = group,tau = tau) chisq_test_stat <- test_stat_list$chisq_stat lr_test_stat <- test_stat_list$lr_stat fit <- survival::survfit(survival::Surv(time, status) ~ 1) prob.t <- -diff(c(1,fit$surv)) values.t <- fit$time if(sum(prob.t)<1) { prob.t <- c(prob.t,1-sum(prob.t)) values.t <- c(values.t,max(values.t)+1) } cen <- 1 - status fit <- survival::survfit(survival::Surv(time[group==1], cen[group==1]) ~ 1) prob.c1 <- -diff(c(1,fit$surv)) time1 <- fit$time if (sum(prob.c1)==0) { prob.c1 <- rep(1/2,2) time1 <- rep(Inf,2) }else { if(sum(prob.c1)<1) { prob.c1 <- c(prob.c1,1-sum(prob.c1)) time1 <- c(time1,max(time1)) } } fit <- survival::survfit(survival::Surv(time[group==0], cen[group==0]) ~ 1) prob.c0 <- -diff(c(1,fit$surv)) time0 <-fit$time if (sum(prob.c0)==0) { prob.c0 <- rep(1/2,2) time0 <- rep(Inf,2) }else { if(sum(prob.c0)<1) { prob.c0 <- c(prob.c0,1-sum(prob.c0)) time0 <- c(time0,max(time0)) } } imputed_altern_time_mat<-matrix(data = NA,ncol = n_impu,nrow = n,byrow = F) imputed_altern_status_mat<-matrix(data = NA,ncol = n_impu,nrow = n,byrow = F) for (subj in 1:n) { if (group[subj]==0) { c <- sample(time1,n_impu,prob=prob.c1,replace = T) + stats::rnorm(n = n_impu,sd = 10^-4) t <- rep(time[subj],n_impu) prob <- prob.t[values.t > time[subj]] values <- values.t[values.t > time[subj]] if ((length(prob)>0) & (sum(prob)>0) & status[subj]==0) { t <- sample(c(values,values), n_impu, prob = c(prob,prob),replace = T) + stats::rnorm(n = n_impu,sd = 10^-4) } imputed_altern_status_mat[subj,] <- ifelse(t<=c,1,0) imputed_altern_time_mat[subj,] <- pmax(ifelse(t<=c,t,c),10^-10) } if (group[subj]==1) { c <- sample(time0,n_impu,prob=prob.c0,replace = T) +stats::rnorm(n = n_impu,sd = 10^-4) t <- rep(time[subj],n_impu) prob <- prob.t[values.t > time[subj]] values <- values.t[values.t > time[subj]] if ((length(prob)>0) & (sum(prob)>0) & status[subj]==0) { t <- sample(c(values,values), n_impu, prob = c(prob,prob),replace = T) + stats::rnorm(n = n_impu,sd = 10^-4) } imputed_altern_status_mat[subj,] <- ifelse(t<=c,1,0) imputed_altern_time_mat[subj,] <- pmax(ifelse(t<=c,t,c),10^-10) } } chisq_stat_perm <- c() lr_stat_perm <- c() pv_chisq_vec <- rep(NA,n_impu) pv_lr_vec <- rep(NA,n_impu) for (imp in 1:n_impu) { p_group_mat <- replicate(n_perm,sample_group(group,status,imputed_altern_status_mat[,imp])) perm <- get_perm_stats(group,p_group_mat,time,status,imputed_altern_time_mat[,imp], imputed_altern_status_mat[,imp],n_perm = n_perm) pv_chisq_vec[imp] <- (sum(chisq_test_stat<=perm$chisq_stat)+1)/(n_perm +1) pv_lr_vec[imp] <- (sum(lr_test_stat<=perm$lr_stat)+1)/(n_perm +1) chisq_stat_perm <- c(chisq_stat_perm,perm$chisq_stat) lr_stat_perm <- c(lr_stat_perm,perm$lr_stat) } pv_chisq <- (sum(chisq_test_stat<=chisq_stat_perm) + 1)/(n_impu*n_perm+1) pv_lr <- (sum(lr_test_stat<=lr_stat_perm) + 1)/(n_impu*n_perm+1) fit_lr <- survival::survdiff(survival::Surv(time, status) ~ group , rho=0) Pvalue_logrank <- 1 - stats::pchisq(fit_lr$chisq, 1) cau <- mean(c(tan((0.5-pv_chisq)*pi), tan((0.5-pv_lr)*pi), tan((0.5-Pvalue_logrank)*pi))) pv_cauchy <- 0.5-atan(cau)/pi return(list(pv_chisq=pv_chisq, pv_lr=pv_lr, pv_cauchy = pv_cauchy, chisq_test_stat=chisq_test_stat, lr_test_stat=lr_test_stat, cauchy_test_stat = cau)) } konp_2_sample_impu_output<-function(time,status,group,n_perm,n_impu = 1) { if (all(unique(status)!= c(0,1)) & all(unique(status)!= c(1,0)) & all(unique(status)!= 1) & all(unique(status)!= 0)) { stop ("ERROR - status vecotr must contain 0 or 1 only\n") } if (length(unique(group)) != 2) { stop ("ERROR - there should be exactly 2 treatment groups\n") } if (class(time) != "numeric" & class(time) != "integer") { stop ("ERROR - time class sould be numeric or integer\n") } if (length(time) != length(group) | length(time) != length(status)) { stop ("ERROR - Vectors time, group and status must be in the same length\n") } if (sum(is.na(time))+ sum(is.na(status)) +sum(is.na(group))>0) { stop ("ERROR - time or status or group has NA's in the vector\n") } if (n_perm%%1 != 0 | n_perm<1) { stop ("ERROR - n_perm must be a natural number\n") } if (n_impu%%1 != 0 | n_impu<1) { stop ("ERROR - n_impu must be a natural number\n") } group_ex <- rep(NA,length(group)) group_unq <- unique(group) group_ex[group==group_unq[1]] <- 0 group_ex[group==group_unq[2]] <- 1 group <- group_ex if (sum(status[group==0])<2 | sum(status[group==1])<2) { stop ("ERROR - Data must have at least two events in each groups in order to preform test\n") } if (min(time)<=0) { stop ("ERROR - the time vector has negative or zero values\n") } n<-length(time) fit <- survival::survfit(survival::Surv(time[group==0], status[group==0]) ~ 1) s0 <- c(1,fit$surv) time0 <- c(0,fit$time) fit <- survival::survfit(survival::Surv(time[group==1], status[group==1]) ~ 1) s1 <- c(1,fit$surv) time1 <- c(0,fit$time) M <- Inf max_ev_0 <- max(time[group==0 & status==1]) max_ev_1 <- max(time[group==1 &status==1]) max_obs_0 <- max(time[group==0]) max_obs_1 <- max(time[group==1]) max_0 <- ifelse(max_ev_0==max_obs_0,M,max_ev_0) max_1 <- ifelse(max_ev_1==max_obs_1,M,max_ev_1) tau <- min(max_0,max_1) test_stat_list <- hhgsurv_test_stat(s0 = s0,s1 = s1,time0 = time0,time1 = time1,time = time,delta = status, trt = group,tau = tau) chisq_test_stat <- test_stat_list$chisq_stat lr_test_stat <- test_stat_list$lr_stat tab_usage <- test_stat_list$tab_usage fit <- survival::survfit(survival::Surv(time, status) ~ 1) prob.t <- -diff(c(1,fit$surv)) values.t <- fit$time if(sum(prob.t)<1) { prob.t <- c(prob.t,1-sum(prob.t)) values.t <- c(values.t,max(values.t)+1) } cen <- 1 - status fit <- survival::survfit(survival::Surv(time[group==1], cen[group==1]) ~ 1) prob.c1 <- -diff(c(1,fit$surv)) time1 <- fit$time if (sum(prob.c1)==0) { prob.c1 <- rep(1/2,2) time1 <- rep(Inf,2) }else { if(sum(prob.c1)<1) { prob.c1 <- c(prob.c1,1-sum(prob.c1)) time1 <- c(time1,max(time1)) } } fit <- survival::survfit(survival::Surv(time[group==0], cen[group==0]) ~ 1) prob.c0 <- -diff(c(1,fit$surv)) time0 <-fit$time if (sum(prob.c0)==0) { prob.c0 <- rep(1/2,2) time0 <- rep(Inf,2) }else { if(sum(prob.c0)<1) { prob.c0 <- c(prob.c0,1-sum(prob.c0)) time0 <- c(time0,max(time0)) } } imputed_altern_time_mat<-matrix(data = NA,ncol = n_impu,nrow = n,byrow = F) imputed_altern_status_mat<-matrix(data = NA,ncol = n_impu,nrow = n,byrow = F) for (subj in 1:n) { if (group[subj]==0) { c <- sample(time1,n_impu,prob=prob.c1,replace = T) + stats::rnorm(n = n_impu,sd = 10^-4) t <- rep(time[subj],n_impu) prob <- prob.t[values.t > time[subj]] values <- values.t[values.t > time[subj]] if ((length(prob)>0) & (sum(prob)>0) & status[subj]==0) { t <- sample(c(values,values), n_impu, prob = c(prob,prob),replace = T) + stats::rnorm(n = n_impu,sd = 10^-4) } imputed_altern_status_mat[subj,] <- ifelse(t<=c,1,0) imputed_altern_time_mat[subj,] <- pmax(ifelse(t<=c,t,c),10^-10) } if (group[subj]==1) { c <- sample(time0,n_impu,prob=prob.c0,replace = T) +stats::rnorm(n = n_impu,sd = 10^-4) t <- rep(time[subj],n_impu) prob <- prob.t[values.t > time[subj]] values <- values.t[values.t > time[subj]] if ((length(prob)>0) & (sum(prob)>0) & status[subj]==0) { t <- sample(c(values,values), n_impu, prob = c(prob,prob),replace = T) + stats::rnorm(n = n_impu,sd = 10^-4) } imputed_altern_status_mat[subj,] <- ifelse(t<=c,1,0) imputed_altern_time_mat[subj,] <- pmax(ifelse(t<=c,t,c),10^-10) } } chisq_stat_perm <- c() lr_stat_perm <- c() pv_chisq_vec <- rep(NA,n_impu) pv_lr_vec <- rep(NA,n_impu) tab_usage_perm_vec <- rep(NA,n_impu) for (imp in 1:n_impu) { p_group_mat <- replicate(n_perm,sample_group(group,status,imputed_altern_status_mat[,imp])) perm <- get_perm_stats(group,p_group_mat,time,status,imputed_altern_time_mat[,imp], imputed_altern_status_mat[,imp],n_perm = n_perm) pv_chisq_vec[imp] <- (sum(chisq_test_stat<=perm$chisq_stat)+1)/(n_perm +1) pv_lr_vec[imp] <- (sum(lr_test_stat<=perm$lr_stat)+1)/(n_perm +1) tab_usage_perm_vec[imp] <- mean(perm$tab_usage_perm) chisq_stat_perm <- c(chisq_stat_perm,perm$chisq_stat) lr_stat_perm <- c(lr_stat_perm,perm$lr_stat) } pv_chisq <- (sum(chisq_test_stat<=chisq_stat_perm) + 1)/(n_impu*n_perm+1) pv_lr <- (sum(lr_test_stat<=lr_stat_perm) + 1)/(n_impu*n_perm+1) fit_lr <- survival::survdiff(survival::Surv(time, status) ~ group , rho=0) Pvalue_logrank <- 1 - stats::pchisq(fit_lr$chisq, 1) cau <- mean(c(tan((0.5-pv_chisq)*pi), tan((0.5-pv_lr)*pi), tan((0.5-Pvalue_logrank)*pi))) pv_cauchy <- 0.5-atan(cau)/pi tab_usage_perm <- mean(tab_usage_perm_vec) return(list(pv_chisq=pv_chisq, pv_lr=pv_lr, pv_cauchy=pv_cauchy, chisq_test_stat=chisq_test_stat, lr_test_stat=lr_test_stat, cauchy_test_stat = cau, tab_usage = tab_usage, tab_usage_perm = tab_usage_perm, imputed_altern_status_mat=imputed_altern_status_mat, imputed_altern_time_mat=imputed_altern_time_mat, p_group_mat=p_group_mat)) }
library(spiderbar) cdc <- paste0(readLines(system.file("extdata", "cdc-robots.txt", package="spiderbar")), collapse="\n") rt1 <- robxp(cdc) expect_true(inherits(rt1, "robxp")) expect_true(can_fetch(rt1, "/asthma/asthma_stats/default.htm", "*")) expect_false(can_fetch(rt1, "/_borders", "*")) imdb <- paste0(readLines(system.file("extdata", "imdb-robots.txt", package="spiderbar")), collapse="\n") rt2 <- robxp(imdb) cd <- crawl_delays(rt2) expect_true(inherits(cd, "data.frame")) expect_equal(sort(cd$crawl_delay), sort(c(0.1, 3.0, -1.0))) imdb <- readLines(system.file("extdata", "imdb-robots.txt", package="spiderbar")) rt2 <- robxp(imdb) gh <- paste0(readLines(system.file("extdata", "github-robots.txt", package="spiderbar")), collapse="\n") rt3 <- robxp(gh) rt3 <- robxp(file(system.file("extdata", "github-robots.txt", package="spiderbar"))) expect_equal(sitemaps(rt1), "http://www.cdc.gov/niosh/sitemaps/sitemapsNIOSH.xml") expect_equal(sitemaps(rt2), "http://www.imdb.com/sitemap_US_index.xml.gz") expect_equal(sitemaps(rt3), character(0))
effectiveness <- function() { href <- "https://www.sec.gov/cgi-bin/browse-edgar?action=geteffect" res <- edgar_GET(href) doc <- xml2::read_html(res, base_url = href, options = "HUGE") entries_xpath <- "//a[contains(@href, 'filenum=')]" info_pieces <- list( registration_number = ".", file_href = "@href", registrant = "../../td[3]/a/text()", registrant_href = "../../td[3]/a/@href", filing_date_str = "../../td[4]/text()", effective_date_str = "../../td[5]/text()", division = "../../preceding-sibling::tr[count(td[@colspan=3]) = 1][1]/td[2]", type = "../../preceding-sibling::tr[count(td[@colspan=5]) = 1][1]/td[1]" ) res <- map_xml(doc, entries_xpath, info_pieces) res$type <- sub(" Statements", "", res$type, fixed = T) res$division <- sub("Division of ", "", res$division, fixed = T) res[res$type == "Securities Act Registration", "effective_date"] <- as.POSIXct(res[res$type == "Securities Act Registration", "effective_date_str"], format = "%B %d, %Y %I:%M %p", tz = "America/New_York") res[res$type != "Securities Act Registration", "effective_date"] <- as.POSIXct(res[res$type != "Securities Act Registration", "effective_date_str"], format = "%B %d, %Y", tz = "America/New_York") res[res$type != "Securities Act Registration", "filing_date"] <- as.POSIXct(res[res$type != "Securities Act Registration", "filing_date_str"], format = "%B %d, %Y", tz = "America/New_York") res$filing_date_str <- NULL res$effective_date_str <- NULL res }
constrainFun <- function(parameter.val, full, fm2, comp, G, mit = 600){ row <- which(fm2$Gamma == comp) fm2[row, 2:3] <- c(parameter.val, "F") if(G) full$G.param <- fm2 else full$R.param <- fm2 con.mod <- asreml::update.asreml(object = full, maxiter = mit, trace = FALSE) cnt <- 0 while(!con.mod$converge & cnt <= 5){ con.mod <- asreml::update.asreml(con.mod) cnt <- cnt + 1 } cnt <- 0 if(con.mod$converge){ pcc.out <- pcc(con.mod, silent = TRUE) while(!pcc.out & cnt <= 5){ con.mod <- asreml::update.asreml(con.mod, maxiter = mit) if(con.mod$converge) pcc.out <- pcc(con.mod, silent = TRUE) cnt <- cnt + 1 } con.mod$converge <- pcc.out } if(con.mod$converge) return(LRTest(full$loglik, con.mod$loglik)$lambda) else return(NA) }
droplets <- function(..., page = 1, per_page = 25, tag = NULL) { res <- do_GET("droplets", query = list(page = page, per_page = per_page, tag_name = tag), ...) droplets <- lapply(res$droplets, structure, class = "droplet") setNames(droplets, vapply(res$droplets, function(x) x$name, character(1))) }
FairSprErr <- function(ens, obs){ stopifnot(is.matrix(ens), is.vector(obs), nrow(ens) == length(obs)) xmask <- apply(!is.na(ens), 1, any) & !is.na(obs) nens <- ncol(ens) spread <- mean(apply(ens[xmask,,drop=F], 1, sd, na.rm=T)**2, na.rm=T) error <- mean((obs - rowMeans(ens))**2, na.rm=T) return(sqrt((nens + 1) / nens * spread/error)) }
calclambda <- function(tau, x.mix) { res = tau%*%t(x.mix) res = t(exp(res-apply(res,2,max))) sweep(res, 1, rowSums(res), "/") }
NULL dLogisticGrowth=nimbleFunction( run = function(x = integer(0),a=double(0),b=double(0),k=double(0),r=double(0), log = integer(0)) { returnType(double(0)) t = 1:(abs(b-a)+1) n = 1/(1+((1-k)/k)*exp(-r*t)) p = n/sum(n) logProb = dcat(a-x+1,prob=p,log=TRUE) if(log) { return(logProb) } else { return(exp(logProb)) } }) rLogisticGrowth = nimbleFunction( run = function(n=integer(0),a=double(0),b=double(0),k=double(0),r=double(0)) { returnType(double(0)) t = 1:(abs(b-a)+1) pop = 1/(1+((1-k)/k)*exp(-r*t)) p = pop/sum(pop) res=a-rcat(n=1,prob=p)+1 return(res) })
context(".plotMsiSlice") test_that(".array2matrix", { x1 <- array(1:12, dim=c(x=2, y=3, z=2)) x2 <- array(1:12, dim=c(1, 12, 1)) r1 <- matrix(1:6, nrow=2, ncol=3) r2 <- matrix(7:12, nrow=2, ncol=3) r3 <- matrix(1:12, nrow=1, ncol=12) expect_identical(MALDIquant:::.array2matrix(x1), r1) expect_identical(MALDIquant:::.array2matrix(x1, z=2), r2) expect_identical(MALDIquant:::.array2matrix(x2), r3) }) test_that(".colorMatrix", { x <- matrix(c(NA, 1:8, NA), nrow=2) colRamp1 <- colorRamp(c("black", "green")) colRamp2 <- function(x)cbind(0, 0, 30*x) r1 <- matrix(c(NA, rgb(colRamp1(1:8/8), maxColorValue=255), NA), nrow=2) r2 <- matrix(c(NA, rgb(colRamp2(1:8), maxColorValue=255), NA), nrow=2) expect_equal(MALDIquant:::.colorMatrix(x, colRamp1), r1) expect_equal(MALDIquant:::.colorMatrix(x, colRamp2, scale=FALSE), r2) }) test_that(".combineColorMatrices", { x <- array(c(1:8, 8:1), dim=c(2, 4, 2)) col <- array(rep(1:2, each=8), dim=c(2, 4, 2)) r <- matrix(rep(2:1, each=4), nrow=2, ncol=4) expect_equal(MALDIquant:::.combineColorMatrices(x, col), r) }) test_that(".rgb", { r <- cbind(1:255, 1:255, 1:255) expect_equal(MALDIquant:::.rgb(r), rgb(r, maxColorValue=255)) })
dome.lm1 <- lm(Dist ~ Velocity + Angle + BallWt + BallDia + Cond, data = domedata) step(dome.lm1, direction = "both", trace = FALSE)
pattern_square <- function(type = "diagonal", subtype = NULL, nrow = 5L, ncol = 5L) { if (type %in% names_weave) { v <- as.integer(!pattern_weave(type, subtype, nrow, ncol)) + 1L m <- matrix(v, nrow = nrow, ncol = ncol) } else { m <- switch(type, diagonal = pattern_diagonal(subtype, nrow, ncol), diagonal_skew = pattern_diagonal(subtype, nrow, ncol, skew = TRUE), horizontal = pattern_horizontal(subtype, nrow, ncol), square = pattern_square_type(subtype, nrow, ncol), square_tiling = pattern_square_tiling(subtype, nrow, ncol), vertical = pattern_vertical(subtype, nrow, ncol), abort(paste("Don't recognize square pattern type", type)) ) } class(m) <- c("pattern_square", "matrix", "array") m } names_square <- c("diagonal", "diagonal_skew", "horizontal", "square", "square_tiling", "vertical") pattern_diagonal <- function(subtype = NULL, nrow = 5L, ncol = 5L, skew = FALSE) { if (is.null(subtype) || is.na(subtype)) subtype <- 3L stopifnot(is_integer(subtype)) m <- matrix(1L, nrow = nrow, ncol = ncol) n <- as.integer(subtype) if (n == 1L) return(m) s <- seq.int(n) for (e in s) { step <- ifelse(skew, -(e - 1L), e - 1L) v <- rep(cycle_elements(s, step), length.out = ncol) for (i in seq(e, nrow, n)) { m[i, ] <- v } } m } pattern_horizontal <- function(subtype = NULL, nrow = 5L, ncol = 5L) { if (is.null(subtype) || is.na(subtype)) subtype <- 3L stopifnot(is_integer(subtype)) n <- as.integer(subtype) if (nrow > 2L && n > 1L) { v1 <- rev(rep(c(seq.int(n, 2L, -1L), 1L), length.out = nrow %/% 2)) v2 <- rep(seq.int(n), length.out = (nrow %/% 2) + (nrow %% 2)) v <- c(v1, v2) } else { s <- seq.int(n) v <- rep(s, length.out = nrow) } v <- rep.int(v, ncol) matrix(v, nrow = nrow, ncol = ncol) } pattern_square_type <- function(subtype, nrow, ncol) { if (is.null(subtype) || is.na(subtype)) subtype <- 3L stopifnot(is_integer(subtype)) n <- as.integer(subtype) if (n <= 4) pattern_square_tiling(n, nrow, ncol) else pattern_diagonal(n, nrow, ncol) } pattern_square_tiling <- function(subtype, nrow, ncol) { if (is.null(subtype) || is.na(subtype)) subtype <- 3L stopifnot(is_integer(subtype)) if (is.character(subtype)) subtype <- strsplit(subtype, "")[[1]] m <- matrix(1L, nrow = nrow, ncol = ncol) n <- as.integer(subtype) if (all(n == 1L)) return(m) if (length(n) == 1L) { n <- switch(as.character(subtype), `1` = c(1L, 1L, 1L, 1L), `2` = c(2L, 1L, 1L, 2L), `3` = c(1L, 2L, 3L, 1L), `4` = 1:4, n) } n <- rep_len(n, 4) vt <- rep_len(n[1:2], ncol) vb <- rep_len(n[3:4], ncol) for (i in seq_len(nrow)) { if (i %% 2 == 1) m[i, ] <- vb else m[i, ] <- vt } m } pattern_vertical <- function(subtype = NULL, nrow = 5L, ncol = 5L) { if (is.null(subtype) || is.na(subtype)) subtype <- 3L stopifnot(is_integer(subtype)) n <- as.integer(subtype) if (ncol > 2L && n > 1L) { v1 <- rev(rep(c(seq.int(n, 2L, -1L), 1L), length.out = ncol %/% 2)) v2 <- rep(seq.int(n), length.out = (ncol %/% 2) + (ncol %% 2)) v <- c(v1, v2) } else { s <- seq.int(n) v <- rep(s, length.out = ncol) } v <- rep.int(v, nrow) matrix(v, nrow = nrow, ncol = ncol, byrow = TRUE) } print.pattern_square <- function(x, ...) { d <- dim(x) x <- matrix(int_to_char(x), nrow = d[1], ncol = d[2]) cat("/", rep("-", ncol(x)), "\\", "\n") for (i in rev(seq_len(nrow(x)))) { cat("|", x[i, ], "|", "\n") } cat("\\", rep("-", ncol(x)), "/", "\n") invisible(NULL) } is_pattern_square <- function(type) { (type %in% names_weave) || (type %in% names_square) } int_to_char <- function(x) { stopifnot(max(x) < 36L) char <- as.character(x) indices <- which(x > 9L) char[indices] <- LETTERS[x[indices] - 9L] char }
context("test-intercept") test_that("can add an intercept column", { x <- add_intercept_column(mtcars) expect_equal(colnames(x)[1], "(Intercept)") expect_is(x[,1], "integer") xx <- add_intercept_column(as.matrix(mtcars)) expect_is(xx, "matrix") expect_equal(colnames(xx)[1], "(Intercept)") }) test_that("existing intercepts are skipped with a warning", { x <- add_intercept_column(mtcars) expect_warning( xx <- add_intercept_column(x), "`data` already has a column named" ) expect_equal( xx, x ) }) test_that("can change the intercept column name", { x <- add_intercept_column(mtcars, name = "intercept") expect_equal(colnames(x)[1], "intercept") }) test_that("name can only be a single character", { expect_error( add_intercept_column(mtcars, name = c("x", "y")), "name should have size 1, not 2." ) expect_error( add_intercept_column(mtcars, name = 1), "name should be a character, not a numeric." ) })
infillExpectedImprovement <- function(predictionList, model){ mean <- predictionList$y sd <- predictionList$s modelMin <- min(model$y) return(expectedImprovement(mean,sd,modelMin)) }
library(mortAAR) library(magrittr) td <- gallery_graves td %>% head(., n = 10) %>% knitr::kable() td %>% replace(td == "?", NA) -> td td %>% head(., n = 10) %>% knitr::kable() td <- td %>% replace(td == "inf_I", "0-6") %>% replace(td == "inf_II", "7-13") %>% replace(td == "juv", "14-19") td %>% head(., n = 10) %>% knitr::kable() td <- td %>% dplyr::filter(!is.na(age)) td %>% head(., n = 10) %>% knitr::kable() td[td$indnr == "139" & td$site == "Niedertiefenbach", ]$age <- "50-60" td %>% head(n = 10) %>% knitr::kable() td <- td %>% tidyr::separate(age, c("from", "to")) td %>% head(., n = 10) %>% knitr::kable() td <- td %>% transform( from = as.numeric(from), to = as.numeric(to) ) td_prepared <- prep.life.table( td, dec = NA, agebeg = "from", ageend = "to", group = "site", method = "Standard", agerange = "included" ) td_result <- td_prepared %>% life.table() td_result %>% plot(display = c("qx", "dx", "lx")) td_result %>% plot(display = c("ex", "rel_popx"))
"bootsum"<-function(model=NULL,outpdf=TRUE, bootfl="out0002.csv", qtype=7,min=TRUE, showmean=FALSE, showmedian=TRUE, showcinorm=FALSE, showci=TRUE){ bootstrap.data <- read.csv(bootfl, header=T) success = length(bootstrap.data[bootstrap.data$ReturnCode<4,"ReturnCode"]) fail = length(bootstrap.data[bootstrap.data$ReturnCode>3,"ReturnCode"]) if(min){ bootstrap.data = bootstrap.data[bootstrap.data$ReturnCode<4,] } mean = apply(bootstrap.data[,-(1:2)],2,FUN=mean) median = apply(bootstrap.data[,-(1:2)],2,FUN=median) SE = apply(bootstrap.data[,-(1:2)],2,FUN=sd) percentile.ci = apply(bootstrap.data[,-(1:2)],2,FUN=quantile, type=qtype, probs=c(0.005,0.025,0.05,0.95,0.975,0.995)) write.csv(percentile.ci,"percentile.ci.csv") lbootstrap = list(mean=mean,median=median,percentile.ci=percentile.ci) sink("bootsum.txt") suppressMessages(print(lbootstrap)) lbootstrap sink() parname = names(bootstrap.data[,-1]) p1 = list() my_grob = grobTree(textGrob(c("Legend:","Mean","2.5,50,97.5th percentiles","95% CI (normal)"), x=c(0.65,0.65,0.65), y=c(0.97,0.94,0.91,0.88), hjust=0,gp=gpar(col=c("black","green4","blue","darkviolet"), fontsize=12, fontface="italic"))) my2 = rectGrob(x = unit(0.64, "npc"), y = unit(0.91, "npc"), width = unit(0.32, "npc"), height = unit(0.18, "npc"), just = "left", hjust = NULL, vjust = NULL, default.units = "npc", name = NULL, gp=gpar(fill = "white"), vp = NULL) for (ii in 1:length(parname)) { p1[[ii]] = ggplot(data=bootstrap.data, aes_string(x=parname[ii])) + geom_histogram(aes_string(y = "..density..")) + geom_density(color="red") + labs(x = parname[ii]) + ggtitle(paste("Successful runs=",success," Failed runs=",fail)) if(showmean){ p1[[ii]] = p1[[ii]] + geom_vline(xintercept=mean(bootstrap.data[,parname[ii]]),color="green4",lty=2) } if(showmedian){ p1[[ii]] = p1[[ii]] + geom_vline(xintercept=median(bootstrap.data[,parname[ii]]),color="blue",lty=3) } if(showcinorm){ SE = sd(bootstrap.data[,parname[ii]]) p1[[ii]] = p1[[ii]] + geom_vline(xintercept=mean(bootstrap.data[,parname[ii]]) + SE,color="darkviolet",lty=5) + geom_vline(xintercept=mean(bootstrap.data[,parname[ii]]) - SE,color="darkviolet",lty=5) } if(showci){ p1[[ii]] = p1[[ii]] + geom_vline(xintercept=quantile(bootstrap.data[,parname[ii]],0.025),color="blue",lty=5) + geom_vline(xintercept=quantile(bootstrap.data[,parname[ii]],0.975),color="blue",lty=5) } p1[[ii]] = p1[[ii]] + annotation_custom(my2) + annotation_custom(my_grob) } if(outpdf){pdf("bootsum.pdf")} suppressWarnings(print(p1)) if(outpdf){dev.off()} if(file.exists("Results")){ res = paste(getwd(),c("bootsum.txt","percentile.ci.csv","bootsum.pdf"),sep="/") file.copy(res,paste(getwd(),"Results",sep="/"),overwrite=TRUE) }else{ dir.create("Results") res = paste(getwd(),c("bootsum.txt","percentile.ci.csv","bootsum.pdf"),sep="/") file.copy(res,paste(getwd(),"Results",sep="/")) } }
llsearch.LE3.CDS.WITHOUT.I <- function(x, y, n, jlo, jhi, start1, start2, start3, start4, start5) { fj <- matrix(0, n) fxy <- matrix(0, jhi - jlo + 1) jgrid <- expand.grid(jlo:jhi) k.ll <- apply(jgrid, 1, p.estFUN.LE3.CDS.WITHOUT.I, x = x, y = y, n = n, start1=start1, start2=start2, start3=start3, start4=start4, start5 = start5) fxy <- matrix(k.ll, nrow = jhi-jlo+1) rownames(fxy) <- jlo:jhi z <- findmax(fxy) jcrit <- z$imax + jlo - 1 list(jhat = jcrit, value = max(fxy)) } p.estFUN.LE3.CDS.WITHOUT.I <- function(j, x, y, n,start1,start2,start3,start4, start5){ a <- p.est.LE3.CDS.WITHOUT.I(x,y,n,j,start1,start2,start3,start4, start5) s2 <- a$sigma2 t2 <- a$tau2 return(p.ll.CDS.WITHOUT.I(n, j, s2, t2)) } p.est.LE3.CDS.WITHOUT.I <- function(x,y,n,j,start1,start2,start3,start4,start5){ xa <- x[1:j] ya <- y[1:j] jp1 <- j+1 xb <- x[jp1:n] yb <- y[jp1:n] fun <- nls(y ~ I(x <= x[j])*(a0 + a1*x) + I(x > x[j])*(a0 + a1*x[j] - a1/b2 + a1/b2*exp(b2*(x-x[j]))), start = list(a0 = start1, a1 = start2, b2 = start5)) a0 <- summary(fun)$coe[1] a1 <- summary(fun)$coe[2] b2 <- summary(fun)$coe[3] b1 <- a1/b2 b0 <- a0 + a1 * x[j] - b1 beta <-c(a0,a1,b0,b1,b2) s2<- sum((ya-a0-a1*xa)^2)/j t2 <- sum((yb-b0-b1*exp(b2*(xb-x[j]))^2))/(n-j) list(a0=beta[1],a1=beta[2],b0=beta[3],b1=beta[4],b2=beta[5],sigma2=s2,tau2=t2,xj=x[j]) } p.ll.CDS.WITHOUT.I <- function(n, j, s2, t2){ q1 <- n * log(sqrt(2 * pi)) q2 <- 0.5 * j * (1 + log(s2)) q3 <- 0.5 * (n - j) * (1 + log(t2)) - (q1 + q2 + q3) } findmax <-function(a) { maxa<-max(a) imax<- which(a==max(a),arr.ind=TRUE)[1] jmax<-which(a==max(a),arr.ind=TRUE)[2] list(imax = imax, jmax = jmax, value = maxa) }
knitr::opts_chunk$set( collapse = TRUE, comment = " message = FALSE, warning = FALSE ) library(registr) library(ggplot2) library(dplyr) registration_data = simulate_unregistered_curves(I = 50, D = 200, seed = 2018) head(registration_data) registration_data %>% ggplot(aes(index, plogis(latent_mean), group = id)) + theme_bw() + geom_line(alpha = 0.25) + labs(y = "Pr(Y = 1)") registration_data %>% ggplot(aes(t, plogis(latent_mean), group = id)) + theme_bw() + geom_line(alpha = 0.25) + labs(y = "Pr(Y = 1)") fpca_data = simulate_functional_data(I = 100, D = 200) ls(fpca_data) head(fpca_data$Y) Y = fpca_data$Y pc_df = data.frame(pop_mean = fpca_data$alpha, psi1 = fpca_data$psi1, psi2 = fpca_data$psi2, index = seq(0, 1, length.out = 200), id = 1) ggplot(Y, aes(index, latent_mean, group = id)) + theme_bw() + geom_line(alpha = 0.25) + geom_line(data = pc_df, aes(y = pop_mean), color = "red") ggplot(pc_df, aes(index, psi1)) + theme_bw() + geom_line(color = "blue") ggplot(pc_df, aes(index, psi2)) + theme_bw() + geom_line(color = "blue") Y %>% filter(id == 7) %>% ggplot(aes(index, value)) + theme_bw() + geom_point(alpha = 0.75, size = 0.25) + geom_line(aes(y = plogis(latent_mean))) + labs(y = "Pr(Y = 1)") registr_bin = register_fpca(Y = registration_data, family = "binomial", Kt = 8, Kh = 3, npc = 1) Y = registr_bin$Y ggplot(Y, aes(tstar, plogis(latent_mean), group = id)) + theme_bw() + geom_line(alpha = 0.25) + labs(y = "Pr(Y = 1)") ggplot(Y, aes(t, plogis(latent_mean), group = id)) + theme_bw() + geom_line(alpha = 0.25) + labs(y = "Pr(Y = 1)") ggplot(Y, aes(t_hat, plogis(latent_mean), group = id)) + theme_bw() + geom_line(alpha = 0.25) + labs(y = "Pr(Y = 1)") ggplot(Y, aes(tstar, t, group = id)) + theme_bw() + geom_line(alpha = 0.25) ggplot(Y, aes(tstar, t_hat, group = id)) + theme_bw() + geom_line(alpha = 0.25) Y$value = Y$latent_mean registr_gauss = register_fpca(Y = registration_data, family = "gaussian", Kt = 10) bfpca_object = bfpca(fpca_data$Y, npc = 2, Kt = 8, print.iter = TRUE) pc_df = pc_df %>% mutate(psi1_est = bfpca_object$efunctions[,1], psi2_est = bfpca_object$efunctions[,2], alpha_est = bfpca_object$alpha %>% as.vector()) ggplot(pc_df, aes(index, pop_mean)) + theme_bw() + geom_line(color = "blue") + geom_line(aes(y = alpha_est), linetype = 2, color = "red") ggplot(pc_df, aes(index, psi1)) + theme_bw() + geom_line(color = "blue") + geom_line(aes(y = psi2_est), linetype = 2, color = "red") ggplot(pc_df, aes(index, psi2)) + theme_bw() + geom_line(color = "blue") + geom_line(aes(y = psi1_est), linetype = 2, color = "red") data_test_gradient = simulate_unregistered_curves(I = 50, D = 100) start_time = Sys.time() reg_analytic = registr(Y = data_test_gradient, family = "binomial", gradient = TRUE) end_time = Sys.time() analytic_gradient = as.numeric(round((end_time - start_time), 2)) start_time = Sys.time() reg_numeric = registr(Y = data_test_gradient, family = "binomial", gradient = FALSE) end_time = Sys.time() numeric_gradient = as.numeric(round((end_time - start_time), 2))
"italy10"
require(OpenMx) foo <- mxAlgebra(A + B, 'foo') A <- mxMatrix('Full', 1, 2, name = 'A') B <- mxMatrix('Full', 2, 1, name = 'B') model <- mxModel('model', A, B, foo) omxCheckError(mxEval(foo, model, compute=TRUE), paste("The following error occurred while", "evaluating the subexpression 'model.A + model.B'", "during the evaluation of 'foo' in model 'model' : non-conformable arrays")) cycle <- mxAlgebra(cycle, 'cycle') model <- mxModel('model', cycle) omxCheckError(mxRun(model), "A cycle has been detected in model 'model' . It involved the following elements: 'cycle' A common trigger for this error is not providing a name string as the first parameter to mxModel.") foo <- mxAlgebra(bar, 'foo') bar <- mxAlgebra(foo, 'bar') model <- mxModel('model', foo, bar) omxCheckError(mxRun(model), "A cycle has been detected in model 'model' . It involved the following elements: 'bar' and 'foo' A common trigger for this error is not providing a name string as the first parameter to mxModel.") A <- mxMatrix('Full', 1, 1, name = 'A') B <- mxMatrix('Full', 2, 2, name = 'B') C <- mxAlgebra(A, 'C') D <- mxAlgebra(B, 'D') constraint1 <- mxConstraint(A == B, name = 'constraint1') constraint2 <- mxConstraint(C == D, name = 'constraint2') constraint3 <- mxConstraint(1 == B, name = 'constraint3') model1 <- mxModel('model1', A, B, C, D, constraint1) model2 <- mxModel('model2', A, B, C, D, constraint2) model3 <- mxModel('model3', A, B, C, D, constraint3) omxCheckError(mxRun(model1), paste("The algebras/matrices", "'A' and 'B' in model 'model1' are in constraint 'constraint1'", "and are not of identical dimensions. The left-hand side is", "1 x 1 and the right-hand side is 2 x 2.")) omxCheckError(mxRun(model2), paste("The algebras/matrices", "'C' and 'D' in model 'model2' are in constraint 'constraint2'", "and are not of identical dimensions. The left-hand side is", "1 x 1 and the right-hand side is 2 x 2.")) omxCheckError(mxRun(model3), paste("The algebras/matrices", "'1' and 'B' in model 'model3' are in constraint 'constraint3'", "and are not of identical dimensions. The left-hand side is", "1 x 1 and the right-hand side is 2 x 2.")) A <- mxMatrix('Full', 1, 1, name = 'A') B <- mxMatrix('Full', 1, 1, name = 'B', labels = 'A[0,0]') model <- mxModel('model', A, B) omxCheckError(mxRun(model), "Requested improper value (0, 0) from (1, 1) matrix 'model.A'") kevin <- 'bacon' B <- mxAlgebra(A[kevin, ], name = 'B') dimnames(A) <- list('Tom', 'Cruise') model <- mxModel('model', A, B) omxCheckError(mxRun(model), paste("The matrix 'model.A' does", "not contain the row name 'bacon'")) model <- mxModel('model', mxModel("model2", mxAlgebra(model2.objective, name="Obj"), mxFitFunctionAlgebra("Obj"))) omxCheckError(mxRun(model), "A cycle has been detected in model 'model' . It involved the following elements: 'model2.Obj' and 'model2.fitfunction' A common trigger for this error is not providing a name string as the first parameter to mxModel.") mod <- mxModel("amodel", mxMatrix("Full", 4, 1, values=7, name="M"), mxMatrix("Full", 4, 1, values=1:4, name="Thr")) omxCheckError(mxAlgebra(expression="minG", name="blah"), "mxAlgebra wants an unquoted expression or formula") omxCheckWarning(omxMnor(matrix(c(1,90,90,1),2,2), c(0, 0), c(-Inf, -Inf), c(1.282,1.282)), "Correlation with absolute value greater than one found.")
stamppConvert <- function(genotype.file, type="csv"){ if(type=="csv" | type=="r"){ if(type=="csv"){ geno <- read.csv(genotype.file) }else{ geno <- genotype.file } totalind <- nrow(geno) nloc <- ncol(geno)-4 pops <- unique(geno[,2]) npops <- length(pops) pop.num <- vector(length=totalind) for (i in 1:totalind){ pop.num[i]=which(geno[i,2]==pops) } format <- geno[,4] ploidy <- geno[,3] geno <- cbind(geno[,1:2], pop.num, ploidy, format, geno[,5:(4+nloc)]) ab.geno <- subset(geno, geno[,5]=="BiA") nind.ab.geno <- length(ab.geno[,2]) freq.geno <- subset(geno, geno[,5]=="freq") nind.freq.geno <- length(freq.geno[,2]) if(nind.ab.geno > 0){ tmp <- ab.geno[,-c(1:5)] tmp <- gsub("-9", "", as.matrix(tmp), fixed=TRUE) tmp.a <- gsub("B", "", as.matrix(tmp), fixed=TRUE) tmp.a <- nchar(as.matrix(tmp.a)) tmp.b <- gsub("A", "", as.matrix(tmp), fixed=TRUE) tmp.b <- nchar(as.matrix(tmp.b)) res <- matrix(NA, nrow=nind.ab.geno, ncol=nloc) for(i in 1:nloc){ res[,i]=(tmp.a[,i]/(tmp.a[,i]+tmp.b[,i])) } rm(tmp.a, tmp.b, tmp) ab.geno.pt1 <- as.data.frame(ab.geno[,c(1:5)], stringsAsFactors=FALSE) ab.geno.pt2 <- as.data.frame(res, stringsAsFactors=FALSE) ab.geno <- cbind(ab.geno.pt1, ab.geno.pt2) rm(ab.geno.pt2, ab.geno.pt1, res) } colnames(ab.geno)=colnames(geno) freq.geno.pt1 <- freq.geno[,c(1:5)] freq.geno.pt2 <- as.matrix(freq.geno[,-c(1:5)]) class(freq.geno.pt2)="numeric" freq.geno.pt2[freq.geno.pt2==-9]=NA freq.geno <- cbind(freq.geno.pt1, freq.geno.pt2) colnames(freq.geno)=colnames(geno) comb.geno <- rbind(ab.geno, freq.geno) rm(ab.geno, freq.geno, geno) comb.geno[,1]=as.character(comb.geno[,1]) comb.geno[,2]=as.character(comb.geno[,2]) comb.geno[,3]=as.integer(as.character(comb.geno[,3])) comb.geno[,4]=as.integer(as.character(comb.geno[,4])) comb.geno[,5]=as.character(comb.geno[,5]) comb.geno <- comb.geno[ order(comb.geno[,3]),] return(comb.geno) } if(type=="genlight"){ geno2 <- genotype.file geno <- as.matrix(geno2) sample <- row.names(geno) pop.names <- pop(geno2) ploidy <- ploidy(geno2) geno=geno*(1/ploidy) geno[is.na(geno)]=NaN format <- vector(length=length(geno[,1])) format[1:length(geno[,1])]="genlight" pops <- unique(pop.names) pop.num <- vector(length=length(geno[,1])) for (i in 1:length(geno[,1])){ pop.num[i]=which(pop.names[i]==pops) } genoLHS <- as.data.frame(cbind(sample, pop.names, pop.num, ploidy, format), stringsAsFactors=FALSE) geno <- cbind(genoLHS, geno) geno[,2]=as.character(pop.names) geno[,4]=as.numeric(as.character(geno[,4])) row.names(geno)=NULL return(geno) } }
structure(list(url = "https://api.scryfall.com/sets/2ec77b94-6d47-4891-xxxx-5d0b4e5c9372", status_code = 404L, headers = structure(list(date = "Wed, 05 Jan 2022 05:19:09 GMT", `content-type` = "application/json; charset=utf-8", `x-frame-options` = "DENY", `x-xss-protection` = "1; mode=block", `x-content-type-options` = "nosniff", `x-download-options` = "noopen", `x-permitted-cross-domain-policies` = "none", `referrer-policy` = "strict-origin-when-cross-origin", `access-control-allow-origin` = "*", `access-control-allow-methods` = "GET, POST, DELETE, OPTIONS", `access-control-allow-headers` = "Accept, Accept-Charset, Accept-Language, Authorization, Cache-Control, Content-Language, Content-Type, DNT, Host, If-Modified-Since, Keep-Alive, Origin, Referer, User-Agent, X-Requested-With", `access-control-max-age` = "300", `x-robots-tag` = "none", `cache-control` = "public", `x-action-cache` = "HIT", vary = "Accept-Encoding", `content-encoding` = "gzip", `strict-transport-security` = "max-age=31536000; includeSubDomains; preload", via = "1.1 vegur", `cf-cache-status` = "DYNAMIC", `expect-ct` = "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"", `report-to` = "{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=TrMtUlv%2F%2BWJWS9WVkEMAPEA0cLhpdtvV3cLtqWzLp70LTe%2BFlZIzq2LRtxhVoqwJWuZA3P3iFxCeVbScm92obAZoZ5B0DnMZsImVSTbIhAT73UG2R7NUsok0IX9r1HtuqCYsOAw2gSC8lgWBH3k%3D\"}],\"group\":\"cf-nel\",\"max_age\":604800}", nel = "{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}", server = "cloudflare", `cf-ray` = "6c8a4005ca6f4edd-GRU", `alt-svc` = "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400, h3-28=\":443\"; ma=86400, h3-27=\":443\"; ma=86400"), class = c("insensitive", "list")), all_headers = list(list(status = 404L, version = "HTTP/2", headers = structure(list(date = "Wed, 05 Jan 2022 05:19:09 GMT", `content-type` = "application/json; charset=utf-8", `x-frame-options` = "DENY", `x-xss-protection` = "1; mode=block", `x-content-type-options` = "nosniff", `x-download-options` = "noopen", `x-permitted-cross-domain-policies` = "none", `referrer-policy` = "strict-origin-when-cross-origin", `access-control-allow-origin` = "*", `access-control-allow-methods` = "GET, POST, DELETE, OPTIONS", `access-control-allow-headers` = "Accept, Accept-Charset, Accept-Language, Authorization, Cache-Control, Content-Language, Content-Type, DNT, Host, If-Modified-Since, Keep-Alive, Origin, Referer, User-Agent, X-Requested-With", `access-control-max-age` = "300", `x-robots-tag` = "none", `cache-control` = "public", `x-action-cache` = "HIT", vary = "Accept-Encoding", `content-encoding` = "gzip", `strict-transport-security` = "max-age=31536000; includeSubDomains; preload", via = "1.1 vegur", `cf-cache-status` = "DYNAMIC", `expect-ct` = "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"", `report-to` = "{\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=TrMtUlv%2F%2BWJWS9WVkEMAPEA0cLhpdtvV3cLtqWzLp70LTe%2BFlZIzq2LRtxhVoqwJWuZA3P3iFxCeVbScm92obAZoZ5B0DnMZsImVSTbIhAT73UG2R7NUsok0IX9r1HtuqCYsOAw2gSC8lgWBH3k%3D\"}],\"group\":\"cf-nel\",\"max_age\":604800}", nel = "{\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}", server = "cloudflare", `cf-ray` = "6c8a4005ca6f4edd-GRU", `alt-svc` = "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400, h3-28=\":443\"; ma=86400, h3-27=\":443\"; ma=86400"), class = c("insensitive", "list")))), cookies = structure(list(domain = ".api.scryfall.com", flag = TRUE, path = "/", secure = FALSE, expiration = structure(1641440572, class = c("POSIXct", "POSIXt")), name = "heroku-session-affinity", value = "REDACTED"), row.names = c(NA, -1L), class = "data.frame"), content = charToRaw("{\n \"object\": \"error\",\n \"code\": \"not_found\",\n \"status\": 404,\n \"details\": \"No Magic set found for the given code or ID\"\n}"), date = structure(1641359949, class = c("POSIXct", "POSIXt" ), tzone = "GMT"), times = c(redirect = 0, namelookup = 5.4e-05, connect = 5.5e-05, pretransfer = 0.000161, starttransfer = 0.173284, total = 0.17351)), class = "response")
HDIofMCMC = function(sampleVec, credMass = 0.95) { sortedPts = sort(sampleVec) ciIdxInc = floor(credMass * length(sortedPts)) nCIs = length(sortedPts) - ciIdxInc ciWidth = rep(0 , nCIs) for (i in 1:nCIs) { ciWidth[i] = sortedPts[i + ciIdxInc] - sortedPts[i] } HDImin = sortedPts[which.min(ciWidth)] HDImax = sortedPts[which.min(ciWidth) + ciIdxInc] HDIlim = c(HDImin , HDImax) return(HDIlim) }
setBoottest_nthreads <- function(nthreads){ max_CRAN <- as.numeric(Sys.getenv("OMP_THREAD_LIMIT")) max_CRAN[is.na(max_CRAN)] <- 1000 max_threads <- min(cpp_get_nb_threads(), 1000, max_CRAN) if(missing(nthreads) || is.null(nthreads)){ nthreads <- 1 } nthreads <- check_set_nthreads(nthreads) options("boottest_nthreads" = nthreads) invisible() } getBoottest_nthreads <- function(){ x <- getOption("boottest_nthreads") if(length(x) != 1 || !is.numeric(x) || is.na(x) || x %% 1 != 0 || x < 0){ stop("The value of getOption(\"boottest_nthreads\") is currently not legal. Please use function setBoottest_nthreads to set it to an appropriate value. ") } x } check_set_nthreads <- function(nthreads){ dreamerr::set_up(1) dreamerr::check_value(nthreads, "integer scalar GE{0} | numeric scalar GT{0} LT{1}", .message = paste0("The argument 'nthreads' must be an integer lower or equal to the number of threads available (", max(cpp_get_nb_threads(), 1), "). It can be equal to 0 which means all threads. Alternatively, if equal to a number strictly between 0 and 1, it represents the fraction of all threads to be used.")) max_threads <- cpp_get_nb_threads() if(nthreads == 0){ nthreads <- max(max_threads, 1) } else if(nthreads < 1){ nthreads <- max(ceiling(max_threads * nthreads), 1) } else if(nthreads > 1){ if(max_threads == 0){ dreamerr::warn_up("OpenMP not detected: cannot use ", nthreads, " threads, single-threaded mode instead.") nthreads <- 1 } else if(nthreads > max_threads){ dreamerr::warn_up("Asked for ", nthreads, " threads while the maximum is ", max_threads, ". Set to ", max_threads, " threads instead.") nthreads <- max_threads } } nthreads }
text_collapse <- function (x, coll="") { UseMethod("text_collapse") } text_collapse.default <- function(x, coll=""){ paste0(unlist(x), collapse = coll) } text_collapse.list <- function(x, coll=""){ text_collapse( unlist(lapply(x, text_collapse, coll=coll)), coll) } text_collapse.data.frame <- function(x, coll=""){ x <- apply(x, 1, text_collapse, coll=coll[1]) x <- unlist(x, recursive = FALSE) if(length(coll)>1){ coll <- coll[2] } text_collapse(x, coll=coll) } text_collapse.matrix <- function(x, coll=""){ text_collapse(as.data.frame(x), coll) }
NULL "%m+%" <- function(e1, e2) standardGeneric("%m+%") setGeneric("%m+%") setMethod("%m+%", signature(e2 = "Period"), function(e1, e2) add_with_rollback(e1, e2)) setMethod("%m+%", signature(e1 = "Period"), function(e1, e2) add_with_rollback(e2, e1)) setMethod("%m+%", signature(e2 = "ANY"), function(e1, e2) stop("%m+% handles only Period objects as second argument")) "%m-%" <- function(e1, e2) standardGeneric("%m-%") setGeneric("%m-%") setMethod("%m-%", signature(e2 = "Period"), function(e1, e2) add_with_rollback(e1, -e2)) setMethod("%m-%", signature(e1 = "Period"), function(e1, e2) add_with_rollback(e2, -e1)) setMethod("%m-%", signature(e2 = "ANY"), function(e1, e2) stop("%m-% handles only Period objects as second argument")) add_with_rollback <- function(e1, e2, roll_to_first = FALSE, preserve_hms = TRUE) { any_HMS <- any([email protected] != 0) || any(e2@minute != 0) || any(e2@hour != 0) || any(e2@day != 0) any_year <- any(e2@year != 0) if (!is.na(any_year) && any_year) { e2$month <- 12 * e2@year + e2@month e2$year <- 0L } new <- .quick_month_add(e1, e2@month) roll <- day(new) < day(e1) roll <- !is.na(roll) & roll new[roll] <- rollback(new[roll], roll_to_first = roll_to_first, preserve_hms = preserve_hms) if (!is.na(any_HMS) && any_HMS) { e2$month <- 0L new + e2 } else { new } } .quick_month_add <- function(object, mval) { tzs <- tz(object) utc <- as.POSIXlt(force_tz(object, tzone = "UTC")) utc$mon <- utc$mon + mval utc <- as.POSIXct(utc) new <- force_tz(utc, tzone = tzs, roll = TRUE) reclass_date(new, object) } rollbackward <- function(dates, roll_to_first = FALSE, preserve_hms = TRUE) { .roll(dates, roll_to_first, preserve_hms) } rollback <- rollbackward rollforward <- function(dates, roll_to_first = FALSE, preserve_hms = TRUE) { .roll(dates, roll_to_first, preserve_hms, forward = TRUE) } .roll <- function(dates, roll_to_first, preserve_hms, forward = FALSE) { if (length(dates) == 0) return(dates) day(dates) <- 1 if (!preserve_hms) { hour(dates) <- 0 minute(dates) <- 0 second(dates) <- 0 } if (forward) { dates <- dates + months(1) } if (roll_to_first) { dates } else { dates - days(1) } }
test_that("traits", { expect_equal(2 * 2, 4) })
grad_fun = function(par,ImpCov,SampCov,Areg,Sreg,A,S,F, A_fixed,A_est,S_fixed,S_est,lambda,type,pars_pen,I){ grad_out <- rep(0,length(par)) h = sqrt(.Machine$double.eps) A_iter <- max(A) if(type=="none"){ for(i in 1:length(par)){ add <- rep(0,length(par)) add[i] <- h ImpCovL = rcpp_RAMmult((par+add),A,S,S_fixed,A_fixed,A_est,S_est,F,I)[[1]] ImpCovDot <- (ImpCovL - ImpCov)/h grad_out[i] <- 0.5 * trace(solve(ImpCov) %*% (ImpCov - SampCov) %*% solve(ImpCov) %*% ImpCovDot) } } else if(type=="ridge"){ for(i in 1:length(par)){ add <- rep(0,length(par)) add[i] <- h ImpCovL = rcpp_RAMmult((par+add),A,S,S_fixed,A_fixed,A_est,S_est,F,I)[[1]] ImpCovDot <- (ImpCovL - ImpCov)/h grad_out[i] <- 0.5 * (trace(solve(ImpCov) %*% (ImpCov - SampCov) %*% solve(ImpCov) %*% ImpCovDot)) + if(any(i==pars_pen)) 2*lambda*(max(Areg[A == i], Sreg[S==i])) else(0) } } else if(type=="lasso"){ for(i in 1:length(par)){ add <- rep(0,length(par)) add[i] <- h ImpCovL = rcpp_RAMmult((par+add),A,S,S_fixed,A_fixed,A_est,S_est,F,I)[[1]] ImpCovDot <- (ImpCovL - ImpCov)/h grad_out[i] <- 0.5 * (trace(solve(ImpCov) %*% (ImpCov - SampCov) %*% solve(ImpCov) %*% ImpCovDot)) } } else if(type=="enet"){ for(i in 1:length(par)){ add <- rep(0,length(par)) add[i] <- 1 + h ImpCovL = RAMmult((par + add),A,S,F,A_fixed,A_est,S_fixed,S_est)[[1]] ImpCovDot <- (ImpCovL - ImpCov)/h grad_out[i] <- 0.5 * trace(solve(ImpCov) %*% (ImpCov - SampCov) %*% solve(ImpCov) %*% ImpCovDot) } }else if(type=="ols_lasso"){ for(i in 1:length(par)){ add <- rep(0,length(par)) add[i] <- h ImpCovL = RAMmult((par + add),A,S,F,A_fixed,A_est,S_fixed,S_est)[[1]] ImpCovDot <- (ImpCovL - ImpCov)/h grad_out[i] <- 0.5 * trace(solve(ImpCov) %*% (ImpCov - SampCov) %*% solve(ImpCov) %*% ImpCovDot) + if(i <= A_iter) lambda*sign(Areg[A==i]) else(0) } } as.numeric(grad_out) }
Cushion <- R6::R6Class( "Cushion", public = list( host = '127.0.0.1', port = 5984, path = NULL, transport = 'http', user = NULL, pwd = NULL, headers = NULL, initialize = function(host, port, path, transport, user, pwd, headers) { if (!missing(host)) self$host <- host if (!missing(port)) self$port <- port if (!missing(path)) self$path <- path if (!missing(transport)) self$transport <- transport if (!missing(user)) self$user <- user if (!missing(pwd)) self$pwd <- pwd if (!missing(user) && !missing(pwd)) { private$auth_headers <- crul::auth(user, pwd) } if (!missing(headers)) self$headers <- headers }, print = function() { cat("<sofa - cushion> ", sep = "\n") cat(paste0(" transport: ", self$transport), sep = "\n") cat(paste0(" host: ", self$host), sep = "\n") cat(paste0(" port: ", self$port), sep = "\n") cat(paste0(" path: ", self$path), sep = "\n") cat(paste0(" type: ", self$type), sep = "\n") cat(paste0(" user: ", self$user), sep = "\n") cat(paste0(" pwd: ", if (!is.null(self$pwd)) '<secret>' else ''), sep = "\n") invisible(self) }, ping = function(as = 'list', ...) { sofa_GET(self$make_url(), as = as, query = NULL, headers = self$get_headers(), auth = self$get_auth(), ...) }, make_url = function() { tmp <- sprintf("%s://%s", self$transport, self$host) if (!is.null(self$port)) { tmp <- sprintf("%s:%s", tmp, self$port) } if (!is.null(self$path)) { tmp <- sprintf("%s/%s", tmp, self$path) } tmp }, get_headers = function() self$headers, get_auth = function() private$auth_headers, version = function() { z <- self$ping() ver <- as.numeric(paste0(strx(z$version, '[0-9]'), collapse="")) if (nchar(ver) < 3) { ver <- as.numeric(paste0(c(ver, rep("0", times=3-nchar(ver))), collapse="")) } return(ver) } ), private = list( auth_headers = NULL ) ) check_cushion <- function(x) { if (!inherits(x, "Cushion")) { stop("input must be a sofa Cushion object, see ?Cushion", call. = FALSE) } } strx <- function(str, pattern) regmatches(str, gregexpr(pattern, str))[[1]]
qnorm(0.80, 500, 100) qnorm(0.80, 500, 110)
perturb <- function(x, mu, dv, tol=0.01){ p = rnorm(length(x), mu, dv) x.p = x + p*tol*(norm(x,"2")/norm(p,"2")) return(x.p) }
setGeneric("sort", function(x, decreasing=FALSE, ...) standardGeneric("sort")) setMethod("sort", signature(x="klausuR"), function(x, decreasing=FALSE, sort.by=c()){ if(length(x@results) == 0){ return(invisible(NULL)) } else {} global.results <- x@results anon.results <- x@anon if(length(sort.by) > 0){ if(!sort.by %in% names(global.results)){ stop(simpleError(paste("Can't sort by '",sort.by,"', there's no such variable!", sep=""))) } else {} new.order <- order(global.results[[sort.by]], decreasing=decreasing) global.results <- global.results[new.order,] anon.results <- anon.results[new.order,] dimnames(global.results)[[1]] <- 1:nrow(global.results) dimnames(anon.results)[[1]] <- 1:nrow(anon.results) } else {} x@results <- global.results x@anon <- anon.results return(x) })
source('../gsDesign_independent_code.R') testthat::test_that("Test: plot.ssrCP graphs are correctly rendered ", { ssr.cp.des <- ssrCP(z1 = seq(-3, 3, 0.1), theta = NULL, maxinc = 2, overrun = 0, beta = 0.1, cpadj = c(0.5, 1 - 0.2), x = gsDesign(k = 2, delta = 0.2), z2 = z2NC) save_plot_obj <- save_gg_plot(plot.ssrCP(x = ssr.cp.des, z1ticks = NULL, mar = c(7, 4, 4, 4) + 0.1, ylab = "Adapted sample size", xlaboffset = -0.2, lty = 1, col = 1)) local_edition(3) expect_snapshot_file(save_plot_obj, "plot_ssrCP_1.png") })
igraph_to_network <- function(in_graph){ if(igraph::is.directed(in_graph)) stop('Only undirected graphs are supported at the moment. Please import undirected igraph object, e.g. output of graph_from_edgelist(el,directed = FASLE)') edges <- igraph::as_edgelist(in_graph) edges <- order.edges(edges, ord.col = TRUE) degree <- igraph::degree(in_graph) n <- igraph::gorder(in_graph) list(edges = edges, degree = degree, n = n) }
forest <- function (x, ...) { UseMethod("forest") } forest.umbrella <- function (x, measure = "eG", main_title = NA, main_value = NA, main_x_axis = NA, max.value = NULL, print.classes = NULL, col_sig = c(" log_cex_dots = FALSE, fix_size_dots = NA, xlim = NULL, xlim_main_title = 0, xlim_value = 2.1, xlim_factor = -2.1, ylim_correction_value = 0, ylim_correction_text = 0, cex_title = 1.4, cex_text_header = 1, cex_text = 0.9, cex_value_header = 1, cex_value = 0.9, cex_x_axis = 1.1, cex_x_axis_value = 0.8, cex_dots = 1.2, col_title = " col_text_header = " col_text = " col_value_header = " col_value = " col_x_axis = " col_dots = " col_lines = " pos_value = "left-align", pos_text = "right-align", add_columns = NULL, main_add_columns = NA, xlim_add_columns = NA, x_lim_adj = 0, y_lim_adj = 0, x_axis_adj = 0, ...) { if (!inherits(x, "umbrella")) { stop("The 'x' argument must be an 'umbrella' object") } if (!measure %in% c("SMD", "eG", "OR", "eOR")) { stop("The 'measure' argument must be either 'eOR' or 'eG'") } else if (measure =="SMD") { measure <- "eG" } else if (measure == "OR") { measure <- "eOR" } if (pos_value == "right-align") { pos_value = 2 pos_value_ylim_cor = 0 } else if (pos_value == "left-align") { pos_value = 4 pos_value_ylim_cor = 0 } else if (pos_value == "center") { pos_value = 3 pos_value_ylim_cor = -0.45 } else { stop("The 'pos_value' must be either 'left-align', 'right-align' or 'center'.") } if (pos_text == "right-align") { pos_text = 2 pos_text_ylim_cor = 0 } else if (pos_text == "left-align") { pos_text = 4 pos_text_ylim_cor = 0 } else if (pos_text == "center") { pos_text = 3 pos_text_ylim_cor = -0.45 } else { stop("The 'pos_text' must be either 'left-align', 'right-align' or 'center'.") } criteria = attr(x,"criteria") y <- NULL for (name in names(x)) { x_i <- x[[name]] if (is.null(criteria) || is.null(print.classes) || x_i$evidence %in% print.classes) { y_i <- x_i$random$value ci_lo_i <- x_i$random$ci_lo ci_up_i <- x_i$random$ci_up if (x_i$measure == "eOR" && measure == "eG") { y_i <- .or_to_d(exp(y_i)); ci_lo_i <- .or_to_d(exp(ci_lo_i)); ci_up_i <- .or_to_d(exp(ci_up_i)); } else if (x_i$measure == "eG" && measure == "eOR") { y_i <- log(.d_to_or(y_i)); ci_lo_i <- log(.d_to_or(ci_lo_i)); ci_up_i <- log(.d_to_or(ci_up_i)); } y_i <- data.frame(y = y_i, ci_lo = ci_lo_i, ci_up = ci_up_i ) if (!is.null(criteria)) { if (criteria == "GRADE") { class <- switch(x_i$evidence, "High" = 1, "Moderate" = 2, "Weak" = 3, 4 ) } else if (criteria == "Ioannidis") { class <- switch(x_i$evidence, "I" = 1, "II" = 2, "III" = 3, "IV" = 4, 5 ) } else if (criteria == "Personalised") { class <- switch(x_i$evidence, "I" = 1, "II" = 2, "III" = 3, "IV" = 4, 5 ) } y_i$class = class } rownames(y_i) <- name y <- rbind(y, y_i) } } if (is.null(y)) { warning("No factors to plot") return(invisible(list(optimal.width = NA, optimal.height = NA))); } n.stud <- nrow(y); y <- y[order(abs(y$y), decreasing = TRUE),] if (!is.null(criteria)) { CLASS <- y$class CLASS <- sort(.as_numeric(CLASS)) LEN <- ifelse(length(CLASS) == 1, 1, length(CLASS) - 1) warn <- ifelse(length(CLASS) == 1, "warning", "ok") if (warn != "warning") { for (i in 1:LEN) { if (!(CLASS[i + 1] == CLASS[i] | CLASS[i + 1] == CLASS[i] + 1)) { CLASS[which(CLASS == CLASS[i + 1])] = CLASS[i] + 1 } } } if (min(CLASS) != 1) { delta = 1 - min(CLASS) CLASS = CLASS + delta } y <- y[order(y$class),] n.classes <- length(unique(y$class)) pos.y.value <- n.stud + 1 - 1:n.stud + n.classes - CLASS + ylim_correction_value + pos_value_ylim_cor pos.y.text <- n.stud + 1 - 1:n.stud + n.classes - CLASS + ylim_correction_text + pos_text_ylim_cor } else { n.classes <- 0 pos.y.value <- n.stud + 1 - 1:n.stud + ylim_correction_value + pos_value_ylim_cor pos.y.text <- n.stud + 1 - 1:n.stud + ylim_correction_text + pos_text_ylim_cor } labels <- rownames(y) if (is.na(fix_size_dots)) { lwd <- 1 / (y$ci_up - y$ci_lo); if(length(lwd) > 1) { lwd <- sqrt(30 + 150 * (lwd - min(lwd)) / (max(lwd) - min(lwd))) * cex_dots } else { if (lwd < 10) { lwd <- 10 } } if (log_cex_dots) { lwd <- log(lwd) * 4 } } else { lwd <- rep(fix_size_dots, nrow(y)) } if (measure == "eG") { value.text <- paste0(gsub(" ", "", format(round(y$y, 2), nsmall = 2)), " [", gsub(" ", "", format(round(y$ci_lo, 2), nsmall = 2)), ", ", gsub(" ", "", format(round(y$ci_up, 2), nsmall = 2)), "]") } else { value.text <- paste0(gsub(" ", "", format(round(exp(y$y), 2), nsmall = 2)), " [", gsub(" ", "", format(round(exp(y$ci_lo), 2), nsmall = 2)), ", ", gsub(" ", "", format(round(exp(y$ci_up), 2), nsmall = 2)), "]") } if (is.null(max.value)) { if (measure == "eG") { est.max.value <- max(-quantile(y$ci_lo, 0.05), -y$y, y$y, quantile(y$ci_up, 0.95)) max.value <- ceiling(est.max.value); } else { est.max.value <- exp(max(-quantile(y$ci_lo, 0.05), -y$y, y$y, quantile(y$ci_up, 0.95))) power <- 10^(-floor(log10(abs(est.max.value)))); max.value <- log(ceiling(est.max.value * power) / power); } } else { if (measure == "eOR") { max.value <- log(max.value) } } plot.new(); if (is.null(xlim)) { xlim <- c(x_lim_adj -2.5 - max(strwidth(labels, units = "inches")), max(strwidth(value.text, units = "inches")) + 2.5 - x_lim_adj); } ylim <- c(-2.2 + y_lim_adj, n.stud + n.classes + 2 - y_lim_adj); plot.window(xlim = xlim, ylim = ylim, ...); lines(x = c(0, 0), y = c(n.classes + n.stud + 0.5, 0), col = " lines(x = c(-2, 2), y = rep(0, 2), col = " for (pos.x in -2:2) { lines(rep(pos.x, 2), c(0, -0.2), col = " if (measure == "eG") { text(pos.x, -0.2, round((pos.x) / 2 * max.value, 2), pos = 1, col = " } else { text(pos.x, -0.2, round(exp((pos.x) / 2 * max.value), 2), pos = 1, col = " } } if (!is.na(main_title)) { text(x = xlim_main_title, y = n.classes + n.stud + 2, paste0(main_title), col = col_title, font = 1, family = "sans", cex = cex_title) } if (measure == "eG") { if (is.na(main_x_axis)) { main_x_axis <- "Equivalent Hedges's g (eG)" } text(x = 0, y = -1.7 + x_axis_adj, paste0(main_x_axis), col = col_x_axis, font = 2, family = "sans", cex = cex_x_axis) } else { if (is.na(main_x_axis)) { main_x_axis <- "Equivalent Odds Ratio (eOR)" } text(x = 0, y = -1.7 + x_axis_adj, paste0(main_x_axis), col = col_x_axis, font = 2, family = "sans", cex = cex_x_axis) } if (!is.null(criteria)) { if (criteria == "GRADE") { if (any(y$class == 1)) { text(x = xlim_factor, y = - 0.05 + n.classes + n.stud + ylim_correction_text + pos_text_ylim_cor, "GRADE 4\n(high)", pos = pos_text, font = 2, col = " } if (any(y$class == 2)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 1) + any(y$class == 3) + any(y$class == 4) + 1 + ylim_correction_text + pos_text_ylim_cor, "GRADE 3\n(moderate)", pos = pos_text, font = 2, col = " } if (any(y$class == 3)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 2) + any(y$class == 4) + 1 + ylim_correction_text + pos_text_ylim_cor, "GRADE 2\n(weak)", pos = pos_text, font = 2, col = " } if (any(y$class == 4)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 3) + 1 + ylim_correction_text + pos_text_ylim_cor, "GRADE 1\n(very weak)", pos = pos_text, font = 2, col = " } } else if (criteria == "Ioannidis") { if (any(y$class == 1)) { text(x = xlim_factor, y = - 0.05 + n.classes + n.stud + ylim_correction_text + pos_text_ylim_cor, "Class I", pos = pos_text, font = 2, col = " } if (any(y$class == 2)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 1) + any(y$class == 3) + any(y$class == 4) + any(y$class == 5) + 1 + ylim_correction_text + pos_text_ylim_cor, "Class II", pos = pos_text, font = 2, col = " } if (any(y$class == 3)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 2) + any(y$class == 4) + any(y$class == 5) + 1 + ylim_correction_text + pos_text_ylim_cor, "Class III", pos = pos_text, font = 2, col = " } if (any(y$class == 4)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 3) + any(y$class == 5) + 1 + ylim_correction_text + pos_text_ylim_cor, "Class IV", pos = pos_text, font = 2, col = " } if (any(y$class == 5)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 4) + 1 + ylim_correction_text + pos_text_ylim_cor, "Class ns", pos = pos_text, font = 2, col = " } } else if (criteria == "Personalised") { if (any(y$class == 1)) { text(x = xlim_factor, y = - 0.05 + n.classes + n.stud + ylim_correction_text + pos_text_ylim_cor, "Class I", pos = pos_text, font = 2, col = " } if (any(y$class == 2)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 1) + any(y$class == 3) + any(y$class == 4) + any(y$class == 5) + 1 + ylim_correction_text + pos_text_ylim_cor, "Class II", pos = pos_text, font = 2, col = " } if (any(y$class == 3)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 2) + any(y$class == 4) + any(y$class == 5) + 1 + ylim_correction_text + pos_text_ylim_cor, "Class III", pos = pos_text, font = 2, col = " } if (any(y$class == 4)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 3) + any(y$class == 5) + 1 + ylim_correction_text + pos_text_ylim_cor, "Class IV", pos = pos_text, font = 2, col = " } if (any(y$class == 5)) { text(x = xlim_factor, y = - 0.05 + sum(y$class > 4) + 1 + ylim_correction_text + pos_text_ylim_cor, "Class V", pos = pos_text, font = 2, col = " } } } for (i in 1:n.stud) { pos.y.value_i <- pos.y.value[i] pos.y.text_i <- pos.y.text[i] y_i <- y$y[i] ci_lo_i <- y$ci_lo[i] ci_up_i <- y$ci_up[i] if (any(is.na(col_sig))) { col_sig <- col_dots} col2_i <- ifelse(ci_lo_i > 0, col_sig[2], ifelse(ci_up_i < 0, col_sig[1], col_dots)); if (y_i < max.value) { lines(x = rep(y_i / max.value * 2, 2), y = rep(pos.y.value_i, 2) - pos_value_ylim_cor - ylim_correction_value, lwd = lwd[i], col = col2_i); } if (ci_lo_i < max.value) { lines(x = c(max(ci_lo_i / max.value * 2, -2), min(ci_up_i / max.value * 2, 2)), y = rep(pos.y.value_i, 2) - pos_value_ylim_cor - ylim_correction_value, lend = 2, col = col2_i); if (ci_lo_i > -max.value) { lines(x = rep(ci_lo_i / max.value * 2, 2), y = pos.y.value_i + c(0.0, 0.0) - pos_value_ylim_cor - ylim_correction_value, lend = 2, col = col2_i); } if (ci_up_i < max.value) { lines(x = rep(ci_up_i / max.value * 2, 2), y = pos.y.value_i + c(0.0, 0.0) - pos_value_ylim_cor - ylim_correction_value, lend = 2, col = col2_i); } } text(x = xlim_factor, y = pos.y.text_i, labels[i], pos = pos_text, col = col_text, family = "sans", cex = cex_text); text(x = xlim_value, y = pos.y.value_i, value.text[i], pos = pos_value, col = col_value, family = "sans", cex = cex_value); } if(is.null(criteria)) { text(xlim_factor, max(pos.y.text) + 1, "Factors", pos = pos_text, col = col_text_header, font = 2, family = "sans", cex = cex_text_header * 1.025);} if (measure == "eG") { if (is.na(main_value)) { main_value = "eG [95% CI]"} text(x = xlim_value, y = max(pos.y.value) + 1 , paste0(main_value), pos = pos_value, col = col_value_header, font = 2, family = "sans", cex = cex_value_header); } else { if (is.na(main_value)) { main_value = "eOR [95% CI]"} text(x = xlim_value, y = max(pos.y.value) + 1, paste0(main_value), pos = pos_value, col = col_value_header, font = 2, family = "sans", cex = cex_value_header); } base_pos = 0 if (!is.null(add_columns)) { if (is.vector(add_columns)) { add_columns <- data.frame(add_columns) } if (length(xlim_add_columns) < ncol(add_columns)) { stop("The 'xlim_add_columns' argument contains less values than the number of columns of the dataset in 'add_columns'.") } if (any(is.na(main_add_columns))) { main_add_columns <- substr(paste0(colnames(add_columns)), start = 1, stop = 7)} for (col in colnames(add_columns)) { base_pos = base_pos + 1 for (i in 1:n.stud) { pos.y.text_i <- pos.y.text[i] text(x = xlim_add_columns[base_pos], y = pos.y.text_i, add_columns[i, col], pos = pos_text, col = col_text, font = 1, family = "sans", cex = cex_text) } text(x = xlim_add_columns[base_pos], y = max(pos.y.text) + 1, paste0(main_add_columns[base_pos]), pos = pos_text, col = col_text_header, font = 2, family = "sans", cex = cex_text_header) } } y <- cbind(y, factor = row.names(y)) width <- round(diff(xlim)); height <- round(diff(ylim) / 3); cat("\n"); cat("Use pdf(filename, width, height) before calling forest to save it.\n"); cat("The optimal width and height of this plot is ~", width, " x ~", height, " inches.\n", sep = ""); cat("\n"); return(list(factor = data.frame(y), size = list(optimal.width = width, optimal.height = height))) }
heat_restriction <- function(x,model, nh,total=TRUE){ if (model=="utah"){ y <- utah_model(x, total = F) } if (model=="nc"){ y <- north_carolina(x, total=F) } z <- y z[which(z>=0)] <- 0 z[which(z<0)] <- 1 for(i in nh:length(z)){ if(sum(z[(1+i-nh):i])==nh) y[i] <- 0 } if (total==TRUE) return(tail(cumsum(y),n=1)) else return(y) }
`sqliteSGP` <- function(sgp_object, state=NULL, years=NULL, content_areas=NULL, other.student.groups, text.output=TRUE, json.output=TRUE, null.output.string=NULL, projection.years.for.target=3, output.directory=file.path("Data", "SchoolView")) { started.at <- proc.time() message(paste("\tStarted sqliteSGP in outputSGP", prettyDate())) YEAR <- DISTRICT_NUMBER <- SCHOOL_NUMBER <- CONTENT_AREA <- DISTRICT_ENROLLMENT_STATUS <- GRADE <- ETHNICITY <- STUDENTGROUP <- SCHOOL_ENROLLMENT_STATUS <- EMH_LEVEL <- MEDIAN_SGP <- NULL INSTRUCTOR_NUMBER <- INSTRUCTOR_ENROLLMENT_STATUS <- TMP_ID <- NULL if (is.null(state)) { tmp.name <- toupper(gsub("_", " ", deparse(substitute(sgp_object)))) state <- getStateAbbreviation(tmp.name, "sqliteSGP") } if (!is.null(SGP::SGPstateData[[state]][["SGP_Configuration"]][["output.groups"]])) { output.groups <- SGP::SGPstateData[[state]][["SGP_Configuration"]][["output.groups"]] } else { output.groups <- c("DISTRICT", "SCHOOL") } group.number <- paste(output.groups, "NUMBER", sep="_") group.enroll.status <- paste(output.groups, "ENROLLMENT_STATUS", sep="_") group.enroll.status.label <- paste0("Enrolled ", sapply(output.groups, capwords), ": Yes") if (state %in% c(datasets::state.abb, "DEMO")) { tmp.state <- gsub(" ", "_", c(datasets::state.name, "Demonstration")[state==c(datasets::state.abb, "DEMO")]) } else { tmp.state <- gsub(" ", "_", state) } sqlite.output.directory <- file.path(output.directory, "SQLITE") dir.create(sqlite.output.directory, recursive=TRUE, showWarnings=FALSE) if (file.exists(file.path(sqlite.output.directory, paste0(tmp.state, "_Data_SQLITE.sqlite")))) file.remove(file.path(sqlite.output.directory, paste0(tmp.state, "_Data_SQLITE.sqlite"))) db <- dbConnect(SQLite(), dbname=file.path(sqlite.output.directory, paste0(tmp.state, "_Data_SQLITE.sqlite"))) if (text.output) { text.output.directory <- file.path(output.directory, "TEXT") dir.create(text.output.directory, recursive=TRUE, showWarnings=FALSE) } if (json.output) { json.output.directory <- file.path(output.directory, "JSON") dir.create(json.output.directory, recursive=TRUE, showWarnings=FALSE) } strtail <- function(s, n=1) { if (n < 0) substring(s, 1-n) else substring(s, nchar(s)-n+1) } strhead <- function(s,n=1) { if (n < 0) substr(s, 1, nchar(s)+n) else substr(s, 1, n) } sqlite.create.table <- function(table.name, field.types, primary.key) { tmp.sql <- paste0("CREATE TABLE ", table.name, " (", paste(field.types, collapse=", "), ", PRIMARY KEY (", paste(primary.key, collapse=", "), "))") return(tmp.sql) } "%w/o%" <- function(x, y) x[!x %in% y] convert.variables <- function(tmp.df, factor.variables=NULL) { if (length(grep("_", tmp.df$YEAR)) > 0) { tmp.df$YEAR <- sapply(strsplit(tmp.df$YEAR, "_"), '[', 2) } if (is.character(tmp.df$CONTENT_AREA)) { tmp.df$CONTENT_AREA <- as.factor(tmp.df$CONTENT_AREA) } tmp.factor.names <- c(factor.variables, names(tmp.df)[sapply(tmp.df, class)=="factor"] %w/o% c(group.number[2], group.number[1], "INSTRUCTOR_NUMBER")) for (i in tmp.factor.names) { tmp.df[[i]] <- unclass(as.factor(tmp.df[[i]])) } tmp.df[sapply(tmp.df, is.nan)] <- NA return(tmp.df) } get.grade <- function(grade) { if (SGP::SGPstateData[[state]][["Assessment_Program_Information"]][["Test_Season"]]=="Fall") grade-1 else grade } get.year <- function(year) { if (SGP::SGPstateData[[state]][["Assessment_Program_Information"]][["Test_Season"]]=="Fall") { yearIncrement(year, -1) } else { return(year) } } convert.names <- function(my.data) { names(my.data)[names(my.data)=="PERCENT_CATCHING_UP_KEEPING_UP"] <- "PERCENT_AT_ABOVE_TARGET" names(my.data)[names(my.data)==paste("MEDIAN_SGP_TARGET", projection.years.for.target, "YEAR", sep="_")] <- "MEDIAN_SGP_TARGET" if ("EMH_LEVEL" %in% names(my.data) && is.numeric(my.data[['EMH_LEVEL']])) { my.data[['EMH_LEVEL']] <- as.character(factor(my.data[['EMH_LEVEL']], levels=1:3, labels=c("E", "H", "M"))) } if ("EMH_LEVEL" %in% names(my.data) && is.character(my.data[['EMH_LEVEL']])) { my.data[['EMH_LEVEL']] <- substr(my.data[['EMH_LEVEL']],1,1) } if ("GENDER" %in% names(my.data)) { my.data[['STUDENTGROUP']][my.data[['STUDENTGROUP']]=="Female"] <- "F" my.data[['STUDENTGROUP']][my.data[['STUDENTGROUP']]=="Male"] <- "M" } if ("INSTRUCTOR_NUMBER" %in% names(my.data)) names(my.data)[names(my.data)=="INSTRUCTOR_NUMBER"] <- "TEACHER_USID" if (group.number[1]!="DISTRICT") names(my.data)[names(my.data)==group.number[1]] <- "DISTRICT_NUMBER" if (group.number[2]!="SCHOOL") names(my.data)[names(my.data)==group.number[2]] <- "SCHOOL_NUMBER" return(my.data) } if (is.null(years)) years <- unique(sgp_object@Data[['YEAR']]) %w/o% NA if (is.null(content_areas)) content_areas <- unique(sgp_object@Data[['CONTENT_AREA']]) %w/o% NA if (!is.null(SGP::SGPstateData[[state]][["SGP_Configuration"]][["null.output.string"]])) { my.null.string <- SGP::SGPstateData[[state]][["SGP_Configuration"]][["null.output.string"]] } else { my.null.string <- "NULL" } setkeyv(sgp_object@Data, c("YEAR", group.number[1], group.number[2])) tmp.school.and.district.by.year <- as.data.frame(convert.variables(unique(sgp_object@Data, by=key(sgp_object@Data))[, c("YEAR", group.number[1], group.number[2]), with=FALSE])) field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER") tmp <- as.data.frame(convert.variables(subset(sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR", group.enroll.status[1], sep="__")]], !is.na(get(group.number[1])) & CONTENT_AREA %in% content_areas & YEAR %in% years & get(group.enroll.status[1])==group.enroll.status.label[1] & !is.na(MEDIAN_SGP)))) tmp <- convert.names(tmp) tmp <- tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))] dbGetQuery(db, sqlite.create.table("DISTRICT", field.types, c("YEAR", "DISTRICT_NUMBER", "CONTENT_AREA"))) dbWriteTable(db, "DISTRICT", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "DISTRICT.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "DISTRICT.json")) field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "GRADE INTEGER NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER") tmp <- as.data.frame(convert.variables(subset(sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR__GRADE", group.enroll.status[1], sep="__")]], !is.na(get(group.number[1])) & CONTENT_AREA %in% content_areas & YEAR %in% years & !is.na(GRADE) & get(group.enroll.status[1])==group.enroll.status.label[1] & !is.na(MEDIAN_SGP)))) tmp <- convert.names(tmp) tmp <- tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))] dbGetQuery(db, sqlite.create.table("DISTRICT_GRADE", field.types, c("YEAR", "DISTRICT_NUMBER", "CONTENT_AREA", "GRADE"))) dbWriteTable(db, "DISTRICT_GRADE", tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))], row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "DISTRICT_GRADE.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "DISTRICT_GRADE.json")) field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "ETHNICITY INTEGER NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER", "ENROLLMENT_PERCENTAGE REAL") tmp <- as.data.frame(convert.variables(subset(sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR__ETHNICITY", group.enroll.status[1], sep="__")]], !is.na(get(group.number[1])) & CONTENT_AREA %in% content_areas & YEAR %in% years & !is.na(ETHNICITY) & get(group.enroll.status[1])==group.enroll.status.label[1] & !is.na(MEDIAN_SGP)), factor.variables="ETHNICITY")) tmp <- convert.names(tmp) tmp$ENROLLMENT_PERCENTAGE <- NA tmp <- tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))] dbGetQuery(db, sqlite.create.table("DISTRICT_ETHNICITY", field.types, c("YEAR", "DISTRICT_NUMBER", "CONTENT_AREA", "ETHNICITY"))) dbWriteTable(db, "DISTRICT_ETHNICITY", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "DISTRICT_ETHNICITY.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "DISTRICT_ETHNICITY.json")) field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "GRADE TEXT NOT NULL", "ETHNICITY TEXT NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER") tmp <- as.data.frame(convert.variables(subset(sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR__GRADE__ETHNICITY", group.enroll.status[1], sep="__")]], !is.na(get(group.number[1])) & CONTENT_AREA %in% content_areas & YEAR %in% years & !is.na(GRADE) & !is.na(ETHNICITY) & get(group.enroll.status[1])==group.enroll.status.label[1] & !is.na(MEDIAN_SGP)), factor.variables="ETHNICITY")) tmp <- convert.names(tmp) tmp <- tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))] dbGetQuery(db, sqlite.create.table("DISTRICT_GRADE_ETHNICITY", field.types, c("YEAR", "DISTRICT_NUMBER", "CONTENT_AREA", "GRADE", "ETHNICITY"))) dbWriteTable(db, "DISTRICT_GRADE_ETHNICITY", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "DISTRICT_GRADE_ETHNICITY.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "DISTRICT_GRADE_ETHNICITY.json")) field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "STUDENTGROUP TEXT NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER", "ENROLLMENT_PERCENTAGE REAL") tmp.list <- list() for (i in other.student.groups %w/o% grep("ETHNICITY", other.student.groups, value=TRUE)) { tmp.list[[i]] <- sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR", i, group.enroll.status[1], sep="__")]] } for (i in seq_along(tmp.list)) { setnames(tmp.list[[i]], 4, "STUDENTGROUP") } tmp <- as.data.frame(convert.variables(subset(rbindlist(tmp.list, fill=TRUE), !is.na(get(group.number[1])) & CONTENT_AREA %in% content_areas & YEAR %in% years & !is.na(STUDENTGROUP) & get(group.enroll.status[1])==group.enroll.status.label[1] & !is.na(MEDIAN_SGP)), factor.variables="STUDENTGROUP")) tmp <- convert.names(tmp) tmp$ENROLLMENT_PERCENTAGE <- NA tmp <- data.table(tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))], key=c("YEAR", "DISTRICT_NUMBER", "CONTENT_AREA", "STUDENTGROUP")) tmp <- as.data.frame(data.table(tmp[!duplicated(tmp, by=key(tmp))])) dbGetQuery(db, sqlite.create.table("DISTRICT_STUDENTGROUP", field.types, c("YEAR", "DISTRICT_NUMBER", "CONTENT_AREA", "STUDENTGROUP"))) dbWriteTable(db, "DISTRICT_STUDENTGROUP", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "DISTRICT_STUDENTGROUP.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "DISTRICT_STUDENTGROUP.json")) field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "GRADE TEXT NOT NULL", "STUDENTGROUP TEXT NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER") tmp.list <- list() for (i in other.student.groups %w/o% grep("ETHNICITY", other.student.groups, value=TRUE)) { tmp.list[[i]] <- sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR__GRADE", i, group.enroll.status[1], sep="__")]] } for (i in seq_along(tmp.list)) { setnames(tmp.list[[i]], 5, "STUDENTGROUP") } tmp <- as.data.frame(convert.variables(subset(rbindlist(tmp.list, fill=TRUE), !is.na(get(group.number[1])) & YEAR %in% years & CONTENT_AREA %in% content_areas & !is.na(STUDENTGROUP) & get(group.enroll.status[1])==group.enroll.status.label[1] & !is.na(MEDIAN_SGP)), factor.variables="STUDENTGROUP")) tmp <- convert.names(tmp) tmp <- data.table(tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))], key=c("YEAR", "DISTRICT_NUMBER", "CONTENT_AREA", "GRADE", "STUDENTGROUP")) tmp <- as.data.frame(tmp[!duplicated(tmp, by=key(tmp))]) dbGetQuery(db, sqlite.create.table("DISTRICT_GRADE_STUDENTGROUP", field.types, c("YEAR", "DISTRICT_NUMBER", "CONTENT_AREA", "GRADE", "STUDENTGROUP"))) dbWriteTable(db, "DISTRICT_GRADE_STUDENTGROUP", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "DISTRICT_GRADE_STUDENTGROUP.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "DISTRICT_GRADE_STUDENTGROUP.json")) field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "SCHOOL_NUMBER TEXT NOT NULL", "EMH_LEVEL TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER") tmp <- as.data.frame(convert.variables(subset(sgp_object@Summary[[group.number[2]]][[paste(group.number[2], "EMH_LEVEL__CONTENT_AREA__YEAR", group.enroll.status[2], sep="__")]], !is.na(get(group.enroll.status[2])) & !is.na(get(group.number[2])) & !is.na(EMH_LEVEL) & CONTENT_AREA %in% content_areas & YEAR %in% years & get(group.enroll.status[2])==group.enroll.status.label[2] & !is.na(MEDIAN_SGP)))) tmp <- as.data.frame(merge(tmp, as.data.frame(tmp.school.and.district.by.year), all.x=TRUE)) tmp <- convert.names(tmp) tmp <- tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))] dbGetQuery(db, sqlite.create.table("SCHOOL", field.types, c("YEAR", "DISTRICT_NUMBER", "SCHOOL_NUMBER", "EMH_LEVEL", "CONTENT_AREA"))) dbWriteTable(db, "SCHOOL", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "SCHOOL.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "SCHOOL.json")) field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "SCHOOL_NUMBER TEXT NOT NULL", "EMH_LEVEL TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "GRADE TEXT NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER") tmp <- as.data.frame(convert.variables(subset(sgp_object@Summary[[group.number[2]]][[paste(group.number[2], "EMH_LEVEL__CONTENT_AREA__YEAR__GRADE", group.enroll.status[2], sep="__")]], !is.na(get(group.number[2])) & !is.na(EMH_LEVEL) & CONTENT_AREA %in% content_areas & YEAR %in% years & !is.na(GRADE) & get(group.enroll.status[2])==group.enroll.status.label[2] & !is.na(MEDIAN_SGP)))) tmp <- data.frame(merge(tmp, as.data.frame(tmp.school.and.district.by.year), all.x=TRUE)) tmp <- convert.names(tmp) tmp <- tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))] dbGetQuery(db, sqlite.create.table("SCHOOL_GRADE", field.types, c("YEAR", "DISTRICT_NUMBER", "SCHOOL_NUMBER", "EMH_LEVEL", "GRADE", "CONTENT_AREA"))) dbWriteTable(db, "SCHOOL_GRADE", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "SCHOOL_GRADE.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "SCHOOL_GRADE.json")) field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "SCHOOL_NUMBER TEXT NOT NULL", "EMH_LEVEL TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "ETHNICITY TEXT NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER", "ENROLLMENT_PERCENTAGE REAL") tmp <- as.data.frame(convert.variables(subset(sgp_object@Summary[[group.number[2]]][[paste(group.number[2], "EMH_LEVEL__CONTENT_AREA__YEAR__ETHNICITY", group.enroll.status[2], sep="__")]], !is.na(get(group.number[2])) & !is.na(EMH_LEVEL) & CONTENT_AREA %in% content_areas & YEAR %in% years & !is.na(ETHNICITY) & get(group.enroll.status[2])==group.enroll.status.label[2] & !is.na(MEDIAN_SGP)), factor.variables="ETHNICITY")) tmp <- data.frame(merge(tmp, as.data.frame(tmp.school.and.district.by.year), all.x=TRUE)) tmp <- convert.names(tmp) tmp$ENROLLMENT_PERCENTAGE <- NA tmp <- tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))] dbGetQuery(db, sqlite.create.table("SCHOOL_ETHNICITY", field.types, c("YEAR", "DISTRICT_NUMBER", "SCHOOL_NUMBER", "EMH_LEVEL", "CONTENT_AREA", "ETHNICITY"))) dbWriteTable(db, "SCHOOL_ETHNICITY", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "SCHOOL_ETHNICITY.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "SCHOOL_ETHNICITY.json")) field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "SCHOOL_NUMBER TEXT NOT NULL", "EMH_LEVEL TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "STUDENTGROUP TEXT NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER", "ENROLLMENT_PERCENTAGE REAL") tmp.list <- list() for (i in other.student.groups %w/o% grep("ETHNICITY", other.student.groups, value=TRUE)) { tmp.list[[i]] <- sgp_object@Summary[[group.number[2]]][[paste(group.number[2], "EMH_LEVEL__CONTENT_AREA__YEAR", i, group.enroll.status[2], sep="__")]] } for (i in seq_along(tmp.list)) { setnames(tmp.list[[i]], 5, "STUDENTGROUP") } tmp <- as.data.frame(convert.variables(subset(rbindlist(tmp.list, fill=TRUE), !is.na(get(group.number[2])) & !is.na(EMH_LEVEL) & CONTENT_AREA %in% content_areas & YEAR %in% years & !is.na(STUDENTGROUP) & get(group.enroll.status[2])==group.enroll.status.label[2] & !is.na(MEDIAN_SGP)), factor.variables="STUDENTGROUP")) tmp <- as.data.frame(merge(tmp, as.data.frame(tmp.school.and.district.by.year), all.x=TRUE)) tmp <- convert.names(tmp) tmp$ENROLLMENT_PERCENTAGE <- NA tmp <- data.table(tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))], key=c("YEAR", "DISTRICT_NUMBER", "SCHOOL_NUMBER", "EMH_LEVEL", "CONTENT_AREA", "STUDENTGROUP")) tmp <- as.data.frame(tmp[!duplicated(tmp, by=key(tmp))]) dbGetQuery(db, sqlite.create.table("SCHOOL_STUDENTGROUP", field.types, c("YEAR", "DISTRICT_NUMBER", "SCHOOL_NUMBER", "EMH_LEVEL", "CONTENT_AREA", "STUDENTGROUP"))) dbWriteTable(db, "SCHOOL_STUDENTGROUP", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "SCHOOL_STUDENTGROUP.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "SCHOOL_STUDENTGROUP.json")) if (any(c(paste(group.number[2], "INSTRUCTOR_NUMBER__EMH_LEVEL__CONTENT_AREA__YEAR", sep="__"), paste(group.number[2], "INSTRUCTOR_NUMBER__EMH_LEVEL__CONTENT_AREA__YEAR__INSTRUCTOR_ENROLLMENT_STATUS", sep="__")) %in% names(sgp_object@Summary[[group.number[2]]]))) { field.types <- c( "DISTRICT_NUMBER TEXT NOT NULL", "SCHOOL_NUMBER TEXT NOT NULL", "EMH_LEVEL TEXT NOT NULL", "TEACHER_USID TEXT NOT NULL", "CONTENT_AREA TEXT NOT NULL", "YEAR INTEGER NOT NULL", "MEDIAN_SGP REAL", "MEDIAN_SGP_TARGET REAL", "PERCENT_AT_ABOVE_TARGET REAL", "PERCENT_AT_ABOVE_PROFICIENT REAL", "MEDIAN_SGP_COUNT INTEGER", "PERCENT_AT_ABOVE_PROFICIENT_COUNT INTEGER") if (paste(group.number[2], "INSTRUCTOR_NUMBER__EMH_LEVEL__CONTENT_AREA__YEAR__INSTRUCTOR_ENROLLMENT_STATUS", sep="__") %in% names(sgp_object@Summary[[group.number[2]]])) { tmp.table.name <- paste(group.number[2], "INSTRUCTOR_NUMBER__EMH_LEVEL__CONTENT_AREA__YEAR__INSTRUCTOR_ENROLLMENT_STATUS", sep="__") tmp <- as.data.frame(convert.variables(subset(sgp_object@Summary[[group.number[2]]][[tmp.table.name]], !is.na(get(group.number[2])) & !is.na(INSTRUCTOR_NUMBER) & !is.na(EMH_LEVEL) & CONTENT_AREA %in% content_areas & YEAR %in% years & INSTRUCTOR_ENROLLMENT_STATUS=="Enrolled Instructor: Yes" & !is.na(MEDIAN_SGP)))) } else { tmp.table.name <- paste(group.number[2], "INSTRUCTOR_NUMBER__EMH_LEVEL__CONTENT_AREA__YEAR", sep="__") tmp <- as.data.frame(convert.variables(subset(sgp_object@Summary[[group.number[2]]][[tmp.table.name]], !is.na(get(group.number[2])) & !is.na(INSTRUCTOR_NUMBER) & !is.na(EMH_LEVEL) & CONTENT_AREA %in% content_areas & YEAR %in% years & !is.na(MEDIAN_SGP)))) } tmp <- data.frame(merge(tmp, as.data.frame(tmp.school.and.district.by.year), all.x=TRUE)) tmp <- convert.names(tmp) tmp <- tmp[, sapply(strsplit(field.types, " "), function(x) head(x,1))] dbGetQuery(db, sqlite.create.table("SCHOOL_TEACHER", field.types, c("YEAR", "DISTRICT_NUMBER", "SCHOOL_NUMBER", "TEACHER_USID", "EMH_LEVEL", "CONTENT_AREA"))) dbWriteTable(db, "SCHOOL_TEACHER", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "SCHOOL_TEACHER.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "SCHOOL_TEACHER.json")) } field.types <- c( "KEY_VALUE_ID INTEGER NOT NULL", "KEY_VALUE_KEY TEXT", "KEY_VALUE_CODE TEXT", "KEY_VALUE_TEXT TEXT") tmp <- subset(sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR", group.enroll.status[1], sep="__")]], !is.na(get(group.number[1])) & CONTENT_AREA %in% content_areas & YEAR %in% years & get(group.enroll.status[1])==group.enroll.status.label[1]) tmp.CONTENT_AREA <- data.frame( KEY_VALUE_KEY="CONTENT_AREA", KEY_VALUE_CODE=seq_along(unique(tmp[['CONTENT_AREA']])), KEY_VALUE_TEXT=sapply(sort(unique(tmp[['CONTENT_AREA']])), capwords)) tmp <- convert.variables(subset(sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR", group.enroll.status[1], sep="__")]], !is.na(get(group.number[1])) & CONTENT_AREA %in% content_areas & YEAR %in% years & get(group.enroll.status[1])==group.enroll.status.label[1])) tmp.YEAR <- data.frame( KEY_VALUE_KEY="YEAR", KEY_VALUE_CODE=sort(unique(tmp[['YEAR']])), KEY_VALUE_TEXT=paste0(as.numeric(sapply(sort(unique(tmp[['YEAR']])), get.year))-1, "-", sapply(sort(unique(tmp[['YEAR']])), get.year))) tmp <- subset(as.data.frame(sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR__GRADE", group.enroll.status[1], sep="__")]]), !is.na(get(group.number[1])) & CONTENT_AREA %in% content_areas & YEAR %in% years & !is.na(GRADE) & get(group.enroll.status[1])==group.enroll.status.label[1]) tmp.GRADE <- data.frame( KEY_VALUE_KEY="GRADE", KEY_VALUE_CODE=sort(unique(as.integer(tmp[['GRADE']]))), KEY_VALUE_TEXT=paste("Grade", get.grade(sort(unique(as.integer(tmp[['GRADE']])))))) tmp <- subset(sgp_object@Summary[[group.number[2]]][[paste(group.number[2], "EMH_LEVEL__CONTENT_AREA__YEAR", group.enroll.status[2], sep="__")]], !is.na(get(group.number[2])) & !is.na(EMH_LEVEL) & CONTENT_AREA %in% content_areas & YEAR %in% years & get(group.enroll.status[2])==group.enroll.status.label[2]) if (!is.factor(tmp$EMH_LEVEL)) tmp[['EMH_LEVEL']] <- as.factor(tmp[['EMH_LEVEL']]) tmp.EMH <- data.frame( KEY_VALUE_KEY="EMH_LEVEL", KEY_VALUE_CODE=strhead(levels(as.factor(tmp$EMH_LEVEL))[sort(unique(as.integer(as.factor(tmp[['EMH_LEVEL']]))))], 1), KEY_VALUE_TEXT= levels(as.factor(tmp$EMH_LEVEL))[sort(unique(as.integer(as.factor(tmp[['EMH_LEVEL']]))))]) tmp <- subset(as.data.frame(sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR__ETHNICITY", group.enroll.status[1], sep="__")]]), !is.na(get(group.number[1])) & CONTENT_AREA %in% content_areas & YEAR %in% years & !is.na(ETHNICITY) & get(group.enroll.status[1])==group.enroll.status.label[1]) tmp.ETHNICITY <- data.frame( KEY_VALUE_KEY="ETHNICITY", KEY_VALUE_CODE=sort(unique(as.integer(as.factor(tmp[['ETHNICITY']])))), KEY_VALUE_TEXT=levels(as.factor(tmp$ETHNICITY))[sort(unique(as.integer(as.factor(tmp[['ETHNICITY']]))))]) tmp.list <- list() for (i in other.student.groups %w/o% grep("ETHNICITY", other.student.groups, value=TRUE)) { tmp.list[[i]] <- sgp_object@Summary[[group.number[1]]][[paste(group.number[1], "CONTENT_AREA__YEAR", i, group.enroll.status[1], sep="__")]] } for (i in seq_along(tmp.list)) { setnames(tmp.list[[i]], 4, "STUDENTGROUP") } tmp <- data.table(convert.names(convert.variables(subset(rbindlist(tmp.list, fill=TRUE), !is.na(get(group.number[1])) & !is.na(STUDENTGROUP) & get(group.enroll.status[1])==group.enroll.status.label[1]))), key=c("YEAR", "DISTRICT_NUMBER", "CONTENT_AREA", "STUDENTGROUP")) tmp <- as.data.frame(data.table(tmp[!duplicated(tmp, by=key(tmp))])) tmp.STUDENTGROUP <- data.frame( KEY_VALUE_KEY="STUDENT_GROUP", KEY_VALUE_CODE=sort(unique(as.integer(as.factor(tmp[['STUDENTGROUP']])))), KEY_VALUE_TEXT=levels(as.factor(tmp$STUDENTGROUP))[sort(unique(as.integer(as.factor(tmp[['STUDENTGROUP']]))))]) tmp <- rbind(tmp.CONTENT_AREA, tmp.YEAR, tmp.GRADE, tmp.EMH, tmp.ETHNICITY, tmp.STUDENTGROUP) tmp <- data.frame(KEY_VALUE_ID=1:dim(tmp)[1], tmp) dbGetQuery(db, sqlite.create.table("KEY_VALUE_LOOKUP", field.types, "KEY_VALUE_ID")) dbWriteTable(db, "KEY_VALUE_LOOKUP", tmp, row.names=FALSE, append=TRUE) if (text.output) write.table(tmp, file=file.path(text.output.directory, "KEY_VALUE_LOOKUP.dat"), row.names=FALSE, na=my.null.string, quote=FALSE, sep="|") if (json.output) cat(toJSON(tmp), file=file.path(json.output.directory, "KEY_VALUE_LOOKUP.json")) dbDisconnect(db) message(paste("\tFinished sqliteSGP in outputSGP", prettyDate(), "in", convertTime(timetakenSGP(started.at)), "\n")) }
mc_initial_values <- function(linear_pred, matrix_pred, link, variance, covariance, offset, Ntrial, contrasts = NULL, data) { n_resp <- length(linear_pred) if (!is.null(contrasts)) { list_X <- list() for (i in 1:n_resp) { list_X[[i]] <- model.matrix(linear_pred[[i]], contrasts = contrasts[[i]], data = data) } } else { list_X <- lapply(linear_pred, model.matrix, data = data) } list_models <- list() power_initial <- list() for (i in 1:n_resp) { if (variance[[i]] == "constant") { power_initial[[i]] <- 0 if (!is.null(offset[[i]])) { data_temp <- data data_temp$offset <- offset[[i]] list_models[[i]] <- glm(linear_pred[[i]], family = quasi(link = link[[i]], variance = "constant"), offset = offset, data = data_temp) } else { list_models[[i]] <- glm(linear_pred[[i]], family = quasi(link = link[[i]], variance = "constant"), data = data) } } if (variance[[i]] == "tweedie" | variance[[i]] == "poisson_tweedie" | variance[[i]] == "geom_tweedie") { power_initial[[i]] <- 1 if (!is.null(offset[[i]])) { data_temp <- data data_temp$offset <- offset[[i]] list_models[[i]] <- glm(linear_pred[[i]], family = quasi(link = link[[i]], variance = "mu"), offset = offset, data = data_temp) } else { list_models[[i]] <- glm(linear_pred[[i]], family = quasi(link = link[[i]], variance = "mu"), data = data) } } if (variance[[i]] == "binomialP" | variance[[i]] == "binomialPQ") { power_initial[[i]] <- c(1) if (variance[[i]] == "binomialPQ") { power_initial[[i]] <- c(1, 1) } if (!is.null(Ntrial[[i]])) { temp <- model.frame(linear_pred[[i]], data = data) Y <- model.response(temp) * Ntrial[[i]] resp <- cbind(Y, Ntrial[[i]] - Y) X <- model.matrix(linear_pred[[i]], data = data) link_temp <- link[[i]] if (link_temp == "loglog") { link_temp <- "cloglog" } list_models[[i]] <- glm(resp ~ X - 1, family = binomial(link = link_temp), data = data) } else { link_temp <- link[[i]] if (link_temp == "loglog") { link_temp <- "cloglog" } list_models[[i]] <- glm(linear_pred[[i]], family = quasi(link = link_temp, variance = "mu(1-mu)"), data = data) } } } list_initial <- list() list_initial$regression <- lapply(list_models, coef) list_initial$power <- power_initial tau0_initial <- lapply(list_models, function(x) summary(x)$dispersion) tau_extra <- lapply(matrix_pred, length) list_initial$tau <- list() for (i in 1:n_resp) { if (covariance[i] == "identity") { list_initial$tau[[i]] <- as.numeric(c(tau0_initial[[i]], rep(0, c(tau_extra[[i]] - 1)))) } if (covariance[i] == "inverse") { list_initial$tau[[i]] <- as.numeric(c(1/tau0_initial[[i]], rep(0, c(tau_extra[[i]] - 1)))) } if (covariance[i] == "expm") { list_initial$tau[[i]] <- as.numeric(c(log(tau0_initial[[i]]), rep(0.1, c(tau_extra[[i]] - 1)))) } } if (n_resp == 1) { list_initial$rho <- 0 } else { list_initial$rho <- rep(0, n_resp * (n_resp - 1)/2) } return(list_initial) }
CreateOutliersPlot <- function(fObj, optns = NULL, ...){ fObjClass <- class(fObj) if( !(fObjClass %in% c('FSVD','FPCA')) ){ stop("CreateOutliersPlot() expects an FPCA or an FSVD object as input.") } newOptns <- CheckAndCreateCOPoptions(optns,fObjClass); nSlices = newOptns$nSlices; ifactor = newOptns$ifactor; colFunc = newOptns$colFunc; fIndices = newOptns$fIndeces; variant = newOptns$variant; groupingType = newOptns$groupingType; unimodal = newOptns$unimodal; outlierList = newOptns$outlierList; maxVar = newOptns$maxVar; showSlices = newOptns$showSlices fVarAlls <- c(); if(fObjClass == 'FPCA'){ fVarAlls <- fObj$lambda } else { fVarAlls <- (fObj$sValues)^2 } if(fIndices[2] > length(fVarAlls)){ stop("You requested a mode of variation that is not available.") } fScores1 <- fScores2 <- c(); if(fObjClass == 'FPCA'){ fScores1 <- fObj$xiEst[,fIndices[1]] fScores2 <- fObj$xiEst[,fIndices[2]] } else { fScores1 <- fObj$sScores1[,fIndices[1]] fScores2 <- fObj$sScores2[,fIndices[2]] } fScoresAll <- cbind(fScores1, fScores2) xedge = 1.05 * max( abs(fScores1)) yedge = 1.05 * max( abs(fScores2)) args1 <- list(); if(fObjClass == 'FSVD'){ args1 <- list( pch=10, xlab=paste('S1 FSC', fIndices[1] ,' scores ', sep='' ), ylab=paste('S2 FSC', fIndices[2] ,' scores ', sep='' ), xlim = c(-xedge, xedge), ylim =c(-yedge, yedge), lwd= 2) } else { args1 <- list( pch=10, xlab=paste('FPC', fIndices[1] ,' scores ', round(100* fObj$cumFVE[fIndices[1]]), '%', sep='' ), ylab=paste('FPC', fIndices[2] ,' scores ', round( diff( 100* fObj$cumFVE[c(fIndices[2]-1, fIndices[2])])), '%', sep='' ), xlim = c(-xedge, xedge), ylim =c(-yedge, yedge), lwd= 2) } inargs <- list(...) args1[names(inargs)] <- inargs nComp <- length(fVarAlls) if(nComp <2 ){ stop("This plotting utility function needs at least two functional components.") return(NULL) } if ( variant == 'bagplot' ){ if ( is.null((ifactor))){ ifactor = 2.58 } bgObj = aplpack::compute.bagplot(x= fScores1, y= fScores2, approx.limit=3333 , factor = ifactor) if(groupingType =='standard'){ args2 = list(x= fScores1, y= fScores2, cex= .33, type='n' ) do.call(plot, c(args2, args1)) points(x = fScores1, y = fScores2, cex= .33, panel.first = grid(), lwd= 2) lines( bgObj$hull.bag[c(1:nrow(bgObj$hull.bag),1),], col=2, lwd=2) lines( bgObj$hull.loop[c(1:nrow(bgObj$hull.loop),1),], col=4, lwd=2) legend(legend= c('0.500', 'The fence'), x='topright', col=c(2,4), lwd=2) return( invisible( list( 'bag' = match( apply(bgObj$pxy.bag,1, prod), apply( bgObj$xydata,1, prod)), 'loop'= match( apply(bgObj$pxy.outer,1, prod), apply( bgObj$xydata,1, prod)), 'outlier' = ifelse( is.null(bgObj$pxy.outlier), NA, match( apply(bgObj$pxy.outlier,1, prod) ,apply( bgObj$xydata,1, prod))) ) ) ) } else { N <- nrow(fScoresAll) kNNIndices95plus <- (1:N %in% match( apply(bgObj$pxy.outlier,1, prod) ,apply( bgObj$xydata,1, prod))) return( makeSlicePlot(nSlices, colFunc, p95plusInd = kNNIndices95plus, N, args1, scoreEsts = fScoresAll , varEsts = fVarAlls[fIndices], useDirOfMaxVar = maxVar, showSlices = showSlices) ) } } else if (variant == 'KDE') { if ( is.null((ifactor))){ ifactor = 2 } fhat <- ks::kde(x=fScoresAll, gridsize = c(400,400), compute.cont = TRUE, H = ks::Hpi( x=fScoresAll, binned=TRUE, pilot="dscalar" ) * ifactor) zin = fhat$estimate if( !is.null(unimodal) && unimodal ){ maxIndex = which( fhat$estimate == max(fhat$estimate), arr.ind = TRUE) zin = monotoniseMatrix( fhat$estimate, maxIndex[1], maxIndex[2]) } qq = quickNNeval(xin = fhat$eval.points[[1]], yin = fhat$eval.points[[2]], zin = zin, xout = fScores1, yout = fScores2 ) if(groupingType =='standard'){ args2 = list (x= fhat$eval.points[[1]], y=fhat$eval.points[[2]], z = zin, labcex=1.66, col= c('black','blue','red'), levels = fhat$cont[c(50, 95, 99)], labels = c('50%', '95%', '99%')) do.call(graphics::contour, c(args2, args1)); grid(col = " points(fScoresAll[qq <= fhat$cont[99], ],cex=0.5, col='orange', pch=10 , lwd =2 ) points(fScoresAll[qq > fhat$cont[99] & qq <= fhat$cont[95], ],cex=0.33, col='red', pch=10, lwd =2 ) points(fScoresAll[qq > fhat$cont[95] & qq <= fhat$cont[50], ],cex=0.33, col='blue', pch=10 , lwd =2 ) points(fScoresAll[qq >= fhat$cont[50], ],cex=0.33, col='black' , pch=10, lwd =2 ) legend('bottomleft', c('< 50%','50%-95%','95%-99%','> 99%'), pch = 19, col= c('black','blue','red', 'orange'), pt.cex=1.5, bg='white' ) return( invisible( list( 'p0to50'= which(qq >= fhat$cont[50]), 'p50to95' = which(qq > fhat$cont[95] & qq <= fhat$cont[50]), 'p95to99' = which(qq > fhat$cont[99] & qq <= fhat$cont[95]), 'p99plus' = which(qq <= fhat$cont[99]) ))) } else { kNNIndices95plus <- qq <= fhat$cont[95] return( makeSlicePlot(nSlices, colFunc, p95plusInd = kNNIndices95plus, N, args1, scoreEsts = fScoresAll , varEsts = fVarAlls[fIndices], useDirOfMaxVar = maxVar, showSlices = showSlices) ) } } else if (variant == 'NN') { centrePoint = c(0,0); distName = 'euclidean'; N <- nrow(fScoresAll) k99 <- floor(0.99*N); k95 <- floor(0.95*N); k50 <- floor(0.50*N); scaledXi <- apply(fScoresAll, 2, scale) distances <- apply(scaledXi, 1, function(aRow) dist(x = rbind(aRow, centrePoint), method = distName) ) kNNIndices0to99 <- sort(x = distances, index.return = TRUE)$ix[1:k99] kNNIndices0to50 <- kNNIndices0to99[1:k50] kNNIndices50to95 <- kNNIndices0to99[(1+k50):k95] kNNIndices95to99 <- kNNIndices0to99[(1+k95):k99] kNNIndices99plus <- setdiff(1:N, kNNIndices0to99) if(groupingType =='standard'){ args2 = list (x = fScores1, y = fScores2, cex= .33, type='n' ) do.call(plot, c(args2, args1)) grid(col = " points(fScoresAll[kNNIndices99plus,],cex=0.5, col='orange', pch=10 , lwd =2 ) points(fScoresAll[kNNIndices95to99,],cex=0.33, col='red', pch=10, lwd =2 ) points(fScoresAll[kNNIndices50to95,],cex=0.33, col='blue', pch=10 , lwd =2 ) points(fScoresAll[kNNIndices0to50, ],cex=0.33, col='black' , pch=10, lwd =2 ) legend('bottomleft', c('< 50%','50%-95%','95%-99%','> 99%'), pch = 19, col= c('black','blue','red', 'orange'), pt.cex=1.5, bg='white' ) return( invisible( list( 'p0to50'= kNNIndices0to50, 'p50to95' = kNNIndices50to95, 'p95to99' = kNNIndices95to99, 'p99plus' = kNNIndices99plus))) } else { kNNIndices95plus <- (1:N %in% setdiff(1:N, kNNIndices0to99[1:k95])) return( makeSlicePlot(nSlices, colFunc, p95plusInd = kNNIndices95plus, N, args1, scoreEsts = fScoresAll, varEsts = fVarAlls[fIndices], useDirOfMaxVar = maxVar, showSlices = showSlices) ) } } } makeSlicePlot <- function( nSlices, colFunc, p95plusInd, N, args1, args2, scoreEsts, varEsts, useDirOfMaxVar, showSlices){ kNNIndices95plus <- p95plusInd args2 = list (x = scoreEsts[,1], y = scoreEsts[,2], cex= .33, type='n' ) do.call(plot, c(args2, args1)) grid(col = " points(scoreEsts[!p95plusInd, ],cex=0.33, col='black' , pch=10, lwd =2 ) Qstr = apply(scoreEsts, 2, scale, center = FALSE) dirOfMaxVar <- c(1,0); if(useDirOfMaxVar){ dirOfMaxVar <- svd(scoreEsts, nv = 1)$v; if(all(dirOfMaxVar <0) ){ dirOfMaxVar = -dirOfMaxVar } abline(0, dirOfMaxVar[2]/dirOfMaxVar[1], col='magenta', lty=2) } colPal = colFunc( nSlices ) v = 1:nSlices; colPal = colPal[v] outlierList <- list() angles <- seq(0,2*pi, length.out = nSlices + 1) - 1*pi/nSlices + atan2(dirOfMaxVar[2],dirOfMaxVar[1]) sd1 = sd(scoreEsts[,1]); sd2 = sd(scoreEsts[,2]); for( i in 1:nSlices){ angle = angles[i] multiplier1 = sign( sin( angle + pi/2) ) multiplier2 = sign( cos( angle + pi/ (nSlices/2))) qrtIndx = multiplier1 * Qstr[,2] > multiplier1 * tan(angle) * Qstr[,1] & multiplier2 * Qstr[,2] < multiplier2 * tan(angle + pi/ (nSlices/2) ) * Qstr[,1] outlierList[[i]] = qrtIndx & kNNIndices95plus points(scoreEsts[ outlierList[[i]], c(1,2), drop=FALSE], cex=0.93, col= colPal[i], pch=3, lwd =2 ) if(showSlices){ bigNumber = 10 * max(abs(as.vector(scoreEsts))) lines(x = c(0, bigNumber * multiplier1), col=colPal[i], y = c(0, bigNumber * multiplier1 * tan(angle) * sd2 / sd1)) } } return( invisible( list( 'p0to95'= which(!p95plusInd), 'outlier' = sapply(outlierList, which), 'outlierColours' = colPal)) ) } quickNNeval <- function(xin,yin, zin, xout, yout){ xIndices = sapply( xout, function(myArg) which.min( abs( xin - myArg) ), simplify = TRUE) yIndices = sapply( yout, function(myArg) which.min( abs( yin - myArg) ), simplify = TRUE ) return( zin[ cbind(xIndices,yIndices)] ) } monotonise <- function(x, maxIndex = NULL){ xq = x; if (is.null(maxIndex)){ maxIndex = which.max(x); } if( maxIndex != length(x) ){ for (i in 1:( length(x) - maxIndex)){ if( xq[ i + maxIndex] > xq[maxIndex + i - 1] ){ xq[ i + maxIndex] = xq[maxIndex + i - 1] } } } if (maxIndex >= 3){ for (i in 1:(maxIndex - 2 )){ if( xq[ - 1 - i + maxIndex] > xq[maxIndex - i] ){ xq[ - 1- i + maxIndex] = xq[maxIndex - i] } } } return(xq) } monotoniseMatrix = function(zin, xmaxind, ymaxind){ if(is.null(xmaxind) && is.null(ymaxind)){ maxIndx = which( max(zin) == zin, arr.ind = TRUE) xmaxind = maxIndx[1] ymaxind = maxIndx[2] } zq = zin; for (j in 1:dim(zin)[2]){ for (i in 1:dim(zin)[1]){ if (i == 1 || j == 1 || j == dim(zin)[1] || i == dim(zin)[2]){ sizeOut = max( abs(xmaxind - i) +1, abs(ymaxind - j) +1 ) xcoord = round( ( seq(i, xmaxind , length.out = sizeOut) ) ) ycoord = round( ( seq(j, ymaxind , length.out = sizeOut) ) ) zq[ cbind(xcoord,ycoord) ] = monotonise( zq[ cbind(xcoord,ycoord) ]) } } } return(zq) }
context("Just testing localPoSpkNUCF functionality") test_that("Check whether localPoSpkNUCF works properly(Vector)",{ localspeFreq<-as.vector(LocalPoSpKNUCF_DNA(seqs="AAGAGCC",k=2)) expected<-c(1/2,1/3,1/4,2/5,1/6,1/7) expect_equal(localspeFreq,expected) }) test_that("Check whether localPoSpkaaF works properly(Matrix)",{ localspeFreq<-LocalPoSpKNUCF_DNA(seqs=c("AAGAGCC","ACCCACC"),k=2) expected<-rbind(c(1/2,1/3,1/4,2/5,1/6,1/7),c(1/2,1/3,2/4,1/5,2/6,3/7)) dimnames(localspeFreq)<-NULL dimnames(expected)<-NULL expect_equal(localspeFreq,expected) }) test_that("Check localPoSpkaaF for sequences with different length",{ expect_error(LocalPoSpKNUCF_DNA(seqs=c("AAGAGCC","ACC"),k=2)) }) test_that("Check whether localPoSpkNUCF works properly(Vector)",{ localspeFreq<-as.vector(LocalPoSpKNUCF_RNA(seqs="AAGAGCC",k=2)) expected<-c(1/2,1/3,1/4,2/5,1/6,1/7) expect_equal(localspeFreq,expected) })
xp.boot.par.est <- function (bootgam.obj = NULL, sd.norm = TRUE, by.cov.type = FALSE, abs.values = FALSE, show.data = TRUE, show.means = TRUE, show.bias = TRUE, dotpch = c(1,19), labels = NULL, pch.mean = "|", xlab = NULL, ylab = NULL, col = c(rgb(.8, .5, .5), rgb(.2, .2, .7), rgb(.2,.2,.7), rgb(.6,.6,.6)), ...) { boot.type <- "bootscm" bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } if (bootgam.obj$group.by.cov == TRUE) { cat ("This plot cannot be created when imported bootscm results are grouped by covariate.\nPlease re-import the bootscm results.") return() } if (!("par.est.first" %in% names(bootgam.obj))) { cat ("The required data is not available. Please check that all necessary PsN data was imported.\n") cat ("Note: If you've used the bootscm.import function, please set 'skip.par.est.import' to FALSE.\n\n") return(NULL) } if (is.null(xlab)) { xlab <- "Relative parameter estimate (from 1st scm-step)" } if (is.null(ylab)) { ylab <- "Covariate" } if (sd.norm == TRUE) { pl.dat <- bootgam.obj$par.est.long.norm bias.dat <- bootgam.obj$bias.dat.norm } else { pl.dat <- bootgam.obj$par.est.long bias.dat <- bootgam.obj$bias.dat } rem <- seq(along = bootgam.obj$results.tab[,1])[bootgam.obj$failed == 1] cleaned.data <- bootgam.obj$results.tab if (length(rem)>0) { cleaned.data <- cleaned.data[-rem,] } incl.freq <- apply (cleaned.data, 2, sum) lev.ord <- names(incl.freq)[order(incl.freq)] lev.ord <- unlist(sapply(lev.ord,function(x) levels(pl.dat$cov)[grep(x,levels(pl.dat$cov))]),use.names = F) abs.fun <- function (dat) {return(dat)} if (abs.values == TRUE) { abs.fun <- abs xlab <- paste("Absolute", xlab) } if (by.cov.type == TRUE) { formula <- factor(cov, levels=lev.ord) ~ abs.fun(value) | cov.type } else { formula <- factor(cov, levels=lev.ord) ~ abs.fun(value) } if (!is.null(labels)) { labels <- rev(labels) if (length(labels)==length(lev.ord)) { idx1 <- match(bias.dat$cov, lev.ord) idx2 <- match(names(incl.freq), lev.ord) idx3 <- match(pl.dat$cov, lev.ord) bias.dat$cov <- labels[idx1] names(incl.freq) <- labels[idx2] pl.dat$cov <- labels[idx3] lev.ord <- names(incl.freq)[order(incl.freq)] } else { cat ("Length of specified labels-vector not equal to number of covariate-parameter relationships. Returning to default.") } } legend <- list(text = list("Selected", cex=.75), points = list(pch=dotpch[2], col=col[3], cex=1), text = list("Not selected", cex=.75), points = list(pch=dotpch[1], col=col[1], cex=1) ) if (show.means == TRUE) { legend <- list(text = list("Selected", cex=.75), points = list(pch=dotpch[2], col=col[3], cex=1), text = list("Not selected", cex=.75), points = list(pch=dotpch[1], col=col[1], cex=1), text = list("mean (selected)", cex=.75), lines = list(lwd=1.5, span=0.1, col=col[3]), text = list("mean (all)", cex=.75), lines = list(lwd=1.5, span=0.1, col=col[4]) ) } p <- stripplot (formula, data = pl.dat, ylab = ylab, xlab = xlab, groups = factor(eval(as.name("incl")), levels = c("Not included", "Included")), par.settings = simpleTheme (col=col, pch=dotpch), key = legend, levels = lev.ord, panel = function (...) { panel.abline (v=0, lty=3) if (show.data == TRUE) { panel.stripplot (jitter.data=TRUE, ...) } if (show.means == TRUE) { panel.xyplot (y = factor(bias.dat[bias.dat$incl == "Included",]$cov, levels=lev.ord), x = abs.fun(as.num(bias.dat[bias.dat$incl == "Included",]$mean)), bias.data=bias.dat, pch = pch.mean, cex=2.5, col=col[3] ) panel.xyplot (y = factor(bias.dat[bias.dat$incl == "Included",]$cov, levels=lev.ord), x = abs.fun(as.num(bias.dat[bias.dat$incl == "Included",]$All)), bias.data=bias.dat, pch = pch.mean, cex=2.5, col=col[4] ) } if (show.bias == TRUE) { panel.text (y = factor(bias.dat[bias.dat$incl=="Included",]$cov, levels=lev.ord), x = abs.fun(max(pl.dat[!is.na(pl.dat$value),]$value)*0.94), labels = paste (round(bias.dat[bias.dat$incl=="Included",]$bias,0), "%", sep=""), cex=0.8) } }, ...) return(p) } ask.covs.plot <- function (bootgam.obj = NULL) { if (!is.null(bootgam.obj)) { cat ("Covariates in database: ") covs <- colnames(bootgam.obj$covariate$sd.all) cat (covs) cat ("\n\nPlot for which covariates (separate by space, return for all): ") ans <- readline() if (ans == "") { return() } ans.cov <- strsplit(ans, " ")[[1]] if (length(ans.cov) < 2) { cat("Please choose at least 2 covariatess from the list!\n\n") Recall(bootgam.obj) } else { if (sum((ans.cov %in% covs)*1) == length(ans.cov)) { return (ans.cov) } else { cat("Please choose covariates from the list only!\n\n") Recall(bootgam.obj) } } } } xp.boot.par.est.corr <- function (bootgam.obj = NULL, sd.norm = TRUE, by.cov.type = FALSE, cov.plot = NULL, ask.covs = FALSE, dotpch = 19, col = rgb(.2, .2, .9, .75), ...) { boot.type <- "bootscm" bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } if (bootgam.obj$group.by.cov == TRUE) { cat ("This plot cannot be created when imported bootscm results are grouped by covariate.\nPlease re-import the bootscm results.") return() } if (!("par.est.first" %in% names(bootgam.obj))) { cat ("The required data is not available. Please check that all necessary PsN data was imported.\n") cat ("Note: If you've used the bootscm.import function, please set 'skip.par.est.import' to FALSE.\n\n") return(NULL) } tmp <- bootgam.obj$par.est.first if (sd.norm == TRUE) { tmp <- bootgam.obj$par.est.first.corr xlab <- "Parameter estimate (from 1st scm-step), SD-normalized" } pl.dat <- tmp pl.dat.incl <- (!is.na(bootgam.obj$par.est.final))*1 if (is.null(cov.plot)) { if (ask.covs==TRUE) { cov.plot <- ask.covs.plot (bootgam.obj) } } if ((!is.null(cov.plot))&&(sum(cov.plot %in% colnames(tmp))>0)) { pl.dat <- tmp[,cov.plot] pl.dat.incl <- pl.dat.incl[,cov.plot] } p <- splom (pl.dat, pch = dotpch, col=col) return(p) } bootgam.print <- function(bootgam.obj = NULL) { bootgam.obj <- get.boot.obj(bootgam.obj, NULL) if (is.null(bootgam.obj)) { return() } boot.type <- get.boot.type (bootgam.obj) cat("\n********************************************************************\n") if (boot.type == "bootgam") { cat("************************* BootGAM results **************************\n") } else { cat("************************* BootSCM results **************************\n") } cat("Run number:", bootgam.obj$runno, "\n") failed <- NULL if (boot.type == "bootgam") { if(is.null(startm <- bootgam.obj$start.mod)) { cat("No start model specified.\n") } else { cat("Start model set to:", startm,"\n") } cat("Seed number:", bootgam.obj$seed,"\n") if(length(bootgam.obj$excluded.ids)>0) { cat("Excluded individuals:",bootgam.obj$excluded.ids,"\n") } else { cat("No individuals were excluded.\n") } cat("\nConvergence algorithm:", bootgam.obj$algo,"\n") if(bootgam.obj$algo == "fluct.ratio") { cat("Lowest important inclusion frequency:") cat("\n Convergence criterium:", format(bootgam.obj$fluct.ratio.last, digits = 5), "(target=", bootgam.obj$conv.value, ")\n") } else { cat("Lowest absolute joint inclusion frequency:") cat("\n Convergence criterium:", format(bootgam.obj$ljif.last, digits = 5), "(target=", bootgam.obj$ljif, ")\n") } failed <- seq(along=eval(as.name("current.bootgam"))$failed)[eval(as.name("current.bootgam"))$failed==1] cat ("Failed BootGAM replicates: ", failed, "\n") } cat("\nTotal number of iterations:", length(bootgam.obj$results.tab[,1]), "\n") cat("\nModel size: ") res <- bootgam.obj$results.tab if (!is.null(failed)) { if (length(failed)>0) { res <- bootgam.obj$results.tab[-failed,] } } print (summary(apply(res, 1, sum))) cat("\nInclusion probabilities:\n") tot.prob <- tail(bootgam.obj$incl.freq,1) ord <- rev(order(tot.prob)) print(t(as.list(round(tot.prob[ord],3)))) cat("********************************************************************\n\n") } check.bootgamobj <- function () { getit <- function() { cat("\nYou have to specify the parameter name and the run number", "of the bootgam objects you want to plot. The following", "bootgam objects are available:\n", fill = 60) if (.Platform$OS == "windows") { cat(objects(pattern = "bootgam.xpose*", pos = 1), fill = 60) } else { cat(objects(pattern = "^bootgam.xpose", pos = 1), fill = 60) } cat("\nParameter (0 to exit): ") ans <- readline() if (ans == 0) { return(ans <- NULL) } cat("Run number (0 to exit):") ans1 <- readline() if (ans1 == 0) { return(ans1 <- NULL) } gobjname <- paste("bootgam.xpose.", ans, ".", ans1, sep = "") if (!exists(gobjname, where = 1)) { cat("\n*There are no objects that matches", gobjname, "\n") gobjname <- Recall() } return(gobjname) } if (exists("current.bootgam", where = 1)) { cur.boot <- eval(as.name("current.bootgam")) cat("\nThe current bootgam object is for", cur.boot$parnam, "in run", cur.boot$runno, ".\n") cat("\nDo you want to proceed with this bootgam object? y(n) ") ans <- readline() if (ans != "y" && ans != "") { gobjname <- getit() if (!is.null(gobjname)) { c1 <- call("assign",pos = 1, "current.bootgam", eval(as.name(gobjname)), immediate = T) eval(c1) } } else { gobjname <- T } } else { gobjname <- getit() if (!is.null(gobjname)) { c2 <- call("assign",pos = 1, "current.bootgam", eval(as.name(gobjname)), immediate = T) eval(c2) } } return(gobjname) } ask.bootgam.bootscm.type <- function () { cat ("Both a bootgam and a bootscm object are available, which one\nwould you like to summarize?\n") cat (" 1) the current bootgam object\n") cat (" 2) the current bootscm object\n") ans <- readline() if (ans == "") { Recall() } else { if ((ans == 1)|(ans == 2)) { if (ans == 1) {return ("bootgam")} if (ans == 2) {return ("bootscm")} } else { cat("Please choose either 1 or 2!\n\n") Recall() } } } get.boot.obj <- function (bootgam.obj = NULL, boot.type = NULL ) { if ((is.null(boot.type))&(is.null(bootgam.obj))) { if (("current.bootgam" %in% ls(.GlobalEnv))&(!"current.bootscm" %in% ls(.GlobalEnv))) { boot.type <- "bootgam" } if (("current.bootscm" %in% ls(.GlobalEnv))&(!"current.bootgam" %in% ls(.GlobalEnv))) { boot.type <- "bootscm" } if (("current.bootscm" %in% ls(.GlobalEnv))&("current.bootgam" %in% ls(.GlobalEnv))) { boot.type <- ask.bootgam.bootscm.type() cat ("\n") } if (is.null(boot.type)) { cat ("No bootgam or bootscm object found!\n") return() } } if (is.null(boot.type)) { boot.type <- get.boot.type (bootgam.obj) } if (boot.type == "bootscm") { if (is.null(bootgam.obj)) { if ("current.bootscm" %in% objects(pos=1)) { if (!is.null(eval(as.name("current.bootscm")))) { bootgam.obj <- eval(as.name("current.bootscm")) } else { cat ("Data not available. Did you import the bootSCM data?\n") } } else { cat (paste(objects())) cat ("Data not available. Did you import the bootSCM data?\n") } } else { c3 <- call("assign",pos = 1, "current.bootscm", bootgam.obj, immediate = T) eval(c3) } } else { if (is.null(bootgam.obj)) { if ("current.bootgam" %in% objects()) { if (!is.null(bootgam.obj)) { bootgam.obj <- eval(as.name("current.bootgam")) } } else { if (check.bootgamobj()) { bootgam.obj <- eval(as.name("current.bootgam")) } else { cat ("Data not available. Did you run the bootGAM data?\n") } } } else { c4 <- call("assign",pos = 1, "current.bootgam", bootgam.obj, immediate = T) eval(c4) } } return(bootgam.obj) } xp.distr.mod.size <- function (bootgam.obj = NULL, boot.type = NULL, main = NULL, bw = 0.5, xlb = NULL, ... ) { bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } boot.type <- get.boot.type (bootgam.obj) if(is.null(main)) { main <- paste("Distribution of covariate model sizes", bootgam.obj$runno) } if (is.null(xlb)) { if (boot.type == "bootgam") { xlb <- paste ("Covariate model size (on", bootgam.obj$parnam, ")", sep = "") } else { xlb <- paste ("Covariate model size (on any parameter)") } } res <- bootgam.obj$results.tab if (!is.null(bootgam.obj$failed)) { res <- res[bootgam.obj$failed == 0,] } sizes <- apply (res, 1, sum) pl <- densityplot (sizes, bw = bw, main = main, ... ) return(pl) } ask.incl.range <- function (bootgam.obj = NULL) { text <- paste("The plots that show correlations between covariate inclusion\n", "frequencies (inclusion index) are not informative when the inclusion\n", "frequency for a covariate is either very high or very low. Therefore\n", "it is advised to show these plots only for intermediately strong \n", "covariates. The default range is 20% to 80%.\n\n", sep="") cat (text) cat ("Specify range (e.g.: 20 80): ") ans <- readline() if (ans == "") { range <- c(20,80) } else { range <- as.numeric(strsplit (ans, " ")[[1]]) } if (length(range) == 2) { return (range) } else { cat("Please specify two numbers, separated by a space!\n\n") Recall(bootgam.obj) } } xp.incl.index.cov <- function ( bootgam.obj = NULL, boot.type = NULL, main = NULL, xlb = "Index", ylb = "Covariate", add.ci = FALSE, incl.range = NULL, return_plot = TRUE, results.tab = NULL, ...) { bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } boot.type <- get.boot.type(bootgam.obj) as.num <- function(dat) { return(as.numeric(as.character(dat))) } if (is.null(main)) { main <- paste("Inclusion index for", bootgam.obj$runno) } se_idx <- function(p, q, n) { A <- (p/n) * (1 - (p/n))/n B <- (q/n) * (1 - (q/n))/n rho <- 1 se <- sqrt(A + B + 2 * sqrt(A) * sqrt(B) * rho) return(se) } inc_obs <- tail(bootgam.obj$incl.freq, 1) if(!is.null(results.tab)) { res <- results.tab } else { res <- bootgam.obj$results.tab } if (is.null(incl.range)) { incl.range <- ask.incl.range() } if (length(incl.range) == 2) { filter <- inc_obs > incl.range[1]/100 & inc_obs < incl.range[2]/100 res <- res[, filter] inc_obs <- inc_obs[, filter] } n_cov <- length(inc_obs) nam <- names(inc_obs) if (!is.null(bootgam.obj$failed)) { res <- res[bootgam.obj$failed == 0, ] } if (boot.type == "bootscm") { cols.dum <- grep("^X.", colnames(res)) if (length(cols.dum) > 0) { res <- res[, -cols.dum] } } cov_idx <- c() n <- length(res[, 1]) for (i in 1:n_cov) { sub <- res[res[, i] == 1, ] obs <- apply(sub, 2, sum) expect <- inc_obs * n idx <- as.num((obs/n)) - (as.num(inc_obs[i])*as.num(inc_obs)) idx[i] <- NA se <- 0 cov_idx <- data.frame(rbind(cov_idx, cbind(COV1 = nam[i], COV2 = nam, idx, se, lbnd = (idx - (1.96 * se)), ubnd = (idx + (1.96 * se))))) } if(return_plot) { p <- dotplot(as.factor(COV1) ~ as.num(idx) | as.factor(COV2), data = cov_idx, plot.zero = TRUE, main = main, xlab = xlb, ylab = ylb, lx = as.num(cov_idx$lbnd), ux = as.num(cov_idx$ubnd), prepanel = prepanel.ci, panel = panel.ci, ...) } else { return(cov_idx) } return(p) } ask.cov.name <- function (bootgam.obj = NULL) { if (!is.null(bootgam.obj)) { cat ("Covariates in database: ") cat (paste (bootgam.obj$covnams)) cat ("\n\nPlot for which covariate (return to exit): ") ans <- readline() if (ans == "") { return() } if (ans %in% (bootgam.obj$covnams)) { return (ans) } else { cat("Please choose a covariate from the list!\n\n") Recall(bootgam.obj) } } } xp.incl.index.cov.ind <- function (bootgam.obj = NULL, boot.type = NULL, cov.name = NULL, main = NULL, ylb = "ID", xlb = "Individual inclusion index", return_plot = TRUE, results.tab = NULL, ... ) { bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } boot.type <- get.boot.type (bootgam.obj) as.num <- function (dat) { return (as.numeric(as.character(dat))) } if (is.null(cov.name)) { cov.name <- ask.cov.name(bootgam.obj) } if (is.null(cov.name)) { return() } if(is.null(main)) { main <- paste ("Individual inclusion index (", cov.name, " on ", bootgam.obj$parnam, ") for ", bootgam.obj$runno, sep="") } if(!is.null(results.tab)) { res <- results.tab bootgam.obj$oid <- bootgam.obj$oid[1:length(results.tab[,1]),] } else { res <- bootgam.obj$results.tab } ids <- colnames(bootgam.obj$oid) oid.cnt <- apply (bootgam.obj$oid, 2, sum) if (!is.null(bootgam.obj$failed)) { res <- res[bootgam.obj$failed == 0,] } oid.rel <- oid.cnt / length(res[,1]) nam <- names(res) cov_idx <- c() sub <- bootgam.obj$oid[res[, cov.name == nam]==1,] obs <- apply (sub, 2, sum) n <- length(sub[,1]) idx <- (as.num(obs) / (n * as.num(oid.rel))) - 1 ord <- order(idx) ids <- as.num(gsub("X","", ids)) cov_idx <- data.frame(cbind ("idn" = ids[ord], "idx" = as.num(idx[ord]))) scales <- list(y = list (labels = rev(cov_idx$idn)), cex=c(0.7,1)) if(return_plot) { p <- xyplot (factor(idn, levels=rev(idn)) ~ as.num(idx), data = cov_idx, main = main, xlab = xlb, ylab = ylb, scales = scales, lx = 0, ux = 0, plot.zero=TRUE, prepanel = prepanel.ci, panel = panel.ci, ... ) return (p) } else { return(cov_idx) } } xp.incl.index.cov.comp <- function (bootgam.obj = NULL, boot.type = NULL, main = NULL, xlb = "Individual inclusion index", ylb = "ID", ... ) { bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } as.num <- function (dat) { return (as.numeric(as.character(dat))) } boot.type <- get.boot.type (bootgam.obj) if(is.null(main)) { main <- paste ("Individual inclusion indices for", bootgam.obj$runno) } ids <- colnames(bootgam.obj$oid) oid.cnt <- apply (bootgam.obj$oid, 2, sum) res <- bootgam.obj$results.tab if (!is.null(bootgam.obj$failed)) { res <- res[bootgam.obj$failed == 0,] } oid.rel <- oid.cnt / length(res[,1]) nam <- names(res) cov_idx <- c() for (i in seq(along=nam)) { sub <- bootgam.obj$oid[res[,nam[i] == nam]==1,] obs <- apply (sub, 2, sum) n <- length(sub[,1]) idx <- (as.num(obs) / (n * as.num(oid.rel))) - 1 cov_idx <- data.frame(rbind (cov_idx, cbind ("cov" = nam[i], "idx" = as.num(idx)))) } p <- xyplot (factor(cov) ~ as.num(idx), data=cov_idx, xlab = xlb, ylab = ylb, main = main, lx = 0, ux = 0, plot.zero = TRUE, prepanel = prepanel.ci, panel = panel.ci, ... ) return (p) } xp.inc.prob <- function (bootgam.obj = NULL, boot.type = NULL, main = NULL, col = " xlb = NULL, ylb = "Covariate", ... ) { bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } boot.type <- get.boot.type (bootgam.obj) if(is.null(main)) { main <- paste("Total frequency of covariates for", bootgam.obj$runno) } rem <- seq(along = bootgam.obj$results.tab[,1])[bootgam.obj$failed == 1] cleaned.data <- bootgam.obj$results.tab if (length(rem)>0) { cleaned.data <- bootgam.obj$results.tab[-rem,] } frac <- function (data) { sum (data) / length(data) } se <- function (data) { p <- sum (data) / length(data) se <- p * (1-p) / length(data) return (se) } as.num <- function (data) { return (as.numeric(as.character(data)))} cov.prob <- apply (cleaned.data, 2, frac) cov.prob <- cov.prob[order(cov.prob)] cov.se <- apply (cleaned.data, 2, se) cov.se <- cov.se[order(cov.prob)] cov.ci <- cbind ("ubnd" = cov.prob + 1.96*cov.se, "lbnd" = cov.prob - 1.96*cov.se) cov.comb <- data.frame ( cbind ( "cov" = names(cov.prob), "prob" = cov.prob, cov.ci) ) cov.comb <- cov.comb[order(cov.comb$prob),] if (is.null(xlb)) { xlb <- paste("Inclusion frequency (%) on ", bootgam.obj$parnam, sep="") if (boot.type == "bootscm") { xlb <- "Inclusion frequency (%)" } } pl <- xyplot (factor(cov, levels=cov) ~ 100*as.num(prob), lx = as.num(cov.comb$lbnd), ux = as.num(cov.comb$ubnd), data = cov.comb, prepanel = prepanel.ci, panel = panel.ci, main = main, xlim = c(0,100), xlab = xlb, ylab = ylb, ... ) return(pl) } xp.inc.prob.comb.2 <- function (bootgam.obj = NULL, boot.type = NULL, main = NULL, col = " xlb = NULL, ylb = "Covariate combination", ... ) { bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } if(is.null(main)) { main <- paste("Most common 2-covariate combinations for", bootgam.obj$runno) } boot.type <- get.boot.type (bootgam.obj) rem <- seq(along = bootgam.obj$results.tab[,1])[bootgam.obj$failed == 1] cleaned.data <- bootgam.obj$results.tab if (length(rem) > 0) { cleaned.data <- cleaned.data[-rem,] } frac <- function (data) { sum (data) / length(data) } se <- function (data) { p <- sum (data) / length(data) se <- p * (1-p) / length(data) return (se) } as.num <- function (data) { return (as.numeric(as.character(data)))} covs <- colnames(cleaned.data) cov_all <- c() for (i in seq(along=covs)) { tmp <- cleaned.data[cleaned.data[,i] == 1, -i] cov.prob <- apply (tmp, 2, frac) cov_all <- data.frame (rbind (cov_all, cbind ("cov1"=covs[i], "cov2" = names(cov.prob), "idx" = as.num(cov.prob)))) } cov_all$idx <- as.num(cov_all$idx) cov_all_10 <- head(cov_all[order(cov_all$idx, decreasing=TRUE),], 10) cov_all_10$label <- paste(cov_all_10$cov1, "+", cov_all_10$cov2) if (is.null(xlb)) { xlb <- paste("Inclusion frequency (%) on ", bootgam.obj$parnam, sep="") if (boot.type == "bootscm") { xlb <- "Inclusion frequency (%) on any parameter)" } } pl <- dotplot (factor(label, levels=rev(cov_all_10$label)) ~ 100*as.num(idx), lx = 0, ux=0, data = cov_all_10, prepanel = prepanel.ci, panel = panel.ci, xlim = c(0,100), main = main, xlab = xlb, ylab = ylb, ...) return(pl) } prepanel.ci <- function(x, y, lx, ux, subscripts, ...) { x <- as.numeric(x) lx <- as.numeric(lx[subscripts]) ux <- as.numeric(ux[subscripts]) list(xlim = range(x, ux, lx, finite = TRUE)) } panel.ci <- function(x, y, lx, ux, subscripts, pch = 16, plot.zero = FALSE, ...) { x <- as.numeric(x) y <- as.numeric(y) lx <- as.numeric(lx[subscripts]) ux <- as.numeric(ux[subscripts]) if (plot.zero == TRUE) { panel.abline (v = 0, lty = 3, lwd = 1, col=" } panel.abline(h = unique(y), col = "grey", lwd = 1) panel.xyplot(x, y, pch = pch, ...) } xp.inc.stab.cov <- function (bootgam.obj = NULL, boot.type = NULL, main = NULL, normalize = TRUE, split.plots = FALSE, xlb = "Bootstrap replicate number", ylb = "Difference of estimate with final", ...) { var <- NULL bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } boot.type <- get.boot.type (bootgam.obj) if(is.null(main) && !is.null(bootgam.obj$runno) && bootgam.obj$runno != "") { main <- paste("Inclusion stability for", bootgam.obj$runno) } freq <- bootgam.obj$incl.freq if(normalize) { freq <- apply(bootgam.obj$incl.freq, 2, function(x) { x - tail(x,1) } ) } if (!is.null(bootgam.obj$failed)) { freq <- freq[bootgam.obj$failed==0,] } freq <- data.frame (cbind (row = seq(along = freq[,1]), freq)) freq.long <- reshape (freq, ids=row.names(freq), varying = names(freq)[-1], idvar = "row", timevar = "var", v.names = "value", times = names(freq)[-1], direction="long") if(split.plots) { pl <- xyplot (value ~ row | var, data = freq.long, main = main, xlab = xlb, ylab = ylb, type = "l", panel=function(...) { panel.abline(h = 0, col=" panel.xyplot(...) }, ...) } else { pl <- xyplot (value ~ row, groups = var, col = rgb(0.4, 0.4, 0.4, 0.7), data = freq.long, main = main, xlab = xlb, ylab = ylb, type = "l", panel=function(...) { panel.abline(h = 0, col='steelblue', lwd=2) panel.xyplot(...) }, ...) } return (pl) } xp.dofv.plot <- function (bootscm.obj = NULL, main = NULL, xlb = "Difference in OFV", ylb = "Density", ... ) { bootscm.obj <- get.boot.obj(bootscm.obj, boot.type = "bootscm") if (is.null(bootscm.obj)) { return() } if(is.null(main)) { main <- paste("Distribution of dOFV for", bootscm.obj$runno) } dofv <- bootscm.obj$dofv[!is.na(bootscm.obj$dofv$dOFV),]$dOFV dofv <- dofv[-1] pl <- densityplot (dofv, lwd=3, main=main, xlab = xlb, ylab = ylb, panel = function () { panel.abline (v=0, lty=3, col=" panel.densityplot (dofv) }, ... ) return (pl) } get.boot.type <- function (bootscm.obj) { boot.type <- "bootgam" if ("dofv" %in% names(bootscm.obj)) { boot.type <- "bootscm" } return(boot.type) } xp.inc.cond.stab.cov <- function ( bootgam.obj = NULL, boot.type = NULL, main = NULL, xlb = "Bootstrap replicate number", ylb = "Conditional inclusion frequency", normalize = TRUE, split.plots = FALSE, ...) { label <- NULL var <- NULL bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } boot.type <- get.boot.type(bootgam.obj) if (is.null(main) && !is.null(bootgam.obj$runno) && bootgam.obj != "") { main <- paste("Conditional index stability for", bootgam.obj$runno) } res <- c() for(i in 1:length(bootgam.obj$incl.freq[,1])) { tmp <- xp.incl.index.cov(bootgam.obj = bootgam.obj, return_plot = FALSE, results.tab = bootgam.obj$results.tab[1:i,], incl.range = c(20,80)) tmp <- tmp[tmp$COV1 != tmp$COV2,] res <- rbind(res, cbind(i, as.character(tmp$COV1), as.character(tmp$COV2), as.numeric(as.character(tmp$idx)))) } res <- data.frame(res) colnames(res) <- c("id", "COV1", "COV2", "value") res$id <- as.numeric(as.character(res$id)) res$value <- as.numeric(as.character(res$value)) res$label <- paste0(res$COV1, "-", res$COV2) if(normalize) { unq <- unique(res$label) lst <- res[res$id == max(res$id),] for(i in seq(unique(res$label))) { res[res$label == unq[i],]$value <- res[res$label == unq[i],]$value - lst[lst$label == unq[i],]$value } } if(split.plots) { pl <- xyplot(value ~ id | factor(label), data = res, main = main, xlab = xlb, ylab = ylb, type = "l", panel=function(...) { panel.abline(h = 0, col=" panel.xyplot(...) }, ...) } else { pl <- xyplot(value ~ id, data = res, main = main, groups = label, col = rgb(0.4, 0.4, 0.4, 0.5), panel=function(...) { panel.abline(h = 0, col='steelblue', lwd=2) panel.xyplot(...) }, xlab = xlb, ylab = ylb, type = "l", ...) } return(pl) } xp.inc.ind.cond.stab.cov <- function ( bootgam.obj = NULL, boot.type = NULL, main = NULL, xlb = "Bootstrap replicate number", ylb = "Conditional inclusion frequency", limits = c(.2, .8), normalize = TRUE, split.plots = FALSE, start = 25, ...) { label <- NULL idn <- NULL bootgam.obj <- get.boot.obj(bootgam.obj, boot.type) if (is.null(bootgam.obj)) { return() } boot.type <- get.boot.type(bootgam.obj) if (is.null(main) && !is.null(bootgam.obj$runno) && bootgam.obj != "") { main <- paste("Conditional index stability for", bootgam.obj$runno) } res <- c() sel <- c(tail(bootgam.obj$incl.freq,1) > limits[1] & tail(bootgam.obj$incl.freq,1) < limits[2]) cov_list <- names(bootgam.obj$incl.freq[sel]) message("Calculating conditional inclusion indices per bootstrap iteration...") pb <- txtProgressBar(min = 0, max = length(bootgam.obj$incl.freq[,1]), initial = 0) res <- c() for(i in start:length(bootgam.obj$incl.freq[,1])) { setTxtProgressBar(pb, i) dat_i <- c() for(j in seq(cov_list)) { tmp <- xp.incl.index.cov.ind(bootgam.obj = bootgam.obj, return_plot = FALSE, results.tab = bootgam.obj$results.tab[1:i,], cov.name = cov_list[j]) tmp <- tmp[order(tmp$idn),] if(j == 1) { dat_i <- tmp colnames(dat_i)[2] <- cov_list[j] } else { dat_i[[cov_list[j]]] <- tmp$idx } } res <- rbind(res, dat_i) } res <- data.frame(res) res$n <- rep(start:length(bootgam.obj$incl.freq[,1]), each = length(dat_i[,1])) res.long <- reshape (res, ids=row.names(res), varying = names(res)[-c(1, length(res[1,]))], idvar = "row", timevar = "var", v.names = "value", times = names(res)[-c(1, length(res[1,]))], direction="long") res.long$label <- paste0(res.long$var, "_", res.long$idn) if(normalize) { message("Normalizing...") pb2 <- txtProgressBar(min = 0, max = length(unique(res.long$label)), initial = 0) unq <- unique(res.long$label) lst <- res.long[res.long$n == max(res$n),] for(i in seq(unique(res.long$label))) { setTxtProgressBar(pb2, i) res.long[res.long$label == unq[i],]$value <- res.long[res.long$label == unq[i],]$value - lst[lst$label == unq[i],]$value } } message("Plotting...") if(split.plots) { pl <- xyplot(value ~ n | var, data = res.long, main = main, group = idn, col = " xlab = xlb, ylab = ylb, type = "l", panel=function(...) { panel.abline(h = 0, col="steelblue") panel.xyplot(...) }, ...) } else { pl <- xyplot(value ~ n, data = res.long, main = main, groups = label, col = rgb(0.4, 0.4, 0.4, 0.25), panel=function(...) { panel.abline(h = 0, col='steelblue', lwd=2) panel.xyplot(...) }, xlab = xlb, ylab = ylb, type = "l", ...) } return(pl) } xp.dofv.npar.plot <- function (bootscm.obj = NULL, main = NULL, xlb = "Difference in OFV", ylb = "Density", ...) { bootscm.obj <- get.boot.obj(bootscm.obj, boot.type = "bootscm") if (is.null(bootscm.obj)) { return() } if (is.null(main)) { main <- paste("Distribution of dOFV for", bootscm.obj$runno) } size <- as.numeric(apply(cbind(bootscm.obj$results.tab, bootscm.obj$results.tab.dum), 1, "sum")) size_orig <- sum(bootscm.obj$results.tab.orig) dofv <- bootscm.obj$dofv$dOFV[-1] ofv <- bootscm.obj$dofv$OFV[-1] ofv_original <- bootscm.obj$ofv_original data <- data.frame(cbind(n = 1:length(size), size, dofv, ofv, ofv_original)) data$class <- 0 chi <- data.frame(cbind(x = c(-4, -3, -2, -1, 0, 1, 2, 3, 4) + size_orig, y = c(qchisq(p = 0.95, df = c(4, 3, 2, 1)), 0, -qchisq(p = 0.95, df = c(1, 2, 3, 4))) )) data$class <- as.numeric(data$dofv <= chi$y[match(data$size, chi$x)]) bg <- c(rgb(0.5,0.5,0.5,0.5), "darkblue") sz <- c(1, 1) font_sz <- c(0.5, .75) font_col <- c(rgb(1,1,1,0), "white") message("Models with largest dOFV:") print(data[order(data$dofv),][1:10,]) pl <- xyplot(dofv ~ size, data=data, ylab = "dOFV", xlab = "Covariate model size", pch = 19, panel = function(...) { llines (x=chi$x, y=chi$y) panel.abline(h = 0, lty = "dotted", col = "black") panel.abline(v = size_orig, lty = "dotted", col = "black") panel.xyplot(..., cex = sz[data$class+1], col=bg[data$class+1]) }, ...) return(pl) } xp.daic.npar.plot <- function (bootscm.obj = NULL, main = NULL, xlb = "Difference in AIC", ylb = "Density", ...) { bootscm.obj <- get.boot.obj(bootscm.obj, boot.type = "bootscm") if (is.null(bootscm.obj)) { return() } if (is.null(main)) { main <- paste("Distribution of dAIC for", bootscm.obj$runno) } size <- as.numeric(apply(cbind(bootscm.obj$results.tab, bootscm.obj$results.tab.dum), 1, "sum")) size_orig <- sum(bootscm.obj$results.tab.orig) dofv <- bootscm.obj$dofv$dOFV[-1] ofv <- bootscm.obj$dofv$OFV[-1] ofv_original <- bootscm.obj$ofv_original data <- data.frame(cbind(n = 1:length(size), size, size_orig, ofv, dofv, ofv_original, class = 0)) data$daic <- (2 * data$size + data$ofv) - (2 * data$size_orig + data$ofv_original) data$class <- as.numeric(data$daic <= 0) bg <- c(rgb(0.5,0.5,0.5,0.5), "darkblue") sz <- c(1, 1) font_sz <- c(0.5, .75) font_col <- c(rgb(1,1,1,0), "white") message("Models with largest dAIC:") print(data[order(data$daic),][1:20,]) pl <- xyplot(daic ~ size, data=data, ylab = "dAIC", xlab = "Covariate model size", pch = 19, panel = function(...) { panel.abline(h = 0, lty = "dotted", col = "black") panel.abline(v = size_orig, lty = "dotted", col = "black") panel.xyplot(..., cex = sz[data$class+1], col=bg[data$class+1]) }, ...) return(pl) }
find_optimal <- function(data, clustering, family, K = 1, cutree = NULL, cutreeLevels = 2:10, cutreeOveride = FALSE) { data <- as.data.frame(data) supported_fams <- c("gaussian", "negative.binomial", "poisson", "binomial", "ordinal") if (!family %in% supported_fams) { stop("family specified is not valid (typo?) or not yet supported, please choose from: ", paste(supported_fams, collapse = ", ")) } if (family != "ordinal" & any(unlist(lapply(data, class)) %in% c("factor", "character"))) { stop("some of the input data are factors or characters, are you looking for ordinal regression?") } if (family == "ordinal") { if (all(unlist(lapply(data, is.factor)))) { message("All data are factors, ordinal regression will use factor levels as is - ensure they are correct") } if (!all(unlist(lapply(data, is.factor))) & any(unlist(lapply(data, is.factor)))) { stop("Some data are factors, some are not - don't know how to proceed with ordinal regression") } if (all(unlist(lapply(data, is.numeric)))) { message("All data are numeric - will coerce to factor and levels will be in numeric order") } } if (is.null(cutree) & !cutreeOveride) { if (all(c("merge","height") %in% names(clustering))){ cutree <- TRUE message("clustering= object WILL work with cutree(), setting cutree=TRUE") } else { cutree <- FALSE message("clustering= object WILL NOT work with cutree(), setting cutree=FALSE") } } if (cutree & !cutreeOveride) { if (!all(c("merge","height") %in% names(clustering))) { stop("cutree() will not work on the object supplied to the clustering= argument, maybe you want cutree=F? Also see Arguments in ?find_optimal") } if (!length(cutree(tree = clustering, k = 2)) == nrow(data)) { stop("Number of samples implied from calling cutree() on object supplied to clustering= does not match the number of rows of object supplied to data=. See Arguments in ?find_optimal") } if (!is.integer(cutreeLevels)) { stop("Object supplied to cutreeLevels= is not an integer") } } if (cutree & cutreeOveride) { warning("checks on whether object supplied to clustering= works with cutree() are being skipped") if (!length(cutree(tree = clustering, k = 2)) == nrow(data)) { stop("Number of samples implied from calling cutree() on object supplied to clustering= does not match the number of rows of object supplied to data=. See Arguments in ?find_optimal") } if (!is.integer(cutreeLevels)) { stop("Object supplied to cutreeLevels= is not an integer") } } if (!cutree) { message("Note: Using individual clustering solutions supplied to clustering=,") if (!is.list(clustering)) { stop("object supplied to clustering= is not a list, see Arguments in ?find_optimal") } if (!all(unlist(lapply(clustering, is.atomic)))) { stop("some components list supplied to clustering= are not atomic vectors, see Arguments in ?find_optimal. Try: unlist(lapply(clustering, class))") } if (!cutree & !zero_range(unlist(lapply(clustering, length)))) { stop("Number of sample labels do not match in all components of the list supplied to clustering=, see Arguments in ?find_optimal") } if (!cutree & !length(clustering[[1]] == nrow(data))) { stop("Number of sample labels in list components supplied to clustering= does not match the number of rows of object supplied to data=. See Arguments in ?find_optimal") } message("they will be coerced to factors.") } if (cutree) { cutree_to_list <- function(x, clustering) {cutree(tree = clustering, k = x)} cluster_list <- lapply(X = as.list(cutreeLevels), FUN = cutree_to_list, clustering = clustering) } if (!cutree) { cluster_list <- lapply(X = clustering, FUN = as.character) } nclusters <- unlist(lapply(X = cluster_list, FUN = function(x) { length(unique(x)) } )) if (family == "gaussian") { aic_sums <- data.frame(sum_aic = gaussian_loop(cluster_list, data, nclusters), nclusters = nclusters) } if (family == "negative.binomial") { aic_sums <- data.frame(sum_aic = negbin_loop(cluster_list, data), nclusters = nclusters) } if (family == "poisson") { aic_sums <- data.frame(sum_aic = poisson_loop(cluster_list, data), nclusters = nclusters) } if (family == "binomial") { aic_sums <- data.frame(sum_aic = binomial_loop(cluster_list, data, K=K), nclusters = nclusters) } if (family == "ordinal") { aic_sums <- data.frame(sum_aic = ordinal_loop(cluster_list, data), nclusters = nclusters) } attr(aic_sums, "family") <- family if (family == "binomial") {attr(aic_sums, "K") <- K} attr(aic_sums, "cutree") <- cutree attr(aic_sums, "cutreeLevels") <- cutreeLevels class(aic_sums) <- c("aicsums","data.frame") aic_sums }
IRW = function(dimension, lsf, N = 10, q = Inf, Nevent = Inf, X, y = lsf(X), K, burnin = 20, sigma = 0.3, last.return = TRUE, use.potential = TRUE, plot = FALSE, plot.lsf = FALSE, print_plot = FALSE, output_dir = NULL, plot.lab = c('x_1', 'x_2') ){ cat("==========================\n") cat(" Beginning of IRW \n") cat("==========================\n\n") x <- z <- ..level.. <- NULL if(missing(K)) { K = function(x){ W = rnorm(dimension) y = (x + sigma*W)/sqrt(1 + sigma^2) return(y) } } Ncall = 0; m = 1 Ndep = 0; Ndup = 0 acceptance = c() potentiel = matrix(1, nrow=N, ncol=N) - diag(1,N) cat(" =================================== \n") cat(" STEP 1 : FIRST SAMPLING AND MINIMUM \n") cat(" =================================== \n\n") if(missing(X)){ cat(" X = matrix(rnorm(dimension*N),ncol=N, dimnames = list(rep(c('x', 'y'), ceiling(dimension/2))[1:dimension])) cat(" y = lsf(X); Ncall = Ncall + N } else{ cat(" row.names(X) <- rep(c('x', 'y'), ceiling(dimension/2))[1:dimension] cat(" if(missing(y)) { y = lsf(X) } N = length(y) } if(plot==TRUE){ cat(" * 2D PLOT : SET-UP \n") if(!is.null(output_dir)){ output_d = paste(output_dir,"_IRW.pdf",sep="") pdf(output_d) } p <- ggplot(data = data.frame(t(X), z = y), aes(x,y)) + geom_point(aes(color=z)) + theme(legend.position = "none") + xlim(-8, 8) + ylim(-8, 8) + xlab(plot.lab[1]) + ylab(plot.lab[2]) if(plot.lsf==TRUE){ xplot <- yplot <- c(-80:80)/10 df_plot = data.frame(expand.grid(x=xplot, y=yplot)) df_plot$z <- lsf(t(df_plot)) p <- p + geom_contour(data = df_plot, aes(z=z, color=..level..), breaks=q) } if(print_plot) print(p) else{ if(!is.null(output_dir)) list_plot <- list(p) } } cat(" ind = which.min(y) L = y[ind] cat(" ================== \n") cat(" STEP 2 : CORE LOOP \n") cat(" ================== \n\n") while((L[Ndep+1] < q) && (Ndep <= Nevent)){ cat(" cat(" cat(" * Select randomly a particle to start sampling from \n") sel = tryCatch(sample(c(1:N)[potentiel[,ind]==1],1),error = function(cond) ind) cat(" - mov. particle : ",ind,"; y =", y[ind],"\n") cat(" - sel. particle : ",sel,"; y =", y[sel],"\n") X_from <- X[,sel] y_from <- y[sel] cat(" * Markov chain drawing \n") acceptance[Ndep + 1] = 0 for(i in 1:burnin){ X_star = K(X_from) tryCatch( {y_star <- lsf(X_star); Ncall = Ncall + 1}, error = function(cond) { message(cond) message("Unable to evaluate the model at proposed point, transition refused \n"); y_star <<- L[Ndep+1]-1 return(y_star) } ) if(y_star>L[Ndep+1]) { X_from = X_star; y_from = y_star; acceptance[Ndep + 1] = acceptance[Ndep + 1] +1 } } if(y_from > L[Ndep+1]) { cat(" * New particle accepted \n") if(plot==TRUE) { cat(" * 2D PLOT : UPDATE \n") p <- p + geom_line(data = df_tmp <- data.frame(x = c(X[1,ind],X_from[1]), y = c(X[2,ind],X_from[2]), z = c(0,0)), color = "green", linetype = 4) + geom_point(data = data.frame(x = X_from[1], y = X_from[2], z = y_from), aes(color=z)) if(print_plot) print(p) else{ if(!is.null(output_dir)) list_plot <- c(list_plot, list(p)) } } X[,ind] = X_from; y[ind] = y_from Ndep = Ndep + 1; cat(" * Refresh potential matrix \n") if(use.potential == TRUE){ if(acceptance[Ndep]==0){ potentiel[,ind] = potentiel[,sel] potentiel[ind,] = potentiel[sel,] Ndup = Ndup + 1 } else{ potentiel[,ind] = seq(1,1,l=N) potentiel[ind,] = seq(1,1,l=N) potentiel[ind,sel] = 0 potentiel[ind,ind] = 0 } } else{ potentiel = matrix(1, nrow=N, ncol=N) - diag(1,N) } cat(" * Find new minimum \n") ind = which.min(y) L[Ndep+1] = y[ind] cat(" - current threshold :",L[Ndep+1],"\n\n") } else{ cat(" * New particule rejected \n") } m = m + 1; } if(plot==TRUE) { cat(" * 2D PLOT : FINAL SAMPLING \n\n") if(!is.null(output_dir)){ if(print_plot) print(p) else{ list_plot <- c(list_plot, list(p)) lapply(list_plot, print) } dev.off() output_d = paste(output_dir,"_MP_final_db.pdf",sep="") pdf(output_d) } print(p) if(!is.null(output_dir)){ dev.off() } } cat("=========================\n") cat(" End of IRW \n") cat("=========================\n\n") cat(" - Number of iterations =",m-1,"\n") cat(" - Number of moves =",Ndep,"\n") cat(" - Number of wrong moves =",m-1-Ndep,"\n") cat(" - Total number of calls =",Ncall,"\n") if(last.return == FALSE){L = L[-length(L)]} res = list(L = L, M = m-1, Ncall = Ncall, X = X, y = y, q = q, Nevent = Nevent, Nwmoves = m-1-Ndep, acceptance = acceptance/T) }
"rxReservedKeywords"
ls_write_tsv <- function(data, file, encoding = limonaid::opts$get("encoding"), preventOverwriting = limonaid::opts$get("preventOverwriting"), silent = limonaid::opts$get("silent")) { dirToWriteTo <- dirname(file); if (nchar(dirToWriteTo) > 0) { if (!dir.exists(dirToWriteTo)) { stop("The directory you specified to write the output file to, '", dirToWriteTo, "', does not exist."); } } if (file.exists(file) && preventOverwriting) { stop("The filename you specified to write the output file to, '", file, "', already exists, and `preventOverwriting` is set to ", "TRUE, so I'm aborting."); } data$relevance <- ifelse( data$relevance == 1, "1", ifelse( is.na(data$relevance) | (nchar(data$relevance) == 0), "", paste0("\"", data$relevance, "\"") ) ); data$text <- gsub("\"", "\"\"", data$text); data$text <- ifelse(grepl(" |@", data$text), paste0("\"", data$text, "\""), data$text); data$name <- ifelse(grepl(" |@", data$name), paste0("\"", data$name, "\""), data$name); colNames <- names(data); colNames[colNames == "type.scale"] <- "type/scale"; if (trimws(tolower(encoding)) == "utf-8") { fileToWrite <- paste(apply(data, 1, paste, collapse="\t"), collapse="\n"); fileToWrite <- paste(paste(colNames, collapse="\t"), "\n", fileToWrite); fileToWrite <- enc2utf8(fileToWrite); con <- file(file, open = "w", encoding="native.enc"); writeLines(fileToWrite, con = con, useBytes=TRUE); close(con); } else { if (trimws(tolower(encoding)) == "default-utf-8") { encoding <- "UTF-8"; } utils::write.table( data, file = file, col.names = colNames, sep = "\t", na = "", quote = FALSE, row.names = FALSE, qmethod = "double", fileEncoding = encoding ); } return(invisible(data)); }
context("Check logdensity_fft") test_that("Check that the default settings of logdensity_fft generates a 'density' object for different sample sizes.", { SAMPLE100 <- rchisq(100,10) SAMPLE1000 <- rchisq(1000,10) SAMPLE10000 <- rchisq(10000,10) expect_is(logdensity_fft(SAMPLE100), 'density') expect_is(logdensity_fft(SAMPLE1000), 'density') expect_is(logdensity_fft(SAMPLE10000), 'density') }) test_that("Check that different kernel inputs for logdensity_fft generates a 'density' object.", { SAMPLE100 <- rchisq(100,10) expect_is(logdensity_fft(SAMPLE100,kernel = 'epanechnikov'), 'density') expect_is(logdensity_fft(SAMPLE100,kernel = 'triangular'), 'density') expect_is(logdensity_fft(SAMPLE100,kernel = 'uniform'), 'density') expect_is(logdensity_fft(SAMPLE100,kernel = 'laplace'), 'density') expect_is(logdensity_fft(SAMPLE100,kernel = 'logistic'), 'density') }) test_that("Check that different bandwidth inputs for logdensity_fft generates a 'density' object.", { SAMPLE100 <- rchisq(100,10) expect_is(logdensity_fft(SAMPLE100,bw='logcv'), 'density') expect_is(logdensity_fft(SAMPLE100,bw='logg'), 'density') expect_is(logdensity_fft(SAMPLE100,bw='nrd'), 'density') expect_is(logdensity_fft(SAMPLE100,bw='ucv'), 'density') expect_is(logdensity_fft(SAMPLE100,bw='SJ-ste'), 'density') expect_is(logdensity_fft(SAMPLE100,bw='SJ-dpi'), 'density') }) test_that("Check that different values of n for logdensity_fft generates a 'density' object.", { SAMPLE100 <- rchisq(100,10) expect_is(logdensity_fft(SAMPLE100,n=64), 'density') expect_is(logdensity_fft(SAMPLE100,n=128), 'density') expect_is(logdensity_fft(SAMPLE100,n=256), 'density') expect_is(logdensity_fft(SAMPLE100,n=1028), 'density') }) test_that("Check that different values of adjust for logdensity_fft generates a 'density' object.", { SAMPLE100 <- rchisq(100,10) expect_is(logdensity_fft(SAMPLE100,adjust=0.5), 'density') expect_is(logdensity_fft(SAMPLE100,adjust=1.5), 'density') expect_is(logdensity_fft(SAMPLE100,adjust=2), 'density') expect_is(logdensity_fft(SAMPLE100,adjust=0.25), 'density') }) test_that("Check that different values of from and to for logdensity_fft generates a 'density' object.", { SAMPLE100 <- rchisq(100,10) expect_is(logdensity_fft(SAMPLE100,from=1e-6,to=1), 'density') expect_is(logdensity_fft(SAMPLE100,from=1e-6,to=100), 'density') expect_is(logdensity_fft(SAMPLE100,from=100,to=200), 'density') expect_is(logdensity_fft(SAMPLE100,from=10,to=10), 'density') }) test_that("Check that different values of cut for logdensity_fft generates a 'density' object.", { SAMPLE100 <- rchisq(100,10) expect_is(logdensity_fft(SAMPLE100,cut=1), 'density') expect_is(logdensity_fft(SAMPLE100,cut=2), 'density') expect_is(logdensity_fft(SAMPLE100,cut=10), 'density') })
convertseis2R<-function(fn, destdir=".", kind=1, Iendian=1, BIGLONG=FALSE) { for(i in 1:length(fn)) { fn2 = fn[i] bn = basename(fn2) bn2 = unlist( strsplit(bn, split="\\.") ) bn3 = paste(collapse=".", bn2[1:(length(bn2)-1)]) bn4 = paste(sep=".", bn3, "RDATA") fndest = paste(sep="/", destdir, bn4) DAT = RSEIS::JGET.seis(fn2, kind = kind, Iendian = Iendian, BIGLONG = BIGLONG, HEADONLY = FALSE, PLOT = -1) save(file=fndest, DAT) } }
summary.trafo_lm <- function(object, ...) { formula <- NULL trafo <- object$trafo method <- object$method lambdahat <- object$lambdahat if (inherits(object, "woparam")) { param <- "woparam" } else if (inherits(object, "oneparam")) { param <- "oneparam" } modOne <- object$orig_mod modOne$name <- "Untransformed model" modTwo <- object$trafo_mod modTwo$name <- "Transformed model" sums <- summary_internal(modOne = modOne, modTwo = modTwo, compare = FALSE, std = object$std) sum_out <- list(trafo = trafo, method = method, lambdahat = lambdahat, orig_sum = sums$modOne_sum, trafo_sum = sums$modTwo_sum, param = param, std = object$std) class(sum_out) <- "summary.trafo_lm" return(sum_out) } print.summary.trafo_lm <- function(x, ...) { cat("Summary of untransformed model \n") print(x$orig_sum) cat("\n") cat("Summary of transformed model: ", x$trafo,"transformation \n") cat("\n") cat("Formula in call: ",x$trafo_sum$formula, "\n") print(x$trafo_sum) cat("\n") if (x$std == TRUE) { } invisible(x) }
fastqueue2 <- function (init = 20L, missing_default = NULL) { queue <- fastmap::fastqueue(init = init, missing_default = missing_default) head <- 0 count <- 0 i <- NA ev <- new.env(parent = environment(.subset2(queue, "as_list"))) q <- NULL queue$at <- with(ev, { function(i){ if (is.na(i) || i < 1L || i > count) { stop("subscript out of bounds") } q[[head - count + i]] } }) queue$mat <- with(ev, { function(i){ q[head - count + i] } }) class(queue) <- c("fastqueue2", "list") queue }
context("Validate GTFS") data_path <- system.file("extdata/spo_gtfs.zip", package = "gtfstools") gtfs <- read_gtfs(data_path) expect_warning(validate_gtfs(gtfs)) a_warning <- tryCatch( validate_gtfs(gtfs), warning = function(cnd) cnd ) expect_s3_class(a_warning, "deprecatedWarning") testthat::skip("Skipping validate_gtfs() tests because it is now deprecated.") full_val <- validate_gtfs(gtfs) full_val <- attr(full_val, "validation_result") partial_val_1 <- validate_gtfs(gtfs, "stop_times") partial_val_1 <- attr(partial_val_1, "validation_result") partial_val_2 <- validate_gtfs(gtfs, c("stop_times", "agency")) partial_val_2 <- attr(partial_val_2, "validation_result") extra_file_gtfs <- gtfs extra_file_gtfs$extra_file <- extra_file_gtfs$calendar extra_file_gtfs <- validate_gtfs(extra_file_gtfs) extra_file_val <- attr(extra_file_gtfs, "validation_result") extra_field_gtfs <- gtfs extra_field_gtfs$calendar <- data.table::copy(gtfs$calendar) extra_field_gtfs$calendar[, extra_field := "ola"] extra_field_gtfs$shapes <- data.table::copy(gtfs$shapes) extra_field_gtfs$shapes[, additional_field := 2] extra_field_gtfs <- validate_gtfs(extra_field_gtfs) extra_field_val <- attr(extra_field_gtfs, "validation_result") missing_req_file_gtfs <- gtfs missing_req_file_gtfs$agency <- NULL missing_req_file_gtfs <- validate_gtfs(missing_req_file_gtfs, warnings = FALSE) missing_req_file_val <- attr(missing_req_file_gtfs, "validation_result") missing_req_field_gtfs <- gtfs missing_req_field_gtfs$stop_times <- data.table::copy(gtfs$stop_times) missing_req_field_gtfs$stop_times[, trip_id := NULL] missing_req_field_gtfs <- validate_gtfs( missing_req_field_gtfs, warnings = FALSE ) missing_req_field_val <- attr(missing_req_field_gtfs, "validation_result") specified_files <- c( "agency", "stops", "routes", "trips", "stop_times", "calendar", "calendar_dates", "fare_attributes", "fare_rules", "shapes", "frequencies", "transfers", "pathways", "levels", "feed_info", "translations", "attributions" ) required_files <- c( "agency", "stops", "routes", "trips", "stop_times", "calendar" ) agency_field <- c( "agency_id", "agency_name", "agency_url", "agency_timezone", "agency_lang", "agency_phone", "agency_fare_url", "agency_email" ) stops_field <- c( "stop_id", "stop_code", "stop_name", "stop_desc", "stop_lat", "stop_lon", "zone_id", "stop_url", "location_type", "parent_station", "stop_timezone", "wheelchair_boarding", "level_id", "platform_code" ) routes_field <- c( "route_id", "agency_id", "route_short_name", "route_long_name", "route_desc", "route_type", "route_url", "route_color", "route_text_color", "route_sort_order", "continuous_pickup", "continuous_drop_off" ) trips_field <- c( "route_id", "service_id", "trip_id", "trip_headsign", "trip_short_name", "direction_id", "block_id", "shape_id", "wheelchair_accessible", "bikes_allowed" ) stop_times_field <- c( "trip_id", "arrival_time", "departure_time", "stop_id", "stop_sequence", "stop_headsign", "pickup_type", "drop_off_type", "continuous_pickup", "continuous_drop_off", "shape_dist_traveled", "timepoint" ) calendar_field <- c( "service_id", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "start_date", "end_date" ) calendar_dates_field <- c("service_id", "date", "exception_type") fare_attributes_field <- c( "agency_id", "fare_id", "price", "currency_type", "payment_method", "transfers", "transfer_duration" ) fare_rules_field <- c( "fare_id", "route_id", "origin_id", "destination_id", "contains_id" ) shapes_field <- c( "shape_id", "shape_pt_lat", "shape_pt_lon", "shape_pt_sequence", "shape_dist_traveled" ) frequencies_field <- c( "trip_id", "start_time", "end_time", "headway_secs", "exact_times" ) transfers_field <- c( "from_stop_id", "to_stop_id", "transfer_type", "min_transfer_time" ) pathways_field <- c( "pathway_id", "from_stop_id", "to_stop_id", "pathway_mode", "is_bidirectional", "length", "traversal_time", "stair_count", "max_slope", "min_width", "signposted_as", "reversed_signposted_as" ) levels_field <- c("level_id", "level_index", "level_name") feed_info_field <- c( "feed_publisher_name", "feed_publisher_url", "feed_lang", "feed_start_date", "feed_end_date", "feed_version", "feed_contact_email", "feed_contact_url" ) translations_field <- c( "table_name", "field_name", "language", "translation", "record_id", "record_sub_id", "field_value" ) attributions_field <- c( "attribution_id", "agency_id", "route_id", "trip_id", "organization_name", "is_producer", "is_operator", "is_authority", "attribution_url", "attribution_email", "attribution_phone" ) test_that("raises errors due to incorrect input types", { no_class_gtfs <- gtfs attr(no_class_gtfs, "class") <- NULL expect_error(validate_gtfs(no_class_gtfs)) expect_error(validate_gtfs(gtfs, files = NA)) expect_error(validate_gtfs(gtfs, files = as.factor("stop_times"))) expect_error(validate_gtfs(gtfs, quiet = "TRUE")) expect_error(validate_gtfs(gtfs, warnings = "TRUE")) }) test_that("raises error due to non-existent/mistyped supplied file in gtfs", { expect_error(validate_gtfs(gtfs, files = "agency.txt")) expect_error(validate_gtfs(gtfs, files = "non-existent-file")) }) test_that("raises warnings and messages adequately", { expect_silent(validate_gtfs(gtfs)) expect_silent(validate_gtfs(gtfs, "stop_times")) expect_silent(validate_gtfs(gtfs, c("stop_times", "agency"))) expect_silent(validate_gtfs(extra_file_gtfs)) expect_silent(validate_gtfs(extra_field_gtfs)) expect_silent(validate_gtfs(missing_req_file_gtfs, warnings = FALSE)) expect_silent(validate_gtfs(missing_req_field_gtfs, warnings = FALSE)) expect_message(validate_gtfs(gtfs, quiet = FALSE)) expect_message(validate_gtfs(gtfs, "stop_times", quiet = FALSE)) expect_message(validate_gtfs(gtfs, c("stop_times", "agency"), quiet = FALSE)) expect_message(validate_gtfs(extra_file_gtfs, quiet = FALSE)) expect_message(validate_gtfs(extra_field_gtfs, quiet = FALSE)) expect_silent( validate_gtfs(missing_req_file_gtfs, warnings = FALSE, quiet = FALSE) ) expect_silent( validate_gtfs(missing_req_field_gtfs, warnings = FALSE, quiet = FALSE) ) expect_warning(validate_gtfs(missing_req_file_gtfs)) expect_warning(validate_gtfs(missing_req_field_gtfs)) }) test_that("results in a dt_gtfs, and validation_result has right col types", { expect_s3_class(validate_gtfs(gtfs), "dt_gtfs") expect_s3_class(full_val, "data.table") expect_equal(class(full_val$file), "character") expect_equal(class(full_val$file_provided_status), "logical") expect_equal(class(full_val$field), "character") expect_equal(class(full_val$field_spec), "character") expect_equal(class(full_val$field_provided_status), "logical") expect_equal(class(full_val$validation_status), "character") expect_equal(class(full_val$validation_details), "character") }) test_that("doesn't change original gtfs (only validation_result attribute)", { no_val_gtfs <- gtfs attr(no_val_gtfs, "validation_result") <- NULL pre_validation_no_val_gtfs <- no_val_gtfs validated_gtfs <- validate_gtfs(no_val_gtfs) expect_identical(no_val_gtfs, pre_validation_no_val_gtfs) expect_false(identical(no_val_gtfs, validated_gtfs)) val_result <- attr(validated_gtfs, "validation_result") attr(no_val_gtfs, "validation_result") <- val_result expect_identical(no_val_gtfs, validated_gtfs) }) test_that("validates against the correct files", { validated_files <- unique(full_val$file) expect_equal(sum(validated_files %in% specified_files), 17) validated_files <- unique(partial_val_1$file) expect_true(validated_files == "stop_times") validated_files <- unique(partial_val_2$file) expect_equal(sum(validated_files %in% c("stop_times", "agency")), 2) }) test_that("validates all fields from desired files", { validated_files <- unique(full_val$file) invisible(lapply( validated_files, function (i) { supposed_fields <- get(paste0(i, "_field")) expect_equal( sum(full_val[file == i]$field %in% supposed_fields), length(supposed_fields) ) } )) supposed_fields <- stop_times_field expect_equal( sum(partial_val_1$field %in% supposed_fields), length(supposed_fields) ) validated_files <- unique(partial_val_2$file) invisible(lapply( validated_files, function (i) { supposed_fields <- get(paste0(i, "_field")) expect_equal( sum(full_val[file == i]$field %in% supposed_fields), length(supposed_fields) ) } )) }) test_that("recognizes extra files and fields as extra", { expect_equal( sum(extra_file_val[file == "extra_file"]$file_spec == "ext"), length(extra_file_val[file == "extra_file"]$field) ) expect_equal( sum(extra_file_val[file == "extra_file"]$field_spec == "ext"), length(extra_file_val[file == "extra_file"]$field) ) expect_equal( sum(extra_file_val[file == "extra_file"]$file_provided_status == TRUE), length(extra_file_val[file == "extra_file"]$field) ) expect_equal( sum(extra_file_val[file == "extra_file"]$field_provided_status == TRUE), length(extra_file_val[file == "extra_file"]$field) ) expect_equal( extra_field_val[file == "calendar" & field == "extra_field"]$field_spec, "ext" ) expect_equal( extra_field_val[file == "shapes" & field == "additional_field"]$field_spec, "ext" ) expect_equal( sum(extra_field_val[file == "calendar"]$field_spec == "ext"), 1 ) expect_equal( sum(extra_field_val[file == "shapes"]$field_spec == "ext"), 1 ) expect_true( extra_field_val[file == "calendar" & field == "extra_field"]$field_provided_status, ) expect_true( extra_field_val[file == "shapes" & field == "additional_field"]$field_provided_status, ) }) test_that("attributes have right validation status and details", { ok_status <- full_val[ file_provided_status == TRUE & field_provided_status == TRUE ] expect_equal(sum(ok_status$validation_status == "ok"), nrow(ok_status)) expect_equal(sum(is.na(ok_status$validation_details)), nrow(ok_status)) file_info_status <- full_val[ file_spec == "opt" & file_provided_status == FALSE ] expect_equal( sum(file_info_status$validation_status == "info"), nrow(file_info_status) ) expect_equal( sum(file_info_status$validation_details == "missing_opt_file"), nrow(file_info_status) ) file_problem_status <- missing_req_file_val[ file_spec == "req" & file_provided_status == FALSE ] expect_equal( sum(file_problem_status$validation_status == "problem"), nrow(file_problem_status) ) expect_equal( sum(file_problem_status$validation_details == "missing_req_file"), nrow(file_problem_status) ) file_extra_status <- extra_file_val[file_spec == "ext"] expect_equal( sum(file_extra_status$validation_status == "info"), nrow(file_extra_status) ) expect_equal( sum(file_extra_status$validation_details == "undocumented_file"), nrow(file_extra_status) ) field_info_status <- full_val[ file_spec == "req" & file_provided_status == TRUE & field_provided_status == FALSE & field_spec == "opt" ] expect_equal( sum(field_info_status$validation_status == "info"), nrow(field_info_status) ) expect_equal( sum(field_info_status$validation_details == "missing_opt_field"), nrow(field_info_status) ) field_problem_status <- missing_req_field_val[ file_provided_status == TRUE & field_spec == "req" & field_provided_status == FALSE ] expect_equal( sum(field_problem_status$validation_status == "problem"), nrow(field_problem_status) ) expect_equal( sum(field_problem_status$validation_details == "missing_req_field"), nrow(field_problem_status) ) field_extra_status <- extra_field_val[ file_spec != "ext" & field_spec == "ext" ] expect_equal( sum(field_extra_status$validation_status == "info"), nrow(field_extra_status) ) expect_equal( sum(field_extra_status$validation_details == "undocumented_field"), nrow(field_extra_status) ) }) test_that("handles 'calendar' absence and 'translations' presence adequately", { expect_equal( sum(full_val[file == "calendar"]$file_spec == "req"), nrow(full_val[file == "calendar"]) ) expect_equal( sum(full_val[file == "calendar_dates"]$file_spec == "opt"), nrow(full_val[file == "calendar_dates"]) ) no_calendar_gtfs <- gtfs no_calendar_gtfs$calendar <- NULL no_calendar_gtfs <- validate_gtfs(no_calendar_gtfs, warnings = FALSE) no_calendar_val <- attr(no_calendar_gtfs, "validation_result") expect_equal( sum(no_calendar_val[file == "calendar"]$file_spec == "opt"), nrow(no_calendar_val[file == "calendar"]) ) expect_equal( sum(no_calendar_val[file == "calendar_dates"]$file_spec == "req"), nrow(no_calendar_val[file == "calendar_dates"]) ) expect_equal( sum(full_val[file == "feed_info"]$file_spec == "opt"), nrow(full_val[file == "feed_info"]) ) translations_gtfs <- gtfs translations_gtfs$translations <- data.table::data.table(NULL) translations_gtfs <- validate_gtfs(translations_gtfs, warnings = FALSE) translations_val <- attr(translations_gtfs, "validation_result") expect_equal( sum(translations_val[file == "feed_info"]$file_spec == "req"), nrow(translations_val[file == "feed_info"]) ) }) test_that("it is deprecated", { expect_warning(validate_gtfs(gtfs)) })
library(urca) library(vars) data(EuStockMarkets) Assets <- as.zoo(EuStockMarkets) AssetsM <- aggregate(Assets, as.yearmon, tail, 1) head(AssetsM) AssetsMsub <- window(AssetsM, start = start(AssetsM), end = "Jun 1996") ADF <- lapply(AssetsMsub, ur.df, type = "drift", selectlags = "AIC") ERS <- lapply(AssetsMsub, ur.ers) DADF <- lapply(diff(AssetsMsub), ur.df, selectlags = "AIC") DERS <- lapply(diff(AssetsMsub), ur.ers) VEC <- ca.jo(AssetsMsub, ecdet = "none", spec = "transitory") summary(VEC)
ISOImagingCondition <- R6Class("ISOImagingCondition", inherit = ISOCodeListValue, private = list( xmlElement = "MD_ImagingConditionCode", xmlNamespacePrefix = "GMD" ), public = list( initialize = function(xml = NULL, value, description = NULL){ super$initialize(xml = xml, id = private$xmlElement, value = value, description = description, addCodeSpaceAttr = FALSE) } ) ) ISOImagingCondition$values <- function(labels = FALSE){ return(ISOCodeListValue$values(ISOImagingCondition, labels)) }
test.sd_scat <- function() { dataPath <- file.path(path.package(package="clusterCrit"),"unitTests","data","testsInternal_400_4.Rdata") load(file=dataPath, envir=.GlobalEnv) idx <- intCriteria(traj_400_4, part_400_4[[4]], c("SD_Scat")) cat(paste("\nFound idx =",idx)) val <- 0.0323239791483279 cat(paste("\nShould be =",val,"\n")) checkEqualsNumeric(idx[[1]],val) }
imagePlaneGridTransform <- function(p, nx, ny){ corners <- matrix(p[1:8], nrow=4, ncol=2, byrow=TRUE) rm1_m <- (corners[2, 2] - corners[1, 2])/(corners[2, 1] - corners[1, 1]) rm2_m <- (corners[3, 2] - corners[4, 2])/(corners[3, 1] - corners[4, 1]) cm1_m <- (corners[4, 2] - corners[1, 2])/(corners[4, 1] - corners[1, 1]) cm2_m <- (corners[3, 2] - corners[2, 2])/(corners[3, 1] - corners[2, 1]) r_pos_x <- quadraticPointsOnInterval(t1=corners[1, 1], t2=corners[4, 1], n=ny, a=p[9]) r_pos <- cbind(r_pos_x, r_pos_x*cm1_m + corners[4, 2] - cm1_m*corners[4, 1]) c_pos_x <- quadraticPointsOnInterval(t1=corners[1, 1], t2=corners[2, 1], n=nx, a=p[10]) c_pos <- cbind(c_pos_x, c_pos_x*rm1_m + corners[2, 2] - rm1_m*corners[2, 1]) r_dygrad <- quadraticPointsOnInterval(t1=corners[2, 2] - corners[1, 2], t2=corners[3, 2] - corners[4, 2], n=ny, a=p[11]) r_dxgrad <- quadraticPointsOnInterval(t1=corners[2, 1] - corners[1, 1], t2=corners[3, 1] - corners[4, 1], n=ny, a=p[11]) c_dygrad <- quadraticPointsOnInterval(t1=corners[4, 2] - corners[1, 2], t2=corners[3, 2] - corners[2, 2], n=nx, a=p[12]) c_dxgrad <- quadraticPointsOnInterval(t1=corners[4, 1] - corners[1, 1], t2=corners[3, 1] - corners[2, 1], n=nx, a=p[12]) rmm <- matrix(r_dygrad/r_dxgrad, nrow=nx, ncol=ny, byrow=T) cmm <- matrix(c_dygrad/c_dxgrad, nrow=nx, ncol=ny, byrow=F) cbm <- matrix(c_pos[, 2] - cmm[, 1]*c_pos[, 1], nrow=nx, ncol=ny, byrow=F) rbm <- matrix(r_pos[, 2] - rmm[1, ]*r_pos[, 1], nrow=nx, ncol=ny, byrow=T) x <- (cbm - rbm) / (rmm - cmm) y <- rmm * x + rbm grid <- cbind(c(x), c(y)) grid }
expect_equal( construct_timeAdjust(Cl=c(1,1,1), timepoints=2, "factor"), matrix(c(rep(1,6),rep(0:1,3)),ncol=2) ) expect_equal( construct_trtMat(Cl=c(1,1,1), trtDelay=NULL, dsntype="SWD", timepoints=4), { a <- matrix(0,nrow=3,ncol=4) a[upper.tri(a)] <- 1 a } ) expect_equal( construct_trtMat(Cl=c(1,1,1), trtDelay=NULL, dsntype="SWD", timepoints=5), { a <- matrix(0,nrow=3,ncol=5) a[upper.tri(a)] <- 1 a } )
tutorial_html_dependency <- function() { htmltools::htmlDependency( name = "tutorial", version = utils::packageVersion("learnr"), src = html_dependency_src("lib", "tutorial"), script = "tutorial.js", stylesheet = "tutorial.css" ) } tutorial_autocompletion_html_dependency <- function() { htmltools::htmlDependency( name = "tutorial-autocompletion", version = utils::packageVersion("learnr"), src = html_dependency_src("lib", "tutorial"), script = "tutorial-autocompletion.js" ) } tutorial_diagnostics_html_dependency <- function() { htmltools::htmlDependency( name = "tutorial-diagnostics", version = utils::packageVersion("learnr"), src = html_dependency_src("lib", "tutorial"), script = "tutorial-diagnostics.js" ) } html_dependency_src <- function(...) { if (nzchar(Sys.getenv("RMARKDOWN_SHINY_PRERENDERED_DEVMODE"))) { r_dir <- utils::getSrcDirectory(html_dependency_src, unique = TRUE) pkg_dir <- dirname(r_dir) file.path(pkg_dir, "inst", ...) } else { system.file(..., package = "learnr") } } idb_html_dependency <- function() { htmltools::htmlDependency( name = "idb-keyvalue", version = "3.2.0", src = system.file("lib/idb-keyval", package = "learnr"), script = "idb-keyval-iife-compat.min.js", all_files = FALSE ) } bootbox_html_dependency <- function() { htmltools::htmlDependency( name = "bootbox", version = "4.4.0", src = system.file("lib/bootbox", package = "learnr"), script = "bootbox.min.js" ) } clipboardjs_html_dependency <- function() { htmltools::htmlDependency( name = "clipboardjs", version = "1.5.15", src = system.file("lib/clipboardjs", package = "learnr"), script = "clipboard.min.js" ) } ace_html_dependency <- function() { htmltools::htmlDependency( name = "ace", version = ACE_VERSION, src = system.file("lib/ace", package = "learnr"), script = "ace.js" ) }
library(cheddar) options(continue=' ') options(width=90) options(prompt='> ') options(SweaveHooks = list(fig=function() par(mgp=c(2.5,1,0), mar=c(4,4,2,1), oma=c(0,0,1,0), cex.main=0.8))) getOption("SweaveHooks")[["fig"]]() data(TL84) PlotNPS(TL84, 'Log10M', 'Log10N') getOption("SweaveHooks")[["fig"]]() PlotNPS(TL84, 'Log10M', 'Log10N', show.web=FALSE, highlight.nodes=NULL) getOption("SweaveHooks")[["fig"]]() PlotNPS(TL84, 'Log10M', 'Log10N', show.nodes.as='labels', show.web=FALSE) getOption("SweaveHooks")[["fig"]]() PlotNPS(TL84, 'Log10M', 'Log10N', show.nodes.as='labels', show.web=FALSE, node.labels='node', cex=0.5) getOption("SweaveHooks")[["fig"]]() lots.of.letters <- c(letters, LETTERS, paste(LETTERS,letters,sep='')) PlotNPS(TL84, 'Log10M', 'Log10N', show.nodes.as='labels', show.web=FALSE, node.labels=lots.of.letters[1:NumberOfNodes(TL84)]) getOption("SweaveHooks")[["fig"]]() PlotNPS(TL84, 'Log10M', 'Log10N', show.nodes.as='both', show.web=FALSE, cex=2) getOption("SweaveHooks")[["fig"]]() PlotNPS(TL84, 'Log10M', 'Log10N', xlab=Log10MLabel(TL84), ylab=Log10NLabel(TL84)) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(1,3)) PlotNPS(TL84, 'Log10M', 'OutDegree', show.web=FALSE) abline(lm(OutDegree(TL84) ~ Log10M(TL84))) PlotNPS(TL84, 'Log10M', 'InDegree', show.web=FALSE) abline(lm(InDegree(TL84) ~ Log10M(TL84))) PlotNPS(TL84, 'Log10M', 'Degree', show.web=FALSE) abline(lm(Degree(TL84) ~ Log10M(TL84))) getOption("SweaveHooks")[["fig"]]() PlotNPS(TL84, 'Log10M', 'PreyAveragedTrophicLevel') getOption("SweaveHooks")[["fig"]]() PlotNPS(TL84, 'Log10M', 'ChainAveragedTrophicLevel') getOption("SweaveHooks")[["fig"]]() par(mfrow=c(1,2)) PlotNPS(TL84, 'Log10M', 'PreyAveragedTrophicLevel', ylim=c(1, 6), main='Prey-averaged') PlotNPS(TL84, 'Log10M', 'ChainAveragedTrophicLevel', ylim=c(1, 6), main='Chain-averaged') getOption("SweaveHooks")[["fig"]]() par(mfrow=c(2,2)) PlotMvN(TL84) PlotNvM(TL84) PlotBvM(TL84) PlotMvB(TL84) getOption("SweaveHooks")[["fig"]]() PlotRankNPS(TL84, 'Log10N') getOption("SweaveHooks")[["fig"]]() PlotRankNPS(TL84, 'Log10N', rank.by='M') getOption("SweaveHooks")[["fig"]]() PlotRankNPS(TL84, 'Log10N', rank.by='M', show.web=TRUE) getOption("SweaveHooks")[["fig"]]() PlotRankNPS(TL84, 'PreyAveragedTrophicLevel', rank.by='M') getOption("SweaveHooks")[["fig"]]() PlotRankNPS(TL84, 'PreyAveragedTrophicLevel', rank.by='M', log10.rank=TRUE) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(1,3)) PlotMvRankM(TL84) PlotNvRankN(TL84) PlotBvRankB(TL84) getOption("SweaveHooks")[["fig"]]() PlotNPSDistribution(TL84, 'Log10M') getOption("SweaveHooks")[["fig"]]() PlotNPSDistribution(TL84, 'Log10M', density.args=list(bw=3)) getOption("SweaveHooks")[["fig"]]() PlotNvM(TL84, col=1, pch=19, highlight.nodes=NULL) getOption("SweaveHooks")[["fig"]]() PlotNvM(TL84, col=1:56, pch=19, highlight.nodes=NULL) getOption("SweaveHooks")[["fig"]]() PlotNvM(TL84, colour.by='resolved.to', pch=19, highlight.nodes=NULL) getOption("SweaveHooks")[["fig"]]() colour.spec <- c(Species='purple3', Genus='green3', 'red3') PlotNvM(TL84, colour.by='resolved.to', colour.spec=colour.spec, pch=19, highlight.nodes=NULL) legend("topright", legend=names(colour.spec), pch=19, col=colour.spec) getOption("SweaveHooks")[["fig"]]() symbol.spec = c(Bacteria=21, Plantae=22, Chromista=23, Protozoa=24, Animalia=25, 19) colour.spec = c(Bacteria='purple3', Plantae='green3', Chromista='blue3', Protozoa='orange3', Animalia='red3', 'black') PlotNvM(TL84, symbol.by='kingdom', symbol.spec=symbol.spec, bg.by='kingdom', bg.spec=colour.spec, colour.by='kingdom', colour.spec=colour.spec, highlight.nodes=NULL) legend("topright", legend=names(colour.spec), pch=symbol.spec, col=colour.spec, pt.bg=colour.spec) getOption("SweaveHooks")[["fig"]]() symbol.spec = c(Bacteria=21, Plantae=22, Chromista=23, Protozoa=24, Animalia=25, 19) colour.spec = c(Bacteria='purple3', Plantae='green3', Chromista='blue3', Protozoa='orange3', Animalia='red3', 'black') PlotNvM(TL84, symbol.by='kingdom', symbol.spec=symbol.spec, bg.by='kingdom', bg.spec=colour.spec, colour.by='kingdom', colour.spec=colour.spec, highlight.nodes=NULL, show.web=FALSE) legend("topright", legend=names(colour.spec), pch=symbol.spec, col=colour.spec, pt.bg=colour.spec) models <- NvMLinearRegressions(TL84, class='kingdom') colours <- PlotLinearModels(models, colour.spec=colour.spec) getOption("SweaveHooks")[["fig"]]() PlotNvM(TL84, pch=NA, highlight.nodes=NULL) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(1,2)) options(cheddarTopAndRightTicks=FALSE) PlotNvM(TL84) options(cheddarTopAndRightTicks=TRUE) PlotNvM(TL84) getOption("SweaveHooks")[["fig"]]() PlotNvM(TL84, highlight.nodes=Cannibals) getOption("SweaveHooks")[["fig"]]() PlotNvM(TL84, highlight.nodes=IsolatedNodes) getOption("SweaveHooks")[["fig"]]() PlotNvM(TL84, highlight.nodes='Chaoborus punctipennis') getOption("SweaveHooks")[["fig"]]() PlotNvM(TL84, highlight.links=ResourceLargerThanConsumer) getOption("SweaveHooks")[["fig"]]() PlotNvM(TL84, highlight.nodes='Chaoborus punctipennis', highlight.links=TrophicLinksForNodes(TL84, 'Chaoborus punctipennis')) getOption("SweaveHooks")[["fig"]]() data(YthanEstuary) par(mfrow=c(1,2)) PlotNvM(YthanEstuary) PlotNvM(YthanEstuary, show.na=TRUE) getOption("SweaveHooks")[["fig"]]() PlotNvM(YthanEstuary, xlim=c(-10, 4), ylim=c(-10, 13), show.na=TRUE) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(2,2)) np <- NPS(TL84) np[1,'M'] <- NA PlotNvM(Community(nodes=np, trophic.links=TLPS(TL84), properties=CPS(TL84)), main='Node 1 M=NA', show.nodes.as='both', cex=2, show.na=TRUE) np <- NPS(TL84) np[1,'N'] <- NA PlotNvM(Community(nodes=np, trophic.links=TLPS(TL84), properties=CPS(TL84)), main='Node 1 N=NA', show.nodes.as='both', cex=2, show.na=TRUE) np <- NPS(TL84) np[1,'M'] <- NA np[1,'N'] <- NA PlotNvM(Community(nodes=np, trophic.links=TLPS(TL84), properties=CPS(TL84)), main='Node 1 M=NA and N=NA', show.nodes.as='both', cex=2, show.na=TRUE) np <- NPS(TL84) np[c(10, 20, 30, 40),'M'] <- NA np[c(10, 20, 30, 40),'N'] <- NA PlotNvM(Community(nodes=np, trophic.links=TLPS(TL84), properties=CPS(TL84)), main='Nodes 10, 20, 30 and 40 M=NA and N=NA', show.nodes.as='both', cex=2, show.na=TRUE) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(1,2)) PlotMvRankM(YthanEstuary) PlotMvRankM(YthanEstuary, show.na=TRUE) getOption("SweaveHooks")[["fig"]]() PlotTLPS(TL84, 'resource.Log10M', 'consumer.Log10M') getOption("SweaveHooks")[["fig"]]() PlotTLPS(TL84, 'resource.Log10M', 'consumer.Log10M', axes.limits.equal=TRUE) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(2,2)) PlotPredationMatrix(TL84) PlotMRvMC(TL84) PlotNCvNR(TL84) PlotBRvBC(TL84) getOption("SweaveHooks")[["fig"]]() PlotMRvMC(TL84) getOption("SweaveHooks")[["fig"]]() PlotMRvMC(TL84, colour.by='consumer.category', bg.by='consumer.category', symbol.by='consumer.category') SumMByClass(TL84) SumNByClass(TL84) SumBiomassByClass(TL84) SumMByClass(TL84, 'kingdom') SumNByClass(TL84, 'kingdom') SumBiomassByClass(TL84, 'kingdom') SumBiomassByClass(TL84) ApplyByClass(TL84, 'Biomass', 'category', sum) models <- NvMLinearRegressions(TL84) names(models) sapply(models, 'coef') models <- NvMLinearRegressions(TL84, class='phylum') names(models) sapply(models, is.null) data(BroadstoneStream) models <- NvMLinearRegressions(BroadstoneStream) sapply(models, is.null) NvMSlope(TL84) NvMIntercept(TL84) NvMSlopeAndIntercept(TL84) NvMSlopeByClass(TL84) NvMInterceptByClass(TL84) NvMSlopeAndInterceptByClass(TL84) NvMSlopeByClass(TL84, class='kingdom') NvMInterceptByClass(TL84, class='kingdom') NvMSlopeAndInterceptByClass(TL84, class='kingdom') getOption("SweaveHooks")[["fig"]]() data(TL86) par(mfrow=c(1,2)) PlotMvN(TL84, show.nodes.as='both', cex=2, xlim=c(-2, 10), ylim=c(-14, 0), highlight.nodes=NULL, highlight.links=NULL, main='') PlotMvN(TL86, show.nodes.as='both', cex=2, xlim=c(-2, 10), ylim=c(-14, 0), highlight.nodes=NULL, highlight.links=NULL, main='') title(main='Jonsson et al. (2005) AER, Fig. 3 (p 30)', outer=TRUE) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(1,2)) PlotMCvMR(TL84, xlim=c(-14, 0), ylim=c(-14, 0), main='') abline(a=0, b=1, lty=2) PlotMCvMR(TL86, xlim=c(-14, 0), ylim=c(-14, 0), main='') abline(a=0, b=1, lty=2) title(main='Jonsson et al. (2005) AER, Fig. 4 (p 33)', outer=TRUE) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(2,2)) PlotNvM(TL84, xlim=c(-14, 0), ylim=c(-2,10), show.web=FALSE, main='') PlotNvM(TL86, xlim=c(-14, 0), ylim=c(-2,10), show.web=FALSE, main='') PlotBvM(TL84, xlim=c(-14, 0), ylim=c(-8,2), show.web=FALSE, main='') PlotBvM(TL86, xlim=c(-14, 0), ylim=c(-8,2), show.web=FALSE, main='') title(main='Jonsson et al. (2005) AER, Fig. 5 (p 37)', outer=TRUE) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(2,2)) PlotNCvNR(TL84, xlim=c(0, 10), ylim=c(-2,10), main='') abline(a=0, b=1, lty=2) PlotNCvNR(TL86, xlim=c(0, 10), ylim=c(-2,10), main='') abline(a=0, b=1, lty=2) PlotBCvBR(TL84, xlim=c(-8, -2), ylim=c(-8, -2), main='') abline(a=0, b=1, lty=2) PlotBCvBR(TL86, xlim=c(-8, -2), ylim=c(-8, -2), main='') abline(a=0, b=1, lty=2) title(main='Jonsson et al. (2005) AER, Fig. 7 (p 47)', outer=TRUE) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(2,2)) TL84.no.iso <- RemoveIsolatedNodes(TL84) TL86.no.iso <- RemoveIsolatedNodes(TL86) tl84.levels <- floor(TrophicHeight(TL84.no.iso)) tl86.levels <- floor(TrophicHeight(TL86.no.iso)) PlotNPyramid(TL84.no.iso, level=tl84.levels, main='', ylab='Trophic height') PlotNPyramid(TL86.no.iso, level=tl86.levels, main='') PlotBPyramid(TL84.no.iso, level=tl84.levels, main='', ylab='Trophic height') PlotBPyramid(TL86.no.iso, level=tl86.levels, main='') title(main='Jonsson et al. (2005) AER, Fig. 8 (p 49)', outer=TRUE) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(2,2)) PlotNvRankN(TL84, xlim=c(0,60), ylim=c(-2, 10), main='') PlotNvRankN(TL86, xlim=c(0,60), ylim=c(-2, 10), main='') PlotBvRankB(TL84, xlim=c(0,60), ylim=c(-8, -2), main='') PlotBvRankB(TL86, xlim=c(0,60), ylim=c(-8, -2), main='') title(main='Jonsson et al. (2005) AER, Fig. 10 (p 57)', outer=TRUE) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(2,2)) PlotRankNPS(TL84, property='Log10N', rank.by='M', log10.rank=TRUE, xlim=c(0,2), ylim=c(-2, 10), ylab=Log10NLabel(TL84), main='') PlotRankNPS(TL86, property='Log10N', rank.by='M', log10.rank=TRUE, xlim=c(0,2), ylim=c(-2, 10), ylab=Log10NLabel(TL84), main='') PlotRankNPS(TL84, property='Log10Biomass', rank.by='M', log10.rank=TRUE, xlim=c(0,2), ylim=c(-8, -2), ylab=Log10BLabel(TL84), main='') PlotRankNPS(TL86, property='Log10Biomass', rank.by='M', log10.rank=TRUE, xlim=c(0,2), ylim=c(-8, -2), ylab=Log10BLabel(TL84), main='') title(main='Jonsson et al. (2005) AER, Fig. 11 (p 60)', outer=TRUE) getOption("SweaveHooks")[["fig"]]() PlotCommunityVCommunity <- function(a, b, property, xlim=NULL, ylim=NULL, ...) { a.nodes <- NP(a, 'node') b.nodes <- NP(b, 'node') all.nodes <- union(a.nodes, b.nodes) a.values <- NPS(a, property)[,property] names(a.values) <- a.nodes b.values <- NPS(b, property)[,property] names(b.values) <- b.nodes points <- PlaceMissingPoints(a.values[all.nodes], xlim, b.values[all.nodes], ylim) plot(points[,1], points[,2], xlim=xlim, ylim=ylim, ...) abline(a=0, b=1, lty=2) } par(mfrow=c(1,2)) PlotCommunityVCommunity(TL84, TL86, 'Log10N', xlim=c(-2,10), ylim=c(-2,10), xlab=~log[10]~(N~of~84), ylab=~log[10]~(N~of~86),pch=19) PlotCommunityVCommunity(TL84, TL86, 'Log10Biomass', xlim=c(-8,-2), ylim=c(-8,-2), xlab=~log[10]~(B~of~84), ylab=~log[10]~(B~of~86),pch=19) title(main='Jonsson et al. (2005) AER, Fig. 12 (p 61)', outer=TRUE) getOption("SweaveHooks")[["fig"]]() data(pHWebs) par(mfrow=c(2,2)) for(community in pHWebs[1:2]) { PlotNvM(community, xlim=c(-15, 10), ylim=c(-5,15), main='', highlight.nodes=NULL) text(-15, 13, with(CPS(community), paste(title, ', pH ', pH, sep='')), adj=0, cex=1.5) tlps <- TLPS(community, node.properties='M') tlps <- tlps[!is.na(tlps$resource.M) & !is.na(tlps$consumer.M),] interaction.strength <- log10( (tlps$consumer.M / tlps$resource.M)^0.75 ) plot(density(interaction.strength), xlim=c(-4,14), ylim=c(0,0.6), main='', xlab=~log[10]((M[C]/M[R])^0.75)) rug(interaction.strength) } title(main='Layer et al. (2010) AER, Fig. 6 (p 282)', outer=TRUE) getOption("SweaveHooks")[["fig"]]() data(BroadstoneStream) par(mfrow=c(1,2)) PlotMvN(BroadstoneStream, show.nodes.as='labels', label.cex=0.8, xlim=c(-2, 4.2), ylim=c(-6,2), main='', show.na=FALSE, highlight.links=NULL) abline(a=0, b=-1) tlps <- TLPS(BroadstoneStream, node.properties='M') lty <- rep(0, NumberOfTrophicLinks(BroadstoneStream)) lty[tlps$resource.M > tlps$consumer.M] <- 1 PlotMvN(BroadstoneStream, show.nodes.as='labels', label.cex=0.8, xlim=c(-2, 4.2), ylim=c(-6,2), main='', show.na=FALSE, highlight.links=NULL, link.lty=lty) abline(a=0, b=-1) title(main='Woodward et al. (2005) AER, Fig. 4 (p 108)', outer=TRUE) collection <- CommunityCollection(list(TL84, TL86, YthanEstuary)) table <- NvMTriTrophicTable(collection) print(round(table,2)) res <- lapply(list(TL84, TL86, YthanEstuary), function(community) { community <- RemoveNodes(community, remove=with(NPS(community), node[is.na(M) | is.na(N)])) community <- RemoveCannibalisticLinks(community) community <- RemoveIsolatedNodes(community) chains <- ThreeNodeChains(community, node.properties='M') MR <- chains$bottom.M MI <- chains$intermediate.M MC <- chains$top.M lp <- TLPS(community, node.properties='M') return (c('MR<=MI<=MC'=sum(MR<=MI & MI<=MC), 'MR<=MC<MI'=sum(MR<=MC & MC<MI), 'MI<MR<=MC'=sum(MI<MR & MR<=MC), 'MI<=MC<MR'=sum(MI<=MC & MC<MR), 'MC<MR<MI'=sum(MC<MR & MR<MI), 'MC<MI<MR'=sum(MC<MI & MI<MR), 'All 2-chains'=nrow(chains), 'MR<MC'=sum(lp$resource.M<lp$consumer.M), 'MR=MC'=sum(lp$resource.M==lp$consumer.M), 'MR>MC'=sum(lp$resource.M>lp$consumer.M), 'All links'=nrow(lp))) }) res <- do.call('cbind', res) colnames(res) <- c('TL84', 'TL86', 'Ythan Estuary') print(round(res,2)) getOption("SweaveHooks")[["fig"]]() par(mfrow=c(3,2)) for(community in list(TL84, TL86, YthanEstuary)) { community <- RemoveIsolatedNodes(community) pch <- rep(1, NumberOfNodes(community)) pch[IsIntermediateNode(community)] <- 20 pch[IsTopLevelNode(community)] <- 8 PlotNvM(community, col=1, highlight.nodes=NULL, show.web=FALSE, main='', pch=pch) PlotAuppervAlower(community, main='') } title(main='Cohen et al. (2009) PNAS, Fig. 1 (p 22336)', outer=TRUE) data(ChesapeakeBay) res <- NodeQuantitativeDescriptors(ChesapeakeBay, 'biomass.flow') print(round(res[1:6,],2)) res <- QuantitativeDescriptors(ChesapeakeBay, 'biomass.flow') print(round(res,3))
NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL
COPPosterior <- function ( marketDist, views, numSimulations = BLCOPOptions("numSimulations") ) { marketSimulations <- t(sampleFrom(marketDist, numSimulations)) subjSimulations <- sapply(views@viewDist, sampleFrom, n = numSimulations ) numViews <- length(views@viewDist) nullPick <- t(Null(t(views@pick))) pick <- views@pick impliedViews <- pick %*% marketSimulations complement <- nullPick %*% marketSimulations .innerChoiceSample <- function(conf) { sample(0:1, prob = c(1-conf, conf), numSimulations, replace = TRUE) } choices <- t(sapply(views@confidences, .innerChoiceSample)) combinedSimulations <- matrix(0, nrow = numViews, ncol = numSimulations) combinedSimulations[choices == 0] <- impliedViews[choices == 0] combinedSimulations[choices == 1] <- t(subjSimulations)[choices==1] impliedCopula <- array(dim = dim(impliedViews)) pooledSimulations <- array(dim = dim(combinedSimulations)) for(i in 1:nrow(impliedViews)) { cdf <- .empCDF(impliedViews[i,]) impliedCopula[i,] <- cdf(impliedViews[i,]) quant <- .empQuantile(combinedSimulations[i,]) pooledSimulations[i,] <- quant(impliedCopula[i,]) } rotMatrix <- solve(rbind(pick, nullPick)) result <- t(rotMatrix %*% rbind(pooledSimulations, complement)) colnames(result) <- assetSet(views) new("COPResult", views = views, marketDist = marketDist, posteriorSims = result) }
passed <- c(TRUE, TRUE, FALSE, TRUE) ages <- c(15, 18, 25, 14, 19) cmplxNums <- c(1+2i, 0+1i, 39+3i, 12+2i) names <- c("Bob", "Ted", "Carol", "Alice") x <- c(1,2,3,4,5,6,7,8) class(x) print(x) attr(x, "dim") <- c(2,4) print(x) class(x) attributes(x) attr(x, "dimnames") <- list(c("A1", "A2"), c("B1", "B2", "B3", "B4")) print(x) attr(x, "dim") <- NULL class(x) print(x) head(iris) unclass(iris) attributes(iris) set.seed(1234) fit <- kmeans(iris[1:4], 3) names(fit) unclass(fit) sapply(fit, class) x <- c(20, 30, 40) x[3] x[c(2,3)] x <- c(A=20, B=30, C=40) x[c(2,3)] x[c("B", "C")] fit[c(2,7)] fit[2] fit[[2]] fit$centers fit[[2]][1,] fit$centers$Petal.Width fit <- kmeans(iris[1:4], 3) means <- fit$centers library(reshape2) dfm <- melt(means) names(dfm) <- c("Cluster", "Measurement", "Centimeters") dfm$Cluster <- factor(dfm$Cluster) head(dfm) library(ggplot2) ggplot(data=dfm, aes(x=Measurement, y=Centimeters, group=Cluster)) + geom_point(size=3, aes(shape=Cluster, color=Cluster)) + geom_line(size=1, aes(color=Cluster)) + ggtitle("Profiles for Iris Clusters") for(i in 1:5) print(1:i) for(i in 5:1)print(1:i) pvalues <- c(.0867, .0018, .0054, .1572, .0183, .5386) results <- ifelse(pvalues <.05, "Significant", "Not Significant") results pvalues <- c(.0867, .0018, .0054, .1572, .0183, .5386) results <- vector(mode="character", length=length(pvalues)) for(i in 1:length(pvalues)){ if (pvalues[i] < .05) results[i] <- "Significant" else results[i] <- "Not Significant" } results f <- function(x, y, z=1){ result <- x + (2*y) + (3*z) return(result) } f(2,3,4) f(2,3) f(x=2, y=3) f(z=4, y=2, 3) args(f) x <- 2 y <- 3 z <- 4 f <- function(w){ z <- 2 x <- w*y*z return(x) } f(x) x y z x <- 5 myenv <- new.env() assign("x", "Homer", env=myenv) ls() ls(myenv) x get("x", env=myenv) myenv <- new.env() myenv$x <- "Homer" myenv$x parent.env(myenv) trim <- function(p){ trimit <- function(x){ n <- length(x) lo <- floor(n*p) + 1 hi <- n + 1 - lo x <- sort.int(x, partial = unique(c(lo, hi)))[lo:hi] } trimit } x <- 1:10 trim10pct <- trim(.1) y <- trim10pct(x) y trim20pct <- trim(.2) y <- trim20pct(x) y ls(environment(trim10pct)) get("p", env=environment(trim10pct)) makeFunction <- function(k){ f <- function(x){ print(x + k) } } g <- makeFunction(10) g (4) k <- 2 g (5) ls(environment(g)) environment(g)$k summary(women) fit <- lm(weight ~ height, data=women) summary(fit) class(women) class(fit) methods(summary) mymethod <- function(x, ...) UseMethod("mymethod") mymethod.a <- function(x) print("Using A") mymethod.b <- function(x) print("Using B") mymethod.default <- function(x) print("Using Default") x <- 1:5 y <- 6:10 z <- 10:15 class(x) <- "a" class(y) <- "b" mymethod(x) mymethod(y) mymethod(z) class(z) <- c("a", "b") mymethod(z) class(z) <- c("c", "a", "b") mymethod(z) set.seed(1234) mymatrix <- matrix(rnorm(10000000), ncol=10) accum <- function(x){ sums <- numeric(ncol(x)) for (i in 1:ncol(x)){ for(j in 1:nrow(x)){ sums[i] <- sums[i] + x[j,i] } } } system.time(accum(mymatrix)) system.time(colSums(mymatrix)) set.seed(1234) k <- 100000 x <- rnorm(k) y <- 0 system.time(for (i in 1:length(x)) y[i] <- x[i]^2) y <- numeric(k) system.time(for (i in 1:k) y[i] <- x[i]^2) y <- numeric(k) system.time(y <- x^2) library(foreach) library(doParallel) registerDoParallel(cores=4) eig <- function(n, p){ x <- matrix(rnorm(100000), ncol=100) r <- cor(x) eigen(r)$values } n <- 1000000 p <- 100 k <- 500 system.time( x <- foreach(i=1:k, .combine=rbind) %do% eig(n, p) ) system.time( x <- foreach(i=1:k, .combine=rbind) %dopar% eig(n, p) ) mtcars$Transmission <- factor(mtcars$a, levels=c(1,2), labels=c("Automatic", "Manual")) aov(mpg ~ Transmission, data=mtcars) head(mtcars[c("mpg", "Transmission")]) table(mtcars$Transmission) args(mad) debug(mad) mad(1:10) undebug(mad) f <- function(x, y){ z <- x + y g(z) } g <- function(x){ z <- round(x) h(z) } h <- function(x){ set.seed(1234) z <- rnorm(x) print(z) } options(error=recover) f(2,3) f(2, -3)
filter_trace_frequency_threshold <- function(eventlog, lower_threshold, upper_threshold, reverse){ if(is.null(lower_threshold) & is.null(upper_threshold)){ stop("Upper threshold or lower threshold must be defined") } if(is.na(lower_threshold)) lower_threshold <- -Inf if(is.na(upper_threshold)) upper_threshold <- Inf absolute <- NULL eventlog %>% trace_coverage("case") %>% filter(absolute >= lower_threshold, absolute <= upper_threshold) %>% pull(1) -> case_selection filter_case(eventlog, case_selection, reverse) }
x <- 5 if (x >= 5) { y <- TRUE } else { y <- FALSE }
primesieve <- function(sieved, unsieved) { p <- unsieved[1] n <- unsieved[length(unsieved)] if (p^2 > n) { return(c(sieved, unsieved)) } else { unsieved <- unsieved[unsieved %% p != 0] sieved <- c(sieved, p) return(primesieve(sieved, unsieved)) } }
colwise <- function(.fun, .cols = true, ...) { if (!is.function(.cols)) { .cols <- as.quoted(.cols) filter <- function(df) eval.quoted(.cols, df) } else { filter <- function(df) Filter(.cols, df) } dots <- list(...) function(df, ...) { stopifnot(is.data.frame(df)) df <- strip_splits(df) filtered <- filter(df) if (length(filtered) == 0) return(data.frame()) out <- do.call("lapply", c(list(filtered, .fun, ...), dots)) names(out) <- names(filtered) quickdf(out) } } catcolwise <- function(.fun, ...) { colwise(.fun, is.discrete, ...) } numcolwise <- function(.fun, ...) { colwise(.fun, is.numeric, ...) }
setMethodS3("exportFracBDiffSet", "AromaUnitFracBCnBinarySet", function(this, ref, ..., tags=NULL, overwrite=FALSE, rootPath="rawCnData", verbose=FALSE) { nbrOfFiles <- length(this) if (nbrOfFiles == 0L) { throw("Nothing to export. ", class(this)[1], " is empty: ", getFullName(this)) } nbrOfUnits <- nbrOfUnits(getOneFile(this)) chipType <- getChipType(this) if (inherits(ref, "AromaUnitFracBCnBinaryFile")) { refList <- rep(list(ref), nbrOfFiles) refSet <- AromaUnitFracBCnBinarySet(refList) refList <- NULL } if (inherits(ref, "AromaUnitFracBCnBinarySet")) { if (getChipType(ref) != chipType) { throw("Chip type of argument 'ref' does not match the data set: ", getChipType(ref), " != ", chipType) } df <- getOneFile(ref) if (nbrOfUnits(df) != nbrOfUnits) { throw("Number of units in argument 'ref' does not match the data set: ", nbrOfUnits(ref), " != ", nbrOfUnits) } refSet <- ref } else { throw("Argument 'ref' must be of class AromaUnitFracBCnBinary{File|Set}: ", class(ref)[1]) } tags <- Arguments$getTags(tags, collapse=",") verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "Calculating CN ratios") dataSet <- getFullName(this) verbose && cat(verbose, "Data set: ", dataSet) platform <- getPlatform(this) verbose && cat(verbose, "Platform: ", platform) chipType <- getChipType(this) verbose && cat(verbose, "Chip type: ", chipType) nbrOfFiles <- length(this) verbose && cat(verbose, "Number of files: ", nbrOfFiles) verbose && cat(verbose, "Reference set:") verbose && print(verbose, refSet) dataSetOut <- paste(c(dataSet, tags), collapse=",") verbose && cat(verbose, "Output data set: ", dataSetOut) chipTypeS <- getChipType(this, fullname=FALSE) outPath <- file.path(rootPath, dataSetOut, chipTypeS) outPath <- Arguments$getWritablePath(outPath) verbose && cat(verbose, "Output path: ", outPath) ratioTag <- "diff" typeTags <- paste(c(ratioTag, "fracB"), collapse=",") for (kk in seq_along(this)) { df <- this[[kk]] verbose && enter(verbose, sprintf("File %d ('%s') of %d", kk, getName(df), nbrOfFiles)) dfR <- refSet[[kk]] refName <- getFullName(dfR) refName <- gsub(",(fracB)", "", refName) refTag <- sprintf("ref=%s", refName) fullname <- getFullName(df) fullname <- gsub(",(fracB)", "", fullname) fullname <- paste(c(fullname, refTag, typeTags), collapse=",") filename <- sprintf("%s.asb", fullname) pathname <- file.path(outPath, filename) verbose && cat(verbose, "Pathname: ", pathname) if (!overwrite && isFile(pathname)) { verbose && cat(verbose, "Nothing to do. File already exists.") verbose && exit(verbose) next } verbose && enter(verbose, "Allocating (temporary) output file") pathnameT <- pushTemporaryFile(pathnameT, verbose=verbose) asb <- AromaUnitSignalBinaryFile$allocate(pathnameT, nbrOfRows=nbrOfUnits(df), platform=platform, chipType=chipType) verbose && print(verbose, asb) verbose && exit(verbose) verbose && enter(verbose, "Reading data from total file") beta <- extractMatrix(df, drop=TRUE, verbose=verbose) verbose && str(verbose, beta) verbose && exit(verbose) verbose && enter(verbose, "Calculating differences") betaR <- extractMatrix(dfR, drop=TRUE, verbose=verbose) verbose && str(verbose, betaR) .stop_if_not(length(betaR) == length(beta)) dBeta <- beta - betaR verbose && str(verbose, dBeta) beta <- betaR <- NULL verbose && exit(verbose) verbose && enter(verbose, "Updating temporary output file") asb[,1] <- dBeta dBeta <- NULL refFile <- list( dataSet=dataSet, fullName=getFullName(dfR), filename=getFilename(dfR), checksum=getChecksum(dfR) ) footer <- readFooter(asb) footer$srcFiles <- list( srcFile = list( dataSet=dataSet, fullName=getFullName(df), filename=getFilename(df), checksum=getChecksum(df) ), refFile = refFile ) writeFooter(asb, footer) footer <- refFile <- NULL verbose && exit(verbose) pathname <- popTemporaryFile(pathnameT, verbose=verbose) verbose && exit(verbose) verbose && exit(verbose) } verbose && enter(verbose, "Setting up output data sets") pattern <- sprintf("%s[.]asb$", typeTags) res <- AromaUnitFracBCnBinarySet$byPath(outPath, pattern=pattern) verbose && exit(verbose) verbose && exit(verbose) invisible(res) }, protected=TRUE)
library(imager) library(tidyverse) x <- load.image("inputs/bear2.png") load.image("inputs/bear.png") %>% grayscale() -> x x %>% cannyEdges() -> x_edges edge_mat <- drop(x_edges) class(edge_mat) <- "array" edge_mat <- edge_mat*1 df <- x %>% cannyEdges() %>% as.cimg() %>% as.data.frame() %>% filter(value == 1) %>% mutate(id = 1:nrow(.)) data <- df %>% select(x, y) ggplot(data) + geom_point(aes(x = x, y = y), color = "black") + scale_y_reverse() saveRDS(data, file = "bear.rds") sparse_points_giraffe <- tibble::tribble( ~"", ~"x", ~"y", "\"5479\"", "\"393\"", "\"893\"", "\"5623\"", "\"381\"", "\"963\"", "\"5800\"", "\"397\"", "\"1043\"", "\"6126\"", "\"365\"", "\"1105\"", "\"6189\"", "\"433\"", "\"1114\"", "\"7072\"", "\"534\"", "\"1529\"", "\"7705\"", "\"638\"", "\"1804\"", "\"8075\"", "\"629\"", "\"1988\"", "\"8652\"", "\"718\"", "\"2235\"", "\"9023\"", "\"880\"", "\"2303\"", "\"8596\"", "\"1053\"", "\"2216\"", "\"7923\"", "\"1129\"", "\"1912\"", "\"7682\"", "\"1118\"", "\"1792\"", "\"6749\"", "\"1261\"", "\"1381\"", "\"6182\"", "\"1323\"", "\"1110\"", "\"6143\"", "\"1409\"", "\"1105\"", "\"5737\"", "\"1360\"", "\"1013\"", "\"5639\"", "\"1374\"", "\"970\"", "\"5501\"", "\"1365\"", "\"903\"", "\"4778\"", "\"1592\"", "\"732\"", "\"2749\"", "\"1747\"", "\"431\"", "\"2657\"", "\"1485\"", "\"423\"", "\"3615\"", "\"1354\"", "\"549\"", "\"4465\"", "\"1228\"", "\"648\"", "\"2898\"", "\"1191\"", "\"450\"", "\"1352\"", "\"1180\"", "\"260\"", "\"575\"", "\"1207\"", "\"70\"", "\"117\"", "\"1133\"", "\"3\"", "\"759\"", "\"1000\"", "\"115\"", "\"1484\"", "\"991\"", "\"291\"", "\"2036\"", "\"884\"", "\"389\"", "\"1609\"", "\"777\"", "\"321\"", "\"621\"", "\"750\"", "\"81\"", "\"16\"", "\"643\"", "\"2\"", "\"602\"", "\"548\"", "\"77\"", "\"1512\"", "\"577\"", "\"298\"", "\"3584\"", "\"562\"", "\"545\"", "\"4500\"", "\"518\"", "\"650\"", "\"2849\"", "\"313\"", "\"444\"", "\"2758\"", "\"7\"", "\"433\"", "\"3317\"", "\"11\"", "\"508\"", "\"4947\"", "\"210\"", "\"785\"" ) sparse_points_stag <- tibble::tribble( ~V0, ~V1, ~V2, 1, 797.6, 1774.8055, 2, 672.2, 1695.061, 3, 575.4, 1538.5255, 4, 601.8, 1381.99, 5, 648, 1252.036, 6, 656.8, 1145.71, 7, 634.8, 1110.268, 8, 632.6, 1065.9655, 9, 531.4, 1042.3375, 10, 461, 944.872, 11, 458.8, 850.36, 12, 588.6, 897.616, 13, 623.8, 953.7325, 14, 637, 933.058, 15, 531.4, 829.6855, 16, 465.4, 779.476, 17, 425.8, 711.5455, 18, 340, 679.057, 19, 271.8, 661.336, 20, 219, 611.1265, 21, 177.2, 563.8705, 22, 252, 617.0335, 23, 326.8, 628.8475, 24, 265.2, 587.4985, 25, 230, 487.0795, 26, 225.6, 419.149, 27, 243.2, 433.9165, 28, 243.2, 478.219, 29, 278.4, 552.0565, 30, 280.6, 484.126, 31, 269.6, 368.9395, 32, 304.8, 233.0785, 33, 335.6, 162.1945, 34, 311.4, 301.009, 35, 304.8, 410.2885, 36, 346.6, 333.4975, 37, 331.2, 448.684, 38, 329, 516.6145, 39, 355.4, 587.4985, 40, 379.6, 501.847, 41, 397.2, 428.0095, 42, 467.6, 348.265, 43, 432.4, 436.87, 44, 403.8, 522.5215, 45, 408.2, 575.6845, 46, 443.4, 658.3825, 47, 522.6, 746.9875, 48, 551.2, 770.6155, 49, 531.4, 670.1965, 50, 562.2, 714.499, 51, 577.6, 749.941, 52, 604, 817.8715, 53, 659, 829.6855, 54, 698.6, 862.174, 55, 733.8, 897.616, 56, 738.2, 933.058, 57, 760.2, 936.0115, 58, 786.6, 938.965, 59, 808.6, 936.0115, 60, 819.6, 906.4765, 61, 843.8, 876.9415, 62, 953.8, 806.0575, 63, 1011, 782.4295, 64, 1035.2, 723.3595, 65, 1061.6, 664.2895, 66, 1070.4, 720.406, 67, 1059.4, 755.848, 68, 1066, 767.662, 69, 1094.6, 732.22, 70, 1125.4, 696.778, 71, 1151.8, 587.4985, 72, 1114.4, 531.382, 73, 1070.4, 475.2655, 74, 1079.2, 460.498, 75, 1094.6, 490.033, 76, 1121, 516.6145, 77, 1138.6, 516.6145, 78, 1156.2, 469.3585, 79, 1136.4, 428.0095, 80, 1114.4, 371.893, 81, 1156.2, 416.1955, 82, 1178.2, 490.033, 83, 1195.8, 581.5915, 84, 1228.8, 522.5215, 85, 1233.2, 430.963, 86, 1217.8, 371.893, 87, 1206.8, 324.637, 88, 1237.6, 380.7535, 89, 1257.4, 419.149, 90, 1244.2, 309.8695, 91, 1222.2, 174.0085, 92, 1264, 259.66, 93, 1281.6, 357.1255, 94, 1286, 419.149, 95, 1286, 498.8935, 96, 1279.4, 555.01, 97, 1312.4, 501.847, 98, 1314.6, 436.87, 99, 1327.8, 428.0095, 100, 1336.6, 460.498, 101, 1323.4, 546.1495, 102, 1288.2, 593.4055, 103, 1244.2, 631.801, 104, 1189.2, 699.7315, 105, 1101.2, 791.29, 106, 997.8, 847.4065, 107, 947.2, 900.5695, 108, 918.6, 927.151, 109, 929.6, 947.8255, 110, 956, 918.2905, 111, 1096.8, 856.267, 112, 1101.2, 924.1975, 113, 1070.4, 1000.9885, 114, 978, 1051.198, 115, 929.6, 1060.0585, 116, 920.8, 1092.547, 117, 912, 1110.268, 118, 912, 1145.71, 119, 909.8, 1219.5475, 120, 934, 1322.92, 121, 973.6, 1429.246, 122, 984.6, 1568.0605, 123, 931.8, 1680.2935, 124, 832.8, 1765.945 ) sparse_points_longhorn <- tibble::tribble( ~V1, ~V2, ~V3, 1L, 148.6, 233.366333333333, 2L, 137.6, 232.790666666667, 3L, 126.6, 218.399, 4L, 125.133333333333, 203.431666666667, 5L, 129.533333333333, 194.796666666667, 6L, 129.533333333333, 185.298166666667, 7L, 123.666666666667, 172.6335, 8L, 116.333333333333, 157.954, 9L, 112.666666666667, 148.4555, 10L, 105.333333333333, 150.470333333333, 11L, 89.2, 149.606833333333, 12L, 81.1333333333333, 144.713666666667, 13L, 77.4666666666666, 136.078666666667, 14L, 87.7333333333333, 131.761166666667, 15L, 89.9333333333333, 128.882833333333, 16L, 77.4666666666666, 123.414, 17L, 60.6, 109.598, 18L, 51.8, 99.8116666666667, 19L, 40.8, 92.9036666666667, 20L, 23.2, 89.7375, 21L, 9.26666666666667, 87.7226666666667, 22L, 4.86666666666666, 83.1173333333333, 23L, 5.59999999999999, 77.0728333333333, 24L, 21.7333333333333, 75.6336666666667, 25L, 32.7333333333333, 77.3606666666667, 26L, 45.9333333333333, 80.8146666666667, 27L, 56.9333333333333, 86.8591666666667, 28L, 67.2, 92.0401666666667, 29L, 76, 98.3725, 30L, 85.5333333333333, 103.265666666667, 31L, 98.7333333333333, 109.885833333333, 32L, 109, 113.339833333333, 33L, 115.6, 113.627666666667, 34L, 121.466666666667, 108.446666666667, 35L, 139.066666666667, 106.431833333333, 36L, 162.533333333333, 106.144, 37L, 178.666666666667, 108.446666666667, 38L, 185.266666666667, 113.339833333333, 39L, 188.933333333333, 114.779, 40L, 195.533333333333, 113.052, 41L, 206.533333333333, 108.158833333333, 42L, 217.533333333333, 103.841333333333, 43L, 228.533333333333, 97.2211666666667, 44L, 241.733333333333, 89.7375, 45L, 254.933333333333, 83.1173333333333, 46L, 276.2, 79.0876666666666, 47L, 294.533333333333, 81.1025, 48L, 293.8, 84.5565, 49L, 291.6, 90.3131666666667, 50L, 274, 91.7523333333333, 51L, 266.666666666667, 92.9036666666667, 52L, 252.733333333333, 101.538666666667, 53L, 239.533333333333, 109.022333333333, 54L, 229.266666666667, 119.384333333333, 55L, 219, 126.580166666667, 56L, 210.933333333333, 130.322, 57L, 210.933333333333, 133.200333333333, 58L, 218.266666666667, 134.927333333333, 59L, 222.666666666667, 140.971833333333, 60L, 219, 146.440666666667, 61L, 210.2, 150.1825, 62L, 194.8, 150.758166666667, 63L, 186, 148.4555, 64L, 183.8, 153.924333333333, 65L, 180.133333333333, 166.013333333333, 66L, 172.066666666667, 180.980666666667, 67L, 168.4, 187.025166666667, 68L, 169.866666666667, 195.0845, 69L, 172.8, 204.295166666667, 70L, 172.066666666667, 216.384166666667, 71L, 160.333333333333, 232.790666666667, 72L, 151.533333333333, 232.790666666667 ) dragonfly <- tibble::tribble( ~V0, ~V1, ~V2, 1, 313.6, 561.374666666667, 2, 307.44, 561.374666666667, 3, 298.64, 562.2345, 4, 300.4, 553.636166666667, 5, 295.12, 533.000166666667, 6, 289.84, 502.906, 7, 295.12, 493.447833333333, 8, 296.88, 459.0545, 9, 301.28, 416.922666666667, 10, 303.04, 392.847333333333, 11, 298.64, 382.529333333333, 12, 299.52, 367.052333333333, 13, 302.16, 360.173666666667, 14, 301.28, 342.117166666667, 15, 298.64, 331.799166666667, 16, 299.52, 312.023, 17, 299.52, 305.144333333333, 18, 300.4, 282.788666666667, 19, 297.76, 268.1715, 20, 295.12, 256.133833333333, 21, 296, 244.956, 22, 297.76, 238.077333333333, 23, 296.88, 232.0585, 24, 291.6, 236.357666666667, 25, 289.84, 244.956, 26, 289.84, 250.974833333333, 27, 289.84, 258.713333333333, 28, 288.08, 273.3305, 29, 288.08, 283.6485, 30, 286.32, 287.087833333333, 31, 270.48, 291.387, 32, 246.72, 299.1255, 33, 227.36, 304.2845, 34, 179.84, 307.723833333333, 35, 149.04, 303.424666666667, 36, 120, 302.564833333333, 37, 85.68, 298.265666666667, 38, 52.24, 288.8075, 39, 28.48, 276.769833333333, 40, 13.52, 260.433, 41, 25.84, 249.255166666667, 42, 46.96, 238.937166666667, 43, 73.36, 236.357666666667, 44, 99.76, 232.918333333333, 45, 127.04, 231.198666666667, 46, 171.92, 233.778166666667, 47, 206.24, 226.039666666667, 48, 237.04, 221.7405, 49, 222.96, 218.301166666667, 50, 207.12, 218.301166666667, 51, 182.48, 219.161, 52, 157.84, 214.861833333333, 53, 124.4, 206.2635, 54, 96.24, 196.805333333333, 55, 71.6, 182.188166666667, 56, 43.44, 164.131666666667, 57, 17.92, 146.935, 58, 11.76, 128.018666666667, 59, 17.92, 117.700666666667, 60, 55.76, 113.4015, 61, 94.48, 121.999833333333, 62, 129.68, 133.177666666667, 63, 156.96, 143.495666666667, 64, 179.84, 148.654666666667, 65, 205.36, 154.6735, 66, 227.36, 162.412, 67, 238.8, 164.9915, 68, 231.76, 143.495666666667, 69, 221.2, 138.336666666667, 70, 219.44, 131.458, 71, 224.72, 131.458, 72, 237.92, 139.1965, 73, 247.6, 165.851333333333, 74, 266.08, 171.010333333333, 75, 280.16, 169.290666666667, 76, 283.68, 160.692333333333, 77, 259.92, 148.654666666667, 78, 255.52, 134.897333333333, 79, 251.12, 115.981, 80, 246.72, 103.943333333333, 81, 241.44, 97.0646666666667, 82, 244.96, 92.7655, 83, 249.36, 97.0646666666667, 84, 253.76, 105.663, 85, 259.04, 116.840833333333, 86, 264.32, 139.1965, 87, 283.68, 152.094, 88, 286.32, 152.953833333333, 89, 299.52, 143.495666666667, 90, 301.28, 135.757166666667, 91, 290.72, 134.0375, 92, 281.92, 134.0375, 93, 279.28, 124.579333333333, 94, 283.68, 115.981, 95, 289.84, 112.541666666667, 96, 294.24, 108.2425, 97, 293.36, 96.2048333333333, 98, 300.4, 106.522833333333, 99, 308.32, 108.2425, 100, 318, 108.2425, 101, 325.92, 95.345, 102, 323.28, 108.2425, 103, 330.32, 115.121166666667, 104, 336.48, 118.5605, 105, 338.24, 133.177666666667, 106, 334.72, 134.0375, 107, 331.2, 135.757166666667, 108, 322.4, 134.0375, 109, 319.76, 136.617, 110, 319.76, 142.635833333333, 111, 332.08, 154.6735, 112, 357.6, 142.635833333333, 113, 359.36, 127.158833333333, 114, 362, 114.261333333333, 115, 365.52, 107.382666666667, 116, 371.68, 99.6441666666666, 117, 372.56, 92.7655, 118, 377.84, 95.345, 119, 376.96, 102.223666666667, 120, 371.68, 109.962166666667, 121, 368.16, 119.420333333333, 122, 366.4, 131.458, 123, 362.88, 146.075166666667, 124, 336.48, 161.552166666667, 125, 336.48, 168.430833333333, 126, 347.92, 171.870166666667, 127, 373.44, 166.711166666667, 128, 377.84, 147.794833333333, 129, 382.24, 141.776, 130, 397.2, 133.177666666667, 131, 400.72, 135.757166666667, 132, 398.96, 138.336666666667, 133, 393.68, 140.916166666667, 134, 384.88, 146.935, 135, 382.24, 162.412, 136, 383.12, 164.9915, 137, 408.64, 156.393166666667, 138, 426.24, 153.813666666667, 139, 457.04, 146.075166666667, 140, 491.36, 135.757166666667, 141, 525.68, 124.579333333333, 142, 562.64, 117.700666666667, 143, 589.92, 116.840833333333, 144, 605.76, 125.439166666667, 145, 604, 136.617, 146, 594.32, 152.953833333333, 147, 560, 177.889, 148, 512.48, 201.964333333333, 149, 481.68, 214.002, 150, 437.68, 220.020833333333, 151, 417.44, 220.020833333333, 152, 394.56, 218.301166666667, 153, 377.84, 217.441333333333, 154, 394.56, 226.039666666667, 155, 416.56, 229.479, 156, 450.88, 235.497833333333, 157, 498.4, 234.638, 158, 538, 238.077333333333, 159, 571.44, 242.3765, 160, 594.32, 257.8535, 161, 599.6, 266.451833333333, 162, 587.28, 281.928833333333, 163, 556.48, 294.826333333333, 164, 522.16, 301.705, 165, 483.44, 306.004166666667, 166, 454.4, 306.864, 167, 411.28, 307.723833333333, 168, 383.12, 304.2845, 169, 364.64, 298.265666666667, 170, 350.56, 293.106666666667, 171, 341.76, 291.387, 172, 333.84, 289.667333333333, 173, 332.08, 283.6485, 174, 329.44, 266.451833333333, 175, 326.8, 247.5355, 176, 321.52, 233.778166666667, 177, 318.88, 243.236333333333, 178, 321.52, 251.834666666667, 179, 320.64, 268.1715, 180, 316.24, 278.4895, 181, 314.48, 285.368166666667, 182, 315.36, 294.826333333333, 183, 316.24, 312.023, 184, 317.12, 328.359833333333, 185, 314.48, 337.818, 186, 312.72, 353.295, 187, 316.24, 365.332666666667, 188, 316.24, 385.968666666667, 189, 311.84, 391.127666666667, 190, 313.6, 407.4645, 191, 316.24, 424.661166666667, 192, 315.36, 447.876666666667, 193, 315.36, 473.671666666667, 194, 318, 495.1675, 195, 320.64, 507.205166666667, 196, 318.88, 517.523166666667, 197, 317.12, 526.981333333333, 198, 315.36, 545.037833333333, 199, 312.72, 552.776333333333, 200, 314.48, 561.374666666667 ) bear <- tibble::tribble( ~V0, ~V1, ~V2, 1, 128.171428571429, 219.8836, 2, 114.971428571429, 220.7372, 3, 98.6285714285714, 220.3104, 4, 86.0571428571428, 216.4692, 5, 81.0285714285714, 208.7868, 6, 82.2857142857143, 196.4096, 7, 81.6571428571428, 190.0076, 8, 77.8857142857143, 175.4964, 9, 74.1142857142857, 169.5212, 10, 59.6571428571428, 177.2036, 11, 50.8571428571429, 190.4344, 12, 52.1142857142857, 198.1168, 13, 56.5142857142857, 204.092, 14, 54.6285714285714, 215.6156, 15, 40.8, 213.4816, 16, 28.8571428571429, 201.1044, 17, 21.9428571428571, 182.752, 18, 23.2, 172.5088, 19, 30.7428571428571, 161.8388, 20, 37.0285714285714, 149.8884, 21, 36.4, 134.5236, 22, 33.2571428571429, 117.8784, 23, 37.0285714285714, 100.3796, 24, 47.7142857142857, 80.7468, 25, 71.6, 61.9676, 26, 106.171428571429, 47.8832, 27, 123.142857142857, 47.4564, 28, 167.142857142857, 50.0172, 29, 180.342857142857, 50.8708, 30, 193.542857142857, 47.8832, 31, 214.914285714286, 47.4564, 32, 238.8, 40.6276, 33, 265.2, 32.0916, 34, 276.514285714286, 29.104, 35, 279.028571428571, 26.1164, 36, 287.2, 28.6772, 37, 293.485714285714, 30.3844, 38, 307.942857142857, 29.104, 39, 316.114285714286, 35.9328, 40, 327.428571428571, 38.9204, 41, 338.742857142857, 43.1884, 42, 338.114285714286, 53.8584, 43, 333.085714285714, 54.712, 44, 326.8, 57.6996, 45, 329.314285714286, 61.5408, 46, 329.942857142857, 63.6748, 47, 324.285714285714, 65.8088, 48, 318.628571428571, 66.2356, 49, 299.142857142857, 75.1984, 50, 293.485714285714, 76.9056, 51, 289.085714285714, 82.0272, 52, 286.571428571429, 83.3076, 53, 269.6, 89.7096, 54, 250.114285714286, 100.8064, 55, 248.857142857143, 109.3424, 56, 245.085714285714, 125.5608, 57, 232.514285714286, 138.7916, 58, 224.342857142857, 145.1936, 59, 220.571428571429, 158.4244, 60, 219.314285714286, 173.3624, 61, 220.571428571429, 187.8736, 62, 220.571428571429, 194.7024, 63, 226.857142857143, 200.2508, 64, 240.057142857143, 202.8116, 65, 245.085714285714, 204.5188, 66, 248.857142857143, 211.3476, 67, 248.228571428571, 213.9084, 68, 237.542857142857, 215.6156, 69, 219.942857142857, 215.6156, 70, 211.142857142857, 215.1888, 71, 199.828571428571, 213.9084, 72, 195.428571428571, 210.0672, 73, 192.914285714286, 200.6776, 74, 190.4, 185.3128, 75, 186.628571428571, 186.5932, 76, 180.971428571429, 194.2756, 77, 174.057142857143, 200.6776, 78, 174.685714285714, 205.7992, 79, 184.742857142857, 209.6404, 80, 187.885714285714, 213.4816, 81, 185.371428571429, 218.1764, 82, 171.542857142857, 218.6032, 83, 161.485714285714, 214.762, 84, 153.314285714286, 210.0672, 85, 148.914285714286, 199.3972, 86, 149.542857142857, 190.4344, 87, 159.6, 183.1788, 88, 160.857142857143, 163.9728, 89, 161.485714285714, 156.2904, 90, 167.142857142857, 142.206, 91, 172.8, 134.5236, 92, 169.657142857143, 131.9628, 93, 161.485714285714, 141.3524, 94, 157.714285714286, 149.8884, 95, 145.771428571429, 155.4368, 96, 133.2, 158.4244, 97, 121.257142857143, 157.144, 98, 117.485714285714, 172.082, 99, 113.085714285714, 184.4592, 100, 114.971428571429, 193.422, 101, 117.485714285714, 201.958, 102, 126.914285714286, 206.226, 103, 133.2, 211.7744, 104, 133.2, 216.4692, 105, 129.428571428571, 219.8836 ) sparse_points2 <- bear %>% select(2:3) %>% set_names(c("x", "y")) ggplot(sparse_points2, aes(x,y)) + geom_polygon() + scale_y_reverse() + theme_void() saveRDS(sparse_points2, "sparse_bear_points.rds") library(TSP) tsp <- TSP(dist(data)) tsp <- insert_dummy(tsp, label = "cut") solve_TSP(tsp, method = "arbitrary_insertion", control = "two_opt") %>% as.integer() -> solution data_to_plot <- data[solution,] ggplot(data_to_plot, aes(x,y)) + geom_path() + scale_y_reverse() + theme_void() set.seed(123) points_sparse <- data_to_plot %>% tibble::rowid_to_column("id") %>% sample_n(100) %>% arrange(id) ggplot(points_sparse) + geom_point(aes(x = x, y = y), color = "black") + scale_y_reverse() ggplot(points_sparse, aes(x,y)) + geom_path() + scale_y_reverse() + theme_void()
context("ndigest") library(digest) test_that("ndigest works for overloaded and regular classes",{ expect_false(isTRUE(all.equal(ndigest(kcs20[[1]]),digest(kcs20[[1]])))) expect_equal(ndigest(''),digest('')) skip_on_cran() expect_equal(ndigest(kcs20[[1]]),"4c045b0343938259cd9986494fc1c2b0") expect_equal(ndigest(read.neuron('testdata/neuron/EBT7R.am')), "a84b2255bb21e35d7906c756e7d14e47") tf=tempfile('kcs20fh') tf2=tempfile('kcs20fh') dir.create(tf) dir.create(tf2) on.exit(unlink(c(tf,tf2),recursive=TRUE)) expect_is(kcs20fh<-as.neuronlistfh(kcs20, dbdir=file.path(tf,'data')),'neuronlistfh') expect_is(kcs20fh2<-as.neuronlistfh(kcs20, dbdir=file.path(tf2,'data')),'neuronlistfh') expect_equal(ndigest(kcs20fh), ndigest(kcs20fh2)) write.neuronlistfh(kcs20fh,file=file.path(tf,'kcs20fh.rds')) write.neuronlistfh(kcs20fh,file=file.path(tf2,'kcs20fh2.rds')) expect_equal(ndigest(kcs20fh), "fb6338dfd6a5adea73bae4cf4efff1a8") kcs20fh3=read.neuronlistfh(file.path(tf,'kcs20fh.rds')) kcs20fh4=read.neuronlistfh(file.path(tf2,'kcs20fh2.rds')) expect_equal(ndigest(kcs20fh3), ndigest(kcs20fh)) expect_equal(ndigest(kcs20fh3), ndigest(kcs20fh4)) })
table.RollingPeriods<- table.TrailingPeriods <- function (R, periods = subset(c(12,36,60), c(12,36,60) < length(as.matrix(R[,1]))), FUNCS=c("mean","sd"), funcs.names = c("Average", "Std Dev"), digits = 4, ...) { R = checkData(R) columns = ncol(R) columnnames = colnames(R) freq = periodicity(R) freq.lab = freq$label if(length(FUNCS) != length(funcs.names)) { warning("The length of the names vector is unequal to the length of the functions vector, so using FUNCS for naming.") funcs.names = NA } if(is.na(funcs.names[1])) funcs.names = FUNCS for(column in 1:columns) { valueNames = vector('character', 0) values = vector('numeric', 0) column.data = na.omit(R[,column,drop=FALSE]) for(FUNC in FUNCS) { func.name = funcs.names[grep(FUNC, FUNCS)] for(period in periods) { values = c(values, apply(as.matrix(last(column.data, period)), FUN = FUNC, ..., MARGIN = 2)) valueNames = c(valueNames,paste("Last", period, freq.lab, func.name, sep=" ")) } } if(column == 1) { resultingtable = data.frame(Value = values, row.names = valueNames) } else { nextcolumn = data.frame(Value = values, row.names = valueNames) resultingtable = cbind(resultingtable, nextcolumn) } } colnames(resultingtable) = columnnames ans = base::round(resultingtable, digits) ans } table.TrailingPeriodsRel <- function (R, Rb, periods = subset(c(12,36,60), c(12,36,60)< length(as.matrix(R[,1]))), FUNCS=c("cor","CAPM.beta"), funcs.names = c("Correlation", "Beta"), digits = 4, ... ) { R = checkData(R) Rb = checkData(Rb) columns = ncol(R) columns.b = ncol(Rb) columnnames = colnames(R) columnnames.b = colnames(Rb) freq = periodicity(R) freq.lab = freq$label if(length(FUNCS) != length(funcs.names)) { warning("The length of the names vector is unequal to the length of the functions vector, so using FUNCS for naming.") funcs.names = NA } if(is.na(funcs.names[1])) funcs.names = FUNCS for(column in 1:columns) { for(column.b in 1:columns.b){ valueNames = vector('character', 0) values = vector('numeric', 0) merged.data = na.omit(merge(R[,column,drop=FALSE],Rb[,column.b,drop=FALSE])) for(FUNC in FUNCS) { func.name = funcs.names[grep(FUNC, FUNCS)] for(period in periods) { values = c(values, apply(last(merged.data[,1,drop=FALSE], period), FUN = FUNC, last(merged.data[,2,drop=FALSE], period), ..., MARGIN = 2)) valueNames = c(valueNames,paste("Last", period, freq.lab, func.name, "to", columnnames.b[column.b], sep=" ")) } } if(column == 1) { resultingtable = data.frame(Value = values, row.names = valueNames) } else { nextcolumn = data.frame(Value = values, row.names = valueNames) resultingtable = cbind(resultingtable, nextcolumn) } } } colnames(resultingtable) = columnnames ans = base::round(resultingtable, digits) ans }
rs_addin_r_make <- function(r_args = list()) { r_make(r_args = r_args) } rs_addin_r_outdated <- function(r_args = list(), .print = TRUE) { out <- r_outdated(r_args = r_args) if (.print) { print(out) } else { out } } rs_addin_r_vis_drake_graph <- function(r_args = list(), .print = TRUE) { assert_pkg("visNetwork") requireNamespace("visNetwork") out <- r_vis_drake_graph(r_args = r_args) if (.print) { print(out) } else { out } } rs_addin_loadd <- function(context = NULL) { assert_pkg("rstudioapi") context <- context %|||% rstudioapi::getActiveDocumentContext() target <- rs_get_symbol_at_cursor(context) if (is.null(target)) { return() } cache <- getOption("rstudio_drake_cache") %||% drake_cache() cache <- decorate_storr(cache) cli_msg( "Loading target", target, "into global environment from cache", cache$path ) loadd( list = target, envir = globalenv(), cache = cache ) } rs_get_symbol_at_cursor <- function(context) { if (identical(context$id, " return(NULL) } cursor_pos <- context$selection[[1]]$range$start cursor_line <- cursor_pos[1] cursor_column <- cursor_pos[2] r_symbol_pattern <- "[.A-Za-z][.A-Za-z0-9_]+" line_symbols <- gregexpr( text = context$contents[cursor_line], pattern = r_symbol_pattern ) match_starts <- line_symbols[[1]] match_ends <- match_starts + attr(x = line_symbols[[1]], "match.length") - 1 match_index <- which( cursor_column >= match_starts & cursor_column <= match_ends ) if (length(match_index) == 0) { cli_msg( "Could not find object name at cursor position.", cli_sym = cli::col_red(cli::symbol$cross) ) return(NULL) } substr( context$contents[cursor_line], start = match_starts[match_index], stop = match_ends[match_index] ) }
groupsubsetselection <- function(y,x,nvarmax,nbest,nb,consind,conslb,ngv=rep(2,30)) { if (length(consind)!=length(conslb)) stop('Check constraint indicator vector and lower bound vector!') if (length(consind)!=dim(x)[2]) stop('Check consind or library!') ng <- length(ngv) ncase <- length(y) ntotalvars <- dim(x)[2] - nb if (sum(ngv)!=ntotalvars) stop('Arguments fault!') all <- (nvarmax+1)*nvarmax/2 wtslen <- (all*max(ngv)+nb*nvarmax)*nbest out <- .Fortran("gss",as.double(y),as.double(t(x)),as.integer(consind), as.double(conslb),as.integer(ncase),as.integer(ntotalvars),as.integer(nb),as.integer(nvarmax),as.integer(nbest),as.integer(ng),as.integer(ngv),groups = integer(all*nbest),rss = double(nvarmax*nbest),wts = double(wtslen), as.integer(wtslen), comptime=double(1)) vars <- matrix(0,all*max(ngv)+nb*nvarmax,nbest) nvars <- matrix(0,nvarmax,nbest) l1 <- c(0,cumsum((1:nvarmax)*max(ngv)+nb))+1 for (i in 1:nvarmax) { for (j in 1:nbest) { g <- out$groups[(sum(0:(i-1))*nbest+(j-1)*i+1):(sum(0:(i-1))*nbest+j*i)] g <- g[which(g>0)] if(length(g)>0) { g <- sort(g,decreasing=F) tmpvars <- sort(getvars.gss_ro(ngv,g),decreasing=F) vars[l1[i]:(l1[i]+nb+length(tmpvars)-1),j] <- c(1:nb,tmpvars+nb) nvars[i,j] <- nb+length(tmpvars)} } } r <- list(groups = out$groups,rss = out$rss, coef = matrix(out$wts,ncol=nbest), vars=vars, nvars=nvars, comptime = out$comptime) r } getvars.gss_ro <- function(nos,idx) { t <- c(0,cumsum(nos))+1 s <- NULL for(i in idx) s<-c(s,t[i]:(t[i+1]-1)) s }
context("call_function") test_that("nested event loops", { sleeper <- function(x) { Sys.sleep(x); Sys.getpid() } afun1 <- async(function(x) { x; call_function(sleeper, args = list(x)) }) afun2 <- async(function(x1, x2) { x1; x2 p1 <- afun1(x1) p2 <- delay(0)$then(function() { synchronise(afun1(x2)) }) when_all(p1, p2) }) res <- synchronise(afun2(1, 2)) expect_equal(length(res), 2) expect_true(res[[1]]$result %in% async_env$worker_pool$list_workers()$pid) expect_true(res[[2]]$result %in% async_env$worker_pool$list_workers()$pid) }) test_that("successful call", { afun <- async(function(x) { call_function(function() 100)$ then(function(x) x$result) }) res <- synchronise(afun()) expect_identical(res, 100) }) test_that("successful calls", { afun <- async(function(x) { when_all( call_function(function() Sys.getpid()), call_function(function() Sys.getpid()), call_function(function() Sys.getpid()), call_function(function() Sys.getpid()) ) }) res <- synchronise(afun()) expect_true(is.integer(viapply(res, "[[", "result"))) }) test_that("calls that error", { skip_without_package("processx", "3.4.1.9001") afun <- async(function(x) { when_all( call_function(function() Sys.getpid()), call_function(function() Sys.getpid()), call_function(function() Sys.getpid()), call_function(function() stop("nope")) ) }) expect_error(synchronise(afun()), "nope", class = "error") }) test_that("calls that crash", { skip_without_package("processx", "3.4.1.9001") afun <- async(function(x) { when_all( call_function(function() Sys.getpid()), call_function(function() Sys.getpid()), call_function(function() Sys.getpid()), call_function(function() asNamespace("callr")$crash()) ) }) err <- tryCatch(synchronise(afun()), error = function(x) x) expect_true( grepl("R session crashed with exit code", err$message) || grepl("R session closed the process connection", err$message)) afun <- async(function(x) { when_all( call_function(function() asNamespace("callr")$crash()), call_function(function() asNamespace("callr")$crash()), call_function(function() asNamespace("callr")$crash()), call_function(function() asNamespace("callr")$crash()) ) }) err <- tryCatch(synchronise(afun()), error = function(x) x) expect_true( grepl("R session crashed with exit code", err$message) || grepl("R session closed the process connection", err$message)) }) test_that("handling call errors", { skip_without_package("processx", "3.4.1.9001") worker_pid <- async(function() { call_function(function() Sys.getpid())$then(function(x) x$result) }) afun <- async(function(x) { when_all( worker_pid(), worker_pid(), worker_pid(), call_function(function() stop("nope"))$ catch(error = function(e) e) ) }) res <- synchronise(afun()) expect_true(is_count(res[[1]])) expect_true(is_count(res[[2]])) expect_true(is_count(res[[3]])) expect_s3_class(res[[4]], "async_rejected") expect_match(res[[4]]$message, "nope") }) test_that("mix calls with others", { skip_on_cran() px <- asNamespace("processx")$get_tool("px") afun <- async(function() { when_all( delay = delay(1/1000)$ then(function() 1), http = http_get(http$url("/status/418"))$ then(function(x) x$status_code), process = run_process(px, c("outln", "foobar"))$ then(function(x) str_trim(x$stdout)), r_process = run_r_process(function() 2)$ then(function(x) x$result), call = call_function(function() 3)$ then(function(x) x$result) ) }) res <- synchronise(afun()) expect_equal( res, list(delay = 1, http = 418, process = "foobar", r_process = 2, call = 3) ) })
aw_workspace_report <- function(req_body = '', company_id = Sys.getenv('AW_COMPANY_ID')) { assertthat::assert_that( file.exists(req_body), is.string(company_id) ) env_vars <- get_env_vars() token_config <- get_token_config(client_id = env_vars$client_id, client_secret = env_vars$client_secret) query <-jsonlite::fromJSON(txt=req_body) metrics <- gsub(".*/", "", query$metricContainer$metrics$id) dimensions <- gsub(".*/", "", query$dimension) if(!is.null(query$metricContainer$metricFilters)) { mf <- query$metricContainer$metricFilters %>% dplyr::rename('filtername' = 3) mets <- tidyr::unnest(query$metricContainer$metrics, cols = c(columnId, filters)) metricsinfo <- mets %>% dplyr::left_join(mf, by = c('filters' = 'id')) finalmnames <- metricsinfo %>% dplyr::mutate(id = gsub(".*/", "", id)) %>% dplyr::mutate(mfinalname = ifelse(!is.na(filtername), paste0(filtername,'_', id), id) ) %>% dplyr::group_by(columnId) %>% dplyr::summarise(mfinalname = paste0(mfinalname, collapse = "-")) %>% dplyr::pull(mfinalname) } else { finalmnames <- metrics } request_url <- sprintf("https://analytics.adobe.io/api/%s/reports/ranked", company_id) req <- httr::RETRY("POST", url = request_url, body = upload_file(req_body), encode = "json", token_config, httr::add_headers( `x-api-key` = env_vars$client_id, `x-proxy-global-company-id` = company_id )) httr::stop_for_status(req) res <- httr::content(req, as = "text",encoding = "UTF-8") res <- jsonlite::fromJSON(res) res_df <- res$rows res_df <- res_df %>% tidyr::unnest(data) %>% dplyr::group_by(itemId,value) %>% dplyr::mutate(col = seq_along(data)) %>% tidyr::spread(key=col, value=data) %>% dplyr::ungroup()%>% dplyr::select(-itemId) colnames(res_df) <- c(dimensions,finalmnames) df <- data.frame(res_df) return(df) }
NULL print.sc_power <- function(x, digits = "auto", ...) { cat("Test-Power in percent:\n") ma <- matrix( unlist(x[1:16]) * 100, byrow = FALSE, ncol = 2, dimnames = list( c( "tauU: A vs. B - Trend A", paste0("Rand-Test: ",x$rand.test.stat[1]), "PLM.Norm: Level", "PLM.Norm: Slope", "PLM.Poisson: Level", "PLM.Poisson: Slope", "HPLM: Level", "HPLM: Slope" ), c("Power", "Alpha-error") ) ) ma } print.sc_ac <- function(x, digits = "auto", ...) { if (digits == "auto") digits <- 2 cat("Autocorrelations\n\n") x <- x$autocorr for (i in 1:length(x)) { x[[i]][, -1] <- round(x[[i]][, -1], digits) cat(names(x)[i], "\n") print(x[[i]], row.names = FALSE) cat("\n") } } print.sc_cdc <- function(x, nice = TRUE, ...) { cat("Conservative Dual Criterion\n\n") cat("N cases = ", x$N, "\n\n") if (nice) x$cdc_p <- .nice_p(x$cdc_p) out <- data.frame( Case = x$case_names, "nB improve" = x$cdc_be, "nB" = x$cdc_b, "binom p" = x$cdc_p, "CDC Evaluation" = x$cdc, check.names = FALSE ) print(out, row.names = FALSE) cat("\n") if (x$decreasing) { cat("Assuming an expected decrease in phase B.\n") cat("Alternative hypothesis (Binomial test): true probability < 50%\n") } else { cat("Assuming an expected increase in phase B.\n") cat("Alternative hypothesis (Binomial test): true probability > 50%\n") } if (x$N > 1) { cat("Overall evaluation of all MBD instances: ",x$cdc_all,"\n") } } print.sc_bctau <- function(x, nice = TRUE, digits = "auto", ...) { cat("Baseline corrected tau\n\n") cat("\n") if (x$continuity) { cat("Continuity correction applied\n") } else { cat("Continuity correction not applied.\n") } if (digits == "auto") { x$parameters$p <- round(x$parameters$p, 3) x$parameters$z <- sprintf("%.2f", x$parameters$z) x$parameters$tau <- sprintf("%.2f", x$parameters$tau) } else { x$parameters$p <- round(x$parameters$p, digits) x$parameters$z <- round(x$parameters$z, digits) x$parameters$tau <- round(x$parameters$tau, digits) } if (nice) { x$parameters$p <- .nice_p(x$parameters$p) } rownames(x$parameters) <- x$parameters$Model print(x$parameters[,-1], ...) cat("\n") if (x$correction) cat("Baseline correction should be applied.\n\n") if (!x$correction) cat("Baseline correction should not be applied.\n\n") } print.sc_desc <- function(x, digits = "auto", ...) { if (digits == "auto") digits <- 3 cat("Describe Single-Case Data\n\n") x$descriptives[-1:-2] <- round(x$descriptives[-1:-2], digits) out <- as.data.frame(t(x$descriptives[-1])) colnames(out) <- x$descriptives$Case print(out[1:(2 * length(x$design) + 1), , drop = FALSE], digits = digits, ...) cat("\n") print(out[-(1:(2 * length(x$design) + 1)),, drop = FALSE], digits = digits, ...) .note_vars(x) } print.sc_design <- function(x, ...) { cat("A scdf design matrix\n\n") cat("Number of cases:", length(x$cases), "\n") cat("Mean: ", x$cases[[1]]$m[1], "\n") cat("SD = ", x$cases[[1]]$s[1], "\n") cat("rtt = ", x$cases[[1]]$rtt[1], "\n") cat("Phase design: ", as.character(x$cases[[1]]$phase), "\n") cat("mean trend-effect: ", apply(sapply(x$cases, function(x) {x$trend}), 1, mean, na.rm = TRUE)[1], "\n") cat("mean level-effect: ", apply(sapply(x$cases, function(x) {x$level}), 1, mean, na.rm = TRUE), "\n") cat("mean slope-effect: ", apply(sapply(x$cases, function(x) {x$slope}), 1, mean, na.rm = TRUE), "\n") cat("sd trend-effect: ", apply(sapply(x$cases, function(x) {x$trend}), 1, sd, na.rm = TRUE)[1], "\n") cat("sd level-effect: ", apply(sapply(x$cases, function(x) {x$level}), 1, sd, na.rm = TRUE), "\n") cat("sd slope-effect: ", apply(sapply(x$cases, function(x) {x$slope}), 1, sd, na.rm = TRUE), "\n") cat("Distribution: ", x$distribution) } print.sc_hplm <- function(x, ...) { cat("Hierarchical Piecewise Linear Regression\n\n") cat("Estimation method", x$model$estimation.method,"\n") cat("Slope estimation method:", x$model$interaction.method,"\n") cat(x$N, "Cases\n\n") out <- list() if (x$model$ICC) { out$ICC <- sprintf("ICC = %.3f; L = %.1f; p = %.3f\n\n", x$ICC$value, x$ICC$L, x$ICC$p) cat(out$ICC) } md <- as.data.frame(summary(x$hplm)$tTable) colnames(md) <- c("B", "SE", "df", "t", "p") row.names(md) <- .plm.row.names(row.names(md), x) md$B <- round(md$B, 3) md$SE <- round(md$SE, 3) md$t <- round(md$t, 3) md$p <- round(md$p, 3) out$ttable <- md cat("Fixed effects (",deparse(x$model$fixed),")\n\n", sep = "") print(md) cat("\nRandom effects (",deparse(x$model$random),")\n\n", sep = "") SD <- round(as.numeric(VarCorr(x$hplm)[,"StdDev"]), 3) md <- data.frame("EstimateSD" = SD) rownames(md) <- names(VarCorr(x$hplm)[, 2]) row.names(md) <- .plm.row.names(row.names(md), x) if (x$model$lr.test) { if (is.null(x$LR.test[[1]]$L.Ratio)) { x$LR.test[[1]]$L.Ratio <- NA x$LR.test[[1]]$"p-value" <- NA x$LR.test[[1]]$df <- NA } md$L <- c(round(unlist(lapply(x$LR.test, function(x) x$L.Ratio[2])), 2), NA) md$df <- c(unlist(lapply(x$LR.test, function(x) x$df[2] - x$df[1])), NA) md$p <- c(round(unlist(lapply(x$LR.test, function(x) x$"p-value"[2])), 3), NA) } print(md, na.print = "-", ...) } print.sc_overlap <- function(x, digits = "auto", ...) { if (digits == "auto") { digits_1 <- 0 digits_2 <- 2 } else { digits_1 <- digits digits_2 <- digits } cat("Overlap Indices\n\n") cat(.phases_string(x$phases.A, x$phases.B),"\n\n") x$overlap[3:8] <- round(x$overlap[3:8], digits_1) x$overlap[9:14] <- round(x$overlap[9:14], digits_2) out <- as.data.frame(t(x$overlap[-1])) colnames(out) <- x$overlap$Case print(out, ...) .note_vars(x) } print.sc_mplm <- function(x, digits = "auto", std = FALSE, ...) { if (digits == "auto") digits <- 3 cat("Multivariate piecewise linear model\n\n") cat("Dummy model:", x$model, "\n\n") coef <- x$full.model$coefficients rownames(coef) <- gsub("(Intercept)", "Intercept", rownames(coef)) rownames(coef) <- gsub("mt", "Trend", rownames(coef)) rownames(coef) <- gsub("phase", "Level Phase ", rownames(coef)) rownames(coef) <- gsub("inter", "Slope Phase ", rownames(coef)) cat("Coefficients: \n") print(coef, digits = digits, ...) if (isTRUE(std)) { coef_std <- x$full.model$coef_std rownames(coef_std) <- gsub("(Intercept)", "Intercept", rownames(coef_std)) rownames(coef_std) <- gsub("mt", "Trend", rownames(coef_std)) rownames(coef_std) <- gsub("phase", "Level Phase ", rownames(coef_std)) rownames(coef_std) <- gsub("inter", "Slope Phase ", rownames(coef_std)) cat("\nStandardized coefficients: \n") print(coef_std, digits = digits, ...) } cat("\n") cat("Formula: ") print(x$formula, showEnv = FALSE) res <- car::Anova(x$full.model, type = 3) res$terms <- gsub("(Intercept)", "Intercept", res$terms) res$terms <- gsub("mt", "Trend", res$terms) res$terms <- gsub("phase", "Level Phase ", res$terms) res$terms <- gsub("inter", "Slope Phase ", res$terms) print(res, digits = digits, ...) .note_vars(x) } print.sc_nap <- function(x, digits = "auto", ...) { if (digits == "auto") digits <- 2 cat("Nonoverlap of All Pairs\n\n") print(x$nap, row.names = FALSE, digits = digits) } print.sc_outlier <- function(x, digits = "auto", ...) { cat("Outlier Analysis for Single-Case Data\n\n") if (x$criteria[1] == "CI") { names(x$ci.matrix) <- x$case.names cat("Criteria: Exceeds", as.numeric(x$criteria[2]) * 100, "% Confidence Interval\n\n") print(x$ci.matrix) } if (x$criteria[1] == "SD") { names(x$sd.matrix) <- x$case.names cat("Criteria: Exceeds", x$criteria[2], "Standard Deviations\n\n") print(x$sd.matrix) } if (x$criteria[1] == "MAD") { names(x$mad.matrix) <- x$case.names cat("Criteria: Exceeds", x$criteria[2], "Mean Average Deviations\n\n") print(x$mad.matrix) } if (x$criteria[1] == "Cook") { cat("Criteria: Cook's Distance based on piecewise-linear-regression exceeds", x$criteria[2],"\n\n") } for(i in 1:length(x$dropped.n)) { cat("Case",x $case.names[i],": Dropped", x$dropped.n[[i]], "\n") } cat("\n") } print.sc_pand <- function(x, ...) { cat("Percentage of all non-overlapping data\n\n") cat("PAND = ", round(x$PAND, 1), "%\n") cat("\u03A6 = ", round(x$phi, 3), " ; \u03A6\u00b2 = ", round(x$phi^2, 3), "\n\n") cat("Number of Cases:", x$N, "\n") cat("Total measurements:", x$n, " ") cat("(in phase A: ", x$nA, "; in phase B: ", x$nB, ")\n", sep = "") cat("n overlapping data per case: ") cat(x$OD.PP, sep = ", ") cat("\n") cat("Total overlapping data: n =",x$OD , "; percentage =", round(x$POD, 1), "\n") ma <- x$matrix cat("\n") cat("2 x 2 Matrix of proportions\n") cat("\t% expected\n") cat("\tA\tB\ttotal\n") cat("% A",round(ma[1, ] * 100, 1), sum(round(ma[1, ] * 100, 1)), sep = "\t") cat("\n") cat("real B",round(ma[2, ] * 100, 1), sum(round(ma[2, ] * 100, 1)), sep = "\t") cat("\n") cat(" total",sum(round(ma[, 1] * 100, 1)), sum(round(ma[, 2] * 100, 1)), sep = "\t") cat("\n") ma <- x$matrix.counts cat("\n") cat("2 x 2 Matrix of counts\n") cat("\texpected\n") cat("\tA\tB\ttotal\n") cat(" A",round(ma[1, ], 1), sum(round(ma[1, ], 1)), sep = "\t") cat("\n") cat("real B",round(ma[2, ], 1), sum(round(ma[2, ], 1)), sep = "\t") cat("\n") cat(" total",sum(round(ma[,1], 1)), sum(round(ma[,2 ], 1)), sep = "\t") cat("\n") cat("\n") if (x$correction) cat("\nNote. Matrix is corrected for ties\n") cat("\nCorrelation based analysis:\n\n") out <- sprintf( "z = %.3f, p = %.3f, \u03c4 = %.3f", x$correlation$statistic, x$correlation$p.value, x$correlation$estimate ) cat(out, "\n") } print.sc_pem <- function(x, ...) { cat("Percent Exceeding the Median\n\n") ma <- cbind(PEM = x$PEM, x$test) print(round(ma, 3)) cat("\n") if (x$decreasing) { cat("Assumed decreasing values in the B-phase.\n\n") cat("Alternative hypothesis: true probability < 50%\n") } else { cat("Alternative hypothesis: true probability > 50%\n") } } print.sc_pet <- function(x, ...) { cat("Percent Exceeding the Trend\n\n") cat("N cases = ", x$N, "\n") cat("\n") ma <- cbind(x$PET, x$p, x$PET.ci) colnames(ma) <- c("PET", "binom.p", "PET CI") rownames(ma) <- x$case.names print(round(ma, 3)) cat("\n") if (x$decreasing) { cat("Assumed decreasing values in the B-phase.\n\n") cat("Binom.test: alternative hypothesis: true probability < 50%\n") cat(sprintf("PET CI: Percent of values less than lower %d%% confidence threshold (smaller %.3f*se below predicted value)\n", x$ci,x$se.factor)) } else { cat("Binom.test: alternative hypothesis: true probability > 50%\n") cat(sprintf("PET CI: Percent of values greater than upper %d%% confidence threshold (greater %.3f*se above predicted value)\n", x$ci,x$se.factor)) } } print.sc_pnd <- function(x, ...) { cat("Percent Non-Overlapping Data\n\n") out <- data.frame( Case = x$case.names, PND = paste0(round(x$PND, 2),"%"), "Total" = x$n.B, "Exceeds" = round(x$PND / 100 * x$n.B) ) print(out, row.names = FALSE) cat("\nMean :", round(mean(x$PND, na.rm = TRUE), 2),"%\n") } print.sc_tauu <- function(x, complete = FALSE, digits = "auto", ...) { if (digits == "auto") digits <- 3 cat("Tau-U\n") cat("Method:", x$method, "\n") cat("Applied Kendall's Tau-", x$tau_method, "\n\n", sep = "") out <- x$table if (length(out) > 1) { cat("Overall Tau-U\n") cat("Meta-anlysis model:", x$meta_method, "effect\n\n") print(x$Overall_tau_u, row.names = FALSE, digits = digits) cat("\n") } if (!complete) { select_vars <- c("Tau", "SE_Tau", "Z", "p") select_rows <- match( c( "A vs. B", "A vs. B - Trend A", "A vs. B + Trend B", "A vs. B + Trend B - Trend A" ), row.names(x$table[[1]]) ) out <- lapply(x$table, function(x) round(x[select_rows, select_vars], 3)) } for(i in seq_along(out)) { cat("Case:", names(out)[i], "\n") print(out[[i]], digits = digits) cat("\n") } } print.sc_plm <- function(x, ...) { cat("Piecewise Regression Analysis\n\n") cat("Dummy model: ", x$model,"\n\n") cat("Fitted a", x$family, "distribution.\n") if (x$ar > 0) cat("Correlated residuals up to autoregressions of lag", x$ar, "are modelled\n\n") if (x$family == "poisson" || x$family == "nbinomial") { Chi <- x$full$null.deviance - x$full$deviance DF <- x$full$df.null - x$full$df.residual cat(sprintf( "\u0347\u00b2(%d) = %.2f; p = %0.3f; AIC = %.0f\n\n", DF, Chi, 1 - pchisq(Chi, df = DF), x$full$aic) ) } else { cat(sprintf( "F(%d, %d) = %.2f; p = %0.3f; R\u00b2 = %0.3f; Adjusted R\u00b2 = %0.3f\n\n", x$F.test["df1"], x$F.test["df2"], x$F.test["F"], x$F.test["p"], x$F.test["R2"], x$F.test["R2.adj"]) ) } if (x$ar == 0) res <- summary(x$full.model)$coefficients if (x$ar > 0) res <- summary(x$full.model)$tTable if (nrow(res) == 1) { res <- cbind( res[, 1, drop = FALSE], t(suppressMessages(confint(x$full))), res[, 2:4, drop = FALSE] ) } else res <- cbind( res[,1], suppressMessages(confint(x$full)), res[, 2:4] ) res <- round(res, 3) res <- as.data.frame(res) if (!is.null(x$r.squares)) res$R2 <- c("", format(round(x$r.squares, 4))) row.names(res) <- .plm.row.names(row.names(res), x) if (!is.null(x$r.squares)) colnames(res) <- c("B", "2.5%", "97.5%", "SE", "t", "p", "delta R\u00b2") if (is.null(x$r.squares)) colnames(res) <- c("B", "2.5%", "97.5%", "SE", "t", "p") if (x$family == "poisson" || x$family == "nbinomial") { OR <- exp(res[, 1:3]) Q <- (OR - 1) / (OR + 1) res <- cbind(res[, -7], round(OR, 3), round(Q, 2)) colnames(res) <- c( "B", "2.5%", "97.5%", "SE", "t", "p", "Odds Ratio", "2.5%", "97.5%", "Yule's Q", "2.5%", "97.5%" ) } print(res) cat("\n") cat("Autocorrelations of the residuals\n") lag.max = 3 cr <- acf(residuals(x$full.model), lag.max = lag.max,plot = FALSE)$acf[2:(1 + lag.max)] cr <- round(cr, 2) print(data.frame(lag = 1:lag.max, cr = cr), row.names = FALSE) cat("\n") cat("Formula: ") print(x$formula, showEnv = FALSE) cat("\n") .note_vars(x) } print.sc_trend <- function(x, digits = 3, ...) { x$trend <- round(x$trend, digits) cat("Trend for each phase\n\n") print(x$trend) cat("\n") cat("Note. Measurement-times start at", 1 + x$offset, " for each phase\n") .note_vars(x) } print.sc_rand <- function(x, ...) { cat("Randomization Test\n\n") if (x$N > 1) cat("Test for", x$N, "cases.\n\n") cat(.phases_string(x$phases.A, x$phases.B), "\n") cat("Statistic: ", x$statistic, "\n\n") if (is.na(x$startpoints[1])) { cat("Minimal length of each phase:", "A =", x$limit[1], ", B =", x$limit[2], "\n") } else { cat("Possible starting points of phase B: ", x$startpoints, "\n") } cat("Observed statistic = ", x$observed.statistic, "\n") if (x$auto.corrected.number) { cat("\nWarning! The assigned number of random permutations exceeds the", "number of possible permutations.", "\nAnalysis is restricted to all possible permutations.\n") } if (x$complete) { cat("\nDistribution based on all", x$possible.combinations, "possible combinations.\n") } else cat("\nDistribution based on a random sample of all", x$possible.combinations, "possible combinations.\n") cat("n = ", x$number,"\n") cat("M = ", mean(x$distribution),"\n") cat("SD = ", sd(x$distribution),"\n") cat("Min = ", min(x$distribution),"\n") cat("Max = ", max(x$distribution),"\n") cat("\n") cat("Probability of observed statistic based on distribution:\n") if (x$p.value == 0) { cat("p < ", format(1/x$number, scientific = FALSE), "\n") } else { cat("p = ", x$p.value, "\n") } if (x$number > 3 && x$number < 5001) { sh <- shapiro.test(x$distribution) cat(sprintf("\nShapiro-Wilk Normality Test: W = %0.3f; p = %0.3f",sh[[1]], sh$p.value)) if (sh$p.value > .05) { cat(" (Hypothesis of normality maintained)\n") } else { cat(" (Hypothesis of normality rejected)\n") } } else { cat("\nSample size must be between 3 and 5000 to perform a Shapiro-Wilk Test.\n") } cat("\nProbabilty of observed statistic based on the assumption of normality:\n") cat(sprintf("z = %0.4f, p = %0.4f (single sided)\n", x$Z, x$p.Z.single)) } print.sc_rci <- function(x, ...) { cat("Reliable Change Index\n\n") cat("Mean Difference = ", x$descriptives[2, 2] - x$descriptives[1, 2], "\n") cat("Standardized Difference = ", x$stand.dif, "\n") cat("\n") cat("Descriptives:\n") print(x$descriptives) cat("\n") cat("Reliability = ", x$reliability, "\n") cat("\n") cat(x$conf.percent * 100, "% Confidence Intervals:\n") print(x$conf) cat("\n") cat("Reliable Change Indices:\n") print(x$RCI) cat("\n") } .note_vars <- function(x) { v <- any(attr(x, .opt$dv) != "values") p <- attr(x, .opt$phase) != "phase" m <- attr(x, .opt$mt) != "mt" if (v || p || m) { cat("\nThe following variables were used in this analysis:\n'", paste0(attr(x, .opt$dv), collapse = "/ "), "' as dependent variable, '", paste0(attr(x, .opt$phase), collapse = "/ "), "' as phase variable, and '", paste0(attr(x, .opt$mt), collapse = "/ "),"' as measurement-time variable.\n", sep = "") } }
redisEval <- function(script, keys=vector("list",0), SHA=FALSE, ...) { if(!is.list(keys)) keys = list(keys) numkeys = length(keys) if(numkeys>0) keys = as.character(keys) CMD = ifelse(SHA,"EVALSHA","EVAL") do.call("redisCmd", args=c(list(CMD, script, as.character(numkeys)),keys,list(...))) }
context("unphased") test_that("unphased, use", { testthat::skip_on_os("solaris") population_size <- 100 max_t <- 110 vx <- sim_phased_unphased(pop_size = population_size, freq_ancestor_1 = 0.5, total_runtime = max_t, size_in_morgan = 1, markers = 1000, time_points = c(50, 100)) num_indiv <- length(unique(vx$individual)) testthat::expect_equal(num_indiv, 10) testthat::expect_equal(length(unique(vx$time)), 2) local_data <- subset(vx, vx$individual == 0 & vx$time == 100) ll_100 <- log_likelihood_diploid(cbind(1, local_data$location, local_data$anc_chrom_1, local_data$anc_chrom_2), pop_size = 100, freq_ancestor_1 = 0.5, t = 100, phased = FALSE) ll_2000 <- log_likelihood_diploid(cbind(1, local_data$location, local_data$anc_chrom_1, local_data$anc_chrom_2), pop_size = 100, freq_ancestor_1 = 0.5, phased = FALSE, t = 2000) testthat::expect_gte(ll_100, ll_2000) vx <- sim_phased_unphased(pop_size = 10000, freq_ancestor_1 = 0.1, total_runtime = 20, size_in_morgan = 1, markers = 10000, time_points = c(20)) local_data <- subset(vx, vx$individual == 0 & vx$time == 20) ll_30 <- log_likelihood_diploid(cbind(1, local_data$location, local_data$anc_chrom_1, local_data$anc_chrom_2), pop_size = 1000, freq_ancestor_1 = 0.1, phased = FALSE, t = 30) ll_100 <- log_likelihood_diploid(cbind(1, local_data$location, local_data$anc_chrom_1, local_data$anc_chrom_2), pop_size = 1000, freq_ancestor_1 = 0.1, phased = FALSE, t = 600) testthat::expect_gte(ll_30, ll_100) multi_ll <- log_likelihood_diploid(cbind(1, local_data$location, local_data$anc_chrom_1, local_data$anc_chrom_2), pop_size = 1000, freq_ancestor_1 = 0.1, phased = FALSE, t = c(3, 30000, 300000)) testthat::expect_true(length(multi_ll) == 3) testthat::expect_gt(multi_ll[1], multi_ll[2]) testthat::expect_gt(multi_ll[2], multi_ll[3]) }) test_that("unphased, time points", { testthat::skip_on_os("solaris") population_size <- 100 max_t <- 10 vx <- sim_phased_unphased(pop_size = population_size, freq_ancestor_1 = 0.5, total_runtime = max_t, size_in_morgan = 1, markers = 1000, time_points = -1) sim_t <- unique(vx$time) testthat::expect_equal(length(sim_t), max_t + 1) testthat::expect_warning( vx <- sim_phased_unphased(pop_size = population_size, freq_ancestor_1 = 0.5, total_runtime = max_t, size_in_morgan = 1, markers = 1000, time_points = max_t + 5) ) testthat::expect_equal(length(unique(vx$time)), 1) }) test_that("unphased, junctions", { testthat::skip_on_os("solaris") N <- 10000 R <- 10000 t <- 10 H_0 <- 0.5 C <- 1 testthat::expect_output( vx <- sim_phased_unphased(pop_size = N, freq_ancestor_1 = H_0, total_runtime = t, size_in_morgan = C, markers = R, time_points = t, num_indiv_sampled = 100, record_true_junctions = TRUE, verbose = TRUE) ) num_j_true <- mean(c(vx$true_results$junctions_chrom_1, vx$true_results$junctions_chrom_2)) vx <- vx$results num_j <- c() for (i in unique(vx$individual)) { dd <- subset(vx, vx$individual == i) num_j_1 <- sum(abs(diff(dd$anc_chrom_1))) num_j_2 <- sum(abs(diff(dd$anc_chrom_1))) num_j <- c(num_j, c(num_j_1, num_j_2)) } obs_j <- mean(num_j) exp_j <- junctions::number_of_junctions(N = N, R = R, H_0 = H_0, C = C, t = t) testthat::expect_equal(obs_j, exp_j, tolerance = 0.2) N <- 10000 R <- 10000 t <- 20 H_0 <- 0.5 C <- 1 vx <- sim_phased_unphased(pop_size = N, freq_ancestor_1 = H_0, total_runtime = t, size_in_morgan = C, markers = R, time_points = t, num_indiv_sampled = 30) num_j <- c() for (i in unique(vx$individual)) { dd <- subset(vx, vx$individual == i) num_j_1 <- sum(abs(diff(dd$anc_chrom_1))) num_j_2 <- sum(abs(diff(dd$anc_chrom_1))) num_j <- c(num_j, c(num_j_1, num_j_2)) } obs_j <- mean(num_j) exp_j <- junctions::number_of_junctions(N = N, R = R, H_0 = H_0, C = C, t = t) testthat::expect_equal(obs_j, exp_j, tolerance = 0.2) })
test_that("flatten_maybe will fail with a non-maybe value", { for_all( a = any_vector(), property = \(a) perhaps(flatten_maybe, default = "failure")(a) |> expect_equal("failure") ) }) test_that("flatten_maybe doesn't change non-nested maybes", { nothing() |> flatten_maybe() |> expect_identical(nothing()) for_all( a = any_vector(), property = \(a) just(a) |> flatten_maybe() |> expect_identical(just(a)) ) }) test_that("flatten_maybe removes a layer from a nested maybe", { just(nothing()) |> flatten_maybe() |> expect_identical(nothing()) for_all( a = any_vector(), property = \(a) just(just(1)) |> flatten_maybe() |> expect_identical(just(1)) ) })
fbrNBglm.fit=function(x, y, weights = rep(1, length(y)), offset = rep(0, length(y)), family, link='log', odisp, control = fbrNBglm.control()) { if(missing(family)) family=negbin(link, odisp) if(family$link!='log') stop('Currently only log link has been implemented.') nobs=NROW(y) good.weights=weights>0 ngood=length(good.weights) if(ngood==0L) stop('None of the weights is positive') ww=weights[good.weights] if(any(ww!=ww[1L])) stop('Bias reduction in the presence of non-equal positive prior weights is currently not available') ww[]=1 if(!is.matrix(x)) x=as.matrix(x) ncolx=NCOL(x) yy=y[good.weights]; xx=x[good.weights,,drop=FALSE]; oo=offset[good.weights] start=control$start if(isTRUE(control$standardizeX)){ x.norm=.colSums(xx*xx, ngood, ncolx) x.stdCols=x.norm > .colSums(xx, ngood, ncolx)^2 / ngood x.norm=sqrt(x.norm) if(any(x.stdCols)){ xx[,x.stdCols]=sweep(xx[,x.stdCols,drop=FALSE],2L,x.norm[x.stdCols],'/') if(!is.null(start)) { start[x.stdCols] = start[x.stdCols] * x.norm[x.stdCols] control$start = start } } } odisp=1/family$getTheta() variance <- family$variance linkfun <- family$linkfun linkinv <- family$linkinv mu.eta <- family$mu.eta d2link = family$d2link dvar = family$dvar xxqr=qr(xx); rk=xxqr$rank if(rk<ncolx){ xx=xx[,xxqr$pivot[seq_len(rk)],drop=FALSE] if(!is.null(control$start)) { start=start[xxqr$pivot[seq_len(rk)]] control$start = start } } xxuniq=unique(xx) infoParmsj=control$infoParms$j infoParmsk=control$infoParms$k infoParmsm=control$infoParms$m .C(C_initQRdecomp, ngood, rk) on.exit(.C(C_finalQRdecomp)) adjScoreFunc=function(bet, approxJacob=FALSE) { this.eta=as.vector(xx%*%bet+oo) this.mu=linkinv(this.eta) this.mu.eta=mu.eta(this.eta) this.var=variance(this.mu) this.weight=this.mu.eta^2/this.var this.resid=(yy-this.mu) this.wresid=this.resid*this.weight score=crossprod(xx, this.wresid/this.mu) this.w2x=sqrt(this.weight)*xx if(approxJacob) return(-crossprod(this.w2x)) this.bias=try(.Call(C_getGlmBias, rtwx = this.w2x, wrt = sqrt(this.weight), ngood, rk)) if(inherits(this.bias, 'try-error')) { this.qr=qr(this.w2x, tol=qr.tol) this.hatd=.rowSums(qr.Q(this.qr)[,seq_len(this.qr$rank), drop=FALSE]^2, ngood, this.qr$rank) this.bias=qr.coef(this.qr, -0.5*this.hatd/sqrt(this.weight)) this.bias[is.na(this.bias)]=0 } this.adjWt=this.weight*( this.resid*infoParmsk*(this.var*d2link(this.mu)+dvar(this.mu)/this.mu.eta)^infoParmsm/(this.var/this.mu.eta)^infoParmsj +1 ) this.adjInfo=crossprod(xx, this.adjWt*xx) adjScore=-this.adjInfo%*%this.bias as.vector(score + adjScore) } approxJacob=NULL attr(adjScoreFunc, 'getApproxJacob')=function(...)approxJacob test.1stepFF=function() { if(rk!=NROW(xxuniq)) stop('this function should only be used for one-way designs') group=grpDuplicated(xx) constOffset = all(ave(oo, group) == oo) oneWayX=1 * (group==rep(seq_len(rk), each=ngood)); dim(oneWayX)=c(ngood, rk) exact = (infoParmsk==0 || infoParmsj==1) && constOffset attr(exact, 'group')=group attr(exact, 'oneWayX')=oneWayX attr(exact, 'constOffset')=constOffset exact } fullFactorial1Step=function(groupX) { ns=.colSums(groupX, ngood, rk) fitted.mean=ybars=crossprod(groupX, yy)/ns off=crossprod(groupX, oo)/ns eval(expr.1step) fitted.coef=xxuniqInv %*% ( linkfun(fitted.mean)-off) } expr.1step= if(infoParmsk==0){ expression( fitted.mean <- (ns*ybars+0.5)/(ns-odisp*.5) ) }else if(infoParmsj==1){ expression({ .tmp=2*ns + infoParmsk * odisp^infoParmsm fitted.mean=(.tmp*ybars+1)/(.tmp-odisp) }) }else if(infoParsmj==0){ expression({ .tmpktaum=infoParmsk*odisp^infoParmsm .tmp=.5*(ybars+(odisp-2*ns)/.tmpktaum/odisp - 1/odisp) fitted.mean = .tmp + sqrt(.tmp^2 +(1+(2*ns+.tmpktaum)*ybars)/.tmpktaum/odisp) }) }else { expression({ fitted.mean <- ybars + .5/ns }) } getMuStart=expression( { eval(family$initialize) etastart=linkfun(mustart[good.weights]) start=lm.fit(xx, etastart, offset=oo)$coef }) if(rk<NROW(xxuniq)){ doIteration=TRUE if(is.null(start)){ eval(getMuStart, envir=sys.frame(sys.nframe())) startAdjscore=adjScoreFunc(start,approxJacob=FALSE) if(FALSE){ xxkm=kmeans(qr.Q(xxqr), rk) approx1wayx=model.matrix(~0+as.factor(xxkm$cluster)) xxuniqInv=diag(1, rk, rk) yy.bak=yy; oo.bak=oo yy=yy/exp(oo-mean(oo)); oo[]=mean(oo) fff=fullFactorial1Step(approx1wayx) yy=yy.bak; oo=oo.bak fff=qr.coef(xxqr, fff[xxkm$cluster]) fffAdjscore=adjScoreFunc(fff, approxJacob=FALSE) if(sum(fffAdjscore^2)<sum(startAdjscore^2)){ start=fff } } } if(!all(is.finite(start)) ){ eval(getMuStart, envir=sys.frame(sys.nframe())) } }else if(rk==NROW(xxuniq)){ FFtestRslt=test.1stepFF() oneWayGroup=attr(FFtestRslt, 'group') oneWayX=attr(FFtestRslt, 'oneWayX') oneWayN=.colSums(oneWayX, ngood, rk) xxuniqInv=if(rk==1L) matrix(1/xxuniq) else if(rk==2L) solve22(xxuniq) else solve(xxuniq) if(FFtestRslt){ doIteration=FALSE start=fullFactorial1Step(oneWayX) attr(start, 'method')='exact' attr(start, 'success')=TRUE attr(start, 'iter')=1L }else{ doIteration=TRUE if(is.null(start)) eval(getMuStart) ss=exp(oo) ssOdisp=ss*odisp if(infoParmsj==1 && infoParmsk==1 && infoParmsm==1){ workMat=cbind(ss, yy, ss*(1+yy*odisp)) rhs=function(this.mu){ onePlusOdispMuScale=1+ssOdisp*this.mu[oneWayGroup] tmpMat=workMat/onePlusOdispMuScale tmpMat[,3L]=tmpMat[,3L]/onePlusOdispMuScale ssSyssY=crossprod(oneWayX, tmpMat) ans=ssSyssY[, 2L]/ssSyssY[, 1L]+.5*ssSyssY[, 3L]/ssSyssY[,1L]^2 if(any(is.na(ans))) ans=exp(log(ssSyssY[, 2L])-log(ssSyssY[, 1L]))+.5*exp(log(ssSyssY[, 3L])-2*log(ssSyssY[,1L])) ans } rhs1=function(this.mu, grpId){ onePlusOdispMuScale=1+ssOdisp*this.mu tmpMat=workMat/onePlusOdispMuScale tmpMat[,3L]=tmpMat[,3L]/onePlusOdispMuScale ssSyssY=crossprod(oneWayX[,grpId], tmpMat) ans=ssSyssY[, 2L]/ssSyssY[, 1L]+.5*ssSyssY[, 3L]/ssSyssY[,1L]^2 if(any(is.na(ans))) ans=exp(log(ssSyssY[, 2L])-log(ssSyssY[, 1L]))+.5*exp(log(ssSyssY[, 3L])-2*log(ssSyssY[,1L])) ans } }else{ tmp=ss*infoParmsk*odisp^infoParmsm workMat=cbind(ss, yy, ss2=ss*tmp, sy=yy*tmp) rhs=function(this.mu){ onePlusOdispMuScale=1+ssOdisp*this.mu[oneWayGroup] tmpMat=workMat/onePlusOdispMuScale tmpMat[,3L:4L]=tmpMat[,3L:4L]/onePlusOdispMuScale^infoParmsj ssSyssY=crossprod(oneWayX, tmpMat) ( ssSyssY[, 1L]*ssSyssY[, 2L] + .5*(ssSyssY[, 4L] +ssSyssY[, 1L] ) )/ ( ssSyssY[, 1L]^2 + .5*ssSyssY[, 3L] ) } rhs1=function(this.mu, grpId){ onePlusOdispMuScale=1+ssOdisp*this.mu tmpMat=workMat/onePlusOdispMuScale tmpMat[,3L:4L]=tmpMat[,3L:4L]/onePlusOdispMuScale^infoParmsj ssSyssY=crossprod(oneWayX[,grpId], tmpMat) ( ssSyssY[, 1L]*ssSyssY[, 2L] + .5*(ssSyssY[, 4L] +ssSyssY[, 1L] ) )/ ( ssSyssY[, 1L]^2 + .5*ssSyssY[, 3L] ) } } tryCatch({ it=1L iterMax=control$maxit startExpXb0=startExpXb1=as.vector(crossprod(oneWayX, exp(xx%*%start))/oneWayN) startAdjscore = rhs(startExpXb0) - startExpXb0 yy.bak=yy; oo.bak=oo yy=yy/exp(oo-mean(oo)); oo[]=mean(oo) fff=fullFactorial1Step(oneWayX) yy=yy.bak; oo=oo.bak fffmu=as.vector(crossprod(oneWayX, exp(xx%*%fff))/oneWayN) fffAdjscore=rhs(fffmu) - fffmu if(!all(is.finite(startAdjscore)) || sum(startAdjscore^2)>sum(fffAdjscore^2)) { start=fff startExpXb0=startExpXb1=fffmu startAdjscore = fffAdjscore } nextExpXb = startExpXb1 for(grpId in seq_len(rk)){ objFunc = function(mu) (rhs1(mu, grpId)-mu) tmpans = newtonRaphson(objFunc, startExpXb1[grpId], maxiter=control$maxit, tol=control$tol) nextExpXb[grpId] = tmpans$root } start= as.vector(xxuniqInv %*% linkfun(nextExpXb)) startAdjscore=adjScoreFunc(start,approxJacob=FALSE) if(sqrt(sum(startAdjscore^2))<=control$tol) { doIteration=FALSE attr(start, 'method')='fullFactorialIter' attr(start, 'success')=TRUE attr(start, 'iter')=it } }, error=function(e){doIteration <<- TRUE; print(e); NULL}) } }else stop("rank of x is larger than number of unique rows of x") if(doIteration){ print("doIteration") approxJacob=adjScoreFunc(start,approxJacob=TRUE) ans=suppressWarnings(nlsolve(start, adjScoreFunc, control$solvers, control)) if(!attr(ans, 'nlsolve.success')){ if(!is.null(control$start) && any(start!=control$start)) { start=control$start ans=nlsolve(start, adjScoreFunc, control$solvers, control) }else warning('None of the non-linear equation solvers succeeded.') } attrs=attributes(ans) names(attrs)=gsub('^nlsolve\\.', '', names(attrs)) attributes(ans)=attrs }else ans=start if(!isTRUE(control$coefOnly)) finalAdjScore = adjScoreFunc(ans) if(rk<ncolx){ ans0=ans ans=rep(NA_real_, ncolx) ans[xxqr$pivot[seq_len(rk)]]=ans0 attributes(ans)=attributes(ans0) } if(isTRUE(control$standardizeX)){ if(any(x.stdCols)) ans[x.stdCols]=ans[x.stdCols]/x.norm[x.stdCols] xx=x[good.weights,,drop=FALSE] } if(control$coefOnly) { ans }else{ ans0=ans ans0[is.na(ans0)]=0 this.ctrl=control this.ctrl$maxit=0L ans=withCallingHandlers(glm.fit3(x=x, y=y, weights = weights, start = ans0, offset = offset, family = family, control = this.ctrl, intercept = TRUE), simpleWarning=ignorableWarnings) ans$converged = attr(ans0, 'success') ans$method = attr(ans0, 'method') ans$iter = attr(ans0, 'iter') ans$adjusted.score = finalAdjScore ans } } fbrNBglm.control= function (standardizeX = TRUE, coefOnly=TRUE, solvers=nlSolvers, verbose = FALSE, maxit=25L, start = NULL, infoParms=list(j=1,k=1,m=1), tol=sqrt(.Machine$double.eps)) { stopifnot(all(sort(names(infoParms))==c('j','k','m'))) structure(list(standardizeX = standardizeX, coefOnly = coefOnly, infoParms=infoParms, solvers = solvers, verbose = verbose, maxit=maxit, start = start, tol = tol), class = "fbrNBglm.control") }
pointdensity <- function(x, eps, type = "frequency", search = "kdtree", bucketSize = 10, splitRule = "suggest", approx = 0) { type <- match.arg(type, choices = c("frequency", "density")) search <- .parse_search(search) splitRule <- .parse_splitRule(splitRule) d <- dbscan_density_int( as.matrix(x), as.double(eps), as.integer(search), as.integer(bucketSize), as.integer(splitRule), as.double(approx) ) if (type == "density") d <- d / (2 * eps * nrow(x)) d }
na.replace <- function(object, ...) { UseMethod("na.replace") } na.replace.tbl_spark <- function(object, ...) { na.replace(spark_dataframe(object), ...) } replace_na.tbl_spark <- function(data, replace, ...) { do.call(na.replace.tbl_spark, append(list(data), replace)) } na.replace.spark_jobj <- function(object, ...) { dots <- list(...) enumerate(dots, function(key, val) { na <- invoke(object, "na") object <<- if (is.null(key)) { invoke(na, "fill", val) } else { invoke(na, "fill", val, as.list(key)) } }) sdf_register(object) } replace_na.spark_jobj <- function(data, replace, ...) { do.call(na.replace.spark_jobj, append(list(data), replace)) } na.omit.tbl_spark <- function(object, columns = NULL, ...) { na.omit(spark_dataframe(object), columns = NULL, ...) } na.omit.spark_jobj <- function(object, columns = NULL, ...) { sc <- spark_connection(object) verbose <- spark_config_value(sc$config, c( "sparklyr.verbose.na", "sparklyr.na.omit.verbose", "sparklyr.na.action.verbose", "sparklyr.verbose" ), TRUE) n_before <- invoke(object, "count") dropped <- sdf_na_omit(object, columns) n_after <- invoke(dropped, "count") if (verbose) { n_diff <- n_before - n_after if (n_diff > 0) { fmt <- "* Dropped %s rows with 'na.omit' (%s => %s)" message(sprintf(fmt, n_diff, n_before, n_after)) } else { message("* No rows dropped by 'na.omit' call") } } if (identical(n_before, n_after) && getOption("na.omit.cache", TRUE)) { sdf_register(object) } else { result <- sdf_register(dropped) invoke(spark_dataframe(result), "cache") result } } na.fail.tbl_spark <- function(object, columns = NULL, ...) { na.fail(spark_dataframe(object), ...) } na.fail.spark_jobj <- function(object, columns = NULL, ...) { n_before <- invoke(object, "count") dropped <- sdf_na_omit(object, columns) n_after <- invoke(dropped, "count") if (n_before != n_after) { stop("* missing values in object") } object } apply_na_action <- function(x, response = NULL, features = NULL, na.action) { if (is.null(na.action)) { return(x) } if (is.character(na.action)) { if (!exists(na.action, envir = parent.frame(), mode = "function")) { stop("no function with name '", na.action, "' found") } na.action <- get(na.action, envir = parent.frame(), mode = "function") } if (!is.function(na.action)) { stop("'na.action' is not a function") } na.action(x, response = response, features = features, columns = c(response, features) ) } sdf_na_omit <- function(object, columns = NULL) { na <- invoke(object, "na") dropped <- if (is.null(columns)) { invoke(na, "drop") } else { invoke(na, "drop", as.list(columns)) } dropped }
irf_fmp <- function(theta, bmat, maxncat = 2, returncat = NA, cvec = NULL, dvec = NULL) { if (any(is.na(returncat))) { if (maxncat == 2) returncat <- 1 else{ returncat <- 0:(maxncat - 1) } } if (maxncat > 2 & (!is.null(cvec) | !is.null(dvec))) message("Beware! Asymptote parameters only available with maxncat = 2!") if (!is.matrix(bmat)) bmat <- as.matrix(bmat) if (ncol(bmat) == 1) bmat <- t(bmat) if (is.null(cvec)) cvec <- rep(0, nrow(bmat)) if (is.null(dvec)) dvec <- rep(1, nrow(bmat)) cvec <- matrix(cvec, nrow = length(theta), ncol = nrow(bmat), byrow = TRUE) dvec <- matrix(dvec, nrow = length(theta), ncol = nrow(bmat), byrow = TRUE) ntheta <- length(theta) if (maxncat > 2) { theta <- t(sapply(theta, function(x) x ^ (1:(ncol(bmat) - maxncat + 1)))) if (nrow(theta) != ntheta) theta <- t(theta) b0 <- bmat[, 1:(maxncat - 1), drop = FALSE] whichbinary <- which(apply(b0, 1, function(x) sum(!is.na(x))) == 1) bm <- bmat[, maxncat:(ncol(bmat)), drop = FALSE] xis <- as.matrix(apply(b0, 1, cumsum)) out <- array(NA, dim = c(ntheta, nrow(bmat), maxncat)) out[, , 1] <- 1 for (i in 2:maxncat) { out[, , i] <- exp(theta %*% t(bm) * (i - 1) + rep(1, ntheta) %*% t(xis[i - 1, ])) } out[is.infinite(out)] <- 1e+200 den <- apply(out, c(1, 2), sum, na.rm = TRUE) for (i in 1:maxncat) out[, , i] <- out[, , i] / den out[, whichbinary, 2] <- cvec[whichbinary] + (dvec[whichbinary] - cvec[whichbinary]) * out[, whichbinary, 2] out[, whichbinary, 1] <- 1 - out[, whichbinary, 2] } else{ theta <- t(sapply(theta, function(x) x ^ (0:(ncol(bmat) - 1)))) out <- array(NA, dim = c(ntheta, nrow(bmat), maxncat)) out[, , 2] <- cvec + (dvec - cvec) / (1 + exp(-theta %*% t(bmat))) out[, , 1] <- 1 - out[, , 2] } out <- out[, , returncat + 1, drop = FALSE] if (dim(out)[3] == 1) out <- matrix(out, nrow = dim(out)[1]) out }
library(rethinking) library(animation) library(ellipse) data(Trolley) d <- Trolley blank(bty="n") y <- table( d$response ) plot( NULL , xlim=c(0.5,7.5) , ylim=c(0,max(y)+1000) , xlab="outcome" , ylab="frequency" ) for ( i in 1:7 ) lines( c(i,i) , c(0,y[i]) , lwd=8 , col=2 ) ycum <- cumsum(y) ani.record(reset=TRUE) nf <- 30 p <- seq(from=0,to=1,len=nf) for ( f in 1:nf ) { ymax <- max(max(y),p[f]*max(ycum))+1000 plot( NULL , xlim=c(0.5,7.5) , ylim=c(0,ymax) , xlab="outcome" , ylab="cumulative frequency" ) lines( c(1,1) , c(0,ycum[1]) , lwd=8 , col=2 ) for ( i in 2:7 ) { xboost <- p[f]*ycum[i-1] lines( c(i,i) , c(0,y[i])+xboost , lwd=8 , col=2 ) } ani.record() } for ( i in 1:7 ) lines( c(i,i) , c(0,ycum[i]) , lwd=6 ) lines( c(1,1) , c(0,ycum[1]) , lwd=8 , col=2 ) for ( i in 2:7 ) lines( c(i,i) , c(ycum[i-1],ycum[i]) , lwd=8 , col=2 ) ani.record() for ( i in 1:6 ) lines( c(i,i+1) , c(ycum[i],ycum[i]) , lty=3 , lwd=2 , col=2 ) ani.record() oopts = ani.options(interval = 0.1) ani.replay() p <- y/sum(y) pcum <- ycum/max(ycum) ani.record(reset=TRUE) for ( l in 1:7 ) { plot( NULL , xlim=c(0.5,7.5) , ylim=c(0,1) , xlab="outcome" , ylab="cumulative proportion" ) for ( i in 1:7 ) lines( c(i,i) , c(0,pcum[i]) , lwd=6 ) lines( c(1,1) , c(0,pcum[1]) , lwd=8 , col=2 ) for ( i in 2:7 ) { xboost <- pcum[i-1] lines( c(i,i) , c(0,p[i])+xboost , lwd=8 , col=2 ) } for ( i in 1:l ) lines( c(-2,i) , c(pcum[i],pcum[i]) , lwd=2 , lty=3 , col=2 ) ani.record() } oopts = ani.options(interval = 0.2) ani.replay() nsteps <- 30 phi_seq <- seq( from=0 , to=2 , len=nsteps ) phi_seq <- c(phi_seq,rep(2,10)) phi_seq <- c(phi_seq, seq( from=2 , to=-2 , len=nsteps*2 ) ) phi_seq <- c(phi_seq,rep(-2,10)) phi_seq <- c(phi_seq, seq( from=-2 , to=0 , len=nsteps ) ) blank(bty="n",w=2.5) par(mfrow=c(1,2)) ani.record(reset=TRUE) par(mfrow=c(1,2)) for ( phi in phi_seq) { lpc <- logit(pcum) + phi ilpc <- inv_logit(lpc) xmax <- max(lpc[1:6]) + 1.5 xmin <- min(lpc[1:6]) - 1 xmax <- 6 xmin <- -5 plot( lpc[1:6] , ilpc[1:6] , lwd=4 , col=4 , pch=1 , xlab="cumulative log-odds" , ylab="cumulative proportion" , xlim=c(xmin,xmax) , ylim=c(0,1) , xaxt="n" ) points( xmax , 1 , lwd=4 , col=grau() ) at <- c(-4,-2,0,2,4) axis(1,at=c(at,xmax),labels=c(at,"Inf")) for ( i in 1:7 ) { lines( c(xmin-1,lpc[i]) , c(ilpc[i],ilpc[i]) , lwd=2 , lty=3 , col=2 ) lines( c(lpc[i],lpc[i]) , c(0,ilpc[i]) , lwd=2 , lty=3 , col=4 ) } lines( c(xmin-1,xmax) , c(1,1) , lwd=2, lty=3 , col=2 ) par( xpd=TRUE ) points( phi , -0.04 , cex=2 , col=1 , pch=16 ) par( xpd=FALSE ) p <- sapply( 2:7 , function(i) ilpc[i] - ilpc[i-1] ) p <- c( ilpc[1] , p ) plot( NULL , xlim=c(0.5,7.5) , ylim=c(0,0.6) , xlab="observed value" , ylab="probability" ) for ( i in 1:7 ) { lines( c(i,i) , c(0,p[i]) , lwd=12 , col=col.alpha(2,0.4) ) lines( c(i,i) , c(0,p[i]) , lwd=8 , col=2 ) } ani.record() } oopts = ani.options(interval = 0.1) ani.replay() data(Trolley) d <- Trolley dat <- list( R = d$response, A = d$action, I = d$intention, C = d$contact ) mRX <- ulam( alist( R ~ dordlogit(phi,alpha), phi <- bA*A + bI*I + bC*C, c(bA,bI,bC) ~ normal(0,0.5), alpha ~ normal(0,1) ) , data=dat , chains=4 , cores=4 ) precis(mRX,2) vals <- c(0,1,1) Rsim <- mcreplicate( 100 , sim(mRX,data=list(A=vals[1],I=vals[2],C=vals[3])) , mc.cores=6 ) simplehist(as.vector(Rsim),lwd=8,col=2,xlab="Response") mtext(concat("A=",vals[1],", I=",vals[2],", C=",vals[3])) dat$G <- ifelse(d$male==1,2,1) mRXG <- ulam( alist( R ~ dordlogit(phi,alpha), phi <- bA[G]*A + bI[G]*I + bC[G]*C, bA[G] ~ normal(0,0.5), bI[G] ~ normal(0,0.5), bC[G] ~ normal(0,0.5), alpha ~ normal(0,1) ) , data=dat , chains=4 , cores=4 ) precis(mRXG,2) vals <- c(0,1,1,2) Rsim <- mcreplicate( 100 , sim(mRXG,data=list(A=vals[1],I=vals[2],C=vals[3],G=vals[4])) , mc.cores=6 ) simplehist(as.vector(Rsim),lwd=8,col=2,xlab="Response") mtext(concat("A=",vals[1],", I=",vals[2],", C=",vals[3],", G=",vals[4])) edu_levels <- c( 6 , 1 , 8 , 4 , 7 , 2 , 5 , 3 ) edu_new <- edu_levels[ d$edu ] simplehist(edu_new,xlab="education level (ordered)",lwd=8,col=2) simplehist(d$age,xlab="age (years)",lwd=6,col=4) library(gtools) nf <- 40 a <- 10 delta <- rdirichlet( nf , a=rep(a,7) ) delta <- rdirichlet( nf , a=1:7 ) ani.record(reset=TRUE) for ( f in 1:nf) { plot( NULL , xlim=c(1,7) , ylim=c(0,0.4) , xlab="index" , ylab="probability" ) if ( f > 1 ) { start <- max(f-3,1) for ( i in start:(f-1) ) lines( 1:7 , delta[i,] , type="l" , lwd=4 , col=grau(0.25*i/f) ) } lines( 1:7 , delta[f,] , type="b" , lwd=4 , col=2 ) ani.record() } oopts = ani.options(interval = 0.3) ani.replay() edu_levels <- c( 6 , 1 , 8 , 4 , 7 , 2 , 5 , 3 ) edu_new <- edu_levels[ d$edu ] dat$E <- edu_new dat$a <- rep(2,7) mRXE <- ulam( alist( R ~ ordered_logistic( phi , alpha ), phi <- bE*sum( delta_j[1:E] ) + bA*A + bI*I + bC*C, alpha ~ normal( 0 , 1 ), c(bA,bI,bC,bE) ~ normal( 0 , 0.5 ), vector[8]: delta_j <<- append_row( 0 , delta ), simplex[7]: delta ~ dirichlet( a ) ), data=dat , chains=4 , cores=4 ) precis(mRXE,2) dat$Y <- standardize(d$age) mRXEYG <- ulam( alist( R ~ ordered_logistic( phi , alpha ), phi <- bE[G]*sum( delta_j[1:E] ) + bA[G]*A + bI[G]*I + bC[G]*C + bY[G]*Y, alpha ~ normal( 0 , 1 ), bA[G] ~ normal( 0 , 0.5 ), bI[G] ~ normal( 0 , 0.5 ), bC[G] ~ normal( 0 , 0.5 ), bE[G] ~ normal( 0 , 0.5 ), bY[G] ~ normal( 0 , 0.5 ), vector[8]: delta_j <<- append_row( 0 , delta ), simplex[7]: delta ~ dirichlet( a ) ), data=dat , chains=4 , cores=4 ) mRXEYGt <- ulam( alist( R ~ ordered_logistic( phi , alpha ), phi <- bE[G]*sum( delta_j[1:E] ) + bA[G]*A + bI[G]*I + bC[G]*C + bY[G]*Y, alpha ~ normal( 0 , 1 ), bA[G] ~ normal( 0 , 0.5 ), bI[G] ~ normal( 0 , 0.5 ), bC[G] ~ normal( 0 , 0.5 ), bE[G] ~ normal( 0 , 0.5 ), bY[G] ~ normal( 0 , 0.5 ), vector[8]: delta_j <<- append_row( 0 , delta ), simplex[7]: delta ~ dirichlet( a ) ), data=dat , chains=4 , cores=4 , threads=2 ) precis(mRXEYGt,2) dat$G1 <- ifelse(dat$G==1,1,0) dat$G2 <- ifelse(dat$G==2,1,0) mRXEYG2t <- ulam( alist( R ~ ordered_logistic( phi , alpha ), phi <- G1*bE[G]*sum( deltaF_j[1:E] ) + G2*bE[G]*sum( deltaM_j[1:E] ) + bA[G]*A + bI[G]*I + bC[G]*C + bY[G]*Y, alpha ~ normal( 0 , 1 ), bA[G] ~ normal( 0 , 0.5 ), bI[G] ~ normal( 0 , 0.5 ), bC[G] ~ normal( 0 , 0.5 ), bE[G] ~ normal( 0 , 0.5 ), bY[G] ~ normal( 0 , 0.5 ), vector[8]: deltaF_j <<- append_row( 0 , deltaF ), vector[8]: deltaM_j <<- append_row( 0 , deltaM ), simplex[7]: deltaF ~ dirichlet( a ), simplex[7]: deltaM ~ dirichlet( a ) ), data=dat , chains=4 , cores=4 , threads=2 ) precis(mRXEYG2t,2)
write.rdsobj <- function(x, file) { if (!inherits(x, "rds.data.frame")) stop("data is not an rds.data.frame object") saveRDS(x, file) } write.graphviz <- function(x, file) { x <- as.rds.data.frame(x) id <- as.char(get.id(x)) rid <- as.char(get.rid(x)) sid <- as.char(get.seed.rid(x)) w <- get.wave(x) el <- cbind(rid, id) el <- el[order(w), ] el <- el[rid != sid, ] cat("digraph rds {\nsize=\"8.5,8.5\";\nlayout=neato;\nmode=\"hier\";", file = file) cat( paste0("\"", el[, 1], "\" -> \"", el[, 2], "\"", collapse = ";\n"), file = file, append = TRUE ) cat("}", file = file, append = TRUE) } write.netdraw <- function(x, file = NULL, by.seed = FALSE) { rds.data <- as.rds.data.frame(x) id <- get.id(rds.data) recruiter.id <- get.rid(rds.data) seed.id <- get.seed.id(rds.data) seed.rid <- get.seed.rid(rds.data) write.parent.child.connections <- function(idx, participants) { children <- get.children(idx) children <- children[!is.na(children)] for (child.idx in children[!is.na(children)]) { if (length(unlist(children)) > 0) { cat(sprintf( "%s %s\n", match(idx, participants), match(child.idx, participants) ), file = DL.file) } } } get.children <- function(idx) { id[recruiter.id == idx] } get.recruiter.row <- function(idx, rid) { rid[id == idx] } get.child.idx <- function(child, rid = get.rid(rds.data)) { parent <- get.recruiter.row(child, rid) if (parent != seed.rid) siblings <- get.children(parent) return((1:length(siblings))[siblings == child]) } if (is.null(file)) { file.base <- paste(getwd(), substitute(rds.data), sep = "/") } else{ file.base <- file } header.to.DL <- paste('DL n = ', nrow(rds.data), ', format = edgelist1\n', 'labels:\n', sep = "") if (by.seed) { seeds <- sort(unique(seed.id)) for (seed in seq(along = seeds)) { n <- sum(seed.id == seeds[seed]) header.to.DL <- paste('DL n = ', n, ', format = edgelist1\n', 'labels:\n', sep = "") if (n < 2) next DL.file <- file(sprintf("%s_Seed%s.DL", file.base, seeds[seed]), "wt") cat(header.to.DL, file = DL.file, append = TRUE, fill = FALSE) participants <- id[seed.id == seeds[seed]] cat( paste("'", paste(participants, collapse = "','"), "'", sep = ""), file = DL.file, append = TRUE, fill = FALSE ) cat( paste('\n', 'data:\n', sep = ""), file = DL.file, append = TRUE, fill = FALSE ) sapply(participants, write.parent.child.connections, participants) close(DL.file) ADL.file <- sprintf("%s_Seed%s.vna", file.base, seeds[seed]) rd1 <- cbind(ID = id, rds.data)[seed.id == seeds[seed], ] cat( "*node data\n", file = ADL.file, append = FALSE, fill = FALSE ) suppressWarnings( utils::write.table( rd1, file = ADL.file, append = TRUE, row.names = FALSE, eol = "\r\n", sep = "\t" ) ) } } else{ DL.file <- file(sprintf("%s.DL", file.base), "wt") cat(header.to.DL, file = DL.file, append = FALSE, fill = FALSE) participants <- id cat( paste("'", paste(participants, collapse = "','"), "'", sep = ""), file = DL.file, append = TRUE, fill = FALSE ) cat( paste('\n', 'data:\n', sep = ""), file = DL.file, append = TRUE, fill = FALSE ) sapply(participants, write.parent.child.connections, participants) cat("\n", file = DL.file, append = TRUE, fill = FALSE) close(DL.file) ADL.file <- sprintf("%s.vna", file.base) rd1 <- cbind(ID = id, rds.data) cat("*node data\n", file = ADL.file, append = FALSE, fill = FALSE) suppressWarnings( utils::write.table( rd1, file = ADL.file, append = TRUE, row.names = FALSE, eol = "\r\n", sep = "\t" ) ) } invisible() } write.rdsat <- function(x, file = NULL) { rds.data <- as.rds.data.frame(x) id <- get.id(rds.data) recruiter.id <- get.rid(rds.data) max.coupons <- length(tabulate(table(recruiter.id))) if (is.null(file)) { file.base <- paste(getwd(), substitute(rds.data), sep = "/") } else{ file.base <- file } get.children <- function(idx) { id[recruiter.id == idx] } coupons <- matrix("", ncol = max.coupons, nrow = nrow(rds.data)) for (idx in id) { children <- get.children(idx) children <- children[!is.na(children)] if (length(children) > 0) { coupons[match(idx, id), seq_along(children)] <- children } } coupons[coupons == ""] <- paste(nrow(rds.data) + (1:sum(coupons == ""))) network.size <- attr(rds.data, "network.size") full.rds <- cbind(id, rds.data[, network.size], id, coupons, rds.data) colnames(full.rds)[2] <- "network.size" header.to.RDSAT <- paste( 'RDS\n', nrow(rds.data), " ", max.coupons, " 0 ", paste(colnames(rds.data), collapse = " "), '\n', sep = "" ) RDSAT.file <- file(sprintf("%s.rdsat", file.base), "wt") cat(header.to.RDSAT, file = RDSAT.file, append = FALSE, fill = FALSE) utils::write.table( full.rds, file = RDSAT.file, quote = FALSE, append = TRUE, row.names = FALSE, col.names = FALSE ) close(RDSAT.file) invisible() }
test_that("classif_xgboost", { requirePackagesOrSkip("xgboost", default.method = "load") parset.list = list( list(), list(nrounds = 20L) ) parset.probs.list = list( list(), list(objective = "multi:softprob") ) old.predicts.list = list() old.probs.list = list() for (i in seq_along(parset.list)) { parset = parset.list[[i]] pars = list(data = data.matrix(binaryclass.train[, 1:60]), label = as.numeric(binaryclass.train[, 61]) - 1) if (is.null(parset$objective)) parset$objective = "binary:logistic" if (is.null(parset$verbose)) parset$verbose = 0L if (is.null(parset$nround)) parset$nrounds = 1L pars = c(pars, parset) model = do.call(xgboost::xgboost, pars) pred = predict(model, data.matrix(binaryclass.test[, 1:60])) old.predicts.list[[i]] = factor(as.numeric(pred > 0.5), labels = binaryclass.class.levs) } for (i in seq_along(parset.probs.list)) { parset = parset.probs.list[[i]] pars = list(data = data.matrix(binaryclass.train[, 1:60]), label = as.numeric(binaryclass.train[, 61]) - 1) if (is.null(parset$objective)) parset$objective = "binary:logistic" if (is.null(parset$verbose)) parset$verbose = 0L if (is.null(parset$nround)) parset$nrounds = 1L if (parset$objective == "multi:softprob") { parset$num_class = length(binaryclass.class.levs) } pars = c(pars, parset) model = do.call(xgboost::xgboost, pars) pred = predict(model, data.matrix(binaryclass.test[, 1:60])) if (parset$objective == "multi:softprob") { y = matrix(pred, nrow = length(pred) / length(binaryclass.class.levs), ncol = length(binaryclass.class.levs), byrow = TRUE) old.probs.list[[i]] = y[, 1] } else { old.probs.list[[i]] = 1 - pred } } testSimpleParsets("classif.xgboost", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.predicts.list, parset.list) testProbParsets("classif.xgboost", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.probs.list, parset.probs.list) }) test_that("xgboost works with different 'missing' arg vals", { expect_silent(makeLearner("classif.xgboost", missing = NA_real_)) expect_silent(makeLearner("classif.xgboost", missing = NA)) expect_silent(makeLearner("classif.xgboost", missing = NULL)) }) test_that("xgboost objective 'multi:softmax' does not work with predict.type = 'prob'", { expect_error(train(makeLearner("classif.xgboost", predict.type = "prob", objective = "multi:softmax"), binaryclass.task)) }) test_that("multiclass xgboost with 'multi:softmax' does not produce NA predictions", { mod = train(makeLearner("classif.xgboost", objective = "multi:softmax"), task = multiclass.task) pred = predict(mod, multiclass.task) expect_false(any(is.na(pred$data$response))) }) test_that("xgboost with multi:softprob", { learner = makeLearner("classif.xgboost", nrounds = 5L, objective = "multi:softprob") mod = train(learner, sonar.task) pred = predict(mod, sonar.task) expect_equal(unname(performance(pred, measures = getDefaultMeasure(sonar.task))), 0) }) test_that("xgboost with binary:logistic", { learner = makeLearner("classif.xgboost", nrounds = 5L) mod = train(learner, sonar.task) pred = predict(mod, sonar.task) expect_equal(unname(performance(pred, measures = getDefaultMeasure(sonar.task))), 0) })