code
stringlengths 1
13.8M
|
---|
library(hdi)
data(riboflavin)
x <- riboflavin[,-1]
y <- riboflavin[,1]
dim(x)
length(y)
x.use <- x[,1:200]
fit.ridge <- ridge.proj(x = x.use, y = y, betainit = "scaled lasso")
fit.ridge1 <- ridge.proj(x = x.use + 10^-16, y = y, betainit = "scaled lasso")
stopifnot(all.equal(fit.ridge$pval, fit.ridge1$pval))
fit.ridge2 <- ridge.proj(x = 2 + 4 * x.use, y = y, betainit = "scaled lasso")
stopifnot(all.equal(fit.ridge$pval, fit.ridge2$pval))
stopifnot(all.equal(max(abs(range(fit.ridge$bhat / fit.ridge2$bhat - 4))), 0))
ci.ridge <- confint(fit.ridge, level = 0.95)
ci.ridge2 <- confint(fit.ridge2, level = 0.95)
stopifnot(all.equal(ci.ridge, ci.ridge2 * 4)) |
dZn <- function(x, summands = NULL) {
if (!is.numeric(summands)) {
if (x > 6) {
return(1)
} else if (x <= 0) {
return(0)
} else {
best_summands <- c(5, 9, 14, 18, 23, 27, 32)
summands <- best_summands[ceiling(x)]
}
}
if (x <= 0) return(0)
2 * pi * sqrt(pZn(x, summands = summands)) * sum((-1)^(0:summands) *
(2 * (0:summands) + 1)/x^3 * exp(-pi^2*(2*(0:summands)+1)^2/
(8*x^2)))
}
dZn <- Vectorize(dZn, "x")
pkolmogorov <- function(q, summands = ceiling(q * sqrt(72) + 3/2)) {
sqrt(2 * pi) * sapply(q, function(x) { if (x > 0) {
sum(exp(-(2 * (1:summands) - 1)^2 * pi^2/(8 * x^2)))/x
} else {
0
}})
}
pkolmogorov <- Vectorize(pkolmogorov, "q")
pdarling_erdos <- function(q) {
exp(-2 * exp(-q))
}
pdarling_erdos <- Vectorize(pdarling_erdos, "q")
pZn <- function(q, summands = NULL) {
if (!is.numeric(summands)) {
if (q > 6) {
return(1)
} else if (q <= 0) {
return(0)
} else {
best_summands <- c(5, 9, 14, 18, 23, 27, 32)
summands <- best_summands[ceiling(q)]
}
}
if (q > 100) return(1)
sapply(q, function(x) {(4/pi * sum((-1)^(0:summands)/(2*(0:summands) + 1) *
exp(-pi^2 * (2 * (0:summands) + 1)^2/
(8 * x^2))))^2})
}
pZn <- Vectorize(pZn, "q")
phidalgo_seo <- function(q) {
pdarling_erdos(q/2)
}
qdarling_erdos <- function(p) {
-log(log(1/sqrt(p)))
}
qdarling_erdos <- Vectorize(qdarling_erdos, "p")
qhidalgo_seo <- function(p) {
2 * qdarling_erdos(p)
}
qZn <- function(p, summands = 500, interval = c(0, 100),
tol = .Machine$double.eps, ...) {
if (p == 1) return(Inf)
if (p == 0) return(0)
if (p < 0 | p > 1) return(NaN)
objective <- function(q) {pZn(q, summands = summands) - p}
args <- list(...); args$tol <- tol; args$interval <- interval
args$f <- objective
res <- do.call(uniroot, args)
res$root
}
qZn <- Vectorize(qZn, "p")
qkolmogorov <- function(p, summands = 500, interval = c(0, 100),
tol = .Machine$double.eps, ...) {
if (p == 1) return(Inf)
if (p == 0) return(0)
if (p < 0 | p > 1) return(NaN)
objective <- function(q) {pkolmogorov(q, summands = summands) - p}
args <- list(...); args$tol <- tol; args$interval <- interval
args$f <- objective
res <- do.call(uniroot, args)
res$root
}
qkolmogorov <- Vectorize(qkolmogorov, "p")
sim_Zn <- function(size, kn, n = 500, gen_func = rnorm, args = NULL, sd = 1) {
Zn_realization <- function() {
if (!is.list(args)) {
dataset <- do.call(gen_func, list(n = n))
} else {
dataset <- do.call(gen_func, c(list(n = n), args))
}
max(sapply(floor(kn(n)):(n - floor(kn(n))), function(k)
abs(1/k*sum(dataset[1:k]) -
1/(n-k)*sum(dataset[(k+1):n]))
))
}
sqrt(kn(n))/sd * sapply(1:size, function(throwaway) Zn_realization())
}
sim_Vn <- function(size, n = 500, gen_func = rnorm, sd = 1, args = NULL) {
Vn_realization <- function() {
if (!is.list(args)) {
dataset <- do.call(gen_func, list(n = n))
} else {
dataset <- do.call(gen_func, c(list(n = n),
args))
}
dataset_mean <- mean(dataset)
max(sapply(1:n, function(k) abs(sum(dataset[1:k]) - k * dataset_mean)))
}
(1/(sd*sqrt(n))) * sapply(1:size, function(throwaway) Vn_realization())
}
sim_Vn_stat <- function(size, kn = function(n) {1}, tau = 0,
use_kernel_var = FALSE, kernel = "ba",
bandwidth = "and", n = 500, gen_func = rnorm,
args = NULL, parallel = FALSE) {
Vn_realization <- function() {
if (!is.list(args)) {
dataset <- do.call(gen_func, list(n = n))
} else {
dataset <- do.call(gen_func, c(list(n = n),
args))
}
stat_Vn(dataset, kn = kn, tau = tau, use_kernel_var = use_kernel_var,
kernel = kernel, bandwidth = bandwidth)
}
has_parallel <- requireNamespace("foreach", quietly = TRUE) &&
requireNamespace("doParallel", quietly = TRUE)
if (parallel & !has_parallel) {
warning("Either foreach or doParallel is not available; defaulting" %s%
"to non-parallel implementation")
parallel <- FALSE
} else {
times <- foreach::times
`%dopar%` <- foreach::`%dopar%`
}
if (parallel) {
foreach::foreach(i = 1:size, .combine = 'c') %dopar% Vn_realization()
} else {
sapply(1:size, function(throwaway) Vn_realization())
}
}
sim_Zn_stat <- function(size, kn = function(n) {floor(sqrt(n))},
use_kernel_var = FALSE, kernel = "ba",
bandwidth = "and", n = 500, gen_func = rnorm,
args = NULL, parallel = FALSE) {
Zn_realization <- function() {
if (!is.list(args)) {
dataset <- do.call(gen_func, list(n = n))
} else {
dataset <- do.call(gen_func, c(list(n = n),
args))
}
stat_Zn(dataset, kn, use_kernel_var = use_kernel_var,
kernel = kernel, bandwidth = bandwidth)
}
has_parallel <- requireNamespace("foreach", quietly = TRUE) &&
requireNamespace("doParallel", quietly = TRUE)
if (parallel & !has_parallel) {
warning("Either foreach or doParallel is not available; defaulting" %s%
"to non-parallel implementation")
parallel <- FALSE
} else {
times <- foreach::times
`%dopar%` <- foreach::`%dopar%`
}
if (parallel) {
foreach::foreach(i = 1:size, .combine = 'c') %dopar% Zn_realization()
} else {
sapply(1:size, function(throwaway) Zn_realization())
}
}
sim_de_stat <- function(size, a = log, b = log, use_kernel_var = FALSE,
kernel = "ba", bandwidth = "and", n = 500,
gen_func = rnorm, args = NULL, parallel = FALSE) {
de_realization <- function() {
if (!is.list(args)) {
dataset <- do.call(gen_func, list(n = n))
} else {
dataset <- do.call(gen_func, c(list(n = n), args))
}
stat_de(dataset, a = a, b = b, use_kernel_var = use_kernel_var,
kernel = kernel, bandwidth = bandwidth)
}
has_parallel <- requireNamespace("foreach", quietly = TRUE) &&
requireNamespace("doParallel", quietly = TRUE)
if (parallel & !has_parallel) {
warning("Either foreach or doParallel is not available; defaulting" %s%
"to non-parallel implementation")
parallel <- FALSE
} else {
times <- foreach::times
`%dopar%` <- foreach::`%dopar%`
}
if (parallel) {
foreach::foreach(i = 1:size, .combine = 'c') %dopar% de_realization()
} else {
sapply(1:size, function(throwaway) de_realization())
}
}
sim_hs_stat <- function(size, corr = TRUE, gen_func = rnorm, args = NULL,
n = 500, parallel = FALSE, use_kernel_var = FALSE,
kernel = "ba", bandwidth = "and") {
hs_realization <- function() {
if (!is.list(args)) {
dataset <- do.call(gen_func, list(n = n))
} else {
dataset <- do.call(gen_func, c(list(n = n),
args))
}
stat_hs(dataset, corr = corr)
}
has_parallel <- requireNamespace("foreach", quietly = TRUE) &&
requireNamespace("doParallel", quietly = TRUE)
if (parallel & !has_parallel) {
warning("Either foreach or doParallel is not available; defaulting" %s%
"to non-parallel implementation")
parallel <- FALSE
} else {
times <- foreach::times
`%dopar%` <- foreach::`%dopar%`
}
if (parallel) {
foreach::foreach(i = 1:size, .combine = 'c') %dopar% hs_realization()
} else {
sapply(1:size, function(throwaway) hs_realization())
}
}
rchangepoint <- function(n, changepoint = NULL, mean1 = 0, mean2 = 0,
dist = rnorm, meanparam = "mean", ...) {
if (is.null(changepoint)) {
changepoint <- ceiling(n/2)
} else if (!is.integer(changepoint)) {
changepoint <- round(changepoint)
}
distargs_pre <- list(...)
distargs_pre$n <- changepoint
distargs_pre[[meanparam]] <- mean1
distargs_post <- list(...)
distargs_post$n <- n - changepoint
distargs_post[[meanparam]] <- mean2
datavec1 <- do.call(dist, distargs_pre)
datavec2 <- do.call(dist, distargs_post)
c(datavec1, datavec2)
} |
compare_data_frame <- function(x, y, paths = c("x", "y"), opts = compare_opts()) {
if (!all_atomic(x) || !all_atomic(y)) {
return()
}
if (!same_cols(x, y)) {
return()
}
if (nrow(x) == 0 || nrow(y) == 0) {
return()
}
rows <- df_rows(x, y, paths = paths, tolerance = opts$tolerance)
if (is.null(rows)) {
return()
}
diff_rows(rows, paths = paths, max_diffs = opts$max_diffs)
}
diff_rows <- function(rows, paths = c("x", "y"), max_diffs = 10) {
diffs <- ses_shortest(rows$x, rows$y)
if (length(diffs) == 0) {
return(new_compare())
}
header <- paste0(" ", names(rows$header), cli::style_bold(rows$header))
format <- lapply(diffs, function(diff) {
path_label <- paste0(paths[[1]], " vs ", paths[[2]])
lines <- line_by_line(rows$x, rows$y, diff, max_diffs = max_diffs)
paste0(c(path_label, header, lines), collapse = "\n")
})
new_compare(unlist(format, recursive = FALSE))
}
df_rows <- function(x, y, paths = c("x", "y"), tolerance = NULL) {
x <- factor_to_char(x)
y <- factor_to_char(y)
if (nrow(x) == nrow(y)) {
is_equal <- function(x, y) {
if (is_numeric(x)) {
num_equal(x, y, tolerance = tolerance)
} else {
identical(x, y)
}
}
same <- vapply(seq_along(x), function(j) is_equal(x[[j]], y[[j]]), logical(1))
x <- x[!same]
y <- y[!same]
}
if (ncol(x) == 0) {
return()
}
printed_rows(as.data.frame(x), as.data.frame(y), row.names = FALSE, paths = paths)
}
printed_rows <- function(x, y, ..., paths = c("x", "y")) {
joint <- rbind(x, y)
if (!is.data.frame(joint)) {
rownames(joint) <- rep("", nrow(joint))
}
n <- nrow(joint) * ncol(joint)
lines <- utils::capture.output(print(joint, ..., width = 500, max = n))
row_idx <- c(seq_len(nrow(x)), seq_len(nrow(y)))
row_idx <- paste0(rep(paths, c(nrow(x), nrow(y))), "[", row_idx, ", ]")
names(lines) <- format(c("", row_idx), align = "right")
list(
header = lines[1],
x = lines[2:(nrow(x) + 1)],
y = lines[(nrow(x) + 2):length(lines)]
)
}
same_cols <- function(x, y) {
if (!identical(names(x), names(y))) {
return(FALSE)
}
for (j in seq_along(x)) {
if (!is.numeric(x[[j]]) || !is.numeric(y[[j]])) {
if (!identical(typeof(x[[j]]), typeof(y[[j]]))) {
return(FALSE)
}
}
if (!identical(attributes(x[[j]]), attributes(y[[j]]))) {
return(FALSE)
}
}
TRUE
}
factor_to_char <- function(x) {
is_factor <- vapply(x, is.factor, logical(1))
x[is_factor] <- lapply(x[is_factor], as.character)
x
}
unrowname <- function(x) {
row.names(x) <- NULL
x
}
all_atomic <- function(x) {
all(vapply(x, is_atomic, logical(1)))
} |
make.packages.html <-
function(lib.loc = .libPaths(), temp = FALSE, verbose = TRUE,
docdir = R.home("doc"))
{
add_lib_index <- function(libs)
{
cat('<div align="left">\n<ul>\n', file = out)
for (i in seq_along(libs)) {
nm <- libs[i]
if (nm == .Library) {
cat('<li>Contents of the <a href="
'standard</a> library</li>\n', sep = "", file = out)
} else {
cat('<li>Contents of <a href="
'</a></li>\n', sep = "", file = out)
}
}
cat("</ul>\n</div>\n", file = out)
}
WINDOWS <- .Platform$OS.type == "windows"
f.tg <- if (temp) {
dir.create(file.path(tempdir(), ".R/doc/html"), recursive = TRUE,
showWarnings = FALSE)
file.path(tempdir(), ".R/doc/html/packages.html")
} else file.path(docdir, "html", "packages.html")
op <- file.path(tempdir(), ".R/doc/html/libPaths.rds")
if (temp && file.exists(f.tg) && file.exists(op)) {
if(identical(lib.loc, readRDS(op))) {
dates <- file.mtime(c(f.tg, lib.loc))
if(which.max(dates) == 1L) return(TRUE)
}
}
if (!file.create(f.tg)) {
warning("cannot update HTML package index")
return(FALSE)
}
if (verbose) {
message("Making 'packages.html' ...", appendLF = FALSE, domain = NA)
flush.console()
}
file.append(f.tg,
file.path(R.home("doc"), "html", "packages-head-utf8.html"))
out <- file(f.tg, open = "a")
on.exit(close(out))
if(WINDOWS) {
rh <- chartr("\\", "/", R.home())
drive <- substring(rh, 1L, 2L)
}
pkgs <- vector("list", length(lib.loc))
names(pkgs) <- lib.loc
for (lib in lib.loc) {
pg <- .packages(all.available = TRUE, lib.loc = lib)
pkgs[[lib]] <- pg[order(toupper(pg), pg)]
}
if (WINDOWS) {
tot <- sum(lengths(pkgs))
if(verbose) {
pb <- winProgressBar("R: creating packages.html", max = tot)
on.exit(close(pb), add = TRUE)
}
npkgs <- 0L
}
if (length(lib.loc) > 1L) add_lib_index(lib.loc)
for (ii in seq_along(lib.loc)) {
lib <- lib.loc[ii]
libname <-
if (identical(lib, .Library)) "the standard library" else if (WINDOWS) chartr("/", "\\", lib) else lib
cat("<p><h3 id=\"lib-",ii,"\">Packages in ", libname, "</h3>\n", sep = "", file = out)
lib0 <- "../../library"
if (!temp) {
if (WINDOWS) {
if (is.na(pmatch(rh, lib))) {
lib0 <- if(substring(lib, 2L, 2L) != ":")
paste0(drive, lib) else lib
lib0 <- paste0("file:///", URLencode(lib0))
}
} else {
if (lib != .Library)
lib0 <- paste0("file:///", URLencode(lib))
}
}
pg <- pkgs[[lib]]
use_alpha <- (length(pg) > 100)
first <- toupper(substr(pg, 1, 1))
nm <- sort(names(table(first)))
if(use_alpha) {
writeLines("<p align=\"center\">", out)
writeLines(paste0("<a href=\"
writeLines("</p>\n", out)
}
cat('<p><table width="100%" summary="R Package list">\n', file = out)
for (a in nm) {
if(use_alpha)
cat("<tr id=\"pkgs-", a, "\"> <td></td>\n", sep = "", file = out)
for (i in pg[first == a]) {
title <- packageDescription(i, lib.loc = lib, fields = "Title",
encoding = "UTF-8")
if (is.na(title)) title <- "-- Title is missing --"
cat('<tr align="left" valign="top" id="lib-', i, '">\n',
'<td width="25%"><a href="', lib0, '/', i,
'/html/00Index.html">', i, "</a></td><td>", title,
"</td></tr>\n", file = out, sep = "")
if (WINDOWS) {
npkgs <- npkgs + 1L
if(verbose) setWinProgressBar(pb, npkgs)
}
}
}
cat("</table>\n\n", file=out)
}
if (length(lib.loc) > 1L) add_lib_index(lib.loc)
cat("</body></html>\n", file=out)
if (verbose) { message(" ", "done"); flush.console() }
if (temp) saveRDS(lib.loc, op)
invisible(TRUE)
} |
mod3 <- lm(y_data~x1_data+x2_data+x3_data+x4_data, data=name_of_the_dataframe)
summary(mod3)
predicted <- predict(mod3, x1_test_data, x2_test_data, x3_test_data, x4_test_data) |
lslSEM <- methods::setRefClass(Class = "lslSEM",
fields = list(
data = "list",
model = "list",
structure = "list"),
methods = list(
input = function(raw) {
"Method input() is used to input a data set for further statistical analysis. \n
Argument raw is a raw data matrix that will be used for analysis."
data$raw <<- as.data.frame(raw)
},
specify = function(pattern, value, scale) {
"Method specify() is used to specify a SEM model for fitting.\n
Argument pattern is a list of pattern matrices for the six model parameter matrices in SEM.
For each pattern matrix, the element can be set as 1, 0, or NA.
1 means that the corresponding parameter should be freely estimated,
0 indicates that the parameter sould be fixed,
and NA makes the parameter to be estimated with penalization.
These pattern matrices for the six model parameter matrices include \n
(1) lambda: a P by M pattern matrix for loading matrix; \n
(2) psi: a P by P pattern matrix covariance matrix of measurement errors. Its default value is diag(1, P).
Note that the diagonal element of psi must be set as 1; \n
(3) beta: a M by M pattern matrix for path coefficient matrix. Its default value is matrix(0, M, M); \n
(4) phi: a M by M pattern matrix for covariance matrix of residuals. Its default value is diag(1, M).
Note that the diagonal element of phi must be set as 1; \n
(5) nu: a P by 1 pattern matrix for intercepts of observed variables. Its default value is matrix(1, P, 1);\n
(6) alpha: a M by 1 pattern matrix for intercepts of latent factors. Its default value is matrix(0, M, 1).\n
Argument value is a list of starting value matrices for the six model parameter matrices in SEM.
These starting value matrices for the six model parameter matrices include \n
(1) lambda: a P by M starting value matrix for the loading matrix. The default value for its element is
(a) 1 for the freely estimated parameters and (2) 0 for the fixed or penealized parameter. \n
(2) psi: a P by P starting value matrix for the covariance matrix of measurement errors. Its default value is diag(0.1, P). \n
(3) beta: a M by M starting value matrix for the path coefficient matrix. Its default value is matrix(0, M, M); \n
(4) phi: a M by M starting value matrix for the covariance matrix of residuals. Its default value is diag(1, M). \n
(5) nu: a P by 1 starting value matrix for the intercepts of observed variables. Its default value is sample means of observed variables;\n
(6) alpha: a M by 1 starting value matrix for the intercepts of latent factors. Its default value is matrix(0, M, 1).\n
Argument scale is a logical indicator for specifying whether the scale of latent variable should be determined automatically.
If scale = TRUE, the first freely estimated loading of each latent factor will be set as one for scale setting.
The default value of scale is 1.
"
if (missing(pattern) | is.null(pattern$lambda)) {
stop("lambda matrix in pattern is not specified")
}
if (is.null(pattern$psi)) {
pattern$psi <- diag(1, dim(pattern$lambda)[1])
}
if (!identical(pattern$psi, t(pattern$psi))) {
stop("psi matrix in pattern is not symmetric")
}
if (is.null(pattern$beta)) {
pattern$beta <- matrix(0, dim(pattern$lambda)[2], dim(pattern$lambda)[2])
}
if (is.null(pattern$phi)) {
pattern$phi <- matrix(1, dim(pattern$lambda)[2], dim(pattern$lambda)[2])
}
if (!identical(pattern$phi, t(pattern$phi))) {
stop("phi matrix in pattern is not symmetric")
}
if (is.null(pattern$nu)) {
pattern$nu <- matrix(1, dim(pattern$lambda)[1], 1)
}
if (is.null(pattern$alpha)) {
pattern$alpha <- matrix(0, dim(pattern$lambda)[2], 1)
}
if (missing(value)) {
value <- list()
value$lambda <- 1*(.is_one(pattern$lambda))
}
if (is.null(value$lambda)) {
value$lambda <- 1*(.is_one(pattern$lambda))
}
if (is.null(value$psi)) {
value$psi <- diag(.1, dim(pattern$lambda)[1])
}
if (!identical(value$psi, t(value$psi))) {
stop("psi matrix in value is not symmetric")
}
if (is.null(value$beta)) {
value$beta <- matrix(0, dim(pattern$lambda)[2], dim(pattern$lambda)[2])
}
if (is.null(value$phi)) {
value$phi <- diag(1, dim(pattern$lambda)[2])
}
if (!identical(value$phi, t(value$phi))) {
stop("phi matrix in value is not symmetric")
}
if (is.null(value$nu)) {
value$nu <- matrix(0, dim(pattern$lambda)[1], 1)
}
if (is.null(value$alpha)) {
value$alpha <- matrix(0, dim(pattern$lambda)[2], 1)
}
if (missing(scale)) {
scale <- TRUE
}
if (scale) {
scale_idx <- apply(pattern$lambda == 1, 2, function(x) min(which(x)))
pattern$lambda[cbind(scale_idx, 1:ncol(pattern$lambda))] <- 0
}
model$pattern <<- pattern
model$value <<- value
},
learn = function(penalty, control, variable) {
"Method learn() is used to calculate penalized likelihood estimates based on the inputed data and specified model.\n
Argument penalty is a list for the information of penalty function and regularization parameters.
Argument penalty includes three elements \n
(1) type = c('l1', 'scad', 'mcp'): the penalty function to be implemented. The default value is 'l1'; \n
(2) gamma = seq(0.025, .10, .025): the values of regularization parameter gamma to be considered; \n
(3) delta = 2.5: the values of shape parameter delta to be considered.\n
Argument control is a list for controlling the optimization process.
Argument control includes two elements: \n
(1) maxit = 500, the maximum number of ECM iterations; \n
(2) epsilon = 10^-5, the convergence criterion of ECM algorithm. \n
Argument variable is a vector of index of variable names to specify which variables in data should be used for analysis.
The default value is 1:nrow(data$raw), which select all of the variables."
if (missing(penalty)) {
penalty <- list(type = "l1", gamma = seq(0.025, .10, .025), delta = 2.5)
} else {
if (is.null(penalty$type)) {
penalty$type <- "l1"
}
if (is.null(penalty$gamma)) {
penalty$gamma <- seq(0.025, .10, .025)
}
if (is.null(penalty$delta)) {
penalty$delta <- 2.5
}
}
if (missing(control)) {
control <- list(maxit = 500, epsilon = 10^-5)
} else {
if (is.null(control$maxit)) {
control$maxit <- 500
}
if (is.null(control$epsilon)) {
control$epsilon <- 10^-5
}
}
if (missing(variable)) {
variable <- seq(1, ncol(data$raw), 1)
}
structure$obs_moment$Sg <<- cov(data$raw[,variable], use = "pairwise.complete.obs")
structure$obs_moment$mu <<- as.matrix(colMeans(data$raw[,variable]))
structure$info$N <<- nrow(data$raw)
structure$info$P <<- nrow(model$pattern$lambda)
structure$info$M <<- ncol(model$pattern$lambda)
theta <- .sem_theta_cal(Ldp = model$pattern$lambda, Psp = model$pattern$psi,
Btp = model$pattern$beta, Php = model$pattern$phi,
nup = model$pattern$nu, app = model$pattern$alpha,
Ld = model$value$lambda, Ps = model$value$psi,
Bt = model$value$beta, Ph = model$value$phi,
nu = model$value$nu, ap = model$value$alpha)
structure$info$Qall <<- length(theta)
A <- length(penalty$gamma)
B <- length(penalty$delta)
penalty_fit <- list(type = penalty$type)
theta_names <- .sem_theta_names(model$pattern$lambda, model$pattern$psi,
model$pattern$beta, model$pattern$phi,
model$pattern$nu, model$pattern$alpha)
gm_name_all <- paste("gm=", as.character(penalty$gamma), sep="")
dt_name_all <- paste("dt=", as.character(penalty$delta), sep="")
structure$overall <<- array(NA, c(18, A, B), dimnames = list(c("gm", "dt", "dpl", "dml",
"Q", "df", "it",
"lrt", "srmr", "rmsea", "mc", "ghat",
"cfi", "nnfi", "bl89", "rni", "aic", "bic"), gm_name_all, dt_name_all))
structure$individual <<- array(NA, c(structure$info$Qall, A, B), dimnames = list(theta_names, gm_name_all, dt_name_all))
for (a in A:1) {
penalty_fit$gm <- penalty$gamma[a]
for (b in B:1) {
penalty_fit$dt <- penalty$delta[b]
fit_summary <- rep(NA, 18)
names(fit_summary) <- c("gm", "dt", "dpl", "dml",
"Q", "df", "it",
"lrt", "srmr", "rmsea", "mc", "ghat",
"cfi", "nnfi", "bl89", "rni", "aic", "bic")
rst_ecm <- .sem_ecm(model$pattern, model$value, penalty_fit, control, structure$info, structure$obs_moment)
Sg <- rst_ecm$implied_moment$Sg
mu <- rst_ecm$implied_moment$mu
N <- structure$info$N
P <- structure$info$P
dml <- rst_ecm$dml
Q <- rst_ecm$Q
lrt <- N * dml
df <- rst_ecm$df
dml_b <- .sem_dml_cal(structure$obs_moment$Sg, structure$obs_moment$mu,
diag(diag(structure$obs_moment$Sg)), structure$obs_moment$mu)
df_b <- P *(P + 3)/2 - 2 * P
lrt_b <- N * dml_b
fit_summary["gm"] <- penalty_fit$gm
fit_summary["dt"] <- penalty_fit$dt
fit_summary["dpl"] <- rst_ecm$dpl
fit_summary["dml"] <- rst_ecm$dml
fit_summary["Q"] <- rst_ecm$Q
fit_summary["df"] <- rst_ecm$df
fit_summary["it"] <- rst_ecm$it
fit_summary["lrt"] <- lrt
fit_summary["srmr"] <- sqrt(sum(.ltri(((Sg - structure$obs_moment$Sg)^2) / tcrossprod(diag(Sg))))/(P * (P + 1) / 2))
fit_summary["rmsea"] <- sqrt(max((lrt - df) / (df * N), 0))
fit_summary["mc"] <- exp(-0.5 * (lrt - df) / N)
fit_summary["ghat"] <- P / (P + 2 * (lrt - df) / N)
fit_summary["cfi"] <- 1 - max(lrt - df, 0) / max(lrt- df, lrt_b - df_b, 0)
fit_summary["nnfi"] <- (lrt_b / df_b - lrt / df)/(lrt_b/ df_b - 1)
fit_summary["bl89"] <- (lrt_b - lrt) / (lrt_b- df)
fit_summary["rni"] <- ((lrt_b - df_b) - (lrt - df))/(lrt_b - df_b)
fit_summary["aic"] <- dml + (2 / N) * Q
fit_summary["bic"] <- dml + (log(N) / N) * Q
structure$overall[, a, b] <<- fit_summary
structure$individual[, a, b] <<- rst_ecm$theta
}
}
},
summarize = function(type, selector, object) {
"Method summarize() is used to obtained a summary for the learned structure.
Argument type specify which type of summary should be made. \n
If type = 'overall', summarize() will give the overall model information (including goodness-of-fit indices) under best AIC and BIC models. \n
If type = 'individual', summarize() will give the parameter estimates under best AIC and BIC model."
if (type == "overall") {
select_idx <- which(as.matrix(structure$overall["aic", , ] == min(structure$overall["aic", , ])), arr.ind = T)
select_idx <- select_idx[dim(select_idx)[1], , drop = F]
aic <- structure$overall[, select_idx[1], select_idx[2]]
select_idx <- which(as.matrix(structure$overall["bic", , ] == min(structure$overall["bic", , ])), arr.ind = T)
select_idx <- select_idx[dim(select_idx)[1], , drop = F]
bic <- structure$overall[, select_idx[1], select_idx[2]]
rst <- data.frame(aic, bic)
colnames(rst) <- c("aic optimal", "bic optimal")
return(rst)
}
if (type == "individual") {
select_idx <- which(as.matrix(structure$overall["aic", , ] == min(structure$overall["aic", , ])), arr.ind = T)
select_idx <- select_idx[dim(select_idx)[1], , drop = F]
aic <- structure$individual[, select_idx[1], select_idx[2]]
select_idx <- which(as.matrix(structure$overall["bic", , ] == min(structure$overall["bic", , ])), arr.ind = T)
select_idx <- select_idx[dim(select_idx)[1], , drop = F]
bic <- structure$individual[, select_idx[1], select_idx[2]]
rst <- data.frame(aic, bic)
colnames(rst) <- c("aic optimal", "bic optimal")
return(rst)
}
},
draw = function(type, object) {
"Method draw() is used to draw a plot for the learned structure.
Argument type specify which type of plot should be drawn. \n
If type = 'overall', draw() will give a plot for the goodness-of-fit indices across different values of gamma and delta.
The argument object can be used to specify which goodness-of-fit indices should be plot.
Its value can be any combination of 'dml', 'srmr', 'rmsea', 'mc', 'ghat', 'cfi', 'nnfi', 'bl89', 'rni', 'aic', and 'bic'.
The default value is c('dml', 'aic', 'bic'). \n
If type = 'individual', draw() will give a plot for the solution paths of parameter estimates under across different values of gamma and delta.
The argument object can be used to specify parameters in which matrix should be plot.
Its value can be 'lambda', 'psi', 'beta', 'phi', 'nu', and 'alpha'.
The default value is 'lambda'."
if (type == "overall") {
if (missing(object)) {
object = c("dml","aic","bic")
}
validation <- reshape2::melt(structure$overall[object, , , drop = F])
validation[, 2] <- as.numeric(substring(validation[, 2], 4))
validation[, 3] <- as.numeric(substring(validation[, 3], 4))
colnames(validation) <- c("criterion", "gm", "dt", "value")
validation_plot <- ggplot2::ggplot(validation, ggplot2::aes(gm, value, colour = criterion)) + ggplot2::geom_line(size = 1) + ggplot2::geom_point(size = 3) +
ggplot2::facet_grid(.~ dt, labeller = label_both) +
ggplot2::labs(title = "Plot of Goodness-of-Fit", x = "gamma", y = "value")
print(validation_plot)
}
if (type == "individual") {
if (missing(object)) {
object = "lambda"
}
theta_names_mat <- matrix(unlist(strsplit(row.names(structure$individual), split="[][,]")), dim(structure$individual)[1], 3, byrow=T)
matrix_name_idc <- theta_names_mat[, 1] == object
thetap <- .sem_theta_cal(Ldp = model$pattern$lambda, Psp = model$pattern$psi,
Btp = model$pattern$beta, Php = model$pattern$phi,
nup = model$pattern$nu, app = model$pattern$alpha,
Ld = model$pattern$lambda, Ps = model$pattern$psi,
Bt = model$pattern$beta, Ph = model$pattern$phi,
nu = model$pattern$nu, ap = model$pattern$alpha)
theta_names_penalized <- row.names(structure$individual)[is.na(thetap)]
path <- reshape2::melt(structure$individual[matrix_name_idc, , , drop = F])
path[, 1] <- as.character(path[,1])
path[, 2] <- as.numeric(substring(path[,2],4))
path[, 3] <- as.numeric(substring(path[,3],4))
penalized <- is.element(path[, 1], theta_names_penalized)
path[, 5] <- penalized
colnames(path) <- c("parameter", "gm", "dt", "value", "penalized")
path_plot <- ggplot2::ggplot(path, ggplot2::aes(gm, value, colour = parameter, linetype = penalized)) + ggplot2::geom_line(size = 1) +
ggplot2::scale_linetype_manual(values = c("FALSE" = "solid", "TRUE" = "dashed")) +
ggplot2::facet_grid(.~ dt, labeller = label_both) +
ggplot2::labs(title = paste("Solution Paths of Parameters in ", object, sep = ""), x = "gamma", y = "value")
print(path_plot)
}
}
)
) |
library(lingtypology)
context("Tests for iso.gltc function")
df <- data.frame(my_langs = c("adyg1241", "udii1243"), stringsAsFactors = FALSE)
test_that("iso.gltc", {
expect_equal(iso.gltc("adyg1241"), c(adyg1241 = "ady"))
expect_equal(iso.gltc(c("adyg1241", "udii1243")), c(adyg1241 = "ady", udii1243 = "udi"))
expect_equal(iso.gltc(df), c(my_langs1 = "ady", my_langs2 = "udi"))
}) |
context('Epochs')
suppressPackageStartupMessages(library(lubridate))
test_that('Easter Monday calculations work:', {
expect_identical(easter_monday(c(1963, 2013)), yday(ymd(19630415, 20130401)))
})
test_that("delta_t correct to within five second:", {
expect_equal(delta_t(ymd(19730201, 20100401, 20130901, 20151201, tz = "UTC")),
c(43.4724, 66.1683, 67.1458, 68.0514), tolerance = 1, scale = 1)
})
test_that("Julian day number converter works:", {
expect_equal(julian_day_to_gregorian(2451545),
ISOdate(2000, 1, 1, hour = 0, tz = "UTC") + .5 * 24 * 60 * 60)
expect_equal(julian_day_to_gregorian(2447187.5),
ISOdate(1988, 1, 27, hour = 0, tz = "UTC"))
})
test_that('Equinox dates are correct:', {
expect_equal(equinox(c(1991:1995, 1999), season = 'mar', want_dt = TRUE),
floor_date(ymd_hms(19910321030254, 19920320084902, 19930320144138, 19940320202901,
19950321021527, 19990321014653), "minute"), tolerance = 2 * 60)
expect_equal(equinox(c(1993, 1997), season='sep', want_dt = TRUE),
floor_date(ymd_hms(19930923002329, 19970922235649), "minute"),
tolerance = 2 * 60)
expect_equal(equinox(2021, season = "sep", want_dt = TRUE),
ymd_hms(20210922192100), tolerance = 2 * 60)
})
test_that("Moon phase dates are correct:", {
expect_equal(next_moon_phase(ymd(19770215), "new", want_dt = TRUE),
ymd_hms(19770218033741), tolerance = 1)
expect_equal(next_moon_phase(ymd(20440101), "last", want_dt = TRUE),
ymd_hms(20440121234815), tolerance = 1)
expect_equal(next_moon_phase(ymd(20160801), "first", want_dt = FALSE),
with_tz(ymd_hm(201608110420, tz = "Australia/Sydney"), tz = "UTC"),
tolerance = 60)
expect_equal(next_moon_phase(ymd(20161101), "full", want_dt = FALSE),
with_tz(ymd_hm(201611150052, tz = "Australia/Sydney"), tz = "UTC"),
tolerance = 60)
})
test_that("Chinese NY dates are correct:", {
expect_equal(lubridate::as_date(chinese_new_year(2015:2018)),
as.Date(c("2015-02-19", "2016-02-08", "2017-01-28", "2018-02-16")))
}) |
library(h2o)
h2o.init()
iris.hex <- as.h2o(iris)
dim(iris.hex |
create_drake_spec <- function(
plan,
envir = parent.frame(),
logger,
jobs = 1,
trigger = drake::trigger(),
cache = NULL
) {
force(envir)
import_names <- names(envir)
args <- list(
plan = plan,
envir = envir,
logger = logger,
jobs = jobs,
cache = cache,
trigger = cds_parse_trigger(trigger = trigger, envir = envir),
ht_targets = ht_new(plan$target),
ht_imports = ht_new(import_names),
ht_globals = ht_new(c(import_names, plan$target))
)
imports <- cds_prepare_imports(args)
imports_kernel <- cds_imports_kernel(args, imports)
import_spec <- memo_expr(
cds_analyze_imports(args, imports),
args$cache,
imports_kernel
)
knitr_hash <- cds_get_knitr_hash(args)
command_spec <- memo_expr(
cds_analyze_commands(args),
args$cache,
args$plan,
args$trigger,
import_spec,
imports_kernel,
knitr_hash
)
cds_set_knitr_files(args = args, spec = command_spec)
out <- c(import_spec, command_spec)
list2env(out, parent = emptyenv(), hash = TRUE)
}
cds_set_knitr_files <- function(args, spec) {
args$logger$disk("set knitr files")
knitr_files <- lightly_parallelize(
X = spec,
FUN = function(x) {
x$deps_build$knitr_in
},
jobs = args$jobs
)
knitr_files <- sort(unique(as.character(unlist(knitr_files))))
args$cache$set(
key = "knitr",
value = knitr_files,
namespace = "memoize"
)
}
cds_get_knitr_hash <- function(args, spec) {
args$logger$disk("get knitr hash")
if (!args$cache$exists(key = "knitr", namespace = "memoize")) {
out <- args$cache$digest("", serialize = FALSE)
return(out)
}
knitr_files <- args$cache$safe_get(key = "knitr", namespace = "memoize")
knitr_hashes <- lightly_parallelize(
X = knitr_files,
FUN = static_storage_hash,
jobs = args$jobs,
config = args
)
knitr_hashes <- as.character(unlist(knitr_hashes))
knitr_hashes <- paste0(knitr_hashes, collapse = "")
args$cache$digest(knitr_hashes, serialize = FALSE)
}
cds_imports_kernel <- function(args, imports) {
out <- lightly_parallelize(
X = imports,
FUN = safe_deparse_function,
jobs = args$jobs
)
names(out) <- names(imports)
out[sort(as.character(names(out)))]
}
cds_prepare_imports <- function(args) {
args$logger$disk("analyze environment")
imports <- as.list(args$envir)
cds_unload_conflicts(
imports = names(imports),
targets = args$plan$target,
envir = args$envir,
logger = args$logger
)
import_names <- setdiff(names(imports), args$plan$target)
imports[import_names]
}
cds_unload_conflicts <- function(imports, targets, envir, logger) {
common <- intersect(imports, targets)
if (length(common)) {
logger$term("unloading", length(common), "targets from environment")
}
remove(list = common, envir = envir)
}
cds_analyze_imports <- function(args, imports) {
args$logger$disk("analyze imports")
names <- names(imports)
out <- lightly_parallelize(
X = seq_along(imports),
FUN = cdl_analyze_import,
jobs = args$jobs,
imports = imports,
names = names,
args = args
)
names(out) <- names
out
}
cdl_analyze_import <- function(index, imports, names, args) {
name <- names[index]
spec <- list(
target = name,
imported = TRUE,
deps_build = cds_import_dependencies(
expr = imports[[index]],
exclude = name,
restrict = args$ht_imports
)
)
as_drake_spec(spec)
}
cds_analyze_commands <- function(args) {
args$logger$disk("analyze commands")
args$plan$imported <- FALSE
if ("trigger" %in% colnames(args$plan)) {
args$plan$trigger <- lapply(
args$plan$trigger,
cds_parse_trigger,
envir = args$envir_targets
)
}
spec <- drake_pmap(.l = args$plan, .f = list, jobs = args$jobs)
names(spec) <- args$plan$target
args$default_condition_deps <- cds_import_dependencies(
args$trigger$condition,
restrict = args$ht_globals
)
args$default_change_deps <- cds_import_dependencies(
args$trigger$change,
restrict = args$ht_globals
)
out <- lightly_parallelize(
X = spec,
FUN = cds_prepare_spec,
jobs = args$jobs,
args = args
)
names(out) <- args$plan$target
out
}
cds_prepare_spec <- function(args, spec) {
target <- spec$target
spec$dynamic <- as_dynamic(spec$dynamic)
spec$deps_build <- cds_command_dependencies(
command = spec$command,
exclude = spec$target,
restrict = args$ht_globals
)
spec$deps_dynamic <- cds_dynamic_deps(
spec$dynamic,
spec$target,
args
)
spec$deps_dynamic_trace <- cds_dynamic_trace(spec$dynamic, args)
cds_assert_trace(spec$dynamic, spec)
spec$command_standardized <- cds_standardize_command(spec$command)
if (inherits(spec$dynamic, "dynamic")) {
dynamic_command <- cds_std_dyn_cmd(spec$dynamic)
spec$command_standardized <- paste(
spec$command_standardized,
dynamic_command
)
cds_exclude_dynamic_file_dsl(spec, field = "file_out")
cds_exclude_dynamic_file_dsl(spec, field = "knitr_in")
}
spec$command_build <- cds_preprocess_command(
spec$command,
args = args
)
if (is.null(spec$trigger) || all(is.na(spec$trigger))) {
spec$trigger <- args$trigger
spec$deps_condition <- args$default_condition_deps
spec$deps_change <- args$default_change_deps
} else {
spec$deps_condition <- cds_import_dependencies(
spec$trigger$condition,
exclude = spec$target,
restrict = args$ht_globals
)
spec$deps_change <- cds_import_dependencies(
spec$trigger$change,
exclude = spec$target,
restrict = args$ht_globals
)
}
cds_no_dynamic_triggers(spec)
for (field in c("deps_build", "deps_condition", "deps_change")) {
spec[[field]]$memory <- ht_filter(
ht = args$ht_targets,
x = spec[[field]]$globals
)
}
spec$deps_build$memory <- base::union(
spec$deps_build$memory,
spec$deps_dynamic_trace
)
as_drake_spec(spec)
}
cds_exclude_dynamic_file_dsl <- function(spec, field) {
if (length(spec$deps_build[[field]])) {
stop0(
field,
"() in dynamic targets is illegal. Target: ",
spec$target
)
}
}
as_drake_spec <- function(spec) {
class(spec) <- c("drake_spec", "drake")
spec
}
print.drake_spec <- function(x, ...) {
type <- ifelse(x$imported, "import", "target")
cat("drake workflow specification of", type, x$target, "\n")
utils::str(x, no.list = TRUE)
}
cds_no_dynamic_triggers <- function(spec) {
cds_no_dynamic_triggers_impl(
spec$target,
spec$deps_dynamic,
unlist(spec$deps_condition)
)
cds_no_dynamic_triggers_impl(
spec$target,
spec$deps_dynamic,
unlist(spec$deps_change)
)
}
cds_no_dynamic_triggers_impl <- function(target, deps_dynamic, deps_trigger) {
common <- intersect(deps_dynamic, deps_trigger)
if (!length(common)) {
return()
}
stop0(
"Dynamic grouping variables are forbidden in the condition ",
"and change triggers. Found dynamic grouping variables for target ",
target, ":\n", multiline_message(common)
)
}
cds_import_dependencies <- function(
expr, exclude = character(0), restrict = NULL
) {
deps <- drake_deps(expr = expr, exclude = exclude, restrict = restrict)
deps$file_out <- deps$strings <- character(0)
deps
}
cds_command_dependencies <- function(
command,
exclude = character(0),
restrict = NULL
) {
deps <- drake_deps(command, exclude = exclude, restrict = restrict)
deps$strings <- character(0)
deps
}
cds_dynamic_deps <- function(dynamic, target, args) {
UseMethod("cds_dynamic_deps")
}
cds_dynamic_deps.dynamic <- function(dynamic, target, args) {
dynamic$.trace <- NULL
out <- ht_filter(args$ht_globals, all.vars(dynamic))
if (!length(out)) {
stop0(
"no admissible grouping variables for dynamic target ",
target
)
}
out
}
cds_dynamic_deps.default <- function(dynamic, target, args) {
character(0)
}
cds_dynamic_trace <- function(dynamic, args) {
UseMethod("cds_dynamic_trace")
}
cds_dynamic_trace.dynamic <- function(dynamic, args) {
all.vars(dynamic$.trace)
}
cds_dynamic_trace.default <- function(dynamic, args) {
character(0)
}
cds_assert_trace <- function(dynamic, spec) {
UseMethod("cds_assert_trace")
}
cds_assert_trace.group <- function(dynamic, spec) {
bad <- setdiff(spec$deps_dynamic_trace, spec$deps_dynamic)
if (!length(bad)) {
return()
}
stop0(
"in dynamic group(), ",
"the only legal dynamic trace variable ",
"is the one you select with `.by`. ",
"illegal dynamic trace variables for target ",
spec$target,
":\n",
multiline_message(bad)
)
}
cds_assert_trace.dynamic <- function(dynamic, spec) {
bad <- setdiff(spec$deps_dynamic_trace, spec$deps_dynamic)
if (!length(bad)) {
return()
}
stop0(
"in map() and cross(), ",
"all dynamic trace variables must be ",
"existing grouping variables, e.g. map(x, .trace = x) ",
"and not map(x, .trace = y). ",
"illegal dynamic trace variables for target ",
spec$target,
":\n",
multiline_message(bad)
)
}
cds_assert_trace.default <- function(dynamic, spec) {
character(0)
}
cds_preprocess_command <- function(command, args) {
command <- as.call(c(quote(local), command))
as.call(c(quote(rlang::expr), command))
}
cds_standardize_command <- function(x) {
if (is.expression(x) && length(x) == 1L) {
x <- x[[1]]
}
look_for_ignore <- "ignore" %in% all.vars(x, functions = TRUE)
if (look_for_ignore) {
x <- ignore_ignore(x)
}
attributes(x) <- NULL
safe_deparse(x, backtick = TRUE)
}
cds_std_dyn_cmd <- function(x) {
transform <- class(x)
vars <- sort(all.vars(x))
by <- as.character(x$.by)
paste(c(transform, vars, by, trace), collapse = " ")
}
cds_parse_trigger <- function(trigger, envir) {
if (is.symbol(trigger)) {
trigger <- safe_deparse(trigger, backtick = FALSE)
}
if (is.character(trigger)) {
trigger <- convert_old_trigger(trigger)
trigger <- parse(text = trigger)
}
eval(trigger, envir = envir)
} |
func.mean.formula<-function(formula, data = NULL,...,drop=FALSE)
{
tf <- terms.formula(formula)
fac <- attr(tf, "term.labels")
if (attr(tf, "response") > 0) response <- as.character(attr(tf, "variables")[2])
if (missing(formula) || (length(formula) != 3L))
stop("'formula' missing or incorrect")
ldata<-data
data<-ldata$df
if (is.null(ldata$df)) stop("'df' element is missing or incorrect")
if (is.vector(data)) data<-as.data.frame(data)
if (is.matrix(data)) data<-as.data.frame(data)
f<-ldata$df[[fac]]
dat<-ldata[[response]]
if (!is.factor(f)) f<-factor(f)
nlev<-nlevels(f)
lev<-levels(f)
if (is.matrix(dat$data)) dat$data<-data.frame(dat$data)
out<-split(dat$data,f,drop=drop,...)
out2<-func.mean(fdata(out[[lev[1]]],dat$argvals,dat$rangeval,dat$names))
for (i in 2:nlev) out2<-c(out2,func.mean(fdata(out[[lev[i]]],dat$argvals,dat$rangeval,dat$names)))
rownames(out2$data)<-lev
out2
}
|
"vfctrSunyiu10d2" |
g <- ggplot(dat, aes(x = x, y = y)) + geom_line(size = 1.5)
g <- g + geom_ribbon(aes(x = ifelse(x > -1 & x < 1, x, 0), ymin = 0, ymax = dat$y), fill = "red", alpha = 1)
g <- g + geom_ribbon(aes(x = ifelse(x > -2 & x < 2, x, 0), ymin = 0, ymax = dat$y), fill = "red", alpha = 0.5)
g <- g + geom_ribbon(aes(x = ifelse(x > -3 & x < 3, x, 0), ymin = 0, ymax = dat$y), fill = "red", alpha = 0.35)
print(g) |
NULL
vec_proxy.wk_wkb <- function(x, ...) {
unclass(x)
}
vec_restore.wk_wkb <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
geodesic_out <- attr(to, "geodesic", exact = TRUE) %||% attr(x, "geodesic", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "geodesic") <- NULL
new_wk_wkb(x, crs = crs_out, geodesic = geodesic_out)
}
vec_cast.wk_wkb <- function(x, to, ...) {
UseMethod("vec_cast.wk_wkb")
}
vec_cast.wk_wkb.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to)
}
vec_cast.wk_wkb.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
wk_is_geodesic_output(x, to)
x
}
vec_cast.wk_wkb.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
wk_is_geodesic_output(x, to)
as_wkb(x)
}
vec_cast.wk_wkb.wk_xy <- function(x, to, ...) {
wk_translate(x, to)
}
vec_cast.wk_wkb.wk_xyz <- function(x, to, ...) {
wk_translate(x, to)
}
vec_cast.wk_wkb.wk_xym <- function(x, to, ...) {
wk_translate(x, to)
}
vec_cast.wk_wkb.wk_xyzm <- function(x, to, ...) {
wk_translate(x, to)
}
vec_cast.wk_wkb.wk_rct <- function(x, to, ...) {
wk_translate(x, to)
}
vec_cast.wk_wkb.wk_crc <- function(x, to, ...) {
wk_crs_output(x, to)
as_wkb(x)
}
vec_ptype2.wk_wkb <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_wkb", y)
}
vec_ptype2.wk_wkb.default <- function(x, y, ..., x_arg = "x", y_arg = "y") {
vctrs::vec_default_ptype2(x, y, x_arg = x_arg, y_arg = y_arg)
}
vec_ptype2.wk_wkb.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = geodesic_attr(wk_is_geodesic_output(x, y)))
}
vec_ptype2.wk_wkb.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = geodesic_attr(wk_is_geodesic_output(x, y)))
}
vec_ptype2.wk_wkb.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
vec_ptype2.wk_wkb.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
vec_ptype2.wk_wkb.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
vec_ptype2.wk_wkb.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
vec_ptype2.wk_wkb.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = geodesic_attr(wk_is_geodesic_output(x, y)))
}
vec_ptype2.wk_wkb.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
vec_proxy.wk_wkt <- function(x, ...) {
unclass(x)
}
vec_restore.wk_wkt <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
geodesic_out <- attr(to, "geodesic", exact = TRUE) %||% attr(x, "geodesic", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "geodesic") <- NULL
new_wk_wkt(x, crs = crs_out, geodesic = geodesic_out)
}
vec_cast.wk_wkt <- function(x, to, ...) {
UseMethod("vec_cast.wk_wkt")
}
vec_cast.wk_wkt.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to)
}
vec_cast.wk_wkt.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
wk_is_geodesic_output(x, to)
x
}
vec_cast.wk_wkt.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
wk_is_geodesic_output(x, to)
as_wkt(x)
}
vec_cast.wk_wkt.wk_xy <- function(x, to, ...) {
wk_translate(x, to)
}
vec_cast.wk_wkt.wk_xyz <- function(x, to, ...) {
wk_translate(x, to)
}
vec_cast.wk_wkt.wk_xym <- function(x, to, ...) {
wk_translate(x, to)
}
vec_cast.wk_wkt.wk_xyzm <- function(x, to, ...) {
wk_translate(x, to)
}
vec_cast.wk_wkt.wk_rct <- function(x, to, ...) {
wk_translate(x, to)
}
vec_cast.wk_wkt.wk_crc <- function(x, to, ...) {
wk_translate(x, to)
}
vec_ptype2.wk_wkt <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_wkt", y)
}
vec_ptype2.wk_wkt.default <- function(x, y, ..., x_arg = "x", y_arg = "y") {
vctrs::vec_default_ptype2(x, y, x_arg = x_arg, y_arg = y_arg)
}
vec_ptype2.wk_wkt.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = geodesic_attr(wk_is_geodesic_output(x, y)))
}
vec_ptype2.wk_wkt.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = geodesic_attr(wk_is_geodesic_output(x, y)))
}
vec_ptype2.wk_wkt.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
vec_ptype2.wk_wkt.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
vec_ptype2.wk_wkt.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
vec_ptype2.wk_wkt.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
vec_ptype2.wk_wkt.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
wk_is_geodesic_output(x, y)
new_wk_wkt(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_wkt.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
vec_proxy.wk_xy <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_xy <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_xy(x, crs = crs_out)
}
vec_cast.wk_xy <- function(x, to, ...) {
UseMethod("vec_cast.wk_xy")
}
vec_cast.wk_xy.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to)
}
vec_cast.wk_xy.wk_xy <- function(x, to, ...) {
wk_crs_output(x, to)
x
}
vec_cast.wk_xy.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x)
}
vec_cast.wk_xy.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x)
}
vec_cast.wk_xy.wk_xyz <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y")),
x, to,
!is.na(unclass(x)$z)
)
}
vec_cast.wk_xy.wk_xym <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y")),
x, to,
!is.na(unclass(x)$m)
)
}
vec_cast.wk_xy.wk_xyzm <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y")),
x, to,
!is.na(unclass(x)$z) & !is.na(unclass(x)$m)
)
}
vec_ptype2.wk_xy <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_xy", y)
}
vec_ptype2.wk_xy.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xy(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xy.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
vec_ptype2.wk_xy.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
vec_ptype2.wk_xy.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyz(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xy.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xym(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xy.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xy.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xy.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_proxy.wk_xyz <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_xyz <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_xyz(x, crs = crs_out)
}
vec_cast.wk_xyz <- function(x, to, ...) {
UseMethod("vec_cast.wk_xyz")
}
vec_cast.wk_xyz.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to)
}
vec_cast.wk_xyz.wk_xyz <- function(x, to, ...) {
wk_crs_output(x, to)
x
}
vec_cast.wk_xyz.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z"))
}
vec_cast.wk_xyz.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z"))
}
vec_cast.wk_xyz.wk_xy <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z"))
}
vec_cast.wk_xyz.wk_xym <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y", "z")),
x, to,
!is.na(unclass(x)$m)
)
}
vec_cast.wk_xyz.wk_xyzm <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y", "z")),
x, to,
!is.na(unclass(x)$m)
)
}
vec_ptype2.wk_xyz <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_xyz", y)
}
vec_ptype2.wk_xyz.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyz(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xyz.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
vec_ptype2.wk_xyz.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
vec_ptype2.wk_xyz.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyz(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xyz.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xyz.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xyz.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xyz.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_proxy.wk_xym <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_xym <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_xym(x, crs = crs_out)
}
vec_cast.wk_xym <- function(x, to, ...) {
UseMethod("vec_cast.wk_xym")
}
vec_cast.wk_xym.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to)
}
vec_cast.wk_xym.wk_xym <- function(x, to, ...) {
wk_crs_output(x, to)
x
}
vec_cast.wk_xym.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "m"))
}
vec_cast.wk_xym.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "m"))
}
vec_cast.wk_xym.wk_xy <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "m"))
}
vec_cast.wk_xym.wk_xyz <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y", "m")),
x, to,
!is.na(unclass(x)$z)
)
}
vec_cast.wk_xym.wk_xyzm <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y", "m")),
x, to,
!is.na(unclass(x)$z)
)
}
vec_ptype2.wk_xym <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_xym", y)
}
vec_ptype2.wk_xym.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xym(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xym.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
vec_ptype2.wk_xym.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
vec_ptype2.wk_xym.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xym(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xym.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xym.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xym.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xym.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_proxy.wk_xyzm <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_xyzm <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_xyzm(x, crs = crs_out)
}
vec_cast.wk_xyzm <- function(x, to, ...) {
UseMethod("vec_cast.wk_xyzm")
}
vec_cast.wk_xyzm.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to)
}
vec_cast.wk_xyzm.wk_xyzm <- function(x, to, ...) {
wk_crs_output(x, to)
x
}
vec_cast.wk_xyzm.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z", "m"))
}
vec_cast.wk_xyzm.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z", "m"))
}
vec_cast.wk_xyzm.wk_xy <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z", "m"))
}
vec_cast.wk_xyzm.wk_xyz <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z", "m"))
}
vec_cast.wk_xyzm.wk_xym <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z", "m"))
}
vec_ptype2.wk_xyzm <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_xyzm", y)
}
vec_ptype2.wk_xyzm.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xyzm.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
vec_ptype2.wk_xyzm.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
vec_ptype2.wk_xyzm.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xyzm.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xyzm.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xyzm.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_xyzm.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_proxy.wk_rct <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_rct <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_rct(x, crs = crs_out)
}
vec_cast.wk_rct <- function(x, to, ...) {
UseMethod("vec_cast.wk_rct")
}
vec_cast.wk_rct.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to)
}
vec_ptype2.wk_rct <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_rct", y)
}
vec_ptype2.wk_rct.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_rct(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_rct.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_rct.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_rct.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_rct.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_rct.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_rct.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_rct.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_proxy.wk_crc <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_crc <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_crc(x, crs = crs_out)
}
vec_cast.wk_crc <- function(x, to, ...) {
UseMethod("vec_cast.wk_crc")
}
vec_cast.wk_crc.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to)
}
vec_ptype2.wk_crc <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_crc", y)
}
vec_ptype2.wk_crc.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_crc(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_crc.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
vec_ptype2.wk_crc.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
vec_ptype2.wk_crc.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_crc.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_crc.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
vec_ptype2.wk_crc.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
} |
"ada.default" <-
function(x,y,test.x,test.y=NULL,loss=c("exponential","logistic"),
type=c("discrete","real","gentle"),iter=50, nu=0.1, bag.frac=0.5,
model.coef=TRUE,bag.shift=FALSE,max.iter=20,delta=10^(-10),verbose=FALSE,
...,na.action=na.rpart){
cl<-match.call(expand.dots=TRUE)
cl[[1]]<-as.name("ada")
type = match.arg(type)
if(missing(type)){
type="discrete"
}
if(missing(loss))
loss="exponential"
loss=tolower(loss)
if(loss=="e"|loss=="ada"){
loss="exponential"
}
if(loss=="l"|loss=="l2"){
loss="logistic"
}
if(missing(y) | missing(x)){
stop("This procedure requires a response and a set of variables")
}
lev=levels(as.factor(y))
if(length(lev)!=2)
stop("Currently this procedure can not directly handle > 2 class response\n")
x=as.data.frame(x)
test.dat=FALSE
if(!is.null(test.y)){
tlev=NULL
if(!missing(test.x)){
tlev=levels(as.factor(test.y))
test.x=as.data.frame(test.x)
test.dat=TRUE
}
if(length(tlev)<1)
warning("test.x must be the testing data and the response must have 2 levels")
}else{
test.x=NULL
}
if(length(lev)>2){
stop(paste("Error: At this time ",cl[[3]]," must have 2 levels",sep=""))
}
extraArgs=list(...)
if (length(extraArgs)) {
arg <- names(formals(rpart))
indx <- match(names(extraArgs), arg, nomatch = 0)
if (any(indx == 0))
stop(paste("Error: Argument", names(extraArgs)[indx == 0],
"not matched"))
}
ny<-c(-1,1)[as.numeric(as.factor(y))]
if(test.dat)
test.y<-c(-1,1)[as.numeric(as.factor(test.y))]
method="class"
if(type=="discrete"){
predict.type<-function(f,dat){
p <- predict(f,newdata=dat,type="class")
a=as.numeric(levels(p))[p]
a
}
}
if(type=="real"){
predict.type<-function(f,dat){
a=predict(f,newdata=dat,type="prob")[,2]
ind<-a==1|(1-a)==1
if(length(ind)>1){
a[ind]=(1-a[ind])*0.0001+a[ind]*.9999
}
f=0.5*log(a/(1-a))
if(sum(is.nan(f))>0)
f[is.nan(f)]=0.51
f
}
}
if(type=="gentle"){
predict.type<-function(f,dat){
predict(f,newdata=dat)
}
method="anova"
}
wfun<-function(yf,f){
exp(-yf*f)
}
if(loss=="logistic"){
wfun<-function(yf,f){
a=exp(-yf*f)
a/(1+a)
}
}
coefs=function(wts,eta,yf,alp){
1
}
if(model.coef){
if(loss=="exponential"){
if(type=="discrete"){
coefs=function(wts,eta,yf,alp){
alp
}
}else{
coefs=function(wts,eta,yf,alp){
alpst=alp
for(i in 1:max.iter){
alp0=alp
pval=wts*exp(-yf*eta*alp)
m11<-sum(eta*pval*eta)
m12<-sum(yf*pval*eta)
if(m11==0){
alp=alpst
break
}
alp=alp+m12/m11
a1=(alp-alp0)^2
if(a1<delta){
break
}
}
if(verbose)
cat("FINAL: iter=",i," rate=",a1,"\n")
alp
}
}
}else{
coefs=function(wts,eta,yf,alp){
alpst=alp
for(i in 1:max.iter){
alp0=alp
pval=wts*exp(-yf*eta*alp)
pval=1-1/(1+pval)
m11<-sum(eta*pval*eta)
m12<-sum(yf*pval*eta)
if(m11==0){
alp=alpst
break
}
alp=alp+m12/m11
a1=(alp-alp0)^2
if(a1<delta){
break
}
alp=alp+m12/m11
}
if(verbose)
cat("FINAL: iter=",i," rate=",a1,"\n")
2*alp
}
}
}
lossObj=list(coefs=coefs,wfun=wfun,predict.type=predict.type,method=method,type=type,loss=loss,shift=bag.shift)
result =ada.machine(x,ny,test.x,test.y,iter,nu,bag.frac,lossObj,oldObj=NULL,na.action=na.action,...)
g=as.factor(lev[as.numeric(as.factor(sign(result$F[[1]])))])
tab=table(as.factor(y),g,dnn=c("True value","Final Prediction"))
nm<-1:(dim(x)[2])
if(is.data.frame(x)){
nm=names(x)
}
obj=structure(list(model=result,fit=g,call=cl,confusion=tab,iter=iter,
actual=as.vector(y),nu=nu,dim=dim(x),names=nm,bag.frac=bag.frac,na.action=na.action),class="ada")
obj
} |
library(hamcrest)
expected <- c(0x1.8f499fd742293p+4 + -0x1.5d7edc8da68ddp-1i, -0x1.55118c572f6bbp+5 + 0x1.4eab78b8b8a4fp-1i,
0x1.5fb798bd45ed3p+5 + -0x1.3f8387bebbd59p-1i, -0x1.1fd142e6b78f5p+5 + 0x1.300adddb3cac4p-1i,
0x1.1778de73a622dp+5 + -0x1.204563ae96192p-1i, -0x1.ad45adfaf52f8p+5 + 0x1.10371541249f6p-1i,
0x1.bb9048b80c7c8p+5 + -0x1.ffc8020325b0bp-2i, -0x1.598767541db83p+5 + 0x1.dea08d7cfee79p-2i,
0x1.edfa916820387p+4 + -0x1.bd002d377fa74p-2i, -0x1.b28bc5054adcfp+4 + 0x1.9aef600704577p-2i,
0x1.1d40a08dd16e6p+5 + -0x1.7876c127275bcp-2i, -0x1.c544a62abd8e6p+5 + 0x1.559f060e20d65p-2i,
0x1.4790466501fa6p+5 + -0x1.3270fc39854e7p-2i, -0x1.79c74d2df2cf8p+5 + 0x1.0ef586f4f301ep-2i,
0x1.6e5cf8cf66022p+5 + -0x1.d66b3a367901cp-3i, -0x1.96d6a05152035p+5 + 0x1.8e748da54454fp-3i,
0x1.590b6407fbbcp+4 + -0x1.461936895b979p-3i, -0x1.c3cba3e0e5722p+4 + 0x1.fad6f949097e8p-4i,
0x1.4c510bd1ab7f9p+4 + -0x1.68fb7911d7606p-4i, -0x1.74d5097a3f629p+5 + 0x1.ad898bd650cc2p-5i,
0x1.1046fd5cbf06bp+5 + -0x1.115f4175a0c98p-6i, -0x1.15ffce72e9309p+5 + -0x1.3899a566cbf2p-6i,
0x1.4f5b9c91cd4a9p+5 + 0x1.c121c93f79c7p-5i, -0x1.25882e4f07496p+5 + -0x1.72c2a3d73ea48p-4i,
0x1.706ea7039dfdfp+5 + 0x1.024b5bdc1086p-3i, -0x1.1daf7667b7d02p+4 + -0x1.4af424523becp-3i,
0x1.0c2d1bd3a73bap+5 + 0x1.93494ffba868ap-3i, -0x1.80c41a19b3bf9p+5 + -0x1.db3898a598a0ep-3i,
0x1.5f98a73e22d05p+5 + 0x1.1157e8ed792b3p-2i, -0x1.6fe70f12c1016p+5 + -0x1.34ce76bdd26adp-2i,
0x1.427beb7cff1e2p+5 + 0x1.57f7002633bfbp-2i, -0x1.1c123698e3eccp+5 + -0x1.7ac8a33ed20c1p-2i,
0x1.730f4faa5aab7p+4 + 0x1.9d3a94143789bp-2i, -0x1.9980825a7028ap+4 + -0x1.bf441ee033184p-2i,
0x1.1b5cd31e92366p+5 + 0x1.e0dcaa3cabcaep-2i, -0x1.119f16d92558ep+5 + -0x1.00fddca7e592cp-1i,
0x1.4aa2017a7dabp+5 + 0x1.114c76f878341p-1i, -0x1.99771927ff842p+5 + -0x1.21560562f18f2p-1i,
0x1.87ee8eb038d7ap+4 + 0x1.31167aabde145p-1i, -0x1.62aa6e7d01e84p+4 + -0x1.4089dc0f7ecedp-1i,
0x1.14bafd8e5b062p+6 + 0x1.4fac42432b564p-1i, -0x1.7cb60696fae02p+5 + -0x1.5e79da71c7e2cp-1i,
0x1.d99d798154782p+5 + 0x1.6ceee7331095dp-1i, -0x1.01e6035e8025dp+5 + -0x1.7b07c17d7acddp-1i,
0x1.d5b80c731e8d1p+4 + 0x1.88c0d9926fae9p-1i, -0x1.0e154e85317fep+5 + -0x1.9616b7e4a44bbp-1i,
0x1.db41ebc6da956p+4 + 0x1.a305fdf85507ap-1i, -0x1.eaa3198085f6dp+4 + -0x1.af8b673d2ba4cp-1i,
0x1.46785c1b5fc7ep+4 + 0x1.bba3c9e199122p-1i, -0x1.0dde62d534a36p+5 + -0x1.c74c179f6d31bp-1i,
0x1.184afa7cf2e41p+5 + 0x1.d2815e817971fp-1i, -0x1.3d040eca83c5dp+5 + -0x1.dd40c9a20bbe4p-1i,
0x1.3c91244be3571p+5 + 0x1.e787a1e21225p-1i, -0x1.04abbfae1f63ap+5 + -0x1.f1534e98b886ap-1i,
0x1.61d0a73a9086ap+4 + 0x1.faa1563b542cfp-1i, -0x1.5ff3107c2b3c4p+5 + -0x1.01b7af7eb978ep+0i,
0x1.0beeefccef25ep+6 + 0x1.05dd97b47280ep+0i, -0x1.2958075e4926ap+5 + -0x1.09c15776cdd0fp+0i,
0x1.ea5d501c6d84dp+3 + 0x1.0d61f3349bf25p+0i, -0x1.012131f110a69p+5 + -0x1.10be805313b9bp+0i,
0x1.5ae18f19e62bep+5 + 0x1.13d62569179e6p+0i, -0x1.7e0296f3d6722p+5 + -0x1.16a81a7622f2ap+0i,
0x1.df027930f5d27p+4 + 0x1.1933a914d147ep+0i, -0x1.d97e454aeb7ebp+4 + -0x1.1b782ca8f31e4p+0i,
0x1.c66d9bca85524p+5 + 0x1.1d7512892432dp+0i, -0x1.cac7da8350f68p+4 + -0x1.1f29da23d90f3p+0i,
0x1.a16cb46c3d7eep+4 + 0x1.2096151fda3f8p+0i, -0x1.b0b6761b2db88p+5 + -0x1.21b96778255b3p+0i,
0x1.78192e572eaap+5 + 0x1.229387932c69ep+0i, -0x1.1127e28b22e27p+5 + -0x1.23243e556e124p+0i,
0x1.a13b51b184cccp+4 + 0x1.236b672f61baap+0i, -0x1.c0e6c6a70d06ap+5 + -0x1.2368f026b419fp+0i,
0x1.bdab5fdc6da5cp+5 + 0x1.231cd9dad204ap+0i, -0x1.1f0dcf7c3b115p+5 + -0x1.22873784c021bp+0i,
0x1.1f316ea5ed274p+5 + 0x1.21a82ef23f9a7p+0i, -0x1.353a99bd6de2dp+5 + -0x1.207ff87c41354p+0i,
0x1.32067c81e8aaep+5 + 0x1.1f0edef8a8e2dp+0i, -0x1.630259d373063p+5 + -0x1.1d553fa765c75p+0i,
0x1.ed4c8b8db8631p+4 + 0x1.1b538a1ae3228p+0i, -0x1.5887233957914p+5 + -0x1.190a401bd847ap+0i,
0x1.66080a26be408p+5 + 0x1.1679f5887eb32p+0i, -0x1.668c25582e01ep+4 + -0x1.13a3502f36815p+0i,
0x1.08ebf6be62dcap+5 + 0x1.108707a4a2b4ap+0i, -0x1.e0556d4fe7afp+2 + -0x1.0d25e51547fbap+0i,
0x1.48630a2d5f4d4p+5 + 0x1.0980c312b97b1p+0i, -0x1.db26322fc8be9p+4 + -0x1.05988d5c60b9p+0i,
0x1.eab90efb37687p+3 + 0x1.016e40a3ee38ap+0i, -0x1.3afcfae6b1a47p+5 + -0x1.fa05d49b04b2bp-1i,
0x1.3da7a7730c12ap+5 + 0x1.f0af50573c2a1p-1i, -0x1.d0523a93f05b6p+4 + -0x1.e6db506dda54p-1i,
0x1.40ae831c0911p+5 + 0x1.dc8c5083f78fp-1i, -0x1.7de70501e30ep+5 + -0x1.d1c4eb51d5dfcp-1i,
0x1.be7c0a272fb3bp+4 + 0x1.c687d9fa70518p-1i, -0x1.022a43b6ec09ep+5 + -0x1.bad7f35b5ac1p-1i,
0x1.cbcd811f9af7fp+5 + 0x1.aeb82b551f1c6p-1i, -0x1.9f1809af5d4aap+4 + -0x1.a22b920c46199p-1i,
0x1.6f791f39ae182p+5 + 0x1.953553233bd32p-1i, -0x1.15496f9b1f283p+5 + -0x1.87d8b4ed42a59p-1i,
0x1.414dee4a8722ap+5 + 0x1.7a19179aa75f5p-1i, -0x1.06ba7bc48f174p+5 + -0x1.6bf9f45e6cee1p-1i,
0x1.ae2f9e39f18f9p+4 + 0x1.5d7edc8da688fp-1i, -0x1.0e495d10b8c01p+5 + -0x1.4eab78b8b8a3dp-1i,
0x1.47c18a65534cdp+5 + 0x1.3f8387bebbd6cp-1i, -0x1.a04d8321ecccep+4 + -0x1.300adddb3cb2ep-1i,
0x1.8ecbdee25849cp+4 + 0x1.204563ae961afp-1i, -0x1.d53902b8eb3e6p+5 + -0x1.1037154124a4dp-1i,
0x1.b7044550833ap+5 + 0x1.ffc8020325b92p-2i, -0x1.a1da219dd6d5ap+5 + -0x1.dea08d7cfeee9p-2i,
0x1.48b23c7f1e87bp+5 + 0x1.bd002d377f9f3p-2i, -0x1.f36f5507e6f81p+4 + -0x1.9aef6007043b2p-2i,
0x1.0b5d8cc21d805p+4 + 0x1.7876c12727496p-2i, -0x1.51b71df0cf0c9p+3 + -0x1.559f060e20b5cp-2i,
0x1.46bf1bbbb379p+4 + 0x1.3270fc398527cp-2i, -0x1.3f37f0cffcf6p+5 + -0x1.0ef586f4f2d97p-2i,
0x1.1a0ba7fe23087p+5 + 0x1.d66b3a3678984p-3i, -0x1.f84aa4978629p+4 + -0x1.8e748da5442d8p-3i,
0x1.e2be3a4d835dp+4 + 0x1.461936895b7fp-3i, -0x1.297700495f909p+5 + -0x1.fad6f94909248p-4i,
0x1.dc8ddeb05b378p+5 + 0x1.68fb7911d729cp-4i, -0x1.cb64e413abb6p+5 + -0x1.ad898bd6500dp-5i,
0x1.1e93b9f28e4fep+5 + 0x1.115f4175a1dp-6i, -0x1.ae1467092df77p+5 + 0x1.3899a566cb4p-6i,
0x1.8fe3861b117cep+5 + -0x1.c121c93f7999p-5i, -0x1.51ba9f19ee10ep+5 + 0x1.72c2a3d73ec74p-4i,
0x1.bd5c7da6cafb8p+5 + -0x1.024b5bdc10ca8p-3i, -0x1.1cdcd4e7c4421p+5 + 0x1.4af424523c0acp-3i,
0x1.3f51afaaec09ap+5 + -0x1.93494ffba8912p-3i, -0x1.f2412bbde414ap+4 + 0x1.db3898a598decp-3i,
0x1.5aece1ad29d7ap+5 + -0x1.1157e8ed79482p-2i, -0x1.f3a1e9d207dd4p+4 + 0x1.34ce76bdd2a3bp-2i,
0x1.1505dab5fb488p+5 + -0x1.57f7002633dbdp-2i, -0x1.9c816f4fe7568p+5 + 0x1.7ac8a33ed2214p-2i,
0x1.c8620a699cd73p+4 + -0x1.9d3a9414379bfp-2i, -0x1.a21b521474bc4p+5 + 0x1.bf441ee033307p-2i,
0x1.ce6b00822127p+1 + -0x1.e0dcaa3cabdfp-2i, -0x1.4975df870fbfcp+4 + 0x1.00fddca7e592dp-1i,
0x1.6ab00fa40a65ep+5 + -0x1.114c76f8782a2p-1i, -0x1.f8237f116a49ap+4 + 0x1.21560562f187bp-1i,
0x1.f3c56584fafccp+4 + -0x1.31167aabde10dp-1i, -0x1.301df2cd1c5eap+5 + 0x1.4089dc0f7ed63p-1i,
0x1.3f0fc8ce1f368p+5 + -0x1.4fac42432b537p-1i, -0x1.9faa14e2ece31p+4 + 0x1.5e79da71c7e57p-1i,
0x1.2a0c366484627p+5 + -0x1.6ceee733109c4p-1i, -0x1.b4539489e7059p+5 + 0x1.7b07c17d7adaep-1i,
0x1.5a4efc982fa28p+5 + -0x1.88c0d9926fc2fp-1i, -0x1.a1c5aedcb77d4p+4 + 0x1.9616b7e4a45c3p-1i,
0x1.2931f78007158p+5 + -0x1.a305fdf855163p-1i, -0x1.1678d12fd6e2p+5 + 0x1.af8b673d2bb98p-1i,
0x1.f2e0b132cb4eap+4 + -0x1.bba3c9e199222p-1i, -0x1.b413962a9d5b3p+4 + 0x1.c74c179f6d44fp-1i,
0x1.2e0961f851802p+5 + -0x1.d2815e8179769p-1i, -0x1.5eeeb82cbec6p+4 + 0x1.dd40c9a20bbf4p-1i,
0x1.237d398e648a4p+4 + -0x1.e787a1e2121d2p-1i, -0x1.90238a8ba1eeep+5 + 0x1.f1534e98b880ep-1i,
0x1.e1227bc206111p+5 + -0x1.faa1563b54319p-1i, -0x1.3dad929c5ef5ap+5 + 0x1.01b7af7eb9753p+0i,
0x1.edee9a6248444p+4 + -0x1.05dd97b4727f2p+0i, -0x1.2e782454f71afp+5 + 0x1.09c15776cdcfap+0i,
0x1.43143b628a8fep+5 + -0x1.0d61f3349bf54p+0i, -0x1.29b7589ed9decp+5 + 0x1.10be805313c2cp+0i,
0x1.20e9335ae55c8p+5 + -0x1.13d6256917a47p+0i, -0x1.493d5ed59f1f6p+5 + 0x1.16a81a7622f82p+0i,
0x1.8f97f95faeb6ap+5 + -0x1.1933a914d14fdp+0i, -0x1.6b7f54a10df1dp+5 + 0x1.1b782ca8f3296p+0i,
0x1.2fb464cb94ab6p+5 + -0x1.1d75128924426p+0i, -0x1.fda3b02b80054p+4 + 0x1.1f29da23d913cp+0i,
0x1.696b3f3c7f8e7p+5 + -0x1.2096151fda441p+0i, -0x1.0171c0d5009dp+5 + 0x1.21b96778255dap+0i,
0x1.4c446f629153ep+5 + -0x1.229387932c6cfp+0i, -0x1.bf7c265647f74p+4 + 0x1.23243e556e158p+0i,
0x1.edb8e76df366bp+4 + -0x1.236b672f61b88p+0i, -0x1.b870358bd5a12p+4 + 0x1.2368f026b417cp+0i,
0x1.81487df3a66d6p+4 + -0x1.231cd9dad206ep+0i, -0x1.634491e420798p+4 + 0x1.22873784c0215p+0i,
0x1.78bafd472b75ap+4 + -0x1.21a82ef23f9e1p+0i, -0x1.a117655c55befp+4 + 0x1.207ff87c4136ap+0i,
0x1.3039a9d8dd05cp+5 + -0x1.1f0edef8a8e86p+0i, -0x1.748c71339b49p+5 + 0x1.1d553fa765ce5p+0i,
0x1.0431ad3c28461p+5 + -0x1.1b538a1ae32bdp+0i, -0x1.7e40b610a8be9p+5 + 0x1.190a401bd8535p+0i,
0x1.f1bc00c3df3a1p+4 + -0x1.1679f5887ebb8p+0i, -0x1.75330b791482cp+4 + 0x1.13a3502f3687p+0i,
0x1.019f4f15c2cf1p+4 + -0x1.108707a4a2ba8p+0i, -0x1.c613441ef0b62p+3 + 0x1.0d25e51547fdep+0i,
0x1.c679c1955eef4p+4 + -0x1.0980c312b982fp+0i, -0x1.4833ce2ed3c6cp+5 + 0x1.05988d5c60b6fp+0i,
0x1.573b3ae43a791p+5 + -0x1.016e40a3ee346p+0i, -0x1.68f8b93402d86p+5 + 0x1.fa05d49b04ab9p-1i,
0x1.1572c1b691d54p+5 + -0x1.f0af50573c298p-1i, -0x1.a2b7a46261403p+4 + 0x1.e6db506dda5d8p-1i,
0x1.1d234f0020e6fp+5 + -0x1.dc8c5083f78dfp-1i, -0x1.fa2ccfa7f554ap+5 + 0x1.d1c4eb51d5db9p-1i,
0x1.8ccc434c53e7p+5 + -0x1.c687d9fa70568p-1i, -0x1.6cc5787e9aacfp+4 + 0x1.bad7f35b5ad1bp-1i,
0x1.a234dbf3326c2p+5 + -0x1.aeb82b551f39ap-1i, -0x1.6cef4b7082f73p+5 + 0x1.a22b920c46297p-1i,
0x1.ef3d8cf9a1e28p+4 + -0x1.953553233be26p-1i, -0x1.01935fa82b453p+5 + 0x1.87d8b4ed42b3cp-1i,
0x1.2cafdc3e1f58p+5 + -0x1.7a19179aa76b9p-1i, -0x1.8f0fd056789eep+5 + 0x1.6bf9f45e6d039p-1i
)
assertThat(stats:::fft(inverse=TRUE,z=c(0+0i, -0.396561834320232-0.024372748716788i, -0.28432164502396+0.339319792587066i,
-0.620594718922276-0.10649969455841i, 0.108705040960789+0.458149855844331i,
0.40638105127794+0.012897726771608i, 0.135564164394107+0.370351089335846i,
0.251373028797265-0.211101842796047i, 0.045156958424782+0.57337159456751i,
-0.526656788780843+0.182831395481868i, 0.38661610155107-0.650816674856556i,
-0.31398053586883-0.619198005177907i, -0.673022632317758+0.134918848739305i,
-0.296436568514828-0.363903182890176i, -0.14596849686517+1.30159362634795i,
-0.201989300142253-0.286464878056107i, 0.02878744633059-0.0194974416715989i,
-0.186104626747335+0.278215987589357i, -0.795575712150335-0.154491865741878i,
0.879334692220646-0.166111132469017i, -0.646755749674721-0.437998250950442i,
-0.892631521629333-0.315083904416331i, 0.240501548686706-0.374813279343272i,
-0.47436267466043+0.212951213125411i, 0.383719402999875+0.39616100299909i,
0.786991706080069-0.2690076172408i, -0.300603988130697-0.412506420747302i,
-0.192549991675432+0.249628486498254i, -0.198642836540144-0.506659373825325i,
0.478335618484215+0.29968168427157i, -0.41103148524016-1.03263543246051i,
0.639363332355193+0.07411893759564i, 0.240065693912277-0.199120174781489i,
-0.615100323552481+0.15986935775391i, 0.710961269166329+0.10554140765429i,
-0.059751991180992+0.360756275049991i, 0.166147379823367-0.696574895115799i,
-0.66765074476524+0.397481919164031i, -0.577993418266634+0.651858573525498i,
-0.411436421619755-0.078475189688077i, 0.238499540639731+0.543068154200646i,
0.301915344669532-0.028769607006748i, -1.54714406297586+0.26060959944474i,
-0.023832187436743-0.405969047495457i, -0.182619528958946+0.164805837091805i,
-0.951314145779893+0.509190538654523i, -0.980920021111176-0.107734813096732i,
1.30846884951779-0.96821553381075i, -1.0618488903508-0.78724546659495i,
-0.400603867794963+0.379556963059384i, 0.28117458347093-0.622739223198561i,
-0.49796900732028-1.50589889103862i, -0.697664083594947+0.215087388589197i,
0.395075318164222-0.382802882532146i, -0.905616409631566+0.580670630225823i,
-0.627272339383443+0.148462932321139i, 0.784560002336236+0.086690829191364i,
0.810629187591171+0.147199772565962i, 0.379140859534258-0.359789344124069i,
-0.346506144636815+0.860727537282235i, 0.079936869956405+0.679281358826091i,
1.27626558733918-0.25330199654913i, -0.176436521512317+0.13770284742425i,
-0.811034187103375+0.474582228678482i, 0.08895041760163+0.706474600674585i,
0.51300435483445-0.531648817395907i, 0.021784857581428+0.966710280703996i,
-0.453208823121029-0.837082852692895i, 0.401401778808807-0.888143393084041i,
-0.546136171243711-0.096607724166328i, 0.548445762636905-0.041018242908347i,
0.623073104284608+0.016921227165896i, 1.12789007401103-0.9150144873193i,
0.08449073290851-1.02166609097454i, 0.547339284992691-0.336889819051726i,
-0.122833454690072+0.854659649355527i, -1.08317093273628-0.23036104725795i,
-0.494782073526916+0.633965520491397i, -0.842318244665128-0.364163119422319i,
-0.211720451852483+0.699364394495562i, -0.178348938556155-0.20819645511782i,
0.31338397456145-0.070005564582076i, 0.099274131040962-0.720117872696125i,
0.86566540189477+0.770837403863086i, -0.65601911618425+1.42426818279974i,
1.00637929936948+0.02247486200823i, -0.443756894757003+0.203591444202617i,
-0.232480240910631-0.852823935033055i, -1.55043980543671+0.58712726232882i,
0.094019483325701-0.509699071248611i, 0.528345251825436+0.1934551151723i,
-0.92671244183002+0.4654172825118i, 0.079701505394056-0.671928588981395i,
-0.928504558018547+0.595035492436651i, 0.687600152134093-0.686832833249492i,
1.02817865022983-0.34504589703951i, 0.256026925938355+0.78597632767588i,
0.780553609215519+0.074805609810367i, 0.226302462406668+0.622953020607153i,
-0.350523520293236+0i, 36.95629+0i, 0.560619738092407-0.682608501712159i,
0.226302462406668-0.622953020607153i, 0.78055360921552-0.074805609810367i,
0.256026925938355-0.785976327675879i, 1.02817865022983+0.34504589703951i,
0.687600152134093+0.686832833249492i, -0.928504558018547-0.595035492436651i,
0.079701505394057+0.671928588981395i, -0.92671244183002-0.4654172825118i,
0.528345251825436-0.1934551151723i, 0.094019483325701+0.509699071248611i,
-1.5504398054367-0.58712726232882i, -0.232480240910631+0.852823935033055i,
-0.443756894757003-0.203591444202617i, 1.00637929936948-0.02247486200823i,
-0.65601911618425-1.42426818279974i, 0.86566540189477-0.770837403863086i,
0.099274131040962+0.720117872696125i, 0.31338397456145+0.070005564582076i,
-0.178348938556155+0.20819645511782i, -0.211720451852483-0.699364394495563i,
-0.842318244665128+0.364163119422319i, -0.494782073526916-0.633965520491396i,
-1.08317093273628+0.23036104725795i, -0.122833454690072-0.854659649355527i,
0.54733928499269+0.336889819051726i, 0.08449073290851+1.02166609097454i,
1.12789007401103+0.9150144873193i, 0.623073104284608-0.016921227165896i,
0.548445762636905+0.041018242908347i, -0.546136171243711+0.096607724166328i,
0.401401778808807+0.888143393084041i, -0.453208823121029+0.837082852692895i,
0.021784857581428-0.966710280703997i, 0.51300435483445+0.531648817395907i,
0.08895041760163-0.706474600674586i, -0.811034187103375-0.474582228678482i,
-0.176436521512317-0.13770284742425i, 1.27626558733918+0.25330199654913i,
0.079936869956406-0.679281358826093i, -0.346506144636815-0.860727537282235i,
0.379140859534258+0.359789344124069i, 0.810629187591171-0.147199772565962i,
0.784560002336236-0.086690829191364i, -0.627272339383443-0.148462932321139i,
-0.905616409631566-0.580670630225823i, 0.395075318164222+0.382802882532146i,
-0.697664083594948-0.215087388589197i, -0.49796900732028+1.50589889103862i,
0.28117458347093+0.622739223198561i, -0.400603867794963-0.379556963059384i,
-1.0618488903508+0.78724546659495i, 1.30846884951779+0.96821553381075i,
-0.980920021111176+0.107734813096732i, -0.951314145779893-0.509190538654523i,
-0.182619528958946-0.164805837091805i, -0.023832187436743+0.405969047495457i,
-1.54714406297586-0.26060959944474i, 0.301915344669532+0.028769607006748i,
0.238499540639731-0.543068154200646i, -0.411436421619755+0.078475189688077i,
-0.577993418266634-0.651858573525498i, -0.667650744765241-0.397481919164031i,
0.166147379823367+0.696574895115799i, -0.059751991180992-0.360756275049991i,
0.71096126916633-0.10554140765429i, -0.615100323552481-0.15986935775391i,
0.240065693912277+0.199120174781489i, 0.639363332355193-0.07411893759564i,
-0.41103148524016+1.03263543246051i, 0.478335618484214-0.29968168427157i,
-0.198642836540144+0.506659373825325i, -0.192549991675432-0.249628486498254i,
-0.300603988130697+0.412506420747302i, 0.786991706080069+0.2690076172408i,
0.383719402999875-0.39616100299909i, -0.47436267466043-0.212951213125411i,
0.240501548686706+0.374813279343272i, -0.892631521629332+0.315083904416331i,
-0.646755749674719+0.43799825095044i, 0.879334692220646+0.166111132469017i,
-0.795575712150335+0.154491865741878i, -0.186104626747335-0.278215987589357i,
0.0287874463305901+0.0194974416715989i, -0.201989300142253+0.286464878056107i,
-0.14596849686517-1.30159362634795i, -0.296436568514828+0.363903182890176i,
-0.673022632317758-0.134918848739305i, -0.31398053586883+0.619198005177907i,
0.38661610155107+0.650816674856556i, -0.526656788780843-0.182831395481868i,
0.045156958424782-0.57337159456751i, 0.251373028797265+0.211101842796047i,
0.135564164394107-0.370351089335846i, 0.40638105127794-0.012897726771608i,
0.108705040960789-0.458149855844331i, -0.620594718922276+0.10649969455841i,
-0.284321645023961-0.339319792587066i, -0.396561834320232+0.024372748716788i
))
, identicalTo( expected, tol = 1e-6 ) ) |
last_n_months <-
function(x = Sys.Date(),
n = 1,
part = getOption("timeperiodsR.parts"),
include_current = F) {
if ( ! "Date" %in% class(x) ) {
x <- as.Date(x)
}
start <- floor_date( x, unit = "month" ) - months(n)
stop <- start + months(n + ifelse( include_current, 1, 0)) - days(1)
out <- custom_period(start, stop)
part <- match.arg(part, getOption("timeperiodsR.parts"))
if ( part == "all" ) {
return(out)
} else {
return(out[[part]])
}
} |
data("WeatherPlay", package = "partykit")
sp_o <- partykit::partysplit(1L, index = 1:3)
sp_h <- partykit::partysplit(3L, breaks = 75)
sp_w <- partykit::partysplit(4L, index = 1:2)
partykit::character_split(sp_o)
pn <- partykit::partynode(1L, split = sp_o, kids = list(
partykit::partynode(2L, split = sp_h, kids = list(
partykit::partynode(3L, info = "yes"),
partykit::partynode(4L, info = "no"))),
partykit::partynode(5L, info = "yes"),
partykit::partynode(6L, split = sp_w, kids = list(
partykit::partynode(7L, info = "yes"),
partykit::partynode(8L, info = "no")))))
py <- partykit::party(pn, WeatherPlay) |
smacofSphere <- function(delta, ndim = 2, type = c("ratio", "interval", "ordinal","mspline"),
algorithm = c("dual", "primal"),
weightmat = NULL, init = "torgerson", ties = "primary", verbose = FALSE,
penalty = 100, relax = FALSE, modulus = 1, itmax = 1000, eps = 1e-6,
spline.degree = 2, spline.intKnots = 2)
{
alg <- match.arg(algorithm, c("dual", "primal"))
type <- match.arg(type, c("ratio", "interval", "ordinal","mspline"), several.ok = FALSE)
if (alg == "dual") {
diss <- delta
if ((is.matrix(diss)) || (is.data.frame(diss))) diss <- strucprep(diss)
checkdiss(diss)
p <- ndim
n <- attr(diss,"Size")
if (p > (n - 1)) stop("Maximum number of dimensions is n-1!")
nn <- n*(n-1)/2
m <- length(diss)
if (is.null(attr(diss, "Labels"))) attr(diss, "Labels") <- paste(1:n)
if (is.null(weightmat)) {
wgths <- initWeights(diss)
} else wgths <- as.dist(weightmat)
dhat <- normDissN(diss,wgths,1)
dhat[is.na(dhat)] <- 1
x <- initConf(init, diss, n, p)
xstart <- x
if (relax) relax <- 2 else relax <- 1
mn <- c(1,rep(0,n))
diss <- as.dist(rbind(0,cbind(0,as.matrix(diss))))
wgths1 <- as.dist(rbind(0,cbind(0,as.matrix(wgths))))
wgths2 <- as.dist(outer(mn,mn,function(x,y) abs(x-y)))
dhat1 <- as.dist(rbind(0,cbind(0,as.matrix(dhat))))
dhat2 <- mean(sqrt(rowSums(x^2)))*wgths2
n1 <- attr(dhat1,"Size")
nn1 <- n1*(n1-1)/2
x <- rbind(0,x)
w <- vmat(wgths1+penalty*wgths2); v<-myGenInv(w); itel<-1;
d <- dist(x)
lb <- sum(wgths1*d*dhat1)/sum(wgths1*d^2)
x <- lb*x
d <- lb*d
sold1 <- sum(wgths1*(dhat1-d)^2)
sold2 <- sum(wgths2*(dhat2-d)^2)
sold <- sold1+penalty*sold2
trans <- type
if (trans=="ratio"){
trans <- "none"
} else if (trans=="ordinal" & ties=="primary"){
trans <- "ordinalp"
} else if(trans=="ordinal" & ties=="secondary"){
trans <- "ordinals"
} else if(trans=="ordinal" & ties=="tertiary"){
trans <- "ordinalt"
} else if(trans=="spline"){
trans <- "mspline"
}
disobj <- transPrep(diss,trans = trans, spline.intKnots = spline.intKnots, spline.degree = spline.degree)
repeat
{
b <- bmat(dhat1,wgths1,d)+penalty*bmat(dhat2,wgths2,d)
y <- v %*% (b %*% x)
y <- x+relax*(y-x)
e <- dist(y)
ssma1 <- sum(wgths1*(dhat1-e)^2)
ssma2 <- sum(wgths2*(dhat2-e)^2)
ssma <- ssma1+penalty*ssma2
dhat3 <- transform(e, disobj, w = wgths1, normq = nn1)
dhat1 <- vecAsDist(dhat3$res)
dhat2 <- mean(e[1:n])*wgths2
snon1 <- sum(wgths1*(dhat1-e)^2)
snon2 <- sum(wgths2*(dhat2-e)^2)
snon <- snon1+penalty*snon2
if (verbose) cat("Iteration: ",formatC(itel,width=3, format="d")," Stress (not normalized): ",
formatC(c(snon),digits=8,width=12,format="f"),"\n")
if (((sold-snon)<eps) || (itel == itmax)) break()
x <- y
d <- e
sold <- snon
itel <- itel+1
if (itel == itmax) warning("Iteration limit reached! Increase itmax argument!")
}
colnames(y) <- paste("D",1:(dim(y)[2]),sep="")
rownames(y) <- labels(diss)
ss <- y[1,]
y <- t(apply(y, 1, function(xx) xx - ss)[,-1] )
confdiss <- dist(y)
attr(dhat1, "Labels") <- labels(diss)
attr(e, "Labels") <- labels(diss)
stress <- sqrt(snon/nn)
e.temp <- as.dist(as.matrix(e)[,-1][-1,])
dummyvec <- as.matrix(e)[,1][-1]
dhat <- as.dist(as.matrix(dhat1)[-1,-1])
spoint <- spp(dhat, confdiss, wgths)
rss <- sum(spoint$resmat[lower.tri(spoint$resmat)])
dhat3$iord.prim <- order(as.vector(as.dist(delta)), as.vector(as.dist(dhat)), na.last = TRUE)
} else {
diss <- delta
if ((is.matrix(diss)) || (is.data.frame(diss))) diss <- strucprep(diss)
checkdiss(diss)
p <- ndim
n <- attr(diss,"Size")
if (p > (n - 1)) stop("Maximum number of dimensions is n-1!")
nn <- n*(n-1)/2
m <- length(diss)
if (is.null(attr(diss, "Labels"))) attr(diss, "Labels") <- paste(1:n)
if (is.null(weightmat)) {
wgths <- initWeights(diss)
} else wgths <- as.dist(weightmat)
dhat <- normDissN(diss,wgths,1)
dhat[is.na(dhat)] <- 1
x <- initConf(init, diss, n, p)
xstart <- x
w <- vmat(wgths)
v <- myGenInv(w)
itel<-1;
x <- x/sqrt(rowSums(x^2))
d <- dist(x)
lb <- sum(wgths*d*dhat)/sum(wgths*d^2)
x <- lb*x
d <- lb*d
sold <- sum(wgths*(dhat-d)^2)
trans <- type
if (trans=="ratio"){
trans <- "none"
} else if (trans=="ordinal" & ties=="primary"){
trans <- "ordinalp"
} else if(trans=="ordinal" & ties=="secondary"){
trans <- "ordinals"
} else if(trans=="ordinal" & ties=="tertiary"){
trans <- "ordinalt"
} else if(trans=="spline"){
trans <- "mspline"
}
disobj <- transPrep(diss,trans = trans, spline.intKnots = spline.intKnots, spline.degree = spline.degree)
repeat {
b <- bmat(dhat,wgths,d)
y <- v%*%b%*%x
y <- sphereProj(y,w)
e <- dist(y)
ssma <- sum(wgths*(dhat-e)^2)
dhat3 <- transform(e, disobj, w = wgths, normq = nn)
dhat <- dhat3$res
snon <- sum(wgths*(dhat-e)^2)
if (verbose) cat("Iteration: ",formatC(itel,width=3, format="d")," Stress (not normalized): ",
formatC(c(snon),digits=8,width=12,format="f"),"\n")
if (((sold-snon)<eps) || (itel == itmax)) break()
x <- y
d <- e
sold <- snon
itel <- itel+1
}
colnames(y) <- paste("D",1:(dim(y)[2]),sep="")
rownames(y) <- labels(diss)
attr(dhat, "Labels") <- labels(diss)
attr(e, "Labels") <- labels(diss)
dhat[is.na(diss)] <- NA
stress <- sqrt(snon/nn)
confdiss <- normDissN(e, wgths, 1)
spoint <- spp(dhat, dist(y), wgths)
rss <- sum(spoint$resmat[lower.tri(spoint$resmat)])
dummyvec <- NA
if (itel == itmax) warning("Iteration limit reached! Increase itmax argument!")
}
result <- list(delta = delta, dhat = dhat, confdist = dist(y), iord = dhat3$iord.prim, conf = y,
stress = stress, spp = spoint$spp, ndim = p, weightmat = wgths, resmat = spoint$resmat, rss = rss,
dummyvec = dummyvec, init = xstart,
model = "Spherical SMACOF", niter = itel, nobj = n, type = type,
algorithm = alg, call = match.call())
class(result) <- c("smacofSP", "smacof")
result
} |
observationGradient <- function(g, nParam) {
if(is.null(dim(g))) {
if(nParam == 1 & length(g) > 1)
return(TRUE)
return(FALSE)
}
if(nrow(g) == 1)
return(FALSE)
return(TRUE)
} |
div(id = "d1_ui",
tagList(
textInput(
"id",
label = "Import from dataONE",
placeholder = "Enter doi or id here"
),
actionBttn(inputId = "D1Button", label = "Download", size = "sm", color = "success"),
hr(),
conditionalPanel(condition="$('html').hasClass('shiny-busy')",
tags$div(id="loadmessage",
HTML(paste0("<div> <h3>Download in Progress.</h3> <p>This download may take a couple of minutes.</p> <img src=\'http://www.lettersmarket.com/uploads/lettersmarket/blog/loaders/common_green/ajax_loader_green_64.gif' height=\"64\" width=\"64\"> </div>"))
)),
DT::DTOutput("identifier"),
div(id = "nextFromD1_div",
fluidRow(
column(8),
column(4,
actionBttn(inputId = "nextFromD1", label = "Next Step", size = "sm", color = "success")
)
)
),
shinyjs::hidden(
div(id = "d1_new_dir_output",
hr(),
p("Location of Downloaded files:"),
verbatimTextOutput("D1dbfilesPath")
)
)
)
) |
knitr::opts_chunk$set(echo = TRUE)
library(flagr)
head(test_data)
summary(test_data)
library(tidyr)
flags <- spread(test_data[, c(1:3)], key = time, value = flags)
propagate_flag(flags[, c(2:ncol(flags))],"hierarchy","puebscd")
propagate_flag(flags[, c(2:ncol(flags))],"hierarchy",c("b","c","d","e","p","s","u"))
library(tidyr)
flags <- spread(test_data[, c(1:3)], key = time, value = flags)
propagate_flag(flags[, c(2:ncol(flags))],"frequency")
library(tidyr)
flags <- spread(test_data[, c(1:3)], key = time, value = flags)
weights <- spread(test_data[, c(1, 3:4)], key = time, value = values)
flags<-flags[, c(2:ncol(flags))]
weights<-weights[, c(2:ncol(weights))]
propagate_flag(flags,"weighted",flag_weights=weights)
propagate_flag(flags,"weighted",flag_weights=weights,threshold=0.1) |
getFunctionEnvelopeCat <- function(data,R=1000,initial,x){
fn <- function(data,index,x,initial){
data <- data[index,]
c1 <- initial[1];c2 <- initial[2]; lambda <- initial[3]
pred <- rep(NA,length(x))
tryCatch({obs.cat <- nls(y ~ c1 * cosh( (x-c2)/c1) + lambda,
data=data,
start=list(c1=c1,c2=c2,lambda=lambda))
pred <- predict(obs.cat,newdata=data.frame(x=x))
}, error = function(e){
cat("cannot fit catenary\n")
})
return(pred)
}
b <- boot::boot(data=data,statistic=fn,R=R,x=x,initial=initial)
tmp <- apply(b$t,2,quantile,probs=c(0.025,0.975),na.rm=TRUE)
bounds <- data.frame(x=x,lwr=tmp[1,],upr=tmp[2,])
return(bounds)
} |
working.cltsk <-
function(q0,obs,th,bins,vth,vlen,llim,verbose,Large,future)
{
ii <- dnb(q0,obs,th,future=future)
if( length(ii)<=5 ){
if(verbose) cat(q0,'k= ',length(ii),'\n')
r <- (list(fout=NULL,nbr=NULL,ret=3))
}
else{
ssout <- dsubsample(obs[ii,],Large=Large)
nbr <- ssout$nbr
if(verbose)
{
with(ssout,cat(q0,'k= ',nrow(nbr),'ns=',ns,'nt=',nt,'\n'))
}
if( (ssout$ns > llim[1]) && (ssout$nt > llim[2]) )
{
vout <- dvariogram(nbr,vth,vlen)
vout <- dsmooth.variogram(vout)
fout <- dfitvariogram(vout,nbr)
if(fout$ret){
r <- list(fout=fout,nbr=nbr,ret=0)
}
else{
r <- (list(fout=NULL,nbr=nbr,ret=4))
}
}else if(ssout$nt <= llim[2]){
if (verbose) cat('insufficient time points.\n')
r <- (list(fout=NULL,nbr=nbr,ret=1))
}else if(ssout$ns <= llim[1]){
if (verbose) cat('insufficient space points.\n')
r <- (list(fout=NULL,nbr=nbr,ret=2))
}else{
if (verbose) cat('insufficient space & time points.\n')
r <- (list(fout=NULL,nbr=nbr,ret=3))
}
}
output <- rep(NA,nrow(bins))
working.cltsk.calkriging <- function(q0, nbr, binsth,fout,verbose,future)
{
jj <- dnb(q0,nbr,binsth,future=future)
if(verbose)
{
cat(binsth,'k=',length(jj),'\n')
}
output <- NA
if( length(jj) >=3)
{
gout <- cal.gamma(q0,nbr[jj,],fout)
output <- with(gout,work.kriging(Gamma,gamma,dat[,4])[1])
}
output
}
if( !is.null(r$fout))
{
output <- apply(bins,1, working.cltsk.calkriging,q0=q0,nbr=r$nbr,fout=r$fout,verbose=verbose,future=future)
}
output
} |
if(F) {
library(disk.frame)
library(dplyr)
setup_disk.frame()
a = disk.frame("c:/data/fannie_mae_disk_frame/fm.df/")
pt=proc.time()
a %>% map(~{
.x
NULL
}
, lazy = F
)
data.table::timetaken(pt)
pt=proc.time()
srckeep(a,c("monthly.rpt.prd", "loan.age"))[,mean(loan.age), monthly.rpt.prd]
data.table::timetaken(pt)
pt=proc.time()
srckeep(b,c("monthly.rpt.prd", "loan.age"))[,mean(loan.age), monthly.rpt.prd]
data.table::timetaken(pt)
b = disk.frame("d:/fm.df")
pt=proc.time()
b %>% map(~{
.x
NULL
}
, lazy = F
)
data.table::timetaken(pt)
} |
context("Integer division operations")
test_that("integer division concatenates and recycles correctly", {
int1 <- ymd("2010-01-01") %--% ymd("2011-01-01")
int2 <- ymd("2009-01-01") %--% ymd("2011-01-01")
int3 <- ymd("2009-01-01") %--% ymd("2010-01-01")
expect_equal(int1 %/% ddays(1:2), c(365, 182))
expect_equal(int1 %/% days(1:2), c(365, 182))
expect_equal(c(int1, int2) %/% ddays(2), c(182, 365))
expect_equal(c(int1, int2) %/% days(2), c(182, 365))
expect_equal(dyears(1) %/% ddays(1:2), c(365, 182))
expect_equal(dyears(1:2) %/% ddays(2), c(182, 365))
expect_equal(months(c(13, 26)) %/% years(2), c(0, 1))
expect_equal(months(13) %/% years(c(1, 2)), c(1, 0))
})
test_that("integer division works for interval numerator", {
verify_output(test_path("test-ops-integer-division.txt"), {
int <- ymd("2010-01-01") %--% ymd("2010-06-01")
dur <- ddays(1)
per <- months(1)
"
int %/% int
int %/% dur
int %/% per
"
dur %/% int
dur %/% dur
dur %/% per
"
per %/% int
per %/% dur
per %/% per
})
}) |
casesDialogFin <-
function () {
defaults <- list (initial.year1 = 1, initial.month1 = 5, initial.day1 = 0,
initial.year2 = 0, initial.month2 = NULL, initial.day2 = NULL,
initial.x = 0, initial.measure = "new_cases", initial.permillion = "FALSE",
initial.mean = TRUE, initial.bar=FALSE,initial.atop=FALSE)
dialog.values <- getDialog ("casesDialogFin", defaults)
initializeDialog(title = gettextRcmdr("Covid cases in Finland"))
measureVariable <- tclVar(dialog.values$initial.measure)
permillionVariable <- tclVar(dialog.values$initial.permillion)
meanVariable <- tclVar(dialog.values$initial.mean)
barVariable <- tclVar(dialog.values$initial.bar)
atopVariable <- tclVar(dialog.values$initial.atop)
years <- c("None",2020:2022)
months <- c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
days <- 1:31
utils::data(popRegionsFin)
utils::data(dataCovidFin)
regions <- popRegionsFin$Alue
mainFrame <- tkframe(top)
regionFrame <- tkframe(mainFrame)
xBox <- variableListBox(regionFrame, regions, title = gettextRcmdr("Region (pick one or more)"),initialSelection = dialog.values$initial.x,
selectmode="multiple")
middleFrame <- tkframe(mainFrame)
rightFrame <- tkframe(mainFrame)
dataFrame <- tkframe(top)
year1Box <- variableListBox(dataFrame, years,
title = gettextRcmdr("Year"),initialSelection = dialog.values$initial.year1)
month1Box <- variableListBox(dataFrame, months,
title = gettextRcmdr("Month"),
initialSelection = dialog.values$initial.month1)
day1Box <- variableListBox(dataFrame, days,
title = gettextRcmdr("Day"),
initialSelection = dialog.values$initial.day1)
year2Box <- variableListBox(dataFrame, years,
title = gettextRcmdr("Year"),initialSelection = dialog.values$initial.year2)
month2Box <- variableListBox(dataFrame, months,
title = gettextRcmdr("Month"),
initialSelection = dialog.values$initial.month2)
day2Box <- variableListBox(dataFrame, days,
title = gettextRcmdr("Day"),
initialSelection = dialog.values$initial.day2)
onOK <- function() {
x <- getSelection(xBox)
xc <- paste0("c('",paste0(x,collapse="','"),"')")
nRegions <- length(x)
if (nRegions == 0) {
errorCondition(recall = incidenceDialog, message = gettextRcmdr("You must select at least one region."))
return()
}
xi <- numeric(nRegions)
for(i in 1:nRegions) xi[i] <- which(x[i]==regions)
year1 <- getSelection(year1Box)
year1.i <- (0:12)[year1==years]
month1 <- (1:12)[getSelection(month1Box)==months]
month1.i <- month1-1
day1 <- getSelection(day1Box)
day1.i <- day1-1
year2 <- getSelection(year2Box)
year2.i <- (0:12)[year2==years]
month2 <- (1:12)[getSelection(month2Box)==months]
month2.i <- month2-1
day2 <- getSelection(day2Box)
day2.i <- day2-1
date1 <- paste(year1,month1,day1,sep="-")
date2 <- paste(year2,month2,day2,sep="-")
measure <- tclvalue(measureVariable)
permillion <- tclvalue(permillionVariable)
mean <- as.logical(as.numeric(tclvalue(meanVariable)))
bar <- as.logical(as.numeric(tclvalue(barVariable)))
atop <- as.logical(as.numeric(tclvalue(atopVariable)))
putDialog ("casesDialogFin",list (initial.year1 = year1.i, initial.month1 = month1.i,
initial.day1 = day1.i, initial.year2 = year2.i, initial.month2 = month2.i,
initial.day2 = day2.i, initial.x = xi-1,initial.measure = measure,
initial.permillion = permillion,initial.mean = mean, initial.bar = bar, initial.atop=atop))
closeDialog()
if(year1!="None" && year2!="None"){
doItAndPrint(paste0("drawBarsFin(data=dataCovidFin, pop=popRegionsFin, regions=",xc,",start='",date1,"',end='",date2,"',measure='",measure,
"',perMillion=",permillion,",drawMean=",mean,",bars=",bar,",atop=",atop,")"))}else
if (year1!="None"){
doItAndPrint(paste0("drawBarsFin(data=dataCovidFin, pop=popRegionsFin, regions=",xc,",start='",date1,"',measure='",measure,"',perMillion=",permillion,",drawMean=",mean,",bars=",bar,",atop=",atop,")"))}else
if (year2!="None"){
doItAndPrint(paste0("drawBarsFin(data=dataCovidFin, pop=popRegionsFin, regions=",xc,",start=NULL, end='",date2,"',measure='",measure,"',perMillion=",permillion,",drawMean=",mean,",bars=",bar,",atop=",atop,")"))} else{
doItAndPrint(paste0("drawBarsFin(data=dataCovidFin, pop=popRegionsFin, regions=",xc,",start=NULL, measure='",measure,"',perMillion=",permillion,",drawMean=",mean,",bars=",bar,",atop=",atop,")"))
}
tkdestroy(top)
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject = "drawBarsFin", reset = "casesDialogFin", apply = "casesDialogFin")
measureFrame <- tkframe(middleFrame)
permillionFrame <- tkframe(rightFrame)
optionsFrame <- tkframe(rightFrame)
radioButtons(middleFrame, name = "measure", buttons = c("newcases", "totalcases"), values = c("new_cases","total_cases"),
labels = gettextRcmdr(c("New cases", "Total cases")),
title = gettextRcmdr("Measure "),
initialValue = dialog.values$initial.measure)
radioButtons(rightFrame, name = "permillion", buttons = c("yes",
"no"), values = c("TRUE", "FALSE"),
labels = gettextRcmdr(c("Yes", "No")),
title = gettextRcmdr("Per million?"),
initialValue = dialog.values$initial.permillion)
checkBoxes(window=rightFrame,frame="optionsFrame", boxes=c("mean","bar","atop"),
initialValues=c(dialog.values$initial.mean,dialog.values$initial.bar,
dialog.values$initial.atop),
labels=gettextRcmdr(c("Mean curve","Bars","Atop")),title="Options")
tkgrid(getFrame(xBox), sticky = "nw")
tkgrid(measureFrame, padx=c(20,0),pady=c(0,10),sticky="w")
tkgrid(permillionFrame, padx=c(20,0),sticky="w")
tkgrid(optionsFrame, padx=c(20,0), pady=c(10,0),sticky="w")
tkgrid(regionFrame, middleFrame, rightFrame)
tkgrid(mainFrame, sticky = "w")
tkgrid(labelRcmdr(dataFrame, text="First date",fg="red"),sticky="w")
tkgrid(getFrame(year1Box), getFrame(month1Box),
getFrame(day1Box), sticky = "nw",pady=c(0,10))
tkgrid(labelRcmdr(dataFrame, text="Second date (optional)",fg="red"),sticky="w")
tkgrid(getFrame(year2Box), getFrame(month2Box),
getFrame(day2Box), sticky = "nw")
tkgrid(dataFrame, sticky="w")
tkgrid(buttonsFrame, columnspan = 2, sticky = "w")
dialogSuffix()
} |
plot.bvarfevd <- function(x, ...) {
par_orig <- graphics::par("mar")
graphics::par(mar = c(5.1, 4.1, 4.1, 7.1))
graphics::barplot(t(x), ylab = "Percentage", xlab = "Period", names.arg = stats::time(x), ...)
graphics::par(mar = par_orig)
legend_names <- dimnames(x)[[2]]
graphics::legend("left", legend = legend_names, xpd = FALSE, fill = grDevices::gray.colors(NCOL(x)), inset = 1)
} |
inner_Add_Symbol <- function(character,symbol="+"){
if (length(character)>=2){
for (character.i in 1:length(character)) {
if (character.i==1){
adj=character[1]
}else{
adj=paste0(adj,symbol,character[character.i])
}
}
}else{
adj=character
}
adj
} |
fpath = system.file("testdata", package = "smerc")
data(nydf)
data(nyw)
coords = with(nydf, cbind(longitude, latitude))
set.seed(1)
cepp_test_ref = cepp.test(coords = coords,
cases = floor(nydf$cases),
pop = nydf$pop,
nstar = 1000, alpha = 0.1)
fname = paste(fpath, "/cepp_test_ref.rda", sep = "")
save(cepp_test_ref,
compress = "bzip2",
file = fname,
version = 2) |
trandn <- function(l, u){
if(any(l>u)){
stop('Truncation limits have to be vectors of the same length with l<u')
}
x=rep(0,length(l));
a=.4;
I <- l>a;
if (any(I)){
x[I] <- ntail(l[I], u[I]);
}
J <- u < (-a);
if (any(J)){
x[J] <- -ntail(-u[J],-l[J]);
}
L <- !(I|J);
if (any(L)){
x[L] <- tn(l[L],u[L]);
}
return(x)
} |
create_nb_code_for_component <- function(comp) {
df <- create_analysis_sample()
if (comp == "setup") return({
nb_code <- c(
"
"```{r setup}",
"suppressWarnings(suppressMessages({",
" library(knitr)",
" library(kableExtra)",
" library(htmltools)",
" library(tidyverse)",
" library(scales)",
" library(ExPanDaR)",
"}))",
"knitr::opts_chunk$set(fig.align = 'center')",
"```", " ", " "
)
})
if (comp == "create_sample") return({
nb_code <- c(
"
"This step reads the raw data provided by `ExPanD()` and generates the sample for the analysis.",
" ",
"```{r create_sample}",
"create_sample <- function(df, df_def) {",
"
" df[, df_def$var_name[df_def$type == \"numeric\"]] <-",
" lapply(df[, df_def$var_name[df_def$type == \"numeric\"]],",
" function(x) ifelse(is.finite(x), x, NA))",
" ",
"
" all_na_vars <- sapply(df, function (x) all(is.na(x)))",
" df_def <- df_def[!all_na_vars,]",
" df <- df[, df_def$var_name]",
" ",
"
" df <- df[complete.cases(df[, df_def$var_name[which(df_def$can_be_na == FALSE)]]), ]"
)
if ((uc$subset_factor != "Full Sample") & (uc$subset_value != "All"))
nb_code <- c(nb_code,
" ",
"
sprintf(' df <- df[which(df$%s == "%s"), ]', uc$subset_factor, uc$subset_value))
if (uc$balanced_panel)
nb_code <- c(nb_code,
" ",
"
' df <- group_by_at(df, vars(one_of(df_def$var_name[df_def$type == "cs_id"]))) %>%',
' mutate(nobs = n())',
' max_nobs <- length(levels(as.data.frame(df[, df_def$var_name[df_def$type == "ts_id"]])[,1]))',
' bal_df <- as.data.frame(select(filter(df, nobs == max_nobs), -nobs))',
' df <- as.data.frame(bal_df)')
if (uc$outlier_treatment > 1) {
if (uc$outlier_factor == "None")
group <- "NULL"
else
group <- sprintf('"%s"', df[,uc$outlier_factor])
nb_code <- c(nb_code,
" ",
"
' nums <- df_def$var_name[df_def$type == "numeric"]')
}
if (uc$outlier_treatment == 2)
nb_code <- c(nb_code, sprintf(' df[, nums] <- treat_outliers(df[, nums], 0.01, FALSE, %s)', group))
if (uc$outlier_treatment == 3)
nb_code <- c(nb_code, sprintf(' df[, nums] <- treat_outliers(df[, nums], 0.05, FALSE, %s)', group))
if (uc$outlier_treatment == 4)
nb_code <- c(nb_code, sprintf(' df[, nums] <- treat_outliers(df[, nums], 0.01, TRUE, %s)', group))
if (uc$outlier_treatment == 5)
nb_code <- c(nb_code, sprintf(' df[, nums] <- treat_outliers(df[, nums], 0.05, TRUE, %s)', group))
nb_code <- c(nb_code,
" ",
" df <- droplevels(df)",
" return(list(df = df, df_def = df_def))",
"}",
" ",
"load(\"ExPanD_nb_data.Rdata\")",
" ",
"smp_list <- create_sample(nb_df, nb_df_def)",
"smp <- smp_list$df",
"smp_def <- smp_list$df_def",
"```", " ", " ")
nb_code
})
if (comp == "bar_chart") return({
nb_code <- c(
"
"```{r bar_chart}",
"df <- smp"
)
if (uc$bar_chart_group_by != "All")
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s", ]',
uc$group_factor,
uc$bar_chart_group_by))
nb_code <- c(nb_code,
sprintf('df$%s <- as.factor(df$%s)', uc$bar_chart_var1, uc$bar_chart_var1))
if (uc$bar_chart_var2 != "None")
nb_code <- c(nb_code,
sprintf('df$%s <- as.factor(df$%s)', uc$bar_chart_var2, uc$bar_chart_var2))
if (uc$bar_chart_var2 != "None" & (!uc$bar_chart_relative)) {
nb_code <- c(nb_code,
sprintf('p <- ggplot(df, aes(x = %s)) +', uc$bar_chart_var1),
sprintf(' geom_bar(aes(fill= %s), position = "stack") +', uc$bar_chart_var2),
sprintf(' labs(x = "%s", fill = "%s")', uc$bar_chart_var1, uc$bar_chart_var2))
} else if (uc$bar_chart_var2 != "None") {
nb_code <- c(nb_code,
sprintf('p <- ggplot(df, aes(x = %s)) +', uc$bar_chart_var1),
sprintf(' geom_bar(aes(fill = %s), position = "fill") +', uc$bar_chart_var2),
sprintf(' labs(x = "%s", fill = "%s", y = "Percent") +', uc$bar_chart_var1, uc$bar_chart_var2),
'scale_y_continuous(labels = percent_format())')
} else {
nb_code <- c(nb_code,
sprintf('p <- ggplot(df, aes(x = %s)) +', uc$bar_chart_var1),
sprintf('geom_bar() + labs(x = "%s")', uc$bar_chart_var1))
}
if (length(unique(df[,uc$bar_chart_var1])) > 5) {
if (!anyNA(suppressWarnings(as.numeric(df[, uc$bar_chart_var1])))) {
nb_code <- c(
nb_code,
sprintf('p <- p + scale_x_discrete(breaks = pretty(as.numeric(as.character(df$%s)), n = 10))', uc$bar_chart_var1)
)
} else {
nb_code <- c(
nb_code,
"p <- p + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90))"
)
}
}
nb_code <- c(nb_code, "p", "```", " ", " ")
nb_code
})
if(comp == "missing_values") return({
nb_code <- c(
"
"```{r missing_values}",
"df <- smp"
)
if (uc$missing_values_group_by != "All")
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s",]',
uc$group_factor,
uc$missing_values_group_by))
nb_code <- c(nb_code,
sprintf('prepare_missing_values_graph(df, "%s")', lts_id$name),
"```", " ", " ")
nb_code
})
if(comp == "descriptive_table") return({
nb_code <- c(
"
"```{r descriptive_statistics}",
"df <- smp",
"t <- prepare_descriptive_table(smp)",
"t$kable_ret %>%",
' kable_styling("condensed", full_width = F, position = "center")',
"```", " ", " ")
nb_code
})
if(comp == "histogram") return({
nb_code <- c(
"
"```{r histogram}"
)
if (uc$hist_group_by == "All")
nb_code <- c(nb_code,
sprintf('var <- as.numeric(smp$%s)', uc$hist_var))
else
nb_code <- c(nb_code,
sprintf('var <- as.numeric(smp$%s[smp$%s == "%s"])',
uc$hist_var, uc$group_factor, uc$hist_group_by))
nb_code <- c(nb_code,
sprintf('hist(var, main="", xlab = "%s", col="red", right = FALSE, breaks= %d)',
uc$hist_var, uc$hist_nr_of_breaks),
"```", " ", " ")
nb_code
})
if(comp == "ext_obs") return({
nb_code <- c(
"
"```{r extreme_obs}",
"df <- smp")
if (uc$group_factor != "None")
nb_code <- c(nb_code,
sprintf('vars <- c("%s", "%s", "%s", "%s")',
lcs_id$name, lts_id$name, uc$ext_obs_var, uc$group_factor))
else if (!cross_sec_data())
nb_code <- c(nb_code,
sprintf('vars <- c("%s", "%s", "%s")',
lcs_id$name, lts_id$name, uc$ext_obs_var))
else
nb_code <- c(nb_code,
sprintf('vars <- c("%s", "%s")',
lcs_id$name, uc$ext_obs_var))
if (uc$ext_obs_period_by != "All")
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s", ]',
lts_id$name, uc$ext_obs_period_by))
if (uc$ext_obs_group_by != "All")
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s", ]',
uc$group_factor, uc$ext_obs_group_by))
nb_code <- c(nb_code,
"df <- df[, vars]",
"df <- droplevels(df[complete.cases(df), ])",
"if (nrow(df) <= 10) {",
' cat("Not enough data to generate table")',
"} else {",
sprintf(' tab <- prepare_ext_obs_table(df, var = "%s")', uc$ext_obs_var),
" tab$kable_ret %>%",
" kable_styling()",
"}",
"```", " ", " ")
nb_code
})
if(comp == "by_group_bar_graph") return({
nb_code <- c(
"
"```{r by_group_bar_graph}",
"df <- smp")
if (uc$bgbg_stat == "q25")
nb_code <- c(nb_code,
'q25 <- function(x, na.rm) {quantile(x, 0.25, na.rm)}')
if (uc$bgbg_stat == "q75")
nb_code <- c(nb_code,
'q75 <- function(x, na.rm) {quantile(x, 0.75, na.rm)}')
if (uc$bgbg_group_by != "All") {
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s", ]',
uc$group_factor, uc$bgbg_group_by))
}
nb_code <- c(nb_code,
sprintf('prepare_by_group_bar_graph(df, "%s", "%s", %s, %s)$plot +',
uc$bgbg_byvar, uc$bgbg_var, uc$bgbg_stat, uc$bgbg_sort_by_stat),
sprintf(' ylab("%s %s")', uc$bgbg_stat, uc$bgbg_var),
"```", " ", " ")
nb_code
})
if(comp == "by_group_violin_graph") return({
nb_code <- c(
"
"```{r by_group_violin_graph}",
"df <- smp")
if (uc$bgvg_group_by != "All") {
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s", ]',
uc$group_factor, uc$bgvg_group_by))
}
nb_code <- c(nb_code,
sprintf('prepare_by_group_violin_graph(df, "%s", "%s", %s)',
uc$bgvg_byvar, uc$bgvg_var, uc$bgvg_sort_by_stat),
"```", " ", " ")
nb_code
})
if(comp == "trend_graph") return({
nb_code <- c(
"
"```{r trend_graph}",
"df <- smp")
vars <- c(uc$trend_graph_var1, uc$trend_graph_var2, uc$trend_graph_var3)
vars <- vars[which(!vars %in% "None")]
if (uc$trend_graph_group_by != "All") {
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s", ]',
uc$group_factor, uc$trend_graph_group_by))
}
nb_code <- c(nb_code,
sprintf('prepare_trend_graph(df, "%s", c("%s"))$plot',
lts_id$name,
paste(vars, collapse = '", "')),
"```", " ", " ")
nb_code
})
if(comp == "quantile_trend_graph") return({
nb_code <- c(
"
"```{r quantile_trend_graph}",
"df <- smp")
quantiles <- as.numeric(uc$quantile_trend_graph_quantiles)
if (uc$quantile_trend_graph_group_by != "All") {
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s", ]',
uc$group_factor, uc$quantile_trend_graph_group_by))
}
nb_code <- c(nb_code,
sprintf('prepare_quantile_trend_graph(df, "%s", c(%s), "%s")$plot',
lts_id$name, paste(quantiles, collapse = ", "),
uc$quantile_trend_graph_var),
"```", " ", " ")
nb_code
})
if(comp == "by_group_trend_graph") return({
nb_code <- c(
"
"```{r by_group_trend_graph}",
"df <- smp")
if (uc$bgtg_group_by != "All") {
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s", ]',
uc$group_factor, uc$bgtg_group_by))
}
nb_code <- c(nb_code,
sprintf('prepare_by_group_trend_graph(df, "%s", "%s", "%s")$plot',
lts_id$name, uc$bgtg_byvar, uc$bgtg_var),
"```", " ", " ")
nb_code
})
if(comp == "corrplot") return({
nb_code <- c(
"
"```{r corrplot}",
"df <- smp")
if (uc$corrplot_group_by != "All") {
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s", ]',
uc$group_factor, uc$corrplot_group_by))
}
vars <- which(sapply(df, function(x) all(is.numeric(x) | is.logical(x))))
vars <- vars[vars %in% which(!sapply(df, function(x) all(is.na(x))))]
vars <- vars[vars %in% which(!sapply(df, function(x) (all(duplicated(x)[-1]))))]
nb_code <- c(nb_code,
sprintf('ret <- prepare_correlation_graph(df[, c(%s)])', paste(vars, collapse = ", ")),
"```", " ", " ")
nb_code
})
if(comp == "scatter_plot") return({
nb_code <- c(
"
"```{r scatter_plot}",
"df <- smp")
if (uc$scatter_group_by != "All") {
nb_code <- c(nb_code,
sprintf('df <- df[df$%s == "%s", ]',
uc$group_factor, uc$scatter_group_by))
}
vars <- c(lcs_id$name, lts_id$name,
uc$scatter_x, uc$scatter_y, uc$scatter_color, uc$scatter_size)
vars <- vars[which(!vars %in% "None")]
nb_code <- c(nb_code,
sprintf('df <- df[, c("%s")]', paste(vars, collapse = '", "')),
"df <- df[complete.cases(df), ]")
scatter_df <- df[, vars]
scatter_df <- scatter_df[complete.cases(scatter_df), ]
if (uc$scatter_color %in% lfactor$name)
nb_code <- c(nb_code,
sprintf('df$%s <- as.factor(df$%s)', uc$scatter_color, uc$scatter_color))
if (uc$scatter_sample & (nrow(scatter_df) > 1000)) {
nb_code <- c(nb_code,
"set.seed(42)",
"df <- sample_n(df, 1000)")
}
parm_str <- sprintf('"%s", "%s"', uc$scatter_x, uc$scatter_y)
if (uc$scatter_color != "None") parm_str <- paste0(parm_str, sprintf(', color = "%s"', uc$scatter_color))
if (uc$scatter_size != "None") parm_str <- paste0(parm_str, sprintf(', size = "%s"', uc$scatter_size))
if (uc$scatter_loess) parm_str <- paste0(parm_str, ", loess = 1")
nb_code <- c(nb_code,
sprintf('prepare_scatter_plot(df, %s)', parm_str),
"```", " ", " ")
nb_code
})
if(comp == "regression") return({
nb_code <- c(
"
"```{r regression}",
"df <- smp")
vars <- c(uc$reg_y, uc$reg_x, uc$reg_fe1, uc$reg_fe2, uc$reg_by)
vars <- vars[!vars %in% "None"]
nb_code <- c(nb_code,
sprintf('df <- df[, c("%s")]', paste(vars, collapse = '", "')),
"df <- df[complete.cases(df), ]")
if (uc$reg_by != "None")
nb_code <- c(nb_code,
sprintf('df$%s <- as.factor(df$%s)', uc$reg_by, uc$reg_by))
if (!uc$reg_y %in% c(lnumeric$name, llogical$name))
nb_code <- c(nb_code,
sprintf('df$%s <- as.factor(df$%s)', uc$reg_y, uc$reg_y))
nb_code <- c(nb_code, "df <- droplevels(df)")
feffect <- ""
if (uc$reg_fe1 != "None") {
feffect <- uc$reg_fe1
if (uc$reg_fe2 != "None") feffect <- c(feffect, uc$reg_fe2)
} else if (uc$reg_fe2 != "None") feffect <- uc$reg_fe2
cluster <- ""
if (uc$cluster == 2) cluster <- uc$reg_fe1
if (uc$cluster == 3) cluster <- uc$reg_fe2
if (uc$cluster == 4) cluster <- c(uc$reg_fe1, uc$reg_fe2)
cluster <- cluster[!cluster %in% "None"]
reg_by <- ifelse(uc$reg_by != "None", uc$reg_by, "")
parm_str <- sprintf('df, dvs = "%s", idvs = c("%s")', uc$reg_y, paste(uc$reg_x, collapse = '", "'))
if (feffect[1] != "") parm_str <- paste0(parm_str,
sprintf(', feffects = c("%s")', paste(feffect, collapse = '", "')))
if (cluster[1] != "") parm_str <- paste0(parm_str,
sprintf(', clusters = c("%s")', paste(cluster, collapse = '", "')))
if (reg_by != "") parm_str <- paste0(parm_str,
sprintf(', byvar = "%s"', uc$reg_by))
parm_str <- paste0(parm_str, sprintf(', models = "%s"', uc$model))
nb_code <- c(nb_code,
sprintf('t <- prepare_regression_table(%s)', parm_str),
"HTML(t$table)",
"```", " ", " ")
nb_code
})
if(comp == "end_note") return({
nb_code <- c(
"
"This Notebook has been automatically generated using the [ExPanDaR](https://joachim-gassen.github.io/ExPanDaR) package.", " "
)
})
return("")
}
output$nb_download <- downloadHandler(
filename = "ExPanD_nb.zip",
content = function(file) {
nb <- c(
"---",
sprintf("title: %s", shiny_title),
"output: html_notebook",
"---", " ", " "
)
if (!is.null(shiny_abstract)) {
nb <- c(nb,
"
shiny_abstract, " ", " "
)
}
comp <- components()
nb_blocks <- c("setup", "create_sample",
names(comp[!names(comp) %in%
c("sample_selection", "subset_factor",
"grouping", "udvars")]),
"end_note")
pos_html_blocks <- 0
for (blk in nb_blocks) {
if (blk == "html_block") {
pos_html_blocks <- pos_html_blocks + 1
nb <- c(nb, shiny_html_blocks[pos_html_blocks], rep(" ", 2))
} else {
comp_code <- create_nb_code_for_component(blk)
if(length(comp_code) <= 1) {
stop(sprintf('Encountered unknown notebook block: "%s"', blk))
} else nb <- c(nb, comp_code)
}
}
write(nb, file = "ExPanD_nb_code.Rmd", sep = "\n")
nb_df <- create_ca_sample()
nb_df_def <- cas_definition
if (length(uc$udvars) != 0) {
nb_df <- cbind(nb_df, udv_sample)
nb_df_def <- rbind(nb_df_def, udv_definition)
}
nb_df_def <- nb_df_def[!nb_df_def$var_name %in% uc$delvars,]
nb_df <- nb_df[, as.character(nb_df_def$var_name)]
save(nb_df, nb_df_def, file = "ExPanD_nb_data.Rdata")
zip::zipr(file, files = c("ExPanD_nb_code.Rmd", "ExPanD_nb_data.Rdata"))
}
) |
.logit4Pred <-
function(lm.out, nm, d, my_formula, brief, res_rows,
n.vars, n.pred, n.obs, n.keep, digits_d, pre, line,
new.data, pred, pred_all, prob_cut,
numeric.all, in.data.frame, X1_new,
X2_new, X3_new, X4_new, X5_new, X6_new,
pdf_file, width, height, ...) {
pred_sort <- TRUE
if (length(prob_cut) == 1)
p.cut <- prob_cut
else
p.cut <- 0.5
for (i in 1:length(prob_cut)) {
if (!new.data) {
p.int <- data.frame(predict(lm.out, type="response", se.fit=TRUE))
label <- integer(length=nrow(p.int))
for (irow in 1:nrow(p.int))
label[irow] <- ifelse (p.int$fit[irow] < p.cut, 0, 1)
if (all(label == 0) || all(label == 1)) {
cat("\n"); stop(call.=FALSE, "\n","------\n",
"For threshold ", p.cut, ", all predicted values are ",
label[1], "\n\n")
}
out <- cbind(lm.out$model[c(nm[seq(2,n.vars)], nm[1])], label,
p.int$fit, p.int$se.fit)
}
else {
Xnew.val <- list(X1_new)
if (n.vars > 2) for (i in 2:(n.pred)) {
pp <- eval(parse(text=paste("X", toString(i),"_new",sep="")))
Xnew.val <- c(Xnew.val, list(pp))
}
Xnew <- expand.grid(Xnew.val)
for (i in 1:(n.pred)) names(Xnew)[i] <- nm[i+1]
p.int <- data.frame(predict(lm.out, type="response",
se.fit=TRUE, newdata=Xnew))
label <- integer(length=nrow(p.int))
for (i in 1:nrow(p.int))
label[i] <- ifelse (p.int$fit[i] < p.cut, 0, 1)
Ynew <- character(length=nrow(Xnew))
Ynew <- ""
out <- cbind(Xnew, Ynew, label, p.int$fit,p.int$se.fit)
}
if (i == 1) {
cat( "\n\n", " FORECASTS", "\n\n")
cat("Probability threshold for predicting ",
levels(lm.out$model[,nm[1]])[2], ":", " ", p.cut, "\n\n", sep="")
if (is.factor(lm.out$model[,nm[1]]))
cat(" 0: ", levels(lm.out$model[,nm[1]])[1], "\n",
" 1: ", levels(lm.out$model[,nm[1]])[2], "\n", sep="")
cat("\n")
cat("Data, Fitted Values, Standard Errors\n")
cat(" [sorted by fitted value]\n")
if (n.keep > 50 && pred_all == FALSE && !new.data)
cat(" [to save space only some intervals printed, ",
" pred_all=TRUE to see all]\n")
names(out)[n.vars+1] <- "predict"
names(out)[n.vars+2] <- "fitted"
names(out)[n.vars+3] <- "std.err"
out <- data.frame(out, stringsAsFactors=TRUE)
if (pred_sort) {
o <- order(out[,n.vars+2])
out <- out[o,]
}
.dash(68)
if (n.keep < 25 || pred_all == TRUE || new.data)
print(out, digits=digits_d)
else {
print(out[1:4,], digits=digits_d)
cat("\n... for the rows of data where fitted is close to 0.5 ...\n\n")
i.mid <- which.min(abs(0.5-sort(p.int$fit)))
print(out[(i.mid-2):(i.mid+2),], digits=digits_d)
cat("\n... for the last 4 rows of sorted data ...\n\n")
print(out[(n.keep-3):n.keep,], digits=digits_d)
}
.dash(68)
cat("\n\n")
cat("----------------------------\n")
cat("Specified confusion matrices\n")
cat("----------------------------\n")
cat("\n")
}
if (i > 1) cat("\n\n")
.logit5Confuse(lm.out, out, n.vars, nm, new.data, prob_cut[i])
}
if (pred && n.pred==1 && !is.factor(lm.out$model[,nm[2]]) && is.null(X1_new)){
.opendev(pdf_file, width, height)
x.values <- lm.out$model[,nm[2]]
if (!is.factor(lm.out$model[,nm[1]])) {
y.values <- lm.out$model[,nm[1]]
y.label <- paste("Probability of", nm[1])
}
else {
y.values <- as.numeric(lm.out$model[,nm[1]])
min.y <- min(y.values, na.rm=TRUE)
y.label <- paste("Probability ", nm[1], " = ",
levels(lm.out$model[,nm[1]])[2], sep="")
for (i in 1:length(y.values))
y.values[i] <- ifelse (y.values[i]==min.y, 0, 1)
}
max.width <- strwidth(as.character(max(pretty(y.values))), units="inches")
margs <- .marg(max.width, y.lab=nm[1], x.lab=nm[2], main=NULL, sub=NULL)
lm <- margs$lm + 0.2
tm <- margs$tm
rm <- margs$rm
bm <- margs$bm
par(bg=getOption("window_fill"))
orig.params <- par(no.readonly=TRUE)
on.exit(par(orig.params))
par(mai=c(bm, lm, tm, rm))
plot(x.values,y.values, type="n", axes=FALSE, ann=FALSE,
ylim=c(-.10,1.10), ...)
usr <- par("usr")
fill_bg <- getOption("panel_fill")
rect(usr[1], usr[3], usr[2], usr[4], col=fill_bg, border="transparent")
min.x <- min(x.values, na.rm=TRUE)
max.x <- max(x.values, na.rm=TRUE)
axT1 <- pretty(c(min.x, max.x))
axT2 <- seq(0,1,.2)
.grid("v", axT1)
.grid("h", axT2)
rect(usr[1], usr[3], usr[2], usr[4],
col="transparent", border=getOption("panel_color"),
lwd=getOption("panel_lwd"), lty=getOption("panel_lty"))
.axes(NULL, NULL, axTicks(1), axTicks(2))
main.lab <- NULL
sub.lab <- NULL
.axlabs(nm[2], y.label, main.lab, sub.lab,
cex.lab=getOption("lab_cex"), cex.main=1.0, ...)
fill <- getOption("pt_fill")
trans <- .7
fill <- .maketrans(fill, (1-trans)*256)
color <- getOption("pt_color")
points(x.values,y.values, pch=21, col=color, bg=fill, cex=0.8)
lines(x.values, p.int$fit, col=color, lwd=2)
if (!is.null(pdf_file)) {
dev.off()
.showfile(pdf_file, "fitted values and scatter plot")
}
}
else {
if (numeric.all && in.data.frame) {
.opendev(pdf_file, width, height)
panel2.smooth <- function (x, y, pch=par("pch"), cex=.9,
col.pt=getOption("pt_color"), col.smooth=getOption("col.bar_color"),
span=2/3, iter=3, ...)
{
usr <- par("usr")
rect(usr[1], usr[3], usr[2], usr[4],
col=getOption("border_fill"), border=getOption("border_color"))
points(x, y, pch=pch, col=col.pt, bg=getOption("pt_fill"), cex=cex)
ok <- is.finite(x) & is.finite(y)
if (any(ok))
lines(lowess(x[ok], y[ok], f=span, iter=iter), col=col.smooth, ...)
}
pairs(lm.out$model[c(nm)], panel=panel2.smooth)
if (!is.null(pdf_file)) {
dev.off()
.showfile(pdf_file, "scatter plot matrix")
}
}
else {
cat("\n\n>>> No scatterplot matrix reported because not all variables are ")
if (!in.data.frame) cat("in the data frame.\n")
if (!numeric.all) cat("numeric.\n")
}
}
} |
getUniqueNode = function(graph, .label, ...) UseMethod("getUniqueNode")
getUniqueNode.graph = function(graph, .label, ...) {
stopifnot(is.character(.label))
param = c(...)
if(length(param) > 1)
stop("Can only search by one property.")
if(length(param) == 0)
stop("Must supply a key = value pair.")
keys = invisible(getConstraint(graph, .label))$property_keys
if(!(names(param) %in% keys)) {
stop("The key = value pair given must have a uniqueness constraint applied.")
}
url = paste0(attr(graph, "root"), "/label/", .label, "/nodes?", names(param), "=")
if(is.character(param[[1]])) {
param[[1]] = URLencode(param[[1]], reserved = TRUE)
url = paste0(url, "%22", param[[1]], "%22")
} else if(is.numeric(param[[1]])) {
url = paste0(url, param[[1]])
} else if(is.logical(param[[1]])) {
if(param[[1]]) {
url = paste0(url, "true")
} else {
url = paste0(url, "false")
}
} else {
stop("Property value must be character, numeric, or logical.")
}
result = http_request(url, "GET")
if(length(result) == 0) {
return(invisible())
}
result = result[[1]]
node = configure_result(result)
return(node)
} |
context("subcrt")
basis(delete=TRUE)
test_that("unbalanced reactions give a warning or are balanced given sufficient basis species", {
expect_warning(subcrt(c("glucose", "ethanol"), c(-1, 3)), "reaction among glucose,ethanol was unbalanced, missing H-6O3")
basis("CHNOS")
s <- subcrt(c("malic acid", "citric acid"), c(-1, 1))
expect_equal(s$reaction$coeff, c(-1, 1, -2, -1, 1.5))
expect_equal(s$reaction$name, c("malic acid", "citric acid", "CO2", "water", "oxygen"))
})
test_that("standard Gibbs energies of reactions involving aqueous species are consistent with the literature", {
T <- c(2, 18, 25, 37, 45, 55, 70, 85, 100, 115, 150, 200)
E.units("J")
AS01.H2O <- c(78.25, 79.34, 79.89, 80.90, 81.63, 82.59, 84.13, 85.78, 87.55, 89.42, 94.22, 102.21)
sout.H2O <- subcrt(c("H2O", "H+", "OH-"), c(-1, 1, 1), T=T)$out
expect_maxdiff(sout.H2O$G/1000, AS01.H2O, 0.01)
AS01.A1 <- c(-263.94, -263.45, -263.17, -262.62, -262.20, -261.63, -260.67, -259.60, -258.44, -257.18, -253.90, -248.44)
sout.A1 <- subcrt(c("H2", "O2", "H2O"), "aq", c(-1, -0.5, 1), T=T)$out
expect_maxdiff(sout.A1$G/1000, AS01.A1, 0.01)
AS01.C7 <- c(-1695.30, -1686.90, -1682.80, -1675.30, -1670.00, -1663.10, -1652.00, -1640.30, -1628.00, -1615.20, -1583.50, -1533.00)
s.C7 <- subcrt(c("S2O3-2", "H2O", "O2", "SO4-2", "H+", "S"), c("aq", "liq", "aq", "aq", "aq", "cr"), c(-5, -1, -4, 6, 2, 4), T=T)
sout.C7 <- s.C7$out
expect_maxdiff(sout.C7$G/1000, AS01.C7, 0.05)
expect_equal(s.C7$polymorphs$sulfur, c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3))
E.units("cal")
})
test_that("subzero degree C calculations are possible", {
s.H2O <- subcrt("H2O", T=c(-20.1, seq(-20, 0)), P=1)$out$water
expect_equal(s.H2O$G[1], NA_real_)
expect_equal(floor(s.H2O$G[2]), -56001)
expect_equal(s.H2O$T[22], 0.01)
})
test_that("calculations using IAPWS-95 are possible", {
oldwat <- water("IAPWS95")
sb <- subcrt(c("H2O", "Na+"), T=c(-30, -20, 0, 10), P=1)$out
expect_true(all(sb$`Na+`$G < sb$water$G))
water(oldwat)
})
test_that("phase transitions of minerals give expected messages and results", {
iacanthite <- info("acanthite", "cr2")
expect_message(subcrt(iacanthite), "subcrt: temperature\\(s\\) of 623.15 K and above exceed limit for acanthite cr2 \\(using NA for G\\)")
expect_equal(subcrt("acanthite")$out$acanthite$polymorph, c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3))
expect_equal(subcrt(c("bunsenite", "nickel", "oxygen"), c(-1, 1, 0.5))$reaction$coeff, c(-1, 1, 0.5))
expect_equal(is.na(subcrt("rhodochrosite", T = c(699:701), P = 1, convert = FALSE)$out[[1]]$G), c(FALSE, FALSE, TRUE))
})
test_that("calculations for K-feldspar are consistent with SUPCRT92", {
add.OBIGT("SUPCRT92", "K-feldspar")
T <- c(100, 100, 1000, 1000)
P <- c(5000, 50000, 5000, 50000)
SUPCRT_G <- c(-886628, -769531, -988590, -871493)
SUPCRT_H <- c(-932344, -815247, -865868, -748771)
SUPCRT_S <- c(62.6, 62.6, 150.6, 150.6)
SUPCRT_V <- c(108.9, 108.9, 108.9, 108.9)
SUPCRT_Cp <- c(56.7, 56.7, 80.3, 80.3)
CHNOSZ <- subcrt("K-feldspar", T=T, P=P)$out[[1]]
expect_equal(round(CHNOSZ$G), SUPCRT_G)
expect_equal(round(CHNOSZ$H), SUPCRT_H)
expect_equal(round(CHNOSZ$S, 1), SUPCRT_S)
expect_equal(round(CHNOSZ$V, 1), SUPCRT_V)
expect_equal(round(CHNOSZ$Cp, 1), SUPCRT_Cp)
OBIGT()
})
test_that("calculations for quartz are nearly consistent with SUPCRT92", {
add.OBIGT("SUPCRT92")
T <- c(100, 100, 1000, 1000)
P <- c(5000, 50000, 5000, 50000)
SUPCRT_G <- c(-202778, -179719, -223906, -199129)
SUPCRT_H <- c(-214133, -191708, -199359, -177118)
SUPCRT_S <- c(12.3, 10.6, 31.8, 29.8)
SUPCRT_V <- c(22.5, 20.3, 23.7, 21.9)
SUPCRT_Cp <- c(12.3, 12.3, 16.9, 16.9)
CHNOSZ <- subcrt("quartz", T=T, P=P)$out[[1]]
expect_equal(round(CHNOSZ$G)[-4], SUPCRT_G[-4])
expect_equal(round(CHNOSZ$H)[-4], SUPCRT_H[-4])
expect_equal(round(CHNOSZ$S, 1)[-4], SUPCRT_S[-4])
expect_equal(round(CHNOSZ$Cp, 1)[-4], SUPCRT_Cp[-4])
expect_equal(round(CHNOSZ$V, 1), SUPCRT_V)
OBIGT()
})
test_that("more calculations for quartz are nearly consistent with SUPCRT92", {
add.OBIGT("SUPCRT92")
S92_1bar <- read.table(header = TRUE, text = "
T G H S V
573 -214507 -209517 24.7 23.3
574 -214532 -209499 24.8 23.3
575 -214557 -209192 25.1 23.7
576 -214582 -209176 25.1 23.7
")
CHNOSZ_1bar <- subcrt("quartz", T=seq(573, 576), P=1)$out[[1]]
expect_equal(round(CHNOSZ_1bar$G), S92_1bar$G)
expect_equal(round(CHNOSZ_1bar$H), S92_1bar$H)
expect_equal(round(CHNOSZ_1bar$S, 1), S92_1bar$S)
expect_equal(round(CHNOSZ_1bar$V, 1), S92_1bar$V)
S92_5000bar <- read.table(header = TRUE, text = "
T G H S V
703 -215044 -204913 26.7 23.3
704 -215071 -204895 26.7 23.3
705 -215142 -204254 27.4 23.7
706 -215170 -204238 27.5 23.7
")
CHNOSZ_5000bar <- subcrt("quartz", T=seq(703, 706), P=5000)$out[[1]]
expect_maxdiff(CHNOSZ_5000bar$G, S92_5000bar$G, 20)
expect_maxdiff(CHNOSZ_5000bar$H, S92_5000bar$H, 300)
expect_maxdiff(CHNOSZ_5000bar$S, S92_5000bar$S, 0.5)
expect_maxdiff(CHNOSZ_5000bar$V, S92_5000bar$V, 0.05)
OBIGT()
})
test_that("duplicated species yield correct phase transitions", {
s1 <- subcrt("chalcocite", T=c(100, 1000), P=1000)
s2 <- subcrt(rep("chalcocite", 2), T=c(100, 1000), P=1000)
expect_equal(s1$out[[1]]$logK, s2$out[[1]]$logK)
expect_equal(s1$out[[1]]$logK, s2$out[[2]]$logK)
basis(c("copper", "chalcocite"))
species("chalcocite")
a <- affinity(T=c(0, 1000, 2), P=1)
expect_equal(as.numeric(a$values[[1]]), c(0, 0))
})
test_that("reaction coefficients for repeated species are handled correctly", {
s1 <- subcrt(c("quartz", "SiO2"), c(-1, 1))
expect_equal(s1$reaction$coeff, c(-1, 1))
s2 <- subcrt(c("pyrrhotite", "pyrrhotite"), c(-1, 1))
expect_equal(s2$reaction$coeff, c(-1, 1))
s3 <- subcrt(c("SiO2", "SiO2"), c(-1, 1))
expect_equal(s3$reaction$coeff, c(-1, 1))
s4 <- subcrt(c("H2O", "H2O", "H2O", "H2O", "H2O"), c(-2, 1, -3, 1, 3))
expect_equal(s4$reaction$coeff, c(-2, 1, -3, 1, 3))
expect_equal(unique(s4$out$logK), 0)
})
test_that("properties of HKF species below 0.35 g/cm3 are NA and give a warning", {
wtext <- "below minimum density for applicability of revised HKF equations \\(2 T,P pairs\\)"
expect_warning(s1 <- subcrt(c("Na+", "quartz"), T=450, P=c(400, 450, 500)), wtext)
expect_equal(sum(is.na(s1$out$`Na+`$logK)), 2)
expect_equal(sum(is.na(s1$out$quartz$logK)), 0)
s2 <- subcrt(c("Na+", "quartz"), T=450, P=c(400, 450, 500), exceed.rhomin=TRUE)
expect_equal(sum(is.na(s2$out$`Na+`$logK)), 0)
})
test_that("combining minerals with phase transitions and aqueous species with IS > 0 does not mangle output", {
add.OBIGT("SUPCRT92")
s1 <- subcrt(c("quartz", "K+"), T=25, IS=1)
s2 <- subcrt(c("K+", "quartz"), T=25, IS=1)
expect_true(identical(colnames(s1$out[[1]]), c("T", "P", "rho", "logK", "G", "H", "S", "V", "Cp", "polymorph")))
expect_true(identical(colnames(s2$out[[2]]), c("T", "P", "rho", "logK", "G", "H", "S", "V", "Cp", "polymorph")))
expect_true(identical(colnames(s1$out[[2]]), c("T", "P", "rho", "logK", "G", "H", "S", "V", "Cp", "loggam", "IS")))
expect_true(identical(colnames(s2$out[[1]]), c("T", "P", "rho", "logK", "G", "H", "S", "V", "Cp", "loggam", "IS")))
expect_true(identical(colnames(subcrt(c("iron", "Na+", "Cl-", "OH-", "pyrrhotite"), T=25, IS=1)$out$pyrrhotite),
c("T", "P", "rho", "logK", "G", "H", "S", "V", "Cp", "polymorph")))
})
test_that("argument checking handles some types of invalid input", {
expect_error(subcrt("H2O", -1, "liq", "xxx"), "invalid property name: xxx")
expect_error(subcrt("H2O", -1, "liq", c(1, 2)), "invalid property names: 1 2")
}) |
fitCatEndPts <- function(endpoints,L){
if(L < minmaxLength(endpoints)['min']){
stop("Not possible: length is too short")
}
fn <- function(para,endpoints,L){
x0 <- endpoints[1,1];x1 <- endpoints[2,1]
y0 <- endpoints[1,2];y1 <- endpoints[2,2]
c1 <- para[1];c2 <- para[2]; lambda <- para[3]
d1 <- (y0 - f(x=x0,c1=c1,c2=c2,lambda=lambda))^2
d2 <- (y1 - f(x=x1,c1=c1,c2=c2,lambda=lambda))^2
d3 <- (L - getCatLength(x0=x0,x1=x1,c1=c1,c2=c2))^2
return( sum(c(d1,d2,d3)))
}
c2 <- mean(endpoints[,1])
c1 <- min(endpoints[,2])/2
lambda <- c1
tryCatch(tmp <- optim(par=c(c1,c2,lambda),fn=fn,endpoints=endpoints,L=L),
error = function(e) e,
finally=print("optim worked"))
if(tmp$convergence !=0){
print("Maybe problems with convergence of optim - be careful")
}
par <- c(c1=tmp$par[1],c2=tmp$par[2],lambda=tmp$par[3])
return(par)
} |
moreFitIndices <- function(object, fit.measures = "all", nPrior = 1) {
fit.choices <- c("gammaHat","adjGammaHat","baseline.rmsea",
"gammaHat.scaled","adjGammaHat.scaled","baseline.rmsea.scaled",
"aic.smallN","bic.priorN","hqc","sic")
flags <- setdiff(fit.measures, c("all", fit.choices))
if (length(flags)) stop(paste("Argument 'fit.measures' includes invalid options:",
paste(flags, collapse = ", "),
"Please choose 'all' or among the following:",
paste(fit.choices, collapse = ", "), sep = "\n"))
if ("all" %in% fit.measures) fit.measures <- fit.choices
fit <- lavInspect(object, "fit")
p <- length(lavaan::lavNames(object, type = "ov", group = 1))
nParam <- fit["npar"]
ngroup <- lavInspect(object, "ngroups")
N <- n <- lavInspect(object, "ntotal")
if (lavInspect(object, "options")$mimic == "EQS") n <- n - ngroup
f <- -2 * fit["logl"]
result <- list()
if (length(grep("gamma", fit.measures, ignore.case = TRUE))) {
gammaHat <- p / (p + 2 * ((fit["chisq"] - fit["df"]) / n))
adjGammaHat <- 1 - (((ngroup * p * (p + 1)) / 2) / fit["df"]) * (1 - gammaHat)
result["gammaHat"] <- gammaHat
result["adjGammaHat"] <- adjGammaHat
if (any(grepl(pattern = "scaled", x = names(fit)))) {
gammaHatScaled <- p / (p + 2 * ((fit["chisq.scaled"] - fit["df.scaled"]) / n))
adjGammaHatScaled <- 1 - (((ngroup * p * (p + 1)) / 2) / fit["df.scaled"]) * (1 - gammaHatScaled)
result["gammaHat.scaled"] <- gammaHatScaled
result["adjGammaHat.scaled"] <- adjGammaHatScaled
}
}
if (length(grep("rmsea", fit.measures))) {
result["baseline.rmsea"] <- nullRMSEA(object, silent = TRUE)
if (any(grepl(pattern = "scaled", x = names(fit)))) {
result["baseline.rmsea.scaled"] <- nullRMSEA(object, scaled = TRUE, silent = TRUE)
}
}
if (!is.na(f)) {
if ("aic.smallN" %in% fit.measures) {
warning('AICc (aic.smallN) was developed for univariate linear models.',
' It is probably not appropriate to use AICc to compare SEMs.')
result["aic.smallN"] <- fit[["aic"]] + (2 * nParam * (nParam + 1)) / (N - nParam - 1)
}
if ("bic.priorN" %in% fit.measures) {
result["bic.priorN"] <- f + log(1 + N/nPrior) * nParam
}
if ("hqc" %in% fit.measures) result["hqc"] <- f + 2 * log(log(N)) * nParam
if ("sic" %in% fit.measures) result["sic"] <- sic(f, object)
}
class(result) <- c("lavaan.vector","numeric")
unlist(result[fit.measures])
}
nullRMSEA <- function(object, scaled = FALSE, silent = FALSE) {
fit <- lavaan::update(object, model = lavaan::lav_partable_independence(object))
fits <- lavaan::fitMeasures(fit, fit.measures = c("rmsea","rmsea.scaled",
"rmsea.robust"))
if (scaled) {
RMSEA <- fits["rmsea.robust"]
if (is.na(RMSEA)) RMSEA <- fits["rmsea.scaled"]
if (is.na(RMSEA)) RMSEA <- fits["rmsea"]
} else RMSEA <- fits["rmsea"]
if (!silent) {
cat("The baseline model's RMSEA =", RMSEA, "\n\n")
if (RMSEA < 0.158 ) {
cat("CFI, TLI, and other incremental fit indices may not be very",
"informative because the baseline model's RMSEA < 0.158",
"(Kenny, Kaniskan, & McCoach, 2015). \n")
}
}
invisible(RMSEA)
}
sic <- function(f, lresults = NULL) {
E.inv <- lavaan::lavTech(lresults, "inverted.information.observed")
if (inherits(E.inv, "try-error")) {
return(as.numeric(NA))
}
E <- MASS::ginv(E.inv) * lavaan::nobs(lresults)
eigvals <- eigen(E, symmetric = TRUE, only.values = TRUE)$values
eigvals <- eigvals[ eigvals > sqrt(.Machine$double.eps)]
DET <- prod(eigvals)
if (DET <= 0) return(NA)
f + log(DET)
}
chisqSmallN <- function(fit0, fit1 = NULL,
smallN.method = if (is.null(fit1)) c("swain","yuan.2015") else "yuan.2005",
..., omit.imps = c("no.conv","no.se")) {
if ("all" %in% smallN.method) smallN.method <- c("swain","yuan.2015",
"yuan.2005","bartlett")
smallN.method <- intersect(tolower(smallN.method),
c("swain","yuan.2015","yuan.2005","bartlett"))
if (!any(smallN.method %in% c("swain","yuan.2015","yuan.2005","bartlett")))
stop('No recognized options for "smallN.method" argument')
if (!inherits(fit0, what = c("lavaan","lavaanList")))
stop("this function is only applicable to fitted lavaan models")
if (!is.null(fit1)) {
if (!inherits(fit1, what = c("lavaan","lavaanList")))
stop("this function is only applicable to fitted lavaan models")
modClass <- unique(sapply(list(fit0, fit1), class))
if (length(modClass) > 1L) stop('All models must be of the same class (e.g.,',
' cannot compare lavaan objects to lavaan.mi)')
suppressMessages(DF0 <- getMethod("fitMeasures", class(fit0))(fit0, fit.measures = "df",
omit.imps = omit.imps)[1])
suppressMessages(DF1 <- getMethod("fitMeasures", class(fit1))(fit1, fit.measures = "df",
omit.imps = omit.imps)[1])
if (DF0 == DF1) stop("Models have the same degrees of freedom.")
parent <- which.min(c(DF0, DF1))
if (parent == 1L) {
parent <- fit0
fit0 <- fit1
fit1 <- parent
parent <- DF0
DF0 <- DF1
DF1 <- parent
}
if (min(c(DF0, DF1)) == 0L) {
message('Less restricted model has df=0, so chi-squared difference ',
'not needed to compare models. Using only the restricted ',
"model's chi-squared statistic.")
fit1 <- NULL
}
}
if (!is.null(fit1)) {
if (any(smallN.method %in% c("yuan.2015","swain"))) {
message('Swain(1975) and Yuan (2015) corrections depend on the number ',
'of free parameters, so it is unavailable for model comparison.')
smallN.method <- smallN.method[-which(smallN.method %in% c("yuan.2015","swain"))]
}
if (!length(smallN.method)) {
stop('No valid options for "smallN.method" argument')
} else warning('Small-N corrections developed for single models, not for ',
'model comparison. Experimentally applying correction to ',
'chi-squared difference statistic, which might be invalid.')
}
N <- lavInspect(fit0, "ntotal")
Ng <- lavInspect(fit0, "ngroups")
if (!lavInspect(fit0, "options")$sample.cov.rescale) N <- N - Ng
P <- length(lavNames(fit0))
K <- length(lavNames(fit0, type = "lv"))
if (is.null(fit1)) {
FIT <- getMethod("fitMeasures", class(fit0))(fit0,
omit.imps = omit.imps,
asymptotic = TRUE,
fit.measures = c("npar","chisq",
"df","pvalue"))
scaled <- any(grepl(pattern = "scaled", x = names(FIT)))
if (scaled) warning('Small-N corrections developed assuming normality, but',
' a scaled test was requested. Applying correction(s) ',
'to the scaled test statistic, but this has not ',
'performed well in past simulations.')
NPAR <- FIT[["npar"]]
chi <- FIT[[if (scaled) "chisq.scaled" else "chisq"]]
DF <- FIT[[if (scaled) "df.scaled" else "df"]]
PV <- FIT[[if (scaled) "pvalue.scaled" else "pvalue"]]
} else {
N1 <- lavInspect(fit1, "ntotal")
Ng1 <- lavInspect(fit1, "ngroups")
if (!lavInspect(fit1, "options")$sample.cov.rescale) N1 <- N1 - Ng1
if (N != N1) stop("Unequal sample sizes")
if (P != length(lavNames(fit1))) stop("Unequal number of observed variables")
K1 <- length(lavNames(fit1, type = "lv"))
if (K != K1 && any(smallN.method %in% c("yuan.2005","bartlett"))) {
warning("Unequal number of latent variables (k). Unclear how to apply ",
"Yuan (2005) or Bartlett (2015) corrections when comparing ",
"models with different k. Experimentally using the larger ",
"model's k, but there is no evidence this is valid.")
K <- max(K, K1)
}
AOV <- try(compareFit(fit0, fit1, argsLRT = list(...), indices = FALSE),
silent = TRUE)
if (inherits(AOV, "try-error")) stop('Model comparison failed. Try using ',
'lavTestLRT() to investigate why.')
if (inherits(fit0, "lavaan")) {
if (grepl("scaled", attr(AOV@nested, "heading"), ignore.case = TRUE))
warning('Small-N corrections developed assuming normality, but scaled ',
'tests were requested. Applying correction(s) to the scaled test',
' statistic, but this has not performed well in past simulations.')
chi <- AOV@nested[["Chisq diff"]][2]
DF <- AOV@nested[["Df diff"]][2]
PV <- AOV@nested[["Pr(>Chisq)"]][2]
} else if (inherits(fit0, "lavaan.mi")) {
if (any(grepl("scaled", colnames(AOV@nested), ignore.case = TRUE)))
warning('Small-N corrections developed assuming normality, but scaled ',
'tests were requested. Applying correction(s) to the scaled test',
' statistic, but this has not performed well in past simulations.')
chi <- AOV@nested[1, 1]
DF <- AOV@nested[1, 2]
PV <- AOV@nested[1, 3]
}
}
out <- list()
out[[ lavInspect(fit0, "options")$test ]] <- c(chisq = chi, df = DF,
pvalue = PV)
class(out[[1]]) <- c("lavaan.vector","numeric")
if ("swain" %in% smallN.method) {
Q <- (sqrt(1 + 8*NPAR) - 1) / 2
num <- P*(2*P^2 + 3*P - 1) - Q*(2*Q^2 + 3*Q - 1)
SC <- 1 - num / (12*DF*N)
out[["swain"]] <- c(chisq = chi*SC, df = DF,
pvalue = pchisq(chi*SC, DF, lower.tail = FALSE),
smallN.factor = SC)
class(out[["swain"]]) <- c("lavaan.vector","numeric")
}
if ("yuan.2015" %in% smallN.method) {
SC <- (lavInspect(fit0, "ntotal") - (2.381 + .361*P + .006*NPAR)) / N
out[["yuan.2015"]] <- c(chisq = chi*SC, df = DF,
pvalue = pchisq(chi*SC, DF, lower.tail = FALSE),
smallN.factor = SC)
class(out[["yuan.2015"]]) <- c("lavaan.vector","numeric")
}
if ("yuan.2005" %in% smallN.method) {
SC <- 1 - ((2*P + 2*K + 7) / (6*N))
out[["yuan.2005"]] <- c(chisq = chi*SC, df = DF,
pvalue = pchisq(chi*SC, DF, lower.tail = FALSE),
smallN.factor = SC)
class(out[["yuan.2005"]]) <- c("lavaan.vector","numeric")
}
if ("bartlett" %in% smallN.method) {
message('Bartlett\'s k-factor correction was developed for EFA models, ',
'not for general SEMs.')
SC <- 1 - ((2*P + 4*K + 5) / (6*N))
out[["bartlett"]] <- c(chisq = chi*SC, df = DF,
pvalue = pchisq(chi*SC, DF, lower.tail = FALSE),
smallN.factor = SC)
class(out[["bartlett"]]) <- c("lavaan.vector","numeric")
}
out[c(lavInspect(fit0, "options")$test, smallN.method)]
} |
library(fitdistrplus)
nbboot <- 201
nbboot <- 10
if (requireNamespace ("ggplot2", quietly = TRUE)) {ggplotEx <- TRUE}
set.seed(123)
s1 <- rgamma(20, 3, 2)
f1 <- fitdist(s1, "gamma")
b1 <- bootdist(f1, niter=nbboot, silent=TRUE)
plot(b1)
quantile(b1)
par(mfrow=c(1,2))
CIcdfplot(b1, CI.level=95/100, CI.output = "probability", CI.fill="grey80", CI.col="black")
CIcdfplot(b1, CI.level=95/100, CI.output = "quantile", datacol="blue")
if(ggplotEx) CIcdfplot(b1, CI.level=95/100, CI.output = "probability", CI.fill="grey80", CI.col="black", plotstyle = "ggplot")
if(ggplotEx) CIcdfplot(b1, CI.level=95/100, CI.output = "quantile", datacol="blue", plotstyle = "ggplot")
par(mfrow=c(1,2))
CIcdfplot(b1, CI.level=85/100, CI.output = "probability")
CIcdfplot(b1, CI.level=85/100, CI.output = "quantile")
if(ggplotEx) CIcdfplot(b1, CI.level=85/100, CI.output = "probability", plotstyle = "ggplot")
if(ggplotEx) CIcdfplot(b1, CI.level=85/100, CI.output = "quantile", plotstyle = "ggplot")
par(mfrow=c(1,2))
CIcdfplot(b1, CI.level=90/100, CI.output = "probability")
CIcdfplot(b1, CI.level=90/100, CI.output = "quantile", CI.col="black", CI.type = "less",
CI.fill="grey85", verticals=TRUE, datacol="blue", do.points=FALSE)
if(ggplotEx) CIcdfplot(b1, CI.level=90/100, CI.output = "probability", plotstyle = "ggplot")
if(ggplotEx) CIcdfplot(b1, CI.level=90/100, CI.output = "quantile", CI.col="black", CI.type = "less",
CI.fill="grey85", verticals=TRUE, datacol="blue", do.points=FALSE, plotstyle = "ggplot")
par(mfrow=c(1,2))
CIcdfplot(b1, CI.level=90/100, CI.output = "probability", CI.type = "greater")
CIcdfplot(b1, CI.level=90/100, CI.output = "quantile", CI.col="black", CI.type = "greater",
CI.fill="grey90", datacol="blue", datapch=21)
if(ggplotEx) CIcdfplot(b1, CI.level=90/100, CI.output = "probability", CI.type = "greater", plotstyle = "ggplot")
if(ggplotEx) CIcdfplot(b1, CI.level=90/100, CI.output = "quantile", CI.col="black", CI.type = "greater",
CI.fill="grey90", datacol="blue", datapch=21, plotstyle = "ggplot")
par(mfrow=c(1,1))
CIcdfplot(b1, CI.level=90/100, CI.output = "probability", CI.col="black", CI.type = "less", CI.fill="grey90")
CIcdfplot(b1, CI.level=90/100, CI.output = "quantile", CI.col="black", CI.type = "less", CI.fill="grey90",
verticals=TRUE, datacol="blue", do.points=FALSE)
CIcdfplot(b1, CI.level=90/100, CI.output = "quantile", CI.col="grey90", CI.type = "less", CI.fill="grey90",
verticals=TRUE, datacol="blue", do.points=FALSE, CI.only=TRUE)
CIcdfplot(b1, CI.level=90/100, CI.output = "probability", CI.col="grey85", CI.type = "less", CI.fill="grey90",
CI.only = TRUE)
CIcdfplot(b1, CI.output = "probability", fitlty=3, fitlwd=4)
if(ggplotEx) CIcdfplot(b1, CI.level=90/100, CI.output = "probability", CI.col="black", CI.type = "less", CI.fill="grey90", plotstyle = "ggplot")
if(ggplotEx) CIcdfplot(b1, CI.level=90/100, CI.output = "quantile", CI.col="black", CI.type = "less", CI.fill="grey90",
verticals=TRUE, datacol="blue", do.points=FALSE, plotstyle = "ggplot")
if(ggplotEx) CIcdfplot(b1, CI.level=90/100, CI.output = "quantile", CI.col="grey90", CI.type = "less", CI.fill="grey90",
verticals=TRUE, datacol="blue", do.points=FALSE, CI.only=TRUE, plotstyle = "ggplot")
if(ggplotEx) CIcdfplot(b1, CI.level=90/100, CI.output = "probability", CI.col="grey85", CI.type = "less", CI.fill="grey90",
CI.only = TRUE, plotstyle = "ggplot")
if(ggplotEx) CIcdfplot(b1, CI.output = "probability", fitlty=3, fitlwd=4, plotstyle = "ggplot")
data(salinity)
log10LC50 <-log10(salinity)
fln <- fitdistcens(log10LC50,"norm")
bln <- bootdistcens(fln, niter=nbboot)
(HC5ln <- quantile(bln,probs = 0.05))
CIcdfplot(bln, CI.output = "quantile", CI.fill = "lightblue", CI.col = "blue",
xlab = "log10(LC50)",xlim=c(0.5,2),lines01 = TRUE)
if(ggplotEx) CIcdfplot(bln, CI.output = "quantile", CI.fill = "lightblue", CI.col = "blue",
xlab = "log10(LC50)",xlim=c(0.5,2),lines01 = TRUE, plotstyle = "ggplot")
CIcdfplot(bln, CI.output = "quantile", CI.fill = "lightblue", CI.col = "blue",
xlab = "log10(LC50)", lines01 = TRUE, xlim = c(0.8, 1.5), ylim = c(0, 0.1))
abline(h = 0.05, lty = 1)
if(ggplotEx) CIcdfplot(bln, CI.output = "quantile", CI.fill = "lightblue", CI.col = "blue",
xlab = "log10(LC50)", lines01 = TRUE, xlim = c(0.8, 1.5), ylim = c(0, 0.1), plotstyle = "ggplot") +
ggplot2::geom_hline(yintercept = 0.05)
CIcdfplot(bln, CI.output = "probability", CI.fill = "lightblue", CI.col = "blue",
xlab = "log10(LC50)", lines01 = TRUE, xlim = c(0.8, 1.5), ylim = c(0, 0.1))
abline(h = 0.05, lty = 1)
if(ggplotEx) CIcdfplot(bln, CI.output = "probability", CI.fill = "lightblue", CI.col = "blue",
xlab = "log10(LC50)", lines01 = TRUE, xlim = c(0.8, 1.5), ylim = c(0, 0.1), plotstyle = "ggplot") +
ggplot2::geom_hline(yintercept = 0.05)
set.seed(123)
s3 <- rgamma(5, 3, 10)
f3 <- fitdist(s3, "norm")
b3 <- bootdist(f3, niter=nbboot, silent=TRUE)
par(mfrow=c(1,2))
CIcdfplot(b3, CI.level=90/100, CI.output = "probability")
CIcdfplot(b3, CI.level=90/100, CI.output = "quantile")
if(ggplotEx) CIcdfplot(b3, CI.level=90/100, CI.output = "probability", plotstyle = "ggplot")
if(ggplotEx) CIcdfplot(b3, CI.level=90/100, CI.output = "quantile", plotstyle = "ggplot") |
max_effective_bets <- function(x0,
sigma,
t,
tol = 1e-20,
maxeval = 5000L,
maxiter = 5000L) {
assertthat::assert_that(assertthat::is.number(tol))
assertthat::assert_that(assertthat::is.number(maxeval))
assertthat::assert_that(assertthat::is.number(maxiter))
assertthat::assert_that(NCOL(sigma) == NCOL(t))
size <- NCOL(sigma)
if (is.null(x0)) {
x0 <- rep(1 / size, size)
}
objective <- function(x0, sigma, t) {
-effective_bets(b = x0, sigma = sigma, t = t)$enb
}
fun <- match.fun(objective)
fn <- function(x) fun(x, sigma, t)
opt <- NlcOptim::solnl(
X = x0,
objfun = fn,
Aeq = matrix(1, ncol = size),
Beq = 1,
lb = rep(0, size),
ub = rep(1, size),
maxIter = maxiter,
maxnFun = maxeval
)
out <- list(
weights = as.vector(opt$par),
enb = -opt$fn,
counts = opt$counts,
lambda_lb = opt$lambda$lower,
lambda_ub = opt$lambda$upper,
lambda_eq = opt$lambda$eqlin,
gradient = opt$grad,
hessian = opt$hessian
)
if (is_col_named(sigma)) {
nms <- colnames(sigma)
rownames(out$lambda_lb) <- nms
rownames(out$lambda_ub) <- nms
rownames(out$gradient) <- nms
rownames(out$hessian) <- nms
colnames(out$hessian) <- nms
}
out
} |
rtopKrige.STSDF = function(object, predictionLocations = NULL, varMatObs, varMatPredObs,
varMat, params = list(), formulaString, sel,
olags = NULL, plags = NULL, lagExact = TRUE, ...) {
if (!requireNamespace("spacetime")) stop("spacetime not available")
params = getRtopParams(params, ...)
cv = params$cv
debug.level = params$debug.level
if (!cv & !all.equal(is.null(olags), is.null(plags)))
stop("Lag times have to be given for both observations and predictionLocations, or for none of them")
if (!missing(varMat) && missing(varMatObs)) {
if (is.atomic(varMat)) {
varMatObs = varMat
if (!cv) stop(paste("Not cross-validation, you must provide either varMatObs",
" and varMatPredObs or varMat with the matrices as elements"))
} else {
varMatObs = varMat$varMatObs
varMatPredObs = varMat$varMatPredObs
}
}
if (cv) {
predictionLocations = object
plags = olags
varMatPredObs = varMatObs
}
ntime = dim(object)[2]
nspace = dim(object)[1]
indx = predictionLocations@index
sinds = sort(unique(indx[,1]))
tinds = sort(unique(indx[,2]))
pspace = dim(predictionLocations)[1]
ptime = dim(predictionLocations)[2]
pfull = if (prod(dim(predictionLocations)) == dim(predictionLocations@data)[1]) TRUE else FALSE
if (is(predictionLocations, "STSDF")) {
predictionLocations@data = cbind(predictionLocations@data,
data.frame(var1.pred = NA, var1.var = NA, var1.yam = NA))
} else if (is(predictionLocations, "STS")) {
predictionLocations = spacetime::STSDF(predictionLocations, data = data.frame(var1.pred = NA, var1.var = NA, var1.yam = NA))
}
if (is.null(olags) & prod(dim(object)) == dim(object@data)[1]) {
obj1 = object[,1]
if (is(predictionLocations, "STSDF")) {
predLoc = predictionLocations@sp
} else {
predLoc = predictionLocations
}
ret = rtopKrige.default(obj1, predLoc, varMatObs,
varMatPredObs, varMat, params, formulaString, wret = TRUE)
weight = ret$weight
wvar = ret$predictions$var1.var
obs = as.data.frame(object)
obs = obs[,c("sp.ID", "timeIndex", as.character(formulaString[[2]]))]
obs = reshape(obs, v.names = as.character(formulaString[[2]]),
idvar = "sp.ID", timevar = "timeIndex", direction = "wide")
if (interactive() & debug.level == 1 & length(sinds) > 1) pb = txtProgressBar(1, length(sinds), style = 3)
for (istat in 1:length(sinds)) {
isind = sinds[istat]
ttinds = which(indx[,1] == isind)
lweight = weight[istat,]
preds = lweight %*% as.matrix(obs[,2:dim(obs)[2]])
diffs = sweep(obs[,2:dim(obs)[2]], 2, preds )
var1.yam = t(lweight) %*% (diffs^2)
if (!pfull) {
ptinds = indx[ttinds,1]
preds = preds[ptinds]
var1.yam = var1.yam[ptinds]
}
predictionLocations@data$var1.pred[ttinds] = preds
predictionLocations@data$var1.var[ttinds] = wvar[istat]
predictionLocations@data$var1.yam[ttinds] = var1.yam
if (interactive() & debug.level == 1 & length(sinds) > 1) setTxtProgressBar(pb, istat)
}
if (interactive() & debug.level == 1 & length(sinds) > 1) close(pb)
} else {
object@sp$sindex = sindex = 1:nspace
object@time$tindex = tindex = 1:ntime
predictionLocations@sp$sindex = 1:pspace
predictionLocations@time$tindex = 1:ptime
obs = as.data.frame(object)
depVar = as.character(formulaString[[2]])
obs = obs[,c("sp.ID", "timeIndex", depVar)]
if (!requireNamespace("reshape2")) stop("reshape2 not available")
obs = reshape2::dcast(obs, sp.ID ~ timeIndex)
obs = obs[order(as.numeric(as.character(obs$sp.ID))), ]
obs = as.matrix(obs[,2:(ntime+1)])
if (!cv | !is.null(olags)) {
ploc = as.data.frame(predictionLocations)
ploc = cbind(ploc, var = 1)
ploc = ploc[,c("sp.ID", "timeIndex", "var")]
ploc$sp.ID = as.numeric(as.character(ploc$sp.ID))
ploc = reshape2::dcast(ploc, sp.ID ~ timeIndex)
ploc = as.matrix(ploc)
}
if (interactive() & debug.level == 1 & ntime > 1) pb = txtProgressBar(1, ntime, style = 3)
spPredLoc = if (!cv) predictionLocations@sp else NULL
if (is.null(olags)) {
oldind = NULL
newkrige = 0
for (itime in 1:ptime) {
newind = which(!is.na(obs[,itime]))
if (length(newind) == 0) next
if (is.null(oldind) || !isTRUE(all.equal(newind, oldind))) {
oldind = newind
newkrige = newkrige + 1
ppq = object[,itime]
vmat = varMatObs[newind, newind]
if (cv) {
vpredobs = NULL
} else {
vpredobs = varMatPredObs[newind,]
}
ret = rtopKrige.default(object = ppq, predictionLocations = spPredLoc, varMatObs = vmat,
varMatPredObs = vpredobs, params = params,
formulaString = formulaString, wret = TRUE, debug.level = 0)
weight = ret$weight
wvar = ret$predictions$var1.var
}
ob = obs[,itime]
ob = ob[!is.na(ob)]
preds = weight %*% ob
var1.yam = rep(NA, dim(weight)[1])
for (istat in 1:dim(weight)[1]) {
diffs = ob - preds[istat]
var1.yam[istat] = sum(weight[istat,] * t(diffs^2))
}
itind = tinds[itime]
ttinds = which(indx[,2] == itind)
if (!pfull & FALSE) {
ptinds = indx[ttinds,1]
preds = preds[ptinds]
var1.yam = var1.yam[ptinds]
}
predictionLocations@data$var1.pred[ttinds] = preds
predictionLocations@data$var1.var[ttinds] = wvar
predictionLocations@data$var1.yam[ttinds] = var1.yam
if (interactive() & debug.level == 1 & ntime > 1) setTxtProgressBar(pb, itime)
}
} else {
ntot = dim(predictionLocations@data)[1]
if (interactive() & debug.level == 1 & ntime > 1) pb = txtProgressBar(1, ntot, style = 3)
itot = 0
objsp = object@sp
objsp = SpatialPointsDataFrame(SpatialPoints(objsp), data = objsp@data)
newkrige = 0
obs2 = obs
for (istat in 1:pspace) {
ispace = predictionLocations@sp@data$sindex[istat]
pxts = as.data.frame(predictionLocations[istat,])
stpred = predictionLocations@sp[istat,]
distm = spDistsN1(coordinates(object@sp),coordinates(stpred))
ppred = SpatialPoints(stpred)
rolags = olags - plags[istat]
nbefore = -floor(min(rolags))
nafter = ceiling(max(c(rolags, 1)))
naadd1 = matrix(NA, nrow = nspace, ncol = nbefore)
naadd2 = matrix(NA, nrow = nspace, ncol = nafter)
obsb = cbind(naadd1, cbind(obs2, naadd2))
obs[,] = NA
if (!lagExact) {
rolags = round(rolags, 0)
for (jstat in 1:nspace) {
obs[jstat, ] = obsb[jstat, (nbefore + 1 + rolags[jstat]) : (nbefore + ntime + rolags[jstat])]
}
} else {
rdiff = rolags - floor(rolags)
for (jstat in 1:nspace) {
nf = (nbefore + 1 + floor(rolags[jstat])) : (nbefore + ntime + floor(rolags[jstat]))
nl = (nbefore + 1 + ceiling(rolags[jstat])) : (nbefore + ntime + ceiling(rolags[jstat]))
obs[jstat, ] = obsb[jstat, nf] * (1-rdiff[jstat]) + obsb[jstat, nl] * rdiff[jstat]
}
}
oldind = NULL
ntl = length(pxts$tindex)
preds = rep(NA, ntl)
var1.yam = rep(NA, ntl)
var1.var = rep(NA, ntl)
tms = as.numeric(as.character(pxts$tindex))
if (cv) vorder = order(varMatObs[istat,]) else vorder = order(varMatPredObs[istat])
for (itime in seq_along(tms)) {
jtime = tms[itime]
tp = ploc[istat, jtime]
if (is.na(tp)) next
newind = vorder[vorder %in% which(!is.na(obs[,jtime]))]
if (cv) newind = newind[-which(newind == istat)]
if (is.numeric(params$nmax) && length(newind) > params$nmax) newind = newind[1:params$nmax]
if (length(newind) == 0) next
newind = newind[newind %in% vorder]
if (is.null(oldind) || !isTRUE(all.equal(newind, oldind))) {
oldind = newind
newkrige = newkrige + 1
ppq = objsp[newind, ]
ppq$intvar = obs[newind, jtime]
vmat = varMatObs[newind, newind]
vpredobs = varMatPredObs[newind, istat, drop = FALSE]
ret = rtopKrige.default(object = ppq, ppred, varMatObs = vmat,
varMatPredObs = vpredobs, params = params,
formulaString = intvar~1, wret = TRUE,
debug.level = 0, cv = FALSE)
weight = ret$weight
wvar = ret$predictions$var1.var
}
preds[itime] = sum(weight * obs[newind,jtime])
diffs = obs[newind,jtime] - preds[itime]
var1.yam[itime] = sum(weight * (diffs^2))
var1.var[itime] = wvar
itot = itot + 1
if (interactive() & debug.level == 1 & ntime > 1) setTxtProgressBar(pb, itot)
}
itind = tinds[itime]
ttinds = which(indx[,1] == ispace)
predictionLocations@data$var1.pred[ttinds] = preds
predictionLocations@data$var1.var[ttinds] = var1.var
predictionLocations@data$var1.yam[ttinds] = var1.yam
}
}
if (interactive() & debug.level == 1 & ntime > 1) close(pb)
}
list(predictions = predictionLocations)
} |
library(GFD)
data(pizza)
head(pizza)
set.seed(1234)
model1 <- GFD(Delivery ~ Crust * Coke * Bread, data = pizza, nperm = 1000, alpha = 0.05)
summary(model1)
data("curdies")
set.seed(987)
nested <- GFD(dugesia ~ season + season:site, data = curdies, nested.levels.unique = TRUE)
summary(nested)
plot(model1, factor = "Crust:Coke:Bread", legendpos = "center", main = "Delivery time of pizza", xlab = "Bread")
plot(model1, factor = "Crust:Coke", legendpos = "topleft", main = "Two-way interaction", xlab = "Coke", col = 3:5, pch = 17)
plot(nested, factor = "season:site", xlab = "site") |
srho = function(truth, response, ...) {
assert_regr(truth, response = response)
cor(truth, response, method = "spearman")
}
add_measure(srho, "Spearman's rho", "regr", -1, 1, FALSE) |
generateCoPaM <- function(U, relabel_technique = "minmin", w = numeric(), X = numeric(), distCriterion = "direct_euc", K = 0, GDM = numeric()) {
calwmeans <- function(ww) {
wm = rep(0, length(ww))
for (ii in 1:length(ww)) {
if (is.list(ww[[ii]])) {
wm[ii] = mean(calwmeans(ww[[ii]]))
} else {
wm[ii] = mean(ww[[ii]])
}
}
return(wm)
}
if (!is.list(U)) {
if (K == 0) {
if (length(dim(U)) == 2) {
K = sum(rowSums(U) > 0)
U = list(U);
} else if (length(dim(U)) == 3) {
K = sum(rowSums(U[,, 1]) > 0)
R = dim(U)[3]
tmp = U
U = list()
r = 1
for (i in 1:R) {
if (sum(rowSums(tmp[, , i]) > 0) == K) {
U[[r]] = tmp[,, i]
r = r + 1
}
}
R = r - 1
}
}
} else {
R = length(U)
}
if (isempty(GDM)) {
Utmp = U[[1]]
while (is.list(Utmp)) {
Utmp = Utmp[[1]]
}
GDM = matrix(TRUE, ncol(Utmp), R)
}
if (isempty(w) || (is.character(w) && (tolower(w) == "all" || tolower(w) == "equal"))) {
w = rep(1, R)
}
if (length(w) == 1) {
w = rep(w, R)
}
if (!is.list(w)) {
w = as.list(w)
}
wmeans = calwmeans(w)
permR = sample(R)
U = U[permR]
GDM = GDM[, permR]
if (!is.matrix(GDM)) {
GDM = matrix(GDM)
}
wmeans = wmeans[permR]
if (is.list(U[[1]] || length(dim(U[[1]])) > 1)) {
U[[1]] = generateCoPaM(U[[1]], relabel_technique = relabel_technique, w = w[[1]], X = X, distCriterion = distCriterion, K = K)
}
CoPaM = matrix(, nrow(U[[1]]), nrow(GDM))
CoPaM[, GDM[, 1]] = U[[1]]
K = nrow(CoPaM)
if (R == 1)
return(CoPaM)
for (r in 2:R) {
if (is.list(U[[r]] || length(dim(U[[r]])) > 1)) {
U[[r]] = generateCoPaM(U[[r]], relabel_technique = relabel_technique, w = w[[r]], X = X, distCriterion = distCriterion, K = K)
}
if (nrow(U[[r]]) != K) {
stop("Inequal number of clusters in partitions.")
}
U[[r]] = relabelClusts(CoPaM[, GDM[, r]], U[[r]], technique = relabel_technique, X = X, distCriterion = distCriterion)$B
CoPaM[, GDM[, r]] = t(apply(CoPaM[, GDM[, r]], 1, "*", GDM[GDM[, r], 1:(r - 1)] %*% as.matrix(wmeans[1:(r - 1)])))
CoPaM[, GDM[, r]] = CoPaM[, GDM[, r]] + wmeans[r] * U[[r]]
CoPaM[, GDM[, r]] = t(apply(CoPaM[, GDM[, r]], 1, "/", GDM[GDM[, r], 1:r] %*% as.matrix(wmeans[1:r])))
}
return(CoPaM)
} |
covHandling <- function(covData,
covStructure=NULL,
N,
thetaNames,
predType=NULL,
defaultExclude=NULL,
T1group=NULL){
if(! (is.null(covData) | is.list(covStructure) & length(covStructure) == 0 |
is.null(covStructure) & "ALL_COVARIATES" %in% defaultExclude)){
if(!("ALL_COVARIATES" %in% defaultExclude)){
covData <- covData[,predType == "c" &
!colnames(covData)%in% defaultExclude, drop=FALSE]
}
if(ncol(covData) != 0){
covNames <- colnames(covData)
if(is.character(covStructure)){
covStructure <- as.list(read.csv(covStructure, header=F,stringsAsFactors=F, sep="}")$V1)
}
if(is.null(covStructure)){
covStructure <- lapply(unique(thetaNames$Parameter),
function(tt) paste(tt, ";", paste(covNames, collapse=" ")))
}
covTmp <- covRecodeFactor(covData, predType)
covData <- covTmp$covData
predFactorLevels <- covTmp$predFactorLevels
names(predFactorLevels) <- colnames(covData)
covTable <- data.frame()
for(i in 1:length(covStructure)){
covStructure[[i]] <- gsub("\\,", " ", gsub("~", ";", covStructure[[i]]))
sss <- strsplit(covStructure[[i]], ";")[[1]]
if(length(sss) != 2)
stop("Check predStructure: in each character argument of the list,\n",
"exactly one semicolon is required to separate parameters (left hand)\n",
"and predictors (right hand):\n",
covStructure[[i]])
pars <- strsplit(sss[1], " +")[[1]]
covs <- strsplit(sss[2], " +")[[1]]
pars <- pars[pars != ""]
covs <- covs[covs != ""]
for(pp in 1:length(pars)){
if (!all(covs %in% colnames(covData)))
stop("Check names of predictors in predStructure. Valid names:\n ",
paste(colnames(covData), collapse = ", "), "\n",
"Currently defined:\n ",
paste(covs, collapse = ", "), "\n")
for(cc in 1:length(covs)){
covTable <- rbind(covTable, data.frame(Parameter = pars[pp], Covariate = covs[cc]))
}
}
}
parSel <- match(covTable$Parameter, thetaNames$Parameter)
if(any(is.na(parSel)))
stop("Check parameter names in predStructure. Problematic right now:\n ",
covTable$Parameter[is.na(parSel)])
covTable$theta <- thetaNames$theta[parSel]
covTable$Parameter <- thetaNames$Parameter[parSel]
covTable$covIdx <- (1:ncol(covData))[match(covTable$Covariate, covNames)]
covTable <- covTable[!duplicated(paste(covTable$theta, covTable$covIdx)),]
covTable$predType <- predType[covTable$covIdx]
covTable$prefix <- ifelse(covTable$predType=="c", "slope", "factor")
covTable$covPar <- apply(covTable[,c("prefix", "Parameter", "Covariate")],
1, paste, collapse="_")
}else{
covTable <- NULL
predFactorLevels <- NULL
}
}else{
covTable <- NULL
predFactorLevels <- NULL
}
return(list(covTable = covTable,
covData=covData,
predFactorLevels = predFactorLevels))
} |
shape_rep <- function(rep, xmin = NULL, xmax = NULL) {
if (class(rep) %in% "numeric") {
mx <- rep
x <- seq_along(mx) - 1
}
if (class(rep) %in% c("list", "data.frame")) {
if (!all(c("x", "mx") %in% names(rep))) {
stop("`rep` doesn't contain both `x` and `mx`.\n")
}
x <- rep$x
mx <- rep$mx
if (length(x) != length(mx)) {
stop("`x` and `mx` must be the same length")
}
}
if (is.null(xmin)) xmin <- x[min(which(mx > 0))]
if (is.null(xmax)) xmax <- max(x)
if (any(diff(x) <= 0)) stop("much as we'd like to reverse ageing, `x` must all be ascending.\n")
if (any(mx < 0)) stop("You appear to have minus-babies (check `mx` for negative values).\n")
x_sub <- x[x >= xmin & x <= xmax]
if (length(x_sub) <= 2) {
stop("must have > 2 nonzero values of `mx` to calculate shape.\n")
}
ltdim <- length(x)
Bx <- c(0, cumsum(mx[1:(ltdim - 1)]))
Bx_sub <- Bx[x >= xmin & x <= xmax]
xStd <- (x_sub - xmin) / (xmax - xmin)
Bxmin <- Bx_sub[which.min(xStd)]
Bxmax <- Bx_sub[which.max(xStd)]
BxStd <- (Bx_sub - Bxmin) / (Bxmax - Bxmin)
aucStd <- area_under_curve(xStd, BxStd)
aucFlat <- 0.5
shape <- aucStd - aucFlat
shape
} |
glmmPQL <- function(fixed, random = NULL, family = "binomial", data = NULL,
subset = NULL, weights = NULL, offset = NULL,
na.action = NULL, start = NULL, etastart = NULL,
mustart = NULL, control = glmmPQL.control(...),
sigma = 0.1, sigma.fixed = FALSE, model = TRUE,
x = FALSE, contrasts = NULL, ...) {
call <- match.call()
nm <- names(call)[-1]
if (is.null(random)) {
keep <- is.element(nm, c("family", "data", "subset", "weights",
"offset", "na.action"))
for (i in nm[!keep]) call[[i]] <- NULL
call$formula <- fixed
environment(call$formula) <- environment(fixed)
call[[1]] <- as.name("glm")
return(eval.parent(call))
}
modelTerms <- terms(fixed, data = data)
modelCall <- as.list(match.call(expand.dots = FALSE))
argPos <- match(c("data", "subset", "na.action", "weights", "offset"),
names(modelCall), 0)
modelData <- as.call(c(model.frame, list(formula = modelTerms,
drop.unused.levels = TRUE),
modelCall[argPos]))
modelData <- eval(modelData, parent.frame())
if (!is.matrix(random) || nrow(random) != nrow(modelData)) {
stop("`random` should be a matrix object, with ", nrow(modelData),
" rows.")
}
if (!is.null(modelCall$subset))
Z <- random[eval(modelCall$subset, data, parent.frame()),]
else Z <- random
if (!is.null(attr(modelData, "na.action")))
Z <- Z[-attr(modelData, "na.action"),]
nObs <- nrow(modelData)
y <- model.response(modelData, "numeric")
if (is.null(y))
y <- rep(0, nObs)
weights <- as.vector(model.weights(modelData))
if (!is.null(weights) && any(weights < 0))
stop("negative weights are not allowed")
if (is.null(weights))
weights <- rep.int(1, nObs)
offset <- as.vector(model.offset(modelData))
if (is.null(offset))
offset <- rep.int(0, nObs)
if (is.character(family))
family <- get(family, mode = "function", envir = parent.frame())
if (is.function(family))
family <- family()
if (is.null(family$family)) {
print(family)
stop("`family' not recognized")
}
if (family$family == "binomial") {
if (is.factor(y) && NCOL(y) == 1)
y <- y != levels(y)[1]
else if (NCOL(y) == 2) {
n <- y[, 1] + y[, 2]
y <- ifelse(n == 0, 0, y[, 1]/n)
weights <- weights * n
}
}
empty <- is.empty.model(modelTerms)
if (!empty)
X <- model.matrix(formula(modelTerms), data = modelData, contrasts)
else
X <- matrix(, nObs, 0)
fit <- glmmPQL.fit(X = X, y = y, Z = Z, weights = weights, start = start,
etastart = etastart, mustart = mustart, offset = offset,
family = family, control = control, sigma = sigma,
sigma.fixed = sigma.fixed, ...)
if (sum(offset) && attr(modelTerms, "intercept") > 0) {
fit$null.deviance <- glm.fit(x = X[, "(Intercept)", drop = FALSE],
y = y, weights = weights, offset = offset, family = family,
control = glm.control(), intercept = TRUE)$deviance
}
if (model)
fit$model <- modelData
fit$na.action <- attr(modelData, "na.action")
if (x)
fit$x <- X
fit <- c(fit, list(call = call, formula = fixed, random = random,
terms = modelTerms,
data = data, offset = offset, control = control,
method = "glmmPQL.fit", contrasts = attr(X, "contrasts"),
xlevels = .getXlevels(modelTerms, modelData)))
class(fit) <- c("BTglmmPQL", "glm", "lm")
fit
} |
domino <- new.env()
domino.call <- function(cmd, stdInput=FALSE) {
if(domino.notFalse(stdInput)){
return(system(cmd, input=stdInput))
} else {
return(system(cmd))
}
}
domino.handleCommandNotFound = function(failureMessage){
stop(paste("Couldn't find domino client in the PATH or in default locations.
Add domino client directory path to PATH environment variable.
If you don't have domino client installed follow instructions on 'http://help.dominodatalab.com/client'.
If you use R-Studio Domino on GNU/Linux through a desktop launcher, add domino path to the .desktop file.
If you need more help, email [email protected] or visit http://help.dominodatalab.com/troubleshooting
- ", failureMessage), call.=FALSE)
}
domino.osSpecificPrefixOfDominoCommand <- function() {
os = Sys.info()["sysname"]
if(os == "Darwin") {return("/Applications/domino/")}
else if (os =="Linux") {return("~/domino/")}
else if (os == "Windows") {return("c:\\program files (x86)\\domino\\")}
else { print("Your operating system is not supported by domino R package.")}
}
domino.notFalse <- function(arg) {
if (arg == FALSE){FALSE} else { TRUE}
}
domino.OK <- function(){return(0)}
domino.projectNameWithoutUser <- function(projectName) {
rev(unlist(strsplit(projectName, "/")))[1]
}
domino.jumpToProjectsWorkingDirectory <- function(projectName) {
setwd(paste("./",domino.projectNameWithoutUser(projectName), sep=""))
print("Changed working directory to new project's directory.")
}
.is.domino.in.path <- function() {
nzchar(Sys.which("domino"))
}
.open.rStudio.login.prompt <- function(message){
if(Sys.getenv("RSTUDIO") != "1"){
stop("The system is not running in RStudio")
}
if(!("tools:rstudio" %in% search())){
stop("Cannot locate RStudio tools")
}
toolsEnv <- as.environment("tools:rstudio")
rStudioLoginPrompt <- get(".rs.askForPassword", envir=toolsEnv)
rStudioLoginPrompt(message)
}
.domino.login.prompt <- function(){
passwordPromptMessage <- "Enter your Domino password: "
password <- try(.open.rStudio.login.prompt(passwordPromptMessage), silent=T)
if(inherits(password, "try-error")){
password <- readline("Enter your Domino password: ")
}
if(password == ""){
password <- NULL
}
password
}
.onAttach <- function(libname, pkgname) {
domino$command_is_in_the_path <- .is.domino.in.path()
} |
layer_type.GeomEdgePath <- function(x) 'point' |
absval.iwres.vs.idv <-
function(object,
ylb = "|iWRES|",
smooth = TRUE,
idsdir = "up",
type = "p",
...) {
if(is.null(check.vars(c("idv","iwres"),
object,silent=FALSE))) {
return()
}
xplot <- xpose.plot.default(xvardef("idv",object),
xvardef("iwres",object),
object,
ylb=ylb,
funy="abs",
idsdir=idsdir,
smooth=smooth,
type = type,
...)
return(xplot)
} |
if (!isGeneric("unstack")) {
setGeneric("unstack", function(x, ...)
standardGeneric("unstack"))
}
setMethod("unstack", signature(x='RasterStack'),
function(x) {
return(x@layers)
} )
setMethod("unstack", signature(x='RasterBrick'),
function(x) {
if (nlayers(x) == 0) {
list()
} else {
lapply(1:nlayers(x), function(i) raster(x, i))
}
} ) |
html2tagList<-function(x){
x<-strsplit(gsub('>','>_AAA_',x),'_AAA_')[[1]]
x<-gsub('\\n','',x)
x<-x[!grepl('<!',x)]
x<-gsub('"',"'",x)
x<-gsub('</(.*?)>',"),",x)
attrIdx=grep('=',x)
attrVal=grep('=',x,value = T)
attrVal=gsub('>',",",attrVal)
attrVal=gsub('<','tags$',attrVal)
attrVal=sub('^ ','',attrVal)
attrVal=sub(' ',"(",attrVal)
x[attrIdx]=attrVal
x=gsub('<','tags$',x)
x=gsub('>',"(",x)
x=sub('^ ','',x)
x=sub(' )',')',x)
endIdx=grep('),',x)
endVal=grep('),',x,value = T)
endVal=paste0("'",gsub('),',"'),",endVal))
x[endIdx]=endVal
xout=paste0(x,collapse = '')
xout=gsub(',$','',xout)
xout<-eval(parse(text=sprintf('htmltools::tagList(list(%s))',xout),keep.source = TRUE))
return(xout)
} |
fun_summary <- function(msec) {
distant_homology <- NULL
total_read <- NULL
indel_status <- NULL
pre_minimum_length <- NULL
indel_length <- NULL
penalty_pre <- NULL
post_minimum_length <- NULL
penalty_post <- NULL
pre_support_length <- NULL
read_length <- NULL
post_support_length <- NULL
pre_minimum_length_adj <- NULL
pre_rep_status <- NULL
post_minimum_length_adj <- NULL
post_rep_status <- NULL
pre_support_length_adj <- NULL
post_support_length_adj <- NULL
minimum_length_1 <- NULL
minimum_length_2 <- NULL
minimum_length <- NULL
shortest_support_length_adj <- NULL
short_support_length <- NULL
mut_type <- NULL
alt_length <- NULL
altered_length <- NULL
short_support_length_adj <- NULL
half_length <- NULL
if (dim(msec)[1] > 0) {
msec <- msec %>% mutate(
distant_homology_rate = fun_zero(distant_homology, total_read)
)
msec <- msec %>% mutate(
pre_minimum_length_adj = ifelse(indel_status == 1,
(((pre_minimum_length - (indel_length + penalty_pre + 1)) +
abs(pre_minimum_length - (indel_length + penalty_pre + 1))) / 2) +
(indel_length + penalty_pre + 1),
(((pre_minimum_length - penalty_pre) +
abs(pre_minimum_length - penalty_pre)) / 2) +
penalty_pre),
post_minimum_length_adj = ifelse(indel_status == 1,
(((post_minimum_length - (indel_length + penalty_post + 1)) +
abs(post_minimum_length - (indel_length + penalty_post + 1))) / 2) +
(indel_length + penalty_post + 1),
(((post_minimum_length - penalty_post) +
abs(post_minimum_length - penalty_post)) / 2) +
penalty_post),
pre_support_length_adj = ifelse(indel_status == 1,
(((pre_support_length -
(read_length - indel_length - penalty_post - 1)) -
abs(pre_support_length -
(read_length - indel_length - penalty_post - 1))) / 2) +
(read_length - indel_length - penalty_post - 1),
(((pre_support_length - (read_length - alt_length - penalty_post)) -
abs(pre_support_length -
(read_length - alt_length - penalty_post))) / 2) +
(read_length - alt_length - penalty_post)),
post_support_length_adj = ifelse(indel_status == 1,
(((post_support_length -
(read_length - indel_length - penalty_pre - 1)) -
abs(post_support_length -
(read_length - indel_length - penalty_pre - 1))) / 2) +
(read_length - indel_length - penalty_pre - 1),
(((post_support_length - (read_length - alt_length - penalty_pre)) -
abs(post_support_length -
(read_length - alt_length - penalty_pre))) / 2) +
(read_length - alt_length - penalty_pre))
)
msec <- msec %>% mutate(
pre_minimum_length_adj = ifelse(indel_status == 1,
(((pre_minimum_length_adj - pre_rep_status - 1) +
abs(pre_minimum_length_adj - pre_rep_status - 1)) / 2) +
pre_rep_status + 1,
pre_minimum_length_adj),
post_minimum_length_adj = ifelse(indel_status == 1,
(((post_minimum_length_adj - post_rep_status - 1) +
abs(post_minimum_length_adj - post_rep_status - 1)) / 2) +
post_rep_status + 1,
post_minimum_length_adj),
pre_support_length_adj = ifelse(indel_status == 1,
(((pre_support_length_adj - (read_length - post_rep_status - 1)) -
abs(pre_support_length_adj - (read_length - post_rep_status - 1))) / 2) +
(read_length - post_rep_status - 1),
pre_support_length_adj),
post_support_length_adj = ifelse(indel_status == 1,
(((post_support_length_adj - (read_length - pre_rep_status - 1)) -
abs(post_support_length_adj - (read_length - pre_rep_status - 1))) / 2) +
(read_length - pre_rep_status - 1),
post_support_length_adj)
)
msec <- msec %>% mutate(
shortest_support_length_adj =
(((pre_minimum_length_adj - post_minimum_length_adj) -
abs(pre_minimum_length_adj - post_minimum_length_adj)) / 2) +
post_minimum_length_adj,
minimum_length_1 =
(((pre_rep_status - (indel_length + penalty_pre + 1)) +
abs(pre_rep_status - (indel_length + penalty_pre + 1))) / 2) +
(indel_length + penalty_pre + 1),
minimum_length_2 =
(((post_rep_status - (indel_length + penalty_post + 1)) +
abs(post_rep_status - (indel_length + penalty_post + 1))) / 2) +
(indel_length + penalty_post + 1)
)
msec <- msec %>% mutate(
minimum_length_1 = ifelse(indel_status == 1,
minimum_length_1, penalty_pre),
minimum_length_2 = ifelse(indel_status == 1,
minimum_length_2, penalty_post)
)
msec <- msec %>% mutate(
minimum_length =
(((minimum_length_1 - minimum_length_2) -
abs(minimum_length_1 - minimum_length_2)) / 2) +
minimum_length_2
)
msec <- msec %>% mutate(
shortest_support_length_adj =
((minimum_length - shortest_support_length_adj) +
abs(minimum_length - shortest_support_length_adj)) / 2 +
shortest_support_length_adj,
pre_minimum_length_adj =
((minimum_length_1 - pre_minimum_length_adj) +
abs(minimum_length_1 - pre_minimum_length_adj)) / 2 +
pre_minimum_length_adj,
post_minimum_length_adj =
((minimum_length_2 - post_minimum_length_adj) +
abs(minimum_length_2 - post_minimum_length_adj)) / 2 +
post_minimum_length_adj
)
msec <- msec %>% mutate(
short_support_length_adj =
(((short_support_length - minimum_length) +
abs(short_support_length - minimum_length)) / 2) +
minimum_length,
altered_length = ifelse(mut_type == "snv",
alt_length,
ifelse(mut_type == "ins",
indel_length,
0)),
half_length = as.integer((read_length - altered_length) / 2)
)
msec <- msec %>% mutate(
short_support_length_total =
short_support_length_adj - shortest_support_length_adj + 1,
pre_support_length_total =
pre_support_length_adj - pre_minimum_length_adj + 1,
post_support_length_total =
post_support_length_adj - post_minimum_length_adj + 1,
half_length_total =
half_length - minimum_length + 1,
total_length_total =
read_length - altered_length - minimum_length_1 - minimum_length_2 + 1
)
}
return(msec)
}
NULL |
zsolve <- function(mat, rel, rhs, sign, lat, lb, ub,
dir = tempdir(), quiet = TRUE, shell = FALSE, ...
){
if (!has_4ti2()) missing_4ti2_stop()
opts <- as.list(match.call(expand.dots = FALSE))[["..."]]
if(is.null(opts)){
opts <- ""
} else {
opts <- paste0("-", names(opts), "", unlist(opts))
opts <- paste(opts, collapse = " ")
}
dir.create(dir2 <- file.path(dir, timeStamp()))
oldWd <- getwd()
setwd(dir2); on.exit(setwd(oldWd), add = TRUE)
if(missing(mat) && missing(lat))
stop("Either mat or lat must be specified.", call. = FALSE)
if(!missing(mat) && !all(is.wholenumber(mat)))
stop("The entries of mat must all be integers.")
if(!missing(lat) && !all(is.wholenumber(lat)))
stop("The entries of lat must all be integers.")
if(!missing(rhs) && !all(is.wholenumber(rhs)))
stop("The entries of rhs must all be integers.")
if(!all(rel %in% c("<", ">")))
stop("rel must be a vector of \"<\"'s or \">\"'s.")
if(!missing(mat)) write.latte(mat, "system.mat")
write.latte(t(rel), "system.rel")
write.latte(t(rhs), "system.rhs")
if(!missing(sign)) write.latte(t(sign), "system.sign")
if(missing(mat) && !missing(lat)) write.latte(mat, "system.lat")
if(!missing(lb)) write.latte(mat, "system.lb")
if(!missing(ub)) write.latte(mat, "system.ub")
if (is_mac() || is_unix()) {
system2(
file.path(get_4ti2_path(), "zsolve"),
paste(opts, file.path(dir2, "system")),
stdout = "zsolve_out",
stderr = "zsolve_err"
)
shell_code <- glue(
"{file.path(get_4ti2_path(), 'zsolve')} {paste(opts, file.path(dir2, 'system'))} > zsolve_out 2> zsolve_err"
)
if(shell) message(shell_code)
} else if (is_win()) {
matFile <- file.path(dir2, "system")
matFile <- chartr("\\", "/", matFile)
matFile <- str_c("/cygdrive/c", str_sub(matFile, 3))
system2(
"cmd.exe",
glue("/c env.exe {file.path(get_4ti2_path(), 'zsolve')} {opts} {matFile}"),
stdout = "zsolve_out",
stderr = "zsolve_err"
)
shell_code <- glue(
"cmd.exe /c env.exe {file.path(get_4ti2_path(), 'zsolve')} {opts} {matFile} > zsolve_out 2> zsolve_err"
)
if(shell) message(shell_code)
}
if(!quiet) message(paste(readLines("zsolve_out"), "\n"))
std_err <- readLines("zsolve_err")
if(any(std_err != "")) warning(str_c(std_err, collapse = "\n"), call. = FALSE)
list(
zinhom = read.latte("system.zinhom"),
zhom = read.latte("system.zhom")
)
} |
codonise64 <- function(s){
m<-dim(s)[2]
n<-dim(s)[1]
if((m%%3)>0){
stop("length of coding sequence cannot divide by 3!")
}
t <- matrix(,n,m/3)
p <- seq(1,m,3)
q <- 1:(m/3)
s[s>=5] <- 100
t[ ,q] <- (s[ ,p]-1)*16 + (s[ ,p+1]-1)*4 + (s[ ,p+2]-1)+1
t[t>64]<-65
return(t)
} |
regrMultBy1or2point <- function(inDat,refLst,regrTo=c(1,0.5),silent=FALSE,callFrom=NULL){
fxNa <- .composeCallName(callFrom,newNa="regrMultBy1or2point")
checkEntr <- .checkRegrArguments(inDat,refLst,regrTo)
refLst <- checkEntr$refLst; regrTo <- checkEntr$regrTo
contrAve <- sapply(lapply(refLst,function(x) as.matrix(inDat[x,])),colMeans,na.rm=TRUE)
if(is.null(dim(contrAve))) contrAve <- matrix(contrAve,ncol=length(contrAve))
normFact <- if(length(refLst) ==1) (regrTo[1]/contrAve[,1]) else (regrTo[2]-regrTo[1])/(contrAve[,2]-contrAve[,1])
normFact <- cbind(k=normFact, d= if(length(refLst) ==1) rep(0,ncol(inDat)) else regrTo[1]-normFact*contrAve[,1])
matrix(rep(normFact[,1],each=nrow(inDat)),nrow=nrow(inDat))*inDat + matrix(rep(normFact[,2],each=nrow(inDat)),nrow=nrow(inDat)) }
|
summary.parameters <- function(object, ci.level = .9, ...) {
if (length(ci.level) != 1 | !is.numeric(ci.level)) stop("ci must be a numeric vector of length 1. ")
if (!inherits(object, "parameters")) stop("First argument has to be an object of class parameters. ")
UseMethod("summary.parameters")
}
summary.parameters.numeric <- function(object, ci.level = .9, ...) {
u <- qnorm(1-(1-ci.level)/2)
cov <- est_cov(object, ...)
sel <- names(object) %in% colnames(cov)
param_ci <- object[sel] %-+% (u * sqrt(diag(as.matrix(cov))))
out <- list(
param = object,
ci.level = ci.level,
ci = cbind(LCL = param_ci[, 1], param = object[sel], UCL = param_ci[, 2]),
cov = cov
)
class(out) <- c("summary.parameters")
out
}
summary.parameters.matrix <- function(object, ci.level = .9, ...) {
u <- qnorm(1-(1-ci.level)/2)
cov <- est_cov(object, ...)
sel <- paste(rownames(object), col(object), sep = "_") %in% colnames(cov)
param_ci <- as.vector(object[sel]) %-+% (u * sqrt(diag(as.matrix(cov))))
out <- list(
param = object,
ci.level = ci.level,
ci = cbind(LCL = param_ci[, 1], param = as.vector(object[sel]), UCL = param_ci[, 2]),
cov = cov
)
class(out) <- c("summary.parameters")
out
}
print.summary.parameters <- function(x, ...) {
if (any(attr(x$param, "source")$func %in% c("as.PWMs", "as.TLMoments", "as.parameters"))) {
cat("Distribution: ", toupper(attr(x$cov, "distribution")), "(", paste(names(x$param), round(x$param, 4), sep = "=", collapse = ", "), ")\n", sep = "")
cat("Confidence intervals based on assumptions: \n")
cat("\tTL(", paste0(attr(x$cov, "trimmings"), collapse = ","), ")\n", sep = "")
cat("\tn = ", attr(x$cov, "n"), "\n", sep = "")
} else {
ns <- attr(x$param, "source")$n
cat(length(ns), " data row(s) with n = ", paste0(ns, collapse = ", "), ".\n", sep = "")
cat("TL(", paste0(attr(x$param, "source")$trim, collapse = ","), ") used to generate ", toupper(attr(x$param, "distribution")), " parameters. \n", sep = "")
}
cat("\n")
cat("Approximate ", x$ci.level*100, "% confidence interval of parameters: \n", sep = "")
print(x$ci)
} |
generateNetwork <-
function(lambda_2=0.45, q=10, min_phase_length=1, k_bar=5, l=10,
lambda_3=2, spacing=1, gauss_weights=TRUE, same=FALSE,
change_method='sequential',
fixed=FALSE, cps=NULL) {
lambda_1 = 6
k = k_bar + 1;
epsilon = c();
if(!is.null(cps)) {
epsilon = cps;
k = length(epsilon);
} else if(!fixed) {
while(k > k_bar || any(c(epsilon, l) - c(0, epsilon) < min_phase_length)) {
k = rpois(1, lambda_1);
if(spacing == 1) {
epsilon = round(seq(round(l/k), l+1, length.out=(k+1)))
epsilon = epsilon[-length(epsilon)]
} else {
epsilon = sort(sample(1:l, k, replace=FALSE))
}
}
} else {
k = k - 1
if(spacing == 1) {
epsilon = round(seq(round(l/(k+1)), l+1, length.out=(k+1)))
epsilon = epsilon[-length(epsilon)]
} else {
epsilon = sort(sample(1:l, k, replace=FALSE))
while(any(c(epsilon, l) - c(0, epsilon) < min_phase_length)) {
epsilon = sort(sample(1:l, k, replace=FALSE))
}
}
}
parents = matrix(FALSE, q, q);
for(i in 1:q) {
num_parents = q+1;
while(num_parents > q) {
num_parents = rpois(1, lambda_2);
}
parents_i = 1:q %in% sample(1:q, num_parents, replace=FALSE)
parents[i, parents_i] = TRUE;
parents[i, i] = TRUE;
}
parents = t(parents);
weights_orig = matrix(rnorm(q*q, 0, 1), q, q);
network = fix_eigenvalues(parents*weights_orig, q, gauss_weights)
parents = abs(network) > 0;
parents_orig = parents;
parents_prev = parents;
network = list(); changes = list()
for(i in 1:(k+1)) {
if(change_method == 'hierarchical') {
parents = parents_orig
parents_prev = parents_orig
}
for(j in 1:q) {
change_num = rpois(1, lambda_3);
if(change_num > 0.5*q)
change_num = round(0.5*q)
add_edges = sum(runif(change_num) > 0.6);
remove_edges = change_num - add_edges;
parents_j = parents[,j];
edge_num = sum(parents_j);
non_edge_num = q - edge_num;
if(remove_edges > edge_num)
remove_edges = edge_num
if(edge_num > 0.5*q)
add_edges = 0;
new_parents_j = parents_j;
if(add_edges > 0) {
add_changes = 1:non_edge_num %in% sample(1:non_edge_num, add_edges, replace=FALSE)
edges = parents_j[parents_j == 0];
edges[add_changes] = 1;
new_parents_j[parents_j == 0] = edges;
}
if(remove_edges > 0) {
remove_changes = 1:edge_num %in% sample(1:edge_num, remove_edges, replace=FALSE)
non_edges = parents_j[parents_j > 0];
non_edges[remove_changes] = 0;
new_parents_j[parents_j>0] = non_edges;
}
if(!same) {
parents[,j] = new_parents_j;
}
}
parent_num = colSums(parents)
parent_num[parent_num == 0] = 1;
weights_phase = matrix(rnorm(q*q, 0, 1), q, q);
if(gauss_weights) {
network[[i]] = parents * weights_phase;
} else {
network[[i]] = parents
}
parents = abs(network[[i]]) > 0;
changes[[i]] = sum(abs(parents_prev - parents))
parents_prev = parents
}
epsilon = c(epsilon, l);
return(list(network=network, epsilon=epsilon, k=k, changes=changes, l=l))
} |
rm(list=ls())
library(SPOT)
library(babsim.hospital)
n <- 29
reps <- 10
funEvals <- 3*n
size <- 2*n
subsetN <- 100
nCores <- 8
progSpot <- matrix(NA, nrow = reps, ncol = 2*funEvals)
x0 <- matrix(as.numeric(babsim.hospital::getParaSet(5374)[1,-1]),1,)
bounds <- getBounds()
a <- bounds$lower
b <- bounds$upper
g <- function(x) {
return(rbind(a[1] - x[1], x[1] - b[1], a[2] - x[2], x[2] - b[2],
a[3] - x[3], x[3] - b[3], a[4] - x[4], x[4] - b[4],
a[5] - x[5], x[5] - b[5], a[6] - x[6], x[6] - b[6],
a[7] - x[7], x[7] - b[7], a[8] - x[8], x[8] - b[8],
a[9] - x[9], x[9] - b[9], a[10] - x[10], x[10] - b[10],
a[11] - x[11], x[11] - b[11], a[12] - x[12], x[12] - b[12],
a[13] - x[13], x[13] - b[13], a[14] - x[14], x[14] - b[14],
a[15] - x[15], x[15] - b[15], a[16] - x[16], x[16] - b[16],
a[17] - x[17], x[17] - b[17], a[18] - x[18], x[18] - b[18],
a[19] - x[19], x[19] - b[19], a[20] - x[20], x[20] - b[20],
a[21] - x[21], x[21] - b[21], a[22] - x[22], x[22] - b[22],
a[23] - x[23], x[23] - b[23], a[24] - x[24], x[24] - b[24],
a[25] - x[25], x[25] - b[25], a[26] - x[26], x[26] - b[26],
a[27] - x[27], x[27] - b[27], x[15] + x[16] - 1,
x[17] + x[18] + x[19] - 1, x[20] + x[21] - 1, x[23] + x[29] - 1)
)
}
for(r in 1:reps){
set.seed(r)
print(r)
sol <- spot(x = x0,
fun = funBaBSimHospital,
lower = a,
upper = b,
verbosity = 0,
nCores = nCores,
control = list(funEvals = 2*funEvals,
noise = TRUE,
designControl = list(
size = size,
retries = 1000),
optimizer = optimNLOPTR,
optimizerControl = list(
opts = list(algorithm = "NLOPT_GN_ISRES"),
eval_g_ineq = g),
model = buildKriging,
plots = FALSE,
progress = TRUE,
directOpt = optimNLOPTR,
directOptControl = list(
funEvals = 0),
eval_g_ineq = g,
subsetSelect = selectN,
subsetControl = list(N = subsetN))
)
progSpot[r, ] <- bov(sol$y, 2*funEvals)
}
progSpotHyb <- matrix(NA, nrow = reps, ncol = 2*funEvals)
for(r in 1:reps){
set.seed(r)
print(r)
solHyb <- spot(x = x0,
fun = funBaBSimHospital,
lower = a,
upper = b,
verbosity = 0,
nCores = nCores,
control = list(funEvals = funEvals,
noise = TRUE,
designControl = list(
size = size,
retries = 1000),
optimizer = optimNLOPTR,
optimizerControl = list(
opts = list(algorithm = "NLOPT_GN_ISRES"),
eval_g_ineq = g),
model = buildKriging,
plots = FALSE,
progress = TRUE,
directOpt = optimNLOPTR,
directOptControl = list(
funEvals = funEvals),
eval_g_ineq = g,
subsetSelect = selectN,
subsetControl = list(N = subsetN))
)
progSpotHyb[r, ] <- bov(solHyb$y, 2*funEvals)
}
matplot(t(progSpotHyb), type="l", col="red", lty=1, xlab="n: blackbox evaluations", ylab="best objective value", log="y")
abline(v=size, lty=2)
matlines(t(progSpot), type="l", col="gray", lty=1)
legend("topright", c("Spot", "SpotHyb"), col=c("gray", "red"), lty=1, bty="n")
resCompBartz07b <- list(progSpot= progSpot, progSpotHyb = progSpotHyb)
save(resCompBartz07b, file="resCompBartz07b.RData") |
logdensity_admkr = function(tau2, cpost)
{
dm = ncol(cpost) - 1
len = nrow(cpost)
band = vector(, dm + 1)
for(j in 1:(dm+1))
{
temp = tem2 = 0
for(i in 1:len)
{
temp = temp + cpost[i,j]
tem2 = tem2 + cpost[i,j]^2
}
sigma = sqrt(tem2/len - (temp/len)^2)
temp = exp(1.0/(dm + 5) * log(4/(dm + 3)))
band[j] = temp * sigma * exp(-1/(dm + 5) * log(len))
}
hprod = prod(band)
cont = exp(-0.5 * (dm+1) * log(2.0 * pi))
xsum = 0
for(i in 1:len)
{
temp = 0
for(j in 1:(dm + 1))
{
tem2 = (tau2[j] - cpost[i,j])/band[j]
temp = temp + tem2^2
}
xsum = xsum + cont * exp(-0.5 * temp)/hprod
}
hatf = log(xsum/len)
return(hatf)
}
logdensity_admkr = function(tau2, cpost)
{
dm = ncol(cpost)
len = nrow(cpost)
band = vector(,dm)
for(j in 1:dm)
{
temp = tem2 = 0
for(i in 1:len)
{
temp = temp + cpost[i,j]
tem2 = tem2 + cpost[i,j]^2
}
sigma = sqrt(tem2/len - (temp/len)^2)
temp = exp(1.0/(dm+5) * log(4/(dm+3)))
band[j] = temp * sigma * exp(-1/(dm+5) * log(len))
}
hprod = prod(band)
cont = exp(-0.5 * (dm+1))
} |
timeline <- function(df, events,
label.col = names(df)[1],
group.col = names(df)[2],
start.col = names(df)[3],
end.col = names(df)[4],
text.size = 4,
text.color = 'black',
num.label.steps = 5,
event.label.col,
event.col,
event.group.col,
event.spots = 1,
event.label = '',
event.label.method = 1,
event.line = FALSE,
event.text.size = 4,
event.above = TRUE,
limits,
...
) {
p <- ggplot()
if(!missing(events)) {
if(missing(event.label.col)) {
event.label.col <- names(events)[1]
}
if(missing(event.col)) {
event.col <- names(events)[2]
}
if(missing(event.group.col)) {
event.group.col <- NULL
}
} else {
event.spots <- 0
}
if(missing(limits)) {
if(missing(events)) {
limits <- range(c(df[,start.col], df[,end.col]), na.rm=TRUE)
} else if(missing(df)) {
limits <- range(events[,event.col], na.rm=TRUE)
} else {
limits <- range(c(df[,start.col], df[,end.col], events[,event.col]), na.rm=TRUE)
}
}
groups <- unique(df[,group.col])
xmin <- limits[1]
xmax <- limits[2]
ymin <- 0
ymax <- length(groups)
group.labels <- data.frame(group=groups,
x=rep(xmin, length(groups)),
y=rep(NA, length(groups)),
stringsAsFactors=FALSE)
df$ymin <- df$ymax <- NA
for(i in seq_along(groups)) {
df[which(df[,group.col] == groups[i]),]$ymin <-
ifelse(event.above, 0, event.spots - 1) + i - event.above
df[which(df[,group.col] == groups[i]),]$ymax <-
ifelse(event.above, 0, event.spots - 1) + i + !event.above
group.labels[which(group.labels$group == groups[i]),]$y <-
ifelse(event.above, 0, event.spots - 1) + i + !event.above
}
df$labelpos <- (df$ymin + df$ymax) / 2
if(!missing(events)) {
if(num.label.steps > 1) {
steps <- rev(seq(0, event.spots, by=event.spots/
(num.label.steps + 1))[2:(num.label.steps+1)])
events$y <- ifelse(event.above, ymax, 0) +
rep(steps, ceiling(nrow(events)/length(steps)))[1:nrow(events)]
} else {
events$y <- ifelse(event.above, ymax, 0)
}
}
group.labels <- rbind(group.labels, data.frame(group=event.label, x=xmin,
y=ifelse(event.above, ymax + 1, 1)))
df[df[,start.col] < xmin & df[,end.col] > xmin, start.col] <- xmin
df[df[,end.col] > xmax & df[,start.col] < xmax, end.col] <- xmax
if(!missing(events)) {
events <- events[events[,event.col] >= xmin & events[,event.col] <= xmax,]
if(event.line) {
p <- p + geom_segment(data=events,
aes_string(x=event.col, xend=event.col, yend='y'),
y=ifelse(event.above, ymin, event.spots), alpha=1)
}
}
p <- p +
geom_rect(data=df, aes_string(xmin=start.col, xmax=end.col,
ymin='ymin', ymax='ymax', fill=label.col), alpha=.9) +
geom_text(data=df, aes_string(y='labelpos', x=start.col, label=label.col),
hjust=-0.05, size=text.size, color=text.color) +
theme(legend.position='none',
axis.ticks.y=element_blank()) +
xlab('') + ylab('') +
xlim(c(xmin, xmax)) +
scale_y_continuous(breaks=group.labels$y-0.5,
labels=group.labels$group,
limits=c(ymin, ymax + event.spots),
minor_breaks=c())
if(!missing(events)) {
if(missing(event.group.col)) {
events$Group <- 'Group'
event.group.col <- 'Group'
}
if(event.label.method == 1) {
p <- p +
geom_point(data=events, aes_string(x=event.col, y='y',
color=event.group.col)) +
geom_text(data=events, aes_string(x=event.col, y='y',
label=event.label.col, color=event.group.col), hjust=-0.05,
size=event.text.size)
} else if(event.label.method == 2) {
p <- p +
geom_point(data=events, aes_string(x=event.col, y='y', color=event.group.col)) +
geom_text(data=events, aes_string(x=event.col, y='y', label=event.label.col,
color=event.group.col), angle=45,
vjust=ifelse(event.above, -0.15, 0),
hjust=ifelse(event.above, -0.15, 0),
size=event.text.size)
} else if(event.label.method == 3) {
p <- p +
geom_point(data=events, aes_string(x=event.col, y='y', color=event.group.col)) +
geom_text(data=events, aes_string(x=event.col, label=event.label.col,
color=event.group.col, y='y'), angle=90,
hjust=ifelse(event.above, -0.15, 0.15),
vjust=ifelse(event.above, 0, 0),
size=event.text.size)
}
if(length(unique(events[,event.group.col])) == 1) {
p <- p + scale_color_grey()
}
}
p <- p + geom_hline(yintercept=ifelse(event.above, 0, event.spots), size=1)
return(p)
} |
ilogit <- function(x) {
stats::plogis(x)
}
invlogit <- function(x) {
stats::plogis(x)
} |
buildElems <- function(elems, type) {
func <- paste0("build", type, "(")
res <- list()
params <- colnames(elems)
for (i in 1:nrow(elems)) {
command <- c()
for (j in 1:length(params)) {
command[j] <- paste0(params[j], " = ", "'", elems[i, j], "'")
}
command <- paste(command, collapse = ", ")
command <- paste0(func, command, ")")
res[[length(res) + 1]] <- eval(parse(text = command))
}
return(res)
} |
context("nonportable")
test_that("initialization", {
AC <- R6Class("AC",
portable = FALSE,
public = list(
x = 1,
initialize = function(x, y) {
self$x <- getx() + x
private$y <- y
},
getx = function() x,
gety = function() private$y
),
private = list(
y = 2
)
)
A <- AC$new(2, 3)
expect_identical(A$x, 3)
expect_identical(A$gety(), 3)
AC <- R6Class("AC", portable = FALSE, public = list(x = 1))
expect_error(AC$new(3))
})
test_that("empty members and methods are allowed", {
AC <- R6Class("AC", portable = FALSE)
expect_no_error(AC$new())
})
test_that("Private members are private, and self/private environments", {
AC <- R6Class("AC",
portable = FALSE,
public = list(
x = 1,
gety = function() private$y,
gety2 = function() y,
getx = function() self$x,
getx2 = function() x,
getx3 = function() getx_priv3(),
getx4 = function() getx_priv4()
),
private = list(
y = 2,
getx_priv3 = function() self$x,
getx_priv4 = function() x
)
)
A <- AC$new()
expect_identical(A$self, A)
expect_identical(A$private, parent.env(A))
expect_identical(A, environment(A$getx))
expect_identical(A, environment(A$private$getx_priv3))
expect_identical(A$x, 1)
expect_null(A$y)
expect_error(A$getx_priv3())
expect_identical(A$gety(), 2)
expect_identical(A$gety2(), 2)
expect_identical(A$getx(), 1)
expect_identical(A$getx2(), 1)
expect_identical(A$getx3(), 1)
expect_identical(A$getx4(), 1)
})
test_that("Active bindings work", {
AC <- R6Class("AC",
portable = FALSE,
public = list(
x = 5
),
active = list(
x2 = function(value) {
if (missing(value)) return(x * 2)
else x <<- value/2
}
)
)
A <- AC$new()
expect_identical(A$x2, 10)
A$x <- 20
expect_identical(A$x2, 40)
A$x2 <- 60
expect_identical(A$x2, 60)
expect_identical(A$x, 30)
})
test_that("Locking objects", {
AC <- R6Class("AC",
portable = FALSE,
public = list(x = 1, getx = function() x),
private = list(y = 2, gety = function() y),
lock_objects = TRUE
)
A <- AC$new()
expect_no_error(A$x <- 5)
expect_identical(A$x, 5)
expect_no_error(A$private$y <- 5)
expect_identical(A$private$y, 5)
expect_error(A$getx <- function() 1)
expect_error(A$gety <- function() 2)
expect_error(A$z <- 1)
expect_error(A$private$z <- 1)
AC <- R6Class("AC",
portable = FALSE,
public = list(x = 1, getx = function() x),
private = list(y = 2, gety = function() y),
lock_objects = FALSE
)
A <- AC$new()
expect_no_error(A$x <- 5)
expect_identical(A$x, 5)
expect_no_error(A$private$y <- 5)
expect_identical(A$private$y, 5)
expect_error(A$getx <- function() 1)
expect_error(A$private$gety <- function() 2)
expect_no_error(A$z <- 1)
expect_identical(A$z, 1)
expect_no_error(A$private$z <- 1)
expect_identical(A$private$z, 1)
})
test_that("Validity checks on creation", {
fun <- function() 1
expect_error(R6Class("AC", public = list(1)))
expect_error(R6Class("AC", private = list(1)))
expect_error(R6Class("AC", active = list(fun)))
expect_error(R6Class("AC", public = list(a=1, a=2)))
expect_error(R6Class("AC", public = list(a=1), private = list(a=1)))
expect_error(R6Class("AC", private = list(a=1), active = list(a=fun)))
expect_error(R6Class("AC", public = list(self = 1)))
expect_error(R6Class("AC", private = list(private = 1)))
expect_error(R6Class("AC", active = list(super = 1)))
expect_error(R6Class("AC", private = list(initialize = fun)))
expect_error(R6Class("AC", active = list(initialize = fun)))
})
test_that("default print method has a trailing newline", {
expect_output_n <- function(object) {
tmp <- tempfile()
on.exit(unlink(tmp))
sink(tmp)
print(object)
sink(NULL)
output <- readChar(tmp, nchars = 10000)
last_char <- substr(output, nchar(output), nchar(output))
expect_identical(last_char, "\n")
}
AC <- R6Class("AC")
expect_output_n(print(AC))
A <- AC$new()
expect_output_n(print(A))
AC <- R6Class("AC", private = list( x = 2 ))
expect_output_n(print(AC))
A <- AC$new()
expect_output_n(print(A))
}) |
globalVariables(c("..dimension_values"))
unspread_draws = function(data, ..., draw_indices = c(".chain", ".iteration", ".draw"), drop_indices = FALSE) {
result =
lapply(enquos(...), function(variable_spec) {
unspread_draws_(data, variable_spec, draw_indices = draw_indices)
}) %>%
reduce_(inner_join, by = draw_indices) %>%
as_tibble()
if (drop_indices) {
result %>%
select(-one_of(draw_indices))
} else {
result
}
}
unspread_draws_ = function(data, variable_spec, draw_indices = c(".chain", ".iteration", ".draw")) {
spec = parse_variable_spec(variable_spec)
variable_names = spec[[1]]
dimension_names = spec[[2]]
wide_dimension_name = spec[[3]]
if (!is.null(wide_dimension_name)) {
stop0("unspread_draws does not support the wide dimension syntax (`|`).")
}
data_subset = data %>%
ungroup() %>%
select(!!c(draw_indices, variable_names, dimension_names))
if (is.null(dimension_names)) {
return(distinct(data_subset))
}
data_distinct = data_subset %>%
unite(..dimension_values, !!!dimension_names, sep = ",") %>%
distinct()
lapply(variable_names, function(variable_name) {
data_distinct %>%
select(!!c(draw_indices, variable_name, "..dimension_values")) %>%
mutate(..variable = paste0(variable_name, "[", ..dimension_values, "]")) %>%
select(-..dimension_values) %>%
spread("..variable", !!variable_name)
}) %>%
reduce_(inner_join, by = draw_indices)
} |
if( identical( .Platform$OS.type, "windows" ) &&
identical( .Platform$r_arch, "x64" ) ){
print( "unit tests not run on windows 64 (workaround alert)" )
} else {
if(require("RUnit", quietly = TRUE)) {
require("RCurl", quietly = TRUE)
pkg <- "haploR"
if(Sys.getenv("RCMDCHECK") == "FALSE") {
path <- file.path(getwd(), "..", "inst", "unitTests")
} else {
path <- system.file(package=pkg, "unitTests")
}
cat("\nRunning unit tests:\n")
print(list(pkg=pkg, getwd=getwd(), pathToUnitTests=path))
library(package=pkg, character.only=TRUE)
testSuite <- defineTestSuite(name=paste(pkg, "unit testing"),
dirs=path,
testFuncRegexp = "^test_+",
testFileRegexp = "^test_+")
tests <- runTestSuite(testSuite)
pathReport <- file.path(path, "report")
printTextProtocol(tests, showDetails=FALSE)
tmp <- getErrors(tests)
if(tmp$nFail > 0 | tmp$nErr > 0) {
stop(paste("\n\nUnit testing failed (
}
} else {
print( "package RUnit not available, cannot run unit tests" )
}
} |
integral.linear <- function(t, size, parms) {
return(data.frame(time=t, metric= size + parms["alpha"] * t))
} |
{}
setSeed <- function(seed=NULL)
{
if(! exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE))
{
runif(1)
}
if(is.null(seed))
{
RNGstate <- get(".Random.seed", envir = .GlobalEnv)
} else {
R.seed <- get(".Random.seed", envir = .GlobalEnv)
assign("R.seed", R.seed, envir=parent.frame())
set.seed(seed)
RNGstate <- structure(seed, kind = as.list(RNGkind()))
do.call("on.exit",
list(quote(assign(".Random.seed", R.seed, envir = .GlobalEnv))),
envir = parent.frame())
}
return(RNGstate)
}
getResultList <- function(fun,
nsim,
vars,
parallel=NULL)
{
ret <-
if(is.null(parallel))
{
lapply(X=seq_len(nsim),
FUN=fun)
} else {
stopifnot(is.scalar(parallel), parallel > 0)
cores <- min(safeInteger(parallel),
min(parallel::detectCores(), 5))
cl <- parallel::makeCluster(cores)
parallel::clusterEvalQ(cl, {
library(crmPack)
NULL
})
parallel::clusterExport(cl=cl,
varlist=vars,
envir=parent.frame())
parallel::clusterExport(cl=cl,
varlist=ls(.GlobalEnv))
res <- parallel::parLapply(cl=cl,
X=seq_len(nsim),
fun=fun)
parallel::stopCluster(cl)
res
}
return(ret)
}
setMethod("simulate",
signature=
signature(object="Design",
nsim="ANY",
seed="ANY"),
def=
function(object, nsim=1L, seed=NULL,
truth, args=NULL, firstSeparate=FALSE,
mcmcOptions=McmcOptions(),
parallel=FALSE, nCores=
min(parallel::detectCores(), 5),
...){
nsim <- safeInteger(nsim)
stopifnot(is.function(truth),
is.bool(firstSeparate),
is.scalar(nsim),
nsim > 0,
is.bool(parallel),
is.scalar(nCores),
nCores > 0)
args <- as.data.frame(args)
nArgs <- max(nrow(args), 1L)
RNGstate <- setSeed(seed)
simSeeds <- sample(x=seq_len(1e5), size=nsim)
runSim <- function(iterSim)
{
set.seed(simSeeds[iterSim])
thisArgs <- args[(iterSim - 1) %% nArgs + 1, , drop=FALSE]
thisTruth <- function(dose)
{
do.call(truth,
c(dose,
thisArgs))
}
thisData <- object@data
if(thisData@placebo)
thisProb.PL <- thisTruth(object@data@doseGrid[1])
stopit <- FALSE
thisDose <- object@startingDose
while(! stopit)
{
thisProb <- thisTruth(thisDose)
thisSize <- size(cohortSize=object@cohortSize,
dose=thisDose,
data=thisData)
if(thisData@placebo)
thisSize.PL <- size(cohortSize=object@PLcohortSize,
dose=thisDose,
data=thisData)
if(firstSeparate && (thisSize > 1L))
{
thisDLTs <- rbinom(n=1L,
size=1L,
prob=thisProb)
if( thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- rbinom(n=1L,
size=1L,
prob=thisProb.PL)
if(thisDLTs == 0)
{
thisDLTs <- c(thisDLTs,
rbinom(n=thisSize - 1L,
size=1L,
prob=thisProb))
if( thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- c(thisDLTs.PL,
rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL))
}
} else {
thisDLTs <- rbinom(n=thisSize,
size=1L,
prob=thisProb)
if( thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL)
}
if( thisData@placebo && (thisSize.PL > 0L) ){
thisData <- update(object=thisData,
x=object@data@doseGrid[1],
y=thisDLTs.PL)
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
newCohort=FALSE)
}else{
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs)
}
doselimit <- maxDose(object@increments,
data=thisData)
thisSamples <- mcmc(data=thisData,
model=object@model,
options=mcmcOptions)
thisDose <- nextBest(object@nextBest,
doselimit=doselimit,
samples=thisSamples,
model=object@model,
data=thisData)$value
stopit <- stopTrial(object@stopping,
dose=thisDose,
samples=thisSamples,
model=object@model,
data=thisData)
}
thisFit <- fit(object=thisSamples,
model=object@model,
data=thisData)
thisResult <-
list(data=thisData,
dose=thisDose,
fit=
subset(thisFit,
select=c(middle, lower, upper)),
stop=
attr(stopit,
"message"))
return(thisResult)
}
resultList <- getResultList(fun=runSim,
nsim=nsim,
vars=
c("simSeeds",
"args",
"nArgs",
"firstSeparate",
"truth",
"object",
"mcmcOptions"),
parallel=if(parallel) nCores else NULL)
dataList <- lapply(resultList, "[[", "data")
recommendedDoses <- as.numeric(sapply(resultList, "[[", "dose"))
fitList <- lapply(resultList, "[[", "fit")
stopReasons <- lapply(resultList, "[[", "stop")
ret <- Simulations(data=dataList,
doses=recommendedDoses,
fit=fitList,
stopReasons=stopReasons,
seed=RNGstate)
return(ret)
})
setMethod("simulate",
signature=
signature(object="RuleDesign",
nsim="ANY",
seed="ANY"),
def=
function(object, nsim=1L, seed=NULL,
truth, args=NULL,
parallel=FALSE,
nCores=
min(parallel::detectCores(), 5),
...){
nsim <- safeInteger(nsim)
stopifnot(is.function(truth),
is.scalar(nsim),
nsim > 0,
is.bool(parallel))
args <- as.data.frame(args)
nArgs <- max(nrow(args), 1L)
RNGstate <- setSeed(seed)
simSeeds <- sample(x=seq_len(1e5), size=nsim)
runSim <- function(iterSim)
{
set.seed(simSeeds[iterSim])
thisArgs <- args[(iterSim - 1) %% nArgs + 1, , drop=FALSE]
thisTruth <- function(dose)
{
do.call(truth,
c(dose,
thisArgs))
}
thisData <- object@data
stopit <- FALSE
thisDose <- object@startingDose
while(! stopit)
{
thisProb <- thisTruth(thisDose)
thisSize <- size(cohortSize=object@cohortSize,
dose=thisDose,
data=thisData)
thisDLTs <- rbinom(n=thisSize,
size=1L,
prob=thisProb)
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs)
thisOutcome <- nextBest(object@nextBest,
data=thisData)
thisDose <- thisOutcome$value
stopit <- thisOutcome$stopHere
}
thisResult <-
list(data=thisData,
dose=thisDose)
return(thisResult)
}
resultList <- getResultList(fun=runSim,
nsim=nsim,
vars=
c("simSeeds",
"args",
"nArgs",
"truth",
"object"),
parallel=if(parallel) nCores else NULL)
dataList <- lapply(resultList, "[[", "data")
recommendedDoses <- as.numeric(sapply(resultList, "[[", "dose"))
ret <- GeneralSimulations(data=dataList,
doses=recommendedDoses,
seed=RNGstate)
return(ret)
})
setMethod("simulate",
signature=
signature(object="DualDesign"),
def=
function(object, nsim=1L, seed=NULL,
trueTox, trueBiomarker, args=NULL,
sigma2W, rho=0,
firstSeparate=FALSE,
mcmcOptions=McmcOptions(),
parallel=FALSE,
nCores=
min(parallel::detectCores(), 5),
...){
nsim <- safeInteger(nsim)
stopifnot(is.function(trueTox),
is.function(trueBiomarker),
is.scalar(sigma2W), sigma2W > 0,
is.scalar(rho), rho < 1, rho > -1,
is.bool(firstSeparate),
is.scalar(nsim),
nsim > 0,
is.bool(parallel))
args <- as.data.frame(args)
nArgs <- max(nrow(args), 1L)
trueToxArgnames <- names(formals(trueTox))[-1]
trueBiomarkerArgnames <- names(formals(trueBiomarker))[-1]
trueCov <- matrix(c(sigma2W, sqrt(sigma2W) * rho,
sqrt(sigma2W) * rho, 1),
nrow=2, byrow=TRUE)
RNGstate <- setSeed(seed)
simSeeds <- sample(x=seq_len(1e5), size=nsim)
runSim <- function(iterSim)
{
set.seed(simSeeds[iterSim])
thisArgs <- args[(iterSim - 1) %% nArgs + 1, , drop=FALSE]
thisTrueTox <- function(dose)
{
do.call(trueTox,
c(dose,
as.list(thisArgs)[trueToxArgnames]))
}
thisTrueBiomarker <- function(dose)
{
do.call(trueBiomarker,
c(dose,
as.list(thisArgs)[trueBiomarkerArgnames]))
}
thisData <- object@data
stopit <- FALSE
thisDose <- object@startingDose
if(thisData@placebo){
thisProb.PL <- thisTrueTox(object@data@doseGrid[1])
thisMeanZ.PL <- qlogis(thisProb.PL)
thisMeanBiomarker.PL <- thisTrueBiomarker(object@data@doseGrid[1])
}
while(! stopit)
{
thisProb <- thisTrueTox(thisDose)
thisMeanZ <- qlogis(thisProb)
thisMeanBiomarker <- thisTrueBiomarker(thisDose)
thisSize <- size(cohortSize=object@cohortSize,
dose=thisDose,
data=thisData)
if(thisData@placebo)
thisSize.PL <- size(cohortSize=object@PLcohortSize,
dose=thisDose,
data=thisData)
tmp <-
if(firstSeparate && (thisSize > 1L))
{
tmpStart <- mvtnorm::rmvnorm(n=1,
mean=
c(thisMeanBiomarker,
thisMeanZ),
sigma=trueCov)
if( thisData@placebo && (thisSize.PL > 0L) )
tmpStart.PL <- mvtnorm::rmvnorm(n=1,
mean=
c(thisMeanBiomarker.PL,
thisMeanZ.PL),
sigma=trueCov)
if(tmpStart[, 2] < 0)
{
tmpStart <-
rbind(tmpStart,
mvtnorm::rmvnorm(n=thisSize - 1,
mean=
c(thisMeanBiomarker,
thisMeanZ),
sigma=trueCov))
if( thisData@placebo && (thisSize.PL > 0L) )
tmpStart.PL <-
rbind(tmpStart.PL,
mvtnorm::rmvnorm(n=thisSize.PL,
mean=
c(thisMeanBiomarker.PL,
thisMeanZ.PL),
sigma=trueCov))
}
if(thisData@placebo && (thisSize.PL > 0L) ){
list(tmpStart=tmpStart, tmpStart.PL=tmpStart.PL)
}else{
list(tmpStart=tmpStart)
}
}else{
tmpStart <- mvtnorm::rmvnorm(n=thisSize,
mean=
c(thisMeanBiomarker,
thisMeanZ),
sigma=trueCov)
if(thisData@placebo && (thisSize.PL > 0L) )
tmpStart.PL <- mvtnorm::rmvnorm(n=thisSize.PL,
mean=
c(thisMeanBiomarker.PL,
thisMeanZ.PL),
sigma=trueCov)
if(thisData@placebo && (thisSize.PL > 0L) ){
list(tmpStart=tmpStart, tmpStart.PL=tmpStart.PL)
}else{
list(tmpStart=tmpStart)
}
}
thisBiomarkers <- tmp$tmpStart[, 1]
thisDLTs <- as.integer(tmp$tmpStart[, 2] > 0)
if(thisData@placebo && (thisSize.PL > 0L) ){
thisBiomarkers.PL <- tmp$tmpStart.PL[, 1]
thisDLTs.PL <- as.integer(tmp$tmpStart.PL[, 2] > 0)
thisData <- update(object=thisData,
x=object@data@doseGrid[1],
y=thisDLTs.PL,
w=thisBiomarkers.PL)
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
w=thisBiomarkers,
newCohort=FALSE)
}else{
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
w=thisBiomarkers)
}
doselimit <- maxDose(object@increments,
data=thisData)
thisSamples <- mcmc(data=thisData,
model=object@model,
options=mcmcOptions)
thisDose <- nextBest(object@nextBest,
doselimit=doselimit,
samples=thisSamples,
model=object@model,
data=thisData)$value
stopit <- stopTrial(object@stopping,
dose=thisDose,
samples=thisSamples,
model=object@model,
data=thisData)
}
thisFit <- fit(object=thisSamples,
model=object@model,
data=thisData)
thisResult <-
list(data=thisData,
dose=thisDose,
fitTox=
subset(thisFit,
select=
c(middle, lower, upper)),
fitBiomarker=
subset(thisFit,
select=
c(middleBiomarker, lowerBiomarker,
upperBiomarker)),
rhoEst=median(thisSamples@data$rho),
sigma2West=median(1/thisSamples@data$precW),
stop=
attr(stopit,
"message"))
return(thisResult)
}
resultList <- getResultList(fun=runSim,
nsim=nsim,
vars=
c("simSeeds",
"args",
"nArgs",
"firstSeparate",
"trueTox",
"trueBiomarker",
"trueCov",
"object",
"mcmcOptions"),
parallel=if(parallel) nCores else NULL)
dataList <- lapply(resultList, "[[", "data")
recommendedDoses <- as.numeric(sapply(resultList, "[[", "dose"))
rhoEstimates <- as.numeric(sapply(resultList, "[[", "rhoEst"))
sigma2Westimates <- as.numeric(sapply(resultList, "[[", "sigma2West"))
fitToxList <- lapply(resultList, "[[", "fitTox")
fitBiomarkerList <- lapply(resultList, "[[", "fitBiomarker")
stopReasons <- lapply(resultList, "[[", "stop")
ret <- DualSimulations(
data=dataList,
doses=recommendedDoses,
rhoEst=rhoEstimates,
sigma2West=sigma2Westimates,
fit=fitToxList,
fitBiomarker=fitBiomarkerList,
stopReasons=stopReasons,
seed=RNGstate)
return(ret)
})
setGeneric("examine",
def=
function(object, ..., maxNoIncrement=100L){
stopifnot(is.scalar(maxNoIncrement) && maxNoIncrement > 0)
standardGeneric("examine")
},
valueClass="data.frame")
setMethod("examine",
signature=
signature(object="Design"),
def=
function(object,
mcmcOptions=McmcOptions(),
...,
maxNoIncrement){
ret <- data.frame(dose=numeric(),
DLTs=integer(),
nextDose=numeric(),
stop=logical(),
increment=integer())
baseData <- object@data
stopit <- FALSE
noIncrementCounter <- 0L
thisDose <- object@startingDose
while(! stopit)
{
thisSize <- size(cohortSize=object@cohortSize,
dose=thisDose,
data=baseData)
if(baseData@placebo)
thisSize.PL <- size(cohortSize=object@PLcohortSize,
dose=thisDose,
data=baseData)
for(numDLTs in 0:thisSize)
{
if(baseData@placebo && (thisSize.PL > 0L) ){
thisData <- update(object=baseData,
x=baseData@doseGrid[1],
y=rep(0,thisSize.PL))
thisData <-
update(object=thisData,
x=thisDose,
y=
rep(x=c(0, 1),
times=
c(thisSize - numDLTs,
numDLTs)),
newCohort=FALSE)
}else{
thisData <-
update(object=baseData,
x=thisDose,
y=
rep(x=c(0, 1),
times=
c(thisSize - numDLTs,
numDLTs)))
}
doselimit <- maxDose(object@increments,
data=thisData)
thisSamples <- mcmc(data=thisData,
model=object@model,
options=mcmcOptions)
nextDose <- nextBest(object@nextBest,
doselimit=doselimit,
samples=thisSamples,
model=object@model,
data=thisData)$value
thisIncrement <-
round((nextDose - thisDose) / thisDose * 100)
stopThisTrial <- stopTrial(object@stopping,
dose=nextDose,
samples=thisSamples,
model=object@model,
data=thisData)
ret <- rbind(ret,
list(dose=thisDose,
DLTs=numDLTs,
nextDose=nextDose,
stop=stopThisTrial,
increment=as.integer(thisIncrement)))
}
if(baseData@placebo && (thisSize.PL > 0L) ){
baseData <-
update(object=baseData,
x=baseData@doseGrid[1],
y=rep(0, thisSize.PL))
baseData <-
update(object=baseData,
x=thisDose,
y=rep(0, thisSize),
newCohort=FALSE)
}else{
baseData <-
update(object=baseData,
x=thisDose,
y=rep(0, thisSize))
}
resultsNoDLTs <- subset(tail(ret, thisSize + 1),
dose==thisDose & DLTs==0)
newDose <- as.numeric(resultsNoDLTs$nextDose)
doseDiff <- newDose - thisDose
if(doseDiff == 0)
{
noIncrementCounter <- noIncrementCounter + 1L
} else {
noIncrementCounter <- 0L
}
stopAlready <- resultsNoDLTs$stop
thisDose <- newDose
stopNoIncrement <- (noIncrementCounter >= maxNoIncrement)
if(stopNoIncrement)
warning(paste("Stopping because",
noIncrementCounter,
"times no increment vs. previous dose"))
stopit <- (thisDose >= max(object@data@doseGrid)) ||
stopAlready || stopNoIncrement
}
return(ret)
})
setMethod("examine",
signature=
signature(object="RuleDesign"),
def=
function(object,
...,
maxNoIncrement){
ret <- data.frame(dose=numeric(),
DLTs=integer(),
nextDose=numeric(),
stop=logical(),
increment=integer())
baseData <- object@data
stopit <- FALSE
noIncrementCounter <- 0L
thisDose <- object@startingDose
while(! stopit)
{
thisSize <- size(cohortSize=object@cohortSize,
dose=thisDose,
data=baseData)
for(numDLTs in 0:thisSize)
{
thisData <-
update(object=baseData,
x=thisDose,
y=
rep(x=c(0, 1),
times=
c(thisSize - numDLTs,
numDLTs)))
thisOutcome <- nextBest(object@nextBest,
data=thisData)
nextDose <- thisOutcome$value
stopThisTrial <- thisOutcome$stopHere
thisIncrement <-
round((nextDose - thisDose) / thisDose * 100)
ret <- rbind(ret,
list(dose=thisDose,
DLTs=numDLTs,
nextDose=nextDose,
stop=stopThisTrial,
increment=as.integer(thisIncrement)))
}
baseData <-
update(object=baseData,
x=thisDose,
y=rep(0, thisSize))
resultsNoDLTs <- subset(tail(ret, thisSize + 1),
dose==thisDose & DLTs==0)
newDose <- as.numeric(resultsNoDLTs$nextDose)
doseDiff <- newDose - thisDose
if(doseDiff == 0)
{
noIncrementCounter <- noIncrementCounter + 1L
} else {
noIncrementCounter <- 0L
}
stopAlready <- resultsNoDLTs$stop
thisDose <- newDose
stopNoIncrement <- (noIncrementCounter >= maxNoIncrement)
if(stopNoIncrement)
warning(paste("Stopping because",
noIncrementCounter,
"times no increment vs. previous dose"))
stopit <- (thisDose >= max(object@data@doseGrid)) ||
stopAlready || stopNoIncrement
}
return(ret)
})
setMethod("simulate",
signature=
signature(object="TDsamplesDesign",
nsim="ANY",
seed="ANY"),
def=
function(object, nsim=1L, seed=NULL,
truth, args=NULL, firstSeparate=FALSE,
mcmcOptions=McmcOptions(),
parallel=FALSE, nCores=
min(parallel::detectCores(), 5),
...){
nsim <- safeInteger(nsim)
stopifnot(is.function(truth),
is.bool(firstSeparate),
is.scalar(nsim),
nsim > 0,
is.bool(parallel))
args <- as.data.frame(args)
nArgs <- max(nrow(args), 1L)
RNGstate <- setSeed(seed)
simSeeds <- sample(x=seq_len(1e5), size=nsim)
runSim <- function(iterSim)
{
set.seed(simSeeds[iterSim])
thisArgs <- args[(iterSim - 1) %% nArgs + 1, , drop=FALSE]
thisTruth <- function(dose)
{
do.call(truth,
c(dose,
thisArgs))
}
thisData <- object@data
if(thisData@placebo)
thisProb.PL <- thisTruth(object@data@doseGrid[1])
stopit <- FALSE
thisDose <- object@startingDose
while(! stopit)
{
thisProb <- thisTruth(thisDose)
thisSize <- size(cohortSize=object@cohortSize,
dose=thisDose,
data=thisData)
if(thisData@placebo)
thisSize.PL <- size(cohortSize=object@PLcohortSize,
dose=thisDose,
data=thisData)
if(firstSeparate && (thisSize > 1L))
{
thisDLTs <- rbinom(n=1L,
size=1L,
prob=thisProb)
if(thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- rbinom(n=1L,
size=1L,
prob=thisProb.PL)
if(thisDLTs == 0)
{
thisDLTs <- c(thisDLTs,
rbinom(n=thisSize - 1L,
size=1L,
prob=thisProb))
if( thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- c(thisDLTs.PL,
rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL))
}
} else {
thisDLTs <- rbinom(n=thisSize,
size=1L,
prob=thisProb)
if(thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL)
}
if(thisData@placebo && (thisSize.PL > 0L) ){
thisData <- update(object=thisData,
x=object@data@doseGrid[1],
y=thisDLTs.PL)
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
newCohort=FALSE)
} else {
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs)
}
thisModel <- update(object@model,
data=thisData)
doselimit <- maxDose(object@increments,
data=thisData)
thisSamples <- mcmc(data=thisData,
model=thisModel,
options=mcmcOptions)
NEXT<-nextBest(object@nextBest,
doselimit=doselimit,
samples=thisSamples,
model=thisModel,
data=thisData,
SIM=TRUE)
thisDose <- NEXT$nextdose
thisTDtargetDuringTrial<- NEXT$TDtargetDuringTrialEstimate
thisTDtargetEndOfTrial<- NEXT$TDtargetEndOfTrialEstimate
thisratioTDEOT <- NEXT$ratioTDEOT
thisCITDEOT <- list(lower=NEXT$CITDEOT[1],
upper=NEXT$CITDEOT[2])
thisTDtargetEndOfTrialatdoseGrid <- NEXT$TDtargetEndOfTrialAtDoseGrid
stopit <- stopTrial(object@stopping,
dose=thisDose,
samples=thisSamples,
model=thisModel,
data=thisData)
}
thisFit <- fit(object=thisSamples,
model=thisModel,
data=thisData)
thisResult <-
list(data=thisData,
dose=thisDose,
TDtargetDuringTrial=thisTDtargetDuringTrial,
TDtargetEndOfTrial=thisTDtargetEndOfTrial,
TDtargetEndOfTrialatdoseGrid=thisTDtargetEndOfTrialatdoseGrid,
TDtargetDuringTrialatdoseGrid=thisDose,
CITDEOT=thisCITDEOT,
ratioTDEOT= thisratioTDEOT,
fit=
subset(thisFit,
select=c(middle, lower, upper)),
stop=
attr(stopit,
"message"))
return(thisResult)
}
resultList <- getResultList(fun=runSim,
nsim=nsim,
vars=
c("simSeeds",
"args",
"nArgs",
"firstSeparate",
"truth",
"object",
"mcmcOptions"),
parallel=if(parallel) nCores else NULL)
dataList <- lapply(resultList, "[[", "data")
TDtargetDuringTrialList<- as.numeric(sapply(resultList, "[[", "TDtargetDuringTrial"))
TDtargetEndOfTrialList<- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrial"))
TDtargetDuringTrialDoseGridList<- as.numeric(sapply(resultList, "[[", "TDtargetDuringTrialatdoseGrid"))
TDtargetEndOfTrialDoseGridList<- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrialatdoseGrid"))
recommendedDoses <- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrialatdoseGrid"))
CIList <- lapply(resultList,"[[","CITDEOT")
ratioList<- as.numeric(sapply(resultList, "[[", "ratioTDEOT"))
CITDEOTList <- lapply(resultList,"[[","CITDEOT")
ratioTDEOTList<- as.numeric(sapply(resultList, "[[", "ratioTDEOT"))
fitList <- lapply(resultList, "[[", "fit")
stopReasons <- lapply(resultList, "[[", "stop")
ret <- PseudoSimulations(data=dataList,
doses=recommendedDoses,
fit=fitList,
FinalTDtargetDuringTrialEstimates=TDtargetDuringTrialList,
FinalTDtargetEndOfTrialEstimates=TDtargetEndOfTrialList,
FinalTDtargetDuringTrialAtDoseGrid=TDtargetDuringTrialDoseGridList,
FinalTDtargetEndOfTrialAtDoseGrid=TDtargetEndOfTrialDoseGridList,
FinalCIs=CIList,
FinalRatios=ratioList,
FinalTDEOTCIs=CITDEOTList,
FinalTDEOTRatios=ratioTDEOTList,
stopReasons=stopReasons,
seed=RNGstate)
return(ret)
})
setMethod("simulate",
signature=
signature(object="TDDesign",
nsim="ANY",
seed="ANY"),
def=
function(object, nsim=1L, seed=NULL,
truth, args=NULL, firstSeparate=FALSE,
parallel=FALSE, nCores=
min(parallel::detectCores(), 5),
...){
nsim <- safeInteger(nsim)
stopifnot(is.function(truth),
is.bool(firstSeparate),
is.scalar(nsim),
nsim > 0,
is.bool(parallel))
args <- as.data.frame(args)
nArgs <- max(nrow(args), 1L)
RNGstate <- setSeed(seed)
simSeeds <- sample(x=seq_len(1e5), size=nsim)
runSim <- function(iterSim)
{
set.seed(simSeeds[iterSim])
thisArgs <- args[(iterSim - 1) %% nArgs + 1, , drop=FALSE]
thisTruth <- function(dose)
{
do.call(truth,
c(dose,
thisArgs))
}
thisData <- object@data
if(thisData@placebo)
thisProb.PL <- thisTruth(object@data@doseGrid[1])
stopit <- FALSE
thisDose <- object@startingDose
while(! stopit)
{
thisProb <- thisTruth(thisDose)
thisSize <- size(cohortSize=object@cohortSize,
dose=thisDose,
data=thisData)
if(thisData@placebo)
thisSize.PL <- size(cohortSize=object@PLcohortSize,
dose=thisDose,
data=thisData)
if(firstSeparate && (thisSize > 1L))
{
thisDLTs <- rbinom(n=1L,
size=1L,
prob=thisProb)
if(thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- rbinom(n=1L,
size=1L,
prob=thisProb.PL)
if(thisDLTs == 0)
{
thisDLTs <- c(thisDLTs,
rbinom(n=thisSize - 1L,
size=1L,
prob=thisProb))
if( thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- c(thisDLTs.PL,
rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL))
}
} else {
thisDLTs <- rbinom(n=thisSize,
size=1L,
prob=thisProb)
if(thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL)
}
if(thisData@placebo && (thisSize.PL > 0L) ){
thisData <- update(object=thisData,
x=object@data@doseGrid[1],
y=thisDLTs.PL)
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
newCohort=FALSE)
} else {
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs)
}
thisModel <- update(object@model,
data=thisData)
doselimit <- maxDose(object@increments,data=thisData)
NEXT<-nextBest(object@nextBest,
doselimit=doselimit,
model=thisModel,
data=thisData,
SIM=TRUE)
thisDose <- NEXT$nextdose
thisTDtargetDuringTrial<- NEXT$TDtargetDuringTrialEstimate
thisTDtargetEndOfTrial<- NEXT$TDtargetEndOfTrialEstimate
thisTDtargetEndOfTrialatdoseGrid <- NEXT$TDtargetEndOfTrialatdoseGrid
thisCITDEOT <- list(lower=NEXT$CITFEOT[1],
upper=NEXT$CITFEOT[2])
thisratioTDEOT <- NEXT$ratioTDEOT
stopit <- stopTrial(object@stopping,
dose=thisDose,
model=thisModel,
data=thisData)
}
thisFit <- list(phi1=thisModel@phi1,
phi2=thisModel@phi2,
probDLE=thisModel@prob(object@data@doseGrid,
thisModel@phi1,thisModel@phi2))
thisResult <-
list(data=thisData,
dose=thisDose,
TDtargetDuringTrial=thisTDtargetDuringTrial,
TDtargetEndOfTrial=thisTDtargetEndOfTrial,
TDtargetEndOfTrialatdoseGrid=thisTDtargetEndOfTrialatdoseGrid,
TDtargetDuringTrialatdoseGrid=thisDose,
CITDEOT=thisCITDEOT,
ratioTDEOT= thisratioTDEOT,
fit=thisFit,
stop=
attr(stopit,
"message"))
return(thisResult)
}
resultList <- getResultList(fun=runSim,
nsim=nsim,
vars=
c("simSeeds",
"args",
"nArgs",
"firstSeparate",
"truth",
"object"),
parallel=if(parallel) nCores else NULL)
dataList <- lapply(resultList, "[[", "data")
TDtargetDuringTrialList<- as.numeric(sapply(resultList, "[[", "TDtargetDuringTrial"))
TDtargetEndOfTrialList<- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrial"))
TDtargetDuringTrialDoseGridList<- as.numeric(sapply(resultList, "[[", "TDtargetDuringTrialatdoseGrid"))
TDtargetEndOfTrialDoseGridList<- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrialatdoseGrid"))
recommendedDoses <- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrialatdoseGrid"))
CIList <- lapply(resultList,"[[","CITDEOT")
ratioList<- as.numeric(sapply(resultList, "[[", "ratioTDEOT"))
CITDEOTList <- lapply(resultList,"[[","CITDEOT")
ratioTDEOTList<- as.numeric(sapply(resultList, "[[", "ratioTDEOT"))
fitList <- lapply(resultList,"[[", "fit")
stopReasons <- lapply(resultList, "[[", "stop")
ret <- PseudoSimulations(data=dataList,
doses=recommendedDoses,
fit=fitList,
FinalTDtargetDuringTrialEstimates=TDtargetDuringTrialList,
FinalTDtargetEndOfTrialEstimates=TDtargetEndOfTrialList,
FinalTDtargetDuringTrialAtDoseGrid=TDtargetDuringTrialDoseGridList,
FinalTDtargetEndOfTrialAtDoseGrid=TDtargetEndOfTrialDoseGridList,
FinalCIs=CIList,
FinalRatios=ratioList,
FinalTDEOTCIs=CITDEOTList,
FinalTDEOTRatios=ratioTDEOTList,
stopReasons=stopReasons,
seed=RNGstate)
return(ret)
})
setMethod("simulate",
signature=
signature(object="DualResponsesDesign",
nsim="ANY",
seed="ANY"),
def=
function(object, nsim=1L, seed=NULL,
trueDLE, trueEff, trueNu,
args=NULL, firstSeparate=FALSE,
parallel=FALSE, nCores=
min(parallel::detectCores(), 5),
...){
nsim <- safeInteger(nsim)
stopifnot(is.function(trueDLE),
is.function(trueEff),
trueNu > 0,
is.bool(firstSeparate),
is.scalar(nsim),
nsim > 0,
is.bool(parallel))
args <- as.data.frame(args)
nArgs <- max(nrow(args), 1L)
trueDLEArgnames <- names(formals(trueDLE))[-1]
trueEffArgnames <- names(formals(trueEff))[-1]
RNGstate <- setSeed(seed)
simSeeds <- sample(x=seq_len(1e5), size=nsim)
runSim <- function(iterSim)
{
set.seed(simSeeds[iterSim])
thisArgs <- args[(iterSim - 1) %% nArgs + 1, , drop=FALSE]
thisTruthDLE <- function(dose)
{ do.call(trueDLE,
c(dose,
as.list(thisArgs)[trueDLEArgnames]))
}
thisTruthEff <- function (dose)
{
do.call(trueEff,
c(dose,
as.list(thisArgs)[trueEffArgnames]))
}
thisData <- object@data
trueSigma2<-1/trueNu
thisData <- object@data
if(thisData@placebo){
thisProb.PL <- thisTruthDLE(object@data@doseGrid[1])
thisMeanEff.PL <- thisTruthEff(object@data@doseGrid[1])
}
stopit <- FALSE
thisDose <- object@startingDose
while(! stopit)
{
thisDLEProb <- thisTruthDLE(thisDose)
thisMeanEff<-thisTruthEff(thisDose)
thisSize <- size(cohortSize=object@cohortSize,
dose=thisDose,
data=thisData)
if(thisData@placebo)
thisSize.PL <- size(cohortSize=object@PLcohortSize,
dose=thisDose,
data=thisData)
if(firstSeparate && (thisSize > 1L))
{
thisDLTs <- rbinom(n=1L,
size=1L,
prob=thisDLEProb)
if(thisData@placebo && (thisSize.PL > 0L) ) {
thisDLTs.PL <- rbinom(n=1L,
size=1L,
prob=thisProb.PL)}
thisEff <- rnorm(n=1L,
mean=thisMeanEff,
sd=sqrt(trueSigma2))
if (thisData@placebo && (thisSize.PL > 0L) ){
thisEff.PL <- rnorm(n=1L,
mean=thisMeanEff.PL,
sd=sqrt(trueSigma2))}
if(thisDLTs == 0)
{
thisDLTs <- c(thisDLTs,
rbinom(n=thisSize - 1L,
size=1L,
prob=thisDLEProb))
thisEff<-c(thisEff,
rnorm(n=thisSize - 1L,
mean=thisMeanEff,
sd=sqrt(trueSigma2)))
if( thisData@placebo && (thisSize.PL > 0L) ) {
thisDLTs.PL <- c(thisDLTs.PL,
rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL))
thisEff.PL <- c(thisMeanEff.PL,
rnorm(n=thisSize.PL,
mean=thisMeanEff.PL,
sd=sqrt(trueSigma2)))
}
}
} else {
thisDLTs <- rbinom(n=thisSize,
size=1L,
prob=thisDLEProb)
thisEff <- rnorm(n=thisSize,
mean=thisMeanEff,
sd=sqrt(trueSigma2))
if (thisData@placebo && (thisSize.PL > 0L) ){
thisDLTs.PL <- rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL)
thisEff.PL <- rnorm(n=thisSize.PL,
mean=thisMeanEff.PL,
sd=sqrt(trueSigma2))
}
}
if(thisData@placebo && (thisSize.PL > 0L) ){
thisData <- update(object=thisData,
x=object@data@doseGrid[1],
y=thisDLTs.PL,
w=thisEff.PL)
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
w=thisEff,
newCohort=FALSE)
} else {
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
w=thisEff)
}
thisDLEModel <- update(object=object@model,
data=thisData)
thisEffModel <- update(object=object@Effmodel,
data=thisData)
thisNu<-thisEffModel@nu
if (thisEffModel@useFixed==FALSE){
thisSigma2 <- 1/(as.numeric(thisNu["a"]/thisNu["b"]))} else {
thisSigma2 <- 1/thisNu}
doselimit <- maxDose(object@increments,data=thisData)
NEXT<-nextBest(object@nextBest,
doselimit=doselimit,
model=thisDLEModel,
data=thisData,
Effmodel=thisEffModel,
SIM=TRUE)
thisDose <- NEXT$nextdose
thisTDtargetDuringTrial <- NEXT$TDtargetDuringTrialEstimate
thisTDtargetDuringTrialAtDoseGrid<- NEXT$TDtargetDuringTrialAtDoseGrid
thisTDtargetEndOfTrial <- NEXT$TDtargetEndOfTrialEstimate
thisTDtargetEndOfTrialAtDoseGrid <- NEXT$TDtargetEndOfTrialAtDoseGrid
thisGstar <- NEXT$GstarEstimate
thisGstarAtDoseGrid <- NEXT$GstarAtDoseGrid
Recommend<- min(thisTDtargetEndOfTrialAtDoseGrid,thisGstarAtDoseGrid)
thisCITDEOT <- list(lower=NEXT$CITDEOT[1],
upper=NEXT$CITDEOT[2])
thisratioTDEOT <- NEXT$ratioTDEOT
thisCIGstar <- list(lower=NEXT$CIGstar[1],
upper=NEXT$CIGstar[2])
thisratioGstar <- NEXT$ratioGstar
OptimalDose <- min(thisGstar,thisTDtargetEndOfTrial)
if (OptimalDose==thisGstar){
thisratio <- thisratioGstar
thisCI<- thisCIGstar
} else { thisratio <- thisratioTDEOT
thisCI <- thisCITDEOT}
stopit <- stopTrial(object@stopping,
dose=thisDose,
model=thisDLEModel,
data=thisData,
Effmodel=thisEffModel)
}
thisDLEFit <- list(phi1=thisDLEModel@phi1,
phi2=thisDLEModel@phi2,
probDLE=thisDLEModel@prob(object@data@doseGrid,
thisDLEModel@phi1,thisDLEModel@phi2))
thisEffFit <- list(theta1=thisEffModel@theta1,
theta2=thisEffModel@theta2,
ExpEff=thisEffModel@ExpEff(object@data@doseGrid,
thisEffModel@theta1,
thisEffModel@theta2))
thisResult <- list(data=thisData,
dose=thisDose,
TDtargetDuringTrial=thisTDtargetDuringTrial ,
TDtargetDuringTrialAtDoseGrid=thisTDtargetDuringTrialAtDoseGrid,
TDtargetEndOfTrial=thisTDtargetEndOfTrial,
TDtargetEndOfTrialAtDoseGrid=thisTDtargetEndOfTrialAtDoseGrid,
Gstar=thisGstar,
GstarAtDoseGrid=thisGstarAtDoseGrid,
Recommend=Recommend,
OptimalDose=OptimalDose,
OptimalDoseAtDoseGrid=Recommend,
ratio=thisratio,
CI=thisCI,
ratioGstar=thisratioGstar,
CIGstar=thisCIGstar,
ratioTDEOT=thisratioTDEOT,
CITDEOT=thisCITDEOT,
fitDLE=thisDLEFit,
fitEff=thisEffFit,
sigma2est=thisSigma2,
stop=attr(stopit,
"message"))
return(thisResult)
}
resultList <- getResultList(fun=runSim,
nsim=nsim,
vars=
c("simSeeds",
"args",
"nArgs",
"firstSeparate",
"trueDLE",
"trueEff",
"trueNu",
"object"),
parallel=if(parallel) nCores else NULL)
dataList <- lapply(resultList, "[[", "data")
recommendedDoses <- as.numeric(sapply(resultList, "[[", "Recommend"))
TDtargetDuringTrialList<- as.numeric(sapply(resultList, "[[", "TDtargetDuringTrial"))
TDtargetEndOfTrialList<- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrial"))
TDtargetDuringTrialDoseGridList<- as.numeric(sapply(resultList, "[[", "TDtargetDuringTrialAtDoseGrid"))
TDtargetEndOfTrialDoseGridList<- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrialAtDoseGrid"))
GstarList <- as.numeric(sapply(resultList,"[[","Gstar"))
GstarAtDoseGridList <- as.numeric(sapply(resultList,"[[","GstarAtDoseGrid"))
OptimalDoseList <- as.numeric(sapply(resultList,"[[","OptimalDose"))
OptimalDoseAtDoseGridList <- as.numeric(sapply(resultList,"[[","Recommend"))
CIList <- lapply(resultList,"[[","CI")
ratioList<- as.numeric(sapply(resultList, "[[", "ratio"))
CITDEOTList <- lapply(resultList,"[[","CITDEOT")
ratioTDEOTList<- as.numeric(sapply(resultList, "[[", "ratioTDEOT"))
CIGstarList <- lapply(resultList,"[[","CIGstar")
ratioGstarList<- as.numeric(sapply(resultList, "[[", "ratioGstar"))
fitDLEList <- lapply(resultList,"[[","fitDLE")
fitEffList <- lapply(resultList,"[[","fitEff")
sigma2Estimates <- as.numeric(sapply(resultList, "[[", "sigma2est"))
stopReasons <- lapply(resultList, "[[", "stop")
ret <- PseudoDualSimulations(data=dataList,
doses=recommendedDoses,
FinalTDtargetDuringTrialEstimates=TDtargetDuringTrialList,
FinalTDtargetEndOfTrialEstimates=TDtargetEndOfTrialList,
FinalTDtargetDuringTrialAtDoseGrid=TDtargetDuringTrialDoseGridList,
FinalTDtargetEndOfTrialAtDoseGrid=TDtargetEndOfTrialDoseGridList,
FinalCIs=CIList,
FinalRatios=ratioList,
FinalGstarEstimates=GstarList,
FinalGstarAtDoseGrid=GstarAtDoseGridList,
FinalGstarCIs=CIGstarList,
FinalGstarRatios=ratioGstarList,
FinalTDEOTCIs=CITDEOTList,
FinalTDEOTRatios=ratioTDEOTList,
FinalOptimalDose=OptimalDoseList,
FinalOptimalDoseAtDoseGrid= OptimalDoseAtDoseGridList,
fit=fitDLEList,
fitEff=fitEffList,
sigma2est=sigma2Estimates,
stopReasons=stopReasons,
seed=RNGstate)
return(ret)
})
setMethod("simulate",
signature=
signature(object="DualResponsesSamplesDesign",
nsim="ANY",
seed="ANY"),
def=
function(object, nsim=1L, seed=NULL,
trueDLE, trueEff, trueNu=NULL,
trueSigma2=NULL,trueSigma2betaW=NULL,
args=NULL, firstSeparate=FALSE,
mcmcOptions=McmcOptions(),
parallel=FALSE, nCores=
min(parallel::detectCores(), 5),
...){
nsim <- safeInteger(nsim)
stopifnot(is.function(trueDLE),
is.bool(firstSeparate),
is.scalar(nsim),
nsim > 0,
is.bool(parallel))
isFlexi <- is(object@Effmodel, "EffFlexi")
if(isFlexi)
{
stopifnot(trueSigma2 > 0,
trueSigma2betaW > 0,
is.numeric(trueEff),
length(trueEff)==length(object@data@doseGrid))
args <- as.data.frame(args)
nArgs <- max(nrow(args), 1L)
trueDLEArgnames <- names(formals(trueDLE))[-1]
RNGstate <- setSeed(seed)
simSeeds <- sample(x=seq_len(1e5), size=nsim)
runSim <- function(iterSim)
{
set.seed(simSeeds[iterSim])
thisArgs <- args[(iterSim - 1) %% nArgs + 1, , drop=FALSE]
thisTruthDLE <- function(dose)
{
do.call(trueDLE,
c(dose,
thisArgs))
}
thisTruthEff <- trueEff
thisData <- object@data
stopit <- FALSE
thisDose <- object@startingDose
thisSigma2 <- trueSigma2
thisSigma2betaW <- trueSigma2betaW
while(! stopit)
{
thisDLEProb <- thisTruthDLE(thisDose)
thisDoseIndex <- which(thisDose==thisData@doseGrid)
thisMeanEff <- thisTruthEff[thisDoseIndex]
thisSize <- size(cohortSize=object@cohortSize,
dose=thisDose,
data=thisData)
if(thisData@placebo)
thisSize.PL <- size(cohortSize=object@PLcohortSize,
dose=thisDose,
data=thisData)
if(firstSeparate && (thisSize > 1L))
{
thisDLTs <- rbinom(n=1L,
size=1L,
prob=thisDLEProb)
if(thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- rbinom(n=1L,
size=1L,
prob=thisProb.PL)
thisEff <- rnorm(n=1L,
mean=thisMeanEff,
sd=sqrt(trueSigma2))
if (thisData@placebo && (thisSize.PL > 0L) )
thisEff.PL <- rnorm(n=1L,
mean=thisMeanEff.PL,
sd=sqrt(trueSigma2))
if(thisDLTs == 0)
{
thisDLTs <- c(thisDLTs,
rbinom(n=thisSize - 1L,
size=1L,
prob=thisDLEProb))
thisEff<-c(thisEff,
rnorm(n=thisSize - 1L,
mean=thisMeanEff,
sd=sqrt(trueSigma2)))
if( thisData@placebo && (thisSize.PL > 0L) ) {
thisDLTs.PL <- c(thisDLTs.PL,
rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL))
thisEff.PL <- c(thisMeanEff.PL,
rnorm(n=thisSize.PL,
mean=thisMeanEff.PL,
sd=sqrt(trueSigma2)))
}
}
} else {
thisDLTs <- rbinom(n=thisSize,
size=1L,
prob=thisDLEProb)
thisEff <- rnorm(n=thisSize,
mean=thisMeanEff,
sd=sqrt(trueSigma2))
if (thisData@placebo && (thisSize.PL > 0L) ){
thisDLTs.PL <- rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL)
thisEff.PL <- rnorm(n=thisSize.PL,
mean=thisMeanEff.PL,
sd=sqrt(trueSigma2))
}
}
if(thisData@placebo && (thisSize.PL > 0L) ){
thisData <- update(object=thisData,
x=object@data@doseGrid[1],
y=thisDLTs.PL,
w=thisEff.PL)
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
w=thisEff,
newCohort=FALSE)
} else {
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
w=thisEff)
}
thisDLEModel <- update(object=object@model,
data=thisData)
thisEffModel <- update(object=object@Effmodel,
data=thisData)
doselimit <- maxDose(object@increments,
data=thisData)
thisDLEsamples <- mcmc(data=thisData,
model=thisDLEModel,
options=mcmcOptions)
thisEffsamples <- mcmc(data=thisData,
model=thisEffModel,
options=mcmcOptions)
thisSigma2 <- mean(thisEffsamples@data$sigma2)
thisSigma2betaW <- mean(thisEffsamples@data$sigma2betaW)
NEXT<-nextBest(object@nextBest,
doselimit=doselimit,
samples=thisDLEsamples,
model=thisDLEModel,
Effmodel=thisEffModel,
Effsamples=thisEffsamples,
data=thisData,
SIM=TRUE)
thisDose <- NEXT$nextdose
thisTDtargetDuringTrial <- NEXT$TDtargetDuringTrialEstimate
thisTDtargetDuringTrialAtDoseGrid<- NEXT$TDtargetDuringTrialAtDoseGrid
thisTDtargetEndOfTrial <- NEXT$TDtargetEndOfTrialEstimate
thisTDtargetEndOfTrialAtDoseGrid <- NEXT$TDtargetEndOfTrialAtDoseGrid
thisGstar <- NEXT$GstarEstimate
thisGstarAtDoseGrid <- NEXT$GstarAtDoseGrid
Recommend<- min(thisTDtargetEndOfTrialAtDoseGrid,thisGstarAtDoseGrid)
thisCITDEOT <- list(lower=NEXT$CITDEOT[1],
upper=NEXT$CITDEOT[2])
thisratioTDEOT <- NEXT$ratioTDEOT
thisCIGstar <- list(lower=NEXT$CIGstar[1],
upper=NEXT$CIGstar[2])
thisratioGstar <- NEXT$ratioGstar
OptimalDose <- min(thisGstar,thisTDtargetEndOfTrial)
if (OptimalDose==thisGstar){
thisratio <- thisratioGstar
thisCI<- thisCIGstar
} else { thisratio <- thisratioTDEOT
thisCI <- thisCITDEOT}
stopit <- stopTrial(object@stopping,
dose=thisDose,
samples=thisDLEsamples,
model=thisDLEModel,
data=thisData,
TDderive=object@nextBest@TDderive,
Effmodel=thisEffModel,
Effsamples=thisEffsamples,
Gstarderive=object@nextBest@Gstarderive)
}
thisDLEFit <- fit(object=thisDLEsamples,
model=thisDLEModel,
data=thisData)
thisEffFit <- fit(object=thisEffsamples,
model=thisEffModel,
data=thisData)
thisResult <-
list(data=thisData,
dose=thisDose,
TDtargetDuringTrial=thisTDtargetDuringTrial ,
TDtargetDuringTrialAtDoseGrid=thisTDtargetDuringTrialAtDoseGrid,
TDtargetEndOfTrial=thisTDtargetEndOfTrial,
TDtargetEndOfTrialAtDoseGrid=thisTDtargetEndOfTrialAtDoseGrid,
Gstar=thisGstar,
GstarAtDoseGrid=thisGstarAtDoseGrid,
Recommend=Recommend,
OptimalDose=OptimalDose,
OptimalDoseAtDoseGrid=Recommend,
ratio=thisratio,
CI=thisCI,
ratioGstar=thisratioGstar,
CIGstar=thisCIGstar,
ratioTDEOT=thisratioTDEOT,
CITDEOT=thisCITDEOT,
fitDLE=subset(thisDLEFit,
select=
c(middle,lower,upper)),
fitEff=subset(thisEffFit,
select=
c(middle,lower,upper)),
sigma2est=thisSigma2,
sigma2betaWest=thisSigma2betaW,
stop=
attr(stopit,
"message"))
return(thisResult)
}
resultList <- getResultList(fun=runSim,
nsim=nsim,
vars=
c("simSeeds",
"args",
"nArgs",
"firstSeparate",
"trueDLE",
"trueEff",
"trueSigma2",
"trueSigma2betaW",
"object",
"mcmcOptions"),
parallel=if(parallel) nCores else NULL)
dataList <- lapply(resultList, "[[", "data")
recommendedDoses <- as.numeric(sapply(resultList, "[[", "Recommend"))
fitDLEList <- lapply(resultList,"[[","fitDLE")
fitEffList <- lapply(resultList,"[[","fitEff")
sigma2Estimates <- as.numeric(sapply(resultList, "[[", "sigma2est"))
sigma2betaWEstimates <- as.numeric(sapply(resultList, "[[", "sigma2betaWest"))
TDtargetDuringTrialList<- as.numeric(sapply(resultList, "[[", "TDtargetDuringTrial"))
TDtargetEndOfTrialList<- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrial"))
TDtargetDuringTrialDoseGridList<- as.numeric(sapply(resultList, "[[", "TDtargetDuringTrialAtDoseGrid"))
TDtargetEndOfTrialDoseGridList<- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrialAtDoseGrid"))
GstarList <- as.numeric(sapply(resultList,"[[","Gstar"))
GstarAtDoseGridList <- as.numeric(sapply(resultList,"[[","GstarAtDoseGrid"))
OptimalDoseList <- as.numeric(sapply(resultList,"[[","OptimalDose"))
OptimalDoseAtDoseGridList <- as.numeric(sapply(resultList,"[[","Recommend"))
CIList <- lapply(resultList,"[[","CI")
ratioList<- as.numeric(sapply(resultList, "[[", "ratio"))
CITDEOTList <- lapply(resultList,"[[","CITDEOT")
ratioTDEOTList<- as.numeric(sapply(resultList, "[[", "ratioTDEOT"))
CIGstarList <- lapply(resultList,"[[","CIGstar")
ratioGstarList<- as.numeric(sapply(resultList, "[[", "ratioGstar"))
stopReasons <- lapply(resultList, "[[", "stop")
ret <- PseudoDualFlexiSimulations(data=dataList,
doses=recommendedDoses,
FinalTDtargetDuringTrialEstimates=TDtargetDuringTrialList,
FinalTDtargetEndOfTrialEstimates=TDtargetEndOfTrialList,
FinalTDtargetDuringTrialAtDoseGrid=TDtargetDuringTrialDoseGridList,
FinalTDtargetEndOfTrialAtDoseGrid=TDtargetEndOfTrialDoseGridList,
FinalCIs=CIList,
FinalRatios=ratioList,
FinalGstarEstimates=GstarList,
FinalGstarAtDoseGrid=GstarAtDoseGridList,
FinalGstarCIs=CIGstarList,
FinalGstarRatios=ratioGstarList,
FinalTDEOTCIs=CITDEOTList,
FinalTDEOTRatios=ratioTDEOTList,
FinalOptimalDose=OptimalDoseList,
FinalOptimalDoseAtDoseGrid= OptimalDoseAtDoseGridList,
fit=fitDLEList,
fitEff=fitEffList,
sigma2est=sigma2Estimates,
sigma2betaWest=sigma2betaWEstimates,
stopReasons=stopReasons,
seed=RNGstate)
return(ret)
} else {
stopifnot(trueNu > 0,
is.function(trueEff))
args <- as.data.frame(args)
nArgs <- max(nrow(args), 1L)
trueDLEArgnames <- names(formals(trueDLE))[-1]
trueEffArgnames <- names(formals(trueEff))[-1]
RNGstate <- setSeed(seed)
simSeeds <- sample(x=seq_len(1e5), size=nsim)
runSim <- function(iterSim)
{
set.seed(simSeeds[iterSim])
thisArgs <- args[(iterSim - 1) %% nArgs + 1, , drop=FALSE]
thisTruthDLE <- function(dose)
{ do.call(trueDLE,
c(dose,
as.list(thisArgs)[trueDLEArgnames]))
}
thisTruthEff <- function (dose)
{
do.call(trueEff,
c(dose,
as.list(thisArgs)[trueEffArgnames]))
}
trueSigma2<-1/trueNu
thisData <- object@data
stopit <- FALSE
thisDose <- object@startingDose
while(! stopit)
{
thisDLEProb <- thisTruthDLE(thisDose)
thisMeanEff<-thisTruthEff(thisDose)
thisSize <- size(cohortSize=object@cohortSize,
dose=thisDose,
data=thisData)
if(firstSeparate && (thisSize > 1L))
{
thisDLTs <- rbinom(n=1L,
size=1L,
prob=thisDLEProb)
if(thisData@placebo && (thisSize.PL > 0L) )
thisDLTs.PL <- rbinom(n=1L,
size=1L,
prob=thisProb.PL)
thisEff <- rnorm(n=1L,
mean=thisMeanEff,
sd=sqrt(trueSigma2))
if (thisData@placebo && (thisSize.PL > 0L) )
thisEff.PL <- rnorm(n=1L,
mean=thisMeanEff.PL,
sd=sqrt(trueSigma2))
if(thisDLTs == 0)
{
thisDLTs <- c(thisDLTs,
rbinom(n=thisSize - 1L,
size=1L,
prob=thisDLEProb))
thisEff<-c(thisEff,
rnorm(n=thisSize - 1L,
mean=thisMeanEff,
sd=sqrt(trueSigma2)))
if( thisData@placebo && (thisSize.PL > 0L) ) {
thisDLTs.PL <- c(thisDLTs.PL,
rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL))
thisEff.PL <- c(thisMeanEff.PL,
rnorm(n=thisSize.PL,
mean=thisMeanEff.PL,
sd=sqrt(trueSigma2)))
}
}
} else {
thisDLTs <- rbinom(n=thisSize,
size=1L,
prob=thisDLEProb)
thisEff <- rnorm(n=thisSize,
mean=thisMeanEff,
sd=sqrt(trueSigma2))
if (thisData@placebo && (thisSize.PL > 0L) ){
thisDLTs.PL <- rbinom(n=thisSize.PL,
size=1L,
prob=thisProb.PL)
thisEff.PL <- rnorm(n=thisSize.PL,
mean=thisMeanEff.PL,
sd=sqrt(trueSigma2))
}
}
if(thisData@placebo && (thisSize.PL > 0L) ){
thisData <- update(object=thisData,
x=object@data@doseGrid[1],
y=thisDLTs.PL,
w=thisEff.PL)
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
w=thisEff,
newCohort=FALSE)
} else {
thisData <- update(object=thisData,
x=thisDose,
y=thisDLTs,
w=thisEff)
}
thisDLEModel <- update(object=object@model,
data=thisData)
thisEffModel <- update(object=object@Effmodel,
data=thisData)
thisNu<-thisEffModel@nu
thisDLEsamples <- mcmc(data=thisData,
model=thisDLEModel,
options=mcmcOptions)
thisEffsamples <- mcmc(data=thisData,
model=thisEffModel,
options=mcmcOptions)
if (thisEffModel@useFixed==FALSE){
thisSigma2 <- 1/(as.numeric(thisNu["a"]/thisNu["b"]))} else {
thisSigma2 <- 1/thisNu}
doselimit <- maxDose(object@increments,data=thisData)
NEXT<-nextBest(object@nextBest,
doselimit=doselimit,
samples=thisDLEsamples,
model=thisDLEModel,
data=thisData,
Effmodel=thisEffModel,
Effsamples=thisEffsamples,
SIM=TRUE)
thisDose <- NEXT$nextdose
thisTDtargetDuringTrial <- NEXT$TDtargetDuringTrialEstimate
thisTDtargetDuringTrialAtDoseGrid<- NEXT$TDtargetDuringTrialAtDoseGrid
thisTDtargetEndOfTrial <- NEXT$TDtargetEndOfTrialEstimate
thisTDtargetEndOfTrialAtDoseGrid <- NEXT$TDtargetEndOfTrialAtDoseGrid
thisGstar <- NEXT$GstarEstimate
thisGstarAtDoseGrid <- NEXT$GstarAtDoseGrid
Recommend<- min(thisTDtargetEndOfTrialAtDoseGrid,thisGstarAtDoseGrid)
thisCITDEOT <- list(lower=NEXT$CITDEOT[1],
upper=NEXT$CITDEOT[2])
thisratioTDEOT <- NEXT$ratioTDEOT
thisCIGstar <- list(lower=NEXT$CIGstar[1],
upper=NEXT$CIGstar[2])
thisratioGstar <- NEXT$ratioGstar
OptimalDose <- min(thisGstar,thisTDtargetEndOfTrial)
if (OptimalDose==thisGstar){
thisratio <- thisratioGstar
thisCI<- thisCIGstar
} else { thisratio <- thisratioTDEOT
thisCI <- thisCITDEOT}
stopit <- stopTrial(object@stopping,
dose=thisDose,
samples=thisDLEsamples,
model=thisDLEModel,
data=thisData,
TDderive=object@nextBest@TDderive,
Effmodel=thisEffModel,
Effsamples=thisEffsamples,
Gstarderive=object@nextBest@Gstarderive)
}
thisDLEFit <- fit(object=thisDLEsamples,
model=thisDLEModel,
data=thisData)
thisEffFit <- fit(object=thisEffsamples,
model=thisEffModel,
data=thisData)
thisResult <- list(data=thisData,
dose=thisDose,
TDtargetDuringTrial=thisTDtargetDuringTrial ,
TDtargetDuringTrialAtDoseGrid=thisTDtargetDuringTrialAtDoseGrid,
TDtargetEndOfTrial=thisTDtargetEndOfTrial,
TDtargetEndOfTrialAtDoseGrid=thisTDtargetEndOfTrialAtDoseGrid,
Gstar=thisGstar,
GstarAtDoseGrid=thisGstarAtDoseGrid,
Recommend=Recommend,
OptimalDose=OptimalDose,
OptimalDoseAtDoseGrid=Recommend,
ratio=thisratio,
CI=thisCI,
ratioGstar=thisratioGstar,
CIGstar=thisCIGstar,
ratioTDEOT=thisratioTDEOT,
CITDEOT=thisCITDEOT,
fitDLE=subset(thisDLEFit,
select=
c(middle,lower,upper)),
fitEff=subset(thisEffFit,
select=
c(middle,lower,upper)),
sigma2est=thisSigma2,
stop=attr(stopit,
"message"))
return(thisResult)
}
resultList <- getResultList(fun=runSim,
nsim=nsim,
vars=
c("simSeeds",
"args",
"nArgs",
"firstSeparate",
"trueDLE",
"trueEff",
"trueNu",
"object"),
parallel=if(parallel) nCores else NULL)
dataList <- lapply(resultList, "[[", "data")
recommendedDoses <- as.numeric(sapply(resultList, "[[", "Recommend"))
TDtargetDuringTrialList<- as.numeric(sapply(resultList, "[[", "TDtargetDuringTrial"))
TDtargetEndOfTrialList<- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrial"))
TDtargetDuringTrialDoseGridList<- as.numeric(sapply(resultList, "[[", "TDtargetDuringTrialAtDoseGrid"))
TDtargetEndOfTrialDoseGridList<- as.numeric(sapply(resultList, "[[", "TDtargetEndOfTrialAtDoseGrid"))
GstarList <- as.numeric(sapply(resultList,"[[","Gstar"))
GstarAtDoseGridList <- as.numeric(sapply(resultList,"[[","GstarAtDoseGrid"))
OptimalDoseList <- as.numeric(sapply(resultList,"[[","OptimalDose"))
OptimalDoseAtDoseGridList <- as.numeric(sapply(resultList,"[[","Recommend"))
CIList <- lapply(resultList,"[[","CI")
ratioList<- as.numeric(sapply(resultList, "[[", "ratio"))
CITDEOTList <- lapply(resultList,"[[","CITDEOT")
ratioTDEOTList<- as.numeric(sapply(resultList, "[[", "ratioTDEOT"))
CIGstarList <- lapply(resultList,"[[","CIGstar")
ratioGstarList<- as.numeric(sapply(resultList, "[[", "ratioGstar"))
fitDLEList <- lapply(resultList,"[[","fitDLE")
fitEffList <- lapply(resultList,"[[","fitEff")
sigma2Estimates <- as.numeric(sapply(resultList, "[[", "sigma2est"))
stopReasons <- lapply(resultList, "[[", "stop")
ret <- PseudoDualSimulations(data=dataList,
doses=recommendedDoses,
FinalTDtargetDuringTrialEstimates=TDtargetDuringTrialList,
FinalTDtargetEndOfTrialEstimates=TDtargetEndOfTrialList,
FinalTDtargetDuringTrialAtDoseGrid=TDtargetDuringTrialDoseGridList,
FinalTDtargetEndOfTrialAtDoseGrid=TDtargetEndOfTrialDoseGridList,
FinalCIs=CIList,
FinalRatios=ratioList,
FinalGstarEstimates=GstarList,
FinalGstarAtDoseGrid=GstarAtDoseGridList,
FinalGstarCIs=CIGstarList,
FinalGstarRatios=ratioGstarList,
FinalTDEOTCIs=CITDEOTList,
FinalTDEOTRatios=ratioTDEOTList,
FinalOptimalDose=OptimalDoseList,
FinalOptimalDoseAtDoseGrid=OptimalDoseAtDoseGridList,
fit=fitDLEList,
fitEff=fitEffList,
sigma2est=sigma2Estimates,
stopReasons=stopReasons,
seed=RNGstate)
return(ret)
}
}) |
test_that("testJob", {
reg = makeTestRegistry()
f = function(x) if (x %% 2 == 0) stop("foo") else x^2
batchMap(reg = reg, f, 1:3)
expect_equal(testJob(reg = reg, id = 1), 1)
expect_equal(testJob(reg = reg, id = 3), 9)
expect_error(testJob(reg = reg, id = 2), "foo")
expect_equal(suppressAll(testJob(reg = reg, id = 1, external = TRUE)), 1)
expect_error(suppressAll(testJob(reg = reg, id = 2, external = TRUE)), "re-run")
expect_equal(findSubmitted(reg = reg), data.table(job.id = integer(0L), key = "job.id"))
expect_equal(findDone(reg = reg), data.table(job.id = integer(0L), key = "job.id"))
expect_equal(findErrors(reg = reg), data.table(job.id = integer(0L), key = "job.id"))
})
test_that("testJob.ExperimentRegistry", {
reg = makeTestExperimentRegistry()
prob = addProblem(reg = reg, "p1", data = iris, fun = function(job, data, ...) nrow(data), seed = 42)
algo = addAlgorithm(reg = reg, "a1", fun = function(job, data, instance, sq, ...) instance^sq)
ids = addExperiments(prob.designs = list(p1 = data.table()), algo.designs = list(a1 = data.table(sq = 1:3)), reg = reg)
suppressAll(x <- testJob(id = 1, reg = reg))
expect_equal(x, 150)
suppressAll(x <- testJob(id = 2, reg = reg, external = TRUE))
expect_equal(x, 150^2)
})
test_that("traceback works in external session", {
reg = makeTestRegistry()
f = function(x) {
g = function(x) findme(x)
findme = function(x) h(x)
h = function(x) stop("Error in h")
g(x)
}
batchMap(f, 1, reg = reg)
expect_output(expect_error(testJob(1, external = TRUE, reg = reg), "external=FALSE"), "findme")
}) |
size.comparing.variances <- function(ratio,alpha,power)
{
g <- function(n){
qf(1-alpha/2,n-1,n-1)*qf(power,n-1,n-1)-ratio
}
u <- uniroot(g,c(ratio,1000*ratio))$root
ceiling(u)
} |
myDirichlet <- function(alpha){
k <- length(alpha)
theta <- rgamma(k, shape = alpha, rate = 1)
return(theta/sum(theta))
}
toSolve <- function(a,n,p0){
myVals <- exp(lgamma(2*a) - lgamma(a) + lgamma(a+n) - lgamma(2*a + n) + log(2))
l <- abs(myVals - p0)
return(a[which(l == min(l))][1])
}
complete.loglikelihood<-function(x,z,pars){
g <- dim(pars)[1]
n <- dim(x)[1]
J <- dim(pars)[2]
d <- dim(x)[2]
logl <- rep(0, n)
logpi <- log(pars[,J])
z <- as.numeric(z)
for (j in 1:d){
logl <- logl + dbinom(x[,j], size = 1, prob = pars[,j][z], log = TRUE)
}
logl <- logl + logpi[z]
return(sum(logl))
}
gibbsBinMix <- function(alpha,beta,gamma,K,m,burn,data,thinning,z.true,outputDir){
if (missing(K)) {stop(cat(paste(" [ERROR]: number of clusters (K) not provided."), "\n"))}
if (missing(m)) {stop(cat(paste(" [ERROR]: number of MCMC iterations (m) not provided."), "\n"))}
if (missing(thinning)) {thinning <- 5}
if (K < 2) {
stop(cat(paste(" [ERROR]: number of clusters (K) should be at least equal to 2."), "\n"))
}
d <- dim(data)[2]
if (burn > m - 1) {
stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n"))
}
if (burn < 0) {
stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n"))
}
if (thinning > m) {
stop(cat(paste(" [ERROR]: thinning not valid."), "\n"))
}
if (m < 1) {
stop(cat(paste(" [ERROR]: mcmc iterations (m) not valid."), "\n"))
}
if (missing(alpha)) {alpha <- 1}
if (missing(beta)) {beta <- 1}
if (missing(gamma)) {gamma <- rep(1,K)}
if (missing(data)) {stop(cat(paste(" [ERROR]: data is missing."), "\n"))}
n <- dim(data)[1]
x <- data
dir.create(outputDir)
setwd(outputDir)
p <- myDirichlet(rep(1,K))
theta <- array(data = runif(K*d), dim = c(K,d))
z <- sample(K,n,replace=TRUE,prob = p)
s <- l <- newL <- numeric(K)
sx <- array(data = 0, dim = c(K,d))
theta.file <- "theta.txt"
z.file <- "z.txt"
p.file <- "p.txt"
conTheta = file(theta.file,open = "w")
conZ = file(z.file,open = "w")
conP = file(p.file,open = "w")
for (iter in 1:m){
s <- rep(0,K)
sx <- array(data = 0, dim = c(K,d))
for(i in 1:n){
for(k in 1:K){
l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,]))
}
for(k in 1:K){
newL[k] <- 1/sum(exp(l - l[k]))
}
z[i] <- sample(K,1,prob = newL)
s[z[i]] <- s[z[i]] + 1
sx[z[i],] <- sx[z[i],] + x[i,]
}
p <- myDirichlet(gamma + s)
for(k in 1:K){
theta[k,] <- rbeta(d, shape1 = alpha + sx[k,], shape2 = beta + s[k] - sx[k,])
}
if((iter %% thinning == 0)&(iter > burn)){
cat(theta,"\n",file=conTheta)
cat(z,"\n",file=conZ)
cat(p,"\n",file=conP)
}
if(iter %% (m/100) == 0){
cat(paste("Running Gibbs: ",100*round(iter/m,3),"% completed.",sep=""),"\n");
}
}
close(conTheta)
close(conP)
close(conZ)
cat(paste("Gibbs finished."),"\n")
cat("\n")
cat(paste("Dealing with Label Switching..."),"\n")
tt <- read.table("theta.txt")
m <- dim(tt)[1]
d <- dim(x)[2]
J <- d + 1
mcmc <- array(data = NA, dim = c(m,K,J))
for (j in 1:d){
for(k in 1:K){
mcmc[,k,j] <- tt[,(j-1)*K + k]
}
}
tt <- read.table("p.txt")
for(k in 1:K){
mcmc[,k,J] <- tt[,k]
}
allocations <- as.matrix(read.table("z.txt",as.is = TRUE))
m <- dim(mcmc)[1]
iter <- 1
ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,])
maxLL <- ll
maxIter <- iter
for (iter in 1:m){
ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,])
if(ll > maxLL){maxLL <- ll;maxIter <- iter;cat(paste("Found new Complete MLE: ", ll,sep=""),"\n")}
}
pMatrix <- array(data = NA, dim = c(m,n,K))
for (iter in 1:m){
p <- mcmc[iter,,J]
theta <- array( mcmc[iter,,1:(J-1)],dim = c(K,J-1) )
for(i in 1:n){
for(k in 1:K){
l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,]))
}
for(k in 1:K){
pMatrix[iter,i,k] <- 1/sum(exp(l - l[k]))
if(is.na(pMatrix[iter,i,k]) == TRUE){pMatrix[iter,i,k] = 0}
}
}
if(iter %% 1000 == 0){cat(paste(" classification probs: ",100*round(iter/m,3),"% completed",sep=""),"\n");}
}
if(missing(z.true)==TRUE){
ls <- label.switching( K = K, method = c("STEPHENS","ECR","ECR-ITERATIVE-1"),
zpivot = allocations[maxIter,], z = allocations, complete = complete.loglikelihood, data = x,
mcmc = mcmc,prapivot = mcmc[maxIter,,], p = pMatrix)
}else{
ls <- label.switching( K = K, method = c("STEPHENS","ECR","ECR-ITERATIVE-1"),
zpivot = allocations[maxIter,], z = allocations, complete = complete.loglikelihood, data = x,
mcmc = mcmc,p = pMatrix,groundTruth = z.true)
}
allocationsECR <- allocationsKL <- allocationsECR.ITERATIVE1 <- allocations
for (i in 1:m){
myPerm <- order(ls$permutations$"ECR"[i,])
allocationsECR[i,] <- myPerm[allocations[i,]]
myPerm <- order(ls$permutations$"STEPHENS"[i,])
allocationsKL[i,] <- myPerm[allocations[i,]]
myPerm <- order(ls$permutations$"ECR-ITERATIVE-1"[i,])
allocationsECR.ITERATIVE1[i,] <- myPerm[allocations[i,]]
}
write.table(allocationsECR, file = "z.ECR.txt")
write.table(allocationsKL, file = "z.KL.txt")
write.table(allocationsECR.ITERATIVE1, file = "z.ECR-ITERATIVE1.txt")
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR")$output
tt <- read.table("theta.txt")
write.table(reordered.mcmc, file = "reorderedMCMC-ECR.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR-ITERATIVE-1")$output
write.table(reordered.mcmc, file = "reorderedMCMC-ECR-ITERATIVE1.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"STEPHENS")$output
write.table(reordered.mcmc, file = "reorderedMCMC-STEPHENS.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
write.table(mcmc, file = "rawMCMC.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
write.table(file = "reorderedSingleBestClusterings.txt",t(ls$clusters[c(1,2,3),]),row.names = paste("z",1:n,sep="."))
file.remove("p.txt")
file.remove("theta.txt")
cat(paste("raw MCMC parameters written to: \'rawMCMC.txt\' "),"\n")
cat(paste("raw MCMC latent allocations written to: \'z.txt\' "),"\n")
cat(paste("reordered MCMC output written to: "),"\n")
cat(paste(" (Method 1): \'reorderedMCMC-ECR.txt\'"),"\n")
cat(paste(" (Method 2): \'reorderedMCMC-ECR-ITERATIVE1.txt\'"),"\n")
cat(paste(" (Method 3): \'reorderedMCMC-STEPHENS.txt\'"),"\n")
cat(paste("reordered single best clusterings written to: \'reorderedSingleBestClusterings.txt\' "),"\n")
cat(paste("reordered MCMC latent allocations written to: "),"\n")
cat(paste(" (Method 1): \'z.ECR.txt\'"),"\n")
cat(paste(" (Method 2): \'z.KL.txt\'"),"\n")
cat(paste(" (Method 3): \'z.ECR-ITERATIVE1.txt\'"),"\n")
setwd("../")
}
collapsedGibbsBinMix <- function(alpha,beta,gamma,K,m,burn,data,thinning,z.true,outputDir){
if (missing(K)) {stop(cat(paste(" [ERROR]: number of clusters (K) not provided."), "\n"))}
if (missing(m)) {stop(cat(paste(" [ERROR]: number of MCMC iterations (m) not provided."), "\n"))}
if (missing(thinning)) {thinning <- 5}
d <- dim(data)[2]
if (burn > m - 1) {
stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n"))
}
if (burn < 0) {
stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n"))
}
if (thinning > m) {
stop(cat(paste(" [ERROR]: thinning not valid."), "\n"))
}
if (m < 1) {
stop(cat(paste(" [ERROR]: mcmc iterations (m) not valid."), "\n"))
}
if (missing(alpha)) {alpha <- 1}
if (missing(beta)) {beta <- 1}
if (missing(gamma)) {gamma <- rep(1,K)}
if (missing(data)) {stop(cat(paste(" [ERROR]: data is missing."), "\n"))}
d <- dim(data)[2]
n <- dim(data)[1]
x <- data
dir.create(outputDir)
setwd(outputDir)
p <- myDirichlet(rep(1,K))
theta <- array(data = runif(K*d), dim = c(K,d))
z <- sample(K,n,replace=TRUE,prob = p)
s <- l <- newL <- numeric(K)
sx <- array(data = 0, dim = c(K,d))
theta.file <- "theta.collapsed.txt"
z.file <- "z.collapsed.txt"
p.file <- "p.collapsed.txt"
conTheta = file(theta.file,open = "w")
conZ = file(z.file,open = "w")
conP = file(p.file,open = "w")
for (iter in 1:100){
s <- rep(0,K)
sx <- array(data = 0, dim = c(K,d))
for(i in 1:n){
for(k in 1:K){
l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,]))
}
for(k in 1:K){
newL[k] <- 1/sum(exp(l - l[k]))
}
z[i] <- sample(K,1,prob = newL)
s[z[i]] <- s[z[i]] + 1
sx[z[i],] <- sx[z[i],] + x[i,]
}
p <- myDirichlet(gamma + s)
for(k in 1:K){
theta[k,] <- rbeta(d, shape1 = alpha + sx[k,], shape2 = beta + s[k] - sx[k,])
}
}
nMatrix <- array(data = 0, dim = c(n,K))
sMatrix <- array(data = 0, dim = c(n,K,d))
for (i in 1:n){
nMatrix[i,] <- s
sMatrix[i,,] <- sx
}
for (i in 1:n){
nMatrix[i,z[i]] <- nMatrix[i,z[i]] - 1
for (j in 1:d){
sMatrix[i,z[i],j] <- sMatrix[i,z[i],j] - x[i,j]
}
}
reallocationAcceptanceRatio <- 0
reallocationAcceptanceRatio2 <- 0
a1 <- a2 <- 1
lar <- c()
for(iter in 1:m){
zOld <- z
for(i in 1:n){
nMatrix[i,1:K] <- s[1:K]
sMatrix[i,1:K,] <- sx[1:K,]
nMatrix[i,z[i]] <- s[z[i]] - 1
sMatrix[i,z[i],] <- sx[z[i],] - x[i,]
A1 <- which(x[i,] == 1)
A0 <- which(x[i,] == 0)
for(k in 1:K){
newL[k] <- log(nMatrix[i,k] + gamma[k]) - d*log(alpha + beta + nMatrix[i,k])
if(length(A1 > 0)){
newL[k] <- newL[k] + sum(log(alpha + sMatrix[i,k,A1]))
}
if(length(A0 > 0)){
newL[k] <- newL[k] + sum(log(beta + nMatrix[i,k] - sMatrix[i,k,A0]))
}
}
newL[1:K] <- exp(newL[1:K])
z[i] <- sample(K,1,prob = newL[1:K])
sx[zOld[i],] <- sx[zOld[i],] - x[i,]
sx[z[i],] <- sx[z[i],] + x[i,]
s[zOld[i]] <- s[zOld[i]] - 1
s[z[i]] <- s[z[i]] + 1
}
if (K > 1){
myPair <- sample(K,2,replace = FALSE)
propZ <- z
set1 <- which(z == myPair[1])
set2 <- which(z == myPair[2])
myP <- rbeta(1,shape1 = gamma[myPair[1]],shape2 = gamma[myPair[2]])
propZ[c(set1,set2)] <- myPair[sample(2,length(set1) + length(set2), replace = TRUE,prob = c(myP,1-myP) )]
newSet1 <- which(propZ == myPair[1])
newSet2 <- which(propZ == myPair[2])
nNew <- c(length(newSet1),length(newSet2))
nOld <- c(length(set1),length(set2))
if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))}
if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))}
sOld <- rbind(sOld1,sOld2)
if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))}
if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))}
sNew <- rbind(sNew1,sNew2)
logAR <- 0
for (i in 1:2){
logAR <- logAR + d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,]))
}
if( log(runif(1)) < logAR ){
reallocationAcceptanceRatio <- reallocationAcceptanceRatio + 1
z <- propZ
s <- rep(0,K)
sx <- array(data = 0, dim = c(K,d))
for(i in 1:n){
s[z[i]] <- s[z[i]] + 1
sx[z[i],] <- sx[z[i],] + x[i,]
}
for(i in 1:n){
nMatrix[i,] <- s
sMatrix[i,,] <- sx
}
for (i in 1:n){
nMatrix[i,z[i]] <- nMatrix[i,z[i]] - 1
for (j in 1:d){
sMatrix[i,z[i],j] <- sMatrix[i,z[i],j] - x[i,j]
}
}
}
}
if(K > 1){
myPair <- sample(K,2,replace = FALSE)
set1 <- which(z == myPair[1])
set2 <- which(z == myPair[2])
nOld <- c(length(set1),length(set2))
propZ <- z
if(nOld[1] > 0){
randomSize <- 1 + floor(nOld[1]*runif(1))
randomIndex <- set1[sample(nOld[1],randomSize,replace = FALSE)]
propZ[randomIndex] <- rep(myPair[2],randomSize)
newSet1 <- which(propZ == myPair[1])
newSet2 <- which(propZ == myPair[2])
nNew <- c(length(newSet1),length(newSet2))
if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))}
if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))}
sOld <- rbind(sOld1,sOld2)
if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))}
if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))}
sNew <- rbind(sNew1,sNew2)
logAR <- log(nOld[1]) - log(nOld[2] + randomSize) -( lgamma(nOld[1] - randomSize + 1) + lgamma(nOld[2]+ randomSize + 1) - lgamma(nOld[2] + 1) - lgamma(nOld[1] + 1))
for(i in 1:2){
logAR <- logAR + d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,]))
}
logAR <- logAR + sum(lgamma(gamma[myPair] + nNew)) - sum(lgamma(gamma[myPair] + nOld))
if( log(runif(1)) < logAR ){
reallocationAcceptanceRatio2 <- reallocationAcceptanceRatio2 + 1
z <- propZ
s <- rep(0,K)
sx <- array(data = 0, dim = c(K,d))
for(i in 1:n){
s[z[i]] <- s[z[i]] + 1
sx[z[i],] <- sx[z[i],] + x[i,]
}
for(i in 1:n){
nMatrix[i,] <- s
sMatrix[i,,] <- sx
}
for (i in 1:n){
nMatrix[i,z[i]] <- nMatrix[i,z[i]] - 1
for (j in 1:d){
sMatrix[i,z[i],j] <- sMatrix[i,z[i],j] - x[i,j]
}
}
}
}
}
if((iter %% thinning == 0)&(iter > burn)){
for(k in 1:K){
myIndex <- which(z == k)
s[k] <- length(myIndex)
if(s[k] > 1){
sx[k,] <- colSums(x[myIndex,])
}else{
if(s[k] == 1){
sx[k,] <- x[myIndex,]
}else{
sx[k,] <- rep(0,d)
}
}
theta[k,] <- rbeta(d, shape1 = alpha + sx[k,], shape2 = beta + s[k] - sx[k,])
}
p <- myDirichlet(gamma + s)
cat(theta,"\n",file=conTheta)
cat(z,"\n",file=conZ)
cat(p,"\n",file=conP)
}
if(iter %% (m/100) == 0){cat(paste("Running collapsed Gibbs: ",100*round(iter/m,3),"% completed. Reallocation proposal acceptance rates: ", 100*round(reallocationAcceptanceRatio/iter,3),"%, ",100*round(reallocationAcceptanceRatio2/iter,3),"%.",sep=""),"\n");
}
}
close(conTheta)
close(conP)
close(conZ)
cat(paste("Collapsed Gibbs finished."),"\n")
cat("\n")
if(K > 1){
cat(paste("Dealing with Label Switching..."),"\n")
tt <- read.table("theta.collapsed.txt")
m <- dim(tt)[1]
d <- dim(x)[2]
J <- d + 1
mcmc <- array(data = NA, dim = c(m,K,J))
for (j in 1:d){
for(k in 1:K){
mcmc[,k,j] <- tt[,(j-1)*K + k]
}
}
tt <- read.table("p.collapsed.txt")
for(k in 1:K){
mcmc[,k,J] <- tt[,k]
}
allocations <- as.matrix(read.table("z.collapsed.txt",as.is = TRUE))
m <- dim(mcmc)[1]
iter <- 1
ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,])
maxLL <- ll
maxIter <- iter
for (iter in 1:m){
ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,])
if(ll > maxLL){maxLL <- ll;maxIter <- iter;cat(paste("Found new Complete MLE: ", ll,sep=""),"\n")}
}
pMatrix <- array(data = NA, dim = c(m,n,K))
for (iter in 1:m){
p <- mcmc[iter,,J]
theta <- array( mcmc[iter,,1:(J-1)],dim = c(K,J-1) )
for(i in 1:n){
for(k in 1:K){
l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,]))
}
for(k in 1:K){
pMatrix[iter,i,k] <- 1/sum(exp(l - l[k]))
if(is.na(pMatrix[iter,i,k]) == TRUE){pMatrix[iter,i,k] = 0}
}
}
if(iter %% 1000 == 0){cat(paste(" classification probs: ",100*round(iter/m,3),"% completed",sep=""),"\n");}
}
if(missing(z.true)==TRUE){
ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"),
zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x,
prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix)
}else{
ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"),
zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x,
prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix,groundTruth = z.true)
}
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR")$output
tt <- read.table("theta.collapsed.txt")
write.table(reordered.mcmc, file = "reorderedMCMC-ECR.collapsed.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR-ITERATIVE-1")$output
write.table(reordered.mcmc, file = "reorderedMCMC-ECR-ITERATIVE1.collapsed.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"STEPHENS")$output
write.table(reordered.mcmc, file = "reorderedMCMC-STEPHENS.collapsed.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
write.table(mcmc, file = "rawMCMC.collapsed.txt",col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
write.table(file = "reorderedSingleBestClusterings.collapsed.txt",t(ls$clusters[c(1,2,3),]),row.names = paste("z",1:n,sep="."))
file.remove("p.collapsed.txt")
file.remove("theta.collapsed.txt")
cat(paste("raw MCMC parameters written to: \'rawMCMC.collapsed.txt\' "),"\n")
cat(paste("raw MCMC latent allocations written to: \'z.collapsed.txt\' "),"\n")
cat(paste("reordered MCMC output written to: "),"\n")
cat(paste(" (Method 1): \'reorderedMCMC-ECR.collapsed.txt\'"),"\n")
cat(paste(" (Method 2): \'reorderedMCMC-ECR-ITERATIVE1.collapsed.txt\'"),"\n")
cat(paste(" (Method 3): \'reorderedMCMC-STEPHENS.collapsed.txt\'"),"\n")
cat(paste("reordered single best clusterings written to: \'reorderedSingleBestClusterings.collapsed.txt\' "),"\n")
}
setwd("../")
}
allocationSamplerBinMix <- function(Kmax, alpha,beta,gamma,m,burn,data,thinning,z.true,ClusterPrior,ejectionAlpha,Kstart,outputDir,metropolisMoves,reorderModels,heat,zStart,LS, rsX, originalX, printProgress){
setwd(outputDir)
cat(paste0("changing working directory to ",outputDir),"\n")
if (missing(m)) {stop(cat(paste(" [ERROR]: number of MCMC iterations (m) not provided."), "\n"))}
if (missing(thinning)) {thinning <- 5}
if (missing(LS)) {LS <- TRUE}
if (missing(printProgress)) { printProgress <- FALSE }
if (missing(ejectionAlpha)) {ejectionAlpha <- 1}
if (burn > m - 1) {
stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n"))
}
if (burn < 0) {
stop(cat(paste(" [ERROR]: burn-in period (burn) not valid"), "\n"))
}
if (thinning > m) {
stop(cat(paste(" [ERROR]: thinning not valid."), "\n"))
}
if (m < 1) {
stop(cat(paste(" [ERROR]: mcmc iterations (m) not valid."), "\n"))
}
if (missing(alpha)) {alpha <- 1}
if (missing(beta)) {beta <- 1}
if (missing(data)) {stop(cat(paste(" [ERROR]: data is missing."), "\n"))}
x <- data
d <- dim(data)[2]
n <- dim(data)[1]
if (missing(Kmax)) {Kmax <- floor((d + 1)/2)}
if (missing(gamma)) {gamma <- rep(1,Kmax)}
if (length(table(gamma)) > 1){
stop(cat(paste(" [ERROR]: Dirichlet prior parameters should be the same."), "\n"))
}
birthProbs <- rep(1,Kmax)
birthProbs[2:(Kmax - 1)] <- rep(0.5,Kmax - 2)
birthProbs[Kmax] <- 0
deathProbs <- 1 - birthProbs
priorK <- numeric(Kmax)
if (missing(ClusterPrior)) {stop(cat(paste(" [ERROR]: ClusterPrior not defined (uniform of poisson)."), "\n"))}
if (missing(ejectionAlpha)) {stop(cat(paste(" [ERROR]: ejectionAlpha not defined (0 < a < 1)."), "\n"))}
if (ejectionAlpha < 0) {stop(cat(paste(" [ERROR]: ejectionAlpha error (0 < a < 1)."), "\n"))}
if (ejectionAlpha > 1) {stop(cat(paste(" [ERROR]: ejectionAlpha error (0 < a < 1)."), "\n"))}
if(ClusterPrior == "uniform"){
priorK <- rep(log(1/Kmax),Kmax)
}
if(ClusterPrior == "poisson"){
denom <- log(ppois(Kmax, lambda = 1, lower.tail = TRUE) - dpois(0,lambda = 1))
for (k in 1:Kmax){
priorK[k] <- dpois(k,lambda = 1, log = TRUE) - denom
}
}
if(missing(Kstart)){
Kstart <- 1
}
K <- Kstart
p <- myDirichlet(rep(1,K))
theta <- array(data = runif(Kmax*d), dim = c(Kmax,d))
s <- l <- newL <- numeric(Kmax)
sx <- array(data = 0, dim = c(Kmax,d))
if(missing(zStart) == TRUE){
cat(paste("Initializing..."),"\n")
cat("\n")
z <- sample(K,n,replace=TRUE,prob = p)
cat(paste("Allocation sampler running..."),"\n")
cat("\n")
}else{
z <- zStart
s[1:K] <- rep(0,K)
sx[1:K,] <- array(data = 0, dim = c(K,d))
for(i in 1:n){
s[z[i]] <- s[z[i]] + 1
sx[z[i],] <- sx[z[i],] + x[i,]
}
}
k.file <- "K.txt"
theta.file <- "theta.varK.txt"
z.file <- "z.varK.txt"
p.file <- "p.varK.txt"
conK = file(k.file,open = "w")
conTheta = file(theta.file,open = "w")
conZ = file(z.file,open = "w")
conP = file(p.file,open = "w")
if(missing(zStart) == TRUE){
for (iter in 1:5){
s[1:K] <- rep(0,K)
sx[1:K,] <- array(data = 0, dim = c(K,d))
for(i in 1:n){
for(k in 1:K){
l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,]))
}
for(k in 1:K){
newL[k] <- 1/sum(exp(l[1:K] - l[k]))
}
if(is.nan(sum(newL[1:K]))==TRUE){newL[1:K]<-rep(1,K)}
z[i] <- sample(K,1,prob = newL[1:K])
s[z[i]] <- s[z[i]] + 1
sx[z[i],] <- sx[z[i],] + x[i,]
}
p <- myDirichlet(heat*gamma[1:K] + heat*s[1:K] + 1 - heat)
for(k in 1:K){
theta[k,] <- rbeta(d, shape1 = heat*alpha + heat*sx[k,] + 1 - heat, shape2 = heat*beta + heat*s[k] - heat*sx[k,] + 1 - heat)
}
}
}
nMatrix <- array(data = 0, dim = c(n,Kmax))
sMatrix <- array(data = 0, dim = c(n,Kmax,d))
for (i in 1:n){
nMatrix[i,1:K] <- s[1:K]
sMatrix[i,1:K,] <- sx[1:K,]
}
for (i in 1:n){
nMatrix[i,z[i]] <- nMatrix[i,z[i]] - 1
for (j in 1:d){
sMatrix[i,z[i],j] <- sMatrix[i,z[i],j] - x[i,j]
}
}
reallocationAcceptanceRatio <- 0
reallocationAcceptanceRatio2 <- 0
reallocationAcceptanceRatio3 <- 0
reallocationAcceptanceRatio4 <- 0
a1 <- a2 <- 1
pZERO <- ejectionAlpha
constLGAMMA <- 2*lgamma(ejectionAlpha) - lgamma(2*ejectionAlpha)
kValues <- c()
if(missing(metropolisMoves) == TRUE){metropolisMoves <- c('M1','M2','M3','M4')}
lmm <- 1/length(metropolisMoves)
if( printProgress == TRUE){
cat(paste(" Reallocation proposal acceptance rates: Move 1, Move 2, Move 3, Move 4"),"\n")
}
for(iter in 1:m){
zOld <- z
sOld <- s
sxOld <- sx
if(K > 1){
myPair <- sample(K,2,replace = FALSE)
j1 <- myPair[1]
j2 <- myPair[2]
set1 <- which(z == j1)
set2 <- which(z == j2)
zOld[set1] = rep(j2,length(set1))
zOld[set2] = rep(j1,length(set2))
z <- zOld
sOld[j1] <- s[j2]
sOld[j2] <- s[j1]
sxOld[j1,] <- sx[j2,]
sxOld[j2,] <- sx[j1,]
s <- sOld
sx <- sxOld
}
for(i in 1:n){
nMatrix[i,1:K] <- s[1:K]
sMatrix[i,1:K,] <- sx[1:K,]
nMatrix[i,z[i]] <- s[z[i]] - 1
sMatrix[i,z[i],] <- sx[z[i],] - x[i,]
A1 <- which(x[i,] == 1)
A0 <- which(x[i,] == 0)
for(k in 1:K){
newL[k] <- heat*log(nMatrix[i,k] + gamma[k]) - heat*d*log(alpha + beta + nMatrix[i,k])
if(length(A1 > 0)){
newL[k] <- newL[k] + heat*sum(log(alpha + sMatrix[i,k,A1]))
}
if(length(A0 > 0)){
newL[k] <- newL[k] + heat*sum(log(beta + nMatrix[i,k] - sMatrix[i,k,A0]))
}
}
newL[1:K] <- exp(newL[1:K])
if( max(newL[1:K]) == 0){newL[1:K] <- rep(1,K);cat("oops","\n")}
z[i] <- sample(K,1,prob = newL[1:K])
sx[zOld[i],] <- sx[zOld[i],] - x[i,]
sx[z[i],] <- sx[z[i],] + x[i,]
s[zOld[i]] <- s[zOld[i]] - 1
s[z[i]] <- s[z[i]] + 1
}
mNumber <- sample(metropolisMoves,1)
if(mNumber == 'M1'){
if (K > 1){
myPair <- sample(K,2,replace = FALSE)
propZ <- z
set1 <- which(z == myPair[1])
set2 <- which(z == myPair[2])
myP <- rbeta(1,shape1 = gamma[myPair[1]],shape2 = gamma[myPair[2]])
propZ[c(set1,set2)] <- myPair[sample(2,length(set1) + length(set2), replace = TRUE,prob = c(myP,1-myP) )]
newSet1 <- which(propZ == myPair[1])
newSet2 <- which(propZ == myPair[2])
nNew <- c(length(newSet1),length(newSet2))
nOld <- c(length(set1),length(set2))
if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))}
if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))}
sOld <- rbind(sOld1,sOld2)
if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))}
if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))}
sNew <- rbind(sNew1,sNew2)
logAR <- 0
for (i in 1:2){
logAR <- logAR + d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,]))
}
if(is.finite(logAR)){
if( log(runif(1)) < logAR ){
reallocationAcceptanceRatio <- reallocationAcceptanceRatio + 1
z <- propZ
s <- rep(0,K)
sx <- array(data = 0, dim = c(K,d))
for(k in 1:K){
ind <- which(z == k)
tmpV <- numeric(n)
tmpM <- array(data = 0,dim = c(n,d))
s[k] <- length(ind)
if(s[k] > 0){
tmpV[ind] <- rep(1,s[k])
tmpM[ind,] <- x[ind,]
sx[k,] <- colSums(array(x[ind,],dim = c(s[k],d)))
}
nMatrix[,k] <- rep(s[k],n) - tmpV
sMatrix[,k,] <- matrix(sx[k,],nrow = n,ncol = d,byrow = TRUE) - tmpM
}
}
}
}
}
if(mNumber == 'M2'){
if(K > 1){
myPair <- sample(K,2,replace = FALSE)
set1 <- which(z == myPair[1])
set2 <- which(z == myPair[2])
nOld <- c(length(set1),length(set2))
propZ <- z
if(nOld[1] > 0){
randomSize <- 1 + floor(nOld[1]*runif(1))
randomIndex <- set1[sample(nOld[1],randomSize,replace = FALSE)]
propZ[randomIndex] <- rep(myPair[2],randomSize)
newSet1 <- which(propZ == myPair[1])
newSet2 <- which(propZ == myPair[2])
nNew <- c(length(newSet1),length(newSet2))
if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))}
if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))}
sOld <- rbind(sOld1,sOld2)
if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))}
if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))}
sNew <- rbind(sNew1,sNew2)
logAR <- log(nOld[1]) - log(nOld[2] + randomSize) -( lgamma(nOld[1] - randomSize + 1) + lgamma(nOld[2]+ randomSize + 1) - lgamma(nOld[2] + 1) - lgamma(nOld[1] + 1))
for(i in 1:2){
logAR <- logAR + heat*d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + heat*sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,]))
}
logAR <- logAR + heat*sum(lgamma(gamma[myPair] + nNew)) - heat*sum(lgamma(gamma[myPair] + nOld))
if(is.finite(logAR)){
if( log(runif(1)) < logAR ){
reallocationAcceptanceRatio2 <- reallocationAcceptanceRatio2 + 1
z <- propZ
s <- rep(0,K)
sx <- array(data = 0, dim = c(K,d))
for(k in 1:K){
ind <- which(z == k)
tmpV <- numeric(n)
tmpM <- array(data = 0,dim = c(n,d))
s[k] <- length(ind)
if(s[k] > 0){
tmpV[ind] <- rep(1,s[k])
tmpM[ind,] <- x[ind,]
sx[k,] <- colSums(array(x[ind,],dim = c(s[k],d)))
}
nMatrix[,k] <- rep(s[k],n) - tmpV
sMatrix[,k,] <- matrix(sx[k,],nrow = n,ncol = d,byrow = TRUE) - tmpM
}
}
}
}
}
}
if(mNumber == 'M3'){
if ( runif(1) < birthProbs[K] ){
birth = TRUE
myPair <- c(sample(K,1),K + 1)
set1 <- which(z == myPair[1])
nOld <- c(length(set1),0)
ejectionAlpha <- toSolve(seq(0.0001,2,length = 500),nOld[1],pZERO);constLGAMMA <- 2*lgamma(ejectionAlpha) - lgamma(2*ejectionAlpha)
propZ <- z
myP <- rbeta(1,shape1 = ejectionAlpha,shape2 = ejectionAlpha)
propZ[set1] <- myPair[sample(2,nOld[1], replace = TRUE,prob = c(1-myP,myP) )]
newSet1 <- which(propZ == myPair[1])
newSet2 <- which(propZ == myPair[2])
nNew <- c(length(newSet1),length(newSet2))
if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))}
if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))}
sOld <- rbind(sOld1,sOld2)
if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))}
if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))}
sNew <- rbind(sNew1,sNew2)
logAR <- log( (1 - birthProbs[K+1])/birthProbs[K] ) + constLGAMMA + lgamma(2*ejectionAlpha + nOld[1]) - lgamma(ejectionAlpha + nNew[1]) - lgamma(ejectionAlpha + nNew[2]) + heat*priorK[K+1] - heat*priorK[K]
logAR <- logAR + heat*d*( lgamma(alpha + beta + nOld[1]) - lgamma(alpha + beta + nNew[1]) - lgamma(alpha + beta + nNew[2]) )
logAR <- logAR + heat*sum(
lgamma(alpha + sNew[1,]) + lgamma(beta + nNew[1] - sNew[1,])
+ lgamma(alpha + sNew[2,]) + lgamma(beta + nNew[2] - sNew[2,])
- lgamma(alpha + sOld[1,]) - lgamma(beta + nOld[1] - sOld[1,])
)
logAR <- logAR + heat*sum(lgamma(gamma[myPair] + nNew)) - heat*sum(lgamma(gamma[myPair[1]] + nOld[1])) + heat*lgamma(sum(gamma[1:(K+1)])) - heat*lgamma(sum(gamma[1:K])) - heat*lgamma(sum(gamma[1:(K+1)]) + n) + heat*lgamma(sum(gamma[1:K]) + n) - heat*lgamma(gamma[K+1]) - heat*d*lbeta(alpha, beta)
}else{
birth = FALSE
myPair <- c(sample(K - 1,1),K)
set1 <- which(z == myPair[1])
set2 <- which(z == myPair[2])
nOld <- c(length(set1),length(set2))
propZ <- z
propZ[c(set1,set2)] <- rep(myPair[1],sum(nOld))
newSet1 <- which(propZ == myPair[1])
nNew <- c(length(newSet1),0)
ejectionAlpha <- toSolve(seq(0.0001,2,length = 500),nNew[1],pZERO);constLGAMMA <- 2*lgamma(ejectionAlpha) - lgamma(2*ejectionAlpha)
if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))}
if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))}
sOld <- rbind(sOld1,sOld2)
if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))}
sNew2 <- rep(0,d)
sNew <- rbind(sNew1,sNew2)
logAR <- - (log( (1 - birthProbs[K])/birthProbs[K - 1] ) + constLGAMMA + lgamma(2*ejectionAlpha + nNew[1]) - lgamma(ejectionAlpha + nOld[1]) - lgamma(ejectionAlpha + nOld[2]))+ heat*priorK[K - 1] - heat*priorK[K]
logAR <- logAR + heat*d*( lgamma(alpha + beta + nOld[1]) + lgamma(alpha + beta + nOld[2]) - lgamma(alpha + beta + nNew[1]) )
logAR <- logAR + heat*sum(
lgamma(alpha + sNew[1,]) + lgamma(beta + nNew[1] - sNew[1,])
- lgamma(alpha + sOld[1,]) - lgamma(beta + nOld[1] - sOld[1,])
- lgamma(alpha + sOld[2,]) - lgamma(beta + nOld[2] - sOld[2,])
)
logAR <- logAR + heat*lgamma(gamma[myPair[1]] + nNew[1]) - heat*sum(lgamma(gamma[myPair] + nOld)) + heat*lgamma(sum(gamma[1:(K-1)])) - heat*lgamma(sum(gamma[1:K])) - heat*lgamma(sum(gamma[1:(K-1)]) + n) + heat*lgamma(sum(gamma[1:K]) + n) + heat*lgamma(gamma[K]) + heat*d*lbeta(alpha, beta)
}
if(is.finite(logAR)){
if( log(runif(1)) < logAR ){
reallocationAcceptanceRatio3 <- reallocationAcceptanceRatio3 + 1
z <- propZ
if(birth == TRUE){K <- K + 1}else{K <- K - 1}
s <- rep(0,K)
sx <- array(data = 0, dim = c(K,d))
for(k in 1:K){
ind <- which(z == k)
tmpV <- numeric(n)
tmpM <- array(data = 0,dim = c(n,d))
s[k] <- length(ind)
if(s[k] > 0){
tmpV[ind] <- rep(1,s[k])
tmpM[ind,] <- x[ind,]
sx[k,] <- colSums(array(x[ind,],dim = c(s[k],d)))
}
nMatrix[,k] <- rep(s[k],n) - tmpV
sMatrix[,k,] <- matrix(sx[k,],nrow = n,ncol = d,byrow = TRUE) - tmpM
}
}
}
}
if(mNumber == 'M4'){
if(K > 1){
myPair <- sample(K,2,replace = FALSE)
propZ <- z
set1 <- which(z == myPair[1])
set2 <- which(z == myPair[2])
union12 <- c(set1,set2)
processed <- c()
notProcessed <- setdiff(union12,processed)
n1New <- n2New <- 0
s1New <- s2New <- numeric(d)
n1 <- n2 <- 0
s1 <- s2 <- numeric(d)
j1 <- myPair[1]
j2 <- myPair[2]
alreadyInJ1 <- alreadyInJ2 <- c()
proposalRatio <- 0
checkCondition <- TRUE
while ( length(notProcessed) > 0 ){
i <- notProcessed[1]
processed <- c(processed,i)
u <- log(gamma[j1] + n1New) - log(gamma[j2] + n2New) + sum( lgamma(alpha + x[i,] + s1New) + lgamma(beta + 1 + n1New - s1New - x[i,]) ) - d*sum(lgamma(alpha+beta+n1New+1)) + sum( lgamma(alpha + s2New) + lgamma(beta + n2New - s2New) ) - d*sum(lgamma(alpha+beta+n2New)) - sum( lgamma(alpha + s1New) + lgamma(beta + n1New - s1New) ) + d*sum(lgamma(alpha+beta+n1New)) - sum( lgamma(alpha + x[i,] + s2New) + lgamma(beta + 1 + n2New - s2New - x[i,]) ) + d*sum(lgamma(alpha+beta+n2New+1))
u <- exp(u)
proposalProbabities <- u/(1 + u)
if( is.finite(proposalProbabities) == FALSE ){checkCondition <- FALSE; proposalProbabities <- 0.5}
if( runif(1) < proposalProbabities ){
propZ[i] <- j1
proposalRatio <- proposalRatio - log(proposalProbabities)
n1New <- n1New + 1
s1New <- s1New + x[i,]
}else{
propZ[i] <- j2
proposalRatio <- proposalRatio - log(1 - proposalProbabities)
n2New <- n2New + 1
s2New <- s2New + x[i,]
}
u <- log(gamma[j1] + n1) - log(gamma[j2] + n2) + sum( lgamma(alpha + x[i,] + s1) + lgamma(beta + 1 + n1 - s1 - x[i,]) ) - d*sum(lgamma(alpha+beta+n1+1)) + sum( lgamma(alpha + s2) + lgamma(beta + n2 - s2) ) - d*sum(lgamma(alpha+beta+n2)) - sum( lgamma(alpha + s1) + lgamma(beta + n1 - s1) ) + d*sum(lgamma(alpha+beta+n1)) - sum( lgamma(alpha + x[i,] + s2) + lgamma(beta + 1 + n2 - s2 - x[i,]) ) + d*sum(lgamma(alpha+beta+n2+1))
u <- exp(u)
u <- u/(1 + u)
if(z[i] == j1){
proposalRatio <- proposalRatio + log(u)
n1 <- n1 + 1
s1 <- s1 + x[i,]
}else{
proposalRatio <- proposalRatio + log(1 - u)
n2 <- n2 + 1
s2 <- s2 + x[i,]
}
notProcessed <- setdiff(union12,processed)
}
newSet1 <- which(propZ == myPair[1])
newSet2 <- which(propZ == myPair[2])
nNew <- c(length(newSet1),length(newSet2))
nOld <- c(length(set1),length(set2))
if(nOld[1] == 0){sOld1 <- rep(0,d)}else{sOld1 <- colSums(array(x[set1,],dim = c(nOld[1],d)))}
if(nOld[2] == 0){sOld2 <- rep(0,d)}else{sOld2 <- colSums(array(x[set2,],dim = c(nOld[2],d)))}
sOld <- rbind(sOld1,sOld2)
if(nNew[1] == 0){sNew1 <- rep(0,d)}else{sNew1 <- colSums(array(x[newSet1,],dim = c(nNew[1],d)))}
if(nNew[2] == 0){sNew2 <- rep(0,d)}else{sNew2 <- colSums(array(x[newSet2,],dim = c(nNew[2],d)))}
sNew <- rbind(sNew1,sNew2)
logAR <- proposalRatio
for (i in 1:2){
logAR <- logAR + d*(lgamma(alpha + beta + nOld[i]) - lgamma(alpha + beta + nNew[i]) ) + sum(lgamma(alpha + sNew[i,]) + lgamma(beta + nNew[i] - sNew[i,]) - lgamma(alpha + sOld[i,]) - lgamma(beta + nOld[i] - sOld[i,]))
}
logAR <- logAR + sum(lgamma(gamma[myPair] + nNew)) - sum(lgamma(gamma[myPair] + nOld))
if(is.finite(logAR)){
if( (log(runif(1)) < logAR) && (checkCondition == TRUE) ){
reallocationAcceptanceRatio4 <- reallocationAcceptanceRatio4 + 1
z <- propZ
s <- rep(0,K)
sx <- array(data = 0, dim = c(K,d))
for(k in 1:K){
ind <- which(z == k)
tmpV <- numeric(n)
tmpM <- array(data = 0,dim = c(n,d))
s[k] <- length(ind)
if(s[k] > 0){
tmpV[ind] <- rep(1,s[k])
tmpM[ind,] <- x[ind,]
sx[k,] <- colSums(array(x[ind,],dim = c(s[k],d)))
}
nMatrix[,k] <- rep(s[k],n) - tmpV
sMatrix[,k,] <- matrix(sx[k,],nrow = n,ncol = d,byrow = TRUE) - tmpM
}
}
}
}
}
if(iter %% thinning == 0){
kValues <- c(kValues,K)
if(iter > burn){
cat(K,"\n",file=conK)
cat(z,"\n",file=conZ)
if (heat == 1){
for(k in 1:K){
myIndex <- which(z == k)
s[k] <- length(myIndex)
if(s[k] > 1){
sx[k,] <- colSums(x[myIndex,])
}else{
if(s[k] == 1){
sx[k,] <- x[myIndex,]
}else{
sx[k,] <- rep(0,d)
}
}
theta[k,] <- rbeta(d, shape1 = alpha + sx[k,], shape2 = beta + s[k] - sx[k,])
}
if( length(rsX) > 0){
for(i in rsX){
na.index <- which(is.na(originalX[i,]) == TRUE)
x[i, na.index] <- rbinom(n = length(na.index), size = 1, prob = theta[z[i],na.index])
}
write.table(x,file = "currentX.txt", quote = FALSE, row.names = FALSE, col.names = FALSE)
}
p <- myDirichlet(gamma[1:K] + s[1:K])
cat(theta,"\n",file=conTheta)
cat(p,"\n",file=conP)
}
}
}
if( printProgress == TRUE){
if(iter %% (m/100) == 0){
cat(paste(" ",100*round(iter/m,3),"% completed. ",
100*round(lmm*reallocationAcceptanceRatio/iter,3),"%, ",
100*round(lmm*reallocationAcceptanceRatio2/iter,3),"%, ",
100*round(lmm*reallocationAcceptanceRatio4/iter,3),"%, ",
100*round(lmm*reallocationAcceptanceRatio3/iter,3),"%",
sep=""),"\n");}
}
}
close(conK)
close(conTheta)
close(conP)
close(conZ)
cat(paste("Allocation Sampler finished."),"\n")
cat("\n")
if(LS == TRUE){
kFile <- read.table("K.txt")[,1]
cat("\n")
print(table(kFile)/length(kFile))
K <- as.numeric(names(table(kFile))[order(table(kFile),decreasing=TRUE)[1]])
cat("\n")
cat(paste("Most probable model: K = ",K," with P(K = ",K,") = ",max(table(kFile)/length(kFile)),sep=""),"\n")
cat("\n")
if(missing(reorderModels)==TRUE){reorderModels <- 'onlyMAP'}
if(reorderModels == 'onlyMAP'){kRange <- K}else{
kRange <- as.numeric(names(table(kFile)/length(kFile)))
}
for ( K in kRange ){
if (K > 1){
cat(paste("Dealing with Label Switching for K =",K),"\n")
tt <- read.table("theta.varK.txt")
index <- which(kFile == K)
d <- dim(x)[2]
J <- d + 1
m <- length(index)
mcmc <- array(data = NA, dim = c(m,K,J))
Kmax <- (dim(tt)/d)[2]
for (j in 1:d){
for(k in 1:K){
mcmc[,k,j] <- tt[index,(j-1)*Kmax + k]
}
}
conP = file(p.file,open = "r")
i <- 0
j <- 0
while (length(oneLine <- readLines(conP, n = 1, warn = FALSE)) > 0) {
i <- i + 1
if(kFile[i] == K){
j <- j + 1
mcmc[j,,J] <- as.numeric(strsplit(oneLine,split = " ")[[1]])
}
}
close(conP)
allocations <- as.matrix(read.table("z.varK.txt",as.is = TRUE)[index,])
iter <- 1
ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,])
maxLL <- ll
maxIter <- iter
for (iter in 1:m){
ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,])
if(ll > maxLL){maxLL <- ll;maxIter <- iter;cat(paste("Found new Complete MLE: ", ll,sep=""),"\n")}
}
pMatrix <- array(data = NA, dim = c(m,n,K))
l <- numeric(K)
for (iter in 1:m){
p <- mcmc[iter,,J]
theta <- array( mcmc[iter,,1:(J-1)],dim = c(K,J-1) )
for(i in 1:n){
for(k in 1:K){
l[k] <- log(p[k]) + sum(x[i,]*log(theta[k,]) + (1-x[i,])*log(1-theta[k,]))
}
for(k in 1:K){
pMatrix[iter,i,k] <- 1/sum(exp(l - l[k]))
if(is.na(pMatrix[iter,i,k]) == TRUE){pMatrix[iter,i,k] = 0}
}
}
if(iter %% 1000 == 0){cat(paste(" classification probs: ",100*round(iter/m,3),"% completed",sep=""),"\n");}
}
if(missing(z.true)==TRUE){
ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"),
zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x,
prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix)
}else{
ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"),
zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x,
prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix,groundTruth = z.true)
}
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR")$output
write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR-ITERATIVE-1")$output
write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"STEPHENS")$output
write.table(reordered.mcmc, file = paste("reorderedMCMC-STEPHENS.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
write.table(mcmc, file = paste("rawMCMC.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
write.table(file = paste("reorderedSingleBestClusterings.mapK.",K,".txt",sep=""),t(ls$clusters[c(1,2,3),]),row.names = paste("z",1:n,sep="."))
allocationsECR <- allocationsKL <- allocationsECR.ITERATIVE1 <- allocations
for (i in 1:m){
myPerm <- order(ls$permutations$"ECR"[i,])
allocationsECR[i,] <- myPerm[allocations[i,]]
myPerm <- order(ls$permutations$"STEPHENS"[i,])
allocationsKL[i,] <- myPerm[allocations[i,]]
myPerm <- order(ls$permutations$"ECR-ITERATIVE-1"[i,])
allocationsECR.ITERATIVE1[i,] <- myPerm[allocations[i,]]
}
write.table(allocationsECR, file = paste("z.ECR.mapK.",K,".txt",sep=""))
write.table(allocationsKL, file = paste("z.KL.mapK.",K,".txt",sep=""))
write.table(allocationsECR.ITERATIVE1, file = paste("z.ECR-ITERATIVE1.mapK.",K,".txt",sep=""))
cat(paste0("raw MCMC parameters for most probable K written to: \'rawMCMC.mapK.",K,".txt\' "),"\n")
cat(paste0("raw MCMC latent allocations for most probable K written to: \'z.mapK.",K,".txt\' "),"\n")
cat(paste0("reordered MCMC output written to: "),"\n")
cat(paste0(" (Method 1): \'reorderedMCMC-ECR.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 2): \'reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 3): \'reorderedMCMC-STEPHENS.mapK.",K,".txt\'"),"\n")
cat(paste0("reordered single best clusterings written to: \'reorderedSingleBestClusterings.mapK.",K,".txt\' "),"\n")
cat(paste0("reordered MCMC latent allocations for most probable K written to: "),"\n")
cat(paste0(" (Method 1): \'z.ECR.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 2): \'z.KL.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 3): \'z.ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n")
}
}
}
setwd("../")
cat(paste0("back to working directory now."),"\n")
return(kValues)
}
coupledMetropolis <- function(Kmax, nChains,heats,binaryData,outPrefix,ClusterPrior,m, alpha, beta, gamma, z.true, ejectionAlpha, burn){
if(missing(nChains) == TRUE){stop(cat(paste(" [ERROR]: number of chains not provided."), "\n"))}
if(missing(heats) == TRUE){
heats <- seq(1,0.1,length = nChains)
}else{
if(heats[1] != 1){stop(cat(paste(" [ERROR]: `heats[1]` should be equal to one."), "\n"))}
}
if(length(heats) != nChains){
stop(cat(paste(" [ERROR]: `length(heats)` should be equal to `nChains`."), "\n"))
}
if(missing(ClusterPrior) == TRUE){ClusterPrior <- 'poisson'}
if (missing(alpha)) {alpha <- 1}
if (missing(beta)) {beta <- 1}
if (missing(binaryData)) {stop(cat(paste(" [ERROR]: data is missing."), "\n"))}
if (missing(gamma)) {gamma <- rep(1,Kmax)}
if (length(table(gamma)) > 1){
stop(cat(paste(" [ERROR]: Dirichlet prior parameters should be the same."), "\n"))
}
d <- dim(binaryData)[2]; n <- dim(binaryData)[1]; priorK <- numeric(Kmax)
if(ClusterPrior == "uniform"){
priorK <- rep(log(1/Kmax),Kmax)
}
if(ClusterPrior == "poisson"){
denom <- log(ppois(Kmax, lambda = 1, lower.tail = TRUE) - dpois(0,lambda = 1))
for (k in 1:Kmax){
priorK[k] <- dpois(k,lambda = 1, log = TRUE) - denom
}
}
if(missing(ejectionAlpha) == TRUE){ejectionAlpha <- 0.2}
x <- binaryData
rsX <- which(is.na(rowSums(x)) == TRUE)
originalX <- x
if(length(rsX) > 0){
cat(paste(" [NOTE]: Found ",length(rsX) ," rows with missing values."), "\n")
for(i in rsX){
na.index <- which(is.na(x[i,]) == TRUE)
x[i,na.index] <- rbinom(n = length(na.index), size = 1, prob = alpha/(alpha + beta))
}
}
currentZ <- array(data = NA, dim = c(nChains,n))
currentK <- numeric(nChains)
myCheck <- match(outPrefix,list.files())
if(is.na(myCheck) == FALSE){
stop(cat(paste(" [ERROR]: directory exists, please provide different name to outPrefix."), "\n"))
}
if( missing(z.true) ){
z.true <- NULL
}
if(missing(burn)){burn = 0}
if(burn > m - 1){
stop(cat(paste(" [ERROR]: Burn-in period not valid: \'burn\' should be less than \'m\'."), "\n"))
}
if(nChains < 2){
if(length(rsX) > 0){
stop(cat(paste(" [ERROR]: At least two chains should be used."), "\n"))}
cat(paste(" Only 1 chain? Well."),"\n")
dir.create(outPrefix)
myHeat <- 1
asr <- allocationSamplerBinMix( alpha = alpha, beta = beta, gamma = gamma, m = 10*m, burn= 10*burn, data = x,
thinning = 10,Kmax = Kmax, ClusterPrior = ClusterPrior,ejectionAlpha = ejectionAlpha,
outputDir = outPrefix,Kstart = 1,heat=myHeat,metropolisMoves = c('M1','M2','M3','M4'),LS = FALSE, rsX = rsX, originalX = originalX)}
else{
registerDoParallel(cores = nChains)
outputDirs <- paste0(outPrefix,1:nChains)
temperatures <- heats
myChain <- 1
for(i in 1:nChains){
cat(paste0(" Create temporary directory: \'",outPrefix,i,"\'."), "\n")
}
cat(paste0(" [NOTE]: screen output from multiple threads is redirected to \'",outPrefix,"-sampler.log\'."), "\n")
sink(paste0(outPrefix,'-sampler.log'))
foreach(myChain=1:nChains, .export=ls(envir=globalenv()) ) %dopar% {
outDir <- outputDirs[myChain]
dir.create(outDir)
myHeat <- temperatures[myChain]
asr <- allocationSamplerBinMix( alpha = alpha, beta = beta, gamma = gamma, m = 10, burn= 9, data = x,
thinning = 1,Kmax = Kmax, ClusterPrior = ClusterPrior,ejectionAlpha = ejectionAlpha,
outputDir = outDir,Kstart=1,heat=myHeat,metropolisMoves='M3',LS = FALSE, rsX = rsX, originalX = originalX)
}
ITERATIONS <- m
sampledK <- array(data = 0, dim = c(ITERATIONS,nChains))
dir.create(outPrefix)
k.file <- paste0(outPrefix,"/K.txt")
theta.file <- paste0(outPrefix,"/theta.varK.txt")
z.file <- paste0(outPrefix,"/z.varK.txt")
p.file <- paste0(outPrefix,"/p.varK.txt")
x.file <- paste0(outPrefix,"/x.txt")
conK = file(k.file,open = "w")
conTheta = file(theta.file,open = "w")
conZ = file(z.file,open = "w")
conP = file(p.file,open = "w")
if(length(rsX) > 0){
conX <- file(x.file, open = "w")
}
ar <- 0
metMoves <- vector('list',length = nChains)
metMoves[[1]] <- c('M1','M2','M3','M4')
for(j in 2:nChains){metMoves[[j]] <- c('M2','M3')}
localAR <- 0
for(iter in 1:ITERATIONS){
if(length(rsX) > 0){
x <- as.matrix(read.table(paste0(outPrefix,1,'/currentX.txt')))
}
for(myChain in 1:nChains){
currentZ[myChain,] <- as.numeric(read.table(paste0(outPrefix,myChain,'/z.varK.txt'))[1,])
currentK[myChain] <- read.table(paste0(outPrefix,myChain,'/K.txt'))[1,]
}
sampledK[iter,] <- currentK
myPair <- sample(nChains,2,replace = FALSE)
j1 <- myPair[1]
j2 <- myPair[2]
z1 <- currentZ[j1,]
z2 <- currentZ[j2,]
K1 <- currentK[j1]
K2 <- currentK[j2]
s1 <- rep(0,K1)
sx1 <- array(data = 0, dim = c(K1,d))
for(k in 1:K1){
ind <- which(z1 == k)
s1[k] <- length(ind)
if(s1[k] > 0){
sx1[k,] <- colSums(array(x[ind,],dim = c(s1[k],d)))
}
}
s2 <- rep(0,K2)
sx2 <- array(data = 0, dim = c(K2,d))
for(k in 1:K2){
ind <- which(z2 == k)
s2[k] <- length(ind)
if(s2[k] > 0){
sx2[k,] <- colSums(array(x[ind,],dim = c(s2[k],d)))
}
}
log.posterior <- priorK[K1] + sum(lgamma( gamma[1:K1] + s1 )) - d*sum(lgamma(alpha+beta+s1)) - lgamma(n + sum(gamma[1:K1]))
for(k in 1:K1){
log.posterior <- log.posterior + sum(lgamma(alpha + sx1[k,]) + lgamma(beta + s1[k] - sx1[k,]))
}
log.posterior <- log.posterior + lgamma(sum(gamma[1:K1])) - sum(lgamma(gamma[1:K1])) - K1*d*lbeta(alpha, beta)
logAR <- (temperatures[j2] - temperatures[j1])*log.posterior
log.posterior <- priorK[K2] + sum(lgamma( gamma[1:K2] + s2 )) - d*sum(lgamma(alpha+beta+s2)) - lgamma(n + sum(gamma[1:K2]))
for(k in 1:K2){
log.posterior <- log.posterior + sum(lgamma(alpha + sx2[k,]) + lgamma(beta + s2[k] - sx2[k,]))
}
log.posterior <- log.posterior + lgamma(sum(gamma[1:K2])) - sum(lgamma(gamma[1:K2])) - K2*d*lbeta(alpha, beta)
logAR <- logAR + (temperatures[j1] - temperatures[j2])*log.posterior
if( log(runif(1)) < logAR ){
ar <- ar + 1
localAR <- localAR + 1
currentZ[j1,] <- z2
currentZ[j2,] <- z1
currentK[j1] <- K2
currentK[j2] <- K1
}
myChain <- 1
foreach(myChain=1:nChains, .export=ls(envir=globalenv()) ) %dopar% {
outDir <- outputDirs[myChain]
myHeat <- temperatures[myChain]
Kstart <- currentK[myChain]
zStart <- currentZ[myChain,]
allocationSamplerBinMix( alpha = alpha, beta = beta, gamma = gamma, m = 10, burn= 9, data = x,
thinning = 1,Kmax = Kmax, ClusterPrior = ClusterPrior,ejectionAlpha = ejectionAlpha,
outputDir = outDir,Kstart=Kstart,zStart = zStart, heat=myHeat,
metropolisMoves = metMoves[[myChain]],LS = FALSE, rsX = rsX, originalX = originalX)
}
if(iter %% (m/100) == 0){
matplot(sampledK[1:iter,],type = "l",lty = 1,lwd = 2, col = topo.colors(nChains))
points(sampledK[1:iter,1], type = "b",col = topo.colors(nChains)[1])
legend('topleft',paste0('f(z,K|data)^{',round(heats,3),'}'),lty = 1, lwd = 2, col = topo.colors(nChains))
write(paste0(100*iter/m,'% completed. Chain switching acceptance rate: ',100*round(ar/iter,3),'%.'),stderr())
}
if(iter > burn){
kk <- as.numeric(read.table(paste0(outPrefix,"1/K.txt"))[1,])
cat(kk,"\n",file=conK)
theta <- as.numeric(read.table(paste0(outPrefix,"1/theta.varK.txt"))[1,])
cat(theta,"\n",file=conTheta)
z <- as.numeric(read.table(paste0(outPrefix,"1/z.varK.txt"))[1,])
cat(z,"\n",file=conZ)
p <- as.numeric(read.table(paste0(outPrefix,"1/p.varK.txt"))[1,])
cat(p,"\n",file=conP)
if(length(rsX) > 0){cat(x,"\n",file=conX)}
}
}
close(conK)
close(conTheta)
close(conP)
close(conZ)
if(nChains > 1){
swapAcceptanceRate <- 100*round(ar/iter,3)
}else{ swapAcceptanceRate <- 'NA' }
if(length(rsX) > 0){
close(conX)
}
write.table(sampledK, file = paste0(outPrefix,"/K.allChains.txt"), col.names = paste0('chain.',1:nChains),quote=FALSE,row.names = FALSE)
for(k in 1:nChains){
unlink(paste0(outPrefix,k), recursive=TRUE)
}
sink()
stopImplicitCluster()
}
if(length(rsX) == 0){
if(is.null(z.true) == TRUE){
dealWithLabelSwitching(outDir = outPrefix, binaryData = binaryData)
}else{
dealWithLabelSwitching(outDir = outPrefix, binaryData = binaryData, z.true = z.true)
}
}else{
if(is.null(z.true) == TRUE){
dealWithLabelSwitchingMissing(outDir = outPrefix, binaryData = binaryData)
}else{
dealWithLabelSwitchingMissing(outDir = outPrefix, binaryData = binaryData, z.true = z.true)
}
}
if(nChains > 1){
kFile <- sampledK[(burn+1):ITERATIONS,1]
}else{
kFile <- read.table(paste0(outPrefix,"/K.txt"))
ITERATIONS <- m
swapAcceptanceRate <- 0
}
K <- as.numeric(names(table(kFile))[order(table(kFile),decreasing=TRUE)[1]])
K.mcmc <- mcmc(kFile, start = 10*burn + 10, end = 10*ITERATIONS, thin = 10)
if( K > 1 ){
parameters.ecr.mcmc <- read.table(paste0(outPrefix,"/reorderedMCMC-ECR.mapK.",K,".txt"), header = TRUE)
allocations.ecr.mcmc <- read.table(paste0(outPrefix,"/z.ECR.mapK.",K,".txt"), header = TRUE)
clusterMembershipPerMethod <- read.table(paste0(outPrefix,"/reorderedSingleBestClusterings.mapK.",K,".txt"), header = TRUE)
classificationProbabilities.ecr <- read.csv(paste0(outPrefix,"/classificationProbabilities.mapK.",K,".csv"))
}else{
parameters.ecr.mcmc <- read.table(paste0(outPrefix,"/MCMC.mapK.",K,".txt"), header = TRUE)
allocations.ecr.mcmc <- rep(1, dim(parameters.ecr.mcmc)[1] )
classificationProbabilities.ecr <- array(data = 1, dim = c(n,1))
clusterMembershipPerMethod <- array(data = 1, dim = c(n,3))
colnames(clusterMembershipPerMethod) <- c('ECR','STEPHENS','ECR-ITERATIVE-1')
}
parameters.ecr.mcmc <- mcmc( parameters.ecr.mcmc )
allocations.ecr.mcmc <- mcmc( allocations.ecr.mcmc )
colnames(classificationProbabilities.ecr) <- paste('cluster',1:K)
bbm.output <- vector('list', length = 7)
bbm.output[[1]] <- K.mcmc
bbm.output[[2]] <- parameters.ecr.mcmc
bbm.output[[3]] <- allocations.ecr.mcmc
bbm.output[[4]] <- classificationProbabilities.ecr
bbm.output[[5]] <- clusterMembershipPerMethod
if(nChains > 1){
sampledK <- array(sampledK, dim = c(ITERATIONS, nChains))
colnames(sampledK) <- paste0("chain.", 1:nChains)
colnames(sampledK)[1] <- paste0(colnames(sampledK)[1],"_(target)")
}else{
sampledK <- asr
write.table(sampledK, file = paste0(outPrefix,"/K.allChains.txt"),
col.names = 'chain.1',quote=FALSE,row.names = FALSE)
}
bbm.output[[6]] <- sampledK
bbm.output[[7]] <- c(nChains, swapAcceptanceRate, m, burn)
names(bbm.output) <- c('K.mcmc', 'parameters.ecr.mcmc', 'allocations.ecr.mcmc', 'classificationProbabilities.ecr', 'clusterMembershipPerMethod', 'K.allChains', 'chainInfo')
class(bbm.output) <- c('list', 'bbm.object')
return(bbm.output)
}
dealWithLabelSwitching <- function(outDir,reorderModels, binaryData,z.true){
setwd(outDir)
x <- binaryData
kFile <- read.table("K.txt")[,1]
theta.file <- "theta.varK.txt"
z.file <- "z.varK.txt"
p.file <- "p.varK.txt"
cat("\n")
print(table(kFile)/length(kFile))
K <- as.numeric(names(table(kFile))[order(table(kFile),decreasing=TRUE)[1]])
cat("\n")
cat(paste("Most probable model: K = ",K," with P(K = ",K,") = ",max(table(kFile)/length(kFile)),sep=""),"\n")
cat("\n")
if(missing(reorderModels)==TRUE){reorderModels <- 'onlyMAP'}
if(reorderModels == 'onlyMAP'){kRange <- K}else{
kRange <- as.numeric(names(table(kFile)/length(kFile)))
}
for ( K in kRange ){
tt <- read.table("theta.varK.txt")
index <- which(kFile == K)
d <- dim(x)[2]
n <- dim(x)[1]
J <- d + 1
m <- length(index)
mcmc <- array(data = NA, dim = c(m,K,J))
Kmax <- (dim(tt)/d)[2]
for (j in 1:d){
for(k in 1:K){
mcmc[,k,j] <- tt[index,(j-1)*Kmax + k]
}
}
conP = file(p.file,open = "r")
i <- 0
j <- 0
while (length(oneLine <- readLines(conP, n = 1, warn = FALSE)) > 0) {
i <- i + 1
if(kFile[i] == K){
j <- j + 1
mcmc[j,,J] <- as.numeric(strsplit(oneLine,split = " ")[[1]])
}
}
close(conP)
if (K > 1){
cat(paste("Dealing with Label Switching for K =",K),"\n")
allocations <- as.matrix(read.table("z.varK.txt",as.is = TRUE)[index,])
iter <- 1
ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,])
maxLL <- ll
maxIter <- iter
for (iter in 1:m){
ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,])
if(ll > maxLL){maxLL <- ll;maxIter <- iter;cat(paste("Found new Complete MLE: ", ll,sep=""),"\n")}
}
ptm <- proc.time()
pMatrix <- array(data = NA, dim = c(m,n,K))
l <- array(data = 0, dim = c(n,K))
for (iter in 1:m){
LOG.P <- log(mcmc[iter,,J])
LOG.THETA <- array(log(mcmc[iter,,1:(J-1)]),dim = c(K,J-1) )
LOG.1_MINUS_THETA <- array(log(1 - mcmc[iter,,1:(J-1)]),dim = c(K,J-1) )
for(k in 1:K){
l[,k] <- LOG.P[k] + rowSums( x * matrix(LOG.THETA[k,], nrow = n, ncol = J - 1, byrow = TRUE) + (1-x)*matrix(LOG.1_MINUS_THETA[k,], nrow = n, ncol = J - 1, byrow = TRUE))
}
for(k in 1:K){
pMatrix[iter,,k] <- apply(l,1,function(y){return(1/sum(exp(y - y[k])))} )
ind <- which(is.na(pMatrix[iter,,k]) == TRUE)
nInd <- length(ind)
if(nInd > 0){pMatrix[iter,ind,k] <- rep(0,nInd)}
}
if(iter %% 1000 == 0){cat(paste(" classification probs: ",100*round(iter/m,3),"% completed",sep=""),"\n");}
}
cat(paste0("proc.time for classification probabilities: ", round(as.numeric((proc.time() - ptm)[3]),2)),"\n")
if(missing(z.true)==TRUE){
ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"),
zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x,
prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix)
}else{
ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"),
zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x,
prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix,groundTruth = z.true)
}
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR")$output
write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR-ITERATIVE-1")$output
write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"STEPHENS")$output
write.table(reordered.mcmc, file = paste("reorderedMCMC-STEPHENS.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
write.table(mcmc, file = paste("rawMCMC.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
write.table(file = paste("reorderedSingleBestClusterings.mapK.",K,".txt",sep=""),t(ls$clusters[c(1,2,3),]),row.names = paste("z",1:n,sep="."))
allocationsECR <- allocationsKL <- allocationsECR.ITERATIVE1 <- allocations
for (i in 1:m){
myPerm <- order(ls$permutations$"ECR"[i,])
allocationsECR[i,] <- myPerm[allocations[i,]]
myPerm <- order(ls$permutations$"STEPHENS"[i,])
allocationsKL[i,] <- myPerm[allocations[i,]]
myPerm <- order(ls$permutations$"ECR-ITERATIVE-1"[i,])
allocationsECR.ITERATIVE1[i,] <- myPerm[allocations[i,]]
}
MeanReorderedpMatrix <- array(data = 0, dim = c(n,K))
for (i in 1:m){
myPerm <- ls$permutations$"ECR"[i,]
MeanReorderedpMatrix <- MeanReorderedpMatrix + pMatrix[i, ,myPerm]
}
MeanReorderedpMatrix <- MeanReorderedpMatrix/m
write.csv(MeanReorderedpMatrix, file = paste0("classificationProbabilities.mapK.",K,".csv"), row.names = FALSE)
write.table(allocationsECR, file = paste("z.ECR.mapK.",K,".txt",sep=""))
write.table(allocationsKL, file = paste("z.KL.mapK.",K,".txt",sep=""))
write.table(allocationsECR.ITERATIVE1, file = paste("z.ECR-ITERATIVE1.mapK.",K,".txt",sep=""))
cat(paste0("raw MCMC parameters for most probable K written to: \'rawMCMC.mapK.",K,".txt\' "),"\n")
cat(paste0("raw MCMC latent allocations for most probable K written to: \'z.mapK.",K,".txt\' "),"\n")
cat(paste0("reordered MCMC output written to: "),"\n")
cat(paste0(" (Method 1): \'reorderedMCMC-ECR.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 2): \'reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 3): \'reorderedMCMC-STEPHENS.mapK.",K,".txt\'"),"\n")
cat(paste0("reordered single best clusterings written to: \'reorderedSingleBestClusterings.mapK.",K,".txt\' "),"\n")
cat(paste0("reordered MCMC latent allocations for most probable K written to: "),"\n")
cat(paste0(" (Method 1): \'z.ECR.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 2): \'z.KL.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 3): \'z.ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n")
}else{
cat(paste0('[NOTE]: Most probable model corresponds to 1 cluster so the label-switching algorithms are not applied.',"\n"))
write.table(mcmc, file = paste("MCMC.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
cat(paste0("MCMC output corresponding to most probable model (K = 1) written to: \'", paste("MCMC.mapK.",K,".txt",sep=""),"\'"),"\n")
}
}
setwd("../")
}
dealWithLabelSwitchingMissing <- function(outDir,reorderModels, binaryData, z.true){
setwd(outDir)
x <- binaryData
d <- dim(x)[2]
n <- dim(x)[1]
x.file <- "x.txt"
kFile <- read.table("K.txt")[,1]
theta.file <- "theta.varK.txt"
z.file <- "z.varK.txt"
p.file <- "p.varK.txt"
cat("\n")
print(table(kFile)/length(kFile))
K <- as.numeric(names(table(kFile))[order(table(kFile),decreasing=TRUE)[1]])
cat("\n")
cat(paste("Most probable model: K = ",K," with P(K = ",K,") = ",max(table(kFile)/length(kFile)),sep=""),"\n")
cat("\n")
if(missing(reorderModels)==TRUE){reorderModels <- 'onlyMAP'}
if(reorderModels == 'onlyMAP'){kRange <- K}else{
kRange <- as.numeric(names(table(kFile)/length(kFile)))
}
for ( K in kRange ){
tt <- read.table("theta.varK.txt")
index <- which(kFile == K)
J <- d + 1
m <- length(index)
mcmc <- array(data = NA, dim = c(m,K,J))
Kmax <- (dim(tt)/d)[2]
for (j in 1:d){
for(k in 1:K){
mcmc[,k,j] <- tt[index,(j-1)*Kmax + k]
}
}
conP = file(p.file,open = "r")
i <- 0
j <- 0
while (length(oneLine <- readLines(conP, n = 1, warn = FALSE)) > 0) {
i <- i + 1
if(kFile[i] == K){
j <- j + 1
mcmc[j,,J] <- as.numeric(strsplit(oneLine,split = " ")[[1]])
}
}
close(conP)
if (K > 1){
cat(paste("Dealing with Label Switching for K =",K),"\n")
conX <- file(x.file, open = "r")
allocations <- as.matrix(read.table("z.varK.txt",as.is = TRUE)[index,])
pMatrix <- array(data = NA, dim = c(m,n,K))
l <- array(data = 0, dim = c(n,K))
ptm <- proc.time()
iter <- 0
xEstimated <- array(data = 0, dim = c(n,d))
for(xLine in 1:length(kFile)){
xC <- readLines(conX, n = 1, warn = FALSE)
if( is.na(match(xLine,index)) == FALSE){
x <- as.numeric(strsplit(xC,split = " ")[[1]])
x <- matrix(x,nrow = n, ncol = d)
xEstimated <- xEstimated + x
iter <- iter + 1
ll <- complete.loglikelihood(x,allocations[iter,],mcmc[iter,,])
if(iter == 1){ maxLL <- ll; maxIter <- iter }
if(ll > maxLL){maxLL <- ll;maxIter <- iter;cat(paste("Found new Complete MLE: ", ll,sep=""),"\n")}
LOG.P <- log(mcmc[iter,,J])
LOG.THETA <- array(log(mcmc[iter,,1:(J-1)]),dim = c(K,J-1) )
LOG.1_MINUS_THETA <- array(log(1 - mcmc[iter,,1:(J-1)]),dim = c(K,J-1) )
for(k in 1:K){
l[,k] <- LOG.P[k] + rowSums( x * matrix(LOG.THETA[k,], nrow = n, ncol = J - 1, byrow = TRUE) + (1-x)*matrix(LOG.1_MINUS_THETA[k,], nrow = n, ncol = J - 1, byrow = TRUE))
}
for(k in 1:K){
pMatrix[iter,,k] <- apply(l,1,function(y){return(1/sum(exp(y - y[k])))} )
ind <- which(is.na(pMatrix[iter,,k]) == TRUE)
nInd <- length(ind)
if(nInd > 0){pMatrix[iter,ind,k] <- rep(0,nInd)}
}
if(iter %% 100 == 0){cat(paste(" classification probs: ",100*round(iter/m,3),"% completed",sep=""),"\n");}
}
}
xEstimated <- xEstimated/iter
write.table(file = "xEstimated.txt", xEstimated, quote = FALSE)
close(conX)
cat(paste0("proc.time for classification probabilities: ", round(as.numeric((proc.time() - ptm)[3]),2)),"\n")
cat(paste0("estimated missing data file written to: \'xEstimated.txt\'"),"\n")
if(missing(z.true)==TRUE){
ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"),
zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x,
prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix)
}else{
ls <- label.switching( method = c("STEPHENS","ECR","ECR-ITERATIVE-1"),
zpivot = allocations[maxIter,], z = allocations,K = K, complete = complete.loglikelihood, data = x,
prapivot = mcmc[maxIter,,], mcmc = mcmc, p = pMatrix,groundTruth = z.true)
}
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR")$output
write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"ECR-ITERATIVE-1")$output
write.table(reordered.mcmc, file = paste("reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
reordered.mcmc<-permute.mcmc(mcmc,ls$permutations$"STEPHENS")$output
write.table(reordered.mcmc, file = paste("reorderedMCMC-STEPHENS.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
write.table(mcmc, file = paste("rawMCMC.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
write.table(file = paste("reorderedSingleBestClusterings.mapK.",K,".txt",sep=""),t(ls$clusters[c(1,2,3),]),row.names = paste("z",1:n,sep="."))
allocationsECR <- allocationsKL <- allocationsECR.ITERATIVE1 <- allocations
for (i in 1:m){
myPerm <- order(ls$permutations$"ECR"[i,])
allocationsECR[i,] <- myPerm[allocations[i,]]
myPerm <- order(ls$permutations$"STEPHENS"[i,])
allocationsKL[i,] <- myPerm[allocations[i,]]
myPerm <- order(ls$permutations$"ECR-ITERATIVE-1"[i,])
allocationsECR.ITERATIVE1[i,] <- myPerm[allocations[i,]]
}
MeanReorderedpMatrix <- array(data = 0, dim = c(n,K))
for (i in 1:m){
myPerm <- ls$permutations$"ECR"[i,]
MeanReorderedpMatrix <- MeanReorderedpMatrix + pMatrix[i, ,myPerm]
}
MeanReorderedpMatrix <- MeanReorderedpMatrix/m
write.csv(MeanReorderedpMatrix, file = paste0("classificationProbabilities.mapK.",K,".csv"), row.names = FALSE)
write.table(allocationsECR, file = paste("z.ECR.mapK.",K,".txt",sep=""))
write.table(allocationsKL, file = paste("z.KL.mapK.",K,".txt",sep=""))
write.table(allocationsECR.ITERATIVE1, file = paste("z.ECR-ITERATIVE1.mapK.",K,".txt",sep=""))
cat(paste0("raw MCMC parameters for most probable K written to: \'rawMCMC.mapK.",K,".txt\' "),"\n")
cat(paste0("raw MCMC latent allocations for most probable K written to: \'z.mapK.",K,".txt\' "),"\n")
cat(paste0("reordered MCMC output written to: "),"\n")
cat(paste0(" (Method 1): \'reorderedMCMC-ECR.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 2): \'reorderedMCMC-ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 3): \'reorderedMCMC-STEPHENS.mapK.",K,".txt\'"),"\n")
cat(paste0("reordered single best clusterings written to: \'reorderedSingleBestClusterings.mapK.",K,".txt\' "),"\n")
cat(paste0("reordered MCMC latent allocations for most probable K written to: "),"\n")
cat(paste0(" (Method 1): \'z.ECR.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 2): \'z.KL.mapK.",K,".txt\'"),"\n")
cat(paste0(" (Method 3): \'z.ECR-ITERATIVE1.mapK.",K,".txt\'"),"\n")
}else{
cat(paste0('[NOTE]: Most probable model corresponds to 1 cluster so the label-switching algorithms are not applied.',"\n"))
write.table(mcmc, file = paste("MCMC.mapK.",K,".txt",sep=""),col.names = c(paste(rep(paste(expression(theta),1:K,sep="."),d),rep(1:d,each=K),sep="-"),paste('p',1:K,sep=".")))
cat(paste0("MCMC output corresponding to most probable model (K = 1) written to: \'", paste("MCMC.mapK.",K,".txt",sep=""),"\'"),"\n")
}
}
setwd("../")
}
print.bbm.object <- function(x, printSubset, ...){
if( missing(printSubset) ){ printSubset = TRUE }
if( 'bbm.object' %in% class(x) ){
cat("\n")
cat(paste0("* Run information:"),"\n")
cat(paste0(" Number of parallel heated chains: ", x$chainInfo[1]),"\n")
cat(paste0(" Swap acceptance rate: ", x$chainInfo[2],"%"),"\n")
cat(paste0(" Total number of iterations: ", x$chainInfo[3]*10),"\n")
cat(paste0(" Burn-in period: ", x$chainInfo[4]*10),"\n")
cat(paste0(" Thinning: 10."),"\n")
kFile <- x$K.mcmc
cat("\n")
cat(paste("* Estimated posterior distribution of the number of clusters:"),"\n")
print(round(table(x$K.mcmc)/length(x$K.mcmc),3))
K <- as.numeric(names(table(kFile))[order(table(kFile),decreasing=TRUE)[1]])
cat("\n")
cat(paste("* Most probable model: K = ",K," with P(K = ",K,"|data) = ",round(max(table(kFile)/length(kFile)),3),sep=""),"\n")
cat("\n")
cat(paste0("* Estimated number of observations per cluster conditionally on K = ", K," (3 label switching algorithms):"),'\n')
print(apply(x$clusterMembershipPerMethod,2,table))
d <- (dim(x$parameters.ecr.mcmc)[2] - K)/K
myMeans <- apply(x$parameters.ecr.mcmc,2,mean)
cat('\n')
if(printSubset == TRUE){
if(d > 5){
cat(paste0('* Posterior mean of probability of success per feature and cluster (ECR algorithm):'),'\n')
pr <- c()
for(k in 1:K){
subS <- paste0("theta.",k,".",1:d)[1:5]
pr <- cbind( pr, myMeans[subS])
}
colnames(pr) <- paste0("cluster_",1:K)
rownames(pr) <- paste0("theta_",1:5)
print(pr)
cat(paste0(' <+ ',d-5,' more rows>'),'\n')
}
}else{
cat(paste0('* Posterior mean of probability of success per feature and cluster (ECR algorithm):'),'\n')
pr <- c()
for(k in 1:K){
subS <- paste0("theta.",k,".",1:d)
pr <- cbind( pr, myMeans[subS])
}
colnames(pr) <- paste0("cluster_",1:K)
rownames(pr) <- paste0("theta_",1:d)
print(pr)
}
}else{
cat(paste(" The input is not in class `bbm.object`"),'\n')
}
} |
minEdge <- function(tree, tau=1e-8, enforce_ultrametric=FALSE){
if(tau<0) stop("tau must be >= 0!")
if(any(tree$edge.length < tau) || enforce_ultrametric){
rooted <- is.rooted(tree)
if(enforce_ultrametric) rooted <- TRUE
if(rooted){
nTip <- Ntip(tree)
ind <- seq_len(nTip)
nh <- nodeHeight(tree)[ind]
if(enforce_ultrametric) nh <- rep(0, nTip)
}
tree$edge.length[tree$edge.length < tau] <- tau
if(rooted){
el <- numeric(max(tree$edge))
el[tree$edge[,2]] <- tree$edge.length
nh2 <- nodeHeight(tree)[ind]
el[ind] <- el[ind] + (nh2 - nh)
tree$edge.length <- el[tree$edge[,2]]
}
}
tree
}
candidate.tree <- function(x, rooted=FALSE, eps = 1e-8, ...){
if(rooted){
dm <- dist.ml(x, ...)
tree <- wpgma(dm)
}
else{
tree <- random.addition(x)
tree <- optim.parsimony(tree, x, trace=0)
tree <- multi2di(tree)
tree <- unroot(tree)
tree <- acctran(tree, x)
tree$edge.length <- tree$edge.length / sum(attr(x, "weight"))
}
minEdge(tree, tau=eps)
}
bootstrap.pml <- function(x, bs = 100, trees = TRUE, multicore = FALSE,
mc.cores = NULL, ...) {
if(.Platform$OS.type=="windows") multicore <- FALSE
if (multicore && is.null(mc.cores)) mc.cores <- detectCores()
extras <- match.call(expand.dots = FALSE)$...
rearr <- c("optNni", "rearrangement")
tmp <- pmatch(names(extras), rearr)
tmp <- tmp[!is.na(tmp)]
do_rearr <- FALSE
if(length(tmp)>0){
if(tmp==1){
do_rearr <- extras$optNni
if(is.name(do_rearr)) do_rearr <- as.logical(as.character(do_rearr))
}
if(tmp==2) do_rearr <- extras$rearrangement %in% c("NNI", "stochastic",
"ratchet")
}
is_ultrametric <- FALSE
tmp <- pmatch("optRooted", names(extras))
if(!is.na(tmp)){
is_ultrametric <- extras$optRooted
}
data <- x$data
weight <- attr(data, "weight")
v <- rep(seq_along(weight), weight)
ntips <- Ntip(x$tree)
BS <- vector("list", bs)
for (i in 1:bs) BS[[i]] <- tabulate(
sample(v, replace = TRUE),
length(weight)
)
pmlPar <- function(weights, fit, trees = TRUE, do_rearr, ...) {
data <- fit$data
tree <- fit$tree
ind <- which(weights > 0)
data <- getRows(data, ind)
attr(data, "weight") <- weights[ind]
fit <- update(fit, data = data)
if(do_rearr){
tree <- candidate.tree(data, rooted = is_ultrametric, bf=fit$bf, Q=fit$Q)
fit <- update(fit, tree = tree)
}
fit <- optim.pml(fit, ...)
if (trees) {
tree <- fit$tree
return(tree)
}
attr(fit, "data") <- NULL
fit
}
eval.success <- FALSE
if (!eval.success & multicore) {
res <- mclapply(BS, pmlPar, x, trees = trees, do_rearr = do_rearr, ...,
mc.cores = mc.cores)
eval.success <- TRUE
}
if (!eval.success) res <- lapply(BS, pmlPar, x, trees = trees,
do_rearr = do_rearr, ...)
if (trees) {
class(res) <- "multiPhylo"
res <- .compressTipLabel(res)
}
res
}
bootstrap.phyDat <- function(x, FUN, bs = 100, multicore = FALSE,
mc.cores = NULL, jumble = TRUE, ...) {
if(.Platform$OS.type=="windows") multicore <- FALSE
if (multicore && is.null(mc.cores)) mc.cores <- detectCores()
weight <- attr(x, "weight")
v <- rep(seq_along(weight), weight)
BS <- vector("list", bs)
for (i in 1:bs) BS[[i]] <- tabulate(sample(v, replace = TRUE), length(weight))
if (jumble) {
J <- vector("list", bs)
l <- length(x)
for (i in 1:bs) J[[i]] <- list(BS[[i]], sample(l))
}
fitPar <- function(weights, data, ...) {
ind <- which(weights > 0)
data <- getRows(data, ind)
attr(data, "weight") <- weights[ind]
FUN(data, ...)
}
fitParJumble <- function(J, data, ...) {
ind <- which(J[[1]] > 0)
data <- getRows(data, ind)
attr(data, "weight") <- J[[1]][ind]
data <- subset(data, J[[2]])
FUN(data, ...)
}
if (multicore) {
if (jumble) {
res <- mclapply(J, fitParJumble, x, ..., mc.cores = mc.cores)
} else {
res <- mclapply(BS, fitPar, x, ..., mc.cores = mc.cores)
}
}
else {
if (jumble) {
res <- lapply(J, fitParJumble, x, ...)
} else {
res <- lapply(BS, fitPar, x, ...)
}
}
if (inherits(res[[1]], "phylo")) {
class(res) <- "multiPhylo"
res <- .compressTipLabel(res)
}
res
}
matchEdges <- function(tree1, tree2) {
bp1 <- bip(tree1)
bp2 <- bip(tree2)
l <- length(tree1$tip.label)
fn <- function(x, y) {
if (x[1] == 1) {
return(x)
} else {
return(y[-x])
}
}
bp1[] <- lapply(bp1, fn, 1:l)
bp2[] <- lapply(bp2, fn, 1:l)
match(bp1, bp2)
}
checkLabels <- function(tree, tip) {
ind <- match(tree$tip.label, tip)
if (any(is.na(ind)) | length(tree$tip.label) != length(tip)) {
stop("tree has different labels")
}
tree$tip.label <- tip
ind2 <- tree$edge[, 2] <= Ntip(tree)
tree$edge[ind2, 2] <- ind[tree$edge[ind2, 2]]
tree
}
plotBS <- function(tree, BStrees, type = "unrooted",
method="FBP", bs.col = "black",
bs.adj = NULL, digits=3, p = 0, frame = "none", ...) {
type <- match.arg(type, c("phylogram", "cladogram", "fan", "unrooted",
"radial", "none"))
method <- match.arg(method, c("FBP", "TBE"))
if (hasArg(BStrees)) {
if(method=="FBP"){
BStrees <- .uncompressTipLabel(BStrees)
if (any(is.rooted(BStrees))) BStrees <- unroot(BStrees)
x <- prop.clades(tree, BStrees)
x <- (x / length(BStrees)) * 100
tree$node.label <- x
}
else {
tree <- transferBootstrap(tree, BStrees)
x <- tree$node.label
}
}
else {
if (is.null(tree$node.label)) stop("You need to supply 'trees' or the tree needs support-values as node.label")
x <- tree$node.label
}
if(type=="none") return( tree )
plot(tree, type = type, ...)
label <- c(rep(0, length(tree$tip.label)), x)
ind <- get("last_plot.phylo", envir = .PlotPhyloEnv)$edge[ ,2 ]
if (type == "phylogram" | type == "cladogram") {
root <- getRoot(tree)
label <- c(rep(0, length(tree$tip.label)), x)
label[root] <- 0
ind <- which(label > p)
if (is.null(bs.adj)) {
bs.adj <- c(1, 1)
}
if (length(ind) > 0) {
if(is.numeric(label)) label <- round(label, digits = digits)
nodelabels(
text = label[ind], node = ind,
frame = frame, col = bs.col, adj = bs.adj, ...
)
}
}
else {
if (is.null(bs.adj)) {
bs.adj <- c(0.5, 0.5)
}
ind2 <- which(label[ind] > p)
if (length(ind2 > 0)) {
if(is.numeric(label)) label <- round(label, digits = digits)
edgelabels(label[ind][ind2], ind2,
frame = frame,
col = bs.col, adj = bs.adj, ...
)
}
}
invisible(tree)
}
maxCladeCred <- function(x, tree = TRUE, part = NULL, rooted = TRUE) {
if (inherits(x, "phylo")) x <- c(x)
if (is.null(part)) {
if (!rooted) {
pp <- unroot(x) |> prop.part()
} else {
pp <- prop.part(x)
}
}
else {
pp <- part
}
pplabel <- attr(pp, "labels")
if (!rooted){
pp <- postprocess.prop.part(pp, method="SHORTwise")
}
x <- .uncompressTipLabel(x)
class(x) <- NULL
m <- max(attr(pp, "number"))
nb <- log(attr(pp, "number") / m)
l <- length(x)
res <- numeric(l)
for (i in 1:l) {
tmp <- checkLabels(x[[i]], pplabel)
if (!rooted) tmp <- unroot(tmp)
ppi <- prop.part(tmp)
if (!rooted) ppi <- SHORTwise(ppi)
indi <- fmatch(ppi, pp)
if (any(is.na(indi))) {
res[i] <- -Inf
} else {
res[i] <- sum(nb[indi])
}
}
if (tree) {
k <- which.max(res)
tr <- x[[k]]
tr <- addConfidences(tr, pp)
attr(tr, "clade.credibility") <- res[k]
return(tr)
}
res
}
mcc <- maxCladeCred
allCompat <- function(x) {
x <- unroot(x)
l <- length(x)
pp <- prop.part(x)
pp <- postprocess.prop.part(pp, method = "SHORTwise")
spl <- as.splits(pp)
w <- attr(spl, "weights")
ind <- (w / l) > 0.5
res <- spl[ind]
spl <- spl[!ind]
w <- attr(spl, "weights")
ord <- order(w, decreasing = TRUE)
for(i in ord){
if(all(compatible(res, spl[i]) == 0)) res <- c(res, spl[i])
}
tree <- as.phylo(res, FALSE)
tree$edge.length <- NULL
tree <- addConfidences(tree, pp)
tree
}
cladeMatrix <- function(x, rooted = FALSE) {
if (!rooted) x <- unroot(x)
pp <- prop.part(x)
pplabel <- attr(pp, "labels")
if (!rooted) pp <- SHORTwise(pp)
x <- .uncompressTipLabel(x)
nnodes <- Nnode(x)
class(x) <- NULL
l <- length(x)
from <- cumsum(c(1, nnodes[-l]))
to <- cumsum(nnodes)
ivec <- integer(to[l])
pvec <- c(0, to)
res <- vector("list", l)
k <- 1
for (i in 1:l) {
ppi <- prop.part(x[[i]])
if (!rooted) ppi <- SHORTwise(ppi)
indi <- sort(fmatch(ppi, pp))
ivec[from[i]:to[i]] <- indi
}
X <- sparseMatrix(i = ivec, p = pvec, dims = c(length(pp), l))
list(X = X, prop.part = pp)
}
moving_average <- function(obj, window = 50) {
fun <- function(x) {
cx <- c(0, cumsum(x))
(cx[(window + 1):length(cx)] - cx[1:(length(cx) - window)]) / (window)
}
res <- apply(obj$X, 1, fun)
rownames(res) <- c()
} |
is_uri <- function(s) {
nchar(s) == 22 &
!str_detect(s, ' ') &
str_detect(s, '[[:digit:]]') &
str_detect(s, '[[:lower:]]') &
str_detect(s, '[[:upper:]]')
}
pitch_class_lookup <- c('C', 'C
verify_result <- function(res) {
if (!is.null(res$error)) {
stop(str_glue('{res$error$message} ({res$error$status})'))
}
}
scopes <- function() {
xml2::read_html("https://developer.spotify.com/documentation/general/guides/authorization/scopes/") %>%
rvest::html_elements('code') %>%
rvest::html_text() %>%
unique()
}
dedupe_album_names <- function(df,
album_name_col = 'album_name',
album_release_year_col = 'album_release_year') {
album_dupe_regex <- '(deluxe|international|anniversary|version|edition|remaster|re-master|live|mono|stereo)'
base_album_names <- df %>%
mutate( album_name_ = album_name_col,
album_release_year_ = album_release_year_col
) %>%
dplyr::filter(!duplicated(tolower(album_name_))) %>%
mutate(base_album_name = gsub(str_glue(' \\(.*{album_dupe_regex}.*\\)'), '', tolower(.data$album_name_)),
base_album_name = gsub(str_glue(' \\[.*{album_dupe_regex}.*\\]'), '', .data$base_album_name),
base_album_name = gsub(str_glue(':.*{album_dupe_regex}.*'), '', .data$base_album_name),
base_album_name = gsub(str_glue(' - .*{album_dupe_regex}.*'), '', .data$base_album_name),
base_album = tolower(.data$album_name_) == .data$base_album_name) %>%
group_by(.data$base_album_name) %>%
dplyr::filter((.data$album_release_year_ == min(.data$album_release_year_)) | base_album) %>%
mutate(num_albums = n(),
num_base_albums = sum(.data$base_album)) %>%
ungroup() %>%
dplyr::filter((.data$base_album == 1) |((.data$num_base_albums == 0 | .data$num_base_albums > 1) & row_number() == 1)) %>%
pull(.data$album_name_)
df %>%
mutate(album_name_ = album_name_col) %>%
filter(.data$album_name_ %in% base_album_names) %>%
select(-all_of("album_name_"))
}
query_playlist <- function(url, params) {
res <- RETRY('GET', url, query = params, encode = 'json')
stop_for_status(res)
res <- fromJSON(content(res, as = 'text', encoding = 'UTF-8'),
flatten = TRUE)
res
} |
test_that("dt_sources captures all tables", {
dt1 <- lazy_dt(data.frame(x = 1), "dt1")
dt2 <- lazy_dt(data.frame(x = 2), "dt2")
dt3 <- lazy_dt(data.frame(x = 3), "dt3")
out <- dt1 %>% left_join(dt2, by = "x") %>% left_join(dt3, by = "x")
expect_equal(
dt_sources(out)[c("dt1", "dt2", "dt3")],
list(dt1 = dt1$parent, dt2 = dt2$parent, dt3 = dt3$parent)
)
})
test_that("joins captures locals from both parents", {
dt1 <- lazy_dt(data.frame(x = 1)) %>% mutate(y = 1) %>% compute("D1")
dt2 <- lazy_dt(data.frame(x = 1)) %>% mutate(z = 1) %>% compute("D2")
expect_named(left_join(dt1, dt2, by = "x")$locals, c("D1", "D2"))
expect_named(inner_join(dt1, dt2, by = "x")$locals, c("D1", "D2"))
})
test_that("simple usage generates expected translation", {
dt1 <- lazy_dt(tibble(x = 1, y = 2, a = 3), "dt1")
dt2 <- lazy_dt(tibble(x = 1, y = 2, b = 4), "dt2")
expect_equal(
dt1 %>% left_join(dt2, by = "x") %>% show_query(),
expr(
setnames(
setcolorder(
dt2[dt1, on = .(x), allow.cartesian = TRUE],
!!c(1L, 4L, 5L, 2L, 3L)
),
!!c("i.y", "y"),
!!c("y.x", "y.y")
)
)
)
expect_equal(
dt1 %>% right_join(dt2, by = "x") %>% show_query(),
expr(
setnames(
dt1[dt2, on = .(x), allow.cartesian = TRUE],
!!c("y", "i.y"),
!!c("y.x", "y.y")
)
)
)
expect_equal(
dt1 %>% inner_join(dt2, by = "x") %>% show_query(),
expr(
setnames(
dt1[dt2, on = .(x), nomatch = NULL, allow.cartesian = TRUE],
!!c("y", "i.y"),
!!c("y.x", "y.y")
)
)
)
expect_equal(
dt1 %>% full_join(dt2, by = "x") %>% show_query(),
expr(merge(dt1, dt2, all = TRUE, by.x = "x", by.y = "x", allow.cartesian = TRUE))
)
expect_equal(
dt1 %>% anti_join(dt2, by = "x") %>% show_query(),
expr(dt1[!dt2, on = .(x)])
)
expect_equal(
dt1 %>% semi_join(dt2, by = "x") %>% show_query(),
expr(dt1[unique(dt1[dt2, which = TRUE, nomatch = NULL, on = .(x)])])
)
})
test_that("full_join produces correct names", {
df1 <- tibble(a = "a", b = "b.x", b.x = "b.x.x.x")
df2 <- tibble(a = "a", b = "b.y", b.x.x = "b.x.x")
dt1 <- lazy_dt(df1, "dt1")
dt2 <- lazy_dt(df2, "dt2")
joined_dt <- full_join(dt1, dt2, by = "a")
expected <- full_join(df1, df2, by = "a") %>% colnames()
expect_equal(
joined_dt %>% .$vars,
expected
)
expect_equal(
suppressWarnings(joined_dt %>% collect() %>% colnames()),
expected
)
})
test_that("join can handle `by` where order doesn't match input", {
dt1 <- lazy_dt(tibble(a = "a", b = "b", c = "c"), name = "dt1")
dt2 <- lazy_dt(tibble(a = "a", b = "b", c = "c", d = "d"), name = "dt2")
dt3 <- left_join(dt1, dt2, by = c("c", "b", "a"))
expect_equal(dt3$vars, letters[1:4])
expect_equal(collect(dt3), collect(dt2))
dt4 <- full_join(dt1, dt2, by = c("c", "b", "a"))
expect_equal(dt4$vars, letters[1:4])
expect_equal(collect(dt4), collect(dt2))
dt5 <- left_join(dt1, dt2, by = c("c", "b"))
expect_equal(
collect(dt5),
tibble(a.x = "a", b = "b", c = "c", a.y = "a", d = "d")
)
})
test_that("left_join produces correct names", {
df1 <- tibble(a = "a", b = "b.x", i.b = "i.b")
df2 <- tibble(a = "a", b = "b.y")
dt1 <- lazy_dt(df1, "dt1")
dt2 <- lazy_dt(df2, "dt2")
joined_dt <- left_join(dt1, dt2, by = "a")
expected <- left_join(df1, df2, by = "a") %>% colnames()
expect_equal(
joined_dt %>% .$vars,
expected
)
expect_equal(
joined_dt %>% collect() %>% colnames(),
expected
)
})
test_that("named by converted to by.x and by.y", {
dt1 <- lazy_dt(data.frame(a1 = 1:3, z = 1), "dt1")
dt2 <- lazy_dt(data.frame(a2 = 1:3, z = 2), "dt2")
out_inner <- inner_join(dt1, dt2, by = c('a1' = 'a2'))
expect_equal(
out_inner %>% show_query(),
expr(
setnames(
dt1[dt2, on = .(a1 = a2), nomatch = NULL, allow.cartesian = TRUE],
!!c("z", "i.z"),
!!c("z.x", "z.y")
)
)
)
expect_setequal(tbl_vars(out_inner), c("a1", "z.x", "z.y"))
out_left <- left_join(dt1, dt2, by = c('a1' = 'a2'))
expect_equal(
out_left %>% show_query(),
expr(
setnames(
setcolorder(
dt2[dt1, on = .(a2 = a1), allow.cartesian = TRUE],
!!c(1L, 3L, 2L)
),
!!c("a2", "i.z", "z"),
!!c("a1", "z.x", "z.y")
)
)
)
expect_setequal(tbl_vars(out_left), c("a1", "z.x", "z.y"))
})
test_that("named by can handle edge cases", {
test_equal <- function(f_join) {
joined_dt <- f_join(dt1, dt2, by = c("x", z = "y"))
expected <- f_join(df1, df2, by = c("x", z = "y"))
expect_equal(
joined_dt %>% collect(),
expected
)
expect_equal(
joined_dt$vars,
colnames(expected)
)
}
df1 <- tibble(x = 1, y = 1, z = 2)
df2 <- tibble(x = 1, y = 2)
dt1 <- lazy_dt(df1, "dt1")
dt2 <- lazy_dt(df2, "dt2")
test_equal(left_join)
test_equal(right_join)
test_equal(full_join)
test_equal(semi_join)
test_equal(anti_join)
})
test_that("setnames only used when necessary", {
dt1 <- lazy_dt(data.frame(x = 1:2, a = 3), "dt1")
dt2 <- lazy_dt(data.frame(x = 2:3, b = 4), "dt2")
expect_equal(
dt1 %>% left_join(dt2, by = "x") %>% show_query(),
expr(setcolorder(dt2[dt1, on = .(x), allow.cartesian = TRUE], !!c(1L, 3L, 2L)))
)
expect_equal(
dt1 %>% left_join(dt2, by = "x") %>% pull(x),
dt1 %>% pull(x)
)
})
test_that("correctly determines vars", {
dt1 <- lazy_dt(data.frame(x = 1, y = 2, a = 3), "dt1")
dt2 <- lazy_dt(data.frame(x = 1, y = 2, b = 4), "dt2")
expect_setequal(
dt1 %>% left_join(dt2, by = c("x", "y")) %>% .$vars,
c("x", "y", "a", "b")
)
expect_setequal(
dt1 %>% left_join(dt2, by = "x") %>% .$vars,
c("x", "y.x", "y.y", "a", "b")
)
expect_setequal(
dt1 %>% semi_join(dt2, by = "x") %>% .$vars,
c("x", "y", "a")
)
})
test_that("can override suffixes", {
dt1 <- lazy_dt(data.frame(x = 1, y = 2, a = 3), "dt1")
dt2 <- lazy_dt(data.frame(x = 1, y = 22, b = 4), "dt2")
expect_equal(
dt1 %>% left_join(dt2, by = "x", suffix = c("X", "Y")) %>% show_query(),
expr(
setnames(
setcolorder(
dt2[dt1, on = .(x), allow.cartesian = TRUE],
!!c(1L, 4L, 5L, 2L, 3L)
),
!!c("i.y", "y"),
!!c("yX", "yY")
)
)
)
})
test_that("automatically data.frame converts to lazy_dt", {
dt1 <- lazy_dt(data.frame(x = 1, y = 2, a = 3), "dt1")
df2 <- data.frame(x = 1, y = 2, a = 3)
out <- left_join(dt1, df2, by = "x")
expect_s3_class(out, "dtplyr_step")
})
test_that("converts other types if requested", {
dt1 <- lazy_dt(data.frame(x = 1, y = 2, a = 3), "dt1")
x <- structure(10, class = "foo")
expect_error(left_join(dt1, x, by = "x"), "copy")
expect_s3_class(left_join(dt1, x, by = "x", copy = TRUE), "dtplyr_step_join")
})
test_that("mutates inside joins are copied as needed", {
dt <- data.table(x = 1)
lhs <- lazy_dt(dt, "dt1") %>% mutate(y = x + 1)
rhs <- lazy_dt(dt, "dt2") %>% mutate(z = x + 1)
collect(inner_join(lhs, rhs, by = "x"))
expect_named(dt, "x")
})
test_that("performs cartesian joins as needed", {
x <- lazy_dt(data.frame(x = c(2, 2, 2), y = 1:3))
y <- lazy_dt(data.frame(x = c(2, 2, 2), z = 1:3))
out <- collect(left_join(x, y, by = "x"))
expect_equal(nrow(out), 9)
})
test_that("performs cross join", {
df1 <- data.frame(x = 1:2, y = "a", stringsAsFactors = FALSE)
df2 <- data.frame(x = 3:4)
dt1 <- lazy_dt(df1, "dt1")
dt2 <- lazy_dt(df2, "dt2")
expected <- left_join(df1, df2, by = character()) %>% as_tibble()
expect_snapshot(left_join(dt1, dt2, by = character()))
expect_equal(left_join(dt1, dt2, by = character()) %>% collect(), expected)
expect_snapshot(right_join(dt1, dt2, by = character()))
expect_equal(right_join(dt1, dt2, by = character()) %>% collect(), expected)
expect_snapshot(full_join(dt1, dt2, by = character()))
expect_equal(full_join(dt1, dt2, by = character()) %>% collect(), expected)
expect_snapshot(inner_join(dt1, dt2, by = character()))
expect_equal(inner_join(dt1, dt2, by = character()) %>% collect(), expected)
}) |
test_that("call_or_default", {
expect_identical(call_or_default(NULL, 0), 0)
expect_identical(call_or_default(sin, 1), sin(1))
})
test_that("get_digtis", {
expect_equal(get_digits(c("0.1", "0.01", ".501", ".5001", "123.321", "123", "012", "5.")),
c(1, 2, 3, 4, 3, 0, 0, 0))
})
test_that("copy_dim", {
x <- c(1, 2, 3)
y <- format(x)
expect_true(!is.array(copy_dim(x, y)))
x <- c(1, 2, 3, 4)
m <- matrix(x, 2, dimnames = list(c("a", "b")))
y <- format(x)
y2 <- copy_dim(m, y)
expect_true(is.matrix(y2))
expect_identical(dim(y2), dim(m))
expect_identical(dimnames(y2), dimnames(m))
x <- rnorm(24)
arr <- array(x, c(2, 3, 4),
dimnames = list(letters[1:2], letters[1:3], letters[1:4]))
y <- format(x)
y2 <- copy_dim(arr, y)
expect_true(is.array(y2))
expect_identical(dim(y2), dim(arr))
expect_identical(dimnames(y2), dimnames(arr))
}) |
context("Get branches")
test_that("We get a error when there is no url", {
expect_error(get_branches(api_key = api_key, owner = owner,
repo = repo),
"Please add a valid URL")
})
test_that("We get a error when there is no api_key", {
expect_error(get_branches(base_url = base_url, owner = owner,
repo = repo),
"Please add a valid API token")
})
test_that("We get a error when there is no owner", {
expect_error(get_branches(base_url = base_url, api_key = api_key,
repo = repo),
"Please add a valid owner")
})
test_that("We get a error when there is no repository", {
expect_error(get_branches(base_url = base_url, api_key = api_key,
owner = owner),
"Please add a valid repository")
})
test_that("Error putting invalid url for API", {
mockery::stub(where = get_branches,
what = "tryCatch",
how = "Failure")
expect_error(get_branches("google.com", api_key, owner, repo),
"Error consulting the url: ")
})
test_that("Branches are read correctly", {
mockery::stub(where = get_branches,
what = "GET",
how = r)
mockery::stub(where = get_branches,
what = "fromJSON",
how = content_branches)
value_branches <- get_branches(base_url, api_key, owner, repo)
expect_true(exists("value_branches"))
})
test_that("Getting branches gives the expected result", {
mockery::stub(where = get_branches,
what = "GET",
how = r)
mockery::stub(where = get_branches,
what = "fromJSON",
how = content_branches)
value_branches <- get_branches(base_url, api_key, owner, repo)
expect_equal(TRUE, !is.null(value_branches))
expect_that(value_branches, is_a("data.frame"))
}) |
context("checkAtomicVector")
test_that("checkAtomicVector", {
myobj = 1:2
expect_succ_all(AtomicVector, myobj)
myobj = NULL
expect_fail_all(AtomicVector, myobj)
expect_true(testAtomicVector(integer(0)))
expect_false(testAtomicVector(NULL))
expect_true(testAtomicVector(1))
expect_true(testAtomicVector(integer(0)))
expect_true(testAtomicVector(factor(1)))
expect_true(testAtomicVector(NA, any.missing = TRUE))
expect_false(testAtomicVector(NA, any.missing = FALSE))
expect_false(testAtomicVector(NA, all.missing = FALSE))
expect_true(testAtomicVector(1, len=1))
expect_false(testAtomicVector(1, len=0))
expect_true(testAtomicVector(1, min.len=0))
expect_false(testAtomicVector(1, min.len=2))
expect_true(testAtomicVector(1, max.len=1))
expect_false(testAtomicVector(1, max.len=0))
expect_true(testAtomicVector(1, unique=TRUE))
expect_false(testAtomicVector(1, min.len=2))
expect_true(testAtomicVector(1, max.len=1))
expect_false(testAtomicVector(1, max.len=0))
expect_true(testAtomicVector(1, unique=TRUE))
expect_true(testAtomicVector(c(1,1), unique=FALSE))
expect_false(testAtomicVector(c(1,1), unique=TRUE))
expect_true(testAtomicVector(1, names="unnamed"))
expect_true(testAtomicVector(setNames(1, "x"), names="named"))
expect_false(testAtomicVector(1, names="unique"))
expect_error(assertAtomicVector(iris), "atomic")
li = list(list = list(1, 2), factor = factor("a"), integer = 1:2, NULL = NULL, data.frame = iris, matrix = matrix(1:9))
expected = setNames(c(FALSE, TRUE, TRUE, FALSE, FALSE, FALSE), names(li))
expect_equal(expected, vlapply(li, testAtomicVector))
})
test_that("type guessing works (
x = structure(list(1:4, letters[1:3]), dim = c(2, 1))
expect_match(checkAtomic(x), "list")
}) |
data_frame <- function(...) {
x <- data.frame(..., stringsAsFactors = FALSE)
rownames(x) <- NULL
x
}
is.stan <- function(x) inherits(x, c("stanreg", "stanfit", "brmsfit"))
stan.has.multiranef <- function(x) {
if (obj_has_name(x, "facet")) {
ri <- string_starts_with("(Intercept", x = x$facet)
if (!sjmisc::is_empty(ri)) {
return(dplyr::n_distinct(x$facet[ri]) > 1)
}
}
FALSE
}
has_value_labels <- function(x) {
!(is.null(attr(x, "labels", exact = T)) && is.null(attr(x, "value.labels", exact = T)))
}
axis_limits_and_ticks <- function(axis.lim, min.val, max.val, grid.breaks, exponentiate, min.est, max.est) {
fac.ll <- dplyr::if_else(exponentiate, .3, .95)
fac.ul <- dplyr::if_else(exponentiate, 3.3, 1.05)
if (is.infinite(min.val) || is.na(min.val)) min.val <- min.est
if (is.infinite(max.val) || is.na(max.val)) max.val <- max.est
if (min.val < 0) fac.ll <- 1 / fac.ll
if (max.val < 0) fac.ul <- 1 / fac.ul
if (is.null(axis.lim)) {
lower_lim <- min.val * fac.ll
upper_lim <- max.val * fac.ul
} else {
lower_lim <- axis.lim[1]
upper_lim <- axis.lim[2]
}
if (is.null(grid.breaks)) {
if (exponentiate) {
lower_lim <- round(lower_lim, 2)
upper_lim <- round(upper_lim, 2)
if (lower_lim == 0) lower_lim <- min.val * fac.ll / 10
ls <- log10(c(lower_lim, upper_lim))
ticks <- grDevices::axisTicks(c(floor(ls[1]), ceiling(ls[2])), log = TRUE)
ll <- which(ticks < lower_lim)
if (!sjmisc::is_empty(ll) && length(ll) > 1) ticks <- ticks[ll[length(ll)]:length(ticks)]
ul <- which(ticks > upper_lim)
if (!sjmisc::is_empty(ul) && length(ul) > 1) ticks <- ticks[1:ul[1]]
} else {
ticks <- pretty(c(floor(lower_lim), ceiling(upper_lim)))
}
} else {
if (length(grid.breaks) == 1)
ticks <- seq(floor(lower_lim), ceiling(upper_lim), by = grid.breaks)
else
ticks <- grid.breaks
}
list(axis.lim = c(min(ticks), max(ticks)), ticks = ticks)
}
estimate_axis_title <- function(fit, axis.title, type, transform = NULL, multi.resp = NULL, include.zeroinf = FALSE) {
if (type %in% c("eff", "pred", "int")) return(axis.title)
if (is.null(axis.title)) {
fitfam <- insight::model_info(fit)
if (!is.null(multi.resp))
fitfam <- fitfam[[multi.resp]]
else if (insight::is_multivariate(fit))
fitfam <- fitfam[[1]]
axis.title <- dplyr::case_when(
!is.null(transform) && transform == "plogis" ~ "Probabilities",
is.null(transform) && fitfam$is_binomial ~ "Log-Odds",
is.null(transform) && fitfam$is_ordinal ~ "Log-Odds",
is.null(transform) && fitfam$is_multinomial ~ "Log-Odds",
is.null(transform) && fitfam$is_categorical ~ "Log-Odds",
is.null(transform) && fitfam$is_count ~ "Log-Mean",
fitfam$is_count ~ "Incidence Rate Ratios",
fitfam$is_ordinal ~ "Odds Ratios",
fitfam$is_multinomial ~ "Odds Ratios",
fitfam$is_categorical ~ "Odds Ratios",
fitfam$is_binomial && !fitfam$is_logit ~ "Risk Ratios",
fitfam$is_binomial ~ "Odds Ratios",
TRUE ~ "Estimates"
)
if (fitfam$is_zero_inflated && isTRUE(include.zeroinf)) {
if (is.null(transform))
axis.title <- c(axis.title, "Log-Odds")
else
axis.title <- c(axis.title, "Odds Ratios")
}
}
axis.title
}
get_p_stars <- function(pval, thresholds = NULL) {
if (is.null(thresholds)) thresholds <- c(.05, .01, .001)
dplyr::case_when(
is.na(pval) ~ "",
pval < thresholds[3] ~ "***",
pval < thresholds[2] ~ "**",
pval < thresholds[1] ~ "*",
TRUE ~ ""
)
}
is_merMod <- function(fit) {
inherits(fit, c("lmerMod", "glmerMod", "nlmerMod", "merModLmerTest"))
}
is_brms_mixed <- function(fit) {
inherits(fit, "brmsfit") && !sjmisc::is_empty(fit$ranef)
}
is_mixed_model <- function(fit) {
mi <- insight::model_info(fit)
if (insight::is_multivariate(fit))
mi[[1]]$is_mixed
else
mi$is_mixed
}
nulldef <- function(x, y, z = NULL) {
if (is.null(x)) {
if (is.null(y))
z
else
y
} else
x
}
geom_intercept_line <- function(yintercept, axis.scaling, vline.color) {
if (yintercept > axis.scaling$axis.lim[1] && yintercept < axis.scaling$axis.lim[2]) {
t <- theme_get()
if (is.null(t$panel.grid.major)) t$panel.grid.major <- t$panel.grid
color <- nulldef(vline.color, t$panel.grid.major$colour, "grey90")
minor_size <- nulldef(t$panel.grid.minor$size, .125)
major_size <- nulldef(t$panel.grid.major$size, minor_size * 1.5)
size <- major_size * 1.5
geom_hline(yintercept = yintercept, color = color, size = size)
} else {
NULL
}
}
geom_intercept_line2 <- function(yintercept, vline.color) {
t <- theme_get()
if (is.null(t$panel.grid.major)) t$panel.grid.major <- t$panel.grid
color <- nulldef(vline.color, t$panel.grid.major$colour, "grey90")
minor_size <- nulldef(t$panel.grid.minor$size, .125)
major_size <- nulldef(t$panel.grid.major$size, minor_size * 1.5)
size <- major_size * 1.5
geom_hline(yintercept = yintercept, color = color, size = size)
}
check_se_argument <- function(se, type = NULL) {
if (!is.null(se) && !is.null(type) && type %in% c("std", "std2")) {
warning("No robust standard errors for `type = \"std\"` or `type = \"std2\"`.")
se <- NULL
}
if (!is.null(se) && !is.null(type) && type == "re") {
warning("No robust standard errors for `type = \"re\"`.")
se <- NULL
}
se
}
list.depth <- function(this, thisdepth = 0) {
if (!is.list(this)) {
return(thisdepth)
} else {
return(max(unlist(lapply(this, list.depth, thisdepth = thisdepth + 1))))
}
}
parse_terms <- function(x) {
if (sjmisc::is_empty(x)) return(x)
vars.pos <-
which(as.vector(regexpr(
pattern = " ([^\\]]*)\\]",
text = x,
perl = T
)) != -1)
if (sjmisc::is_empty(vars.pos)) return(x)
vars.names <- clear_terms(x)[vars.pos]
tmp <- unlist(regmatches(
x,
gregexpr(
pattern = " ([^\\]]*)\\]",
text = x,
perl = T
)
))
tmp <- gsub("(\\[*)(\\]*)", "", tmp)
tmp <- sjmisc::trim(strsplit(tmp, ",", fixed = T))
parsed.terms <- seq_len(length(tmp)) %>%
purrr::map(~ sprintf("%s%s", vars.names[.x], tmp[[.x]])) %>%
purrr::flatten_chr()
c(x[-vars.pos], parsed.terms)
}
clear_terms <- function(x) {
cleaned.pos <- regexpr(pattern = "\\s", x)
replacers <- which(cleaned.pos == -1)
cleaned.pos[replacers] <- nchar(x)[replacers]
sjmisc::trim(substr(x, 0, cleaned.pos))
}
is_empty_list <- function(x) {
all(purrr::map_lgl(x, sjmisc::is_empty))
}
model_deviance <- function(x) {
tryCatch(
{
m_deviance(x)
},
error = function(x) { NULL }
)
}
model_aic <- function(x) {
performance::performance_aic(x)
}
model_aicc <- function(x) {
tryCatch(
{
performance::performance_aicc(x)
},
error = function(x) { NULL }
)
}
model_loglik <- function(x) {
tryCatch(
{
stats::logLik(x)
},
error = function(x) { NULL }
)
}
m_deviance <- function(x) {
if (is_merMod(x)) {
if (!requireNamespace("lme4", quietly = TRUE)) {
stop("Package 'lme4' required for this function to work, please install it.")
}
d <- lme4::getME(x, "devcomp")$cmp["dev"]
if (is.na(d)) d <- stats::deviance(x, REML = FALSE)
} else {
d <- stats::deviance(x)
}
d
}
tidy_label <- function(labs, sep = ".") {
duped.val <- names(which(table(labs) > 1))
dupes <- duped.val %>%
purrr::map(~which(labs == .x)) %>%
purrr::as_vector(.type = "double")
labs[dupes] <- sprintf("%s%s%s", labs[dupes], sep, dupes)
labs
}
se_ranef <- function(object) {
if (!requireNamespace("lme4", quietly = TRUE)) {
stop("Package 'lme4' required for this function to work, please install it.")
}
if (inherits(object, "MixMod")) {
se.bygroup <- lme4::ranef(object, post_vars = TRUE)
vars.m <- attr(se.bygroup, "post_vars")
if (dim(vars.m[[1]])[1] == 1)
se.bygroup <- sqrt(unlist(vars.m))
else {
se.bygroup <- do.call(
rbind,
purrr::map_df(vars.m, ~ t(as.data.frame(sqrt(diag(.x)))))
)
dimnames(se.bygroup)[[2]] <- dimnames(vars.m[[1]])[[1]]
se.bygroup <- list(se.bygroup)
names(se.bygroup) <- insight::find_random(object, flatten = TRUE)
}
} else {
se.bygroup <- lme4::ranef(object, condVar = TRUE)
n.groupings <- length(se.bygroup)
for (m in 1:n.groupings) {
vars.m <- attr(se.bygroup[[m]], "postVar")
K <- dim(vars.m)[1]
J <- dim(vars.m)[3]
names.full <- dimnames(se.bygroup[[m]])
se.bygroup[[m]] <- array(NA, c(J, K))
for (j in 1:J) {
se.bygroup[[m]][j, ] <- sqrt(diag(as.matrix(vars.m[, , j])))
}
dimnames(se.bygroup[[m]]) <- list(names.full[[1]], names.full[[2]])
}
}
se.bygroup
}
get_observations <- function(model) {
tryCatch(
{
insight::n_obs(model)
},
error = function(x) { NULL }
)
}
.labelled_model_data <- function(models) {
if (!inherits(models, "list")) models <- list(models)
mf <- try(lapply(models, function(.x) insight::get_data(.x)[, -1, drop = FALSE]), silent = TRUE)
if (inherits(mf, "try-error")) {
return(FALSE)
}
lbs <- unlist(lapply(mf, function(x) {
any(sapply(x, function(i) !is.null(attributes(i)$label)))
}))
any(lbs)
} |
NULL
img_simplicity <- function(imgfile, algorithm = "zip", rotate = FALSE){
1 - img_complexity(imgfile, algorithm, rotate)
} |
get_bh_threshold <-
function(pvals, alpha, mtests = length(pvals)){
m <- length(pvals)
pvals <- sort(pvals)
prejected <- which(pvals <= (1:m)/mtests*alpha)
ifelse(length(prejected)==0, 0, pvals[prejected[which.max(prejected)]])
} |
unpivot = function(m){
m = as.matrix(m)
m = data.frame( rep(rownames(m), ncol(m)),
rep(colnames(m), each=nrow(m)),
c(m) )
return(m)
} |
modelMembers.default <-
function( BMAobject)
{
dimnames(as.matrix(BMAobject$weights))[[1]]
} |
surv_stoEM_ipw <- function(data, zetat, zetaz, B = 100, theta = 0.5, offset = TRUE){
t = data$t
d = data$d
Z = data$Z
X = data.matrix(data$X)
nx = dim(X)[2]
n = length(t)
Coeft1 = Coeft1.se = numeric(B)
for (j in 1:B){
Usim = SimulateU_surv(t, d, Z, X, zetat = zetat, zetaz = zetaz, theta = theta, offset=TRUE)
Z.fit = glm(Z ~ X, offset = zetaz * Usim$U, family=binomial(link="probit"))
ps = Z.fit$fitted.values
ipw = (sum(Z)/n) * Z/ps + (1-(sum(Z)/n))*(1-Z)/(1-ps)
ipw = pmin(ipw, 10)
ipw = pmax(ipw, 0.1)
t1.ipw = coxph(Surv(t, d) ~ Z, weights = ipw, robust = TRUE)
Coeft1[j] = t1.ipw$coefficients
Coeft1.se[j] = summary(t1.ipw)$coefficients[,'robust se']
}
names(Coeft1) = names(Coeft1.se) = names(t1.ipw$coefficients)
tau1 = mean(Coeft1)
tau1.se = sqrt(mean((Coeft1.se)^2) + (1+1/B) * var(Coeft1))
return (list(tau1 = tau1, tau1.se = tau1.se))
} |
"qrisk" <-
function(x, alpha=c(.1,.3), w = c(.7,.3), mu = .07, R = NULL, r = NULL, lambda = 10000){
n <- nrow(x)
p <- ncol(x)
m <- length(alpha)
if(length(w)!=m)stop("length of w doesn't match length of alpha")
xbar <- apply(x,2,mean)
y <- x[,1]
r <- c(r,lambda*(xbar[1]-mu), -lambda*(xbar[1]-mu))
X <- x[,1]-x[,-1]
R <- rbind(R,lambda*(xbar[1]-xbar[-1]), -lambda*(xbar[1]-xbar[-1]))
R <- cbind(matrix(0,nrow(R),m),R)
f <- rq.fit.hogg(X,y,taus=alpha,weights=w,R=R,r=r)
fit <- f$coefficients
pihat <- c(1-sum(fit[-(1:m)]),fit[-(1:m)])
x <- as.matrix(x)
yhat <- x%*%pihat
etahat <- quantile(yhat,alpha)
muhat <- mean(yhat)
qrisk <- 0
for(i in 1:length(alpha))
qrisk <- qrisk + w[i]*sum(yhat[yhat<etahat[i]])/(n*alpha[i])
list(pihat = pihat, muhat = muhat, qrisk = qrisk)
}
"srisk" <-
function(x,mu=.07,lambda=100000000,alpha=.1,eps=.0001){
n <- nrow(x)
p <- ncol(x)
X <- rbind(x,apply(x,2,mean))
y <- X[,1]
y[n+1] <- lambda*(y[n+1]-mu)
X <- X[,1]-X[,-1]
X <- cbind(c(rep(1,n),0),X)
X[n+1,] <- lambda*X[n+1,]
fit <- lm(y~X-1)
pihat <- c(1-sum(fit$coef[-1]),fit$coef[-1])
if(abs(fit$residual[n+1]) > eps) return("lambda too small?")
yhat <- x%*%pihat
muhat <- mean(x%*%pihat)
sigma <- sqrt(var(x%*%pihat))
list(pihat = pihat, muhat = muhat, sigma = sigma)
} |
expect_traces <- function(p, n.traces, name){
stopifnot(is.numeric(n.traces))
L <- expect_doppelganger_built(p, paste0("plotly-color-", name))
expect_equivalent(length(L$data), n.traces)
L
}
test_that("plot_ly() handles a simple scatterplot", {
p <- plot_ly(palmerpenguins::penguins, x = ~bill_length_mm, y = ~flipper_length_mm, color = ~bill_depth_mm)
})
test_that("Mapping a factor variable to color works", {
d <- palmerpenguins::penguins %>%
filter(!is.na(bill_length_mm))
p <- plot_ly(d, x = ~bill_length_mm, y = ~flipper_length_mm, color = ~species)
l <- expect_traces(p, 3, "scatterplot-color-factor")
markers <- lapply(l$data, "[[", "marker")
cols <- unlist(lapply(markers, "[[", "color"))
expect_equivalent(length(cols), 3)
})
test_that("Custom RColorBrewer pallette works for factor variable", {
d <- palmerpenguins::penguins %>%
filter(!is.na(bill_length_mm))
cols <- RColorBrewer::brewer.pal(9, "Set1")
colsToCompare <- toRGB(cols)
p <- plot_ly(d, x = ~bill_length_mm, y = ~flipper_length_mm, color = ~species,
colors = "Set1")
l <- expect_traces(p, 3, "scatterplot-color-factor-custom")
markers <- lapply(l$data, "[[", "marker")
colz <- unlist(lapply(markers, "[[", "color"))
idx <- if (packageVersion("scales") > '1.0.0') c(1, 2, 3) else c(1, 5, 9)
expect_identical(sort(colsToCompare[idx]), sort(colz))
p <- plot_ly(d, x = ~bill_length_mm, y = ~flipper_length_mm, color = ~species,
colors = cols[1:3])
l <- expect_traces(p, 3, "scatterplot-color-factor-custom2")
markers <- lapply(l$data, "[[", "marker")
colz <- unlist(lapply(markers, "[[", "color"))
expect_identical(sort(colsToCompare[1:3]), sort(colz))
})
test_that("Passing hex codes to colors argument works", {
colz <- c('
d <- data.frame(Category = LETTERS[1:5], Value = 1:5, stringsAsFactors = FALSE)
p <- plot_ly(d, x = ~Category, y = ~Value, type = "bar",
color = ~Category, colors = colz)
l <- expect_traces(p, 5, "bar-color-factor-custom")
colz2 <- sapply(l$data, function(x) x[["marker"]][["color"]])
expect_identical(sort(toRGB(colz)), sort(colz2))
})
test_that("Mapping a numeric variable to color works", {
d <- palmerpenguins::penguins %>%
filter(!is.na(bill_length_mm))
p <- plot_ly(d, x = ~bill_length_mm, y = ~flipper_length_mm, color = ~bill_depth_mm)
l <- expect_traces(p, 2, "scatterplot-color-numeric")
idx <- vapply(l$data, is.colorbar, logical(1))
markerScale <- l$data[[which(idx)]]$marker
markerDat <- l$data[[which(!idx)]]$marker
expect_true(all(markerDat$color == na.omit(palmerpenguins::penguins$bill_depth_mm)))
expect_true(markerScale$colorbar$title == "bill_depth_mm")
expect_true(min(na.omit(palmerpenguins::penguins$bill_depth_mm)) == markerScale$cmin)
expect_true(max(na.omit(palmerpenguins::penguins$bill_depth_mm)) == markerScale$cmax)
expect_true(all(0 <= markerScale$colorscale[,1] & markerScale$colorscale[,1] <= 1))
})
test_that("color/stroke mapping with box translates correctly", {
d <- data.frame(x = rep(c("A", "B"), each = 5), y = rnorm(10))
l <- plot_ly(d) %>%
add_boxplot(x = ~x, y = ~y, color = ~x, colors = c('A' = "blue", 'B' = "red"), stroke = I("black")) %>%
expect_traces(2, "box-color-stroke")
expect_true(l$data[[1]]$fillcolor == toRGB("blue", 0.5))
expect_true(l$data[[2]]$fillcolor == toRGB("red", 0.5))
expect_true(l$data[[1]]$line$color == toRGB("black"))
expect_true(l$data[[2]]$line$color == toRGB("black"))
})
test_that("Custom RColorBrewer pallette works for numeric variable", {
d <- palmerpenguins::penguins %>%
filter(!is.na(bill_length_mm))
p <- plot_ly(d, x = ~bill_length_mm, y = ~flipper_length_mm,
color = ~bill_depth_mm, colors = "Greens")
l <- expect_traces(p, 2, "scatterplot-color-numeric-custom")
})
test_that("axis titles get attached to scene object for 3D plots", {
d <- palmerpenguins::penguins %>%
filter(!is.na(bill_length_mm))
p <- plot_ly(d, x = ~bill_length_mm, y = ~bill_depth_mm, z = ~flipper_length_mm)
l <- expect_traces(p, 1, "scatterplot-scatter3d-axes")
expect_identical(l$data[[1]]$type, "scatter3d")
scene <- l$layout$scene
expect_true(scene$xaxis$title == "bill_length_mm")
expect_true(scene$yaxis$title == "bill_depth_mm")
expect_true(scene$zaxis$title == "flipper_length_mm")
})
test_that("Can specify a scale manually", {
pal <- c("1" = "red", "0" = "blue")
p <- plot_ly(mtcars, x = ~mpg, y = ~disp, color = ~factor(vs), colors = pal)
l <- expect_traces(p, 2, "color-manual")
markers <- lapply(l$data, "[[", "marker")
expected <- setNames(pal[sapply(l$data, "[[", "name")], NULL)
expect_equivalent(toRGB(expected), sapply(markers, "[[", "color"))
})
test_that("attributes are boxed-up correctly", {
df <- data.frame(
a = rnorm(5, 50, 1),
b = letters[1:5],
stringsAsFactors = FALSE
)
p <- plot_ly(df, x = ~a, y = ~b, color = ~b) %>%
add_bars(text = ~paste("Value: ", round(a, 1)), hoverinfo = "text")
l <- plotly_build(p)$x
expect_length(l$data, 5)
for (i in seq_along(l$data)) {
expect_is(l$data[[i]]$x, "AsIs")
expect_is(l$data[[i]]$y, "AsIs")
expect_length(l$data[[i]]$text, 1)
}
}) |
pairw.anova<-function(y,x,conf.level=0.95,method="tukey",MSE=NULL,df.err=NULL,control=NULL){
indices <- c("lsd","bonf","tukey","scheffe","dunnett")
method <- match.arg(method, indices)
if(method=="lsd"){
res <- lsdCI(y,x,conf.level=conf.level,MSE=MSE,df.err=df.err)}
if(method=="bonf"){
res <- bonfCI(y,x,conf.level=conf.level,MSE=MSE,df.err=df.err)}
if(method=="tukey"){
res <- tukeyCI(y,x,conf.level=conf.level,MSE=MSE,df.err=df.err)}
if(method=="scheffe"){
res <- scheffeCI(y,x,conf.level=conf.level,MSE=MSE,df.err=df.err)}
if(method=="dunnett"){
res <- dunnettCI(y,x,conf.level=conf.level,control=control)}
res
}
lsdCI<-function(y, x, conf.level = 0.95, MSE = NULL, df.err = NULL){
fitted<-tapply(y,factor(x),mean)
nis<-tapply(y,factor(x),length)
a<-anova(lm(y~factor(x)))
df.error<-ifelse(is.null(df.err),a$Df[length(a$Df)],df.err)
MSE<-ifelse(is.null(MSE),a$"Mean Sq"[length(a$"Mean Sq")],MSE)
dif.mat<-outer(fitted,fitted,"-")
diffs<-dif.mat[upper.tri(dif.mat)]
SE.diff.mat<-sqrt(MSE*outer(1/nis,1/nis,"+"))
SE.diff<-SE.diff.mat[upper.tri(SE.diff.mat)]
p.val<- 2*pt(abs(diffs/SE.diff),df.error,lower.tail=FALSE)
t<-qt(1-(1-conf.level)/2,df.error)
hwidths<-t*SE.diff
LSD<-round(qt(1-((1-conf.level)/2),df.error)*SE.diff,5)
Decision<- ifelse(abs(diffs)>LSD,"Reject H0","FTR H0")
val<-as.data.frame(cbind(LSD,round(diffs, 5),round(diffs-hwidths,5),round(diffs+hwidths,5),Decision,round(p.val,5)))
lvl<-outer(levels(x),levels(x),function(x1,x2){paste(paste("mu",x1,sep=""),paste("mu",x2,sep=""),sep="-")})
dimnames(val)<-list(lvl[upper.tri(lvl)],
c("LSD","Diff","Lower","Upper","Decision","Adj. p-value"))
head<-paste(paste(as.character(conf.level*100),"%",sep=""),c("LSD confidence intervals"))
res <- list()
res$head <- head
res$conf <- conf.level
comp <- outer(levels(x),levels(x),function(x1,x2){paste(x1, x2, sep="-")})
res$comp <- comp[upper.tri(comp)]
res$summary <- val
res$band <- cbind(diffs-hwidths, diffs+hwidths)
res$fitted <- fitted
res$x <- x
res$y <- y
res$method <- "Fisher LSD"
class(res)<-"pairw"
res
}
bonfCI<-function(y,x, conf.level=0.95,MSE=NULL,df.err=NULL){
fitted<-tapply(y,factor(x),mean)
nis<-tapply(y,factor(x),length)
a<-anova(lm(y~factor(x)))
df.error<-ifelse(is.null(df.err),a$Df[length(a$Df)],df.err)
MSE<-ifelse(is.null(MSE),a$"Mean Sq"[length(a$"Mean Sq")],MSE)
r<-length(fitted)
dif.mat<-outer(fitted,fitted,"-")
diffs<-dif.mat[upper.tri(dif.mat)]
SE.diff.mat<-sqrt(MSE*outer(1/nis,1/nis,"+"))
L.hat.SE<-SE.diff.mat[upper.tri(SE.diff.mat)]
p.val<- 2*pt(abs(diffs/L.hat.SE),df=df.error,lower.tail=FALSE)
p.adj<-ifelse(p.val*((r^2-r)/2)>=1,1,round(p.val*((r^2-r)/2),6))
t<-qt(1-(1-conf.level)/(r*(r-1)),df.error)
hwidths<-t*L.hat.SE
val<-round(cbind(diffs,diffs-hwidths,diffs+hwidths),5)
Decision<-ifelse((val[,2]>0&val[,3]>0)|val[,2]<0&val[,3]<0,"Reject H0","FTR H0")
val<-as.data.frame(cbind(val,Decision,p.adj))
lvl<-outer(levels(x),levels(x),function(x1,x2){paste(paste("mu",x1,sep=""),paste("mu",x2,sep=""),sep="-")})
dimnames(val)<-list(lvl[upper.tri(lvl)],
c("Diff","Lower","Upper","Decision","Adj. p-value"))
head<-paste(paste(as.character(conf.level*100),"%",sep=""),c("Bonferroni confidence intervals"))
res <- list()
res$head <- head
res$conf <- conf.level
comp <- outer(levels(x),levels(x),function(x1,x2){paste(x1, x2, sep="-")})
res$comp <- comp[upper.tri(comp)]
res$summary <- val
res$band <- cbind(diffs-hwidths, diffs+hwidths)
res$fitted <- fitted
res$x <- x
res$y <- y
res$method <- "Bonferroni"
class(res)<-"pairw"
res
}
tukeyCI<-function(y,x, conf.level=0.95,MSE=NULL,df.err=NULL){
fitted<-tapply(y,factor(x),mean)
nis<-tapply(y,factor(x),length)
a<-anova(lm(y~factor(x)))
df.error<-ifelse(is.null(df.err),a$Df[length(a$Df)],df.err)
MSE<-ifelse(is.null(MSE),a$"Mean Sq"[length(a$"Mean Sq")],MSE)
r<-length(fitted)
dif.mat<-outer(fitted,fitted,"-")
diffs<-dif.mat[upper.tri(dif.mat)]
SE.diff.mat<-sqrt(MSE*outer(1/nis,1/nis,"+"))
SE.diff<-SE.diff.mat[upper.tri(SE.diff.mat)]
Q.star<-abs((sqrt(2)*diffs)/ SE.diff)
p.val<-round(ptukey(Q.star,r,df=df.error,lower.tail=FALSE),6)
T<-qtukey(conf.level,r,df.error)/sqrt(2)
hwidths<-T*SE.diff
val<-round(cbind(diffs,diffs-hwidths,diffs+hwidths),5)
Decision<-ifelse((val[,2]>0&val[,3]>0)|val[,2]<0&val[,3]<0,"Reject H0","FTR H0")
val<-as.data.frame(cbind(val,Decision,p.val))
lvl<-outer(levels(x),levels(x),function(x1,x2){paste(paste("mu",x1,sep=""),paste("mu",x2,sep=""),sep="-")})
dimnames(val)<-list(lvl[upper.tri(lvl)],
c("Diff","Lower","Upper","Decision","Adj. p-value"))
head<-paste(paste(as.character(conf.level*100),"%",sep=""),c("Tukey-Kramer confidence intervals"))
res <- list()
res$head <- head
res$conf <- conf.level
comp <- outer(levels(x),levels(x),function(x1,x2){paste(x1, x2, sep="-")})
res$comp <- comp[upper.tri(comp)]
res$summary <- val
res$band <- cbind(diffs-hwidths, diffs+hwidths)
res$fitted <- fitted
res$x <- x
res$y <- y
res$method <- "Tukey HSD"
class(res)<-"pairw"
res
}
scheffeCI<-function(y,x, conf.level=0.95,MSE=NULL,df.err=NULL){
fitted<-tapply(y,factor(x),mean)
nis<-tapply(y,factor(x),length)
a<-anova(lm(y~factor(x)))
df.error<-ifelse(is.null(df.err),a$Df[length(a$Df)],df.err)
MSE<-ifelse(is.null(MSE),a$"Mean Sq"[length(a$"Mean Sq")],MSE)
r<-length(fitted)
dif.mat<-outer(fitted,fitted,"-")
diffs<-dif.mat[upper.tri(dif.mat)]
SE.diff.mat<-sqrt(MSE*outer(1/nis,1/nis,"+"))
SE.diff<-SE.diff.mat[upper.tri(SE.diff.mat)]
F.star<-diffs^2/((r-1)*SE.diff^2)
p.val<-round(pf(F.star,r-1,df.error,lower.tail=FALSE),6)
S<-sqrt((r-1)*qf(conf.level,r-1,df.error))
hwidths<-S*SE.diff
val<-round(cbind(diffs,diffs-hwidths,diffs+hwidths),5)
Decision<-ifelse((val[,2]>0&val[,3]>0)|val[,2]<0&val[,3]<0,"Reject H0","FTR H0")
val<-as.data.frame(cbind(val,Decision,p.val))
lvl<-outer(levels(x),levels(x),function(x1,x2){paste(paste("mu",x1,sep=""),paste("mu",x2,sep=""),sep="-")})
dimnames(val)<-list(lvl[upper.tri(lvl)],
c("Diff","Lower","Upper","Decision","Adj. P-value"))
head<-paste(paste(as.character(conf.level*100),"%",sep=""),c("Scheffe confidence intervals"))
res <- list()
res$head <- head
res$conf <- conf.level
comp <- outer(levels(x),levels(x),function(x1,x2){paste(x1, x2, sep="-")})
res$comp <- comp[upper.tri(comp)]
res$summary <- val
res$band <- cbind(diffs-hwidths, diffs+hwidths)
res$fitted <- fitted
res$x <- x
res$y <- y
res$method <- "Scheffe"
class(res)<-"pairw"
res
}
dunnettCI<-function(y, x, conf.level = 0.95, control = NULL){
x <- factor(x)
if(is.null(control)) stop(call. = FALSE, "Please specify the control")
nis <- tapply(y, x, length)
nu <- sum(nis) - nlevels(x)
p.sd <- function(y, x){
rs <- seq(1, nlevels(x))
for(i in levels(x)) rs[i] <- sum((y[x == i] - mean(y[x == i]))^2)
rs <- rs[-c(1:nlevels(x))]
sqrt(sum(rs)/nu)
}
s <- p.sd(y, x)
controlm <- mean(y[x == control])
fittedm <- tapply(y[x != control], factor(x)[x != control], mean)
fittedm <-fittedm[complete.cases(fittedm)]
controln <- length(y[x == control])
fittedn <- tapply(y[x != control], factor(x)[x != control], length)
fittedn <-fittedn[complete.cases(fittedn)]
diffs <- fittedm - controlm
Dj <- seq(1, (nlevels(x) - 1))
for(i in 1 : (nlevels(x)-1)) Dj[i] <- diffs[i]/(s*sqrt((1/fittedn[i]) + (1/controln)))
Rij <- seq(1, (nlevels(x) - 1))
for(i in 1 : (nlevels(x)-1)) Rij[i] <- sqrt(fittedn[i]/(fittedn[i] + controln))
R <- outer(Rij, Rij, "*")
diag(R) <- rep(1, (nlevels(x) - 1))
upper <- seq(1, (nlevels(x) - 1))
for(i in 1 : (nlevels(x)-1)) upper[i] <- diffs[i] + s*sqrt((1/fittedn[i])+ (1/controln))*qmvt((1 - (1 - conf.level)/2), df = nu, sigma = R, tail="lower.tail")$quantile
lower <- seq(1, (nlevels(x) - 1))
for(i in 1 : (nlevels(x)-1)) lower[i] <- diffs[i] - s*sqrt((1/fittedn[i])+ (1/controln))*qmvt((1 - (1 - conf.level)/2), df = nu, sigma = R, tail="lower.tail")$quantile
fl <- levels(x)[levels(x)!=control]
con <- levels(x)[levels(x)==control]
decision<-ifelse((lower>0&upper>0)|lower<0&upper<0,"Reject H0","FTR H0")
lvl <- paste(paste("mu", fl, sep=""),paste("mu", con, sep=""),sep="-")
val <- as.data.frame(cbind(round(apply(cbind(lower, upper), 1, mean), 6),round(lower, 6),round(upper, 6),decision))
dimnames(val)<-list(lvl,c("Diff","Lower","Upper","Decision"))
head<-paste(paste(as.character(conf.level*100),"%",sep=""),c("Dunnett confidence intervals"))
res <- list()
res$head <- head
res$conf <- conf.level
comp <- paste(fl, con, sep="-")
res$comp <- comp
res$summary <- val
res$band <- cbind(lower, upper)
res$fitted <- fittedm
res$x <- x
res$y <- y
method <- "Dunnett"
class(res)<-"pairw"
res
}
scheffe.cont <- function(y, x, lvl = c("x1", "x2"), conf.level = 0.95, MSE = NULL, df.err = NULL){
alpha <- 1 - conf.level
n <- length(y); x <- factor(x)
r <- nlevels(x)
Y.new <- y[x == lvl[1]|x ==lvl[2]]
X.new <- x[x == lvl[1]|x ==lvl[2]]
means <- tapply(Y.new, X.new, mean)
means <- means[complete.cases(means)]
ni <- tapply(Y.new, X.new, length)
ni <- ni[complete.cases(ni)]
D <- means[1] - means[2]
a<-anova(lm(y~factor(x)))
df.error<-ifelse(is.null(df.err),a$Df[length(a$Df)],df.err)
MSE<-ifelse(is.null(MSE),a$"Mean Sq"[length(a$"Mean Sq")],MSE)
S.D <- sqrt(MSE * ((1/ni[1])+(1/ni[2])))
S <- sqrt((r - 1)*qf(1 - alpha, r - 1, n - r))
CI <- list(lower = D - S.D * S, upper = D + S.D * S)
F.star <- D^2/((r - 1)*(S.D^2))
P.val <- pf(F.star, r - 1, n - r, lower.tail = FALSE)
Dec <- ifelse(P.val <= alpha, "Reject H0", "FTR H0")
res <- data.frame(Diff = D, Lower = CI$lower, Upper = CI$upper, Decision = Dec, P = P.val)
names(res) <- c("Diff", "Lower", "Upper", "Decision", "Adj. P-value")
row.names(res) <- paste("mu",lvl[1],"-","mu",lvl[2], sep = "")
res
}
bonf.cont <- function(y, x, lvl = c("x1", "x2"), conf.level = 0.95, MSE = NULL, df.err = NULL, comps = 1){
alpha <- 1 - conf.level
n <- length(y); x <- factor(x)
Y.new <- y[x == lvl[1]|x ==lvl[2]]
X.new <- x[x == lvl[1]|x ==lvl[2]]
means <- tapply(Y.new, X.new, mean)
means <- means[complete.cases(means)]
ni <- tapply(Y.new, X.new, length)
ni <- ni[complete.cases(ni)]
D <- means[1] - means[2]
a<-anova(lm(y~factor(x)))
df.error<-ifelse(is.null(df.err),a$Df[length(a$Df)],df.err)
MSE<-ifelse(is.null(MSE),a$"Mean Sq"[length(a$"Mean Sq")],MSE)
S.D <- sqrt(MSE * ((1/ni[1])+(1/ni[2])))
t.crit <- qt(1-(alpha/(2*comps)), df.error)
CI <- list(lower = D - S.D * t.crit, upper = D + S.D * t.crit)
P.val <- 2*pt(abs(D/S.D), df.error, lower.tail = FALSE)*comps
Dec <- ifelse(P.val <= alpha, "Reject H0", "FTR H0")
res <- data.frame(Diff = D, Lower = CI$lower, Upper = CI$upper, Decision = Dec, P = ifelse(P.val>1,1,P.val))
names(res) <- c("Diff", "Lower", "Upper", "Decision", "Adj. P-value")
row.names(res) <- paste("mu",lvl[1],"-","mu",lvl[2], sep = "")
res
}
print.pairw <- function(x, ...){
cat("\n")
cat(x$head,"\n")
cat("\n")
rq<-structure(x$summary)
print(rq)
invisible(x)
}
plot.pairw <- function(x, type = 1, lcol = 1, lty = NULL, lwd = NULL, cap.length = 0.1, xlab = "", main = NULL, explanation = TRUE, ...){
if(class(x)!="pairw") stop("Requires object of class pairw")
if(type == 1){
levels <- factor(names(x$fitted))
cont <- outer(levels, levels, function(x1,x2)paste(x1,x2,sep="-"))
cont1 <- cont[upper.tri(cont)]
dec <- x$summary$Decision
dec1 <- ifelse(dec=="FTR H0", FALSE, TRUE)
xlvl <- x$x
y <- x$y
names(dec1) <- cont1
lett <- multcompLetters(dec1)$Letters
bplot(y, xlvl, simlett = TRUE, lett = lett, xlab = xlab, ...)
if(explanation){
if(x$method == "kBonferroni"){
cat(paste("The true effects of factor levels with the same letter are not", "\n", "significantly different at alpha = ", 1- x$conf, " using the ", strsplit(x$method, "k")[[1]][2], " method.", "\n\n", sep = ""))
} else if (x$method == "mBonferroni"){
cat(paste("The true effects of factor levels in blocks with the same letter are not", "\n", "significantly different at alpha = ", 1- x$conf, " using the ", strsplit(x$method, "m")[[1]][2], " method.", "\n\n", sep = ""))
} else{
cat(paste("The population means of factor levels with the same letter are not", "\n", "significantly different at alpha = ", 1- x$conf, " using the ", x$method, " method.", "\n\n", sep = ""))
}
}
}
if(type == 2){
ci <- x$band
w <- diff(range(min(ci[,1]),max(ci[,2])))*.05
r <- nrow(x$summary)
b <- barplot(rep(0, r), names.arg = x$comp, main = ifelse(is.null(main), x$head, main), xlab = xlab, horiz = TRUE, xlim = c(min(ci[,1]) - w , max(ci[,2])), border=NA, axis.lty = 1, ...)
abline(h = b, col = "gray")
arrows(ci[,1], b, ci[,2], b, angle = 90, col = lcol, lty = lty, lwd = lwd, length = cap.length, code = 3)
abline(v=0, col="gray", lty=2)
points(apply(x$band,1,mean), b, pch = 19)
}
} |
sim_linked <- function(phy,
Q = rep(1, 6),
rate = 0.1,
node_mut_rate_double = 1e-9,
l = 1000,
bf = rep(0.25, 4),
rootseq = NULL,
node_time = 0.01) {
levels <- c("a", "c", "g", "t")
if (is.null(rootseq)) {
rootseq <- sample(levels, l, replace = TRUE, prob = bf)
}
if (length(rootseq) != l) {
stop(
"'rootseq' must have the same length as 'l'. \n",
"length 'rootseq': ", length(rootseq), " \n",
"value of 'l': ", l, " \n"
)
}
if (is.matrix(Q)) Q <- Q[lower.tri(Q)]
eig_q <- phangorn::edQt(Q, bf)
m <- length(levels)
phy <- stats::reorder(phy)
edge <- phy$edge
num_nodes <- max(edge)
parent <- as.integer(edge[, 1])
child <- as.integer(edge[, 2])
root <- as.integer(parent[!match(parent, child, 0)][1])
res <- matrix(NA, l, num_nodes)
res[, root] <- rootseq
parents <- sort(unique(as.integer(edge[, 1])))
assertthat::assert_that(parents[1] == root)
assertthat::assert_that(node_mut_rate_double >= 0)
node_transition_matrix <- make_transition_matrix(node_mut_rate_double)
eigen_obj <- eigen(node_transition_matrix, FALSE)
eigen_obj$inv <- solve.default(eigen_obj$vec)
branch_subs_all <- cbind(0, 0, rep(0, max(parents)))
node_subs_all <- cbind(0, 0, rep(0, max(parents)))
for (focal_parent in parents) {
offspring <- edge[which(parent == focal_parent), 2]
p_matrix <- get_p_matrix(node_time,
eig = eigen_obj,
rate = rate)
result <- get_mutated_sequences(res[, focal_parent],
p_matrix)
node_subs_1 <- sum(res[, focal_parent] != result[[1]])
node_subs_2 <- sum(res[, focal_parent] != result[[2]])
all_node_subs <- c(node_subs_1, node_subs_2)
indices <- which(parent == focal_parent)
for (i in 1:2) {
branch_length <- phy$edge.length[indices[i]]
P <- get_p_matrix(branch_length, eig_q, rate)
before_mut_seq <- result[[i]]
after_mut_seq <- c()
for (j in 1:m) {
ind <- before_mut_seq == levels[j]
after_mut_seq[ind] <- sample(levels, sum(ind), replace = TRUE,
prob = P[, j])
}
res[, offspring[i]] <- after_mut_seq
branch_subs <- sum(after_mut_seq != before_mut_seq)
from <- focal_parent
to <- offspring[i]
a <- which(edge[, 1] == from & edge[, 2] == to)
branch_subs_all[a, ] <- c(focal_parent, offspring[i], branch_subs)
node_subs_all[a, ] <- c(focal_parent, offspring[i], all_node_subs[i])
}
}
branch_subs_all <- branch_subs_all[-which(branch_subs_all[, 1] == 0), ]
node_subs_all <- node_subs_all[-which(node_subs_all[, 1] == 0), ]
updated_subs <- calc_accumulated_substitutions(phy,
branch_subs_all[, 3],
node_subs_all[, 3])
phy_no_extinct <- geiger::drop.extinct(phy)
k <- length(phy$tip.label)
label <- c(phy$tip.label, as.character((k + 1):num_nodes))
colnames(res) <- label
res <- res[, phy_no_extinct$tip.label, drop = FALSE]
alignment_phydat <- phyDat.DNA(as.data.frame(res, stringsAsFactors = FALSE))
output <- list("alignment" = alignment_phydat,
"root_seq" = rootseq,
"total_branch_substitutions" = updated_subs$total_branch_subs,
"total_node_substitutions" = updated_subs$total_node_subs,
"total_accumulated_substitutions" =
updated_subs$total_accumulated_substitutions)
return(output)
} |
trans_phased <- function(n_alleles, annotate = FALSE) {
eg <- cbind(rep(1:n_alleles, each = n_alleles),
rep(1:n_alleles, times = n_alleles))
f <- function(x) { return(paste(x, collapse = "|")) }
geno.list <- apply(eg, 1, f)
ng <- length(geno.list)
geno.list
ng - n_alleles^2
trans <- matrix(0, ng^2, ng)
gm.list <- rep("", ng^2)
gf.list <- rep("", ng^2)
for (gm in 1:ng) {
for (gf in 1:ng) {
am.list <- strsplit(geno.list[gm], "|", fixed = TRUE)[[1]]
af.list <- strsplit(geno.list[gf], "|", fixed = TRUE)[[1]]
geno.off <- function(am, af) {
go <- paste(c(am, af), collapse = "|")
return(which(geno.list == go))
}
for (i in 1:2) {
for (j in 1:2) {
go <- geno.off(am.list[i], af.list[j])
trans[ng * gm + gf - ng, go] <- trans[ng * gm + gf - ng, go] + 0.25
}
}
gm.list[ng * gm + gf - ng] <- geno.list[gm]
gf.list[ng * gm + gf - ng] <- geno.list[gf]
}
}
if (annotate) {
trans <- data.frame(trans)
trans <- data.frame(gm = gm.list, gf = gf.list, trans)
names(trans)[3:ncol(trans)] <- geno.list
}
return(trans)
} |
regmed.edges <- function(fit, type="mediators", eps = 1e-3) {
if(type != "mediators" && type != "any"){
stop("unknown type of edges to select")
}
alpha <- fit$alpha
beta <- fit$beta
delta <- fit$delta
df <- NULL
if(type=="mediators"){
df <- cbind(alpha, beta, alpha*beta)
keep <- abs(df[,3]) > eps
med.keep <- rownames(df[keep,, drop=FALSE])
if(sum(keep) > 0) {
df1 <- data.frame(Vertex1=colnames(alpha), Vertex2=med.keep, coef=alpha[keep])
df2 <- data.frame(Vertex1=med.keep, Vertex2 = colnames(beta), coef=beta[keep])
df <- rbind(df1, df2)
if(abs(delta) > eps) {
df3 <- data.frame(Vertex1 = colnames(alpha), Vertex2=colnames(beta),
coef=delta)
df <- rbind(df, df3)
rownames(df) <- NULL
}
}
}
if(type == "any"){
df1 <- data.frame(Vertex1=colnames(alpha), Vertex2=rownames(alpha), coef=alpha[,1])
which <- abs(alpha) > eps
if(any(which)){
df <- df1[which,,drop=FALSE]
}
df2 <- data.frame(Vertex1=rownames(beta), Vertex2=colnames(beta), coef=beta[,1])
which <- abs(beta) > eps
if(any(which)){
df <- rbind(df, df2 <- df2[which,,drop=FALSE])
rownames(df) <- NULL
}
if(abs(delta) > eps){
df3 <- data.frame(Vertex1=colnames(alpha), Vertex2=colnames(beta), coef=delta)
df <- rbind(df, df3)
rownames(df) <- NULL
}
}
y.name <- colnames(beta)
med.name <- rownames(alpha)
obj <- list(edges = df, y.name=y.name, med.name=med.name)
class(obj) <- c("regmed.edges", "list")
return(obj)
} |
plot.ICA.BinCont <- function(x, Xlab, Main=" ", Type="Percent", Labels=FALSE, ...){
if (missing(Xlab)) {Xlab <- expression(R[H]^2)}
Object <- x
dev.new()
if (Type=="Density"){
plot(density(x$R2_H, na.rm = T), xlab=Xlab, ylab="Density", main=Main, lwd=2)
}
if (Type=="Freq"){
h <- hist(Object$R2_H, plot = FALSE, ...)
h$density <- h$counts/sum(h$counts)
cumulMidPoint <- ecdf(x=Object$R2_H)(h$mids)
labs <- paste(round((1-cumulMidPoint), digits=4)*100, "%", sep="")
if (Labels==FALSE){
plot(h,freq=T, xlab=Xlab, ylab="Frequency", main=Main, col="grey")
}
if (Labels==TRUE){
plot(h,freq=T, xlab=Xlab, ylab="Frequency", main=Main, labels=labs, col="grey")
}
}
if (Type=="Percent"){
h <- hist(Object$R2_H, plot = FALSE, ...)
h$density <- h$counts/sum(h$counts)
cumulMidPoint <- ecdf(x=Object$R2_H)(h$mids)
labs <- paste(round((1-cumulMidPoint), digits=4)*100, "%", sep="")
if (Labels==FALSE){
plot(h, freq=F, xlab=Xlab, ylab="Percentage", main=Main, col="grey")
}
if (Labels==TRUE){
plot(h, freq=F, xlab=Xlab, ylab="Percentage", main=Main, labels=labs, col="grey")
}
}
if (Type=="CumPerc"){
h <- hist(Object$R2_H, breaks=length(Object$R2_H), plot = FALSE, ...)
h$density <- h$counts/sum(h$counts)
cumulative <- cumsum(h$density)
plot(x=h$mids, y=cumulative, xlab=Xlab, ylab="Cumulative percentage", col=0, main=Main)
lines(x=h$mids, y=cumulative)
}
}
|
"drone_blades" |
require("tfplot")
if(identical(as.logical(Sys.getenv("_R_CHECK_HAVE_FAME_")), TRUE)) {
require("TSfame")
cat("************** connecting testFame.db\n")
con <- TSconnect("fame", dbname="testFame.db")
cat("************** examples\n")
seriesA <- tis(1:24, start = c(2002, 1), freq = 12)
seriesNames(seriesA) <- "seriesA"
seriesA2 <- tis(rnorm(24), start = c(2002, 1), freq = 12)
seriesNames(seriesA2) <- "seriesA2"
seriesB <- tis(rnorm(104), start = c(2002, 1), tif = "wmonday")
seriesNames(seriesB) <- "seriesB"
seriesC <- tis(rnorm(104), start = c(2002, 1), tif = "wfriday")
seriesNames(seriesC) <- "seriesC"
start(seriesC)
TSdoc(seriesB) <- paste("Line", 1:4, "of seriesB documentation", collapse="\n")
TSdescription(seriesB) <- "seriesB description"
cat("******* cleanup to db\n")
if( TSexists("seriesA", con)) TSdelete("seriesA", con)
if( TSexists("seriesA2", con)) TSdelete("seriesA2", con)
if( TSexists("seriesB", con)) TSdelete("seriesB", con)
if( TSexists("seriesC", con)) TSdelete("seriesC", con)
if( TSexists("tsseries", con)) TSdelete("tsseries", con)
if( TSexists("tsseriesM1", con)) TSdelete("tsseriesM1", con)
if( TSexists("tsseriesM2", con)) TSdelete("tsseriesM2", con)
if( TSexists(c("tsseriesM1", "tsseriesM2"), con))
TSdelete(c("tsseriesM1", "tsseriesM2"), con)
cat("******* write to db\n")
if(!TSput(seriesA, con)) stop("TSput seriesA error.")
if(!TSput(seriesA2, con)) stop("TSput seriesA2 error.")
if(!TSput(seriesB, con)) stop("TSput seriesB error.")
if(!TSreplace(seriesB, con)) stop("TSreplace seriesB error.")
tsseries <- ts(rnorm(30), start=c(1999,2), frequency=12)
seriesNames(tsseries) <- "tsseries"
if(!TSput(tsseries, con)) stop("TSput tsseries error.")
tsseriesM <- ts(matrix(rnorm(60), 30,2), start=c(1999,2), frequency=12)
seriesNames(tsseriesM) <- c("tsseriesM1","tsseriesM2")
if(!TSput(tsseriesM, con)) stop("TSput tsseriesM error.")
cat("******* read from db\n")
z <- TSget("tsseries", con)
if(max(abs(c(z) - c(tsseries))) > 1e-15) stop("TSget tsseries error.")
if(any(start(z) != c(1999,2))) stop("TSget tsseries start error.")
if(any(start(TSdates("tsseries", con))[[1]] != c(1999,2)))
stop("TSdates tsseries start error.")
z <- TSget(c("tsseriesM1","tsseriesM2"), con)
if(max(abs(c(z) - c(tsseriesM))) > 1e-15) stop("TSget tsseriesM error.")
if(any(start(z) != c(1999,2))) stop("TSget tsseriesM start error.")
if(any(start(TSdates(c("tsseriesM1","tsseriesM2"), con))[[1]] != c(1999,2)))
if(any(start(TSdates(seriesNames(tsseriesM), con))[[1]] != c(1999,2)))
stop("TSdates tsseriesM start error.")
a <- TSget("seriesA", con)
if(max(abs(c(a) - c(seriesA))) > 1e-15) stop("TSget seriesA error.")
if(any(start(TSdates("seriesA", con))[[1]] != c(2002, 1)))
stop("TSget seriesA start error.")
if(!TSexists("seriesA", con)) stop("TSget seriesA exists error.")
if( TSexists("seriesZ", con)) stop("TSget seriesZ !exists error.")
a2 <- TSget("seriesA2", con)
if(max(abs(c(a2) - c(seriesA2))) > 1e-15) stop("TSget seriesA2 error.")
z <- TSget(c("seriesA","seriesA2"), con)
tfplot(z)
b <- TSget("seriesB", con, TSrepresentation="zoo")
if(max(abs(c(b) - c(seriesB))) > 1e-15) stop("TSget seriesB error.")
if(as.Date(start(b))!= "2002-01-07") stop("seriesB start date error.")
if(weekdays(start(seriesB)) != weekdays(start(b)))stop("seriesB weekdays error.")
if(weekdays(start(b)) != "Monday") stop("seriesB start weekdays error.")
if(weekdays(start(b)) != weekdays(end(b))) stop("seriesB weekdays error.")
tfplot(b)
tframe(seriesB)
tfwindow(seriesB, tf=NULL)
bi <- TSget("seriesB", con, TSrepresentation="tis")
if(max(abs(c(bi) - c(seriesB))) > 1e-15) stop("TSget bi error.")
if(base::as.Date(start(bi))!= "2002-01-07") stop("bi start date error.")
if(weekdays(start(seriesB)) != weekdays(start(bi)))stop("bi weekdays error.")
if(weekdays(start(bi)) != "Monday") stop("bi start weekdays error.")
if(weekdays(start(bi)) != weekdays(end(bi))) stop("bi weekdays error.")
tfplot(bi)
cat("******* documentation from db\n")
if(TSdoc("seriesB", con) != TSdoc(seriesB)) stop("TSdoc error.")
if(TSdescription("seriesB", con) != TSdescription(seriesB))
stop("TSdescription error.")
cat("******* TSdates from db\n")
TSdates("seriesB", con)
TSdates(c("seriesA","seriesA2","seriesB"), con)
cat("******* delete from db\n")
TSdelete("seriesB", con)
if(!TSput(seriesC, con)) stop("TSput seriesC error.")
if( TSput(seriesC, con)) stop("TSput seriesC error overwriting.")
ci <- TSget("seriesC", con, TSrepresentation="tis")
start(ci)
start(bi)
cat("******* timeSeries representation\n")
ci <- TSget("seriesC", con, TSrepresentation="timeSeries")
if("timeSeries" != class(ci)) stop("timeSeries class object not returned.")
start(ci)
start(bi)
cat("******* misc\n")
TSdates("seriesA", con)
if(base::as.Date(start(seriesC))!= "2002-01-04") stop("seriesC start date error.")
if(weekdays(start(seriesC)) != "Friday") stop("seriesC start weekdays error.")
if(weekdays(start(seriesC)) != weekdays(end(seriesC))) stop("seriesC weekdays error.")
cat("************** disconnecting test\n")
dbDisconnect(con)
} else cat("FAME not available. Skipping tests.") |
verify_SingleGrainData <- function(
object,
threshold = 10,
cleanup = FALSE,
cleanup_level = 'aliquot',
verbose = TRUE,
plot = FALSE
){
if(is(object, "list")){
results <- .warningCatcher(lapply(1:length(object), function(x) {
verify_SingleGrainData(
object = object[[x]],
threshold = threshold,
cleanup = cleanup,
cleanup_level = cleanup_level,
verbose = verbose,
plot = plot
)
}))
if(cleanup){
return(results)
}else{
return(merge_RLum(results))
}
}
if(is(object, "Risoe.BINfileData")){
temp.results_matrix <- lapply(X = object@DATA, FUN = function(x){
c(mean(x), var(x))
})
temp.results_matrix <- do.call(rbind, temp.results_matrix)
temp.results_matrix_RATIO <- temp.results_matrix[,2]/temp.results_matrix[,1]
temp.results_matrix_VALID <- temp.results_matrix_RATIO > threshold
selection <- data.frame(
POSITION = object@METADATA$POSITION,
GRAIN = object@METADATA$GRAIN,
MEAN = temp.results_matrix[, 1],
VAR = temp.results_matrix[, 2],
RATIO = temp.results_matrix_RATIO,
THRESHOLD = rep_len(threshold, length(object@DATA)),
VALID = temp.results_matrix_VALID
)
unique_pairs <- unique(
selection[selection[["VALID"]], c("POSITION", "GRAIN")])
if(cleanup_level == "aliquot"){
selection_id <- sort(unlist(lapply(1:nrow(unique_pairs), function(x) {
which(
.subset2(selection, 1) == .subset2(unique_pairs, 1)[x] &
.subset2(selection, 2) == .subset2(unique_pairs, 2)[x]
)
})))
}else{
selection_id <- which(selection[["VALID"]])
}
if(cleanup){
object@DATA <- object@DATA[selection_id]
object@METADATA <- object@METADATA[selection_id,]
object@METADATA$ID <- 1:length(object@DATA)
selection_id <- paste(selection_id, collapse = ", ")
if(verbose){
cat(paste0("\n[verify_SingleGrainData()] Risoe.BINfileData object reduced to records: \n", selection_id))
cat("\n\n[verify_SingleGrainData()] Risoe.BINfileData object record index reset.")
}
return_object <- object
}else{
return_object <- set_RLum(
class = "RLum.Results",
data = list(
unique_pairs = unique_pairs,
selection_id = selection_id,
selection_full = selection),
info = list(call = sys.call())
)
}
}else if(is(object,"RLum.Analysis")){
object_list <- lapply(get_RLum(object), function(x){
x@data[,2]
})
temp.results_matrix <- lapply(X = object_list, FUN = function(x){
c(mean(x), var(x))
})
temp.results_matrix <- do.call(rbind, temp.results_matrix)
temp.results_matrix_RATIO <- temp.results_matrix[,2]/temp.results_matrix[,1]
temp.results_matrix_VALID <- temp.results_matrix_RATIO > threshold
temp_structure <- structure_RLum(object, fullExtent = TRUE)
if (object@originator == "Risoe.BINfileData2RLum.Analysis") {
selection <- data.frame(
POSITION = temp_structure$info.POSITION,
GRAIN = temp_structure$info.GRAIN,
MEAN = temp.results_matrix[, 1],
VAR = temp.results_matrix[, 2],
RATIO = temp.results_matrix_RATIO,
THRESHOLD = rep_len(threshold, length(object_list)),
VALID = temp.results_matrix_VALID
)
unique_pairs <- unique(
selection[selection[["VALID"]], c("POSITION", "GRAIN")])
} else if (object@originator == "read_XSYG2R") {
selection <- data.frame(
POSITION = if(any(grepl(pattern = "position", names(temp_structure)))){
temp_structure$info.position}else{
NA
},
GRAIN = NA,
MEAN = temp.results_matrix[, 1],
VAR = temp.results_matrix[, 2],
RATIO = temp.results_matrix_RATIO,
THRESHOLD = rep_len(threshold, length(object_list)),
VALID = temp.results_matrix_VALID
)
unique_pairs <- unique(
selection[["POSITION"]][selection[["VALID"]]])
} else{
stop("[verify_SingleGrainData()] I don't know what to do object 'originator' not supported!",
call. = FALSE)
}
if(cleanup_level == "aliquot") {
if (object@originator == "read_XSYG2R") {
if(!is.na(unique_pairs)){
selection_id <-
sort(unlist(lapply(1:nrow(unique_pairs), function(x) {
which(.subset2(selection, 1) == .subset2(unique_pairs, 1)[x])
})))
}else{
selection_id <- NA
}
} else if (object@originator == "Risoe.BINfileData2RLum.Analysis") {
selection_id <-
sort(unlist(lapply(1:nrow(unique_pairs), function(x) {
which(
.subset2(selection, 1) == .subset2(unique_pairs, 1)[x] &
.subset2(selection, 2) == .subset2(unique_pairs, 2)[x]
)
})))
}
if(length(selection_id) == 0) selection_id <- NA
} else{
selection_id <- which(selection[["VALID"]])
}
if(cleanup && !any(is.na(selection_id))){
if(verbose){
selection_id_text <- paste(selection_id, collapse = ", ")
cat(paste0("\n[verify_SingleGrainData()] RLum.Analysis object reduced to records: ",
selection_id_text))
}
if (length(selection_id) == 0) {
object <- set_RLum(
class = "RLum.Analysis",
originator = object@originator,
protocol = object@protocol,
records = list(),
info = list(
unique_pairs = unique_pairs,
selection_id = selection_id,
selection_full = selection)
)
} else{
object <- set_RLum(
class = "RLum.Analysis",
records = get_RLum(object, record.id = selection_id, drop = FALSE),
info = list(
unique_pairs = unique_pairs,
selection_id = selection_id,
selection_full = selection)
)
}
return_object <- object
}else{
if(any(is.na(selection_id))){
warning("[verify_SingleGrainData()] selection_id is NA, nothing removed, everything selected!",
call. = FALSE)
}
return_object <- set_RLum(
class = "RLum.Results",
data = list(
unique_pairs = unique_pairs,
selection_id = selection_id,
selection_full = selection),
info = list(call = sys.call())
)
}
}else{
stop(paste0("[verify_SingleGrainData()] Input type '", is(object)[1], "' is not allowed for this function!"), call. = FALSE)
}
if(plot){
plot(
NA,
NA,
xlim = c(1,nrow(selection)),
ylim = range(selection[["RATIO"]]),
log = "y",
xlab = "Record index",
ylab = "Calculated ratio [a.u.]",
main = "Record selection"
)
points(x = which(selection[["VALID"]]),
y = selection[["RATIO"]][selection[["VALID"]]], pch = 20, col = "darkgreen")
points(x = which(!selection[["VALID"]]),
y = selection[["RATIO"]][!selection[["VALID"]]], pch = 20, col = rgb(0,0,0,0.5))
abline(h = threshold, col = "red", lty = 1, lwd = 2)
mtext(
side = 3,
text = paste0(
"(total: ", nrow(selection),
" | valid: ", length(which(selection[["VALID"]])),
" | invalid: ", length(which(!selection[["VALID"]])), ")"),
cex = 0.9 * par()$cex)
}
return(return_object)
} |
duncan<-function (y, trt, DFerror, SSerror, alpha = 0.05, group = TRUE, main = NULL)
{
MSerror <- SSerror/DFerror
name.y <- paste(deparse(substitute(y)))
name.t <- paste(deparse(substitute(trt)))
junto <- subset(data.frame(y, trt), is.na(y) == FALSE)
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.err = sds[, 2]/sqrt(nn[, 2]),
replication = nn[, 2])
names(means)[1:2] <- c(name.t, name.y)
ntr <- nrow(means)
k.snk<-ntr-1
Tprob <- vector(mode="integer",k.snk)
kk <- 1
for (kk in 1:k.snk) {
alphap=1-(1-alpha)^((kk+1)-1)
Tprob[kk] <- qtukey(1 - alphap, kk+1, DFerror)
}
p.nan<-as.vector(na.action(na.omit(Tprob)))[1]
ult<-p.nan-1
if(ntr==50) Tprob[p.nan:length(Tprob)]<-seq(Tprob[ult],3.61,length=length(Tprob)-ult)
if(ntr==100) Tprob[p.nan:length(Tprob)]<-seq(Tprob[ult],3.67,length=length(Tprob)-ult)
nr <- unique(nn[, 2])
nfila <- c("Alpha", "Error Degrees of Freedom", "Error Mean Square")
nfila1 <- c("Distances between averages", "Critical Value of Studentized Range")
nvalor <- c(alpha, DFerror, MSerror)
nvalor1 <- rbind(t(seq(2,ntr)),t(Tprob))
xtabla <- data.frame(...... = nvalor)
xtabla1 <- data.frame(...... = nvalor1)
row.names(xtabla) <- nfila
row.names(xtabla1) <- nfila1
HSD <- vector(mode="integer",k.snk)
if (group) {
if (length(nr) == 1) {
kk <- 1
for (kk in 1:k.snk) {
HSD[kk] <- Tprob[kk] * sqrt(MSerror/nr)
}
}
else {
nr1 <- 1/mean(1/nn[, 2])
kk <- 1
for (kk in 1:k.snk) {
HSD[kk] <- Tprob[kk] * sqrt(MSerror/nr1)
}
}
cat("\nTeste de Duncan \n------------------------------------------------------------------------")
cat("\nGrupos Tratamentos Medias\n")
output <- order.stat.SNK(means[, 1], means[, 2], HSD)
cat('------------------------------------------------------------------------\n')
}
}
order.stat.SNK<-function (treatment, means, minimum)
{
n <- length(means)
letras<-letters
if(n>26) {
l<-floor(n/26)
for(i in 1:l) letras<-c(letras,paste(letters,i,sep=''))
}
z <- data.frame(treatment, means)
w <- z[order(z[, 2], decreasing = TRUE), ]
M <- rep("", n)
k <- 1
k1 <- 0
j <- 1
i <- 1
r <- 1
cambio <- n
cambio1 <- 0
chequeo = 0
M[1] <- letras[k]
while (j < n) {
chequeo <- chequeo + 1
if (chequeo > n)
break
for (i in j:n) {
if (abs(j-i) == 0) {r<-1} else {r<-abs(j-i)}
s <- abs(w[i, 2] - w[j, 2]) <= minimum[r]
if (s) {
if (lastC(M[i]) != letras[k])
M[i] <- paste(M[i], letras[k], sep = "")
}
else {
k <- k + 1
cambio <- i
cambio1 <- 0
ja <- j
for (jj in cambio:n) M[jj] <- paste(M[jj], " ",
sep = "")
M[cambio] <- paste(M[cambio], letras[k], sep = "")
for (v in ja:cambio) {
if (abs(v-cambio) == 0) {r<-1} else {r<-abs(v-cambio)}
if (abs(w[v, 2] - w[cambio, 2]) > minimum[r]) {
j <- j + 1
cambio1 <- 1
}
else break
}
break
}
}
if (cambio1 == 0)
j <- j + 1
}
w <- data.frame(w, stat = M)
trt <- as.character(w$treatment)
means <- as.numeric(w$means)
for (i in 1:n) {
cat(M[i], "\t", trt[i], "\t ", means[i], "\n")
}
output <- data.frame(trt, means, M)
return(output)
} |
LogIntegratedGaussianLikelihood <- function(suf, prior) {
n <- suf$n
if (n > 0) {
ybar <- suf$sum / n
} else {
ybar <- 0
}
if (n > 1) {
sample.variance <- (suf$sumsq - n * ybar^2) / (n - 1)
} else {
sample.variance <- 0
}
kappa <- prior$mu.guess.weight
mu0 <- prior$mu.guess
df <- prior$sigma.prior$prior.df
ss <- prior$sigma.prior$prior.guess^2 * df
posterior.mean <- (n * ybar + kappa * mu0) / (n + kappa)
DF <- df + n
SS <- ss + (n - 1) * sample.variance + n * (ybar - posterior.mean)^2 +
kappa * (mu0 - posterior.mean)^2
return( - .5 * n * log(2 * pi) + .5 * log(kappa / (n + kappa)) +
lgamma(DF/2) - lgamma(df / 2) +
.5 * df * log(ss / 2) - .5 * DF * log(SS / 2))
} |
test_that("input_requirement works with correct dimensions", {
set.seed(200100)
X <- matrix(rnorm(100), nrow = 10)
d <- rnorm(10)
out <- input_requirement(X,d)
expect_equal(dim(out), c(10,10))
})
test_that("input_requirement fails with incorrect dimensions (non-square X)", {
set.seed(200100)
X <- matrix(rnorm(110), nrow = 10, ncol = 11)
d <- rnorm(10)
expect_error(input_requirement(X,d))
})
test_that("input_requirement fails with incorrect dimensions (d different than dimensions of X)", {
set.seed(200100)
X <- matrix(rnorm(100), nrow = 10)
d <- rnorm(11)
expect_error(input_requirement(X,d))
})
test_that("augmented_input_requirement works with correct dimensions", {
set.seed(200100)
X <- matrix(rnorm(100), nrow = 10)
w <- rnorm(10)
c <- rnorm(10)
d <- rnorm(10)
out <- augmented_input_requirement(X,w,c,d)
expect_equal(dim(out), c(11,11))
})
test_that("augmented_input_requirement fails with incorrect dimensions (non-square X)", {
set.seed(200100)
X <- matrix(rnorm(110), nrow = 10, ncol = 11)
w <- rnorm(10)
c <- rnorm(10)
d <- rnorm(10)
expect_error(augmented_input_requirement(X,w,c,d))
})
test_that("augmented_input_requirement fails with incorrect dimensions (d different than dimensions of X)", {
set.seed(200100)
X <- matrix(rnorm(100), nrow = 10)
w <- rnorm(10)
c <- rnorm(10)
d <- rnorm(11)
expect_error(augmented_input_requirement(X,w,c,d))
})
test_that("output_allocation works with correct dimensions", {
set.seed(200100)
X <- matrix(rnorm(100), nrow = 10)
d <- rnorm(10)
out <- output_allocation(X,d)
expect_equal(dim(out), c(10,10))
})
test_that("output_allocation fails with incorrect dimensions (non-square X)", {
set.seed(200100)
X <- matrix(rnorm(110), nrow = 10, ncol = 11)
d <- rnorm(10)
expect_error(output_allocation(X,d))
})
test_that("output_allocation fails with incorrect dimensions (d different than dimensions of X)", {
set.seed(200100)
X <- matrix(rnorm(100), nrow = 10)
d <- rnorm(11)
expect_error(output_allocation(X,d))
})
test_that("leontief_inverse works with correct dimensions", {
set.seed(200100)
A <- matrix(rnorm(100), nrow = 10)
out <- leontief_inverse(A)
expect_equal(dim(out), c(10,10))
})
test_that("leontief_inverse fails with incorrect dimensions (non-square X)", {
set.seed(200100)
A <- matrix(rnorm(110), nrow = 10, ncol = 11)
expect_error(leontief_inverse(A))
}) |
contourPlot2 <- function(data,
x = "x",
y = "y",
z = "z",
domain = NULL,
background = NULL,
underlayer = NULL,
overlayer = NULL,
legend = NULL,
levels = NULL,
size = 0.,
fill = TRUE,
tile = FALSE,
transparency = 0.75,
colors = NULL,
bare = FALSE) {
if (isTRUE(tile)) {
fill <- FALSE
bare <- FALSE
size <- 0.
}
data <- data[, c(x, y, z)]
vars <- c(x, y, z)
for (i in seq_along(vars)) {
if (!is.numeric(data[[vars[i]]])) {
data[[vars[i]]] <- as.numeric(data[[vars[i]]])
}
}
colnames(data) <- c("x", "y", "z")
if (missing(domain)) {
xmin <- min(data$x)
xmax <- max(data$x)
ymin <- min(data$y)
ymax <- max(data$y)
nx <- 5
ny <- 5
} else {
xmin <- domain[1]
xmax <- domain[2]
ymin <- domain[3]
ymax <- domain[4]
nx <- domain[5]
ny <- domain[6]
}
if (requireNamespace("openair", quietly = TRUE)) {
lgndname <- openair::quickText(legend, auto.text = TRUE)
} else {
lgndname <- legend
}
if (is.null(levels)) {
if (is.null(colors)) {
nlevels <- 7
} else {
nlevels <- length(colors)
}
levels <- pretty(range(data$z, na.rm = TRUE), n = nlevels, min.n = 4)
}
nlevels <- length(levels)
if (levels[1] >= 0) {
levels <- append(levels, Inf)
nlevels <- length(levels)
}
prettyLevels <- prettyNum(levels)
lab_levels <- paste(prettyLevels[1:(nlevels - 1)], "\U2013",
prettyLevels[2:nlevels])
if (levels[nlevels] == Inf & !isTRUE(tile)) {
lab_levels[nlevels - 1] <- paste("\U2265", prettyLevels[nlevels - 1])
} else if (levels[nlevels] == Inf & isTRUE(tile)) {
lab_levels[nlevels - 1] <- paste("\U2265", prettyLevels[nlevels - 1])
}
if (levels[1] == -Inf) {
lab_levels[1] <- paste("<", prettyLevels[2])
}
if (is.null(colors)) {
myPalette <- grDevices::colorRampPalette(
rev(RColorBrewer::brewer.pal(11, name = "Spectral")))
myColors <- myPalette(nlevels)
myColors <- myColors[2:length(myColors)]
myColorsLines <- cbind(myColors, "black")
} else {
myPalette <- grDevices::colorRampPalette(colors, alpha = TRUE)
myColors <- myPalette(length(levels) - 1)
myColorsLines <- cbind(myColors, "black")
}
img <- matrix(data = NA, nrow = 10, ncol = 10)
gimg <- grid::rasterGrob(img, interpolate = FALSE)
if (!missing(background)) {
if (requireNamespace("magick", quietly = TRUE)) {
img <- magick::image_read(background)
gimg <- grid::rasterGrob(img)
} else {
warning("Missing magick package. Please install it to be able to read background basemap.")
}
}
if (missing(underlayer)) {
underlayer <- geom_blank()
}
if (missing(overlayer)) {
overlayer <- geom_blank()
}
if (isFALSE(fill) & size == 0) {
size <- 0.5
}
if (isTRUE(tile)) {
size <- 0.
}
v <- ggplot(data) +
annotation_custom(gimg, -Inf, Inf, -Inf, Inf) +
underlayer
if (isTRUE(tile)) {
v <- v +
geom_raster(aes(x = x, y = y,
fill = cut(z, breaks = levels, right = FALSE)),
alpha = transparency) +
scale_fill_manual(lgndname,
drop = FALSE,
guide = guide_legend(reverse = TRUE),
labels = lab_levels,
values = myColors)
}
if (isTRUE(fill)) {
v <- v +
geom_contour_filled(aes(x = x, y = y, z = z,
fill = stat(level)),
breaks = levels,
size = 0,
alpha = transparency) +
scale_fill_manual(lgndname,
drop = FALSE,
guide = guide_legend(reverse = TRUE),
labels = lab_levels,
values = myColors)
}
if (size != 0) {
lineLevels <- levels
if (levels[length(levels)] == "Inf") {
lineLevels <- levels[1:length(levels) - 1]
}
v <- v +
geom_contour(aes(x = x,
y = y,
z = z,
colour = factor(stat(level))),
breaks = lineLevels,
size = size,
linejoin = "round",
lineend = "round",
alpha = 1.,
show.legend = isFALSE(fill)) +
scale_color_manual(lgndname,
drop = FALSE,
limits = factor(lineLevels),
guide = guide_legend(reverse = TRUE),
values = myColorsLines)
}
v <- v +
scale_x_continuous(breaks = seq(xmin, xmax, length.out = nx),
labels = myCoordsLabels,
expand = c(0, 0)) +
scale_y_continuous(breaks = seq(ymin, ymax, length.out = ny),
labels = myCoordsLabels,
expand = c(0, 0)) +
labs(x = "x [m]", y = "y [m]") +
overlayer +
coord_fixed(ratio = 1,
xlim = c(xmin, xmax),
ylim = c(ymin, ymax)) +
theme_bw(base_size = 10,
base_family = "sans") +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
if (isTRUE(bare)) {
v <- v + theme(axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
legend.position = "none",
panel.background = element_blank(),
panel.border = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
plot.background = element_blank())
}
return(v)
} |
wilcoxonPairedRC = function (x, g=NULL,
zero.method="Wilcoxon",
ci=FALSE, conf=0.95, type="perc",
R=1000, histogram=FALSE, digits=3,
verbose=FALSE, ... ){
if(is.factor(g)==F){g=factor(g)}
x = x[as.numeric(g)<3]
g = g[as.numeric(g)<3]
g = droplevels(g)
X1 = x[as.numeric(g)==1]
X2 = x[as.numeric(g)==2]
if(length(X1)!=length(X2)){stop("Groups not the same length", call.=FALSE)}
Diff = X1 - X2
Diff2 = abs(Diff)
if(zero.method=="none")
{RR = -1 * rank(Diff2) * sign(Diff)}
if(zero.method=="Pratt")
{R = -1 * rank(Diff2) * sign(Diff)
RR = R[R!=0]}
if(zero.method=="Wilcoxon")
{Diff = Diff[Diff!=0]
Diff2 = Diff2[Diff2!=0]
RR = -1 * rank(Diff2) * sign(Diff)
}
Rplus = sum(RR[RR>0])
Rminus = sum(abs(RR[RR<0]))
Tee = min(Rplus, Rminus)
n = length(RR)
if(Rplus>=Rminus){
RC = -4 * abs((Tee - (Rplus + Rminus)/2) / n / (n+1))}
if(Rplus<Rminus){
RC = 4 * abs((Tee - (Rplus + Rminus)/2) / n / (n+1))}
RC = signif(RC, digits=digits)
if(verbose)
{
cat("\n")
cat("Levels:",levels(g))
cat("\n")
cat("zero.method:", zero.method)
cat("\n")
cat("n kept", "=", length(RR))
cat("\n")
cat("Ranks plus", "=", Rplus)
cat("\n")
cat("Ranks minus", "=", Rminus)
cat("\n")
cat("T value =", Tee)
cat("\n")
cat("\n")
}
if(ci==TRUE){
Data = data.frame(x1=x[as.numeric(g)==1], x2=x[as.numeric(g)==2])
Function = function(input, index){
Input = input[index,]
Diff = Input$x1 - Input$x2
Diff2 = abs(Diff)
if(zero.method=="none")
{RR = -1 * rank(Diff2) * sign(Diff)}
if(zero.method=="Pratt")
{R = -1 * rank(Diff2) * sign(Diff)
RR = R[R!=0]}
if(zero.method=="Wilcoxon")
{Diff = Diff[Diff!=0]
Diff2 = Diff2[Diff2!=0]
RR = -1 * rank(Diff2) * sign(Diff)
}
Rplus = sum(RR[RR>0])
Rminus = sum(abs(RR[RR<0]))
Tee = min(Rplus, Rminus)
n = length(RR)
if(Rplus>=Rminus){
RC = -4 * abs((Tee - (Rplus + Rminus)/2) / n / (n+1))}
if(Rplus<Rminus){
RC = 4 * abs((Tee - (Rplus + Rminus)/2) / n / (n+1))}
return(RC)
}
Boot = boot(Data, Function, R=R)
BCI = boot.ci(Boot, conf=conf, type=type)
if(type=="norm") {CI1=BCI$normal[2]; CI2=BCI$normal[3]}
if(type=="basic"){CI1=BCI$basic[4]; CI2=BCI$basic[5]}
if(type=="perc") {CI1=BCI$percent[4]; CI2=BCI$percent[5]}
if(type=="bca") {CI1=BCI$bca[4]; CI2=BCI$bca[5]}
CI1=signif(CI1, digits=digits)
CI2=signif(CI2, digits=digits)
if(histogram==TRUE){hist(Boot$t[,1], col = "darkgray", xlab="rc",
main="")}
}
if(ci==FALSE){names(RC)="rc"; return(RC)}
if(ci==TRUE){DF=data.frame(rc=RC, lower.ci=CI1, upper.ci=CI2)
rownames(DF) = 1:nrow(DF)
return(DF)
}
} |
predict.bn.fit = function(object, node, data, method = "parents", ...,
prob = FALSE, debug = FALSE) {
check.data(data, allow.levels = TRUE)
check.nodes(nodes = node, graph = object, max.nodes = 1)
check.prediction.method(method, data)
check.logical(debug)
check.logical(prob)
if (prob && !is(object, c("bn.fit.dnet", "bn.fit.onet", "bn.fit.donet")))
stop("prediction probabilities are only available for discrete networks.")
extra.args = list(...)
check.unused.args(extra.args, prediction.extra.args[[method]])
if (method == "parents") {
check.fit.vs.data(fitted = object, data = data,
subset = object[[node]]$parents)
if (is(object, c("bn.fit.dnet", "bn.fit.onet", "bn.fit.donet")))
discrete.prediction(node = node, fitted = object, data = data,
prob = prob, debug = debug)
else if (is(object, "bn.fit.gnet"))
gaussian.prediction(node = node, fitted = object, data = data,
debug = debug)
else if (is(object, "bn.fit.cgnet"))
mixedcg.prediction(node = node, fitted = object, data = data,
debug = debug)
}
else if (method == "bayes-lw") {
if (is.null(extra.args$from))
extra.args$from = intersect(setdiff(names(data), node), names(object))
else
check.nodes(nodes = extra.args$from, graph = object, min.nodes = 1)
if (node %in% extra.args$from)
stop("node ", node, " is both a predictor and being predicted.")
check.fit.vs.data(fitted = object, data = data, subset = extra.args$from)
if (is.null(extra.args$n))
extra.args$n = 500
else if (!is.positive.integer(extra.args$n))
stop("the number of observations to be sampled must be a positive integer number.")
map.prediction(node = node, fitted = object, data = data, n = extra.args$n,
from = extra.args$from, prob = prob, debug = debug)
}
}
predict.bn.naive = function(object, data, prior, ..., prob = FALSE, debug = FALSE) {
check.data(data, allowed.types = discrete.data.types, allow.levels = TRUE)
if (is(object, "bn.naive"))
check.bn.naive(object)
else
check.bn.tan(object)
check.logical(debug)
check.logical(prob)
if (is(object, "bn"))
fitted = bn.fit(object, data)
else
fitted = object
training = attr(fitted, "training")
check.fit.vs.data(fitted = fitted, data = data,
subset = setdiff(names(fitted), training))
check.unused.args(list(...), character(0))
prior = check.classifier.prior(prior, fitted[[training]])
naive.classifier(training = training, fitted = fitted, data = data,
prior = prior, prob = prob, debug = debug)
}
predict.bn.tan = predict.bn.naive |
mcrals <- function(x, ncomp,
cont.constraints = list(),
spec.constraints = list(),
spec.ini = matrix(runif(ncol(x) * ncomp), ncol(x), ncomp),
cont.forced = matrix(NA, nrow(x), ncomp),
spec.forced = matrix(NA, ncol(x), ncomp),
cont.solver = mcrals.nnls,
spec.solver = mcrals.nnls,
exclrows = NULL, exclcols = NULL, verbose = FALSE,
max.niter = 100, tol = 10^-6, info = "") {
stopifnot("Parameter 'max.niter' should be positive." = max.niter > 0)
if (any(spec.ini < 0)) {
warning("Initial estimation of pure spectra has negative numbers, it can cause problems.")
}
x <- prepCalData(x, exclrows, exclcols, min.nrows = 2, min.ncols = 2)
stopifnot("Number of rows in 'cont.forced' should be the same as number of rows in 'x'." = nrow(cont.forced) == nrow(x))
stopifnot("Number of columns in 'cont.forced' should be the same as 'ncomp'." = ncol(cont.forced) == ncomp)
stopifnot("Number of rows in 'spec.forced' should be the same as number of columns in 'x'." = nrow(spec.forced) == ncol(x))
stopifnot("Number of columns in 'spec.forced' should be the same as 'ncomp'." = ncol(cont.forced) == ncomp)
model <- mcrals.cal(
x, ncomp,
cont.constraints = cont.constraints,
spec.constraints = spec.constraints,
spec.ini = spec.ini,
cont.forced = cont.forced,
spec.forced = spec.forced,
cont.solver = cont.solver,
spec.solver = spec.solver,
max.niter = max.niter,
tol = tol,
verbose = verbose
)
model$variance <- getVariance.mcr(model, x)
class(model) <- c("mcr", "mcrals")
model$call <- match.call()
model$info <- info
return(model)
}
predict.mcrals <- function(object, x, ...) {
attrs <- mda.getattr(x)
Ct <- object$cont.solver(x, object$resspec)
Ct <- mda.setattr(Ct, attrs, "rows")
return(Ct)
}
print.mcrals <- function(x, ...) {
cat("\nMCRALS unmixing case (class mcrals)\n")
if (length(x$info) > 1) {
cat("\nInfo:\n")
cat(x$info)
}
cat("\n\nCall:\n")
print(x$call)
cat("\nMajor model fields:\n")
cat("$ncomp - number of calculated components\n")
cat("$resspec - matrix with resolved spectra\n")
cat("$rescons - matrix with resolved concentrations\n")
cat("$expvar - vector with explained variance\n")
cat("$cumexpvar - vector with cumulative explained variance\n")
cat("$info - case info provided by user\n")
}
summary.mcrals <- function(object, ...) {
cat("\nSummary for MCR ALS case (class mcrals)\n")
if (length(object$info) > 1) {
fprintf("\nInfo:\n%s\n", object$info)
}
if (length(object$exclrows) > 0) {
fprintf("Excluded rows: %d\n", length(object$exclrows))
}
if (length(object$exclcols) > 0) {
fprintf("Excluded coumns: %d\n", length(object$exclcols))
}
cat("\nConstraints for spectra:\n")
if (length(object$spec.constraints) > 0) {
cat(paste(" - ", sapply(object$spec.constraints, function(x) x$name), collapse = "\n"))
cat("\n")
} else {
cat(" - none\n\n")
}
cat("\nConstraints for contributions:\n")
if (length(object$cont.constraints) > 0) {
cat(paste(" - ", sapply(object$cont.constraints, function(x) x$name), collapse = "\n"))
cat("\n")
} else {
cat(" - none\n\n")
}
cat("\n")
out <- round(t(object$variance[1:2, ]), 2)
rownames(out) <- colnames(object$variance)
colnames(out) <- c("Expvar", "Cumexpvar")
show(out)
}
mcrals.cal <- function(D, ncomp, cont.constraints, spec.constraints, spec.ini,
cont.forced, spec.forced, cont.solver, spec.solver, max.niter, tol, verbose) {
attrs <- mda.getattr(D)
exclrows <- attrs$exclrows
exclcols <- attrs$exclcols
nobj <- nrow(D)
nvar <- ncol(D)
colind <- seq_len(nvar)
rowind <- seq_len(nobj)
if (!is.null(exclrows)) {
D <- D[-exclrows, , drop = FALSE]
rowind <- rowind[-exclrows]
}
if (!is.null(exclcols)) {
D <- D[, -exclcols, drop = FALSE]
spec.ini <- spec.ini[-exclcols, , drop = FALSE]
colind <- colind[-exclcols]
}
totvar <- sum(D^2)
var <- 0
if (verbose) {
cat(sprintf("\nStarting iterations (max.niter = %d):\n", max.niter))
}
cont.forced.ind <- !is.na(cont.forced)
spec.forced.ind <- !is.na(spec.forced)
St <- spec.ini
for (i in seq_len(max.niter)) {
Ct <- tryCatch(
cont.solver(D, St),
error = function(e) {
stop("Unable to resolve the components, perhaps 'ncomp' is too large or initial estimates for spectra are not good enough.", call. = FALSE)
}
)
if (any(cont.forced.ind)) {
Ct[cont.forced.ind] <- cont.forced[cont.forced.ind]
}
for (cc in cont.constraints) {
Ct <- employ.constraint(cc, x = Ct, d = D)
}
St <- tryCatch(
spec.solver(D, Ct),
error = function(e) {
stop("Unable to resolve the components, perhaps 'ncomp' is too large or initial estimates for spectra are not good enough.", call. = FALSE)
}
)
if (any(spec.forced.ind)) {
St[spec.forced.ind] <- spec.forced[spec.forced.ind]
}
for (sc in spec.constraints) {
St <- employ.constraint(sc, x = St, d = D)
}
if (verbose) {
cat(sprintf("Iteration %4d, R2 = %.6f\n", i, var))
}
var_old <- var
var <- tryCatch(
1 - sum((D - tcrossprod(cont.solver(D, St), St))^2) / totvar,
error = function(e) {
print(e)
stop("Unable to resolve the components, perhaps 'ncomp' is too large.\n
or initial estimates for spectra are not good enough.", call. = FALSE)
}
)
if ( (var - var_old) < tol) {
if (verbose) cat("No more improvements.\n")
break
}
}
Ct <- tryCatch(
cont.solver(D, St),
error = function(e) {
print(e)
stop("Unable to resolve the components, perhaps 'ncomp' is too large.\n
or initial estimates for spectra are not good enough.", call. = FALSE)
}
)
cont <- matrix(0, nobj, ncomp)
cont[rowind, ] <- Ct
spec <- matrix(0, ncomp, nvar)
spec[, colind] <- t(St)
rownames(spec) <- colnames(cont) <- paste("Comp", seq_len(ncomp))
cont <- mda.setattr(cont, attrs, "row")
spec <- mda.setattr(spec, attrs, "col")
if (is.null(attr(cont, "yaxis.name"))) attr(cont, "yaxis.name") <- "Observations"
attr(cont, "name") <- "Resolved contributions"
attr(spec, "name") <- "Resolved spectra"
return(
list(
ncomp = ncomp,
rescont = cont,
resspec = mda.t(spec),
cont.constraints = cont.constraints,
spec.constraints = spec.constraints,
cont.solver = cont.solver,
spec.colver = spec.solver,
max.niter = max.niter
)
)
}
mcrals.ols <- function(D, A) {
if (ncol(D) != nrow(A)) D <- t(D)
return(D %*% (A %*% solve(crossprod(A))))
}
mcrals.nnls <- function(D, A,
tol = 10 * .Machine$double.eps * as.numeric(sqrt(crossprod(A[, 1]))) * nrow(A)) {
if (nrow(D) != nrow(A)) D <- t(D)
nvar <- ncol(D)
ncomp <- ncol(A)
itmax <- 30 * ncomp
B <- matrix(0, nvar, ncomp)
for (v in seq_len(nvar)) {
d <- D[, v, drop = FALSE]
nz <- rep(0, ncomp)
wz <- nz
p <- rep(FALSE, ncomp)
z <- rep(TRUE, ncomp)
b <- nz
E <- d - A %*% b
w <- t(A) %*% E
iter <- 0
while (any(z) && any(w[z] > tol)) {
b.hat <- nz
wz[p] <- -Inf
wz[z] <- w[z]
t <- which.max(wz)
p[t] <- TRUE
z[t] <- FALSE
b.hat[p] <- mcrals.ols(d, A[, p, drop = FALSE])
while (any(b.hat[p] <= 0)) {
iter <- iter + 1
if (iter > itmax) {
return(b.hat)
}
q <- (b.hat <= 0) & p
alpha <- min(b[q]/(b[q] - b.hat[q]))
b <- b + alpha * (b.hat - b)
z <- ((abs(b) < tol) & p) | z
p <- !z
b.hat <- nz
b.hat[p] <- mcrals.ols(d, A[, p, drop = FALSE])
}
b <- b.hat
E <- d - A %*% b
w <- crossprod(A, E)
}
B[v, ] <- b
}
return(B)
}
mcrals.fcnnls <- function(D, A,
tol = 10 * .Machine$double.eps * as.numeric(sqrt(crossprod(A[, 1]))) * nrow(A)) {
ind2sub <- function(size, ind) {
return(list(
r = ((ind - 1) %% size[1]) + 1,
c = floor((ind - 1) / size[1]) + 1
))
}
sub2ind <- function(size, r, c) {
return((c - 1) * size[1] + r)
}
cssls <- function(AtD, AtA, P.set = NULL) {
if (is.null(P.set) || length(P.set) == 0 || all(P.set)) {
return(solve(AtA, AtD))
}
B <- matrix(0, nrow(AtD), ncol(AtD))
ncomp <- nrow(P.set)
nvar <- ncol(P.set)
codedPset <- (2^((ncomp - 1):0)) %*% P.set
sortedEset <- order(codedPset)
sortedPset <- codedPset[sortedEset]
breaks <- diff(sortedPset)
breakIdx <- c(0, which(breaks > 0), nvar)
for (k in seq_len(length(breakIdx) - 1)) {
cols2solve <- sortedEset[(breakIdx[k] + 1) : breakIdx[k+1]]
vars <- P.set[, sortedEset[breakIdx[k] + 1]]
B[vars, cols2solve] <- solve(
AtA[vars, vars, drop = FALSE],
AtD[vars, cols2solve, drop = FALSE]
)
}
return(B)
}
if (nrow(D) != nrow(A)) D <- t(D)
nvar <- ncol(D)
ncomp <- ncol(A)
nobj <- nrow(A)
W <- matrix(0, ncomp, nvar)
iter <- 0
maxiter <- 3 * ncomp
AtA <- crossprod(A)
AtD <- crossprod(A, D)
B <- cssls(AtD, AtA)
P.set <- B > 0
B[!P.set] <- 0
B.hat <- B
F.set <- which(!apply(P.set, 2, all))
while (length(F.set) != 0) {
B[, F.set] <- cssls(AtD[, F.set, drop = FALSE], AtA, P.set[, F.set, drop = FALSE])
H.set <- F.set[which(apply(B[, F.set, drop = FALSE] < 0, 2, any))]
nHset <- length(H.set)
if (nHset > 0) {
while (length(H.set) != 0 && (iter < maxiter)) {
iter <- iter + 1
alpha <- matrix(Inf, ncomp, nHset)
nvInd <- which(P.set[, H.set, drop = FALSE] & (B[, H.set, drop = FALSE] < 0),
arr.ind = TRUE)
nvR <- nvInd[, 1]
nvC <- nvInd[, 2]
hIdx <- sub2ind(dim(alpha), nvR, nvC)
bIdx <- sub2ind(dim(B), nvR, H.set[nvC])
alpha[hIdx] <- B.hat[bIdx] / (B.hat[bIdx] - B[bIdx])
alphaMin <- apply(alpha, 2, min)
alphaMinIdx <- apply(alpha, 2, which.min)
alpha <- matrix(alphaMin, ncomp, nHset, byrow = TRUE)
B.hat[, H.set] <- B.hat[, H.set] - alpha * (B.hat[, H.set] - B[, H.set])
idx2zero <- sub2ind(dim(B.hat), alphaMinIdx, H.set)
B.hat[idx2zero] <- 0
P.set[idx2zero] <- FALSE
B[, H.set] <- cssls(AtD[, H.set, drop = FALSE], AtA, P.set[, H.set, drop = FALSE])
H.set <- which(apply(B < 0, 2, any))
nHset <- length(H.set)
}
}
W[, F.set] <- AtD[, F.set, drop = FALSE] - AtA %*% B[, F.set, drop = FALSE]
J.set <- apply(((!P.set[, F.set, drop = FALSE]) * W[, F.set, drop = FALSE]) <= 0, 2, all)
F.set <- F.set[!J.set]
if (length(F.set) > 0) {
mxidx <- apply((!P.set[, F.set, drop = FALSE]) * W[, F.set, drop = FALSE], 2, which.max)
P.set[sub2ind(c(ncomp, nvar), mxidx, F.set)] <- TRUE
B.hat[, F.set] <- B[, F.set]
}
if (iter == maxiter) {
warning("Maximum number of iterations is reached, quit with current solution.")
return(t(B))
}
}
return(t(B))
} |
library( "urbin" )
ela8a <- urbinElaInt( allCoef = c( 0.33, 0.22, 0.05, 0.6 ),
allXVal = c( 1, 0.4, 0.12, 0.13 ),
xPos = c( 2, 0, 3, 4 ),
xBound = c( 0, 500, 1000, 1500, Inf ),
model = "logit" )
ela8a
ela8b <- urbinElaInt( allCoef = c( 0.33, 0.22, 0.05, 0.6 ),
allXVal = c( 1, 0.4, 0.12, 0.13 ),
xPos = c( 2, 0, 3, 4 ),
xBound = c( 0, 500, 1000, 1500, Inf ),
allCoefVcov = c( 0.003, 0.045, 0.007, 0.009 ),
model = "logit" )
ela8b
ela9a <- urbinElaInt( allCoef = c( 0.2, 0.3, 0.5, -0.2, 0.03, 0.6 ),
allXVal = c( 1, 0.4, 0.12 ),
xPos = c( 2, 0, 3 ),
xBound = c( 0, 500, 1000, Inf ), yCat = 2,
model = "mlogit" )
ela9a
ela9b <- urbinElaInt( allCoef = c( 0.2, 0.3, 0.5, -0.2, 0.03, 0.6 ),
allXVal = c( 1, 0.4, 0.12 ),
xPos = c( 2, 0, 3 ),
xBound = c( 0, 500, 1000, Inf ), yCat = 2,
allCoefVcov = c( 0.003, 0.045, 0.007, 0.009, 0.0008, 0.9 ),
model = "mlogit" )
ela9b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.