code
stringlengths
1
13.8M
expected <- eval(parse(text="structure(list(size = numeric(0), isdir = logical(0), mode = structure(integer(0), class = \"octmode\"), mtime = numeric(0), ctime = numeric(0), atime = numeric(0), uid = integer(0), gid = integer(0), uname = character(0), grname = character(0)), .Names = c(\"size\", \"isdir\", \"mode\", \"mtime\", \"ctime\", \"atime\", \"uid\", \"gid\", \"uname\", \"grname\"))")); test(id=0, code={ argv <- eval(parse(text="list(character(0))")); .Internal(file.info(argv[[1]])); }, o=expected);
gibbs_discrete <- function(p, i = 1, iter = 1000){ x <- matrix(0, iter, 2) nX <- dim(p)[1] nY <- dim(p)[2] for(k in 1:iter){ j <- sample(1:nY, 1, prob = p[i, ]) i <- sample(1:nX, 1, prob = p[, j]) x[k, ] <- c(i, j) } x }
post_imp_diag <- function(X_orig, X_imp, scale = TRUE, n.boot = 100) { if (!identical(dim(X_orig), dim(X_imp))) stop(paste("Warning! The dimensions of the original and imputed dataframes are unequal!", sep = "")) X_orig <- as.data.frame(X_orig) X_imp <- as.data.frame(X_imp) factors_present <- (sum(sapply(X_orig, is.factor)) > 0) if (factors_present & (scale == TRUE)) { ind <- sapply(X_orig, is.numeric) X_orig[ind] <- as.data.frame(lapply(X_orig[ind], scale)) } else if ((factors_present == FALSE) & (scale == TRUE)) { X_orig <- as.data.frame(scale(X_orig)) } histograms <- list() boxplots <- list() statistics <- list() barcharts <- list() X_orig_num <- X_orig[sapply(X_orig, is.numeric)] if (factors_present == TRUE) { X_orig_factor <- X_orig[!sapply(X_orig, is.numeric)] } X_imp_num <- X_imp[sapply(X_imp, is.numeric)] if (factors_present == TRUE) { X_imp_factor <- X_imp[!sapply(X_imp, is.numeric)] } if (factors_present == TRUE) { for (i in 1:ncol(X_orig_factor)) { pltName <- colnames(X_orig_factor)[i] col_index <- is.na(X_orig_factor[, i]) orig_values <- X_orig_factor[, i][!col_index] imp_values <- X_imp_factor[, i][col_index] origvec <- rep("Original values", length(orig_values)) impvec <- rep("Imputed values", length(imp_values)) vals <- data.frame(cbind(c(orig_values, imp_values), c(origvec, impvec))) levels(vals$X1) <- levels(orig_values) colnames(vals) <- c(colnames(X_orig_factor)[i], "Data") q <- ggplot(data = data.frame(x = vals[, 1], y = vals[, 2]), aes(x = factor(y), fill = factor(x))) + geom_bar(position = "fill") + ggtitle("Bar chart of original and imputed values") + labs(y = "Proportion", x = colnames(X_orig_factor)[i]) + guides(fill = guide_legend(title = "")) + theme(plot.title = element_text(hjust = 0.5)) barcharts[[pltName]] <- q } } X_orig_mat <- as.matrix(as.data.frame(scale(X_orig_num))) X_imp_mat <- as.matrix(as.data.frame(scale(X_imp_num))) colnames(X_orig_mat) <- colnames(X_orig_num) colnames(X_imp_mat) <- colnames(X_imp_num) X_orig_dendro <- stats::as.dendrogram(stats::hclust(stats::dist(t(X_orig_mat)))) X_imp_dendro <- stats::as.dendrogram(stats::hclust(stats::dist(t(X_imp_mat)))) X_orig_dendro_plot <- ggdendro::ggdendrogram(data = X_orig_dendro, rotate = TRUE) + labs(title = "Original dataframe - variable clusters") + theme(plot.title = element_text(hjust = 0.5)) X_imp_dendro_plot <- ggdendro::ggdendrogram(data = X_imp_dendro, rotate = TRUE) + labs(title = "Imputed dataframe - variable clusters") + theme(plot.title = element_text(hjust = 0.5)) for (i in 1:ncol(X_orig_num)) { pltName <- colnames(X_orig_num)[i] col_index <- is.na(X_orig_num[, i]) orig_values <- X_orig_num[, i][!col_index] imp_values <- X_imp_num[, i][col_index] if (length(imp_values) != 0) { tstats <- stats::t.test(orig_values, imp_values, alternative = "two.sided", var.equal = FALSE) ksstats <- stats::ks.test(orig_values, imp_values, exact=TRUE)$statistic statistics[[pltName]] <- c(Mean_original = mean(orig_values), SD_original = stats::sd(orig_values), Mean_imputed = mean(imp_values), SD_imputed = stats::sd(imp_values), Welch_ttest_P = tstats$p.value, KS_test = ksstats) origvec <- rep("Original values", length(orig_values)) impvec <- rep("Imputed values", length(imp_values)) vals <- data.frame(cbind(c(orig_values, imp_values), c(origvec, impvec))) vals$X1 <- as.numeric(as.character(vals$X1)) colnames(vals) <- c(colnames(X_orig_num)[i], "Data") p <- ggplot(data = data.frame(x = vals[, 1], y = vals[, 2]), aes(x, fill=y)) + geom_histogram(alpha = 0.5, binwidth = 0.5, position="identity") + ggtitle("Overlaid histogram of original and imputed values") + labs(x = colnames(X_orig_num)[i]) + guides(fill = guide_legend(title = "")) + theme(plot.title = element_text(hjust = 0.5)) q <- ggplot(data = data.frame(x = vals[, 2], y = vals[, 1]), aes(x = x, y = y)) + geom_boxplot() + stat_summary(fun.y = mean, geom = "point", shape = 3, size = 5) + ggtitle("Boxplots of original and imputed values") + labs(x = colnames(X_orig_num)[i], y = "") + theme(plot.title = element_text(hjust = 0.5)) histograms[[pltName]] <- p boxplots[[pltName]] <- q } else { statistics[[pltName]] <- c(Mean_original = mean(orig_values), SD_original = stats::sd(orig_values), Mean_imputed = NA, SD_imputed = NA, Welch_ttest_P = NA, KS_test = NA) origvec <- rep("Original values", length(orig_values)) impvec <- rep("Imputed values", length(imp_values)) vals <- data.frame(cbind(c(orig_values, imp_values), c(origvec, impvec))) vals$X1 <- as.numeric(as.character(vals$X1)) colnames(vals) <- c(colnames(X_orig_num)[i], "Data") p <- ggplot(data = data.frame(x = vals[, 1], y = vals[, 2]), aes(x, fill=y)) + geom_histogram(alpha = 0.5, binwidth = 0.5, position="identity") + ggtitle("Histogram of original values") + labs(x = colnames(X_orig_num)[i]) + guides(fill = guide_legend(title = "")) + theme(plot.title = element_text(hjust = 0.5)) q <- ggplot(data = data.frame(x = vals[, 2], y = vals[, 1]), aes(x = x, y = y)) + geom_boxplot() + stat_summary(fun.y = mean, geom = "point", shape = 3, size = 5) + ggtitle("Boxplot of original values") + labs(x = colnames(X_orig_num)[i], y = "") + theme(plot.title = element_text(hjust = 0.5)) histograms[[pltName]] <- p boxplots[[pltName]] <- q } } corrs <- NULL meanmat <- matrix(nrow = ncol(X_orig_num), ncol = ncol(X_orig_num)) locimat <- matrix(nrow = ncol(X_orig_num), ncol = ncol(X_orig_num)) hicimat <- matrix(nrow = ncol(X_orig_num), ncol = ncol(X_orig_num)) for (i in 1:ncol(X_orig_num)) { for (j in 1:ncol(X_orig_num)) { for (b in 1:n.boot) { idx <- sample.int(nrow(X_orig_num), nrow(X_orig_num), replace = TRUE) corrs[b] <- cor(X_orig_num[idx, ], use = "pairwise.complete.obs", method = "pearson")[i, j] } meanmat[i, j] <- mean(corrs) locimat[i, j] <- quantile(corrs, c(0.025)) hicimat[i, j] <- quantile(corrs, c(0.975)) corrs <- NULL } } meanmat[lower.tri(meanmat, diag = TRUE)] <- NA y <- as.data.frame(meanmat) colnames(y) <- colnames(X_orig_num) rownames(y) <- colnames(X_orig_num) y$var1 <- row.names(y) z <- gather(data = y, key = "var2", value = "value", -var1) correlation_results <- z[!is.na(z$value), ] locimat[lower.tri(locimat, diag = TRUE)] <- NA y <- as.data.frame(locimat) colnames(y) <- colnames(X_orig_num) rownames(y) <- colnames(X_orig_num) y$var1 <- row.names(y) z <- gather(data = y, key = "var2", value = "value", -var1) z <- z[!is.na(z$value), ] correlation_results <- cbind(correlation_results, z$value) hicimat[lower.tri(hicimat, diag = TRUE)] <- NA y <- as.data.frame(hicimat) colnames(y) <- colnames(X_orig_num) rownames(y) <- colnames(X_orig_num) y$var1 <- row.names(y) z <- gather(data = y, key = "var2", value = "value", -var1) z <- z[!is.na(z$value), ] correlation_results <- cbind(correlation_results, z$value) meanmat <- matrix(nrow = ncol(X_imp_num), ncol = ncol(X_imp_num)) locimat <- matrix(nrow = ncol(X_imp_num), ncol = ncol(X_imp_num)) hicimat <- matrix(nrow = ncol(X_imp_num), ncol = ncol(X_imp_num)) for (i in 1:ncol(X_imp_num)) { for (j in 1:ncol(X_imp_num)) { for (b in 1:n.boot) { idx <- sample.int(nrow(X_imp_num), nrow(X_imp_num), replace = TRUE) corrs[b] <- cor(X_imp_num[idx, ], use = "pairwise.complete.obs", method = "pearson")[i, j] } meanmat[i, j] <- mean(corrs) locimat[i, j] <- quantile(corrs, c(0.025)) hicimat[i, j] <- quantile(corrs, c(0.975)) } } meanmat[lower.tri(meanmat, diag = TRUE)] <- NA y <- as.data.frame(meanmat) colnames(y) <- colnames(X_imp_num) rownames(y) <- colnames(X_imp_num) y$var1 <- row.names(y) z <- gather(data = y, key = "var2", value = "value", -var1) z <- z[!is.na(z$value), ] correlation_results <- cbind(correlation_results, z$value) locimat[lower.tri(locimat, diag = TRUE)] <- NA y <- as.data.frame(locimat) colnames(y) <- colnames(X_imp_num) rownames(y) <- colnames(X_imp_num) y$var1 <- row.names(y) z <- gather(data = y, key = "var2", value = "value", -var1) z <- z[!is.na(z$value), ] correlation_results <- cbind(correlation_results, z$value) hicimat[lower.tri(hicimat, diag = TRUE)] <- NA y <- as.data.frame(hicimat) colnames(y) <- colnames(X_imp_num) rownames(y) <- colnames(X_imp_num) y$var1 <- row.names(y) z <- gather(data = y, key = "var2", value = "value", -var1) z <- z[!is.na(z$value), ] correlation_results <- cbind(correlation_results, z$value) colnames(correlation_results) <- c("var1", "var2", "orig.cor", "orig.lo.ci", "orig.hi.ci", "imp.cor", "imp.lo.ci", "imp.hi.ci") p <- ggplot(data = correlation_results, aes(x = orig.cor, y = imp.cor)) + geom_point(alpha = 0.2) + geom_errorbar(aes(ymin = imp.lo.ci, ymax = imp.hi.ci), alpha = 0.1) + geom_errorbarh(aes(xmin = orig.lo.ci, xmax = orig.hi.ci), alpha = 0.1) + geom_abline(slope = 1, intercept = 0, col = "blue", alpha = 0.5) + geom_line(stat = "smooth", method = "lm", col = "red", alpha = 0.5) + ggtitle("Scatter plot of correlation coefficients") + theme(plot.title = element_text(hjust = 0.5)) + labs(x = "Correlation coefficient (original)", y = "Correlation coefficient (imputed)") list(Histograms = histograms, Boxplots = boxplots, Barcharts = barcharts, Statistics = statistics, Variable_clusters_orig = X_orig_dendro_plot, Variable_clusters_imp = X_imp_dendro_plot, Correlation_stats = correlation_results, Correlation_plot = p) }
context("mboFinalize") options(mlrMBO.debug.mode = FALSE) test_that("mboFinalize", { or = NULL assign(".counter", 0L, envir = .GlobalEnv) f = makeSingleObjectiveFunction( fn = function(x) { .counter = get(".counter", envir = .GlobalEnv) assign(".counter", .counter + 1L, envir = .GlobalEnv) if (.counter == 12) stop("foo") sum(x^2) }, par.set = makeNumericParamSet(len = 2L, lower = -2, upper = 1) ) learner = makeLearner("regr.rpart") save.file = tempfile("state", fileext=".RData") ctrl = makeMBOControl(save.on.disk.at = 0:4, save.file.path = save.file) ctrl = setMBOControlTermination(ctrl, iters = 3L) ctrl = setMBOControlInfill(ctrl, crit = crit.mr, opt.focussearch.points = 10L) des = generateTestDesign(10L, getParamSet(f)) expect_error(or <- mbo(f, des, learner = learner, control = ctrl), "foo") or = mboFinalize(save.file) expect_equal(getOptPathLength(or$opt.path), 12L) unlink(save.file) assign(".counter", 0L, envir = .GlobalEnv) f = makeMultiObjectiveFunction( fn = function(x) { .counter <<- .counter + 1 if (.counter == 13L) stop ("foo") c(sum(x^2), prod(x^2)) }, n.objectives = 2L, par.set = makeNumericParamSet(len = 2L, lower = -2, upper = 1) ) des = generateTestDesign(10L, getParamSet(f)) ctrl = makeMBOControl(save.on.disk.at = 0:8, save.file.path = save.file, n.objectives = 2L) ctrl = setMBOControlTermination(ctrl, iters = 7L) ctrl = setMBOControlInfill(ctrl, crit = crit.mr, opt.focussearch.points = 100L) ctrl = setMBOControlMultiObj(ctrl, method = "parego", parego.s = 100L) or = NULL expect_error(or <- mbo(f, des, learner = learner, control = ctrl), "foo") or = mboFinalize(save.file) expect_equal(getOptPathLength(or$opt.path), 12L) unlink(save.file) }) test_that("mboFinalize works when at end", { f = makeSingleObjectiveFunction( fn = function(x) sum(x^2), par.set = makeNumericParamSet(len = 2L, lower = -2, upper = 1) ) learner = makeLearner("regr.rpart") save.file = tempfile(fileext = ".RData") des = generateTestDesign(10L, getParamSet(f)) ctrl = makeMBOControl(save.on.disk.at = 0:2, save.file.path = save.file) ctrl = setMBOControlTermination(ctrl, iters = 1L) ctrl = setMBOControlInfill(ctrl, crit = crit.mr, opt.focussearch.points = 10L) or = mbo(f, des, learner = learner, control = ctrl) expect_equal(getOptPathLength(or$opt.path), 11L) expect_warning({or = mboFinalize(save.file)}, "No need to finalize") expect_equal(getOptPathLength(or$opt.path), 11L) unlink(save.file) }) options(mlrMBO.debug.mode = TRUE)
`dsbelpl` <- function(x,a){ erg=c(0,0); erg[1]=sum(x[(x[,1]>=a[1]&x[,2]<=a[2]),3]); erg[2]=sum(x[!(x[,1]>a[2]|x[,2]<a[1]),3]); dsbelpl=erg; }
qa.xdate <- function(rwl, seg.length, n, bin.floor){ if(!is.data.frame(rwl)) stop("'rwl' must be a data.frame") if(seg.length*2 > nrow(rwl)) stop("'seg.length' can be at most 1/2 the number of years in 'rwl'") if(as.logical(seg.length %% 2)) stop("'seg.length' must be even") if(!is.int(seg.length)) stop("'seg.length' and 'seg.lag' must be integers") if(seg.length <= 0) stop("'seg.length' must be positive") if(!is.null(n)){ if(!is.int(n)) stop("'n' must be an integer") if(!as.logical(n %% 2)) stop("'n' must be odd") if(n <= 3) stop("'n' must be larger than 3") } if(!is.null(bin.floor) && (!is.int(bin.floor) || bin.floor < 0)) stop("'bin.floor' must be a non-negative integer") }
paf<-function(a,b){ rown<-dim(a)[1] coln<-dim(a)[2] res<-matrix(0,rown,coln) counter<-0 for (i in 1:rown){ if (b[i]==1){ counter<-counter+1 res[counter,]<-a[i,] } } res<-res[1:counter,] return(res) }
library(sstModel) name <- c("EURCHF", "USDCHF", "equityCHF", "equityEUR", "equityUSD", "kYCHF", "mYCHF", "kYEUR", "mYEUR", "PC1RateUSD", "PC2RateUSD", "AAACHF", "AAAEUR", "AAAUSD") corr.mat <- diag(rep(1, 14)) colnames(corr.mat) <- name rownames(corr.mat) <- name volatility <- rep(0.05, 14) cov.mat <- diag(volatility, length(volatility), length(volatility)) %*% corr.mat %*% diag(volatility, length(volatility), length(volatility)) colnames(cov.mat) <- rownames(cov.mat) <- colnames(corr.mat) attr(cov.mat, "base.currency") <- "CHF" mapping.table <- mappingTable(currency(name = "EURCHF", from = "EUR", to = "CHF"), currency(name = "USDCHF", from = "USD", to = "CHF"), equity(name = "equityCHF", type = "equity", currency = "CHF"), equity(name = "equityEUR", type = "equity", currency = "EUR"), equity(name = "equityEUR", type = "equity", currency = "USD", scale = 0.4694625), pcRate(name = c("PC1RateUSD"), currency = "USD"), pcRate(name = c("PC2RateUSD"), currency = "USD"), pcRate(name = c("PC1RateUSD"), currency = "EUR", scale = 1), pcRate(name = c("PC2RateUSD"), currency = "EUR", scale = 1), rate(name = "kYCHF", currency = "CHF", horizon = "k"), rate(name = c("PC1RateUSD", "PC2RateUSD"), currency = "EUR", horizon = "k", scale = c(0.1, 0.7)), rate(name = c("PC1RateUSD", "PC2RateUSD"), currency = "USD", horizon = "k", scale = c(0.2, 0.5)), rate(name = "mYCHF", currency = "CHF", horizon = "m"), rate(name = c("PC1RateUSD", "PC2RateUSD"), currency = "EUR", horizon = "m", scale = c(0.05, 0.6)), rate(name = c("PC1RateUSD", "PC2RateUSD"), currency = "USD", horizon = "m", scale = c(0.1, 0.9)), spread(name = "AAACHF", currency = "CHF", rating = "AAA"), spread(name = "AAAEUR", currency = "EUR", rating = "AAA"), spread(name = "AAAUSD", currency = "USD", rating = "AAA")) initial.values <- list() initial.values$initial.fx <- data.frame(from = c("EUR", "USD"), to = c("CHF", "CHF"), fx = c(1.05,1.02), stringsAsFactors = F) initial.values$initial.rate <- data.frame(time = c(2L, 2L, 2L, 10L, 10L, 10L), currency = c("CHF", "EUR", "USD"), rate = c(0.01, 0.01, 0.01, 0.03, 0.03, 0.03), stringsAsFactors = F) mapping.time <- data.frame(time = c(2L, 10L), mapping = c("k","m"), stringsAsFactors = F) mr <- marketRisk(cov.mat = cov.mat, mapping.table = mapping.table, base.currency = "CHF", initial.values = initial.values, mapping.time = mapping.time) M <- matrix(c(1, 1, 1, 1), 2) colnames(M) <- c("storno", "invalidity") rownames(M) <- colnames(M) lr <- lifeRisk(corr.mat = M, quantile = c(0.995, 0.995)) hr <- healthRisk(corr.mat = M) list.assets <- list(asset(type = "equity", currency = "CHF", value = 30000000), asset(type = "equity", currency = "EUR", value = 20000000), asset(type = "equity", currency = "USD", value = 5000000)) list.liabilities <- list(liability(time = 2L, currency = "CHF", value = 400000), liability(time = 2L, currency = "EUR", value = 700000), liability(time = 2L, currency = "USD", value = 340000), liability(time = 10L, currency = "CHF", value = 500000), liability(time = 10L, currency = "EUR", value = 100000), liability(time = 10L, currency = "USD", value = 240000)) list.asset.forward <- list(assetForward(type = "equity", currency = "CHF", time = 10L, exposure = 10000, price = 45000, position = "long")) list.marketItems <- append(append(append(append(list(), list.assets), list.liabilities),list.asset.forward), list(delta(name = "EURCHF", currency = "CHF", sensitivity = 1000))) valid.param <- list(mvm = list(mvm.life = 2, mvm.health = 4, mvm.nonlife = 3), rtkr = 0, rtkg = 0, correction.term = 2, credit.risk = 3, expected.insurance.result = 10^6, expected.financial.result = 10^5) p <- portfolio(market.items = list.marketItems, participation.item = participation(currency = "CHF", value = 3000), life.item = life(name = c("storno", "invalidity"), currency = c("CHF", "CHF"), sensitivity = c(100, 2000)), health.item = health(name = c("storno", "invalidity"), currency = c("CHF", "CHF"), sensitivity = c(230, 500)), base.currency = "CHF", portfolio.parameters = valid.param) list.correlation.matrix <- list(base = matrix(c(1,0.15,0.075,0.15, 0.15,1,0.25,0.25, 0.075,0.25,1,0.15, 0.15,0.25,0.15,1), ncol=4, byrow = T), scenario1 = matrix(c(1,1,1,0.35, 1,1,1,0.35, 1,1,1,0.35, 0.35,0.35,0.35,1), ncol=4, byrow = T), scenario2 = matrix(c(1,0.6,0.5,0.25, 0.6,1,0.8,0.35, 0.5,0.8,1,0.35, 0.25,0.35,0.35,1), ncol=4, byrow = T), scenario3 = matrix(c(1,0.25,0.25,0.5, 0.25,1,0.25,0.25, 0.25,0.25,1,0.25, 0.5,0.25,0.25,1), ncol=4, byrow = T)) list.correlation.matrix <- lapply(list.correlation.matrix, function(corr) {rownames(corr) <- colnames(corr) <- c("market", "life","health","nonlife"); corr}) region.boundaries <- matrix(c(0.2,0.3,0.3,0.5, 0.5,0.2,0.2,0.8, 0.6,0.8,0.8,0.2), nrow=3, byrow = T) colnames(region.boundaries) <- c("market", "life","health","nonlife") rownames(region.boundaries) <- c("scenario1", "scenario2", "scenario3") scenario.probability = c(0.01, 0.01, 0.01) region.probability = c(0.023, 0.034, 0.107) model <- sstModel(portfolio = p, market.risk = mr, life.risk = lr, health.risk = hr, nonlife.risk = nonLifeRisk(type = "simulations", param = list(simulations = c(1, 2, 3, 4)), currency = "CHF"), nhmr = 0.06, reordering.parameters = list(list.correlation.matrix = list(base=list.correlation.matrix[[1]])), scenario.risk = scenarioRisk("tornado", 0.08, "CHF", -10000), participation.risk = participationRisk(volatility = 0.5), standalones = list(standalone(name = "std_equityCHF", equity(name = "equityCHF", type = "equity", currency = "CHF")), standalone(name = "std_spreadAAACHF", spread(name = "AAACHF", currency = "CHF", rating = "AAA")), standalone(name = "std_ratekCHF", rate(name = "kYCHF", currency = "CHF", horizon = "k")) )) output <- compute(object = model, nsim = as.integer(100), nested.market.computations = T) p2 <- portfolio(market.items = list.marketItems, participation.item = participation(currency = "CHF", value = 3000), health.item = health(name = c("storno", "invalidity"), currency = c("CHF", "CHF"), sensitivity = c(230, 500)), base.currency = "CHF", portfolio.parameters = valid.param) model2 <- sstModel(portfolio = p2, market.risk = mr, health.risk = hr, nonlife.risk = nonLifeRisk(type = "simulations", param = list(simulations = c(1, 2, 3, 4)), currency = "CHF"), nhmr = 0.06, reordering.parameters = list(list.correlation.matrix = list(base=list.correlation.matrix[[1]])), scenario.risk = scenarioRisk("tornado", 0.08, "CHF", -10000), participation.risk = participationRisk(volatility = 0.5), standalones = list(standalone(name = "std_equityCHF", equity(name = "equityCHF", type = "equity", currency = "CHF")), standalone(name = "std_spreadAAACHF", spread(name = "AAACHF", currency = "CHF", rating = "AAA")), standalone(name = "std_ratekCHF", rate(name = "kYCHF", currency = "CHF", horizon = "k")) )) output2 <- compute(object = model2, nsim = as.integer(100)) p3 <- portfolio(market.items = list.marketItems, participation.item = participation(currency = "CHF", value = 3000), life.item = life(name = c("storno", "invalidity"), currency = c("CHF", "CHF"), sensitivity = c(100, 2000)), base.currency = "CHF", portfolio.parameters = valid.param) model3 <- sstModel(portfolio = p3, market.risk = mr, life.risk = lr, nonlife.risk = nonLifeRisk(type = "simulations", param = list(simulations = c(1, 2, 3, 4)), currency = "CHF"), nhmr = 0.06, reordering.parameters = list(list.correlation.matrix = list(base=list.correlation.matrix[[1]])), scenario.risk = scenarioRisk("tornado", 0.08, "CHF", -10000), participation.risk = participationRisk(volatility = 0.5), standalones = list(standalone(name = "std_equityCHF", equity(name = "equityCHF", type = "equity", currency = "CHF")), standalone(name = "std_spreadAAACHF", spread(name = "AAACHF", currency = "CHF", rating = "AAA")), standalone(name = "std_ratekCHF", rate(name = "kYCHF", currency = "CHF", horizon = "k")) )) output3 <- compute(object = model3, nsim = as.integer(100)) p4 <- portfolio(market.items = list.marketItems, life.item = life(name = c("storno", "invalidity"), currency = c("CHF", "CHF"), sensitivity = c(100, 2000)), health.item = health(name = c("storno", "invalidity"), currency = c("CHF", "CHF"), sensitivity = c(230, 500)), base.currency = "CHF", portfolio.parameters = valid.param) model4 <- sstModel(portfolio = p4, market.risk = mr, life.risk = lr, health.risk = hr, nonlife.risk = nonLifeRisk(type = "simulations", param = list(simulations = c(1, 2, 3, 4)), currency = "CHF"), nhmr = 0.06, reordering.parameters = list(list.correlation.matrix = list(base=list.correlation.matrix[[1]])), scenario.risk = scenarioRisk("tornado", 0.08, "CHF", -10000), standalones = list(standalone(name = "std_equityCHF", equity(name = "equityCHF", type = "equity", currency = "CHF")), standalone(name = "std_spreadAAACHF", spread(name = "AAACHF", currency = "CHF", rating = "AAA")), standalone(name = "std_ratekCHF", rate(name = "kYCHF", currency = "CHF", horizon = "k")) )) output4 <- compute(object = model4, nsim = as.integer(100)) p5 <- portfolio(market.items = list(list.marketItems[[1]]), participation.item = participation(currency = "CHF", value = 3000), life.item = life(name = c("storno", "invalidity"), currency = c("CHF", "CHF"), sensitivity = c(100, 2000)), health.item = health(name = c("storno", "invalidity"), currency = c("CHF", "CHF"), sensitivity = c(230, 500)), base.currency = "CHF", portfolio.parameters = valid.param) model5 <- sstModel(portfolio = p5, market.risk = mr, life.risk = lr, health.risk = hr, participation.risk = participationRisk(volatility = 0.5), nonlife.risk = nonLifeRisk(type = "simulations", param = list(simulations = c(1, 2, 3, 4)), currency = "CHF"), nhmr = 0.06, reordering.parameters = list(list.correlation.matrix = list(base=list.correlation.matrix[[1]])), scenario.risk = scenarioRisk("tornado", 0.08, "CHF", -10000), standalones = list(standalone(name = "std_equityCHF", equity(name = "equityCHF", type = "equity", currency = "CHF")), standalone(name = "std_spreadAAACHF", spread(name = "AAACHF", currency = "CHF", rating = "AAA")), standalone(name = "std_ratekCHF", rate(name = "kYCHF", currency = "CHF", horizon = "k")) )) output5 <- compute(object = model5, nsim = as.integer(100)) p6 <- portfolio(market.items = list(list.marketItems[[1]]), life.item = life(name = c("storno", "invalidity"), currency = c("CHF", "CHF"), sensitivity = c(100, 2000)), health.item = health(name = c("storno", "invalidity"), currency = c("CHF", "CHF"), sensitivity = c(230, 500)), base.currency = "CHF", portfolio.parameters = valid.param) model6 <- sstModel(portfolio = p6, market.risk = mr, life.risk = lr, health.risk = hr, nonlife.risk = nonLifeRisk(type = "simulations", param = list(simulations = c(1, 2, 3, 4)), currency = "CHF"), nhmr = 0.06, reordering.parameters = list(list.correlation.matrix = list(base=list.correlation.matrix[[1]])), scenario.risk = scenarioRisk("tornado", 0.08, "CHF", -10000), standalones = list(standalone(name = "std_equityCHF", equity(name = "equityCHF", type = "equity", currency = "CHF")), standalone(name = "std_spreadAAACHF", spread(name = "AAACHF", currency = "CHF", rating = "AAA")), standalone(name = "std_ratekCHF", rate(name = "kYCHF", currency = "CHF", horizon = "k")) )) output6 <- compute(object = model6, nsim = as.integer(100))
itemDiscrimination = function(attributeName, itemVariable, attributeProfile, profileProb){ focalAttribute = which(colnames(attributeProfile) == attributeName) itemKLI = itemVariable$KLI(attributeProfile = attributeProfile) possibleUprofiles1 = which(attributeProfile[,focalAttribute] == 1) possibleVprofiles1 = which(attributeProfile[,focalAttribute] == 0) omegaK1 = NULL attributeList = 1:ncol(attributeProfile) mAttributeList = attributeList[which(attributeList != focalAttribute)] D_A1 = 0 D_B1 = 0 probSum1 = 0 for (u in 1:length(possibleUprofiles1)){ for (v in 1:length(possibleVprofiles1)){ keep = TRUE for (m in 1:length(mAttributeList)){ if (attributeProfile[possibleUprofiles1[u], mAttributeList[m]] != attributeProfile[possibleVprofiles1[v],mAttributeList[m]]) { keep=FALSE break } } if (keep){ omegaK1 = rbind(omegaK1, matrix(data = c(possibleUprofiles1[u], possibleVprofiles1[v]), nrow = 1)) D_A1 = D_A1 + itemKLI[possibleUprofiles1[u], possibleVprofiles1[v]] D_B1 = D_B1 + profileProb[possibleUprofiles1[u]]*itemKLI[possibleUprofiles1[u], possibleVprofiles1[v]] probSum1 = probSum1 + profileProb[possibleUprofiles1[u]] } } } D_A1 = D_A1/nrow(omegaK1) D_B1 = D_B1/probSum1 possibleUprofiles0 = which(attributeProfile[,focalAttribute] == 0) possibleVprofiles0 = which(attributeProfile[,focalAttribute] == 1) omegaK0 = NULL D_A0 = 0 D_B0 = 0 probSum0 = 0 for (u in 1:length(possibleUprofiles0)){ for (v in 1:length(possibleVprofiles0)){ keep = TRUE for (m in 1:length(mAttributeList)){ if (attributeProfile[possibleUprofiles0[u], mAttributeList[m]] != attributeProfile[possibleVprofiles0[v],mAttributeList[m]]) { keep=FALSE break } } if (keep){ omegaK0 = rbind(omegaK0, matrix(data = c(possibleUprofiles0[u], possibleVprofiles0[v]), nrow = 1)) D_A0 = D_A0 + itemKLI[possibleUprofiles0[u], possibleVprofiles0[v]] D_B0 = D_B0 + profileProb[possibleUprofiles0[u]]*itemKLI[possibleUprofiles0[u], possibleVprofiles0[v]] probSum0 = probSum0 + profileProb[possibleUprofiles0[u]] } } } D_A0 = D_A0/nrow(omegaK0) D_B0 = D_B0/probSum1 D_A = D_A0+D_A1 D_B = D_B0+D_B1 return(list(D_A = D_A, D_B = D_B, D_A1 = D_A1, D_A0 = D_A0, D_B1 = D_B1, D_B0 = D_B0)) }
density.bma <- function (x, reg = NULL, addons = "lemsz", std.coefs = FALSE, n = 300, plot = TRUE, hnbsteps = 30, addons.lwd = 1.5, ...) { dtcm = function(x, df, ncp, varp) { sqvarp = sqrt(varp) dt((x - ncp)/sqvarp, df = df)/sqvarp } dsgivenykernel <- function(sf, kpa, N, z) { (kpa - 2)/2 * (1 - sf)^((kpa - 4)/2) * (1 - sf * z)^(-(N - 1)/2) } dotargs = match.call(expand.dots = FALSE)$... bmao = x if (!is.bma(bmao)) stop("Argument bmao needs to be a bma object") if (hnbsteps%%2) stop("Argument nbsteps needs to be an even integer") nbsteps = max(hnbsteps, 2) n = max(ceiling(n), 1) N = bmao$info$N K = bmao$info$K if (is.null(reg)) reg = 1:K nameix = 1:K names(nameix) = bmao$reg.names reg = nameix[reg] ishyper = (bmao$gprior$gtype == "hyper") tm = bmao$topmod bools = (tm$bool_binary()) betas = tm$betas() betas2 = tm$betas2() if (std.coefs) { sddata = apply(as.matrix(bmao$X.data), 2, stats::sd) betas = diag(sddata[-1]) %*% betas/sddata[1] betas2 = diag(sddata[-1]^2) %*% betas2/sddata[1]^2 } sigmadiag = (betas2 - betas^2) * (N - 3)/(N - 1) pmps = pmp.bma(bmao$topmod, oldstyle = TRUE)[, 1] pips = c(tcrossprod(bools, t(pmps))) Eb1 = c(tcrossprod(betas, t(pmps)))/pips Ebsd = sqrt(c(tcrossprod(betas2, t(pmps)))/pips - Eb1^2) Ebsd[is.nan(Ebsd)] = 0 Eb1[is.nan(Eb1)] = 0 Eball = cbind(Eb1, Ebsd) if ((any(grep("E", addons, ignore.case = FALSE))) | (any(grep("S", addons, ignore.case = FALSE)))) { Eb1.mcmc = bmao$info$b1mo/bmao$info$inccount Ebsd.mcmc = sqrt(bmao$info$b2mo/bmao$info$inccount - Eb1.mcmc^2) if (std.coefs) { sddata = apply(as.matrix(bmao$X.data), 2, stats::sd) Eb1.mcmc = Eb1.mcmc * sddata[-1]/sddata[1] Ebsd.mcmc = Ebsd.mcmc * sddata[-1]/sddata[1] } } if (ishyper) { yXdata = as.matrix(bmao$X.data) yXdata = yXdata - matrix(colMeans(yXdata), N, K + 1, byrow = TRUE) if (std.coefs) yXdata = yXdata %*% diag(1/sddata) yty = c(crossprod(yXdata[, 1])) positions = lapply(lapply(as.list(as.data.frame(bools)), as.logical), which) olsmodels = lapply(lapply(positions, .ols.terms2, yty = yty, N = N, K = K, XtX.big = crossprod(yXdata[, -1]), Xty.big = c(crossprod(yXdata[, -1], yXdata[, 1]))), function(x) x$full.results()) f21a = bmao$gprior.info$hyper.parameter } plotndens <- function(ix, doplot = FALSE) { sss = function(lbound, uboundp1, nbsteps) { s.seq = seq(lbound, uboundp1, (uboundp1 - lbound)/nbsteps)[-nbsteps] tmat = sapply(as.list(s.seq), function(ss) { dtcm(seqs, N - 1, ss * bhati, invdiagi * ss * (1 - ss * z)/(N - 1) * yty) }) smat = sapply(as.list(s.seq), dsgivenykernel, kpa = k + f21a, N = N, z = z) if (any(is.infinite(smat))) smat[is.infinite(smat)] = 0 intconst = (4 * sum(smat[c(FALSE, TRUE)]) + 2 * sum(smat[c(TRUE, FALSE)]) - 3 * smat[nbsteps] - smat[1]) * (s.seq[nbsteps] - s.seq[1])/nbsteps/3 return(list(dv = c(4 * tmat[, c(FALSE, TRUE)] %*% smat[c(FALSE, TRUE)] + 2 * tmat[, c(TRUE, FALSE)] %*% smat[c(TRUE, FALSE)] - 3 * tmat[, nbsteps] * smat[nbsteps] - tmat[, 1] * smat[1]) * (s.seq[nbsteps] - s.seq[1])/nbsteps/3, ic = intconst)) } if (pips[ix] == 0) { reslist = list(x = numeric(n), y = numeric(n), n = n, call = sys.call(), data.name = names(nameix)[ix], has.na = FALSE) class(reslist) = c("density", "coef.density") return(reslist) } lbound = min(betas[ix, as.logical(bools[ix, ])]) - 3 * Eball[ix, 2] ubound = max(betas[ix, as.logical(bools[ix, ])]) + 3 * Eball[ix, 2] seqs = seq(lbound, ubound, (ubound - lbound)/(n - 1)) densvec = numeric(length(seqs)) for (m in 1:length(pmps)) { if (bools[ix, m]) { if (ishyper) { ixadj = sum(bools[1:ix, m]) bhati = olsmodels[[m]]$bhat[[ixadj]] invdiagi = olsmodels[[m]]$diag.inverse[[ixadj]] k = sum(bools[, m]) Esf = betas[ix, m]/bhati z = 1 - olsmodels[[m]]$ymy/yty midpoint = 1 - (1 - Esf) * 4 if (midpoint < 0.5) { dvl = sss(1e-04, 0.9999999, nbsteps * 2) addvec = dvl$dv/dvl$ic } else { dvl1 = sss(1e-04, midpoint, nbsteps) dvl2 = sss(midpoint, 1, nbsteps) addvec = (dvl1$dv + dvl2$dv)/(dvl1$ic + dvl2$ic) } } else { addvec = dtcm(seqs, N - 1, betas[ix, m], sigmadiag[ix, m]) } densvec = densvec + pmps[m] * addvec } } reslist = list(x = seqs, y = densvec, bw = NULL, n = n, call = sys.call(), data.name = names(nameix)[ix], has.na = FALSE) class(reslist) = "density" if (!doplot) { return(reslist) } main_default = paste("Marginal Density:", names(nameix)[ix], "(PIP", round(c(crossprod(pmps, bools[ix, ])) * 100, 2), "%)") if (any(grep("p", addons, ignore.case = TRUE))) { decr = 0.12 parplt = par()$plt parplt_temp = parplt parplt_temp[4] = (1 - decr) * parplt[4] + decr * parplt[3] par(plt = parplt_temp) main_temp = main_default main_default = NULL } dotargs = .adjustdots(dotargs, type = "l", col = "steelblue4", main = main_default, xlab = if (std.coefs) "Standardized Coefficient" else "Coefficient", ylab = "Density") eval(as.call(c(list(as.name("plot"), x = as.name("seqs"), y = as.name("densvec")), as.list(dotargs)))) leg.col = numeric(0) leg.lty = numeric(0) leg.legend = character(0) if (any(grep("g", addons, ignore.case = TRUE))) { grid() } if (any(grep("b", addons, ignore.case = TRUE))) { for (m in 1:length(pmps)) { Ebm = betas[ix, m] if (as.logical(Ebm)) { Ebheight = min(densvec[max(sum(seqs < Ebm), 1)], densvec[sum(seqs < Ebm) + 1]) lines(x = rep(Ebm, 2), y = c(0, Ebheight), col = 8) } } leg.col = c(leg.col, 8) leg.lty = c(leg.lty, 1) leg.legend = c(leg.legend, "EV Models") } if (any(grep("e", addons, ignore.case = FALSE))) { abline(v = Eball[ix, 1], col = 2, lwd = addons.lwd) leg.col = c(leg.col, 2) leg.lty = c(leg.lty, 1) leg.legend = c(leg.legend, "Cond. EV") } if (any(grep("s", addons, ignore.case = FALSE))) { abline(v = Eball[ix, 1] - 2 * Eball[ix, 2], col = 2, lty = 2, lwd = addons.lwd) abline(v = Eball[ix, 1] + 2 * Eball[ix, 2], col = 2, lty = 2, lwd = addons.lwd) leg.col = c(leg.col, 2) leg.lty = c(leg.lty, 2) leg.legend = c(leg.legend, "2x Cond. SD") } if (any(grep("m", addons, ignore.case = TRUE))) { median_index = sum(cumsum(densvec) < sum(densvec)/2) abline(v = (seqs[median_index] + seqs[median_index + 1])/2, col = 3, lwd = addons.lwd) leg.col = c(leg.col, 3) leg.lty = c(leg.lty, 1) leg.legend = c(leg.legend, "Median") } if (any(grep("z", addons, ignore.case = TRUE))) { abline(h = 0, col = "gray", lwd = addons.lwd) } if (any(grep("E", addons, ignore.case = FALSE))) { abline(v = Eb1.mcmc[ix], col = 4, lwd = addons.lwd) leg.col = c(leg.col, 4) leg.lty = c(leg.lty, 1) leg.legend = c(leg.legend, "Cond. EV (MCMC)") } if (any(grep("S", addons, ignore.case = FALSE))) { abline(v = Eb1.mcmc[ix] - 2 * Ebsd.mcmc[ix], col = 4, lty = 2, lwd = addons.lwd) abline(v = Eb1.mcmc[ix] + 2 * Ebsd.mcmc[ix], col = 4, lty = 2, lwd = addons.lwd) leg.col = c(leg.col, 4) leg.lty = c(leg.lty, 2) leg.legend = c(leg.legend, "2x SD (MCMC)") } if (any(grep("l", addons, ignore.case = TRUE)) & (length(leg.col) > 0)) { leg.pos = "topright" if (Eball[ix, 1] > seqs[floor(n/2)]) leg.pos = "topleft" legend(x = leg.pos, lty = leg.lty, col = leg.col, legend = leg.legend, box.lwd = 0, bty = "n", lwd = addons.lwd) } if (any(grep("p", addons, ignore.case = TRUE))) { pusr = par()$usr rect(pusr[1], pusr[4] * (1 + decr * 0.2), pusr[2], pusr[4] * (1 + decr), xpd = TRUE, col = 8) rect(pusr[1], pusr[4] * (1 + decr * 0.2), pips[ix] * pusr[2] + (1 - pips[ix]) * pusr[1], pusr[4] * (1 + decr), xpd = TRUE, col = 9) mtext("PIP:", side = 2, las = 2, line = 1, at = pusr[4] * (1 + decr * 0.6)) par(plt = parplt) title(main_temp) } return(reslist) } densres = list() oldask = par()$ask plots = 0 for (vbl in 1:length(reg)) { doplot = (if (as.logical(pips[reg[vbl]])) plot else FALSE) plots = plots + doplot if (plots == 2) { par(ask = TRUE) } densres[[nameix[vbl]]] = plotndens(reg[vbl], doplot) densres[[nameix[vbl]]]$call = sys.call() } par(ask = oldask) if (length(densres) == 1) densres = densres[[1]] else class(densres) = c("coef.density", class(densres)) if (!plot) return(densres) if (plot & (plots == 0)) { warning("No plot produced as PIPs of provided variables are zero under 'exact' estimation.") } return(invisible(densres)) }
setMethodS3("findNeutralCopyNumberState", "default", function(C, isAI, weights=NULL, ..., minDensity=1e-10, flavor=c("firstPeak", "maxPeak"), verbose=FALSE) { C <- Arguments$getNumerics(C) nbrOfLoci <- length(C) length2 <- rep(nbrOfLoci, times=2) isAI <- Arguments$getLogicals(isAI, length=length2, disallow=NULL) if (!is.null(weights)) { weights <- Arguments$getNumerics(weights, range=c(0, Inf), length=length2) } minDensity <- Arguments$getDouble(minDensity) flavor <- match.arg(flavor) verbose <- Arguments$getVerbose(verbose) if (verbose) { pushState(verbose) on.exit(popState(verbose)) } verbose && enter(verbose, "Identifying segments that are copy neutral states") isAB <- !isAI isNA <- (is.na(isAB) | is.na(C)) isNeutral <- isAB idxs <- which(isAB) n <- length(idxs) verbose && cat(verbose, "Number of segments in allelic balance: ", n) if (n == 0) { verbose && exit(verbose) return(isNeutral) } else if (n == 1) { verbose && exit(verbose) return(isNeutral) } else if (n < 5) { warning("The calling of regions in a copy-neutral state is uncertain, because there are less than five (5) regions in allelic balance: ", n) } if (!is.null(weights)) { weights <- weights[idxs] weights <- weights / sum(weights) } y <- C[idxs] idxs <- NULL if (verbose) { cat(verbose, "Data points:") df <- data.frame(C=y, weights=weights) print(verbose, head(df)) str(verbose, df) df <- NULL } fit <- findPeaksAndValleys(y, weights=weights, ...) verbose && cat(verbose, "Fit:") verbose && cat(verbose, "Fit filtered by 'minDensity':") ok <- (fit[,"density"] > minDensity) verbose && print(verbose, fit[ok,]) isPeak <- (fit[,"type"] == "peak") & ok idxs <- which(isPeak) .stop_if_not(length(idxs) >= 1) if (flavor == "firstPeak") { idx <- idxs[1] } else if (flavor == "maxPeak") { idx <- idxs[which.max(fit[idxs,"density"])] } neutralC <- fit[idx,"x"] verbose && cat(verbose, "Neutral copy number:") verbose && cat(verbose, "Mode at: ", neutralC) verbose && cat(verbose, "Mode ampliture: ", fit[idx,"density"]) if (idx+1 <= nrow(fit)) { nextValleyC <- fit[idx+1, "x"] } else { nextValleyC <- Inf } verbose && cat(verbose, "Upper range at: ", nextValleyC) isNeutral <- isNeutral & (C < nextValleyC) isNeutral[isNA] <- NA verbose && cat(verbose, "Neutral region calls:") verbose && summary(verbose, isNeutral) verbose && exit(verbose) isNeutral })
Titanic <- array(c( 0, 0, 35, 0, 0, 0, 17, 0, 118, 154, 387, 670, 4, 13, 89, 3, 5, 11, 13, 0, 1, 13, 14, 0, 57, 14, 75, 192, 140, 80, 76, 20), dim = c(4, 2, 2, 2), dimnames = list(Class = c("1st", "2nd", "3rd", "Crew"), Sex = c("Male", "Female"), Age = c("Child", "Adult"), Survived = c("No", "Yes"))) class(Titanic) <- "table"
UnoC <- function(Surv.rsp, Surv.rsp.new, lpnew, time = NULL) { if(is.null(time)){ tau <- max(Surv.rsp.new[,1]) }else{ tau <- time } time <- Surv.rsp[,1] event <- 1-Surv.rsp[,2] time.new <- Surv.rsp.new[,1] event.new <- Surv.rsp.new[,2] n <- length(time) n.new <- length(time.new) n_lp <- length(lpnew) n_tau <- length(tau) if(n.new != n_lp) stop(" 'Surv.rsp' and 'linear predictors' must have the same length!\n") if(n_tau > 1){ UnoC <- vector("numeric",length=n_tau) }else{ UnoC <- 0 } ans <- .C("UnoC", as.numeric(time), as.numeric(event), as.integer(n), as.numeric(time.new), as.numeric(event.new), as.integer(n.new), as.numeric(lpnew), as.numeric(tau), as.integer(n_tau), as.numeric(UnoC), PACKAGE="survAUC") ans[[10]] }
CompPVs <- function(T){ tmp <- sort(T) ind <- order(T) m <- length(T) pv <- rep(1, length(T)) i <-1 for(j in seq_len(m-1)) { if (tmp[j] < tmp[j + 1]) { pv[ind[i:j]] <- j / m i <- j + 1 } } pv }
library(tiledb) array_name <- tempfile() create_array <- function() { if (tiledb_object_type(array_name) == "ARRAY") { message("Array already exists.") return(invisible(NULL)) } dom <- tiledb_domain(dims = c(tiledb_dim("rows", c(1L, 4L), 4L, "INT32"), tiledb_dim("cols", c(1L, 4L), 4L, "INT32"))) attr <- tiledb_attr("a", type = "FLOAT64") tiledb:::libtiledb_attribute_set_cell_val_num(attr@ptr, NA) ctx <- tiledb_ctx() schptr <- tiledb:::libtiledb_array_schema_create(ctx@ptr, "DENSE") tiledb:::libtiledb_array_schema_set_domain(schptr, dom@ptr) tiledb:::libtiledb_array_schema_set_cell_order(schptr, "ROW_MAJOR") tiledb:::libtiledb_array_schema_set_tile_order(schptr, "ROW_MAJOR") tiledb:::libtiledb_array_schema_add_attribute(schptr, attr@ptr) tiledb:::libtiledb_array_create(array_name, schptr) invisible(NULL) } write_array <- function() { data <- c(1.1, 1.1, 2.2, 2.2, 3.3, 4.4, 5.5, 6.6, 6.6, 7.7, 7.7, 8.8, 8.8, 8.8, 9.9, 9.0, 10.0, 11.1, 12.2, 12.2, 13.3, 14.4, 14.4, 14.4, 15.5, 16.6) offsets <- c(0L, 2L, 4L, 5L, 6L, 7L, 9L, 11L, 14L, 16L, 17L, 18L, 20L, 21L, 24L, 25L) offsets <- offsets * 8 ctx <- tiledb_ctx() arrptr <- tiledb:::libtiledb_array_open(ctx@ptr, array_name, "WRITE") qryptr <- tiledb:::libtiledb_query(ctx@ptr, arrptr, "WRITE") qryptr <- tiledb:::libtiledb_query_set_layout(qryptr, "ROW_MAJOR") bufptr <- tiledb:::libtiledb_query_buffer_var_vec_create(offsets, data) qryptr <- tiledb:::libtiledb_query_set_buffer_var_vec(qryptr, "a", bufptr) qryptr <- tiledb:::libtiledb_query_submit(qryptr) tiledb:::libtiledb_array_close(arrptr) invisible(NULL) } read_array <- function(txt="", subarr=NULL) { cat("\nReading", txt, "\n") ctx <- tiledb_ctx() arrptr <- tiledb:::libtiledb_array_open(ctx@ptr, array_name, "READ") if (is.null(subarr)) { schptr <- tiledb:::libtiledb_array_get_schema(arrptr) domptr <- tiledb:::libtiledb_array_schema_get_domain(schptr) lst <- tiledb:::libtiledb_domain_get_dimensions(domptr) subarr <- c(tiledb:::libtiledb_dim_get_domain(lst[[1]]), tiledb:::libtiledb_dim_get_domain(lst[[2]])) } bufptr <- tiledb:::libtiledb_query_buffer_var_vec_alloc(arrptr, subarr, "a") qryptr <- tiledb:::libtiledb_query(ctx@ptr, arrptr, "READ") qryptr <- tiledb:::libtiledb_query_set_subarray(qryptr, subarr) qryptr <- tiledb:::libtiledb_query_set_layout(qryptr, "ROW_MAJOR") qryptr <- tiledb:::libtiledb_query_set_buffer_var_vec(qryptr, "a", bufptr) qryptr <- tiledb:::libtiledb_query_submit(qryptr) tiledb:::libtiledb_array_close(arrptr) rl <- tiledb:::libtiledb_query_get_buffer_var_vec(qryptr, "a", bufptr) invisible(rl) } write_subarray <- function() { data <- c(11.1, 11.1, 22.2, 22.2, 33.3, 44.4) offsets <- c(0L, 2L, 4L, 5L) offsets <- offsets * 4 subarr <- c(2L,3L, 2L,3L) ctx <- tiledb_ctx() arrptr <- tiledb:::libtiledb_array_open(ctx@ptr, array_name, "WRITE") qryptr <- tiledb:::libtiledb_query(ctx@ptr, arrptr, "WRITE") qryptr <- tiledb:::libtiledb_query_set_subarray(qryptr, subarr) qryptr <- tiledb:::libtiledb_query_set_layout(qryptr, "ROW_MAJOR") bufptr <- tiledb:::libtiledb_query_buffer_var_vec_create(offsets, data) qryptr <- tiledb:::libtiledb_query_set_buffer_var_vec(qryptr, "a", bufptr) qryptr <- tiledb:::libtiledb_query_submit(qryptr) tiledb:::libtiledb_array_close(arrptr) invisible(NULL) } create_array() write_array() print(read_array("original")) write_subarray() print(read_array("after subarray")) print(read_array("after subarray, subset", c(2L,3L, 2L,3L))) cat("Done.\n")
write.simmap<-function(tree,file=NULL,append=FALSE,map.order=NULL,quiet=FALSE,format="phylip",version=1.0){ if(!(inherits(tree,"simmap")||inherits(tree,"multiSimmap"))) stop("tree should be an object of class \"simmap\" or \"multiSimmap\".") if(inherits(tree,"multiPhylo")) N<-length(tree) else { N<-1 tree<-list(tree) } n<-sapply(tree,Ntip) if(format=="nexus"){ trans<-unique(sort(sapply(tree,function(x) x$tip.label))) nn<-length(trans) write(" write(paste("[R-package PHYTOOLS, ",date(),"]\n",sep=""),file,append=TRUE) write("BEGIN TAXA;",file,append=TRUE) write(paste("\tDIMENSIONS NTAX = ",nn,";",sep=""),file,append=TRUE) write("\tTAXLABELS",file,append=TRUE) for(i in 1:length(trans)) write(paste("\t\t",trans[i],sep=""),file,append=TRUE) write("\t;",file,append=TRUE) write("END;",file,append=TRUE) if(version==1.0) write("BEGIN SMPTREES;\n\tTRANSLATE",file,append=TRUE) else write("BEGIN TREES;\n\tTRANSLATE",file,append=TRUE) for(i in 1:(nn-1)) write(paste("\t\t",i,"\t",trans[i],",",sep=""),file, append=TRUE) write(paste("\t\t",i+1,"\t",trans[i+1],sep=""),file,append=TRUE) write("\t;",file,append=TRUE) for(i in 1:N){ tree[[i]]$tip.label<-sapply(tree[[i]]$tip.label,function(x) which(x==trans)) tree.string<-if(version==1.0) write.v1(tree[[i]],map.order=map.order, quiet=quiet) else write.v2(tree[[i]],map.order=map.order, quiet=quiet) write(paste("\tTREE * UNTITLED = [&R] ",tree.string,sep=""),file, append=TRUE) } write("END;",file,append=TRUE) } else { for(i in 1:N){ if(version==1.0) write(write.v1(tree[[i]],map.order=map.order,quiet=quiet),file,append=append) else write(write.v2(tree[[i]],map.order=map.order,quiet=quiet),file,append=append) } } } write.v1<-function(tree,map.order,quiet){ if(is.null(map.order)){ if(!is.null(attr(tree,"map.order"))) map.order<-attr(tree,"map.order") else { if(!quiet) message("map order should be specified in function call or by tree attribute \"map.order\".\nAssuming right-to-left order.") map.order<-"R" } } map.order<-toupper(unlist(strsplit(map.order,NULL))[1]) if(map.order!="R"&&map.order!="L"){ if(!quiet) message("do not recognize map order. Assuming right-to-left order.") map.order<-"R" } tree<-reorderSimmap(tree,"cladewise") n<-Ntip(tree) string<-vector() string[1]<-"(" j<-2 for(i in 1:nrow(tree$edge)){ if(tree$edge[i,2]<=n){ string[j]<-tree$tip.label[tree$edge[i,2]] j<-j+1 string[j]<-":{" j<-j+1 if(map.order=="L"){ for(l in 1:length(tree$maps[[i]])){ string[j]<-paste(c(names(tree$maps[[i]])[l],",", round(tree$maps[[i]][l],8)),collapse="") string[j+1]<-":" j<-j+2 } } else { for(l in length(tree$maps[[i]]):1){ string[j]<-paste(c(names(tree$maps[[i]])[l],",", round(tree$maps[[i]][l],8)),collapse="") string[j+1]<-":" j<-j+2 } } string[j-1]<-"}" v<-which(tree$edge[,1]==tree$edge[i,1]) k<-i while(length(v)>0&&k==v[length(v)]){ string[j]<-")" j<-j+1 w<-which(tree$edge[,2]==tree$edge[k,1]) if(length(w)>0){ string[j]<-":{" j<-j+1 if(map.order=="L"){ for(l in 1:length(tree$maps[[w]])){ string[j]<-paste(c(names(tree$maps[[w]])[l],",", round(tree$maps[[w]][l],8)),collapse="") string[j+1]<-":" j<-j+2 } } else { for(l in length(tree$maps[[w]]):1){ string[j]<-paste(c(names(tree$maps[[w]])[l],",", round(tree$maps[[w]][l],8)),collapse="") string[j+1]<-":" j<-j+2 } } string[j-1]<-"}" } v<-which(tree$edge[,1]==tree$edge[w,1]) k<-w } string[j]<-"," j<-j+1 } else if(tree$edge[i,2]>=n){ string[j]<-"(" j<-j+1 } } string<-c(string[1:(length(string)-1)],";") string<-paste(string,collapse="") string } write.v2<-function(tree,map.order,quiet){ if(is.null(map.order)){ if(!is.null(attr(tree,"map.order"))) map.order<-attr(tree,"map.order") else { if(!quiet) message("map order should be specified in function call or by tree attribute \"map.order\".\nAssuming right-to-left order.") map.order<-"R" } } map.order<-toupper(unlist(strsplit(map.order,NULL))[1]) if(map.order!="R"&&map.order!="L"){ if(!quiet) message("do not recognize map order. Assuming right-to-left order.") map.order<-"R" } tree<-reorderSimmap(tree,"cladewise") n<-Ntip(tree) string<-vector() string[1]<-"(" j<-2 for(i in 1:nrow(tree$edge)){ if(tree$edge[i,2]<=n){ string[j]<-tree$tip.label[tree$edge[i,2]] j<-j+1 string[j]<-":[&map={" j<-j+1 nn<-length(tree$maps[[i]]) if(nn==1){ string[j]<-names(tree$maps[[i]])[1] j<-j+1 } else { if(map.order=="L"){ for(l in 1:(nn-1)){ string[j]<-paste(c(names(tree$maps[[i]])[l],",", round(tree$maps[[i]][l],8)),collapse="") string[j+1]<-"," j<-j+2 } string[j]<-names(tree$maps[[i]])[nn] j<-j+1 } else { for(l in nn:2){ string[j]<-paste(c(names(tree$maps[[i]])[l],",", round(tree$maps[[i]][l],8)),collapse="") string[j+1]<-"," j<-j+2 } string[j]<-names(tree$maps[[i]])[1] j<-j+1 } } string[j]<-paste(c("}]",round(tree$edge.length[i],8)),collapse="") j<-j+1 v<-which(tree$edge[,1]==tree$edge[i,1]) k<-i while(length(v)>0&&k==v[length(v)]){ string[j]<-")" j<-j+1 w<-which(tree$edge[,2]==tree$edge[k,1]) if(length(w)>0){ nn<-length(tree$maps[[w]]) string[j]<-":[&map={" j<-j+1 if(nn==1){ string[j]<-names(tree$maps[[w]])[1] j<-j+1 } else { if(map.order=="L"){ for(l in 1:(nn-1)){ string[j]<-paste(c(names(tree$maps[[w]])[l],",", round(tree$maps[[w]][l],8)),collapse="") string[j+1]<-"," j<-j+2 } string[j]<-names(tree$maps[[w]])[nn] j<-j+1 } else { for(l in nn:2){ string[j]<-paste(c(names(tree$maps[[w]])[l],",", round(tree$maps[[w]][l],8)),collapse="") string[j+1]<-"," j<-j+2 } string[j]<-names(tree$maps[[w]])[1] j<-j+1 } } string[j]<-paste(c("}]",round(tree$edge.length[w],8)),collapse="") j<-j+1 } v<-which(tree$edge[,1]==tree$edge[w,1]) k<-w } string[j]<-"," j<-j+1 } else if(tree$edge[i,2]>=n){ string[j]<-"(" j<-j+1 } } string<-c(string[1:(length(string)-1)],";") string<-paste(string,collapse="") string }
test_that("fredr_series()", { skip_if_no_key() series <- fredr_series(series_id = "GNPCA") expect_s3_class(series, c("tbl_df", "tbl", "data.frame")) expect_true(ncol(series) == 15) expect_true(nrow(series) == 1) }) test_that("input is validated", { expect_error(fredr_series()) })
context("make_log") testthat::test_that( "Default make_log works", testthat::expect_true( grepl("dummy", make_log("dummy")) ) ) testthat::test_that( "make_Log works with endNewLine", testthat::expect_true( grepl("\n$", make_log("dummy", endNewLine = TRUE)) ) ) testthat::test_that( "make_Log works with newLine", testthat::expect_true( grepl("^\n", make_log("dummy", newLine = TRUE)) ) ) testthat::test_that( "emit_log is silent when it should be", testthat::expect_equal( capture.output( emit_log("test", lvl = 30, trh = 40), type = "message" ), character(0) ) ) testthat::test_that( "emit_log logs when it should", testthat::expect_message( emit_log("test", lvl = 30, trh = 0), "test" ) ) testthat::test_that( "log_i works", { optVal <- getOption("nhlapi_log_threshold") options(nhlapi_log_threshold = 0L) expect_message( log_i("test"), "test" ) options(nhlapi_log_threshold = optVal) } )
TradePlot <- function(MSEobj, ..., Lims=c(0.2, 0.2, 0.8, 0.8), Title=NULL, Labels=NULL, Satisficed=FALSE, Show='both', point.size=2, lab.size=4, axis.title.size=12, axis.text.size=10, legend=TRUE, legend.title.size=12, position = c("right", "bottom"), cols=NULL, fill="gray80", alpha=0.4, PMlist=NULL, Refs=NULL, Yrs=NULL ) { if (class(MSEobj) != 'MSE' & class(MSEobj) !='MMSE') stop("Object must be class `MSE` or class `MMSE`", call.=FALSE) if (class(MSEobj)=='MMSE') legend <- FALSE if (!requireNamespace("ggrepel", quietly = TRUE)) { stop("Package \"ggrepel\" needed for this function to work. Please install it.", call. = FALSE) } if (is.null(PMlist)) { PMlist <- unlist(list(...)) } else { PMlist <- unlist(PMlist) } position <- match.arg(position) if(length(PMlist) == 0) PMlist <- c("STY", "LTY", "P10", "AAVY") if (class(PMlist) != 'character') stop("Must provide names of PM methods") if (length(PMlist)<2) stop("Must provided more than 1 PM method") if (is.null(cols)) { cols <- c(" } if (length(cols) == MSEobj@nMPs) { Col <- 'MP' } else { Col <- 'Class' } nPMs <- length(PMlist) if (nPMs %% 2 != 0) { message("Odd number of PMs. Recycling first PM") PMlist <- c(PMlist, PMlist[1]) nPMs <- length(PMlist) } if (length(Lims) < nPMs) { message("Recycling limits") Lims <- rep(Lims,10)[1:nPMs] } if (length(Lims) > nPMs) { Lims <- Lims[1:nPMs] } runPM <- vector("list", length(PMlist)) for (X in 1:length(PMlist)) { ref <- Refs[[PMlist[X]]] yrs <- Yrs[[PMlist[X]]] if (is.null(ref)) { if (is.null(yrs)) { runPM[[X]] <- eval(call(PMlist[X], MSEobj)) } else { runPM[[X]] <- eval(call(PMlist[X], MSEobj, Yrs=yrs)) } } else { if (is.null(yrs)) { runPM[[X]] <- eval(call(PMlist[X], MSEobj, Ref=ref)) } else { runPM[[X]] <- eval(call(PMlist[X], MSEobj, Ref=ref, Yrs=yrs)) } } } nplots <- nPMs/2 n.col <- ceiling(sqrt(nplots)) n.row <- ceiling(nplots/n.col) m <- matrix(1:(n.col*n.row), ncol=n.col, nrow=n.row, byrow=FALSE) xmin <- xmax <- ymin <- ymax <- x <- y <- Class <- label <- fontface <- NULL plots <- listout <- list() xInd <- seq(1, by=2, length.out=nplots) yInd <- xInd + 1 if (!(is.null(Title))) Title <- rep(Title, nplots)[1:nplots] for (pp in 1:nplots) { yPM <- PMlist[yInd[pp]] yvals <- runPM[[match(yPM, PMlist)]]@Mean ycap <- runPM[[match(yPM, PMlist)]]@Caption yname <- runPM[[match(yPM, PMlist)]]@Name yline <- Lims[match(yPM, PMlist)] xPM <- PMlist[xInd[pp]] xvals <- runPM[[match(xPM, PMlist)]]@Mean xcap <- runPM[[match(xPM, PMlist)]]@Caption xname <- runPM[[match(xPM, PMlist)]]@Name xline <- Lims[match(xPM, PMlist)] xlim <- c(0, max(max(xvals, 1))) ylim <- c(0, max(max(yvals, 1))) xrect <- data.frame(xmin=0, xmax=xline, ymin=0, ymax=max(ylim)) yrect <- data.frame(xmin=0, xmax=max(xlim), ymin=0, ymax=yline) if(legend) { MPType <- MPtype(MSEobj@MPs) Class <- MPType[match(MSEobj@MPs, MPType[,1]),2] } else { Class <- rep('', MSEobj@nMPs) } if (class(MSEobj) =='MSE') { labels <- MSEobj@MPs if (class(Labels) == "list") { repnames <- names(Labels) invalid <- repnames[!repnames %in% labels] if (length(invalid >0)) { warning("Labels: ", paste(invalid, collapse=", "), " are not MPs in MSE") Labels[invalid] <- NULL repnames <- names(Labels) } labels[labels %in% repnames] <- Labels %>% unlist() } } else { labels <- runPM[[1]]@MPs } df <- data.frame(x=xvals, y=yvals, label=labels, Class=Class, pass=xvals>xline & yvals>yline, fontface="plain", xPM=xPM, yPM=yPM) df$fontface <- as.character(df$fontface) df$fontface[!df$pass] <- "italic" df$fontface <- factor(df$fontface) listout[[pp]] <- df if (Satisficed) { xlim <- c(xline, 1) ylim <- c(yline, 1) plots[[pp]] <- ggplot2::ggplot() } else { plots[[pp]] <- ggplot2::ggplot() + ggplot2::geom_rect(data=xrect, ggplot2::aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), fill=fill, alpha=alpha) + ggplot2::geom_rect(data=yrect, ggplot2::aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), fill=fill, alpha=alpha) } if (Col == "Class") { plots[[pp]] <- plots[[pp]] + ggplot2::geom_point(data=df, ggplot2::aes(x, y, shape=Class, color=Class), size=point.size, na.rm=TRUE) if (!is.null(lab.size)) plots[[pp]] <- plots[[pp]] + ggrepel::geom_text_repel(data=df, ggplot2::aes(x, y, color=Class, label=label, fontface = fontface), show.legend=FALSE, size=lab.size, na.rm=TRUE) } else if (Col == "MP") { plots[[pp]] <- plots[[pp]] + ggplot2::geom_point(data=df, ggplot2::aes(x, y, shape=Class, color=label), size=point.size, na.rm=TRUE) if (!is.null(lab.size)) plots[[pp]] <- plots[[pp]] + ggrepel::geom_text_repel(data=df, ggplot2::aes(x, y, color=label, label=label, fontface = fontface), show.legend=FALSE, size=lab.size, na.rm=TRUE) } plots[[pp]] <- plots[[pp]] + ggplot2::xlab(xcap) + ggplot2::ylab(ycap) + ggplot2::xlim(xlim) + ggplot2::ylim(ylim) + ggplot2::theme_classic() + ggplot2::theme(axis.title = ggplot2::element_text(size=axis.title.size), axis.text = ggplot2::element_text(size=axis.text.size), legend.text=ggplot2::element_text(size=legend.title.size), legend.title = ggplot2::element_text(size=legend.title.size)) + ggplot2::labs(shape= "MP Type", color="MP Type") if (Col == "Class") { plots[[pp]] <- plots[[pp]] + ggplot2::scale_colour_manual(values=cols) } else if (Col == "MP") { plots[[pp]] <- plots[[pp]] + ggplot2::scale_colour_manual(values=cols) + ggplot2::guides(color='none') } if (!is.null(Title)) plots[[pp]] <- plots[[pp]] + ggplot2::labs(title=Title[pp]) if (legend==FALSE) plots[[pp]] <- plots[[pp]] + ggplot2::theme(legend.position="none") } out <- do.call("rbind", listout) tab <- table(out$label, out$pass) passall <- rownames(tab)[tab[,ncol(tab)] == nplots] if (class(MSEobj)=='MSE') { Results <- summary(MSEobj, PMlist, silent=TRUE, Refs=Refs) Results$Satisificed <- FALSE Results$Satisificed[match(passall, Results$MP)] <- TRUE Results <- Results[,unique(colnames(Results))] } else { Results <- 'Summary table of results only available for objects of class `MSE`' } out <- list(Results=Results, Plots=plots) if (Show == "plots") { join_plots(plots, n.col, n.row, position = position, legend=legend) } else if (Show == "table") { print(Results) } else if (Show == "none") { return(invisible(out)) } else { join_plots(plots, n.col, n.row, position = position, legend=legend) if (class(MSEobj) =='MSE') print(Results) } invisible(out) } Tplot <- function(MSEobj, Lims=c(0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5), ...) { if (class(Lims)!="numeric") stop("Second argument must be numeric") TradePlot(MSEobj, Lims=Lims, PMlist=list("PNOF", "LTY", "P100", "LTY", "P50", "LTY", "P10", "LTY"), ...) } Tplot2 <- function(MSEobj, Lims=c(0.2, 0.2, 0.8, 0.8), ...) { if (class(Lims)!="numeric") stop("Second argument must be numeric") TradePlot(MSEobj, Lims=Lims, PMlist=list("STY", "LTY", "P10", "AAVY"), ...) } Tplot3 <- function(MSEobj, Lims=c(0.5, 0.5, 0.8, 0.5), ...) { if (class(Lims)!="numeric") stop("Second argument must be numeric") TradePlot(MSEobj, Lims=Lims, PMlist=list("PNOF", "LTY", "P50", "AAVY"), ...) } NOAA_plot2 <- function(MSEobj) { TradePlot(MSEobj, Lims=c(0.5, 0, 0.8, 0.5), PMlist=list("PNOF", "LTY", "P50", "AAVY"), Refs=list(AAVY=0.15)) } Cplot <- function(MSEobj, MPs = NA, lastYrs = 5, point.size=2, lab.size=4, axis.title.size=12, axis.text.size=10, legend.title.size=12) { if (!all(is.na(MPs))) MSEobj <- Sub(MSEobj, MPs = MPs) if (!requireNamespace("ggrepel", quietly = TRUE)) { stop("Package \"ggrepel\" needed for this function to work. Please install it.", call. = FALSE) } mp <- Catch <- Biomass <- mB <- mC <- NULL nsim <- MSEobj@nsim nMPs <- MSEobj@nMPs MPs <- MSEobj@MPs nyears <- MSEobj@nyears proyears <- MSEobj@proyears RefYd <- MSEobj@OM$RefY MPType <- MPtype(MSEobj@MPs) Class <- MPType[match(MSEobj@MPs, MPType[,1]),2] pastC <- MSEobj@CB_hist/RefYd temp <- aperm( replicate(nMPs, pastC), c(1, 3, 2)) lastYr <- temp[, , nyears, drop = FALSE] Yield <- abind::abind(lastYr, MSEobj@Catch[, , , drop = FALSE]/RefYd, along = 3) ny <- MSEobj@proyears + 1 relYield <- Yield[, , , drop = FALSE]/Yield[, , rep(1, ny), drop = FALSE] relYield <- relYield[,,(proyears - lastYrs + 1):proyears] bio <- MSEobj@SB_SBMSY[,,(proyears - lastYrs + 1):proyears] histSSB <- MSEobj@SSB_hist relSSB <- histSSB[,nyears]/ MSEobj@OM$SSBMSY temp <- array(replicate(nMPs, relSSB), dim=dim(bio)) relbio <- bio/temp dimnames(relbio) <- list(1:nsim, MPs, 1:lastYrs) Bdf <- as.data.frame.table(relbio) names(Bdf) <- c("sim", "mp", "yr", 'Biomass') dimnames(relYield) <- list(1:nsim, MPs, 1:lastYrs) Cdf <- as.data.frame.table(relYield) names(Cdf) <- c("sim", "mp", "yr", 'Catch') DF <- dplyr::left_join(Cdf, Bdf,by = c("sim", "mp", "yr")) DF <- DF %>% dplyr::group_by(mp) %>% dplyr::summarize(mC=median(Catch), upC=quantile(Catch, 0.95), lowC=quantile(Catch, 0.05), mB=median(Biomass), upB=quantile(Biomass, 0.95), lowB=quantile(Biomass, 0.05), .groups='keep') DF$class <- Class p1 <- ggplot2::ggplot(DF, ggplot2::aes(x=mB, y=mC, color=class, shape=class)) + ggplot2::geom_point() + ggplot2::expand_limits(x=0, y=0) + ggplot2::geom_vline(xintercept = 1, color="gray") + ggplot2::geom_hline(yintercept = 1, color="gray") + ggplot2::theme_classic() + ggplot2::theme(axis.title = ggplot2::element_text(size=axis.title.size), axis.text = ggplot2::element_text(size=axis.text.size), legend.text=ggplot2::element_text(size=legend.title.size), legend.title = ggplot2::element_text(size=legend.title.size)) + ggrepel::geom_text_repel(ggplot2::aes(label=mp), show.legend=FALSE) + ggplot2::labs(x=paste("Median Spawning Biomass (last", lastYrs, "years)\n relative to current"), y=paste("Median Yield (last", lastYrs, "years)\n relative to current"), shape= "MP Type", color="MP Type") print(p1) }
gutenberg_download <- function(gutenberg_id, mirror = NULL, strip = TRUE, meta_fields = NULL, verbose = TRUE, files = NULL, ...) { if (is.null(mirror)) { mirror <- gutenberg_get_mirror(verbose = verbose) } if (inherits(gutenberg_id, "data.frame")) { gutenberg_id <- gutenberg_id[["gutenberg_id"]] } id <- as.character(gutenberg_id) path <- id %>% stringr::str_sub(1, -2) %>% stringr::str_split("") %>% sapply(stringr::str_c, collapse = "/") path <- ifelse(nchar(id) == 1, "0", path) full_url <- stringr::str_c(mirror, path, id, stringr::str_c(id, ".zip"), sep = "/") names(full_url) <- id try_download <- function(url) { ret <- read_zip_url(url) if (!is.null(ret)) { return(ret) } base_url <- stringr::str_replace(url, ".zip$", "") for (suffix in c("-8", "-0")) { new_url <- paste0(base_url, suffix, ".zip") ret <- read_zip_url(new_url) if (!is.null(ret)) { return(ret) } } warning("Could not download a book at ", url) NULL } if (!is.null(files)) { downloaded <- files %>% stats::setNames(id) %>% purrr::map(readr::read_lines) } else { downloaded <- full_url %>% purrr::map(try_download) } ret <- downloaded %>% purrr::discard(is.null) %>% purrr::map_df(~tibble(text = .), .id = "gutenberg_id") %>% mutate(gutenberg_id = as.integer(gutenberg_id)) if (strip) { ret <- ret %>% group_by(gutenberg_id) %>% do(tibble(text = gutenberg_strip(.$text, ...))) %>% ungroup() } if (length(meta_fields) > 0) { meta_fields <- unique(c("gutenberg_id", meta_fields)) utils::data("gutenberg_metadata", package = "gutenbergr", envir = environment()) md <- gutenberg_metadata[meta_fields] ret <- ret %>% inner_join(md, by = "gutenberg_id") } ret } gutenberg_strip <- function(text) { text[is.na(text)] <- "" starting_regex <- "(^\\*\\*\\*.*PROJECT GUTENBERG|END.*SMALL PRINT)" text <- discard_start_while(text, !stringr::str_detect(text, starting_regex))[-1] text <- discard_start_while(text, text != "") ending_regex <- "^(End of .*Project Gutenberg.*|\\*\\*\\*.*END OF.*PROJECT GUTENBERG)" text <- keep_while(text, !stringr::str_detect(text, ending_regex)) text <- discard_start_while(text, text == "") start_paragraph_regex <- "(produced by|prepared by|transcribed from|project gutenberg|^special thanks|^note: )" while (length(text) > 0 && stringr::str_detect(stringr::str_to_lower(text[1]), start_paragraph_regex)) { text <- discard_start_while(text, text != "") text <- discard_start_while(text, text == "") } text <- discard_end_while(text, text == "") text } gutenberg_get_mirror <- function(verbose = TRUE) { mirror <- getOption("gutenberg_mirror") if (!is.null(mirror)) { return(mirror) } if (verbose) { message("Determining mirror for Project Gutenberg from ", "http://www.gutenberg.org/robot/harvest") } wget_url <- "http://www.gutenberg.org/robot/harvest?filetypes[]=txt" lines <- readr::read_lines(wget_url) a <- lines[stringr::str_detect(lines, stringr::fixed("<a href="))][1] mirror_full_url <- stringr::str_match(a, "href=\"(.*?)\"")[2] parsed <- urltools::url_parse(mirror_full_url) mirror <- paste0(parsed$scheme, "://", parsed$domain) if (mirror == "http://www.gutenberg.lib.md.us") { mirror <- "http://aleph.gutenberg.org" } if (verbose) { message("Using mirror ", mirror) } options(gutenberg_mirror = mirror) return(mirror) }
edar <- function() { edar_pack <- c("psych", "Hmisc", "PerformanceAnalytics") for (i in 1:length(edar_pack)){ requireNamespace(edar_pack[i], quietly = TRUE) } appDir <- system.file("shiny-apps", "EDAR", package = "Statsomat") if (appDir == "") { stop("Could not find example directory. Try re-installing Statsomat.", call. = FALSE) } shiny::runApp(appDir, display.mode = "normal") }
`ensembleValidDates` <- function (x) { UseMethod("ensembleValidDates") }
input_mats <- function(X, ...){ object <- new_input_mats(X, ...) check(object) return(object) } new_input_mats <- function(X, ...){ stopifnot(is.matrix(X) | is.list(X) | is.null(X)) object <- c(list(X = X), do.call("new_id_attributes", list(...))) object[sapply(object, is.null)] <- NULL class(object) <- "input_mats" return(object) } check.input_mats <- function(object){ if (!is.list(object$X)){ stop("'X' must be a list or a list of lists.", call. = FALSE) } X <- flatten_lists(object$X) if(!all(sapply(X, function(y) inherits(y, "matrix")))){ stop("'X' must be a list or list of lists of matrices.", call. = FALSE) } X_nrows <- sapply(X, nrow) if (is.list(object$X)){ if (!all(X_nrows[1] == X_nrows)){ stop("The number of rows in each matrix in 'X' must be the same.", call. = FALSE) } } id_vars <- c("strategy_id", "patient_id", "state_id", "transition_id", "time_id") id_vars_n <- c("n_strategies", "n_patients", "n_states", "n_transitions", "n_times") for (i in 1:length(id_vars)){ if (!is.null(object[[id_vars[i]]])){ if(length(object[[id_vars[i]]]) != X_nrows[1]){ msg <- paste0("The length of '", id_vars[i], "' does not equal the number of rows in the ", "'X' matrices.") stop(msg, call. = FALSE) } } } id_args <- object[names(object)[names(object) != "X"]] check(do.call("id_attributes", id_args)) } as.data.table.input_mats <- function(x, ...) { id_dt <- make_id_data_table(x) xl <- lapply(flatten_lists(x$X), as.data.table) x_dt <- NULL for (i in 1:length(xl)) { cols_i <- colnames(xl[[i]]) new_cols <- cols_i[!cols_i %in% colnames(x_dt)] if (length(new_cols) > 0) { x_dt <- cbind(x_dt, xl[[i]][, new_cols, with = FALSE]) } } tbl <- cbind(id_dt, x_dt) setattr(tbl, "id_vars", attr(id_dt, "id_vars")) tbl } print.input_mats <- function(x, ...) { x_dt <- as.data.table(x) id_vars <- attr(x_dt, "id_vars") size <- unlist(x[grepl("n_", names(x))]) cat("An \"input_mats\" object \n\n") cat("Column binding the ID variables with all variables contained in the X matrices:\n") print(as.data.table(x), ...) cat("\n") cat("Number of unique values of ID variables:\n") print(size) cat("\n") if ("time_intervals" %in% names(x)) { cat("Time intervals:\n") print(x$time_intervals) } invisible(x) } size_id_map <- function(){ c(strategy_id = "n_strategies", patient_id = "n_patients", state_id = "n_states", transition_id = "n_transitions", time_id = "n_times") } get_input_mats_id_vars <- function(data){ map <- size_id_map() res <- list() id_vars <- attr(data, "id_vars") for (i in 1:length(id_vars)){ res[[id_vars[i]]] <- data[[id_vars[i]]] res[[map[id_vars[i]]]] <- length(unique(data[[id_vars[i]]])) if (id_vars[[i]] == "time_id"){ res[["time_intervals"]] <- attr(data, "time_intervals") } } if ("grp_id" %in% colnames(data)) res[["grp_id"]] <- data[["grp_id"]] if ("patient_wt" %in% colnames(data)) res[["patient_wt"]] <- data[["patient_wt"]] return(res) } check_input_data <- function(input_data){ if (!inherits(input_data, "expanded_hesim_data")){ stop("'input_data' must be of class 'expanded_hesim_data'.") } if (!inherits(input_data, "data.table") & !inherits(input_data, "data.frame")){ stop("'input_data' must inherit from either 'data.table' or 'data.frame'.") } if (!inherits(input_data, "data.table")){ setattr(input_data, "class", c("expanded_hesim_data", "data.table", "data.frame")) } } extract_X <- function(coef_mat, data){ varnames <- colnames(coef_mat) if (is.null(varnames)){ stop("Variable names for coefficients cannot be NULL.", call. = FALSE) } if(!all(varnames %in% colnames(data))){ stop("Not all variables in 'object' are contained in 'input_data'.", call. = FALSE) } X <- as.matrix(data[, varnames, with = FALSE]) if (!is.numeric(X)) { stop("'input_data' must only include numeric variables.", call. = FALSE) } return(X) } get_terms <- function(object){ tt <- stats::terms(object) return(stats::delete.response(tt)) } create_input_mats <- function (object, ...) { if (missing(object)){ stop("'object' is missing with no default.") } UseMethod("create_input_mats", object) } formula_list_rec <- function(object, input_data, ...){ x <- vector(mode = "list", length = length(object)) names(x) <- names(object) for (i in 1:length(x)){ if (inherits(object[[i]], "formula")){ x[[i]] <- stats::model.matrix(object[[i]], data = input_data, ...) } else{ x[[i]] <- formula_list_rec(object[[i]], data = input_data, ...) } } return(x) } create_input_mats.formula_list <- function(object, input_data, ...){ check_input_data(input_data) X_list <- formula_list_rec(object, input_data, ...) args <- c(list(X = X_list), get_input_mats_id_vars(input_data)) return(do.call("new_input_mats", args)) } create_input_mats.lm <- function(object, input_data, ...){ check_input_data(input_data) terms <- get_terms(object) X <- stats::model.matrix(terms, data = input_data, ...) args <- c(list(X = list(mu = X)), get_input_mats_id_vars(input_data)) return(do.call("new_input_mats", args)) } create_input_mats_flexsurvreg_X <- function(object, input_data, ...){ mfo <- stats::model.frame(object) covnames <- attr(mfo, "covnames") missing.covs <- unique(covnames[!covnames %in% names(input_data)]) if (length(missing.covs) > 0){ missing.covs <- sprintf("\"%s\"", missing.covs) plural <- if (length(missing.covs)>1) "s" else "" stop(sprintf("Value%s of covariate%s ",plural, plural), paste(missing.covs, collapse=", "), " not supplied in \"input_data\"") } tt <- attr(mfo, "terms") Terms <- stats::delete.response(tt) mf <- stats::model.frame(Terms, input_data, xlev = stats::.getXlevels(tt, mfo)) if (!is.null(cl <- attr(Terms, "dataClasses"))) stats::.checkMFClasses(cl, mf) pars <- object$dlist$pars X_list <- vector(mode = "list", length = length(pars)) names(X_list) <- pars for (i in 1:length(pars)){ form <- object$all.formulae[[pars[i]]] if (is.null(form)){ form <- stats::formula(~1) } else{ form <- stats::delete.response(stats::terms(form)) } X_list[[i]] <- stats::model.matrix(form, mf, ...) } return(X_list) } create_input_mats.flexsurvreg <- function(object, input_data,...){ check_input_data(input_data) X_list <- create_input_mats_flexsurvreg_X(object, input_data, ...) args <- c(list(X = X_list), get_input_mats_id_vars(input_data)) return(do.call("new_input_mats", args)) } create_input_mats.flexsurvreg_list <- function(object, input_data,...){ check_input_data(input_data) X_list_2d <- vector(mode = "list", length = length(object)) names(X_list_2d) <- names(object) for (i in 1:length(object)){ X_list_2d[[i]] <- create_input_mats_flexsurvreg_X(object[[i]], input_data, ...) } args <- c(list(X = X_list_2d), get_input_mats_id_vars(input_data)) return(do.call("new_input_mats", args)) } create_input_mats.partsurvfit <- function(object, input_data, ...){ check_input_data(input_data) return(create_input_mats.flexsurvreg_list(object$models, input_data, ...)) } create_input_mats.params_lm <- function(object, input_data, ...){ check_input_data(input_data) X <- extract_X(object$coefs, input_data) args <- c(list(X = list(mu = X)), get_input_mats_id_vars(input_data)) return(do.call("new_input_mats", args)) } create_input_mats_params_surv_X <- function(object, input_data){ X_list <- vector(mode = "list", length = length(object$coefs)) names(X_list) <- names(object$coefs) for (i in 1:length(X_list)){ X_list[[i]] <- extract_X(object$coefs[[i]], input_data) } return(X_list) } create_input_mats.params_surv <- function(object, input_data, ...){ check_input_data(input_data) X_list <- create_input_mats_params_surv_X(object, input_data) args <- c(list(X = X_list), get_input_mats_id_vars(input_data)) return(do.call("new_input_mats", args)) } create_input_mats.params_surv_list <- function(object, input_data, ...){ X_list_2d <- vector(mode = "list", length = length(object)) names(X_list_2d) <- names(object) for (i in 1:length(object)){ X_list_2d[[i]] <- create_input_mats_params_surv_X(object[[i]], input_data) } args <- c(list(X = X_list_2d), get_input_mats_id_vars(input_data)) return(do.call("new_input_mats", args)) } create_input_mats_multinom_X <- function(object, input_data, ...){ check_input_data(input_data) terms <- get_terms(object) if (!is.null(attr(terms(object), "offset"))){ stop("An offset is not supported.", call. = FALSE) } m <- stats::model.frame(terms, input_data, na.action = stats::na.omit, xlev = object$xlevels) if (!is.null(cl <- attr(terms, "dataClasses"))) stats::.checkMFClasses(cl, m) return(stats::model.matrix(terms, m, contrasts = object$contrasts)) } create_input_mats.multinom <- function(object, input_data, ...){ X <- create_input_mats_multinom_X(object, input_data, ...) args <- c(list(X = X), get_input_mats_id_vars(input_data)) return(do.call("new_input_mats", args)) } create_input_mats.multinom_list <- function(object, input_data, ...){ X_list <- vector(mode = "list", length = length(object)) names(X_list) <- names(object) for (i in 1:length(object)){ X_list[[i]] <- create_input_mats_multinom_X(object[[i]], input_data, ...) } args <- c(list(X = X_list), get_input_mats_id_vars(input_data)) return(do.call("new_input_mats", args)) } create_input_mats.params_mlogit_list <- function(object, input_data, ...){ X_list <- vector(mode = "list", length = length(object)) for (i in 1:length(object)){ X_list[[i]] <- extract_X(object[[i]]$coefs[, , 1], input_data) } args <- c(list(X = X_list), get_input_mats_id_vars(input_data)) return(do.call("new_input_mats", args)) }
mww_eval<-function(d,x,filter,LU=NULL){ if(is.matrix(x)){ N <- dim(x)[1] k <- dim(x)[2] }else{ N <- length(x) k <- 1 } x <- as.matrix(x,dim=c(N,k)) xwav <- matrix(0,N,k) for(j in 1:k){ xx <- x[,j] resw <- DWTexact(xx,filter) xwav_temp <- resw$dwt index <- resw$indmaxband Jmax <- resw$Jmax xwav[1:index[Jmax],j] <- xwav_temp } new_xwav <- matrix(0,min(index[Jmax],N),k) if(index[Jmax]<N){ new_xwav[(1:(index[Jmax])),] <- xwav[(1:(index[Jmax])),] } xwav <- new_xwav index <- c(0,index) if(is.null(LU)==TRUE){ LU <- c(1,Jmax) } L <- max(LU[1],1) U <- min(LU[2],Jmax) nscale <- U-L+1 n <- index[U+1]-index[L] if(k==1){ res<-mww_wav_eval(d,as.vector(xwav),index,LU) }else{ res<-mww_wav_eval(d,xwav,index,LU) } return(res) }
dtmod <- function(x, mu = 0, sigma = 1, nu = 30, log = FALSE){ if (log == TRUE){ x <- log(x) } nenner1 <- try(sigma*beta(1/2, nu/2)) zaehler1 <- try(nu^(-1/2)) nenner2 <- try(nu*sigma^2) zaehler2 <- try((x-mu)^2) dtmod <- try(zaehler1/nenner1*(1+zaehler2/nenner2)^(-1*(nu+1)/2)) return (dtmod) }
context("Profile") test_that("renv/profile is read and used to select a profile", { project <- renv_tests_scope() init(profile = "testing") renv_imbue_self(project) expect_true(file.exists("renv/profile")) contents <- readLines("renv/profile") expect_equal(contents, "testing") renv_scope_envvars(R_PROFILE_USER = NULL) script <- renv_test_code({ writeLines(Sys.getenv("RENV_PROFILE")) }) args <- c("-s", "-f", shQuote(script)) output <- renv_system_exec(R(), args, action = "reading profile") }) test_that("a profile changes the default library / lockfile path", { renv_tests_scope() renv_scope_envvars(RENV_PROFILE = "testing") project <- getwd() init() profile <- file.path(project, "renv/profile") expect_false(file.exists(profile)) prefix <- "renv/profiles/testing" expect_equal( paths$lockfile(project = project), file.path(project, prefix, "renv.lock") ) expect_equal( paths$library(project = project), file.path(project, prefix, "renv/library", renv_platform_prefix()) ) expect_equal( paths$settings(project = project), file.path(project, prefix, "renv/settings.dcf") ) }) test_that("profile-specific dependencies can be written", { renv_tests_scope() renv_scope_envvars(RENV_PROFILE = "testing") init() path <- renv_paths_renv("_dependencies.R") ensure_parent_directory(path) writeLines("library(toast)", con = path) deps <- dependencies(quiet = TRUE) expect_true("toast" %in% deps$Package) renv_scope_envvars(RENV_PROFILE = "other") deps <- dependencies(quiet = TRUE) expect_false("toast" %in% deps$Package) }) test_that("profile-specific dependencies can be declared in DESCRIPTION", { renv_tests_scope() renv_scope_envvars(RENV_PROFILE = "testing") init() writeLines( "Config/renv/profiles/testing/dependencies: toast", con = "DESCRIPTION" ) deps <- dependencies() expect_true("toast" %in% deps$Package) }) test_that("profile-specific remotes are parsed", { project <- renv_tests_scope() renv_scope_envvars(RENV_PROFILE = "testing") init() desc <- heredoc(' Type: Project Config/renv/profiles/testing/dependencies: bread Config/renv/profiles/testing/remotes: [email protected] ') writeLines(desc, con = "DESCRIPTION") remotes <- renv_project_remotes(project) actual <- remotes$bread expected <- list(Package = "bread", Version = "0.1.0", Source = "Repository") expect_equal(actual, expected) })
require(copula) source(system.file("Rsource", "utils.R", package="copula", mustWork=TRUE)) showProc.time() (doExtras <- copula:::doExtras()) tC2.F <- tCopula(df=2, df.fixed=TRUE) (cm <- setTheta(tC2.F, value=-0.5, freeOnly=TRUE)) (cp <- setTheta(tC2.F, value= 0.5, freeOnly=TRUE)) (c2 <- setTheta(tC2.F, value=c(0.5,3), freeOnly=FALSE)) stopifnot(all.equal(getTheta(cm), -0.5), all.equal(getTheta(cp), +0.5), all.equal(getTheta(cm, freeOnly=FALSE, named=TRUE), c(rho.1 = -0.5, df = 2)), all.equal(getTheta(cp, freeOnly=FALSE), c(0.5, 2)), all.equal(getTheta(c2, freeOnly=FALSE, named=TRUE), c(rho.1 = 0.5, df = 3))) (N3 <- normalCopula(c(0.5,0.3,0.2), dim=3, dispstr = "un")) fixedParam(N3) <- c(TRUE, FALSE, FALSE); N3 (N3.2 <- setTheta(N3, c( 0.4, 0.2) -> t2)) (N3.3 <- setTheta(N3, c(0.6, 0.4, 0.2) -> t3, freeOnly=FALSE)) stopifnot(all.equal(getTheta(N3.2), t2), all.equal(getTheta(N3.3), t3[-1]), all.equal(getTheta(N3.2, freeOnly=FALSE), c(0.5, t2)), all.equal(getTheta(N3.3, freeOnly=FALSE), t3)) (tC3 <- tCopula(c(0.5,0.3,0.2), dim=3, dispstr = "un")) fixedParam(tC3) <- c(TRUE, FALSE, FALSE, TRUE); tC3 (tC3.2 <- setTheta(tC3, c( 0.4, 0.1) -> t2)) (tC3.3 <- setTheta(tC3, c(0.6, 0.4, 0.1, 3) -> t3, freeOnly=FALSE)) stopifnot(all.equal(getTheta(tC3.2), t2), all.equal(getTheta(tC3.3), t3[-c(1,4)]), all.equal(getTheta(tC3.2, freeOnly=FALSE), c(0.5, t2, 4)), all.equal(getTheta(tC3.3, freeOnly=FALSE), t3)) fixedParam(tC3) <- c(TRUE, FALSE, FALSE, FALSE); tC3 (tC3u.2 <- setTheta(tC3, c( 0.4, 0.2, 5) -> t2)) (tC3u.3 <- setTheta(tC3, c(0.6, 0.4, 0.2, 3) -> t3, freeOnly=FALSE)) stopifnot(all.equal(getTheta(tC3u.2), t2), all.equal(getTheta(tC3u.3), t3[-1]), all.equal(getTheta(tC3u.2, freeOnly=FALSE), c(0.5, t2)), all.equal(getTheta(tC3u.3, freeOnly=FALSE), t3)) n <- 100 nc3 <- normalCopula(dim = 3, c(.6,.3,.2), dispstr = "un") nc3@parameters set.seed(4521) x <- rCopula(n, nc3) u <- pobs(x) fitCopula(nc3, data = u) fitCopula(nc3, data = u, estimate.variance = FALSE) fitCopula(nc3, data = x, method = "ml") fitCopula(nc3, data = x, method = "ml", estimate.variance = FALSE) fitCopula(nc3, data = u, method = "itau") fitCopula(nc3, data = u, method = "itau", estimate.variance = FALSE) fitCopula(nc3, data = u, method = "irho") fitCopula(nc3, data = u, method = "irho", estimate.variance = FALSE) showProc.time() nc2 <- normalCopula(dim = 3, fixParam(c(.6,.3,.2), c(TRUE, FALSE, FALSE)), dispstr = "un") nc2@parameters fitCopula(nc2, data = u) fitCopula(nc2, data = u, estimate.variance = FALSE) fitCopula(nc2, data = x, method = "ml") fitCopula(nc2, data = x, method = "ml", estimate.variance = FALSE) fitCopula(nc2, data = u, method = "itau") fitCopula(nc2, data = u, method = "itau", estimate.variance = FALSE) fitCopula(nc2, data = u, method = "irho") fitCopula(nc2, data = u, method = "irho", estimate.variance = FALSE) showProc.time() nc1 <- normalCopula(dim = 3, fixParam(c(.6,.3,.2), c(TRUE, TRUE, FALSE)), dispstr = "un") nc1@parameters fitCopula(nc1, data = u) fitCopula(nc1, data = x, method = "ml") fitCopula(nc1, data = u, method = "itau") fitCopula(nc1, data = u, method = "irho") showProc.time() tc3df <- tCopula(dim = 3, c(.6,.3,.2), dispstr = "un") tc3df@parameters set.seed(4521) x <- rCopula(n, tc3df) u <- pobs(x) fitCopula(tc3df, data = u) fitCopula(tc3df, data = x, method = "ml") fitCopula(tc3df, data = u, method = "itau") fitCopula(tc3df, data = u, estimate.variance = FALSE) fitCopula(tc3df, data = x, method = "ml", estimate.variance = FALSE) fitCopula(tc3df, data = u, method = "itau", estimate.variance = FALSE) fitCopula(tc3df, data = u, method = "itau.mpl") showProc.time() tc2df <- tCopula(dim = 3, fixParam(c(.6,.3,.2), c(TRUE, FALSE, FALSE)), dispstr = "un") tc2df@parameters fitCopula(tc2df, data = u) fitCopula(tc2df, data = x, method = "ml") fitCopula(tc2df, data = u, method = "itau") fitCopula(tc2df, data = u, estimate.variance = FALSE) fitCopula(tc2df, data = x, method = "ml", estimate.variance = FALSE) fitCopula(tc2df, data = u, method = "itau", estimate.variance = FALSE) fitCopula(tc2df, data = u, method = "itau.mpl") showProc.time() tc1df <- tCopula(dim = 3, fixParam(c(.6,.3,.2), c(TRUE, TRUE, FALSE)), dispstr = "un") tc1df@parameters fitCopula(tc1df, data = u) fitCopula(tc1df, data = x, method = "ml") fitCopula(tc1df, data = u, method = "itau") fitCopula(tc1df, data = u, method = "itau.mpl") showProc.time() tc2 <- tCopula(dim = 3, fixParam(c(.6,.3,.2), c(TRUE, FALSE, FALSE)), dispstr = "un", df.fixed = TRUE) tc2@parameters fitCopula(tc2, data = u) fitCopula(tc2, data = u, method = "itau") showProc.time() tc1 <- tCopula(dim = 3, fixParam(c(.6,.3,.2), c(TRUE, TRUE, FALSE)), dispstr = "un", df.fixed = TRUE) tc1@parameters fitCopula(tc1, data = u) fitCopula(tc1, data = u, method = "itau") showProc.time() testdCdc <- function(cop, v, cop.unfixed) { fixed <- attr(cop@parameters, "fixed") if (.hasSlot(cop, "df.fixed")) fixed <- fixed[-length(fixed)] stopifnot(all.equal(copula:::dCdu(cop, v), copula:::dCdu(cop.unfixed, v)), all.equal(copula:::dCdtheta(cop, v), copula:::dCdtheta(cop.unfixed, v)[, !fixed, drop = FALSE]), all.equal(copula:::dlogcdu(cop, v), copula:::dlogcdu(cop.unfixed, v)), all.equal(copula:::dlogcdtheta(cop, v), copula:::dlogcdtheta(cop.unfixed, v)[, !fixed, drop = FALSE])) } set.seed(7615) v <- matrix(runif(15), 5, 3) testdCdc(nc2, v, nc3) testdCdc(nc1, v, nc3) tc3 <- tCopula(dim = 3, c(.6,.3,.2), dispstr = "un", df.fixed = TRUE) testdCdc(tc2, v, tc3) testdCdc(tc1, v, tc3) showProc.time() cD <- rbind( Nc2 = comparederiv(nc2, v), Nc1 = comparederiv(nc1, v), tc2 = comparederiv(tc2, v), tc1 = comparederiv(tc1, v)) cD stopifnot( cD[,"dCdu" ] < 0.3, cD[,"dCdtheta"] < 0.2, cD[,"dlogcdu" ] < 7e-8, cD[,"dlogcdtheta"] < 4e-8) showProc.time() if (doExtras) { do1 <- function(n, cop) { u <- pobs(rCopula(n, cop)) gofCopula(cop, pobs(u), sim = "mult")$p.value } n <- 100 M <- 10 mM <- sapply(list(nc2=nc2, nc1=nc1, tc2=tc2, tc1=tc1 ), function(COP) mean(replicate(M, do1(n, COP)))) print(mM) print(mM < 0.05) showProc.time() }
xpose.panel.histogram <- function(x, object, breaks=NULL, dens=TRUE, hidlty = object@[email protected]$hidlty, hidcol = object@[email protected]$hidcol, hidlwd = object@[email protected]$hidlwd, hiborder = object@[email protected]$hiborder, hilty = object@[email protected]$hilty, hicol = object@[email protected]$hicol, hilwd = object@[email protected]$hilwd, math.dens=NULL, vline= NULL, vllwd= 3, vllty= 1, vlcol= "grey", hline= NULL, hllwd= 3, hllty= 1, hlcol= "grey", bins.per.panel.equal = TRUE, showMean = FALSE, meanllwd= 3, meanllty= 1, meanlcol= "orange", showMedian = FALSE, medianllwd= 3, medianllty= 1, medianlcol= "black", showPCTS = FALSE, PCTS = c(0.025,0.975), PCTSllwd= 2, PCTSllty= hidlty, PCTSlcol= "black", vdline= NULL, vdllwd= 3, vdllty= 1, vdlcol= "red", ..., groups) { if(length(unique(x)) <= object@[email protected]){ x <- as.factor(x) } if(is.factor(x)) { nint <- length(levels(x)) breaks <- seq(0.5, length = length(levels(x))+1) } else { if(!bins.per.panel.equal){ nint <- round(log2(length(x))+1) endpoints <- range(x[!is.na(x)]) breaks <- do.breaks(endpoints, nint) } } panel.histogram(x, breaks=breaks, lty = hilty, lwd = hilwd, col = hicol, border = hiborder, ... ) if(dens){ if (is.numeric(x)) { panel.densityplot(x, lty=hidlty, col=hidcol, lwd=hidlwd, ...) } } if (!is.null(math.dens)){ panel.mathdensity(dmath = dnorm, args = list(mean=math.dens$mean,sd=math.dens$sd), col.line="black",lwd=3, ...) } if(!is.null(vline)) { panel.abline(v=vline,col=vlcol,lwd=vllwd,lty=vllty) } if(!is.null(hline)) { panel.abline(h=hline,col=hlcol,lwd=hllwd,lty=hllty) } if(!is.null(hline)) { panel.abline(h=hline,col=hlcol,lwd=hllwd,lty=hllty) } if(showMean | showMedian) sp <- summary(x) if(showMean) panel.abline(v=sp[4],col=meanlcol,lwd=meanllwd,lty=meanllty) if(showMedian) panel.abline(v=sp[3],col=medianlcol,lwd=medianllwd,lty=medianllty) if(showPCTS){ qu <- quantile(x, PCTS, na.rm=T) panel.abline(v=qu,col=PCTSlcol,lwd=PCTSllwd,lty=PCTSllty) } if(!is.null(vdline)) { panel.abline(v=vdline[groups = panel.number()], col=vdlcol,lwd=vdllwd,lty=vdllty) } }
library(checkargs) context("isNonZeroIntegerOrNaOrNanVector") test_that("isNonZeroIntegerOrNaOrNanVector works for all arguments", { expect_identical(isNonZeroIntegerOrNaOrNanVector(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanVector(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanVector(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanVector(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanVector(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_error(isNonZeroIntegerOrNaOrNanVector(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanVector(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanVector(0, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanVector(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanVector(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanVector(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanVector(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanVector(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector("", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector("X", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanVector(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanVector(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNonZeroIntegerOrNaOrNanVector(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNonZeroIntegerOrNaOrNanVector(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNonZeroIntegerOrNaOrNanVector(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
getTestedLanguages = function() { .TestedLanguages } wordStem = function(words, language = character(), warnTested = FALSE) { if(length(language)) { if(length(language) == 1) { langs = getStemLanguages() idx = pmatch(language, langs) if(is.na(idx)) stop("No such language: ", language, ". See the documentation for wordStem() and getStemLanguages().") language = langs[idx] if(warnTested && !(language %in% getTestedLanguages())) warning("Currently, ", language, " is not tested. It may work, but you will need support for UTF characters.") } else { if(!is.character(language)) { if(!is.list(language) && !all(sapply(language, function(x) inherits(x, "NativeSymbol")))) stop("Require two native symbols or names of native symbols") } else { language = lapply(language, function(x) getNativeSymbolInfo(x)$address) } } } lens = nchar(words, "bytes") lim = .Call("S_getMaxWordLength", PACKAGE = "RTextTools") if(any(lens > lim)) stop("There is a limit of ", lim, "characters on the number of characters in a word being stemmed") .Call("S_stemWords", words, lens, language, PACKAGE="RTextTools") } getStemLanguages = function() { .Call("S_getLanguages", PACKAGE = "RTextTools") }
print.summary.tmatrix <- function(x,...){ cat(paste("transition matrix",x$name.mat,"\n\n")) cat(paste("lambda:", round(x$lambda, 3),"\n\n")) cat("stable stage distribution: \n") names(x$stable.stage.distribution)<- x$m.names print(noquote(format(round(x$stable.stage.distribution,3)))); cat("\n\n") cat("reproductive value:\n") names(x$reproductive.value)<- x$m.names print(noquote(format(round(x$reproductive.value,3)))); cat("\n\n") cat("sensitivities:\n") dimnames(x$sensitivity) <-list(x$m.names, x$m.names) print(round(x$sensitivity,3)); cat("\n\n") cat("elasticities:\n") class(x$elasticity) <-"matrix" dimnames(x$elasticity) <-list(x$m.names, x$m.names) print(round(x$elasticity,3)); cat("\n\n") }
slide.layouts.pptx = function( doc, layout, ... ) { if( length( doc$styles ) == 0 ){ stop("You must defined layout in your pptx template.") } if( !missing( layout ) ){ if( !is.element( layout, doc$styles ) ){ stop("Slide layout '", layout, "' does not exist in defined layouts.") } if( !is.character(layout) ) stop("argument 'layout' must be a single string value.") if( length(layout) != 1 ) stop("argument 'layout' must be a single string value.") if( !is.element(layout, doc$styles)) { stop(shQuote(layout), " does not exists in the of available layout names of the template pptx file. ", "Use slide.layouts(", deparse(substitute(doc)), ") to list them." ) } plotSlideLayout( doc, layout ) } doc$styles }
setGeneric(name = 'hm_get', def = function(obj, slot_name = NA_character_) { standardGeneric('hm_get') } ) setMethod(f = 'hm_get', signature = 'hydromet', definition = function(obj, slot_name = NA_character_) { check_class(argument = obj, target = 'hydromet', arg_name = 'obj') check_class(argument = slot_name, target = 'character', arg_name = 'slot_name') check_string(argument = slot_name, target = slotNames(obj), arg_name = 'slot_name') check_length(argument = slot_name, max_allow = 1, arg_name = 'slot_name') out <- eval( parse( text = paste0('obj', '@', slot_name) ) ) return(out) } ) setMethod(f = 'hm_get', signature = 'hydromet_station', definition = function(obj, slot_name = NA_character_) { check_class(argument = obj, target = 'hydromet_station', arg_name = 'obj') check_class(argument = slot_name, target = 'character', arg_name = 'slot_name') check_string(argument = slot_name, target = slotNames(obj), arg_name = 'slot_name') check_length(argument = slot_name, max_allow = 1, arg_name = 'slot_name') out <- eval( parse( text = paste0('obj', '@', slot_name) ) ) return(out) } ) setMethod(f = 'hm_get', signature = 'hydromet_compact', definition = function(obj, slot_name = NA_character_) { check_class(argument = obj, target = 'hydromet_compact', arg_name = 'obj') check_class(argument = slot_name, target = 'character', arg_name = 'slot_name') check_string(argument = slot_name, target = slotNames(obj), arg_name = 'slot_name') check_length(argument = slot_name, max_allow = 1, arg_name = 'slot_name') out <- eval( parse( text = paste0('obj', '@', slot_name) ) ) return(out) } )
stopifnot(all.equal( exp(stat.extend:::lsubfactorial(1:7)), c(0, 1, 2, 9, 44, 265, 1854) )) stopifnot(all.equal( exp(stat.extend:::lsubfactorial(c(0, NA, 2, -1, 3))), c(1, NA, 1, NA, 2) ))
context("Statistical meta-features") test_that("statistical.result", { aux = statistical(Species ~ ., iris) expect_named(aux, ls.statistical()) expect_equal(aux, statistical(iris[1:4], iris[5])) expect_named(statistical(Species ~ ., iris, ls.statistical()[1:3]), ls.statistical()[1:3]) }) test_that("byclass.result", { aux = statistical(Species ~ ., iris, by.class=TRUE) expect_named(aux, ls.statistical()) expect_equal(aux, statistical(iris[1:4], iris[5], by.class=TRUE)) expect_named(statistical(Species ~ ., iris, ls.statistical()[1:3]), ls.statistical()[1:3]) }) test_that("statistical.transform", { aux <- cbind(class=iris$Species, iris) expect_equal( statistical(Species ~ ., aux, ls.statistical()[1:5], transform=FALSE), statistical(Species ~ ., iris, ls.statistical()[1:5], transform=FALSE) ) expect_false(isTRUE(all.equal( statistical(Species ~ ., aux, "sp", transform=FALSE), statistical(Species ~ ., iris, "sp", transform=FALSE) ))) }) test_that("statistical.errors",{ expect_error(statistical(iris[1:130, 1:4], iris[5])) expect_error(statistical(as.matrix(iris[, c(1,2)]), iris$Species)) expect_error(statistical(Species ~ ., iris, features=c("abc", "xdef"))) })
context("util") test_that("template filler", { tmpl = "this is my {{ template }}" values = list(template = "filled") filled = fill_template(tmpl, values) expect_equal(filled, "this is my filled") expect_error(fill_template(tmpl, list(key="unrelated"))) }) test_that("template default values", { tmpl = "this is my {{ template | default }}" values = list(template = "filled") filled1 = fill_template(tmpl, values) expect_equal(filled1, "this is my filled") filled2 = fill_template(tmpl, list()) expect_equal(filled2, "this is my default") }) test_that("template required key", { tmpl = "this is my {{ template }}" values = list(template = "filled") expect_error(fill_template(tmpl, values, required="missing")) })
library(dplyr) library(magrittr) library(jsonlite) library(data.table) scale01 = function(x){ scaleToInt(x,1,0) } scaleToInt = function(x, max,min){ scaleFun = scaleIntervals(max(x),min(x),max,min) scaleFun(x) } scaleIntervals = function(max,min,maxOut,minOut){ a = (max - min)/(maxOut - minOut) b = max - maxOut*a hede = teval(paste0("function(x){(x - ",b,")/",a,'}')) hede } trimNAs = function(aVector) { return(aVector[!is.na(aVector)]) } teval = function(daString){ eval(parse(text=daString)) } returnGameData = function(gameID){ playByPlay = fread('data/playByPlayTrim.csv',stringsAsFactors = F,data.table = F) games = fread('data/cfl_games_trim.csv',data.table=F) games %<>% filter(sked_id==gameID) playByPlay %<>% filter(game_id==gameID) %>% arrange(play_id) playByPlay$secondsQuarter = playByPlay$time %>% strsplit(':') %>% sapply(function(x){ x %<>% as.numeric() 900 - (x[1]*60*60 + x[2]*60 + x[3]) }) + playByPlay$play_id * 0.00001 playByPlay %<>% mutate(secondsTotal = secondsQuarter + (quarter-1)*15*60) home = games$home_initial homeID = games$home_id toYardFromHome = function(x){ x %>% sapply(function(x){ team = gsub("([0-9])*",'',x) yard = gsub("([A-Z]|[a-z])*",'',x) %>% as.numeric if (tolower(team)==home){ return(yard) } else { return(110-yard) } }) } playByPlay$yardsFromHome = playByPlay$yardline %>% toYardFromHome playByPlay$end_yardsFromHome = playByPlay$end_yardline %>% toYardFromHome playByPlay %<>% mutate(homeIsHappy = home_score_after - home_score_before, awayIsHappy = away_score_after - away_score_before, isHome = playByPlay$end_possession_id == homeID) playByPlay$epicEvent = playByPlay$name playByPlay$epicEvent[playByPlay$homeIsHappy >0 | playByPlay$awayIsHappy > 0] = 'SCORE!!!111' playByPlay$epicEvent[!(playByPlay$epicEvent %in% c('Pass','Rush') | playByPlay$homeIsHappy>0 | playByPlay$awayIsHappy >0)] = NA playByPlay$epicness = 0 playByPlay$epicness[is.na(playByPlay$epicEvent)] = -9999 playByPlay$epicness[playByPlay$homeIsHappy > 0 | playByPlay$awayIsHappy > 0] = 10 playByPlay$epicness[playByPlay$homeIsHappy > 1 | playByPlay$awayIsHappy > 1] = 15 playByPlay$epicness[playByPlay$homeIsHappy > 2 | playByPlay$awayIsHappy > 2] = 20 playByPlay$epicness[playByPlay$homeIsHappy ==6 | playByPlay$awayIsHappy ==6 ] = 30 outliers = (trimNAs(playByPlay$yards[playByPlay$epicness ==0]) %>% boxplot %>% .$out) outliers = outliers[outliers>0] outIds = playByPlay$play_id[playByPlay$epicness ==0][playByPlay$yards[playByPlay$epicness ==0] %in% outliers] playByPlay$epicness[playByPlay$play_id %in% outIds] = 20 playByPlay$epicness[ playByPlay$epicness ==0] = (((playByPlay$yards[playByPlay$epicness==0] %>% scale01)*8 ))+5 playByPlay$epicness[playByPlay$epicness == -9999] = NA location = games$home_team if (location == "BC"){ location = 'Vancouver' } return(list(playByPlay = playByPlay, game = games)) }
context("canvasXpress Charts - Precalculated Barplot") precalc.data <- data.frame(mean = c(5, 50, 250, 100, NA), stdev = c(20, 10, 20, 15, NA), stringsAsFactors = F, row.names = c("Group1", "Group2", "Group3", "Group4", "Missing")) precalc.data.l <- as.list(precalc.data) precalc.data <- as.data.frame(t(precalc.data)) smp.data <- data.frame(level = c("Lev1", "Lev2", "Lev3", "Lev4", "NA"), stringsAsFactors = F) rownames(smp.data) <- colnames(precalc.data) test_that("precalculated barplot - dataframe data", { result <- canvasXpress(data = precalc.data, graphType = "Bar", graphOrientation = "vertical", smpLabelFontStyle = "italic", smpLabelRotate = 90, showLegend = FALSE, title = "Precalculated barplot - data without smpAnnot", titleScaleFontFactor = 0.5) check_ui_test(result) result <- canvasXpress(data = precalc.data, smpAnnot = smp.data, graphType = "Bar", graphOrientation = "vertical", smpLabelFontStyle = "italic", smpLabelRotate = 90, showLegend = FALSE, title = "Precalculated barplot - data with smpAnnot", titleScaleFontFactor = 0.5) check_ui_test(result) }) test_that("precalculated barplot - list data", { result <- canvasXpress(data = precalc.data.l, graphType = "Bar", graphOrientation = "vertical", smpLabelFontStyle = "italic", smpLabelRotate = 90, showLegend = FALSE, title = "Precalculated barplot - list data without smpAnnot", titleScaleFontFactor = 0.5) check_ui_test(result) result <- canvasXpress(data = precalc.data.l, smpAnnot = colnames(precalc.data), graphType = "Bar", graphOrientation = "vertical", smpLabelFontStyle = "italic", smpLabelRotate = 90, showLegend = FALSE, title = "Precalculated barplot - list data with smpAnnot", titleScaleFontFactor = 0.5) check_ui_test(result) result <- canvasXpress(data = precalc.data.l, smpAnnot = smp.data, graphType = "Bar", graphOrientation = "vertical", smpLabelFontStyle = "italic", smpLabelRotate = 90, showLegend = FALSE, title = "Precalculated barplot - list data with smpAnnot", titleScaleFontFactor = 0.5) check_ui_test(result) })
"diffChange" <- function (modellist, diffsadd) { for(diffs in diffsadd) { if(length(diffs$type) == 0) diffs$type <- "perd" for(i in 1:length(diffs$dataset)) slot(modellist[[diffs$dataset[i] ]], diffs$what) <- diffs$spec } newl <- list() for(i in 1:length(diffsadd)) { if(length(diffsadd[[i]]$type) == 0) diffsadd[[i]]$type <- "perdataset" if(diffsadd[[i]]$type == "multifree") { for(j in 1:length(diffsadd[[i]]$dataset)){ newl[[length(newl)+1]] <- diffsadd[[i]] newl[[length(newl)]]$dataset <- diffsadd[[i]]$dataset[j] } } else newl[[length(newl)+1]] <- diffsadd[[i]] } list(modellist=modellist, diffsadd = newl) }
url_to_json <- function(url) url |> throttle() |> utils::URLencode() |> readLines(warn = FALSE) |> RJSONIO::fromJSON() |> tryCatch(error = function(e) stop("Cannot read from Reddit, check your inputs or internet connection"))
context("standard bootstrap test: regression, single mediator, covariates") library("robmed", quietly = TRUE) n <- 250 a <- c <- 0.2 b <- 0 R <- 1000 seed <- 20150601 set.seed(seed) X <- rnorm(n) M <- a * X + rnorm(n) Y <- b * M + c * X + rnorm(n) C1 <- rnorm(n) C2 <- rnorm(n) test_data <- data.frame(X, Y, M, C1, C2) set.seed(seed) level <- c(0.9, 0.95) boot <- test_mediation(test_data, x = "X", y = "Y", m = "M", covariates = c("C1", "C2"), test = "boot", R = R, level = level[1], type = "bca", method = "regression", robust = FALSE) summary_boot <- summary(boot, type = "boot") summary_data <- summary(boot, type = "data") boot_less <- retest(boot, alternative = "less", level = level[2]) boot_greater <- retest(boot, alternative = "greater", level = level[2]) boot_perc <- retest(boot, type = "perc", level = level[2]) ci <- setup_ci_plot(boot) ci_perc <- setup_ci_plot(boot_perc, p_value = TRUE) density <- setup_density_plot(boot) ellipse <- setup_ellipse_plot(boot) coef_names <- c("a", "b", "Direct", "Total", "ab") mx_names <- c("(Intercept)", "X", "C1", "C2") ymx_names <- c("(Intercept)", "M", "X", "C1", "C2") test_that("output has correct structure", { expect_s3_class(boot, "boot_test_mediation") expect_s3_class(boot, "test_mediation") expect_s3_class(boot$fit, "reg_fit_mediation") expect_s3_class(boot$fit, "fit_mediation") expect_s3_class(boot$reps, "boot") }) test_that("arguments are correctly passed", { expect_identical(boot$alternative, "twosided") expect_identical(boot$R, as.integer(R)) expect_identical(boot$level, level[1]) expect_identical(boot$type, "bca") expect_identical(boot$fit$x, "X") expect_identical(boot$fit$y, "Y") expect_identical(boot$fit$m, "M") expect_identical(boot$fit$covariates, c("C1", "C2")) expect_false(boot$fit$robust) expect_identical(boot$fit$family, "gaussian") expect_null(boot$fit$control) }) test_that("dimensions are correct", { expect_length(boot$ab, 1L) expect_length(boot$ci, 2L) d_boot <- dim(boot$reps$t) expect_identical(d_boot, c(as.integer(R), 11L)) }) test_that("values of coefficients are correct", { expect_equivalent(boot$ab, mean(boot$reps$t[, 1])) }) test_that("output of coef() method has correct attributes", { coef_boot <- coef(boot, type = "boot") coef_data <- coef(boot, type = "data") expect_length(coef_boot, 5L) expect_named(coef_boot, coef_names) expect_length(coef_data, 5L) expect_named(coef_data, coef_names) }) test_that("coef() method returns correct values of coefficients", { expect_equivalent(coef(boot, parm = "a", type = "boot"), mean(boot$reps$t[, 3])) expect_equivalent(coef(boot, parm = "b", type = "boot"), mean(boot$reps$t[, 7])) expect_equivalent(coef(boot, parm = "Direct", type = "boot"), mean(boot$reps$t[, 8])) expect_equivalent(coef(boot, parm = "Total", type = "boot"), mean(boot$reps$t[, 11])) expect_equivalent(coef(boot, parm = "ab", type = "boot"), boot$ab) expect_equivalent(coef(boot, parm = "a", type = "data"), boot$fit$a) expect_equivalent(coef(boot, parm = "b", type = "data"), boot$fit$b) expect_equivalent(coef(boot, parm = "Direct", type = "data"), boot$fit$direct) expect_equivalent(coef(boot, parm = "Total", type = "data"), boot$fit$total) expect_equivalent(coef(boot, parm = "ab", type = "data"), boot$fit$a * boot$fit$b) }) test_that("output of confint() method has correct attributes", { ci_boot <- confint(boot, type = "boot") ci_data <- confint(boot, type = "data") expect_equal(dim(ci_boot), c(5L, 2L)) expect_equal(rownames(ci_boot), coef_names) expect_equal(colnames(ci_boot), c("5 %", "95 %")) expect_equal(dim(ci_data), c(5L, 2L)) expect_equal(rownames(ci_data), coef_names) expect_equal(colnames(ci_data), c("5 %", "95 %")) }) test_that("confint() method returns correct values of confidence intervals", { expect_equivalent(confint(boot, parm = "ab", type = "boot"), boot$ci) expect_equivalent(confint(boot, parm = "ab", type = "data"), boot$ci) }) test_that("summary has correct structure", { expect_s3_class(summary_boot, "summary_test_mediation") expect_s3_class(summary_data, "summary_test_mediation") expect_identical(summary_boot$object, boot) expect_identical(summary_data$object, boot) expect_s3_class(summary_boot$summary, "summary_reg_fit_mediation") expect_s3_class(summary_boot$summary, "summary_fit_mediation") expect_s3_class(summary_data$summary, "summary_reg_fit_mediation") expect_s3_class(summary_data$summary, "summary_fit_mediation") expect_s3_class(summary_boot$summary$fit_mx, "summary_lm") expect_s3_class(summary_boot$summary$fit_ymx, "summary_lm") expect_type(summary_boot$summary$fit_ymx$s, "list") expect_named(summary_boot$summary$fit_ymx$s, c("value", "df")) expect_type(summary_data$summary$fit_ymx$s, "list") expect_named(summary_data$summary$fit_ymx$s, c("value", "df")) expect_type(summary_boot$summary$fit_ymx$R2, "list") expect_named(summary_boot$summary$fit_ymx$R2, c("R2", "adj_R2")) expect_type(summary_data$summary$fit_ymx$R2, "list") expect_named(summary_data$summary$fit_ymx$R2, c("R2", "adj_R2")) expect_type(summary_boot$summary$fit_ymx$F_test, "list") expect_named(summary_boot$summary$fit_ymx$F_test, c("statistic", "df", "p_value")) df_test_boot <- summary_boot$summary$fit_ymx$F_test$df expect_identical(df_test_boot[1], 4L) expect_identical(df_test_boot[2], summary_boot$summary$fit_ymx$s$df) expect_type(summary_data$summary$fit_ymx$F_test, "list") expect_named(summary_data$summary$fit_ymx$F_test, c("statistic", "df", "p_value")) df_test_data <- summary_data$summary$fit_ymx$F_test$df expect_identical(df_test_data[1], 4L) expect_identical(df_test_data[2], summary_data$summary$fit_ymx$s$df) expect_null(summary_boot$plot) expect_null(summary_data$plot) }) test_that("attributes are correctly passed through summary", { expect_false(summary_boot$summary$robust) expect_false(summary_data$summary$robust) expect_identical(summary_boot$summary$n, as.integer(n)) expect_identical(summary_data$summary$n, as.integer(n)) expect_identical(summary_boot$summary$x, "X") expect_identical(summary_boot$summary$y, "Y") expect_identical(summary_boot$summary$m, "M") expect_identical(summary_boot$summary$covariates, c("C1", "C2")) expect_identical(summary_data$summary$x, "X") expect_identical(summary_data$summary$y, "Y") expect_identical(summary_data$summary$m, "M") expect_identical(summary_data$summary$covariates, c("C1", "C2")) }) test_that("effect summaries have correct names", { expect_identical(dim(summary_boot$summary$fit_mx$coefficients), c(4L, 5L)) expect_identical(rownames(summary_boot$summary$fit_mx$coefficients), mx_names) expect_identical(colnames(summary_boot$summary$fit_mx$coefficients)[1:2], c("Data", "Boot")) expect_identical(dim(summary_data$summary$fit_mx$coefficients), c(4L, 4L)) expect_identical(rownames(summary_data$summary$fit_mx$coefficients), mx_names) expect_identical(colnames(summary_data$summary$fit_mx$coefficients)[1], "Estimate") expect_identical(dim(summary_boot$summary$fit_ymx$coefficients), c(5L, 5L)) expect_identical(rownames(summary_boot$summary$fit_ymx$coefficient), ymx_names) expect_identical(colnames(summary_boot$summary$fit_ymx$coefficient)[1:2], c("Data", "Boot")) expect_identical(dim(summary_data$summary$fit_ymx$coefficient), c(5L, 4L)) expect_identical(rownames(summary_data$summary$fit_ymx$coefficient), ymx_names) expect_identical(colnames(summary_data$summary$fit_ymx$coefficient)[1], "Estimate") expect_identical(dim(summary_boot$summary$direct), c(1L, 5L)) expect_identical(rownames(summary_boot$summary$direct), "X") expect_identical(colnames(summary_boot$summary$direct)[1:2], c("Data", "Boot")) expect_identical(dim(summary_data$summary$direct), c(1L, 4L)) expect_identical(rownames(summary_data$summary$direct), "X") expect_identical(colnames(summary_data$summary$direct)[1], "Estimate") expect_identical(dim(summary_boot$summary$total), c(1L, 5L)) expect_identical(rownames(summary_boot$summary$total), "X") expect_identical(colnames(summary_boot$summary$total)[1:2], c("Data", "Boot")) expect_identical(dim(summary_data$summary$total), c(1L, 4L)) expect_identical(rownames(summary_data$summary$total), "X") expect_identical(colnames(summary_data$summary$total)[1], "Estimate") }) test_that("effect summaries contain correct coefficient values", { expect_equivalent(summary_boot$summary$fit_mx$coefficients[2, "Data"], boot$fit$a) expect_identical(summary_boot$summary$fit_ymx$coefficients[2, "Data"], boot$fit$b) expect_identical(summary_boot$summary$direct["X", "Data"], boot$fit$direct) expect_identical(summary_boot$summary$total["X", "Data"], boot$fit$total) expect_equivalent(summary_data$summary$fit_mx$coefficients[2, "Estimate"], boot$fit$a) expect_identical(summary_data$summary$fit_ymx$coefficients[2, "Estimate"], boot$fit$b) expect_identical(summary_data$summary$direct["X", "Estimate"], boot$fit$direct) expect_identical(summary_data$summary$total["X", "Estimate"], boot$fit$total) expect_equivalent(summary_boot$summary$fit_mx$coefficients[2, "Boot"], mean(boot$reps$t[, 3])) expect_equivalent(summary_boot$summary$fit_ymx$coefficients[2, "Boot"], mean(boot$reps$t[, 7])) expect_equal(summary_boot$summary$direct["X", "Boot"], mean(boot$reps$t[, 8])) expect_equal(summary_boot$summary$total["X", "Boot"], mean(boot$reps$t[, 11])) }) test_that("output of retest() has correct structure", { expect_identical(class(boot_less), class(boot)) expect_identical(class(boot_greater), class(boot)) expect_identical(class(boot_perc), class(boot)) expect_identical(boot_less$fit, boot$fit) expect_identical(boot_greater$fit, boot$fit) expect_identical(boot_perc$fit, boot$fit) expect_identical(boot_less$reps, boot$reps) expect_identical(boot_greater$reps, boot$reps) expect_identical(boot_perc$reps, boot$reps) }) test_that("arguments of retest() are correctly passed", { expect_identical(boot_less$alternative, "less") expect_identical(boot_greater$alternative, "greater") expect_identical(boot_perc$alternative, "twosided") expect_identical(boot_less$level, level[2]) expect_identical(boot_greater$level, level[2]) expect_identical(boot_perc$level, level[2]) expect_identical(boot_less$type, "bca") expect_identical(boot_greater$type, "bca") expect_identical(boot_perc$type, "perc") expect_identical(boot_less$ab, boot$ab) expect_identical(boot_greater$ab, boot$ab) expect_identical(boot_perc$ab, boot$ab) expect_identical(length(boot_less$ci), length(boot$ci)) expect_equivalent(boot_less$ci[1], -Inf) expect_equal(boot_less$ci[2], boot$ci[2]) expect_identical(colnames(confint(boot_less)), c("Lower", "Upper")) expect_identical(length(boot_greater$ci), length(boot$ci)) expect_equal(boot_greater$ci[1], boot$ci[1]) expect_equivalent(boot_greater$ci[2], Inf) expect_identical(colnames(confint(boot_greater)), c("Lower", "Upper")) expect_identical(length(boot_perc$ci), length(boot$ci)) }) test_that("output of p_value() method has correct attributes", { digits <- 3 p_boot <- p_value(boot_perc, type = "boot", digits = digits) p_data <- p_value(boot_perc, type = "data", digits = digits) expect_length(p_boot, 5L) expect_named(p_boot, coef_names) expect_equal(p_boot["ab"], round(p_boot["ab"], digits = digits)) expect_length(p_data, 5L) expect_named(p_data, coef_names) expect_equal(p_data["ab"], round(p_data["ab"], digits = digits)) }) test_that("objects returned by setup_xxx_plot() have correct structure", { expect_s3_class(ci$ci, "data.frame") expect_identical(dim(ci$ci), c(2L, 4L)) expect_named(ci$ci, c("Effect", "Estimate", "Lower", "Upper")) effect_names <- c("Direct", "ab") effect_factor <- factor(effect_names, levels = effect_names) expect_identical(ci$ci$Effect, effect_factor) expect_identical(ci$level, level[1]) expect_false(ci$have_methods) expect_s3_class(ci_perc$ci, "data.frame") expect_s3_class(ci_perc$p_value, "data.frame") expect_identical(dim(ci_perc$ci), c(2L, 5L)) expect_identical(dim(ci_perc$p_value), c(2L, 3L)) expect_named(ci_perc$ci, c("Label", "Effect", "Estimate", "Lower", "Upper")) expect_named(ci_perc$p_value, c("Label", "Effect", "Value")) label_names <- c("Confidence interval", "p-Value") expect_identical(ci_perc$ci$Label, factor(rep.int(label_names[1], 2), levels = label_names)) expect_identical(ci_perc$p_value$Label, factor(rep.int(label_names[2], 2), levels = label_names)) effect_names <- c("Direct", "ab") effect_factor <- factor(effect_names, levels = effect_names) expect_identical(ci_perc$ci$Effect, effect_factor) expect_identical(ci_perc$p_value$Effect, effect_factor) expect_identical(ci$level, level[1]) expect_false(ci$have_methods) expect_s3_class(density$density, "data.frame") expect_identical(ncol(density$density), 2L) expect_gt(nrow(density$density), 0L) expect_named(density$density, c("ab", "Density")) expect_s3_class(density$ci, "data.frame") expect_identical(dim(density$ci), c(1L, 3L)) expect_named(density$ci, c("Estimate", "Lower", "Upper")) expect_identical(density$test, "boot") expect_identical(density$level, level[1]) expect_false(density$have_effect) expect_false(density$have_methods) expect_identical(ellipse, setup_ellipse_plot(boot$fit)) expect_error(setup_weight_plot(boot)) }) set.seed(seed) boot_f1 <- test_mediation(Y ~ m(M) + X + covariates(C1, C2), data = test_data, test = "boot", R = R, level = 0.9, type = "bca", method = "regression", robust = FALSE) set.seed(seed) boot_f2 <- test_mediation(Y ~ m(M) + X + covariates(C1, C2), test = "boot", R = R, level = 0.9, type = "bca", method = "regression", robust = FALSE) med <- m(M) cov <- covariates(C1, C2) set.seed(seed) boot_f3 <- test_mediation(Y ~ med + X + cov, data = test_data, test = "boot", R = R, level = 0.9, type = "bca", method = "regression", robust = FALSE) test_that("formula interface works correctly", { expect_equal(boot_f1, boot) expect_equal(boot_f2, boot) expect_equal(boot_f3, boot) })
res_boot1 <- resampleData(.data = satisfaction) str(res_boot1, max.level = 3, list.len = 3) res_boot1a <- resampleData(.data = satisfaction, .seed = 2364) res_boot1b <- resampleData(.data = satisfaction, .seed = 2364) identical(res_boot1, res_boot1a) res_jack <- resampleData(.data = satisfaction, .resample_method = "jackknife") str(res_jack, max.level = 3, list.len = 3) dat <- data.frame( "x1" = rnorm(100), "x2" = rnorm(100), "group" = sample(c("male", "female"), size = 100, replace = TRUE), stringsAsFactors = FALSE) cv_10a <- resampleData(.data = dat, .resample_method = "cross-validation", .R = 100) str(cv_10a, max.level = 3, list.len = 3) cv_10 <- resampleData(.data = dat, .resample_method = "cross-validation", .id = "group", .R = 100) cv_loocv <- resampleData(.data = dat[, -3], .resample_method = "cross-validation", .cv_folds = nrow(dat), .R = 50) str(cv_loocv, max.level = 2, list.len = 3) res_perm <- resampleData(.data = dat, .resample_method = "permutation", .id = "group") str(res_perm, max.level = 2, list.len = 3) \dontrun{ res_perm <- resampleData(.data = dat, .resample_method = "permutation") } model <- " QUAL ~ EXPE EXPE ~ IMAG SAT ~ IMAG + EXPE + QUAL + VAL LOY ~ IMAG + SAT VAL ~ EXPE + QUAL EXPE =~ expe1 + expe2 + expe3 + expe4 + expe5 IMAG =~ imag1 + imag2 + imag3 + imag4 + imag5 LOY =~ loy1 + loy2 + loy3 + loy4 QUAL =~ qual1 + qual2 + qual3 + qual4 + qual5 SAT =~ sat1 + sat2 + sat3 + sat4 VAL =~ val1 + val2 + val3 + val4 " a <- csem(satisfaction, model) res_boot <- resampleData(a, .resample_method = "bootstrap", .R = 499) res_jack <- resampleData(a, .resample_method = "jackknife") res_boot_data <- resampleData(.data = satisfaction, .seed = 2364) res_boot_object <- resampleData(a, .seed = 2364) identical(res_boot_data, res_boot_object)
latlong_footprint <- function(departure_lat, departure_long, arrival_lat, arrival_long, flightClass = "Unknown", output = "co2e") { if (!(all(is.numeric(c(departure_long, arrival_long))) && departure_long >= -180 && arrival_long >= -180 && departure_long <= 180 && arrival_long <= 180)) { stop("Airport longitude must be numeric and has values between -180 and 180") } if (!(all(is.numeric(c(departure_lat, arrival_lat))) && departure_lat >= -90 && arrival_lat >= -90 && departure_lat <= 90 && arrival_lat <= 90)) { stop("Airport latitude must be numeric and has values between -90 and 90") } lon1 = departure_long * pi / 180 lat1 = departure_lat * pi / 180 lon2 = arrival_long * pi / 180 lat2 = arrival_lat * pi / 180 radius = 6373 dlon = lon2 - lon1 dlat = lat2 - lat1 a = (sin(dlat / 2)) ^ 2 + cos(lat1) * cos(lat2) * (sin(dlon / 2)) ^ 2 b = 2 * atan2(sqrt(a), sqrt(1 - a)) distance = radius * b distance_type <- dplyr::case_when(distance <= 483 ~ "short", distance >= 3700 ~ "long", TRUE ~ "medium") emissions_vector <- conversion_factors %>% dplyr::filter(.data$distance == distance_type) %>% dplyr::filter(.data$flightclass == flightClass) %>% dplyr::pull(output) round(distance * emissions_vector, 3) }
count.excellent <- function(indices){ rmseaE <- ifelse(indices[4] < .05, 1, 0) srmrE <- ifelse(indices[5] < .05, 1, 0) nnfiE <- ifelse(indices[6] > .95, 1, 0) cfiE <- ifelse(indices[7] > .95, 1, 0) excellent <- sum(rmseaE, srmrE, nnfiE, cfiE, na.rm = TRUE) return(excellent) }
ray <- function(betam, u, lat, x0, y0, K, dt, itime, direction, interpolation = "trin", tl = 1, a = 6371000, verbose = FALSE, ofile){ dt <- dt * 60 * 60 if(!is.unsorted(lat)) { message("Sorting latitude from north to south") betamz <- rev(colMeans(betam, na.rm = TRUE)) uz <- rev(colMeans(u, na.rm = TRUE)) lat <- lat[order(lat, decreasing = TRUE)] } else { betamz <- colMeans(betam, na.rm = TRUE) uz <- colMeans(u, na.rm = TRUE) } phirad <- lat*pi/180 k <- K/a k2 <- (K/a)^2 x_ini <- x0 y_ini <- y0 l_time <- list() l_x0 <- list() l_y0 <- list() count <- 0 while(TRUE) { count <- count + 1 if(abs(y0) > 90) break if(interpolation == "trin") { beta_y0 <- trin(y = y0, yk = betamz) u_y0 <- trin(y = y0, yk = uz, mercator = TRUE) } else if(interpolation == "ypos"){ beta_y0 <- ypos(y = y0, lat = lat, yk = betamz) u_y0 <- ypos(y = y0, lat = lat, yk = uz, mercator = TRUE) } Ks2_y0 <- beta_y0/u_y0 l2_y0 <- Ks2_y0 - k2 if(count == 1 & l2_y0 < 0) next if(round(l2_y0, 13) <= 0) tl <- -1 if(Ks2_y0 < 0) break ug0 <-(2 * beta_y0 * k2 / Ks2_y0^2 ) * 180 / (a*pi) vg0 <- (direction * tl * 2 * beta_y0 * k * sqrt(abs(l2_y0))* cos(y0*pi/180)/Ks2_y0^2)*(180/(pi*a)) y1 <- y0 + dt*vg0 if(interpolation == "trin") { beta_y1 <- trin(y = y1, yk = betamz) u_y1 <- trin(y = y1, yk = uz, mercator = TRUE) } else if(interpolation == "ypos"){ beta_y1 <- ypos(y = y1, lat = lat, yk = betamz) u_y1 <- ypos(y = y1, lat = lat, yk = uz, mercator = TRUE) } Ks2_y1 <- beta_y1/u_y1 l2_y1 <- Ks2_y1 - k2 if(count == 1 & l2_y1 < 0) next if(round(l2_y1, 13) < 0) tl <- -1 if(Ks2_y1 < 0) break ug1 <- (2 * beta_y1 * k2 / Ks2_y1^2 ) * 180 / (a*pi) vg1 <- (direction * tl * 2 * beta_y1 * k * sqrt(abs(l2_y1))* cos(y1*pi/180)/Ks2_y1^2)*(180/(pi*a)) x2 <- x0 + 0.5*dt*(ug0+ug1) y2 <- y0 + 0.5*dt*(vg0+vg1) x0 <- x2 y0 <- y2 l_time[[count]] <- count l_x0[[count]] <- x0 l_y0[[count]] <- y0 if(count == itime) break } count <- c(0, unlist(l_time)) df <- data.frame( K = K, lat_ini = y_ini, lon_ini = x_ini, time = dt*count/(60*60), iday = rep(seq(0, 23, dt/(60*60)), length(count))[1:length(count)], lat = c(y_ini, unlist(l_y0)), lon = c(x_ini, unlist(l_x0)) ) df$lon_shift <- ifelse(df$lon < 0, df$lon + 360, df$lon) df$y0 <- df$lat df$x0 <- df$lon pontos <- sf::st_as_sf(df, coords = c("x0", "y0"), crs = 4326) if(!missing(ofile)) { utils::write.csv(x = pontos, file = ofile, row.names = FALSE) } return(pontos) }
library(RcppHNSW) context("search with small test set") index <- hnsw_build(ui10) expect_equal(index$size(), 10) res <- hnsw_search(ui10[1, , drop = FALSE], index, k = 4) expect_equal(res$idx, self_nn_index4[1, , drop = FALSE], tol = 1e-6) expect_equal(res$dist, self_nn_dist4[1, , drop = FALSE], tol = 1e-6) expect_error(hnsw_search(ui10[1, , drop = FALSE], index, k = 500)) index$markDeleted(1) res <- hnsw_search(ui10[1, , drop = FALSE], index, k = 4) expect_equal(res$idx[1, ], c(6, 10, 3, 7), tol = 1e-6) expect_equal(res$dist[1, ], c(self_nn_dist4[1, 2:4], 0.812404), tol = 1e-6) expect_error(index$markDeleted(0)) expect_error(index$markDeleted(11))
preview.pls <- function(x, y, L, scale.x = TRUE, scale.y = TRUE){ if (class(x) != "list") { stop("x should be of list type.") } if (class(y) != "list") { stop("y should be of list type.") } x <- lapply(x, as.matrix) y <- lapply(y, as.matrix) nl <- as.numeric(lapply(x, nrow)) pl <- as.numeric(lapply(x, ncol)) ql <- as.numeric(lapply(y, ncol)) p <- unique(pl) q <- unique(ql) if(length(p) > 1){ stop("The dimension of data x should be consistent among different datasets.")} if(length(q) > 1){ stop("The dimension of data y should be consistent among different datasets.")} ip <- c(1:p) meanx <- lapply(1:L, function(l) drop( matrix(1, 1, nl[l]) %*% x[[l]] / nl[l] ) ) meany <- lapply(1:L, function(l) drop( matrix(1, 1, nl[l]) %*% y[[l]] / nl[l] ) ) x <- lapply(1:L, function(l) scale(x[[l]], meanx[[l]], FALSE) ) y <- lapply(1:L, function(l) scale(y[[l]], meany[[l]], FALSE) ) x.scale <- function(l){ one <- matrix(1, 1, nl[l]) normx <- sqrt(drop(one %*% (x[[l]]^2)) / (nl[l] - 1)) if (any(normx < .Machine$double.eps)) { stop("Some of the columns of the predictor matrix have zero variance.") } return(normx) } y.scale <- function(l){ one <- matrix(1, 1, nl[l]) normy <- sqrt(drop(one %*% (y[[l]]^2)) / (nl[l] - 1)) if (any(normy < .Machine$double.eps)) { stop("Some of the columns of the response matrix have zero variance.") } return(normy) } if (scale.x) { normx <- lapply(1:L, x.scale ) } else { normx <- rep(list(rep(1,p)), L) } if (scale.y) { normy <- lapply(1:L, y.scale ) } else { normy <- rep(list(rep(1,q)), L) } if (scale.x) { x <- lapply(1:L, function(l) scale(x[[l]], FALSE, normx[[l]]) ) } if (scale.y) { y <- lapply(1:L, function(l) scale(y[[l]], FALSE, normy[[l]]) ) } fun.1 <- function(l) { Z_l <- t(x[[l]]) %*% y[[l]] Z_l <- Z_l / nl[l] } Z <- matrix(mapply(fun.1, c(1:L)), nrow = p) c <- mapply(function(l) svd(Z[, ((l - 1) * q + 1):(l * q)] %*% t(Z[, ((l - 1) * q + 1):(l * q)] ), nu = 1)$u, 1:L) what <- c listname <- mapply(function(l) paste("Dataset ", l), 1:L) names(meanx) <- listname names(meany) <- listname names(normx) <- listname names(normy) <- listname names(x) <- listname names(y) <- listname for (l in 1:L) { plot(x = 1:p, y = as.numeric(what[,l]), main = paste("Dataset ", l, "\n", "The first direction vector"), xlab = "Dimension", ylab = "Value", pch = 15) } object <- list( x = x, y = y, loading = what, meanx = meanx, normx = normx, meany = meany, normy = normy ) class(object) <- "preview.spls" return(object) }
extractCTDC <- function(x) { if (protcheck(x) == FALSE) { stop("x has unrecognized amino acid type") } group1 <- list( "hydrophobicity" = c("R", "K", "E", "D", "Q", "N"), "normwaalsvolume" = c("G", "A", "S", "T", "P", "D", "C"), "polarity" = c("L", "I", "F", "W", "C", "M", "V", "Y"), "polarizability" = c("G", "A", "S", "D", "T"), "charge" = c("K", "R"), "secondarystruct" = c("E", "A", "L", "M", "Q", "K", "R", "H"), "solventaccess" = c("A", "L", "F", "C", "G", "I", "V", "W") ) group2 <- list( "hydrophobicity" = c("G", "A", "S", "T", "P", "H", "Y"), "normwaalsvolume" = c("N", "V", "E", "Q", "I", "L"), "polarity" = c("P", "A", "T", "G", "S"), "polarizability" = c("C", "P", "N", "V", "E", "Q", "I", "L"), "charge" = c( "A", "N", "C", "Q", "G", "H", "I", "L", "M", "F", "P", "S", "T", "W", "Y", "V" ), "secondarystruct" = c("V", "I", "Y", "C", "W", "F", "T"), "solventaccess" = c("R", "K", "Q", "E", "N", "D") ) group3 <- list( "hydrophobicity" = c("C", "L", "V", "I", "M", "F", "W"), "normwaalsvolume" = c("M", "H", "K", "F", "R", "Y", "W"), "polarity" = c("H", "Q", "R", "K", "N", "E", "D"), "polarizability" = c("K", "M", "H", "F", "R", "Y", "W"), "charge" = c("D", "E"), "secondarystruct" = c("G", "N", "P", "S", "D"), "solventaccess" = c("M", "S", "P", "T", "H", "Y") ) xSplitted <- strsplit(x, split = "")[[1]] n <- nchar(x) g1 <- lapply(group1, function(g) length(which(xSplitted %in% g))) names(g1) <- paste(names(g1), "Group1", sep = ".") g2 <- lapply(group2, function(g) length(which(xSplitted %in% g))) names(g2) <- paste(names(g2), "Group2", sep = ".") g3 <- lapply(group3, function(g) length(which(xSplitted %in% g))) names(g3) <- paste(names(g3), "Group3", sep = ".") CTDC <- unlist(c(g1, g2, g3)) / n ids <- unlist(lapply(1:7, function(x) x + c(0, 7, 14))) CTDC[ids] }
census <- pick_top(fgeo.x::stem5, sp, 2) elevation <- fgeo.x::elevation$col context("plot_each_species") test_that("works with species parameters", { spp <- unique(census$sp) elev <- elevation cns <- census expect_silent( plot_each_species( cns, elev, species = spp, fill = "white", shape = 21, point_size = 5 )[[1]] ) }) test_that("works with elevation parameters", { spp <- unique(census$sp) elev <- elevation cns <- census expect_silent( plot_each_species( cns, elev, species = spp, fill = "white", shape = 21, point_size = 5, contour_size = 1, low = "grey", high = "black", hide_color_legend = TRUE, bins = 7, add_elevation_labels = FALSE )[[1]] ) expect_silent( plot_each_species( cns, elev, species = spp, fill = "white", shape = 21, point_size = 5, contour_size = 1, low = "grey", high = "black", hide_color_legend = TRUE, bins = NULL, add_elevation_labels = TRUE, label_color = "black", xyjust = 1, fontface = "bold", xlim = c(0, 500), ylim = c(0, 400), custom_theme = ggplot2::theme_bw() )[[1]] ) }) test_that("outputs a list of ggplots", { p <- plot_each_species(census) expect_type(p, "list") expect_is(p[[1]], "gg") }) test_that("errs with wrong inputs", { expect_error(plot_each_species(1), "is not TRUE") expect_error(plot_each_species(census, 1), "Can't deal with data of class") expect_error(plot_each_species(census, NULL, 1), "is not TRUE") expect_error(plot_each_species(census, xlim = 0), "Limits must be in a") }) context("plot_sp_elev") test_that("outputs a ggplot", { expect_is(plot_sp_elev(census), "gg") }) test_that("errs with wrong inputs", { expect_error(plot_sp_elev(1), "is not TRUE") expect_error(plot_sp_elev(census, 1), "Can't deal with data of class") expect_error(plot_sp_elev(census, xlim = 0), "Limits must be in a") }) context("plot_elev") test_that("outputs a ggplot", { p <- plot_elev(elevation) expect_is(p, "gg") }) test_that("errs with wrong inputs", { expect_error(plot_elev(1), "Can't deal with data of class") expect_error(plot_elev(census), "Ensure your data set has these variables") expect_error(plot_elev(list(not_col = census)), "Your list must contain") expect_error(plot_elev(elevation, xlim = 0), "Limits must be in a") }) context("plot_base_elevation") test_that("works with raw elevation data", { elevation_ls <- fgeo.x::elevation expect_silent(plot_base_elevation(elevation_ls)) expect_silent(plot_base_elevation(elevation_ls)) }) test_that("errs if elevation data is confused with census data", { expect_error(plot_base_elevation(census), "Ensure your data set has") })
model.bayesbr = function(Y,X = NULL,W = NULL,name_y,names_x = NULL,names_w = NULL){ model = Y verification = name_y if(!is.null(X)){ if(is.null(ncol(X))){ tam = 1 } else{ tam = ncol(X) } for (i in 1:tam) { aux = TRUE for(name in verification){ if (name == names_x[i]) { aux = FALSE break } } if(aux && names_x[i]!="(Intercept)"){ if(!is.null(ncol(X))){ model = cbind(model,X[,i]) } else{ model = cbind(model,X[i]) } verification = c(verification,names_x[i]) } } } if(!is.null(W)){ if(is.null(ncol(W))){ tam = 1 } else{ tam = ncol(W) } for (i in 1:tam) { aux = TRUE for(name in verification){ if (name == names_w[i]) { aux = FALSE break } } if(aux && names_w[i]!="(Intercept)"){ if(!is.null(ncol(W))){ model = cbind(model,W[,i]) } else{ model = cbind(model,W[i]) } verification = c(verification,names_w[i]) } } } model = data.frame(model) colnames(model) = verification return(model) }
plot.lordif.MC <- function(x,mfrow=c(3,1),width=7,height=7,...) { if (class(x)!="lordif.MC") stop(paste(deparse(substitute(x))," must be of class lordif.MC")) nr<-x$nr Item<-1:dim(x$cutoff)[1] sysname<-Sys.info()[["sysname"]] if(sysname=="Windows") { dev.new(width=width,height=height,record=TRUE) } else if (sysname=="Linux") { dev.new(width=width,height=height) par(ask=TRUE) } else { dev.new(width=width,height=height) } par(mfrow=mfrow) par(mar=c(2,5,1,2)+0.1) max.chi<-max(pretty(c(x$cutoff$chi12,x$cutoff$chi13,x$cutoff$chi23))) plot(Item,x$cutoff$chi12,ylab=substitute(paste0("Pr(",chi[12]^2,")")),ylim=c(0,max.chi),type="b",...) abline(h=x$alpha,col="red") plot(Item,x$cutoff$chi13,ylab=substitute(paste0("Pr(",chi[13]^2,")")),ylim=c(0,max.chi),type="b",...) abline(h=x$alpha,col="red") plot(Item,x$cutoff$chi23,ylab=substitute(paste0("Pr(",chi[23]^2,")")),ylim=c(0,max.chi),type="b",...) abline(h=x$alpha,col="red") max.R2<-max(pretty(c(x$cutoff$pseudo13.McFadden,x$cutoff$pseudo13.Nagelkerke,x$cutoff$pseudo13.CoxSnell))) plot(Item,x$cutoff$pseudo12.McFadden,ylab=substitute(paste0(R[2]^2," - ",R[1]^2)),type="b",col="black",lty=1,ylim=c(0,max.R2)) points(Item,x$cutoff$pseudo12.Nagelkerke,type="b",col="blue",lty=2,pch=2) points(Item,x$cutoff$pseudo12.CoxSnell,type="b",col="red",lty=3,pch=3) legend("topleft",c("McFadden","Nagelkerke","Cox & Snell"),lty=1:3,col=c("black","blue","red"),pch=1:3,bg="white") plot(Item,x$cutoff$pseudo13.McFadden,ylab=substitute(paste0(R[3]^2," - ",R[1]^2)),type="b",col="black",lty=1,ylim=c(0,max.R2)) points(Item,x$cutoff$pseudo13.Nagelkerke,type="b",col="blue",lty=2,pch=2) points(Item,x$cutoff$pseudo13.CoxSnell,type="b",col="red",lty=3,pch=3) plot(Item,x$cutoff$pseudo23.McFadden,ylab=substitute(paste0(R[3]^2," - ",R[2]^2)),type="b",col="black",lty=1,ylim=c(0,max.R2)) points(Item,x$cutoff$pseudo23.Nagelkerke,type="b",col="blue",lty=2,pch=2) points(Item,x$cutoff$pseudo23.CoxSnell,type="b",col="red",lty=3,pch=3) max.beta<-max(pretty(x$cutoff$beta12)) plot(Item,x$cutoff$beta12,ylab=substitute(Delta(beta[1])),type="b",ylim=c(0,max.beta),...) }
context("SortArgs") test_that("SortArgs works.", { x <- SortArgs( PasteAndDep(substitute(UKAnophelesPlumbeus)), PasteAndDep(substitute(UKAir)), PasteAndDep(substitute(OneHundredBackground)), PasteAndDep(substitute(LogisticRegression)), PasteAndDep(substitute(PrintMap)), TRUE ) expect_equal(x, paste("workflow(occurrence = UKAnophelesPlumbeus,", "covariate = UKAir, process = OneHundredBackground,", "model = LogisticRegression, output = PrintMap,", "forceReproducible = TRUE)")) w <- eval(parse(text = x)) expect_true(inherits(w, "zoonWorkflow")) expect_false(any(vapply(w, is.null, FUN.VALUE = FALSE))) y <- SortArgs( PasteAndDep(substitute(UKAnophelesPlumbeus)), PasteAndDep(substitute("UKAir")), PasteAndDep(substitute(BackgroundAndCrossvalid(k = 2))), PasteAndDep(substitute(list(LogisticRegression, LogisticRegression))), PasteAndDep(substitute(Chain(PrintMap, PrintMap))), TRUE ) expect_true(length(y) == 1) expect_true(inherits(y, "character")) w2 <- eval(parse(text = y)) expect_true(inherits(w2, "zoonWorkflow")) expect_false(any(vapply(w2, is.null, FUN.VALUE = FALSE))) })
sim.taxonomy = function(tree, beta = 0, lambda.a = 0, kappa = 0, root.edge = TRUE){ if(!"phylo" %in% class(tree)) stop("tree must be an object of class \"phylo\"") if(!(beta >= 0 && beta <= 1)) stop("beta must be a probability between 0 and 1") if(lambda.a < 0) stop("lambda.a must be zero or positive") if(!(kappa >= 0 && kappa <= 1)) stop("kappa must be a probability between 0 and 1") if(is.null(tree$edge.length)) stop("tree must have edge lengths") if(!ape::is.rooted(tree)) stop("tree must be rooted") node.ages = n.ages(tree) species<-data.frame(sp = integer(), edge = integer(), parent = integer(), start = numeric(), end = numeric(), mode = character(), cryptic = logical(), cryptic.id = integer() ) root = length(tree$tip.label) + 1 if(root.edge && exists("root.edge",tree)){ start = node.ages[root] + tree$root.edge mode = "o" } else { start = node.ages[root] mode = "r" } species <- rbind(species, data.frame(sp = root, edge = root, parent = 0, start = start, end = node.ages[root], mode = mode, cryptic = 0, cryptic.id = root)) aux = function(node, p) { descendants = tree$edge[which(tree$edge[,1] == node), 2] if(length(descendants) == 0) { return(p) } d1 <- descendants[1] d2 <- descendants[2] if(beta == 1 || (beta > 0 && runif(1) > (1 - beta))){ a <- p$sp[which(p$edge == node)] p <- rbind(p, data.frame(sp = d1, edge = d1, parent = a, start = node.ages[a], end = node.ages[d1], mode="s", cryptic = 0, cryptic.id = d1)) p <- rbind(p, data.frame(sp = d2, edge = d2, parent = a, start = node.ages[a], end = node.ages[d2], mode="s", cryptic = 0, cryptic.id = d2)) } else{ p$sp[which(p$sp == node)] = d1 p$parent[which(p$parent == node)] = d1 p$cryptic.id[which(p$cryptic.id == node)] = d1 a <- p$parent[which(p$edge == node)] m <- p$mode[which(p$sp == d1)][1] p <- rbind(p, data.frame(sp = d1, edge = d1, parent = a, start = node.ages[ancestor(d1, tree)], end = node.ages[d1], mode = m, cryptic = 0, cryptic.id = d1)) start = node.ages[ancestor(d2, tree)] p <- rbind(p, data.frame(sp = d2, edge = d2, parent = d1, start = start, end = node.ages[d2], mode="b", cryptic = 0, cryptic.id = d2)) } p = aux(d1, p) p = aux(d2, p) p } species = aux(root, species) species = species[order(species$sp),] species = taxonomy(species) if(lambda.a > 0) species = sim.anagenetic.species(tree, species, lambda.a) if(kappa > 0) species = sim.cryptic.species(species, kappa) rownames(species) = NULL return(species) } sim.anagenetic.species = function(tree, species, lambda.a){ if(!"phylo" %in% class(tree)) stop("tree must be an object of class \"phylo\"") if(!"taxonomy" %in% class(species)) stop("species must be an object of class \"taxonomy\"") if(any(species$mode=="a")) stop("taxonomy object already contains anagenetic species") if(lambda.a < 0) stop("lambda.a must be zero or positive") node.ages = n.ages(tree) if(lambda.a > 0){ root = root(tree) species.counter = max(as.numeric(names(node.ages))) + 1 edges = data.frame(edge = numeric(), start = numeric(), end = numeric()) for(i in unique(species$edge)){ edges = rbind(edges, data.frame(edge = i, start = species$start[which(species$edge == i)][1], end = species$end[which(species$edge == i)][1])) } for(i in unique(species$sp)){ sp.start = max(species$start[which(species$sp == i)]) sp.end = min(species$end[which(species$sp == i)]) rand = rpois(1, (sp.start - sp.end) * lambda.a) if (rand > 0) { potential.edges = species$edge[which(species$sp == i)] p = subset(edges, edges$edge %in% potential.edges) p = p[order(p$end, decreasing = TRUE),] s = subset(species, species$edge %in% potential.edges) species = subset(species, !species$edge %in% potential.edges) h = runif(rand, min = sp.end, max = sp.start) h = sort(h, decreasing = T) for(j in 1:(length(h)+1)){ if(j == 1){ sp = species.counter start = sp.start end = h[j] edge = p$edge[which(p$start == start)] edge = c(edge, p$edge[which(p$start < start & p$start > end)]) edge.start = p$start[which(p$edge %in% edge)] edge.end = p$end[which(p$edge %in% edge)] edge.end[length(edge.end)] = end mode = s$mode[1] parent = s$parent[1] species <- rbind(species, data.frame(sp = sp, edge = edge, parent = parent, start = edge.start, end = edge.end, mode = mode, cryptic = 0, cryptic.id = sp)) if(any(species$parent == i & species$start <= start & species$start > end)) { species$parent[which(species$parent == i & species$start <= start & species$start > end)] = sp } species.counter = species.counter + 1 } else if (j == (length(h)+1)){ sp = i start = h[j-1] end = sp.end edge = p$edge[which(p$start > start & p$end < start)] edge = c(edge, p$edge[which(p$start < start & p$start > end)]) edge.start = p$start[which(p$edge %in% edge)] edge.end = p$end[which(p$edge %in% edge)] edge.start[1] = start mode = "a" parent = species.counter - 1 species <- rbind(species, data.frame(sp = sp, edge = edge, parent = parent, start = edge.start, end = edge.end, mode = mode, cryptic = 0, cryptic.id = sp)) } else { sp = species.counter start = h[j-1] end = h[j] edge = p$edge[which(p$start > start & p$end < start)] edge = c(edge, p$edge[which(p$start < start & p$start > end)]) edge.start = p$start[which(p$edge %in% edge)] edge.end = p$end[which(p$edge %in% edge)] edge.start[1] = start edge.end[length(edge.end)] = end mode = "a" parent = species.counter - 1 species <- rbind(species, data.frame(sp = sp, edge = edge, parent = parent, start = edge.start, end = edge.end, mode = mode, cryptic = 0, cryptic.id = sp)) if(any(species$parent == i & species$start < start & species$start > end)) { species$parent[which(species$parent == i & species$start < start & species$start > end)] = sp } species.counter = species.counter + 1 } } } } } rownames(species) = NULL return(species) } sim.cryptic.species = function(species, kappa){ if(!"taxonomy" %in% class(species)) stop("species must be an object of class \"taxonomy\"") if(any(species$cryptic == 1)) stop("taxonomy object already contains cryptic species") if(!(kappa >= 0 && kappa <= 1)) stop("kappa must be a probability between 0 and 1") if(kappa > 0){ for(i in unique(species$sp)){ if(species$mode[which(species$sp == i)][1] == "o") next if(species$mode[which(species$sp == i)][1] == "r") next if(runif(1) < kappa){ species$cryptic[which(species$sp == i)] = 1 parent = species$parent[which(species$sp == i)][1] c = species$cryptic.id[which(species$sp == parent)][1] species$cryptic.id[which(species$sp == i)] = c species$cryptic.id[which(species$cryptic.id == i)] = c } } } return(species) }
Collect.youtube <- function(credential, videoIDs, verbose = FALSE, writeToFile = FALSE, maxComments = 1e10, ...) { cat("Collecting comment threads for youtube videos...\n") flush.console() apiKey <- credential$auth if (is.null(apiKey) || nchar(apiKey) < 1) { stop("Please provide a valid youtube api key.", call. = FALSE) } if (missing(videoIDs) || !is.vector(videoIDs) || length(videoIDs) < 1) { stop("Please provide a vector of one or more youtube video ids.", call. = FALSE) } api_cost <- total_api_cost <- 0 dataCombined <- data.frame(Comment = "foo", AuthorDisplayName = "bar", AuthorProfileImageUrl = NA, AuthorChannelUrl = NA, AuthorChannelID = NA, ReplyCount = "99999999", LikeCount = "99999999", PublishedAt = "timestamp", UpdatedAt = "timestamp", CommentID = "99999999123456789", ParentID = "foobar", VideoID = "foobarfoobar", stringsAsFactors = FALSE) for (k in 1:length(videoIDs)) { cat(paste0("Video ", k, " of ", length(videoIDs), "\n", sep = "")) cat("---------------------------------------------------------------\n") rObj <- yt_scraper(videoIDs, apiKey, k, verbose) rObj$scrape_all(maxComments) api_cost <- rObj$api_cost if (length(rObj$data) == 0) { cat("\n") next } if (verbose) { cat(paste0("** Creating dataframe from threads of ", videoIDs[k], ".\n")) } tempData <- lapply(rObj$data, function(x) { data.frame(Comment = x$snippet$topLevelComment$snippet$textDisplay, AuthorDisplayName = x$snippet$topLevelComment$snippet$authorDisplayName, AuthorProfileImageUrl = x$snippet$topLevelComment$snippet$authorProfileImageUrl, AuthorChannelUrl = x$snippet$topLevelComment$snippet$authorChannelUrl, AuthorChannelID = ifelse(is.null(x$snippet$topLevelComment$snippet$authorChannelId$value), "[NoChannelId]", x$snippet$topLevelComment$snippet$authorChannelId$value), ReplyCount = x$snippet$totalReplyCount, LikeCount = x$snippet$topLevelComment$snippet$likeCount, PublishedAt = x$snippet$topLevelComment$snippet$publishedAt, UpdatedAt = x$snippet$topLevelComment$snippet$updatedAt, CommentID = x$snippet$topLevelComment$id, ParentID = NA, VideoID = videoIDs[k], stringsAsFactors = FALSE) }) core_df <- do.call("rbind", tempData) commentIDs <- core_df$CommentID commentIDs_with_replies <- core_df[which(core_df$ReplyCount > 0), ] commentIDs_with_replies <- commentIDs_with_replies$CommentID if (length(commentIDs_with_replies) > 0) { cat(paste0("** Collecting replies for ", length(commentIDs_with_replies), " threads with replies. Please be patient.\n")) base_url <- "https://www.googleapis.com/youtube/v3/comments" dataRepliesAll <- data.frame(Comment = "foo", AuthorDisplayName = "bar", AuthorProfileImageUrl = NA, AuthorChannelUrl = NA, AuthorChannelID = NA, ReplyCount = "99999999", LikeCount = "99999999", PublishedAt = "timestamp", UpdatedAt = "timestamp", CommentID = "99999999123456789", ParentID = "foobar", VideoID = videoIDs[k], stringsAsFactors = FALSE) total_replies <- 0 for (i in 1:length(commentIDs_with_replies)) { api_opts <- list(part = "snippet", textFormat = "plainText", parentId = commentIDs_with_replies[i], key = apiKey) req <- httr::GET(base_url, query = api_opts) init_results <- httr::content(req) err <- FALSE if (req$status_code != 200) { err <- TRUE cat(paste0("\nComment error: ", init_results$error$code, "\nDetail: ", init_results$error$message, "\n")) cat(paste0("parentId: ", commentIDs_with_replies[i], "\n\n")) } else { api_cost <- api_cost + 2 } num_items <- length(init_results$items) if (verbose) { if (i == 1) { cat("Comment replies ") } cat(paste(num_items, "")) flush.console() } else { cat(".") flush.console() } total_replies <- total_replies + num_items tempDataReplies <- lapply(init_results$items, function(x) { data.frame(Comment = x$snippet$textDisplay, AuthorDisplayName = x$snippet$authorDisplayName, AuthorProfileImageUrl = x$snippet$authorProfileImageUrl, AuthorChannelUrl = x$snippet$authorChannelUrl, AuthorChannelID = ifelse(is.null(x$snippet$authorChannelId$value), "[NoChannelId]", x$snippet$authorChannelId$value), ReplyCount = 0, LikeCount = x$snippet$likeCount, PublishedAt = x$snippet$publishedAt, UpdatedAt = x$snippet$updatedAt, CommentID = x$id, ParentID = x$snippet$parentId, VideoID = videoIDs[k], stringsAsFactors = FALSE) }) tempDataRepliesBinded <- do.call("rbind", tempDataReplies) dataRepliesAll <- rbind(dataRepliesAll, tempDataRepliesBinded) if (err || rObj$api_error) { break } } total_api_cost <- total_api_cost + api_cost cat(paste0("\n** Collected replies: ", total_replies, "\n")) cat(paste0("** Total video comments: ", length(commentIDs) + total_replies, "\n")) if (verbose) { cat(paste0("(Video API unit cost: ", api_cost, ")\n")) } cat("---------------------------------------------------------------\n") dataRepliesAll <- dataRepliesAll[-1, ] dataCombinedTemp <- rbind(core_df, dataRepliesAll) dataCombined <- rbind(dataCombined, dataCombinedTemp) } else { total_api_cost <- total_api_cost + api_cost dataCombined <- rbind(dataCombined, core_df) cat("\n") } } cat(paste0("** Total comments collected for all videos ", nrow(dataCombined)-1, ".\n", sep = "")) dataCombined <- dataCombined[-1, ] if (nrow(dataCombined) == 0) { stop(paste0("No comments could be collected from the given video Ids: ", paste0(videoIDs, collapse = ", "), "\n"), call. = FALSE) } else { cat(paste0("(Estimated API unit cost: ", total_api_cost, ")\n")) } if (writeToFile) { writeOutputFile(dataCombined, "rds", "YoutubeData") } dataCombined <- tibble::as_tibble(dataCombined) class(dataCombined) <- append(class(dataCombined), c("datasource", "youtube")) cat("Done.\n") flush.console() dataCombined } yt_scraper <- setRefClass( "yt_scraper", fields = list( base_url = "character", api_opts = "list", nextPageToken = "character", page_count = "numeric", data = "list", unique_count = "numeric", done = "logical", core_df = "data.frame", verbose = "logical", api_cost = "numeric", api_error = "logical"), methods = list( scrape = function() { opts <- api_opts if (is.null(nextPageToken) || length(trimws(nextPageToken)) == 0L || trimws(nextPageToken) == "") { if (page_count >= 1) { if (verbose) { cat(paste0("-- No nextPageToken. Returning. page_count is: ", page_count, "\n")) } return(0) } else { if (verbose) { cat("-- First thread page. No pageToken.\n") } } } else { opts$pageToken <- trimws(nextPageToken) if (verbose) { cat(paste0("-- Value of pageToken: ", opts$pageToken, "\n")) } } page_count <<- page_count + 1 req <- httr::GET(base_url, query = opts) res <- httr::content(req) if (req$status_code != 200) { api_error <<- TRUE nextPageToken <<- "" cat(paste0("\nThread error: ", res$error$code, "\nDetail: ", res$error$message, "\n")) cat(paste0("videoId: ", opts$videoId, "\n\n")) return(0) } else { api_cost <<- api_cost + 3 } if (is.null(res$nextPageToken)) { nextPageToken <<- "" } else { nextPageToken <<- res$nextPageToken } data <<- c(data, res$items) return(length(res$items)) }, scrape_all = function(maxComments) { cat(paste0("** video Id: ", api_opts$videoId ,"\n", sep = "")) if (verbose) { cat(paste0(" [results per page: ", api_opts$maxResults, " | max comments per video: ", maxComments, "]\n", sep = "")) } thread_count <- 0 while (TRUE) { thread_count <- scrape() if (verbose) { cat(paste0("-- Collected threads from page: ", thread_count, "\n", sep = "")) } if (thread_count == 0 | length(data) > maxComments | api_error) { done <<- TRUE nextPageToken <<- "" if (length(data) > maxComments) { cat(paste0("-- API returned more than max comments. Results truncated to first ", maxComments, " threads.\n", sep = "")) data <<- data[1:maxComments] } if (verbose) { cat(paste0("-- Done collecting threads.\n", sep = "")) } break } } if (verbose) { cat(paste0("** Results page count: ", page_count, "\n")) } cat(paste0("** Collected threads: ", length(data), "\n")) if (verbose) { cat(paste0("(Threads API unit cost: ", api_cost, ")\n")) } }, initialize = function(videoIDs, apiKey, k, verbose = FALSE) { base_url <<- "https://www.googleapis.com/youtube/v3/commentThreads/" api_opts <<- list(part = "snippet", maxResults = 100, textFormat = "plainText", videoId = videoIDs[k], key = apiKey, fields = "items,nextPageToken", orderBy = "published") page_count <<- 0 nextPageToken <<- "" data <<- list() unique_count <<- 0 done <<- FALSE core_df <<- data.frame() verbose <<- verbose api_cost <<- 0 api_error <<- FALSE }, reset = function() { data <<- list() page_count <<- 0 nextPageToken <<- "" unique_count <<- 0 done <<- FALSE core_df <<- data.frame() api_cost <<- 0 api_error <<- FALSE }, cache_core_data = function() { if (nrow(core_df) < unique_count) { sub_data <- lapply(data, function(x) { data.frame( Comment = x$snippet$topLevelComment$snippet$textDisplay, AuthorDisplayName = x$snippet$topLevelComment$snippet$authorDisplayName, AuthorProfileImageUrl = x$snippet$topLevelComment$snippet$authorProfileImageUrl, AuthorChannelUrl = x$snippet$topLevelComment$snippet$authorChannelUrl, AuthorChannelID = ifelse(is.null(x$snippet$topLevelComment$snippet$authorChannelId$value), "[NoChannelId]", x$snippet$topLevelComment$snippet$authorChannelId$value), ReplyCount = x$snippet$totalReplyCount, LikeCount = x$snippet$topLevelComment$snippet$likeCount, PublishedAt = x$snippet$topLevelComment$snippet$publishedAt, UpdatedAt = x$snippet$topLevelComment$snippet$updatedAt, CommentID = x$snippet$topLevelComment$id, stringsAsFactors = FALSE) }) core_df <<- do.call("rbind", sub_data) } else { message("core_df is already up to date.\n") } } ) )
plot_intensities_ratio <- function(spectral_count_object, target_variable, list_conditions, force = FALSE){ spectral_count_object <- spectral_count_object if (!force && interactive()) { response <- select.list(c("yes", "no"), title = "Do you allow to create a pdf file with log2 abundance ratios?") if (response == "yes") { if (length(spectral_count_object) == 4) { if (spectral_count_object[[4]] == "spectral_count_object") { target_variable <- target_variable metadata <- spectral_count_object[[2]] if (target_variable %in% colnames(metadata) == TRUE) { if (all((unique(list_conditions)) %in% metadata[[target_variable]]) == TRUE) { if ((length(list_conditions) == 2) & (length(unique(list_conditions)) == 2)) { sc_data <- spectral_count_object[[1]] colnames(sc_data) <- metadata[[target_variable]] sc_data <- as.data.frame(sapply(split.default(sc_data, names(sc_data)), rowMeans)) ref <- list_conditions[1] cond <- list_conditions[2] sc_data_pairwise <- sc_data[-which(sc_data[[ref]] == 0 & sc_data[[cond]] == 0), c(ref, cond)] ref_log <- log2(sc_data_pairwise[, 1] + 1) cond_log <- log2(sc_data_pairwise[, 2] + 1) to_plot <- matrix(NA, length(ref_log), 3) to_plot[, 1] <- ref_log to_plot[, 2] <- cond_log to_plot[, 3] <- cond_log - ref_log to_plot <- to_plot[rev(order(to_plot[, 1])),] pepsprots <- spectral_count_object[[3]] if("species" %in% colnames(pepsprots)){ taxa <- "Species" } else if("genus" %in% colnames(pepsprots)){ taxa <- "Genus" } else if("family" %in% colnames(pepsprots)){ taxa <- "Family" } else if("order" %in% colnames(pepsprots)){ taxa <- "Order" } else if("class" %in% colnames(pepsprots)){ taxa <- "Class" } else if("phylum" %in% colnames(pepsprots)){ taxa <- "Phylum" } else if("superkingdom" %in% colnames(pepsprots)){ taxa <- "Superkingdom" } else{ taxa <- "" } if (names(spectral_count_object[1]) == "SC_subgroups") { if (nchar(taxa) == 0){ elements <- "Subgroup" } else{ elements <- paste(c(taxa, "(from subgroups)"), collapse = " ") } } else if (names(spectral_count_object[1]) == "SC_groups") { if (nchar(taxa) == 0){ elements <- "Group" } else{ elements <- paste(c(taxa, "(from groups)"), collapse = " ") } } else{ if (nchar(taxa) == 0){ elements <- "Peptide" } else{ elements <- paste(c(taxa, "(from peptides)"), collapse = " ") } } number <- paste(c("n=", length(ref_log)), collapse = "") xlab <- paste(c(elements, " by decreasing abundance in ", ref, " (", number, ")"), collapse = "") ylab <- paste(c("log2(ratio ", cond, "/", ref, " )"), collapse = "") main <- paste(c("Abudances in ", cond, " versus ", ref), collapse = "") filename <- paste(elements, "ratios", cond, "VS", ref, sep = "_") filename <- paste(filename, ".pdf", sep = "") old_par <- par(no.readonly = TRUE) on.exit(suppressWarnings(par(old_par))) pdf(filename, width = 7.5, height = 6) par(fig = c(0, 0.85, 0, 1)) plot(to_plot[, 3], pch = ".", cex = 2, xlab = xlab, ylab = ylab, main = main) abline(h = 0, col = "blue", lwd = 0.5) abline(h = -1.584963, col = "blue", lwd = 1) abline(h = 1.584963, col = "blue", lwd = 1) par(fig = c(0.70, 1, 0, 1), new = TRUE) boxplot(to_plot[, 3], axes = FALSE) abline(h = 0, col = "blue", lwd = 0.5) abline(h = -1.584963, col = "blue", lwd = 1) abline(h = 1.584963, col = "blue", lwd = 1) dev.off() print(paste("The figure", filename, "was generated", sep = " ")) } else{ stop("Precise only TWO conditions in list_conditions argument") } } else{ vars <- paste(list_conditions, collapse = ", ") stop(paste(c("The variables [", vars, "] must be present in: '", target_variable, "'"), collapse = " ")) } } else{ options <- colnames(metadata) stop(paste(c("Change target_variable for ONE of these options: ", options), collapse = "' '")) } } else { stop("Invalid spectral count object") } } else{ stop("Invalid spectral count object") } } else{ stop("No file was created") } } }
intg1.TMLW <- function(x){ (exp(x)-1)*dlweibul(x)}
setClass( Class = "Muller94BoundaryKernel", representation = representation(), contains = "BoundaryKernel" ) setMethod( f = "leftBoundaryKernelFunction", signature = "Muller94BoundaryKernel", definition = function(.Object,q,u){ if (.Object@mu == 0){ 2/((1+q)^3)*(3*(1-q)*u+2*(1-q+q^2)) }else if (.Object@mu == 1){ 12/((1+q)^4)*(u+1)*((1-2*q)*u+(1-2*q+3*q^2)*0.5) }else if (.Object@mu == 2){ 15*(1+u)^2*(q-u)*(1/(1+q)^5)*(2*u*(5*((1-q)/(1+q))-1)+3*q-1+(5*(1-q)^2)/(1+q)) }else if (.Object@mu == 3){ 70*(1+u)^3*(q-u)^2*(1/(1+q)^7)*(2*u*(7*((1-q)/(1+q))-1)+3*q-1+(7*(1-q)^2)/(1+q)) }else { stop("Mu can only take values 0,1,2 or 3") } }) setMethod( f = "interiorKernelFunction", signature = "Muller94BoundaryKernel", definition = function(.Object,u){ if (.Object@mu == 0){ rep(1/2,times=length(u)) }else if (.Object@mu == 1){ (3/4)*(1-u^2) }else if (.Object@mu == 2){ (15/16)*(1-u^2)^2 }else if (.Object@mu == 3){ (35/32)*(1-u^2)^3 }else { stop("Mu can only take values 0,1,2 or 3") } }) setMethod( f = "rightBoundaryKernelFunction", signature = "Muller94BoundaryKernel", definition = function(.Object,q,u){ leftBoundaryKernelFunction(.Object,q,-u) }) muller94BoundaryKernel <- function(dataPoints, mu=1, b=length(dataPoints)^(-2/5), dataPointsCache=NULL, lower.limit=0,upper.limit=1){ dataPoints.scaled <- dataPoints dataPointsCache.scaled <- dataPointsCache if(is.null(dataPointsCache)){ dataPointsCache.scaled <- seq(0,1,0.01) } if(lower.limit!=0 || upper.limit!=1){ dataPoints.scaled <- (dataPoints-lower.limit)/(upper.limit-lower.limit) if(!is.null(dataPointsCache)){ dataPointsCache.scaled <- (dataPointsCache-lower.limit)/(upper.limit-lower.limit) } } kernel <- new(Class="Muller94BoundaryKernel",dataPoints = dataPoints.scaled, b = b, dataPointsCache = dataPointsCache.scaled, mu = mu, lower.limit=lower.limit,upper.limit=upper.limit) setDensityCache(kernel, densityFunction=NULL) return(kernel) }
makeJennrichSampsonFunction = function() { makeSingleObjectiveFunction( name = "Jennrich-Sampson Function", id = "jennrichSampson_2d", fn = function(x) { assertNumeric(x, len = 2L, any.missing = FALSE, all.missing = FALSE) i = 1:10 sum((2 + 2 * i - (exp(i * x[1]) + exp(i * x[2])))^2) }, par.set = makeNumericParamSet( len = 2L, id = "x", lower = c(-1, -1), upper = c(1, 1), vector = TRUE ), tags = attr(makeJennrichSampsonFunction, "tags"), global.opt.params = c(0.25782521321500883, 0.25782521381356827), global.opt.value = 124.36218235561473896 ) } class(makeJennrichSampsonFunction) = c("function", "smoof_generator") attr(makeJennrichSampsonFunction, "name") = c("Jennrich-Sampson") attr(makeJennrichSampsonFunction, "type") = c("single-objective") attr(makeJennrichSampsonFunction, "tags") = c("single-objective", "continuous", "differentiable", "non-separable", "non-scalable", "unimodal")
clean.Gspline <- function(dir, label, care.of.y=TRUE){ FILES <- dir(dir) if (paste("mixmoment", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/mixmoment", label, ".sim", sep = "")) if (paste("mweight", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/mweight", label, ".sim", sep = "")) if (paste("mlogweight", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/mlogweight", label, ".sim", sep = "")) if (paste("mmean", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/mmean", label, ".sim", sep = "")) if (paste("gspline", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/gspline", label, ".sim", sep = "")) if (paste("lambda", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/lambda", label, ".sim", sep = "")) if ((paste("Y", label, ".sim", sep="") %in% FILES) & care.of.y) file.remove(paste(dir, "/Y", label, ".sim", sep = "")) if (paste("logposter", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/logposter", label, ".sim", sep = "")) if (paste("r", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/r", label, ".sim", sep = "")) } write.headers.Gspline <- function(dir, dim, nP, label, gparmi, store.a, store.y, store.r, care.of.y=TRUE){ FILES <- dir(dir) sink(paste(dir, "/mixmoment", label, ".sim", sep = ""), append = FALSE) mname <- paste("Mean.", 1:dim, " ", sep="") D <- diag(dim) rows <- row(D)[lower.tri(row(D), diag = TRUE)] cols <- col(D)[lower.tri(col(D), diag = TRUE)] dname <- paste("D.", rows, ".", cols, sep = "") cat("k", mname, dname, "\n", sep = " "); sink() total.length <- ifelse(dim == 1, 2*gparmi["K1"] + 1, (2*gparmi["K1"] + 1)*(2*gparmi["K2"] + 1)) sink(paste(dir, "/mweight", label, ".sim", sep = ""), append = FALSE) cat(paste("w", 1:min(total.length, 9), sep = ""), sep = " ") if (total.length >= 10){ cat(" ") cat(paste("w", 10:total.length, sep = ""), "\n", sep = " ") } else{ cat("\n") } sink() if (store.a){ sink(paste(dir, "/mlogweight", label, ".sim", sep = ""), append = FALSE) cat(paste("a", 1:min(total.length, 9), sep = ""), sep = " ") if (total.length >= 10){ cat(" ") cat(paste("a", 10:total.length, sep = ""), "\n", sep = " ") } else{ cat("\n") } sink() } else if (paste("mlogweight", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/mlogweight", label, ".sim", sep = "")) ind1 <- rep(1:total.length, rep(dim, total.length)) ind2 <- rep(1:dim, total.length) sink(paste(dir, "/mmean", label, ".sim", sep = ""), append = FALSE) cat(paste("mu", ind1, ".", ind2, sep = ""), "\n", sep = " "); sink() sink(paste(dir, "/gspline", label, ".sim", sep = ""), append = FALSE) gname <- paste(" gamma", 1:dim, sep = "") sname <- paste(" sigma", 1:dim, sep = "") dname <- paste(" delta", 1:dim, sep = "") intcptname <- paste(" intercept", 1:dim, sep = "") scname <- paste(" scale", 1:dim, sep = "") cat(gname, sname, dname, intcptname, scname, "\n", sep = " "); sink() sink(paste(dir, "/lambda", label, ".sim", sep = ""), append = FALSE) lname <- if(gparmi["equal.lambda"]) "lambda" else paste("lambda", 1:dim, sep = "") cat(lname, "\n", sep = " "); sink() if (care.of.y){ ind1 <- rep(1:nP, rep(dim, nP)) ind2 <- rep(1:dim, nP) if (store.y){ sink(paste(dir, "/Y", label, ".sim", sep = ""), append = FALSE) cat(paste("Y.", ind1, ".", ind2, sep = ""), "\n", sep = " ") sink() } else{ if (paste("Y", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/Y", label, ".sim", sep = "")) } } if (store.r){ sink(paste(dir, "/r", label, ".sim", sep = ""), append = FALSE) cat(paste("r.", ind1, ".", ind2, sep = ""), "\n", sep = " ") sink() } else{ if (paste("r", label, ".sim", sep="") %in% FILES) file.remove(paste(dir, "/r", label, ".sim", sep = "")) } pname <- if (gparmi["equal.lambda"]) "penalty" else paste("penalty", 1:dim, sep = "") pname <- c("loglik ", pname, " logprw") sink(paste(dir, "/logposter", label, ".sim", sep = ""), append = FALSE) cat(pname, "\n", sep = " "); sink() }
NULL storagegateway_activate_gateway <- function(ActivationKey, GatewayName, GatewayTimezone, GatewayRegion, GatewayType = NULL, TapeDriveType = NULL, MediumChangerType = NULL, Tags = NULL) { op <- new_operation( name = "ActivateGateway", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$activate_gateway_input(ActivationKey = ActivationKey, GatewayName = GatewayName, GatewayTimezone = GatewayTimezone, GatewayRegion = GatewayRegion, GatewayType = GatewayType, TapeDriveType = TapeDriveType, MediumChangerType = MediumChangerType, Tags = Tags) output <- .storagegateway$activate_gateway_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$activate_gateway <- storagegateway_activate_gateway storagegateway_add_cache <- function(GatewayARN, DiskIds) { op <- new_operation( name = "AddCache", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$add_cache_input(GatewayARN = GatewayARN, DiskIds = DiskIds) output <- .storagegateway$add_cache_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$add_cache <- storagegateway_add_cache storagegateway_add_tags_to_resource <- function(ResourceARN, Tags) { op <- new_operation( name = "AddTagsToResource", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$add_tags_to_resource_input(ResourceARN = ResourceARN, Tags = Tags) output <- .storagegateway$add_tags_to_resource_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$add_tags_to_resource <- storagegateway_add_tags_to_resource storagegateway_add_upload_buffer <- function(GatewayARN, DiskIds) { op <- new_operation( name = "AddUploadBuffer", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$add_upload_buffer_input(GatewayARN = GatewayARN, DiskIds = DiskIds) output <- .storagegateway$add_upload_buffer_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$add_upload_buffer <- storagegateway_add_upload_buffer storagegateway_add_working_storage <- function(GatewayARN, DiskIds) { op <- new_operation( name = "AddWorkingStorage", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$add_working_storage_input(GatewayARN = GatewayARN, DiskIds = DiskIds) output <- .storagegateway$add_working_storage_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$add_working_storage <- storagegateway_add_working_storage storagegateway_assign_tape_pool <- function(TapeARN, PoolId, BypassGovernanceRetention = NULL) { op <- new_operation( name = "AssignTapePool", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$assign_tape_pool_input(TapeARN = TapeARN, PoolId = PoolId, BypassGovernanceRetention = BypassGovernanceRetention) output <- .storagegateway$assign_tape_pool_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$assign_tape_pool <- storagegateway_assign_tape_pool storagegateway_attach_volume <- function(GatewayARN, TargetName = NULL, VolumeARN, NetworkInterfaceId, DiskId = NULL) { op <- new_operation( name = "AttachVolume", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$attach_volume_input(GatewayARN = GatewayARN, TargetName = TargetName, VolumeARN = VolumeARN, NetworkInterfaceId = NetworkInterfaceId, DiskId = DiskId) output <- .storagegateway$attach_volume_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$attach_volume <- storagegateway_attach_volume storagegateway_cancel_archival <- function(GatewayARN, TapeARN) { op <- new_operation( name = "CancelArchival", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$cancel_archival_input(GatewayARN = GatewayARN, TapeARN = TapeARN) output <- .storagegateway$cancel_archival_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$cancel_archival <- storagegateway_cancel_archival storagegateway_cancel_retrieval <- function(GatewayARN, TapeARN) { op <- new_operation( name = "CancelRetrieval", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$cancel_retrieval_input(GatewayARN = GatewayARN, TapeARN = TapeARN) output <- .storagegateway$cancel_retrieval_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$cancel_retrieval <- storagegateway_cancel_retrieval storagegateway_create_cachedi_scsi_volume <- function(GatewayARN, VolumeSizeInBytes, SnapshotId = NULL, TargetName, SourceVolumeARN = NULL, NetworkInterfaceId, ClientToken, KMSEncrypted = NULL, KMSKey = NULL, Tags = NULL) { op <- new_operation( name = "CreateCachediSCSIVolume", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$create_cachedi_scsi_volume_input(GatewayARN = GatewayARN, VolumeSizeInBytes = VolumeSizeInBytes, SnapshotId = SnapshotId, TargetName = TargetName, SourceVolumeARN = SourceVolumeARN, NetworkInterfaceId = NetworkInterfaceId, ClientToken = ClientToken, KMSEncrypted = KMSEncrypted, KMSKey = KMSKey, Tags = Tags) output <- .storagegateway$create_cachedi_scsi_volume_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$create_cachedi_scsi_volume <- storagegateway_create_cachedi_scsi_volume storagegateway_create_nfs_file_share <- function(ClientToken, NFSFileShareDefaults = NULL, GatewayARN, KMSEncrypted = NULL, KMSKey = NULL, Role, LocationARN, DefaultStorageClass = NULL, ObjectACL = NULL, ClientList = NULL, Squash = NULL, ReadOnly = NULL, GuessMIMETypeEnabled = NULL, RequesterPays = NULL, Tags = NULL, FileShareName = NULL, CacheAttributes = NULL, NotificationPolicy = NULL) { op <- new_operation( name = "CreateNFSFileShare", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$create_nfs_file_share_input(ClientToken = ClientToken, NFSFileShareDefaults = NFSFileShareDefaults, GatewayARN = GatewayARN, KMSEncrypted = KMSEncrypted, KMSKey = KMSKey, Role = Role, LocationARN = LocationARN, DefaultStorageClass = DefaultStorageClass, ObjectACL = ObjectACL, ClientList = ClientList, Squash = Squash, ReadOnly = ReadOnly, GuessMIMETypeEnabled = GuessMIMETypeEnabled, RequesterPays = RequesterPays, Tags = Tags, FileShareName = FileShareName, CacheAttributes = CacheAttributes, NotificationPolicy = NotificationPolicy) output <- .storagegateway$create_nfs_file_share_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$create_nfs_file_share <- storagegateway_create_nfs_file_share storagegateway_create_smb_file_share <- function(ClientToken, GatewayARN, KMSEncrypted = NULL, KMSKey = NULL, Role, LocationARN, DefaultStorageClass = NULL, ObjectACL = NULL, ReadOnly = NULL, GuessMIMETypeEnabled = NULL, RequesterPays = NULL, SMBACLEnabled = NULL, AccessBasedEnumeration = NULL, AdminUserList = NULL, ValidUserList = NULL, InvalidUserList = NULL, AuditDestinationARN = NULL, Authentication = NULL, CaseSensitivity = NULL, Tags = NULL, FileShareName = NULL, CacheAttributes = NULL, NotificationPolicy = NULL) { op <- new_operation( name = "CreateSMBFileShare", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$create_smb_file_share_input(ClientToken = ClientToken, GatewayARN = GatewayARN, KMSEncrypted = KMSEncrypted, KMSKey = KMSKey, Role = Role, LocationARN = LocationARN, DefaultStorageClass = DefaultStorageClass, ObjectACL = ObjectACL, ReadOnly = ReadOnly, GuessMIMETypeEnabled = GuessMIMETypeEnabled, RequesterPays = RequesterPays, SMBACLEnabled = SMBACLEnabled, AccessBasedEnumeration = AccessBasedEnumeration, AdminUserList = AdminUserList, ValidUserList = ValidUserList, InvalidUserList = InvalidUserList, AuditDestinationARN = AuditDestinationARN, Authentication = Authentication, CaseSensitivity = CaseSensitivity, Tags = Tags, FileShareName = FileShareName, CacheAttributes = CacheAttributes, NotificationPolicy = NotificationPolicy) output <- .storagegateway$create_smb_file_share_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$create_smb_file_share <- storagegateway_create_smb_file_share storagegateway_create_snapshot <- function(VolumeARN, SnapshotDescription, Tags = NULL) { op <- new_operation( name = "CreateSnapshot", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$create_snapshot_input(VolumeARN = VolumeARN, SnapshotDescription = SnapshotDescription, Tags = Tags) output <- .storagegateway$create_snapshot_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$create_snapshot <- storagegateway_create_snapshot storagegateway_create_snapshot_from_volume_recovery_point <- function(VolumeARN, SnapshotDescription, Tags = NULL) { op <- new_operation( name = "CreateSnapshotFromVolumeRecoveryPoint", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$create_snapshot_from_volume_recovery_point_input(VolumeARN = VolumeARN, SnapshotDescription = SnapshotDescription, Tags = Tags) output <- .storagegateway$create_snapshot_from_volume_recovery_point_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$create_snapshot_from_volume_recovery_point <- storagegateway_create_snapshot_from_volume_recovery_point storagegateway_create_storedi_scsi_volume <- function(GatewayARN, DiskId, SnapshotId = NULL, PreserveExistingData, TargetName, NetworkInterfaceId, KMSEncrypted = NULL, KMSKey = NULL, Tags = NULL) { op <- new_operation( name = "CreateStorediSCSIVolume", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$create_storedi_scsi_volume_input(GatewayARN = GatewayARN, DiskId = DiskId, SnapshotId = SnapshotId, PreserveExistingData = PreserveExistingData, TargetName = TargetName, NetworkInterfaceId = NetworkInterfaceId, KMSEncrypted = KMSEncrypted, KMSKey = KMSKey, Tags = Tags) output <- .storagegateway$create_storedi_scsi_volume_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$create_storedi_scsi_volume <- storagegateway_create_storedi_scsi_volume storagegateway_create_tape_pool <- function(PoolName, StorageClass, RetentionLockType = NULL, RetentionLockTimeInDays = NULL, Tags = NULL) { op <- new_operation( name = "CreateTapePool", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$create_tape_pool_input(PoolName = PoolName, StorageClass = StorageClass, RetentionLockType = RetentionLockType, RetentionLockTimeInDays = RetentionLockTimeInDays, Tags = Tags) output <- .storagegateway$create_tape_pool_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$create_tape_pool <- storagegateway_create_tape_pool storagegateway_create_tape_with_barcode <- function(GatewayARN, TapeSizeInBytes, TapeBarcode, KMSEncrypted = NULL, KMSKey = NULL, PoolId = NULL, Worm = NULL, Tags = NULL) { op <- new_operation( name = "CreateTapeWithBarcode", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$create_tape_with_barcode_input(GatewayARN = GatewayARN, TapeSizeInBytes = TapeSizeInBytes, TapeBarcode = TapeBarcode, KMSEncrypted = KMSEncrypted, KMSKey = KMSKey, PoolId = PoolId, Worm = Worm, Tags = Tags) output <- .storagegateway$create_tape_with_barcode_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$create_tape_with_barcode <- storagegateway_create_tape_with_barcode storagegateway_create_tapes <- function(GatewayARN, TapeSizeInBytes, ClientToken, NumTapesToCreate, TapeBarcodePrefix, KMSEncrypted = NULL, KMSKey = NULL, PoolId = NULL, Worm = NULL, Tags = NULL) { op <- new_operation( name = "CreateTapes", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$create_tapes_input(GatewayARN = GatewayARN, TapeSizeInBytes = TapeSizeInBytes, ClientToken = ClientToken, NumTapesToCreate = NumTapesToCreate, TapeBarcodePrefix = TapeBarcodePrefix, KMSEncrypted = KMSEncrypted, KMSKey = KMSKey, PoolId = PoolId, Worm = Worm, Tags = Tags) output <- .storagegateway$create_tapes_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$create_tapes <- storagegateway_create_tapes storagegateway_delete_automatic_tape_creation_policy <- function(GatewayARN) { op <- new_operation( name = "DeleteAutomaticTapeCreationPolicy", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$delete_automatic_tape_creation_policy_input(GatewayARN = GatewayARN) output <- .storagegateway$delete_automatic_tape_creation_policy_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$delete_automatic_tape_creation_policy <- storagegateway_delete_automatic_tape_creation_policy storagegateway_delete_bandwidth_rate_limit <- function(GatewayARN, BandwidthType) { op <- new_operation( name = "DeleteBandwidthRateLimit", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$delete_bandwidth_rate_limit_input(GatewayARN = GatewayARN, BandwidthType = BandwidthType) output <- .storagegateway$delete_bandwidth_rate_limit_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$delete_bandwidth_rate_limit <- storagegateway_delete_bandwidth_rate_limit storagegateway_delete_chap_credentials <- function(TargetARN, InitiatorName) { op <- new_operation( name = "DeleteChapCredentials", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$delete_chap_credentials_input(TargetARN = TargetARN, InitiatorName = InitiatorName) output <- .storagegateway$delete_chap_credentials_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$delete_chap_credentials <- storagegateway_delete_chap_credentials storagegateway_delete_file_share <- function(FileShareARN, ForceDelete = NULL) { op <- new_operation( name = "DeleteFileShare", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$delete_file_share_input(FileShareARN = FileShareARN, ForceDelete = ForceDelete) output <- .storagegateway$delete_file_share_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$delete_file_share <- storagegateway_delete_file_share storagegateway_delete_gateway <- function(GatewayARN) { op <- new_operation( name = "DeleteGateway", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$delete_gateway_input(GatewayARN = GatewayARN) output <- .storagegateway$delete_gateway_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$delete_gateway <- storagegateway_delete_gateway storagegateway_delete_snapshot_schedule <- function(VolumeARN) { op <- new_operation( name = "DeleteSnapshotSchedule", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$delete_snapshot_schedule_input(VolumeARN = VolumeARN) output <- .storagegateway$delete_snapshot_schedule_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$delete_snapshot_schedule <- storagegateway_delete_snapshot_schedule storagegateway_delete_tape <- function(GatewayARN, TapeARN, BypassGovernanceRetention = NULL) { op <- new_operation( name = "DeleteTape", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$delete_tape_input(GatewayARN = GatewayARN, TapeARN = TapeARN, BypassGovernanceRetention = BypassGovernanceRetention) output <- .storagegateway$delete_tape_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$delete_tape <- storagegateway_delete_tape storagegateway_delete_tape_archive <- function(TapeARN, BypassGovernanceRetention = NULL) { op <- new_operation( name = "DeleteTapeArchive", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$delete_tape_archive_input(TapeARN = TapeARN, BypassGovernanceRetention = BypassGovernanceRetention) output <- .storagegateway$delete_tape_archive_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$delete_tape_archive <- storagegateway_delete_tape_archive storagegateway_delete_tape_pool <- function(PoolARN) { op <- new_operation( name = "DeleteTapePool", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$delete_tape_pool_input(PoolARN = PoolARN) output <- .storagegateway$delete_tape_pool_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$delete_tape_pool <- storagegateway_delete_tape_pool storagegateway_delete_volume <- function(VolumeARN) { op <- new_operation( name = "DeleteVolume", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$delete_volume_input(VolumeARN = VolumeARN) output <- .storagegateway$delete_volume_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$delete_volume <- storagegateway_delete_volume storagegateway_describe_availability_monitor_test <- function(GatewayARN) { op <- new_operation( name = "DescribeAvailabilityMonitorTest", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_availability_monitor_test_input(GatewayARN = GatewayARN) output <- .storagegateway$describe_availability_monitor_test_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_availability_monitor_test <- storagegateway_describe_availability_monitor_test storagegateway_describe_bandwidth_rate_limit <- function(GatewayARN) { op <- new_operation( name = "DescribeBandwidthRateLimit", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_bandwidth_rate_limit_input(GatewayARN = GatewayARN) output <- .storagegateway$describe_bandwidth_rate_limit_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_bandwidth_rate_limit <- storagegateway_describe_bandwidth_rate_limit storagegateway_describe_bandwidth_rate_limit_schedule <- function(GatewayARN) { op <- new_operation( name = "DescribeBandwidthRateLimitSchedule", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_bandwidth_rate_limit_schedule_input(GatewayARN = GatewayARN) output <- .storagegateway$describe_bandwidth_rate_limit_schedule_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_bandwidth_rate_limit_schedule <- storagegateway_describe_bandwidth_rate_limit_schedule storagegateway_describe_cache <- function(GatewayARN) { op <- new_operation( name = "DescribeCache", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_cache_input(GatewayARN = GatewayARN) output <- .storagegateway$describe_cache_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_cache <- storagegateway_describe_cache storagegateway_describe_cachedi_scsi_volumes <- function(VolumeARNs) { op <- new_operation( name = "DescribeCachediSCSIVolumes", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_cachedi_scsi_volumes_input(VolumeARNs = VolumeARNs) output <- .storagegateway$describe_cachedi_scsi_volumes_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_cachedi_scsi_volumes <- storagegateway_describe_cachedi_scsi_volumes storagegateway_describe_chap_credentials <- function(TargetARN) { op <- new_operation( name = "DescribeChapCredentials", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_chap_credentials_input(TargetARN = TargetARN) output <- .storagegateway$describe_chap_credentials_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_chap_credentials <- storagegateway_describe_chap_credentials storagegateway_describe_gateway_information <- function(GatewayARN) { op <- new_operation( name = "DescribeGatewayInformation", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_gateway_information_input(GatewayARN = GatewayARN) output <- .storagegateway$describe_gateway_information_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_gateway_information <- storagegateway_describe_gateway_information storagegateway_describe_maintenance_start_time <- function(GatewayARN) { op <- new_operation( name = "DescribeMaintenanceStartTime", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_maintenance_start_time_input(GatewayARN = GatewayARN) output <- .storagegateway$describe_maintenance_start_time_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_maintenance_start_time <- storagegateway_describe_maintenance_start_time storagegateway_describe_nfs_file_shares <- function(FileShareARNList) { op <- new_operation( name = "DescribeNFSFileShares", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_nfs_file_shares_input(FileShareARNList = FileShareARNList) output <- .storagegateway$describe_nfs_file_shares_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_nfs_file_shares <- storagegateway_describe_nfs_file_shares storagegateway_describe_smb_file_shares <- function(FileShareARNList) { op <- new_operation( name = "DescribeSMBFileShares", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_smb_file_shares_input(FileShareARNList = FileShareARNList) output <- .storagegateway$describe_smb_file_shares_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_smb_file_shares <- storagegateway_describe_smb_file_shares storagegateway_describe_smb_settings <- function(GatewayARN) { op <- new_operation( name = "DescribeSMBSettings", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_smb_settings_input(GatewayARN = GatewayARN) output <- .storagegateway$describe_smb_settings_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_smb_settings <- storagegateway_describe_smb_settings storagegateway_describe_snapshot_schedule <- function(VolumeARN) { op <- new_operation( name = "DescribeSnapshotSchedule", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_snapshot_schedule_input(VolumeARN = VolumeARN) output <- .storagegateway$describe_snapshot_schedule_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_snapshot_schedule <- storagegateway_describe_snapshot_schedule storagegateway_describe_storedi_scsi_volumes <- function(VolumeARNs) { op <- new_operation( name = "DescribeStorediSCSIVolumes", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_storedi_scsi_volumes_input(VolumeARNs = VolumeARNs) output <- .storagegateway$describe_storedi_scsi_volumes_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_storedi_scsi_volumes <- storagegateway_describe_storedi_scsi_volumes storagegateway_describe_tape_archives <- function(TapeARNs = NULL, Marker = NULL, Limit = NULL) { op <- new_operation( name = "DescribeTapeArchives", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_tape_archives_input(TapeARNs = TapeARNs, Marker = Marker, Limit = Limit) output <- .storagegateway$describe_tape_archives_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_tape_archives <- storagegateway_describe_tape_archives storagegateway_describe_tape_recovery_points <- function(GatewayARN, Marker = NULL, Limit = NULL) { op <- new_operation( name = "DescribeTapeRecoveryPoints", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_tape_recovery_points_input(GatewayARN = GatewayARN, Marker = Marker, Limit = Limit) output <- .storagegateway$describe_tape_recovery_points_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_tape_recovery_points <- storagegateway_describe_tape_recovery_points storagegateway_describe_tapes <- function(GatewayARN, TapeARNs = NULL, Marker = NULL, Limit = NULL) { op <- new_operation( name = "DescribeTapes", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_tapes_input(GatewayARN = GatewayARN, TapeARNs = TapeARNs, Marker = Marker, Limit = Limit) output <- .storagegateway$describe_tapes_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_tapes <- storagegateway_describe_tapes storagegateway_describe_upload_buffer <- function(GatewayARN) { op <- new_operation( name = "DescribeUploadBuffer", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_upload_buffer_input(GatewayARN = GatewayARN) output <- .storagegateway$describe_upload_buffer_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_upload_buffer <- storagegateway_describe_upload_buffer storagegateway_describe_vtl_devices <- function(GatewayARN, VTLDeviceARNs = NULL, Marker = NULL, Limit = NULL) { op <- new_operation( name = "DescribeVTLDevices", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_vtl_devices_input(GatewayARN = GatewayARN, VTLDeviceARNs = VTLDeviceARNs, Marker = Marker, Limit = Limit) output <- .storagegateway$describe_vtl_devices_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_vtl_devices <- storagegateway_describe_vtl_devices storagegateway_describe_working_storage <- function(GatewayARN) { op <- new_operation( name = "DescribeWorkingStorage", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$describe_working_storage_input(GatewayARN = GatewayARN) output <- .storagegateway$describe_working_storage_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$describe_working_storage <- storagegateway_describe_working_storage storagegateway_detach_volume <- function(VolumeARN, ForceDetach = NULL) { op <- new_operation( name = "DetachVolume", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$detach_volume_input(VolumeARN = VolumeARN, ForceDetach = ForceDetach) output <- .storagegateway$detach_volume_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$detach_volume <- storagegateway_detach_volume storagegateway_disable_gateway <- function(GatewayARN) { op <- new_operation( name = "DisableGateway", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$disable_gateway_input(GatewayARN = GatewayARN) output <- .storagegateway$disable_gateway_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$disable_gateway <- storagegateway_disable_gateway storagegateway_join_domain <- function(GatewayARN, DomainName, OrganizationalUnit = NULL, DomainControllers = NULL, TimeoutInSeconds = NULL, UserName, Password) { op <- new_operation( name = "JoinDomain", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$join_domain_input(GatewayARN = GatewayARN, DomainName = DomainName, OrganizationalUnit = OrganizationalUnit, DomainControllers = DomainControllers, TimeoutInSeconds = TimeoutInSeconds, UserName = UserName, Password = Password) output <- .storagegateway$join_domain_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$join_domain <- storagegateway_join_domain storagegateway_list_automatic_tape_creation_policies <- function(GatewayARN = NULL) { op <- new_operation( name = "ListAutomaticTapeCreationPolicies", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$list_automatic_tape_creation_policies_input(GatewayARN = GatewayARN) output <- .storagegateway$list_automatic_tape_creation_policies_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$list_automatic_tape_creation_policies <- storagegateway_list_automatic_tape_creation_policies storagegateway_list_file_shares <- function(GatewayARN = NULL, Limit = NULL, Marker = NULL) { op <- new_operation( name = "ListFileShares", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$list_file_shares_input(GatewayARN = GatewayARN, Limit = Limit, Marker = Marker) output <- .storagegateway$list_file_shares_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$list_file_shares <- storagegateway_list_file_shares storagegateway_list_gateways <- function(Marker = NULL, Limit = NULL) { op <- new_operation( name = "ListGateways", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$list_gateways_input(Marker = Marker, Limit = Limit) output <- .storagegateway$list_gateways_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$list_gateways <- storagegateway_list_gateways storagegateway_list_local_disks <- function(GatewayARN) { op <- new_operation( name = "ListLocalDisks", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$list_local_disks_input(GatewayARN = GatewayARN) output <- .storagegateway$list_local_disks_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$list_local_disks <- storagegateway_list_local_disks storagegateway_list_tags_for_resource <- function(ResourceARN, Marker = NULL, Limit = NULL) { op <- new_operation( name = "ListTagsForResource", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$list_tags_for_resource_input(ResourceARN = ResourceARN, Marker = Marker, Limit = Limit) output <- .storagegateway$list_tags_for_resource_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$list_tags_for_resource <- storagegateway_list_tags_for_resource storagegateway_list_tape_pools <- function(PoolARNs = NULL, Marker = NULL, Limit = NULL) { op <- new_operation( name = "ListTapePools", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$list_tape_pools_input(PoolARNs = PoolARNs, Marker = Marker, Limit = Limit) output <- .storagegateway$list_tape_pools_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$list_tape_pools <- storagegateway_list_tape_pools storagegateway_list_tapes <- function(TapeARNs = NULL, Marker = NULL, Limit = NULL) { op <- new_operation( name = "ListTapes", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$list_tapes_input(TapeARNs = TapeARNs, Marker = Marker, Limit = Limit) output <- .storagegateway$list_tapes_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$list_tapes <- storagegateway_list_tapes storagegateway_list_volume_initiators <- function(VolumeARN) { op <- new_operation( name = "ListVolumeInitiators", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$list_volume_initiators_input(VolumeARN = VolumeARN) output <- .storagegateway$list_volume_initiators_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$list_volume_initiators <- storagegateway_list_volume_initiators storagegateway_list_volume_recovery_points <- function(GatewayARN) { op <- new_operation( name = "ListVolumeRecoveryPoints", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$list_volume_recovery_points_input(GatewayARN = GatewayARN) output <- .storagegateway$list_volume_recovery_points_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$list_volume_recovery_points <- storagegateway_list_volume_recovery_points storagegateway_list_volumes <- function(GatewayARN = NULL, Marker = NULL, Limit = NULL) { op <- new_operation( name = "ListVolumes", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$list_volumes_input(GatewayARN = GatewayARN, Marker = Marker, Limit = Limit) output <- .storagegateway$list_volumes_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$list_volumes <- storagegateway_list_volumes storagegateway_notify_when_uploaded <- function(FileShareARN) { op <- new_operation( name = "NotifyWhenUploaded", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$notify_when_uploaded_input(FileShareARN = FileShareARN) output <- .storagegateway$notify_when_uploaded_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$notify_when_uploaded <- storagegateway_notify_when_uploaded storagegateway_refresh_cache <- function(FileShareARN, FolderList = NULL, Recursive = NULL) { op <- new_operation( name = "RefreshCache", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$refresh_cache_input(FileShareARN = FileShareARN, FolderList = FolderList, Recursive = Recursive) output <- .storagegateway$refresh_cache_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$refresh_cache <- storagegateway_refresh_cache storagegateway_remove_tags_from_resource <- function(ResourceARN, TagKeys) { op <- new_operation( name = "RemoveTagsFromResource", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$remove_tags_from_resource_input(ResourceARN = ResourceARN, TagKeys = TagKeys) output <- .storagegateway$remove_tags_from_resource_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$remove_tags_from_resource <- storagegateway_remove_tags_from_resource storagegateway_reset_cache <- function(GatewayARN) { op <- new_operation( name = "ResetCache", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$reset_cache_input(GatewayARN = GatewayARN) output <- .storagegateway$reset_cache_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$reset_cache <- storagegateway_reset_cache storagegateway_retrieve_tape_archive <- function(TapeARN, GatewayARN) { op <- new_operation( name = "RetrieveTapeArchive", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$retrieve_tape_archive_input(TapeARN = TapeARN, GatewayARN = GatewayARN) output <- .storagegateway$retrieve_tape_archive_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$retrieve_tape_archive <- storagegateway_retrieve_tape_archive storagegateway_retrieve_tape_recovery_point <- function(TapeARN, GatewayARN) { op <- new_operation( name = "RetrieveTapeRecoveryPoint", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$retrieve_tape_recovery_point_input(TapeARN = TapeARN, GatewayARN = GatewayARN) output <- .storagegateway$retrieve_tape_recovery_point_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$retrieve_tape_recovery_point <- storagegateway_retrieve_tape_recovery_point storagegateway_set_local_console_password <- function(GatewayARN, LocalConsolePassword) { op <- new_operation( name = "SetLocalConsolePassword", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$set_local_console_password_input(GatewayARN = GatewayARN, LocalConsolePassword = LocalConsolePassword) output <- .storagegateway$set_local_console_password_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$set_local_console_password <- storagegateway_set_local_console_password storagegateway_set_smb_guest_password <- function(GatewayARN, Password) { op <- new_operation( name = "SetSMBGuestPassword", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$set_smb_guest_password_input(GatewayARN = GatewayARN, Password = Password) output <- .storagegateway$set_smb_guest_password_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$set_smb_guest_password <- storagegateway_set_smb_guest_password storagegateway_shutdown_gateway <- function(GatewayARN) { op <- new_operation( name = "ShutdownGateway", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$shutdown_gateway_input(GatewayARN = GatewayARN) output <- .storagegateway$shutdown_gateway_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$shutdown_gateway <- storagegateway_shutdown_gateway storagegateway_start_availability_monitor_test <- function(GatewayARN) { op <- new_operation( name = "StartAvailabilityMonitorTest", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$start_availability_monitor_test_input(GatewayARN = GatewayARN) output <- .storagegateway$start_availability_monitor_test_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$start_availability_monitor_test <- storagegateway_start_availability_monitor_test storagegateway_start_gateway <- function(GatewayARN) { op <- new_operation( name = "StartGateway", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$start_gateway_input(GatewayARN = GatewayARN) output <- .storagegateway$start_gateway_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$start_gateway <- storagegateway_start_gateway storagegateway_update_automatic_tape_creation_policy <- function(AutomaticTapeCreationRules, GatewayARN) { op <- new_operation( name = "UpdateAutomaticTapeCreationPolicy", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_automatic_tape_creation_policy_input(AutomaticTapeCreationRules = AutomaticTapeCreationRules, GatewayARN = GatewayARN) output <- .storagegateway$update_automatic_tape_creation_policy_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_automatic_tape_creation_policy <- storagegateway_update_automatic_tape_creation_policy storagegateway_update_bandwidth_rate_limit <- function(GatewayARN, AverageUploadRateLimitInBitsPerSec = NULL, AverageDownloadRateLimitInBitsPerSec = NULL) { op <- new_operation( name = "UpdateBandwidthRateLimit", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_bandwidth_rate_limit_input(GatewayARN = GatewayARN, AverageUploadRateLimitInBitsPerSec = AverageUploadRateLimitInBitsPerSec, AverageDownloadRateLimitInBitsPerSec = AverageDownloadRateLimitInBitsPerSec) output <- .storagegateway$update_bandwidth_rate_limit_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_bandwidth_rate_limit <- storagegateway_update_bandwidth_rate_limit storagegateway_update_bandwidth_rate_limit_schedule <- function(GatewayARN, BandwidthRateLimitIntervals) { op <- new_operation( name = "UpdateBandwidthRateLimitSchedule", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_bandwidth_rate_limit_schedule_input(GatewayARN = GatewayARN, BandwidthRateLimitIntervals = BandwidthRateLimitIntervals) output <- .storagegateway$update_bandwidth_rate_limit_schedule_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_bandwidth_rate_limit_schedule <- storagegateway_update_bandwidth_rate_limit_schedule storagegateway_update_chap_credentials <- function(TargetARN, SecretToAuthenticateInitiator, InitiatorName, SecretToAuthenticateTarget = NULL) { op <- new_operation( name = "UpdateChapCredentials", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_chap_credentials_input(TargetARN = TargetARN, SecretToAuthenticateInitiator = SecretToAuthenticateInitiator, InitiatorName = InitiatorName, SecretToAuthenticateTarget = SecretToAuthenticateTarget) output <- .storagegateway$update_chap_credentials_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_chap_credentials <- storagegateway_update_chap_credentials storagegateway_update_gateway_information <- function(GatewayARN, GatewayName = NULL, GatewayTimezone = NULL, CloudWatchLogGroupARN = NULL) { op <- new_operation( name = "UpdateGatewayInformation", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_gateway_information_input(GatewayARN = GatewayARN, GatewayName = GatewayName, GatewayTimezone = GatewayTimezone, CloudWatchLogGroupARN = CloudWatchLogGroupARN) output <- .storagegateway$update_gateway_information_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_gateway_information <- storagegateway_update_gateway_information storagegateway_update_gateway_software_now <- function(GatewayARN) { op <- new_operation( name = "UpdateGatewaySoftwareNow", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_gateway_software_now_input(GatewayARN = GatewayARN) output <- .storagegateway$update_gateway_software_now_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_gateway_software_now <- storagegateway_update_gateway_software_now storagegateway_update_maintenance_start_time <- function(GatewayARN, HourOfDay, MinuteOfHour, DayOfWeek = NULL, DayOfMonth = NULL) { op <- new_operation( name = "UpdateMaintenanceStartTime", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_maintenance_start_time_input(GatewayARN = GatewayARN, HourOfDay = HourOfDay, MinuteOfHour = MinuteOfHour, DayOfWeek = DayOfWeek, DayOfMonth = DayOfMonth) output <- .storagegateway$update_maintenance_start_time_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_maintenance_start_time <- storagegateway_update_maintenance_start_time storagegateway_update_nfs_file_share <- function(FileShareARN, KMSEncrypted = NULL, KMSKey = NULL, NFSFileShareDefaults = NULL, DefaultStorageClass = NULL, ObjectACL = NULL, ClientList = NULL, Squash = NULL, ReadOnly = NULL, GuessMIMETypeEnabled = NULL, RequesterPays = NULL, FileShareName = NULL, CacheAttributes = NULL, NotificationPolicy = NULL) { op <- new_operation( name = "UpdateNFSFileShare", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_nfs_file_share_input(FileShareARN = FileShareARN, KMSEncrypted = KMSEncrypted, KMSKey = KMSKey, NFSFileShareDefaults = NFSFileShareDefaults, DefaultStorageClass = DefaultStorageClass, ObjectACL = ObjectACL, ClientList = ClientList, Squash = Squash, ReadOnly = ReadOnly, GuessMIMETypeEnabled = GuessMIMETypeEnabled, RequesterPays = RequesterPays, FileShareName = FileShareName, CacheAttributes = CacheAttributes, NotificationPolicy = NotificationPolicy) output <- .storagegateway$update_nfs_file_share_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_nfs_file_share <- storagegateway_update_nfs_file_share storagegateway_update_smb_file_share <- function(FileShareARN, KMSEncrypted = NULL, KMSKey = NULL, DefaultStorageClass = NULL, ObjectACL = NULL, ReadOnly = NULL, GuessMIMETypeEnabled = NULL, RequesterPays = NULL, SMBACLEnabled = NULL, AccessBasedEnumeration = NULL, AdminUserList = NULL, ValidUserList = NULL, InvalidUserList = NULL, AuditDestinationARN = NULL, CaseSensitivity = NULL, FileShareName = NULL, CacheAttributes = NULL, NotificationPolicy = NULL) { op <- new_operation( name = "UpdateSMBFileShare", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_smb_file_share_input(FileShareARN = FileShareARN, KMSEncrypted = KMSEncrypted, KMSKey = KMSKey, DefaultStorageClass = DefaultStorageClass, ObjectACL = ObjectACL, ReadOnly = ReadOnly, GuessMIMETypeEnabled = GuessMIMETypeEnabled, RequesterPays = RequesterPays, SMBACLEnabled = SMBACLEnabled, AccessBasedEnumeration = AccessBasedEnumeration, AdminUserList = AdminUserList, ValidUserList = ValidUserList, InvalidUserList = InvalidUserList, AuditDestinationARN = AuditDestinationARN, CaseSensitivity = CaseSensitivity, FileShareName = FileShareName, CacheAttributes = CacheAttributes, NotificationPolicy = NotificationPolicy) output <- .storagegateway$update_smb_file_share_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_smb_file_share <- storagegateway_update_smb_file_share storagegateway_update_smb_file_share_visibility <- function(GatewayARN, FileSharesVisible) { op <- new_operation( name = "UpdateSMBFileShareVisibility", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_smb_file_share_visibility_input(GatewayARN = GatewayARN, FileSharesVisible = FileSharesVisible) output <- .storagegateway$update_smb_file_share_visibility_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_smb_file_share_visibility <- storagegateway_update_smb_file_share_visibility storagegateway_update_smb_security_strategy <- function(GatewayARN, SMBSecurityStrategy) { op <- new_operation( name = "UpdateSMBSecurityStrategy", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_smb_security_strategy_input(GatewayARN = GatewayARN, SMBSecurityStrategy = SMBSecurityStrategy) output <- .storagegateway$update_smb_security_strategy_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_smb_security_strategy <- storagegateway_update_smb_security_strategy storagegateway_update_snapshot_schedule <- function(VolumeARN, StartAt, RecurrenceInHours, Description = NULL, Tags = NULL) { op <- new_operation( name = "UpdateSnapshotSchedule", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_snapshot_schedule_input(VolumeARN = VolumeARN, StartAt = StartAt, RecurrenceInHours = RecurrenceInHours, Description = Description, Tags = Tags) output <- .storagegateway$update_snapshot_schedule_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_snapshot_schedule <- storagegateway_update_snapshot_schedule storagegateway_update_vtl_device_type <- function(VTLDeviceARN, DeviceType) { op <- new_operation( name = "UpdateVTLDeviceType", http_method = "POST", http_path = "/", paginator = list() ) input <- .storagegateway$update_vtl_device_type_input(VTLDeviceARN = VTLDeviceARN, DeviceType = DeviceType) output <- .storagegateway$update_vtl_device_type_output() config <- get_config() svc <- .storagegateway$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .storagegateway$operations$update_vtl_device_type <- storagegateway_update_vtl_device_type
Chao1_sharedFun <- function(x1, x2, conf=0.95) { f2p <- sum(x1 == 2 & x2 >= 1) fp2 <- sum(x1 >= 1 & x2 == 2) est <- Chao1_sharedEstFun(x1, x2) if (f2p == 0 || fp2 == 0) { se <- VarEstFun(x1, x2, diffFun=diff_Chao1bc, FunName=Chao1_bcEstFun) } else { se <- VarEstFun(x1, x2, diff_Chao1, FunName=Chao1_sharedEstFun) } CI <- logCI(x1, x2, est, se, conf) out <- matrix(c(est, se, CI), nrow = 1) rownames(out) <- c("Chao1(shared)") colnames(out) <- c("Estimator", "Est_s.e.", paste(conf*100, "% Lower"), paste(conf*100, "% Upper")) return(out) }
library(testthat) library(MOFA2) test_check("MOFA2")
context("Summarizing table structure") test_that("path summaries", { lyt <- basic_table() %>% split_cols_by("ARM") %>% split_cols_by("SEX", "Gender", labels_var = "gend_label") %>% add_colcounts() %>% split_rows_by("RACE", "Ethnicity", labels_var = "ethn_label", label_pos = "hidden") %>% summarize_row_groups("RACE", label_fstr = "%s (n)") %>% split_rows_by("FACTOR2", "Factor2", split_fun = remove_split_levels("C"), labels_var = "fac2_label", label_pos = "hidden") %>% summarize_row_groups("FACTOR2") %>% analyze("AGE", "Age Analysis", afun = function(x) list(mean = mean(x), median = median(x)), format = "xx.xx") %>% analyze("AGE", "Age Analysis redux", afun = range, format = "xx.x - xx.x", table_names = "AgeRedux") %>% analyze("VAR3", "Var3 Counts", afun = list_wrap_x(table), nested = FALSE) tbl <- build_table(lyt, rawdat) cpathsum <- col_paths_summary(tbl) arm1tmp <- c("ARM", "ARM1") arm2tmp <- c("ARM", "ARM2") expect_identical(cpathsum, data.frame(label = c("ARM1", "Male", "Female", "ARM2", "Male", "Female"), path = I(list(arm1tmp, c(arm1tmp, c("SEX", "M")), c(arm1tmp, c("SEX", "F")), arm2tmp, c(arm2tmp, c("SEX", "M")), c(arm2tmp, c("SEX", "F")))), stringsAsFactors = FALSE)) cpval <- col_paths(tbl) expect_identical(cpval, cpathsum$path[-c(1, 4)]) rpathsum <- row_paths_summary(tbl) expect_identical(complx_lyt_rnames, rpathsum$label) expect_identical(row_paths(tbl), rpathsum$path) })
knitr::opts_chunk$set( collapse = TRUE, comment = " eval = TRUE ) library(antaresEditObject) path <- tempdir() createStudy(path = path, study_name = "my-study") updateGeneralSettings(nbyears = 10) createArea("earth") createCluster(area = "earth", cluster_name = "america", add_prefix = FALSE) createCluster(area = "earth", cluster_name = "africa", add_prefix = FALSE) createCluster(area = "earth", cluster_name = "europe", add_prefix = FALSE) createArea("moon") createCluster(area = "moon", cluster_name = "tranquility", add_prefix = FALSE) createCluster(area = "moon", cluster_name = "serenety", add_prefix = FALSE) getAreas() readClusterDesc() readScenarioBuilder() scenarioBuilder(n_scenario = 3) scenarioBuilder(n_scenario = 5) scenarioBuilder(n_scenario = 3, areas = "earth") scenarioBuilder(n_scenario = 3, areas_rand = "earth") my_scenario <- scenarioBuilder(n_scenario = 3) updateScenarioBuilder(ldata = my_scenario, series = "load") updateScenarioBuilder(ldata = list(l = my_scenario)) my_scenario <- scenarioBuilder(n_scenario = 3) updateScenarioBuilder( ldata = my_scenario, series = c("load", "hydro", "solar") ) load_scenario <- scenarioBuilder(n_scenario = 3) hydro_scenario <- scenarioBuilder(n_scenario = 4) solar_scenario <- scenarioBuilder(n_scenario = 5) updateScenarioBuilder(ldata = list( l = load_scenario, h = hydro_scenario, s = solar_scenario )) readScenarioBuilder() my_scenario <- scenarioBuilder(n_scenario = 3) updateScenarioBuilder( ldata = my_scenario, series = "thermal" ) readScenarioBuilder()$t updateScenarioBuilder( ldata = my_scenario, series = "thermal", clusters_areas = data.table::data.table( area = c("earth", "earth"), cluster = c("africa", "europe") ) ) readScenarioBuilder()$t clearScenarioBuilder() unlink(file.path(path, "my-study"), recursive = TRUE)
data("SATcoaching", package = "clubSandwich") suppressPackageStartupMessages(library(robumeta)) full_model <- robu(d ~ 0 + study_type + hrs + test, studynum = study, var.eff.size = V, small = FALSE, data = SATcoaching) res <- Wald_test_cwb(full_model = full_model, constraints = constrain_equal(1:3), R = 99) test_that("plot() returns a ggplot2 object when run on a Wald_test_wildemeta",{ x <- plot(res) y <- plot(res, fill = "purple", alpha = 0.5) + ggplot2::theme_light() expect_s3_class(x, "ggplot") expect_s3_class(y, "ggplot") }) test_that("plot() throws an error if ggplot2 is not installed.", { mockery::stub(plot.Wald_test_wildmeta, 'ggplot2_is_missing', TRUE) expect_error(plot(res)) })
vector.alpha <- function(x, set, type="cor", CI=.95, CItype="xci", minval=-1.0) { comb.data <- data.frame(cbind(x, set)) comp.data <- subset(comb.data, complete.cases(comb.data)) N <- nrow(comp.data) if(type=="cor") { std.data <- data.frame(scale2(comp.data)) Zcross.prod <- std.data$x * std.data[2:length(std.data)] tZcross.prod <- data.frame(t(Zcross.prod)) Zcov.mat <- cov(tZcross.prod) Zcor.mat <- cor(tZcross.prod) Zavg.r <- mean(Zcor.mat[upper.tri(Zcor.mat)]) Zalpha <- alpha.cov(Zcov.mat) Zalpha <- ifelse(Zalpha >= minval, Zalpha, minval) if(CItype=="xci") { ZCIs <- alpha.xci(Zalpha, k=N, n=ncol(set), CI=CI) } if(CItype=="aci") { ZCIs <- alpha.aci(Zalpha, k=N, n=ncol(set), CI=CI) } out <- rbind(N, Zavg.r, Zalpha, ZCIs[1], ZCIs[2]) } if(type=="cov") { cnt.data <- data.frame(scale2(comp.data, scale=F)) Ccross.prod <- cnt.data$x * cnt.data[2:length(cnt.data)] tCcross.prod <- data.frame(t(Ccross.prod)) Ccov.mat <- cov(tCcross.prod) Ccor.mat <- cor(tCcross.prod) Cavg.r <- mean(Ccor.mat[upper.tri(Ccor.mat)]) Calpha <- alpha.cov(Ccov.mat) Calpha <- ifelse(Calpha >= minval, Calpha, minval) if(CItype=="xci") { CCIs <- alpha.xci(Calpha, k=N, n=ncol(set), CI=CI) } if(CItype=="aci") { CCIs <- alpha.aci(Calpha, k=N, n=ncol(set), CI=CI) } out <- rbind(N, Cavg.r, Calpha, CCIs[1], CCIs[2]) } if(type=="XY") { cnt.data <- data.frame(scale2(comp.data, scale=F)) Ccross.prod <- cnt.data$x * cnt.data[2:length(cnt.data)] XYelems <- Ccross.prod / (var(comp.data$x)*(N-1)/N) tXYelems <- data.frame(t(XYelems)) XYcov.mat <- cov(tXYelems) XYcor.mat <- cor(tXYelems) XYavg.r <- mean(XYcor.mat[upper.tri(XYcor.mat)]) XYalpha <- alpha.cov(XYcov.mat) XYalpha <- ifelse(XYalpha >= minval, XYalpha, minval) if(CItype=="xci") { XYCIs <- alpha.xci(XYalpha, k=N, n=ncol(set), CI=CI) } if(CItype=="aci") { XYCIs <- alpha.aci(XYalpha, k=N, n=ncol(set), CI=CI) } out <- rbind(N, XYavg.r, XYalpha, XYCIs[1], XYCIs[2]) } if(type=="YX") { cnt.data <- data.frame(scale2(comp.data, scale=F)) y.vars <- diag(var(cnt.data[2:length(cnt.data)]))*(N-1)/N y.mat <- matrix(rep(y.vars, N), nrow=N, ncol=length(y.vars), byrow=T) YXelems <- cnt.data$x * cnt.data[2:length(cnt.data)] / y.mat tYXelems <- data.frame(t(YXelems)) YXcov.mat <- cov(tYXelems) YXcor.mat <- cor(tYXelems) YXavg.r <- mean(YXcor.mat[upper.tri(YXcor.mat)]) YXalpha <- alpha.cov(YXcov.mat) YXalpha <- ifelse(YXalpha >= minval, YXalpha, minval) if(CItype=="xci") { YXCIs <- alpha.xci(YXalpha, k=N, n=ncol(set), CI=CI) } if(CItype=="aci") { YXCIs <- alpha.aci(YXalpha, k=N, n=ncol(set), CI=CI) } out <- rbind(N, YXavg.r, YXalpha, YXCIs[1], YXCIs[2]) } colnames(out) <- c("Results") rownames(out) <- c("N", "Average r", "Alpha", "Lower Limit", "Upper Limit") return(out) }
duncan.test <- function (y, trt, DFerror, MSerror, alpha=0.05, group=TRUE,main = NULL,console=FALSE) { name.y <- paste(deparse(substitute(y))) name.t <- paste(deparse(substitute(trt))) if(is.null(main))main<-paste(name.y,"~", name.t) clase<-c("aov","lm") if("aov"%in%class(y) | "lm"%in%class(y)){ if(is.null(main))main<-y$call A<-y$model DFerror<-df.residual(y) MSerror<-deviance(y)/DFerror y<-A[,1] ipch<-pmatch(trt,names(A)) nipch<- length(ipch) for(i in 1:nipch){ if (is.na(ipch[i])) return(if(console)cat("Name: ", trt, "\n", names(A)[-1], "\n")) } name.t<- names(A)[ipch][1] trt <- A[, ipch] if (nipch > 1){ trt <- A[, ipch[1]] for(i in 2:nipch){ name.t <- paste(name.t,names(A)[ipch][i],sep=":") trt <- paste(trt,A[,ipch[i]],sep=":") }} name.y <- names(A)[1] } junto <- subset(data.frame(y, trt), is.na(y) == FALSE) Mean<-mean(junto[,1]) CV<-sqrt(MSerror)*100/Mean medians<-tapply.stat(junto[,1],junto[,2],stat="median") for(i in c(1,5,2:4)) { x <- tapply.stat(junto[,1],junto[,2],function(x)quantile(x)[i]) medians<-cbind(medians,x[,2]) } medians<-medians[,3:7] names(medians)<-c("Min","Max","Q25","Q50","Q75") means <- tapply.stat(junto[,1],junto[,2],stat="mean") sds <- tapply.stat(junto[,1],junto[,2],stat="sd") nn <- tapply.stat(junto[,1],junto[,2],stat="length") means<-data.frame(means,std=sds[,2],r=nn[,2],medians) names(means)[1:2]<-c(name.t,name.y) ntr<-nrow(means) Tprob<-NULL k<-0 for(i in 2:ntr){ k<-k+1 x <- suppressWarnings(warning(qtukey((1-alpha)^(i-1), i, DFerror))) if(x=="NaN")break else Tprob[k]<-x } if(k<(ntr-1)){ for(i in k:(ntr-1)){ f <- Vectorize(function(x)ptukey(x,i+1,DFerror)-(1-alpha)^i) Tprob[i]<-uniroot(f, c(0,100))$root } } Tprob<-as.numeric(Tprob) nr <- unique(nn[,2]) if(console){ cat("\nStudy:", main) cat("\n\nDuncan's new multiple range test\nfor",name.y,"\n") cat("\nMean Square Error: ",MSerror,"\n\n") cat(paste(name.t,",",sep="")," means\n\n") print(data.frame(row.names = means[,1], means[,2:6])) } if(length(nr) == 1 ) sdtdif <- sqrt(MSerror/nr) else { nr1 <- 1/mean(1/nn[,2]) sdtdif <- sqrt(MSerror/nr1) } DUNCAN <- Tprob * sdtdif names(DUNCAN)<-2:ntr duncan<-data.frame(Table=Tprob,CriticalRange=DUNCAN) if ( group & length(nr) == 1 & console){ cat("\nAlpha:",alpha,"; DF Error:",DFerror,"\n") cat("\nCritical Range\n") print(DUNCAN) } if ( group & length(nr) != 1 & console) cat("\nGroups according to probability of means differences and alpha level(",alpha,")\n") if ( length(nr) != 1) duncan<-NULL Omeans<-order(means[,2],decreasing = TRUE) Ordindex<-order(Omeans) comb <-utils::combn(ntr,2) nn<-ncol(comb) dif<-rep(0,nn) DIF<-dif LCL<-dif UCL<-dif pvalue<-dif odif<-dif sig<-NULL for (k in 1:nn) { i<-comb[1,k] j<-comb[2,k] dif[k]<-means[i,2]-means[j,2] DIF[k]<-abs(dif[k]) nx<-abs(i-j)+1 odif[k] <- abs(Ordindex[i]- Ordindex[j])+1 pvalue[k]<- round(1-ptukey(DIF[k]/sdtdif,odif[k],DFerror)^(1/(odif[k]-1)),4) LCL[k] <- dif[k] - DUNCAN[odif[k]-1] UCL[k] <- dif[k] + DUNCAN[odif[k]-1] sig[k]<-" " if (pvalue[k] <= 0.001) sig[k]<-"***" else if (pvalue[k] <= 0.01) sig[k]<-"**" else if (pvalue[k] <= 0.05) sig[k]<-"*" else if (pvalue[k] <= 0.1) sig[k]<-"." } if(!group){ tr.i <- means[comb[1, ],1] tr.j <- means[comb[2, ],1] comparison<-data.frame("difference" = dif, pvalue=pvalue,"signif."=sig,LCL,UCL) rownames(comparison)<-paste(tr.i,tr.j,sep=" - ") if(console){cat("\nComparison between treatments means\n\n") print(comparison)} groups=NULL } if (group) { comparison=NULL Q<-matrix(1,ncol=ntr,nrow=ntr) p<-pvalue k<-0 for(i in 1:(ntr-1)){ for(j in (i+1):ntr){ k<-k+1 Q[i,j]<-p[k] Q[j,i]<-p[k] } } groups <- orderPvalue(means[, 1], means[, 2],alpha, Q,console) names(groups)[1]<-name.y if(console) { cat("\nMeans with the same letter are not significantly different.\n\n") print(groups) } } parameters<-data.frame(test="Duncan",name.t=name.t,ntr = ntr,alpha=alpha) statistics<-data.frame(MSerror=MSerror,Df=DFerror,Mean=Mean,CV=CV) rownames(parameters)<-" " rownames(statistics)<-" " rownames(means)<-means[,1] means<-means[,-1] output<-list(statistics=statistics,parameters=parameters, duncan=duncan, means=means,comparison=comparison,groups=groups) class(output)<-"group" invisible(output) }
plot_ly <- function(data=data.frame(), ..., type=NULL, name=NULL, color=NULL, colors=NULL, alpha=NULL, stroke=NULL, strokes=NULL, alpha_stroke=1, size=NULL, sizes=c(10, 100), span=NULL, spans=c(1, 20), symbol=NULL, symbols=NULL, linetype=NULL, linetypes=NULL, split=NULL, frame=NULL, width=NULL, height=NULL, source="A") { UseMethod("plot_ly") } plot_ly.tbl_df <- function(data=data.frame(), ..., type=NULL, name=NULL, color=NULL, colors=NULL, alpha=NULL, stroke=NULL, strokes=NULL, alpha_stroke=1, size=NULL, sizes=c(10, 100), span=NULL, spans=c(1, 20), symbol=NULL, symbols=NULL, linetype=NULL, linetypes=NULL, split=NULL, frame=NULL, width=NULL, height=NULL, source="A") { data %>% drop_class("tbl_df") %>% plotly::plot_ly(..., type=type, name=name, color=color, colors=colors, alpha=alpha, stroke=stroke, strokes=strokes, alpha_stroke=alpha_stroke, size=size, sizes=sizes, span=span, spans=spans, symbol=symbol, symbols=symbols, linetype=linetype, linetypes=linetypes, split=split, frame=frame, width=width, height=height, source=source ) } plot_ly.Seurat <- function(data = data.frame(), ..., type = NULL, name= NULL, color= NULL, colors = NULL, alpha = NULL, stroke= NULL, strokes = NULL, alpha_stroke = 1, size= NULL, sizes = c(10, 100), span= NULL, spans = c(1, 20), symbol= NULL, symbols = NULL, linetype= NULL, linetypes = NULL, split= NULL, frame= NULL, width = NULL, height = NULL, source = "A") { data %>% as_tibble() %>% plot_ly( ...,type = type, name = name, color = color, colors = colors, alpha = alpha, stroke =stroke, strokes = strokes, alpha_stroke = alpha_stroke, size = size, sizes = sizes, span = span, spans = spans, symbol = symbol, symbols = symbols, linetype = linetype, linetypes = linetypes, split = split, frame = frame, width = width, height = height, source =source) }
testthat::context(desc="Test nextBox() function") testthat::test_that(desc="Test, if nextBox() throws errors/warnings on wrong arguments", { testthat::expect_error(object=nextBox()) }) testthat::test_that(desc="Test, if nextBox() returns results of same length as input", { testthat::expect_equivalent(object=length(nextBox(quote=rpois(1,100),status="X")),expected=1) testthat::expect_equivalent(object=length(nextBox(quote=rpois(1,100),status="O")),expected=1) length <- 1+rpois(1,10) input <- rpois(length,30) testthat::expect_equivalent(object=length(nextBox(quote=input,status="X")),expected=length) testthat::expect_equivalent(object=length(nextBox(quote=input,status="O")),expected=length) }) testthat::test_that(desc="Test, if nextBox() produces appropriate return values for boxsize=1 and status=X and log=F", { testthat::expect_equal(object=nextBox(quote=46.00,status="X",boxsize=1L,log=F),expected=47.00) testthat::expect_equal(object=nextBox(quote=46.01,status="X",boxsize=1L,log=F),expected=47.00) testthat::expect_equal(object=nextBox(quote=46.99,status="X",boxsize=1L,log=F),expected=47.00) testthat::expect_equal(object=nextBox(quote=47.00,status="X",boxsize=1L,log=F),expected=48.00) }) testthat::test_that(desc="Test, if nextBox() produces appropriate return values for boxsize=0.5 and status=X", { testthat::expect_equal(object=nextBox(quote=46.00,status="X",boxsize=0.5,log=F),expected=46.50) testthat::expect_equal(object=nextBox(quote=46.01,status="X",boxsize=0.5,log=F),expected=46.50) testthat::expect_equal(object=nextBox(quote=46.99,status="X",boxsize=0.5,log=F),expected=47.00) testthat::expect_equal(object=nextBox(quote=47.00,status="X",boxsize=0.5,log=F),expected=47.50) }) testthat::test_that(desc="Test, if nextBox() produces appropriate return values for boxsize=1 and status=O and log=F", { testthat::expect_equal(object=nextBox(quote=46.00,status="O",boxsize=1L,log=F),expected=45.00) testthat::expect_equal(object=nextBox(quote=46.01,status="O",boxsize=1L,log=F),expected=46.00) testthat::expect_equal(object=nextBox(quote=46.99,status="O",boxsize=1L,log=F),expected=46.00) testthat::expect_equal(object=nextBox(quote=47.00,status="O",boxsize=1L,log=F),expected=46.00) }) testthat::test_that(desc="Test, if nextBox() produces appropriate return values for boxsize=0.5 and status=O", { testthat::expect_equal(object=nextBox(quote=46.00,status="O",boxsize=0.5,log=F),expected=45.50) testthat::expect_equal(object=nextBox(quote=46.01,status="O",boxsize=0.5,log=F),expected=46.00) testthat::expect_equal(object=nextBox(quote=46.99,status="O",boxsize=0.5,log=F),expected=46.50) testthat::expect_equal(object=nextBox(quote=47.00,status="O",boxsize=0.5,log=F),expected=46.50) }) calcQuoteFromBoxnumberForLog <- function(boxnumber, eps, boxsize) { exp((boxnumber+eps)*boxsize) } testthat::test_that(desc="Test, if nextBox() produces appropriate return values for boxsize=1% and status=X and log=T", { boxsize=getLogBoxsize(1) boxnumber=385 testthat::expect_equal(object=nextBox(quote=calcQuoteFromBoxnumberForLog(boxnumber,0.00, boxsize), status="X",boxsize=boxsize,log=T), expected=calcQuoteFromBoxnumberForLog(boxnumber,1.0, boxsize)) testthat::expect_equal(object=nextBox(quote=calcQuoteFromBoxnumberForLog(boxnumber,0.01, boxsize), status="X",boxsize=boxsize,log=T), expected=calcQuoteFromBoxnumberForLog(boxnumber,1.0, boxsize)) testthat::expect_equal(object=nextBox(quote=calcQuoteFromBoxnumberForLog(boxnumber,0.99, boxsize), status="X",boxsize=boxsize,log=T), expected=calcQuoteFromBoxnumberForLog(boxnumber,1.0, boxsize)) testthat::expect_equal(object=nextBox(quote=calcQuoteFromBoxnumberForLog(boxnumber,1.00, boxsize), status="X",boxsize=boxsize,log=T), expected=calcQuoteFromBoxnumberForLog(boxnumber,2.0, boxsize)) }) testthat::test_that(desc="Test, if nextBox() produces appropriate return values for boxsize=1% and status=O and log=T", { boxsize=getLogBoxsize(1) boxnumber=385 testthat::expect_equal(object=nextBox(quote=calcQuoteFromBoxnumberForLog(boxnumber,0.00, boxsize), status="O",boxsize=boxsize,log=T), expected=calcQuoteFromBoxnumberForLog(boxnumber,-1.0, boxsize)) testthat::expect_equal(object=nextBox(quote=calcQuoteFromBoxnumberForLog(boxnumber,0.01, boxsize), status="O",boxsize=boxsize,log=T), expected=calcQuoteFromBoxnumberForLog(boxnumber,0.0, boxsize)) testthat::expect_equal(object=nextBox(quote=calcQuoteFromBoxnumberForLog(boxnumber,0.99, boxsize), status="O",boxsize=boxsize,log=T), expected=calcQuoteFromBoxnumberForLog(boxnumber,0.0, boxsize)) testthat::expect_equal(object=nextBox(quote=calcQuoteFromBoxnumberForLog(boxnumber,1.00, boxsize), status="O",boxsize=boxsize,log=T), expected=calcQuoteFromBoxnumberForLog(boxnumber,0.0, boxsize)) })
is.keyvalue <- function(x){ inherits(x, "keyvalue") } is.keyvalue11 <- function(x){ is.keyvalue(x) && attr(x, "keyvalue11") }
"parties_v" "parties_df" "polls"
leave1out.rma.peto <- function(x, digits, transf, targs, progbar=FALSE, ...) { mstyle <- .get.mstyle("crayon" %in% .packages()) .chkclass(class(x), must="rma.peto") na.act <- getOption("na.action") if (!is.element(na.act, c("na.omit", "na.exclude", "na.fail", "na.pass"))) stop(mstyle$stop("Unknown 'na.action' specified under options().")) if (!x$int.only) stop(mstyle$stop("Method only applicable for models without moderators.")) if (x$k == 1) stop(mstyle$stop("Stopped because k = 1.")) if (missing(digits)) { digits <- .get.digits(xdigits=x$digits, dmiss=TRUE) } else { digits <- .get.digits(digits=digits, xdigits=x$digits, dmiss=FALSE) } if (missing(transf)) transf <- FALSE if (missing(targs)) targs <- NULL ddd <- list(...) .chkdots(ddd, c("time")) if (.isTRUE(ddd$time)) time.start <- proc.time() beta <- rep(NA_real_, x$k.f) se <- rep(NA_real_, x$k.f) zval <- rep(NA_real_, x$k.f) pval <- rep(NA_real_, x$k.f) ci.lb <- rep(NA_real_, x$k.f) ci.ub <- rep(NA_real_, x$k.f) QE <- rep(NA_real_, x$k.f) QEp <- rep(NA_real_, x$k.f) I2 <- rep(NA_real_, x$k.f) H2 <- rep(NA_real_, x$k.f) if (progbar) pbar <- pbapply::startpb(min=0, max=x$k.f) for (i in seq_len(x$k.f)) { if (progbar) pbapply::setpb(pbar, i) if (!x$not.na[i]) next res <- try(suppressWarnings(rma.peto(ai=x$ai.f, bi=x$bi.f, ci=x$ci.f, di=x$di.f, add=x$add, to=x$to, drop00=x$drop00, level=x$level, subset=-i)), silent=TRUE) if (inherits(res, "try-error")) next beta[i] <- res$beta se[i] <- res$se zval[i] <- res$zval pval[i] <- res$pval ci.lb[i] <- res$ci.lb ci.ub[i] <- res$ci.ub QE[i] <- res$QE QEp[i] <- res$QEp I2[i] <- res$I2 H2[i] <- res$H2 } if (progbar) pbapply::closepb(pbar) if (.isTRUE(transf)) transf <- exp if (is.function(transf)) { if (is.null(targs)) { beta <- sapply(beta, transf) se <- rep(NA,x$k.f) ci.lb <- sapply(ci.lb, transf) ci.ub <- sapply(ci.ub, transf) } else { beta <- sapply(beta, transf, targs) se <- rep(NA,x$k.f) ci.lb <- sapply(ci.lb, transf, targs) ci.ub <- sapply(ci.ub, transf, targs) } transf <- TRUE } tmp <- .psort(ci.lb, ci.ub) ci.lb <- tmp[,1] ci.ub <- tmp[,2] if (na.act == "na.omit") { out <- list(estimate=beta[x$not.na], se=se[x$not.na], zval=zval[x$not.na], pval=pval[x$not.na], ci.lb=ci.lb[x$not.na], ci.ub=ci.ub[x$not.na], Q=QE[x$not.na], Qp=QEp[x$not.na], I2=I2[x$not.na], H2=H2[x$not.na]) out$slab <- x$slab[x$not.na] } if (na.act == "na.exclude" || na.act == "na.pass") { out <- list(estimate=beta, se=se, zval=zval, pval=pval, ci.lb=ci.lb, ci.ub=ci.ub, Q=QE, Qp=QEp, I2=I2, H2=H2) out$slab <- x$slab } if (na.act == "na.fail" && any(!x$not.na)) stop(mstyle$stop("Missing values in results.")) out$digits <- digits out$transf <- transf if (.isTRUE(ddd$time)) { time.end <- proc.time() .print.time(unname(time.end - time.start)[3]) } class(out) <- "list.rma" return(out) }
summary.addreg <- function(object, correlation = FALSE, ...) { df.r <- object$df.residual coef.p <- object$coefficients p <- length(object$coefficients) dispersion <- 1 if(!object$boundary) { if(object$family$family == "poisson") { x <- object$x y <- object$y s <- if (!is.null(object$standard)) object$standard else rep(1, NROW(y)) eta <- object$linear.predictors info <- t(x) %*% apply(x,2,"*",s/eta) covmat.unscaled <- try(solve(info), silent = TRUE) } else if(object$family$family == "binomial") { x <- object$x s <- object$prior.weights y <- s * object$y eta <- object$linear.predictors info1 <- t(x) %*% apply(x,2,"*",s/eta) info2 <- t(x) %*% apply(x,2,"*",s/(1-eta)) info <- info1 + info2 covmat.unscaled <- try(solve(info), silent = TRUE) } else if(substr(object$family$family,1,7) == "negbin1") { x <- object$x y <- object$y s <- if (!is.null(object$standard)) object$standard else rep(1, NROW(y)) mu <- object$fitted.values phi <- object$scale - 1 r <- mu / phi dgd <- tgd <- rep(0, length(y)) dgd[y > 0] <- mapply(function(r, y) sum(1/(r + seq_len(y) - 1)), r = r[y > 0], y = y[y > 0]) tgd[y > 0] <- mapply(function(r, y) -sum(1/(r + seq_len(y) - 1)^2), r = r[y > 0], y = y[y > 0]) info1 <- -t(apply(x, 2, "*", s^2 * tgd)) %*% x / phi^2 info2 <- t(x) %*% (s/phi^2 * (r * tgd + dgd + phi/(phi+1) - log(phi+1))) info3 <- -sum(r/phi * (2/phi * (dgd + phi/(phi+1) - log(phi+1)) + r/phi * tgd + phi/(phi+1)^2) - y*(2*phi+1)/(phi*(phi+1))^2) info <- rbind(cbind(info1, info2), c(info2, info3)) covmat.full <- try(solve(info), silent = TRUE) if(!inherits(covmat.full,"try-error") | all(is.nan(covmat.full))) { covmat.unscaled <- covmat.full[(1:p),(1:p), drop = FALSE] var.phi <- covmat.full[(p+1),(p+1)] } else { covmat.unscaled <- matrix(NaN, p, p) var.phi <- NaN } } if(!inherits(covmat.unscaled,"try-error") | all(is.nan(covmat.unscaled))) { covmat.scaled <- dispersion * covmat.unscaled var.cf <- diag(covmat.scaled) s.err <- sqrt(var.cf) tvalue <- coef.p/s.err pvalue <- 2 * pnorm(-abs(tvalue)) coef.table <- cbind(coef.p, s.err, tvalue, pvalue) } else { warning("summary.addreg: information matrix is singular, could not calculate covariance matrix", call. = FALSE) covmat.unscaled <- matrix(NaN, p, p) covmat.scaled <- matrix(NaN, p, p) coef.table <- cbind(coef.p, NaN, NaN, NaN) } } else { warning("MLE on boundary of parameter space, cannot use asymptotic covariance matrix", call. = FALSE) covmat.unscaled <- matrix(NaN, p, p) covmat.scaled <- matrix(NaN, p, p) coef.table <- cbind(coef.p, NaN, NaN, NaN) if(substr(object$family$family,1,7) == "negbin1") { phi <- object$scale - 1 var.phi <- NaN } } dimnames(covmat.unscaled) <- dimnames(covmat.scaled) <- list(names(coef.p), names(coef.p)) dimnames(coef.table) <- list(names(coef.p), c("Estimate","Std. Error","z value","Pr(>|z|)")) aliased <- rep(FALSE, p) names(aliased) <- names(coef.p) keep <- match(c("call", "family", "deviance", "aic", "aic.c", "df.residual", "null.deviance", "df.null", "iter", "na.action", "method"), names(object), 0L) ans <- c(object[keep], list(deviance.resid = residuals(object,type="deviance"), coefficients = coef.table, aliased = FALSE, dispersion = dispersion, df = c(p, df.r, p), cov.unscaled = covmat.unscaled, cov.scaled = covmat.scaled)) if(correlation && !any(is.nan(covmat.unscaled))) { dd <- sqrt(diag(covmat.unscaled)) ans$correlation <- covmat.unscaled/outer(dd, dd) } if(substr(object$family$family,1,7) == "negbin1") { ans$phi <- phi ans$var.phi <- var.phi } if(inherits(object,"addreg.smooth")) ans$knots <- object$knots class(ans) <- c("summary.addreg", "summary.glm") ans }
Gneglog=function(x,y,alpha) exp(-1/x-1/y+(x^(alpha)+y^(alpha))^(-1/alpha))
NMixMCMC <- function(y0, y1, censor, x_w, scale, prior, init, init2, RJMCMC, nMCMC = c(burn = 10, keep = 10, thin = 1, info = 10), PED, keep.chains = TRUE, onlyInit = FALSE, dens.zero = 1e-300, parallel = FALSE, cltype) { thispackage <- "mixAK" EMin <- -5 dd <- NMixMCMCdata(y0 = y0, y1 = y1, censor = censor) rm(list=c("y0", "y1", "censor")) if (missing(x_w)){ dd$x_w <- rep(0, dd$n) dd$fx_w <- factor(dd$x_w) dd$nx_w <- 1 dd$lx_w <- levels(dd$fx_w) }else{ if (length(x_w) != dd$n) stop("argument x_w should be a vector of length ", dd$n, " (it has a length ", length(x_w),").") if (any(is.na(x_w))) stop("NA's in a vector x_w are not allowed.") if (is.factor(x_w)) dd$fx_w <- x_w else dd$fx_w <- factor(x_w) dd$x_w <- as.numeric(dd$fx_w) - 1 dd$lx_w <- levels(dd$fx_w) dd$nx_w <- length(dd$lx_w) rm(list = "x_w") } tmpinity <- dd$y0 if (dd$are.Interval) tmpinity[dd$censor == 3] <- (dd$y0[dd$censor == 3] + dd$y1[dd$censor == 3])/2 if (missing(prior)) stop("prior must be given") if (!is.list(prior)) stop("prior must be a list") if (!length(prior)) stop("prior has a zero length") if (missing(init)) init <- list() if (!is.list(init)) stop("init must be a list") inprior <- names(prior) ipriorK <- match("priorK", inprior, nomatch=NA) ipriormuQ <- match("priormuQ", inprior, nomatch=NA) iKmax <- match("Kmax", inprior, nomatch=NA) ilambda <- match("lambda", inprior, nomatch=NA) idelta <- match("delta", inprior, nomatch=NA) ixi <- match("xi", inprior, nomatch=NA) ice <- match("ce", inprior, nomatch=NA) iD <- match("D", inprior, nomatch=NA) izeta <- match("zeta", inprior, nomatch=NA) ig <- match("g", inprior, nomatch=NA) ih <- match("h", inprior, nomatch=NA) ininit <- names(init) iy <- match("y", ininit, nomatch=NA) iK <- match("K", ininit, nomatch=NA) iw <- match("w", ininit, nomatch=NA) imu <- match("mu", ininit, nomatch=NA) iSigma <- match("Sigma", ininit, nomatch=NA) iLi <- match("Li", ininit, nomatch=NA) igammaInv <- match("gammaInv", ininit, nomatch=NA) ir <- match("r", ininit, nomatch=NA) if (is.na(ipriorK)) prior$priorK <- "fixed" if (length(prior$priorK) != 1) stop("prior$priorK must be of length 1") CpriorK <- pmatch(prior$priorK, table=c("fixed", "uniform", "tpoisson"), nomatch=0) - 1 if (CpriorK == -1) stop("prior$priorK must be one of fixed/uniform/tpoisson") if (prior$priorK != "fixed" & dd$nx_w > 1) stop("covariates on mixture weights not allowed if K is not fixed.") if (missing(PED)){ if (prior$priorK == "fixed") PED <- TRUE else PED <- FALSE } if (is.na(ipriormuQ)) prior$priormuQ <- "independentC" if (length(prior$priormuQ) != 1) stop("prior$priormuQ must be of length 1") CpriormuQ <- pmatch(prior$priormuQ, table=c("naturalC", "independentC"), nomatch=0) - 1 if (CpriormuQ == -1) stop("prior$priormuQ must be one of naturalC/independentC") if (is.na(iKmax)) stop("prior$Kmax must be given") if (length(prior$Kmax) != 1) stop("prior$Kmax must be of length 1") if (is.na(prior$Kmax)) stop("NA in prior$Kmax") if (prior$Kmax <= 0) stop("prior$Kmax must be positive") CKmax <- as.numeric(prior$Kmax) if (CpriorK == 2){ if (is.na(ilambda)) stop("prior$lambda must be given when prior$priorK = tpoisson") if (length(prior$lambda) != 1) stop("prior$lambda must be of length 1") if (is.na(prior$lambda)) stop("NA in prior$lambda") if (prior$lambda <= 0) stop("prior$lambda must be positive") }else{ prior$lambda <- 0 } Clambda <- as.numeric(prior$lambda) names(Clambda) <- "lambda" if (is.na(idelta)) prior$delta <- 1 if (length(prior$delta) != 1) stop("prior$delta must be of length 1") if (is.na(prior$delta)) stop("NA in prior$delta") if (prior$delta <= 0) stop("prior$delta must be positive") Cdelta <- as.numeric(prior$delta) names(Cdelta) <- "delta" if (is.na(iy)){ init$y <- NMixMCMCinity(y0=dd$y0, y1=dd$y1, censor=dd$censor, sd.init=sd(tmpinity), are.Censored=dd$are.Censored, are.Right=dd$are.Right, are.Exact=dd$are.Exact, are.Left=dd$are.Left, are.Interval=dd$are.Interval, p=dd$p, n=dd$n, random=FALSE) }else{ init$y <- NMixMCMCinity(y0=dd$y0, y1=dd$y1, censor=dd$censor, sd.init=sd(tmpinity), are.Censored=dd$are.Censored, are.Right=dd$are.Right, are.Exact=dd$are.Exact, are.Left=dd$are.Left, are.Interval=dd$are.Interval, p=dd$p, n=dd$n, inity=init$y) } if (missing(scale)){ SHIFT <- apply(init$y, 2, mean) SCALE <- apply(init$y, 2, sd) scale <- list(shift=SHIFT, scale=SCALE) rm(list=c("SHIFT", "SCALE")) } if (!is.list(scale)) stop("scale must be a list") if (length(scale) != 2) stop("scale must have 2 components") inscale <- names(scale) iscale.shift <- match("shift", inscale, nomatch=NA) iscale.scale <- match("scale", inscale, nomatch=NA) if (is.na(iscale.shift)) stop("scale$shift is missing") if (length(scale$shift) == 1) scale$shift <- rep(scale$shift, dd$p) if (length(scale$shift) != dd$p) stop(paste("scale$shift must be a vector of length ", dd$p, sep="")) if (is.na(iscale.scale)) stop("scale$scale is missing") if (length(scale$scale) == 1) scale$scale <- rep(scale$scale, dd$p) if (length(scale$scale) != dd$p) stop(paste("scale$scale must be a vector of length ", dd$p, sep="")) if (any(scale$scale <= 0)) stop("all elements of scale$scale must be positive") z0 <- (dd$y0 - matrix(rep(scale$shift, dd$n), ncol=dd$p, byrow=TRUE))/matrix(rep(scale$scale, dd$n), ncol=dd$p, byrow=TRUE) z1 <- (dd$y1 - matrix(rep(scale$shift, dd$n), ncol=dd$p, byrow=TRUE))/matrix(rep(scale$scale, dd$n), ncol=dd$p, byrow=TRUE) tmpinitz <- (tmpinity - matrix(rep(scale$shift, dd$n), ncol=dd$p, byrow=TRUE))/matrix(rep(scale$scale, dd$n), ncol=dd$p, byrow=TRUE) if (dd$p == 1){ initz <- (init$y - scale$shift)/scale$scale zBar <- mean(initz) zMin <- min(initz) zMax <- max(initz) }else{ initz <- (init$y - matrix(rep(scale$shift, dd$n), ncol=dd$p, byrow=TRUE))/matrix(rep(scale$scale, dd$n), ncol=dd$p, byrow=TRUE) zBar <- apply(initz, 2, mean) zMin <- apply(initz, 2, min) zMax <- apply(initz, 2, max) } zBar[abs(zBar) < 1e-14] <- 0 zVar <- var(initz) zVar[abs(zVar - 1) < 1e-14] <- 1 zR <- zMax - zMin zMid <- 0.5*(zMin + zMax) if (is.na(ixi)) prior$xi <- matrix(rep(zMid, CKmax), nrow=CKmax, ncol=dd$p, byrow=TRUE) if (any(is.na(prior$xi))) stop("NA in prior$xi") if (dd$p == 1){ if (length(prior$xi) == 1) prior$xi <- rep(prior$xi, CKmax) if (length(prior$xi) != CKmax) stop(paste("prior$xi must be of length ", CKmax, sep="")) prior$xi <- as.numeric(prior$xi) names(prior$xi) <- paste("xi", 1:CKmax, sep="") Cxi <- prior$xi }else{ if (length(prior$xi) == dd$p) prior$xi <- matrix(rep(as.numeric(prior$xi), each=CKmax), nrow=CKmax, ncol=dd$p) if (CKmax == 1) prior$xi <- matrix(as.numeric(prior$xi), nrow=1) if (!is.matrix(prior$xi)) stop("prior$xi must be a matrix") if (ncol(prior$xi) != dd$p) stop(paste("prior$xi must have ", dd$p, " columns", sep="")) if (nrow(prior$xi) != CKmax) stop(paste("prior$xi must have ", CKmax, " rows", sep="")) rownames(prior$xi) <- paste("j", 1:CKmax, sep="") colnames(prior$xi) <- paste("m", 1:dd$p, sep="") Cxi <- as.numeric(t(prior$xi)) names(Cxi) <- paste("xi", rep(1:CKmax, each=dd$p), ".", rep(1:dd$p, CKmax), sep="") } if (any(is.na(Cxi))) stop("NA in prior$xi") if (CpriormuQ == 0){ if (is.na(ice)) prior$ce <- rep(1, CKmax) if (length(prior$ce) == 1) prior$ce <- rep(prior$ce, CKmax) if (length(prior$ce) != CKmax) stop(paste("prior$ce must be of length ", CKmax, sep="")) if (any(is.na(prior$ce))) stop("NA in prior$ce") if (any(prior$ce <= 0)) stop("prior$ce must be positive") prior$ce <- as.numeric(prior$ce) }else{ prior$ce <- rep(0, CKmax) } Cce <- prior$ce names(Cce) <- names(prior$ce) <- paste("c", 1:CKmax, sep="") if (CpriormuQ == 1){ if (is.na(iD)){ if (dd$p == 1) prior$D <- rep(zR^2, CKmax) else prior$D <- t(matrix(rep(diag(zR^2), CKmax), nrow=dd$p, ncol=CKmax*dd$p)) } if (any(is.na(prior$D))) stop("NA in prior$D") if (dd$p == 1){ if (length(prior$D) == 1) prior$D <- rep(prior$D, CKmax) if (length(prior$D) != CKmax) stop(paste("prior$D must be of length ", CKmax, sep="")) prior$D <- as.numeric(prior$D) names(prior$D) <- paste("D", 1:CKmax, sep="") if (any(prior$D <= 0)) stop("prior$D must be positive") CDinv <- 1/prior$D names(CDinv) <- paste("Dinv", 1:CKmax, sep="") }else{ if (!is.matrix(prior$D)) stop("prior$D must be a matrix") if (ncol(prior$D) != dd$p) stop(paste("prior$D must have ", dd$p, " columns", sep="")) if (nrow(prior$D) == dd$p){ if (any(prior$D[lower.tri(prior$D)] != t(prior$D)[lower.tri(prior$D)])) stop("prior$D must be a symmetric matrix") err <- try(Dinv <- chol(prior$D), silent=TRUE) if (class(err) == "try-error") stop("Cholesky decomposition of prior$D failed") Dinv <- chol2inv(Dinv) CDinv <- rep(Dinv[lower.tri(Dinv, diag=TRUE)], CKmax) prior$D <- matrix(rep(as.numeric(t(prior$D)), CKmax), nrow=dd$p*CKmax, ncol=dd$p, byrow=TRUE) }else{ if (nrow(prior$D) != CKmax*dd$p) stop(paste("prior$D must have ", CKmax, " times ", dd$p, " rows", sep="")) CDinv <- numeric(0) for (j in 1:CKmax){ Dinv <- prior$D[((j-1)*dd$p+1):(j*dd$p),] if (any(Dinv[lower.tri(Dinv)] != t(Dinv)[lower.tri(Dinv)])) stop(paste(j, "-th block of prior$D is not symmetric", sep="")) err <- try(Dinv <- chol(Dinv), silent=TRUE) if (class(err) == "try-error") stop(paste("Cholesky decomposition of the ", j, "-th block of prior$D failed", sep="")) Dinv <- chol2inv(Dinv) CDinv <- c(CDinv, Dinv[lower.tri(Dinv, diag=TRUE)]) } } colnames(prior$D) <- paste("m", 1:dd$p, sep="") rownames(prior$D) <- paste("j", rep(1:CKmax, each=dd$p), ".", rep(1:dd$p, CKmax), sep="") names(CDinv) <- paste("Dinv", rep(1:CKmax, each=dd$LTp), rep(dd$naamLTp, CKmax), sep="") } }else{ if (dd$p == 1){ prior$D <- rep(1, CKmax) names(prior$D) <- paste("D", 1:CKmax, sep="") CDinv <- 1/prior$D names(CDinv) <- paste("Dinv", 1:CKmax, sep="") }else{ prior$D <- matrix(rep(as.numeric(diag(dd$p)), CKmax), nrow=dd$p*CKmax, ncol=dd$p, byrow=TRUE) colnames(prior$D) <- paste("m", 1:dd$p, sep="") rownames(prior$D) <- paste("j", rep(1:CKmax, each=dd$p), ".", rep(1:dd$p, CKmax), sep="") Dinv <- diag(dd$p) CDinv <- rep(Dinv[lower.tri(Dinv, diag=TRUE)], CKmax) names(CDinv) <- paste("Dinv", rep(1:CKmax, each=dd$LTp), rep(dd$naamLTp, CKmax), sep="") } } if (is.na(izeta)) prior$zeta <- dd$p + 1 if (length(prior$zeta) != 1) stop("prior$zeta must be of length 1") if (is.na(prior$zeta)) stop("NA in prior$zeta") if (prior$zeta <= dd$p - 1) stop(paste("prior$zeta must be higher than ", dd$p - 1, sep="")) Czeta <- as.numeric(prior$zeta) names(Czeta) <- "zeta" if (is.na(ig)) prior$g <- rep(0.2, dd$p) if (length(prior$g) == 1) prior$g <- rep(prior$g, dd$p) if (length(prior$g) != dd$p) stop(paste("prior$g must be of length ", dd$p, sep="")) if (any(is.na(prior$g))) stop("NA in prior$g") if (any(prior$g <= 0)) stop("prior$g must be positive") Cg <- as.numeric(prior$g) names(Cg) <- paste("g", 1:dd$p, sep="") if (is.na(ih)) prior$h <- 10/(zR^2) if (length(prior$h) == 1) prior$h <- rep(prior$h, dd$p) if (length(prior$h) != dd$p) stop(paste("prior$h must be of length ", dd$p, sep="")) if (any(is.na(prior$h))) stop("NA in prior$h") if (any(prior$h <= 0)) stop("prior$h must be positive") Ch <- as.numeric(prior$h) names(Ch) <- paste("h", 1:dd$p, sep="") Cinteger <- c(CpriorK, CpriormuQ, CKmax) names(Cinteger) <- c("priorK", "priormuQ", "Kmax") Cdouble <- c(Clambda, Cdelta, Cxi, Cce, CDinv, Czeta, Cg, Ch) if (is.na(iK)){ if (prior$priorK == "fixed") init$K <- CKmax else init$K <- 1 } if (prior$priorK == "fixed") init$K <- CKmax if (length(init$K) != 1) stop("init$K must be of length 1") if (is.na(init$K)) stop("NA in init$K") if (init$K <= 0 | init$K > CKmax) stop("init$K out of the range") if (is.na(iw)){ init$w <- rep(rep(1, init$K)/init$K, dd$nx_w) } init$w <- as.numeric(init$w) if (length(init$w) == CKmax * dd$nx_w & CKmax > init$K) init$w <- init$w[1:(init$K * dd$nx_w)] if (dd$nx_w > 1) names(init$w) <- paste("w", rep(1:init$K, dd$nx_w), ".", rep(1:dd$nx_w, each = init$K), sep="") else names(init$w) <- paste("w", 1:init$K, sep="") if (any(is.na(init$w))) stop("NA in init$w") if (length(init$w) != init$K * dd$nx_w) stop(paste("init$w must be of length ", init$K * dd$nx_w, sep="")) if (any(init$w < 0)) stop("init$w may not be negative") for (ff in 1:dd$nx_w) init$w[((ff - 1) * init$K + 1):(ff * init$K)] <- init$w[((ff - 1) * init$K + 1):(ff * init$K)] / sum(init$w[((ff - 1) * init$K + 1):(ff * init$K)]) if (is.na(imu)){ if (dd$p == 1){ dist <- zR/(init$K + 1) init$mu <- seq(zMin+dist, zMax-dist, length=init$K) }else{ dist <- zR/(init$K + 1) init$mu <- matrix(NA, nrow=init$K, ncol=dd$p) for (j in 1:dd$p) init$mu[,j] <- seq(zMin[j]+dist[j], zMax[j]-dist[j], length=init$K) } } if (any(is.na(init$mu))) stop("NA in init$mu") if (dd$p == 1){ init$mu <- as.numeric(init$mu) if (length(init$mu) == CKmax & CKmax > init$K) init$mu <- init$mu[1:init$K] if (length(init$mu) != init$K) stop(paste("init$mu must be of length ", init$K, sep="")) names(init$mu) <- paste("mu", 1:init$K, sep="") }else{ if (!is.matrix(init$mu)) stop("init$mu must be a matrix") if (ncol(init$mu) != dd$p) stop(paste("init$mu must have ", dd$p, " columns", sep="")) if (nrow(init$mu) != init$K) stop(paste("init$mu must have ", init$K, " rows", sep="")) rownames(init$mu) <- paste("j", 1:init$K, sep="") colnames(init$mu) <- paste("m", 1:dd$p, sep="") } if (is.na(iSigma)){ if (is.na(iLi)){ if (dd$p == 1){ init$Sigma <- rep(zVar, init$K) names(init$Sigma) <- paste("Sigma", 1:init$K, sep="") init$Li <- sqrt(1 / init$Sigma) names(init$Li) <- paste("Li", 1:init$K, sep="") }else{ init$Sigma <- matrix(rep(t(zVar), init$K), ncol=dd$p, byrow=TRUE) Sigmainv <- chol(zVar) Sigmainv <- chol2inv(Sigmainv) Litmp <- t(chol(Sigmainv)) init$Li <- rep(Litmp[lower.tri(Litmp, diag=TRUE)], init$K) rownames(init$Sigma) <- paste("j", rep(1:init$K, each=dd$p), ".", rep(1:dd$p, init$K), sep="") colnames(init$Sigma) <- paste("m", 1:dd$p, sep="") names(init$Li) <- paste("Li", rep(1:init$K, each=dd$LTp), rep(dd$naamLTp, init$K), sep="") } }else{ if (any(is.na(init$Li))) stop("NA in init$Li") if (dd$p == 1){ if (length(init$Li) == 1) init$Li <- rep(init$Li, init$K) if (length(init$Li) == CKmax & CKmax > init$K) init$Li <- init$Li[1:init$K] if (length(init$Sigma) != init$K) stop(paste("init$Sigma must be of length ", init$K, sep="")) init$Li <- as.numeric(init$Li) names(init$Li) <- paste("Li", 1:init$K, sep="") if (any(init$Li <= 0)) stop("init$Li must be positive") init$Sigma <- (1 / init$Li)^2 names(init$Sigma) <- paste("Sigma", 1:init$K, sep="") }else{ if (length(init$Li) == dd$LTp){ tmpSigma <- matrix(0, nrow=dd$p, ncol=dd$p) tmpSigma[lower.tri(tmpSigma, diag=TRUE)] <- init$Li tmpSigma <- tmpSigma %*% t(tmpSigma) err <- try(tmpSigma <- chol(tmpSigma), silent=TRUE) if (class(err) == "try-error") stop("init$Li does not lead to a positive definite matrix") tmpSigma <- chol2inv(tmpSigma) init$Sigma <- matrix(rep(t(tmpSigma), init$K), ncol=dd$p, byrow=TRUE) init$Li <- rep(init$Li, init$K) }else{ if (length(init$Li) == CKmax*dd$LTp & CKmax > init$K) init$Li <- init$Li[1:(init$K*dd$LTp)] if (length(init$Li) != init$K*dd$LTp) stop(paste("init$Li must be of length ", init$K*dd$LTp, sep="")) init$Sigma <- matrix(NA, ncol=dd$p, nrow=dd$p*init$K) for (j in 1:init$K){ tmpSigma <- matrix(0, nrow=dd$p, ncol=dd$p) tmpSigma[lower.tri(tmpSigma, diag=TRUE)] <- init$Li[((j-1)*dd$LTp+1):(j*dd$LTp)] tmpSigma <- tmpSigma %*% t(tmpSigma) err <- try(tmpSigma <- chol(tmpSigma), silent=TRUE) if (class(err) == "try-error") stop(paste("the ", j,"-th block of init$Li does not lead to a positive definite matrix", sep="")) tmpSigma <- chol2inv(tmpSigma) init$Sigma[((j-1)*dd$p):(j*dd$p),] <- tmpSigma } } rownames(init$Sigma) <- paste("j", rep(1:init$K, each=dd$p), ".", rep(1:dd$p, init$K), sep="") colnames(init$Sigma) <- paste("m", 1:dd$p, sep="") names(init$Li) <- paste("Li", rep(1:init$K, each=dd$LTp), rep(dd$naamLTp, init$K), sep="") } } }else{ if (any(is.na(init$Sigma))) stop("NA in init$Sigma") if (dd$p == 1){ if (length(init$Sigma) == 1) init$Sigma <- rep(init$Sigma, init$K) if (length(init$Sigma) == CKmax & CKmax > init$K) init$Sigma <- init$Sigma[1:init$K] if (length(init$Sigma) != init$K) stop(paste("init$Sigma must be of length ", init$K, sep="")) init$Sigma <- as.numeric(init$Sigma) names(init$Sigma) <- paste("Sigma", 1:init$K, sep="") if (any(init$Sigma <= 0)) stop("init$Sigma must be positive") init$Li <- sqrt(1 / init$Sigma) names(init$Li) <- paste("Li", 1:init$K, sep="") }else{ if (!is.matrix(init$Sigma)) stop("init$Sigma must be a matrix") if (ncol(init$Sigma) != dd$p) stop(paste("init$Sigma must have ", dd$p, " columns", sep="")) if (nrow(init$Sigma) == dd$p){ if (any(init$Sigma[lower.tri(init$Sigma)] != t(init$Sigma)[lower.tri(init$Sigma)])) stop("init$Sigma must be a symmetric matrix") err <- try(Sigmainv <- chol(init$Sigma), silent=TRUE) if (class(err) == "try-error") stop("Cholesky decomposition of init$Sigma failed") Sigmainv <- chol2inv(Sigmainv) Litmp <- t(chol(Sigmainv)) init$Li <- rep(Litmp[lower.tri(Litmp, diag=TRUE)], init$K) }else{ if (nrow(init$Sigma) == CKmax*dd$p & CKmax > init$K) init$Sigma <- init$Sigma[1:(init$K*dd$p),] if (nrow(init$Sigma) != init$K*dd$p) stop(paste("init$Sigma must have ", init$K, " times ", dd$p, " rows", sep="")) init$Li <- numeric(0) for (j in 1:init$K){ Sigmainv <- init$Sigma[((j-1)*dd$p+1):(j*dd$p),] if (any(Sigmainv[lower.tri(Sigmainv)] != t(Sigmainv)[lower.tri(Sigmainv)])) stop(paste(j, "-th block of init$Sigma is not symmetric", sep="")) err <- try(Sigmainv <- chol(Sigmainv), silent=TRUE) if (class(err) == "try-error") stop(paste("Cholesky decomposition of the ", j, "-th block of init$Sigma failed", sep="")) Sigmainv <- chol2inv(Sigmainv) Litmp <- t(chol(Sigmainv)) init$Li <- c(init$Li, Litmp[lower.tri(Litmp, diag=TRUE)]) } } rownames(init$Sigma) <- paste("j", rep(1:init$K, each=dd$p), ".", rep(1:dd$p, init$K), sep="") colnames(init$Sigma) <- paste("m", 1:dd$p, sep="") names(init$Li) <- paste("Li", rep(1:init$K, each=dd$LTp), rep(dd$naamLTp, init$K), sep="") } } if (dd$p == 1){ init$Q <- 1 / init$Sigma names(init$Q) <- paste("Q", 1:init$K, sep="") }else{ init$Q <- numeric(0) for (j in 1:init$K){ tmpLi <- diag(dd$p) tmpLi[lower.tri(tmpLi, diag=TRUE)] <- init$Li[((j-1)*dd$LTp + 1):(j*dd$LTp)] tmpQ <- tmpLi %*% t(tmpLi) init$Q <- c(init$Q, tmpQ[lower.tri(tmpQ, diag=TRUE)]) } names(init$Q) <- paste("Q", rep(1:init$K, each=dd$LTp), rep(dd$naamLTp, init$K), sep="") } if (is.na(igammaInv)){ if (dd$p == 1) init$gammaInv <- Czeta * zVar else init$gammaInv <- Czeta * diag(zVar) } init$gammaInv <- as.numeric(init$gammaInv) if (length(init$gammaInv) == 1) init$gammaInv <- rep(init$gammaInv, dd$p) if (length(init$gammaInv) != dd$p) stop(paste("init$gammaInv must be of length ", dd$p, sep="")) if (any(is.na(init$gammaInv))) stop("NA in init$gammaInv") names(init$gammaInv) <- paste("gammaInv", 1:dd$p, sep="") if (is.na(ir)) init$r <- NMixMCMCinitr(z=initz, K=init$K, w=init$w[1:init$K], mu=init$mu, Sigma=init$Sigma, p=dd$p, n=dd$n) else init$r <- NMixMCMCinitr(z=initz, K=init$K, w=init$w[1:init$K], mu=init$mu, Sigma=init$Sigma, p=dd$p, n=dd$n, initr=init$r) rm(list="initz") if (PED){ if (missing(init2)) init2 <- list() if (!is.list(init2)) stop("init2 must be a list") ininit2 <- names(init2) iy2 <- match("y", ininit2, nomatch=NA) iK2 <- match("K", ininit2, nomatch=NA) iw2 <- match("w", ininit2, nomatch=NA) imu2 <- match("mu", ininit2, nomatch=NA) iSigma2 <- match("Sigma", ininit2, nomatch=NA) iLi2 <- match("Li", ininit2, nomatch=NA) igammaInv2 <- match("gammaInv", ininit2, nomatch=NA) ir2 <- match("r", ininit2, nomatch=NA) if (is.na(iy2)){ init2$y <- NMixMCMCinity(y0=dd$y0, y1=dd$y1, censor=dd$censor, sd.init=sd(tmpinity), are.Censored=dd$are.Censored, are.Right=dd$are.Right, are.Exact=dd$are.Exact, are.Left=dd$are.Left, are.Interval=dd$are.Interval, p=dd$p, n=dd$n, random=TRUE) }else{ init2$y <- NMixMCMCinity(y0=dd$y0, y1=dd$y1, censor=dd$censor, sd.init=sd(tmpinity), are.Censored=dd$are.Censored, are.Right=dd$are.Right, are.Exact=dd$are.Exact, are.Left=dd$are.Left, are.Interval=dd$are.Interval, p=dd$p, n=dd$n, inity=init2$y) } initz2 <- (init2$y - matrix(rep(scale$shift, dd$n), ncol=dd$p, byrow=TRUE))/matrix(rep(scale$scale, dd$n), ncol=dd$p, byrow=TRUE) if (dd$p == 1){ initz2 <- (init2$y - scale$shift)/scale$scale zBar2 <- mean(initz2) zMin2 <- min(initz2) zMax2 <- max(initz2) }else{ initz2 <- (init2$y - matrix(rep(scale$shift, dd$n), ncol=dd$p, byrow=TRUE))/matrix(rep(scale$scale, dd$n), ncol=dd$p, byrow=TRUE) zBar2 <- apply(initz2, 2, mean) zMin2 <- apply(initz2, 2, min) zMax2 <- apply(initz2, 2, max) } zBar2[abs(zBar2) < 1e-14] <- 0 zVar2 <- var(initz2) zVar2[abs(zVar2 - 1) < 1e-14] <- 1 zR2 <- zMax2 - zMin2 zMid2 <- 0.5*(zMin2 + zMax2) if (is.na(iK2)){ if (prior$priorK == "fixed") init2$K <- CKmax else init2$K <- min(c(2, CKmax)) } if (length(init2$K) != 1) stop("init2$K must be of length 1") if (is.na(init2$K)) stop("NA in init2$K") if (init2$K <= 0 | init2$K > CKmax) stop("init2$K out of the range") if (is.na(iw2)){ init2$w <- rDirichlet(1, rep(Cdelta, init2$K)) if (dd$nx_w > 1) for (ff in 2:dd$nx_w) init2$w <- c(init2$w, rDirichlet(1, rep(Cdelta, init2$K))) } init2$w <- as.numeric(init2$w) if (length(init2$w) == CKmax * dd$nx_w & CKmax > init2$K) init2$w <- init2$w[1:(init2$K * dd$nx_w)] if (dd$nx_w > 1) names(init2$w) <- paste("w", rep(1:init2$K, dd$nx_w), ".", rep(1:dd$nx_w, each = init2$K), sep="") else names(init2$w) <- paste("w", 1:init2$K, sep="") if (any(is.na(init2$w))) stop("NA in init2$w") if (length(init2$w) != init2$K * dd$nx_w) stop(paste("init2$w must be of length ", init2$K * dd$nx_w, sep="")) if (any(init2$w < 0)) stop("init2$w may not be negative") for (ff in 1:dd$nx_w) init2$w[((ff - 1) * init2$K + 1):(ff * init2$K)] <- init2$w[((ff - 1) * init2$K + 1):(ff * init2$K)] / sum(init2$w[((ff - 1) * init2$K + 1):(ff * init2$K)]) if (is.na(imu2)){ tmpsd <- apply(tmpinitz, 2, sd)/init2$K if (dd$p == 1){ dist <- (zMax2 - zMin2)/(init2$K + 1) tmpxi <- seq(zMin2+dist, zMax2-dist, length=init2$K) init2$mu <- rnorm(init2$K, mean=tmpxi, sd=tmpsd) init2$mu <- init2$mu[order(init2$mu)] }else{ dist <- (zMax2 - zMin2)/(init2$K + 1) init2$mu <- matrix(NA, nrow=init2$K, ncol=dd$p) for (j in 1:dd$p){ tmpxi <- seq(zMin2[j]+dist[j], zMax2[j]-dist[j], length=init2$K) init2$mu[,j] <- rnorm(init2$K, mean=tmpxi, sd=tmpsd[j]) init2$mu[,j] <- init2$mu[,j][order(init2$mu[,j])] } } } if (any(is.na(init2$mu))) stop("NA in init2$mu") if (dd$p == 1){ init2$mu <- as.numeric(init2$mu) if (length(init2$mu) == CKmax & CKmax > init2$K) init2$mu <- init2$mu[1:init2$K] if (length(init2$mu) != init2$K) stop(paste("init2$mu must be of length ", init2$K, sep="")) names(init2$mu) <- paste("mu", 1:init2$K, sep="") }else{ if (!is.matrix(init2$mu)) stop("init2$mu must be a matrix") if (ncol(init2$mu) != dd$p) stop(paste("init2$mu must have ", dd$p, " columns", sep="")) if (nrow(init2$mu) != init2$K) stop(paste("init2$mu must have ", init2$K, " rows", sep="")) rownames(init2$mu) <- paste("j", 1:init2$K, sep="") colnames(init2$mu) <- paste("m", 1:dd$p, sep="") } if (is.na(iSigma2)){ if (is.na(iLi2)){ ctmp <- runif(init2$K, 0.1, 1.1) if (dd$p == 1){ init2$Sigma <- ctmp*zVar2 names(init2$Sigma) <- paste("Sigma", 1:init2$K, sep="") init2$Li <- sqrt(1 / init2$Sigma) names(init2$Li) <- paste("Li", 1:init2$K, sep="") }else{ init2$Sigma <- ctmp[1]*zVar2 Sigmainv <- chol(init2$Sigma) Sigmainv <- chol2inv(Sigmainv) Litmp <- t(chol(Sigmainv)) init2$Li <- Litmp[lower.tri(Litmp, diag=TRUE)] if (init2$K > 1){ for (k in 2:init2$K){ Sigmatmp <- ctmp[k]*zVar2 init2$Sigma <- rbind(init2$Sigma, Sigmatmp) Sigmainv <- chol(Sigmatmp) Sigmainv <- chol2inv(Sigmainv) Litmp <- t(chol(Sigmainv)) init2$Li <- c(init2$Li, Litmp[lower.tri(Litmp, diag=TRUE)]) } } rownames(init2$Sigma) <- paste("j", rep(1:init2$K, each=dd$p), ".", rep(1:dd$p, init2$K), sep="") colnames(init2$Sigma) <- paste("m", 1:dd$p, sep="") names(init2$Li) <- paste("Li", rep(1:init2$K, each=dd$LTp), rep(dd$naamLTp, init2$K), sep="") } }else{ if (any(is.na(init2$Li))) stop("NA in init2$Li") if (dd$p == 1){ if (length(init2$Li) == 1) init2$Li <- rep(init2$Li, init2$K) if (length(init2$Li) == CKmax & CKmax > init2$K) init2$Li <- init2$Li[1:init2$K] if (length(init2$Sigma) != init2$K) stop(paste("init2$Sigma must be of length ", init2$K, sep="")) init2$Li <- as.numeric(init2$Li) names(init2$Li) <- paste("Li", 1:init2$K, sep="") if (any(init2$Li <= 0)) stop("init2$Li must be positive") init2$Sigma <- (1 / init2$Li)^2 names(init2$Sigma) <- paste("Sigma", 1:init2$K, sep="") }else{ if (length(init2$Li) == dd$LTp){ tmpSigma <- matrix(0, nrow=dd$p, ncol=dd$p) tmpSigma[lower.tri(tmpSigma, diag=TRUE)] <- init2$Li tmpSigma <- tmpSigma %*% t(tmpSigma) err <- try(tmpSigma <- chol(tmpSigma), silent=TRUE) if (class(err) == "try-error") stop("init2$Li does not lead to a positive definite matrix") tmpSigma <- chol2inv(tmpSigma) init2$Sigma <- matrix(rep(t(tmpSigma), init2$K), ncol=dd$p, byrow=TRUE) init2$Li <- rep(init2$Li, init2$K) }else{ if (length(init2$Li) == CKmax*dd$LTp & CKmax > init2$K) init2$Li <- init2$Li[1:(init2$K*dd$LTp)] if (length(init2$Li) != init2$K*dd$LTp) stop(paste("init2$Li must be of length ", init2$K*dd$LTp, sep="")) init2$Sigma <- matrix(NA, ncol=dd$p, nrow=dd$p*init2$K) for (j in 1:init2$K){ tmpSigma <- matrix(0, nrow=dd$p, ncol=dd$p) tmpSigma[lower.tri(tmpSigma, diag=TRUE)] <- init2$Li[((j-1)*dd$LTp+1):(j*dd$LTp)] tmpSigma <- tmpSigma %*% t(tmpSigma) err <- try(tmpSigma <- chol(tmpSigma), silent=TRUE) if (class(err) == "try-error") stop(paste("the ", j,"-th block of init2$Li does not lead to a positive definite matrix", sep="")) tmpSigma <- chol2inv(tmpSigma) init2$Sigma[((j-1)*dd$p):(j*dd$p),] <- tmpSigma } } rownames(init2$Sigma) <- paste("j", rep(1:init2$K, each=dd$p), ".", rep(1:dd$p, init2$K), sep="") colnames(init2$Sigma) <- paste("m", 1:dd$p, sep="") names(init2$Li) <- paste("Li", rep(1:init2$K, each=dd$LTp), rep(dd$naamLTp, init2$K), sep="") } } }else{ if (any(is.na(init2$Sigma))) stop("NA in init2$Sigma") if (dd$p == 1){ if (length(init2$Sigma) == 1) init2$Sigma <- rep(init2$Sigma, init2$K) if (length(init2$Sigma) == CKmax & CKmax > init2$K) init2$Sigma <- init2$Sigma[1:init2$K] if (length(init2$Sigma) != init2$K) stop(paste("init2$Sigma must be of length ", init2$K, sep="")) init2$Sigma <- as.numeric(init2$Sigma) names(init2$Sigma) <- paste("Sigma", 1:init2$K, sep="") if (any(init2$Sigma <= 0)) stop("init2$Sigma must be positive") init2$Li <- sqrt(1 / init2$Sigma) names(init2$Li) <- paste("Li", 1:init2$K, sep="") }else{ if (!is.matrix(init2$Sigma)) stop("init2$Sigma must be a matrix") if (ncol(init2$Sigma) != dd$p) stop(paste("init2$Sigma must have ", dd$p, " columns", sep="")) if (nrow(init2$Sigma) == dd$p){ if (any(init2$Sigma[lower.tri(init2$Sigma)] != t(init2$Sigma)[lower.tri(init2$Sigma)])) stop("init2$Sigma must be a symmetric matrix") err <- try(Sigmainv <- chol(init2$Sigma), silent=TRUE) if (class(err) == "try-error") stop("Cholesky decomposition of init2$Sigma failed") Sigmainv <- chol2inv(Sigmainv) Litmp <- t(chol(Sigmainv)) init2$Li <- rep(Litmp[lower.tri(Litmp, diag=TRUE)], init2$K) }else{ if (nrow(init2$Sigma) == CKmax*dd$p & CKmax > init2$K) init2$Sigma <- init2$Sigma[1:(init2$K*dd$p),] if (nrow(init2$Sigma) != init2$K*dd$p) stop(paste("init2$Sigma must have ", init2$K, " times ", dd$p, " rows", sep="")) init2$Li <- numeric(0) for (j in 1:init2$K){ Sigmainv <- init2$Sigma[((j-1)*dd$p+1):(j*dd$p),] if (any(Sigmainv[lower.tri(Sigmainv)] != t(Sigmainv)[lower.tri(Sigmainv)])) stop(paste(j, "-th block of init2$Sigma is not symmetric", sep="")) err <- try(Sigmainv <- chol(Sigmainv), silent=TRUE) if (class(err) == "try-error") stop(paste("Cholesky decomposition of the ", j, "-th block of init2$Sigma failed", sep="")) Sigmainv <- chol2inv(Sigmainv) Litmp <- t(chol(Sigmainv)) init2$Li <- c(init2$Li, Litmp[lower.tri(Litmp, diag=TRUE)]) } } rownames(init2$Sigma) <- paste("j", rep(1:init2$K, each=dd$p), ".", rep(1:dd$p, init2$K), sep="") colnames(init2$Sigma) <- paste("m", 1:dd$p, sep="") names(init2$Li) <- paste("Li", rep(1:init2$K, each=dd$LTp), rep(dd$naamLTp, init2$K), sep="") } } if (is.na(igammaInv2)){ if (dd$p == 1) init2$gammaInv <- Czeta * zVar2 * runif(1, 0, dd$p) else init2$gammaInv <- Czeta * diag(zVar2) * runif(dd$p, 0, dd$p) } init2$gammaInv <- as.numeric(init2$gammaInv) if (length(init2$gammaInv) == 1) init2$gammaInv <- rep(init2$gammaInv, dd$p) if (length(init2$gammaInv) != dd$p) stop(paste("init2$gammaInv must be of length ", dd$p, sep="")) if (any(is.na(init2$gammaInv))) stop("NA in init2$gammaInv") names(init2$gammaInv) <- paste("gammaInv", 1:dd$p, sep="") if (is.na(ir2)) init2$r <- NMixMCMCinitr(z=initz2, K=init2$K, w=init2$w[1:init2$K], mu=init2$mu, Sigma=init2$Sigma, p=dd$p, n=dd$n) else init2$r <- NMixMCMCinitr(z=initz2, K=init2$K, w=init2$w[1:init2$K], mu=init2$mu, Sigma=init2$Sigma, p=dd$p, n=dd$n, initr=init2$r) rm(list="initz2") }else{ init2 <- NULL } if (missing(RJMCMC)) RJMCMC <- list() if (!is.list(RJMCMC)) stop("RJMCMC must be a list") inRJMCMC <- names(RJMCMC) iPaction <- match("Paction", ininit, nomatch=NA) iPsplit <- match("Psplit", ininit, nomatch=NA) iPbirth <- match("Pbirth", ininit, nomatch=NA) ipar.u1 <- match("par.u1", ininit, nomatch=NA) ipar.u2 <- match("par.u2", ininit, nomatch=NA) ipar.u3 <- match("par.u3", ininit, nomatch=NA) if (is.na(iPaction)){ actionAll <- 1 RJMCMC$Paction <- c(1, 1, 1)/3 } else{ if (is.null(RJMCMC$Paction)){ actionAll <- 1 RJMCMC$Paction <- c(1, 1, 1)/3 }else{ actionAll <- 0 } } if (length(RJMCMC$Paction) != 3) stop("RJMCMC$Paction must be of length 3") if (any(RJMCMC$Paction < 0)) stop("RJMCMC$Paction must be all non-negative") RJMCMC$Paction <- RJMCMC$Paction / sum(RJMCMC$Paction) CPaction <- as.numeric(RJMCMC$Paction) names(CPaction) <- names(RJMCMC$Paction) <- c("P.Gibbs.K", "P.split.combine", "P.birth.death") if (is.na(iPsplit)){ if (CKmax == 1) RJMCMC$Psplit <- 0 else RJMCMC$Psplit <- c(1, rep(0.5, CKmax - 2), 0) } if (length(RJMCMC$Psplit) != CKmax) stop(paste("RJMCMC$Psplit must be of length ", CKmax, sep="")) if (any(RJMCMC$Psplit < 0)) stop("RJMCMC$Psplit must be all non-negative") if (any(RJMCMC$Psplit > 1)) stop("RJMCMC$Psplit must be all at most 1") if (RJMCMC$Psplit[CKmax] != 0) stop(paste("RJMCMC$Psplit[", CKmax, "] must be zero")) if (CKmax > 1){ if (RJMCMC$Psplit[1] != 1) stop(paste("RJMCMC$Psplit[", 1, "] must be one")) } CPsplit <- as.numeric(RJMCMC$Psplit) names(CPsplit) <- names(RJMCMC$Psplit) <- paste("Psplit.", 1:CKmax, sep="") if (is.na(iPbirth)){ if (CKmax == 1) RJMCMC$Pbirth <- 0 else RJMCMC$Pbirth <- c(1, rep(0.5, CKmax - 2), 0) } if (length(RJMCMC$Pbirth) != CKmax) stop(paste("RJMCMC$Pbirth must be of length ", CKmax, sep="")) if (any(RJMCMC$Pbirth < 0)) stop("RJMCMC$Pbirth must be all non-negative") if (any(RJMCMC$Pbirth > 1)) stop("RJMCMC$Pbirth must be all at most 1") if (RJMCMC$Pbirth[CKmax] != 0) stop(paste("RJMCMC$Pbirth[", CKmax, "] must be zero")) if (CKmax > 1){ if (RJMCMC$Pbirth[1] != 1) stop(paste("RJMCMC$Pbirth[", 1, "] must be one")) } CPbirth <- as.numeric(RJMCMC$Pbirth) names(CPbirth) <- names(RJMCMC$Pbirth) <- paste("Pbirth.", 1:CKmax, sep="") if (is.na(ipar.u1)) RJMCMC$par.u1 <- c(2, 2) if (length(RJMCMC$par.u1) != 2) stop("RJMCMC$par.u1 must be of length 2") if (any(RJMCMC$par.u1 <= 0)) stop("RJMCMC$par.u1 must be all positive") Cpar.u1 <- as.numeric(RJMCMC$par.u1) names(Cpar.u1) <- names(RJMCMC$par.u1) <- c("u1.1", "u1.2") if (dd$p == 1){ if (is.na(ipar.u2)) RJMCMC$par.u2 <- c(1, 2*dd$p) if (length(RJMCMC$par.u2) != 2) stop("RJMCMC$par.u2 must be of length 2") if (any(RJMCMC$par.u2 <= 0)) stop("RJMCMC$par.u2 must be all positive") Cpar.u2 <- as.numeric(RJMCMC$par.u2) names(Cpar.u2) <- names(RJMCMC$par.u2) <- c("u2.1", "u2.2") }else{ if (is.na(ipar.u2)) RJMCMC$par.u2 <- rbind(matrix(c(rep(-1, dd$p-1), rep(1, dd$p-1)), ncol=2), c(1, 2*dd$p)) if (!is.matrix(RJMCMC$par.u2)) stop("RJMCMC$par.u2 must be a matrix") if (nrow(RJMCMC$par.u2) != dd$p) stop(paste("RJMCMC$par.u2 must have ", dd$p, " rows", sep="")) if (ncol(RJMCMC$par.u2) != 2) stop(paste("RJMCMC$par.u2 must have ", 2, " columns", sep="")) rownames(RJMCMC$par.u2) <- paste("u2.", 1:dd$p, sep="") colnames(RJMCMC$par.u2) <- paste(c(1, 2)) if (any(RJMCMC$par.u2[dd$p,] <= 0)) stop(paste("RJMCMC$par.u2[", dd$p, ",] must be all positive", sep="")) if (any(RJMCMC$par.u2[-dd$p,1] >= RJMCMC$par.u2[-dd$p,2])) stop(paste("The first column of RJMCMC$par.u2[-", dd$p, ",] must be strictly lower than the second column", sep="")) Cpar.u2 <- as.numeric(t(RJMCMC$par.u2)) names(Cpar.u2) <- paste("u2.", rep(1:dd$p, each=2), ".", rep(1:2, dd$p), sep="") } if (dd$p == 1){ if (is.na(ipar.u3)) RJMCMC$par.u3 <- c(1, dd$p) if (length(RJMCMC$par.u3) != 2) stop("RJMCMC$par.u3 must be of length 2") if (any(RJMCMC$par.u3 <= 0)) stop("RJMCMC$par.u3 must be all positive") Cpar.u3 <- as.numeric(RJMCMC$par.u3) names(Cpar.u3) <- names(RJMCMC$par.u3) <- c("u3.1", "u3.2") }else{ if (is.na(ipar.u3)) RJMCMC$par.u3 <- rbind(matrix(c(rep(0, dd$p-1), rep(1, dd$p-1)), ncol=2), c(1, dd$p)) if (!is.matrix(RJMCMC$par.u3)) stop("RJMCMC$par.u3 must be a matrix") if (nrow(RJMCMC$par.u3) != dd$p) stop(paste("RJMCMC$par.u3 must have ", dd$p, " rows", sep="")) if (ncol(RJMCMC$par.u3) != 2) stop(paste("RJMCMC$par.u3 must have ", 2, " columns", sep="")) rownames(RJMCMC$par.u3) <- paste("u3.", 1:dd$p, sep="") colnames(RJMCMC$par.u3) <- paste(c(1, 2)) if (any(RJMCMC$par.u3[dd$p,] <= 0)) stop(paste("RJMCMC$par.u3[", dd$p, ",] must be all positive", sep="")) if (any(RJMCMC$par.u3[-dd$p,1] >= RJMCMC$par.u3[-dd$p,2])) stop(paste("The first column of RJMCMC$par.u3[-", dd$p, ",] must be strictly lower than the second column", sep="")) Cpar.u3 <- as.numeric(t(RJMCMC$par.u3)) names(Cpar.u3) <- paste("u3.", rep(1:dd$p, each=2), ".", rep(1:2, dd$p), sep="") } CRJMCMC <- c(CPaction, CPsplit, CPbirth, Cpar.u1, Cpar.u2, Cpar.u3) if (onlyInit) return(list(prior=prior, init=init, init2=init2, scale=scale, RJMCMC=RJMCMC)) if (length(nMCMC) != 4) stop("nMCMC must be of length 4") if (is.null(names(nMCMC))) names(nMCMC) <- c("burn", "keep", "thin", "info") names.nMCMC <- names(nMCMC) if (!match("burn", names.nMCMC, nomatch=0)) stop(paste("nMCMC[", dQuote("burn"), "] must be specified", sep="")) else n.burn <- nMCMC["burn"] if (!match("keep", names.nMCMC, nomatch=0)) stop(paste("nMCMC[", dQuote("keep"), "] must be specified", sep="")) else n.keep <- nMCMC["keep"] if (!match("thin", names.nMCMC, nomatch=0)) stop(paste("nMCMC[", dQuote("thin"), "] must be specified", sep="")) else n.thin <- nMCMC["thin"] if (!match("info", names.nMCMC, nomatch=0)) stop(paste("nMCMC[", dQuote("info"), "] must be specified", sep="")) else n.info <- nMCMC["info"] nMCMC <- c(n.burn, n.keep, n.thin, n.info) names(nMCMC) <- c("burn", "keep", "thin", "info") if (nMCMC["burn"] < 0) stop(paste("nMCMC[", dQuote("burn"), "] must be non-negative", sep="")) if (nMCMC["keep"] <= 0) stop(paste("nMCMC[", dQuote("keep"), "] must be positive", sep="")) if (nMCMC["thin"] <= 0) stop(paste("nMCMC[", dQuote("thin"), "] must be positive", sep="")) if (nMCMC["info"] <= 0 | nMCMC["info"] > max(nMCMC["burn"], nMCMC["keep"])) nMCMC["info"] <- max(nMCMC["burn"], nMCMC["keep"]) Cpar <- list(z0 = z0, z1 = z1, censor = dd$censor, dimy = c(p=dd$p, n=dd$n), priorInt = Cinteger, priorDouble = Cdouble, x_w = as.integer(c(dd$nx_w, dd$x_w))) rm(list=c("Cinteger", "Cdouble")) if (PED){ if (parallel){ if (parallel::detectCores() < 2) warning("It does not seem that at least 2 CPU cores are available needed for efficient parallel generation of the two chains.") if (missing(cltype)) cl <- parallel::makeCluster(2) else cl <- parallel::makeCluster(2, type = cltype) cat(paste("Parallel MCMC sampling of two chains started on ", date(), ".\n", sep="")) RET <- parallel::parLapply(cl, 1:2, NMixMCMCwrapper, scale = scale, prior = prior, inits = list(init, init2), Cpar = Cpar, RJMCMC = RJMCMC, CRJMCMC = CRJMCMC, actionAll = actionAll, nMCMC = nMCMC, keep.chains = keep.chains, PED = TRUE, dens.zero = dens.zero, lx_w = dd$lx_w) cat(paste("Parallel MCMC sampling finished on ", date(), ".\n", sep="")) parallel::stopCluster(cl) }else{ RET <- lapply(1:2, NMixMCMCwrapper, scale = scale, prior = prior, inits = list(init, init2), Cpar = Cpar, RJMCMC = RJMCMC, CRJMCMC = CRJMCMC, actionAll = actionAll, nMCMC = nMCMC, keep.chains = keep.chains, PED = TRUE, dens.zero = dens.zero, lx_w = dd$lx_w) } cat(paste("\nComputation of penalized expected deviance started on ", date(), ".\n", sep="")) if (prior$priorK == "fixed"){ resPED <- .C(C_NMix_PED, PED = double(5), pm.indDevObs = double(dd$n), pm.indpopt = double(dd$n), pm.windpopt = double(dd$n), invalid.indDevObs = integer(dd$n), invalid.indpopt = integer(dd$n), invalid.windpopt = integer(dd$n), sum.ISweight = double(dd$n), err = integer(1), y0 = as.double(t(z0)), y1 = as.double(t(z1)), censor = as.integer(t(dd$censor)), nxw_xw = as.integer(Cpar$x_w), dimy = as.integer(c(dd$p, dd$n)), chK1 = as.integer(RET[[1]]$K), chw1 = as.double(t(RET[[1]]$w)), chmu1 = as.double(t(RET[[1]]$mu)), chLi1 = as.double(t(RET[[1]]$Li)), chK2 = as.integer(RET[[1]]$K), chw2 = as.double(t(RET[[2]]$w)), chmu2 = as.double(t(RET[[2]]$mu)), chLi2 = as.double(t(RET[[2]]$Li)), M = as.integer(nMCMC["keep"]), Kmax = as.integer(CKmax), Krandom = as.integer(0), Dens.ZERO = as.double(dens.zero), EMin = as.double(EMin), PACKAGE = thispackage) }else{ resPED <- .C(C_NMix_PED, PED = double(5), pm.indDevObs = double(dd$n), pm.indpopt = double(dd$n), pm.windpopt = double(dd$n), invalid.indDevObs = integer(dd$n), invalid.indpopt = integer(dd$n), invalid.windpopt = integer(dd$n), sum.ISweight = double(dd$n), err = integer(1), y0 = as.double(t(z0)), y1 = as.double(t(z1)), censor = as.integer(t(dd$censor)), nxw_xw = as.integer(Cpar$x_w), dimy = as.integer(c(dd$p, dd$n)), chK1 = as.integer(RET[[1]]$K), chw1 = as.double(RET[[1]]$w), chmu1 = as.double(RET[[1]]$mu), chLi1 = as.double(RET[[1]]$Li), chK2 = as.integer(RET[[2]]$K), chw2 = as.double(RET[[2]]$w), chmu2 = as.double(RET[[2]]$mu), chLi2 = as.double(RET[[2]]$Li), M = as.integer(nMCMC["keep"]), Kmax = as.integer(CKmax), Krandom = as.integer(1), Dens.ZERO = as.double(dens.zero), EMin = as.double(EMin), PACKAGE = thispackage) } cat(paste("Computation of penalized expected deviance finished on ", date(), ".\n", sep="")) if (resPED$err) stop("Something went wrong.") names(resPED$PED) <- c("D.expect", "p(opt)", "PED", "wp(opt)", "wPED") RET$PED <- resPED$PED detS <- prod(scale$scale) idetS <- 1 / detS log.idetS <- -log(detS) RET$PED["D.expect"] <- RET$PED["D.expect"] - 2*dd$n*log.idetS RET$PED["PED"] <- RET$PED["PED"] - 2*dd$n*log.idetS RET$PED["wPED"] <- RET$PED["wPED"] - 2*dd$n*log.idetS RET$D <- resPED$pm.indDevObs - 2*log.idetS RET$popt <- resPED$pm.indpopt RET$wpopt <- resPED$pm.windpopt RET$inv.D <- resPED$invalid.indDevObs RET$inv.popt <- resPED$invalid.indpopt RET$inv.wpopt <- resPED$invalid.windpopt RET$sumISw <- resPED$sum.ISweight class(RET) <- "NMixMCMClist" }else{ RET <- NMixMCMCwrapper(chain = 1, scale = scale, prior = prior, inits = list(init), Cpar = Cpar, RJMCMC = RJMCMC, CRJMCMC = CRJMCMC, actionAll = actionAll, nMCMC = nMCMC, keep.chains = keep.chains, PED = FALSE, dens.zero = dens.zero, lx_w = dd$lx_w) } return(RET) }
loc_title <- ph_location_type(type = "title") loc_footer <- ph_location_type(type = "ftr") loc_dt <- ph_location_type(type = "dt") loc_slidenum <- ph_location_type(type = "sldNum") loc_body <- ph_location_type(type = "body") doc <- read_pptx() doc <- add_slide(doc) doc <- ph_with(x = doc, "Un titre", location = loc_title) doc <- ph_with(x = doc, "pied de page", location = loc_footer) doc <- ph_with(x = doc, format(Sys.Date()), location = loc_dt) doc <- ph_with(x = doc, "slide 1", location = loc_slidenum) doc <- ph_with(x = doc, letters[1:10], location = loc_body) loc_subtitle <- ph_location_type(type = "subTitle") loc_ctrtitle <- ph_location_type(type = "ctrTitle") doc <- add_slide(doc, layout = "Title Slide", master = "Office Theme") doc <- ph_with(x = doc, "Un sous titre", location = loc_subtitle) doc <- ph_with(x = doc, "Un titre", location = loc_ctrtitle) fileout <- tempfile(fileext = ".pptx") print(doc, target = fileout )
lp_lin_iv <- function(endog_data, shock = NULL, instr = NULL, use_twosls = FALSE, instrum = NULL, lags_endog_lin = NULL, exog_data = NULL, lags_exog = NULL, contemp_data = NULL, lags_criterion = NaN, max_lags = NaN, trend = NULL, confint = NULL, use_nw = TRUE, nw_lag = NULL, nw_prewhite = FALSE, adjust_se = FALSE, hor = NULL, num_cores = 1){ if(!is.null(instr)){ shock <- instr warning("'instr' is a deprecated input name. Use 'shock' instead.") } if(!(is.data.frame(endog_data))){ stop('The data has to be a data.frame().') } if(is.nan(lags_endog_lin) & !is.character(lags_criterion)){ stop('"lags_endog_lin" can only be NaN if a lag length criterion is given.') } if(is.null(shock)){ stop('You have to provide an instrument to shock with.') } if(!is.data.frame(shock)){ stop('The instrument has to be given as a data.frame().') } if(!is.null(exog_data) & !is.data.frame(exog_data)){ stop('Exogenous data has to be given as a data.frame.') } if(!is.null(exog_data) & is.null(lags_exog)){ stop('Please provide a lag length for the exogenous data.') } if(is.null(lags_criterion)){ stop('"lags_criterion" has to be NaN or a character, specifying the lag length criterion.') } if(is.null(trend)){ stop('Please specify whether and which type of trend to include.') } if(is.null(confint)){ stop('Please specify a value for the width of the confidence bands.') } if(is.null(hor)){ stop('Please specify the number of horizons.') } if(!(is.nan(lags_criterion) | lags_criterion == 'AICc'| lags_criterion == 'AIC' | lags_criterion == 'BIC')){ stop('Possible lag length criteria are AICc, AIC or BIC. NaN if lag length is specified.') } if((is.character(lags_criterion)) & (!is.na(lags_endog_lin))){ stop('You can not provide a lag criterion (AICc, AIC or BIC) and a fixed number of lags. Please set lags_endog_lin to NaN if you want to use a lag length criterion.') } if(!(hor > 0) | is.nan(hor) | !(hor %% 1 == 0)){ stop('The number of horizons has to be an integer and > 0.') } if(!(trend %in% c(0,1,2))){ stop('For trend please enter 0 = no trend, 1 = trend, 2 = trend and quadratic trend.') } if(!(confint >=0)){ stop('The width of the confidence bands has to be >=0.') } if(isTRUE(use_twosls) & is.null(instrum)){ stop('Please specify at least one instrument to use for 2SLS.') } specs <- list() specs$shock <- shock specs$use_twosls <- use_twosls specs$instrum <- instrum specs$lags_endog_lin <- lags_endog_lin specs$exog_data <- exog_data specs$lags_exog <- lags_exog specs$contemp_data <- contemp_data specs$lags_criterion <- lags_criterion specs$max_lags <- max_lags specs$trend <- trend specs$confint <- confint specs$hor <- hor specs$use_nw <- use_nw specs$nw_prewhite <- nw_prewhite specs$adjust_se <- adjust_se specs$nw_lag <- nw_lag specs$model_type <- 1 specs$starts <- 1 specs$ends <- dim(endog_data)[1] specs$column_names <- names(endog_data) specs$endog <- ncol(endog_data) data_lin <- create_lin_data(specs, endog_data) y_lin <- data_lin[[1]] x_lin <- data_lin[[2]] z_lin <- data_lin[[3]] specs$y_lin <- y_lin specs$x_lin <- x_lin specs$z_lin <- z_lin b1 <- matrix(NaN, specs$endog, specs$endog) b1_low <- matrix(NaN, specs$endog, specs$endog) b1_up <- matrix(NaN, specs$endog, specs$endog) irf_mean <- matrix(NaN, 1, specs$hor) irf_low <- irf_mean irf_up <- irf_mean irf_lin_mean <- matrix(NaN, nrow = specs$endog, ncol = specs$hor) irf_lin_low <- irf_lin_mean irf_lin_up <- irf_lin_mean diagnost_ols_each_h <- matrix(NaN, specs$hor, 4) rownames(diagnost_ols_each_h) <- paste("h", 1:specs$hor, sep = " ") colnames(diagnost_ols_each_h) <- c("R-sqrd.", "Adj. R-sqrd.", "F-stat", " p-value") if(is.null(num_cores)){ num_cores <- min(specs$endog, parallel::detectCores() - 1) } cl <- parallel::makeCluster(num_cores) doParallel::registerDoParallel(cl) if(is.nan(specs$lags_criterion) == TRUE){ lin_irfs <- foreach(s = 1:specs$endog, .packages = 'lpirfs') %dopar%{ for (h in 1:(specs$hor)){ yy <- y_lin[h : dim(y_lin)[1], ] xx <- x_lin[1 : (dim(x_lin)[1] - h + 1), ] if(!is.matrix(xx)){ xx <- as.matrix(xx) } if(!is.matrix(yy)){ yy <- matrix(yy) } if(is.null(nw_lag)){ lag_nw <- h } else { lag_nw <- nw_lag } if(specs$use_twosls == FALSE){ get_ols_vals <- lpirfs::get_std_err(yy, xx, lag_nw, s, specs) std_err <- get_ols_vals[[1]] b <- get_ols_vals[[2]] get_diagnost <- lpirfs::ols_diagnost(yy[, s], xx) diagnost_ols_each_h[h, 1] <- get_diagnost[[3]] diagnost_ols_each_h[h, 2] <- get_diagnost[[4]] diagnost_ols_each_h[h, 3] <- get_diagnost[[5]] diagnost_ols_each_h[h, 4] <- stats::pf(get_diagnost[[5]], get_diagnost[[6]], get_diagnost[[7]], lower.tail = F) } else { zz <- specs$z_lin[1 : (dim(z_lin)[1] - h + 1), ] %>% as.matrix() get_tsls_vals <- get_std_err_tsls(yy, xx, lag_nw, s, zz, specs) b <- get_tsls_vals[[2]] std_err <- get_tsls_vals[[1]] get_diagnost <- lpirfs::ols_diagnost(yy[, s], xx) diagnost_ols_each_h[h, 1] <- get_diagnost[[3]] diagnost_ols_each_h[h, 2] <- get_diagnost[[4]] diagnost_ols_each_h[h, 3] <- get_diagnost[[5]] diagnost_ols_each_h[h, 4] <- stats::pf(get_diagnost[[5]], get_diagnost[[6]], get_diagnost[[7]], lower.tail = F) } irf_mean[1, h] <- b[2] irf_low[1, h] <- b[2] - std_err[2] irf_up[1, h] <- b[2] + std_err[2] } return(list(irf_mean, irf_low, irf_up, diagnost_ols_each_h)) } diagnostic_list <- list() for(i in 1:specs$endog){ irf_lin_mean[i , ] <- as.matrix(do.call(rbind, lin_irfs[[i]][1])) irf_lin_low[i , ] <- as.matrix(do.call(rbind, lin_irfs[[i]][2])) irf_lin_up[i , ] <- as.matrix(do.call(rbind, lin_irfs[[i]][3])) diagnostic_list[[i]] <- lin_irfs[[i]][[4]] } names(diagnostic_list) <- paste("Endog. Variable:", specs$column_names , sep = " ") } else { lag_crit <- switch(specs$lags_criterion, 'AICc'= 1, 'AIC' = 2, 'BIC' = 3) chosen_lags <- list() chosen_lags_h <- matrix(NaN, specs$hor, 1) lin_irfs <- foreach(s = 1:specs$endog, .packages = 'lpirfs') %dopar% { for (h in 1:specs$hor){ if(is.null(nw_lag)){ lag_nw <- h } else { lag_nw <- nw_lag } n_obs <- nrow(y_lin[[1]]) - h + 1 val_criterion <- lpirfs::get_vals_lagcrit(y_lin, x_lin, lag_crit, lag_nw, s, specs$max_lags, n_obs) lag_choice <- which.min(val_criterion) yy <- y_lin[[lag_choice]][, s] yy <- yy[h: length(yy)] xx <- x_lin[[lag_choice]] xx <- xx[1:(dim(xx)[1] - h + 1),] if(specs$use_twosls == FALSE){ get_ols_vals <- lpirfs::get_std_err(yy, xx, lag_nw, 1, specs) std_err <- get_ols_vals[[1]] b <- get_ols_vals[[2]] get_diagnost <- lpirfs::ols_diagnost(yy, xx) diagnost_ols_each_h[h, 1] <- get_diagnost[[3]] diagnost_ols_each_h[h, 2] <- get_diagnost[[4]] diagnost_ols_each_h[h, 3] <- get_diagnost[[5]] diagnost_ols_each_h[h, 4] <- stats::pf(get_diagnost[[5]], get_diagnost[[6]], get_diagnost[[7]], lower.tail = F) chosen_lags_h[h, 1] <- lag_choice } else { zz <- z_lin[[lag_choice]] zz <- zz[1:(dim(zz)[1] - h + 1),] get_tsls_vals <- get_std_err_tsls(yy, xx, lag_nw, 1, zz, specs) b <- get_tsls_vals[[2]] std_err <- get_tsls_vals[[1]] get_diagnost <- lpirfs::ols_diagnost(yy, xx) diagnost_ols_each_h[h, 1] <- get_diagnost[[3]] diagnost_ols_each_h[h, 2] <- get_diagnost[[4]] diagnost_ols_each_h[h, 3] <- get_diagnost[[5]] diagnost_ols_each_h[h, 4] <- stats::pf(get_diagnost[[5]], get_diagnost[[6]], get_diagnost[[7]], lower.tail = F) chosen_lags_h[h, 1] <- lag_choice } irf_mean[1, h] <- b[2] irf_low[1, h] <- b[2] - std_err[2] irf_up[1, h] <- b[2] + std_err[2] } return(list(irf_mean, irf_low, irf_up, diagnost_ols_each_h, chosen_lags_h)) } diagnostic_list <- list() for(i in 1:specs$endog){ irf_lin_mean[i , ] <- as.matrix(do.call(rbind, lin_irfs[[i]][1])) irf_lin_low[i , ] <- as.matrix(do.call(rbind, lin_irfs[[i]][2])) irf_lin_up[i , ] <- as.matrix(do.call(rbind, lin_irfs[[i]][3])) diagnostic_list[[i]] <- lin_irfs[[i]][[4]] chosen_lags[[i]] <- lin_irfs[[i]][[5]] } names(diagnostic_list) <- paste("Endog. Variable:", specs$column_names , sep = " ") names(chosen_lags) <- paste("Endog. Variable:", specs$column_names , sep = " ") specs$chosen_lags <- chosen_lags } parallel::stopCluster(cl) result <- list(irf_lin_mean = irf_lin_mean, irf_lin_low = irf_lin_low, irf_lin_up = irf_lin_up, diagnostic_list = diagnostic_list, specs = specs) class(result) <- "lpirfs_lin_iv_obj" return(result) }
sequentialSignatureFinder <- function(startingGene, logFileName = "", coeffMissingAllowed = 0.75, subsetToUse = 1:ncol(geData)) { n <- nrow(geData) m <- ncol(geData) toExplore <- rep(FALSE, m) toExplore[subsetToUse] <- TRUE toExplore[startingGene] <- FALSE logFileName <- paste(logFileName, "SignatureFinderLog.txt", sep = "") cat(paste("Working on ", m, " genes observed on ", n, " samples.\n", sep = ""), file = logFileName, append = FALSE) cat(paste("Starting on ", ttime <- Sys.time(), "\n", sep = ""), file = logFileName, append = TRUE) cat(paste("Starting signature: ", paste(colnames(geData)[startingGene], collapse = ", "), ";\n", sep = ""), file = logFileName, append = TRUE) aClassify <- rep(NA, n) ssignature <- startingGene runs <- 0 result <- list() result$signatureName <- (colnames(geData)[startingGene])[1] result$startingSignature <- colnames(geData)[startingGene] result$coeffMissingAllowed <- coeffMissingAllowed if(length(ssignature) > 1) notMissing <- apply(!is.na(geData[, ssignature]), 1, sum) else notMissing <- !is.na(geData[, ssignature]) + 0 notMissing <- notMissing > 0 clusters <- classify(geData[notMissing, ssignature])$clusters tmp1 <- min(survfit(stData[clusters == 1]~ 1)$surv) tmp2 <- min(survfit(stData[clusters == 2]~ 1)$surv) if(tmp1 > tmp2) { clusters[clusters == 1] <- 0 clusters[clusters == 2] <- 1 } else clusters[clusters == 2] <- 0 runningDistance <- survdiff(stData[notMissing] ~ clusters)$chisq result$startingTValue <- runningDistance result$startingPValue <- 1 - pchisq(runningDistance, df = 1) tmpClassification <- rep(NA, n) tmpClassification[notMissing] <- clusters result$startingClassification <- as.factor(tmpClassification) levels(result$startingClassification) <- c("good", "poor") cat(paste("tValue = ", runningDistance, " (", result$startingPValue, ")\n", sep = ""), file = logFileName, append = TRUE) exitFromMain <- FALSE repeat { if(exitFromMain) break runs <- runs + 1 distances <- rep(0, m) j <- 1 while(j <= m) { if(!toExplore[j]) { j <- j + 1; next } distances[j] <- tValueFun(c(ssignature, j), coeffMissingAllowed = coeffMissingAllowed) j <- j + 1 } exitFromInner <- FALSE repeat { if(exitFromInner) break maxDistance <- max(distances) if(maxDistance >= runningDistance) { candidate <- which(distances == maxDistance) if(length(candidate) == 1) { notMissing <- apply(!is.na(geData[, c(ssignature, candidate)]), 1, sum) notMissing <- notMissing > floor(length(c(ssignature, candidate))^coeffMissingAllowed) clusters <- classify(geData[notMissing, c(ssignature, candidate)])$clusters checkOne <- (min(table(clusters)) > floor(0.1 * n)) sf0 <- survfit(stData[clusters == 1] ~ 1)$surv sf1 <- survfit(stData[clusters == 2] ~ 1)$surv checkTwo <- sum(fivenum(sf0) > fivenum(sf1)) checkTwo <- ((checkTwo == 0) | (checkTwo == 5)) if(checkOne & checkTwo) { ssignature <- c(ssignature, candidate) toExplore[ssignature] <- FALSE runningDistance <- maxDistance cat(paste("... improved signature: ", paste(colnames(geData)[ssignature], collapse = ", "), ";\ntValue = ", runningDistance, " (", 1 - pchisq(runningDistance, df = 1), ")\n", sep = ""), file = logFileName, append = TRUE) exitFromInner <- TRUE } } else { if(length(candidate) > 0.01*m) { exitFromInner <- TRUE exitFromMain <- TRUE break } tmpCandidate <- findBest(runningDistance, ssignature, candidate) if(length(tmpCandidate) > 0) { tmp <- survdiff(stData ~ classify(geData[, c(ssignature, tmpCandidate)])$clusters)$chisq if(tmp > runningDistance) { candidate <- tmpCandidate ssignature <- c(ssignature, candidate) runningDistance <- tmp toExplore[ssignature] <- FALSE cat(paste("... improved signature: ", paste(colnames(geData)[ssignature], collapse = ", "), ";\ntValue = ", runningDistance, " (", 1 - pchisq(runningDistance, df = 1), ")\n", sep = ""), file = logFileName, append = TRUE) exitFromInner <- TRUE } } } distances[candidate] <- 0 } else { exitFromInner <- TRUE exitFromMain <- TRUE } } } if(length(ssignature) > 1) { notMissing <- apply(!is.na(geData[, ssignature]), 1, sum) notMissing <- notMissing > floor(length(ssignature)^coeffMissingAllowed) } else { notMissing <- !is.na(geData[, ssignature]) + 0 notMissing <- notMissing > 0 } clusters <- rep(NA, n) clusters[notMissing] <- classify(geData[notMissing, ssignature])$clusters clusters <- goodAndPoorClassification(clusters) K <- length(ssignature) result$signature <- colnames(geData)[ssignature] result$tValue <- survdiff(stData[notMissing] ~ clusters[notMissing])$chisq result$pValue <- 1-pchisq(result$tValue, df = 1) result$signatureIDs <- ssignature names(result$signatureIDs) <- result$signature result$classification <- clusters cat(paste("\n\nfinal signature: ", paste(colnames(geData)[ssignature], collapse = " "), sep = ""), file = logFileName, append = TRUE) cat(paste("\ntValue = ", runningDistance, " (", 1 - pchisq(runningDistance, df = 1), ")\n", sep = ""), file = logFileName, append = TRUE) cat(paste("\nlength of the signature = ", length(ssignature), sep = ""), file = logFileName, append = TRUE) cat(paste("\nnumber of joint missing values = ", sum(!notMissing), " (", 100*round(sum(!notMissing)/n,2), "%)", sep = ""), file = logFileName, append = TRUE) cat(paste("\n\nEnd of computation at ", t2 <- Sys.time(), "; elapsed time: ", t2 - ttime, ".", sep = ""), file = logFileName, append = TRUE) return(result) }
setup.inspector <- function(config.file , validate = TRUE) { if (missing(config.file)) runStopCommand('Configuration file not set.') else configuration <- checkConfigFile(config.file) object <- new( "Inspector", paths = list( filename = configuration$paths$filename, filename_output_tag = configuration$paths$filename_output_tag, dir_data = configuration$paths$dir_data, dir_output = configuration$paths$dir_output, dir_references = configuration$paths$dir_references ), supplementaryFiles = list( header_translations = configuration$supplementaryFiles$header_translations, allele_ref_std = configuration$supplementaryFiles$allele_ref_std, allele_ref_std_population = configuration$supplementaryFiles$allele_ref_std_population, allele_ref_alt = configuration$supplementaryFiles$allele_ref_alt, beta_ref_std = configuration$supplementaryFiles$beta_ref_std ), input_parameters = list( effect_type = configuration$input_parameters$effect_type, column_separator = configuration$input_parameters$column_separator, na.string = configuration$input_parameters$na.string, imputed_T = paste(configuration$input_parameters$imputed_T,collapse = '|'), imputed_F = paste(configuration$input_parameters$imputed_F,collapse = '|'), calculate_missing_p = configuration$input_parameters$calculate_missing_p, file_order_string = paste(configuration$input_parameters$file_order_string,collapse = '|') ), output_parameters = list( save_final_dataset = configuration$output_parameters$save_final_dataset, save_as_effectSize_reference = configuration$output_parameters$save_as_effectSize_reference, gzip_final_dataset = configuration$output_parameters$gzip_final_dataset, out_header = configuration$output_parameters$out_header, out_sep = configuration$output_parameters$out_sep, out_na = configuration$output_parameters$out_na, out_dec = configuration$output_parameters$out_dec, html_report = configuration$output_parameters$html_report, object_file = configuration$output_parameters$object_file, add_column_multiallelic = configuration$output_parameters$add_column_multiallelic, add_column_HQ = configuration$output_parameters$add_column_HQ, add_column_AFmismatch = configuration$output_parameters$add_column_AFmismatch, add_column_AF = configuration$output_parameters$add_column_AF, add_column_rsid = configuration$output_parameters$add_column_rsid, add_column_hid = configuration$output_parameters$add_column_hid, ordered = configuration$output_parameters$ordered ), remove_chromosomes = list( remove_X = configuration$remove_chromosomes$remove_X, remove_Y = configuration$remove_chromosomes$remove_Y, remove_XY = configuration$remove_chromosomes$remove_XY, remove_M = configuration$remove_chromosomes$remove_M ), plot_specs = list( make_plots = configuration$plot_specs$make_plots, plot_cutoff_p = configuration$plot_specs$plot_cutoff_p, graphic_device = configuration$plot_specs$graphic_device, plot_title = configuration$plot_specs$plot_title ), filters = list( HQfilter_FRQ = configuration$filters$HQfilter_FRQ, HQfilter_HWE = configuration$filters$HQfilter_HWE, HQfilter_cal = configuration$filters$HQfilter_cal, HQfilter_imp = configuration$filters$HQfilter_imp, threshold_diffEAF = configuration$filters$threshold_diffEAF, minimal_impQ_value = configuration$filters$minimal_impQ_value, maximal_impQ_value = configuration$filters$maximal_impQ_value ), debug = list( verbose = configuration$debug$verbose, save_pre_modification_file = configuration$debug$save_pre_modification_file, reduced.AF.plot = configuration$debug$reduced.AF.plot, test_row_count = configuration$debug$test_row_count ), input_files = configuration$paths$input_files, created_at = Sys.time(), start_time = Sys.time(), end_time = Sys.time() ) if(!validate) return(object) else if(validate.Inspector(object)) return(object) }
Cornfield_exact_conditional_CI_2x2 <- function(n, alpha=0.05, printresults=TRUE) { n11 <- n[1, 1] n1p <- n[1, 1] + n[1, 2] n2p <- n[2, 1] + n[2, 2] np1 <- n[1, 1] + n[2, 1] estimate <- n[1, 1] * n[2, 2] / (n[1, 2] * n[2, 1]) tol <- 0.0000001 theta0 <- 0.00001 theta1 <- 100000 if (is.na(estimate) || estimate==Inf) { L <- uniroot(calculate_L, c(theta0,theta1), n11=n11, np1=np1, n1p=n1p, n2p=n2p, alpha=alpha, tol=tol)$root } else if (estimate == 0) { L <- 0 } else { L <- uniroot(calculate_L, c(theta0,estimate), n11=n11, np1=np1, n1p=n1p, n2p=n2p, alpha=alpha, tol=tol)$root } if (n[2, 1] == 0 || n[1, 2] == 0) { U <- Inf } else if (estimate == 0) { U <- uniroot(calculate_U, c(theta0,theta1), n11=n11, np1=np1, n1p=n1p, n2p=n2p, alpha=alpha, tol=tol)$root } else { U <- uniroot(calculate_U, c(estimate,theta1), n11=n11, np1=np1, n1p=n1p, n2p=n2p, alpha=alpha, tol=tol)$root } if (printresults) { print(sprintf('Cornfield exact conditional CI: estimate = %6.4f (%g%% CI %6.4f to %6.4f)', estimate, 100 * (1 - alpha), L, U), quote=FALSE) } res <- data.frame(lower=L, upper=U, estimate=estimate) invisible(res) } calculate_L <- function(theta0, n11, np1, n1p, n2p, alpha) { f <- 0 for (x11 in n11:min(c(np1, n1p))) { f <- f + noncentralhyge(x11, theta0, n1p, n2p, np1) } f <- f - alpha / 2 return(f) } calculate_U <- function(theta0, n11, np1, n1p, n2p, alpha) { f <- 0 for (x11 in max(c(0, np1-n2p)):n11) { f <- f + noncentralhyge(x11, theta0, n1p, n2p, np1) } f <- f - alpha / 2 return(f) } noncentralhyge <- function(x11, theta0, n1p, n2p, np1) { numerator <- choose(n1p, x11) * choose(n2p, np1 - x11) * (theta0 ^ x11) denominator <- 0 for (i in max(c(0, np1-n2p)):min(c(n1p, np1))) { denominator <- denominator + choose(n1p, i) * choose(n2p, np1 - i) * (theta0 ^ i) } f <- numerator / denominator return(f) }
CV.S=function (y, S, W = NULL, trim = 0, draw = FALSE, metric = metric.lp, ...) { n = ncol(S) isfdata <- is.fdata(y) if (isfdata) { nn<-nrow(y) if (is.null(W)) W<-diag(nn) y2 = t(y$data) y.est = t(S %*% y2) y.est <- fdata(y.est, y$argvals, y$rangeval, y$names) e <- fdata(sweep((y - y.est)$data,2,1-diag(S),"%/%"), y$argvals, y$rangeval, y$names) ee <- drop(norm.fdata(e, metric = metric, ...)[, 1]^2) if (trim > 0) { e.trunc = quantile(ee, probs = (1 - trim), na.rm = TRUE, type = 4) ind <- ee <= e.trunc if (draw) plot(y, col = (2 - ind)) res = mean(ee[ind]) } else res = mean(ee) } else { if (is.null(W)) W<-diag(n) y2 <- y y.est = S %*% y2 I = diag(n)/(1 - diag(S))^2 W = W * I e <- y2 - y.est if (trim > 0) { ee = t(e) e.trunc = quantile(abs(ee), probs = (1 - trim), na.rm = TRUE, type = 4) l <- which(abs(ee) <= e.trunc) res = mean(diag(W)[l] * e[l]^2) } res = mean(diag(W) * e^2) } if (is.nan(res)) res = Inf return(res) }
are_equal_tracelogs <- function( tracelog_1, tracelog_2 ) { beautier::check_tracelog(tracelog_1) beautier::check_tracelog(tracelog_2) if (is.na(tracelog_1$filename)) { if (!is.na(tracelog_2$filename)) return(FALSE) } else { if (tracelog_1$filename != tracelog_2$filename) return(FALSE) } tracelog_1$log_every == tracelog_2$log_every && tracelog_1$mode == tracelog_2$mode && tracelog_1$sanitise_headers == tracelog_2$sanitise_headers && tracelog_1$sort == tracelog_2$sort }
izoo2rzoo <-function(x, ...) UseMethod("izoo2rzoo") izoo2rzoo.default <- function(x, from= start(x), to= end(x), date.fmt="%Y-%m-%d", tstep ="days", ...) { valid.class <- c("xts", "zoo") if (length(which(!is.na(match(class(x), valid.class )))) <= 0) stop("Invalid argument: 'class(x)' must be in c('xts', 'zoo')") izoo2rzoo.zoo(x=x, from=from, to=to, date.fmt=date.fmt, tstep=tstep, ...) } izoo2rzoo.zoo <- function(x, from= start(x), to= end(x), date.fmt="%Y-%m-%d", tstep ="days", ... ) { if (!is.zoo(x)) stop("Invalid argument: 'x' must be of class 'zoo'") ifelse ( grepl("%H", date.fmt, fixed=TRUE) | grepl("%M", date.fmt, fixed=TRUE) | grepl("%S", date.fmt, fixed=TRUE) | grepl("%I", date.fmt, fixed=TRUE) | grepl("%p", date.fmt, fixed=TRUE) | grepl("%X", date.fmt, fixed=TRUE), subdaily.date.fmt <- TRUE, subdaily.date.fmt <- FALSE ) if(subdaily.date.fmt) { from <- as.POSIXct(from, format=date.fmt) to <- as.POSIXct(to, format=date.fmt) } else { from <- as.Date(from, format=date.fmt) to <- as.Date(to, format=date.fmt) } if ( class(time(x))[1] %in% c("factor", "character") ) ifelse(subdaily.date.fmt, time(x) <- as.POSIXct(dates, format=date.fmt), time(x) <- as.Date(dates, format=date.fmt) ) x.freq <- sfreq(x) if (x.freq %in% c("minute","hourly") ) { if (!subdaily.date.fmt) stop("Invalid argument: 'date.fmt' (", date.fmt, ") is not compatible with a sub-daily time series !!") } else if (subdaily.date.fmt) { time(x) <- as.POSIXct(time(x)) warning("'date.fmt' (", date.fmt, ") is sub-daily, while 'x' is a '", x.freq, "' ts => 'time(x)=as.POSIXct(time(x))'") } dates <- seq(from=from, to=to, by= tstep) na.zoo <- zoo(rep(NA, length(dates)), dates) x.sel <- window(x, start=from, end=to) x.merged <- merge(na.zoo, x.sel) x.merged <- x.merged[,-1] if ( is.matrix(x) | is.data.frame(x) ) colnames(x.merged) <- colnames(x) return( x.merged ) }
[ { "title": "bugsparallel", "href": "http://ggorjan.blogspot.com/2009/06/bugsparallel.html" }, { "title": "Two sample Student’s t-test "href": "http://statistic-on-air.blogspot.com/2009/07/two-sample-students-t-test-2.html" }, { "title": "Integration take two – Shiny application", "href": "https://beckmw.wordpress.com/2013/05/13/integration-take-two-shiny-application/" }, { "title": "Visualizing Growth of a Retail Chain", "href": "https://rstats.wordpress.com/2011/03/15/visualizing-store-growth/" }, { "title": "Rblpapi ‘Release Candidate’ 0.3.2.5", "href": "http://dirk.eddelbuettel.com/blog/2016/03/06/" }, { "title": "Drawing pedigree examples using the kinship R package", "href": "http://ggorjan.blogspot.com/2010/06/drawing-pedigree-examples-using-kinship.html" }, { "title": "How long until an R portfolio makes money?", "href": "http://www.arilamstein.com/blog/2016/10/26/long-r-portfolio-makes-money/" }, { "title": "Le Monde puzzle [ "href": "https://xianblog.wordpress.com/2011/03/26/le-monde-puzzle-7/" }, { "title": "A Quantstrat to Build On Part 6", "href": "http://timelyportfolio.blogspot.com/2011/07/quantstrat-to-build-on-part-6.html" }, { "title": "Backtesting in Excel and R", "href": "http://blog.fosstrading.com/2011/02/backtesting-in-excel-and-r.html" }, { "title": "Graph Examples from Visualizing Data by William Cleveland", "href": "http://www.wekaleamstudios.co.uk/posts/graph-examples-from-visualizing-data-by-william-cleveland/" }, { "title": "rbokeh Version 0.4.1 Released", "href": "http://ryanhafen.com/blog/rbokeh-0-4-1" }, { "title": "And the most loyal fans in the NBA are…", "href": "https://statofmind.wordpress.com/2014/04/11/and-the-most-loyal-fans-in-the-nba-are/" }, { "title": "RStudio – Infoworld 2015 Technology of the Year Award Recipient!", "href": "https://blog.rstudio.org/2015/01/28/rstudio-infoworld-2015-technology-of-the-year-award-recipient/" }, { "title": "Simpler isn’t always faster", "href": "http://jcarroll.com.au/2016/04/14/simpler-isnt-always-faster/" }, { "title": "Linking text, results, and analyses: Increasing transparency and efficiency", "href": "http://jeromyanglim.blogspot.com/2009/09/linking-text-results-and-analyses.html" }, { "title": "self-organizing map in R", "href": "http://onetipperday.sterding.com/2012/07/self-organizing-map-in-r.html" }, { "title": "Program for useR! 2011 available", "href": "http://blog.revolutionanalytics.com/2011/07/program-for-user-2011-available.html" }, { "title": "Post 4: Sampling the person ability parameters", "href": "https://web.archive.org/web/http://mcmcinirt.stat.cmu.edu/archives/283?utm_source=rss&utm_medium=rss&utm_campaign=post-4-sampling-the-student-ability-parameters" }, { "title": "What’s new in Revolution R Enterprise 7.4", "href": "http://blog.revolutionanalytics.com/2015/05/announcing_rre7_4.html" }, { "title": "How to plot points, regression line and residuals", "href": "http://statistic-on-air.blogspot.com/2011/06/how-to-plot-points-regression-line-and.html" }, { "title": "A Visualization Of The 100 Greatest Love Songs ft. D3.js", "href": "https://aschinchon.wordpress.com/2015/10/12/a-visualization-of-the-100-greatest-love-songs-ft-d3-js/" }, { "title": "Extracting upstream regions of a RefSeq human gene list in R using Bioconductor", "href": "http://tata-box-blog.blogspot.com/2012/07/extracting-upstream-regions-of-refseq.html" }, { "title": "Download Federal Reserve Economic Data (FRED) with Python", "href": "https://statcompute.wordpress.com/2015/12/10/download-federal-reserve-economic-data-fred-with-python/" }, { "title": "Example 8.19: Referencing lists of variables", "href": "https://feedproxy.google.com/~r/SASandR/~3/KTVoBAjS7vI/example-819-referencing-lists-of.html" }, { "title": "R 3.1.2 release (and upgrading for Windows users)", "href": "https://www.r-statistics.com/2014/11/r-3-1-2-release-and-upgrading-for-windows-users/" }, { "title": "Good advice for security with R", "href": "http://blog.revolutionanalytics.com/2015/08/good-advice-for-security-with-r.html" }, { "title": "How do I re-arrange??: Ordering a plot revisited", "href": "https://trinkerrstuff.wordpress.com/2013/08/14/how-do-i-re-arrange-ordering-a-plot-revisited/" }, { "title": "Spreadsheet errors", "href": "http://www.cybaea.net/Blogs/Spreadsheet-errors.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+CybaeaData+%28CYBAEA+Data+and+Analysis%29" }, { "title": "Twenty rules for good graphics", "href": "http://robjhyndman.com/hyndsight/graphics/?utm_source=rss&utm_medium=rss&utm_campaign=graphics" }, { "title": "R Hero saves Backup City with archivist and GitHub", "href": "http://r-addict.com/2016/06/13/RHero-Saves-Backup-City-With-archivist-github.html" }, { "title": "Interactive Simple Networks", "href": "http://www.moreorlessnumbers.com/2014/12/interactive-simple-networks.html" }, { "title": "Modeling Trick: Masked Variables", "href": "http://www.win-vector.com/blog/2012/07/modeling-trick-masked-variables/?utm_source=rss&utm_medium=rss&utm_campaign=modeling-trick-masked-variables" }, { "title": "R in production systems", "href": "https://erehweb.wordpress.com/2011/02/02/r-in-production-systems/" }, { "title": "Function for phylogeny resolution", "href": "https://feedproxy.google.com/~r/github/wpna/~3/kw3X3qI_IFE/" }, { "title": "Mango at SQL Relay!", "href": "http://www.mango-solutions.com/wp/2015/10/mango-at-sql-relay/" }, { "title": "Frazzini goes French", "href": "http://timelyportfolio.blogspot.com/2014/09/frazzini-oes-french.html" }, { "title": "Macroeconomic charts by the Fed using R and Plotly", "href": "http://moderndata.plot.ly/macroeconomic-charts-by-the-fed-using-r-and-plotly/" }, { "title": "Steal This Blog!", "href": "http://www.gettinggeneticsdone.com/2011/06/steal-this-blog.html" }, { "title": "U-boats in WW-II", "href": "http://wiekvoet.blogspot.com/2015/05/u-boats-in-ww-ii.html" }, { "title": "Sourcing Code from GitHub", "href": "http://christophergandrud.blogspot.com/2012/07/sourcing-code-from-github.html" }, { "title": "Data Analysis Tools", "href": "http://www.dataperspective.info/2014/01/data-analysis-tools.html" }, { "title": "Another Great Google Summer of Code 2012 R Project", "href": "http://timelyportfolio.blogspot.com/2012/08/another-great-google-summer-of-code.html" }, { "title": "SparkR: Distributed data frames with Spark and R", "href": "http://blog.revolutionanalytics.com/2015/06/sparkr-announcement.html" }, { "title": "a brief on naked statistics", "href": "https://xianblog.wordpress.com/2013/04/03/a-brief-on-naked-statistics/" }, { "title": "Structural “Arbitrage”: Trading the Equity Curve", "href": "https://quantstrattrader.wordpress.com/2014/10/15/structural-arbitrage-trading-the-equity-curve/" }, { "title": "Course: Statistical Practice in Epidemiology with R", "href": "https://martynplummer.wordpress.com/2013/02/25/course-statistical-practice-in-epidemiology-with-r-2/" }, { "title": "Forest Plot (with Horizontal Bands)", "href": "https://designdatadecisions.wordpress.com/2016/07/02/forest-plot-with-horizontal-bands/" }, { "title": "The Relationship between Vectorized and Devectorized Code", "href": "http://www.johnmyleswhite.com/notebook/2013/12/22/the-relationship-between-vectorized-and-devectorized-code/" }, { "title": "Ryan Peek on using xts and ggplot for time-series data", "href": "http://www.noamross.net/blog/2013/2/6/xtsmarkdown.html" } ]
unsmooth.region.plot = function( plot.list, plot.chr, plot.start, plot.stop, plot.column = "R", plot.points = TRUE, plot.lines = TRUE, gene.names = TRUE, annot.colors = c("black", "red", "green", "blue", "cyan"), vert.pad = .05, num.ticks = 5, ylim.low = NULL, ylim.high = NULL, pch.vec = NULL, lty.vec = NULL, lwd.vec = NULL, plot.legend = TRUE, legend.loc = "topright" ) { common.list.genes = names(which(table(unlist(lapply(plot.list, rownames))) == length(plot.list))) for (i in (1:length(plot.list))) { plot.list[[i]] = plot.list[[i]][common.list.genes,] } chr = as.numeric(plot.list[[1]][,"chr"]) pos = as.numeric(plot.list[[1]][,"pos"]) chr.pos.perm = order(chr, pos) for (i in (1:length(plot.list))) { plot.list[[i]] = plot.list[[i]][chr.pos.perm,] } chr.ind = as.numeric(as.numeric(plot.list[[1]][,"chr"]) == plot.chr) start.ind = as.numeric(as.numeric(plot.list[[1]][,"pos"]) >= plot.start) stop.ind = as.numeric(as.numeric(plot.list[[1]][,"pos"]) <= plot.stop) plot.rows = which(chr.ind * start.ind * stop.ind == 1) for (i in (1:length(plot.list))) { plot.list[[i]] = plot.list[[i]][plot.rows,] } plot.vals = c() for (i in (1:length(plot.list))) { plot.vals = c(plot.vals, as.numeric(plot.list[[i]][,plot.column])) } if (!is.null(ylim.low)) { ylim.low = min(ylim.low, min(plot.vals)) - vert.pad } else ylim.low = min(plot.vals) - vert.pad if (!is.null(ylim.high)) { ylim.high = max(ylim.high, max(plot.vals)) + vert.pad } else ylim.high = max(plot.vals) + vert.pad if (is.null(pch.vec)) { pch.vec = rep(1, length(plot.list)) } plot(as.numeric(plot.list[[1]][,"pos"])/1e6, as.numeric(plot.list[[1]][,plot.column]), axes = F, xlab = "", ylab = "", main = "", xlim = c(plot.start, plot.stop)/1e6, ylim = c(ylim.low, ylim.high), pch = pch.vec[1], col = annot.colors[1]) plot.matrix = matrix(NA, nrow(plot.list[[i]]), length(plot.list)) plot.matrix[,1] = as.numeric(plot.list[[1]][,plot.column]) if (plot.points && (length(plot.list) >= 2)) { for (i in (2:length(plot.list))) { points(as.numeric(plot.list[[i]][,"pos"])/1e6, as.numeric(plot.list[[i]][,plot.column]), pch = pch.vec[i], col = annot.colors[i]) plot.matrix[,i] = as.numeric(plot.list[[i]][,plot.column]) } } if (is.null(lty.vec)) { lty.vec = rep(1, length(plot.list)) } if (is.null(lwd.vec)) { lwd.vec = rep(1, length(plot.list)) } if (plot.lines) { for (i in (1:length(plot.list))) { lines(as.numeric(plot.list[[i]][,"pos"])/1e6, as.numeric(plot.list[[i]][,plot.column]), col = annot.colors[i], lty = lty.vec[i], lwd = lwd.vec[i]) } } if (gene.names) { text(rownames(plot.list[[1]]), x = as.numeric(plot.list[[1]][,"pos"])/1e6, y = apply(plot.matrix, 1, max, na.rm = T), pos = 3) } plot.ticks = signif(seq(plot.start/1e6, plot.stop/1e6, by = (plot.stop/1e6 - plot.start/1e6)/(num.ticks - 1)), 3) axis(side = 1, at = plot.ticks, labels = plot.ticks, cex = 1) axis(side = 2, cex = 1) if (plot.column == "R^2") { yaxis.label = expression(rho^2) } else yaxis.label = expression(rho) mtext(side = 1, text = paste(c("chr", plot.chr, " Position (Mb)"), collapse = ""), line = 2.5) mtext(side = 2, text = yaxis.label, line = 2.5) if (plot.legend) { legend(legend.loc, lwd = rep(3, length(plot.list)), col = annot.colors[1:length(plot.list)], names(plot.list), bty = "n", inset = .05, pch = pch.vec, lty = lty.vec) } }
randomNeighborShort <- function(currentModelObject, numChanges, allItems, data, bifactor = FALSE, init.model, lavaan.model.specs) { mapply( assign, c("factors", "itemsPerFactor"), syntaxExtraction(initialModelSyntaxFile = init.model, items = allItems), MoreArgs = list(envir = environment()) ) mapply( assign, names(lavaan.model.specs), lavaan.model.specs, MoreArgs = list(envir = environment()) ) internalModelObject <- stringr::str_split(currentModelObject$model.syntax, pattern = "\n", simplify = T) mapply( assign, c("factors", "currentItems"), syntaxExtraction(initialModelSyntaxFile = internalModelObject, items = allItems), MoreArgs = list(envir = environment()) ) replacePattern <- paste0("\\b", paste0(allItems, collapse = "\\b|\\b" ), "\\b") replacementItemPool <- c() for (i in 1:length(factors)) { if (class(allItems) == "list") { replacementItemPool[[i]] <- allItems[[i]][!(allItems[[i]] %in% currentItems[[i]])] } else { replacementItemPool[[i]] <- allItems[!(allItems %in% currentItems[[i]])] } } changingItems <- c() replacementItem <- c() for (i in 1:numChanges) { if (bifactor) { currentFactor <- sample(1:(length(factors) - 1), 1) } else { currentFactor <- sample(1:length(factors), 1) } changingItemTemp <- c() changingItemTemp <- sample(currentItems[[currentFactor]], 1) while (changingItemTemp %in% changingItems || length(changingItemTemp %in% changingItems) == 0) { changingItemTemp <- sample(currentItems[[currentFactor]], 1) } changingItems <- c(changingItems, changingItemTemp) tempReplacementItems <- sample(replacementItemPool[[currentFactor]], 1) while (tempReplacementItems %in% replacementItem) { tempReplacementItems <- sample(replacementItemPool[[currentFactor]], 1) } replacementItem <- c(replacementItem, tempReplacementItems) } for (i in 1:length(factors)) { for (j in 1:numChanges) { currentItems[[i]] <- gsub( pattern = paste0(changingItems[j], "\\b"), replacement = replacementItem[j], x = currentItems[[i]] ) } } if (bifactor == TRUE) { currentItems[[length(itemsPerFactor)]] <- unlist(currentItems[1:(length(itemsPerFactor) - 1)]) } newModelSyntax <- as.vector( stringr::str_split(currentModelObject$model.syntax, "\n", simplify = T) ) for (i in 1:length(factors)) { newModelSyntax[i] <- paste( factors[i], "=~", paste(currentItems[[i]], collapse = " + ") ) } newModelSyntax <- stringr::str_flatten(newModelSyntax, collapse = "\n") randomNeighborModel <- modelWarningCheck( lavaan::lavaan( model = newModelSyntax, data = data, model.type = model.type, auto.var = auto.var, ordered = ordered, estimator = estimator, int.ov.free = int.ov.free, int.lv.free = int.lv.free, auto.fix.first = auto.fix.first, std.lv = std.lv, auto.fix.single = auto.fix.single, auto.cov.lv.x = auto.cov.lv.x, auto.th = auto.th, auto.delta = auto.delta, auto.cov.y = auto.cov.y ) ) randomNeighborModel$model.syntax = newModelSyntax return(randomNeighborModel) } selectionFunction <- function(currentModelObject = currentModel, randomNeighborModel, currentTemp, maximize, fitStatistic, consecutive) { if (length(randomNeighborModel[[2]]) > 0 | length(randomNeighborModel[[2]]) > 0) { return(currentModelObject) } if (is.null(currentModelObject[[1]])) { return(randomNeighborModel) } else { probability = exp(-(goal(randomNeighborModel[[1]], fitStatistic, maximize) - goal(currentModelObject[[1]], fitStatistic, maximize)) / currentTemp) } if (probability > stats::runif(1)) { newModel = randomNeighborModel } else { newModel = currentModelObject } } goal <- function(x, fitStatistic = 'cfi', maximize) { if (class(x) == "lavaan" & is.character(fitStatistic) & length(fitStatistic) == 1) { energy <- fitWarningCheck(lavaan::fitMeasures(x, fit.measures = fitStatistic), maximize) if (maximize == TRUE) { return(-energy) } else { return(energy) } } else { if (class(x) == "NULL") { if (maximize == TRUE) { return(-Inf) } else { return(Inf) } } } } consecutiveRestart <- function(maxConsecutiveSelection = 25, consecutive) { if (consecutive == maxConsecutiveSelection) { currentModel = bestModel consecutive = 0 } } linearTemperature <- function(currentStep, maxSteps) { currentTemp <- (maxSteps - (currentStep)) / maxSteps } quadraticTemperature <- function(currentStep, maxSteps) { currentTemp <- ((maxSteps - (currentStep)) / maxSteps) ^ 2 } logisticTemperature <- function(currentStep, maxSteps) { x = 1:maxSteps x.new = scale(x, center = T, scale = maxSteps / 12) currentTemp <- 1 / (1 + exp((x.new[(currentStep + 1)]))) } checkModels <- function(currentModel, fitStatistic, maximize = maximize, bestFit = bestFit, bestModel) { if (class(currentModel) == "list") { currentSyntax <- currentModel$model.syntax currentModel <- currentModel[[1]] } if (is.null(currentModel)) { return(bestModel) } currentFit = fitWarningCheck( lavaan::fitmeasures(object = currentModel, fit.measures = fitStatistic), maximize ) if (maximize == TRUE) { if (currentFit > bestFit) { bestModel = list() bestModel$bestModel = currentModel bestModel$bestSyntax = currentSyntax } else { bestModel = bestModel } } else { if (currentFit < bestFit) { bestModel = list() bestModel$bestModel = currentModel bestModel$bestSyntax = currentSyntax } else { if (currentFit < bestFit) { bestModel = currentModel } else { bestModel = bestModel } } } return(bestModel) } modelWarningCheck <- function(expr) { warn <- err <- c() value <- withCallingHandlers( tryCatch( expr, error = function(e) { err <<- append(err, regmatches(paste(e), gregexpr("ERROR: [A-z ]{1,}", paste(e)))) NULL } ), warning = function(w) { warn <<- append(warn, regmatches(paste(w), gregexpr("WARNING: [A-z ]{1,}", paste(w)))) invokeRestart("muffleWarning") } ) list( 'lavaan.output' = value, 'warnings' <- as.character(unlist(warn)), 'errors' <- as.character(unlist(err)) ) } syntaxExtraction = function(initialModelSyntaxFile, items) { factors = unique(lavaan::lavaanify(initialModelSyntaxFile)[lavaan::lavaanify(initialModelSyntaxFile)$op == "=~", 'lhs']) vectorModelSyntax = stringr::str_split(string = initialModelSyntaxFile, pattern = '\\n', simplify = TRUE) factorSyntax = c() itemSyntax = c() for (i in 1:length(factors)) { chosenFactorLocation = c(1:length(vectorModelSyntax))[grepl(x = vectorModelSyntax, pattern = paste0(factors[i], "[ ]{0,}=~ "))] factorSyntax[i] = vectorModelSyntax[chosenFactorLocation] itemSyntax[i] <- gsub( pattern = paste(factors[i], "=~ "), replacement = "", x = factorSyntax[i] ) } itemsPerFactor = stringr::str_extract_all(string = itemSyntax, pattern = paste0("(\\b", paste0( paste0(unlist(items), collapse = "\\b)|(\\b"), "\\b)" ))) return(list('factors' = factors, 'itemsPerFactor' = itemsPerFactor)) } modelWarningCheck <- function(expr) { warn <- err <- c() value <- withCallingHandlers(tryCatch(expr, error = function(e) { err <<- append(err, regmatches(paste(e), gregexpr("ERROR: [A-z ]{1,}", paste(e)))) NULL }), warning = function(w) { warn <<- append(warn, regmatches(paste(w), gregexpr("WARNING: [A-z ]{1,}", paste(w)))) invokeRestart("muffleWarning") }) list(lavaan.output = value, warnings <- as.character(unlist(warn)), errors <- as.character(unlist(err))) } fitWarningCheck <- function(expr, maximize) { value <- withCallingHandlers(tryCatch(expr, error = function(e) { if (maximize == T) { return(0) } else { return(Inf) } invokeRestart("muffleWarning") } ) ) return(value) } checkModelSpecs <- function( x ) { requiredElements <- c('model.type', 'auto.var', 'estimator', 'ordered', 'int.ov.free', 'int.lv.free', 'auto.fix.first', 'auto.fix.single', 'auto.cov.lv.x', 'auto.th', 'auto.delta', 'auto.cov.y', 'std.lv') missingSpecs <- requiredElements[ which( !requiredElements %in% names(x) ) ] if (length(missingSpecs) > 0) { errorMessage <- paste0("The following elements of lavaan.model.specs have not been specified:\n\n", paste(missingSpecs, collapse = "\n"), "\n\nPlease include the proper specifications for these elements, or use the default values provided.") stop(errorMessage) } } fitmeasuresCheck <- function( x ) { validMeasures <- c( "npar", "fmin", "chisq", "df", "pvalue", "baseline.chisq", "baseline.df", "baseline.pvalue", "cfi", "tli", "nnfi", "rfi", "nfi", "pnfi", "ifi", "rni", "logl", "unrestricted.logl", "aic", "bic", "ntotal", "bic2", "rmsea", "rmsea.ci.lower", "rmsea.ci.upper", "rmsea.pvalue", "rmr", "rmr_nomean", "srmr", "srmr_bentler", "srmr_bentler_nomean", "crmr", "crmr_nomean", "srmr_mplus", "srmr_mplus_nomean", "cn_05", "cn_01", "gfi", "agfi", "pgfi", "mfi", "ecvi", "chisq.scaled", "df.scaled", "pvalue.scaled", "chisq.scaling.factor", "baseline.chisq.scaled", "baseline.df.scaled", "baseline.pvalue.scaled", "baseline.chisq.scaling.factor", "cfi.scaled", "tli.scaled", "cfi.robust", "tli.robust", "nnfi.scaled", "nnfi.robust", "rfi.scaled", "nfi.scaled", "ifi.scaled", "rni.scaled", "rni.robust", "rmsea.scaled", "rmsea.ci.lower.scaled", "rmsea.ci.upper.scaled", "rmsea.pvalue.scaled", "rmsea.robust", "rmsea.ci.lower.robust", "rmsea.ci.upper.robust", "rmsea.pvalue.robust" ) invalidMeasures <- x[ which( !x %in% validMeasures ) ] if (length(invalidMeasures) > 0) { errorMessage <- paste0("The following elements of fit.indices or fitStatistics are not valid fit measures provided by the lavaan::fitmeasures function:\n\n", paste(invalidMeasures, collapse = "\n"), "\n\nPlease check the output of this function for proper spelling and capitalization of the fit measure(s) you are interested in.") stop(errorMessage) } } fitStatTestCheck <- function(measures, test) { tempEnv <- new.env() mapply( assign, measures, 0, MoreArgs=list(envir = tempEnv)) checkIfEval <- tryCatch( expr = eval(parse(text=test), envir = tempEnv), error = function(e) { stop("There was a problem with the fit.statistics.test provided. It cannot be evaluated properly. Please read the function documentation to see how to properly specify a test.") } ) if (!is.character(test)) { stop("There is a problem with the fit.statistics.test provided. The fit.statistics.test was given as a logical, not a character. Please read the function documentation to see how to properly specify a test. ") } }
detindex <- function(storage, mini=c("B","D","M"), pmini=1, verbose=TRUE) { MC <- match.call() if(verbose) { print("", quote = FALSE) print("Running detindex", quote = FALSE) print("", quote = FALSE) print(date(), quote = FALSE) print("", quote = FALSE) print("Call:", quote = FALSE) print(MC) print("", quote = FALSE) } if(!file.exists(storage)) stop("Incorrect path to storage directory") out<- dir(path=storage) out <- out[out != "max.created.txt"] out <- sort(as.numeric(out)) ndirs <- length(out) if(mini=="B" | mini=="D"){ detguide <- parseguide <- parseguidesym <- rep(0,ndirs) subdir <- paste(storage,out,sep="/") for(i in 1:ndirs){ filenames <- dir(path=subdir[i]) if(any(filenames=="detguide.txt")) detguide[i] <- 1 if(any(filenames=="parseguide.txt")) parseguide[i] <- 1 if(any(filenames=="parseguidesym.txt"))parseguidesym[i] <- 1 } index=data.frame(p=out, detguide, parseguide, parseguidesym) } if(mini=="B" | mini=="M"){ storage <- paste(storage,pmini, sep="/") if(!file.exists(storage)) stop("No storage for this value of pmini") out<- dir(path=storage) ndirs <- length(out) minidetguide <- parseguide <- parseguidesym <- rep(0,ndirs) subdir <- paste(storage,out,sep="/") for(i in 1:ndirs){ filenames <- dir(path=subdir[i]) if(any(filenames=="minidetguide.txt")) minidetguide[i] <- 1 if(any(filenames=="parseguide.htm")) parseguide[i] <- 1 if(any(filenames=="parseguidesym.htm"))parseguidesym[i] <- 1 } index2=data.frame(R1Cs=out, minidetguide, parseguide, parseguidesym) } if(mini=="D")outlast <- list(Detguides=index, Call=MC) if(mini=="M")outlast <- list(Minidetguides=index2, Call=MC) if(mini=="B")outlast <- list(Detguides=index, Minidetguides=index2, Call=MC) if(verbose) { print("", quote = FALSE) print("Finished running detindex", quote = FALSE) print("", quote = FALSE) print(date(), quote = FALSE) print("", quote = FALSE) print("1 indicates file is present, 0 not present", quote=FALSE) } outlast }
multi_selectOut <- function(data, plot, out="plot", draw="FALSE") { if(toupper(out) == "DATA") { return(data) } else if(toupper(out) == "PLOT" & isTRUE(draw)) { return(grid::grid.draw(plot)) } else if(toupper(out) == "PLOT" & !isTRUE(draw)) { return(plot) } else if(toupper(out) == "GROB" & isTRUE(draw)) { return(plot) } else if(toupper(out) == "GROB" & !isTRUE(draw)) { return(ggplot2::ggplotGrob(plot)) } else { warning("Did not recognize input to out...") if(isTRUE(draw)) { return(grid::grid.draw(plot)) } else { return(plot) } } }
"%<c-%" <- function(x, value) { name <- substitute(x) if (!is.name(name)) stop("Left-hand side must be a name") env <- parent.frame() assign(as.character(name), value, env) lockBinding(name, env) invisible(value) }
remove_clicks <- function(clicksDF, targetTimes, nRemove) { for (remove_it in 1:nRemove) { distanceToNext <- diff(clicksDF$time) removeRow <- order(distanceToNext)[1] if (removeRow == 1) {removeRow <- 2} clicksDF <- rbind(clicksDF[1:(removeRow-1), ], clicksDF[(removeRow+1):nrow(clicksDF), ] ) } return(clicksDF) }
irlsl1reg <- function( G,d,L,alpha,maxiter=100,tolx=1.0e-4,tolr=1.0e-6) { GTG=t(G) %*% G GTd=t(G) %*% d m= Ainv( (2*GTG+alpha*(t(L) %*%L)) , (2*GTd) ) iter=1 while(iter < maxiter) { iter=iter+1 absLm=abs(L %*% m) absLm[absLm<tolr]=tolr R=diag(1/as.vector(absLm) ) mold=m KADD = alpha * t(L) %*% R %*% L m = Ainv( (2*GTG + KADD ) , (2*GTd) ) if(Vnorm(m-mold)/(1+Vnorm(mold)) < tolx) { mreg=m return(mreg) } } mreg=m return(mreg) }
listCol_w <- function(inDT, listcol, drop = TRUE, fill = NA_character_) { if (!is.data.table(inDT)) inDT <- as.data.table(inDT) else inDT <- copy(inDT) LC <- Names(inDT, listcol) reps <- vapply(inDT[[listcol]], length, 1L) Nam <- paste(LC, .pad(sequence(max(reps))), sep = "_fl_") M <- matrix(fill, nrow = nrow(inDT), ncol = max(reps), dimnames = list(NULL, Nam)) M[cbind(rep(sequence(nrow(inDT)), reps), sequence(reps))] <- unlist( inDT[[listcol]], use.names = FALSE) out <- cbind(inDT, M) if (isTRUE(drop)) { out[, (LC) := NULL] } out[] } NULL
resampling.model <- function(model,data,k,console=FALSE) { modelo<-model parte<-strsplit(model,"~")[[1]] model<-as.formula(model) ecuacion<-lm(model,data=data) xx<-data.frame(anova(ecuacion),NA) yy<-ecuacion$model[[1]] fc<-xx[,4] names(xx)<-c("Df","Sum Sq","Mean Sq","F value","Pr(>F)","Resampling") m<-nrow(data) gk<-nrow(xx)-1 f<-rep(0,gk) cuenta <- rep(0,gk) model <- paste("y","~",parte[2]) model<-as.formula(model) for(i in 1:k){ y<-sample(yy,m) resample<-lm(model,data=data) for (j in 1:gk){ f[j]<-anova(resample)[j,4] if(f[j] >= fc[j])cuenta[j]<-cuenta[j]+1 } } for( j in 1:gk){ xx[j,6]<-cuenta[j]/k } if(console){ cat("\nResampling of the experiments\n") cat(rep("-",14),"\n") cat("Proposed model:",modelo,"\n") cat("---\n") cat("Resampling of the analysis of variancia for the proposed model\n") cat("Determination of the P-Value by Resampling\n") cat("Samples:",k,"\n\n") xx<-as.matrix(xx) print(xx,na.print="") cat("---\n\n") } out<-list(model=resample, solution=xx,acum=cuenta,samples=k) invisible(out) }
sim_gen <- function(simSetup, generator) { sim_setup(simSetup, new("sim_fun", order = 1, call = match.call(), generator)) } sim_gen_generic <- function(simSetup, ...) { sim_gen(simSetup, gen_generic(...)) }
for (x in 1) { x for (x in k ) 3 } for (x in 1) { x for (x in k ) 3 }
aplsm<-function(Niter,Y.i, Y.ia,D, type){ M=ncol(Y.ia) N=ncol(Y.i) d <- dist(t(Y.ia)) fit <- cmdscale(d,eig=TRUE, k=D) Z.a= fit$points ZsMat=list("Z.i" = lsm(Y.i,D=D)$lsmEZ,"Z.a" = Z.a) if(type == "DD"){ lsmhMat<-DDlsmh(Niter,Y.i,Y.ia,M,N,D,ZsMat) } if(type == "DV"){ lsmhMat<-DVlsmh(Niter,Y.i,Y.ia,M,N,D,ZsMat) } if(type == "VV"){ lsmhMat<-VVlsmh(Niter,Y.i,Y.ia,M,N,D,ZsMat) } return(lsmhMat) }
frommlmm_toebic<-function(XX, res.mlmm){ n.step<-length(res.mlmm) id<-grep("selec_",names(res.mlmm[[n.step]]) ) names.snp<-names(res.mlmm[[n.step]])[id] names.snp<-unlist(sapply(names.snp,function(x){ unlist(strsplit(x,"selec_"))[2] })) if(n.step>2) { id<-which( res.mlmm[[n.step]][-(1:(n.step-2))]==min( res.mlmm[[n.step]][-(1:(n.step-2))] ,na.rm=TRUE) ) last.snp<-names( res.mlmm[[n.step]])[-(1:(n.step-2))][id] } else { id<-which(res.mlmm[[n.step]]==min( res.mlmm[[n.step]],na.rm=TRUE ) ) last.snp<-names( res.mlmm[[n.step]])[id] } names.snp<-c(names.snp,last.snp) nb.effet<-length(XX) selec_XX<-list() for(ki in 1:nb.effet){ selec_XX[[ki]]<-matrix(unlist(lapply(names.snp,function(xj){ XX[[ki]][,which(colnames(XX[[ki]])==xj)] })),ncol=length(names.snp),byrow=FALSE) } for(ki in 1:nb.effet){ colnames(selec_XX[[ki]])<-names.snp rownames(selec_XX[[ki]])<-rownames(XX[[1]]) } res<-selec_XX }
`update.elrm` <- function(object,iter,burnIn=0,alpha=0.05,...) { r=object$r; if(iter %% 1 != 0) { stop("'iter' must be an integer"); } if(iter < 0) { stop("'iter' must be greater than or equal to 0"); } if(burnIn %% 1 != 0) { stop("'burnIn' must be an integer"); } if(iter+nrow(object$mc) < burnIn + 1000) { stop("'burnIn' must be atleast 1000 iterations smaller than the total number of Monte Carlo iterations"); } dataset = object$dataset; formula = as.call(object$call[[1]])[["formula"]]; zCols = as.call(object$call[[1]])[["interest"]]; info = getDesignMatrix(formula,zCols,dataset=dataset); design.matrix = info$design.matrix; yCol = info$yCol; mCol = info$mCol; zCols = info$zCols; wCols = info$wCols; if((r %% 2) != 0) { stop("'r' must be an even number"); } if(r > length(as.vector(design.matrix[,yCol]))) { msg = paste("'r' must be smaller than or equal to",length(as.vector(design.matrix[,yCol])),"(length of the response vector)"); stop(msg); } out.filename = paste("elrmout",round(runif(1,0,10000),0),".txt",sep=""); tempdata.filename = paste("elrmtempdata",round(runif(1,0,10000),0),".txt",sep=""); write.table(design.matrix,tempdata.filename,quote=FALSE,row.names=FALSE,col.names=FALSE); Z.matrix = matrix(nrow = nrow(design.matrix), ncol = length(zCols)); Z.matrix = as.matrix(design.matrix[,zCols]); observed.response = as.matrix(design.matrix[,yCol]); S.matrix = NULL; message("Generating the Markov chain ..."); t1 = format(Sys.time(),""); last.sample = object$last; if(iter > 0) { sample.size = max(floor(iter*0.05),1); k = 0; while(k < iter) { progress((k/iter)*100); Sys.sleep(0.10); design.matrix[,yCol]=last.sample; write.table(design.matrix,tempdata.filename,quote=FALSE,row.names=FALSE,col.names=FALSE); .C("MCMC", as.integer(yCol), as.integer(mCol), as.integer(wCols), as.integer(length(wCols)), as.integer(zCols), as.integer(length(zCols)), as.integer(r), as.character(tempdata.filename), as.character(out.filename), as.integer(min(sample.size,iter-k)), as.integer(0), PACKAGE="elrm"); mc = matrix(scan(out.filename,what=numeric(),skip=0,n=min(sample.size,iter-k)*nrow(object$dataset),sep="\t",quiet=T),nrow=min(sample.size,iter-k),ncol=nrow(object$dataset),byrow=T); S.temp = mc %*% Z.matrix k = k + sample.size; S.matrix = rbind(S.matrix,S.temp); last.sample = mc[nrow(mc),]; } last = last.sample; S.matrix = round(S.matrix,6); progress((k/iter)*100); Sys.sleep(0.10); message('\n'); } unlink(tempdata.filename); unlink(out.filename); t2 = format(Sys.time(),""); dif1 = difftime(t2,t1,units="auto"); message(paste("Generation of the Markov Chain required", round(dif1,4), attr(dif1,"units"))); message("Conducting inference ..."); t3 = format(Sys.time(),""); S.observed = round(as.vector(t(Z.matrix)%*%observed.response,mode='numeric'),6); names(S.observed) = names(design.matrix)[zCols]; S.matrix = matrix(rbind(as.matrix(object$mc),S.matrix),ncol=ncol(object$mc)); S.begin = as.matrix(S.matrix[0:burnIn,]); if(burnIn == 1) { S.begin = as.matrix(t(S.begin)); } S.matrix = as.matrix(S.matrix[(burnIn+1):nrow(S.matrix),]); marginal = getMarginalInf(S.matrix, S.observed, alpha); if(length(zCols) > 1) { joint = getJointInf(S.matrix, S.observed); t4 = format(Sys.time(),""); dif2 = difftime(t4,t3,units="auto"); message(paste("Inference required", round(dif2,4), attr(dif2,"units"))); coeffs = as.vector(c(NA,marginal$estimate),mode='numeric'); names(coeffs) = c("joint",names(marginal$estimate)); pvals = as.vector(c(joint$pvalue,marginal$pvalue),mode='numeric'); pvals.se = as.vector(c(joint$pvalue.se,marginal$pvalue.se),mode='numeric'); names(pvals) = names(coeffs); names(pvals.se) = names(coeffs); marginal$distribution[["joint"]] = joint$distribution; sizes = c(joint$mc.size,marginal$mc.size); names(sizes) = c("joint",names(marginal$mc.size)); S.matrix = data.frame(rbind(S.begin,S.matrix)); colnames(S.matrix) = names(design.matrix)[zCols]; object$coeffs=coeffs; object$coeffs.ci=marginal$estimate.ci; object$p.values=pvals; object$p.values.se=pvals.se; object$mc=mcmc(S.matrix); object$mc.size=sizes; object$distribution=marginal$distribution; object$last = last.sample; object$ci.level = (1-alpha)*100; object$call.history = c(object$call.history, match.call()); } else { t4 = format(Sys.time(),""); dif2 = difftime(t4,t3,units="auto"); message(paste("Inference required", round(dif2,4), attr(dif2,"units"))); S.matrix = data.frame(rbind(S.begin,S.matrix)); colnames(S.matrix) = names(design.matrix)[zCols]; object$coeffs = marginal$estimate; object$coeffs.ci=marginal$estimate.ci; object$p.values=marginal$pvalue; object$p.values.se=marginal$pvalue.se object$mc=mcmc(S.matrix); object$mc.size=marginal$mc.size object$distribution=marginal$distribution; object$last = last.sample; object$ci.level = (1-alpha)*100; object$call.history = c(object$call.history, match.call()); } return(object); }
siarelicit <- function(siardata) { if(siardata$SHOULDRUN==FALSE || siardata$GRAPHSONLY ==TRUE) { cat("You must load in some data first (via option 1) in order to use this feature of the program. \n") cat("Press <Enter> to continue") readline() invisible() return(siardata) } cat("This function allows you to elicit parameters for the Dirichlet \n") cat("distribution based on estimates for the mean proportions and the \n") cat("standard deviations from one of them. \n\n") sourcenames <- as.character(siardata$sources[,1]) cat(paste("There are",length(sourcenames),"current sources. They are: \n")) cat(sourcenames,"\n \n") cat("===========================================================================\n") cat("Mean proportion estimates. \n") cat("===========================================================================\n\n") cat("Please first enter your mean estimate of the proportions of each of these \n") cat(" sources separated by a space. (Note: these should add up to 1) \n") propsum <- 0 while(propsum!=1) { meanprops <- as.numeric(scan(what="list",nlines=1,quiet=TRUE,sep=" ")) propsum <- sum(meanprops) if(length(meanprops)!=length(sourcenames)) { cat(paste("Only",length(sourcenames),"allowed. \n")) propsum <- 0 } if(propsum!=1) cat("Does not sum to 1, try again. \n") } cat("Thank you. \n \n") cat("===========================================================================\n") cat("Standard deviation estimate. \n") cat("===========================================================================\n\n") qu <- "Which source would you like to enter the standard deviation for:" sdans <- menu(sourcenames,title = qu) cat(paste("Please now enter the standard deviation for source:",sourcenames[sdans],"\n")) badsd <- TRUE while(badsd==TRUE) { sourcesd <- as.numeric(scan(what="",nlines=1,quiet=TRUE)) if(sourcesd < 0) { cat("Bad standard deviation entered. Try again. \n") } else if((meanprops[sdans]*(1-meanprops[sdans])/sourcesd^2)<1) { cat("Standard deviation does not satisfy Dirichlet constraints. Try again. \n") } else { badsd <- FALSE } } cat("Thank you. \n \n") Q <- (meanprops[sdans]*(1-meanprops[sdans])/sourcesd^2)-1 alphapars <- meanprops*Q cat("Dirichlet prior parameters are: \n") cat(alphapars) cat("\n") cat("Please enter these as arguments in the siarmcmcdirichletv4 function. \n") }
unite. <- function(.df, col = "new_col", ..., sep = "_", remove = TRUE, na.rm = FALSE) { UseMethod("unite.") } unite..tidytable <- function(.df, col = "new_col", ..., sep = "_", remove = TRUE, na.rm = FALSE) { vec_assert(sep, character(), 1) vec_assert(remove, logical(), 1) vec_assert(na.rm, logical(), 1) dots <- enquos(...) if (length(dots) == 0) { unite_cols <- names(.df) } else { unite_cols <- tidyselect_names(.df, ...) } if (na.rm) { cols <- unname(map.(.df[, ..unite_cols], as.character)) rows <- transpose(cols) .united <- map_chr.(rows, ~ paste0(.x[!is.na(.x)], collapse = sep)) .df <- mutate.(.df, !!col := .united) } else { .df <- mutate.(.df, !!col := paste(!!!syms(unite_cols), sep = sep)) } if (remove) .df <- .df[, -..unite_cols] .df } unite..data.frame <- function(.df, col = "new_col", ..., sep = "_", remove = TRUE, na.rm = FALSE) { .df <- as_tidytable(.df) unite.(.df, col = col, ..., sep = sep, remove = remove, na.rm = na.rm) } globalVariables("..unite_cols")