code
stringlengths
1
13.8M
tab <- function(score, file, key = "c", time = "4/4", tempo = "2 = 60", header = NULL, paper = NULL, string_names = NULL, endbar = "|.", midi = TRUE, colors = NULL, crop_png = TRUE, transparent = FALSE, res = 150, keep_ly = FALSE, simplify = TRUE, details = FALSE){ .check_lilypond() fp <- .adjust_file_path(file) ext <- if(fp$ext == "pdf") "--pdf" else paste0("-dresolution=", res, " --png") if(is.null(paper$textheight) & fp$ext == "png"){ png_args <- "\" -dbackend=eps " } else { png_args <- "\" " } if(transparent & fp$ext == "png") png_args <- paste0(png_args, "\ -dpixmap-format=pngalpha ") if(fp$ext == "pdf") crop_png <- FALSE if(details) cat(" lilypond(score, fp$lp, key, time, tempo, header, paper, string_names, endbar, midi, colors, crop_png, simplify) lp_path <- tabr_options()$lilypond is_windows <- Sys.info()[["sysname"]] == "Windows" if(lp_path == ""){ lp_path <- if(is_windows) "lilypond.exe" else "lilypond" } call_string <- paste0("\"", lp_path, png_args, ext, " -dstrip-output-dir= if(is_windows){ system(call_string, show.output.on.console = details) } else { system(call_string) } if(!keep_ly) unlink(fp$lp) .eps_cleanup(fp$tp) } render_tab <- tab render_score <- function(score, file, key = "c", time = "4/4", tempo = "2 = 60", header = NULL, paper = NULL, endbar = "|.", colors = NULL, crop_png = TRUE, transparent = FALSE, res = 150, keep_ly = FALSE, simplify = TRUE, details = FALSE){ tab(score, file, key, time, tempo, header, paper, FALSE, endbar, FALSE, colors, crop_png, transparent, res, keep_ly, simplify, details) } render_midi <- function(score, file, key = "c", time = "4/4", tempo = "2 = 60"){ file0 <- gsub("\\.mid$", ".png", file) tab(score, file0, key, tempo = tempo, midi = TRUE) unlink(file0, recursive = TRUE, force = TRUE) invisible() } render_chordchart <- function(chords, file, size = 1.2, header = NULL, paper = NULL, colors = NULL, crop_png = TRUE, transparent = FALSE, res = 150, keep_ly = FALSE, details = FALSE){ .check_lilypond() header <- .header_plus_colors(header, colors) colors <- .lp_color_overrides(colors) if(colors$score != ""){ global <- paste0(.lp_override_all_colors, "global = {\n ", colors$overrides, "}\n\n") } else { global <- "" } i <- seq_along(chords) id <- names(chords) fp <- .adjust_file_path(file) ext <- if(fp$ext == "pdf") "--pdf" else paste0("-dresolution=", res, " --png") if(is.null(paper$textheight) & fp$ext == "png"){ png_args <- "\" -dbackend=eps " } else { png_args <- "\" " } if(transparent & fp$ext == "png") png_args <- paste0(png_args, "\ -dpixmap-format=pngalpha ") crop_png_w <- if(crop_png & !length(header)) TRUE else FALSE paper_args <- .lp_paper_args2(paper, crop_png, crop_png_w) paper <- do.call(.lp_paper, paper_args) x <- paste0( " ")\n", do.call(.lp_header, if(is.null(header)) list() else header), "\n", global, "\\include \"predefined-guitar-fretboards.ly\"\n" ) def <- purrr::map_chr(i, ~.define_chord(.x, id[.x], chords[.x])) %>% paste(collapse = "") x <- paste0(x, "\n", def, "\nmychorddiagrams = \\chordmode {\n") set <- purrr::map_chr(i, ~.set_chord(.x, id[.x])) %>% paste(collapse = "") x <- paste0(x, set, "}\n\nchordNames = \\chordmode {\n", " \\override ChordName.font-size = paste(names(chords), collapse = " "), "\n}\n\n") markup <- paste0( "\\markup\\vspace " <<\n", " \\context ChordNames { \\mychorddiagrams }\n", " \\context FretBoards {\n", " \\override FretBoards.FretBoard.size = " \\mychorddiagrams\n", " }\n", " >>\n", " \\layout {}\n", " }\n}\n\\markup\\vspace x <- paste0(paper, x, markup) write(file = fp$lp, x) lp_path <- tabr_options()$lilypond is_windows <- Sys.info()[["sysname"]] == "Windows" if(lp_path == ""){ lp_path <- if(is_windows) "lilypond.exe" else "lilypond" } call_string <- paste0("\"", lp_path, png_args, ext, " -dstrip-output-dir= if(is_windows){ system(call_string, show.output.on.console = details) } else { system(call_string) } if(!keep_ly) unlink(fp$lp) .eps_cleanup(file) } .paper_defaults2 <- list(textheight = 220, linewidth = 150, indent = 0, fontsize = 14, page_numbers = FALSE, print_first_page_number = TRUE, first_page_number = 1) .lp_paper_args2 <- function(x, crop, cropw){ y <- list(crop = crop, cropw = cropw) if(is.null(x)) return(c(.paper_defaults2, y)) for(i in names(.paper_defaults2)) if(!i %in% names(x)) x[[i]] <- .paper_defaults2[[i]] c(x, list(crop = crop, cropw = cropw)) } .define_chord <- function(i, id, value){ paste0(" "\\storePredefinedDiagram " \\chordmode{", id, "} } .set_chord <- function(i, id){ paste0(" \\set predefinedDiagramTable = }
rrumpars2logpars <- function(v1){ l1 <- rep(0,length(v1)) l1[-1] <- log( 1 / v1[-1] ) l1[1] <- log( prod(v1) ) return(l1) }
ordi.focal.drop <- function(dat,dist.method="jaccard"){ res<-list() type.c="centroid" res<-vector("list",dim(dat)[1]) spnames<-rownames(dat) ODB<-ordi.breadth(dat,dist.method=dist.method) for(i in 1:length(spnames)){ res[[i]]$species<-spnames[i] res[[i]]$ODB<-ODB$tot.breadth[i] res[[i]]$ODB.scaled<-ODB$scaled.breadth[i] } for(focal.bug in 1:length(spnames)){ cat("\n",focal.bug,"of",length(spnames)) dat.m.f<-dat[-focal.bug,] temp<-which(apply(dat.m.f,2,sum)==0) if(length(temp)!=0){ dat.m.f<-dat.m.f[,-temp] focal.bug.m.f<-dat[focal.bug,-temp] }else{focal.bug.m.f<-dat[focal.bug,]} specialization.m.f<-ordi.breadth(dat.m.f,dist.method=dist.method) temp<-hyp.group.dist.m.f(dat.m.f,grouping=as.numeric(focal.bug.m.f),distances=TRUE) focal.breadth<-temp$distances.all total.breadth<-temp$tot.breath specdist<-focal.breadth specdisto<-specdist[order(specdist)] scale.factor<-hyp.group.dist.m.f(dat.m.f,grouping=rep("YES",dim(dat.m.f)[2])) res[[focal.bug]]$focal.distances<-specdisto res[[focal.bug]]$focal.breadth<-total.breadth res[[focal.bug]]$focal.scale.factor<-scale.factor res[[focal.bug]]$focal.scaled.breadth<-total.breadth/scale.factor } return(res) }
install_taxstats <- function(pkg = c("taxstats"), ...) { if (!identical(Sys.getenv("R_GRATTAN_BUILD_MAIN_VIGNETTE"), "true") || !identical(Sys.getenv("R_GRATTAN_ALLOW_TAXSTATS"), "true")) { message("Unable to install taxstats. Set both of the following environment variables\n\t", "Sys.setenv('R_GRATTAN_BUILD_MAIN_VIGNETTE' = 'true')\n", " "Sys.setenv('R_GRATTAN_ALLOW_TAXSTATS' = 'true')\n") return(NULL) } if (!missing(..1)) { dots <- list(...) if ("lib" %in% names(dots)) { if (!requireNamespace("data.table", lib.loc = dots$lib, quietly = TRUE)) { utils::install.packages("data.table", lib = dots$lib, ...) } } } utils::install.packages(pkgs = c(pkg), repos = "https://hughparsonage.github.io/tax-drat", type = "source", ...) }
rray_split <- function(x, axes = NULL) { axes <- vec_cast(axes, integer()) validate_axes(axes, x) if (is_null(axes)) { axes <- seq_len(rray_dim_n(x)) } res <- rray__split(x, as_cpp_idx(axes)) for (i in seq_along(res)) { res[[i]] <- vec_cast_container(res[[i]], x) } res }
lst <- function(...) { xs <- quos(..., .named = TRUE) lst_quos(xs) } lst_quos <- function(xs) { col_names <- names2(xs) lengths <- rep_along(xs, 0L) output <- rep_named(rep_along(xs, ""), list(NULL)) for (i in seq_along(xs)) { unique_output <- output[!duplicated(names(output)[seq_len(i)], fromLast = TRUE)] res <- eval_tidy(xs[[i]], unique_output) if (!is.null(res)) { lengths[[i]] <- NROW(res) output[[i]] <- res } names(output)[[i]] <- col_names[[i]] } output }
fitPlain <- function(cell,family){ dat=cell$Loss mu=mean(dat) sigma=sd(dat) if(family=="weibull"){ nll=function(x){ -sum(dweibull(dat,exp(x[1]),exp(x[2]),log=TRUE)) } start=c((sigma/mu)^(-1.086),mu/(gamma(1+1/((sigma/mu)^(-1.086))))) pars=exp(optim(log(start),nll)$par) } if(family=="gamma"){ nll=function(x){ -sum(dgamma(dat,exp(x[1]),exp(x[2]),log=TRUE)) } start=c(mu^2/sigma^2,mu/sigma^2) pars=exp(optim(log(start),nll)$par) } if(family=="lnorm"){ pars=c(mean(log(dat)),sd(log(dat))) } if (family == "gh") { q0.1 <- as.numeric(stats::quantile(dat, 0.1)) q0.9 <- as.numeric(stats::quantile(dat, 0.9)) A <- stats::median(dat) gamma2 <- q0.9 - q0.1 gamma3 <- (A - q0.1)/(q0.9 - A) gamma4 <- (as.numeric(stats::quantile(dat, 0.75)) - as.numeric(stats::quantile(dat, 0.25)))/gamma2 g <- -log(gamma3)/stats::qnorm(0.9) if (g == 0) { h <- 2 * log(stats::qnorm(0.75)/(gamma4 * stats::qnorm(0.9)))/(stats::qnorm(0.9)^2 - stats::qnorm(0.75)^2) } else { h <- (2 * log((gamma3^(1 - (stats::qnorm(0.75)/stats::qnorm(0.9))) * (gamma3^(2 * stats::qnorm(0.75)/stats::qnorm(0.9)) - 1))/((gamma3^2 - 1) * gamma4)))/(stats::qnorm(0.9)^2 - stats::qnorm(0.75)^2) } B <- gamma2/(exp(0.5 * h * stats::qnorm(0.9)^2) * (exp(g * stats::qnorm(0.9)) - exp(-g * stats::qnorm(0.9)))/g) if(h<0) base::warning("estimated kurtosis parameter is negative") pars = c(A, B, g, h) } return(buildPlainSevdist(family,pars)) }
print.BANOVA.Bernoulli <- function(x, ...){ cat('Call:\n') print(x$call) cat('\n Coefficients: \n') print(data.frame(x$coef.tables$full_table)) }
eigs <- function(A, k, which = "LM", sigma = NULL, opts = list(), ...) RSpectra::eigs(A, k, which, sigma, opts, ...) eigs_sym <- function(A, k, which = "LM", sigma = NULL, opts = list(), lower = TRUE, ...) RSpectra::eigs_sym(A, k, which, sigma, opts, lower, ...)
lexical_sort <- function(x) { as.numeric(sort(as.character(x))) }
as.sfc.cartogramR <- function(x, ...) { if (!inherits(x, "cartogramR")) stop(paste(deparse(substitute(x)), "must be a cartogramR object")) return(x$cartogram) }
expected <- FALSE test(id=17, code={ argv <- list(complex(real=3, imaginary=-Inf)) do.call('is.null', argv); }, o = expected);
Slope_Legend <- function(colors=colors, maskNegatives=T) { colorsfunc <- colorRamp(colors) par(ann=F, mar=c(0,0,0,0)) layout(matrix(1:2,ncol=2), widths=c(0.75, 0.25)) plot(1,1, type='n', axes=F) lineSize <- 2 textSize <- 1.75 rectSize <- 1 colorslist <- colorsfunc(rev(seq(0, 1, 0.001))) colorslist <- apply(colorslist, 1, function(x) rgb(x[1], x[2], x[3], maxColorValue=255)) legend_gradient <- as.raster(matrix(colorslist, ncol=1)) XPos1 <- 1.15 XPos2 <- XPos1-(0.55*rectSize) XPos3 <- XPos1-(0.05*rectSize) XPos4 <- XPos1-(0.45*rectSize) XPos5 <- XPos1-(0.15*rectSize) YPos0 <- 0.5 YPos1 <- YPos0+(0.3*rectSize) YPos2 <- YPos0-(0.25*rectSize) YPos3 <- YPos0+(0.375*rectSize) YPos4 <- YPos0-(0.27*rectSize) YPos5 <- YPos0-(0.32*rectSize) YPos6 <- YPos0-(0.295*rectSize) YPos7 <- YPos0-(0.34*rectSize) YPos8 <- YPos0-(0.39*rectSize) YPos9 <- YPos0-(0.365*rectSize) plot(c(0,2), c(0,1), type='n', axes=F, xlab='', ylab='') Slope_Labels <- seq(0,90, l=10) Slope_Labels <- format(Slope_Labels, scientific=F) text(x=XPos1, y=seq(YPos2, YPos1, l=10), labels=Slope_Labels, adj=c(0, NA), cex=textSize) rasterImage(legend_gradient, XPos2, YPos2, XPos3,YPos1) rect(XPos2, YPos2, XPos3, YPos1, lwd=lineSize) segments(x0=rep(XPos2, 10), y0=seq(YPos2,YPos1,l=10), x1=rep(XPos4, 10), y1=seq(YPos2,YPos1,l=10), lwd=lineSize) segments(x0=rep(XPos5, 10), y0=seq(YPos2,YPos1,l=10), x1=rep(XPos3, 10), y1=seq(YPos2,YPos1,l=10), lwd=lineSize) if(maskNegatives==T){ edgeblack <- ' rect(XPos2, YPos5, XPos3, YPos4, lwd=lineSize, col=edgeblack, border="black") text(x=XPos1, y=YPos6, labels="Negative\nSlope", cex=textSize, adj=c(0,NA)) } }
samEL = function(X, y, p=3, lambda = NULL, nlambda = NULL, lambda.min.ratio = 0.25, thol=1e-5, max.ite = 1e5, regfunc="L1"){ gcinfo(FALSE) fit = list() fit$p = p fit = list() X = as.matrix(X) y = as.vector(y) n = nrow(X) d = ncol(X) m = d*p if(sum(y<0)>0){ cat("Please check the responses. (Must be non-negative)") fit = "Please check the responses." return(fit) } fit$p = p X.min = apply(X,2,min) X.max = apply(X,2,max) X.ran = X.max - X.min X.min.rep = matrix(rep(X.min,n),nrow=n,byrow=T) X.ran.rep = matrix(rep(X.ran,n),nrow=n,byrow=T) X = (X-X.min.rep)/X.ran.rep fit$X.min = X.min fit$X.ran = X.ran Z = matrix(0,n,m) fit$nkots = matrix(0,p-1,d) fit$Boundary.knots = matrix(0,2,d) for(j in 1:d){ tmp = (j-1)*p + c(1:p) tmp0 = ns(X[,j],df=p) Z[,tmp] = tmp0 fit$nkots[,j] = attr(tmp0,'knots') fit$Boundary.knots[,j] = attr(tmp0,'Boundary.knots') } L0 = norm(Z,"f")^2 Z = cbind(Z,rep(1,n)) a0 = log(mean(y)) z = colSums(matrix(rep(y,m+1),n,m+1)*Z) if(is.null(lambda)){ g = -z + colSums(matrix(rep(exp(a0),m+1),n,m+1)*Z) if(is.null(nlambda)) nlambda = 20; lambda_max=max(sqrt(colSums(matrix(g[1:(p*d)],p,d)^2))) lambda = exp(seq(log(1),log(lambda.min.ratio),length=nlambda))*lambda_max } else nlambda = length(lambda) out = .C("grpPR", A = as.double(Z), y = as.double(y), lambda = as.double(lambda), nlambda = as.integer(nlambda), LL0 = as.double(L0), nn = as.integer(n), dd = as.integer(d), pp = as.integer(p), xx = as.double(matrix(0,m+1,nlambda)), aa0 = as.double(a0), mmax_ite = as.integer(max.ite), tthol = as.double(thol), regfunc = as.character(regfunc), aalpha = as.double(0.5), z = as.double(z),df = as.integer(rep(0,nlambda)),func_norm = as.double(matrix(0,d,nlambda)), package="SAM") fit$lambda = out$lambda fit$w = matrix(out$xx,ncol=nlambda) fit$df = out$df fit$func_norm = matrix(out$func_norm,ncol=nlambda) rm(out,X,y,Z,X.min.rep,X.ran.rep) class(fit) = "samEL" return(fit) } print.samEL = function(x,...){ cat("Path length:",length(x$df),"\n") cat("d.f.:",x$df[1],"--->",x$df[length(x$df)],"\n") } plot.samEL = function(x,...){ par = par(omi = c(0.0, 0.0, 0, 0), mai = c(1, 1, 0.1, 0.1)) matplot(x$lambda,t(x$func_norm),type="l",xlab="Regularization Parameters",ylab = "Functional Norms",cex.lab=2,log="x",lwd=2) } predict.samEL = function(object, newdata,...){ gcinfo(FALSE) out = list() nt = nrow(newdata) d = ncol(newdata) X.min.rep = matrix(rep(object$X.min,nt),nrow=nt,byrow=T) X.ran.rep = matrix(rep(object$X.ran,nt),nrow=nt,byrow=T) newdata = (newdata-X.min.rep)/X.ran.rep newdata = pmax(newdata,0) newdata = pmin(newdata,1) m = object$p*d Zt = matrix(0,nt,m) for(j in 1:d){ tmp = (j-1)*object$p + c(1:object$p) Zt[,tmp] = ns(newdata[,j],df=object$p,knots=object$knots[,j],Boundary.knots=object$Boundary.knots[,j]) } out$expectation = exp(cbind(Zt,rep(1,nt))%*%object$w) rm(Zt,newdata) return(out) }
demo.FCAk <- function(data) {cat(" If you've got a nice little dataset say with 4 or 5 entries","\n", " send it to me and I'll put the demo in the next release ","\n") cat(" [email protected] ","\n") } demo.FCAk() cat("\n","\n","args(demo.FCAk)","\n") print(args(demo.FCAk))
library(maat) library(knitr) library(kableExtra) include_graphics("assessment.svg") include_graphics("routing_T1T2.svg") include_graphics("routing_T2T3.svg") include_graphics("routing_T3.svg") assessment_structure <- createAssessmentStructure( n_test = 3, n_phase = 2, route_limit_below = 1, route_limit_above = 2 ) cor_v <- matrix(.8, 3, 3) diag(cor_v) <- 1 set.seed(1) examinee_list <- simExaminees( N = 10, mean_v = c(0, 0.5, 1.0), sd_v = c(1, 1, 1), cor_v = cor_v, assessment_structure = assessment_structure, initial_grade = "G4", initial_phase = "P1", initial_test = "T1" ) fn <- system.file("extdata", "module_definition_MATH_normal_N500.csv", package = "maat") d <- read.csv(fn) kable_styling(kable(d)) fn <- system.file("extdata", "module_definition_MATH_normal_N500.csv", package = "maat") module_list <- loadModules( fn = fn, base_path = system.file(package = "maat"), assessment_structure = assessment_structure, examinee_list = examinee_list ) cut_scores <- list( G3 = c(-1.47, -0.55, 0.48), G4 = c(-1.07, -0.15, 0.88), G5 = c(-0.67, 0.25, 1.28), G6 = c(-0.27, 0.65, 1.68), G7 = c( 0.13, 1.05, 2.08), G8 = c( 0.53, 1.45, 2.48) ) library(TestDesign) config <- createShadowTestConfig( interim_theta = list(method = "MLE"), final_theta = list(method = "MLE") ) set.seed(1) maat_output_CI <- maat( examinee_list = examinee_list, assessment_structure = assessment_structure, module_list = module_list, config = config, cut_scores = cut_scores, overlap_control_policy = "within_test", transition_policy = "CI", combine_policy = "conditional", transition_CI_alpha = 0.05 ) set.seed(1) maat_output_difficulty <- maat( examinee_list = examinee_list, assessment_structure = assessment_structure, module_list = module_list, config = config, cut_scores = cut_scores, overlap_control_policy = "within_test", transition_policy = "pool_difficulty_percentile", combine_policy = "conditional", transition_CI_alpha = 0.05, transition_percentile_lower = 0.05, transition_percentile_upper = 0.95 ) plot(maat_output_CI, type = "route") plot(maat_output_difficulty, type = "route") plot( x = maat_output_CI, type = "correlation", theta_range = c(-4, 4), main = c("Fall", "Winter", "Spring")) plot( x = maat_output_difficulty, type = "correlation", theta_range = c(-4, 4), main = c("Fall", "Winter", "Spring")) plot( x = maat_output_CI, type = "audit", examinee_id = 1 )
timselsum <- function(var, nts = 6, infile, outfile, nc34 = 4, overwrite = FALSE, verbose = FALSE, nc = NULL) { timselx_wrapper(1, var, infile, outfile, nc34, overwrite, nts = nts, verbose = verbose, nc = nc) }
plot1of15<-function(eList, yearStart, yearEnd, qf, istat, isBottom=FALSE) { localINFO <- getInfo(eList) if("edgeAdjust" %in% names(localINFO)){ edgeAdjust <- localINFO$edgeAdjust } else { edgeAdjust <- TRUE } localAnnualSeries <- makeAnnualSeries(eList, edgeAdjust = edgeAdjust) xSpan<-c(yearStart,yearEnd) xTicks<-pretty(xSpan,n=6) numXTicks<-length(xTicks) xLeft<-xTicks[1] xRight<-xTicks[numXTicks] x<-localAnnualSeries[1,istat,] y<-qf*localAnnualSeries[2,istat,] yTop<-1.05*max(y,na.rm=TRUE) yTicks<-yPretty(yTop) numYTicks<-length(yTicks) yTop<-yTicks[numYTicks] plot(x,y,axes=FALSE,xlim=c(xLeft,xRight),xaxs="i",ylim=c(0,yTop),yaxs="i",ylab="",xlab="",main="",type="p") if(isBottom) axis(1,tcl=0.5,at=xTicks,labels=xTicks) else axis(1,tcl=0.5,at=xTicks,labels=FALSE) axis(2,tcl=0.5,at=yTicks,labels=TRUE) axis(3,tcl=0.5,at=xTicks,labels=FALSE) axis(4,tcl=0.5,at=yTicks,labels=FALSE) y<-qf*localAnnualSeries[3,istat,] par(new=TRUE) plot(x,y,axes=FALSE,xlim=c(xLeft,xRight),xaxs="i",ylim=c(0,yTop),yaxs="i",ylab="",xlab="",main="",type="l") axis(1,tcl=0.5,at=xTicks,labels=FALSE) axis(2,tcl=0.5,at=yTicks,labels=FALSE) axis(3,tcl=0.5,at=xTicks,labels=FALSE) axis(4,tcl=0.5,at=yTicks,labels=FALSE) box() }
layer_brain <- function(geom = NULL, stat = NULL, data = NULL, mapping = NULL, position = NULL, params = list(), inherit.aes = TRUE, check.aes = TRUE, check.param = TRUE, show.legend = NA) { ggplot2::layer( geom = geom, stat = stat, data = data, mapping = mapping, position = position, params = params, inherit.aes = inherit.aes, check.aes = check.aes, check.param = check.param, show.legend = show.legend, layer_class = LayerBrain ) } LayerBrain <- ggproto("LayerBrain", ggplot2:::Layer, setup_layer = function(self, data, plot) { dt <- ggproto_parent(ggplot2:::Layer, self)$setup_layer(data, plot) atlas <- as.data.frame(self$geom_params$atlas) if(is.null(atlas) | nrow(atlas) == 0) stop("No atlas supplied, please provide a brain atlas to the geom.", call. = FALSE) if(!is.null(self$geom_params$hemi)){ hemi <- match.arg(self$geom_params$hemi, unique(atlas$hemi)) atlas <- atlas[atlas$hemi %in% hemi,] } if(!is.null(self$geom_params$side)){ side <- match.arg(self$geom_params$side, unique(atlas$side)) atlas <- atlas[atlas$side %in% side,] } if(class(dt)[1] != "waiver"){ data <- brain_join(dt, atlas) merge_errs <- sapply(data$geometry, function(x) ifelse(length(!is.na(x)) > 0, TRUE, FALSE)) if(any(!merge_errs)){ k <- data[!merge_errs,] k <- k[,apply(k, 2, function(x) all(!is.na(x)))] k$geometry <- NULL k <- paste(utils::capture.output(k), collapse="\n") warning(paste("Some data not merged. Check for spelling mistakes in:\n", k, collapse="\n "), call. = FALSE) data <- data[merge_errs,] } }else{ data <- atlas } data <- sf::st_as_sf(data) if ((isTRUE(self$inherit.aes) && is.null(self$computed_mapping$geometry) && is.null(plot$computed_mapping$geometry)) || (!isTRUE(self$inherit.aes) && is.null(self$computed_mapping$geometry))) { if (ggplot2:::is_sf(data)) { geometry_col <- attr(data, "sf_column") self$computed_mapping$geometry <- as.name(geometry_col) } } if ((isTRUE(self$inherit.aes) && is.null(self$computed_mapping$hemi) && is.null(plot$computed_mapping$hemi)) || (!isTRUE(self$inherit.aes) && is.null(self$computed_mapping$hemi))) { self$computed_mapping$hemi <- as.name("hemi") } if ((isTRUE(self$inherit.aes) && is.null(self$computed_mapping$side) && is.null(plot$computed_mapping$side)) || (!isTRUE(self$inherit.aes) && is.null(self$computed_mapping$side))) { self$computed_mapping$side <- as.name("side") } if ((isTRUE(self$inherit.aes) && is.null(self$computed_mapping$type) && is.null(plot$computed_mapping$type)) || (!isTRUE(self$inherit.aes) && is.null(self$computed_mapping$type))) { self$computed_mapping$type <- as.name("type") } if ((isTRUE(self$inherit.aes) && is.null(self$computed_mapping$fill) && is.null(plot$computed_mapping$fill)) || (!isTRUE(self$inherit.aes) && is.null(self$computed_mapping$fill))) { self$computed_mapping$fill <- as.name("region") } self$computed_mapping$label <- as.name("label") self$geom_params$legend <- "polygon" data } ) if(getRversion() >= "2.15.1"){ utils::globalVariables(c("layer")) }
getUtopiaPayoff<-function(v){ paramCheckResult=getEmptyParamCheckResult() initialParamCheck_utopiaPayoff(paramCheckResult = paramCheckResult, v) A = v n=getNumberOfPlayers(A) N=length(A) M=A[N]-A[(N-1):(N-n)] return(M) } initialParamCheck_utopiaPayoff=function(paramCheckResult,v=v){ stopOnInvalidGameVector(paramCheckResult, v) }
eulersys <- function(f, x0, y0, h, n) { x <- x0 y <- y0 values <- data.frame(x = x, t(y0)) for(i in 1:n) { y0 <- y0 + h * f(x0, y0) x0 <- x0 + h values <- rbind(values, data.frame(x = x0, t(y0))) } return(values) }
context("Just testing codonFraction functionality") test_that("Check codonFraction works properly",{ CodonFr<-CodonFraction(seqs=c("ATACGAATCATA","ATGGTCCTCATGGTGGTG")) codonList<-list("A"=c("GCT","GCC","GCA","GCG"),"R"=c("AGA","AGG","CGT","CGC","CGA","CGG"), "N"=c("AAT","AAC"),"D"=c("GAT","GAC"),"C"=c("TGT","TGC"),"Q"=c("CAA","CAG"), "E"=c("GAA","GAG"),"G"=c("GGT","GGC","GGA","GGG"),"H"=c("CAT","CAC"), "I"=c("ATT","ATC","ATA"),"L"=c("TTA","TTG","CTT","CTC","CTA","CTG"),"K"=c("AAA","AAG"), "M"=c("ATG"),"F"=c("TTT","TTC"),"P"=c("CCT","CCC","CCA","CCG"), "S"=c("AGT","AGC","TCT","TCC","TCA","TCG"),"T"=c("ACT","ACC","ACA","ACG"),"W"=c("TGG"), "Y"=c("TAT","TAC"),"V"=c("GTT","GTC","GTA","GTG"),"STOPcod"=c("TAA","TAG","TGA")) codonVector<-unlist(codonList) numCodon<-length(codonVector) expected_matrix<-matrix(0,ncol = numCodon,nrow = 2) colnames(expected_matrix)<-codonVector expected_matrix[1,c("ATA","CGA","ATC")]<-c(2/3,1,1/3) expected_matrix[2,c("ATG","GTC","CTC","GTG")]<-c(2/2,1/3,1,2/3) lexSort<-nameKmer(k=3,type = "dna") expected_matrix<-expected_matrix[,lexSort] dimnames(expected_matrix)<-NULL dimnames(CodonFr)<-NULL expect_equal(CodonFr,expected_matrix) })
.cor_test_bayes <- function(data, x, y, ci = 0.95, method = "pearson", bayesian_prior = "medium", bayesian_ci_method = "hdi", bayesian_test = c("pd", "rope", "bf"), ...) { insight::check_if_installed("BayesFactor") var_x <- .complete_variable_x(data, x, y) var_y <- .complete_variable_y(data, x, y) if (tolower(method) %in% c("spearman", "spear", "s")) { var_x <- datawizard::ranktransform(var_x, sign = TRUE, method = "average") var_y <- datawizard::ranktransform(var_y, sign = TRUE, method = "average") method <- "Bayesian Spearman" } else if (tolower(method) %in% c("gaussian")) { var_x <- stats::qnorm(rank(var_x) / (length(var_x) + 1)) var_y <- stats::qnorm(rank(var_y) / (length(var_y) + 1)) method <- "Bayesian Gaussian rank" } else { method <- "Bayesian Pearson" } out <- .cor_test_bayes_base( x, y, var_x, var_y, ci = ci, bayesian_prior = bayesian_prior, bayesian_ci_method = bayesian_ci_method, bayesian_test = bayesian_test, ... ) out$Method <- method out } .cor_test_bayes_base <- function(x, y, var_x, var_y, ci = 0.95, bayesian_prior = "medium", bayesian_ci_method = "hdi", bayesian_test = c("pd", "rope", "bf"), method = "pearson", ...) { insight::check_if_installed("BayesFactor") if (x == y) { rez <- BayesFactor::correlationBF(stats::rnorm(1000), stats::rnorm(1000), rscale = bayesian_prior) params <- parameters::model_parameters( rez, dispersion = FALSE, ci_method = bayesian_ci_method, test = bayesian_test, rope_range = c(-0.1, 0.1), rope_ci = 1, ... ) if ("Median" %in% names(params)) params$Median <- 1 if ("Mean" %in% names(params)) params$Mean <- 1 if ("MAP" %in% names(params)) params$MAP <- 1 if ("SD" %in% names(params)) params$SD <- 0 if ("MAD" %in% names(params)) params$MAD <- 0 if ("CI_low" %in% names(params)) params$CI_low <- 1 if ("CI_high" %in% names(params)) params$CI_high <- 1 if ("pd" %in% names(params)) params$pd <- 1 if ("ROPE_Percentage" %in% names(params)) params$ROPE_Percentage <- 0 if ("BF" %in% names(params)) params$BF <- Inf } else { rez <- BayesFactor::correlationBF(var_x, var_y, rscale = bayesian_prior) params <- parameters::model_parameters( rez, dispersion = FALSE, ci_method = bayesian_ci_method, test = bayesian_test, rope_range = c(-0.1, 0.1), rope_ci = 1, ... ) } if (sum(names(params) %in% c("Median", "Mean", "MAP")) == 1) { names(params)[names(params) %in% c("Median", "Mean", "MAP")] <- "rho" } params[names(params) %in% c("Effects", "Component")] <- NULL params <- params[names(params) != "Parameter"] params$Parameter1 <- x params$Parameter2 <- y params[unique(c("Parameter1", "Parameter2", names(params)))] }
print.R0.R <- function (x, ... ) { if (class(x)!="R0.R") { stop("'x' must be of class 'R0.R'") } cat("Reproduction number estimate using ",x$method," method.\n") if (x$method.code %in% c("EG","ML","AR")) { cat("R : ",x$R) if (!any(is.na(x$conf.int))) { cat("[", x$conf.int[1],",",x$conf.int[2],"]\n") } } else { if (x$method.code %in% c("TD","SB")) { cat(x$R[1:min(length(x$R),10)],"...\n") } } cat("\n") }
add1.mixmeta <- function(object, ...) { if(!object$method %in% c("fixed","ml")) stop("Fit only comparable in models with method='fixed' or method='ml'") NextMethod(generic="add1", ...) }
library(stringr) library(tableschema.r) library(testthat) library(foreach) library(config) context("types.castInteger") TESTS <- list( list('default', 1, 1, {} ), list('default', '1', 1, {} ), list('default', '1$', 1, list(bareNumber = FALSE) ), list('default', 'ab1$', 1, list(bareNumber = FALSE) ), list('default', '3.14', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r")), {}), list('default', '', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r")), {}), list('default', 1.2, config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r")), {}), list('default', types.castInteger('default', list(1:5)), config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r")), {}) ) foreach(j = seq_along(TESTS) ) %do% { TESTS[[j]] <- setNames(TESTS[[j]], c("format", "value", "result","options")) test_that(str_interp('format "${TESTS[[j]]$format}" should check "${TESTS[[j]]$value}" as "${TESTS[[j]]$result}"'), { expect_equal(types.castInteger(TESTS[[j]]$format, TESTS[[j]]$value, TESTS[[j]]$options), TESTS[[j]]$result) }) } test_that('error at NULL values',{ expect_error(types.castInteger('default', NULL)) })
context("charlatan_settings") test_that("charlatan_settings - default", { aa <- charlatan_settings() expect_is(aa, "list") expect_named(aa, "global_messy") expect_null(aa$global_messy) }) test_that("charlatan_settings - set messy to TRUE", { aa <- charlatan_settings(messy = TRUE) expect_is(aa, "list") expect_named(aa, "global_messy") expect_true(aa$global_messy) }) test_that("charlatan_settings - global settings override local settings", { charlatan_settings() aa <- PersonProvider$new() expect_false(aa$messy) charlatan_settings(messy = TRUE) bb <- PersonProvider$new() expect_true(bb$messy) })
office_get_offices_by_level <- function(office_level_ids) { office_level_ids %<>% as_char_vec() r <- "Office.getOfficesByLevel?" out <- tibble() for (l in office_level_ids) { q <- elmers("&levelId={l}") this <- get( req = r, query = q, level_one = "offices", level_two = "office" ) out %<>% bind_rows(this) } out %>% select( office_id, name, title, office_level_id, everything() ) %>% distinct() }
plotMCMCdiag <- function(x, nbloc=3, HIWg=NULL, header="", ...){ if (!inherits(x, "BayesSUR")) stop("Use only with a \"BayesSUR\" object") x$output[-1] <- paste(x$output$outFilePath,x$output[-1],sep="") logP <- t( as.matrix( read.table(x$output$logP) ) ) model_size <- as.matrix( read.table(x$output$model_size) ) ncol_Y <- ncol(read.table(x$output$gamma)) nIter <- x$input$nIter covariancePrior <- x$input$covariancePrior if(covariancePrior=="HIW" & is.null(x$output$Gvisit)) Gvisit <- as.matrix( read.table(x$output$Gvisit) ) if(nIter <= 1) stop("The diagosis only shows results from more than one MCMC iteration!") if(nIter < 4000) message("NOTE: The diagosis only shows results of two iteration points due to less than 4000 MCMC iterations!") if(nIter >= 4000){ logP <- logP[,ncol(logP)-floor(nIter/1000)-1+1:floor(nIter/1000)] }else{ logP <- logP[,c(1,ncol(logP))] } if(is.null(HIWg)){ Ptau.indx <- ifelse(covariancePrior!="IG", 7, 3) Plik.indx <- ifelse(covariancePrior!="IG", 10, 5) model_size <- model_size if(nIter >= 4000){ model_size <- rowSums( model_size[nrow(model_size)-floor(nIter/1000)-1+1:floor(nIter/1000),] ) }else{ model_size <- rowSums( model_size[c(1,nrow(model_size)),] ) } dens.all <- density(logP[Ptau.indx,]) if(nIter >= 4000){ dens.first <- density(logP[Ptau.indx, 1:floor(ncol(logP)/2)]) dens.last <- density(logP[Ptau.indx, (1+floor(ncol(logP)/2)):ncol(logP)]) ymin <- min(dens.all$y,dens.first$y,dens.last$y) ymax <- max(dens.all$y,dens.first$y,dens.last$y) xmin <- min(dens.all$x,dens.first$x,dens.last$x) xmax <- max(dens.all$x,dens.first$x,dens.last$x) }else{ ymin <- min(dens.all$y) ymax <- max(dens.all$y) xmin <- min(dens.all$x) xmax <- max(dens.all$x) nbloc <- 1 } mid <- floor(floor(ncol(logP)/2)/nbloc) ymax2 <- xmin2 <- xmax2 <- list.dens <- NULL for (i in 1:nbloc){ dens <- density(logP[Ptau.indx, (ifelse(nbloc==1,0,floor(ncol(logP)/2))+1+mid*(i-1)):ncol(logP)]) ymax2 <- max(ymax2,dens$y) xmin2 <- min(xmin2,dens$x) xmax2 <- max(xmax2,dens$x) list.dens <- c(list.dens,list(dens)) } opar <- par(no.readonly=TRUE) on.exit(par(opar)) par(mfrow=c(2,2)) if(nbloc>1){ plot.default(logP[Plik.indx,], xlab="Iterations (*1000)", ylab="Log likelihood (posterior)", type="l", lty=1, ...) }else{ plot.default(logP[Plik.indx,]~c(1,nIter), xlab="Iterations", ylab="Log likelihood (posterior)", type="l", lty=1, ...) } if(nbloc>1){ plot.default(model_size, xlab="Iterations (*1000)", ylab="Model size", type="l", lty=1, ...) }else{ plot.default(model_size~c(1,nIter), xlab="Iterations", ylab="Model size", type="l", lty=1, ...) } title.0 <- expression(paste("Log Posterior Distribution: log ",P(gamma~group("|",list(Y,.),"")))) plot.default(dens.all,main="",col="black",xlim=c(xmin,xmax),ylim=c(ymin,ymax),xlab=title.0,ylab="", type="l", lty=1) if(nIter >= 4000){ par(new=TRUE) plot.default(dens.first,main="",col="red",xlim=c(xmin,xmax),ylim=c(ymin,ymax),xlab="",ylab="", type="l", lty=1) par(new=TRUE) plot.default(dens.last,main="",col="green",xlim=c(xmin,xmax),ylim=c(ymin,ymax),xlab="",,ylab="Density", type="l", lty=1) if(nbloc>1) legend("topleft",title="iteration",legend=paste(c("ALL","First half","Last half")," = [",c(1,1,floor(ncol(logP)/2)*1000+1),":",c(ncol(logP),floor((ncol(logP))/2),ncol(logP))*1000,"]",sep=""),col=1:3,lty=1,text.col=1:3, cex=0.8) } for (i in 1:nbloc){ plot.default(list.dens[[i]],col=i,xlim=c(xmin2,xmax2),ylim=c(ymin,ymax2),xlab=title.0,ylab="", type="l", lty=1,main="") if(nbloc>1) par(new=TRUE) } title(ylab="Density") if(nbloc>1) legend("topleft",title="moving window",legend=paste("set ",1:nbloc," = [",(floor((ncol(logP))/2)+mid*(nbloc:1-1))*1000+1,":",(ncol(logP))*1000,"]",sep=""),col=1:nbloc,lty=1,text.col=1:nbloc, cex=0.8) }else{ if(covariancePrior != "HIW") stop("The argument HIWg only works for the model with hyper-inverse Wishart prior on the covariance!") if(HIWg == "degree"){ m <- ncol_Y node1 <- node2 <- NULL for(i in 1:(m-1)){ node1 <- c(node1, rep(i, m-i)) node2 <- c(node2, (i+1):m) } nodes <- cbind(node1, node2) node.degree <- matrix(0, nrow=nrow(Gvisit), ncol=m) for(i in 1:m) node.degree[,i] <- rowSums(Gvisit[,which(nodes==i, arr.ind=TRUE)[,1]]) matplot(node.degree, type="l", lty=1, col=hcl.colors(m), xlab="Iterations (*1000)", ylab="degree", main="Response degrees", xlim=c(1,nrow(Gvisit)*1.1)) legend("topright",legend=1:m,col=hcl.colors(m),lty=1,text.col=hcl.colors(m), cex=1/m*4) } if(substr(HIWg, 1, 4) == "edge"){ m <- ncol_Y node1 <- node2 <- NULL for(i in 1:(m-1)){ node1 <- c(node1, rep(i, m-i)) node2 <- c(node2, (i+1):m) } if(HIWg == "edge"){ matplot(Gvisit, type="l", lty=1, col=hcl.colors(ncol(Gvisit)), xlab="Iterations (*1000)", ylab="", main="Edges selection", xlim=c(1,nrow(Gvisit)*1.1)) legend("topright",legend=paste(node1,"-",node2,sep=""),col=hcl.colors(ncol(Gvisit)),lty=1,text.col=hcl.colors(ncol(Gvisit)), cex=1/m*2) }else{ plot.default(Gvisit[,which(paste(node1,node2,sep="")==substr(HIWg,5,nchar(HIWg)))], type="l", lty=1, xlab="Iterations (*1000)", ylab="", main=paste("Edge-",substr(HIWg,5,nchar(HIWg))," selection",sep="")) } } if(HIWg == "lik"){ Gvisit <- t(logP[1:4,]) matplot(Gvisit, type="l", lty=1, col=1:ncol(Gvisit), xlab="Iterations (*1000)", ylab="Log likelihood (posterior)", main="Likelihoods of graph learning") legend("topright",legend=c("tau", "eta", "JT", "SigmaRho"),col=1:ncol(Gvisit),lty=1,text.col=1:ncol(Gvisit), cex=0.8) } } title(paste("\n",header,sep=""), outer=T) }
timeOptSimPwrLaw <- function (dat,numsim=2000,beta=NULL,sedrate=NULL,sedmin=0.5,sedmax=5,numsed=100,linLog=1,limit=T,fit=1,fitModPwr=T,flow=NULL,fhigh=NULL,roll=NULL,targetE=NULL,targetP=NULL,detrend=T,ncores=2,output=0,genplot=T,check=T,verbose=T) { if(verbose) cat("\n----- TimeOpt Monte Carlo Simulation -----\n") cormethod=1 if(!is.null(sedrate) && verbose) { cat("\n**** WARNING: you are only investigating one sedimentation rate.\n") cat(" sedrate option takes precedence over sedmin/sedmax/numsed\n\n") sedmin=sedrate sedmax=sedrate numsed=1 } dat = data.frame(dat) npts <- length(dat[,1]) dx <- dat[2,1]-dat[1,1] if(check) { if(dx<0) { if (verbose) cat("\n * Sorting data into increasing height/depth/time, removing empty entries\n") dat <- dat[order(dat[,1], na.last = NA, decreasing = F), ] dx <- dat[2,1]-dat[1,1] npts <- length(dat[,1]) } dtest <- dat[2:npts,1]-dat[1:(npts-1),1] epsm=1e-9 if( (max(dtest)-min(dtest)) > epsm ) { cat("\n**** ERROR: sampling interval is not uniform.\n") stop("**** TERMINATING NOW!") } } if (verbose) { cat(" * Number of data points in stratigraphic series:",npts,"\n") cat(" * Stratigraphic series length (meters):",(npts-1)*dx,"\n") cat(" * Sampling interval (meters):",dx,"\n\n") } if (detrend) { lm.1 <- lm(dat[,2] ~ dat[,1]) dat[2] <- dat[2] - (lm.1$coeff[2]*dat[1] + lm.1$coeff[1]) if(verbose) cat(" * Linear trend subtracted. m=",lm.1$coeff[2],"b=",lm.1$coeff[1],"\n") } dat[2]=dat[2]-colMeans(dat[2]) dat[2]=dat[2]/sapply(dat[2],sd) if(is.null(beta)) { spec1=periodogram(dat,padfac=1,output=1,verbose=F,genplot=F) spec2=data.frame(cbind(spec1[,1],spec1[,3])) spec2=spec2[-length(spec2[,1]),] beta=pwrLawFit(spec2,output=2,verbose=F,genplot=F)[,1] if(verbose) cat(" * Estimated beta =",beta,"\n") } res=timeOpt(dat,sedmin=sedmin,sedmax=sedmax,numsed=numsed,linLog=linLog,limit=limit,fit=fit,fitModPwr=fitModPwr,flow=flow,fhigh=fhigh,roll=roll,targetE=targetE,targetP=targetP,detrend=detrend,output=1,title=NULL,genplot=F,verbose=F,check=F) datCorPwr = max(res[,4]) if(verbose) { cat(" * (Envelope r^2) x (Spectral Power r^2) =", datCorPwr,"\n") } if(verbose) cat("\n * PLEASE WAIT: Performing", numsim,"simulations using", ncores,"cores\n") if(ncores<2) stop("WARNING: number of ncores must be greater than one!") cl<-makeCluster(as.integer(ncores)) registerDoParallel(cl) resParallel<-foreach(icount(numsim),.combine=rbind) %dopar% { sim = pwrLaw(npts, dx, mean=0, sdev=1, beta=beta, genplot=F, verbose=F) sim[2]=sim[2]-colMeans(sim[2]) sim[2]=sim[2]/sapply(sim[2],sd) simres=max(timeOpt(sim,sedmin=sedmin,sedmax=sedmax,numsed=numsed,linLog=linLog,limit=limit,fit=fit,fitModPwr=fitModPwr,flow=flow,fhigh=fhigh,roll=roll,targetE=targetE,targetP=targetP,detrend=detrend,output=1,title=NULL,genplot=F,verbose=F,check=F)[4]) simres } stopCluster(cl) simres=resParallel numgt = sum(simres>datCorPwr) pvalCorPwr=numgt/numsim if(pvalCorPwr < (10/numsim) && (10/numsim) <=1 ) pvalCorPwr= 10/numsim if(pvalCorPwr >= (10/numsim) && (10/numsim) <=1 ) pvalCorPwr=pvalCorPwr if((10/numsim) > 1 ) pvalCorPwr=1 if(verbose) cat("\n * (Envelope r^2) * (Spectral Power r^2) p-value =",pvalCorPwr, "\n") if(genplot) { dev.new(title = paste("TimeOpt Monte Carlo Results"), height = 5, width = 6) par(mfrow=c(1,1)) plot(density(simres), col="black",xlim=c(0,1),type="l",xlab=expression(paste({"r"^2}["opt"])),main=expression(bold(paste({"r"^2}["opt"]," Monte Carlo Results"))),cex.lab=1.1,lwd=2) polygon(density(simres),col="red",border=NA) abline(v=datCorPwr,col="blue",lwd=2,lty=3) mtext(round(datCorPwr,digits=5),side=3,line=0,at=datCorPwr,cex=1,font=4,col="blue") } if(output == 1) return(data.frame(pvalCorPwr)) if(output == 2) return(data.frame(simres)) }
iso_simulation_by_heriability = function(n.row, n.col, lon.lat=FALSE, mile=FALSE, density.choice, density.layout=c('diagSet', 'random', 'equal_space', 'p_rep'), h2, sigma_env, sigma_variety=(sigma_env*h2)/(1-h2), mu_variety, mu_check=mu_variety+1.68*sqrt(sigma_variety), cov_fun='exp', ranges=sqrt(2), simulation=3, nugget=0, mu_floor=0, p_rep_check=0.05) { density.choice = sort(round(density.choice,2)) tmp.1 = check_layout_generation(n.row, n.col, density.choice, density.layout, p_rep_check=p_rep_check) D.tmp.fix = spatial_dist(tmp.1[[1]][[1]][,1:2], lon.lat=lon.lat, mile=mile) check=NULL dta.out.tmp = do.call(rbind, lapply(1:simulation, function(x){ true.pool=rnorm(n.row*n.col, mu_variety, sqrt(sigma_variety)) env.error=iso_spatial_floor(D.tmp.fix, cov.var=cov_fun, nugget=nugget, sill=sigma_env, ranges=ranges, mu=mu_floor) do.call(rbind, lapply(1:length(density.choice), function(y){ den.=density.choice[y] general.design=sample(true.pool, round(n.row*n.col*(1-den.))) p_rep.design=sample(true.pool, round(n.row*n.col*(1-(den.-p_rep_check)/2-p_rep_check))) do.call(rbind, lapply(density.layout, function(z){ print(paste(x,y,z)) den.ind=as.character(den.) tmp.2=tmp.1[[z]][[den.ind]] if(z=='p_rep'){ tmp.2$env.error=env.error; tmp.2$true.value=NA; tmp.2$entry='check'; tmp.2$p_rep=NA p_rep.dta=taRifx::sort.data.frame(droplevels(subset(tmp.2, !check %in% c(0, 1))), f=~check) p.true=sample(1:length(p_rep.design), round(n.row*n.col*(den.-p_rep_check)/2)) p_rep.dta$true.value=rep(p_rep.design[p.true], each=2) if(length(p.true)!=0){ p_rep.dta$entry=paste0('entry.d', p_rep.dta$check-1) p_rep.dta$p_rep=T } sig.dta=droplevels(subset(tmp.2, check %in% 0)) if(length(p.true)==0){sig.dta$true.value=p_rep.design}else{sig.dta$true.value=p_rep.design[-p.true]} sig.dta$entry=paste0('entry.', 1:nrow(sig.dta)) sig.dta$p_rep=F check.dta=droplevels(subset(tmp.2, check %in% 1)) check.dta$true.value=mu_check; check.dta$p_rep=F out=data.frame(simulation=x, layout.=z, tot.den=den., den.check=p_rep_check, den.p_rep=den.-p_rep_check, taRifx::sort.data.frame(rbind(p_rep.dta, sig.dta, check.dta), f=~row.var+col.var)) out$response=with(out, true.value+env.error); return(out) } else { tmp.2$env.error=env.error check.dta=droplevels(subset(tmp.2, check %in% 1)) check.dta$true.value=mu_check; check.dta$entry='check'; check.dta$p_rep=F sig.dta=droplevels(subset(tmp.2, check %in% 0)) sig.dta$true.value=general.design sig.dta$entry=paste0('entry.', 1:nrow(sig.dta)); sig.dta$p_rep=F out=data.frame(simulation=x, layout.=z, tot.den=den., den.check=den., den.p_rep=0, taRifx::sort.data.frame(rbind(check.dta, sig.dta), f=~row.var+col.var)) out$response=with(out, true.value+env.error); return(out) } }) ) }) ) }) ) out=data.frame(grid.=paste0(n.row,'*',n.col), h2=h2, ranges=ranges, dta.out.tmp) }
context("Element apply") test_that("elementapply_byname works as expected", { half <- function(x){ x/2 } m <- matrix(c(1:4), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>% setrowtype("row") %>% setcoltype("col") expect_equal(elementapply_byname(FUN = half, a = m, row = "r1", col = "c1"), matrix(c(0.5, 2, 3, 4), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>% setrowtype("row") %>% setcoltype("col")) expect_equal(elementapply_byname(FUN = half, a = m, row = "r2", col = "c1"), matrix(c(1, 1, 3, 4), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>% setrowtype("row") %>% setcoltype("col")) expect_equal(elementapply_byname(FUN = half, a = m, row = "r1", col = "c2"), matrix(c(1, 2, 1.5, 4), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>% setrowtype("row") %>% setcoltype("col")) expect_equal(elementapply_byname(FUN = half, a = m, row = "r2", col = "c2"), matrix(c(1, 2, 3, 2), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>% setrowtype("row") %>% setcoltype("col")) expect_null(elementapply_byname(half, a = NULL, row = "r", col = "c")) expect_error(elementapply_byname(half, a = m, row = "bogus", col = "c1"), "subscript out of bounds") expect_equal(elementapply_byname(half, a = m, row = 1, col = 1), matrix(c(0.5, 2, 3, 4), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>% setrowtype("row") %>% setcoltype("col")) expect_equal(elementapply_byname(half, a = m, row = 1, col = "c2"), matrix(c(1, 2, 1.5, 4), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>% setrowtype("row") %>% setcoltype("col")) divide <- function(x, divisor){ x/divisor } expect_equal(elementapply_byname(divide, a = m, row = 1, col = 1, .FUNdots = list(divisor = 2)), matrix(c(0.5, 2, 3, 4), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>% setrowtype("row") %>% setcoltype("col")) expect_equal(elementapply_byname(divide, a = m, row = 1, col = 1, .FUNdots = list(divisor = 10)), matrix(c(0.1, 2, 3, 4), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>% setrowtype("row") %>% setcoltype("col")) l <- list(m, m) expected <- matrix(c(10, 2, 3, 4), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>% setrowtype("row") %>% setcoltype("col") expect_equal(elementapply_byname(divide, a = l, row = 1, col = 1, .FUNdots = list(divisor = 0.1)), list(expected, expected)) }) context("Unary apply") test_that("unaryapply_byname works as expected", { productnames <- c("p1", "p2") industrynames <- c("i1", "i2") U <- matrix(1:4, ncol = 2, dimnames = list(productnames, industrynames)) %>% setrowtype("Products") %>% setcoltype("Industries") expect_equal(unaryapply_byname(FUN = `-`, a = U, rowcoltypes = "row"), difference_byname(0, U) %>% setcoltype("Products")) expect_equal(unaryapply_byname(FUN = `-`, a = U, rowcoltypes = "col"), difference_byname(0, U) %>% setrowtype("Industries")) expect_equal(unaryapply_byname(FUN = `-`, a = U, rowcoltypes = "all"), difference_byname(0, U)) }) context("Binary apply") test_that("binaryapply_byname works as expected", { expect_equal(binaryapply_byname(FUN = sum, a = list(1, 2, 3), b = list(4,5,6)), list(5, 7, 9)) expect_error(binaryapply_byname(FUN = sum, a = NULL, b = NULL, match_type = "all", set_rowcoltypes = TRUE, .organize = FALSE), "set_rowcoltypes == TRUE, but a and b and NULL. How can we set row and column types from NULL?") }) context("Cumulative apply") test_that("cumapply_byname works as expected", { expect_equal(cumapply_byname(FUN = `sum`, a = list(1, 2, 3)), list(1, 3, 6)) expect_equal(cumapply_byname(FUN = `prod`, a = list(1, 2, 3)), list(1, 2, 6)) }) context("n-ary apply") test_that("naryapply_byname works as expected", { expect_equal(naryapply_byname(FUN = `-`, 42), -42) expect_equal(naryapply_byname(FUN = `sum`, ... = list(1,2,3)), list(1,2,3)) expect_equal(naryapply_byname(FUN = sum_byname, 2, 3), 5) expect_equal(naryapply_byname(FUN = sum_byname, 2, 3, 4, -4, -3, -2), 0) expect_equal(naryapply_byname(FUN = `^`, list(1,2,3), .FUNdots = list(2)), list(1, 4, 9)) expect_false(matsbyname:::naryapplylogical_byname(FUN = iszero_byname, 42)) })
data.gen.bm <- function(x0=0, w0=0, time=seq(0, by=0.01, length.out = 101), do.plot=TRUE) { delta <- diff(time)[1] n <- length(time) W <- numeric(n) t0 <- time[1] W[1] <- w0 for(i in 2:n) W[i] <- W[i-1] + rnorm(1) * sqrt(delta) x <- ts(W, start=t0, deltat = delta) if (do.plot) { title = paste("Brownian motion\n", "x0 = ", x0, "\u0394t = ", delta) plot(x, xlab = "t", ylab = "x", main = title, type = "l") } return(x) } data.gen.gbm <- function(x0=10, w0=0, mu=1, sigma=0.5, time=seq(0, by=0.01, length.out = 101), do.plot=TRUE) { delta <- diff(time)[1] n <- length(time) W <- numeric(n) t0 <- time[1] W[1] <- w0 for(i in 2:n) W[i] <- W[i-1] + rnorm(1) * sqrt(delta) S <- x0 * exp((mu-sigma^2/2)*(time-t0) + sigma*(W-W[1])) x <- ts(S, start=t0, deltat = delta) if (do.plot) { title = paste("Geometric Brownian motion\n", "x0 = ", x0, "\u0394t = ", delta, "\u03BC = ", mu, "\u03C3 = ", sigma) plot(x, xlab = "t", ylab = "x", main = title, type = "l") } return(x) } data.gen.fbm <- function(hurst=0.95, time=seq(0, by=0.01, length.out=1000), do.plot=TRUE) { if(hurst<0|hurst>1) stop('Error: Hurst parameter must be between 0 and 1') delta <- diff(time)[1] n <- length(time) r <- numeric(n+1) r[1] <- 1 for(k in 1:n) r[k+1] <- 0.5 * ((k+1)^(2*hurst) - 2*k^(2*hurst) + (k-1)^(2*hurst)) r <- c(r, r[seq(length(r)-1, 2)]) lambda <- Re((fft(r)) / (2*n)) W <- fft(sqrt(lambda) * (rnorm(2*n) + rnorm(2*n)*1i)) W <- n^(-hurst) * cumsum(Re(W[1:n])) W=(time[n]^hurst)*W x <- ts(W, start=time[1], deltat = delta) if (do.plot) { title = paste("Fractional Brownian motion\n", "hurst = ", hurst, "\u0394t = ", delta) plot(x, xlab = "t", ylab = "x", main = title, type = "l") } return(x) }
library(Thresher) set.seed(98576) savedSims <- list() savedReap <- list() nProtein <- 20 splinter <- sample((nProtein/2) + (-3:3), 1) positive <- sample(nProtein, nProtein/2) negative <- (1:nProtein)[!((1:nProtein) %in% positive)] posi <- positive[positive <= splinter] nega <- negative[negative <= splinter] rho <- rnorm(1, 0.5, 0.1) sigma1 <- matrix(rho, ncol=nProtein, nrow=nProtein) diag(sigma1) <- 1 sigma2 <- sigma1 sigma2[(1+splinter):nProtein, 1:splinter] <- 0 sigma2[1:splinter, (1+splinter):nProtein] <- 0 sigma3 <- sigma1 sigma3[positive, negative] <- -sigma3[positive, negative] sigma3[negative, positive] <- -sigma3[negative, positive] sigma4 <- sigma2 sigma4[positive, negative] <- -sigma4[positive, negative] sigma4[negative, positive] <- -sigma4[negative, positive] sigma5 <- sigma2 sigma5[posi, nega] <- -sigma5[posi, nega] sigma5[nega, posi] <- -sigma5[nega, posi] nSample <- round(rnorm(1, 300, 60)) print(splinter) print(rho) rm(nega, negative, posi, positive, rho, splinter) counter <- 0 for (nm in paste("sigma", 1:5, sep='')) { ss <- matrix(0, nProtein+2, nProtein+2) diag(ss) <- 1 ss[1:nProtein, 1:nProtein] <- get(nm) counter <- counter+1 value <- SimThresher(ss, nSample, paste(nm, counter, sep="."), method='auer.gervini') savedSims[[counter]] <- value reaped <- Reaper(value, useLoadings=TRUE) savedReap[[counter]] <- reaped } if (FALSE) { for (i in 1:5) makeFigures(savedSims[[i]]) for (i in 1:5) makeFigures(savedReap[[i]]) } sigma <- list(sigma1, sigma2, sigma3, sigma4, sigma5) save(savedSims, savedReap, sigma, file = "../../data/savedSims.Rda")
print.cladisticMatrix <- function(x, ...) { if (!inherits(x = x, what = "cladisticMatrix")) stop("cladistic_matrix must be an object of class \"cladisticMatrix\".") n_blocks <- length(x = x) - 1 n_taxa <- nrow(x = x$matrix_1$matrix) block_sizes <- unname(obj = unlist(x = lapply(X = x[2:length(x)], FUN = function(x) ncol(x = x$matrix)))) n_characters <- sum(block_sizes) data_types <- sort(x = tolower(x = unique(x = unname(obj = unlist(x = lapply(X = x[2:length(x = x)], FUN = function(x) x$datatype)))))) character_ordering <- unname(obj = unlist(x = lapply(X = x[2:length(x = x)], FUN = function(x) x$ordering))) character_weights <- unname(obj = unlist(x = lapply(X = x[2:length(x = x)], FUN = function(x) x$character_weights))) n_unordered_characters <- sum(character_ordering == "unord") n_ordered_characters <- sum(character_ordering == "ord") n_continuous_characters <- sum(character_ordering == "cont") n_stepmatrix_characters <- length(x = grep(pattern = "step", x = character_ordering)) character_sizes <- nchar(x = c(n_unordered_characters, n_ordered_characters, n_continuous_characters, n_stepmatrix_characters)) character_spacings <- unlist(x = lapply(X = as.list(x = max(x = character_sizes) - character_sizes), function(x) paste(rep(x = " ", times = x), collapse = ""))) unique_non_continuous_weights <- unique(x = character_weights[character_ordering != "cont"]) if(length(x = block_sizes) == 1) block_parentheses <- "" if(length(x = block_sizes) == 2) block_parentheses <- paste0(" (in 2 matrix blocks of ", paste0(block_sizes, collapse = " and "), " characters, respectively)") if(length(x = block_sizes) > 2) block_parentheses <- paste0(" (in ", n_blocks, " matrix blocks of ", paste0(paste0(block_sizes[1:(length(x = block_sizes) - 1)], collapse = ", "), ", and ", block_sizes[length(x = block_sizes)]), " characters, respectively)") if(length(x = data_types) == 1) data_type_lines <- data_types if(length(x = data_types) == 2) data_type_lines <- paste0(paste0(data_types, collapse = " and ")) if(length(x = data_types) > 2) data_type_lines <- paste0(paste0(data_types[1:(length(x = data_types) - 1)], collapse = ", "), ", and ", data_types[length(x = data_types)]) if(length(x = unique_non_continuous_weights) == 1) weight_line <- paste0("All non-continuous characters are weighted ", unique_non_continuous_weights, ".\n") if(length(x = unique_non_continuous_weights) > 1) weight_line <- paste0("Non-continuous characters have variable weights.\n") cat(paste0("Cladistic matrix containing ", n_taxa, " taxa and ", n_characters, " ", data_type_lines, " type characters", block_parentheses, ", of which:\n", paste0(" ", character_spacings[1], n_unordered_characters, " are unordered,\n"), paste0(" ", character_spacings[2], n_ordered_characters, " are ordered,\n"), paste0(" ", character_spacings[3], n_continuous_characters, " are continuous, and\n"), paste0(" ", character_spacings[4], n_stepmatrix_characters, " are step-matrix characters\n"), weight_line) ) }
create_ti_method_r <- function( definition, run_fun, package_required = character(), package_loaded = character(), remotes_package = character(), return_function = TRUE ) { definition <- .method_load_definition(definition) definition$run <- lst( backend = "function", run_fun, package_required, package_loaded, remotes_package ) .method_process_definition(definition = definition, return_function = return_function) } .method_execution_preproc_function <- function(method) { run <- method$run if (!is.null(run$package_loaded) && !any(is.na(run$package_loaded)) && length(run$package_loaded)) { for (pack in run$package_loaded) { suppressMessages(do.call(require, list(pack))) } } if (!is.null(run$package_required) && !any(is.na(run$package_required)) && length(run$package_required)) { for (pack in run$package_required) { suppressMessages(do.call(requireNamespace, list(pack))) } } } .method_execution_execute_function <- function(method, inputs, priors, parameters, verbose, seed, preproc_meta) { args <- c( inputs, lst( priors, parameters, verbose, seed ) ) args <- args[intersect(names(args), names(formals(method$run$run_fun)))] trajectory <- do.call(method$run$run_fun, args) trajectory } .method_execution_postproc_function <- function(preproc_meta) { } generate_parameter_documentation <- function(definition) { parameter_ids <- names(definition$parameters$parameters) map_chr( parameter_ids, function(parameter_id) { parameter <- definition$parameters$parameters[[parameter_id]] paste0("@param ", parameter$id, " ", dynparam::get_description(parameter, sep = ". "), ".") } ) }
setConstructorS3("RspDirective", function(value=character(), ...) { extend(RspConstruct(value, ...), "RspDirective") }) setMethodS3("requireAttributes", "RspDirective", function(this, names, condition=c("all", "any"), ...) { condition <- match.arg(condition) attrs <- getAttributes(this) ok <- is.element(names, names(attrs)) if (condition == "all") { if (!all(ok)) { throw(RspPreprocessingException(sprintf("One or more required attributes (%s) are missing", paste(sQuote(names[!ok]), collapse=", ")), item=this)) } } else if (condition == "any") { if (!any(ok)) { throw(RspPreprocessingException(sprintf("At least one of the required attributes (%s) must be given", paste(sQuote(names[!ok]), collapse=", ")), item=this)) } } invisible(this) }, protected=TRUE) setMethodS3("getNameContentDefaultAttributes", "RspDirective", function(item, known=NULL, doc=NULL, ...) { name <- getAttribute(item, "name") content <- getAttribute(item, "content") default <- getAttribute(item, "default") file <- getAttribute(item, "file") if (is.null(name) && is.null(content) && !is.null(file)) { name <- "file" content <- file file <- NULL } if (is.null(name) && is.null(content)) { attrs <- getAttributes(item) names <- setdiff(names(attrs), c("file", "default", known)) if (length(names) == 0L) { throw(RspPreprocessingException("At least one of attributes 'name' and 'content' must be given", item=item)) } name <- names[1L] content <- attrs[[name]] if (length(content) > 1L) content <- paste(content, collapse="") } if (!is.null(file) && !is.null(doc)) { path <- getPath(doc) if (!is.null(path)) { pathname <- file.path(getPath(doc), file) } else { pathname <- file } stop_if_not(!is.null(pathname)) content <- .readText(pathname) } stop_if_not(is.null(content) || length(content) == 1L) if (!is.null(content) && (is.na(content) || content == "NA")) { value <- default } else { value <- content } list(name=name, value=value, content=content, file=file, default=default) }, protected=TRUE) setMethodS3("asRspString", "RspDirective", function(object, ...) { body <- unclass(object) attrs <- getAttributes(object) if (length(attrs) == 0L) { attrs <- "" } else { attrs <- sprintf('%s="%s"', names(attrs), attrs) attrs <- paste(c("", attrs), collapse=" ") } comment <- getComment(object) if (length(comment) == 0L) { comment <- "" } else { comment <- sprintf(" } suffixSpecs <- attr(object, "suffixSpecs") if (length(suffixSpecs) == 0L) { suffixSpecs <- "" } fmtstr <- "@%s%s%s%s" fmtstr <- paste(escFmtStr(.rspBracketOpen), fmtstr, escFmtStr(.rspBracketClose), sep="") s <- sprintf(fmtstr, body, attrs, comment, suffixSpecs) RspString(s) }) setConstructorS3("RspUnparsedDirective", function(value="unparsed", ...) { extend(RspDirective(value, ...), "RspUnparsedDirective") }) setMethodS3("parseDirective", "RspUnparsedDirective", function(expr, ...) { parseAttributes <- function(rspCode, known=mandatory, mandatory=NULL, ...) { bfr <- rspCode known <- unique(union(known, mandatory)) pos <- regexpr("^[ \t\n\r]+", bfr) len <- attr(pos, "match.length") bfr <- substring(bfr, first=len+1L) attrs <- list() if (nchar(bfr) > 0L) { bfr <- paste(" ", bfr, sep="") while (nchar(bfr) > 0L) { pos <- regexpr("^[ \t\n\r]+", bfr) if (pos == -1L) { throw(Exception("Error when parsing attributes of RSP preprocessing directive. Expected white space: ", code=sQuote(rspCode))) } len <- attr(pos, "match.length") bfr <- substring(bfr, first=len+1L) if (nchar(bfr) == 0L) { break } if (regexpr("^ comment <- gsub("^ attr(attrs, "comment") <- comment break } pos <- regexpr("^[abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_][abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0-9_]*", bfr) if (pos == -1L) { throw(Exception("Error when parsing attributes of RSP preprocessing directive. Expected an attribute name: ", code=sQuote(rspCode))) } len <- attr(pos, "match.length") name <- substring(bfr, first=1L, last=len) bfr <- substring(bfr, first=len+1L) pos <- regexpr("^[ \t\n\r]*=[ \t\n\r]*", bfr) if (pos == -1L) { throw(Exception("Error when parsing attributes of RSP preprocessing directive. Expected an equal sign: ", code=sQuote(rspCode))) } len <- attr(pos, "match.length") bfr <- substring(bfr, first=len+1L) bfrR <- charToRaw(bfr) lbracketR <- bfrR[1L] lbracket <- rawToChar(lbracketR) rbracket <- c("{"="}", "("=")", "["="]", "<"=">")[lbracket] if (is.na(rbracket)) { bfrR <- bfrR[-1L] wbracket <- 1L pos <- which(bfrR == lbracketR) if (length(pos) == 0L) { throw(Exception("Error when parsing attributes of RSP preprocessing directive. Expected an attribute value within quotation marks: ", code=sQuote(rspCode))) } if (pos[1L] == 1L) { value <- "" } else { keep <- (bfrR[pos-1L] != charToRaw("\\")) pos <- pos[keep] if (length(pos) == 0L) { throw(Exception("Error when parsing attributes of RSP preprocessing directive. Expected an attribute value within quotation marks: ", code=sQuote(rspCode))) } pos <- pos[1L] bfrR <- bfrR[1:(pos-1)] value <- rawToChar(bfrR) } brackets <- c(lbracket, lbracket) bfr <- substring(bfr, first=pos+2L) } else { for (wbracket in seq_len(nchar(bfr))) { ch <- substring(bfr, first=wbracket, last=wbracket) if (ch != lbracket) { wbracket <- wbracket - 1L break } } bfr <- substring(bfr, first=wbracket+1L) rbracket <- c("{"="\\}", "("="\\)", "["="\\]", "<"=">", "+"="\\+", "."="\\.", "?"="\\?", "|"="\\|")[lbracket] if (is.na(rbracket)) rbracket <- lbracket rbrackets <- paste(rep(rbracket, times=wbracket), collapse="") pattern <- sprintf("^(.*?)([^\\]?)%s", rbrackets) pos <- regexpr(pattern, bfr) if (pos == -1L) { throw(Exception("Error when parsing attributes of RSP preprocessing directive. Expected a attribute value within brackets: ", code=sQuote(rspCode))) } len <- attr(pos, "match.length") value <- substring(bfr, first=1L, last=len-wbracket) lbrackets <- paste(rep(lbracket, times=wbracket), collapse="") rbrackets <- gsub("\\\\", "\\", rbrackets) brackets <- c(lbrackets, rbrackets) bfr <- substring(bfr, first=len+wbracket) } names(value) <- name attrs <- c(attrs, value) } } if (length(names(attrs)) != length(unique(names(attrs)))) throw(Exception("Duplicated attributes in RSP preprocessing directive.", code=sQuote(rspCode))) if (!is.null(known)) { nok <- which(is.na(match(names(attrs), known))) if (length(nok) > 0L) { nok <- paste("'", names(attrs)[nok], "'", collapse=", ", sep="") throw(Exception("Unknown attribute(s) in RSP preprocessing directive: ", nok, code=sQuote(rspCode))) } } if (!is.null(mandatory)) { nok <- which(is.na(match(mandatory, names(attrs)))) if (length(nok) > 0L) { nok <- paste("'", mandatory[nok], "'", collapse=", ", sep="") throw(Exception("Missing attribute(s) in RSP preprocessing directive: ", nok, code=sQuote(rspCode))) } } attrs } body <- expr pattern <- "^[ ]*([abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0-9]*)([ \t\n\r]+(.*))*" if (regexpr(pattern, body) == -1L) { throw("Not an RSP preprocessing directive: ", body) } directive <- gsub(pattern, "\\1", body) directive <- tolower(directive) attrs <- gsub(pattern, "\\2", body) attrs <- parseAttributes(attrs, known=NULL) comment <- attr(attrs, "comment") className <- sprintf("Rsp%sDirective", capitalize(directive)) clazz <- tryCatch({ ns <- getNamespace("R.rsp") Class$forName(className, envir=ns) }, error = function(ex) { NULL }) if (!is.null(clazz)) { res <- newInstance(clazz, attrs=attrs, comment=comment) } else { res <- RspUnknownDirective(directive, attrs=attrs) } attr(res, "suffixSpecs") <- attr(expr, "suffixSpecs") res }) setMethodS3("asRspString", "RspUnparsedDirective", function(object, ...) { body <- unclass(object) suffixSpecs <- attr(object, "suffixSpecs") fmtstr <- "@%s%s" fmtstr <- paste(escFmtStr(.rspBracketOpen), fmtstr, escFmtStr(.rspBracketClose), sep="") s <- sprintf(fmtstr, body, suffixSpecs) RspString(s) }) setConstructorS3("RspIncludeDirective", function(value="include", ...) { this <- extend(RspDirective(value, ...), "RspIncludeDirective") if (!missing(value)) { requireAttributes(this, names=c("file", "text"), condition="any") } this }) setMethodS3("getFile", "RspIncludeDirective", function(directive, ...) { getAttribute(directive, "file") }) setMethodS3("getContent", "RspIncludeDirective", function(directive, ...) { getAttribute(directive, "content") }) setMethodS3("getVerbatim", "RspIncludeDirective", function(directive, ...) { res <- getAttribute(directive, "verbatim", default=FALSE) res <- as.logical(res) res <- isTRUE(res) res }) setMethodS3("getWrap", "RspIncludeDirective", function(directive, ...) { res <- getAttribute(directive, "wrap") if (!is.null(res)) { res <- as.integer(res) } res }) setConstructorS3("RspEvalDirective", function(value="eval", ...) { this <- extend(RspDirective(value, ...), "RspEvalDirective") if (!missing(value)) { requireAttributes(this, names=c("file", "text"), condition="any") lang <- getAttribute(this, default="R") this <- setAttribute(this, "language", lang) } this }) setMethodS3("getFile", "RspEvalDirective", function(directive, ...) { getAttribute(directive, "file") }) setMethodS3("getContent", "RspEvalDirective", function(directive, ...) { getAttribute(directive, "content") }) setConstructorS3("RspPageDirective", function(value="page", ...) { extend(RspDirective(value, ...), "RspPageDirective") }) setMethodS3("getType", "RspPageDirective", function(directive, default=NA, as=c("text", "IMT"), ...) { as <- match.arg(as) res <- getAttribute(directive, "type", default=as.character(default)) res <- tolower(res) if (as == "IMT" && !is.na(res)) { res <- parseInternetMediaType(res) } res }) setConstructorS3("RspUnknownDirective", function(value="unknown", ...) { extend(RspDirective(value, ...), "RspUnknownDirective") }) setConstructorS3("RspErrorDirective", function(value="error", ...) { extend(RspDirective(value, ...), "RspErrorDirective") })
`print.strata` <- function(x,...) { takenone <- if (is.null(x$args$takenone)) 0 else x$args$takenone L <- x$args$Ls + takenone rh <- x$args$rh ph <- c(x$args$model.control$ptakenone,x$args$model.control$ph,x$args$model.control$pcertain) cat("Given arguments:\n") cat("x = "); print(x$call$x) if (!is.null(x$args$nclass)) cat("nclass = ",x$args$nclass,", ",sep="") if (!is.null(x$args$CV)) cat("CV = ",x$args$CV,", ",sep="") if (!is.null(x$args$n)) cat("n = ",x$args$n,", ",sep="") cat("Ls = ",x$args$Ls,sep="") if (!is.null(x$args$takenone)) cat(", takenone = ",x$args$takenone,sep="") if (!is.null(x$args$bias.penalty)) { if (x$args$takenone==1) cat(", bias.penalty = ",x$args$bias.penalty,sep="")} if (!is.null(x$args$takeall)) cat(", takeall = ",x$args$takeall,sep="") cat("\nallocation: q1 = ",x$args$alloc$q1,", q2 = ",x$args$alloc$q2,", q3 = ",x$args$alloc$q3,sep="") if (!is.null(x$args$model)) { cat("\nmodel = ",x$args$model,sep="") nparam <- length(x$args$model.control) if (nparam>0) { cat(": ") for (i in 1:nparam) { cat(names(x$args$model.control)[i],"=",x$args$model.control[[i]],sep=" ") if (i<nparam) cat(", ") } } } if (!is.null(x$args$algo)) { cat("\n") cat("algo = ", x$args$algo, ": ", sep = "") for (i in 1:length(x$args$algo.control)) { if (i %in% c(5,9)) cat("\n ") cat(names(x$args$algo.control)[i]," = ",x$args$algo.control[[i]],sep="") if (i<length(x$args$algo.control)) cat(", ") } } tableau <- data.frame(x$meanh,x$varh,x$Nh,x$nh,ifelse(x$Nh==0,NA,x$nh/x$Nh)) colnames(tableau) <- c("E(Y)","Var(Y)","Nh","nh","fh") if(!is.null(x$args$certain)) tableau <- rbind(tableau,c(x$certain.info["meanc"],NA,x$certain.info["Nc"],x$certain.info["Nc"],1)) tableau <- rbind(tableau,c(NA,NA,round(sum(tableau$Nh)),round(x$n),x$n/sum(tableau$Nh))) rownames(tableau)<-if(!is.null(x$args$certain)) c(paste("stratum",1:L),"","Total") else c(paste("stratum",1:L),"Total") if (grepl("strata.bh", deparse(x$call[[1]]))) { tableau<-cbind("bh"=c(x$args$bh,max(x$args$x)+1,rep(NA,nrow(tableau)-L)), "|"=c(rep("|",nrow(tableau)-1),NA), tableau) } else if (identical(as.character(x$call[[1]]),"strata.cumrootf")||identical(as.character(x$call[[1]]),"strata.geo")) { tableau<-cbind("|"=c(rep("|",nrow(tableau)-1),NA), "bh"=c(x$bh,max(x$args$x)+1,rep(NA,nrow(tableau)-L)), tableau) } else { tableau<-cbind("|"=c(rep("|",nrow(tableau)-1),NA), "bh"=c(x$bh,max(x$args$x)+1,rep(NA,nrow(tableau)-L)), tableau) if(is.numeric(x$args$initbh)) tableau <- cbind("initbh" = c(x$args$initbh, max(x$args$x)+1, rep(NA,nrow(tableau)-L)), tableau) } rh.tab <- if(is.null(x$args$certain)) c(rh,NA) else c(rh,1,NA) if(takenone>0) rh.tab <- c(rep(NA, length(takenone)), rh.tab) tableau <- cbind("rh" = rh.tab,tableau) if (identical(x$args$model,"loglinear")) tableau<-cbind("ph"=c(ph,NA),tableau) type <- c(rep("take-none", takenone), rep("take-some", x$args$Ls - x$takeall), rep("take-all", x$takeall)) tableau <- cbind("|" = c(rep("|", nrow(tableau) - 1), NA), "type" = if(is.null(x$args$certain)) c(type, NA) else c(type, "certain", NA), tableau) tableau[,unlist(lapply(tableau,is.numeric))]<-round(tableau[,unlist(lapply(tableau,is.numeric))],2) tableauc <- format(tableau) substr2last <- function(x) substr(x, nchar(x) -1 , nchar(x)) for (i in 1:(nrow(tableauc)-1)) tableauc[i,] <- ifelse(substr2last(tableauc[i,]) %in% c("NA", "aN"), "-", tableauc[i,]) tableauc[dim(tableauc)[1],] <- ifelse(substr2last(tableauc[dim(tableauc)[1],]) == "NA", "", ifelse(substr2last(tableauc[dim(tableauc)[1],]) == "aN", "-", tableauc[dim(tableauc)[1],])) cat("\n\nStrata information:\n") print(tableauc,na.print="") cat("\nTotal sample size:",x$n,"\n") cat("Anticipated population mean:",x$mean,"\n") sortie <- if (is.null(x$args$takenone)) 1 else { if(0==x$args$takenone) 2 else 3 } if (sortie%in%c(1,2)) { cat("Anticipated CV:",ifelse(1==sortie,x$CV,x$RRMSE),"\n") if (2==sortie) cat("Note: CV=RRMSE (Relative Root Mean Squared Error) because takenone=0.\n") } else { est<-cbind(x$relativebias,x$propbiasMSE,x$RRMSE,x$args$CV) dimnames(est) <- if(length(est)==4) list(" ",c("relative bias","prop bias MSE","RRMSE","target RRMSE")) else list(" ",c("relative bias","prop bias MSE","RRMSE")) cat("\nAnticipated moments of the estimator:\n") print.default(est, print.gap = 2, quote = FALSE, right=TRUE) } if (!is.null(x$converge) && !is.na(x$converge)) { if (!x$converge) cat("\nWarning : the algorithm did not converge.\n") } } `plot.strata` <- function(x,logscale=FALSE,drop=0,main=paste("Graphical Representation of the Stratified Design",xname),xlab,...) { L <- x$args$L ncert <- if (is.null(x$args$certain)) 0 else 1 if (!((length(drop)==1)&&isTRUE((drop%%1)==0)&&(isTRUE(drop>=0)||isTRUE(drop<x$Nh[L])))) stop("'drop' must be an integer between 0 and 'Nh[L]'-1 inclusively") data <- if(is.null(x$args$certain)) sort(x$args$x) else sort(x$args$x[-x$args$certain]) data <- data[1:(length(data)-drop)] if(logscale) data <- log(data) bh <- if (identical(as.character(x$call[[1]]),"strata.bh")) x$args$bh else x$bh bhfull <- if(logscale) c(min(data),log(bh),max(data)+1) else c(min(data),bh,max(data)+1) if (missing(xlab)) xlab <- if(logscale) "Stratification variable X on the log scale" else "Stratification variable X" xname <- paste(deparse(substitute(x), 500), collapse = "\n") if (L<10) { layout(matrix(c(2,1),2,1),heights=c(1,4)) par(mar=c(5.1, 4.1, 0.1, 4.1)) hist(data,breaks="FD",col=rgb(0.5,0.7,1),border=rgb(0.3,0.5,1),freq=FALSE,main="",xlab=xlab,xlim=c(bhfull[1],bhfull[L+1])) for (i in 2:L) abline(v=bhfull[i],lty=1) par(mar=c(1, 4.1, 3.6, 4.1)) plot(x=c(bhfull[1],bhfull[L+1]),y=rep(2,2),xlim=c(bhfull[1],bhfull[L+1]),ylim=c(1,3), type="l",xaxt="n",yaxt="n",xlab="",ylab="") abline(h=2) space <- bhfull[-1]-bhfull[-(L+1)] lcert <- (bhfull[L+1]-bhfull[1])/10 off <- (bhfull[L+1]-bhfull[1])*0.04 if (!is.null(x$args$certain)) space <- c(space[-L],space[L]-lcert,lcert) if (any(space<(bhfull[L+1]-bhfull[1])/15)) { space <- rep(bhfull[L+1]-bhfull[1]+off*2,L+ncert)/(L+ncert) space[1] <- space[1] - off space[length(space)] <- space[length(space)] - off } abline(v=bhfull[1]+cumsum(space)[-length(space)],lty=1) pos <- bhfull[1]+c(0,cumsum(space)[-length(space)])+space/2 pos[1] <- pos[1] - off/2 pos[length(pos)] <- pos[length(pos)] + off/2 text(x=pos,y=rep(2.5,length(space)),labels=as.character(c(x$Nh,x$certain.info["Nc"]))[1:(L+ncert)]) text(x=pos,y=rep(1.5,length(space)),labels=as.character(c(x$nh,x$certain.info["Nc"]))[1:(L+ncert)]) mtext(c("Nh","nh"),at=c(2.5,1.5),line=1,side=2,las=1,font=2) mtext(c(sum(x$Nh),sum(x$nh))+x$certain.info["Nc"],at=c(2.5,1.5),line=1,side=4,las=1,font=2) mtext(c(1:L,"certain")[1:(L+ncert)],at=pos,line=0,side=3,las=1,font=2) mtext(main,side=3,las=1,font=2,line=2,cex=1.2) par(mar=c(5.1, 4.1, 4.1, 2.1)) layout(matrix(1,1,1)) } else { par(mar=c(5.1, 4.1, 4.1, 2.1)) hist(data,breaks="FD",col=rgb(0.5,0.7,1),border=rgb(0.3,0.5,1),freq=FALSE,main=main,xlab=xlab,xlim=c(bhfull[1],bhfull[L+1])) for (i in 2:L) abline(v=bhfull[i],lty=1) } }
test_that("msplot works", { multiv_data <- c(-1.00699287, -0.53823436, -0.55879513, -0.18606117, -0.52050693, 0.46096140, -0.32240037, -0.46775918, -0.38068162, 0.02840495, -0.16316400, 0.18996883, -0.25430960, -0.06389951, -0.46119745, -0.30353525, -1.21554894, -1.22182643, -0.63857941, -0.84320227, -0.77277610, -0.88696090, -0.80527829, -0.33013994, -0.25724301, 0.86073945, -0.75379286, -0.81968759, -0.57461555, -1.02516021) multiv_data <- array(multiv_data, dim = c(5, 3, 2)) univ_data <- multiv_data[,,1] ms_multiv <- msplot(dts = multiv_data, n_projections = 7, seed = 20, plot = T, return_mvdir = TRUE) ms_univ <- msplot(dts = univ_data, n_projections = 7, seed = 20, plot = T,return_mvdir = TRUE, show_legend = F, plot_title = "msplot", title_cex = 2.5) expect_equal(ms_univ$mean_outlyingness, c(-3.914187996322071, 0.799832282094095, -0.656101785795584, 3.985668697844344, 0.061413333960102)) expect_equal(ms_multiv$var_outlyingness, c(283.159734194725274, 6.614769686570630, 0.222222222222222, 17.322766085413605, 13.382474792869186)) })
gmm_1 <- list(alpha = c(0.4, 0.6), mu = matrix(c(0, 2, 4, 1, 3, 5), 3, dimnames = list(c("A", "B", "C"), NULL)), sigma = list(matrix(c(1, 1, 1, 1, 2, 2, 1, 2, 3), 3, dimnames = list(c("A", "B", "C"), c("A", "B", "C"))), matrix(c(2, 3, 1, 3, 5, 2, 1, 2, 4), 3, dimnames = list(c("A", "B", "C"), c("A", "B", "C"))))) class(gmm_1) <- "gmm" gmm_2 <- list(alpha = 1, mu = matrix(0, 2, dimnames = list(c("A", "B"), NULL)), sigma = list(matrix(1, 2, 2, dimnames = list(c("A", "B"), c("A", "B"))))) class(gmm_2) <- "gmm" test_that("conditionalize a gmm object", { expect_equal(conditional(gmm_1, "C"), list(alpha = c(0.4, 0.6), mu_x = matrix(c(0, 2, 1, 3), 2, dimnames = list(c("A", "B"), NULL)), sigma_x = list(matrix(c(1, 1, 1, 2), 2, dimnames = list(c("A", "B"), c("A", "B"))), matrix(c(2, 3, 3, 5), 2, dimnames = list(c("A", "B"), c("A", "B")))), coeff = list(matrix(c(2, 0, 1), dimnames = list(c("(Intercept)", "A", "B"), "C")), matrix(c(3, - 1, 1), dimnames = list(c("(Intercept)", "A", "B"), "C"))), sigma_c = list(matrix(1, dimnames = list("C", "C")), matrix(3, dimnames = list("C", "C"))))) }) test_that("conditionalize a gmm object with unordered dependent variables", { expect_equal(conditional(gmm_1, c("C", "B")), list(alpha = c(0.4, 0.6), mu_x = matrix(c(0, 1), 1, dimnames = list("A", NULL)), sigma_x = list(matrix(1, dimnames = list("A", "A")), matrix(2, dimnames = list("A", "A"))), coeff = list(matrix(c(2, 1, 4, 1), 2, dimnames = list(c("(Intercept)", "A"), c("B", "C"))), matrix(c(1.5, 1.5, 4.5, 0.5), 2, dimnames = list(c("(Intercept)", "A"), c("B", "C")))), sigma_c = list(matrix(c(1, 1, 1, 2), 2, dimnames = list(c("B", "C"), c("B", "C"))), matrix(c(0.5, 0.5, 0.5, 3.5), 2, dimnames = list(c("B", "C"), c("B", "C")))))) }) test_that("conditionalize a gmm object with duplicated dependent variables", { expect_equal(conditional(gmm_1, c("C", "C")), list(alpha = c(0.4, 0.6), mu_x = matrix(c(0, 2, 1, 3), 2, dimnames = list(c("A", "B"), NULL)), sigma_x = list(matrix(c(1, 1, 1, 2), 2, dimnames = list(c("A", "B"), c("A", "B"))), matrix(c(2, 3, 3, 5), 2, dimnames = list(c("A", "B"), c("A", "B")))), coeff = list(matrix(c(2, 0, 1), dimnames = list(c("(Intercept)", "A", "B"), "C")), matrix(c(3, - 1, 1), dimnames = list(c("(Intercept)", "A", "B"), "C"))), sigma_c = list(matrix(1, dimnames = list("C", "C")), matrix(3, dimnames = list("C", "C"))))) }) test_that("conditionalize a gmm object with no explanatory variable", { expect_equal(conditional(gmm_1, c("A", "B", "C")), list(alpha = c(0.4, 0.6), mu_x = matrix(numeric(), ncol = 2, dimnames = list(character(), NULL)), sigma_x = list(matrix(numeric(), 0, 0, dimnames = list(character(), character())), matrix(numeric(), 0, 0, dimnames = list(character(), character()))), coeff = list(matrix(c(0, 2, 4), 1, dimnames = list("(Intercept)", c("A", "B", "C"))), matrix(c(1, 3, 5), 1, dimnames = list("(Intercept)", c("A", "B", "C")))), sigma_c = list(matrix(c(1, 1, 1, 1, 2, 2, 1, 2, 3), 3, dimnames = list(c("A", "B", "C"), c("A", "B", "C"))), matrix(c(2, 3, 1, 3, 5, 2, 1, 2, 4), 3, dimnames = list(c("A", "B", "C"), c("A", "B", "C")))))) }) test_that("conditionalize a gmm object with non-positive definite covariance matrices", { expect_equal(conditional(gmm_2, "B"), list(alpha = 1, mu_x = matrix(0, dimnames = list("A", NULL)), sigma_x = list(matrix(1, dimnames = list("A", "A"))), coeff = list(matrix(c(0, 1), dimnames = list(c("(Intercept)", "A"), "B"))), sigma_c = list(matrix(2.225074e-308, dimnames = list("B", "B")))), tolerance = 0.01) })
PivotCalculationGroups <- R6::R6Class("PivotCalculationGroups", public = list( initialize = function(parentPivot) { if(parentPivot$argumentCheckMode > 0) { checkArgument(parentPivot$argumentCheckMode, FALSE, "PivotCalculationGroups", "initialize", parentPivot, missing(parentPivot), allowMissing=FALSE, allowNull=FALSE, allowedClasses="PivotTable") } private$p_parentPivot <- parentPivot if(private$p_parentPivot$traceEnabled==TRUE) private$p_parentPivot$trace("PivotCalculationGroups$new", "Creating new Pivot Calculation Groups...") private$p_groups <- list() if(private$p_parentPivot$traceEnabled==TRUE) private$p_parentPivot$trace("PivotCalculationGroups$new", "Created new Pivot Calculation Groups.") }, isExistingCalculationGroup = function(calculationGroupName=NULL) { if(private$p_parentPivot$argumentCheckMode > 0) { checkArgument(private$p_parentPivot$argumentCheckMode, FALSE, "PivotCalculationGroups", "isExistingCalculationGroup", calculationGroupName, missing(calculationGroupName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_parentPivot$traceEnabled==TRUE) private$p_parentPivot$trace("PivotCalculationGroups$isExistingCalculationGroup", "Checking calculation group exists...", list(calculationGroupName=calculationGroupName)) calcGroupExists <- calculationGroupName %in% names(private$p_groups) if(private$p_parentPivot$traceEnabled==TRUE) private$p_parentPivot$trace("PivotCalculationGroups$isExistingCalculationGroup", "Checked calculation group exists.") return(invisible(calcGroupExists)) }, item = function(index) { if(private$p_parentPivot$argumentCheckMode > 0) { checkArgument(private$p_parentPivot$argumentCheckMode, FALSE, "PivotCalculationGroups", "item", index, missing(index), allowMissing=FALSE, allowNull=FALSE, allowedClasses=c("integer", "numeric")) } if(private$p_parentPivot$traceEnabled==TRUE) private$p_parentPivot$trace("PivotCalculationGroups$item", "Getting calculation group...") if(index<1) { stop(paste0("PivotCalculationGroups$index(): index must be greater than 0."), call. = FALSE) } if(index>length(private$p_groups)) { stop(paste0("PivotCalculationGroups$index(): index must be less than or equal to ", length(private$p_groups), "."), call. = FALSE) } if(private$p_parentPivot$traceEnabled==TRUE) private$p_parentPivot$trace("PivotCalculationGroups$item", "Got calculation group....") return(invisible(private$p_groups[[index]])) }, getCalculationGroup = function(calculationGroupName=NULL) { if(private$p_parentPivot$argumentCheckMode > 0) { checkArgument(private$p_parentPivot$argumentCheckMode, FALSE, "PivotCalculationGroups", "getCalculationGroup", calculationGroupName, missing(calculationGroupName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_parentPivot$traceEnabled==TRUE) private$p_parentPivot$trace("PivotCalculationGroups$getCalculationGroup", "Getting calculation group...", list(calculationGroupName=calculationGroupName)) calculationGroup <- private$p_groups[[calculationGroupName]] if(is.null(calculationGroup)) { stop(paste0("PivotCalculationGroups$getCalculationGroup(): No calculation group exists with the name '", calculationGroupName, "'"), call. = FALSE) } if(private$p_parentPivot$traceEnabled==TRUE) private$p_parentPivot$trace("PivotCalculationGroups$getCalculationGroup", "Got calculation group.") return(invisible(calculationGroup)) }, addCalculationGroup = function(calculationGroupName=NULL) { if(private$p_parentPivot$argumentCheckMode > 0) { checkArgument(private$p_parentPivot$argumentCheckMode, FALSE, "PivotCalculationGroups", "addCalculationGroup", calculationGroupName, missing(calculationGroupName), allowMissing=FALSE, allowNull=FALSE, allowedClasses="character") } if(private$p_parentPivot$traceEnabled==TRUE) private$p_parentPivot$trace("PivotCalculationGroups$addCalculationGroup", "Adding calculation group...", list(calculationGroupName=calculationGroupName)) if(calculationGroupName %in% names(private$p_groups)) { stop(paste0("PivotCalculationGroups$addCalculationGroup(): A calculation group already exists", " in the Pivot Table with the name '", calculationGroupName, "'. calculationGroupName must unique."), call. = FALSE) } calculationGroup <- PivotCalculationGroup$new(private$p_parentPivot, calculationGroupName) private$p_groups[[calculationGroupName]] <- calculationGroup if(is.null(private$p_defaultGroup)) private$p_defaultGroup <- calculationGroup if(private$p_parentPivot$traceEnabled==TRUE) private$p_parentPivot$trace("PivotCalculationGroups$addCalculationGroup", "Added calculation group.") return(invisible(calculationGroup)) }, asList = function() { lst <- list() if(length(private$p_groups) > 0) { groupNames <- names(private$p_groups) for (i in 1:length(private$p_groups)) { groupName <- groupNames[i] lst[[groupName]] = private$p_groups[[groupName]]$asList() } } return(invisible(lst)) }, asJSON = function() { if (!requireNamespace("jsonlite", quietly = TRUE)) { stop("The jsonlite package is needed to convert to JSON. Please install the jsonlite package.", call. = FALSE) } jsonliteversion <- utils::packageDescription("jsonlite")$Version if(numeric_version(jsonliteversion) < numeric_version("1.1")) { stop("Version 1.1 or above of the jsonlite package is needed to convert to JSON. Please install an updated version of the jsonlite package.", call. = FALSE) } return(jsonlite::toJSON(self$asList())) }, asString = function(seperator=", ") { if(private$p_parentPivot$argumentCheckMode > 0) { checkArgument(private$p_parentPivot$argumentCheckMode, FALSE, "PivotCalculationGroups", "asString", seperator, missing(seperator), allowMissing=TRUE, allowNull=FALSE, allowedClasses="character") } cstr <- "" if(length(private$p_groups)>0) { for(i in 1:length(private$p_groups)) { cg <- private$p_groups[[i]] sep <- "" if(i > 1) { sep <- seperator } cstr <- paste0(cstr, sep, cg$asString()) } } return(cstr) } ), active = list( count = function(value) { return(invisible(length(private$p_groups))) }, groups = function(value) { return(invisible(private$p_groups)) }, defaultGroup = function(value) { return(invisible(private$p_defaultGroup)) } ), private = list( p_parentPivot = NULL, p_groups = NULL, p_defaultGroup = NULL ) )
Tkp <- function(TranMat,k,p){ k <- as.numeric(k) if (class(p)=="initProbObject"){ p <- as.vector(p$init_prob) } else { p <- as.vector(p) } if(spam::is.spam(T)){ TkpOut <- p for (i in 1:k){ TkpOut <- TranMat%*%TkpOut } } else { TranMat <- as.matrix(TranMat) TkpOut <- p for (i in 1:k){ TkpOut <- TranMat%*%TkpOut } } return(TkpOut) }
search_quotes <- function(search, fuzzy=FALSE, fields = c("topic", "subtopic", "text", "source"), ...) { data <- .get.sq() if(missing(search)) stop("No search parameters entered.", call.=FALSE) merged <- data.frame(data[,fields], check.names = FALSE) cols <- colnames(merged) if (length(cols) > 1) merged <- do.call(paste, merged[,cols]) if(fuzzy) OK <- agrep(tolower(search), tolower(merged), ...) else OK <- which(str_detect(merged, search)) if (length(OK)) data <- data[OK,] else stop("The search parameters \'", search, "\' did not match any items.") class(data) <- c("statquote", 'data.frame') return(data) }
parallelML <- function(MLCall, MLPackage, samplingSize = 0.2, numberCores = detectCores(), underSample = FALSE, underSampleTarget = NULL, sampleMethod = "bagging") UseMethod("parallelML") parallelML.default <- function(MLCall, MLPackage, samplingSize = 0.2, numberCores = detectCores(), underSample = FALSE, underSampleTarget = NULL, sampleMethod = "bagging"){ arguments <- getArgs(MLCall) toPredict <- as.character(arguments$formula[2]) if ("" %in% names(arguments)){ stop("One of the items in your function call was not named: every item must be like formula = yourFormula") } else if (!("data" %in% names(arguments))){ stop("You did not provide an argument data in MLCall") } else if (!("formula" %in% names(arguments))){ stop("You did not provide an argument formula in MLCall") } else { registerCores(numberCores) fcall <- getCall(MLCall) data <- fcall$data fcall$formula <- eval(fcall$formula) call <- gsub(' ','',deparse(fcall)) call <- gsub('M.formula','M',call) trainSamples <- trainSample(eval(data),numberCores,samplingSize, underSample, toPredict, underSampleTarget,sampleMethod) function_call <- list() for (i in 1:numberCores){ function_call[[i]] <- fcall function_call[[i]]$data <- trainSamples[[i]] } parallelModel <- foreach(i = 1:numberCores) %dopar% { library(MLPackage,character.only=TRUE) eval(function_call[[i]], parent.frame()) } class(parallelModel) <- "parallelML" attr(parallelModel,"call") <- call attr(parallelModel,"samp") <- samplingSize return(parallelModel) } }
context("Nod") library(polite)
context("clust.SimpleKMeans") skip_if_not_installed("RWeka") skip_on_cran() test_that("autotest", { learner = mlr3::lrn("clust.SimpleKMeans") expect_learner(learner) result = run_autotest(learner) expect_true(result, info = result$error) }) test_that("Learner properties are respected", { task = tsk("usarrests") learner = mlr_learners$get("clust.SimpleKMeans") expect_learner(learner, task) parset_list = list( list(N = 3, init = 2L, periodic_pruning = 1L), list(V = TRUE, M = TRUE, O = TRUE), list(num_slots = 2L, init = 2L, min_density = 1L) ) for (i in seq_along(parset_list)) { parset = parset_list[[i]] learner$param_set$values = parset p = learner$train(task)$predict(task) expect_prediction_clust(p) if ("complete" %in% learner$properties) { expect_prediction_complete(p, learner$predict_type) } if ("exclusive" %in% learner$properties) { expect_prediction_exclusive(p, learner$predict_type) } } })
elasticity <- function(beta, binwidth, zstar, t0, t1, notch = FALSE, e_parametric = FALSE, e_parametric_lb = 1e-04, e_parametric_ub = 3) { Dz <- beta*binwidth Dz_over_zstar <- Dz/zstar dt <- t1 - t0 if(notch == FALSE) { if(e_parametric) { e <- -log(1+Dz_over_zstar)/log(1-(dt/(1-t0))) } else { e <- Dz_over_zstar/(dt/(1-t0)) } } else { e <- (1/(2+Dz_over_zstar))*(Dz_over_zstar**2)/(dt/(1-t0)) if(e_parametric) { f = file() sink(file = f) estimate <- tryCatch({ suppressWarnings(BB::BBoptim(0.01, notch_equation, t0 = t0, t1 = t1, zstar = zstar, dzstar = Dz, lower = e_parametric_lb, upper = e_parametric_ub)) }, error=function(error_message) { return(error_message) }) sink() close(f) warning_message <- "The elasticity estimate based on the parametric version for notches has no solution, returning the reduced-form estimate." if(!"convergence" %in% names(estimate)) { warning(warning_message) } else { if(estimate$convergence != 0) { warning(warning_message) } else { e <- estimate$par if(abs(e-e_parametric_ub) < 1e-05) { warning("The elasticity estimate based on the parametric version for notches hit the upper bound of possible solution values. \n Interpet with caution! \n Consider setting e_parametric = FALSE, or increase e_parametric_ub.") } if(abs(e-e_parametric_lb) < 1e-05) { warning("The elasticity estimate based on the parametric version for notches hit the lower bound of possible solution values. \n Interpet with caution! \n Consider setting e_parametric = FALSE, or decrease e_parametric_lb.") } } } } } return(e) }
summary.Fract.Poly <- function(object, ..., Object){ if (missing(Object)){Object <- object} x <- Object if (is.null(Object$Results.M1)==FALSE){ cat("Best fitting model for m=1: \n") print(Object$Results.M1[order(Object$Results.M1[,2]),][1:1,]) } if (is.null(Object$Results.M2)==FALSE){ cat("\nBest fitting model for m=2: \n") print(Object$Results.M2[order(Object$Results.M2[,3]),][1:1,]) } if (is.null(Object$Results.M3)==FALSE){ cat("\nBest fitting model for m=3: \n") print(Object$Results.M3[order(Object$Results.M3[,4]),][1:1,]) } if (is.null(Object$Results.M4)==FALSE){ cat("\nBest fitting model for m=4: \n") print(Object$Results.M4[order(Object$Results.M4[,5]),][1:1,]) } if (is.null(Object$Results.M5)==FALSE){ cat("\nBest fitting model for m=5: \n") print(Object$Results.M5[order(Object$Results.M5[,6]),][1:1,]) } }
omegasCFA <- function( data, n.factors, model = "balanced", model.type = "higher-order", interval = .95, missing = "pairwise", fit.measures = FALSE) { listwise <- FALSE pairwise <- FALSE complete_cases <- nrow(data) if (any(is.na(data))) { if (missing == "listwise") { pos <- which(is.na(data), arr.ind = TRUE)[, 1] data <- data[-pos, ] ncomp <- nrow(data) complete_cases <- ncomp listwise <- TRUE } else { pairwise <- TRUE } } data <- scale(data, scale = FALSE) sum_res <- omegasCFAMultiOut(data, n.factors, interval, pairwise, model, model.type, fit.measures) sum_res$complete_cases <- complete_cases sum_res$call <- match.call() sum_res$k <- ncol(data) sum_res$n.factors <- n.factors sum_res$pairwise <- pairwise sum_res$listwise <- listwise sum_res$interval <- interval class(sum_res) <- "omegasCFA" return(sum_res) }
compare_graphs <- function(graph1, graph2, titles = NULL, position = c("vertical", "horizontal"), n_nodes = 5, n_weights = 5, edge_width_range = c(0.2,2), edge_alpha_range = c(0.4, 1), node_size_range = c(1,10), unique_legend = TRUE) { if (is.null(graph1$igraph) || is.null(graph1$net) || is.null(graph1$deg) || is.null(graph2$igraph) || is.null(graph2$net) || is.null(graph2$deg)) { stop("Can only compare graphs generated by foodingraph") } position <- match.arg(position) graph1_degrees <- degree(graph1$igraph) graph2_degrees <- degree(graph2$igraph) range_degrees1 <- c(min(graph1_degrees), max(graph1_degrees)) range_degrees2 <- c(min(graph2_degrees), max(graph2_degrees)) range_degrees <- c(min(range_degrees1, range_degrees2), max(range_degrees1, range_degrees2)) breaks_degrees <- extended(range_degrees[1], range_degrees[2], n_nodes) breaks_degrees <- unique(round(breaks_degrees)) graph1_edges <- E(graph1$igraph) graph2_edges <- E(graph2$igraph) range_weights1 <- c(min(graph1_edges$weight), max(graph1_edges$weight)) range_weights2 <- c(min(graph2_edges$weight), max(graph2_edges$weight)) range_weights <- c(min(range_weights1, range_weights2), max(range_weights1, range_weights2)) breaks_weights <- extended(range_weights[1], range_weights[2], n_weights) graph1$net <- suppressMessages( graph1$net + scale_edge_alpha_continuous(name = "Edge weight", range = edge_alpha_range, breaks = breaks_weights, limits = range_weights) + scale_edge_width_continuous(name = "Edge weight", range = edge_width_range, breaks = breaks_weights, limits = range_weights) + scale_size_continuous(name = "Node degrees", range = node_size_range, breaks = breaks_degrees, limits = range_degrees) ) graph2$net <- suppressMessages( graph2$net + scale_edge_alpha_continuous(name = "Edge weight", range = edge_alpha_range, breaks = breaks_weights, limits = range_weights) + scale_edge_width_continuous(name = "Edge weight", range = edge_width_range, breaks = breaks_weights, limits = range_weights) + scale_size_continuous(name = "Node degrees", range = node_size_range, breaks = breaks_degrees, limits = range_degrees) ) if (unique_legend == TRUE && position == "vertical") { final_graph <- plot_grid( graph1$net + theme(legend.position = "none"), graph2$net + theme(legend.position = "none"), NULL, ncol = 1, axis = "lr", rel_heights = c(1, 1, 0.3), labels = c(titles[1], "", titles[2]) ) legend_plot <- get_legend( graph1$net + theme( legend.position = "bottom", legend.direction = "vertical" ) + guides(fill = guide_legend( nrow = 5, order = 1, override.aes = list(size = 5)) ) ) final_graph <- final_graph + draw_grob(legend_plot, 0, 0, 1, .3/2.3) } else if (unique_legend == TRUE && position == "horizontal") { final_graph <- plot_grid( graph1$net + theme(legend.position = "none"), NULL, graph2$net + theme(legend.position = "none"), ncol = 3, nrow = 1, axis = "tb", rel_widths = c(1, 0.3, 1), labels = c(titles[1], "", titles[2]) ) legend_plot <- get_legend(graph1$net) final_graph <- final_graph + draw_grob(legend_plot, 1/2.3, 0, .3/2.3, 1) } else { final_graph <- plot_grid( graph1$net, graph2$net, labels = titles, ncol = ifelse(position == "vertical", 1, 2), nrow = ifelse(position == "vertical", 2, 1), align = ifelse(position == "vertical", "v", "h"), axis = "bl" ) } class_pos <- ifelse(position == "vertical", "foodingraph_vertical", "foodingraph_horizontal") class(final_graph) <- c(class(final_graph), class_pos) final_graph }
cat("\nReactive submit, reset and missed colorAsFactor") driver %>% getEl(' submitBtn <- wait_for(" test_that('treatColorAsFactor hides correct', expect_true(is.null(driver %>% getEl(' caratColorOpt <- driver %>% getSelectOptions('color') %>% Filter(function(x) text(x) == 'carat', .) if (length(caratColorOpt) != 1) stop_externals('Impossible') else caratColorOpt[[1]] %>% click() test_that('treatColorAsFactor appears correct', expect_true(!is.null(wait_for(' driver %>% getEl(' driver %>% getEl(' test_that('Unreactive submit works correct', expect_true(driver %>% has_shiny_correct_state( pastePlus('^unreactive', 'colorFactors', shorten=F), NULL, NULL, shortShotName=F))) driver %>% getEl(' test_that('Submit button grays correct', { expect_true(!is.null(wait_for(' driver %>% getEl(' expect_true(!is.null(wait_for(' }) driver %>% getEl(' test_that('Reset works correct', { expect_true(wait_for({ text(driver %>% getEl(' catchStale=T, timeout = 20)) expect_true(wait_for({ is.null(driver %>% getEl(' expect_true(!is.null(wait_for(' expect_true(has_shiny_correct_state(driver, '^reset', NULL, NULL, shortShotName=F)) })
context("lama_translate_all") dict = new_lama_dictionary( a = c(a = "A", b = "B", c = "X", d = "D", e = "X", f = "F"), x = c(x = "X", y = NA, "NA_" = NA, z = "Z"), u = c(u = NA, v = "V", w = NA, "NA_" = "NAnew"), xx = c(x = "X", y = NA, "NA_" = NA, z = "Z") ) df <- data.frame( a = factor( c("c", "d", "d", "a", "a", "f", NA, "e"), levels = c("f", "e", "X1", "d", "c", "a", "X2") ), a_labeled = c("X", "D", "D", "A", "A", "F", NA, "X"), x = factor( c("y", "y", NA, "x", "x", "y", "y", "x"), levels = c("X1", "y", "X2", "x", "X3") ), x_labeled = c(NA, NA, NA, "X", "X", NA, NA, "X"), u = c("u", "v", NA, "v", "u", "v", "u", "v"), u_labeled = c(NA, "V", "NAnew", "V", NA, "V", NA, "V"), stringsAsFactors = FALSE ) test_that("'lama_translate_all' works", { df_new <- lama_translate_all( df, dict, prefix = "new_", suffix = "_new", fn_colname = toupper, keep_order = TRUE ) expect_s3_class(df_new, "data.frame") expect_column_names( df_new, c( "a", "a_labeled", "x", "x_labeled", "u", "u_labeled", "new_A_new", "new_X_new", "new_U_new" ) ) expect_factor_levels(df_new$new_A_new, c("F", "X", "D", "A", "B")) expect_factor_levels(df_new$new_X_new, c("X", "Z")) expect_factor_levels(df_new$new_U_new, c("V", "NAnew")) expect_identical(as.character(df_new$new_A_new), df_new$a_labeled) expect_identical(as.character(df_new$new_X_new), df_new$x_labeled) expect_identical(as.character(df_new$new_U_new), df_new$u_labeled) }) test_that("'lama_translate_all' throws the right errors", { expect_error( lama_translate_all(df, df), paste( "The argument 'dictionary' must be a lama_dictionary class object." ) ) expect_error( lama_translate_all(df, dict, prefix = NA_character_), paste( "The argument 'prefix' must be a character string." ) ) expect_error( lama_translate_all(df, dict, prefix = c("x", "y")), paste( "The argument 'prefix' must be a character string." ) ) expect_error( lama_translate_all(df, dict, prefix = "_"), paste( "The argument 'prefix' must be a valid object name prefix." ) ) expect_error( lama_translate_all(df, dict, suffix = NA_character_), paste( "The argument 'suffix' must be a character string." ) ) expect_error( lama_translate_all(df, dict, suffix = c("x", "y")), paste( "The argument 'suffix' must be a character string." ) ) expect_error( lama_translate_all(df, dict, suffix = " "), paste( "The argument 'suffix' must be a valid object name suffix." ) ) expect_error( lama_translate_all(df, dict, keep_order = NA), paste( "The argument 'keep_order' must be a logical." ) ) expect_error( lama_translate_all(df, dict, fn_colname = 3), paste( "The argument 'fn_colname' must be a function taking a character string and", "returning a character string." ) ) expect_error( lama_translate_all(df, dict, fn_colname = function(x) 4), paste( "The function given in argument 'fn_colname' does not produce valid", "column names: It must take character strings and return character", "strings." ) ) expect_error( lama_translate_all(df, dict, fn_colname = function(x) ifelse(x == "x", NA, toupper(x))), paste( "The function given in argument 'fn_colname' does not produce valid", "column names: It must take character strings and return character", "strings." ) ) expect_error( lama_translate_all(df, dict, fn_colname = function(x) sprintf("%s ", x)), paste( "The function given in argument 'fn_colname' does not produce valid", "column names: The following produced column names are", "invalid: 'a ', 'x ', 'u '." ) ) })
ti_error <- dynwrap::create_ti_method_r( dynwrap::definition( method = dynwrap::def_method(id = "error"), wrapper = dynwrap::def_wrapper(input_required = "counts") ), run_fun = function( counts, seed = NA, verbose = FALSE ) { stop("This control method always errors.") } )
MC_OMNI_logistic <- function(num_sims, cor_mat, obs_omni, null_model, factor_matrix) { fitted_values <- null_model$fitted.values skat_dmat <- model.matrix(null_model) num_sub <- length(fitted_values) results <- rep(NA, num_sims) for (i in 1:num_sims) { sim_Y <- rbinom(n=num_sub, size=1, prob=fitted_values) skat_obj <- SKAT_Null_Model(sim_Y ~ skat_dmat - 1, out_type='D', Adjustment=FALSE) boot_null_mod <- glm(sim_Y ~ skat_dmat - 1, family=binomial()) new_Z <- score_stats_only(null_model=boot_null_mod, factor_matrix=factor_matrix, link_function='logit') GBJ_p <- GBJ(test_stats=new_Z, cor_mat=cor_mat)$GBJ_pvalue GHC_p <- GHC(test_stats=new_Z, cor_mat=cor_mat)$GHC_pvalue minP_p <- minP(test_stats=new_Z, cor_mat=cor_mat)$minP_pvalue skat_p <- SKAT(Z=factor_matrix, obj=skat_obj)$p.value results[i] <- min(GBJ_p, GHC_p, minP_p, skat_p) if (i%%100 == 0) {cat(i, ' done\n')} } return( length(which(results <= obs_omni))/num_sims ) } MC_OMNI_linear <- function(num_sims, null_model, cor_mat, factor_matrix, obs_omni) { fitted_values <- null_model$fitted.values skat_dmat <- model.matrix(null_model) num_sub <- length(fitted_values) results <- rep(NA, num_sims) for (i in 1:num_sims) { sim_Y <- rnorm(n=num_sub, mean=fitted_values) skat_obj <- SKAT_Null_Model(sim_Y ~ skat_dmat - 1, out_type='C', Adjustment=FALSE) boot_null_mod <- glm(sim_Y ~ skat_dmat - 1) new_Z <- score_stats_only(null_model=boot_null_mod, factor_matrix=factor_matrix, link_function='linear') GBJ_p <- GBJ(test_stats=new_Z, cor_mat=cor_mat)$GBJ_pvalue GHC_p <- GHC(test_stats=new_Z, cor_mat=cor_mat)$GHC_pvalue minP_p <- minP(test_stats=new_Z, cor_mat=cor_mat)$minP_pvalue skat_p <- SKAT(Z=factor_matrix, obj=skat_obj)$p.value results[i] <- min(GBJ_p, GHC_p, minP_p, skat_p) if (i%%100 == 0) {cat(i, ' done\n')} } return( length(which(results <= obs_omni))/num_sims ) } MC_OMNI_ss <- function(num_sims, cor_mat, obs_omni) { diag(cor_mat) <- 1 results <- rep(NA, num_sims) for (i in 1:num_sims) { new_Z <- mvtnorm::rmvnorm(n=1, sigma=cor_mat) GBJ_p <- GBJ(test_stats=new_Z, cor_mat=cor_mat)$GBJ_pvalue GHC_p <- GHC(test_stats=new_Z, cor_mat=cor_mat)$GHC_pvalue minP_p <- minP(test_stats=new_Z, cor_mat=cor_mat)$minP_pvalue results[i] <- min(GBJ_p, GHC_p, minP_p) if (i%%100 == 0) {cat(i, ' done\n')} } return( length(which(results <= obs_omni))/num_sims ) } test_that("OMNI p-value correct for logistic regression case", { skip_on_cran() set.seed(1) G_cor <- matrix(data=0.3, nrow=5, ncol=5) diag(G_cor) <- 1 num_sub <- 1000 G_mat <- bindata::rmvbin(n=num_sub, margprob=rep(0.3, 5), bincorr=G_cor) X1 <- rnorm(num_sub) X2 <- rnorm(num_sub) mu <- rje::expit(-1 + 0.1 * X1 + 0.2 * X2) outcome <- rbinom(n=num_sub, size=1, prob=mu) null_mod <- glm(outcome ~ X1 + X2, family=binomial()) score_stats_output <- calc_score_stats(null_model=null_mod, factor_matrix=G_mat, link_function='logit') test_stats <- score_stats_output$test_stats cor_mat <- score_stats_output$cor_mat omni_output <- OMNI_individual(null_model=null_mod, factor_matrix=G_mat, link_function='logit', num_boots=40) obs_omni <- omni_output$OMNI analytic_p <- omni_output$OMNI_pvalue sim_p <- MC_OMNI_logistic(num_sims=100, cor_mat=cor_mat, obs_omni=obs_omni, null_model=null_mod, factor_matrix=G_mat) expect_equal(analytic_p, sim_p, tolerance = 0.02) }) test_that("OMNI p-value correct for linear regression case", { skip_on_cran() set.seed(10) G_cor <- matrix(data=0.3, nrow=5, ncol=5) diag(G_cor) <- 1 num_sub <- 550 cprob <- bincorr2commonprob(margprob=rep(0.3, 5), bincorr=G_cor) sigma_struct <- commonprob2sigma(commonprob=cprob) G_mat <- bindata::rmvbin(n=num_sub, margprob=rep(0.3, 5), sigma=sigma_struct) X1 <- rnorm(num_sub) X2 <- rnorm(num_sub) mu <- 0.1 * X1 + 0.2 * X2 outcome <- rnorm(n=num_sub, mean=mu) null_mod <- glm(outcome ~ X1 + X2) omni_output <- OMNI_individual(null_model=null_mod, factor_matrix=G_mat, link_function='linear', num_boots=100) obs_omni <- omni_output$OMNI analytic_p <- omni_output$OMNI_pvalue sim_p <- MC_OMNI_linear(num_sims=500, null_model=null_mod, cor_mat=cor_mat, factor_matrix=G_mat, obs_omni=obs_omni) expect_equal(analytic_p, sim_p, tolerance = 0.02) }) test_that("OMNI p-value correct for summary statistics case", { skip_on_cran() set.seed(0) cor_mat <- matrix(data=0.3, nrow=5, ncol=5) diag(cor_mat) <- 1 test_stats <- as.numeric(rmvnorm(n=1, sigma=cor_mat)) omni_output <- OMNI_ss(test_stats=test_stats, cor_mat=cor_mat, num_boots=100) obs_omni <- omni_output$OMNI analytic_p <- omni_output$OMNI_pvalue sim_p <- MC_OMNI_ss(num_sims=1000, cor_mat=cor_mat, obs_omni=obs_omni) expect_equal(analytic_p, sim_p, tolerance = 0.05) })
thr_image <- function (dn, intercept, slope) { stopifnot(length(intercept) == 1) stopifnot(class(intercept) == "numeric") stopifnot(length(slope) == 1) stopifnot(class(slope) == "numeric") dn <- dn * 255 if (.get_max(dn) > 255) warning("\"dn\" values should be normalized") dn[dn > 255] <- 255 thr <- intercept + slope * dn thr[thr < 0] <- 0 thr / 255 }
print.ContObservHMM <- function(x, ...) { cat("\nThe number of Baum-Welch iterations: ") cat((nrow(x$Parameters))-1) cat("\nThe parameters accumulated so far: \n") par<-round(x$Parameters, 2) print(par) cat("\nThe results accumulated so far: \n") res1<-(x$Results[-(nrow(x$Parameters)),3]) res2<-(x$Results[-(nrow(x$Parameters)),4]) res3<-(x$Results[-(nrow(x$Parameters)),5]) res<-cbind(res1, res2, res3) colnames(res)<-c("P", "AIC", "SBIC") print(res) yesno<-ifelse(((x$Viterbi[1,1]) == 0), "not yet ", "already ") cat("\nThe Viterbi algorithm was ") cat(yesno) cat("executed\n\n") }
descr <- function(X, Ndistinct = TRUE, higher = TRUE, table = TRUE, Qprobs = c(0.01, 0.05, 0.25, 0.5, 0.75, 0.95, 0.99), cols = NULL, label.attr = 'label', ...) { nam <- l1orlst(as.character(substitute(X))) armat <- function(x, y) c(x[1L], Ndist = y, x[-1L]) natrm <- function(x) if(is.na(names(x)[length(x)])) x[-length(x)] else x dotsok <- if(!missing(...)) names(substitute(c(...))[-1L]) %!in% c('pid','g') else TRUE numstats <- if(Ndistinct && dotsok) function(x, ...) armat(qsu.default(x, higher = higher, ...), fndistinctCpp(x)) else function(x, ...) qsu.default(x, higher = higher, ...) descrnum <- if(is.numeric(Qprobs)) function(x, ...) list(Class = class(x), Label = attr(x, label.attr), Stats = numstats(x, ...), Quant = quantile(na_rm(x), probs = Qprobs)) else function(x, ...) list(Class = class(x), Label = attr(x, label.attr), Stats = numstats(x, ...)) descrcat <- function(x, tab = table) if(tab) list(Class = class(x), Label = attr(x, label.attr), Stats = if(Ndistinct) c(N = fnobsC(x), Ndist = fndistinctCpp(x)) else `names<-`(fnobsC(x), 'Nobs'), Table = natrm(fnobs.default(x, x))) else list(Class = class(x), Label = attr(x, label.attr), Stats = if(Ndistinct) c(N = fnobsC(x), Ndist = fndistinctCpp(x)) else `names<-`(fnobsC(x), 'Nobs')) descrdate <- function(x) list(Class = class(x), Label = attr(x, label.attr), Stats = c(if(Ndistinct) c(N = fnobsC(x), Ndist = fndistinctCpp(x)) else `names<-`(fnobsC(x), 'Nobs'), `names<-`(range(x, na.rm = TRUE), c("Min", "Max")))) if(is.list(X)) { is_sf <- inherits(X, "sf") class(X) <- NULL if(is_sf) X[[attr(X, "sf_column")]] <- NULL } else X <- unclass(qDF(X)) if(length(cols)) X <- X[cols2int(cols, X, names(X), FALSE)] res <- vector('list', length(X)) num <- .Call(C_vtypes, X, 1L) res[num] <- lapply(X[num], descrnum, ...) if(!all(num)) { date <- vapply(unattrib(X), is_date, TRUE) if(any(date)) { res[date] <- lapply(X[date], descrdate) cat <- !(num | date) } else cat <- !num res[cat] <- lapply(X[cat], descrcat) } attributes(res) <- list(names = names(X), name = nam, N = length(X[[1L]]), arstat = !dotsok, table = table, class = "descr") res } print.descr <- function(x, n = 7, perc = TRUE, digits = 2, t.table = TRUE, summary = TRUE, ...) { w <- paste(rep("-", .Options$width), collapse = "") nam <- names(x) arstat <- attr(x, "arstat") cb <- function(...) if(t.table) cbind(...) else formatC(rbind(...), drop0trailing = TRUE) ct <- function(z) if(t.table) cbind(Freq = z) else z cat('Dataset: ', attr(x,"name"),', ',length(x), ' Variables, N = ', attr(x, "N"), "\n", sep = "") cat(w, "\n", sep = "") for(i in seq_along(x)) { xi <- x[[i]] namxi <- names(xi) cat(nam[i]," (",strclp(xi[[1L]]),"): ",xi[[2L]], "\n", sep = "") cat(namxi[3L], ": \n", sep = "") print.qsu(xi[[3L]], digits) if(length(xi) > 3L) { if(arstat) cat("\n") cat(namxi[4L], ": \n", sep = "") if(namxi[4L] == "Table") { t <- unclass(xi[[4L]]) if(length(t) <= 2*n) { if(perc) print.default(cb(Freq = t, Perc = round(t/bsum(t)*100, digits)), right = TRUE, print.gap = 2, quote = FALSE) else print.table(ct(t)) } else { lt <- length(t) t1 <- t[seq_len(n)] t2 <- t[seq(lt-n, lt)] if(perc) { st <- bsum(t) print.default(cb(Freq = t1, Perc = round(t1/st*100, digits)), right = TRUE, print.gap = 2, quote = FALSE) cat(" ---\n") print.default(cb(Freq = t2, Perc = round(t2/st*100, digits)), right = TRUE, print.gap = 2, quote = FALSE) } else { print.table(ct(t1)) cat(" ---\n") print.table(ct(t2)) } if(summary) { cat("\nSummary of Table: \n") print.summaryDefault(summary.default(t), digits) } } } else print.qsu(xi[[4L]], digits) } cat(w, "\n", sep = "") } invisible(x) } as.data.frame.descr <- function(x, ...) { if(attr(x, "arstat")) stop("Cannot handle arrays of statistics!") if(attr(x, "table")) { r <- lapply(x, function(z) c(list(Class = strclp(z[[1L]]), Label = null2NA(z[[2L]])), unlist(`names<-`(lapply(z[names(z) != "Table"][-(1:2)], as.vector, "list"), NULL), recursive = FALSE))) } else { r <- lapply(x, function(z) c(list(Class = strclp(z[[1L]]), Label = null2NA(z[[2L]])), unlist(`names<-`(lapply(z[-(1:2)], as.vector, "list"), NULL), recursive = FALSE))) } r <- .Call(C_rbindlist, r, TRUE, TRUE, "Variable") if(allNA(r[["Label"]])) r[["Label"]] <- NULL attr(r, "row.names") <- .set_row_names(length(r[[1L]])) class(r) <- "data.frame" r }
library(testthat) library(XML) library(rgeos) process_testxml = function(xmlfile, n, total, descSkip) { funcTranslate=list( "getboundary" = list(func=gBoundary,res=readWKT,arg1=readWKT), "getCentroid" = list(func=gCentroid,res=readWKT,arg1=readWKT), "convexhull" = list(func=gConvexHull,res=readWKT,arg1=readWKT), "getInteriorPoint" = list(func=gPointOnSurface,res=readWKT,arg1=readWKT), "isSimple" = list(func=gIsSimple,res=as.logical,arg1=readWKT), "isValid" = list(func=gIsValid,res=as.logical,arg1=readWKT), "isWithinDistance" = list(func=gWithinDistance,res=as.logical,arg1=readWKT,arg2=readWKT,arg3=as.numeric), "intersects" = list(func=gIntersects,res=as.logical,arg1=readWKT,arg2=readWKT), "contains" = list(func=gContains,res=as.logical,arg1=readWKT,arg2=readWKT), "within" = list(func=gWithin,res=as.logical,arg1=readWKT,arg2=readWKT), "intersection" = list(func=gIntersection,res=readWKT,arg1=readWKT,arg2=readWKT), "union" = list(func=gUnion,res=readWKT,arg1=readWKT,arg2=readWKT), "difference" = list(func=gDifference,res=readWKT,arg1=readWKT,arg2=readWKT), "symdifference" = list(func=gSymdifference,res=readWKT,arg1=readWKT,arg2=readWKT), "relate" = list(func=gRelate,res=as.logical,arg1=readWKT,arg2=readWKT,arg3=as.character), "covers" = list(func=gCovers,res=as.logical,arg1=readWKT,arg2=readWKT), "coveredBy" = list(func=gCoveredBy,res=as.logical,arg1=readWKT,arg2=readWKT)) context(paste('(',n,'/',total,')',basename(xmlfile))) x = xmlRoot(xmlTreeParse(readLines(xmlfile),ignoreBlanks=TRUE)) nodes = xmlSApply(x,xmlName) test_that("valid node types",{ validNodeTypes = c("precisionModel","case","comment") expect_that( all(nodes %in% validNodeTypes), is_true() ) }) pmAttrs = xmlAttrs( x[[ which(nodes == "precisionModel")[1] ]] ) test_that("precisionModel attribute tests", { expect_that( length(pmAttrs) == 1 | length(pmAttrs) == 3, is_true() ) if (length(pmAttrs) == 1) { type = pmAttrs[["type"]] } else if (length(pmAttrs) == 3) { setScale(as.numeric( pmAttrs[["scale"]] )) expect_that( pmAttrs[["offsetx"]], equals("0.0") ) expect_that( pmAttrs[["offsety"]], equals("0.0") ) } }) for ( i in which(nodes == "case") ) { caseNodes = xmlSApply(x[[i]],xmlName) whichDesc = which(caseNodes == "desc") whichTests = which(caseNodes == "test") desc = xmlValue( x[[i]][[ whichDesc[1] ]] ) if (desc %in% descSkip) next whichArgs = which(caseNodes != "desc" & caseNodes != "test") args = rep( NA,length(whichArgs) ) for ( j in whichArgs) { if (is.null( xmlAttrs(x[[i]][[j]]) )) { args[[ xmlName(x[[i]][[j]]) ]] = xmlValue(x[[i]][[j]]) } else { file = xmlAttrs(x[[i]][[j]])[["file"]] args[[ xmlName(x[[i]][[j]]) ]] = paste( readLines(file), collapse="" ) } } names(args) = tolower(names(args)) for ( j in whichTests ) { test_that(paste(desc,'- test nodes in proper format') , { expect_that( xmlSize( x[[i]][[j]] ), equals(1) ) expect_that( xmlName( x[[i]][[j]][[1]] ), equals("op") ) }) if ( xmlSize( x[[i]][[j]] ) == 1 & xmlName( x[[i]][[j]][[1]] ) == "op" ) { opAttrs = xmlAttrs( x[[i]][[j]][[1]] ) opReturn = xmlValue( x[[i]][[j]][[1]] ) opNArgs = length(opAttrs)-1 if ( 'pattern' %in% names(opAttrs) ) opNArgs = opNArgs-1 opName = opAttrs[['name']] test_that(paste(desc,'-',opName), { funcdetails = funcTranslate[[opName]] expect_that( is.null(funcdetails), is_false() ) if ( !is.null(funcdetails) ) { funcNArgs = length( funcdetails )-2 expect_that(funcNArgs==opNArgs, is_true()) funcArgs = list() for (k in 1:funcNArgs) { argName = paste("arg",k,sep='') argVal = tolower(opAttrs[[argName]]) if (argVal %in% names(args)) argVal = args[[ argVal ]] funcArgs[k] = funcdetails[[argName]](argVal) } funcReturn = do.call(funcdetails[["func"]], funcArgs) expectedReturn = funcdetails[["res"]](opReturn) if (is.logical(funcReturn)) { expect_that(funcReturn == expectedReturn, is_true()) } else if (is.null(funcReturn)) { expect_that(is.null(funcReturn) & is.null(expectedReturn), is_true()) } else if (gIsEmpty(expectedReturn)) { expect_that(identical(funcReturn,expectedReturn), is_true()) } else { expect_that(gEquals(funcReturn,expectedReturn),is_true()) } } }) } } } }
GRAY1 <- " GRAY2 <- " GRAY3 <- " GRAY4 <- " GRAY5 <- " GRAY6 <- " GRAY7 <- " GRAY8 <- " GRAY9 <- " BLUE1 <- " BLUE2 <- " BLUE3 <- " BLUE4 <- " BLUE5 <- " BLUE6 <- " RED1 <- " RED2 <- " RED3 <- " GREEN1 <- " GREEN2 <- " GREEN3 <- " GREEN4 <- " GREEN5 <- " ORANGE1 <- " ORANGE2 <- " theme_swd <- function() { theme_minimal(base_size = 8, base_family = "Helvetica") + theme( panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_line(size = .1, color = GRAY9), axis.text = element_text(color = GRAY7), axis.ticks.x = element_line(size = 0.5, color = GRAY9), axis.ticks.y = element_line(size = 0.5, color = GRAY9), axis.title = element_text(color = GRAY3), axis.title.y = element_text(hjust = 1, margin = margin(0, 6, 0, 15, "pt")), axis.title.x = element_text(hjust = 0, margin = margin(6, 0, 15, 0, "pt")), plot.subtitle = element_text(color = GRAY4, size= 8), plot.title = element_text(color = GRAY4, size= 12), plot.title.position = "plot", plot.caption = element_text(hjust = 0, color = GRAY6), plot.caption.position = "plot", plot.margin = margin(.5,.5,.5,.5,"cm"), strip.text = element_text(color = GRAY7)) }
test_that("estimate_spatial works", { rmvn <- function(n, mu = 0, V = matrix(1)){ p <- length(mu) if(any(is.na(match(dim(V),p)))) stop("Dimension not right!") D <- chol(V) t(matrix(rnorm(n*p), ncol=p)%*%D + rep(mu,rep(n,p))) } set.seed(5) n <- 200 coords <- cbind(runif(n,0,1), runif(n,0,1)) set.seed(2) x <- as.matrix(runif(n),n,1) sigma.sq = 10 phi = 1 tau.sq = 0.1 D <- as.matrix(dist(coords)) R <- exp(-phi*D) w <- rmvn(1, rep(0,n), sigma.sq*R) y <- rnorm(n, 10*sin(pi * x) + w, sqrt(tau.sq)) set.seed(1) est_known <- RFGLS_estimate_spatial(coords, y, x, ntree = 10, cov.model = "exponential", nthsize = 20, sigma.sq = sigma.sq, tau.sq = tau.sq, phi = phi) expect_true(is.matrix(est_known$predicted_matrix)) expect_equal(dim(est_known$predicted_matrix), c(200,10)) expect_length(est_known$predicted, 200) set.seed(1) est_known_parallel <- RFGLS_estimate_spatial(coords, y, x, ntree = 10, cov.model = "exponential", nthsize = 20, sigma.sq = sigma.sq, tau.sq = tau.sq, phi = phi, h = 2) expect_equal(est_known_parallel$P_matrix, est_known$P_matrix) })
.performCV_core_new_new <- function(cv_data , r = 10^c(-5 , -4 , -3 , -2 , - 1) , s = 10^c(-1 , 0 , 1 , 2 , 3) , stop_cond = 10^-6 , print_out = FALSE , cv_deg_thresh = c(1,10) , normal_start_f = TRUE , weight_f = 0 , ...) { oopts <- options(scipen = 999) on.exit(options(oopts)) result_1 <- .one_cycle(cv_data, r, s, estimated_fitness_start = NULL, estimated_PA_start = NULL, alpha_start = NULL, stop_cond,print_out,cv_deg_thresh,normal_start_f,weight_f); s <- c(0.5, 0.75, 1, 1.5, 2) * result_1$s_optimal; s <- s[s <= 10^4] s <- s[s >= 10^-2] r <- c(0.5, 0.75, 1, 1.5, 2) * result_1$r_optimal; r <- r[r >= 10^-5] r <- r[r <= 10^1] estimated_PA <- result_1$estimated_PA; estimated_fitness <- result_1$estimated_fitness; estimated_alpha <- result_1$alpha_optimal; result_2 <- .one_cycle(cv_data,r,s,estimated_fitness_start = estimated_fitness, estimated_PA_start = estimated_PA, alpha_start = estimated_alpha, stop_cond, print_out, cv_deg_thresh, normal_start_f, weight_f); s <- c(1/1.75 , 1/1.5 , 1/1.25 ,1, 1.25 , 1.5 , 1.75) * result_2$s_optimal; s <- s[s <= 10^4] s <- s[s >= 10^-2] r <- c(1/1.75 , 1/1.5 , 1/1.25 ,1, 1.25 , 1.5 , 1.75) * result_2$r_optimal; r <- r[r >= 10^-5] r <- r[r <= 10^1] estimated_PA <- result_2$estimated_PA; estimated_fitness <- result_2$estimated_fitness; estimated_alpha <- result_2$alpha_optimal; result_2_5 <- .one_cycle(cv_data,r,s, estimated_fitness_start = estimated_fitness, estimated_PA_start = estimated_PA, alpha_start = estimated_alpha, stop_cond, print_out, cv_deg_thresh, normal_start_f, weight_f); s <- c(1/1.75 , 1/1.5 , 1/1.25 ,1, 1.25 , 1.5 , 1.75) * result_2_5$s_optimal; s <- s[s <= 10^4] s <- s[s >= 10^-2] r <- c(1/1.75 , 1/1.5 , 1/1.25 ,1, 1.25 , 1.5 , 1.75) * result_2_5$r_optimal; r <- r[r >= 10^-5] r <- r[r <= 10^1] result_2_75 <- .one_cycle(cv_data,r,s, estimated_fitness_start = estimated_fitness, estimated_PA_start = estimated_PA, alpha_start = estimated_alpha, stop_cond, print_out, cv_deg_thresh, normal_start_f, weight_f); s <- c(1/1.75 , 1/1.5 , 1/1.25 ,1, 1.25 , 1.5 , 1.75) * result_2_75$s_optimal; s <- s[s <= 10^4] s <- s[s >= 10^-2] r <- c(1/1.75 , 1/1.5 , 1/1.25 ,1, 1.25 , 1.5 , 1.75) * result_2_75$r_optimal; r <- r[r >= 10^-5] r <- r[r <= 10^1] estimated_PA <- result_2_75$estimated_PA; estimated_fitness <- result_2_75$estimated_fitness; estimated_alpha <- result_2_75$alpha_optimal; result_3 <- .one_cycle(cv_data,r,s, estimated_fitness_start = estimated_fitness, estimated_PA_start = estimated_PA, alpha_start = estimated_alpha, stop_cond, print_out, cv_deg_thresh, normal_start_f, weight_f); r_optimal <- result_3$r_optimal lambda_optimal <- result_3$lambda_optimal s_optimal <- result_3$s_optimal alpha_optimal <- result_3$alpha_optimal estimated_fitness <- result_3$estimated_fitness estimated_PA <- result_3$estimated_PA result <- list(r_optimal = r_optimal, lambda_optimal = lambda_optimal, s_optimal = s_optimal, alpha_optimal = alpha_optimal, estimated_fitness = estimated_fitness, estimated_PA = estimated_PA, cv_deg_thresh = cv_deg_thresh) class(result) <- "CV_Result" return(result) }
d2 = matrix(c(1.1, 1.2, 1.3, 1.4, 0, 0, 0.5, 0.8), nrow=2, ncol=4, byrow=T) test_that("smoothing, k2", { result2 = smooth.knn.dist(d2, 2) expected2 = list(distances=c(0.16410065, 0.000325), nearest=c(1.1, 0.5)) expect_equal(result2, expected2, tolerance=1e-6) }) test_that("smoothing, k3", { result3 = smooth.knn.dist(d2, 3) expected3 = list(distances=c(0.2959671, 0.000325), nearest=c(1.1, 0.5)) expect_equal(result3, expected3, tolerance=1e-6) }) test_that("smoothing, local 0.5", { result.local05 = smooth.knn.dist(d2, 2, local.connectivity=0.5) expected.local05 = list(distances=c(0.67821503, 0.015625), nearest=c(0.55, 0.25)) expect_equal(result.local05, expected.local05, tolerance=1e-6) }) test_that("smoothing, local 3", { result.local3 = smooth.knn.dist(d2, 2, local.connectivity=3) expected.local3 = list(distances=c(0.00125, 0.000325), nearest=c(1.3, 0.8)) expect_equal(result.local3, expected.local3, tolerance=1e-6) }) test_that("param ab using search 1", { result = find.ab.params(1, 0.1) expected = c(a=1.57694346041, b=0.895060878123) expect_equal(expected, result, tolerance=1e-4) }) test_that("param ab using search 2", { result = find.ab.params(2, 0.1) expected = c(a=0.544660540037, b=0.84205542675) expect_equal(expected, result, tolerance=1e-4) }) test_that("param ab using search 3", { result = find.ab.params(0.6, 0.2) expected = c(a=2.95031796402, b=1.14888917655) expect_equal(expected, result, tolerance=1e-4) }) test_that("epochs per sample with uniform weights", { result = make.epochs.per.sample(rep(1, 5), 4) expected = c(1, 1, 1, 1, 1) expect_equal(expected, result) }) test_that("epochs per sample for a matrix", { g = matrix(0, ncol=3, nrow=3) g[1,] = c(0.5, 0.5, 0.4) g[2,] = c(1.0, 0.8, 0.3) g[3,] = c(0.8, 1.1, 0) g = t(g) result = make.epochs.per.sample(g, 5) expected = g expected[1:9] = c(2.2, 2.2, 2.75, 1.1, 1.375, 3.66666667, 1.375, 1, -1) expect_equal(expected, result) }) test_that("number clipping with default xmax", { expect_equal(clip(2), 2) expect_equal(clip(4.2), 4) expect_equal(clip(-12), -4) }) test_that("number clipping with vector", { result = clip(c(0,1,4.2, 6, -2, -9)) expected = c(0, 1, 4, 4, -2, -4) expect_equal(expected, result) }) test_that("number clipping with custom xmax", { expect_equal(clip(2, 1), 1) expect_equal(clip(4.2, 6), 4.2) expect_equal(clip(-12, 3), -3) }) test_that("number clipping with default xmax", { mat = matrix(1:8, ncol=2, nrow=4) rownames(mat) = letters[1:4] result = center.embedding(mat) expected = mat expected[,1] = mat[,1] - mean(mat[,1]) expected[,2] = mat[,2] - mean(mat[,2]) expect_equal(result, expected) }) test_that("column.seeds produces unique integers", { mat = matrix(seq(0, 1, length=30), ncol=10) result = column.seeds(mat) expect_equal(length(result), 10) expect_is(result, "numeric") expect_equal(length(unique(result)), length(result)) }) test_that("column.seeds produces reproducible integers", { mat0 = matrix(seq(0, 1, length=30), ncol=10) result0 = column.seeds(mat0) mat1 = mat0[, 1, drop=FALSE] mat2 = mat0[, 2:10] result1 = column.seeds(mat1) result2 = column.seeds(mat2) expect_equal(result0, c(result1, result2)) })
simulate_pkpdmodel_ode <- function(U = 1e5, I = 0, V = 10, n=0, dU = 0, dI = 1, dV = 2, b = 1e-5, g = 1, p = 10, C0 = 1, dC = 1, C50 = 1, k = 1, Emax = 0, txstart = 10, txinterval = 1, tstart = 0, tfinal = 20, dt = 0.01) { pkpdode <- function(t, y, parms) { with( as.list(c(y,parms)), { e=Emax*C^k/(C^k + C50) dCdt = - dC*C dUdt = n - dU*U - b*V*U dIdt = b*V*U - dI*I dVdt = (1-e)*p*I - dV*V - g*b*V*U list(c(dCdt, dUdt, dIdt, dVdt)) } ) } adddrug <- function(t,y,parms) { y['C'] = y['C'] + parms['C0'] return(y) } Y0 = c(C = 0, U = U, I = I, V = V); timevec = seq(tstart, tfinal, by = dt); pars = c(n=n,dU=dU,dI=dI,dV=dV,b=b, g=g, p=p, C0 = C0, dC=dC,C50 = C50, k = k, Emax = Emax); drugtimes = seq(txstart, tfinal, by = txinterval) odeoutput = deSolve::ode(y = Y0, times = timevec, func = pkpdode, events = list(func = adddrug, time = drugtimes), parms=pars, atol=1e-12, rtol=1e-12); result = list() result$ts = as.data.frame(odeoutput) return(result) }
plot_warming_stripes <- function(variable, infile, climatology_file, out_dir, climate_year_start, climate_year_end, start_date, end_date, country_code, outfile_name, language, pointsTF, lineTF, title, stripe_color, circ_plot, verbose, nc = NULL) { cmsafops::wfldmean(variable, infile, outfile = file.path(tempdir(),"tmp_warming_stripes_plot.nc"), overwrite = TRUE, nc = nc) temp_file <- file.path(tempdir(),"tmp_warming_stripes_plot.nc") file_data <- cmsafops::read_file(temp_file, variable) nc_in <- ncdf4::nc_open(temp_file) dum_dat <- ncdf4::ncvar_get( nc_in, file_data$variable$name, collapse_degen = FALSE ) dim_names <- names(nc_in$dim) dimensions <- cmsafops::get_dimensions(nc_in, dim_names) time_info <- cmsafops::get_time_info(nc_in, dim_names, dimensions$names$t) dimension.data.t <- nc_in$dim[[dimensions$names$t]]$vals dum_dat <- as.vector(dum_dat) date_info_1 <- as.Date(cmsafops::get_time(time_info$units, dimension.data.t)) date_info <- as.numeric(date_info_1) dataT <- data.frame(date_info, dum_dat) ncdf4::nc_close(nc_in) nBins = 10 minT = min(dataT$dum_dat) maxT = max(dataT$dum_dat) minY = min(dataT$date_info) maxY = max(dataT$date_info) xlabel <- rep(NA, length(date_info_1)) n <- round(seq(1, length(xlabel), length.out = 4)) xlabel[n] <- format(date_info_1[n], "%Y") title <- gsub("XXXX", xlabel[1], title) resfactor <- 1 if (circ_plot) { getYmult <- function() { if(grDevices::dev.cur() == 1) { warning("No graphics device open.") ymult <- 1 } else { xyasp <- graphics::par("pin") xycr <- diff(graphics::par("usr"))[c(1,3)] ymult <- xyasp[1]/xyasp[2]*xycr[2]/xycr[1] } return(ymult) } draw.circle <- function(x, y, radius, nv=100, border=NULL, col=NA, lty=1, density=NULL, angle=45, lwd = 1) { xylim <- graphics::par("usr") plotdim <- graphics::par("pin") ymult <- getYmult() angle.inc <- 2*pi/nv angles <- seq(0,2*pi-angle.inc, by = angle.inc) if(length(col) < length(radius)) col <- rep(col, length.out = length(radius)) for(circle in 1:length(radius)) { xv <- cos(angles)*radius[circle]+x yv <- sin(angles)*radius[circle]*ymult+y graphics::polygon(xv, yv, border = border, col = col[circle], lty = lty, density = density, angle = angle, lwd = lwd) } invisible(list(x = xv, y = yv)) } grDevices::png(filename=paste0(out_dir, "/", outfile_name), res = 72*resfactor, height=800*resfactor, width=800*resfactor) temp <- dataT temp$date_info <- format(date_info_1,"%Y") colnames(temp) <- c("date", "level") Red <- RColorBrewer::brewer.pal(9, "YlOrRd") Red <- grDevices::colorRampPalette(Red)(170) Blues <- RColorBrewer::brewer.pal(9, "Blues") Blues <- grDevices::colorRampPalette(Blues)(170) colors=c(rev(Blues),Red) if (stripe_color == 2){palette <- grDevices::colorRampPalette(c(" " " colors <- palette(340) } if (stripe_color == 3){palette <- grDevices::colorRampPalette(c(" " " " colors <- palette(340) } AssignColor=function(data,colors) { data$colIndex=rep(-9999,length(data$date)) data$color=rep(-9999,length(data$date)) borders=seq(min(data$level),max(data$level),length=length(colors)+1) for(i in 1:(length(borders)-1)) { vect=which(data$level>=borders[i] & data$level<=borders[i+1]) data$colIndex[vect]=i data$color[vect]=colors[i] } return(data) } temp=AssignColor(temp,colors) delta=5 xxx=seq(1,length(temp$date))*0 temp$radius=((temp$level+abs(min(temp$level))))*0.08 for(i in 2:length(xxx)) { xxx[i]=xxx[i-1]+temp$radius[i-1]+temp$radius[i]+delta } FactorShape=1;shape="1x1" graphics::par("mar") graphics::par(mfrow = c(1,1)) graphics::par(mar = c(0, 0, 0, 0), bg = "black") YlimVal = 1.1 XlimVal = FactorShape*YlimVal plot(mean(xxx), col = "white", xlim = c(-XlimVal,XlimVal), ylim = c(-YlimVal,YlimVal) , bty = "n", xaxt = "n", yaxt = "n", xlab = "", ylab = "") x = rep(-9999,length(xxx)) y = rep(-9999,length(xxx)) RangeAt3oClock = 50 radiusStart = 0.04 radius = rep(-9999,length(xxx)) for(i in length(xxx):1) { x[i] = 0 y[i] = 0 radius[i] = i/length(xxx)+radiusStart colorCircle = temp$color[i] draw.circle(x[i],y[i],radius[i],nv = 100, border = colorCircle, col = colorCircle, lty = 1, angle = 45, lwd = 1) } alpha = 0.04 colorCircle = "gray20" draw.circle(x[i]-alpha, y[i], radiusStart, nv=10000, border = colorCircle, col = colorCircle, lty = 1, angle = 45, lwd = 0.000000001) delta = radiusStart xleft = 0-alpha ybottom = -delta - 0.001 xright = 10 ytop = delta + 0.001 graphics::rect(xleft, ybottom, xright, ytop, density = NULL, angle = 45, col = "gray20", border = "NA", lty = graphics::par("lty"), lwd = graphics::par("lwd")) cexYear = 1.5 t = c(1:length(temp$date)) t = c(min(t), stats::median(t), max(t)) for (i in t) { graphics::text(radius[i], 0, paste(temp$date[i]), cex=cexYear, col = temp$color[i]) } title(title, col.main = "white", cex.main = 1.8, line = -2.5, font.main = 2) } else { grDevices::png(filename = paste0(out_dir, "/", outfile_name), res = 72*resfactor, height = 640*resfactor, width = 1140*resfactor) graphics::par(bg = "black") graphics::plot(x = date_info_1, y = dum_dat, ylab = '', xlab='', type = "n", axes = FALSE) rangeT = maxT - minT binWidth = rangeT/nBins palette <- rev(RColorBrewer::brewer.pal(nBins,"RdBu")) if (stripe_color == 2){palette <- grDevices::colorRampPalette(c(" " " palette <- palette(nBins) } if (stripe_color == 3){palette <- grDevices::colorRampPalette(c(" " " " palette <- palette(nBins) } binCol <- function (Temp){ index.col <- floor((Temp - minT)/binWidth)+1 if(index.col > 10){index.col <- 10} palette[index.col] } diff_time <- abs(date_info[2] - date_info[1]) rectPlot <- function(df.row){ y <- df.row["date_info"] lineCol <- binCol(df.row["dum_dat"]) graphics::rect(y-(diff_time/2), minT, y+(diff_time/2), maxT, col=lineCol, border=NA, lwd=0) } apply(dataT, 1, rectPlot) title(title, col.main = "white", cex.main = 2.0, line = 0.2, font.main = 2) graphics::mtext(xlabel, side = 1, line = -0.5, at = date_info_1, cex = 1.5, col = "white") if (pointsTF) graphics::points(dataT,pch=21,bg="white") if (lineTF) graphics::abline(stats::line(dataT),col="white") } grDevices::dev.off() tmp_climate_dir <- file.path(tempdir(), "tmp_climate_dir") if (dir.exists(tmp_climate_dir)) { unlink(tmp_climate_dir, recursive = TRUE) } if (!dir.exists(tmp_climate_dir)) { dir.create(tmp_climate_dir) } tmp_clim_mean_value <- file.path(tmp_climate_dir, paste0("tmp_clim_mean_value.nc")) cmsafops::fldmean(var = variable, infile = climatology_file, outfile = tmp_clim_mean_value, overwrite = TRUE) nc_in <- ncdf4::nc_open(tmp_clim_mean_value) dum_dat_mean <- ncdf4::ncvar_get(nc_in, variable, collapse_degen = FALSE) ncdf4::nc_close(nc_in) years_all <- cmsafops::get_date_time(file_data$dimension_data$t, file_data$time_info$units)$years months_all <- cmsafops::get_date_time(file_data$dimension_data$t, file_data$time_info$units)$months days_all <- cmsafops::get_date_time(file_data$dimension_data$t, file_data$time_info$units)$days ranking <- data.frame(years_all, months_all, days_all, as.vector(dum_dat)) names(ranking) <- c("Year", "Month", "Day","Value") titles <- c("Analyzed years", "Climatology Mean Value", "Maximum", "Minimum") ordered_index_dataT <- order(dataT['dum_dat']) ordered_dataT <- dataT[ordered_index_dataT, ] row.names(ordered_dataT) <- NULL standout_years <- c(paste0(climate_year_start, " - " ,format(end_date, format = "%Y")), paste(climate_year_start, climate_year_end, sep = " - "), toString(ordered_dataT[nrow(ordered_dataT),1]), toString(ordered_dataT[1,1])) standout_values <- c(toString(mean(dataT$dum_dat)), mean(dum_dat_mean), toString(ordered_dataT[nrow(ordered_dataT),2]), toString(ordered_dataT[1,2])) final_values <- data.frame(title = titles, years = standout_years, value = standout_values) calc.parameters.monitor.climate(final_values, ranking[order(ranking$Value),]) if (dir.exists(tmp_climate_dir)) { unlink(tmp_climate_dir, recursive = TRUE) } }
logout_server <- function(input, output, session, isLogged = reactive(FALSE), textlogged = "You are logged in") { observeEvent(isLogged(), { if(isLogged()){ shinyjs::show("logout") } else { shinyjs::hide("logout") } }) output$who <- renderUI({ if(isLogged()){ textlogged } }) reactive(input$logout) }
extractDocumentation <- function(path, start_type=NULL, comment="*'") { if(length(path)>1) { out <- list() for(p in path) { out <- append(out,extractDocumentation(p,start_type=start_type, comment=comment)) } return(mergeDocumentation(out)) } escapeRegex <- function(x) { return(gsub("([.|()\\^{}+$*?]|\\[|\\])", "\\\\\\1", x)) } removeComments <- function(x,comment) { return(grep(paste0("^(",escapeRegex(comment),"|[^*])"),x, value=TRUE)) } extract_block <- function(x,comment) { code <- "@(\\w*) ?(.*)$" pattern <- paste0("^(",escapeRegex(comment),") *",code) type <- sub(pattern,"\\2",x[1]) if(type=="equations") { x[1] <- sub(pattern,"\\1 \\3",x[1]) x <- paste(x,collapse="\n") equation <- "(^|\n)[^\n]*?[ \n\t]*\\.\\.([^.]|\n)(.|\n)*?;" eq <- stri_extract_all_regex(x,equation)[[1]] if(length(eq)==1 && is.na(eq)) { eq <- NULL } else { eq <- gamsequation2tex(eq) } x <- stri_replace_all_regex(x,equation,paste(comment,"\n",comment," x <- stri_extract_all_regex(x,paste0(escapeRegex(comment),".*(\\n|$)"))[[1]] x <- gsub(paste0("(\n|",escapeRegex(comment)," *)"),"",x) for(i in names(eq)) { delim <- ifelse(grepl("CONVERSION FAILED!",i,fixed = TRUE), "```","") x[grep(" } type <- "description" } else if(type=="code") { com <- grepl(paste0("^",escapeRegex(comment)," *"),x) x[!com] <- paste0("```\n",x[!com],"\n```") x[com] <- sub(paste0("^",escapeRegex(comment)," *"),"",x[com]) x[1] <- sub(code,"\\2",x[1]) x <- paste(x,collapse="\n") x <- gsub("\n```\n```\n","\n",x,fixed=TRUE) x <- strsplit(x,"\n")[[1]] type <- "description" } else if(type=="stop") { return(NULL) } else { x <- grep(paste0("^",escapeRegex(comment)," *"), x, value=TRUE) x <- sub(paste0("^",escapeRegex(comment)," *"),"",x) x[1] <- sub(code,"\\2",x[1]) } while(length(x)>1 & x[1]=="") x <- x[-1] while(length(x)>1 & tail(x,1)=="") x <- x[-length(x)] if(length(x)==1) if(is.na(x) | x=="") return(NULL) if(type=="description") x <- c(x,"") out <- list() out[[type]] <- x return(out) } if(!file.exists(path)) return(list()) x <- readLines(path, warn = FALSE) x <- removeComments(x,comment) if(!is.null(start_type)) { x <- c(paste0(comment," @",start_type," "),x) } blocks_start <- suppressWarnings(grep(paste0("^",escapeRegex(comment)," @[a-z]*( |$)"),x)) if(length(blocks_start)==0) return(list()) blocks_end <- c(blocks_start[-1]-1,length(x)) blocks <- list() for(i in 1:length(blocks_start)) { blocks <- c(blocks,extract_block(x[blocks_start[i]:blocks_end[i]], comment)) } return(mergeDocumentation(blocks)) }
context("mllogis") set.seed(313) tiny_data <- stats::rlogis(10, 1, 7) small_data <- stats::rlogis(100, 10, 3) medium_data <- stats::rlogis(1000, 1 / 2, 2) large_data <- stats::rlogis(10000, 20, 13) m <- stats::median(tiny_data) mad <- stats::median(abs(tiny_data - m)) start <- c(m, log(mad)) mle1 <- suppressWarnings(nlm(function(p) { -sum(stats::dlogis(tiny_data, p[1], exp(p[2]), log = TRUE)) }, p = start)) m <- stats::median(small_data) mad <- stats::median(abs(small_data - m)) start <- c(m, log(mad)) mle2 <- suppressWarnings(nlm(function(p) { -sum(stats::dlogis(small_data, p[1], exp(p[2]), log = TRUE)) }, p = start)) m <- stats::median(medium_data) mad <- stats::median(abs(medium_data - m)) start <- c(m, log(mad)) mle3 <- suppressWarnings(nlm(function(p) { -sum(stats::dlogis(medium_data, p[1], exp(p[2]), log = TRUE)) }, p = start)) m <- stats::median(large_data) mad <- stats::median(abs(large_data - m)) start <- c(m, log(mad)) mle4 <- suppressWarnings(nlm(function(p) { -sum(stats::dlogis(large_data, p[1], exp(p[2]), log = TRUE)) }, p = start)) expect_equal(c(mle1$estimate[1], exp(mle1$estimate[2])), as.numeric(mllogis(tiny_data)), tolerance = 1e-5 ) expect_equal(c(mle2$estimate[1], exp(mle2$estimate[2])), as.numeric(mllogis(small_data)), tolerance = 1e-5 ) expect_equal(c(mle3$estimate[1], exp(mle3$estimate[2])), as.numeric(mllogis(medium_data)), tolerance = 1e-5 ) expect_equal(c(mle4$estimate[1], exp(mle4$estimate[2])), as.numeric(mllogis(large_data)), tolerance = 1e-5 ) expect_equal(-mle1$minimum, attr(mllogis(tiny_data), "logLik"), tolerance = 1e-5 ) expect_equal(-mle2$minimum, attr(mllogis(small_data), "logLik"), tolerance = 1e-5 ) expect_equal(-mle3$minimum, attr(mllogis(medium_data), "logLik"), tolerance = 1e-5 ) expect_equal(-mle4$minimum, attr(mllogis(large_data), "logLik"), tolerance = 1e-5 ) expect_error(mllogis(c(tiny_data, NA))) expect_equal( coef(mllogis(small_data)), coef(mllogis(c(small_data, NA), na.rm = TRUE)) ) est <- mllogis(small_data, na.rm = TRUE) expect_equal(attr(est, "model"), "Logistic") expect_equal(class(est), "univariateML")
tar_definition <- function( default = targets::tar_target_raw("target_name", quote(identity())) ) { tar_assert_target(default) if_any(tar_runtime$exists_target(), tar_runtime$get_target(), default) }
consensusClusterNoPlots <- function(df, link_method, dist_method, max_k, reps, p_var, p_net, cc_seed){ ff <- tempfile() grDevices::png(filename=ff) res <- suppressMessages(ConsensusClusterPlus(as.matrix(df), maxK = max_k, innerLinkage = link_method, reps = reps, pItem = p_var, pFeature = p_net, clusterAlg = "hc", distance = dist_method, seed = cc_seed, plot = NULL)) grDevices::dev.off() unlink(ff) return(res) }
expected <- eval(parse(text="FALSE")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(x = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE), y = c(-0.0561287395290008, -0.155795506705329, -1.47075238389927, -0.47815005510862, 0.417941560199702, 1.35867955152904, -0.102787727342996, 0.387671611559369, -0.0538050405829051, -1.37705955682861)), .Names = c(\"x\", \"y\"), row.names = c(NA, -10L), class = \"data.frame\"))")); do.call(`is.array`, argv); }, o=expected);
library(tidyverse) library(tidytext) fog_recent <- readRDS("fog_recent.rds") fog_recent %>% count(message) %>% count(n) tr_normal <- function(x) { unicode_symbols <- map(cli:::symbol_utf8, rex::escape) normal_symbols <- rlang::with_options(cli.unicode = FALSE, cli::symbol) reduce2(unicode_symbols, normal_symbols, str_replace_all, .init = x) } clean_timings <- function(x) { str_replace_all(x, "\\[[0-9]+s(?:/[0-9]+s)?\\]", "[timing]") } clean_testthat_summary <- function(x) { str_replace_all(x, "\\[ OK:[^\n]+ \\]", "[testthat summary]") } clean_backtrace <- function(x) { str_replace_all(x, "( +[1-9][0-9]*[.] +(?:[\\\\|+└│├].*| *)\n)+", "[backtrace]\n") } clean_pre_backtrace <- function(x) { str_replace_all(x, "[x } clean_ptime <- function(x) { str_replace_all(x, " [>] base::assign.*\n", "") } clean_paths <- function(x) { str_replace_all(x, "/home/hornik/tmp/[^\n]+/Work/build/Packages/|/data/gannet/ripley/R/packages/[^\n]+[.]Rcheck/|/home/ripley/R/Lib32-dev/|D:/temp/[^\n]+/RLIBS_[^\n/]+/", "[path]/") } fog_clean <- fog_recent %>% mutate(message = tr_normal(message)) %>% mutate(message = clean_timings(message)) %>% mutate(message = clean_testthat_summary(message)) %>% mutate(message = clean_backtrace(message)) %>% mutate(message = clean_pre_backtrace(message)) %>% mutate(message = clean_ptime(message)) %>% mutate(message = clean_paths(message)) %>% group_by(package, result, check, message) %>% summarize( flavors = paste0(flavors, collapse = ", "), n_flavors = sum(n_flavors), version = version[[1]] ) %>% ungroup() unlink("msg", recursive = TRUE) dir.create("msg", showWarnings = FALSE) fog_clean %>% filter(check != "vignettes") %>% rowid_to_column() %>% transmute(text = message, path = sprintf("msg/%04d-%s.txt", rowid, package)) %>% pwalk(brio::write_lines)
mapXY <- function(start,end,y,yMod,x,yfactor,r2,pts_1,pts_2,pts_3,pts_4,chrt=FALSE ){ roundedX<-roundedY<-list() for (counter in start: end ) { r2backup<-r2 current_x <- x[[counter]] current_y <- y[[counter]] yMod_current<- yMod[[counter]] diffx<-max(current_x) - min(current_x) diffy<-max(current_y) - min(current_y) ratexy <- diffx/diffy ifelse ( (diffx/r2) * 2 < ratexy*4 , r2 <- diffx/(ratexy*2) ,r2 ) topBotline_x <- c(min(current_x)+r2, max(current_x)-r2 ) x2_1<-min(current_x)+r2 x2_2<-max(current_x)-r2 bottomline_y<-rep(min(yMod_current),2) topline_y <-rep(max(yMod_current),2) y2_1<-max(current_y)-r2*yfactor y2_2<-min(current_y)+r2*yfactor xy_1 <- cbind(x2_2 + r2 * sin(pts_2), y2_1 + (r2 * cos(pts_2) *yfactor) ) xy_2 <- cbind(x2_1 + r2 * sin(pts_1), y2_1 + (r2 * cos(pts_1) *yfactor) ) xy_3 <- cbind(x2_1 + r2 * sin(pts_4), y2_2 + (r2 * cos(pts_4) *yfactor) ) xy_4 <- cbind(x2_2 + r2 * sin(pts_3), y2_2 + (r2 * cos(pts_3) *yfactor) ) yMod_current[which(yMod_current==max(yMod_current))]<-yMod_current[which(yMod_current==max(yMod_current))]-r2*yfactor yMod_current[which(yMod_current==min(yMod_current))]<-yMod_current[which(yMod_current==min(yMod_current))]+r2*yfactor if(chrt==FALSE){ roundedX[[counter]]<-c(current_x[1:2],xy_4[,1],topBotline_x,xy_3[,1], current_x[3:4],xy_2[,1],topBotline_x,xy_1[,1]) roundedY[[counter]]<-c(yMod_current[1:2],xy_4[,2],bottomline_y,xy_3[,2], yMod_current[3:4],xy_2[,2],topline_y ,xy_1[,2]) } else { roundedX[[counter]]<-c(xy_4[,1],xy_3[,1], xy_2[,1],xy_1[,1] ,xy_4[,1][1] ) roundedY[[counter]]<-c(xy_4[,2],xy_3[,2], xy_2[,2] ,xy_1[,2] ,xy_4[,2][1] ) } attr(roundedY[[counter]],"rowIndex")<-attr(current_y,"rowIndex") attr(roundedX[[counter]],"rowIndex")<-attr(current_x,"rowIndex") attr(roundedY[[counter]],"chrName1")<-attr(current_y,"chrName1") attr(roundedX[[counter]],"chrName1")<-attr(current_x,"chrName1") r2<-r2backup } roundXroundY<-list() roundXroundY$roundedX<-roundedX roundXroundY$roundedY<-roundedY return(roundXroundY) } mapXYCen <- function(start,end,ycoordCentsS,xcoordCentsS,pts_1,pts_2,pts_3,pts_4,mimic=FALSE ){ roundedX<-roundedY<-xy_1<-xy_2<-xy_3<-xy_4<-list() for (counter in start: end ) { chrRegion <- attr(ycoordCentsS[[counter]],"chrRegion") minX<-min(xcoordCentsS[[counter]]) maxX<-max(xcoordCentsS[[counter]]) minY<-min(ycoordCentsS[[counter]]) maxY<-max(ycoordCentsS[[counter]]) diffx<-maxX - minX diffy<-maxY - minY if(is.null(chrRegion)){ halfmaxY <- diffy/2 } else if(chrRegion %in% c("qcen") ) { halfmaxY <- diffy } else if(chrRegion %in% c("pcen")){ halfmaxY <- diffy minY <- minY-diffy } else { halfmaxY <- diffy/2 } halfmaxX <- diffx/2 xy_1 <- cbind( minX + halfmaxX + halfmaxX * sin(pts_1) , minY + halfmaxY * cos(pts_1)) xy_2 <- cbind( minX + halfmaxX + halfmaxX * sin(pts_2) , minY + halfmaxY * cos(pts_2)) xy_3 <- cbind( minX + halfmaxX + halfmaxX * sin(pts_3) , maxY + halfmaxY * cos(pts_3)) xy_4 <- cbind( minX + halfmaxX + halfmaxX * sin(pts_4) , maxY + halfmaxY * cos(pts_4)) if(mimic==FALSE) { roundedX[[counter]] <-c(xy_4[,1],minX , maxX , xy_3[,1], minX+halfmaxX, xy_2[,1],maxX , minX , xy_1[,1]) roundedY[[counter]] <-c(xy_4[,2],maxY , maxY , xy_3[,2], minY+halfmaxY, xy_2[,2],minY , minY , xy_1[,2]) } else { roundedX[[counter]]<-c(minX,xy_1[,1],minX+halfmaxX,(xy_2[,1]), maxX, (xy_3[,1] ),minX+halfmaxX,xy_4[,1]) roundedY[[counter]]<-c(minY,xy_1[,2],minY+halfmaxY,(xy_2[,2]), maxY, (xy_3[,2] ),minY+halfmaxY,xy_4[,2]) } len <- length(roundedX[[counter]]) chrRegion <- attr(ycoordCentsS[[counter]],"chrRegion") if(!is.null(chrRegion)){ start <- ifelse(chrRegion %in% c("cen","pcen"),1,(floor(len/2)+1) ) end <- ifelse(chrRegion %in% c("cen","qcen"),len,floor(len/2) ) } else { start <- 1 end <- len } roundedX[[counter]]<-roundedX[[counter]][start:end] roundedY[[counter]]<-roundedY[[counter]][start:end] attr(roundedY[[counter]],"rowIndex") <- attr(ycoordCentsS[[counter]],"rowIndex") attr(roundedY[[counter]],"chrRegion")<- chrRegion attr(roundedX[[counter]],"rowIndex") <- attr(xcoordCentsS[[counter]],"rowIndex") attr(roundedX[[counter]],"chrRegion")<- chrRegion } roundXroundY<-list() roundXroundY$roundedX<-roundedX roundXroundY$roundedY<-roundedY return(roundXroundY) } mapXYCenLines <- function(start,end,ycoordCentsS,xcoordCentsS ){ X1<-Y1<-X2<-Y2<-list() for (counter in start: end ) { diffx<-max(xcoordCentsS[[counter]]) - min(xcoordCentsS[[counter]]) diffy<-max(ycoordCentsS[[counter]]) - min(ycoordCentsS[[counter]]) halfmaxX <- diffx/2 halfmaxY <- diffy/2 minX<-min(xcoordCentsS[[counter]]) maxX<-max(xcoordCentsS[[counter]]) minY<-min(ycoordCentsS[[counter]]) maxY<-max(ycoordCentsS[[counter]]) xy_1 <- cbind( minX, minY ) xy_2 <- cbind( minX+halfmaxX, minY+halfmaxY ) xy_3 <- cbind( minX, maxY ) xy_4 <- cbind( maxX, minY ) xy_5 <- cbind( maxX-halfmaxX, maxY-halfmaxY ) xy_6 <- cbind( maxX, maxY ) X1[[counter]]<-c(xy_1[,1],xy_2[,1],xy_3[,1] ) Y1[[counter]]<-c(xy_1[,2],xy_2[,2],xy_3[,2] ) X2[[counter]]<-c(xy_4[,1],xy_5[,1],xy_6[,1] ) Y2[[counter]]<-c(xy_4[,2],xy_5[,2],xy_6[,2] ) } XY<-list() XY$X1<-X1 XY$Y1<-Y1 XY$X2<-X2 XY$Y2<-Y2 return(XY) } mapxyRoundCenLines <- function(start,end,ycoordCentsS,xcoordCentsS,pts_1,pts_2,pts_3,pts_4,mimic=FALSE ){ roundedX1<-roundedY1<-roundedX2<-roundedY2<-list() for (counter in start: end ) { diffx<-max(xcoordCentsS[[counter]]) - min(xcoordCentsS[[counter]]) diffy<-max(ycoordCentsS[[counter]]) - min(ycoordCentsS[[counter]]) halfmaxX <- diffx/2 halfmaxY <- diffy/2 minX<-min(xcoordCentsS[[counter]]) maxX<-max(xcoordCentsS[[counter]]) minY<-min(ycoordCentsS[[counter]]) maxY<-max(ycoordCentsS[[counter]]) xy_1 <- cbind( min(xcoordCentsS[[counter]])+halfmaxX + halfmaxX * sin(pts_1), min(ycoordCentsS[[counter]]) + halfmaxY * cos(pts_1) ) xy_2 <- cbind( min(xcoordCentsS[[counter]])+halfmaxX + halfmaxX * sin(pts_2), min(ycoordCentsS[[counter]]) + halfmaxY * cos(pts_2)) xy_3 <- cbind( min(xcoordCentsS[[counter]])+halfmaxX + halfmaxX * sin(pts_3), max(ycoordCentsS[[counter]]) + halfmaxY * cos(pts_3)) xy_4 <- cbind( min(xcoordCentsS[[counter]])+halfmaxX + halfmaxX * sin(pts_4), max(ycoordCentsS[[counter]]) + halfmaxY * cos(pts_4 ) ) roundedX1[[counter]]<-c( rev(xy_2[,1] ) ,xy_4[,1] ) roundedY1[[counter]]<-c( rev(xy_2[,2]) ,xy_4[,2] ) roundedX2[[counter]]<-c( xy_1[,1] ,rev(xy_3[,1] ) ) roundedY2[[counter]]<-c( xy_1[,2] ,rev(xy_3[,2] ) ) } roundXroundY<-list() roundXroundY$roundedX1<-roundedX1 roundXroundY$roundedY1<-roundedY1 roundXroundY$roundedX2<-roundedX2 roundXroundY$roundedY2<-roundedY2 return(roundXroundY) } mapXYchromatidLA <- function(start,end,y,x,xModifier=.1 ){ longArmChrtx<-longArmChrty<-list() for (counter in start: end ) { maxX<-minX<-halfX<-halfXModMinus<-halfXModPlus<-NULL maxX <- max(x[[counter]]) minX <- min(x[[counter]]) maxY <- max(y[[counter]]) minY <- min(y[[counter]]) halfX <- (maxX+minX)/2 halfXModPlus <- halfX + xModifier halfXModMinus <- halfX - xModifier longArmChrtx[[counter]]<-c(maxX,maxX,halfXModPlus,halfXModPlus,halfXModMinus,halfXModMinus,minX,minX) longArmChrty[[counter]]<-c(maxY,minY,minY, maxY, maxY, minY, minY,maxY) } chrtXchrtYLA<-list() chrtXchrtYLA$longArmChrtx<-longArmChrtx chrtXchrtYLA$longArmChrty<-longArmChrty return(chrtXchrtYLA) } mapXYchromatidSA <- function(start,end,y,x,xModifier=.1 ){ shortArmChrtx<-shortArmChrty<-list() for (counter in start: end ) { maxX<-minX<-halfX<-halfXModMinus<-halfXModPlus<-NULL maxX <- max(x[[counter]]) minX <- min(x[[counter]]) maxY <- max(y[[counter]]) minY <- min(y[[counter]]) halfX <- (maxX+minX)/2 halfXModPlus <- halfX + xModifier halfXModMinus <- halfX - xModifier shortArmChrtx[[counter]] <-c(maxX,maxX,minX,minX,halfXModMinus,halfXModMinus,halfXModPlus,halfXModPlus) shortArmChrty[[counter]] <-c(maxY,minY,minY,maxY, maxY, minY, minY, maxY) } chrtXchrtYSA<-list() chrtXchrtYSA$shortArmChrtx<-shortArmChrtx chrtXchrtYSA$shortArmChrty<-shortArmChrty return(chrtXchrtYSA) } mapXYchromatidHolo <- function(start,end,y,x,xModifier=.1 ){ xCT1<-yCT1<-xCT2<-yCT2<-list() for (counter in start: end ) { maxX<-minX<-halfX<-halfXModMinus<-halfXModPlus<-NULL maxX <- max(x[[counter]]) minX <- min(x[[counter]]) maxY <- max(y[[counter]]) minY <- min(y[[counter]]) halfX <- (maxX+minX)/2 halfXModPlus <- halfX + xModifier halfXModMinus <- halfX - xModifier xCT1[[counter]]<-c(maxX,maxX,halfXModPlus,halfXModPlus) yCT1[[counter]]<-c(maxY,minY,minY, maxY) xCT2[[counter]]<-c(halfXModMinus,halfXModMinus,minX,minX) yCT2[[counter]]<-c(maxY, minY, minY,maxY) attr(xCT1[[counter]],"arm") <- attr(xCT2[[counter]],"arm") <- attr(yCT1[[counter]],"arm") <- attr(yCT2[[counter]],"arm") <- attr(y[[counter]],"arm") attr(xCT1[[counter]],"rowIndex") <- attr(xCT2[[counter]],"rowIndex") <- attr(yCT1[[counter]],"rowIndex") <- attr(yCT2[[counter]],"rowIndex") <- attr(y[[counter]],"rowIndex") attr(xCT1[[counter]],"wholeArm") <- attr(xCT2[[counter]],"wholeArm") <- attr(yCT1[[counter]],"wholeArm") <- attr(yCT2[[counter]],"wholeArm") <- attr(y[[counter]],"wholeArm") attr(xCT1[[counter]],"whichArm") <- attr(xCT2[[counter]],"whichArm") <- attr(yCT1[[counter]],"whichArm") <- attr(yCT2[[counter]],"whichArm") <- attr(y[[counter]],"whichArm") attr(xCT1[[counter]],"squareSide") <- attr(xCT2[[counter]],"squareSide") <- attr(yCT1[[counter]],"squareSide") <- attr(yCT2[[counter]],"squareSide") <- attr(y[[counter]],"squareSide") } chrtXchrtYHolo<-list() chrtXchrtYHolo$xCT1<-xCT1 chrtXchrtYHolo$xCT2<-xCT2 chrtXchrtYHolo$yCT1<-yCT1 chrtXchrtYHolo$yCT2<-yCT2 return(chrtXchrtYHolo) } mapXYchromatidSARo <- function(start,end,y,x,r2,xModifier,pts){ RoundedSAChrtx<-RoundedSAChrty<-list() for (counter in start: end ) { maxX<-minX<-halfX<-halfXModMinus<-halfXModPlus<-NULL maxX <- max(x[[counter]]) minX <- min(x[[counter]]) maxY <- max(y[[counter]]) minY <- min(y[[counter]]) halfX <- (maxX+minX)/2 halfXModPlus <- halfX + xModifier halfXModMinus <- halfX - xModifier r2backup<-r2 diffx<-maxX - minX diffy<-maxY - minY ratexy<-diffx/diffy ifelse( (diffx/r2) * 2 < ratexy*4 , r2 <- diffx/(ratexy*2) ,r2 ) yMod<-y[[counter]] yMod[which(yMod==max(yMod))] <- yMod[which(yMod==max(yMod))]-r2 yMod[which(yMod==min(yMod))] <- yMod[which(yMod==min(yMod))]+r2 topBotline_x<-c(minX+r2, maxX-r2) topBotline_x2 <- c(halfXModPlus + r2, maxX-r2, halfXModMinus-r2,minX+r2) bottomline_y <-rep(minY,2) ptsl <- split(pts, sort(rep(1:4, each=length(pts)/4, len=length(pts))) ) xy_1 <- cbind( (minX+r2) + r2 * sin(ptsl[[1]]), (maxY-r2) + r2 * cos(ptsl[[1]])) xy_2 <- cbind( (maxX-r2) + r2 * sin(ptsl[[2]]), (maxY-r2) + r2 * cos(ptsl[[2]])) xy_3 <- cbind( (maxX-r2) + r2 * sin(ptsl[[3]]), (minY+r2) + r2 * cos(ptsl[[3]])) xy_4 <- cbind( (minX+r2) + r2 * sin(ptsl[[4]]), (minY+r2) + r2 * cos(ptsl[[4]])) xy_7 <- cbind( (halfXModMinus-r2) + r2 * sin(ptsl[[2]]), (maxY-r2) + r2 * cos(ptsl[[2]])) xy_8 <- cbind( (halfXModPlus +r2) + r2 * sin(ptsl[[1]]), (maxY-r2) + r2 * cos(ptsl[[1]])) xy_11 <- cbind( (halfXModMinus+ xModifier) + xModifier * sin(ptsl[[4]]), (minY+(xModifier*2)) + xModifier * cos(ptsl[[4]])) xy_12 <- cbind( (halfXModPlus - xModifier) + xModifier * sin(ptsl[[3]]), (minY+(xModifier*2)) + xModifier * cos(ptsl[[3]])) RoundedSAChrtx[[counter]] <- c(rep(maxX,2) ,xy_3[,1] ,topBotline_x[2:1] ,xy_4[,1] ,rep(minX,2) ,xy_1[,1],topBotline_x2[4:3] ,xy_7[,1], halfXModMinus,halfXModMinus ,rev(xy_11[,1]) ,rev(xy_12[,1]) ,rep(halfXModPlus,2) ,xy_8[,1] ,topBotline_x2[1:2] ,xy_2[,1] ) RoundedSAChrty[[counter]] <- c(yMod[1:2] , xy_3[,2] , bottomline_y , xy_4[,2] ,yMod[2:1] ,xy_1[,2] ,rep(maxY,2) ,xy_7[,2], yMod[1], minY+(xModifier*2) ,rev(xy_11[,2]),rev(xy_12[,2]) ,c(minY+(xModifier*2),yMod[1]) ,xy_8[,2], rep(maxY,2),xy_2[,2] ) RoundedSAChrty[[counter]][which(RoundedSAChrty[[counter]]>maxY)]<-maxY r2<-r2backup } chrtXchrtYSARo<-list() chrtXchrtYSARo$RoundedSAChrtx<-RoundedSAChrtx chrtXchrtYSARo$RoundedSAChrty<-RoundedSAChrty return(chrtXchrtYSARo) } mapXYchromatidLARo <- function(start,end,y,x,r2,xModifier,pts){ RoundedLAChrtx<-RoundedLAChrty<-list() for (counter in start: end ) { maxX<-minX<-halfX<-halfXModMinus<-halfXModPlus <- NULL maxX <- max(x[[counter]]) minX <- min(x[[counter]]) maxY <- max(y[[counter]]) minY <- min(y[[counter]]) halfX <- (maxX+minX)/2 halfXModPlus <- halfX + xModifier halfXModMinus <- halfX - xModifier r2backup<-r2 diffx<-maxX - minX diffy<-maxY - minY ratexy<-diffx/diffy ifelse( (diffx/r2) * 2 < ratexy*4 , r2 <- diffx/(ratexy*2) ,r2 ) yMod<-y[[counter]] yMod[which(yMod==max(yMod))] <- yMod[which(yMod==max(yMod))]-r2 yMod[which(yMod==min(yMod))] <- yMod[which(yMod==min(yMod))]+r2 topBotline_x <- c(minX+r2, maxX-r2) topBotline_x2 <- c(halfXModPlus + r2, maxX-r2, halfXModMinus-r2,minX+r2) bottomline_y <-rep(minY,2) ptsl<-split(pts, sort(rep(1:4, each=length(pts)/4, len=length(pts))) ) xy_1 <- cbind( (minX+r2) + r2 * sin(ptsl[[1]]), (maxY-r2) + r2 * cos(ptsl[[1]])) xy_2 <- cbind( (maxX-r2) + r2 * sin(ptsl[[2]]), (maxY-r2) + r2 * cos(ptsl[[2]])) xy_3 <- cbind( (maxX-r2) + r2 * sin(ptsl[[3]]), (minY+r2) + r2 * cos(ptsl[[3]])) xy_4 <- cbind( (minX+r2) + r2 * sin(ptsl[[4]]), (minY+r2) + r2 * cos(ptsl[[4]])) xy_5 <- cbind( (halfXModPlus +r2) + r2 * sin(ptsl[[4]]), (minY+r2) + r2 * cos(ptsl[[4]])) xy_6 <- cbind( (halfXModMinus-r2) + r2 * sin(ptsl[[3]]), (minY+r2) + r2 * cos(ptsl[[3]])) xy_9 <- cbind( (halfXModPlus - xModifier) + xModifier * sin(ptsl[[2]]), (maxY-(xModifier*2)) + xModifier * cos(ptsl[[2]])) xy_10 <- cbind( (halfXModMinus+ xModifier) + xModifier * sin(ptsl[[1]]), (maxY-(xModifier*2)) + xModifier * cos(ptsl[[1]])) RoundedLAChrtx[[counter]] <- c(rep(maxX,2) ,xy_3[,1] ,topBotline_x2[2:1] ,xy_5[,1] ,halfXModPlus ,rev(xy_9[,1]),rev(xy_10[,1]) ,halfXModMinus ,halfXModMinus ,xy_6[,1], topBotline_x2[3:4],xy_4[,1],rep(minX,2) ,xy_1[,1],topBotline_x,xy_2[,1] ) RoundedLAChrty[[counter]] <- c(yMod[1:2] ,xy_3[,2] ,bottomline_y[1:2] ,xy_5[,2] ,maxY-(xModifier*2) ,rev(xy_9[,2]),rev(xy_10[,2]) ,maxY-(xModifier*2) ,yMod[2] ,xy_6[,2], rep(minY,2), xy_4[,2], yMod[2:1], xy_1[,2],rep(maxY,2) ,xy_2[,2] ) RoundedLAChrty[[counter]][which(RoundedLAChrty[[counter]]<minY)]<-minY r2<-r2backup } chrtXchrtYLARo<-list() chrtXchrtYLARo$RoundedLAChrtx<-RoundedLAChrtx chrtXchrtYLARo$RoundedLAChrty<-RoundedLAChrty return(chrtXchrtYLARo) } mapXYchromatidHoloRo <- function(start,end,y,x,r2, xModifier,pts ){ holoRightx<-holoLeftx<-holoRighty<-holoLefty<-list() for (counter in start: end ) { maxX<-minX<-halfX<-halfXModMinus<-halfXModPlus<-NULL maxX <- max(x[[counter]]) minX <- min(x[[counter]]) maxY <- max(y[[counter]]) minY <- min(y[[counter]]) diffx<-maxX - minX diffy<-maxY - minY ratexy<-diffx/diffy ifelse( (diffx/r2) * 2 < ratexy*4 , r2 <- diffx/(ratexy*2) ,r2 ) yMod<-y[[counter]] yMod[which(yMod==max(yMod))] <- yMod[which(yMod==max(yMod))]-r2 yMod[which(yMod==min(yMod))] <- yMod[which(yMod==min(yMod))]+r2 halfX <- (maxX+minX)/2 halfXModPlus <- halfX + xModifier halfXModMinus <- halfX - xModifier topBotline_x2 <- c(halfXModPlus + r2, maxX-r2, halfXModMinus-r2,minX+r2) bottomline_y <-rep(minY,2) ptsl<-split(pts, sort(rep(1:4, each=length(pts)/4, len=length(pts))) ) xy_1 <- cbind( (minX+r2) + r2 * sin(ptsl[[1]]), (maxY-r2) + r2 * cos(ptsl[[1]])) xy_2 <- cbind( (maxX-r2) + r2 * sin(ptsl[[2]]), (maxY-r2) + r2 * cos(ptsl[[2]])) xy_3 <- cbind( (maxX-r2) + r2 * sin(ptsl[[3]]), (minY+r2) + r2 * cos(ptsl[[3]])) xy_4 <- cbind( (minX+r2) + r2 * sin(ptsl[[4]]), (minY+r2) + r2 * cos(ptsl[[4]])) xy_5 <- cbind( (halfXModPlus +r2) + r2 * sin(ptsl[[4]]), (minY+r2) + r2 * cos(ptsl[[4]])) xy_6 <- cbind( (halfXModMinus-r2) + r2 * sin(ptsl[[3]]), (minY+r2) + r2 * cos(ptsl[[3]])) xy_7 <- cbind( (halfXModMinus-r2) + r2 * sin(ptsl[[2]]), (maxY-r2) + r2 * cos(ptsl[[2]])) xy_8 <- cbind( (halfXModPlus +r2) + r2 * sin(ptsl[[1]]), (maxY-r2) + r2 * cos(ptsl[[1]])) holoRightx[[counter]]<-c(rep(maxX,2),xy_3[,1],topBotline_x2[1:2],xy_5[,1] ,halfXModPlus,halfXModPlus ,xy_8[,1], topBotline_x2[2:1],xy_2[,1] ) holoRighty[[counter]]<-c(yMod[1:2],xy_3[,2],bottomline_y, xy_5[,2] ,yMod[3:4] ,xy_8[,2], rep(maxY,2),xy_2[,2] ) holoLeftx[[counter]]<-c(rep(halfXModMinus,2),xy_6[,1],topBotline_x2[3:4], xy_4[,1],rep(minX,2), xy_1[,1],topBotline_x2[4:3],xy_7[,1] ) holoLefty[[counter]]<-c(yMod[1:2], xy_6[,2],bottomline_y, xy_4[,2],yMod[3:4], xy_1[,2],rep(maxY,2), xy_7[,2] ) } chrtXchrtYHoloRo<-list() chrtXchrtYHoloRo$holoRightx<-holoRightx chrtXchrtYHoloRo$holoLeftx<-holoLeftx chrtXchrtYHoloRo$holoRighty<-holoRighty chrtXchrtYHoloRo$holoLefty<-holoLefty return(chrtXchrtYHoloRo) } mapXYmarksRo <- function(start,end,y,x,r2, xModifier,pts ) { markRightx<-markLeftx<-markRighty<-markLefty<-list() for (counter in start: end ) { if( attr(y[[counter]],"wholeArm")=='false' ) { maxX<-minX<-halfX<-halfXModMinus<-halfXModPlus<-NULL maxX <- max(x[[counter]]) minX <- min(x[[counter]]) maxY <- max(y[[counter]]) minY <- min(y[[counter]]) r2backup<-r2 diffx<-maxX - minX diffy<-maxY - minY ratexy<-diffx/diffy ifelse( (diffx/r2) * 2 < ratexy*4 , r2 <- diffx/(ratexy*2) ,r2 ) yMod<-y[[counter]] yMod[which(yMod==max(yMod))] <- yMod[which(yMod==max(yMod))]-r2 yMod[which(yMod==min(yMod))] <- yMod[which(yMod==min(yMod))]+r2 halfX <- (maxX+minX)/2 halfXModPlus <- halfX + xModifier halfXModMinus <- halfX - xModifier topBotline_x2 <- c(halfXModPlus + r2, maxX-r2, halfXModMinus-r2,minX+r2) bottomline_y <-rep(minY,2) ptsl<-split(pts, sort(rep(1:4, each=length(pts)/4, len=length(pts))) ) xy_1 <- cbind( (minX+r2) + r2 * sin(ptsl[[1]]), (maxY-r2) + r2 * cos(ptsl[[1]])) xy_2 <- cbind( (maxX-r2) + r2 * sin(ptsl[[2]]), (maxY-r2) + r2 * cos(ptsl[[2]])) xy_3 <- cbind( (maxX-r2) + r2 * sin(ptsl[[3]]), (minY+r2) + r2 * cos(ptsl[[3]])) xy_4 <- cbind( (minX+r2) + r2 * sin(ptsl[[4]]), (minY+r2) + r2 * cos(ptsl[[4]])) xy_5 <- cbind( (halfXModPlus +r2) + r2 * sin(ptsl[[4]]), (minY+r2) + r2 * cos(ptsl[[4]])) xy_6 <- cbind( (halfXModMinus-r2) + r2 * sin(ptsl[[3]]), (minY+r2) + r2 * cos(ptsl[[3]])) xy_7 <- cbind( (halfXModMinus-r2) + r2 * sin(ptsl[[2]]), (maxY-r2) + r2 * cos(ptsl[[2]])) xy_8 <- cbind( (halfXModPlus +r2) + r2 * sin(ptsl[[1]]), (maxY-r2) + r2 * cos(ptsl[[1]])) markRightx[[counter]]<-c(rep(maxX,2),xy_3[,1],topBotline_x2[1:2],xy_5[,1] ,halfXModPlus,halfXModPlus ,xy_8[,1], topBotline_x2[2:1],xy_2[,1] ) markRighty[[counter]]<-c(yMod[1:2],xy_3[,2],bottomline_y, xy_5[,2] ,yMod[3:4] ,xy_8[,2], rep(maxY,2),xy_2[,2] ) markLeftx[[counter]]<-c(rep(halfXModMinus,2),xy_6[,1],topBotline_x2[3:4], xy_4[,1],rep(minX,2), xy_1[,1],topBotline_x2[4:3],xy_7[,1] ) markLefty[[counter]]<-c(yMod[1:2], xy_6[,2],bottomline_y, xy_4[,2],yMod[3:4], xy_1[,2],rep(maxY,2), xy_7[,2] ) r2<-r2backup } else { if( attr(y[[counter]],"whichArm")=='short' ) { maxX<-minX<-halfX<-halfXModMinus<-halfXModPlus<-NULL maxX <- max(x[[counter]]) minX <- min(x[[counter]]) maxY <- max(y[[counter]]) minY <- min(y[[counter]]) halfX <- (maxX+minX)/2 halfXModPlus <- halfX + xModifier halfXModMinus <- halfX - xModifier r2backup<-r2 diffx<-maxX - minX diffy<-maxY - minY ratexy<-diffx/diffy ifelse( (diffx/r2) * 2 < ratexy*4 , r2 <- diffx/(ratexy*2) ,r2 ) yMod<-y[[counter]] yMod[which(yMod==max(yMod))] <- yMod[which(yMod==max(yMod))]-r2 yMod[which(yMod==min(yMod))] <- yMod[which(yMod==min(yMod))]+r2 topBotline_x<-c(minX+r2, maxX-r2) topBotline_x2 <- c(halfXModPlus + r2, maxX-r2, halfXModMinus-r2,minX+r2) bottomline_y <-rep(minY,2) ptsl<-split(pts, sort(rep(1:4, each=length(pts)/4, len=length(pts))) ) xy_1 <- cbind( (minX+r2) + r2 * sin(ptsl[[1]]), (maxY-r2) + r2 * cos(ptsl[[1]])) xy_2 <- cbind( (maxX-r2) + r2 * sin(ptsl[[2]]), (maxY-r2) + r2 * cos(ptsl[[2]])) xy_3 <- cbind( (maxX-r2) + r2 * sin(ptsl[[3]]), (minY+r2) + r2 * cos(ptsl[[3]])) xy_4 <- cbind( (minX+r2) + r2 * sin(ptsl[[4]]), (minY+r2) + r2 * cos(ptsl[[4]])) xy_7 <- cbind( (halfXModMinus-r2) + r2 * sin(ptsl[[2]]), (maxY-r2) + r2 * cos(ptsl[[2]])) xy_8 <- cbind( (halfXModPlus +r2) + r2 * sin(ptsl[[1]]), (maxY-r2) + r2 * cos(ptsl[[1]])) xy_11 <- cbind( (halfXModMinus+ xModifier) + xModifier * sin(ptsl[[4]]), (minY+(xModifier*2)) + xModifier * cos(ptsl[[4]])) xy_12 <- cbind( (halfXModPlus - xModifier) + xModifier * sin(ptsl[[3]]), (minY+(xModifier*2)) + xModifier * cos(ptsl[[3]])) markRightx[[counter]] <- c(rep(maxX,2),xy_3[,1] , topBotline_x[2:1],xy_4[,1],rep(minX,2),xy_1[,1],topBotline_x2[4:3] ,xy_7[,1], halfXModMinus,halfXModMinus ,rev(xy_11[,1]),rev(xy_12[,1]) , rep(halfXModPlus,2) ,xy_8[,1], topBotline_x2[2:1],xy_2[,1] ) markRighty[[counter]] <- c(yMod[1:2], xy_3[,2] , bottomline_y, xy_4[,2],yMod[2:1],xy_1[,2],rep(maxY,2) ,xy_7[,2], yMod[1], minY+(xModifier*2) ,rev(xy_11[,2]),rev(xy_12[,2]) ,c(minY+(xModifier*2),yMod[1]) ,xy_8[,2], rep(maxY,2),xy_2[,2] ) markLeftx[[counter]]<-NA markLefty[[counter]]<-NA r2<-r2backup } else { maxX<-minX<-halfX<-halfXModMinus<-halfXModPlus <- NULL maxX <- max(x[[counter]]) minX <- min(x[[counter]]) maxY <- max(y[[counter]]) minY <- min(y[[counter]]) halfX <- (maxX+minX)/2 halfXModPlus <- halfX + xModifier halfXModMinus <- halfX - xModifier r2backup<-r2 diffx<-maxX - minX diffy<-maxY - minY ratexy<-diffx/diffy ifelse( (diffx/r2) * 2 < ratexy*4 , r2 <- diffx/(ratexy*2) ,r2 ) yMod<-y[[counter]] yMod[which(yMod==max(yMod))] <- yMod[which(yMod==max(yMod))]-r2 yMod[which(yMod==min(yMod))] <- yMod[which(yMod==min(yMod))]+r2 topBotline_x <- c(minX+r2, maxX-r2) topBotline_x2 <- c(halfXModPlus + r2, maxX-r2, halfXModMinus-r2,minX+r2) bottomline_y <- rep(minY,2) ptsl<-split(pts, sort(rep(1:4, each=length(pts)/4, len=length(pts))) ) xy_1 <- cbind( (minX+r2) + r2 * sin(ptsl[[1]]), (maxY-r2) + r2 * cos(ptsl[[1]])) xy_2 <- cbind( (maxX-r2) + r2 * sin(ptsl[[2]]), (maxY-r2) + r2 * cos(ptsl[[2]])) xy_3 <- cbind( (maxX-r2) + r2 * sin(ptsl[[3]]), (minY+r2) + r2 * cos(ptsl[[3]])) xy_4 <- cbind( (minX+r2) + r2 * sin(ptsl[[4]]), (minY+r2) + r2 * cos(ptsl[[4]])) xy_5 <- cbind( (halfXModPlus +r2) + r2 * sin(ptsl[[4]]), (minY+r2) + r2 * cos(ptsl[[4]])) xy_6 <- cbind( (halfXModMinus-r2) + r2 * sin(ptsl[[3]]), (minY+r2) + r2 * cos(ptsl[[3]])) xy_9 <- cbind( (halfXModPlus - xModifier) + xModifier * sin(ptsl[[2]]), (maxY-(xModifier*2)) + xModifier * cos(ptsl[[2]])) xy_10 <- cbind( (halfXModMinus+ xModifier) + xModifier * sin(ptsl[[1]]), (maxY-(xModifier*2)) + xModifier * cos(ptsl[[1]])) markRightx[[counter]] <- c(rep(maxX,2),xy_3[,1] , topBotline_x2[1:2],xy_5[,1],halfXModPlus, rev(xy_9[,1]),rev(xy_10[,1]) ,halfXModMinus, halfXModMinus ,xy_6[,1], topBotline_x2[3:4],xy_4[,1],rep(minX,2),xy_1[,1],topBotline_x,xy_2[,1] ) markRighty[[counter]] <- c(yMod[1:2], xy_3[,2] , bottomline_y[1:2],xy_5[,2],maxY-(xModifier*2), rev(xy_9[,2]),rev(xy_10[,2]) ,maxY-(xModifier*2), yMod[2] ,xy_6[,2], rep(minY,2), xy_4[,2], yMod[2:1], xy_1[,2],rep(maxY,2) ,xy_2[,2] ) markLeftx[[counter]]<-NA markLefty[[counter]]<-NA r2<-r2backup } } attr(markLeftx[[counter]],"arm") <- attr(markLefty[[counter]],"arm") <- attr(markRightx[[counter]],"arm") <- attr(markRighty[[counter]],"arm") <- attr(y[[counter]],"arm") attr(markLeftx[[counter]],"rowIndex") <- attr(markLefty[[counter]],"rowIndex") <- attr(markRightx[[counter]],"rowIndex") <- attr(markRighty[[counter]],"rowIndex") <- attr(y[[counter]],"rowIndex") attr(markLeftx[[counter]],"wholeArm") <- attr(markLefty[[counter]],"wholeArm") <- attr(markRightx[[counter]],"wholeArm") <- attr(markRighty[[counter]],"wholeArm") <- attr(y[[counter]],"wholeArm") attr(markLeftx[[counter]],"whichArm") <- attr(markLefty[[counter]],"whichArm") <- attr(markRightx[[counter]],"whichArm") <- attr(markRighty[[counter]],"whichArm") <- attr(y[[counter]],"whichArm") attr(markLeftx[[counter]],"squareSide") <- attr(markLefty[[counter]],"squareSide") <- attr(markRightx[[counter]],"squareSide") <- attr(markRighty[[counter]],"squareSide") <- attr(y[[counter]],"squareSide") } chrtXchrtYmarkRo<-list() chrtXchrtYmarkRo$markRightx<-markRightx chrtXchrtYmarkRo$markRighty<-markRighty chrtXchrtYmarkRo$markLeftx <-markLeftx chrtXchrtYmarkRo$markLefty <-markLefty return(chrtXchrtYmarkRo) } makeRoundCoordXY <- function(r2, yfactor, x, y, start, end, n, ptsl) { xyCoords <- mapXY(1 , (length(y) ) , y, y , x, yfactor,r2, ptsl[[1]],ptsl[[2]],ptsl[[3]],ptsl[[4]] ) return(xyCoords) }
mvnintGHKOcpp_R <- function(mu, R, lower, upper, nrep){ .Call('mvnintGHKOcpp', PACKAGE = 'gcKrig', mu, R, lower, upper, nrep) } mvnintGHKcpp_R <- function(mu, R, lower, upper, nrep){ .Call('mvnintGHKcpp', PACKAGE = 'gcKrig', mu, R, lower, upper, nrep) } mvnintGHK <- function(mean, sigma, lower, upper, nrep = 5000, log = TRUE, reorder = TRUE){ if(!is.matrix(sigma)) stop("Input 'sigma' must be of form matrix!") if(!isSymmetric(sigma)) stop("Input covariance matrix 'sigma' must be symmetric!") if(length(lower)== 1 & lower[1] == -Inf) lower <- rep(-.Machine$double.xmax, nrow(sigma)) if(length(upper)== 1 & upper[1] == Inf) upper <- rep(.Machine$double.xmax, nrow(sigma)) if( inherits(try(chol(sigma),silent=TRUE),"try-error") ) stop("Cholesky Decomposition failed. Input matrix sigma is not a valid covariance matrix!") if(!all.equal(length(mean), nrow(sigma), length(lower), length(upper))) stop("Input 'mean', lower' and 'upper' must have same length as dimension of the sigma!") lower <- ifelse(lower == -Inf, -.Machine$double.xmax, lower) upper <- ifelse(upper == Inf, .Machine$double.xmax, upper) if(!all(lower <= upper)) stop("Elements in 'lower' must be <= the corresponding elements in 'upper'!") if(reorder == TRUE){ ans <- mvnintGHKOcpp_R(mu = mean, R = sigma, lower = lower, upper = upper, nrep = nrep) }else{ ans <- mvnintGHKcpp_R(mu = mean, R = sigma, lower = lower, upper = upper, nrep = nrep) } if(ans$value < -.Machine$double.max.exp) stop("Computation Failed Due to Numerical Problem or Large Dimensionality!") if(log == F) ans$value <- exp(ans$value) return(ans) }
monoreg.rowwise <- function(yM, wM) { yM <- as.matrix(yM) wM <- as.matrix(wM) res <- sirt_rcpp_monoreg_rowwise( YM=yM, WM=wM ) return(res) }
cens.p <- function(family = "NO", type = c( "right", "left", "interval"),...) { type <- match.arg(type) if (type=="counting") stop(paste("gamlss has no not support counting")) fname <- family if (mode(family) != "character" && mode(family) != "name") fname <- as.character(substitute(family)) distype <- eval(call(family))$type dfun <- paste("d",fname,sep="") pfun <- paste("p",fname,sep="") pdf <- eval(parse(text=dfun)) cdf <- eval(parse(text=pfun)) fun <- if (type=="left") function(q, log = FALSE, ...) { if (!is.Surv(q)) stop(paste("the q variable is not a Surv object")) pfun1 <- cdf(q[,1],...) pfun2 <- runif(length(q[,1]),0,pfun1) pfun <- ifelse(q[,"status"]==1, pfun1,pfun2) pfun } else if (type=="right") function(q, log = FALSE, ...) { if (!is.Surv(q)) stop(paste("the q variable is not a Surv object")) pfun1 <- cdf(q[,1],...) pfun2 <- runif(length(q[,1]),pfun1,1) pfun <- ifelse(q[,"status"]==1, pfun1,pfun2) pfun } else if (type=="interval") function(q, log = FALSE, ...) { if (!is.Surv(q)) stop(paste("the q variable is not a Surv object")) pfun1 <- cdf(q[,1],...) pfun2 <- runif(length(q[,1]),0,pfun1) pfun0 <- runif(length(q[,1]),pfun1,1) suppressWarnings(pfun3<-runif( length(q[,1]), cdf(q[,1],...), cdf(q[,2],...) ) ) pfun0 <-ifelse(q[,"status"]==0, pfun0,0) pfun1 <-ifelse(q[,"status"]==1, pfun1,0) pfun2 <-ifelse(q[,"status"]==2, pfun2,0) pfun3 <-ifelse(q[,"status"]==3, pfun3,0) dfun <- pfun0+pfun1+pfun2+pfun3 dfun } fun }
makeRLearner.regr.slim = function() { makeRLearnerRegr( cl = "regr.slim", package = "flare", par.set = makeParamSet( makeNumericVectorLearnerParam(id = "lambda"), makeIntegerLearnerParam(id = "nlambda", default = 5L, lower = 1L), makeNumericLearnerParam(id = "lambda.min.value", lower = 0, upper = 1), makeNumericLearnerParam(id = "lambda.min.ratio", lower = 0, upper = 1), makeNumericLearnerParam(id = "rho", default = 1, lower = 0), makeDiscreteLearnerParam(id = "method", values = c("lq", "dantzig", "lasso"), default = "lq"), makeNumericLearnerParam(id = "q", lower = 1, upper = 2, requires = quote(method == "lq")), makeLogicalLearnerParam(id = "res.sd", default = FALSE), makeNumericLearnerParam(id = "prec", default = 1e-5, lower = .Machine$double.eps), makeIntegerLearnerParam(id = "max.ite", default = 1e5L), makeLogicalLearnerParam(id = "verbose", default = FALSE, tunable = FALSE), makeIntegerLearnerParam(id = "lambda.idx", default = 3L, when = "predict") ), par.vals = list(lambda.idx = 3L), properties = "numerics", name = "Sparse Linear Regression using Nonsmooth Loss Functions and L1 Regularization", short.name = "slim", note = "`lambda.idx` has been set to `3` by default.", callees = c("slim", "predict.slim") ) } trainLearner.regr.slim = function(.learner, .task, .subset, .weights = NULL, ...) { d = getTaskData(.task, .subset, target.extra = TRUE) flare::slim(X = as.matrix(d$data), Y = d$target, ...) } predictLearner.regr.slim = function(.learner, .model, .newdata, ...) { predict(.model$learner.model, newdata = as.matrix(.newdata), ...)[[1]][, 1L] }
grnn.predict <- function(net, x) { if (class(net) != "General Regression Neural Net") stop("net needs to be a GRNN object.", call. = F) if (is.matrix(x) == F) stop("x needs to be a matrix.", call. = F) if (anyNA(x) == T) stop("NA found in x.", call. = F) if (ncol(x) != ncol(net$x)) stop("x dimension is not consistent with grnn.", call. = F) return(Reduce(c, lapply(split(x, seq(nrow(x))), function(x_) grnn.predone(net, x_)))) }
cmdscale <- function (d, k = 2, eig = FALSE, add = FALSE, x.ret = FALSE, list. = eig || add || x.ret) { if (anyNA(d)) stop("NA values not allowed in 'd'") if(!list.) { if (eig) warning( "eig=TRUE is disregarded when list.=FALSE") if(x.ret) warning("x.ret=TRUE is disregarded when list.=FALSE") } if (is.null(n <- attr(d, "Size"))) { if(add) d <- as.matrix(d) x <- as.matrix(d^2) storage.mode(x) <- "double" if ((n <- nrow(x)) != ncol(x)) stop("distances must be result of 'dist' or a square matrix") rn <- rownames(x) } else { rn <- attr(d, "Labels") x <- matrix(0, n, n) if (add) d0 <- x x[row(x) > col(x)] <- d^2 x <- x + t(x) if (add) { d0[row(x) > col(x)] <- d d <- d0 + t(d0) } } n <- as.integer(n) if(is.na(n) || n > 46340) stop("invalid value of 'n'") if((k <- as.integer(k)) > n - 1 || k < 1) stop("'k' must be in {1, 2, .. n - 1}") x <- .Call(C_DoubleCentre, x) if(add) { i2 <- n + (i <- 1L:n) Z <- matrix(0, 2L*n, 2L*n) Z[cbind(i2,i)] <- -1 Z[ i, i2] <- -x Z[i2, i2] <- .Call(C_DoubleCentre, 2*d) e <- eigen(Z, symmetric = FALSE, only.values = TRUE)$values add.c <- max(Re(e)) x <- matrix(double(n*n), n, n) non.diag <- row(d) != col(d) x[non.diag] <- (d[non.diag] + add.c)^2 x <- .Call(C_DoubleCentre, x) } e <- eigen(-x/2, symmetric = TRUE) ev <- e$values[seq_len(k)] evec <- e$vectors[, seq_len(k), drop = FALSE] k1 <- sum(ev > 0) if(k1 < k) { warning(gettextf("only %d of the first %d eigenvalues are > 0", k1, k), domain = NA) evec <- evec[, ev > 0, drop = FALSE] ev <- ev[ev > 0] } points <- evec * rep(sqrt(ev), each=n) dimnames(points) <- list(rn, NULL) if (list.) { evalus <- e$values list(points = points, eig = if(eig) evalus, x = if(x.ret) x, ac = if(add) add.c else 0, GOF = sum(ev)/c(sum(abs(evalus)), sum(pmax(evalus, 0))) ) } else points }
context("Testing robets tidiers") test_that("sw_*.robets test returns tibble with correct rows and columns.", { fit_robets <- WWWusage %>% robets::robets() test <- sw_tidy(fit_robets) expect_is(test, "tbl") expect_equal(nrow(test), 7) expect_equal(ncol(test), 2) test <- sw_glance(fit_robets) expect_is(test, "tbl") expect_equal(nrow(test), 1) expect_equal(ncol(test), 2) test <- sw_augment(fit_robets, rename_index = "date") expect_is(test, "tbl") expect_equal(nrow(test), 100) expect_equal(ncol(test), 4) expect_equal(colnames(test)[[1]], "date") test <- sw_tidy_decomp(fit_robets) expect_is(test, "tbl") expect_equal(nrow(test), 101) expect_equal(ncol(test), 4) expect_warning( USAccDeaths %>% robets() %>% sw_augment(timetk_idx = T) ) })
library(ecospace) nchar <- 9 ecospace <- create_ecospace(nchar = nchar, char.state = rep(3, nchar), char.type = rep(c("factor", "ord.fac", "ord.num"), nchar / 3)) Smax <- 50 set.seed(3142) neutral_sample <- neutral(Sseed = 5, Smax = Smax, ecospace = ecospace) head(neutral_sample, 10) set.seed(3142) Sseed = 5 redund_sample <- redundancy(Sseed = Sseed, Smax = Smax, ecospace = ecospace) unique(redund_sample) set.seed(3142) redund_sample2 <- redundancy(Sseed = Sseed, Smax = Smax, ecospace = ecospace, strength = 0.95) library(FD, quietly = TRUE) pc <- prcomp(FD::gowdis(redund_sample)) plot(pc$x, type = "n", main = paste("Redundancy model,\n", Smax, "species")) text(pc$x[,1], pc$x[,2], labels = seq(Smax), col = c(rep("red", Sseed), rep("black", 5), rep("slategray", (Smax - Sseed - 5))), pch = c(rep(19, Sseed), rep(21, (Smax - Sseed))), cex = .8) pc.r <- prcomp(FD::gowdis(redund_sample2)) plot(pc.r$x, type = "n", main = paste("Redundancy model (95% identical),\n", Smax, "species")) text(pc.r$x[,1], pc.r$x[,2], labels = seq(Smax), col = c(rep("red", Sseed), rep("black", 5), rep("slategray", (Smax - Sseed - 5))), pch = c(rep(19, Sseed), rep(21, (Smax - Sseed))), cex = .8) set.seed(3142) Sseed = 5 partS_sample <- partitioning(Sseed = Sseed, Smax = Smax, ecospace = ecospace) set.seed(3142) Sseed = 5 partR_sample <- partitioning(Sseed = Sseed, Smax = Smax, ecospace = ecospace, rule = "relaxed") pc.ps <- prcomp(FD::gowdis(partS_sample)) plot(pc.ps$x, type = "n", main = paste("'Strict' partitioning model,\n", Smax, "species")) text(pc.ps$x[,1], pc$x[,2], labels = seq(Smax), col = c(rep("red", Sseed), rep("black", 5), rep("slategray", (Smax - Sseed - 5))), pch = c(rep(19, Sseed), rep(21, (Smax - Sseed))), cex = .8) pc.pr <- prcomp(FD::gowdis(partR_sample)) plot(pc.pr$x, type = "n", main = paste("'Relaxed' partitioning model,\n", Smax, "species")) text(pc.pr$x[,1], pc.pr$x[,2], labels = seq(Smax), col = c(rep("red", Sseed), rep("black", 5), rep("slategray", (Smax - Sseed - 5))), pch = c(rep(19, Sseed), rep(21, (Smax - Sseed))), cex = .8) set.seed(3142) Sseed = 5 exp_sample <- expansion(Sseed = Sseed, Smax = Smax, ecospace = ecospace) pc.e <- prcomp(FD::gowdis(exp_sample)) plot(pc.e$x, type = "n", main = paste("Expansion model,\n", Smax, "species")) text(pc.e$x[,1], pc$x[,2], labels = seq(Smax), col = c(rep("red", Sseed), rep("black", 5), rep("slategray", (Smax - Sseed - 5))), pch = c(rep(19, Sseed), rep(21, (Smax - Sseed))), cex = .8) library(vegan, quietly = TRUE) start <- neutral_sample[1:Sseed,] neu <- neutral_sample[(Sseed + 1):Smax,] red <- redund_sample2[(Sseed + 1):Smax,] par <- partR_sample[(Sseed + 1):Smax,] exp <- exp_sample[(Sseed + 1):Smax,] nmds.data <- rbind(start, neu, red, par, exp) all <- metaMDS(gowdis(nmds.data), zerodist = "add", k = 2, trymax = 10) plot(all$points[,1], all$points[,2], col = c(rep("red", Sseed), rep("orange", nrow(neu)), rep("red", nrow(red)), rep("blue", nrow(par)), rep("purple", nrow(exp))), pch = c(rep(19, Sseed), rep(21, nrow(neu)), rep(22, nrow(red)), rep(23, nrow(par)), rep(24, nrow(exp))), main = paste("Combined models,\n", Smax, "species per model"), xlab = "Axis 1", ylab = "Axis 2", cex = 2, cex.lab = 1.5, lwd = 1) leg.txt <- c("seed", "neutral", "redundancy", "partitioning", "expansion") leg.col <- c("red", "orange", "red", "blue", "purple") leg.pch <- c(19, 21, 22, 23, 24) legend("topright", inset = .02, legend = leg.txt, pch = leg.pch, col = leg.col, cex = .75) options(warn = -1) metrics <- calc_metrics(samples = neutral_sample, Smax = 10, Model = "Neutral") metrics options(warn = -1) metrics <- calc_metrics(samples = neutral_sample, increm = FALSE) metrics options(warn = -1) metrics <- calc_metrics(samples = neutral_sample, Smax = 10, Model = "Neutral", increm = TRUE) metrics nreps <- 1:25 n.samples <- lapply(X = nreps, FUN = neutral, Sseed = 3, Smax = 20, ecospace) n.metrics <- lapply(X = nreps, FUN = calc_metrics, samples = n.samples, Model = "neutral", Param = "NA") all <- rbind_listdf(n.metrics) means <- n.metrics[[1]] for(n in 1:20) { means[n,4:11] <- apply(all[which(all$S == means$S[n]),4:11], 2, mean, na.rm = TRUE) } par(mfrow = c(2,4), mar = c(4, 4, 1, .3)) attach(all) plot(S, H, type = "p", cex = .75, col = "gray") lines(means$S, means$H, type = "l", lwd = 2) plot(S, D, type = "p", cex = .75, col = "gray") lines(means$S, means$D, type = "l", lwd = 2) plot(S, M, type = "p", cex = .75, col = "gray") lines(means$S, means$M, type = "l", lwd = 2) plot(S, V, type = "p", cex = .75, col = "gray") lines(means$S, means$V, type = "l", lwd = 2) plot(S, FRic, type = "p", cex = .75, col = "gray") lines(means$S, means$FRic, type = "l", lwd = 2) plot(S, FEve, type = "p", cex = .75, col = "gray") lines(means$S, means$FEve, type = "l", lwd = 2) plot(S, FDiv, type = "p", cex = .75, col = "gray") lines(means$S, means$FDiv, type = "l", lwd = 2) plot(S, FDis, type = "p", cex = .75, col = "gray") lines(means$S, means$FDis, type = "l", lwd = 2)
QUV1_fair <- function(method_in) { metd <- NULL machine_df <- data.frame('tool' = 'Exposure Chamber', 'modi' = 'QUV1', 'pers' = 'Kunal') total_time_in <- 65000 step_time_in <- "0:30" total_time_out <- 65023 step_time_out <- "0:28" method_df <- data.frame('metd' = c('hot-quv', 'cyclic-quv'), 'temp' = c('static', 'cyclic')) specific_method <- method_df %>% dplyr::filter(metd == method_in) QUV1_metadata <- glue::glue(tmp_QUV1, .open = '<<', .close = '>>') return(QUV1_metadata) }
na.warn <- function(object) { missing <- sum(!stats::complete.cases(object)) if (missing > 0) { warning("Dropping ", missing, " rows with missing values", call. = FALSE) } stats::na.exclude(object) }
expected_dist(1,5,metric="kendall") expected_dist(2,6,metric="cayley") expected_dist(1.5,7,metric="hamming") expected_dist(5,30,"ulam") expected_dist(3.5,45,"footrule") expected_dist(4,10,"spearman")
context("test-crime-at-location") test_that("crime at location", { skip_on_cran() x <- ukc_crime_location(lat = 52, lng = 0) expect_true(length(x) == 13) y <- ukc_crime_location(location = 802171) expect_error(ukc_crime_location()) expect_error(ukc_crime_location(lat = 52, lng = c(0, 0.5))) poly_df_3 <- data.frame( lat = c(52.268, 52.794, 52.130), lng = c(0.543, 0.238, 0.478) ) z <- ukc_crime_poly(poly_df_3, date = "2020-01") expect_s3_class(z, "data.frame") expect_true("anti-social-behaviour" %in% z$category) crime_loc <- ukc_crime_loc(883407, date = "2019-11") expect_s3_class(crime_loc, "data.frame") crime_coord <- ukc_crime_coord(52.1, 0.23, date = "2019-12") expect_s3_class(crime_coord, "data.frame") expect_error(ukc_stop_search_loc(ukc_crime_loc)) expect_error( ukc_crime_coord(c(51, 52), c(1, 2)) ) })
panMatrix <- function(clustering){ gids <- str_extract(names(clustering), "GID[0-9]+") ugids <- sort(unique(gids)) uclst <- sort(unique(clustering)) pan.matrix <- matrix(0, nrow = length(ugids), ncol = length(uclst)) rownames(pan.matrix) <- ugids colnames(pan.matrix) <- str_c("Cluster", uclst) for(i in 1:length(ugids)){ tb <- table(clustering[gids == ugids[i]]) idd <- as.numeric(names(tb)) idx <- which(uclst %in% idd) pan.matrix[i,idx] <- tb } attr(pan.matrix, "clustering") <- clustering return(pan.matrix) }
NULL globalaccelerator <- function(config = list()) { svc <- .globalaccelerator$operations svc <- set_config(svc, config) return(svc) } .globalaccelerator <- list() .globalaccelerator$operations <- list() .globalaccelerator$metadata <- list( service_name = "globalaccelerator", endpoints = list("*" = list(endpoint = "globalaccelerator.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "globalaccelerator.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "globalaccelerator.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "globalaccelerator.{region}.sc2s.sgov.gov", global = FALSE)), service_id = "Global Accelerator", api_version = "2018-08-08", signing_name = "globalaccelerator", json_version = "1.1", target_prefix = "GlobalAccelerator_V20180706" ) .globalaccelerator$service <- function(config = list()) { handlers <- new_handlers("jsonrpc", "v4") new_service(.globalaccelerator$metadata, handlers, config) }
expected <- eval(parse(text="structure(list(`1` = c(41L, 36L, 12L, 18L, NA, 28L, 23L, 19L, 8L, NA, 7L, 16L, 11L, 14L, 18L, 14L, 34L, 6L, 30L, 11L, 1L, 11L, 4L, 32L, NA, NA, NA, 23L, 45L, 115L, 37L), `2` = c(NA, NA, NA, NA, NA, NA, 29L, NA, 71L, 39L, NA, NA, 23L, NA, NA, 21L, 37L, 20L, 12L, 13L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), `3` = c(135L, 49L, 32L, NA, 64L, 40L, 77L, 97L, 97L, 85L, NA, 10L, 27L, NA, 7L, 48L, 35L, 61L, 79L, 63L, 16L, NA, NA, 80L, 108L, 20L, 52L, 82L, 50L, 64L, 59L), `4` = c(39L, 9L, 16L, 78L, 35L, 66L, 122L, 89L, 110L, NA, NA, 44L, 28L, 65L, NA, 22L, 59L, 23L, 31L, 44L, 21L, 9L, NA, 45L, 168L, 73L, NA, 76L, 118L, 84L, 85L), `5` = c(96L, 78L, 73L, 91L, 47L, 32L, 20L, 23L, 21L, 24L, 44L, 21L, 28L, 9L, 13L, 46L, 18L, 13L, 24L, 16L, 13L, 23L, 36L, 7L, 14L, 30L, NA, 14L, 18L, 20L)), .Names = c(\"1\", \"2\", \"3\", \"4\", \"5\"))")); test(id=0, code={ argv <- eval(parse(text="list(c(41L, 36L, 12L, 18L, NA, 28L, 23L, 19L, 8L, NA, 7L, 16L, 11L, 14L, 18L, 14L, 34L, 6L, 30L, 11L, 1L, 11L, 4L, 32L, NA, NA, NA, 23L, 45L, 115L, 37L, NA, NA, NA, NA, NA, NA, 29L, NA, 71L, 39L, NA, NA, 23L, NA, NA, 21L, 37L, 20L, 12L, 13L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 135L, 49L, 32L, NA, 64L, 40L, 77L, 97L, 97L, 85L, NA, 10L, 27L, NA, 7L, 48L, 35L, 61L, 79L, 63L, 16L, NA, NA, 80L, 108L, 20L, 52L, 82L, 50L, 64L, 59L, 39L, 9L, 16L, 78L, 35L, 66L, 122L, 89L, 110L, NA, NA, 44L, 28L, 65L, NA, 22L, 59L, 23L, 31L, 44L, 21L, 9L, NA, 45L, 168L, 73L, NA, 76L, 118L, 84L, 85L, 96L, 78L, 73L, 91L, 47L, 32L, 20L, 23L, 21L, 24L, 44L, 21L, 28L, 9L, 13L, 46L, 18L, 13L, 24L, 16L, 13L, 23L, 36L, 7L, 14L, 30L, NA, 14L, 18L, 20L), structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), .Label = c(\"1\", \"2\", \"3\", \"4\", \"5\"), class = \"factor\"))")); .Internal(split(argv[[1]], argv[[2]])); }, o=expected);
testMGD <- function( .object = NULL, .alpha = 0.05, .approach_p_adjust = "none", .approach_mgd = c("all", "Klesel", "Chin", "Sarstedt", "Keil", "Nitzl","Henseler", "CI_para","CI_overlap"), .output_type = c("complete", "structured"), .parameters_to_compare = NULL, .eval_plan = c("sequential", "multiprocess"), .handle_inadmissibles = c("replace", "drop", "ignore"), .R_permutation = 499, .R_bootstrap = 499, .saturated = FALSE, .seed = NULL, .type_ci = "CI_percentile", .type_vcv = c("indicator", "construct"), .verbose = TRUE ){ diff <- setdiff(.approach_mgd, args_default(TRUE)$.approach_mgd) if(length(diff) != 0) { stop2( "The following error occured in the testMGD() function:\n", "Unknown approach: ", paste0(diff, collapse = ", "), ".", " Possible choices are: ", paste0(args_default(TRUE)$.approach_mgd, collapse = ", ")) } .approach_mgd <- match.arg(.approach_mgd, several.ok = TRUE) .handle_inadmissibles <- match.arg(.handle_inadmissibles) .type_vcv <- match.arg(.type_vcv) .output_type <- match.arg(.output_type) if(!all(.type_ci %in% args_default(.choices = TRUE)$.type_ci )){ stop2("The specified confidence interval in .type.ci is not valid.\n", "Please choose one of the following: CI_standard_z, CI_standard_t,\n", "CI_percentile, CI_basic, CI_bc, CI_bca.") } if(!inherits(.object, "cSEMResults_multi")) { stop2( "The following error occured in the testMGD() function:\n", "At least two groups required." ) } if(any(.approach_mgd %in% c("all", "Sarstedt")) & .handle_inadmissibles == "drop"){ stop2( "The following error occured in the testMGD() function:\n", "Approach `'Sarstedt'` not supported if `.handle_inadmissibles == 'drop'`") } if(inherits(.object[[1]], "cSEMResults_2ndorder")){ model_type <- .object[[1]]$Second_stage$Information$Model$model_type } else { model_type <- .object[[1]]$Information$Model$model_type } if(any(.approach_mgd %in% c("all", "Klesel")) & model_type == "Nonlinear"){ stop2("The following error occured in the testMGD() function:\n", "The approach suggested by Klesel et al. (2019) cannot be applied", " to nonlinear models as cSEM currently can not calculate", " the model-implied VCV matrix for such models.\n", "Consider setting `.approach_mgd = c('Chin', 'Sarstedt')`") } if(sum(unlist(verify(.object))) != 0) { warning2( "The following warning occured in the testMGD() function:\n", "Initial estimation results for at least one group are inadmissible.\n", "See `verify(.object)` for details.") } if(TRUE %in% lapply(utils::combn(.object, 2, simplify = FALSE), function(x){ identical(x[[1]], x[[2]])})){ warning2( "The following warning occured in the testMGD() function:\n", "At least two groups are identical. Results may not be meaningful.") } if(any(.approach_mgd %in% c("all", "Henseler","CI_para","CI_overlap")) & !all(.approach_p_adjust %in% "none")){ warning2( "The following warning occured in the testMGD() function:\n", "Currently, there is no p-value adjustment possible for the approach suggested by\n", "Henseler (2007), CI_para, and CI_overlap. Adjustment is ignored for these approaches." ) } if(.verbose) { cat(rule2("Several tests for multi-group comparisons", type = 3), "\n\n") } .alpha <- .alpha[order(.alpha)] names_all_param <- getParameterNames(.object, .model = .parameters_to_compare) if(!is.null(names_all_param$names_cor_measurement_error)|!is.null(names_all_param$names_cor_indicator)){ stop2("The following error occured in the testMGD() function:\n", "Currenlty it is not allowed to compare measurement error covariance", " and/or indicator covariances across groups.") } names_param <- unlist(names_all_param) teststat <- list() if(any(.approach_mgd %in% c("all", "Klesel"))) { fit <- fit(.object = .object, .saturated = .saturated, .type_vcv = .type_vcv) temp <- c( "dG" = calculateDistance(.matrices = fit, .distance = "geodesic"), "dL" = calculateDistance(.matrices = fit, .distance = "squared_euclidian") ) teststat[["Klesel"]] <- temp } if(any(.approach_mgd %in% c("all", "Chin"))) { teststat[["Chin"]] <- calculateParameterDifference(.object = .object, .model = .parameters_to_compare) } if(any(.approach_mgd %in% c("all", "Sarstedt", "Keil", "Nitzl", "Henseler", "CI_para","CI_overlap"))) { if(!inherits(.object, "cSEMResults_resampled")) { if(.verbose) { cat("Bootstrap cSEMResults objects ...\n\n") } .object <- resamplecSEMResults( .object = .object, .resample_method = "bootstrap", .handle_inadmissibles = .handle_inadmissibles, .R = .R_bootstrap, .seed = .seed, .eval_plan = .eval_plan ) } bootstrap_results <- lapply(.object, function(y) { if(inherits(.object, "cSEMResults_2ndorder")) { x <- y$Second_stage$Information$Resamples$Estimates$Estimates1 nobs <- nrow(y$First_stage$Information$Data) } else { x <- y$Estimates$Estimates_resample$Estimates1 nobs <- nrow(y$Information$Data) } path_resamples <- x$Path_estimates$Resampled loading_resamples <- x$Loading_estimates$Resampled weight_resamples <- x$Weight_estimates$Resampled cor_exo_cons_resamples <- x$Exo_construct_correlation$Resampled n <- nrow(path_resamples) ses <- infer(.object=y,.quantity = "sd") path_se <- ses$Path_estimates$sd loading_se <- ses$Loading_estimates$sd weight_se <- ses$Weight_estimates$sd cor_exo_cons_se <- ses$Exo_construct_correlation$sd bias <- infer(.object=y,.quantity = "bias") path_bias <- bias$Path_estimates$bias loading_bias <- bias$Loading_estimates$bias weight_bias <- bias$Weight_estimates$bias cor_exo_cons_bias <- bias$Exo_construct_correlation$bias out<-list( "n" = n, "nObs" = nobs, "para_all" = cbind(path_resamples,loading_resamples,weight_resamples, cor_exo_cons_resamples), "ses_all" = c(path_se, loading_se, weight_se, cor_exo_cons_se), "bias_all" = c(path_bias, loading_bias, weight_bias, cor_exo_cons_bias) ) if(any(.approach_mgd %in% c("all", "CI_para", "CI_overlap"))){ diff <- setdiff(.type_ci, args_default(TRUE)$.type_ci) if(length(diff) != 0) { stop2( "The following error occured in the testMGD() function:\n", "Unknown approach: ", paste0(diff, collapse = ", "), ".", " Possible choices are: ", paste0(args_default(TRUE)$.type_ci, collapse = ", ")) } cis <- infer(.object=y, .quantity=.type_ci, .alpha = .alpha) cis_temp <- purrr::transpose(cis) cis_ret<-lapply(cis_temp,function(x){ path_ci <- x$Path_estimates loading_ci <- x$Loading_estimates weight_ci <- x$Weight_estimates cor_exo_cons_ci <- x$Exo_construct_correlation list(path_estimates = path_ci, loading_estimates = loading_ci, weight_estimates = weight_ci, cor_exo_cons_estimates = cor_exo_cons_ci) }) names(cis_ret) <- names(cis_temp) out[["ci_all"]] <- cis_ret } return(out) }) if(any(.approach_mgd %in% c("all", "Nitzl", "Keil","Henseler"))) { diff_para_Keil <- diff_para_Nitzl <- diff_para_Henseler<- calculateParameterDifference( .object = .object, .model = .parameters_to_compare ) if(any(.approach_mgd %in% c("all","Henseler"))) { temp <- rep(NA,length(unlist(diff_para_Henseler))) teststat[["Henseler"]] <-relist(flesh = temp,skeleton = diff_para_Henseler) } object_permu <- utils::combn(.object, 2, simplify = FALSE) names(object_permu) <- sapply(object_permu, function(x) paste0(names(x)[1], '_', names(x)[2])) if(any(.approach_mgd %in% c("all", "Keil"))) { teststat_Keil <- lapply(names(object_permu), function(x) { diff <- diff_para_Keil[[x]] ses1 <- bootstrap_results[[names(object_permu[[x]][1])]]$ses_all ses2 <- bootstrap_results[[names(object_permu[[x]][2])]]$ses_all n1<-bootstrap_results[[names(object_permu[[x]][1])]]$nObs n2<-bootstrap_results[[names(object_permu[[x]][2])]]$nObs ses_total <- sqrt((n1-1)^2/(n1+n2-2)*ses1^2 + (n2-1)^2/(n1+n2-2)*ses2^2)*sqrt(1/n1+1/n2) test_stat <- diff/ses_total[names(diff)] list("teststat" = test_stat, "df" = n1 + n2 - 2) }) names(teststat_Keil) <- names(object_permu) teststat[["Keil"]] <- teststat_Keil } if(any(.approach_mgd %in% c("all", "Nitzl"))) { teststat_Nitzl <- lapply(names(object_permu), function(x){ diff <- diff_para_Nitzl[[x]] ses1 <- bootstrap_results[[names(object_permu[[x]][1])]]$ses_all ses2 <- bootstrap_results[[names(object_permu[[x]][2])]]$ses_all n1<-bootstrap_results[[names(object_permu[[x]][1])]]$nObs n2<-bootstrap_results[[names(object_permu[[x]][2])]]$nObs ses_total <- sqrt((n1-1)/(n1)*ses1^2 + (n2-1)/(n2)*ses2^2) test_stat <- diff/ses_total[names(diff)] numerator <- ((n1-1)/n1*ses1^2+(n2-1)/n2*ses2^2)^2 denominator <- (n1-1)/n1^2*ses1^4+(n2-1)/n2^2*ses2^4 df <- round(numerator/denominator-2) df <- df[names(diff)] list("teststat" = test_stat, "df" = df) }) names(teststat_Nitzl) <- names(object_permu) teststat[["Nitzl"]] <- teststat_Nitzl } } if(any(.approach_mgd %in% c("all", "Sarstedt"))) { ll <- purrr::transpose(bootstrap_results) group_id <- rep(1:length(.object), unlist(ll$n)) all_comb <- cbind(do.call(rbind,ll$para_all), "group_id" = group_id) all_comb <- all_comb[, c(names_param, "group_id")] teststat[["Sarstedt"]] <- calculateFR(.resample_sarstedt = all_comb) } } if(inherits(.object, "cSEMResults_2ndorder")) { X_all_list <- lapply(.object, function(x) x$First_stage$Information$Data) arguments <- .object[[1]]$Second_stage$Information$Arguments_original } else { X_all_list <- lapply(.object, function(x) x$Information$Data) arguments <- .object[[1]]$Information$Arguments } X_all <- do.call(rbind, X_all_list) id <- rep(1:length(X_all_list), sapply(X_all_list, nrow)) arguments[[".id"]] <- "id" if(any(.approach_mgd %in% c("all", "Klesel", "Chin", "Sarstedt"))) { if(.verbose){ cat("Permutation ...\n\n") } old_seed <- .Random.seed on.exit({.Random.seed <<- old_seed}) if(is.null(.seed)) { set.seed(seed = NULL) .seed <- sample(.Random.seed, 1) } set.seed(.seed) ref_dist <- list() n_inadmissibles <- 0 counter <- 0 progressr::with_progress({ progress_bar_csem <- progressr::progressor(along = 1:.R_permutation) repeat{ counter <- counter + 1 progress_bar_csem(message = sprintf("Permutation run = %g", counter)) X_temp <- cbind(X_all, id = sample(id)) arguments[[".data"]] <- X_temp Est_temp <- do.call(csem, arguments) status_code <- sum(unlist(verify(Est_temp))) if(status_code == 0 | (status_code != 0 & .handle_inadmissibles == "ignore")) { teststat_permutation <- list() if(any(.approach_mgd %in% c("all", "Klesel"))) { fit_temp <- fit(Est_temp, .saturated = .saturated, .type_vcv = .type_vcv) temp <- c( "dG" = calculateDistance(.matrices = fit_temp, .distance = "geodesic"), "dL" = calculateDistance(.matrices = fit_temp, .distance = "squared_euclidian") ) teststat_permutation[["Klesel"]] <- temp } if(any(.approach_mgd %in% c("all", "Chin"))) { teststat_permutation[["Chin"]] <- calculateParameterDifference( .object = Est_temp, .model = .parameters_to_compare) } if(any(.approach_mgd %in% c("all", "Sarstedt"))) { all_comb_permutation <- all_comb all_comb_permutation[ , "group_id"] <- sample(group_id) teststat_permutation[["Sarstedt"]] <- calculateFR(all_comb_permutation) } ref_dist[[counter]] <- teststat_permutation } else if(status_code != 0 & .handle_inadmissibles == "drop") { ref_dist[[counter]] <- NA } else { counter <- counter - 1 n_inadmissibles <- n_inadmissibles + 1 } if(length(ref_dist) == .R_permutation) { break } else if(counter + n_inadmissibles == 10000) { stop("Not enough admissible result.", call. = FALSE) } } }) ref_dist1 <- Filter(Negate(anyNA), ref_dist) } if(any(.approach_mgd %in% c("all", "Klesel"))) { ref_dist_Klesel <- lapply(ref_dist1, function(x) x$Klesel) ref_dist_matrix_Klesel <- do.call(cbind, ref_dist_Klesel) teststat_Klesel <- teststat$Klesel pvalue_Klesel <- rowMeans(ref_dist_matrix_Klesel >= teststat_Klesel) decision_Klesel <- lapply(.alpha, function(x) { pvalue_Klesel > x }) names(decision_Klesel) <- paste0(.alpha * 100, "%") } if(any(.approach_mgd %in% c("all", "Chin"))) { teststat_Chin <- teststat$Chin ref_dist_Chin <- lapply(ref_dist1, function(x) x$Chin) ref_dist_Chin_temp <- purrr::transpose(ref_dist_Chin) names(ref_dist_Chin_temp) <- names(teststat_Chin) ref_dist_matrices_Chin <- lapply(ref_dist_Chin_temp, function(x) { temp <- do.call(cbind, x) temp_ind <- stats::complete.cases(temp) temp[temp_ind, ,drop = FALSE] }) pvalue_Chin <- lapply(1:length(ref_dist_matrices_Chin), function(x) { rowMeans(ref_dist_matrices_Chin[[x]] >= abs(teststat_Chin[[x]])) + rowMeans(ref_dist_matrices_Chin[[x]] <= (-abs(teststat_Chin[[x]]))) }) names(pvalue_Chin) <- names(ref_dist_matrices_Chin) padjusted_Chin <- lapply(as.list(.approach_p_adjust), function(x){ pvector <- stats::p.adjust(unlist(pvalue_Chin),method = x) relist(flesh = pvector,skeleton = pvalue_Chin) }) names(padjusted_Chin) <- .approach_p_adjust decision_Chin <- lapply(padjusted_Chin, function(adjust_approach){ temp <- lapply(.alpha, function(alpha){ lapply(adjust_approach,function(group_comp){ group_comp > alpha }) }) names(temp) <- paste0(.alpha*100, "%") temp }) decision_overall_Chin <- lapply(decision_Chin, function(decision_Chin_list){ lapply(decision_Chin_list,function(x){ all(unlist(x)) }) }) } if(any(.approach_mgd %in% c("all", "Sarstedt"))) { teststat_Sarstedt <- teststat$Sarstedt ref_dist_Sarstedt <- lapply(ref_dist1, function(x) x$Sarstedt) ref_dist_matrix_Sarstedt <- do.call(cbind, ref_dist_Sarstedt) pvalue_Sarstedt <- rowMeans(ref_dist_matrix_Sarstedt >= teststat_Sarstedt) padjusted_Sarstedt<- lapply(as.list(.approach_p_adjust), function(x){ pvector <- stats::p.adjust(pvalue_Sarstedt, method = x) }) names(padjusted_Sarstedt) <- .approach_p_adjust decision_Sarstedt <- lapply(padjusted_Sarstedt,function(p_value){ temp <- lapply(.alpha, function(alpha){ p_value > alpha }) names(temp) <- paste(.alpha*100,"%",sep= '') temp }) decision_overall_Sarstedt <- lapply(decision_Sarstedt, function(x){ lapply(x, function(xx){ all(xx) }) }) } if(any(.approach_mgd %in% c("all", "Keil"))){ pvalue_Keil <- lapply(teststat$Keil,function(x){ p_value <- 2*(1-pt(abs(x$teststat),df = x$df)) p_value }) padjusted_Keil<- lapply(as.list(.approach_p_adjust), function(x){ pvector <- stats::p.adjust(unlist(pvalue_Keil),method = x) relist(flesh = pvector,skeleton = pvalue_Keil) }) names(padjusted_Keil) <- .approach_p_adjust decision_Keil <- lapply(padjusted_Keil, function(adjust_approach){ temp <- lapply(.alpha, function(alpha){ lapply(adjust_approach,function(group_comp){ group_comp > alpha }) }) names(temp) <- paste0(.alpha*100, "%") temp }) decision_overall_Keil <- lapply(decision_Keil, function(decision_Keil_list){ lapply(decision_Keil_list,function(x){ all(unlist(x)) }) }) } if(any(.approach_mgd %in% c("all", "Nitzl"))){ pvalue_Nitzl <- lapply(teststat$Nitzl,function(x){ p_value <- 2*(1-pt(abs(x$teststat),df = x$df)) p_value }) padjusted_Nitzl<- lapply(as.list(.approach_p_adjust), function(x){ pvector <- stats::p.adjust(unlist(pvalue_Nitzl),method = x) relist(flesh = pvector,skeleton = pvalue_Nitzl) }) names(padjusted_Nitzl) <- .approach_p_adjust decision_Nitzl <- lapply(padjusted_Nitzl, function(adjust_approach){ temp <- lapply(.alpha, function(alpha){ lapply(adjust_approach,function(group_comp){ group_comp > alpha }) }) names(temp) <- paste0(.alpha*100, "%") temp }) decision_overall_Nitzl <- lapply(decision_Nitzl, function(decision_Nitzl_list){ lapply(decision_Nitzl_list,function(x){ all(unlist(x)) }) }) } if(any(.approach_mgd %in% c("all", "Henseler"))) { teststat_Henseler <- teststat$Henseler ll_centered <- lapply(bootstrap_results, function(x){ t(apply(x$para_all,1,function(row){ row-x$bias_all })) }) names(ll_centered) <- names(bootstrap_results) pairs_centered <- utils::combn(ll_centered, 2, simplify = FALSE) names(pairs_centered) <- sapply(pairs_centered, function(x) paste0(names(x)[1], '_', names(x)[2])) pvalue_Henseler <- lapply(pairs_centered,function(x){ calculatePr(.resample_centered = x, .parameters_to_compare = names_param) }) padjusted_Henseler<- lapply(as.list("none"), function(x){ pvector <- stats::p.adjust(unlist(pvalue_Henseler),method = x) relist(flesh = pvector,skeleton = pvalue_Henseler) }) names(padjusted_Henseler) <- "none" decision_Henseler <- lapply(padjusted_Henseler, function(adjust_approach){ temp <- lapply(.alpha, function(alpha){ lapply(adjust_approach,function(group_comp){ group_comp > alpha/2 & group_comp < 1- alpha/2 }) }) names(temp) <- paste0(.alpha*100, "%") temp }) decision_overall_Henseler <- lapply(decision_Henseler, function(decision_Henseler_list){ lapply(decision_Henseler_list,function(x){ all(unlist(x)) }) }) } if(any(.approach_mgd %in% c("all", "CI_para", "CI_overlap"))) { cis <- lapply(bootstrap_results,function(x){ x$ci_all }) cis_comp <- utils::combn(cis, 2, simplify = FALSE) names(cis_comp) <- sapply(cis_comp, function(x) paste0(names(x)[1], '_', names(x)[2])) param_per_group <- getRelevantParameters(.object = .object, .model = .parameters_to_compare) param_per_group <- purrr::transpose(param_per_group) param_comp <- utils::combn(param_per_group, 2, simplify = FALSE) names(param_comp) <- sapply(param_comp, function(x) paste0(names(x)[1], '_', names(x)[2])) if(any(.approach_mgd %in% c("all", "CI_para"))) { decision_ci_para <- lapply(.alpha, function(alpha) { tttt <- lapply(names(cis_comp), function(comp) { tt = lapply(names(cis_comp[[comp]][[1]]), function(interval_type){ ttt <- lapply(names(cis_comp[[comp]][[1]][[interval_type]]), function(param) { lb <- paste0(100 * (1 - alpha), "%L") ub <- paste0(100 * (1 - alpha), "%U") temp_para1 <- param_comp[[comp]][[1]][[param]] temp_cis1 <- cis_comp[[comp]][[1]][[interval_type]][[param]] temp_cis_selected1 <- temp_cis1[, names(temp_para1), drop = FALSE] lb_temp1 <-temp_cis_selected1[lb,] names(lb_temp1) <- colnames(temp_cis_selected1[lb,,drop=FALSE]) ub_temp1 <-temp_cis_selected1[ub,] names(ub_temp1) <- colnames(temp_cis_selected1[ub,,drop=FALSE]) temp_para2 <- param_comp[[comp]][[2]][[param]] temp_cis2 <- cis_comp[[comp]][[2]][[interval_type]][[param]] temp_cis_selected2 <- temp_cis2[, names(temp_para2), drop = FALSE] lb_temp2 <-temp_cis_selected2[lb,] names(lb_temp2) <- colnames(temp_cis_selected2[lb,,drop=FALSE]) ub_temp2 <-temp_cis_selected2[ub,] names(ub_temp2) <- colnames(temp_cis_selected2[ub,,drop=FALSE]) decision<- (lb_temp2 <= temp_para1 & ub_temp2 >= temp_para1) | (lb_temp1 <= temp_para2 & ub_temp1 >= temp_para2) out=data.frame("Estimate"=temp_para1,"lb"=lb_temp2, "ub"=ub_temp2,"Estimate"=temp_para2,"lb"=lb_temp1, "ub"=ub_temp1,"decision"=decision) if(nrow(out)!=0){ colnames(out)=c(paste0("Est_",names(cis_comp[[comp]])[1]), paste0("lb_",names(cis_comp[[comp]])[2]), paste0("ub_",names(cis_comp[[comp]])[2]), paste0("Est_",names(cis_comp[[comp]])[2]), paste0("lb_",names(cis_comp[[comp]])[1]), paste0("ub_",names(cis_comp[[comp]])[1]), "Decision") } out$Name <- rownames(out) out <- out[, c(ncol(out), 1:(ncol(out) -1))] rownames(out) <- NULL out }) do.call(rbind,ttt) }) names(tt) = names(cis_comp[[comp]][[1]]) tt }) names(tttt) <- names(cis_comp) tttt }) names(decision_ci_para) <- paste0((1 - .alpha) * 100, "%") decision_overall_ci_para<-lapply(names(decision_ci_para), function(alpha) { t <- lapply(names(decision_ci_para[[alpha]]), function(comp) { tt <- lapply(names(decision_ci_para[[alpha]][[comp]]),function(interval_type){ all(decision_ci_para[[alpha]][[comp]][[interval_type]][,"Decision"]) }) names(tt) <- names(decision_ci_para[[alpha]][[comp]]) tt }) names(t) <- names(decision_ci_para[[alpha]]) temp <- purrr::transpose(t) overall_dec<-lapply(names(temp),function(x){ all(unlist(temp[[x]])) }) names(overall_dec)<-names(temp) overall_dec }) names(decision_overall_ci_para) <- names(decision_ci_para) } if(any(.approach_mgd %in% c("all", "CI_overlap"))) { decision_ci_overlap <- lapply(.alpha, function(alpha) { ttt <- lapply(names(cis_comp), function(comp) { t <- lapply(names(cis_comp[[comp]][[1]]), function(interval_type) { tt <- lapply(names(cis_comp[[comp]][[1]][[interval_type]]), function(param) { lb <- paste0(100 * (1 - alpha), "%L") ub <- paste0(100 * (1 - alpha), "%U") para_rel <- names(param_comp[[comp]][[1]][[param]]) lb1 <- cis_comp[[comp]][[1]][[interval_type]][[param]][lb,para_rel ] ub1 <- cis_comp[[comp]][[1]][[interval_type]][[param]][ub,para_rel ] lb2 <- cis_comp[[comp]][[2]][[interval_type]][[param]][lb,para_rel ] ub2 <- cis_comp[[comp]][[2]][[interval_type]][[param]][ub,para_rel ] decision <- (lb2 <= lb1 & lb1 <= ub2) | (lb2 <= ub1 & ub1 <= ub2) | (lb1<=lb2 & ub1>=ub2) | (lb2<=lb1 & ub2>=ub1) out <- data.frame(lb1,ub1,lb2,ub2,decision) if(nrow(out)!=0){ colnames(out)=c(paste0("lb_",names(cis_comp[[comp]])[1]), paste0("ub_",names(cis_comp[[comp]])[1]), paste0("lb_",names(cis_comp[[comp]])[2]), paste0("ub_",names(cis_comp[[comp]])[2]), "Decision" ) out$Name <- para_rel out <- out[, c(ncol(out), 1:(ncol(out) - 1))] rownames(out) <- NULL out } out }) do.call(rbind,tt) }) names(t) <- names(cis_comp[[comp]][[1]]) t }) names(ttt) <- names(cis_comp) ttt }) names(decision_ci_overlap) <- paste0((1 - .alpha) * 100, "%") decision_overall_ci_overlap<-lapply(names(decision_ci_overlap), function(alpha) { t <- lapply(names(decision_ci_overlap[[alpha]]), function(comp) { tt <- lapply(names(decision_ci_overlap[[alpha]][[comp]]),function(interval_type){ all(decision_ci_overlap[[alpha]][[comp]][[interval_type]][,"Decision"]) }) names(tt) <- names(decision_ci_overlap[[alpha]][[comp]]) tt }) names(t) <- names(decision_ci_overlap[[alpha]]) temp <- purrr::transpose(t) overall_dec<-lapply(names(temp),function(x){ all(unlist(temp[[x]])) }) names(overall_dec)<-names(temp) overall_dec }) names(decision_overall_ci_overlap) <- names(decision_ci_overlap) } } out <- list() out[["Information"]] <- list( "Group_names" = names(.object), "Number_of_observations"= sapply(X_all_list, nrow), "Approach" = .approach_mgd, "Approach_p_adjust" = .approach_p_adjust, "Alpha" = .alpha, "Parameters_to_compare" = .parameters_to_compare) if(any(.approach_mgd %in% c("all", "Klesel", "Chin", "Sarstedt"))) { out[["Information"]][["Information_permutation"]] <- list( "Number_admissibles" = length(ref_dist1), "Total_runs" = counter + n_inadmissibles, "Permutation_seed" = .seed, "Permutation_values" = list(), "Handle_inadmissibles" = .handle_inadmissibles ) } else { out[["Information"]][["Information_permutation"]] <- list( "Number_admissibles" = NA, "Total_runs" = NA, "Permutation_seed" = NA, "Permutation_values" = NA, "Handle_inadmissibles" = NA ) } if(any(.approach_mgd %in% c("all", "Sarstedt", "Keil", "Nitzl", "Henseler", "CI_param","CI_overlap"))) { info_boot <-lapply(.object, function(x){ if(inherits(.object, "cSEMResults_2ndorder")) { x <- x$Second_stage$Information$Resamples$Information_resample } else { x <- x$Information$Information_resample } list( "Number_admissibles" = x$Number_of_admissibles, "Total_runs" = x$Number_of_runs, "Bootstrap_seed" = x$Seed, "Handle_inadmissibles" = x$Handle_inadmissibles ) }) names(info_boot) <- names(.object) info_boot <- purrr::transpose(info_boot) out[["Information"]][["Information_bootstrap"]] <- list( "Number_admissibles" = info_boot$Number_admissibles, "Total_runs" = info_boot$Total_runs, "Bootstrap_seed" = info_boot$Bootstrap_seed, "Handle_inadmissibles" = info_boot$Handle_inadmissibles ) } else { out[["Information"]][["Information_bootstrap"]] <- list( "Number_admissibles" = NA, "Total_runs" = NA, "Bootstrap_seed" = NA, "Handle_inadmissibles" = NA ) } if(any(.approach_mgd %in% c("all", "Klesel"))) { out[["Klesel"]] <- list( "Test_statistic" = teststat_Klesel, "P_value" = pvalue_Klesel, "Decision" = decision_Klesel, "VCV_type" = .type_vcv ) out[["Information"]][["Information_permutation"]][["Permutation_values"]][["Klesel"]] <- ref_dist_matrix_Klesel } if(any(.approach_mgd %in% c("all", "Chin"))) { out[["Chin"]] <- list( "Test_statistic" = teststat_Chin, "P_value" = padjusted_Chin, "Decision" = decision_Chin, "Decision_overall" = decision_overall_Chin ) out[["Information"]][["Information_permutation"]][["Permutation_values"]][["Chin"]] <- ref_dist_matrices_Chin } if(any(.approach_mgd %in% c("all", "Sarstedt"))) { out[["Sarstedt"]] <- list( "Test_statistic" = teststat_Sarstedt, "P_value" = padjusted_Sarstedt, "Decision" = decision_Sarstedt, "Decision_overall" = decision_overall_Sarstedt ) out[["Information"]][["Information_permutation"]][["Permutation_values"]][["Sarstedt"]] <- ref_dist_matrix_Sarstedt } if(any(.approach_mgd %in% c("all", "Keil"))) { out[["Keil"]] <- list( "Test_statistic" = purrr::transpose(teststat_Keil)$teststat, "P_value" = padjusted_Keil, "Decision" = decision_Keil, "Decision_overall" = decision_overall_Keil, "df" = purrr::transpose(teststat_Keil)$df[[1]] ) } if(any(.approach_mgd %in% c("all", "Nitzl"))) { out[["Nitzl"]] <- list( "Test_statistic" = purrr::transpose(teststat_Nitzl)$teststat, "P_value" = padjusted_Nitzl, "Decision" = decision_Nitzl, "Decision_overall" = decision_overall_Nitzl, "df" = purrr::transpose(teststat_Nitzl)$df[[1]] ) } if(any(.approach_mgd %in% c("all", "Henseler"))) { out[["Henseler"]] <- list( "Test_statistic" = teststat_Henseler, "P_value" = padjusted_Henseler, "Decision" = decision_Henseler, "Decision_overall" = decision_overall_Henseler ) } if(any(.approach_mgd %in% c("all", "CI_para"))) { out[["CI_para"]] <- list( "Decision" = decision_ci_para, "Decision_overall" = decision_overall_ci_para ) } if(any(.approach_mgd %in% c("all", "CI_overlap"))) { out[["CI_overlap"]] <- list( "Decision" = decision_ci_overlap, "Decision_overall" = decision_overall_ci_overlap ) } class(out) <- "cSEMTestMGD" if(.output_type == "complete") { return(out) } else { structureTestMGDDecisions(out) } }
test_that("nth", { x = 1:10 expect_equal(nth(x,1),1) expect_equal(nth(x,5),5) expect_equal(nth(x,-1),10) expect_equal(nth(x,-2),9) })
is.t <- function(x,m,a=10,n0=NULL) { p=rep(0,m+2); y=rep(0,m+2); q=0; x2=var(x); if(is.null(n0)) { n0=2*x2/(x2+1); df=m; } else { df=m+1; } if(n0>0) { di=max(x)-min(x); for(i in 1:m) { p[i]=pt(min(x)+di*i/m,n0)-pt(min(x)+di*(i-1)/m,n0); if(p[i]==0) { break; } for(j in 1:length(x)) if(x[j]>(min(x)+di*(i-1)/m) && x[j]<=(min(x)+di*i/m)) y[i]=y[i]+1; q=q+(y[i]-(length(x)*p[i]))^2/(length(x)*p[i]); } p[m+1]=pt(Inf,n0)-pt(max(x),n0); p[m+2]=pt(min(x),n0); y[m+2]=length(which(x==min(x))); if(p[m+1]!=0) q=q+(y[m+1]-(length(x)*p[m+1]))^2/(length(x)*p[m+1]); if(p[m+2]!=0) q=q+(y[m+2]-(length(x)*p[m+2]))^2/(length(x)*p[m+2]); q0=qchisq(1-a,df); pvalue=pchisq(q,df); if(q<=q0) { return(data.frame("qchisq"=q,"pvalue"=pvalue)); } else { return(data.frame("state"=-1,"pvalue"=1)); } } else { return(data.frame("state"=-1,"pvalue"=1)); } }
spss.get <- function(file, lowernames=FALSE, datevars=NULL, use.value.labels=TRUE, to.data.frame=TRUE, max.value.labels=Inf, force.single=TRUE, allow=NULL, charfactor=FALSE, reencode=NA) { w <- read.spss(file, use.value.labels=use.value.labels, to.data.frame=to.data.frame, max.value.labels=max.value.labels, reencode=reencode) a <- attributes(w) vl <- a$variable.labels nam <- a$names nam <- makeNames(a$names, unique=TRUE, allow=allow) if(lowernames) nam <- casefold(nam) names(w) <- nam lnam <- names(vl) if(length(vl)) for(i in 1:length(vl)) { n <- lnam[i] lab <- vl[i] if(lab != '' && lab != n) label(w[[i]]) <- lab } attr(w, 'variable.labels') <- NULL if(force.single || length(datevars) || charfactor) for(v in nam) { x <- w[[v]] changed <- FALSE if(v %in% datevars) { x <- importConvertDateTime(x, 'date', 'spss') changed <- TRUE } else if(all(is.na(x))) { storage.mode(x) <- 'integer' changed <- TRUE } else if(!(is.factor(x) || is.character(x))) { if(all(is.na(x))) { storage.mode(x) <- 'integer' changed <- TRUE } else if(max(abs(x),na.rm=TRUE) <= (2^31-1) && all(floor(x) == x, na.rm=TRUE)) { storage.mode(x) <- 'integer' changed <- TRUE } } else if(charfactor && is.character(x)) { if(length(unique(x)) < .5*length(x)) { x <- sub(' +$', '', x) x <- factor(x, exclude='') changed <- TRUE } } if(changed) w[[v]] <- x } w } csv.get <- function(file, lowernames=FALSE, datevars=NULL, datetimevars=NULL, dateformat='%F', fixdates=c('none','year'), comment.char = "", autodates=TRUE, allow=NULL, charfactor=FALSE, sep=',', skip=0, vnames=NULL, labels=NULL, ...){ fixdates <- match.arg(fixdates) if(length(vnames)) vnames <- scan(file, what=character(0), skip=vnames-1, nlines=1, sep=sep, quiet=TRUE) if(length(labels)) labels <- scan(file, what=character(0), skip=labels-1, nlines=1, sep=sep, quiet=TRUE) w <- if(length(vnames)) read.csv(file, check.names=FALSE, comment.char=comment.char, header=FALSE, col.names=vnames, skip=skip, sep=sep, ...) else read.csv(file, check.names=FALSE, comment.char=comment.char, sep=sep, skip=skip, ...) n <- nam <- names(w) m <- makeNames(n, unique=TRUE, allow=allow) if(length(labels)) n <- labels if(lowernames) m <- casefold(m) changed <- any(m != nam) if(changed) names(w) <- m if(autodates) { tmp <- w names(tmp) <- NULL for(i in 1:length(tmp)) { if(! is.character(tmp[[1]])) next } } cleanup.import(w, labels=if(length(labels))labels else if(changed)n else NULL, datevars=datevars, datetimevars=datetimevars, dateformat=dateformat, fixdates=fixdates, charfactor=charfactor) } stata.get <- function(file, lowernames=FALSE, convert.dates=TRUE, convert.factors=TRUE, missing.type=FALSE, convert.underscore=TRUE, warn.missing.labels=TRUE, force.single=TRUE, allow=NULL, charfactor=FALSE, ...) { convertObjs <- function(x, charfactor, force.single) { if((inherits(x, 'Date') || is.factor(x)) && storage.mode(x) != 'integer') { storage.mode(x) <- 'integer' } else if(charfactor && is.character(x)) { if(length(unique(x)) < length(x) / 2) { x <- sub(' +$', '', x) x <- factor(x, exclude='') } } else if(is.numeric(x)) { if(all(is.na(x))) { storage.mode(x) <- 'integer' } else if(force.single && max(abs(x), na.rm=TRUE) <= (2^31-1) && all(floor(x) == x, na.rm=TRUE)) { storage.mode(x) <- 'integer' } } return(x) } create.attribs <- function(var.label, val.label, format, label.table) { attribs <- list() if(format != '') { attribs$format <- format } if(var.label != '') { attribs$label <- var.label } if(val.label != '' && val.label %in% names(label.table) && !is.null(label.table[[val.label]])) { attribs$value.label.table <- label.table[[val.label]] } return(attribs) } w <- read.dta(file, convert.dates=convert.dates, convert.factors=convert.factors, missing.type=missing.type, convert.underscore=convert.underscore, warn.missing.labels=warn.missing.labels, ...) a <- attributes(w) num.vars <- length(w) nam <- makeNames(a$names, unique=TRUE, allow=allow) if(lowernames) nam <- casefold(nam, upper=FALSE) a$names <- nam if(!length(a$var.labels)) { a$var.labels <- character(num.vars) } if(length(a$val.labels)) { val.labels <- a$val.labels } else { val.labels <- character(num.vars) } attribs <- mapply(FUN=create.attribs, var.label=a$var.labels, val.label=val.labels, format=a$formats, MoreArgs=list(label.table=a$label.table), SIMPLIFY=FALSE) attr(w, 'var.labels') <- NULL w <- lapply(w, FUN=convertObjs, force.single=force.single, charfactor=charfactor) w <- unname(w) for(i in seq(along.with=w)) { if('label' %in% names(attribs[[i]])) { label(w[[i]]) <- attribs[[i]]$label attribs[[i]]$label <- NULL } consolidate(attributes(w[[i]])) <- attribs[[i]] } stata.info <- a[c('datalabel','version','time.stamp','val.labels','label.table')] attributes(w) <- c(a[c('names','row.names','class')], stata.info=list(stata.info)) return(w) }
WHInit <- function(V, ...) { I <- ncol(V); K <- nrow(V); L <- as.integer(K/2); eps <- 0.0001; H <- matrix(0, nrow=2L, ncol=I); W <- matrix(0, nrow=K, ncol=2L); rrA <- 1:L; rrB <- (L+1):K; rrBA <- c(rrB, rrA); PMA <- V[rrA,,drop=FALSE]; PMB <- V[rrB,,drop=FALSE]; H[1,] <- as.integer(colMeans(PMA > 0.5*PMB) > 0.5); H[2,] <- as.integer(colMeans(PMB > 0.5*PMA) > 0.5); summary <- 2*H[1L,] + H[2L,]; dummy <- unique(summary); status <- 0L; if (length(dummy) == 1L) { if (prod(H[,1L]) == 0) { W[,1L] <- rowMedians(V)/2; W[,2L] <- W[rrBA,1L]; H <- H*2; if (H[2L,1L] == 1){ W <- W[,c(2L,1L),drop=FALSE]; H <- H[c(2L,1L),,drop=FALSE]; } status <- 1L; } else { W[,1L] <- rowMedians(V); W[,2L] <- W[,1L]; W[rrB,1L] <- eps; W[rrA,2L] <- eps; status <- 2L; } } else { aux <- colSums(H); aux <- rep(aux, times=2L); dim(aux) <- c((length(aux)/2), 2); aux <- t(aux); H <- 2 * H/aux; H[is.na(H)] <- 0; W <- t(miqr.solve(t(H),t(V))); W[W < 0] <- eps; corDiff <- cor(W[,1L],W[rrBA,2L]) - cor(W[,1L],W[,2L]); if (is.na(corDiff) || corDiff < 0.1) { W0 <- W; W[,1L] <- rowMedians(W0); W[,2L] <- W0[rrBA,1L]; H <- miqr.solve(W, V); H[H < 0] <- 0; status <- 1L; } } stopifnot(nrow(W) == K && ncol(W) == 2L); stopifnot(nrow(H) == 2L && ncol(H) == I); list(W=W, H=H, status=status); }
MLWS<-function(X,m,epsilon=c(0.02,0.05), coint.elements=NULL, B=NULL, prewhite=c("none","uni","multi"), eta=rep(1/sqrt(min(dim(X))),min(dim(X))), rep=FALSE, approx=100, split=1, T_limdist=1000, M_limdist=5000){ epsilon<-epsilon[1] prewhite<-prewhite[1] X<-as.matrix(X) if(which.max(dim(X))==1){X<-t(X)} n<-ncol(X) q<-nrow(X) means<-apply(X,1,mean) for(a in 1:q){X[a,]<-X[a,]-means[a]} if(is.null(B)==FALSE){X<-apply(X,2,function(x){B%*%x})} if(is.null(coint.elements)){ if(prewhite!="uni"){d.est<-as.vector(GSE(X=X,m=m))} B<-diag(q) }else{ params<-as.vector(GSE_coint(X=X,m=m, elements=coint.elements)) ncoint<-length(coint.elements)-1 d.est<-as.vector(params[-(1:(ncoint))]) B<-diag(q) for(i in 1:ncoint){ B[coint.elements[1],coint.elements[(i+1)]]<--params[i] } X<-apply(X,2,function(x){B%*%x}) } eta<-as.vector(eta) if(length(eta)!=q)stop("eta must be a vector of length q.") if((prewhite%in%c("none","uni","multi"))==FALSE)stop("prewhite must be either 'none', 'uni' or 'multi'.") if(prewhite=="multi"){ if(rep==TRUE){print("Estimating VARFIMA")} theta.hat<-VARFIMA.est(data=t(X), approx=approx, split=split, rep=rep) if(rep==TRUE){print(theta.hat)} if(rep==TRUE){print("Pre-Whitening...")} filtered<-pre.White(theta=theta.hat, data=t(X), q=q, approx=approx) } if(prewhite=="uni"){ for(aa in 1:q){ prewhite_est<-list() suppressWarnings( for(i in 1:4){ prewhite_est[[1]]<-fracdiff(X[aa,], nar=0, nma=0) prewhite_est[[2]]<-fracdiff(X[aa,], nar=1, nma=0) prewhite_est[[3]]<-fracdiff(X[aa,], nar=0, nma=1) prewhite_est[[4]]<-fracdiff(X[aa,], nar=1, nma=1) } ) est<-prewhite_est[[which.min(unlist(lapply(prewhite_est, BIC)))]] X[aa,]<-(fdiff(residuals(est), -est$d)) } d.est<-as.vector(GSE(X=X,m=m)) } W.stat<-W_multi(X=X, d_vec=d.est, m=m, epsilon=epsilon, eta=eta) crit<-cbind(c(1.118,1.252,1.374,1.517),c(1.022,1.155,1.277,1.426)) colnames(crit)<-c("eps=.02","eps=.05") rownames(crit)<-c("alpha=.1","alpha=.05","alpha=.025","alpha=.01") if(epsilon==0.02){crit<-crit[,1]} if(epsilon==0.05){crit<-crit[,2]} if(any(eta!=rep(1/sqrt(q),q))){ G_est<-G.hat(X,d=d.est,m=m) cat("Simulating limit distribution...","\n") dist<-simMLWS(G=G_est, eta=eta, epsilon=epsilon, T=T_limdist, M=M_limdist) crit<-quantile(dist, probs=c(0.9,0.95,0.975,0.99)) pval<-1-ecdf(dist)(W.stat) out<-list("B"=B,"d"=d.est,"W.stat"=W.stat, "CriticalValues"=crit, "pval"=pval) }else{ out<-list("B"=B,"d"=d.est,"W.stat"=W.stat, "CriticalValues"=crit) } out }
TAR.lagd<-function(ay,p1,p2,ph.1,ph.2,sig.1,sig.2,thres,lagp1,lagp2,constant=1,d0,thresVar){ loglik<-lik<-pr<-NULL if (!missing(thresVar)){ for (i in 1:d0){ loglik[i]<- TAR.lik(ay,p1,p2,ph.1,ph.2,sig.1,sig.2,i,thres,lagp1,lagp2,constant=constant,thresVar)}} else { for (i in 1:d0){ loglik[i]<- TAR.lik(ay,p1,p2,ph.1,ph.2,sig.1,sig.2,i,thres,lagp1,lagp2,constant=constant)}} lik<- (exp(loglik-max(loglik)))*(rev(c(1:d0))/sum(1:d0)) lagd<- (sum((cumsum(lik)/sum(lik))<runif(1, min=0, max=1)))+1 return(lagd) }
test_that("classif_nodeHarvest", { requirePackagesOrSkip("nodeHarvest", default.method = "load") parset.list = list( list(nodes = 2L), list(nodes = 2L, maxinter = 1L), list(nodes = 2L, mode = "outbag") ) old.predicts.list = list() old.probs.list = list() for (i in seq_along(parset.list)) { parset = parset.list[[i]] Y = ifelse(binaryclass.df[binaryclass.train.inds, binaryclass.class.col] == binaryclass.class.levs[1], 1, 0) parset = c(parset, list(X = binaryclass.df[binaryclass.train.inds, -binaryclass.class.col], Y = Y, silent = TRUE)) set.seed(getOption("mlr.debug.seed")) m = do.call(nodeHarvest::nodeHarvest, parset) p = predict(m, binaryclass.df[-binaryclass.train.inds, ]) old.predicts.list[[i]] = ifelse(p > 0.5, binaryclass.class.levs[1], binaryclass.class.levs[2]) old.probs.list[[i]] = p } testSimpleParsets("classif.nodeHarvest", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.predicts.list, parset.list) testProbParsets("classif.nodeHarvest", binaryclass.df, binaryclass.target, binaryclass.train.inds, old.probs.list, parset.list) })
do_exec_plan <- function(.data) { plan <- ExecPlan$create() final_node <- plan$Build(.data) tab <- plan$Run(final_node) if (inherits(tab, "RecordBatchReader")) { tab <- tab$read_table() } if (length(final_node$sort$temp_columns) > 0) { tab <- tab[, setdiff(names(tab), final_node$sort$temp_columns), drop = FALSE] } if (ncol(tab)) { original_schema <- source_data(.data)$schema r_meta <- original_schema$r_metadata if (!is.null(r_meta)) { new_schema <- tab$schema common_names <- intersect(names(r_meta$columns), names(tab)) keep <- common_names[ map_lgl(common_names, ~ original_schema[[.]] == new_schema[[.]]) ] r_meta$columns <- r_meta$columns[keep] if (has_aggregation(.data)) { r_meta$attributes <- NULL } tab$r_metadata <- r_meta } } tab } ExecPlan <- R6Class("ExecPlan", inherit = ArrowObject, public = list( Scan = function(dataset) { if (inherits(dataset, "arrow_dplyr_query")) { if (inherits(dataset$.data, "RecordBatchReader")) { return(ExecNode_ReadFromRecordBatchReader(self, dataset$.data)) } filter <- dataset$filtered_rows if (isTRUE(filter)) { filter <- Expression$scalar(TRUE) } colnames <- unique(unlist(map( dataset$selected_columns, field_names_in_expression ))) dataset <- dataset$.data assert_is(dataset, "Dataset") } else { if (inherits(dataset, "ArrowTabular")) { dataset <- InMemoryDataset$create(dataset) } assert_is(dataset, "Dataset") filter <- Expression$scalar(TRUE) colnames <- names(dataset) } ExecNode_Scan(self, dataset, filter, colnames %||% character(0)) }, Build = function(.data) { group_vars <- dplyr::group_vars(.data) grouped <- length(group_vars) > 0 target_names <- names(.data) .data <- ensure_group_vars(.data) .data <- ensure_arrange_vars(.data) if (inherits(.data$.data, "arrow_dplyr_query")) { node <- self$Build(.data$.data) } else { node <- self$Scan(.data) } if (inherits(.data$filtered_rows, "Expression")) { node <- node$Filter(.data$filtered_rows) } if (!is.null(.data$aggregations)) { node <- node$Project(summarize_projection(.data)) if (grouped) { .data$aggregations <- lapply(.data$aggregations, function(x) { x[["fun"]] <- paste0("hash_", x[["fun"]]) x }) } node <- node$Aggregate( options = map(.data$aggregations, ~ .[c("fun", "options")]), target_names = names(.data$aggregations), out_field_names = names(.data$aggregations), key_names = group_vars ) if (grouped) { node <- node$Project( make_field_refs(c(group_vars, names(.data$aggregations))) ) if (getOption("arrow.summarise.sort", FALSE)) { node$sort <- list( names = group_vars, orders = rep(0L, length(group_vars)) ) } } } else { projection <- c(.data$selected_columns, .data$temp_columns) node <- node$Project(projection) if (!is.null(.data$join)) { node <- node$Join( type = .data$join$type, right_node = self$Build(.data$join$right_data), by = .data$join$by, left_output = names(.data), right_output = setdiff(names(.data$join$right_data), .data$join$by) ) } } if (length(.data$arrange_vars)) { node$sort <- list( names = names(.data$arrange_vars), orders = .data$arrange_desc, temp_columns = names(.data$temp_columns) ) } if (!is.null(.data$head)) { node$head <- .data$head } if (!is.null(.data$tail)) { node$tail <- .data$tail } node }, Run = function(node) { assert_is(node, "ExecNode") sorting <- node$sort %||% list() select_k <- node$head %||% -1L has_sorting <- length(sorting) > 0 if (has_sorting) { if (!is.null(node$tail)) { sorting$orders <- !sorting$orders select_k <- node$tail } sorting$orders <- as.integer(sorting$orders) } out <- ExecPlan_run(self, node, sorting, select_k) if (!has_sorting) { slice_size <- node$head %||% node$tail if (!is.null(slice_size)) { out <- head(out, slice_size) } } else if (!is.null(node$tail)) { out <- out$read_table() out <- out[rev(seq_len(nrow(out))), , drop = FALSE] } out }, Stop = function() ExecPlan_StopProducing(self) ) ) ExecPlan$create <- function(use_threads = option_use_threads()) { ExecPlan_create(use_threads) } ExecNode <- R6Class("ExecNode", inherit = ArrowObject, public = list( sort = NULL, head = NULL, tail = NULL, preserve_sort = function(new_node) { new_node$sort <- self$sort new_node$head <- self$head new_node$tail <- self$tail new_node }, Project = function(cols) { if (length(cols)) { assert_is_list_of(cols, "Expression") self$preserve_sort(ExecNode_Project(self, cols, names(cols))) } else { self$preserve_sort(ExecNode_Project(self, character(0), character(0))) } }, Filter = function(expr) { assert_is(expr, "Expression") self$preserve_sort(ExecNode_Filter(self, expr)) }, Aggregate = function(options, target_names, out_field_names, key_names) { self$preserve_sort( ExecNode_Aggregate(self, options, target_names, out_field_names, key_names) ) }, Join = function(type, right_node, by, left_output, right_output) { self$preserve_sort( ExecNode_Join( self, type, right_node, left_keys = names(by), right_keys = by, left_output = left_output, right_output = right_output ) ) } ), active = list( schema = function() ExecNode_output_schema(self) ) )
render_camera = function(theta = NULL, phi = NULL, zoom = NULL, fov = NULL) { if(is.null(theta) && is.null(phi) && is.null(zoom) && is.null(fov)) { allmissing = TRUE } else { allmissing = FALSE } if(rgl::rgl.cur() == 0) { stop("No rgl window currently open.") } if(is.null(fov)) { fov = rgl::par3d()$FOV } if(is.null(zoom)) { zoom = rgl::par3d()$zoom } if(is.null(phi) || is.null(theta)) { rotmat = rot_to_euler(rgl::par3d()$userMatrix) if(is.null(phi)) { phi = rotmat[1] } if(is.null(theta)) { if(0.001 > abs(abs(rotmat[3]) - 180)) { theta = -rotmat[2] + 180 } else { theta = rotmat[2] } } } rgl::rgl.viewpoint(theta = theta, phi = phi, fov = fov, zoom = zoom) if(allmissing) { return(c("theta"=theta,"phi"=phi,"zoom"=zoom,"fov"=fov)) } }
Boot.Rent <- do(1000) * mean( ~ Rent, data = resample(ManhattanApartments)) head(Boot.Rent, 3) favstats( ~ mean, data = Boot.Rent) cdata( ~ mean, 0.95, data = Boot.Rent)
reshape_ci <- function(x, ci_type = "CI") { ci_type <- match.arg(ci_type, choices = c("CI", "SI", "HDI", "ETI")) ci_low <- paste0(ci_type, "_low") ci_high <- paste0(ci_type, "_high") if (ci_low %in% names(x) & ci_high %in% names(x) & "CI" %in% names(x)) { ci_position <- which(names(x) == "CI") if (length(unique(x$CI)) > 1) { if (!"Parameter" %in% names(x)) { x$Parameter <- NA remove_parameter <- TRUE } else { remove_parameter <- FALSE } x <- stats::reshape( x, idvar = "Parameter", timevar = "CI", direction = "wide", v.names = c(ci_low, ci_high), sep = "_" ) row.names(x) <- NULL if (remove_parameter) x$Parameter <- NULL } ci_colname <- names(x)[c(grepl(paste0(ci_low, "_*"), names(x)) | grepl(paste0(ci_high, "_*"), names(x)))] colnames_1 <- names(x)[0:(ci_position - 1)][!names(x)[0:(ci_position - 1)] %in% ci_colname] colnames_2 <- names(x)[!names(x) %in% c(ci_colname, colnames_1)] x <- x[c(colnames_1, ci_colname, colnames_2)] } else { if (!"Parameter" %in% names(x)) { x$Parameter <- 1:nrow(x) remove_parameter <- TRUE } else { remove_parameter <- FALSE } lows <- grepl(paste0(ci_low, "_*"), names(x)) highs <- grepl(paste0(ci_high, "_*"), names(x)) ci <- as.numeric(gsub(paste0(ci_low, "_"), "", names(x)[lows])) if (paste0(ci, collapse = "-") != paste0(gsub(paste0(ci_high, "_"), "", names(x)[highs]), collapse = "-")) { stop("Something went wrong in the CIs reshaping.") return(x) } if (sum(lows) > 1 & sum(highs) > 1) { low <- stats::reshape( x[!highs], direction = "long", varying = list(names(x)[lows]), sep = "_", timevar = "CI", v.names = ci_low, times = ci ) high <- stats::reshape( x[!lows], direction = "long", varying = list(names(x)[highs]), sep = "_", timevar = "CI", v.names = ci_high, times = ci ) x <- merge(low, high) x$id <- NULL x <- x[order(x$Parameter), ] row.names(x) <- NULL if (remove_parameter) x$Parameter <- NULL } ci_position <- which(lows)[1] ci_colname <- c("CI", ci_low, ci_high) colnames_1 <- names(x)[0:(ci_position - 1)][!names(x)[0:(ci_position - 1)] %in% ci_colname] colnames_2 <- names(x)[!names(x) %in% c(ci_colname, colnames_1)] x <- x[c(colnames_1, ci_colname, colnames_2)] } class(x) <- intersect(c("data.frame", "numeric"), class(x)) x }
predictSSNobject <- function(object, newdata){ newX <- vector("list") if(is.null(newdata)){ dfPred <- getSSNdata.frame(object$ssn.object, "preds") dfPred <- dfPred[dfPred$netID == object$internals$netID, ] ridPred <- as.numeric(as.character(dfPred[,"rid"])) } else { dfPred <- newdata dfPred <- dfPred[dfPred$netID == object$internals$netID, ] ridPred <- as.numeric(as.character(dfPred[,"rid"])) } if(object$internals$n.linear > 0){ linVarbs <- dfPred[,colnames(object$internals$variables)[1:object$internals$n.linear]] newX <- c(newX, list(linear = cbind(1, linVarbs))) } else { newX <- c(newX, list(linear = rep(1, length(ridPred)))) } if(object$internals$n.smooth > 0){ smTerms <- object$internals$sm.terms.names smDesign <- vector("list") dataOriginal <- data.frame(object$internals$variables) for(i in 1:length(smTerms)){ oldVariable <- dataOriginal[smTerms[[i]]] new_bit <- construct_bspline_basis(as.matrix(dfPred[smTerms[[i]]]), dimensions = object$internals$sm.basis[[i]], cyclic = object$internals$sm.cyclic[[i]], range.variables = oldVariable) newX <- c(newX, new_bit) } } if(object$internals$net){ ridPredRemap <- re_map_rid(rid_vector = ridPred, all_rid = as.integer(object$internals$adjacency$rid_bid[, 1])) newX <- c(newX, spam( x = list(i = 1:length(ridPredRemap), j = ridPredRemap, val = rep(1, length(ridPredRemap))), nrow = length(ridPred), ncol = ncol(object$internals$X.list[[length(object$internals$X.list)]]))) } newX <- lapply(newX, as.matrix) Xstar <- Reduce("cbind.spam", newX) predictions <- as.numeric(Xstar %*% object$internals$beta_hat) left1 <- forwardsolve.spam(object$internals$U, t(object$internals$X.spam)) left2 <- backsolve.spam(object$internals$U, left1) vec <- Xstar %*% left2 predictions.se <- sqrt((1 + rowSums(vec*vec))*object$internals$sigma.sq) list(predictions = predictions, predictions.se = predictions.se) }