code
stringlengths
1
13.8M
.simpleAD <- function(dataset, groups, indexMat) { groups <- as.factor(groups) B <- NCOL(indexMat) nObs <- NROW(dataset) p <- NCOL(dataset) C <- length(tab <- table(groups)) K <- C * (C - 1)/2 labsMat <- t(outer(levels(groups), levels(groups), FUN = paste, sep = "-")) labsPC <- labsMat[lower.tri(labsMat)] T <- array(NA, c(B + 1, p, K)) DM <- NULL for(j in seq_len(p)) { DM <- cbind(DM, .dummyze(dataset[,j])) } Q <- as.integer(apply(dataset, MARGIN = 2, FUN = function(x) nlevels(factor(x)))) CM <- -.DesM(tab) / rep(tab, tab) SM <- array(1/nObs, c(nObs, K)) CS <- diag(max(Q)) CS[upper.tri(CS)] <- 1 sq1 <- c(0L, cumsum(Q)) CS.bd <- array(0, c(sum(Q), sum(Q))) fSM <- array(0, c(sum(Q) - length(Q), length(Q))) dd <- diag(p) for(k in seq_along(Q)) { CS.bd[(sq1[k] + 1):sq1[k + 1], (sq1[k] + 1):sq1[k + 1]] <- CS[1:Q[k], 1:Q[k]] fSM[, k] <- rep(dd[k, ], times = (Q - 1)) } FM <- DM %*% CS.bd colnames(FM) <- colnames(DM) num <- crossprod(CM, FM)[, -cumsum(Q)] temp <- crossprod(SM, FM)[, -cumsum(Q)] den <- temp * (1 - temp) den[den < .Machine$double.eps] <- 0 stat <- num / sqrt(den) stat[!is.finite(stat)] <- 0 T[1, , ] <- t(stat %*% fSM) for(bb in 2L:(B + 1)) { ind <- indexMat[, bb - 1] FM.p <- FM[ind, ] num <- crossprod(CM, FM.p)[, -cumsum(Q)] temp <- crossprod(SM, FM.p)[, -cumsum(Q)] den <- temp * (1 - temp) den[den < .Machine$double.eps] <- 0 stat <- t(num / sqrt(den)) stat[!is.finite(stat)] <- 0 T[bb, , ] <- t(crossprod(stat, fSM)) } dimnames(T) <- list( c("p-obs", paste("p-*", seq_len(B), sep = "")), colnames(dataset), labsPC ) return(T) }
library(testthat) library(ramlegacy) test_check("ramlegacy", filter = "load|Load")
print.qif <- function(x, digits = NULL, quote = FALSE, prefix = "", ...) { if(is.null(digits)) digits <- options()$digits else options(digits = digits) cat("\n", x$title) cat("\n", x$version, "\n") cat("\nModel:\n") cat(" Link: ", x$model$link, "\n") cat(" Variance to Mean Relation:", x$model$varfun, "\n") if(!is.null(x$model$M)) cat(" Correlation Structure: ", x$model$corstr, ", M =", x$ model$M, "\n") else cat(" Correlation Structure: ", x$model$corstr, "\n") cat("\nCall:\n") dput(x$call) cat("\nNumber of observations : ", length(x$y), "\n") cat("\nNumber of clusters : ", length(x$nobs), "\n") cat("\nMaximum cluster size : ", x$max.id, "\n") cat("\n\nStatistics:\n") print(x$statistics, digits = digits) cat("\n\nCoefficients:\n") print(x$coefficients, digits = digits) cat("\nEstimated Scale Parameter: ", x$scale, "\n") cat("\nNumber of Iterations: ", x$iteration,"\n") invisible(x) } print.summary.qif <- function(x, digits = NULL, quote = FALSE, prefix = "", ... ) { if(is.null(digits)) digits <- options()$digits else options(digits = digits) cat("\n",x$title) cat("\n",x$version,"\n") cat("\nModel:\n") cat(" Link: ",x$model$link,"\n") cat(" Variance to Mean Relation:",x$model$varfun,"\n") if(!is.null(x$model$M)) cat(" Correlation Structure: ",x$model$corstr,", M =",x$model$M,"\n") else cat(" Correlation Structure: ",x$model$corstr,"\n") cat("\nCall:\n") dput(x$call) cat("\nSummary of Residuals:\n") print(x$residual.summary, digits = digits) cat("\n\nCoefficients:\n") print(x$coefficients, digits = digits) cat("\nEstimated Scale Parameter: ", x$scale,"\n") cat("\nNumber of Iterations: ", x$iteration,"\n") invisible(x) } summary.qif <- function(object, correlation = TRUE, ...) { coef <- object$coefficients resid <- object$residuals n <- length(resid) summary <- list() summary$call <- object$call summary$version <- object$version summary$nobs <- length(object$nobs) summary$residual.summary <- quantile(as.vector(object$residuals)) names(summary$residual.summary) <- c("Min", "1Q", "Median", "3Q", "Max") summary$model<- object$model summary$title <- object$title summary$coefficients <- object$parameter summary$scale <- object$scale summary$iteration <- object$iteration attr(summary,"class") <- "summary.qif" summary } qif <- function (formula = formula(data), id = id, data = parent.frame(), b = NULL, tol = 1e-8, maxiter = 1000, family = gaussian, corstr = "independence", invfun="finv") { if ((invfun!="finv")&&(invfun!="ginv")){ stop("Unknown inverse function. Only finv or ginv.") } call <- match.call() m <- match.call(expand.dots = FALSE) m$b <- m$tol <- m$maxiter <- m$link <- m$varfun <- m$corstr <- m$family <- m$invfun <- NULL if (is.null(m$id)) m$id <- as.name("id") m[[1]] <- as.name("model.frame") m <- eval(m, parent.frame()) Terms <- attr(m, "terms") y <- as.matrix(model.extract(m, "response")) x <- model.matrix(Terms, m) QR <- qr(x) if (QR$rank < ncol(x)) stop("rank-deficient model matrix") if (dim(y)[2] > 1) stop("Only one response (1 column)") id <- model.extract(m, id) if (is.null(id)) { stop("Id variable not found") } nobs <- nrow(x) np <- ncol(x) xnames <- dimnames(x)[[2]] if (is.null(xnames)) { xnames <- paste("x", 1:np, sep = "") dimnames(x) <- list(NULL, xnames) } if (is.character(family)) family <- get(family) if (is.function(family)) family <- family() if (!is.null(b)) { beta <- matrix(as.double(b), ncol = 1) if (nrow(beta) != np) { stop("Dim beta != ncol(x)") } } else { mm <- match.call(expand.dots = FALSE) mm$b <- mm$tol <- mm$maxiter <- mm$link <- mm$varfun <- mm$corstr <- mm$id <- mm$invfun <- NULL mm[[1]] <- as.name("glm") beta <- eval(mm, parent.frame())$coef beta <- as.numeric(beta) } if (length(id) != length(y)) stop("Id and y not same length") maxiter <- as.integer(maxiter) links <- c("identity", "log", "logit", "inverse") fams <- c("gaussian", "poisson", "binomial", "Gamma") varfuns <- c("constant", "mu", "mu(1-mu)", "mu^2") corstrs <- c("independence", "exchangeable", "AR-1", "unstructured") famv <- match(family$family, fams, -1) dist <- family$family linkv <- as.integer(match(c(family$link), links, -1)) if (famv < 1) stop("unknown family") if (famv <= 4) varfunv <- famv else varfunv <- match(family$varfun, varfuns, -1) varfunv <- as.integer(varfunv) corstrv <- as.integer(match(corstr, corstrs, -1)) if (linkv < 1) stop("unknown link.") if (varfunv < 1) stop("unknown varfun.") if (corstrv < 1) stop("unknown corstr.") y <- as.matrix(y) x <- as.matrix(x) obs <- lapply(split(id, id), "length") nobs <- as.numeric(obs) nsub <- length(nobs) np <- dim(x)[[2]] time1 <- date() betadiff <- 1 iteration <- 0 betanew <- beta while(betadiff > tol && iteration < maxiter) { beta <- betanew if (corstr == "independence") { sumg <- matrix(rep(0,np),nrow=np) sumc <- matrix(rep(0,np*np),nrow=np) arsumg <- matrix(rep(0,np),nrow=np) arsumc <- matrix(rep(0,np*np),nrow=np) gi <- matrix(rep(0,np),nrow=np) arsumgfirstdev <- matrix(rep(0,np*np),nrow=np) firstdev <- matrix(rep(0,np*np),nrow=np) } else { sumg <- matrix(rep(0,2*np),nrow=2*np) sumc <- matrix(rep(0,2*np*2*np),nrow=2*np) arsumg <- matrix(rep(0,2*np),nrow=2*np) arsumc <- matrix(rep(0,2*np*2*np),nrow=2*np) gi <- matrix(rep(0,2*np),nrow=2*np) arsumgfirstdev <- matrix(rep(0,2*np*np),nrow=2*np) firstdev <- matrix(rep(0,2*np*np),nrow=2*np) } if (corstr == "unstructured") { n1 <- nobs[1] m0 <- diag(n1) m1 <- matrix(rep(0,n1*n1),n1) loc1 <- 0 loc2 <- 0 for (i in 1:nsub) { loc1 <- loc2+1 loc2 <- loc1+nobs[i]-1 yi <- as.matrix(y[loc1:loc2,]) xi <- x[loc1:loc2,] ni <- nrow(yi) if (dist == "gaussian") { ui <- xi %*% beta } else if (dist == "poisson") { ui <- exp(xi %*% beta) } else if (dist == "Gamma") { ui <- 1 / (xi %*% beta) } else if (dist == "binomial") { ui <- 1 /(1 + exp(- xi %*% beta)) } m1 <- m1 + (yi-ui) %*% t(yi-ui) } m1 <- 1/nsub * m1 } loc1 <- 0 loc2 <- 0 for (i in 1:nsub) { loc1 <- loc2+1 loc2 <- loc1+nobs[i]-1 yi <- as.matrix(y[loc1:loc2,]) xi <- x[loc1:loc2,] ni <- nrow(yi) m0 <- diag(ni) if (corstr == "independence") { m1 <- matrix(rep(0,ni*ni),ni) } else if (corstr == "exchangeable") { m1 <- matrix(rep(1,ni*ni),ni) - m0 } else if (corstr == "AR-1") { m1 <- matrix(rep(0,ni*ni),ni) for (k in 1:ni) { for (l in 1:ni) { if (abs(k-l)==1) m1[k,l] <-1 } } } if (dist == "gaussian") { ui <- xi %*% beta fui <- ui fui_dev <- diag(ni) vui <- diag(ni) } else if (dist == "poisson") { ui <- exp(xi %*% beta) fui <- log(ui) fui_dev <- diag(as.vector(ui)) vui <- diag(as.vector(sqrt(1/ui))) } else if (dist == "Gamma") { ui <- 1 / (xi %*% beta) fui <- 1 / ui fui_dev <- -diag(as.vector(ui)) %*% diag(as.vector(ui)) vui <- diag(as.vector(1/ui)) } else if (dist == "binomial") { ui <- 1 /(1 + exp(- xi %*% beta)) fui <- log(ui) - log(1-ui) fui_dev <- diag(as.vector(ui)) %*% diag(as.vector(1-ui)) vui <- diag(as.vector(sqrt(1/ui))) %*% diag(as.vector(sqrt(1/(1-ui)))) } if (corstr == "independence") { wi <- t(xi) %*% fui_dev %*% vui %*% m0 %*% vui gi0 <- (1/nsub)*wi %*% (yi-ui) gi[1:np,] <- gi0 arsumc <- arsumc + gi %*% t(gi) arsumg <- arsumg + gi di0 <- -(1/nsub) * wi %*% fui_dev %*% xi firstdev[1:np,] <- di0 arsumgfirstdev <- arsumgfirstdev + firstdev } else if (corstr == "unstructured") { wi <- t(xi) %*% fui_dev %*% m0 zi <- t(xi) %*% fui_dev %*% m1 gi0 <- (1/nsub)*wi %*% (yi-ui) gi1 <- (1/nsub)*zi %*% (yi-ui) gi[1:np,] <- gi0 gi[(np+1):(2*np),] <- gi1 arsumc <- arsumc + gi %*% t(gi) arsumg <- arsumg + gi if (is.na(arsumc[1,1])) { } di0 <- -(1/nsub) * wi %*% fui_dev %*% xi di1 <- -(1/nsub) * zi %*% fui_dev %*% xi firstdev[1:np,] <- di0 firstdev[(np+1):(2*np),] <- di1 arsumgfirstdev <- arsumgfirstdev + firstdev } else { wi <- t(xi) %*% fui_dev %*% vui %*% m0 %*% vui zi <- t(xi) %*% fui_dev %*% vui %*% m1 %*% vui gi0 <- (1/nsub)*wi %*% (yi-ui) gi1 <- (1/nsub)*zi %*% (yi-ui) gi[1:np,] <- gi0 gi[(np+1):(2*np),] <- gi1 arsumc <- arsumc + gi %*% t(gi) arsumg <- arsumg + gi if (is.na(arsumc[1,1])) { } di0 <- -(1/nsub) * wi %*% fui_dev %*% xi di1 <- -(1/nsub) * zi %*% fui_dev %*% xi firstdev[1:np,] <- di0 firstdev[(np+1):(2*np),] <- di1 arsumgfirstdev <- arsumgfirstdev + firstdev } } if (invfun=="finv") { a <- arsumc storage.mode(a)<-"double" lda<-as.integer(nrow(a)) n<-as.integer(ncol(a)) z <- .Fortran("finv", a=a, lda, n) arcinv <- z$a } else arcinv=ginv(arsumc) Q <- t(arsumg) %*% arcinv %*% arsumg arqif1dev <- t(arsumgfirstdev) %*% arcinv %*% arsumg arqif2dev <- t(arsumgfirstdev) %*% arcinv %*% arsumgfirstdev if (invfun=="finv") { a <- arqif2dev storage.mode(a)<-"double" lda<-as.integer(nrow(a)) n<-as.integer(ncol(a)) z <- .Fortran("finv", a=a, lda, n) invarqif2dev <- z$a } else invarqif2dev <- ginv(arqif2dev) betanew <- beta - invarqif2dev %*% arqif1dev betadiff <- abs(sum(betanew - beta)) iteration <- iteration +1 } time2 <- date() fit <- list() attr(fit, "class") <- c("qif", "glm") fit$title <- "QIF: Quadratic Inference Function" fit$version <- "QIF function, version 1.5 modified 2019/07/2" links <- c("Identity", "Logarithm", "Logit", "Reciprocal") varfuns <- c("Gaussian", "Poisson", "Binomial", "Gamma") corstrs <- c("Independent", "Exchangeable", "AR-1","Unstructured") fit$model <- list() fit$model$link <- links[linkv] fit$model$varfun <- varfuns[varfunv] fit$model$corstr <- corstrs[corstrv] fit$terms <- Terms fit$formula <- as.vector(attr(Terms, "formula")) fit$call <- call fit$nobs <- nobs fit$iteration <- iteration fit$coefficients <- as.vector(beta) names(fit$coefficients) <- xnames fit$linear.predictors <- as.matrix(x %*% beta) if (dist == "gaussian") { mu <- x %*% beta pearson <- y - mu } else if (dist == "poisson") { mu <- exp(x %*% beta) pearson <- (y - mu) / sqrt(mu) } else if (dist == "Gamma") { mu <- 1 / (x %*% beta) pearson <- (y - mu) / mu } else if (dist == "binomial") { mu <- 1 /(1 + exp(- x %*% beta)) pearson <- (y - mu) / sqrt(mu * (1-mu)) } fit$fitted.value <- as.matrix(mu) fit$residuals <- y - mu fit$pearson.resi <- pearson fit$scale <- sum(pearson**2)/(length(y)-length(beta)) fit$family <- family fit$y <- y fit$x <- x fit$id <- unique(id) fit$max.id <- max(nobs) fit$xnames <- xnames pvalue <- 1 - pchisq(Q,np) if (corstr == "indenpendence") { AIC <- Q BIC <- Q } else { AIC <- Q + 2*np BIC <- Q + np*log(nsub) } statistics <- c(Q, np, pvalue, AIC, BIC) names(statistics) <- c("Q", "D.F.", "pvalue","AIC","BIC") fit$statistics <- statistics betase <- sqrt(diag(invarqif2dev)) Z <- as.vector(beta)/betase betapvalue <- 2*(1-pnorm(abs(Z))) parameter <- cbind(beta, betase, Z, betapvalue) dimnames(parameter)[[2]] <- c("estimate", "stderr", "Z", "pvalue") dimnames(parameter)[[1]] <- xnames fit$parameter <- parameter dimnames(invarqif2dev)[[1]] <- xnames dimnames(invarqif2dev)[[2]] <- xnames fit$covariance <- invarqif2dev fit }
download_t1_data = function(...) { x = kirby21.base::download_kirby21_data(modality = "T1", ...) return(x) }
context("manual - ") only_test_with_token<-function(expr){ testthat::test_that("only test with token: ", { if(!lx_has_token()){ skip(crayon::blue("no 'LIFX' api token in renvironment")) return(invisible(NULL)) } expr } ) } user_confirm<-function(expectation){ user_input<-readline(prompt = paste(expectation, "?", " (enter if correct; 'n' if not)")) result<-FALSE if(user_input==""){result<-TRUE} expect_true(result,label = " expectation") } only_test_with_token({ lx_color(color_name = "red",brightness = 1,duration = 0, power = "on") user_confirm("bright red?") }) only_test_with_token({ lx_color(power = "off") user_confirm("light off?") }) only_test_with_token({ lx_color(color_name = "cyan", brightness = 1, duration = 3,power = "on") user_confirm("to cyan in 3 seconds?") }) only_test_with_token({ lx_color(brightness = 0.01,duration = 0) user_confirm("jump to very dim cyan?") }) only_test_with_token({ lx_color(saturation = 0,duration = 1) user_confirm("1 second to white?") }) only_test_with_token({ lx_color(kelvin = 2000,brightness = 1,duration = 0) user_confirm("immediate bright warm?") }) only_test_with_token({ lx_color(kelvin = 3000,delta = T, duration = 1) user_confirm("1 second to cold light?") }) only_test_with_token({ lx_effect_breathe("red","blue",period = 1,cycles = 3) user_confirm("breath red blue 3x?") }) only_test_with_token({ lx_color(hue = 255, saturation = 0, power = "off") user_confirm("lights off?") }) context("lx_list_lights") expected_items <- c("id", "uuid", "label", "connected", "power", "color", "brightness", "effect", "group", "location", "product", "last_seen", "seconds_since_seen" ) only_test_with_token( { expect_true(all(expected_items %in% names(lx_list_lights()[[1]]))) }) context("lx_rate_limit") only_test_with_token({ ratelimit <- lx_rate_limit() expect_true(all(names(ratelimit)==c("limit", "remaining", "reset"))) expect_true(is.numeric(ratelimit)) expect_true(all(ratelimit>0)) })
library(sf) library(dplyr) library(tidyverse) library(data.table) library(mapview) source("./prep_data/prep_functions.R") update <- 2010 root_dir <- "L:\\ setwd(root_dir) dir.create("./disaster_risk_area") destdir_raw <- paste0("./disaster_risk_area/",update) dir.create(destdir_raw) dir.create("./disaster_risk_area/shapes_in_sf_cleaned", showWarnings = FALSE) destdir_clean <- paste0("./disaster_risk_area/shapes_in_sf_cleaned/",update) dir.create(destdir_clean) download.file("ftp://geoftp.ibge.gov.br/organizacao_do_territorio/tipologias_do_territorio/populacao_em_areas_de_risco_no_brasil/base_de_dados/PARBR2018_BATER.zip" , destfile= paste0(destdir_raw,"/PARBR2018_BATER.zip")) setwd(destdir_raw) zipfiles <- list.files(pattern = ".zip") unzip(zipfiles) temp_sf <- st_read("PARBR2018_BATER.shp") names(temp_sf) temp_sf$ID <- NULL temp_sf$AREA_GEO <- NULL temp_sf <- rename(temp_sf, code_state = GEO_UF,) temp_sf <- rename(temp_sf, code_muni = GEO_MUN) temp_sf <- rename(temp_sf, name_muni = MUNICIPIO) temp_sf <- rename(temp_sf, geo_bater = GEO_BATER) temp_sf <- rename(temp_sf, origem = ORIGEM) temp_sf <- rename(temp_sf, acuracia = ACURACIA) temp_sf <- rename(temp_sf, obs = OBS) temp_sf <- rename(temp_sf, num = NUM) temp_sf$name_muni <- stringi::stri_encode(as.character(temp_sf$name_muni), "UTF-8") original_crs <- sf::st_crs(temp_sf) temp_sf <- as.data.table(temp_sf) temp_sf[ code_state== 11, abbrev_state := "RO" ] temp_sf[ code_state== 12, abbrev_state := "AC" ] temp_sf[ code_state== 13, abbrev_state := "AM" ] temp_sf[ code_state== 14, abbrev_state := "RR" ] temp_sf[ code_state== 15, abbrev_state := "PA" ] temp_sf[ code_state== 16, abbrev_state := "AP" ] temp_sf[ code_state== 17, abbrev_state := "TO" ] temp_sf[ code_state== 21, abbrev_state := "MA" ] temp_sf[ code_state== 22, abbrev_state := "PI" ] temp_sf[ code_state== 23, abbrev_state := "CE" ] temp_sf[ code_state== 24, abbrev_state := "RN" ] temp_sf[ code_state== 25, abbrev_state := "PB" ] temp_sf[ code_state== 26, abbrev_state := "PE" ] temp_sf[ code_state== 27, abbrev_state := "AL" ] temp_sf[ code_state== 28, abbrev_state := "SE" ] temp_sf[ code_state== 29, abbrev_state := "BA" ] temp_sf[ code_state== 31, abbrev_state := "MG" ] temp_sf[ code_state== 32, abbrev_state := "ES" ] temp_sf[ code_state== 33, abbrev_state := "RJ" ] temp_sf[ code_state== 35, abbrev_state := "SP" ] temp_sf[ code_state== 41, abbrev_state := "PR" ] temp_sf[ code_state== 42, abbrev_state := "SC" ] temp_sf[ code_state== 43, abbrev_state := "RS" ] temp_sf[ code_state== 50, abbrev_state := "MS" ] temp_sf[ code_state== 51, abbrev_state := "MT" ] temp_sf[ code_state== 52, abbrev_state := "GO" ] temp_sf[ code_state== 53, abbrev_state := "DF" ] head(temp_sf) temp_sf <- st_as_sf(temp_sf, crs=original_crs) temp_sf <- harmonize_projection(temp_sf) temp_sf <- lwgeom::st_make_valid(temp_sf) setcolorder(temp_sf, c('geo_bater', 'origem', 'acuracia', 'obs', 'num', 'code_muni', 'name_muni', 'code_state', 'abbrev_state', 'geometry')) temp_sf <- to_multipolygon(temp_sf) temp_sf7 <- st_transform(temp_sf, crs=3857) %>% sf::st_simplify(preserveTopology = T, dTolerance = 100) %>% st_transform(crs=4674) head(temp_sf7) setwd(root_dir) readr::write_rds(temp_sf, path= paste0(destdir_clean,"/disaster_risk_area2010.rds"), compress = "gz") sf::st_write(temp_sf, dsn= paste0(destdir_clean,"/disaster_risk_area2010.gpkg") ) sf::st_write(temp_sf7, dsn= paste0(destdir_clean,"/disaster_risk_area2010 _simplified", ".gpkg"))
init_test_pkgzip <- function() { path <- tempfile(tmpdir = get_wspace_dir(), pattern = "pkgzip_") dir.create(path, recursive = T) path <- normalizePath(path) on_test_exit(function() { unlink(path, recursive = T, force = T) }) return(list( path = path, get_pkgzip_fpath = function() { files <- list.files(path, pattern = sprintf("%s_pkgzip_.*[.]zip", Sys.Date()), full.names = T) expect_length(files, 1) return(files) } )) } expect_that_pkgzip_contains <- function(names, type, pkgzip, optional_names = c()) { files <- pkgzip$get_pkgzip_fpath() cont_path <- file.path(pkgzip$path, "cont") expect_success({ unzip(zipfile = files, exdir = file.path(pkgzip$path, "cont")) succeed() }) c_url <- RSuite:::rsuite_contrib_url(repos = sprintf("file:///%s", cont_path), type = type) avail <- data.frame(available.packages(contriburl = c_url, filters = c()), stringsAsFactors = F)$Package avail <- avail[order(avail)] names <- c(names, intersect(optional_names, avail)) names <- names[order(names)] expect_equal(object = avail, expected = names) }
eblup.mse.f.c2 <- function(gamma.i , X.i , X.bar.i , sum.A.i ,...){ x.bar.i <- as.matrix(apply(X.i, 2, mean)) x.tmp <- (X.bar.i - gamma.i * x.bar.i) res <- t(x.tmp) %*% solve(sum.A.i) %*% x.tmp return(res) }
fclustering <- function(curve_sets, k, type = c("area", "st", "erl", "cont"), ...) { if(!(length(class(curve_sets)) == 1 && class(curve_sets) == "list")) { curve_sets <- list(curve_sets) } curve_sets <- lapply(curve_sets, FUN=convert_to_curveset) if(any(sapply(curve_sets, FUN=curve_set_is1obs))) stop("Some or all sets of curves have one observed function.") checkequal <- function(f) { all(sapply(curve_sets, FUN=function(curve_set) { f(curve_set) == f(curve_sets[[1]]) })) } if(!checkequal(curve_set_nfunc)) stop("The numbers of functions in curve sets differ.") if(!checkequal(curve_set_narg)) warning("The numbers of points where the curves are observed (r) differ in the given curve sets.") type <- match.arg(type) if(type %in% c("erl", "cont")) warning("Type is ", type, ". Check if the triangular inequality is equal to 1. \n", "If not, the measure does not form a metric. pam should not be used.") if(type == "st") { measure <- "max"; scaling <- "st" } else { measure <- type; scaling <- NULL } n <- length(curve_sets) lstats <- list() jr <- NULL jstats <- NULL for(j in 1:n) { nr <- curve_set_narg(curve_sets[[j]]) nfunc <- curve_set_nfunc(curve_sets[[j]]) funcs <- curve_set_funcs(curve_sets[[j]]) co <- combn(nfunc, 2, simplify = FALSE) stats <- array(0, c(2*length(co), nr)) for(i in 1:length(co)) { stats[i,] <- funcs[, co[[i]][1]]-funcs[, co[[i]][2]] } for(i in 1:length(co)) { stats[length(co)+i, ] <- funcs[, co[[i]][2]]-funcs[, co[[i]][1]] } lstats[[j]] <- stats jr <- c(jr, curve_sets[[1]][['r']]) jstats <- cbind(jstats, lstats[[j]]) } jstats <- rbind(jstats, rep(0, length(jr))) data <- create_curve_set(list(r=jr, obs=t(jstats))) b <- dist(data_and_sim_curves(curve_sets[[1]])) if(measure == "max") fo <- forder(data, measure="max", scaling=scaling) else fo <- 1 - forder(data, measure=measure, scaling=scaling) b[1:length(b)] <- fo[1:length(b)] resultpamF <- pam(b, k=k) bb <- as.matrix(b) nr1 <- curve_set_narg(curve_sets[[1]]) r <- NULL for(i in 1:(nr1-2)) { for(j in (i+1):(nr1-1)) { for(kk in (j+1):(nr1)) { r <- c(r, bb[i,j] + bb[j,kk] >= bb[i,kk] - 0.00000001) } } } res <- list(curve_sets=curve_sets, k=k, type=type, pam=resultpamF, dis=b, triangineq = sum(r)/length(r)) class(res) <- "fclust" res } print.fclust <- function(x, ...) { cat("Functional clustering:\n") cat(" * Based on the measure \'", x$type, "\' at ", x$k, " clusters \n", sep="") cat(" * Triangular inequality is satisfied in", x$triangineq*100, "% of cases.\n") cat("The object contains:\n") cat("$pam - Results of the partitioning around medoids\n") cat("$pam$clustering - The clustering vector\n") cat("$dis - The dissimilarity matrix\n") } plot.fclust <- function(x, plotstyle = c("marginal", "joined"), coverage = 0.5, nstep, ncol, ...) { csets <- x$curve_sets n <- length(csets) k <- x$k type <- x$type plotstyle <- match.arg(plotstyle) if(coverage < 0 | coverage > 1) stop("Unreasonable coverage.") if(missing(ncol)) ncol <- k+1 if(!is.numeric(ncol) || length(ncol) != 1) stop("Unreasonable ncol.") if(type %in% "st") centralf <- min else centralf <- max if(missing(nstep)) { nstep <- 1 checkequal <- function(f) { all(sapply(csets, FUN=function(curve_set) { f(curve_set) == f(csets[[1]]) })) } if(!checkequal(curve_set_narg)) nstep <- 2 } if(!(nstep %in% c(1,2))) stop("Invalid value of nstep.") if(!all(sapply(csets, FUN = curve_set_is1d))) stop("Plots are valid only for 1-dimensional curve_set objects.") resultpamF <- x$pam resultpamT <- x$pam$clustering nis <- as.numeric(table(resultpamT)) cr_all <- vector("list", n) if(plotstyle == "marginal") { for(j in 1:n) { cr <- vector("list", k) ff <- vector("list", k) for(i in 1:k) { clusteri <- subset(csets[[j]], resultpamT==i) if(nis[i] > 3) { cr[[i]] <- central_region(clusteri, type=type, coverage=coverage) } else { cr[[i]] <- data.frame(r=clusteri[['r']], central=1, lo=NA, hi=NA) } cr[[i]]$central <- curve_set_funcs(csets[[j]])[, resultpamF$id.med[i]] } cr_all[[j]] <- cr } } else { cr <- vector("list", k) ff <- vector("list", k) for(i in 1:k) { if(nis[i] > 3) { clusteri <- lapply(csets, FUN=subset, subset=resultpamT==i) cr[[i]] <- central_region(clusteri, type=type, coverage=coverage, nstep=nstep) if(n > 1) for(z in 1:n) cr[[i]][[z]]$central <- curve_set_funcs(csets[[z]])[, resultpamF$id.med[i]] else cr[[i]]$central <- curve_set_funcs(csets[[1]])[, resultpamF$id.med[i]] } } for(j in 1:n) cr_all[[j]] <- lapply(cr, FUN=function(z) { z[[j]] }) } alt <- "two.sided" d <- list(xlab="", ylab="") labels <- paste("Group", 1:k) if(n < 2) { n_of_plots <- k + 1 ncols_of_plots <- min(n_of_plots, ncol) nrows_of_plots <- ceiling(n_of_plots / ncols_of_plots) scales <- "fixed" } else scales <- "free_y" if(!is.null(names(csets))) csetnames <- names(csets) else csetnames <- paste("Curves", 1:n) df <- NULL for(i in 1:n) { df_i <- combined_df_construction(cr_all[[i]], labels=labels) df_i$cset <- csetnames[i] df <- rbind(df, df_i) } df$cset <- factor(df$cset, levels=csetnames) funcs <- lapply(csets, FUN=curve_set_funcs) nams <- lapply(funcs, FUN=function(x) { n <- colnames(x); if(!is.null(n)) n else 1:ncol(x) }) funcs.df <- do.call(rbind, lapply(1:length(funcs), FUN = function(i) { data.frame(r = rep(cr_all[[1]][[i]][['r']], times=ncol(funcs[[i]])), curves = c(funcs[[i]]), id = factor(rep(nams[[i]], each=length(cr_all[[1]][[i]][['r']])), levels = nams[[i]]), plotmain = factor(rep(paste("Group", resultpamT), each=length(cr_all[[1]][[i]][['r']])), levels = labels), cset = csetnames[i]) })) size <- 0.3 df$Group <- df$plotmain p1 <- ( ggplot() + geom_line(data = df, aes_(x = ~r, y = ~curves, group = ~Group, linetype = ~Group), size = size, col='black') + set_envelope_legend_position() + labs(title = "", x = d$xlab, y = d$ylab) ) if(n > 1) p1 <- ( p1 + facet_grid(cset~type, scales="free_y") ) else p1 <- ( p1 + facet_wrap(~type, scales="free_y") ) p2 <- ( ggplot() + geom_line(data = funcs.df, aes_(x = ~r, y = ~curves, group = ~id), col='grey70') + basic_stuff_for_fclustplot(df, d$xlab, d$ylab, main="", size=size) + guides(linetype = "none") ) if(n > 1) p2 <- (p2 + facet_grid(cset~plotmain, scales=scales)) else p2 <- (p2 + facet_wrap(~ plotmain, scales=scales, nrow=nrows_of_plots, ncol=ncols_of_plots)) list(p1, p2) }
probs_qtl2_to_doqtl <- function(probs) { is_x_chr <- attr(probs, "is_x_chr") n_geno <- sapply(probs, ncol) crosstype <- attr(probs, "crosstype") if(is.null(crosstype)) warning('Expecting crosstype "do" but it is missing.') else if(crosstype!="do") warning('Expecting crosstype "do" but it is "', crosstype, '"') n_pos <- sapply(probs, function(a) dim(a)[3]) if(all(n_geno==8)) { result <- array(dim=c(nrow(probs[[1]]), ncol(probs[[1]]), sum(n_pos))) dimnames(result) <- list(rownames(probs[[1]]), colnames(probs[[1]]), unlist(lapply(probs, function(a) dimnames(a)[[3]]))) cur <- 0 for(i in seq_along(probs)) { result[,,cur + 1:n_pos[i]] <- probs[[i]] cur <- cur + n_pos[i] } return(result) } else { if(!all(n_geno[is_x_chr] == 44) || !all(n_geno[!is_x_chr]==36)) stop("There should be 44 genotypes on the X and 36 on the autosomes.") alleles <- attr(probs, "alleles") if(is.null(alleles)) alleles <- LETTERS[1:8] if(length(alleles) != 8) stop("length(alleles) != 8") homozyg <- paste0(alleles, alleles) hemizyg <- paste0(alleles, "Y") for(chr in names(probs)[is_x_chr]) { probs[[chr]][,homozyg,] <- probs[[chr]][,homozyg,,drop=FALSE] + probs[[chr]][,hemizyg,,drop=FALSE] probs[[chr]] <- probs[[chr]][,1:36,,drop=FALSE] } mat <- rbind(rep(1:8, each=8), rep(1:8, 8)) geno_labels <- apply(mat[,mat[1,] <= mat[2,]], 2, function(a) paste(alleles[a], collapse="")) result <- array(dim=c(nrow(probs[[1]]), ncol(probs[[1]]), sum(n_pos))) dimnames(result) <- list(rownames(probs[[1]]), geno_labels, unlist(lapply(probs, function(a) dimnames(a)[[3]]))) cur <- 0 for(i in seq_along(probs)) { result[,,cur + 1:n_pos[i]] <- probs[[i]][,geno_labels,,drop=FALSE] cur <- cur + n_pos[i] } return(result) } }
plotBaseline <- function(x, y, specNo = 1, grid = FALSE, labels = 1:n, rev.x = FALSE, zoom = list(xz = 1, yz = 1, xc = 0, yc = 0), ...) { if(!missing(y)) warning("Argument 'y' is ignored") spectrum <- getSpectra(x)[specNo,] baseline <- getBaseline(x)[specNo,] corrected <- getCorrected(x)[specNo,] n <- length(spectrum) if (is.numeric(labels)) { xvals <- labels xaxt <- par("xaxt") } else { xvals <- 1:n xaxt <- "n" } par(bg="white", cex.main=0.7, pty="m", mar=c(3,2,2,1), mfrow=c(2,1)) yu <- max(spectrum); yl <- min(spectrum) p <- yu-yl ylim <- c(-p*0.025/zoom$yz + p*zoom$yc/100 + yl, p*1.025/zoom$yz + p*zoom$yc/100 + yl) yuc <- max(corrected); ylc <- min(corrected) pc <- yuc-ylc ylimc <- c(-pc*0.025/zoom$yz + pc*zoom$yc/100 + ylc, pc*1.025/zoom$yz + pc*zoom$yc/100 + ylc) xr <- range(xvals) xc <- mean(xr) xhwd <- diff(xr) / 2 xlim <- (xr - xc)/zoom$xz + xc + xhwd * zoom$xc/100 if(rev.x) xlim <- rev(xlim) plot(xvals, spectrum, type = "l", xlim = xlim, ylim = ylim, xaxt = xaxt, xlab = "", ylab = "", main = "Original spectrum") lines(xvals, baseline, col = 2) if (!is.numeric(labels)) { ticks <- axTicks(1) ticks <- ticks[ticks >= 1 & ticks <= length(labels)] axis(1, ticks, labels[ticks], ...) } if(grid) grid() plot(xvals, corrected, type = "l", xlim = xlim, ylim = ylimc, xaxt = xaxt, xlab = "", ylab = "", main = "Baseline corrected spectrum") lines(xvals, numeric(n), col = 2) if (!is.numeric(labels)) axis(1, ticks, labels[ticks], ...) if(grid) grid() } setMethod("plot", "baseline", function(x, y, specNo = 1, grid = FALSE, labels = 1:n, rev.x = FALSE, zoom = NULL, ...) { if(!missing(y)) warning("Argument 'y' is ignored") n <- dim(getSpectra(x))[2] if (!isTRUE(zoom)) { if (missing(zoom)) zoom <- list(xz = 1, yz = 1, xc = 0, yc = 0) plotBaseline(x, specNo = specNo, grid = grid, labels = labels, rev.x = rev.x, zoom = zoom) } else { if(requireNamespace("gWidgets", quietly = TRUE)){ xz <- 1; yz <- 1; xc <- 0; yc <- 0 if (length(dev.list()) == 0) dev.new() mydevice <- dev.cur() updatePlot <- function() { currdevice <- dev.cur() if (currdevice != mydevice) dev.set(mydevice) plotBaseline(x, specNo = specNo, grid = grid, labels = labels, rev.x = rev.x, zoom = list(xz = xz, yz = yz, xc = xc, yc = yc)) if (currdevice != mydevice) dev.set(currdevice) } zoomX <- gWidgets::gslider(from=1,to=100,by=.1, value=1, handler = function(h,...){ xz <<- gWidgets::svalue(zoomX); updatePlot()}) zoomY <- gWidgets::gslider(from=1,to=100,by=.5, value=1, handler = function(h,...){ yz <<- gWidgets::svalue(zoomY); updatePlot()}) centerX <- gWidgets::gslider(from=-100,to=100,by=.1, value=0, handler = function(h,...){ xc <<- gWidgets::svalue(centerX); updatePlot()}) centerY <- gWidgets::gslider(from=-100,to=100,by=.1, value=0, handler = function(h,...){ yc <<- gWidgets::svalue(centerY); updatePlot()}) resetZoom <- gWidgets::gbutton(text = "Reset zoom and center", handler = function(h,...){ gWidgets::svalue(zoomX)<-1; gWidgets::svalue(zoomY)<-1; gWidgets::svalue(centerX)<-0; gWidgets::svalue(centerY)<-0; updatePlot()}) gridCheck <- gWidgets::gcheckbox('Grid', handler = function(h,...){ grid <<- gWidgets::svalue(gridCheck); updatePlot()}) zoomWindow <- gWidgets::gwindow(paste("Zoom: Device", mydevice), width=300) superGroup <- gWidgets::ggroup(horizontal=FALSE,container=zoomWindow) subgroupXz <- gWidgets::gframe("X zoom",horizontal=FALSE) gWidgets::add(subgroupXz,zoomX,expand=TRUE) subgroupXc <- gWidgets::gframe("X center",horizontal=FALSE) gWidgets::add(subgroupXc,centerX,expand=TRUE) gWidgets::add(superGroup,subgroupXz,expand=TRUE) gWidgets::add(superGroup,subgroupXc,expand=TRUE) addSpace(superGroup,20,horizontal=FALSE) subgroupYz <- gWidgets::gframe("Y zoom",horizontal=FALSE) gWidgets::add(subgroupYz,zoomY,expand=TRUE) subgroupYc <- gWidgets::gframe("Y center",horizontal=FALSE) gWidgets::add(subgroupYc,centerY,expand=TRUE) gWidgets::add(superGroup,subgroupYz,expand=TRUE) gWidgets::add(superGroup,subgroupYc,expand=TRUE) subgroup3 <- ggroup(horizontal=TRUE,expand=TRUE) gWidgets::add(subgroup3,resetZoom,expand=TRUE) gWidgets::add(subgroup3,gridCheck,expand=FALSE) gWidgets::add(superGroup,subgroup3,expand=TRUE) updatePlot() } else { warning('Package gWidgets not installed') return(list()) } } } )
"r.con" <- function(rho,n,p=.95,twotailed=TRUE) { z <- fisherz(rho) if(n<4) {stop("number of subjects must be greater than 3")} se <- 1/sqrt(n-3) p <- 1-p if(twotailed) p<- p/2 dif <- qnorm(p) zlow <- z + dif*se zhigh <- z - dif*se ci <- c(zlow,zhigh) ci <- fisherz2r(ci) return(ci) } "r2t" <- function(rho,n) { return( rho*sqrt((n-2)/(1-rho^2))) }
test_that("tbl_subset_col()", { data <- tibble(a = 1:2, b = 3:4) expect_equal(tbl_subset_col(data, 2), data[2]) })
departures.icm <- function(dat, at) { if (dat$param$vital == FALSE) { return(dat) } nDepartures <- 0 idsElig <- which(dat$attr$active == 1 & dat$attr$status == "s") nElig <- length(idsElig) if (nElig > 0) { rates <- dat$param$ds.rate vecDepartures <- which(rbinom(nElig, 1, rates) == 1) if (length(vecDepartures) > 0) { idsDpt <- idsElig[vecDepartures] nDepartures <- length(idsDpt) dat$attr$active[idsDpt] <- 0 } } if (at == 2) { dat$epi$ds.flow <- c(0, nDepartures) } else { dat$epi$ds.flow[at] <- nDepartures } nDepartures <- 0 idsElig <- which(dat$attr$active == 1 & dat$attr$status == "i") nElig <- length(idsElig) if (nElig > 0) { rates <- dat$param$di.rate vecDepartures <- which(rbinom(nElig, 1, rates) == 1) if (length(vecDepartures) > 0) { idsDpt <- idsElig[vecDepartures] nDepartures <- length(idsDpt) dat$attr$active[idsDpt] <- 0 } } if (at == 2) { dat$epi$di.flow <- c(0, nDepartures) } else { dat$epi$di.flow[at] <- nDepartures } nDepartures <- 0 idsElig <- which(dat$attr$active == 1 & dat$attr$status == "r") nElig <- length(idsElig) if (nElig > 0) { rates <- dat$param$dr.rate vecDepartures <- which(rbinom(nElig, 1, rates) == 1) if (length(vecDepartures) > 0) { idsDpt <- idsElig[vecDepartures] nDepartures <- length(idsDpt) dat$attr$active[idsDpt] <- 0 } } if (at == 2) { dat$epi$dr.flow <- c(0, nDepartures) } else { dat$epi$dr.flow[at] <- nDepartures } return(dat) } arrivals.icm <- function(dat, at) { if (dat$param$vital == FALSE) { return(dat) } a.rate <- dat$param$a.rate nOld <- dat$epi$num[at - 1] nArrivals <- sum(rbinom(nOld, 1, a.rate)) totArrivals <- nArrivals dat$attr$active <- c(dat$attr$active, rep(1, totArrivals)) dat$attr$group <- c(dat$attr$group, c(rep(1, nArrivals))) dat$attr$status <- c(dat$attr$status, rep("s", totArrivals)) dat$attr$infTime <- c(dat$attr$infTime, rep(NA, totArrivals)) if (at == 2) { dat$epi$a.flow <- c(0, nArrivals) } else { dat$epi$a.flow[at] <- nArrivals } return(dat) } departures.icm.bip <- function(dat, at) { if (dat$param$vital == FALSE) { return(dat) } group <- dat$attr$group nDepartures <- nDeparturesG2 <- 0 idsElig <- which(dat$attr$active == 1 & dat$attr$status == "s") nElig <- length(idsElig) if (nElig > 0) { gElig <- group[idsElig] rates <- c(dat$param$ds.rate, dat$param$ds.rate.g2) ratesElig <- rates[gElig] vecDepartures <- which(rbinom(nElig, 1, ratesElig) == 1) if (length(vecDepartures) > 0) { idsDpt <- idsElig[vecDepartures] nDepartures <- sum(group[idsDpt] == 1) nDeparturesG2 <- sum(group[idsDpt] == 2) dat$attr$active[idsDpt] <- 0 } } if (at == 2) { dat$epi$ds.flow <- c(0, nDepartures) dat$epi$ds.flow.g2 <- c(0, nDeparturesG2) } else { dat$epi$ds.flow[at] <- nDepartures dat$epi$ds.flow.g2[at] <- nDeparturesG2 } nDepartures <- nDeparturesG2 <- 0 idsElig <- which(dat$attr$active == 1 & dat$attr$status == "i") nElig <- length(idsElig) if (nElig > 0) { gElig <- group[idsElig] rates <- c(dat$param$di.rate, dat$param$di.rate.g2) ratesElig <- rates[gElig] vecDepartures <- which(rbinom(nElig, 1, ratesElig) == 1) if (length(vecDepartures) > 0) { idsDpt <- idsElig[vecDepartures] nDepartures <- sum(group[idsDpt] == 1) nDeparturesG2 <- sum(group[idsDpt] == 2) dat$attr$active[idsDpt] <- 0 } } if (at == 2) { dat$epi$di.flow <- c(0, nDepartures) dat$epi$di.flow.g2 <- c(0, nDeparturesG2) } else { dat$epi$di.flow[at] <- nDepartures dat$epi$di.flow.g2[at] <- nDeparturesG2 } nDepartures <- nDeparturesG2 <- 0 idsElig <- which(dat$attr$active == 1 & dat$attr$status == "r") nElig <- length(idsElig) if (nElig > 0) { gElig <- group[idsElig] rates <- c(dat$param$dr.rate, dat$param$dr.rate.g2) ratesElig <- rates[gElig] vecDepartures <- which(rbinom(nElig, 1, ratesElig) == 1) if (length(vecDepartures) > 0) { idsDpt <- idsElig[vecDepartures] nDepartures <- sum(group[idsDpt] == 1) nDeparturesG2 <- sum(group[idsDpt] == 2) dat$attr$active[idsDpt] <- 0 } } if (at == 2) { dat$epi$dr.flow <- c(0, nDepartures) dat$epi$dr.flow.g2 <- c(0, nDeparturesG2) } else { dat$epi$dr.flow[at] <- nDepartures dat$epi$dr.flow.g2[at] <- nDeparturesG2 } return(dat) } arrivals.icm.bip <- function(dat, at) { if (dat$param$vital == FALSE) { return(dat) } a.rate <- dat$param$a.rate a.rate.g2 <- dat$param$a.rate.g2 nOld <- dat$epi$num[at - 1] nArrivals <- nArrivalsG2 <- 0 nOldG2 <- dat$epi$num.g2[at - 1] if (is.na(a.rate.g2)) { nArrivals <- sum(rbinom(nOld, 1, a.rate)) nArrivalsG2 <- sum(rbinom(nOld, 1, a.rate)) } else { nArrivals <- sum(rbinom(nOld, 1, a.rate)) nArrivalsG2 <- sum(rbinom(nOldG2, 1, a.rate.g2)) } totArrivals <- nArrivals + nArrivalsG2 dat$attr$active <- c(dat$attr$active, rep(1, totArrivals)) dat$attr$group <- c(dat$attr$group, c(rep(1, nArrivals), rep(2, nArrivalsG2))) dat$attr$status <- c(dat$attr$status, rep("s", totArrivals)) dat$attr$infTime <- c(dat$attr$infTime, rep(NA, totArrivals)) if (at == 2) { dat$epi$a.flow <- c(0, nArrivals) dat$epi$a.flow.g2 <- c(0, nArrivalsG2) } else { dat$epi$a.flow[at] <- nArrivals dat$epi$a.flow.g2[at] <- nArrivalsG2 } return(dat) }
`seq_range` <- function (r, n = 80) seq(min(r), max(r), len = n)
coef.pense_fit <- function (object, lambda, alpha = NULL, sparse = NULL, standardized = FALSE, exact = deprecated(), correction = deprecated(), ...) { if (is_present(exact)) { deprecate_stop('2.0.0', 'coef(exact=)') } if (is_present(correction)) { deprecate_stop('2.0.0', 'coef(correction=)') } if (length(lambda) > 1L) { warn("Only first element in `lambda` is used.") } cl <- match.call(expand.dots = TRUE) concat <- !isFALSE(cl$concat) lambda <- .as(lambda[[1L]], 'numeric') lambda_index <- .lambda_index_cvfit(object, lambda = lambda, alpha = alpha, se_mult = 0) if (length(lambda_index) > 1L) { warn(paste("Requested penalization level not part of the sequence.", "Returning interpolated coefficients.")) return(.interpolate_coefs(object, indices = lambda_index, lambda = lambda, sparse = sparse, envir = parent.frame(), standardized = standardized, concat = concat)) } else { return(.concat_coefs(object$estimates[[lambda_index]], object$call, sparse = sparse, envir = parent.frame(), standardized = standardized, concat = concat)) } } coef.pense_cvfit <- function (object, alpha = NULL, lambda = 'min', se_mult = 1, sparse = NULL, standardized = FALSE, exact = deprecated(), correction = deprecated(), ...) { if (is_present(exact)) { deprecate_stop('2.0.0', 'coef(exact=)') } if (is_present(correction)) { deprecate_stop('2.0.0', 'coef(correction=)') } cl <- match.call(expand.dots = TRUE) concat <- !isFALSE(cl$concat) lambda_index <- .lambda_index_cvfit(object, lambda = lambda, alpha = alpha, se_mult = se_mult) if (length(lambda_index) > 1L) { warn(paste("Requested penalization level not part of the sequence.", "Returning interpolated coefficients.")) .interpolate_coefs(object, indices = lambda_index, lambda = .as(lambda[[1L]], 'numeric'), sparse = sparse, envir = parent.frame(), standardized = standardized, concat = concat) } else { .concat_coefs(object$estimates[[lambda_index]], call = object$call, sparse = sparse, envir = parent.frame(), standardized = standardized, concat = concat) } } .lambda_index_cvfit <- function (object, lambda, alpha, se_mult) { if (is.character(lambda) && !identical(lambda, 'se')) { se_mult <- .parse_se_string(lambda, only_fact = TRUE) } if (is.character(lambda)) { if (!any(object$cvres$cvse > 0) && isTRUE(se_mult > 0)) { warn(paste("Only a single cross-validation replication was performed.", "Standard error not available. Using minimum lambda.")) } considered_alpha <- if (!missing(alpha) && !is.null(alpha)) { object$alpha[na.omit(.approx_match(.as(alpha, 'numeric'), object$alpha))] } else { object$alpha } if (length(considered_alpha) == 0L) { abort("`object` was not fit with the requested `alpha` value.") } if (isTRUE(se_mult > 0) && !any(object$cvres$cvse > 0)) { warn("Standard errors not available. Returning estimate for `lambda = \"min\"`.") } best_per_alpha <- vapply(considered_alpha, FUN.VALUE = numeric(2L), FUN = function (alpha) { rows <- which((object$cvres$alpha - alpha)^2 < .Machine$double.eps) se_selection <- .cv_se_selection(object$cvres$cvavg[rows], object$cvres$cvse[rows], se_mult) sel_index <- rows[[which(se_selection == 'se_fact')]] c(lambda = object$cvres$lambda[[sel_index]], cvavg = object$cvres$cvavg[[sel_index]]) }) best_alpha_index <- which.min(best_per_alpha['cvavg', ]) alpha <- considered_alpha[[best_alpha_index]] lambda <- best_per_alpha['lambda', best_alpha_index] } if (missing(alpha) || is.null(alpha)) { if (length(object$alpha) > 1L) { warn(paste("`object` was fit for multiple `alpha` values.", "Using first value in `object$alpha`.", "To select a different value, specify parameter `alpha`.")) } alpha <- object$alpha[[1L]] } if (length(lambda) > 1L) { warn("Only first element in `lambda` is used.") } if (length(alpha) > 1L) { warn("Only the first element in `alpha` is used.") } alpha <- .as(alpha[[1L]], 'numeric') est_alpha <- vapply(object$estimates, FUN = `[[`, 'alpha', FUN.VALUE = numeric(1L)) alpha_ests_indices <- which((alpha - est_alpha)^2 < .Machine$double.eps) if (length(alpha_ests_indices) == 0L) { abort("`object` was not fit with the requested `alpha` value.") } lambda <- .as(lambda[[1L]], 'numeric') est_lambda <- vapply(object$estimates[alpha_ests_indices], FUN = `[[`, 'lambda', FUN.VALUE = numeric(1L)) selected_ests <- alpha_ests_indices[.approx_match(lambda, est_lambda)] if (anyNA(selected_ests)) { est_lambda_ord <- order(est_lambda, decreasing = TRUE) max_lambda_index <- est_lambda_ord[[1L]] min_lambda_index <- est_lambda_ord[[length(est_lambda_ord)]] if (!isTRUE(lambda < est_lambda[[max_lambda_index]])) { selected_ests <- alpha_ests_indices[[max_lambda_index]] if (!isTRUE(sum(abs(object$estimates[[selected_ests]]$beta)) < .Machine$double.eps)) { warn(paste("Selected `lambda` is larger than highest penalization level in `object`.", "Returning estimate for highest penalization level.")) } } else if (!isTRUE(lambda > est_lambda[[min_lambda_index]])) { warn(paste("Selected `lambda` is smaller than smallest penalization level in `object`.", "Returning estimate for smallest penalization level.")) selected_ests <- alpha_ests_indices[[min_lambda_index]] } else { lambda_diff <- est_lambda[est_lambda_ord] - lambda lambda_ind_left <- min(which(lambda_diff < 0)) lambda_ind_right <- max(which(lambda_diff >= 0)) selected_ests <- alpha_ests_indices[est_lambda_ord[c(lambda_ind_left, lambda_ind_right)]] } } selected_ests } .interpolate_coefs <- function (object, indices, lambda, ...) { lambdas <- vapply(object$estimates[indices], FUN = `[[`, 'lambda', FUN.VALUE = numeric(1L)) interp_w <- 1 / abs(lambdas - lambda) interp_w <- interp_w / sum(interp_w) interp_beta <- interp_w[[1L]] * object$estimates[[indices[[1L]]]]$beta + interp_w[[2L]] * object$estimates[[indices[[2L]]]]$beta interp_int <- interp_w[[1L]] * object$estimates[[indices[[1L]]]]$intercept + interp_w[[2L]] * object$estimates[[indices[[2L]]]]$intercept interp_std_beta <- interp_w[[1L]] * object$estimates[[indices[[1L]]]]$std_beta + interp_w[[2L]] * object$estimates[[indices[[2L]]]]$std_beta interp_std_int <- interp_w[[1L]] * object$estimates[[indices[[1L]]]]$std_intercept + interp_w[[2L]] * object$estimates[[indices[[2L]]]]$std_intercept return(.concat_coefs(list(intercept = interp_int, beta = interp_beta, std_intercept = interp_std_int, std_beta = interp_std_beta), object$call, ...)) } .concat_coefs <- function (coef, call, sparse, envir, standardized = FALSE, concat = TRUE) { if (!concat) { return(coef) } var_names <- tryCatch(colnames(eval(call$x, envir = envir)), error = function (e) NULL) if (is.null(var_names)) { var_names <- paste('X', seq_len(length(coef$beta)), sep = '') } var_names <- c('(Intercept)', var_names) if (isTRUE(standardized)) { beta <- coef$std_beta intercept <- coef$std_intercept } else { beta <- coef$beta intercept <- coef$intercept } if (!is.null(sparse) && pmatch(sparse[[1L]], 'matrix', nomatch = 0L) == 1L) { if (is(beta, 'dsparseVector')) { return(sparseMatrix(x = c(intercept, beta@x), i = c(1L, 1L + beta@i), j = rep.int(1L, length(beta@i) + 1L), dims = c(beta@length + 1L, 1L), dimnames = list(var_names, NULL))) } else { nz_ind <- which(abs(beta) > .Machine$double.eps) return(sparseMatrix(x = c(intercept, beta[nz_ind]), i = c(1L, 1L + nz_ind), j = rep.int(1L, length(nz_ind) + 1L), dims = c(length(beta) + 1L, 1L), dimnames = list(var_names, NULL))) } } else if (isTRUE(sparse) || (is.null(sparse) && is(beta, 'dsparseVector'))) { if (is(beta, 'dsparseVector')) { return(sparseVector(c(intercept, beta@x), i = c(1L, beta@i + 1L), length = beta@length + 1L)) } else { return(sparseVector(c(intercept, beta), i = seq_len(length(beta) + 1L), length = length(beta) + 1L)) } } else if (isFALSE(sparse) || (is.null(sparse) && is.numeric(beta))) { coefvec <- c(intercept, as.numeric(beta)) names(coefvec) <- var_names return(coefvec) } else { abort("argument `sparse` must be TRUE/FALSE or \"matrix\".") } }
histPlot <- function(x, col = fadeColor('black', '22'), border = 'black', breaks = "default", probability = FALSE, hollow = FALSE, add = FALSE, lty = 2, lwd = 1, freqTable = FALSE, right = TRUE, axes = TRUE, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, ...){ if(breaks[1] == 'default'){ breaks <- 'Sturges' } if(freqTable){ nObs <- sum(x[, 2]) xR <- range(x[, 1]) xR <- xR + c(-1, 1) * diff(xR) / 10^5 H <- list() if(is.character(breaks)[1]){ breaks <- 10 } if(length(breaks) == 1){ H$breaks <- pretty(xR, n = breaks, min.n = 1) } else { H$breaks <- breaks } H$mids <- H$breaks[-1] - diff(H$breaks) / 2 H$counts <- rep(0, length(H$mids)) for(i in 1:length(H$counts)){ if(right){ c1 <- x[, 1] <= H$breaks[i + 1] c2 <- x[, 1] > H$breaks[i] temp <- which(c1 & c2) } else { c1 <- x[, 1] < H$breaks[i + 1] c2 <- x[, 1] >= H$breaks[i] temp <- which(c1 & c2) } H$counts[i] <- sum(x[temp, 2]) } H$density <- (H$counts / sum(H$counts)) / diff(H$breaks) } else { if(length(breaks) > 1 && is.numeric(breaks)[1]){ H <- graphics::hist(x, breaks = breaks, plot = FALSE, right = right, include.lowest = FALSE) } else { H <- graphics::hist(x, breaks = breaks, plot = FALSE, right = right) } } br <- H$breaks mi <- H$mids y <- H$counts if(probability){ y <- H$density } if(is.null(ylab)){ ylab <- 'frequency' if(probability){ ylab <- 'density' } } if(is.null(xlab)){ xlab <- H$xname } if(is.null(xlim)){ xlim <- range(br) } if(is.null(ylim)){ ylim = c(0, max(y)) } if(!add){ plot(x, xlim = xlim, ylim = ylim, type = 'n', axes = FALSE, ylab = ylab, xlab = xlab, ...) graphics::abline(h = 0) if(axes){ graphics::axis(1) graphics::axis(2) } } if(hollow){ n <- length(H$breaks) br <- c(br[1], br) y <- c(0, y, 0) graphics::points(br, y, type = 's', col = border, lty = lty, lwd = lwd) } else { miL <- length(mi) for(i in 1:miL){ rect(br[i], 0, br[i + 1], y[i], border = ' lines(rep(br[i], 2), c(0, y[i]), col = border) lines(br[i:(i + 1)], rep(y[i], 2), col = border) if(i > 1){ if(y[i] < y[i-1]){ lines(rep(br[i], 2), y[(i - 1):i], col = border) } } } lines(rep(br[miL + 1], 2), c(0, y[miL]), col = border) } }
`[.gtfs` <- function(x, value) { subclass <- setdiff(class(x), c("gtfs", "list")) return(new_gtfs(NextMethod(), subclass = subclass)) }
aldvmm.pred <- function(par, X, y = NULL, psi, ncmp, dist, lcoef, lcpar, lcmp) { parlist <- aldvmm.getpar(par = par, lcoef = lcoef, lcmp = lcmp, lcpar = lcpar, ncmp = ncmp) if (ncmp > 1) { exp_xd <- matrix(data = NA, nrow = nrow(X[[2]]), ncol = (ncmp - 1), dimnames = list(rownames(X[[2]]), paste0(lcmp, 1:(ncmp - 1)))) for (c in 1:(ncmp - 1)) { exp_xd[, c] <- exp(X[[2]] %*% parlist[[lcoef[2]]][[c]]) } p_c <- matrix(data = NA, nrow = nrow(X[[2]]), ncol = ncmp, dimnames = list(rownames(X[[2]]), paste0(lcmp, 1:ncmp))) for (c in 1:(ncmp - 1)) { p_c[, c] <- exp_xd[, c] / (1 + rowSums(exp_xd)) } p_c[, ncmp] <- 1 - rowSums(p_c[, 1:(ncmp - 1), drop = FALSE]) } else { p_c <- matrix(data = 1, nrow = nrow(X[[1]]), ncol = ncmp, dimnames = list(rownames(X[[1]]), paste0(lcmp, 1))) } if (dist == "normal") { ev <- matrix(data = NA, nrow = nrow(X[[1]]), ncol = ncmp, dimnames = list(rownames(X[[1]]), paste0(lcmp, 1:ncmp))) for (c in 1:ncmp) { max <- 1 - stats::pnorm((max(psi) - X[[1]] %*% parlist[[lcoef[1]]][[c]]) / exp(parlist[[lcpar[1]]][[c]]), mean = 0, sd = 1) min <- stats::pnorm((min(psi) - X[[1]] %*% parlist[[lcoef[1]]][[c]]) / exp(parlist[[lcpar[1]]][[c]]), mean = 0, sd = 1) * min(psi) mid_a <- stats::pnorm((max(psi) - X[[1]] %*% parlist[[lcoef[1]]][[c]]) / exp(parlist[[lcpar[1]]][[c]]), mean = 0, sd = 1) mid_b <- stats::pnorm((min(psi) - X[[1]] %*% parlist[[lcoef[1]]][[c]]) / exp(parlist[[lcpar[1]]][[c]]), mean = 0, sd = 1) mid_c <- stats::dnorm((max(psi) - X[[1]] %*% parlist[[lcoef[1]]][[c]]) / exp(parlist[[lcpar[1]]][[c]]), mean = 0, sd = 1) mid_d <- stats::dnorm((min(psi) - X[[1]] %*% parlist[[lcoef[1]]][[c]]) / exp(parlist[[lcpar[1]]][[c]]), mean = 0, sd = 1) mid_e <- stats::pnorm((min(psi) - X[[1]] %*% parlist[[lcoef[1]]][[c]]) / exp(parlist[[lcpar[1]]][[c]]), mean = 0, sd = 1) mid_f <- stats::pnorm((max(psi) - X[[1]] %*% parlist[[lcoef[1]]][[c]]) / exp(parlist[[lcpar[1]]][[c]]), mean = 0, sd = 1) mid <- (mid_a - mid_b) * (X[[1]] %*% parlist[[lcoef[1]]][[c]] + exp(parlist[[lcpar[1]]][[c]]) * (mid_c - mid_d) / (mid_e - mid_f)) ev[, c] <- max + min + mid } } pred <- list() if (any(is.na(p_c))) { warning("fitted probabilities of component membership include missing values\n", call. = FALSE) } pred[["prob"]] <- colMeans(p_c) names(pred[["prob"]]) <- paste0(lcmp, 1:ncmp) pred[["yhat"]] <- rowSums(p_c * ev) names(pred[["yhat"]]) <- rownames(X[[1]]) if (!is.null(y)) { pred[["y"]] <- y names(pred[["y"]]) <- rownames(X[[1]]) pred[["res"]] <- pred[["y"]] - pred[["yhat"]] names(pred[["res"]]) <- rownames(X[[1]]) } if (any(is.na(pred[["yhat"]]))) { warning("fitted values include missing values\n", call. = FALSE) } return(pred) }
skip_on_cran() tbl <- dplyr::tibble( a = 1:5, b = letters[1:5], c = c(3.5, 8.3, 6.7, 9.1, NA_real_) ) test_that("`col_schema_match()` works properly", { schema_obj_i_1 <- col_schema(a = "integer", b = "character", d = "numeric") schema_obj_i_2 <- col_schema(a = "integer", b = "character", c = "character") schema_obj_i_3 <- col_schema(a = "integer", b = "character", c = "numeric", d = "numeric") schema_obj_1_1 <- col_schema(a = "integer", b = "character", c = "numeric") schema_obj_1_1_i <- col_schema(a = "integer_i", b = "character_i", c = "numeric_i") schema_obj_2_1 <- col_schema(b = "character", c = "numeric", a = "integer") schema_obj_2_2 <- col_schema(c = "numeric", a = "integer", b = "character") schema_obj_2_1_i <- col_schema(b = "character_i", c = "numeric_i", a = "integer_i") schema_obj_2_2_i <- col_schema(c = "numeric_i", a = "integer_i", b = "character_i") schema_obj_3_1 <- col_schema(b = "character", c = "numeric") schema_obj_3_2 <- col_schema(a = "integer", b = "character") schema_obj_3_3 <- col_schema(a = "integer", c = "numeric") schema_obj_3_4 <- col_schema(a = "integer") schema_obj_3_5 <- col_schema(b = "character") schema_obj_3_6 <- col_schema(c = "numeric") schema_obj_3_1_i <- col_schema(b = "character_i", c = "numeric_i") schema_obj_3_2_i <- col_schema(a = "integer_i", b = "character_i") schema_obj_3_3_i <- col_schema(a = "integer_i", c = "numeric_i") schema_obj_3_4_i <- col_schema(a = "integer_i") schema_obj_3_5_i <- col_schema(b = "character_i") schema_obj_3_6_i <- col_schema(c = "numeric_i") schema_obj_4_1 <- col_schema(b = "character", c = "numeric") schema_obj_4_2 <- col_schema(c = "numeric", b = "character") schema_obj_4_3 <- col_schema(a = "integer", b = "character") schema_obj_4_4 <- col_schema(b = "character", a = "integer") schema_obj_4_5 <- col_schema(a = "integer", c = "numeric") schema_obj_4_6 <- col_schema(c = "numeric", a = "integer") schema_obj_4_1_i <- col_schema(b = "character_i", c = "numeric_i") schema_obj_4_2_i <- col_schema(c = "numeric_i", b = "character_i") schema_obj_4_3_i <- col_schema(a = "integer_i", b = "character_i") schema_obj_4_4_i <- col_schema(b = "character_i", a = "integer_i") schema_obj_4_5_i <- col_schema(a = "integer_i", c = "numeric_i") schema_obj_4_6_i <- col_schema(c = "integer_i", a = "numeric_i") expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_1_1, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_1_1_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_2_1, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_2_2, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_2_1_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_2_2_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_1, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_2, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_3, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_4, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_5, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_6, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_1_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_2_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_3_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_4_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_5_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_6_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_1, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_2, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_3, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_4, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_5, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_6, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_1_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_2_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_3_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_4_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_5_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_6_i, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_1, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_2, complete = TRUE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_3, complete = TRUE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_2_1, complete = TRUE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_2_2, complete = TRUE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_1_1, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_2_1_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_2_2_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_1, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_2, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_3, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_4, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_5, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_6, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_1_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_2_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_3_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_4_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_5_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_6_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_1, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_2, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_3, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_4, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_5, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_6, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_1_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_2_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_3_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_4_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_5_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_6_i, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_1, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_2, complete = TRUE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_3, complete = TRUE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_1, complete = FALSE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_2, complete = FALSE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_3, complete = FALSE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_4, complete = FALSE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_5, complete = FALSE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_6, complete = FALSE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_1_1, complete = FALSE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_4_1, complete = FALSE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_4_3, complete = FALSE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_4_5, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_1_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_2_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_3_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_4_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_5_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_3_6_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_2_1, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_2_2, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_2, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_4, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_6, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_1_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_2_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_3_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_4_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_5_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_4_6_i, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_1, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_2, complete = FALSE, in_order = TRUE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_3, complete = FALSE, in_order = TRUE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_4_1, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_4_2, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_4_3, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_4_4, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_4_5, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_4_6, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_1_1, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_2_1, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_2_2, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_1, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_2, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_3, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_4, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_5, complete = FALSE, in_order = FALSE)) expect_error(regexp = NA, tbl %>% col_schema_match(schema_obj_3_6, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_2_1_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_2_2_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_1_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_2_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_3_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_4_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_5_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_3_6_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_1_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_2_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_3_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_4_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_5_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_4_6_i, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_1, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_2, complete = FALSE, in_order = FALSE)) expect_error(tbl %>% col_schema_match(schema_obj_cnc_3, complete = FALSE, in_order = FALSE)) })
.set.btt <- function(btt, p, int.incl, Xnames) { mstyle <- .get.mstyle("crayon" %in% .packages()) if (missing(btt) || is.null(btt)) { if (p > 1L) { if (int.incl) { btt <- seq.int(from=2, to=p) } else { btt <- seq_len(p) } } else { btt <- 1 } } else { if (is.character(btt)) { btt <- grep(btt, Xnames) if (length(btt) == 0L) stop(mstyle$stop("Cannot identify coefficient(s) corresponding to the specified 'btt' string.")) } else { btt <- sort(unique(round(btt))) if (any(btt < 0) && any(btt > 0)) stop(mstyle$stop("Cannot mix positive and negative 'btt' values.")) btt <- seq_len(p)[btt] btt <- btt[!is.na(btt)] if (length(btt) == 0L) stop(mstyle$stop("Non-existent coefficients specified via 'btt'.")) } } return(btt) } .format.btt <- function(btt) { sav <- c() if (length(btt) > 1L) { while (length(btt) > 0L) { x <- rle(diff(btt)) if (x$values[1] == 1 && length(x$values) != 0L) { sav <- c(sav, c(btt[1], ":", btt[x$lengths[1] + 1])) btt <- btt[-c(1:(x$lengths[1] + 1))] sav <- c(sav, ",") } else { sav <- c(sav, btt[1], ",") btt <- btt[-1] } } sav <- paste0(sav[-length(sav)], collapse="") } else { sav <- paste0(btt) } return(sav) } .psort <- function(x,y) { if (is.null(x) || length(x) == 0L) return(NULL) if (missing(y)) { if (is.matrix(x)) { xy <- x } else { xy <- rbind(x) } } else { xy <- cbind(x,y) } n <- nrow(xy) for (i in seq_len(n)) { if (anyNA(xy[i,])) next xy[i,] <- sort(xy[i,]) } colnames(xy) <- NULL return(xy) } .tr <- function(X) return(sum(diag(X))) .is.square <- function(X) NROW(X) == NCOL(X) .is.intercept <- function(x, eps=1e-08) return(all(abs(x - 1) < eps)) .is.dummy <- function(x, eps=1e-08) return(all(abs(x) < eps | abs(x - 1) < eps)) .is.vector <- function(x) is.atomic(x) && !is.matrix(x) && !is.null(x) .pval <- function(p, digits=4, showeq=FALSE, sep="", add0=FALSE) { digits <- max(digits, 1) cutoff <- paste(c(".", rep(0,digits-1),1), collapse="") ncutoff <- as.numeric(cutoff) ifelse(is.na(p), paste0(ifelse(showeq, "=", ""), sep, NA), ifelse(p >= ncutoff, paste0(ifelse(showeq, "=", ""), sep, formatC(p, digits=digits, format="f")), paste0("<", sep, ifelse(add0, "0", ""), cutoff))) } .fcf <- function(x, digits) { if (all(is.na(x))) { x } else { trimws(formatC(x, format="f", digits=digits)) } } .level <- function(level, allow.vector=FALSE) { if (!allow.vector && length(level) != 1L) { mstyle <- .get.mstyle("crayon" %in% .packages()) stop(mstyle$stop("Argument 'level' must specify a single value.")) } ifelse(level == 0, 1, ifelse(level >= 1, (100-level)/100, ifelse(level > .5, 1-level, level))) } .print.vector <- function(x) { if (is.null(names(x))) names(x) <- seq_along(x) len.n <- nchar(names(x)) len.x <- nchar(x, keepNA=FALSE) len.max <- pmax(len.n, len.x) format <- sapply(len.max, function(x) paste("%", x, "s", sep="")) row.n <- paste(mapply(formatC, names(x), width=len.max), collapse=" ") row.x <- paste(mapply(formatC, x, width=len.max), collapse=" ") cat(row.n, "\n", row.x, "\n", sep="") } .space <- function(x=TRUE) { no.rmspace <- !exists(".rmspace") if (no.rmspace && x) cat("\n") } .get.footsym <- function() { if (exists(".footsym")) { fs <- get(".footsym") } else { fs <- c("\u00b9", "1)", "\u00b2", "2)", "\u00b3", "3)") } return(fs) } .print.time <- function(x) { mstyle <- .get.mstyle("crayon" %in% .packages()) hours <- floor(x/60/60) minutes <- floor(x/60) - hours*60 seconds <- round(x - minutes*60 - hours*60*60, ifelse(x > 60, 0, 2)) cat("\n") cat(mstyle$message(paste("Processing time:", hours, ifelse(hours == 0 || hours > 1, "hours,", "hour,"), minutes, ifelse(minutes == 0 || minutes > 1, "minutes,", "minute,"), seconds, ifelse(x < 60 || seconds == 0 || seconds > 1, "seconds", "second")))) cat("\n") } .make.unique <- function(x) { if (is.null(x)) return(NULL) x <- as.character(x) ux <- unique(x) for (i in seq_along(ux)) { xiTF <- x == ux[i] xi <- x[xiTF] if (length(xi) == 1L) next x[xiTF] <- paste(xi, seq_along(xi), sep=".") } return(x) } .chkdots <- function(ddd, okargs) { mstyle <- .get.mstyle("crayon" %in% .packages()) for (i in seq_along(okargs)) ddd[okargs[i]] <- NULL if (length(ddd) > 0L) warning(mstyle$warning(paste0("Extra argument", ifelse(length(ddd) > 1L, "s ", " "), "(", paste0("'", names(ddd), "'", collapse=", "), ") disregarded.")), call.=FALSE) } .getx <- function(x, mf, data, enclos=sys.frame(sys.parent(n=2))) { mstyle <- .get.mstyle("crayon" %in% .packages()) mf.x <- mf[[match(x, names(mf))]] out <- try(eval(mf.x, data, enclos), silent=TRUE) spec <- x %in% names(mf) if (inherits(out, "try-error") || is.function(out)) stop(mstyle$stop(paste0("Cannot find the object/variable ('", deparse(mf.x), "') specified for the '", x, "' argument.")), call.=FALSE) if (spec && is.null(out)) { mf.txt <- deparse(mf.x) if (mf.txt == "NULL") { mf.txt <- " " } else { mf.txt <- paste0(" ('", mf.txt, "') ") } stop(mstyle$stop(paste0(deparse(mf)[1], ":\n The object/variable", mf.txt, "specified for the '", x, "' argument is NULL.")), call.=FALSE) } return(out) } .getfromenv <- function(what, element, envir=.metafor, default=NULL) { x <- try(get(what, envir=envir, inherits=FALSE), silent=TRUE) if (inherits(x, "try-error")) { return(default) } else { if (missing(element)) { return(x) } else { x <- x[[element]] if (is.null(x)) { return(default) } else { return(x) } } } } .do.call <- function(fun, ...) { if (is.list(..1) && ...length() == 1L) { args <- c(...) } else { args <- list(...) } args <- args[!sapply(args, is.null)] do.call(fun, args) } .chkclass <- function(class, must, notap, notav, type="Method") { mstyle <- .get.mstyle("crayon" %in% .packages()) obj <- as.character(match.call()[2]) obj <- substr(obj, 7, nchar(obj)-1) if (!missing(must) && !is.element(must, class)) stop(mstyle$stop(paste0("Argument '", obj, "' must be an object of class \"", must, "\".")), call.=FALSE) if (!missing(notap) && any(is.element(notap, class))) stop(mstyle$stop(paste0(type, " not applicable to objects of class \"", class[1], "\".")), call.=FALSE) if (!missing(notav) && any(is.element(notav, class))) stop(mstyle$stop(paste0(type, " not available for objects of class \"", class[1], "\".")), call.=FALSE) } .equal.length <- function(...) { ddd <- list(...) ddd <- ddd[sapply(ddd, function(x) length(x) > 0)] if (length(ddd) == 0L) { return(TRUE) } else { ks <- lengths(ddd) return(length(unique(ks)) == 1L) } } .all.specified <- function(...) { ddd <- list(...) not0 <- lengths(ddd) != 0L all(not0) } .setlab <- function(measure, transf.char, atransf.char, gentype, short=FALSE) { if (gentype == 1) lab <- "Observed Outcome" if (gentype == 2) lab <- "Overall Estimate" if (gentype == 3) lab <- "Estimate" if (!is.null(measure)) { if (is.element(measure, c("RR","MPRR"))) { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[RR]", "Log Risk Ratio") } else { lab <- ifelse(short, lab, "Transformed Log Risk Ratio") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Risk Ratio", "Risk Ratio (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Risk Ratio", "Risk Ratio") } } if (is.element(measure, c("OR","PETO","D2OR","D2ORN","D2ORL","MPOR","MPORC","MPPETO","MPORM"))) { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[OR]", "Log Odds Ratio") } else { lab <- ifelse(short, lab, "Transformed Log Odds Ratio") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Odds Ratio", "Odds Ratio (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Odds Ratio", "Odds Ratio") } } if (is.element(measure, c("RD","MPRD"))) { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Risk Difference", "Risk Difference") } else { lab <- ifelse(short, lab, "Transformed Risk Difference") } } if (measure == "AS") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Arcsine RD", "Arcsine Transformed Risk Difference") } else { lab <- ifelse(short, lab, "Transformed Arcsine Transformed Risk Difference") } } if (measure == "PHI") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Phi", "Phi Coefficient") } else { lab <- ifelse(short, lab, "Transformed Phi Coefficient") } } if (measure == "YUQ") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Yule's Q", "Yule's Q") } else { lab <- ifelse(short, lab, "Transformed Yule's Q") } } if (measure == "YUY") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Yule's Y", "Yule's Y") } else { lab <- ifelse(short, lab, "Transformed Yule's Y") } } if (measure == "IRR") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[IRR]", "Log Incidence Rate Ratio") } else { lab <- ifelse(short, lab, "Transformed Log Incidence Rate Ratio") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Rate Ratio", "Incidence Rate Ratio (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Rate Ratio", "Incidence Rate Ratio") } } if (measure == "IRD") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "IRD", "Incidence Rate Difference") } else { lab <- ifelse(short, lab, "Transformed Incidence Rate Difference") } } if (measure == "IRSD") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "IRSD", "Square Root Transformed Incidence Rate Difference") } else { lab <- ifelse(short, lab, "Transformed Square Root Transformed Incidence Rate Difference") } } if (measure == "MD") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "MD", "Mean Difference") } else { lab <- ifelse(short, lab, "Transformed Mean Difference") } } if (is.element(measure, c("SMD","SMDH","PBIT","OR2D","OR2DN","OR2DL","SMD1"))) { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "SMD", "Standardized Mean Difference") } else { lab <- ifelse(short, lab, "Transformed Standardized Mean Difference") } } if (measure == "ROM") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[RoM]", "Log Ratio of Means") } else { lab <- ifelse(short, lab, "Transformed Log Ratio of Means") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Ratio of Means", "Ratio of Means (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Ratio of Means", "Ratio of Means") } } if (measure == "RPB") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Correlation", "Point-Biserial Correlation") } else { lab <- ifelse(short, lab, "Transformed Point-Biserial Correlation") } } if (measure == "CVR") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[CVR]", "Log Coefficient of Variation Ratio") } else { lab <- ifelse(short, lab, "Transformed Log Coefficient of Variation Ratio") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "CVR", "Coefficient of Variation Ratio (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "CVR", "Coefficient of Variation Ratio") } } if (measure == "VR") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[VR]", "Log Variability Ratio") } else { lab <- ifelse(short, lab, "Transformed Log Variability Ratio") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "VR", "Variability Ratio (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "VR", "Variability Ratio") } } if (is.element(measure, c("COR","UCOR","RTET","RBIS"))) { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Correlation", "Correlation Coefficient") } else { lab <- ifelse(short, lab, "Transformed Correlation Coefficient") } } if (measure == "ZCOR") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, expression('Fisher\'s ' * z[r]), "Fisher's z Transformed Correlation Coefficient") } else { lab <- ifelse(short, lab, "Transformed Fisher's z Transformed Correlation Coefficient") funlist <- lapply(list(transf.ztor, transf.ztor.int, tanh), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Correlation", "Correlation Coefficient") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Correlation", "Correlation Coefficient") } } if (measure == "PCOR") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Correlation", "Partial Correlation Coefficient") } else { lab <- ifelse(short, lab, "Transformed Partial Correlation Coefficient") } } if (measure == "ZPCOR") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, expression('Fisher\'s ' * z[r]), "Fisher's z Transformed Partial Correlation Coefficient") } else { lab <- ifelse(short, lab, "Transformed Fisher's z Transformed Partial Correlation Coefficient") funlist <- lapply(list(transf.ztor, transf.ztor.int, tanh), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Correlation", "Partial Correlation Coefficient") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Correlation", "Partial Correlation Coefficient") } } if (measure == "SPCOR") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Correlation", "Semi-Partial Correlation Coefficient") } else { lab <- ifelse(short, lab, "Transformed Semi-Partial Correlation Coefficient") } } if (measure == "PR") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Proportion", "Proportion") } else { lab <- ifelse(short, lab, "Transformed Proportion") } } if (measure == "PLN") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[Pr]", "Log Proportion") } else { lab <- ifelse(short, lab, "Transformed Log Proportion") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Proportion", "Proportion (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Proportion", "Proportion") } } if (measure == "PLO") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[Odds]", "Log Odds") } else { lab <- ifelse(short, lab, "Transformed Log Odds") funlist <- lapply(list(transf.ilogit, transf.ilogit.int, plogis), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Proportion", "Proportion (logit scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Proportion", "Proportion") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Odds", "Odds (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Odds", "Odds") } } if (measure == "PAS") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, expression(arcsin(sqrt(p))), "Arcsine Transformed Proportion") } else { lab <- ifelse(short, lab, "Transformed Arcsine Transformed Proportion") funlist <- lapply(list(transf.iarcsin), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Proportion", "Proportion (arcsine scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Proportion", "Proportion") } } if (measure == "PFT") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "PFT", "Double Arcsine Transformed Proportion") } else { lab <- ifelse(short, lab, "Transformed Double Arcsine Transformed Proportion") funlist <- lapply(list(transf.ipft.hm), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Proportion", "Proportion") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Proportion", "Proportion") } } if (measure == "IR") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Rate", "Incidence Rate") } else { lab <- ifelse(short, lab, "Transformed Incidence Rate") } } if (measure == "IRLN") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[IR]", "Log Incidence Rate") } else { lab <- ifelse(short, lab, "Transformed Log Incidence Rate") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Rate", "Incidence Rate (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Rate", "Incidence Rate") } } if (measure == "IRS") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Sqrt[IR]", "Square Root Transformed Incidence Rate") } else { lab <- ifelse(short, lab, "Transformed Square Root Transformed Incidence Rate") funlist <- lapply(list(transf.isqrt, atransf.char), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Rate", "Incidence Rate (square root scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Rate", "Incidence Rate") } } if (measure == "IRFT") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "IRFT", "Freeman-Tukey Transformed Incidence Rate") } else { lab <- ifelse(short, lab, "Transformed Freeman-Tukey Transformed Incidence Rate") } } if (measure == "MN") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Mean", "Mean") } else { lab <- ifelse(short, lab, "Transformed Mean") } } if (measure == "MNLN") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[Mean]", "Log Mean") } else { lab <- ifelse(short, lab, "Transformed Log Mean") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Mean", "Mean (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Mean", "Mean") } } if (measure == "CVLN") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[CV]", "Log Coefficient of Variation") } else { lab <- ifelse(short, lab, "Transformed Log Coefficient of Variation") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "CV", "Coefficient of Variation (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "CV", "Coefficient of Variation") } } if (measure == "SDLN") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[SD]", "Log Standard Deviation") } else { lab <- ifelse(short, lab, "Transformed Log Standard Deviation") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "SD", "Standard Deviation (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "SD", "Standard Deviation") } } if (measure == "MC") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Mean Change", "Mean Change") } else { lab <- ifelse(short, lab, "Transformed Mean Change") } } if (is.element(measure, c("SMCC","SMCR","SMCRH"))) { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "SMC", "Standardized Mean Change") } else { lab <- ifelse(short, lab, "Transformed Standardized Mean Change") } } if (measure == "ROMC") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[RoM]", "Log Ratio of Means") } else { lab <- ifelse(short, lab, "Transformed Log Ratio of Means") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Ratio of Means", "Ratio of Means (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Ratio of Means", "Ratio of Means") } } if (measure == "CVRC") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[CVR]", "Log Coefficient of Variation Ratio") } else { lab <- ifelse(short, lab, "Transformed Log Coefficient of Variation Ratio") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "CVR", "Coefficient of Variation Ratio (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "CVR", "Coefficient of Variation Ratio") } } if (measure == "VRC") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Log[VR]", "Log Variability Ratio") } else { lab <- ifelse(short, lab, "Transformed Log Variability Ratio") funlist <- lapply(list(exp, transf.exp.int), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "VR", "Variability Ratio (log scale)") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "VR", "Variability Ratio") } } if (measure == "ARAW") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, "Alpha", "Cronbach's alpha") } else { lab <- ifelse(short, lab, "Transformed Cronbach's alpha") } } if (measure == "AHW") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, expression('Alpha'[HW]), "Transformed Cronbach's alpha") } else { lab <- ifelse(short, lab, "Transformed Cronbach's alpha") funlist <- lapply(list(transf.iahw), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Alpha", "Cronbach's alpha") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Alpha", "Cronbach's alpha") } } if (measure == "ABT") { if (identical(transf.char, "FALSE") && identical(atransf.char, "FALSE")) { lab <- ifelse(short, expression('Alpha'[B]), "Transformed Cronbach's alpha") } else { lab <- ifelse(short, lab, "Transformed Cronbach's alpha") funlist <- lapply(list(transf.iabt), deparse) if (any(sapply(funlist, identical, atransf.char))) lab <- ifelse(short, "Alpha", "Cronbach's alpha") if (any(sapply(funlist, identical, transf.char))) lab <- ifelse(short, "Alpha", "Cronbach's alpha") } } } return(lab) } .get.mstyle <- function(withcrayon) { if (withcrayon) { if (exists(".mstyle")) { .mstyle <- get(".mstyle") if (!is.list(.mstyle)) .mstyle <- list(.mstyle) } else { .mstyle <- list() } if (is.null(.mstyle$section)) { section <- crayon::bold } else { section <- .mstyle$section } if (is.null(.mstyle$header)) { header <- crayon::underline } else { header <- .mstyle$header } if (is.null(.mstyle$body1)) { body1 <- crayon::reset } else { body1 <- .mstyle$body1 } if (is.null(.mstyle$body2)) { body2 <- crayon::reset } else { body2 <- .mstyle$body2 } if (is.null(.mstyle$na)) { na <- crayon::reset } else { na <- .mstyle$na } if (is.null(.mstyle$text)) { text <- crayon::reset } else { text <- .mstyle$text } if (is.null(.mstyle$result)) { result <- crayon::reset } else { result <- .mstyle$result } if (is.null(.mstyle$stop)) { stop <- crayon::combine_styles(crayon::red, crayon::bold) } else { stop <- .mstyle$stop } if (is.null(.mstyle$warning)) { warning <- crayon::yellow } else { warning <- .mstyle$warning } if (is.null(.mstyle$message)) { message <- crayon::green } else { message <- .mstyle$message } if (is.null(.mstyle$verbose)) { verbose <- crayon::cyan } else { verbose <- .mstyle$verbose } if (is.null(.mstyle$legend)) { legend <- crayon::silver } else { legend <- .mstyle$legend } } else { tmp <- function(...) paste0(...) section <- tmp header <- tmp body1 <- tmp body2 <- tmp na <- tmp text <- tmp result <- tmp stop <- tmp warning <- tmp message <- tmp verbose <- tmp legend <- tmp } return(list(section=section, header=header, body1=body1, body2=body2, na=na, text=text, result=result, stop=stop, warning=warning, message=message, verbose=verbose, legend=legend)) } .print.output <- function(x, mstyle) { if (missing(mstyle)) { for (i in seq_along(x)) { cat(x[i], "\n") } } else { for (i in seq_along(x)) { cat(mstyle(x[i]), "\n") } } } .is.even <- function(x) x %% 2 == 0 .print.table <- function(x, mstyle) { is.header <- !grepl(" [-0-9]", x) has.header <- any(is.header) for (i in seq_along(x)) { if (is.header[i]) { x[i] <- trimws(x[i], which="right") x[i] <- mstyle$header(x[i]) } else { x[i] <- gsub("NA", mstyle$na("NA"), x[i], fixed=TRUE) if (.is.even(i-has.header)) { x[i] <- mstyle$body2(x[i]) } else { x[i] <- mstyle$body1(x[i]) } } cat(x[i], "\n") } } .set.digits <- function(digits, dmiss) { res <- c(est=4, se=4, test=4, pval=4, ci=4, var=4, sevar=4, fit=4, het=4) if (exists(".digits")) { .digits <- get(".digits") if (is.null(names(.digits)) && length(.digits) == 1L) { res <- c(est=.digits, se=.digits, test=.digits, pval=.digits, ci=.digits, var=.digits, sevar=.digits, fit=.digits, het=.digits) } else if (any(names(.digits) != "") && any(names(.digits) == "")) { pos <- pmatch(names(.digits), names(res)) res[c(na.omit(pos))] <- .digits[!is.na(pos)] otherval <- .digits[names(.digits) == ""][1] res[(1:9)[-c(na.omit(pos))]] <- otherval } else { pos <- pmatch(names(.digits), names(res)) res[c(na.omit(pos))] <- .digits[!is.na(pos)] } } if (!dmiss) { if (is.null(names(digits))) { res <- c(est=digits[[1]], se=digits[[1]], test=digits[[1]], pval=digits[[1]], ci=digits[[1]], var=digits[[1]], sevar=digits[[1]], fit=digits[[1]], het=digits[[1]]) } else { pos <- pmatch(names(digits), names(res)) res[c(na.omit(pos))] <- digits[!is.na(pos)] } } if (res["pval"] <= 1) res["pval"] <- 2 res } .get.digits <- function(digits, xdigits, dmiss) { res <- xdigits if (exists(".digits")) { .digits <- get(".digits") pos <- pmatch(names(.digits), names(res)) res[c(na.omit(pos))] <- .digits[!is.na(pos)] } if (!dmiss) { if (is.null(names(digits))) { res <- c(est=digits[[1]], se=digits[[1]], test=digits[[1]], pval=digits[[1]], ci=digits[[1]], var=digits[[1]], sevar=digits[[1]], fit=digits[[1]], het=digits[[1]]) } else { pos <- pmatch(names(digits), names(res)) res[c(na.omit(pos))] <- digits[!is.na(pos)] } } if (length(res) == 1L && is.null(names(res))) res <- c(est=res[[1]], se=res[[1]], test=res[[1]], pval=res[[1]], ci=res[[1]], var=res[[1]], sevar=res[[1]], fit=res[[1]], het=res[[1]]) if (!is.null(res["pval"]) && res["pval"] <= 1) res["pval"] <- 2 res } .isTRUE <- function(x) !is.null(x) && is.logical(x) && !is.na(x) && x .isFALSE <- function(x) !is.null(x) && is.logical(x) && !is.na(x) && !x .glmulti <- str2expression(" if (!(\"glmulti\" %in% .packages())) stop(\"Must load the 'glmulti' package first to use this code.\") setOldClass(\"rma.uni\") setMethod(\"getfit\", \"rma.uni\", function(object, ...) { if (object$test==\"z\") { cbind(estimate=coef(object), se=sqrt(diag(vcov(object))), df=Inf) } else { cbind(estimate=coef(object), se=sqrt(diag(vcov(object))), df=object$k-object$p) } }) setOldClass(\"rma.mv\") setMethod(\"getfit\", \"rma.mv\", function(object, ...) { if (object$test==\"z\") { cbind(estimate=coef(object), se=sqrt(diag(vcov(object))), df=Inf) } else { cbind(estimate=coef(object), se=sqrt(diag(vcov(object))), df=object$k-object$p) } }) setOldClass(\"rma.glmm\") setMethod(\"getfit\", \"rma.glmm\", function(object, ...) { if (object$test==\"z\") { cbind(estimate=coef(object), se=sqrt(diag(vcov(object))), df=Inf) } else { cbind(estimate=coef(object), se=sqrt(diag(vcov(object))), df=object$k-object$p) } }) ") .MuMIn <- str2expression(" makeArgs.rma <- function (obj, termNames, comb, opt, ...) { ret <- MuMIn:::makeArgs.default(obj, termNames, comb, opt) names(ret)[1L] <- \"mods\" ret } coefTable.rma <- function (model, ...) { MuMIn:::.makeCoefTable(model$b, model$se, coefNames = rownames(model$b)) } ") .mice <- str2expression(" glance.rma <- function (x, ...) data.frame(df.residual=df.residual(x)) tidy.rma <- function (x, ...) { ret <- coef(summary(x)) colnames(ret)[2] <- \"std.error\" ret$term <- rownames(ret) return(ret) } ") .shorten <- function(x, minlen) { y <- x x <- c(na.omit(x)) n <- length(unique(x)) maxlen <- max(nchar(unique(x))) for (l in seq_len(maxlen)) { tab <- table(x, substr(x, 1, l)) if (nrow(tab) == n && ncol(tab) == n && sum(tab[upper.tri(tab)]) == 0 && sum(tab[lower.tri(tab)]) == 0) break } if (!missing(minlen) && l < minlen) { if (minlen > maxlen) minlen <- maxlen l <- minlen } return(substr(y, 1, l)) } .mvrnorm <- function(n, mu, Sigma) { p <- nrow(Sigma) eS <- eigen(Sigma, symmetric = TRUE) eval <- eS$values evec <- eS$vectors Y <- matrix(rnorm(p * n), nrow = n, byrow = TRUE) %*% t(evec %*% (t(evec) * sqrt(pmax(eval, 0)))) Y <- sweep(Y, 2, mu, "+") return(Y) } .setnafalse <- function(x, arg="subset", k, stoponk0=TRUE) { mstyle <- .get.mstyle("crayon" %in% .packages()) if (is.logical(x)) { x <- x[seq_len(k)] if (anyNA(x)) x[is.na(x)] <- FALSE } if (is.numeric(x)) { if (anyNA(x)) x <- x[!is.na(x)] x <- as.integer(round(x)) x <- x[x != 0L] if (any(x > 0L) && any(x < 0L)) stop(mstyle$stop(paste0("Cannot mix positive and negative values for subsetting.")), call.=FALSE) if (all(x > 0L)) x <- is.element(seq_len(k), x) if (all(x < 0L)) x <- !is.element(seq_len(k), abs(x)) } if (stoponk0 && !any(x)) stop(mstyle$stop(paste0("Stopped because k = 0 after subsetting.")), call.=FALSE) return(x) } .wmean <- function (x, w, na.rm=FALSE) { if (na.rm) { i <- !(is.na(x) | is.na(w)) x <- x[i] w <- w[i] } sum(x*w) / sum(w) } .tes.intfun <- function(x, theta, tau, sei, H0, alternative, crit) { if (alternative == "two.sided") pow <- (pnorm(crit, mean=(x-H0)/sei, sd=1, lower.tail=FALSE) + pnorm(-crit, mean=(x-H0)/sei, sd=1, lower.tail=TRUE)) if (alternative == "greater") pow <- pnorm(crit, mean=(x-H0)/sei, sd=1, lower.tail=FALSE) if (alternative == "less") pow <- pnorm(crit, mean=(x-H0)/sei, sd=1, lower.tail=TRUE) res <- pow * dnorm(x, theta, tau) return(res) } .tes.lim <- function(theta, yi, vi, H0, alternative, alpha, tau2, test, tes.alternative, progbar, tes.alpha, correct, rel.tol, subdivisions, tau2.lb) { pval <- tes(x=yi, vi=vi, H0=H0, alternative=alternative, alpha=alpha, theta=theta, tau2=tau2, test=test, tes.alternative=tes.alternative, progbar=progbar, tes.alpha=tes.alpha, correct=correct, rel.tol=rel.tol, subdivisions=subdivisions, tau2.lb=tau2.lb, find.lim=FALSE)$pval return(pval - tes.alpha) } .fsn.fisher <- function(fsnum, pi, alpha) { k <- length(pi) X2 <- -2*sum(log(c(pi, rep(0.5, fsnum)))) return(pchisq(X2, df=2*(k+fsnum), lower.tail=FALSE) - alpha) } .fsn.fitre <- function(yi, vi) { k <- length(yi) wi <- 1/vi sumwi <- sum(wi) est <- sum(wi*yi)/sumwi Q <- sum(wi * (yi - est)^2) tau2 <- max(0, (Q - (k-1)) / (sumwi - sum(wi^2)/sumwi)) wi <- 1 / (vi + tau2) sumwi <- sum(wi) est <- sum(wi*yi)/sumwi se <- sqrt(1 / sumwi) zval <- est / se pval <- 2*pnorm(abs(zval), lower.tail=FALSE) return(list(est=est, se=se, zval=zval, pval=pval, tau2=tau2)) } .fsn.fitnew <- function(new, yi, vi, vnew, tau2, alpha, iters) { new <- ceiling(new) mus <- rep(NA_real_, iters) pvals <- rep(NA_real_, iters) for (j in seq_len(iters)) { yinew <- c(yi, rnorm(new, 0, sqrt(vnew+tau2))) vinew <- c(vi, rep(vnew, new)) tmp <- .fsn.fitre(yinew, vinew) mus[j] <- tmp$est pvals[j] <- tmp$pval } return(list(mean = mean(mus), rejrate = mean(pvals <= alpha))) } .fsn.re <- function(fsnum, yi, vi, vnew, tau2, target, alpha, iters, verbose=FALSE) { fsnum <- ceiling(fsnum) tmp <- .fsn.fitnew(fsnum, yi, vi, vnew, tau2, alpha, iters) est <- tmp$mean diff <- est - target if (verbose) cat("fsnum =", formatC(fsnum, width=4, format="d"), " est =", .fcf(est, 4), " target =", .fcf(target, 4), " diff =", formatC(diff, format="f", digits=4, flag=" "), "\n") return(diff) }
admedian<- function(b,nf,thresh) { bgmodel<- base::array(0,dim=c(dim(b)[1],dim(b)[2],nf)) for(i in 1:nf) { bgmodel[,,i]=b[,,i] } for(i in 2:dim(b)[3]) { if(i<=(nf+1)) { b[,,i-1]=base::floor(base::abs(b[,,i]-base::apply(bgmodel[,,1:i-1],c(1,2),FUN="median",na.rm=FALSE))) } else { j= (i-1)%%nf if(j!=0) { bgmodel[,,j]=b[,,i-1] } else { bgmodel[,,nf]=b[,,i-1] } b[,,i-1]=base::floor(base::abs(b[,,i] - base::apply(bgmodel,c(1,2),FUN="median",na.rm=FALSE))) } b[,,i-1]<- imager::threshold(b[,,i-1],thr=thresh,approx=TRUE) graphics::plot(imager::as.cimg(b[,,i-1]),main=i) } return (b) }
find_q2 <- function(site_no){ peaks <- suppressWarnings(dataRetrieval::readNWISpeak(siteNumbers = site_no, convertType = FALSE)) flood <- peaks %>% dplyr::mutate_(peak_dt = ~ suppressWarnings(lubridate::ymd(peak_dt)), peak_va = ~ as.numeric(peak_va)) %>% dplyr::filter_(~ !is.na(peak_dt)) %>% dplyr::group_by_(~ site_no) %>% dplyr::mutate_(n = ~ length(site_no)) %>% dplyr::filter_(~ n > 2) %>% dplyr::summarize_(flood_val = ~ construct_prob_plot(peak_va), years = ~ sum(!is.na(peak_va))) %>% dplyr::filter_(~ years >= 20) return(flood) } construct_prob_plot <- function(vals){ vals <- vals[!is.na(vals)] n <- length(vals) if (n < 2) { Q2 <- NA } else { rank <- rank(-vals) prob <- rank / (n + 1) Q2 <- stats::approx(x = prob, y = vals, xout = 0.5) Q2 <- Q2$y } return(Q2) } find_nws <- function(site_no, type = "flood") { if(!is.character(site_no)) stop("Input site_no must be a character") type <- tolower(type) if(type != "action" & type != "flood" & type != "moderate" & type != "major") stop("type must be one of 'action', 'flood', 'moderate', or 'major'") type <- R.utils::capitalize(tolower(type)) type <- paste0(type, "_Q") flood_val <- NWS_flood_discharge %>% dplyr::select_(~ USGS, ~ Action_Q, ~ Flood_Q, ~ Moderate_Q, ~ Major_Q) %>% dplyr::filter_(~ USGS %in% site_no) %>% tidyr::gather_(key_col = "key", value_col = "flood_val", gather_cols = c("Action_Q", "Flood_Q", "Moderate_Q", "Major_Q")) %>% dplyr::filter_(~ key == type & !is.na(flood_val)) %>% dplyr::select_(.dots = list("-key")) %>% dplyr::rename_(.dots = list(site_no = "USGS")) return(flood_val) }
RequestIgnorer <- R6::R6Class( "RequestIgnorer", public = list( LOCALHOST_ALIASES = c('localhost', '127.0.0.1', '0.0.0.0'), ignored_hosts = list(), initialize = function() { private$ignored_hosts_init() self$ignore_request() }, ignore_request = function() { fun <- function(x) { if (is.null(self$ignored_hosts$bucket)) return(FALSE) host <- parseurl(x$uri)$domain %||% NULL if (is.null(host)) return(FALSE) if (!is.null(vcr_c$ignore_hosts)) self$ignore_hosts(vcr_c$ignore_hosts) if (vcr_c$ignore_localhost) self$ignore_localhost() self$ignored_hosts$includes(host) } VCRHooks$define_hook(hook_type = "ignore_request", fun = fun) }, ignore_localhost = function() { self$ignored_hosts$merge(self$LOCALHOST_ALIASES) }, ignore_localhost_value = function(value) { self$ignore_hosts(value) }, ignore_hosts = function(hosts) { self$ignored_hosts$merge(hosts) }, should_be_ignored = function(request) { if (missing(request)) stop("'request' can not be missing") VCRHooks$invoke_hook(hook_type = "ignore_request", args = request) } ), private = list( ignored_hosts_init = function() { self$ignored_hosts <- EnvHash$new() } ) ) EnvHash <- R6::R6Class( "EnvHash", public = list( bucket = c(), print = function(...) { bucks <- self$bucket if (length(bucks) == 0) "" else bucks cat("<ignored hosts>", sep = "\n") cat(paste0(" ", paste0(bucks, collapse = ", ")), sep = "\n") invisible(self) }, merge = function(vals) { self$bucket <- unique(c(self$bucket, vals)) }, includes = function(name) { name %in% self$bucket }, reject = function(fun) { self$bucket <- Filter(Negate(fun), self$bucket) } ) )
context("Testing bats and tbats tidiers") test_that("sw_*.bats test returns tibble with correct rows and columns.", { fit_bats <- WWWusage %>% forecast::bats() test <- sw_tidy(fit_bats) expect_is(test, "tbl") expect_equal(nrow(test), 7) expect_equal(ncol(test), 2) test <- sw_glance(fit_bats) expect_is(test, "tbl") expect_equal(nrow(test), 1) expect_equal(ncol(test), 12) test <- sw_augment(fit_bats, rename_index = "date") expect_is(test, "tbl") expect_equal(nrow(test), 100) expect_equal(ncol(test), 4) expect_equal(colnames(test)[[1]], "date") test <- sw_tidy_decomp(fit_bats) expect_is(test, "tbl") expect_equal(nrow(test), 100) expect_equal(ncol(test), 3) fit_tbats <- USAccDeaths %>% forecast::tbats() test <- sw_tidy(fit_tbats) expect_is(test, "tbl") expect_equal(nrow(test), 8) expect_equal(ncol(test), 2) test <- sw_glance(fit_tbats) expect_is(test, "tbl") expect_equal(nrow(test), 1) expect_equal(ncol(test), 12) test <- sw_augment(fit_tbats, rename_index = "date") expect_is(test, "tbl") expect_equal(nrow(test), 72) expect_equal(ncol(test), 4) expect_equal(colnames(test)[[1]], "date") test <- sw_tidy_decomp(fit_tbats) expect_is(test, "tbl") expect_equal(nrow(test), 72) expect_equal(ncol(test), 5) expect_warning( WWWusage %>% bats() %>% sw_augment(timetk_idx = T) ) monthly_bike_sales <- bike_sales %>% mutate(month.date = as_date(as.yearmon(order.date))) %>% group_by(month.date) %>% summarize(total.daily.sales = sum(price.ext)) monthly_bike_sales_ts <- tk_ts(monthly_bike_sales, start = 2011, freq = 12, silent = TRUE) fit <- bats(monthly_bike_sales_ts) test <- fit %>% sw_augment() expect_equal(class(test$index), "yearmon") test <- fit %>% sw_augment(timetk_idx = T) expect_equal(class(test$index), "Date") test <- fit %>% sw_tidy_decomp() expect_equal(class(test$index), "yearmon") test <- fit %>% sw_tidy_decomp(timetk_idx = T) expect_equal(class(test$index), "Date") data_ts <- USAccDeaths %>% tk_tbl() %>% mutate(index = as_date(index)) %>% tk_ts(start = 1973, freq = 12, silent = TRUE) fit <- tbats(data_ts) test <- fit %>% sw_augment() expect_equal(class(test$index), "yearmon") test <- fit %>% sw_augment(timetk_idx = T) expect_equal(class(test$index), "Date") test <- fit %>% sw_tidy_decomp() expect_equal(class(test$index), "yearmon") test <- fit %>% sw_tidy_decomp(timetk_idx = T) expect_equal(class(test$index), "Date") })
as_xml_document <- function(x, ...) { UseMethod("as_xml_document") } as_xml_document.character <- read_xml.character as_xml_document.raw <- read_xml.raw as_xml_document.connection <- read_xml.connection as_xml_document.response <- read_xml.response as_xml_document.list <- function(x, ...) { if (length(x) > 1) { stop("Root nodes must be of length 1", call. = FALSE) } add_node <- function(x, parent, tag = NULL) { if (is.atomic(x)) { return(.Call(node_new_text, parent$node, as.character(x))) } if (!is.null(tag)) { parent <- xml_add_child(parent, tag) attr <- r_attrs_to_xml(attributes(x)) for (i in seq_along(attr)) { xml_set_attr(parent, names(attr)[[i]], attr[[i]]) } } for (i in seq_along(x)) { add_node(x[[i]], parent, names(x)[[i]]) } } doc <- xml_new_document() add_node(x, doc) xml_root(doc) } as_xml_document.xml_node <- function(x, ...) { xml_new_root(.value = x, ..., .copy = TRUE) } as_xml_document.xml_nodeset <- function(x, root, ...) { doc <- xml_new_root(.value = root, ..., .copy = TRUE) for (i in seq_along(x)) { xml_add_child(doc, x[[i]], .copy = TRUE) } doc } as_xml_document.xml_document <- function(x, ...) { x }
setGeneric(name = "backtest", def = function(object, horizon="6m", data.width="24m", keep.history=F, optim.param=NULL, optim.param.min=1, optim.param.max=10, optim.param.scale=.1, from=NULL, until=NULL, which=NULL, rf=0, printSteps=F) { standardGeneric("backtest") } ) setMethod(f = "backtest", signature = "Strategy", definition = function(object, horizon, data.width, keep.history, optim.param, optim.param.min, optim.param.max, optim.param.scale, from, until, which, rf, printSteps) { if (!is.null(optim.param)) { if (!is.character(optim.param)) stop("Please provide parameter name to be optimized as character!") if (!(is.null(optim.param.min) || is.null(optim.param.max) || is.numeric(optim.param.min) || is.numeric(optim.param.max)) || length(optim.param.min) != length(optim.param) || length(optim.param.max) != length(optim.param) || any(optim.param.min>optim.param.max) ) stop("Please provide optimization parameter minimum and maximum as increasing or equal numerics with correct scaling for each parameter!") if (!all((optim.param.max-optim.param.min)/optim.param.scale >= 1)) warning(paste0("The following parameters will be fixed: ", paste(optim.param[which((optim.param.max-optim.param.min)/optim.param.scale < 1)], collapse=", "))) } else { warning("No parameters to optimize given in optim.params, values of strategy object taken. Performance will be the same as in strategy execution without backtesting.") parameters <- getParameters(object) parameters.numeric <- list() m <- 1 for (i in 1:length(parameters)) { if (is.numeric(parameters[[i]])) { parameters.numeric[m] <- parameters[i] names(parameters.numeric)[m] <- names(parameters[i]) m <- m+1 } } if (length(parameters.numeric) > 0) { optim.param <- names(parameters.numeric) optim.param.min <- optim.param.max <- (1:length(optim.param)) * NA optim.param.scale <- rep(1, length(optim.param)) for (i in 1:length(optim.param)) { optim.param.min[i] <- optim.param.max[i] <- parameters.numeric[[i]] } } else { optim.param <- "pseudo" optim.param.min <- optim.param.max <- optim.param.scale <- 1 } } if (!is.numeric(rf) || length(rf) != 1) stop("Please provide risk free return as numeric (single) value!") prices <- getPrices(object, from=from, until=until, which=which) weights <- getWeights(object, from=from, until=until, which=which, use.backtest=FALSE) strategy <- getStratName(object) indicators <- getIndicators(object) object.name <- deparse(substitute(object)) object.env <- parent.frame() setup <- matrix(ncol=length(optim.param), nrow=3) colnames(setup) <- optim.param rownames(setup) <- c("Minimum", "Maximum", "Scaling") setup[1,] <- optim.param.min setup[2,] <- optim.param.max setup[3,] <- optim.param.scale stratFUN <- getStratFUN(object) rolling.dates <- xts.rollingWindows(prices, data.width, horizon, keep.history) rolling.from <- rolling.dates$start rolling.to <- rolling.dates$end nbPeriods <- length(rolling.to) param.calib_mat <- matrix(nrow=nbPeriods, ncol=length(optim.param)) rownames(param.calib_mat) <- rolling.to colnames(param.calib_mat) <- optim.param param.calib <- as.list(rep(NA, ncol(prices))) names(param.calib) <- colnames(prices) for (i in 1:length(param.calib)) param.calib[[i]] <- as.xts(param.calib_mat) signals <- list() optim.list <- list() for (i in 1:length(optim.param)) { optim.list[[i]] <- seq(optim.param.min[i], optim.param.max[i], optim.param.scale[i]) } names(optim.list) <- optim.param params.grid <- expand.grid(optim.list) sharpeFUN <- function(x, rf, calib.data) { params <- as.list(x) if (printSteps==T) print(paste("Params: ", paste(names(params), params, sep="="))) stratvals <- stratFUN(prices=calib.data, weights=weights[index(calib.data)], indicators=indicators, parameters=params) signals <- stratvals$signals logReturns <- stratvals$logReturns[paste0(index(signals))] returns <- exp(logReturns * signals) - 1 vola <- vapply(returns-rf, sd, 0) vola[vola==0] <- 1 sharpe.ratios <- colMeans(returns-rf)/vola if (printSteps==T) print(paste("Sharpe Ratios: ", paste(paste(names(sharpe.ratios), sharpe.ratios, sep="="), sep=", "))) return(sharpe.ratios) } if (printSteps == T) { print("Period Windows:") print(t(t(apply(cbind(rolling.from, rolling.to), 1, paste, collapse=" until ")))) print("Parameter Combinations:") print(params.grid) } for(tn in 1:nbPeriods) { print(paste0("Period ", tn, " of ", nbPeriods, " started.")) calibration.data <- prices[paste0(rolling.from[tn], "::", rolling.to[tn])] calibration.data <- calibration.data[-nrow(calibration.data),] sharpe.calib <- as.matrix(t(apply(params.grid, 1, sharpeFUN, rf=rf, calib.data=calibration.data))) sharpe.calib.max <- apply(sharpe.calib, 2, max, na.rm=T) names(sharpe.calib.max) <- colnames(prices) param.max <- matrix(nrow=ncol(params.grid), ncol=ncol(prices)) rownames(param.max) <- colnames(params.grid) colnames(param.max) <- colnames(prices) sharpe.calib.which.max <- sharpe.calib*NA for (i in 1:ncol(prices)) { sharpe.calib.which.max[,i] <- sharpe.calib.max[colnames(prices[,i])] == sharpe.calib[,i] param.max[,i] <- as.numeric(params.grid[min(which(sharpe.calib.which.max[,i]==1)),]) } if (tn < nbPeriods) { performance.data <- prices[paste0(rolling.to[tn], "::", rolling.to[tn+1])] performance.data <- performance.data[-nrow(performance.data),] } else { performance.data <- prices[paste0(rolling.to[tn], "::")] } strat.signals <- list() for ( i in 1:ncol(performance.data)) { params.perf <- as.list(param.max[,i]) names(params.perf) <- optim.param if (printSteps==T) { print(paste("Params for out-of-sample for ", colnames(performance.data[,i]), " ", paste(names(params.perf), params.perf, sep="=", collapse=","))) } perf.data <- rbind(calibration.data[,i], performance.data[,i]) stratvals <- stratFUN(perf.data, weights=weights[index(perf.data)], indicators=indicators, parameters=params.perf) signals_o <- stratvals$signals[paste0(index(performance.data))] strat.signals[[i]] <- signals_o } names(strat.signals) <- colnames(performance.data) signals[[tn]] <- as.xts(do.call(cbind, strat.signals)) for (j in 1:length(param.calib)) param.calib[[j]][tn,] <- param.max[,j] } signals.xts <- Reduce(rbind, signals) [email protected] <- signals.xts [email protected] <- param.calib [email protected] <- setup assign(object.name, object, envir=object.env) } )
l_layer_heatImage <-function (widget, x = seq(0, 1, length.out = nrow(z)), y = seq(0, 1, length.out = ncol(z)), z, zlim = range(z[is.finite(z)]), xlim = range(x), ylim = range(y), col = grDevices::heat.colors(12), breaks, oldstyle = FALSE, useRaster, index="end", parent="root", ...) { l_throwErrorIfNotLoonWidget(widget) if (missing(z)) { if (!missing(x)) { if (is.list(x)) { z <- x$z; y <- x$y; x <- x$x } else { if(is.null(dim(x))) stop("argument must be matrix-like") z <- x x <- seq.int(0, 1, length.out = nrow(z)) } } else stop("no 'z' matrix specified") } else if (is.list(x)) { y <- x$y x <- x$x } if (any(!is.finite(x)) || any(!is.finite(y))) stop("'x' and 'y' values must be finite and non-missing") if (any(diff(x) <= 0) || any(diff(y) <= 0)) stop("increasing 'x' and 'y' values expected") if (!is.matrix(z)) stop("'z' must be a matrix") if (!typeof(z) %in% c("logical", "integer", "double")) stop("'z' must be numeric or logical") if (length(x) > 1 && length(x) == nrow(z)) { dx <- 0.5*diff(x) x <- c(x[1L] - dx[1L], x[-length(x)] + dx, x[length(x)] + dx[length(x)-1]) } if (length(y) > 1 && length(y) == ncol(z)) { dy <- 0.5*diff(y) y <- c(y[1L] - dy[1L], y[-length(y)] + dy, y[length(y)] + dy[length(y)-1L]) } if (missing(breaks)) { nc <- length(col) if (!missing(zlim) && (any(!is.finite(zlim)) || diff(zlim) < 0)) stop("invalid z limits") if (diff(zlim) == 0) zlim <- if (zlim[1L] == 0) { c(-1, 1) } else { zlim[1L] + c(-.4, .4)*abs(zlim[1L]) } z <- (z - zlim[1L])/diff(zlim) zi <- if (oldstyle) { floor((nc - 1) * z + 0.5) } else { floor((nc - 1e-5) * z + 1e-7) } zi[zi < 0 | zi >= nc] <- NA } else { if (length(breaks) != length(col) + 1) stop("must have one more break than colour") if (any(!is.finite(breaks))) stop("'breaks' must all be finite") if (is.unsorted(breaks)) { warning("unsorted 'breaks' will be sorted before use") breaks <- sort(breaks) } zi <- .bincode(z, breaks, TRUE, TRUE) - 1L } if (length(x) <= 1) x <- graphics::par("usr")[1L:2] if (length(y) <= 1) y <- graphics::par("usr")[3:4] if (length(x) != nrow(z)+1 || length(y) != ncol(z)+1) stop("dimensions of z are not length(x)(-1) times length(y)(-1)") check_irregular <- function(x, y) { dx <- diff(x) dy <- diff(y) (length(dx) && !isTRUE(all.equal(dx, rep(dx[1], length(dx))))) || (length(dy) && !isTRUE(all.equal(dy, rep(dy[1], length(dy))))) } if (missing(useRaster)) { useRaster <- getOption("preferRaster", FALSE) if (useRaster && check_irregular(x, y)) useRaster <- FALSE if (useRaster) { useRaster <- FALSE ras <- grDevices::dev.capabilities("rasterImage")$rasterImage if(identical(ras, "yes")) useRaster <- TRUE if(identical(ras, "non-missing")) useRaster <- all(!is.na(zi)) } } if (useRaster) { if(check_irregular(x,y)) stop(gettextf("%s can only be used with a regular grid", sQuote("useRaster = TRUE")), domain = NA) if (!is.character(col)) { col <- as.integer(col) stop("integer colors must be non-negative") col[col < 1L] <- NA_integer_ p <- grDevices::palette() col <- p[((col - 1L) %% length(p)) + 1L] } zc <- col[zi + 1L] dim(zc) <- dim(z) zc <- t(zc)[ncol(zc):1L,, drop = FALSE] id <- l_layer_rasterImage(widget, grDevices::as.raster(zc), min(x), min(y), max(x), max(y)) } else { nx <- length(x) x0 <- x[-nx] x1 <- x[-1] ny <- length(y) y0 <- y[-ny] y1 <- y[-1] xcoords <- Map(function(xl, xu){c(xl, xu)}, rep(x0, ny-1), rep(x1, ny-1)) ycoords <- Map(function(yl, yu){c(yl, yu)}, rep(y0, each=nx-1), rep(y1, each=nx-1)) color <- substr(col[as.vector(zi)+1],1,7) id <- l_layer_rectangles(widget, x=xcoords, y=ycoords, color=color, linecolor="", parent = parent, index=index, ...) } return(id) }
context("getRequiredParamNames") test_that("getRequiredParamNames", { ps = makeParamSet( makeIntegerParam("a", default = 1L), makeIntegerParam("b", default = 1L, requires = quote(a == 1)), makeIntegerParam("c", default = 1L, requires = quote(a == 2 && b == 1)) ) expect_equal(getRequiredParamNames(ps), c("a", "b")) ps2 = filterParams(ps, ids = c("b", "c")) expect_equal(getRequiredParamNames(ps2), c("a", "b")) ps2 = filterParams(ps, ids = c("c")) expect_equal(getRequiredParamNames(ps2), c("a", "b")) ps2 = filterParams(ps, ids = character(0)) expect_equal(getRequiredParamNames(ps2), character(0)) })
vault_client_kv2 <- R6::R6Class( "vault_client_kv2", inherit = vault_client_object, cloneable = FALSE, private = list( api_client = NULL, mount = NULL, validate_path = function(path, mount, zero_length_ok = FALSE) { path <- sub("^/", "", path) mount <- mount %||% private$mount if (!string_starts_with(path, mount)) { stop(sprintf( "Invalid mount given for this path - expected '%s'", mount)) } relative <- substr(path, nchar(mount) + 2, nchar(path)) if (!zero_length_ok && !nzchar(relative)) { stop("Invalid path") } list(mount = mount, relative = relative, data = sprintf("/%s/data/%s", mount, relative), metadata = sprintf("/%s/metadata/%s", mount, relative), delete = sprintf("/%s/delete/%s", mount, relative), undelete = sprintf("/%s/undelete/%s", mount, relative), destroy = sprintf("/%s/destroy/%s", mount, relative)) }, validate_version = function(version, multiple_allowed = FALSE) { if (is.null(version)) { NULL } else { if (multiple_allowed) { assert_integer(version) list(versions = I(version)) } else { assert_scalar_integer(version) list(version = version) } } } ), public = list( initialize = function(api_client, mount) { super$initialize("Interact with vault's key/value store (version 2)") assert_scalar_character(mount) private$mount <- sub("^/", "", mount) private$api_client <- api_client }, config = function(mount = NULL) { path <- sprintf("%s/config", mount %||% private$mount) private$api_client$GET(path)$data }, custom_mount = function(mount) { vault_client_kv2$new(private$api_client, mount) }, delete = function(path, version = NULL, mount = NULL) { path <- private$validate_path(path, mount) if (is.null(version)) { private$api_client$DELETE(path$data) } else { body <- private$validate_version(version, TRUE) private$api_client$POST(path$delete, body = body) } invisible(NULL) }, destroy = function(path, version, mount = NULL) { path <- private$validate_path(path, mount) body <- private$validate_version(version, TRUE) private$api_client$POST(path$destroy, body = body) invisible(NULL) }, get = function(path, version = NULL, field = NULL, metadata = FALSE, mount = NULL) { path <- private$validate_path(path, mount) query <- private$validate_version(version) assert_scalar_logical(metadata) assert_scalar_character_or_null(field) res <- tryCatch( private$api_client$GET(path$data, query = query), vault_invalid_path = function(e) NULL) if (is.null(res)) { return(NULL) } ret <- res$data$data if (!is.null(field)) { ret <- ret[[field]] } else if (metadata) { attr(ret, "metadata") <- res$data$metadata } ret }, list = function(path, full_names = FALSE, mount = NULL) { path <- private$validate_path(path, mount, TRUE) res <- tryCatch( private$api_client$LIST(path$metadata), vault_invalid_path = function(e) NULL) ret <- list_to_character(res$data$keys) if (full_names) { ret <- paste(sub("/+$", "", path$mount), ret, sep = "/") } ret }, metadata_get = function(path, mount = NULL) { path <- private$validate_path(path, mount) res <- tryCatch( private$api_client$GET(path$metadata), vault_invalid_path = function(e) NULL) if (is.null(res)) { return(NULL) } res$data }, metadata_put = function(path, cas_required = NULL, max_versions = NULL, mount = NULL) { path <- private$validate_path(path, mount) body <- drop_null(list( cas_required = cas_required, max_versions = max_versions)) private$api_client$POST(path$metadata, body = body) invisible(NULL) }, metadata_delete = function(path, mount = NULL) { path <- private$validate_path(path, mount) private$api_client$DELETE(path$metadata) invisible(NULL) }, put = function(path, data, cas = NULL, mount = NULL) { assert_named(data) body <- list(data = data) if (!is.null(cas)) { assert_scalar_integer(cas) body$options <- list(cas = cas) } path <- private$validate_path(path, mount) ret <- private$api_client$POST(path$data, body = body) invisible(ret$data) }, undelete = function(path, version, mount = NULL) { path <- private$validate_path(path, mount) body <- private$validate_version(version, TRUE) private$api_client$POST(path$undelete, body = body) invisible(NULL) } ))
theme_hc <- function(base_size = 12, base_family = "sans", style = c("default", "darkunica"), bgcolor = NULL) { if (!is.null(bgcolor)) { warning("`bgcolor` is deprecated. Use `style` instead.") style <- bgcolor } style <- match.arg(style) bgcolor <- switch(style, default = " "darkunica" = " ret <- theme(rect = element_rect(fill = bgcolor, linetype = 0, colour = NA), text = element_text(size = base_size, family = base_family), title = element_text(hjust = 0.5), axis.title.x = element_text(hjust = 0.5), axis.title.y = element_text(hjust = 0.5), panel.grid.major.y = element_line(colour = " panel.grid.minor.y = element_blank(), panel.grid.major.x = element_blank(), panel.grid.minor.x = element_blank(), panel.border = element_blank(), panel.background = element_blank(), legend.position = "bottom", legend.key = element_rect(fill = " if (style == "darkunica") { ret <- (ret + theme(rect = element_rect(fill = bgcolor), text = element_text(colour = " title = element_text(colour = " axis.title.x = element_text(colour = " axis.title.y = element_text(colour = " panel.grid.major.y = element_line(colour = " legend.title = element_text(colour = " } ret } hc_pal <- function(palette = "default") { if (palette %in% names(ggthemes::ggthemes_data$hc)) { manual_pal(unname(ggthemes::ggthemes_data$hc[[palette]])) } else { stop("Palette `", palette, "` not valid. Must be one of ", stringr::str_c("`", names(ggthemes::ggthemes_data$hc), "`", collapse = ", "), call. = FALSE) } } scale_colour_hc <- function(palette = "default", ...) { discrete_scale("colour", "hc", hc_pal(palette), ...) } scale_color_hc <- scale_colour_hc scale_fill_hc <- function(palette = "default", ...) { discrete_scale("fill", "hc", hc_pal(palette), ...) }
get.oc.comb.kb <- function(target, p.true, ncohort, cohortsize, n.earlystop = 100, marginL = 0.05, marginR = 0.05, startdose = c(1, 1), cutoff.eli = 0.95, extrasafe = FALSE, offset = 0.05, ntrial = 1000) { JJ = nrow(p.true) KK = ncol(p.true) if (JJ > KK) { stop("p.true should be arranged in a way such that the number of rows", " is less than or equal to the number of columns (i.e. rotated).") } if (target < 0.05) { stop("The target is too low.") } if (target > 0.6) { stop("The target is too high.") } if (offset >= 0.5) { stop("The offset is too large.") } if (n.earlystop <= 6) { stop("The value of n.earlystop is too low to ensure good operating ", "characteristics.\n ", "n.earlystop = 9 to 18 is recommended.") } set.seed(6) ndose = length(p.true) npts = ncohort * cohortsize Y <- array(matrix(rep(0, length(p.true) * ntrial), dim(p.true)[1]), dim = c(dim(p.true), ntrial)) N <- array(matrix(rep(0, length(p.true) * ntrial), dim(p.true)[1]), dim = c(dim(p.true), ntrial)) dselect = matrix(rep(0, 2 * ntrial), ncol = 2) total.incoherent.dlt = rep(0,ntrial) total.incoherent.no.dlt = rep(0,ntrial) total.incoherent = rep(0,ntrial) total.long.incoherent.dlt = rep(0,ntrial) total.long.incoherent.no.dlt = rep(0,ntrial) total.long.incoherent = rep(0,ntrial) temp = get.boundary.comb.kb(target, ncohort, cohortsize, cutoff.eli=0.95)$boundary b.e = temp[2, ] b.d = temp[3, ] b.elim = temp[4, ] for (trial in 1:ntrial) { y <- matrix(rep(0, ndose), dim(p.true)[1], dim(p.true)[2]) n <- matrix(rep(0, ndose), dim(p.true)[1], dim(p.true)[2]) incoherent.dlt = incoherent.no.dlt = 0 long.incoherent.dlt = long.incoherent.no.dlt = 0 earlystop = 0 d = startdose elimi = matrix(rep(0, ndose), dim(p.true)[1], dim(p.true)[2]) for (pp in 1:ncohort) { y.current <- y[d[1], d[2]] y[d[1], d[2]] = y[d[1], d[2]] + sum(runif(cohortsize) < p.true[d[1], d[2]]) n[d[1], d[2]] = n[d[1], d[2]] + cohortsize if (n[d[1], d[2]] >= n.earlystop) { break } nc = n[d[1], d[2]] if (!is.na(b.elim[nc])) { if (y[d[1], d[2]] >= b.elim[nc]) { for (i in min(d[1], dim(p.true)[1]):dim(p.true)[1]) { for (j in min(d[2], dim(p.true)[2]):dim(p.true)[2]) { elimi[i, j] = 1 } } if (d[1] == 1 && d[2] == 1) { d = c(99, 99) earlystop = 1 break } } if (extrasafe) { if (d[1] == 1 && d[2] == 1 && n[1, 1] >= 3) { if (1 - pbeta(target, y[1, 1] + 1, n[1, 1] - y[1, 1] + 1) > cutoff.eli - offset) { d = c(99, 99) earlystop = 1 break } } } } if (y[d[1], d[2]] <= b.e[nc]) { elevel = matrix(c(1, 0, 0, 1), 2) pr_H0 = rep(0, length(elevel) / 2) nn = pr_H0 for (i in seq(1, length(elevel) / 2, by = 1)) { if (d[1] + elevel[1, i] <= dim(p.true)[1] && d[2] + elevel[2, i] <= dim(p.true)[2]) { if (elimi[d[1] + elevel[1, i], d[2] + elevel[2, i]] == 0) { yn = y[d[1] + elevel[1, i], d[2] + elevel[2, i]] nn[i] = n[d[1] + elevel[1, i], d[2] + elevel[2, i]] pr_H0[i] <- pbeta(target+marginR, yn + 0.5, nn[i] - yn + 0.5) - pbeta(target-marginL, yn + 0.5, nn[i] - yn + 0.5) } } } pr_H0 = pr_H0 + nn * 5e-04 if (max(pr_H0) == 0) { d = d } else { if ((y[d[1], d[2]] - y.current) > 0) { incoherent.dlt <- incoherent.dlt + 1 } if (y[d[1], d[2]] / n[d[1], d[2]] > target + marginR) { long.incoherent.dlt <- long.incoherent.dlt+1 } k = which(pr_H0 == max(pr_H0))[as.integer(runif(1) * length(which(pr_H0 == max(pr_H0))) + 1)] d = d + c(elevel[1, k], elevel[2, k]) } } else if (y[d[1], d[2]] >= b.d[nc]) { delevel = matrix(c(-1, 0, 0, -1), 2) pr_H0 = rep(0, length(delevel) / 2) nn = pr_H0 for (i in seq(1, length(delevel) / 2, by = 1)) { if (d[1] + delevel[1, i] > 0 && d[2] + delevel[2, i] > 0) { yn = y[d[1] + delevel[1, i], d[2] + delevel[2, i]] nn[i] = n[d[1] + delevel[1, i], d[2] + delevel[2, i]] pr_H0[i] = pbeta(target + marginR, yn + 0.5, nn[i] - yn + 0.5) - pbeta(target - marginL, yn + 0.5, nn[i] - yn + 0.5) } } pr_H0 = pr_H0 + nn * 5e-04 if (max(pr_H0) == 0) { d = d } else { if ((y[d[1], d[2]] - y.current) == 0) { incoherent.no.dlt <- incoherent.no.dlt + 1 } if (y[d[1], d[2]] / n[d[1], d[2]] < target - marginL) { long.incoherent.no.dlt <- long.incoherent.no.dlt + 1 } k = which(pr_H0 == max(pr_H0))[as.integer(runif(1) * length(which(pr_H0 == max(pr_H0))) + 1)] d = d + c(delevel[1, k], delevel[2, k]) } } else { d = d } } Y[, , trial] = y N[, , trial] = n total.incoherent.dlt[trial] = incoherent.dlt total.incoherent.no.dlt[trial] = incoherent.no.dlt total.incoherent[trial] = incoherent.dlt + incoherent.no.dlt total.long.incoherent.dlt[trial] = long.incoherent.dlt total.long.incoherent.no.dlt[trial] = long.incoherent.no.dlt total.long.incoherent[trial] = long.incoherent.dlt + long.incoherent.no.dlt if (earlystop == 1) { dselect[trial, ] = c(99, 99) } else { select.mtd.comb <- function (target, npts, ntox, cutoff.eli = 0.95, extrasafe = FALSE, offset = 0.05, mtd.contour = FALSE) { y = ntox n = npts if (nrow(n) > ncol(n) | nrow(y) > ncol(y)) { stop("npts and ntox should be arranged in a way (i.e., rotated) such that for each of them, the number of rows is less than or equal to the number of columns.") } elimi = matrix(0, dim(n)[1], dim(n)[2]) if (extrasafe) { if (n[1, 1] >= 3) { if (1 - pbeta(target, y[1, 1] + 1, n[1, 1] - y[1, 1] + 1) > cutoff.eli - offset) { elimi[, ] = 1 } } } for (i in 1:dim(n)[1]) { for (j in 1:dim(n)[2]) { if (n[i, j] >= 3) { if (1 - pbeta(target, y[i, j] + 1, n[i, j] - y[i, j] + 1) > cutoff.eli) { elimi[i:dim(n)[1], j] = 1 elimi[i, j:dim(n)[2]] = 1 break } } } } if (elimi[1] == 1) { selectdose = c(99, 99) selectdoses = matrix(selectdose, nrow = 1) } else { phat = (y + 0.05)/(n + 0.1) phat = Iso::biviso(phat, n + 0.1, warn = TRUE)[, ] phat.out = phat phat.out[n == 0] = NA phat[elimi == 1] = 1.1 phat = phat * (n != 0) + (1e-05) * (matrix(rep(1:dim(n)[1], each = dim(n)[2], len = length(n)), dim(n)[1], byrow = T) + matrix(rep(1:dim(n)[2], each = dim(n)[1], len = length(n)), dim(n)[1])) phat[n == 0] = 10 selectdose = which(abs(phat - target) == min(abs(phat - target)), arr.ind = TRUE) if (length(selectdose) > 2) selectdose = selectdose[1, ] aa = function(x) as.numeric(as.character(x)) if (mtd.contour == TRUE) { selectdoses = cbind(row = 1:dim(n)[1], col = rep(99, dim(n)[1])) for (k in dim(n)[1]:1) { kn = n[k, ] ky = y[k, ] kelimi = elimi[k, ] kphat = phat[k, ] if (kelimi[1] == 1 || sum(n[kelimi == 0]) == 0) { kseldose = 99 } else { adm.set = (kn != 0) & (kelimi == 0) adm.index = which(adm.set == T) y.adm = ky[adm.set] n.adm = kn[adm.set] selectd = sort(abs(kphat[adm.set] - target), index.return = T)$ix[1] kseldose = adm.index[selectd] } selectdoses[k, 2] = ifelse(is.na(kseldose), 99, kseldose) if (k < dim(n)[1]) if (selectdoses[k + 1, 2] == dim(n)[2]) selectdoses[k, 2] = dim(n)[2] if (k < dim(n)[1]) if (aa(selectdoses[k + 1, 2]) == dim(n)[2] & aa(selectdoses[k + 1, 2]) == aa(selectdoses[k, 2])) selectdoses[k, 2] = 99 } } else { selectdoses = matrix(99, nrow = 1, ncol = 2) selectdoses[1, ] = matrix(selectdose, nrow = 1) } selectdoses = matrix(selectdoses[selectdoses[, 2] != 99, ], ncol = 2) colnames(selectdoses) = c("DoseA", "DoseB") } if (mtd.contour == FALSE) { if (selectdoses[1, 1] == 99 && selectdoses[1, 2] == 99) { message("All tested doses are overly toxic. No MTD is selected! \n") out = list(target = target, MTD = 99, p_est = matrix(NA, nrow = dim(npts)[1], ncol = dim(npts)[2])) } else { out = list(target = target, MTD = selectdoses, p_est = round(phat.out, 2)) } return(out) } else { if (length(selectdoses) == 0) { message("All tested doses are overly toxic. No MTD is selected! \n") out = list(target = target, MTD = 99, p_est = matrix(NA, nrow = dim(npts)[1], ncol = dim(npts)[2])) } else { out = list(target = target, MTD = selectdoses, p_est = round(phat.out, 2)) } return(out) } } selcomb = select.mtd.comb(target, n, y, cutoff.eli, extrasafe, offset) dselect[trial, 1] = selcomb$MTD[1] dselect[trial, 2] = selcomb$MTD[2] } } selpercent = matrix(rep(0, ndose), dim(p.true)[1], dim(p.true)[2]) nptsdose = apply(N, c(1, 2), mean, digits = 2, format = "f") ntoxdose = apply(Y, c(1, 2), mean, digits = 2, format = "f") for (i in 1:dim(p.true)[1]) { for (j in 1:dim(p.true)[2]) { selpercent[i, j] = sum(dselect[, 1] == i & dselect[, 2] == j) / ntrial * 100 } } if (JJ <= KK) { over_dosing_60_num <- NULL for(i in 1:ntrial){ over_dosing_60_num[i] <- sum(N[,,i][p.true > target + marginR]) } over_dosing_60 = mean(over_dosing_60_num > 0.6 * npts) * 100 over_dosing_80_num <- NULL for(i in 1:ntrial){ over_dosing_80_num[i] <- sum(N[,,i][p.true > target + marginR]) } over_dosing_80 = mean(over_dosing_80_num > 0.8 * npts) * 100 under_dosing_60_num <- NULL for(i in 1:ntrial){ under_dosing_60_num[i] <- sum(N[,,i][p.true < target - marginR]) } under_dosing_60 = mean(under_dosing_60_num > 0.6 * npts) * 100 under_dosing_80_num <- NULL for(i in 1:ntrial) { under_dosing_80_num[i] <- sum(N[,,i][p.true < target - marginR]) } under_dosing_80 = mean(under_dosing_80_num > 0.8 * npts) * 100 } else { over_dosing_60_num <- NULL for(i in 1:ntrial) { over_dosing_60_num[i] <- sum(N[,,i][p.true > target + marginR]) } over_dosing_60 = mean(over_dosing_60_num > 0.6 * npts) * 100 over_dosing_80_num <- NULL for(i in 1:ntrial){ over_dosing_80_num[i] <- sum(N[,,i][p.true > target + marginR]) } over_dosing_80 = mean(over_dosing_80_num > 0.8 * npts) * 100 under_dosing_60_num <- NULL for(i in 1:ntrial){ under_dosing_60_num[i] <- sum(N[,,i][p.true < target - marginR]) } under_dosing_60 = mean(under_dosing_60_num > 0.6 * npts) * 100 under_dosing_80_num <- NULL for(i in 1:ntrial){ under_dosing_80_num[i] <- sum(N[,,i][p.true < target - marginR]) } under_dosing_80 = mean(under_dosing_80_num > 0.8 * npts) * 100 } out = list(name = "get.oc.comb.kb", target = target, p.true = p.true, ncohort = ncohort, cohortsize = cohortsize, ntotal = ncohort * cohortsize, ntrial = ntrial, selpercent = selpercent, pcs = sum(selpercent[which(p.true <= target + marginR & p.true >= target - marginR, arr.ind = TRUE)]), nmtd = sum(nptsdose[p.true <= target + marginR & p.true >= target - marginR]) / sum(nptsdose) * 100, nmtd.over = sum(nptsdose[p.true > target + marginR]) / sum(nptsdose) * 100, nmtd.over.sd = sd( nptsdose[p.true > target + marginR] / sum(nptsdose)), nptsdose = nptsdose, ntoxdose = ntoxdose, totaltox = round(sum(Y) / ntrial, 1), totaln = round(sum(N) / ntrial, 1), npercent = paste(round(sum(nptsdose[which(abs(p.true - target) == min(abs(p.true - target)), arr.ind = TRUE)]) / sum(nptsdose) * 100, 1), '%', sep = ""), low_dose = sum(nptsdose[p.true < target - marginR]) / sum(nptsdose) * 100, high_tox = sum(nptsdose[p.true > target + marginR]) / sum(nptsdose) * 100, over_dosing_60 = over_dosing_60, over_dosing_80 = over_dosing_80, under_dosing_60 = under_dosing_60, under_dosing_80 = under_dosing_80, pctearlystop = sum(dselect == 99) / ntrial * 100, over.sel.pcs = sum(selpercent[which(p.true >= target + marginR, arr.ind = TRUE)]), percent.under.MTD.sel.20 = sum(selpercent[which(p.true < target - marginR, arr.ind = TRUE)]), total.incoherent.dlt = sum(total.incoherent.dlt) / (ncohort * ntrial) * 100, total.incoherent.no.dlt = sum(total.incoherent.no.dlt) / (ncohort * ntrial) * 100, total.incoherent = sum(total.incoherent) / (ncohort * ntrial) * 100, total.long.incoherent.dlt = sum(long.incoherent.dlt) / (ncohort * ntrial) * 100, total.long.incoherent.no.dlt = sum(long.incoherent.no.dlt) / (ncohort * ntrial) * 100, total.long.incoherent = sum(total.long.incoherent) * 100 ) return(out) }
printMixture=function(fit,digits=3,file=NULL){ est=fit names.var=est$covariates$names is.truncation=est$is.truncation is.interval=est$is.interval n.beta=length(est$covariates$beta) n.gamma=length(est$covariates$gamma) n.alpha=length(est$covariates$alpha) n.q=length(est$covariates$q) if(is.null(file)){ cat("\n") cat("Call: "); print(est$call) cat("\n") if(length(est$par$beta)==0){ cat("The AFT Location-Scale Mixture Regression Model for ") }else{ cat("The Logistic-AFT Location-Scale Mixture Regression Model for ") } if(is.truncation){ if(is.interval){ cat("Left-Truncated and Interval-Censored Data \n") }else{ cat("Left-Truncated and Right-Censored Data \n") } }else{ if(is.interval){ cat("Interval-Censored Data \n") }else{ cat("Right-Censored Data \n") } } cat("\n") empty=" " colnames.outTable=c("EST","STD","95% LCL","95% UCL","P-Value","Exp(EST)","Gradient") rownames.outTable=NULL if(n.beta>0){ rownames.outTable=c(rownames.outTable,"Event Probability Sub-model ") loc=est$covariates$beta for (i in 1:length(loc)){ rownames.outTable=c(rownames.outTable,paste(empty,names.var[loc[i]],sep="")) } } rownames.outTable=c(rownames.outTable,"AFT Location-Scale Sub-model") rownames.outTable=c(rownames.outTable," Location Part") loc=est$covariates$gamma for (i in 1:length(loc)){ rownames.outTable=c(rownames.outTable,paste(empty,names.var[loc[i]],sep="")) } rownames.outTable=c(rownames.outTable," Scale Part") loc=est$covariates$alpha for (i in 1:length(loc)){ rownames.outTable=c(rownames.outTable,paste(empty,names.var[loc[i]],sep="")) } if(is.null(est$fix.par$q)){ if(n.q==1){ rownames.outTable=c(rownames.outTable," Shape Parameter") }else{ rownames.outTable=c(rownames.outTable," Shape Part") loc=est$covariates$q for (i in 1:length(loc)){ rownames.outTable=c(rownames.outTable,paste(empty,names.var[loc[i]],sep="")) } } }else{ if(est$fix.par$q=="logistic"){ rownames.outTable=c(rownames.outTable," Log-Logistic Distribution") }else{ rownames.outTable=c(rownames.outTable," Shape Parameter") } } outTable=as.data.frame(matrix(NA,length(rownames.outTable),length(colnames.outTable))) outTable=matrix(NA,length(rownames.outTable),length(colnames.outTable)) colnames(outTable)=colnames.outTable row.names(outTable)=rownames.outTable k=0 j=0 if(n.beta>0){ j=j+1 loc=est$covariates$beta for (i in 1:length(loc)){ j=j+1 k=k+1 parest=round(est$parest[k],digits) std=round(est$std[k],digits) LCL=round(parest-qnorm(1-0.025)*std,digits) UCL=round(parest+qnorm(1-0.025)*std,digits) pvalue=round(est$pvalue[k],digits) if(i==1) exp.est=NA else exp.est=round(exp(est$parest[k]),digits) grad=est$gradient[k] outTable[j,]=c(parest,std,LCL,UCL,pvalue,exp.est,grad) } } j=j+2 loc=est$covariates$gamma for (i in 1:length(loc)){ j=j+1 k=k+1 parest=round(est$parest[k],digits) std=round(est$std[k],digits) LCL=round(parest-qnorm(1-0.025)*std,digits) UCL=round(parest+qnorm(1-0.025)*std,digits) pvalue=round(est$pvalue[k],digits) exp.est=NA grad=est$gradient[k] outTable[j,]=c(parest,std,LCL,UCL,pvalue,exp.est,grad) } j=j+1 loc=est$covariates$alpha for (i in 1:length(loc)){ j=j+1 k=k+1 parest=round(est$parest[k],digits) std=round(est$std[k],digits) LCL=round(parest-qnorm(1-0.025)*std,digits) UCL=round(parest+qnorm(1-0.025)*std,digits) pvalue=round(est$pvalue[k],digits) exp.est=NA grad=est$gradient[k] outTable[j,]=c(parest,std,LCL,UCL,pvalue,exp.est,grad) } if(is.null(est$fix.par$q) & n.q!=1) j=j+1 loc=est$covariates$q for (i in 1:length(loc)){ j=j+1 k=k+1 if(!is.null(est$fix.par$q)){ if(est$par$q=="logistic"){ parest=est$par$q }else{ parest=round(est$par$q,digits) } outTable[j,1]=parest }else{ parest=round(est$parest[k],digits) std=round(est$std[k],digits) LCL=round(parest-qnorm(1-0.025)*std,digits) UCL=round(parest+qnorm(1-0.025)*std,digits) pvalue=round(est$pvalue[k],digits) exp.est=NA grad=est$gradient[k] outTable[j,]=c(parest,std,LCL,UCL,pvalue,exp.est,grad) } } print(outTable[,-6],na.print="",quote=F) cat("\n") cat(paste("Log-Likelihood = ",round(est$LLF,digits),"\n",sep="")) cat(paste("AIC = ",round(est$AIC,digits),"\n",sep="")) if(is.null(est$COV)){ cat("warning: Hessian Matrix is Singular !! \n") }else if(est$convergence!=0){ cat(paste("warning: No Convergence !! \n",sep=",")) } cat("\n") }else{ write("",file=file,append=F) if(length(est$par$beta)==0){ write(paste("","","The AFT Location-Scale Mixture Regression Model",sep=","),file=file,append=T) }else{ write(paste("","","The Logistic-AFT Location-Scale Mixture Regression Model",sep=","),file=file,append=T) } if(is.truncation){ if(is.interval){ write(paste("",""," for Left-Truncated and Interval-Censored Data",sep=","),file=file,append=T) }else{ write(paste("",""," for Left-Truncated and Right-Censored Data",sep=","),file=file,append=T) } }else{ if(is.interval){ write(paste("",""," for Interval-Censored Data",sep=","),file=file,append=T) }else{ write(paste("",""," for Right-Censored Data",sep=","),file=file,append=T) } } write("",file=file,append=T) write(paste("","","","EST","STD","95% LCL","95% UCL","P-Value","Gradient",sep=","),file=file,append=T) k=0 if(n.beta>0){ write(paste("","Event Probability Sub-model",sep=","),file=file,append=T) loc=est$covariates$beta for (i in 1:length(loc)){ k=k+1 parest=round(est$parest[k],digits) std=round(est$std[k],digits) LCL=round(parest-qnorm(1-0.025)*std,digits) UCL=round(parest+qnorm(1-0.025)*std,digits) pvalue=ifelse(round(est$pvalue[k],digits)==0," <0.001",round(est$pvalue[k],digits)) grad=ifelse(round(est$gradient[k],digits=10)==0,"<1.0E-10",round(est$gradient[k],digits=10)) if (i==1){ write(paste("","",names.var[loc[i]],parest,std,LCL,UCL,pvalue,grad,sep=","),file=file,append=T) }else{ write(paste("","",names.var[loc[i]],parest,std,LCL,UCL,pvalue,grad,sep=","),file=file,append=T) } } } write(paste("","AFT Location-Scale Sub-model",sep=","),file=file,append=T) write(paste(""," Location Part",sep=","),file=file,append=T) loc=est$covariates$gamma for (i in 1:length(loc)){ k=k+1 parest=round(est$parest[k],digits) std=round(est$std[k],digits) LCL=round(parest-qnorm(1-0.025)*std,digits) UCL=round(parest+qnorm(1-0.025)*std,digits) pvalue=ifelse(round(est$pvalue[k],digits)==0, " <0.001",round(est$pvalue[k],digits)) grad=ifelse(round(est$gradient[k],digits=10)==0,"<1.0E-10",round(est$gradient[k],digits=10)) if (i==1) write(paste("","",names.var[loc[i]],parest,std,LCL,UCL,pvalue,grad,sep=","),file=file,append=T) else write(paste("","",names.var[loc[i]],parest,std,LCL,UCL,pvalue,grad,sep=","),file=file,append=T) } write(paste(""," Scale Part",sep=","),file=file,append=T) loc=est$covariates$alpha for (i in 1:length(loc)){ k=k+1 parest=round(est$parest[k],digits) std=round(est$std[k],digits) LCL=round(parest-qnorm(1-0.025)*std,digits) UCL=round(parest+qnorm(1-0.025)*std,digits) pvalue=ifelse(round(est$pvalue[k],digits)==0," <0.001",round(est$pvalue[k],digits)) grad=ifelse(round(est$gradient[k],digits=10)==0,"<1.0E-10",round(est$gradient[k],digits=10)) if (i==1) write(paste("","",names.var[loc[i]],parest,std,LCL,UCL,pvalue,grad,sep=","),file=file,append=T) else write(paste("","",names.var[loc[i]],parest,std,LCL,UCL,pvalue,grad,sep=","),file=file,append=T) } if(is.null(est$fix.par$q)){ if(n.q==1){ write(paste(""," Shape Parameter",sep=","),file=file,append=T) }else{ write(paste(""," Shape Part",sep=","),file=file,append=T) } }else{ if(est$fix.par$q=="logistic"){ write(paste(""," Log-Logistic Distribution",sep=","),file=file,append=T) }else{ write(paste("","Shape Parameter",sep=","),file=file,append=T) } } loc=est$covariates$q for (i in 1:length(loc)){ if(is.null(est$fix.par$q)){ k=k+1 parest=round(est$parest[k],digits) std=round(est$std[k],digits) LCL=round(parest-qnorm(1-0.025)*std,digits) UCL=round(parest+qnorm(1-0.025)*std,digits) pvalue=ifelse(round(est$pvalue[k],digits)==0," <0.001",round(est$pvalue[k],digits)) grad=ifelse(round(est$gradient[k],digits=10)==0,"<1.0E-10",round(est$gradient[k],digits=10)) if (i==1 & length(loc)==1){ write(paste("","","",parest,std,LCL,UCL,pvalue,"",grad,sep=","),file=file,append=T) }else if (i==1){ write(paste("","",names.var[loc[i]],parest,std,LCL,UCL,pvalue,grad,sep=","),file=file,append=T) } else write(paste("","",names.var[loc[i]],parest,std,LCL,UCL,pvalue,grad,sep=","),file=file,append=T) }else{ if(length(loc)==1){ if(est$par$q[i]!="logistic"){ write(paste("","","",round(est$par$q[i],digits),sep=","),file=file,append=T) } }else{ write(paste("","",names.var[loc[i]],"",sep=","),file=file,append=T) } } } write("",file=file,append=T) write(paste(",Log-Likelihood = ",round(est$LLF,digits),sep=""),file=file,append=T) write(paste(",AIC = ",round(est$AIC,digits),sep=""),file=file,append=T) if(is.null(est$COV)){ write("warning: Hessian Matrix is Singular !!",file=file,append=T) }else if(est$convergence!=0){ write(paste("","warning: No Convergence !!",sep=","),file=file,append=T) } } }
cbs_get_datasets <- function( catalog = "CBS" , convert_dates = TRUE , select = NULL , verbose = FALSE , cache = TRUE , base_url = getOption("cbsodataR.base_url", BASE_URL) , ... ){ toc <- .cache$cbs_get_datasets if (is.null(toc)){ toc <- cbs_get_toc( ... , convert_dates = convert_dates , select = select , verbose = verbose , cache = cache , base_url = base_url , include_ID = FALSE ) try({ toc2 <- cbs_get_toc(... , convert_dates = convert_dates , select = select , verbose = verbose , cache = cache , base_url = "https://dataderden.cbs.nl" , include_ID = FALSE ) toc <- rbind(toc, toc2) }, silent = TRUE) .cache$cbs_get_datasets <- toc } if (!is.null(catalog)){ cats <- unique(toc$Catalog) if (!(catalog %in% cats)){ stop("Invalid value for `catalog`, should be one of: " , paste0('"', cats ,'"', collapse = ", ") , 'or `NULL`' , call. = FALSE ) } toc <- toc[toc$Catalog == catalog, ] } toc }
prosim <- function(C, fam, tht, dm, no){ kop3 = kopula(fam, tht, dm) u3 = rCopula(no, kop3) C3 = pCopula(u3, kop3) S3 = pCopula(1 - u3, kop3) S = C p = numeric(length(C)) for (i in 1:length(C)){ m = C3 >= C[i] & S3 >= S[i] p[i] = sum(m)/no } return(p) }
Brain2 <- R6::R6Class( classname = 'rave-brain', portable = FALSE, cloneable = TRUE, private = list( .subject_code = '' ), public = list( meta = NULL, surfaces = NULL, volumes = NULL, atlases = NULL, electrodes = NULL, misc = NULL, xfm = diag(rep(1, 4)), Norig = diag(rep(1, 4)), Torig = diag(rep(1, 4)), initialize = function(subject_code, xfm, Norig, Torig){ stopifnot2( length(xfm) == 16 && length(dim(xfm)) == 2 && sum(dim(xfm)) == 8, msg = 'xfm must be 4x4 matrix') stopifnot2( length(Norig) == 16 && length(dim(Norig)) == 2 && sum(dim(Norig)) == 8, msg = 'Norig must be 4x4 matrix') stopifnot2( length(Torig) == 16 && length(dim(Torig)) == 2 && sum(dim(Torig)) == 8, msg = 'Torig must be 4x4 matrix') private$.subject_code <- subject_code self$xfm <- xfm self$Norig <- Norig self$Torig <- Torig self$volumes <- list() self$surfaces <- list() self$electrodes <- BrainElectrodes$new(subject_code = subject_code) self$meta <- list() self$misc <- BlankGeom$new( group = GeomGroup$new(name = sprintf('_internal_group_data_%s', subject_code)), name = sprintf('_misc_%s', subject_code) ) }, add_surface = function(surface){ stopifnot2( R6::is.R6( surface ) && 'brain-surface' %in% class( surface ), msg = 'surface must be a brain-surface object') stopifnot2( surface$has_hemispheres, msg = 'surface miss mesh objects') if( surface$mesh_type == 'std.141' ){ surface$set_group_position( self$scanner_center ) offset_x <- switch ( surface$surface_type, 'inflated' = { offset_x <- 50 }, 'sphere' = { offset_x <- 128 }, { 0 } ) surface$left_hemisphere$position <- c(-offset_x, 0, 0) surface$right_hemisphere$position <- c(offset_x, 0, 0) }else if( surface$mesh_type == 'fs' ){ surface$set_group_position( 0, 0, 0 ) } surface$set_subject_code( self$subject_code ) self$surfaces[[ surface$surface_type ]] <- surface }, remove_surface = function(surface_types){ if(missing(surface_types)){ surface_types <- self$surface_types } for( s in surface_types){ self$surfaces[[ s ]] <- NULL } }, remove_volume = function(volume_types){ if(missing(volume_types)){ volume_types <- self$volume_types } for( s in volume_types){ self$volumes[[ s ]] <- NULL } }, add_volume = function(volume){ stopifnot2( R6::is.R6( volume ) && 'brain-volume' %in% class( volume ), msg = 'volume must be a brain-volume object') stopifnot2( volume$has_volume, msg = 'volume miss datacube objects') volume$set_subject_code( self$subject_code ) self$volumes[[ volume$volume_type ]] <- volume }, remove_atlas = function(atlas_types){ if(missing(atlas_types)){ atlas_types <- self$atlas_types } for( s in atlas_types){ self$atlases[[ s ]] <- NULL } }, add_atlas = function(atlas){ stopifnot2( R6::is.R6( atlas ) && 'brain-atlas' %in% class( atlas ), msg = 'atlas must be a brain-atlas object') stopifnot2( atlas$has_atlas, msg = 'atlas miss datacube2 objects') atlas$set_subject_code( self$subject_code ) self$atlases[[ atlas$atlas_type ]] <- atlas }, add_vertex_color = function(name, path, lazy = TRUE){ path <- normalizePath(path) self$misc$group$set_group_data( name = name, value = list( path = path, absolute_path = path, file_name = filename(path), is_new_cache = FALSE, is_cache = TRUE, lazy = lazy ), is_cached = TRUE ) }, set_electrodes = function(electrodes){ if( R6::is.R6(electrodes) && 'brain-electrodes' %in% class(electrodes)){ self$electrodes <- electrodes self$electrodes$set_subject_code( self$subject_code ) }else{ self$electrodes$set_electrodes( electrodes ) } }, set_electrode_values = function(table_or_path){ self$electrodes$set_values(table_or_path = table_or_path) }, calculate_template_coordinates = function(save_to = 'auto', hemisphere = TRUE){ table <- self$electrodes$raw_table if( !is.data.frame(table) || !nrow(table) ){ return(invisible()) } n <- nrow(table) surface_types <- self$surface_types tempenv <- new.env(parent = emptyenv()) tempenv$has_change <- FALSE rows <- lapply(seq_len(n), function(ii){ row <- table[ii, ] fs_position <- c(row$Coord_x, row$Coord_y, row$Coord_z) if( all(fs_position == 0) ){ return(row) } is_surface_electrode <- row$SurfaceElectrode surf_t <- row$SurfaceType if( isTRUE(is_surface_electrode) ){ if( is.na(surf_t) || surf_t == 'NA' ){ surf_t <- 'pial' } mapped <- electrode_mapped_141(position = fs_position, is_surface = TRUE, vertex_number = row$VertexNumber, surf_type = surf_t, hemisphere = row$Hemisphere) if( !mapped && surf_t %in% surface_types ){ lh_vert <- self$surfaces[[ surf_t ]]$group$get_data(sprintf('free_vertices_Standard 141 Left Hemisphere - %s (%s)', surf_t, self$subject_code)) rh_vert <- self$surfaces[[ surf_t ]]$group$get_data(sprintf('free_vertices_Standard 141 Right Hemisphere - %s (%s)', surf_t, self$subject_code)) mesh_center <- self$surfaces[[ surf_t ]]$group$position lh_dist <- colSums((t(lh_vert) - (fs_position - mesh_center))^2) rh_dist <- colSums((t(rh_vert) - (fs_position - mesh_center))^2) lh_node <- which.min(lh_dist) lh_dist <- lh_dist[ lh_node ] rh_node <- which.min(rh_dist) rh_dist <- rh_dist[ rh_node ] if(hemisphere || !isTRUE(row$Hemisphere %in% c('left', 'right'))){ node <- rh_node - 1 hemisphere <- 'right' if( lh_dist < rh_dist ){ node <- lh_node - 1 hemisphere <- 'left' } } else { hemisphere <- row$Hemisphere if(hemisphere == 'right'){ node <- rh_node - 1 } else { node <- lh_node - 1 } } row$Hemisphere <- hemisphere row$VertexNumber <- node tempenv$has_change <- TRUE } } mni_position <- c(row$MNI305_x, row$MNI305_y, row$MNI305_z) if( all(mni_position == 0) ){ mni_position <- self$vox2vox_MNI305 %*% c(fs_position, 1) row$MNI305_x <- mni_position[1] row$MNI305_y <- mni_position[2] row$MNI305_z <- mni_position[3] tempenv$has_change <- TRUE } row }) rows <- do.call(rbind, rows) nms <- unique(c("Electrode","Coord_x","Coord_y","Coord_z","Label","MNI305_x","MNI305_y","MNI305_z", "SurfaceElectrode","SurfaceType","Radius","VertexNumber","Hemisphere", names(rows))) rows <- rows[, nms] raw_path <- self$electrodes$raw_table_path if( isTRUE( save_to == 'auto' ) ){ save_to <- raw_path } if(tempenv$has_change && length(save_to) == 1 && is.character(save_to)){ safe_write_csv(rows, save_to) self$electrodes$set_electrodes(save_to) return(invisible(rows)) } self$electrodes$set_electrodes(rows) self$electrodes$raw_table_path <- raw_path invisible(rows) }, get_geometries = function(volumes = TRUE, surfaces = TRUE, electrodes = TRUE, atlases = TRUE){ geoms <- list(self$misc) if( is.logical(volumes) ){ if(isTRUE(volumes)){ volumes <- self$volume_types }else{ volumes <- NULL } }else{ volumes <- volumes[ volumes %in% self$volume_types ] } for( v in volumes ){ geoms <- c( geoms , self$volumes[[ v ]]$object ) } if( is.logical(atlases) ){ if(isTRUE(atlases)){ atlases <- self$atlas_types }else{ atlases <- NULL } }else{ atlases <- atlases[ atlases %in% self$atlas_types ] } for( a in atlases ){ geoms <- c( geoms , self$atlases[[ a ]]$object ) } if( is.logical(surfaces) ){ if(isTRUE(surfaces)){ surfaces <- self$surface_types }else{ surfaces <- NULL } }else{ surfaces <- surfaces[ surfaces %in% self$surface_types ] } for( s in surfaces ){ geoms <- c( geoms , self$surfaces[[ s ]]$left_hemisphere, self$surfaces[[ s ]]$right_hemisphere ) } if( isTRUE(electrodes) && !is.null(self$electrodes) ){ geoms <- c(geoms, self$electrodes$objects) } return( unlist( geoms ) ) }, print = function( ... ){ cat('Subject -', self$subject_code, end = '\n') cat('Transforms:\n\n- FreeSurfer TalXFM [from scanner to MNI305]:\n') base::print( self$xfm ) cat('\n- Torig [Voxel CRS to FreeSurfer origin, vox2ras-tkr]\n') base::print( self$Torig ) cat('\n- Norig [Voxel CRS to Scanner center, vox2ras]\n') base::print( self$Norig ) cat('\n- Scanner center relative to FreeSurfer origin\n') base::print( self$scanner_center ) cat('\n- FreeSurfer RAS to MNI305, vox2vox-MNI305\n') base::print( self$vox2vox_MNI305 ) cat(sprintf('Surface information (total count %d)\n', length( self$surfaces ))) lapply( self$surfaces, function( surface ){ s <- sprintf( ' %s [ %s ]', surface$surface_type, surface$mesh_type) v <- 'invalid' level <- 'WARNING' if( surface$has_hemispheres ){ v <- '' level <- 'INFO' } cat2(s, v , level = level) invisible() }) cat(sprintf('Volume information (total count %d)\n', length( self$volumes ))) lapply( self$volumes, function( volume ){ s <- sprintf( ' %s', volume$volume_type) v <- 'invalid' level <- 'WARNING' if( volume$has_volume ){ v <- '' level <- 'INFO' } cat2(s, v , level = level) invisible() }) return(invisible(self)) }, localize = function( coregistered_ct, col = c("white", "green", 'darkgreen'), controllers = list(), control_presets = NULL, voxel_colormap = NULL, ... ){ control_presets <- c('localization', control_presets) controllers[["Highlight Box"]] <- FALSE if(!missing( coregistered_ct )){ ct <- read_nii2( normalizePath(coregistered_ct, mustWork = TRUE) ) ct_shift <- ct$get_center_matrix() ct_qform <- ct$get_qform() matrix_world <- brain$Torig %*% solve(brain$Norig) %*% ct_qform %*% ct_shift add_voxel_cube(self, "CT", ct$get_data(), size = ct$get_size(), matrix_world = matrix_world) key <- seq(0, max(ct$get_range())) cmap <- create_colormap( gtype = 'volume', dtype = 'continuous', key = key, value = key, color = col ) controllers[["Left Opacity"]] <- 0.4 controllers[["Right Opacity"]] <- 0.4 controllers[["Voxel Type"]] <- "CT" controllers[["Voxel Min"]] <- 3000 controllers[["Edit Mode"]] <- "CT/volume" self$plot( control_presets = control_presets, voxel_colormap = cmap, controllers = controllers, custom_javascript = "canvas.controls.noPan=true;", ... ) } else { controllers[["Edit Mode"]] <- "MRI slice" controllers[["Overlay Coronal"]] <- TRUE controllers[["Overlay Axial"]] <- TRUE controllers[["Overlay Sagittal"]] <- TRUE controllers[["Left Opacity"]] <- 0.1 controllers[["Right Opacity"]] <- 0.1 self$plot( control_presets = control_presets, controllers = controllers, custom_javascript = "canvas.controls.noPan=true;", ... ) } }, plot = function( volumes = TRUE, surfaces = TRUE, atlases = TRUE, start_zoom = 1, cex = 1, background = ' side_canvas = TRUE, side_width = 250, side_shift = c(0, 0), side_display = TRUE, control_panel = TRUE, control_display = TRUE, default_colormap = NULL, palettes = NULL, control_presets = NULL, time_range = NULL, val_ranges = NULL, value_alias = NULL, value_ranges = val_ranges, controllers = list(), width = NULL, height = NULL, debug = FALSE, token = NULL, browser_external = TRUE, ... ){ geoms <- self$get_geometries( volumes = volumes, surfaces = surfaces, electrodes = TRUE, atlases = atlases ) is_r6 <- vapply(geoms, function(x){ 'AbstractGeom' %in% class(x) }, FALSE) geoms <- geoms[is_r6] names(geoms) <- NULL global_data <- self$global_data control_presets <- unique( c( 'subject2', 'surface_type2', 'hemisphere_material', 'surface_color', 'map_template', 'electrodes', 'voxel', control_presets, 'animation', 'display_highlights') ) if( !length(self$volumes) ){ side_display <- FALSE } threejs_brain( .list = geoms, palettes = palettes, controllers = controllers, value_alias = value_alias, side_canvas = side_canvas, side_width = side_width, side_shift = side_shift, control_panel = control_panel, control_presets = control_presets, control_display = control_display, value_ranges = value_ranges, default_colormap = default_colormap, side_display = side_display, width = width, height = height, debug = debug, token = token, browser_external = browser_external, global_data = global_data, start_zoom = start_zoom, cex = cex, background = background, ...) } ), active = list( subject_code = function(v){ if(!missing(v)){ stop('Cannot set subject code. This attribute cannot be changed once you initialize Brain2 object.') } private$.subject_code }, vox2vox_MNI305 = function(){ self$xfm %*% self$Norig %*% solve(self$Torig) }, scanner_center = function(){ -(self$Norig %*% solve( self$Torig ) %*% c(0,0,0,1))[1:3] }, surface_types = function(){ names(self$surfaces) }, surface_mesh_types = function(){ sapply(self$surface_types, function(st){ self$surfaces[[st]]$mesh_type }, simplify = FALSE, USE.NAMES = TRUE) }, volume_types = function(){ names(self$volumes) }, atlas_types = function(){ names(self$atlases) }, global_data = function(){ re <- structure(list(list( Norig = self$Norig, Torig = self$Torig, xfm = self$xfm, vox2vox_MNI305 = self$vox2vox_MNI305, scanner_center = self$scanner_center, atlas_types = self$atlas_types, volume_types = self$volume_types )), names = self$subject_code) re$.subject_codes <- self$subject_code re } ) )
ukppd_avail_items <- function() { query <- build_sparql_file_query( "ppi", "transaction", "0A73B494-6838-4604-961B-0453DF4CC0BB", "current") proc <- process_request(query) proc %||% return(invisible(NULL)) all_items <- gsub(".*/ppi/(.+)", "\\1", proc$type[-1]) already_included <- c("transactionDate", "pricePaid", "transactionCategory") setdiff(all_items, already_included) } ukppd_avail_optional_items <- function() { query <- build_sparql_file_query( "ppi", "address", "e738e64c33d83e5492f9a1bb0e3e4c24ed4ce684") proc <- process_request(query) proc %||% return(invisible(NULL)) all_items <- gsub(".*/common/(.+)", "\\1", proc$type[-1]) already_included <- c("postcode") setdiff(all_items, already_included) } ukppd_avail_postcodes <- function() { pc$NUTS3 <- gsub("[0-9]", "", pc$NUTS3) pc[!pc$NUTS3 %in% c("UKM", "UKN"), ]$CODE }
library(testthat) library(RSocrata) test_check("RSocrata")
xyplot.EmpiricalSemivariogramSSN <- function(object, ...) { plot(c(1,1),type = "n") t.background <- trellis.par.get("background") t.background$col <- "white" trellis.par.set("background", t.background) xyplot(gamma ~ distance | azimuth, data=object, pch = 19, col = "black", as.table = TRUE, ...) }
context("Run models for all data sets and call the appropriate summaries / plots") test_that("cipriani-efficacy", { test.regress(depression, likelihood="binom", link="logit", t1="escitalopram", t2="sertraline") }) test_that("luades-smoking", { expect_that(mtc.nodesplit.comparisons(smoking), equals( data.frame(t1=c("A", "A", "A", "B", "B", "C"), t2=c("B", "C", "D", "C", "D", "D"), stringsAsFactors=FALSE))) test.regress(smoking, likelihood="binom", link="logit", t1="B", t2="D") }) test_that("luades-thrombolytic", { expect_that(mtc.nodesplit.comparisons(thrombolytic), equals( data.frame(t1=c("ASPAC", "ASPAC", "ASPAC", "AtPA", "AtPA", "AtPA", "AtPA", "Ret", "SK", "SK", "tPA"), t2=c("AtPA", "SK", "tPA", "Ret", "SK", "SKtPA", "UK", "SK", "tPA", "UK", "UK"), stringsAsFactors=FALSE))) test.regress(thrombolytic, likelihood="binom", link="logit", t1="SK", t2="UK") }) test_that("tsd2-1 (event data, pair-wise)", { expect_that(nrow(mtc.nodesplit.comparisons(blocker)), equals(0)) test.regress(blocker, likelihood="binom", link="logit") }) test_that("tsd2-2 (fat survival, rate data)", { expect_that(nrow(mtc.nodesplit.comparisons(dietfat)), equals(0)) test.regress(dietfat, likelihood="poisson", link="log") }) test_that("tsd2-3 (diabetes, rate data)", { data.ab <- dget("../data/studyrow/tsd2-3.out.txt") network <- mtc.network(data.ab=data.ab) comparisons <- mtc.comparisons(network) comparisons$t1 <- as.character(comparisons$t1) comparisons$t2 <- as.character(comparisons$t2) expect_that(mtc.nodesplit.comparisons(network), equals(comparisons)) test.regress(network, likelihood="binom", link="cloglog", t1="ARB", t2="BetaB") }) test_that("parkinson example", { expect_that(mtc.nodesplit.comparisons(parkinson), equals( data.frame(t1=c("A", "A", "B", "C"), t2=c("C", "D", "D", "D"), stringsAsFactors=FALSE))) test.regress(parkinson, likelihood="normal", link="identity", t1="B", t2="D") }) test_that("tsd2-5 (parkinson AB data)", { data.ab <- dget("../data/studyrow/tsd2-5.out.txt") network <- mtc.network(data.ab=data.ab) expect_that(mtc.nodesplit.comparisons(network), equals( data.frame(t1=c("1", "1", "2", "3"), t2=c("3", "4", "4", "4"), stringsAsFactors=FALSE))) test.regress(network, likelihood="normal", link="identity", t1="3", t2="4") }) test_that("tsd2-7 (parkinson RE data)", { expect_that(mtc.nodesplit.comparisons(parkinson_diff), equals( data.frame(t1=c("A", "A", "B", "C"), t2=c("C", "D", "D", "D"), stringsAsFactors=FALSE))) test.regress(parkinson_diff, likelihood="normal", link="identity", t1="D", t2="A") }) test_that("tsd2-8 (parkinson mixed data)", { expect_that(mtc.nodesplit.comparisons(parkinson_shared), equals( data.frame(t1=c("A", "A", "B", "C"), t2=c("C", "D", "D", "D"), stringsAsFactors=FALSE))) test.regress(parkinson_shared, likelihood="normal", link="identity", t1="B", t2="D") }) test_that("ns-complex (numbered studies)", { data.re <- read.table("../data/ns-complex.csv", header=TRUE, sep=",") data.re$Study <- NULL network <- mtc.network(data.re=data.re) test.regress(network, likelihood="normal", link="identity", t1="B", t2="D") }) test_that("ns-complex (named studies)", { data.re <- read.table("../data/ns-complex.csv", header=TRUE, sep=",") data.re$study <- data.re$Study data.re$Study <- NULL network <- mtc.network(data.re=data.re) test.regress(network, likelihood="normal", link="identity", t1="H", t2="D") }) test_that("certolizumab regression (binomial data, continuous covariate)", { model <- mtc.model(certolizumab, type="regression", linearModel="fixed", regressor=list(control="Placebo", coefficient="unrelated", variable="diseaseDuration")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(certolizumab, type="regression", linearModel="fixed", regressor=list(control="Placebo", coefficient="shared", variable="diseaseDuration")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(certolizumab, type="regression", linearModel="fixed", regressor=list(control="Placebo", coefficient="exchangeable", variable="diseaseDuration")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(certolizumab, type="regression", linearModel="random", regressor=list(control="Placebo", coefficient="unrelated", variable="diseaseDuration")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(certolizumab, type="regression", linearModel="random", regressor=list(control="Placebo", coefficient="shared", variable="diseaseDuration")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(certolizumab, type="regression", linearModel="random", regressor=list(control="Placebo", coefficient="exchangeable", variable="diseaseDuration")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) expect_true(TRUE) }) test_that("atrial fibrillation regression (classes, binomial data, continuous covariate)", { classes <- list("control"=c('01'), "anti-coagulant"=c('02','03','04','09'), "anti-platelet"=c('05','06','07','08','10','11','12','16','17'), "mixed"=c('13','14','15')) model <- mtc.model(atrialFibrillation, type="regression", linearModel="fixed", regressor=list(classes=classes, coefficient="shared", variable="stroke")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(atrialFibrillation, type="regression", linearModel="random", regressor=list(classes=classes, coefficient="shared", variable="stroke")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) expect_true(TRUE) }) test_that("heart failure prevention (binomial data, binary covariate)", { model <- mtc.model(hfPrevention, type="regression", linearModel="fixed", regressor=list(control="control", coefficient="unrelated", variable="secondary")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(hfPrevention, type="regression", linearModel="fixed", regressor=list(control="control", coefficient="shared", variable="secondary")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(hfPrevention, type="regression", linearModel="fixed", regressor=list(control="control", coefficient="exchangeable", variable="secondary")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(hfPrevention, type="regression", linearModel="random", regressor=list(control="control", coefficient="unrelated", variable="secondary")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(hfPrevention, type="regression", linearModel="random", regressor=list(control="control", coefficient="shared", variable="secondary")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) model <- mtc.model(hfPrevention, type="regression", linearModel="random", regressor=list(control="control", coefficient="exchangeable", variable="secondary")) capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) expect_true(TRUE) }) test_that("node-splitting with down-weighting", { studies <- unique(smoking$data.ab$study) weight <- (0:(length(studies)-1))/length(studies) network <- mtc.network(smoking$data.ab, studies=data.frame(study=studies, weight=weight, stringsAsFactors=FALSE)) model <- mtc.model(network, type="nodesplit", t1="A", t2="B", powerAdjust="weight") capture.output(result <- mtc.run(model, n.adapt=100, n.iter=500)) expect_true(TRUE) })
context("BFS") test_that("BFS", { G <- graph(list( "a" = "b", "b" = character(), "c" = "d", "d" = character(), "e" = "f", "f" = character() )) expect_equal(sort(bfs(G, "a")), c("a", "b")) expect_equal(sort(bfs(G, "c")), c("c", "d")) expect_equal(sort(bfs(G, c("a", "c"))), c("a", "b", "c", "d")) G <- graph(list( "7" = c("11", "8"), "5" = "11", "3" = c("8", "10"), "11" = c("2", "9", "10"), "8" = "9", "2" = character(), "9" = character(), "10" = character() )) expect_equal(bfs(G, character()), character()) expect_equal(bfs(G, "10"), "10") expect_equal(bfs(G, "7"), c("7", "11", "8", "2", "9", "10")) expect_equal( sort(bfs(G, c("7", "5"))), c("10", "11", "2", "5", "7", "8", "9") ) }) test_that("BFS bug fixed", { bridges <- graph(list( "Altstadt-Loebenicht" = c( "Kneiphof", "Kneiphof", "Lomse" ), "Kneiphof" = c( "Altstadt-Loebenicht", "Altstadt-Loebenicht", "Vorstadt-Haberberg", "Vorstadt-Haberberg", "Lomse" ), "Vorstadt-Haberberg" = c( "Kneiphof", "Kneiphof", "Lomse" ), "Lomse" = c( "Altstadt-Loebenicht", "Kneiphof", "Vorstadt-Haberberg" ) )) expect_equal( bfs(bridges), c("Altstadt-Loebenicht", "Kneiphof", "Lomse", "Vorstadt-Haberberg") ) })
check_decoding = function(decoding,data,controls){ if(check_saving(name = "states",filetype = "txt",controls = controls)){ sink(file=paste0(controls[["path"]],"/models/",controls[["id"]],"/states.txt")) writeLines("Frequency of decoded states\n") if(controls[["model"]]=="hmm"){ out = table((decoding)) names(out) = paste("state",names(out)) print(out) cat("\n") } if(controls[["model"]]=="hhmm"){ out_cs = table(factor(decoding[,1],levels = seq_len(controls[["states"]][1]))) names(out_cs) = paste("CS state",names(out_cs)) print(out_cs) cat("\n") for(state in seq_len(controls[["states"]][1])){ writeLines(paste0("Conditional on CS state ",state,":")) out_fs = table(factor(decoding[decoding[,1]==state,-1],levels = seq_len(controls[["states"]][2]))) names(out_fs) = paste("FS state",names(out_fs)) print(out_fs) cat("\n") } } if(controls[["sim"]]){ compare_true_predicted_states = function(no_states,decoded_states,true_states,label=NULL){ c_table = matrix(0,no_states,no_states) rownames(c_table) = paste0("true ",label,"state ",seq_len(no_states)) colnames(c_table) = paste0("decoded ",label,"state ",seq_len(no_states)) for(i in seq_len(no_states)) for(j in seq_len(no_states)){ value = sum(decoded_states==i & true_states==j, na.rm = TRUE) / sum(decoded_states==i, na.rm = TRUE) * 100 c_table[i,j] = if(is.nan(value)) "NA" else sprintf("%.0f%%",value) } print(c_table,quote=FALSE,right=TRUE) } writeLines("Comparison between true and decoded states\n") if(controls[["model"]]=="hmm"){ compare_true_predicted_states(controls[["states"]][1],decoding,data[["states0"]]) } if(controls[["model"]]=="hhmm"){ compare_true_predicted_states(controls[["states"]][1],decoding[,1],data[["states0"]][,1],label="CS ") writeLines("") for(cs_state in seq_len(controls[["states"]][1])){ writeLines(paste0("Conditional on true CS state ",cs_state,":")) compare_true_predicted_states(controls[["states"]][2],decoding[data[["states0"]][,1]==cs_state,-1],data[["states0"]][data[["states0"]][,1]==cs_state,-1],label="FS ") writeLines("") } } } sink() } check_saving(object = decoding, filetype = "rds", controls = controls) message("Hidden states decoded.") }
.onAttach <- function(libname, pkgname){ if (!interactive()) return() Rcmdr <- options()$Rcmdr plugins <- Rcmdr$plugins if ((!pkgname %in% plugins) && !getRcmdr("autoRestart")) { Rcmdr$plugins <- c(plugins, pkgname) options(Rcmdr=Rcmdr) closeCommander(ask=FALSE, ask.save=TRUE) Commander() } } .packageName <- "RcmdrPlugin.FactoMineR"
GFS_GP_R <- function(train, test, numLabels=3, numRules=8, popSize=30, numisland=2, steady=1, numIter=100, tourSize=4, mutProb=0.01, aplMut=0.1, probMigra=0.001, probOptimLocal=0.00, numOptimLocal=0, idOptimLocal=0, nichinggap=0, maxindniche=8, probintraniche=0.75, probcrossga=0.5, probmutaga=0.5, lenchaingap=10, maxtreeheight=8, seed=-1){ alg <- RKEEL::R6_GFS_GP_R$new() alg$setParameters(train, test, numLabels, numRules, popSize, numisland, steady, numIter, tourSize, mutProb, aplMut, probMigra, probOptimLocal, numOptimLocal, idOptimLocal, nichinggap, maxindniche, probintraniche, probcrossga, probmutaga, lenchaingap, maxtreeheight, seed) return (alg) } R6_GFS_GP_R <- R6::R6Class("R6_GFS_GP_R", inherit = RegressionAlgorithm, public = list( numLabels = 3, numRules = 8, popSize = 30, numisland = 2, steady = 1, numIter = 100, tourSize = 4, mutProb = 0.01, aplMut = 0.1, probMigra = 0.001, probOptimLocal = 0.00, numOptimLocal = 0, idOptimLocal = 0, nichinggap = 0, maxindniche = 8, probintraniche = 0.75, probcrossga = 0.5, probmutaga = 0.5, lenchaingap = 10, maxtreeheight = 8, seed = -1, setParameters = function(train, test, numLabels=3, numRules=8, popSize=30, numisland=2, steady=1, numIter=100, tourSize=4, mutProb=0.01, aplMut=0.1, probMigra=0.001, probOptimLocal=0.00, numOptimLocal=0, idOptimLocal=0, nichinggap=0, maxindniche=8, probintraniche=0.75, probcrossga=0.5, probmutaga=0.5, lenchaingap=10, maxtreeheight=8, seed=-1){ super$setParameters(train, test) self$numLabels <- numLabels self$numRules <- numRules self$popSize <- popSize self$numisland <- numisland self$steady <- steady self$numIter <- numIter self$tourSize <- tourSize self$mutProb <- mutProb self$aplMut <- aplMut self$probMigra <- probMigra self$probOptimLocal <- probOptimLocal self$numOptimLocal <- numOptimLocal self$idOptimLocal <- idOptimLocal self$nichinggap <- nichinggap self$maxindniche <- maxindniche self$probintraniche <- probintraniche self$probcrossga <- probcrossga self$probmutaga <- probmutaga self$lenchaingap <- lenchaingap self$maxtreeheight <- maxtreeheight if(seed == -1) { self$seed <- sample(1:1000000, 1) } else { self$seed <- seed } } ), private = list( jarName = "crispSymRegGAP.jar", algorithmName = "GFS-GP-R", algorithmString = "Fuzzy Rule Learning, Grammar-based GAP Algorithm", getParametersText = function(){ text <- "" text <- paste0(text, "seed = ", self$seed, "\n") text <- paste0(text, "subAlgorithm = ModelFuzzyGAP", "\n") text <- paste0(text, "dataformat = keel", "\n") text <- paste0(text, "numlabels = ", self$numLabels, "\n") text <- paste0(text, "numrules = ", self$numRules, "\n") text <- paste0(text, "outlabel = MFGAP", "\n") text <- paste0(text, "popsize = ", self$popSize, "\n") text <- paste0(text, "numisland = ", self$numisland, "\n") text <- paste0(text, "steady = ", self$steady, "\n") text <- paste0(text, "numitera = ", self$numIter, "\n") text <- paste0(text, "toursize = ", self$tourSize, "\n") text <- paste0(text, "probmuta = ", self$mutProb, "\n") text <- paste0(text, "amplmuta = ", self$aplMut, "\n") text <- paste0(text, "probmigra = ", self$probMigra, "\n") text <- paste0(text, "proboptimlocal = ", self$probOptimLocal, "\n") text <- paste0(text, "numoptimlocal = ", self$numOptimLocal, "\n") text <- paste0(text, "idoptimlocal = ", self$idOptimLocal, "\n") text <- paste0(text, "nichinggap = ", self$nichinggap, "\n") text <- paste0(text, "maxindniche = ", self$maxindniche, "\n") text <- paste0(text, "probintraniche = ", self$probintraniche, "\n") text <- paste0(text, "probcrossga = ", self$probcrossga, "\n") text <- paste0(text, "probmutaga = ", self$probmutaga, "\n") text <- paste0(text, "lenchaingap = ", self$lenchaingap, "\n") text <- paste0(text, "maxtreeheight = ", self$maxtreeheight, "\n") return(text) } ) )
example.memoise = function() { li = memoise.fun.li(rtutor.default.memoise.funs(), libs="rio") } memoise.fun.li = function(funs, libs=NULL) { restore.point("memoise.fun.li") libs = unique(c("base","utils", libs)) fun.li = lapply(funs, function(str) { restore.point("inner.memoise.fun.li") if (has.substr(str,":::")) { fun.name = str.right.of(str,":::") pkg = str.left.of(str,":::") } else if (has.substr(str,"::")) { fun.name = str.right.of(str,"::") pkg = str.left.of(str,"::") } else { fun.name = str fun = get(fun.name) pkg = getPackageName(environment(fun)) } if (!pkg %in% libs) return(NULL) call = substitute(memoise(pkg::fun.name), list(pkg=as.name(pkg), fun.name=as.name(fun.name))) li = list(eval(call)) names(li) = fun.name li }) fun.li = do.call(c, fun.li) fun.li } rtutor.default.memoise.funs = function() { c("read.csv","read.table","readRDS","foreign::read.dta","readstata13::read.dta13","rio::import", "readr::read_csv") }
chebyshev.c.weight <- function( x ) { n <- length( x ) y <- rep( 0, n ) for ( i in 1:n ) { if ( ( x[i] > -2 ) && ( x[i] < 2 ) ) y[i] <- 1 / ( sqrt( 1 - 0.25 * x[i] * x[i] ) ) } return( y ) }
FstBoot <- function(popdata, fst.method="EBFST", bsrep=100, log.bs=F, locus=F){ calcFst <- eval(parse(text=fst.method)) gpdata0 <- popdata numpop <- gpdata0$npops numloci <- gpdata0$nloci if(fst.method=="EBFST"){ fst0 <- calcFst(gpdata0, locus=locus) fst0.l <- fst0$pairwise$fst.locus fst0 <- fst0$pairwise$fst }else{ fst0 <- calcFst(gpdata0) } gp_locind_resample <- function(popdata, crep){ gpdat <- popdata$pop_list indnames <- popdata$ind_names gpout <- c("bs", popdata$loci_names) select_pop <- sample(1:numpop, numpop, replace=T) for(cpop in 1:numpop){ cbspop <- select_pop[cpop] cgp <- gpdat[[cbspop]] cnind <- nrow(cgp) select_ind <- sample(1:cnind, cnind, replace=T) cgp <- cbind(indnames[[cbspop]][select_ind], ",", cgp[select_ind,]) cgp <- apply(cgp, 1, paste, collapse=" ") gpout <- c(gpout, "POP", cgp) } cat(gpout, file="finepopbs.tmp", sep="\n") gpdat <- read.genepop("finepopbs.tmp") if(log.bs){file.rename("finepopbs.tmp", paste0("gtdata_bs",crep,".txt")) }else{file.remove("finepopbs.tmp")} return(list(gp=gpdat, pop=select_pop)) } bs.poplist <- list() bs.fstlist <- list() bs.fstlist.l <- list() crep <- 1 trial.success <- "" while(crep <= bsrep){ message("Bootstrapping ", crep, "/", bsrep, " ", trial.success) gc() bs.gpdata <- gp_locind_resample(gpdata0, crep) cgp <- bs.gpdata$gp cpop <- bs.gpdata$pop cfst <- cfst.l <- NULL try({ if(fst.method=="EBFST"){ cfst <- calcFst(cgp, locus=locus) cfst.l <- cfst$pairwise$fst.locus cfst <- cfst$pairwise$fst }else{ cfst <- calcFst(cgp) } }) if(sum(!is.finite(cfst))==0 & !is.null(cfst)){ bs.poplist[[crep]] <- cpop bs.fstlist[[crep]] <- cfst bs.fstlist.l[[crep]] <- cfst.l crep <- crep+1 trial.success <- "" }else{ trial.success <- "retry" } } result <- list( bs.pop.list=bs.poplist, bs.fst.list=bs.fstlist, org.fst=fst0 ) if(fst.method=="EBFST"&locus==T){ result$bs.fst.list.locus <- bs.fstlist.l result$org.fst.locus <- fst0.l } return(result) }
plot.haptable <- function(x, separate.plots = F, filename, filetype = "png", use.dd, verbose = T, ...) { .coef <- coef.haptable(x) .markernames <- na.omit(x$marker) .info <- attr(.coef, "info") .haplos <- attr(.coef, "haplos") .n.sel.haplo <- length(.haplos) .maternal <- .info$model$maternal .poo <- .info$model$poo .comb.sex <- .info$model$comb.sex .ref.cat <- .info$haplos$ref.cat .reference.method <- .info$haplos$reference.method if(missing(use.dd)){ .use.dd <- 1:.n.sel.haplo }else{ .use.dd <- use.dd } if(identical(.comb.sex, "males")) .use.dd <- F .use.dd.mat <- .use.dd .use.single.mat <- 1:.n.sel.haplo .prod.file <- !missing(filename) .params <- list(coeff = .coef, ref.cat = .ref.cat, reference.method = .reference.method, haplos = .haplos, markernames = .markernames, maternal = .maternal, poo = .poo, use.dd = .use.dd, verbose = verbose, ...) .params.mat <- .params .params.mat$use.dd <- .use.dd.mat .params.mat$use.single <- .use.single.mat if(!.prod.file){ .oldpar <- par(no.readonly = T) on.exit(par(.oldpar)) if(!.maternal){ .params$type <- 1 invisible(do.call("f.plot.effects", .params)) } if(.maternal & !separate.plots){ par(mfrow = c(2,1), oma = c(2,0,0,0)) .par <- par(no.readonly = T) .params$type <- 3 invisible(do.call("f.plot.effects", .params)) par(mar = .par$mar) .params.mat$type <- 4 invisible(do.call("f.plot.effects", .params.mat)) } if(.maternal & separate.plots){ .params$type <- 1 invisible(do.call("f.plot.effects", .params)) .params.mat$type <- 2 invisible(do.call("f.plot.effects", .params.mat)) } } if(.prod.file){ .jpeg.size <- c(440, 460) if(.n.sel.haplo > 4) .jpeg.size <- .jpeg.size + (.n.sel.haplo - 4) * c(30,0) if(!.maternal){ if(filetype == "png"){ png(filename = filename, width = .jpeg.size[1], height = .jpeg.size[2], pointsize = 9) } if(filetype == "jpeg"){ jpeg(filename = filename, width = .jpeg.size[1], height = .jpeg.size[2], pointsize = 9, quality = 100) } .params$type <- 1 invisible(do.call("f.plot.effects", .params)) dev.off() } if(.maternal & !separate.plots){ if(filetype == "png"){ png(filename = filename, width = .jpeg.size[1], height = .jpeg.size[2], pointsize = 9) } if(filetype == "jpeg"){ jpeg(filename = filename, width = .jpeg.size[1], height = .jpeg.size[2], pointsize = 9, quality = 100) } par(mfrow = c(2,1), oma = c(2,0,0,0)) .par <- par(no.readonly = T) .params$type <- 3 invisible(do.call("f.plot.effects", .params)) par(mar = .par$mar) .params.mat$type <- 4 invisible(do.call("f.plot.effects", .params.mat)) dev.off() } if(.maternal & separate.plots){ if(filetype == "png"){ png(filename = paste("1", filename, sep = ""), width = .jpeg.size[1], height = .jpeg.size[2], pointsize = 9) } if(filetype == "jpeg"){ jpeg(filename = paste("1", filename, sep = ""), width = .jpeg.size[1], height = .jpeg.size[2], pointsize = 9, quality = 100) } .params$type <- 1 invisible(do.call("f.plot.effects", .params)) dev.off() if(filetype == "png"){ png(filename = paste("2", filename, sep = ""), width = .jpeg.size[1], height = .jpeg.size[2], pointsize = 9) } if(filetype == "jpeg"){ jpeg(filename = paste("2", filename, sep = ""), width = .jpeg.size[1], height = .jpeg.size[2], pointsize = 9, quality = 100) } .params.mat$type <- 2 invisible(do.call("f.plot.effects", .params.mat)) dev.off() } } }
library (testthat) context ("Retreieving a primary input vector") siot <- iotable_get ( source = "germany_1990", geo = 'DE', year = 1990, unit = "MIO_EUR", labelling = "short") test_that("correct data is returned", { expect_equal(primary_input_get(data_table = siot, primary_input = "D1")[,3], 296464 ) })
config <- function(appId, instrumentationKey, connectionString, autoTrackPageVisitTime=TRUE, ...) { if (!missing(instrumentationKey)) { assertthat::assert_that(assertthat::is.string(instrumentationKey), is_instrumentation_key(instrumentationKey)) cfg <- list(instrumentationKey = instrumentationKey, ...) } else if (!missing(connectionString)) { assertthat::assert_that( grepl('InstrumentationKey=', connectionString, ignore.case=TRUE), grepl('IngestionEndpoint=', connectionString, ignore.case=TRUE) ) cfg <- list(connectionString=connectionString, ...) } else { stop("An instrumentation key or connection string must be provided!") } assertthat::assert_that(rlang::is_string(appId)) cfg$appId = appId assertthat::assert_that(rlang::is_logical(autoTrackPageVisitTime, n=1)) cfg$autoTrackPageVisitTime <- autoTrackPageVisitTime cfg }
omxRAMtoML <- function(model) { namespace <- imxGenerateNamespace(model) job <- shareData(model) return(RAMtoMLHelper(model, job, namespace)) } RAMtoMLHelper <- function(model, job, namespace) { model <- convertRAMtoMLModel(model, job, namespace) if (length(model@submodels) > 0) { model@submodels <- lapply(model@submodels, RAMtoMLHelper, job, namespace) } return(model) } createNewName <- function(model, namespace, suggestedName) { if (availableName(model, namespace, suggestedName)) { return(suggestedName) } else { return(paste(suggestedName, imxUntitledName(), sep = '_')) } } convertRAMtoMLModel <- function(model, job, namespace) { objective <- model$objective if (is.null(objective)) { return(model) } if (!is(objective, "MxRAMObjective")) { return(model) } modelname <- model@name aName <- imxConvertIdentifier(objective@A, modelname, namespace) sName <- imxConvertIdentifier(objective@S, modelname, namespace) fName <- imxConvertIdentifier(objective@F, modelname, namespace) mName <- imxConvertIdentifier(objective@M, modelname, namespace) iName <- createNewName(model, namespace, 'I') model <- mxModel(model, mxMatrix(type="Iden", nrow = nrow(job[[aName]]), name = iName)) zName <- createNewName(model, namespace, 'Z') zFormula <- substitute(solve(I - A), list(I = as.symbol(iName), A = as.symbol(aName))) algebra <- eval(substitute(mxAlgebra(x, y), list(x = zFormula, y = zName))) model <- mxModel(model, algebra) covName <- createNewName(model, namespace, 'covariance') covFormula <- substitute(F %*% Z %*% S %*% t(Z) %*% t(F), list(F = as.symbol(fName), Z = as.symbol(zName), S = as.symbol(sName))) algebra <- eval(substitute(mxAlgebra(x, y), list(x = covFormula, y = covName))) model <- mxModel(model, algebra) if(!single.na(mName)) { meansFormula <- substitute(t(F %*% Z %*% t(M)), list(F = as.symbol(fName), Z = as.symbol(zName), M = as.symbol(mName))) meansName <- createNewName(model, namespace, 'means') algebra <- eval(substitute(mxAlgebra(x, y), list(x = meansFormula, y = meansName))) model <- mxModel(model, algebra) } translatedNames <- modelManifestNames(job[[fName]]@values, modelname) dataset <- job[[modelname]]@data if (dataset@type == 'raw') { objectiveType <- as.symbol('mxFIMLObjective') if (is.na(mName)) { objective <- eval(substitute(obj(covariance = x, thresholds = z, vector = w, dimnames = u), list(x = covName, z = objective@thresholds, w = objective@vector, u = translatedNames, obj = objectiveType))) } else { objective <- eval(substitute(obj(covariance = x, means = y, thresholds = z, vector = w, dimnames = u), list(x = covName, y = meansName, z = objective@thresholds, w = objective@vector, u = translatedNames, obj = objectiveType))) } } else { objectiveType <- as.symbol('mxMLObjective') if (is.na(mName)) { objective <- eval(substitute(obj(covariance = x, thresholds = z, dimnames = u), list(x = covName, z = objective@thresholds, u = translatedNames, obj = objectiveType))) } else { objective <- eval(substitute(obj(covariance = x, means = y, thresholds = z, dimnames = u), list(x = covName, y = meansName, z = objective@thresholds, u = translatedNames, obj = objectiveType))) } } model@objective <- objective class(model) <- 'MxModel' return(model) }
correlation.systemfit <- function( results, eqni, eqnj ) { nCoefEq <- NULL for( i in 1:length( results$eq ) ) { nCoefEq <- c( nCoefEq, length( coef( results$eq[[ i ]] ) ) ) } cij <- vcov( results )[(1+sum(nCoefEq[1:eqni])-nCoefEq[eqni]):(sum(nCoefEq[1:eqni])), (1+sum(nCoefEq[1:eqnj])-nCoefEq[eqnj]):(sum(nCoefEq[1:eqnj]))] cii <- vcov( results )[(1+sum(nCoefEq[1:eqni])-nCoefEq[eqni]):(sum(nCoefEq[1:eqni])), (1+sum(nCoefEq[1:eqni])-nCoefEq[eqni]):(sum(nCoefEq[1:eqni]))] cjj <- vcov( results )[(1+sum(nCoefEq[1:eqnj])-nCoefEq[eqnj]):(sum(nCoefEq[1:eqnj])), (1+sum(nCoefEq[1:eqnj])-nCoefEq[eqnj]):(sum(nCoefEq[1:eqnj]))] rij <- NULL for( i in 1:nrow( residuals( results ) ) ) { xik <- model.matrix( results$eq[[eqni]] )[i,] xjk <- model.matrix( results$eq[[eqnj]] )[i,] top <- xik %*% cij %*% xjk bottom <- sqrt( ( xik %*% cii %*% xik ) * ( xjk %*% cjj %*% xjk ) ) rijk <- top / bottom rij <- rbind( rij, rijk ) } rij } se.ratio.systemfit <- function( resultsi, resultsj, eqni ) { ratio <- NULL for( i in 1:nrow( residuals( resultsi ) ) ) { xik <- model.matrix( resultsi$eq[[eqni]] )[i,] top <- sqrt( xik %*% vcov( resultsi$eq[[eqni]] ) %*% xik ) bottom <- sqrt( xik %*% vcov( resultsj$eq[[eqni]] ) %*% xik ) rk <- top / bottom ratio <- rbind( ratio, rk ) } ratio } coef.systemfit <- function( object, modified.regMat = FALSE, ... ) { if( modified.regMat ){ if( is.null( object$restrict.regMat ) ){ stop( "coefficients of the modified regressor matrix are not available,", " because argument 'restrict.regMat' has not been used in this estimation." ) } else { return( drop( solve( crossprod( object$restrict.regMat ), t( object$restrict.regMat ) %*% coef( object ) ) ) ) } } else { return( object$coefficients ) } } coef.summary.systemfit <- function( object, modified.regMat = FALSE, ... ) { if( modified.regMat ){ if( is.null( object$coefModReg ) ){ stop( "coefficients of the modified regressor matrix are not available,", " because argument 'restrict.regMat' has not been used in this estimation." ) } else { return( object$coefModReg ) } } else { return( object$coefficients ) } } coef.systemfit.equation <- function( object, ... ) { object$coefficients } coef.summary.systemfit.equation <- function( object, ... ) { object$coefficients } residuals.systemfit <- function( object, ... ) { result <- data.frame( obsNo = c( 1:length( residuals( object$eq[[1]] ) ) ) ) for( i in 1:length( object$eq ) ) { result[[ object$eq[[i]]$eqnLabel ]] <- residuals( object$eq[[i]] ) } result$obsNo <- NULL rownames( result ) <- names( residuals( object$eq[[ 1 ]] ) ) return( result ) } residuals.systemfit.equation <- function( object, na.rm = FALSE, ... ) { if( na.rm ) { return( object$residuals[ !is.na( object$residuals ) ] ) } else { return( object$residuals ) } } vcov.systemfit <- function( object, modified.regMat = FALSE, ... ) { if( modified.regMat ){ if( is.null( object$restrict.regMat ) ){ stop( "coefficients of the modified regressor matrix", " and their covariance matrix are not available,", " because argument 'restrict.regMat' has not been used in this estimation." ) } else { txtxInv <- solve( crossprod( object$restrict.regMat ) ) result <- txtxInv %*% t( object$restrict.regMat ) %*% vcov( object ) %*% object$restrict.regMat %*% txtxInv return( result ) } } else { return( object$coefCov ) } } vcov.systemfit.equation <- function( object, ... ) { object$coefCov } fitted.systemfit <- function( object, ... ) { nEq <- length( object$eq ) fitted.values <- matrix( NA, length( object$eq[[1]]$fitted.values ), nEq ) colnames( fitted.values ) <- as.character( 1:ncol( fitted.values ) ) for(i in 1:nEq ) { fitted.values[ , i ] <- object$eq[[ i ]]$fitted.values colnames( fitted.values )[ i ] <- object$eq[[ i ]]$eqnLabel } rownames( fitted.values ) <- names( fitted( object$eq[[ 1 ]] ) ) return( as.data.frame( fitted.values ) ) } fitted.systemfit.equation <- function( object, na.rm = FALSE, ... ) { if( na.rm ) { return( object$fitted.values[ !is.na( object$fitted.values ) ] ) } else { return( object$fitted.values ) } } model.frame.systemfit <- function( formula, ... ){ mfColNames <- NULL for( i in 1:length( formula$eq ) ) { mfi <- model.frame( formula$eq[[ i ]] ) if( i == 1 ) { result <- mfi } else { for( j in 1:ncol( mfi ) ) { if( ! names( mfi )[ j ] %in% names( result ) ) { result[[ names( mfi )[ j ] ]] <- mfi[ , j ] } } } } return( result ) } model.frame.systemfit.equation <- function( formula, ... ){ if( !is.null( formula$model ) ) { result <- formula$model } else { stop( "returning model frame not possible. Please re-estimate", " the system with control variable 'model'", " set to TRUE" ) } return( result ) }
context("network: HTTP response handling; Parsing response data to R workable variables") bad_http_response <- 'HTTP/1.1 400 OK\r\nContent-Type: application/json; charset=utf-8\r\nVary: Accept-Encoding,User-Agent\r\n\r\nTHE BODY' good_http_response <- 'HTTP/1.1 200 OK\r\nContent-Type: application/json; charset=utf-8\r\nVary: Accept-Encoding,User-Agent\r\n\r\nTHE BODY' test_that("Error on non 200 status response", { expect_error(.extract_response_body(bad_http_response)) }) test_that("Body extraction on successful request", { expect_equal(.extract_response_body(good_http_response), 'THE BODY') }) api_json_response_sample <- "{\"records\": [{\"oid\":198254,\"typ\":\"occ\",\"cid\":20434,\"tna\":\"Alopex lagopus\",\"rnk\":3,\"tid\":43911,\"eag\":1.80000,\"lag\":0.30000,\"rid\":[2048],\"cc2\":\"Canada\",\"sta\":\"Yukon\",\"cxi\":33,\"ein\":740,\"lin\":923},{\"oid\":198265,\"typ\":\"occ\",\"cid\":20436,\"tna\":\"Alopex lagopus\",\"rnk\":3,\"tid\":43911,\"eag\":1.80000,\"lag\":0.30000,\"rid\":[2048],\"cc2\":\"Canada\",\"sta\":\"Yukon\",\"cxi\":33,\"ein\":740,\"lin\":923},{\"oid\":199751,\"typ\":\"occ\",\"cid\":20626,\"tna\":\"Alopex lagopus\",\"rnk\":3,\"tid\":43911,\"eag\":0.12600,\"lag\":0.01170,\"rid\":[1784],\"cc2\":\"Canada\",\"sta\":\"Yukon\",\"cxi\":922,\"ein\":922,\"lin\":922},{\"oid\":199941,\"typ\":\"occ\",\"cid\":20643,\"tna\":\"Alopex lagopus\",\"rnk\":3,\"tid\":43911,\"eag\":0.12600,\"lag\":0.01170,\"rid\":[2872],\"cc2\":\"United States\",\"sta\":\"Alaska\",\"cny\":\"North Slope\",\"cxi\":922,\"ein\":922,\"lin\":922},{\"oid\":373590,\"typ\":\"occ\",\"cid\":35359,\"tna\":\"Alopex\",\"rnk\":5,\"tid\":41193,\"eag\":5.33300,\"lag\":0.01170,\"rid\":[9534],\"cc2\":\"Hungary\",\"sta\":\"Barany\",\"cxi\":1,\"ein\":34,\"lin\":33},{\"oid\":485281,\"typ\":\"occ\",\"cid\":48587,\"tna\":\"Alopex lagopus\",\"rnk\":3,\"tid\":43911,\"eag\":0.12600,\"lag\":0.01170,\"rid\":[12964],\"cc2\":\"Russian Federation\",\"sta\":\"Respublika Saha (Jakutija)\",\"cxi\":922,\"ein\":922,\"lin\":922},{\"oid\":766675,\"typ\":\"occ\",\"cid\":81830,\"tna\":\"Alopex lagopus\",\"rnk\":3,\"tid\":43911,\"eag\":0.12600,\"lag\":0.01170,\"rid\":[27585],\"cc2\":\"United States\",\"sta\":\"Alaska\",\"cxi\":922,\"ein\":922,\"lin\":922}]}" api_json_response_sample_returns <- '{\n"records": [\n{"oid":1001,"typ":"occ","cid":160,"tna":"Wellerella","rnk":5,"tid":29018,"oei":"Missourian","eag":305.90000,"lag":303.40000,"rid":[12]}\n]\n}\n' test_that(".parse_raw_data for a JSON string response is a data.frame", { parsed <- .parse_raw_data(api_json_response_sample) expect_is(parsed, 'data.frame') }) test_that(".parse_raw_data for a JSON string that includes \n yields just one row in the dataframe", { parsed <- .parse_raw_data(api_json_response_sample_returns) expect_equal(dim(parsed)[1], 1) }) test_that("A JSON string with different columns for some occurency resolves to a data.frame comprising all the columns", { expected_names <- c("oid", "typ", "cid", "tna", "rnk", "tid", "eag", "lag", "rid", "cc2", "sta", "cxi", "ein", "lin", "cny") resp_names <- names(.parse_raw_data(api_json_response_sample)) expect_identical(resp_names, expected_names) })
rl_record_policy <- function(x, last_result, trading_system, path_terminal, fileName = "SystemControl"){ requireNamespace("stringr", quietly = TRUE) requireNamespace("dplyr", quietly = TRUE) is_T3 <- str_detect(path_terminal, "Terminal3") is_T4 <- str_detect(path_terminal, "Terminal4") if(is_T3 == TRUE) { addition <- 200 } else if(is_T4 == TRUE) { addition <- 300 } else { addition <- 200 } y <- x %>% dplyr::filter(TradeState == last_result) %$% Policy if(y == "ON"){ decision_DF <- data.frame(MagicNumber = trading_system + addition, IsEnabled = 1) composed_name <- paste0(fileName, as.character(decision_DF[1, 1]), ".csv") f_name <- file.path(path_terminal, composed_name) write.csv(decision_DF, file = f_name, quote = FALSE, row.names = FALSE) } else { decision_DF <- data.frame(MagicNumber = trading_system + addition, IsEnabled = 0) composed_name <- paste0(fileName, as.character(decision_DF[1, 1]), ".csv") f_name <- file.path(path_terminal, composed_name) write.csv(decision_DF, file = f_name, quote = FALSE, row.names = FALSE) } }
dbgamma <- function(x, prob, scale, shape) { if(length(prob)==1) prob <- rep(prob, length(x)) if(length(scale)==1) scale <- rep(scale, length(x)) if(length(shape)==1) shape <- rep(shape, length(x)) d <- 1-prob d[x>0] <- prob[x>0]*dgamma(x[x>0], scale=scale[x>0], shape=shape[x>0]) d }
`goodness.cca` <- function (object, choices, display = c("species", "sites"), model = c("CCA", "CA"), summarize = FALSE, addprevious = FALSE, ...) { display <- match.arg(display) model <- match.arg(model) if (!inherits(object, "cca")) stop("can be used only with objects inheriting from 'cca'") if (inherits(object, "capscale")) stop("not implemented for 'capscale'") if (inherits(object, c("capscale", "dbrda")) && display == "species") stop(gettextf("cannot analyse species with '%s'", object$method)) v <- sqrt(weights(object, display="species")) * object[[model]]$v if (is.null(v)) stop(gettextf("model = '%s' does not exist", model)) if (display == "sites") u <- sqrt(weights(object, display="sites")) * object[[model]]$u eig <- object[[model]]$eig if (!inherits(object, "dbrda")) eig <- eig[eig > 0] if (inherits(object, "dbrda")) { u <- cbind(u, object[[model]][["imaginary.u"]]) display <- "dbrda" } All <- ordiYbar(object, "initial") if (is.null(All)) stop("old style result object: update() your model") tot <- switch(display, "species" = colSums(All^2), "sites" = rowSums(All^2), "dbrda" = diag(All)) if (!missing(choices)) { choices <- choices[choices <= length(eig)] if (display != "dbrda") v <- v[, choices, drop = FALSE] if (display %in% c("sites", "dbrda")) u <- u[, choices, drop = FALSE] eig <- eig[choices] } if (addprevious) { if (!is.null(object$pCCA)) prev <- ordiYbar(object, "pCCA") else prev <- 0 if (model == "CA" && !is.null(object$CCA)) prev <- prev + ordiYbar(object, "CCA") } if (display == "species") { if (length(eig) == 1) out <- v^2 * eig else out <- t(apply(v^2 %*% diag(eig, nrow=length(eig)), 1, cumsum)) if (addprevious) out <- out + colSums(prev^2) dimnames(out) <- dimnames(v) } else if (display == "sites") { out <- matrix(0, nrow(u), ncol(u)) if (addprevious) mat <- prev else mat <- 0 for (i in seq_len(ncol(u))) { mat <- tcrossprod(u[,i], v[,i]) * sqrt(eig[i]) + mat out[,i] <- rowSums(mat^2) } dimnames(out) <- dimnames(u) } else { out <- matrix(0, nrow(u), ncol(u)) mat <- 0 for (i in seq_len(ncol(u))) { mat <- u[,i]^2 * eig[i] + mat out[,i] <- mat } dimnames(out) <- dimnames(u) } out/tot }
.isSupportedFormat <- function(dname) { res <- dname %in% c(.nativeDrivers(), 'ascii', 'CDF') if (!res) { res <- .isSupportedGDALFormat(dname) } return(res) } .gdalWriteFormats <- function() { .requireRgdal() gd <- rgdal::gdalDrivers() gd <- as.matrix( gd[gd[,3] == T, ] ) i <- which(gd[,1] %in% c('VRT', 'MEM', 'MFF', 'MFF2')) gd[-i,] } .isSupportedGDALFormat <- function(dname) { .requireRgdal() gd <- .gdalWriteFormats() res <- dname %in% gd[,1] if (!res) { stop(paste(dname, "is not a supported file format. See writeFormats()" ) ) } return(res) } .getGdalDType <- function(dtype, format='') { if (!(dtype %in% c('LOG1S', 'INT1S', 'INT2S', 'INT4S', 'INT1U', 'INT2U', 'INT4U', 'FLT4S', 'FLT8S'))) { stop('not a valid data type') } if (dtype == 'INT1S') { warning('data type "INT1S" is not available in GDAL. Changed to "INT2S" (you may prefer "INT1U" (Byte))') dtype <- 'INT2S' } type <- .shortDataType(dtype) size <- dataSize(dtype) * 8 if (format=='BMP' | format=='ADRG' | format=='IDA' | format=='SGI') { return('Byte') } if (format=='PNM') { if (size == 8) { return('Byte') } else { return('UInt16') } } if (format=='RMF') { if (type == 'FLT') { return('Float64') } } if (type == 'LOG') { warning('data type "LOG" is not available in GDAL. Changed to "INT1U"') return('Byte') } if (type == 'INT') { type <- 'Int' if (size == 64) { size <- 32 warning('8 byte integer values not supported by rgdal, changed to 4 byte integer values') } if (! dataSigned(dtype) ) { if (size == 8) { return('Byte') } else { type <- paste('U', type, sep='') } } } else { type <- 'Float' } return(paste(type, size, sep='')) } .getRasterDType <- function(dtype) { if (!(dtype %in% c('Byte', 'UInt16', 'Int16', 'UInt32','Int32', 'Float32', 'Float64', 'CInt16', 'CInt32', 'CFloat32', 'CFloat64'))) { return ('FLT4S') } else if (dtype == 'Byte') { return('INT1U') } else if (dtype == 'UInt16') { return('INT2U') } else if (dtype == 'Int16' | dtype == 'CInt16') { return('INT2S') } else if (dtype == 'UInt32') { return('INT4U') } else if (dtype == 'Int32' | dtype == 'CInt32') { return('INT4S') } else if (dtype == 'Float32' | dtype == 'CFloat32' ) { return('FLT4S') } else if (dtype == 'Float64' | dtype == 'CFloat64' ) { return('FLT8S') } else { return('FLT4S') } }
`alpha95` <- function(az , iang) { DEG2RAD = pi/180 a = iang * DEG2RAD; b = (90-az) * DEG2RAD; x = sin(a) * cos(b); y = sin(a) * sin(b); z = cos(a); v = cbind(x,y,z); KapT = t(v) %*% v B = length(x)*diag( 3) - KapT E1 = eigen(B) E = eigen( KapT ) Rn = sum(y ) Re = sum(x ) Rd = sum(z ) N = length(x); Ir = 180*atan2( sqrt(Rn^2+Re^2), Rd )/pi; Dr = 180*atan2(Re, Rn)/pi; R = sqrt(Rn^2+Re^2+Rd^2) K = (N-1)/(N-R); S = 81/sqrt(K); Kappa = log(E$values[1]/E$values[2])/ log(E$values[2]/E$values[3]) Alpha95 = 180*acos(1- ( (N-R)*((20^(1/(N-1)))-1)/R))/pi; return(list(Ir=Ir, Dr=Dr, R=R, K=K, S=S, Alph95=Alpha95, Kappa =Kappa, E=E, MAT=v)) }
plot.pd2bart = function( x, plquants =c(.05,.95), contour.color='white', justmedian=TRUE, ... ) { pdquants = apply(x$fd,2,quantile,probs=c(plquants[1],.5,plquants[2])) qq <- vector('list',3) for (i in 1:3) qq[[i]] <- matrix(pdquants[i,],nrow=length(x$levs[[1]])) if(justmedian) { zlim = range(qq[[2]]) vind = c(2) } else { par(mfrow=c(1,3)) zlim = range(qq) vind = 1:3 } for (i in vind) { image(x=x$levs[[1]],y=x$levs[[2]],qq[[i]],zlim=zlim, xlab=x$xlbs[1],ylab=x$xlbs[2],...) contour(x=x$levs[[1]],y=x$levs[[2]],qq[[i]],zlim=zlim, ,add=TRUE,method='edge',col=contour.color) title(main=c('Lower quantile','Median','Upper quantile')[i]) } }
library(tidystats) library(tidyverse) library(BayesFactor) data(puzzles) data(attitude) data(raceDolls) t <- c(-.15, 2.39, 2.42, 2.43) N <- c(100, 150, 97, 99) set.seed(1) generalTestBF <- generalTestBF(RT ~ shape*color + ID, data = puzzles, whichRandom = "ID", neverExclude = "ID", progress = FALSE) generalTestBF temp <- tidy_stats(generalTestBF) set.seed(1) bfFull <- lmBF(RT ~ shape + color + shape:color + ID, data = puzzles, whichRandom = "ID", ) bfFull set.seed(1) bfMain <- lmBF(RT ~ shape + color + ID, data = puzzles, whichRandom = "ID") bfMain set.seed(1) bfMainFull <- bfMain / bfFull bfMainFull temp <- tidy_stats(bfFull) temp <- tidy_stats(bfMain) temp <- tidy_stats(bfMainFull) attitudeBF <- regressionBF(rating ~ ., data = attitude, progress = FALSE) head(attitudeBF) attitudeBFBest <- attitudeBF / attitudeBF[63] head(attitudeBFBest) temp <- tidy_stats(attitudeBF) temp <- tidy_stats(attitudeBFBest) sleepTTestBF <- ttestBF(x = sleep$extra[sleep$group == 1], y = sleep$extra[sleep$group == 2], paired = TRUE) sleepTTestBF temp <- tidy_stats(sleepTTestBF) sleepAnovaBF <- anovaBF(extra ~ group + ID, data = sleep, whichRandom = "ID", progress = FALSE) sleepAnovaBF puzzlesAnovaBF = anovaBF(RT ~ shape * color + ID, data = puzzles, whichRandom = "ID", whichModels = 'top', progress = FALSE) puzzlesAnovaBF temp <- tidy_stats(sleepAnovaBF) temp <- tidy_stats(puzzlesAnovaBF) correlationBF = correlationBF(y = iris$Sepal.Length, x = iris$Sepal.Width) correlationBF temp <- tidy_stats(correlationBF) contingencyTableBF = contingencyTableBF(raceDolls, sampleType = "indepMulti", fixedMargin = "cols") contingencyTableBF temp <- tidy_stats(contingencyTableBF) proportionBF = proportionBF(y = 15, N = 25, p = .5) proportionBF temp <- tidy_stats(proportionBF) metaBF = meta.ttestBF(t, N, rscale = 1, nullInterval = c(0, Inf)) metaBF temp <- tidy_stats(metaBF) results <- list() results <- results %>% add_stats(generalTestBF) %>% add_stats(bfFull) %>% add_stats(bfMain) %>% add_stats(bfMainFull) %>% add_stats(attitudeBF) %>% add_stats(attitudeBFBest) %>% add_stats(sleepTTestBF) %>% add_stats(sleepAnovaBF) %>% add_stats(puzzlesAnovaBF) %>% add_stats(correlationBF) %>% add_stats(contingencyTableBF) %>% add_stats(proportionBF) %>% add_stats(metaBF) write_stats(results, "inst/test_data/BayesFactor.json")
uptakeFuncDefault = function(strainName, groupName, pathName, varName, keyResName, subst, ess, boost, maxGrowthRate, growthLim, yield, nonBoostFrac, stoichiom, parms) { if (length(ess) > 0) { ess.lim = prod(growthLim[ess], na.rm = TRUE) } if (length(boost) > 0) { boost.lim = prod(growthLim[boost], na.rm = TRUE) nbf = nonBoostFrac[boost] } if (varName %in% subst) { if (length(ess) == 0 & length(boost) == 0) { v = maxGrowthRate[varName] * growthLim[varName]/yield[varName] } else if (length(ess) > 0 & length(boost) == 0) { v = ess.lim * maxGrowthRate[varName] * growthLim[varName]/yield[varName] } else if (length(ess) == 0 & length(boost) > 0) { v = (nbf + (1 - nbf) * boost.lim) * maxGrowthRate[varName] * growthLim[varName]/yield[varName] } } else if (varName %in% ess) { if (length(subst) == 0) { if (varName == keyResName) { v = maxGrowthRate[keyResName] * ess.lim/yield[keyResName] } else { v = (stoichiom[varName]/stoichiom[keyResName]) * maxGrowthRate[keyResName] * ess.lim/yield[keyResName] } } else { subst.uptake = ess.lim * sum(maxGrowthRate[subst] * growthLim[subst]/yield[subst]) v = (stoichiom[varName]/mean(stoichiom[subst])) * subst.uptake } } else if (varName %in% boost) { subst.uptake = (1 - nbf) * boost.lim * sum(maxGrowthRate[subst] * growthLim[subst]/yield[subst]) v = subst.uptake * stoichiom[boost]/mean(stoichiom[subst]) } else { v = 0 } return(max(v, 0)) }
print.POST <- function(x, ..., siglevel = 1.0) { attr(x = x, which = "tree") <- NULL x <- unclass(x = x) if (siglevel < 1.0) { if (ncol(x = x) == 3L) { showi <- x[,1L] <= siglevel if (any(showi)) { cat("POST: p-values <= ", siglevel, "\n") print(x = x[showi,c(1L:3L),drop=FALSE]) } else { cat("POST: No p-values <= ", siglevel, "\n") } showi <- x[,2L] <= siglevel if (any(showi)) { cat("\nSingle OTU test: p-values <= ", siglevel, "\n") print(x = x[showi,2L,drop=FALSE]) } else { cat("\nSingle OTU test: No p-values <= ", siglevel, "\n") } } else { showi <- x[,1L] <= siglevel if (any(showi)) { cat("Single OTU test: p-values <= ", siglevel, "\n") print(x = x[showi,1L,drop=FALSE]) } else { cat("Single OTU test: No p-values <= ", siglevel, "\n") } } } else { print(x = x) } }
bd.sim <- function(n0, lambda, mu, tMax, lShape = NULL, mShape = NULL, envL = NULL, envM = NULL, lShifts = NULL, mShifts = NULL, nFinal = c(0, Inf), nExtant = c(0, Inf), trueExt = FALSE) { if ((is.numeric(lambda) & length(lambda) == 1) & (is.numeric(mu) & length(mu) == 1) & (is.null(c(lShape, mShape, envL, envM, lShifts, mShifts)))) { l <- lambda m <- mu return(bd.sim.constant(n0, l, m, tMax, nFinal, nExtant, trueExt)) } else { l <- make.rate(lambda, tMax, envL, lShifts) m <- make.rate(mu, tMax, envM, mShifts) return(bd.sim.general(n0, l, m, tMax, lShape, mShape, nFinal, nExtant, trueExt)) } }
test_that("format_string() works as expected", { expect_identical(as.character(format_string("L", 7)), "110100101110110") expect_identical(as.character(format_string("M", 0)), "101010000010010") expect_identical(as.character(format_string("Q", 3)), "011101000000110") expect_identical(as.character(format_string("H", 2)), "001110011100111") })
preserve_attributes <- function(fn) { function(.data, ...) { out <- NextMethod() if (any(miss_col <- !(.data %@% "key" %in% colnames(out)))) { miss_nm <- colnames(.data)[miss_col] warn(glue( "This function lost the ", glue_collapse(miss_nm, sep = ", ", last = " and "), " columns! These values will be removed from the report." )) out <- mutate(out, !!!set_names(rep(list(NA), sum(miss_col)), miss_nm)) } out <- structure(out, class = union(class(.data), class(out))) attr <- append(attributes(out), attributes(.data)) `attributes<-`(out, attr[!duplicated(names(attr))]) } } dplyr::`%>%` dplyr::mutate mutate.vitae_preserve <- preserve_attributes(dplyr::mutate) dplyr::transmute transmute.vitae_preserve <- preserve_attributes(dplyr::transmute) dplyr::group_by group_by.vitae_preserve <- preserve_attributes(dplyr::group_by) dplyr::summarise summarise.vitae_preserve <- preserve_attributes(dplyr::summarise) dplyr::rename rename.vitae_preserve <- preserve_attributes(dplyr::rename) dplyr::arrange arrange.vitae_preserve <- preserve_attributes(dplyr::arrange) dplyr::select select.vitae_preserve <- preserve_attributes(dplyr::select) dplyr::filter filter.vitae_preserve <- preserve_attributes(dplyr::filter) dplyr::distinct distinct.vitae_preserve <- preserve_attributes(dplyr::distinct) dplyr::slice slice.vitae_preserve <- preserve_attributes(dplyr::slice)
unique.circular <- function (x, ...) { z <- unique.default(x, ...) circularp(z) <- circularp(x) class(z) <- class(x) return(z) }
vfpripo <- function(ck, pro){ if (is.finite(ck) & ck >= 0 & ck <= 1) { npro = length(pro) k = min(which(pro > 1)) - 1 b = NULL b[k] = pro[k] - ck for(i in (k + 1):npro) { b[i] = b[i - 1]/pro[i] } bb = 0 a = list() for(j in npro:(k+1)) { if (j == npro) a[[j]] = seq(b[j], b[j - 1], b[j]) else { a[[j]] = seq(2*b[j], b[j-1], b[j] ) } } h = c(1e-14, 1e-09) for(i in npro:(k+1)) { h = c(h, as.numeric(a[[i]])) } return(c(ck + h, pro[(k-1):1])) } else {return(NaN)} }
as_eml_document <- function(x, root = "eml", ns ="eml") { doc <- xml2::xml_new_document() add_node(x, doc, root) xml2::xml_set_namespace(xml2::xml_root(doc), ns) doc } add_node <- function(x, parent, tag) { if (is.atomic(x)) { return() } if(!is.na(suppressWarnings(as.integer(tag)))){ return(xml2::xml_set_text(parent, paste(x, collapse=""))) } if(!is.null(names(x)) & length(x) > 0){ parent <- xml2::xml_add_child(parent, tag) } if(tag %in% c("para", "section")){ if(length(x) >= 1) { for(i in seq_along(x)){ if(grepl("<\\w+>", x[[i]])){ n <- read_xml(paste0("<", tag, ">", x[[i]], "</", tag, ">")) xml2::xml_add_child(parent, n, .copy = TRUE) } else { textType <- xml2::xml_add_child(parent, tag) xml2::xml_set_text(textType, as.character(x[[i]])) } } return() } } x <- sort_properties(x, tag) update_tag <- !is.null(names(x)) for(i in seq_along(x)){ if(is.atomic(x[[i]])){ serialize_atomics(x[[i]], parent, tag, names(x)[[i]]) } next_tag <- tag if(update_tag){ next_tag <- names(x)[[i]] } add_node(x[[i]], parent, next_tag) } } serialize_atomics <- function(x, parent, tag, key){ if(is.null(key)){ textType <- xml2::xml_add_child(parent, tag) return(xml2::xml_set_text(textType, as.character(x))) } if(key %in% c("para", "section")){ if(grepl("<\\w+>", x)){ n <- read_xml(paste0("<", key, ">", x, "</", key, ">")) xml2::xml_add_child(parent, n, .copy = TRUE) return() } } if(grepl("^@*id$", key)){ if(grepl("^_:b\\d+", x)){ return() } if(!any(grepl("^@*id$", eml_db[[eml_version()]][[tag]]))){ return() } } is_attr <- FALSE order <- eml_db[[eml_version()]][[tag]] if(length(order) > 0 & !is.na(key)){ is_attr <- any(grepl(paste0("^ } key <- gsub("^schemaLocation$", "xsi:schemaLocation", key) key <- gsub("^lang$", "xml:lang", key) if(grepl("xmlns:\\w+", key)) is_attr <- TRUE if(grepl("xml:\\w+", key)) is_attr <- TRUE if(grepl("xsi:\\w+", key)) is_attr <- TRUE if(length(key) > 0){ if(!is.na(suppressWarnings(as.integer(key)))){ return(xml2::xml_set_text(parent, paste(as.character(x), collapse=""))) } if(!is_attr){ if(xml_name(parent) == key){ xml2::xml_set_text(parent, as.character(x)) } else { textType <- xml2::xml_add_child(parent, key) xml2::xml_set_text(textType, as.character(x)) } } else { xml2::xml_set_attr(parent, key, x) } } } sort_properties <- function(x, tag){ n <- names(x) children <- eml_db[[eml_version()]][[tag]] if(length(children) == 0 | length(n) == 0) return(x) is_attr <- grep("^( possible_attrs <- unique(gsub("^( c(children[is_attr], "id", "schemaLocation"))) attrs <- which(n %in% possible_attrs) order <- unique(c(gsub("^( nodes <- x if(length(attrs) > 0 ){ n <- n[-attrs] nodes <- x[-attrs] } if(!all(n %in% order)) return(x) fixed <- names(sort( vapply(n,function(i) which(i == order), integer(1)))) c(x[attrs],nodes[fixed]) }
processDivRates <- function(speciation_time_log = "", speciation_rate_log = "", extinction_time_log = "", extinction_rate_log = "", fossilization_time_log = "", fossilization_rate_log = "", burnin = 0.25, probs = c(0.025, 0.975), summary = "mean") { if (is.character(speciation_time_log) == FALSE) stop("speciation_time_log must be a character string or vector of strings") if (is.character(speciation_rate_log) == FALSE) stop("speciation_rate_log must be a character string or vector of strings") if (is.character(extinction_time_log) == FALSE) stop("extinction_time_log must be a character string or vector of strings") if (is.character(extinction_rate_log) == FALSE) stop("extinction_rate_log must be a character string or vector of strings") if (is.character(fossilization_time_log) == FALSE) stop("fossilization_time_log must be a character string vector of strings") if (is.character(fossilization_rate_log) == FALSE) stop("fossilization_rate_log must be a character string vector of strings") if (fossilization_time_log != "" & fossilization_rate_log == "") stop("both please provide both fossilization rates and times, or neither") if (fossilization_time_log == "" & fossilization_rate_log != "") stop("both please provide both fossilization rates and times, or neither") do_speciation_time_log_exist <- file.exists(speciation_time_log) if (any(do_speciation_time_log_exist == FALSE) == TRUE) { stop( paste0( "Some speciation_time_log files do not exist:", paste0("\t", speciation_time_log[do_speciation_time_log_exist == FALSE]), sep = "\n" ) ) } do_speciation_rate_log_exist <- file.exists(speciation_rate_log) if (any(do_speciation_rate_log_exist == FALSE) == TRUE) { stop( paste0( "Some speciation_rate_log files do not exist:", paste0("\t", speciation_rate_log[do_speciation_rate_log_exist == FALSE]), sep = "\n" ) ) } do_extinction_time_log_exist <- file.exists(extinction_time_log) if (any(do_extinction_time_log_exist == FALSE) == TRUE) { stop( paste0( "Some extinction_time_log files do not exist:", paste0("\t", extinction_time_log[do_extinction_time_log_exist == FALSE]), sep = "\n" ) ) } do_extinction_rate_log_exist <- file.exists(extinction_rate_log) if (any(do_extinction_rate_log_exist == FALSE) == TRUE) { stop( paste0( "Some extinction_rate_log files do not exist:", paste0("\t", extinction_rate_log[do_extinction_rate_log_exist == FALSE]), sep = "\n" ) ) } if (fossilization_time_log != "") { do_fossilization_time_log_exist <- file.exists(fossilization_time_log) if (any(do_fossilization_time_log_exist == FALSE) == TRUE) { stop( paste0( "Some fossilization_time_log files do not exist:", paste0("\t", fossilization_time_log[do_fossilization_time_log_exist == FALSE]), sep = "\n" ) ) } } if (fossilization_rate_log != "") { do_fossilization_rate_log_exist <- file.exists(fossilization_rate_log) if (any(do_fossilization_rate_log_exist == FALSE) == TRUE) { stop( paste0( "Some fossilization_rate_log files do not exist:", paste0("\t", fossilization_rate_log[do_fossilization_rate_log_exist == FALSE]), sep = "\n" ) ) } } speciation_time <- readTrace(paths = speciation_time_log, burnin = burnin) speciation_rate <- readTrace(paths = speciation_rate_log, burnin = burnin) extinction_time <- readTrace(paths = extinction_time_log, burnin = burnin) extinction_rate <- readTrace(paths = extinction_rate_log, burnin = burnin) if (fossilization_time_log != "") { fossilization_time <- readTrace(paths = fossilization_time_log, burnin = burnin) fossilization_rate <- readTrace(paths = fossilization_rate_log, burnin = burnin) } else { fossilization_time <- NULL fossilization_rate <- NULL } if (is.null(fossilization_time)) { trace_lengths_same <- identical( length(speciation_time), length(speciation_rate), length(extinction_time), length(extinction_rate) ) } else { trace_lengths_same <- identical( length(speciation_time), length(speciation_rate), length(extinction_time), length(extinction_rate), length(fossilization_time), length(fossilization_rate) ) } if (trace_lengths_same == FALSE) { stop("You must provide the same number of log files for each parameter type.") } else if (trace_lengths_same == TRUE) { if (length(speciation_time) == 0) { stop("You must provide at least one log file per parameter type.") } else if (length(speciation_time) > 1) { stop("Currently, only one log file per parameter type is supported.") } else if (length(speciation_time) == 1) { speciation_time <- speciation_time[[1]] speciation_rate <- speciation_rate[[1]] extinction_time <- extinction_time[[1]] extinction_rate <- extinction_rate[[1]] if (!is.null(fossilization_time)) { fossilization_time <- fossilization_time[[1]] fossilization_rate <- fossilization_rate[[1]] } speciation_time$`interval_times[0]` <- rep(0, nrow(speciation_time)) extinction_time$`interval_times[0]` <- rep(0, nrow(extinction_time)) if (!is.null(fossilization_time)) { fossilization_time$`interval_times[0]` <- rep(0, nrow(fossilization_time)) } net_diversification_rate <- as.matrix(speciation_rate[, grepl("speciation", colnames(speciation_rate))]) - as.matrix(extinction_rate[, grepl("extinction", colnames(extinction_rate))]) colnames(net_diversification_rate) <- paste( rep("net_div", times = ncol(net_diversification_rate)), rep("[", times = ncol(net_diversification_rate)), seq_len(ncol(net_diversification_rate)), rep("]", times = ncol(net_diversification_rate)), sep = "" ) relative_extinction_rate <- as.matrix(extinction_rate[, grepl("extinction", colnames(extinction_rate))]) / as.matrix(speciation_rate[, grepl("speciation", colnames(speciation_rate))]) colnames(relative_extinction_rate) <- paste( rep("rel_ext", times = ncol(relative_extinction_rate)), rep("[", times = ncol(relative_extinction_rate)), seq_len(ncol(relative_extinction_rate)), rep("]", times = ncol(relative_extinction_rate)), sep = "" ) rates <- list( "speciation rate" = speciation_rate, "extinction rate" = extinction_rate, "net-diversification rate" = net_diversification_rate, "relative-extinction rate" = relative_extinction_rate, "fossilization rate" = fossilization_rate, "speciation time" = speciation_time, "extinction time" = extinction_time, "fossilization time" = fossilization_time ) plotdata <- .makePlotData(rates = rates, probs = probs, summary = summary) return(plotdata) } } }
library(hamcrest) expected <- c(0x1.f777e71439a25p+4 + 0x1.0efd4d78363dcp-3i, -0x1.099b82b08dcdep+5 + -0x1.1f60eb3e91a8p-3i, 0x1.4adc6cafd59bp+5 + 0x1.2f7bee7cb753p-3i, -0x1.367b7606366a5p+5 + -0x1.3f4a458e312ccp-3i, 0x1.627e95762bd98p+2 + 0x1.4ec7f22d6bc6ap-3i, -0x1.9d0df5bc1f5abp+4 + -0x1.5df10a75f9a6fp-3i, 0x1.797a3e022c469p+4 + 0x1.6cc1b9e1b31p-3i, -0x1.0f7fd60c7a499p+5 + -0x1.7b3642406dd32p-3i, 0x1.4c2d7f1bb0ebp+5 + 0x1.894afcaa11659p-3i, -0x1.867625825ca31p+5 + -0x1.96fc5a6ac941dp-3i, 0x1.3c27fd1e0933ap+5 + 0x1.a446e5e918fc6p-3i, -0x1.0ff7c93080fadp+5 + -0x1.b127438599bc3p-3i, 0x1.19e1f35719edfp+5 + 0x1.bd9a327427adep-3i, -0x1.eeb57e415035ep+4 + -0x1.c99c8d8e4759cp-3i, 0x1.d455c838826bap+4 + 0x1.d52b4c1e908f2p-3i, -0x1.398563f647b4ep+5 + -0x1.e04382a4e7efdp-3i, 0x1.e0527c24c1e2dp+5 + 0x1.eae2639358bep-3i, -0x1.fec95c0cc721fp+5 + -0x1.f50540035df2p-3i, 0x1.51ed325df1cbcp+5 + 0x1.fea988636b9aep-3i, -0x1.4313783cea8dap+5 + -0x1.03e6668e478aap-2i, 0x1.76f9592b716eep+4 + 0x1.08365f97fcf3ep-2i, -0x1.ca2cf6d606bcap+3 + -0x1.0c439866288ecp-2i, 0x1.100307418cdbcp+5 + 0x1.100d0aed4d9c4p-2i, -0x1.19deaf546e54cp+5 + -0x1.1391c24153e1ep-2i, 0x1.8e4c17969b4fap+4 + 0x1.16d0dad36891dp-2i, -0x1.299c5fa51131ap+5 + -0x1.19c982ab7b5cdp-2i, 0x1.6a35f816084fdp+5 + 0x1.1c7af99d4b064p-2i, -0x1.1b67b8d0f0d1dp+5 + -0x1.1ee49178f1dadp-2i, 0x1.1b9c7f041d515p+5 + 0x1.2105ae36e7d17p-2i, -0x1.61fd0b8438adfp+5 + -0x1.22ddc61f6de77p-2i, 0x1.3171b08060711p+5 + 0x1.246c61ed58c61p-2i, -0x1.23be178d4f4d7p+5 + -0x1.25b11cec3334ep-2i, 0x1.2293585544099p+5 + 0x1.26aba511aee97p-2i, -0x1.b1a3e70608a88p+5 + -0x1.275bbb125ecbep-2i, 0x1.a468e822288b4p+4 + 0x1.27c13271b49bdp-2i, -0x1.f4ec457fbc4d8p+4 + -0x1.27dbf18d3e1e8p-2i, 0x1.7f1bd98e661f1p+4 + 0x1.27abf1a31ee08p-2i, -0x1.3b05e1cd862p+4 + -0x1.27313ed3c578ep-2i, 0x1.16d0cd781ecd8p+5 + 0x1.266bf81edb3e2p-2i, -0x1.f295f21a954f8p+4 + -0x1.255c4f5b6f749p-2i, 0x1.35ee54932c2a2p+5 + 0x1.2402892b5f69ap-2i, -0x1.8937060b0635fp+4 + -0x1.225efce9fffb9p-2i, 0x1.a4917473434ccp+5 + 0x1.207214960bb94p-2i, -0x1.83c48991d9495p+5 + -0x1.1e3c4cb6db3c3p-2i, 0x1.b8c986f24fc3ap+5 + 0x1.1bbe343cefa12p-2i, -0x1.e5cbb5dcc68b7p+5 + -0x1.18f86c5dd50dep-2i, 0x1.3df8cb4c57f4bp+5 + 0x1.15eba86b68d9ap-2i, -0x1.35bd47daa2e13p+5 + -0x1.1298ada68bc36p-2i, 0x1.4d4d5b292177cp+5 + 0x1.0f00530d4c205p-2i, -0x1.c4ff4b68ebcc6p+4 + -0x1.0b238124955b6p-2i, 0x1.1390501c6bb9ep+4 + 0x1.070331bd7121cp-2i, -0x1.66218d81e22e2p+5 + -0x1.02a06fb5ea62ap-2i, 0x1.854d7a0b38318p+4 + 0x1.fbf8ad6b42d47p-3i, -0x1.20cfa9f995dbap+5 + -0x1.f23025cc44262p-3i, 0x1.e0e24343a982bp+5 + 0x1.e7e9c14e1d752p-3i, -0x1.fd67a451179fap+3 + -0x1.dd28187c64297p-3i, 0x1.23acf5b31f67p+4 + 0x1.d1ede3071a22ep-3i, -0x1.198dba702d9c2p+5 + -0x1.c63df712ebec8p-3i, 0x1.08c7f3cff0758p+5 + 0x1.ba1b4881bc3ep-3i, -0x1.7f2d389294a33p+4 + -0x1.ad88e833acc04p-3i, 0x1.3bd2267f4c864p+5 + 0x1.a08a0340d310fp-3i, -0x1.c209fd2670b7ap+4 + -0x1.9321e22bcc8ecp-3i, 0x1.8ea5d3aac26bdp+5 + 0x1.8553e80d664aap-3i, -0x1.cc8a7dd1cc378p+3 + -0x1.772391b98c3edp-3i, 0x1.f62bb555f99bep+4 + 0x1.689474ddb8846p-3i, -0x1.1cf4ae1b70219p+5 + -0x1.59aa3f191b896p-3i, 0x1.4eb2c150804bep+5 + 0x1.4a68b50eb76bcp-3i, -0x1.b7ee0b56f6a7fp+5 + -0x1.3ad3b171abc76p-3i, 0x1.4138ea58ae8aep+5 + 0x1.2aef240becbedp-3i, -0x1.7209b9eaeec43p+5 + -0x1.1abf10bfa80b9p-3i, 0x1.755cd9214371fp+5 + 0x1.0a478e8394f0ap-3i, -0x1.6414b0ba2c612p+5 + -0x1.f3198cb4e4d8p-4i, 0x1.95314c7d3e84ep+5 + 0x1.d125e48beed2ep-4i, -0x1.6af3dd07d7142p+5 + -0x1.aebcb86aebc54p-4i, 0x1.e1cbac30b75bp+4 + 0x1.8be6b9e0f24acp-4i, -0x1.652aa2b77e5efp+5 + -0x1.68acb5fb467f6p-4i, 0x1.4824d5f7c0402p+5 + 0x1.4517930c23b2cp-4i, -0x1.f405c9cebdb51p+5 + -0x1.21304e6b23ee8p-4i, 0x1.442d63d64f661p+5 + 0x1.f9fff45fa9f74p-5i, -0x1.dacbb5481a69fp+4 + -0x1.b11f75ce23dcdp-5i, 0x1.06a237e072101p+5 + 0x1.67d18a875f3a4p-5i, -0x1.996ea64579dbp+5 + -0x1.1e28b7962fefcp-5i, 0x1.a14f02f633cc8p+5 + 0x1.a86f31f9962f4p-6i, -0x1.192a3392d1759p+5 + -0x1.1421ba0261548p-6i, 0x1.77c725038532ep+5 + 0x1.fe39fba7d0a4p-8i, -0x1.44afeed378a72p+5 + 0x1.524f60c8b808p-10i, 0x1.c27915b7b67dep+3 + -0x1.53a626f37485p-7i, -0x1.9fff528a03b6cp+4 + 0x1.3e56494faf51p-6i, 0x1.a007844837a8bp+4 + -0x1.d28912576b9d8p-6i, -0x1.0e36d0a2260b7p+6 + 0x1.3322fed5c121ep-5i, 0x1.746258ba6ca0ap+5 + -0x1.7cb3dc16d30ap-5i, -0x1.ede2b21e93712p+4 + 0x1.c5e48afa5687ap-5i, 0x1.1f8d740cc0c66p+5 + -0x1.075146ec2a54cp-4i, -0x1.bbe2dc0a49197p+4 + 0x1.2b6dc200b0794p-4i, 0x1.545a438ed642ap+5 + -0x1.4f3e973197af1p-4i, -0x1.4b8f293549fbcp+5 + 0x1.72baba1259394p-4i, 0x1.3bcb13c78fdep+5 + -0x1.95d9339c46967p-4i, -0x1.e4528e4e43d24p+4 + 0x1.b891247259cdfp-4i, 0x1.63d1be78c0504p+4 + -0x1.dad9c71f0dc24p-4i, -0x1.7a85c679183efp+5 + 0x1.fcaa724ba86p-4i, 0x1.c2a50329e43b4p+4 + -0x1.0efd4d7836562p-3i, -0x1.9f6cdc5d6bd7p+4 + 0x1.1f60eb3e91b62p-3i, 0x1.4042301b8fb1ep+5 + -0x1.2f7bee7cb74d6p-3i, -0x1.1acd9fc75e2ebp+5 + 0x1.3f4a458e3171p-3i, 0x1.61c75a96455cdp+4 + -0x1.4ec7f22d6be4cp-3i, -0x1.e0c53a3b39e61p+4 + 0x1.5df10a75f9c72p-3i, 0x1.356dc8b1ab198p+5 + -0x1.6cc1b9e1b31eep-3i, -0x1.4935cc863670ap+5 + 0x1.7b3642406ddaep-3i, 0x1.2450039c61c1ap+4 + -0x1.894afcaa11a49p-3i, -0x1.5ab851a72c68cp+4 + 0x1.96fc5a6ac96f1p-3i, 0x1.6f287506b8e4bp+5 + -0x1.a446e5e919028p-3i, -0x1.3610f50565c1ep+5 + 0x1.b127438599d79p-3i, 0x1.6913f27c9765dp+5 + -0x1.bd9a327427c1ep-3i, -0x1.1e8c9d9ce3e4ep+5 + 0x1.c99c8d8e47bd2p-3i, 0x1.2f70bfd941b14p+5 + -0x1.d52b4c1e90c62p-3i, -0x1.b1a566a2b62afp+5 + 0x1.e04382a4e7f9cp-3i, 0x1.ca19d783a032bp+5 + -0x1.eae2639358dcap-3i, -0x1.215266e255c2cp+5 + 0x1.f50540035e0f7p-3i, 0x1.21a99f531adcfp+5 + -0x1.fea988636be3cp-3i, -0x1.cdd93b2896d9p+5 + 0x1.03e6668e47a6dp-2i, 0x1.8f0870c0fbea1p+5 + -0x1.08365f97fcfa4p-2i, -0x1.11efde8b53ddcp+5 + 0x1.0c4398662899cp-2i, 0x1.e40290d791da8p+4 + -0x1.100d0aed4daedp-2i, -0x1.3d47465da3ccbp+5 + 0x1.1391c241540bap-2i, 0x1.a01e31ad35e9bp+4 + -0x1.16d0dad368ad3p-2i, -0x1.8652d08928c45p+4 + 0x1.19c982ab7b706p-2i, 0x1.a33a629c57a02p+5 + -0x1.1c7af99d4b0a2p-2i, -0x1.6a1b10656c5a2p+5 + 0x1.1ee49178f1dddp-2i, 0x1.428f24fff2116p+5 + -0x1.2105ae36e7f3ep-2i, -0x1.212f7dd0f0894p+5 + 0x1.22ddc61f6dfb2p-2i, 0x1.9238d2cb14adap+5 + -0x1.246c61ed58d22p-2i, -0x1.efc9e3a179c2dp+5 + 0x1.25b11cec333c7p-2i, 0x1.945de61effe84p+4 + -0x1.26aba511aef5cp-2i, -0x1.ecff360dddfe1p+4 + 0x1.275bbb125ee72p-2i, 0x1.c2dfcaa11ae0cp+4 + -0x1.27c13271b4bdep-2i, -0x1.c7495911a6866p+5 + 0x1.27dbf18d3e27bp-2i, 0x1.04dbb72c2f8d6p+5 + -0x1.27abf1a31ee3bp-2i, -0x1.cf4f8a9303d06p+4 + 0x1.27313ed3c5894p-2i, 0x1.f4f17b5353a4ap+4 + -0x1.266bf81edb72fp-2i, -0x1.3423b759dc0f1p+5 + 0x1.255c4f5b6f856p-2i, 0x1.575960952e6c2p+5 + -0x1.2402892b5f76ep-2i, -0x1.530975024064ap+5 + 0x1.225efcea000b6p-2i, 0x1.ad957191b8968p+5 + -0x1.207214960bc71p-2i, -0x1.0926f3c6c5b19p+5 + 0x1.1e3c4cb6db62cp-2i, 0x1.3ad7fe37c56d1p+4 + -0x1.1bbe343cefb3cp-2i, -0x1.0e0d3849bf2f8p+5 + 0x1.18f86c5dd50fbp-2i, 0x1.6bc5205766c1p+5 + -0x1.15eba86b68e1dp-2i, -0x1.1d615b4644ee6p+5 + 0x1.1298ada68bd16p-2i, 0x1.bd41aa80c6cd6p+4 + -0x1.0f00530d4c454p-2i, -0x1.d319e0de78d58p+4 + 0x1.0b238124956c4p-2i, 0x1.ba9d0ed0c5c09p+5 + -0x1.070331bd7127ep-2i, -0x1.899434ed561e2p+5 + 0x1.02a06fb5ea61ap-2i, 0x1.230b87cd78373p+5 + -0x1.fbf8ad6b42d02p-3i, -0x1.70d1fd249c87ap+5 + 0x1.f23025cc44656p-3i, 0x1.c9d77d8c3f1bp+5 + -0x1.e7e9c14e1db8p-3i, -0x1.536da301e6061p+5 + 0x1.dd28187c643ap-3i, 0x1.a54707eb7925ap+4 + -0x1.d1ede3071a2fap-3i, -0x1.e0b61508aa797p+4 + 0x1.c63df712ebed3p-3i, 0x1.be185ca704f06p+4 + -0x1.ba1b4881bc794p-3i, -0x1.2ddead1a8e4c6p+5 + 0x1.ad88e833ad253p-3i, 0x1.a844aff512914p+5 + -0x1.a08a0340d3196p-3i, -0x1.61a753e55f788p+5 + 0x1.9321e22bcc97p-3i, 0x1.70a9c6fdd50cp+5 + -0x1.8553e80d665acp-3i, -0x1.2080250f0d9dbp+5 + 0x1.772391b98c909p-3i, 0x1.43a4c319b287ep+5 + -0x1.689474ddb8b28p-3i, -0x1.7469f7e3ffbedp+5 + 0x1.59aa3f191b953p-3i, 0x1.99ddbb6ef9b76p+4 + -0x1.4a68b50eb78cp-3i, -0x1.0cb283f26a6b1p+5 + 0x1.3ad3b171abd17p-3i, 0x1.f3232867601c8p+5 + -0x1.2aef240becf0ap-3i, -0x1.d11bb86c031c5p+3 + 0x1.1abf10bfa828ap-3i, 0x1.2ec007ba79a3ep+2 + -0x1.0a478e8394e64p-3i, -0x1.521e074a87d18p+4 + 0x1.f3198cb4e5074p-4i, 0x1.2ed19e606202bp+5 + -0x1.d125e48bef0c2p-4i, -0x1.8c7ba9b4be68p+4 + 0x1.aebcb86aec2c7p-4i, 0x1.e7e3b1188defcp+3 + -0x1.8be6b9e0f264fp-4i, -0x1.980c30e55e4bap+5 + 0x1.68acb5fb46982p-4i, 0x1.5fdbb43dca325p+5 + -0x1.4517930c23d87p-4i, -0x1.374a5890d2db2p+5 + 0x1.21304e6b2428bp-4i, 0x1.1a122791e446p+5 + -0x1.f9fff45fab052p-5i, -0x1.672a8bf2121c8p+5 + 0x1.b11f75ce246cep-5i, 0x1.76f0538651d48p+5 + -0x1.67d18a875f8bcp-5i, -0x1.42a8e165f9f46p+4 + 0x1.1e28b796303b4p-5i, 0x1.589d4a6743295p+5 + -0x1.a86f31f996f34p-6i, -0x1.deba16f3a01e4p+4 + 0x1.1421ba026342p-6i, 0x1.3a73a0e09c0ddp+5 + -0x1.fe39fba7d97p-8i, -0x1.1ac7fd90e4d6bp+5 + -0x1.524f60c8bedcp-10i, 0x1.6cdac3d0b7e01p+4 + 0x1.53a626f374508p-7i, -0x1.6ffe3fefa9bf6p+4 + -0x1.3e56494faeb7cp-6i, 0x1.35cbda1474122p+5 + 0x1.d289125768d82p-6i, -0x1.61aad79622fbep+4 + -0x1.3322fed5c00e5p-5i, 0x1.23146d411eecfp+5 + 0x1.7cb3dc16d2e1cp-5i, -0x1.9f9f722c6e87ap+5 + -0x1.c5e48afa56845p-5i, 0x1.d09ae32e6d36fp+4 + 0x1.075146ec2a674p-4i, -0x1.d6cf6ef5f3268p+4 + -0x1.2b6dc200afdcp-4i, 0x1.05b77ea8e1dap+5 + 0x1.4f3e97319762ep-4i, -0x1.dd73f4d17379ep+4 + -0x1.72baba1259314p-4i, 0x1.72d6021dc8e1ap+5 + 0x1.95d9339c4675cp-4i, -0x1.0a0e90ebc8e23p+5 + -0x1.b891247259d5p-4i, 0x1.58bbf0514c9d5p+5 + 0x1.dad9c71f0d36p-4i, -0x1.67572c4bcb041p+4 + -0x1.fcaa724ba8184p-4i ) assertThat(stats:::fft(inverse=TRUE,z=c(0+0i, 0.387467656494932+0.087887055302609i, -0.272873251193193+0.348592754161238i, 0.004458949776547+0.629650782467665i, 0.341584576251984-0.324095747592006i, -0.168430070639157+0.370058402820591i, -0.170428057808592+0.355656926196737i, 0.189403333913117-0.268102153555681i, -0.422393428437039+0.390356155279087i, -0.087640681591324+0.550557720201075i, 0.658588238094553-0.373223641927201i, 0.496874726588664-0.484876739592876i, -0.31731700831643+0.608664501667523i, 0.394341624780511+0.254548322791397i, 0.41572635983388+1.24202430087578i, 0.154628074397381+0.314566308335485i, -0.0346516632643838+0.0028512332394526i, 0.21124567010677+0.259642705863708i, -0.752934806590152-0.299829330401428i, 0.801459675117551+0.398101492628935i, 0.687689177637489-0.370430914656473i, -0.16579837040666+0.931976287573366i, 0.4349783189495+0.095497912734406i, -0.498467368867177+0.147981243599366i, -0.545289926208066-0.082722529650794i, 0.074896052891279+0.828318552752319i, 0.373794651598343-0.347565624414014i, -0.315250819254099-0.002607973396642i, -0.387194782168348+0.382417178295367i, 0.297245727562182-0.47985315800206i, 0.18661904602752-1.09565329821592i, 0.309489896357372-0.564353693815631i, -0.123480299994003+0.286414030578086i, 0.611672005716161+0.172522395665558i, 0.115882106548999-0.709349175206409i, -0.273698566243724-0.242496361362738i, 0.195101021176864+0.689026217108972i, 0.548472086565796+0.550388738353233i, 0.847502438074939-0.201830644093705i, -0.379464166532177+0.177328031483713i, -0.391275629246155-0.445767240777387i, -0.302106709204265-0.026685237267354i, -0.79833731892196-1.35064045553977i, -0.006270875287866+0.406619621766477i, 0.203178986634338+0.138669231219335i, 0.28577151725736+1.04048462196259i, -0.951091951990917+0.263125400955221i, -1.55273704456497-0.4884052830452i, 1.03655094548686-0.82026863162249i, -0.544479807501977-0.089937124268889i, -0.318237293080151-0.604638992947871i, 1.53081943790421+0.41508607639562i, -0.428407442656421+0.591155496756211i, 0.250536419409091+0.48974897289035i, -1.06495103443053-0.15231137996281i, 0.528470245209354-0.369094879343149i, -0.143586055741212-0.776165408742494i, -0.142163961786417+0.811527486156436i, -0.242673181991965+0.462931841911418i, -0.227060138460294-0.8996455386592i, 0.140618002041668+0.669357636192236i, -1.15075510955329+0.60727129746021i, 0.210495011044416-0.076051105432621i, 0.025462294286431+0.939338286240659i, 0.678321489541989+0.216560603562504i, -0.72301809819317-0.151884043937172i, 0.309750749369855+0.916000993505714i, -0.869358145138734-0.387714269931044i, -0.923902644829032+0.310364265964412i, 0.137075984674729-0.537408545089108i, -0.247211147291535+0.491285965055452i, -0.538436918775419+0.313993798842096i, -1.4240627600889+0.28536430467877i, 0.33518415776981+0.968809509539808i, 0.417064770976696-0.489011267648477i, 0.706824854495443+0.495913096111714i, 0.852058997401168+0.707333688273278i, 0.803715235744214+0.027629717482164i, 0.593150061762205-0.700205546303819i, -0.20778265900559-0.700544411609522i, 0.27408688214629-0.00552167031428i, -0.320552702241218-0.018874842257346i, -0.082433228830737-0.722239479989061i, 0.695578381955947-0.927220365278698i, -0.67171193555105+1.41693472431622i, -0.348626905572753+0.944332406693984i, 0.396744586483308+0.284540666501424i, -0.047212876898303-0.882681522880203i, 0.34969735463211-1.62058439231521i, -0.20159867103638-0.4774838031943i, -0.128283457812938-0.547829299293464i, 0.783387993225221+0.679494259559114i, -0.080477953289285-0.67183603482321i, -1.10277855376794+0.00821053408902i, -0.930405516723233+0.280853848995036i, 1.01744543253628-0.37551671023178i, -0.820595854020355+0.099654497324053i, 0.418907739583679+0.662854525394047i, -0.615106309065234+0.246834962926732i, -1.13019829311483+0i, 36.95629+0i, -0.873350170339161+0.132319073897442i, -0.615106309065235-0.246834962926732i, 0.418907739583679-0.662854525394047i, -0.820595854020355-0.099654497324053i, 1.01744543253628+0.37551671023178i, -0.930405516723233-0.280853848995036i, -1.10277855376794-0.00821053408902i, -0.080477953289285+0.671836034823211i, 0.783387993225221-0.679494259559114i, -0.128283457812938+0.547829299293463i, -0.20159867103638+0.4774838031943i, 0.34969735463211+1.62058439231521i, -0.047212876898303+0.882681522880203i, 0.396744586483308-0.284540666501424i, -0.348626905572753-0.944332406693984i, -0.67171193555105-1.41693472431622i, 0.695578381955947+0.927220365278698i, -0.082433228830737+0.722239479989061i, -0.320552702241218+0.018874842257346i, 0.27408688214629+0.00552167031428i, -0.20778265900559+0.700544411609522i, 0.593150061762205+0.700205546303819i, 0.803715235744214-0.027629717482164i, 0.852058997401169-0.707333688273278i, 0.706824854495443-0.495913096111714i, 0.417064770976696+0.489011267648477i, 0.33518415776981-0.968809509539809i, -1.4240627600889-0.28536430467877i, -0.538436918775419-0.313993798842096i, -0.247211147291535-0.491285965055452i, 0.137075984674729+0.537408545089108i, -0.923902644829032-0.310364265964412i, -0.869358145138734+0.387714269931044i, 0.309750749369855-0.916000993505715i, -0.72301809819317+0.151884043937172i, 0.67832148954199-0.216560603562504i, 0.025462294286431-0.939338286240659i, 0.210495011044416+0.076051105432621i, -1.15075510955329-0.60727129746021i, 0.140618002041669-0.669357636192237i, -0.227060138460294+0.8996455386592i, -0.242673181991965-0.462931841911418i, -0.142163961786417-0.811527486156435i, -0.143586055741212+0.776165408742494i, 0.528470245209354+0.369094879343149i, -1.06495103443053+0.15231137996281i, 0.250536419409091-0.48974897289035i, -0.428407442656422-0.591155496756212i, 1.53081943790421-0.41508607639562i, -0.318237293080151+0.604638992947871i, -0.544479807501976+0.089937124268889i, 1.03655094548686+0.82026863162249i, -1.55273704456497+0.4884052830452i, -0.951091951990917-0.263125400955221i, 0.28577151725736-1.04048462196259i, 0.203178986634338-0.138669231219335i, -0.006270875287866-0.406619621766477i, -0.79833731892196+1.35064045553977i, -0.302106709204265+0.026685237267354i, -0.391275629246155+0.445767240777387i, -0.379464166532177-0.177328031483713i, 0.847502438074939+0.201830644093705i, 0.548472086565796-0.550388738353233i, 0.195101021176864-0.689026217108973i, -0.273698566243724+0.242496361362738i, 0.115882106548999+0.70934917520641i, 0.611672005716161-0.172522395665558i, -0.123480299994003-0.286414030578086i, 0.309489896357372+0.564353693815631i, 0.18661904602752+1.09565329821592i, 0.297245727562182+0.47985315800206i, -0.387194782168348-0.382417178295367i, -0.315250819254099+0.002607973396642i, 0.373794651598343+0.347565624414014i, 0.074896052891279-0.828318552752319i, -0.545289926208067+0.082722529650794i, -0.498467368867177-0.147981243599366i, 0.4349783189495-0.095497912734406i, -0.16579837040666-0.931976287573366i, 0.687689177637486+0.370430914656471i, 0.801459675117551-0.398101492628935i, -0.752934806590153+0.299829330401428i, 0.21124567010677-0.259642705863708i, -0.0346516632643838-0.0028512332394526i, 0.154628074397381-0.314566308335485i, 0.41572635983388-1.24202430087578i, 0.394341624780511-0.254548322791398i, -0.31731700831643-0.608664501667524i, 0.496874726588664+0.484876739592876i, 0.658588238094553+0.373223641927201i, -0.087640681591324-0.550557720201075i, -0.422393428437039-0.390356155279087i, 0.189403333913117+0.268102153555681i, -0.170428057808592-0.355656926196737i, -0.168430070639157-0.370058402820591i, 0.341584576251983+0.324095747592006i, 0.004458949776547-0.629650782467666i, -0.272873251193193-0.348592754161238i, 0.387467656494932-0.087887055302609i )) , identicalTo( expected, tol = 1e-6 ) )
operador_binario <- function(fun, a, b){ }
library(compareGroups) library(htmlwidgets) library(webshot) library(readr) data(predimed) tab <- descrTable(predimed, method = c(p14=2, wht=2, toevent=2), hide.no = 'no', hide = c(sex="Male")) out <- export2md(tab, header.label=c("all"="All","N"="available"), strip = TRUE, first = TRUE, background = grey(0.95), size = 14, position = "left") webshot::webshot("./www/examples/example1.html", "./www/examples/example1.png") file.remove("./www/examples/example1.html") tab <- descrTable(group ~ ., predimed, method = c(p14=2, wht=2, toevent=2), hide.no = 'no', hide = c(sex="Male")) out <- export2md(tab, header.label=c("p.overall"="p-value","N"="available"), strip = TRUE, first = TRUE, background = grey(0.95), size=14, position = "left") webshot::webshot("./www/examples/example2.html", "./www/examples/example2.png") file.remove("./www/examples/example2.html") tab <- descrTable(group ~ ., predimed, method = c(p14=2, wht=2, toevent=2), type = 1, sd.type=2, hide.no = 'no', hide = c(sex="Male")) out <- export2md(tab, header.label=c("p.overall"="p-value","N"="available"), strip = TRUE, first = TRUE, background = grey(0.95), size=14, position = "left") webshot::webshot("./www/examples/example3.html", "./www/examples/example3.png") file.remove("./www/examples/example3.html") predimed$tevent <- with(predimed, Surv(toevent, event=='Yes')) tab <- descrTable(tevent ~ . - toevent - event, predimed, method = c(p14=2, wht=2), show.ratio=TRUE, show.p.overall=FALSE, hide.no = 'no', hide = c(sex="Male")) out <- export2md(tab, header.label=c("p.ratio"="p-value"), strip = TRUE, first = TRUE, background = grey(0.95), size = 14, position = "left") webshot::webshot("./www/examples/example4.html", "./www/examples/example4.png") file.remove("./www/examples/example4.html") tab <- strataTable(tab, "group")[-1] out <- export2md(tab, header.label=c("p.ratio"="p-value"), strip = TRUE, first = TRUE, background = grey(0.95), header.color = "white",header.background = "blue", size=10, position = "left") webshot::webshot("./www/examples/example5.html", "./www/examples/example5.png") file.remove("./www/examples/example5.html") tab <- descrTable(predimed) plot(tab['age'], file="./www/examples/var", type="png") file.rename("./www/examples/varage.png","./www/examples/example6.png") tab <- descrTable(group ~ ., predimed) plot(tab['smoke'], bivar=TRUE, file="./www/examples/var", type="png") file.rename("./www/examples/varsmoke.png","./www/examples/example7.png") data(SNPs) tab <- compareSNPs(~ . , SNPs[,6:20]) sink("./www/examples/example8.txt") tab sink()
km = function(data, w=1) { x = icendata(data, w) if(any(x$o[,2] != Inf)) stop("Not all observations are exact or right-censored") if(nrow(x$o) == 0) { f = idf(x$t, x$t, x$wt) ll = sum(x$wt * log(f$p)) return(list(f=f, ll=ll)) } c = colSums(x$wo * outer(x$o[,1], x$t, "<")) n = sum(x$wt, x$wo) r = n - c - c(0,cumsum(x$wt))[1:length(x$t)] S = cumprod(1 - x$wt/r) p = rev(diff(rev(c(1,S,0)))) dc = x$wt + c if(max(x$t) > max(x$o[,1])) { f = idf(x$t, x$t, p[-length(p)]) ll = sum( x$wt * log(f$p) ) } else { f = idf(c(x$t,max(x$o[,1])), c(x$t,Inf), p) ll = sum(c(x$wt, n - sum(x$wt)) * log(f$p)) } list(f=f, ll=ll) }
mean2.1996BS <- function(X, Y){ check_nd(X) check_nd(Y) if (ncol(X)!=ncol(Y)){ stop("* mean2.1996BS : two samples X and Y should be of same dimension.") } n1 = nrow(X) n2 = nrow(Y) n = (n1+n2-2) x1 = colMeans(X) x2 = colMeans(Y) S = (((n1-1)*cov(X) + (n2-1)*cov(Y))/n) trS = aux_trace(S) xdiff = as.vector(x1-x2) term1 = ((n1*n2)/(n1+n2))*sum(xdiff*xdiff) - trS term2 = sqrt((2*n*(n+1)/((n-1)*(n+2)))*(aux_trace(S%*%S) - (trS^2)/n)) thestat = (term1/term2) pvalue = pnorm(thestat,lower.tail=FALSE) hname = "Two-sample Test for High-Dimensional Means by Bai and Saranadasa (1996)." Ha = "true means are different." DNAME = paste(deparse(substitute(X))," and ",deparse(substitute(Y)),sep="") names(thestat) = "statistic" res = list(statistic=thestat, p.value=pvalue, alternative = Ha, method=hname, data.name = DNAME) class(res) = "htest" return(res) }
hyper.like=function(parm,X,covarray,weights=1,errorscale=1,k.vec=FALSE,output='sum'){ N=dim(X)[1] dims=dim(X)[2] coord.orth=parm[1:dims] scat.orth=parm[dims+1] eTce=projcovarray(covarray,coord.orth) eTe=sum(coord.orth^2) orthvariance=scat.orth^2+(eTce/eTe)*(errorscale^2) if(length(k.vec)> 1){ scat.vec=scat.orth/(coord.orth/sqrt(eTe)) X=t(t(X)-k.vec*scat.vec^2) } originoffset=(X %*% coord.orth)/sqrt(eTe)-sqrt(eTe) if(output=='sum' | output=='val'){ loglike= -0.5*( log(orthvariance)+ (originoffset^2)/orthvariance ) } if(output=='sig'){ sigma=sqrt((originoffset^2)/orthvariance) } if(output=='sum'){out=sum(weights*loglike)} if(output=='val'){out=as.numeric(loglike)} if(output=='sig'){out=as.numeric(sigma)} return=out }
`summary.elrm` <- function(object,...) { inferences = as.data.frame(cbind(round(as.numeric(object$coeffs),5),round(as.numeric(object$p.values),5),round(as.numeric(object$p.values.se),5),object$mc.size)); results = data.frame(row.names=names(object$coeffs), inferences); names(results) = c("estimate","p-value","p-value_se","mc_size"); message("\nCall:\n"); message(object$call.history); message('\n'); message("Results:\n"); message(paste0(capture.output(results), collapse = "\n")); message('\n'); message(object$ci.level,"% Confidence Intervals for Parameters\n",sep=""); message(paste0(capture.output(object$coeffs.ci), collapse = "\n")); }
test_that("rstar returns reasonable values", { skip_if_not_installed("caret") x <- example_draws() val <- rstar(x) expect_true(val > 0.8 & val < 10) }) test_that("rstar works with 1d example", { skip_if_not_installed("caret") x <- example_draws() x <- as_draws_df(x) x <- x[, c(variables(x)[1], ".chain", ".iteration", ".draw")] val <- rstar(x) expect_true(val > 0.5 & val < 10) }) test_that("rstar works with draws_df example", { skip_if_not_installed("caret") x <- example_draws() x <- as_draws_df(x) val <- rstar(x) expect_true(val > 0.5 & val < 10) }) test_that("rstar with uncertainty returns vectors of correct length", { skip_if_not_installed("caret") x <- example_draws() val <- rstar(x, method = "gbm", uncertainty = T, verbose = F) expect_equal(length(val), 1000) val <- rstar(x, method = "knn", uncertainty = T, nsimulations = 10) expect_equal(length(val), 10) }) test_that("incorrect nsimulations values throws error", { skip_if_not_installed("caret") x <- example_draws() expect_error(rstar(x, method = "knn", nsimulations = 0), "'nsimulations' must be greater than or equal to 1.") }) test_that("rstar with uncertainty returns reasonable values", { skip_if_not_installed("caret") x <- example_draws() val <- rstar(x, method = "gbm", uncertainty = T, verbose = F) expect_true(max(val) > 0.3 & min(val) < 10) }) test_that("rstar accepts different classifiers", { skip_if_not_installed("caret") x <- example_draws() val <- rstar(x, method = "gbm", verbose=F) expect_true(is.numeric(val)) val <- rstar(x, method = "knn") expect_true(is.numeric(val)) }) test_that("rstar accepts different hyperparameters", { skip_if_not_installed("caret") x <- example_draws() caret_grid <- data.frame(interaction.depth=c(3), n.trees = 1, shrinkage=c(0.1), n.minobsinnode=10) start <- Sys.time() val <- rstar(x, method = "gbm", verbose=F, hyperparameters = caret_grid) end <- Sys.time() dif1 <- end - start caret_grid <- data.frame(interaction.depth=c(3), n.trees = 1000, shrinkage=c(0.1), n.minobsinnode=10) start <- Sys.time() val <- rstar(x, method = "gbm", verbose=F, hyperparameters = caret_grid) end <- Sys.time() dif2 <- end - start expect_true(dif1 < dif2) }) test_that("rstar accepts different training proportion", { skip_if_not_installed("caret") x <- example_draws() val1 <- rstar(x, method = "knn") val2 <- rstar(x, method = "knn", training_proportion = 0.1) expect_true(val1 > val2) }) test_that("rstar throws error when passed invalid training_proportion", { skip_if_not_installed("caret") x <- example_draws() expect_error(rstar(x, method = "knn", training_proportion = 0), "'training_proportion' must be greater than 0 and less than 1") expect_error(rstar(x, method = "knn", training_proportion = 1), "'training_proportion' must be greater than 0 and less than 1") }) test_that("split-chain R* returns generally higher values", { skip_if_not_installed("caret") skip_on_cran() x <- example_draws() n <- 10 vals_split <- vector(length = n) vals_unsplit <- vector(length = n) for(i in 1:n) { vals_split[i] <- rstar(x, method = "knn") vals_unsplit[i] <- rstar(x, method = "knn", split = FALSE) } expect_true(median(vals_split) > median(vals_unsplit)) })
context("errcheck_times") test_that("",{ expect_error(errcheck_times("nonnumeric","notrealfunc"), "Error in errcheck_times called by notrealfunc: times must be numeric") expect_error(errcheck_times(1,"notrealfunc"), "Error in errcheck_times called by notrealfunc: times must be a vector") expect_error(errcheck_times(c(1,2,3,NA),"notrealfunc"), "Error in errcheck_times called by notrealfunc: times must not contain NAs, NaNs, Infs") expect_error(errcheck_times(c(1,3,4,5),"notrealfunc"), "Error in errcheck_times called by notrealfunc: times must be unit spaced; output timescales in units of cycles per sampling interval") })
stdzDose <- function(x) { cdose <- tolower(x) udose <- unique(cdose) useUnq <- length(udose) != length(cdose) if(useUnq) { mix <- match(cdose, udose) cdose <- udose } cdose <- sub('[ ]*(cap|capsule|tablet|tab|pill)[s]?', '', cdose) cdose <- sub('(and )?one half', 0.5, cdose) cdose <- sub('one', 1, cdose) cdose <- sub('two', 2, cdose) cdose <- sub('three', 3, cdose) cdose <- sub('four', 4, cdose) cdose <- sub('five', 5, cdose) cdose <- sub('six', '6', cdose) cdose <- sub('seven', '7', cdose) cdose <- sub('eight', '8', cdose) cdose <- sub('nine', '9', cdose) cdose <- sub('ten', '10', cdose) cdose <- sub('half', 0.5, cdose, fixed = TRUE) cdose <- sub('1-2', 1.5, cdose, fixed = TRUE) cdose <- sub('1-1/2', 1.5, cdose, fixed = TRUE) cdose <- sub('1/2', 0.5, cdose, fixed = TRUE) ix <- grep("[0-9]+[ ]0.5", cdose) if(length(ix)) { cdose[ix] <- as.numeric(sub("([0-9]+)[ ]0.5", "\\1", cdose[ix])) + 0.5 } ix <- grep("[0-9][ ]?(to|-)[ ]?[0-9]", cdose) if(length(ix)) { cda <- sub("([0-9.]+)[ ]?(to|-)[ ]?([0-9.]+)", "\\1", cdose[ix]) cdb <- sub("([0-9.]+)[ ]?(to|-)[ ]?([0-9.]+)", "\\3", cdose[ix]) cdose[ix] <- sprintf("%.2f", (as.numeric(cda) + as.numeric(cdb)) / 2) } cdose <- nowarnnum(cdose) if(useUnq) { cdose <- cdose[mix] } cdose }
distances <- function (X, Y) { onerow <- function (xy) { d <- function(xy2) { sqrt(sum((xy2 - xy)^2)) } apply(Y, 1, d) } t(apply(X, 1, onerow)) } telemetry.LT <- function(CH, detectfn, realparval, PIA, nmix = 1, knownclass = 1, uppersigma = 20) { normalize <- function (parm) { par3 <- ndetectpar(detectfn) == 3 sigma <- parm['sigma'] z <- if (par3) parm[parnames(detectfn)[3]] else 1 if (detectfn %in% c(14,16)) lambda0 <- 10000 / (sigma^2 * 2 * pi) else { rdfn <- function (r, pars) r * dfn(r, pars, 0) lambda0 <- 10000/integrate (rdfn, 0, sigma * uppersigma, pars=c(1, sigma, z))$value } out <- c(lambda0=lambda0, sigma=sigma) if (par3) out <- c(out,z=z) out } Lx <- function(x) { pind <- as.numeric(PIA[cbind(df$i, df$s, df$k, rep(x,n))]) param <- Nrealparval[pind,, drop = FALSE] sapply(1:n, function(i) dfn(df$d[i], param[i,], 0)) } px <- function(x) { indexmatrix <- cbind(df$i, df$s, df$k, rep(x,n)) pind <- as.numeric(PIA[indexmatrix]) realparval[pind,'pmix', drop = FALSE] } detectfn <- valid.detectfn(detectfn, 14:19) dfn <- getdfn (detectfn) Nrealparval <- t(apply(realparval, 1, normalize)) df <- data.frame(xy(CH), i = animalID(CH, names = FALSE, sortorder = 'snk'), s = occasion(CH, sortorder = 'snk'), k = trap(CH, names = FALSE, sortorder = 'snk') ) df <- df[order(df$i, df$s, df$k),] ni <- table(df$i) df$cx <- rep(tapply(df$x, df$i, mean),ni) df$cy <- rep(tapply(df$y, df$i, mean),ni) df$d <- sqrt((df$x-df$cx)^2 + (df$y-df$cy)^2) n <- nrow(df) df$knownclass <- if (length(knownclass) == 1) rep(knownclass, n) else rep(knownclass, ni) L <- sapply(1:nmix, Lx) if (nmix>1) { pmix <- sapply(1:nmix, px) pmix[df$knownclass > 1,] <- 0 pmix[cbind(1:n,df$knownclass-1)] <- 1 L <- apply(L * pmix, 1, sum) } if (any (knownclass != 1)) { pmix <- realparval[,'pmix'] obsmix <- tabulate(knownclass)[2:(length(pmix)+1)] Lknown <- sum(obsmix * log(pmix)) } else Lknown <- 0 if (any(L<=0)) list(value = -1e10, resultcode = 9) else list(value = sum(log(L)) + Lknown, resultcode = 0) } telemetry.LC <- function(CH, detectfn, detectpar, mask, bvn = TRUE) { if (! all(detector(traps(CH)) %in% c('proximity'))) stop ("requires proximity CH") n <- dim(CH)[1] J <- dim(CH)[2] traps <- traps(CH) K <- ndetector(traps) detectfn <- valid.detectfn(detectfn, 14:19) detectpar <- detectpar[c('lambda0','sigma','z')] g <- getdfn (detectfn) xylist <- telemetryxy(CH) centrexy <- t(sapply(xylist, apply, 2, mean)) dfn <- function (xy) { centres <- matrix(apply(xy, 2, mean), ncol = 2) if (bvn) { vcv <- var(xy)/nrow(xy) detS <- det(vcv)^0.5 tempmask <- sweep (mask, MARGIN = 2, STATS = centres, FUN = '-') close <- apply(tempmask,1, function(x) sum(x^2)) < (detS*30) if (sum(close)<1) { close <- nearesttrap(matrix(0, ncol = 2, nrow = 1), tempmask) } tempmask <- tempmask[close,, drop = FALSE] invS <- solve(vcv) mymvn <- function(XY) exp(-(XY %*% invS %*% XY)/2) / 2/pi/det(vcv) dbvn <- apply(tempmask,1,mymvn) dbvn <- dbvn / sum(dbvn) list(dbvn=dbvn, mask = mask[close,, drop=FALSE]) } else { list(dbvn = 1.0, mask = centres) } } pmask <- lapply(xylist, dfn) loglik <- 0 for (id in names(xylist)) { m <- nrow(pmask[[id]]$mask) dtrap <- edist (traps, pmask[[id]]$mask) if (m==1) dtrap <- t(dtrap) gkm <- g(dtrap, unlist(detectpar), 0) prw <- matrix(1, nrow = K, ncol = m) for (j in 1:J) { wij <- CH[id,j,] prw <- prw * (sweep(gkm, STATS=wij, MARGIN=1, FUN = '*') + sweep(1-gkm, STATS=1-wij, MARGIN=1, FUN = '*')) } prwm <- apply(prw,2,prod) prwm <- prwm * pmask[[id]]$dbvn loglik <- loglik + log(sum(prwm)) } loglik } telemetry.LCmask <- function(CH, mask, bvn = TRUE) { dfn <- function (xy) { f <- numeric(mm) if (nrow(xy) == 0) f[] <- 1/mm else { centres <- matrix(apply(xy, 2, mean), ncol = 2) if (bvn) { vcv <- var(xy)/nrow(xy) detS <- det(vcv)^0.5 tempmask <- sweep (mask, MARGIN = 2, STATS = centres, FUN = '-') close <- apply(tempmask,1, function(x) sum(x^2)) < (detS*30) if (sum(close)<1) { close <- nearesttrap(matrix(0, ncol = 2, nrow = 1), tempmask) } tempmask <- tempmask[close,, drop = FALSE] invS <- solve(vcv) mymvn <- function(XY) exp(-(XY %*% invS %*% XY)/2) / 2/pi/det(vcv) dbvn <- apply(tempmask,1,mymvn) dbvn <- dbvn / sum(dbvn) f[close] <- dbvn } else { cell <- nearesttrap(centres, mask) f[cell] <- 1 } } f } mm <- nrow(mask) xylist <- telemetryxy(CH) nullxy <- rep(list(matrix(nrow=0, ncol=2)), nrow(CH)) names(nullxy) <- rownames(CH) xylist <- c(xylist, nullxy[!(rownames(CH) %in% names(xylist))]) sapply(xylist, dfn)[,rownames(CH)] }
Pfr_P_ratio <- function(w.length, s.irrad=rep(1.0,length(w.length)), unit.in="energy", check.spectrum=TRUE, use.cached.mult=FALSE){ if (check.spectrum && !check_spectrum(w.length, s.irrad)) { return(NA) } if (unit.in == "energy") { s.q.irrad <- as_quantum_mol(w.length,s.irrad) } else if (unit.in == "photon" || unit.in == "quantum") { s.q.irrad <- s.irrad } else { warning("'unit.in' value not supported.") return(NA) } Pr.wave.raw <- s.q.irrad * Phy_Sigma_R(w.length, use.cached.mult) Pfr.wave.raw <- s.q.irrad * Phy_Sigma_FR(w.length, use.cached.mult) if (length(w.length) == 1){ return(Pr.wave.raw / (Pr.wave.raw + Pfr.wave.raw)) } Pr.selector <- !is.na(Pr.wave.raw) Pfr.selector <- !is.na(Pfr.wave.raw) selector <- Pr.selector & Pfr.selector if (any(!selector)) { warning("NAs removed. Possibly spectral data extends beyond 300...770 nm.") } Pr.wave <- Pr.wave.raw[selector] Pfr.wave <- Pfr.wave.raw[selector] w.length <- w.length[selector] Pr.int <- integrate_xy(w.length, Pr.wave) Pfr.int <- integrate_xy(w.length, Pfr.wave) return(Pr.int / (Pr.int + Pfr.int)) }
cor.prob <- function(df) { dfr <- nrow(df) - 2 R <- cor(df, use = "pairwise.complete.obs") above <- row(R) < col(R) r2 <- R[above]^2 Fstat <- r2 * dfr / (1 - r2) R[above] <- 1 - pf(Fstat, 1, dfr) cor.mat <- t(R) cor.mat[upper.tri(cor.mat)] <- NA diag(cor.mat) <- NA cor.mat %>% as.data.frame() %>% tibble::rownames_to_column(var = "h_var") %>% gather(key = "v_var", value = "p.value", -.data$h_var) } pwcorr <- function(df, vars = NULL, method = "pearson", var_label_df = NULL) { if (!method %in% c("pearson", "kendall", "spearman")) stop("Invalid correlation method specified") if (is.null(vars)) vars <- names(df) if (!is.null(var_label_df)) { if (!names(var_label_df) %in% c("variable", "label")) stop("var_label_df must contains columns `variable` and `label`") labels <- var_label_df$label[var_label_df$variable %in% vars] } else { labels <- vars } df <- select(df, one_of(vars)) cor.matrix <- cor(df, method = method, use = "pairwise.complete.obs") cor.matrix[upper.tri(cor.matrix)] <- NA display <- cor.matrix %>% as.data.frame() %>% tibble::rownames_to_column(var = "h_var") %>% mutate_if(is.numeric, round, 3) if(method == "pearson") { display <- display %>% gather(key = "v_var", value = "corr", -.data$h_var) %>% left_join(cor.prob(df), by = c("h_var", "v_var")) %>% mutate(p.disp = case_when(.data$p.value < 0.01 ~ "<0.01", is.na(.data$p.value) ~ NA_character_, TRUE ~ paste(round(.data$p.value, 2))), display = case_when(!is.na(.data$corr) & !is.na(.data$p.disp) ~ paste0(round(.data$corr, 2), "\n(", .data$p.disp, ")"), .data$corr == 1 & is.na(.data$p.disp) ~ "1", is.na(.data$corr) & is.na(.data$p.disp) ~ " ", TRUE ~ NA_character_)) %>% select(.data$h_var, .data$v_var, .data$display) %>% mutate(h_var = factor(.data$h_var, levels = vars, labels = labels), v_var = factor(.data$v_var, levels = vars, labels = labels)) %>% arrange(.data$h_var, .data$v_var) %>% spread(key = "v_var", value = "display") %>% rename(" " = .data$h_var) } return(display) }
findBlockAndFilter <- function (x, base.position = 1:length(x), size = sum(blocks[, "size"], na.rm = TRUE)/100, num = sum(blocks[, "num"], na.rm = TRUE)/100, extendNA = TRUE, fillSmallNA = FALSE) { x <- as.numeric(x) t <- length(x) block.num <- 1 block_start <- base.position[1] block_end <- base.position[t] blockNumItem <- t blockType <- x[1] x.val <- x x.val[is.na(x)] <- max(x, na.rm = TRUE) + 1 x.diff <- sort(unique(c(1, which(x.val[-1] != x.val[-t]) + 1))) x.diff <- x.diff[x.diff <= t] block.num <- length(x.diff) if (block.num <= 1) return(blocks <- cbind(start = block_start, end = block_end, size = block_end - block_start + 1, num = blockNumItem, type = blockType)) block_start <- base.position[x.diff] block_end <- base.position[c(x.diff[-1] - 1, t)] blockNumItem <- c(diff(x.diff), t - x.diff[block.num] + 1) blockType <- x[x.diff] blocks <- cbind(start = block_start, end = block_end, size = block_end - block_start + 1, num = blockNumItem, type = blockType) if (extendNA) { block.ids <- which(is.na(blocks[, "type"]) & blocks[, "size"] > -1) block.ids.next <- block.ids[block.ids < nrow(blocks)] block.ids.pre <- block.ids[block.ids > 1] if (length(block.ids.next) > 0) blocks[block.ids.next, "end"] <- blocks[block.ids.next + 1, "start"] - 1 if (length(block.ids.pre) > 0) blocks[block.ids.pre, "start"] <- blocks[block.ids.pre - 1, "end"] + 1 blocks[, "size"] <- blocks[, "end"] - blocks[, "start"] + 1 } blocks.margin <- block_start[-1] - block_end[-length(block_end)] - 1 blocks.extentSize <- as.numeric(blocks[, "size"]) + c(blocks.margin, 0) + c(0, blocks.margin) filter.block <- (blocks.extentSize < size & as.numeric(blocks[, "num"]) < num) if (sum(filter.block, na.rm = T) > 0) { blocks[filter.block, "type"] <- NA } blocks <- mergeBlocks(blocks) if (nrow(blocks) == 1) return(blocks) if (fillSmallNA) { blocks.margin <- blocks[-1, "start"] - blocks[-nrow(blocks), "end"] - 1 blocks.extentSize <- as.numeric(blocks[, "size"]) + c(blocks.margin, 0) + c(0, blocks.margin) filter.block <- blocks.extentSize < size block.na.ids <- which(is.na(blocks[, "type"]) & filter.block) block.na.num <- length(block.na.ids) if (block.na.num > 0) { blocks[block.na.ids, "type"] <- sapply(block.na.ids, function(i) { if (i == 1) return(blocks[2, "type"]) if (i == nrow(blocks)) return(blocks[nrow(blocks) - 1, "type"]) if (blocks[i - 1, "type"] == blocks[i + 1, "type"]) return(blocks[i - 1, "type"]) blocks[i, "type"] }) } } blocks <- mergeBlocks(blocks) if (nrow(blocks) == 1) return(blocks) block.ids <- which(is.na(blocks[, "type"])) block.ids.next <- block.ids[block.ids < nrow(blocks)] block.ids.pre <- block.ids[block.ids > 1] if (length(block.ids.next) > 0) blocks[block.ids.next, "end"] <- blocks[block.ids.next + 1, "start"] - 1 if (length(block.ids.pre) > 0) blocks[block.ids.pre, "start"] <- blocks[block.ids.pre - 1, "end"] + 1 tmp.blocks <- blocks for (i in 2:nrow(blocks)) if (blocks[i, 1] - blocks[i - 1, 2] > 1) tmp.blocks <- rbind(tmp.blocks, c(blocks[i - 1, "end"] + 1, blocks[i, "start"] - 1, blocks[i, "start"] - blocks[i - 1, "end"] - 1, 0, NA)) blocks <- tmp.blocks[order(tmp.blocks[, "end"]), ] mergeBlocks(blocks) }
panel.compareZcases <- function (x=x, y=y, z=NULL, ..., loa.settings = FALSE) { if (loa.settings) return(list(group.args = c("pch"), zcase.args = c(""), ignore=c("col"), default.settings = list(key = FALSE, grid = TRUE, reset.xylims = c("refit.xylims", "zlim.in.ylim")))) extra.args <- list(...) if ("groups" %in% names(extra.args)) { if ("group.args" %in% names(extra.args) && length(extra.args$group.args) > 0) { temp <- as.numeric(factor(extra.args$groups, levels = extra.args$group.ids)) for (i in extra.args$group.args) { extra.args[[i]] <- extra.args[[i]][temp] } } extra.args$groups <- NULL } if ("zcases" %in% names(extra.args)) { if ("zcase.args" %in% names(extra.args) && length(extra.args$zcase.args) > 0) { temp <- as.numeric(factor(extra.args$zcases, levels = extra.args$zcase.ids)) for (i in extra.args$zcase.args) { extra.args[[i]] <- extra.args[[i]][temp] } } } if (isGood4LOA(extra.args$grid)) panel.loaGrid(panel.scales = extra.args$panel.scales, grid = extra.args$grid) extra.args$grid <- NULL if(!is.null(z)){ if(!"zcases" %in% names(extra.args)) extra.args$zcases <- rep("default", length(z)) if(!"zcase.ids" %in% names(extra.args)) extra.args$zcase.ids <- "default" } temp <- length(extra.args$zcase.ids) + 1 if("zcase.ids" %in% names(extra.args)) extra.args$zcase.ids <- rev(extra.args$zcase.ids) extra.args$col <-if("col" %in% names(extra.args)) rep(extra.args$col, length.out=3) else rev(do.call(colHandler, listUpdate(extra.args, list(z=1:(temp+1), ref=1:(temp+1), zlim=NULL)))[-1]) if("line.col" %in% names(extra.args)) extra.args$col[1] <- extra.args$line.col if(temp>1){ x <- x[extra.args$zcases == extra.args$zcase.ids[1]] y <- y[extra.args$zcases == extra.args$zcase.ids[1]] x1 <- c(x, rev(x)) for(i in (temp-1):1){ y1 <- z[extra.args$zcases == extra.args$zcase.ids[i]] y1 <- if(i>1) c(y1, rev(z[extra.args$zcases == extra.args$zcase.ids[i-1]])) else c(y1, rev(y)) do.call(panel.polygon, listUpdate(extra.args, list(x=x1, y=y1, col=extra.args$col[i+1], alpha=0.1, border=FALSE))) } for(i in (temp-1):1){ y1 <- z[extra.args$zcases == extra.args$zcase.ids[i]] do.call(panel.lines, listUpdate(extra.args, list(x=x, y=y1, col=extra.args$col[i+1]))) } } do.call(panel.lines, listUpdate(extra.args, list(x=x, y=y, col=extra.args$col[1]))) }
LaplacesDemon.hpc <- function(Model, Data, Initial.Values, Covar=NULL, Iterations=10000, Status=100, Thinning=10, Algorithm="MWG", Specs=list(B=NULL), Debug=list(DB.chol=FALSE, DB.eigen=FALSE, DB.MCSE=FALSE, DB.Model=TRUE), LogFile="", Chains=2, CPUs=2, Type="PSOCK", Packages=NULL, Dyn.libs=NULL) { detectedCores <- max(detectCores(), as.integer(Sys.getenv("NSLOTS")), na.rm=TRUE) cat("\n\nCPUs Detected:", detectedCores, "\n", file=LogFile, append=TRUE) if(CPUs > detectedCores) { cat("\nOnly", detectedCores, "will be used.\n", file=LogFile, append=TRUE) CPUs <- detectedCores} if(is.vector(Initial.Values)) { Initial.Values <- matrix(Initial.Values, Chains, length(Initial.Values), byrow=TRUE) cat("\nWarning: initial values were a vector, and are now a", file=LogFile, append=TRUE) cat("\n", Chains, "x", length(Initial.Values), "matrix.\n", file=LogFile, append=TRUE)} if(Algorithm == "INCA" && Chains != CPUs) { Chains <- CPUs cat("\nINCA:", Chains, "chains will be used\n")} cat("\nLaplace's Demon is preparing environments for CPUs...", file=LogFile, append=TRUE) cat("\n file=LogFile, append=TRUE) cl <- makeCluster(CPUs, Type) cat("\n file=LogFile, append=TRUE) on.exit({stopCluster(cl); cat("\n\nLaplace's Demon has finished.\n", file=LogFile, append=TRUE)}) Packages <- c(Packages, "LaplacesDemon") varlist <- unique(c(ls(), ls(envir=.GlobalEnv), ls(envir=parent.env(environment())))) clusterExport(cl, varlist=varlist, envir=environment()) clusterSetRNGStream(cl) wd <- getwd() clusterExport(cl, varlist=c("Packages", "Dyn.libs", "wd"), envir=environment()) demon.wrapper <- function(x, ...) { if(!is.null(Packages)) { sapply(Packages, function(x) library(x, character.only=TRUE, quietly=TRUE))} if(!is.null(Dyn.libs)) { sapply(Dyn.libs, function(x) dyn.load(paste(wd, x, sep = "/"))) on.exit(sapply(Dyn.libs, function(x) dyn.unload(paste(wd, x, sep = "/"))))} LaplacesDemon(Model, Data, Initial.Values[x,], Covar, Iterations, Status, Thinning, Algorithm, Specs, Debug, LogFile=paste(LogFile, ".", x, sep="")) } cat("\nStatus messages are not displayed for parallel processing.", file=LogFile, append=TRUE) cat("\nLaplace's Demon is beginning parallelization...\n", file=LogFile, append=TRUE) if(Algorithm == "INCA") { system(paste("Rscript -e 'library(parallel);library(LaplacesDemon);server_Listening(n=",CPUs,")'", sep=""), wait=FALSE) cat("Start hpc server...\n", file=LogFile, append=TRUE) clusterExport(cl, varlist="Chains", envir=environment()) clusterEvalQ(cl, con <- NULL) doCon <- function(i) { Sys.sleep(i/2) con <<- socketConnection("localhost", 19009, blocking=TRUE, open="r+")} clusterExport(cl, varlist="doCon", envir=environment()) expr <- NULL for (i in 1:CPUs) { tmp <- parse(text=paste("doCon(", i,")", sep="")) expr <- c(expr, tmp)} clusterApply(cl, expr, eval, env=.GlobalEnv) cat("\nOpen connections to hpc server...", file=LogFile, append=TRUE)} LaplacesDemon.out <- clusterApply(cl, 1:Chains, demon.wrapper, Model, Data, Initial.Values, Covar, Iterations, Status, Thinning, Algorithm, Specs, Debug) class(LaplacesDemon.out) <- "demonoid.hpc" if(Algorithm == "INCA") { clusterEvalQ(cl, {close(con)}) cat("\nClose connections to hpc server...", file=LogFile, append=TRUE) } return(LaplacesDemon.out) }
targets::tar_test("tar_jags_df() with dic", { skip_if_not_installed("rjags") skip_if_not_installed("R2jags") tmp <- tempfile() expect_false(file.exists(tmp)) tar_jags_example_file(path = tmp) expect_true(file.exists(tmp)) data <- tar_jags_example_data(n = 10) data$.join_data <- NULL dir <- tempfile() dir.create(dir) msg <- capture.output( out <- R2jags::jags( data = data, parameters.to.save = "beta", model.file = tmp, n.chains = 3, n.iter = 200L, n.burn = 100L, progress.bar = "none", working.directory = dir, DIC = TRUE ) ) out draws <- tar_jags_df(out, data = data, "draws") cols <- c("beta", "deviance", ".chain", ".iteration", ".draw") expect_true(all(cols %in% colnames(draws))) expect_equal(nrow(draws), 300L) summary <- tar_jags_df(out, data = data, "summary") expect_true( all(c("variable", "mean", "sd", "q5", ".join_data") %in% colnames(summary)) ) expect_true("beta" %in% summary$variable) expect_true("deviance" %in% summary$variable) expect_true(nrow(summary) < 10L) expect_equal(summary$.join_data, rep(NA_real_, 2)) data$.join_data$beta <- 1 summary <- tar_jags_df( out, data = data, output = "summary", variables = c("beta", "deviance") ) expect_equal(summary$.join_data[summary$variable == "beta"], 1) expect_equal(summary$.join_data[summary$variable == "deviance"], NA_real_) summaries <- as.list( quote( list( custom = ~posterior::quantile2(.x, probs = c(0.025, 0.5, 0.975)), custom2 = function(x, my_arg) my_arg ) ) ) summaries <- summaries[-1] summary <- tar_jags_df( out, data = data, output = "summary", summaries = summaries, summary_args = list(my_arg = 3L) ) expect_true( all(c("variable", "q97.5", "q2.5", "custom2") %in% colnames(summary)) ) expect_true("beta" %in% summary$variable) expect_true("deviance" %in% summary$variable) expect_true(all(summary$custom2 == 3L)) expect_true(nrow(summary) < 10L) dic <- tar_jags_df(out, data = data, "dic") expect_equal(nrow(dic), 1) expect_equal(sort(colnames(dic)), sort(c("dic", "pD"))) expect_error(tar_jags_df(out, "nope")) })
convert.input <- function(input.id, outfolder, formatname, mimetype, site.id, start_date, end_date, pkg, fcn, con = con, host, browndog, write = TRUE, format.vars, overwrite = FALSE, exact.dates = FALSE, allow.conflicting.dates = TRUE, insert.new.file = FALSE, pattern = NULL, forecast = FALSE, ensemble = FALSE, ensemble_name = NULL, dbparms=NULL, ... ) { input.args <- list(...) PEcAn.logger::logger.debug(paste("Convert.Inputs", fcn, input.id, host$name, outfolder, formatname, mimetype, site.id, start_date, end_date)) Rbinary <- ifelse(!exists("settings") || is.null(settings$host$Rbinary),"R",settings$host$Rbinary) n <- nchar(outfolder) if (substr(outfolder, n, n) != "/") { outfolder <- paste0(outfolder, "/") } outname <- utils::tail(unlist(strsplit(outfolder, "/")), n = 1) PEcAn.logger::logger.info(paste("start CHECK Convert.Inputs", fcn, input.id, host$name, outfolder, formatname, mimetype, site.id, start_date, end_date, forecast, ensemble)) if (forecast) { if (!is.integer(ensemble)) {ensemble = as.integer(1) } start_date <- lubridate::force_tz(lubridate::as_datetime(start_date), "UTC") end_date <- lubridate::force_tz(lubridate::as_datetime(end_date), "UTC") existing.dbfile <- list() existing.input <- list() existing_records <- list(input.id = NULL, dbfile.id = NULL) files.to.delete <- list() for (i in seq_len(ensemble)) { filename_pattern = paste0(pattern, "\\.([^.]*\\.)?") if (!is.null(ensemble_name)) { filename_pattern = paste0(filename_pattern, ensemble_name, "($|\\.)") } else if (ensemble > 1) { filename_pattern = paste0(filename_pattern, i, "($|\\.)") } existing.dbfile[[i]] <- PEcAn.DB::dbfile.input.check(siteid = site.id, mimetype = mimetype, formatname = formatname, parentid = input.id, startdate = start_date, enddate = end_date, con = con, hostname = host$name, exact.dates = TRUE, pattern = filename_pattern) if(nrow(existing.dbfile[[i]]) > 0) { existing.input[[i]] <- PEcAn.DB::db.query(paste0("SELECT * FROM inputs WHERE id=", existing.dbfile[[i]]$container_id),con) existing.input[[i]]$start_date <- lubridate::force_tz(lubridate::as_datetime(existing.input[[i]]$start_date), "UTC") existing.input[[i]]$end_date <- lubridate::force_tz(lubridate::as_datetime(existing.input[[i]]$end_date), "UTC") existing.machine <- PEcAn.DB::db.query(paste0("SELECT * from machines where id = '", existing.dbfile[[i]]$machine_id, "'"), con) machine.host <- ifelse(host$name == "localhost", PEcAn.remote::fqdn(), host$name) machine <- PEcAn.DB::db.query(paste0("SELECT * from machines where hostname = '", machine.host, "'"), con) if (existing.machine$id == machine$id) { if (overwrite) { files.to.delete <- c(files.to.delete, as.list(PEcAn.remote::remote.execute.R( paste0("list.files('", existing.dbfile[[i]]$file_path, "', full.names=TRUE)"), host, user = NA, verbose = TRUE,R = Rbinary, scratchdir = outfolder))) } else { existing_records$input.id = c(existing_records$input.id, existing.input[[i]]$id) existing_records$dbfile.id = c(existing_records$dbfile.id, existing.dbfile[[i]]$id) } } else { insert.new.file <- TRUE } } else { existing.input[[i]] <- data.frame() } } if (length(files.to.delete) > 0) { file.deletion.commands <- .get.file.deletion.commands(unlist(files.to.delete)) PEcAn.remote::remote.execute.R( file.deletion.commands$move.to.tmp, host, user = NA, verbose = TRUE,R = Rbinary, scratchdir = outfolder) successful <- FALSE on.exit( if (exists("successful") && successful) { PEcAn.logger::logger.info( "Conversion successful, with overwrite=TRUE. Deleting old files.") PEcAn.remote::remote.execute.R( file.deletion.commands$delete.tmp, host, user = NA, verbose = TRUE, R = Rbinary, scratchdir = outfolder) } else { PEcAn.logger::logger.info("Conversion failed. Replacing old files.") PEcAn.remote::remote.execute.R( file.deletion.commands$replace.from.tmp, host, user = NA, verbose = TRUE, R = Rbinary, scratchdir = outfolder) }, add = TRUE ) } if (length(existing_records$input.id) == ensemble) { if (ensemble == 1) { PEcAn.logger::logger.info("File with forecast data in the given range already exists on this machine.") } else { PEcAn.logger::logger.info("Files for all ensemble members for this forecast already exist on this machine.") } return(existing_records) } } else if (exact.dates) { if(!is.null(input.args$dbfile.id)){ existing.dbfile <- PEcAn.DB::dbfile.input.check(siteid = site.id, mimetype = mimetype, formatname = formatname, parentid = input.id, startdate = start_date, enddate = end_date, con = con, hostname = host$name, exact.dates = TRUE, pattern = pattern ) if ("id" %in% colnames(existing.dbfile)) { existing.dbfile <- existing.dbfile %>% dplyr::filter(.data$id==input.args$dbfile.id) } }else{ existing.dbfile <- PEcAn.DB::dbfile.input.check(siteid = site.id, mimetype = mimetype, formatname = formatname, parentid = input.id, startdate = start_date, enddate = end_date, con = con, hostname = host$name, exact.dates = TRUE, pattern = pattern ) } PEcAn.logger::logger.debug("File id =", existing.dbfile$id, " File name =", existing.dbfile$file_name, " File path =", existing.dbfile$file_path, " Input id =", existing.dbfile$container_id, digits = 10) PEcAn.logger::logger.info("end CHECK for existing input record") if (nrow(existing.dbfile) > 0) { existing.input <- PEcAn.DB::db.query(paste0("SELECT * FROM inputs WHERE id=", existing.dbfile[["container_id"]]),con) start_date <- lubridate::force_tz(lubridate::as_date(start_date), "UTC") end_date <- lubridate::force_tz(lubridate::as_date(end_date), "UTC") existing.input$start_date <- lubridate::force_tz(lubridate::as_date(existing.input$start_date), "UTC") existing.input$end_date <- lubridate::force_tz(lubridate::as_date(existing.input$end_date), "UTC") if(overwrite){ files.to.delete <- PEcAn.remote::remote.execute.R( paste0("list.files('", existing.dbfile[["file_path"]], "', full.names=TRUE)"), host, user = NA, verbose = TRUE,R = Rbinary, scratchdir = outfolder) file.deletion.commands <- .get.file.deletion.commands(files.to.delete) PEcAn.remote::remote.execute.R( file.deletion.commands$move.to.tmp, host, user = NA, verbose = TRUE,R = Rbinary, scratchdir = outfolder) successful <- FALSE on.exit( if (exists("successful") && successful) { PEcAn.logger::logger.info("Conversion successful, with overwrite=TRUE. Deleting old files.") PEcAn.remote::remote.execute.R( file.deletion.commands$delete.tmp, host, user = NA, verbose = TRUE, R = Rbinary, scratchdir = outfolder) } else { PEcAn.logger::logger.info("Conversion failed. Replacing old files.") PEcAn.remote::remote.execute.R( file.deletion.commands$replace.from.tmp, host, user = NA, verbose = TRUE, R = Rbinary, scratchdir = outfolder) }, add = TRUE ) } existing.machine <- PEcAn.DB::db.query(paste0("SELECT * from machines where id = '", existing.dbfile$machine_id, "'"), con) machine.host <- ifelse(host$name == "localhost", PEcAn.remote::fqdn(), host$name) machine <- PEcAn.DB::db.query(paste0("SELECT * from machines where hostname = '", machine.host, "'"), con) if (existing.machine$id != machine$id) { PEcAn.logger::logger.info("Valid Input record found that spans desired dates, but valid files do not exist on this machine.") PEcAn.logger::logger.info("Downloading all years of Valid input to ensure consistency") insert.new.file <- TRUE start_date <- existing.input$start_date end_date <- existing.input$end_date } else { PEcAn.logger::logger.info("Skipping this input conversion because files are already available.") return(list(input.id = existing.input$id, dbfile.id = existing.dbfile$id)) } } else { } } else { if (!is.null(ensemble) && ensemble) { return.all <-TRUE }else{ return.all <- FALSE } existing.dbfile <- PEcAn.DB::dbfile.input.check(siteid = site.id, mimetype = mimetype, formatname = formatname, parentid = input.id, startdate = start_date, enddate = end_date, con = con, hostname = host$name, pattern = pattern, return.all = return.all ) PEcAn.logger::logger.debug("File id =", existing.dbfile$id, " File name =", existing.dbfile$file_name, " File path =", existing.dbfile$file_path, " Input id =", existing.dbfile$container_id, digits = 10) PEcAn.logger::logger.info("end CHECK for existing input record.") if (nrow(existing.dbfile) > 0) { if (!is.null(ensemble) && ensemble) { existing.input <- existing.dbfile[["container_id"]] %>% unique() %>% purrr::map_dfr(function(one.cont.id) { PEcAn.DB::db.query(paste0("SELECT * FROM inputs WHERE id=", one.cont.id), con) }) } else{ existing.input <- PEcAn.DB::db.query(paste0("SELECT * FROM inputs WHERE id=", existing.dbfile[["container_id"]]), con) } start_date <- lubridate::force_tz(lubridate::as_date(start_date), "UTC") end_date <- lubridate::force_tz(lubridate::as_date(end_date), "UTC") existing.input$start_date <- lubridate::force_tz(lubridate::as_date(existing.input$start_date), "UTC") existing.input$end_date <- lubridate::force_tz(lubridate::as_date(existing.input$end_date), "UTC") if (overwrite) { files.to.delete <- PEcAn.remote::remote.execute.R( paste0("list.files('", existing.dbfile[["file_path"]], "', full.names=TRUE)"), host, user = NA, verbose = TRUE,R = Rbinary, scratchdir = outfolder) file.deletion.commands <- .get.file.deletion.commands(files.to.delete) PEcAn.remote::remote.execute.R( file.deletion.commands$move.to.tmp, host, user = NA, verbose = TRUE,R = Rbinary, scratchdir = outfolder) successful <- FALSE on.exit( if (exists("successful") && successful) { PEcAn.logger::logger.info( "Conversion successful, with overwrite=TRUE. Deleting old files.") PEcAn.remote::remote.execute.R( file.deletion.commands$delete.tmp, host, user = NA, verbose = TRUE, R = Rbinary, scratchdir = outfolder) } else { PEcAn.logger::logger.info( "Conversion failed. Replacing old files.") PEcAn.remote::remote.execute.R( file.deletion.commands$replace.from.tmp, host, user = NA, verbose = TRUE, R = Rbinary, scratchdir = outfolder) }, add = TRUE ) } else if ((start_date >= existing.input$start_date) && (end_date <= existing.input$end_date)) { existing.machine <- PEcAn.DB::db.query(paste0("SELECT * from machines where id = '", existing.dbfile$machine_id, "'"), con) machine.host <- ifelse(host$name == "localhost", PEcAn.remote::fqdn(), host$name) machine <- PEcAn.DB::db.query(paste0("SELECT * from machines where hostname = '", machine.host, "'"), con) if(existing.machine$id != machine$id){ PEcAn.logger::logger.info("Valid Input record found that spans desired dates, but valid files do not exist on this machine.") PEcAn.logger::logger.info("Downloading all years of Valid input to ensure consistency") insert.new.file <- TRUE start_date <- existing.input$start_date end_date <- existing.input$end_date } else { PEcAn.logger::logger.info("Skipping this input conversion because files are already available.") return(list(input.id = existing.input$id, dbfile.id = existing.dbfile$id)) } } else { start_date <- min(start_date, existing.input$start_date) end_date <- max(end_date, existing.input$end_date) PEcAn.logger::logger.info( paste0( "Changed start/end dates to '", start_date, "'/'", end_date, "' ", " so that existing input can be updated while maintaining continuous time span." ) ) } } else { } } machine.host <- ifelse(host$name == "localhost", PEcAn.remote::fqdn(), host$name) machine <- PEcAn.DB::db.query(paste0("SELECT * from machines where hostname = '", machine.host, "'"), con) if (nrow(machine) == 0) { PEcAn.logger::logger.error("machine not found", host$name) return(NULL) } if (missing(input.id) || is.na(input.id) || is.null(input.id)) { input <- dbfile <- NULL } else { input <- PEcAn.DB::db.query(paste("SELECT * from inputs where id =", input.id), con) if (nrow(input) == 0) { PEcAn.logger::logger.error("input not found", input.id) return(NULL) } if(!is.null(input.args$dbfile.id)){ dbfile <- PEcAn.DB::db.query( paste( "SELECT * from dbfiles where id=",input.args$dbfile.id," and container_id =", input.id, " and container_type = 'Input' and machine_id =", machine$id ), con ) }else{ dbfile <- PEcAn.DB::db.query( paste( "SELECT * from dbfiles where container_id =", input.id, " and container_type = 'Input' and machine_id =", machine$id ), con ) } if (nrow(dbfile) == 0) { PEcAn.logger::logger.error("dbfile not found", input.id) return(NULL) } if (nrow(dbfile) > 1) { PEcAn.logger::logger.warn("multiple dbfile records, using last", dbfile) dbfile <- dbfile[nrow(dbfile), ] } } conversion <- "local.remote" if (!is.null(browndog) && host$name == "localhost") { if (mimetype == "application/x-netcdf") { outputtype <- "pecan.zip" } else { if (formatname == "ed.met_driver_header_files_format" || formatname == "ed.met_driver_header files format") { outputtype <- "ed.zip" } else if (formatname == "Sipnet.climna") { outputtype <- "clim" } else if (formatname == "DALEC meteorology") { outputtype <- "dalec.dat" } else if (formatname == "LINKAGES met") { outputtype <- "linkages.dat" } else { PEcAn.logger::logger.severe(paste("Unknown formatname", formatname)) } } if (!is.null(browndog$username) && !is.null(browndog$password)) { userpwd <- paste(browndog$username, browndog$password, sep = ":") curloptions <- list(userpwd = userpwd, httpauth = 1L) } curloptions <- c(curloptions, followlocation = TRUE) out.html <- RCurl::getURL(paste0("http://dap-dev.ncsa.illinois.edu:8184/inputs/", browndog$inputtype), .opts = curloptions) if (outputtype %in% unlist(strsplit(out.html, "\n"))) { PEcAn.logger::logger.info(paste("Conversion from", browndog$inputtype, "to", outputtype, "through Brown Dog")) conversion <- "browndog" } } if (conversion == "browndog") { url <- file.path(browndog$url, outputtype) files <- list.files(dbfile$file_path, pattern = dbfile$file_name) files <- grep(dbfile$file_name, files, value = TRUE) zipfile <- paste0(dbfile$file_name, ".", browndog$inputtype) system(paste("cd", dbfile$file_path, "; zip", zipfile, paste(files, collapse = " "))) zipfile <- file.path(dbfile$file_path, zipfile) if (!file.exists(outfolder)) { dir.create(outfolder, showWarnings = FALSE, recursive = TRUE) } html <- RCurl::postForm(url, fileData = RCurl::fileUpload(zipfile), .opts = curloptions) link <- XML::getHTMLLinks(html) file.remove(zipfile) outfile <- file.path(outfolder, unlist(strsplit(basename(link), "_"))[2]) download.url(url = link, file = outfile, timeout = 600, .opts = curloptions, retry404 = TRUE) if (file.exists(outfile)) { if (utils::tail(unlist(strsplit(outfile, "[.]")), 1) == "zip") { fname <- utils::unzip(outfile, list = TRUE)$Name utils::unzip(outfile, files = fname, exdir = outfolder, overwrite = TRUE) file.remove(outfile) } else { fname <- list.files(outfolder) } } result <- data.frame( file = file.path(outfolder, fname), host = PEcAn.remote::fqdn(), mimetype = mimetype, formatname = formatname, startdate = paste(input$start_date, "00:00:00"), enddate = paste(input$end_date, "23:59:59"), stringsAsFactors = FALSE) } else if (conversion == "local.remote") { fcn.args <- input.args fcn.args$overwrite <- overwrite fcn.args$in.path <- dbfile$file_path fcn.args$in.prefix <- dbfile$file_name fcn.args$outfolder <- outfolder fcn.args$start_date <- start_date fcn.args$end_date <- end_date fcn.args$dbparms <- dbparms if (forecast && !is.null(input.id) && !is.na(input.id)) { fcn.args$year.fragment = TRUE } arg.string <- listToArgString(fcn.args) if (!missing(format.vars)) { arg.string <- paste0(arg.string, ", format=", paste0(list(format.vars))) } cmdFcn <- paste0(pkg, "::", fcn, "(", arg.string, ")") PEcAn.logger::logger.debug(paste0("convert.input executing the following function:\n", cmdFcn)) result <- PEcAn.remote::remote.execute.R( script = cmdFcn, host, user = NA, verbose = TRUE, R = Rbinary, scratchdir = outfolder ) if (is.data.frame(result)) { result <- list(result) } } PEcAn.logger::logger.info("RESULTS: Convert.Input") PEcAn.logger::logger.info(result) if (length(result[[1]]) <= 1){ PEcAn.logger::logger.debug(paste0("Processing data failed, please check validity of args:", arg.string)) PEcAn.logger::logger.severe(paste0("Unable to process data using this function:",fcn)) } result_sizes <- purrr::map_dfr( result, ~ dplyr::mutate( ., file_size = purrr::map_dbl(file, file.size), missing = is.na(file_size), empty = file_size == 0 ) ) if (any(result_sizes$missing) || any(result_sizes$empty)){ log_format_df = function(df){ df %>% format() %>% rbind(colnames(.), .) %>% purrr::reduce( paste, sep=" ") %>% paste(collapse="\n") } PEcAn.logger::logger.severe( "Requested Processing produced empty files or Nonexistant files :\n", log_format_df(result_sizes[,c(1,8,9,10)]), "\n Table of results printed above.", wrap = FALSE) } outlist <- unlist(strsplit(outname, "_")) if (exists("existing.input") && is.data.frame(existing.input)) { existing.input <- list(existing.input) } if (exists("existing.dbfile") && is.data.frame(existing.dbfile)) { existing.dbfile <- list(existing.dbfile) } if (write) { newinput = list(input.id = NULL, dbfile.id = NULL) for(i in 1:length(result)) { id_not_added <- TRUE if (exists("existing.input") && nrow(existing.input[[i]]) > 0 && (existing.input[[i]]$start_date != start_date || existing.input[[i]]$end_date != end_date)) { PEcAn.DB::db.query(paste0("UPDATE inputs SET start_date='", start_date, "', end_date='", end_date, "' WHERE id=", existing.input[[i]]$id), con) id_not_added = FALSE newinput$input.id = c(newinput$input.id, existing.input[[i]]$id) newinput$dbfile.id = c(newinput$dbfile.id, existing.dbfile[[i]]$id) } if (overwrite) { if (exists("existing.input") && nrow(existing.input[[i]]) > 0) { PEcAn.DB::db.query(paste0("UPDATE inputs SET name='", basename(dirname(result[[i]]$file[1])), "' WHERE id=", existing.input[[i]]$id), con) } if (exists("existing.dbfile") && nrow(existing.dbfile[[i]]) > 0) { PEcAn.DB::db.query(paste0("UPDATE dbfiles SET file_path='", dirname(result[[i]]$file[1]), "', ", "file_name='", result[[i]]$dbfile.name[1], "' WHERE id=", existing.dbfile[[i]]$id), con) } } if (is.numeric(ensemble)){ parent.id <- ifelse(is.null(input[i]), NA, input[1]$id) }else{ parent.id <- ifelse(is.null(input[i]), NA, input[i]$id) } if ("newsite" %in% names(input.args) && !is.null(input.args[["newsite"]])) { site.id <- input.args$newsite } if (insert.new.file && id_not_added) { dbfile.id <- PEcAn.DB::dbfile.insert(in.path = dirname(result[[i]]$file[1]), in.prefix = result[[i]]$dbfile.name[1], 'Input', existing.input[[i]]$id, con, reuse=TRUE, hostname = machine$hostname) newinput$input.id <- c(newinput$input.id, existing.input[[i]]$id) newinput$dbfile.id <- c(newinput$dbfile.id, dbfile.id) } else if (id_not_added) { if (!is.null(ensemble) | is.null(ensemble_name)){ ens.flag <- TRUE }else{ ens.flag <- FALSE } new_entry <- PEcAn.DB::dbfile.input.insert(in.path = dirname(result[[i]]$file[1]), in.prefix = result[[i]]$dbfile.name[1], siteid = site.id, startdate = start_date, enddate = end_date, mimetype, formatname, parentid = parent.id, con = con, hostname = machine$hostname, allow.conflicting.dates = allow.conflicting.dates, ens=ens.flag ) newinput$input.id <- c(newinput$input.id, new_entry$input.id) newinput$dbfile.id <- c(newinput$dbfile.id, new_entry$dbfile.id) } } successful <- TRUE return(newinput) } else { PEcAn.logger::logger.warn("Input was not added to the database") successful <- TRUE return(NULL) } } .get.file.deletion.commands <- function(files.to.delete) { if(length(files.to.delete) > 0) { tmp.dirs <- file.path(unique(dirname(files.to.delete)), 'tmp') tmp.paths <- file.path(dirname(files.to.delete), 'tmp', basename(files.to.delete)) tmp.dirs.string <- paste0("c(", paste(paste0("'", tmp.dirs, "'"), collapse=', '), ")") tmp.path.string <- paste0("c(", paste(paste0("'", tmp.paths, "'"), collapse=', '), ")") original.path.string <- paste0("c(", paste(paste0("'", files.to.delete, "'"), collapse=', '), ")") move.to.tmp <- paste0( "dir.create(", tmp.dirs.string, ", recursive=TRUE, showWarnings=FALSE); ", "file.rename(from=", original.path.string, ", to=", tmp.path.string, ")" ) replace.from.tmp <- paste0( "file.rename(from=", tmp.path.string, ", to=", original.path.string, ");", "unlink(", tmp.dirs.string, ", recursive=TRUE)" ) delete.tmp <- paste0( "unlink(", tmp.dirs.string, ", recursive=TRUE)" ) return(list(move.to.tmp=move.to.tmp, replace.from.tmp=replace.from.tmp, delete.tmp=delete.tmp)) } else { return(NULL) } }
specdens <- function(object, main, plot = TRUE, ...){ if (!inherits(object, c("bvpot", "mcpot"))) stop("Use only with 'bvpot'/'mcpot' objects") model <- object$model alpha <- object$param["alpha"] if (model == "log"){ h <- function(q){ res <- rep(NaN, length(q)) q01 <- q[q > 0 & q <= 1] res[q > 0 & q <= 1] <- (1/alpha - 1) * (q01 * (1-q01))^(-(1+1/alpha)) * (q01^(-1/alpha) + (1-q01)^(-1/alpha))^(alpha-2) res } } if (model == "alog"){ asCoef1 <- object$param["asCoef1"] asCoef2 <- object$param["asCoef2"] h <- function(q){ res <- rep(NaN, length(q)) q01 <- q[q > 0 & q <= 1] res[q > 0 & q <= 1] <- (1/alpha - 1) * (asCoef1 * asCoef2)^(1/alpha) * (q01 * (1-q01))^(-(1+1/alpha)) * ((asCoef1/q01)^(1/alpha) + (asCoef2/(1-q01))^(1/alpha))^(alpha-2) res } } if (model == "nlog"){ h <- function(q){ res <- rep(NaN, length(q)) q01 <- q[q > 0 & q <= 1] res[q > 0 & q <= 1] <- (1 + alpha) * (q01 * (1-q01))^(alpha-1) * (q01^alpha + (1-q01)^alpha)^(-1/alpha-2) res } } if (model == "anlog"){ asCoef1 <- object$param["asCoef1"] asCoef2 <- object$param["asCoef2"] h <- function(q){ res <- rep(NaN, length(q)) q01 <- q[q > 0 & q <= 1] res[q > 0 & q <= 1] <- (1 + alpha) * (asCoef1 * asCoef2)^(-alpha) * (q01 * (1-q01))^(alpha-1) * ((q01/asCoef1)^alpha + ((1-q01)/asCoef2)^alpha)^(-1/alpha-2) res } } if (model == "mix"){ h <- function(q){ res <- rep(NaN, length(q)) res[q > 0 & q <= 1] <- 2 * alpha res } } if (model == "amix"){ asCoef <- object$param["asCoef"] h <- function(q){ res <- rep(NaN, length(q)) q01 <- q[q > 0 & q <= 1] res[q > 0 & q <= 1] <- 2 * alpha + 6 * asCoef * (1-q01) res } } if (plot){ eps <- .Machine$double.eps^0.5 if (model == "log") eps <- 0.01 if (missing(main)) main <- "Spectral Density" plot(h, from = eps, to = 1 - eps, main = main, ...) } attributes(h) <- list(model = model) invisible(h) }
pairwiseMedianTest = function(formula=NULL, data=NULL, x=NULL, g=NULL, digits = 4, method = "fdr", ...) { if(!is.null(formula)){ x = eval(parse(text=paste0("data","$",all.vars(formula[[2]])[1]))) g = eval(parse(text=paste0("data","$",all.vars(formula[[3]])[1]))) } if(!is.factor(g)){g=factor(g)} n = length(levels(g)) N = n*(n-1)/2 d = data.frame(x = x, g = g) Z = data.frame(Comparison=rep("A", N), p.value=rep(NA, N), p.adjust=rep(NA, N), stringsAsFactors=FALSE) k=0 for(i in 1:(n-1)){ for(j in (i+1):n){ k=k+1 Namea = as.character(levels(g)[i]) Nameb = as.character(levels(g)[j]) Datax = subset(d, g==levels(g)[i]) Datay = subset(d, g==levels(g)[j]) Dataz = rbind(Datax, Datay) Dataz$g2 = factor(Dataz$g) z = median_test(x ~ g2, data=Dataz, ...) P = signif(pvalue(z)[1], digits=digits) P.adjust = NA Z[k,] =c( paste0(Namea, " - ", Nameb, " = 0"), P, P.adjust) } } Z$p.adjust = signif(p.adjust(Z$p.value, method = method), digits=4) return(Z) }
CF=function(data,group){ n=tapply(data, group, length) k=length(tapply(data, group, length)) xbar=tapply(data, group, mean) var=tapply(data, group, var) w=n/var; h=w/sum(w); C=sum(w*(xbar-sum(h*xbar))^2); pvalue=1-pchisq(C,k-1); result=matrix(c(round(C,digits=4),round(k-1),round(pvalue,digits=4))) rownames(result)=c("Test Statistic","df","p-value") colnames(result)=c("Cochran F") return(t(result)) }
expected <- eval(parse(text="c(\"ddenseMatrix\", \"dMatrix\", \"denseMatrix\", \"Matrix\", \"mMatrix\")")); test(id=0, code={ argv <- eval(parse(text="list(\"ddenseMatrix\", c(\"ddenseMatrix\", \"dMatrix\", \"denseMatrix\", \"Matrix\", \"mMatrix\"))")); do.call(`.cache_class`, argv); }, o=expected);
autowin <- function(reference, xvar, cdate, bdate, baseline, range, stat, func, type, refday, cmissing = FALSE, cinterval = "day", upper = NA, lower = NA, binary = FALSE, centre = list(NULL, "both"), cohort = NULL, spatial = NULL, cutoff.day = NULL, cutoff.month = NULL, furthest = NULL, closest = NULL, thresh = NULL){ if(all(is.na(as.Date(cdate, format = "%d/%m/%Y")))){ stop("cdate is not in the correct format. Please provide date data in dd/mm/yyyy.") } if(all(is.na(as.Date(bdate, format = "%d/%m/%Y")))){ stop("bdate is not in the correct format. Please provide date data in dd/mm/yyyy.") } thresholdQ <- "N" if((!is.na(upper) || !is.na(lower)) && (cinterval == "week" || cinterval == "month")){ thresholdQ <- readline("You specified a climate threshold using upper and/or lower and are working at a weekly or monthly scale. Do you want to apply this threshold before calculating weekly/monthly means (i.e. calculate thresholds for each day)? Y/N") thresholdQ <- toupper(thresholdQ) if(thresholdQ != "Y" & thresholdQ != "N"){ thresholdQ <- readline("Please specify yes (Y) or no (N)") } } if(is.null(cohort) == TRUE){ cohort = lubridate::year(as.Date(bdate, format = "%d/%m/%Y")) } WindowOpen <- reference$Dataset$WindowOpen[1] WindowClose <- reference$Dataset$WindowClose[1] reference <- reference$BestModelData$climate if(is.null(thresh) == FALSE){ stop("Parameter 'thresh' is now redundant. Please use parameter 'binary' instead.") } if(type == "variable" || type == "fixed"){ stop("Parameter 'type' now uses levels 'relative' and 'absolute' rather than 'variable' and 'fixed'.") } if(is.null(cutoff.day) == FALSE & is.null(cutoff.month) == FALSE){ stop("cutoff.day and cutoff.month are now redundant. Please use parameter 'refday' instead.") } if(is.null(furthest) == FALSE & is.null(closest) == FALSE){ stop("furthest and closest are now redundant. Please use parameter 'range' instead.") } xvar = xvar[[1]] message("Initialising, please wait...") if (stat == "slope" & func == "log" || stat == "slope" & func == "inv"){ stop("stat = slope cannot be used with func = log or inv as negative values may be present.") } if (cinterval == "day"){ if ((min(as.Date(bdate, format = "%d/%m/%Y")) - range[1]) < min(as.Date(cdate, format = "%d/%m/%Y"))){ stop("You do not have enough climate data to search that far back. Please adjust the value of range or add additional climate data.") } } if (cinterval == "week"){ if ((min(as.Date(bdate, format = "%d/%m/%Y")) - lubridate::weeks(range[1])) < min(as.Date(cdate, format = "%d/%m/%Y"))){ stop("You do not have enough climate data to search that far back. Please adjust the value of range or add additional climate data.") } } if (cinterval == "month"){ if ((min(as.Date(bdate, format = "%d/%m/%Y")) - months(range[1])) < min(as.Date(cdate, format = "%d/%m/%Y"))){ stop("You do not have enough climate data to search that far back. Please adjust the value of range or add additional climate data.") } } duration <- (range[1] - range[2]) + 1 maxmodno <- (duration * (duration + 1)) / 2 cont <- convertdate(bdate = bdate, cdate = cdate, xvar = xvar, cinterval = cinterval, type = type, refday = refday, cohort = cohort, spatial = spatial, thresholdQ = thresholdQ) modno <- 1 modlist <- list() cmatrix <- matrix(ncol = (duration), nrow = length(bdate)) climate1 <- matrix(ncol = 1, nrow = length(bdate), 1) if(cinterval == "day" || (!is.na(thresholdQ) && thresholdQ == "N")){ if(is.null(spatial) == FALSE){ if (is.na(upper) == FALSE && is.na(lower) == TRUE){ if (binary == TRUE){ cont$xvar$Clim <- ifelse (cont$xvar$Clim > upper, 1, 0) } else { cont$xvar$Clim <- ifelse (cont$xvar$Clim > upper, cont$xvar$Clim, 0) } } if (is.na(lower) == FALSE && is.na(upper) == TRUE){ if (binary == TRUE){ cont$xvar$Clim <- ifelse (cont$xvar$Clim < lower, 1, 0) } else { cont$xvar$Clim <- ifelse (cont$xvar$Clim < lower, cont$xvar$Clim, 0) } } if (is.na(lower) == FALSE && is.na(upper) == FALSE){ if (binary == TRUE){ cont$xvar$Clim <- ifelse (cont$xvar$Clim > lower && cont$xvar$Clim < upper, 1, 0) } else { cont$xvar$Clim <- ifelse (cont$xvar$Clim > lower && cont$xvar$Clim < upper, cont$xvar$Clim - lower, 0) } } } else { if (is.na(upper) == FALSE && is.na(lower) == TRUE){ if (binary == TRUE){ cont$xvar <- ifelse (cont$xvar > upper, 1, 0) } else { cont$xvar <- ifelse (cont$xvar > upper, cont$xvar, 0) } } if (is.na(lower) == FALSE && is.na(upper) == TRUE){ if (binary == TRUE){ cont$xvar <- ifelse (cont$xvar < lower, 1, 0) } else { cont$xvar <- ifelse (cont$xvar < lower, cont$xvar, 0) } } if (is.na(lower) == FALSE && is.na(upper) == FALSE){ if (binary == TRUE){ cont$xvar <- ifelse (cont$xvar > lower & cont$xvar < upper, 1, 0) } else { cont$xvar <- ifelse (cont$xvar > lower & cont$xvar < upper, cont$xvar - lower, 0) } } } } if(is.null(spatial) == FALSE){ for (i in 1:length(bdate)){ cmatrix[i, ] <- cont$xvar[which(cont$cintno$spatial %in% cont$bintno$spatial[i] & cont$cintno$Date %in% (cont$bintno$Date[i] - c(range[2]:range[1]))), 1] } } else { for (i in 1:length(bdate)){ cmatrix[i, ] <- cont$xvar[which(cont$cintno %in% (cont$bintno[i] - c(range[2]:range[1])))] } } cmatrix <- as.matrix(cmatrix[, c(ncol(cmatrix):1)]) if (cmissing == FALSE && length(which(is.na(cmatrix))) > 0){ if(is.null(spatial) == FALSE){ if (cinterval == "day"){ .GlobalEnv$missing <- as.Date(cont$cintno$Date[is.na(cont$xvar$Clim)], origin = min(as.Date(cdate, format = "%d/%m/%Y")) - 1) } if (cinterval == "month"){ .GlobalEnv$missing <- c(paste("Month:", month(as.Date(cont$cintno$Date[is.na(cont$xvar$Clim)], origin = min(as.Date(cdate, format = "%d/%m/%Y")) - 1)), "Year:", year(as.Date(cont$cintno$Date[is.na(cont$xvar$Clim)], origin = min(as.Date(cdate, format = "%d/%m/%Y")) - 1)))) } if (cinterval == "week"){ .GlobalEnv$missing <- c(paste("Week:", month(as.Date(cont$cintno$Date[is.na(cont$xvar$Clim)], origin = min(as.Date(cdate, format = "%d/%m/%Y")) - 1)), "Year:", year(as.Date(cont$cintno$Date[is.na(cont$xvar$Clim)], origin = min(as.Date(cdate, format = "%d/%m/%Y")) - 1)))) } stop(c("Climate data should not contain NA values: ", length(.GlobalEnv$missing), " NA value(s) found. Please add missing climate data or set cmissing=TRUE. See object missing for all missing climate data")) } else { if (cinterval == "day"){ .GlobalEnv$missing <- as.Date(cont$cintno[is.na(cont$xvar)], origin = min(as.Date(cdate, format = "%d/%m/%Y")) - 1) } if (cinterval == "month"){ .GlobalEnv$missing <- c(paste("Month:", month(as.Date(cont$cintno[is.na(cont$xvar)], origin = min(as.Date(cdate, format = "%d/%m/%Y")) - 1)), "Year:", year(as.Date(cont$cintno[is.na(cont$xvar)], origin = min(as.Date(cdate, format = "%d/%m/%Y")) - 1)))) } if (cinterval == "week"){ .GlobalEnv$missing <- c(paste("Week:", month(as.Date(cont$cintno[is.na(cont$xvar)], origin = min(as.Date(cdate, format = "%d/%m/%Y")) - 1)), "Year:", year(as.Date(cont$cintno[is.na(cont$xvar)], origin = min(as.Date(cdate, format = "%d/%m/%Y")) - 1)))) } stop(c("Climate data should not contain NA values: ", length(.GlobalEnv$missing), " NA value(s) found. Please add missing climate data or set cmissing=TRUE. See object missing for all missing climate data")) } } if (cmissing != FALSE && any(is.na(cmatrix))){ message("Missing climate data detected. Please wait while NAs are replaced.") for(i in which(is.na(cmatrix))){ if(i %% nrow(cmatrix) == 0){ col <- i/nrow(cmatrix) row <- nrow(cmatrix) } else { col <- i%/%nrow(cmatrix) + 1 row <- i %% nrow(cmatrix) } if(cmissing == "method1"){ if(cinterval == "day"){ cdate_new <- data.frame(Date = as.Date(cdate, format = "%d/%m/%Y")) bioldate <- as.Date(bdate[row], format = "%d/%m/%Y") missingdate <- bioldate - (col + range[2] - 1) if(is.null(spatial) == FALSE){ cdate_new$spatial <- spatial[[2]] siteID <- spatial[[1]][row] cmatrix[row, col] <- mean(xvar[which(cdate_new$Date %in% c(missingdate - (1:2), missingdate + (1:2)) & cdate_new$spatial %in% siteID)], na.rm = T) } else { cmatrix[row, col] <- mean(xvar[which(cdate_new$Date %in% c(missingdate - (1:2), missingdate + (1:2)))], na.rm = T) } } else if(cinterval == "week" || cinterval == "month"){ if(is.null(spatial) == FALSE){ cdate_new <- data.frame(Date = cont$cintno$Date, spatial = cont$cintno$spatial) bioldate <- cont$bintno$Date[row] missingdate <- bioldate - (col + range[2] - 1) siteID <- spatial[[1]][row] cmatrix[row, col] <- mean(cont$xvar$Clim[which(cdate_new$Date %in% c(missingdate - (1:2), missingdate + (1:2)) & cdate_new$spatial %in% siteID)], na.rm = T) } else { cdate_new <- data.frame(Date = cont$cintno) bioldate <- cont$bintno[row] missingdate <- bioldate - (col + range[2] - 1) cmatrix[row, col] <- mean(cont$xvar[which(cdate_new$Date %in% c(missingdate - (1:2), missingdate + (1:2)))], na.rm = T) } } if(is.na(cmatrix[row, col])){ stop("Too many consecutive NAs present in the data. Consider using method2 or manually replacing NAs.") } } else if(cmissing == "method2"){ if(cinterval == "day"){ cdate_new <- data.frame(Date = as.Date(cdate, format = "%d/%m/%Y"), Month = lubridate::month(as.Date(cdate, format = "%d/%m/%Y")), Day = lubridate::day(as.Date(cdate, format = "%d/%m/%Y"))) bioldate <- as.Date(bdate[row], format = "%d/%m/%Y") missingdate <- bioldate - (col + range[2] - 1) missingdate <- data.frame(Date = missingdate, Month = lubridate::month(missingdate), Day = lubridate::day(missingdate)) if(is.null(spatial) == FALSE){ cdate_new$spatial <- spatial[[2]] siteID <- spatial[[1]][row] cmatrix[row, col] <- mean(xvar[which(cdate_new$Month %in% missingdate$Month & cdate_new$Day %in% missingdate$Day & cdate_new$spatial %in% siteID)], na.rm = T) } else { cmatrix[row, col] <- mean(xvar[which(cdate_new$Month %in% missingdate$Month & cdate_new$Day %in% missingdate$Day)], na.rm = T) } } else if(cinterval == "week" || cinterval == "month"){ if(is.null(spatial) == FALSE){ cdate_new <- data.frame(Date = cont$cintno$Date, spatial = cont$cintno$spatial) bioldate <- cont$bintno$Date[row] missingdate <- bioldate - (col + range[2] - 1) if(cinterval == "week"){ cdate_new$Date <- cdate_new$Date - (floor(cdate_new$Date/52) * 52) cdate_new$Date <- ifelse(cdate_new$Date == 0, 52, cdate_new$Date) missingdate <- missingdate - (floor(missingdate/52) * 52) missingdate <- ifelse(missingdate == 0, 52, missingdate) } else { cdate_new$Date <- cdate_new$Date - (floor(cdate_new$Date/12) * 12) cdate_new$Date <- ifelse(cdate_new$Date == 0, 12, cdate_new$Date) missingdate <- missingdate - (floor(missingdate/12) * 12) missingdate <- ifelse(missingdate == 0, 12, missingdate) } siteID <- spatial[[1]][row] cmatrix[row, col] <- mean(cont$xvar$Clim[which(cdate_new$Date %in% missingdate & cdate_new$spatial %in% siteID)], na.rm = T) } else { cdate_new <- data.frame(Date = cont$cintno) bioldate <- cont$bintno[row] missingdate <- bioldate - (col + range[2] - 1) if(cinterval == "week"){ cdate_new$Date <- cdate_new$Date - (floor(cdate_new$Date/52) * 52) cdate_new$Date <- ifelse(cdate_new$Date == 0, 52, cdate_new$Date) missingdate <- missingdate - (floor(missingdate/52) * 52) missingdate <- ifelse(missingdate == 0, 52, missingdate) } else { cdate_new$Date <- cdate_new$Date - (floor(cdate_new$Date/12) * 12) cdate_new$Date <- ifelse(cdate_new$Date == 0, 12, cdate_new$Date) missingdate <- missingdate - (floor(missingdate/12) * 12) missingdate <- ifelse(missingdate == 0, 12, missingdate) } cmatrix[row, col] <- mean(cont$xvar[which(cdate_new$Date %in% missingdate)], na.rm = T) } } if(is.na(cmatrix[row, col])){ stop("There is not enough data to replace missing values using method2. Consider dealing with NA values manually") } } else { stop("cmissing should be method1, method2 or FALSE") } } } modeldat <- model.frame(baseline) modeldat$yvar <- modeldat[, 1] modeldat$climate <- seq(1, nrow(modeldat), 1) if (is.null(weights(baseline)) == FALSE){ if (class(baseline)[1] == "glm" & sum(weights(baseline)) == nrow(model.frame(baseline)) || attr(class(baseline), "package") == "lme4" & sum(weights(baseline)) == nrow(model.frame(baseline))){ } else { modeldat$modweights <- weights(baseline) baseline <- update(baseline, .~., weights = modeldat$modweights, data = modeldat) } } if(!is.null(attr(class(baseline), "package")) && attr(class(baseline), "package") == "lme4" && class(baseline)[1] == "lmerMod" && baseline@resp$REML == 1){ message("Linear mixed effects models are run in climwin using maximum likelihood. Baseline model has been changed to use maximum likelihood.") baseline <- update(baseline, yvar ~., data = modeldat, REML = F) } if(attr(baseline, "class")[1] == "lme" && baseline$method == "REML"){ message("Linear mixed effects models are run in climwin using maximum likelihood. Baseline model has been changed to use maximum likelihood.") baseline <- update(baseline, yvar ~., data = modeldat, method = "ML") } if (func == "lin"){ modeloutput <- update(baseline, .~. + climate, data = modeldat) } else if (func == "quad") { modeloutput <- update(baseline, .~. + climate + I(climate ^ 2), data = modeldat) } else if (func == "cub") { modeloutput <- update(baseline, .~. + climate + I(climate ^ 2) + I(climate ^ 3), data = modeldat) } else if (func == "log") { modeloutput <- update(baseline, .~. + log(climate), data = modeldat) } else if (func == "inv") { modeloutput <- update (baseline, .~. + I(climate ^ -1), data = modeldat) } else { stop("Define func") } pb <- txtProgressBar(min = 0, max = maxmodno, style = 3, char = "|") for (m in range[2]:range[1]){ for (n in 1:duration){ if ( (m - n) >= (range[2] - 1)){ if (stat != "slope" || n > 1){ windowopen <- m - range[2] + 1 windowclose <- windowopen-n + 1 if (stat == "slope"){ time <- seq(1, n, 1) climate1 <- apply(cmatrix[, windowclose:windowopen], 1, FUN = function(x) coef(lm(x ~ time))[2]) } else { if (n == 1){ climate1 <- cmatrix[, windowclose:windowopen] } else { climate1 <- apply(cmatrix[, windowclose:windowopen], 1, FUN = stat) } } modeloutput <- cor(climate1, reference) modlist$cor[modno] <- modeloutput modlist$WindowOpen[modno] <- m modlist$WindowClose[modno] <- m - n + 1 modno <- modno + 1 } } } setTxtProgressBar(pb, modno - 1) } modlist$Furthest <- range[1] modlist$Closest <- range[2] modlist$Statistics <- stat modlist$Functions <- type modlist$BestWindowOpen <- WindowOpen modlist$BestWindowClose <- WindowClose if (type == TRUE){ modlist$Reference.day <- refday[1] modlist$Reference.month <- refday[2] } local <- as.data.frame(modlist) return(local) }
embedding.rect.cat.epsNEW <- function(cat,cycle=FALSE,eps=1/nrow(cat))embedding.rect.eps(cat$xcat.work,cat$ycat.work,cycle=cycle,eps=eps)
library(kernlab) data(iris) teardown({ detach("package:kernlab", unload = TRUE) }) test_that("pmml.ksvm error when a specified kernel is not supported", { expect_error( pmml(ksvm(Sepal.Length ~ ., data = iris, kernel = "laplacedot"), dataset = iris), "laplacedot kernel is not supported. Supported ksvm kernels: rbfdot, polydot, vanilladot, tanhdot." ) invisible(capture.output(mod2 <- ksvm(Sepal.Length ~ ., data = iris, kernel = "besseldot"))) expect_error( pmml(mod2, dataset = iris), "besseldot kernel is not supported. Supported ksvm kernels: rbfdot, polydot, vanilladot, tanhdot." ) invisible(capture.output(mod3 <- ksvm(Sepal.Length ~ ., data = iris, kernel = "anovadot"))) expect_error( pmml(mod3, dataset = iris), "anovadot kernel is not supported. Supported ksvm kernels: rbfdot, polydot, vanilladot, tanhdot." ) invisible(capture.output(mod4 <- ksvm(Sepal.Length ~ ., data = iris, kernel = "splinedot"))) expect_error( pmml(mod4, dataset = iris), "splinedot kernel is not supported. Supported ksvm kernels: rbfdot, polydot, vanilladot, tanhdot." ) })
plot.bivrp <- function(x, kernel, superpose.points, chp, add.dplots, theta.sort, add.polygon, reduce.polygon, one.dim, pch=16, cex=.8, conf, xlab, ylab, main, point.col, point.pch, transparent.colors, density.bw="SJ", ...) { obj <- x rm(x) if(missing(kernel)) kernel <- FALSE if(missing(chp)) chp <- FALSE if(missing(superpose.points)) superpose.points <- FALSE if(missing(conf)) conf <- obj$conf if(missing(one.dim)) one.dim <- FALSE if(missing(add.dplots)) add.dplots <- TRUE if(missing(theta.sort)) theta.sort <- TRUE if(missing(reduce.polygon)) reduce.polygon <- "proportional" if(one.dim) { if(missing(xlab)) xlab <- "Residuals" if(missing(ylab)) ylab <- "Density" if(missing(main)) main <- "" } else { if(missing(xlab)) xlab <- "Residuals 1" if(missing(ylab)) ylab <- "Residuals 2" if(missing(main)) main <- "" } if(missing(add.polygon)) add.polygon <- FALSE if(missing(transparent.colors)) transparent.colors <- TRUE reslist.ord <- obj$reslist.ord res.original.ord <- obj$res.original.ord res.simlist <- list() for(i in 1:nrow(res.original.ord)) { res.simlist[[i]] <- matrix(unlist( lapply(reslist.ord, function(x) x[i,])), byrow=T, ncol=2) } rxs <- range(res1 <- unlist(lapply(reslist.ord, function(a) a$x))) rys <- range(res2 <- unlist(lapply(reslist.ord, function(a) a$y))) rxo <- range(res.original1 <- res.original.ord[,1]) ryo <- range(res.original2 <- res.original.ord[,2]) if(add.dplots) { preps <- add_dplots_prep(res1=res1, res2=res2, res.original1=res.original1, res.original2=res.original2, density.bw = density.bw) d1 <- preps$d1 d2 <- preps$d2 cc1 <- preps$cc1 c2 <- preps$c2 startd1 <- preps$startd1 startd2 <- preps$startd2 d1.or <- preps$d1.or d2.or <- preps$d2.or range.x <- c(min(rxs, rxo), max(rxs, rxo)*1.7) range.y <- c(min(rys, ryo), max(rys, ryo)*1.7) axes. <- F bty. <- "n" xlab. <- xlab ylab. <- ylab xlab <- "" ylab <- "" } else { range.x <- c(min(rxs, rxo), max(rxs, rxo)) range.y <- c(min(rys, ryo), max(rys, ryo)) axes. <- T bty. <- "o" } if(theta.sort) { plot(0, 0, xlim=range.x, ylim=range.y, type="n", xaxt="n", yaxt="n", xlab=xlab, ylab=ylab, main=main, bty=bty., ...) x.seq <- seq(min(rxs, rxo), max(rxs, rxo), length = 5) axis(1, x.seq, round(x.seq, 2)) y.seq <- seq(min(rys, ryo), max(rys, ryo), length = 5) axis(2, y.seq, round(y.seq, 2)) pol.centre <- matrix(0, ncol=2, nrow=nrow(res.original.ord)) pol.inside <- NULL if(add.polygon) ppoly <- T else ppoly <- F for(i in 1:nrow(res.original.ord)) { chpoly <- chp_perpoint(df.point=res.simlist[[i]], res.original=res.original.ord[i,], reduce.polygon=reduce.polygon, pch=pch, cex=cex, conf=conf, ppoly=ppoly, ...) pol.centre[i,] <- chpoly$pol.centre pol.inside[i] <- chpoly$pol.inside } if(missing(point.col)) point.col <- c(1,2) if(missing(point.pch)) point.pch <- c(16,16) point.colours <- ifelse(pol.inside, point.col[1], point.col[2]) point.pchs <- ifelse(pol.inside, point.pch[1], point.pch[2]) points(res.original.ord, pch=point.pchs, cex=cex, col=point.colours, ...) points(pol.centre, pch=1, cex=cex, col=point.colours, ...) arrows(pol.centre[,1], pol.centre[,2], as.numeric(res.original.ord[,1]), as.numeric(res.original.ord[,2]), code=3, length=0, lty=2, col=point.colours) tot.points <- nrow(res.original.ord) n.out <- sum(!pol.inside) cat(n.out, " out of ", tot.points, " points out of polygons (", round(n.out/tot.points*100, 2), "%).", "\n", sep="") if(add.dplots) { add_dplots_plot(range.x, range.y, xlab., ylab., d1, d2, cc1, c2, startd1, startd2, res1, res2, res.original1, res.original2, d1.or, d2.or, transparent.colors) } } else { res1 <- obj$res1 res2 <- obj$res2 res.original1 <- obj$res.original1 res.original2 <- obj$res.original2 if(one.dim) { par(mfrow=c(1,2)) dres1 <- density(res1, bw = "SJ") dres1.or <- density(res.original1, bw = "SJ") plot(res1, rep(0, length(res1)), xlim=range(res1, res.original1), pch=16, col="lightgray", ylim=c(0, max(dres1$y, dres1.or$y)), type="n", xlab=xlab, ylab=ylab, main=main) polygon(dres1, col="lightgray", border="lightgray") polygon(dres1.or, col=" points(res1, rep(0, length(res1)), pch=21, col="white", bg="lightgray") points(res.original1, rep(0, length(res.original1)), pch=16, col=1) dres2 <- density(res2, bw = "SJ") dres2.or <- density(res.original2, bw = "SJ") plot(res2, rep(0, length(res2)), xlim=range(res2, res.original2), pch=16, col="lightgray", ylim=c(0, max(dres2$y, dres2.or$y)), type="n", xlab=xlab, ylab=ylab, main=main) polygon(dres2, col="lightgray", border="lightgray") polygon(dres2.or, col=" points(res2, rep(0, length(res2)), pch=21, col="white", bg="lightgray") points(res.original2, rep(0, length(res.original2)), pch=16, col=1) return(invisible()) } if(chp) { chp.xy <- chull(res1, res2) dxy <- data.frame(res1, res2) pol <- dxy[chp.xy,] pol.area <- polygon_area(pol)$area if(reduce.polygon == "peel") { dif <- 1 while(dif > conf) { dxy <- dxy[-chp.xy,] chp.xy <- with(dxy, chull(res1, res2)) pol <- dxy[chp.xy,] pol.area2 <- polygon_area(pol)$area dif <- pol.area2/pol.area } } else { pol <- get_newpolygon(conf, pol, method = reduce.polygon) } plot(res1, res2, xlim=range.x, ylim=range.y, type="n", xlab=xlab, ylab=ylab, main=main, axes=axes., bty=bty., ...) col.polygon <- "lightgray" if(superpose.points) { points(res1, res2, col="lightgray", pch=16) col.polygon <- NA } polygon(pol, col=col.polygon, lty=2) points(res.original1, res.original2, pch=pch, cex=cex, ...) if(add.dplots) { add_dplots_plot(range.x, range.y, xlab., ylab., d1, d2, cc1, c2, startd1, startd2, res1, res2, res.original1, res.original2, d1.or, d2.or, transparent.colors) } return(invisible()) } if(kernel) { plot(res1, res2, xlim=range.x, ylim=range.y, type="n", xlab=xlab, ylab=ylab, main=main, axes=axes., bty=bty., ...) post1 <- kde2d(res1, res2, n=100, h = c(width.SJ(res1), width.SJ(res2)), lims=c(range(res1)*1.2, range(res2)*1.2)) dx <- diff(post1$x[1:2]) dy <- diff(post1$y[1:2]) sz <- sort(post1$z) c1 <- cumsum(sz)*dx*dy level <- approx(c1, sz, xout=1-conf)$y ckern <- contourLines(post1$x, post1$y, post1$z, levels=level) col.polygon <- "lightgray" if(superpose.points) { points(res1, res2, col="lightgray", pch=16) col.polygon <- NA } for(i in 1:length(ckern)) polygon(ckern[[i]]$x, ckern[[i]]$y, col=col.polygon, lty=2) points(res.original1, res.original2, pch=pch, cex=cex, ...) if(add.dplots) { add_dplots_plot(range.x, range.y, xlab., ylab., d1, d2, cc1, c2, startd1, startd2, res1, res2, res.original1, res.original2, d1.or, d2.or, transparent.colors) } } } }
pool_propdiff_nw <- function(object, conf.level=0.95) { if(all(class(object)!="mistats")) stop("object must be of class 'mistats'") if(!is.list(object$statistics)) stop("object must be a list") obj1 <- lapply(object$statistics, function(x) x[, c("prop1", "se1", "n1")]) obj0 <- lapply(object$statistics, function(x) x[, c("prop0", "se0", "n0")]) obj1 <- list(statistics=obj1) obj0 <- list(statistics=obj0) class(obj0) <- class(obj1) <- 'mistats' p0_pool <- pool_prop_wilson(obj0, conf.level=conf.level) p1_pool <- pool_prop_wilson(obj1, conf.level=conf.level) w0 <- p0_pool[-1] w1 <- p1_pool[-1] l0 <- w0[1] u0 <- w0[2] l1 <- w1[1] u1 <- w1[2] phat0 <- p0_pool[1] phat1 <- p1_pool[1] prop_diff <- phat1 - phat0 lower <- prop_diff - sqrt((phat1-l1)^2 + (u0-phat0)^2) upper <- prop_diff + sqrt((phat0-l0)^2 + (u1-phat1)^2) output <- round(matrix(c(prop_diff, lower, upper), 1, 3), 4) colnames(output) <- c("Prop diff", "CI L NW", "CI U NW") class(output) <- "mipool" return(output) }
get_importance_local <- function(model){ model$importance$local }
verbose=TRUE require(haplo.stats) source("dump.varx.s") if(verbose) cat("setting up data...\n") if(verbose) cat("test matrix (441x441) that causes error in LINPACK, but not LAPACK svd\n") ginv.varx <- Ginv(varx) ginv.varx.eps <- Ginv(varx, eps=1e-4) if(verbose) cat("the zero matrix should give ginv=0, rank=0\n") zeroMat <- matrix(0) epsMat <- matrix(1e-7) zeroGinv <- Ginv(zeroMat) epsGinv <- Ginv(epsMat) print(ginv.varx$Ginv[1:5,1:5]) ginv.varx$rank print(ginv.varx.eps$Ginv[1:5,1:5]) ginv.varx.eps$rank print(zeroGinv) print(epsGinv)
NULL anova.spsur <- function(object, ..., lrtest = TRUE) { object <- list(object, ...) ancall <- sys.call() nmodels <- length(object) vtypes <- character(length = nmodels) vLL <- vdf <- vector(mode = "numeric", length=nmodels) vAIC <- vBIC <- vector(mode = "numeric", length=nmodels) if (lrtest) { vlrtest <- vpval <- vector(mode = "numeric", length=nmodels) vlrtest[1] <- vpval[1] <- NA } for (i in 1:nmodels) { obj_i <- object[[i]] if (!inherits(obj_i, "spsur")) stop("object not a fitted spsur model") if (is.null(obj_i$LL)) stop("object not fitted by maximum likelihood") LL <- logLik(obj_i) vAIC[i] <- stats::AIC(LL) vBIC[i] <- stats::BIC(LL) vLL[i] <- LL vdf[i] <- attr(LL, "df") vtypes[i] <- paste("model ",i,": ",obj_i$type, sep="") if (lrtest) { if(i>1) { vlrtest[i] <- 2*(vLL[i] - vLL[i-1]) vpval[i] <- pchisq(vlrtest[i], df = vdf[i] - vdf[i-1], lower.tail = FALSE) } } } if (lrtest) { res <- data.frame(logLik = vLL, df = vdf, AIC = vAIC, BIC = vBIC, LRtest = vlrtest, `p-val` = vpval, row.names = vtypes) } else { res <- data.frame(`logLik` = vLL, df = vdf, AIC = vAIC, BIC = vBIC, row.names = vtypes) } class(res) <- c("anova", "data.frame") return(res) } coef.spsur <- function(object, ...) { ret <- NULL if (!(object$type == "sim" || object$type == "slx")) ret <- c(ret, object$deltas) ret <- c(ret, object$coefficients) ret } fitted.spsur <- function(object, ...) { if (is.null(object$na.action)) fits <- object$fitted.values else fits <- napredict(object$na.action, object$fitted.values) G <- object$G if (!(length(fits) %% G == 0)) stop("Length of fitted values incompatible with number of equations") N <- length(fits) %/% G res <- vector("list", G) indx <- 1 for (i in 1:G) { res[[i]] <- fits[indx:(indx + N - 1)] indx <- indx + N } names(res) <- paste0("fitted_values_eq",1:G) res } logLik.spsur <- function(object, ...) { LL <- c(object$LL) class(LL) <- "logLik" N <- length(residuals(object)) attr(LL, "nall") <- N attr(LL, "nobs") <- N attr(LL, "df") <- object$parameters LL } residuals.spsur <- function(object, ...) { if (is.null(object$na.action)) resids <- object$residuals else resids <- napredict(object$na.action, object$residuals) G <- object$G if (!(length(resids) %% G == 0)) stop("Length of residuals incompatible with number of equations") N <- length(resids) %/% G res <- vector("list", G) indx <- 1 for (i in 1:G) { res[[i]] <- resids[indx:(indx + N - 1)] indx <- indx + N } names(res) <- paste0("residuals_eq",1:G) res } vcov.spsur <- function(object, ...) { res <- object$resvar idxsigma <- grepl("sigma", rownames(res)) res <- res[!idxsigma, !idxsigma] res } print.spsur <- function(x, digits = max(3L, getOption("digits") - 3L), ...) { if (!inherits(x, "spsur")) stop("Argument must be a spsur object") summx <- summary(x) fulltable <- summx$coef_table G <- length(fulltable) fullrownames <- NULL for (i in 1:G) { rownames_i <- rownames(fulltable[[i]]) rownames_i <- gsub(paste("_",i,sep=""), "", rownames_i) newrownames <- which (!(rownames_i %in% fullrownames)) rownames_i <- rownames_i[newrownames] fullrownames <- c(fullrownames, rownames_i) } mtable <- matrix(NA, nrow = length(fullrownames), ncol = 2*G) rownames(mtable) <- fullrownames colnames(mtable) <- paste(rep(c("coeff_","pval_"), G), rep(1:G, each = 2), sep="") idxcol <- 1 for (i in 1:G) { table_i <- fulltable[[i]][,c("Estimate", "Pr(>|t|)")] table_i[, 2] <- round(table_i[, 2], digits = min(digits, 3)) rownames(table_i) <- gsub(paste("_",i,sep=""), "", rownames(table_i)) mtable[rownames(table_i), c(idxcol,idxcol+1)] <- table_i idxcol <- idxcol + 2 } if (any(grepl("rho",rownames(mtable)))) { idxrowrho <- which(grepl("rho", rownames(mtable))) rowrho <- matrix(mtable[idxrowrho, ], nrow=1) rownames(rowrho) <- c("rho") mtable <- mtable[-idxrowrho, ] mtable <- rbind(mtable, rowrho) } if (any(grepl("lambda",rownames(mtable)))) { idxrowlambda <- which(grepl("lambda", rownames(mtable))) rowlambda <- matrix(mtable[idxrowlambda, ], nrow=1) rownames(rowlambda) <- c("lambda") mtable <- mtable[-idxrowlambda, ] mtable <- rbind(mtable, rowlambda) } print(round(mtable, digits = digits)) invisible(x) } plot.spsur <- function(x, ci = 0.95, viewplot = TRUE, ...) { if (!inherits(x, "spsur")) stop("Argument must be a spsur object") critval <- qnorm((1-ci)/2, lower.tail = FALSE) G <- x$G p <- x$p eq <- NULL for (i in 1:G) { eq <- c(eq, rep(i,p[i])) } eq <- as.factor(eq) dfx <- data.frame(eq = eq, nbetas = names(x$coefficients), betas = x$coefficients, sebetas = x$rest.se, lwbetas = x$coefficients - critval*x$rest.se, upbetas = x$coefficients + critval*x$rest.se, row.names = NULL) lplbetas <- vector("list", G) for (i in 1:G) { plbetasi <- ggplot2::ggplot(dfx[dfx$eq==i, ], ggplot2::aes(.data$nbetas, .data$betas, colour = i)) + ggplot2::geom_pointrange(ggplot2::aes(ymin = .data$lwbetas, ymax = .data$upbetas), show.legend = FALSE) + ggplot2::labs(title = paste("Equation ",i), x = "", y = "betas") lplbetas[[i]] <- plbetasi if (viewplot) { gridExtra::grid.arrange(lplbetas[[i]], newpage = TRUE) readline(prompt="Press [enter] to continue") } } if(!is.null(x$deltas)) { eq <- rep(0, length(x$deltas)) for (i in 1:G) { ni <- i*as.integer(grepl(paste("_", i, sep=""), names(x$deltas))) eq <- eq + ni } eq <- as.factor(eq) dfxsp <- data.frame(eq = eq, ndeltas = names(x$deltas), deltas = x$deltas, sedeltas = x$deltas.se, lwdeltas = x$deltas - critval*x$deltas.se, updeltas = x$deltas + critval*x$deltas.se, row.names = NULL) pldeltas <- ggplot2::ggplot(dfxsp, ggplot2::aes(.data$ndeltas, .data$deltas, colour = eq)) + ggplot2::geom_pointrange(ggplot2::aes(ymin = .data$lwdeltas, ymax = .data$updeltas), show.legend = FALSE) + ggplot2::labs(title = "", x = "", y = "Spatial Coefficients") if (viewplot) gridExtra::grid.arrange(pldeltas, nrow = 1) } else pldeltas <- NULL plots <- list(lplbetas = lplbetas, pldeltas = pldeltas) }
require("fftwtools") require("pracma") require("data.table") require("gstat") require(sp) require("stringr") require(gridExtra) require(moments) require(ggplot2) require(png) require(grid) if(getRversion() >= "3.1.0") utils::suppressForeignCheck(c("h", "..density..")) AFMImageAnalyser<-setClass("AFMImageAnalyser", slots = c( versions="data.table", AFMImage="AFMImage", variogramAnalysis="AFMImageVariogramAnalysis", psdAnalysis="AFMImagePSDAnalysis", fdAnalysis="AFMImageFractalDimensionsAnalysis", gaussianMixAnalysis="AFMImageGaussianMixAnalysis", networksAnalysis="AFMImageNetworksAnalysis", threeDimensionAnalysis="AFMImage3DModelAnalysis", mean="numeric", variance="numeric", TotalRrms="numeric", Ra="numeric", fullfilename="character", updateProgress="function")) setMethod("initialize", "AFMImageAnalyser", function(.Object, AFMImage, variogramAnalysis, psdAnalysis, fdAnalysis, gaussianMixAnalysis, networksAnalysis, threeDimensionAnalysis, mean, variance, TotalRrms, Ra, fullfilename) { if (!missing(AFMImage)) .Object@AFMImage<-AFMImage if (!missing(variogramAnalysis)) .Object@variogramAnalysis<-variogramAnalysis if (!missing(psdAnalysis)) .Object@psdAnalysis<-psdAnalysis if (!missing(fdAnalysis)) .Object@fdAnalysis<-fdAnalysis if (!missing(gaussianMixAnalysis)) .Object@gaussianMixAnalysis<-gaussianMixAnalysis if (!missing(networksAnalysis)) .Object@networksAnalysis<-networksAnalysis if (!missing(threeDimensionAnalysis)) .Object@threeDimensionAnalysis<-threeDimensionAnalysis if (!missing(mean)) .Object@mean<-mean if (!missing(variance)) .Object@variance<-variance if (!missing(TotalRrms)) .Object@TotalRrms<- TotalRrms if (!missing(Ra)) .Object@Ra<-Ra .Object@fullfilename<-fullfilename .Object@versions<-getLibrariesVersions() validObject(.Object) return(.Object) }) AFMImageAnalyser <- function(AFMImage) { return(new("AFMImageAnalyser", AFMImage= AFMImage, fullfilename= AFMImage@fullfilename)) } analyse<-function(AFMImageAnalyser) { AFMImage<-AFMImageAnalyser@AFMImage sampleFitPercentage<-3.43/100 variogramAnalysis<-AFMImageVariogramAnalysis(sampleFitPercentage) variogramAnalysis@omnidirectionalVariogram<- calculateOmnidirectionalVariogram(AFMImageVariogramAnalysis= variogramAnalysis, AFMImage=AFMImage) variogramAnalysis@directionalVariograms<- calculateDirectionalVariograms(AFMImageVariogramAnalysis= variogramAnalysis, AFMImage=AFMImage) AFMImageVariogram<-variogramAnalysis@omnidirectionalVariogram class(AFMImageVariogram)=c("gstatVariogram","data.frame") variogramAnalysis<-evaluateVariogramModels(variogramAnalysis, AFMImage) psdAnalysis<-AFMImagePSDAnalysis() roughnessAgainstLengthscale(psdAnalysis)<-RoughnessByLengthScale(AFMImage, psdAnalysis) AFMImageAnalyser@psdAnalysis<-psdAnalysis tryCatch({ intersection <- getAutoIntersectionForRoughnessAgainstLengthscale(AFMImageAnalyser, second_slope= FALSE) intersections<-c(intersection) intersection <- getAutoIntersectionForRoughnessAgainstLengthscale(AFMImageAnalyser, second_slope= TRUE) AFMImagePSDSlopesAnalysis<-intersection intersections<-c(intersections,intersection) intersections(psdAnalysis)<-intersections psdAnalysis@AFMImagePSDSlopesAnalysis<-AFMImagePSDSlopesAnalysis }, error = function(e) {print(paste("Impossible to find PSD intersections automaticaly",e))}) fdAnalysis<-AFMImageFractalDimensionsAnalysis() fractalDimensionMethods(fdAnalysis)<-getFractalDimensions(AFMImage, fdAnalysis) AFMImageAnalyser@mean=mean(AFMImage@data$h) AFMImageAnalyser@variance=var(AFMImage@data$h) AFMImageAnalyser@TotalRrms=sqrt(var(AFMImage@data$h)) AFMImageAnalyser@Ra=mean(abs(AFMImage@data$h)) AFMImageAnalyser@variogramAnalysis<-variogramAnalysis AFMImageAnalyser@psdAnalysis<-psdAnalysis AFMImageAnalyser@fdAnalysis<-fdAnalysis return(AFMImageAnalyser) } setGeneric(name= "putAnalysisOnDisk", def= function(AFMImageAnalyser, AFMImage) { return(standardGeneric("putAnalysisOnDisk")) }) setMethod(f="putAnalysisOnDisk", "AFMImageAnalyser", definition= function(AFMImageAnalyser, AFMImage) { filename<-basename(AFMImage@fullfilename) exportDirectory<-paste(dirname(AFMImage@fullfilename), "outputs", sep="/") saveAFMImageAnalyser(AFMImageAnalyser, AFMImage, exportDirectory) saveOnDisk(AFMImage, exportDirectory) }) setGeneric(name= "saveAFMImageAnalyser", def= function(AFMImageAnalyser, AFMImage, exportDirectory) { return(standardGeneric("saveAFMImageAnalyser")) }) setMethod(f="saveAFMImageAnalyser", "AFMImageAnalyser", definition= function(AFMImageAnalyser, AFMImage, exportDirectory) { filename<-basename(AFMImage@fullfilename) exportCsvFilename<-paste(filename,"AFMImageAnalyser.rda", sep="-") exportCsvFullFilename<-paste(exportDirectory, exportCsvFilename, sep="/") print(paste("saving", basename(exportCsvFullFilename))) tryCatch({ newVariableName=paste(filename,"AFMImageAnalyser.rda", sep="-") assign(newVariableName, AFMImageAnalyser) save(list=c(newVariableName), file=exportCsvFullFilename) }, error = function(e) {print("error",e)}) }) totalRMSRoughness<-function(AFMImage) { sqrt(var(AFMImage@data$h)) } setGeneric(name= "getRoughnessParameters", def= function(AFMImage) { return(standardGeneric("getRoughnessParameters")) }) setMethod(f="getRoughnessParameters", "AFMImage", definition= function(AFMImage) { area=AFMImage@hscansize*AFMImage@vscansize surfaceArea<- surfaceArea(matrix(AFMImage@data$h,nrow = AFMImage@lines,ncol = AFMImage@samplesperline), cellx = AFMImage@hscansize/AFMImage@samplesperline, celly = AFMImage@vscansize/AFMImage@lines, byCell = FALSE) totalRMSRoughness_TotalRrms = sqrt(var(AFMImage@data$h)) MeanRoughness_Ra = mean(abs(AFMImage@data$h)) return(data.table(totalRMSRoughness_TotalRrms, MeanRoughness_Ra, area, surfaceArea)) }) checkIsotropy<-function(AFMImage, AFMImageAnalyser) { print("checking isotropy...") sampleFitPercentage<-3.43/100 variogramAnalysis<-AFMImageVariogramAnalysis(sampleFitPercentage) if(!is.null(AFMImageAnalyser@updateProgress)) variogramAnalysis@updateProgress<-AFMImageAnalyser@updateProgress variogramAnalysis@directionalVariograms<- calculateDirectionalVariograms(AFMImage=AFMImage, AFMImageVariogramAnalysis=variogramAnalysis) AFMImageAnalyser@variogramAnalysis<-variogramAnalysis print("done.") return(AFMImageAnalyser) } checkNormality<- function(..., AFMImage) { force(AFMImage) fullfilename<-AFMImage@fullfilename args<-names(list(...)) toPng<-c(match('pngfullfilename',args)!=-1) toPdf<-c(match('pdffullfilename',args)!=-1) qq <- checkNormalityQQ(AFMImage) m <- checkNormalityDensity(AFMImage) toFile<-FALSE if (!is.na(toPng)) { reportName<-paste(fullfilename, "-normality-checks",".png",sep="") print(paste("saving", basename(reportName))) png(reportName, width=1280, height=800, res=200) toFile<-TRUE } if (!is.na(toPdf)) { reportName<-paste(fullfilename, "-normality-checks",".pdf",sep="") print(paste("saving", basename(reportName))) pdf(reportName, width=11.69, height=8.27) toFile<-TRUE } if (toFile) { title<- paste("Normality tests for ",basename(fullfilename)) }else{ title<-"Normality tests" } grid.newpage() pushViewport(viewport(layout = grid.layout(3, 2, heights = unit(c(0.5, 5, 0.5), "null")))) print(qq, vp = viewport(layout.pos.row = 2, layout.pos.col = 1)) print(m, vp = viewport(layout.pos.row = 2, layout.pos.col = 2)) grid.text(title, vp = viewport(layout.pos.row = 1, layout.pos.col = 1:2)) other<-paste("mean=", mean(AFMImage@data$h), "- skewness=", moments::skewness(AFMImage@data$h)) grid.text(other, vp = viewport(layout.pos.row = 3, layout.pos.col = 1:2)) if (toFile) { dev.off() } } checkNormalityQQ<- function(AFMImage) { h<-NULL ggplot(data=AFMImage@data, mapping=aes(sample=h)) + stat_qq() + geom_abline(intercept = mean(AFMImage@data$h), slope = sd(AFMImage@data$h)) } checkNormalityDensity<- function(AFMImage) { h<-..density..<-NULL ggplot(AFMImage@data, aes(x=h)) + geom_histogram( aes(y=..density..), colour="black", fill="white") + stat_function(fun = dnorm, args = list(mean = mean(AFMImage@data$h), sd = sd(AFMImage@data$h))) } getLibrariesVersions<-function() { v<-data.table(installed.packages()) Package<-NULL AFMPackage<-v[Package=="AFM",] gstatPackage<-v[Package=="gstat",] fractaldimPackage<-v[Package=="fractaldim",] fftwtoolsPackage<-v[Package=="fftwtools",] versions=data.table(lib=c("AFM", "gstat", "fractaldim", "fftwtools"), version=c(AFMPackage[1,]$Version, gstatPackage[1,]$Version, fractaldimPackage[1,]$Version, fftwtoolsPackage[1,]$Version) ) return(versions) }