code
stringlengths
1
13.8M
create_FolderTemplates <- function( path, mode = "SG", n_folders = 1, names = paste("Sample_", 1:n_folders), verbose = TRUE ){ if(missing(path)) stop("[create_FolderTemplates()] Input for 'path' is missing!", call. = FALSE) if(!dir.exists(normalizePath(path, mustWork = FALSE))) stop("[create_FolderTemplates()] ",path, " does not exist!", call. = FALSE) if(!toupper(mode) %in% c("SG","MG")) stop("[create_FolderTemplates()] mode = '",mode,"' not supported!", call. = FALSE) names <- gsub( pattern = " ", replacement = "_", x = names, fixed = TRUE ) names <- rep(names, length.out = n_folders[1]) switch (toupper(mode), "SG" = extdata <- "extdata/samp1", "MG" = extdata <- "extdata/FER1" ) extdata_path <- list.files( path = system.file(extdata, "", package="BayLum"), full.names = TRUE, recursive = TRUE) if(verbose) cat("\n[create_FolderTemplates()]\n-|\n") for(i in 1:n_folders[1]){ dir.create(path = paste0(normalizePath(path),"/",names[i]), showWarnings = FALSE) file.copy( from = extdata_path, to = paste0(normalizePath(path),"/",names[i]), recursive = TRUE, overwrite = TRUE) if(verbose) cat(" |__(dir created:)", path,"\n") } if(verbose) message("All templates created. Please modify the parameters according to your data!") }
`endfunction` <- function(text) {invisible(NULL)}
cmorwavf <- function(lb = -8, ub = 8, n = 1000, fb = 5, fc = 1) { if (!isPosscal(n) || !isWhole(n) || n <= 0) stop("n must be an integer strictly positive") if (!isPosscal(fb) || fb <= 0) stop("fb must be a positive scalar > 0") if (!isPosscal(fc) || fc <= 0) stop("fc must be a positive scalar > 0") x <- seq(lb, ub, length.out = n) psi <- ((pi * fb) ^ (-0.5)) * exp(2 * 1i * pi * fc * x) * exp(-x^2 / fb) list(x = x, psi = psi) }
.plotFtest <- function(x, ftbase=1.01, siglines=NULL, xlab="Frequency", ...) { if(is.null(x$mtm$Ftest) || !("Ftest" %in% class(x))) { stop(paste("Ftest not computed for given mtm object!")) } log <- match.call(expand.dots = )$log ylab <- match.call(expand.dots = )$ylab if(is.null(ylab)) ylab <- "Harmonic F-test Statistic" ylog = "n" if(is.null(log) || log == "yes") { ylog = "y" } ftestVals = x$mtm$Ftest ftestVals[ftestVals < ftbase] <- ftbase ftmax <- max(ftestVals) .lplotDefault(x$freq, ftestVals, log=ylog, ylab=ylab, xlab=xlab, ylim=c(ftbase,ftmax), type="l", ...) if(!is.null(siglines)) { for(j in 1:length(siglines)) { if(is.numeric(siglines[j]) && 0.80 <= siglines[j] && 1.000000 >= siglines[j]) { sig0 <- qf(siglines[j],2,2*x$mtm$k-2) abline(h=sig0, col="red", lty=2, lwd=1) mtext(paste(siglines[j]*100,"%",sep=""), side=4, line=0, at=ceiling(sig0), col="red") } } } } .lplotSpec <- function(x, ..., dT) { plot(x, ...) } .lplotDefault <- function(x, y, ..., dT) { plot(x, y, ...) } .lftr3p <- function(x, xv, nhi, nehl, nehc, slo, shi) { ip <- 2 xp <- matrix(NA, nhi, 3) xp[,3] <- .llftr7(xv, nhi, "hi", "even", "extend", nehl, ip) xp[,2] <- .llftr7(x, nhi, "-", slo, shi, nehc, ip) xp[,1] <- xp[,2] - sqrt(xp[,3]) xp[,3] <- xp[,2] + sqrt(xp[,3]) return(xp) } .llftr7 <- function(x,nhi,lohi,slo,shi,neh,ip) { nlo <- 1 y <- array(NA, nhi) z <- array(NA, nhi+2*neh) zNlo <- nlo + neh zNhi <- nhi + neh zHi <- zNhi + neh fw <- as.double(neh + 1) wt <- ((1-((-neh:neh)/fw))*(1+((-neh:neh)/fw)))**ip cwt <- sum(wt) wt <- wt/cwt innerSeq <- zNlo:zNhi z[innerSeq] <- x lowerSeq <- 1:neh z[lowerSeq] <- x[1] upperSeq <- (zNhi+1):zHi z[upperSeq] <- x[nhi] if(tolower(slo) == "even") { z[rev(lowerSeq)] <- z[(zNlo+1):(zNlo+neh)] } if(tolower(slo) == "odd") { z[rev(lowerSeq)] <- 2.0*z[zNlo] - z[(zNlo+1):(zNlo+neh)] } if(tolower(shi) == "even") { for( j in 1:neh) { z[zNhi+j] <- z[zNhi-j] } } if(tolower(shi) == "odd") { for( j in 1:neh) { z[zNhi + j] = 2.*z[zNhi] - z[zNhi-j] } } if(tolower(lohi) == "hi") { for( n in (nlo+1):(nhi-1) ) { if( (x[n] < x[n-1]) && (x[n] < x[n+1]) ) { zNoff <- n +neh z[zNoff] <- (x[n-1]+x[n+1])/2.0 } } } if(tolower(lohi) == "lo") { for( n in (nlo+1):(nhi-1) ) { if( (x[n] > x[n-1] ) && (x[n] > x[n+1]) ) { zNoff <- n +neh z[n] = (x[n-1]+x[n+1])/2.0 } } } zOffSetSeq <- 1:(2*neh+1) for (n in nlo:nhi) { y[n] <- sum(wt*z[zOffSetSeq]) zOffSetSeq <- zOffSetSeq +1 } return(y) } .trnrm <- function(k) sqrt(2*k-2) .C2toF <- function(xx, trnrm_) { return( trnrm_*log((1.0+sqrt(xx))/(1.0-sqrt(xx)))/2.0 ) } .FtoMSC <- function(ff, trnrm_) tanh(ff/trnrm_)**2 .paxpt7 <- function(ndata=2000, nmax=40) { ndec <- round(log10(max(11,ndata))); nout = 6*ndec -1; if(nout > nmax) { return(); } n <- 0; out <- array(NA, nout) for(m in seq(-ndec, -1, 1)) { for(k in c(1,2,5)) { n <- n +1; v <- as.double(k*10**m); out[n] <- v; out[nout +1 -n] <- as.double(1.0 - v); } } return(list(out=out, Qnorm=qnorm(out),nout=nout)); } .cdfToMSqCoh <- function(cdf, k) { fnavm <- as.double(k-1); return(1.0 - (1.0 - cdf)**(1.0/fnavm)); } .mscToCDFquantiles <- function(msc, k) { 1 - (1-msc)^(k-1) }
library(rgdal) library(spdep) library(rgeos) library(measurements) area <- function(spatobj = NULL, folder = NULL, shape = NULL) { if (is.null(spatobj)) spatobj <- rgdal::readOGR(dsn = folder, layer = shape) provi <- slot(spatobj, "polygons") area <- sapply(provi, slot, "area") return(area) } contig <- function(spatobj = NULL, folder = NULL, shape = NULL, queen = FALSE) { if (is.null(spatobj)) spatobj <- rgdal::readOGR(dsn = folder, layer = shape) data_ngb <- spdep::poly2nb(spatobj, queen = queen) contig <- spdep::nb2mat(data_ngb, style = "B", zero.policy = TRUE) return(contig) } perimeter <- function(spatobj = NULL, folder = NULL, shape = NULL) { if (is.null(spatobj)) spatobj <- rgdal::readOGR(dsn = folder, layer = shape) perim <- vector(length = length(spatobj)) for (i in 1:length(spatobj)) perim[i] <- rgeos::gLength(spatobj[i, ]) return(perim) } distance <- function(spatobj = NULL, folder = NULL, shape = NULL, distin = "m", distout = "m", diagval = "0") { if (is.null(spatobj)) spatobj <- rgdal::readOGR(dsn = folder, layer = shape) dist <- matrix(0, nrow = length(spatobj), ncol = length(spatobj)) centroids <- vector("list", length(spatobj)) for (i in 1:length(spatobj)) centroids[[i]] <- rgeos::gCentroid(spatobj[i, ]) for (i in 1:(length(spatobj) - 1)) for (j in (i + 1):length(spatobj)) dist[i, j] <- rgeos::gDistance(centroids[[i]], centroids[[j]]) dist <- dist + t(dist) if (diagval == "a") { a <- area(spatobj = spatobj, folder = folder, shape = shape) diag(dist) <- sqrt(a) * 0.6 } dist <- measurements::conv_unit(dist, from = distin, to = distout) return(dist) } distcenter <- function(spatobj = NULL, folder = NULL, shape = NULL, center = 1, distin = "m", distout = "m") { if (is.null(spatobj)) spatobj <- rgdal::readOGR(dsn = folder, layer = shape) distcenter <- vector(length = length(spatobj)) centroids <- vector("list", length(spatobj)) for (i in 1:length(spatobj)) centroids[[i]] <- rgeos::gCentroid(spatobj[i, ]) for (i in 1:length(spatobj)) distcenter[i] <- rgeos::gDistance(centroids[[i]], centroids[[center]]) distcenter <- measurements::conv_unit(distcenter, from = distin, to = distout) return(distcenter) } boundaries <- function(spatobj = NULL, folder = NULL, shape = NULL) { if (is.null(spatobj)) spatobj <- rgdal::readOGR(dsn = folder, layer = shape) boundaries <- contig(spatobj) mat <- upper.tri(boundaries, diag = FALSE) * 1 boundaries <- boundaries * mat for (i in 1:(length(spatobj) - 1)) for (j in (i + 1):length(spatobj)) { if (boundaries[i, j] != 0) boundaries[i, j] <- rgeos::gLength(rgeos::gIntersection(spatobj[i, ], spatobj[j, ])) } boundaries <- boundaries + t(boundaries) return(boundaries) }
computeMu = function(X, Y, optargs=list()) { if (!is.matrix(X) || !is.numeric(X) || any(is.na(X))) stop("X: real matrix, no NA") n = nrow(X) d = ncol(X) if (!is.numeric(Y) || length(Y)!=n || any(Y!=0 & Y!=1)) stop("Y: vector of 0 and 1, size nrow(X), no NA") if (!is.list(optargs)) stop("optargs: list") M = if (is.null(optargs$M)) computeMoments(X,Y) else optargs$M K = optargs$K if (is.null(K)) { Sigma = svd(M[[2]])$d large_ratio <- ( abs(Sigma[-d] / Sigma[-1]) > 3 ) K <- if (any(large_ratio)) max(2, which.min(large_ratio)) else d } d = ncol(X) fixed_design = FALSE jd_nvects = ifelse(!is.null(optargs$jd_nvects), optargs$jd_nvects, 0) if (jd_nvects == 0) { jd_nvects = d fixed_design = TRUE } M2_t = array(dim=c(d,d,jd_nvects)) for (i in seq_len(jd_nvects)) { rho = if (fixed_design) c(rep(0,i-1),1,rep(0,d-i)) else normalize( rnorm(d) ) M2_t[,,i] = .T_I_I_w(M[[3]],rho) } jd_method = ifelse(!is.null(optargs$jd_method), optargs$jd_method, "uwedge") V = if (jd_nvects > 1) { suppressWarnings({jd = jointDiag::ajd(M2_t, method=jd_method)}) if (jd_method=="uwedge") jd$B else MASS::ginv(jd$A) } else eigen(M2_t[,,1])$vectors M2_t = array(dim=c(d,d,K)) for (i in seq_len(K)) M2_t[,,i] = .T_I_I_w(M[[3]],V[,i]) suppressWarnings({jd = jointDiag::ajd(M2_t, method=jd_method)}) U = if (jd_method=="uwedge") MASS::ginv(jd$B) else jd$A mu = normalize(U[,1:K]) C = MASS::ginv(mu) %*% M[[1]] mu[,C < 0] = - mu[,C < 0] mu }
psdVal <- function(species="List",units=c("mm","cm","in"),incl.zero=TRUE, addLens=NULL,addNames=NULL,showJustSource=FALSE) { units <- match.arg(units) PSDlit <- get(utils::data("PSDlit",envir=environment()),envir=environment()) if (iPSDLitCheck(PSDlit,species <- capFirst(species))) { if (showJustSource) { PSDlit[PSDlit$species==species,c(1,12)] } else { ifelse(units=="in",cols <- 2:6,cols <- 7:11) PSDvec <- as.matrix(PSDlit[PSDlit$species==species,cols])[1,] if (units=="mm") PSDvec <- PSDvec*10 names(PSDvec) <- c("stock","quality","preferred","memorable","trophy") if (incl.zero) { PSDvec <- c(0,PSDvec) names(PSDvec)[1] <- "substock" } if (!is.null(addLens)) { addLens <- iHndlAddNames(addLens,addNames) tmp <- which(PSDvec %in% addLens) if (length(tmp>0)) { WARN("At least one Gabelhouse length that was in 'addLens' has been removed.") PSDvec <- PSDvec[-tmp] } PSDvec <- c(PSDvec,addLens) PSDvec <- PSDvec[order(PSDvec)] } PSDvec } } } iPSDLitCheck <- function(data,species) { OK <- FALSE if (length(species)!=1) STOP("'species' can have only one name.") else if (species=="List") iListSpecies(data) else if (!any(unique(data$species)==species)) STOP("The Gabelhouse lengths do not exist for ",species, ".\n Type psdVal() for a list of available species.\n\n") else OK <- TRUE OK } iHndlAddNames <- function(addLens,addNames) { if (is.null(names(addLens))) { if (is.null(addNames)) names(addLens) <- as.character(addLens) else { if (length(addLens)!=length(addNames)) STOP("'addLens' and 'addNames' have different lengths.") names(addLens) <- addNames } } addLens }
phase.plot <- function(x, y, phases, arrow.len = min(par()$pin[2] / 30, par()$pin[1] / 40), arrow.col = "black", arrow.lwd = arrow.len * 0.3) { a.row <- seq(1, NROW(phases), round(NROW(phases) / 30)) a.col <- seq(1, NCOL(phases), round(NCOL(phases) / 40)) phases[-a.row, ] <- NA phases[, -a.col] <- NA for (i in seq_len(NROW(phases))) { for (j in seq_len(NCOL(phases))) { if (!is.na(phases[i, j])) { arrow(x[j], y[i], l = arrow.len, w = arrow.lwd, alpha = phases[i, j], col = arrow.col) } } } } arrow <- function(x, y, l = 0.1, w = 0.3 * l, alpha, col = "black") { l2 <- l / 3 w2 <- w / 6 l3 <- l / 2 x1 <- l * cos(alpha) y1 <- l * sin(alpha) x2 <- w * cos(alpha + pi / 2) y2 <- w * sin(alpha + pi / 2) x7 <- w * cos(alpha + 3 * pi / 2) y7 <- w * sin(alpha + 3 * pi / 2) x3 <- l2 * cos(alpha) + w2 * cos(alpha + pi / 2) y3 <- l2 * sin(alpha) + w2 * sin(alpha + pi / 2) x6 <- l2 * cos(alpha) + w2 * cos(alpha + 3 * pi / 2) y6 <- l2 * sin(alpha) + w2 * sin(alpha + 3 * pi / 2) x4 <- l3 * cos(alpha + pi) + w2 * cos(alpha + pi / 2) y4 <- l3 * sin(alpha + pi) + w2 * sin(alpha + pi / 2) x5 <- l3 * cos(alpha + pi) + w2 * cos(alpha + 3 * pi / 2) y5 <- l3 * sin(alpha + pi) + w2 * sin(alpha + 3 * pi / 2) X <- (par()$usr[2] - par()$usr[1]) / par()$pin[1] * c(x1,x2,x3,x4,x5,x6,x7) Y <- (par()$usr[4] - par()$usr[3]) / par()$pin[2] * c(y1,y2,y3,y4,y5,y6,y7) polygon(x + X, y + Y, col = col, ljoin = 1, border = NA) } arrow2 <- function(x, y, angle, size = .1, col = "black", chr = intToUtf8(0x279B)) { text(x,y, labels = chr, col = col, cex = 10 * size, srt = 57.29578 * angle) }
context("Calculate XMR Upper Long Run Recalculation") library(testthat) library(dplyr) library(tidyr) Measure <- c(58, 57, 69, 62, 66, 58, 66, 62, 61, 61, 67, 68, 69, 70, 69, 68, 67, 69) Time <- c(2000:2017) example_data <- data.frame(Time, Measure) df <- xmr(example_data, measure = "Measure", recalc = T) test_that("Upper shortrun recalculation is correct", { mv <- df$`Moving Range`[df$Order %in% c(11:15)] %>% mean() avm <- df$`Average Moving Range`[11] calc <- avm - mv max <- max(calc, na.rm = T) expect_lt(max, 0.01) m <- df$Measure[df$Order %in% c(11:15)] %>% mean() cl <- df$`Central Line`[11] calc <- m - cl max <- max(calc, na.rm = T) expect_lt(max, 0.01) }) test_that("Upper Process Limit calculation is correct", { up <- df$`Upper Natural Process Limit` calc <- (df$`Central Line` + (2.66 * df$`Average Moving Range`)) max <- max(up - calc, na.rm = T) expect_lt(max, 0.01) }) test_that("Lower Process Limit calculation is correct", { lower <- df$`Lower Natural Process Limit` calc <- (df$`Central Line` - (2.66 * df$`Average Moving Range`)) calc <- ifelse(calc < 0, 0, calc) max <- max(lower - calc, na.rm = T) expect_lt(max, 0.01) })
context("Resource configs") test_that("User config works", { user <- user_config("username", sshkey="random key") expect_is(user, "user_config") expect_identical(user$key, "random key") user <- user_config("username", password="random password") expect_is(user, "user_config") expect_identical(user$pwd, "random password") user <- user_config("username", sshkey="../testthat.R") expect_is(user, "user_config") expect_identical(user$key, readLines("../testthat.R")) }) test_that("Datadisk config works", { disk <- datadisk_config(100) expect_is(disk, "datadisk_config") expect_identical(disk$res_spec$diskSizeGB, 100) expect_identical(disk$vm_spec$createOption, "attach") expect_identical(disk$vm_spec$caching, "None") expect_null(disk$vm_spec$storageAccountType) }) test_that("Image config works", { expect_error(image_config()) img <- image_config(publisher="pubname", offer="offname", sku="skuname") expect_is(img, "image_marketplace") img <- image_config(id="resource_id") expect_is(img, "image_custom") }) test_that("Network security group config works", { nsg <- nsg_config() expect_is(nsg, "nsg_config") res <- build_resource_fields(nsg) expect_identical(res$properties, list(securityRules=list()) ) nsg <- nsg_config(list(nsg_rule_allow_ssh)) expect_is(nsg, "nsg_config") expect_is(nsg$properties$securityRules[[1]], "nsg_rule") expect_identical(nsg$properties$securityRules[[1]]$name, "Allow-ssh") res <- build_resource_fields(nsg) rule <- unclass(nsg_rule_allow_ssh) rule$properties$priority <- 1010 expect_identical(res$properties, list(securityRules=list(rule)) ) }) test_that("Public IP address config works", { ip <- ip_config() expect_is(ip, "ip_config") expect_null(ip$type) expect_null(ip$dynamic) ip <- ip_config("static", FALSE) expect_is(ip, "ip_config") res <- build_resource_fields(ip) expect_identical(res$properties, list( publicIPAllocationMethod="static", publicIPAddressVersion="IPv4", dnsSettings=list(domainNameLabel="[parameters('vmName')]") ) ) expect_identical(res$sku, list(name="static") ) }) test_that("Virtual network config works", { vnet <- vnet_config() expect_is(vnet, "vnet_config") expect_is(vnet$properties$subnets[[1]], "subnet_config") res <- build_resource_fields(vnet) expect_identical(res$properties, list( addressSpace=list(addressPrefixes=I("10.0.0.0/16")), subnets=list( list( name="subnet", properties=list( addressPrefix="10.0.0.0/16", networkSecurityGroup=list(id="[variables('nsgId')]") ) ) ) ) ) vnet <- vnet_config("10.1.0.0/16") expect_identical(vnet$properties$subnets[[1]]$properties$addressPrefix, "10.1.0.0/16") vnet <- vnet_config( address_space="10.1.0.0/16", subnets=list(subnet_config("mysubnet", addresses="10.0.0.0/24")) ) expect_identical(vnet$properties$subnets[[1]]$properties$addressPrefix, "10.1.0.0/24") }) test_that("Network interface config works", { nic <- nic_config() expect_is(nic, "nic_config") res <- build_resource_fields(nic) expect_identical(res$properties, list( ipConfigurations=list( list( name="ipconfig", properties=list( privateIPAllocationMethod="dynamic", subnet=list(id="[variables('subnetId')]"), publicIPAddress=list(id="[variables('ipId')]") ) ) ) ) ) }) test_that("Load balancer config works", { lb <- lb_config() expect_is(lb, "lb_config") expect_null(lb$type) lb <- lb_config(type="basic") res <- build_resource_fields(lb) expect_identical(res$properties, list( frontendIPConfigurations=list( list( name="[variables('lbFrontendName')]", properties=list( publicIPAddress=list(id="[variables('ipId')]") ) ) ), backendAddressPools=list( list( name="[variables('lbBackendName')]" ) ), loadBalancingRules=list(), probes=list() ) ) expect_identical(res$sku, list(name="basic") ) lb <- lb_config(type="basic", rules=list(lb_rule_ssh), probes=list(lb_probe_ssh)) expect_is(lb$rules[[1]], "lb_rule") expect_is(lb$probes[[1]], "lb_probe") res <- build_resource_fields(lb) expect_identical(res$properties$loadBalancingRules[[1]], unclass(lb_rule_ssh)) expect_identical(res$properties$probes[[1]], unclass(lb_probe_ssh)) }) test_that("Autoscaler config works", { as <- autoscaler_config() expect_is(as, "as_config") expect_is(as$properties$profiles[[1]], "as_profile_config") res <- build_resource_fields(as) expect_identical(res$properties, list( name="[variables('asName')]", targetResourceUri="[variables('vmId')]", enabled=TRUE, profiles=list( unclass(autoscaler_profile()) ) ) ) })
.proctime00 <- proc.time() library(utils) options(digits = 5) options(show.signif.stars = FALSE) SweaveTeX <- function(file, ...) { if(!file.exists(file)) stop("File", file, "does not exist in", getwd()) texF <- sub("\\.[RSrs]nw$", ".tex", file) Sweave(file, ...) if(!file.exists(texF)) stop("File", texF, "does not exist in", getwd()) readLines(texF) } p0 <- paste0 latexEnv <- function(lines, name) { stopifnot(is.character(lines), is.character(name), length(lines) >= 2, length(name) == 1) beg <- p0("\\begin{",name,"}") end <- p0("\\end{",name,"}") i <- grep(beg, lines, fixed=TRUE) j <- grep(end, lines, fixed=TRUE) if((n <- length(i)) != length(j)) stop(sprintf("different number of %s / %s", beg,end)) if(any(j-1 < i+1)) stop(sprintf("positionally mismatched %s / %s", beg,end)) lapply(mapply(seq, i+1,j-1, SIMPLIFY=FALSE), function(ind) lines[ind]) } t1 <- SweaveTeX("swv-keepSrc-1.Rnw") if(FALSE) writeLines(t1) inp <- latexEnv(t1, "Sinput") out <- latexEnv(t1, "Soutput") stopifnot(length(inp) == 5, grepl(" length(out) == 1, any(grepl("\\includegraphics", t1))) t2 <- SweaveTeX("keepsource.Rnw") comml <- grep(" stopifnot(length(comml) == 2, grepl("initial comment line", comml[1]), grepl("last comment", comml[2])) Sweave("customgraphics.Rnw") Sweave(f <- "Sexpr-verb-ex.Rnw") tools::texi2pdf(sub("Rnw$","tex", f)) cat('Time elapsed: ', proc.time() - .proctime00,'\n')
zPath <- function(viv, cutoff = NULL, method = c("greedy.weighted", "strictly.weighted"), connect = TRUE) { if (!(requireNamespace("zenplots", quietly = TRUE))) { message("Please install package zenplots to use this function. Note zenplots requires packge graph from Bioconductor, see help for zpath for instructions.") return(invisible(NULL)) } method <- match.arg(method) zpath <- NULL diag(viv) <- NA viv[upper.tri(viv)] <- NA if (!is.numeric(cutoff)) cutoff <- quantile(viv, .8, na.rm = TRUE) viv[is.na(viv)] <- -Inf w <- viv > cutoff if (sum(w) == 0) stop("No off diagonal entries in 'viv' exceed 'cutoff'.") zinfo <- cbind(viv[w], row(viv)[w], col(viv)[w]) if (nrow(zinfo) == 1) return(rownames(viv)[zinfo[1,2:3]]) if (method == "greedy.weighted") { zpath <- tryCatch(zpath <- zenplots::zenpath(zinfo[, 1], pairs = zinfo[, -1], method = "greedy.weighted"), error = function(e) NULL, warning = function(w) {} ) } if (method == "strictly.weighted" | is.null(zpath) | length(zpath) == 0) { zpath <- zenplots::zenpath(zinfo[, 1], pairs = zinfo[, -1], method = "strictly.weighted") zpath <- zenplots::connect_pairs(zpath) if (connect) zpath <- unlist(zpath) } if (is.numeric(zpath)) { zpath <- rownames(viv)[zpath] } else if (is.list(zpath)) zpath <- lapply(zpath, function(z) rownames(viv)[z]) zpath }
plotSNHT = function(data, stat, time = NULL, alpha = NULL){ stopifnot(is.numeric(data)) stopifnot(is(stat, "data.frame")) stopifnot("score" %in% colnames(stat)) if(!is.null(alpha)) stopifnot(is.numeric(alpha)) if(is.null(time)){ time = 1:length(data) stopifnot(nrow(stat) == length(data)) if("time" %in% colnames(stat)) stop("The snht statistic wasn't computed on evenly spaced data. ", "Please supply the times to this plotting function.") stat$time = time } else { stopifnot("time" %in% colnames(stat)) time = as.numeric(time) if(any(is.na(time))) stop("Supplied times were coerced to numeric, and the result has ", "missing values. Please check your time vector.") } pData = qplot(x = time, y = data) pStat = qplot(x = stat$time, y = stat$score, geom = "line") + labs(x = "time", y = "SNHT Statistic") if(!is.null(alpha)) pStat = pStat + geom_hline(yintercept = qchisq(1-alpha, df = 1), linetype = 4, color = "blue") pStat = pStat + geom_vline(xintercept = stat$time[which.max(stat$score)], color = "red", linetype = 4) pData = pData + geom_vline(xintercept = stat$time[which.max(stat$score)], color = "red", linetype = 4) print(gridExtra::grid.arrange(pData, pStat)) }
context("BLUP estimates of QTL effects") calc_blup <- function(probs, pheno, kinship=NULL, addcovar=NULL, tol=1e-12, quiet=TRUE) { addcovar <- cbind(rep(1, length(pheno)), addcovar) if(!is.null(kinship)) { Ke <- decomp_kinship(kinship) Keval <- Ke$values Kevec <- Ke$vectors pheno <- Kevec %*% pheno addcovar <- Kevec %*% addcovar probs <- Kevec %*% probs lmmfit <- Rcpp_fitLMM(Keval, pheno, addcovar, tol=tol) hsq <- lmmfit$hsq if(!quiet) message("hsq_pg: ", hsq) wts <- 1/sqrt(hsq * Keval + (1-hsq)) pheno <- wts * pheno addcovar <- wts * addcovar probs <- wts * probs } k <- probs %*% t(probs) ke <- decomp_kinship(k) keval <- ke$values kevec <- ke$vectors pheno <- kevec %*% pheno addcovar <- kevec %*% addcovar lmmfit <- Rcpp_fitLMM(keval, pheno, addcovar, tol=tol) beta <- lmmfit$beta hsq <- lmmfit$hsq if(!quiet) message("hsq_qtl: ", hsq) wts <- hsq * keval + (1-hsq) u <- as.numeric( t(kevec %*% probs) %*% diag(hsq/wts) %*% (pheno - addcovar %*% beta) ) c(u, beta) } iron <- read_cross2(system.file("extdata", "iron.zip", package="qtl2")) iron <- iron[c(1:30, 190:210),] phe <- iron$pheno[,1,drop=FALSE] test_that("scan1blup works with no kinship matrix", { pr <- calc_genoprob(iron[,"16"]) blup <- scan1blup(pr, phe) blup_se <- scan1blup(pr, phe, se=TRUE) expect_equivalent(blup, blup_se) for(i in 1:dim(pr[[1]])[[3]]) { blup_alt <- calc_blup(pr[[1]][,,i], phe) names(blup_alt) <- colnames(blup) expect_equal(unclass(blup)[i,], blup_alt, tol=1e-6) } sex <- as.numeric(iron$covar$sex=="m") names(sex) <- rownames(iron$covar) blup <- scan1blup(pr, phe, addcovar=sex) blup_se <- scan1blup(pr, phe, addcovar=sex, se=TRUE) expect_equivalent(blup, blup_se) for(i in 1:dim(pr[[1]])[[3]]) { blup_alt <- calc_blup(pr[[1]][,,i], phe, addcovar=sex) names(blup_alt) <- colnames(blup) expect_equal(unclass(blup)[i,], blup_alt, tolerance=1e-5) } }) test_that("scan1blup works with kinship matrix", { skip_on_cran() pr <- calc_genoprob(iron) K <- calc_kinship(pr[,c(1:15,17:19,"X")]) pr <- pr[,"16"] sex <- as.numeric(iron$covar$sex=="m") names(sex) <- rownames(iron$covar) blup <- scan1blup(pr, phe, K, sex) blup_se <- scan1blup(pr, phe, K, sex, se=TRUE) expect_equivalent(blup, blup_se) for(i in 1:dim(pr[[1]])[[3]]) { blup_alt <- calc_blup(pr[[1]][,,i], phe, K, sex) names(blup_alt) <- colnames(blup) expect_equal(unclass(blup)[i,], blup_alt, tolerance=1e-5) } }) test_that("scan1blup works with kinship matrix on another chromosome", { skip_if(isnt_karl(), "this test only run locally") pr <- calc_genoprob(iron) K <- calc_kinship(pr[,c(1:10,12:19,"X")]) pr <- pr[,"11"] sex <- as.numeric(iron$covar$sex=="m") names(sex) <- rownames(iron$covar) blup <- scan1blup(pr, phe, K, sex) blup_se <- scan1blup(pr, phe, K, sex, se=TRUE) expect_equivalent(blup, blup_se) for(i in 1:dim(pr[[1]])[[3]]) { blup_alt <- calc_blup(pr[[1]][,,i], phe, K, sex) names(blup_alt) <- colnames(blup) expect_equal(unclass(blup)[i,], blup_alt, tolerance=1e-5) } }) test_that("scan1blup deals with mismatching individuals", { skip_if(isnt_karl(), "this test only run locally") iron <- read_cross2(system.file("extdata", "iron.zip", package="qtl2")) map <- insert_pseudomarkers(iron$gmap, step=2.5) probs <- calc_genoprob(iron, map, error_prob=0.002) kinship <- calc_kinship(probs, "loco")[["3"]] probs <- probs[,"3"] Xc <- get_x_covar(iron) X <- match(iron$covar$sex, c("f", "m"))-1 names(X) <- rownames(iron$covar) phe <- iron$pheno[,2,drop=FALSE] ind <- c(1:50, 101:150) expected <- scan1blup(probs[ind,], phe[ind,,drop=FALSE], kinship[ind,ind], addcovar=X[ind]) expect_equal(scan1blup(probs[ind,], phe, kinship, addcovar=X), expected) expect_equal(scan1blup(probs, phe[ind,,drop=FALSE], kinship, addcovar=X), expected) expect_equal(scan1blup(probs, phe, kinship[ind,ind], addcovar=X), expected) expect_equal(scan1blup(probs, phe, kinship, addcovar=X[ind]), expected) expected <- scan1blup(probs[ind,], phe[ind,,drop=FALSE], addcovar=X[ind]) expect_equal(scan1blup(probs[ind,], phe, addcovar=X), expected) expect_equal(scan1blup(probs, phe[ind,,drop=FALSE], addcovar=X), expected) expect_equal(scan1blup(probs, phe, addcovar=X[ind]), expected) })
raterpage <- tabItem(tabName = "rateratio", h2("Precision of a rate ratio"), "Enter the proportions of events you expect in the groups. If you intend to use uneven allocation ratios (e.g. 2 allocated to group 1 for each participant allocated to group 2), adjust the allocation ratio accordingly. To estimate the ratio of the upper confidence interval limit to the lower limit from a number of events, enter the number of events in 'Number of events'. To estimate the number of observations required to get a ratio of the upper confidence interval limit to the lower limit of X, enter the ratio in 'Upper-lower ratio'.", tags$br(), h4("Please enter the following"), numericInput("rateratio_rate_exp", "Event rate in the exposed group", value = NULL, step = .01, min = .01, max = .99), numericInput("rateratio_rate_control", "Event rate in the control group", value = NULL, step = .01, min = .01, max = .99), numericInput("rateratio_r", "Allocation ratio", value = 1, step = .2), "(N2 / N1)", h4("Please enter one of the following"), uiOutput("rateratio_resetable_input"), actionButton("rateratio_reset_input", "Reset 'Number of observations' or 'Confidence interval width'"), h4("Results"), verbatimTextOutput("rateratio_out"), tableOutput("rateratio_tab"), "Code to replicate in R:", verbatimTextOutput("rateratio_code"), h4("References"), "Rothamn KJ, Greenland S (2018) Planning Study Size Based on Precision Rather Than Power.", tags$i("Epidemiology"), "29:599-603", tags$a(href = "https://doi.org/10.1097/EDE.0000000000000876","doi:10.1097/EDE.0000000000000876") ) rateratio_fn <- function(input, code = FALSE){ if(is.na(input$rateratio_n_exp) & is.na(input$rateratio_ciwidth)) { cat("Awaiting 'number of observations' or 'confidence interval width'") } else { z <- ifelse(is.na(input$rateratio_n_exp), paste0(", prec.level = ", input$rateratio_ciwidth), paste0(", n1 = ", input$rateratio_n_exp)) x <- paste0("prec_rateratio(rate1 = ", input$rateratio_rate_exp, ", rate2 = ", input$rateratio_rate_control, ", r = ", input$rateratio_r, z, ", conf.level = ", input$conflevel, ")") if(code){ cat(x) } else { eval(parse(text = x)) } } }
svykappa<-function(formula, design,...) UseMethod("svykappa",design) svykappa.default<-function(formula, design,...) { if (ncol(attr(terms(formula), "factors")) != 2) stop("kappa is only computed for two variables") rows <- formula[[2]][[2]] cols <- formula[[2]][[3]] df <- model.frame(design) nrow <- length(unique(df[[as.character(rows)]])) ncol <- length(unique(df[[as.character(cols)]])) rnames<-paste(".",letters,"_",sep="") cnames<-paste(".",LETTERS,"_",sep="") if (nrow != ncol) stop("number of categories is different") probs <- eval(bquote(svymean(~.(rows) + .(cols) + interaction(.(rows), .(cols)), design, ...))) nms <- c(rnames[1:nrow], cnames[1:ncol], outer(1:nrow, 1:ncol, function(i, j) paste(rnames[i], cnames[j], sep = "."))) names(probs) <- nms v <- vcov(probs) dimnames(v) <- list(nms, nms) attr(probs, "var") <- v obs <- parse(text = paste(nms[nrow + ncol + 1+ (0:(nrow-1))*(ncol+1)], collapse = "+"))[[1]] expect <- parse(text = paste(nms[1:nrow], nms[nrow + 1:ncol], sep = "*", collapse = "+"))[[1]] svycontrast(probs, list(kappa = bquote((.(obs) - .(expect))/(1 - .(expect))))) } "names<-.svrepstat"<-function(x, value){ if (is.list(x) && !is.null(x$replicates)){ names(x[[1]])<-value colnames(x$replicates)<-value x } else NextMethod() }
NULL .opsworkscm$associate_node_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ServerName = structure(logical(0), tags = list(type = "string")), NodeName = structure(logical(0), tags = list(type = "string")), EngineAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$associate_node_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NodeAssociationStatusToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$create_backup_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ServerName = structure(logical(0), tags = list(type = "string")), Description = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$create_backup_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Backup = structure(list(BackupArn = structure(logical(0), tags = list(type = "string")), BackupId = structure(logical(0), tags = list(type = "string")), BackupType = structure(logical(0), tags = list(type = "string")), CreatedAt = structure(logical(0), tags = list(type = "timestamp")), Description = structure(logical(0), tags = list(type = "string")), Engine = structure(logical(0), tags = list(type = "string")), EngineModel = structure(logical(0), tags = list(type = "string")), EngineVersion = structure(logical(0), tags = list(type = "string")), InstanceProfileArn = structure(logical(0), tags = list(type = "string")), InstanceType = structure(logical(0), tags = list(type = "string")), KeyPair = structure(logical(0), tags = list(type = "string")), PreferredBackupWindow = structure(logical(0), tags = list(type = "string")), PreferredMaintenanceWindow = structure(logical(0), tags = list(type = "string")), S3DataSize = structure(logical(0), tags = list(deprecated = TRUE, type = "integer")), S3DataUrl = structure(logical(0), tags = list(deprecated = TRUE, type = "string")), S3LogUrl = structure(logical(0), tags = list(type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServerName = structure(logical(0), tags = list(type = "string")), ServiceRoleArn = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), StatusDescription = structure(logical(0), tags = list(type = "string")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ToolsVersion = structure(logical(0), tags = list(type = "string")), UserArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$create_server_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(AssociatePublicIpAddress = structure(logical(0), tags = list(type = "boolean")), CustomDomain = structure(logical(0), tags = list(type = "string")), CustomCertificate = structure(logical(0), tags = list(type = "string")), CustomPrivateKey = structure(logical(0), tags = list(type = "string", sensitive = TRUE)), DisableAutomatedBackup = structure(logical(0), tags = list(type = "boolean")), Engine = structure(logical(0), tags = list(type = "string")), EngineModel = structure(logical(0), tags = list(type = "string")), EngineVersion = structure(logical(0), tags = list(type = "string")), EngineAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list")), BackupRetentionCount = structure(logical(0), tags = list(type = "integer")), ServerName = structure(logical(0), tags = list(type = "string")), InstanceProfileArn = structure(logical(0), tags = list(type = "string")), InstanceType = structure(logical(0), tags = list(type = "string")), KeyPair = structure(logical(0), tags = list(type = "string")), PreferredMaintenanceWindow = structure(logical(0), tags = list(type = "string")), PreferredBackupWindow = structure(logical(0), tags = list(type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServiceRoleArn = structure(logical(0), tags = list(type = "string")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), BackupId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$create_server_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Server = structure(list(AssociatePublicIpAddress = structure(logical(0), tags = list(type = "boolean")), BackupRetentionCount = structure(logical(0), tags = list(type = "integer")), ServerName = structure(logical(0), tags = list(type = "string")), CreatedAt = structure(logical(0), tags = list(type = "timestamp")), CloudFormationStackArn = structure(logical(0), tags = list(type = "string")), CustomDomain = structure(logical(0), tags = list(type = "string")), DisableAutomatedBackup = structure(logical(0), tags = list(type = "boolean")), Endpoint = structure(logical(0), tags = list(type = "string")), Engine = structure(logical(0), tags = list(type = "string")), EngineModel = structure(logical(0), tags = list(type = "string")), EngineAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list")), EngineVersion = structure(logical(0), tags = list(type = "string")), InstanceProfileArn = structure(logical(0), tags = list(type = "string")), InstanceType = structure(logical(0), tags = list(type = "string")), KeyPair = structure(logical(0), tags = list(type = "string")), MaintenanceStatus = structure(logical(0), tags = list(type = "string")), PreferredMaintenanceWindow = structure(logical(0), tags = list(type = "string")), PreferredBackupWindow = structure(logical(0), tags = list(type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServiceRoleArn = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), StatusReason = structure(logical(0), tags = list(type = "string")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServerArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$delete_backup_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$delete_backup_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$delete_server_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ServerName = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$delete_server_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$describe_account_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$describe_account_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Attributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Maximum = structure(logical(0), tags = list(type = "integer")), Used = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$describe_backups_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupId = structure(logical(0), tags = list(type = "string")), ServerName = structure(logical(0), tags = list(type = "string")), NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$describe_backups_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Backups = structure(list(structure(list(BackupArn = structure(logical(0), tags = list(type = "string")), BackupId = structure(logical(0), tags = list(type = "string")), BackupType = structure(logical(0), tags = list(type = "string")), CreatedAt = structure(logical(0), tags = list(type = "timestamp")), Description = structure(logical(0), tags = list(type = "string")), Engine = structure(logical(0), tags = list(type = "string")), EngineModel = structure(logical(0), tags = list(type = "string")), EngineVersion = structure(logical(0), tags = list(type = "string")), InstanceProfileArn = structure(logical(0), tags = list(type = "string")), InstanceType = structure(logical(0), tags = list(type = "string")), KeyPair = structure(logical(0), tags = list(type = "string")), PreferredBackupWindow = structure(logical(0), tags = list(type = "string")), PreferredMaintenanceWindow = structure(logical(0), tags = list(type = "string")), S3DataSize = structure(logical(0), tags = list(deprecated = TRUE, type = "integer")), S3DataUrl = structure(logical(0), tags = list(deprecated = TRUE, type = "string")), S3LogUrl = structure(logical(0), tags = list(type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServerName = structure(logical(0), tags = list(type = "string")), ServiceRoleArn = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), StatusDescription = structure(logical(0), tags = list(type = "string")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ToolsVersion = structure(logical(0), tags = list(type = "string")), UserArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$describe_events_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ServerName = structure(logical(0), tags = list(type = "string")), NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$describe_events_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ServerEvents = structure(list(structure(list(CreatedAt = structure(logical(0), tags = list(type = "timestamp")), ServerName = structure(logical(0), tags = list(type = "string")), Message = structure(logical(0), tags = list(type = "string")), LogUrl = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$describe_node_association_status_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NodeAssociationStatusToken = structure(logical(0), tags = list(type = "string")), ServerName = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$describe_node_association_status_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NodeAssociationStatus = structure(logical(0), tags = list(type = "string")), EngineAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$describe_servers_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ServerName = structure(logical(0), tags = list(type = "string")), NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$describe_servers_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Servers = structure(list(structure(list(AssociatePublicIpAddress = structure(logical(0), tags = list(type = "boolean")), BackupRetentionCount = structure(logical(0), tags = list(type = "integer")), ServerName = structure(logical(0), tags = list(type = "string")), CreatedAt = structure(logical(0), tags = list(type = "timestamp")), CloudFormationStackArn = structure(logical(0), tags = list(type = "string")), CustomDomain = structure(logical(0), tags = list(type = "string")), DisableAutomatedBackup = structure(logical(0), tags = list(type = "boolean")), Endpoint = structure(logical(0), tags = list(type = "string")), Engine = structure(logical(0), tags = list(type = "string")), EngineModel = structure(logical(0), tags = list(type = "string")), EngineAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list")), EngineVersion = structure(logical(0), tags = list(type = "string")), InstanceProfileArn = structure(logical(0), tags = list(type = "string")), InstanceType = structure(logical(0), tags = list(type = "string")), KeyPair = structure(logical(0), tags = list(type = "string")), MaintenanceStatus = structure(logical(0), tags = list(type = "string")), PreferredMaintenanceWindow = structure(logical(0), tags = list(type = "string")), PreferredBackupWindow = structure(logical(0), tags = list(type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServiceRoleArn = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), StatusReason = structure(logical(0), tags = list(type = "string")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServerArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$disassociate_node_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ServerName = structure(logical(0), tags = list(type = "string")), NodeName = structure(logical(0), tags = list(type = "string")), EngineAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$disassociate_node_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(NodeAssociationStatusToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$export_server_engine_attribute_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ExportAttributeName = structure(logical(0), tags = list(type = "string")), ServerName = structure(logical(0), tags = list(type = "string")), InputAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$export_server_engine_attribute_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(EngineAttribute = structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure")), ServerName = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$list_tags_for_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), NextToken = structure(logical(0), tags = list(type = "string")), MaxResults = structure(logical(0), tags = list(type = "integer"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$list_tags_for_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), NextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$restore_server_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(BackupId = structure(logical(0), tags = list(type = "string")), ServerName = structure(logical(0), tags = list(type = "string")), InstanceType = structure(logical(0), tags = list(type = "string")), KeyPair = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$restore_server_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$start_maintenance_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ServerName = structure(logical(0), tags = list(type = "string")), EngineAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$start_maintenance_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Server = structure(list(AssociatePublicIpAddress = structure(logical(0), tags = list(type = "boolean")), BackupRetentionCount = structure(logical(0), tags = list(type = "integer")), ServerName = structure(logical(0), tags = list(type = "string")), CreatedAt = structure(logical(0), tags = list(type = "timestamp")), CloudFormationStackArn = structure(logical(0), tags = list(type = "string")), CustomDomain = structure(logical(0), tags = list(type = "string")), DisableAutomatedBackup = structure(logical(0), tags = list(type = "boolean")), Endpoint = structure(logical(0), tags = list(type = "string")), Engine = structure(logical(0), tags = list(type = "string")), EngineModel = structure(logical(0), tags = list(type = "string")), EngineAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list")), EngineVersion = structure(logical(0), tags = list(type = "string")), InstanceProfileArn = structure(logical(0), tags = list(type = "string")), InstanceType = structure(logical(0), tags = list(type = "string")), KeyPair = structure(logical(0), tags = list(type = "string")), MaintenanceStatus = structure(logical(0), tags = list(type = "string")), PreferredMaintenanceWindow = structure(logical(0), tags = list(type = "string")), PreferredBackupWindow = structure(logical(0), tags = list(type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServiceRoleArn = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), StatusReason = structure(logical(0), tags = list(type = "string")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServerArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$tag_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), Tags = structure(list(structure(list(Key = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$tag_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$untag_resource_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ResourceArn = structure(logical(0), tags = list(type = "string")), TagKeys = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$untag_resource_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$update_server_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(DisableAutomatedBackup = structure(logical(0), tags = list(type = "boolean")), BackupRetentionCount = structure(logical(0), tags = list(type = "integer")), ServerName = structure(logical(0), tags = list(type = "string")), PreferredMaintenanceWindow = structure(logical(0), tags = list(type = "string")), PreferredBackupWindow = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$update_server_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Server = structure(list(AssociatePublicIpAddress = structure(logical(0), tags = list(type = "boolean")), BackupRetentionCount = structure(logical(0), tags = list(type = "integer")), ServerName = structure(logical(0), tags = list(type = "string")), CreatedAt = structure(logical(0), tags = list(type = "timestamp")), CloudFormationStackArn = structure(logical(0), tags = list(type = "string")), CustomDomain = structure(logical(0), tags = list(type = "string")), DisableAutomatedBackup = structure(logical(0), tags = list(type = "boolean")), Endpoint = structure(logical(0), tags = list(type = "string")), Engine = structure(logical(0), tags = list(type = "string")), EngineModel = structure(logical(0), tags = list(type = "string")), EngineAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list")), EngineVersion = structure(logical(0), tags = list(type = "string")), InstanceProfileArn = structure(logical(0), tags = list(type = "string")), InstanceType = structure(logical(0), tags = list(type = "string")), KeyPair = structure(logical(0), tags = list(type = "string")), MaintenanceStatus = structure(logical(0), tags = list(type = "string")), PreferredMaintenanceWindow = structure(logical(0), tags = list(type = "string")), PreferredBackupWindow = structure(logical(0), tags = list(type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServiceRoleArn = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), StatusReason = structure(logical(0), tags = list(type = "string")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServerArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$update_server_engine_attributes_input <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(ServerName = structure(logical(0), tags = list(type = "string")), AttributeName = structure(logical(0), tags = list(type = "string")), AttributeValue = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure")) return(populate(args, shape)) } .opsworkscm$update_server_engine_attributes_output <- function(...) { args <- c(as.list(environment()), list(...)) shape <- structure(list(Server = structure(list(AssociatePublicIpAddress = structure(logical(0), tags = list(type = "boolean")), BackupRetentionCount = structure(logical(0), tags = list(type = "integer")), ServerName = structure(logical(0), tags = list(type = "string")), CreatedAt = structure(logical(0), tags = list(type = "timestamp")), CloudFormationStackArn = structure(logical(0), tags = list(type = "string")), CustomDomain = structure(logical(0), tags = list(type = "string")), DisableAutomatedBackup = structure(logical(0), tags = list(type = "boolean")), Endpoint = structure(logical(0), tags = list(type = "string")), Engine = structure(logical(0), tags = list(type = "string")), EngineModel = structure(logical(0), tags = list(type = "string")), EngineAttributes = structure(list(structure(list(Name = structure(logical(0), tags = list(type = "string")), Value = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))), tags = list(type = "list")), EngineVersion = structure(logical(0), tags = list(type = "string")), InstanceProfileArn = structure(logical(0), tags = list(type = "string")), InstanceType = structure(logical(0), tags = list(type = "string")), KeyPair = structure(logical(0), tags = list(type = "string")), MaintenanceStatus = structure(logical(0), tags = list(type = "string")), PreferredMaintenanceWindow = structure(logical(0), tags = list(type = "string")), PreferredBackupWindow = structure(logical(0), tags = list(type = "string")), SecurityGroupIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServiceRoleArn = structure(logical(0), tags = list(type = "string")), Status = structure(logical(0), tags = list(type = "string")), StatusReason = structure(logical(0), tags = list(type = "string")), SubnetIds = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), ServerArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "structure")) return(populate(args, shape)) }
test_that("r_squared_profiling remains stable", { cycles <- alloy$cycles status <- alloy$status data <- reliability_data(x = cycles, status = status) tbl_john <- estimate_cdf(data, "johnson") threshold <- seq(0, min(cycles[status == 1]) - 0.1, length.out = 100) profile_r2 <- r_squared_profiling.default( x = tbl_john$x[tbl_john$status == 1], y = tbl_john$prob[tbl_john$status == 1], thres = threshold, distribution = "weibull3" ) expect_snapshot_output(profile_r2) }) test_that("rank_regression remains stable", { obs <- seq(10000, 100000, 10000) status <- c(0, 1, 1, 0, 0, 0, 1, 0, 1, 0) data <- reliability_data(x = obs, status = status) tbl_john <- estimate_cdf(data, "johnson") rr <- rank_regression( tbl_john, distribution = "weibull", conf_level = .90 ) expect_snapshot_output(rr$coefficients) expect_snapshot_output(rr$r_squared) expect_snapshot_output(rr) cycles <- c(300, 300, 300, 300, 300, 291, 274, 271, 269, 257, 256, 227, 226, 224, 213, 211, 205, 203, 197, 196, 190, 189, 188, 187, 184, 180, 180, 177, 176, 173, 172, 171, 170, 170, 169, 168, 168, 162, 159, 159, 159, 159, 152, 152, 149, 149, 144, 143, 141, 141, 140, 139, 139, 136, 135, 133, 131, 129, 123, 121, 121, 118, 117, 117, 114, 112, 108, 104, 99, 99, 96, 94) status <- c(rep(0, 5), rep(1, 67)) data <- reliability_data(x = cycles, status = status) tbl_john <- estimate_cdf(data, "johnson") rr <- rank_regression( tbl_john, distribution = "weibull3", conf_level = .90 ) expect_snapshot_output(rr$coefficients) expect_snapshot_output(rr$r_squared) expect_snapshot_output(rr) }) test_that("rank_regression supports multiple methods", { data <- reliability_data(shock, x = "distance", status = "status") methods <- c("johnson", "nelson", "kaplan") cdf_tbl <- estimate_cdf(data, methods) rr <- rank_regression( x = cdf_tbl, distribution = "weibull" ) expect_equal(length(rr), 3) expect_true(all(methods %in% names(rr))) })
matchValues_varLabels <- function(GADSdat, mc_vars, values, label_by_hand = character(0)) { check_GADSdat(GADSdat) if(!is.vector(values) & length(values) > 0) stop("values needs to be a character vector of at least length 1.") values <- unique(values[!is.na(values)]) labels <- unique(extractMeta(GADSdat, mc_vars)[, c("varName", "varLabel")]) if(!all(label_by_hand %in% mc_vars)) stop("All variable names in label_by_hand must be variables in mc_vars.") names(values) <- values matches <- lapply(values, function(value) { out <- labels[grep(value, labels$varLabel), "varName"] if(length(out) > 1) stop("Multiple matches found for ", value, ". There must be always exactly 1 match.") out }) matches <- unlist(matches[sapply(matches, function(x) length(x) > 0)]) matches <- c(matches, label_by_hand) unassigned_mcs <- mc_vars[!mc_vars %in% matches] if(length(unassigned_mcs) > 0) stop("The following mc_vars have not been assigned a value: ", paste(unassigned_mcs, collapse = ", ")) names(mc_vars) <- names(matches)[match(mc_vars, matches)] mc_vars }
testMutationalPatternPair <- function (a, mtx, PRINT=FALSE) { return (testMutationalPatternBinom (mtx[,a[1]], mtx[,a[2]], PRINT=PRINT)) }
new_s2_xptr <- function(x = list(), class = character()) { if (!is.list(x) || is.object(x)) { stop("x must be a bare list of 'externalptr' objects") } class(x) <- union(class, "s2_xptr") x } validate_s2_xptr <- function(x) { type <- vapply(unclass(x), typeof, character(1)) valid_items <- type %in% c("externalptr", "NULL") if (any(!valid_items)) { stop("Items must be externalptr objects or NULL") } invisible(x) } `[.s2_xptr` <- function(x, i) { new_s2_xptr(NextMethod(), class(x)) } `[[.s2_xptr` <- function(x, i) { x[i] } `c.s2_xptr` <- function(...) { dots <- list(...) inherits_first <- vapply(dots, inherits, class(dots[[1]])[1], FUN.VALUE = logical(1)) if (!all(inherits_first)) { stop(sprintf("All items must inherit from '%s'", class(dots[[1]])[1])) } xptr <- new_s2_xptr(NextMethod(), class(dots[[1]])) validate_s2_xptr(xptr) xptr } rep.s2_xptr <- function(x, ...) { if (length(x) == 0) { new_s2_xptr(list(), class(x)) } else { new_s2_xptr(NextMethod(), class(x)) } } rep_len.s2_xptr <- function(x, length.out) { rep(x, length.out = length.out) } as.data.frame.s2_xptr <- function(x, ..., optional = FALSE) { if (!optional) { NextMethod() } else { new_data_frame(list(x)) } } str.s2_xptr <- function(object, ..., indent.str = "", width = getOption("width")) { if (length(object) == 0) { cat(paste0(" ", class(object)[1], "[0]\n")) return(invisible(object)) } width <- width - nchar(indent.str) - 2 length <- min(length(object), ceiling(width / 5)) formatted <- format(object[seq_len(length)], trim = TRUE) title <- paste0(" ", class(object)[1], "[1:", length(object), "]") cat( paste0( title, " ", strtrim(paste0(formatted, collapse = ", "), width - nchar(title)), "\n" ) ) invisible(object) } print.s2_xptr <- function(x, ...) { cat(sprintf("<%s[%s]>\n", class(x)[1], length(x))) if (length(x) == 0) { return(invisible(x)) } out <- stats::setNames(format(x, ...), names(x)) print(out, quote = FALSE) invisible(x) }
knitr::knit("vignettes/AfterFitting.Rmd.orig", output = "vignettes/AfterFitting.Rmd") if (dir.exists("vignettes/figures_AfterFitting")) { unlink("vignettes/figures_AfterFitting", recursive = TRUE) } file.rename(from = "figures_AfterFitting", to = "vignettes/figures_AfterFitting") knitr::knit("vignettes/ModelSpecification.Rmd.orig", output = "vignettes/ModelSpecification.Rmd") if (dir.exists("vignettes/figures_ModelSpecification")) { unlink("vignettes/figures_ModelSpecification", recursive = TRUE) } file.rename(from = "figures_ModelSpecification", to = "vignettes/figures_ModelSpecification") knitr::knit("vignettes/MinimalExample.Rmd.orig", output = "vignettes/MinimalExample.Rmd") if (dir.exists("vignettes/figures_MinimalExample")) { unlink("vignettes/figures_MinimalExample", recursive = TRUE) } file.rename(from = "figures_MinimalExample", to = "vignettes/figures_MinimalExample") knitr::knit("vignettes/SelectingParameters.Rmd.orig", output = "vignettes/SelectingParameters.Rmd") if (dir.exists("vignettes/figures_SelectingParameters")) { unlink("vignettes/figures_SelectingParameters", recursive = TRUE) } file.rename(from = "figures_SelectingParameters", to = "vignettes/figures_SelectingParameters")
collect.disk.frame <- function(x, ..., parallel = !is.null(attr(x,"recordings"))) { cids = get_chunk_ids(x, full.names = TRUE, strip_extension = FALSE) if(nchunks(x) > 0) { if(parallel) { tmp<-future.apply::future_lapply(cids, function(.x) { get_chunk.disk.frame(x, .x, full.names = TRUE) }, future.seed = TRUE) return(rbindlist(tmp)) } else { purrr::map_dfr(cids, ~get_chunk.disk.frame(x, .x, full.names = TRUE)) } } else { data.table() } } collect_list <- function(x, simplify = FALSE, parallel = !is.null(attr(x,"recordings")), ...) { cids = get_chunk_ids(x, full.names = TRUE, strip_extension = FALSE) if(length(cids) > 0) { list_of_results = NULL if (parallel) { list_of_results = future.apply::future_lapply(cids, function(.x) { get_chunk(x, .x, full.names = TRUE) }, future.seed=TRUE) } else { list_of_results = lapply(cids, function(cid) { get_chunk(x, cid, full.names = TRUE) }) } if (simplify) { return(simplify2array(list_of_results)) } else { return(list_of_results) } } else { list() } }
sec2hms <- function (...) { x <- c(...) if (any(x > 3600)) stop("`...` must be <= 3600") hs <- x%%3600 h <- floor(hs) ms <- (hs - h) * 60 m <- floor(ms) s <- floor((ms - m) * 60) hms <- lapply(list(h, m, s), function(x) sprintf("%02d", x)) chron::times(paste(hms[[1]], hms[[2]], hms[[3]], sep=":")) } hijack <- function(FUN, ...){ .FUN <- FUN args <- list(...) invisible(lapply(seq_along(args), function(i) { formals(.FUN)[[names(args)[i]]] <<- args[[i]] })) .FUN } mtabulate <- function (vects) { lev <- sort(unique(unlist(vects))) dat <- do.call(rbind, lapply(vects, function(x, lev) { tabulate(factor(x, levels = lev, ordered = TRUE), nbins = length(lev)) }, lev = lev)) colnames(dat) <- sort(lev) data.frame(dat, check.names = FALSE) } validate_relate <- function(x){ grepl("[\\+\\-\\*\\/]([^_]+)_(.+)", x, perl=TRUE) }
draw_app <- function() { appDir <- system.file("app", package = "rusk") if (appDir == "") { stop("Could not find . Try re-installing `rusk`.", call. = FALSE) } shiny::runApp(appDir, display.mode = "normal") }
x <- list(createTestObj(return.types=TRUE), as.character(1:16)) objSizes <- matrix(0, nrow=length(x[[1]]), ncol=length(x[[2]]), dimnames=x) objLens <- objSizes for (s in seq(ncol(objSizes))) { cat("Doing scale=", s, ": ", sep="") for (i in seq(nrow(objSizes))) { cat("", i) x <- createTestObj(i, s) objSizes[i, s] <- object.size(x) objLens[i, s] <- length(x) } cat("\n") } objSizes objLens
netsplit <- function(x, method, upper = TRUE, reference.group = x$reference.group, baseline.reference = x$baseline.reference, order = NULL, sep.trts = x$sep.trts, quote.trts = "", tol.direct = 0.0005, fixed = x$fixed, random = x$random, backtransf = x$backtransf, warn = FALSE, warn.deprecated = gs("warn.deprecated"), verbose = FALSE, ...) { chkclass(x, "netmeta") x <- updateversion(x) is.bin <- inherits(x, "netmetabin") if (!missing(method)) method <- setchar(method, c("Back-calculation", "SIDDE")) else { if (is.bin) method <- "SIDDE" else method <- "Back-calculation" } chklogical(upper) chklogical(baseline.reference) if (!is.null(order)) { order <- setseq(order, x$trts) baseline.reference <- FALSE reference.group <- "" } chkchar(sep.trts) chkchar(quote.trts) chknumeric(tol.direct, min = 0, length = 1) if (!is.null(backtransf)) chklogical(backtransf) chklogical(warn) chklogical(verbose) args <- list(...) chklogical(warn.deprecated) fixed <- deprecated(fixed, missing(fixed), args, "comb.fixed", warn.deprecated) chklogical(fixed) fixed.logical <- fixed random <- deprecated(random, missing(random), args, "comb.random", warn.deprecated) chklogical(random) random.logical <- random seq.comps <- rownames(x$Cov.fixed) dat.trts <- matrix(unlist(compsplit(seq.comps, x$sep.trts)), ncol = 2, byrow = TRUE) dat.trts <- as.data.frame(dat.trts, stringsAsFactors = FALSE) names(dat.trts) <- c("treat1", "treat2") if (!upper) { t1 <- dat.trts$treat1 dat.trts$treat1 <- dat.trts$treat2 dat.trts$treat2 <- t1 } if (is.null(order)) { wo <- rep_len(FALSE, length(seq.comps)) if (reference.group != "") { reference.group <- setref(reference.group, colnames(x$TE.fixed)) if (baseline.reference) wo <- dat.trts$treat1 == reference.group else wo <- dat.trts$treat2 == reference.group } else if (!missing(baseline.reference)) warning("Argument 'baseline.reference' ignored as ", "reference group is not defined ", "(argument 'reference.group').") if (any(wo)) { t1.wo <- dat.trts$treat1[wo] dat.trts$treat1[wo] <- dat.trts$treat2[wo] dat.trts$treat2[wo] <- t1.wo } } else { treat1.pos <- as.numeric(factor(dat.trts$treat1, levels = order)) treat2.pos <- as.numeric(factor(dat.trts$treat2, levels = order)) wo <- treat1.pos > treat2.pos if (any(wo)) { ttreat1 <- dat.trts$treat1 dat.trts$treat1[wo] <- dat.trts$treat2[wo] dat.trts$treat2[wo] <- ttreat1[wo] ttreat1.pos <- treat1.pos treat1.pos[wo] <- treat2.pos[wo] treat2.pos[wo] <- ttreat1.pos[wo] } o <- order(treat1.pos, treat2.pos) dat.trts <- dat.trts[o, ] } comparison <- as.character(interaction(paste(quote.trts, dat.trts$treat1, quote.trts, sep = ""), paste(quote.trts, dat.trts$treat2, quote.trts, sep = ""), sep = sep.trts)) if (!(is.bin & method == "SIDDE")) { prop.direct.fixed <- rep_len(NA, length(x$prop.direct.fixed)) seq.comps.fixed <- names(x$prop.direct.fixed) trts.fixed <- matrix(unlist(compsplit(seq.comps.fixed, x$sep.trts)), ncol = 2, byrow = TRUE) trts.fixed <- as.data.frame(trts.fixed, stringsAsFactors = FALSE) names(trts.fixed) <- c("treat1", "treat2") for (i in seq_along(comparison)) { sel.i <- (trts.fixed$treat1 == dat.trts$treat1[i] & trts.fixed$treat2 == dat.trts$treat2[i]) | (trts.fixed$treat1 == dat.trts$treat2[i] & trts.fixed$treat2 == dat.trts$treat1[i]) prop.direct.fixed[i] <- x$prop.direct.fixed[sel.i] } prop.direct.random <- rep_len(NA, length(x$prop.direct.random)) seq.comps.random <- names(x$prop.direct.random) trts.random <- matrix(unlist(compsplit(seq.comps.random, x$sep.trts)), ncol = 2, byrow = TRUE) trts.random <- as.data.frame(trts.random, stringsAsFactors = FALSE) names(trts.random) <- c("treat1", "treat2") for (i in seq_along(comparison)) { sel.i <- (trts.random$treat1 == dat.trts$treat1[i] & trts.random$treat2 == dat.trts$treat2[i]) | (trts.random$treat1 == dat.trts$treat2[i] & trts.random$treat2 == dat.trts$treat1[i]) prop.direct.random[i] <- x$prop.direct.random[sel.i] } } if (method == "Back-calculation") { sel.one.fixed <- abs(x$P.fixed - 1) < tol.direct TE.indirect.fixed <- x$TE.indirect.fixed seTE.indirect.fixed <- x$seTE.indirect.fixed lower.indirect.fixed <- x$lower.indirect.fixed upper.indirect.fixed <- x$upper.indirect.fixed statistic.indirect.fixed <- x$statistic.indirect.fixed pval.indirect.fixed <- x$pval.indirect.fixed TE.indirect.fixed[sel.one.fixed] <- NA seTE.indirect.fixed[sel.one.fixed] <- NA lower.indirect.fixed[sel.one.fixed] <- NA upper.indirect.fixed[sel.one.fixed] <- NA statistic.indirect.fixed[sel.one.fixed] <- NA pval.indirect.fixed[sel.one.fixed] <- NA sel.one.random <- abs(x$P.random - 1) < tol.direct TE.indirect.random <- x$TE.indirect.random seTE.indirect.random <- x$seTE.indirect.random lower.indirect.random <- x$lower.indirect.random upper.indirect.random <- x$upper.indirect.random statistic.indirect.random <- x$statistic.indirect.random pval.indirect.random <- x$pval.indirect.random TE.indirect.random[sel.one.random] <- NA seTE.indirect.random[sel.one.random] <- NA lower.indirect.random[sel.one.random] <- NA upper.indirect.random[sel.one.random] <- NA statistic.indirect.random[sel.one.random] <- NA pval.indirect.random[sel.one.random] <- NA } is.tictoc <- FALSE if (method == "SIDDE") { if (is.null(x$data)) stop("SIDDE method only available for network meta-analysis objects ", "created with argument 'keepdata' equal to TRUE.") if (verbose) cat("Start computations for SIDDE approach\n") is.tictoc <- is.installed.package("tictoc", stop = FALSE) dat <- x$data dat <- dat[order(dat$.studlab, dat$.treat1, dat$.treat2), ] if (!is.null(dat$.subset)) dat <- dat[dat$.subset, , drop = FALSE] if (!is.null(dat$.drop)) dat <- dat[!dat$.drop, , drop = FALSE] idx.d <- which(!is.na(x$TE.direct.fixed), arr.ind = TRUE) idx.d <- idx.d[idx.d[, 1] < idx.d[, 2], , drop = FALSE] rownames(idx.d) <- seq_len(nrow(idx.d)) idx1 <- idx.d[, 1] idx2 <- idx.d[, 2] n.comps <- nrow(idx.d) trts <- x$trts TE.indirect.fixed <- x$TE.direct.fixed TE.indirect.fixed[!is.na(TE.indirect.fixed)] <- NA seTE.indirect.fixed <- TE.indirect.fixed TE.indirect.random <- x$TE.direct.random TE.indirect.random[!is.na(TE.indirect.random)] <- NA seTE.indirect.random <- TE.indirect.random if (is.tictoc) { tictoc <- rep(NA, n.comps) names.tictoc <- "" } for (i in seq_len(n.comps)) { idx1.i <- idx1[i] idx2.i <- idx2[i] if (is.tictoc) tictoc::tic() if (verbose) cat(paste0("- ", paste(trts[idx1.i], trts[idx2.i], sep = sep.trts), " (", i, "/", n.comps, ")\n")) drop.i <- (dat$.treat1 == trts[idx1.i] & dat$.treat2 == trts[idx2.i]) | (dat$.treat2 == trts[idx1.i] & dat$.treat1 == trts[idx2.i]) drop.studies <- unique(dat$.studlab[drop.i]) dat.i <- dat[!(dat$.studlab %in% drop.studies), , drop = FALSE] dat.i$.design <- NULL if (nrow(dat.i) > 0) con <- netconnection(dat.i$.treat1, dat.i$.treat2, dat.i$.studlab) else con <- list(n.subnets = 0) if (con$n.subnets == 1) { if (is.bin) net.i <- netmetabin(dat.i$.event1, dat.i$.n1, dat.i$.event2, dat.i$.n2, dat.i$.treat1, dat.i$.treat2, dat.i$.studlab, data = dat.i, sm = x$sm, method = x$method, fixed = fixed.logical, random = random.logical, warn = warn) else net.i <- netmeta(dat.i$.TE, dat.i$.seTE, dat.i$.treat1, dat.i$.treat2, dat.i$.studlab, data = dat.i, fixed = fixed.logical, random = random.logical, warn = warn) if (trts[idx1.i] %in% rownames(net.i$TE.fixed) & trts[idx2.i] %in% colnames(net.i$TE.fixed)) { TE.indirect.fixed[idx1.i, idx2.i] <- net.i$TE.fixed[trts[idx1.i], trts[idx2.i]] TE.indirect.fixed[idx2.i, idx1.i] <- net.i$TE.fixed[trts[idx2.i], trts[idx1.i]] seTE.indirect.fixed[idx1.i, idx2.i] <- seTE.indirect.fixed[idx2.i, idx1.i] <- net.i$seTE.fixed[trts[idx1.i], trts[idx2.i]] } if (!is.bin) { if (trts[idx1.i] %in% rownames(net.i$TE.random) & trts[idx2.i] %in% colnames(net.i$TE.random)) { TE.indirect.random[idx1.i, idx2.i] <- net.i$TE.random[trts[idx1.i], trts[idx2.i]] TE.indirect.random[idx2.i, idx1.i] <- net.i$TE.random[trts[idx2.i], trts[idx1.i]] seTE.indirect.random[idx1.i, idx2.i] <- seTE.indirect.random[idx2.i, idx1.i] <- net.i$seTE.random[trts[idx1.i], trts[idx2.i]] } } } if (is.tictoc) { tictoc.i <- tictoc::toc(func.toc = NULL) tictoc[i] <- as.numeric(tictoc.i$toc) - as.numeric(tictoc.i$tic) names.tictoc[i] <- paste(trts[idx1.i], trts[idx2.i], sep = sep.trts) if (verbose) cat(paste(round(tictoc[i], 3), "sec elapsed\n")) } } ci.if <- ci(TE.indirect.fixed, seTE.indirect.fixed, x$level.ma) lower.indirect.fixed <- ci.if$lower upper.indirect.fixed <- ci.if$upper statistic.indirect.fixed <- ci.if$statistic pval.indirect.fixed <- ci.if$p if (!is.bin) { ci.ir <- ci(TE.indirect.random, seTE.indirect.random, x$level.ma) lower.indirect.random <- ci.ir$lower upper.indirect.random <- ci.ir$upper statistic.indirect.random <- ci.ir$statistic pval.indirect.random <- ci.ir$p } } TE.direct.fixed <- x$TE.direct.fixed seTE.direct.fixed <- x$seTE.direct.fixed lower.direct.fixed <- x$lower.direct.fixed upper.direct.fixed <- x$upper.direct.fixed statistic.direct.fixed <- x$statistic.direct.fixed pval.direct.fixed <- x$pval.direct.fixed if (!is.null(x$P.fixed)) { sel.zero.fixed <- abs(x$P.fixed) < tol.direct TE.direct.fixed[sel.zero.fixed] <- NA seTE.direct.fixed[sel.zero.fixed] <- NA lower.direct.fixed[sel.zero.fixed] <- NA upper.direct.fixed[sel.zero.fixed] <- NA statistic.direct.fixed[sel.zero.fixed] <- NA pval.direct.fixed[sel.zero.fixed] <- NA } TE.direct.random <- x$TE.direct.random seTE.direct.random <- x$seTE.direct.random lower.direct.random <- x$lower.direct.random upper.direct.random <- x$upper.direct.random statistic.direct.random <- x$statistic.direct.random pval.direct.random <- x$pval.direct.random if (!is.null(x$P.random)) { sel.zero.random <- abs(x$P.random) < tol.direct TE.direct.random[sel.zero.random] <- NA seTE.direct.random[sel.zero.random] <- NA lower.direct.random[sel.zero.random] <- NA upper.direct.random[sel.zero.random] <- NA statistic.direct.random[sel.zero.random] <- NA pval.direct.random[sel.zero.random] <- NA } fixed <- direct.fixed <- indirect.fixed <- data.frame(comparison, TE = NA, seTE = NA, lower = NA, upper = NA, statistic = NA, p = NA, stringsAsFactors = FALSE) direct.fixed$I2 <- direct.fixed$tau <- direct.fixed$tau2 <- direct.fixed$Q <- NA k <- rep_len(NA, length(comparison)) for (i in seq_along(comparison)) { t1.i <- dat.trts$treat1[i] t2.i <- dat.trts$treat2[i] fixed$TE[i] <- x$TE.fixed[t1.i, t2.i] fixed$seTE[i] <- x$seTE.fixed[t1.i, t2.i] fixed$lower[i] <- x$lower.fixed[t1.i, t2.i] fixed$upper[i] <- x$upper.fixed[t1.i, t2.i] fixed$statistic[i] <- x$statistic.fixed[t1.i, t2.i] fixed$p[i] <- x$pval.fixed[t1.i, t2.i] k[i] <- x$A.matrix[t1.i, t2.i] direct.fixed$TE[i] <- TE.direct.fixed[t1.i, t2.i] direct.fixed$seTE[i] <- seTE.direct.fixed[t1.i, t2.i] direct.fixed$lower[i] <- lower.direct.fixed[t1.i, t2.i] direct.fixed$upper[i] <- upper.direct.fixed[t1.i, t2.i] direct.fixed$statistic[i] <- statistic.direct.fixed[t1.i, t2.i] direct.fixed$p[i] <- pval.direct.fixed[t1.i, t2.i] direct.fixed$Q[i] <- x$Q.direct[t1.i, t2.i] direct.fixed$tau2[i] <- x$tau2.direct[t1.i, t2.i] direct.fixed$tau[i] <- x$tau.direct[t1.i, t2.i] direct.fixed$I2[i] <- x$I2.direct[t1.i, t2.i] indirect.fixed$TE[i] <- TE.indirect.fixed[t1.i, t2.i] indirect.fixed$seTE[i] <- seTE.indirect.fixed[t1.i, t2.i] indirect.fixed$lower[i] <- lower.indirect.fixed[t1.i, t2.i] indirect.fixed$upper[i] <- upper.indirect.fixed[t1.i, t2.i] indirect.fixed$statistic[i] <- statistic.indirect.fixed[t1.i, t2.i] indirect.fixed$p[i] <- pval.indirect.fixed[t1.i, t2.i] } m.fixed <- suppressWarnings(metagen(direct.fixed$TE - indirect.fixed$TE, sqrt(direct.fixed$seTE^2 + indirect.fixed$seTE^2), level = x$level.ma, method.tau = "DL", method.tau.ci = "")) compare.fixed <- data.frame(comparison, TE = m.fixed$TE, seTE = m.fixed$seTE, lower = m.fixed$lower, upper = m.fixed$upper, statistic = m.fixed$statistic, p = m.fixed$pval, z = m.fixed$statistic, stringsAsFactors = FALSE) sel.k0 <- k == 0 vars <- c("TE", "seTE", "lower", "upper", "statistic", "p") indirect.fixed[sel.k0, vars] <- fixed[sel.k0, vars] if (!is.bin) { random <- direct.random <- indirect.random <- data.frame(comparison, TE = NA, seTE = NA, lower = NA, upper = NA, statistic = NA, p = NA, stringsAsFactors = FALSE) predict <- data.frame(comparison, lower = NA, upper = NA, stringsAsFactors = FALSE) direct.random$I2 <- direct.random$tau <- direct.random$tau2 <- direct.random$Q <- NA for (i in seq_along(comparison)) { t1.i <- dat.trts$treat1[i] t2.i <- dat.trts$treat2[i] random$TE[i] <- x$TE.random[t1.i, t2.i] random$seTE[i] <- x$seTE.random[t1.i, t2.i] random$lower[i] <- x$lower.random[t1.i, t2.i] random$upper[i] <- x$upper.random[t1.i, t2.i] random$statistic[i] <- x$statistic.random[t1.i, t2.i] random$p[i] <- x$pval.random[t1.i, t2.i] direct.random$TE[i] <- TE.direct.random[t1.i, t2.i] direct.random$seTE[i] <- seTE.direct.random[t1.i, t2.i] direct.random$lower[i] <- lower.direct.random[t1.i, t2.i] direct.random$upper[i] <- upper.direct.random[t1.i, t2.i] direct.random$statistic[i] <- statistic.direct.random[t1.i, t2.i] direct.random$p[i] <- pval.direct.random[t1.i, t2.i] direct.random$Q[i] <- x$Q.direct[t1.i, t2.i] direct.random$tau2[i] <- x$tau2.direct[t1.i, t2.i] direct.random$tau[i] <- x$tau.direct[t1.i, t2.i] direct.random$I2[i] <- x$I2.direct[t1.i, t2.i] indirect.random$TE[i] <- TE.indirect.random[t1.i, t2.i] indirect.random$seTE[i] <- seTE.indirect.random[t1.i, t2.i] indirect.random$lower[i] <- lower.indirect.random[t1.i, t2.i] indirect.random$upper[i] <- upper.indirect.random[t1.i, t2.i] indirect.random$statistic[i] <- statistic.indirect.random[t1.i, t2.i] indirect.random$p[i] <- pval.indirect.random[t1.i, t2.i] predict$lower[i] <- x$lower.predict[t1.i, t2.i] predict$upper[i] <- x$upper.predict[t1.i, t2.i] } m.random <- suppressWarnings(metagen(direct.random$TE - indirect.random$TE, sqrt(direct.random$seTE^2 + indirect.random$seTE^2), level = x$level.ma, method.tau = "DL", method.tau.ci = "")) compare.random <- data.frame(comparison, TE = m.random$TE, seTE = m.random$seTE, lower = m.random$lower, upper = m.random$upper, statistic = m.random$statistic, p = m.random$pval, z = m.random$statistic, stringsAsFactors = FALSE) indirect.random[sel.k0, vars] <- random[sel.k0, vars] } else { random <- fixed random[!is.na(random)] <- NA random$comparison <- comparison direct.random <- indirect.random <- compare.random <- random predict <- random[, c("comparison", "lower", "upper")] } x$fixed <- fixed.logical x$random <- random.logical res <- list(comparison = comparison, k = k, prop.fixed = if (is.bin & method == "SIDDE") NULL else prop.direct.fixed, fixed = fixed, direct.fixed = direct.fixed, indirect.fixed = indirect.fixed, compare.fixed = compare.fixed, prop.random = if (is.bin & method == "SIDDE") NULL else prop.direct.random, random = random, direct.random = direct.random, indirect.random = indirect.random, compare.random = compare.random, predict = predict, method = method, sm = x$sm, level.ma = x$level.ma, prediction = x$prediction, level.predict = x$level.predict, tau = x$tau, reference.group = reference.group, baseline.reference = baseline.reference, order = order, sep.trts = sep.trts, quote.trts = quote.trts, nchar.trts = x$nchar.trts, tol.direct = tol.direct, backtransf = backtransf, x = x, version = packageDescription("netmeta")$Version ) if (is.tictoc) { res$tictoc <- tictoc names(res$tictoc) <- names.tictoc } class(res) <- c("netsplit", if (is.bin & method == "SIDDE") "netsplit.netmetabin") res } print.netsplit <- function(x, fixed = x$x$fixed, random = x$x$random, show = "all", overall = TRUE, ci = FALSE, test = show %in% c("all", "with.direct", "both"), only.reference = FALSE, sortvar = NULL, nchar.trts = x$nchar.trts, digits = gs("digits"), digits.stat = gs("digits.stat"), digits.pval = gs("digits.pval"), digits.prop = max(gs("digits.pval") - 2, 2), text.NA = ".", backtransf = x$backtransf, scientific.pval = gs("scientific.pval"), big.mark = gs("big.mark"), legend = TRUE, warn.deprecated = gs("warn.deprecated"), ...) { chkclass(x, "netsplit") x <- updateversion(x) is.bin <- inherits(x, "netsplit.netmetabin") oldopts <- options(width = 200) on.exit(options(oldopts)) chklogical(overall) chklogical(ci) chklogical(test) missing.only.reference <- missing(only.reference) if (!missing.only.reference) chklogical(only.reference) mf <- match.call() error <- try(sortvar.x <- eval(mf[[match("sortvar", names(mf))]], x, enclos = sys.frame(sys.parent())), silent = TRUE) if (!any(class(error) == "try-error")) sortvar <- sortvar.x if (!is.null(sortvar)) { if (length(dim(sortvar)) == 2) { if (dim(sortvar)[1] != length(x$comparison)) stop("Argument 'sortvar' must be of length ", length(x$comparison), ".", call. = FALSE) if (is.numeric(sortvar)) { sortvar[is.zero(abs(sortvar), n = 1000)] <- 0 sortvar[is.zero(1 - abs(sortvar), n = 1000)] <- 1 * sign(sortvar)[is.zero(1 - abs(sortvar), n = 1000)] } sortvar <- order(do.call(order, as.list(as.data.frame(sortvar)))) } else chklength(sortvar, length(x$comparison), text = paste0("Argument 'sortvar' must be of length ", length(x$comparison), ".")) if (!is.numeric(sortvar)) sortvar <- setchar(sortvar, x$comparison) } if (is.null(nchar.trts)) nchar.trts <- 666 chknumeric(nchar.trts, length = 1) chknumeric(digits, min = 0, length = 1) chknumeric(digits.stat, min = 0, length = 1) chknumeric(digits.pval, min = 1, length = 1) chknumeric(digits.prop, min = 0, length = 1) if (is.null(backtransf)) backtransf <- TRUE chklogical(backtransf) chklogical(scientific.pval) chklogical(legend) fun <- "print.netmeta" args <- list(...) chklogical(warn.deprecated) fixed <- deprecated(fixed, missing(fixed), args, "comb.fixed", warn.deprecated) chklogical(fixed) fixed.logical <- fixed random <- deprecated(random, missing(random), args, "comb.random", warn.deprecated) chklogical(random) random.logical <- random show <- deprecated(show, missing(show), args, "showall") if (is.logical(show)) if (show) show <- "all" else show <- "both" show <- setchar(show, c("all", "both", "with.direct", "direct.only", "indirect.only", "reference.only")) if (show == "reference.only") { warning("Argument 'show = \"reference.only\" replaced with ", "'only.reference = TRUE'.", call. = FALSE) show <- "both" if (missing.only.reference) only.reference <- TRUE } sm <- x$sm sm.lab <- sm relative <- is.relative.effect(sm) if (!backtransf & relative) sm.lab <- paste("log", sm, sep = "") if (!(sm.lab == "" | sm.lab == "log")) sm.lab <- paste("(", sm.lab, ") ", sep = "") else sm.lab <- "" level.ma <- x$level.ma ci.lab <- paste(100 * level.ma, "%-CI", sep ="") random.available <- !is.null(x$random) if (!random.available & random) { warning("No results for random effects model available. ", "Argument 'random' set to FALSE.", call. = FALSE) random <- FALSE } if (show == "all") sel <- rep_len(TRUE, length(x$direct.fixed$TE)) else if (show == "with.direct") sel <- !is.na(x$direct.fixed$TE) else if (show == "both") sel <- !is.na(x$direct.fixed$TE) & !is.na(x$indirect.fixed$TE) else if (show == "direct.only") sel <- !is.na(x$direct.fixed$TE) & is.na(x$indirect.fixed$TE) else if (show == "indirect.only") sel <- is.na(x$direct.fixed$TE) & !is.na(x$fixed$TE) if (only.reference) { if (x$reference.group == "") { warning("First treatment used as reference as argument ", "'reference.group' was unspecified in netsplit().", call. = FALSE) x$reference.group <- compsplit(x$comparison, x$sep.trts)[[1]][1] } sel.ref <- apply(!is.na(sapply(compsplit(x$comparison, x$sep.trts), match, x$reference.group)), 2, sum) >= 1 sel <- sel & sel.ref } comp <- x$comparison[sel] k <- x$k[sel] prop.fixed <- x$prop.fixed[sel] TE.fixed <- x$fixed$TE[sel] lower.fixed <- x$fixed$lower[sel] upper.fixed <- x$fixed$upper[sel] TE.direct.fixed <- x$direct.fixed$TE[sel] lower.direct.fixed <- x$direct.fixed$lower[sel] upper.direct.fixed <- x$direct.fixed$upper[sel] TE.indirect.fixed <- x$indirect.fixed$TE[sel] lower.indirect.fixed <- x$indirect.fixed$lower[sel] upper.indirect.fixed <- x$indirect.fixed$upper[sel] TE.compare.fixed <- x$compare.fixed$TE[sel] lower.compare.fixed <- x$compare.fixed$lower[sel] upper.compare.fixed <- x$compare.fixed$upper[sel] statistic.compare.fixed <- x$compare.fixed$statistic[sel] pval.compare.fixed <- x$compare.fixed$p[sel] if (random.available) { prop.random <- x$prop.random[sel] TE.random <- x$random$TE[sel] lower.random <- x$random$lower[sel] upper.random <- x$random$upper[sel] TE.direct.random <- x$direct.random$TE[sel] lower.direct.random <- x$direct.random$lower[sel] upper.direct.random <- x$direct.random$upper[sel] TE.indirect.random <- x$indirect.random$TE[sel] lower.indirect.random <- x$indirect.random$lower[sel] upper.indirect.random <- x$indirect.random$upper[sel] TE.compare.random <- x$compare.random$TE[sel] lower.compare.random <- x$compare.random$lower[sel] upper.compare.random <- x$compare.random$upper[sel] statistic.compare.random <- x$compare.random$statistic[sel] pval.compare.random <- x$compare.random$p[sel] } if (backtransf & relative) { TE.fixed <- exp(TE.fixed) lower.fixed <- exp(lower.fixed) upper.fixed <- exp(upper.fixed) TE.direct.fixed <- exp(TE.direct.fixed) lower.direct.fixed <- exp(lower.direct.fixed) upper.direct.fixed <- exp(upper.direct.fixed) TE.indirect.fixed <- exp(TE.indirect.fixed) lower.indirect.fixed <- exp(lower.indirect.fixed) upper.indirect.fixed <- exp(upper.indirect.fixed) TE.compare.fixed <- exp(TE.compare.fixed) lower.compare.fixed <- exp(lower.compare.fixed) upper.compare.fixed <- exp(upper.compare.fixed) if (random.available) { TE.random <- exp(TE.random) lower.random <- exp(lower.random) upper.random <- exp(upper.random) TE.direct.random <- exp(TE.direct.random) lower.direct.random <- exp(lower.direct.random) upper.direct.random <- exp(upper.direct.random) TE.indirect.random <- exp(TE.indirect.random) lower.indirect.random <- exp(lower.indirect.random) upper.indirect.random <- exp(upper.indirect.random) TE.compare.random <- exp(TE.compare.random) lower.compare.random <- exp(lower.compare.random) upper.compare.random <- exp(upper.compare.random) } } fixed <- list(comp = comp, k = k, prop = formatPT(prop.fixed, digits = digits.prop)) names.fixed <- c("comparison", "k", "prop") if (overall) { fixed$TE.fixed <- formatN(TE.fixed, digits, text.NA = text.NA, big.mark = big.mark) names.fixed <- c(names.fixed, "nma") if (ci) { fixed$ci.fixed <- formatCI(round(lower.fixed, digits), round(upper.fixed, digits)) fixed$ci.fixed[is.na(fixed$ci.fixed)] <- text.NA names.fixed <- c(names.fixed, ci.lab) } } fixed$TE.direct.fixed <- formatN(TE.direct.fixed, digits, text.NA = text.NA, big.mark = big.mark) names.fixed <- c(names.fixed, "direct") if (ci) { fixed$ci.direct.fixed <- formatCI(round(lower.direct.fixed, digits), round(upper.direct.fixed, digits)) fixed$ci.direct.fixed[is.na(fixed$ci.direct.fixed)] <- text.NA names.fixed <- c(names.fixed, ci.lab) } fixed$TE.indirect.fixed <- formatN(TE.indirect.fixed, digits, text.NA = text.NA, big.mark = big.mark) names.fixed <- c(names.fixed, "indir.") if (ci) { fixed$ci.indirect.fixed <- formatCI(round(lower.indirect.fixed, digits), round(upper.indirect.fixed, digits)) fixed$ci.indirect.fixed[is.na(fixed$ci.indirect.fixed)] <- text.NA names.fixed <- c(names.fixed, ci.lab) } if (test) { fixed$diff <- formatN(TE.compare.fixed, digits, text.NA = text.NA, big.mark = big.mark) names.fixed <- c(names.fixed, if (backtransf & relative) "RoR" else "Diff") if (ci) { fixed$ci.diff <- formatCI(round(lower.compare.fixed, digits), round(upper.compare.fixed, digits)) fixed$ci.diff[is.na(fixed$ci.diff)] <- text.NA names.fixed <- c(names.fixed, ci.lab) } fixed$statistic <- formatN(statistic.compare.fixed, digits.stat, big.mark = big.mark) fixed$statistic[fixed$statistic == "--"] <- text.NA fixed$p <- formatPT(pval.compare.fixed, digits = digits.pval, scientific = scientific.pval) fixed$p[rmSpace(fixed$p) == "--"] <- text.NA names.fixed <- c(names.fixed, c("z", "p-value")) } fixed <- as.data.frame(fixed) names(fixed) <- names.fixed if (random.available) { random.logical <- random random <- list(comp = comp, k = k, prop = formatPT(prop.random, digits = digits.prop)) names.random <- c("comparison", "k", "prop") if (overall) { random$TE.random <- formatN(TE.random, digits, text.NA = text.NA, big.mark = big.mark) names.random <- c(names.random, "nma") if (ci) { random$ci.random <- formatCI(round(lower.random, digits), round(upper.random, digits)) random$ci.random[is.na(random$ci.random)] <- text.NA names.random <- c(names.random, ci.lab) } } random$TE.direct.random <- formatN(TE.direct.random, digits, text.NA = text.NA, big.mark = big.mark) names.random <- c(names.random, "direct") if (ci) { random$ci.direct.random <- formatCI(round(lower.direct.random, digits), round(upper.direct.random, digits)) random$ci.direct.random[is.na(random$ci.direct.random)] <- text.NA names.random <- c(names.random, ci.lab) } random$TE.indirect.random <- formatN(TE.indirect.random, digits, text.NA = text.NA, big.mark = big.mark) names.random <- c(names.random, "indir.") if (ci) { random$ci.indirect.random <- formatCI(round(lower.indirect.random, digits), round(upper.indirect.random, digits)) random$ci.indirect.random[is.na(random$ci.indirect.random)] <- text.NA names.random <- c(names.random, ci.lab) } if (test) { random$diff <- formatN(TE.compare.random, digits, text.NA = text.NA, big.mark = big.mark) names.random <- c(names.random, if (backtransf & relative) "RoR" else "Diff") if (ci) { random$ci.diff <- formatCI(round(lower.compare.random, digits), round(upper.compare.random, digits)) random$ci.diff[is.na(random$ci.diff)] <- text.NA names.random <- c(names.random, ci.lab) } random$statistic <- formatN(statistic.compare.random, digits.stat, big.mark = big.mark) random$statistic[random$statistic == "--"] <- text.NA random$p <- formatPT(pval.compare.random, digits = digits.pval, scientific = scientific.pval) random$p[rmSpace(random$p) == "--"] <- text.NA names.random <- c(names.random, c("z", "p-value")) } random <- as.data.frame(random) names(random) <- names.random } noprop <- is.bin | x$method == "SIDDE" | all(fixed$prop == "") if (noprop) { fixed <- fixed[, !(names(fixed) %in% "prop")] if (random.available) random <- random[, !(names(random) %in% "prop")] } if (!is.null(sortvar)) { sortvar <- sortvar[sel] o <- order(sortvar) if (fixed.logical) fixed <- fixed[o, ] if (random.logical) random <- random[o, ] } if (fixed.logical | random.logical) { if (x$method == "SIDDE") cat("Separate indirect from direct design evidence (SIDDE)\n\n") else cat(paste("Separate indirect from direct evidence (SIDE)", "using back-calculation method\n\n")) } else legend <- FALSE if (fixed.logical) { cat("Fixed effects model: \n\n") fixed[is.na(fixed)] <- text.NA trts <- unique(sort(unlist(compsplit(fixed$comparison, x$sep.trts)))) fixed$comparison <- comps(fixed$comparison, trts, x$sep.trts, nchar.trts) prmatrix(fixed, quote = FALSE, right = TRUE, rowlab = rep("", dim(fixed)[1])) if (random.logical) cat("\n") } if (random.logical) { cat("Random effects model: \n\n") random[is.na(random)] <- text.NA trts <- unique(sort(unlist(compsplit(random$comparison, x$sep.trts)))) random$comparison <- comps(random$comparison, trts, x$sep.trts, nchar.trts) prmatrix(random, quote = FALSE, right = TRUE, rowlab = rep("", dim(random)[1])) } if (legend) { cat("\nLegend:\n") cat(" comparison - Treatment comparison\n") cat(" k - Number of studies providing direct evidence\n") if (!noprop) cat(" prop - Direct evidence proportion\n") if (overall) cat(paste(" nma - Estimated treatment effect ", sm.lab, "in network meta-analysis\n", sep = "")) cat(paste(" direct - Estimated treatment effect ", sm.lab, "derived from direct evidence\n", sep = "")) cat(paste(" indir. - Estimated treatment effect ", sm.lab, "derived from indirect evidence\n", sep = "")) if (test) { if (backtransf & relative) cat(" RoR - Ratio of Ratios (direct versus indirect)\n") else cat(" Diff - Difference between direct and indirect treatment estimates\n") cat(" z - z-value of test for disagreement (direct versus indirect)\n") cat(" p-value - p-value of test for disagreement (direct versus indirect)\n") } trts.abbr <- treats(trts, nchar.trts) diff.trts <- trts != trts.abbr if (any(diff.trts)) { cat("\n") tmat <- data.frame(trts.abbr, trts) names(tmat) <- c("Abbreviation", "Treatment name") tmat <- tmat[diff.trts, ] tmat <- tmat[order(tmat$Abbreviation), ] prmatrix(tmat, quote = FALSE, right = TRUE, rowlab = rep("", length(trts.abbr))) } } invisible(NULL) }
fitAdaptRandom2 <- function(outcomes,freq,nclass=2,initoutcomep,initclassp,initlambdacoef,initltaucoef, level2size,constload,calcSE=FALSE,justEM,gh,probit,byclass,qniterations, penalty,EMtol,verbose=FALSE) { outcomes <- as.matrix(outcomes) mode(outcomes) <- "integer" momentdata <- replicate(nclass, NULL) nlevel1 <- level2size nlevel2 <- dim(outcomes)[2]/level2size nlevel3 <- length(freq) if (constload) nlambda <- 1 else nlambda <- nlevel1 outcomestart <- nclass outcomeend <- (nclass+nlevel1*nlevel2*nclass-1) if (byclass) { lambdastart <- (nlevel1*nlevel2*nclass+nclass) lambdaend <- (nlevel1*nlevel1*nclass+nclass+nclass*nlambda-1) taustart <- (nlevel1*nlevel2*nclass+nclass+nclass*nlambda) tauend <- (nlevel1*nlevel2*nclass+nclass+nclass*nlambda+nclass-1) } else { lambdastart <- (nlevel1*nlevel2*nclass+nclass) lambdaend <- (nlevel1*nlevel2*nclass+nclass+nlambda-1) taustart <- (nlevel1*nlevel2*nclass+nclass+nlambda) tauend <- (nlevel1*nlevel2*nclass+nclass+nlambda) } calclikelihood <- function(classx,outcomex,lambdacoef,ltaucoef, updatemoments=FALSE,calcfitted=FALSE,zprop=NULL) { classp2 <- c(0,classx) classp2 <- exp(classp2)/sum(exp(classp2)) newmoments <- replicate(nclass, NULL) ill <- matrix(rep(NA,nclass*nlevel3),ncol=nclass) mylambdacoef <- lambdacoef if (constload) { if (byclass) mylambdacoef <- matrix(rep(lambdacoef,nlevel1),nrow=nclass) else mylambdacoef <- rep(lambdacoef,nlevel1) } for (iclass in 1:nclass) { result <- .Call("bernoulliprobrandom2",outcomes,outcomex[iclass,], if (byclass) mylambdacoef[iclass,] else mylambdacoef, if (byclass) ltaucoef[iclass] else ltaucoef, gh,momentdata[[iclass]], probit,updatemoments,level2size) ill[,iclass] <- exp(result[[1]]) if (updatemoments) newmoments[[iclass]] <- result[[2]] } if (is.null(zprop)) { for (iclass in 1:nclass) ill[,iclass] <- ill[,iclass]*classp2[iclass] ill2 <- log(rowSums(ill)) ll <- sum(ill2*freq) } else { ill2 <- rowSums(log(ill)*zprop) ll <- sum(ill2*freq) } if (probit) { outcomep <- pnorm(as.vector(outcomex)) noutcomep <- pnorm(as.vector(-outcomex)) } else { outcomep <- as.vector(1/(1+exp(-outcomex))) noutcomep <- as.vector(1/(1+exp(outcomex))) } penll <- ll+penalty/(nclass*2)*sum(log(outcomep))+penalty/(nclass*2)*sum(log(noutcomep)) if (is.nan(penll) || is.infinite(penll)) penll <- -1.0*.Machine$double.xmax if (calcfitted) { fitted <- exp(ill2)*sum(ifelse(apply(outcomes,1,function(x) any(is.na(x))),0,freq))* ifelse(apply(outcomes,1,function(x) any(is.na(x))),NA,1) classprob <- ill/exp(ill2) return(list(logLik=ll,penlogLik=penll,moments=newmoments,fitted=fitted,classprob=classprob)) } else return(list(logLik=ll,penlogLik=penll,moments=newmoments)) } adaptivefit <- function(classx,outcomex,lambdacoef,ltaucoef) { fitparams <- function(classx,outcomex,lambdacoef,ltaucoef, calcSE,noiterations=qniterations,zprop=NULL) { calcllfornlm <- function(params,zprop) { oneiteration <- calclikelihood(if (nclass==1) NULL else params[1:(nclass-1)], matrix(params[outcomestart:outcomeend],nrow=nclass), if (byclass) matrix(params[lambdastart:lambdaend],nrow=nclass) else params[lambdastart:lambdaend], params[taustart:tauend], zprop=zprop) return(-oneiteration$penlogLik) } nlm1 <- nlm(calcllfornlm, c(classx,as.vector(outcomex),lambdacoef,ltaucoef), iterlim = noiterations, print.level=ifelse(verbose,2,0), check.analyticals = FALSE,hessian=calcSE,zprop=zprop) return(list(penlogLik=-nlm1$minimum, classx=if (nclass==1) NULL else nlm1$estimate[1:(nclass-1)], outcomex=matrix(nlm1$estimate[outcomestart:outcomeend],nrow=nclass), lambdacoef= if (byclass) matrix(nlm1$estimate[lambdastart:lambdaend],nrow=nclass) else nlm1$estimate[lambdastart:lambdaend], ltaucoef=nlm1$estimate[taustart:tauend], nlm=nlm1)) } oneiteration <- calclikelihood(classx, outcomex, lambdacoef,ltaucoef, updatemoments=TRUE) currll <- oneiteration$penlogLik if (verbose) cat('Initial ll',currll,"\n") lastll <- 2*currll while (abs((lastll-currll)/lastll)>1.0e-6) { lastll <- currll momentdata <<- oneiteration$moments oneiteration <- calclikelihood(classx,outcomex,lambdacoef,ltaucoef, updatemoments=TRUE) currll <- oneiteration$penlogLik zprop <- oneiteration$classprob if (verbose) cat("current ll",currll,"\n") } adaptive <- TRUE prevll <- -Inf nadaptive <- 0 while(adaptive) { fitresults <- fitparams(classx,outcomex,lambdacoef,ltaucoef, calcSE=FALSE,zprop=zprop) currll <- fitresults$penlogLik outcomex <- fitresults$outcomex classx <- fitresults$classx lambdacoef <- fitresults$lambdacoef ltaucoef <- fitresults$ltaucoef if (verbose) cat("current ll from optimisation",currll,"\n") optll <- currll oneiteration <- calclikelihood(classx,outcomex,lambdacoef,ltaucoef, updatemoments=TRUE) currll <- oneiteration$penlogLik lastll <- 2*currll while(abs((lastll-currll)/lastll)>1.0e-7) { lastll <- currll momentdata <<- oneiteration$moments oneiteration <- calclikelihood(classx,outcomex,lambdacoef,ltaucoef, updatemoments=TRUE) currll <- oneiteration$penlogLik if (verbose) cat("current ll",currll,"\n") } adaptive <- (abs((currll-optll)/currll)>1.0e-6) || (abs((currll-prevll)/currll)>1.0e-6) if ((prevll-currll)/abs(currll) > 1.0e-3) stop("divergence - increase quadrature points") nadaptive <- nadaptive+1 if (nadaptive > 200) stop("too many adaptive iterations - increase quadrature points") prevll <- currll zprop <- oneiteration$classprob } fitresults <- fitparams(classx,outcomex,lambdacoef,ltaucoef, calcSE=calcSE,noiterations=500) return(list(nlm=fitresults$nlm,momentdata=momentdata)) } for (iclass in 1:nclass) momentdata[[iclass]] <- matrix(c(rep(c(0,1),each=nlevel3), rep(rep(c(0,1,0),each=nlevel3),times=nlevel2)), nrow=nlevel3) if (nclass==1) classx <- NULL else { classx <- rep(NA,nclass-1) initclassp <- ifelse(initclassp<1.0e-4,1.0e-4,initclassp) initclassp <- ifelse(initclassp>(1.0-1.0e-4),1-1.0e-4,initclassp) for (i in 2:nclass) classx[i-1] <- log(initclassp[i]/initclassp[1]) } initoutcomep <- ifelse(initoutcomep<1.0e-4,1.0e-4,initoutcomep) initoutcomep <- ifelse(initoutcomep>(1.0-1.0e-4),1-1.0e-4,initoutcomep) if (probit) outcomex <- qnorm(initoutcomep) else outcomex <- log(initoutcomep/(1-initoutcomep)) if (missing(initlambdacoef) || is.null(initlambdacoef)) { if (byclass) lambdacoef <- matrix(rep(0,level2size*nclass),nrow=nclass) else lambdacoef <- rep(0,level2size) } else lambdacoef <- initlambdacoef if (missing(initltaucoef) || is.null(initltaucoef)) { testltaucoef <- -3.0 maxltau <- NA maxll <- -Inf repeat { if (verbose) cat('trying ltaucoef ',testltaucoef,"\n") if (byclass) theltaucoef <- rep(testltaucoef,nclass) else theltaucoef <- testltaucoef onelikelihood <- calclikelihood(classx,outcomex,lambdacoef,theltaucoef) currll <- onelikelihood$penlogLik if (verbose) cat("ll",currll,"\n") if (currll < maxll) break() maxll <- currll maxltau <- testltaucoef testltaucoef <- testltaucoef+0.1 } if (verbose) cat('using ltaucoef ',maxltau,"\n") if (byclass) ltaucoef <- rep(maxltau,nclass) else ltaucoef <- maxltau } else ltaucoef <- initltaucoef myfit <- adaptivefit(classx, outcomex, lambdacoef,ltaucoef) optim.fit <- myfit$nlm momentdata <<- myfit$momentdata if (!calcSE) separ <- rep(NA,length(optim.fit$estimate)) else { s <- svd(optim.fit$hessian) separ <- diag(s$v %*% diag(1/s$d) %*% t(s$u)) separ[!is.nan(separ) & (separ>=0.0)] <- sqrt(separ[!is.nan(separ) & (separ>=0.0)]) separ[is.nan(separ) | (separ<0.0)] <- NA } if (nclass==1) classp <- 1 else { classp <-optim.fit$estimate[1:(nclass-1)] classp <- c(0,classp) } outcomex <- matrix(optim.fit$estimate[outcomestart:outcomeend],nrow=nclass) classp <- exp(classp)/sum(exp(classp)) if (probit) outcomep <- pnorm(outcomex) else outcomep <- exp(outcomex)/(1+exp(outcomex)) if (byclass) lambdacoef <- matrix(optim.fit$estimate[lambdastart:lambdaend],nrow=nclass) else lambdacoef <- optim.fit$estimate[lambdastart:lambdaend] ltaucoef <- optim.fit$estimate[taustart:tauend] calcrandom <- function() { outcomex <- log(outcomep/(1-outcomep)) onerandom <- function(x) { loglik <- function(beta) { for (i in 1:nclass) { if (byclass) { if (probit) outcomep <- pnorm(outcomex[i,]+rep(lambdacoef[i,],nlevel2)* (beta[1]+exp(ltaucoef[i])*rep(beta[2:(1+nlevel2)],each=nlevel1))) else outcomep <- 1/(1+exp(-outcomex[i,]-rep(lambdacoef[i,],nlevel2)* (beta[1]+exp(ltaucoef[i])*rep(beta[2:(1+nlevel2)],each=nlevel1)))) } else { if (probit) outcomep <- pnorm(outcomex[i,]+rep(lambdacoef,nlevel2)* (beta[1]+exp(ltaucoef)*rep(beta[2:(1+nlevel2)],each=nlevel1))) else outcomep <- 1/(1+exp(-outcomex[i,]-rep(lambdacoef,nlevel2)* (beta[1]+exp(ltaucoef)*rep(beta[2:(1+nlevel2)],each=nlevel1)))) } oneprob <- t(apply(t(x)*outcomep+t(1-x)*(1-outcomep),2,prod,na.rm=TRUE)) if (i==1) allprob <- oneprob*classp[i] else allprob <- allprob+oneprob*classp[i] } ll <- -(sum(log(allprob))+sum(dnorm(beta,mean=0,sd=1,log=TRUE))) if (is.nan(ll) || is.infinite(ll)) ll <- 1.0*.Machine$double.xmax return(ll) } beta <- rep(0,1+nlevel2) optim.fit <- nlm(loglik,beta,print.level=0,iterlim=1000,hessian=TRUE,gradtol=1.0e-7) if (optim.fit$code >= 3) warning("Maximum likelihood not found - nlm exited with code ", optim.fit$code, " .\n") beta <- optim.fit$estimate sebeta <- sqrt(diag(solve(optim.fit$hessian))) checkx <- matrix(x,ncol=nlevel1,byrow=T) checkx <- apply(checkx,1,function(x) any(is.na(x))) checkx <- c(FALSE,checkx) beta[checkx] <- NA sebeta[checkx] <- NA return(c(beta=beta,sebeta=sebeta)) } betas <- t(apply(outcomes,1,onerandom)) return(betas) } ranef <- calcrandom() if (byclass) final <- calclikelihood(if (nclass==1) NULL else optim.fit$estimate[1:(nclass-1)], matrix(optim.fit$estimate[outcomestart:outcomeend],nrow=nclass), matrix(optim.fit$estimate[lambdastart:lambdaend],nrow=nclass), optim.fit$estimate[taustart:tauend], updatemoments=FALSE,calcfitted=TRUE) else final <- calclikelihood(if (nclass==1) NULL else optim.fit$estimate[1:(nclass-1)], matrix(optim.fit$estimate[outcomestart:outcomeend],nrow=nclass), optim.fit$estimate[lambdastart:lambdaend], optim.fit$estimate[taustart:tauend], updatemoments=FALSE,calcfitted=TRUE) fitted <- final$fitted classprob <- final$classprob np <- length(optim.fit$estimate) nobs <- sum(freq) deviance <- 2*sum(ifelse(freq==0,0,freq*log(freq/fitted))) if (any(abs(as.vector(outcomex))>20)) warning("Problem in solution, probably unstable") list(fit=optim.fit,nclass=nclass,classp=classp,outcomep=outcomep,lambdacoef=lambdacoef,taucoef=exp(ltaucoef),se=separ, np=np,nobs=nobs,logLik=final$logLik,penlogLik=final$penlogLik,freq=freq,fitted=fitted,ranef=ranef ,classprob=classprob,deviance=deviance) }
library(knotR) filename <- "8_19.svg" a <- reader(filename) Mver <- matrix(c( 02,18, 03,17, 04,16, 05,15, 07,13, 08,12, 09,11, 14,06 ),ncol=2,byrow=TRUE) ou819 <- matrix(c( 01,06, 02,15, 09,03, 05,10, 06,15, 14,07, 12,18, 16,11 ),ncol=2,byrow=TRUE) sym819 <- symmetry_object(a,Mver=Mver,xver=c(1,10)) jj <- knotoptim(filename, symobj = sym819, ou = ou819, prob = 0, iterlim=1000, print.level=2 ) write_svg(jj,filename,safe=FALSE) dput(jj,file=sub('.svg','.S',filename))
fsl_nanm = function( ..., outfile = tempfile(fileext = ".nii.gz"), retimg = FALSE ) { fslnanm(..., outfile = outfile, retimg = retimg) return(outfile) }
test_that("test_sc2pv", { pfm <- matrix(c(3, 5, 4, 2, 7, 0, 3, 4, 9, 1, 1, 3, 3, 6, 4, 1, 11, 0, 3, 0, 11, 0, 2, 1, 11, 0, 2, 1, 3, 3, 2, 6, 4, 1, 8, 1, 3, 4, 6, 1, 8, 5, 1, 0, 8, 1, 4, 1, 9, 0, 2, 3, 9, 5, 0, 0, 11, 0, 3, 0, 2, 7, 0, 5), nrow = 4, dimnames = list(c("A", "C", "G", "T"))) bg <- c(A = 0.25, C = 0.25, G = 0.25, T = 0.25) score <- 8.77 type <- "PFM" pvalue <- TFMsc2pv(pfm, score, bg, type) expect_equal(pvalue, 0.00001007156, tolerance=1e-5) })
globalVariables("dot") Greek <- read.table(system.file("etc/GreekLetters.txt", package="sem"), as.is=TRUE) math <- function(text, html.only=FALSE, hat=FALSE){ if (length(text) > 1) { result <- sapply(text, math, html=html.only, hat=hat) names(result) <- names(text) return(result) } subscripts <- c("& "& superscripts <- c("& "& names(subscripts) <- names(superscripts) <- 0:9 hat <- if (hat) "& text <- gsub(" ", "", text) symbol <- regexpr("^[a-zA-Z]+", text) if (symbol != 1) stop("text does not start with an alphabetic symbol name") symbol <- if (html.only) { paste0("&", substring(text, 1, attr(symbol, "match.length")), ";") } else{ s <- substring(text, 1, attr(symbol, "match.length")) s <- Greek[s, "decimal"] if (is.na(s)) stop(s, " is not a Greek letter") s } subscript <- regexpr("_\\{", text) subscript <- if (subscript >= 1){ subscript <- substring(text, subscript + 2) endbrace <- regexpr("\\}", subscript) if (endbrace < 1) stop("unmatched closing brace in ", text) substring(subscript, 1, endbrace - 1) } else "" if (subscript != ""){ subscript <- unlist(strsplit(subscript, split="")) subscript <- subscripts[subscript] if (any(is.na(subscript))) stop ("invalid non-numeral subscript") subscript <- paste(subscript, collapse="") } superscript <- regexpr("\\^\\{", text) superscript <- if (superscript >= 1){ superscript <- substring(text, superscript + 2) endbrace <- regexpr("\\}", superscript) if (endbrace < 1) stop("unmatched closing brace in ", text) substring(superscript, 1, endbrace - 1) } else "" if (superscript != ""){ superscript <- unlist(strsplit(superscript, split="")) superscript <- superscripts[superscript] if (any(is.na(superscript))) stop ("invalid non-numeral superscript") superscript <- paste(superscript, collapse="") } paste0(symbol, hat, subscript, superscript) } path.diagram <- function(...) { .Deprecated("pathDiagram", package = "sem") pathDiagram(...) } pathDiagram <- function (model, ...) { UseMethod("pathDiagram") } pathDiagram.semmod <- function(model, obs.variables, ...) { parse.path <- function(path) { path.1 <- gsub("-", "", gsub(" ","", path)) direction <- if (regexpr("<>", path.1) > 0) 2 else if (regexpr("<", path.1) > 0) - 1 else if (regexpr(">", path.1) > 0) 1 else stop(paste("ill-formed path:", path)) path.1 <- strsplit(path.1, "[<>]")[[1]] list(first = path.1[1], second = path.1[length(path.1)], direction = direction) } if ((!is.matrix(model)) | ncol(model) != 3) stop ("model argument must be a 3-column matrix") startvalues <- as.numeric(model[,3]) par.names <- model[,2] n.paths <- length(par.names) heads <- from <- to <- rep(0, n.paths) for (p in 1:n.paths) { path <- parse.path(model[p,1]) heads[p] <- abs(path$direction) to[p] <- path$second from[p] <- path$first if (path$direction == -1) { to[p] <- path$first from[p] <- path$second } } ram <- matrix(0, p, 5) all.vars <- unique(c(to, from)) latent.vars <- setdiff(all.vars, obs.variables) vars <- c(obs.variables, latent.vars) pars <- na.omit(unique(par.names)) ram[,1] <- heads ram[,2] <- apply(outer(vars, to, "=="), 2, which) ram[,3] <- apply(outer(vars, from, "=="), 2, which) par.nos <- apply(outer(pars, par.names, "=="), 2, which) if (length(par.nos) > 0) ram[,4] <- unlist(lapply(par.nos, function(x) if (length(x) == 0) 0 else x)) ram[,5] <- startvalues colnames(ram) <- c("heads", "to", "from", "parameter", "start value") pars <- unique(na.omit(par.names)) coeff <- rep(0, length(pars)) names(coeff) <- pars fake.sem <- list( ram = ram, n = length(obs.variables), var.names = vars, coeff = coeff, semmod = model ) class(fake.sem) <- "sem" pathDiagram(fake.sem, ...) } pathDiagram.sem <- function (model, file = "pathDiagram", style = c("ram", "traditional"), output.type = c("html", "graphics", "dot"), graphics.fmt = "pdf", dot.options = NULL, size = c(8, 8), node.font = c("Helvetica", 14), edge.font = c("Helvetica", 10), digits = 2, rank.direction = c("LR", "TB"), min.rank = NULL, max.rank = NULL, same.rank = NULL, variables = model$var.names, var.labels, parameters, par.labels, ignore.double = TRUE, ignore.self = FALSE, error.nodes = TRUE, edge.labels = c("names", "values", "both"), edge.colors = c("black", "black"), edge.weight = c("fixed", "proportional"), node.colors = c("transparent", "transparent", "transparent"), standardize = FALSE, ...) { Dot <- function(..., semicolon = TRUE, newline = TRUE) { cat(file = handle, paste0(..., if (semicolon) ";" else "", if (newline) "\n" else "")) } style <- match.arg(style) output.type <- match.arg(output.type) edge.labels <- match.arg(edge.labels) edge.weight <- match.arg(edge.weight) rank.direction <- match.arg(rank.direction) if (output.type == "html") { handle <- textConnection("dot", "w") } else { dot.file <- paste0(file, ".dot") handle <- file(dot.file, "w") if (output.type == "graphics") graph.file <- paste0(file, ".", graphics.fmt) } on.exit(close(handle)) Dot("digraph \"", deparse(substitute(model)), "\" {", semicolon = FALSE) Dot(" rankdir=", rank.direction) Dot(" size=\"", size[1], ",", size[2], "\"") Dot( " node [fontname=\"", node.font[1], "\" fontsize=", node.font[2], " fillcolor=\"", node.colors[1], "\" shape=box style=filled]" ) Dot(" edge [fontname=\"", edge.font[1], "\" fontsize=", edge.font[2], "]") Dot(" center=1") if (!is.null(min.rank)) { min.rank <- paste0("\"", min.rank, "\"") min.rank <- gsub(",", "\" \"", gsub(" ", "", min.rank)) Dot(" {rank=min ", min.rank, "}", semicolon = FALSE) } if (!is.null(max.rank)) { max.rank <- paste0("\"", max.rank, "\"") max.rank <- gsub(",", "\" \"", gsub(" ", "", max.rank)) Dot(" {rank=max ", max.rank, "}", semicolon = FALSE) } if (!is.null(same.rank)) { for (s in 1:length(same.rank)) { same <- paste0("\"", same.rank[s], "\"") same <- gsub(",", "\" \"", gsub(" ", "", same)) Dot(" {rank=same ", same, "}", semicolon = FALSE) } } latent <- variables[-(1:model$n)] for (lat in latent) { Dot(" \"", lat, "\" [shape=ellipse]", semicolon = FALSE) } endogenous <- classifyVariables(model$semmod)$endogenous endogenous <- variables[apply(outer(endogenous, model$var.names, "=="), 1, which)] if (style == "traditional") { variables <- c(variables, paste0(endogenous, ".error")) error.color <- if (length(node.colors) < 3) node.colors[1] else node.colors[3] } for (endog in endogenous) { Dot(" \"", endog, "\" [fillcolor=\"", node.colors[2], "\"]", semicolon = FALSE) if (style == "traditional") { if (error.nodes) Dot( " \"", endog, ".error\" [shape=ellipse] [fillcolor=\"", error.color, "\"]", semicolon = FALSE ) else Dot( " \"", endog, ".error\" [shape=ellipse width=0 height=0 fixedsize=true label=\"\"] [fillcolor=\"", error.color, "\"]", semicolon = FALSE ) } } ram <- model$ram if (missing(parameters)) { par.names <- names(coef(model)) rownames(ram)[ram[, "parameter"] != 0] <- par.names[ram[, "parameter"]] rownames(ram)[ram[, "parameter"] == 0] <- ram[ram[, "parameter"] == 0, "start value"] parameters <- rownames(ram) } if (standardize) ram[, 5] <- stdCoef(model)[, 2] else ram[names(model$coeff), 5] <- model$coeff coefs <- ram[, 5] na.coefs <- is.na(coefs) if (any(na.coefs)) { for (coef in which(na.coefs)) { ram[coef, 5] <- (ram[ram[coef, 4] == ram[, 4], 5])[1] } } values <- round(ram[, 5], digits) heads <- ram[, 1] to <- ram[, 2] from <- ram[, 3] if (!missing(par.labels)) { check <- names(par.labels) %in% parameters if (any(!check)) { msg <- if (sum(!check) > 1) paste( "The following parameters do not appear in the model:", paste(names(par.labels)[!check], collapse = ", ") ) else paste("The following parameter does not appear in the model:", names(par.labels)[!check]) warning(msg) par.labels <- par.labels[check] } names(parameters) <- parameters parameters[names(par.labels)] <- par.labels } labels <- if (edge.labels == "names") parameters else if (edge.labels == "values") values else paste(parameters, values, sep = "=") colors <- ifelse(values > 0, edge.colors[1], edge.colors[2]) direction <- ifelse((heads == 2), " dir=both", "") lineweight <- rep(1, nrow(ram)) if (edge.weight == "proportional") { lineweight <- abs(values) / mean(values) if (!standardize) warning("proportional edge weights requested for an unstandardized model") } if (style == "ram") { for (par in 1:nrow(ram)) { if ((!ignore.double) || (heads[par] == 1)) { if (ignore.self && to[par] == from[par]) next Dot( " \"", variables[from[par]], "\" -> \"", variables[to[par]], "\" [label=\"", labels[par], "\"", direction[par], " color=", colors[par], " penwidth=", round(lineweight[par] + 0.001, 3), "]" ) } } } else for (par in 1:nrow(ram)) { if (heads[par] == 1) { Dot( " \"", variables[from[par]], "\" -> \"", variables[to[par]], "\" [label=\"", labels[par], "\"", direction[par], " color=", colors[par], " penwidth=", round(lineweight[par] + 0.001, 3), "]" ) } else if (variables[to[par]] %in% endogenous) { if (variables[to[par]] == variables[from[par]]) { lab <- labels[par] val <- round(sqrt(values[par]), digits = digits) lab <- if (edge.labels == "names") paste0("sqrt(", lab, ")") else if (edge.labels == "values") val else paste0("sqrt(", parameters[par], ")=", val) Dot( " \"", variables[to[par]], ".error\" -> \"", variables[to[par]], "\" [color=", edge.colors[1], " label=\"", lab, "\" penwidth=", round(sqrt(lineweight[par]) + 0.001, 3)," ]" ) } else{ Dot( " \"", variables[to[par]], ".error\" -> \"", variables[from[par]], ".error\" [dir=both label=\"", labels[par], "\" color=", colors[par], " penwidth=", round(lineweight[par] + 0.001, 3), "]" ) } } else if (!ignore.double && (variables[to[par]] != variables[from[par]])) { Dot( " \"", variables[from[par]], "\" -> \"", variables[to[par]], "\" [label=\"", labels[par], "\"", direction[par], " color=", colors[par], " penwidth=", round(lineweight[par] + 0.001, 3), "]" ) } } if (!missing(var.labels)) { check <- names(var.labels) %in% variables if (any(!check)) { msg <- if (sum(!check) > 1) paste( "The following variables do not appear in the model:", paste(names(var.labels)[!check], collapse = ", ") ) else paste("The following variable does not appear in the model:", names(var.labels)[!check]) warning(msg) var.labels <- var.labels[check] } Dot(" // variable labels: ", semicolon = FALSE) lines <- paste0(' "', names(var.labels), '" [label="', var.labels, '"];\n') Dot(paste(lines, collapse = ""), semicolon = FALSE, newline = FALSE) } Dot("}", semicolon = FALSE) if (output.type == "graphics") { cmd <- paste0("dot -T", graphics.fmt, " -o ", graph.file, " -Gcharset=latin1 ", dot.options, " ", dot.file) cat("Running ", cmd, "\n") result <- try(system(cmd)) } if (output.type == "html" && requireNamespace("DiagrammeR")) { print(DiagrammeR::DiagrammeR(textConnection(dot), type = "grViz")) } result <- if (output.type == "html") dot else readLines(dot.file) invisible(result) }
dateNumToMillis <- function(datenum) { datenum * 1000 }
test_that("wkb_meta() works", { expect_identical( wkb_meta(wkt_translate_wkb("POINT (30 10)")), tibble::tibble( feature_id = 1L, part_id = 1L, type_id = 1L, size = 1L, srid = NA_integer_, has_z = FALSE, has_m = FALSE ) ) }) test_that("wkt_meta() works", { expect_identical( wkt_meta("POINT (30 10)"), tibble::tibble( feature_id = 1L, part_id = 1L, type_id = 1L, size = 1L, srid = NA_integer_, has_z = FALSE, has_m = FALSE ) ) }) test_that("wkt_streamer_meta() works", { expect_identical( wkt_streamer_meta("POINT (30 10)"), tibble::tibble( feature_id = 1L, part_id = 1L, type_id = 1L, size = NA_integer_, srid = NA_integer_, has_z = FALSE, has_m = FALSE ) ) expect_identical( wkt_streamer_meta("MULTIPOINT ((30 10))", recursive = FALSE), tibble::tibble( feature_id = 1L, part_id = 1L, type_id = 4L, size = NA_integer_, srid = NA_integer_, has_z = FALSE, has_m = FALSE ) ) expect_identical( wkt_streamer_meta("MULTIPOINT ((30 10))", recursive = TRUE), tibble::tibble( feature_id = c(1L, 1L), part_id = c(1L, 2L), type_id = c(4L, 1L), size = c(NA_integer_, NA_integer_), srid = c(NA_integer_, NA_integer_), has_z = c(FALSE, FALSE), has_m = c(FALSE, FALSE) ) ) expect_identical( wkt_streamer_meta("GEOMETRYCOLLECTION (POINT (30 10))", recursive = FALSE), tibble::tibble( feature_id = 1L, part_id = 1L, type_id = 7L, size = NA_integer_, srid = NA_integer_, has_z = FALSE, has_m = FALSE ) ) expect_identical( wkt_streamer_meta(c("GEOMETRYCOLLECTION (POINT (30 10))", NA), recursive = TRUE), tibble::tibble( feature_id = c(1L, 1L, 2L), part_id = c(1L, 2L, NA_integer_), type_id = c(7L, 1L, NA_integer_), size = c(NA_integer_, NA_integer_, NA_integer_), srid = c(NA_integer_, NA_integer_, NA_integer_), has_z = c(FALSE, FALSE, NA), has_m = c(FALSE, FALSE, NA) ) ) }) test_that("wkt_streamer_meta() works with NULLs", { expect_identical( wkt_streamer_meta(NA), tibble::tibble( feature_id = 1L, part_id = NA_integer_, type_id = NA_integer_, size = NA_integer_, srid = NA_integer_, has_z = NA, has_m = NA ) ) }) test_that("wkt_meta() counts coordinates when NULLs are present", { expect_identical( wkt_meta(c("LINESTRING (20 20, 0 0)", NA)), tibble::tibble( feature_id = c(1L, 2L), part_id = c(1L, NA_integer_), type_id = c(2L, NA_integer_), size = c(2L, NA_integer_), srid = c(NA_integer_, NA_integer_), has_z = c(FALSE, NA), has_m = c(FALSE, NA) ) ) }) test_that("wkt_streamer_meta() returns SRIDs if present", { expect_identical( wkt_streamer_meta("SRID=33;POINT (30 10)"), tibble::tibble( feature_id = 1L, part_id = 1L, type_id = 1L, size = NA_integer_, srid = 33L, has_z = FALSE, has_m = FALSE ) ) }) test_that("wkt_streamer_meta() fails on parse error", { expect_error(wkt_streamer_meta("NOPE"), class = "WKParseException") }) test_that("geometry type converters work", { types_str <- c( "point", "linestring", "polygon", "multipoint", "multilinestring", "multipolygon", "geometrycollection" ) expect_identical(wk_geometry_type_id(types_str), 1:7) expect_identical(wk_geometry_type(7:1), rev(types_str)) })
if (interactive()) pkgload::load_all(".") run_test <- fritools::is_running_on_fvafrcu_machines() test_repo <- function() { d <- tempfile() dir.create(d) RUnit::checkTrue(!packager:::is_git_repository(d)) RUnit::checkTrue(!packager:::is_git_clone(d)) RUnit::checkTrue(!packager:::uses_git(d)) gert::git_init(d) RUnit::checkTrue(packager:::is_git_repository(d)) RUnit::checkTrue(packager:::is_git_clone(d)) RUnit::checkTrue(packager:::uses_git(d)) RUnit::checkTrue(!packager:::is_git_uncommitted(d)) fritools::touch(file.path(d, "foobar.txt")) result <- packager:::git_add(path = d, files = "foobar.txt") RUnit::checkTrue(is(result, "tbl")) result <- packager:::git_commit(d, message = "ini") RUnit::checkTrue(is(result, "character")) fritools::touch(file.path(d, "foobaz.txt")) result <- git_add_commit(d, message = "sec", untracked = TRUE) RUnit::checkTrue(is(result, "character")) } if (interactive()) test_repo() test_git_tag_create <- function() { if (run_test) { path <- file.path(tempdir(), "prutp") on.exit(unlink(path, recursive = TRUE)) packager:::package_skeleton(path) RUnit::checkException(packager:::git_tag_create(path = path, version = "0.0.0", message = "Foo")) packager:::use_git(path) result <- packager:::git_tag_create(path = path, version = "0.0.0.9000", message = "Initial Commit") RUnit::checkIdentical("0.0.0.9000", getElement(result, "name")) desc::desc_bump_version("minor", file = path) RUnit::checkException(packager::git_tag(path = path)) } } if (interactive()) test_git_tag_create() test_git_tag <- function() { if (run_test) { path <- file.path(tempdir(), "prutp") on.exit(unlink(path, recursive = TRUE)) packager:::package_skeleton(path) RUnit::checkException(packager::git_tag(path = path)) packager:::use_git(path) result <- packager::git_tag(path = path) RUnit::checkIdentical("1.0", getElement(result, "name")) desc::desc_bump_version("minor", file = path) RUnit::checkException(packager::git_tag(path = path)) git_add_commit(path = path) result <- packager::git_tag(path = path) RUnit::checkIdentical("1.1", getElement(result, "name")) desc::desc_set(Version = "0.3", file = path) git_add_commit(path = path) RUnit::checkException(packager::git_tag(path = path)) } } if (interactive()) test_git_tag()
library(hamcrest) x <- 1 y <- asS4(x, TRUE) z <- asS4(y, FALSE) assertThat(isS4(x), identicalTo(FALSE)) assertThat(isS4(y), identicalTo(TRUE)) assertThat(isS4(z), identicalTo(FALSE))
kern.fun.default <- function(x,t,h,type_data=c("discrete","continuous"), ker=c("bino","triang","dirDU","BE","GA","LN","RIG"),a0=0,a1=1,a=1,c=2,...) { if (missing(type_data)) stop("argument 'type_data' is omitted") if ((type_data=="discrete") & (ker=="GA"||ker=="LN"||ker=="BE" ||ker=="RIG")) stop(" Not appropriate kernel for type_data") if ((type_data=="continuous") & (ker=="bino"||ker=="triang"||ker=="dirDU")) stop(" Not appropriate kernel for 'type_data'") if ((type_data=="discrete") & missing(ker)) ker<-"bino" if ((type_data=="continuous") & missing(ker)) ker<-"GA" kx <- kef(x,t,h,type_data,ker,a0,a1,a,c) structure(list(kernel = ker,x=x,t=t,kx=kx),class="kern.fun") }
manipulatorExecute <- function(manipulator) { result <- withVisible(eval(manipulator$.code, envir = manipulator)) if (result$visible) { eval(print(result$value), enclos=parent.env(manipulator)) } } manipulatorSave <- function(manipulator, filename) { suppressWarnings(save(manipulator, file=filename)) } manipulatorLoad <- function(filename) { load(filename) get("manipulator") } hasActiveManipulator <- function() { .Call(getNativeSymbolInfo("rs_hasActiveManipulator", PACKAGE="")) } activeManipulator <- function() { .Call(getNativeSymbolInfo("rs_activeManipulator", PACKAGE="")) } ensureManipulatorSaved <- function() { .Call(getNativeSymbolInfo("rs_ensureManipulatorSaved", PACKAGE="")) } createUUID <- function() { .Call(getNativeSymbolInfo("rs_createUUID", PACKAGE="")) } executeAndAttachManipulator <- function(manipulator) { .Call(getNativeSymbolInfo("rs_executeAndAttachManipulator", PACKAGE=""), manipulator) } setManipulatorValue <- function(manipulator, name, value) { assign(name, value, envir = get(".userVisibleValues", envir = manipulator)) underlyingValue <- value controls <- get(".controls", envir = manipulator) control <- controls[[name]] if (inherits(control, "manipulator.picker")) underlyingValue <- (control$values[[value]]) assign(name, underlyingValue, envir = manipulator) } userVisibleValues <- function(manipulator, variables) { mget(variables, envir = get(".userVisibleValues", envir = manipulator)) } buttonNames <- function(manipulator) { if (exists(".buttonNames", envir = manipulator)) get(".buttonNames", envir = manipulator) else character() } trackingMouseClicks <- function(manipulator) { exists(".mouseClick", envir = manipulator) } setMouseClick <- function(manipulator, deviceX, deviceY, userX, userY, ndcX, ndcY) { mouseClick <- list(deviceX = deviceX, deviceY = deviceY, userX = userX, userY = userY, ndcX = ndcX, ndcY = ndcY) assign(".mouseClick", mouseClick, envir = manipulator) } clearMouseClick <- function(manipulator) { assign(".mouseClick", NULL, envir = manipulator) } resolveVariableArguments <- function(args) { if ( (length(args) == 1L) && is.list(args[[1L]]) && (is.null(names(args)) || (names(args)[[1L]] == "")) ) { return (args[[1L]]) } else { return (args) } }
get_restriction_matrix <- function(restriction_matrix, k){ if(!is.null(restriction_matrix)){ restriction_matrix = as.matrix(restriction_matrix) if(dim(restriction_matrix)[1] == k & dim(restriction_matrix)[2] == k){ restriction_matrix = restriction_matrix }else if(dim(restriction_matrix)[1] == k^2 | dim(restriction_matrix)[2] == k^2){ ones = matrix(rep(1,k*k),k,k) restriction_matrix = c(ones) %*% restriction_matrix restriction_matrix = matrix(restriction_matrix, ncol = k) restriction_matrix[restriction_matrix == 1] <- NA }else{ stop(paste0("Different restriction matrix dimension than B. Please use either of the two valid formats containing either kxk (", k,"x",k, ") or k^2xk^2 (", k^2,"x",k^2, ") dimensions.")) } }else{ restriction_matrix <- matrix(NA, k, k) } return(restriction_matrix) }
barplot.conData <- function(height, plottype='RelFreq', color=NULL, legend=TRUE,...){ height.data <- height$probs varNames <- height$varNames if (plottype == 'All'){ if(length(color)<3){ color = c('darkslategray1','darkslategray3','darkslategray4') }else if (length(color) > 3){ color=color[1:3] } barplot(t(height.data)[,nrow(height.data):1], main = "" , xlab = "" , ylab = "" , names.arg = rev(varNames) , col = color , las = 2 , cex.axis = 0.8 , beside=TRUE , horiz=TRUE) if(legend==TRUE) legend('topright', c("rel.freq","p1|1","p1|0"), fill = color,cex=0.7) }else if (plottype == 'RelFreq'){ if(is.null(color)) color='darkslategray3' barplot(rev(height.data[,1]) , main = "" , xlab = "", ylab = "", names.arg = rev(varNames), col = rev(color), las = 2 , cex.axis = 1 , beside = TRUE , horiz = TRUE) } }
`getTargetSGPContentArea` <- function(grade, content_area, state, max.sgp.target.years.forward, my.sgp.target.content_area) { if (is.null(SGP::SGPstateData[[state]][["SGP_Configuration"]][["content_area.projection.sequence"]][[content_area]])) { return(content_area) } else { tmp.content_areas.by.grade <- paste(SGP::SGPstateData[[state]][["SGP_Configuration"]][["content_area.projection.sequence"]][[content_area]], SGP::SGPstateData[[state]][["SGP_Configuration"]][["grade.projection.sequence"]][[content_area]], sep=".") tmp.index <- match(paste(content_area, grade, sep="."), tmp.content_areas.by.grade) if (is.na(tmp.index)) { message(paste0("\tNOTE: '", content_area, "', GRADE '", grade, "' combination is not in current @Data. Will return ", content_area, " for '", my.sgp.target.content_area, "'.")) return(content_area) } else { return(SGP::SGPstateData[[state]][["SGP_Configuration"]][["content_area.projection.sequence"]][[content_area]][ min(tmp.index+max.sgp.target.years.forward, length(SGP::SGPstateData[[state]][["SGP_Configuration"]][["grade.projection.sequence"]][[content_area]]))]) } } }
"maboost"<- function(x,...)UseMethod("maboost")
modify_call <- function(call, new_args) { stopifnot(is.call(call), is.list(new_args)) call <- standardise_call(call) nms <- names(new_args) %||% rep("", length(new_args)) if (any(nms == "")) { stop("All new arguments must be named", call. = FALSE) } for(nm in nms) { call[[nm]] <- new_args[[nm]] } call }
ttsLSTM <- function (y,x=NULL,train.end,arOrder=1,xregOrder=0,type, memoryLoops=10,shape=NULL,dim3=5){ if (!is.zoo(y)) {print("The data must be a zoo object.")} if (max(diff(unique(y)))==min(diff(unique(y)))) {stop("Binary dependent variable is not allowed for current version")} y=timeSeries::as.timeSeries(y) if (!is.null(x)) { x=timeSeries::as.timeSeries(x) if ( nrow(y) != nrow(x) ) {print("Variables must have the same rows.") } } if (is.null(train.end)) {print("The train.end must be specified.") } train.start=start(y) t0=which(as.character(time(y))==train.end) test.start=as.character(time(y))[t0+1] test.end=as.character(end(y)) p=max(arOrder,xregOrder) colNAMES=c(outer(paste0(names(x),"_L"),0:p,FUN=paste0)) if (p==0) { y=y datasetX=timeSeries::as.timeSeries(x) ar0=NULL } else { datasetY=timeSeries::as.timeSeries(embed(y,p+1),time(y)[-c(1:p)]) y=datasetY[,1] ar0=datasetY[,-1] colnames(ar0)=paste0("ar",1:p) if (is.null(x)) {datasetX=NULL } else { datasetX=timeSeries::as.timeSeries(embed(x,p+1),time(x)[-c(1:p)]) colnames(datasetX)=colNAMES } } colnames(y)="y" if (min(arOrder)==0) {ar=NULL } else {ar=ar0[,paste0("ar",arOrder)]} if (is.null(x)) {X=datasetX} else { L.ID=paste0("L",xregOrder) IDx=NULL for (i in L.ID) {IDx=c(IDx,grep(colNAMES,pattern=i))} X=datasetX[,IDx] } DF <- na.omit(cbind(y,ar,X)) trend <- 1:nrow(y) if (timeSeries::isRegular(y)) { seasonDummy <- data.frame(forecast::seasonaldummy(as.ts(y))) DF0 <- cbind(ar0,X,seasonDummy,trend) } else {DF0 <- cbind(ar0,X,trend)} if (type=="trend") {DF<-cbind(DF,trend)} else if (type=="sesaon") {DF<-cbind(DF,seasonDummy) } else if (type=="both") {DF<-cbind(DF,trend,seasonDummy) } else {DF <- DF} newData= timeSeries::as.timeSeries(DF) trainData=window(newData,start=train.start,end=train.end) testData=window(newData,start=test.start,end=test.end) train0 = data.frame(value = as.numeric(trainData[,1]), trainData[,-1]) train = train0[complete.cases(train0), ] test0 = data.frame(value = as.numeric(testData[,1]), testData[,-1]) test = test0[complete.cases(test0), ] batch.size = DescTools::GCD(nrow(train),nrow(test)) nrow(train)/batch.size; nrow(test)/batch.size names(train) train.new=as.matrix(train) dimnames(train.new)=NULL test.new=as.matrix(test) dimnames(test.new)=NULL if(is.null(shape)) {SHAPE=ncol(train.new)} else {SHAPE=shape} k=dim3 x.train = array(data = train.new[,-1], dim = c(nrow(train.new), SHAPE, k)) y.train = array(data = train.new[,1], dim = c(nrow(train.new), 1)) x.test = array(data = test.new[,-1], dim = c(nrow(test.new), SHAPE, k)) y.test = array(data = test.new[,1], dim = c(nrow(test.new), 1)) model <- keras::keras_model_sequential() model %>% keras::layer_lstm(units = 100, input_shape = c(SHAPE, k), batch_size = batch.size, return_sequences = TRUE, stateful = TRUE) %>% keras::layer_dropout(rate = 0.5) %>% keras::layer_lstm(units = 50, return_sequences = FALSE, stateful = TRUE) %>% keras::layer_dropout(rate = 0.5) %>% keras::layer_dense(units = 1) model %>% keras::compile(loss = 'mae', optimizer = 'adam') for(i in 1:memoryLoops){ model %>% keras::fit(x = x.train, y = y.train, batch_size = batch.size, epochs = 1, verbose = 0, shuffle = FALSE) model %>% keras::reset_states()} return(list(output=model,batch.size=batch.size,k=k,SHAPE=SHAPE,arOrder=arOrder,data=cbind(y,DF0),dataused=DF)) }
extrapolation <- function (results, lambda, lambda0, estimate0, fitting.method, B, parameter) { if (parameter == 'inbreeding'){ inb <- t(results$inb_dep) se_inb <- t(results$se_inb_dep) inb_ave<-colMeans(inb, na.rm = TRUE) se_inb_ave<-colMeans(se_inb, na.rm = TRUE) lambda<-c(lambda0, lambda) inb_ave<-c(estimate0$inb0, inb_ave) se_inb<-c(estimate0$se0, se_inb_ave) p.names<-c("inb", "se_inb") estimates<-data.frame(inb_ave, se_inb) colnames(estimates) <- p.names inb_pred <- c() inb_pred_se <- c() AIC <- c() se_pred <- c() var <- c() for (i in 1: length(fitting.method)) { f <- fitting.method[i] if (f == 'line') { extrapolation_inb <- lm(estimates[ ,1] ~ lambda) inb_pred[i] <- predict(extrapolation_inb, newdata = data.frame(lambda = 0)) extrapolation_inb_se <- lm(estimates[,2] ~ lambda) inb_pred_se[i] <- predict(extrapolation_inb_se, newdata = data.frame(lambda = 0)) AIC[i] <- AIC(extrapolation_inb) } if (f == 'quad') { extrapolation_inb1<- lm(estimates[ ,1] ~ lambda+ I(lambda^2)) inb_pred[i] <- predict(extrapolation_inb1, newdata = data.frame(lambda = 0)) extrapolation_inb1_se<- lm(estimates[ ,2] ~ lambda+ I(lambda^2)) inb_pred_se[i] <-predict(extrapolation_inb1_se, newdata = data.frame(lambda = 0)) AIC[i] <- AIC(extrapolation_inb1) } if (f == 'nonl') { extrapolation_inb2<-fit.nls(lambda, p.names, estimates[, ]) inb_pred[i] <-predict(extrapolation_inb2[[1]], newdata = data.frame(lambda = 0)) inb_pred_se[i] <-predict(extrapolation_inb2[[2]], newdata = data.frame(lambda = 0)) AIC[i] <- AIC(extrapolation_inb2) } if (f == 'cubi') { extrapolation_inb<- lm(estimates[ ,1] ~ lambda+ I(lambda^2)+ I(lambda^3)) inb_pred[i] <-predict(extrapolation_inb, newdata = data.frame(lambda = 0)) extrapolation_inb_se<- lm(estimates[,2] ~ lambda+ I(lambda^2)+ I(lambda^3)) inb_pred_se[i] <-predict(extrapolation_inb_se, newdata = data.frame(lambda = 0)) AIC[i] <- AIC(extrapolation_inb) } S <- c() for ( ii in 1:length(inb[ 1,])) { diff <- c() for ( j in 1: B ) { diff[j] <- inb[j,ii]-inb_ave[ii] } diff <- na.omit(diff) S[ii] <- 1/(B-1)*sum(diff^2) } lambda1 <- lambda[-1] if (f == 'line') { extrapolation_var <- lm(S ~ lambda1) se_pred[i] <- predict(extrapolation_var, newdata = data.frame(lambda1 = 0)) } if (f == 'quad') { extrapolation_var1 <- lm(S ~ lambda1+ I(lambda1^2)) se_pred[i] <- predict(extrapolation_var1, newdata = data.frame(lambda1 = 0)) } if (f == 'nonl') { p.names1 <- c("S") estimates1 <- data.frame(S) colnames(estimates1) <- p.names1 ex <- fit.nls(lambda1, p.names1, estimates1[ ]) se_pred[i] <- predict(ex[[1]], newdata = data.frame(lambda1 = 0)) } if (f == 'cubi') { extrapolation_var1 <- lm(S ~ lambda1+ I(lambda1^2)+ I(lambda1^3)) se_pred[i] <- predict(extrapolation_var1, newdata = data.frame(lambda1 = 0)) } var[i] <- inb_pred_se[i]^2 + se_pred[i]^2 } extrapolation <- list() extrapolation$fitting.method <- fitting.method extrapolation$inb_dep <- inb_pred extrapolation$se <- inb_pred_se extrapolation$sampling_se <- se_pred extrapolation$var <- var extrapolation$AIC <- AIC } if (parameter =='heritability'){ h <- t(results$heritability) se_h <- t(results$se_h) VA <- t(results$VA) VE <- t(results$VE) h_ave<-colMeans(h, na.rm = TRUE) se_h_ave<-colMeans(se_h, na.rm = TRUE) VA_ave<-colMeans(VA, na.rm = TRUE) VE_ave<-colMeans(VE, na.rm = TRUE) lambda <- c(lambda0, lambda) h_ave <- c(estimate0$h0, h_ave) se_h <- c(estimate0$seh0, se_h_ave) VA <- c(estimate0$VA0, VA_ave) VE <- c(estimate0$VE0, VE_ave) p.names<-c("h", "se_h", "VA", "VE") estimates<-data.frame(h_ave, se_h, VA, VE) colnames(estimates) <- p.names h_pred <- c() h_pred_se <- c() VA_pred <- c() VE_pred <- c() AIC <- c() aicc <- c() se_pred <- c() var <- c() for (i in 1: length(fitting.method)) { f <- fitting.method[i] if (f == 'line') { extrapolation_h<- lm(estimates[ ,1] ~ lambda) h_pred[i] <-predict(extrapolation_h, newdata = data.frame(lambda = 0)) extrapolation_h_se <- lm(estimates[,2] ~ lambda) h_pred_se[i] <- predict(extrapolation_h_se, newdata = data.frame(lambda = 0)) extrapolation_VA <- lm(estimates[ ,3] ~ lambda) VA_pred[i] <-predict(extrapolation_VA, newdata = data.frame(lambda = 0)) extrapolation_VE<- lm(estimates[ ,4] ~ lambda) VE_pred[i] <-predict(extrapolation_VE, newdata = data.frame(lambda = 0)) AIC[i] <- AIC(extrapolation_h) } if (f == 'quad') { extrapolation_h<- lm(estimates[ ,1] ~ lambda+ I(lambda^2)) h_pred[i] <-predict(extrapolation_h, newdata = data.frame(lambda = 0)) extrapolation_h_se<- lm(estimates[ ,2] ~ lambda+ I(lambda^2)) h_pred_se[i] <-predict(extrapolation_h_se, newdata = data.frame(lambda = 0)) extrapolation_VA <- lm(estimates[ ,3] ~ lambda+ I(lambda^2)) VA_pred[i] <-predict(extrapolation_VA, newdata = data.frame(lambda = 0)) extrapolation_VE<- lm(estimates[ ,4] ~ lambda+ I(lambda^2)) VE_pred[i] <-predict(extrapolation_VE, newdata = data.frame(lambda = 0)) AIC[i] <- AIC(extrapolation_h) } if (f == 'nonl') { extrapolation_h<-fit.nls(lambda, p.names, estimates[, ]) h_pred[i] <-predict(extrapolation_h[[1]], newdata = data.frame(lambda = 0)) h_pred_se[i] <-predict(extrapolation_h[[2]], newdata = data.frame(lambda = 0)) VA_pred[i] <-predict(extrapolation_h[[3]], newdata = data.frame(lambda = 0)) VE_pred[i] <-predict(extrapolation_h[[4]], newdata = data.frame(lambda = 0)) } if (f == 'cubi') { extrapolation_h<- lm(estimates[ ,1] ~ lambda+ I(lambda^2)+I(lambda^3)) h_pred[i] <-predict(extrapolation_h, newdata = data.frame(lambda = 0)) extrapolation_h_se<- lm(estimates[ ,2] ~ lambda+ I(lambda^2)+I(lambda^3)) h_pred_se[i] <-predict(extrapolation_h_se, newdata = data.frame(lambda = 0)) extrapolation_VA <- lm(estimates[ ,3] ~ lambda+ I(lambda^2)+I(lambda^3)) VA_pred[i] <-predict(extrapolation_VA, newdata = data.frame(lambda = 0)) extrapolation_VE<- lm(estimates[ ,4] ~ lambda+ I(lambda^2)+I(lambda^3)) VE_pred[i] <-predict(extrapolation_VE, newdata = data.frame(lambda = 0)) AIC[i] <- AIC(extrapolation_h) } S <- c() for ( ii in 1:length(h[ 1, ])) { diff <- c() for ( j in 1: B ) { diff[j] <- h[j,ii]-h_ave[ii] } diff <- na.omit(diff) S[ii] <- 1/(B-1)*sum(diff^2) } lambda1 <- lambda[-1] if (f == 'line') { extrapolation_var <- lm(S ~ lambda1) se_pred[i] <- predict(extrapolation_var, newdata = data.frame(lambda1 = 0)) } if (f == 'quad') { extrapolation_var1 <- lm(S ~ lambda1+ I(lambda1^2)) se_pred[i] <- predict(extrapolation_var1, newdata = data.frame(lambda1 = 0)) } if (f == 'nonl') { p.names1 <- c("S") estimates1 <- data.frame(S) colnames(estimates1) <- p.names1 ex <- fit.nls(lambda1, p.names1, estimates1[ ]) se_pred[i] <- predict(ex[[1]], newdata = data.frame(lambda1 = 0)) } if (f == 'cubi') { extrapolation_var1 <- lm(S ~ lambda1+ I(lambda1^2)+I(lambda1^3)) se_pred[i] <- predict(extrapolation_var1, newdata = data.frame(lambda1 = 0)) } var[i] <- h_pred_se[i]^2 + se_pred[i]^2 } extrapolation <- list() extrapolation$fitting.method <- fitting.method extrapolation$h <- h_pred extrapolation$se <- h_pred_se extrapolation$sampling_se <- se_pred extrapolation$var <- var extrapolation$VA <- VA_pred extrapolation$VE <- VE_pred extrapolation$AIC <- AIC } return(extrapolation) }
sf_upsert_metadata <- function(metadata_type, metadata, control = list(...), ..., all_or_none = deprecated(), verbose = FALSE){ which_operation <- "upsertMetadata" metadata <- metadata_type_validator(obj_type = metadata_type, obj_data = metadata) control_args <- return_matching_controls(control) control_args$api_type <- "Metadata" control_args$operation <- "upsert" if(is_present(all_or_none)) { deprecate_warn("0.1.3", "salesforcer::sf_upsert_metadata(all_or_none = )", "sf_upsert_metadata(AllOrNoneHeader = )", details = paste0("You can pass the all or none header directly ", "as shown above or via the `control` argument.")) control_args$AllOrNoneHeader <- list(allOrNone = tolower(all_or_none)) } control <- do.call("sf_control", control_args) operation_node <- newXMLNode(which_operation, namespaceDefinitions = c('http://soap.sforce.com/2006/04/metadata'), suppressNamespaceWarning = TRUE) xml_dat <- build_metadata_xml_from_list(input_data = metadata, metatype = metadata_type, root = operation_node) base_metadata_url <- make_base_metadata_url() root <- make_soap_xml_skeleton(soap_headers = control, metadata_ns = TRUE) body_node <- newXMLNode("soapenv:Body", parent = root) body_node <- addChildren(body_node, xml_dat) request_body <- as(root, "character") httr_response <- rPOST(url = base_metadata_url, headers = c("SOAPAction"=which_operation, "Content-Type"="text/xml"), body = request_body) if(verbose){ make_verbose_httr_message(httr_response$request$method, httr_response$request$url, httr_response$request$headers, request_body) } catch_errors(httr_response) response_parsed <- content(httr_response, encoding="UTF-8") resultset <- response_parsed %>% xml_ns_strip() %>% xml_find_all('.//result') %>% map_df(xml_nodeset_to_df) %>% type_convert(col_types = cols()) return(resultset) }
library(neuralnet) concrete<-read.csv(file = "concrete.txt",stringsAsFactors = F) normalize<-function(x){ return((x-min(x))/(max(x)-min(x))) } concrete<-as.data.frame(lapply(concrete, normalize)) concrete_train<-concrete[1:773,] concrete_test<-concrete[774:1030,] concrete_model<-neuralnet(strength~cement+slag+ash+water+superplastic+coarseagg+fineagg+age,data = concrete_train,hidden = 5) model_res<-compute(concrete_model,concrete_test[,1:8]) x=model_res$net.result y=concrete_test$strength cor(x,y) plot(concrete_model)
dput_levels <- function(vec){ if (is.factor(vec)) return(dput(levels(vec))) if (!is.factor(vec)) return(dput(unique(vec))) }
filterarchids_warning <- function(archs_ids, filter) { my_labelsIds <- vector(mode = "character") for(id in archs_ids) { sid = entrez_summary(db = "sparcle", id = id) if(length(sid) > 2) { if(sum(str_count(sid$displabel, filter)) == length(filter) ) { my_labelsIds <- c(my_labelsIds, id) } } } my_labelsIds }
context("Checking children") test_that("children ...",{ })
aout.weibull <- function(data, param, alpha = 0.1, hide.outliers = FALSE, lower = auto.l, upper = auto.u, method.in = "Broyden", global.in = "qline", control.in = list(sigma = 0.1, maxit = 1000, xtol = 1e-12, ftol = 1e-12, btol = 1e-4)){ if (!is.numeric(param) | !is.vector(param) | !identical(all.equal(length(param), 2), TRUE)) stop("param must be a numeric vector of length 2.") if (!is.numeric(data) | !is.vector(data)) stop("data must be a numeric vector.") if (!identical(all.equal(length(alpha), 1), TRUE) | alpha <= 0 | alpha >= 1) stop("alpha must be a real number between 0 and 1, but it is ", alpha, ".") bet <- param[1] lambda <- param[2] auto.l <- qweibull(alpha/2, bet, lambda) auto.u <- qweibull(1 - alpha/2, bet, lambda) fn3 <- function(x, betta, lammda, a) { y <- numeric() y[1] <- 1 - a - pweibull(x[2], betta, lammda) + pweibull(x[1], betta, lammda) y[2] <- dweibull(x[1], betta, lammda) - dweibull(x[2], betta, lammda) y } if (bet > 1) { temp.sol <- nleqslv(c(auto.l, auto.u), fn = fn3, a = alpha, betta = bet, lammda = lambda, method = method.in, global = global.in, control = control.in) if (!identical(all.equal(temp.sol$termcd, 6), TRUE)) temp.region <- temp.sol$x else { warning("Lower bound of inlier region is only approximately zero") temp.region <- c(0, qweibull(1 - alpha, bet, lambda)) } } else temp.region <- c(0, qweibull(1 - alpha, bet, lambda)) temp <- data.frame(data = data, is.outlier = (data < temp.region[1] | data > temp.region[2])) if (identical(all.equal(hide.outliers, FALSE), TRUE)) temp else temp[temp[,2] == FALSE, 1] }
plot_qqline <- function(data, ycol, group, symsize = 3, symthick = 1, s_alpha = 1, ColPal = "all_grafify", ColSeq = TRUE, ColRev = FALSE, TextXAngle = 0, fontsize = 20, Group, ...){ if (!missing("Group")) { warning("Use `group` argument instead, as `Group` is deprecated.") group <- substitute(Group)} if(missing(group)){ P <- ggplot2::ggplot(data, aes(sample = {{ ycol }}))+ geom_qq_line(na.rm = T, size = 1, ...)+ geom_qq(na.rm = T, shape = 21, fill = " size = {{ symsize }}, stroke = {{ symthick }}, alpha = {{ s_alpha }}, ...)+ theme_classic(base_size = {{ fontsize }})+ theme(strip.background = element_blank())+ guides(x = guide_axis(angle = {{ TextXAngle }})) } else { P <- ggplot2::ggplot(data, aes(sample = {{ ycol }}, group = {{ group }}))+ geom_qq_line(na.rm = T, size = 1, ...)+ geom_qq(na.rm = T, shape = 21, aes(fill = {{ group }}), size = {{ symsize }}, stroke = {{ symthick }}, alpha = {{ s_alpha }}, ...)+ labs(fill = enquo(group))+ theme_classic(base_size = {{ fontsize }})+ theme(strip.background = element_blank())+ guides(x = guide_axis(angle = {{ TextXAngle }}))} if (ColSeq) { P <- P + scale_fill_grafify(palette = {{ ColPal }}, reverse = {{ ColRev }}) } else { P <- P + scale_fill_grafify2(palette = {{ ColPal }}, reverse = {{ ColRev }})} P }
lsm_c_contig_mn <- function(landscape, directions = 8) { landscape <- landscape_as_list(landscape) result <- lapply(X = landscape, FUN = lsm_c_contig_mn_calc, directions = directions) layer <- rep(seq_along(result), vapply(result, nrow, FUN.VALUE = integer(1))) result <- do.call(rbind, result) tibble::add_column(result, layer, .before = TRUE) } lsm_c_contig_mn_calc <- function(landscape, directions) { contig <- lsm_p_contig_calc(landscape, directions = directions) if (all(is.na(contig$value))) { return(tibble::tibble(level = "class", class = as.integer(NA), id = as.integer(NA), metric = "contig_mn", value = as.double(NA))) } contig_mn <- stats::aggregate(x = contig[, 5], by = contig[, 2], FUN = mean) return(tibble::tibble(level = "class", class = as.integer(contig_mn$class), id = as.integer(NA), metric = "contig_mn", value = as.double(contig_mn$value))) }
context("detect_entities") body = get_request_body() test_that("detect_entities works on single string", { output <- with_mock( comprehendHTTP = mock_comprehendHTTP, detect_entities(text = body$single$Text, language = body$single$LanguageCode) ) expected <- read.table(sep="\t", text=" Index BeginOffset EndOffset Score Text Type 0 0 10 0.9999857 Jeff Bezos PERSON 0 23 26 0.6394255 CEO PERSON", header=TRUE, stringsAsFactors=FALSE) expect_similar(output, expected) }) test_that("detect_entities works on character vector", { output <- with_mock( comprehendHTTP = mock_comprehendHTTP, detect_entities(text = body$batch$TextList, language = body$batch$LanguageCode) ) expected <- read.table(sep="\t", text=" Index BeginOffset EndOffset Score Text Type 0 0 10 0.9999857 Jeff Bezos PERSON 0 23 26 0.6394255 CEO PERSON 2 0 3 0.9972390 AWS ORGANIZATION 2 13 21 0.5615919 numerous QUANTITY", header=TRUE, stringsAsFactors=FALSE) attr(expected, "ErrorList") <- list() expect_similar(output, expected) })
DBI <- function (mu.link = "logit", sigma.link = "log") { mstats <- checklink("mu.link", "Double Poisson", substitute(mu.link), c("logit", "probit", "cloglog", "cauchit", "log", "own")) dstats <- checklink("sigma.link", "Double Poisson", substitute(sigma.link), c("inverse", "log", "identity", "sqrt")) structure( list( family = c("DBI", "Double Binomial"), parameters = list(mu = TRUE,sigma = TRUE), nopar = 2, type = "Discrete", mu.link = as.character(substitute(mu.link)), sigma.link = as.character(substitute(sigma.link)), mu.linkfun = mstats$linkfun, sigma.linkfun = dstats$linkfun, mu.linkinv = mstats$linkinv, sigma.linkinv = dstats$linkinv, mu.dr = mstats$mu.eta, sigma.dr = dstats$mu.eta, dldm = function(y, mu, sigma, bd) { y/(mu*sigma)-(bd-y)/((1-mu)*sigma)+as.vector(attr(numeric.deriv(GetBI_C(mu, sigma, bd), "mu"),"gradient")) }, d2ldm2 = function(y, mu, sigma, bd) { dldm <- y/(mu*sigma)-(bd-y)/((1-mu)*sigma)+as.vector(attr(numeric.deriv(GetBI_C(mu, sigma, bd), "mu"),"gradient")) d2ldm2 <- -dldm^2 d2ldm2 <- ifelse(d2ldm2 < -1e-15, d2ldm2,-1e-15) d2ldm2 }, dldd = function(y, mu, sigma, bd) { logofy <- ifelse(y==0,1,log(y)) logofn_y <- ifelse(bd==y, 1,log(bd-y)) dldd <- (y*logofy)/sigma^2-(log(mu)*y)/sigma^2+(logofn_y*(bd-y))/sigma^2- (log(1-mu)*(bd-y))/sigma^2-(bd*log(bd))/sigma^2+ as.vector(attr(numeric.deriv(GetBI_C(mu, sigma, bd), "sigma"),"gradient")) dldd }, d2ldd2 = function(y, mu, sigma, bd) { logofy <- ifelse(y==0,1,log(y)) logofn_y <- ifelse(bd==y,1,log(bd-y)) dldd <- (y*logofy)/sigma^2-(log(mu)*y)/sigma^2+(logofn_y* (bd-y))/sigma^2- (log(1-mu)*(bd-y))/sigma^2-(bd*log(bd))/sigma^2+ as.vector(attr(numeric.deriv(GetBI_C(mu, sigma, bd), "sigma"),"gradient")) d2ldd2 <- -dldd^2 d2ldd2 <- ifelse(d2ldd2 < -1e-15, d2ldd2,-1e-15) d2ldd2 }, d2ldmdd = function(y) rep(0,length(y)), G.dev.incr = function(y, mu, sigma, bd,...) -2*dDBI(y, mu, sigma, bd, log = TRUE), rqres = expression( rqres(pfun="pDBI", type="Discrete", ymin=0, bd=bd, y=y, mu=mu, sigma=sigma) ), mu.initial = expression({mu <- (y + 0.5)/(bd + 1)}), sigma.initial = expression(sigma <- rep(1.1,length(y))), mu.valid = function(mu) all(mu > 0) && all(mu < 1), sigma.valid = function(sigma) all(sigma > 0), y.valid = function(y) all(y >= 0) ), class = c("gamlss.family","family")) } GetBI_C <- function(mu, sigma, bd) { ly <- max(length(bd),length(mu),length(sigma)) bd <- rep(bd, length = ly) sigma <- rep(1/sigma, length = ly) mu <- rep(mu, length = ly) TheC <- .C("getBI_C2",as.double(mu),as.double(sigma),as.double(bd), as.integer(ly), theC=double(ly))$theC TheC } dDBI <- function(x, mu = .5, sigma = 1, bd=2, log = FALSE) { if (any(mu < 0) | any(mu > 1)) stop(paste("mu must be between 0 and 1", "\n", "")) if (any(x < 0) ) stop(paste("x must be >=0", "\n", "")) if (any(bd < x)) stop(paste("x must be <= than the binomial denominator", bd, "\n")) if (any(sigma <= 0)) stop(paste("sigma must be positive", "\n", "")) if (any(sigma < 1e-10)) warning(" values of sigma in BB less that 1e-10 are set to 1e-10" ) ly <- max(length(x),length(bd),length(mu),length(sigma)) x <- rep(x, length = ly) bd <- rep(bd, length = ly) sigma <- rep(sigma, length = ly) mu <- rep(mu, length = ly) logofx <- ifelse(x==0,1,log(x)) logofbd_x <- ifelse(bd==x,1,log(bd-x)) res <- GetBI_C(mu,sigma,bd) ll <- ifelse((abs(sigma-1) < 0.001), dbinom(x, size = bd, prob = mu, log = TRUE), lchoose(bd,x)+x*logofx+(bd-x)*logofbd_x-bd*log(bd)+ (bd/sigma)*log(bd) + (x/sigma)*log(mu)+((bd-x)/sigma)*log(1-mu)- (x/sigma)*logofx - ((bd-x)/sigma)*logofbd_x+res) if(log==FALSE) fy <- exp(ll) else fy <- ll fy } pDBI<-function(q, mu = .5, sigma = 1, bd=2, lower.tail = TRUE, log.p = FALSE) { if (any(mu < 0) | any(mu > 1)) stop(paste("mu must be between 0 and 1", "\n", "")) if (any(sigma <= 0) ) stop(paste("sigma must be greater than 0 ", "\n", "")) if (any(q < 0) ) stop(paste("q must be >=0", "\n", "")) ly <- max(length(q),length(mu),length(sigma)) q <- rep(q, length = ly) sigma <- rep(sigma, length = ly) mu <- rep(mu, length = ly) bd <- rep(bd, length = ly) fn <- function(q, mu, sigma, bd) sum(dDBI(0:q, mu=mu, sigma=sigma, bd=bd)) Vcdf <- Vectorize(fn) cdf <- Vcdf(q=q, mu=mu, sigma=sigma, bd=bd) cdf <- if(lower.tail==TRUE) cdf else 1-cdf cdf <- if(log.p==FALSE) cdf else log(cdf) cdf } qDBI <- function(p, mu = .5, sigma = 1, bd=2, lower.tail = TRUE, log.p = FALSE ) { if (any(mu < 0) | any(mu > 1)) stop(paste("mu must be between 0 and 1", "\n", "")) if (any(sigma <= 0) ) stop(paste("sigma must be greater than 0 ", "\n", "")) if (any(p < 0) | any(p > 1.0001)) stop(paste("p must be between 0 and 1", "\n", "")) if (log.p==TRUE) p <- exp(p) else p <- p if (lower.tail==TRUE) p <- p else p <- 1-p ly <- max(length(p),length(mu),length(sigma)) p <- rep(p, length = ly) sigma <- rep(sigma, length = ly) mu <- rep(mu, length = ly) bd <- rep(bd, length = ly) QQQ <- rep(0,ly) nsigma <- rep(sigma, length = ly) nmu <- rep(mu, length = ly) for (i in seq(along=p)) { cumpro <- 0 if (p[i]+0.000000001 >= 1) {QQQ[i] <- bd[i]} else { for (j in seq(from = 0, to = bd[i])) { cumpro <- pDBI(j, mu = mu[i], sigma = sigma[i], bd=bd[i], log.p = FALSE) QQQ[i] <- j if (p[i] <= cumpro ) break } } } QQQ } rDBI <- function(n,mu = .5, sigma = 1, bd=2) { if (any(mu < 0) | any(mu > 1)) stop(paste("mu must be between 0 and 1", "\n", "")) if (any(sigma <= 0) ) stop(paste("sigma must be greater than 0 ", "\n", "")) if (any(n <= 0)) stop(paste("n must be a positive integer", "\n", "")) n <- ceiling(n) p <- runif(n) r <- qDBI(p, mu=mu, sigma=sigma, bd = bd ) as.integer(r) }
filesroot = "/home/peter/Data/EOD.Global.Indexes" setwd(paste(filesroot, "/.incoming", sep="")) start_t<-Sys.time() if (!file.exists("../.archive")){ dir.create("../.archive", mode="0777") dir.create("../.archive/csv_files", mode="0777") dir.create("../.archive/zip_files", mode="0777") } if (!file.exists("../.archive/zip_files")) dir.create("../.archive/zip_files", mode="0777") if (!file.exists("../.archive/csv_files")) dir.create("../.archive/csv_files", mode="0777") zipfiles = list.files(pattern="*.zip") if(length(zipfiles)>0){ system("unzip \\*.zip") system("mv *.zip ../.archive/zip_files/") } else { print("No zip files to process.") } files = list.files(pattern="*.csv") if(length(files) == 0){ stop("There are no csv files to process in the .incoming directory.") } prevfiles = list.files("../.archive/csv_files") rmfiles = files[files %in% prevfiles] if(length(rmfiles) >0){ file.remove(rmfiles) files = files[!files %in% prevfiles] } if (length(files) == 0) stop("There are no files to process or these files have been processed previously. Stopping.") for (file in files){ print(paste("Splitting ",file,sep="")) system(paste('awk -F "," ' , "'NR!=1 {filename=$1; sub($1FS,blank); print >> filename",'".csv"',"}'" , file, sep=" ")) system(paste("mv ", file, " ../.archive/csv_files/", file, sep="")) } tmpfiles = list.files() header = 'Date,Open,High,Low,Close,Volume' for (file in tmpfiles){ targetdir = strtrim(file, (nchar(file)-4)) fullpathdir = paste("../", targetdir, sep="") fullpathfile = paste("../", targetdir, "/", file, sep="") if (!file.exists(fullpathdir)){ dir.create(fullpathdir, mode="0777") system(paste("echo ", header," > ", fullpathfile, sep="")) } print(paste("Updating ", file, sep="")) system(paste("cat ", file, " >> ", fullpathfile, sep="")) file.remove(file) } end_t<-Sys.time() print(c("Elapsed time: ",end_t-start_t)) print(paste("Processed ", length(files) ," days of prices for ", length(tmpfiles), " symbols.", sep=""))
dd_logliknorm_rhs2 = function(t,x,m) { nx = sqrt(length(x)) dim(x) = c(nx,nx) xx = matrix(0,nx+2,nx+2) xx[2:(nx+1),2:(nx+1)] = x dx = m[[1]] * xx[1:nx,2:(nx+1)] + m[[2]] * xx[3:(nx+2),2:(nx+1)] + m[[4]] * xx[2:(nx+1),1:nx] + m[[5]] * xx[2:(nx+1),3:(nx+2)] - (m[[3]] + m[[6]]) * xx[2:(nx+1),2:(nx+1)] dim(dx) = c(nx^2,1) return(list(dx)) }
ls_fun_calls <- function (x) { if (is.function(x)) { c(ls_fun_calls(formals(x)), ls_fun_calls(body(x))) } else if (is.call(x)) { fname <- as.character(x[[1]]) c(list(fname), unlist(lapply(x[-1], ls_fun_calls), use.names = FALSE, recursive = FALSE)) } }
NULL check_i_arguments <- function(arg, nn, n_v, dots = FALSE) { mc <- match.call() varname <- sub("dots$", "", deparse(mc[["arg"]]), fixed = TRUE) if (!is.list(arg)) { if ((!is.vector(arg, "numeric")) || (length(arg) < 1)) stop(paste(varname, "needs to be a numeric vector of length >= 1!")) if (dots) { arg <- as.list(arg) arg <- lapply(arg, rep, length.out=nn) } else arg <- lapply(seq_len(n_v), function(x) rep(arg, length.out=nn)) } else { if (!dots && (length(arg) != n_v)) stop(paste("if", varname, "is a list, its length needs to correspond to the number of accumulators.")) for (i in seq_along(arg)) { if ((!is.vector(arg[[i]], "numeric")) || (length(arg[[i]]) < 1)) stop(paste0(varname, "[[", i, "]] needs to be a numeric vector of length >= 1!")) arg[[i]] <- rep(arg[[i]], length.out=nn) } } return(arg) } dLBA <- function(rt, response, A, b, t0, ..., st0=0, distribution = c("norm", "gamma", "frechet", "lnorm"), args.dist = list(), silent = FALSE) { dots <- list(...) if (is.null(names(dots))) stop("... arguments need to be named.") if (is.data.frame(rt)) { response <- rt$response rt <- rt$rt } response <- as.numeric(response) nn <- length(rt) n_v <- max(vapply(dots, length, 0)) if(!silent) message(paste("Results based on", n_v, "accumulators/drift rates.")) if (!is.numeric(response) || max(response) > n_v) stop("response needs to be a numeric vector of integers up to number of accumulators.") if (any(response < 1)) stop("the first response/accumulator must have value 1.") if (n_v < 2) stop("There need to be at least two accumulators/drift rates.") distribution <- match.arg(distribution) response <- rep(response, length.out = nn) A <- check_i_arguments(A, nn=nn, n_v=n_v) b <- check_i_arguments(b, nn=nn, n_v=n_v) t0 <- check_i_arguments(t0, nn=nn, n_v=n_v) switch(distribution, norm = { if (any(!(c("mean_v","sd_v") %in% names(dots)))) stop("mean_v and sd_v need to be passed for distribution = \"norm\"") dots$mean_v <- check_i_arguments(dots$mean_v, nn=nn, n_v=n_v, dots = TRUE) dots$sd_v <- check_i_arguments(dots$sd_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("mean_v","sd_v")] }, gamma = { if (!("shape_v" %in% names(dots))) stop("shape_v needs to be passed for distribution = \"gamma\"") if ((!("rate_v" %in% names(dots))) & (!("scale_v" %in% names(dots)))) stop("rate_v or scale_v need to be passed for distribution = \"gamma\"") dots$shape_v <- check_i_arguments(dots$shape_v, nn=nn, n_v=n_v, dots = TRUE) if ("scale_v" %in% names(dots)) { dots$scale_v <- check_i_arguments(dots$scale_v, nn=nn, n_v=n_v, dots = TRUE) if (is.list(dots$scale_v)) { dots$rate_v <- lapply(dots$scale_v, function(x) 1/x) } else dots$rate_v <- 1/dots$scale_v } else dots$rate_v <- check_i_arguments(dots$rate_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("shape_v","rate_v")] }, frechet = { if (any(!(c("shape_v","scale_v") %in% names(dots)))) stop("shape_v and scale_v need to be passed for distribution = \"frechet\"") dots$shape_v <- check_i_arguments(dots$shape_v, nn=nn, n_v=n_v, dots = TRUE) dots$scale_v <- check_i_arguments(dots$scale_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("shape_v","scale_v")] }, lnorm = { if (any(!(c("meanlog_v","sdlog_v") %in% names(dots)))) stop("meanlog_v and sdlog_v need to be passed for distribution = \"lnorm\"") dots$meanlog_v <- check_i_arguments(dots$meanlog_v, nn=nn, n_v=n_v, dots = TRUE) dots$sdlog_v <- check_i_arguments(dots$sdlog_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("meanlog_v","sdlog_v")] } ) for (i in seq_len(length(dots))) { if (length(dots[[i]]) < n_v) dots[[i]] <- rep(dots[[i]],length.out=n_v) } out <- vector("numeric", nn) for (i in unique(response)) { sel <- response == i out[sel] <- do.call(n1PDF, args = c(rt=list(rt[sel]), A = list(lapply(A, "[", i = sel)[c(i, seq_len(n_v)[-i])]), b = list(lapply(b, "[", i = sel)[c(i, seq_len(n_v)[-i])]), t0 = list(lapply(t0, "[", i = sel)[c(i, seq_len(n_v)[-i])]), lapply(dots, function(x) lapply(x, "[", i = sel)[c(i, seq_len(n_v)[-i])]), distribution=distribution, args.dist=list(args.dist), silent=TRUE, st0 = list(st0))) } return(out) } pLBA <- function(rt, response, A, b, t0, ..., st0=0, distribution = c("norm", "gamma", "frechet", "lnorm"), args.dist = list(), silent = FALSE) { dots <- list(...) if (is.null(names(dots))) stop("... arguments need to be named.") if (is.data.frame(rt)) { response <- rt$response rt <- rt$rt } response <- as.numeric(response) nn <- length(rt) n_v <- max(vapply(dots, length, 0)) if(!silent) message(paste("Results based on", n_v, "accumulators/drift rates.")) if (!is.numeric(response) || max(response) > n_v) stop("response needs to be a numeric vector of integers up to number of accumulators.") if (n_v < 2) stop("There need to be at least two accumulators/drift rates.") distribution <- match.arg(distribution) response <- rep(response, length.out = nn) A <- check_i_arguments(A, nn=nn, n_v=n_v) b <- check_i_arguments(b, nn=nn, n_v=n_v) t0 <- check_i_arguments(t0, nn=nn, n_v=n_v) switch(distribution, norm = { if (any(!(c("mean_v","sd_v") %in% names(dots)))) stop("mean_v and sd_v need to be passed for distribution = \"norm\"") dots$mean_v <- check_i_arguments(dots$mean_v, nn=nn, n_v=n_v, dots = TRUE) dots$sd_v <- check_i_arguments(dots$sd_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("mean_v","sd_v")] }, gamma = { if (!("shape_v" %in% names(dots))) stop("shape_v needs to be passed for distribution = \"gamma\"") if ((!("rate_v" %in% names(dots))) & (!("scale_v" %in% names(dots)))) stop("rate_v or scale_v need to be passed for distribution = \"gamma\"") dots$shape_v <- check_i_arguments(dots$shape_v, nn=nn, n_v=n_v, dots = TRUE) if ("scale_v" %in% names(dots)) { dots$scale_v <- check_i_arguments(dots$scale_v, nn=nn, n_v=n_v, dots = TRUE) if (is.list(dots$scale_v)) { dots$rate_v <- lapply(dots$scale_v, function(x) 1/x) } else dots$rate_v <- 1/dots$scale_v } else dots$rate_v <- check_i_arguments(dots$rate_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("shape_v","rate_v")] }, frechet = { if (any(!(c("shape_v","scale_v") %in% names(dots)))) stop("shape_v and scale_v need to be passed for distribution = \"frechet\"") dots$shape_v <- check_i_arguments(dots$shape_v, nn=nn, n_v=n_v, dots = TRUE) dots$scale_v <- check_i_arguments(dots$scale_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("shape_v","scale_v")] }, lnorm = { if (any(!(c("meanlog_v","sdlog_v") %in% names(dots)))) stop("meanlog_v and sdlog_v need to be passed for distribution = \"lnorm\"") dots$meanlog_v <- check_i_arguments(dots$meanlog_v, nn=nn, n_v=n_v, dots = TRUE) dots$sdlog_v <- check_i_arguments(dots$sdlog_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("meanlog_v","sdlog_v")] } ) for (i in seq_len(length(dots))) { if (length(dots[[i]]) < n_v) dots[[i]] <- rep(dots[[i]],length.out=n_v) } out <- vector("numeric", nn) for (i in unique(response)) { sel <- response == i out[sel] <- do.call(n1CDF, args = c(rt=list(rt[sel]), A = list(lapply(A, "[", i = sel)[c(i, seq_len(n_v)[-i])]), b = list(lapply(b, "[", i = sel)[c(i, seq_len(n_v)[-i])]), t0 = list(lapply(t0, "[", i = sel)[c(i, seq_len(n_v)[-i])]), lapply(dots, function(x) lapply(x, "[", i = sel)[c(i, seq_len(n_v)[-i])]), distribution=distribution, args.dist=list(args.dist), silent=TRUE, st0 = list(st0))) } return(out) } inv_cdf_lba <- function(x, response, A, b, t0, ..., st0, distribution, args.dist, value, abs = TRUE) { if (abs) abs(value - pLBA(rt=x, response=response, A=A, b = b, t0 = t0, ..., st0=st0, distribution=distribution, args.dist=args.dist, silent=TRUE)) else (value - pLBA(rt=x, response=response, A=A, b = b, t0 = t0, ..., st0=st0, distribution=distribution, args.dist=args.dist, silent=TRUE)) } qLBA <- function(p, response, A, b, t0, ..., st0=0, distribution = c("norm", "gamma", "frechet", "lnorm"), args.dist = list(), silent = FALSE, interval = c(0, 10), scale_p = FALSE, scale_max = Inf) { dots <- list(...) if (is.null(names(dots))) stop("... arguments need to be named.") if (is.data.frame(p)) { response <- p$response p <- p$p } response <- as.numeric(response) nn <- length(p) n_v <- max(vapply(dots, length, 0)) if(!silent) message(paste("Results based on", n_v, "accumulators/drift rates.")) if (!is.numeric(response) || max(response) > n_v) stop("response needs to be a numeric vector of integers up to number of accumulators.") if (any(response < 1)) stop("the first response/accumulator must have value 1.") if (n_v < 2) stop("There need to be at least two accumulators/drift rates.") distribution <- match.arg(distribution) response <- rep(response, length.out = nn) A <- check_i_arguments(A, nn=nn, n_v=n_v) b <- check_i_arguments(b, nn=nn, n_v=n_v) t0 <- check_i_arguments(t0, nn=nn, n_v=n_v) st0 <- rep(st0, length.out = nn) out <- vector("numeric", nn) p <- unname(p) for (i in seq_len(nn)) { if (scale_p) max_p <- do.call( pLBA, args = c( rt = list(scale_max), response = list(response[i]), A = ret_arg(A, i), b = ret_arg(b, i), t0 = ret_arg(t0, i), sapply(dots, function(z, i) sapply(z, ret_arg2, which = i, simplify = FALSE), i = i, simplify = FALSE), args.dist = list(args.dist), distribution = distribution, st0 = list(st0[i]), silent = TRUE ) ) else max_p <- 1 tmp <- do.call( optimize, args = c( f = inv_cdf_lba, interval = list(interval), response = list(response[i]), A = ret_arg(A, i), b = ret_arg(b, i), t0 = ret_arg(t0, i), sapply(dots, function(z, i) sapply(z, ret_arg2, which = i, simplify = FALSE), i = i, simplify = FALSE), args.dist = list(args.dist), distribution = distribution, st0 = list(st0[i]), value = p[i] * max_p, tol = .Machine$double.eps ^ 0.5 ) ) if (tmp$objective > 0.0001) { tmp <- do.call( optimize, args = c( f = inv_cdf_lba, interval = list(c(min(interval), max(interval) / 2)), response = list(response[i]), A = ret_arg(A, i), b = ret_arg(b, i), t0 = ret_arg(t0, i), sapply(dots, function(z, i) sapply(z, ret_arg2, which = i, simplify = FALSE), i = i, simplify = FALSE), args.dist = list(args.dist), distribution = distribution, st0 = list(st0[i]), value = p[i] * max_p, tol = .Machine$double.eps ^ 0.5 ) ) } if (tmp$objective > 0.0001) { try({ uni_tmp <- do.call( uniroot, args = c( f = inv_cdf_lba, interval = list(c(min(interval), max(interval) / 2)), response = list(response[i]), A = ret_arg(A, i), b = ret_arg(b, i), t0 = ret_arg(t0, i), sapply(dots, function(z, i) sapply(z, ret_arg2, which = i, simplify = FALSE), i = i, simplify = FALSE), args.dist = list(args.dist), distribution = distribution, st0 = list(st0[i]), value = p[i] * max_p, tol = .Machine$double.eps ^ 0.5, abs = FALSE ) ) tmp$objective <- uni_tmp$f.root tmp$minimum <- uni_tmp$root }, silent = TRUE) } if (tmp$objective > 0.0001) { tmp[["minimum"]] <- NA warning( "Cannot obtain RT that is less than 0.0001 away from desired p = ", p[i], ".\nIncrease/decrease interval or obtain for different boundary.", call. = FALSE ) } out[i] <- tmp[["minimum"]] } return(out ) } rLBA <- function(n,A,b,t0, ..., st0=0, distribution = c("norm", "gamma", "frechet", "lnorm"), args.dist = list(), silent = FALSE) { dots <- list(...) if (is.null(names(dots))) stop("... arguments need to be named.") if (any(names(dots) == "")) stop("all ... arguments need to be named.") n_v <- max(vapply(dots, length, 0)) if(!silent) message(paste("Results based on", n_v, "accumulators/drift rates.")) nn <- n distribution <- match.arg(distribution) A <- check_i_arguments(A, nn=nn, n_v=n_v) b <- check_i_arguments(b, nn=nn, n_v=n_v) t0 <- check_i_arguments(t0, nn=nn, n_v=n_v) st0 <- rep(unname(st0), length.out = nn) switch(distribution, norm = { rng <- rlba_norm if (any(!(c("mean_v","sd_v") %in% names(dots)))) stop("mean_v and sd_v need to be passed for distribution = \"norm\"") dots$mean_v <- check_i_arguments(dots$mean_v, nn=nn, n_v=n_v, dots = TRUE) dots$sd_v <- check_i_arguments(dots$sd_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("mean_v","sd_v")] }, gamma = { rng <- rlba_gamma if (!("shape_v" %in% names(dots))) stop("shape_v needs to be passed for distribution = \"gamma\"") if ((!("rate_v" %in% names(dots))) & (!("scale_v" %in% names(dots)))) stop("rate_v or scale_v need to be passed for distribution = \"gamma\"") dots$shape_v <- check_i_arguments(dots$shape_v, nn=nn, n_v=n_v, dots = TRUE) if ("scale_v" %in% names(dots)) { dots$scale_v <- check_i_arguments(dots$scale_v, nn=nn, n_v=n_v, dots = TRUE) if (is.list(dots$scale_v)) { dots$rate_v <- lapply(dots$scale_v, function(x) 1/x) } else dots$rate_v <- 1/dots$scale_v } else dots$rate_v <- check_i_arguments(dots$rate_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("shape_v","rate_v")] }, frechet = { rng <- rlba_frechet if (any(!(c("shape_v","scale_v") %in% names(dots)))) stop("shape_v and scale_v need to be passed for distribution = \"frechet\"") dots$shape_v <- check_i_arguments(dots$shape_v, nn=nn, n_v=n_v, dots = TRUE) dots$scale_v <- check_i_arguments(dots$scale_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("shape_v","scale_v")] }, lnorm = { rng <- rlba_lnorm if (any(!(c("meanlog_v","sdlog_v") %in% names(dots)))) stop("meanlog_v and sdlog_v need to be passed for distribution = \"lnorm\"") dots$meanlog_v <- check_i_arguments(dots$meanlog_v, nn=nn, n_v=n_v, dots = TRUE) dots$sdlog_v <- check_i_arguments(dots$sdlog_v, nn=nn, n_v=n_v, dots = TRUE) dots <- dots[c("meanlog_v","sdlog_v")] } ) for (i in seq_len(length(dots))) { if (length(dots[[i]]) < n_v) dots[[i]] <- rep(dots[[i]],length.out=n_v) } tmp_acc <- as.data.frame(dots, optional = TRUE) colnames(tmp_acc) <- sub("\\.c\\(.+", "", colnames(tmp_acc)) parameter_char <- apply(tmp_acc, 1, paste0, collapse = "\t") parameter_factor <- factor(parameter_char, levels = unique(parameter_char)) parameter_indices <- split(seq_len(nn), f = parameter_factor) out <- vector("list", length(parameter_indices)) for (i in seq_len(length(parameter_indices))) { ok_rows <- parameter_indices[[i]] tmp_dots <- lapply(dots, function(x) sapply(x, "[[", i = ok_rows[1])) out[[i]] <- do.call(rng, args = c(n=list(length(ok_rows)), A = list(sapply(A, "[", i = ok_rows)), b = list(sapply(b, "[", i = ok_rows)), t0 = list(sapply(t0, "[", i = ok_rows)), st0 = list(st0[ok_rows]), tmp_dots, args.dist)) } out <- do.call("rbind", out) as.data.frame(out) }
library(testthat) escapeString <- function(s) { t <- gsub("(\\\\)", "\\\\\\\\", s) t <- gsub("(\n)", "\\\\n", t) t <- gsub("(\r)", "\\\\r", t) t <- gsub("(\")", "\\\\\"", t) return(t) } prepStr <- function(s) { t <- escapeString(s) u <- eval(parse(text=paste0("\"", t, "\""))) if(s!=u) stop("Unable to escape string!") t <- paste0("\thtml <- \"", t, "\"") utils::writeClipboard(t) return(invisible()) } evaluationMode <- "sequential" processingLibrary <- "dplyr" description <- "test: sequential dplyr" countFunction <- "n()" isDevelopmentVersion <- (length(strsplit(packageDescription("pivottabler")$Version, "\\.")[[1]]) > 3) testScenarios <- function(description="test", releaseEvaluationMode="batch", releaseProcessingLibrary="dplyr", runAllForReleaseVersion=FALSE) { isDevelopmentVersion <- (length(strsplit(packageDescription("pivottabler")$Version, "\\.")[[1]]) > 3) if(isDevelopmentVersion||runAllForReleaseVersion) { evaluationModes <- c("sequential", "batch") processingLibraries <- c("dplyr", "data.table") } else { evaluationModes <- releaseEvaluationMode processingLibraries <- releaseProcessingLibrary } testCount <- length(evaluationModes)*length(processingLibraries) c1 <- character(testCount) c2 <- character(testCount) c3 <- character(testCount) c4 <- character(testCount) testCount <- 0 for(evaluationMode in evaluationModes) for(processingLibrary in processingLibraries) { testCount <- testCount + 1 c1[testCount] <- evaluationMode c2[testCount] <- processingLibrary c3[testCount] <- paste0(description, ": ", evaluationMode, " ", processingLibrary) c4[testCount] <- ifelse(processingLibrary=="data.table", ".N", "n()") } df <- data.frame(evaluationMode=c1, processingLibrary=c2, description=c3, countFunction=c4, stringsAsFactors=FALSE) return(df) } context("CALCULATION TESTS") if (requireNamespace("lubridate", quietly = TRUE)) { scenarios <- testScenarios("calculation tests: calculate dply summarise") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) library(dplyr) library(lubridate) trains <- mutate(bhmtrains, ArrivalDelta=difftime(ActualArrival, GbttArrival, units="mins"), ArrivalDelay=ifelse(ArrivalDelta<0, 0, ArrivalDelta)) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(trains) pt$addRowDataGroups("TOC", totalCaption="All TOCs") pt$defineCalculation(calculationName="TotalTrains", caption="Total Trains", summariseExpression=countFunction) pt$defineCalculation(calculationName="MinArrivalDelay", caption="Min Arr. Delay", summariseExpression="min(ArrivalDelay, na.rm=TRUE)") pt$defineCalculation(calculationName="MaxArrivalDelay", caption="Max Arr. Delay", summariseExpression="max(ArrivalDelay, na.rm=TRUE)") pt$defineCalculation(calculationName="MeanArrivalDelay", caption="Mean Arr. Delay", summariseExpression="mean(ArrivalDelay, na.rm=TRUE)", format="%.1f") pt$defineCalculation(calculationName="MedianArrivalDelay", caption="Median Arr. Delay", summariseExpression="median(ArrivalDelay, na.rm=TRUE)") pt$defineCalculation(calculationName="IQRArrivalDelay", caption="Delay IQR", summariseExpression="IQR(ArrivalDelay, na.rm=TRUE)") pt$defineCalculation(calculationName="SDArrivalDelay", caption="Delay Std. Dev.", summariseExpression="sd(ArrivalDelay, na.rm=TRUE)", format="%.1f") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total Trains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Min Arr. Delay</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Max Arr. Delay</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Mean Arr. Delay</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Median Arr. Delay</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Delay IQR</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Delay Std. Dev.</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3909</td>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">49</td>\n <td class=\"Cell\">2.3</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">4.3</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">22928</td>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">273</td>\n <td class=\"Cell\">3.5</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">4</td>\n <td class=\"Cell\">8.1</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">48279</td>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">177</td>\n <td class=\"Cell\">2.3</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">4.2</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">181</td>\n <td class=\"Cell\">3.0</td>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">8.4</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">All TOCs</th>\n <td class=\"Cell\">83710</td>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">273</td>\n <td class=\"Cell\">2.7</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">6.1</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 168438.858522) expect_identical(as.character(pt$getHtml()), html) }) } } if (requireNamespace("lubridate", quietly = TRUE)) { scenarios <- testScenarios("calculation tests: calculate on rows dply summarise") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) library(dplyr) library(lubridate) trains <- mutate(bhmtrains, ArrivalDelta=difftime(ActualArrival, GbttArrival, units="mins"), ArrivalDelay=ifelse(ArrivalDelta<0, 0, ArrivalDelta)) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(trains) pt$addColumnDataGroups("TOC", totalCaption="All TOCs") pt$defineCalculation(calculationName="TotalTrains", caption="Total Trains", summariseExpression=countFunction) pt$defineCalculation(calculationName="MinArrivalDelay", caption="Min Arr. Delay", summariseExpression="min(ArrivalDelay, na.rm=TRUE)") pt$defineCalculation(calculationName="MaxArrivalDelay", caption="Max Arr. Delay", summariseExpression="max(ArrivalDelay, na.rm=TRUE)") pt$defineCalculation(calculationName="MeanArrivalDelay", caption="Mean Arr. Delay", summariseExpression="mean(ArrivalDelay, na.rm=TRUE)", format="%.1f") pt$defineCalculation(calculationName="MedianArrivalDelay", caption="Median Arr. Delay", summariseExpression="median(ArrivalDelay, na.rm=TRUE)") pt$defineCalculation(calculationName="IQRArrivalDelay", caption="Delay IQR", summariseExpression="IQR(ArrivalDelay, na.rm=TRUE)") pt$defineCalculation(calculationName="SDArrivalDelay", caption="Delay Std. Dev.", summariseExpression="sd(ArrivalDelay, na.rm=TRUE)", format="%.1f") pt$addRowCalculationGroups() pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Arriva Trains Wales</th>\n <th class=\"ColumnHeader\" colspan=\"1\">CrossCountry</th>\n <th class=\"ColumnHeader\" colspan=\"1\">London Midland</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Virgin Trains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">All TOCs</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total Trains</th>\n <td class=\"Cell\">3909</td>\n <td class=\"Cell\">22928</td>\n <td class=\"Cell\">48279</td>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">83710</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Min Arr. Delay</th>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">0</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Max Arr. Delay</th>\n <td class=\"Cell\">49</td>\n <td class=\"Cell\">273</td>\n <td class=\"Cell\">177</td>\n <td class=\"Cell\">181</td>\n <td class=\"Cell\">273</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Mean Arr. Delay</th>\n <td class=\"Cell\">2.3</td>\n <td class=\"Cell\">3.5</td>\n <td class=\"Cell\">2.3</td>\n <td class=\"Cell\">3.0</td>\n <td class=\"Cell\">2.7</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Median Arr. Delay</th>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">0</td>\n <td class=\"Cell\">1</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Delay IQR</th>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">4</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n <td class=\"Cell\">3</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Delay Std. Dev.</th>\n <td class=\"Cell\">4.3</td>\n <td class=\"Cell\">8.1</td>\n <td class=\"Cell\">4.2</td>\n <td class=\"Cell\">8.4</td>\n <td class=\"Cell\">6.1</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 168438.858522) expect_identical(as.character(pt$getHtml()), html) }) } } if (requireNamespace("lubridate", quietly = TRUE)) { scenarios <- testScenarios("calculation tests: deriving values from other calculations") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) library(dplyr) library(lubridate) trains <- mutate(bhmtrains, ArrivalDelta=difftime(ActualArrival, GbttArrival, units="mins"), ArrivalDelay=ifelse(ArrivalDelta<0, 0, ArrivalDelta), DelayedByMoreThan5Minutes=ifelse(ArrivalDelay>5,1,0)) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(trains) pt$addRowDataGroups("TOC", totalCaption="All TOCs") pt$defineCalculation(calculationName="DelayedTrains", caption="Trains Arr. 5+ Mins Late", summariseExpression="sum(DelayedByMoreThan5Minutes, na.rm=TRUE)") pt$defineCalculation(calculationName="TotalTrains", caption="Total Trains", summariseExpression=countFunction) pt$defineCalculation(calculationName="DelayedPercent", caption="% Trains Arr. 5+ Mins Late", type="calculation", basedOn=c("DelayedTrains", "TotalTrains"), format="%.1f %%", calculationExpression="values$DelayedTrains/values$TotalTrains*100") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Trains Arr. 5+ Mins Late</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total Trains</th>\n <th class=\"ColumnHeader\" colspan=\"1\">% Trains Arr. 5+ Mins Late</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">372</td>\n <td class=\"Cell\">3909</td>\n <td class=\"Cell\">9.5 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">2780</td>\n <td class=\"Cell\">22928</td>\n <td class=\"Cell\">12.1 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">3561</td>\n <td class=\"Cell\">48279</td>\n <td class=\"Cell\">7.4 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">770</td>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">9.0 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">All TOCs</th>\n <td class=\"Cell\">7483</td>\n <td class=\"Cell\">83710</td>\n <td class=\"Cell\">8.9 %</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix()), 182432.916225) expect_identical(as.character(pt$getHtml()), html) }) } } scenarios <- testScenarios("calculation tests: showing values only") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) library(dplyr) trains <- bhmtrains %>% group_by(TrainCategory, TOC) %>% summarise(NumberOfTrains=n()) %>% ungroup() pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(trains) pt$addColumnDataGroups("TrainCategory", addTotal=FALSE) pt$addRowDataGroups("TOC", addTotal=FALSE) pt$defineCalculation(calculationName="TotalTrains", type="value", valueName="NumberOfTrains") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">830</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">63</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">33792</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\"></td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 83710) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: showing values plus derived totals") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) library(dplyr) trains <- bhmtrains %>% group_by(TrainCategory, TOC) %>% summarise(NumberOfTrains=n()) %>% ungroup() pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(trains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", type="value", valueName="NumberOfTrains", summariseExpression="sum(NumberOfTrains)") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">830</td>\n <td class=\"Cell\">3909</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">63</td>\n <td class=\"Cell\">22928</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">33792</td>\n <td class=\"Cell\">48279</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">8594</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">49025</td>\n <td class=\"Cell\">34685</td>\n <td class=\"Cell\">83710</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 334840) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: showing values plus pre-calculated totals") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(dplyr) library(pivottabler) trains <- bhmtrains %>% group_by(TrainCategory, TOC) %>% summarise(NumberOfTrains=n()) %>% ungroup() trainsTrainCat <- bhmtrains %>% group_by(TrainCategory) %>% summarise(NumberOfTrains=n()) %>% ungroup() trainsTOC <- bhmtrains %>% group_by(TOC) %>% summarise(NumberOfTrains=n()) %>% ungroup() trainsTotal <- bhmtrains %>% summarise(NumberOfTrains=n()) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode) pt$addData(trains) pt$addTotalData(trainsTrainCat, variableNames="TrainCategory") pt$addTotalData(trainsTOC, variableNames="TOC") pt$addTotalData(trainsTotal, variableNames=NULL) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="TotalTrains", type="value", valueName="NumberOfTrains") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\">&nbsp;</th>\n <th class=\"ColumnHeader\">Express Passenger</th>\n <th class=\"ColumnHeader\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">Arriva Trains Wales</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">830</td>\n <td class=\"Total\">3909</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">CrossCountry</th>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">63</td>\n <td class=\"Total\">22928</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">London Midland</th>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">33792</td>\n <td class=\"Total\">48279</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\"></td>\n <td class=\"Total\">8594</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Total</th>\n <td class=\"Total\">49025</td>\n <td class=\"Total\">34685</td>\n <td class=\"Total\">83710</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 334840) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: calcs first 1") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$defineCalculation(calculationName="NumberOfTrains", caption="Number of Trains", summariseExpression=countFunction) pt$defineCalculation(calculationName="MaximumSpeedMPH", caption="Maximum Speed (MPH)", summariseExpression="max(SchedSpeedMPH, na.rm=TRUE)") pt$addColumnCalculationGroups() pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"3\">Number of Trains</th>\n <th class=\"ColumnHeader\" colspan=\"3\">Maximum Speed (MPH)</th>\n </tr>\n <tr>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">830</td>\n <td class=\"Cell\">3909</td>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\">90</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">63</td>\n <td class=\"Cell\">22928</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">125</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">33792</td>\n <td class=\"Cell\">48279</td>\n <td class=\"Cell\">110</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">110</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">125</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">49025</td>\n <td class=\"Cell\">34685</td>\n <td class=\"Cell\">83710</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">125</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 336380) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: calcs first 2") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE, noDataGroupNBSP=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addColumnDataGroups("PowerType") pt$defineCalculation(calculationName="NumberOfTrains", caption="Number of Trains", summariseExpression=countFunction) pt$defineCalculation(calculationName="MaximumSpeedMPH", caption="Maximum Speed (MPH)", summariseExpression="max(SchedSpeedMPH, na.rm=TRUE)") pt$addRowCalculationGroups() pt$addRowDataGroups("TOC") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\" colspan=\"2\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"4\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"3\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"ColumnHeader\" colspan=\"1\">DMU</th>\n <th class=\"ColumnHeader\" colspan=\"1\">EMU</th>\n <th class=\"ColumnHeader\" colspan=\"1\">HST</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n <th class=\"ColumnHeader\" colspan=\"1\">DMU</th>\n <th class=\"ColumnHeader\" colspan=\"1\">EMU</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n <th class=\"ColumnHeader\" colspan=\"1\"></th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"5\">Number of Trains</th>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">3079</td>\n <td class=\"Cell\">830</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">830</td>\n <td class=\"Cell\">3909</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">22133</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">732</td>\n <td class=\"Cell\">22865</td>\n <td class=\"Cell\">63</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">63</td>\n <td class=\"Cell\">22928</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">5638</td>\n <td class=\"Cell\">8849</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">14487</td>\n <td class=\"Cell\">5591</td>\n <td class=\"Cell\">28201</td>\n <td class=\"Cell\">33792</td>\n <td class=\"Cell\">48279</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">2137</td>\n <td class=\"Cell\">6457</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">8594</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">8594</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">32987</td>\n <td class=\"Cell\">15306</td>\n <td class=\"Cell\">732</td>\n <td class=\"Cell\">49025</td>\n <td class=\"Cell\">6484</td>\n <td class=\"Cell\">28201</td>\n <td class=\"Cell\">34685</td>\n <td class=\"Cell\">83710</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"5\">Maximum Speed (MPH)</th>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">90</td>\n <td class=\"Cell\">90</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">125</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">110</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">110</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">110</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">125</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">125</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">100</td>\n <td class=\"Cell\">125</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 505565) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: filter overrides - % of row total") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="CountTrains", summariseExpression=countFunction, caption="Count", visible=FALSE) filterOverrides <- PivotFilterOverrides$new(pt, keepOnlyFiltersFor="TOC") pt$defineCalculation(calculationName="TOCTotalTrains", filters=filterOverrides, summariseExpression=countFunction, caption="TOC Total", visible=FALSE) pt$defineCalculation(calculationName="PercentageOfTOCTrains", type="calculation", basedOn=c("CountTrains", "TOCTotalTrains"), calculationExpression="values$CountTrains/values$TOCTotalTrains*100", format="%.1f %%", caption="% of TOC") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">78.8 %</td>\n <td class=\"Cell\">21.2 %</td>\n <td class=\"Cell\">100.0 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">99.7 %</td>\n <td class=\"Cell\">0.3 %</td>\n <td class=\"Cell\">100.0 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">30.0 %</td>\n <td class=\"Cell\">70.0 %</td>\n <td class=\"Cell\">100.0 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">100.0 %</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">100.0 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">58.6 %</td>\n <td class=\"Cell\">41.4 %</td>\n <td class=\"Cell\">100.0 %</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 1000) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: filter overrides - % of grand total") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="CountTrains", summariseExpression=countFunction, caption="Count", visible=FALSE) filterOverrides <- PivotFilterOverrides$new(pt, removeAllFilters=TRUE) pt$defineCalculation(calculationName="GrandTotalTrains", filters=filterOverrides, summariseExpression=countFunction, caption="Grand Total", visible=FALSE) pt$defineCalculation(calculationName="PercentageOfAllTrains", type="calculation", basedOn=c("CountTrains", "GrandTotalTrains"), calculationExpression="values$CountTrains/values$GrandTotalTrains*100", format="%.1f %%", caption="% of All") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">3.7 %</td>\n <td class=\"Cell\">1.0 %</td>\n <td class=\"Cell\">4.7 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">27.3 %</td>\n <td class=\"Cell\">0.1 %</td>\n <td class=\"Cell\">27.4 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">17.3 %</td>\n <td class=\"Cell\">40.4 %</td>\n <td class=\"Cell\">57.7 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">10.3 %</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">10.3 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">58.6 %</td>\n <td class=\"Cell\">41.4 %</td>\n <td class=\"Cell\">100.0 %</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 400) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: filter overrides - ratios/multiples") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") pt$defineCalculation(calculationName="CountTrains", summariseExpression=countFunction, caption="Count", visible=FALSE) filterOverrides <- PivotFilterOverrides$new(pt, removeAllFilters=TRUE) filterOverrides$add(variableName="TrainCategory", values="Express Passenger", action="replace") filterOverrides$add(variableName="TOC", values="CrossCountry", action="replace") pt$defineCalculation(calculationName="CrossCountryExpress", filters=filterOverrides, summariseExpression=countFunction, caption="CrossCountry Express Trains", visible=FALSE) pt$defineCalculation(calculationName="MultipleOfCCExpressTrains", type="calculation", basedOn=c("CountTrains", "CrossCountryExpress"), calculationExpression="values$CountTrains/values$CrossCountryExpress", format="%.2f", caption="Multiple of CC Express") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">0.13</td>\n <td class=\"Cell\">0.04</td>\n <td class=\"Cell\">0.17</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">1.00</td>\n <td class=\"Cell\">0.00</td>\n <td class=\"Cell\">1.00</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">0.63</td>\n <td class=\"Cell\">1.48</td>\n <td class=\"Cell\">2.11</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">0.38</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">0.38</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">2.14</td>\n <td class=\"Cell\">1.52</td>\n <td class=\"Cell\">3.66</td>\n </tr>\n</table>" expect_equal(round(sum(pt$cells$asMatrix(), na.rm=TRUE), digits=3), 14.644) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: filter overrides - subsets of data") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(bhmtrains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("TOC") filterDMU <- PivotFilter$new(pt, variableName="PowerType", values="DMU") filterOverrides <- PivotFilterOverrides$new(pt, filter=filterDMU, action="intersect") pt$defineCalculation(calculationName="CountDMU", filters=filterOverrides, summariseExpression=countFunction, caption="DMU", visible=FALSE) pt$defineCalculation(calculationName="CountTrains", summariseExpression=countFunction, caption="Count", visible=FALSE) pt$defineCalculation(calculationName="PercentageDMU", type="calculation", basedOn=c("CountTrains", "CountDMU"), calculationExpression="values$CountDMU/values$CountTrains*100", format="%.1f %%", caption="% DMU") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Total</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Arriva Trains Wales</th>\n <td class=\"Cell\">100.0 %</td>\n <td class=\"Cell\">100.0 %</td>\n <td class=\"Cell\">100.0 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">CrossCountry</th>\n <td class=\"Cell\">96.8 %</td>\n <td class=\"Cell\">100.0 %</td>\n <td class=\"Cell\">96.8 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">London Midland</th>\n <td class=\"Cell\">38.9 %</td>\n <td class=\"Cell\">16.5 %</td>\n <td class=\"Cell\">23.3 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Virgin Trains</th>\n <td class=\"Cell\">24.9 %</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">24.9 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">67.3 %</td>\n <td class=\"Cell\">18.7 %</td>\n <td class=\"Cell\">47.2 %</td>\n </tr>\n</table>" expect_equal(round(sum(pt$cells$asMatrix(), na.rm=TRUE), digits=3), 855.192) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: filter overrides - custom function 1") for(i in 1:nrow(scenarios)) { evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(dplyr) trains <- bhmtrains %>% mutate(GbttDateTime=if_else(is.na(GbttArrival), GbttDeparture, GbttArrival), GbttDate=as.Date(GbttDateTime)) januaryDates <- seq(as.Date("2017-01-01"), as.Date("2017-01-07"), by="days") getYesterdayDateFilter <- function(pt, filters, cell) { filter <- filters$getFilter("GbttDate") if(is.null(filter)||(filter$type=="ALL")||(length(filter$values)>1)) { newFilter <- PivotFilter$new(pt, variableName="GbttDate", type="NONE") filters$setFilter(newFilter, action="replace") } else { date <- filter$values date <- date - 1 filter$values <- date } } library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(trains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("GbttDate", fromData=FALSE, explicitListOfValues=as.list(januaryDates), visualTotals=TRUE) pt$defineCalculation(calculationName="CountTrains", summariseExpression=countFunction, caption="Current Day Count") filterOverrides <- PivotFilterOverrides$new(pt, overrideFunction=getYesterdayDateFilter) pt$defineCalculation(calculationName="CountPreviousDayTrains", filters=filterOverrides, summariseExpression=countFunction, caption="Previous Day Count") pt$defineCalculation(calculationName="Daily Change", type="calculation", basedOn=c("CountTrains", "CountPreviousDayTrains"), calculationExpression="values$CountTrains-values$CountPreviousDayTrains", caption="Daily Change") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"3\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"3\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"3\">Total</th>\n </tr>\n <tr>\n <th class=\"ColumnHeader\" colspan=\"1\">Current Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Previous Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Daily Change</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Current Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Previous Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Daily Change</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Current Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Previous Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Daily Change</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-01</th>\n <td class=\"Cell\">297</td>\n <td class=\"Cell\">486</td>\n <td class=\"Cell\">-189</td>\n <td class=\"Cell\">214</td>\n <td class=\"Cell\">309</td>\n <td class=\"Cell\">-95</td>\n <td class=\"Cell\">511</td>\n <td class=\"Cell\">795</td>\n <td class=\"Cell\">-284</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-02</th>\n <td class=\"Cell\">565</td>\n <td class=\"Cell\">297</td>\n <td class=\"Cell\">268</td>\n <td class=\"Cell\">318</td>\n <td class=\"Cell\">214</td>\n <td class=\"Cell\">104</td>\n <td class=\"Cell\">883</td>\n <td class=\"Cell\">511</td>\n <td class=\"Cell\">372</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-03</th>\n <td class=\"Cell\">605</td>\n <td class=\"Cell\">565</td>\n <td class=\"Cell\">40</td>\n <td class=\"Cell\">438</td>\n <td class=\"Cell\">318</td>\n <td class=\"Cell\">120</td>\n <td class=\"Cell\">1043</td>\n <td class=\"Cell\">883</td>\n <td class=\"Cell\">160</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-04</th>\n <td class=\"Cell\">607</td>\n <td class=\"Cell\">605</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">437</td>\n <td class=\"Cell\">438</td>\n <td class=\"Cell\">-1</td>\n <td class=\"Cell\">1044</td>\n <td class=\"Cell\">1043</td>\n <td class=\"Cell\">1</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-05</th>\n <td class=\"Cell\">609</td>\n <td class=\"Cell\">607</td>\n <td class=\"Cell\">2</td>\n <td class=\"Cell\">438</td>\n <td class=\"Cell\">437</td>\n <td class=\"Cell\">1</td>\n <td class=\"Cell\">1047</td>\n <td class=\"Cell\">1044</td>\n <td class=\"Cell\">3</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-06</th>\n <td class=\"Cell\">607</td>\n <td class=\"Cell\">609</td>\n <td class=\"Cell\">-2</td>\n <td class=\"Cell\">436</td>\n <td class=\"Cell\">438</td>\n <td class=\"Cell\">-2</td>\n <td class=\"Cell\">1043</td>\n <td class=\"Cell\">1047</td>\n <td class=\"Cell\">-4</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-07</th>\n <td class=\"Cell\">577</td>\n <td class=\"Cell\">607</td>\n <td class=\"Cell\">-30</td>\n <td class=\"Cell\">433</td>\n <td class=\"Cell\">436</td>\n <td class=\"Cell\">-3</td>\n <td class=\"Cell\">1010</td>\n <td class=\"Cell\">1043</td>\n <td class=\"Cell\">-33</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">3867</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">2714</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">6581</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 39486) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: filter overrides - custom function 2") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(dplyr) trains <- bhmtrains %>% mutate(GbttDateTime=if_else(is.na(GbttArrival), GbttDeparture, GbttArrival), GbttDate=as.Date(GbttDateTime)) januaryDates <- seq(as.Date("2017-01-01"), as.Date("2017-01-07"), by="days") getThreeDayFilter <- function(pt, filters, cell) { filter <- filters$getFilter("GbttDate") if(is.null(filter)||(filter$type=="ALL")||(length(filter$values)>1)) { newFilter <- PivotFilter$new(pt, variableName="GbttDate", type="NONE") filters$setFilter(newFilter, action="replace") } else { date <- filter$values newDates <- seq(date-1, date+1, by="days") filter$values <- newDates } } library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(trains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("GbttDate", fromData=FALSE, explicitListOfValues=as.list(januaryDates), visualTotals=TRUE) pt$defineCalculation(calculationName="CountTrains", summariseExpression=countFunction, caption="Current Day Count") filterOverrides <- PivotFilterOverrides$new(pt, overrideFunction=getThreeDayFilter) pt$defineCalculation(calculationName="ThreeDayCount", filters=filterOverrides, summariseExpression=countFunction, caption="Three Day Total") pt$defineCalculation(calculationName="ThreeDayAverage", type="calculation", basedOn="ThreeDayCount", calculationExpression="values$ThreeDayCount/3", format="%.1f", caption="Three Day Rolling Average") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"3\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"3\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"3\">Total</th>\n </tr>\n <tr>\n <th class=\"ColumnHeader\" colspan=\"1\">Current Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Three Day Total</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Three Day Rolling Average</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Current Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Three Day Total</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Three Day Rolling Average</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Current Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Three Day Total</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Three Day Rolling Average</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-01</th>\n <td class=\"Cell\">297</td>\n <td class=\"Cell\">1348</td>\n <td class=\"Cell\">449.3</td>\n <td class=\"Cell\">214</td>\n <td class=\"Cell\">841</td>\n <td class=\"Cell\">280.3</td>\n <td class=\"Cell\">511</td>\n <td class=\"Cell\">2189</td>\n <td class=\"Cell\">729.7</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-02</th>\n <td class=\"Cell\">565</td>\n <td class=\"Cell\">1467</td>\n <td class=\"Cell\">489.0</td>\n <td class=\"Cell\">318</td>\n <td class=\"Cell\">970</td>\n <td class=\"Cell\">323.3</td>\n <td class=\"Cell\">883</td>\n <td class=\"Cell\">2437</td>\n <td class=\"Cell\">812.3</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-03</th>\n <td class=\"Cell\">605</td>\n <td class=\"Cell\">1777</td>\n <td class=\"Cell\">592.3</td>\n <td class=\"Cell\">438</td>\n <td class=\"Cell\">1193</td>\n <td class=\"Cell\">397.7</td>\n <td class=\"Cell\">1043</td>\n <td class=\"Cell\">2970</td>\n <td class=\"Cell\">990.0</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-04</th>\n <td class=\"Cell\">607</td>\n <td class=\"Cell\">1821</td>\n <td class=\"Cell\">607.0</td>\n <td class=\"Cell\">437</td>\n <td class=\"Cell\">1313</td>\n <td class=\"Cell\">437.7</td>\n <td class=\"Cell\">1044</td>\n <td class=\"Cell\">3134</td>\n <td class=\"Cell\">1044.7</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-05</th>\n <td class=\"Cell\">609</td>\n <td class=\"Cell\">1823</td>\n <td class=\"Cell\">607.7</td>\n <td class=\"Cell\">438</td>\n <td class=\"Cell\">1311</td>\n <td class=\"Cell\">437.0</td>\n <td class=\"Cell\">1047</td>\n <td class=\"Cell\">3134</td>\n <td class=\"Cell\">1044.7</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-06</th>\n <td class=\"Cell\">607</td>\n <td class=\"Cell\">1793</td>\n <td class=\"Cell\">597.7</td>\n <td class=\"Cell\">436</td>\n <td class=\"Cell\">1307</td>\n <td class=\"Cell\">435.7</td>\n <td class=\"Cell\">1043</td>\n <td class=\"Cell\">3100</td>\n <td class=\"Cell\">1033.3</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-07</th>\n <td class=\"Cell\">577</td>\n <td class=\"Cell\">1503</td>\n <td class=\"Cell\">501.0</td>\n <td class=\"Cell\">433</td>\n <td class=\"Cell\">1083</td>\n <td class=\"Cell\">361.0</td>\n <td class=\"Cell\">1010</td>\n <td class=\"Cell\">2586</td>\n <td class=\"Cell\">862.0</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">3867</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">2714</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\">6581</td>\n <td class=\"Cell\"></td>\n <td class=\"Cell\"></td>\n </tr>\n</table>" expect_equal(round(sum(pt$cells$asMatrix(), na.rm=TRUE), digits=1), 78457.3) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: filter overrides - custom function 3") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(dplyr) trains <- bhmtrains %>% mutate(GbttDateTime=if_else(is.na(GbttArrival), GbttDeparture, GbttArrival), GbttDate=as.Date(GbttDateTime)) %>% filter((as.Date("2017-01-01") <= GbttDate)&(GbttDate <= as.Date("2017-01-07"))) januaryDates <- seq(as.Date("2017-01-01"), as.Date("2017-01-07"), by="days") getCumulativeFilter <- function(pt, filters, cell) { filter <- filters$getFilter("GbttDate") if(is.null(filter)||(filter$type=="ALL")||(length(filter$values)>1)) { } else { date <- filter$values newDates <- seq(as.Date("2017-01-01"), date, by="days") filter$values <- newDates } } library(pivottabler) pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(totalStyleIsCellStyle=TRUE, explicitHeaderSpansOfOne=TRUE)) pt$addData(trains) pt$addColumnDataGroups("TrainCategory") pt$addRowDataGroups("GbttDate", fromData=FALSE, explicitListOfValues=as.list(januaryDates)) pt$defineCalculation(calculationName="CountTrains", summariseExpression=countFunction, caption="Current Day Count") filterOverrides <- PivotFilterOverrides$new(pt, overrideFunction=getCumulativeFilter) pt$defineCalculation(calculationName="CumulativeCount", filters=filterOverrides, summariseExpression=countFunction, caption="Cumulative Count") pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\" colspan=\"1\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"2\">Express Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"2\">Ordinary Passenger</th>\n <th class=\"ColumnHeader\" colspan=\"2\">Total</th>\n </tr>\n <tr>\n <th class=\"ColumnHeader\" colspan=\"1\">Current Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Cumulative Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Current Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Cumulative Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Current Day Count</th>\n <th class=\"ColumnHeader\" colspan=\"1\">Cumulative Count</th>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-01</th>\n <td class=\"Cell\">297</td>\n <td class=\"Cell\">297</td>\n <td class=\"Cell\">214</td>\n <td class=\"Cell\">214</td>\n <td class=\"Cell\">511</td>\n <td class=\"Cell\">511</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-02</th>\n <td class=\"Cell\">565</td>\n <td class=\"Cell\">862</td>\n <td class=\"Cell\">318</td>\n <td class=\"Cell\">532</td>\n <td class=\"Cell\">883</td>\n <td class=\"Cell\">1394</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-03</th>\n <td class=\"Cell\">605</td>\n <td class=\"Cell\">1467</td>\n <td class=\"Cell\">438</td>\n <td class=\"Cell\">970</td>\n <td class=\"Cell\">1043</td>\n <td class=\"Cell\">2437</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-04</th>\n <td class=\"Cell\">607</td>\n <td class=\"Cell\">2074</td>\n <td class=\"Cell\">437</td>\n <td class=\"Cell\">1407</td>\n <td class=\"Cell\">1044</td>\n <td class=\"Cell\">3481</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-05</th>\n <td class=\"Cell\">609</td>\n <td class=\"Cell\">2683</td>\n <td class=\"Cell\">438</td>\n <td class=\"Cell\">1845</td>\n <td class=\"Cell\">1047</td>\n <td class=\"Cell\">4528</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-06</th>\n <td class=\"Cell\">607</td>\n <td class=\"Cell\">3290</td>\n <td class=\"Cell\">436</td>\n <td class=\"Cell\">2281</td>\n <td class=\"Cell\">1043</td>\n <td class=\"Cell\">5571</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">2017-01-07</th>\n <td class=\"Cell\">577</td>\n <td class=\"Cell\">3867</td>\n <td class=\"Cell\">433</td>\n <td class=\"Cell\">2714</td>\n <td class=\"Cell\">1010</td>\n <td class=\"Cell\">6581</td>\n </tr>\n <tr>\n <th class=\"RowHeader\" rowspan=\"1\">Total</th>\n <td class=\"Cell\">3867</td>\n <td class=\"Cell\">3867</td>\n <td class=\"Cell\">2714</td>\n <td class=\"Cell\">2714</td>\n <td class=\"Cell\">6581</td>\n <td class=\"Cell\">6581</td>\n </tr>\n</table>" expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 88492) expect_identical(as.character(pt$getHtml()), html) }) } scenarios <- testScenarios("calculation tests: custom function with calcFuncArgs") for(i in 1:nrow(scenarios)) { if(!isDevelopmentVersion) break evaluationMode <- scenarios$evaluationMode[i] processingLibrary <- scenarios$processingLibrary[i] description <- scenarios$description[i] countFunction <- scenarios$countFunction[i] test_that(description, { library(pivottabler) library(dplyr) library(lubridate) trains <- mutate(bhmtrains, GbttDateTime=if_else(is.na(GbttArrival), GbttDeparture, GbttArrival), GbttDate=make_date(year=year(GbttDateTime), month=month(GbttDateTime), day=day(GbttDateTime)), GbttMonth=make_date(year=year(GbttDateTime), month=month(GbttDateTime), day=1), ArrivalDelta=difftime(ActualArrival, GbttArrival, units="mins"), ArrivalDelay=ifelse(ArrivalDelta<0, 0, ArrivalDelta), DelayedByMoreThan5Minutes=ifelse(ArrivalDelay>5,1,0)) getWorstSingleDayPerformance <- function(pivotCalculator, netFilters, calcFuncArgs, format, fmtFuncArgs, baseValues, cell) { trains <- pivotCalculator$getDataFrame("trains") filteredTrains <- pivotCalculator$getFilteredDataFrame(trains, netFilters) dateSummary <- filteredTrains %>% group_by(GbttDate) %>% summarise(DelayedPercent = sum(DelayedByMoreThan5Minutes, na.rm=TRUE) / n() * 100) %>% arrange(desc(DelayedPercent)) tv <- dateSummary$DelayedPercent[1] date <- dateSummary$GbttDate[1] if(calcFuncArgs$output=="day") { value <- list() value$rawValue <- date value$formattedValue <- format(date, format="%a %d") } else if(calcFuncArgs$output=="performance") { value <- list() value$rawValue <- tv value$formattedValue <- pivotCalculator$formatValue(tv, format=format) } return(value) } pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode) pt$addData(trains, "trains") pt$addColumnDataGroups("GbttMonth", dataFormat=list(format="%B %Y")) pt$addRowDataGroups("TOC", totalCaption="All TOCs") pt$defineCalculation(calculationName="WorstSingleDay", caption="Day", format="%.1f %%", type="function", calculationFunction=getWorstSingleDayPerformance, calcFuncArgs=list(output="day")) pt$defineCalculation(calculationName="WorstSingleDayPerf", caption="Perf", format="%.1f %%", type="function", calculationFunction=getWorstSingleDayPerformance, calcFuncArgs=list(output="performance")) pt$evaluatePivot() html <- "<table class=\"Table\">\n <tr>\n <th class=\"RowHeader\" rowspan=\"2\">&nbsp;</th>\n <th class=\"ColumnHeader\" colspan=\"2\">December 2016</th>\n <th class=\"ColumnHeader\" colspan=\"2\">January 2017</th>\n <th class=\"ColumnHeader\" colspan=\"2\">February 2017</th>\n <th class=\"ColumnHeader\" colspan=\"2\">Total</th>\n </tr>\n <tr>\n <th class=\"ColumnHeader\">Day</th>\n <th class=\"ColumnHeader\">Perf</th>\n <th class=\"ColumnHeader\">Day</th>\n <th class=\"ColumnHeader\">Perf</th>\n <th class=\"ColumnHeader\">Day</th>\n <th class=\"ColumnHeader\">Perf</th>\n <th class=\"ColumnHeader\">Day</th>\n <th class=\"ColumnHeader\">Perf</th>\n </tr>\n <tr>\n <th class=\"RowHeader\">Arriva Trains Wales</th>\n <td class=\"Cell\">Tue 27</td>\n <td class=\"Cell\">42.9 %</td>\n <td class=\"Cell\">Sun 29</td>\n <td class=\"Cell\">18.8 %</td>\n <td class=\"Cell\">Sun 12</td>\n <td class=\"Cell\">18.8 %</td>\n <td class=\"Total\">Tue 27</td>\n <td class=\"Total\">42.9 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">CrossCountry</th>\n <td class=\"Cell\">Thu 01</td>\n <td class=\"Cell\">35.4 %</td>\n <td class=\"Cell\">Fri 06</td>\n <td class=\"Cell\">19.4 %</td>\n <td class=\"Cell\">Thu 23</td>\n <td class=\"Cell\">27.9 %</td>\n <td class=\"Total\">Thu 01</td>\n <td class=\"Total\">35.4 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">London Midland</th>\n <td class=\"Cell\">Thu 01</td>\n <td class=\"Cell\">26.9 %</td>\n <td class=\"Cell\">Fri 06</td>\n <td class=\"Cell\">17.2 %</td>\n <td class=\"Cell\">Thu 23</td>\n <td class=\"Cell\">12.1 %</td>\n <td class=\"Total\">Thu 01</td>\n <td class=\"Total\">26.9 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">Virgin Trains</th>\n <td class=\"Cell\">Thu 01</td>\n <td class=\"Cell\">33.0 %</td>\n <td class=\"Cell\">Thu 12</td>\n <td class=\"Cell\">21.4 %</td>\n <td class=\"Cell\">Sat 11</td>\n <td class=\"Cell\">25.5 %</td>\n <td class=\"Total\">Thu 01</td>\n <td class=\"Total\">33.0 %</td>\n </tr>\n <tr>\n <th class=\"RowHeader\">All TOCs</th>\n <td class=\"Total\">Thu 01</td>\n <td class=\"Total\">29.5 %</td>\n <td class=\"Total\">Fri 06</td>\n <td class=\"Total\">16.3 %</td>\n <td class=\"Total\">Thu 23</td>\n <td class=\"Total\">17.1 %</td>\n <td class=\"Total\">Thu 01</td>\n <td class=\"Total\">29.5 %</td>\n </tr>\n</table>" expect_equal(round(sum(pt$cells$asMatrix(), na.rm=TRUE), 0), 530) expect_identical(as.character(pt$getHtml()), html) }) }
setMethodS3("extractAlleleSet", "SnpChipEffectSet", function(this, units=NULL, sortUnits=TRUE, transform=log2, ..., verbose=FALSE) { requireNamespace("oligoClasses") || throw("Package not loaded: oligoClasses") chipType <- getChipType(this, fullname=FALSE) cdf <- getCdf(this) if (is.null(units)) { units <- indexOf(cdf, pattern="^SNP_A-") } else { units <- Arguments$getIndices(units, max=nbrOfUnits(cdf)) } verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } unitNames <- getUnitNames(cdf, units=units) if (sortUnits) { verbose && enter(verbose, "Sort units by their names") srt <- sort(unitNames, method="quick", index.return=TRUE) unitNames <- srt$x units <- units[srt$ix] srt <- NULL; verbose && exit(verbose) } verbose && enter(verbose, "Inferring the number of groups to extract") verbose && cat(verbose, "Chip type: ", getChipType(this)) ugcMap <- getUnitGroupCellMap(this, units=units, verbose=verbose) maxGroup <- max(ugcMap$group, na.rm=TRUE) ugcMap <- NULL verbose && cat(verbose, "Max number of groups unit (unit,group,cell) map: ", maxGroup) if (maxGroup > 4) { maxGroup <- 4L } if (!is.element(maxGroup, c(2,4))) { throw("Unsupported value on 'maxGroup': ", maxGroup) } groups <- 1:maxGroup verbose && cat(verbose, "Groups to extract: ", seqToHumanReadable(groups)) verbose && exit(verbose) if (maxGroup == 4) { verbose && enter(verbose, "Inferring which unit groups to be swapped to (sense, antisense)") dirs <- getGroupDirections(cdf, units=units, verbose=less(verbose, 5)) names(dirs) <- NULL gc <- gc() verbose && print(verbose, gc) lens <- sapply(dirs, FUN=length) uLens <- unique(lens) if (any(!is.element(uLens, unique(c(2,maxGroup))))) { throw("Internal error: Unexpected number of unit groups: ", paste(uLens, collapse=", ")) } dirs <- lapply(dirs, FUN=.subset, 1L) dirs <- unlist(dirs, use.names=FALSE) idxs <- which(dirs == 2) dirs <- NULL gc <- gc() verbose && print(verbose, gc) verbose && exit(verbose) } verbose && enter(verbose, "Extracting data") theta <- extractTheta(this, groups=groups, units=units, verbose=verbose) units <- NULL gc <- gc() verbose && print(verbose, gc) verbose && exit(verbose) if (maxGroup == 4 && length(idxs) > 0) { verbose && enter(verbose, "Ordering unit groups to be (sense, antisense)") verbose && cat(verbose, "Swapping elements:") verbose && str(verbose, idxs) theta[idxs,,] <- theta[idxs,c(3,4,1,2),,drop=FALSE] idxs <- NULL; gc <- gc() verbose && print(verbose, gc) verbose && exit(verbose) } if (!is.null(transform)) { verbose && enter(verbose, "Transforming signals") theta <- transform(theta) verbose && str(verbose, theta) gc <- gc() verbose && print(verbose, gc) verbose && exit(verbose) } verbose && enter(verbose, "Allocate and populate AlleleSet") if (maxGroup == 2) { res <- new("AlleleSet", alleleA = theta[,1,,drop=TRUE], alleleB = theta[,2,,drop=TRUE] ) } else if (maxGroup == 4) { res <- new("AlleleSet", antisenseAlleleA = theta[,3,,drop=TRUE], senseAlleleA = theta[,1,,drop=TRUE], antisenseAlleleB = theta[,4,,drop=TRUE], senseAlleleB = theta[,2,,drop=TRUE] ) } theta <- NULL .featureNames(res) <- unitNames unitNames <- NULL pdPkgName <- .cleanPlatformName(chipType) .annotation(res) <- pdPkgName filenames <- sapply(this, getFilename) names(filenames) <- NULL filenames <- gsub(",chipEffects", "", filenames) .sampleNames(res) <- filenames verbose && exit(verbose) res })
test_that("Tests that computing confidence intervals is going well", { x <- iris[1:125,-1] y <- iris[1:125,1] x_test <- iris[126:150,-1] y_test <- iris[126:150,1] rf <- forestry(x = x, y = y, OOBhonest = TRUE, seed = 3242) context("test the bootstrapped prediction intervals") preds <- getCI(rf, newdata = x_test, level = .99, method = "OOB-bootstrap") coverage <- length(which(y_test < preds$CI.upper & y_test > preds$CI.lower)) / length(y_test) skip_if_not_mac() expect_gt(coverage, 0) })
phf_pbp <- function(game_id = 368719) { base_url <- "https://web.api.digitalshift.ca/partials/stats/game/play-by-play?game_id=" full_url <- paste0(base_url, game_id) auth_ticket <- getOption( "fastRhockey.phf_ticket", default = 'ticket="4dM1QOOKk-PQTSZxW_zfXnOgbh80dOGK6eUb_MaSl7nUN0_k4LxLMvZyeaYGXQuLyWBOQhY8Q65k6_uwMu6oojuO"' ) res <- httr::RETRY("GET", full_url, httr::add_headers(`Authorization`= auth_ticket)) check_status(res) plays_data <- data.frame() tryCatch( expr={ data <- res %>% httr::content(as = "text", encoding="utf-8") %>% jsonlite::fromJSON() %>% purrr::pluck("content") %>% rvest::read_html() %>% rvest::html_table() plays_data <- data[ !sapply( lapply(data, function(x){ if("Time" %in% colnames(x) && nrow(x)>0){ return(x) } if("Play" %in% colnames(x) && nrow(x)>0){ return(x) } }),is.null)] if(length(plays_data) %in% c(5,6)){ plays_data <- plays_data[1:5] } else if(length(plays_data)>6) { plays_data } plays_df <- purrr::map_dfr(1:length(plays_data), function(x){ plays_data[[x]] %>% helper_phf_pbp_normalize_columns() %>% dplyr::mutate( period_id = x, game_id = game_id)}) game_details <- phf_game_details(game_id) plays_df <- plays_df %>% dplyr::left_join(game_details, by = "game_id") plays_df <- helper_phf_pbp_data(plays_df) }, error = function(e) { message(glue::glue("{Sys.time()}: Invalid game_id or no game data available!")) }, warning = function(w) { }, finally = { } ) return(plays_df) }
mb_get_markets <- function(session_data,event_id,market_states = c("open","suspended"),market_types=c("multirunner","binary"),grading_types=NULL,include_runners=FALSE,include_prices=FALSE) { valid_market_states<- c("suspended","open") valid_market_types <- c("multirunner","binary") valid_grading_types<- c('asian-handicap','high-score-wins','low-score-wins','point-spread','point-total','single-winner-wins','one_x_two','handicap', 'total', 'both_to_score', 'correct_score', 'half_time_full_time') content <- list(status_code=0) if(is.null(session_data)|!is.list(session_data)){ print(paste("You have not provided data about your session in the session_data parameter. Please execute mb_login('my_user_name','verysafepassword') and save the resulting object in a variable e.g. my_session <- mb_login(username,pwd); and pass session_data=my_session as a parameter in this function."));return(content) } if(event_id%%1>0){ print(paste("The event_id must be an integer. Please amend and try again."));return(content) } if(length(event_id)>1){ print(paste("The event_id must be a single integer. Please amend and try again."));return(content) } if(sum(!is.element(market_states,valid_market_states))>0){ print(paste("All market_states values must be one of",paste(valid_market_states,collapse=","),". Please amend and try again."));return(content) } if(sum(!is.element(market_types,valid_market_types))>0){ print(paste("All market_types values must be one of",paste(valid_market_types,collapse=","),". Please amend and try again."));return(content) } if(sum(!is.null(grading_types))>0) { if(sum(!is.element(grading_types,valid_grading_types))>0){ print(paste("All grading_types values must be one of",paste(valid_grading_types,collapse=","),". Please amend and try again."));return(content) } } param_list <- list('exchange-type'='back-lay','odds-type'=session_data$odds_type,currency=session_data$currency,'market-states'=paste(market_states,collapse=","),'per-page'='500','types'=paste(grading_types,collapse=","),'market-types'=paste(market_types,collapse=",")) if(include_runners==TRUE){ param_list <- c(param_list,'include-runners'='true') } if(include_prices==TRUE){ param_list <- c(param_list,'include-prices'='true') } get_markets_resp <- httr::GET(paste("https://www.matchbook.com/edge/rest/events/",event_id,"/markets",sep=""),query=param_list,httr::set_cookies('session-token'=session_data$session_token),httr::add_headers('User-Agent'='rlibnf')) status_code <- get_markets_resp$status_code if(status_code==200) { content <- jsonlite::fromJSON(content(get_markets_resp, "text", "application/json"))$markets } else { print(paste("Warning/Error in communicating with https://www.matchbook.com/edge/rest/events/",event_id,"/markets",sep="")) content$status_code <- status_code } return(content) }
getParseFun <- function(parseData) { UPROWS <- 4L w <- which(parseData$token == "FUNCTION") w <- w[getParseGGParent(parseData, parseData$id[w]) == 0L] parseData$text[w - UPROWS] } getParseFormals <- function(parseData) { w <- which(parseData$token == "SYMBOL_FORMALS") w <- w[getParseGGParent(parseData, parseData$id[w]) == 0L] x <- split(parseData$text[w], parseData$parent[w]) names(x) <- NULL x }
findOOBErrors <- function(forest, X.train, Y.train = NULL, n.cores = 1) { categorical <- grepl("class", c(forest$type, forest$family, forest$treetype), TRUE) if ("quantregForest" %in% class(forest)) { class(forest) <- "randomForest" train.terminal.nodes <- attr(predict(forest, X.train, nodes = TRUE), "nodes") bag.count <- forest$inbag if (categorical) { oob.errors <- forest$y != forest$predicted } else { oob.errors <- forest$y - forest$predicted } } else if ("randomForest" %in% class(forest)) { train.terminal.nodes <- attr(predict(forest, X.train, nodes = TRUE), "nodes") bag.count <- forest$inbag if (categorical) { oob.errors <- forest$y != forest$predicted } else { oob.errors <- forest$y - forest$predicted } } else if ("ranger" %in% class(forest)) { train.terminal.nodes <- predict(forest, X.train, num.threads = n.cores, type = "terminalNodes")$predictions bag.count <- matrix(unlist(forest$inbag.counts, use.names = FALSE), ncol = forest$num.trees, byrow = FALSE) if (categorical) { oob.errors <- Y.train != forest$predictions } else { oob.errors <- Y.train - forest$predictions } } else if ("rfsrc" %in% class(forest)) { train.terminal.nodes <- forest$membership bag.count <- forest$inbag if (categorical) { oob.errors <- forest$yvar != forest$class.oob } else { oob.errors <- forest$yvar - forest$predicted.oob } } train.terminal.nodes[bag.count != 0] <- NA train_nodes <- data.table::as.data.table(train.terminal.nodes) train_nodes[, `:=`(oob_error = oob.errors)] train_nodes <- data.table::melt( train_nodes, id.vars = c("oob_error"), measure.vars = 1:ncol(train.terminal.nodes), variable.name = "tree", value.name = "terminal_node", variable.factor = FALSE, na.rm = TRUE) train_nodes <- train_nodes[, .(node_errs = list(oob_error)), keyby = c("tree", "terminal_node")] return(train_nodes) }
PRMR <- function (Data.Name, JK = NULL, CL = NULL, PeriodEnd = NULL, Period = NULL) { v013 <- rweight <- mm1 <- age5 <- birth <- exposure <- sex <- agegrp <- mm_death <- NULL Data.Name <- Data.Name[!Data.Name$v005 == 0, ] Data.Name$ID <- seq.int(nrow(Data.Name)) if (is.null(CL)) { Z <- stats::qnorm(.025,lower.tail=FALSE) } else { Z <- stats::qnorm((100-CL)/200,lower.tail=FALSE) } if (is.null(Period)){Periodmsg = 84} else {Periodmsg = Period} if (is.null(PeriodEnd)){ PeriodEndy_ <- as.integer((mean(Data.Name$v008) - 1)/12)+1900 PeriodEndm_ <- round(mean(Data.Name$v008) - ((PeriodEndy_ - 1900) * 12),0) PeriodEndm_m <- round(min(Data.Name$v008) - ((PeriodEndy_ - 1900) * 12),0) PeriodEndm_x <- round(max(Data.Name$v008) - ((PeriodEndy_ - 1900) * 12),0) } else { dates <- paste(PeriodEnd, "01", sep = "-") PeriodEndm_ <- as.numeric(format(as.Date(dates), "%m")) PeriodEndy_ <- as.numeric(format(as.Date(dates), "%Y")) if (PeriodEndm_ >= round(mean(Data.Name$v008) - (((as.integer((mean(Data.Name$v008) - 1)/12)+1900) - 1900) * 12),0) & PeriodEndy_ >= as.integer((mean(Data.Name$v008) - 1)/12)+1900) message(crayon::bold("Note:", "\n", "You specified a reference period that ends after the survey fieldwork dates....."), "\n", "1. Make sure the dates in the survey are coded according to the Gregorian calendar.", "\n", "2. If the dates are coded according to the Gregorian calendar, use a proper PeriodEnd that came before the time of the survey.", "\n", "3. If the dates are not coded according to the Gregorian calendar, use a PeriodEnd according to the used calendar.") } if (is.null(PeriodEnd)){ cat("\n", crayon::white$bgBlue$bold("The current function calculated PRMR based on a reference period of"), crayon::red$bold$underline(Periodmsg), crayon::white$bold$bgBlue("months"), "\n", crayon::white$bold$bgBlue("The reference period ended at the time of the interview, in"), crayon::red$bold$underline(PeriodEndy_ + round(PeriodEndm_/12,digits=2)), "OR", crayon::red$bold$underline(month.abb[PeriodEndm_m]), "-", crayon::red$bold$underline(month.abb[PeriodEndm_x]), crayon::red$bold$underline(PeriodEndy_), "\n", crayon::white$bold$bgBlue("The average reference period is"), crayon::red$bold$underline(round((PeriodEndy_ + PeriodEndm_/12)-(Periodmsg/24), digits =2)), "\n") } else { cat("\n", crayon::white$bgBlue$bold("The current function calculated PRMR based on a reference period of"), crayon::red$bold$underline(Periodmsg), crayon::white$bold$bgBlue("months"), "\n", crayon::white$bold$bgBlue("The reference period ended in"), crayon::red$bold$underline(PeriodEndy_ + round(PeriodEndm_/12,digits=2)), "OR", crayon::red$bold$underline(month.abb[PeriodEndm_]), crayon::red$bold$underline(PeriodEndy_), "\n", crayon::white$bold$bgBlue("The average reference period is"), crayon::red$bold$underline(round((PeriodEndy_ + PeriodEndm_/12)-(Periodmsg/24), digits =2)), "\n") } Data.Name$id <- c(as.factor(Data.Name$v021)) Data.Name$rweight = Data.Name$v005 / 1000000 DeathEx <- DataPrepareM(Data.Name, PeriodEnd, Period) BirthEx <- DataPrepareM_GFR(Data.Name, PeriodEnd, Period) if (is.null(JK)){PSU <- 0} else {PSU <- max(as.numeric(DeathEx$id))} DeathEx$mm9[is.na(DeathEx$mm9)] <- 0 DeathEx$prm_death = ifelse(DeathEx$mm1 ==2 & DeathEx$mm9 >= 2 & DeathEx$mm9 <= 6, DeathEx$death, 0) DeathEx$mm_death = DeathEx$prm_death options(dplyr.summarise.inform = FALSE) AGEDIST <- (dplyr::group_by(Data.Name, v013) %>% summarise(x = sum(rweight)))$x/sum(Data.Name$rweight) options(survey.lonely.psu = "adjust") dstrat <- survey::svydesign(id = ~ v021, strata = ~ v022, weights = ~ rweight, data = DeathEx) dsub <- subset(dstrat, mm1==2) asprmr <- (survey::svyby(~ mm_death, by = ~ agegrp, denominator = ~ exposure, design = dsub, survey::svyratio))[, 2] ASFR <- (dplyr::group_by(BirthEx, age5) %>% summarise(x = sum(birth*rweight)))$x/ (dplyr::group_by(BirthEx, age5) %>% summarise(x = sum(exposure*rweight)))$x prmr <- (sum(asprmr[1:7] * AGEDIST) * 100000) / ceiling(sum(ASFR[1:7] * AGEDIST)) N = (dplyr::group_by(DeathEx, sex) %>% summarise(x = sum(exposure)))$x[1] WN = (survey::svyby(~ exposure, by = ~ sex, design = dsub, survey::svytotal))$exposure[1] PRMR_DEFT = sqrt(survey::svyby(~ mm_death, by = ~ sex, denominator = ~ exposure, design = dsub, deff = "replace", survey::svyratio)$DEff)[1] JKres <- matrix(0, nrow = PSU, ncol = 1) dimnames(JKres) <- list(NULL, c("PRMRj_f")) if (is.null(JK)){ RESULTS <- cbind.data.frame(round(WN, 0),round(prmr, 0), round(N, 0), row.names = NULL) names(RESULTS) <- c("Exposure_years","PRMR", "N") list(RESULTS) } else { for (i in unique(as.numeric(DeathEx$id))) { Data.NameJ <- Data.Name[which(!Data.Name$id == i), ] DeathExJ <- DeathEx[which(!DeathEx$id == i), ] BirthExJ <- BirthEx[which(!BirthEx$id == i), ] AGEDISTj <- (dplyr::group_by(Data.NameJ, v013) %>% summarise(x = sum(rweight)))$x/sum(Data.NameJ$rweight) ASPRMRj <- (dplyr::group_by(DeathExJ, sex, agegrp) %>% summarise(x = sum(mm_death*rweight)))$x/ (dplyr::group_by(DeathExJ, sex, agegrp) %>% summarise(x = sum(exposure*rweight)))$x ASFRj <- (dplyr::group_by(BirthExJ, age5) %>% summarise(x = sum(birth*rweight)))$x/ (dplyr::group_by(BirthExJ, age5) %>% summarise(x = sum(exposure*rweight)))$x JKres[i,1] <- (sum(ASPRMRj[1:7] * AGEDISTj) * 100000) / (sum(ASFRj[1:7] * AGEDISTj)) } PRMRjf = JKres[1:PSU, 1] JKSEf = ((PSU * prmr[1] - (PSU-1) * PRMRjf)-prmr[1])^2 SE = sqrt(sum(JKSEf) / (PSU * (PSU-1))) RSE = SE / prmr LCI = prmr - (Z * SE) LCI[LCI <= 0] = 0 UCI = prmr + (Z * SE) PSUs = PSU RESULTS <- cbind.data.frame(round(WN, 0), round(prmr,0), round(SE,3), round(N, 0), round(PRMR_DEFT,3), round(RSE,3), round(LCI,3), round(UCI,3), PSUs, row.names = NULL) names(RESULTS) <- c("Exposure_years","PRMR", "SE", "N", "DEFT", "RSE", "LCI", "UCI", "iterations") list(RESULTS) } }
genlabels <- function(X) { if(is.vector(X)) { if(length(X)==3) names(X) <- c("AA","AB","BB") if(length(X)==5) names(X) <- c("A","B","AA","AB","BB") } if(is.matrix(X) | is.data.frame(X)) { if(ncol(X)==3) colnames(X) <- c("AA","AB","BB") if(ncol(X)==5) colnames(X) <- c("A","B","AA","AB","BB") } return(X) }
prcbr <- function (formula, b0, data, logL = TRUE, omethod = "BFGS", lo = -Inf, up = Inf, ...) { mf <- match.call(expand.dots = FALSE) m <- match(c("formula", "data"), names(mf), 0) mf <- mf[c(1, m)] F <- Formula::Formula(formula) mf[[1]] <- as.name("model.frame") mf$formula <- F mf <- eval(mf, parent.frame()) y <- model.response(mf) X <- model.matrix(F, data = mf, rhs = 1) Z <- model.matrix(F, data = mf, rhs = 2)[, -1, drop = FALSE] p <- NCOL(Z) b0 <- matrix(b0, p) M <- ncol(b0) cntl <- KW.control(...) eps <- .Machine$double.eps^(2/3) plogL <- function(b, X, y, Z, cntl) { -logLik(rcbr.fit(X, y, offset = Z %*% b, mode = "KW", cntl)) } pglogL <- function(b, X, y, Z, cntl) { f <- rcbr.fit(X, y, offset = Z %*% b, mode = "KW", cntl) if (class(f)[[1]] == "KW1") { Fhat <- stepfun(f$x, cumsum(c(0, f$y))) FZb <- Fhat(X[, 2] + Z %*% b) } else if (class(f)[[1]] == "KW2") { Fhatu <- stepfun(f$uv[, 1], cumsum(c(0, f$W))) Fhatv <- stepfun(f$uv[, 2], cumsum(c(0, f$W))) Fhat <- function(u, v) pmin(Fhatu(u), Fhatv(v)) FZb <- Fhat(X[, 3], X[, 2] + Z %*% b) } FZb <- FZb * ((eps < FZb) && (FZb < (1 - eps))) c(crossprod(crossprod(Z, y - FZb)/length(y))) } if (logL) { if (M == 1) { g <- optim(b0, plogL, method = omethod, X = X, y = y, Z = Z, lower = lo, upper = up, cntl = cntl) bhat <- g$par } else { g <- apply(b0, 2, FUN = function(b) plogL(b, X, y, Z, cntl = cntl)) bhat <- b0[, which(g == max(g))] } f <- rcbr.fit(X, y, offset = Z %*% bhat, mode = "KW", cntl) } else { if (M == 1) { g <- optim(b0, pglogL, method = omethod, X = X, y = y, Z = Z, lower = lo, upper = up, cntl = cntl) bhat <- g$par } else { g <- apply(b0, 2, FUN = function(b) pglogL(b, X, y, Z, cntl = cntl)) bhat <- b0[, which(g == min(g))] } f <- rcbr.fit(X, y, offset = Z %*% bhat, mode = "KW", cntl) } list(bopt = g, fopt = f) }
convertBMRToRankMatrix = function(bmr, measure = NULL, ties.method = "average", aggregation = "default") { assertClass(bmr, "BenchmarkResult") measure = checkBMRMeasure(measure, bmr) assertChoice(aggregation, c("mean", "default")) if (aggregation == "mean") { df = setDT(as.data.frame(bmr)) df = df[, list(x = mean(get(measure$id))), by = c("task.id", "learner.id")] } else if (aggregation == "default") { aggr.meas = measureAggrName(measure) df = setDT(getBMRAggrPerformances(bmr, as.df = TRUE)) df = df[, c("task.id", "learner.id", aggr.meas), with = FALSE] setnames(df, aggr.meas, "x") } if (!measure$minimize) { df$x = -df$x } df[, "alg.rank" := rank(.SD$x, ties.method = ties.method), by = "task.id"] df = melt(df, c("task.id", "learner.id"), "alg.rank") df = dcast(df, learner.id ~ task.id) task.id.names = setdiff(colnames(df), "learner.id") mat = as.matrix(setDF(df)[, task.id.names]) rownames(mat) = df$learner.id colnames(mat) = task.id.names return(mat) }
lavMultipleImputation <- function(model = NULL, dataList = NULL, ndat = length(dataList), cmd = "sem", ..., store.slots = c("partable"), FUN = NULL, show.progress = FALSE, parallel = c("no", "multicore", "snow"), ncpus = max(1L, parallel::detectCores() - 1L), cl = NULL) { dotdotdot <- list() fit <- do.call("lavaanList", args = c(list(model = model, dataList = dataList, ndat = ndat, cmd = cmd, store.slots = store.slots, FUN = FUN, show.progress = show.progress, parallel = parallel, ncpus = ncpus, cl = cl), dotdotdot)) fit@meta$lavMultipleImputation <- TRUE fit }
print.spTD<-function(x, ...) { cat("-----------------------------------------------------"); cat('\n'); cat("Model: "); cat(x$model); cat('\n'); cat("Call: "); print(x$call); cat("Iterations: "); cat(x$iterations); cat("\n") cat("nBurn: "); cat(x$nBurn); cat("\n") cat("Acceptance rate for phi (%): "); cat(x$accept); cat("\n") cat("-----------------------------------------------------"); cat('\n'); print(x$PMCC); cat("-----------------------------------------------------"); cat('\n'); cat("Computation time: "); cat(x$computation.time); cat("\n") } fitted.spTD<-function(object, ...){ x<-data.frame(object$fitted) x } confint.spTD<-function(object, parm, level=0.95, ...){ x<-as.mcmc(object) up<-level+(1-level)/2 low<-(1-level)/2 FUN <- function(x){quantile(x,probs=c(low,up))} out<-apply(x,2,FUN=FUN) out<-t(out) if(missing(parm)){ out } else{ if(length(parm)>1){ out<-as.matrix(out[dimnames(out)[[1]] %in% parm,]) out } else{ out<-t(as.matrix(out[dimnames(out)[[1]] %in% parm,])) dimnames(out)[[1]]<-parm out } } } coef.spTD<-function(object, digits=4, ...){ round(t(object$parameter)[1,],digits=digits) } residuals.spTD<-function(object, ...){ if(object$scale.transform=="NONE"){ tmp<-object$Y-object$fitted[,1] tmp } else if(object$scale.transform=="SQRT"){ tmp<-sqrt(object$Y)-object$fitted[,1] tmp } else if(object$scale.transform=="LOG"){ tmp<-log(object$Y)-object$fitted[,1] tmp } else{ } } as.mcmc.spTD<-function(x, ...){ if (x$combined.fit.pred == TRUE) { stop("\n } model <- x$model if (is.null(model) == TRUE) { stop("\n } else if (model == "GP" | model == "truncatedGP") { r <- x$r p <- x$p if(x$cov.fnc=="matern"){ if((is.null(x$sp.covariate.names)) & (is.null(x$tp.covariate.names))){ para <- rbind((x$betap), t(x$sig2ep), t(x$sig2etap), t(x$phip), t(x$nup)) dimnames(para)[[1]] <- c(dimnames(x$X)[[2]], "sig2eps", "sig2eta", "phi", "nu") } else if((!is.null(x$sp.covariate.names)) & (is.null(x$tp.covariate.names))){ para <- rbind((x$betap), t(x$sig2ep), t(x$sig2etap), t(x$sig2betap), t(x$phip), t(x$nup)) dimnames(para)[[1]] <- c(dimnames(x$X)[[2]], "sig2eps", "sig2eta", "sig2beta", "phi", "nu") } else if((is.null(x$sp.covariate.names)) & (!is.null(x$tp.covariate.names))){ para <- rbind((x$betap), t(x$sig2ep), t(x$sig2etap), t(x$sig2deltap), t(x$sig2op), t(x$phip), t(x$nup)) dimnames(para)[[1]] <- c(dimnames(x$X)[[2]], "sig2eps", "sig2eta", "sig2deltap", "sig2op", "phi", "nu") } else if((!is.null(x$sp.covariate.names)) & (!is.null(x$tp.covariate.names))){ para <- rbind((x$betap), t(x$sig2ep), t(x$sig2etap), t(x$sig2betap), t(x$sig2deltap), t(x$sig2op), t(x$phip), t(x$nup)) dimnames(para)[[1]] <- c(dimnames(x$X)[[2]], "sig2eps", "sig2eta", "sig2beta", "sig2deltap", "sig2op", "phi", "nu") } else { stop("Error") } } else { if((is.null(x$sp.covariate.names)) & (is.null(x$tp.covariate.names))){ para <- rbind((x$betap), t(x$sig2ep), t(x$sig2etap), t(x$phip)) dimnames(para)[[1]] <- c(dimnames(x$X)[[2]], "sig2eps", "sig2eta", "phi") } else if((!is.null(x$sp.covariate.names)) & (is.null(x$tp.covariate.names))){ para <- rbind((x$betap), t(x$sig2ep), t(x$sig2etap), t(x$sig2betap), t(x$phip)) dimnames(para)[[1]] <- c(dimnames(x$X)[[2]], "sig2eps", "sig2eta", "sig2beta", "phi") } else if((is.null(x$sp.covariate.names)) & (!is.null(x$tp.covariate.names))){ para <- rbind((x$betap), t(x$sig2ep), t(x$sig2etap), t(x$sig2deltap), t(x$sig2op), t(x$phip)) dimnames(para)[[1]] <- c(dimnames(x$X)[[2]], "sig2eps", "sig2eta", "sig2deltap", "sig2op", "phi") } else if((!is.null(x$sp.covariate.names)) & (!is.null(x$tp.covariate.names))){ para <- rbind((x$betap), t(x$sig2ep), t(x$sig2etap), t(x$sig2betap), t(x$sig2deltap), t(x$sig2op), t(x$phip)) dimnames(para)[[1]] <- c(dimnames(x$X)[[2]], "sig2eps", "sig2eta", "sig2beta", "sig2deltap", "sig2op", "phi") } else { stop("Error") } } para<-t(para) para<-mcmc(para) para } else { } } summary.spTD<-function(object, digits=4, package="spTDyn", coefficient=NULL, ...){ if(package=="coda"){ if(object$combined.fit.pred==TRUE){ stop("\n } else{ if(is.null(coefficient)){ cat("\n if(!is.null(object$sp.covariate.names)) {cat("\n tmp<-as.mcmc(object) summary(tmp, ...) } else if(coefficient=="spatial"){ if(is.null(object$sp.covariate.names)) {stop("\n cat("\n tmp<-as.mcmc(t(object$betasp)) if(object$model=="GPP"){n<-object$knots} else{n<-object$n} tmp<-sp.dimname.fnc(x=tmp,names=object$sp.covariate.names,n=n,q=object$q) summary(tmp, ...) } else if(coefficient=="temporal"){ if(is.null(object$tp.covariate.names)) {stop("\n cat("\n tmp<-as.mcmc(t(object$betatp)) tmp<-tp.dimname.fnc(x=tmp,names=object$tp.covariate.names,u=object$u,T=object$T) summary(tmp, ...) } else if(coefficient=="rho"){ if(is.null(object$rhotp)) {stop("\n cat("\n tmp<-as.mcmc(t(object$rhotp)) dimnames(tmp)[[2]]<-paste("rho",1:object$u,sep="") summary(tmp, ...) } else{ stop("Error: the argument coefficient only takes charecter 'spatial' and 'temporal'.") } } } else{ if(package=="spTDyn"){ coefficient <- coefficient } else if("Xsp"%in%names(object) | "Xtp"%in%names(object)){ coefficient <- coefficient } else{ coefficient <- NULL } if(is.null(coefficient)){ if((!is.null(object$sp.covariate.names)) & (!is.null(object$tp.covariate.names))){cat("\n else if((!is.null(object$sp.covariate.names)) & (is.null(object$tp.covariate.names))) {cat("\n else if((is.null(object$sp.covariate.names)) & (!is.null(object$tp.covariate.names))) {cat("\n else { } print(object) cat("-----------------------------------------------------"); cat('\n'); cat("Parameters:\n") print(round(object$parameter,digits=digits)); cat("-----------------------------------------------------"); cat('\n'); } else if(coefficient=="spatial"){ if(is.null(object$sp.covariate.names)) {stop("\n cat("\n tmp<-as.mcmc(t(object$betasp)) if(object$model=="GPP"){n<-object$knots} else{n<-object$n} tmp<-sp.dimname.fnc(x=tmp,names=object$sp.covariate.names,n=n,q=object$q) summary(tmp, ...) } else if(coefficient=="temporal"){ if(is.null(object$tp.covariate.names)) {stop("\n cat("\n tmp<-as.mcmc(t(object$betatp)) tmp<-tp.dimname.fnc(x=tmp,names=object$tp.covariate.names,u=object$u,T=object$T) summary(tmp, ...) } else if(coefficient=="rho"){ if(is.null(object$rhotp)) {stop("\n cat("\n tmp<-as.mcmc(t(object$rhotp)) dimnames(tmp)[[2]]<-paste("rho",1:object$u,sep="") summary(tmp, ...) } else{ stop("Error: the argument coefficient only takes character 'spatial' and 'temporal'.") } } } plot.spTD<-function(x, residuals=FALSE, coefficient=NULL, ...){ if(as.logical(residuals)==FALSE){ if(x$combined.fit.pred==TRUE){ if(!is.null(x$sp.covariate.names)) {cat(" cat("\n plot(x$fitted[,1],residuals(x),ylab="Residuals",xlab="Fitted values");abline(h=0,lty=2);title("Residuals vs Fitted") par(ask=TRUE) qqnorm(residuals(x));qqline(residuals(x),lty=2) } else{ if(is.null(coefficient)){ if((!is.null(x$sp.covariate.names)) & (!is.null(x$tp.covariate.names))){cat("\n else if((!is.null(x$sp.covariate.names)) & (is.null(x$tp.covariate.names))) {cat("\n else if((is.null(x$sp.covariate.names)) & (!is.null(x$tp.covariate.names))) {cat("\n else { } if(x$model=="GP"){ tmp<-as.mcmc(x) plot(tmp, ...) } else{ x$model="GP" tmp<-as.mcmc(x) plot(tmp, ...) } } else if(coefficient=="spatial"){ if(is.null(x$sp.covariate.names)) {stop("\n tmp<-as.mcmc(t(x$betasp)) if(x$model=="GPP"){n<-x$knots} else{n<-x$n} tmp<-sp.dimname.fnc(x=tmp,names=x$sp.covariate.names,n=n,q=x$q) plot(tmp, ...) } else if(coefficient=="temporal"){ if(is.null(x$tp.covariate.names)) {stop("\n tmp<-as.mcmc(t(x$betatp)) tmp<-tp.dimname.fnc(x=tmp,names=x$tp.covariate.names,u=x$u,T=x$T) plot(tmp, ...) } else if(coefficient=="rho"){ if(is.null(x$rhotp)) {stop("\n tmp<-as.mcmc(t(x$rhotp)) dimnames(tmp)[[2]]<-paste("rho",1:x$u,sep="") plot(tmp, ...) } else{ stop("Error: the argument coefficient only takes charecter 'spatial' and 'temporal'.") } } } else{ if(!is.null(x$sp.covariate.names)) {cat(" plot(x$fitted[,1],residuals(x),ylab="Residuals",xlab="Fitted values");abline(h=0,lty=2);title("Residuals vs Fitted") par(ask=TRUE) qqnorm(residuals(x));qqline(residuals(x),lty=2) } } sp.dimname.fnc<-function(x,names,n,q){ dimnames(x)[[2]][1:(n*q)]<-1:(n*q) for(i in 1:q){ dimnames(x)[[2]][(1+(i-1)*n):(n*i)]<-rep(paste(names[i],"site",1:n,sep="")) } x } tp.dimname.fnc<-function(x,names,u,T){ dimnames(x)[[2]][1:(u*T)]<-1:(u*T) for(i in 1:u){ dimnames(x)[[2]][(1+(i-1)*T):(T*i)]<-rep(paste(names[i],"time",1:T,sep="")) } x } spT.Summary.Stat <- function(y) { up.low.limit<-function(y,limit) { y<-sort(y) y<-y[limit] y } if(is.vector(y)==TRUE){ y <- matrix(y[!is.na(y)]) } else{ y <- t(y) } N <- length(y[1, ]) nItr <- length(y[, 1]) z <- matrix(nrow = N, ncol = 5) dimnames(z) <- list(dimnames(y)[[2]], c("Mean","Median","SD","Low2.5p","Up97.5p")) if (nItr < 40) { stop("\n } z[, 1] <- apply(y,2,mean) z[, 2] <- apply(y,2,median) z[, 3] <- apply(y,2,sd) nl <- as.integer(nItr * 0.025) nu <- as.integer(nItr * 0.975) z[, 4] <- apply(y,2,up.low.limit,limit=nl) z[, 5] <- apply(y,2,up.low.limit,limit=nu) as.data.frame(z) } spT.segment.plot<-function(obs, est, up, low, limit=NULL){ tmp<-cbind(obs,est,up,low) tmp<-na.omit(tmp) if(is.null(limit)==TRUE){ plot(tmp[,1],tmp[,2],xlab="Observations",ylab="Predictions", pch="*", xlim=c(min(c(tmp),na.rm=TRUE),max(c(tmp),na.rm=TRUE)), ylim=c(min(c(tmp),na.rm=TRUE),max(c(tmp),na.rm=TRUE))) } else{ plot(tmp[,1],tmp[,2],xlab="Observations",ylab="Predictions", xlim=c(limit[1],limit[2]),ylim=c(limit[1],limit[2]),pch="*") } segments(tmp[,1],tmp[,2],tmp[,1],tmp[,3]) segments(tmp[,1],tmp[,2],tmp[,1],tmp[,4]) } spT.hit.false<-function(obs,fore,tol){ tmp<-cbind(obs,fore) tmp<-na.omit(tmp) c11<-tmp[tmp[,1]<=tol & tmp[,2]<=tol,] c11<-length(c11)/2 c12<-tmp[tmp[,1]<=tol & tmp[,2]>tol,] c12<-length(c12)/2 c21<-tmp[tmp[,1]>tol & tmp[,2]<=tol,] c21<-length(c21)/2 c22<-tmp[tmp[,1]>tol & tmp[,2]>tol,] c22<-length(c22)/2 mat<-matrix(c(c11,c21,c12,c22),2,2) dimnames(mat)[[1]]<-c(paste("[Obs:<=",tol,"]"),paste("[Obs:> ",tol,"]")) dimnames(mat)[[2]]<-c(paste("[Forecast:<=",tol,"]"),paste("[Forecast:>",tol,"]")) POD<-round(mat[1,1]/sum(diag(mat)),4) FAR<-round(mat[1,2]/sum(mat[1,]),4) HAR<-round(sum(diag(mat))/sum(mat),4) top<-2*(mat[1,1]*mat[2,2]-mat[1,2]*mat[2,1]) bot<-mat[1,2]^2+mat[2,1]^2+2*mat[1,1]*mat[2,2]+(mat[1,2]+mat[2,1])*sum(diag(mat)) S<-round(top/bot,4) x<-list(False.Alarm=FAR,Hit.Rate=HAR,Probability.of.Detection=POD, Heidke.Skill=S,cross.table=mat,tolerance.limit=tol) x } spT.keep.morethan.dist <- function(coords, tol.dist=100) { a <- as.data.frame(coords) names(a) <- c("long","lat") n <- nrow(coords) c1 <- rep(1:n, each=n) c2 <- rep(1:n, n) b <- matrix(NA, nrow=n, ncol=n) w <- as.vector(upper.tri(b)) bigmat <- matrix(0, nrow=n*n, ncol=7) bigmat[, 1] <- c1 bigmat[, 2] <- c2 bigmat[, 3] <- a$long[c1] bigmat[, 4] <- a$lat[c1] bigmat[, 5] <- a$long[c2] bigmat[, 6] <- a$lat[c2] ubmat <- bigmat[w, ] ubmat[,7] <- as.vector(apply(ubmat[,3:6], 1, spT.geo_dist)) v <- ubmat[,7] w <- ubmat[v<tol.dist, ] z <- unique(w[,1]) a <- coords[-z, ] a } PMCC<-function(z=NULL, z.mean=NULL, z.sd=NULL, z.samples=NULL) { if(is.null(z)){ stop("Error: need to provide z values.") } if(is.null(z.mean) | is.null(z.sd)){ if(!is.null(z.mean)){ stop("Error: need to provide z.sd value.") } if(!is.null(z.sd)){ stop("Error: need to provide z.mean value.") } if(is.null(z.samples)){ stop("Error: need to provide z.samples value.") } } if(!is.null(z.samples)){ if ( !is.matrix(z.samples)) { stop("Error: z.samples must be a (N x nItr) matrix") } if (dim(z.samples)[1] != length(z)) { stop("Error: observations in z.samples in each iteration must be equal to length of z") } if ( dim(z.samples)[2] < 40) { stop("Error: samples are too small to obtain summary statistics") } sum.stat = matrix(NA,length(c(z)),6) sum.stat[,1:5] = as.matrix(spT.Summary.Stat(z.samples)) sum.stat[,6] = c(z) sum.stat = sum.stat[!is.na(sum.stat[,6]),] goodness.of.fit = round(sum((sum.stat[,1]-sum.stat[,6])^2),2) penalty = round(sum(sum.stat[,3]^2),2) pmcc = round(goodness.of.fit + penalty,2) out = NULL out$pmcc = pmcc; out$goodness.of.fit = goodness.of.fit out$penalty = penalty out } else{ if(is.null(z.mean) | is.null(z.sd)){ stop("Error: need to provide z.mean and/or z.sd values.") } if(length(c(z)) != length(c(z.mean))){ stop("Error: z and z.mean should be in same length.") } if(length(c(z)) != length(c(z.sd))){ stop("Error: z and z.sd should be in same length.") } sum.stat = matrix(NA,length(c(z)),3) sum.stat[,1] = c(z) sum.stat[,2] = c(z.mean) sum.stat[,3] = c(z.sd) sum.stat = sum.stat[!is.na(sum.stat[,1]),] goodness.of.fit = round(sum((sum.stat[,1]-sum.stat[,2])^2),2) penalty = round(sum(sum.stat[,3]^2),2) pmcc = round(goodness.of.fit + penalty,2) out = NULL out$pmcc = pmcc; out$goodness.of.fit = goodness.of.fit out$penalty = penalty out } } spT.check.locations<-function(fit.locations, pred.locations, method="geodetic:km", tol=5){ if(!method %in% c("geodetic:km", "geodetic:mile", "euclidean", "maximum", "manhattan", "canberra")){ stop("\n } coords.all <- rbind(fit.locations,pred.locations) tn.fitsites <- length(fit.locations[, 1]) nfit.sites <- 1:tn.fitsites tn.predsites <- length(coords.all[, 1]) - tn.fitsites npred.sites <- (tn.fitsites + 1):(length(coords.all[, 1])) if(method=="geodetic:km"){ coords.D <- as.matrix(spT.geodist(Lon=coords.all[,1],Lat=coords.all[,2], KM=TRUE)) } else if(method=="geodetic:mile"){ coords.D <- as.matrix(spT.geodist(Lon=coords.all[,1],Lat=coords.all[,2], KM=FALSE)) } else{ coords.D <- as.matrix(dist(coords.all, method, diag = T, upper = T)) } coords.D[is.na(coords.D)]<-0 diag(coords.D)<-NA fdmis<-coords.D[nfit.sites, npred.sites] if(is.matrix(fdmis)==TRUE){ fdmis<-cbind(c(t(fdmis)),1:dim(fdmis)[[2]],sort(rep(1:dim(fdmis)[[1]],dim(fdmis)[[2]]))) fdmis<-fdmis[fdmis[,1] < tol,] if(!is.na(fdmis[1])==TRUE){ cat(" cat("\n fdmis<-matrix(fdmis,(length(fdmis)/3),3) for(i in 1:dim(fdmis)[[1]]){ print(paste("Distance:", round(fdmis[i,1],2)," Predicted location:",fdmis[i,2]," Fitted location:", fdmis[i,3],"")) } cat(" dimnames(fdmis)[[2]]<-c('distance','pred_location','fit_location') fdmis } else{ cat(" cat("\n } } else{ fdmis<-cbind(c(fdmis),1:length(fdmis)) fdmis<-fdmis[fdmis[,1] < tol,] if(!is.na(fdmis[1])==TRUE){ cat(" cat("\n fdmis<-matrix(fdmis) for(i in 1:dim(fdmis)[[1]]){ print(paste("Distance:", round(fdmis[i,1],2)," Predicted location:",1," Fitted location:", fdmis[i,2],"")) } cat(" dimnames(fdmis)[[2]]<-c('distance','fit_location') fdmis } else{ cat(" cat("\n } } } spT.check.sites.inside<-function(coords, method, tol=0.1){ if(!method %in% c("geodetic:km", "geodetic:mile", "euclidean", "maximum", "manhattan", "canberra")){ stop("\n } if(method=="geodetic:km"){ fdm<- as.matrix(spT.geodist(Lon=coords[,1],Lat=coords[,2], KM=TRUE)) } else if(method=="geodetic:mile"){ fdm<- as.matrix(spT.geodist(Lon=coords[,1],Lat=coords[,2], KM=FALSE)) } else{ fdm<- as.matrix(dist(coords, method, diag = TRUE, upper = TRUE)) } diag(fdm)<-NA fdm<-cbind(c(fdm),1:dim(fdm)[[2]],sort(rep(1:dim(fdm)[[1]],dim(fdm)[[2]]))) fdm<-fdm[!is.na(fdm[,1]),] fdmis<-fdm[fdm[,1] < tol,] if(!is.na(fdmis[1])==TRUE){ cat(" print(paste("( < ",tol," unit) to each other.")) fdmis<-matrix(fdmis,(length(fdmis)/3),3) for(i in 1:dim(fdmis)[[1]]){ print(paste("Distance (unit):", round(fdmis[i,1],2)," site:",fdmis[i,2]," site:", fdmis[i,3],"")) } dimnames(fdmis)[[2]]<-c('dist_km','pred_site','fit_site') fdmis cat(" stop("Error: Termination.") } } fnc.time<-function(t) { if(t < 60){ t <- round(t,2) tt <- paste(t," - Sec.") cat(paste(" } if(t < (60*60) && t >= 60){ t1 <- as.integer(t/60) t <- round(t-t1*60,2) tt <- paste(t1," - Mins.",t," - Sec.") cat(paste(" } if(t < (60*60*24) && t >= (60*60)){ t2 <- as.integer(t/(60*60)) t <- t-t2*60*60 t1 <- as.integer(t/60) t <- round(t-t1*60,2) tt <- paste(t2," - Hour/s.",t1," - Mins.",t," - Sec.") cat(paste(" } if(t >= (60*60*24)){ t3 <- as.integer(t/(60*60*24)) t <- t-t3*60*60*24 t2 <- as.integer(t/(60*60)) t <- t-t2*60*60 t1 <- as.integer(t/60) t <- round(t-t1*60,2) tt <- paste(t3," - Day/s.",t2," - Hour/s.",t1," - Mins.",t," - Sec.") cat(paste(" } tt } sp<-function(x){ class(x)<-"spBeta" x } tp<-function(x){ class(x)<-"tpBeta" x } ObsGridLoc<-function(obsLoc, gridLoc, distance.method="geodetic:km", plot=FALSE) { if(!distance.method %in% c("geodetic:km", "geodetic:mile", "euclidean", "maximum", "manhattan", "canberra")){ stop("\n } coords.all <- rbind(obsLoc, gridLoc) n1.sites <- 1:dim(obsLoc)[[1]] n2.sites <- (dim(obsLoc)[[1]] + 1):(dim(coords.all)[[1]]) if(distance.method=="geodetic:km"){ coords.D <- as.matrix(spT.geodist(Lon=coords.all[,1],Lat=coords.all[,2], KM=TRUE)) } else if(distance.method=="geodetic:mile"){ coords.D <- as.matrix(spT.geodist(Lon=coords.all[,1],Lat=coords.all[,2], KM=FALSE)) } else{ coords.D <- as.matrix(dist(coords.all, distance.method, diag = T, upper = T)) } coords.D[is.na(coords.D)]<-0 diag(coords.D)<-NA fdmis<-coords.D[n1.sites, n2.sites] min.fnc<-function(x){ x<-cbind(x,1:length(x)) x<-x[order(x[,1]),] x<-x[1,] x } fdmis<-t(apply(fdmis,1,min.fnc)) fdmis<-cbind(obsLoc,gridLoc[fdmis[,2],],fdmis[,2],fdmis[,1]) dimnames(fdmis)[[2]]<-c("obsLon","obsLat","gridLon","gridLat","gridNum","dist") if(plot==TRUE){ plot(fdmis[,1:2],pch="*") points(fdmis[,3:4],pch=19,col=2) legend("bottomleft",pch=c(8,19),col=c(1,2),legend=c("Observation locations", "Grid locations"),cex=0.9) } fdmis } gridTodata<-function(gridData, gridLoc=NULL, gridLon=NULL, gridLat=NULL) { options(warn=-1) if(!is.null(gridLoc)){ lonlat<-gridLoc dimnames(lonlat)[[2]]<-c("lon","lat") } else if((!is.null(gridLon)) & (!is.null(gridLat))){ lonlat<-expand.grid(gridLon, gridLat) dimnames(lonlat)[[2]]<-c("lon","lat") } else{ stop("Error: check grid location input in the function") } if(is.list(gridData)){ n<-length(gridData) if(n>1){ dat<-NULL for(i in 1:n){ grid<-c(gridData[[i]]) dat<-cbind(dat,grid) } for(i in 1:n){ dimnames(dat)[[2]][i]<-paste("grid",i,sep="") } dat<-cbind(lon=rep(lonlat[,1],length(c(gridData[[1]]))/dim(lonlat)[[1]]), lat=rep(lonlat[,2],length(c(gridData[[1]]))/dim(lonlat)[[1]]),dat) } else{ dat<-cbind(lon=rep(lonlat[,1],length(c(gridData[[1]]))/dim(lonlat)[[1]]), lat=rep(lonlat[,2],length(c(gridData[[1]]))/dim(lonlat)[[1]]),grid=c(gridData)) } } else{ dat<-cbind(lon=rep(lonlat[,1],length(c(gridData))/dim(lonlat)[[1]]), lat=rep(lonlat[,2],length(c(gridData))/dim(lonlat)[[1]]),grid=c(gridData)) } dat<-dat[order(dat[,1],dat[,2]),] dat } ObsGridData<-function(obsData, gridData, obsLoc, gridLoc, distance.method="geodetic:km") { obsLoc<-as.matrix(obsLoc) gridLoc<-as.matrix(gridLoc) dimnames(obsLoc)<-NULL dimnames(gridLoc)<-NULL if((is.list(gridData)) & (is.list(gridLoc))){ n1<-length(gridData) n2<-length(gridLoc) if(n1 != n2){ stop("\n Error: list of gridData and gridLoc should be same") } datt<-NULL for(i in 1:n1){ gLoc<-gridLoc[[i]] gLoc<-gLoc[order(gLoc[,1],gLoc[,2]),] comb<-ObsGridLoc(obsLoc=obsLoc, gridLoc=gLoc, distance.method=distance.method) grid<-gridTodata(gridData=gridData[[i]], gridLoc=gLoc) grid<-cbind(gridNum=sort(rep(1:dim(gLoc)[[1]],dim(grid)[[1]]/dim(gLoc)[[1]])),grid) dat<-NULL for(j in comb[,5]){ dat<-rbind(dat,grid[grid[,1]==j,]) } dimnames(dat)[[2]]<-c(paste("gridNum",i,sep=""),paste("grid.lon",i,sep=""),paste("grid.lat",i,sep=""),paste("grid",i,sep="")) if(dim(obsData)[[1]] != dim(dat)[[1]]){ stop("Error: check the day and year for gridData\n obsData and gridData time points mismatch.\n")} datt<-cbind(datt,dat) } dat<-cbind(obsData,datt); rm(datt); dat } else{ comb<-ObsGridLoc(obsLoc=obsLoc, gridLoc=gridLoc[order(gridLoc[,1],gridLoc[,2]),], distance.method=distance.method) grid<-gridTodata(gridData=gridData, gridLoc=gridLoc[order(gridLoc[,1],gridLoc[,2]),]) grid<-cbind(gridNum=sort(rep(1:dim(gridLoc)[[1]],dim(grid)[[1]]/dim(gridLoc)[[1]])),grid) dat<-NULL for(i in comb[,5]){ dat<-rbind(dat,grid[grid[,1]==i,]) } dimnames(dat)[[2]][2:3]<-c("grid.lon","grid.lat") if(dim(obsData)[[1]] != dim(dat)[[1]]){ stop("Error: check the day and year for gridData\n obsData and gridData time points mismatch.\n")} dat<-cbind(obsData,dat) dat } } truncated.fnc<-function(Y, at=0, lambda=NULL, both=FALSE){ if(is.null(lambda)){ stop("Error: define truncation parameter lambda properly using list ") } if(is.null(at)){ stop("Error: define truncation point properly using list ") } if(at < 0){ stop("Error: currently truncation point only can take value >= zero ") } zm <- cbind(Y,Y-at,1) zm[zm[, 2] <= 0, 3] <- 0 zm[, 2] <- zm[, 2]^(1/lambda) zm[zm[, 3] == 0, 2] <- -(rgamma(nrow(zm[zm[,3]==0,]), shape=1, rate=1/(range(zm[zm[,3]==1,2],na.rm=TRUE)[[2]]/4.1))) if (both == TRUE) { zm } else { c(zm[,2]) } } reverse.truncated.fnc<-function(Y, at=0, lambda=NULL){ if(is.null(lambda)){ stop("Error: define truncation parameter lambda properly using list ") } zm <- Y zm[zm <= 0]<- 0 zm <- zm^(lambda) zm <- zm + at zm } prob.below.threshold <- function(out, at){ fnc<-function(x, at){ length(x[x <= at])/length(x) } apply(out,1,fnc,at=at) }
toMaxDiag_n <- function(pars, u, sigmaType, kKi, kLh, kLhi, kY, kX, kZ) { kP <- ncol(kX) kR <- length(kKi) kK <- ncol(kZ) kL <- sum(kLh) beta <- pars[1:kP] s0 <- length(pars[-(1:kP)]) ovSigma <- constructSigma(pars = pars[-(1:kP)], sigmaType = sigmaType, kK = kK, kR = kR, kLh = kLh, kLhi = kLhi) if (min(eigen(ovSigma)$values) <= 0) { return(list(value = -Inf, gradient = rep(0, length(pars)), hessian = matrix(0, length(pars), length(pars)))) } return(qFunctionDiagCpp_n(beta, ovSigma, kKi, u, kY, kX, kZ)) }
library(testthat) library(tryCatchLog) context("test_tryCatchLog_basics.R") source("init_unit_test.R") source("disable_logging_output.R") test_that("log(-1) did throw a warning", { expect_warning(log(-1)) }) test_that("log('abc') did throw an error", { expect_error(log("abc")) }) test_that("tryCatchLog creates no warning", { expect_silent(tryCatchLog(log(1))) }) test_that("tryCatchLog did throw a warning", { expect_warning(tryCatchLog(log(-1))) }) test_that("tryCatchLog did throw an error", { expect_error(tryCatchLog(log("abc"), error = stop)) }) test_that("tryCatchLog did call the error handler", { expect_equal(2, tryCatchLog({ flag <- 1 log("abc") flag <- 3 }, error = function(e) { flag <<- 2 })) }) test_that("tryCatchLog with warning continues", { withCallingHandlers( tryCatchLog({ did.warn <- FALSE flag <- 1 log(-1) flag <- 2 }) , warning = function(w) { did.warn <<- TRUE invokeRestart("muffleWarning") } ) expect_equal(2, flag) expect_true(did.warn) }) test_that("tryCatchLog with message continues", { withCallingHandlers( tryCatchLog({ msg.sent <- FALSE did.continue <- FALSE throw.msg <- function() message("read this message!") throw.msg() did.continue <- TRUE }) , message = function(w) { msg.sent <<- TRUE invokeRestart("muffleMessage") } ) expect_true(did.continue) expect_true(msg.sent) }) test_that("tryCatchLog stops with an error and called the outer error function", { tryCatch( tryCatchLog({ did.raise.err <- FALSE canceled <- TRUE log("a") canceled <- FALSE }, error = stop), error = function(e) { did.raise.err <<- TRUE } ) expect_true(canceled) expect_true(did.raise.err) })
showCutPoints <- function(data) { if (inherits(data, c("edsurvey.data.frame.list"))) { return(itterateESDFL(match.call(), data)) } checkDataClass(data, c("edsurvey.data.frame", "light.edsurvey.data.frame")) cat(paste0("Achievement Levels:\n")) als <- getAttributes(data, "achievementLevels") if (length(als) > 0) { for(i in 1:length(als)) { cat(paste0(" ", names(als)[i], ": ", paste(unname(als[[i]]), collapse=", "), "\n")) } } else { cat(paste0(" No achievement levels.\n")) } }
SDMmodel2MaxEnt <- function(model) { if (class(model@model) != "Maxent") stop("'model' must be a SDMmodel object trained using the 'Maxent' method!") maxent_model <- new("MaxEnt") maxent_model@presence <- .get_presence(model@data) maxent_model@absence <- .get_absence(model@data) maxent_model@lambdas <- model@model@lambdas maxent_model@hasabsence <- TRUE return(maxent_model) }
test_that("orphanReactants function: output class is wrong", { expect_true(is.vector(orphanReactants("2 A[c] + 3 B[c] => 5 D[c]"))) expect_true(is.vector(orphanReactants("2 5-A[c] + 3 B[c] <=> 5 3D[c]"))) }) test_that("orphanReactants function: output value is wrong", { expect_equal(orphanReactants("2 A[c] + 3 B[c] => 5 D[c]"), c("A[c]", "B[c]")) expect_equivalent(orphanReactants("2 5-A[c] + 3 B[c] <=> 5 3D[c]"), c("3D[c]", "5-A[c]", "B[c]")) })
fastML.init <- function(etas.obj){ params.ind =etas.obj$params.ind params.fix =etas.obj$params.fix nparams.etas =etas.obj$nparams.etas nparams =etas.obj$nparams ntheta =etas.obj$ntheta params<-etas.obj$params params.lim =c(0,0,0,0.9999,0,0,0) fast.eps=etas.obj$fast.eps params.etas =params[1:nparams.etas] betacov =etas.obj$betacov params.e =params.fix params.e[params.ind==1]=exp(params.etas)+params.lim[params.ind==1] lambda = params.e[1] k0 = params.e[2] c = params.e[3] p = params.e[4] gamma = params.e[5] d = params.e[6] q = params.e[7] predictor =as.matrix(etas.obj$cov.matrix)%*%as.vector(betacov)+as.vector(etas.obj$offset) eta=as.numeric(predictor) x =etas.obj$cat$xcat.work y =etas.obj$cat$ycat.work t =etas.obj$cat$time.work m =etas.obj$cat$magnitude n <-length(x) qq=list() for(i in 2:n){ dx=x[i]-x[1:(i-1)] dy=y[i]-y[1:(i-1)] dt1=abs(t[i]-t[1:(i-1)]) ds=1/((dx*dx+dy*dy)/exp(gamma*m[i])+d)^q dt=ds*exp(eta[i])*(dt1+c)^(-p) qq[[i]]=max(dt) print(c(i,qq[[i]])) } maxq=max(unlist(qq)) ind=array(0,n) index.parz=numeric(0) index.tot=numeric(0) for(i in 2:n){ maxq=as.numeric(qq[[i]]) dx=x[i]-x[1:(i-1)] dy=x[i]-x[1:(i-1)] dt=abs(x[i]-x[1:(i-1)]) ds=1/((dx*dx+dy*dy)/exp(gamma*m[i])+d)^q dt=ds*(dt+c)^(-p)*exp(eta[i]) index.parz=which(dt>fast.eps*maxq) ind[i]=ind[i-1]+length(index.parz) index.tot=c(index.tot,index.parz) cat(c(i,length(index.parz)),";") } return(list(index.tot=index.tot,ind=ind)) }
group_data <- function(.data) { UseMethod("group_data") } group_data.data.frame <- function(.data) { rows <- new_list_of(list(seq_len(nrow(.data))), ptype = integer()) new_data_frame(list(.rows = rows), n = 1L) } group_data.tbl_df <- function(.data) { as_tibble(NextMethod()) } group_data.rowwise_df <- function(.data) { attr(.data, "groups") } group_data.grouped_df <- function(.data) { attr(validate_grouped_df(.data), "groups") } group_keys <- function(.tbl, ...) { UseMethod("group_keys") } group_keys.data.frame <- function(.tbl, ...) { if (dots_n(...) > 0) { lifecycle::deprecate_warn( "1.0.0", "group_keys(... = )", details = "Please `group_by()` first" ) .tbl <- group_by(.tbl, ...) } out <- group_data(.tbl) .Call(`dplyr_group_keys`, out) } group_rows <- function(.data) { group_data(.data)[[".rows"]] } group_indices <- function(.data, ...) { if (nargs() == 0) { lifecycle::deprecate_warn("1.0.0", "group_indices()", "cur_group_id()") return(cur_group_id()) } UseMethod("group_indices") } group_indices.data.frame <- function(.data, ...) { if (dots_n(...) > 0) { lifecycle::deprecate_warn( "1.0.0", "group_keys(... = )", details = "Please `group_by()` first" ) .data <- group_by(.data, ...) } .Call(`dplyr_group_indices`, .data, group_rows(.data)) } group_vars <- function(x) { UseMethod("group_vars") } group_vars.data.frame <- function(x) { setdiff(names(group_data(x)), ".rows") } groups <- function(x) { UseMethod("groups") } groups.data.frame <- function(x) { syms(group_vars(x)) } group_size <- function(x) UseMethod("group_size") group_size.data.frame <- function(x) { lengths(group_rows(x)) } n_groups <- function(x) UseMethod("n_groups") n_groups.data.frame <- function(x) { nrow(group_data(x)) }
PredStempCens = function(Est.StempCens, locPre, timePre, xPre){ if(class(Est.StempCens)!="Est.StempCens") stop("An object of the class Est.StempCens must be provided") if(class(locPre)!="matrix" & class(locPre)!="data.frame") stop("locPre must be a matrix or data.frame") if(class(xPre)!="matrix") stop("xPre must be a matrix") if(class(timePre)!="matrix" & class(timePre)!="data.frame") stop("timePre must be a matrix or data.frame") if(nrow(locPre)!=nrow(timePre)) stop("The number of rows in locPre must be equal to the length of timePre") if(nrow(locPre)!=nrow(xPre)) stop("The number of rows in locPre must be equal to the number of rows in xPre") model = Est.StempCens loc.Pre = locPre time.Pre = timePre x.pre = xPre ypred <- PredictNewValues(model,loc.Pre,time.Pre,x.pre) out.ST <- ypred class(out.ST) <- "Pred.StempCens" return(invisible(out.ST)) }
`%like%` <- function(var, pattern){ stringi::stri_detect_regex(var, pattern, case_insensitive = TRUE) } `%LIKE%` <- `%like%` `%slike%` <- function(var, pattern){ stringi::stri_detect_regex(var, pattern, case_insensitive = FALSE) } `%SLIKE%` <- `%slike%`
setMethod("posterior_predict", "ubmsFit", function(object, param=c("y","z"), draws=NULL, re.form=NULL, ...){ param <- match.arg(param, c("y", "z")) nsamp <- nsamples(object) samp_inds <- get_samples(object, draws) switch(param, "z" = sim_z(object, samples=samp_inds, re.form=re.form), "y" = sim_y(object, samples=samp_inds, re.form=re.form)) }) setGeneric("sim_z", function(object, ...) standardGeneric("sim_z")) setGeneric("sim_y", function(object, ...) standardGeneric("sim_y")) process_z <- function(object, samples, re.form, z){ if(is.null(z)){ z <- t(sim_z(object, samples=samples, re.form=re.form)) } else { z <- t(z) } z }
rulefile <- tempfile(fileext=".R") writeLines("rules:\n-\n expr:\n name:", con=rulefile) expect_warning(validator(.file = rulefile))
context("test-ahull.R") test_that("Triangles ", { ex1 <- ahull(, c(0, 1, 2, 3, 4), c(0, 1, 2, 0, 0)) expect_equal(ex1$area, 1.5) expect_equal(ex1$xmin, 1) ex2 <- ahull(data.table(x = c(1:6), y = c(0, 2, 1.5, 2, 0.9, -1))) ex3 <- ahull(data.table(x = c(1:6), y = -c(0, 2, 1.5, 2, 0.9, -1)), incl_negative = TRUE) ex4 <- ahull(data.table(x = c(1:6), y = c(0, 2, 1.5, 2, 0.9, -1)), maximize = "") expect_equal(ex2$ymax, 1.5) expect_equal(ex3$ymin, -1.5) ex5 <- ahull(data.table(x = 1:5, y = c(0, 1, 0, 1, 0))) expect_equal(ex5[["h"]], 0) expect_true(is.na(area_from_min(1L, data.table(x = 1:6, y = c(0, 1, 0, 1, 0, 0)))[["xmax"]])) expect_equal(area_from_min(1L, data.table(x = 1:6, y = c(0, 1, 0, 1, 0, 1)))[["h"]], 0) expect_equal(area_from_min(6L, data.table(x = 1:6, y = c(0, 1, 0, 1, 0, 0)))[["h"]], 0) expect_equal(area_from_min(2L, data.table(x = 1:6, y = c(0, 1, 0, 1, 0, 0)))[["h"]], 1) expect_true(is.na(area_from_min(2L, data.table(x = 1:6, y = c(0, 1, 0, 1, 0, 0)))[["w"]])) expect_true(is.na(area_from_min(4L, data.table(x = 1:6, y = c(0.1, 1, 0, 1, 0.2, 0)))[["w"]])) }) test_that("warnings", { expect_warning(ahull(, 0, 0)) }) test_that("mini-utils", { library(magrittr) library(data.table) expect_identical(A(1, 1, 2, 2, 3, 0), list(0.5, 2.5)) expect_identical(height2x(1.5, 1:5, c(1, 2, -1, 1, 2)), c(2+1/6, 1.5, 4.5)) expect_error(height2x(1.5, 5:1, c(1, 2, -1, 1, 2)), regexp = "sorted") dtemi <- data.table(x = 1:5, y = c(0.03, 0.49, 0, 0.65, 1)) expect_identical(areas_right_of(dtemi), c(1L, 3L)) dtemil_1nna <- areas_right_of(dtemi, return_ind = FALSE)[[1L]] %>% as.double %>% .[!is.na(.)] expect_equal(dtemil_1nna, 0.23, tol = 0.001) }) test_that("Corners", { h0 <- ahull(, c(0:4), rep(-1, 5)) expect_equal(h0[["h"]], 0) hxy <- ahull(, 0:4, c(0, 1, 2, 1, 0.5)) expect_equal(hxy[["area"]], 1.75) h01 <- ahull(, c(0:4), c(0, 1, 2, -1, 4)) expect_equal(h01[["xmax"]], 2+1/3) }) test_that("Hulls may be above 0 even if the next point on the curve is negative", { skip("Not yet considered") })
plot.cdslist <- function(x, which = 2L, ...){ loss <- sapply(x, "[[", "minloss") K <- sapply(x, "[[", "K") plot(K, loss, type = "b", pch = 16, main = "Scree Plot", xlab = "K", ylab = "Loss") invisible(lapply(x, plot, which = which, ...)) }
plot_number_of_repetitions <- function(x, ...) { mapping <- attr(x, "mapping") level <- attr(x, "level") units <- attr(x, "units") type <- attr(x,"type") absolute <- NULL if(level == "log") { attr(x, "raw") %>% ggplot(aes("", absolute)) + geom_boxplot() + scale_y_continuous() + theme_light() + coord_flip() + labs(x = "", y = glue("Number of {type} repetitions (per case)")) -> p } else if(level == "case") { x %>% ggplot(aes_string(glue("reorder({mapping$case_id}, absolute)"), "absolute")) + geom_col(aes(fill = absolute)) + scale_fill_continuous_tableau(palette = "Blue", name = "Number of repetitions") + labs(x = "Cases", y = glue("Number of {type} repetitions")) + scale_y_continuous() + coord_flip() + theme_light() + theme(axis.text.x = element_blank()) + scale_x_discrete(breaks = NULL) -> p } else if(level == "activity") { x %>% ggplot(aes_string(glue("reorder({mapping$activity_id}, absolute)"), "absolute")) + geom_col(aes(fill = absolute)) + scale_y_continuous() + theme_light() + coord_flip() + labs(x = "Activity", y = glue("Number of {type} repetitions")) -> p } else if(level == "resource") { if(type %in% c("redo", "all")) { x %>% ggplot(aes_string(glue("reorder(first_resource, absolute)"), "absolute")) + geom_col(aes(fill = absolute)) + scale_y_continuous() + theme_light() + coord_flip() + labs(x = "First resource", y = glue("Number of {type} repetitions")) -> p } else if (type == "repeat") { x %>% ggplot(aes_string(glue("reorder({mapping$resource_id}, absolute)"), "absolute")) + geom_col(aes(fill = absolute)) + scale_y_continuous() + theme_light() + coord_flip() + labs(x = "Resource", y = glue("Number of {type} repetitions")) -> p } } else if(level == "resource-activity") { if(type %in% c("redo", "all")) { x %>% ggplot(aes_string(mapping$activity_id, "first_resource")) + geom_tile(aes(fill = absolute)) + geom_text(aes(label = absolute), fontface = "bold", color = "white") + theme_light() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + scale_fill_continuous_tableau(glue("Number of {type} repetitions"), palette = "Blue") + labs(x = "Activity", y = "First resource") -> p } else if (type == "repeat") { x %>% ggplot(aes_string(mapping$activity_id, mapping$resource_id)) + geom_tile(aes(fill = absolute)) + geom_text(aes(label = absolute), fontface = "bold", color = "white") + theme_light() + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + scale_fill_continuous_tableau(glue("Number of {type} repetitions"), palette = "Blue") + labs(x = "Activity", y = "Resource") -> p } } if(!is.null(attr(x, "groups"))) { p <- p + facet_grid(as.formula(paste(c(paste(attr(x, "groups"), collapse = "+"), "~." ), collapse = "")), scales = "free_y") } return(p) }
wbt_change_vector_analysis <- function(date1, date2, magnitude, direction, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--date1=", date1)) args <- paste(args, paste0("--date2=", date2)) args <- paste(args, paste0("--magnitude=", magnitude)) args <- paste(args, paste0("--direction=", direction)) if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "change_vector_analysis" wbt_run_tool(tool_name, args, verbose_mode) } wbt_closing <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "closing" wbt_run_tool(tool_name, args, verbose_mode) } wbt_create_colour_composite <- function(red, green, blue, output, opacity=NULL, enhance=TRUE, zeros=FALSE, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--red=", red)) args <- paste(args, paste0("--green=", green)) args <- paste(args, paste0("--blue=", blue)) args <- paste(args, paste0("--output=", output)) if (!is.null(opacity)) { args <- paste(args, paste0("--opacity=", opacity)) } if (enhance) { args <- paste(args, "--enhance") } if (zeros) { args <- paste(args, "--zeros") } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "create_colour_composite" wbt_run_tool(tool_name, args, verbose_mode) } wbt_flip_image <- function(input, output, direction="vertical", wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(direction)) { args <- paste(args, paste0("--direction=", direction)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "flip_image" wbt_run_tool(tool_name, args, verbose_mode) } wbt_ihs_to_rgb <- function(intensity, hue, saturation, red=NULL, green=NULL, blue=NULL, output=NULL, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--intensity=", intensity)) args <- paste(args, paste0("--hue=", hue)) args <- paste(args, paste0("--saturation=", saturation)) if (!is.null(red)) { args <- paste(args, paste0("--red=", red)) } if (!is.null(green)) { args <- paste(args, paste0("--green=", green)) } if (!is.null(blue)) { args <- paste(args, paste0("--blue=", blue)) } if (!is.null(output)) { args <- paste(args, paste0("--output=", output)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "ihs_to_rgb" wbt_run_tool(tool_name, args, verbose_mode) } wbt_image_slider <- function(input1, input2, output, palette1="grey", reverse1=FALSE, label1="", palette2="grey", reverse2=FALSE, label2="", height=600, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input1=", input1)) args <- paste(args, paste0("--input2=", input2)) args <- paste(args, paste0("--output=", output)) if (!is.null(palette1)) { args <- paste(args, paste0("--palette1=", palette1)) } if (reverse1) { args <- paste(args, "--reverse1") } if (!is.null(label1)) { args <- paste(args, paste0("--label1=", label1)) } if (!is.null(palette2)) { args <- paste(args, paste0("--palette2=", palette2)) } if (reverse2) { args <- paste(args, "--reverse2") } if (!is.null(label2)) { args <- paste(args, paste0("--label2=", label2)) } if (!is.null(height)) { args <- paste(args, paste0("--height=", height)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "image_slider" wbt_run_tool(tool_name, args, verbose_mode) } wbt_image_stack_profile <- function(inputs, points, output, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--inputs=", inputs)) args <- paste(args, paste0("--points=", points)) args <- paste(args, paste0("--output=", output)) if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "image_stack_profile" wbt_run_tool(tool_name, args, verbose_mode) } wbt_integral_image <- function(input, output, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "integral_image" wbt_run_tool(tool_name, args, verbose_mode) } wbt_line_thinning <- function(input, output, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "line_thinning" wbt_run_tool(tool_name, args, verbose_mode) } wbt_mosaic <- function(output, inputs=NULL, method="nn", wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--output=", output)) if (!is.null(inputs)) { args <- paste(args, paste0("--inputs=", inputs)) } if (!is.null(method)) { args <- paste(args, paste0("--method=", method)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "mosaic" wbt_run_tool(tool_name, args, verbose_mode) } wbt_mosaic_with_feathering <- function(input1, input2, output, method="cc", weight=4.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input1=", input1)) args <- paste(args, paste0("--input2=", input2)) args <- paste(args, paste0("--output=", output)) if (!is.null(method)) { args <- paste(args, paste0("--method=", method)) } if (!is.null(weight)) { args <- paste(args, paste0("--weight=", weight)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "mosaic_with_feathering" wbt_run_tool(tool_name, args, verbose_mode) } wbt_normalized_difference_index <- function(input1, input2, output, clip=0.0, correction=0.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input1=", input1)) args <- paste(args, paste0("--input2=", input2)) args <- paste(args, paste0("--output=", output)) if (!is.null(clip)) { args <- paste(args, paste0("--clip=", clip)) } if (!is.null(correction)) { args <- paste(args, paste0("--correction=", correction)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "normalized_difference_index" wbt_run_tool(tool_name, args, verbose_mode) } wbt_opening <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "opening" wbt_run_tool(tool_name, args, verbose_mode) } wbt_remove_spurs <- function(input, output, iterations=10, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(iterations)) { args <- paste(args, paste0("--iterations=", iterations)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "remove_spurs" wbt_run_tool(tool_name, args, verbose_mode) } wbt_resample <- function(inputs, output, cell_size=NULL, base=NULL, method="cc", wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--inputs=", inputs)) args <- paste(args, paste0("--output=", output)) if (!is.null(cell_size)) { args <- paste(args, paste0("--cell_size=", cell_size)) } if (!is.null(base)) { args <- paste(args, paste0("--base=", base)) } if (!is.null(method)) { args <- paste(args, paste0("--method=", method)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "resample" wbt_run_tool(tool_name, args, verbose_mode) } wbt_rgb_to_ihs <- function(intensity, hue, saturation, red=NULL, green=NULL, blue=NULL, composite=NULL, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--intensity=", intensity)) args <- paste(args, paste0("--hue=", hue)) args <- paste(args, paste0("--saturation=", saturation)) if (!is.null(red)) { args <- paste(args, paste0("--red=", red)) } if (!is.null(green)) { args <- paste(args, paste0("--green=", green)) } if (!is.null(blue)) { args <- paste(args, paste0("--blue=", blue)) } if (!is.null(composite)) { args <- paste(args, paste0("--composite=", composite)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "rgb_to_ihs" wbt_run_tool(tool_name, args, verbose_mode) } wbt_split_colour_composite <- function(input, red=NULL, green=NULL, blue=NULL, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) if (!is.null(red)) { args <- paste(args, paste0("--red=", red)) } if (!is.null(green)) { args <- paste(args, paste0("--green=", green)) } if (!is.null(blue)) { args <- paste(args, paste0("--blue=", blue)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "split_colour_composite" wbt_run_tool(tool_name, args, verbose_mode) } wbt_thicken_raster_line <- function(input, output, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "thicken_raster_line" wbt_run_tool(tool_name, args, verbose_mode) } wbt_tophat_transform <- function(input, output, filterx=11, filtery=11, variant="white", wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(variant)) { args <- paste(args, paste0("--variant=", variant)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "tophat_transform" wbt_run_tool(tool_name, args, verbose_mode) } wbt_write_function_memory_insertion <- function(input1, input2, output, input3=NULL, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input1=", input1)) args <- paste(args, paste0("--input2=", input2)) args <- paste(args, paste0("--output=", output)) if (!is.null(input3)) { args <- paste(args, paste0("--input3=", input3)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "write_function_memory_insertion" wbt_run_tool(tool_name, args, verbose_mode) } wbt_evaluate_training_sites <- function(inputs, polys, field, output, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--inputs=", inputs)) args <- paste(args, paste0("--polys=", polys)) args <- paste(args, paste0("--field=", field)) args <- paste(args, paste0("--output=", output)) if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "evaluate_training_sites" wbt_run_tool(tool_name, args, verbose_mode) } wbt_generalize_classified_raster <- function(input, output, min_size=4, method="longest", wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(min_size)) { args <- paste(args, paste0("--min_size=", min_size)) } if (!is.null(method)) { args <- paste(args, paste0("--method=", method)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "generalize_classified_raster" wbt_run_tool(tool_name, args, verbose_mode) } wbt_generalize_with_similarity <- function(input, similarity, output, min_size=4, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--similarity=", similarity)) args <- paste(args, paste0("--output=", output)) if (!is.null(min_size)) { args <- paste(args, paste0("--min_size=", min_size)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "generalize_with_similarity" wbt_run_tool(tool_name, args, verbose_mode) } wbt_image_segmentation <- function(inputs, output, threshold=0.5, steps=10, min_area=4, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--inputs=", inputs)) args <- paste(args, paste0("--output=", output)) if (!is.null(threshold)) { args <- paste(args, paste0("--threshold=", threshold)) } if (!is.null(steps)) { args <- paste(args, paste0("--steps=", steps)) } if (!is.null(min_area)) { args <- paste(args, paste0("--min_area=", min_area)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "image_segmentation" wbt_run_tool(tool_name, args, verbose_mode) } wbt_min_dist_classification <- function(inputs, polys, field, output, threshold=NULL, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--inputs=", inputs)) args <- paste(args, paste0("--polys=", polys)) args <- paste(args, paste0("--field=", field)) args <- paste(args, paste0("--output=", output)) if (!is.null(threshold)) { args <- paste(args, paste0("--threshold=", threshold)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "min_dist_classification" wbt_run_tool(tool_name, args, verbose_mode) } wbt_parallelepiped_classification <- function(inputs, polys, field, output, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--inputs=", inputs)) args <- paste(args, paste0("--polys=", polys)) args <- paste(args, paste0("--field=", field)) args <- paste(args, paste0("--output=", output)) if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "parallelepiped_classification" wbt_run_tool(tool_name, args, verbose_mode) } wbt_adaptive_filter <- function(input, output, filterx=11, filtery=11, threshold=2.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(threshold)) { args <- paste(args, paste0("--threshold=", threshold)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "adaptive_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_bilateral_filter <- function(input, output, sigma_dist=0.75, sigma_int=1.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(sigma_dist)) { args <- paste(args, paste0("--sigma_dist=", sigma_dist)) } if (!is.null(sigma_int)) { args <- paste(args, paste0("--sigma_int=", sigma_int)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "bilateral_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_canny_edge_detection <- function(input, output, sigma=0.5, low=0.05, high=0.15, add_back=FALSE, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(sigma)) { args <- paste(args, paste0("--sigma=", sigma)) } if (!is.null(low)) { args <- paste(args, paste0("--low=", low)) } if (!is.null(high)) { args <- paste(args, paste0("--high=", high)) } if (add_back) { args <- paste(args, "--add_back") } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "canny_edge_detection" wbt_run_tool(tool_name, args, verbose_mode) } wbt_conservative_smoothing_filter <- function(input, output, filterx=3, filtery=3, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "conservative_smoothing_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_corner_detection <- function(input, output, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "corner_detection" wbt_run_tool(tool_name, args, verbose_mode) } wbt_diff_of_gaussian_filter <- function(input, output, sigma1=2.0, sigma2=4.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(sigma1)) { args <- paste(args, paste0("--sigma1=", sigma1)) } if (!is.null(sigma2)) { args <- paste(args, paste0("--sigma2=", sigma2)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "diff_of_gaussian_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_diversity_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "diversity_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_edge_preserving_mean_filter <- function(input, output, threshold, filter=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) args <- paste(args, paste0("--threshold=", threshold)) if (!is.null(filter)) { args <- paste(args, paste0("--filter=", filter)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "edge_preserving_mean_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_emboss_filter <- function(input, output, direction="n", clip=0.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(direction)) { args <- paste(args, paste0("--direction=", direction)) } if (!is.null(clip)) { args <- paste(args, paste0("--clip=", clip)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "emboss_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_fast_almost_gaussian_filter <- function(input, output, sigma=1.8, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(sigma)) { args <- paste(args, paste0("--sigma=", sigma)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "fast_almost_gaussian_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_gaussian_filter <- function(input, output, sigma=0.75, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(sigma)) { args <- paste(args, paste0("--sigma=", sigma)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "gaussian_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_high_pass_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "high_pass_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_high_pass_median_filter <- function(input, output, filterx=11, filtery=11, sig_digits=2, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(sig_digits)) { args <- paste(args, paste0("--sig_digits=", sig_digits)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "high_pass_median_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_k_nearest_mean_filter <- function(input, output, filterx=11, filtery=11, k=5, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(k)) { args <- paste(args, paste0("--k=", k)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "k_nearest_mean_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_laplacian_filter <- function(input, output, variant="3x3(1)", clip=0.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(variant)) { args <- paste(args, paste0("--variant=", variant)) } if (!is.null(clip)) { args <- paste(args, paste0("--clip=", clip)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "laplacian_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_laplacian_of_gaussian_filter <- function(input, output, sigma=0.75, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(sigma)) { args <- paste(args, paste0("--sigma=", sigma)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "laplacian_of_gaussian_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_lee_sigma_filter <- function(input, output, filterx=11, filtery=11, sigma=10.0, m=5.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(sigma)) { args <- paste(args, paste0("--sigma=", sigma)) } if (!is.null(m)) { args <- paste(args, paste0("--m=", m)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "lee_sigma_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_line_detection_filter <- function(input, output, variant="vertical", absvals=FALSE, clip=0.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(variant)) { args <- paste(args, paste0("--variant=", variant)) } if (absvals) { args <- paste(args, "--absvals") } if (!is.null(clip)) { args <- paste(args, paste0("--clip=", clip)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "line_detection_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_majority_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "majority_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_maximum_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "maximum_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_mean_filter <- function(input, output, filterx=3, filtery=3, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "mean_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_median_filter <- function(input, output, filterx=11, filtery=11, sig_digits=2, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(sig_digits)) { args <- paste(args, paste0("--sig_digits=", sig_digits)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "median_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_minimum_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "minimum_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_olympic_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "olympic_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_percentile_filter <- function(input, output, filterx=11, filtery=11, sig_digits=2, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(sig_digits)) { args <- paste(args, paste0("--sig_digits=", sig_digits)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "percentile_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_prewitt_filter <- function(input, output, clip=0.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(clip)) { args <- paste(args, paste0("--clip=", clip)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "prewitt_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_range_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "range_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_roberts_cross_filter <- function(input, output, clip=0.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(clip)) { args <- paste(args, paste0("--clip=", clip)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "roberts_cross_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_scharr_filter <- function(input, output, clip=0.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(clip)) { args <- paste(args, paste0("--clip=", clip)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "scharr_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_sobel_filter <- function(input, output, variant="3x3", clip=0.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(variant)) { args <- paste(args, paste0("--variant=", variant)) } if (!is.null(clip)) { args <- paste(args, paste0("--clip=", clip)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "sobel_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_standard_deviation_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "standard_deviation_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_total_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(filterx)) { args <- paste(args, paste0("--filterx=", filterx)) } if (!is.null(filtery)) { args <- paste(args, paste0("--filtery=", filtery)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "total_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_unsharp_masking <- function(input, output, sigma=0.75, amount=100.0, threshold=0.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(sigma)) { args <- paste(args, paste0("--sigma=", sigma)) } if (!is.null(amount)) { args <- paste(args, paste0("--amount=", amount)) } if (!is.null(threshold)) { args <- paste(args, paste0("--threshold=", threshold)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "unsharp_masking" wbt_run_tool(tool_name, args, verbose_mode) } wbt_user_defined_weights_filter <- function(input, weights, output, center="center", normalize=FALSE, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--weights=", weights)) args <- paste(args, paste0("--output=", output)) if (!is.null(center)) { args <- paste(args, paste0("--center=", center)) } if (normalize) { args <- paste(args, "--normalize") } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "user_defined_weights_filter" wbt_run_tool(tool_name, args, verbose_mode) } wbt_balance_contrast_enhancement <- function(input, output, band_mean=100.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(band_mean)) { args <- paste(args, paste0("--band_mean=", band_mean)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "balance_contrast_enhancement" wbt_run_tool(tool_name, args, verbose_mode) } wbt_correct_vignetting <- function(input, pp, output, focal_length=304.8, image_width=228.6, n=4.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--pp=", pp)) args <- paste(args, paste0("--output=", output)) if (!is.null(focal_length)) { args <- paste(args, paste0("--focal_length=", focal_length)) } if (!is.null(image_width)) { args <- paste(args, paste0("--image_width=", image_width)) } if (!is.null(n)) { args <- paste(args, paste0("--n=", n)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "correct_vignetting" wbt_run_tool(tool_name, args, verbose_mode) } wbt_direct_decorrelation_stretch <- function(input, output, k=0.5, clip=1.0, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(k)) { args <- paste(args, paste0("--k=", k)) } if (!is.null(clip)) { args <- paste(args, paste0("--clip=", clip)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "direct_decorrelation_stretch" wbt_run_tool(tool_name, args, verbose_mode) } wbt_gamma_correction <- function(input, output, gamma=0.5, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(gamma)) { args <- paste(args, paste0("--gamma=", gamma)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "gamma_correction" wbt_run_tool(tool_name, args, verbose_mode) } wbt_gaussian_contrast_stretch <- function(input, output, num_tones=256, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(num_tones)) { args <- paste(args, paste0("--num_tones=", num_tones)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "gaussian_contrast_stretch" wbt_run_tool(tool_name, args, verbose_mode) } wbt_histogram_equalization <- function(input, output, num_tones=256, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(num_tones)) { args <- paste(args, paste0("--num_tones=", num_tones)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "histogram_equalization" wbt_run_tool(tool_name, args, verbose_mode) } wbt_histogram_matching <- function(input, histo_file, output, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--histo_file=", histo_file)) args <- paste(args, paste0("--output=", output)) if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "histogram_matching" wbt_run_tool(tool_name, args, verbose_mode) } wbt_histogram_matching_two_images <- function(input1, input2, output, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input1=", input1)) args <- paste(args, paste0("--input2=", input2)) args <- paste(args, paste0("--output=", output)) if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "histogram_matching_two_images" wbt_run_tool(tool_name, args, verbose_mode) } wbt_min_max_contrast_stretch <- function(input, output, min_val, max_val, num_tones=256, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) args <- paste(args, paste0("--min_val=", min_val)) args <- paste(args, paste0("--max_val=", max_val)) if (!is.null(num_tones)) { args <- paste(args, paste0("--num_tones=", num_tones)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "min_max_contrast_stretch" wbt_run_tool(tool_name, args, verbose_mode) } wbt_panchromatic_sharpening <- function(pan, output, red=NULL, green=NULL, blue=NULL, composite=NULL, method="brovey", wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--pan=", pan)) args <- paste(args, paste0("--output=", output)) if (!is.null(red)) { args <- paste(args, paste0("--red=", red)) } if (!is.null(green)) { args <- paste(args, paste0("--green=", green)) } if (!is.null(blue)) { args <- paste(args, paste0("--blue=", blue)) } if (!is.null(composite)) { args <- paste(args, paste0("--composite=", composite)) } if (!is.null(method)) { args <- paste(args, paste0("--method=", method)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "panchromatic_sharpening" wbt_run_tool(tool_name, args, verbose_mode) } wbt_percentage_contrast_stretch <- function(input, output, clip=1.0, tail="both", num_tones=256, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(clip)) { args <- paste(args, paste0("--clip=", clip)) } if (!is.null(tail)) { args <- paste(args, paste0("--tail=", tail)) } if (!is.null(num_tones)) { args <- paste(args, paste0("--num_tones=", num_tones)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "percentage_contrast_stretch" wbt_run_tool(tool_name, args, verbose_mode) } wbt_sigmoidal_contrast_stretch <- function(input, output, cutoff=0.0, gain=1.0, num_tones=256, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(cutoff)) { args <- paste(args, paste0("--cutoff=", cutoff)) } if (!is.null(gain)) { args <- paste(args, paste0("--gain=", gain)) } if (!is.null(num_tones)) { args <- paste(args, paste0("--num_tones=", num_tones)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "sigmoidal_contrast_stretch" wbt_run_tool(tool_name, args, verbose_mode) } wbt_standard_deviation_contrast_stretch <- function(input, output, stdev=2.0, num_tones=256, wd=NULL, verbose_mode=FALSE, compress_rasters=FALSE) { wbt_init() args <- "" args <- paste(args, paste0("--input=", input)) args <- paste(args, paste0("--output=", output)) if (!is.null(stdev)) { args <- paste(args, paste0("--stdev=", stdev)) } if (!is.null(num_tones)) { args <- paste(args, paste0("--num_tones=", num_tones)) } if (!is.null(wd)) { args <- paste(args, paste0("--wd=", wd)) } if (compress_rasters) { args <- paste(args, "--compress_rasters") } tool_name <- "standard_deviation_contrast_stretch" wbt_run_tool(tool_name, args, verbose_mode) }
div_adjust <- function(x, t, div, backward = TRUE, additive = FALSE) { if (!is.null(dim(x))) stop(sQuote("x"), " must be a vector") valid.t <- t > 1L & t <= length(x) if (all(!valid.t)) return(x) if (length(div) == 1L && length(t) > 1L) div <- rep(div, length(t)) else if (length(div) != length(t)) stop("different lengths for ", sQuote("div"), " and ", sQuote("t")) div <- div[valid.t] t <- t[valid.t] n <- length(x) if (anyDuplicated(t)) { div <- tapply(div, t, sum) t <- as.numeric(names(div)) } if (!additive) { rets1 <- c(1, x[-1L]/x[-n]) rets1[t] <- (x[t] + div)/x[t - 1L] new.series <- x[1L] * cumprod(rets1) if (backward) new.series <- new.series * x[n] / new.series[n] } else { dif <- c(0, x[-1L] - x[-n]) dif[t] <- dif[t] + div new.series <- x[1L] + cumsum(dif) if (backward) new.series <- new.series - new.series[n] + x[n] } new.series } split_adjust <- function(x, t, ratio, backward = TRUE) { if (!is.null(dim(x))) stop(sQuote("x"), " must be a vector") valid.t <- t > 1L & t <= length(x) if (all(!valid.t)) return(x) if (length(t) > 1L && length(ratio) == 1L) ratio <- rep(ratio, length(t)) ratio <- ratio[valid.t] t <- t[valid.t] if (length(ratio) != length(t)) stop("different lengths for ", sQuote("ratio"), " and ", sQuote("t")) new.series <- x for (i in seq_along(t)) { t1 <- seq_len(t[i] - 1L) new.series[t1] <- new.series[t1]/ratio[i] } if (!backward) new.series <- x[1L] * new.series/new.series[1L] new.series }
get_hyperparameter_defaults <- function(models = get_supported_models(), n = 100, k = 10, model_class = "classification") { defaults <- list( rf = tibble::tibble( mtry = floor(sqrt(k)), splitrule = "extratrees", min.node.size = if (model_class == "classification") 1L else 5L), xgb = tibble::tibble( eta = .3, gamma = 0, max_depth = 6, subsample = .7, colsample_bytree = .8, min_child_weight = 1, nrounds = 50 ), glm = tibble::tibble( alpha = 1, lambda = 2 ^ seq(-10, 3, len = 10) ) ) return(defaults[models]) } get_random_hyperparameters <- function(models = get_supported_models(), n = 100, k = 10, tune_depth = 5, model_class = "classification") { replace_ks <- k < tune_depth grids <- list() if ("rf" %in% models) { split_rules <- if (model_class == "classification" | model_class == "multiclass") { c("gini", "extratrees") } else { c("variance", "extratrees") } grids$rf <- tibble::tibble( mtry = sample(seq_len(k), tune_depth, TRUE, prob = 1 / seq_len(k)), splitrule = sample(split_rules, tune_depth, TRUE), min.node.size = sample(min(n, 20), tune_depth, TRUE) ) } if ("xgb" %in% models) { grids$xgb <- tibble::tibble( eta = runif(tune_depth, 0.001, .5), gamma = runif(tune_depth, 0, 10), max_depth = sample(10, tune_depth, replace = TRUE), subsample = runif(tune_depth, .35, 1), colsample_bytree = runif(tune_depth, .5, .9), min_child_weight = stats::rexp(tune_depth, .2), nrounds = sample(25:1000, tune_depth, prob = 1 / (25:1000)) ) } if ("glm" %in% models) { grids$glm <- expand.grid( alpha = c(0, 1), lambda = 2 ^ runif(tune_depth, -10, 3) ) %>% dplyr::arrange(alpha) %>% tibble::as_tibble() } return(grids) }
Id <- "$Id: bhpm.cluster.BB.hier3.lev1.convergence.R,v 1.11 2020/03/31 12:42:23 clb13102 Exp clb13102 $" bhpm.cluster.BB.dep.lev1.convergence.diag <- function(raw, debug_diagnostic = FALSE) { c_base = bhpm.cluster.1a.dep.lev1.convergence.diag(raw, debug_diagnostic) if (is.null(c_base)) { return(NULL) } monitor = raw$monitor theta_mon = monitor[monitor$variable == "theta",]$monitor pi_mon = monitor[monitor$variable == "pi",]$monitor alpha_pi_mon = monitor[monitor$variable == "alpha.pi",]$monitor beta_pi_mon = monitor[monitor$variable == "beta.pi",]$monitor theta.trt.grps <- raw$Trt.Grps[ raw$Trt.Grps$param == "theta", ]$Trt.Grp nchains = raw$chains if (alpha_pi_mon == 1 && !("alpha.pi" %in% names(raw))) { message("Missing alpha.pi data") return(NULL) } if (beta_pi_mon == 1 && !("beta.pi" %in% names(raw))) { message("Missing beta.pi data") return(NULL) } if (pi_mon == 1 && !("pi" %in% names(raw))) { message("Missing pi data") return(NULL) } if (raw$sim_type == "MH") { if (alpha_pi_mon == 1 && !("alpha.pi_acc" %in% names(raw))) { message("Missing beta.pi_acc data") return(NULL) } if (beta_pi_mon == 1 && !("beta.pi_acc" %in% names(raw))) { message("Missing beta.pi_acc data") return(NULL) } } else { if (theta_mon == 1 && !("theta_acc" %in% names(raw))) { message("Missing theta_acc data") return(NULL) } } pi_conv = data.frame(Trt.Grp = integer(0), Outcome.Grp = character(0), stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE) alpha.pi_conv = data.frame(Trt.Grp = integer(0), stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE) beta.pi_conv = data.frame(Trt.Grp = integer(0), stat = numeric(0), upper_ci = numeric(0), stringsAsFactors=FALSE) type <- NA if (nchains > 1) { type = "Gelman-Rubin" i = 1 if (pi_mon == 1) { for (b in 1:raw$nOutcome.Grp[i]) { for (t in 1:(raw$nTreatments - 1)) { g = M_global$GelmanRubin(raw$pi[, t, b, ], nchains) row <- data.frame(Trt.Grp = theta.trt.grps[t], Outcome.Grp = raw$Outcome.Grp[i, b], stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE) pi_conv = rbind(pi_conv, row) } } } if (alpha_pi_mon == 1) { for (t in 1:(raw$nTreatments - 1)) { g = M_global$GelmanRubin(raw$alpha.pi[,t,], nchains) row <- data.frame(Trt.Grp = theta.trt.grps[t], stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE) alpha.pi_conv = rbind(alpha.pi_conv, row) } } if (beta_pi_mon == 1) { for (t in 1:(raw$nTreatments - 1)) { g = M_global$GelmanRubin(raw$beta.pi[,t,], nchains) row <- data.frame(Trt.Grp = theta.trt.grps[t], stat = g$psrf[1], upper_ci = g$psrf[2], stringsAsFactors=FALSE) beta.pi_conv = rbind(beta.pi_conv, row) } } } else { type = "Geweke" i = 1 if (pi_mon == 1) { for (b in 1:raw$nOutcome.Grp[i]) { for (t in 1:(raw$nTreatments - 1)) { g = M_global$Geweke(raw$pi[1, t, b, ]) row <- data.frame(Trt.Grp = theta.trt.grps[t], Outcome.Grp = raw$Outcome.Grp[i, b], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE) pi_conv = rbind(pi_conv, row) } } } if (alpha_pi_mon == 1) { for (t in 1:(raw$nTreatments - 1)) { g = M_global$Geweke(raw$alpha.pi[1, t,]) row <- data.frame(Trt.Grp = theta.trt.grps[t], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE) alpha.pi_conv = rbind(alpha.pi_conv, row) } } if (beta_pi_mon == 1) { for (t in 1:(raw$nTreatments - 1)) { g = M_global$Geweke(raw$beta.pi[1, t,]) row <- data.frame(Trt.Grp = theta.trt.grps[t], stat = g$z, upper_ci = NA, stringsAsFactors=FALSE) beta.pi_conv = rbind(beta.pi_conv, row) } } } alpha.pi_acc <- data.frame(nchains = numeric(0), Trt.Grp = integer(0)) beta.pi_acc <- data.frame(nchains = numeric(0), Trt.Grp = integer(0)) theta_acc = data.frame(chain = numeric(0), Trt.Grp = integer(0), Cluster = character(0), Outcome.Grp = character(0), Outcome = character(0), rate = numeric(0), stringsAsFactors=FALSE) for (i in 1:raw$nClusters) { for (b in 1:raw$nOutcome.Grp[i]) { for (j in 1:raw$nOutcome[i, b]) { for (c in 1:nchains) { for (t in 1:(raw$nTreatments - 1)) { rate <- raw$theta_acc[c, t, i, b, j]/raw$iter row <- data.frame(chain = c, Trt.Grp = theta.trt.grps[t], Cluster = raw$Clusters[i], Outcome.Grp = raw$Outcome.Grp[i, b], Outcome = raw$Outcome[i, b,j], rate = rate, stringsAsFactors=FALSE) theta_acc = rbind(theta_acc, row) } } } } } if (raw$sim_type == "MH") { for (c in 1:nchains) { if (alpha_pi_mon == 1) { for (t in 1:(raw$nTreatments - 1)) { alpha.pi_acc[c, t] <- raw$alpha.pi_acc[c, t]/raw$iter } } if (beta_pi_mon == 1) { for (t in 1:(raw$nTreatments - 1)) { beta.pi_acc[c, t] <- raw$beta.pi_acc[c, t]/raw$iter } } } } rownames(theta_acc) <- NULL rownames(pi_conv) <- NULL rownames(alpha.pi_conv) <- NULL rownames(beta.pi_conv) <- NULL rownames(alpha.pi_acc) <- NULL rownames(beta.pi_acc) <- NULL c_base$theta_acc = theta_acc c_BB = list(pi.conv.diag = pi_conv, alpha.pi.conv.diag = alpha.pi_conv, beta.pi.conv.diag = beta.pi_conv, alpha.pi_acc = alpha.pi_acc, beta.pi_acc = beta.pi_acc) conv.diag = c(c_base, c_BB) attr(conv.diag, "model") = attr(raw, "model") return(conv.diag) } bhpm.cluster.BB.dep.lev1.print.convergence.summary <- function(conv) { if (is.null(conv)) { message("NULL conv data") return(NULL) } monitor = conv$monitor theta_mon = monitor[monitor$variable == "theta",]$monitor gamma_mon = monitor[monitor$variable == "gamma",]$monitor mu.theta_mon = monitor[monitor$variable == "mu.theta",]$monitor mu.gamma_mon = monitor[monitor$variable == "mu.gamma",]$monitor sigma2.theta_mon = monitor[monitor$variable == "sigma2.theta",]$monitor sigma2.gamma_mon = monitor[monitor$variable == "sigma2.gamma",]$monitor mu.theta.0_mon = monitor[monitor$variable == "mu.theta.0",]$monitor mu.gamma.0_mon = monitor[monitor$variable == "mu.gamma.0",]$monitor tau2.theta.0_mon = monitor[monitor$variable == "tau2.theta.0",]$monitor tau2.gamma.0_mon = monitor[monitor$variable == "tau2.gamma.0",]$monitor pi_mon = monitor[monitor$variable == "pi",]$monitor alpha_pi_mon = monitor[monitor$variable == "alpha.pi",]$monitor beta_pi_mon = monitor[monitor$variable == "beta.pi",]$monitor model = attr(conv, "model") if (is.null(model)) { message("Convergence model attribute missing") return(NULL) } if (gamma_mon == 1 && !("gamma.conv.diag" %in% names(conv))) { message("Missing gamma.conv.diag data") return(NULL) } if (theta_mon == 1 && !("theta.conv.diag" %in% names(conv))) { message("Missing theta.conv.diag data") return(NULL) } if (mu.gamma_mon == 1 && !("mu.gamma.conv.diag" %in% names(conv))) { message("Missing mu.gamma.conv.diag data") return(NULL) } if (mu.theta_mon == 1 && !("mu.theta.conv.diag" %in% names(conv))) { message("Missing mu.theta.conv.diag data") return(NULL) } if (sigma2.gamma_mon == 1 && !("sigma2.gamma.conv.diag" %in% names(conv))) { message("Missing sigma2.gamma.conv.diag data") return(NULL) } if (sigma2.theta_mon == 1 && !("sigma2.theta.conv.diag" %in% names(conv))) { message("Missing sigma2.theta.conv.diag data") return(NULL) } if (mu.gamma.0_mon == 1 && !("mu.gamma.0.conv.diag" %in% names(conv))) { message("Missing mu.gamma.0.conv.diag data") return(NULL) } if (mu.theta.0_mon == 1 && !("mu.theta.0.conv.diag" %in% names(conv))) { message("Missing mu.theta.0.conv.diag data") return(NULL) } if (tau2.gamma.0_mon == 1 && !("tau2.gamma.0.conv.diag" %in% names(conv))) { message("Missing tau2.gamma.0.conv.diag data") return(NULL) } if (tau2.theta.0_mon == 1 && !("tau2.theta.0.conv.diag" %in% names(conv))) { message("Missing tau2.theta.0.conv.diag data") return(NULL) } if (gamma_mon == 1 && !("gamma_acc" %in% names(conv))) { message("Missing gamma_acc data") return(NULL) } if (theta_mon == 1 && !("theta_acc" %in% names(conv))) { message("Missing theta_acc data") return(NULL) } if (pi_mon == 1 && !("pi.conv.diag" %in% names(conv))) { message("Missing pi.conv.diag data") return(NULL) } if (alpha_pi_mon == 1 && !("alpha.pi.conv.diag" %in% names(conv))) { message("Missing alpha.pi.conv.diag data") return(NULL) } if (beta_pi_mon == 1 && !("beta.pi.conv.diag" %in% names(conv))) { message("Missing beta.pi.conv.diag data") return(NULL) } if (alpha_pi_mon == 1 && !("alpha.pi_acc" %in% names(conv))) { message("Missing alpha.pi_acc data") return(NULL) } if (beta_pi_mon == 1 && !("beta.pi_acc" %in% names(conv))) { message("Missing beta.pi_acc data") return(NULL) } cat(sprintf("Summary Convergence Diagnostics:\n")) cat(sprintf("================================\n")) if (conv$type == "Gelman-Rubin") { if (theta_mon == 1) { cat(sprintf("theta:\n")) cat(sprintf("------\n")) max_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == max(conv$theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%d %s %s %s): %0.6f\n", max_t$Trt.Grp, max_t$Cluster, max_t$Outcome.Grp, max_t$Outcome, max_t$stat)) min_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == min(conv$theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%d %s, %s %s): %0.6f\n", min_t$Trt.Grp, min_t$Cluster, min_t$Outcome.Grp, min_t$Outcome, min_t$stat)) } if (gamma_mon == 1) { cat(sprintf("gamma:\n")) cat(sprintf("------\n")) max_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == max(conv$gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%s %s %s): %0.6f\n", max_t$Cluster, max_t$Outcome.Grp, max_t$Outcome, max_t$stat)) min_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == min(conv$gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%s %s %s): %0.6f\n", min_t$Cluster, min_t$Outcome.Grp, min_t$Outcome, min_t$stat)) } if (mu.gamma_mon == 1) { cat(sprintf("mu.gamma:\n")) cat(sprintf("---------\n")) max_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat == max(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%s): %0.6f\n", max_t$Outcome.Grp, max_t$stat)) min_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat == min(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%s): %0.6f\n", min_t$Outcome.Grp, min_t$stat)) } if (mu.theta_mon == 1) { cat(sprintf("mu.theta:\n")) cat(sprintf("---------\n")) max_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat == max(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%d %s): %0.6f\n", max_t$Trt.Grp, max_t$Outcome.Grp, max_t$stat)) min_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat == min(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%d %s): %0.6f\n", min_t$Trt.Grp, min_t$Outcome.Grp, min_t$stat)) } if (sigma2.gamma_mon == 1) { cat(sprintf("sigma2.gamma:\n")) cat(sprintf("-------------\n")) max_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat == max(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%s): %0.6f\n", max_t$Outcome.Grp, max_t$stat)) min_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat == min(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%s): %0.6f\n", min_t$Outcome.Grp, min_t$stat)) } if (sigma2.theta_mon == 1) { cat(sprintf("sigma2.theta:\n")) cat(sprintf("-------------\n")) max_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat == max(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%d %s): %0.6f\n", max_t$Trt.Grp, max_t$Outcome.Grp, max_t$stat)) min_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat == min(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%d %s): %0.6f\n", min_t$Trt.Grp, min_t$Outcome.Grp, min_t$stat)) } if (pi_mon == 1) { cat(sprintf("pi:\n")) cat(sprintf("---\n")) max_t = head(conv$pi.conv.diag[conv$pi.conv.diag$stat == max(conv$pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Gelman-Rubin diagnostic (%d %s): %0.6f\n", max_t$Trt.Grp, max_t$Outcome.Grp, max_t$stat)) min_t = head(conv$pi.conv.diag[conv$pi.conv.diag$stat == min(conv$pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Gelman-Rubin diagnostic (%d %s): %0.6f\n", min_t$Trt.Grp, min_t$Outcome.Grp, min_t$stat)) } if (mu.gamma.0_mon == 1) { cat(sprintf("mu.gamma.0:\n")) cat(sprintf("-----------\n")) max_t = head(conv$mu.gamma.0.conv.diag[conv$mu.gamma.0.conv.diag$stat == max(conv$mu.gamma.0.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: %0.6f\n", max_t$stat)) min_t = head(conv$mu.gamma.0.conv.diag[conv$mu.gamma.0.conv.diag$stat == min(conv$mu.gamma.0.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: %0.6f\n", min_t$stat)) } if (mu.theta.0_mon == 1) { cat(sprintf("mu.theta.0:\n")) cat(sprintf("-----------\n")) max_t = head(conv$mu.theta.0.conv.diag[conv$mu.theta.0.conv.diag$stat == max(conv$mu.theta.0.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: %d %0.6f\n", max_t$Trt.Grp, max_t$stat)) min_t = head(conv$mu.theta.0.conv.diag[conv$mu.theta.0.conv.diag$stat == min(conv$mu.theta.0.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: %d %0.6f\n", min_t$Trt.Grp, min_t$stat)) } if (tau2.gamma.0_mon == 1) { cat(sprintf("tau2.gamma.0:\n")) cat(sprintf("-------------\n")) max_t = head(conv$tau2.gamma.0.conv.diag[conv$tau2.gamma.0.conv.diag$stat == max(conv$tau2.gamma.0.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: %0.6f\n", max_t$stat)) min_t = head(conv$tau2.gamma.0.conv.diag[conv$tau2.gamma.0.conv.diag$stat == min(conv$tau2.gamma.0.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: %0.6f\n", min_t$stat)) } if (tau2.theta.0_mon == 1) { cat(sprintf("tau2.theta.0:\n")) cat(sprintf("-------------\n")) max_t = head(conv$tau2.theta.0.conv.diag[conv$tau2.theta.0.conv.diag$stat == max(conv$tau2.theta.0.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: %d %0.6f\n", max_t$Trt.Grp, max_t$stat)) min_t = head(conv$tau2.theta.0.conv.diag[conv$tau2.theta.0.conv.diag$stat == min(conv$tau2.theta.0.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: %d %0.6f\n", min_t$Trt.Grp, min_t$stat)) } if (alpha_pi_mon == 1) { cat(sprintf("alpha.pi:\n")) cat(sprintf("----------\n")) max_t = head(conv$alpha.pi.conv.diag[conv$alpha.pi.conv.diag$stat == max(conv$alpha.pi.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: %d %0.6f\n", max_t$Trt.Grp, max_t$stat)) min_t = head(conv$alpha.pi.conv.diag[conv$alpha.pi.conv.diag$stat == min(conv$alpha.pi.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: %d %0.6f\n", min_t$Trt.Grp, min_t$stat)) } if (beta_pi_mon == 1) { cat(sprintf("beta.pi:\n")) cat(sprintf("--------\n")) max_t = head(conv$beta.pi.conv.diag[conv$beta.pi.conv.diag$stat == max(conv$beta.pi.conv.diag$stat), ], 1) cat(sprintf("Max Gelman-Rubin diagnostic: %d %0.6f\n", max_t$Trt.Grp, max_t$stat)) min_t = head(conv$beta.pi.conv.diag[conv$beta.pi.conv.diag$stat == min(conv$beta.pi.conv.diag$stat), ], 1) cat(sprintf("Min Gelman-Rubin diagnostic: %d %0.6f\n", min_t$Trt.Grp, min_t$stat)) } } else { if (theta_mon == 1) { cat(sprintf("theta:\n")) cat(sprintf("------\n")) max_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == max(conv$theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%d %s %s %s): %0.6f (%s)\n", max_t$Trt.Grp, max_t$Cluster, max_t$Outcome.Grp, max_t$Outcome, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$theta.conv.diag[conv$theta.conv.diag$stat == min(conv$theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%d %s %s %s): %0.6f (%s)\n", min_t$Trt.Grp, min_t$Cluster, min_t$Outcome.Grp, min_t$Outcome, min_t$stat, chk_val(min_t$stat))) } if (gamma_mon == 1) { cat(sprintf("gamma:\n")) cat(sprintf("------\n")) max_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == max(conv$gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%s %s %s): %0.6f (%s)\n", max_t$Cluster, max_t$Outcome.Grp, max_t$Outcome, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$gamma.conv.diag[conv$gamma.conv.diag$stat == min(conv$gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%s %s %s): %0.6f (%s)\n", min_t$Cluster, min_t$Outcome.Grp, min_t$Outcome, min_t$stat, chk_val(min_t$stat))) } if (mu.gamma_mon == 1) { cat(sprintf("mu.gamma:\n")) cat(sprintf("---------\n")) max_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat == max(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%s): %0.6f (%s)\n", max_t$Outcome.Grp, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$mu.gamma.conv.diag[conv$mu.gamma.conv.diag$stat == min(conv$mu.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%s): %0.6f (%s)\n", min_t$Outcome.Grp, min_t$stat, chk_val(min_t$stat))) } if (mu.theta_mon == 1) { cat(sprintf("mu.theta:\n")) cat(sprintf("---------\n")) max_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat == max(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%d %s): %0.6f (%s)\n", max_t$Trt.Grp, max_t$Outcome.Grp, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$mu.theta.conv.diag[conv$mu.theta.conv.diag$stat == min(conv$mu.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%d %s): %0.6f (%s)\n", min_t$Trt.Grp, min_t$Outcome.Grp, min_t$stat, chk_val(min_t$stat))) } if (sigma2.gamma_mon == 1) { cat(sprintf("sigma2.gamma:\n")) cat(sprintf("-------------\n")) max_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat == max(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%s): %0.6f (%s)\n", max_t$Outcome.Grp, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$sigma2.gamma.conv.diag[conv$sigma2.gamma.conv.diag$stat == min(conv$sigma2.gamma.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%s): %0.6f (%s)\n", min_t$Outcome.Grp, min_t$stat, chk_val(min_t$stat))) } if (sigma2.theta_mon == 1) { cat(sprintf("sigma2.theta:\n")) cat(sprintf("-------------\n")) max_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat == max(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%d %s): %0.6f (%s)\n", max_t$Trt.Grp, max_t$Outcome.Grp, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$sigma2.theta.conv.diag[conv$sigma2.theta.conv.diag$stat == min(conv$sigma2.theta.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%d %s): %0.6f (%s)\n", min_t$Trt.Grp, min_t$Outcome.Grp, min_t$stat, chk_val(min_t$stat))) } if (pi_mon == 1) { cat(sprintf("pi:\n")) cat(sprintf("---\n")) max_t = head(conv$pi.conv.diag[conv$pi.conv.diag$stat == max(conv$pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic (%d %s): %0.6f (%s)\n", max_t$Trt.Grp, max_t$Outcome.Grp, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$pi.conv.diag[conv$pi.conv.diag$stat == min(conv$pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic (%d %s): %0.6f (%s)\n", min_t$Trt.Grp, min_t$Outcome.Grp, min_t$stat, chk_val(min_t$stat))) } if (mu.gamma.0_mon == 1) { cat(sprintf("mu.gamma.0:\n")) cat(sprintf("-----------\n")) max_t = head(conv$mu.gamma.0.conv.diag[conv$mu.gamma.0.conv.diag$stat == max(conv$mu.gamma.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: %0.6f (%s)\n", max_t$stat, chk_val(max_t$stat))) min_t = head(conv$mu.gamma.0.conv.diag[conv$mu.gamma.0.conv.diag$stat == min(conv$mu.gamma.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: %0.6f (%s)\n", min_t$stat, chk_val(min_t$stat))) } if (mu.theta.0_mon == 1) { cat(sprintf("mu.theta.0:\n")) cat(sprintf("-----------\n")) max_t = head(conv$mu.theta.0.conv.diag[conv$mu.theta.0.conv.diag$stat == max(conv$mu.theta.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: %d %0.6f (%s)\n", max_t$Trt.Grp, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$mu.theta.0.conv.diag[conv$mu.theta.0.conv.diag$stat == min(conv$mu.theta.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: %d %0.6f (%s)\n", min_t$Trt.Grp, min_t$stat, chk_val(min_t$stat))) } if (tau2.gamma.0_mon == 1) { cat(sprintf("tau2.gamma.0:\n")) cat(sprintf("-------------\n")) max_t = head(conv$tau2.gamma.0.conv.diag[conv$tau2.gamma.0.conv.diag$stat == max(conv$tau2.gamma.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: %0.6f (%s)\n", max_t$stat, chk_val(max_t$stat))) min_t = head(conv$tau2.gamma.0.conv.diag[conv$tau2.gamma.0.conv.diag$stat == min(conv$tau2.gamma.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: %0.6f (%s)\n", min_t$stat, chk_val(min_t$stat))) } if (tau2.theta.0_mon == 1) { cat(sprintf("tau2.theta.0:\n")) cat(sprintf("-------------\n")) max_t = head(conv$tau2.theta.0.conv.diag[conv$tau2.theta.0.conv.diag$stat == max(conv$tau2.theta.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: %d %0.6f (%s)\n", max_t$Trt.Grp, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$tau2.theta.0.conv.diag[conv$tau2.theta.0.conv.diag$stat == min(conv$tau2.theta.0.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: %d %0.6f (%s)\n", min_t$Trt.Grp, min_t$stat, chk_val(min_t$stat))) } if (alpha_pi_mon == 1) { cat(sprintf("alpha.pi:\n")) cat(sprintf("----------\n")) max_t = head(conv$alpha.pi.conv.diag[conv$alpha.pi.conv.diag$stat == max(conv$alpha.pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: %d %0.6f (%s)\n", max_t$Trt.Grp, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$alpha.pi.conv.diag[conv$alpha.pi.conv.diag$stat == min(conv$alpha.pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: %d %0.6f (%s)\n", min_t$Trt.Grp, min_t$stat, chk_val(min_t$stat))) } if (beta_pi_mon == 1) { cat(sprintf("beta.pi:\n")) cat(sprintf("----------\n")) max_t = head(conv$beta.pi.conv.diag[conv$beta.pi.conv.diag$stat == max(conv$beta.pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Max Geweke statistic: %d %0.6f (%s)\n", max_t$Trt.Grp, max_t$stat, chk_val(max_t$stat))) min_t = head(conv$beta.pi.conv.diag[conv$beta.pi.conv.diag$stat == min(conv$beta.pi.conv.diag$stat),, drop = FALSE], 1) cat(sprintf("Min Geweke statistic: %d %0.6f (%s)\n", min_t$Trt.Grp, min_t$stat, chk_val(min_t$stat))) } } if (conv$sim_type == "MH") { cat("\nSampling Acceptance Rates:\n") cat("==========================\n") if (theta_mon == 1) { cat("theta:\n") cat("------\n") print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$theta_acc$rate), max(conv$theta_acc$rate))) } if (gamma_mon == 1) { cat("gamma:\n") cat("------\n") print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$gamma_acc$rate), max(conv$gamma_acc$rate))) } if (alpha_pi_mon == 1) { cat("alpha.pi:\n") cat("---------\n") print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$alpha.pi_acc$rate), max(conv$alpha.pi_acc$rate))) } if (beta_pi_mon == 1) { cat("beta.pi:\n") cat("--------\n") print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$beta.pi_acc$rate), max(conv$beta.pi_acc$rate))) } } else { cat("\nSampling Acceptance Rates:\n") cat("==========================\n") if (theta_mon == 1) { cat("theta:\n") cat("------\n") print(sprintf("Min: %0.6f, Max: %0.6f", min(conv$theta_acc$rate), max(conv$theta_acc$rate))) } } }
avgFDR.p.adjust <- function(pval, t, make.decision=FALSE){ adjcondP <- vector("list", length(pval)) adj.pval <- lapply(pval, FUN = p.adjust, method="BH") for (i in which(p.adjust(sapply(adj.pval,min),method="BH")<=t) ){ adjcondP[[i]] <- p.adjust(pval[[i]], method = "BH") } if (make.decision==FALSE){return(adjcondP)} else if(make.decision==TRUE){ sig.level=sum(p.adjust(sapply(adj.pval,min),method="BH")<=t)/length(pval)*t f <- function(x){ifelse(x<=sig.level,"reject","not reject")} return(list(adjust.p = adjcondP,adjust.sig.level=sig.level,dec.make=lapply(adjcondP, f))) } }
to_mhcnuggets_names <- function(mhcs) { if (length(mhcs) == 0) { stop("'mhcs' must have at least one value") } mhcnuggets_names <- rep(NA, length(mhcs)) for (i in seq_along(mhcnuggets_names)) { mhcnuggets_names[i] <- mhcnuggetsr::to_mhcnuggets_name(mhcs[i]) } mhcnuggets_names }
NULL new_bigfloat <- function(x = character(), cxx = TRUE) { vec_assert(x, character()) if (cxx) { c_bigfloat(x) } else { new_vctr(x, class = c("bignum_bigfloat", "bignum_vctr")) } } bigfloat <- function(x = character()) { as_bigfloat(x) } as_bigfloat <- function(x) { UseMethod("as_bigfloat") } is_bigfloat <- function(x) { inherits(x, "bignum_bigfloat") } vec_ptype_full.bignum_bigfloat <- function(x, ...) { "bigfloat" } vec_ptype_abbr.bignum_bigfloat <- function(x, ...) { "bigflt" } vec_ptype2.bignum_bigfloat.bignum_bigfloat <- function(x, y, ...) x vec_ptype2.bignum_bigfloat.logical <- function(x, y, ...) x vec_ptype2.logical.bignum_bigfloat <- function(x, y, ...) y vec_ptype2.bignum_bigfloat.integer <- function(x, y, ...) x vec_ptype2.integer.bignum_bigfloat <- function(x, y, ...) y vec_ptype2.bignum_bigfloat.double <- function(x, y, ...) x vec_ptype2.double.bignum_bigfloat <- function(x, y, ...) y vec_ptype2.bignum_bigfloat.bignum_biginteger <- function(x, y, ...) x vec_ptype2.bignum_biginteger.bignum_bigfloat <- function(x, y, ...) y vec_cast.bignum_bigfloat.bignum_bigfloat <- function(x, to, ...) { x } vec_cast.bignum_bigfloat.logical <- function(x, to, ...) { new_bigfloat(as.character(as.integer(x))) } vec_cast.logical.bignum_bigfloat <- function(x, to, ..., x_arg = "", to_arg = "") { out <- c_bigfloat_to_logical(x) lossy <- !vec_in(x, vec_c(0, 1, NA_bigfloat_, NaN)) maybe_lossy_cast(out, x, to, lossy, x_arg = x_arg, to_arg = to_arg) } vec_cast.bignum_bigfloat.integer <- function(x, to, ...) { new_bigfloat(as.character(x)) } vec_cast.integer.bignum_bigfloat <- function(x, to, ..., x_arg = "", to_arg = "") { out <- c_bigfloat_to_integer(x) lossy <- xor(is.na(x), is.na(out)) maybe_lossy_cast(out, x, to, lossy, x_arg = x_arg, to_arg = to_arg) } vec_cast.bignum_bigfloat.double <- function(x, to, ...) { new_bigfloat(as.character(x)) } vec_cast.double.bignum_bigfloat <- function(x, to, ..., x_arg = "", to_arg = "") { out <- c_bigfloat_to_double(x) x_loopback <- vec_cast(out, new_bigfloat()) x_na <- is.na(x) lossy <- (x_loopback != x & !x_na) | xor(x_na, is.na(x_loopback)) maybe_lossy_cast(out, x, to, lossy, x_arg = x_arg, to_arg = to_arg) } vec_cast.bignum_bigfloat.bignum_biginteger <- function(x, to, ..., x_arg = "", to_arg = "") { out <- new_bigfloat(vec_data(x)) x_loopback <- vec_cast(out, new_biginteger()) x_na <- is.na(x) lossy <- (x_loopback != x & !x_na) | xor(x_na, is.na(x_loopback)) maybe_lossy_cast(out, x, to, lossy, x_arg = x_arg, to_arg = to_arg) } vec_cast.bignum_bigfloat.character <- function(x, to, ..., x_arg = "", to_arg = "") { stop_incompatible_cast(x, to, x_arg = x_arg, to_arg = to_arg) } vec_cast.character.bignum_bigfloat <- function(x, to, ..., x_arg = "", to_arg = "") { stop_incompatible_cast(x, to, x_arg = x_arg, to_arg = to_arg) } as.logical.bignum_bigfloat <- function(x, ...) { warn_on_lossy_cast(vec_cast(x, logical())) } as.integer.bignum_bigfloat <- function(x, ...) { warn_on_lossy_cast(vec_cast(x, integer())) } as.double.bignum_bigfloat <- function(x, ...) { warn_on_lossy_cast(vec_cast(x, double())) } as.character.bignum_bigfloat <- function(x, ...) { format(x) } as_bigfloat.default <- function(x) { warn_on_lossy_cast(vec_cast(x, new_bigfloat())) } as_bigfloat.character <- function(x) { new_bigfloat(x) } is.na.bignum_bigfloat <- function(x) { is.na(c_bigfloat_to_double(x)) }
library(testthat) source("utils.R") invoke_test <- function(fun, expected_res, ...) { res <- seqR::count_kmers(hash_dim=2, verbose=FALSE, ...) expect_matrices_equal(expected_res, as.matrix(res)) } test_that("(string list) test one sequence with kmer_gaps (1) not positional", { invoke_test(expected_res=to_matrix(c("a.a_1"=3, "b.b_1"=1, "a.b_1"=1)), kmer_alphabet=c("a", "b"), sequences=list(c("a", "a", "a", "b", "a", "b", "a")), kmer_gaps=c(1), positional=FALSE, with_kmer_counts=TRUE) }) test_that("(string list) test one sequence with kmer_gaps (1) positional", { invoke_test(expected_res=to_matrix(c("1_a.a_1"=1, "2_a.b_1"=1, "3_a.a_1"=1, "4_b.b_1"=1, "5_a.a_1"=1)), kmer_alphabet=c("a", "b"), sequences=list(c("a", "a", "a", "b", "a", "b", "a")), kmer_gaps=c(1), positional=TRUE, with_kmer_counts=TRUE) }) test_that("(string list) test one sequence with gapps (1,0) not positional", { invoke_test(expected_res=to_matrix(c("b.b.a_1.0"=1, "a.a.b_1.0"=2, "a.b.a_1.0"=1)), kmer_alphabet=c("a", "b"), sequences=list(c("a", "a", "a", "b", "a", "b", "a")), kmer_gaps=c(1, 0), positional=FALSE, with_kmer_counts=TRUE) }) test_that("(string list) test one sequence with gapps (1,0) not positional, alphabet all", { invoke_test(expected_res=to_matrix(c("b.b.a_1.0"=1, "a.a.b_1.0"=2, "a.b.a_1.0"=1)), kmer_alphabet="all", sequences=list(c("a", "a", "a", "b", "a", "b", "a")), kmer_gaps=c(1, 0), positional=FALSE, with_kmer_counts=TRUE) }) test_that("(string list) test 2 sequences with kmer_gaps (1,1) positional; some items are not from alphabet", { sequences <- list( c("a", "b", "c", "c", "as", "b", "c", "a", "a", "b", "a"), c("b", "b", "c", "c", "a", "a", "b", "c", "a", "b", "a")) expectedRes <- matrix(c( 1, 0, 0, 0, 1, 1 ), nrow=2, byrow=TRUE) colnames(expectedRes) <- c("6_b.a.b_1.1", "7_b.a.a_1.1", "5_a.b.a_1.1") invoke_test(expected_res=expectedRes, kmer_alphabet=c("a", "b"), sequences=sequences, kmer_gaps=c(1,1), positional=TRUE, with_kmer_counts=TRUE) }) test_that("(string list) the k-mer is longer than a sequence", { sequences <- list( c("a", "b", "a", "b", "a", "b", "a", "b", "a"), c("a", "b", "a", "a", "a", "a", "b", "a", "a")) expectedRes <- matrix(nrow=2, ncol=0) invoke_test(expected_res=expectedRes, kmer_alphabet=c("a", "b"), sequences=sequences, kmer_gaps=rep(1, 10000), positional=FALSE, with_kmer_counts=TRUE) }) test_that("(string vector) count non positional k-mers (0, 1)", { sequences <- c("AAAAAC", "AAA", "AAAC") expected_res <- matrix(c( 2, 1, 0, 0, 0, 1), nrow = 3, byrow=TRUE) colnames(expected_res) <- c("A.A.A_0.1", "A.A.C_0.1") invoke_test(expected_res = expected_res, kmer_alphabet=c("A", "C"), sequences = sequences, kmer_gaps = c(0,1), positional = FALSE, with_kmer_counts=TRUE) }) test_that("(string vector) count non positional k-mers (0, 1), alphabet all", { sequences <- c("AAAAAC", "AAA", "AAAC") expected_res <- matrix(c( 2, 1, 0, 0, 0, 1), nrow = 3, byrow=TRUE) colnames(expected_res) <- c("A.A.A_0.1", "A.A.C_0.1") invoke_test(expected_res = expected_res, kmer_alphabet="all", sequences = sequences, kmer_gaps = c(0,1), positional = FALSE, with_kmer_counts=TRUE) }) test_that("(string vector) count non positional k-mers (0, 1); some items are not allowed", { sequences <- c("AAAACAAAAC", "AACTAAAA", "AACTAAAAC") expected_res <- matrix(c( 3, 0, 0, 1, 1, 1, 1, 1, 1 ), nrow = 3, byrow=TRUE) colnames(expected_res) <- c("A.A.A_0.1", "A.A.T_0.1", "T.A.A_0.1") invoke_test(expected_res = expected_res, kmer_alphabet=c("A", "T"), sequences = sequences, kmer_gaps = c(0, 1), positional = FALSE, with_kmer_counts=TRUE) }) test_that("(string vector) the k-mer is longer than the sequence", { sequences <- c("AAAACAAAAC", "AACTAAAA", "AACTAAAAC") expected_res <- matrix(nrow=3, ncol=0) invoke_test(expected_res = expected_res, kmer_alphabet=c("A", "T"), sequences = sequences, kmer_gaps = rep(1,100), positional = FALSE, with_kmer_counts=TRUE) })
all_bills <- function(id = NULL, ordinance = NULL, title = NULL, proposer = NULL, gazette_from = 'all', gazette_to = 'all', first_from = 'all', first_to = 'all', second_from = 'all', second_to = 'all', third_from = 'all', third_to = 'all', n = 10000, extra_param = NULL, count = FALSE, verbose = TRUE) { query <- "Vbills?" filter_args <- {} if (!is.null(id)) { filter_args <- c(filter_args, .generate_filter("internal_key", id)) } if (!is.null(ordinance)) { ordinance <-.capitalise(ordinance) filter_args <- c(filter_args, paste0("ordinance_title_eng eq '", ordinance, "'")) } if (!is.null(title)) { title <-.capitalise(title) filter_args <- c(filter_args, paste0("bill_title_eng eq '", title, "'")) } if (!is.null(proposer)) { proposer <-.capitalise(proposer) filter_args <- c(filter_args, paste0("proposed_by_eng eq '", proposer, "'")) } if (is.null(gazette_from) | is.null(gazette_to)) { filter_args <- c(filter_args, "bill_gazette_date eq null") } else if (gazette_from != "all" & gazette_to != "all") { gazette_from <- as.Date(gazette_from) gazette_to <- as.Date(gazette_to) filter_args <- c(filter_args, paste0("bill_gazette_date ge datetime\'", gazette_from, "\' and bill_gazette_date le datetime\'", gazette_to, "\'")) } else if (gazette_from != "all") { gazette_from <- as.Date(gazette_from) filter_args <- c(filter_args, paste0("bill_gazette_date ge datetime\'", gazette_from, "\'")) } else if (gazette_to != "all") { gazette_to <- as.Date(gazette_to) filter_args <- c(filter_args, paste0("bill_gazette_date le datetime\'", gazette_to, "\'")) } if (is.null(first_from) | is.null(first_to)) { filter_args <- c(filter_args, "first_reading_date eq null") } else if (first_from != "all" & first_to != "all") { first_from <- as.Date(first_from) first_to <- as.Date(first_to) filter_args <- c(filter_args, paste0("first_reading_date ge datetime\'", first_from, "\' and first_reading_date le datetime\'", first_to, "\'")) } else if (first_from != "all") { first_from <- as.Date(first_from) filter_args <- c(filter_args, paste0("first_reading_date ge datetime\'", first_from, "\'")) } else if (first_to != "all") { first_to <- as.Date(first_to) filter_args <- c(filter_args, paste0("first_reading_date le datetime\'", first_to, "\'")) } if (is.null(second_from) | is.null(second_to)) { filter_args <- c(filter_args, "second_reading_date eq null") } else if (second_from != "all" & second_to != "all") { second_from <- as.Date(second_from) second_to <- as.Date(second_to) filter_args <- c(filter_args, paste0("second_reading_date ge datetime\'", second_from, "\' and second_reading_date le datetime\'", second_to, "\'")) } else if (second_from != "all") { second_from <- as.Date(second_from) filter_args <- c(filter_args, paste0("second_reading_date ge datetime\'", second_from, "\'")) } else if (second_to != "all") { second_to <- as.Date(second_to) filter_args <- c(filter_args, paste0("second_reading_date le datetime\'", second_to, "\'")) } if (is.null(third_from) | is.null(third_to)) { filter_args <- c(filter_args, "third_reading_date eq null") } else if (third_from != "all" & third_to != "all") { third_from <- as.Date(third_from) third_to <- as.Date(third_to) filter_args <- c(filter_args, paste0("third_reading_date ge datetime\'", third_from, "\' and third_reading_date le datetime\'", third_to, "\'")) } else if (third_from != "all") { third_from <- as.Date(third_from) filter_args <- c(filter_args, paste0("third_reading_date ge datetime\'", third_from, "\'")) } else if (third_to != "all") { third_to <- as.Date(third_to) filter_args <- c(filter_args, paste0("third_reading_date le datetime\'", third_to, "\'")) } if (!is.null(filter_args)) { query <- paste0(query, "$filter=", paste(filter_args, collapse = " and ")) } if (!is.null(extra_param)) { query <- paste0(query, extra_param) } df <- legco_api("bill", query, n, count, verbose) if (!count) { colnames(df) <-.unify_colnames(colnames(df)) } df } legco_all_bills <- all_bills
NMADBURL = "https://redcap.ispm.unibe.ch/api/" PUBLICTOKEN = "4A32EEA60CC5410145152BC48BDC73C1"
expected <- structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c("13", "14", "15", "16", "17"), class = "factor") test(id=0, code={ argv <- structure(list(.Data = structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c("13", "14", "15", "16", "17"), class = "factor"), .Label = c("13", "14", "15", "16", "17"), class = "factor"), .Names = c(".Data", ".Label", "class")) do.call('structure', argv); }, o = expected);
boltDimensions = function(dlog, runQuiet = FALSE) { require(sampSurf) if(!is(dlog, 'downLog')) stop('must pass a downLog argument!') taper = dlog@taper nTaper = nrow(taper) buttDiam = dlog@buttDiam topDiam = dlog@topDiam logLen = dlog@logLen solidType = dlog@solidType nSegs = nTaper - 1 boltDim = matrix(NA, nrow=nSegs, ncol=5) boltDim[, 1] = taper[1:nSegs, 'diameter'] boltDim[, 2] = taper[2:nTaper, 'diameter'] boltDim[, 3] = taper[1:nSegs, 'length'] boltDim[, 4] = taper[2:nTaper, 'length'] boltDim[, 5] = diff(taper$length) vol = matrix(NA, nrow=nSegs, ncol=1) biomass = vol carbon = vol if(!is.null(solidType)) for(i in seq_len(nSegs)) vol[i, 1] = .StemEnv$wbVolume(buttDiam, topDiam, logLen, solidType, boltDim[i,4]) - .StemEnv$wbVolume(buttDiam, topDiam, logLen, solidType, boltDim[i,3]) else vol[, 1] = .StemEnv$SmalianVolume(taper)$boltVol if(!is.na(dlog@biomass)) biomass[, 1] = vol[,1]*dlog@conversions['volumeToWeight'] if(!is.na(dlog@carbon)) carbon[, 1] = biomass[,1]*dlog@conversions['weightToCarbon'] sa = matrix(NA, nrow=nSegs, ncol=1) for(i in seq_len(nSegs)) { if(!is.null(solidType)) sa[i, 1] = .StemEnv$wbSurfaceArea(buttDiam, topDiam, logLen, solidType, boltDim[i,3], boltDim[i,4] ) else sa[i, 1] = .StemEnv$splineSurfaceArea(taper, boltDim[i,3], boltDim[i,4] ) } ca = matrix(NA, nrow=nSegs, ncol=1) for(i in seq_len(nSegs)) { if(!is.null(solidType)) ca[i, 1] = .StemEnv$wbCoverageArea(buttDiam, topDiam, logLen, solidType, boltDim[i,3], boltDim[i,4] ) else ca[i, 1] = .StemEnv$splineCoverageArea(taper, boltDim[i,3], boltDim[i,4] ) } df = data.frame(boltDim, vol, sa, ca, biomass, carbon) colnames(df) = c('botDiam', 'topDiam', 'botLen', 'topLen', 'boltLen', .StemEnv$puaEstimates[c('volume', 'surfaceArea', 'coverageArea', 'biomass', 'carbon')]) if(!runQuiet) { sums = colSums(df) if(dlog@units == 'metric') { lu = 'meters' cu = 'cubic meters' su = 'square meters' } else { lu = 'feet' cu = 'cubic feet' su = 'square feet' } if(is.null(solidType)) { fromArea = '(from spline fit)' fromVol = "(from Smalian's)" } else { fromArea = '(from taper equation)' fromVol = fromArea } cat('\nSummary of bolts in taper data frame...') .StemEnv$underLine(40,postfix='') cat('\n Units =', dlog@units) cat('\n Number of segments =', nSegs) cat('\n Solid type =', ifelse(is.null(solidType), 'NULL', solidType)) cat('\n Total Length =', sums['boltLen'], lu) cat('\n Total volume =', sums['volume'], cu, fromVol) cat('\n Total biomass =', sums['biomass']) cat('\n Total carbon =', sums['carbon']) cat('\n Total surface area =', sums['surfaceArea'], su, fromArea) cat('\n Total coverge area =', sums['coverageArea'], su, fromArea) cat('\n') } return(invisible(df)) }
as.ckan_user <- function(x, ...) UseMethod("as.ckan_user") as.ckan_user.character <- function(x, ...) get_user(x, ...) as.ckan_user.ckan_user <- function(x, ...) x as.ckan_user.list <- function(x, ...) structure(x, class = "ckan_user") is.ckan_user <- function(x) inherits(x, "ckan_user") print.ckan_user <- function(x, ...) { cat(paste0("<CKAN User> ", x$id), "\n") cat(" Name: ", x$name, "\n", sep = "") cat(" Display Name: ", x$display_name, "\n", sep = "") cat(" Full Name: ", x$fullname, "\n", sep = "") cat(" No. Packages: ", x$number_created_packages, "\n", sep = "") cat(" No. Edits: ", x$number_of_edits, "\n", sep = "") cat(" Created: ", x$created, "\n", sep = "") } get_user <- function(id, url = get_default_url(), key = get_default_key(), ...) { res <- ckan_GET(url, 'user_show', list(id = id), key = key, opts = list(...)) as_ck(jsl(res), "ckan_user") }
library(testthat) test_that("autotest", { autotest_sdistribution( sdist = Beta, pars = list(shape1 = 1, shape2 = 1), traits = list( valueSupport = "continuous", variateForm = "univariate", type = PosReals$new(zero = TRUE) ), support = Interval$new(0, 1), symmetry = "symmetric", mean = 0.5, mode = NaN, median = 0.5, variance = 1 / 12, skewness = 0, exkur = -1.2, entropy = 0, pgf = NaN, pdf = dbeta(1:3, 1, 1), cdf = pbeta(1:3, 1, 1), quantile = qbeta(c(0.24, 0.42, 0.5), 1, 1) ) }) test_that("manual", { expect_equal(Beta$new(1, 2)$mode(), 0) expect_equal(Beta$new(2, 1)$mode(), 1) expect_equal(Beta$new(0.5, 0.5)$mode(), c(0, 1)) expect_equal(Beta$new(0.5, 0.5)$mode(1), 0) expect_equal(Beta$new(2, 2)$mode(1), 0.5) expect_false(testSymmetric(Beta$new()$setParameterValue(shape1 = 1, shape2 = 2))) }) test_that("vector", { d <- VectorDistribution$new(distribution = "Beta", params = data.frame(shape1 = 1:2, shape2 = 1)) expect_error(d$mode(), "cannot be") })