code
stringlengths
1
13.8M
mirtCluster <- function(spec, omp_threads, remove = FALSE, ...){ if(requireNamespace("parallel", quietly = TRUE)){ if(missing(spec)) spec <- parallel::detectCores() if(missing(omp_threads)) .mirtClusterEnv$omp_threads <- 1L if(remove){ if(is.null(.mirtClusterEnv$MIRTCLUSTER)){ message('There is no visible mirtCluster() definition') return(invisible()) } parallel::stopCluster(.mirtClusterEnv$MIRTCLUSTER) .mirtClusterEnv$MIRTCLUSTER <- NULL .mirtClusterEnv$ncores <- 1L .mirtClusterEnv$omp_threads <- 1L return(invisible()) } if(!is.null(.mirtClusterEnv$MIRTCLUSTER)){ message('mirtCluster() has already been defined') return(invisible()) } .mirtClusterEnv$MIRTCLUSTER <- parallel::makeCluster(spec, ...) .mirtClusterEnv$ncores <- length(.mirtClusterEnv$MIRTCLUSTER) mySapply(1L:.mirtClusterEnv$ncores*2L, function(x) invisible()) } return(invisible()) }
at2 <- function(x, ...) UseMethod("at2") at2.Container <- function(x, index, ...) { x$at2(index) } NULL at2.dict.table <- function(x, index, ...) { .assert_index_and_arg(x, index) .subset2(x, index) } NULL
context("test-sanitize") test_that("sanitize utility works", { expect_equal(sanitize("["), "\\[") expect_equal(sanitize("\\[|+$"), "\\\\\\[\\|\\+\\$") })
impute.MAR = function(dataSet.mvs, model.selector, method = "MLE"){ if (length(which(model.selector[[1]]==1)) == 0){ dataSet.imputed = dataSet.mvs } else{ dataSet.MCAR = dataSet.mvs[which(model.selector[[1]]==1),] switch(method, MLE = { dataSet.MCAR.imputed = impute.wrapper.MLE(dataSet.MCAR) }, SVD = { dataSet.MCAR.imputed = impute.wrapper.SVD(dataSet.MCAR, K = 2) }, KNN = { dataSet.MCAR.imputed = impute.wrapper.KNN(dataSet.MCAR, K = 15) } ) dataSet.imputed = dataSet.mvs dataSet.imputed[which(model.selector[[1]]==1),] = dataSet.MCAR.imputed } return(dataSet.imputed) }
perturbationRpca <- function (lambda, U, x, n, f = 1/n, center, sort = TRUE) { stopifnot(f >= 0 & f <= 1) q <- ncol(U) d <- length(x) stopifnot(length(lambda) == q) stopifnot(nrow(U) == d) if (!missing(center)) x <- x - center lambda <- (1-f) * lambda z <- sqrt(f) * crossprod(U,x) z2 <- z * z num <- tcrossprod(z) den <- matrix(lambda + z2, q, q, byrow = TRUE) - matrix(z2 + lambda^2, q, q) V <- num / den diag(V) <- 1 U <- U %*% V sigma2 <- .colSums(U * U, d, q) lambda <- (lambda + z2) * sigma2 U <- U * rep.int(1/sqrt(sigma2), rep.int(d,q)) if (sort) { ind <- order(lambda, decreasing = TRUE) if (!identical(ind, 1:q)) { lambda <- lambda[ind] U <- U[,ind] } } list(values = lambda, vectors = U) }
context("test-press.R") describe("press", { it("Adds parameters to output", { res <- press( x = 1, mark(1, max_iterations = 10) ) expect_equal(colnames(res), c("expression", "x", summary_cols, data_cols)) expect_equal(nrow(res), 1) res2 <- press( x = 1:3, mark(1, max_iterations = 10) ) expect_equal(colnames(res2), c("expression", "x", summary_cols, data_cols)) expect_equal(nrow(res2), 3) }) it("Outputs status message before evaluating each parameter", { expect_message(regexp = "Running with:\n.*x", res <- press( x = 1, mark(rep(1, x), max_iterations = 10) ) ) expect_equal(colnames(res), c("expression", "x", summary_cols, data_cols)) expect_equal(nrow(res), 1) msgs <- character() withCallingHandlers(message = function(e) msgs <<- append(msgs, conditionMessage(e)), res2 <- press( x = 1:3, mark(rep(1, x), max_iterations = 10) ) ) expect_true(grepl("Running with:\n.*x\n.*1\n.*2\n.*3\n", paste(msgs, collapse = ""))) expect_equal(colnames(res2), c("expression", "x", summary_cols, data_cols)) expect_equal(nrow(res2), 3) }) it("expands the grid if has named parameters", { res <- press( x = c(1, 2), y = c(1, 3), mark(list(x, y), max_iterations = 10) ) expect_equal(res$x, c(1, 2, 1, 2)) expect_equal(res$y, c(1, 1, 3, 3)) expect_equal(res$result[[1]], list(1, 1)) expect_equal(res$result[[2]], list(2, 1)) expect_equal(res$result[[3]], list(1, 3)) expect_equal(res$result[[4]], list(2, 3)) }) it("takes values as-is if given in .grid", { res <- press( .grid = data.frame(x = c(1, 2), y = c(1,3)), mark(list(x, y), max_iterations = 10) ) expect_equal(res$x, c(1, 2)) expect_equal(res$y, c(1, 3)) expect_equal(res$result[[1]], list(1, 1)) expect_equal(res$result[[2]], list(2, 3)) }) it("runs `setup` with the parameters evaluated", { x <- 1 res <- press( y = 2, { x <- y mark(x) }) expect_equal(res$result[[1]], 2) }) })
context("US States") require(sf) test_that("No date returns current states", { expect_identical(us_states(), USAboundaries::states_contemporary_lores) }) test_that("Dates outside the valid range have an error message", { expect_error(us_states("1780-02-03")) expect_error(us_states("2015-06-17")) }) test_that("Current states can be filtered", { expect_equal(nrow(us_states(states = c("Virginia", "Maryland"))), 2) }) test_that("Error message if no matches are found", { expect_error(us_states(states = "No place"), "No matches found") }) test_that("Historical states can be filtered", { expect_equal(nrow(us_states("1875-01-02", states = c("Virginia", "Maryland"))), 2) }) test_that("Correct resolution shapefiles are returned", { skip_if_not_installed("USAboundariesData") expect_identical(us_states(resolution = "low"), USAboundaries::states_contemporary_lores) expect_identical(us_states(resolution = "high"), USAboundariesData::states_contemporary_hires) })
loglikLOOCVVAR1 <- function(lambdas, Y, unbalanced=matrix(nrow=0, ncol=2), ...){ if (!is(Y, "array")){ stop("Input (Y) is of wrong class.") } if (length(dim(Y)) != 3){ stop("Input (Y) is of wrong dimensions: either covariate, time or sample dimension is missing.") } if (!is(lambdas, "numeric")){ stop("Input (lambdas) is of wrong class.") } if (length(lambdas) != 2){ stop("Input (lambdas) is of wrong length.") } if (any(is.na(lambdas))){ stop("Input (lambdas) is not a vector of non-negative numbers.") } if (any(lambdas < 0)){ stop("Input (lambdas) is not a vector of non-negative numbers.") } if (!is(unbalanced, "matrix")){ stop("Input (unbalanced) is of wrong class.") } if (ncol(unbalanced) != 2){ stop("Wrong dimensions of the matrix unbalanced.") } LOOscheme <- cbind(rep(2:dim(Y)[2], dim(Y)[3]), sort(rep(1:dim(Y)[3], dim(Y)[2]-1))) if (nrow(unbalanced) > 0){ LOO2unbalanced <- numeric() for (k in 1:nrow(unbalanced)){ LOO2unbalanced <- c(LOO2unbalanced, which(apply(LOOscheme, 1, function(Y, Z){ all(Y == Z) }, Z=unbalanced[k,]))) } LOOscheme <- LOOscheme[-LOO2unbalanced,] } loglik <- 0 for (k in 1:nrow(LOOscheme)){ VAR1hat <- ridgeVAR1(Y, lambdas[1], lambdas[2], unbalanced=rbind(unbalanced, LOOscheme[k,,drop=FALSE]), ...) loglik <- loglik + .armaVAR1_loglik_LOOCVinternal(Y[,LOOscheme[k,1] , LOOscheme[k,2]], Y[,LOOscheme[k,1]-1, LOOscheme[k,2]], VAR1hat$A, VAR1hat$P) } return(-loglik) }
"norm.proposal" <- function(m,n,sigma) { set <- function(sigma) { s <<- sigma } get <- function() { s } set <- function(sigma) { s <<- sigma } tune <- function(x,scale=1,eps=1.0E-6) { set(scale*pmax(apply(x,1:2,sd),eps)) } proposal <- function(mu) { matrix(rnorm(m*n,mu,s),m,n) } s <- sigma list(m=m, n=n, set=set, get=get, tune=tune, proposal=proposal) }
WavTransf1D <- function(P, order = 5, jmax, periodic = FALSE, metric = "Riemannian", ...) { n <- dim(P)[3] J <- log2(n) if (!isTRUE(all.equal(as.integer(J), J))) { stop(paste0("Input length is non-dyadic, please change length ", n, " to dyadic number.")) } if (!isTRUE(order %% 2 == 1)) { warning("Refinement order should be an odd integer, by default set to 5") order <- 5 } metric <- match.arg(metric, c("Riemannian", "logEuclidean", "Cholesky", "rootEuclidean", "Euclidean", "Riemannian-Rahman")) dots <- list(...) method <- (if(is.null(dots$method)) "fast" else dots$method) d <- dim(P)[1] L <- (order - 1) / 2 L_round <- 2 * ceiling(L / 2) N <- (2 * L + 1) * n Nj <- as.integer(ifelse(periodic & (order > 1), N, n) / (2^(0:J))) Mper <- wavPyr_C(P, ifelse(periodic & (order > 1), L, 0), J, Nj, ifelse(metric == "Riemannian-Rahman", "Riemannian", metric)) M <- list() M[[1]] <- Mper[, , sum(head(Nj, J)) + 1:Nj[J + 1], drop = FALSE] for(j in 1:J) { if(periodic & (order > 1)) { M[[j + 1]] <- Mper[, , ifelse(j < J, sum(Nj[1:(J - j)]), 0) + L * 2^j - L_round + 1:(2^j + 2 * L_round), drop = FALSE] } else { M[[j + 1]] <- Mper[, , ifelse(j < J, sum(Nj[1:(J - j)]), 0) + 1:2^j, drop = FALSE] } } D <- Dw <- list() if (missing(jmax)) { jmax <- J - 1 } if (jmax > J - 1) { warning(paste0("'jmax' cannot exceed maximum scale j = ", J - 1)) jmax <- J - 1 } for (j in 0:jmax) { n_M <- dim(M[[j + 1]])[3] L1 <- ifelse(order > n_M, floor((n_M - 1) / 2), L) tm1 <- impute_C(M[[j + 1]], W_1D[[min(L1 + 1, 5)]], L1, FALSE, metric, method)[, , 2 * (1:n_M), drop = FALSE] tM <- (if(periodic){ tm1[, , L_round / 2 + ifelse(j > 0 | L %% 2 == 0, 0, -1) + 1:(2^j + L_round), drop = FALSE] } else tm1) n_W <- dim(tM)[3] W <- wavCoeff_C(tM, M[[j + 2]][, , 2 * (1:n_W), drop = FALSE], j, ifelse(metric == "Riemannian-Rahman", "Riemannian", metric)) Dw[[j + 1]] <- W[, , 1:n_W, drop = FALSE] D[[j + 1]] <- W[, , n_W + 1:n_W, drop = FALSE] names(D)[j + 1] <- names(Dw)[j + 1] <- paste0("D.scale", j) } return(list(D = D, D.white = Dw, M0 = M[[1]])) } WavTransf2D <- function(P, order = c(3, 3), jmax, metric = "Riemannian", ...) { J1 <- log2(dim(P)[3]) J2 <- log2(dim(P)[4]) J <- max(J1, J2) J0_2D <- abs(J1 - J2) if (!isTRUE(all.equal(as.integer(J1), J1) & all.equal(as.integer(J2), J2))) { stop(paste0("Input length is non-dyadic, please change length ", dim(P)[3], " or ", dim(P)[4], " to dyadic number.")) } if (!isTRUE((order[1] %% 2 == 1) & (order[2] %% 2 == 1))) { warning("Refinement orders in both directions should be odd integers, by default set to c(3,3).") order <- c(3, 3) } if (!isTRUE((order[1] <= 9) & (order[2] <= 9))) { stop(paste0("Refinement orders in both directions should be smaller or equal to 9, please change ", order, " to be upper bounded by c(9, 9)." )) } metric <- match.arg(metric, c("Riemannian", "logEuclidean", "Cholesky", "rootEuclidean", "Euclidean")) dots <- list(...) method <- (if(is.null(dots$method)) "fast" else dots$method) L <- (order - 1) / 2 d <- dim(P)[1] if(metric == "logEuclidean" | metric == "Cholesky" | metric == "rootEuclidean") { P <- array(Ptransf2D_C(array(P, dim = c(d, d, dim(P)[3] * dim(P)[4])), FALSE, FALSE, metric), dim = dim(P)) } grid_n <- cbind(2^((J1:0)[1:(J + 1)]), 2^((J2:0)[1:(J + 1)])) grid_n[which(is.na(grid_n))] <- 0 M <- list() for (j in J:0) { if(j == J){ Mper <- array(c(P), dim = c(d, d, grid_n[1, 1] * grid_n[1, 2])) M[[j + 1]] <- P } else { Mper <- wavPyr2D_C(Mper, max(grid_n[J - j, 1], 1), max(grid_n[J - j, 2], 1), metric) M[[j + 1]] <- array(c(Mper), dim = c(d, d, max(grid_n[J + 1 - j, 1], 1), max(grid_n[J + 1 - j, 2], 1))) } } D <- Dw <- list() W <- lapply(1:length(W_2D), function(i) array(c(aperm(W_2D[[i]], c(3, 4, 1, 2))), dim = c(dim(W_2D[[i]])[3] * dim(W_2D[[i]])[4], 4))) if (missing(jmax)) { jmax <- J - 1 } if (jmax > J - 1) { warning(paste0("'jmax' cannot exceed maximum scale j = ", J - 1)) jmax <- J - 1 } for (j in 0:jmax) { if(grid_n[J + 1 - j, 1] < 1) { n_M <- dim(M[[j + 1]])[4] L1 <- ifelse(order[2] > n_M, floor((n_M - 1) / 2), L[2]) tm1 <- impute_C(array(M[[j + 1]][, , 1, ], dim = c(d, d, 2^j)), W_1D[[min(L1 + 1, 5)]], L1, TRUE, metric, method) W <- wavCoeff_C(tm1, M[[j + 2]][, , 1, ], J0_2D + j, metric) Dw[[j + 1]] <- array(W[, , 1:(2 * n_M)], dim = dim(M[[j + 2]])) D[[j + 1]] <- array(W[, , (2 * n_M) + 1:(2 * n_M)], dim = dim(M[[j + 2]])) } else if(grid_n[J + 1 - j, 2] < 1) { n_M <- dim(M[[j + 1]])[3] L1 <- ifelse(order[1] > n_M, floor((n_M - 1) / 2), L[1]) tm1 <- impute_C(array(M[[j + 1]][, , , 1], dim = c(d, d, 2^j)), W_1D[[min(L1 + 1, 5)]], L1, TRUE, metric, method) W <- wavCoeff_C(tm1, M[[j + 2]][, , , 1], J0_2D + j, metric) Dw[[j + 1]] <- array(W[, , 1:(2 * n_M)], dim = dim(M[[j + 2]])) D[[j + 1]] <- array(W[, , (2 * n_M) + 1:(2 * n_M)], dim = dim(M[[j + 2]])) } else { tm1 <- impute2D_R(M[[j + 1]], L, metric, method) n_tM <- dim(tm1)[3] * dim(tm1)[4] W <- wavCoeff_C(array(tm1, dim = c(d, d, n_tM)), array(M[[j + 2]], dim = c(d, d, n_tM)), 2 * j, metric) Dw[[j + 1]] <- array(W[, , 1:n_tM], dim = dim(M[[j + 2]])) D[[j + 1]] <- array(W[, , n_tM + 1:n_tM], dim = dim(M[[j + 2]])) } names(D)[j + 1] <- names(Dw)[j + 1] <- paste0("D.scale", j) } return(list(D = D, D.white = Dw, M0 = M[[1]])) }
plot.break_down_uncertainty <- function(x, ..., vcolors = DALEX::colors_breakdown_drwhy(), show_boxplots = TRUE, max_features = 10, max_vars = NULL) { if (!is.null(max_vars)) { max_features <- max_vars } variable <- contribution <- NULL df <- as.data.frame(x) df$variable <- reorder(df$variable, df$contribution, function(x) mean(abs(x))) vnames <- tail(levels(df$variable), max_features) df <- df[df$variable %in% vnames, ] pl <- ggplot(df, aes(x = variable, y = contribution)) if (any(df$B == 0)) { x_bars <- df[df$B == 0,] pl <- pl + geom_col(data = x_bars, aes(x = variable, y = contribution, fill = factor(sign(contribution)))) + scale_fill_manual(values = vcolors) } if (show_boxplots) { pl <- pl + geom_boxplot(coef = 100, fill = " } pl + facet_wrap(~label, ncol = 1) + coord_flip() + DALEX::theme_drwhy_vertical() + theme(legend.position = "none") + xlab("") }
test_that("posix offset is 1970-01-01 01:00:00 CET)", { Sys.setenv(TZ = 'CET') expect_equal(as.POSIXct(as.numeric(as.POSIXct("1975-12-16 03:46:00 CET")), origin = min(as.POSIXct(Sys.Date()), 0)), as.POSIXct("1975-12-16 03:46:00 CET")) }) test_that("util_interpret_limits works", { Sys.setenv(TZ = 'CET') meta <- prep_create_meta( VAR_NAMES = 1:26, DATA_TYPE = c(rep(DATA_TYPES$INTEGER, 13), rep(DATA_TYPES$FLOAT, 9), rep(DATA_TYPES$DATETIME, 4)), LABEL = LETTERS, MISSING_LIST = "" ) expect_error(util_interpret_limits(meta), regexp = "No column containing the term LIMIT") meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]] <- NA expect_warning(util_interpret_limits(meta), regexp = "HARD_LIMITS has no defined intervals and is omitted.") meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]] <- "xx" expect_warning(util_interpret_limits(meta), regexp = "Found invalid limits for .HARD_LIMITS.: .* will ignore these", perl = TRUE) meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]] <- NA meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][1] <- "[0; 10)" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][2] <- "[0;Inf)" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][3] <- "(0; 10)" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][4] <- "[0; 10]" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][5] <- "[-Inf; 0]" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][6] <- "(-Inf; Inf]" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][7] <- "(0.1; 13.324]" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][8] <- "(0.1; 13324.0]" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][23] <- "(2020-01-01 00:00:00 CET; Inf]" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][24] <- "(+Inf; 2019-09-09 00:00:00 CET]" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][25] <- "(2020-01-01 00:00:00 CET; ]" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][26] <- "(+Inf; ]" m2 <- util_interpret_limits(meta) a <- m2[, c("HARD_LIMIT_LOW", "HARD_LIMIT_UP", "INCL_HARD_LIMIT_LOW", "INCL_HARD_LIMIT_UP")] b <- dplyr::tribble( ~HARD_LIMIT_LOW, ~HARD_LIMIT_UP, ~INCL_HARD_LIMIT_LOW, ~INCL_HARD_LIMIT_UP, 0, 10, TRUE, FALSE, 0, Inf, TRUE, FALSE, 0, 10, FALSE, FALSE, 0, 10, TRUE, TRUE, -Inf, 0, TRUE, TRUE, -Inf, Inf, FALSE, TRUE, 0.1, 13.324, FALSE, TRUE, 0.1, 13324, FALSE, TRUE, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1577833200, Inf, FALSE, TRUE, Inf, 1567980000, FALSE, TRUE, 1577833200, NA, FALSE, TRUE, Inf, NA, FALSE, TRUE, ) expect_equivalent(a, b, tolerance = 1e-3) meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]] <- NA meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][1] <- "[0; 0-0)" meta[[WELL_KNOWN_META_VARIABLE_NAMES$HARD_LIMITS]][2] <- "[3-3;Inf)" expect_warning(m3 <- util_interpret_limits(meta), regexp = paste0("In util_interpret_limits: Damaged (lower|upper)", ".+HARD_LIMITS.+: .+(3-3|0-0).+ in .+[12].+"), all = TRUE, perl = TRUE ) })
print(si <- sessionInfo(), locale=FALSE) Sys.info() ' time make test-Large ' Sys.memGB <- function (kind = "MemTotal") { mm <- drop(read.dcf("/proc/meminfo", fields = kind)) if (any(is.na(mm))) { warning("Non-existing 'kind': ", names(mm)[is.na(mm)][1]) 0 } else if (!all(grepl(" kB$", mm))) { warning("Memory info ", dQuote(kind), " is not returned in 'kB' aka kiloBytes") 0 } else as.numeric(sub(" kB$", "", mm))/(1000 * 1024) } availableGB <- if(file.exists("/proc/meminfo")) { Sys.memGB("MemAvailable") } else { 0 } cat("Available (processor aka CPU) memory: ", round(availableGB, 1), "GB (Giga Bytes)\n") if(.Machine$sizeof.pointer < 8) { cat(".Machine :\n"); str(.Machine) cat("not a 64-bit system -- forget about these tests!\n") q("no") } if(availableGB > 11) local(withAutoprint({ tf <- tempfile(); file <- file(tf, "wb") txtLine <- c(rep(as.raw(32:127), 2^5), charToRaw("\n")) system.time({ for(i in 1:(2^15-1)) writeBin(rep_len(txtLine, 2^16), file) for(i in 1:(2^15-1)) writeBin(rep_len(as.raw(0L), 2^16), file) }) close(file) log2(file.size(tf)) "FIXME: on 32-bit Linux (F 24), still see Program received signal SIGSEGV, Segmentation fault. ... in do_readLines (call=0x8.., op=0x8.., ....) at ../../../R/src/main/connections.c:3852 3852 if(c != '\n') buf[nbuf++] = (char) c; else break; " if(.Machine$sizeof.pointer > 4) withAutoprint({ system.time( x <- readLines(tf) ) str(ncx <- nchar(x, "bytes")) tail(ncx) table(ncx) head(iL <- which(ncx == 4075)) stopifnot(diff(iL) == 21) }) else cat("32-bit: still seg.faulting - FIXME\n") })) if(availableGB > 21) system.time({ res <- c(a=raw(2), raw(2^31-1)) }) if(FALSE) { os <- object.size(res) } else { os <- structure(19327353184, class = "object_size") print(os, units = "GB") } if(exists("res")) rm(res) gc(reset = TRUE) if(availableGB > 37) system.time({ res <- c(a = list(rep(c(b=raw(1)), 2^31-2), raw(2)), recursive=TRUE) }) if(exists("res")) withAutoprint({ str(res) gc() rm(res) }) gc(reset = TRUE) if(availableGB > 4) system.time(local(withAutoprint({ txt <- strrep("test me:", 53687091); object.size(txt) nc <- nchar(txt) nc*5L+8L en <- encodeString(txt) stopifnot(identical(txt,en)) }))) if(availableGB > 6) system.time(withAutoprint({ r <- pretty(c(-1,1)*1e300, n = 449423288, min.n = 1) head(r) ; length(r) stopifnot(all.equal(length(r), 400000001, tol = 0.1)) })) rm(r) gc() n <- 4e4 n <- 2.2e9 if(availableGB > 60) withAutoprint({ n/.Machine$integer.max ii <- seq_len(n) system.time(ii <- ii + 0) system.time(i2 <- ii[-n]) }) if(availableGB > 99) withAutoprint({ system.time( x <- ii/n ) system.time( y <- sin(pi*x) ) system.time(sorted <- !is.unsorted(x)) stopifnot(sorted) system.time(ap1 <- approx(x,y, ties = "ordered")) stopifnot(exprs = { is.list(ap1) names(ap1) == c("x","y") length(ap1$x) == 50 all.equal(ap1$y, sin(pi*ap1$x), tol= 1e-9) }) rm(ap1) gc() }) if(availableGB > 165) withAutoprint({ system.time(iis <- which(isMl <- ii < 9999)) gc() system.time(r <- ifelse(isMl, ii, ii*1.125)) stopifnot(exprs = { length(r) == n iis == seq_len(9998) }) rm(isMl, iis, r) }) gc() if(availableGB > 211) withAutoprint({ system.time(xo <- x + 1/(2*n)) system.time(ap <- approx(x,y, ties = "ordered", xout = xo)) gc(reset = TRUE) stopifnot(exprs = { is.list(ap) names(ap) == c("x","y") length(ap$x) == n is.na(ap$y[n]) all.equal(ap$y[i2], sin(pi*xo[i2]), tol= if(n < 1e7) 1e-8 else 1e-15) }) rm(ap); gc() system.time(apf <- approxfun(x,y, ties="ordered", rule = 2)) xi <- seq(0, 1, by = 2^-12) stopifnot(all.equal(apf(xi), sin(pi*xi), tol= if(n < 1e7) 1e-7 else 1e-11)) rm(apf); gc() system.time(ssf <- splinefun(x,y, ties = "ordered")) system.time(ss <- spline (x,y, ties = "ordered", xout = xi)) gc() stopifnot(exprs = { is.list(ss) names(ss) == c("x","y") length(ss$y) == length(xi) all.equal(ss$y , sin(pi*xi), tol= 1e-15) all.equal(ssf(xi), ss$y, tol= 1e-15) }) rm(x, y, xo, ss, ssf) gc(reset=TRUE) }) if(availableGB > 24) withAutoprint({ system.time(L <- rep.int((0:15) %% 7 == 2, 2^28)) print(object.size(L), unit="GB") system.time(sL <- sum(L)) stopifnot(exprs = { is.logical(L) length(L) == 2^32 !is.integer(length(L)) is.integer(sL) identical(sL, as.integer(2^29)) }) }) gc(reset=TRUE) L <- as.integer(2^31 - 1) if(availableGB > 12) withAutoprint({ system.time(x31 <- rep.int(L, 2^31+1)) print(object.size(x31), unit = "GB") system.time(S <- sum(x31)) system.time(S.4 <- sum(x31, x31, x31, x31)) stopifnot(is.integer(x31), identical(S, 2^62), identical(S.4, 2^64)) system.time(x32 <- c(x31, x31)) rm(x31) system.time(S.2 <- sum(x32)) stopifnot(S.2 == 2^63) rm(x32) }) if(availableGB > 16) withAutoprint({ i <- as.integer(2^30) system.time(i2.31 <- seq(-i, by=1L, length=2*i+1)) object.size(i2.31) stopifnot(is.integer(i2.31), i2.31[1] == -i, i2.31[length(i2.31)] == i) if(availableGB > 24) withAutoprint({ system.time(i2.31 <- pmin(i2.31, 0L)) str(i2.31) system.time(stopifnot(i2.31[(i+1):length(i2.31)] == 0)) }) }) if(availableGB > 44) withAutoprint({ system.time(m <- match(rep("a", 2^31), "a")) stopifnot(all(m == 1L)) rm(m) system.time({x <- character(2^31); x[26:1] <- letters }) system.time(m <- match(x, "a")) head(m, 30) system.time(stopifnot(m[26] == 1L, is.na(m[-26]))) rm(x, m) }) if(availableGB > 14) withAutoprint({ vec <- rep(0, 3e8) raw_con <- rawConnection(serialize(vec, NULL)) repeat { x <- readBin(raw_con, "raw", n = 1e+06) if(length(x) == 0) break cat(".") }; cat("\n") }) if(availableGB > 20) withAutoprint({ x <- raw(2^31) writeBin(x, con = nullfile()) con <- rawConnection(raw(0L), "w") writeBin(x, con = con) stopifnot(identical(x, rawConnectionValue(con))) system.time(x <- pi*seq_len(2.1*2^30)) zzfil <- tempfile("test-large-bin") zz <- file(zzfil, "wb") system.time(z <- writeBin(x, zz)) stopifnot(is.null(z)) close(zz); zz <- file(zzfil, "rb") system.time(r <- readBin(zz, double(), n = length(x) + 999)) system.time(stopifnot(identical(x, r))) close(zz); rm(r, zz) }) mkDat <- function(n) { x <- 5*(1:n)/(n+1) data.frame(x = x, y = sin(pi*x^2) * exp(-x/2) + rnorm(n)/8) } set.seed(1); dat <- mkDat(n = 42000) system.time( fit <- loess(y~x, data=dat) ) r <- tools::assertError( predict(fit, newdata=data.frame(x=.5), se=TRUE) , verbose=TRUE) stopifnot(grepl("^workspace .* is too large .* 'se = TRUE'", r[[1]]$message)) (i <- 2^31) > .Machine$integer.max system.time(x <- raw(i)) x [i] <- r1 <- as.raw(1); stopifnot(x [i] == r1) x[[i]] <- r2 <- as.raw(2); stopifnot(x[[i]] == r2) x[[i]] <- r3 <- as.raw(3); stopifnot(x[[i]] == r3) stopifnot((n <- 2^31 + 352) > .Machine$integer.max) system.time(L <- integer(n)) system.time(LL <- vector("list", n)) system.time(nm <- c(LETTERS, letters, rep("xx", length(L) - 2*26))) Ln <- L system.time(names(Ln) <- nm) op <- options(max.print = 300) L Ln LL options(op) LL <- matrix(as.raw(1:2), 2, 2^30) ca.half <- 0.5+ (eps <- unique(sort(outer(2^-c(16, 21, 26, 30), -1:1)))) print(eps, digits=3) LL[cbind(2, ca.half)] LL[cbind(1, 1+ca.half)] LL[cbind(2+ca.half, 1)] LL[cbind(-ca.half, 1)] stopifnot(exprs = { length(LL[cbind(2, ca.half)]) == 0 LL[cbind(1, 1+ca.half)] == as.raw(1L) LL[cbind(2+ca.half, 1)] == as.raw(2L) length(LL[cbind( -ca.half, 1)]) == 0 }) gc() proc.time()
context("calc_summary_measures") samples <- data.frame(value = 1:10, type = "car") test_that("calc_summary_measures works as expected with default arguments", { expect_known_output(calc_summary_measures(samples), file = testthat::test_path("test-data/calc_summary_measures_default.rds")) }) test_that("calc_CrI works as expected when grouping", { expect_known_output(calc_summary_measures(samples, summarise_by = "type"), file = testthat::test_path("test-data/calc_summary_measures_grouping.rds")) }) test_that("calc_CrI works as expected when given a custom CrI list", { expect_known_output(calc_summary_measures(samples, CrIs = c(0.1, 0.4, 0.95)), file = testthat::test_path("test-data/calc_summary_measures_custom_CrI.rds")) })
cf <- check_that(women, height > 0, sd(weight) > 0) as.data.frame(cf) women$id <- letters[1:15] i <- indicator(mw = mean(weight), ratio = weight/height) as.data.frame(confront(women, i, key="id"))
Lixn <- function(traj1,traj2,method="spatial",tc=0,hr1,hr2,OZ=NULL){ output <- NULL trajs <- GetSimultaneous(traj1,traj2,tc) tr1 <- ld(trajs[1]) tr2 <- ld(trajs[2]) n <- nrow(tr1) pts1 <- SpatialPoints(tr1[,1:2]) pts2 <- SpatialPoints(tr2[,1:2]) if (method == 'spatial'){ if (gContains(hr1,hr2) == TRUE){output <- list(pTable=NA,nTable=NA,oTable=NA,Laa=NA,p.AA=NA,Lbb=NA,p.BB=NA,Lixn=NA,p.IXN="ContainsA")} else if (gContains(hr2,hr1) == TRUE){output <- list(pTable=NA,nTable=NA,oTable=NA,Laa=NA,p.AA=NA,Lbb=NA,p.BB=NA,Lixn=NA,p.IXN="ContainsB")} else { areaA <- gDifference(hr1,hr2) areaB <- gDifference(hr2,hr1) areaAB <- gIntersection(hr1,hr2) if (is.null(areaAB) == FALSE){ A1.int <- gCovers(areaA,pts1,byid=T) AB1.int <- gCovers(areaAB,pts1,byid=T) B2.int <- gCovers(areaB,pts2,byid=T) AB2.int <- gCovers(areaAB,pts2,byid=T) l.vec <- c(length(A1.int),length(B2.int),length(AB1.int),length(AB2.int)) if (diff(range(l.vec)) == 0){ n11 <- sum(AB1.int*AB2.int) n22 <- sum(A1.int*B2.int) n12 <- sum(A1.int*AB2.int) n21 <- sum(AB1.int*B2.int) } else {n11 <- 0; n12 <- 0; n21 <- 0; n22 <- 0} a <- gArea(hr1) b <- gArea(hr2) ab <- gArea(areaAB) p11 <- (ab^2)/(a*b) p12 <- (1 - (ab/a))*(ab/b) p21 <- (ab/a)*(1 - (ab/b)) p22 <- (1-(ab/a))*(1-(ab/b)) } else {output <- list(pTable=NA,nTable=NA,oTable=NA,Laa=NA,p.AA=NA,Lbb=NA,p.BB=NA,Lixn=NA,p.IXN=NA)} } } else if (method == 'frequency'){ areaAB <- OZ areaA <- gDifference(gBoundary(pts1),areaAB) areaB <- gDifference(gBoundary(pts2),areaAB) if (is.null(areaAB) == FALSE){ A1.int <- gCovers(areaA,pts1,byid=T) AB1.int <- gCovers(areaAB,pts1,byid=T) B2.int <- gCovers(areaB,pts2,byid=T) AB2.int <- gCovers(areaAB,pts2,byid=T) l.vec <- c(length(A1.int),length(B2.int),length(AB1.int),length(AB2.int)) if (diff(range(l.vec)) == 0){ n11 <- sum(AB1.int*AB2.int) n22 <- sum(A1.int*B2.int) n12 <- sum(A1.int*AB2.int) n21 <- sum(AB1.int*B2.int) } else {n11 <- 0; n12 <- 0; n21 <- 0; n22 <- 0} t1 <- ld(traj1) t2 <- ld(traj2) r <- nrow(t1) s <- nrow(t2) p1 <- SpatialPoints(t1[,1:2]) p2 <- SpatialPoints(t2[,1:2]) AB1.int <- gCovers(areaAB,p1,byid=T) AB2.int <- gCovers(areaAB,p2,byid=T) rAB <- length(which(AB1.int == T)) sAB <- length(which(AB2.int == T)) p11 <- (rAB*sAB)/(r*s) p12 <- (1 - (rAB/r))*(sAB/s) p21 <- (rAB/r)*(1-(sAB/s)) p22 <- (1 - (rAB/r))*(1 - (sAB/s)) } else {output <- list(pTable=NA,nTable=NA,oTable=NA,Laa=NA,p.AA=NA,Lbb=NA,p.BB=NA,Lixn=NA,p.IXN=NA)} } else {stop(paste("The method - ",method,", is not recognized. Please try again.",sep=""))} if (is.null(output)){ w <- (n11*n22)/(n12*n21) L <- log(w) se.L <- sqrt((1/n11) + (1/n12) + (1/n21) + (1/n22)) n.1 <- n11 + n21 n.2 <- n12 + n22 n1. <- n11 + n12 n2. <- n21 + n22 p.1 <- p11+p21 p.2 <- p12+p22 p1. <- p11+p12 p2. <- p21+p22 chi.tot <- (((n11-p11*n)^2)/p11*n) + (((n12-p12*n)^2)/p12*n) + (((n21-p21*n)^2)/(p21*n)) + (((n22-p22*n)^2)/(p22*n)) Laa <- log((p.2*n.1)/(p.1*n.2)) chiAA <- ((n.1-p.1*n)^2)/(p.2*p.1*n) Lbb <- log((p2.*n1.)/(p1.*n2.)) chiBB <- ((n1.-p1.*n)^2)/(p2.*p1.*n) Lixn <- log(((n11/p11)+(n22/p22))/((n12/p12)+(n21/p21))) chiIXN <- (((n11/p11) + (n22/p22) - (n12/p12) - (n21/p21))^2)/(n*((1/p11) + (1/p12) + (1/p21) + (1/p22))) o11 <- n11/(p11*n) o12 <- n12/(p12*n) o21 <- n21/(p21*n) o22 <- n22/(p22*n) p.AA <- 1 - pchisq(chiAA,df=1) p.BB <- 1 - pchisq(chiBB,df=1) p.IXN <- 1 - pchisq(chiIXN,df=1) pTable <- matrix(c(p11,p12,p21,p22),ncol=2,byrow=T,dimnames=list(c("B","b"),c("A","b"))) nTable <- matrix(c(n11,n12,n21,n22),ncol=2,byrow=T,dimnames=list(c("B","b"),c("A","b"))) oTable <- matrix(c(o11,o12,o21,o22),ncol=2,byrow=T,dimnames=list(c("B","b"),c("A","b"))) output <- list(pTable=pTable,nTable=nTable,oTable=oTable,Laa=Laa,p.AA=p.AA,Lbb=Lbb,p.BB=p.BB,Lixn=Lixn,p.IXN=p.IXN) } return(output) }
prsim.weather <- function(data_p, data_t, station_id_p="Precip",station_id_t="Temp", number_sim=1, win_h_length=15, n_wave=100,verbose=TRUE,t_margin='sep',p_margin='egpd',...){ fun_icwt<-function(x){ wt.r<-Re(x) J<-length(x[1,]) dial<-2*2^(0:J*.125) rec<-rep(NA,(length(x[,1]))) for(l in 1:(length(x[,1]))){ rec[l]<-0.2144548*sum(wt.r[l,]/sqrt(dial)[1:length(wt.r[l,])]) } return(rec) } p_margin <- p_margin[1] if (!(p_margin %in% c("egpd"))) { if (!is.character(p_margin)) stop("'p_margin' should be a character string.") rCDF_p <- get(paste0("r",p_margin), mode = "function") CDF_fit_p <- get(paste0(p_margin,"_fit"), mode = "function") } t_margin <- t_margin[1] if (!(t_margin %in% c("sep"))) { if (!is.character(t_margin)) stop("'p_margin' should be a character string.") rCDF_t <- get(paste0("r",t_margin), mode = "function") CDF_fit_t <- get(paste0(t_margin,"_fit"), mode = "function") } op <- options("warn")$warn for(l in 1:length(data_p)){ if (nrow(data_p[[l]])[1]<730) stop("At least one year of data required.") if (is.numeric(station_id_p)){ station_id_p <- colnames(data_p[[l]])[station_id_p] } if (is.na(station_id_p)||!("Precip" %in% colnames(data_p[[l]]))) stop("Wrong column (name) for observations selected.") if (any(class(data_p[[l]][,1])%in%c("POSIXct","POSIXt"))){ data <- data.frame(YYYY=as.integer(format(data_p[[l]][,1],'%Y')), MM=as.integer(format(data_p[[l]][,1],'%m')), DD=as.integer(format(data_p[[l]][,1],'%d')), Precip=data_p[[l]][,station_id_p], timestamp=data_p[[l]][,1]) } else { if(!all(c("YYYY","MM","DD") %in% colnames(data_p[[l]]))) stop("Wrong time column names") data_p[[l]] <- data_p[[l]][,c("YYYY","MM","DD", station_id_p)] tmp <- paste(data_p[[l]]$YYYY,data_p[[l]]$MM,data_p[[l]]$DD,sep=" ") names(data_p[[l]]) <- c("YYYY","MM","DD","Precip") data_p[[l]]$timestamp <- as.POSIXct(strptime(tmp, format="%Y %m %d", tz="GMT")) } if (nrow(data_t[[l]])[1]<730) stop("At least one year of data required.") if (is.numeric(station_id_t)){ station_id_t <- colnames(data_t[[l]])[station_id_t] } if (is.na(station_id_t)||!("Temp" %in% colnames(data_t[[l]]))) stop("Wrong column (name) for observations selected.") if (any(class(data_t[[l]][,1])%in%c("POSIXct","POSIXt"))){ data <- data.frame(YYYY=as.integer(format(data_t[[l]][,1],'%Y')), MM=as.integer(format(data_t[[l]][,1],'%m')), DD=as.integer(format(data_t[[l]][,1],'%d')), Temp=data_t[[l]][,station_id_t], timestamp=data_t[[l]][,1]) } else { if(!all(c("YYYY","MM","DD") %in% colnames(data_t[[l]]))) stop("Wrong time column names") data_t[[l]] <- data_t[[l]][,c("YYYY","MM","DD", station_id_t)] tmp <- paste(data_t[[l]]$YYYY,data_t[[l]]$MM,data_t[[l]]$DD,sep=" ") names(data_t[[l]]) <- c("YYYY","MM","DD","Temp") data_t[[l]]$timestamp <- as.POSIXct(strptime(tmp, format="%Y %m %d", tz="GMT")) } data_p[[l]] <- data_p[[l]][format(data_p[[l]]$timestamp, "%m %d") != "02 29",] data_t[[l]] <- data_t[[l]][format(data_t[[l]]$timestamp, "%m %d") != "02 29",] if(which(format(data_p[[l]]$timestamp,format='%j')=='001')[1]>1){ data_p[[l]] <- data_p[[l]][-c(1:(which(format(data_p[[l]]$timestamp,format='%j')=='001')[1]-1)),] } if ((nrow(data_p[[l]]) %% 365)>0) stop("No missing values allowed. Some days are missing.") if(which(format(data_t[[l]]$timestamp,format='%j')=='001')[1]>1){ data_t[[l]] <- data_t[[l]][-c(1:(which(format(data_t[[l]]$timestamp,format='%j')=='001')[1]-1)),] } if ((nrow(data_t[[l]]) %% 365)>0) stop("No missing values allowed. Some days are missing.") if(length(which(is.na(data_p[[l]]$timestamp)))>0){ data_p[[l]][which(is.na(data_p[[l]]$timestamp)),]$Precip <- mean(data_p[[l]]$Precip,na.rm=T) } if(length(which(is.na(data_t[[l]]$timestamp)))>0){ data_t[[l]][which(is.na(data_t[[l]]$timestamp)),]$Temp <- mean(data_p[[l]]$Temp,na.rm=T) } data_p[[l]]$index <- as.numeric(format(data_p[[l]]$timestamp,format='%j')) data_t[[l]]$index <- as.numeric(format(data_t[[l]]$timestamp,format='%j')) if(length(which(is.na(data_p[[l]]$index))>0)){ data_p[[l]]$index[which(is.na(data_p[[l]]$index))] <- rep(c(1:365), times=length(unique(data_p[[l]]$YYYY)))[which(is.na(data_p[[l]]$index))] } if(length(which(is.na(data_t[[l]]$index))>0)){ data_t[[l]]$index[which(is.na(data_t[[l]]$index))] <- rep(c(1:365), times=length(unique(data_t[[l]]$YYYY)))[which(is.na(data_t[[l]]$index))] } } if (verbose) cat(paste0("Detrending with (half-)length ",win_h_length,"...\n")) set.seed(10) noise_mat_r <- list() for (r in 1:number_sim){ station_rand <- sample(size=1,1:length(data_t)) years <- unique(data_t[[station_rand]]$YYYY) year_samp <- sample(years) data_samp <- data_t[[station_rand]][which(data_t[[station_rand]]$YYYY==year_samp[1]),] for(i in 2:length(year_samp)){ data_year <- data_t[[station_rand]][which(data_t[[station_rand]]$YYYY==year_samp[i]),] data_samp <- rbind(data_samp,data_year) } ts_wn <- data_samp$Temp scale.range = deltat(data_p[[l]]$Precip) * c(1, length(data_p[[l]]$Precip)) sampling.interval <- 0.1 octave <- logb(scale.range, 2) scale <- ifelse1(n_wave > 1, 2^c(octave[1] + seq(0, n_wave - 2) * diff(octave)/(floor(n_wave) - 1), octave[2]), scale.range[1]) scale <- unique(round(scale/sampling.interval) * sampling.interval) wt_morlet <- cwt_wst(signal=ts_wn,scales=scale,wname='MORLET',makefigure=FALSE,dt=1,powerscales=FALSE,wparam=5) noise_mat_r[[r]] <- as.matrix(wt_morlet$coefs) } p_fit <-p_val_p <- t_fit <- p_val_t<- rep(list(rep(list(NA),times=12)),times=length(data_p)) if(p_margin=='egpd'){ for(i in 1:length(data_p)){ for(m in 1:12){ pos_month <- as.numeric(data_p[[i]]$MM)%in%m data_month <- data_p[[i]]$Precip[which(as.numeric(data_p[[i]]$MM)==m)] data_month <- data_month[which(data_month>0)] p_fit[[i]][[m]] <- fit.extgp(data=data_month,method='pwm',init= c(0.9, 4,0.1),model=1) } } } if(p_margin!='egpd'){ for(i in 1:length(data_p)){ for(m in 1:12){ pos_month <- as.numeric(data_p[[i]]$MM)%in%m data_month <- data_p[[i]]$Precip[which(as.numeric(data_p[[i]]$MM)==m)] data_month <- data_month[which(data_month>0)] p_fit[[i]][[m]] <- CDF_fit_p(xdat=data_month,...) } } } if(t_margin=='sep'){ for(i in 1:length(data_p)){ for(m in 1:12){ data_month <- data_t[[i]]$Temp[which(as.numeric(data_t[[i]]$MM)==m)] l_moments <- lmoms(data_month) aep_par <- lmom2par(lmom=l_moments, type='aep4') t_fit[[i]][[m]] <- aep_par } } } if(t_margin!='sep'){ for(i in 1:length(data_t)){ for(m in 1:12){ pos_month <- as.numeric(data_t[[i]]$MM)%in%m data_month <- data_t[[i]]$Temp[which(as.numeric(data_t[[i]]$MM)==m)] data_month <- data_month[which(data_month>0)] t_fit[[i]][[m]] <- CDF_fit_t(xdat=data_month,...) } } } if(verbose) cat(paste0("Starting ",number_sim," simulations:\n")) out_list<-list() for(l in 1:length(data_p)){ data_sim_t <- data_sim_p <- list() for (r in c(1:number_sim)){ scale.range = deltat(data_p[[l]]$Precip) * c(1, length(data_p[[l]]$Precip)) sampling.interval <- 0.1 octave <- logb(scale.range, 2) scale <- ifelse1(n_wave > 1, 2^c(octave[1] + seq(0, n_wave - 2) * diff(octave)/(floor(n_wave) - 1), octave[2]), scale.range[1]) scale <- unique(round(scale/sampling.interval) * sampling.interval) wt_morlet_p <- cwt_wst(signal=data_p[[l]]$Precip,scales=scale,wname='MORLET', powerscales=FALSE,makefigure=FALSE,dt=1,wparam=5) wt_morlet_t <- cwt_wst(signal=data_t[[l]]$Temp,scales=scale,wname='MORLET', powerscales=FALSE,makefigure=FALSE,dt=1,wparam=5) morlet_mat_p <- as.matrix(wt_morlet_p$coefs) morlet_mat_t <- as.matrix(wt_morlet_t$coefs) modulus_p <- Mod(morlet_mat_p) modulus_t <- Mod(morlet_mat_t) phases_p <- Arg(morlet_mat_p) phases_t <- Arg(morlet_mat_t) noise_mat <- noise_mat_r[[r]] phases_random <- Arg(noise_mat) mat_new_p <- matrix(complex(modulus=modulus_p,argument=phases_random),ncol=ncol(phases_random)) mat_new_t <- matrix(complex(modulus=modulus_t,argument=phases_random),ncol=ncol(phases_random)) rec_orig_p = fun_icwt(x=morlet_mat_p)+mean(data_p[[l]]$Precip) rec_orig_t = fun_icwt(x=morlet_mat_t)+mean(data_t[[l]]$Temp) rec_p<- fun_icwt(x=mat_new_p) rec_t<- fun_icwt(x=mat_new_t) rec_random_p<-rec_p rec_random_t<-rec_t data_new <- data.frame("random_p"=rec_random_p,'random_t'=rec_random_t) data_new$MM <- data_p[[l]]$MM data_new$DD <- data_p[[l]]$DD data_new$YYYY <- data_p[[l]]$YYYY data_new$index <- data_p[[l]]$index data_new$seasonal_p <- data_new$random_p data_new$seasonal_t <- data_new$random_t data_new$rank_p <- rank(data_new$seasonal_p) data_new$rank_t <- rank(data_new$seasonal_t) d<-1 data_new$simulated_p <- NA data_new$simulated_t <- NA for(m in c(1:12)){ data_month <- data_t[[l]][which(as.numeric(data_t[[l]]$MM)%in%c(m)),] if(t_margin=='sep'){ sample <- rlmomco(n=length(data_month$Temp),t_fit[[l]][[m]]) } if(t_margin!='sep'){ sample <- rCDF_t(n=length(data_month$Temp),t_fit[[l]][[m]]) } ranks <- rank(sample,ties.method='first') data_new$rank_t[which(as.numeric(data_t[[l]]$MM)%in%c(m))] <- rank(round(data_new[which(as.numeric(data_t[[l]]$MM)%in%c(m)),]$seasonal_t),1) data_ordered <- sample[order(ranks)] data_new$simulated_t[which(as.numeric(data_t[[l]]$MM)%in%c(m))] <- data_ordered[data_new$rank_t[which(as.numeric(data_t[[l]]$MM)%in%c(m))]] } for(m in c(1:12)){ data_month <- data_p[[l]][which(as.numeric(data_p[[l]]$MM)%in%c(m)),] if(p_margin=='egpd'){ sample <- rextgp(n=length(which(data_month$Precip>0)),kappa=p_fit[[l]][[m]]$fit$pwm[1],sigma=p_fit[[l]][[m]]$fit$pwm[2], xi=p_fit[[l]][[m]]$fit$pwm[3]) } if(p_margin!='egpd'){ sample <- rCDF_t(n=length(data_month$Precip),p_fit[[l]][[m]]) } zeros <- rep(0,length(which(data_month$Precip==0))) outs <- c(sample,zeros) ranks <- rank(outs,ties.method='first') data_new$rank_p[which(as.numeric(data_p[[l]]$MM)%in%c(m))] <- rank(data_new[which(as.numeric(data_p[[l]]$MM)%in%c(m)),]$seasonal_p) data_ordered <- outs[order(ranks)] data_new$simulated_p[which(as.numeric(data_p[[l]]$MM)%in%c(m))] <- data_ordered[data_new$rank_p[which(as.numeric(data_p[[l]]$MM)%in%c(m))]] } data_sim_p[[r]] <- data_new$simulated_p data_sim_t[[r]] <- data_new$simulated_t if(verbose) cat(".") } if(verbose) cat("\nFinished.\n") data_sim_p <- as.data.frame(data_sim_p) names(data_sim_p) <- paste("r",seq(1:number_sim),sep="") data_stoch_p <- data.frame(data_p[[l]][,c("YYYY", "MM", "DD", "timestamp", "Precip")], data_sim_p) data_sim_t <- as.data.frame(data_sim_t) names(data_sim_t) <- paste("r",seq(1:number_sim),sep="") data_stoch_t <- data.frame(data_t[[l]][,c("YYYY", "MM", "DD", "timestamp", "Temp")], data_sim_t) out_list[[l]] <- list(data_stoch_t,data_stoch_p) } return(out_list) }
context("general justifier tests") testthat::test_that("reading a file with justifications works", { examplePath <- file.path(system.file(package="justifier"), 'extdata'); res <- justifier::load_justifications(file.path(examplePath, "example-minutes.jmd")); testthat::expect_equal(length(res$raw), 2); }); testthat::test_that("reading a directory with justifications works", { examplePath <- file.path(system.file(package="justifier"), 'extdata'); res <- load_justifications_dir(examplePath); testthat::expect_equal(length(res), 8); }); testthat::test_that("parsing justifications works", { examplePath <- file.path(system.file(package="justifier"), 'extdata'); res <- load_justifications(file.path(examplePath, "pp19.1-target-behavior-selection.jmd")); testthat::expect_equal(res$supplemented$decisions$ decision_to_select_behavior_1$ justification$justification_05$ assertion$assertion_nocturnal_2$ source$source_Lange$xdoi, "doi:10.1111/j.1749-6632.2009.05300.x"); testthat::expect_equal(res$supplemented$assertions$ assertion_sleep_memory_1$ source$source_Diekelmann$xdoi, "doi:10.1038/nrn2762"); testthat::expect_equal(res$supplemented$sources$ source_Diekelmann$ comment, "test of a comment"); }); testthat::test_that("parsing simplified, just extracted justifications from yum works", { examplePath <- file.path(system.file(package="justifier"), 'extdata'); res1 <- yum::load_and_simplify(file.path(examplePath, "pp19.1-target-behavior-selection.jmd")); res2 <- justifier::parse_justifications(res1); testthat::expect_equal(res2$supplemented$decisions$ decision_to_select_behavior_1$ justification$justification_05$ assertion$assertion_nocturnal_2$ source$source_Lange$xdoi, "doi:10.1111/j.1749-6632.2009.05300.x"); }); testthat::test_that("the intervention development justification from the vignette is parsed correctly", { exampleFile <- system.file("doc", "justifier-in-intervention-development.Rmd", package="justifier"); if (file.exists(exampleFile)) { res1 <- yum::load_and_simplify(exampleFile); res2 <- justifier::parse_justifications(res1); testthat::expect_equal(res2$supplemented$decisions$target_behavior_selection$type, "selection_target_behavior"); } }); testthat::test_that("odd objects provided to to_specList throw an error", { testthat::expect_error(justifier::to_specList(list(1:4))); }); testthat::test_that("reading the example study jmd file works", { examplePath <- file.path(system.file(package="justifier"), 'extdata'); res <- load_justifications(file=file.path(examplePath, "study-example.jmd")); testthat::expect_equal(length(res$raw), 6); });
context("ml classification - logistic regression") skip_databricks_connect() test_that("ml_logistic_regression() default params", { test_requires_latest_spark() sc <- testthat_spark_connection() test_default_args(sc, ml_logistic_regression) }) test_that("ml_logistic_regression() param setting", { test_requires_latest_spark() sc <- testthat_spark_connection() test_args <- list( fit_intercept = FALSE, elastic_net_param = 1e-4, reg_param = 1e-5, max_iter = 50, thresholds = c(0.3, 0.7), tol = 1e-04, weight_col = "wow", aggregation_depth = 3, features_col = "foo", label_col = "bar", family = "multinomial", prediction_col = "pppppp", probability_col = "apweiof", raw_prediction_col = "rparprpr" ) test_param_setting(sc, ml_logistic_regression, test_args) }) test_that("ml_logistic_regression.tbl_spark() works properly", { sc <- testthat_spark_connection() training <- tibble( id = 0:3L, text = c( "a b c d e spark", "b d", "spark f g h", "hadoop mapreduce" ), label = c(1, 0, 1, 0) ) test <- tibble( id = 4:7L, text = c("spark i j k", "l m n", "spark hadoop spark", "apache hadoop") ) training_tbl <- testthat_tbl("training") test_tbl <- testthat_tbl("test") pipeline <- ml_pipeline(sc) %>% ft_tokenizer("text", "words") %>% ft_hashing_tf("words", "features", num_features = 1000) %>% ml_logistic_regression(max_iter = 10, reg_param = 0.001) m1 <- pipeline %>% ml_fit(training_tbl) m1_predictions <- m1 %>% ml_transform(test_tbl) %>% pull(probability) m2 <- training_tbl %>% ft_tokenizer("text", "words") %>% ft_hashing_tf("words", "features", num_features = 1000) %>% ml_logistic_regression(max_iter = 10, reg_param = 0.001) m2_predictions <- m2 %>% ml_transform(test_tbl %>% ft_tokenizer("text", "words") %>% ft_hashing_tf("words", "features", num_features = 1000)) %>% pull(probability) expect_equal(m1_predictions, m2_predictions) }) test_that("ml_logistic_regression() agrees with stats::glm()", { sc <- testthat_spark_connection() set.seed(42) iris_weighted <- iris %>% mutate( weights = rpois(nrow(iris), 1) + 1, ones = rep(1, nrow(iris)), versicolor = ifelse(Species == "versicolor", 1L, 0L) ) iris_weighted_tbl <- testthat_tbl("iris_weighted") r <- glm(versicolor ~ Sepal.Width + Petal.Length + Petal.Width, family = binomial(logit), weights = weights, data = iris_weighted ) s <- ml_logistic_regression(iris_weighted_tbl, formula = "versicolor ~ Sepal_Width + Petal_Length + Petal_Width", reg_param = 0L, weight_col = "weights" ) expect_equal(unname(coef(r)), unname(coef(s)), tolerance = 1e-5, scale = 1) r <- glm(versicolor ~ Sepal.Width + Petal.Length + Petal.Width, family = binomial(logit), data = iris_weighted ) s <- ml_logistic_regression(iris_weighted_tbl, formula = "versicolor ~ Sepal_Width + Petal_Length + Petal_Width", reg_param = 0L, weight_col = "ones" ) expect_equal(unname(coef(r)), unname(coef(s)), tolerance = 1e-5, scale = 1) }) test_that("ml_logistic_regression can fit without intercept", { sc <- testthat_spark_connection() set.seed(42) iris_weighted <- iris %>% mutate( weights = rpois(nrow(iris), 1) + 1, ones = rep(1, nrow(iris)), versicolor = ifelse(Species == "versicolor", 1L, 0L) ) iris_weighted_tbl <- testthat_tbl("iris_weighted") expect_error(s <- ml_logistic_regression( iris_weighted_tbl, formula = versicolor ~ Sepal_Width + Petal_Length + Petal_Width, fit_intercept = FALSE ), NA) r <- glm(versicolor ~ Sepal.Width + Petal.Length + Petal.Width - 1, family = binomial(logit), data = iris_weighted) expect_equal(unname(coef(r)), unname(coef(s)), tolerance = 1e-5, scale = 1) }) test_that("ml_logistic_regression() agrees with stats::glm() for reversed categories", { sc <- testthat_spark_connection() set.seed(42) iris_weighted <- iris %>% mutate( weights = rpois(nrow(iris), 1) + 1, ones = rep(1, nrow(iris)), versicolor = ifelse(Species == "versicolor", 1L, 0L) ) iris_weighted_tbl <- testthat_tbl("iris_weighted") r <- glm(versicolor ~ Sepal.Width + Petal.Length + Petal.Width, family = binomial(logit), weights = weights, data = iris_weighted ) s <- ml_logistic_regression(iris_weighted_tbl, formula = "versicolor ~ Sepal_Width + Petal_Length + Petal_Width", reg_param = 0L, weight_col = "weights" ) expect_equal(unname(coef(r)), unname(coef(s)), tolerance = 1e-5, scale = 1) r <- glm(versicolor ~ Sepal.Width + Petal.Length + Petal.Width, family = binomial(logit), data = iris_weighted ) s <- ml_logistic_regression(iris_weighted_tbl, formula = "versicolor ~ Sepal_Width + Petal_Length + Petal_Width", reg_param = 0L, weight_col = "ones" ) expect_equal(unname(coef(r)), unname(coef(s)), tolerance = 1e-5, scale = 1) }) test_that("ml_logistic_regression.tbl_spark() takes both quoted and unquoted formulas", { sc <- testthat_spark_connection() iris_weighted_tbl <- testthat_tbl("iris_weighted") m1 <- ml_logistic_regression( iris_weighted_tbl, formula = "versicolor ~ Sepal_Width + Petal_Length + Petal_Width" ) m2 <- ml_logistic_regression( iris_weighted_tbl, formula = versicolor ~ Sepal_Width + Petal_Length + Petal_Width ) expect_identical(m1$formula, m2$formula) }) test_that("ml_logistic_regression.tbl_spark() takes 'response' and 'features' columns instead of formula for backwards compatibility", { sc <- testthat_spark_connection() iris_weighted_tbl <- testthat_tbl("iris_weighted") m1 <- ml_logistic_regression( iris_weighted_tbl, formula = "versicolor ~ Sepal_Width + Petal_Length + Petal_Width" ) m2 <- ml_logistic_regression( iris_weighted_tbl, response = "versicolor", features = c("Sepal_Width", "Petal_Length", "Petal_Width") ) expect_identical(m1$formula, m2$formula) }) test_that("ml_logistic_regression.tbl_spark() warns when 'response' is a formula and 'features' is specified", { sc <- testthat_spark_connection() iris_weighted_tbl <- testthat_tbl("iris_weighted") expect_warning( ml_logistic_regression(iris_weighted_tbl, response = versicolor ~ Sepal_Width + Petal_Length + Petal_Width, features = c("Sepal_Width", "Petal_Length", "Petal_Width") ), "'features' is ignored when a formula is specified" ) }) test_that("ml_logistic_regression.tbl_spark() errors if 'formula' is specified and either 'response' or 'features' is specified", { sc <- testthat_spark_connection() iris_weighted_tbl <- testthat_tbl("iris_weighted") expect_error( ml_logistic_regression(iris_weighted_tbl, "versicolor ~ Sepal_Width + Petal_Length + Petal_Width", response = "versicolor" ), "only one of 'formula' or 'response'-'features' should be specified" ) expect_error( ml_logistic_regression(iris_weighted_tbl, "versicolor ~ Sepal_Width + Petal_Length + Petal_Width", features = c("Sepal_Width", "Petal_Length", "Petal_Width") ), "only one of 'formula' or 'response'-'features' should be specified" ) }) test_that("we can fit multinomial models", { sc <- testthat_spark_connection() test_requires_version("2.1.0", "multinomial models not supported < 2.1.0") n <- 200 data <- data.frame( x = seq_len(n), y = rep.int(letters[1:4], times = n / 4) ) capture.output(r <- nnet::multinom(y ~ x, data = data)) tbl <- copy_to(sc, data, overwrite = TRUE) s <- ml_logistic_regression(tbl, y ~ x) train <- data.frame(x = sample(n)) rp <- predict(r, train) sp <- predict(s, copy_to(sc, train, overwrite = TRUE)) expect_equal(as.character(rp), as.character(sp)) }) test_that("weights column works for logistic regression", { sc <- testthat_spark_connection() set.seed(42) iris_weighted <- iris %>% mutate( weights = rpois(nrow(iris), 1) + 1, ones = rep(1, nrow(iris)), versicolor = ifelse(Species == "versicolor", 1L, 0L) ) iris_weighted_tbl <- testthat_tbl("iris_weighted") r <- glm(versicolor ~ Sepal.Width + Petal.Length + Petal.Width, family = binomial(logit), weights = weights, data = iris_weighted ) s <- ml_logistic_regression(iris_weighted_tbl, response = "versicolor", features = c("Sepal_Width", "Petal_Length", "Petal_Width"), reg_param = 0L, weight_col = "weights" ) expect_equal(unname(coef(r)), unname(coef(s)), tolerance = 1e-5, scale = 1) r <- glm(versicolor ~ Sepal.Width + Petal.Length + Petal.Width, family = binomial(logit), data = iris_weighted ) s <- ml_logistic_regression(iris_weighted_tbl, response = "versicolor", features = c("Sepal_Width", "Petal_Length", "Petal_Width"), reg_param = 0L, weight_col = "ones" ) expect_equal(unname(coef(r)), unname(coef(s)), tolerance = 1e-5, scale = 1) }) test_that("logistic regression bounds on coefficients", { sc <- testthat_spark_connection() test_requires_version("2.2.0", "coefficient bounds require 2.2+") iris_tbl <- testthat_tbl("iris") lr <- ml_logistic_regression( iris_tbl, Species ~ Petal_Width + Sepal_Length, upper_bounds_on_coefficients = matrix(rep(1, 6), nrow = 3), lower_bounds_on_coefficients = matrix(rep(-1, 6), nrow = 3), upper_bounds_on_intercepts = c(1, 1, 1), lower_bounds_on_intercepts = c(-1, -1, -1) ) expect_equal(max(coef(lr)), 1) expect_equal(min(coef(lr)), -1) })
strikes <- stats::ts(c(4737, 5117, 5091, 3468, 4320, 3825, 3673, 3694, 3708, 3333, 3367, 3614, 3362, 3655, 3963, 4405, 4595, 5045, 5700, 5716, 5138, 5010, 5353, 6074, 5031, 5648, 5506, 4230, 4827, 3885),start=1951,frequency=1)
intervalICC <- function(r1, r2, predefined.classes=FALSE, classes, c.limits, optim.method=1){ if(missing(r1) | missing(r2)) stop("Both r1 and r2 need to be specified") if(optim.method!=1 & optim.method!=2) stop("Misspecified optimization method: must be 1 or 2") if(predefined.classes){ if(missing(classes)) stop("Unspecified classes") if(missing(c.limits)) stop("Unspecified classes limits") if(!is.matrix(c.limits) & !is.data.frame(c.limits)) stop("Classes limits should be a matrix or a data frame") if(!is.vector(classes)) stop("Classes should be a vector") if(!is.vector(r1) | !is.vector(r2)) stop("r1 and r2 should be vectors") if(length(r1)!=length(r2)) stop("r1 and r2 should have equal lenghts") ratings <- as.data.frame(cbind(r1,r2)) c.limits <- as.data.frame(c.limits) if(ncol(c.limits)!=2) stop("Classes limits should be a matrix or a data frame with 2 columns") if(length(classes)!=nrow(c.limits)) stop("Number of classes differs from number of intervals given in c.limits") names(ratings) <- c("t1","t2") names(c.limits) <- c("lower","upper") if(!is.numeric(c.limits$lower) | !is.numeric(c.limits$upper)) stop("Classes limits must be numeric") if(any(is.na(classes))) stop("Missing values in classes") if(any(is.na(c.limits))) stop("Missing values in classes limits") if(any(is.na(ratings))){ warning("Missing values detected: data rows omitted from calculation") ratings <- na.omit(ratings) } ratings$t1 <- factor(ratings$t1, levels=classes) ratings$t2 <- factor(ratings$t2, levels=classes) if(any(is.na(ratings))) stop("Unrecognized class in r1 or r2") if(any(c.limits$lower >= c.limits$upper)) stop("Misspecified classes limits: lower bound equal to upper bound or greater detected") c.means <- rowMeans(c.limits) n.classes <- nrow(c.limits) n.resp <- nrow(ratings) t.means <- mat.or.vec(n.classes,n.classes) t.sd <- mat.or.vec(n.classes,n.classes) for(i in 1:n.classes){ for(j in i:n.classes){ t.means[i,j] <- 0.5*(c.means[i] + c.means[j]) t.means[j,i] <- t.means[i,j] t.sd[i,j] <- sqrt((c.means[i] - t.means[i,j])^2 + (c.means[j] - t.means[i,j])^2) t.sd[j,i] <- t.sd[i,j] } } t.r <- table(ratings$t1,ratings$t2) theta0 <- c(0,0, sum(t.means*t.r)/n.resp) theta0[1:2] <- c(max(sqrt(sum((t.means - theta0[3])^2*t.r)/(n.resp-1)),.Machine$double.eps+1e-10), max(sum(t.sd*t.r)/n.resp,.Machine$double.eps+1e-10)) if(optim.method==1){ est <- .intervalICC.est1(ratings,classes,c.limits,theta0) }else{ est <- .intervalICC.est2(ratings,classes,c.limits,theta0) } }else{ if( (!is.matrix(r1) & !is.data.frame(r1)) | (!is.matrix(r2) & !is.data.frame(r2)) ) stop("r1 and r2 should be matrices or data frames") if(ncol(r1)!=2 | ncol(r2)!=2) stop("r1 and r2 should be matrices or data frames with 2 columns") if(nrow(r1)!=nrow(r2)) stop("r1 and r2 should have equal number of rows") if(!is.numeric(r1[,1]) | !is.numeric(r1[,2]) | !is.numeric(r2[,1]) | !is.numeric(r2[,2])) stop("r1 and r2 should be numeric") if(any(r1[,1] >= r1[,2]) | any(r2[,1] >= r2[,2])) stop("Misspecified limits: lower bound equal to upper bound or greater detected") ratings <- cbind(r1,r2) if(any(is.na(ratings))){ warning("Missing values detected: data rows omitted from calculation") ratings <- na.omit(ratings) } r1 <- ratings[,1:2] r2 <- ratings[,3:4] ratings.num <- cbind(rowMeans(r1), rowMeans(r2)) theta0=c(max(sd(rowMeans(ratings.num)),.Machine$double.eps+1e-10), max(mean(apply(ratings.num,1,sd)),.Machine$double.eps+1e-10), mean(ratings.num)) if(optim.method==1){ est <- .intervalICC.est3(r1,r2,theta0) }else{ est <- .intervalICC.est4(r1,r2,theta0) } } class(est) <- "ICCfit" est }
mtcars nrow(mtcars) sample(x=1:32, size=.7 * 32) index = sample(x=1:nrow(mtcars), size=.7 * nrow(mtcars), replace=F) index train= mtcars[index,] test= mtcars[-index,] nrow(train) nrow(test) nrow(train) + nrow(test) data(mtcars) smp_size <- floor(0.75 * nrow(mtcars)) set.seed(123) train_ind <- sample(seq_len(nrow(mtcars)), size = smp_size) train <- mtcars[train_ind, ] test <- mtcars[-train_ind, ] require(caTools) set.seed(101) sample = sample.split(mtcars$am, SplitRatio = .75) sample train = subset(mtcars, sample == TRUE) test = subset(mtcars, sample == FALSE) train; test table(train$am); table(test$am) mtcars$id <- 1:nrow(mtcars) train <- mtcars %>% dplyr::sample_frac(.75) test <- dplyr::anti_join(mtcars, train, by = 'id') library(caret) intrain<-createDataPartition(y=factor(mtcars$am),p=0.7,list=FALSE) intrain training<-mtcars[intrain,] testing<-mtcars[-intrain,] training testing table(training$am) table(testing$am)
tam_mml_3pl_deviance <- function( hwt0, rfx, res.hwt, pweights, snodes, deviance=NA, deviance.history=NULL, iter=NULL ) { rfx <- NULL olddeviance <- deviance if ( snodes==0 ){ rfx <- rowSums( hwt0 ) deviance <- - 2 * sum( pweights * log( rfx ) ) } else { deviance <- - 2 * sum( pweights * log( res.hwt$rfx ) ) } rel_deviance_change <- abs( ( deviance - olddeviance ) / deviance ) deviance_change <- abs( ( deviance - olddeviance ) ) if (!is.null(deviance.history)){ deviance.history[iter,2] <- deviance } res <- list( rfx=rfx, deviance=deviance, deviance_change=deviance_change, rel_deviance_change=rel_deviance_change, deviance.history=deviance.history) return(res) }
brocolors <- function(set=c("general", "general2", "bg", "bgpng", "CC", "CCalt", "f2", "sex", "main", "crayons", "web")) { general <- c('lightblue' =rgb(102,203,254,maxColorValue=255), 'hotpink' =rgb(254, 0,128,maxColorValue=255), 'pink' =rgb(254,102,254,maxColorValue=255), 'green' =rgb(102,254,102,maxColorValue=255), 'purple' =rgb(128, 0,128,maxColorValue=255), 'lightpurple'=rgb(203,102,254,maxColorValue=255), 'yellow' =rgb(254,203,102,maxColorValue=255), 'darkblue' =rgb( 0,128,128,maxColorValue=255)) general2 <- c(blue=" green=" orange=" red=" bg <- rgb(24, 24, 24, maxColorValue=255) bgpng <- rgb(32, 32, 32, maxColorValue=255) text <- c('yellow' =rgb(255, 255, 102, maxColorValue=255), 'lightblue'=rgb(102, 204, 255, maxColorValue=255), 'pink' =rgb(255, 102, 255, maxColorValue=255)) CC <- c("AJ" =rgb(240,240, 0,maxColorValue=255), "B6" =rgb(128,128,128,maxColorValue=255), "129" =rgb(240,128,128,maxColorValue=255), "NOD" =rgb( 16, 16,240,maxColorValue=255), "NZO" =rgb( 0,160,240,maxColorValue=255), "CAST"=rgb( 0,160, 0,maxColorValue=255), "PWK" =rgb(240, 0, 0,maxColorValue=255), "WSB" =rgb(144, 0,224,maxColorValue=255)) CCalt <- c("AJ" = " "B6" = " "129" = " "NOD" = " "NZO" = " "CAST"= " "PWK" = " "WSB" = " f2 <- c(AA=as.character(CCalt[1]), AB=rgb(0, 200, 0, maxColorValue=255), BB=as.character(CCalt[4]), error=" sex <- c(female=rgb(255,80,80, maxColorValue=255), male=as.character(CCalt[4])) main <- rgb(0, 64, 128, maxColorValue=255) crayons = c("Almond"=" "Antique Brass"=" "Apricot"=" "Aquamarine"=" "Asparagus"=" "Atomic Tangerine"=" "Banana Mania"=" "Beaver"=" "Bittersweet"=" "Black"=" "Blizzard Blue"=" "Blue"=" "Blue Bell"=" "Blue Gray"=" "Blue Green"=" "Blue Violet"=" "Blush"=" "Brick Red"=" "Brown"=" "Burnt Orange"=" "Burnt Sienna"=" "Cadet Blue"=" "Canary"=" "Caribbean Green"=" "Carnation Pink"=" "Cerise"=" "Cerulean"=" "Chestnut"=" "Copper"=" "Cornflower"=" "Cotton Candy"=" "Dandelion"=" "Denim"=" "Desert Sand"=" "Eggplant"=" "Electric Lime"=" "Fern"=" "Forest Green"=" "Fuchsia"=" "Fuzzy Wuzzy"=" "Gold"=" "Goldenrod"=" "Granny Smith Apple"=" "Gray"=" "Green"=" "Green Blue"=" "Green Yellow"=" "Hot Magenta"=" "Inchworm"=" "Indigo"=" "Jazzberry Jam"=" "Jungle Green"=" "Laser Lemon"=" "Lavender"=" "Lemon Yellow"=" "Macaroni and Cheese"=" "Magenta"=" "Magic Mint"=" "Mahogany"=" "Maize"=" "Manatee"=" "Mango Tango"=" "Maroon"=" "Mauvelous"=" "Melon"=" "Midnight Blue"=" "Mountain Meadow"=" "Mulberry"=" "Navy Blue"=" "Neon Carrot"=" "Olive Green"=" "Orange"=" "Orange Red"=" "Orange Yellow"=" "Orchid"=" "Outer Space"=" "Outrageous Orange"=" "Pacific Blue"=" "Peach"=" "Periwinkle"=" "Piggy Pink"=" "Pine Green"=" "Pink Flamingo"=" "Pink Sherbert"=" "Plum"=" "Purple Heart"=" "Purple Mountain's Majesty"=" "Purple Pizzazz"=" "Radical Red"=" "Raw Sienna"=" "Raw Umber"=" "Razzle Dazzle Rose"=" "Razzmatazz"=" "Red"=" "Red Orange"=" "Red Violet"=" "Robin's Egg Blue"=" "Royal Purple"=" "Salmon"=" "Scarlet"=" "Screamin' Green"=" "Sea Green"=" "Sepia"=" "Shadow"=" "Shamrock"=" "Shocking Pink"=" "Silver"=" "Sky Blue"=" "Spring Green"=" "Sunglow"=" "Sunset Orange"=" "Tan"=" "Teal Blue"=" "Thistle"=" "Tickle Me Pink"=" "Timberwolf"=" "Tropical Rain Forest"=" "Tumbleweed"=" "Turquoise Blue"=" "Unmellow Yellow"=" "Violet (Purple)"=" "Violet Blue"=" "Violet Red"=" "Vivid Tangerine"=" "Vivid Violet"=" "White"=" "Wild Blue Yonder"=" "Wild Strawberry"=" "Wild Watermelon"=" "Wisteria"=" "Yellow"=" "Yellow Green"=" "Yellow Orange"=" web <- c(navy=" blue=" aqua=" teal=" olive=" green=" lime=" yellow=" orange=" red=" maroon=" fuchsia=" purple=" black=" gray=" silver=" switch(match.arg(set), general=general, general2=general2, bg=bg, bgpng=bgpng, CC=CC, CCalt=CCalt, f2=f2, sex=sex, main=main, crayons=crayons, web=web) } plot_crayons <- function(method2order=c("hsv", "cluster"), cex=0.6, mar=rep(0.1, 4), bg="white", fg="black", border=FALSE) { method2order <- match.arg(method2order) crayons <- brocolors("crayons") colval <- col2rgb(crayons) if(method2order == "hsv") { colval <- t(rgb2hsv(colval)) ord <- order(names(crayons)!="Black", names(crayons)!="Gray", names(crayons)!="Silver", names(crayons)!="White", colval[,1], colval[,2], colval[,3]) } else { ord <- hclust(dist(t(colval)))$ord } oldmar <- par("mar") oldfg <- par("fg") oldbg <- par("bg") on.exit(par(mar=oldmar, fg=oldfg, bg=oldbg)) par(mar=mar, fg=fg, bg=bg) x <- (1:7)-1 y <- (1:19)-1 x <- rep(x, each=19) y <- rep(y, 7) plot(0, 0, type="n", xlab="", ylab="", xaxs="i", yaxs="i", xlim=c(0, max(x)+1), ylim=c(max(y)+0.5, -0.5), xaxt="n", yaxt="n") dx <- 0.2 dy <- 0.4 if(border) border <- fg else border <- crayons[ord] rect(x+dx/4, y-dy, x+dx, y+dy, border=border, col=crayons[ord]) text(x+dx*1.2, y, names(crayons)[ord], cex=cex, adj=c(0, 0.5)) } crayons <- function(color_names=NULL, ...) { crayons <- brocolors("crayons") if(is.null(color_names)) return(crayons) dots <- list(...) color_names <- unlist(c(color_names,dots)) allnames <- names(crayons) m <- match(color_names, allnames) notfound <- color_names[is.na(m)] g <- vapply(notfound, function(a) { z <- grep(a, allnames, ignore.case=TRUE) if(length(z) < 1) return(-1) if(length(z) > 1) return(-2) z }, 1) if(any(g < 0)) { if(any(g == -1)) warning("Some colors not found") if(any(g == -2)) warning("Some colors with multiple matches") } g[g < 0] <- NA m[is.na(m)] <- g result <- crayons[g] names(result)[is.na(g)] <- color_names[is.na(g)] result }
sc09G <- function(data, k=2, nnbd=7, ...){ mydata = prec_input_dist(data) myk = max(1, round(k)) mynnbd = max(5, round(nnbd)) params = list(...) pnames = names(params) myiter = ifelse(("maxiter"%in%pnames), max(10, round(params$maxiter)), 10) myclust = ifelse(("algclust"%in%pnames), match.arg(tolower(params$algclust),c("kmeans","gmm")), "kmeans") kmeansflag = ifelse(all(myclust=="kmeans"), TRUE, FALSE) cpprun = cpp_sc09G(mydata, myk, mynnbd, kmeansflag, myiter) output = list() output$cluster = round(as.vector(cpprun$labels+1)) output$eigval = as.vector(cpprun$values) output$embeds = cpprun$embeds output$algorithm = "sc09G" return(structure(output, class="T4cluster")) }
stop <- function(..., call. = TRUE, domain = NULL) { args <- list(...) if (length(args) == 1L && inherits(args[[1L]], "condition")) { cond <- args[[1L]] if(nargs() > 1L) warning("additional arguments ignored in stop()") message <- conditionMessage(cond) call <- conditionCall(cond) .Internal(.signalCondition(cond, message, call)) .Internal(.dfltStop(message, call)) } else .Internal(stop(call., .makeMessage(..., domain = domain))) } stopifnot <- function(..., exprs, local = TRUE) { missE <- missing(exprs) cl <- if(missE) { match.call()[-1L] } else { if(...length()) stop("Must use 'exprs' or unnamed expressions, but not both") envir <- if (isTRUE(local)) parent.frame() else if(isFALSE(local)) .GlobalEnv else if (is.environment(local)) local else stop("'local' must be TRUE, FALSE or an environment") exprs <- substitute(exprs) E1 <- if(is.symbol(exprs)) exprs else exprs[[1]] if(identical(quote(`{`), E1)) do.call(expression, as.list(exprs[-1])) else if(identical(quote(expression), E1)) eval(exprs, envir=envir) else as.expression(exprs) } Dparse <- function(call, cutoff = 60L) { ch <- deparse(call, width.cutoff = cutoff) if(length(ch) > 1L) paste(ch[1L], "....") else ch } head <- function(x, n = 6L) x[seq_len(if(n < 0L) max(length(x) + n, 0L) else min(n, length(x)))] abbrev <- function(ae, n = 3L) paste(c(head(ae, n), if(length(ae) > n) "...."), collapse="\n ") for (i in seq_along(cl)) { cl.i <- cl[[i]] r <- withCallingHandlers( tryCatch(if(missE) ...elt(i) else eval(cl.i, envir=envir), error = function(e) { e$call <- cl.i; stop(e) }), warning = function(w) { w$call <- cl.i; w }) if (!(is.logical(r) && !anyNA(r) && all(r))) { msg <- if(is.call(cl.i) && identical(cl.i[[1]], quote(all.equal)) && (is.null(ni <- names(cl.i)) || length(cl.i) == 3L || length(cl.i <- cl.i[!nzchar(ni)]) == 3L)) sprintf(gettext("%s and %s are not equal:\n %s"), Dparse(cl.i[[2]]), Dparse(cl.i[[3]]), abbrev(r)) else sprintf(ngettext(length(r), "%s is not TRUE", "%s are not all TRUE"), Dparse(cl.i)) stop(simpleError(msg, call = sys.call(-1))) } } invisible() } warning <- function(..., call. = TRUE, immediate. = FALSE, noBreaks. = FALSE, domain = NULL) { args <- list(...) if (length(args) == 1L && inherits(args[[1L]], "condition")) { cond <- args[[1L]] if(nargs() > 1L) cat(gettext("additional arguments ignored in warning()"), "\n", sep = "", file = stderr()) message <- conditionMessage(cond) call <- conditionCall(cond) withRestarts({ .Internal(.signalCondition(cond, message, call)) .Internal(.dfltWarn(message, call)) }, muffleWarning = function() NULL) invisible(message) } else .Internal(warning(call., immediate., noBreaks., .makeMessage(..., domain = domain))) } gettext <- function(..., domain = NULL) { args <- lapply(list(...), as.character) .Internal(gettext(domain, unlist(args))) } bindtextdomain <- function(domain, dirname = NULL) .Internal(bindtextdomain(domain, dirname)) ngettext <- function(n, msg1, msg2, domain = NULL) .Internal(ngettext(n, msg1, msg2, domain)) gettextf <- function(fmt, ..., domain = NULL) sprintf(gettext(fmt, domain = domain), ...)
plot2Densities <- function(Data, Cls, col = c("red", "blue"), pde = TRUE, meanLines = FALSE, medianLines = FALSE, ...) { if (length(Data) != length(Cls)) stop("Impact: Data and Cls have different lengths!") UniqueCls <- sort(unique(Cls)) if (length(table(Data = Data[Cls == UniqueCls[1]])) < 2 | length(table(Data = Data[Cls == UniqueCls[2]])) < 2) { suppressWarnings(pdeX1Try <- try(ParetoDensityEstimationIE(Data = Data[Cls == UniqueCls[1]]), TRUE)) suppressWarnings(pdeX2Try <- try(ParetoDensityEstimationIE(Data = Data[Cls == UniqueCls[2]]), TRUE)) } else{ suppressWarnings(PDEKernelsTry <- try(ParetoDensityEstimationIE(Data), TRUE)) if (class(PDEKernelsTry) != "try-error") { PDEKernels <- PDEKernelsTry$kernels suppressWarnings(pdeX1Try <- try(ParetoDensityEstimationIE(Data = Data[Cls == UniqueCls[1]], kernels = PDEKernels), TRUE)) suppressWarnings(pdeX2Try <- try(ParetoDensityEstimationIE(Data = Data[Cls == UniqueCls[2]], kernels = PDEKernels), TRUE)) } else{ message("Pareto density estimation failed. Reverting to standard pdf.") pde <- FALSE } } if (class(pdeX1Try) == "try-error" | class(pdeX2Try) == "try-error") { message("Pareto density estimation failed. Reverting to standard pdf.") pde <- FALSE } if (hasArg("pde") == TRUE & pde == FALSE) { pdx1 <- density(Data[Cls == UniqueCls[1]])$x pdx2 <- density(Data[Cls == UniqueCls[2]])$x pd1 <- density(Data[Cls == UniqueCls[1]])$y pd2 <- density(Data[Cls == UniqueCls[2]])$y } else { pdx1 <- pdeX1Try$kernels pdx2 <- pdeX2Try$kernels pd1 <- pdeX1Try$paretoDensity pd2 <- pdeX2Try$paretoDensity } xmin <- min(pdx1, pdx2) xmax <- max(pdx1, pdx2) ymax <- max(pd1, pd2) plot(pd1 ~ pdx1, type = "l", lwd = 3, col = col[1], xlim = c(xmin, xmax), ylim = c(0, ymax), ...) lines(pd2 ~ pdx2, lwd = 3, col = col[2], ...) if (hasArg("medianLines") == TRUE & medianLines == TRUE) { abline(v = c_median(Data[Cls == UniqueCls[1]]), col = "magenta") abline(v = c_median(Data[Cls == UniqueCls[2]]), col = "magenta", lty = 2) } if (hasArg("meanLines") == TRUE & meanLines == TRUE) { abline(v = mean(Data[Cls == UniqueCls[1]]), col = "darkgreen") abline(v = mean(Data[Cls == UniqueCls[2]]), col = "darkgreen", lty = 2) } }
printnum <- function(x, ...) { UseMethod("printnum", x) } printnum.default <- function(x, na_string = getOption("papaja.na_string"), ...) { if(is.null(x)) stop("The parameter 'x' is NULL. Please provide a value for 'x'") x <- as.character(x) if(anyNA(x)) { x[is.na(x)] <- na_string } x } printnum.list <- function(x, ...) { lapply(x, printnum, ...) } printnum.integer <- function(x, numerals = TRUE, capitalize = FALSE, zero_string = "no", na_string = getOption("papaja.na_string"), ...) { validate(x, check_integer = TRUE, check_NA = FALSE) validate(numerals, check_class = "logical", check_length = 1) validate(capitalize, check_class = "logical", check_length = 1) validate(na_string, check_class = "character", check_length = 1) system_call <- sys.call() if(!is.null(system_call[["zero"]]) && is.null(system_call[["zero_string"]])) zero_string <- "no" validate(zero_string, check_class = "character", check_length = 1) if(numerals) return(as.character(x)) if(anyNA(x)) return(rep(na_string, length(x))) zero_string <- tolower(zero_string) number_to_words <- function(x) { if(x == 0) return(zero_string) single_digits <- c("", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine") names(single_digits) <- 0:9 teens <- c("ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", " seventeen", "eighteen", "nineteen") names(teens) <- 0:9 tens <- c("twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety") names(tens) <- 2:9 number_names <- c("thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion", "octillion", "nonillion", "decillion") digits <- rev(strsplit(as.character(x), "")[[1]]) n_digits <- length(digits) if(n_digits == 1) { number <- as.vector(single_digits[digits]) } else if (n_digits == 2) { if (x <= 19) { number <- as.vector(teens[digits[1]]) } else { number <- paste( tens[digits[2]] , Recall(as.numeric(digits[1])) , sep = "-" ) } } else if(n_digits == 3) { number <- paste( single_digits[digits[3]] , "hundred and" , Recall(collapse(digits[2:1])) ) } else { required_number_word <- ((n_digits + 2) %/% 3) - 1 if (required_number_word > length(number_names)) { stop("Number is too large.") } number <- paste( Recall(collapse(digits[n_digits:(3*required_number_word + 1)])) , number_names[required_number_word] , "," , Recall(collapse(digits[(3*required_number_word):1]))) } number } collapse <- function(...) as.numeric(paste(..., collapse = "")) clean_number <- function(x) { x <- gsub("^\ +|\ +$", "", x) x <- gsub("\ +,", ",", x) x <- gsub(paste0("( and ", zero_string, "|-", zero_string, "|, ", zero_string, ")"), "", x) x <- gsub("(\ *,|-|\ +and)$", "", x) if(!grepl(" and ", x)) x <- gsub(", ", " and ", x) x } if(length(x) > 1) { return( vapply( x , function(y) { y_number <- clean_number(number_to_words(y)) if(capitalize) x_number <- capitalize(y_number) y_number } , FUN.VALUE = "a" ) ) } x_number <- clean_number(number_to_words(x)) if(capitalize) x_number <- capitalize(x_number) x_number } printnum.numeric <- function( x , gt1 = TRUE , zero = TRUE , margin = 1 , na_string = getOption("papaja.na_string") , use_math = TRUE , add_equals = FALSE , ... ) { if(is.null(x)) stop("The parameter 'x' is NULL. Please provide a value for 'x'") ellipsis <- list(...) validate(gt1, check_class = "logical") validate(zero, check_class = "logical") validate(margin, check_class = "numeric", check_integer = TRUE, check_length = 1, check_range = c(1, 2)) validate(na_string, check_class = "character", check_length = 1) validate(use_math, check_class = "logical") validate(add_equals, check_class = "logical") ellipsis <- defaults( ellipsis , set = list( x = x , gt1 = gt1 , zero = zero , na_string = na_string , use_math = use_math ) , set.if.null = list( digits = 2 , big.mark = "," ) ) validate(ellipsis$digits, "digits", check_class = "numeric", check_integer = TRUE, check_range = c(0, Inf)) if(length(x) > 1) { vprintnumber <- function(i, x){ ellipsis.i <- lapply(X = ellipsis, FUN = sel, i) do.call("printnumber", ellipsis.i) } } if(is.numeric(x) & length(x) > 1) { x_out <- sapply(seq_along(x), vprintnumber, x) names(x_out) <- names(x) } else { x_out <- do.call("printnumber", ellipsis) } if(add_equals) { x_out <- add_equals(x_out) } x_out } printnum.data.frame <- function( x , margin = 2 , ... ) { if(margin == 1) { ellipsis <- list(...) ellipsis$x <- x ellipsis$margin <- margin x_out <- do.call("printnum.matrix", ellipsis) } else { x_out <- mapply( FUN = printnum , x = x , ... , SIMPLIFY = FALSE ) } x_out <- as.data.frame( x_out , stringsAsFactors = FALSE , check.names = FALSE , fix.empty.names = FALSE ) rownames(x_out) <- rownames(x) x_out } printnum.matrix <- function( x , margin = 2 , ... ) { ellipsis <- list(...) x_out <- apply( X = x , MARGIN = (3 - margin) , FUN = function(x) { ellipsis$x <- x do.call("printnum", ellipsis) } ) if(margin == 2 || nrow(x) == 1) { x_out <- t(x_out) dimnames(x_out) <- dimnames(x) } if(!is.matrix(x_out)) x_out <- matrix(x_out, ncol = ncol(x)) x_out } printnum.papaja_labelled <-function(x, ...){ x_out <- NextMethod("printnum") variable_label(x_out) <- variable_label(x) x_out } printnumber <- function(x, gt1 = TRUE, zero = TRUE, na_string = "", use_math = TRUE, ...) { ellipsis <- list(...) validate(x, check_class = "numeric", check_NA = FALSE, check_length = 1, check_infinite = FALSE) if(is.na(x)) return(na_string) if(is.infinite(x)) { x_out <- paste0(ifelse(x < 0, "-", ""), "\\infty") if(use_math) x_out <- paste0("$", x_out, "$") return(x_out) } if(!is.null(ellipsis$digits)) { validate(ellipsis$digits, "digits", check_class = "numeric", check_integer = TRUE, check_length = 1, check_range = c(0, Inf)) } validate(gt1, check_class = "logical", check_length = 1) validate(zero, check_class = "logical", check_length = 1) validate(na_string, check_class = "character", check_length = 1) if(!gt1 & abs(x) > 1) warning("You specified gt1 = FALSE, but passed absolute value(s) that exceed 1.") ellipsis <- defaults( ellipsis , set.if.null = list( digits = 2 , format = "f" , flag = "0" , big.mark = "," ) ) x_out <- round(x, ellipsis$digits) + 0 if(sign(x_out) == -1) { xsign <- "-" lt <- "> " gt <- "< " } else { xsign <- "" lt <- "< " gt <- "> " } if(x_out == 0 & !zero) x_out <- paste0(lt, "0.", paste0(rep(0, ellipsis$digits-1), collapse = ""), "1") if(!gt1) { if(x_out == 1) { x_out <- paste0(gt, xsign, ".", paste0(rep(9, ellipsis$digits), collapse = "")) } else if(x_out == -1) { x_out <- paste0(lt, xsign, ".", paste0(rep(9, ellipsis$digits), collapse = "")) } ellipsis$x <- x_out x_out <- do.call("formatC", ellipsis) x_out <- gsub("0\\.", "\\.", x_out) } else { ellipsis$x <- x_out x_out <- do.call("formatC", ellipsis) } x_out } printp <- function(x, digits = 3L, na_string = "", add_equals = FALSE) { validate(x, check_class = "numeric", check_range = c(0, 1), check_NA = FALSE) validate(na_string, check_class = "character", check_length = 1) validate(digits, check_class = "numeric") p <- printnum(x, digits = digits, gt1 = FALSE, zero = FALSE, na_string = na_string, add_equals = add_equals) p } print_df <- function(x, digits = 2L) { if(is.null(x)) return(NULL) if(is.integer(x)) return(printnum(x)) return(printnum(x, digits = as.numeric(x %% 1 != 0) * digits)) }
setClass("modelorg_irrev", representation( irrev = "logical", matchrev = "integer", rev2irrev = "matrix", irrev2rev = "integer" ), contains = "modelorg" ) modelorg_irrev <- function(id, name) { if (missing(id) || missing(name)) { stop("Creating an object of class modelorg_irrev needs name and id!") } id <- as.character(id) name <- as.character(name) obj <- new("modelorg_irrev", id = id, name = name) return(obj) } setMethod(f = "initialize", signature = "modelorg_irrev", definition = function(.Object, id, name) { if (!missing(id) || !missing(name)) { .Object <- callNextMethod(.Object, id = id, name = name) } return(.Object) } ) setMethod("irrev", signature(object = "modelorg_irrev"), function(object) { return(object@irrev) } ) setReplaceMethod("irrev", signature(object = "modelorg_irrev"), function(object, value) { object@irrev <- value return(object) } ) setMethod("matchrev", signature(object = "modelorg_irrev"), function(object) { return(object@matchrev) } ) setReplaceMethod("matchrev", signature(object = "modelorg_irrev"), function(object, value) { object@matchrev <- value return(object) } ) setMethod("rev2irrev", signature(object = "modelorg_irrev"), function(object) { return(object@rev2irrev) } ) setReplaceMethod("rev2irrev", signature(object = "modelorg_irrev"), function(object, value) { object@rev2irrev <- value return(object) } ) setMethod("irrev2rev", signature(object = "modelorg_irrev"), function(object) { return(object@irrev2rev) } ) setReplaceMethod("irrev2rev", signature(object = "modelorg_irrev"), function(object, value) { object@irrev2rev<- value return(object) } )
library(readr) relig_income <- read_csv("data-raw/relig_income.csv") usethis::use_data(relig_income, overwrite = TRUE)
makebreaks.ic <- function(y,d,x,w, breaks){ n <- nrow(y) q <- ncol(x) yy <- c(y[,1], y[,2]) r <- range(yy[abs(yy) != Inf]) n1 <- sum(o <- (d %in% c(1,3))) yc <- (y[o,1] + y[o,2])/2 if(missing(breaks)){breaks <- max(5, min(10, ceiling(n1/q/5)))} if(length(breaks) > 1){ breaks <- sort(unique(breaks)) k <- length(breaks) - 1 if(r[1] < breaks[1] | r[2] > breaks[k + 1]) {stop("all finite y values must be within the breaks")} breaks <- breaks[1:which(breaks >= r[2])[1]] k <- length(breaks) - 1 } else{ k <- breaks breaks <- wtd.quantile(yc, weights = w, probs = (0:k)/k) check.l <- (mean(yy < breaks[1]) > 0.03) check.r <- (mean(yy > breaks[k + 1]) > 0.03) if(k > 2 && (check.l | check.r)){ if(check.l & !check.r){breaks <- c(-Inf, wtd.quantile(yc, weights = w, probs = (0:(k - 1))/(k - 1)))} if(!check.l & check.r){breaks <- c(wtd.quantile(yc, weights = w, probs = (0:(k - 1))/(k - 1)), Inf)} if(check.l & check.r){breaks <- c(-Inf, wtd.quantile(yc, weights = w, probs = (0:(k - 2))/(k - 2)), Inf)} } breaks[1] <- r[1]; breaks[k + 1] <- r[2] a <- duplicated(round(breaks,8)) if(any(a)){ for(j in which(a)){ if(a[j - 1]){breaks[j] <- NA} else{ h <- abs(yc - breaks[j]) h <- min(h[h > 0]) h <- max(1e-6, min(h/2, (r[2] - r[1])/n/100)) breaks[j-1] <- breaks[j-1] - h breaks[j] <- breaks[j] + h } } breaks <- breaks[!is.na(breaks)] k <- length(breaks) h <- c(Inf, breaks[2:k] - breaks[1:(k - 1)]) breaks[h <= 0] <- NA breaks <- breaks[!is.na(breaks)] k <- length(breaks) - 1 } } if(any(yy %in% breaks)){ eps <- min(breaks[2:(k + 1)] - breaks[1:k])/n1 breaks[1:k] <- breaks[1:k] - eps breaks[k + 1] <- breaks[k + 1] + eps } names(breaks) <- NULL list(breaks = breaks, k = k) } convert.Surv <- function(y){ code <- y[,3] n <- nrow(y) y1 <- rep.int(-Inf,n) y2 <- rep.int(Inf,n) w1 <- (code != 2) y1[w1] <- y[w1,1] w2 <- (code != 0) y2[w2] <- y[w2,2] w2bis <- (code == 2) y2[w2bis] <- y[w2bis,1] w2ter <- (code == 1) y2[w2ter] <- y[w2ter,1] yy <- c(y1,y2); yy <- yy[is.finite(yy)] eps <- (max(yy) - min(yy))/1e+5 w <- (code == 1) y1[w] <- y1[w] - eps y2[w] <- y2[w] + eps y <- cbind(y1, y2) attr(y, "code") <- code attr(y, "eps") <- eps y } pch.fit.ic <- function(z,y,d,x,w,breaks){ if(missing(z)){z <- rep.int(-Inf,n)} if(missing(d)){d <- rep.int(1,n)} if(missing(w)){w <- rep.int(1,n)} Breaks <- suppressWarnings(if(all(attr(y, "code") %in% 0:1)) makebreaks.ct(y[,1],is.finite(y[,2]),x,w,breaks) else makebreaks.ic(y,d,x,w,breaks)) n <- nrow(y); k <- Breaks$k Breaks <- Breaks$breaks h <- Breaks[2:(k + 1)] - Breaks[1:k] attr(Breaks, "h") <- h; attr(Breaks, "k") <- k mod <- icpch.fit(y,d,x,w,Breaks) beta <- mod$beta beta[is.na(beta)] <- 0 lambda <- cleanlambda(exp(x%*%beta),x, mod$rangex) Lambda <- CumSum(t(t(lambda)*h)) colnames(lambda) <- colnames(Lambda) <- 1:k br <- c(Breaks[1] - 1, Breaks) u <- approxfun(br, c(1:k, k + 1, k + 1), rule = 2, method = "constant") conv.status <- 0 if(!mod$conv){conv.status <- 1; warning("the algorithm did not converge", call. = FALSE)} list(beta = beta, lambda = lambda, Lambda = Lambda, loglik = mod$loglik, s.i = mod$s.i, h = mod$h, covar = mod$vcov, breaks = Breaks, y = y, u = u, rangex = mod$rangex, conv.status = conv.status) } icpch.fit <- function(y,d,x,w,breaks){ k <- length(breaks) - 1 n <- nrow(y) zeror <- NULL rangex <- list() for(j in 1:k){ open <- (y[,1] >= breaks[j] | y[,1] <= breaks[j+1]) close <- (y[,2] >= breaks[j] | y[,2] <= breaks[j+1]) r <- myapply(x[(open | close),, drop = FALSE], range) delta <- r[,2] - r[,1] r[,1] <- r[,1] - 0.2*delta r[,2] <- r[,2] + 0.2*delta zeror.j <- rep.int(FALSE, n) for(h in 1:ncol(x)){ out.l <- (x[,h] < r[h,1]) out.r <- (x[,h] > r[h,2]) ml <- mean(out.l); mr <- mean(out.r) if(max(ml,mr) < 0.05){r[h,1] <- -Inf; r[h,2] <- Inf} else{ if(ml > mr){outx <- out.l; r[h,2] <- Inf} else{outx <- out.r; r[h,1] <- -Inf} zeror.j <- (zeror.j | outx) } } zeror <- cbind(zeror, zeror.j) rangex[[j]] <- r } cn <- colnames(x) qq <- ncol(x) xx <- qr(x) sel <- xx$pivot[1:xx$rank] x <- x0 <- x[,sel, drop = FALSE] q <- ncol(x) mx <- colMeans(x) sx <- myapply(x,sd) const <- (sx == 0) if(int <- any(const)){ const <- which(const) mx[const] <- 0 sx[const] <- x[1,const] } else{ const <- integer(0) mx <- rep.int(0, q) } vars <- which(sx > 0) x <- scale(x, center = mx, scale = sx) conv <- TRUE U1 <- break.y(y[,1], breaks) U2 <- break.y(y[,2], breaks) beta0 <- matrix(0,q,k) if(int){beta0[const,] <- max(-10, -log(mean(breaks - breaks[1])))} safeit <- 0; fit.ok <- FALSE; count <- 0 while(!fit.ok){ fit <- newton(beta0, icpch.loglik, tol = 1e-5, maxit = 10*(1 + q*k), safeit = safeit, y = y, x = x, w = w, U1 = U1, U2 = U2, zeror = zeror) fit.ok <- all(abs(fit$gradient) < sqrt(n)/15 + count) count <- count + 1; safeit <- safeit + 2 if(count == 20){conv <- FALSE; break} } beta <- matrix(fit$estimate, q,k) beta[vars,] <- beta[vars,]/sx[vars] beta[const,] <- beta[const,] - colSums(beta[vars,, drop = FALSE]*mx[vars]) loglik <- icpch.loglik(beta, y, x0,w,U1,U2, zeror, deriv = 2, final = TRUE) Beta <- matrix(NA, qq, k) Beta[sel,] <- beta rownames(Beta) <- cn h <- attr(loglik, "hessian") s.i <- attr(loglik, "s.i") eps <- 1/(n^2) ok <- FALSE while(!ok){ omega <- try(chol2inv(chol(t(s.i*w)%*%s.i + diag(eps, q*k))), silent = TRUE) v <- try(chol2inv(chol(h%*%omega%*%h + diag(eps, q*k))), silent = TRUE) ok <- (!inherits(omega, "try-error") && !inherits(v, "try-error")) eps <- eps*5 } V <- matrix(0, qq*k, qq*k) sel2 <- rep.int(sel, k) sel2 <- sel2 + rep(0:(k - 1), each = length(sel))*q V[sel2,sel2] <- v list(beta = Beta, vcov = V, rangex = rangex, converged = conv, loglik = as.numeric(loglik), s.i = s.i, h = h) } break.y <- function(y,breaks){ k <- length(breaks) - 1 U <- NULL for(j in 1:k){ u <- pmin(y - breaks[j], breaks[j + 1] - breaks[j]) U <- cbind(U, pmax(u,0)) } U } icpch.loglik <- function(beta, y, x,w,U1,U2, zeror, deriv = 0, final = FALSE){ k <- ncol(U1) q <- ncol(x) n <- nrow(x) beta <- matrix(beta, q,k) log.lambda <- tcrossprod(x, t(beta))*(!zeror) - zeror*1e+10 lambda <- exp(log.lambda) lambda <- pmin(lambda, 1e+10) H1 <- .rowSums(lambda*U1, n, k) H2 <- .rowSums(lambda*U2, n, k) S1 <- exp(-H1); S1[y[,1] == -Inf] <- 1 S2 <- exp(-H2); S2[y[,2] == Inf] <- 0 deltaS <- pmax(S1 - S2, 1e-12) dS <- deltaS if(final){ events <- which(attr(y, "code") == 1) dS[events] <- dS[events]/2/attr(y, "eps") } l <- sum(w*log(dS)) if(deriv == 0){return(-l)} xw <- x*w deltaSU <- S1*U1 - S2*U2 deltaU <- U2 - U1 lambda.deltaU <- lambda*deltaU lambda.deltaSU <- lambda*deltaSU A1 <- lambda.deltaSU/deltaS A2 <- S1*S2/deltaS^2 A3 <- A1 + A2*lambda.deltaU^2 xA2 <- x*A2 s.i <- NULL for(j in 1:k){s.i <- cbind(s.i, -x*A1[,j])} s <- .colSums(w*s.i, n, q*k) h <- matrix(NA, q*k, q*k) for(j1 in 1:k){ ind1 <- (j1*q - q + 1):(j1*q) for(j2 in j1:k){ ind2 <- (j2*q - q + 1):(j2*q) if(j1 == j2){h[ind1,ind2] <- -crossprod(xw, x*A3[,j1])} else{h[ind1,ind2] <- h[ind2,ind1] <- -crossprod(xw, xA2*lambda.deltaU[,j1]*lambda.deltaU[,j2])} } } out <- -l attr(out, "gradient") <- -s attr(out, "hessian") <- -h attr(out, "s.i") <- s.i out }
list.save <- function(x, file, type = tools::file_ext(file), ...) { fun <- paste("list.savefile", tolower(type), sep = ".") if (exists(fun, mode = "function")) { fun <- get(fun, mode = "function") fun(x, file, ...) } else { stop("Unrecognized type of file: ", file, call. = FALSE) } invisible(x) } list.savefile.json <- function(x, file, ...) { json <- jsonlite::toJSON(x, ...) writeLines(json, file) } list.savefile.yaml <- function(x, file, ...) { yaml <- yaml::as.yaml(x, ...) writeLines(yaml, file) } list.savefile.yml <- list.savefile.yaml list.savefile.rdata <- function(x, file, name = "x", ...) { if (!is.list(x)) stop("x is not a list") env <- new.env(parent = parent.frame(), size = 1L) assign(name, x, envir = env) save(list = name, file = file, envir = env, ...) } list.savefile.rds <- function(x, file, ...) saveRDS(x, file, ...)
classclustermeds<-function(citrus.foldFeatureSet,citrus.foldClustering,citrus.combinedFCSSet,groupsizes,meds){ cutoffs<-cumsum(groupsizes) cutoffs<-c(0,cutoffs) if(is.null(meds)){ signals<-allmeds(citrus.combinedFCSSet = citrus.combinedFCSSet,citrus.foldClustering = citrus.foldClustering,citrus.foldFeatureSet = citrus.foldFeatureSet) }else{ signals<-meds } data<-citrus.combinedFCSSet$data parnames<-colnames(signals[[1]]) ind<-grep("fileId",parnames) group<-list() ameds<-list() count<-1 for(j in signals){ for(i in 2:length(cutoffs)){ a<-j[j[,ind]<=cutoffs[i]&j[,ind]>cutoffs[i-1],] ameds[[i-1]]<-apply(a,2,median) } group[[count]]<-do.call("rbind",ameds) count<-count+1 } return(group) }
create_batch_body <- function(metabolites_type = 'all-except-peptides', databases = '["all-except-mine"]', masses_mode = 'mz', ion_mode = 'positive', adducts = '["M+H","M+Na"]', tolerance = 10, tolerance_mode = 'ppm', unique_mz) { masses <- paste(unique_mz, collapse = ",") tolerance <- as.character(tolerance) post_body <- paste0( '{"metabolites_type":"' , metabolites_type, '","databases":' , databases, ',"masses_mode":"' , masses_mode, '","ion_mode":"' , ion_mode, '","adducts":' , adducts, ',"tolerance":' , tolerance, ',"tolerance_mode":"' , tolerance_mode, '","masses":[' , masses, ']}') }
suppressMessages(library(LatticeKrig)) options( echo=FALSE) test.for.zero.flag<-1 set.seed( 333) xLocation<- cbind( runif( 10, 3,5), runif( 10,3,5)) xNew<- cbind( runif( 4, 3,5), runif( 4,3,5)) LKinfo<- LKrigSetup( cbind( c(3,5), c(3,5)), NC=3, NC.buffer=2, a.wght=5, alpha=c(1), nlevel=1, normalize=TRUE) PHI<- LKrig.basis(xNew, LKinfo) Q<- LKrig.precision(LKinfo) covMatrix<- (PHI)%*% solve( Q)%*%t(PHI) test.for.zero( diag(covMatrix), rep( 1, nrow( xNew)), tag="check using Qinverse formula", tol=1e-7) covMatrix2<- LKrig.cov( xNew, LKinfo=LKinfo) test.for.zero( covMatrix,covMatrix2, tag="check using Qinverse formula full matrix",, tol=1e-7) alpha<- c( 1, .8,.2) LKinfo<- LKrigSetup( cbind( c(3,5), c(3,5)), NC=2, NC.buffer=2, a.wght=5, alpha=alpha, nlevel=3, normalize=TRUE) varTest<- sum( alpha) PHI<- LKrig.basis(xNew, LKinfo) Q<- LKrig.precision(LKinfo) covMatrix<- (PHI)%*% solve( Q)%*%t(PHI) test.for.zero( diag(covMatrix), rep( varTest, nrow( xNew)), tag=" Qinverse formula norm", tol=1e-7) alpha<- c( 1, .8,.2) alpha<- alpha/sum( alpha) LKinfo<- LKrigSetup( cbind( c(3,5), c(3,5)), NC=2, NC.buffer=2, a.wght=5, alpha=alpha, nlevel=3, normalize=FALSE) PHI<- LKrig.basis(xNew, LKinfo) Q<- LKrig.precision(LKinfo) covMatrix<- (PHI)%*% solve( Q)%*%t(PHI) covMatrix2<- LKrig.cov( xNew, LKinfo=LKinfo) test.for.zero( covMatrix, covMatrix2, tag=" Qinverse formula nonorm") alpha<- c( 1, .8,.2) alpha<- alpha/sum( alpha) LKinfo<- LKrigSetup( cbind( c(3,5), c(3,5)), NC=2, NC.buffer=2, a.wght=4.5, alpha=alpha, nlevel=3, normalize=TRUE, BasisType="Tensor") varTest<- sum( alpha) PHI<- LKrig.basis(xNew, LKinfo) Q<- LKrig.precision(LKinfo) covMatrix<- (PHI)%*% solve( Q)%*%t(PHI) varTest<-LKrig.cov( xNew, marginal=TRUE, LKinfo=LKinfo) test.for.zero( diag(covMatrix), varTest, tag=" Qinverse formula Tensor no norm") test.for.zero( diag(covMatrix), sum(alpha), tag=" Qinverse formula Tensor no norm") set.seed( 333) xLocation<- cbind( runif( 10, 3,5), runif( 10,3,5)) LKinfo<- LKrigSetup( cbind( c(3,5), c(3,5)), NC=3, NC.buffer=2, a.wght=5, alpha=1, nlevel=1, normalize=TRUE) LKinfo0<- LKrigSetup( cbind( c(3,5), c(3,5)), NC=3, NC.buffer=2, a.wght=5, alpha=1, nlevel=1, normalize=FALSE) wght1<- LKrigNormalizeBasisFast.LKRectangle(LKinfo, Level=1, xLocation) wght0<-LKrig.cov( xLocation, LKinfo= LKinfo0, marginal=TRUE) test.for.zero( wght0, wght1, tag=" 1 level Marginal variance compared to fast normalize", tol=2e-7) alphaVec<- c( 1,.5,.2) LKinfo0<- LKrigSetup( cbind( c(3,5), c(3,5)), NC=3, NC.buffer=2, a.wght=5, alpha=alphaVec, nlevel=3, normalize=FALSE ) LKinfo<- LKrigSetup( cbind( c(3,5), c(3,5)), NC=3, NC.buffer=2, a.wght=5, alpha=alphaVec,nlevel=3,normalize=TRUE) test1<-LKrigNormalizeBasisFast.LKRectangle( LKinfo, Level=1, xLocation ) test2<-LKrigNormalizeBasisFast.LKRectangle( LKinfo, Level=2, xLocation ) test3<-LKrigNormalizeBasisFast.LKRectangle( LKinfo, Level=3, xLocation ) testVar1<- cbind( test1, test2, test3) %*% alphaVec testVar0<-LKrig.cov( xLocation, LKinfo= LKinfo0, marginal=TRUE) test.for.zero( testVar0, testVar1, tag="Marginal variance and fast normalize", tol=1e-7) cat( "Done with testing fast normalize algorithm", fill=TRUE) options( echo=TRUE)
source("ESEUR_config.r") pal_col=rainbow(2) dad=read.csv(paste0(ESEUR_dir, "sourcecode/13-13.csv.xz"), as.is=TRUE) samp=sample(1:nrow(dad), 20000) dad=dad[samp, ] plot(dad$inscount, dad$O3, log="xy", col=pal_col[2], xlab="LLVM instructions", ylab="Compile time (secs)\n") one_dad=subset(dad, (inscount >= 300) | (inscount < 300 & O3 <= 0.10)) O3_mod=nls(O3 ~ a+b*inscount^c, data=one_dad, start=list(a=0.01, b=1e-3, c=0.6)) x_vals=exp(seq(1, 10, by=0.1)) pred=predict(O3_mod, newdata=data.frame(inscount=x_vals)) lines(x_vals, pred, col=pal_col[1])
options(prompt = "R> ", continue = "+ ", width = 70, useFancyQuotes = FALSE) set.seed(123) numSim=100 library("lifecontingencies") showClass("lifetable") showClass("actuarialtable") showMethods(classes=c("actuarialtable","lifetable")) interest2Discount(0.03) discount2Interest(interest2Discount(0.03)) convertible2Effective(i=0.10,k=4) capitals <- c(-1000,200,500,700) times <- c(0,1,2,5) presentValue(cashFlows=capitals, timeIds=times, interestRates=0.03) presentValue(cashFlows=capitals, timeIds=times, interestRates=c( 0.04, 0.02, 0.03, 0.05), probabilities=c(1,1,1,0.5)) getIrr <- function(p) (presentValue(cashFlows=capitals, timeIds=times, interestRates=p) - 0)^2 nlm(f=getIrr, p=0.1)$estimate 100 * annuity(i=0.03, n=5) 100 * accumulatedValue(i=0.03, n=5) ann1 <- annuity(i=0.03, n=5, k=1, type="immediate") ann2 <- annuity(i=0.03, n=5, k=12, type="immediate") c(ann1,ann2) incrAnn <- increasingAnnuity(i=0.03, n=10, type="due") decrAnn <- decreasingAnnuity(i=0.03, n=10, type="immediate") c(incrAnn, decrAnn) annuity(i=((1+0.04)/(1+0.03)-1), n=10) capital <- 100000 interest <- 0.05 payments_per_year <- 2 rate_per_period <- (1+interest)^(1/payments_per_year)-1 years <- 30 R <- 1/payments_per_year * capital/annuity(i=interest, n=years, k=payments_per_year) R balanceDue <- numeric(years * payments_per_year) balanceDue[1] <- capital * (1+rate_per_period) - R for(i in 2:length(balanceDue)) balanceDue[i]<- balanceDue[i-1] * (1+rate_per_period) - R plot(x=c(1:length(balanceDue)), y=balanceDue, main="Loan amortization", ylab="EoP balance due", xlab="year", type="l",col="steelblue") bond<-function(faceValue, couponRate, couponsPerYear, yield,maturity) { out <- numeric(1) numberOfCF <- maturity * couponsPerYear CFs <- numeric(numberOfCF) payments <- couponRate * faceValue / couponsPerYear cf <- payments * rep(1,numberOfCF) cf[numberOfCF] <- faceValue + payments times <- seq.int(from=1/couponsPerYear, to=maturity, by=maturity/numberOfCF) out <- presentValue(cashFlows=cf, interestRates=yield, timeIds=times) return(out) } perpetuity<-function(yield, immediate=TRUE) { out <- numeric(1) out <- 1 / yield out <- ifelse(immediate==TRUE, out, out*(1+yield)) return(out) } bndEx1 <-bond(1000, 0.06, 2, 0.05, 3) bndEx2 <-bond(1000, 0.06, 2, 0.06, 3) ppTy1 <-perpetuity(0.1) c(bndEx1, bndEx2, ppTy1) cashFlows <- c(100,100,100,600,500,700) timeVector <- seq(1:6) interestRate <- 0.03 dur1 <-duration(cashFlows = cashFlows, timeIds = timeVector, i = interestRate, k = 1, macaulay = TRUE) dur2 <-duration(cashFlows = cashFlows, timeIds = timeVector, i = interestRate, k = 1, macaulay = FALSE) cvx1 <-convexity(cashFlows = cashFlows, timeIds = timeVector, i = interestRate, k = 1) c(dur1, dur2, cvx1) GTCFin<- 10000 * (1 + 0.05)^7 GTCFin yieldT0 <- 0.04 durLiab <- 7 pvLiab <- presentValue(cashFlows = GTCFin,timeIds = 7, interestRates = yieldT0) convLiab <- convexity(cashFlows=GTCFin, timeIds = 7, i=yieldT0) pvBond <- bond(100,0.03,1,yieldT0,5) durBond <- duration(cashFlows=c(3,3,3,3,103), timeIds=seq(1,5), i = yieldT0) convBond <- convexity(cashFlows=c(3,3,3,3,103), timeIds=seq(1,5), i = yieldT0) pvPpty <- perpetuity(yieldT0) durPpty <- (1+yieldT0)/yieldT0 covnPpty <- 2/(yieldT0^2) a <- matrix(c(durBond, durPpty,1,1), nrow=2, byrow=TRUE) b <- as.vector(c(7,1)) weights <-solve(a,b) weights bondNum <- weights[1] * pvLiab / pvBond pptyNum <- weights[2] * pvLiab / pvPpty bondNum pptyNum convAsset <- weights[1] * convBond + weights[2] * covnPpty convAsset>convLiab yieldT1low <- 0.03 immunizationTestLow <- (bondNum * bond(100,0.03,1,yieldT1low,5) + pptyNum * perpetuity(yieldT1low)> GTCFin / (1+yieldT1low)^7) yieldT1high <- 0.05 immunizationTestHigh <- (bondNum * bond(100,0.03,1,yieldT1high,5) + pptyNum * perpetuity(yieldT1high)> GTCFin/(1+yieldT1high)^7) immunizationTestLow immunizationTestHigh x_example <- seq(from=0,to=9, by=1) lx_example <- c(1000,950,850,700,680,600,550,400,200,50) exampleLt <- new("lifetable", x=x_example, lx=lx_example, name="example lifetable") print(exampleLt) head(exampleLt) data("demoUsa") data("demoIta") usaMale07 <- demoUsa[,c("age", "USSS2007M")] usaMale00 <- demoUsa[,c("age", "USSS2000M")] names(usaMale07) <- c("x","lx") names(usaMale00) <- c("x","lx") usaMale07Lt <-as(usaMale07,"lifetable") usaMale07Lt@name <- "USA MALES 2007" usaMale00Lt <-as(usaMale00,"lifetable") usaMale00Lt@name <- "USA MALES 2000" lxIPS55M <- with(demoIta, IPS55M) pos2Remove <- which(lxIPS55M %in% c(0,NA)) lxIPS55M <-lxIPS55M[-pos2Remove] xIPS55M <-seq(0,length(lxIPS55M)-1,1) ips55M <- new("lifetable",x=xIPS55M, lx=lxIPS55M, name="IPS 55 Males") lxIPS55F <- with(demoIta, IPS55F) pos2Remove <- which(lxIPS55F %in% c(0,NA)) lxIPS55F <- lxIPS55F[-pos2Remove] xIPS55F <- seq(0,length(lxIPS55F)-1,1) ips55F <- new("lifetable",x=xIPS55F, lx=lxIPS55F, name="IPS 55 Females") data("demoIta") itaM2002 <- demoIta[,c("X","SIM92")] names(itaM2002) <- c("x","lx") itaM2002Lt <- as(itaM2002,"lifetable") itaM2002Lt@name <- "IT 2002 Males" itaM2002 <- as(itaM2002Lt,"data.frame") itaM2002$qx <- 1-itaM2002$px for(i in 20:60) itaM2002$qx[itaM2002$x==i] = 0.2 * itaM2002$qx[itaM2002$x==i] itaM2002reduced <- probs2lifetable(probs=itaM2002[,"qx"], radix=100000, type="qx",name="IT 2002 Males reduced") exampleAct <- new("actuarialtable",x=exampleLt@x, lx=exampleLt@lx, interest=0.03, name="example actuarialtable") getOmega(exampleAct) print(exampleLt) print(exampleAct) exampleActDf <- as(exampleAct, "data.frame") data(soa08) require(markovchain) soa08Mc<-as(soa08,"markovchainList") data("soa08Act") soa08ActDf <- as(soa08Act, "data.frame") plot(soa08Act, type="l",col="steelblue") demoEx1<-pxt(ips55M,20,1) demoEx2<-qxt(ips55M,30,2) demoEx3<-exn(ips55M, 50,20,"complete") c(demoEx1,demoEx2,demoEx3) mx20t1 <- mxt(ips55M,20,1) qx20t1 <- mx2qx(mx20t1) c(mx20t1,qx20t1) data("soa08Act") pxtLin <- pxt(soa08Act,80,0.5,"linear") pxtCnst <- pxt(soa08Act,80,0.5,"constant force") pxtHyph <- pxt(soa08Act,80,0.5,"hyperbolic") c(pxtLin,pxtCnst,pxtHyph) tablesList <- list(ips55M, ips55F) jsp <- pxyzt(tablesList, x=c(65,63), t=2) lsp <- pxyzt(tablesList, x=c(65,63), t=2, status="last") jelt <- exyzt(tablesList, x=c(65,63), status="joint") c(jsp,lsp,jelt) data(soa08Act) UComm <- Axn(actuarialtable=soa08Act, x=25, n=65-25, k=12) UCpt <- ((soa08ActDf$Mx[26]-soa08ActDf$Mx[66])/soa08ActDf$Dx[26]) * 0.06/real2Nominal(i=0.06,k=12) c(UComm, UCpt) P <- UCpt/axn(actuarialtable=soa08Act,x=25,n=10) P (10 + 1 ) * Axn(actuarialtable=soa08Act, x=25, n=10) DAxn(actuarialtable = soa08Act, x=25, n=10) + IAxn(actuarialtable = soa08Act, x=25, n=10) UCpt <- axn(actuarialtable=soa08Act, x=75, m=10) UComm <- with(soa08ActDf,Nx[86]/Dx[76]) c(UCpt,UComm) P=axn(actuarialtable=soa08Act, x=75, m=10) / axn(actuarialtable=soa08Act, x=75, n=5) P PComm <- with(soa08ActDf,(Nx[86]/Dx[76]) / ((Nx[76]-Nx[81])/Dx[76])) PComm U <- axn(actuarialtable=soa08Act, x=75, m=10, k=12) P <- axn(actuarialtable=soa08Act, x=75, m=10, k=12) / axn(actuarialtable=soa08Act, x=75, n=5) c(U,P) P=100000 * Axn(soa08Act,x=25,n=40)/axn(soa08Act,x=25,n=40) reserveFun = function(t) return(100000*Axn(soa08Act,x=25+t,n=40-t)-P* axn(soa08Act,x=25+t,n=40-t)) for(t in 0:40) {if(t%%5==0) cat("At time ",t, " benefit reserve is ", reserveFun(t),"\n")} yearlyRate <- 12000 irate <- 0.02 APV <- yearlyRate*axn(soa08Act, x=25, i=irate,m=65-25,k=12) levelPremium <- APV/axn(soa08Act, x=25,n=65-25,k=12) annuityReserve<-function(t) { out<-NULL if(t<65-25) out <- yearlyRate*axn(soa08Act, x=25+t, i=irate, m=65-(25+t),k=12)-levelPremium*axn(soa08Act, x=25+t, n=65-(25+t),k=12) else { out <- yearlyRate*axn(soa08Act, x=25+t, i=irate,k=12) } return(out) } years <- seq(from=0, to=getOmega(soa08Act)-25-1,by=1) annuityRes <- numeric(length(years)) for(i in years) annuityRes[i+1] <- annuityReserve(i) dataAnnuityRes <- data.frame(years=years, reserve=annuityRes) plot(y=dataAnnuityRes$reserve, x=dataAnnuityRes$years, col="steelblue", main="Deferred annuity benefit reserve", ylab="amount",xlab="years",type="l") G <- (100000*Axn(soa08Act, x=35) + (2.5*100000/1000 + 25)* axn(soa08Act,x=35))/((1-.1)*axn(soa08Act,x=35)) G twoLifeTables <- list(maleTable=soa08Act, femaleTable=soa08Act) axn(soa08Act, x=65,m=1)+axn(soa08Act, x=70,m=1)- axyzn(tablesList=twoLifeTables, x=c(65,y=70),status="joint",m=1) axyzn(tablesList=twoLifeTables, x=c(65,y=70), status="last",m=1) axn(actuarialtable = soa08Act, x=60,m=1)- axyzn(tablesList = twoLifeTables, x=c(65,60),status="joint",m=1) rLife(n = 5, object = soa08Act, x = 45, type = "Kx") futureLifetimes <- as.data.frame(rLifexyz(n=numSim, tablesList=list(husband=ips55M,wife=ips55F), x=c(68,65), type="Tx")) names(futureLifetimes) <- c("husband","wife") temp <- futureLifetimes$wife - futureLifetimes$husband futureLifetimes$widowance <- sapply(temp, max,0) mean(futureLifetimes$widowance) hist(futureLifetimes$widowance, freq=FALSE, main="Distribution of widowance yars", xlab="Widowance years", col="steelblue", nclass=100);abline(v=mean(futureLifetimes$widowance), col="red", lwd=2) APVAxn <- Axn(soa08Act,x=25,n=40,type="EV") APVAxn sampleAxn <- rLifeContingencies(n=numSim, lifecontingency="Axn", object=soa08Act,x=25,t=40,parallel=FALSE) tt1 <-t.test(x=sampleAxn,mu=APVAxn)$p.value APVIAxn <- IAxn(soa08Act,x=25,n=40,type="EV") APVIAxn sampleIAxn <- rLifeContingencies(n=numSim, lifecontingency="IAxn", object=soa08Act,x=25,t=40,parallel=FALSE) tt2 <-t.test(x=sampleIAxn,mu=APVIAxn)$p.value APVaxn <- axn(soa08Act,x=25,n=40,type="EV") APVaxn sampleaxn <- rLifeContingencies(n=numSim, lifecontingency="axn", object=soa08Act,x=25,t=40,parallel=FALSE) tt3 <- t.test(x=sampleaxn,mu=APVaxn)$p.value APVAExn <- AExn(soa08Act,x=25,n=40,type="EV") APVAExn sampleAExn <- rLifeContingencies(n=numSim, lifecontingency="AExn", object=soa08Act,x=25,t=40,parallel=FALSE) tt4 <-t.test(x=sampleAExn,mu=APVAExn)$p.value c(tt1, tt2,tt3, tt4) par(mfrow=c(2,2)) hist(sampleAxn, main="Term Insurance", xlab="Actuarial present value",nclass=50, col="steelblue",freq=FALSE);abline(v=APVAxn, col="red", lwd=2) hist(sampleIAxn, main="Increasing Life Insurance", xlab="Actuarial present value",nclass=50, col="steelblue",freq=FALSE);abline(v=APVIAxn, col="red", lwd=2) hist(sampleaxn, main="Temporary Annuity Due", xlab="Actuarial present value",nclass=50, col="steelblue",freq=FALSE);abline(v=APVaxn, col="red", lwd=2) hist(sampleAExn, main="Endowment Insurance", xlab="Actuarial present value",nclass=50, col="steelblue",freq=FALSE);abline(v=APVAExn, col="red", lwd=2) tablesList=list(soa08Act,soa08Act);x=c(60,60);m=0;status="last";t=30;k=1 APVAxyz<-Axyzn(tablesList=tablesList,x=x,n=t,status=status,type="EV") samplesAxyz<-rLifeContingenciesXyz(n=numSim,lifecontingency = "Axyz", tablesList = tablesList,x=x,t=t,m=m,k=k,status=status, parallel=FALSE) tt5<-t.test(x=samplesAxyz, mu=APVAxyz)$p.value APVaxyz<-axyzn(tablesList=tablesList,x=x,n=t,m=m,k=k,status=status,type="EV") samplesaxyz<-rLifeContingenciesXyz(n=numSim,lifecontingency = "axyz", tablesList = tablesList,x=x,t=t,m=m,k=k,status=status, parallel=FALSE) tt6<-t.test(x=samplesaxyz, mu=APVaxyz)$p.value c(tt5,tt6) var(sampleAxn) Axn(soa08Act, x=25,n=40, power=2)-Axn(soa08Act, x=25,n=40, power=1)^2 APV <- Axn(actuarialtable = soa08Act, x=25, n=40) APV samples <- rLifeContingencies(n=numSim, lifecontingency = "Axn", object= soa08Act, x=25,t=40,parallel=FALSE) pct90Pr <- as.numeric(quantile(samples,.90)) pct90Pr pct90Pr2 <- qnorm(p=0.90,mean=APV, sd=sd(samples)/sqrt(1000)) pct90Pr2 nsim <- 50 employees <- 100 salaryDistribution <- rlnorm(n=employees,m=10.77668944,s=0.086177696) ageDistribution <- round(runif(n=employees,min=25, max=65)) policyLength <- sapply(65-ageDistribution, min, 1) getEmployeeBenefit<-function(index,type="EV") { out <- numeric(1) out <- salaryDistribution[index]*Axn(actuarialtable=soa08Act, x=ageDistribution[index],n=policyLength[index], i=0.02,m=0,k=1, type=type) return(out) } require(parallel) cl <- makeCluster(1) worker.init <- function(packages) { for (p in packages) { library(p, character.only=TRUE) } invisible(NULL) } clusterCall(cl, worker.init, c('lifecontingencies')) clusterExport(cl, varlist=c("employees","getEmployeeBenefit", "salaryDistribution","policyLength", "ageDistribution","soa08Act")) employeeBenefits <- numeric(employees) employeeBenefits <- parSapply(cl, 1:employees,getEmployeeBenefit, type="EV") employeeBenefit <- sum(employeeBenefits) benefitDistribution<-numeric(nsim) yearlyBenefitSimulate<-function(i) { out <- numeric(1) expenseSimulation <- numeric(employees) expenseSimulation <- sapply(1:employees, getEmployeeBenefit, type="ST") out <- sum(expenseSimulation) return(out) } benefitDistribution <- parSapply(cl, 1:nsim,yearlyBenefitSimulate ) stopCluster(cl) riskMargin <- as.numeric(quantile(benefitDistribution,.75)-employeeBenefit) totalBookedCost <- employeeBenefit+riskMargin employeeBenefit riskMargin totalBookedCost valdezDf<-data.frame( x=c(50:54), lx=c(4832555,4821937,4810206,4797185,4782737), heart=c(5168, 5363, 5618, 5929, 6277), accidents=c(1157, 1206, 1443, 1679,2152), other=c(4293,5162,5960,6840,7631) ) valdezMdt<-new("mdt",name="ValdezExample",table=valdezDf) valdezDf<-as(valdezMdt,"data.frame") require(markovchain) valdezMarkovChainList<-as(valdezMdt,"markovchainList") getOmega(valdezMdt) getDecrements(valdezMdt) summary(valdezMdt) dxt(valdezMdt,x=51,decrement="other") dxt(valdezMdt,x=51,t=2, decrement="other") dxt(valdezMdt,x=51) dxt(valdezMdt,x=51,t=2, decrement="other") pxt(valdezMdt,x=50,t=3) qxt(valdezMdt,x=53,t=2,decrement=1) rmdt(n = 2,object = valdezMdt,x = 50,t = 2) qxt.prime.fromMdt(object = valdezMdt,x=53, decrement="accidents") qxt.fromQxprime(qx.prime = 0.01,other.qx.prime = c(0.03,0.06)) myTable<-data.frame(x=c(16,17,18), lx=c(20000,17600,14520), da=c(1300,1870,2380), doc=c(1100,1210,1331) ) myMdt<-new("mdt",table=myTable,name="Sample") Axn.mdt(object=myMdt,x=16,i=.1,decrement="da") axnmdt.firsttype<-function (object, x, n, i , payment="advance", delta=0) { out <- numeric(1) if (!(class(object) %in% c("lifetable", "actuarialtable", "mdt"))) stop("Error! Only lifetable, actuarialtable or mdt classes are accepted") if (missing(object)) stop("Error! Need a Multiple decrement table") if (missing(x)) stop("Error! Need age!") if (x > getOmega(object)) { stop("Age greater than Omega") } if(class(object)=="mdt"){ if (x < min(object@table$x)) { stop("Age lower than minimum age") }} if(class(object)=="actuarialtable"){ if (x < min(object@x)) { stop("Age lower than minimum age") }} if(!(missing(i))){ interest <- i }else{ if(class(object)=="actuarialtable"){ interest=object@interest }else{ stop("Needed Interest Rate ") } } if (missing(n)) n <- (getOmega(object) - x) if (n == 0) { stop("Contract duration equal to zero") } probs = numeric(n) times = seq(from = 0, to = n-1, by = 1) if (payment == "arrears") times = times + 1 for (j in 1:length(times)) probs[j] = pxt(object, x, times[j]) out <- sum(apply(cbind(probs,((1 + interest)/(1+delta))^-times),1,prod)) return(out) } data("de_angelis_di_falco") HealthyMaleTable2013 <- de_angelis_di_falco$HealthyMaleTable2013 DAT<-new("actuarialtable", x=de_angelis_di_falco$DisabledMaleLifeTable$age, lx=de_angelis_di_falco$DisabledMaleLifeTable$'2013', name="DisabledTable",i=0.03) axnmdt.firsttype(DAT,x=65,n=10,i=0.03,payment="arrears",delta=0.02) axnmdt.firsttype(DAT,65,10,payment="arrears",delta=0.02) axnmdt.firsttype(DAT,65,10,payment="arrears",i=0.03,delta=0.02) axnmdt.firsttype(DAT,65,10,payment="arrears",delta=0) axn(DAT,65,10,payment="arrears")
waldLLR = function(target, dataset, xIndex, csIndex, wei = NULL, univariateModels=NULL, hash = FALSE, stat_hash=NULL, pvalue_hash=NULL){ if (!survival::is.Surv(target) ) stop('The survival test can not be performed without a Surv object target'); csIndex[which(is.na(csIndex))] = 0; if ( hash ) { csIndex2 = csIndex[which(csIndex!=0)] csIndex2 = sort(csIndex2) xcs = c(xIndex,csIndex2) key = paste(as.character(xcs) , collapse=" "); if (is.null(stat_hash[key]) == FALSE) { stat = stat_hash[key]; pvalue = pvalue_hash[key]; results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); } } pvalue <- log(1); stat <- 0; results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); event <- target[, 2] numCases <- dim(dataset)[1]; if (length(event) == 0) event = vector('numeric',numCases) + 1; if ( length(csIndex) == 0 || sum(csIndex == 0, na.rm = TRUE) > 0 ) { llr_results <- survival::survreg( target ~ dataset[, index], weights = wei, control = list(iter.max = 5000), dist = "loglogistic" ) res <- summary(llr_results)[[ 9 ]] stat <- res[2, 3]^2 pvalue <- pchisq(stat, 1, lower.tail = FALSE, log.p = TRUE); } else { llr_results_full <- survival::survreg( target ~ ., data = as.data.frame( dataset[ , c(csIndex, xIndex)] ), weights = wei, control = list(iter.max = 5000), dist = "loglogistic" ) res <- summary(llr_results_full)[[ 9 ]] pr <- dim(res)[1] - 1 stat <- res[pr, 3]^2 pvalue <- pchisq(stat, 1, lower.tail = FALSE, log.p = TRUE) } if ( is.na(pvalue) || is.na(stat) ) { pvalue <- log(1); stat <- 0; } else { if( hash ) { stat_hash[key] <- stat; pvalue_hash[key] <- pvalue; } } results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash); return(results); }
library(fitdistrplus) visualize <- FALSE nsample <- 1000 nsample <- 10 data(groundbeef) serving <- groundbeef$serving fitW <- fitdist(serving,"weibull") fitln <- fitdist(serving,"lnorm") fitg <- fitdist(serving,"gamma") try(cdfcomp("list(fitW, fitln, fitg)",horizontals = FALSE), silent=TRUE) try(cdfcomp(list(fitW, fitln, fitg, a=1),horizontals = FALSE), silent=TRUE) cdfcomp(list(fitW, fitln, fitg), horizontals = FALSE) cdfcomp(list(fitW, fitln, fitg), horizontals = TRUE) cdfcomp(list(fitW, fitln, fitg), horizontals = TRUE, lines01 = TRUE) cdfcomp(list(fitW, fitln, fitg), horizontals = TRUE, verticals = TRUE, datacol = "grey") if (requireNamespace ("ggplot2", quietly = TRUE)) { cdfcomp(list(fitW, fitln, fitg), horizontals = FALSE, plotstyle = "ggplot") } if (requireNamespace ("ggplot2", quietly = TRUE) & visualize) { cdfcomp(list(fitW, fitln, fitg), horizontals = TRUE, plotstyle = "ggplot") cdfcomp(list(fitW, fitln, fitg), horizontals = TRUE, lines01 = TRUE, plotstyle = "ggplot") cdfcomp(list(fitW, fitln, fitg), horizontals = TRUE, verticals = TRUE, datacol = "grey", plotstyle = "ggplot") } cdfcomp(list(fitW, fitln, fitg), legendtext = c("Weibull", "lognormal", "gamma"), main = "ground beef fits", xlab = "serving sizes (g)", ylab = "F(g)", xlim = c(0, 250), ylim = c(.5, 1)) if (requireNamespace ("ggplot2", quietly = TRUE) & visualize) { cdfcomp(list(fitW, fitln, fitg), legendtext = c("Weibull", "lognormal", "gamma"), main = "ground beef fits", xlab = "serving sizes (g)", ylab = "F(g)", xlim = c(0, 250), ylim = c(.5, 1), plotstyle = "ggplot") } cdfcomp(list(fitW, fitln, fitg), legendtext = c("Weibull", "lognormal", "gamma"), main = "ground beef fits", xlab = "serving sizes (g)", ylab = "F(g)", xlogscale = TRUE) if (requireNamespace ("ggplot2", quietly = TRUE) & visualize) { cdfcomp(list(fitW, fitln, fitg), legendtext = c("Weibull", "lognormal", "gamma"), main = "ground beef fits", xlab = "serving sizes (g)", ylab = "F(g)", xlogscale = TRUE, plotstyle = "ggplot") } cdfcomp(list(fitW,fitln,fitg),legendtext=c("Weibull","lognormal","gamma"), main="ground beef fits",xlab="serving sizes (g)", ylab="F(g)", xlogscale=TRUE, ylogscale=TRUE, ylim=c(.005, .99)) if (requireNamespace ("ggplot2", quietly = TRUE) & visualize) { cdfcomp(list(fitW,fitln,fitg),legendtext=c("Weibull","lognormal","gamma"), main="ground beef fits",xlab="serving sizes (g)", ylab="F(g)", xlogscale=TRUE, ylogscale=TRUE, ylim=c(.005, .99), plotstyle = "ggplot") } cdfcomp(list(fitW,fitln,fitg), legendtext=c("Weibull","lognormal","gamma"), main="ground beef fits",xlab="serving sizes (g)", ylab="F(g)",xlim = c(0,250), xlegend = "topleft") if (requireNamespace ("ggplot2", quietly = TRUE) & visualize) { cdfcomp(list(fitW,fitln,fitg), legendtext=c("Weibull","lognormal","gamma"), main="ground beef fits",xlab="serving sizes (g)", ylab="F(g)",xlim = c(0,250), xlegend = "topleft", plotstyle = "ggplot") } data(endosulfan) ATV <-subset(endosulfan, group == "NonArthroInvert")$ATV taxaATV <- subset(endosulfan, group == "NonArthroInvert")$taxa flnMGEKS <- fitdist(ATV,"lnorm",method="mge",gof="KS") flnMGEAD <- fitdist(ATV,"lnorm",method="mge",gof="AD") flnMGEADL <- fitdist(ATV,"lnorm",method="mge",gof="ADL") flnMGEAD2L <- fitdist(ATV,"lnorm",method="mge",gof="AD2L") llfit <- list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L) cdfcomp(list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L), xlogscale=TRUE, main="fits of a lognormal dist. using various GOF dist.") cdfcomp(list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L), xlogscale=TRUE,main="fits of a lognormal dist. using various GOF dist.", legendtext=c("MGE KS","MGE AD","MGE ADL","MGE AD2L")) cdfcomp(list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L), xlogscale=TRUE,main="fits of a lognormal dist. using various GOF dist.", legendtext=c("MGE KS","MGE AD","MGE ADL","MGE AD2L"), fitcol=c("black", "darkgreen", "yellowgreen", "yellow2"), horizontals=FALSE, datapch="+") cdfcomp(llfit, xlogscale=TRUE, main="fits of a lognormal dist. using various GOF dist.", legendtext=paste("MGE", c("KS","AD","ADL","AD2L")), fitcol="grey35", fitlty="dotted", horizontals=FALSE, datapch=21, datacol="grey30") cdfcomp(list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L), xlogscale=TRUE, verticals=TRUE, xlim=c(10,100000), datapch=21) cdfcomp(flnMGEKS, xlogscale=TRUE, verticals=TRUE, xlim=c(10,100000)) cdfcomp(list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L), xlogscale=TRUE, verticals=TRUE, xlim=c(1,100000), datapch=21, name.points=taxaATV) cdfcomp(flnMGEKS, xlogscale=TRUE, verticals=TRUE, xlim=c(1,100000), name.points=taxaATV) if (requireNamespace ("ggplot2", quietly = TRUE) & visualize) { cdfcomp(list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L), xlogscale=TRUE, main = "fits of a lognormal dist. using various GOF dist.", plotstyle = "ggplot") cdfcomp(list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L), xlogscale=TRUE,main="fits of a lognormal dist. using various GOF dist.", legendtext=c("MGE KS","MGE AD","MGE ADL","MGE AD2L"), plotstyle = "ggplot") cdfcomp(list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L), xlogscale=TRUE,main="fits of a lognormal dist. using various GOF dist.", legendtext=c("MGE KS","MGE AD","MGE ADL","MGE AD2L"), fitcol=c("black", "darkgreen", "yellowgreen", "yellow2"), horizontals=FALSE, datapch="+", plotstyle = "ggplot") cdfcomp(llfit, xlogscale=TRUE, main="fits of a lognormal dist. using various GOF dist.", legendtext=paste("MGE", c("KS","AD","ADL","AD2L")), fitcol="grey35", fitlty="dotted", horizontals=FALSE, datapch=21, datacol="grey30", plotstyle = "ggplot") cdfcomp(list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L), xlogscale=TRUE, verticals=TRUE, xlim=c(10,100000), datapch=21, plotstyle = "ggplot") cdfcomp(flnMGEKS, xlogscale=TRUE, verticals=TRUE, xlim=c(10,100000), plotstyle = "ggplot") cdfcomp(list(flnMGEKS, flnMGEAD, flnMGEADL, flnMGEAD2L), xlogscale=TRUE, verticals=TRUE, xlim=c(1,100000), datapch=21, name.points=taxaATV, plotstyle = "ggplot") cdfcomp(flnMGEKS, xlogscale=TRUE, verticals=TRUE, xlim=c(1,100000), name.points=taxaATV, plotstyle = "ggplot") } if (visualize) { data(endosulfan) log10ATV <-log10(subset(endosulfan, group == "NonArthroInvert")$ATV) taxaATV <- subset(endosulfan, group == "NonArthroInvert")$taxa fln <- fitdist(log10ATV, "norm") fll <- fitdist(log10ATV, "logis") cdfcomp(list(fln, fll), legendtext = c("normal", "logistic"), xlab = "log10ATV", name.points=taxaATV, xlim = c(0,5)) if (requireNamespace ("ggplot2", quietly = TRUE)) { cdfcomp(list(fln, fll), legendtext = c("normal", "logistic"),xlab = "log10ATV", name.points=taxaATV, xlim=c(0,5), plotstyle = "ggplot") } cdfcomp(list(fln,fll),legendtext=c("normal","logistic"),xlab="log10ATV", use.ppoints = TRUE, a.ppoints = 0) if (requireNamespace ("ggplot2", quietly = TRUE)) { cdfcomp(list(fln,fll),legendtext=c("normal","logistic"),xlab="log10ATV", use.ppoints = TRUE, a.ppoints = 0, plotstyle = "ggplot") } cdfcomp(list(fln,fll),legendtext=c("normal","logistic"),xlab="log10ATV", use.ppoints = FALSE) if (requireNamespace ("ggplot2", quietly = TRUE)) { cdfcomp(list(fln,fll),legendtext=c("normal","logistic"),xlab="log10ATV", use.ppoints = FALSE, plotstyle = "ggplot") } } if (visualize) { x1 <- c(6.4,13.3,4.1,1.3,14.1,10.6,9.9,9.6,15.3,22.1,13.4,13.2,8.4,6.3,8.9,5.2,10.9,14.4) x <- seq(0, 1.1*max(x1), length=100) dgumbel <- function(x,a,b) 1/b*exp((a-x)/b)*exp(-exp((a-x)/b)) pgumbel <- function(q,a,b) exp(-exp((a-q)/b)) f1 <- mledist(x1, "norm") f2 <- mledist(x1, "gumbel", start = list(a = 10, b = 5)) f3 <- mledist(x1, "exp") plot(ecdf(x1)) lines(x, pnorm(x, f1$estimate[1], f1$estimate[2]), col = "red") lines(x, pgumbel(x, f2$estimate[1], f2$estimate[2]), col = "green") lines(x, pexp(x, f3$estimate[1]), col = "blue") legend("bottomright", lty = 1, leg = c("Normal", "Gumbel", "Exp"), col = c("red", "green", "blue")) f1 <- fitdist(x1, "norm") f2 <- fitdist(x1, "gumbel", start = list(a = 10, b = 5)) f3 <- fitdist(x1, "exp") cdfcomp(list(f1, f2, f3), xlim=range(x), fitcol = c("red", "green", "blue"), fitlty = 1, legendtext = c("Normal", "Gumbel", "Exp")) cdfcomp(list(f1, f2, f3), xlim=range(x), fitcol = c("red", "green", "blue"), fitlty = 1, fitlwd = (1:3)*2, legendtext = c("Normal", "Gumbel", "Exp")) if (requireNamespace ("ggplot2", quietly = TRUE)) { cdfcomp(list(f1, f2, f3), xlim=range(x), fitcol=c("red","green","blue"), fitlty = 1, legendtext = c("Normal", "Gumbel", "Exp"), plotstyle = "ggplot") cdfcomp(list(f1, f2, f3), xlim=range(x), fitcol=c("red","green","blue"), fitlty = 1, fitlwd = 1:3, legendtext = c("Normal", "Gumbel", "Exp"), plotstyle = "ggplot") } } dnorm2 <- function(x, poid, m1, s1, m2, s2) poid*dnorm(x, m1, s1) + (1-poid)*dnorm(x, m2, s2) qnorm2 <- function(p, poid, m1, s1, m2, s2) { L2 <- function(x, prob) (prob - pnorm2(x, poid, m1, s1, m2, s2))^2 sapply(p, function(pr) optimize(L2, c(-1000, 1000), prob=pr)$minimum) } pnorm2 <- function(q, poid, m1, s1, m2, s2) poid*pnorm(q, m1, s1) + (1-poid)*pnorm(q, m2, s2) set.seed(1234) x2 <- c(rnorm(nsample, 5), rnorm(nsample, 10)) fit1 <- fitdist(x2, "norm2", "mle", start=list(poid=1/3, m1=4, s1=2, m2=8, s2=2), lower=c(0, 0, 0, 0, 0)) fit2 <- fitdist(x2, "norm2", "qme", probs=c(1/6, 1/4, 1/3, 1/2, 2/3), start=list(poid=1/3, m1=4, s1=2, m2=8, s2=2), lower=c(0, 0, 0, 0, 0), upper=c(1/2, Inf, Inf, Inf, Inf)) fit3 <- fitdist(x2, "norm2", "mge", gof="AD", start=list(poid=1/3, m1=4, s1=2, m2=8, s2=2), lower=c(0, 0, 0, 0, 0), upper=c(1/2, Inf, Inf, Inf, Inf)) cdfcomp(list(fit1, fit2, fit3), datapch=".") cdfcomp(list(fit1, fit2, fit3), datapch=".", xlim=c(6, 8), ylim=c(.4, .55)) if (requireNamespace ("ggplot2", quietly = TRUE) & visualize) { cdfcomp(list(fit1, fit2, fit3), datapch=".", plotstyle = "ggplot") cdfcomp(list(fit1, fit2, fit3), datapch=".", xlim=c(6, 8), ylim=c(.4, .55), plotstyle = "ggplot") } set.seed(1234) x3 <- rpois(20, 10) fit1 <- fitdist(x3, "pois", "mle") fit2 <- fitdist(x3, "nbinom", "qme", probs=c(1/3, 2/3)) cdfcomp(list(fit1, fit2), datapch=21, horizontals=FALSE) if (requireNamespace ("ggplot2", quietly = TRUE) & visualize) { cdfcomp(list(fit1, fit2), datapch=21, horizontals=FALSE, plotstyle = "ggplot") } if (visualize) { n <- 1e4 f1 <- fitdist(rlnorm(n), "lnorm") cdfcomp(f1, do.points=TRUE) cdfcomp(f1, do.points=FALSE) cdfcomp(f1, horizontals = FALSE, verticals = FALSE, do.points = FALSE) if (requireNamespace ("ggplot2", quietly = TRUE) & visualize) { cdfcomp(f1, do.points = TRUE, plotstyle = "ggplot") cdfcomp(f1, do.points = FALSE, plotstyle = "ggplot") cdfcomp(f1, horizontals = FALSE, verticals = FALSE, do.points = FALSE, plotstyle = "ggplot") } } set.seed(1234) x3 <- rpois(nsample, 10) fit1 <- fitdist(x3, "pois", "mle") cdfcomp(fit1, fitcol = "red", horizontals=FALSE, addlegend = FALSE) fit2 <- fitdist(x3, "nbinom", "qme", probs=c(1/3, 2/3)) cdfcomp(fit2, fitcol = "blue", horizontals=FALSE, addlegend = FALSE, add = TRUE) cdfcomp(list(fit1, fit2), horizontals=FALSE, addlegend = FALSE, fitcol=c("red", "blue")) if (requireNamespace ("ggplot2", quietly = TRUE) & visualize) { cdfcomp(list(fit1, fit2), fitcol = c("red", "blue"), fitlty = 1, horizontals = FALSE, addlegend = FALSE, plotstyle = "ggplot") } if (visualize) { serving <- groundbeef$serving fitW <- fitdist(serving,"weibull") fitW2 <- fitdist(serving,"weibull", method="qme", probs=c(1/3,2/3)) fitW3 <- fitdist(serving,"weibull", method="qme", probs=c(1/2,2/3)) fitln <- fitdist(serving,"lnorm") fitg <- fitdist(serving,"gamma") cdfcomp(list(fitW, fitln, fitg)) cdfcomp(list(fitW, fitW2, fitln, fitg)) cdfcomp(list(fitW, fitW2, fitW3, fitln, fitg)) if (requireNamespace ("ggplot2", quietly = TRUE)) cdfcomp(list(fitW, fitW2, fitW3, fitln, fitg), plotstyle = "ggplot") }
x= rnorm(100, 50,10) y= rnorm(100, 70, 15) x1= runif(100, 50,100) x2= runif(100, 70, 120) y1 = runif(100, 100,200) y2 = runif(100, 100,200) matplot(x, cbind(y1,y2),type="l",col=c("red","green"),lty=c(1,1)) x1 <- seq(-2, 2, 0.05) x2 <- seq(-3, 3, 0.05) y1 <- pnorm(x1) y2 <- pnorm(x2,1,1) plot(x1,y1,ylim=range(c(y1,y2)),xlim=range(c(x1,x2)), type="l",col="red") lines(x2,y2,col="green") par(mfrow=c(1,2)) plot(x) plot(y) par(mfrow=c(1,1)) plot(x1, y1,col='red') points(x2,y2,col='blue') lines(x2,y2,col='green') kx = matrix( c(21,50,80,41), nrow=2 ) x y = matrix( c(1,2,1,2), nrow=2 ) y plot(x, y, col=c("red","blue")) require(ggplot2) df= data.frame(x, y1,y2) ggplot(df, aes(x,y1)) + geom_line(colour="red") ggplot(df, aes(x)) + geom_line(aes(y=y1), colour="red") + geom_line(aes(y=y2), colour="green")
`peak.2.array` <- function(peak) { if ( !all(attr(peak,'class',exact=TRUE) %in% c('peak','list')) ) stop("Input should have class \"peak\".") for ( i in seq(names(peak)) ){ for (j in 1:length(peak[[i]])) { if ( is.data.frame(peak[[i]][[j]])){ feat <- names(peak[[i]][[j]]) break } } if (is.data.frame(peak[[i]][[j]])) break } cat('peaks features:\n') print(feat) cat('\n') array <- data.frame(t(rep(NA,length(feat)+2))) for ( i in seq(names(peak)) ){ for ( j in 1:length(peak[[i]]) ) { if ( is.data.frame(peak[[i]][[j]]) ) { for ( z in seq(length(as.vector(peak[[i]][[j]]$mname.peak))) ){ w <- NA for ( y in 1:length(feat) ) w <- c(w,as.vector(peak[[i]][[j]][[y]][z])) array <- rbind( array,data.frame(t(c( names(peak[i]), names(peak[[i]][j]), w[-1] ))) ) } } else { array <- rbind( array,data.frame(t(c( names(peak[i]), names(peak[[i]][j]), rep(NA,length(feat)) ))) ) } } } attributes(array)$names <- c('trait','chr',feat) array <- array[-1,] attributes(array)$class <- c('peak.array','data.frame') return(array) }
assert_valid_compression <- function(compression){ assert( is_scalar_atomic(compression) && ( compression %in% c("base::zip", "zip::zipr") || compression %in% 1:9 || is_bool(compression) ), '`compression` must be `TRUE`, `FALSE`, or an integer between 1 and 9', 'or the character scalers "base::zip" or "zip::zipr" not: ', string_repr(compression) ) }
context("Calculate aggregate Elo scores") library(bwsTools) res1 <- elo(agg, "pid", "trial", "character", "decision", iter = 1) res2 <- elo(indiv, "id", "block", "label", "value", iter = 100) test_that("function works on BIBD and non-BIBD data", { expect_equal(nrow(res1), length(unique(agg$character))) expect_equal(nrow(res2), length(unique(indiv$label))) expect_equal(ncol(res1), 2) expect_equal(ncol(res2), 2) }) test_that("function outputs scores that are not constant", { expect_true(length(unique(round(res1$elo))) > 1) expect_true(length(unique(round(res2$elo))) > 1) }) test_that("scores between ae_mnl and elo correlate positively", { totals <- unique(table(indiv$label)) bests <- with(indiv, tapply(value, label, function(x) sum(x == 1))) worsts <- with(indiv, tapply(value, label, function(x) sum(x == -1))) res3 <- ae_mnl(data.frame(totals, bests, worsts), "totals", "bests", "worsts") expect_true(cor(res3$b, res2$elo) > .9) }) rm(res1, res2)
test_that("data loads", { imd_uk <- load_composite_imd() expect_equal(nrow(imd_uk), 42619) }) test_that("error thrown", { expect_error(load_composite_imd("Z"), "Invalid nation: it must be one of 'E', 'W', 'S', 'N'") })
bal.plot <- function(x, var.name, ..., which, which.sub = NULL, cluster = NULL, which.cluster = NULL, imp = NULL, which.imp = NULL, which.treat = NULL, which.time = NULL, mirror = FALSE, type = "density", colors = NULL, grid = FALSE, sample.names, position = "right", facet.formula = NULL, disp.means = getOption("cobalt_disp.means", FALSE), alpha.weight = TRUE) { tryCatch(identity(x), error = function(e) stop(conditionMessage(e), call. = FALSE)) .call <- match.call(expand.dots = TRUE) .alls <- vapply(seq_along(.call), function(z) identical(.call[[z]], quote(.all)), logical(1L)) .nones <- vapply(seq_along(.call), function(z) identical(.call[[z]], quote(.none)), logical(1L)) if (any(c(.alls, .nones))) { .call[.alls] <- expression(NULL) .call[.nones] <- expression(NA) return(eval.parent(.call)) } tryCatch(force(x), error = function(e) stop(conditionMessage(e), call. = FALSE)) args <- list(...) x <- process_obj(x) X <- x2base(x, ..., cluster = cluster, imp = imp) if (is_null(X$covs.list)) { X$covs <- get.C2(X$covs, addl = X$addl, distance = X$distance, cluster = X$cluster, treat = X$treat, drop = FALSE) co.names <- attr(X$covs, "co.names") if (missing(var.name)) { var.name <- NULL; k = 1 while(is_null(var.name)) { x <- co.names[[k]] if ("isep" %nin% x[["type"]]) var.name <- x[["component"]][x[["type"]] == "base"][1] else { if (k < length(co.names)) k <- k + 1 else stop("Please specify an argument to 'var.name'.", call. = FALSE) } } message(paste0("No 'var.name' was provided. Displaying balance for ", var.name, ".")) } var.name_in_name <- vapply(co.names, function(x) var.name %in% x[["component"]][x[["type"]] == "base"] && "isep" %nin% x[["type"]], logical(1L)) var.name_in_name_and_factor <- vapply(seq_along(co.names), function(x) var.name_in_name[x] && "fsep" %in% co.names[[x]][["type"]], logical(1L)) if (any(var.name_in_name_and_factor)) { X$var <- unsplitfactor(as.data.frame(X$covs[,var.name_in_name_and_factor, drop = FALSE]), var.name, sep = attr(co.names, "seps")["factor"])[[1]] } else if (any(var.name_in_name)) { X$var <- X$covs[,var.name] } else { stop(paste0("\"", var.name, "\" is not the name of an available covariate."), call. = FALSE) } if (get.treat.type(X$treat) != "continuous") X$treat <- treat_vals(X$treat)[X$treat] } else { X$covs.list <- lapply(seq_along(X$covs.list), function(i) { get.C2(X$covs.list[[i]], addl = X$addl.list[[i]], distance = X$distance.list[[i]], cluster = X$cluster, treat = X$treat.list[[i]], drop = FALSE) }) co.names.list <- lapply(X$covs.list, attr, "co.names") ntimes <- length(X$covs.list) if (missing(var.name)) { var.name <- NULL; k <- 1; time <- 1 while (is_null(var.name)) { x <- co.names.list[[time]][[k]] if ("isep" %nin% x[["type"]]) { var.name <- x[["component"]][x[["type"]] == "base"][1] } else { if (time < ntimes) { if (k < length(co.names.list[[time]])) k <- k + 1 else { k <- 1 time <- time + 1 } } else if (k < length(co.names.list[[time]])) k <- k + 1 else stop("Please specified an argument to 'var.name'.", call. = FALSE) } } message(paste0("No 'var.name' was provided. Displaying balance for ", var.name, ".")) } var.list <- make_list(length(X$covs.list)) appears.in.time <- rep.int(TRUE, length(X$covs.list)) for (i in seq_along(X$covs.list)) { var.name_in_name <- vapply(co.names.list[[i]], function(x) var.name %in% x[["component"]][x[["type"]] == "base"] && "isep" %nin% x[["type"]], logical(1L)) var.name_in_name_and_factor <- var.name_in_name & vapply(co.names.list[[i]], function(x) "fsep" %in% x[["type"]], logical(1L)) if (any(var.name_in_name_and_factor)) { var.list[[i]] <- unsplitfactor(as.data.frame(X$covs.list[[i]][,var.name_in_name_and_factor, drop = FALSE]), var.name, sep = attr(co.names.list[[i]], "seps")["factor"])[[1]] } else if (any(var.name_in_name)) { var.list[[i]] <- X$covs.list[[i]][,var.name] } else { appears.in.time[i] <- FALSE } } if (all(vapply(var.list, is_null, logical(1L)))) stop(paste0("\"", var.name, "\" is not the name of an available covariate."), call. = FALSE) X$var <- unlist(var.list[appears.in.time]) X$time <- rep(which(appears.in.time), times = lengths(var.list[appears.in.time])) X$treat.list[appears.in.time] <- lapply(X$treat.list[appears.in.time], function(t) if (get.treat.type(t) != "continuous") treat_vals(t)[t] else t) X$treat <- unlist(X$treat.list[appears.in.time]) if (is_not_null(names(X$treat.list)[appears.in.time])) treat.names <- names(X$treat.list)[appears.in.time] else treat.names <- which(appears.in.time) if (is_not_null(X$weights)) X$weights <- do.call("rbind", lapply(seq_len(sum(appears.in.time)), function(x) X$weights)) if (is_not_null(X$cluster)) X$cluster <- rep(X$cluster, sum(appears.in.time)) if (is_not_null(X$imp)) X$imp <- rep(X$imp, sum(appears.in.time)) } if (is_null(X$subclass)) { if (NCOL(X$weights) == 1L) weight.names <- "adjusted" else weight.names <- names(X$weights) } else weight.names <- "adjusted" if (missing(which)) { if (is_not_null(args$un)) { message("Note: \'un\' is deprecated; please use \'which\' for the same and added functionality.") if (args$un) which <- "unadjusted" else which <- weight.names } else { if (is_null(X$weights) && is_null(X$subclass)) which <- "unadjusted" else which <- weight.names } } else { if (is_null(X$weights) && is_null(X$subclass)) which <- "unadjusted" else { which <- tolower(which) which <- match_arg(which, unique(c("adjusted", "unadjusted", "both", weight.names)), several.ok = TRUE) } } if (is_not_null(args$size.weight)) { message("Note: \'size.weight\' is no longer allowed; please use \'alpha.weight\' for similar functionality.") } title <- paste0("Distributional Balance for \"", var.name, "\"") subtitle <- NULL facet <- NULL is.categorical.var <- is.factor(X$var) || is.character(X$var) || is_binary(X$var) if (is_null(X$subclass) || (length(which) == 1 && which == "unadjusted")) { if (is_not_null(which.sub) && !all(is.na(which.sub))) { if (is_null(X$subclass)) warning("which.sub was specified but no subclasses were supplied. Ignoring which.sub.", call. = FALSE) else warning("which.sub was specified but only the unadjusted sample was requested. Ignoring which.sub.", call. = FALSE) } facet <- "which" if ("both" %in% which) which <- c("Unadjusted Sample", weight.names) else { if ("adjusted" %in% which) which <- c(which[which != "adjusted"], weight.names) if ("unadjusted" %in% which) which <- c("Unadjusted Sample", which[which != "unadjusted"]) } which <- unique(which) if (is_null(X$weights)) X$weights <- setNames(data.frame(rep.int(1, length(X$treat))), "Unadjusted Sample") else { if (ncol(X$weights) == 1) { which[which != "Unadjusted Sample"] <- "Adjusted Sample" names(X$weights) <- "Adjusted Sample" } if ("Unadjusted Sample" %in% which) { X$weights <- setNames(data.frame(rep.int(max(X$weights), length(X$treat)), X$weights), c("Unadjusted Sample", names(X$weights))) } } X$weights <- X$weights[which] ntypes <- length(which) nadj <- sum(which != "Unadjusted Sample") if (!missing(sample.names)) { if (!is.vector(sample.names, "character")) { warning("The argument to sample.names must be a character vector. Ignoring sample.names.", call. = FALSE) sample.names <- NULL } else if (length(sample.names) %nin% c(ntypes, nadj)) { warning("The argument to sample.names must contain as many names as there are sample types, or one fewer. Ignoring sample.names.", call. = FALSE) sample.names <- NULL } } else sample.names <- NULL in.imp <- rep.int(TRUE, length(X$var)) if (is_not_null(X$imp)) { if (is_null(which.imp)) { in.imp <- !is.na(X$imp) facet <- c("imp", facet) } else if (!all(is.na(which.imp))) { if (is.numeric(which.imp)) { if (all(which.imp %in% seq_len(nlevels(X$imp)))) { in.imp <- !is.na(X$imp) & X$imp %in% levels(X$imp)[which.imp] } else { stop(paste0("The following inputs to 'which.imp' do not correspond to given imputations:\n\t", word_list(which.imp[!which.imp %in% seq_len(nlevels(X$imp))])), call. = FALSE) } facet <- c("imp", facet) } else stop("The argument to 'which.imp' must be the indices corresponding to the imputations for which distributions are to be displayed.", call. = FALSE) } } else if (is_not_null(which.imp) && !all(is.na(which.imp))) { warning("'which.imp' was specified but no 'imp' values were supplied. Ignoring 'which.imp'.", call. = FALSE) } in.cluster <- rep.int(TRUE, length(X$var)) if (is_not_null(X$cluster)) { if (is_null(which.cluster)) { in.cluster <- !is.na(X$cluster) facet <- c("cluster", facet) } else if (!all(is.na(which.cluster))) { if (is.numeric(which.cluster)) { if (all(which.cluster %in% seq_len(nlevels(X$cluster)))) { in.cluster <- !is.na(X$cluster) & X$cluster %in% levels(X$cluster)[which.cluster] } else { stop(paste0("The following inputs to 'which.cluster' do not correspond to given clusters:\n\t", word_list(which.cluster[!which.cluster %in% seq_len(nlevels(X$cluster))])), call. = FALSE) } } else if (is.character(which.cluster)) { if (all(which.cluster %in% levels(X$cluster))) { in.cluster <- !is.na(X$cluster) & X$cluster %in% which.cluster } else { stop(paste0("The following inputs to 'which.cluster' do not correspond to given clusters:\n\t", word_list(which.cluster[which.cluster %nin% levels(X$cluster)])), call. = FALSE) } } else stop("The argument to 'which.cluster' must be the names or indices corresponding to the clusters for which distributions are to be displayed.", call. = FALSE) facet <- c("cluster", facet) } } else if (is_not_null(which.cluster)) { warning("'which.cluster' was specified but no 'cluster' values were supplied. Ignoring 'which.cluster'.", call. = FALSE) } in.time <- rep.int(TRUE, length(X$var)) if (is_not_null(X$time)) { if (is_null(which.time) || all(is.na(which.time))) { in.time <- !is.na(X$time) } else { if (is.numeric(which.time)) { if (all(which.time %in% seq_along(X$covs.list))) { if (all(which.time %in% seq_along(X$covs.list)[appears.in.time])) { } else if (any(which.time %in% seq_along(X$covs.list)[appears.in.time])) { warning(paste0(var.name, " does not appear in time period ", word_list(which.time[!which.time %in% seq_along(X$covs.list)[appears.in.time]], "or"), "."), call. = FALSE) which.time <- which.time[which.time %in% seq_along(X$covs.list)[appears.in.time]] } else { stop(paste0(var.name, " does not appear in time period ", word_list(which.time, "or"), "."), call. = FALSE) } in.time <- !is.na(X$time) & X$time %in% which.time } else { stop(paste0("The following inputs to 'which.time' do not correspond to given time periods:\n\t", word_list(which.time[!which.time %in% seq_along(X$covs.list)])), call. = FALSE) } } else if (is.character(which.time)) { if (all(which.time %in% treat.names)) { if (all(which.time %in% treat.names[appears.in.time])) { } else if (any(which.time %in% treat.names[appears.in.time])) { time.periods <- word_list(which.time[!which.time %in% treat.names[appears.in.time]], "and") warning(paste0(var.name, " does not appear in the time period", ifelse(attr(time.periods, "plural"), "s ", " "), "corresponding to treatment", ifelse(attr(time.periods, "plural"), "s ", " "), time.periods, "."), call. = FALSE) which.time <- which.time[which.time %in% treat.names[appears.in.time]] } else { time.periods <- word_list(which.time, "and") stop(paste0(var.name, " does not appear in the time period", ifelse(attr(time.periods, "plural"), "s ", " "), "corresponding to treatment", ifelse(attr(time.periods, "plural"), "s ", " "), time.periods, "."), call. = FALSE) } in.time <- !is.na(X$time) & treat.names[X$time] %in% which.time } else { stop(paste0("The following inputs to 'which.time' do not correspond to given time periods:\n\t", word_list(which.time[!which.time %in% treat.names])), call. = FALSE) } } else stop("The argument to 'which.time' must be the names or indices corresponding to the time periods for which distributions are to be displayed.", call. = FALSE) } facet <- c("time", facet) } else if (is_not_null(which.time)) { warning("'which.time' was specified but a point treatment was supplied. Ignoring 'which.time'.", call. = FALSE) } nobs <- sum(in.imp & in.cluster & in.time) if (nobs == 0) stop("No observations to display.", call. = FALSE) Q <- make_list(which) for (i in which) { Q[[i]] <- make_df(c("treat", "var", "weights", "which"), nobs) Q[[i]]$treat <- X$treat[in.imp & in.cluster & in.time] Q[[i]]$var <- X$var[in.imp & in.cluster & in.time] Q[[i]]$weights <- X$weights[in.imp & in.cluster & in.time, i] Q[[i]]$which <- i if ("imp" %in% facet) Q[[i]]$imp <- factor(paste("Imputation", X$imp[in.imp & in.cluster & in.time])) if ("cluster" %in% facet) Q[[i]]$cluster <- factor(X$cluster[in.imp & in.cluster & in.time]) if ("time" %in% facet) Q[[i]]$time <- factor(paste("Time", X$time[in.imp & in.cluster & in.time])) } D <- do.call(rbind, Q) D$which <- factor(D$which, levels = which) if (is_not_null(sample.names)) { if (length(sample.names) == nadj) { levels(D$which)[levels(D$which) != "Unadjusted Sample"] <- sample.names } else if (length(sample.names) == ntypes) { levels(D$which) <- sample.names } } } else { if (is_not_null(X$cluster)) stop("Subclasses are not supported with clusters.", call. = FALSE) if (is_not_null(X$imp)) stop("Subclasses are not supported with multiple imputations.", call. = FALSE) if (!missing(sample.names)) { if (which %nin% c("both", "unadjusted")) { warning("'sample.names' can only be used with which = \"both\" or \"unadjusted\" to rename the unadjusted sample when called with subclasses. Ignoring 'sample.names'.", call. = FALSE) sample.names <- NULL } else if (!is.vector(sample.names, "character")) { warning("The argument to 'sample.names' must be a character vector. Ignoring 'sample.names'.", call. = FALSE) sample.names <- NULL } else if (length(sample.names) != 1) { warning("The argument to 'sample.names' must be of length 1 when called with subclasses. Ignoring 'sample.names'.", call. = FALSE) sample.names <- NULL } } else sample.names <- NULL sub.names <- levels(X$subclass) if (is_null(which.sub)) { which.sub <- sub.names } else { which.sub.original <- which.sub if (anyNA(which.sub)) which.sub <- which.sub[!is.na(which.sub)] if (is_null(which.sub)) { stop(paste0("The argument to 'which.sub' cannot be .none or NA when which = \"", which, "\"."), call. = FALSE) } else if (is.character(which.sub)) { which.sub <- which.sub[which.sub %in% sub.names] } else if (is.numeric(which.sub)) { which.sub <- sub.names[which.sub[which.sub %in% seq_along(sub.names)]] } if (is_null(which.sub)) { stop("The argument to 'which.sub' must be .none, .all, or the valid names or indices of subclasses.", call. = FALSE) } else if (any(which.sub.original %nin% which.sub)) { w.l <- word_list(which.sub.original[which.sub.original %nin% which.sub]) warning(paste(w.l, ifelse(attr(w.l, "plural"), "do", "does"), "not correspond to any subclass in the object and will be ignored."), call. = FALSE) } } in.sub <- !is.na(X$subclass) & X$subclass %in% which.sub D <- make_df(c("weights", "treat", "var", "subclass"), sum(in.sub)) D$weights <- 1 D$treat <- X$treat[in.sub] D$var <- X$var[in.sub] D$subclass <- paste("Subclass", X$subclass[in.sub]) if (which == "both") { D2 <- make_df(c("weights", "treat", "var", "subclass"), length(X$treat)) D2$weights <- 1 D2$treat <- X$treat D2$var <- X$var D2$subclass <- rep("Unadjusted Sample", length(X$treat)) D <- rbind(D2, D, stringsAsFactors = TRUE) D$subclass <- relevel(factor(D$subclass), "Unadjusted Sample") } facet <- "subclass" if (is_not_null(sample.names)) { levels(D$subclass)[levels(D$subclass) == "Unadjusted Sample"] <- sample.names } } treat.type <- get.treat.type(assign.treat.type(D$treat)) D <- na.omit(D[order(D$var),]) D <- D[D$weights > 0,] if (treat.type == "continuous") { if (is.categorical.var) { D$weights <- ave(D[["weights"]], D[c("var", facet)], FUN = function(x) x/sum(x)) } D$treat <- as.numeric(D$treat) if (is.categorical.var) { bw <- if_null_then(args$bw, "nrd0") adjust <- if_null_then(args$adjust, 1) kernel <- if_null_then(args$kernel, "gaussian") n <- if_null_then(args$n, 512) D$var <- factor(D$var) cat.sizes <- tapply(rep(1, NROW(D)), D$var, sum) smallest.cat <- names(cat.sizes)[which.min(cat.sizes)] if (is.character(bw)) { if (is.function(get0(paste0("bw.", bw)))) { bw <- get0(paste0("bw.", bw))(D$treat[D$var == smallest.cat]) } else { stop(paste(bw, "is not an acceptable entry to 'bw'. See ?stats::density for allowable options."), call. = FALSE) } } ntypes <- length(cat.sizes) if (is_not_null(args$colours)) colors <- args$colours if (is_null(colors)) { colors <- gg_color_hue(ntypes) } else { if (length(colors) > ntypes) { colors <- colors[seq_len(ntypes)] warning(paste("Only using first", ntypes, "values in 'colors'."), call. = FALSE) } else if (length(colors) < ntypes) { warning("Not enough colors were specified. Using default colors instead.", call. = FALSE) colors <- gg_color_hue(ntypes) } if (!all(vapply(colors, isColor, logical(1L)))) { warning("The argument to 'colors' contains at least one value that is not a recognized color. Using default colors instead.", call. = FALSE) colors <- gg_color_hue(ntypes) } } bp <- ggplot2::ggplot(D, mapping = aes(x = .data$treat, fill = .data$var, weight = .data$weights)) + ggplot2::geom_density(alpha = .4, bw = bw, adjust = adjust, kernel = kernel, n = n, trim = TRUE, outline.type = "full") + ggplot2::labs(fill = var.name, y = "Density", x = "Treat", title = title, subtitle = subtitle) + ggplot2::scale_fill_manual(values = colors) + ggplot2::geom_hline(yintercept = 0) + ggplot2::scale_y_continuous(expand = ggplot2::expansion(mult = c(0, .05))) } else { D$var.mean <- ave(D[["var"]], D[facet], FUN = mean) D$treat.mean <- ave(D[["treat"]], D[facet], FUN = mean) bp <- ggplot2::ggplot(D, mapping = aes(x = .data$var, y = .data$treat, weight = .data$weights)) if (identical(which, "Unadjusted Sample") || isFALSE(alpha.weight)) bp <- bp + ggplot2::geom_point(alpha = .9) else bp <- bp + ggplot2::geom_point(aes(alpha = .data$weights), show.legend = FALSE) + ggplot2::scale_alpha(range = c(.04, 1)) bp <- bp + ggplot2::geom_smooth(method = "lm", formula = y ~ x, se = FALSE, color = "firebrick2", alpha = .4, size = 1.5) + { if (nrow(D) <= 1000) ggplot2::geom_smooth(method = "loess", formula = y ~ x, se = FALSE, color = "royalblue1", alpha = .1, size = 1.5) else ggplot2::geom_smooth(method = "gam", formula = y ~ s(x, bs = "cs"), se = FALSE, color = "royalblue1", alpha = .1, size = 1.5) } + ggplot2::geom_hline(aes(yintercept = .data$treat.mean), linetype = 1, alpha = .9) + ggplot2::geom_vline(aes(xintercept = .data$var.mean), linetype = 1, alpha = .8) + ggplot2::labs(y = "Treat", x = var.name, title = title, subtitle = subtitle) } } else { D$treat <- factor(D$treat) if (is_null(which.treat)) which.treat <- character(0) else if (is.numeric(which.treat)) { which.treat <- levels(D$treat)[seq_along(levels(D$treat)) %in% which.treat] if (is_null(which.treat)) { warning("No numbers in 'which.treat' correspond to treatment values. All treatment groups will be displayed.", call. = FALSE) which.treat <- character(0) } } else if (is.character(which.treat)) { which.treat <- levels(D$treat)[levels(D$treat) %in% which.treat] if (is_null(which.treat)) { warning("No names in 'which.treat' correspond to treatment values. All treatment groups will be displayed.", call. = FALSE) which.treat <- character(0) } } else if (anyNA(which.treat)) { which.treat <- character(0) } else { warning("The argument to 'which.treat' must be NA, NULL, or a vector of treatment names or indices. All treatment groups will be displayed.", call. = FALSE) which.treat <- character(0) } if (is_not_null(which.treat) && !anyNA(which.treat)) D <- D[D$treat %in% which.treat,] for (i in names(D)[vapply(D, is.factor, logical(1L))]) D[[i]] <- factor(D[[i]]) D$weights <- ave(D[["weights"]], D[c("treat", facet)], FUN = function(x) x/sum(x)) ntypes <- nlevels.treat <- nlevels(D$treat) if (is_not_null(args$colours)) colors <- args$colours if (is_null(colors)) { colors <- gg_color_hue(ntypes) } else { if (length(colors) > ntypes) { colors <- colors[seq_len(ntypes)] warning(paste("Only using first", ntypes, "values in 'colors'."), call. = FALSE) } else if (length(colors) < ntypes) { warning("Not enough colors were specified. Using default colors instead.", call. = FALSE) colors <- gg_color_hue(ntypes) } if (!all(vapply(colors, isColor, logical(1L)))) { warning("The argument to 'colors' contains at least one value that is not a recognized color. Using default colors instead.", call. = FALSE) colors <- gg_color_hue(ntypes) } } names(colors) <- levels(D$treat) if (is_binary(D$var) || is.factor(D$var) || is.character(D$var)) { D$var <- factor(D$var) bp <- ggplot2::ggplot(D, mapping = aes(x = .data$var, fill = .data$treat, weight = .data$weights)) + ggplot2::geom_bar(position = "dodge", alpha = .8, color = "black") + ggplot2::labs(x = var.name, y = "Proportion", fill = "Treatment", title = title, subtitle = subtitle) + ggplot2::scale_x_discrete(drop=FALSE) + ggplot2::scale_fill_manual(drop=FALSE, values = colors) + ggplot2::geom_hline(yintercept = 0) + ggplot2::scale_y_continuous(expand = ggplot2::expansion(mult = c(0, .05))) } else { type <- match_arg(type, c("histogram", "density", "ecdf")) if (type %in% c("ecdf")) { mirror <- FALSE alpha <- 1 legend.alpha <- alpha expandScale <- ggplot2::expansion(mult = .005) } else if (nlevels.treat <= 2 && isTRUE(mirror)) { posneg <- c(1, -1) alpha <- .8 legend.alpha <- alpha expandScale <- ggplot2::expansion(mult = .05) } else { mirror <- FALSE posneg <- rep(1, nlevels.treat) alpha <- .4 legend.alpha <- alpha/nlevels.treat expandScale <- ggplot2::expansion(mult = c(0, .05)) } if (type == "histogram") { if (isTRUE(disp.means)) { D$var.mean <- ave(D[c("var", "weights")], D[c("treat", facet)], FUN = function(x) w.m(x[[1]], x[[2]]))[[1]] } if (!is_(args$bins, "numeric")) args$bins <- 12 geom_fun <- function(t) { out <- list(ggplot2::geom_histogram(data = D[D$treat == levels(D$treat)[t],], mapping = aes(x = .data$var, y = posneg[t]*ggplot2::after_stat(!!sym("count")), weight = .data$weights, fill = names(colors)[t]), alpha = alpha, bins = args$bins, color = "black"), NULL) if (isTRUE(disp.means)) out[[2]] <- ggplot2::geom_segment(data = unique(D[D$treat == levels(D$treat)[t], c("var.mean", facet), drop = FALSE]), mapping = aes(x = .data$var.mean, xend = .data$var.mean, y = 0, yend = posneg[t]*Inf), color = if (isTRUE(mirror)) "black" else colors[[t]]) return(clear_null(out)) } ylab <- "Proportion" } else if (type %in% c("ecdf")) { D$cum.pt <- ave(D[["weights"]], D[c("treat", facet)], FUN = function(x) cumsum(x)/sum(x)) extra <- setNames(do.call(expand.grid, c(list(c("top", "bottom")), lapply(c("treat", facet), function(i) levels(D[[i]])))), c("pos_", "treat", facet)) merge.extra <- data.frame(pos_ = c("top", "bottom"), var = c(-Inf, Inf), cum.pt = c(0, 1)) extra <- merge(extra, merge.extra) extra[["pos_"]] <- NULL D[names(D) %nin% names(extra)] <- NULL D <- rbind(extra[names(D)], D) geom_fun <- function(t) { ggplot2::geom_step(data = D[D$treat == levels(D$treat)[t],], mapping = aes(x = .data$var, y = .data$cum.pt, color = names(colors)[t])) } ylab <- "Cumulative Proportion" } else { bw <- if_null_then(args$bw, "nrd0") adjust <- if_null_then(args$adjust, 1) kernel <- if_null_then(args$kernel, "gaussian") n <- if_null_then(args$n, 512) if (is.character(bw)) { t.sizes <- tapply(rep(1, NROW(D)), D$treat, sum) smallest.t <- names(t.sizes)[which.min(t.sizes)] if (is.function(get0(paste0("bw.", bw)))) { bw <- get0(paste0("bw.", bw))(D$var[D$treat == smallest.t]) } else { stop(paste(bw, "is not an acceptable entry to 'bw'. See ?stats::density for allowable options."), call. = FALSE) } } if (isTRUE(disp.means)) { D$var.mean <- ave(D[c("var", "weights")], D[c("treat", facet)], FUN = function(x) w.m(x[[1]], x[[2]]))[[1]] } geom_fun <- function(t) { out <- list( ggplot2::geom_density(data = D[D$treat == levels(D$treat)[t],], mapping = aes(x = .data$var, y = posneg[t]*ggplot2::after_stat(!!sym("density")), weight = .data$weights, fill = names(colors)[t]), alpha = alpha, bw = bw, adjust = adjust, kernel = kernel, n = n, trim = TRUE, outline.type = "full"), NULL) if (isTRUE(disp.means)) out[[2]] <- ggplot2::geom_segment(data = unique(D[D$treat == levels(D$treat)[t], c("var.mean", facet), drop = FALSE]), mapping = aes(x = .data$var.mean, xend = .data$var.mean, y = 0, yend = posneg[t]*Inf), color = if (isTRUE(mirror)) "black" else colors[[t]]) return(clear_null(out)) } ylab <- "Density" } bp <- Reduce("+", c(list(ggplot2::ggplot()), lapply(seq_len(nlevels.treat), geom_fun))) + ggplot2::scale_fill_manual(values = colors, guide = ggplot2::guide_legend(override.aes = list(alpha = legend.alpha, size = .25))) + ggplot2::scale_color_manual(values = colors) + ggplot2::labs(x = var.name, y = ylab, title = title, subtitle = subtitle, fill = "Treatment", color = "Treatment") + ggplot2::scale_y_continuous(expand = expandScale) if (isTRUE(mirror)) bp <- bp + ggplot2::geom_hline(yintercept = 0) } } bp <- bp + ggplot2::theme(panel.background = element_rect(fill = "white", color = "black"), panel.border = element_rect(fill = NA, color = "black"), plot.background = element_blank(), legend.position = position, legend.key=element_rect(fill = "white", color = "black", size = .25)) if (!isTRUE(grid)) { bp <- bp + ggplot2::theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) } else { bp <- bp + ggplot2::theme(panel.grid.major = element_line(color = "gray87"), panel.grid.minor = element_line(color = "gray90")) } if (is_not_null(facet)) { if (is_not_null(facet.formula)) { if (!rlang::is_formula(facet.formula)) { stop("'facet.formula' must be a formula.", call. = FALSE) } test.facet <- invisible(ggplot2::facet_grid(facet.formula)) if (any(c(names(test.facet$params$rows), names(test.facet$params$cols)) %nin% facet)) { stop(paste("Only", word_list(facet, is.are = TRUE, quotes = 2), "allowed in 'facet.formula'."), call. = FALSE) } if ("which" %nin% c(names(test.facet$params$rows), names(test.facet$params$cols))) { if (length(which) > 1) stop("\"which\" must be in the facet formula when the which argument refers to more than one sample.", call. = FALSE) else message(paste0("Displaying balance for the ", if (which %in% c("Adjusted Sample", "Unadjusted Sample")) tolower(which) else paste(which, "sample"), ".")) } } else if (length(facet) >= 2) { if ("which" %in% facet) { facet.formula <- f.build(facet[facet %nin% "which"], "which") } else if ("imp" %in% facet) { facet.formula <- f.build("imp", facet[facet %nin% "imp"]) } else { facets <- data.frame(facet = facet, length = vapply(facet, function(x) nlevels(D[[x]]), numeric(1L)), stringsAsFactors = FALSE) facets <- facets[with(facets, order(length, facet, decreasing = c(FALSE, TRUE))), ] facet.formula <- formula(facets) } } else facet.formula <- f.build(".", facet) bp <- bp + ggplot2::facet_grid(facet.formula, drop = FALSE, scales = ifelse("subclass" %in% facet, "free_x", "fixed")) } return(bp) }
individuals_stats_per_game <- function(df1){ df1 <- df1[-nrow(df1),] for(i in 4:ncol(df1)){ if(i==7 || i==10 || i==13 || i==16){ df1[i] <- round(df1[i],3) } else{ df1[i] <- round(df1[i] / df1[2],2) } } names(df1) <- c("Name","G","GS","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%", "ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-") df1[is.na(df1)] <- 0 return(df1) }
gbt.ksval <- function(object, y, x) { error_messages <- c() error_messages_type <- c( "object_type" = "Error: object must be a GBTorch ensemble \n", "model_not_trained" = "Error: GBTorch ensemble must be trained, see function documentation gbt.train \n", "response_not_vec" = "Error: y must be a vector of type numeric or matrix with dimension 1 \n", "dmat_not_mat" = "Error: x must be a matrix \n", "y_x_correspondance" = "Error: length of y must correspond to the number of rows in x \n" ) if(class(object)!="Rcpp_ENSEMBLE"){ error_messages <- c(error_messages, error_messages_type["object_type"]) }else{ if(object$get_num_trees()==0) error_messages <- c(error_messages, error_messages_type["model_not_trained"]) } if(!is.vector(y, mode="numeric")){ if(is.matrix(y) && ncol(y)>1 ){ error_messages <- c(error_messages, error_messages_type["response_not_vec"]) } } if(!is.matrix(x)) error_messages <- c(error_messages, error_messages_type["dmat_not_mat"]) if(length(y) != nrow(x)) error_messages <- c(error_messages, error_messages_type["y_x_correspondance"]) if(length(error_messages)>0) stop(error_messages) loss_type <- object$get_loss_function() mu_pred <- predict(object, x) n <- length(y) u <- numeric(n) if(loss_type == "mse") { msg1 <- c("Gaussian regression \n") msg2 <- c("Assuming constant variance \n") lsigma <- 0.0 lsigma <- stats::nlminb(lsigma, nll_norm, y=y, mu_pred=mu_pred)$par msg3 <- c("Variance estimate is: ", exp(2*lsigma), "\n") message(msg1, msg2, msg3) u <- pnorm(y, mean=mu_pred, sd=exp(lsigma)) }else if(loss_type %in% c("gamma::neginv", "gamma::log")) { msg1 <- c("Gamma regression \n") msg2 <- c("Assuming constant shape \n") lshape <- 0.0 lshape <- stats::nlminb(lshape, nll_gamma, y=y, mu_pred=mu_pred)$par msg3 <- c("Shape estimate is: ", exp(lshape), "\n") message(msg1, msg2, msg3) u <- pgamma(y, shape=exp(lshape), scale=mu_pred/exp(lshape)) }else if(loss_type == "negbinom") { msg1 <- c("Overdispersed count (negative binomial) regression \n") msg2 <- c("Assuming constant dispersion \n") ldisp <- 0.0 ldisp <- stats::nlminb(ldisp, nll_nbinom, y=y, mu_pred=mu_pred)$par msg3 <- c("Dispersion estimate is: ", exp(ldisp), "\n") message(msg1, msg2, msg3) u <- unbinom(y, mu=mu_pred, dispersion=exp(ldisp)) }else if(loss_type == "poisson") { message("Count (Poisson) regression \n") u <- upois(y, lambda=mu_pred) }else if(loss_type == "logloss") { message("Classification \n") u <- ubernoulli(y, p=mu_pred) } res <- ks.test(u, "punif") hist(u, freq=FALSE, oma=c(2, 3, 5, 2)+0.1, main=NULL, xlab="CDF transformed observations") mytitle="Histogram: Model-CDF transformed observations" mysubtitle=paste0(res$method, ": ", format(res$p.value)) mtext(side=3, line=2.2, at=-0.07, adj=0, cex=1.1, mytitle) mtext(side=3, line=1.2, at=-0.07, adj=0, cex=0.8, mysubtitle) return(res) } nll_nbinom <- function(ldisp, y, mu_pred) { disp <- exp(ldisp) -sum(dnbinom(y, size=disp, mu=mu_pred, log=TRUE)) } nll_norm <- function(lsigma, y, mu_pred) { sigma <- exp(lsigma) -sum(dnorm(y, mean=mu_pred, sd=sigma, log=TRUE)) } nll_gamma <- function(lshape, y, mu_pred) { shape <- exp(lshape) scale <- mu_pred / shape -sum(dgamma(y, shape=shape, scale=scale, log=TRUE)) } unbinom <- function(X, mu, dispersion) { n <- length(X) U <- rep(0,n) v <- runif(n) for(i in 1:n){ U[i] <- pnbinom(X[i]-1, size=dispersion, mu=mu[i]) + v[i]*dnbinom(X[i], size=dispersion, mu=mu[i]) } ind0 <- U==0 U[ind0] <- U[ind0] + 1e-9*runif(1) ind1 <- U==1 U[ind1] <- U[ind1] - 1e-9*runif(1) return(U) } upois <- function(X, lambda){ n <- length(X) U <- rep(0, n) v <- runif(n) for(i in 1:n) { U[i] <- ppois(X[i]-1, lambda[i]) + v[i]*dpois(X[i], lambda[i]) } ind0 <- U==0 U[ind0] <- U[ind0] + 1e-9*runif(1) ind1 <- U==1 U[ind1] <- U[ind1] - 1e-9*runif(1) return(U) } ubernoulli <- function(X, p) { n <- length(X) U <- pbinom(X-1, 1, p) + runif(n)*dbinom(X, 1, p) return(U) }
makeMAXdata <- function(x, data = NULL, effDuration = NULL, trace = 0) { flag <- FALSE blockNames <- NULL dataNames <- NULL if (missing(data)) { if ( is(x, "Rendata") && !is.null(x$MAXdata) ) { vn <- x$info$varName if (trace) cat("using 'MAXdata' within a 'Rendata' object\n") effDuration <- x$MAXinfo$duration block <- factor(x$MAXdata$block, levels = 1L:nrow(x$MAXinfo)) data <- tapply(x$MAXdata[ , vn], x$MAXdata$block, list) if (length(effDuration) != length(data)) stop("in object 'x', elements 'MAXinfo' and 'MAXdata' do not have ", "the same number of blocks") flag <- TRUE if ( !is.null(x$MAXinfo$comment) && all(nchar(as.character(x$MAXinfo$comment)) > 0L) ){ blockNames <- as.character(x$MAXinfo$comment) } else if (!any(is.na(x$MAXinfo$start)) && !any(is.na(x$MAXinfo$end))) { blockNames <- paste(formatPeriod(start = x$MAXinfo$start, end = x$MAXinfo$end), "(MAX)") } else blockNames <- paste("MAX block", 1L:nrow(x$MAXinfo)) if ( !is.null(x$MAXdata$comment) && any(nchar(as.character(x$MAXdata$comment)) > 0L) ){ dataNames <- as.character(x$MAXdata$comment) } else if (!any(is.na(x$MAXdata$date))) { dataNames <- format(x$MAXdata$date, "%Y-%m-%d") } else dataNames <- rep("", nrow(x$MAXdata)) } else { flag <- FALSE block <- NULL effDuration <- NULL threshold <- NULL r <- NULL } } else { if (is.null(data)) { flag <- FALSE block <- NULL effDuration <- NULL threshold <- NULL; r <- NULL } else if (is.list(data)) { if (length(data) != length(effDuration)) stop("when 'data' is a list, 'effDuration' must be a numeric ", "vector of length length(data)") blockNames <- names(data) if (is.null(blockNames)) blockNames <- paste("MAX block", 1L:length(data)) r <- unlist(lapply(data, length)) block <- factor(rep(1:length(data), times = r), levels = 1:length(data)) dataNames <- lapply(data, fillNames) flag <- TRUE } else { if (length(effDuration) != 1L) stop("when 'data' is a vector, 'effDuration' must be a numeric ", "with length 1") block <- factor(rep(1L, times = length(data)), levels = 1) r <- length(data) dataNames <- fillNames(data) blockNames <- "MAX block1" data <- list("MAX block 1" = data) flag <- TRUE } } if (!flag) { block <- NULL effDuration <- NULL r <- NULL } else { r <- unlist(lapply(data, length)) names(effDuration) <- names(r) <- paste("block", 1L:length(effDuration)) } list(flag = flag, block = block, blockNames = blockNames, effDuration = effDuration, r = r, data = data, dataNames = dataNames) } makeOTSdata <- function(x, data = NULL, effDuration = NULL, threshold = NULL, trace = 0) { flag <- FALSE blockNames <- NULL dataNames <- NULL if (missing(data)) { if ( is(x, "Rendata") && !is.null(x$OTSdata) ) { vn <- x$info$varName if (trace) cat("using 'OTSdata' within a 'Rendata' object\n") effDuration <- x$OTSinfo$duration threshold <- x$OTSinfo$threshold r <- x$OTSinfo$r block <- factor(x$OTSdata$block, levels = 1:nrow(x$OTSinfo)) data <- tapply(x$OTSdata[ , vn], block, as.numeric) data <- lapply(data, function(x) as.numeric(x)) ind <- (table(block) == 0) if (any(ind)) { for (i in (1L:length(data))[ind]) data[[i]] <- numeric(0) } flag <- TRUE if ( !is.null(x$OTSinfo$comment) && all(nchar(as.character(x$OTSinfo$comment)) > 0L) ){ blockNames <- as.character(x$OTSinfo$comment) } else if (!any(is.na(x$OTSinfo$start)) && !any(is.na(x$OTSinfo$end))) { blockNames <- paste(formatPeriod(start = x$OTSinfo$start, end = x$OTSinfo$end), "(OTS)") } else blockNames <- paste("OTS block", 1L:nrow(x$OTSinfo)) if ( !is.null(x$OTSdata$comment) && any(nchar(as.character(x$OTSdata$comment)) > 0L) ){ dataNames <- as.character(x$OTSdata$comment) } else if (!any(is.na(x$OTSdata$date))) { dataNames <- format(x$OTSdata$date, "%Y-%m-%d") } else dataNames <- rep("", nrow(x$OTSdata)) } else { if (trace) cat("'x' not of class 'Rendata': ignored\n") flag <- FALSE } } else { if (is.null(data)) { flag <- FALSE block <- NULL; effDuration <- NULL threshold <- NULL; r <- NULL } else if (is.list(data)) { if ( (length(data) != length(effDuration)) || (length(data) != length(threshold)) ) stop("when 'data' is a list, 'effDuration' and 'threshold' must be a ", "numeric vector of length length(data)") blockNames <- names(data) if (is.null(blockNames)) blockNames <- paste("OTS block", 1L:length(data)) r <- unlist(lapply(data, length)) block <- factor(rep(1L:length(data), times = r), levels = 1L:length(data)) dataNames <- lapply(data, fillNames) flag <- TRUE } else { if ((length(effDuration) != 1) || (length(threshold) != 1L)) stop("when 'data' is a vector, 'effDuration' and 'threshold' must be ", "numeric with length 1") r <- length(data) block <- factor(1L, levels = 1) dataNames <- fillNames(data) blockNames <- "OTS block1" data <- list("OTS block1" = data) flag <- TRUE } } if (!flag) { block <- NULL effDuration <- NULL threshold <- NULL r <- NULL } else { names(effDuration) <- names(r) <- names(threshold) <- paste("block", 1:length(effDuration)) } list(flag = flag, block = block, blockNames = blockNames, effDuration = effDuration, threshold = threshold, r = r, data = data, dataNames = dataNames) } plot.Rendata <- function(x, textOver = quantile(x$OTdata[, x$info$varName], probs = 0.99), showHist = TRUE, ...) { block <- 1 periodsLeg <- c("OTdata", "OTSdata", "MAXdata") periodsBg <- c("lightcyan", "lightyellow", "DarkOliveGreen1") names(periodsBg) <- periodsLeg periodsFg <- c("cyan", "gold", "DarkOliveGreen2") names(periodsFg) <- periodsLeg periodsFlag <- c(TRUE, FALSE, FALSE) names(periodsFlag) <- periodsLeg y <- x$OTdata[ , x$info$varName] start <- as.POSIXct(x$OTinfo$start) end <- as.POSIXct(x$OTinfo$end) ymin <- x$OTinfo$threshold ymax <- max(y) if (showHist) { if (!is.null(x$OTSinfo)) { OTSstart <- as.POSIXct(x$OTSinfo$start) OTSend <- as.POSIXct(x$OTSinfo$start) start <- min(start, OTSstart) end <- max(end, OTSend) if (!is.null(x$OTSdata)) { ymin <- min(ymin, min(x$OTSdata[ , x$info$varName])) ymax <- max(ymax, max(x$OTSdata[ , x$info$varName])) } } if (!is.null(x$MAXinfo)) { MAXstart <- as.POSIXct(x$MAXinfo$start) MAXend <- as.POSIXct(x$MAXinfo$start) start <- min(start, MAXstart) end <- max(end, MAXend) ymin <- min(ymin, min(x$MAXdata[ , x$info$varName])) ymax <- max(ymax, max(x$MAXdata[ , x$info$varName])) } } yLab <- x$info$varName if (!is.null(x$info$varUnit)) yLab <- paste(yLab, " (", x$info$varUnit, ")", sep = "") plot(x = x$OTdata[ , "date"], y = x$OTdata[ , x$info$varName], type ="n", xlim = c(start, end), ylim = c(ymin, ymax), xlab = " ", ylab = yLab, main = x$info$longLab, ...) rg <- par()$usr[3:4] drg <- rg[2]-rg[1] rg <- rg + c(drg, -drg)/100 rect(xleft = x$OTinfo$start, xright = x$OTinfo$end, ybottom = rg[1], ytop = rg[2], col = periodsBg["OTdata"], border = periodsFg["OTdata"]) if (!is.null(x$OTmissing)) { for (i in 1:nrow(x$OTmissing)) { polygon(x = c(x$OTmissing$start[i], x$OTmissing$end[i], x$OTmissing$end[i], x$OTmissing$start[i]), y = rep(rg, each = 2), border = periodsBg["OTdata"], col = "white") } } lines(x = x$OTdata[ , "date"], y = x$OTdata[ , x$info$varName], type ="h", col = "SteelBlue3") lines(x = as.POSIXct(c(x$OTinfo$start, x$OTinfo$end)), y = rep(as.numeric(x$OTinfo$threshold), times = 2), col = "orange", lwd = 2) if (!is.na(textOver)){ ind <- (x$OTdata[, x$info$varName] > textOver) if (any(ind)) { points(x = x$OTdata[ind, "date"], y = x$OTdata[ind, x$info$varName], pch = 21, cex = 0.7, col = "SteelBlue4") text(x = x$OTdata[ind, "date"], y = x$OTdata[ind, x$info$varName], labels = format(x$OTdata[ind, "date"], "%Y-%m-%d"), col = "SteelBlue4", pos = 4, cex = 0.7) } } if (showHist && !is.null(x$OTSinfo)) { periodsFlag["OTSdata"] <- TRUE for (i in 1:nrow(x$OTSinfo)) { rect(xleft = x$OTSinfo$start[i], xright = x$OTSinfo$end[i], ybottom = rg[1], ytop = rg[2], col = periodsBg["OTSdata"], border = periodsFg["OTSdata"]) lines(x = as.POSIXct(c(x$OTSinfo$start[i], x$OTSinfo$end[i])), y = rep(x$OTSinfo$threshold[i], times = 2), col = "orange", lwd = 2) } if (!is.null(x$OTSdata)) { for (i in 1:nrow(x$OTSinfo)) { datai <- subset(x$OTSdata, block == i) ind <- !is.na(datai[ , "date"]) if (any(ind)) { lines(x = datai[ind, "date"], y = datai[ind, x$info$varName], type ="h", col = "red3") } if (any(!ind)) { segments(x0 = rep(x$OTSinfo$start[i], sum(!ind)), x1 = rep(x$OTSinfo$end[i], sum(!ind)), y0 = datai[!ind , x$info$varName], y1 = datai[!ind , x$info$varName], lty = "dashed", col = "red3") } } if (!is.na(textOver)){ ind <- (x$OTSdata[ , x$info$varName] > textOver) & !is.na(x$OTSdata[ , "date"]) if (any(ind)) { points(x = x$OTSdata[ind, "date"], y = x$OTSdata[ind, x$info$varName], pch = 21, cex = 0.7, col = "red3") text(x = x$OTSdata[ind, "date"], y = x$OTSdata[ind, x$info$varName], labels = format(x$OTSdata[ind, "date"], "%Y-%m-%d"), col = "red3", pos = 4, cex = 0.7) } } } } if (showHist && !is.null(x$MAXinfo)) { periodsFlag["MAXdata"] <- TRUE if (!is.null(x$MAXdata)) { for (i in 1:nrow(x$MAXinfo)) { rect(xleft = x$MAXinfo$start[i], xright = x$MAXinfo$end[i], ybottom = rg[1], ytop = rg[2], col = periodsBg["MAXdata"], border = periodsFg["MAXdata"]) datai <- subset(x$MAXdata, block == i) ind <- !is.na(datai[ , "date"]) if (any(ind)) { lines(x = datai[ind, "date"], y = datai[ind, x$info$varName], type ="h", col = "SpringGreen4") } if (any(!ind)) { segments(x0 = rep(x$MAXinfo$start[i], sum(!ind)), x1 = rep(x$MAXinfo$end[i], sum(!ind)), y0 = datai[!ind , x$info$varName], y1 = datai[!ind , x$info$varName], lty = "dashed", col = "SpringGreen4") } } if (!is.na(textOver)){ ind <- (x$MAXdata[ , x$info$varName] > textOver) & !is.na(x$MAXdata[ , "date"]) if (any(ind)) { points(x = x$MAXdata[ind, "date"], y = x$MAXdata[ind, x$info$varName], pch = 21, cex = 0.7, col = "SpringGreen4") text(x = x$MAXdata[ind, "date"], y = x$MAXdata[ind, x$info$varName], labels = format(x$MAXdata[ind, "date"], "%Y-%m-%d"), col = "SpringGreen4", pos = 4, cex = 0.7) } } } } legend("topleft", fill = periodsBg[periodsFlag], col = periodsFg[periodsFlag], legend = periodsLeg[periodsFlag]) } summary.Rendata <- function(object, ...) { ans <- list(info = object$info, OTinfo = object$OTinfo, MAXinfo = object$MAXinfo, OTSinfo = object$OTSinfo) ans$info <- paste(sprintf("o Dataset %s", object$info$shortLab), sprintf(" data '%s', variable '%s' (%s)", object$info$name, object$info$varName, object$info$varUnit), sep = "\n") ans$OTinfo <- paste("o OT data (main sample)", "from ", format(object$OTinfo$start, "%Y-%m-%d"), " to ", format(object$OTinfo$end, "%Y-%m-%d"), sprintf(" (eff. dur. %6.2f years)\n", object$OTinfo$effDuration)) var <- object$OTdata[ , object$info$varName] ans$OTsummary <- c(n = length(var), summary(var)) if (!is.null(object$OTmissing)) { dur <- as.numeric(as.POSIXct(object$OTmissing$end) - as.POSIXct(object$OTmissing$start), units = "days") ans$OTmissing <- sprintf("o missing 'OT' periods, total %5.2f years", sum(dur)/365.25) ans$OTmissingsummary <- c(n = length(dur), summary(dur/365.25)) } else { ans$OTmissing <- "o no missing OT periods" ans$OTmissingsummary <- NULL } if (!is.null(object$MAXinfo)) { ans$MAXinfo <- sprintf("o 'MAX' historical info: %d blocks, %d obs., total duration = %5.2f years", nrow(object$MAXinfo), nrow(object$MAXdata), sum(object$MAXinfo$duration)) } else ans$MAXinfo <- "o no 'MAX' historical data" if (!is.null(object$OTSinfo)) { ans$OTSinfo <- sprintf("o 'OTS' historical info: %d blocks, %d obs., total duration = %5.2f years", nrow(object$OTSinfo), nrow(object$OTSdata), sum(object$OTSinfo$duration)) } else ans$OTSinfo <- "o no 'OTS' historical data" class(ans) <- "summary.Rendata" ans } print.summary.Rendata <- function(x, ...) { cat(x$info, "\n") cat("\n") cat(x$OTinfo, "\n") print(x$OTsummary) cat("\n") cat(x$OTmissing, "\n\n") if (!is.null(x$OTmissingsummary)){ print(x$OTmissingsummary) cat("\n") } cat(x$MAXinfo, "\n\n") cat(x$OTSinfo, "\n\n") } print.Rendata <- function(x, ...) { print(summary(x, ...)) }
test_that("special characters are escaped", { out <- rd2html("a & b") expect_equal(out, "a &amp; b") }) test_that("simple tags translated to known good values", { expect_equal(rd2html("\\ldots"), "...") expect_equal(rd2html("\\dots"), "...") expect_equal(rd2html("\\R"), "<span style=\"R\">R</span>") expect_equal(rd2html("\\cr"), "<br />") "Macros" expect_equal(rd2html("\\newcommand{\\f}{'f'} \\f{}"), "'f'") expect_equal(rd2html("\\renewcommand{\\f}{'f'} \\f{}"), "'f'") }) test_that("comments converted to html", { expect_equal(rd2html("a\n%b\nc"), c("a", "<!-- %b -->", "c")) }) test_that("simple wrappers work as expected", { expect_equal(rd2html("\\strong{x}"), "<strong>x</strong>") expect_equal(rd2html("\\strong{\\emph{x}}"), "<strong><em>x</em></strong>") }) test_that("subsection generates h3", { expect_snapshot(cat_line(rd2html("\\subsection{A}{B}"))) }) test_that("subsection generates h3", { expect_snapshot(cat_line(rd2html("\\subsection{A}{ p1 p2 }"))) }) test_that("subsection generates generated anchor", { text <- c("<body>", rd2html("\\subsection{A}{B}"), "</body>") html <- xml2::read_xml(paste0(text, collapse = "\n")) tweak_anchors(html) expect_equal(xpath_attr(html, ".//h3", "id"), "a") expect_equal(xpath_attr(html, ".//a", "href"), " }) test_that("nested subsection generates h4", { expect_snapshot(cat_line(rd2html("\\subsection{H3}{\\subsection{H4}{}}"))) }) test_that("if generates html", { expect_equal(rd2html("\\if{html}{\\bold{a}}"), "<b>a</b>") expect_equal(rd2html("\\if{latex}{\\bold{a}}"), character()) }) test_that("ifelse generates html", { expect_equal(rd2html("\\ifelse{html}{\\bold{a}}{x}"), "<b>a</b>") expect_equal(rd2html("\\ifelse{latex}{x}{\\bold{a}}"), "<b>a</b>") }) test_that("out is for raw html", { expect_equal(rd2html("\\out{<hr />}"), "<hr />") }) test_that("support platform specific code", { os_specific <- function(command, os, output) { rd2html(paste0( " output, "\n", " )) } expect_equal(os_specific("ifdef", "windows", "X"), character()) expect_equal(os_specific("ifdef", "unix", "X"), "X") expect_equal(os_specific("ifndef", "windows", "X"), "X") expect_equal(os_specific("ifndef", "unix", "X"), character()) }) test_that("tabular genereates complete table html", { table <- "\\tabular{ll}{a \\tab b \\cr}" expectation <- c("<table class='table'>", "<tr><td>a</td><td>b</td></tr>", "</table>") expect_equal(rd2html(table), expectation) }) test_that("internal \\crs are stripped", { table <- "\\tabular{l}{a \\cr b \\cr c \\cr}" expectation <- c("<table class='table'>", "<tr><td>a</td></tr>", "<tr><td>b</td></tr>", "<tr><td>c</td></tr>", "</table>") expect_equal(rd2html(table), expectation) }) test_that("can convert single row", { expect_equal( rd2html("\\tabular{lll}{A \\tab B \\tab C \\cr}")[[2]], "<tr><td>A</td><td>B</td><td>C</td></tr>" ) }) test_that("don't need internal whitespace", { expect_equal( rd2html("\\tabular{lll}{\\tab\\tab C\\cr}")[[2]], "<tr><td></td><td></td><td>C</td></tr>" ) expect_equal( rd2html("\\tabular{lll}{\\tab B \\tab\\cr}")[[2]], "<tr><td></td><td>B</td><td></td></tr>" ) expect_equal( rd2html("\\tabular{lll}{A\\tab\\tab\\cr}")[[2]], "<tr><td>A</td><td></td><td></td></tr>" ) expect_equal( rd2html("\\tabular{lll}{\\tab\\tab\\cr}")[[2]], "<tr><td></td><td></td><td></td></tr>" ) }) test_that("can skip trailing \\cr", { expect_equal( rd2html("\\tabular{lll}{A \\tab B \\tab C}")[[2]], "<tr><td>A</td><td>B</td><td>C</td></tr>" ) }) test_that("code blocks in tables render ( expect_equal( rd2html('\\tabular{ll}{a \\tab \\code{b} \\cr foo \\tab bar}')[[2]], "<tr><td>a</td><td><code>b</code></td></tr>" ) }) test_that("tables with tailing \n ( expect_equal( rd2html(' \\tabular{ll}{ a \\tab \\cr foo \\tab bar } ')[[2]], "<tr><td>a</td><td></td></tr>" ) }) test_that("code inside Sexpr is evaluated", { local_context_eval() expect_equal(rd2html("\\Sexpr{1 + 2}"), "3") }) test_that("can control \\Sexpr output", { local_context_eval() expect_equal(rd2html("\\Sexpr[results=hide]{1}"), character()) expect_equal(rd2html("\\Sexpr[results=text]{1}"), "1") expect_equal(rd2html("\\Sexpr[results=rd]{\"\\\\\\emph{x}\"}"), "<em>x</em>") }) test_that("Sexpr can contain multiple expressions", { local_context_eval() expect_equal(rd2html("\\Sexpr{a <- 1; a}"), "1") }) test_that("Sexprs with multiple args are parsed", { local_context_eval() expect_equal(rd2html("\\Sexpr[results=hide,stage=build]{1}"), character()) }) test_that("Sexprs with multiple args are parsed", { local_context_eval() expect_error(rd2html("\\Sexpr[results=verbatim]{1}"), "not yet supported") }) test_that("Sexprs in file share environment", { local_context_eval() expect_equal(rd2html("\\Sexpr{x <- 1}\\Sexpr{x}"), c("1", "1")) local_context_eval() expect_error(rd2html("\\Sexpr{x}"), "not found") }) test_that("Sexprs run from package root", { local_context_eval(src_path = test_path("assets/reference")) expect_equal( rd2html("\\packageTitle{testpackage}"), "A test package" ) }) test_that("DOIs are linked", { skip_if(getRversion() <= "3.6.0") local_context_eval(src_path = test_path("assets/reference")) expect_snapshot(rd2html("\\doi{test}")) }) test_that("simple links generate <a>", { expect_equal( rd2html("\\href{http://bar.com}{BAR}"), "<a href='http://bar.com'>BAR</a>" ) expect_equal( rd2html("\\email{[email protected]}"), "<a href='mailto:[email protected]'>[email protected]</a>" ) expect_equal( rd2html("\\url{http://bar.com}"), "<a href='http://bar.com'>http://bar.com</a>" ) }) test_that("can convert cross links to online documentation url", { expect_equal( rd2html("\\link[base]{library}"), a("library", href = "https://rdrr.io/r/base/library.html") ) }) test_that("can convert cross links to the same package ( withr::local_options(list( "downlit.package" = "test", "downlit.topic_index" = c(x = "y", z = "z"), "downlit.rdname" = "z" )) expect_equal(rd2html("\\link{x}"), "<a href='y.html'>x</a>") expect_equal(rd2html("\\link[test]{x}"), "<a href='y.html'>x</a>") expect_equal(rd2html("\\link[test]{z}"), "z") }) test_that("can parse local links with topic!=label", { withr::local_options(list( "downlit.topic_index" = c(x = "y") )) expect_equal(rd2html("\\link[=x]{z}"), "<a href='y.html'>z</a>") }) test_that("functions in other packages generates link to rdrr.io", { withr::local_options(list( "downlit.package" = "test", "downlit.topic_index" = c(x = "y", z = "z") )) expect_equal( rd2html("\\link[stats:acf]{xyz}"), a("xyz", downlit::href_topic("acf", "stats")) ) expect_equal(rd2html("\\link[test:x]{xyz}"), "<a href='y.html'>xyz</a>") }) test_that("link to non-existing functions return label", { expect_equal(rd2html("\\link[xyzxyz:xyzxyz]{abc}"), "abc") expect_equal(rd2html("\\link[base:xyzxyz]{abc}"), "abc") }) test_that("code blocks autolinked to vignettes", { withr::local_options(list( "downlit.package" = "test", "downlit.article_index" = c("abc" = "abc.html") )) expect_equal( rd2html("\\code{vignette('abc')}"), "<code><a href='abc.html'>vignette('abc')</a></code>" ) }) test_that("link to non-existing functions return label", { withr::local_options(list( "downlit.package" = "test", "downlit.topic_index" = c("TEST-class" = "test") )) expect_equal(rd2html("\\linkS4class{TEST}"), "<a href='test.html'>TEST</a>") }) test_that("bad specs throw errors", { expect_snapshot(error = TRUE, { rd2html("\\url{}") rd2html("\\url{a\nb}") rd2html("\\email{}") rd2html("\\linkS4class{}") }) }) test_that("empty input gives empty output", { expect_equal(flatten_para(character()), character()) }) test_that("empty lines break paragraphs", { expect_equal( flatten_para(rd_text("a\nb\n\nc")), "<p>a\nb</p>\n<p>c</p>" ) }) test_that("indented empty lines break paragraphs", { expect_equal( flatten_para(rd_text("a\nb\n \nc")), "<p>a\nb</p> \n<p>c</p>" ) }) test_that("block tags break paragraphs", { out <- flatten_para(rd_text("a\n\\itemize{\\item b}\nc")) expect_equal(out, "<p>a</p><ul>\n<li><p>b</p></li>\n</ul><p>c</p>") }) test_that("inline tags + empty line breaks", { out <- flatten_para(rd_text("a\n\n\\code{b}")) expect_equal(out, "<p>a</p>\n<p><code>b</code></p>") }) test_that("single item can have multiple paragraphs", { out <- flatten_para(rd_text("\\itemize{\\item a\n\nb}")) expect_equal(out, "<ul>\n<li><p>a</p>\n<p>b</p></li>\n</ul>\n") }) test_that("nl after tag doesn't trigger paragraphs", { out <- flatten_para(rd_text("One \\code{}\nTwo")) expect_equal(out, "<p>One <code></code>\nTwo</p>") }) test_that("cr generates line break", { out <- flatten_para(rd_text("a \\cr b")) expect_equal(out, "<p>a <br /> b</p>") }) test_that("simple lists work", { expect_equal( rd2html("\\itemize{\\item a}"), c("<ul>", "<li><p>a</p></li>", "</ul>") ) expect_equal( rd2html("\\enumerate{\\item a}"), c("<ol>", "<li><p>a</p></li>", "</ol>") ) }) test_that("\\describe items can contain multiple paragraphs", { out <- rd2html("\\describe{ \\item{Label 1}{Contents 1} \\item{Label 2}{Contents 2} }") expect_snapshot_output(cat(out, sep = "\n")) }) test_that("\\describe items can contain multiple paragraphs", { out <- rd2html("\\describe{ \\item{Label}{ Paragraph 1 Paragraph 2 } }") expect_snapshot_output(cat(out, sep = "\n")) }) test_that("nested item with whitespace parsed correctly", { out <- rd2html(" \\describe{ \\item{Label}{ This text is indented in a way pkgdown doesn't like. }}") expect_snapshot_output(cat(out, sep = "\n")) }) test_that("preformatted blocks aren't double escaped", { out <- flatten_para(rd_text("\\preformatted{\\%>\\%}")) expect_equal(out, "<pre><code>%&gt;%</code></pre>\n") }) test_that("newlines are preserved in preformatted blocks", { out <- flatten_para(rd_text("\\preformatted{^\n\nb\n\nc}")) expect_equal(out, "<pre><code>^\n\nb\n\nc</code></pre>\n") }) test_that("spaces are preserved in preformatted blocks", { out <- flatten_para(rd_text("\\preformatted{^\n\n b\n\n c}")) expect_equal(out, "<pre><code>^\n\n b\n\n c</code></pre>\n") }) test_that("S4 methods gets comment", { out <- rd2html("\\S4method{fun}{class}(x, y)") expect_equal(out[1], " expect_equal(out[2], "fun(x, y)") }) test_that("S3 methods gets comment", { out <- rd2html("\\S3method{fun}{class}(x, y)") expect_equal(out[1], " expect_equal(out[2], "fun(x, y)") out <- rd2html("\\method{fun}{class}(x, y)") expect_equal(out[1], " expect_equal(out[2], "fun(x, y)") }) test_that("Methods for class function work", { out <- rd2html("\\S3method{fun}{function}(x, y)") expect_equal(out[1], " expect_equal(out[2], "fun(x, y)") out <- rd2html("\\method{fun}{function}(x, y)") expect_equal(out[1], " expect_equal(out[2], "fun(x, y)") out <- rd2html("\\S4method{fun}{function,function}(x, y)") expect_equal(out[1], " expect_equal(out[2], "fun(x, y)") }) test_that("eqn", { out <- rd2html(" \\eqn{\\alpha}{alpha}") expect_equal(out, "\\(\\alpha\\)") out <- rd2html(" \\eqn{x}") expect_equal(out, "\\(x\\)") }) test_that("deqn", { out <- rd2html(" \\deqn{\\alpha}{alpha}") expect_equal(out, "$$\\alpha$$") out <- rd2html(" \\deqn{x}") expect_equal(out, "$$x$$") }) test_that("special", { skip_if_not(getRversion() >= "4.0.0") out <- rd2html("\\special{( \\dots )}") expect_equal(out, "( ... )") }) test_that("figures are converted to img", { expect_equal(rd2html("\\figure{a}"), "<img src='figures/a' alt='' />") expect_equal(rd2html("\\figure{a}{b}"), "<img src='figures/a' alt='b' />") expect_equal( rd2html("\\figure{a}{options: height=1}"), "<img src='figures/a' height=1 />" ) })
plotStressStrain <- function(stress, strain,strain_in,stress_in,...){ plot(strain, stress , main="stress-strain", xlab="Strain [-]", ylab ="Stress [Pa]",type="l", col="red",lwd=2) lines(strain_in,stress_in, col="blue") legend("topleft",legend=c("raw stress", "reconstructed"),col=c("red", "blue"), lty=1:2, cex=0.6) abline(h=0, v=0,lty=2) } plotStressRate <- function(stress, rate,...){ plot(stress,rate,main="stress-rate",xlab ="Rate [1/s]", ylab="Stress [Pa]",type="l", col="red",lwd=2) abline(h=0, v=0,lty=2) } plotColeCole <- function(Gp_t,Gpp_t,...){ plot(Gp_t,Gpp_t,main="Cole-Cole plot",xlab=expression("G'"[t]*" [Pa]"),ylab=expression("G''"[t]*" [Pa]"),type="l", col="red",lwd=2) abline(h=0,v=0, lty=2) abline(a=c(0,0), b=c(1,1),lty=2) } plotVGP <- function(G_star_t,delta_t,...){ plot(G_star_t,delta_t,main="VGP plot",xlab=expression("G*"[t]*" [Pa]"),ylab=expression("delta"[t]*" [rad]"),type="l", col="red",lwd=2) abline(h=0, v=0,lty=2)} plotGpdot <- function(Gp_t_dot,Gpp_t_dot,...){ plot(Gp_t_dot,Gpp_t_dot,main=expression("dG'"[t]*"/dt-dG''"[t]*"/dt"), xlab=expression("dG'"[t]*"/dt [Pa/s]"),ylab=expression("dG''"[t]*"/dt [Pa/s]"),type="l", col="red",lwd=2 ) } plotSpeedGp <- function(Gp_t,G_speed,...){ plot(Gp_t,G_speed,main=expression("Speed-G'"[t]*"") ,xlab=expression("G'"[t]*" [Pa]"),ylab=expression("Speed-G''"[t]*" [Pa/s]"),type="l", col="red",lwd=2 )} plotSpeedGpp <- function(G_speed,Gpp_t,...){ plot(G_speed,Gpp_t,main=expression("Speed-G''"[t]*"") ,xlab=expression("Speed [Pa/s]"),ylab=expression("G''"[t]*" [Pa]"),type="l", col="red",lwd=2 ) } plotDeltaStrain <- function(strain,delta_t,...){ plot(strain,delta_t,main=expression("delta"[t]*"-strain"),xlab=expression("strain [-]"),ylab=expression("delta"[t]*" [rad]"),type="l", col="red",lwd=2 )} plotPAV <- function(strain,delta_t_dot,...){ plot(strain,delta_t_dot,main="PAV-strain",xlab=expression("strain [-]"),ylab=expression("PAV [] (time-normalized)"),type="l", col="red", lwd=2)} plotDisp <- function(strain,disp_stress,...){ plot(strain,disp_stress,main="displacement stress-strain",xlab=expression("strain [-]"),ylab=expression("displacement stress [Pa]"),type="l", col="red", lwd=2 )} plotStrain <- function(Gp_t,eq_strain_est,...){ plot(Gp_t,eq_strain_est,main="est. eq. strain-tan(delta)",xlab=expression("G'"[t]*" [Pa]"),ylab=expression("esp eq. strain[-]"),type="l", col="red", lwd=2 )} plotTimeStrain <- function(time_wave,strain,time_wave_in,strain_in, ...){ plot(time_wave,strain,main="Strain-time",xlab=expression("Time [s]"),ylab = expression("Strain [-]"),type="l", col="red",xlim=c(0,3), lwd=2) lines(time_wave_in,strain_in,lty=2)} plotTimeRate <- function(time_wave,rate,time_wave_in,strain_rate,...){ plot(time_wave,rate,main="Rate-time",xlab=expression("Time [s]"),ylab = expression("Rate [1/s]"),type="l", col="red",xlim=c(0,3), lwd=2) lines(time_wave_in,strain_rate,lty=2)} plotTimeStress <- function(time_wave,stress,time_wave_in,strain_rate,...){ plot(time_wave,stress,main="Stress-time",xlab=expression("Time [s]"),ylab=expression("Stress [Pa]"),type="l", col="red", xlim=c(0,3), lwd=2) lines(time_wave_in,strain_rate,lty=2)} plotStressTime <- function(time_wave_in,stress_in,time_wave,stress){ plot(time_wave_in,stress_in,xlab=expression("Time[s]"),ylab=expression("Stress [Pa]"),type="l", col="black",lty=2 ) lines(time_wave,stress,main="Stress-time",type="l", col="red", lwd=2 )} plotFft <- function(ft_amp,fft_resp,spp_params,...){ plot(ft_amp,fft_resp,main="Fourier spectrum",xlab=expression("Number of harmonics [-]"),ylab=expression(paste(I[n],"/",I[1],"[-]")),log="y") segments(x0=as.numeric(spp_params[2]), y0=10^-10, x1 = as.numeric(spp_params[2]), y1 = 0.7,col="red",lwd=2)}
feature.test <- function(x, y, B=100, type.measure="deviance", s="lambda.min", keeplambda=FALSE, olsestimates=TRUE, penalty.factor = rep(1, nvars), alpha=1, control=list(trace=FALSE, maxcores=24), ...) { warn <- options()$warn options(warn=-1) con <- list(trace=FALSE) con[names(control)] <- control control <- con sfixed <- ifelse(is.numeric(s), TRUE, FALSE) lambda <- NA nobs <- nrow(x) nvars <- ncol(x) x <- scale(x) y <- y / sd(y) if (!sfixed) { o <- glmnet::cv.glmnet(x, y, standardize=FALSE, type.measure=type.measure, penalty.factor=penalty.factor, ..., grouped=FALSE, pmax = min(nobs-1, nvars)) lambda <- as.numeric(o[s]) } else { lambda <- s keeplambda <- TRUE } o <- glmnet::glmnet(x, y, standardize=FALSE, penalty.factor=penalty.factor, ..., pmax = min(nobs-1, nvars)) o.coef <- coef(o, s=lambda)[-1] o.select <- which(o.coef != 0) o.non.zero <- o.coef[o.select] o.nselected <- length(o.non.zero) o.sigmalasso <- sqrt(sum( (y - predict(o, newx=x, s=lambda))^2)/(nobs - o.nselected -1)) o.coef.lasso <- o.non.zero names(o.coef.lasso) <- o.select if (o.nselected>0) { o.lm <- lm(y ~ x[,o.select]) o.summarylm <- summary(o.lm) o.fullp <- -pf(o.summarylm$fstatistic[1], o.summarylm$fstatistic[2], o.summarylm$fstatistic[3], lower.tail=FALSE, log.p=TRUE) o.tstat <- coef(o.summarylm)[-1,3] o.betacoef <- coef(o.summarylm)[-1,1] names(o.tstat) <- o.select o.sigmaols <- o.summarylm$sigma } else { o.betacoef <- 0 o.sigmalasso <- 0 o.sigmaols <- 0 o.coef.lasso <- 0 o.ols.order <- NA o.fullp <- 0 o.tstat <- 0 } scaling.factor <- o.coef.lasso * o.sigmaols / (abs(o.betacoef) * o.sigmalasso ) o.lasso.teststat <- scaling.factor*o.tstat o.lasso.torder <- order(abs(o.lasso.teststat), decreasing=TRUE) o.lasso.max <- max(c(0, abs(o.lasso.teststat))) o.ols.max <- max(c(0, abs(o.tstat))) if (o.nselected > 0) { simnull <- parallel::mclapply(1:B, function(iii) { py <- sample(y) cat(".") if (!keeplambda) { to <- glmnet::cv.glmnet(x, py, standardize=FALSE, type.measure=type.measure, penalty.factor=penalty.factor, ..., pmax = min(nobs-1, nvars), grouped=FALSE) lambda <- as.numeric(to[s]) } to <- glmnet::glmnet(x, py, standardize=FALSE, penalty.factor=penalty.factor, ..., pmax = min(nobs-1, nvars)) to.coef <- coef(to, s=lambda)[-1] to.select <- which(to.coef != 0) to.non.zero <- to.coef[to.select] to.nselected <- length(to.non.zero) to.sigmalasso <- sqrt(sum( (py - predict(to, newx=x, s=lambda))^2)/(nobs - to.nselected -1)) to.coef.lasso <- to.non.zero names(to.coef.lasso) <- to.select if (to.nselected>0) { to.lm <- lm(py ~ x[,to.select]) to.summarylm <- summary(to.lm) to.fullp <- -pf(to.summarylm$fstatistic[1], to.summarylm$fstatistic[2], to.summarylm$fstatistic[3], lower.tail=FALSE, log.p=TRUE) to.tstat <- coef(to.summarylm)[-1,3] to.betacoef <- coef(to.summarylm)[-1,1] names(to.tstat) <- to.select to.sigmaols <- to.summarylm$sigma } else { to.sigmaols <- 0 to.betacoef <- 0 to.tstat <- 0 to.fullp <- 0 } scaling.factor <- to.coef.lasso * to.sigmaols / (abs(to.betacoef) * to.sigmalasso ) to.lasso.teststat <- scaling.factor*max(abs(to.tstat)) to.lasso.max <- max(c(0, to.lasso.teststat)) to.ols.max <- max(c(0, abs(to.tstat))) c(to.lasso.max, to.ols.max, to.fullp) }, mc.cores=min(parallel::detectCores(), control$maxcores) ) dist.lasso <- sapply(simnull, function(i) {i[[1]]}) dist.ols <- sapply(simnull, function(i) {i[[2]]}) dist.fullp <- sapply(simnull, function(i) {i[[3]]}) p.maxlasso <- sum(dist.lasso >= o.lasso.max)/B p.maxols <- sum(dist.ols >= o.ols.max)/B p.full <- sum(dist.fullp >= o.fullp)/B } else { p.maxlasso <- NA p.maxols <- NA p.full <- NA } options(warn=warn) list( p.full=p.full, ols.selected=o.select[o.ols.order], p.maxols=p.maxols, lasso.selected=o.select[o.lasso.torder], p.maxlasso=p.maxlasso, lambda.orig=lambda, B=B) }
WindowSizeRecog <- function(InputData, COREorder, WScutoff){ ChrSeq <- as.character(unique(InputData[,1])) OrderSeqAll_Vec <- c() WindowAll_Vec <- c() for(chrIter in ChrSeq){ InputData_Start <- InputData[which(InputData[,1] == chrIter),"start"] InputData_End <- InputData[which(InputData[,1] == chrIter),"end"] RemInd <- which(duplicated(paste(InputData_Start, InputData_End, sep = "_"))) if(length(RemInd) > 0){ InputData_Start <- InputData_Start[-RemInd] InputData_End <- InputData_End[-RemInd] } InputData_End <- InputData_End[order(InputData_Start, decreasing = F)] InputData_Start <- InputData_Start[order(InputData_Start, decreasing = F)] InputData_Center <- 0.5*(InputData_Start + InputData_End) InputData_StartSeq <- min(InputData_Start) InputData_EndSeq <- max(InputData_End) peakNumIter <- COREorder if(((length(InputData_Start)-(peakNumIter - 1))-1) > 0){ OrderElement_Vec <- rep(0,((length(InputData_Start)-(peakNumIter - 1))-1)) WindowElement_Vec <- rep(0,((length(InputData_Start)-(peakNumIter - 1))-1)) i <- 1 while(i < (length(InputData_Start)-(peakNumIter - 1))){ widthElement <- (InputData_End[(i+(peakNumIter - 1))] - InputData_Start[i]) checkwindow <- max(InputData_Start[(i+1):(i + (peakNumIter - 1))] - InputData_End[i:(i+ (peakNumIter - 1) - 1)]) OrderElement_Vec[i] <- peakNumIter WindowElement_Vec[i] <- checkwindow i <- i + 1 } OrderSeqAll_Vec <- c(OrderSeqAll_Vec, OrderElement_Vec) WindowAll_Vec <- c(WindowAll_Vec, WindowElement_Vec) } } i <- COREorder SortedWindow_Vec <- sort(WindowAll_Vec[which(OrderSeqAll_Vec == i)]) SortedWindowQuan <- quantile(SortedWindow_Vec) aa <- (as.numeric(SortedWindowQuan[4]) + WScutoff*(as.numeric(SortedWindowQuan[4])- as.numeric(SortedWindowQuan[2]))) RemovePeaks <- which(SortedWindow_Vec > aa) if(length(RemovePeaks) > 0){ bb <- log(SortedWindow_Vec[-RemovePeaks]) }else{ bb <- log(SortedWindow_Vec) } bb_quan <- quantile(bb) TightReg <- (as.numeric(bb_quan[2]) - WScutoff*(as.numeric(bb_quan[4]) - as.numeric(bb_quan[2]))) Outliers <- which(bb < TightReg) if(length(Outliers) > 0){ WindowSize <- exp(TightReg) }else{ WindowSize <- 1 } return(WindowSize) }
context("widely") test_that("widely can widen, operate, and re-tidy", { skip_if_not_installed("gapminder") library(gapminder) ret <- gapminder %>% widely(cor)(year, country, lifeExp) expect_is(ret$item1, "character") expect_is(ret$item2, "character") expect_true(all(c("Afghanistan", "United States") %in% ret$item1)) expect_true(all(c("Afghanistan", "United States") %in% ret$item2)) expect_true(all(ret$value <= 1)) expect_true(all(ret$value >= -1)) expect_equal(nrow(ret), length(unique(gapminder$country)) ^ 2) ret2 <- gapminder %>% widely(cor, sort = TRUE)(year, country, lifeExp) expect_equal(sort(ret$value, decreasing = TRUE), ret2$value) }) test_that("widely works within groups", { skip_if_not_installed("gapminder") library(gapminder) ret <- gapminder %>% group_by(continent) %>% widely(cor)(year, country, lifeExp) expect_equal(colnames(ret), c("continent", "item1", "item2", "value")) expect_is(ret$item1, "character") expect_is(ret$item2, "character") expect_true(all(c("Afghanistan", "United States") %in% ret$item1)) expect_true(all(c("Afghanistan", "United States") %in% ret$item2)) expect_true(any("Canada" == ret$item1 & "United States" == ret$item2)) expect_false(any("Afghanistan" == ret$item1 & "United States" == ret$item2)) expect_true(all(ret$value <= 1)) expect_true(all(ret$value >= -1)) }) test_that("widely's maximum size argument works", { skip_if_not_installed("gapminder") library(gapminder) f <- function() { widely(cor, maximum_size = 1000)(gapminder, year, country, lifeExp) } expect_error(f(), "1704.*large") })
intdiv = function(dividend, divisor) { a = as.integer(dividend) b = as.integer(divisor) sign(a) * (abs(a) %/% b) }
context("general_MT and general_diagnosis.MT work correctly") test_that("general_MT", { iris_versicolor <- iris[61:100, -5] unit_space <- general_MT(unit_space_data = iris_versicolor, generates_transform_function = generates_normalization_function, calc_A = function(x) solve(cor(x)), includes_transformed_data = TRUE) correct_distance <- c(1.351, 0.802, 1.164, 0.643, 1.122, 1.184, 0.910, 1.224, 1.691, 0.547, 1.413, 0.692, 1.151, 1.292, 0.771, 0.982, 1.092, 1.116, 0.487, 0.976, 0.621, 0.776, 0.423, 1.324, 1.188, 1.161, 0.959, 1.136, 0.721, 0.685, 1.094, 0.584, 0.310, 1.109, 0.430, 0.982, 0.488, 0.524, 1.572, 0.297) expect_equal(round(as.vector(unit_space$distance), 3), correct_distance) }) test_that("general_diagnosis.MT without passing newdata", { iris_versicolor <- iris[61:100, -5] unit_space <- general_MT(unit_space_data = iris_versicolor, generates_transform_function = generates_normalization_function, calc_A = function(x) solve(cor(x)), includes_transformed_data = TRUE) diagnosis <- general_diagnosis.MT(unit_space = unit_space, threshold = 4, includes_transformed_newdata = TRUE) correct_distance <- c(1.351, 0.802, 1.164, 0.643, 1.122, 1.184, 0.910, 1.224, 1.691, 0.547, 1.413, 0.692, 1.151, 1.292, 0.771, 0.982, 1.092, 1.116, 0.487, 0.976, 0.621, 0.776, 0.423, 1.324, 1.188, 1.161, 0.959, 1.136, 0.721, 0.685, 1.094, 0.584, 0.310, 1.109, 0.430, 0.982, 0.488, 0.524, 1.572, 0.297) expect_equal(round(as.vector(diagnosis$distance), 3), correct_distance) }) test_that("general_diagnosis.MT with passing newdata", { iris_versicolor <- iris[61:100, -5] unit_space <- general_MT(unit_space_data = iris_versicolor, generates_transform_function = generates_normalization_function, calc_A = function(x) solve(cor(x)), includes_transformed_data = TRUE) correct_distance <- c(1.351, 0.802, 1.164, 0.643, 1.122, 1.184, 0.910, 1.224, 1.691, 0.547, 1.413, 0.692, 1.151, 1.292, 0.771, 0.982, 1.092, 1.116, 0.487, 0.976, 0.621, 0.776, 0.423, 1.324, 1.188, 1.161, 0.959, 1.136, 0.721, 0.685, 1.094, 0.584, 0.310, 1.109, 0.430, 0.982, 0.488, 0.524, 1.572, 0.297) iris_test <- iris[c(1:10, 51:60, 101:111), -5] diagnosis <- general_diagnosis.MT(unit_space = unit_space, newdata = iris_test, threshold = 4, includes_transformed_newdata = TRUE) correct_distance <- c(5.061, 4.270, 4.561, 4.262, 5.186, 5.225, 4.590, 4.806, 4.017, 4.552, 1.483, 0.870, 1.152, 1.027, 0.819, 0.839, 0.925, 1.144, 0.996, 1.129, 3.375, 2.138, 2.268, 1.758, 2.566, 2.745, 2.403, 2.452, 2.254, 3.029, 1.872) expect_equal(round(as.vector(diagnosis$distance), 3), correct_distance) })
expected <- eval(parse(text="FALSE")); test(id=0, code={ argv <- eval(parse(text="list(1L, FALSE, TRUE, NA)")); .Internal(duplicated(argv[[1]], argv[[2]], argv[[3]], argv[[4]])); }, o=expected);
eudract_convert <- function(input, output, xslt=system.file("extdata","simpleToEudraCT.xslt", package="eudract"), schema_input=system.file("extdata","simple.xsd", package="eudract"), schema_output=system.file("extdata","adverseEvents.xsd", package="eudract") ){ doc <- xml2::read_xml(input) style <- xml2::read_xml(xslt) schema_input <- xml2::read_xml(schema_input) schema_output <- xml2::read_xml(schema_output) check_in <- xml2::xml_validate(doc, schema_input) if( !check_in){ stop(attr(check_in,"errors"))} output_xml <- xslt::xml_xslt(doc, style) xml2::write_xml(output_xml, output) message(paste0("'",output, "' is created or modified\n")) check_out <- xml2::xml_validate(output_xml, schema_output) if( !check_out){ warning(attr(check_out,"errors"))} message("Please email [email protected] to tell us if you have successfully uploaded a study to EudraCT.\nThis is to allow us to measure the impact of this tool.") invisible(check_out) }
to_numeric <- function(x) { x <- sub("[,.]([0-9]*)$", ";\\1", x) x <- gsub("[,. ]", "", x) x <- sub(";", ".", x) as.numeric(x) }
impulseest <- function(x,M=30,K=NULL,regul=F,lambda=1){ N <- dim(x$output)[1] if(is.null(K)) K <- rep(0,nInputSeries(x)*nOutputSeries(x)) out <- rep(list(0),length(K)) for(i in seq(nOutputSeries(x))){ for(j in seq(nInputSeries(x))){ index <- (i-1)*nInputSeries(x)+j out[[index]] <- impulsechannel(outputData(x)[,i,drop=F], inputData(x)[,j,drop=F],N,M, K[index],regul,lambda) } } out$ninputs <- nInputSeries(x) out$noutputs <- nOutputSeries(x) class(out) <- "impulseest" return(out) } impulsechannel <- function(y,u,N,M,K=0,regul=F,lambda=1){ ind <- (M+K+1):N z_reg <- function(i) u[(i-K):(i-M-K),] Z <- t(sapply(ind,z_reg)) Y <- y[ind,] if(regul==F){ fit <- lm(Y~Z-1) coefficients <- coef(fit); residuals <- resid(fit) } else{ inner <- t(Z)%*%Z + lambda*diag(dim(Z)[2]) pinv <- solve(inner)%*% t(Z) coefficients <- pinv%*%Y residuals <- Y - Z%*%coefficients } df <- nrow(Z)-ncol(Z);sigma2 <- sum(residuals^2)/df vcov <- sigma2 * solve(t(Z)%*%Z) se <- sqrt(diag(vcov)) out <- list(coefficients=coefficients,residuals=residuals,lags=K:(M+K), x=colnames(u),y=colnames(y),se = se) out } impulseplot <- function(model,sd=2){ plotseq <- seq(model$noutputs*model$ninputs) g <- vector("list",model$nin*model$nout) for(i in plotseq){ z <- model[[i]] lim <- z$se*sd yindex <- (i-1)%/%model$nin + 1;uindex <- i-model$nin*(yindex-1) df <- data.frame(x=z$lags,y=coef(z),lim=lim) g[[i]] <- with(df,ggplot(df,aes(x,y))+ geom_segment(aes(xend=x,yend=0))+geom_hline(yintercept = 0) + geom_point(size=2) + ggtitle(paste("From",z$x,"to",z$y))+ geom_line(aes(y=lim),linetype="dashed",colour="steelblue") + geom_line(aes(y=-lim),linetype="dashed",colour="steelblue") + ggplot2::theme_bw(14) + ylab(ifelse(uindex==1,"IR Coefficients","")) + xlab(ifelse(yindex==model$nout,"Lags","")) + theme(axis.title=element_text(size=12,color = "black",face = "plain"), title=element_text(size=9,color = "black",face="bold")) + scale_x_continuous(expand = c(0.01,0.01))) } multiplot(plotlist=g,layout=plotseq) } step <- function(model){ plotseq <- seq(model$noutputs*model$ninputs) g <- vector("list",model$nin*model$nout) for(i in plotseq){ z <- model[[i]] stepResp <- cumsum(coef(z)) yindex <- (i-1)%/%model$nin + 1;uindex <- i-model$nin*(yindex-1) df <- data.frame(x=z$lags,y=stepResp) g[[i]] <- with(df,ggplot(df,aes(x,y))+ geom_step() + ggtitle(paste("From",z$x,"to",z$y)) + theme_bw(14) + ylab(ifelse(uindex==1,"Step Response","")) + xlab(ifelse(yindex==model$nout,"Lags","")) + theme(axis.title=element_text(size=12,color = "black",face = "plain"), title=element_text(size=9,,color = "black",face="bold"))) } multiplot(plotlist=g,layout=plotseq) } spa <- function(x,winsize=NULL,freq=NULL){ N <- dim(x$out)[1] nout <- nOutputSeries(x); nin <- nInputSeries(x) if(is.null(winsize)) winsize <- min(N/10,30) if(is.null(freq)) freq <- (1:128)/128*pi/deltat(x) M <- winsize Ryu <- mult_ccf(x$out,x$input,lag.max = M) Ruu <- mult_ccf(x$input,x$input,lag.max=M) Ryy <- mult_ccf(x$out,x$out,lag.max = M) cov2spec <- function(omega,R,M){ seq1 <- exp(-1i*(-M:M)*omega) sum(R*signal::hanning(2*M+1)*seq1) } G <- array(0,c(nout,nin,length(freq))) spec <- array(0,c(nout,1,length(freq))) for(i in 1:nout){ phi_y <- sapply(freq,cov2spec,Ryy[i,i,],M) temp <- phi_y for(j in 1:nin){ phi_yu <- sapply(freq,cov2spec,Ryu[i,j,],M) phi_u <- sapply(freq,cov2spec,Ruu[j,j,],M) G[i,j,] <- phi_yu/phi_u temp <- temp - phi_yu*Conj(phi_yu)/phi_u } spec[i,1,] <- temp } out <- idfrd(G,matrix(freq),deltat(x),spec) return(out) } mult_ccf <- function(X,Y=NULL,lag.max=30){ N <- dim(X)[1]; nx <- dim(X)[2] ny <- ifelse(is.null(Y),nx,dim(Y)[2]) ccvfij <- function(i,j,lag=30) ccf(X[,i],Y[,j],plot=F,lag.max =lag, type="covariance") Xindex <- matrix(sapply(1:nx,rep,nx),ncol=1)[,1] temp <- mapply(ccvfij,i=Xindex,j=rep(1:ny,ny), MoreArgs = list(lag=lag.max)) ccfextract <- function(i,l) l[,i]$acf temp2 <- t(sapply(1:(nx*ny),ccfextract,l=temp)) dim(temp2) <- c(nx,ny,2*lag.max+1) return(temp2) } etfe <- function(data,n=128){ y <- data$output u <- data$input N <- dim(data$output)[1] if(N < n){ n=N } v=seq(1,N,length.out = n) temp <- cbind(data$output[v,],data$input[v,]) tempfft <- mvfft(temp)/dim(temp)[1] G <- comdiv(tempfft[,1],tempfft[,2]) resp = G[1:ceiling(length(G)/2)] frequency <- matrix(seq( 1 , ceiling(n/2) ) * pi / floor(n/2) / deltat(data)) out <- idfrd(respData = resp,freq=frequency,Ts=data$Ts) return(out) } comdiv <- function(z1,z2){ mag1 <- Mod(z1);mag2 <- Mod(z2) phi1 <- Arg(z1); phi2 <- Arg(z2) complex(modulus=mag1/mag2,argument=signal::unwrap(phi1-phi2)) }
lmkkmeans_missingData <- function(Km, parameters, missing = NULL, verbose = FALSE) { state <- list() N <- dim(Km)[2] P <- dim(Km)[3] if (!is.null(missing)) { avail <- abs(1 - missing) } else { avail <- matrix(1, N, P) } Theta <- matrix(NA, N, P) for (i in 1:N) { Theta[i, ] <- 1/sum(avail[i, ]) } Theta <- Theta * avail K_Theta <- matrix(0, nrow(Km), ncol(Km)) for (m in 1:P) { avail_m <- avail[, m] > 0 K_Theta[avail_m, avail_m] <- K_Theta[avail_m, avail_m] + (Theta[avail_m, m, drop = FALSE] %*% t(Theta[avail_m, m, drop = FALSE])) * Km[avail_m, avail_m, m] } objective <- rep(0, parameters$iteration_count) for (iter in 1:parameters$iteration_count) { if (verbose) print(sprintf("running iteration %d...", iter)) H <- eigen(K_Theta, symmetric = TRUE)$vectors[, 1:parameters$cluster_count] HHT <- H %*% t(H) Q <- matrix(0, N * P, N * P) for (m in 1:P) { avail_m <- avail[, m] > 0 start_index <- (m - 1) * N + 1 end_index <- m * N Q[(start_index:end_index)[avail_m], (start_index:end_index)[avail_m]] <- diag(1, sum(avail_m), sum(avail_m)) * Km[avail_m, avail_m, m] - HHT[avail_m, avail_m] * Km[avail_m, avail_m, m] } avail_vec <- as.logical(as.vector(avail)) sum_avail_vec <- sum(avail_vec) Q <- Q[avail_vec, avail_vec] problem <- list() problem$sense <- "min" problem$c <- rep(0, sum_avail_vec) A <- Matrix::Matrix(rep(diag(1, N, N), P), nrow = N, ncol = N * P, sparse = TRUE) problem$A <- A[, avail_vec, drop = F] problem$bc <- rbind(blc = rep(1, N), buc = rep(1, N)) problem$bx <- rbind(blx = rep(0, sum_avail_vec), bux = rep(1, sum_avail_vec)) I <- matrix(1:sum_avail_vec, sum_avail_vec, sum_avail_vec, byrow = FALSE) J <- matrix(1:sum_avail_vec, sum_avail_vec, sum_avail_vec, byrow = TRUE) problem$qobj <- list(i = I[lower.tri(I, diag = TRUE)], j = J[lower.tri(J, diag = TRUE)], v = Q[lower.tri(Q, diag = TRUE)]) opts <- list() opts$verbose <- 0 result <- Rmosek::mosek(problem, opts) Theta <- matrix(0, N, P) count <- 0 for (i in 1:P) { avail_i <- which(avail[, i] == 1) startt <- (count + 1) endt <- count + sum(avail[, i]) Theta[avail_i, i] <- result$sol$itr$xx[startt:endt] count <- count + sum(avail[, i]) } K_Theta <- matrix(0, nrow(Km), ncol(Km)) for (m in 1:P) { avail_m <- avail[, m] > 0 K_Theta[avail_m, avail_m] <- K_Theta[avail_m, avail_m] + (Theta[avail_m, m, drop = FALSE] %*% t(Theta[avail_m, m, drop = FALSE])) * Km[avail_m, avail_m, m] } objective[iter] <- sum(diag(t(H) %*% K_Theta %*% H)) - sum(diag(K_Theta)) } normalize <- which(rowSums(H^2, 2) > .Machine$double.eps) H_normalized <- matrix(0, N, parameters$cluster_count) H_normalized[normalize, ] <- H[normalize, ]/matrix(sqrt(rowSums(H[normalize, ]^2, 2)), nrow(H[normalize, ]), parameters$cluster_count, byrow = FALSE) state$clustering <- stats::kmeans( H_normalized, centers = parameters$cluster_count, iter.max = 1000, nstart = 10 )$cluster state$objective <- objective state$parameters <- parameters state$Theta <- Theta state }
library(testthat) library(getSpatialData) library(raster) library(sf) Sys.setenv("R_TESTS" = "")
mnis_extra <- function(ID, ref_dods = FALSE, addresses = TRUE, biography_entries = TRUE, committees = TRUE, constituencies = TRUE, elections_contested = TRUE, experiences = TRUE, government_posts = TRUE, honours = TRUE, house_memberships = TRUE, interests = TRUE, known_as = TRUE, maiden_speeches = TRUE, opposition_posts = TRUE, other_parliaments = TRUE, parliamentary_posts = TRUE, parties = TRUE, preferred_names = TRUE, staff = TRUE, statuses = TRUE, tidy = TRUE, tidy_style = "snake_case") { .Defunct("mnis_additional", msg = "mnis_extra is defunct") ID <- as.character(ID) if (is.null(ID) == TRUE) { stop("ID cannot be null", call. = FALSE) } mnis_df <- tibble::tibble(member_id = ID) if (addresses == TRUE) { addresses_df <- mnis_addresses(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages( suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, addresses_df)) ) } if (biography_entries == TRUE) { biography_entries_df <- mnis_biography_entries(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, biography_entries_df))) } if (committees == TRUE) { committees_df <- mnis_committees(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, committees_df))) } if (constituencies == TRUE) { constituencies_df <- mnis_constituencies(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, constituencies_df))) } if (elections_contested == TRUE) { elections_contested_df <- mnis_elections_contested(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, elections_contested_df))) addresses_df <- NULL biography_entries_df <- NULL committees_df <- NULL constituencies_df <- NULL elections_contested_df <- NULL experiences_df <- NULL government_posts_df <- NULL honours_df <- NULL house_memberships_df <- NULL interests_df <- NULL known_as_df <- NULL maiden_speeches_df <- NULL opposition_posts_df <- NULL other_parliaments_df <- NULL parliamentary_posts_df <- NULL parties_df <- NULL preferred_names_df <- NULL staff_df <- NULL statuses_df <- NULL if (addresses == TRUE) { addresses_df <- mnis_addresses(ID, ref_dods, tidy, tidy_style) } if (biography_entries == TRUE) { biography_entries_df <- mnis_biography_entries( ID, ref_dods, tidy, tidy_style ) } if (committees == TRUE) { committees_df <- mnis_committees(ID, ref_dods, tidy, tidy_style) } if (constituencies == TRUE) { constituencies_df <- mnis_constituencies(ID, ref_dods, tidy, tidy_style) } if (elections_contested == TRUE) { elections_contested_df <- mnis_elections_contested( ID, ref_dods, tidy, tidy_style ) } if (experiences == TRUE) { experiences_df <- mnis_experiences(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, experiences_df))) experiences_df <- mnis_experiences(ID, ref_dods, tidy, tidy_style) } if (government_posts == TRUE) { government_posts_df <- mnis_government_posts(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, government_posts_df))) } if (honours == TRUE) { honours_df <- mnis_honours(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, honours_df))) } if (house_memberships == TRUE) { house_memberships_df <- mnis_house_memberships(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, house_memberships_df))) } if (interests == TRUE) { interests_df <- mnis_interests(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, interests_df))) government_posts_df <- mnis_government_posts(ID, ref_dods, tidy, tidy_style) } if (honours == TRUE) { honours_df <- mnis_honours(ID, ref_dods, tidy, tidy_style) } if (house_memberships == TRUE) { house_memberships_df <- mnis_house_memberships( ID, ref_dods, tidy, tidy_style ) } if (interests == TRUE) { interests_df <- mnis_interests(ID, ref_dods, tidy, tidy_style) } if (known_as == TRUE) { known_as_df <- mnis_known_as(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, known_as_df))) known_as_df <- mnis_known_as(ID, ref_dods, tidy, tidy_style) } if (maiden_speeches == TRUE) { maiden_speeches_df <- mnis_maiden_speeches(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, maiden_speeches_df))) maiden_speeches_df <- mnis_maiden_speeches(ID, ref_dods, tidy, tidy_style) } if (opposition_posts == TRUE) { opposition_posts_df <- mnis_opposition_posts(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, opposition_posts_df))) opposition_posts_df <- mnis_opposition_posts(ID, ref_dods, tidy, tidy_style) } if (other_parliaments == TRUE) { other_parliaments_df <- mnis_other_parliaments(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, other_parliaments_df))) } if (parliamentary_posts == TRUE) { parliamentary_posts_df <- mnis_parliamentary_posts(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, parliamentary_posts_df))) } if (parties == TRUE) { parties_df <- mnis_parties(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, parties_df))) other_parliaments_df <- mnis_other_parliaments( ID, ref_dods, tidy, tidy_style ) } if (parliamentary_posts == TRUE) { parliamentary_posts_df <- mnis_parliamentary_posts( ID, ref_dods, tidy, tidy_style ) } if (parties == TRUE) { parties_df <- mnis_parties(ID, ref_dods, tidy, tidy_style) } if (preferred_names == TRUE) { preferred_names_df <- mnis_preferred_names(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, preferred_names_df))) preferred_names_df <- mnis_preferred_names(ID, ref_dods, tidy, tidy_style) } if (staff == TRUE) { staff_df <- mnis_staff(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, staff_df))) staff_df <- mnis_staff(ID, ref_dods, tidy, tidy_style) } if (statuses == TRUE) { statuses_df <- mnis_statuses(ID = ID, ref_dods = ref_dods, tidy = TRUE, tidy_style = "snake_case") suppressMessages(suppressWarnings(mnis_df <- dplyr::inner_join(mnis_df, statuses_df))) } if (tidy == TRUE) { mnis_df <- mnis::mnis_tidy(mnis_df, tidy_style) statuses_df <- mnis_statuses(ID, ref_dods, tidy, tidy_style) } mnis_df <- list( addresses_df, biography_entries_df, committees_df, constituencies_df, elections_contested_df, experiences_df, government_posts_df, honours_df, house_memberships_df, interests_df, known_as_df, maiden_speeches_df, opposition_posts_df, other_parliaments_df, parliamentary_posts_df, parties_df, preferred_names_df, staff_df, statuses_df ) names(mnis_df) <- c( "addresses", "biography_entries", "committees", "constituencies", "elections_contested", "experiences", "government_posts", "honours", "house_memberships", "interests", "known_as", "maiden_speeches", "opposition_posts", "other_parliaments", "parliamentary_posts", "parties", "preferred_names", "staff", "statuses" ) mnis_df } else { mnis_df } }
gamKTS <- function() { gamKTS1OnOk <- function() { selTsName <- verifyCharEntry(tcltk::tclvalue(KTSEnv$selTsP)) if (is.na(selTsName)) { tcltk::tkmessageBox(message = "Choose a time series", icon = "warning") } else { KTSEnv$selTsName <- selTsName showPANgamKTS2() } } gamKTS2OnOk <- function() { refreshDataSetsList(outp = FALSE) tssel <- tsCheckedTF() predictorTS <- KTSEnv$dSList$TS[which(tssel == TRUE)] nPredictorTS <- length(predictorTS) selTs <- get(KTSEnv$selTsName, envir = KTSEnv) if (any(predictorTS == KTSEnv$selTsName)) { tcltk::tkmessageBox(message = paste("The time series", "to fill cannot be", "one of the predictors"), icon = "warning") } else if (nPredictorTS == 0) { tcltk::tkmessageBox(message = paste("Choose, at least,", "a predictor time series"), icon = "warning") } else if (nPredictorTS > 3) { tcltk::tkmessageBox(message = paste("The maximum number of", "predictor time series is 3"), icon = "warning") } else { tmComptibility <- matrix(rep(FALSE, 3 * nPredictorTS), nPredictorTS, 3) for (i in 1:nPredictorTS) { tmComptibility[i, ] <- are2TsTimeCompatible(selTs, get(predictorTS[i], envir = KTSEnv)) } if (any(tmComptibility[, 1] == FALSE)) { tcltk::tkmessageBox(message = paste("The initial date of all the", "time series must be the same"), icon = "warning") } else if (any(tmComptibility[, 2] == FALSE)) { tcltk::tkmessageBox(message = paste("The sampling period of all", "the time series must", "be the same"), icon = "warning") } else if (any(tmComptibility[, 3] == FALSE)) { tcltk::tkmessageBox(message = paste("All time series must", "have the same length"), icon = "warning") } else { KTSEnv$predictorTS <- predictorTS showPANgamKTS3() } } } gamKTS3OnOk <- function() { fx <- tcltk::tclvalue(KTSEnv$fxE) bs <- verifyCharEntry(tcltk::tclvalue(KTSEnv$bsE), noValid = NA) per <- verifyRealEntry(tcltk::tclvalue(KTSEnv$perE), noValid = NA) selTs <- get(KTSEnv$selTsName, envir = KTSEnv) gapToUse <- gapForSelMethod(KTSEnv$selTsName, selTs) selGap <- gapToUse$selGap selGapName <- gapToUse$selGapName nasInSelTs <- which(is.na(selTs$value)) tmComptibility <- areTsGapTimeCompatible(selTs, selGap) if (length(nasInSelTs) == 0) { tcltk::tkmessageBox(message = paste("The selected time", "series contains no NAs"), icon = "warning") } else if (length(selGap$gaps) == 0) { tcltk::tkmessageBox(message = "The gap set is empty", icon = "warning") } else if (length(setdiff(union(selGap$gaps, nasInSelTs), nasInSelTs)) != 0) { tcltk::tkmessageBox(message = paste("Some NAs in the gap set", "do not exist in the time series.", "Check that the selected gap set", "comes from the selected", "time series"), icon = "warning") } else if (tmComptibility[1] == FALSE) { tcltk::tkmessageBox(message = paste("The initial date of the time", "series and the one stored in", "the gap set do not match"), icon = "warning") } else if (tmComptibility[2] == FALSE) { tcltk::tkmessageBox(message = paste("The sampling period of the", "time series and the one stored", "in the gap set do not match"), icon = "warning") } else if (tmComptibility[3] == FALSE) { tcltk::tkmessageBox(message = paste("The time series is shorter", "than some indices stored", "in the set of gaps"), icon = "warning") } else { getPiece <- function(gapLims, per, X, Y) { if (is.vector(X)) { X <- as.matrix(X) } L <- round(per * (gapLims[2] - gapLims[1] + 1), 0) P <- (gapLims[1] - L):(gapLims[2] + L) P <- intersect(P, 1:nrow(X)) lP <- length(P) if (lP > 0) { X <- X[P, ] Y <- Y[P] } else { X <- NA Y <- NA } res <- list(X1 = X, Y1 = Y, predLims = P) } multSpline <- function(XP, YP, per = 1, bs = "cr", fx = TRUE) { TI <- 1:length(YP) if (is.vector(XP)) { gamMod <- try(mgcv::gam(YP ~ te(XP, TI, bs = bs, fx = fx)), silent = TRUE) if (any(class(gamMod) == "try-error")) { stop("The gam model failed") } else { res <- try(stats::predict(gamMod, newdata = data.frame(XP, TI)), silent = TRUE) if (class(res) == "try-error") { stop("The prediction failed") } else { res } } } else if (ncol(XP) == 2) { XP1 <- XP[, 1] XP2 <- XP[, 2] gamMod <- try(mgcv::gam(YP ~ te(XP1, XP2, TI, bs = bs, fx = fx)), silent = TRUE) if (any(class(gamMod) == "try-error")) { stop("The gam model failed") } else { res <- try(stats::predict(gamMod, newdata = data.frame(XP1, XP2,TI)), silent = TRUE) if (class(res) == "try-error") { stop("The prediction failed") } else { res } } } else if (ncol(XP) == 3) { XP1 <- XP[, 1] XP2 <- XP[, 2] XP3 <- XP[, 3] gamMod <- try(mgcv::gam(YP ~ te(XP1, XP2, XP3, TI, bs = bs, fx = fx)), silent = TRUE) if (any(class(gamMod) == "try-error")) { stop("The gam model failed") } else { res <- try(stats::predict(gamMod, newdata = data.frame(XP1, XP2,XP3, TI)), silent = TRUE) if (class(res) == "try-error") { stop("The prediction failed") } else { res } } } } placePrediction <- function(YTimSer, gapLims, gamPred, predLims) { predLims1 <- gapLims[1] - predLims[1] aa <- gapLims[1]:gapLims[2] YTimSer$value[aa] <- gamPred[predLims1:(predLims1 + gapLims[2] - gapLims[1])] YTimSer } multSplinInterp <- function(X, YTimSer, gapsInYnotInX, per = 1, bs = "cr",fx = TRUE) { gapMatrix <- groupIndices(gapsInYnotInX) nG <- nrow(gapMatrix) res <- vector("list", nG) gamPred <- vector("list", nG) for (i in 1:nrow(gapMatrix)) { res[[i]] <- getPiece(gapLims = gapMatrix[i, 1:2], per = per, X = X, Y = YTimSer$value) gamPred[[i]] <- try(multSpline(XP = res[[i]]$X1, YP = res[[i]]$Y1, per = per, bs = bs, fx = fx), silent = TRUE) } YTimSerPred <- YTimSer for (j in 1:nrow(gapMatrix)) { if (is.numeric(gamPred[[j]])) { YTimSerPred <- placePrediction(YTimSerPred, gapLims = gapMatrix[j,1:2], gamPred = gamPred[[j]], predLims = res[[j]]$predLims) } } YTimSerPred } if (is.na(bs)) { bs <- "cr" tcltk::tkmessageBox(message = paste("The smoothing basis", "entry was not valied and", "it defaulted to cr"), icon = "warning") } if (is.na(per)) { per <- 100 tcltk::tkmessageBox(message = paste("The window was not valid", "and it defaulted to 100%"), icon = "warning") } if (fx == "df") { fx <- TRUE } else { fx <- FALSE } per <- 0.01 * per lPred <- length(KTSEnv$predictorTS) if (lPred == 1) { X <- get(KTSEnv$predictorTS, envir = KTSEnv)$value } else { X <- NULL for (i in 1:lPred) { X <- cbind(X, get(KTSEnv$predictorTS[i], envir = KTSEnv)$value) } } filledTS <- multSplinInterp(X = X, YTimSer = selTs, gapsInYnotInX = selGap$gaps, per = per, bs = bs, fx = fx) filledTS$value[which(is.nan(filledTS$value))] <- NA assign(paste0(KTSEnv$selTsName, "_", selGapName, "_mSpl"), filledTS, envir = KTSEnv) gapsAfterFill <- getGapsAfterFill(filledTS, selGap, envir = environment(gamKTS1OnOk)) remainingNAsInGap <- gapsAfterFill$remainingNAsInGap filledNasTable <- gapsAfterFill$filledNasTable writeMethodTitle("MULTIVARIATE SPLINE INTERPOLATION") tcltk::tkinsert(KTSEnv$txtWidget, "end", "GAM model with tensor product smooth ") tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("Filled time series:", KTSEnv$selTsName)) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("Predictor time series:", KTSEnv$predictorTS, collapse = ",")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("Regression:", fx)) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("Smoothing basis:", bs)) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("Window:", 100 * per, "% gap length")) tcltk::tkinsert(KTSEnv$txtWidget, "end", paste("\n")) writeMethodSummary(filledNasTable, remainingNAsInGap, KTSEnv$selTsName, selGapName, selGap) endingLines() cleanEnvir() refreshDataSetsList(outp = FALSE) showPANgamKTS1() } } showPANgamKTS1 <- function() { refreshDataSetsList(outp = FALSE) createSubPanR4C1() createTITLE(labTitle = "MULTIVARIATE SPLINES") createTsRb(labTitle = "Time series to fill") createOK(labTitle = "NEXT", action = gamKTS1OnOk) tcltk::tkpack(KTSEnv$subPanR4C1, expand = TRUE, fill = "both") } showPANgamKTS2 <- function() { createSubPanR4C1() createTITLE(labTitle = "MULTIVARIATE SPLINES") createTsChb(labTitle = "Predictor time series") createOK(labTitle = "NEXT", action = gamKTS2OnOk) tcltk::tkpack(KTSEnv$subPanR4C1, expand = TRUE, fill = "both") } showPANgamKTS3 <- function() { createSubPanR4C1() createTITLE(labTitle = "MULTIVARIATE SPLINES") if (is.null(KTSEnv$dSList$gaps) == FALSE) { createGapRb() } createEntry(labTitle = "Window (% gap length)", textVariableName = "perE") createTitle(labTitle = "Type of regression") assign("fxE", tcltk::tclVar("df"), envir = KTSEnv) createRb(variable = KTSEnv$fxE, dataVector = c("df", "penalized")) createEntry(labTitle = "Smoothing basis", textVariableName = "bsE") createOK(labTitle = "RUN", action = gamKTS3OnOk) createNote(labTitle = "The window can be greater than 100%") createNote(labTitle = "The smoothing basis is usually cr or tp ", pady = c(5,1)) createNote(labTitle = "cr: cubic regression spline ", pady = c(0, 1)) createNote(labTitle = "tp: plate regression spline ", pady = c(0, 10)) tcltk::tkpack(KTSEnv$subPanR4C1, expand = TRUE, fill = "both") } cleanEnvir() refreshDataSetsList(outp = FALSE) checkIfAnyTs(action = "showPANgamKTS1", envirName = environment(showPANgamKTS1)) }
rarity <- function(x, index = "all", detection = 0.2/100, prevalence = 20/100) { index <- tolower(index) accepted <- c("log_modulo_skewness", "low_abundance", "rare_abundance") accepted <- tolower(accepted) if (length(index) == 1 && index == "all") { index <- accepted } if (!is.null(index)) { index <- intersect(index, accepted) } if (!is.null(index) && length(index) == 0) { return(NULL) } tab <- rarity_help(x, index, detection, prevalence) if (is.vector(tab)) { tab <- as.matrix(tab, ncol=1) colnames(tab) <- index } as.data.frame(tab) } rarity_help <- function(x, index="all", detection, prevalence) { if ( length(index) > 1 ) { tab <- NULL for (idx in index) { tab <- cbind(tab, rarity_help(x, index = idx, detection, prevalence)) } colnames(tab) <- index return(as.data.frame(tab)) } otu <- abundances(x) otuc <- transform(x, "compositional") otu.relative <- abundances(otuc) if (index == "log_modulo_skewness") { r <- log_modulo_skewness(otu, q=0.5, n=50) } else if (index == "low_abundance") { r <- apply(otu.relative, 2, function(x) low_abundance(x, detection=detection)) } else if (index == "rare_abundance") { r <- rare_abundance(x, detection=detection, prevalence=prevalence) } names(r) <- colnames(otu) r }
"print.splsda" <- function( x, ... ) { xmat <- x$x p <- ncol(xmat) A <- x$A xAnames <- colnames(xmat)[A] q <- length(unique(x$y)) eta <- x$eta K <- x$K kappa <- x$kappa select <- x$select fit <- x$fit classifier <- x$classifier switch( classifier, logistic = { if ( q == 2 ) { cname <- "Logistic regression" } if ( q > 2 ) { cname <- "Multinomial regression" } }, lda = { cname <- "Linear Discriminant Analysis (LDA)" } ) cat( "\nSparse Partial Least Squares Discriminant Analysis\n" ) cat( "----\n") if ( q == 2 ) { cat( paste("Parameters: eta = ",eta,", K = ",K,"\n",sep="") ) } if ( q > 2 ) { cat( paste("Parameters: eta = ",eta,", K = ",K,", kappa = ",kappa,"\n",sep="") ) } cat( paste("Classifier: ",cname,"\n\n",sep="") ) cat( paste("SPLSDA chose ",length(A)," variables among ",p," variables\n\n",sep='') ) cat( "Selected variables: \n" ) if ( !is.null(xAnames) ) { for (i in 1:length(A)) { cat( paste(xAnames[i],'\t',sep='') ) if ( i%%5==0 ) { cat('\n') } } } else { for (i in 1:length(A)) { cat( paste(A[i],'\t',sep='') ) if ( i%%5==0 ) { cat('\n') } } } cat('\n') }
"Lorenz63"
imputeHeinze <- function(data, pool=TRUE) { time <- data[,1] status <- data[,2] g1 <- data[,3] == 0 g2 <- !g1 data1 <- data[g1,] data2 <- data[g2,] tmax <- max(time) time1 <- data1[,1] status1 <- data1[,2] time2 <- data2[,1] status2 <- data2[,2] if(pool) { fitS1 <- survfit(Surv(time, status) ~ 1) fitS2 <- fitS1 } else { fitS1 <- survfit(Surv(time1, status1) ~ 1) fitS2 <- survfit(Surv(time2, status2) ~ 1) } fit1 <- survfit(Surv(time1, 1-status1) ~ 1) fit2 <- survfit(Surv(time2, 1-status2) ~ 1) if(pool) { fS1 <- approxfun(fitS1$time, fitS1$surv, method="constant", yleft=1, rule=2, f=0) fS2 <- fS1 } else { fS1 <- approxfun(fitS1$time, fitS1$surv, method="constant", yleft=1, rule=2, f=0) fS2 <- approxfun(fitS2$time, fitS2$surv, method="constant", yleft=1, rule=2, f=0) } f1 <- approxfun(fit1$time, fit1$surv, method="constant", yleft=1, rule=2, f=0) f2 <- approxfun(fit2$time, fit2$surv, method="constant", yleft=1, rule=2, f=0) list(fS1=fS1, fS2=fS2, f1=f1, f2=f2, fitS1=fitS1, fitS2=fitS2, fit1=fit1, fit2=fit2, tmax=tmax, g1=g1, g2=g2, data=data) } permuteHeinze <- function(imp, pp, index=TRUE) { pdata <- imp$data[pp, ] T <- pdata[,1] C <- imp$data[,1] pdelta <- as.logical(pdata[,2]) vS1 <- !pdelta & imp$g1 vS2 <- !pdelta & imp$g2 if(any(vS1)) { tmp <- sampleFromCondKM(T[vS1], imp$fitS1, imp$tmax, 1, imp$fS1) T[vS1] <- tmp[1,] pdelta[vS1] <- tmp[2,] } if(any(vS2)) { tmp <- sampleFromCondKM(T[vS2], imp$fitS2, imp$tmax, 1, imp$fS2) T[vS2] <- tmp[1,] pdelta[vS2] <- tmp[2,] } v1 <- imp$data[,2] & imp$g1 v2 <- imp$data[,2] & imp$g2 if(any(v1)) C[v1] <- sampleFromCondKM(C[v1], imp$fit1, imp$tmax, 0, imp$f1)[1,] if(any(v2)) C[v2] <- sampleFromCondKM(C[v2], imp$fit2, imp$tmax, 0, imp$f2)[1,] pY <- pmin(T, C) pdelta <- (T <= C) * pdelta matrix(c(pY, pdelta, imp$data[,3]), ncol=3, nrow=length(pY)) }
library(tidyverse) library(data.table) library(lubridate) library(readr) library(countrycode) library(ggplot2) options(scipen=999) inspect = FALSE pred_matrix <- readRDS("output-data/pred_matrix.RDS") export_covariates <- readRDS("output-data/export_covariates.RDS") pred_matrix <- pred_matrix[nchar(export_covariates$iso3c) == 3, ] export_covariates <- export_covariates[nchar(export_covariates$iso3c) == 3, ] pred_matrix <- pred_matrix*export_covariates$population / 100000 export_covariates$week <- round(as.numeric(export_covariates$date)/7, 0)+1-min(round(as.numeric(export_covariates$date)/7, 0)) export_covariates$date[export_covariates$date != max(export_covariates$date)] <- ave(export_covariates$date[export_covariates$date != max(export_covariates$date)], export_covariates$week[export_covariates$date != max(export_covariates$date)], FUN = function(x) min(x, na.rm = T)) pred_matrix <- pred_matrix[!duplicated(paste0(export_covariates$date, "_", export_covariates$iso3c)), ] export_covariates <- export_covariates[!duplicated(paste0(export_covariates$date, "_", export_covariates$iso3c)), ] min(table(export_covariates$date)) == max(table(export_covariates$date)) estimate <- as.numeric(pred_matrix[, 1]) export_covariates$row_order <- 1:nrow(export_covariates) export_covariates <- merge(export_covariates, read_csv("source-data/economist_country_names.csv")[, c("Name", "ISOA3", "Regions", "Income group WB", "Economy IMF")], by.x = "iso3c", by.y = "ISOA3", all.x = T) export_covariates <- export_covariates[order(export_covariates$row_order), ] export_covariates$row_order <- NULL export_covariates$country <- export_covariates$Name export_covariates$country[is.na(export_covariates$country)] <- countrycode( export_covariates$iso3c[is.na(export_covariates$country)], "iso3c", "country.name") export_covariates$Name <- NULL export_covariates$continent <- countrycode(export_covariates$iso3c, "iso3c", "continent") confidence_intervals <- function(new_col_names = "estimated_daily_excess_deaths", group = "iso3c", unit = "iso3c", time = "date", population = "population", known_data_column = "daily_excess_deaths", recorded_data_column = "daily_covid_deaths", return_cumulative = F, drop_ci_if_known_data = T, covars = export_covariates, bootstrap_predictions = pred_matrix, model_prediction = estimate, include_model_prediction_in_ci = T, include_final_prediction_in_ci = T, recency_buffer = 0, return_histogram_data = F ){ if(sum(is.na(covars[, group])) > 0){ stop("Some observations lack a grouping.") } if(sum(is.na(bootstrap_predictions)) + sum(is.na(model_prediction)) != 0){ stop("Some predictions are NA.") } if(nrow(covars) != nrow(bootstrap_predictions) | nrow(covars) != length(model_prediction)){ stop("Dimensionality mismatch: check that predictions are 1-1 mapped to covars") } if(max(covars[, time]) > Sys.Date()-recency_buffer){ most_recent <- sort(unique(covars[, time]), decreasing = T)[2] temp_boot <- bootstrap_predictions[covars[, time] == most_recent, ] temp_estimate <- estimate[covars[, time] == most_recent] temp_covars <- covars[covars[, time] == most_recent, ] max_time <- max(covars[, time]) for(i in unique(covars[, unit])){ bootstrap_predictions[covars[, time] == max_time & covars[, unit] == i, ] <- temp_boot[temp_covars[, unit] == i, ] estimate[covars[, time] == max_time & covars[, unit] == i] <- temp_estimate[temp_covars[, unit] == i] } } recorded_data <- as.numeric(covars[, recorded_data_column]) raw_estimate <- estimate if(!missing(known_data_column)){ known_data <- covars[, known_data_column] estimate[!is.na(known_data)] <- known_data[!is.na(known_data)] } else { known_data <- rep(NA, nrow(covars)) } if(drop_ci_if_known_data){ for(i in 1:ncol(bootstrap_predictions)){ bootstrap_predictions[!is.na(known_data), i] <- known_data[!is.na(known_data)] } } covars$id <- paste0(covars[, group], "_", covars[, time]) if(max(table(covars$id)) > 1){ estimate <- ave(estimate, covars$id, FUN = function(x) sum(x)) known_data <- ave(known_data, covars$id, FUN = function(x) sum(x, na.rm = T)) raw_estimate <- ave(known_data, covars$id, FUN = function(x) sum(x, na.rm = T)) recorded_data <- ave(recorded_data, covars$id, FUN = function(x) sum(x, na.rm = T)) for(i in 1:ncol(bootstrap_predictions)){ bootstrap_predictions[, i] <- ave(bootstrap_predictions[, i], covars$id, FUN = function(x) sum(x)) } covars$population <- ave(covars$population, covars$id, FUN = function(x) sum(x, na.rm = T)) } if(return_cumulative){ bootstrap_predictions <- data.frame(bootstrap_predictions) bootstrap_predictions$row_order <- 1:nrow(bootstrap_predictions) bootstrap_predictions[, unit] <- covars[, unit] bootstrap_predictions[, time] <- covars[, time] bootstrap_predictions$raw_estimate <- raw_estimate bootstrap_predictions$known_data <- ifelse(is.na(known_data), 0, known_data) bootstrap_predictions$recorded_data <- ifelse(is.na(recorded_data), 0, recorded_data) bootstrap_predictions <- bootstrap_predictions[ order(bootstrap_predictions[, time]), ] week_mult <- rep(7, length(unique(bootstrap_predictions[, time]))) week_mult[length(week_mult)] <- as.numeric(rev(sort(unique(bootstrap_predictions[, time])))[1]-rev(sort(unique(bootstrap_predictions[, time])))[2]) for(i in setdiff(colnames(bootstrap_predictions), c("row_order", unit, time))){ bootstrap_predictions[, i] <- ave(bootstrap_predictions[, i], bootstrap_predictions[, unit], FUN = function(x){ cumsum(x*week_mult)}) } bootstrap_predictions <- bootstrap_predictions[ order(bootstrap_predictions$row_order), ] bootstrap_predictions$iso3c <- NULL bootstrap_predictions$date <- NULL bootstrap_predictions$row_order <- NULL raw_estimate <- bootstrap_predictions$raw_estimate bootstrap_predictions$raw_estimate <- NULL recorded_data <- bootstrap_predictions$recorded_data bootstrap_predictions$recorded_data <- NULL estimate <- bootstrap_predictions[, 1] known_data <- bootstrap_predictions$known_data bootstrap_predictions$known_data <- NULL bootstrap_predictions <- as.matrix(bootstrap_predictions) } estimate <- estimate[!duplicated(covars$id)] raw_estimate <- raw_estimate[!duplicated(covars$id)] bootstrap_predictions <- bootstrap_predictions[!duplicated(covars$id), ] known_data <- known_data[!duplicated(covars$id)] recorded_data <- recorded_data[!duplicated(covars$id)] covars <- covars[!duplicated(covars$id), ] for(i in 1:nrow(bootstrap_predictions)){ bootstrap_predictions[i, ] <- sort(bootstrap_predictions[i, ]) } if(return_histogram_data){ histagram_data <- cbind(covars[, c(group, time, population)], estimate, bootstrap_predictions[, 2:ncol(bootstrap_predictions)]) colnames(histagram_data)[1:4] <- c(colnames(covars[, c(group, time, population)]), "estimate") return(histagram_data) } ci_95_top <- bootstrap_predictions[, round(ncol(bootstrap_predictions)*0.975, 0)] ci_90_top <- bootstrap_predictions[, round(ncol(bootstrap_predictions)*0.95, 0)] ci_50_top <- bootstrap_predictions[, round(ncol(bootstrap_predictions)*0.75, 0)] ci_50_bot <- bootstrap_predictions[, round(ncol(bootstrap_predictions)*0.25, 0)] ci_90_bot <- bootstrap_predictions[, round(ncol(bootstrap_predictions)*0.05, 0)] ci_95_bot <- bootstrap_predictions[, round(ncol(bootstrap_predictions)*0.025, 0)] if(include_model_prediction_in_ci){ ci_95_top <- ifelse(ci_95_top > raw_estimate, ci_95_top, raw_estimate) ci_90_top <- ifelse(ci_90_top > raw_estimate, ci_90_top, raw_estimate) ci_50_top <- ifelse(ci_50_top > raw_estimate, ci_50_top, raw_estimate) ci_50_bot <- ifelse(ci_50_bot < raw_estimate, ci_50_bot, raw_estimate) ci_90_bot <- ifelse(ci_90_bot < raw_estimate, ci_90_bot, raw_estimate) ci_95_bot <- ifelse(ci_95_bot < raw_estimate, ci_95_bot, raw_estimate) } if(include_final_prediction_in_ci){ ci_95_top <- ifelse(ci_95_top > estimate, ci_95_top, estimate) ci_90_top <- ifelse(ci_90_top > estimate, ci_90_top, estimate) ci_50_top <- ifelse(ci_50_top > estimate, ci_50_top, estimate) ci_50_bot <- ifelse(ci_50_bot < estimate, ci_50_bot, estimate) ci_90_bot <- ifelse(ci_90_bot < estimate, ci_90_bot, estimate) ci_95_bot <- ifelse(ci_95_bot < estimate, ci_95_bot, estimate) } result <- cbind.data.frame(covars[, c(group, time, population)], estimate, ci_95_top, ci_90_top, ci_50_top, ci_50_bot, ci_90_bot, ci_95_bot, raw_estimate, known_data, recorded_data) colnames(result) <- c(colnames(covars[, c(group, time, population)]), paste0(new_col_names), paste0(new_col_names, "_ci_95_top"), paste0(new_col_names, "_ci_90_top"), paste0(new_col_names, "_ci_50_top"), paste0(new_col_names, "_ci_50_bot"), paste0(new_col_names, "_ci_90_bot"), paste0(new_col_names, "_ci_95_bot"), paste0(new_col_names, "_raw_estimate"), "daily_excess_deaths", "daily_covid_deaths") if(return_cumulative){ colnames(result)[4:ncol(result)] <- paste0("cumulative_", colnames(result)[4:ncol(result)]) } result <- unique(result) return(result) } country_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "iso3c", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = F, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = T) if(inspect){ ggplot(country_export[country_export$iso3c %in% c("IND", "ZAF", "USA", "CHN", "IDN", "PAK", "BRA", "NGA"), ], aes(x=date, y=estimated_daily_excess_deaths, col = iso3c))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_50_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_50_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ geom_line(aes(y=daily_excess_deaths), col="black", linetype = "solid")+geom_line(aes(y=daily_covid_deaths), col = "red")+ facet_wrap(.~iso3c)+theme_minimal()+ theme(legend.position = "none") } write_csv(country_export, "output-data/export_country.csv") country_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "iso3c", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = F, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = T) per_capita_columns <- grep("deaths", colnames(country_export)) for(i in per_capita_columns){ country_export[, i] <- 100000*country_export[, i]/country_export[, "population"] } colnames(country_export)[per_capita_columns] <- paste0(colnames(country_export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(country_export[country_export$iso3c %in% c("IND", "ZAF", "USA", "CHN", "IDN", "RUS", "BRA", "NGA", "MEX"), ], aes(x=date, y=estimated_daily_excess_deaths_per_100k, col = iso3c))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+ geom_line(aes(y=daily_excess_deaths_per_100k), col="black", linetype = "solid")+ facet_wrap(.~iso3c)+theme_minimal()+ theme(legend.position = "none") } write_csv(country_export, "output-data/export_country_per_100k.csv") region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "continent", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(region_export, aes(x=date, y=estimated_daily_excess_deaths, col = continent))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent)+theme_minimal()+ theme(legend.position = "none") } write_csv(region_export, "output-data/export_regions.csv") export_covariates$continent_alt <- countrycode(export_covariates$iso3c, "iso3c", "continent") export_covariates$continent_alt[export_covariates$continent_alt == "Europe"] <- "Europe, United States, Canada, and Oceania" export_covariates$continent_alt[export_covariates$iso3c %in% c("USA", "CAN")] <- "Europe, United States, Canada, and Oceania" export_covariates$continent_alt[export_covariates$continent_alt == "Oceania"] <- "Europe, United States, Canada, and Oceania" export_covariates$continent_alt[export_covariates$continent_alt == "Americas"] <- "Latin America and Caribbean" region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "continent_alt", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(region_export, aes(x=date, y=estimated_daily_excess_deaths, col = continent_alt))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent_alt)+theme_minimal()+ theme(legend.position = "none") } region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "continent", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) per_capita_columns <- grep("deaths", colnames(region_export)) for(i in per_capita_columns){ region_export[, i] <- 100000*region_export[, i]/region_export[, "population"] } colnames(region_export)[per_capita_columns] <- paste0(colnames(region_export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(region_export, aes(x=date, y=estimated_daily_excess_deaths_per_100k, col = continent))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent)+theme_minimal()+ theme(legend.position = "none") } write_csv(region_export, "output-data/export_regions_per_100k.csv") export_covariates$world <- "World" world_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "world", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(world_export, aes(x=date, y=estimated_daily_excess_deaths, col = world))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_50_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_50_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+theme_minimal()+ theme(legend.position = "none") } write_csv(world_export, "output-data/export_world.csv") world_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "world", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) per_capita_columns <- grep("deaths", colnames(world_export)) for(i in per_capita_columns){ world_export[, i] <- 100000*world_export[, i]/world_export[, "population"] } colnames(world_export)[per_capita_columns] <- paste0(colnames(world_export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(world_export, aes(x=date, y=estimated_daily_excess_deaths_per_100k, col = world))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+theme_minimal()+ theme(legend.position = "none") } write_csv(world_export, "output-data/export_world_per_100k.csv") country_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "iso3c", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(country_export[country_export$iso3c %in% c("IND", "CHN"), ], aes(x=date, y=cumulative_estimated_daily_excess_deaths, col = iso3c))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_50_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_50_bot))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ geom_line(aes(y=cumulative_daily_excess_deaths), col="black", linetype = "solid")+ geom_line(aes(y=cumulative_daily_covid_deaths), col = "red")+ facet_wrap(.~iso3c)+theme_minimal()+ theme(legend.position = "none") } write_csv(country_export, "output-data/export_country_cumulative.csv") country_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "iso3c", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) per_capita_columns <- grep("deaths", colnames(country_export)) for(i in per_capita_columns){ country_export[, i] <- 100000*country_export[, i]/country_export[, "population"] } colnames(country_export)[per_capita_columns] <- paste0(colnames(country_export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(country_export[country_export$iso3c %in% c("IND", "USA", "MEX", "PER", "RUS", "ZAF"), ], aes(x=date, y=cumulative_estimated_daily_excess_deaths_per_100k, col = iso3c))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+ geom_line(aes(y=cumulative_daily_excess_deaths_per_100k), col="black", linetype = "solid")+ facet_wrap(.~iso3c)+theme_minimal()+ theme(legend.position = "none") } write_csv(country_export, "output-data/export_country_per_100k_cumulative.csv") region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "continent", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(region_export, aes(x=date, y=cumulative_estimated_daily_excess_deaths, col = continent))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_50_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_50_bot))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+geom_line(aes(y=cumulative_daily_covid_deaths), col = "red")+ facet_wrap(.~continent)+theme_minimal()+ theme(legend.position = "none") } write_csv(region_export, "output-data/export_regions_cumulative.csv") region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "continent", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) per_capita_columns <- grep("deaths", colnames(region_export)) for(i in per_capita_columns){ region_export[, i] <- 100000*region_export[, i]/region_export[, "population"] } colnames(region_export)[per_capita_columns] <- paste0(colnames(region_export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(region_export, aes(x=date, y=cumulative_estimated_daily_excess_deaths_per_100k, col = continent))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent)+theme_minimal()+ theme(legend.position = "none") } write_csv(region_export, "output-data/export_regions_per_100k_cumulative.csv") export_covariates$world <- "World" world_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "world", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) ggplot(world_export, aes(x=date, y=cumulative_estimated_daily_excess_deaths, col = world))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot))+ geom_line(aes(y=cumulative_daily_covid_deaths), col = "blue")+ geom_ribbon(aes(ymin=cumulative_estimated_daily_excess_deaths_ci_95_top, ymax=cumulative_estimated_daily_excess_deaths_ci_95_bot), fill = 'darkred', alpha=0.3)+ geom_line(col="black", linetype = "dashed")+theme_minimal()+ theme(legend.position = "none")+xlab("Estimated excess deaths (red), confirmed covid-19 deaths (blue)")+ylab("Total deaths, World") ggsave('global_mortality.png', width = 8, height = 5) write_csv(world_export, "output-data/export_world_cumulative.csv") export_covariates$world <- "World" world_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "world", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F, return_histogram_data = T) write_csv(world_export, "output-data/export_world_cumulative_histogram_data.csv") world_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "world", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) per_capita_columns <- grep("deaths", colnames(world_export)) for(i in per_capita_columns){ world_export[, i] <- 100000*world_export[, i]/world_export[, "population"] } colnames(world_export)[per_capita_columns] <- paste0(colnames(world_export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(world_export, aes(x=date, y=cumulative_estimated_daily_excess_deaths_per_100k, col = world))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+theme_minimal()+ theme(legend.position = "none") } write_csv(world_export, "output-data/export_world_per_100k_cumulative.csv") export_covariates$world <- "World" world_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "world", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) export_covariates_alt <- export_covariates export_covariates_alt$daily_excess_deaths_alt <- export_covariates$daily_excess_deaths export_covariates_alt$daily_excess_deaths_alt[is.na(export_covariates_alt$daily_excess_deaths_alt)] <- export_covariates_alt$daily_covid_deaths[is.na(export_covariates_alt$daily_excess_deaths_alt)] world_export_alt <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "world", time = "date", covars = export_covariates_alt, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", recorded_data_column = "daily_excess_deaths_alt", model_prediction = estimate, include_model_prediction_in_ci = F) world_export$cumulative_daily_excess_deaths_alternative <- world_export_alt$cumulative_daily_covid_deaths if(inspect){ ggplot(world_export, aes(x=date, y=cumulative_estimated_daily_excess_deaths, col = world))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot))+ geom_line(aes(y=cumulative_daily_excess_deaths_alternative, col = "red"))+ geom_line(aes(y=cumulative_daily_covid_deaths), col = "black")+ geom_line(col="black", linetype = "dashed")+theme_minimal()+ theme(legend.position = "none") } export_covariates$continent_alt <- countrycode(export_covariates$iso3c, "iso3c", "continent") export_covariates$continent_alt[export_covariates$continent_alt == "Europe"] <- "Europe, United States, Canada, and Oceania" export_covariates$continent_alt[export_covariates$iso3c %in% c("USA", "CAN")] <- "Europe, United States, Canada, and Oceania" export_covariates$continent_alt[export_covariates$continent_alt == "Oceania"] <- "Europe, United States, Canada, and Oceania" export_covariates$continent_alt[export_covariates$continent_alt == "Americas"] <- "Latin America and Caribbean" region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "continent_alt", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(region_export, aes(x=date, y=estimated_daily_excess_deaths, col = continent_alt))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent_alt)+theme_minimal()+ theme(legend.position = "none") } write_csv(region_export, "output-data/output-by-alternative-regions/export_regions_EU_NA_Oceania_collapsed.csv") export_covariates$custom_regions <- countrycode(export_covariates$iso3c, "iso3c", "continent") export_covariates$custom_regions[export_covariates$iso3c %in% c("USA", "CAN")] <- "North America" export_covariates$custom_regions[export_covariates$custom_regions == "Americas"] <- "Latin America and Caribbean" export_covariates$custom_regions[export_covariates$iso3c %in% c("AUT", "BEL", "BGR", "HRV", "CYP", "CZE", "DNK", "EST", "FIN", "FRA", "DEU", "GRC", "HUN", "IRL", "ITA", "LVA", "LTU", "LUX", "MLT", "NLD", "POL", "PRT", "ROU", "SVK", "SVN", "ESP", "SWE")] <- "European Union" export_covariates$custom_regions[export_covariates$custom_regions == "Europe"] <- "Europe (not EU)" export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "custom_regions", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) export <- export[export$custom_regions %in% c("Latin America and Caribbean", "North America", "European Union", "Asia", "Oceania"), ] if(inspect){ ggplot(export[, ], aes(x=date, y=estimated_daily_excess_deaths, col = custom_regions))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~custom_regions)+theme_minimal()+ theme(legend.position = "none") } write_csv(export, "output-data/output-by-alternative-regions/export_regions_lat_am_na_eu.csv") per_capita_columns <- grep("deaths", colnames(export)) for(i in per_capita_columns){ export[, i] <- 100000*export[, i]/export[, "population"] } colnames(export)[per_capita_columns] <- paste0(colnames(export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(export[, ], aes(x=date, y=estimated_daily_excess_deaths_per_100k, col = custom_regions))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~custom_regions)+theme_minimal()+ theme(legend.position = "none") } write_csv(export, "output-data/output-by-alternative-regions/export_regions_lat_am_na_eu_per_100k.csv") export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "custom_regions", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) export <- export[export$custom_regions %in% c("Latin America and Caribbean", "North America", "European Union", "Asia", "Oceania"), ] if(inspect){ ggplot(export[, ], aes(x=date, y=cumulative_estimated_daily_excess_deaths, col = custom_regions))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~custom_regions)+theme_minimal()+ theme(legend.position = "none") } write_csv(export, "output-data/output-by-alternative-regions/export_regions_lat_am_na_eu_cumulative.csv") per_capita_columns <- grep("deaths", colnames(export)) for(i in per_capita_columns){ export[, i] <- 100000*export[, i]/export[, "population"] } colnames(export)[per_capita_columns] <- paste0(colnames(export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(export[, ], aes(x=date, y=cumulative_estimated_daily_excess_deaths_per_100k, col = custom_regions))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~custom_regions)+theme_minimal()+ theme(legend.position = "none") } write_csv(export, "output-data/output-by-alternative-regions/export_regions_lat_am_na_eu_per_100k_cumulative.csv") export_covariates$continent_alt <- countrycode(export_covariates$iso3c, "iso3c", "continent") export_covariates$continent_alt[export_covariates$iso3c %in% c("USA", "CAN")] <- "US and Canada" export_covariates$continent_alt[export_covariates$continent_alt == "Americas"] <- "Latin America and Caribbean" region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "continent_alt", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(region_export, aes(x=date, y=estimated_daily_excess_deaths, col = continent_alt))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent_alt)+theme_minimal()+ theme(legend.position = "none") } per_capita_columns <- grep("deaths", colnames(region_export)) for(i in per_capita_columns){ region_export[, i] <- 100000*region_export[, i]/region_export[, "population"] } colnames(region_export)[per_capita_columns] <- paste0(colnames(region_export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(region_export, aes(x=date, y=estimated_daily_excess_deaths_per_100k, col = continent_alt))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent_alt)+theme_minimal()+ theme(legend.position = "none") } region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "continent_alt", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(region_export, aes(x=date, y=cumulative_estimated_daily_excess_deaths, col = continent_alt))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent_alt)+theme_minimal()+ theme(legend.position = "none") } per_capita_columns <- grep("deaths", colnames(region_export)) for(i in per_capita_columns){ region_export[, i] <- 100000*region_export[, i]/region_export[, "population"] } colnames(region_export)[per_capita_columns] <- paste0(colnames(region_export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(region_export, aes(x=date, y=cumulative_estimated_daily_excess_deaths_per_100k, col = continent_alt))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent_alt)+theme_minimal()+ theme(legend.position = "none") } country_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "iso3c", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = F, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = T) if(inspect){ ggplot(country_export[country_export$iso3c %in% c("EGY"), ], aes(x=date, y=estimated_daily_excess_deaths, col = iso3c))+ geom_line(col="black", linetype = "dashed")+ geom_line(aes(y=daily_excess_deaths), col="black", linetype = "solid")+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_raw_estimate))+ facet_wrap(.~iso3c)+theme_minimal()+ theme(legend.position = "none") } country_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "iso3c", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = F, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = T) oecd <- country_export[country_export$iso3c %in% c("AUT","AUS","BEL","CAN","CHL","COL","CZE","DNK","EST","FIN","FRA","DEU","GRC","HUN","ISL","IRL","ISR","ITA","JPN","KOR","LVA","LTU","LUX","MEX", "NLD", "NZL","NOR","POL","PRT","SVK","SVN","ESP","SWE","CHE","TUR","GBR","USA") & country_export$date == max(country_export$date), ] sum(oecd$cumulative_estimated_daily_excess_deaths)/sum(oecd$cumulative_daily_covid_deaths) export_covariates$region <- countrycode(export_covariates$iso3c, "iso3c", "region") export_covariates$region[is.na(export_covariates$region)] <- "SHN" ssa_region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "region", time = "date", covars = export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) ssa_region_export <- ssa_region_export[ssa_region_export$region == "Sub-Saharan Africa" & ssa_region_export$date == max(ssa_region_export$date), ] sum(ssa_region_export$cumulative_estimated_daily_excess_deaths)/sum(ssa_region_export$cumulative_daily_covid_deaths) income_groups <- read_csv("source-data/world_bank_income_groups.csv") income_groups <- income_groups[income_groups$GroupCode%in% c("LIC", "LMC", "UMC", "HIC"), c("CountryCode", "GroupName")] colnames(income_groups) <- c("iso3c", "World_Bank_income_group") export_covariates$`Income group WB` <- NULL export_covariates$row_order <- 1:nrow(export_covariates) wb_export_covariates <- merge(export_covariates, income_groups, by = "iso3c", all.x = T) wb_export_covariates$World_Bank_income_group[is.na(wb_export_covariates$World_Bank_income_group)] <- "Unknown income group" wb_export_covariates <- wb_export_covariates[order(wb_export_covariates$row_order), ] wb_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "World_Bank_income_group", time = "date", covars = wb_export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(wb_export[wb_export$World_Bank_income_group != "Unknown income group", ], aes(x=date, y=estimated_daily_excess_deaths, col = World_Bank_income_group))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~World_Bank_income_group)+theme_minimal()+ theme(legend.position = "none") } write_csv(wb_export, "output-data/output-by-world-bank-income-group/wb_income_groups.csv") per_capita_columns <- grep("deaths", colnames(wb_export)) for(i in per_capita_columns){ wb_export[, i] <- 100000*wb_export[, i]/wb_export[, "population"] } colnames(wb_export)[per_capita_columns] <- paste0(colnames(wb_export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(wb_export[wb_export$World_Bank_income_group != "Unknown income group", ], aes(x=date, y=estimated_daily_excess_deaths_per_100k, col = World_Bank_income_group))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~World_Bank_income_group)+theme_minimal()+ theme(legend.position = "none") } write_csv(wb_export, "output-data/output-by-world-bank-income-group/wb_income_groups_per_100k.csv") wb_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "World_Bank_income_group", time = "date", covars = wb_export_covariates, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(wb_export[wb_export$World_Bank_income_group != "Unknown income group", ], aes(x=date, y=cumulative_estimated_daily_excess_deaths, col = World_Bank_income_group))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~World_Bank_income_group)+theme_minimal()+ theme(legend.position = "none") } write_csv(wb_export, "output-data/output-by-world-bank-income-group/wb_income_groups_cumulative.csv") per_capita_columns <- grep("deaths", colnames(wb_export)) for(i in per_capita_columns){ wb_export[, i] <- 100000*wb_export[, i]/wb_export[, "population"] } colnames(wb_export)[per_capita_columns] <- paste0(colnames(wb_export)[per_capita_columns], "_per_100k") if(inspect){ ggplot(wb_export[wb_export$World_Bank_income_group != "Unknown income group", ], aes(x=date, y=cumulative_estimated_daily_excess_deaths_per_100k, col = World_Bank_income_group))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_top_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_90_bot_per_100k))+ geom_line(aes(y=cumulative_estimated_daily_excess_deaths_ci_95_bot_per_100k))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~World_Bank_income_group)+theme_minimal()+ theme(legend.position = "none") } write_csv(wb_export, "output-data/output-by-world-bank-income-group/wb_income_groups_per_100k_cumulative.csv") export_covariates$continent_alt <- "Other" export_covariates$continent_alt[export_covariates$iso3c %in% c("AUS", "AUT", "BEL", "BGR", "CAN", "CHE", "CHI", "CYP", "CZE", "DEU", "DNK", "ESP", "EST", "FIN", "FRA", "FRO", "GBR", "GIB", "GRC", "GRL", "HRV", "HUN", "IMN", "IRL", "ISL", "ITA", "LIE", "LTU", "LUX", "LVA", "MCO", "MEX", "MLT", "NLD", "NOR", "NZL", "POL", "PRT", "ROU", "SHN", "SMR", "SPM", "SVK", "SVN", "SWE", "USA", "VAT")] <- "W. Europe, NA, and Aus/NZ" region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "continent_alt", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(region_export[region_export$continent_alt != "Other", ], aes(x=date, y=estimated_daily_excess_deaths, col = continent_alt))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent_alt)+theme_minimal()+ theme(legend.position = "none") } write_csv(region_export[region_export$continent_alt != "Other", ], "output-data/output-by-alternative-regions/export_regions_w_europe_aus_nz_north_america.csv") export_covariates$continent_alt <- "Other" export_covariates$continent_alt[export_covariates$iso3c %in% c( "AUT", "BEL", "BGR", "CHE", "CHI", "CYP", "CZE", "DEU", "DNK", "ESP", "EST", "FIN", "FRA", "FRO", "GBR", "GIB", "GRC", "GRL", "HRV", "HUN", "IMN", "IRL", "ISL", "ITA", "LIE", "LTU", "LUX", "LVA", "MCO", "MLT", "NLD", "NOR", "POL", "PRT", "ROU", "SHN", "SMR", "SPM", "SVK", "SVN", "SWE", "VAT")] <- "W. Europe" region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "continent_alt", time = "date", covars = export_covariates, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = F) if(inspect){ ggplot(region_export[region_export$continent_alt != "Other", ], aes(x=date, y=estimated_daily_excess_deaths, col = continent_alt))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_top))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_90_bot))+ geom_line(aes(y=estimated_daily_excess_deaths_ci_95_bot))+ geom_line(col="black", linetype = "dashed")+ facet_wrap(.~continent_alt)+theme_minimal()+ theme(legend.position = "none") } write_csv(region_export[region_export$continent_alt != "Other", ], "output-data/output-by-alternative-regions/export_regions_western_europe.csv") custom_region_export <- function( region, name = "un_subregion", data = export_covariates, folder_prefix = "output-data/output-by-alternative-regions/export_regions_"){ data[, "region"] <- data[, region] data$region[is.na(data$region)] <- "Other" region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "region", time = "date", covars = data, return_cumulative = F, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = T) write_csv(region_export, paste0(folder_prefix, name, ".csv")) per_capita_columns <- grep("deaths", colnames(region_export)) for(i in per_capita_columns){ region_export[, i] <- 100000*region_export[, i]/region_export[, "population"] } colnames(region_export)[per_capita_columns] <- paste0(colnames(region_export)[per_capita_columns], "_per_100k") write_csv(region_export, paste0(folder_prefix, name, "_per_100k.csv")) region_export <- confidence_intervals(new_col_names = "estimated_daily_excess_deaths", group = "region", time = "date", covars = data, return_cumulative = T, drop_ci_if_known_data = T, bootstrap_predictions = pred_matrix, known_data_column = "daily_excess_deaths", model_prediction = estimate, include_model_prediction_in_ci = T) write_csv(region_export, paste0(folder_prefix, name, "_cumulative.csv")) per_capita_columns <- grep("deaths", colnames(region_export)) for(i in per_capita_columns){ region_export[, i] <- 100000*region_export[, i]/region_export[, "population"] } colnames(region_export)[per_capita_columns] <- paste0(colnames(region_export)[per_capita_columns], "_per_100k") write_csv(region_export, paste0(folder_prefix, name, "_per_100k_cumulative.csv")) } export_covariates$un_subregion <- countrycode(export_covariates$iso3c, "iso3c", "un.regionsub.name") custom_region_export(region = "un_subregion", name = "un_subregion") export_covariates$wb_region <- countrycode(export_covariates$iso3c, "iso3c", "region") custom_region_export(region = "wb_region", name = "wb_region") if(inspect){ for(name in c("un_subregion", "wb_region")){ pdat <- read_csv(paste0(folder_prefix, name, ".csv")) ggplot(pdat, aes(x=date, y=estimated_daily_excess_deaths))+facet_wrap(.~region)+geom_line() pdat <- read_csv(paste0(folder_prefix, name, "_per_100k.csv")) ggplot(pdat, aes(x=date, y=estimated_daily_excess_deaths_per_100k))+facet_wrap(.~region)+geom_line() pdat <- read_csv(paste0(folder_prefix, name, "_cumulative.csv")) ggplot(pdat, aes(x=date, y=cumulative_estimated_daily_excess_deaths))+facet_wrap(.~region)+geom_line() pdat <- read_csv(paste0(folder_prefix, name, "_per_100k_cumulative.csv")) ggplot(pdat, aes(x=date, y=cumulative_estimated_daily_excess_deaths_per_100k))+facet_wrap(.~region)+geom_line() } }
shift_to <- function(RIA_data_in, to = -1024, min_value_in = NULL, use_orig = TRUE, write_orig = TRUE, verbose_in = TRUE) { data_in <- check_data_in(RIA_data_in, use_type = "single", use_orig = use_orig, verbose_in = verbose_in) if (!is.null(min_value_in)) {shift <- (-min_value_in + to) } else {shift <- to} RIA_data_mod <- data_in + shift if(any(class(RIA_data_in) == "RIA_image") ) { if(write_orig) {RIA_data_in$data$orig <- RIA_data_mod } else {RIA_data_in$data$modif<- RIA_data_mod} if(!any(class(RIA_data_in$data) == "RIA_data")) class(RIA_data_in$data) <- append(class(RIA_data_in$data), "RIA_data") RIA_data_in$log$shift <- shift RIA_data_in$log$events <- append(RIA_data_in$log$events, paste("Shifted_by_", shift, sep = "")) return(RIA_data_in) } else return(RIA_data_mod) }
df.col.findId <- function(df, label_name) { if (!is.character(label_name) & !is.numeric(label_name)) { stop("Argument label_name is not a character or a numeric vector.") } if (is.character(label_name) == TRUE) { if (all(!is.na(label_name))) { col.id <- match(label_name, colnames(df)) if(any(is.na(col.id))){ stop(paste("Error in argument label_name. label_name } } else { stop("Argument label_name doesn't match any column name.") } } else { if (length(label_name) <= ncol(df)) { col.id <- label_name } else { stop("Argument label_name is out of bound.") } } return(col.id) }
get_DRAC_references <- function(x) { refs <- DRAC_refs() refs_names <- names(refs) used <- list(refs = NULL, desc = NULL) ref_tmp <- unique(x$`TI:4`) for (i in 1:length(ref_tmp)) { if (ref_tmp[i] == "X") next used$refs <- c(used$refs, refs[refs_names %in% ref_tmp[i]]) used$desc <- c(used$desc, "Conversion factors") } ref_tmp <- unique(x$`TI:13`) if (any(ref_tmp == "Y")) { used$refs <- c(used$refs, refs["Mejdahl1987"]) used$desc <- c(used$desc, "External rubidium") } ref_tmp <- unique(x$`TI:22`) if (any(ref_tmp == "Y")) { used$refs <- c(used$refs, refs["Mejdahl1987"]) used$desc <- c(used$desc, "Internal rubidium") } ref_tmp <- unique(x$`TI:31`) if (any(ref_tmp == "Y")) { used$refs <- c(used$refs, refs["Aitken1985"]) used$desc <- c(used$desc, "Gamma dose rate scaling") } ref_tmp <- unique(x$`TI:34`) for (i in 1:length(ref_tmp)) { if (ref_tmp[i] == "X") next used$refs <- c(used$refs, refs[refs_names %in% ref_tmp[i]]) used$desc <- c(used$desc, "Alpha grain size attenuation factors") } ref_tmp <- unique(x$`TI:35`) for (i in 1:length(ref_tmp)) { if (ref_tmp[i] == "X") next used$refs <- c(used$refs, refs[refs_names %in% ref_tmp[i]]) used$desc <- c(used$desc, "Beta grain size attenuation factors") } ref_tmp <- unique(x$`TI:38`) for (i in 1:length(ref_tmp)) { if (ref_tmp[i] == "X") next used$refs <- c(used$refs, refs[refs_names %in% ref_tmp[i]]) used$desc <- c(used$desc, "Beta etch attenuation factor") } ref_tmp <- unique(x$`TI:50`) if (any(ref_tmp == "X")) { used$refs <- c(used$refs, refs[c("PrescottHutton1994", "PrescottStephan1982")]) used$desc <- c(used$desc, c("Cosmic dose rate", "Cosmic dose rate")) } return(used) } DRAC_refs <- function() { list( Aitken1985 = bibentry( bibtype = "Book", author = person("M.J.", "Aitken"), title = "Thermoluminescence Dating", year = "1985", publisher = "Academic Press", adress = "London" ), AitkenXie1990 = bibentry( bibtype = "Article", author = c( person("M.J.", "Aitken"), person("J.", "Xie") ), title = "Moisture correction for annual gamma dose", year = "1990", journal = "Ancient TL", volume = "8", pages = "6-9" ), AdamiecAitken1998 = bibentry( bibtype = "Article", author = c( person("G.", "Adamiec"), person("M.J.", "Aitken") ), title = "Dose-rate conversion factors: update", year = "1998", journal = "Ancient TL", volume = "16", pages = "37-46" ), Guerinetal2011 = bibentry( bibtype = "Article", author = c( person("G.", "Guerin"), person("N.", "Mercier"), person("G.", "Adamiec") ), title = "Dose-rate conversion factors: update", year = "2011", journal = "Ancient TL", volume = "29", pages = "5-8" ), Liritzisetal2013 = bibentry( bibtype = "Article", author = c( person("I.", "Liritzis"), person("K.", "Stamoulis"), person("C.", "Papachristodoulou"), person("K.", "Ioannides") ), title = "A re-evaluation of radiation dose-rate conversion factors. ", year = "2013", journal = "Mediterranean Archaeology and Archaeometry", volume = "13", pages = "1-15" ), Bell1979 = bibentry( bibtype = "Article", author = c( person("W.T.", "Bell") ), title = "Attenuation factors for the absorbed radiation dose in quartz inclusions for thermoluminescence dating", year = "1979", journal = "Ancient TL", volume = "8", pages = "1-12" ), Bell1980 = bibentry( bibtype = "Article", author = c( person("W.T.", "Bell") ), title = "Alpha attenuation in Quartz grains for Thermoluminescence Dating", year = "1980", journal = "Ancient TL", volume = "12", pages = "4-8" ), Brennanetal1991 = bibentry( bibtype = "Article", author = c( person("B.J.", "Brennan"), person("R.G.", "Lyons"), person("S.W.", "Phillips") ), title = "Attenuation of alpha particle track dose for spherical grains", year = "1991", journal = "International Journal of Radiation Applications and Instrumentation. Part D. Nuclear Tracks and Radiation Measurements", volume = "18", pages = "249-253" ), Mejdahl1979 = bibentry( bibtype = "Article", author = c( person("V.", "Mejdahl") ), title = "Thermoluminescence Dating: Beta-Dose Attenuation in Quartz Grains", year = "1979", journal = "Archaeometry", volume = "21", pages = "61-72" ), Mejdahl1987 = bibentry( bibtype = "Article", author = c( person("V.", "Mejdahl") ), title = "Internal radioactivity in quartz and feldspar grains", year = "1987", journal = "Ancient TL", volume = "5", pages = "10-17" ), Brennan2003 = bibentry( bibtype = "Article", author = c( person("B.J.", "Brennan") ), title = "Beta doses to spherical grains", year = "2003", journal = "Radiation Measurements", volume = "37", pages = "299-303" ), `Guerinetal2012-Q` = bibentry( bibtype = "Article", author = c( person("G.", "Guerin"), person("N.", "Mercier"), person("R.", "Nathan"), person("G.", "Adamiec"), person("Y.", "Lefrais") ), title = "On the use of the infinite matrix assumption and associated concepts: A critical review", year = "2012", journal = "Radiation Measurements", volume = "47", pages = "778-785" ), `Guerinetal2012-F` = bibentry( bibtype = "Article", author = c( person("G.", "Guerin"), person("N.", "Mercier"), person("R.", "Nathan"), person("G.", "Adamiec"), person("Y.", "Lefrais") ), title = "On the use of the infinite matrix assumption and associated concepts: A critical review", year = "2012", journal = "Radiation Measurements", volume = "47", pages = "778-785" ), PrescottHutton1994 = bibentry( bibtype = "Article", author = c( person("J.R.", "Prescott"), person("J.T.", "Hutton") ), title = "Cosmic ray contributions to dose rates for luminescence and ESR dating: Large depths and long-term time variations", year = "1994", journal = "Radiation Measurements", volume = "23", pages = "497-500" ), PrescottStephan1982 = bibentry( bibtype = "Article", author = c( person("J.R.", "Prescott"), person("L.G.", "Stephan") ), title = "The contribution of cosmic radiation to the environmental dose for thermoluminescence dating", year = "1982", journal = "PACT", volume = "6", pages = "17-25" ), Readhead2002 = bibentry( bibtype = "Article", author = c( person("M.L.", "ReadHead") ), title = "Absorbed dose fraction for 87Rb beta particles", year = "2002", journal = "Ancient TL", volume = "20", pages = "25-29" ) ) }
test_that("The `action_levels()` helper function works as expected", { al <- action_levels() al %>% expect_is("action_levels") al %>% names() %>% expect_equal( c( "warn_fraction", "warn_count", "stop_fraction", "stop_count", "notify_fraction", "notify_count", "fns") ) al[[7]] %>% names() %>% expect_equal(c("warn", "stop", "notify")) al[[1]] %>% expect_null() al[[2]] %>% expect_null() al[[3]] %>% expect_null() al[[4]] %>% expect_null() al[[5]] %>% expect_null() al[[6]] %>% expect_null() al[[7]] %>% expect_is("list") al[[7]][[1]] %>% expect_null() al[[7]][[2]] %>% expect_null() al[[7]][[3]] %>% expect_null() al %>% length() %>% expect_equal(7) al[[7]] %>% length() %>% expect_equal(3) al <- action_levels(warn_at = 0.2, stop_at = 0.8, notify_at = 0.345) al %>% expect_is("action_levels") al %>% names() %>% expect_equal( c( "warn_fraction", "warn_count", "stop_fraction", "stop_count", "notify_fraction", "notify_count", "fns") ) al[[7]] %>% names() %>% expect_equal(c("warn", "stop", "notify")) al$warn_fraction %>% expect_equal(0.2) al$warn_count %>% expect_null() al$stop_fraction %>% expect_equal(0.8) al$stop_count %>% expect_null() al$notify_fraction %>% expect_equal(0.345) al$notify_count %>% expect_null() al[[7]] %>% expect_is("list") al[[7]][[1]] %>% expect_null() al[[7]][[2]] %>% expect_null() al[[7]][[3]] %>% expect_null() al %>% length() %>% expect_equal(7) al[[7]] %>% length() %>% expect_equal(3) al <- action_levels(warn_at = 20, stop_at = 80, notify_at = 34.6) al %>% expect_is("action_levels") al %>% names() %>% expect_equal( c( "warn_fraction", "warn_count", "stop_fraction", "stop_count", "notify_fraction", "notify_count", "fns") ) al[[7]] %>% names() %>% expect_equal(c("warn", "stop", "notify")) al$warn_fraction %>% expect_null() al$warn_count %>% expect_equal(20) al$stop_fraction %>% expect_null() al$stop_count %>% expect_equal(80) al$notify_fraction %>% expect_null() al$notify_count %>% expect_equal(34) al[[7]] %>% expect_is("list") al[[7]][[1]] %>% expect_null() al[[7]][[2]] %>% expect_null() al[[7]][[3]] %>% expect_null() al %>% length() %>% expect_equal(7) al[[7]] %>% length() %>% expect_equal(3) expect_error(action_levels(warn_at = "20")) expect_error(action_levels(warn_at = 0)) expect_error(action_levels(warn_at = -1.5)) al <- action_levels( warn_at = 3, fns = list(warn = ~ my_great_function(vl = .vars_list)) ) al %>% expect_is("action_levels") al %>% names() %>% expect_equal( c( "warn_fraction", "warn_count", "stop_fraction", "stop_count", "notify_fraction", "notify_count", "fns") ) al[[7]] %>% names() %>% expect_equal("warn") al[[7]][[1]] %>% expect_is("formula") al[[7]][[1]] %>% as.character() %>% expect_equal(c("~", "my_great_function(vl = .vars_list)")) al$warn_fraction %>% expect_null() al$warn_count %>% expect_equal(3) al$stop_fraction %>% expect_null() al$stop_count %>% expect_null() al$notify_fraction %>% expect_null() al$notify_count %>% expect_null() al[[7]] %>% expect_is("list") al %>% length() %>% expect_equal(7) al[[7]] %>% length() %>% expect_equal(1) expect_error(action_levels(warn_at = 3, fns = list(warn = "text"))) expect_error( action_levels( warn_at = 3, fns = list( warn = ~ my_great_function(vl = .vars_list), ~ another_function() ) ) ) expect_error( action_levels( warn_at = 3, fns = list( warn = ~ my_great_function(vl = .vars_list), notable = ~ another_function() ) ) ) }) test_that("The appropriate actions occur when using `action_levels()`", { agent <- create_agent(tbl = small_table, label = "small_table_tests") %>% col_vals_gt( vars(d), 1000, actions = action_levels(warn_at = 3, fns = list(warn = ~"warning") ) ) %>% col_vals_in_set( vars(f), c("low", "high"), actions = action_levels(warn_at = 0.1, fns = list(warn = ~"warning") ) ) %>% interrogate() agent_report <- get_agent_report(agent, display_table = FALSE) agent_report$W %>% expect_equal(rep(TRUE, 2)) agent <- create_agent(tbl = small_table, label = "small_table_tests") %>% col_vals_gt( vars(d), 1000, actions = action_levels(notify_at = 3, fns = list(notify = ~"notify") ) ) %>% col_vals_in_set( vars(f), c("low", "high"), actions = action_levels(notify_at = 0.1, fns = list(notify = ~"notify") ) ) %>% interrogate() agent_report <- get_agent_report(agent, display_table = FALSE) agent_report$N %>% expect_equal(rep(TRUE, 2)) agent <- create_agent(tbl = small_table, label = "small_table_tests") %>% col_vals_gt( vars(d), 1000, actions = action_levels(stop_at = 3, fns = list(stop = ~"stop") ) ) %>% col_vals_in_set( vars(f), c("low", "high"), actions = action_levels(stop_at = 0.1, fns = list(stop = ~"stop") ) ) %>% interrogate() agent_report <- get_agent_report(agent, display_table = FALSE) agent_report$S %>% expect_equal(rep(TRUE, 2)) })
setSPEC.fn = function(SPEC.name) { source( system.file("SPEC", SPEC.name, package = "CGManalyzer") ) }
data(mtcars) head(mtcars) dim(mtcars) y.train <- mtcars[,11] x.train <- as.matrix(mtcars[,-11]) gbt_mod <- gbt.train(y.train, x.train, loss_function = "poisson", verbose=10) pred <- predict(gbt_mod, x.train) plot(pred, y.train)
ordGEE2 <- function(formula, id, data, corstr="exchangeable", maxit=50, tol=1e-3) { ID <- data[, as.character(id)] N <- length(ID) n <- length(unique(ID)) clsize.vec <- as.numeric(table(ID)) m <- clsize.vec[1] Resp <- as.factor(getResp(formula=formula, data=data)) Resp <- as.numeric(levels(Resp))[Resp] K <- length(unique(Resp))-1 Y.Mat <- matrix(0, nrow=N, ncol=K) for (k in 1:K) { Y.Mat[, k] <- Resp==k } Y <- as.vector(t(Y.Mat)) Z <- get_Z(Y, n=n, m=m, K=K) f <- kronecker(ID, rep(1,K)) DM <- getDM(formula=formula, data=data) DM <- cbind(matrix(rep(diag(K), sum(clsize.vec)),ncol=K, byrow=T), DM[kronecker(1:sum(clsize.vec),rep(1,K)),-1]) p_b <- ncol(DM) form.k <- paste("as.numeric(Resp>=K)", as.character(formula)[3], sep="~") init.glm <- glm(formula=eval(parse(text=form.k)), family=binomial,data=data) beta_est.init <- coefficients(init.glm) if(K>1){ for(k in (K-1):1){ form.k <- paste("as.numeric(Resp>=k)", as.character(formula)[3], sep="~") init.glm <- glm(formula=eval(parse(text=form.k)), family=binomial,data=data) beta_est.init <- c(coefficients(init.glm)[1], beta_est.init) } } j1.indx <- NULL k1.indx <- NULL j2.indx <- NULL k2.indx <- NULL for(j1 in 1:(m-1)) { for(j2 in (j1+1):m) { j1.indx <- c(j1.indx, rep(j1, K^2)) k1.indx <- c(k1.indx, kronecker(1:K, rep(1, K))) j2.indx <- c(j2.indx, rep(j2,K^2)) k2.indx <- c(k2.indx, kronecker(rep(1,K), 1:K)) } } indx.tab <- cbind(j1.indx, k1.indx, j2.indx, k2.indx) indx.tab.t <- t(indx.tab) if (corstr=="exchangeable") { alpha_est.init <- 0.5 p_a <- 1 assocDM <- matrix(rep(1, length(Z)), ncol=p_a) } else { if (corstr=="log-linear") { p_a <- K + K * (K - 1)/2 alpha_est.init <- c(log(3), rep(0, p_a-1)) assocDM_i <- cbind(rep(1, length(j1.indx)), (as.numeric(k1.indx==2) + as.numeric(k2.indx==2)), as.numeric((k1.indx==2)&(k2.indx==2))) assocDM <- matrix(rep(t(assocDM_i), n), ncol=p_a, byrow=T) } } p_t <- p_b + p_a theta_est.init <- c(beta_est.init, alpha_est.init) beta <- beta_est.init alpha <- alpha_est.init theta <- theta_est.init dif <- 1 differ <- c() iter <- 0 res <- list() res$beta <- numeric(p_b) res$alpha <- numeric(p_a) res$variance <- matrix(0, nrow=p_t, ncol=p_t) res$convergence <- FALSE res$iteration = 0 while(iter<maxit & dif >tol) { beta_est.o <- beta alpha_est.o <- alpha theta_est.o <- theta nrow_DM_i <- m*K nrow_assocDM_i <- K^2 * (m*(m-1))/2 U = rep(0, p_t) M = matrix(0, nrow=p_t, ncol=p_t) Sigma = matrix(0, nrow=p_t, ncol=p_t) for (i in 1:n) { U_i <- rep(0, p_t) M_i <- matrix(0, nrow=p_t, ncol=p_t) Sigma_i <- matrix(0, nrow=p_t, ncol=p_t) ordgee2_i <- .C("Cgetordgee2_i", as.double(DM[(i-1)*nrow_DM_i + 1:nrow_DM_i, ]), as.double(Y[(i-1)*nrow_DM_i + 1:nrow_DM_i]), as.double(assocDM[(i-1)*nrow_assocDM_i + 1:nrow_assocDM_i, ]), as.double(Z[(i-1)*nrow_assocDM_i + 1:nrow_assocDM_i]), as.integer(m), as.integer(K), as.integer(p_b), as.integer(p_a), beta = as.double(beta), alpha = as.double(alpha), U_i = as.double( U_i ), M_i = as.double(M_i), Sigma_i = as.double(Sigma_i) ) U <- U + ordgee2_i$U_i M <- M + matrix(ordgee2_i$M_i, nrow=p_t, byrow=FALSE) Sigma <- Sigma + matrix(ordgee2_i$Sigma_i, nrow=p_t, byrow=FALSE) } U_beta <- 1/n * U[1:p_b] U_alpha <- 1/n * U[(p_b+1):p_t] M1 <- 1/n * M[1:p_b, 1:p_b] M2 <- as.matrix( 1/n * M[(p_b+1):p_t, (p_b+1):p_t] ) if (any(is.na(M1)) | any(is.na(M2))) { return(res) } else { if ((abs(det(M1)) < 1e-15) | (abs(det(M2)) < 1e-15)) { return (res) } else { if (any(eigen(M1)$values<=1e-5) | any(eigen(M2)$values<=1e-5)) { inv.M1 <- solve(M1) inv.M2 <- solve(M2) } else { inv.M1 <- chol2inv(chol(M1)) inv.M2 <- chol2inv(chol(M2)) } } } beta <- beta_est.o + 0.8 * inv.M1%*%U_beta alpha <- alpha_est.o + 0.8 * inv.M2%*%U_alpha theta <- c(beta, alpha) dif <- max(abs(theta/theta_est.o-1)) differ <- c(differ, dif) iter <- iter + 1 } beta_nam <- c(unlist(lapply("Y>=", 1:K, FUN=paste, sep="")), dimnames(DM)[[2]][-(1:K)]) alpha_nam <- NULL if (corstr=="exchangeable") { alpha_nam <- "Delta" } else { if (corstr=="log-linear") { alpha_nam <- c("Delta", "Delta_2", "Delta_22") } } Gamma <- 1/n * M Sigma <- 1/n * Sigma res$beta <- as.vector(beta) res$alpha <- as.vector(alpha) if (abs(det(Gamma)) < 1e-15) { res$variance <- ginv(Gamma) %*% Sigma %*% t(ginv(Gamma))/n } else { inv.Gamma <- matrix(0, nrow=p_t, ncol=p_t) inv.Gamma[1:p_b, 1:p_b] <- inv.M1 inv.Gamma[(p_b+1):p_t, (p_b+1):p_t] <- inv.M2 inv.Gamma[(p_b+1):p_t, 1:p_b] <- -( inv.M2%*% Gamma[(p_b+1):p_t, 1:p_b]%*%inv.M1 ) res$variance <- inv.Gamma%*% Sigma %*% t(inv.Gamma)/n } res$convergence <- (iter<maxit & dif < tol) res$iteration = iter res$differ <- differ names(res$beta) <- beta_nam names(res$alpha) <- alpha_nam dimnames(res$variance) <- list(c(beta_nam, alpha_nam), c(beta_nam, alpha_nam)) res$call <- match.call() class(res) <- "mgee2" return(res) }
test_that( "test are_disjoint_sets with disjoint sets returns true", { x <- 1:5 y <- 6:10 expect_true(are_disjoint_sets(x, y)) } ) test_that( "test are_disjoint_sets with intersecting sets returns false", { x <- 1:5 expect_false(actual <- are_disjoint_sets(x, 4:8)) expect_match( cause(actual), noquote("x and 4:8 have common elements: 4, 5") ) } ) test_that( "test are_intersecting_sets with intersecting sets returns true", { x <- 1:5 y <- 5:9 expect_true(are_intersecting_sets(x, y)) } ) test_that( "test are_intersecting_sets with disjoint sets returns false", { x <- 1:5 expect_false(actual <- are_intersecting_sets(x, 6:10)) expect_match( cause(actual), noquote("x and 6:10 have no common elements") ) } ) test_that( "test are_set_equal with equal sets returns true", { x <- 1:5 y <- c(1, 3, 5, 4, 2) expect_true(are_set_equal(x, y)) } ) test_that( "test are_set_equal with different size sets returns false", { x <- 1:5 y <- c(1:4, 4) expect_false(actual <- are_set_equal(x, y)) expect_match( cause(actual), "1:5 and c\\(1, 2, 3, 4\\) have different numbers of elements \\(5 versus 4\\)" ) } ) test_that( "test are_set_equal with unequal sets returns false", { x <- 1:5 y <- c(99, 3, 5, 4, 2) expect_false(actual <- are_set_equal(x, y)) expect_match( cause(actual), noquote("The element .+1.+ in 1:5 is not in c\\(99, 3, 5, 4, 2\\)") ) } ) test_that( "test is_subset with equal sets returns true", { x <- 1:5 expect_true(is_subset(x, x)) } ) test_that( "test is_subset with equal sets and strictly = TRUE returns false", { x <- 1:5 expect_false(is_subset(x, x, strictly = TRUE)) } ) test_that( "test is_subset with a subset returns true", { x <- 1:5 y <- 6:1 expect_true(is_subset(x, y)) } ) test_that( "test is_subset with a non-subset returns false", { x <- 1:5 y <- 4:1 expect_false(actual <- is_subset(x, y)) expect_match( cause(actual), noquote("The element .+5.+ in x is not in y") ) } ) test_that( "test is_superset with equal sets returns true", { x <- 1:5 expect_true(is_superset(x, x)) } ) test_that( "test is_superset with equal sets and strictly = TRUE returns false", { x <- 1:5 expect_false(is_superset(x, x, strictly = TRUE)) } ) test_that( "test is_superset with a superset returns true", { x <- 1:6 y <- 5:1 expect_true(is_superset(x, y)) } ) test_that( "test is_superset with a non-superset returns false", { x <- 1:4 y <- 5:1 expect_false(actual <- is_superset(x, y)) expect_match( cause(actual), "The element .+5.+ in y is not in x" ) } )
find.limits <- function(map, mar.min = 2, ...) { if(!is.list(map)) stop("argument map must be a list() of matrix polygons!") n <- length(map) myrange <- function(x, c.select = 1L, ...) { return(na.omit(x[, c.select], ...)) } xlim <- range(unlist(lapply(map, myrange, c.select = 1L, ...))) ylim <- range(unlist(lapply(map, myrange, c.select = 2L, ...))) mar <- NULL asp <- attr(map, "asp") if(is.null(asp)) asp <- (diff(ylim) / diff(xlim)) / cos((mean(ylim) * pi) / 180) if(!is.null(height2width <- attr(map, "height2width"))) { height2width <- height2width * 0.8 if(!is.null(mar.min)) { if(height2width > 1) { side <- 17.5 * (1 - 1/height2width) + mar.min / height2width mar <- c(mar.min, side, mar.min, side) } else { top <- 17.5 * (1 - height2width) + mar.min * height2width mar <- c(top, mar.min, top, mar.min) } } } return(list(ylim = ylim, xlim = xlim, mar = mar, asp = asp)) }
noz = function(x) { if (!is.list(x)) { stop("x should be a list with location ids for the regions in the clusters") } remain_idx = seq_along(x) i = 1 u = 1 while (i < length(x)) { no_inter = sapply(remain_idx, function(j) !any(duplicated(unlist(x[c(i, j)])))) remain_idx = remain_idx[no_inter] if (length(remain_idx) > 0) { i = min(remain_idx) u = c(u, i) } else { i = length(x) + 1 } } return(u) }
get_oc_3arm <- function(shape, m0, mA, hr2, hr3, frac, ta, tf, c1, c, diff, n, nsim, seed = 2483) { kappa=shape m2=mA/hr2 m3=mA/hr3 lambda0=log(2)/m0^kappa rho0=lambda0^(1/kappa) scale0=1/rho0 H0=function(shape, scale, t){(t/scale)^shape} lambda1=log(2)/mA^kappa rho1=lambda1^(1/kappa) lambda2=log(2)/m2^kappa rho2=lambda2^(1/kappa) lambda3=log(2)/m3^kappa rho3=lambda3^(1/kappa) scale1=1/rho1 scale2=1/rho2 scale3=1/rho3 scale=c(scale1, scale2, scale3) s=0 set.seed(seed) n1=ceiling(n*frac) n2=ceiling(n*(1-frac)) tau=ta+tf outcome2<-No.success<-n.Subj<-matrix(999, ncol=3, nrow=nsim) for (i in 1:nsim) { for (a in 1:3){ w=rweibull(n, shape, scale[a]) u=runif(n, 0, ta) x=pmax(0, pmin(w,tau-u)) delta = as.numeric(w<tau-u) O1=sum(delta[1:n1]) M1=H0(shape,scale0,x[1:n1]) E1=sum(M1) Z1=(E1-O1)/sqrt(E1) O=sum(delta) M=H0(shape,scale0,x) E=sum(M) Z=(E-O)/sqrt(E) outcome1<-ifelse(Z1>c1, Z, NA) No.success[i,a]<-Z outcome2[i,a]<-ifelse(outcome1>c, 1, 0) n.Subj[i,a] <- ifelse(Z1>c1, n, n1) } } Outcome<-apply(outcome2, 1, sum, na.rm=T) Outcome[is.na(Outcome)]<-0 Prob.neg <-length(Outcome[Outcome==0])/nsim Prob.pos <-length(Outcome[Outcome==3])/nsim Prob.neg2pos1 <-length(Outcome[Outcome==1])/nsim Prob.neg1pos2 <-length(Outcome[Outcome==2])/nsim Prob.ArmA<-sum(outcome2[,1], na.rm=TRUE)/nsim Prob.ArmB<-sum(outcome2[,2], na.rm=TRUE)/nsim Prob.ArmC<-sum(outcome2[,3], na.rm=TRUE)/nsim mean.Subj<-apply(n.Subj,2,mean, na.rm=T) Prob.select.ArmA <- sum(outcome2[,1][(outcome2[, 2] == 0 & outcome2[, 3] == 0) | (outcome2[, 2] == 0 & is.na(outcome2[, 3])) | (is.na(outcome2[, 2]) & outcome2[, 3] == 0) | (is.na(outcome2[, 2]) & is.na(outcome2[, 3]))]/nsim ) Prob.select.ArmB <- sum(outcome2[,2][(outcome2[, 1] == 0 & outcome2[, 3] == 0) | (outcome2[, 1] == 0 & is.na(outcome2[, 3])) | (is.na(outcome2[, 1]) & outcome2[, 3] == 0) | (is.na(outcome2[, 1]) & is.na(outcome2[, 3]))]/nsim ) Prob.select.ArmC <- sum(outcome2[,3][(outcome2[, 1] == 0 & outcome2[, 2] == 0) | (outcome2[, 1] == 0 & is.na(outcome2[, 2])) | (is.na(outcome2[, 1]) & outcome2[, 2] == 0) | (is.na(outcome2[, 1]) & is.na(outcome2[, 2]))]/nsim ) Prob.NoArm<-Prob.neg No.success.BothArms.select<-No.success[Outcome==2 | Outcome ==3,] SSD.SelectArm<-function(x, diff, MOD=FALSE) { NoArm<-ArmA<-ArmB<-ArmC<-NA ArmA<-ifelse(x[1]-x[2] > diff & x[1]-x[3] > diff,1,0) ArmB<-ifelse(x[2]-x[1] > diff & x[2]-x[3] > diff,1,0) ArmC<-ifelse(x[3]-x[1] > diff & x[3]-x[2] > diff,1,0) if(abs(x[3]-x[1]) <= diff | abs(x[2]-x[1]) <= diff | abs(x[2]-x[3]) <= diff) { NoArm <- 1 } return(list(ArmA, ArmB, ArmC, NoArm)) } if( length(No.success[Outcome==2|Outcome==3,]) > 1 ) { SSD.SelectArm.2ndSeg<-matrix(unlist( apply(No.success[Outcome==2|Outcome==3,],1,SSD.SelectArm, diff) ),ncol=4,byrow=T)} else {SSD.SelectArm.2ndSeg <- matrix(NA,ncol=4) } ProbArmA.2ndSeg<-sum(SSD.SelectArm.2ndSeg[,1],na.rm=TRUE)/nsim ProbArmB.2ndSeg<-sum(SSD.SelectArm.2ndSeg[,2],na.rm=TRUE)/nsim ProbArmC.2ndSeg<-sum(SSD.SelectArm.2ndSeg[,3],na.rm=TRUE)/nsim ProbNoArm.2ndSeg<-sum(SSD.SelectArm.2ndSeg[,4],na.rm=TRUE)/nsim Overall.ArmA<-Prob.select.ArmA + ProbArmA.2ndSeg Overall.ArmB<-Prob.select.ArmB + ProbArmB.2ndSeg Overall.ArmC<-Prob.select.ArmC + ProbArmC.2ndSeg Overall.NoArm<-Prob.NoArm + ProbNoArm.2ndSeg soln<-data.frame("n"=n, "SSD Arm A"=Overall.ArmA, "SSD Arm B"= Overall.ArmB, "SSD Arm C"= Overall.ArmC, "SSD No Arm"=Overall.NoArm, "diff"=diff,"Mean N Arm A"=mean.Subj[1],"Mean N Arm B"=mean.Subj[2], "Mean N Arm C"=mean.Subj[3]) return(soln) }
context("Test fnb.detect_distribution") test_that("Check distribution detection function", { x <- matrix(c(2, 3, 2, 1, 2, 5, 3, 4, 2, 4, 0, 1, 1, 1, 0, 3, 4, 4, 3, 5), nrow = 5, ncol = 4 ) x <- cbind(x, rnorm(5)) col_names <- c("wo", "mo", "bo", "so", "ma") colnames(x) <- col_names real_distribution <- list( bernoulli = c("bo"), multinomial = c("wo", "mo", "so"), gaussian = c("ma") ) expect_equal(real_distribution, fnb.detect_distribution(x)) x <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2) colnames(x) <- c("wo", "mo") distribution <- fnb.detect_distribution(x) real_distribution <- list( multinomial = c("wo", "mo") ) expect_equal(real_distribution, distribution) })
find_airport <- function(x){ filter(airportCode, grepl(x, origin) | grepl (x, city)) } findAirport <- function(...){ warning(paste("findAirport is deprecated, use find_airport(), instead.")) do.call(find_airport, list(...)) } globalVariables(c("airportCode", "origin", "city"))
comp.simu.test <- function(object, m = 10000, type = "smallprop", level = 0.05, adjust = TRUE, ncores = NULL, iseed = NULL, pkg = "ICSOutlier", qtype = 7, ...) { if (class(object) != "ics2") stop("'object' must be of class ics2") S1 <- get(object@S1name) S2 <- get(object@S2name) if (!is.function(S1)) stop(paste("S1 in '", S1, ", must be a specified as a function")) if (!is.function(S2)) stop(paste("S2 in '", S2, ", must be a specified as a function")) type <- match.arg(type, c("smallprop")) n <- nrow(object@Scores) p <- ncol(object@Scores) MEAN <- rep(0, p) if(!is.null(ncores) && ncores > 1){ if(is.null(iseed)){ if (exists(".Random.seed", envir=globalenv())){ oldseed <- get(".Random.seed", envir=globalenv()) rm(.Random.seed, envir=globalenv()) on.exit(assign(".Random.seed", oldseed, envir=globalenv())) } } ctype <- "PSOCK" cl <- makeCluster(ncores, type=ctype) clusterExport(cl, c("n","m","MEAN","S1","S2","object", "pkg", "iseed"), envir = environment()) clusterEvalQ(cl, lapply(pkg, require,character.only = TRUE)) clusterSetRNGStream(cl = cl, iseed = iseed) EV <- parSapply(cl, 1:m, function(i,...) { ics2(rmvnorm(n, MEAN), S1 = S1, S2 = S2, S1args = object@S1args, S2args = object@S2args)@gKurt } ) stopCluster(cl) } else { EV <- replicate(m, ics2(rmvnorm(n, MEAN), S1 = S1, S2 = S2, S1args = object@S1args, S2args = object@S2args)@gKurt) } if (adjust == TRUE) { levels <- level/1:p } else { levels <- rep(level, p) } EV.quantile <- numeric(p) for (i in 1:p) { EV.quantile[i] <- quantile(EV[i, ], probs = 1 - levels[i], type = qtype, ...) } decisions <- (object@gKurt > EV.quantile) k <- match(FALSE, decisions) - 1 if (is.na(k)) { index <- 1:p } else { if (k == 0) index <- 0 else index <- 1:k } RES <- list(index = index, test = "simulation", criterion = EV.quantile, levels = levels, adjust = adjust, type = type, m = m) RES }
"print.ahazpen" <- function(x, digits = max(3, getOption("digits") - 3), ...) { cat("\nCall:\n", deparse(x$call), "\n\n", sep = "") cat("* No. predictors: ", format(x$nvars, width = 7,digits = digits), "\n") cat("* No. observations: ", format(x$nobs, width = 7,digits = digits), "\n") cat("* Max no. predictors in path:", format(max(x$df), width = 7,digits = digits),"\n") cat("* Penalty parameter lambda:\n") cat(" -No. grid points:", format(length(x$lambda), width = 7,digits = digits), "\n") cat(" -Min value: ", format(min(x$lambda), width = 7,digits = digits), "\n") cat(" -Max value: ", format(max(x$lambda), width = 7,digits = digits)) cat("\n\n") invisible(x) }
knitr::opts_chunk$set(echo = TRUE) library(PKNCA)
library("testthat") library("gratia") library("mgcv") `expect_doppelganger` <- function(title, fig, ...) { testthat::skip_if_not_installed("vdiffr") vdiffr::expect_doppelganger(title, fig, ...) } set.seed(0) n.samp <- 200 dat <- data_sim("eg1", n = n.samp, dist = "binary", scale = .33, seed = 0) p <- binomial()$linkinv(dat$f) n <- sample(c(1, 3), n.samp, replace = TRUE) dat <- transform(dat, y = rbinom(n, n, p), n = n) m <- gam(y / n ~ s(x0) + s(x1) + s(x2) + s(x3), family = binomial, data = dat, weights = n, method = "REML") types <- c("deviance", "response", "pearson") methods <- c("uniform", "simulate", "normal") test_that("qq_plot() uniform method works", { skip_if(packageVersion("mgcv") < "1.8.36") set.seed(42) plt <- qq_plot(m) expect_doppelganger("qq_plot uniform randomisation", plt) }) test_that("qq_plot() uniform method works with response residuals", { skip_if(packageVersion("mgcv") < "1.8.36") set.seed(42) plt <- qq_plot(m, type = "response") expect_doppelganger("qq_plot uniform randomisation response residuals", plt) }) test_that("qq_plot() uniform method works with pearson residuals", { skip_if(packageVersion("mgcv") < "1.8.36") set.seed(42) plt <- qq_plot(m, type = "pearson") expect_doppelganger("qq_plot uniform randomisation pearson residuals", plt) }) test_that("qq_plot() normal method works", { plt <- qq_plot(m, method = "normal") expect_doppelganger("qq_plot normality assumption", plt) }) test_that("qq_plot() normal method works", { plt <- qq_plot(m, method = "normal", type = "response") expect_doppelganger("qq_plot normality assumption response residuals", plt) }) test_that("qq_plot() normal method works", { plt <- qq_plot(m, method = "normal", type = "pearson") expect_doppelganger("qq_plot normality assumption pearson residuals", plt) }) test_that("qq_plot() simulate method works", { set.seed(42) plt <- qq_plot(m, method = "simulate") expect_doppelganger("qq_plot data simulation", plt) }) test_that("qq_plot() simulate method works", { set.seed(42) plt <- qq_plot(m, method = "simulate", type = "response") expect_doppelganger("qq_plot data simulation response residuals", plt) }) test_that("qq_plot() simulate method works", { set.seed(42) plt <- qq_plot(m, method = "simulate", type = "pearson") expect_doppelganger("qq_plot data simulation pearson residuals", plt) }) test_that("qq_plot() fails if unsupported residuals requested", { expect_error(qq_plot(m, type = "scaled.pearson"), paste("'arg' should be one of", paste(dQuote(types), collapse = ', ')), fixed = TRUE) }) test_that("qq_plot() fails if unsupported method requested", { expect_error(qq_plot(m, method = "foo"), paste("'arg' should be one of", paste(dQuote(methods), collapse = ', ')), fixed = TRUE) }) test_that("qq_plot() prints message if direct method requested", { expect_message(qq_plot(m, method = "direct"), "`method = \"direct\"` is deprecated, use `\"uniform\"`", fixed = TRUE) }) test_that("qq_plot.default fails with error", { expect_error(qq_plot(dat), "Unable to produce a Q-Q plot for <data.frame>") }) test_that("pearson_residuals fails if no var_fun available", { expect_error(pearson_residuals(var_fun = NULL), "Pearson residuals are not available for this family.", fixed = TRUE) })
build.q.set <- function(q.concourse, q.sample, q.distribution) { q.sample <- as.character(q.sample) if (!is.matrix(q.concourse)) { stop("The input specified for q.concourse is not a matrix.") } if (!is.vector(q.distribution)) { stop("The input specified for q.distribution is not a matrix.") } if (!is.vector(q.sample)) { stop("The input specified for q.sample is not a vector.") } if (length(q.sample) != sum(q.distribution)) { stop( paste( "There are", length(q.sample), "items in your q-sample, but", sum(q.distribution), "entries expected in the q-distribution", sep=" " ) ) } missing.in.concourse <- !q.sample %in% rownames(q.concourse) if (any(missing.in.concourse)) { stop( paste( "There are item handles in your sample not defined in the concourse:", q.sample[missing.in.concourse], sep=" " ) ) } q.set <- q.concourse[q.sample,] q.set <- as.matrix(q.set) message(paste("Build a q.set of", nrow(q.set), "items.")) return(q.set) }
pphat <- function(q, n, mu=0, sigma=1, type="known", LSL=-3, USL=3, nodes=30) { if ( n < 1 ) stop("n must be >= 1") if ( sigma<1e-10 ) stop("sigma much too small") ctyp <- -1 + pmatch(type, c("known", "estimated")) if ( is.na(ctyp) ) stop("invalid sigma mode") if ( LSL >= USL ) stop("wrong relationship between lower and upper specification limits (LSL must be smaller than USL)") if ( nodes<2 ) stop("far too less nodes") p.star <- pnorm( LSL/sigma ) + pnorm( -USL/sigma ) if ( type == "estimated" ) p.star <- 0 cdf <- rep(NA, length(q)) for ( i in 1:length(q) ) { cdf[i] <- 0 if ( q[i] >= 1 ) cdf[i] <- 1 if ( p.star<q[i] && q[i]<1 ) cdf[i] <- .C("phat_cdf", as.double(q[i]), as.integer(n), as.double(mu), as.double(sigma), as.integer(ctyp), as.double(LSL), as.double(USL), as.integer(nodes), ans=double(length=1), PACKAGE="spc")$ans } names(cdf) <- NULL cdf }
calculate_n05_using_bisection_from_the_summed_fields <- function (fsum1or, fsum2or, d) { dimx = ncol(fsum1or) dimy = nrow(fsum1or) rows = nrow(fsum1or) - 2 * d cols = ncol(fsum1or) - 2 * d x1 = 1 x2 = 2 * max(rows, cols) - 1 if (x2 < 5) { stop("Domain size needs to be at least 2 grid points") } FSS1 = calculate_FSS_from_enlarged_summed_fields(fsum1or, fsum2or, x1, d) FSS2 = calculate_FSS_from_enlarged_summed_fields(fsum1or, fsum2or, x2, d) if (FSS1 > 0.5) return(1) if (FSS2 <= 0.5) { stop("FSS does never reach value 0.5. There is something wrong.") } repeat { xnew = (x1 + x2)/2 if (xnew%%2 == 0) { xnew = xnew + 1 } FSSnew = calculate_FSS_from_enlarged_summed_fields(fsum1or, fsum2or, xnew, d) if (FSSnew > 0.5) { x2 = xnew FSS2 = FSSnew } else { x1 = xnew FSS1 = FSSnew } if (x2 - x1 <= 2) { break } } return(x2) }
if (.Platform$OS.type != "windows" && require(betareg)) { library(rstanarm) SEED <- 12345 set.seed(SEED) ITER <- 10 CHAINS <- 2 REFRESH <- 0 context("stan_betareg") source(test_path("helpers", "expect_stanreg.R")) source(test_path("helpers", "SW.R")) simple_betareg_data <- function(N, draw_z = FALSE) { x <- rnorm(N, 2, 1) z <- if (draw_z) rnorm(N, 0, 1) else rep(0, N) mu <- binomial(link="logit")$linkinv(1 + 0.2 * x) phi <- 20 y <- rbeta(N, mu * phi, (1 - mu) * phi) data.frame(y,x,z) } dat <- simple_betareg_data(200, draw_z = TRUE) link1 <- c("logit", "probit", "cloglog", "cauchit", "log", "loglog") link2 <- c("log", "identity", "sqrt") test_that("sparse = TRUE errors", { expect_error( stan_betareg(y ~ x, link = "logit", seed = SEED, sparse = TRUE, data = dat), "unknown arguments: sparse" ) }) test_that("QR errors when number of x and/or z predictors is <= 1", { expect_error( stan_betareg(y ~ x, link = "logit", seed = SEED, QR = TRUE, data = dat), "'QR' can only be specified when there are multiple predictors" ) expect_error( stan_betareg(y ~ x | z, link = "logit", seed = SEED, QR = TRUE, data = dat), "'QR' can only be specified when there are multiple predictors" ) }) test_that("QR works when number of x and/or z predictors is >= 1", { SW(fit1 <- stan_betareg(y ~ x + z, link = "logit", seed = SEED, QR = TRUE, prior = NULL, prior_intercept = NULL, refresh = 0, data = dat, algorithm = "optimizing")) expect_stanreg(fit1) expect_output(print(prior_summary(fit1)), "Q-space") SW(fit2 <- stan_betareg(y ~ x + z | z, link = "logit", seed = SEED, QR = TRUE, prior = NULL, prior_intercept = NULL, refresh = 0, data = dat, algorithm = "optimizing")) expect_stanreg(fit2) }) test_that("stan_betareg returns expected result when modeling x and dispersion", { for (i in 1:length(link1)) { SW(fit <- stan_betareg(y ~ x, link = link1[i], seed = SEED, prior = NULL, prior_intercept = NULL, prior_phi = NULL, refresh = 0, data = dat, algorithm = "optimizing")) expect_stanreg(fit) val <- coef(fit) ans <- coef(betareg(y ~ x, link = link1[i], data = dat)) expect_equal(val, ans, tol = 0.1, info = link1[i]) } }) test_that("stan_betareg works with QR = TRUE and algorithm = 'optimizing'", { SW(fit <- stan_betareg(y ~ x + z, link = "logit", seed = SEED, QR = TRUE, prior = NULL, prior_intercept = NULL, prior_phi = NULL, refresh = 0, data = dat, algorithm = "optimizing")) expect_stanreg(fit) val <- coef(fit) ans <- coef(betareg(y ~ x + z, link = "logit", data = dat)) expect_equal(val, ans, tol = 0.1, info = "logit") }) test_that("stan_betareg works with QR = TRUE and algorithm = 'sampling'", { SW(fit <- stan_betareg(y ~ x + z, link = "logit", QR = TRUE, prior = NULL, prior_intercept = NULL, prior_phi = NULL, refresh = 0, iter = 100, chains = 2, data = dat)) expect_stanreg(fit) val <- coef(fit) ans <- coef(betareg(y ~ x + z, link = "logit", data = dat)) expect_equal(val, ans, tol = 0.1) }) test_that("stan_betareg ok when modeling x and z (link.phi = 'log')", { N <- 200 dat <- data.frame(x = rnorm(N, 2, 1), z = rnorm(N, 2, 1)) mu <- binomial(link="logit")$linkinv(1 + 0.2 * dat$x) phi <- poisson(link = link2[1])$linkinv(1.5 + 0.4*dat$z) dat$y <- rbeta(N, mu * phi, (1 - mu) * phi) for (i in 1:length(link1)) { SW(fit <- stan_betareg(y ~ x | z, link = link1[i], link.phi = link2[1], seed = SEED, refresh = 0, prior = NULL, prior_intercept = NULL, prior_z = NULL, prior_intercept_z = NULL, data = dat, algorithm = "optimizing")) expect_stanreg(fit) val <- coef(fit) ans <- coef(betareg(y ~ x | z, link = link1[i], link.phi = link2[1], data = dat)) expect_equal(val, ans, tol = 0.1, info = c(link1[i], link2[1])) } }) test_that("stan_betareg ok when modeling x and z (link.phi = 'identity')", { N <- 200 dat <- data.frame(x = rnorm(N, 2, 1), z = rnorm(N, 2, 1)) mu <- binomial(link = "logit")$linkinv(1 + 0.2*dat$x) phi <- dat$z - min(dat$z) + 5.5 dat$y <- rbeta(N, mu * phi, (1 - mu) * phi) for (i in 1:length(link1)) { SW(fit <- stan_betareg(y ~ x | z, link = link1[i], link.phi = link2[2], prior = NULL, prior_intercept = NULL, prior_z = NULL, prior_intercept_z = NULL, data = dat, algorithm = "optimizing", seed = SEED, refresh = 0)) expect_stanreg(fit) val <- coef(fit) ans <- coef(betareg(y ~ x | z, link = link1[i], link.phi = link2[2], data = dat)) expect_equal(val, ans, tol = 0.15, info = c(link1[i], link2[2])) } }) test_that("stan_betareg ok when modeling x and z (link.phi = 'sqrt')", { for (i in 1:length(link1)) { N <- 1000 dat <- data.frame(x = rnorm(N, 2, 1), z = rep(1, N)) mu <- binomial(link = "logit")$linkinv(-0.8 + 0.5*dat$x) phi <- poisson(link = "sqrt")$linkinv(8 + 2*dat$z) dat$y <- rbeta(N, mu * phi, (1 - mu) * phi) SW(fit <- stan_betareg(y ~ x | 1, link = link1[i], link.phi = link2[3], data = dat, algorithm = "sampling", chains = 1, iter = 1, refresh = 0)) expect_stanreg(fit) } }) test_that("stan_betareg ok when modeling x and dispersion with offset and weights", { N <- 200 weights <- rbeta(N, 2, 2) offset <- rep(0.3, N) dat <- data.frame(x = rnorm(N, 2, 1)) mu <- binomial(link="logit")$linkinv(1+0.2*dat$x) phi <- 20 dat$y <- rbeta(N, mu * phi, (1 - mu) * phi) SW(fit <- stan_betareg(y ~ x, link = "logit", seed = SEED, prior = NULL, prior_intercept = NULL, prior_phi = NULL, data = dat, weights = weights, offset = offset, algorithm = "optimizing", iter = 2000, refresh = 0)) expect_stanreg(fit) val <- coef(fit) ans <- coef(betareg(y ~ x, link = "logit", weights = weights, offset = offset, data = dat)) expect_equal(val, ans, tol = 0.3, info = "logit") }) test_that("heavy tailed priors work with stan_betareg", { expect_stanreg(stan_betareg(y ~ x | z, data = dat, prior = product_normal(), prior_z = product_normal(), chains = 1, iter = 1, refresh = 0)) expect_stanreg(stan_betareg(y ~ x | z, data = dat, prior = laplace(), prior_z = laplace(), chains = 1, iter = 1, refresh = 0)) expect_stanreg(stan_betareg(y ~ x | z, data = dat, prior = lasso(), prior_z = lasso(), chains = 1, iter = 1, refresh = 0)) }) test_that("loo/waic for stan_betareg works", { source(test_path("helpers", "expect_equivalent_loo.R")) ll_fun <- rstanarm:::ll_fun data("GasolineYield", package = "betareg") SW(fit_logit <- stan_betareg(yield ~ batch + temp | temp, data = GasolineYield, link = "logit", chains = CHAINS, iter = ITER, seed = SEED, refresh = 0)) expect_equivalent_loo(fit_logit) expect_identical(ll_fun(fit_logit), rstanarm:::.ll_beta_i) }) source(test_path("helpers", "check_for_error.R")) source(test_path("helpers", "expect_linpred_equal.R")) SW <- suppressWarnings context("posterior_predict (stan_betareg)") test_that("compatible with stan_betareg with z", { data("GasolineYield", package = "betareg") fit <- SW(stan_betareg(yield ~ pressure + temp | temp, data = GasolineYield, iter = ITER*5, chains = 2*CHAINS, seed = SEED, refresh = 0)) check_for_error(fit) }) test_that("compatible with stan_betareg without z", { data("GasolineYield", package = "betareg") fit <- SW(stan_betareg(yield ~ temp, data = GasolineYield, iter = ITER, chains = CHAINS, seed = SEED, refresh = 0)) check_for_error(fit) }) test_that("compatible with betareg with offset", { GasolineYield2 <- GasolineYield GasolineYield2$offs <- runif(nrow(GasolineYield2)) fit <- SW(stan_betareg(yield ~ temp, data = GasolineYield2, offset = offs, iter = ITER*5, chains = CHAINS, seed = SEED, refresh = 0)) fit2 <- SW(stan_betareg(yield ~ temp + offset(offs), data = GasolineYield2, iter = ITER*5, chains = CHAINS, seed = SEED, refresh = 0)) expect_warning(posterior_predict(fit, newdata = GasolineYield), "offset") check_for_error(fit, data = GasolineYield2, offset = GasolineYield2$offs) check_for_error(fit2, data = GasolineYield2, offset = GasolineYield2$offs) expect_linpred_equal(fit) expect_linpred_equal(fit2) }) test_that("predict ok for stan_betareg", { dat <- list() dat$N <- 200 dat$x <- rnorm(dat$N, 2, 1) dat$z <- rnorm(dat$N, 2, 1) dat$mu <- binomial(link = "logit")$linkinv(0.5 + 0.2*dat$x) dat$phi <- exp(1.5 + 0.4*dat$z) dat$y <- rbeta(dat$N, dat$mu * dat$phi, (1 - dat$mu) * dat$phi) dat <- data.frame(dat$y, dat$x, dat$z) colnames(dat) <- c("y", "x", "z") betaregfit <- betareg(y ~ x | z, data = dat) SW(capture.output( stanfit <- stan_betareg(y ~ x | z, data = dat, chains = CHAINS, iter = ITER, seed = SEED, refresh = 0) )) pb <- predict(betaregfit, type = "response") ps <- predict(stanfit, type = "response") expect_error(presp(stanfit)) newd <- data.frame(x = c(300,305)) pb <- predict(betaregfit, newdata = newd, type = "link") ps <- predict(stanfit, newdata = newd, type = "link") }) }
"read.pdb2" <- function (file, maxlines=-1, multi=FALSE, rm.insert=FALSE, rm.alt=TRUE, ATOM.only = FALSE, verbose=TRUE) { if(missing(file)) { stop("read.pdb: please specify a PDB 'file' for reading") } if(!is.numeric(maxlines)) { stop("read.pdb: 'maxlines' must be numeric") } if(!is.logical(multi)) { stop("read.pdb: 'multi' must be logical TRUE/FALSE") } toread <- file.exists(file) if(substr(file,1,4)=="http") { toread <- TRUE } if(!toread) { if(nchar(file)==4) { file <- get.pdb(file, URLonly=TRUE) cat(" Note: Accessing on-line PDB file\n") } else { stop("No input PDB file found: check filename") } } cl <- match.call() atom.format <- matrix(c(6, 'character', "type", 5, 'numeric', "eleno", -1, NA, NA, 4, 'character', "elety", 1, 'character', "alt", 4, 'character', "resid", 1, 'character', "chain", 4, 'numeric', "resno", 1, 'character', "insert", -3, NA, NA, 8, 'numeric', "x", 8, 'numeric', "y", 8, 'numeric', "z", 6, 'numeric', "o", 6, 'numeric', "b", -6, NA, NA, 4, 'character', "segid", 2, 'character', "elesy", 2, 'character', "charge" ), ncol=3, byrow=TRUE, dimnames = list(c(1:19), c("widths","what","name")) ) trim <- function(s) { s <- sub("^ +", "", s) s <- sub(" +$", "", s) s[(s=="")]<-"" s } split.fields <- function(x) { x <- trim( substring(x, first, last) ) paste(x,collapse=";") } is.character0 <- function(x){length(x)==0 & is.character(x)} widths <- as.numeric(atom.format[,"widths"]) drop.ind <- (widths < 0) widths <- abs(widths) st <- c(1, 1 + cumsum( widths )) first <- st[-length(st)][!drop.ind] last <- cumsum( widths )[!drop.ind] names(first) = na.omit(atom.format[,"name"]) names(last) = names(first) raw.lines <- readLines(file, n = maxlines) type <- substring(raw.lines, first["type"], last["type"]) raw.end <- sort(c(which(type == "END"), which(type == "ENDMDL"))) if (length(raw.end) > 1) { cat(" PDB has multiple END/ENDMDL records \n") if (!multi) { cat(" multi=FALSE: taking first record only \n") } else { cat(" multi=TRUE: 'read.dcd/read.ncdf' will be quicker! \n") raw.lines.multi <- raw.lines type.multi <- type } raw.lines <- raw.lines[ (1:raw.end[1]) ] type <- type[ (1:raw.end[1]) ] } if ( length(raw.end) !=1 ) { if (length(raw.lines) == maxlines) { cat(" You may need to increase 'maxlines' \n") cat(" check you have all data in $atom \n") } } if(ATOM.only) { raw.lines <- raw.lines[type %in% c("HEADER", "ATOM ", "HETATM")] type <- substring(raw.lines, first["type"], last["type"]) } remark <- .parse.pdb.remark350(raw.lines) raw.header <- raw.lines[type == "HEADER"] raw.seqres <- raw.lines[type == "SEQRES"] raw.helix <- raw.lines[type == "HELIX "] raw.sheet <- raw.lines[type == "SHEET "] raw.atom <- raw.lines[type %in% c("ATOM ","HETATM")] if (verbose) { if (!is.character0(raw.header)) { cat(" ", raw.header, "\n") } } seqres <- unlist(strsplit( trim(substring(raw.seqres,19,80))," +")) if(!is.null(seqres)) { seqres.ch <- substring(raw.seqres, 12, 12) seqres.ln <- substring(raw.seqres, 13, 17) seqres.in <- ( !duplicated(seqres.ch) ) names(seqres) <- rep(seqres.ch[seqres.in], times=seqres.ln[seqres.in]) } if(length(raw.helix) > 0) { helix <- list(start = as.numeric(substring(raw.helix,22,25)), end = as.numeric(substring(raw.helix,34,37)), chain = trim(substring(raw.helix,20,20)), type = trim(substring(raw.helix,39,40))) insert.i <- trim(substring(raw.helix,26,26)) insert.e <- trim(substring(raw.helix,38,38)) names(helix$start) <- insert.i names(helix$end) <- insert.e } else { helix <- NULL } if(length(raw.sheet) > 0) { sheet <- list(start = as.numeric(substring(raw.sheet,23,26)), end = as.numeric(substring(raw.sheet,34,37)), chain = trim(substring(raw.sheet,22,22)), sense = trim(substring(raw.sheet,39,40))) insert.i <- trim(substring(raw.sheet,27,27)) insert.e <- trim(substring(raw.sheet,38,38)) names(sheet$start) <- insert.i names(sheet$end) <- insert.e pa <- paste(sheet$start, insert.i, sheet$chain, sep='_') keep.inds <- which(!duplicated(pa)) sheet <- lapply(sheet, '[', keep.inds) } else { sheet <- NULL } atom <- read.table(text=sapply(raw.atom, split.fields), stringsAsFactors=FALSE, sep=";", quote='', colClasses=unname(atom.format[!drop.ind,"what"]), col.names=atom.format[!drop.ind,"name"], comment.char="", na.strings="") xyz.models <- matrix(as.numeric(c(t(atom[,c("x","y","z")]))), nrow=1) if (length(raw.end) > 1 && multi) { raw.atom <- raw.lines.multi[ type.multi %in% c("ATOM ","HETATM") ] if( (length(raw.atom)/length(raw.end)) ==nrow(atom) ){ tmp.xyz=( rbind( substr(raw.atom, first["x"],last["x"]), substr(raw.atom, first["y"],last["y"]), substr(raw.atom, first["z"],last["z"]) ) ) xyz.models <- matrix( as.numeric(tmp.xyz), ncol=nrow(atom)*3, nrow=length(raw.end), byrow=TRUE) rownames(xyz.models) = NULL } else { warning(paste("Unequal number of atoms in multi-model records:", file)) } rm(raw.lines.multi) } rm(raw.lines, raw.atom) if (rm.alt) { if ( sum( !is.na(atom[,"alt"]) ) > 0 ) { first.alt <- sort( unique(na.omit(atom[,"alt"])) )[1] cat(paste(" PDB has ALT records, taking",first.alt,"only, rm.alt=TRUE\n")) alt.inds <- which( (atom[,"alt"] != first.alt) ) if(length(alt.inds)>0) { atom <- atom[-alt.inds,] xyz.models <- xyz.models[ ,-atom2xyz(alt.inds), drop=FALSE ] } } } if (rm.insert) { if ( sum( !is.na(atom[,"insert"]) ) > 0 ) { cat(" PDB has INSERT records, removing, rm.insert=TRUE\n") insert.inds <- which(!is.na(atom[,"insert"])) atom <- atom[-insert.inds,] xyz.models <- xyz.models[ ,-atom2xyz(insert.inds), drop=FALSE ] } } output<-list(atom=atom, helix=helix, sheet=sheet, seqres=seqres, xyz=as.xyz(xyz.models), calpha = NULL, remark = remark, call=cl) class(output) <- c("pdb", "sse") ca.inds <- atom.select.pdb(output, string="calpha", verbose=FALSE) output$calpha <- seq(1, nrow(atom)) %in% ca.inds$atom return(output) }
library( "miscTools" ) m <- matrix( 1:9, 3 ) print( insertRow( m, 1, 10:12 ) ) print( insertRow( m, 2, 10:12 ) ) print( insertRow( m, 3, 10:12 ) ) print( insertRow( m, 4, 10:12 ) ) print( insertCol( m, 1, 10:12 ) ) print( insertCol( m, 2, 10:12 ) ) print( insertCol( m, 3, 10:12 ) ) print( insertCol( m, 4, 10:12 ) ) print( insertRow( m, 1, 10:12, "R0" ) ) print( insertRow( m, 2, 10:12, "R1a" ) ) print( insertRow( m, 3, 10:12, "R2a" ) ) print( insertRow( m, 4, 10:12, "R4" ) ) print( insertCol( m, 1, 10:12, "C0" ) ) print( insertCol( m, 2, 10:12, "C1a" ) ) print( insertCol( m, 3, 10:12, "C2a" ) ) print( insertCol( m, 4, 10:12, "C4" ) ) rownames( m ) <- c( "R1", "R2", "R3" ) colnames( m ) <- c( "C1", "C2", "C3" ) print( insertRow( m, 1, 10:12 ) ) print( insertRow( m, 2, 10:12 ) ) print( insertRow( m, 3, 10:12 ) ) print( insertRow( m, 4, 10:12 ) ) print( insertCol( m, 1, 10:12 ) ) print( insertCol( m, 2, 10:12 ) ) print( insertCol( m, 3, 10:12 ) ) print( insertCol( m, 4, 10:12 ) ) print( insertRow( m, 1, 10:12, "R0" ) ) print( insertRow( m, 2, 10:12, "R1a" ) ) print( insertRow( m, 3, 10:12, "R2a" ) ) print( insertRow( m, 4, 10:12, "R4" ) ) print( insertCol( m, 1, 10:12, "C0" ) ) print( insertCol( m, 2, 10:12, "C1a" ) ) print( insertCol( m, 3, 10:12, "C2a" ) ) print( insertCol( m, 4, 10:12, "C4" ) ) insertRow( matrix( 1:3, ncol=1 ), 2, 4 ) insertCol( matrix( 1:3, nrow=1 ), 2, 4 )
fill_serie <- function(df, colName, timeStep){ if(is.data.frame(df) == FALSE){ return('df must be a data frame object') } if(timeStep != 'day' & timeStep != 'month' & timeStep != '4h' & timeStep != 'day/3' & timeStep != 'hour'){ return('timeStep must be one of the following: day - month - 4h - day/3 - hour') } colnames(df) <- c('Date', colName) N <- length(df[ , 1]) time.min <- df[1, 1] time.max <- df[N, 1] if(timeStep == 'day' | timeStep == 'month'){ all.dates <- seq(from = time.min, to = time.max, by = timeStep) } else if(timeStep == 'hour'){ all.dates <- seq(from = time.min, to = time.max, by = timeStep) } else if(timeStep == '4h'){ all.dates <- seq(from = as.POSIXct( as.character(time.min), tz = 'ART' ), to = as.POSIXct( as.character(time.max), tz = 'ART' ), by = '4 hour') } else { all.dates <- seq(from = as.POSIXct( as.character(time.min), tz = 'ART' ), to = as.POSIXct( as.character(time.max), tz = 'ART' ), by = '6 hour') aux_index <- which(format(all.dates, '%H') == '03') all.dates <- all.dates[-aux_index] rm(aux_index) } all.dates.frame <- data.frame(Date = all.dates) merged.data <- merge(all.dates.frame, df, all = TRUE) return(merged.data) }
bruvo.dist <- function(pop, replen = 1, add = TRUE, loss = TRUE, by_locus = FALSE){ if (pop@type != "codom" || all(is.na(unlist(lapply(alleles(pop), as.numeric))))){ stop(non_ssr_data_warning()) } if (length(replen) < nLoc(pop)){ replen <- vapply(alleles(pop), function(x) guesslengths(as.numeric(x)), 1) warning(repeat_length_warning(replen), immediate. = TRUE) if (interactive()) Sys.sleep(2L) } bruvomat <- new('bruvomat', pop, replen) funk_call <- match.call() if (length(add) != 1 || !is.logical(add) || length(loss) != 1 || !is.logical(loss)){ stop("add and loss flags must be either TRUE or FALSE. Please check your input.") } dist.mat <- bruvos_distance(bruvomat, funk_call = funk_call, add, loss, by_locus) if (by_locus){ names(dist.mat) <- locNames(pop) } return(dist.mat) } bruvo.between <- function(query, ref, replen = 1, add = TRUE, loss = TRUE, by_locus = FALSE){ pop <- repool(query, ref) query_length <- dim(query@tab)[1] if (pop@type != "codom" || all(is.na(unlist(lapply(alleles(pop), as.numeric))))){ stop(non_ssr_data_warning()) } if (length(replen) < nLoc(pop)){ replen <- vapply(alleles(pop), function(x) guesslengths(as.numeric(x)), 1) warning(repeat_length_warning(replen), immediate. = TRUE) if (interactive()) Sys.sleep(2L) } bruvomat <- new('bruvomat', pop, replen) funk_call <- match.call() if (length(add) != 1 || !is.logical(add) || length(loss) != 1 || !is.logical(loss)){ stop("add and loss flags must be either TRUE or FALSE. Please check your input.") } dist.mat <- bruvos_between(bruvomat, query_length, funk_call = funk_call, add, loss, by_locus) if (by_locus){ names(dist.mat) <- locNames(pop) } return(dist.mat) } bruvo.boot <- function(pop, replen = 1, add = TRUE, loss = TRUE, sample = 100, tree = "upgma", showtree = TRUE, cutoff = NULL, quiet = FALSE, root = NULL, ...){ if (pop@type != "codom" || all(is.na(unlist(lapply(alleles(pop), as.numeric))))){ stop(non_ssr_data_warning()) } if (length(replen) < length(locNames(pop))) { replen <- vapply(alleles(pop), function(x) guesslengths(as.numeric(x)), 1) warning(repeat_length_warning(replen), immediate. = TRUE) if (interactive()) Sys.sleep(2L) } bootgen <- new('bruvomat', pop, replen) treechar <- paste(as.character(substitute(tree)), collapse = "") if ("upgma" %in% treechar){ treefun <- upgma } else if ("nj" %in% treechar){ treefun <- nj } else { treefun <- match.fun(tree) } bootfun <- function(x){ treefun(bruvos_distance(x, funk_call = match.call(), add = add, loss = loss)) } tre <- bootfun(bootgen) if (is.null(root)){ root <- ape::is.ultrametric(tre) } if (any (tre$edge.length < 0)){ warning(negative_branch_warning(), immediate.=TRUE) tre <- fix_negative_branch(tre) } if (quiet == FALSE){ cat("\nBootstrapping...\n") cat("(note: calculation of node labels can take a while even after") cat(" the progress bar is full)\n\n") } bp <- boot.phylo(tre, bootgen, FUN = bootfun, B = sample, quiet = quiet, rooted = root, ...) tre$node.labels <- round(((bp / sample)*100)) if (!is.null(cutoff)){ if (cutoff < 1 | cutoff > 100){ cat("Cutoff value must be between 0 and 100.\n") prompt_msg <- "Choose a new cutoff value between 0 and 100:\n" cutoff <- as.numeric(readline(prompt = prompt_msg)) } tre$node.labels[tre$node.labels < cutoff] <- NA } tre$tip.label <- indNames(pop) if (showtree){ poppr.plot.phylo(tre, treechar, root) } return(tre) } bruvo.msn <- function (gid, replen = 1, add = TRUE, loss = TRUE, mlg.compute = "original", palette = topo.colors, sublist = "All", exclude = NULL, blacklist = NULL, vertex.label = "MLG", gscale = TRUE, glim = c(0,0.8), gadj = 3, gweight = 1, wscale = TRUE, showplot = TRUE, include.ties = FALSE, threshold = NULL, clustering.algorithm = NULL, ...){ if (!inherits(gid, "genind")){ stop("Bruvo's distance only works for microsatellite markers. gid must be a genind/genclone object.") } if (!is.genclone(gid)){ gid <- as.genclone(gid) } if (!inherits(gid@mlg, "MLG")){ gid@mlg <- new("MLG", gid@mlg) } if (!is.null(blacklist)) { warning( option_deprecated( match.call(), "blacklist", "exclude", "2.8.7.", "Please use `exclude` in the future" ), immediate. = TRUE ) exclude <- blacklist } visible_mlg <- visible(gid@mlg) if (visible_mlg == "custom"){ mll(gid) <- mlg.compute } else if (visible_mlg == "contracted"){ mll(gid) <- "original" if (is.null(threshold)){ threshold <- cutoff(gid@mlg)["contracted"] } if (is.null(clustering.algorithm)){ clustering.algorithm <- distalgo(gid@mlg) } } gadj <- ifelse(gweight == 1, gadj, -gadj) if (toupper(sublist[1]) != "ALL" | !is.null(exclude)){ gid <- popsub(gid, sublist, exclude) } if (!is.null(threshold)){ bruvo_args <- list(replen = replen, add = add, loss = loss) filtered <- filter_at_threshold(gid, threshold, indist = NULL, clustering.algorithm, bruvo_args = bruvo_args) distmat <- filtered$indist cgid <- filtered$cgid gid <- filtered$gid } else { cgid <- gid[.clonecorrector(gid), ] distmat <- as.matrix(bruvo.dist(cgid, replen=replen, add = add, loss = loss)) } poppr_msn_list <- msn_constructor( gid = gid, cgid = cgid, palette = palette, indist = distmat, include.ties = include.ties, mlg.compute = mlg.compute, vlab = vertex.label, visible_mlg = visible_mlg, wscale = wscale, gscale = gscale, glim = glim, gadj = gadj, showplot = showplot, ...) return(poppr_msn_list) } test_replen <- function(gid, replen){ replen <- cromulent_replen(gid, replen) alleles <- lapply(alleles(gid), as.numeric) are_consistent <- vapply(locNames(gid), consistent_replen, logical(1), alleles, replen) names(are_consistent) <- locNames(gid) return(are_consistent) } consistent_replen <- function(index, alleles, replen){ !any(duplicated(round(alleles[[index]]/replen[index]))) } fix_replen <- function(gid, replen, e = 1e-5, fix_some = TRUE){ replen <- cromulent_replen(gid, replen) consistent_reps <- test_replen(gid, replen) names(replen) <- locNames(gid) ADD <- FALSE SUB <- FALSE newReps <- replen while (any(!consistent_reps)){ if (!SUB){ newReps[!consistent_reps] <- newReps[!consistent_reps] - e SUB <- TRUE } else { newReps[!consistent_reps] <- newReps[!consistent_reps] + (2*e) ADD <- TRUE } consistent_reps <- test_replen(gid, newReps) if (any(!consistent_reps) & ADD & SUB){ inconsistent <- paste(names(replen[!consistent_reps]), collapse = ", ") msg <- paste("The repeat lengths for", inconsistent, "are not consistent.\n\n", "This might be due to inconsistent allele calls or repeat", "lengths that are too large.\n", "Check the alleles to make sure there are no duplicated", "or similar alleles that might end up being the same after", "division.\n") if (fix_some){ original <- test_replen(gid, replen) fixed <- paste(names(replen[!original & consistent_reps]), collapse = ", ") msg <- paste(msg, "\nRepeat lengths with some modification are", "being returned:", fixed) newReps[!consistent_reps] <- replen[!consistent_reps] } else { msg <- paste(msg, "\nOriginal repeat lengths are being returned.") newReps <- replen } warning(msg, immediate. = TRUE) consistent_reps <- TRUE } } return(newReps) }
fitOR <- function(dd) { llikh <- function(ab,d2) { dz <- d2[,-1,drop=FALSE] m <- dim(dz)[2] n <- dim(dz)[1] a <- ab[1:3] b <- matrix( ab[-(1:3)],nrow=2,byrow=TRUE) b <- rbind(b,b[1,]+b[2,]) ll <- 0 for (i in 1:n) { h <- rep(0,4) for (j in 1:3) h[j+1] <- a[j] + drop( b[j,] %*% t(dz[i,])) hh <- sum(exp(h)) ll <- ll + h[d2$xy[i]] - log(hh) } ll } dllikh <- function(ab,d2) { dz <- d2[,-1,drop=FALSE] m <- dim(dz)[2] n <- dim(dz)[1] a <- ab[1:3] b <- matrix(ab[-(1:3)],nrow=2,byrow=TRUE) b <- rbind(b,b[1,]+b[2,]) dl <- rep(0,3+2*m) for (i in 1:n) { h <- rep(0,4) for (j in 1:3) h[j+1] <- a[j] + drop(b[j,] %*% t(dz[i,])) hh <- sum(exp(h)) pp <- exp(h)/hh xy <- d2$xy[i] for (j in 1:3) dl[j] <- dl[j] + (xy-1==j)*1 - pp[j+1] for (k in 1:m) { k1 <- m + k ix <- ifelse ((xy==2 | xy==4),1,0) iy <- ifelse ((xy==3 | xy==4),1,0) dl[3+k] <- dl[3+k] +(ix - pp[4]-pp[2])*dz[i,k] dl[3+k1] <- dl[3+k1]+(iy - pp[4]-pp[3])*dz[i,k] } } dl } m <- dim(dd)[2]-2 covnam <- names(dd)[-(1:2)] xy <- 1+2*dd$x+dd$y ddxy <- cbind(xy,dd) mmu <- paste("xy ~",paste(covnam,collapse="+"),collapse="") d2 <- ddxy[,c(-2,-3)] fit0 <- multinom(xy~1, data=ddxy) sF <- summary(fitF <- multinom(formula(mmu), data=ddxy, Hess=TRUE)) start <- coef(sF) start <- c(start[1:3,1],start[1,2:(m+1)],start[2,2:(m+1)]) fitH <- optim(start, llikh, dllikh, d2, hessian=TRUE, method="BFGS", control=list(fnscale=-1,maxit=200,trace=0) ) cH <- matrix(NA,nrow=3,ncol=m+1) cH[,1] <- fitH$par[1:3] for (j in 1:m) cH[1:2,1+j] <- fitH$par[-c(1:3)][(2*j-1):(2*j)] cH[3,2:(m+1)] <- cH[1,2:(m+1)]+cH[2,2:(m+1)] attributes(cH) <- attributes(fitF$coeff) fitH$coeff <- cH return(list(fitH=fitH,fitF=sF,fit0=fit0)) }
ti_pp <- function(Llim, Ulim, mu, sigma, n=10, n.batch=1, alpha=0.05, coverprob = 0.675, side = 2){ k <- k_factor(n = n, alpha = alpha, P = coverprob, side = side) Func <- function(V){ (pnorm(q = Ulim-k*sqrt(V), mean = mu, sd = sigma/sqrt(n))-pnorm(q = Llim+k*sqrt(V), mean = mu, sd = sigma/sqrt(n)))*dchisq(x = (n-1)*V/sigma^2, df = n-1) } (min(1, integrate(Func, lower = 0, upper = ((Ulim-Llim)/(2*k))^2, rel.tol = 1e-10)$value*(n-1)/sigma^2))^n.batch }
str2rect <- function(grb, fontcol, fill, fontface, fontfamily, inflate.labels, cex_index, align.labels, xmod.labels, ymod.labels, eval.labels) { if (eval.labels) { txtWraps <- mapply(function(x,y)list(txt=x, lines=y), grb$name, 1, SIMPLIFY=FALSE) } else { txtWraps <- lapply(grb$name, FUN=function(txt) { txtWrap <- list(txt) txtWrap[2:5] <- sapply(2:5, FUN=function(x, txt) { sq <- seq(1,5,by=2) results <- lapply(sq, FUN=function(pos, x, txt) { strwrap(txt, width = pos+(nchar(txt)/x))}, x, txt) lengths <- sapply(seq_along(sq), FUN=function(x)length(results[[x]])) results <- (results[lengths==x])[1]},txt) txtWrap <- sapply(txtWrap, FUN=paste, collapse="\n") strID <- which(txtWrap!="") nLines <- (1:5)[strID] txtWrap <- txtWrap[strID] return(list(txt=txtWrap, lines=nLines))}) } inchesW <- convertWidth(grb$width, "inches", valueOnly=TRUE) inchesH <- convertHeight(grb$height, "inches", valueOnly=TRUE) gp <- get.gpar() results <- mapply(txtWraps, inchesW, inchesH, FUN=function(wrap, inchesW, inchesH) { txtH <- convertHeight(unit(1,"lines"), "inches", valueOnly=TRUE) * (wrap$lines-0.25) * gp$lineheight txtW <- convertWidth(stringWidth(wrap$txt), "inches", valueOnly=TRUE) incrW <- (inchesW / txtW) incrH <- (inchesH / txtH) incr <- pmin.int(incrH, incrW) if (inflate.labels) { aspR <- pmax.int(incrH, incrW) / incr winningStr <- which.min(aspR) } else { incr[incr>1] <- 1 winningStr <- which.max(incr)[1] } return(list(txt=wrap$txt[winningStr], cex=incr[winningStr], lines=wrap$lines[winningStr])) }) txt <- unlist(results[1,]) cex <- if (eval.labels) rep(cex_index, length(grb$name)) else unlist(results[2,]) * cex_index nlines <- unlist(results[3,]) if (align.labels[1]%in%c("center", "centre")) { x <- grb$x + 0.5*grb$width xjust <- .5 } else if(align.labels[1]=="left") { x <- grb$x + unit(.25, "lines") xjust <- 0 } else if(align.labels[1]=="right") { x <- grb$x + grb$width - unit(.25, "lines") xjust <- 1 } if (align.labels[2]%in%c("center", "centre")) { y <- grb$y + 0.5*grb$height yjust <- .5 } else if(align.labels[2]=="top") { y <- grb$y + grb$height - unit(.25, "lines") yjust <- 1 } else if(align.labels[2]=="bottom") { y <- grb$y + unit(.25, "lines") yjust <- 0 } if (is.null(names(xmod.labels))) { xmod.labels <- rep(xmod.labels, length.out = length(x)) } else { tmp <- rep(0, length.out = length(x)) names(tmp) <- grb$name sel <- which(names(xmod.labels) %in% names(tmp)) if (!length(sel)==0) tmp[names(xmod.labels)[sel]] <- xmod.labels[sel] xmod.labels <- unname(tmp) } if (is.null(names(ymod.labels))) { ymod.labels <- rep(ymod.labels, length.out = length(y)) } else { tmp <- rep(0, length.out = length(y)) names(tmp) <- grb$name sel <- which(names(ymod.labels) %in% names(tmp)) if (!length(sel)==0) tmp[names(ymod.labels)[sel]] <- ymod.labels[sel] ymod.labels <- unname(tmp) } x <- x + unit(xmod.labels, "inch") y <- y + unit(ymod.labels, "inch") if (eval.labels) txt <- sapply(txt, function(tx) { parse(text=tx) }) txtGrb <- textGrob(txt, x=x, y=y, just=c(xjust, yjust), gp=gpar(cex=cex, fontface=fontface, fontfamily=fontfamily, col=fontcol)) txtGrbW <- mapply(txt, cex, FUN=function(x,y, fontface){ convertWidth(grobWidth(textGrob(x, gp=gpar(cex=y, fontface=fontface, fontfamily=fontfamily))),"inches", valueOnly=TRUE)}, fontface, USE.NAMES=FALSE) tooLarge <- (txtGrbW > inchesW) txtGrb$gp$cex[tooLarge] <- txtGrb$gp$cex[tooLarge] * (inchesW[tooLarge]/txtGrbW[tooLarge]) * 0.9 bckH <- mapply(txt, txtGrb$gp$cex, nlines, FUN=function(x,y,z, fontface){ convertHeight(grobHeight(textGrob(x, gp=gpar(cex=y, fontface=fontface, fontfamily=fontfamily))),"npc", valueOnly=TRUE) * z/(z-0.25)}, fontface, USE.NAMES=FALSE) bckW <- mapply(txt, txtGrb$gp$cex, FUN=function(x,y, fontface){ convertWidth(grobWidth(textGrob(x, gp=gpar(cex=y, fontface=fontface, fontfamily=fontfamily))),"npc", valueOnly=TRUE)}, fontface, USE.NAMES=FALSE) rectx <- txtGrb$x recty <- txtGrb$y if (align.labels[1]=="left") { rectx <- rectx + unit(0.5*bckW, "npc") } else if(align.labels[1]=="right") { rectx <- rectx - unit(0.5*bckW, "npc") } if (align.labels[2]=="bottom") { recty <- recty + unit(0.5*bckH, "npc") } else if(align.labels[2]=="top") { recty <- recty - unit(0.5*bckH, "npc") } bckGrb <- rectGrob(x=rectx, y=recty, width=bckW, height=bckH, gp=gpar(fill=fill, col=NA)) return(list(txt=txtGrb, bg=bckGrb)) }
setClass(Class = "clv.bgnbd.static.cov", contains = "clv.fitted.transactions.static.cov", slots = c( cbs = "data.table"), prototype = list( cbs = data.table())) clv.bgnbd.static.cov <- function(cl, clv.data){ dt.cbs.bgnbd <- bgnbd_cbs(clv.data = clv.data) clv.model <- clv.model.bgnbd.static.cov() return(new("clv.bgnbd.static.cov", clv.fitted.transactions.static.cov(cl=cl, clv.model=clv.model, clv.data=clv.data), cbs = dt.cbs.bgnbd)) }
get_data_plot_info <- function(ip, theta_range = c(-5, 5), tif = FALSE) { ip <- itempool(flatten_itempool_cpp(ip)) item_ids <- ip$resp_id theta_range <- process_theta_range(theta_range, n_theta = 301) theta <- theta_range$theta theta_range <- theta_range$range info_data <- info(ip = ip, theta = theta, tif = tif) if (tif) colnames(info_data) <- "info" else colnames(info_data) <- item_ids info_data <- data.frame(cbind(theta = theta, info_data)) if (!tif) info_data <- reshape(data = info_data, direction = "long", varying = list(item_ids), v.names = "info", timevar = "item_id", times = item_ids, idvar = "theta", new.row.names = sequence(length(theta) * length(ip))) return(info_data) } plot_info <- function(ip, tif = FALSE, theta_range = c(-5,5), focus_item = NULL, title = "", suppress_plot = FALSE, base_r_graph = FALSE, ...) { args <- list(...) if (!is(ip, "Itempool")) tryCatch( {ip <- itempool(ip)}, error = function(cond) { message("\nip cannot be converted to an 'Itempool' object. \n") stop(cond) }) focus_item <- check_focus_item(focus_item, ip = ip, single_value = FALSE) if (tif && !is.null(focus_item)) { message("When 'tif = TRUE', focus_item cannot be plotted.") focus_item <- NULL } if (title == "") title = ifelse( tif, "Test Information Function", paste0("Item Information Function", ifelse(is.null(focus_item), "", paste0(" for '", paste0(focus_item, collapse = "', '"), "'"))) ) theta_range <- process_theta_range(theta_range, n_theta = 501) theta <- theta_range$theta theta_range <- theta_range$range info_data <- get_data_plot_info(ip = ip, theta_range = theta, tif = tif) x_label <- expression("Theta ("*theta*")") y_label <- ifelse(tif, "Test Information", "Information") legend_title <- "Item ID" if (!base_r_graph && requireNamespace("ggplot2", quietly = TRUE)) { if (is.null(focus_item)) { if (tif || ip$n$items == 1) { p <- ggplot2::ggplot(data = info_data, ggplot2::aes_string(x = 'theta', y = 'info')) } else p <- ggplot2::ggplot(data = info_data, ggplot2::aes_string(x = 'theta', y = 'info', color = 'item_id')) p <- p + ggplot2::geom_line(...) + ggplot2::labs(x = x_label, y = y_label, title = title, color = ifelse(tif, NA, legend_title)) + ggplot2::theme(text = ggplot2::element_text(size = 18)) if (!tif) p <- p + ggplot2::guides(colour = ggplot2::guide_legend( override.aes = list(alpha = 1, size = 4))) } else { p <- ggplot2::ggplot() + ggplot2::geom_line( data = info_data[!info_data$item_id %in% focus_item, ], mapping = ggplot2::aes_string(x = "theta", y = "info", group = "item_id"), color = ifelse("color" %in% names(args), args$color, "tomato1"), alpha = ifelse("alpha" %in% names(args), args$alpha, 0.4)) + ggplot2::geom_line( data = info_data[info_data$item_id %in% focus_item, ], mapping = ggplot2::aes_string(x = "theta", y = "info", group = "item_id")) + ggplot2::labs(x = x_label, y = y_label, title = title) } p <- p + ggplot2::theme_bw() if (suppress_plot) return(p) else print(p) } else { old_par <- graphics::par(no.readonly = TRUE) y_lim = c(0, max(info_data$info)) if (is.null(focus_item)) { if (tif) { plot(x = info_data$theta, y = info_data$info, xlim = theta_range, ylab = y_label, xlab = x_label, ylim = y_lim, main = title, panel.first = graphics::grid(), type = "l") } else { item_ids <- unique(info_data$item_id) cl <- c(" " if (ip$n$items > 1) graphics::par(mar = c(5.1, 4.1, 4.1, 3 + .6 * max(nchar(item_ids)))) plot(0, 0, xlim = theta_range, ylim = y_lim, ylab = y_label, xlab = x_label, main = title, panel.first = graphics::grid(), type = "n") for (i in seq_along(item_ids)) { temp <- info_data[info_data$item_id == item_ids[i], ] graphics::lines(x = temp$theta, y = temp$info, col = cl[i], lty = 1, lwd = ifelse(item_ids[i] %in% focus_item, 2, 1)) } if (ip$n$items > 1) graphics::legend("topleft", item_ids, col = cl, lty = 1, xpd = TRUE, inset = c(1, 0), bty = "n", title = legend_title) } } else { item_ids <- unique(info_data$item_id) plot(0, 0, xlim = theta_range, ylim = y_lim, ylab = y_label, xlab = x_label, main = title, panel.first = graphics::grid(), type = "n") for (i in seq_along(item_ids)) { if (item_ids[i] %in% focus_item) next temp <- info_data[info_data$item_id == item_ids[i], ] graphics::lines(x = temp$theta, y = temp$info, lty = 1, col = ifelse("color" %in% names(args), args$color, "tomato1")) } for (i in seq_along(focus_item)) { temp <- info_data[info_data$item_id == focus_item[i], ] graphics::lines(x = temp$theta, y = temp$info, col = "black", lty = 1, lwd = 2) } } p <- grDevices::recordPlot() graphics::par(old_par) return(invisible(p)) } }
library('forecast') bonds <- structure(c(5.83, 6.06, 6.58, 7.09, 7.31, 7.23, 7.43, 7.37, 7.6, 7.89, 8.12, 7.96, 7.93, 7.61, 7.33, 7.18, 6.74, 6.27, 6.38, 6.6, 6.3, 6.13, 6.02, 5.79, 5.73, 5.89, 6.37, 6.62, 6.85, 7.03, 6.99, 6.75, 6.95, 6.64, 6.3, 6.4, 6.69, 6.52, 6.8, 7.01, 6.82, 6.6, 6.32, 6.4, 6.11, 5.82, 5.87, 5.89, 5.63, 5.65, 5.73, 5.72, 5.73, 5.58, 5.53, 5.41, 4.87, 4.58, 4.89, 4.69, 4.78, 4.99, 5.23, 5.18, 5.54, 5.9, 5.8, 5.94, 5.91, 6.1, 6.03, 6.26, 6.66, 6.52, 6.26, 6, 6.42, 6.1, 6.04, 5.83, 5.8, 5.74, 5.72, 5.23, 5.14, 5.1, 4.89, 5.13, 5.37, 5.26, 5.23, 4.97, 4.76, 4.55, 4.61, 5.07, 5, 4.9, 5.28, 5.21, 5.15, 4.9, 4.62, 4.24, 3.88, 3.91, 4.04, 4.03, 4.02, 3.9, 3.79, 3.94, 3.56, 3.32, 3.93, 4.44, 4.29, 4.27, 4.29, 4.26, 4.13, 4.06, 3.81, 4.32, 4.7), .Tsp = c(1994, 2004.33333333333, 12), class = "ts") usnetelec <- structure(c(296.1, 334.1, 375.3, 403.8, 447, 476.3, 550.3, 603.9, 634.6, 648.5, 713.4, 759.2, 797.1, 857.9, 920, 987.2, 1058.4, 1147.5, 1217.8, 1332.8, 1445.5, 1535.1, 1615.9, 1753, 1864.1, 1870.3, 1920.8, 2040.9, 2127.4, 2209.4, 2250.7, 2289.6, 2298, 2244.4, 2313.4, 2419.5, 2473, 2490.5, 2575.3, 2707.4, 2967.3, 3038, 3073.8, 3083.9, 3197.2, 3247.5, 3353.5, 3444.2, 3492.2, 3620.3, 3694.8, 3802.1, 3736.6, 3858.5, 3848), .Tsp = c(1949, 2003, 1), class = "ts") ukcars <- structure(c(330.371, 371.051, 270.67, 343.88, 358.491, 362.822, 261.281, 240.355, 325.382, 316.7, 171.153, 257.217, 298.127, 251.464, 181.555, 192.598, 245.652, 245.526, 225.261, 238.211, 257.385, 228.461, 175.371, 226.462, 266.15, 287.251, 225.883, 265.313, 272.759, 234.134, 196.462, 205.551, 291.283, 284.422, 221.571, 250.697, 253.757, 267.016, 220.388, 277.801, 283.233, 302.072, 259.72, 297.658, 306.129, 322.106, 256.723, 341.877, 356.004, 361.54, 270.433, 311.105, 326.688, 327.059, 274.257, 367.606, 346.163, 348.211, 250.008, 292.518, 343.318, 343.429, 275.386, 329.747, 364.521, 378.448, 300.798, 331.757, 362.536, 389.133, 323.322, 391.832, 421.646, 416.823, 311.713, 381.902, 422.982, 427.722, 376.85, 458.58, 436.225, 441.487, 369.566, 450.723, 462.442, 468.232, 403.636, 413.948, 460.496, 448.932, 407.787, 469.408, 494.311, 433.24, 335.106, 378.795, 387.1, 372.395, 335.79, 397.08, 449.755, 402.252, 391.847, 385.89, 424.325, 433.28, 391.213, 408.74, 445.458, 428.202, 379.048, 394.042, 432.796), .Tsp = c(1977, 2005, 4), class = "ts") visitors <- structure(c(75.7, 75.4, 83.1, 82.9, 77.3, 105.7, 121.9, 150, 98, 118, 129.5, 110.6, 91.7, 94.8, 109.5, 105.1, 95, 130.3, 156.7, 190.1, 139.7, 147.8, 145.2, 132.7, 120.7, 116.5, 142, 140.4, 128, 165.7, 183.1, 222.8, 161.3, 180.4, 185.2, 160.5, 157.1, 163.8, 203.3, 196.9, 179.6, 207.3, 208, 245.8, 168.9, 191.1, 180, 160.1, 136.6, 142.7, 175.4, 161.4, 149.9, 174.1, 192.7, 247.4, 176.2, 192.8, 189.1, 181.1, 149.9, 157.3, 185.3, 178.2, 162.7, 190.6, 198.6, 253.1, 177.4, 190.6, 189.2, 168, 161.4, 172.2, 208.3, 199.3, 197.4, 216, 223.9, 266.8, 196.1, 238.2, 217.8, 203.8, 175.2, 176.9, 219.3, 199.1, 190, 229.3, 255, 302.4, 242.8, 245.5, 257.9, 226.3, 213.4, 204.6, 244.6, 239.9, 224, 267.2, 285.9, 344, 250.5, 304.3, 307.4, 255.1, 214.9, 230.9, 282.5, 265.4, 254, 301.6, 311, 384, 303.8, 319.1, 313.5, 294.2, 244.8, 261.4, 329.7, 304.9, 268.6, 320.7, 342.9, 422.3, 317.2, 392.7, 365.6, 333.2, 261.5, 306.9, 358.2, 329.2, 309.2, 350.4, 375.6, 465.2, 342.9, 408, 390.9, 325.9, 289.1, 308.2, 397.4, 330.4, 330.9, 366.5, 379.5, 448.3, 346.2, 353.6, 338.6, 341.1, 283.4, 304.2, 372.3, 323.7, 323.9, 354.8, 367.9, 457.6, 351, 398.6, 389, 334.1, 298.1, 317.1, 388.5, 355.6, 353.1, 397, 416.7, 460.8, 360.8, 434.6, 411.9, 405.6, 319.3, 347.9, 429, 372.9, 403, 426.5, 459.9, 559.9, 416.6, 429.2, 428.7, 405.4, 330.2, 370, 446.9, 384.6, 366.3, 378.5, 376.2, 523.2, 379.3, 437.2, 446.5, 360.3, 329.9, 339.4, 418.2, 371.9, 358.6, 428.9, 437, 534, 396.6, 427.5, 392.5, 321.5, 260.9, 308.3, 415.5, 362.2, 385.6, 435.3, 473.3, 566.6, 420.2, 454.8, 432.3, 402.8, 341.3, 367.3, 472, 405.8, 395.6, 449.9, 479.9, 593.1, 462.4, 501.6, 504.7, 409.5), .Tsp = c(1985.33333333333, 2005.25, 12), class = "ts") par(mfrow = c(2,2)) mod1 <- ets(bonds) mod2 <- ets(usnetelec) mod3 <- ets(ukcars) mod4 <- ets(visitors) plot(forecast(mod1), main="(a) US 10-year bonds yield", xlab="Year", ylab="Percentage per annum") plot(forecast(mod2), main="(b) US net electricity generation", xlab="Year", ylab="Billion kwh") plot(forecast(mod3), main="(c) UK passenger motor vehicle production", xlab="Year", ylab="Thousands of cars") plot(forecast(mod4), main="(d) Overseas visitors to Australia", xlab="Year", ylab="Thousands of people") etsnames <- c(mod1$method, mod2$method, mod3$method, mod4$method) etsnames <- gsub("Ad","A\\\\damped",etsnames) etsfit <- ets(usnetelec) etsfit accuracy(etsfit) fcast <- forecast(etsfit) plot(fcast) fcast mod1 <- auto.arima(bonds, seasonal=FALSE, approximation=FALSE) mod2 <- auto.arima(usnetelec) mod3 <- auto.arima(ukcars) mod4 <- auto.arima(visitors) par(mfrow = c(2,2)) plot(forecast(mod1), main="(a) US 10-year bonds yield", xlab="Year", ylab="Percentage per annum") plot(forecast(mod2), main="(b) US net electricity generation", xlab="Year", ylab="Billion kwh") plot(forecast(mod3), main="(c) UK passenger motor vehicle production", xlab="Year", ylab="Thousands of cars") plot(forecast(mod4), main="(d) Overseas visitors to Australia", xlab="Year", ylab="Thousands of people") arimafit <- auto.arima(usnetelec) fcast <- forecast(arimafit) plot(fcast) arimanames <- c(as.character(mod1), as.character(mod2), as.character(mod3), as.character(mod4)) arimanames <- gsub("\\[([0-9]*)\\]", "$_{\\1}$", arimanames) summary(fcast)
contrast_ratio <- function(col, col2 = "white", plot = FALSE, border = FALSE, cex = 2, off = 0.05, mar = rep(0.5, 4), digits = 2L, ...) { if(length(col) < 1L || length(col2) < 1L) stop("both 'col' and 'col2' need to specify at least one color") n <- max(c(length(col), length(col2))) if(!(length(col) == n && length(col2) == n)) { col <- rep_len(col, n) col2 <- rep_len(col2, n) } ratio <- (relative_luminance(col) + 0.05)/(relative_luminance(col2) + 0.05) ratio[ratio < 1] <- 1/ratio[ratio < 1] plot <- rep_len(plot, 2L) if(any(plot)) { opar <- par(mar = mar) on.exit(par(opar)) if(identical(border, FALSE)) border <- "transparent" if(length(off) == 1L) off <- c(off, 0) plot(0, 0, xlim = c(0, sum(plot)), ylim = c(0, n), type = "n", axes = FALSE, xlab = "", ylab = "", ...) if(plot[1L]) { rect(0L, 1L:n - 1L, 1L - off[2L], 1L:n - off[1L], col = col, border = if(isTRUE(border)) col2 else border) text((1 - off[2L])/2, 1L:n - (1 - (1 - off[1L])/2), format(round(ratio, digits = digits), nsmall = 2L), cex = cex, col = col2) } if(plot[2L]) { rect(0L + plot[1L], 0L:(n - 1L), 1L - off[2L] + plot[1L], 1L:n - off[1L], col = col2, border = if(isTRUE(border)) col else border) text((1 - off[2L])/2 + plot[1L], 1L:n - (1 - (1 - off[1L])/2), format(round(ratio, digits = digits), nsmall = 2L), cex = cex, col = col) } invisible(ratio) } else { return(ratio) } } relative_luminance <- function(col) { rgb <- t(col2rgb(col))/255 rgb[] <- ifelse(rgb <= 0.03928, rgb/12.92, ((rgb + 0.055)/1.055)^2.4) as.numeric(rgb %*% c(0.2126, 0.7152, 0.0722)) }