code
stringlengths
1
13.8M
CEx <- function(model, param, conc){ if (missing(model) || missing (param) || missing(conc)) stop('argument missing') if (is.vector(param)) param <- t(param) effv <- matrix(0, length(model), length(conc)) for (i in seq(model)){ fun <- model[i] p <- param[i, ] for (j in seq(conc)){ if (fun == 'Hill') ev <- 1 / (1 + (p[1] / conc[j])^p[2]) else if (fun == 'Hill_two') ev <- p[2] * conc[j] / (p[1] + conc[j]) else if (fun == 'Hill_three') ev <- p[3] /(1 + (p[1] / conc[j])^p[2]) else if (fun == 'Hill_four') ev <- p[4] + (p[3] - p[4]) / (1 + (p[1] / conc[j])^p[2]) else if(fun == 'Weibull') ev <- 1 - exp(-exp(p[1] + p[2] * log10(conc[j]))) else if(fun == 'Weibull_three') ev <- p[3] * (1 - exp(-exp(p[1] + p[2] * log10(conc[j])))) else if(fun == 'Weibull_four') ev <- p[3] + (p[4] - p[3]) * exp(-exp(p[1] + p[2] * log10(conc[j]))) else if (fun == "Logit") ev <- 1 / (1 + exp(-p[1] - p[2] * log10(conc[j]))) else if(fun == 'Logit_three') ev <- p[3] / (1 + exp((-p[1]) - p[2] * log10(conc[j]))) else if(fun == 'Logit_four') ev <- p[4] + (p[3] - p[4]) / (1 + exp((-p[1]) - p[2] * log10(conc[j]))) else if (fun == "BCW") ev <- 1 - exp(-exp(p[1] + p[2] * ((conc[j]^p[3] - 1) / p[3]))) else if (fun == "BCL") ev <- 1 / (1 + exp(-p[1] - p[2]((conc[j]^p[3] - 1) / p[3]))) else if (fun == "GL") ev <- 1 / (1 + exp(-p[1] - p[2] * log10(conc[j])))^p[3] else if (fun == "Brain_Consens") ev <- 1 - (1 + p[1] * conc[j]) / (1 + exp(p[2] * p[3]) * conc[j]^p[2]) else if(fun == "BCV") ev <- 1 - p[1] * (1 + p[2] * conc[j]) / (1 + (1 + 2 * p[2] * p[3]) * (conc[j] / p[3])^p[4]) else if(fun == "Cedergreen") ev <- 1 - (1 + p[1] * exp(-1 / (conc[j]^p[2]))) / (1 + exp(p[3] * (log(conc[j]) - log(p[4])))) else if(fun == "Beckon") ev <- (p[1] + (1 - (p[1]) / (1 + (p[2] / conc[j])^p[3]))) / (1 + (conc[j] / p[4])^p[5]) else if(fun == "Biphasic") ev <- p[1] - p[1] / (1 + 10^((conc[j] - p[2]) * p[3])) + (1 - p[1]) / (1 + 10^((p[4] - conc[j]) * p[5])) else if(fun == 'Hill_five') ev <- 1 - (1 + (p[3] - 1) / (1 + (p[1] / conc[j])^p[2])) * (1 - 1 / (1 + (p[4] / conc[j])^p[5])) effv[i, j] <- ev } } colName <- paste('Rspn_@_', conc, sep = '') colnames(effv) <- colName if(is.null(rownames(param))) rownames(effv) <- model else rownames(effv) <- rownames(param) return(effv) }
test.readOrg <- function() { checkException(readOrg("~/Packages/orgutils/inst/unitTests/orgtable0.org"), silent = TRUE) t1 <- readOrg("~/Packages/orgutils/inst/unitTests/orgtable1.org") checkEquals(t1, structure(list(col1 = c(1L, 4L), col2 = c(2L, 5L), col3 = c("3", "test")), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA, -2L))) t2 <- readOrg("~/Packages/orgutils/inst/unitTests/orgtable2.org") checkEquals(t2, structure(list(col1 = c(1L, 4L), col2 = c(2L, 5L), col3 = c("3", "test")), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA, -2L))) t3 <- readOrg("~/Packages/orgutils/inst/unitTests/orgtable3.org", table.name = "table3") checkEquals(t3, structure(list(col1 = c(1L, 4L), col2 = c(2L, 5L), col3 = c("3", "test")), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA, -2L))) t4 <- readOrg("~/Packages/orgutils/inst/unitTests/orgtable4.org", table.name = "table4") checkEquals(t4, structure(list(col1 = c(1L, 4L), col2 = c(2L, 5L), col3 = c("3", "test")), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA, -2L))) t5 <- readOrg("~/Packages/orgutils/inst/unitTests/orgtable5.org", table.name = "table5") checkEquals(t5, structure(list(col1 = c(1L, 4L), col2 = c(2L, 5L), col3 = c("3", "test")), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA, -2L))) t6 <- readOrg("~/Packages/orgutils/inst/unitTests/orgtable6.org", table.name = "table6") checkEquals(t6, structure(list(col1 = c(1L, 4L, 7L), col2 = c(2L, 5L, 8L), col3 = c(3L, 6L, 9L)), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA, -3L))) t7 <- readOrg("~/Packages/orgutils/inst/unitTests/orgtable7.org") checkEquals(t7, structure(list(col1 = character(0), col2 = character(0), col3 = character(0)), .Names = c("col1", "col2", "col3"), row.names = integer(0), class = "data.frame")) t8 <- readOrg("~/Packages/orgutils/inst/unitTests/orgtable8.org") checkEquals(t8, structure(list(col1 = character(0), col2 = character(0), col3 = character(0)), .Names = c("col1", "col2", "col3"), row.names = integer(0), class = "data.frame")) t9 <- readOrg("~/Packages/orgutils/inst/unitTests/orgtable9.org") checkEquals(t9, structure(list(col1 = 1L, col2 = 2L, col3 = 3L), .Names = c("col1", "col2", "col3"), row.names = c(NA, -1L), class = "data.frame")) } test.toOrg <- function() { df <- data.frame(x = 1:3, row.names = letters[1:3]) tbl <- structure(c("| row.names | x |", "|-----------+---|", "| a | 1 |", "| b | 2 |", "| c | 3 |"), class = "org") checkEquals(tbl, toOrg(df)) checkEquals(tbl, toOrg(df), TRUE) df <- data.frame(x = 1:3) tbl <- structure(c("| x |", "|---|", "| 1 |", "| 2 |", "| 3 |"), class = "org") checkEquals(tbl, toOrg(df)) df <- data.frame(x = 1:3) tbl <- structure(c("| row.names | x |", "|-----------+---|", "| 1 | 1 |", "| 2 | 2 |", "| 3 | 3 |"), class = "org") checkEquals(tbl, toOrg(data.frame(x = 1:3), TRUE)) checkEquals(toOrg(as.Date("2016-1-1")), structure(paste0("<2016-01-01 ", format(as.Date("2016-01-01"), "%a"), ">"), class = c("org", "character"))) checkEquals(toOrg(as.Date("2016-1-1"), inactive = TRUE), structure(paste0("[2016-01-01 ", format(as.Date("2016-01-01"), "%a"), "]"), class = c("org", "character"))) times <- as.POSIXct(c("2016-1-1 10:00:00", "2016-1-1 11:00:00"), tz = Sys.timezone(location = TRUE)) checkEquals(toOrg(times), structure(paste("<2016-01-01", format(times, "%a"), c("10:00:00>", "11:00:00>")), class = c("org", "character"))) times <- as.POSIXlt(times) checkEquals(toOrg(times), structure(paste("<2016-01-01", format(times, "%a"), c("10:00:00>", "11:00:00>")), class = c("org", "character"))) }
poped_optim_2 <- function(poped.db, opt_xt=poped.db$settings$optsw[2], opt_a=poped.db$settings$optsw[4], opt_x=poped.db$settings$optsw[3], opt_samps=poped.db$settings$optsw[1], opt_inds=poped.db$settings$optsw[5], method=c("ARS","BFGS","LS"), control=list(), trace = TRUE, fim.calc.type=poped.db$settings$iFIMCalculationType, ofv_calc_type=poped.db$settings$ofv_calc_type, approx_type=poped.db$settings$iApproximationMethod, d_switch=poped.db$settings$d_switch, ED_samp_size = poped.db$settings$ED_samp_size, bLHS=poped.db$settings$bLHS, use_laplace=poped.db$settings$iEDCalculationType, out_file="", parallel=F, parallel_type=NULL, num_cores = NULL, loop_methods=ifelse(length(method)>1,TRUE,FALSE), iter_max = 10, stop_crit_eff = 1.001, stop_crit_diff = NULL, stop_crit_rel = NULL, ofv_fun = poped.db$settings$ofv_fun, maximize=T, transform_parameters = F, ...){ called_args <- match.call() default_args <- formals() for(i in names(called_args)[-1]){ if(length(grep("^poped\\.db\\$",capture.output(default_args[[i]])))==1) { eval(parse(text=paste(capture.output(default_args[[i]]),"<-",i))) } } fmf = 0 dmf = 0 if(is.null(ofv_fun) || is.function(ofv_fun)){ ofv_fun_user <- ofv_fun } else { if(file.exists(as.character(ofv_fun))){ source(as.character(ofv_fun)) ofv_fun_user <- eval(parse(text=fileparts(ofv_fun)[["filename"]])) } else { stop("ofv_fun is not a function or NULL, and no file with that name was found") } } if(!is.null(ofv_fun)){ poped.db$settings$ofv_calc_type = 0 } output <-calc_ofv_and_fim(poped.db,d_switch=d_switch, ED_samp_size=ED_samp_size, bLHS=bLHS, use_laplace=use_laplace, ofv_calc_type=ofv_calc_type, fim.calc.type=fim.calc.type, ofv_fun = ofv_fun_user, ...) fmf <- output$fim dmf <- output$ofv fmf_init <- fmf dmf_init <- dmf poped.db_init <- poped.db if(is.nan(dmf_init)) stop("Objective function of initial design is NaN") fn=blockheader(poped.db,name="optim",e_flag=!d_switch, fmf=fmf_init,dmf=dmf_init, out_file=out_file, trflag=trace, ...) my_ofv <- create_ofv(poped.db=poped.db, opt_xt=opt_xt, opt_a=opt_a, opt_x=opt_x, opt_samps=opt_samps, opt_inds=opt_inds, fim.calc.type=fim.calc.type, ofv_calc_type=ofv_calc_type, approx_type=approx_type, d_switch=d_switch, ED_samp_size = ED_samp_size, bLHS=bLHS, use_laplace=use_laplace, ofv_fun = ofv_fun, transform_parameters = transform_parameters, ...) par <- my_ofv$par ofv_fun <- my_ofv$fun back_transform_par_fun <- my_ofv$back_transform_par lower=my_ofv$space[["lower"]] upper=my_ofv$space[["upper"]] allowed_values=my_ofv$space[["allowed_values"]] par_cat_cont=my_ofv$space[["par_cat_cont"]] par_fixed_index=my_ofv$space[["par_fixed_index"]] par_not_fixed_index=my_ofv$space[["par_not_fixed_index"]] par_df_unique=my_ofv$space[["par_df_unique"]] par_df=my_ofv$space[["par_df"]] par_dim=my_ofv$space[["par_dim"]] par_type=my_ofv$space[["par_type"]] if(!(fn=="")) sink(fn, append=TRUE, split=TRUE) iter <- 0 stop_crit <- FALSE output$ofv <- dmf_init while(stop_crit==FALSE && iter < iter_max){ ofv_init <- output$ofv iter=iter+1 method_loop <- method if(loop_methods){ cat("************* Iteration",iter," for all optimization methods***********************\n\n") } while(length(method_loop)>0){ cur_meth <- method_loop[1] method_loop <- method_loop[-1] if(cur_meth=="ARS"){ cat("*******************************************\n") cat("Running Adaptive Random Search Optimization\n") cat("*******************************************\n") con <- list(trace = trace, parallel=parallel, parallel_type=parallel_type, num_cores = num_cores) nmsC <- names(con) con[(namc <- names(control$ARS))] <- control$ARS output <- do.call(optim_ARS,c(list(par=par, fn=ofv_fun, lower=lower, upper=upper, allowed_values = allowed_values, maximize=maximize ), con, ...)) } if(cur_meth=="LS"){ cat("*******************************************\n") cat("Running Line Search Optimization\n") cat("*******************************************\n") con <- list(trace = trace, parallel=parallel, parallel_type=parallel_type, num_cores = num_cores) nmsC <- names(con) con[(namc <- names(control$LS))] <- control$LS output <- do.call(optim_LS,c(list(par=par, fn=ofv_fun, lower=lower, upper=upper, allowed_values = allowed_values, maximize=maximize ), con, ...)) } if(cur_meth=="BFGS"){ cat("*******************************************\n") cat("Running L-BFGS-B Optimization\n") cat("*******************************************\n") if(all(par_cat_cont=="cat")){ cat("\nNo continuous variables to optimize, L-BFGS-B Optimization skipped\n\n") next } if(trace) trace_optim=3 if(is.numeric(trace)) trace_optim = trace con <- list(trace=trace_optim) nmsC <- names(con) con[(namc <- names(control$BFGS))] <- control$BFGS fnscale=-1 if(!maximize) fnscale=1 if(is.null(con[["fnscale"]])) con$fnscale <- fnscale par_full <- par output <- optim(par=par[par_cat_cont=="cont"], fn=ofv_fun, gr=NULL, only_cont=T, lower=lower[par_cat_cont=="cont"], upper=upper[par_cat_cont=="cont"], method = "L-BFGS-B", control=con) output$ofv <- output$value par_tmp <- output$par output$par <- par_full output$par[par_cat_cont=="cont"] <- par_tmp fprintf('\n') if(fn!="") fprintf(fn,'\n') } if(cur_meth=="GA"){ cat("*******************************************\n") cat("Running Genetic Algorithm (GA) Optimization\n") cat("*******************************************\n") if (!requireNamespace("GA", quietly = TRUE)) { stop("GA package needed for this function to work. Please install it.", call. = FALSE) } if(all(par_cat_cont=="cat")){ cat("\nNo continuous variables to optimize, GA Optimization skipped\n\n") next } parallel_ga <- parallel if(!is.null(num_cores)) parallel_ga <- num_cores if(!is.null(parallel_type)) parallel_ga <- parallel_type con <- list(parallel=parallel_ga) dot_vals <- dots(...) nmsC <- names(con) con[(namc <- names(control$GA))] <- control$GA par_full <- par ofv_fun_2 <- ofv_fun if(!maximize) { ofv_fun_2 <- function(par,only_cont=F,...){ -ofv_fun(par,only_cont=F,...) } } output_ga <- do.call(GA::ga,c(list(type = "real-valued", fitness = ofv_fun_2, only_cont=T, min=lower[par_cat_cont=="cont"], max=upper[par_cat_cont=="cont"], suggestions=par[par_cat_cont=="cont"]), con, ...)) output$ofv <- output_ga@fitnessValue if(!maximize) output$ofv <- -output$ofv output$par <- output_ga@solution par_tmp <- output$par output$par <- par_full output$par[par_cat_cont=="cont"] <- par_tmp fprintf('\n') if(fn!="") fprintf(fn,'\n') } par <- output$par } if(!loop_methods){ stop_crit <- TRUE } else { cat("*******************************************\n") cat("Stopping criteria testing\n") cat("(Compare between start of iteration and end of iteration)\n") cat("*******************************************\n") rel_diff <- (output$ofv - ofv_init)/abs(ofv_init) abs_diff <- (output$ofv - ofv_init) fprintf("Difference in OFV: %.3g\n",abs_diff) fprintf("Relative difference in OFV: %.3g%%\n",rel_diff*100) eff <- efficiency(ofv_init, output$ofv, poped.db) fprintf("Efficiency: \n (%s) = %.5g\n",attr(eff,"description"),eff) compare <-function(crit,crit_stop,maximize,inv=FALSE,neg=FALSE,text=""){ if(is.null(crit_stop)){ return(FALSE) } cat("\n",text,"\n") if(is.nan(crit)){ fprintf(" Stopping criteria using 'NaN' as a comparitor cannot be used\n") return(FALSE) } comparitor <- "<=" if(!maximize) comparitor <- ">=" if(inv) crit_stop <- 1/crit_stop if(neg) crit_stop <- -crit_stop fprintf(" Is (%0.5g %s %0.5g)? ",crit,comparitor,crit_stop) res <- do.call(comparitor,list(crit,crit_stop)) if(res) cat(" Yes.\n Stopping criteria achieved.\n") if(!res) cat(" No.\n Stopping criteria NOT achieved.\n") return(res) } if(all(is.null(c(stop_crit_eff,stop_crit_rel,stop_crit_diff)))){ cat("No stopping criteria defined") } else { stop_eff <- compare(eff,stop_crit_eff,maximize,inv=!maximize, text="Efficiency stopping criteria:") stop_abs <- compare(abs_diff,stop_crit_diff,maximize,neg=!maximize, text="OFV difference stopping criteria:") stop_rel <- compare(rel_diff,stop_crit_rel,maximize,neg=!maximize, text="Relative OFV difference stopping criteria:") if(stop_eff || stop_rel || stop_abs) stop_crit <- TRUE if(stop_crit){ cat("\nStopping criteria achieved.\n") } else { cat("\nStopping criteria NOT achieved.\n") } cat("\n") } } } if(!(fn=="")) sink() par <- back_transform_par_fun(par) if(length(par_fixed_index)!=0){ par_df_2[par_not_fixed_index,"par"] <- par par <- par_df_2$par } if(!is.null(par_df_unique)){ par_df_unique$par <- par for(j in par_df_unique$par_grouping){ par_df[par_df$par_grouping==j,"par"] <- par_df_unique[par_df_unique$par_grouping==j,"par"] } } else { par_df$par <- par } if(opt_xt){ xt <- zeros(par_dim$xt) par_xt <- par_df[par_type=="xt","par"] for(i in 1:poped.db$design$m){ if((poped.db$design$ni[i]!=0 && poped.db$design$groupsize[i]!=0)){ xt[i,1:poped.db$design$ni[i]] <- par_xt[1:poped.db$design$ni[i]] par_xt <- par_xt[-c(1:poped.db$design$ni[i])] } } poped.db$design$xt[,]=xt[,] } if(opt_a) poped.db$design$a[,]=matrix(par_df[par_type=="a","par"],par_dim$a) FIM <-calc_ofv_and_fim(poped.db, ofv=output$ofv, fim=0, d_switch=d_switch, ED_samp_size=ED_samp_size, bLHS=bLHS, use_laplace=use_laplace, ofv_calc_type=ofv_calc_type, fim.calc.type=fim.calc.type, ofv_fun = ofv_fun_user, ...)[["fim"]] time_value <- blockfinal(fn=fn,fmf=FIM, dmf=output$ofv, groupsize=poped.db$design$groupsize, ni=poped.db$design$ni, xt=poped.db$design$xt, x=poped.db$design$x, a=poped.db$design$a, model_switch=poped.db$design$model_switch, poped.db$parameters$param.pt.val$bpop, poped.db$parameters$param.pt.val$d, poped.db$parameters$docc, poped.db$parameters$param.pt.val$sigma, poped.db, fmf_init=fmf_init, dmf_init=dmf_init, ...) results <- list( ofv= output$ofv, FIM=FIM, initial=list(ofv=dmf_init, FIM=fmf_init, poped.db=poped.db_init), run_time=time_value, poped.db = poped.db ) class(results) <- "poped_optim" return(invisible(results)) }
if (suppressWarnings( require("testthat") && require("ggeffects") && require("lme4") && require("sjlabelled") )) { data(efc) efc$e15relat <- as_label(efc$e15relat) efc$e42dep <- as_label(efc$e42dep) efc$c172code <- as.factor(efc$c172code) m <- lmer(neg_c_7 ~ e42dep + c172code + (1 | e15relat), data = efc) test_that("ggpredict, contrasts-1", { options(contrasts = rep("contr.sum", 2)) pr <- ggpredict(m, c("c172code", "e42dep")) expect_false(anyNA(pr$std.error)) }) test_that("ggpredict, contrasts-2", { options(contrasts = rep("contr.sum", 2)) pr <- ggpredict(m, "c172code") expect_false(anyNA(pr$std.error)) }) test_that("ggpredict, contrasts-3", { options(contrasts = rep("contr.sum", 2)) pr <- ggpredict(m, "e42dep") expect_false(anyNA(pr$std.error)) }) test_that("ggpredict, contrasts-4", { options(contrasts = rep("contr.treatment", 2)) pr <- ggpredict(m, c("c172code", "e42dep")) expect_false(anyNA(pr$std.error)) }) test_that("ggpredict, contrasts-5", { options(contrasts = rep("contr.treatment", 2)) pr <- ggpredict(m, "c172code") expect_false(anyNA(pr$std.error)) }) test_that("ggpredict, contrasts-6", { options(contrasts = rep("contr.treatment", 2)) pr <- ggpredict(m, "e42dep") expect_false(anyNA(pr$std.error)) }) }
plot_nma <- function(s.id = "study", t.id = "treatment", data, title = "", adjust.figsizex = 1.1, adjust.figsizey = 1.1){ alphabetic = TRUE weight.edge = TRUE adjust.thick = 5 weight.node = TRUE adjust.node.size = 10 node.col = "orange" edge.col = "black" text.cex = 1 if(missing(s.id) | missing(t.id)){ stop("both study id and treatment id must be specified.") } if(!missing(data)){ s.id <- eval(substitute(s.id), data, parent.frame()) t.id <- eval(substitute(t.id), data, parent.frame()) } unique.sid <- unique(s.id) nstudy <- length(unique.sid) sid.ori <- s.id for(s in 1:nstudy){ s.id[sid.ori == unique.sid[s]] <- s } unique.tid <- sort(unique(t.id)) ntrt <- length(unique.tid) if(ntrt <= 2) stop("there are less than 3 treatments, no need for network plot.") trtname <- unique.tid trtname.order <- 1:ntrt if(length(trtname) != ntrt){ stop("the length of trtname do not match the data.") } tid.ori <- t.id for(t in 1:ntrt){ t.id[tid.ori == unique.tid[t]] <- t } polar <- pi/2 - 2*pi/ntrt*(0:(ntrt - 1)) x <- cos(polar) y <- sin(polar) graphics::plot(x, y, axes = FALSE, xlab="", ylab="", cex = 0.1, xlim = c(-adjust.figsizex, adjust.figsizex), ylim = c(-adjust.figsizey, adjust.figsizey), main = title) wt <- matrix(0, ntrt, ntrt) for(t1 in 2:ntrt){ for(t2 in 1:(t1 - 1)){ study.t1 <- s.id[t.id == t1] study.t2 <- s.id[t.id == t2] study.t1.t2 <- intersect(study.t1, study.t2) wt[t1, t2] <- length(study.t1.t2) } } wt <- c(wt) if(weight.edge == TRUE){ wt.unique <- unique(wt[wt > 0]) wtmin <- min(wt.unique) wtmax <- max(wt.unique) if(wtmin < wtmax){ wt[wt > 0] <- round(1 + adjust.thick*(wt[wt > 0] - wtmin)/(wtmax - wtmin)) }else{ wt[wt > 0] <- 2 } }else{ wt[wt > 0] <- 2 } wt <- matrix(wt, ntrt, ntrt) for(t1 in 2:ntrt){ for(t2 in 1:(t1 - 1)){ if(t1 != t2 & wt[t1, t2] > 0){ graphics::lines(x = x[c(t1, t2)], y = y[c(t1, t2)], lwd = wt[t1, t2], col = edge.col) } } } if(weight.node){ wt <- matrix(0, ntrt, ntrt) for(t1 in 2:ntrt){ for(t2 in 1:(t1 - 1)){ study.t1 <- s.id[t.id == t1] study.t2 <- s.id[t.id == t2] study.t1.t2 <- intersect(study.t1, study.t2) wt[t1, t2] <- length(study.t1.t2) } } wt <- wt + t(wt) wt <- colSums(wt) node.sizes <- 3 + (wt - min(wt))/(max(wt) - min(wt))*adjust.node.size graphics::points(x, y, pch = 20, cex = node.sizes, col = node.col) }else{ graphics::points(x, y, pch = 20, cex = 3, col = node.col) } sides <- numeric(ntrt) eps <- 10^(-4) for(t in 1:ntrt){ if((polar[t] <= pi/2 & polar[t] > pi/4) | (polar[t] < -5*pi/4 & polar[t] >= -3*pi/2)){ sides[t] <- 3 } if(polar[t] <= pi/4 & polar[t] >= -pi/4){ sides[t] <- 4 } if(polar[t] < -pi/4 & polar[t] > -3*pi/4){ sides[t] <- 1 } if(polar[t] <= -3*pi/4 & polar[t] >= -5*pi/4){ sides[t] <- 2 } } for(t in 1:ntrt){ if(weight.node){ graphics::text(x = x[t], y = y[t], labels = trtname[trtname.order[t]], cex = text.cex) }else{ graphics::text(x = x[t], y = y[t], labels = trtname[trtname.order[t]], pos = sides[t], cex = text.cex) } } }
check_horizontal <- function(original, horizontal, fig_name, skip_on_windows = FALSE) { sort <- function(x) x[order(names(x))] flipped <- function(fun) { function(x, ...) fun(flip_aes(x), ...) } set.seed(10) h <- ggplot_build(original) set.seed(10) v <- ggplot_build(horizontal) if (skip_on_windows) { skip_on_os("windows") } expect_doppelganger(fig_name, horizontal) } expect_doppelganger <- function(title, fig, path = NULL, ...) { testthat::skip_if_not_installed("vdiffr") vdiffr::expect_doppelganger(title, fig, path = path, ...) }
test_that("classif_glmnet", { requirePackagesOrSkip("glmnet", default.method = "load") parset.list = list( list(), list(alpha = 0.5), list(devmax = 0.8), list(s = 0.1) ) old.predicts.list = list() old.probs.list = list() for (i in seq_along(parset.list)) { parset = parset.list[[i]] s = parset[["s"]] if (is.null(s)) { s = 0.01 } parset[["s"]] = NULL x = binaryclass.train y = x[, binaryclass.class.col] x[, binaryclass.class.col] = NULL pars = list(x = as.matrix(x), y = y, family = "binomial") pars = c(pars, parset) glmnet::glmnet.control(factory = TRUE) ctrl.args = names(formals(glmnet::glmnet.control)) if (any(names(pars) %in% ctrl.args)) { on.exit(glmnet::glmnet.control(factory = TRUE)) do.call(glmnet::glmnet.control, pars[names(pars) %in% ctrl.args]) m = do.call(glmnet::glmnet, pars[!names(pars) %in% ctrl.args]) } else { m = do.call(glmnet::glmnet, pars) } newx = binaryclass.test newx[, binaryclass.class.col] = NULL p = factor(predict(m, as.matrix(newx), type = "class", s = s)[, 1]) p2 = predict(m, as.matrix(newx), type = "response", s = s)[, 1] old.predicts.list[[i]] = p old.probs.list[[i]] = 1 - p2 } testSimpleParsets("classif.glmnet", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.predicts.list, parset.list) testProbParsets("classif.glmnet", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.probs.list, parset.list) })
source("ESEUR_config.r") library("circular") plot_layout(2, 1, max_height=11.0) par(mar=MAR_default-c(2.7, 3.7, 0.5, 0.7)) pal_col=rainbow(3) plot_commits=function(df, repo_str, col_str) { hrs=as.numeric(round(df$local_time, units="hours")) / (60*60) week_hr=(shift_weekend+hrs) %% hrs_per_week HoW=circular((360/hrs_per_week)*week_hr, units="degrees", rotation="clock") rose.diag(HoW, bins=7*8, shrink=1.2, prop=5, col=col_str, border="grey", axes=FALSE, control.circle=circle.control(col="grey", lwd=0.5)) axis.circular(at=circular(day_angle, units="degrees", rotation="clock"), labels=c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")) text(0.8, 1, repo_str, cex=1.4) arrows.circular(mean(HoW), y=rho.circular(HoW), col=pal_col[2], lwd=3) return(HoW) } commits=read.csv(paste0(ESEUR_dir, "time-series/commits/scc_commit.tsv.xz"), sep="\t", as.is=TRUE) commits$sha1=NULL commits$local_time=as.POSIXct(commits$local_time, format="%Y-%m-%d %H:%M:%S") hrs_per_day=24 hrs_per_week=hrs_per_day*7 day_angle=seq(0, 359, 360/7) shift_weekend=3*hrs_per_day linux_circ=plot_commits(subset(commits, repository_id == 1), "Linux", pal_col[1]) BSD_circ=plot_commits(subset(commits, repository_id == 5), "OpenBSD", pal_col[3])
dualDiscrete <- function(length.sim, max.infected.A, max.infected.B, init.individuals.A, init.individuals.B, init.structure.A, init.structure.B, structure.matrix.A, structure.matrix.B, pExit.A, param.pExit.A, timeDep.pExit.A=FALSE, diff.pExit.A=FALSE, hostCount.pExit.A=FALSE, pMove.A, param.pMove.A, timeDep.pMove.A=FALSE, diff.pMove.A=FALSE, hostCount.pMove.A=FALSE, nContact.A, param.nContact.A, timeDep.nContact.A=FALSE, diff.nContact.A=FALSE, hostCount.nContact.A=FALSE, pTrans.A, param.pTrans.A, timeDep.pTrans.A=FALSE, diff.pTrans.A=FALSE, hostCount.pTrans.A=FALSE, prefix.host.A="H", pExit.B, param.pExit.B, timeDep.pExit.B=FALSE, diff.pExit.B=FALSE, hostCount.pExit.B=FALSE, pMove.B, param.pMove.B, timeDep.pMove.B=FALSE, diff.pMove.B=FALSE, hostCount.pMove.B=FALSE, nContact.B, param.nContact.B, timeDep.nContact.B=FALSE, diff.nContact.B=FALSE, hostCount.nContact.B=FALSE, pTrans.B, param.pTrans.B, timeDep.pTrans.B=FALSE, diff.pTrans.B=FALSE, hostCount.pTrans.B=FALSE, prefix.host.B="V", print.progress=TRUE, print.step=10){ CoreSanityChecks(length.sim, max.infected=(max.infected.A+max.infected.B), init.individuals=(init.individuals.A+init.individuals.B)) none.at.start.A = (init.individuals.A == 0) none.at.start.B = (init.individuals.B == 0) if(none.at.start.A) init.structure.A = "NA" if(none.at.start.B) init.structure.B = "NA" if((!is.function(pMove.A)) && (!is.function(pMove.B))) stop("At least one host must move.") nContactParsed.A <- parseFunction(nContact.A, param.nContact.A, as.character(quote(nContact.A)), diff=diff.nContact.A, timeDep = timeDep.nContact.A, hostCount=hostCount.nContact.A, stateNames=colnames(structure.matrix.A)) nContactParsed.B <- parseFunction(nContact.B, param.nContact.B, as.character(quote(nContact.B)), diff=diff.nContact.B, timeDep = timeDep.nContact.B, hostCount=hostCount.nContact.B, stateNames=colnames(structure.matrix.B)) pTransParsed.A <- parseFunction(pTrans.A, param.pTrans.A, as.character(quote(pTrans.A)), diff=diff.pTrans.A, timeDep = timeDep.pTrans.A, hostCount=hostCount.pTrans.A, stateNames=colnames(structure.matrix.A)) pTransParsed.B <- parseFunction(pTrans.B, param.pTrans.B, as.character(quote(pTrans.B)), diff=diff.pTrans.B, timeDep = timeDep.pTrans.B, hostCount=hostCount.pTrans.B, stateNames=colnames(structure.matrix.B)) pExitParsed.A <- parseFunction(pExit.A, param.pExit.A, as.character(quote(pExit.A)), diff=diff.pExit.A, timeDep = timeDep.pExit.A, hostCount=hostCount.pExit.A, stateNames=colnames(structure.matrix.A)) pExitParsed.B <- parseFunction(pExit.B, param.pExit.B, as.character(quote(pExit.B)), diff=diff.pExit.B, timeDep = timeDep.pExit.B, hostCount=hostCount.pExit.B, stateNames=colnames(structure.matrix.B)) MatrixSanityChecks(structure.matrix.A,init.structure.A, none.at.start.A) MatrixSanityChecks(structure.matrix.B,init.structure.B, none.at.start.B) if(is.function(pMove.A)) pMoveParsed.A <- parseFunction(pMove.A, param.pMove.A, as.character(quote(pMove.A)), diff=diff.pMove.A, timeDep = timeDep.pMove.A, hostCount=hostCount.pMove.A, stateNames=colnames(structure.matrix.A)) if(is.function(pMove.B)) pMoveParsed.B <- parseFunction(pMove.B, param.pMove.B, as.character(quote(pMove.B)), diff=diff.pMove.B, timeDep = timeDep.pMove.B, hostCount=hostCount.pMove.B, stateNames=colnames(structure.matrix.B)) ParamHost.A <- paramConstructor(param.pExit.A, param.pMove=param.pMove.A, param.nContact.A, param.pTrans.A, param.sdMove=NA) ParamHost.B <- paramConstructor(param.pExit.B, param.pMove=param.pMove.B, param.nContact.B, param.pTrans.B, param.sdMove=NA) countingHosts <- any(c(hostCount.pExit.A, hostCount.pMove.A, hostCount.nContact.A, hostCount.pTrans.A),c(hostCount.pExit.B, hostCount.pMove.B, hostCount.nContact.B, hostCount.pTrans.B)) message("Starting the simulation\nInitializing ...", appendLF = FALSE) res <- nosoiSimConstructor(total.time = 1, type = "dual", pop.A = nosoiSimOneConstructor( N.infected = init.individuals.A, table.hosts = iniTable(init.individuals.A, init.structure.A, prefix.host.A, ParamHost.A, current.count.A = init.individuals.A, current.count.B = init.individuals.B), table.state = iniTableState(init.individuals.A, init.structure.A, prefix.host.A), prefix.host = prefix.host.A, popStructure = "discrete"), pop.B = nosoiSimOneConstructor( N.infected = init.individuals.B, table.hosts = iniTable(init.individuals.B, init.structure.B, prefix.host.B, ParamHost.B, current.count.A = init.individuals.A, current.count.B = init.individuals.B), table.state = iniTableState(init.individuals.B, init.structure.B, prefix.host.B), prefix.host = prefix.host.B, popStructure = "discrete")) message(" running ...") for (pres.time in 1:length.sim) { exiting.full.A <- getExitingMoving(res$host.info.A, pres.time, pExitParsed.A) exiting.full.B <- getExitingMoving(res$host.info.B, pres.time, pExitParsed.B) res$host.info.A$table.hosts[exiting.full.A, `:=` (out.time = pres.time, active = FALSE)] res$host.info.B$table.hosts[exiting.full.B, `:=` (out.time = pres.time, active = FALSE)] res$host.info.A <- updateTableState(res$host.info.A, exiting.full.A, pres.time) res$host.info.B <- updateTableState(res$host.info.B, exiting.full.B, pres.time) if (!any(c(res$host.info.A$table.hosts[["active"]], res$host.info.B$table.hosts[["active"]]))) {break} if(countingHosts) updateHostCount(res$host.info.A, res.B=res$host.info.B, type="discrete") if(is.function(pMove.A)) moving.full.A <- getExitingMoving(res$host.info.A, pres.time, pMoveParsed.A) if(is.function(pMove.B)) moving.full.B <- getExitingMoving(res$host.info.B, pres.time, pMoveParsed.B) if(is.function(pMove.A)) res$host.info.A <- makeMoves(res$host.info.A, pres.time, moving.full.A, structure.matrix = structure.matrix.A) if(is.function(pMove.B)) res$host.info.B <- makeMoves(res$host.info.B, pres.time, moving.full.B, structure.matrix = structure.matrix.B) if(countingHosts) updateHostCount(res$host.info.A, res.B=res$host.info.B, type="discrete") df.meetTransmit.A <- meetTransmit(res$host.info.A, pres.time, positions = c("current.in", "host.count.A", "host.count.B"), nContactParsed.A, pTransParsed.A) res$host.info.B <- writeInfected(df.meetTransmit.A, res$host.info.B, pres.time, ParamHost.B) df.meetTransmit.B <- meetTransmit(res$host.info.B, pres.time, positions = c("current.in", "host.count.A", "host.count.B"), nContactParsed.B, pTransParsed.B) res$host.info.A <- writeInfected(df.meetTransmit.B, res$host.info.A, pres.time, ParamHost.A) if(countingHosts) updateHostCount(res$host.info.A, res.B = res$host.info.B, type = "discrete") if (print.progress == TRUE) progressMessage(Host.count.A = res$host.info.A$N.infected, Host.count.B = res$host.info.B$N.infected, pres.time = pres.time, print.step = print.step, length.sim = length.sim, max.infected.A = max.infected.A, max.infected.B = max.infected.B, type = "dual") if (res$host.info.A$N.infected > max.infected.A || res$host.info.B$N.infected > max.infected.B) {break} } endMessage(Host.count.A=res$host.info.A$N.infected, Host.count.B=res$host.info.B$N.infected, pres.time, type="dual") res$total.time <- pres.time return(res) }
as.tabular <- function(x, like = NULL) { UseMethod("as.tabular") } as.tabular.default <- function(x, like = NULL) { dim <- dim(x) if (length(dim) != 2) stop("Cannot convert to tabular") if (is.null(like)) { rows <- factor(levels=rownames(x, do.NULL = FALSE)) cols <- factor(levels=colnames(x, do.NULL = FALSE)) names <- names(dimnames(x)) if (!length(names)) names <- c("", "") df <- data.frame(A=rows, B=cols) formula <- Factor(A, names[1]) ~ Factor(B, names[2]) if (names[1] == "") formula[[2]] <- call("*", quote(Heading()), formula[[2]]) if (names[2] == "") formula[[3]] <- call("*", quote(Heading()), formula[[3]]) like <- tabular(formula, data=df) } else { if (!inherits(like, "tabular")) stop("'like' must be a 'tabular' object") if (any(dim != dim(like))) stop("Dimension of 'x' must match dimension of 'like'") } mode(x) <- "list" attributes(x) <- attributes(like) x } as.tabular.data.frame <- function(x, like = NULL) { dimnames <- dimnames(x) res <- matrix(1, nrow(x), ncol(x)) mode(res) <- "list" for (j in seq_len(ncol(x))) { col <- x[,j] if (is.factor(col)) col <- as.character(col) mode(col) <- "list" res[,j] <- col } dimnames(res) <- dimnames as.tabular.default(res, like = like) }
test_that("construction", { expect_silent(Logicals$new()) l <- Logicals$new() expect_equal(l$elements, list(TRUE, FALSE)) expect_equal(l$min, NaN) expect_equal(l$max, NaN) expect_equal(l$lower, TRUE) expect_equal(l$upper, FALSE) })
ISOpureS2.model_core.compute_loglikelihood <- function(tumordata, model) { loglikelihood <- 0; D <- dim(tumordata)[2]; G <- dim(model$log_BBtranspose)[2]; loglikelihood <- loglikelihood + D*(lgamma(sum(model$vv)) - sum(lgamma(model$vv))) + sum((model$vv-1) %*% t(ISOpure.util.matlab_log(model$theta))); kappaomegaPP <- model$omega %*% model$PPtranspose * ISOpure.util.repmat(t(model$kappa), 1, G); for (dd in 1:D) { log_all_rates <- rbind(model$log_BBtranspose, model$log_cc[dd,,drop=FALSE]); log_P_t_given_theta <- ISOpure.util.logsum(t(ISOpure.util.repmat(ISOpure.util.matlab_log(model$theta[dd,,drop=FALSE]), G, 1)) + log_all_rates, 1); loglikelihood <- loglikelihood + (log_P_t_given_theta %*% tumordata[,dd]); loglikelihood <- loglikelihood + lgamma(sum(kappaomegaPP[dd,])) - sum(lgamma(kappaomegaPP[dd,])) + ((kappaomegaPP[dd,,drop=FALSE]-1) %*% t(model$log_cc[dd,,drop=FALSE])); } return(loglikelihood); }
predict.mKrig <- function(object, xnew = NULL, ynew = NULL, grid.list=NULL, derivative = 0, Z = NULL, drop.Z = FALSE, just.fixed = FALSE, collapseFixedEffect = object$collapseFixedEffect, ...) { cov.args <- list(...) if( !is.null(grid.list)){ xnew<- make.surface.grid(grid.list) } if (is.null(xnew)) { xnew <- object$x } if (is.null(Z) & (length(object$ind.drift) >0 )) { Z <- object$Tmatrix[, !object$ind.drift] } if (!is.null(ynew)) { coef.hold <- mKrig.coef(object, ynew, collapseFixedEffect=collapseFixedEffect) c.coef <- coef.hold$c.coef beta <- coef.hold$beta } else { c.coef <- object$c.coef beta <- object$beta } if( object$nt>0){ if (derivative == 0) { if (drop.Z | object$nZ == 0) { temp1 <- fields.mkpoly(xnew, m = object$m) %*% beta[object$ind.drift, ] } else { if( nrow( xnew) != nrow(as.matrix(Z)) ){ stop(paste("number of rows of covariate Z", nrow(as.matrix(Z)), " is not the same as the number of locations", nrow( xnew) ) ) } temp0 <- cbind(fields.mkpoly(xnew, m = object$m),as.matrix(Z)) temp1 <- temp0 %*% beta } } else { if (!drop.Z & object$nZ > 0) { stop("derivative not supported with Z covariate included") } temp1 <- fields.derivative.poly(xnew, m = object$m, beta[object$ind.drift, ]) } if (just.fixed) { return(temp1) } } if (derivative == 0) { temp2 <- do.call(object$cov.function.name, c(object$args, list(x1 = xnew, x2 = object$knots, C = c.coef), cov.args)) } else { temp2 <- do.call(object$cov.function.name, c(object$args, list(x1 = xnew, x2 = object$knots, C = c.coef, derivative = derivative), cov.args)) } if( object$nt>0){ return((temp1 + temp2)) } else{ return( temp2) } }
pdot.dsr.integrate.logistic <- function(right, width, beta, x, integral.numeric, BT, models, GAM=FALSE, rem=FALSE, point=FALSE){ if(length(right)>1){ lower <- right[1] right <- right[2] integral.numeric <- TRUE }else{ lower <- 0 } if(is.null(x$observer)){ stop("data must have a column named \"observer\"") } if(integral.numeric | point){ if(GAM|length(right)>1){ is.constant <- FALSE }else{ is.constant <- is.logistic.constant(x[x$observer==1,], models$g0model,width) } if(is.constant){ int1 <- rep(integratelogistic(x=x[x$observer==1,][1,], models, beta, lower=lower, right, point), nrow(x[x$observer==1,])) }else{ int1 <- rep(NA,nrow(x[x$observer==1,])) for(i in 1:nrow(x[x$observer==1,])){ int1[i] <- integratelogistic(x=(x[x$observer==1,])[i,], models, beta, lower=lower,right,point) } } if(!BT){ if(is.logistic.constant(x[x$observer==2,],models$g0model,width)){ int2 <- rep(integratelogistic(x=x[x$observer==2,][1,], models, beta, lower=lower, right, point), nrow(x[x$observer==2,])) }else{ int2 <- rep(NA,nrow(x[x$observer==2,])) for(i in 1:nrow(x[x$observer==2,])){ int2[i] <- integratelogistic(x=x[x$observer==2,][i,], models, beta, lower=lower, right, point) } } }else{ int2 <- NULL } }else{ int1 <- integratelogistic.analytic(x[x$observer==1,], models=models, beta=beta, width=right) if(!BT){ int2 <- integratelogistic.analytic(x[x$observer==2,], models=models, beta=beta, width=right) }else{ int2 <- NULL } } if(!BT){ if(is.logistic.constant(x[x$observer==1,],models$g0model,width) & is.logistic.constant(x[x$observer==2,],models$g0model,width)){ int3 <- rep(integratelogisticdup(x1=x[x$observer==1,][1,], x2=x[x$observer==2,][1,],models,beta, lower=lower,right, point), nrow(x[x$observer==2,])) }else{ int3 <- rep(NA, nrow(x[x$observer==1,])) for(i in 1:nrow(x[x$observer==1,])){ int3[i] <- integratelogisticdup(x1=(x[x$observer==1,])[i,], x2=(x[x$observer==2,])[i,], models, beta, lower=lower, right, point) } } pdot <- int1 + int2 - int3 }else{ int3 <- NULL pdot <- int1 } if(!point){ div <- width }else{ div <- width^2 } return(list(pdot = pdot/div, int1 = int1/div, int2 = int2/div, int3 = int3/div)) }
context("babel-export") test_that("export writes files", { x <- bot %>% efourier(3) fn <- "plop.txt" expect_message(export(x, file=fn)) expect_true(fn %in% list.files()) shut_up <- file.remove("plop.txt") x %<>% PCA fn <- "plop.txt" expect_message(export(x, file=fn)) expect_true(fn %in% list.files()) shut_up <- file.remove("plop.txt") x <- shapes[4] fn <- "plop.txt" expect_message(export(x, file=fn)) expect_true(fn %in% list.files()) shut_up <- file.remove("plop.txt") })
powDT <- function(r,k,mu,mu0,n,n0,contrast,sigma=NA,df=Inf,alpha=0.05,mcs=1e+05,testcall){ theta <- mu-mu0 if(contrast=="props" & is.na(sigma)){ pooled.mu <- (mu*n*k+mu0*n0)/(n*k+n0) sigma <- sqrt(pooled.mu*(1-pooled.mu)) } corr <- n/(n0+n) delta <- theta/(sigma*sqrt(1/n+1/n0)) if(testcall=="SD"){ cvSet <- cvSDDT(k=k, alpha=alpha, alternative="U", df=df, corr=corr) } if(testcall=="SU"){ cvSet <- cvSUDT(k=k, alpha=alpha, alternative="U", df=df, corr=corr) } z0 <- rnorm(mcs) if(df == Inf){u <- 1}else{u <- sqrt(rchisq(mcs,df=df)/df)} dvSet <- sapply(cvSet,function(x){(x*u+sqrt(corr)*z0)/sqrt(1-corr)}) list.J.Fun <- list(J2.fun,J3.fun,J4.fun,J5.fun,J6.fun,J7.fun,J8.fun,J9.fun,J10.fun,J11.fun,J12.fun,J13.fun,J14.fun,J15.fun,J16.fun) if(testcall=="SU"){ pow <- mean((1-pnorm(dvSet[,1],mean=delta/sqrt(1-corr)))^k) if(r<k){ s <- 1 p.rej <- (1-pnorm(dvSet[,s+1],mean=delta/sqrt(1-corr)))^(k-s) Psi.d1 <- pnorm(dvSet[,s],mean=delta/sqrt(1-corr)) J1 <- Psi.d1 list.J <- c(list(1),list(J1)) list.Psi <- list(Psi.d1) pow <- pow+choose(k,s)*mean(p.rej*J1) if(r<(k-1)){ for(s in 2:(k-r)){ p.rej <- (1-pnorm(dvSet[,s+1],mean=delta/sqrt(1-corr)))^(k-s) Psi.ds <- pnorm(dvSet[,s],mean=delta/sqrt(1-corr)) Js <- list.J.Fun[[s-1]](Psi.ds,list.J,list.Psi) list.J <- c(list.J,list(Js)) list.Psi <- c(list.Psi,list(Psi.ds)) pow <- pow+choose(k,s)*mean(p.rej*Js) } } } } if(testcall=="SD"){ powSet <- NULL Psi.d1 <- 1-pnorm(dvSet[,k],mean=delta/sqrt(1-corr)) J1 <- Psi.d1 list.J <- c(list(1),list(J1)) list.Psi <- list(Psi.d1) p.acc <- pnorm(dvSet[,k-1],mean=delta/sqrt(1-corr))^(k-1) powSet <- c(powSet,choose(k,k-1)*mean(p.acc*J1)) if(k>2){ for(s in (k-2):0){ if(s==0){p.acc <- 1}else{p.acc <- pnorm(dvSet[,s],mean=delta/sqrt(1-corr))^s} Psi.ds <- 1-pnorm(dvSet[,s+1],mean=delta/sqrt(1-corr)) Js <- list.J.Fun[[k-s-1]](Psi.ds,list.J,list.Psi) powSet <- c(powSet,choose(k,s)*mean(p.acc*Js)) list.J <- c(list.J,list(Js)) list.Psi <- c(list.Psi,list(Psi.ds)) } } pow <- sum(powSet[r:k]) } pow }
library(gridGraphics) attach(beaver1) axis.POSIXct1 <- function() { time <- strptime(paste(1990, day, time %/% 100, time %% 100), "%Y %j %H %M") plot(time, temp, type = "l") } axis.POSIXct2 <- function() { time <- strptime(paste(1990, day, time %/% 100, time %% 100), "%Y %j %H %M") plot(time, temp, type = "l", xaxt = "n") r <- as.POSIXct(round(range(time), "hours")) axis.POSIXct(1, at = seq(r[1], r[2], by = "hour"), format = "%H") } axis.POSIXct3 <- function() { plot(.leap.seconds, seq_along(.leap.seconds), type = "n", yaxt = "n", xlab = "leap seconds", ylab = "", bty = "n") rug(.leap.seconds) } axis.POSIXct4 <- function() { lps <- as.Date(.leap.seconds) plot(lps, seq_along(.leap.seconds), type = "n", yaxt = "n", xlab = "leap seconds", ylab = "", bty = "n") rug(lps) } axis.POSIXct5 <- function() { set.seed(1) random.dates <- as.Date("2001/1/1") + 70*sort(stats::runif(100)) plot(random.dates, 1:100) } axis.POSIXct6 <- function() { set.seed(1) random.dates <- as.Date("2001/1/1") + 70*sort(stats::runif(100)) plot(random.dates, 1:100, xaxt = "n") axis.Date(1, at = seq(as.Date("2001/1/1"), max(random.dates)+6, "weeks")) axis.Date(1, at = seq(as.Date("2001/1/1"), max(random.dates)+6, "days"), labels = FALSE, tcl = -0.2) } plotdiff(expression(axis.POSIXct1()), "axis.POSIXct-1") plotdiff(expression(axis.POSIXct2()), "axis.POSIXct-2", width=8, height=8) plotdiff(expression(axis.POSIXct3()), "axis.POSIXct-3") plotdiff(expression(axis.POSIXct4()), "axis.POSIXct-4") plotdiff(expression(axis.POSIXct5()), "axis.POSIXct-5") plotdiff(expression(axis.POSIXct6()), "axis.POSIXct-6", width=9, height=9) detach(beaver1) plotdiffResult()
context("Uploading multiple files") vcr::vcr_configure( dir = cassette_dir("uploading-multiple-files") ) setup({ multidir <<- fs::dir_copy( file.path(rprojroot::find_testthat_root_file(), "test-files", "uploads"), ".osfr-tests" ) if (has_pat()) { vcr::use_cassette("create-p1", { p1 <<- osf_create_project(title = "osfr-multifile-upload-test") }) } }) teardown({ fs::dir_delete(multidir) if (has_pat()) { vcr::use_cassette("delete-p1", { osf_rm(p1, recurse = TRUE, check = FALSE) }) } }) test_that("multiple files can be uploaded", { skip_if_no_pat() infiles <- fs::dir_ls(multidir, type = "file") vcr::use_cassette("upload-infiles", { out <- osf_upload(p1, infiles) }) expect_s3_class(out, "osf_tbl_file") expect_equal(out$name, basename(infiles)) }) test_that("a directory can be uploaded", { skip_if_no_pat() vcr::use_cassette("create-and-populate-c1", { c1 <- osf_create_component(p1, "dir-upload") out <- osf_upload(c1, multidir) }) expect_s3_class(out, "osf_tbl_file") expect_match(out$name, basename(multidir)) vcr::use_cassette("list-c1-files", c1_files <- osf_ls_files(out) ) expect_true( all(c1_files$name %in% basename(fs::dir_ls(multidir))) ) }) test_that("a subdirectory can be uploaded", { skip_if_no_pat() indir <- file.path(multidir, "subdir1", "subdir1_1") vcr::use_cassette("create-and-populate-c2", { c2 <- osf_create_component(p1, "subdir-upload") out <- osf_upload(c2, indir, verbose = TRUE) }) expect_s3_class(out, "osf_tbl_file") expect_match(out$name, basename(indir)) vcr::use_cassette("list-c2-subdirs", subdirs <- osf_ls_files(c2, type = "folder") ) expect_equal( subdirs$name, basename(indir) ) vcr::use_cassette("list-c2-subdir-files", subdir_files <- osf_ls_files(out) ) expect_equal( subdir_files$name, basename(fs::dir_ls(indir)) ) }) test_that("recurse argument respects specified levels", { skip_if_no_pat() vcr::use_cassette("create-and-populate-c3", { c3 <- osf_create_component(p1, "recurse=1") out <- osf_upload(c3, path = multidir, recurse = 1) }) vcr::use_cassette("list-c3-subdir1", sd1_files <- osf_ls_files(out, path = "subdir1") ) expect_setequal( sort(sd1_files$name), dir(file.path(multidir, "subdir1")) ) vcr::use_cassette("list-c3-subdir2", sd2_files <- osf_ls_files(out, path = "subdir2") ) expect_setequal( sd2_files$name, dir(file.path(multidir, "subdir2")) ) vcr::use_cassette("list-c3-subdir1_1", sd1_1_files <- osf_ls_files(out, path = "subdir1/subdir1_1") ) expect_equal(nrow(sd1_1_files), 0) }) test_that("recurse=TRUE uploads the entire OSF directory structure", { skip_if_no_pat() vcr::use_cassette("create-and-populate-c4", { c4 <- osf_create_component(p1, "recurse=TRUE") out <- osf_upload(c4, path = multidir, recurse = TRUE) }) vcr::use_cassette("list-c4-subdir1_1-files", sd1_1_files <- osf_ls_files(out, path = "subdir1/subdir1_1") ) expect_equal( sd1_1_files$name, dir(file.path(multidir, "subdir1/subdir1_1")) ) }) test_that("files in parent directories can be uploaded", { cwd <- getwd() on.exit(setwd(cwd)) setwd(fs::path(multidir, "subdir1/subdir1_1")) skip_if_no_pat() vcr::use_cassette("create-c5", { c5 <- osf_create_component(p1, "parent-directories") }) vcr::use_cassette("c5-upload-f1", { upf1 <- osf_upload(c5, path = "../d.txt") }) vcr::use_cassette("c5-upload-f2", { upf2 <- osf_upload(c5, path = "../../a.txt") }) vcr::use_cassette("c5-upload-updir", { updir <- osf_upload(c5, path = "../../subdir2") }) vcr::use_cassette("list-c5-files", c5_files <- osf_ls_files(c5) ) expect_equal( c5_files$name, c("d.txt", "a.txt", "subdir2") ) }) test_that("conflicting files are skipped or overwritten", { skip_if_no_pat() infiles <- fs::dir_ls(multidir, type = "file") vcr::use_cassette("create-and-populate-c6", { c6 <- osf_create_component(p1, "conflicts") out1 <- osf_upload(c6, path = infiles[1]) }) writeLines("foo", infiles[1]) vcr::use_cassette("c6-conflict-skip", { out2 <- osf_upload(c6, path = infiles[1], conflicts = "skip") }) versions <- get_meta(out2, "attributes", "current_version") expect_true(all(versions) == 1) vcr::use_cassette("c6-conflict-overwrite", { out3 <- osf_upload(c6, path = infiles[1], conflicts = "overwrite") }) expect_equal(get_meta(out3, "attributes", "current_version"), 2) })
arh_rkhs <- function(fdata) { n <- nrow(fdata$fdata) lambda.me <- colMeans(fdata$lambda) lambda.cent <- sweep(fdata$lambda, 2, lambda.me) Covariance = t(lambda.cent) %*% (lambda.cent) / n Cross.Cov = t(lambda.cent[2:n,]) %*% (lambda.cent[1:(n-1),]) / (n - 1) rho = Cross.Cov %*% invgen(Covariance) return(list(fdata = fdata, lambda_cent = lambda.cent, lambda_me = lambda.me, rho = rho)) }
testFunc4 <- function(x, y) x + y testFunc5 <- function(x, y) x + y
np.gmeta <- function(Thetahat, se, alpha=c(0.025,0.975), n, m, band_pwr = 0.5, resample=200, B=40, len=10) { out<-.Fortran("confdistint",K=as.integer(length(Thetahat)), Thetahat = as.double(Thetahat),se = as.double(se), n=as.double(n),resample=as.integer(resample),B=as.integer(B),len=as.integer(len), m=as.integer(m),band_pwr=as.double(band_pwr), shrink=as.double(0),smoothlist=as.double(rep(0,len)), eligids=as.integer(rep(0,len^2)),distvs=as.double(rep(0,len^2)), finalxi1=as.double(rep(0,resample)),finalxi2=as.double(rep(0,resample)),finalxi3=as.double(rep(0,resample)) ) percentiles = matrix(0,3,length(alpha)) colnames(percentiles) = as.character(alpha); rownames(percentiles) = c("min.unif","max.smooth","mean.smooth") percentiles[1,] = quantile(out$finalxi1,alpha) percentiles[2,] = quantile(out$finalxi2,alpha) percentiles[3,] = quantile(out$finalxi3,alpha) aa=out$eligids;aa=aa[aa!=0] return( list(percentiles = percentiles, shrink = out$shrink, smoothlist= out$smoothlist, distance = matrix(out$distvs,10,10), elig.ind = arrayInd(aa,c(len,len))) ) }
quat2RM_svg <- function(q){ RM <- cbind( c(1 - 2*q[2]^2 - 2*q[3]^2, 2*q[1]*q[2] - 2*q[3]*q[4], 2*q[1]*q[3] + 2*q[2]*q[4]), c(2*q[1]*q[2] + 2*q[3]*q[4], 1 - 2*q[1]^2 - 2*q[3]^2, 2*q[2]*q[3] - 2*q[1]*q[4]), c(2*q[1]*q[3] - 2*q[2]*q[4], 2*q[2]*q[3] + 2*q[1]*q[4], 1 - 2*q[1]^2 - 2*q[2]^2) ) RM }
t <- read.csv("tableparamVSfunction.csv", sep = ",", header = TRUE, check.names = FALSE) row.names(t) <- t[, 1] t <- t[, -1] t[is.na(t)] <- 0 table.value(t, plegend.drawKey = FALSE, ppoints.cex = 0.2, symbol = "circle", axis.text = list(cex = 0.8), pgrid.draw = TRUE, ptable.y = list(srt = 45, pos = "left"), ptable.margin = list(bottom = 2, left = 15, top = 15, right = 2))
source("incl/start.R") if (require(plyr, character.only = TRUE)) { message("*** dplyr w / doFuture + parallel ...") strategies <- future:::supportedStrategies() strategies <- setdiff(strategies, "multiprocess") res0 <- NULL for (strategy in strategies) { message(sprintf("- plan('%s') ...", strategy)) plan(strategy) mu <- 1.0 sigma <- 2.0 res <- foreach(i = 1:3, .packages = "stats") %dopar% { dnorm(i, mean = mu, sd = sigma) } print(res) if (is.null(res0)) { res0 <- res } else { stopifnot(all.equal(res, res0)) } print(sessionInfo()) x <- list(a = 1:10, beta = exp(-3:3), logic = c(TRUE, FALSE, FALSE, TRUE)) y0 <- llply(x, quantile, probs = (1:3) / 4, .parallel = FALSE) print(y0) y1 <- llply(x, quantile, probs = (1:3) / 4, .parallel = TRUE) print(y1) stopifnot(all.equal(y1, y0)) message(sprintf("- plan('%s') ... DONE", strategy)) } message("*** dplyr w / doFuture + parallel ... DONE") } source("incl/end.R")
context("paths") test_that("test cleanup_hashpath", { expect_equal(cleanup_hashpath(" expect_equal(cleanup_hashpath(" expect_equal(cleanup_hashpath(" expect_equal(cleanup_hashpath(" }) test_that("test extract_link_name", { expect_equal(extract_link_name(" expect_equal(extract_link_name("abc"), "abc") }) test_that("test route_link", { expect_equal(route_link("abc"), "./ expect_equal(route_link(" }) test_that("test parse_url_path", { p <- parse_url_path("?a=1&b=foo expect_error(parse_url_path()) expect_error(parse_url_path("www.foo.bar")) expect_equal(p$path, "") expect_equal(p$query$b, "foo") p <- parse_url_path("www.foo.bar/?a=1&b[1]=foo&b[2]=bar") expect_true(length(p$query$b) == 2) expect_equal(p$query$b[[2]], "bar") p <- parse_url_path("/ expect_equal(p$path, "foo") expect_equal(p$query$a, "1") expect_true(length(p$query$b) == 2) p <- parse_url_path("?a=1&b=foo") expect_equal(p$path, "") expect_equal(p$query$b, "foo") }) test_that("test valid_path", { expect_error(valid_path()) expect_true(valid_path(list(a="a", b="b"), "b")) expect_false(valid_path(list(a="a", c="b"), "b")) expect_false(valid_path(list(), "b")) }) test_that("test get_query_param parameters", { session <- list(userData = NULL) session$userData$shiny.router.page <- shiny::reactiveVal(list( path = "root", query = list(one = 1, two = 2), unparsed = "root" )) expect_error(shiny::isolate(get_query_param())) expect_equal(shiny::isolate(get_query_param("one", session)), 1) expect_failure( expect_equal(shiny::isolate(get_query_param("two", session)), 1) ) expect_equal(shiny::isolate(get_query_param(session = session)), list(one = 1, two = 2)) })
theme_ipsum_rc <- function( base_family="Roboto Condensed", base_size = 11.5, plot_title_family=base_family, plot_title_size = 18, plot_title_face="bold", plot_title_margin = 10, subtitle_family=if (.Platform$OS.type == "windows") "Roboto Condensed" else "Roboto Condensed Light", subtitle_size = 13, subtitle_face = "plain", subtitle_margin = 15, strip_text_family = base_family, strip_text_size = 12, strip_text_face = "plain", caption_family=if (.Platform$OS.type == "windows") "Roboto Condensed" else "Roboto Condensed Light", caption_size = 9, caption_face = "plain", caption_margin = 10, axis_text_size = base_size, axis_title_family = base_family, axis_title_size = 9, axis_title_face = "plain", axis_title_just = "rt", plot_margin = margin(30, 30, 30, 30), panel_spacing = grid::unit(2, "lines"), grid_col = " axis_col = " ret <- ggplot2::theme_minimal(base_family = base_family, base_size = base_size) ret <- ret + theme(legend.background = element_blank()) ret <- ret + theme(legend.key = element_blank()) ret <- ret + theme(plot.margin = plot_margin) ret <- ret + theme(panel.spacing = panel_spacing) if (inherits(grid, "character") | grid == TRUE) { ret <- ret + theme(panel.grid = element_line(color = grid_col, size = 0.2)) ret <- ret + theme(panel.grid.major = element_line(color = grid_col, size = 0.2)) ret <- ret + theme(panel.grid.minor = element_line(color = grid_col, size = 0.15)) if (inherits(grid, "character")) { if (regexpr("X", grid)[1] < 0) ret <- ret + theme(panel.grid.major.x = element_blank()) if (regexpr("Y", grid)[1] < 0) ret <- ret + theme(panel.grid.major.y = element_blank()) if (regexpr("x", grid)[1] < 0) ret <- ret + theme(panel.grid.minor.x = element_blank()) if (regexpr("y", grid)[1] < 0) ret <- ret + theme(panel.grid.minor.y = element_blank()) } } else { ret <- ret + theme(panel.grid = element_blank()) ret <- ret + theme(panel.grid.major = element_blank()) ret <- ret + theme(panel.grid.major.x = element_blank()) ret <- ret + theme(panel.grid.major.y = element_blank()) ret <- ret + theme(panel.grid.minor = element_blank()) ret <- ret + theme(panel.grid.minor.x = element_blank()) ret <- ret + theme(panel.grid.minor.y = element_blank()) } if (inherits(axis, "character") | axis == TRUE) { ret <- ret + theme(axis.line = element_line(color = axis_col, size = 0.15)) if (inherits(axis, "character")) { axis <- tolower(axis) if (regexpr("x", axis)[1] < 0) { ret <- ret + theme(axis.line.x = element_blank()) } else { ret <- ret + theme(axis.line.x = element_line(color = axis_col, size = 0.15)) } if (regexpr("y", axis)[1] < 0) { ret <- ret + theme(axis.line.y = element_blank()) } else { ret <- ret + theme(axis.line.y = element_line(color = axis_col, size = 0.15)) } } else { ret <- ret + theme(axis.line.x = element_line(color = axis_col, size = 0.15)) ret <- ret + theme(axis.line.y = element_line(color = axis_col, size = 0.15)) } } else { ret <- ret + theme(axis.line = element_blank()) } if (!ticks) { ret <- ret + theme(axis.ticks = element_blank()) ret <- ret + theme(axis.ticks.x = element_blank()) ret <- ret + theme(axis.ticks.y = element_blank()) } else { ret <- ret + theme(axis.ticks = element_line(size = 0.15)) ret <- ret + theme(axis.ticks.x = element_line(size = 0.15)) ret <- ret + theme(axis.ticks.y = element_line(size = 0.15)) ret <- ret + theme(axis.ticks.length = grid::unit(5, "pt")) } xj <- switch(tolower(substr(axis_title_just, 1, 1)), b = 0, l = 0, m = 0.5, c = 0.5, r = 1, t = 1) yj <- switch(tolower(substr(axis_title_just, 2, 2)), b = 0, l = 0, m = 0.5, c = 0.5, r = 1, t = 1) ret <- ret + theme(axis.text = element_text(size = axis_text_size, margin = margin(t = 0, r = 0))) ret <- ret + theme(axis.text.x = element_text(size = axis_text_size, margin = margin(t = 0))) ret <- ret + theme(axis.text.y = element_text(size = axis_text_size, margin = margin(r = 0))) ret <- ret + theme(axis.title = element_text(size = axis_title_size, family = axis_title_family)) ret <- ret + theme(axis.title.x = element_text( hjust = xj, size = axis_title_size, family = axis_title_family, face = axis_title_face )) ret <- ret + theme(axis.title.y = element_text( hjust = yj, size = axis_title_size, family = axis_title_family, face = axis_title_face )) ret <- ret + theme(axis.title.y.right = element_text( hjust = yj, size = axis_title_size, angle = 90, family = axis_title_family, face = axis_title_face )) ret <- ret + theme(strip.text = element_text( hjust = 0, size = strip_text_size, face = strip_text_face, family = strip_text_family )) ret <- ret + theme(plot.title = element_text( hjust = 0, size = plot_title_size, margin = margin(b = plot_title_margin), family = plot_title_family, face = plot_title_face )) ret <- ret + theme(plot.subtitle = element_text( hjust = 0, size = subtitle_size, margin = margin(b = subtitle_margin), family = subtitle_family, face = subtitle_face )) ret <- ret + theme(plot.caption = element_text( hjust = 1, size = caption_size, margin = margin(t = caption_margin), family = caption_family, face = caption_face )) ret } import_roboto_condensed <- function() { rc_font_dir <- system.file("fonts", "roboto-condensed", package="hrbrthemes") } font_rc <- "Roboto Condensed" font_rc_light <- "Roboto Condensed Light"
GO4Organism <- function(organism, domain = "BP"){ species <- organism ont <- domain gonames <- c("Entrezgene ID", "GO ID", "Ont.", "Level" ) if(toupper(domain) != "BP" && toupper(domain) != "MF" && toupper(domain) != "CC"){ stop("The argument \"domain\" can only be \"BP\", \"MF\" or \"CC\".") } if(is.null(species)){ stop("The \"organism\" argument is missing with no default") } if(!is.null(species) && toupper(species) != "BP" && toupper(species) != "MF" && toupper(species) != "CC" && !(toupper(species) %in% SupportedOrganism)){ print(SupportedOrganismv2) stop("The \"organism\" argument should be given from the list above") } if(toupper(species) == "BP"){ return(BP) } else if(toupper(species) == "MF"){ return(MF) } else if(toupper(species) == "CC"){ return(GOTermCCOnLevel(names(as.list(go2h2)))) } else if(toupper(species) == "HOMO SAPIENS" || toupper(species) == "HUMAN"){ goids <- HumanAll }else if(toupper(species) == "RATTUS NORVEGICUS" || toupper(species) == "RAT"){ goids <- gontr::RatAll }else if(toupper(species) == "MUS MUSCULUS" || toupper(species) == "MOUSE"){ goids <- gontr::MouseAll }else if(toupper(species) == "DANIO RERIO" || toupper(species) == "ZEBRAFISH"){ goids <- ZebrafishAll }else if(toupper(species) == "CAENORHABDITIS ELEGANS" || toupper(species) == "WORM"){ goids <- EleganAll }else if(toupper(species) == "ARABIDOPSIS THALIANA" || toupper(species) == "CRESS"){ goids <- AthalianAll }else if(toupper(species) == "SACCHAROMYCES CEREVISIAE" || toupper(species) == "YEAST"){ goids <- YeastAll }else if(toupper(species) == "SCHIZOSACCHAROMYCES POMBE" || toupper(species) == "FISSION YEAST"){ goids <- PombeAll }else if(toupper(species) == "DROSOPHILA MELANOGASTER" || toupper(species) == "FRUIT FLY"){ goids <- DrosophilaAll }else if(toupper(species) == "ESCHERICHIA COLI" || toupper(species) == "E.COLI"){ goids <- EcoliAll[,c(1,2)] } J <- goids a <- which(J[,2] == '') if(length(a) != 0){ J <- J[-a,] } gene_ontology <- Ontology(J[,2]) J <- cbind(J , gene_ontology) a1 <- which(is.na(J[,3])) if(length(a1 )!= 0){ J <- J[-a1,] } if(length(J) != 0){ if(is.null(ont) || toupper(ont) == "BP"){ J <- J[-which(!J[,3] == 'BP'),] go_level <- lapply(J[,2], function(x) go2h[[x]][length(go2h[[x]])] - 1) h <- which(go_level == 'NULL') if(length(h) == 0){ go_level <- unlist(go_level) J <- cbind(J,go_level) }else{go_level[h] = 'NA' go_level <- unlist(go_level) J <- cbind(J, go_level) J <- J[-which(J[,4] == 'NA'),]} rownames(J) <- NULL colnames(J) <- gonames J <- unique(J[,c(2,4)]) return(J) }else if(toupper(ont) == "MF"){ J <- J[-which(!J[,3] == "MF"),] go_level <- lapply(J[,2], function(x) go2h1[[x]][length(go2h1[[x]])] - 1) h <- which(go_level == 'NULL') if(length(h) == 0){ go_level <- unlist(go_level) J <- cbind(J,go_level) }else{go_level[h] = 'NA' go_level <- unlist(go_level) J <- cbind(J,go_level) J <- J[-which(J[,4] == 'NA'),]} colnames(J) <- gonames J <- unique(J[,c(2,4)]) rownames(J) <- NULL return(J) }else if(toupper(ont) == "CC"){ J <- J[-which(!J[,3] == "CC"),] go_level <- lapply(J[,2], function(x) go2h2[[x]][length(go2h2[[x]])] - 1 ) h <- which(go_level == 'NULL') if(length(h) == 0){ go_level <- unlist(go_level) J <- cbind(J,go_level) }else{go_level[h] = 'NA' go_level <- unlist(go_level) J <- cbind(J,go_level) J <- J[-which(J[,4] == 'NA'),]} colnames(J) <- gonames J <- unique(J[,c(2,4)]) rownames(J) <- NULL return(J) } } }
evppi_legend_cols <- function(evppi_obj, col = NULL) { n_cols <- length(evppi_obj$parameters) + 1 if (is.null(col)) { cols <- colors() gr <- floor(seq(from = 261, to = 336, length.out = n_cols)) return(cols[gr]) } else { if (length(col) != n_cols) { message( "The vector 'col' must have the number of elements for an EVPI colour and each of the EVPPI parameters. Forced to black\n") return(rep("black", length(evppi_obj$parameters) + 1)) } } col } evppi_legend_text <- function(evppi_obj) { cmd <- if (nchar(evppi_obj$parameters[1]) <= 25) { paste0("EVPPI for ", evppi_obj$parameters) } else "EVPPI for the selected\nsubset of parameters" if (length(evppi_obj$index) > 1 && (("Strong & Oakley (univariate)" %in% evppi_obj$method) || ("Sadatsafavi et al" %in% evppi_obj$method))) { for (i in seq_along(evppi_obj$index)) { } cmd <- paste0("(", paste(1:length(evppi_obj$index)), ") EVPPI for ", evppi_obj$parameters) } c("EVPI", cmd) }
getfiledestinations <- function() { folders <- base::list.dirs(recursive=FALSE, full.names=FALSE) folders <- grep("^(\\.|225|output|calib_run|figure)",folders, invert=TRUE, value=TRUE) files <- NULL for(f in folders) files <- c(files,dir(path=f,pattern="^files$",recursive = TRUE, full.names=TRUE)) out <- NULL for(f in files) { tmp <- grep("^\\*",readLines(f, warn = FALSE),invert=TRUE,value=TRUE) add <- data.frame(file=tmp,destination=dirname(f),stringsAsFactors = FALSE) out <- rbind(out,add) } out <- as.data.frame(lapply(out,trimws),stringsAsFactors=FALSE) return(out[out[[1]]!="",]) }
get_cohort <- function(resource, limit = 20L, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { tbl_json <- get(resource_url = resource, limit = limit, verbose = verbose, warnings = warnings, progress_bar = progress_bar) tidy_tbls <- as_tidy_tables_cohorts(tbl_json) return(tidy_tbls) } get_cohort_by_cohort_symbol <- function(cohort_symbol, limit = 20L, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { resource <- '/rest/cohort' cohort_symbol <- purrr::map_chr(cohort_symbol, utils::URLencode, reserved = TRUE) resource_urls <- sprintf("%s/%s", resource, cohort_symbol) purrr::map( resource_urls, get_cohort, limit = limit, warnings = warnings, verbose = verbose, progress_bar = progress_bar ) %>% purrr::pmap(dplyr::bind_rows) } get_cohort_all <- function(limit = 20L, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { resource <- '/rest/cohort/all' get_cohort(resource = resource, limit = limit, verbose = verbose, warnings = warnings, progress_bar = progress_bar) } get_cohorts <- function( cohort_symbol = NULL, verbose = FALSE, warnings = TRUE, progress_bar = TRUE) { if(!(rlang::is_scalar_logical(verbose) && verbose %in% c(TRUE, FALSE))) stop("verbose must be either TRUE or FALSE") if(!(rlang::is_scalar_logical(warnings) && warnings %in% c(TRUE, FALSE))) stop("warnings must be either TRUE or FALSE") if (!rlang::is_null(cohort_symbol)) { get_cohort_by_cohort_symbol( cohort_symbol = cohort_symbol, verbose = verbose, warnings = warnings, progress_bar = progress_bar ) %>% coerce_to_s4_cohorts() %>% return() } else { return(coerce_to_s4_cohorts(get_cohort_all(verbose = verbose, warnings = warnings, progress_bar = progress_bar))) } }
row_f_var <- function(x, y, ratio=1, alternative="two.sided", conf.level=0.95) { force(x) force(y) if(is.vector(x)) x <- matrix(x, nrow=1) if(is.vector(y)) y <- matrix(y, nrow=1) if(is.data.frame(x) && all(sapply(x, is.numeric))) x <- data.matrix(x) if(is.data.frame(y) && all(sapply(y, is.numeric))) y <- data.matrix(y) assert_numeric_mat_or_vec(x) assert_numeric_mat_or_vec(y) if(nrow(y)==1 & nrow(x)>1) { y <- matrix(y, nrow=nrow(x), ncol=ncol(y), byrow=TRUE) } assert_equal_nrow(x, y) if(length(alternative)==1) alternative <- rep(alternative, length.out=nrow(x)) assert_character_vec_length(alternative, 1, nrow(x)) choices <- c("two.sided", "less", "greater") alternative <- choices[pmatch(alternative, choices, duplicates.ok=TRUE)] assert_all_in_set(alternative, choices) if(length(ratio)==1) ratio <- rep(ratio, length.out=nrow(x)) assert_numeric_vec_length(ratio, 1, nrow(x)) assert_all_in_open_interval(ratio, 0, Inf) if(length(conf.level)==1) conf.level <- rep(conf.level, length.out=nrow(x)) assert_numeric_vec_length(conf.level, 1, nrow(x)) assert_all_in_closed_interval(conf.level, 0, 1) hasinfx <- is.infinite(x) x[hasinfx] <- NA hasinfx <- rowSums(hasinfx) > 0 hasinfy <- is.infinite(y) y[hasinfy] <- NA hasinfy <- rowSums(hasinfy) > 0 nxs <- rep.int(ncol(x), nrow(x)) - matrixStats::rowCounts(is.na(x)) nys <- rep.int(ncol(y), nrow(y)) - matrixStats::rowCounts(is.na(y)) nxys <- nxs + nys dfx <- nxs - 1 dfy <- nys - 1 vxs <- rowVars(x, na.rm=TRUE) vys <- rowVars(y, na.rm=TRUE) estimate <- vxs/vys fres <- do_ftest(estimate, ratio, alternative, dfx, dfy, conf.level) w1 <- hasinfx showWarning(w1, 'had infinite "x" observations that were removed') w2 <- hasinfy showWarning(w2, 'had infinite "y" observations that were removed') w3 <- nxs <= 1 showWarning(w3, 'had less than 1 "x" observation') w4 <- nys <= 1 showWarning(w4, 'had less than 1 "y" observation') w5 <- vxs == 0 showWarning(w5, 'had zero variance in "x"') w6 <- vys == 0 showWarning(w6, 'had zero variance in "y"') fres[w3 | w4 | (w5 & w6),] <- NA rnames <- rownames(x) if(!is.null(rnames)) rnames <- make.unique(rnames) data.frame(obs.x=nxs, obs.y=nys, obs.tot=nxys, var.x=vxs, var.y=vys, var.ratio=estimate, df.num=dfx, df.denom=dfy, statistic=fres[,1], pvalue=fres[,2], conf.low=fres[,3], conf.high=fres[,4], ratio.null=ratio, alternative=alternative, conf.level=conf.level, row.names=rnames, stringsAsFactors=FALSE ) } col_f_var <- function(x, y, ratio=1, alternative="two.sided", conf.level=0.95) { row_f_var(t(x), t(y), ratio, alternative, conf.level) }
gl.pcoa.plot <- function(glPca, x, scale=FALSE, ellipse=FALSE, p=0.95, labels="pop", theme_plot=4, as.pop=NULL, hadjust=1.5, vadjust=1, xaxis=1, yaxis=2, plot.out=TRUE, verbose=NULL) { pkg <- "plotly" if (!(requireNamespace(pkg, quietly = TRUE))) { stop("Package ",pkg," needed for this function to work. Please install it.") } pkg <- "directlabels" if (!(requireNamespace(pkg, quietly = TRUE))) { stop("Package ",pkg," needed for this function to work. Please install it.") } pkg <- "ggrepel" if (!(requireNamespace(pkg, quietly = TRUE))) { stop("Package ",pkg," needed for this function to work. Please install it.") } pkg <- "ggthemes" if (!(requireNamespace(pkg, quietly = TRUE))) { stop("Package ",pkg," needed for this function to work. Please install it.") } else { funname <- match.call()[[1]] build <- "Jacob" if(class(x)=="genlight"){ if (is.null(verbose)){ if(!is.null(x@other$verbose)){ verbose <- x@other$verbose } else { verbose <- 2 } } } if(class(x)=="fd"){ x <- x$gl if (is.null(verbose)){ verbose <- 2 } } if(class(x)=="dist"){ if (is.null(verbose)){ verbose <- 2 } } if (verbose < 0 | verbose > 5){ cat(paste(" Warning: Parameter 'verbose' must be an integer between 0 [silent] and 5 [full report], set to 2\n")) verbose <- 2 } if (verbose >= 1){ if(verbose==5){ cat("Starting",funname,"[ Build =",build,"]\n") } else { cat("Starting",funname,"\n") } } if(class(glPca)!="glPca") { stop("Fatal Error: glPca object required as primary input (parameter glPca)!\n") } if(class(x) != "genlight" && class(x) != "dist" && class(x) != "fd") { stop("Fatal Error: genlight, fd or dist object required as secondary input (parameter x)!\n") } if (labels != "none" && labels != "ind" && labels != "pop" && labels != "interactive" && labels != "legend"){ cat(" Warning: Parameter 'labels' must be one of none|ind|pop|interactive|legend, set to 'pop'\n") labels <- "pop" } if (p < 0 | p > 1){ cat(" Warning: Parameter 'p' must fall between 0 and 1, set to 0.95\n") p <- 0.95 } if (hadjust < 0 | hadjust > 3){ cat(" Warning: Parameter 'hadjust' must fall between 0 and 3, set to 1.5\n") hadjust <- 1.5 } if (vadjust < 0 | hadjust > 3){ cat(" Warning: Parameter 'vadjust' must fall between 0 and 3, set to 1.5\n") vadjust <- 1.5 } if (xaxis < 1 | xaxis > ncol(glPca$scores)){ cat(" Warning: X-axis must be specified to lie between 1 and the number of retained dimensions of the ordination",ncol(glPca$scores),"; set to 1\n") xaxis <- 1 } if (xaxis < 1 | xaxis > ncol(glPca$scores)){ cat(" Warning: Y-axis must be specified to lie between 1 and the number of retained dimensions of the ordination",ncol(glPca$scores),"; set to 2\n") yaxis <- 2 } pop.hold <- pop(x) if (!is.null(as.pop)){ if(as.pop %in% names(x@other$ind.metrics)){ pop(x) <- as.matrix(x@other$ind.metrics[as.pop]) if (verbose >= 2) {cat(" Temporarily setting population assignments to",as.pop,"as specified by the as.pop parameter\n")} } else { stop("Fatal Error: individual metric assigned to 'pop' does not exist. Check names(gl@other$loc.metrics) and select again\n") } } m <- cbind(glPca$scores[,xaxis],glPca$scores[,yaxis]) df <- data.frame(m) s <- sum(glPca$eig[glPca$eig >= 0]) e <- round(glPca$eig*100/s,1) if(class(x)=="genlight"){ xlab <- paste("PCA Axis", xaxis, "(",e[xaxis],"%)") ylab <- paste("PCA Axis", yaxis, "(",e[yaxis],"%)") ind <- indNames(x) pop <- factor(pop(x)) df <- cbind(df,ind,pop) PCoAx <- PCoAy <- NA colnames(df) <- c("PCoAx","PCoAy","ind","pop") } else { xlab <- paste("PCoA Axis", xaxis, "(",e[xaxis],"%)") ylab <- paste("PCoA Axis", yaxis, "(",e[yaxis],"%)") ind <- rownames(as.matrix(x)) pop <- ind df <- cbind(df,ind,pop) colnames(df) <- c("PCoAx","PCoAy","ind","pop") if(labels == "interactive"){ cat(" Sorry, interactive labels are not available for an ordination generated from a Distance Matrix\n") cat(" Labelling the plot with names taken from the Distance Matrix\n") } labels <- "pop" } theme_list <- list( theme_minimal(), theme_classic(), theme_bw(), theme_gray(), theme_linedraw(), theme_light(), theme_dark(), ggthemes::theme_economist(), ggthemes::theme_economist_white(), ggthemes::theme_calc(), ggthemes::theme_clean(), ggthemes::theme_excel(), ggthemes::theme_excel_new(), ggthemes::theme_few(), ggthemes::theme_fivethirtyeight(), ggthemes::theme_foundation(), ggthemes::theme_gdocs(), ggthemes::theme_hc(), ggthemes::theme_igray(), ggthemes::theme_solarized(), ggthemes::theme_solarized_2(), ggthemes::theme_solid(), ggthemes::theme_stata(), ggthemes::theme_tufte(), ggthemes::theme_wsj()) if (labels == "ind") { if (verbose>0) cat(" Plotting individuals\n") p <- ggplot(df, aes(x=PCoAx, y=PCoAy, group=ind, colour=pop)) + geom_point(size=2,aes(colour=pop)) + theme_list[theme_plot] + ggrepel::geom_text_repel(aes(label = ind),show.legend=FALSE) + theme(axis.title=element_text(face="bold.italic",size="20", color="black"), axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=10), axis.text.y = element_text(face="bold",angle=0, vjust=0.5, size=10), legend.title = element_text(colour="black", size=18, face="bold"), legend.text = element_text(colour="black", size = 16, face="bold") ) + labs(x=xlab, y=ylab) + geom_hline(yintercept=0) + geom_vline(xintercept=0) if(scale==TRUE) { p <- p + coord_fixed(ratio=e[yaxis]/e[xaxis]) } if(ellipse==TRUE) {p <- p + stat_ellipse(aes(colour=pop), type="norm", level=0.95)} } if (labels == "pop") { if (class(x)=="genlight"){ if (verbose>0) cat(" Plotting populations\n") } else { if (verbose>0) cat(" Plotting entities from the Distance Matrix\n") } p <- ggplot(df, aes(x=PCoAx, y=PCoAy, group=pop, colour=pop)) + geom_point(size=2,aes(colour=pop)) + theme_list[theme_plot] + directlabels::geom_dl(aes(label=pop),method="smart.grid") + theme(axis.title=element_text(face="bold.italic",size="20", color="black"), axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=10), axis.text.y = element_text(face="bold",angle=0, vjust=0.5, size=10), legend.title = element_text(colour="black", size=18, face="bold"), legend.text = element_text(colour="black", size = 16, face="bold") ) + labs(x=xlab, y=ylab) + geom_hline(yintercept=0) + geom_vline(xintercept=0) + theme(legend.position="none") if(scale==TRUE) { p <- p + coord_fixed(ratio=e[yaxis]/e[xaxis]) } if(ellipse==TRUE) {p <- p + stat_ellipse(aes(colour="black"), type="norm", level=0.95)} } if (labels=="interactive" | labels=="ggplotly") { cat(" Displaying an interactive plot\n") cat(" NOTE: Returning the ordination scores, not a ggplot2 compatable object\n") plot.out <- FALSE p <- ggplot(df, aes(x=PCoAx, y=PCoAy)) + geom_point(size=2,aes(colour=pop, fill=ind)) + theme_list[theme_plot] + theme(axis.title=element_text(face="bold.italic",size="20", color="black"), axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=10), axis.text.y = element_text(face="bold",angle=0, vjust=0.5, size=10), legend.title = element_text(colour="black", size=18, face="bold"), legend.text = element_text(colour="black", size = 16, face="bold") ) + labs(x=xlab, y=ylab) + geom_hline(yintercept=0) + geom_vline(xintercept=0) + theme(legend.position="none") if(scale==TRUE) { p <- p + coord_fixed(ratio=e[yaxis]/e[xaxis]) } if(ellipse==TRUE) {p <- p + stat_ellipse(aes(colour=pop), type="norm", level=0.95)} cat("Ignore any warning on the number of shape categories\n") } if (labels == "legend") { if (verbose>0) cat("Plotting populations identified by a legend\n") p <- ggplot(df, aes(x=PCoAx, y=PCoAy,colour=pop)) + geom_point(size=2,aes(colour=pop)) + theme_list[theme_plot] + ggrepel::geom_text_repel(aes(label = pop),show.legend=FALSE) + theme(axis.title=element_text(face="bold.italic",size="20", color="black"), axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=10), axis.text.y = element_text(face="bold",angle=0, vjust=0.5, size=10), legend.title = element_text(colour="black", size=18, face="bold"), legend.text = element_text(colour="black", size = 16, face="bold") ) + labs(x=xlab, y=ylab) + geom_hline(yintercept=0) + geom_vline(xintercept=0) if(scale==TRUE) { p <- p + coord_fixed(ratio=e[yaxis]/e[xaxis]) } if(ellipse==TRUE) {p <- p + stat_ellipse(aes(colour=pop), type="norm", level=0.95)} } if (labels == "none" | labels==FALSE) { if (verbose>0) cat("Plotting points with no labels\n") p <- ggplot(df, aes(x=PCoAx, y=PCoAy,colour=pop)) + geom_point(size=2,aes(colour=pop)) + theme_list[theme_plot] + theme(axis.title=element_text(face="bold.italic",size="20", color="black"), axis.text.x = element_text(face="bold",angle=0, vjust=0.5, size=10), axis.text.y = element_text(face="bold",angle=0, vjust=0.5, size=10), legend.title = element_text(colour="black", size=18, face="bold"), legend.text = element_text(colour="black", size = 16, face="bold") ) + labs(x=xlab, y=ylab) + geom_hline(yintercept=0) + geom_vline(xintercept=0)+ theme(legend.position="none") if(scale==TRUE) { p <- p + coord_fixed(ratio=e[yaxis]/e[xaxis]) } if(ellipse==TRUE) {p <- p + stat_ellipse(aes(colour=pop), type="norm", level=0.95)} } if (verbose>0) cat(" Preparing plot .... please wait\n") if(labels=="interactive"){ pp <- plotly::ggplotly(p) show(pp) } else { show(p) } if(plot.out) { if(verbose >= 2){cat(" While waiting, returning ggplot compliant object\n")} } else { if(verbose >= 2){cat(" While waiting, returning dataframe with coordinates of points in the ordinated space\n")} df <- data.frame(id=indNames(x), pop=as.character(pop(x)), glPca$scores) row.names(df) <- NULL } if (!is.null(as.pop)){ pop(x) <- pop.hold if (verbose >= 3) {cat(" Resetting population assignments to initial state\n")} } if (verbose >= 1) { cat("Completed:",funname,"\n") } if(plot.out) { return(p) } else { return(df) } } }
testthat::context("TargetAssigningPipe") testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("initialize",{ testthat::skip_if_not_installed("stringi") targets <- list("ham","spam") targetsName <- list("_ham_","_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() testthat::expect_silent(TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps)) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("initialize targets type error",{ testthat::skip_if_not_installed("stringi") targets <- NULL targetsName <- list("_ham_","_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() testthat::expect_error(TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps), "[TargetAssigningPipe][initialize][FATAL] Checking the type of the 'targets' variable: NULL", fixed = TRUE) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("initialize targetsName type error",{ testthat::skip_if_not_installed("stringi") targets <- list("ham","spam") targetsName <- NULL propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() testthat::expect_error(TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps), "[TargetAssigningPipe][initialize][FATAL] Checking the type of the 'targetsName' variable: NULL", fixed = TRUE) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("initialize propertyName type error",{ testthat::skip_if_not_installed("stringi") targets <- list("ham","spam") targetsName <- list("_ham_","_spam_") propertyName <- NULL alwaysBeforeDeps <- list() notAfterDeps <- list() testthat::expect_error(TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps), "[TargetAssigningPipe][initialize][FATAL] Checking the type of the 'propertyName' variable: NULL", fixed = TRUE) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("initialize alwaysBeforeDeps type error",{ testthat::skip_if_not_installed("stringi") targets <- list("ham","spam") targetsName <- list("_ham_","_spam_") propertyName <- "target" alwaysBeforeDeps <- NULL notAfterDeps <- list() testthat::expect_error(TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps), "[TargetAssigningPipe][initialize][FATAL] Checking the type of the 'alwaysBeforeDeps' variable: NULL", fixed = TRUE) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("initialize notAfterDeps type error",{ testthat::skip_if_not_installed("stringi") targets <- list("ham","spam") targetsName <- list("_ham_","_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- NULL testthat::expect_error(TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps), "[TargetAssigningPipe][initialize][FATAL] Checking the type of the 'notAfterDeps' variable: NULL", fixed = TRUE) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("pipe",{ testthat::skip_if_not_installed("stringi") targets <- list("ham","spam") targetsName <- list("_ham_","_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() pipe <- TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps) path <- file.path("testFiles", "testTargetAssigningPipe", "files", "_ham_", "testFile.tsms") instance <- ExtractorSms$new(path) testthat::expect_equal(pipe$pipe(instance)$getSpecificProperty("target"), "ham") }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("pipe unrecognizable target",{ testthat::skip_if_not_installed("stringi") targets <- list("ham","spam") targetsName <- list("_ham_","_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() pipe <- TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps) path <- "testFiles/_pan_/30.tsms" instance <- ExtractorSms$new(path) testthat::expect_warning(pipe$pipe(instance), "\\[TargetAssigningPipe\\]\\[pipe\\]\\[WARN\\] The file: testFiles/_pan_/30.tsms has a target unrecognizable") }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("pipe instance type error",{ testthat::skip_if_not_installed("stringi") targets <- list("ham","spam") targetsName <- list("_ham_","_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() pipe <- TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps) instance <- NULL testthat::expect_error(pipe$pipe(instance), "[TargetAssigningPipe][pipe][FATAL] Checking the type of the 'instance' variable: NULL", fixed = TRUE) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("getTarget",{ testthat::skip_if_not_installed("stringi") targets <- list("ham", "spam") targetsName <- list("_ham_", "_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() pipe <- TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps) path <- "testFiles/_ham_/30.tsms" testthat::expect_equal(pipe$getTarget(path), "ham") }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("getTarget unrecognizable",{ testthat::skip_if_not_installed("stringi") targets <- list("ham", "spam") targetsName <- list("_ham_", "_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() pipe <- TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps) path <- "testFiles/_pan_/30.tsms" testthat::expect_equal(pipe$getTarget(path), "unrecognizable") }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("getTarget path type error",{ testthat::skip_if_not_installed("stringi") targets <- list("ham", "spam") targetsName <- list("_ham_", "_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() pipe <- TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps) path <- NULL testthat::expect_error(pipe$getTarget(path), "[TargetAssigningPipe][getTarget][FATAL] Checking the type of the 'path' variable: NULL", fixed = TRUE) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("checkTarget",{ testthat::skip_if_not_installed("stringi") targets <- list("ham", "spam") targetsName <- list("_ham_", "_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() pipe <- TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps) target <- "_ham_" path <- "testFiles/_ham_/30.tsms" testthat::expect_equal(pipe$checkTarget(target, path), list("_ham_" = "ham")) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("checkTarget target type error",{ testthat::skip_if_not_installed("stringi") targets <- list("ham", "spam") targetsName <- list("_ham_", "_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() pipe <- TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps) target <- NULL path <- "testFiles/_ham_/30.tsms" testthat::expect_error(pipe$checkTarget(target, path), "[TargetAssigningPipe][checkTarget][FATAL] Checking the type of the 'target' variable: NULL", fixed = TRUE) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("checkTarget path type error",{ testthat::skip_if_not_installed("stringi") targets <- list("ham","spam") targetsName <- list("_ham_","_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() pipe <- TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps) target <- "_ham_" path <- NULL testthat::expect_error(pipe$checkTarget(target, path), "[TargetAssigningPipe][checkTarget][FATAL] Checking the type of the 'path' variable: NULL", fixed = TRUE) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::setup({ bdpar.Options$reset() bdpar.Options$configureLog() }) testthat::test_that("getTargets",{ testthat::skip_if_not_installed("stringi") targets <- list("ham", "spam") targetsName <- list("_ham_", "_spam_") propertyName <- "target" alwaysBeforeDeps <- list() notAfterDeps <- list() pipe <- TargetAssigningPipe$new(targets, targetsName, propertyName, alwaysBeforeDeps, notAfterDeps) testthat::expect_equal(pipe$getTargets(), list("_ham_" = "ham", "_spam_" = "spam")) }) testthat::teardown({ bdpar.Options$reset() bdpar.Options$configureLog() })
context("densities-snorm") set.seed(313) x <- rnorm(10) theta0 <- 0 tau <- 0.05 sigma <- 0.1 alpha <- c(0, 0.025, 0.05, 1) eta <- c(1, 0.4, 0.1) expect_equal( log(dsnorm(x, theta0 = theta0, sigma = sigma, tau = tau, eta = eta)), dsnorm(x, theta0 = theta0, sigma = sigma, tau = tau, eta = eta, log = TRUE) ) n <- 3 y <- rep(1, n) expect_equal({ set.seed(1) rsnorm(n, theta0 = theta0, sigma = sigma, tau = tau, eta = eta) }, { set.seed(1) rsnorm(y, theta0 = theta0, sigma = sigma, tau = tau, eta = eta) }, ) expect_error(rsnorm(n, theta0 = theta0, sigma = sigma, tau = tau, eta = 1)) integrand <- function(theta) { theta * dsnorm(theta, theta0, tau, sigma, alpha, eta) } expectation <- integrate(integrand, lower = -Inf, upper = Inf)$value expect_equal(esnorm(theta0, tau, sigma, alpha, eta), expectation) expect_error(psnorm(x, theta0 = NA, sigma = sigma, tau = tau, eta = eta)) expect_error(psnorm(x, theta0 = theta0, sigma = -1, tau = tau, eta = eta)) expect_error(psnorm(x, theta0 = theta0, sigma = sigma, tau = 0, eta = eta)) expect_error(rsnorm(1, theta0 = NA, sigma = sigma, tau = tau, eta = eta)) expect_error(rsnorm(1, theta0 = theta0, sigma = -1, tau = tau, eta = eta)) expect_error(rsnorm(1, theta0 = theta0, sigma = sigma, tau = 0, eta = eta)) expect_error(dsnorm(x, theta0 = NA, sigma = sigma, tau = tau, eta = eta)) expect_error(dsnorm(x, theta0 = theta0, sigma = -1, tau = tau, eta = eta)) expect_error(dsnorm(x, theta0 = theta0, sigma = sigma, tau = 0, eta = eta)) expect_error(dsnorm("x", theta0 = theta0, sigma = sigma, tau = tau, eta = eta))
.defaultLinkableStates_l_hist <- c("selected", "color", "active") .defaultLinkableStates_l_plot <- c("selected", "color", "active", "size") .defaultLinkableStates_l_plot3D <- c("selected", "color", "active", "size") .defaultLinkableStates_l_serialaxes <- c("selected", "color", "active") .defaultLinkableStates_l_graph <- c("selected", "color", "active", "size") hasDefaultLinkableStatesVar <- function(l_className) { tryCatch(eval(parse(text = paste0(".defaultLinkableStates_", l_className))), error = function(e) { warning(substitute(deparse(l_className)), " does not have linked states.") }) }
pcf.kern.vech<-function(dendat,h,N,kernel="gauss",weights=NULL,support=NULL, lowest=0,radi=0) { d<-length(N) if (d>1){ if (kernel=="bart") ker<-function(xx,d){ musd<-2*pi^(d/2)/gamma(d/2) c<-d*(d+2)/(2*musd) return( c*(1-rowSums(xx^2))*(rowSums(xx^2) <= 1) ) } if (kernel=="gauss") ker<-function(xx,d){ return( (2*pi)^(-d/2)*exp(-rowSums(xx^2)/2) ) } if (kernel=="uniform") ker<-function(xx,d){ c<-gamma(d/2+1)/pi^(d/2) return( (rowSums(xx^2) <= 1) ) } if (kernel=="epane") ker<-function(xx,d){ c<-(3/4)^d xxx<-(1-xx^2)*(1-xx^2>=0) return( c*apply(xxx,1,prod) ) } recnum<-prod(N) value<-matrix(0,recnum,1) index<-matrix(0,recnum,d) if (is.null(support)){ support<-matrix(0,2*d,1) for (i in 1:d){ support[2*i-1]<-min(dendat[,i])-radi support[2*i]<-max(dendat[,i])+radi } } lowsuppo<-matrix(0,d,1) for (i in 1:d) lowsuppo[i]<-support[2*i-1] step<-matrix(0,d,1) for (i in 1:d) step[i]<-(support[2*i]-support[2*i-1])/N[i] numpositive<-0 for (i in 1:recnum){ inde<-digit(i-1,N)+1 arg<-lowsuppo+step*inde-step/2 argu<-matrix(arg,dim(dendat)[1],d,byrow=TRUE) w<-ker((dendat-argu)/h,d)/prod(h) valli<-mean(w) if (!is.null(weights)) valli<-t(weights)%*%w if (valli>lowest){ numpositive<-numpositive+1 value[numpositive]<-valli index[numpositive,]<-inde } } value<-value[1:numpositive] index<-index[1:numpositive,] down<-index-1 high<-index pcf<-list( value=value,index=index, down=down,high=high, support=support,N=N) } else{ d<-1 x<-matrix(dendat,length(dendat),1) if (kernel=="gauss") ker<-function(xx,d){ return( (2*pi)^(-1/2)*exp(-xx^2/2) ) } if (kernel=="uniform") ker<-function(xx,d){ return( (abs(xx) <= 1) ) } index<-seq(1:N) len<-length(index) value<-matrix(0,N,1) if (is.null(support)){ support<-matrix(0,2,1) support[1]<-min(x) support[2]<-max(x) } step<-(support[2]-support[1])/N lowsuppo<-support[1] numpositive<-0 for (i in 1:N){ inde<-i argu<-lowsuppo+step*inde-step/2 w<-ker((x-argu)/h,1)/h if (!is.null(weights)) valli<-t(weights)%*%w else valli<-mean(w) if (valli>lowest){ numpositive<-numpositive+1 value[numpositive]<-valli index[numpositive]<-inde } } value<-value[1:numpositive] index<-index[1:numpositive] down<-matrix(0,numpositive,1) high<-matrix(0,numpositive,1) down[,1]<-index-1 high[,1]<-index pcf<-list( value=value, down=down,high=high, support=support,N=N) } return(pcf) }
vanDeemter <- function(col, ext, dead, length, A, B, C, Foley = FALSE, GG = FALSE, do.plot = TRUE) { if (!is.numeric(A) | !is.numeric(B) | !is.numeric(C)) { stop("A, B and C parameters must be numeric") } if (!is.logical(Foley) | !is.logical(GG)) { stop("Foley and GG parameters must be logical") } if (Foley == TRUE & GG == TRUE) { stop("Just one approach (Foley or GG) at the time is possible") } if (Foley == FALSE & GG == FALSE) { stop("Foley or GG parameter must be TRUE") } if (!is.numeric(length)) { stop("length parameter must be numeric") } if (!is.data.frame(col)) { stop("col parameter must be a data frame") } if (!is.data.frame(ext)) { stop("ext parameter must be a data frame") } if (!is.data.frame(dead)) { stop("dead parameter must be a data frame") } col <- col[order(col$flow), ] ext <- ext[order(ext$flow), ] dead <- dead[order(dead$flow), ] t <- table(c(ext$flow, col$flow, dead$flow)) del <- as.numeric(names(which(t < max(as.vector(t))))) ext <- ext[!ext$flow %in% del, ] col <- col[!col$flow %in% del, ] dead <- dead[!dead$flow %in% del, ] Flow <- col[, "flow"] tr <- col[, "tr"] t0 <- dead[, "tr"] tre <- ext[, "tr"] velocity2 <- length/t0 if (Foley == TRUE) { var <- ((col$A10 + col$B10)^2)/(1.764 * ((col$B10/col$A10)^2) - 11.15 * (col$B10/col$A10) + 28) vare <- ((ext$A10 + ext$B10)^2)/(1.764 * ((ext$B10/ext$A10)^2) - 11.15 * (ext$B10/ext$A10) + 28) H <- ((var - vare)/(tr * tr - tre * tre)) * length * 1000 data <- as.data.frame(cbind(velocity2, H)) d <- ggplot(data, aes(x = data[, 1], y = data[, 2])) + geom_point(color = "black", size = 2, show.legend = TRUE) + geom_smooth(method = "nls", formula = y ~ A + (B/x) + C * x, method.args = list(start = c(A = A, B = B, C = C)), se = FALSE) d2 <- d + theme_bw() d22 <- d2 + theme(plot.title = element_text(face = "bold"), axis.title = element_text(size = 15), axis.title.y = element_text(margin = margin(0, 20, 0, 0)), legend.text = element_text(size = 15), legend.title = element_text(size = 15)) + scale_y_continuous(expression(H ~ (mu ~ m))) d22 <- d22 + theme_minimal() d22 <- d22 + scale_x_continuous(expression(u(mm/min))) if (do.plot == TRUE) { print(d22) } x <- data[, 1] y <- data[, 2] fit <- nls(y ~ A + (B/x) + C * x, start = list(A = A, B = B, C = C)) summary<-summary(fit) cor <- cor(y,predict(fit)) ME <- mean(abs(y-predict(fit))/abs(y))*100 return(list(coefficients=coefficients(fit),summary=summary, correlation=cor,MeanError=ME,RSE=summary(fit)$sigma)) } if (GG == TRUE) { col <- col[order(col$flow), ] ext <- ext[order(ext$flow), ] dead <- dead[order(dead$flow), ] t <- table(c(ext$flow, col$flow, dead$flow)) del <- as.numeric(names(which(t < max(as.vector(t))))) ext <- ext[!ext$flow %in% del, ] col <- col[!col$flow %in% del, ] dead <- dead[!dead$flow %in% del, ] var <- (((col$A60^3) + (col$B60^3))/(col$A60 + col$B60)) - (((2 * (col$B60 - col$A60)^2))/pi) vare <- (((ext$A60^3) + (ext$B60^3))/(ext$A60 + ext$B60)) - (((2 * (ext$B60 - ext$A60)^2))/pi) tr <- tr + (2 * (col$B60 - col$A60))/(sqrt(2 * pi)) tre <- tre + (2 * (ext$B60 - ext$A60))/(sqrt(2 * pi)) H <- ((var - vare)/(tr * tr - tre * tre)) * length * 1000 data <- as.data.frame(cbind(velocity2, H)) d <- ggplot(data, aes(x = data[, 1], y = data[, 2])) + geom_point(color = "black", size = 2, show.legend = TRUE) + geom_smooth(method = "nls", formula = y ~ A + (B/x) + C * x, method.args = list(start = c(A = A, B = B, C = C)), se = FALSE) d2 <- d + theme_bw() d22 <- d2 + theme(plot.title = element_text(face = "bold"), axis.title = element_text(size = 15), axis.title.y = element_text(margin = margin(0, 20, 0, 0)), legend.text = element_text(size = 15), legend.title = element_text(size = 15)) + scale_y_continuous(expression(H ~ (mu ~ m))) d22 <- d22 + theme_minimal() d22 <- d22 + scale_x_continuous(expression(u(mm/min))) if (do.plot == TRUE) { print(d22) } x <- data[, 1] y <- data[, 2] fit <- nls(y ~ A + (B/x) + C * x, start = list(A = A, B = B, C = C)) summary <- summary(fit) cor <- cor(y,predict(fit)) ME <- mean(abs(y-predict(fit))/abs(y))*100 return(list(coefficients = coefficients(fit), summary = summary, correlation = cor, MeanError = ME, RSE = summary(fit)$sigma)) } }
font_awesome_brands <-c("500px", "accessible-icon", "accusoft", "acquisitions-incorporated", "adn", "adversal", "affiliatetheme", "airbnb", "algolia", "alipay", "amazon", "amazon-pay", "amilia", "android", "angellist", "angrycreative", "angular", "app-store", "app-store-ios", "apper", "apple", "apple-pay", "artstation", "asymmetrik", "atlassian", "audible", "autoprefixer", "avianex", "aviato", "aws", "bandcamp", "battle-net", "behance", "behance-square", "bimobject", "bitbucket", "bitcoin", "bity", "black-tie", "blackberry", "blogger", "blogger-b", "bluetooth", "bluetooth-b", "bootstrap", "btc", "buffer", "buromobelexperte", "buy-n-large", "buysellads", "canadian-maple-leaf", "cc-amazon-pay", "cc-amex", "cc-apple-pay", "cc-diners-club", "cc-discover", "cc-jcb", "cc-mastercard", "cc-paypal", "cc-stripe", "cc-visa", "centercode", "centos", "chrome", "chromecast", "cloudflare", "cloudscale", "cloudsmith", "cloudversify", "codepen", "codiepie", "confluence", "connectdevelop", "contao", "cotton-bureau", "cpanel", "creative-commons", "creative-commons-by", "creative-commons-nc", "creative-commons-nc-eu", "creative-commons-nc-jp", "creative-commons-nd", "creative-commons-pd", "creative-commons-pd-alt", "creative-commons-remix", "creative-commons-sa", "creative-commons-sampling", "creative-commons-sampling-plus", "creative-commons-share", "creative-commons-zero", "critical-role", "css3", "css3-alt", "cuttlefish", "d-and-d", "d-and-d-beyond", "dailymotion", "dashcube", "deezer", "delicious", "deploydog", "deskpro", "dev", "deviantart", "dhl", "diaspora", "digg", "digital-ocean", "discord", "discourse", "dochub", "docker", "draft2digital", "dribbble", "dribbble-square", "dropbox", "drupal", "dyalog", "earlybirds", "ebay", "edge", "edge-legacy", "elementor", "ello", "ember", "empire", "envira", "erlang", "ethereum", "etsy", "evernote", "expeditedssl", "facebook", "facebook-f", "facebook-messenger", "facebook-square", "fantasy-flight-games", "fedex", "fedora", "figma", "firefox", "firefox-browser", "first-order", "first-order-alt", "firstdraft", "flickr", "flipboard", "fly", "font-awesome", "font-awesome-alt", "font-awesome-flag", "font-awesome-logo-full", "fonticons", "fonticons-fi", "fort-awesome", "fort-awesome-alt", "forumbee", "foursquare", "free-code-camp", "freebsd", "fulcrum", "galactic-republic", "galactic-senate", "get-pocket", "gg", "gg-circle", "git", "git-alt", "git-square", "github", "github-alt", "github-square", "gitkraken", "gitlab", "gitter", "glide", "glide-g", "gofore", "goodreads", "goodreads-g", "google", "google-drive", "google-pay", "google-play", "google-plus", "google-plus-g", "google-plus-square", "google-wallet", "gratipay", "grav", "gripfire", "grunt", "guilded", "gulp", "hacker-news", "hacker-news-square", "hackerrank", "hips", "hire-a-helper", "hive", "hooli", "hornbill", "hotjar", "houzz", "html5", "hubspot", "ideal", "imdb", "innosoft", "instagram", "instagram-square", "instalod", "intercom", "internet-explorer", "invision", "ioxhost", "itch-io", "itunes", "itunes-note", "java", "jedi-order", "jenkins", "jira", "joget", "joomla", "js", "js-square", "jsfiddle", "kaggle", "keybase", "keycdn", "kickstarter", "kickstarter-k", "korvue", "laravel", "lastfm", "lastfm-square", "leanpub", "less", "line", "linkedin", "linkedin-in", "linode", "linux", "lyft", "magento", "mailchimp", "mandalorian", "markdown", "mastodon", "maxcdn", "mdb", "medapps", "medium", "medium-m", "medrt", "meetup", "megaport", "mendeley", "microblog", "microsoft", "mix", "mixcloud", "mixer", "mizuni", "modx", "monero", "napster", "neos", "nimblr", "node", "node-js", "npm", "ns8", "nutritionix", "octopus-deploy", "odnoklassniki", "odnoklassniki-square", "old-republic", "opencart", "openid", "opera", "optin-monster", "orcid", "osi", "page4", "pagelines", "palfed", "patreon", "paypal", "penny-arcade", "perbyte", "periscope", "phabricator", "phoenix-framework", "phoenix-squadron", "php", "pied-piper", "pied-piper-alt", "pied-piper-hat", "pied-piper-pp", "pied-piper-square", "pinterest", "pinterest-p", "pinterest-square", "playstation", "product-hunt", "pushed", "python", "qq", "quinscape", "quora", "r-project", "raspberry-pi", "ravelry", "react", "reacteurope", "readme", "rebel", "red-river", "reddit", "reddit-alien", "reddit-square", "redhat", "renren", "replyd", "researchgate", "resolving", "rev", "rocketchat", "rockrms", "rust", "safari", "salesforce", "sass", "schlix", "scribd", "searchengin", "sellcast", "sellsy", "servicestack", "shirtsinbulk", "shopify", "shopware", "simplybuilt", "sistrix", "sith", "sketch", "skyatlas", "skype", "slack", "slack-hash", "slideshare", "snapchat", "snapchat-ghost", "snapchat-square", "soundcloud", "sourcetree", "speakap", "speaker-deck", "spotify", "squarespace", "stack-exchange", "stack-overflow", "stackpath", "staylinked", "steam", "steam-square", "steam-symbol", "sticker-mule", "strava", "stripe", "stripe-s", "studiovinari", "stumbleupon", "stumbleupon-circle", "superpowers", "supple", "suse", "swift", "symfony", "teamspeak", "telegram", "telegram-plane", "tencent-weibo", "the-red-yeti", "themeco", "themeisle", "think-peaks", "tiktok", "trade-federation", "trello", "tripadvisor", "tumblr", "tumblr-square", "twitch", "twitter", "twitter-square", "typo3", "uber", "ubuntu", "uikit", "umbraco", "uncharted", "uniregistry", "unity", "unsplash", "untappd", "ups", "usb", "usps", "ussunnah", "vaadin", "viacoin", "viadeo", "viadeo-square", "viber", "vimeo", "vimeo-square", "vimeo-v", "vine", "vk", "vnv", "vuejs", "watchman-monitoring", "waze", "weebly", "weibo", "weixin", "whatsapp", "whatsapp-square", "whmcs", "wikipedia-w", "windows", "wix", "wizards-of-the-coast", "wodu", "wolf-pack-battalion", "wordpress", "wordpress-simple", "wpbeginner", "wpexplorer", "wpforms", "wpressr", "xbox", "xing", "xing-square", "y-combinator", "yahoo", "yammer", "yandex", "yandex-international", "yarn", "yelp", "yoast", "youtube", "youtube-square", "zhihu")
annotate_mf_all <- function(xlfilepath) { spsheet <- readxl::read_excel(xlfilepath) if (any(grepl("^\\.\\.\\.", names(spsheet)))) { stop("Check the spreadsheet for empty values in the header row") } m_formatting <- tidyxl::xlsx_cells(xlfilepath) rowtally <- dplyr::count(m_formatting, row) if (length(unique(rowtally$n)) != 1) { stop("Data in spreadsheet does not appear to be rectangular (this includes multisheet files)") } format_defs <- tidyxl::xlsx_formats(xlfilepath) bold <- format_defs$local$font$bold italic <- format_defs$local$font$italic underlined <- format_defs$local$font$underline highlighted <- format_defs$local$fill$patternFill$patternType hl_color <- format_defs$local$fill$patternFill$fgColor$rgb strikethrough <- format_defs$local$font$strike text_clr <- format_defs$local$font$color$rgb format_opts <- tibble::lst( bold, highlighted, hl_color, italic, strikethrough, text_clr, underlined ) formatting_indicators <- dplyr::bind_cols(lapply( format_opts, function(x) x[m_formatting$local_format_id] )) format_joined <- dplyr::bind_cols(m_formatting, formatting_indicators) cols_spsheet <- match( names(spsheet), format_joined$character ) target_var_fmt <- function(col_ind) { orig_format <- dplyr::filter(format_joined, row >= 2 & col == col_ind) orig_format <- dplyr::select(orig_format, bold:underlined) formatted <- dplyr::bind_cols(spsheet, orig_format) formatted <- dplyr::mutate_at( formatted, dplyr::vars(bold:underlined), ~ replace(., is.na(.), FALSE) ) formatted$highlighted <- gsub( pattern = "FALSE", replacement = "", formatted$highlighted ) formatted$text_clr <- gsub( pattern = "FALSE", replacement = "", formatted$text_clr ) formatted$underlined <- gsub( pattern = "FALSE", replacement = "", formatted$underlined ) formatted$hl_color <- gsub( pattern = "FALSE", replacement = "", formatted$hl_color ) formatted <- dplyr::mutate_at( formatted, dplyr::vars(bold, italic, strikethrough), as.logical ) formatted <- dplyr::mutate_at( formatted, dplyr::vars(bold:underlined), function(x) { ifelse(x == TRUE, deparse(substitute(x)), x) } ) formatted <- dplyr::mutate_at( formatted, dplyr::vars(bold:underlined), ~ replace(., . == "FALSE", "") ) formatted$highlighted <- ifelse(formatted$highlighted != "", paste0("highlight", "-", formatted$hl_color), formatted$highlighted ) formatted$hl_color <- NULL formatted$text_clr <- ifelse(formatted$text_clr != "", paste0("color", "-", formatted$text_clr), formatted$text_clr ) formatted$underlined <- ifelse(formatted$underlined != "", paste0("underlined", "-", formatted$underlined), formatted$underlined ) formatted$newvar <- paste( formatted$bold, formatted$highlighted, formatted$italic, formatted$strikethrough, formatted$text_clr, formatted$underlined ) formatted$newvar <- stringr::str_squish(formatted$newvar) formatted$newvar <- gsub(" ", ", ", formatted$newvar) formatted <- dplyr::select(formatted, -c(bold:underlined)) formatted[[names(spsheet)[col_ind]]] <- paste0("(", formatted$newvar, ") ", formatted[[names(spsheet)[col_ind]]]) formatted[[names(spsheet)[col_ind]]] } for (i in seq_along(cols_spsheet)) { spsheet[, names(spsheet)[i]] <- target_var_fmt(i) } spsheet dplyr::mutate_all(spsheet, stringr::str_remove, "^\\(\\) ") }
precomp <- function(file, fun, ...) { bnf <- basename(file) if (!grepl("\\.", bnf)) file <- paste0(file, ".rds") precomp_global_mode <- getOption("spant.precomp_mode") precomp_global_verbose <- getOption("spant.precomp_verbose") if (precomp_global_mode == "default") { if (file.exists(file)) { if (precomp_global_verbose) cat("reading precomputed result:", file) result <- readRDS(file) } else { result <- do.call(fun, list(...)) if (precomp_global_verbose) cat("writing precomputed result:", file) saveRDS(result, file) } } else if (precomp_global_mode == "overwrite") { if (file.exists(file)) { result <- do.call(fun, list(...)) if (precomp_global_verbose) cat("overwriting precomputed result:", file) saveRDS(result, file) } else { result <- do.call(fun, list(...)) if (precomp_global_verbose) cat("writing precomputed result:", file) saveRDS(result, file) } } else if (precomp_global_mode == "clean") { if (file.exists(file)) { if (precomp_global_verbose) cat("reading and deleting precomputed result:", file) result <- readRDS(file) file.remove(file) } else { stop(paste0("precomputed file not found: ", file)) } } else if (precomp_global_mode == "disabled") { result <- do.call(fun, list(...)) } else { stop("I don't belong here.") } return(result) } set_precomp_mode <- function(mode = NA) { if (!((mode == "default") | (mode == "overwrite") | (mode == "clean") | (mode == "disabled"))) { stop("function argument must be one of \"default\", \"overwrite\", \"clean\" or \"disabled\"") } options(spant.precomp_mode = mode) } set_precomp_verbose <- function(verbose = NA) { if (!is.logical(verbose)) stop("function argument must be logical (TRUE or FALSE)") if (is.na(verbose)) stop("function argument must be logical (TRUE or FALSE)") options(spant.precomp_verbose = verbose) }
moo.ind.cpt=function(out.point,data,range,pos=TRUE,same=FALSE,sd=0.01,...){ n=length(data) if(any(out.point<1)){stop('out.point is less than 1')} else if(any(out.point>n)){stop('out.point is larger than the length of the data')} data[out.point]=make.many.outlier(data[out.point],range.data=range,pos=pos,same=same,sd=sd) outlier.ans=cpt.mean(data,...) return(outlier.ans) }
scale_color_flat <- function(palette = "contrast", discrete = TRUE, reverse = FALSE, ...) { pal <- palette_flat(palette = palette, reverse = reverse) if (discrete) { discrete_scale("colour", paste0("flat_", palette), palette = pal, ...) } else { scale_color_gradientn(colours = pal(256), ...) } } scale_color_flat_d <- function(palette = "contrast", discrete = TRUE, reverse = FALSE, ...) { scale_color_flat(palette = palette, discrete = discrete, reverse = reverse, ...) } scale_color_flat_c <- function(palette = "contrast", discrete = FALSE, reverse = FALSE, ...) { scale_color_flat(palette = palette, discrete = discrete, reverse = reverse, ...) } scale_colour_flat <- scale_color_flat scale_colour_flat_c <- scale_color_flat_c scale_colour_flat_d <- scale_color_flat_d scale_fill_flat <- function(palette = "contrast", discrete = TRUE, reverse = FALSE, ...) { pal <- palette_flat(palette = palette, reverse = reverse) if (discrete) { discrete_scale("fill", paste0("flat_", palette), palette = pal, ...) } else { scale_fill_gradientn(colours = pal(256), ...) } } scale_fill_flat_d <- function(palette = "contrast", discrete = TRUE, reverse = FALSE, ...) { scale_fill_flat(palette = palette, discrete = discrete, reverse = reverse, ...) } scale_fill_flat_c <- function(palette = "contrast", discrete = FALSE, reverse = FALSE, ...) { scale_fill_flat(palette = palette, discrete = discrete, reverse = reverse, ...) } flat_colors_list <- c( `red` = " `dark red` = " `purple` = " `deep purple` = " `blue` = " `light blue` = " `cyan` = " `teal` = " `green` = " `light green` = " `yellow` = " `amber` = " `orange` = " `deep orange` = " `grey` = " `blue grey` = " ) flat_colors <- function(...) { cols <- c(...) if (is.null(cols)) { return(flat_colors_list) } flat_colors_list[cols] } flat_palettes <- list( `full` = flat_colors(), `ice` = flat_colors("purple", "deep purple", "blue", "light blue"), `rainbow` = flat_colors("purple", "deep purple", "blue", "light blue", "green", "light green", "amber", "orange", "deep orange", "red"), `contrast` = flat_colors("blue", "green", "amber", "purple", "red"), `light` = flat_colors("light blue", "purple", "yellow", "light green", "orange"), `complement` = flat_colors("blue grey", "blue", "light blue", "teal", "green", "yellow", "amber", "orange", "red") ) palette_flat <- function(palette = "contrast", reverse = FALSE, ...) { pal <- flat_palettes[[palette]] if (reverse) pal <- rev(pal) grDevices::colorRampPalette(pal, ...) }
mrMLM<-function(fileGen=NULL,filePhe=NULL,fileKin=NULL,filePS=NULL,PopStrType=NULL,fileCov=NULL,Genformat=NULL,method=NULL, Likelihood="REML",trait=NULL,SearchRadius=20,CriLOD=NULL,SelectVariable=50, Bootstrap=FALSE,DrawPlot=TRUE,Plotformat="tiff",dir=NULL){ if(DrawPlot==TRUE){ manhattan_mrMLM<-function(data_in,data_fin,mar=c(2.9,2.8,0.7,2.8),VerLabDis=1.5,HorLabDis=1.5, HorTckDis=0.2,VerTckDis=0.4,label_size=0.8,CoorLwd=5, TckLen=-0.03,TckLwd=0.7,log_times=2,LOD_times=1.2,lodline){ method<-unique(data_in[,3]) data_method<-list(NULL) for(i in 1:length(method)){ data_method[[i]]<-data_in[which(data_in[,3]==method[i]),] } logp_4method<-numeric() for(i in 1:length(method)){ method_p<-data_method[[i]][,8] logp_4method<-cbind(logp_4method,method_p) } logp_4method<-apply(logp_4method,2,as.numeric) p_4method<-10^-logp_4method p_median<-apply(p_4method,1,median) locsub<-which(p_median==0) pmin<-min(p_median[p_median!=0]) subvalue<-10^(1.1*log10(pmin)) p_median[locsub]<-subvalue data_p<-as.matrix(p_median) data_num<-as.matrix(seq(1:length(p_median))) data_chr<-as.matrix(data_method[[1]][,5]) data_pos<-as.matrix(data_method[[1]][,6]) manresult<-cbind(data_chr,data_pos,data_p,data_num) manresult<-apply(manresult,2,as.numeric) colnames(manresult)<-c("Chromosome","BPnumber","P-value","SNPname") manresult<-as.data.frame(manresult) data_fin_method<-unique(data_fin[,3]) data_fin_method_length<-1:length(unique(data_fin[,3])) for(r in 1:length(unique(data_fin[,3]))){ data_fin[which(data_fin[,3]==data_fin_method[r]),3]<-r } data_fin_mark<-matrix(data_fin[,c(5,6,8,3)],,4) data_fin_mark<-matrix(apply(data_fin_mark,2,as.numeric),,4) data_fin_mark_chr<-matrix(data_fin_mark[order(data_fin_mark[,1]),],,4) data_fin_mark_order<-numeric() for(i in c(unique(data_fin_mark_chr[,1]))){ data_fin_mark_erery_chr<-matrix(data_fin_mark_chr[which(data_fin_mark_chr[,1]==i),],,4) data_fin_mark_pos<-matrix(data_fin_mark_erery_chr[order(data_fin_mark_erery_chr[,2]),],,4) all_pos<-unique(data_fin_mark_pos[,2]) all_pos_maxlod<-numeric() for(ii in 1:length(all_pos)){ all_pos_every<-matrix(data_fin_mark_pos[which(data_fin_mark_pos[,2]==all_pos[ii]),],,4) lod_me<-median(all_pos_every[,3]) all_pos_every_median<-c(all_pos_every[1,1:2],lod_me,all_pos_every[1,4]) if(nrow(all_pos_every)>=2){ all_pos_every_median<-c(all_pos_every[1,1:2],lod_me,max(data_fin_mark[,4])+1) } all_pos_maxlod<-rbind(all_pos_maxlod,all_pos_every_median) } data_fin_mark_order<-rbind(data_fin_mark_order,all_pos_maxlod) } snpOfInterest<-numeric() for(i in c(unique(data_fin_mark_order[,1]))){ manresult_chr<-manresult[which(manresult[,1]==i),] data_fin_mark_order_chr<-matrix(data_fin_mark_order[which(data_fin_mark_order[,1]==i),],,4) mark_loc<-manresult_chr[which(manresult_chr[,2]%in%data_fin_mark_order_chr[,2]),4] snpOfInterest<-c(snpOfInterest,mark_loc) } bpnumber <- numeric() chrnum <- unique(manresult[,1]) for(i in 1:length(chrnum)) { bpnumber <- rbind(bpnumber,as.matrix(c(1:length(which(manresult[,1]==chrnum[i]))))) } manresult2<-cbind(manresult[,1],bpnumber,manresult[,3:4]) colnames(manresult2)<-c("Chromosome","BPnumber","P-value","SNPname") x<-manresult2;col=c("lightgreen","lightskyblue");logp=TRUE chr = "Chromosome";bp ="BPnumber";p ="P-value";snp="SNPname"; highlight<-snpOfInterest CHR=BP=P=index=NULL d=data.frame(CHR=x[[chr]], BP=x[[bp]], P=x[[p]]) if (!is.null(x[[snp]])) d=transform(d, SNP=x[[snp]]) d <- subset(d, (is.numeric(CHR) & is.numeric(BP) & is.numeric(P))) d <- d[order(d$CHR, d$BP), ] if (logp) { d$logp <- -log10(d$P) } else { d$logp <- d$P } d$pos=NA d$index=NA ind = 0 for (i in unique(d$CHR)){ ind = ind + 1 d[d$CHR==i,]$index = ind } nchr = length(unique(d$CHR)) if (nchr==1) { d$pos=d$BP ticks=floor(length(d$pos))/2+1 xlabel = paste('Chromosome',unique(d$CHR),'position') labs = ticks } else { lastbase=0 ticks=NULL for (i in unique(d$index)) { if (i==1) { d[d$index==i, ]$pos=d[d$index==i, ]$BP } else { lastbase=lastbase+tail(subset(d,index==i-1)$BP, 1) d[d$index==i, ]$pos=d[d$index==i, ]$BP+lastbase } ticks = c(ticks, (min(d[d$index == i,]$pos) + max(d[d$index == i,]$pos))/2 + 1) } xlabel = 'Chromosomes' labs <- unique(d$CHR) } xmax = ceiling(max(d$pos) * 1.03) xmin = floor(max(d$pos) * -0.03) par(mar=mar) def_args <- list(xaxt='n',yaxt="n",bty='n', xaxs='i', yaxs='i', las=1, pch=20, xlim=c(xmin,xmax), ylim=c(0,log_times*max(d$logp)), xlab=xlabel,ylab="",mgp=c(HorLabDis,0,0),cex.lab=label_size) dotargs <- list(NULL) do.call("plot", c(NA, dotargs, def_args[!names(def_args) %in% names(dotargs)])) axis(1, at=ticks, labels=labs,lwd=CoorLwd,tck=TckLen,mgp=c(2.5,HorTckDis,0.5),cex.axis=TckLwd) suppressWarnings(axis(2, at=seq(0,log_times*max(d$logp),ceiling(log_times*max(d$logp)/5)),lwd=CoorLwd,tck=TckLen,mgp=c(2.2,VerTckDis,0),cex.axis=TckLwd)) mtext(expression(-log[10]('P-value')),side=2,line=VerLabDis,cex=label_size,font=1) col=rep(col, max(d$CHR)) if (nchr==1) { with(d, points(pos, logp, pch=20, col=col[1])) } else { icol=1 for (i in unique(d$index)) { with(d[d$index==unique(d$index)[i], ], points(pos, logp, col=col[icol], pch=20)) icol=icol+1 } } d.highlight=d[which(d$SNP %in% highlight), ] highlight_LOD<-as.numeric(data_fin_mark_order[,3]) d.highlight<-as.data.frame(cbind(d.highlight,highlight_LOD)) par(new=T) def_args <- list(xaxt='n', yaxt='n',bty='n', xaxs='i', yaxs='i', las=1, pch=20, xlim=c(xmin,xmax), ylim=c(0,LOD_times*max(highlight_LOD)),xlab="",ylab="") dotargs <- list(NULL) do.call("plot", c(NA, dotargs, def_args[!names(def_args) %in% names(dotargs)])) suppressWarnings(axis(4,mgp=c(1.4,VerTckDis,0),at=seq(0,LOD_times*max(highlight_LOD),ceiling(LOD_times*max(highlight_LOD)/5)),col="magenta",col.ticks="magenta",col.axis="magenta",lwd=CoorLwd,tck=TckLen,cex.axis=TckLwd)) mtext("LOD score",side=4,line=VerLabDis,cex=label_size,font=1,col="magenta") abline(h=lodline,col="gray25",lty=2,lwd=2) peach_colors<-c("magenta","deepskyblue2") col_pos<-list(NULL) method_num<-sort(unique(data_fin_mark_order[,4])) if(max(unique(data_fin[,3]))<max(unique(data_fin_mark_order[,4]))){ col_pos[[1]]<-which(data_fin_mark_order[,4]==max(method_num)) col_pos[[2]]<-which(data_fin_mark_order[,4]!=max(method_num)) }else{ if(length(unique(data_fin[,3]))==1){ col_pos[[1]]<-which(data_fin_mark_order[,4]==max(method_num)) }else{ col_pos[[1]]<-1:nrow(data_fin_mark_order) } } if(length(col_pos)>1&&length(col_pos[[2]])!=0){ with(d.highlight, points(pos[col_pos[[2]]], highlight_LOD[col_pos[[2]]], col=peach_colors[2], pch=20)) with(d.highlight, points(pos[col_pos[[2]]], highlight_LOD[col_pos[[2]]], col=peach_colors[2], pch=20,type="h",lty=2)) with(d.highlight, points(pos[col_pos[[1]]], highlight_LOD[col_pos[[1]]], col=peach_colors[1], pch=20)) with(d.highlight, points(pos[col_pos[[1]]], highlight_LOD[col_pos[[1]]], col=peach_colors[1], pch=20,type="h",lty=2)) }else{ with(d.highlight, points(pos[col_pos[[1]]], highlight_LOD[col_pos[[1]]], col=peach_colors[1], pch=20)) with(d.highlight, points(pos[col_pos[[1]]], highlight_LOD[col_pos[[1]]], col=peach_colors[1], pch=20,type="h",lty=2)) } } QQ_mrMLM<-function(data_in,mar=c(2.5,2.5,1,1),label_size=0.7,TckLen=-0.02, CoorLwd=3,TckLwd=0.6,HorLabDis=1,HorTckDis=0.02,VerLabDis=1.1, VerTckDis=0.3,P_stand=0.9){ method<-unique(data_in[,3]) data_method<-list(NULL) for(i in 1:length(method)){ data_method[[i]]<-data_in[which(data_in[,3]==method[i]),] } logp_4method<-numeric() for(i in 1:length(method)){ method_p<-data_method[[i]][,8] logp_4method<-cbind(logp_4method,method_p) } logp_4method<-apply(logp_4method,2,as.numeric) p_4method<-10^-logp_4method p_median<-apply(p_4method,1,median) locsub<-which(p_median==0) pmin<-min(p_median[p_median!=0]) subvalue<-10^(1.1*log10(pmin)) p_median[locsub]<-subvalue data_p<-as.matrix(p_median) p_value<-data_p pvalue<-matrix(p_value,,1) observed<-sort(pvalue[,1]) observed<-observed/2 observed<-observed[which(observed!=0)] newobserved<-observed[which(observed<(0.7/2))] lobs<--(log10(newobserved)) expected<-c(1:length(newobserved)) lexp<--(log10(expected/(length(pvalue)+1))) par(mar=mar) suppressWarnings(plot(lexp,lobs,xlim=c(0,max(lexp)),ylim=c(0,max(lobs)),xlab=expression('Expected -log'[10]*'(P-value)'), yaxt="n",ylab="",col="blue",pch=20,cex.lab=label_size,tck=TckLen,bty="l",lwd=CoorLwd, lwd.ticks=CoorLwd,cex.axis=TckLwd,mgp=c(HorLabDis,HorTckDis,0))) suppressWarnings(axis(2, at=seq(0,max(lobs)),lwd=CoorLwd,tck=TckLen,mgp=c(2.2,VerTckDis,0),cex.axis=TckLwd)) mtext(expression('Observed -log'[10]*'(P-value)'),side=2,line=VerLabDis,cex=label_size,font=1) abline(0,1,col="red") box(bty="l",lwd=CoorLwd) } } screen<-function(reMR,rawgen,gen_num,phe_num,ps_num){ if(nrow(reMR)>=200){ reMR4<-as.matrix(reMR[,4]) datashuz1<-rawgen[-1,1] calculate_gene<-t(gen_num[which(datashuz1%in%reMR4),-c(1,2)]) gene_shuzhi<-apply(calculate_gene,2,as.numeric) larsres<-lars(gene_shuzhi,phe_num,type = "lar",trace = FALSE,use.Gram=FALSE,max.steps=200) X<-gene_shuzhi[,which(larsres$beta[nrow(larsres$beta),]!=0)] MR200<-reMR[which(larsres$beta[nrow(larsres$beta),]!=0),] z<-cbind(matrix(1,nrow(gene_shuzhi),1),ps_num) u1<-try({sblgwas(z,phe_num,X,t = -4,max.iter = 200,min.err = 1e-8)},silent=TRUE) if('try-error' %in% class(u1)){ u1<-try({sblgwas(z,phe_num,X,t = -2,max.iter = 200,min.err = 1e-8)},silent=TRUE) } reMRshai<-MR200[which(u1$blup$p_wald<=0.01),] ind1<-which(larsres$beta[nrow(larsres$beta),]!=0) indz<-ind1[which(u1$blup$p_wald<=0.01)] }else if(nrow(reMR)<200){ reMR4<-as.matrix(reMR[,4]) datashuz1<-rawgen[-1,1] calculate_gene<-t(gen_num[which(datashuz1%in%reMR4),-c(1,2)]) gene_shuzhi<-apply(calculate_gene,2,as.numeric) X<-gene_shuzhi z<-cbind(matrix(1,nrow(gene_shuzhi),1),ps_num) u1<-try({sblgwas(z,phe_num,X,t = -4,max.iter = 200,min.err = 1e-8)},silent=TRUE) if('try-error' %in% class(u1)){ u1<-try({sblgwas(z,phe_num,X,t = -2,max.iter = 200,min.err = 1e-8)},silent=TRUE) } reMRshai<-reMR[which(u1$blup$p_wald<=0.01),] indz<-which(u1$blup$p_wald<=0.01) } reMR<-cbind(reMRshai[,1:12],reMR[1:nrow(reMRshai),13:14]) result<-list(reMR,indz) return(result) } svrad<-SearchRadius;svmlod<-CriLOD;lars1<-SelectVariable if(Genformat=="Num"){Genformat<-1}else if(Genformat=="Cha"){Genformat<-2}else if(Genformat=="Hmp"){Genformat<-3} Plotformat1<-paste("*.",Plotformat,sep="");Plotformat2<-paste("*.",Plotformat,sep="") readraw<-ReadData(fileGen,filePhe,fileKin,filePS,fileCov,Genformat) PheName<-readraw$phename CLO<-readraw$CLO print("Running in progress, please be patient...") for (i in trait){ InputData<-inputData(readraw,Genformat,method,i,PopStrType) reMR<-NULL;reFMR<-NULL;reFME<-NULL;rePLA<-NULL;rePKW<-NULL;reISIS<-NULL re1MR<-NULL;re1FMR<-NULL;re1FME<-NULL;re1PLA<-NULL;re1PKW<-NULL;re1ISIS<-NULL remanMR<-NULL;reqqMR<-NULL;remanFMR<-NULL;reqqFMR<-NULL;remanFME<-NULL;reqqFME<-NULL; replPLA<-NULL;remanPKW<-NULL;reqqPKW<-NULL; replISIS<-NULL;metaresult<-NULL;result_output<-NULL TRY1<-try({ if("mrMLM"%in%method){ outMR<-mrMLMFun(InputData$doMR$gen,InputData$doMR$phe,InputData$doMR$outATCG,InputData$doMR$genRaw,InputData$doMR$kk,InputData$doMR$psmatrix,0.01,svrad,svmlod,Genformat,CLO) if(is.null(outMR$result2)==FALSE){ me<-matrix("mrMLM",nrow(outMR$result2),1) tr<-matrix(i,nrow(outMR$result2),1) trna<-matrix(PheName[i,],nrow(outMR$result2),1) colnames(me)<-"Method" colnames(tr)<-"Trait ID" colnames(trna)<-"Trait name" reMR<-cbind(tr,trna,me,as.matrix(outMR$result2)) if(nrow(reMR)>50){ reMR<-screen(reMR,InputData$doMR$genRaw,InputData$doMR$gen,InputData$doMR$phe,InputData$doMR$psmatrix)[[1]] } } me1<-matrix("mrMLM",nrow(outMR$result1),1) tr1<-matrix(i,nrow(outMR$result1),1) tr1na<-matrix(PheName[i,],nrow(outMR$result1),1) colnames(me1)<-"Method" colnames(tr1)<-"Trait ID" colnames(tr1na)<-"Trait name" re1MR<-cbind(tr1,tr1na,me1,as.matrix(outMR$result1)) } },silent=FALSE) if ('try-error' %in% class(TRY1)|| !('try-error' %in% class(TRY1))){ TRY2<-try({ if("FASTmrMLM"%in%method){ outFMR<-FASTmrMLM(InputData$doMR$gen,InputData$doMR$phe,InputData$doMR$outATCG,InputData$doMR$genRaw,InputData$doMR$kk,InputData$doMR$psmatrix,0.01,svrad,svmlod,Genformat,CLO) if(is.null(outFMR$result2)==FALSE){ me<-matrix("FASTmrMLM",nrow(outFMR$result2),1) tr<-matrix(i,nrow(outFMR$result2),1) trna<-matrix(PheName[i,],nrow(outFMR$result2),1) colnames(me)<-"Method" colnames(tr)<-"Trait ID" colnames(trna)<-"Trait name" reFMR<-cbind(tr,trna,me,as.matrix(outFMR$result2)) if(nrow(reFMR)>50){ reFMR<-screen(reFMR,InputData$doMR$genRaw,InputData$doMR$gen,InputData$doMR$phe,InputData$doMR$psmatrix)[[1]] } } me1<-matrix("FASTmrMLM",nrow(outFMR$result1),1) tr1<-matrix(i,nrow(outFMR$result1),1) tr1na<-matrix(PheName[i,],nrow(outFMR$result1),1) colnames(me1)<-"Method" colnames(tr1)<-"Trait ID" colnames(tr1na)<-"Trait name" re1FMR<-cbind(tr1,tr1na,me1,as.matrix(outFMR$result1)) } },silent=FALSE) } if ('try-error' %in% class(TRY2)|| !('try-error' %in% class(TRY2))){ TRY3<-try({ if("FASTmrEMMA"%in%method){ outFME<-FASTmrEMMA(InputData$doFME$gen,InputData$doFME$phe,InputData$doFME$outATCG,InputData$doFME$genRaw,InputData$doFME$kk,InputData$doFME$psmatrix,0.005,svmlod,Genformat,Likelihood,CLO) if(is.null(outFME$result2)==FALSE){ me<-matrix("FASTmrEMMA",nrow(outFME$result2),1) tr<-matrix(i,nrow(outFME$result2),1) trna<-matrix(PheName[i,],nrow(outFME$result2),1) colnames(me)<-"Method" colnames(tr)<-"Trait ID" colnames(trna)<-"Trait name" reFME<-cbind(tr,trna,me,as.matrix(outFME$result2)) if(nrow(reFME)>50){ reFME<-screen(reFME,InputData$doFME$genRaw,InputData$doFME$gen,InputData$doFME$phe,InputData$doFME$psmatrix)[[1]] } } me1<-matrix("FASTmrEMMA",nrow(outFME$result1),1) tr1<-matrix(i,nrow(outFME$result1),1) tr1na<-matrix(PheName[i,],nrow(outFME$result1),1) colnames(me1)<-"Method" colnames(tr1)<-"Trait ID" colnames(tr1na)<-"Trait name" re1FME<-cbind(tr1,tr1na,me1,as.matrix(outFME$result1)) } },silent=FALSE) } if ('try-error' %in% class(TRY3)|| !('try-error' %in% class(TRY3))){ TRY4<-try({ if("pLARmEB"%in%method){ outPLA<-pLARmEB(InputData$doMR$gen,InputData$doMR$phe,InputData$doMR$outATCG,InputData$doMR$genRaw,InputData$doMR$kk,InputData$doMR$psmatrix,CriLOD,lars1,Genformat,Bootstrap,CLO) if(is.null(outPLA$result)==FALSE){ me<-matrix("pLARmEB",nrow(outPLA$result),1) tr<-matrix(i,nrow(outPLA$result),1) trna<-matrix(PheName[i,],nrow(outPLA$result),1) colnames(me)<-"Method" colnames(tr)<-"Trait ID" colnames(trna)<-"Trait name" rePLA<-cbind(tr,trna,me,as.matrix(outPLA$result)) replPLA<-outPLA$plot if(nrow(rePLA)>50){ rePLAQ<-screen(rePLA,InputData$doMR$genRaw,InputData$doMR$gen,InputData$doMR$phe,InputData$doMR$psmatrix) rePLA<-rePLAQ[[1]] } } } },silent=FALSE) } if ('try-error' %in% class(TRY4)|| !('try-error' %in% class(TRY4))){ TRY5<-try({ if("pKWmEB"%in%method){ outPKW<-pKWmEB(InputData$doMR$gen,InputData$doMR$phe,InputData$doMR$outATCG,InputData$doMR$genRaw,InputData$doMR$kk,InputData$doMR$psmatrix,0.05,svmlod,Genformat,CLO) if(is.null(outPKW$result2)==FALSE){ me<-matrix("pKWmEB",nrow(outPKW$result2),1) tr<-matrix(i,nrow(outPKW$result2),1) trna<-matrix(PheName[i,],nrow(outPKW$result2),1) colnames(me)<-"Method" colnames(tr)<-"Trait ID" colnames(trna)<-"Trait name" rePKW<-cbind(tr,trna,me,as.matrix(outPKW$result2)) if(nrow(rePKW)>50){ rePKW<-screen(rePKW,InputData$doMR$genRaw,InputData$doMR$gen,InputData$doMR$phe,InputData$doMR$psmatrix)[[1]] } } me1<-matrix("pKWmEB",nrow(outPKW$result1),1) tr1<-matrix(i,nrow(outPKW$result1),1) tr1na<-matrix(PheName[i,],nrow(outPKW$result1),1) colnames(me1)<-"Method" colnames(tr1)<-"Trait ID" colnames(tr1na)<-"Trait name" re1PKW<-cbind(tr1,tr1na,me1,as.matrix(outPKW$result1)) } },silent=FALSE) } if ('try-error' %in% class(TRY5)|| !('try-error' %in% class(TRY5))){ TRY6<-try({ if("ISIS EM-BLASSO"%in%method){ outISIS<-ISIS(InputData$doMR$gen,InputData$doMR$phe,InputData$doMR$outATCG,InputData$doMR$genRaw,InputData$doMR$kk,InputData$doMR$psmatrix,0.01,svmlod,Genformat,CLO) if(is.null(outISIS$result)==FALSE){ me<-matrix("ISIS EM-BLASSO",nrow(outISIS$result),1) tr<-matrix(i,nrow(outISIS$result),1) trna<-matrix(PheName[i,],nrow(outISIS$result),1) colnames(me)<-"Method" colnames(tr)<-"Trait ID" colnames(trna)<-"Trait name" reISIS<-cbind(tr,trna,me,as.matrix(outISIS$result)) replISIS<-outISIS$plot if(nrow(reISIS)>50){ reISISQ<-screen(reISIS,InputData$doMR$genRaw,InputData$doMR$gen,InputData$doMR$phe,InputData$doMR$psmatrix) reISIS<-reISISQ[[1]] } } } },silent=FALSE) } if ('try-error' %in% class(TRY6)|| !('try-error' %in% class(TRY6))){ TRY7<-try({ output1qq<-list(re1MR,re1FMR,re1FME,re1PKW) output1q<-do.call(rbind,output1qq) if(isFALSE(all(lengths(output1qq)==0))){ eff<-numeric() logp<-numeric() for(bb in c(which(lengths(output1qq)!=0))){ eff_every<-as.matrix(output1qq[[bb]][,7]) colnames(eff_every)<-colnames(output1qq[[bb]])[7] eff<-cbind(eff,eff_every) logp_every<-as.matrix(output1qq[[bb]][,8]) colnames(logp_every)<-colnames(output1qq[[bb]])[8] logp<-cbind(logp,logp_every) } gencode1<-as.matrix(output1qq[[which(lengths(output1qq)!=0)[1]]][,9]) colnames(gencode1)<-colnames(output1q)[[9]] output1<-cbind(output1qq[[which(lengths(output1qq)!=0)[1]]][,c(1,2,4,5,6)],eff,logp,gencode1) if("SNP effect (pKWmEB)"%in%colnames(output1)){ output1<-output1[,-c(which(colnames(output1)%in%"SNP effect (pKWmEB)"))] } }else{ output1<-output1q } write.table(output1,paste(dir,"/",i,"_intermediate result.csv",sep=""),sep=",",row.names=FALSE,col.names = T) },silent=FALSE) } if ('try-error' %in% class(TRY7)|| !('try-error' %in% class(TRY7))){ TRY8<-try({ output<-list(reMR,reFMR,reFME,rePLA,rePKW,reISIS) output<-do.call(rbind,output) write.table(output,paste(dir,"/",i,"_Final result.csv",sep=""),sep=",",row.names=FALSE,col.names = T) },silent=FALSE) } if ('try-error' %in% class(TRY8)|| !('try-error' %in% class(TRY8))){ TRY9<-try({ if(DrawPlot==TRUE){ if(isFALSE(all(lengths(output1qq)==0))){ manwidth<-28000;manhei<-7000;manwordre<-60;manfigurere<-600 qqwidth<-10000;qqhei<-10000;qqwordre<-60;qqfigurere<-600 if(Plotformat1=="*.png"){ png(paste(dir,"/",i,"_Manhattan plot.png",sep=""),width=as.numeric(manwidth), height=as.numeric(manhei), units= "px", pointsize =as.numeric(manwordre),res=as.numeric(manfigurere)) manhattan_mrMLM(data_in=as.matrix(output1q),data_fin=as.matrix(output),lodline=CriLOD) dev.off() png(paste(dir,"/",i,"_qq plot.png",sep=""),width=as.numeric(qqwidth), height=as.numeric(qqhei), units= "px", pointsize =as.numeric(qqwordre),res=as.numeric(qqfigurere)) QQ_mrMLM(data_in=as.matrix(output1q)) dev.off() }else if(Plotformat1=="*.tiff"){ tiff(paste(dir,"/",i,"_Manhattan plot.tiff",sep=""),width=as.numeric(manwidth), height=as.numeric(manhei), units= "px", pointsize =as.numeric(manwordre),res=as.numeric(manfigurere)) manhattan_mrMLM(data_in=as.matrix(output1q),data_fin=as.matrix(output),lodline=CriLOD) dev.off() tiff(paste(dir,"/",i,"_qq plot.tiff",sep=""),width=as.numeric(qqwidth), height=as.numeric(qqhei), units= "px", pointsize =as.numeric(qqwordre),res=as.numeric(qqfigurere)) QQ_mrMLM(data_in=as.matrix(output1q)) dev.off() }else if(Plotformat1=="*.jpeg"){ jpeg(paste(dir,"/",i,"_Manhattan plot.jpeg",sep=""),width=as.numeric(manwidth), height=as.numeric(manhei), units= "px", pointsize =as.numeric(manwordre),res=as.numeric(manfigurere)) manhattan_mrMLM(data_in=as.matrix(output1q),data_fin=as.matrix(output),lodline=CriLOD) dev.off() jpeg(paste(dir,"/",i,"_qq plot.jpeg",sep=""),width=as.numeric(qqwidth), height=as.numeric(qqhei), units= "px", pointsize =as.numeric(qqwordre),res=as.numeric(qqfigurere)) QQ_mrMLM(data_in=as.matrix(output1q)) dev.off() }else if(Plotformat1=="*.pdf"){ pdf(paste(dir,"/",i,"_Manhattan plot.pdf",sep=""),width=16,height=4,pointsize = 20) manhattan_mrMLM(data_in=as.matrix(output1q),data_fin=as.matrix(output),CoorLwd=2,lodline=CriLOD) dev.off() pdf(paste(dir,"/",i,"_qq plot.pdf",sep=""),pointsize = 25) QQ_mrMLM(data_in=as.matrix(output1q),CoorLwd=2) dev.off() } }else{ warning("Draw plot need intermediate result of mrMLM, FASTmrMLM, FASTmrEMMA or pKWmEB!") } } },silent=FALSE) } } } ReadData<-function(fileGen=NULL,filePhe=NULL,fileKin=NULL,filePS=NULL,fileCov=NULL,Genformat=NULL){ kkRaw<-NULL psmatrixRaw<-NULL covmatrixRaw<-NULL inputform<-Genformat CLO<-NULL if(!is.null(fileGen)){ if(is.character(fileGen)==TRUE){ genRaw<-fread(fileGen,header = FALSE,stringsAsFactors=T) }else{ genRaw<-fileGen CLO<-1 } genRaw<-as.matrix(genRaw) } wnameGen <- as.matrix(genRaw[1,],1,) if(inputform==1){ titlenameGen<-wnameGen[1:4,] hapName<-c("rs if(all(titlenameGen==hapName)==FALSE){ warning("please check the individual's name in genotypic file") } } if(inputform==2){ titlenameGen<-wnameGen[1:3,] hapName<-c("rs if(all(titlenameGen==hapName)==FALSE){ warning("please check the individual's name in genotypic file") } } if(inputform==3){ titlenameGen<-wnameGen[1:11,] hapName<- c("rs if(all(titlenameGen==hapName)==FALSE){ warning("please check the individual's name in genotypic file") } } if(!is.null(filePhe)){ if(is.character(filePhe)==TRUE){ pheRaw1q<-fread(filePhe,header=F, stringsAsFactors=T) }else{ pheRaw1q<-filePhe CLO<-1 } pheRaw1q<-as.matrix(pheRaw1q) } wnamePhe <- as.matrix(pheRaw1q[,1],,1) wsameName <- intersect(wnameGen,wnamePhe) wlocGen <- match(wsameName,wnameGen) if(is.null(wlocGen)){ warning("please check the individual's name (ID) in genotypic and phenotypic files") } if(!is.null(fileKin)){ kkRaw<-fread(fileKin,header = FALSE,stringsAsFactors=T) kkRaw<-as.matrix(kkRaw) nnkk<-dim(kkRaw)[1] kkRaw[1,2:nnkk]<-" " } if(!is.null(filePS)){ psmatrixRaw<-fread(filePS,header = FALSE,stringsAsFactors=T) psmatrixRaw<-as.matrix(psmatrixRaw) } if(!is.null(fileCov)){ covmatrixRaw<-fread(fileCov,header = FALSE,stringsAsFactors=T) covmatrixRaw<-as.matrix(covmatrixRaw) } phename<-as.matrix(pheRaw1q[1,2:ncol(pheRaw1q)]) output<-list(genRaw=genRaw,pheRaw1q=pheRaw1q,kkRaw=kkRaw,psmatrixRaw=psmatrixRaw,covmatrixRaw=covmatrixRaw,phename=phename,CLO=CLO) return(output) } DoData<-function(genRaw=NULL,Genformat=NULL,pheRaw1q=NULL,kkRaw=NULL,psmatrixRaw=NULL, covmatrixRaw=NULL,trait=NULL,type=NULL,PopStrType=NULL){ inputform<-Genformat pheRaw1qq<-as.matrix(pheRaw1q[,2:ncol(pheRaw1q)]) pheRaw1<-cbind(pheRaw1q[,1],pheRaw1qq[,trait]) pheRaw2<-pheRaw1[-1,] pheRaw3<-as.data.frame(pheRaw2,stringsAsFactors=FALSE) pheRaw4<-as.matrix(pheRaw3[is.na(pheRaw3[,2])==F,]) pheRawthem<-matrix(c(pheRaw1[1,1]," "),1,) pheRaw<-rbind(pheRawthem,pheRaw4) row.names(pheRaw)<-NULL pheRaw<-as.matrix(pheRaw) if(type==1&&inputform==1){ genRawz<-genRaw[-1,-c(1:4)] genRawz2<-gsub("0","0.5",genRawz) genRawz3<-gsub("-1","0",genRawz2) genRawz4<-cbind(genRaw[-1,c(1:4)],genRawz3) genRaw<-rbind(genRaw[1,],genRawz4) }else{ genRaw<-genRaw } if(inputform==1){ nameGen <- as.matrix(genRaw[1,],1,) namePhe <- as.matrix(pheRaw[,1],,1) sameName <- intersect(nameGen,namePhe) locGen <- match(sameName,nameGen) locPhe <- match(sameName,namePhe) hapName <- matrix(c("rs hapHave <- intersect(nameGen,hapName) locHap <- match(hapHave,nameGen) newGenloc <- c(locHap,locGen) newPheloc <- locPhe newGen <- as.matrix(genRaw[-1,newGenloc]) newPhe <- as.matrix(pheRaw[newPheloc,]) nnhap <- length(hapHave) rownewGen <- dim(newGen)[1] colnewGen <- dim(newGen)[2] rownewPhe <- dim(newPhe)[1] newGen <-rbind(genRaw[1,newGenloc],newGen) locChr <- as.numeric(which(newGen[1,]=="chrom")) locPos <- as.numeric(which(newGen[1,]=="pos")) needloc <- c(locChr,locPos,(nnhap+1):colnewGen) needGen <- newGen[,needloc] gen<-as.matrix(needGen[-1,]) gen<-matrix(as.numeric(gen),nrow=nrow(gen)) rm(newGen,needGen) gc() pheRaw[1,2]<-" " newPhe<-rbind(pheRaw[1,],newPhe) phe<-as.matrix(newPhe[-1,-1]) phe<-matrix(as.numeric(phe),nrow=nrow(phe)) outATCG<-NULL }else if(inputform==2){ nameGen <- as.matrix(genRaw[1,],1,) namePhe <- as.matrix(pheRaw[,1],,1) sameName <- intersect(nameGen,namePhe) locGen <- match(sameName,nameGen) locPhe <- match(sameName,namePhe) hapName <- matrix(c("rs hapHave <- intersect(nameGen,hapName) locHap <- match(hapHave,nameGen) newGenloc <- c(locHap,locGen) newPheloc <- locPhe newGen <- as.matrix(genRaw[-1,newGenloc]) newPhe <- as.matrix(pheRaw[newPheloc,]) nnhap <- length(hapHave) rownewGen <- dim(newGen)[1] colnewGen <- dim(newGen)[2] rownewPhe <- dim(newPhe)[1] computeGen <- newGen[,(nnhap+1):colnewGen] colComGen <- ncol(computeGen) referSam <- as.vector(computeGen[,1]) ATCGloc <- c(which(computeGen[,1]=="A"),which(computeGen[,1]=="T"),which(computeGen[,1]=="C"),which(computeGen[,1]=="G")) NNRRloc <- setdiff(c(1:rownewGen),ATCGloc) for(i in 2:colComGen) { if(length(NNRRloc)>0){ referSam[NNRRloc] <- as.vector(computeGen[NNRRloc,i]) ATCGlocLoop <- c(which(computeGen[NNRRloc,i]=="A"),which(computeGen[NNRRloc,i]=="T"),which(computeGen[NNRRloc,i]=="C"),which(computeGen[NNRRloc,i]=="G")) NNRRloc <- setdiff(NNRRloc,NNRRloc[ATCGlocLoop]) }else{ break } } for(i in 1:rownewGen) { tempSel1 <- as.vector(c(which(computeGen[i,]=="A"),which(computeGen[i,]=="T"),which(computeGen[i,]=="C"),which(computeGen[i,]=="G"))) tempSel2 <- as.vector(c(which(computeGen[i,]==referSam[i]))) notRef <- setdiff(tempSel1,tempSel2) notATCG <- setdiff(c(1:colComGen),tempSel1) computeGen[i,tempSel2] <- as.numeric(1) if(type==1){ computeGen[i,notRef] <- as.numeric(0) computeGen[i,notATCG] <- as.numeric(0.5) }else{ computeGen[i,notRef] <- as.numeric(-1) computeGen[i,notATCG] <- as.numeric(0) } } outATCG<-as.matrix(referSam) newGen <- cbind(newGen[,1:nnhap],computeGen) newGen <-rbind(genRaw[1,newGenloc],newGen) rm(computeGen) gc() locChr <- as.numeric(which(newGen[1,]=="chrom")) locPos <- as.numeric(which(newGen[1,]=="pos")) needloc <- c(locChr,locPos,(nnhap+1):colnewGen) needGen<-newGen[,needloc] gen<-as.matrix(needGen[-1,]) gen<-matrix(as.numeric(gen),nrow=nrow(gen)) rm(newGen,needGen) gc() pheRaw[1,2]<-" " newPhe<-rbind(pheRaw[1,],newPhe) phe<-as.matrix(newPhe[-1,-1]) phe<-matrix(as.numeric(phe),nrow=nrow(phe)) }else if(inputform==3){ nameGen<-as.matrix(genRaw[1,],1,) namePhe<-as.matrix(pheRaw[,1],,1) sameName<-intersect(nameGen,namePhe) locGen<-match(sameName,nameGen) locPhe<-match(sameName,namePhe) hapName<-matrix(c("rs hapHave<-intersect(nameGen,hapName) locHap<-match(hapHave,nameGen) newGenloc<-c(locHap,locGen) newPheloc<-locPhe newGen<-as.matrix(genRaw[-1,newGenloc]) newPhe<-as.matrix(pheRaw[newPheloc,]) nnhap<-length(hapHave) rownewGen<-dim(newGen)[1] colnewGen<-dim(newGen)[2] rownewPhe<-dim(newPhe)[1] computeGen<-newGen[,(nnhap+1):colnewGen] colComGen<-ncol(computeGen) referSam<-as.vector(computeGen[,1]) ATCGloc<-c(which(computeGen[,1]=="AA"),which(computeGen[,1]=="TT"),which(computeGen[,1]=="CC"),which(computeGen[,1]=="GG")) NNRRloc<-setdiff(c(1:rownewGen),ATCGloc) for(i in 2:colComGen) { if(length(NNRRloc)>0){ referSam[NNRRloc]<-as.vector(computeGen[NNRRloc,i]) ATCGlocLoop<-c(which(computeGen[NNRRloc,i]=="AA"),which(computeGen[NNRRloc,i]=="TT"),which(computeGen[NNRRloc,i]=="CC"),which(computeGen[NNRRloc,i]=="GG")) NNRRloc<-setdiff(NNRRloc,NNRRloc[ATCGlocLoop]) }else{ break } } for(i in 1:rownewGen) { tempSel1<-as.vector(c(which(computeGen[i,]=="AA"),which(computeGen[i,]=="TT"),which(computeGen[i,]=="CC"),which(computeGen[i,]=="GG"))) tempSel2<-as.vector(c(which(computeGen[i,]==referSam[i]))) notRef<-setdiff(tempSel1,tempSel2) notATCG<-setdiff(c(1:colComGen),tempSel1) computeGen[i,tempSel2]<-as.numeric(1) if(type==1){ computeGen[i,notRef]<-as.numeric(0) computeGen[i,notATCG]<-as.numeric(0.5) }else{ computeGen[i,notRef]<-as.numeric(-1) computeGen[i,notATCG]<-as.numeric(0) } } outATCG<-as.matrix(referSam) newGen<-cbind(newGen[,1:nnhap],computeGen) newGen<-rbind(genRaw[1,newGenloc],newGen) rm(computeGen) gc() locChr<-as.numeric(which(newGen[1,]=="chrom")) locPos<-as.numeric(which(newGen[1,]=="pos")) needloc<-c(locChr,locPos,(nnhap+1):colnewGen) needGen<-newGen[,needloc] gen<-as.matrix(needGen[-1,]) gen<-matrix(as.numeric(gen),nrow=nrow(gen)) rm(newGen,needGen) gc() pheRaw[1,2]<-" " newPhe<-rbind(pheRaw[1,],newPhe) phe<-as.matrix(newPhe[-1,-1]) phe<-matrix(as.numeric(phe),nrow=nrow(phe)) } if(is.null(kkRaw)){ kk<-NULL }else{ kkPre<-as.matrix(kkRaw[-1,-1]) nameKin<-as.matrix(kkRaw[-1,1]) sameGenKin<-intersect(sameName,nameKin) locKin<-match(sameGenKin,nameKin) kk<-kkPre[locKin,locKin] kk<-matrix(as.numeric(kk),nrow=nrow(kk)) } if(is.null(psmatrixRaw)){ psmatrix<-NULL }else{ nnpprow<-dim(psmatrixRaw)[1] nnppcol<-dim(psmatrixRaw)[2] psmatrixRaw[1,2:nnppcol]<-" " psmatrixPre<-psmatrixRaw[3:nnpprow,] namePop<-as.matrix(psmatrixPre[,1]) sameGenPop<-intersect(sameName,namePop) locPop<-match(sameGenPop,namePop) selectpsmatrixq<-psmatrixPre[locPop,-1] if(PopStrType=="Q"){ selectpsmatrix<-matrix(as.numeric(selectpsmatrixq),nrow = length(locPop)) coldelet<-which.min(apply(selectpsmatrix,2,sum)) psmatrix<-as.matrix(selectpsmatrix[,-coldelet]) }else if(PopStrType=="PCA"){ psmatrix<-matrix(as.numeric(selectpsmatrixq),nrow = length(locPop)) }else if(PopStrType=="EvolPopStr"){ otrait_ind<-sort(unique(selectpsmatrixq)) pop_col<-length(otrait_ind)-1 pop_each<-numeric() for(j in 1:length(selectpsmatrixq)){ if(selectpsmatrixq[j]==otrait_ind[1]){ pop_0<-matrix(-1,1,pop_col) }else{ pop_0<-matrix(0,1,pop_col) popnum_loc<-which(otrait_ind[]==selectpsmatrixq[j]) pop_0[1,popnum_loc-1]<-1 } pop_each<-rbind(pop_each,pop_0) } psmatrix=pop_each } } if(is.null(covmatrixRaw)){ phe<-phe }else{ nncovrow<-nrow(covmatrixRaw) covmatrixPre<-covmatrixRaw[3:nncovrow,] namecov<-as.matrix(covmatrixPre[,1]) sameGencov<-intersect(sameName,namecov) loccov<-match(sameGencov,namecov) selectcovmatrixq<-covmatrixPre[loccov,-1] covname<-covmatrixRaw[2,-1] label<-substr(covname,1,3) if(("Cat"%in%label)&&("Con"%in%label)){ cat_loc<-as.numeric(which(label=="Cat")) con_loc<-as.numeric(which(label=="Con")) selectcovmatrixqq<-selectcovmatrixq selectcovmatrixq<-selectcovmatrixq[,cat_loc] covnum<-t(selectcovmatrixq) yygg1<-numeric() for(i in 1:nrow(covnum)){ otrait_ind<-sort(unique(covnum[i,])) cov_col<-length(otrait_ind)-1 col_each<-numeric() for(j in 1:length(covnum[i,])){ if(covnum[i,j]==otrait_ind[length(otrait_ind)]){ cov_0<-matrix(-1,1,cov_col) }else{ cov_0<-matrix(0,1,cov_col) covnum_loc<-which(otrait_ind[]==covnum[i,j]) cov_0[1,covnum_loc]<-1 } col_each<-rbind(col_each,cov_0) } yygg1<-cbind(yygg1,col_each) } yygg1<-cbind(yygg1,as.matrix(selectcovmatrixqq[,con_loc])) }else if(all(label=="Cat")){ covnum<-t(selectcovmatrixq) yygg1<-numeric() for(i in 1:nrow(covnum)){ otrait_ind<-sort(unique(covnum[i,])) cov_col<-length(otrait_ind)-1 col_each<-numeric() for(j in 1:length(covnum[i,])){ if(covnum[i,j]==otrait_ind[length(otrait_ind)]){ cov_0<-matrix(-1,1,cov_col) }else{ cov_0<-matrix(0,1,cov_col) covnum_loc<-which(otrait_ind[]==covnum[i,j]) cov_0[1,covnum_loc]<-1 } col_each<-rbind(col_each,cov_0) } yygg1<-cbind(yygg1,col_each) } }else if(all(label=="Con")){ yygg1<-selectcovmatrixq } W.orig<-matrix(1,nrow(phe),1) xenvir<-cbind(W.orig,yygg1) xenvir<-apply(xenvir,2,as.numeric) beta<-solve(t(xenvir)%*%xenvir)%*%t(xenvir)%*%phe phe<-phe-xenvir%*%beta+W.orig } genRaw<-genRaw[,1:12] doresult<-list(gen=gen,phe=phe,outATCG=outATCG,genRaw=genRaw,kk=kk,psmatrix=psmatrix) return(doresult) } inputData<-function(readraw,Genformat=NULL,method=NULL,trait=NULL,PopStrType=NULL){ doMR<-NULL;doFME<-NULL if("mrMLM"%in%method){ doMR<-DoData(readraw$genRaw,Genformat,readraw$pheRaw1q,readraw$kkRaw,readraw$psmatrixRaw,readraw$covmatrixRaw,trait,type=2,PopStrType) } if("FASTmrMLM"%in%method){ doMR<-DoData(readraw$genRaw,Genformat,readraw$pheRaw1q,readraw$kkRaw,readraw$psmatrixRaw,readraw$covmatrixRaw,trait,type=2,PopStrType) } if("FASTmrEMMA"%in%method){ doFME<-DoData(readraw$genRaw,Genformat,readraw$pheRaw1q,readraw$kkRaw,readraw$psmatrixRaw,readraw$covmatrixRaw,trait,type=1,PopStrType) } if("pLARmEB"%in%method){ doMR<-DoData(readraw$genRaw,Genformat,readraw$pheRaw1q,readraw$kkRaw,readraw$psmatrixRaw,readraw$covmatrixRaw,trait,type=2,PopStrType) } if("pKWmEB"%in%method){ doMR<-DoData(readraw$genRaw,Genformat,readraw$pheRaw1q,readraw$kkRaw,readraw$psmatrixRaw,readraw$covmatrixRaw,trait,type=2,PopStrType) } if("ISIS EM-BLASSO"%in%method){ doMR<-DoData(readraw$genRaw,Genformat,readraw$pheRaw1q,readraw$kkRaw,readraw$psmatrixRaw,readraw$covmatrixRaw,trait,type=2,PopStrType) } output<-list(doMR=doMR,doFME=doFME) return(output) }
ramIndex<-function(input){ sptInput<-unlist(strsplit(input, "=")) value<-as.numeric(sptInput[2]) left<-sptInput[1] leftLength<-nchar(left) leftInd<-substr(left,7,leftLength-1) leftSplit<-unlist(strsplit(leftInd, ",")) ind1<-as.numeric(leftSplit[1]) ind2<-as.numeric(leftSplit[2]) c(ind1,ind2,value) } ramMatrix<-function(model){ if(length(model) == 0) { stop("ERROR: empty model syntax") } model <- unlist( strsplit(model, "\n") ) model <- gsub(" model <- gsub(";","\n", model) model <- unlist( strsplit(model, "\n") ) model <- gsub("[[:space:]]+", "", model) idx <- which(nzchar(model)) model <- model[idx] manifestInd<-grep('manifest', model) if (length(manifestInd)>1) warning('Multiple manifest keywords found and the first was used.') manifestLine<-model[manifestInd] manifestSplit<-unlist( strsplit(manifestLine, "=") ) manifest<-manifestSplit[2] latentInd<-grep('latent', model) if (length(latentInd)>0){ if (length(latentInd)>1) warning('Multiple latent keywords found and the first was used.') latentLine<-model[latentInd] latentSplit<-unlist( strsplit(latentLine, "=") ) latent<-latentSplit[2] }else{ latent<-0 } manifest<-as.numeric(manifest) latent<-as.numeric(latent) nrow<-manifest+latent A<-S<-matrix(0, nrow, nrow) arrowInd<-grep('arrow', model) arrowLine<-model[arrowInd] for (i in 1:length(arrowLine)){ temp<-ramIndex(arrowLine[i]) A[temp[1],temp[2]]<-temp[3] } slingInd<-grep('sling', model) slingLine<-model[slingInd] for (i in 1:length(slingLine)){ temp<-ramIndex(slingLine[i]) S[temp[1],temp[2]]<-temp[3] S[temp[2],temp[1]]<-temp[3] } F<-diag(manifest) if (latent>0) FLatent<-matrix(0,manifest,latent) F<-cbind(F,FLatent) labelInd<-grep('label', model) varname<-character(0) if (length(labelInd)>0){ varnameLine<-model[labelInd] varname<-substr(varnameLine,7,nchar(varnameLine)) varname<-unlist(strsplit(varname,",")) } if (length(varname)!=nrow){ if (length(varname)>0){ warning('The provided number of varible labels is not equal to the total number of variables. Default variables names will be used') } varname<-c(paste('V',1:manifest,sep=''),paste('F',1:latent,sep='')) } rownames(S)<-colnames(S)<-varname rownames(A)<-colnames(A)<-varname rownames(F)<-varname[1:manifest] colnames(F)<-varname cat("Matrix A\n") print(A) cat("Matrix S\n") print(S) cat("Matrix F\n") print(F) lname<-NULL if (nrow>manifest) lname=varname[(manifest+1):nrow] invisible(return(list(F=F, A=A, S=S, nvar=nrow, manifest=manifest,latent=latent,lname=lname,varname=varname))) } ramFlip<-function(input){ input<-unlist(strsplit(input,">")) n<-length(input) input<-input[n:1] paste(input[1:(n-1)], collapse="<") } ramRmOne<-function(input){ input<-unlist(strsplit(input,">")) n<-length(input) paste(input[2:n], collapse=">") } makePathList <- function(AMatrix, Ase, indirect=TRUE) { k <- 0 tIndex <- 1:10000 tFrom <- tTo <- tStartID <- tFromID <- tLength <- tValue <- rep(0, 10000) tPath <- rep(NULL,10000) tPathName<-tPathSig<-rep(NULL,10000) tNames<-rownames(AMatrix) if (is.null(tNames)) tNames<-1:nrow(AMatrix) for (i in 1:nrow(AMatrix)) { for (j in 1:ncol(AMatrix)) { if (AMatrix[i,j] != 0) { k <- k + 1 tFrom[k] <- j tTo[k] <- i tStartID[k] <- tIndex[k] tFromID[k] <- tIndex[k] tLength[k] <- 1 tValue[k] <- AMatrix[i,j] tPath[k]<-paste(j,' > ',i,sep='') tPathName[k]<-paste(tNames[j],' > ',tNames[i],sep='') if (!missing(Ase)){ if (Ase[i,j] != 0){ tPathSig[k]<-abs(AMatrix[i,j]/Ase[i,j]) } } } } } m<-k if (indirect){ t1 <- 0 maxLength <- 0 while (t1 != k) { t1 <- k maxLength <- maxLength + 1 tSelect1 <- tLength == 1 tSelect2 <- tLength == maxLength if (length(tIndex[tSelect1]) == 0 | length(tIndex[tSelect2]) == 0) break for (i in tIndex[tSelect2]) { for (j in tIndex[tSelect1]) { if (tTo[i] == tFrom[j]) { k <- k + 1 tFrom[k] <- tFrom[i] tTo[k] <- tTo[j] tStartID[k] <- tIndex[i] tFromID[k] <- tIndex[j] tLength[k] <- 1 + maxLength tValue[k] <- tValue[i] * tValue[j] tPath[k]<-paste(tPath[i],' > ',tTo[j],sep='') tPathName[k]<-paste(tPathName[i],' > ',tNames[tTo[j]],sep='') } } } } } return(list(index=tIndex[1:k], fromVar=tFrom[1:k], toVar=tTo[1:k], startID=tStartID[1:k], fromID=tFromID[1:k], length=tLength[1:k], value=tValue[1:k], tPath=tPath[1:k], tPathName=tPathName[1:k], nPath=m, tPathSig=tPathSig[1:m])) } makeSpanList <- function(SMatrix, Sse) { k <- 0 tIndex <- c(1:10000) tVarA <- tVarB <- tValue <- rep(0, 10000) tPath <- rep(NULL,10000) tPathName <- tPathSig <- tPathSE <- rep(NULL,10000) tNames<-rownames(SMatrix) if (is.null(tNames)) tNames<-1:nrow(SMatrix) for (i in 1:dim(SMatrix)[1]) { for (j in 1:dim(SMatrix)[2]) { if (SMatrix[i,j] != 0) { k <- k + 1 tVarA[k] <- j tVarB[k] <- i tValue[k] <- SMatrix[i,j] tPath[k]<-paste(j,' <> ',i,sep='') tPathName[k]<-paste(tNames[j],' <> ',tNames[i],sep='') if (!missing(Sse)){ tPathSE[k] <- Sse[i,j] if (tPathSE[k] != 0){ tPathSig[k]<-abs(tValue[k]/tPathSE[k]) } } } } } return(list(index=tIndex[1:k], varA=tVarA[1:k], varB=tVarB[1:k], value=tValue[1:k], tPath=tPath[1:k], tPathName=tPathName[1:k], tPathSig=tPathSig[1:k])) } makeBridgeList <- function(pathList, spanList) { k <- 0 tIndex <- c(1:10000) tVarA <- tVarB <- tSpanID <- tPath1ID <- tPath2ID <- tValue <- rep(0, 10000) tPath <- rep(NULL,10000) tPathName <- rep(NULL,10000) for (i in 1:length(spanList$index)) { k <- k + 1 tVarA[k] <- spanList$varA[i] tVarB[k] <- spanList$varB[i] tSpanID[k] <- spanList$index[i] tPath1ID[k] <- 0 tPath2ID[k] <- 0 tValue[k] <- spanList$value[i] tPath[k]<-spanList$tPath[k] tPathName[k]<-spanList$tPathName[k] } for (i in 1:length(spanList$index)) { for (j in 1:length(pathList$index)) { if (spanList$varA[i] == pathList$fromVar[j]) { k <- k + 1 tVarA[k] <- pathList$toVar[j] tVarB[k] <- spanList$varB[i] tSpanID[k] <- spanList$index[i] tPath1ID[k] <- pathList$index[j] tPath2ID[k] <- 0 tValue[k] <- spanList$value[i] * pathList$value[j] tPath[k]<-paste(ramFlip(pathList$tPath[j]), ' < ', tPath[i], sep='') tPathName[k]<-paste(ramFlip(pathList$tPathName[j]), ' < ', tPathName[i], sep='') } if (spanList$varB[i] == pathList$fromVar[j]) { k <- k + 1 tVarA[k] <- spanList$varB[i] tVarB[k] <- pathList$toVar[j] tSpanID[k] <- spanList$index[i] tPath1ID[k] <- 0 tPath2ID[k] <- pathList$index[j] tValue[k] <- spanList$value[i] * pathList$value[j] tPath[k]<-paste(ramFlip(pathList$tPath[j]), ' < ', tPath[i], sep='') tPathName[k]<-paste(ramFlip(pathList$tPathName[j]), ' < ', tPathName[i], sep='') } } } for (i in 1:length(spanList$index)) { for (j in 1:length(pathList$index)) { if (spanList$varA[i] == pathList$fromVar[j]) { for (h in 1:length(pathList$index)) { if (spanList$varB[i] == pathList$fromVar[h]) { k <- k + 1 tVarA[k] <- pathList$toVar[j] tVarB[k] <- pathList$toVar[h] tSpanID[k] <- spanList$index[i] tPath1ID[k] <- pathList$index[j] tPath2ID[k] <- pathList$index[h] tValue[k] <- spanList$value[i] * pathList$value[j] * pathList$value[h] tPath[k]<-paste(ramFlip(pathList$tPath[h]), " < ", tPath[i], substring(pathList$tPath[j],2), sep='') tPathName[k]<-paste(ramFlip(pathList$tPathName[h]), " < ", tPathName[i], ">", ramRmOne(pathList$tPathName[j]), sep='') } } } } } return(list(index=tIndex[1:k], varA=tVarA[1:k], varB=tVarB[1:k], spanID=tSpanID[1:k], path1ID=tPath1ID[1:k], path2ID=tPath2ID[1:k], value=tValue[1:k], path=tPath[1:k],pathName=tPathName[1:k], tPathSig=pathList$tPathSig, tSpanSig=spanList$tPathSig)) } ramPathBridge<-function(rammatrix, allbridge=FALSE, indirect=TRUE){ Amatrix<-rammatrix$A Smatrix<-rammatrix$S if (is.null(rammatrix$Ase)) { tPathlist <- makePathList(Amatrix,indirect=indirect) }else{ tPathlist <- makePathList(Amatrix,rammatrix$Ase,indirect=indirect) } if (is.null(rammatrix$Sse)) { tSpanlist <- makeSpanList(Smatrix) }else{ tSpanlist <- makeSpanList(Smatrix,rammatrix$Sse) } tBridgelist<-NULL if (allbridge) tBridgelist <- makeBridgeList(tPathlist, tSpanlist) ramobject<-list(path=tPathlist, bridge=tBridgelist, span=tSpanlist, ram=rammatrix) class(ramobject)<-'RAMpath' ramobject } plot.RAMpath <- function (x, file, from, to, type=c("path","bridge"), size = c(8, 8), node.font = c("Helvetica", 14), edge.font = c("Helvetica", 10), rank.direction = c("LR","TB"), digits = 2, output.type=c("graphics", "dot"), graphics.fmt="pdf", dot.options=NULL, ...) { pathbridge<-x if (length(type)>1) type<-type[1] tPathlist<-pathbridge$path tBridgelist<-pathbridge$bridge tSpanlist<-pathbridge$span rammatrix<-pathbridge$ram varname<-rammatrix$varname nvar<-length(varname) latent <- rammatrix$lname npath<-tPathlist$nPath nspan<-length(tSpanlist$index) pathValue<-round(tPathlist$value[1:npath],digits=digits) spanValue<-round(tSpanlist$value) tPathlist$value<-round(tPathlist$value,digits) tSpanlist$value<-round(tSpanlist$value,digits) if (!is.null(tBridgelist)) tBridgelist$value<-round(tBridgelist$value,digits) tPathSig<-pathbridge$path$tPathSig tSpanSig<-pathbridge$span$tPathSig tBridgelist$pathName <- gsub("[[:space:]]+", "", tBridgelist$pathName) tPathlist$tPathName <- gsub("[[:space:]]+", "", tPathlist$tPathName) output.type <- match.arg(output.type) if (missing(from)|missing(to)){ if (!missing(file)) { dot.file <- paste(file, ".dot", sep="") handle <- file(dot.file, "w") on.exit(close(handle)) if (output.type == "graphics") graph.file <- paste(file, ".", graphics.fmt, sep="") }else handle <- stdout() rank.direction <- match.arg(rank.direction) cat(file = handle, paste("digraph \"pathdiagram\" {\n", sep = "")) cat(file = handle, paste(" rankdir=", rank.direction, ";\n",sep = "")) cat(file = handle, paste(" size=\"", size[1], ",", size[2],"\";\n", sep = "")) cat(file = handle, paste(" node [fontname=\"", node.font[1], "\" fontsize=", node.font[2], " shape=box];\n", sep = "")) cat(file = handle, paste(" edge [fontname=\"", edge.font[1],"\" fontsize=", edge.font[2], "];\n", sep = "")) cat(file = handle, " center=1;\n") if (!is.null(latent)){ for (lat in latent) { cat(file = handle, paste(" \"", lat, "\" [shape=ellipse]\n",sep = "")) } } if (max(abs(rammatrix$M))>0){ cat(file = handle, paste(" \"1\" [shape=triangle]\n",sep = "")) cat(file = handle, paste(" \"1\" -> \"1\" [label=\"1\" dir=both]\n",sep = "")) } for (i in 1:npath){ sig<-'' if (!is.null(tPathSig)){ if (!is.na(tPathSig[i])){ if (tPathSig[i]>1.96) sig<-'*' } } cat(file = handle, paste(" \"", varname[tPathlist$fromVar[i]], "\" -> \"", varname[tPathlist$toVar[i]], "\" [label=\"",tPathlist$value[i], sig, "\"];\n", sep = "")) } if (max(abs(rammatrix$M))>0){ Mpath<-which(abs(rammatrix$M)>0) for (i in Mpath){ sig<-'' if (rammatrix$Mse[i]!=0){ temp<-rammatrix$M[i]/rammatrix$Mse[i] if (abs(temp)>1.96) sig<-'*' } cat(file = handle, paste(" \"1\" -> \"", rownames(rammatrix$M)[i], "\" [label=\"",round(rammatrix$M[i],digits=digits), sig, "\"];\n", sep = "")) } } for (i in 1:nspan){ sig<-'' if (!is.null(tSpanSig)){ if (!is.na(tSpanSig[i])){ if (tSpanSig[i]>1.96) sig<-'*' } } if (tSpanlist$varA[i] >= tSpanlist$varB[i]) cat(file = handle, paste(" \"", varname[tSpanlist$varA[i]], "\" -> \"", varname[tSpanlist$varB[i]], "\" [label=\"", tSpanlist$value[i], sig, "\" dir=both];\n", sep = "")) } cat(file = handle, "}\n") if (output.type == "graphics" && !missing(file)){ cmd <- paste("dot -T", graphics.fmt, " -o ", graph.file, " ", dot.options, " ", dot.file, sep="") cat("Running ", cmd, "\n") result <- try(system(cmd)) } }else{ if (!is.numeric(from)){ varA<-which(varname==from) }else varA<-from if (!is.numeric(to)){ varB<-which(varname==to) } else varB<-to if (length(varA)==0|varA>nvar|varA<0) stop("The from variable does not exist") if (length(varB)==0|varB>nvar|varB<0) stop("The to variable does not exist") if (type=="path"){ index<-which(tPathlist$fromVar==varA & tPathlist$toVar==varB) if (length(index)==0) stop('No such path exists') for (j in 1:length(index)){ if (!missing(file)) { dot.file <- paste(file, j, ".dot", sep="") handle <- file(dot.file, "w") on.exit(close(handle)) if (output.type == "graphics") graph.file <- paste(file, j, ".", graphics.fmt, sep="") }else handle <- stdout() rank.direction <- match.arg(rank.direction) cat(file = handle, paste("strict digraph \"pathdiagram\" {\n", sep = "")) cat(file = handle, paste(" rankdir=", rank.direction, ";\n",sep = "")) cat(file = handle, paste(" size=\"", size[1], ",", size[2],"\";\n", sep = "")) cat(file = handle, paste(" node [fontname=\"", node.font[1], "\" fontsize=", node.font[2], " shape=box style=dashed];\n", sep = "")) cat(file = handle, paste(" edge [fontname=\"", edge.font[1],"\" fontsize=", edge.font[2], " style=dashed];\n", sep = "")) cat(file = handle, " center=1;\n") sPath<-tPathlist$tPathName[index[j]] sPathInd<-unlist(strsplit(sPath,">")) nPathToPlot<-length(sPathInd) for (k in 1:nPathToPlot){ if (sPathInd[k] %in% latent){ cat(file = handle, paste(" \"", sPathInd[k], "\" [shape=ellipse style=solid];\n",sep = "")) }else{ cat(file = handle, paste(" \"", sPathInd[k], "\" [style=solid];\n",sep = "")) } } for (k in 1:(nPathToPlot-1)){ value<- pathValue[(tPathlist$fromVar[1:npath]==which(sPathInd[k]==varname) ) & (tPathlist$toVar[1:npath]==which(sPathInd[k+1]==varname))] cat(file = handle, paste(" \"", sPathInd[k], "\" -> \"", sPathInd[k+1], "\" [label=\"", value, "\" style=solid];\n", sep = "")) } if (!is.null(latent)){ for (lat in latent) { cat(file = handle, paste(" \"", lat, "\" [shape=ellipse];\n",sep = "")) } } for (i in 1:npath){ cat(file = handle, paste(" \"", varname[tPathlist$fromVar[i]], "\" -> \"", varname[tPathlist$toVar[i]], "\" [label=\"",tPathlist$value[i], "\"];\n", sep = "")) } for (i in 1:nspan){ if (tSpanlist$varA[i] >= tSpanlist$varB[i]) cat(file = handle, paste(" \"", varname[tSpanlist$varA[i]], "\" -> \"", varname[tSpanlist$varB[i]], "\" [label=\"", tSpanlist$value[i], "\" dir=both];\n", sep = "")) } cat(file = handle, "label=\"Effect ",tPathlist$tPathName[index[j]],"=",tPathlist$value[index[j]] ,"\";\n labelloc = \"top\";\n") cat(file = handle, "}\n") if (output.type == "graphics" && !missing(file)){ cmd <- paste("dot -T", graphics.fmt, " -o ", graph.file, " ", dot.options, " ", dot.file, sep="") cat("Running ", cmd, "\n") result <- try(system(cmd)) } } } if (type=="bridge"){ index<-which(tBridgelist$varA==varA & tBridgelist$varB==varB) for (j in 1:length(index)){ if (!missing(file)) { dot.file <- paste(file, j, ".dot", sep="") handle <- file(dot.file, "w") on.exit(close(handle)) if (output.type == "graphics") graph.file <- paste(file, j, ".", graphics.fmt, sep="") }else handle <- stdout() rank.direction <- match.arg(rank.direction) cat(file = handle, paste("strict digraph \"pathdiagram\" {\n", sep = "")) cat(file = handle, paste(" rankdir=", rank.direction, ";\n",sep = "")) cat(file = handle, paste(" size=\"", size[1], ",", size[2],"\";\n", sep = "")) cat(file = handle, paste(" node [fontname=\"", node.font[1], "\" fontsize=", node.font[2], " shape=box style=dashed];\n", sep = "")) cat(file = handle, paste(" edge [fontname=\"", edge.font[1],"\" fontsize=", edge.font[2], " style=dashed];\n", sep = "")) cat(file = handle, " center=1;\n") sPath<-tBridgelist$pathName[index[j]] sBridge<-unlist(strsplit(sPath,"<>")) sLeft<-unlist(strsplit(sBridge[1],"<")) sRight<-unlist(strsplit(sBridge[2],">")) sPathName<-unique(c(sLeft,sRight)) nPathToPlot<-length(sPathName) for (k in 1:nPathToPlot){ if (sPathName[k] %in% latent){ cat(file = handle, paste(" \"", sPathName[k], "\" [shape=ellipse style=solid];\n",sep = "")) }else{ cat(file = handle, paste(" \"", sPathName[k], "\" [style=solid];\n",sep = "")) } } nLeft<-length(sLeft) if (nLeft>1){ for (k in 1:(nLeft-1)){ value<- pathValue[(tPathlist$fromVar[1:npath]==which(sLeft[k+1]==varname) ) & (tPathlist$toVar[1:npath]==which(sLeft[k]==varname))] cat(file = handle, paste(" \"", sLeft[k+1], "\" -> \"", sLeft[k], "\" [label=\"", value, "\" style=solid];\n", sep = "")) } } nRight<-length(sRight) if (nRight>1){ for (k in 1:(nRight-1)){ value<- pathValue[(tPathlist$fromVar[1:npath]==which(sRight[k]==varname) ) & (tPathlist$toVar[1:npath]==which(sRight[k+1]==varname))] cat(file = handle, paste(" \"", sRight[k], "\" -> \"", sRight[k+1], "\" [label=\"", value, "\" style=solid];\n", sep = "")) } } value<- spanValue[(tSpanlist$varA==which(sLeft[nLeft]==varname) ) & (tSpanlist$varB==which(sRight[1]==varname))] cat(file = handle, paste(" \"", sLeft[nLeft], "\" -> \"", sRight[1], "\" [label=\"", value, "\" style=solid dir=both];\n", sep = "")) if (!is.null(latent)){ for (lat in latent) { cat(file = handle, paste(" \"", lat, "\" [shape=ellipse];\n",sep = "")) } } for (i in 1:npath){ cat(file = handle, paste(" \"", varname[tPathlist$fromVar[i]], "\" -> \"", varname[tPathlist$toVar[i]], "\" [label=\"",tPathlist$value[i], "\"];\n", sep = "")) } for (i in 1:nspan){ if (!(tSpanlist$varA[i]==which(sLeft[nLeft]==varname) & tSpanlist$varB[i]==which(sRight[1]==varname)) & !(tSpanlist$varB[i]==which(sLeft[nLeft]==varname) & tSpanlist$varA[i]==which(sRight[1]==varname))){ if (tSpanlist$varA[i] >= tSpanlist$varB[i]) cat(file = handle, paste(" \"", varname[tSpanlist$varA[i]], "\" -> \"", varname[tSpanlist$varB[i]], "\" [label=\"", tSpanlist$value[i], "\" dir=both];\n", sep = "")) } } cat(file = handle, "label=\"Bridge ",tBridgelist$pathName[index[j]],"=",tBridgelist$value[index[j]] ,"\";\n labelloc = \"top\";\n") cat(file = handle, "}\n") if (output.type == "graphics" && !missing(file)){ cmd <- paste("dot -T", graphics.fmt, " -o ", graph.file, " ", dot.options, " ", dot.file, sep="") cat("Running ", cmd, "\n") result <- try(system(cmd)) } } } } invisible(NULL) } ramUniquePath<-function(tPathlist){ tUniquePath<-cbind(tPathlist$fromVar, tPathlist$toVar) name<-tPathlist$tPathName[1] k<-1 for (i in 2:length(tPathlist$index)){ check<-cbind(tUniquePath[1:(i-1), 1]==tPathlist$fromVar[i], tUniquePath[1:(i-1), 2]==tPathlist$toVar[i]) maxT<-max(apply(check,1,sum)) if (maxT<2){ k<-k+1 tUniquePath[k,]<-c(tPathlist$fromVar[i], tPathlist$toVar[i]) name<-c(name, tPathlist$tPathName[i]) } } return(list(tUniquePath=tUniquePath[1:k, ], tUniqueName=name)) } summary.RAMpath<-function(object, from, to, type=c("path","bridge"), se=FALSE, ...){ pathbridge<-object if (length(type)>1) type<-type[1] tPathlist<-pathbridge$path tBridgelist<-pathbridge$bridge tSpanlist<-pathbridge$span rammatrix<-pathbridge$ram varname<-rammatrix$varname nvar<-length(varname) if (missing(from)|missing(to)){ if (type=="path"){ tUniquePath<-ramUniquePath(tPathlist) npath<-length(tUniquePath$tUniqueName) cat('Path and its decomposions:\n\n') nString<-max(nchar(tPathlist$tPathName)) txt<-sprintf(paste("%-",nString+8,"s %4s %12s %9s\n",sep=""), "Path Name", "", "Value", "Pecent") if (se) txt<-sprintf(paste("%-",nString+8,"s %4s %12s %12s %9s\n",sep=""), "Path Name", "", "Value", "se", "Pecent") cat(txt) for (i in 1:npath){ index<-which(tPathlist$fromVar==tUniquePath$tUniquePath[i,1] & tPathlist$toVar==tUniquePath$tUniquePath[i,2]) if (length(index)>0){ name<-paste(varname[tUniquePath$tUniquePath[i,1]]," > ",varname[tUniquePath$tUniquePath[i,2]],sep="") path<-length(index) value<-sum(tPathlist$value[index]) percent<-100 txt<-sprintf(paste("%-",nString+8,"s %4.0f %12.3f %9.2f\n",sep=""), name, path, value, percent) if (se) txt<-sprintf(paste("%-",nString+8,"s %4.0f %12.3f %12s %9.2f\n",sep=""), name, path, value, " ", percent) cat(txt) for (j in 1:length(index)){ name<-tPathlist$tPathName[index[j]] path<-j value.j<-tPathlist$value[index[j]] percent.j<-value.j/value*100 if (se){ se.j<-ramEffectSE(object, name) txt<-sprintf(paste(" %-",nString+6,"s %4.0f %12.3f %12.3f %9.2f\n",sep=""), name, path, value.j, se.j, percent.j) }else{ txt<-sprintf(paste(" %-",nString+6,"s %4.0f %12.3f %9.2f\n",sep=""), name, path, value.j, percent.j) } cat(txt) } } } } if (type=="bridge"){ nString<-max(nchar(tBridgelist$pathName)) cat('Covariance and its bridges:\n\n') txt<-sprintf(paste("%-",nString+8,"s %4s %12s %9s\n",sep=""), "Path Name", "", "Value", "Percent") cat(txt) for (i in 1:nvar){ for (k in 1:i){ index<-which(tBridgelist$varA==i & tBridgelist$varB==k) if (length(index)>0){ name<-paste(varname[i]," <> ",varname[k],sep='') path<-length(index) value<-sum(tBridgelist$value[index]) percent<-100 txt<-sprintf(paste("%-",nString+8,"s %4.0f %12.3f %9.2f\n",sep=""), name, path, value, percent) cat(txt) for (j in 1:length(index)){ name<-tBridgelist$pathName[index[j]] path<-j value.j<-tBridgelist$value[index[j]] percent.j<-value.j/value*100 txt<-sprintf(paste(" %-",nString+6,"s %4.0f %12.3f %9.2f\n",sep=""), name, path, value.j, percent.j) cat(txt) } }else{ name<-paste(varname[i],"<>",varname[k],sep='') path<-0 value<-NA percent<-NA txt<-sprintf(paste("%-",nString+8,"s %4.0f %12.3f %9.2f\n",sep=""), name, path, value, percent) cat(txt) } } } } }else{ if (!is.numeric(from)){ varA<-which(varname==from) }else varA<-from if (!is.numeric(to)){ varB<-which(varname==to) } else varB<-to if (length(varA)==0|varA>nvar|varA<0) stop("The from variable does not exist") if (length(varB)==0|varB>nvar|varB<0) stop("The to variable does not exist") if (type=="path"){ cat('Path and its decomposions:\n\n') nString<-max(nchar(tPathlist$tPathName)) txt<-sprintf(paste("%-",nString+8,"s %3s %12s %9s\n",sep=""), "Path Name", "", "Value", "Percent") cat(txt) index<-which(tPathlist$fromVar==varA & tPathlist$toVar==varB) if (length(index)==0) stop(paste("No such path from ",varname[varA]," to ",varname[varB], sep="")) if (length(index)>0){ name<-paste(varname[varA]," > ", varname[varB],sep="") path<-length(index) value<-sum(tPathlist$value[index]) percent<-100 txt<-sprintf(paste("%-",nString+8,"s %3.0f %12.3f %9.2f\n",sep=""), name, path, value, percent) cat(txt) for (j in 1:length(index)){ name<-tPathlist$tPathName[index[j]] path<-j value.j<-tPathlist$value[index[j]] percent.j<-value.j/value*100 txt<-sprintf(paste(" %-",nString+6,"s %3.0f %12.3f %9.2f\n",sep=""), name, path, value.j, percent.j) cat(txt) } } } if (type=="bridge"){ nString<-max(nchar(tBridgelist$pathName)) cat("Covariance and its bridges:\n\n") txt<-sprintf(paste("%-",nString+8,"s %3s %12s %9s\n",sep=""), "Path Name", "", "Value", "Percent") cat(txt) index<-which(tBridgelist$varA==varA & tBridgelist$varB==varB) if (length(index)==0) stop(paste("No covariance between ", varname[varA], " and ", varname[varB], sep="")) if (length(index)>0){ name<-paste(varname[varA]," <> ",varname[varB],sep='') path<-length(index) value<-sum(tBridgelist$value[index]) percent<-100 txt<-sprintf(paste("%-",nString+8,"s %3.0f %12.3f %9.2f\n",sep=""), name, path, value, percent) cat(txt) for (j in 1:length(index)){ name<-tBridgelist$pathName[index[j]] path<-j value.j<-tBridgelist$value[index[j]] percent.j<-value.j/value*100 txt<-sprintf(paste(" %-",nString+6,"s %3.0f %12.3f %9.2f\n",sep=""), name, path, value.j, percent.j) cat(txt) } } } } } isNumeric <- function(constant){ save <- options(warn = -1) on.exit(save) !(is.na(as.numeric(constant))) } ramParseLavaan<-function(input, manifest, type=0){ sptInput<-unlist(strsplit(input, "=")) sLeft<-sptInput[1] sRight<-sptInput[2] sLeft1<-unlist(strsplit(sLeft, "(", fixed=TRUE)) sLeft2<-unlist(strsplit(sLeft1[2], ")", fixed=TRUE)) leftSplit<-unlist(strsplit(sLeft2, ",")) toVar<-as.numeric(leftSplit[1]) fromVar<-as.numeric(leftSplit[2]) findAt<-grep("@", sRight) if (length(findAt)>0){ fixed<-0 if (nchar(sRight)==1){ fixedAt<-1 label<-NA }else{ splitRight<-unlist(strsplit(sRight, "@", fixed=TRUE)) if (length(splitRight)==1){ label<-splitRight[1] fixedAt<-1 }else{ if (splitRight[1]==""){ label<-NA fixedAt<-as.numeric(splitRight[2]) }else{ label<-splitRight[1] fixedAt<-as.numeric(splitRight[2]) } } } }else{ findQM<-grep("?", sRight, fixed=TRUE) if (length(findQM>0)){ fixed<-1 if (nchar(sRight)==1){ fixedAt<-NA label<-NA }else{ splitRight<-unlist(strsplit(sRight, "?", fixed=TRUE)) if (length(splitRight)==1){ label<-splitRight[1] fixedAt<-NA }else{ if (splitRight[1]==""){ label<-NA fixedAt<-as.numeric(splitRight[2]) }else{ label<-splitRight[1] fixedAt<-as.numeric(splitRight[2]) } } } }else{ if (isNumeric(sRight)){ fixed<-1 label<-NA fixedAt<-as.numeric(sRight) }else{ fixed<-1 label<-sRight fixedAt<-NA } } } if (type==0){ if (toVar<=manifest & fromVar>manifest){arrowType<-2}else{arrowType<-1} }else{ arrowType<-3 } list(ramValue=c(fromVar, toVar, arrowType, fixed, fixedAt), ramLabel=label) } ram2lavaan<-function(model){ if(length(model) == 0) { stop("ERROR: empty model syntax") } model <- unlist( strsplit(model, "\n") ) model <- gsub(" model <- gsub(";","\n", model) model <- unlist( strsplit(model, "\n") ) model <- gsub("[[:space:]]+", "", model) idx <- which(nzchar(model)) model <- model[idx] manifestInd<-grep('manifest', model) if (length(manifestInd)>1) warning('Multiple manifest keywords found and the first was used.') manifestLine<-model[manifestInd] manifestSplit<-unlist( strsplit(manifestLine, "=") ) manifest<-manifestSplit[2] latentInd<-grep('latent', model) if (length(latentInd)>0){ if (length(latentInd)>1) warning('Multiple latent keywords found and the first was used.') latentLine<-model[latentInd] latentSplit<-unlist( strsplit(latentLine, "=") ) latent<-latentSplit[2] }else{ latent<-0 } manifest<-as.numeric(manifest) latent<-as.numeric(latent) nrow<-manifest+latent ramMatrix<-NULL ramLabel<-NULL arrowInd<-grep('arrow', model) arrowLine<-model[arrowInd] for (i in 1:length(arrowLine)){ temp<-ramParseLavaan(arrowLine[i], manifest, 0) ramMatrix<-rbind(ramMatrix, temp$ramValue) ramLabel<-c(ramLabel, temp$ramLabel) } slingInd<-grep('sling', model) slingLine<-model[slingInd] for (i in 1:length(slingLine)){ temp<-ramParseLavaan(slingLine[i], manifest, 1) ramMatrix<-rbind(ramMatrix, temp$ramValue) ramLabel<-c(ramLabel, temp$ramLabel) } labelInd<-grep('label', model) varname<-character(0) if (length(labelInd)>0){ varnameLine<-model[labelInd] varname<-substr(varnameLine,7,nchar(varnameLine)) varname<-unlist(strsplit(varname,",")) } if (length(varname)!=nrow){ if (length(varname)>0){ warning('The provided number of varible labels is not equal to the total number of variables. Default variables names will be used') } varname<-c(paste('V',1:manifest,sep=''),paste('F',1:latent,sep='')) } nEq<-nrow(ramMatrix) lavaanModel<-NULL for (i in 1:nEq){ arrowType<-"~" if (ramMatrix[i,3]==2) arrowType="=~" if (ramMatrix[i,3]==3) arrowType="~~" if (ramMatrix[i,4]==1){ if (is.na(ramMatrix[i,5]) & is.na(ramLabel[i])) preLabel<-NULL if (is.na(ramMatrix[i,5]) & !is.na(ramLabel[i])) preLabel<-paste(ramLabel[i], "*", sep="") if (!is.na(ramMatrix[i,5]) & is.na(ramLabel[i])) preLabel<-paste("start(",ramMatrix[i,5],")", "*", sep="") if (!is.na(ramMatrix[i,5]) & !is.na(ramLabel[i])) { multMod<-varname[ramMatrix[i,1]] if (ramMatrix[i,3]==2) {multMod<-varname[ramMatrix[i,2]]} preLabel<-paste(ramLabel[i], "*",multMod,"+start(",ramMatrix[i,5],")", "*", sep="") } }else{ preLabel<-paste(ramMatrix[i,5],"*",sep="") } temp<-paste(varname[ramMatrix[i,2]], arrowType, preLabel, varname[ramMatrix[i,1]], "\n", sep="") if (ramMatrix[i,3]==2) temp<-paste(varname[ramMatrix[i,1]], arrowType, preLabel, varname[ramMatrix[i,2]], "\n", sep="") lavaanModel<-paste(lavaanModel, temp) } return(lavaanModel) } ramFit<-function(ramModel, data, type=c('ram','lavaan'), digits=3, zero.print="0", ...){ if (missing(type)) type = 'ram' if (type=='ram') { lavaanModel<-ram2lavaan(ramModel) }else{ lavaanModel<-ramModel } fitModel<-lavaan(model= lavaanModel, data=data, fixed.x=FALSE, warn=FALSE, ...) parTable<-fitModel@ParTable parEst<-fitModel@Fit@est parSE<-fitModel@Fit@se fitInd<-fitMeasures(fitModel) varALL<-unique(c(parTable$rhs, parTable$lhs)) varData<-names(data) obsVar<-latVar<-NULL for (i in 1:length(varALL)){ if (varALL[i] %in% varData){ obsVar<-c(obsVar, varALL[i]) }else{ latVar<-c(latVar, varALL[i]) } } varName<-c(obsVar, latVar) manifest<-length(obsVar) latent<-length(latVar) nrow<-length(varName) A<-S<-Ase<-Sse<-matrix(0,nrow,nrow,dimnames=list(varName, varName)) M<-Mse<-matrix(0,nrow,1,dimnames=list(varName, 'M')) for (j in parTable$id){ if (parTable$op[j]=="~"){ A[parTable$lhs[j], parTable$rhs[j]]<-parEst[j] Ase[parTable$lhs[j], parTable$rhs[j]]<-parSE[j] } if (parTable$op[j]=="=~"){ A[parTable$rhs[j], parTable$lhs[j]]<-parEst[j] Ase[parTable$rhs[j], parTable$lhs[j]]<-parSE[j] } if (parTable$op[j]=="~~"){ S[parTable$lhs[j], parTable$rhs[j]]<-parEst[j] Sse[parTable$lhs[j], parTable$rhs[j]]<-parSE[j] S[parTable$rhs[j], parTable$lhs[j]]<-parEst[j] Sse[parTable$rhs[j], parTable$lhs[j]]<-parSE[j] } } A.na<-A A.na[A==0]<-NA S.na<-S S.na[S==0]<-NA Ase.na<-Ase Ase.na[Ase==0]<-NA Sse.na<-Sse Sse.na[Sse==0]<-NA cat("\n--------------------\n") cat("Parameter estimates:\n") cat("--------------------\n") cat("\nMatrix A\n\n") print(A.na, digits=digits,na.print = zero.print) cat("\nMatrix S\n\n") print(S.na,digits=digits,na.print = zero.print) cat("\n----------------------------------------\n") cat("Standard errors for parameter estimates:\n") cat("----------------------------------------\n") cat("\nMatrix A\n\n") print(Ase.na,digits=digits,na.print = zero.print) cat("\nMatrix S\n\n") print(Sse.na,digits=digits,na.print = zero.print) lname<-NULL if (nrow>manifest) lname=varName[(manifest+1):nrow] invisible((list(A=A, S=S, Ase=Ase, Sse=Sse, M=M, Mse=Mse, fit=fitInd, lavaan=fitModel, nvar=nrow, manifest=manifest,latent=latent,lname=lname,varname=varName, model=lavaanModel, data=data))) }
.sigsQcNegativeControl <- function(genesList, expressionMatrixList, outputDir, studyName, numResampling=50, warningsFile, logFile){ if(missing(genesList)){ stop("Need to specify a list of genes. The IDs must match those in the expression matrices.") } if(missing(expressionMatrixList)){ stop("Neet to specify a list of expression matrices where the rows represent the genes and the columns the samples.") } if(missing(outputDir)){ stop("Need to specify an output directory") } if(missing(studyName)){ studyName = "MyStudy" } if(missing(warningsFile)){ warningsFile = file.path(outputDir, "warnings.log") } if(missing(logFile)){ logFile = file.path(outputDir, "log.log") } tryCatch({ re.power = numResampling; if(!dir.exists(outputDir)){ dir.create(path=outputDir, showWarnings = F, recursive = T) } log.con = file(logFile, open = "a") warnings.con = file(warningsFile, open = "a") for(genes.i in 1:length(genesList)){ genes = as.matrix(genesList[[genes.i]]) colnames(genes) = names(genesList)[genes.i] .sigQcNegativeControl(genes, expressionMatrixList, outputDir, studyName, rePower=numResampling, warningsFile, logFile); } }, error = function(err) { cat("", file=log.con, sep="\n") cat(paste(Sys.time(),"Errors occurred during in sigQcNegativeControl:", err, sep=" "), file=log.con, sep="\n") }, finally = { close(log.con) close(warnings.con) }) } .sigQcNegativeControl <- function(genes, expressionMatrixList, outputDir, studyName, rePower=50, warningsFile, logFile){ if(missing(genes)){ stop("Need to specify a list of genes. The IDs must match those in the expression matrices.") } if(missing(expressionMatrixList)){ stop("Neet to specify a list of expression matrices where the rows represent the genes and the columns the samples.") } if(missing(outputDir)){ stop("Need to specify an output directory") } if(missing(studyName)){ studyName = "MyStudy" } if(missing(warningsFile)){ warningsFile = file.path(outputDir, "warnings.log") } if(missing(logFile)){ logFile = file.path(outputDir, "log.log") } tryCatch({ re.power = rePower; if(!dir.exists(outputDir)){ dir.create(path=outputDir, showWarnings = F, recursive = T) } log.con = file(logFile, open = "a") warnings.con = file(warningsFile, open = "a") len = dim(genes)[1] datasets.num = length(expressionMatrixList) datasets.names = names(expressionMatrixList) for(dataset.i in 1:datasets.num){ expressionMatrix = expressionMatrixList[[dataset.i]] if(is.null(datasets.names)) datasetName = paste0("Dataset",dataset.i) else datasetName = datasets.names[dataset.i] data.matrix.ncols = dim(expressionMatrix)[2] data.matrix.nrows = dim(expressionMatrix)[1] gene_sigs_list = list() signatureName = colnames(genes) for(i in 1:re.power){ random.index.vector = stats::runif(min=1, max=data.matrix.nrows, n=len); random.genes = as.matrix(rownames(expressionMatrix)[random.index.vector]); gene_sigs_list[[paste0("NC",i)]] = random.genes; } names_sigs = names(gene_sigs_list) cat(paste(Sys.time(), "Computing the Negative Control...", sep=" "), file=log.con, sep="") mRNA_expr_matrix = list() names = c(datasetName) mRNA_expr_matrix[[datasetName]] = expressionMatrix sigQC.out_dir = file.path(outputDir, "negative_control", datasetName, signatureName, "sigQC") dir.create(path = sigQC.out_dir, showWarnings = FALSE, recursive = T) .compute_without_plots(names_datasets = names, gene_sigs_list = gene_sigs_list, names_sigs = names_sigs, mRNA_expr_matrix = mRNA_expr_matrix, out_dir = sigQC.out_dir ) cat("DONE", file=log.con, sep="\n") metrics.file.path = file.path(sigQC.out_dir, "radarchart_table", "radarchart_table.txt") metrics.table = utils::read.table(file = metrics.file.path, header = T, sep = "\t", check.names = F, row.names = 1) neg.controls.summary = matrix(nrow = 6, ncol = dim(metrics.table)[2]) colnames(neg.controls.summary) = colnames(metrics.table) rownames(neg.controls.summary) = c("mean", "Q0.025", "Q0.25", "Q0.5", "Q0.75", "Q0.975") neg.controls.summary[1,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){mean(t, na.rm=T)}) neg.controls.summary[2,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){stats::quantile(t, na.rm=T, probs=c(0.025))}) neg.controls.summary[3,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){stats::quantile(t, na.rm=T, probs=c(0.25))}) neg.controls.summary[4,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){stats::quantile(t, na.rm=T, probs=c(0.5))}) neg.controls.summary[5,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){stats::quantile(t, na.rm=T, probs=c(0.75))}) neg.controls.summary[6,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){stats::quantile(t, na.rm=T, probs=c(0.975))}) stripchartMatrixList=list() stripchartMatrixList[["Negative Control"]]=metrics.table sigQC.out_dir = outputDir sig.metrics.file.path = file.path(outputDir, "radarchart_table", "radarchart_table.txt") if(file.exists(sig.metrics.file.path)){ sig.metrics.table = utils::read.table(file = sig.metrics.file.path, header = T, sep = "\t", check.names = F, row.names = 1) index = which(rownames(sig.metrics.table) == paste0(gsub(' ','.', datasetName),'_',gsub(' ','.', signatureName))) sig.metrics.table = sig.metrics.table[index,,drop=F] stripchartMatrixList[["Original Metric Value"]]=sig.metrics.table } sigQC.out_dir = file.path(outputDir, "negative_control", datasetName, signatureName) stripchart_group_names <- c('Relative Med. SD','Skewness',expression(sigma["" >= "10%" ]),expression(sigma["" >= "25%" ]),expression(sigma["" >= "50%" ]),'Coef. of Var.', 'Non-NA Prop.','Prop. Expressed', 'Autocor.',expression(rho["Mean,Med" ]), expression(rho["PCA1,Med" ]),expression(rho["Mean,PCA1" ]), expression(sigma["PCA1" ]), expression(rho["Med,Z-Med" ])) .boxplot.matrix2(x=neg.controls.summary[2:6,], outputDir=sigQC.out_dir, plotName="boxplot_metrics", plotTitle=paste("Boxplot Negative Controls for",signatureName,sep=" "), stripchartMatrixList=stripchartMatrixList, stripchartPch=c(1, 21), stripchartCol = c("gray", "red"), xlab ="Metrics", ylab="Score",group.names=stripchart_group_names) summary.filePath = file.path(sigQC.out_dir, "neg_controls_summary_table.txt") utils::write.table(x = neg.controls.summary,file = summary.filePath,row.names = TRUE, col.names = TRUE,sep=",") } for(dataset.i in 1:datasets.num){ if(is.null(datasets.names)) datasetName = paste0("Dataset",dataset.i) else datasetName = datasets.names[dataset.i] expressionMatrix = expressionMatrixList[[dataset.i]] signatureName = colnames(genes) expressionMatrix_perm_list <- list() for(i in 1:re.power){ expressionMatrix_perm <- expressionMatrix genes_present <- intersect(rownames(expressionMatrix),genes[,1]) new_ordering <- replicate(sample(1:length(genes_present)),n=dim(expressionMatrix)[2]) for(col.num in 1:dim(expressionMatrix)[2]){ expressionMatrix_perm[genes_present,col.num] <- expressionMatrix[genes_present[new_ordering[,col.num]],col.num] } expressionMatrix_perm_list[[paste0("PC",i)]] <- expressionMatrix_perm } sigQC.out_dir = file.path(outputDir, "permutation_control", datasetName, signatureName, "sigQC") dir.create(path = sigQC.out_dir, showWarnings = FALSE, recursive = T) gene_sigs_list <- list() gene_sigs_list[[colnames(genes)]] <- genes .compute_without_plots(names_datasets = names(expressionMatrix_perm_list), gene_sigs_list = gene_sigs_list, names_sigs = names(gene_sigs_list), mRNA_expr_matrix = expressionMatrix_perm_list, out_dir = sigQC.out_dir ) cat("DONE", file=log.con, sep="\n") metrics.file.path = file.path(sigQC.out_dir, "radarchart_table", "radarchart_table.txt") metrics.table = utils::read.table(file = metrics.file.path, header = T, sep = "\t", check.names = F, row.names = 1) neg.controls.summary = matrix(nrow = 6, ncol = dim(metrics.table)[2]) colnames(neg.controls.summary) = colnames(metrics.table) rownames(neg.controls.summary) = c("mean", "Q0.025", "Q0.25", "Q0.5", "Q0.75", "Q0.975") neg.controls.summary[1,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){mean(t, na.rm=T)}) neg.controls.summary[2,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){stats::quantile(t, na.rm=T, probs=c(0.025))}) neg.controls.summary[3,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){stats::quantile(t, na.rm=T, probs=c(0.25))}) neg.controls.summary[4,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){stats::quantile(t, na.rm=T, probs=c(0.5))}) neg.controls.summary[5,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){stats::quantile(t, na.rm=T, probs=c(0.75))}) neg.controls.summary[6,] = apply(X=metrics.table,MARGIN = 2,FUN = function(t){stats::quantile(t, na.rm=T, probs=c(0.975))}) stripchartMatrixList=list() stripchartMatrixList[["Permutation Control"]]=metrics.table sigQC.out_dir = outputDir sig.metrics.file.path = file.path(outputDir, "radarchart_table", "radarchart_table.txt") if(file.exists(sig.metrics.file.path)){ sig.metrics.table = utils::read.table(file = sig.metrics.file.path, header = T, sep = "\t", check.names = F, row.names = 1) index = which(rownames(sig.metrics.table) == paste0(gsub(' ','.', datasetName),'_',gsub(' ','.', signatureName))) sig.metrics.table = sig.metrics.table[index,,drop=F] stripchartMatrixList[["Original Metric Value"]]=sig.metrics.table } sigQC.out_dir = file.path(outputDir, "permutation_control", datasetName, signatureName) stripchart_group_names <- c('Relative Med. SD','Skewness',expression(sigma["" >= "10%" ]),expression(sigma["" >= "25%" ]),expression(sigma["" >= "50%" ]),'Coef. of Var.', 'Non-NA Prop.','Prop. Expressed', 'Autocor.',expression(rho["Mean,Med" ]), expression(rho["PCA1,Med" ]),expression(rho["Mean,PCA1" ]), expression(sigma["PCA1" ]), expression(rho["Med,Z-Med" ])) .boxplot.matrix2(x=neg.controls.summary[2:6,], outputDir=sigQC.out_dir, plotName="boxplot_metrics", plotTitle=paste("Boxplot Permutation Controls for",signatureName,sep=" "), stripchartMatrixList=stripchartMatrixList, stripchartPch=c(1, 21), stripchartCol = c("gray", "red"), xlab ="Metrics", ylab="Score",group.names=stripchart_group_names) summary.filePath = file.path(sigQC.out_dir, "perm_controls_summary_table.txt") utils::write.table(x = neg.controls.summary,file = summary.filePath,row.names = TRUE, col.names = TRUE,sep=",") } }, error = function(err) { cat("", file=log.con, sep="\n") cat(paste(Sys.time(),"Errors occurred during in sigQcNegativeControl:", err, sep=" "), file=log.con, sep="\n") }, finally = { close(log.con) close(warnings.con) }) }
.ddg.init.proc.nodes <- function () { .ddg.set("ddg.proc.nodes", .ddg.create.proc.node.rows()) .ddg.set("ddg.pnum", 0) .ddg.set("ddg.total.elapsed.time", 0) time <- proc.time() time <- time[1] + time[2] .ddg.set("ddg.proc.start.time", time) .ddg.set("ddg.starts.open", vector()) } .ddg.is.proc.type <- function(type) { return(type %in% c("Operation", "Start", "Finish", "Binding", "Incomplete")) } .ddg.pnum <- function() { return (.ddg.get("ddg.pnum")) } .ddg.total.elapsed.time <- function() { return (.ddg.get("ddg.total.elapsed.time")) } .ddg.start.proc.time <- function() { return(.ddg.get("ddg.proc.start.time")) } .ddg.elapsed.time <- function(){ time <- proc.time() orig.total.elapsed <- .ddg.total.elapsed.time() total.elapsed <- time[1] + time[2] - .ddg.start.proc.time() elapsed <- total.elapsed - orig.total.elapsed .ddg.set("ddg.total.elapsed.time", total.elapsed) return(elapsed) } .ddg.create.proc.node.rows <- function (size=100) { return (data.frame( ddg.type = character(size), ddg.num = numeric(size), ddg.name = character(size), ddg.value = character(size), ddg.return.linked = logical(size), ddg.time = double(size), ddg.snum = numeric(size), ddg.startLine = numeric(size), ddg.startCol = numeric(size), ddg.endLine = numeric(size), ddg.endCol = numeric(size), stringsAsFactors=FALSE)) } .ddg.proc.node.table <- function() { return (.ddg.get("ddg.proc.nodes")) } .ddg.proc.nodes <- function() { ddg.proc.nodes <- .ddg.get("ddg.proc.nodes") return (ddg.proc.nodes [ddg.proc.nodes$ddg.num > 0, ]) } .ddg.proc.node.returned <- function(pn) { ddg.proc.nodes <- .ddg.proc.node.table() ddg.proc.nodes$ddg.return.linked[pn] <- TRUE .ddg.set("ddg.proc.nodes", ddg.proc.nodes) } .ddg.proc.node.exists <- function(pname) { ddg.proc.nodes <- .ddg.proc.node.table() matching.nodes <- ddg.proc.nodes[ddg.proc.nodes$ddg.name == pname, ] return (nrow(matching.nodes) > 0) } .ddg.proc.number <- function(pname, find.unreturned.function=FALSE) { ddg.proc.nodes <- .ddg.proc.node.table() if (find.unreturned.function) { matching <- ddg.proc.nodes[ddg.proc.nodes$ddg.name == pname & !ddg.proc.nodes$ddg.return.linked, ] } else { matching <- ddg.proc.nodes[ddg.proc.nodes$ddg.name == pname, ] } if (nrow (matching) > 0) { return (matching$ddg.num[nrow(matching)]) } error.msg <- paste("No procedure node found for", pname) if (.ddg.debug.lib()) print (sys.calls()) .ddg.insert.error.message(error.msg) return(0) } .ddg.proc.name <- function(pnum) { if (pnum < 1 || pnum > .ddg.pnum()) { error.msg <- paste("No name found for procedure number", pnum) .ddg.insert.error.message(error.msg) return ("") } return(.ddg.proc.node.table()$ddg.name[pnum]) } .ddg.save.debug.proc.nodes <- function () { fileout <- paste(.ddg.path.debug(), "/procedure-nodes.csv", sep="") ddg.proc.nodes <- .ddg.proc.nodes() utils::write.csv(ddg.proc.nodes, fileout, row.names=FALSE) } .ddg.record.proc <- function(ptype, pname, pvalue, ptime, snum=NA, pos=NA) { if (!.ddg.is.proc.type (ptype)) { print (paste (".ddg.record.proc: bad value for ptype - ", ptype)) } ddg.pnum <- .ddg.inc("ddg.pnum") ddg.proc.nodes <- .ddg.proc.node.table() if (nrow(ddg.proc.nodes) < ddg.pnum) { ddg.proc.nodes <- .ddg.add.rows("ddg.proc.nodes", .ddg.create.proc.node.rows()) } ddg.proc.nodes$ddg.type[ddg.pnum] <- ptype ddg.proc.nodes$ddg.num[ddg.pnum] <- ddg.pnum ddg.proc.nodes$ddg.name[ddg.pnum] <- pname ddg.proc.nodes$ddg.value[ddg.pnum] <- pvalue ddg.proc.nodes$ddg.time[ddg.pnum] <- ptime ddg.proc.nodes$ddg.snum[ddg.pnum] <- snum if (is.object(pos) && length(pos@startLine == 1)) { ddg.proc.nodes$ddg.startLine[ddg.pnum] <- pos@startLine ddg.proc.nodes$ddg.startCol[ddg.pnum] <- pos@startCol ddg.proc.nodes$ddg.endLine[ddg.pnum] <- pos@endLine ddg.proc.nodes$ddg.endCol[ddg.pnum] <- pos@endCol } else if (is.vector(pos) && length(pos) == 4) { ddg.proc.nodes$ddg.startLine[ddg.pnum] <- pos[1] ddg.proc.nodes$ddg.startCol[ddg.pnum] <- pos[2] ddg.proc.nodes$ddg.endLine[ddg.pnum] <- pos[3] ddg.proc.nodes$ddg.endCol[ddg.pnum] <- pos[4] } else { ddg.proc.nodes$ddg.startLine[ddg.pnum] <- NA ddg.proc.nodes$ddg.startCol[ddg.pnum] <- NA ddg.proc.nodes$ddg.endLine[ddg.pnum] <- NA ddg.proc.nodes$ddg.endCol[ddg.pnum] <- NA } .ddg.set("ddg.proc.nodes", ddg.proc.nodes) if (.ddg.debug.lib()) { print (paste("Adding procedure node", ddg.pnum, "named", pname)) } } .ddg.proc.node <- function(ptype, pname, pvalue="", functions.called=NULL, cmd = NULL, scriptNum=NA, startLine=NA, startCol=NA, endLine=NA, endCol=NA) { if (!.ddg.is.proc.type (ptype)) { print (paste (".ddg.proc.node: bad value for ptype - ", ptype)) } if (!is.null(cmd)) { snum <- [email protected] pos <- cmd@pos } else if (!is.na(scriptNum)){ snum <- scriptNum pos <- c(startLine, startCol, endLine, endCol) } else { snum <- NA pos <- NA } if (ptype == "Start") { ddg.starts.open <- .ddg.get ("ddg.starts.open") ddg.starts.open <- c(ddg.starts.open, pname) .ddg.set ("ddg.starts.open", ddg.starts.open) } else if (ptype == "Finish") { ddg.starts.open <- .ddg.get ("ddg.starts.open") num.starts.open <- length(ddg.starts.open) if (num.starts.open > 0) { last.start.open <- ddg.starts.open[num.starts.open] if (num.starts.open > 1) { ddg.starts.open <- ddg.starts.open[1:num.starts.open-1] } else { ddg.starts.open <- vector() } .ddg.set ("ddg.starts.open", ddg.starts.open) if (last.start.open != pname) { .ddg.insert.error.message("Start and finish nodes do not match") } } else { .ddg.insert.error.message( "Attempting to create a finish node when there are no open blocks") } } .ddg.set("ddg.last.proc.node.created", paste(ptype, pname)) ptime <- .ddg.elapsed.time() .ddg.record.proc(ptype, pname, pvalue, ptime, snum, pos) if( !.ddg.is.null.or.na (functions.called)) { pfunctions <- .ddg.get.function.info(functions.called) .ddg.add.to.function.table (pfunctions) nonlocals.used <- .ddg.get.nonlocals.used (pfunctions) if (!is.null (nonlocals.used) && length (nonlocals.used) > 0) { nonlocals.used[sapply(nonlocals.used, is.null)] <- NULL create.use.edge <- function (var) { if (is.null(var) || length(var) == 0) return () var <- .ddg.extract.var (var) scope <- .ddg.get.scope(var) if (.ddg.data.node.exists(var, scope)) { .ddg.data2proc(var, scope) } } sapply (nonlocals.used, create.use.edge) } nonlocals.set <- .ddg.get.nonlocals.set (pfunctions) if (!is.null (nonlocals.set) && length (nonlocals.set) > 0) { nonlocals.set[sapply(nonlocals.set, is.null)] <- NULL nonlocals.set <- unique(unlist(nonlocals.set)) nonlocals.set <- unique(sapply (nonlocals.set, function (var) { return(.ddg.extract.var (var)) })) sapply (nonlocals.set, .ddg.save.var) sapply (nonlocals.set, .ddg.lastproc2data) } } if (.ddg.debug.lib()) print(paste("proc.node:", ptype, pname)) }
mixcombine <- function(..., weight, rescale=TRUE) { comp <- list(...) cl <- grep("mix$", class(comp[[1]]), ignore.case=TRUE, value=TRUE) dl <- dlink(comp[[1]]) lik <- likelihood(comp[[1]]) assert_that(all(sapply(comp, inherits, "mix")), msg="All components must be mixture objects.") assert_that(all(sapply(comp, likelihood) == lik), msg="All components must have the same likelihood set.") mix <- do.call(cbind, comp) if(!missing(weight)) { assert_that(length(weight) == length(comp)) mix[1,] <- mix[1,] * rep(weight, times=sapply(comp, ncol)) } if(rescale) mix[1,] <- mix[1,] / sum(mix[1,]) class(mix) <- cl dlink(mix) <- dl likelihood(mix) <- lik if("normMix" %in% cl) sigma(mix) <- sigma(comp[[1]]) mix }
compute.contrasts <- function(x, y, type=c("Fisher", "simple")) { n <- nrow(x) p <- ncol(x) stopifnot(length(y) == n) stopifnot(y %in% 0:1) stopifnot(table(y) > 3) xbar0 <- colMeans(x[y==0, ]) xbar1 <- colMeans(x[y==1, ]) s0 <- apply(x[y==0, ], 2, sd) s1 <- apply(x[y==1, ], 2, sd) n0 <- sum(y==0) n1 <- sum(y==1) w <- (xbar0-xbar1) / sqrt(s0^2/n0 + s1^2/n1) rho0 <- cor(x[y==0, ]) rho1 <- cor(x[y==1, ]) if (type[1]=="Fisher") { z <- (atanh(rho0) - atanh(rho1)) / sqrt(1/(n0-3) + 1/(n1-3)) diag(z) <- 0 } else if (type[1]=="simple") { xx0 <- scale(x[y==0, ]) xx1 <- scale(x[y==1, ]) zz0 <- array(NA, c(n0, p, p)) zz1 <- array(NA, c(n1, p, p)) for (j in seq(p)) for (k in seq(p)) { zz0[, j, k] <- xx0[, j] * xx0[, k] zz1[, j, k] <- xx1[, j] * xx1[, k] } m0 <- m1 <- s0 <- s1 <- matrix(NA, p, p) for (j in seq(p)) for (k in seq(p)) { m0[j, k] <- mean(zz0[, j, k]) m1[j, k] <- mean(zz1[, j, k]) s0[j, k] <- sd(zz0[, j, k]) s1[j, k] <- sd(zz1[, j, k]) } z <- (m0 - m1) / sqrt(s0^2 / n0 + s1^2 / n1) } else stop("Not implemented") list(w=w, z=z) } hiertest <- function(x, y, type=c("Fisher", "simple")) { cc <- compute.contrasts(x, y, type=type) knots <- get.knots(cc$w, cc$z) out <- test.statistics(knots$main.knots, knots$int.knots) class(out) <- "hiertest" out } interactions.above <- function(testobj, lambda) { ints <- testobj$stats[testobj$is.int] ints[ints > lambda] } plot.hiertest <- function(x, ...) { plot(x$stats,col=x$is.int+1, pch=20, main="Test statistics ordered by magnitude", ylab="CHT Statistic", ...) legend("topright", legend=c("Main effect", "Interaction"), col=1:2, pch=20) } print.hiertest <- function(x, nshow = 20, ...) { top <- x$stats[1:nshow] print(data.frame(Name = names(top), Statistic = top), row.names = FALSE, ...) cat("... List truncated. Use estimate.fdr to determine a proper cutoff.", fill = TRUE) } reject <- function(test.obj, lamlist) { lamlist <- sort(lamlist) nams <- names(test.obj$stats) reject <- list() for (i in seq(length(lamlist))){ ii <- test.obj$stats >= lamlist[i] test.obj$stats <- test.obj$stats[ii] test.obj$is.int <- test.obj$is.int[ii] nams <- nams[ii] reject[[i]] <- list(int=nams[test.obj$is.int], main=nams[!test.obj$is.int]) } reject } get.knots <- function(w, z) { p <- length(w) if (nrow(z) != p) browser() stopifnot(nrow(z) == p, ncol(z) == p) aw <- abs(w) diag(z) <- rep(0, p) az <- abs(z) main.knots <- pmax(aw, (aw + apply(az, 1, max)) / 2) int.knots <- matrix(NA, p, p) for (j in seq(p)) { for (k in seq(p)) { if (j == k) next int.knots[j, k] <- max(aw[j] - sum(pmax(az[j, -j] - az[j, k], 0)), 0) / 2 } } int.knots <- pmin(az, az / 2 + int.knots) int.knots <- pmax(int.knots, t(int.knots)) list(main.knots=main.knots, int.knots=int.knots) } test.statistics <- function(main.stats, int.stats) { p <- length(main.stats) int.stats <- int.stats[upper.tri(int.stats)] o <- order(-c(main.stats,int.stats)) main.nams <- names(main.stats) if (is.null(main.nams)) main.nams <- 1:p int.nams <- outer(main.nams, main.nams, paste, sep=":") nams <- c(main.nams, int.nams[upper.tri(int.nams)]) stats <- c(main.stats, int.stats) names(stats) <- nams stats <- stats[o] list(stats=stats, is.int=o>p) } estimate.fdr <- function(x, y, lamlist, type=c("Fisher", "simple"), B=100) { p <- ncol(x) nlam <- length(lamlist) ut <- upper.tri(diag(p)) cc <- compute.contrasts(x, y, type=type) lams <- get.knots(cc$w, cc$z)$int.knots[ut] ncalled <- rep(NA, nlam) for (i in seq(nlam)) ncalled[i] <- sum(lams >= lamlist[i]) ncalled[ncalled==0] <- NA lamstars <- matrix(NA, B, length(lams)) for (b in seq(B)) { ccstar <- compute.contrasts(x, sample(y), type=type) lamstars[b, ] <- get.knots(cc$w, ccstar$z)$int.knots[ut] } null.ncalled <- rep(NA, nlam) for (i in seq(nlam)) null.ncalled[i] <- sum(lamstars >= lamlist[i]) out <- list(ncalled=ncalled, null.ncalled=null.ncalled, fdr=pmin(null.ncalled / B / ncalled, 1), lamlist=lamlist) class(out) <- "estfdr" out } plot.estfdr <- function(x, ...) { plot(x$ncalled, x$fdr, type="l", ylab="Estimated FDR", xlab="Number of interactions called", ...) } print.estfdr <- function(x, ...) { print(data.frame("Lambda cutoff" = x$lamlist, "Number called" = x$ncalled, "Estimated FDR" = x$fdr), ...) }
setConstructorS3("AromaUnitSignalBinarySet", function(...) { extend(AromaTabularBinarySet(...), "AromaUnitSignalBinarySet") }) setMethodS3("findByName", "AromaUnitSignalBinarySet", function(static, ..., chipType=NULL) { NextMethod("findByName", subdirs=chipType) }, static=TRUE, protected=TRUE) setMethodS3("byName", "AromaUnitSignalBinarySet", function(static, name, tags=NULL, ..., chipType=NULL, paths=NULL, pattern="[.]asb$") { suppressWarnings({ path <- findByName(static, name=name, tags=tags, chipType=chipType, ..., paths=paths, mustExist=TRUE) }) suppressWarnings({ byPath(static, path=path, ..., pattern=pattern) }) }, static=TRUE) setMethodS3("validate", "AromaUnitSignalBinarySet", function(this, ...) { chipTypes <- lapply(this, FUN=getChipType) chipTypes <- unique(chipTypes) if (length(chipTypes) > 1) { throw("The located ", class(this)[1], " contains files with different chip types: ", paste(chipTypes, collapse=", ")) } NextMethod("validate") }, protected=TRUE) setMethodS3("getPlatform", "AromaUnitSignalBinarySet", function(this, ...) { getPlatform(getOneFile(this), ...) }) setMethodS3("getChipType", "AromaUnitSignalBinarySet", function(this, ...) { getChipType(getOneFile(this), ...) }) setMethodS3("getAromaUgpFile", "AromaUnitSignalBinarySet", function(this, ...) { getAromaUgpFile(getOneFile(this), ...) })
NULL mean_error <- function(actual, predicted, na.rm = FALSE) { if (!is.numeric(actual)) { abort_argument_type( arg = "actual", must = "be numeric", not = actual ) } if (!is.numeric(predicted)) { abort_argument_type( arg = "predicted", must = "be numeric", not = predicted ) } if (!is.logical(na.rm)) { abort_argument_type( arg = "na.rm", must = "be logical", not = na.rm ) } if (length(actual) != length(predicted)) { abort_argument_diff_length( arg1 = "actual", arg2 = "predicted" ) } mean(error(actual, predicted), na.rm = na.rm) } mean_error_pct <- function(actual, predicted, na.rm = FALSE) { if (!is.numeric(actual)) { abort_argument_type( arg = "actual", must = "be numeric", not = actual ) } if (!is.numeric(predicted)) { abort_argument_type( arg = "predicted", must = "be numeric", not = predicted ) } if (!is.logical(na.rm)) { abort_argument_type( arg = "na.rm", must = "be logical", not = na.rm ) } if (length(actual) != length(predicted)) { abort_argument_diff_length( arg1 = "actual", arg2 = "predicted" ) } mean(error_pct(actual, predicted), na.rm = na.rm) } mean_error_abs <- function(actual, predicted, na.rm = FALSE) { if (!is.numeric(actual)) { abort_argument_type( arg = "actual", must = "be numeric", not = actual ) } if (!is.numeric(predicted)) { abort_argument_type( arg = "predicted", must = "be numeric", not = predicted ) } if (!is.logical(na.rm)) { abort_argument_type( arg = "na.rm", must = "be logical", not = na.rm ) } if (length(actual) != length(predicted)) { abort_argument_diff_length( arg1 = "actual", arg2 = "predicted" ) } mean(error_abs(actual, predicted), na.rm = na.rm) } mean_error_abs_pct <- function(actual, predicted, na.rm = FALSE) { if (!is.numeric(actual)) { abort_argument_type( arg = "actual", must = "be numeric", not = actual ) } if (!is.numeric(predicted)) { abort_argument_type( arg = "predicted", must = "be numeric", not = predicted ) } if (!is.logical(na.rm)) { abort_argument_type( arg = "na.rm", must = "be logical", not = na.rm ) } if (length(actual) != length(predicted)) { abort_argument_diff_length( arg1 = "actual", arg2 = "predicted" ) } mean(error_abs_pct(actual, predicted), na.rm = na.rm) } mean_error_sqr <- function(actual, predicted, na.rm = FALSE) { if (!is.numeric(actual)) { abort_argument_type( arg = "actual", must = "be numeric", not = actual ) } if (!is.numeric(predicted)) { abort_argument_type( arg = "predicted", must = "be numeric", not = predicted ) } if (!is.logical(na.rm)) { abort_argument_type( arg = "na.rm", must = "be logical", not = na.rm ) } if (length(actual) != length(predicted)) { abort_argument_diff_length( arg1 = "actual", arg2 = "predicted" ) } mean(error_sqr(actual, predicted), na.rm = na.rm) } mean_error_sqr_root <- function(actual, predicted, na.rm = FALSE) { if (!is.numeric(actual)) { abort_argument_type( arg = "actual", must = "be numeric", not = actual ) } if (!is.numeric(predicted)) { abort_argument_type( arg = "predicted", must = "be numeric", not = predicted ) } if (!is.logical(na.rm)) { abort_argument_type( arg = "na.rm", must = "be logical", not = na.rm ) } if (length(actual) != length(predicted)) { abort_argument_diff_length( arg1 = "actual", arg2 = "predicted" ) } sqrt(mean_error_sqr(actual, predicted, na.rm = na.rm)) } bias <- function(actual, predicted, na.rm = FALSE) { if (!is.numeric(actual)) { abort_argument_type( arg = "actual", must = "be numeric", not = actual ) } if (!is.numeric(predicted)) { abort_argument_type( arg = "predicted", must = "be numeric", not = predicted ) } if (!is.logical(na.rm)) { abort_argument_type( arg = "na.rm", must = "be logical", not = na.rm ) } if (length(actual) != length(predicted)) { abort_argument_diff_length( arg1 = "actual", arg2 = "predicted" ) } mean_error(actual, predicted, na.rm = na.rm) } loa <- function(actual, predicted, na.rm = FALSE) { if (!is.numeric(actual)) { abort_argument_type( arg = "actual", must = "be numeric", not = actual ) } if (!is.numeric(predicted)) { abort_argument_type( arg = "predicted", must = "be numeric", not = predicted ) } if (!is.logical(na.rm)) { abort_argument_type( arg = "na.rm", must = "be logical", not = na.rm ) } if (length(actual) != length(predicted)) { abort_argument_diff_length( arg1 = "actual", arg2 = "predicted" ) } bias <- bias(actual, predicted, na.rm = na.rm) SD <- stats::sd(error(actual, predicted), na.rm = na.rm) lower <- bias - 1.96 * SD upper <- bias + 1.96 * SD loa <- list(lower = lower, upper = upper) loa }
tango.pboot<-function(...) { return( tango.stat(...) ) }
mydata<-as.table(matrix(c(51,2,42,46,7, 4,0,5,3,0, 44,4,174,39,2, 14,3,34,36,4, 4,1,26,11,0, 1,0,1,2,0, 0,0,0,0,0, 5,0,4,2,0, 1,0,3,0,0, 0,0,0,0,0, 1006,112,921,495,91, 81,1,79,22,2, 1084,109,1909,397,134, 486,42,419,220,33, 63,3,151,26,1, 34,3,7,21,1, 8,0,2,1,0, 23,0,20,13,3, 6,11,5,0,0, 0,0,3,0,0, 28,0,18,4,7, 0,0,2,0,0, 22,2,98,14,1, 5,0,25,0,0, 2,0,0,0,0), nrow=25, ncol=5, byrow = TRUE)) hyp <- "a:=x[1,1]+x[1,2]+x[1,3]+x[1,4]+x[1,5]; b:=x[1,1]+x[2,1]+x[3,1]+x[4,1]+x[5,1]; c:=x[7,1]+x[7,2]+x[7,3]+x[7,4]+x[7,5]; d:=x[6,2]+x[7,2]+x[8,2]+x[9,2]+x[10,2]; e:=x[13,1]+x[13,2]+x[13,3]+x[13,4]+x[13,5]; f:=x[11,3]+x[12,3]+x[13,3]+x[14,3]+x[15,3]; g:=x[14,1]+x[14,2]+x[14,3]+x[14,4]+x[14,5]; h:=x[11,4]+x[12,4]+x[13,4]+x[14,4]+x[15,4]; i:=x[18,1]+x[18,2]+x[18,3]+x[18,4]+x[18,5]; j:=x[16,3]+x[17,3]+x[18,3]+x[19,3]+x[20,3]; k:=x[19,1]+x[19,2]+x[19,3]+x[19,4]+x[19,5]; l:=x[16,4]+x[17,4]+x[18,4]+x[19,4]+x[20,4]; a > b & c > d & e > f & k > l; a > b & c > d & g > h & i > j; a = b & c = d & e = f & k = l; a = b & c = d & g = h & i = j" res <- gorica(mydata, hyp) test_that("contingency table supp 3_1 works", { expect_equivalent(res$fit$gorica_weights, c(0.1522023526, 0.6953728373, 0.0008049366, 0.000866056, 0.1507538174), tolerance = .03) })
factory_gt <- function(tab, align = NULL, hrule = NULL, notes = NULL, title = NULL, escape = TRUE, ...) { assert_dependency("gt") idx_col <- ncol(tab) out <- gt::gt(tab, caption = title) theme_ms <- getOption("modelsummary_theme_gt", default = theme_ms_gt) out <- theme_ms(out, output_format = settings_get("output_format"), hrule = hrule) if (!is.null(notes)) { for (n in notes) { out <- gt::tab_source_note(out, source_note = n) } } span <- attr(tab, 'span_gt') if (!is.null(span)) { for (s in span) { out <- gt::tab_spanner(out, label = s$label, columns = s$position) } } if (!is.null(align)) { left <- grep('l', align) center <- grep('c', align) right <- grep('r', align) out <- out <- gt::cols_align(out, align = 'center', columns = center) out <- gt::cols_align(out, align = 'left', columns = left) out <- gt::cols_align(out, align = 'right', column = right) } if (is.null(settings_get("output_file"))) { if (settings_equal("output_format", "html")) { out <- gt::as_raw_html(out) } if (settings_equal("output_format", "latex")) { out <- gt::as_latex(out) } if (!is.null(getOption("modelsummary_orgmode")) && settings_equal("output_format", c("html", "latex"))) { out <- sprintf(" return(out) } if (settings_equal("output_format", c("default", "gt"))) { return(out) } } else { gt::gtsave(out, settings_get("output_file")) } }
library(ggplot2) library(grid) this_base <- "fig10-03_presidential-approval-data-waffle-chart" my_data <- data.frame(decision = c("Approve", "Disapprove", "No Opinion"), ncases = c(53L, 34L, 13L)) ndeep <- 10 my_data_waffle <- expand.grid(y = 1:ndeep, x = seq_len(ceiling(sum(my_data$ncases) / ndeep))) decisionvec <- rep(my_data$decision, my_data$ncases) my_data_waffle$decision <- c(decisionvec, rep(NA, nrow(my_data_waffle) - length(decisionvec))) my_data_waffle$decision <- factor(my_data_waffle$decision) p <- ggplot(my_data_waffle, aes(x = x, y = y, fill = decision)) + geom_tile(color = "black", size = 0.5) + geom_hline(aes(yintercept = 5.5), size = 2) + geom_vline(aes(xintercept = 5.5), size = 2) + scale_fill_manual(breaks = c("1", "2"), values = c("grey30", "grey60", "white"), labels = c("Approve", "Disapprove")) + scale_x_continuous(expand = c(0, 0)) + scale_y_continuous(expand = c(0, 0), trans = 'reverse') + ggtitle("Fig 10.3 Presidential Approval Data \nWaffle Chart") + theme(panel.border = element_rect(fill = NA, size = 3), plot.title = element_text(size = rel(1.2), face = "bold"), axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), legend.title = element_blank(), legend.position = "bottom", legend.direction = "vertical") p ggsave(paste0(this_base, ".png"), p, width = 5, height = 6)
dpcoa <- function (df, dis = NULL, scannf = TRUE, nf = 2, full = FALSE, tol = 1e-07, RaoDecomp = TRUE) { if (!inherits(df, "data.frame")) stop("df is not a data.frame") if (any(df < 0)) stop("Negative value in df") if (any(rowSums(df) < tol)) stop("Remove empty samples") nesp <- ncol(df) nrel <- nrow(df) if (!is.null(dis)) { if (!inherits(dis, "dist")) stop("dis is not an object 'dist'") n1 <- attr(dis, "Size") if (nesp != n1) stop("Non convenient dimensions") if (!is.euclid(dis)) stop("an Euclidean matrix is needed") } if (is.null(dis)) { dis <- (matrix(1, nesp, nesp) - diag(rep(1, nesp))) * sqrt(2) rownames(dis) <- colnames(dis) <- names(df) dis <- as.dist(dis) } if (is.null(attr(dis, "Labels"))) attr(dis, "Labels") <- names(df) d <- as.matrix(dis) d <- (d^2) / 2 w.samples <- rowSums(df)/sum(df) w.esp <- colSums(df)/sum(df) dfp <- as.matrix(sweep(df, 1, rowSums(df), "/")) pco1 <- dudi.pco(dis, row.w = w.esp, full = TRUE) wrel <- data.frame(dfp %*% as.matrix(pco1$li)) row.names(wrel) <- rownames(df) res <- as.dudi(wrel, rep(1, ncol(wrel)), w.samples, scannf = scannf, nf = nf, call = match.call(), type = "dpcoa", tol = tol, full = full) w <- as.matrix(pco1$li) %*% as.matrix(res$c1) w <- data.frame(w) row.names(w) <- names(df) res$dls <- w res$dw <- w.esp res$co <- res$l1 <- NULL if(RaoDecomp){ res$RaoDiv <- apply(dfp, 1, function(x) sum(d * outer(x, x))) fun1 <- function(x) { w <- -sum(d * outer (x, x)) return(sqrt(w)) } dnew <- matrix(0, nrel, nrel) idx <- dfp[col(dnew)[col(dnew) < row(dnew)], ] - dfp[row(dnew)[col(dnew) < row(dnew)], ] dnew <- apply(idx, 1, fun1) attr(dnew, "Size") <- nrel attr(dnew, "Labels") <- rownames(df) attr(dnew, "Diag") <- TRUE attr(dnew, "Upper") <- FALSE attr(dnew, "method") <- "dis" attr(dnew, "call") <- match.call() class(dnew) <- "dist" res$RaoDis <- dnew Bdiv <- crossprod(w.samples, (as.matrix(dnew)^2)/2) %*% w.samples Tdiv <- crossprod(w.esp, d) %*% (w.esp) Wdiv <- Tdiv - Bdiv divdec <- data.frame(c(Bdiv, Wdiv, Tdiv)) names(divdec) <- "Diversity" rownames(divdec) <- c("Between-samples diversity", "Within-samples diversity", "Total diversity") res$RaoDecodiv <- divdec } class(res) <- "dpcoa" return(res) } plot.dpcoa <- function(x, xax = 1, yax = 2, ...) { if (!inherits(x, "dpcoa")) stop("Object of type 'dpcoa' expected") nf <- x$nf if (xax > nf) stop("Non convenient xax") if (yax > nf) stop("Non convenient yax") opar <- par(no.readonly = TRUE) on.exit (par(opar)) par(mfrow = c(2,2)) s.corcircle(x$c1[, c(xax, yax)], cgrid = 0, sub = "Principal axes", csub = 1.5, possub = "topleft", fullcircle = TRUE) add.scatter.eig(x$eig, length(x$eig), xax, yax, posi = "bottomleft", ratio = 1/4) X <- as.list(x$call)[[2]] X <- eval.parent(X) s.distri(x$dls[, c(xax, yax)], t(X), cellipse = 1, cstar = 0, sub = "Categories & Collections", possub = "bottomleft", csub = 1.5) s.label(x$dls[, c(xax, yax)], sub = "Categories", possub = "bottomleft", csub = 1.5) if(!is.null(x$RaoDiv)) s.value(x$li[, c(xax, yax)], x$RaoDiv, sub = "Rao Divcs") else s.label(x$li[, c(xax, yax)], sub = "Collections", possub = "bottomleft", csub = 1.5) } summary.dpcoa <- function(object, ...){ summary.dudi(object, ...) } print.dpcoa <- function (x, ...) { if (!inherits(x, "dpcoa")) stop("to be used with 'dpcoa' object") cat("Double principal coordinate analysis\n") cat("call: ") print(x$call) cat("class: ") cat(class(x), "\n") cat("\n$nf (axis saved) :", x$nf) cat("\n$rank: ", x$rank) cat("\n\neigen values: ") l0 <- length(x$eig) cat(signif(x$eig, 4)[1:(min(5, l0))]) if (l0 > 5) cat(" ...\n\n") else cat("\n\n") nr <- ifelse(!is.null(x$RaoDecomp), 4, 3) sumry <- array("", c(nr, 4), list(1:nr, c("vector", "length", "mode", "content"))) sumry[1, ] <- c("$dw", length(x$dw), mode(x$dw), "category weights") sumry[2, ] <- c("$lw", length(x$lw), mode(x$lw), "collection weights") sumry[3, ] <- c("$eig", length(x$eig), mode(x$eig), "eigen values") if(nr == 4) sumry[4, ] <- c("$RaoDiv", length(x$RaoDiv), mode(x$RaoDiv), "diversity coefficients within collections") print(sumry, quote = FALSE) cat("\n") if(!is.null(x$RaoDecomp)){ sumry <- array("", c(1, 3), list(1:1, c("dist", "Size", "content"))) sumry[1, ] <- c("$RaoDis", attributes(x$RaoDis)$Size, "distances among collections") print(sumry, quote = FALSE) cat("\n") } sumry <- array("", c(nr, 4), list(1:nr, c("data.frame", "nrow", "ncol", "content"))) sumry[1, ] <- c("$dls", nrow(x$dls), ncol(x$dls), "coordinates of the categories") sumry[2, ] <- c("$li", nrow(x$li), ncol(x$li), "coordinates of the collections") sumry[3, ] <- c("$c1", nrow(x$c1), ncol(x$c1), "scores of the principal axes of the categories") if(nr == 4) sumry[4, ] <- c("$RaoDecodiv", 3, 1, "decomposition of diversity") print(sumry, quote = FALSE) }
layersList <- function(obj) { if (is.ggplot(obj)) obj <- list(obj) rmNullObs(lapply(obj, layersListFull)) }
NULL multinom_test <- function (x, p = rep(1/length(x), length(x)), detailed = FALSE) { args <- as.list(environment()) %>% add_item(method = "exact_multinom_test") if (!is.vector(x)) { stop("'x' must be a vector") } if (sum(p) != 1) { stop("sum of probabilities must be 1") } if (length(x) != length(p)) { stop("'x' and 'p' lengths differ") } if(is.null(names(x))){ names(x) <- paste0("grp", 1:length(x)) } size <- sum(x) groups <- length(x) numEvents <- choose(size + groups - 1, groups - 1) pObs <- stats::dmultinom(x, size, p) findVectors <- function(groups, size) { if (groups == 1) { mat <- size } else { mat <- matrix(rep(0, groups - 1), nrow = 1) for (i in 1:size) { mat <- rbind(mat, findVectors(groups - 1, i)) } mat <- cbind(mat, size - rowSums(mat)) } mat } eventMat <- findVectors(groups, size) eventProb <- apply(eventMat, 1, function(x) stats::dmultinom(x, size, p)) p.val <- sum(eventProb[eventProb <= pObs]) results <- tibble( p = p.val, method = "Exact multinomial test" ) %>% add_significance() %>% select(.data$p, .data$p.signif, .data$method) descriptives <- tibble( group = names(x), observed = x, expected = p*size ) if(!detailed){ results <- results[, c("p", "p.signif")] } results %>% set_attrs(args = args, descriptives = descriptives) %>% add_class(c("rstatix_test", "exact_multinom_test")) }
vis.mirror.pt <- function(x, titles, size_titles = 5, horizon = NULL, breaks_x_left, breaks_x_right, from = 1, cols, ord, xlab = "Time", ylab = "Probability", legend.pos = "right") { if (!requireNamespace("ggplot2", quietly = TRUE)) { stop("Package ggplot2 needed for this function to work. Please install it.", call. = FALSE) } n_states <- 1 + sum(!is.na(x[[1]][["trans"]][from, ])) if (missing(cols)) cols <- set_colours(n = n_states, type = "areas") if (missing(ord)) ord <- seq_len(n_states) p_left <- plot.probtrans(x[[1]], use.ggplot = TRUE, ord = ord, cols = cols) p_right <- plot.probtrans(x[[2]], use.ggplot = TRUE, ord = ord, cols = cols) build_p1 <- ggplot2::ggplot_build(p_left) left_xlim <- p_left$coordinates$limits$x right_xlim <- p_right$coordinates$limits$x if (!is.null(horizon)) { if (horizon > max(left_xlim) | horizon > max(right_xlim)) stop(paste0("Horizon should be smaller than both ", max(left_xlim), " and ", max(right_xlim))) left_xlim[which(left_xlim == max(left_xlim))] <- horizon right_xlim[which(right_xlim == max(right_xlim))] <- horizon } dat_left <- p_left$data[time <= max(left_xlim)] dat_left[time == max(dat_left$time), ]$time <- max(left_xlim) dat_right <- p_right$data[time <= max(right_xlim)] dat_right[time == max(dat_right$time), ]$time <- max(right_xlim) if (any(levels(dat_left$state) != levels(dat_right$state))) stop("Argument 'ord' must be the same for both plots.") ylim <- c(0, 1) main <- prep_compare_df( dat_left = dat_left, dat_right = dat_right ) dat_main <- main$df_compare max_t <- main$max_t diff <- main$diff breaks_size <- c(floor(max_t / 3), floor(max(dat_right$time) / 3)) if (any(breaks_size == 0)) breaks_size <- c(round(max_t / 3, digits = 1), round(max(dat_right$time) / 3, digits = 1)) if (missing(breaks_x_left)) breaks_x_left <- seq(from = 0, to = max_t, by = breaks_size[1]) if (missing(breaks_x_right)) breaks_x_right <- seq(from = 0, to = max(dat_right$time), by = breaks_size[2]) if (any(breaks_x_left > max_t)) stop(paste0("Max follow up on left side is ", round(max_t, 3), ", make sure all breaks are smaller!")) if (any(breaks_x_right > max(dat_right$time))) stop(paste0("Max follow up on right side is ", round(max(dat_right$time), 3), ", make sure all breaks are smaller!")) breakos <- c(breaks_x_left, max(dat_main$time) - breaks_x_right) labos <- c(breaks_x_left, breaks_x_right) p_main <- ggplot2::ggplot(data = dat_main, ggplot2::aes(x = .data$time)) + ggplot2::geom_ribbon( ggplot2::aes(ymin = .data$low, ymax = .data$upp, fill = .data$state), col = "black", na.rm = TRUE ) + ggplot2::geom_segment( x = max_t, xend = max_t, y = ylim[1], yend = ylim[2], size = 2 ) + ggplot2::scale_x_continuous(xlab, breaks = breakos, labels = labos) + ggplot2::ylab(ylab) + ggplot2::scale_fill_manual(values = cols) + ggplot2::guides(fill = ggplot2::guide_legend(reverse = TRUE)) if (missing(titles)) { p <- p_main + ggplot2::theme( legend.position = legend.pos, panel.grid = ggplot2::element_blank(), panel.background = ggplot2::element_blank(), axis.line = ggplot2::element_blank() ) + ggplot2::coord_cartesian(expand = 0, ylim = ylim) return(p) } else { pos_title_left <- (max_t / 2) pos_title_right <- (max(dat_main$time) - max(dat_right$time) / 2) titles_df <- data.frame( labs = c(titles[1], titles[2]), pos_x = c(pos_title_left, pos_title_right), pos_y = rep(1.05, 2) ) base_p <- p_main + ggplot2::theme( plot.margin = ggplot2::unit(c(30.5, 5.5, 5.5, 5.5), "points"), legend.position = legend.pos, panel.grid = ggplot2::element_blank() ) + ggplot2::coord_cartesian(clip = "off", expand = 0, ylim = ylim) + ggplot2::geom_text( data = titles_df, ggplot2::aes(x = .data$pos_x, y = .data$pos_y, label = .data$labs), hjust = 0.5, size = size_titles ) return(base_p) } } prep_compare_df <- function(dat_left, dat_right) { . <- time <- time_orig <- state <- side <- NULL p1_maxt <- max(dat_left$time) p2_maxt <- max(dat_right$time) max_t <- p1_maxt diff <- ifelse(p2_maxt != p1_maxt, p2_maxt - p1_maxt, 0) df_p2 <- data.table::copy(dat_right) df_p2[, time := data.table::shift( x = time, fill = NA, n = 1, type = "lag" ), by = state] df_p2 <- unique(df_p2[!is.na(time)]) df_p2[, ':=' ( time_orig = time, time = -time + 2 * max_t + (diff + 0.01) )] cols <- c("time", "time_orig") df_p2 <- rbind(df_p2, df_p2) data.table::setorder(df_p2, time) df_p2[, (cols) := Map( f = data.table::shift, x = .SD, fill = time[1L], n = 1, type = "lag" ), by = state, .SDcols = cols] df_p2[, side := "right"] df_p1 <- dat_left[, ':=' ( time_orig = time, side = "left" )] plot_df <- rbind(df_p1, df_p2[!is.na(time)]) res <- list("df_compare" = plot_df, "max_t" = max_t, "diff" = diff) return(res) }
sirt_summary_print_computation_time_s1 <- function(object) { cat( "Date of Analysis:", paste(object$s2 ), "\n" ) cat("Computation Time:", print(object$s2 - object$s1), "\n\n") }
context("gather_array") test_that("works with array of length 1", { json <- '[{"name": "bob"}]' expect_identical( json %>% gather_array, tbl_json( data.frame( document.id = 1L, array.index = 1L ), list( list(name = "bob") ) ) ) } ) test_that("works with single array", { json <- '[{"name": "bob"}, {"name": "susan"}]' expect_identical( json %>% gather_array, tbl_json( data.frame( document.id = c(1L, 1L), array.index = c(1L, 2L) ), list( list(name = "bob"), list(name = "susan") ) ) ) } ) test_that("works with multiple json", { json <- c( '[{"name": "bob"}, {"name": "susan"}]', '[{"name": "john"}]' ) expect_identical( json %>% gather_array, tbl_json( data.frame( document.id = c(1L, 1L, 2L), array.index = c(1L, 2L, 1L) ), list( list(name = "bob"), list(name = "susan"), list(name = "john") ) ) ) } ) test_that("works with value array", { json <- c('["a", "b"]') expect_identical( json %>% gather_array, tbl_json( data.frame( document.id = c(1L, 1L), array.index = c(1L, 2L) ), list("a", "b") ) ) } ) test_that("empty json are dropped", { json <- c('[{"name": "bob"}]', '[]') expect_identical( json %>% gather_array, tbl_json( data.frame( document.id = 1L, array.index = 1L ), list( list(name = "bob") ) ) ) } ) test_that("null values are kept", { json <- '["string", null]' expect_identical( json %>% gather_array, tbl_json( data.frame( document.id = c(1L, 1L), array.index = c(1L, 2L) ), list("string", NULL) ) ) } ) test_that("objects throws error", { json <- c('[{"name": "bob"}]', '{"name": "susan"}') expect_error(json %>% gather_array) } ) test_that("values throws error", { json <- c('[{"name": "bob"}]', '"bob"') expect_error(json %>% gather_array) } ) test_that("correctly handles character(0), {}, []", { empty <- tbl_json( data.frame( document.id = integer(0), array.index = integer(0), stringsAsFactors = FALSE), list()) expect_identical( character(0) %>% gather_array, empty) expect_error('{}' %>% gather_array) expect_identical( '[]' %>% gather_array, empty) } )
mcSimulations <- function(N, nobs = 250, nMC = 100, rho = 0.5, sparsity = 0.05, penalty = "ENET", covariance = "Toeplitz", method = "normal", modelSel = "cv", ...) { results <- list() results$confusionMatrix <- matrix(0, nMC, 4) results$matrixNorms <- matrix(0, nMC, 6) pb <- utils::txtProgressBar(min = 0, max = nMC, style = 3) for (i in 1:nMC) { s <- simulateVAR(nobs = nobs, N = N, rho = rho, sparsity = sparsity, covariance = covariance, method = method, ...) rets <- s$series genA <- s$A[[1]] spRad <- max(Mod(eigen(genA)$values)) res <- fitVAR(data = rets, penalty = penalty, method = modelSel, ...) A <- res$A[[1]] estSpRad <- max(Mod(eigen(A)$values)) L <- A L[L != 0] <- 1 L[L == 0] <- 0 genL <- genA genL[genL != 0] <- 1 genL[genL == 0] <- 0 results$confusionMatrix[i, 1:4] <- prop.table(table(Predicted = L, Real = genL)) results$accuracy[i] <- 1 - sum(abs(L - genL)) / N^2 results$matrixNorms[i, 1] <- abs(sum(L) / N^2 - sparsity) results$matrixNorms[i, 2] <- l2norm(A - genA) / l2norm(genA) results$matrixNorms[i, 3] <- frobNorm(A - genA) / frobNorm(genA) results$matrixNorms[i, 4] <- res$mse results$matrixNorms[i, 5] <- spRad results$matrixNorms[i, 6] <- estSpRad utils::setTxtProgressBar(pb, i) } close(pb) results$confusionMatrix <- as.data.frame(results$confusionMatrix) colnames(results$confusionMatrix) <- c("TP", "FP", "FN", "TN") results$matrixNorms <- as.data.frame(results$matrixNorms) colnames(results$matrixNorms) <- c("sparDiff", "l2", "frob", "mse", "spRad", "estSpRad") return(results) }
library(backtest) load("backtest.function.test.RData") bt.1 <- backtest(x, in.var = "in.var.1", ret.var = "ret.var.1", by.period = FALSE) bt.2 <- backtest(x, in.var = "in.var.1", ret.var = "ret.var.1", by.var = "country", by.period = FALSE) bt.3 <- backtest(x, id.var = "id", in.var = "in.var.1", ret.var = "ret.var.1", date.var = "date", by.period = FALSE) bt.4 <- backtest(x, in.var = c("in.var.1", "in.var.2"), ret.var = "ret.var.1", by.var = "country", by.period = FALSE) bt.5 <- backtest(x, in.var = "in.var.1", ret.var = "ret.var.1", by.period = TRUE, date.var = "date", buckets = 2) bt.6 <- backtest(x, in.var = "in.var.1", ret.var = "ret.var.1", by.period = TRUE, date.var = "date", natural = TRUE, id = "id", buckets = 2) bt.7 <- backtest(x, id.var = "id", in.var = "in.var.1", ret.var = "ret.var.1", by.period = FALSE, date.var = "date", overlaps = 2) stopifnot( all.equal(truth.1, as.numeric(bt.1@results[1,1 , , ,"means"])), all(mapply(all.equal, truth.2, bt.2@results[1,1 , , ,"means"])), all(mapply(all.equal, truth.3, bt.3@results[1,1 , , ,"means"])), all(mapply(all.equal, truth.4.A, bt.4@results["ret.var.1","in.var.1", , ,"means"])), all(mapply(all.equal, truth.4.B, bt.4@results["ret.var.1","in.var.2", , ,"means"])), all(mapply(all.equal, truth.5, bt.5@results[1,1 , , ,"means"])), all(mapply(all.equal, truth.6, bt.6@results[1,1 , , ,"means"])) )
fxmonitor <- function(formula, data, start, end = 3, alpha = 0.05, meat. = NULL) { if(missing(formula)) formula <- colnames(data)[1] if(is.character(formula)) formula <- as.formula(paste(formula, "~", paste(colnames(data)[colnames(data) != formula], collapse = " + "))) if(is.character(start)) start <- as.Date(start) monitor <- end(window(data, end = start-1)) n <- NROW(window(data, end = monitor)) hist.fm <- fxlm(formula, data = window(data, end = monitor)) sigma2 <- coef(hist.fm)["(Variance)"] mf <- model.frame(formula, data = as.data.frame(data)) y <- model.response(mf) X <- model.matrix(formula, data = as.data.frame(data)) attr(X, "assign") <- NULL y.pred <- predict(hist.fm, as.data.frame(X)) mscore <- as.vector(y - y.pred) * X mscore <- cbind(mscore, ((y - y.pred)^2 - sigma2)) mscore <- mscore/sqrt(n) hist.score <- mscore[1:n,] J12 <- if(!is.null(meat.)) meat.(hist.fm) else crossprod(hist.score) J12 <- root.matrix(J12) mscore <- apply(as.matrix(mscore), 2, cumsum) mscore <- zoo(t(chol2inv(chol(J12)) %*% t(mscore)), order.by = index(data)) colnames(mscore) <- names(coef(hist.fm)) cv <- matrix(c( 1.159, 1.329, 1.430, 1.472, 1.502, 1.541, 1.567, 1.253, 1.445, 1.544, 1.589, 1.619, 1.668, 1.688, 1.383, 1.590, 1.695, 1.753, 1.789, 1.838, 1.860, 1.467, 1.688, 1.793, 1.861, 1.899, 1.961, 1.964, 1.568, 1.814, 1.939, 2.006, 2.046, 2.090, 2.128, 1.616, 1.896, 2.022, 2.076, 2.131, 2.159, 2.219, 1.680, 1.997, 2.103, 2.177, 2.226, 2.257, 2.311, 1.801, 2.114, 2.217, 2.301, 2.397, 2.380, 2.454, 1.976, 2.300, 2.423, 2.525, 2.573, 2.597, 2.650, 2.118, 2.478, 2.599, 2.712, 2.812, 2.766, 2.888, 2.435, 2.789, 2.973, 3.288, 3.226, 3.230, 3.401), nrow = 7) cv_row <- c(2:6, 8, 10) cv_col <- c(0.2, 0.15, 0.1, 0.075, 0.05, 0.04, 0.03, 0.02, 0.01, 0.005, 0.001) alpha <- 1 - (1 - alpha)^(1/ncol(mscore)) critval <- apply(cv, 2, function(x) approx(cv_row, x, end, rule = 2)$y) critval <- approx(cv_col, critval, alpha, rule = 2)$y rval <- list(process = mscore, n = n, formula = formula, data = data, monitor = monitor, critval = critval, J12 = J12) class(rval) <- "fxmonitor" return(rval) } plot.fxmonitor <- function(x, which = NULL, aggregate = NULL, ylim = NULL, xlab = "Time", ylab = "Empirical fluctuation process", main = "Monitoring of FX model", ...) { n <- x$n proc <- x$process if(is.null(which)) which <- 1:NCOL(proc) if(is.null(aggregate)) aggregate <- length(which) > 1 proc <- proc[,which] dummy <- zoo((n+1):NROW(proc)/n, index(proc)[-(1:n)]) * x$critval if(aggregate) { maxabs <- zoo(apply(abs(coredata(proc)), 1, max), order.by = index(proc)) if(is.null(ylim)) ylim <- c(0, max(c(max(maxabs), max(dummy)))) plot(maxabs, ylim = ylim, xlab = xlab, ylab = ylab, main = main, ...) abline(h = 0) abline(v = x$monitor, lty = 2) lines(dummy, col = 2) } else { if(missing(ylim)) ylim <- c(min(min(proc), min(-dummy)), max(max(proc), max(dummy))) if(missing(ylab) && NCOL(proc) > 1) ylab <- colnames(proc) mypanel <- function(z, ...) { lines(z, ...) abline(h = 0) abline(v = x$monitor, lty = 2) lines(-dummy, col = 2) lines(dummy, col = 2) } plot(proc, panel = mypanel, ylim = ylim, xlab = xlab, ylab = ylab, main = main, ...) } invisible(x) } print.fxmonitor <- function(x, ...) { n <- x$n proc <- x$process maxabs <- apply(abs(coredata(proc)), 1, max)[-(1:n)] dummy <- ((n+1):NROW(proc)/n) * x$critval breakpoint <- if(any(maxabs > dummy)) min(which(maxabs > dummy)) + n else NA form <- as.character(x$formula) form <- paste(form[2], form[1], form[3]) cat("Monitoring of FX model\n\n") cat(paste("Formula:", form, "\n")) cat(paste("History period:", start(proc), "to", x$monitor, "\n")) cat(paste("Break detected:", ifelse(is.na(breakpoint), "none", as.character(index(proc)[breakpoint])), "\n")) invisible(x) } breakpoints.fxmonitor <- function(obj, ...) { n <- obj$n proc <- obj$process maxabs <- apply(abs(coredata(proc)), 1, max)[-(1:n)] dummy <- ((n+1):NROW(proc)/n) * obj$critval breakpoint <- if(any(maxabs > dummy)) min(which(maxabs > dummy)) + n else NA return(breakpoint) } breakdates.fxmonitor <- function(obj, ...) { rval <- breakpoints(obj) if(!is.na(rval)) rval <- index(obj$process)[rval] return(rval) }
current_mps <- function(tidy = TRUE, tidy_style = "snake_case") { suppressMessages(constit <- hansard::constituencies( current = TRUE, tidy = FALSE )) current <- mnis::mnis_eligible(house = "commons", tidy = FALSE) if (.Platform$OS.type == "windows") { current$MemberFrom <- stringi::stri_trans_general( current$MemberFrom, "latin-ascii" ) current$MemberFrom <- gsub( "Ynys MA\U00B4n", "Ynys M\U00F4n", current$MemberFrom ) } df <- dplyr::right_join(current, constit, by = c("MemberFrom" = "label._value") ) if (tidy == TRUE) { df$startedDate._value <- as.POSIXct(df$startedDate._value) df$startedDate._datatype <- "POSIXct" df$CurrentStatus.StartDate <- gsub("T", " ", df$CurrentStatus.StartDate) df$CurrentStatus.StartDate <- as.POSIXct(df$CurrentStatus.StartDate) df$HouseStartDate <- gsub("T", "", df$HouseStartDate) df$HouseStartDate <- as.POSIXct(df$HouseStartDate) df$DateOfBirth <- as.character(df$DateOfBirth) df$DateOfBirth <- gsub("T00:00:00", "", df$DateOfBirth) df$DateOfBirth <- as.Date(df$DateOfBirth) df$DateOfBirth <- as.POSIXct(df$DateOfBirth) df <- parlitools_tidy(df, tidy_style) } df }
toolGetMapping <- function(name, type = NULL, where = NULL, error.missing = TRUE, returnPathOnly = FALSE, activecalc = NULL) { if (is.null(where)) { mf <- getConfig("mappingfolder") fname <- paste0(mf, "/", type, "/", name) if (file.exists(as.character(name))) { fname <- name } else if (!file.exists(as.character(fname))) { packages <- getConfig("packages") if (!is.null(activecalc[[1]]) & any(grepl(paste0("^", activecalc[[1]], "$"), getCalculations()[, "type"]))) { fp <- as.character(attr(prepFunctionName(activecalc[[1]], "calc"), "package")) packages <- c(fp, grep(fp, packages, invert = TRUE, value = TRUE)) } for (i in packages) { out <- toolGetMapping(name, type = type, where = i, error.missing = FALSE, returnPathOnly = TRUE) if (out != "") { fname <- out break } } } } else if (where == "mappingfolder") { mf <- getConfig("mappingfolder") fname <- paste0(mf, "/", type, "/", name) } else if (where == "local") { if (is.null(type)) { fname <- name } else { fname <- paste0(type, "/", name) } } else { if (is.null(type)) { tmpfname <- name } else { tmpfname <- paste0(type, "/", name) } fname <- system.file("extdata", tmpfname, package = where) if (fname == "") fname <- system.file("inst/extdata", tmpfname, package = where) if (fname == "") fname <- system.file("extdata", strsplit(tmpfname, split = "/")[[1]][2], package = where) if (fname == "") fname <- system.file("inst/extdata", strsplit(tmpfname, split = "/")[[1]][2], package = where) if (fname == "" & error.missing) { stop('Mapping "', name, '" with type "', type, '" not found in package "', where, '"!') } } if (error.missing & !file.exists(as.character(fname))) stop('Mapping "', name, '" not found!') fname <- gsub("/+", "/", fname) if (returnPathOnly) return(fname) filetype <- tolower(file_ext(fname)) if (filetype == "csv") { if (grepl(pattern = ";", x = readLines(fname, 1))) { return(read.csv(fname, sep = ";", stringsAsFactors = FALSE, comment.char = "*")) } else { return(read.csv(fname, sep = ",", stringsAsFactors = FALSE, comment.char = "*")) } } else if (filetype == "rda") { data <- NULL load(fname) if (is.null(data)) stop(fname, " did not contain a object named \"data\"!") return(data) } else if (filetype == "rds") { return(readRDS(fname)) } else { stop("Unsupported filetype \"", filetype, "\"") } }
compare_logical <- function(x, y, paths = c("x", "y"), max_diffs = Inf) { diff_element( encodeString(x), encodeString(y), paths, quote = NULL, max_diffs = max_diffs ) } compare_character <- function(x, y, paths = c("x", "y"), quote = "\"", max_diffs = Inf) { if (multiline(x) || multiline(y)) { x <- split_by_line(x) y <- split_by_line(y) opts <- compare_opts(max_diffs = max_diffs) if (length(x) == 1 && length(y) == 1) { new_compare(compare_by_line1(x, y, paths, opts)) } else { new_compare(compare_by_line(x, y, paths, opts)) } } else { diff_element(x, y, paths, quote = quote, max_diffs = max_diffs) } } compare_numeric <- function(x, y, paths = c("x", "y"), tolerance = default_tol(), max_diffs = Inf) { if (num_equal(x, y, tolerance)) { return(new_compare()) } if (!is.null(dim(x)) && identical(dim(x), dim(y))) { rows <- printed_rows(x, y, paths = paths) out <- diff_rows(rows, paths = paths, max_diffs = max_diffs) if (length(out) > 0) { return(out) } } if (length(x) == length(y)) { digits <- min_digits(x, y) x_fmt <- num_exact(x, digits = digits) y_fmt <- num_exact(y, digits = digits) } else { x_fmt <- as.character(x) y_fmt <- as.character(y) } out <- diff_element( x_fmt, y_fmt, paths, quote = NULL, justify = "right", max_diffs = max_diffs ) if (length(out) > 0) { out } else { glue::glue("{paths[[1]]} != {paths[[2]]} but don't know how to show the difference") } } num_exact <- function(x, digits = 6) { sprintf(paste0("%0.", digits, "f"), x) } min_digits <- function(x, y) { attributes(x) <- NULL attributes(y) <- NULL digits(abs(x - y)) } digits <- function(x) { x <- x[!is.na(x) & x != 0] if (length(x) == 0) { return(0) } scale <- -log10(min(x)) if (scale <= 0) { 0L } else { ceiling(round(scale, digits = 2)) } }
stretch_to_unitspheroid <- function(hellip){ V <- vertices(hellip) tfm <- solve(V) hellip1 <- transform_ellipsoid(hellip, tfm) return(list(hellip1,tfm)) }
reac <- function(A,vector="n",bound=NULL,return.N=FALSE){ if(any(length(dim(A))!=2,dim(A)[1]!=dim(A)[2])) stop("A must be a square matrix") order<-dim(A)[1] if(!isIrreducible(A)){ warning("Matrix is reducible") } else{ if(!isPrimitive(A)) warning("Matrix is imprimitive") } M<-A eigvals<-eigen(M)$values lmax<-which.max(Re(eigvals)) lambda<-Re(eigvals[lmax]) A<-M/lambda if(vector[1]=="n"){ if(!any(bound=="upper",bound=="lower")) stop('Please specify bound="upper", bound="lower" or specify vector') if(bound=="upper"){ reac<-norm(A) if(return.N){ N<-reac*lambda return(list(reac=reac,N=N)) } else{ return(reac) } } if(bound=="lower"){ reac<-.minCS(A) if(return.N){ N<-reac*lambda return(list(reac=reac,N=N)) } else{ return(reac) } } } else{ if(!is.null(bound)) warning("Specification of vector overrides calculation of bound") n0<-vector vector<-n0/sum(n0) reac<-sum(A%*%vector) if(return.N){ N<-reac*sum(n0)*lambda return(list(reac=reac,N=N)) } else{ return(reac) } }}
"ellipse.default" <- function (x, scale = c(1, 1), centre = c(0, 0), level = 0.95, t = sqrt(qchisq(level, 2)), which = c(1, 2), npoints = 100, ...) { names <- c("x", "y") if (is.matrix(x)) { xind <- which[1] yind <- which[2] r <- x[xind, yind] if (missing(scale)) { scale <- sqrt(c(x[xind, xind], x[yind, yind])) if (scale[1] > 0) r <- r/scale[1] if (scale[2] > 0) r <- r/scale[2] } if (!is.null(dimnames(x)[[1]])) names <- dimnames(x)[[1]][c(xind, yind)] } else r <- x r <- min(max(r,-1),1) d <- acos(r) a <- seq(0, 2 * pi, len = npoints) matrix(c(t * scale[1] * cos(a + d/2) + centre[1], t * scale[2] * cos(a - d/2) + centre[2]), npoints, 2, dimnames = list(NULL, names)) }
test_that("SetXSet", { expect_true(setintersect(Set$new(1, 2, 3), Set$new(3:5)) == (Set$new(3))) expect_equal(Set$new(1) & Set$new(), Set$new()) expect_equal(Set$new(1, 2, 3) & Set$new(1), Set$new(1)) expect_equal(Set$new(1) & Set$new(1, 2, 3), Set$new(1)) expect_equal(Tuple$new(1, "a", 2L) & Set$new(elements = letters), Set$new("a")) expect_equal(Multiset$new(1, "a", 2L) & Set$new(elements = letters), Set$new("a")) expect_equal(Set$new(1) & Set$new(1, 2), Set$new(1)) expect_equal(Set$new() & Set$new(), Set$new()) }) test_that("conditionalset", { useUnicode(FALSE) expect_equal( (ConditionalSet$new(function(x) x == 1) & ConditionalSet$new(function(y) y > 1))$strprint(), "{x in V, y in V : x == 1 & y > 1}" ) expect_equal( ConditionalSet$new(function(x) x == 1) & ConditionalSet$new(function(y) y == 1), ConditionalSet$new(function(x) x == 1) ) expect_true((ConditionalSet$new(function(x) x == 0) & Set$new(elements = -2:2))$equals(Set$new(0))) useUnicode(TRUE) }) test_that("fuzzy", { expect_true((FuzzySet$new(1, 0.1, 2, 0.3) & Set$new(elements = 2:5)) == Set$new(2)) }) test_that("interval", { expect_equal(Interval$new(1, 5) & Interval$new(7, 10), Set$new()) expect_equal(Interval$new(1, 5) & Interval$new(2, 10), Interval$new(2, 5)) expect_equal(Interval$new(1, 7) & Interval$new(3, 10), Interval$new(3, 7)) expect_equal(Interval$new(3, 10) & Interval$new(1, 7), Interval$new(3, 7)) }) test_that("mixed", { expect_equal(Set$new(elements = 1:2) & ConditionalSet$new(function(x) x == 3), Set$new()) expect_equal(Set$new("a", 2) & Interval$new(1, 10), Set$new(2)) expect_equal(Interval$new(1, 10) & Set$new("a", 2), Set$new(2)) expect_equal(Interval$new() & Set$new(), Set$new()) expect_equal(Interval$new(1, 5) & Interval$new(2, 3), Interval$new(2, 3)) expect_equal(Interval$new(2, 3) & Interval$new(1, 5), Interval$new(2, 3)) }) test_that("UnionSet", { expect_equal( setintersect( UnionSet$new(list(Set$new(1, 2, 5), Set$new(2, "a", Tuple$new(2)))), Set$new(1, "a", Tuple$new(2), 7) ), Set$new(1, "a", Tuple$new(2)) ) expect_true(setintersect( UnionSet$new(list(Set$new(1, 2, 5), Set$new(4, 3))), UnionSet$new(list(Set$new(1, 2, 5), Set$new(4, 3))) )$equals(Set$new(1:5))) }) test_that("ComplementSet", { expect_equal( ComplementSet$new(Reals$new(), Integers$new()) & Set$new(1.1, 2, 4.5, "a"), Set$new(1.1, 4.5) ) expect_equal(ComplementSet$new(Reals$new(), Integers$new()) & ComplementSet$new(Set$new(1.1, 2.3), Set$new(2)), Set$new(1.1, 2.3)) expect_true(setintersect( ComplementSet$new(Set$new(1, 2, 5), Set$new(4, 3)), UnionSet$new(list(Set$new(1), Set$new(2, 5))) )$equals(Set$new(1, 2, 5))) }) test_that("ProductSet", { useUnicode(FALSE) obj <- setproduct(Set$new(1, 2), Set$new(3, 4), simplify = TRUE) & Set$new(Tuple$new(1, 4)) expect_equal(as.character(obj), "{(1, 4)}") obj <- (Set$new(1, 2) * Set$new(3, 4)) & Set$new(Tuple$new(1, 4), Tuple$new(5, 6)) expect_equal(as.character(obj), "{(1, 4)}") expect_equal(as.character((Set$new(1, 2) * Set$new(3, 4)) & Tuple$new(1, 4)), "{}") expect_message( (Set$new(1, 2) * Set$new(3, 4)) & (Set$new(1, 2) * Set$new(3, 4)), "currently not implemented") useUnicode(TRUE) })
fv_heatmap_box <- function(width = 12, collapsible = T, collapsed = F) { box(title = HTML('<p style="font-size:120%;">Hypothesis Testing</p>'), width = width, solidHeader = T, status = "primary", collapsible = collapsible, collapsed = collapsed, sidebarPanel( width = 3, selectInput('FV_Stats.Overview.ID', 'Algorithms to compare', choices = NULL, selected = NULL, multiple = T), textInput('FV_Stats.Overview.Target', label = RT_TAR_LABEL), textInput('FV_Stats.Overview.Alpha', label = HTML('<p>Significe level \\(\\alpha\\)</p>'), value = 0.01), hr(), selectInput('FV_Stats.Overview.TableFormat', label = 'Select the table format', choices = supported_table_format, selected = supported_table_format[[1]]), downloadButton('FV_Stats.Overview.DownloadTable', label = 'Download the table'), hr(), selectInput('FV_Stats.Overview.Format', label = 'Select the figure format', choices = supported_fig_format, selected = supported_fig_format[[1]]), downloadButton('FV_Stats.Overview.DownloadHeatmap', label = 'Download the heatmap') ), mainPanel( width = 9, HTML_P('The <b>Kolmogorov-Smirnov test</b> is performed on empirical CDFs of running times for each pair of algorithms, in order to determine which algorithm gives a significantly smaller running time distribution. The resulting p-values are arranged in a matrix, where each cell \\((i, j)\\) contains a p-value from the test with the alternative hypothesis: the running time of algorithm \\(i\\) is smaller (thus better) than that of \\(j\\).'), DT::dataTableOutput('FV_Stats.Overview.Pmatrix') ), fluidRow( column( width = 12, HTML('<div style="margin-top: 50px;"></div>'), HTML_P('Decisions of the test, based on the \\(p-\\) value matrix and the \\(\\alpha\\) value, are visualized in a heatmap (<b>left</b>) and a network (<b>right</b>). In each cell (row, column) of the heatmap, the alternative hypothesis is again: the row algorithm has smaller (better) running time than the column. The color indicates: <ul> <li><font color="red">Red: A row is better than the column</font></li> <li><font color="blue">Blue: A row is worse than the column</font></li> <li><font color="grey">Gray: no significant distinction between the row and column</font></li> </ul> On the right subplot, the partial order resulted from the test is visualized as a network, where an arrow from algorithm \\(A\\) to \\(B\\) indicates \\(A\\) is siginicantly better than \\(B\\) with the specified \\(\\alpha\\) value.') ) ), fluidRow( column( width = 6, align = 'center', HTML('<div style="margin-top: 30px;"></div>'), plotlyOutput.IOHanalyzer('FV_Stats.Overview.Heatmap', aspect_ratio = 1) ), column( width = 6, align = 'center', HTML('<div style="margin-top: 30px;"></div>'), plotOutput("FV_Stats.Overview.Graph", height = '70vh') ) ) ) } fv_glicko2_box <- function(width = 12, collapsible = T, collapsed = T) { box(title = HTML('<p style="font-size:120%;">Glicko2-based ranking</p>'), width = width, solidHeader = T, status = "primary", collapsible = collapsible, collapsed = collapsed, sidebarPanel( width = 3, selectInput('FV_Stats.Glicko.ID', 'Algorithms to compare', choices = NULL, selected = NULL, multiple = T), selectInput('FV_Stats.Glicko.Funcid', 'Functions to use', choices = NULL, selected = NULL, multiple = T), selectInput('FV_Stats.Glicko.Dim', 'Dimensions to use', choices = NULL, selected = NULL, multiple = T), textInput('FV_Stats.Glicko.Nrgames', label = "Number of games per (function,dimension) pair", value = 25), actionButton('FV_Stats.Glicko.Create', 'Create / Update Ranking'), hr(), selectInput('FV_Stats.Glicko.Format', label = 'Select the figure format', choices = supported_fig_format, selected = supported_fig_format[[1]]), downloadButton('FV_Stats.Glicko.Download', label = 'Download the figure'), hr(), selectInput('FV_Stats.Glicko.TableFormat', label = 'Select the table format', choices = supported_table_format, selected = supported_table_format[[1]]), downloadButton('FV_Stats.Glicko.DownloadTable', label = 'Download the table') ), mainPanel( width = 9, HTML_P('The <b>Glicko2</b> This procedure ranks algorithms based on a glico2-procedure. Every round, for every function and dimension of the datasetlist, each pair of algorithms competes. This competition samples a random function value for the provided runtime (maximum used among all algorithms). Whichever algorithm has the better function value wins the game. Then, from these games, the glico2-rating is used to determine the ranking.'), HTML_P("The chosen <b>budget values</b> per (function, dimension)-pair are as follows (double click an entry to edit it):"), DT::dataTableOutput("FV_Stats.Glicko.Targets"), hr(), HTML_P("The results of the ranking are:"), plotlyOutput.IOHanalyzer("FV_Stats.Glicko.Candlestick"), DT::dataTableOutput('FV_Stats.Glicko.Dataframe') ) ) }
library("tmle.npvi") log <- Arguments$getVerbose(-8, timestamp=TRUE) dataSet <- "tcga2012brca" path <- file.path("geneData", dataSet) path <- Arguments$getReadablePath(path) files <- list.files(path) nas <- sapply(files, function(ff) { obs <- loadObject(file.path(path, ff)) sum(is.na(obs)) }) files <- files[which(nas==0)] descr <- list(thresh=2e-2, f=identity, flavor="learning", nodes=1, iter=10, cvControl=2, stoppingCriteria=list(mic = 0.001, div = 0.001, psi = 0.01), nMax=30) fileout <- sprintf("%s,tmle.npvi,%s,2014-11-21.rda", dataSet, descr$flavor) mc.cores <- 3 nms <- unlist(strsplit(files, split=".xdr")) TMLE <- parallel::mclapply(seq(along=files), mc.cores=mc.cores, FUN=function(ii) { ff <- files[ii] print(ii) print(ff) pathname <- file.path(path, ff) obs <- loadObject(pathname) nbcov <- ncol(extractW(obs)) if (nbcov==1) { colnames(obs) <- c("Y", "X", "W") } whichSmall <- which(abs(obs[, "X"]) <= descr$thresh) obs[whichSmall, "X"] <- 0 tmle <- try(tmle.npvi(obs=obs, f=descr$f, flavor=descr$flavor, stoppingCriteria=descr$stoppingCriteria, cvControl=descr$cvControl, nMax=descr$nMax)) if (inherits(tmle, "try-error")) { return(attr(tmle, "condition")) } else { return(list(nbcov=nbcov, hist=getHistory(tmle))) } }) names(TMLE) <- nms save(descr, TMLE, file=fileout)
"_PACKAGE" NULL NULL NULL NULL NULL
to_long_tab <- function(reg.coef, d = 3, t.value.col = 3, Pr.col = 4){ if(!class(reg.coef)[1] %in% c("matrix", "data.frame", "coeftest")){stop("reg.coef needs to be a data.frame or an coeftest object")} tryCatch({ if(class(reg.coef)[1] == "coeftest"){ reg.coef <- as.data.frame(`[`(reg.coef)) } if(! "n.r" %in% colnames(reg.coef)){ reg.coef <- data.frame(n.r = 1:nrow(reg.coef), reg.coef) } if(! "prob." %in% colnames(reg.coef)){ t.value.col <- t.value.col + 1 reg.coef <- data.frame(reg.coef, prob. = 2 * (1 - pnorm(abs(reg.coef[ , t.value.col])))) } if(! "sig." %in% colnames(reg.coef)){ df <- reg.coef Pr.col <- Pr.col + 1 reg.coef <- data.frame(df, sig.=ifelse(df[,Pr.col]<0.001, paste0(rep("\x2a", 3), collapse = ""), ifelse(df[,Pr.col]<0.01, paste0(rep("\x2a", 2), collapse = ""), ifelse(df[,Pr.col]<0.05, paste0(rep("\x2a", 1), collapse = ""), ifelse(df[,Pr.col]<0.1,"\xe2\x80\xa0",""))))) } Estimate <- NULL n.r <- NULL var_ <- NULL key <- NULL test <- cbind(var_ = rownames(df), reg.coef[,c(1:3, ncol(reg.coef))]) digits <- function(x,d){ if(class(x)[1]=="numeric") {formatC(x, format = "f", digits = d)} else{x} } test <- data.frame(purrr::map(test, digits, d)) test <- tidyr::unite(test, Estimate, 3, 5, sep="") test[,4] <- paste0("(",test[,4],")") reg.table <- dplyr::arrange(tidyr::gather(test, key, beta, -c(var_, n.r)), n.r)[,c(2,1,4)] even.row <- rep(c(FALSE, TRUE), nrow(reg.table)/2) reg.table$var_ <- as.character(reg.table$var_) reg.table$var_[even.row] <- "" }, error=function(e){cat("ERROR :", conditionMessage(e), "\n")}) return(reg.table) } combine_long_tab <- function(tbl_1, tbl_2, tbl_3=NULL, tbl_4=NULL, tbl_5=NULL, tbl_6=NULL, tbl_7=NULL, tbl_8=NULL, tbl_9=NULL, tbl_10=NULL, tbl_11=NULL, tbl_12=NULL, tbl_13=NULL, tbl_14=NULL, tbl_15=NULL, tbl_16=NULL, tbl_17=NULL, tbl_18=NULL, tbl_19=NULL, tbl_20=NULL) { tryCatch({ all_tbls <- list(tbl_1,tbl_2,tbl_3,tbl_4,tbl_5,tbl_6,tbl_7,tbl_8,tbl_9,tbl_10,tbl_11,tbl_12,tbl_13,tbl_14,tbl_15,tbl_16,tbl_17,tbl_18,tbl_19,tbl_20) non_empty <- length(all_tbls) - sum(unlist(purrr::map(all_tbls, is.null))) list_tbls <- all_tbls[1:non_empty] for(i in 1:length(list_tbls)){ list_tbls[[i]]$var_[seq(2, nrow(list_tbls[[i]]), by = 2)] <- paste0(list_tbls[[i]]$var_[seq(1, nrow(list_tbls[[i]]), by = 2)],"s.e.") list_tbls[[i]]$n.r <- NULL } main.table <- purrr::reduce(list_tbls, dplyr::full_join,by=c("var_")) main.table[is.na(main.table)] <- "" main.table$var_[seq(2, nrow(main.table), by = 2)] <- "" names(main.table) <- c("Variables", paste0("Model ", 0:(non_empty-1))) }, error=function(e){cat("ERROR :", conditionMessage(e), "\n")}) return(main.table)} compare_models <- function(model1, model2, model3=NULL, model4=NULL, model5=NULL, model6=NULL, model7=NULL, model8=NULL, model9=NULL, model10=NULL, model11=NULL, model12=NULL, model13=NULL, model14=NULL, model15=NULL, model16=NULL, model17=NULL, model18=NULL, model19=NULL, model20=NULL, likelihood.only = FALSE, round.digit = 3, main.effect.only = NULL, intn.effect.only = NULL){ tryCatch({ list_all <- list(model1, model2, model3, model4, model5, model6, model7, model8, model9, model10, model11, model12, model13, model14, model15, model16, model17, model18, model19, model20) non_empty <- length(list_all) - sum(unlist(purrr::map(list_all, is.null))) model_list <- list_all[1:non_empty] if(likelihood.only == TRUE){ compare.df <- c("LogLikelihood", round(unlist(purrr::map(model_list, logLik)), round.digit)) }else { n <- non_empty compare <- if(n==2){ suppressWarnings(suppressMessages(anova(model1,model2)))}else if(n==3){ suppressWarnings(suppressMessages(anova(model1,model2,model3)))}else if(n==4){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4)))}else if(n==5){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5)))}else if(n==6){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6)))}else if(n==7){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7)))}else if(n==8){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8)))}else if(n==9){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9)))}else if(n==10){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10)))}else if(n==11){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11)))}else if(n==12){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11,model12)))}else if(n==13){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11,model12,model13)))}else if(n==14){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11,model12,model13,model14)))}else if(n==15){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11,model12,model13,model14,model15)))}else if(n==16){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11,model12,model13,model14,model15,model16)))}else if(n==17){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11,model12,model13,model14,model15,model16,model17)))}else if(n==18){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11,model12,model13,model14,model15,model16,model17,model18)))}else if(n==19){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11,model12,model13,model14,model15,model16,model17,model18,model19)))}else if(n==20){ suppressWarnings(suppressMessages(anova(model1,model2,model3,model4,model5,model6,model7,model8,model9,model10,model11,model12,model13,model14,model15,model16,model17,model18,model19,model20)))} Chisq <- NULL sig <- NULL Delta_F <- NULL if(!is.null(main.effect.only)){ for(i in main.effect.only){ compare[i,] <- anova(model_list[[main.effect.only[1]-2]], model_list[[i]])[2,] } } if(!is.null(intn.effect.only)){ for(i in intn.effect.only){ compare[i,] <- if(!is.null(main.effect.only)){anova(model_list[[i-length(main.effect.only)]], model_list[[i]])[2,] }else{ anova(model_list[[intn.effect.only[1] - 1]], model_list[[i]])[2,] } } } ch <- function(x){as.character(x)} convert.sig <- function(df){ifelse(df<0.001, paste0(rep("\x2a", 3), collapse = ""), ifelse(df<0.01, paste0(rep("\x2a", 2), collapse = ""), ifelse(df<0.05, paste0(rep("\x2a", 1), collapse = ""), ifelse(df<0.1,"\xe2\x80\xa0",""))))} dg <- function(x)formatC(x, format = "f", digits = 3) compare.df <- if(class(model1)[1]=="negbin"){ data.frame(AIC=ch(t(dg(unlist(purrr::map(model_list, MuMIn::AICc))))), Log_Likelihood=ch(t(dg(compare[3][[1]]))), Chisq=ch(t(dg(compare[7][[1]]))), sig=ch(t(convert.sig(compare[8][[1]])))) %>% unite(Chisq,Chisq,sig,sep="") %>% t() }else if(class(model1)[1]=="lmerMod"){ data.frame(AIC=ch(t(dg(unlist(purrr::map(model_list, MuMIn::AICc))))), Log_Likelihood=ch(t(dg(compare[4][[1]]))), Chisq=ch(t(dg(compare[6][[1]]))), sig=ch(t(convert.sig(compare[8][[1]])))) %>% unite(Chisq,Chisq,sig,sep="") %>% t() }else if(class(model1)[1]=="lm"){ data.frame(R_squared=ch(t(dg(unlist(purrr::map(model_list, function(df){summary(df)$r.squared}))))), Adj_R_squared=ch(t(dg(unlist(purrr::map(model_list, function(df){summary(df)$adj.r.squared}))))), Delta_F=ch(t(dg(compare[5][[1]]))), sig=ch(t(convert.sig(compare[6][[1]])))) %>% tidyr::unite(Delta_F,Delta_F,sig,sep="") %>% t() }else{ data.frame(AIC=ch(t(dg(unlist(purrr::map(model_list, MuMIn::AICc))))), Log_Likelihood=ch(t(dg(compare[1][[1]]))),Chisq=ch(t(dg(compare[2][[1]]))), sig=ch(t(convert.sig(compare[4][[1]])))) %>% unite(Chisq,Chisq,sig,sep="") %>% t() } compare.df[nrow(compare.df),1] <- "" compare.df <- data.frame(Variables=row.names(compare.df),compare.df) } names(compare.df) <- c("Variables", paste0("Model ", 0:(non_empty-1))) }, error=function(e){cat("ERROR :", conditionMessage(e), "\n")}) return(compare.df) }
library(profvis) library(dplyr) library(vctrs) library(bench) bench_mean <- function(n = 1e6, ngroups = 1000) { args <- list(n = n, ngroups = ngroups) main_length <- callr::r(function(n, ngroups) { library(dplyr, warn.conflicts = FALSE) library(purrr) library(vctrs) df <- tibble(x = rnorm(n), g = sample(rep(1:ngroups, n / ngroups))) %>% group_by(g) bench::mark(summarise(df, a = length(x))) %>% mutate(branch = "main", fun = "length", n = n, ngroups = ngroups) %>% select(branch, fun, n, ngroups, min:last_col()) }, args = args) main_internal <- callr::r(function(n, ngroups) { library(dplyr, warn.conflicts = FALSE) library(purrr) library(vctrs) df <- tibble(x = rnorm(n), g = sample(rep(1:ngroups, n / ngroups))) %>% group_by(g) bench::mark(summarise(df, a = .Internal(mean(x)))) %>% mutate(branch = "main", fun = ".Internal(mean(.))", n = n, ngroups = ngroups) %>% select(branch, fun, n, ngroups, min:last_col()) }, args = args) main_mean <- callr::r(function(n, ngroups) { library(dplyr, warn.conflicts = FALSE) library(purrr) library(vctrs) df <- tibble(x = rnorm(n), g = sample(rep(1:ngroups, n / ngroups))) %>% group_by(g) bench::mark(summarise(df, a = mean(x))) %>% mutate(branch = "main", fun = "mean(.)", n = n, ngroups = ngroups) %>% select(branch, fun, n, ngroups, min:last_col()) }, args = args) released_internal <- callr::r(function(n, ngroups) { library(dplyr, warn.conflicts = FALSE) library(purrr) library(vctrs) df <- tibble(x = rnorm(n), g = sample(rep(1:ngroups, n / ngroups))) %>% group_by(g) bench::mark(summarise(df, a = .Internal(mean(x)))) %>% mutate(branch = "0.8.3", fun = ".Internal(mean(.))", n = n, ngroups = ngroups) %>% select(branch, fun, n, ngroups, min:last_col()) }, args = args, libpath = "../bench-libs/0.8.3") released_hybrid_mean <- callr::r(function(n, ngroups) { library(dplyr, warn.conflicts = FALSE) library(purrr) library(vctrs) df <- tibble(x = rnorm(n), g = sample(rep(1:ngroups, n / ngroups))) %>% group_by(g) bench::mark(summarise(df, a = mean(x))) %>% mutate(branch = "0.8.3", fun = "hybrid mean(.)", n = n, ngroups = ngroups) %>% select(branch, fun, n, ngroups, min:last_col()) }, args = args, libpath = "../bench-libs/0.8.3") released_nonhybrid_mean <- callr::r(function(n, ngroups) { library(dplyr, warn.conflicts = FALSE) library(purrr) library(vctrs) mean2 <- function(x, ...) UseMethod("mean") df <- tibble(x = rnorm(n), g = sample(rep(1:ngroups, n / ngroups))) %>% group_by(g) bench::mark(summarise(df, a = mean2(x))) %>% mutate(branch = "0.8.3", fun = "mean2(.)", n = n, ngroups = ngroups) %>% select(branch, fun, n, ngroups, min:last_col()) }, args = args, libpath = "../bench-libs/0.8.3") as_tibble(vec_rbind(main_length, main_internal, main_mean, released_internal, released_hybrid_mean, released_nonhybrid_mean)) %>% select(branch:ngroups, median, mem_alloc, n_gc) } bench_mean(1e6, 10) bench_mean(1e6, 100000) bench_mean(1e7, 10) bench_mean(1e7, 1000000)
library(citrus) library(testthat) library(dplyr) preprocessed_data <- citrus::preprocessed_data hyperparameters <- list(dependent_variable = 'response', min_segmentation_fraction = 0.05, number_of_segments = 6, print_plot = FALSE, print_safety_check=20, saveoutput = FALSE) model <- citrus::tree_segment(preprocessed_data, hyperparameters) model <- citrus::tree_segment_prettify(model,print_plot = T) model <- citrus::tree_abstract(model, preprocessed_data) output <- citrus::output_table(preprocessed_data,model) test_that("Number of Columns", { expect_equal(ncol(output), 16) }) test_that("Number of Rows", { expect_equal(nrow(output), 6) }) test_that("No nulls", { expect_equal(ncol(output[complete.cases(output), ]), 16) })
.wrsi <- function(Y, X) { Pavail <- colSums(X) / sum(X) Xu <- X * Y Pused <- colSums(Xu) / sum(Xu) Pw <- colSums(Xu) / colSums(X) WRSI <- Pused / Pavail cbind( WRSI=WRSI, zWRSI=log(WRSI), rWRSI=(exp(2 * log(WRSI)) - 1)/(1 + exp(2 * log(WRSI))), Pused=Pused, Pavail=Pavail, Pw=Pw, u=colSums(Xu), a=colSums(X)) }
embed_timeseries <- function(timeseries, embedding.dimension) { if (missing(timeseries)) stop("Provide a time series.", call. = FALSE) if (!is.xts(timeseries) && class(timeseries) == "numeric") { timeseries <- xts(timeseries, order.by = seq.Date(from = Sys.Date(), by = 1, length.out = length(timeseries))) } ts.index <- index(timeseries)[-(1:(embedding.dimension-1))] ts.embed <- stats::embed(timeseries, dimension = embedding.dimension) colnames(ts.embed) <- c('target', paste0('Tm', 1:(embedding.dimension-1))) df <- as.data.frame(xts(ts.embed, order.by = ts.index)) df } soft.completion <- function(x) { if ("data.frame" %in% class(x)) x <- as.matrix(x) as.data.frame(complete(x, softImpute(x))) }
`ensemble.analogue.object` <- function( ref.location, future.stack, current.stack, name="reference1", method="mahal", an=10000, probs=c(0.025, 0.975), weights=NULL, z=2) { target.values <- as.numeric(raster::extract(future.stack, ref.location)) names(target.values) <- names(future.stack) if ((method %in% c("mahal", "quantile", "sd")) == F) {method <- "none"} if (method == "mahal") { a <- dismo::randomPoints(current.stack, n=an, p=NULL, excludep=F) a <- data.frame(a) background.data <- raster::extract(current.stack, a) background.data <- data.frame(background.data) TrainValid <- complete.cases(background.data) background.data <- background.data[TrainValid,] cov.mahal <- cov(background.data) out <- list(name=name, ref.location=ref.location, stack.name=future.stack@title, method=method, target.values=target.values, cov.mahal=cov.mahal) return(out) } if (method == "quantile") { lower.interval <- data.frame(t(quantile(current.stack, probs[1]))) upper.interval <- data.frame(t(quantile(current.stack, probs[2]))) norm.values <- as.numeric(upper.interval - lower.interval) } if (method == "sd") { norm.values <- raster::cellStats(current.stack, stat="sd") } if (method == "none") { norm.values <- rep(1, length=length(names(current.stack))) } names(norm.values) <- names(current.stack) zero.norm.values <- which(norm.values == 0) if(length(zero.norm.values) > 0) { cat(paste("WARNING: some of the normalizing values were zero", "\n\n", sep="")) print(names(zero.norm.values)) cat(paste("\n", "respective values were now set to one", "\n", sep="")) norm.values[names(norm.values) %in% names(zero.norm.values)] <- 1 } if (is.null(weights)==T || all.equal(names(weights), names(current.stack))==F) { paste("WARNING: length of weights is different from number of variables in current RasterStack", "\n", sep="") weight.values <- rep(1, raster::nlayers(current.stack)) names(weight.values) <- names(current.stack) }else{ weight.values <- weights } weight.values <- weight.values / sum(weight.values) out <- list(name=name, ref.location=ref.location, stack.name=future.stack@title, method=method, target.values=target.values, norm.values=norm.values, weights=weight.values, z=z) return(out) } `ensemble.analogue` <- function( x=NULL, analogue.object=NULL, analogues=1, RASTER.object.name=analogue.object$name, RASTER.stack.name=x@title, RASTER.format="raster", RASTER.datatype="INT2S", RASTER.NAflag=-32767, KML.out=T, KML.blur=10, KML.maxpixels = 100000, limits=c(1, 5, 20, 50), limit.colours=c('red', 'orange', 'blue', 'grey'), CATCH.OFF=FALSE ) { .BiodiversityR <- new.env() if(is.null(x) == T) {stop("value for parameter x is missing (RasterStack object)")} if(inherits(x, "RasterStack") == F) {stop("x is not a RasterStack object")} if (is.null(analogue.object) == T) {stop("value for parameter analogue.object is missing (hint: use the ensemble.analogue.object function)")} if (KML.out==T && raster::isLonLat(x)==F) { cat(paste("\n", "NOTE: not possible to generate KML files as Coordinate Reference System (CRS) of stack ", x@title , " is not longitude and latitude", "\n", sep = "")) KML.out <- FALSE } predict.analogue <- function(object=analogue.object, newdata=newdata) { method <- object$method if (method == "mahal") { centroid <- object$target.values cov.mahal <- object$cov.mahal p <- mahalanobis(newdata, center=centroid, cov=cov.mahal) p <- as.numeric(p) return(p) }else{ targetdata <- object$target.values normdata <- object$norm.values weightdata <- object$weights z <- object$z out <- newdata for (i in 1:ncol(out)) { out[,i] <- as.numeric(out[,i]) - as.numeric(targetdata[as.numeric(na.omit(match(names(out)[i], names(targetdata))))]) out[,i] <- abs(out[,i]) out[,i] <- as.numeric(out[,i]) / as.numeric(normdata[as.numeric(na.omit(match(names(out)[i], names(normdata))))]) out[,i] <- (out[,i]) ^ z out[,i] <- as.numeric(out[,i]) * as.numeric(weightdata[as.numeric(na.omit(match(names(out)[i], names(weightdata))))]) } p <- rowSums(out) z2 <- 1/z p <- p ^ z2 return(p) } } dir.create("ensembles", showWarnings = F) dir.create("ensembles/analogue", showWarnings = F) if (KML.out == T) { dir.create("kml", showWarnings = F) dir.create("kml/analogue", showWarnings = F) } if(length(x@title) == 0) {x@title <- "stack1"} stack.title <- RASTER.stack.name if (gsub(".", "_", stack.title, fixed=T) != stack.title) {cat(paste("\n", "WARNING: title of stack (", stack.title, ") contains '.'", "\n\n", sep = ""))} rasterfull <- paste("ensembles/analogue/", RASTER.object.name, "_", stack.title , "_analogue", sep="") kmlfull <- paste("kml/analogue/", RASTER.object.name, "_", stack.title , "_analogue", sep="") if (CATCH.OFF == F) { tryCatch(analogue.raster <- raster::predict(object=x, model=analogue.object, fun=predict.analogue, na.rm=TRUE, filename=rasterfull, progress='text', overwrite=T, format=RASTER.format), error= function(err) {print(paste("prediction of analogue raster failed"))}, silent=F) }else{ analogue.raster <- raster::predict(object=x, model=analogue.object, fun=predict.analogue, na.rm=TRUE, filename=rasterfull, progress='text', overwrite=T, format=RASTER.format) } analogue.raster <- round(analogue.raster, digits=8) raster::setMinMax(analogue.raster) print(analogue.raster) raster::writeRaster(analogue.raster, filename="working.grd", overwrite=T) working.raster <- raster::raster("working.grd") names(working.raster) <- paste(RASTER.object.name, "_", stack.title , "_", analogue.object$method, "_z", analogue.object$z, "_analogue", sep="") raster::writeRaster(working.raster, filename=rasterfull, progress='text', overwrite=T, format=RASTER.format) limits.data <- data.frame(limits) limits.data <- data.frame(cbind(limits, limits)) names(limits.data) <- c("threshold", "count") freqs <- raster::freq(analogue.raster, digits=8) for (i in 1:length(limits)) { j <- 1 while (sum(freqs[1:j, 2]) < limits[i]) {j <- j+1} limits.data[i, 1] <- freqs[j, 1] limits.data[i, 2] <- sum(freqs[1:j, 2]) } cat(paste("\n", "suggested breaks in colour scheme", "\n", sep="")) print(limits.data) if (KML.out == T) { breaks1 <- c(raster::minValue(analogue.raster), limits.data[,1]) raster::KML(working.raster, filename=kmlfull, overwrite=T, blur=KML.blur, col=limit.colours, breaks=breaks1) } j <- 1 while (sum(freqs[1:j, 2]) < analogues) {j <- j+1} threshold <- freqs[j, 1] cat(paste("\n", "Threshold (n =", j, "): ", threshold, "\n", sep="")) index1 <- which(analogue.raster[,] <= threshold) pres1 <- raster::xyFromCell(analogue.raster, index1) vars <- length(names(x)) output1 <- data.frame(array(dim=c(length(index1), 5+vars))) output2 <- data.frame(array(dim=c(1, 5+vars))) names(output1) <- names(output2) <- c("model", "method", "lon", "lat", "distance", names(x)) output1[, 1] <- rep(analogue.object$stack.name, nrow(output1)) output2[1, 1] <- analogue.object$stack.name if (analogue.object$method == "mahal") { method1 <- "mahal" }else{ method1 <- paste(analogue.object$method, "_z_", analogue.object$z, sep="") } output1[, 2] <- rep(method1, nrow(output1)) output1[, c(3:4)] <- pres1 point.data1 <- raster::extract(x, pres1) output1[, c(6:(5+vars))] <- point.data1 point.data2 <- raster::extract(analogue.raster, pres1) output1[, 5] <- point.data2 output1 <- output1[order(output1[,"distance"], decreasing=F),] output2[1, 1] <- analogue.object$stack.name output2[1, 2] <- "target" output2[1 ,3] <- as.numeric(analogue.object$ref.location[,1]) output2[1 ,4] <- as.numeric(analogue.object$ref.location[,2]) output2[, c(6:(5+vars))] <- analogue.object$target.values output3 <- rbind(output2, output1) cat(paste("\n", "analogue raster provided in folder: ", getwd(), "//ensembles//analogue", "\n\n", sep="")) return(output3) }
get_remaining_quota <- function(api_key) { query = list(apikey = api_key) response <- GET("https://datenservice.kof.ethz.ch/api/v1/main/remainingquota", query = query) if(response$status_code == 200) { fromJSON(content(response, as="text"))$quota } else { stop(sprintf("The API returned a status code of %d. Are you sure you provided a valid API key?", response$status_code)) } }
add_rugged_terrain <- function(data) { if (length(attributes(data)$ps_data_type) > 0 && attributes(data)$ps_data_type %in% c("dyad_year", "leader_dyad_year")) { if (length(attributes(data)$ps_system) > 0 && attributes(data)$ps_system == "cow") { rugged %>% select(-.data$gwcode) -> hold_this hold_this %>% left_join(data, ., by=c("ccode1"="ccode")) %>% rename(rugged1 = .data$rugged, newlmtnest1 = .data$newlmtnest) %>% left_join(., hold_this, by=c("ccode2"="ccode")) %>% rename(rugged2 = .data$rugged, newlmtnest2 = .data$newlmtnest) -> data return(data) } else { rugged %>% select(-.data$ccode) -> hold_this hold_this %>% left_join(data, ., by=c("gwcode1"="gwcode")) %>% rename(rugged1 = .data$rugged, newlmtnest1 = .data$newlmtnest) %>% left_join(., hold_this, by=c("gwcode2"="gwcode")) %>% rename(rugged2 = .data$rugged, newlmtnest2 = .data$newlmtnest) -> data return(data) } } else if (length(attributes(data)$ps_data_type) > 0 && attributes(data)$ps_data_type %in% c("state_year", "leader_year")) { if (length(attributes(data)$ps_system) > 0 && attributes(data)$ps_system == "cow") { rugged %>% select(-.data$gwcode) %>% left_join(data, .) -> data return(data) } else { rugged %>% select(-.data$ccode) %>% left_join(data, .) -> data return(data) } } else { stop("add_rugged_terrain() requires a data/tibble with attributes$ps_data_type of state_year or dyad_year. Try running create_dyadyears() or create_stateyears() at the start of the pipe.") } }
test_that('stack modelling function', { data(Env) data(Occurrences) SSDM <- stack_modelling(c('CTA', 'SVM'), Occurrences, Env, rep = 1, Xcol = 'LONGITUDE', Ycol = 'LATITUDE', Spcol = 'SPECIES', ensemble.thresh = 0, verbose = FALSE, cores = 0) expect_is(SSDM, 'Stacked.SDM') })
pwchisq <- function(x, lambda = 1, nu = 1, delta = 0, mode = 1, maxit1 = 100000, eps = 10^(-10)) { util_check_nonneg(x) util_check_nonneg(lambda) util_check_nonneg(nu) util_check_nonneg(delta) util_check_nonneg(mode) util_check_gt(maxit1, 1) util_check_nonneg(eps) if (length(lambda) != length(nu) || length(nu) != length(delta)) { stop("'lambda', 'nu', and 'delta' should have the same length.") } res <- pwchisqCpp( q = as.double(x), lambda = as.vector(lambda), mult = as.vector(nu), delta = as.vector(delta), n = as.integer(length(lambda)), mode = as.double(mode), maxit = as.integer(maxit1), eps = as.double(eps) ) if (res$ifault == -1 || res$ifault == 2) { warning("Input value(s) is not appropriate.") } else if (res$ifault == 4) { warning("The required accuracy could not be achived in 'maxit1' iterations.") } else if (res$ifault == 1 || res$ifault == 3 || res$ifault == 5 || res$ifault == 6 || res$ifault == 9 || res$ifault == 10) { warning("The estimate of the probability has a problem (e.g., prob < 0, prob > 1, etc.).") } return(res$prob) }
MixtureLogitAFT=function(formula,eventprobreg=~1,locationreg=~1,scalereg=~1,var.entry,var.mixturetype=NULL,var.weight=NULL, data,time.origin=0,shape=NULL){ cat("Running ...") time1=Sys.time() call=match.call() shapereg=~1 out=parameterize(formula,eventprobreg,locationreg,scalereg,shapereg,data,shape,var.entry) dataset=out$dataset covariates=out$covariates var.centime=out$var.centime var.truntime=out$var.truntime is.reg=out$is.reg x=out$x fix.par=out$fix.par par=out$par is.interval=out$is.interval is.truncation=out$is.truncation minmax.time=out$minmax.time var.obsweight=var.weight is.weight=F; if(!is.null(var.obsweight)) is.weight=T if(is.null(dataset)) return("Error: data !!") if(is.null(var.centime)) return("Error: survival time !!") if(any(is.na(match(var.centime,names(dataset))))) return("Error: survival time !!") if(!is.null(var.truntime)){ if(any(is.na(match(var.truntime,names(dataset))))) return("Error: truncation time !!") } if(!is.null(covariates$names[-1])){ if(any(is.na(match(covariates$names[-1],names(dataset))))) return("Error: covariates !!") } if(!is.null(var.mixturetype)){ if(any(is.na(match(var.mixturetype,names(dataset))))) return("Error: variable of mixture type !!") } if(!is.null(var.obsweight)){ if(any(is.na(match(var.obsweight,names(dataset))))) return("Error: variable of observation weight !!") } dataset=dataset[,c(var.centime,var.truntime,covariates$names[-1],var.mixturetype,var.obsweight)] dataset=obsKeep(dataset,covariates,var.centime,var.truntime) num.obs=nrow(dataset) if (length(covariates$names[-1])>0){ groups.obs=groupObs(dataset[,covariates$names[-1]],covariates$levels) }else{ groups.obs=list() groups.obs$labels="0";groups.obs$levels=0;groups.obs$levelsTrue=T;groups.obs$obs=rep(0,dim(dataset)[1]) } if(length(covariates$labels)==length(groups.obs$labels))groups.obs$labels=covariates$labels groups.obs$total.obs=numeric(length(groups.obs$levels)) groups.obs$case.obs=numeric(length(groups.obs$levels)) buffer.dataset=cbind(dataset[,var.centime[3]],groups.obs$obs) total.obs=table(buffer.dataset[,2]) groups.obs$total.obs[match(as.numeric(names(total.obs)),groups.obs$levels)]=total.obs index=which(buffer.dataset[,1] != 2) if(length(index)>0) buffer.dataset=buffer.dataset[index,] case.obs=table(buffer.dataset[,2]) groups.obs$case.obs[match(as.numeric(names(case.obs)),groups.obs$levels)]=case.obs levels.mixturetype=NULL if(!is.null(var.mixturetype)){ buffer=unique(cbind(dataset[,var.mixturetype],groups.obs$obs)) buffer=buffer[order(buffer[,2]),] if(is.null(dim(buffer))){ buffer=buffer[!is.na(buffer[2])] levels.mixturetype=buffer[1] }else{ buffer=buffer[!is.na(buffer[,2]),] levels.mixturetype=buffer[,1] } } weight=rep(1,num.obs) if(!is.null(var.obsweight)) weight=dataset[,var.obsweight] if(!is.null(var.mixturetype)){ mtype=dataset[,var.mixturetype] }else{ if(is.reg$beta==F){ mtype=rep(1,num.obs) }else{ mtype=rep(2,num.obs) } } var=var.centime if(is.truncation) var=c(var,var.truntime) survtime=dataset[,var] index=which(survtime[,var.centime[3]]==2) if(length(index)>0) survtime[index,var.centime[2]]=NA index=which(survtime[,var.centime[3]]==4) if(length(index)>0) survtime[index,var.centime[1]]=NA if(is.truncation){ index=which(survtime[,var.truntime[3]]==2) if(length(index)>0) survtime[index,var.truntime[2]]=NA index=which(survtime[,var.truntime[3]]==4) if(length(index)>0) survtime[index,var.truntime[1]]=NA } var=c(var.centime[1:2]) if(is.truncation) var=c(var,var.truntime[1:2]) survtime[,var]=survtime[,var]-time.origin survtime[,var]=log(survtime[,var]) is.fix.par=list() if (length(covariates$q) != length(fix.par$q)){ fix.par$q=NULL } is.fix.par$q = !is.null(fix.par$q) survtime.turnbull=cbind(survtime,weight=weight) index=which(survtime.turnbull[,3]==1) if(length(index)>0) survtime.turnbull[index,2]=survtime.turnbull[index,1] if (is.truncation){ turnbullEst=turnbullR(dataset=survtime.turnbull,var.centime=names(survtime.turnbull)[1:3],var.truntime=names(survtime.turnbull)[4:6], var.obsweight=names(survtime.turnbull)[7],is.graph=F,tolerance=1e-3) TurnbullEST=condition.turnbullR(turnbullEst,is.graph=F) }else{ turnbullEst=turnbullR(dataset=survtime.turnbull,var.centime=names(survtime.turnbull)[1:3],var.truntime=NULL, var.obsweight=names(survtime.turnbull)[4],is.graph=F,tolerance=1e-3) TurnbullEST=condition.turnbullR(turnbullEst,is.graph=F) } TurnbullEST$p0=1-turnbullEst[1,"survival"] TurnbullEST$p2=turnbullEst[nrow(turnbullEst)-1,"survival"] if (TurnbullEST$SkewY > 0) TurnbullEST$SkewY=-1 else TurnbullEST$SkewY=1 y=list(E=NULL,Var=NULL,Skew=NULL) y[1:3]=TurnbullEST[2:4] if (is.reg$beta){ par$beta[1]=log((1-TurnbullEST$p0-TurnbullEST$p2)/TurnbullEST$p2) } w=list(E=NULL,Var=NULL) w$E=(log(y$Skew^2)+digamma(y$Skew^{-2}))/y$Skew w$Var=trigamma(y$Skew^{-2})/y$Skew^2 par$alpha[1]=log(sqrt(y$Var/w$Var)) par$gamma[1]=y$E-w$E*exp(par$alpha[1]) par$q[1]=y$Skew if (is.fix.par$q) par$q=fix.par$q par.nfix=NULL if (is.reg$beta){ par.nfix=c(par.nfix,par$beta) } par.nfix=c(par.nfix,par$gamma,par$alpha) if (!is.fix.par$q){ par.nfix=c(par.nfix,par$q) } options(warn=-1) convergence=1 times.call=1; times.stop=3 while(convergence!=0 & times.call<=times.stop){ convergence=0 parscale=rep(1^(times.call-1),length(par.nfix)) cat(" ...") est=optim(par=par.nfix,fn=LLF,gr=GLLF,method="BFGS",control=list(parscale=parscale,reltol=1e-16),hessian=F, par.all=par,is.fix.par=is.fix.par,survtime=survtime,x=x,is.reg=is.reg,weight=weight,mtype=mtype) par.nfix=est$par gradient=-GLLF(par.nfix,par,is.fix.par,survtime,x,is.reg,weight,mtype) hessian=HLLF(par.nfix,par,is.fix.par,survtime,x,is.reg,weight,mtype) COV=NULL std=rep(NA,length(par.nfix)) if(!any(is.na(hessian) | abs(hessian)==Inf)){ if(det(hessian)>0){ COV=solve(hessian,tol=1e-25) std=sqrt(diag(COV)) } } if(est$convergence!=0){ convergence=est$convergence }else if(any(is.na(hessian) | abs(hessian)==Inf)){ convergence=2 }else if(det(hessian)<=0){ convergence=3 }else if(any(is.na(std))){ convergence=4 }else if(max(abs(gradient))>1e-03){ convergence=5 } times.call=times.call+1 } cat("\n") if(convergence==0){ cat("Convergence"); cat("\n") }else{ cat("Not convergence"); cat("\n") } chisq=rep(NA,length(par.nfix)) pvalue=rep(NA,length(par.nfix)) if(all(!is.na(std))){ chisq=(par.nfix/std)^2 pvalue=1-pchisq(chisq,1) } LogLF=-est$value AIC=2.0*(-LogLF+length(par.nfix)) start=1 if (is.reg$beta){ len=length(par$beta); par$beta=par.nfix[seq(start,start+len-1)]; start=start+len } len=length(par$gamma); par$gamma=par.nfix[seq(start,start+len-1)]; start=start+len len=length(par$alpha); par$alpha=par.nfix[seq(start,start+len-1)]; start=start+len if (!is.fix.par$q){ len=length(par$q); par$q=par.nfix[seq(start,start+len-1)]; start=start+len } residuals.data=residualData(par,survtime,x) index=which(residuals.data[,3]==1) if(length(index)>0) residuals.data[index,2]=residuals.data[index,1] if(is.truncation){ index=which(residuals.data[,4]==-Inf) if(length(index)>0){ residuals.data[index,4]=NA residuals.data[index,6]=0 } } vars=c(covariates$main,var.obsweight) if(length(vars)>0){ res.dataset=cbind(residuals.data,dataset[vars]) }else{ res.dataset=residuals.data } index=which(res.dataset[,3]==2) if(length(index)>0) res.dataset[index,3]=0 index=which(res.dataset[,3]==4) if(length(index)>0) res.dataset[index,3]=2 groups.obs=groups.obs[c("labels","total.obs","case.obs")] time2=Sys.time() run.time=time2-time1 run.time=paste(as.numeric(run.time),units(run.time),sep=" ") cat(run.time); cat("\n") MixtureRegEST=list(call=call,convergence=convergence,covariates=covariates,time.origin=time.origin,is.truncation=is.truncation,minmax.time=minmax.time, is.interval=is.interval,is.weight=is.weight,fix.par=fix.par,par=par,parest=par.nfix, std=std,chisq=chisq,pvalue=pvalue,gradient=gradient,LLF=LogLF,AIC=AIC,COV=COV,groups.obs=groups.obs,mixturetype=levels.mixturetype, res.dataset=res.dataset,run.time=run.time,method="mixtureLogitAFT") class(MixtureRegEST) = "mixture" return(MixtureRegEST) } if(F){ par.all=par print(LLF(par.nfix,par.all,is.fix.par,survtime,x,is.reg,weight,mtype),16) GLLF(par.nfix,par.all,is.fix.par,survtime,x,is.reg,weight,mtype) HLLF(par.nfix,par.all,is.fix.par,survtime,x,is.reg,weight,mtype) }
context("RateCardService") skip("Reduce Total Test Runtime") rdfp_options <- readRDS("rdfp_options.rds") options(rdfp.network_code = rdfp_options$network_code) options(rdfp.httr_oauth_cache = FALSE) options(rdfp.application_name = rdfp_options$application_name) options(rdfp.client_id = rdfp_options$client_id) options(rdfp.client_secret = rdfp_options$client_secret) dfp_auth(token = "rdfp_token.rds") test_that("dfp_createRateCards", { expect_true(TRUE) }) test_that("dfp_getRateCardsByStatement", { request_data <- list('filterStatement'=list('query'="WHERE status='ACTIVE'")) dfp_getRateCardsByStatement_result <- dfp_getRateCardsByStatement(request_data) expect_is(dfp_getRateCardsByStatement_result, "data.frame") }) test_that("dfp_performRateCardAction", { expect_true(TRUE) }) test_that("dfp_updateRateCards", { expect_true(TRUE) })
intw1 <- function(z) {c0 <- -0.1351788; PsiSw(z)*dlweibul(z+c0) }
library(Rcpp); get.context <- function (file,start){ cpp_get_context(file, start, length(start)); };
regSeries <- function(nVar, dMax, series, pReg = NULL) { if (is.vector(series)) { series <- t(series) } if (is.data.frame(series)) { series <- as.matrix(series) } if (is.null(pReg)) { if (is.null(dMax)) { stop("'dMax' or 'pReg' is required.") } pReg <- regOrd(nVar,dMax) } else { if (is.vector(pReg)) { pReg <- as.matrix(pReg) } } RpFull <- NULL for (i in 1:nVar) { Rp <- c() for (k in 1:dim(pReg)[2]) { R1 <- series[,i]^pReg[i,k] Rp <- cbind(Rp, R1) } if (is.null(RpFull)) { RpFull <- Rp } else { RpFull <- RpFull * Rp } } RpFull }
summary.OBsProb <- function (object, nTop = 10, digits = 3, ...) { nFac <- ncol(object$X) - object$blk cat("\n Calculations:\n") calc <- c(object$N, object$COLS, object$BLKS, object$MXFAC, object$MXINT, object$mdcnt) names(calc) <- c("nRun", "nFac", "nBlk", "mFac", "mInt", "totMod") out.list <- list(calc = calc) print(round(calc, digits = digits)) prob <- data.frame(Factor = names(object$prob), Prob = round(object$prob, digits), row.names = c(" ",seq(length(object$prob)-1))) cat("\n Factor probabilities:\n") print(prob, digits = digits) cat("\n Model probabilities:\n") ind <- seq(min(nTop, object$NTOP)) Prob <- round(object$ptop, digits) NumFac <- object$nftop Sigma2 <- round(object$sigtop, digits) Factors <- apply(object$jtop, 1, function(x) ifelse(all(x == 0), "none", paste(x[x != 0], collapse = ","))) dd <- data.frame(Prob, Sigma2, NumFac, Factors)[ind, ] print(dd, digits = digits, right = FALSE) out.list[["probabilities"]] <- prob out.list[["models"]] <- dd invisible(out.list) }
est.union = function(collection, fun = mean, return.matrix = FALSE){ estado.pr = collection$data[[1]] for ( i in 2:length(collection$data) ) { estado.pr = ts.union(estado.pr, collection$data[[i]]) } colnames(estado.pr) <- paste0("C", 1:length(collection$data)) if(return.matrix){ return(estado.pr) } st = start(estado.pr) estado.pr = apply(estado.pr, 1, fun, na.rm = TRUE) estado.pr = ts(estado.pr, start=st, frequency=12) col = collection col$union = estado.pr class(col) <- "Catalog" return(col) }
frailty.vs<-function(formula,model,penalty,data,B=NULL,v=NULL,alpha=NULL,tun1=NULL,tun2=NULL,varfixed=FALSE,varinit=0.1){ Call <- match.call() mc <- match.call() indx <- match(c("formula", "data"), names(Call), nomatch = 0) if (indx[1] == 0) stop("A formula argument is required") temp <- Call[c(1, indx)] temp[[1]] <- as.name("model.frame") special <- c("strata", "cluster") temp$formula <- terms(subbars(formula), special) m <- eval(temp) Terms <- attr(m, "terms") Y <- model.extract(m, "response") temp <- Call[c(1, indx)] temp[[1]] <- as.name("model.frame") special <- c("strata", "cluster") temp$formula <- terms(formula, special) Terms <- temp[[2]] formula1 <- paste(paste(Terms[[2]][[2]], Terms[[3]], sep = "~")[[2]], paste(Terms[[3]])[3], sep = "+") formula1 <- formula(formula1) fr <- FrailtyFrames(mc, formula1, contrasts) namesX <- names(fr$fixef) namesX <- namesX[-1] namesY <- names(fr$mf)[1] FL <- HGLMFactorList(formula1, fr, 0L, 0L) namesRE <- FL$namesRE y <- matrix(Y[, 1], length(fr$Y), 1) x <- fr$X z <- FL$Design n <- nrow(x) p <- ncol(x) x1 <- x[1:n, 2:p] x2 <- matrix(x1, n, p - 1) x <- x2 n <- nrow(x) p <- ncol(x) alphas<-alpha nrand <- length(z) n.alpha<-length(alphas) if (varfixed==TRUE) result<-frailty1.vs(formula=formula,model=model,penalty=penalty,data=data,B=B,v=v,alpha=alpha,tun1=tun1,tun2=tun2,varfixed=varfixed,varinit=varinit) else { if (n.alpha<=nrand) result<-frailty1.vs(formula=formula,model=model,penalty=penalty,data=data,B=B,v=v,alpha=alpha,tun1=tun1,tun2=tun2,varfixed=varfixed,varinit=varinit) else result<-frailty2.vs(formula=formula,model=model,penalty=penalty,data=data,B=B,v=v,alpha=alpha,tun1=tun1,tun2=tun2) } return(result) }
slapGT<-function(EBS, data_inf, rand_nam, Ynames, grouping, Emethod){ gr<-data_inf[,grouping] if(length(levels(gr))<2){stop("Grouping variable should have at leat 2 levels.")} if(length(levels(gr))==2) gtmod ="logistic" if(length(levels(gr))>2) gtmod ="multinomial" if(Emethod=="joint"){ formula_gtp<-formula(paste0("~",paste0(rand_nam,collapse = "+"),"+",paste0(Ynames,collapse ="+"))) joint_gt<-globaltest::gt(data_inf[,grouping], formula_gtp, data=EBS, permutations=1e5, model =gtmod) gt_obj<-c(joint_gt@result[,1],joint_gt@result[,2],joint_gt@result[,3], joint_gt@result[,4],joint_gt@result[,5]) names(gt_obj)<-c("p-value","Statistic","Expected","Std.dev","Cov") } if(Emethod=="pairwise"){ formula_gtp<-formula(paste0("~", paste0(rand_nam,collapse = "+"),"+", paste0(Ynames,collapse ="+"))) pair_gt<-globaltest::gt(data_inf[,grouping], formula_gtp, data=EBS, permutations=1e5, model =gtmod) gt_obj<-c(pair_gt@result[,1],pair_gt@result[,2],pair_gt@result[,3], pair_gt@result[,4],pair_gt@result[,5]) names(gt_obj)<-c("p-value","Statistic","Expected","Std.dev","Cov") } gt_obj<-c(gt_obj,GT.model=gtmod) return(gt_obj) }
require(OpenMx) require(rpf) require(ifaTools) set.seed(2) numItems <- 15 numPersons <- 250 slope <- 2 groupSize <- 5 items <- list() items[1:numItems] <- rpf.drm() correct.mat <- matrix(NA, 4, numItems) dimnames(correct.mat) <- list(names(rpf.rparam(items[[1]])), paste("i", 1:numItems, sep="")) correct.mat['a',] <- slope correct.mat['b',] <- slope * seq(-1.5, 1.5, length.out = groupSize) correct.mat['g',] <- kronecker(logit(1/2:(1+numItems/groupSize)), rep(1,groupSize)) correct.mat['u',] <- logit(1) correct.mask <- matrix(FALSE, 4, numItems) correct.mask[1,1] <- TRUE correct.mask[2,] <- TRUE correct.mask[3,] <- TRUE mkmodel <- function() { maxParam <- max(vapply(items, rpf.numParam, 0)) maxOutcomes <- max(vapply(items, function(i) i$outcomes, 0)) data <- rpf.sample(numPersons, items, correct.mat) ip.mat <- mxMatrix(name="item", nrow=maxParam, ncol=numItems, values=c(1, 0, NA, logit(1)), free=TRUE, dimnames=list(names(rpf.rparam(items[[1]])), colnames(data))) ip.mat$free[1,] <- TRUE ip.mat$labels[1,] <- 'slope' ip.mat$values[3,] <- correct.mat['g',] ip.mat$labels[3,] <- paste0('g', 1:ncol(ip.mat)) ip.mat$free[4,] <- FALSE m1 <- mxModel(model="model1", ip.mat, mxData(observed=data, type="raw"), mxExpectationBA81(ItemSpec=items), mxFitFunctionML()) m2 <- mxModel("3pl", m1, univariatePrior("logit-norm", paste0('g', 1:ncol(ip.mat)), correct.mat['g',]), mxFitFunctionMultigroup(c('model1', 'univariatePrior')), mxComputeEM('model1.expectation', 'scores', mxComputeNewtonRaphson())) m2 } if (file.exists("inst/models/enormous/lib/stderrlib.R")) { source("inst/models/enormous/lib/stderrlib.R") } else if (file.exists("lib/stderrlib.R")) { source("lib/stderrlib.R") } else { stop("Cannot find stderrlib.R") } name = "ifa-3pl-se" recompute=FALSE getMCdata(name, mkmodel, correct.mat[correct.mask], maxCondNum=5000, recompute=recompute) omxCheckCloseEnough(norm(mcBias, "2"), .5525, .001) omxCheckCloseEnough(max(abs(mcBias)), .3055, .001) omxCheckCloseEnough(log(det(mcHessian)), 90.31, .1) if (0) { result <- NULL set.seed(3) model <- mkmodel() model <- mxRun(mxModel(model, mxComputeSequence(list( mxComputeOnce('model1.expectation', 'scores'), mxComputeOnce('fitfunction', 'information', 'hessian'), mxComputeReportDeriv() )))) h1 <- model$output$hessian h2 <- model$output$hessian h3 <- model$output$hessian em <- model$compute fitfun <- em$mstep$fitfunction em$accel <- "" em$tolerance <- 1e-11 for (semType in c('mr','tian')) { em$information <- "mr1991" em$infoArgs <- list(fitfunction=fitfun, semMethod=semType, semTolerance=sqrt(1e-6)) plan <- mxComputeSequence(list( em, mxComputeHessianQuality(), mxComputeStandardError(), mxComputeReportDeriv() )) model$compute <- plan fit <- mxRun(model, silent=TRUE) result <- rbind(result, data.frame(rd=(fit$output$standardErrors - mcSE)/mcSE, algo=semType, param=names(mcSE))) } if (1) { em$accel <- 'ramsay1975' em$tolerance <- 1e-11 em$information <- "mr1991" em$infoArgs <- list(fitfunction=fitfun, semMethod="agile") plan <- mxComputeSequence(list( em, mxComputeHessianQuality(), mxComputeStandardError(), mxComputeReportDeriv() )) if (is.null(fit)) fit <- model fit$compute <- plan fit <- mxRun(fit, silent=TRUE) result <- rbind(result, data.frame(rd=(fit$output$standardErrors - mcSE)/mcSE, algo="agile", param=names(mcSE))) } library(ggplot2) ggplot(result, aes(rd, param, color=algo, shape=algo)) + geom_point() + geom_vline(xintercept=0) } rda <- paste(name, "-result.rda", sep="") load(rda) detail <- testPhase(mkmodel, 500, methods=c('re', 'estepH', 'mr', 'tian', 'agile', 'meat', 'oakes')) if (0) { asem <- studyASEM(mkmodel) smooth <- checkSmoothness(mkmodel) } save(detail, asem, smooth, file=rda) stop("done") if (0) { asem <- studyASEM(mkmodel, reps = 50, targets=seq(-8.1, -3.9, .2)) got <- checkSmoothness(mkmodel()) } if (0) { seed <- 1 set.seed(seed) m1 <- mkmodel() f1 <- paste("ifa-3pl-se", seed, ".csv", sep="") write.table(sapply(m1$data$observed, unclass)-1, f1, quote=FALSE, row.names=FALSE, col.names=FALSE) m1 <- mxRun(m1) covname <- "~/ifa/ifa-3pl-se/3pl-se-cov.txt" H <- read.csv(covname, header = FALSE, row.names=NULL) H <- H[,-ncol(H)] H <- solve(H) labels <- names(m1$output$estimate) fmOrder <- c(labels[-c(2,9,16,23,30)], labels[c(2,9,16,23,30)]) fmPerm <- match(colnames(mcHessian), fmOrder) H <- H[fmPerm, fmPerm] H <- 2 * H m1$compute <- mxComputeSequence(list( mxComputeOnce('expectation','scores'), mxComputeOnce('fitfunction', 'information', "hessian"), mxComputeReportDeriv())) m1 <- mxRun(m1) mvn_KL_D(H, solve(H)) mvn_KL_D(junk, solve(junk)) } if (0) { require(mirt) seed <- 1 set.seed(seed) m1 <- mkmodel() val <- mirt(sapply(m1$data$observed, unclass)-1, 1, "3PL", pars="values") val[val$name == "a1", 'value'] <- 8 val[val$name == "a1", 'est'] <- FALSE gnum <- val[val$name=='g', 'parnum'] fit <- mirt(sapply(m1$data$observed, unclass)-1, 1, "3PL", pars=val, constrain=list(gnum[1:6], gnum[7:12], gnum[13:18], gnum[19:24], gnum[25:30]), SE=TRUE, SE.type="complete") fit$information } if (0) { grp <- bank[[1]]$grp source("~/2012/sy/irtplot.R") booklet(function(item) { rpf.plot(grp, item, data.bins=30, basis=c(1), factor=1) }, colnames(correct.mat), output="4plm.pdf") rpf.plot(grp, "i1") rpf.plot(grp, "i6") rpf.plot(grp, "i11") rpf.plot(grp, "i16") grp$param <- correct.mat } if (0) { m1 <- mkmodel(1) if (0) { raw <- sapply(m1$data$observed, unclass) - 1 write.table(raw, file="3pl1.csv", quote=FALSE, row.names=FALSE, col.names=FALSE) } } if(1) { omxCheckCloseEnough(max(sapply(bank, function(t) t$condnum['meat'])), 733, 1) omxCheckCloseEnough(max(abs(emp$bias)), .04, .01) omxCheckCloseEnough(norm(check.se("meat"), "2"), 2.08, .01) omxCheckCloseEnough(norm(check.se("sw"), "2"), 3.298, .01) omxCheckCloseEnough(norm(check.se("sem"), "2"), 2.935, .01) if (0) { plot(emp$bias, correct.mat[correct.mask]) hist(check.se("sem")) hist(check.se("meat")) hist(check.se("sw")) } }
postgis_insert <- function(conn, df, tbl, write_cols = NA, geom_name = NA_character_, hstore_name = NA_character_) { query_text <- prep_write_query(conn, df, tbl, mode = "insert", write_cols, NA, NA, geom_name, hstore_name, NA) RPostgreSQL::dbSendQuery(conn, query_text) } postgis_update <- function(conn, df, tbl, id_cols, update_cols, geom_name = NA_character_, hstore_name = NA_character_, hstore_concat = TRUE) { query_text <- prep_write_query(conn, df, tbl, mode = "update", NA, id_cols, update_cols, geom_name, hstore_name, hstore_concat) RPostgreSQL::dbSendQuery(conn, query_text) } prep_write_query <- function(conn, df, tbl, mode, write_cols, id_cols, update_cols, geom_name, hstore_name, hstore_concat) { if (!is(conn, "PostgreSQLConnection")) { stop("conn is not a valid PostgreSQL connection") } if (!is(df, "data.frame") & !is(df, "Spatial")) { stop("df must be a data.frame or Spatial*DataFrame") } test_single_str(tbl) test_single_str(geom_name) test_single_str(hstore_name) if (mode == "update") { if (length(intersect(id_cols, update_cols)) > 0) { stop("the same column cannot appear in id_cols and update_cols") } if (geom_name %in% id_cols || hstore_name %in% id_cols) { stop("geometry and hstore columns cannot be used in id_cols") } } quote_id <- make_id_quote(conn) quote_str <- make_str_quote(conn) if (!is.na(geom_name)) { if (!is(df, "Spatial")) { stop("geom_name specified but df is not a spatial object") } if (all(is.na(write_cols))) { write_cols <- colnames(df@data) } else if (!all(write_cols %in% colnames(df@data))) { stop(paste("columns not found in df:", paste(setdiff(write_cols, colnames(df@data)), collapse = ", "))) } srid <- find_srid(conn, proj4string(df)) geom_wkt <- rgeos::writeWKT(df, byid = nrow(df@data) > 1) df <- cbind(df@data[, write_cols, drop = FALSE], geom_wkt, stringsAsFactors = FALSE) igeom <- ncol(df) colnames(df)[igeom] <- geom_name } else { if (is(df, "Spatial")) { stop("geom_name must be specified since df is as spatial object") } if (all(is.na(write_cols))) { write_cols <- colnames(df) } else if (!all(write_cols %in% colnames(df))) { stop(paste("columns not found in df:", paste(setdiff(write_cols, colnames(df)), collapse = ", "))) } df <- df[, write_cols, drop = FALSE] } fact_cols <- vapply(df, is.factor, FALSE) df[fact_cols] <- lapply(df[fact_cols], as.character) if (mode == "update") { if (!all(c(id_cols, update_cols) %in% colnames(df))) stop(paste("columns not found in df:", paste(setdiff(c(id_cols, update_cols), colnames(df)), collapse = ", "))) if (any(duplicated(df[, id_cols]))) stop("id_cols do not uniquely identify rows in df") } if (!is.na(hstore_name)) { if (!all(vapply(df[[hstore_name]], is.list, FALSE))) { stop(paste("column", deparse(substitute(hstore_name)), "is not a valid hstore")) } df[[hstore_name]] <- vapply(df[[hstore_name]], jsonlite::toJSON, "") df[[hstore_name]] <- json_to_hstore(df[[hstore_name]]) } if (mode == "update") { tbl_q <- quote_id(tbl) tbl_tmp <- quote_id(paste0(tbl, "_tmp")) id_q <- quote_id(id_cols) update_q <- quote_id(update_cols) update_tmp <- paste0(tbl_tmp, ".", update_q) if (!is.na(hstore_name)) { i_hs <- which(update_cols == hstore_name) update_tmp[i_hs] <- paste0(update_tmp[i_hs], "::hstore") if (hstore_concat) { update_tmp[i_hs] <- paste0("COALESCE(", tbl_q, ".", update_q[i_hs], ", hstore('')) || ", update_tmp[i_hs]) } } query_text <- paste("UPDATE", tbl_q, "SET", paste(update_q, "=", update_tmp, collapse = ", "), "FROM (VALUES") } else { col_ids <- quote_id(colnames(df)) query_text <- paste("INSERT INTO", quote_id(tbl), "(", paste(col_ids, collapse = ", "), ") VALUES") } df_q <- do.call(cbind, lapply(df, function(var) { if(is.character(var)) quote_str(var) else var })) na_inds <- do.call(cbind, lapply(df, is.na)) df_q[na_inds] <- "NULL" if (!is.na(geom_name)) { df_q[, igeom] <- paste0("ST_GeomFromText(", df_q[, igeom], ", ", srid, ")") } query_values <- apply(df_q, 1, function(row) { paste("(", paste(row, collapse = ", "), ")") }) query_text <- paste(query_text, paste(query_values, collapse = ", ")) if (mode == "update") { query_text <- paste(query_text, ") AS", tbl_tmp, "(", paste(quote_id(colnames(df)), collapse = ", "), ")", "WHERE", paste(paste0(tbl_q, ".", id_q), "=", paste0(tbl_tmp, ".", id_q), collapse = " AND ")) } query_text }
suppressWarnings(library(dplyr, warn.conflicts = FALSE, quietly = TRUE)) library(tidyr, quietly = TRUE) library(nlme) data(bdf, package = "mlmRev") bdf_long <- bdf %>% filter(schoolNR %in% levels(schoolNR)[1:12]) %>% droplevels() %>% pivot_longer(cols = c(IQ.verb, IQ.perf, aritPRET), names_to = "measure", values_to = "score") %>% select(schoolNR, pupilNR, sex, Minority, measure, score) %>% arrange(schoolNR, pupilNR, measure) bdf_MVML <- lme(score ~ 0 + measure, random = ~ 1| schoolNR / pupilNR, corr = corSymm(form = ~ 1 | schoolNR / pupilNR), weights = varIdent(form = ~ 1 | measure), data = bdf_long, control = lmeControl(msMaxIter = 100, apVar = FALSE, returnObject = TRUE)) set.seed(20200311) bdf_long$school_id <- bdf_long$schoolNR levels(bdf_long$school_id) <- LETTERS[1:nlevels(bdf_long$school_id)] bdf_long_wm <- bdf_long %>% mutate( row_index = rbinom(n = n(), size = 1, prob = 0.9), score = if_else(row_index == 1, score, as.numeric(NA)), measure_id = as.integer(factor(measure)) ) %>% filter(!is.na(score)) %>% select(-row_index) %>% arrange(schoolNR, pupilNR, measure_id) bdf_long_shuff <- sample_frac(bdf_long_wm, 1) %>% mutate(row = row_number()) bdf_wm <- lme(score ~ 0 + measure, random = ~ 1| schoolNR / pupilNR, corr = corSymm(form = ~ measure_id | schoolNR / pupilNR), weights = varIdent(form = ~ 1 | measure_id), data = bdf_long_wm, control=lmeControl(msMaxIter = 100, apVar = FALSE, returnObject = TRUE)) bdf_wm_shuff <- lme(score ~ 0 + measure, random = ~ 1| schoolNR / pupilNR, corr = corSymm(form = ~ measure_id | schoolNR / pupilNR), weights = varIdent(form = ~ 1 | measure_id), data = bdf_long_shuff, control=lmeControl(msMaxIter = 100, apVar = FALSE, returnObject = TRUE)) bdf_wm_id <- lme(score ~ 0 + measure, random = ~ 1| school_id / pupilNR, corr = corSymm(form = ~ measure_id | school_id / pupilNR), weights = varIdent(form = ~ 1 | measure_id), data = bdf_long_shuff, control=lmeControl(msMaxIter = 100, apVar = FALSE, returnObject = TRUE)) test_that("targetVariance() works with multivariate models.", { skip_on_cran() test_Sigma_mats(bdf_MVML, bdf_long$schoolNR) test_Sigma_mats(bdf_wm, bdf_long_wm$schoolNR) test_Sigma_mats(bdf_wm_id, bdf_long_shuff$school_id) test_Sigma_mats(bdf_wm_shuff, bdf_long_shuff$school_id) }) test_that("Derivative matrices are of correct dimension with multivariate models.", { skip_on_cran() test_deriv_dims(bdf_MVML) test_deriv_dims(bdf_wm) test_deriv_dims(bdf_wm_id) test_deriv_dims(bdf_wm_shuff) }) test_that("Information matrices work with FIML too.", { test_with_FIML(bdf_MVML) test_with_FIML(bdf_wm) test_with_FIML(bdf_wm_id) test_with_FIML(bdf_wm_shuff) }) test_that("New REML calculations work.", { skip_on_cran() check_REML2(bdf_MVML) check_REML2(bdf_wm) check_REML2(bdf_wm_id) check_REML2(bdf_wm_shuff) }) test_that("Info matrices work with dropped observations.", { skip_on_cran() test_after_deleting(bdf_MVML, seed = 10) test_after_deleting(bdf_wm, seed = 20) test_after_deleting(bdf_wm_id, seed = 30) test_after_deleting(bdf_wm_shuff, seed = 40) }) test_that("Results do not depend on order of data.", { skip("For now.") test_after_shuffling(bdf_MVML, seed = 20) test_after_shuffling(bdf_wm, seed = 17) test_after_shuffling(bdf_wm_id, seed = 20) test_after_shuffling(bdf_wm_shuff, seed = 17) })
TestTrimHistogram <- function() { hist.1 <- hist(c(1,2,3), breaks=0:9, plot=FALSE) hist.trimmed <- TrimHistogram(hist.1) checkTrue(sum(hist.1$counts) == sum(hist.trimmed$counts)) checkTrue(length(hist.1$counts) > length(hist.trimmed$counts)) hist.2 <- hist(c(4,5,6), breaks=0:9, plot=FALSE) hist.trimmed <- TrimHistogram(hist.2) checkTrue(sum(hist.2$counts) == sum(hist.trimmed$counts)) checkTrue(length(hist.2$counts) > length(hist.trimmed$counts)) zero.hist <- hist(numeric(), breaks=c(0,1,2,3,4,5,6,7,8,9), plot=FALSE) zero.trimmed <- TrimHistogram(zero.hist) checkEquals(length(zero.hist$counts), length(zero.trimmed$counts)) }
library( knitr) opts_chunk$set(cache=TRUE, message = FALSE, comment = "", dev="pdf", dpi=300, fig.show = "hold", fig.align = "center") library( stockR) set.seed( 747) N <- 100 M <- 5000 S <- N K <- 3 myData <- sim.stock.data( nAnimal=N, nSNP=M, nSampleGrps=N, K=K) dim( myData) ncol( myData) nrow( myData) table( attributes( myData)$grps) attributes( myData)$grps myData[1:5,1:3] stocks <- stockSTRUCTURE( myData, K=3) stocks$postProb stocks$hardClass <- apply( stocks$postProb, 1, which.max) stocks$boot <- stockBOOT( stocks, B=25, mc.cores=2) stocks$uncertClass <- apply( stocks$boot$postProbs, 1:2, quantile, probs=c(0.05,0.5,0.95)) print( round( stocks$uncertClass[,99,], 3)) S <- 15 K <- 3 myData <- sim.stock.data( nAnimal=N, nSNP=M, nSampleGrps=S, K=K) stocks <- stockSTRUCTURE( myData, K=3, sample.grps=attributes(myData)$sampleGrps) attributes( myData)$grps apply( stocks$postProbs, 1, which.max) stocks$boot <- stockBOOT( stocks, B=25, mc.cores=2) stocks$uncertClass <- apply( stocks$boot$postProbs, 1:2, quantile, probs=c(0.05,0.5,0.95)) print( round( stocks$uncertClass, 3)) myData <- sim.stock.data( nAnimal=N, nSNP=M, nSampleGrps=N, K=K) totMark <- prod( dim( myData)) myData[sample( 1:totMark, size=floor( 0.3*totMark))] <- NA stocks <- stockSTRUCTURE( myData, K=3) attributes( myData)$grps apply( stocks$postProbs, 1, which.max) rm( list=ls()) toLatex(sessionInfo())
compileCode <- TRUE library(rstan) ; library(HRW) nWarm <- 1000 nKept <- 1000 nThin <- 1 fTrue <- function(x) return(3*exp(-78*(x-0.38)^2)+exp(-200*(x-0.75)^2)-x) muXTrue <- 0.5 ; sigmaXTrue <- 1/6 sigmaEpsTrue <- 0.35 set.seed(1) n <- 1000 misPropn <- 0.2 x <- rnorm(n,muXTrue,sigmaXTrue) y <- fTrue(x) + sigmaEpsTrue*rnorm(n) nUnobs <- round(misPropn*n) ; nObs <- n - nUnobs indsUnobs <- sample(1:n,nUnobs,replace=FALSE) indsObs <- setdiff(1:n,indsUnobs) xUnobsTrue <- x[indsUnobs] ; xObs <- x[indsObs] yxUnobs <- y[indsUnobs] ; yxObs <- y[indsObs] ncZ <- 25 knots <- seq(min(xObs),max(xObs),length=(ncZ+2))[-c(1,ncZ+2)] ZxObs <- outer(xObs,knots,"-") ZxObs <- ZxObs*(ZxObs>0) npRegMCARModel <- 'data { int<lower=1> nObs; int<lower=1> nUnobs; int<lower=1> ncZ; vector[nObs] yxObs; vector[nUnobs] yxUnobs; vector[nObs] xObs; vector[ncZ] knots; matrix[nObs,ncZ] ZxObs; real<lower=0> sigmaBeta; real<lower=0> sigmaMu; real<lower=0> Ax; real<lower=0> Aeps; real<lower=0> Au; } parameters { vector[2] beta; vector[ncZ] u; real muX; real<lower=0> sigmaX; real<lower=0> sigmaEps; real<lower=0> sigmaU; real xUnobs[nUnobs]; } transformed parameters { matrix[nObs,2] XxObs; matrix[nUnobs,2] XxUnobs; matrix[nUnobs,ncZ] ZxUnobs; for (i in 1:nObs) { XxObs[i,1] = 1 ; XxObs[i,2] = xObs[i]; } for (i in 1:nUnobs) { XxUnobs[i,1] = 1 ; XxUnobs[i,2] = xUnobs[i]; for (k in 1:ncZ) { ZxUnobs[i,k] = (xUnobs[i]-knots[k])*step(xUnobs[i]-knots[k]); } } } model { yxObs ~ normal(XxObs*beta+ZxObs*u,sigmaEps); xObs ~ normal(muX,sigmaX); yxUnobs ~ normal(XxUnobs*beta+ZxUnobs*u,sigmaEps); xUnobs ~ normal(muX,sigmaX); u ~ normal(0,sigmaU) ; beta ~ normal(0,sigmaBeta); muX ~ normal(0,sigmaMu); sigmaX ~ cauchy(0,Ax); sigmaEps ~ cauchy(0,Aeps); sigmaU ~ cauchy(0,Au); }' allData <- list(nObs = nObs,nUnobs = nUnobs,ncZ = ncZ,xObs = xObs, yxObs = yxObs,yxUnobs = yxUnobs,ZxObs = ZxObs,knots = knots, sigmaMu = 1e5,sigmaBeta = 1e5,sigmaEps = 1e5,sigmaX = 1e5,Ax = 1e5, Aeps = 1e5,Au = 1e5) if (compileCode) stanCompilObj <- stan(model_code = npRegMCARModel,data = allData, iter = 1,chains = 1) stanObj <- stan(model_code = npRegMCARModel,data = allData,warmup = nWarm, iter = (nWarm + nKept),chains = 1,thin = nThin,refresh = 100, fit = stanCompilObj) betaMCMC <- NULL for (j in 1:2) { charVar <- paste("beta[",as.character(j),"]",sep = "") betaMCMC <- rbind(betaMCMC,extract(stanObj,charVar,permuted = FALSE)) } uMCMC <- NULL for (k in 1:ncZ) { charVar <- paste("u[",as.character(k),"]",sep = "") uMCMC <- rbind(uMCMC,extract(stanObj,charVar,permuted = FALSE)) } muXMCMC <- as.vector(extract(stanObj,"muX",permuted = FALSE)) sigmaXMCMC <- as.vector(extract(stanObj,"sigmaX",permuted = FALSE)) sigmaEpsMCMC <- as.vector(extract(stanObj,"sigmaEps",permuted = FALSE)) sigmaUMCMC <- as.vector(extract(stanObj,"sigmaU",permuted = FALSE)) xUnobsMCMC <- NULL for (i in 1:nUnobs) { charVar <- paste("xUnobs[",as.character(i),"]",sep = "") xUnobsMCMC <- rbind(xUnobsMCMC,extract(stanObj,charVar,permuted = FALSE)) } obsCol <- "darkblue" ; misCol <- "lightskyblue" estFunCol <- "darkgreen"; trueFunCol <- "indianred3" varBandCol <- "palegreen" ; cexVal <- 0.3 ng <- 201 xg <- seq(0,1,,length = ng) Xg <- cbind(rep(1,ng),xg) Zg <- outer(xg,knots,"-") Zg <- Zg*(Zg>0) fMCMC <- Xg%*%betaMCMC + Zg%*%uMCMC credLower <- apply(fMCMC,1,quantile,0.025) credUpper <- apply(fMCMC,1,quantile,0.975) fg <- apply(fMCMC,1,mean) par(mfrow = c(1,1),mai = c(1.02,0.82,0.82,0.42)) plot(xg,fg,type = "n",bty = "l",xlab = "x",ylab = "y",xlim = range(x),ylim = range(y)) polygon(c(xg,rev(xg)),c(credLower,rev(credUpper)),col = varBandCol,border = FALSE) lines(xg,fg,lwd = 2,col = estFunCol) lines(xg,fTrue(xg),lwd = 2,col = trueFunCol) points(xObs,yxObs,col = obsCol,cex = cexVal) points(xUnobsTrue,yxUnobs,col = misCol,cex = cexVal) legend("topright",c("fully observed","x value unobserved"),col = c(obsCol,misCol), pch = rep(1,2),pt.cex = cexVal) legend("topleft",c("true f","estimated f"),col = c(trueFunCol,estFunCol), lwd = rep(2,2)) indQ1 <- length(xg[xg <= quantile(xObs,0.25)]) fQ1MCMC <- fMCMC[indQ1,] indQ2 <- length(xg[xg <= quantile(xObs,0.50)]) fQ2MCMC <- fMCMC[indQ2,] indQ3 <- length(xg[xg <= quantile(xObs,0.75)]) fQ3MCMC <- fMCMC[indQ3,] parms <- list(cbind(muXMCMC,sigmaXMCMC,sigmaEpsMCMC,fQ1MCMC,fQ2MCMC,fQ3MCMC)) parNamesVal <- list(c(expression(mu[x])),c(expression(sigma[x])), c(expression(sigma[epsilon])), c("first quartile","of x"), c("second quart.","of x"), c("third quartile","of x")) summMCMC(parms,parNames = parNamesVal,numerSummCex = 1, KDEvertLine = FALSE,addTruthToKDE = c(muXTrue,sigmaXTrue, sigmaEpsTrue,fTrue(xg[indQ1]), fTrue(xg[indQ2]),fTrue(xg[indQ3]))) parms <- list(t(xUnobsMCMC[1:5,])) parNamesVal <- list(c(expression(x["unobs,1"])), c(expression(x["unobs,2"])), c(expression(x["unobs,3"])), c(expression(x["unobs,4"])), c(expression(x["unobs,5"]))) summMCMC(parms,parNames = parNamesVal,KDEvertLine = FALSE,addTruthToKDE = x[1:5])
addtoedges <- function(profileEdges=blackbox.getOption("profileEdges"), locedge) { if(is.null(locedge)) return(profileEdges) oldnr <- nrow(profileEdges) if (is.null(oldnr)) oldnr <- 0 if ( oldnr>1000 ) { message.redef("profileEdges growing dangerously...")} profileEdges <- rbind(profileEdges, locedge) nr <- nrow(profileEdges) if (is.null(nr)) nr <- 0 if ( oldnr<1001 & nr>1000 ) { cat("(Reducing profileEdges)", "\n") blob <- resetCHull(profileEdges, formats="vertices", redundant.mode="double") profileEdges <- blob$vertices } blackbox.options(profileEdges=profileEdges) return(profileEdges) }
gausskernel <- function(X=NULL,sigma=NULL) { return(exp(-1*as.matrix(dist(X)^2)/sigma)) }