code
stringlengths 1
13.8M
|
---|
MediaDistancia=function(Distancias,n,Normatizar=TRUE){
Distancias2=vector("list", length(Distancias))
for(i in 1:length(Distancias)){
if(class(Distancias[[i]])=="Distancia"){
Distancias2[[i]]=as.matrix(Distancias[[i]]$Distancia)
}
if(class(Distancias[[i]])!="Distancia"){
Distancias2[[i]]=as.matrix(Distancias[[i]])
}}
Distancias=Distancias2
if(Normatizar==TRUE){
for(i in 1:length(Distancias)){
Distancias[[i]]=(Normatiza(Distancias[[i]],Metodo = 2))
}
}
for(i in 1:length(Distancias)){
Distancias[[i]]=Distancias[[i]]*n[i]
}
Dist=Distancias[[i]]*0
for(i in 1:length(Distancias)){
Dist=Dist+Distancias[[i]]/sum(n)
}
as.dist(Dist)
} |
plotEAF = function(opt.paths, xlim = NULL, ylim = NULL, ...) {
requirePackages("eaf", why = "plotEAF")
assertList(opt.paths, min.len = 1L, types = "list", names = "unique")
if (!is.null(xlim)) {
assertNumeric(xlim, len = 2L)
}
if (!is.null(ylim)) {
assertNumeric(ylim, len = 2L)
}
algos = names(opt.paths)
y.names = NULL
minimize = NULL
data = data.frame()
for (i in seq_along(algos)) {
a = algos[i]
runs = opt.paths[[i]]
assertList(runs, types = "OptPath", min.len = 1L)
fronts = lapply(seq_along(runs), function(j) {
run = runs[[j]]
df = as.data.frame(getOptPathParetoFront(run), stringsAsFactors = TRUE)
cns = colnames(df)
if (length(cns) != 2L) {
stopf("Must always have 2 objectives in opt path. But found: %i", length(cns))
}
if (i == 1L && j == 1L) {
y.names <<- cns
minimize <<- run$minimize
}
if (!all(y.names == cns)) {
stopf("Must always have the same 2 objectives in opt path: %s (first ones taken). But found here: %s",
collapse(y.names), collapse(cns))
}
if (!all(minimize == run$minimize)) {
stopf("Must always have the same 'minimize' settings for objectives in opt path: %s (first one taken).
But found here: %s", collapse(minimize), collapse(run$minimize))
}
cbind(df, .algo = a, .repl = j, stringsAsFactors = TRUE)
})
fronts = do.call(rbind, fronts)
data = rbind(data, fronts)
}
yn1 = y.names[1L]
yn2 = y.names[2L]
f = as.formula(sprintf("%s + %s ~ .repl", yn1, yn2))
defaults = list(
xlab = yn1, ylab = yn2,
percentiles = 50,
col = c("darkgrey", "darkgrey", "darkgrey", "black", "black", "black"),
lty = c("solid", "dashed", "dotdash", "solid", "dashed", "dotdash")
)
args = list(...)
args = insert(defaults, args)
args$data = data
args$groups = quote(.algo)
args$maximise = !minimize
args$xlim = xlim
args$ylim = ylim
do.call(eaf::eafplot, c(list(f), args))
return(data)
} |
supported_currencies <- function(max_attempts = 3) {
validate_arguments(arg_max_attempts = max_attempts)
url <- build_get_request(
base_url = "https://api.coingecko.com",
path = c("api", "v3", "simple", "supported_vs_currencies"),
query_parameters = NULL
)
supported_currencies <- api_request(
url = url,
max_attempts = max_attempts
)
return(unlist(supported_currencies))
} |
tidy_list <- function(x, id.name= "id", content.name = "content",
content.attribute.name = 'attribute', ...){
if (is.data.frame(x[[1]])){
tidy_list_df(x = x, id.name = id.name)
} else {
if (is.atomic(x[[1]])){
tidy_list_vector(x = x, id.name = id.name,
content.name = content.name,
content.attribute.name = content.attribute.name
)
} else {
stop("`x` must be a list of `data.frame`s or atomic `vector`s")
}
}
}
tidy_list_df <- function (x, id.name = "id"){
if (is.null(names(x))) {
names(x) <- seq_along(x)
}
list.names <- rep(names(x), sapply2(x, nrow))
x <- lapply(x, data.table::as.data.table)
x[['fill']] <- TRUE
out <- data.frame(list.names, do.call(rbind, x),
row.names = NULL, check.names = FALSE, stringsAsFactors = FALSE)
colnames(out)[1] <- id.name
data.table::data.table(out)
}
tidy_list_vector <- function(x, id.name = "id",
content.attribute.name = 'attribute', content.name = "content"){
if (is.null(names(x))) {
names(x) <- seq_along(x)
}
if (all(!sapply2(x, function(y) is.null(names(y))))){
tidy_list(
lapply(x, tidy_vector, content.attribute.name , content.name ),
id.name
)
} else {
dat <- data.frame(
rep(names(x), sapply2(x, length)),
unlist(x, use.names = FALSE),
stringsAsFactors = FALSE,
check.names = FALSE,
row.names = NULL
)
colnames(dat) <- c(id.name, content.name)
data.table::data.table(dat)
}
} |
context('corrgrapher working properly for explainers')
options(check.attributes = FALSE)
set.seed(2020)
custom_values <- data.frame(label = colnames(dragons)[-5],
value = rep(15, ncol(dragons) - 1),
stringsAsFactors = FALSE)
custom_values <- custom_values[order(custom_values$label),]
rownames(custom_values) <- NULL
model_pd_list <- list(numerical = model_pd)
test_that(
'Function is working properly with just necessary arguments',{
expect_is(corrgrapher(simple_model_exp),'corrgrapher')
expect_is(corrgrapher(tit_model_exp),'corrgrapher')
}
)
test_that('Values argument working', {
expect_equal({
df <- corrgrapher(model_exp,
values = custom_values,
partial_dependency = model_pd_list)[['nodes']][, c('label', 'value')]
df[order(df$label),]
},
custom_values)})
test_that('Values argument overrides feature_importance_*',{
expect_warning(
cgr <- corrgrapher(
model_exp,
values = custom_values,
feature_importance = model_fi,
partial_dependency = model_pd_list
)
)
expect_equal({
df <- cgr[['nodes']][, c('label', 'value')]
df <- df[order(df$label), ]
rownames(df) <- NULL
df
},
custom_values)
expect_warning(
cgr <- corrgrapher(
model_exp,
values = custom_values,
feature_importance = list(),
partial_dependency = model_pd_list
)
)
expect_equal({
df <- cgr[['nodes']][,c('label','value')]
df <- df[order(df$label),]
rownames(df) <- NULL
df
},
custom_values)
})
test_that("Output type",{
expect_is(cgr_exp, 'corrgrapher')
expect_true(all(c("nodes", "edges", "pds") %in% names(cgr_exp)))
}) |
context("method subscript")
test_that("get by index", {
init_data()
expect_equal(pm_first[1, 1], p(1, 1, 2))
expect_equal(pm_first[2, 1], p(0, 3, 1))
expect_equal(pm_first[1, 2], p(1, 0, 4))
expect_equal(pm_first[2, 2], 2)
expect_equal(m_first[1, 1], 3)
expect_equal(m_first[2, 1], 7)
expect_equal(m_first[1, 2], 0)
expect_equal(m_first[2, 2], 1)
})
test_that("get all", {
init_data()
expect_equal(pm_first[,], pm_first)
expect_equal(m_first[,], m_first)
})
test_that("get by sequnce", {
init_data()
expect_equal(pm_first[c(1, 3), c(1, 3)],
polyMatrix(matrix(c(1, 0, 1, 3, 2, 0,
3, 1, 0, 0, 0, 0), 2, 6, byrow = TRUE),
2, 2, 2))
expect_equal(pm_first[c(3, 1), c(3, 1)],
polyMatrix(matrix(c(1, 3, 0, 0, 0, 0,
0, 1, 3, 1, 0, 2), 2, 6, byrow = TRUE),
2, 2, 2))
expect_equal(pm_first[c(3, 1, 3), c(3, 1, 3)],
polyMatrix(matrix(c(1, 3, 1, 0, 0, 0, 0, 0, 0,
0, 1, 0, 3, 1, 3, 0, 2, 0,
1, 3, 1, 0, 0, 0, 0, 0, 0), 3, 9, byrow = TRUE),
3, 3, 2))
expect_equal(pm_first[c(3, 1), 1],
polyMatrix(matrix(c(3, 0, 0,
1, 1, 2), 2, 3, byrow = TRUE),
2, 1, 2))
expect_equal(pm_first[1, c(3, 1)],
polyMatrix(matrix(c(0, 1, 3, 1, 0, 2), 1, 6), 1, 2, 2))
expect_equal(m_first[c(1, 3), c(1, 3)],
matrix(c(3, 2, 4, 8), 2, 2, byrow = TRUE))
expect_equal(m_first[c(3, 1), c(3, 1)],
matrix(c(8, 4, 2, 3), 2, 2, byrow = TRUE))
expect_equal(m_first[c(3, 1, 3), c(3, 1, 3)],
matrix(c(8, 4, 8, 2, 3, 2, 8, 4, 8), 3, 3, byrow = TRUE))
expect_equal(m_first[c(3, 1), 1], c(4, 3))
expect_equal(m_first[1, c(3, 1)], c(2, 3))
})
test_that("get by logic", {
init_data()
expect_equal(pm_first[c(TRUE, FALSE, FALSE), c(TRUE, FALSE, FALSE)], p(1, 1, 2))
expect_equal(pm_first[c(FALSE, TRUE, FALSE), c(TRUE, FALSE, FALSE)], p(0, 3, 1))
expect_equal(pm_first[c(TRUE, FALSE, FALSE), c(FALSE, TRUE, FALSE)], p(1, 0, 4))
expect_equal(pm_first[c(FALSE, TRUE, FALSE), c(FALSE, TRUE, FALSE)], 2)
expect_equal(pm_first[c(TRUE, FALSE), c(TRUE, FALSE)],
polyMatrix(matrix(c(1, 0, 1, 3, 2, 0,
3, 1, 0, 0, 0, 0), 2, 6, byrow = TRUE),
2, 2, 2))
expect_equal(pm_first[c(FALSE, TRUE), c(TRUE, FALSE)],
polyMatrix(matrix(c(0, 0, 3, 0, 1, 0), 1, 6, byrow = TRUE),
1, 2, 2))
expect_equal(pm_first[c(TRUE, FALSE), c(FALSE, TRUE)],
polyMatrix(matrix(c(1, 0, 4,
0, 0, 6), 2, 3, byrow = TRUE),
2, 1, 2))
expect_equal(pm_first[c(FALSE, TRUE), c(FALSE, TRUE)], 2)
expect_equal(pm_first[TRUE, TRUE], pm_first)
expect_equal(m_first[c(TRUE, FALSE, FALSE), c(TRUE, FALSE, FALSE)], 3)
expect_equal(m_first[c(FALSE, TRUE, FALSE), c(TRUE, FALSE, FALSE)], 7)
expect_equal(m_first[c(TRUE, FALSE, FALSE), c(FALSE, TRUE, FALSE)], 0)
expect_equal(m_first[c(FALSE, TRUE, FALSE), c(FALSE, TRUE, FALSE)], 1)
expect_equal(m_first[c(TRUE, FALSE), c(TRUE, FALSE)],
matrix(c(3, 2, 4, 8), 2, 2, byrow = TRUE))
expect_equal(m_first[c(FALSE, TRUE), c(TRUE, FALSE)], c(7, 0))
expect_equal(m_first[c(TRUE, FALSE), c(FALSE, TRUE)], c(0, 2))
expect_equal(m_first[c(FALSE, TRUE), c(FALSE, TRUE)], 1)
expect_equal(m_first[TRUE, TRUE], m_first)
})
test_that("row access", {
init_data()
expect_equal(pm_first[1,],
polyMatrix(matrix(c(1, 1, 0, 1, 0, 3, 2, 4, 0), 1, 9, byrow = TRUE),
1, 3, 2))
expect_equal(pm_first[c(3, 1),],
polyMatrix(matrix(c(3, 0, 1, 0, 0, 0, 0, 6, 0,
1, 1, 0, 1, 0, 3, 2, 4, 0), 2, 9, byrow = TRUE),
2, 3, 2))
expect_equal(pm_first[c(TRUE, FALSE),],
polyMatrix(matrix(c(1, 1, 0, 1, 0, 3, 2, 4, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 2, 9, byrow = TRUE),
2, 3, 2))
expect_equal(pm_first[c(TRUE, FALSE, FALSE),],
polyMatrix(matrix(c(1, 1, 0, 1, 0, 3, 2, 4, 0), 1, 9, byrow = TRUE), 1, 3, 2))
expect_equal(pm_first[c(FALSE, TRUE),],
polyMatrix(matrix(c(0, 2, 0, 3, 0, 0, 1, 0, 0), 1, 9, byrow = TRUE), 1, 3, 2))
expect_equal(m_first[1,], c(3, 0, 2))
expect_equal(m_first[c(3, 1),], matrix(c(4, 2, 8, 3, 0, 2), 2, 3, byrow = TRUE))
expect_equal(m_first[c(TRUE, FALSE),], matrix(c(3, 0, 2, 4, 2, 8), 2, 3, byrow = TRUE))
expect_equal(m_first[c(TRUE, FALSE, FALSE),], c(3, 0, 2))
expect_equal(m_first[c(FALSE, TRUE),], c(7, 1, 0))
})
test_that("columns access", {
init_data()
expect_equal(pm_first[, 1],
polyMatrix(matrix(c(1, 1, 2,
0, 3, 1,
3, 0, 0), 3, 3, byrow = TRUE),
3, 1, 2))
expect_equal(pm_first[, c(3, 1)],
polyMatrix(matrix(c(0, 1, 3, 1, 0, 2,
0, 0, 0, 3, 0, 1,
1, 3, 0, 0, 0, 0), 3, 6, byrow = TRUE),
3, 2, 2))
expect_equal(pm_first[, c(TRUE, FALSE)],
polyMatrix(matrix(c(1, 0, 1, 3, 2, 0,
0, 0, 3, 0, 1, 0,
3, 1, 0, 0, 0, 0), 3, 6, byrow = TRUE),
3, 2, 2))
expect_equal(pm_first[, c(TRUE, FALSE, FALSE)],
polyMatrix(matrix(c(1, 1, 2,
0, 3, 1,
3, 0, 0), 3, 3, byrow = TRUE),
3, 1, 2))
expect_equal(pm_first[, c(FALSE, TRUE)],
polyMatrix(matrix(c(1, 0, 4,
2, 0, 0,
0, 0, 6), 3, 3, byrow = TRUE),
3, 1, 2))
expect_equal(m_first[, 1], c(3, 7, 4))
expect_equal(m_first[, c(3, 1)], matrix(c(2, 3, 0, 7, 8, 4), 3, 2, byrow = TRUE))
expect_equal(m_first[, c(TRUE, FALSE)], matrix(c(3, 2, 7, 0, 4, 8), 3, 2, byrow = TRUE))
expect_equal(m_first[, c(TRUE, FALSE, FALSE)], c(3, 7, 4))
expect_equal(m_first[, c(FALSE, TRUE)], c(0, 1, 2))
})
test_that("set one item: numeric and matrix", {
init_data()
pm_first[1, 1] <- 9
expect_equal(pm_first,
polyMatrix(matrix(c(9, 1, 0, 0, 0, 3, 0, 4, 0,
0, 2, 0, 3, 0, 0, 1, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
expect_error(pm_first[1, 1] <- c(1, 2))
expect_error(pm_first[1, 1] <- c())
pm_first[2, 1] <- matrix(8, 1, 1)
expect_equal(pm_first,
polyMatrix(matrix(c(9, 1, 0, 0, 0, 3, 0, 4, 0,
8, 2, 0, 0, 0, 0, 0, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
expect_error(pm_first[1, 1] <- matrix(1, 2, 2))
pm_first[2, 3] <- 5
expect_equal(pm_first,
polyMatrix(matrix(c(9, 1, 0, 0, 0, 3, 0, 4, 0,
8, 2, 5, 0, 0, 0, 0, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_second[2, 3] <- 0
expect_equal(pm_second, polyMatrix(0, 3, 3, 0))
m_first[1, 2] <- 1
expect_equal(m_first, matrix(c(3, 1, 2,
7, 1, 0,
4, 2, 8), 3, 3, byrow = TRUE))
expect_error(m_first[1, 1] <- c(1, 2))
expect_error(m_first[1, 1] <- c())
m_first[1, 1] <- matrix(1, 1, 1)
expect_equal(m_first, matrix(c(1, 1, 2,
7, 1, 0,
4, 2, 8), 3, 3, byrow = TRUE))
expect_error(m_first[1, 1] <- matrix(1, 2, 2))
})
test_that("set one item: polynomail and polyMatrix", {
init_data()
pm_first[1, 1] <- p(7, 6)
expect_equal(pm_first,
polyMatrix(matrix(c(7, 1, 0, 6, 0, 3, 0, 4, 0,
0, 2, 0, 3, 0, 0, 1, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_second[2, 3] <- p(3, 4, 5)
expect_equal(pm_second,
polyMatrix(matrix(c(0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 3, 0, 0, 4, 0, 0, 5,
0, 0, 0, 0, 0, 0, 0, 0, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_second[2, 3] <- p(3, 4)
expect_equal(pm_second,
polyMatrix(matrix(c(0, 0, 0, 0, 0, 0,
0, 0, 3, 0, 0, 4,
0, 0, 0, 0, 0, 0), 3, 6, byrow = TRUE),
3, 3, 1))
pm_second[1, 2] <- p(3, 2, 1)
expect_equal(pm_second,
polyMatrix(matrix(c(0, 3, 0, 0, 2, 0, 0, 1, 0,
0, 0, 3, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[2, 3] <- polyMatrix(matrix(c(2, 4, 6), 1, 3), 1, 1, 2)
expect_equal(pm_first,
polyMatrix(matrix(c(7, 1, 0, 6, 0, 3, 0, 4, 0,
0, 2, 2, 3, 0, 4, 1, 0, 6,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
})
test_that("set 2x2 items: number and matrix", {
init_data()
pm_first[c(2, 1), c(3, 1)] <- 9
expect_equal(pm_first,
polyMatrix(matrix(c(9, 1, 9, 0, 0, 0, 0, 4, 0,
9, 2, 9, 0, 0, 0, 0, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_second[c(2, 1), c(3, 1)] <- 0
expect_equal(pm_second, polyMatrix(0, 3, 3, 0))
m_first[c(2, 1), c(3, 1)] <- 9
expect_equal(m_first, matrix(c(9, 0, 9, 9, 1, 9, 4, 2, 8), 3, 3, byrow = TRUE))
})
test_that("set 2x2: matrix", {
init_data()
pm_first[c(2, 1), c(3, 1)] <- matrix(c(2, 4, 6, 8), 2, 2, byrow = TRUE)
expect_equal(pm_first,
polyMatrix(matrix(c(8, 1, 6, 0, 0, 0, 0, 4, 0,
4, 2, 2, 0, 0, 0, 0, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_second[c(2, 1), c(3, 1)] <- matrix(c(0, 3, 6, 9), 2, 2, byrow = TRUE)
expect_equal(pm_second,
polyMatrix(matrix(c(9, 0, 6, 3, 0, 0, 0, 0, 0), 3, 3, byrow = TRUE), 3, 3, 0))
m_first[c(3, 2), c(2, 1)] <- matrix(c(2, 4, 6, 8), 2, 2, byrow = TRUE)
expect_equal(m_first, matrix(c(3, 0, 2, 8, 6, 0, 4, 2, 8), 3, 3, byrow = TRUE))
})
test_that("set 2x2: polynomail", {
init_data()
pm_first[c(2, 1), c(3, 1)] <- p(7, 2)
expect_equal(pm_first,
polyMatrix(matrix(c(7, 1, 7, 2, 0, 2, 0, 4, 0,
7, 2, 7, 2, 0, 2, 0, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_second[c(2, 1), c(3, 1)] <- p(2, 4)
expect_equal(pm_second,
polyMatrix(matrix(c(2, 0, 2, 4, 0, 4,
2, 0, 2, 4, 0, 4,
0, 0, 0, 0, 0, 0), 3, 6, byrow = TRUE),
3, 3, 1))
pm_second[c(3, 1), c(1, 2)] <- p(3, 5, 7)
expect_equal(pm_second,
polyMatrix(matrix(c(3, 3, 2, 5, 5, 4, 7, 7, 0,
2, 0, 2, 4, 0, 4, 0, 0, 0,
3, 3, 0, 5, 5, 0, 7, 7, 0), 3, 9, byrow = TRUE),
3, 3, 2))
})
test_that("set 2x2: polyMatrix", {
pm_second[c(2, 1), c(3, 1)] <- polyMatrix(matrix(c(1, 3, 2, 4,
5, 7, 6, 8), 2, 4, byrow = TRUE),
2, 2, 1)
expect_equal(pm_second,
polyMatrix(matrix(c(7, 0, 5, 8, 0, 6,
3, 0, 1, 4, 0, 2,
0, 0, 0, 0, 0, 0), 3, 6, byrow = TRUE),
3, 3, 1))
pm_second[c(2, 1), c(3, 1)] <- polyMatrix(matrix(c(1, 2, 3, 4, 1, 1,
5, 6, 7, 8, 2, 2), 2, 6, byrow = TRUE),
2, 2, 2)
expect_equal(pm_second,
polyMatrix(matrix(c(6, 0, 5, 8, 0, 7, 2, 0, 2,
2, 0, 1, 4, 0, 3, 1, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0), 3, 9, byrow = TRUE),
3, 3, 2))
})
test_that("set one row", {
init_data()
pm_first[1,] <- 1
expect_equal(pm_first,
polyMatrix(matrix(c(1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 2, 0, 3, 0, 0, 1, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[1,] <- matrix(c(3, 4, 5), 1, 3)
expect_equal(pm_first,
polyMatrix(matrix(c(3, 4, 5, 0, 0, 0, 0, 0, 0,
0, 2, 0, 3, 0, 0, 1, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[1,] <- p(2, 3)
expect_equal(pm_first,
polyMatrix(matrix(c(2, 2, 2, 3, 3, 3, 0, 0, 0,
0, 2, 0, 3, 0, 0, 1, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[1,] <- polyMatrix(matrix(c(1, 2, 0, 3, 0, 0), 1, 6, byrow = TRUE), 1, 3, 1)
expect_equal(pm_first,
polyMatrix(matrix(c(1, 2, 0, 3, 0, 0, 0, 0, 0,
0, 2, 0, 3, 0, 0, 1, 0, 0,
3, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
})
test_that("set two rows", {
init_data()
pm_first[c(3, 1),] <- 1
expect_equal(pm_first,
polyMatrix(matrix(c(1, 1, 1, 0, 0, 0, 0, 0, 0,
0, 2, 0, 3, 0, 0, 1, 0, 0,
1, 1, 1, 0, 0, 0, 0, 0, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[c(3, 1),] <- matrix(c(3, 4, 5, 1, 2, 3), 2, 3, byrow = TRUE)
expect_equal(pm_first,
polyMatrix(matrix(c(1, 2, 3, 0, 0, 0, 0, 0, 0,
0, 2, 0, 3, 0, 0, 1, 0, 0,
3, 4, 5, 0, 0, 0, 0, 0, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[c(3, 1),] <- p(2, 3)
expect_equal(pm_first,
polyMatrix(matrix(c(2, 2, 2, 3, 3, 3, 0, 0, 0,
0, 2, 0, 3, 0, 0, 1, 0, 0,
2, 2, 2, 3, 3, 3, 0, 0, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[c(3, 1),] <- polyMatrix(matrix(c(1, 2, 0, 3, 0, 0,
0, 9, 8, 0, 0, 7), 2, 6, byrow = TRUE), 2, 3, 1)
expect_equal(pm_first,
polyMatrix(matrix(c(0, 9, 8, 0, 0, 7, 0, 0, 0,
0, 2, 0, 3, 0, 0, 1, 0, 0,
1, 2, 0, 3, 0, 0, 0, 0, 0), 3, 9, byrow = TRUE),
3, 3, 2))
})
test_that("set one column", {
init_data()
pm_first[, 1] <- 2
expect_equal(pm_first,
polyMatrix(matrix(c(2, 1, 0, 0, 0, 3, 0, 4, 0,
2, 2, 0, 0, 0, 0, 0, 0, 0,
2, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[, 1] <- matrix(c(3, 2, 1), 3, 1, byrow = TRUE)
expect_equal(pm_first,
polyMatrix(matrix(c(3, 1, 0, 0, 0, 3, 0, 4, 0,
2, 2, 0, 0, 0, 0, 0, 0, 0,
1, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[, 1] <- p(1, 9)
expect_equal(pm_first,
polyMatrix(matrix(c(1, 1, 0, 9, 0, 3, 0, 4, 0,
1, 2, 0, 9, 0, 0, 0, 0, 0,
1, 0, 1, 9, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[, 1] <- polyMatrix(matrix(c(2, 5, 0, 8, 7, 0), 3, 2, byrow = TRUE), 3, 1, 1)
expect_equal(pm_first,
polyMatrix(matrix(c(2, 1, 0, 5, 0, 3, 0, 4, 0,
0, 2, 0, 8, 0, 0, 0, 0, 0,
7, 0, 1, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
})
test_that("set tow columns", {
init_data()
pm_first[, c(3, 1)] <- 2
expect_equal(pm_first,
polyMatrix(matrix(c(2, 1, 2, 0, 0, 0, 0, 4, 0,
2, 2, 2, 0, 0, 0, 0, 0, 0,
2, 0, 2, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[, c(3, 1)] <- matrix(c(9, 3, 8, 2, 7, 1), 3, 2, byrow = TRUE)
expect_equal(pm_first,
polyMatrix(matrix(c(3, 1, 9, 0, 0, 0, 0, 4, 0,
2, 2, 8, 0, 0, 0, 0, 0, 0,
1, 0, 7, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[, c(3, 1)] <- p(1, 9)
expect_equal(pm_first,
polyMatrix(matrix(c(1, 1, 1, 9, 0, 9, 0, 4, 0,
1, 2, 1, 9, 0, 9, 0, 0, 0,
1, 0, 1, 9, 0, 9, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
pm_first[, c(3, 1)] <- polyMatrix(matrix(c(1, 2, 4, 5,
0, 0, 5, 8,
2, 7, 0, 0), 3, 4, byrow = TRUE),
3, 2, 1)
expect_equal(pm_first,
polyMatrix(matrix(c(2, 1, 1, 5, 0, 4, 0, 4, 0,
0, 2, 0, 8, 0, 5, 0, 0, 0,
7, 0, 2, 0, 0, 0, 0, 6, 0), 3, 9, byrow = TRUE),
3, 3, 2))
})
test_that("set whole matrix", {
init_data()
pm_small[,] <- 6
expect_equal(pm_small,
polyMatrix(matrix(c(6, 6, 6, 6), 2, 2, byrow = TRUE), 2, 2, 0))
pm_small[,] <- p(2, 8)
expect_equal(pm_small,
polyMatrix(matrix(c(2, 2, 8, 8, 2, 2, 8, 8), 2, 4, byrow = TRUE), 2, 2, 1))
})
test_that("custom 1", {
pm <- parse.polyMatrix("1, x + 2",
"0, x^2",
"0, 0")
expect_equal(pm[, 1], parse.polyMatrix("1", "0", "0"))
expect_equal(pm[, 2], parse.polyMatrix("2 + x", "x^2", "0"))
}) |
print.outbreaker_chains <- function(x, n_row = 3, n_col = 8, type = "chain", ...) {
if(type == "chain"){
cat("\n\n ///// outbreaker results ///\n")
cat("\nclass: ", class(x))
cat("\ndimensions", nrow(x), "rows, ", ncol(x), "columns")
if (ncol(x) > n_col) {
ori_names <- names(x)
x <- x[, seq_len(min(n_col, ncol(x)))]
not_shown <- setdiff(ori_names, names(x))
alpha_txt <- paste(not_shown[range(grep("alpha", not_shown))], collapse=" - ")
t_inf_txt <- paste(not_shown[range(grep("t_inf", not_shown))], collapse=" - ")
kappa_txt <- paste(not_shown[range(grep("kappa", not_shown))], collapse=" - ")
cat("\nancestries not shown:", alpha_txt)
cat("\ninfection dates not shown:", t_inf_txt)
cat("\nintermediate generations not shown:", kappa_txt)
}
cat("\n\n/// head //\n")
print(head(as.data.frame(x), n_row))
cat("\n...")
cat("\n/// tail //\n")
print(tail(as.data.frame(x), n_row))
} else if(type == "cluster"){
matrix_ances <- t(apply(x[, grep("alpha", colnames(x))],
1, function(X){
while(any(!is.na(X[X]))) X[!is.na(X[X])] <- X[X[!is.na(X[X])]]
X[!is.na(X)] <- names(X[X[!is.na(X)]])
X[is.na(X)] <- names(X[is.na(X)])
return(X)
}))
max_clust_size <- max(unlist(apply(matrix_ances, 1, table)))
table_tot <- t(apply(matrix_ances, 1, function(X){
table_clust <- numeric(max_clust_size)
names(table_clust) <- 1:max_clust_size
table_clust[names(table(table(X)))] <- table(table(X))
return(table_clust)
}))
if (ncol(table_tot) > n_col) {
cat("\n Biggest cluster:", max_clust_size)
cat("\n Cluster not shown:", n_col, "to", ncol(table_tot), "\n")
table_tot <- table_tot[, seq_len(min(n_col, ncol(table_tot)))]
}
if((n_row * 2) < nrow(table_tot)){
cat("\n\n/// head //\n")
print(head(as.data.frame(table_tot), n_row))
cat("\n...")
cat("\n/// tail //\n")
print(tail(as.data.frame(table_tot), n_row))
} else
print(as.data.frame(table_tot))
} else stop("type should be chain or cluster")
}
plot.outbreaker_chains <- function(x, y = "post",
type = c("trace", "hist", "density", "cluster",
"alpha", "t_inf", "kappa", "network"),
burnin = 0, min_support = 0.1, labels = NULL,
group_cluster = NULL, ...) {
type <- match.arg(type)
if (!y %in% names(x)) {
stop(paste(y,"is not a column of x"))
}
frequency <- low <- med <- up <- categ <- NULL
if (burnin > max(x$step)) {
stop("burnin exceeds the number of steps in x")
}
x <- x[x$step>burnin,,drop = FALSE]
if (type == "trace") {
out <- ggplot(x) + geom_line(aes_string(x="step", y = y)) +
labs(x="Iteration", y = y, title = paste("trace:",y))
}
if (type == "hist") {
out <- ggplot(x) + geom_histogram(aes_string(x = y)) +
geom_point(aes_string(x = y, y = 0), shape="|", alpha = 0.5, size = 3) +
labs(x = y, title = paste("histogram:",y))
}
if (type == "density") {
out <- ggplot(x) + geom_density(aes_string(x = y)) +
geom_point(aes_string(x = y, y = 0), shape="|", alpha = 0.5, size = 3) +
labs(x = y, title = paste("density:",y))
}
if (type =="alpha") {
alpha <- as.matrix(x[,grep("alpha", names(x))])
colnames(alpha) <- seq_len(ncol(alpha))
from <- as.vector(alpha)
to <- as.vector(col(alpha))
from[is.na(from)] <- 0
out_dat <- data.frame(xyTable(from,to))
names(out_dat) <- c("from", "to", "frequency")
get_prop <- function(i) {
ind <- which(out_dat$to == out_dat$to[i])
out_dat[[3]][i]/sum(out_dat[[3]][ind])
}
get_alpha_lab <- function(axis, labels = NULL) {
if(is.null(labels)) labels <- seq_len(ncol(alpha))
if(axis == 'x') return(labels) else
if(axis == 'y') return(c("Import", labels))
}
get_alpha_color <- function(color = NULL) {
if(is.null(color)) return(NULL)
else return(scale_color_manual(values = color))
}
get_lab_color <- function(labels = NULL, color = NULL) {
list(alpha_lab_x = get_alpha_lab('x', labels),
alpha_lab_y = get_alpha_lab('y', labels),
alpha_color = get_alpha_color(color))
}
tmp <- get_lab_color(labels, ...)
out_dat[3] <- vapply(seq_along(out_dat[[3]]), get_prop, 1)
out_dat$from <- factor(out_dat$from, levels = c(0, sort(unique(out_dat$to))))
out_dat$to <- factor(out_dat$to, levels = sort(unique(out_dat$to)))
out <- ggplot(out_dat) +
geom_point(aes(x = to, y = from, size = frequency, color = to)) +
scale_x_discrete(drop = FALSE, labels = tmp$alpha_lab_x) +
scale_y_discrete(drop = FALSE, labels = tmp$alpha_lab_y) +
labs(x = 'To', y = 'From', size = 'Posterior\nfrequency') +
tmp$alpha_color +
scale_size_area() +
guides(colour = FALSE)
}
if (type =="t_inf") {
get_t_inf_lab <- function(labels = NULL) {
N <- ncol(t_inf)
if(is.null(labels)) labels <- 1:N
return(labels)
}
get_t_inf_color <- function(color = NULL) {
if(is.null(color)) return(NULL)
else return(scale_fill_manual(values = color))
}
get_lab_color <- function(labels = NULL, color = NULL) {
list(t_inf_lab_x = get_t_inf_lab(labels),
t_inf_color = get_t_inf_color(color))
}
t_inf <- as.matrix(x[,grep("t_inf", names(x))])
tmp <- get_lab_color(...)
dates <- as.vector(t_inf)
cases <- as.vector(col(t_inf))
out_dat <- data.frame(cases = factor(cases), dates = dates)
out <- ggplot(out_dat) +
geom_violin(aes(x = cases, y = dates, fill = cases)) +
coord_flip() + guides(fill = FALSE) +
labs(y = 'Infection time', x = NULL) +
tmp$t_inf_color +
scale_x_discrete(labels = tmp$t_inf_lab)
}
if (type == "kappa") {
get_kappa_lab <- function(labels = NULL) {
N <- ncol(kappa)
if(is.null(labels)) labels <- 1:N
return(labels)
}
kappa <- as.matrix(x[,grep("kappa", names(x))])
generations <- as.vector(kappa)
cases <- as.vector(col(kappa))
to_keep <- !is.na(generations)
generations <- generations[to_keep]
cases <- cases[to_keep]
out_dat <- data.frame(xyTable(generations, cases))
get_prop <- function(i) {
ind <- which(out_dat$y == out_dat$y[i])
out_dat[[3]][i]/sum(out_dat[[3]][ind])
}
out_dat[3] <- vapply(seq_along(out_dat[[3]]), get_prop, 1)
names(out_dat) <- c("generations", "cases", "frequency")
out <- ggplot(out_dat) +
geom_point(aes(x = generations, y = as.factor(cases), size = frequency, color = factor(cases))) +
scale_size_area() +
scale_y_discrete(labels = get_kappa_lab(...)) +
guides(colour = FALSE) +
labs(title = "number of generations between cases",
x = "number of generations to ancestor",
y = NULL)
}
if (type == "network") {
alpha <- x[, grep("alpha",names(x)), drop = FALSE]
from <- unlist(alpha)
to <- as.vector(col(alpha))
N <- ncol(alpha)
edges <- stats::na.omit(data.frame(xyTable(from, to)))
edges[3] <- edges$number/nrow(alpha)
names(edges) <- c("from", "to", "value")
edges <- edges[edges$value > min_support,,drop = FALSE]
edges$arrows <- "to"
find_nodes_size <- function(i) {
sum(from==i, na.rm = TRUE) / nrow(alpha)
}
get_node_lab <- function(labels = NULL) {
if(is.null(labels)) labels <- 1:N
return(labels)
}
nodes <- data.frame(id = seq_len(ncol(alpha)),
label = seq_len(ncol(alpha)))
nodes$value <- vapply(nodes$id,
find_nodes_size,
numeric(1))
nodes$shape <- rep("dot", N)
nodes$label <- get_node_lab(...)
smry <- summary(x, burnin = burnin)
is_imported <- is.na(smry$tree$from)
nodes$shaped[is_imported] <- "star"
out <- visNetwork::visNetwork(nodes = nodes, edges = edges, ...)
out <- visNetwork::visNodes(out, shadow = list(enabled = TRUE, size = 10),
color = list(highlight = "red"))
out <- visNetwork::visEdges(out, arrows = list(
to = list(enabled = TRUE, scaleFactor = 0.2)),
color = list(highlight = "red"))
}
if (type == "cluster"){
matrix_ances <- t(apply(x[x$step > burnin, grep("alpha", colnames(x))], 1, function(X){
while(any(!is.na(X[X]))) X[!is.na(X[X])] <- X[X[!is.na(X[X])]]
X[!is.na(X)] <- names(X[X[!is.na(X)]])
X[is.na(X)] <- names(X[is.na(X)])
return(X)
}))
max_clust_size <- max(unlist(apply(matrix_ances, 1, table)))
if(!is.null(group_cluster)) {
max_clust_size <- max(max_clust_size, group_cluster)
if(max_clust_size != max(group_cluster)) group_cluster <- c(group_cluster, max_clust_size)
if(min(group_cluster) != 0) group_cluster <- c(0, group_cluster)
}
table_tot <- t(apply(matrix_ances, 1, function(X){
table_clust <- numeric(max_clust_size)
names(table_clust) <- 1:max_clust_size
table_clust[names(table(table(X)))] <- table(table(X))
return(table_clust)
}))
if(!is.null(group_cluster)) {
group_cluster[which.max(group_cluster)] <- group_cluster[which.max(group_cluster)] + 1
aggreg_vector <- sapply(seq_len(max_clust_size), function(X) sum(X > group_cluster))
aggreg_clust_size <- t(aggregate(t(table_tot), by = list(aggreg_vector), sum)[,-1])
colnames(aggreg_clust_size) <- sapply(seq_len(length(group_cluster) - 1), function(X){
if(group_cluster[X] == group_cluster[X+1] -1) return(as.character(group_cluster[X] + 1)) else
return(paste0(group_cluster[X] + 1, " - ", group_cluster[X + 1]))
})
cluster_size_tot <- t(apply(aggreg_clust_size, 2, function(X)
quantile(X, probs = c(0.025, 0.5, 0.975))))
} else
cluster_size_tot <- t(apply(table_tot, 2, function(X)
quantile(X, probs = c(0.025, 0.5, 0.975))))
out_dat <- cbind.data.frame(rownames(cluster_size_tot), cluster_size_tot,
stringsAsFactors=FALSE)
colnames(out_dat) <- c("categ", "low", "med", "up")
out <- ggplot(out_dat) + geom_bar(aes(x = factor(categ, levels = categ),
y = med), stat = "identity") +
geom_errorbar(aes(x = categ, ymin=low, ymax=up), width=.2) +
guides(fill = FALSE) + labs(y = 'Number of clusters', x = "Cluster size")
}
return(out)
}
summary.outbreaker_chains <- function(object, burnin = 0, group_cluster = NULL, ...) {
x <- object
if (burnin > max(x$step)) {
stop("burnin exceeds the number of steps in object")
}
x <- x[x$step>burnin,,drop = FALSE]
out <- list()
interv <- ifelse(nrow(x)>2, diff(tail(x$step, 2)), NA)
out$step <- c(first = min(x$step),
last = max(x$step),
interval = interv,
n_steps = length(x$step)
)
out$post <- summary(x$post)
out$like <- summary(x$like)
out$prior <- summary(x$prior)
out$pi <- summary(x$pi)
out$a <- summary(x$a)
out$b <- summary(x$b)
out$tree <- list()
alpha <- as.matrix(x[,grep("alpha", names(x))])
f1 <- function(x) {
as.integer(names(sort(table(x, exclude = NULL), decreasing = TRUE)[1]))
}
out$tree$from <- apply(alpha, 2, f1)
out$tree$to <- seq_len(ncol(alpha))
t_inf <- as.matrix(x[,grep("t_inf", names(x))])
out$tree$time <- apply(t_inf, 2, median)
f2 <- function(x) {
(sort(table(x, exclude = NULL), decreasing = TRUE)/length(x))[1]
}
out$tree$support <- apply(alpha, 2, f2)
out$tree$support[is.na(out$tree$from)] <- NA
f3 <- function(x) {
(length(which(is.na(x)))/length(x))[1]
}
out$tree$import <- apply(alpha, 2, f3)
kappa <- as.matrix(x[,grep("kappa", names(x))])
out$tree$generations <- apply(kappa, 2, function(X) {
return(median(X[!is.na(X)]))})
out$tree <- as.data.frame(out$tree)
rownames(out$tree) <- NULL
matrix_ances <- t(apply(x[x$step > burnin, grep("alpha", colnames(x))],
1, function(X){
while(any(!is.na(X[X]))) X[!is.na(X[X])] <- X[X[!is.na(X[X])]]
X[!is.na(X)] <- names(X[X[!is.na(X)]])
X[is.na(X)] <- names(X[is.na(X)])
return(X)
}))
max_clust_size <- max(unlist(apply(matrix_ances, 1, table)))
if(!is.null(group_cluster)) {
max_clust_size <- max(max_clust_size, group_cluster)
if(max_clust_size != max(group_cluster)) group_cluster <- c(group_cluster, max_clust_size)
if(min(group_cluster) != 0) group_cluster <- c(0, group_cluster)
}
table_tot <- t(apply(matrix_ances, 1, function(X){
table_clust <- numeric(max_clust_size)
names(table_clust) <- 1:max_clust_size
table_clust[names(table(table(X)))] <- table(table(X))
return(table_clust)
}))
if(!is.null(group_cluster)) {
group_cluster[which.max(group_cluster)] <- group_cluster[which.max(group_cluster)] + 1
aggreg_vector <- sapply(seq_len(max_clust_size), function(X) sum(X > group_cluster))
aggreg_clust_size <- t(aggregate(t(table_tot), by = list(aggreg_vector), sum)[,-1])
colnames(aggreg_clust_size) <- sapply(seq_len(length(group_cluster) - 1), function(X){
if(group_cluster[X] == group_cluster[X+1] -1) return(as.character(group_cluster[X] + 1)) else
return(paste0(group_cluster[X] + 1, " - ", group_cluster[X + 1]))
})
out$cluster <- apply(aggreg_clust_size, 2, summary)
} else
out$cluster <- apply(table_tot, 2, summary)
return(out)
} |
context("VS/ES operators")
test_that("c on attached vs", {
g <- make_ring(10)
vg <- V(g)[1:5]
vg2 <- V(g)[6:10]
expect_equivalent(c(vg, vg2), V(g))
expect_equal(get_vs_graph_id(c(vg, vg2)), get_graph_id(g))
vg <- V(g)
vg2 <- V(g)[FALSE]
expect_equivalent(c(vg, vg2), V(g))
expect_equivalent(c(vg2, vg), V(g))
vg <- V(g)[c(2,5,6,8)]
expect_equivalent(c(vg, vg), V(g)[c(2,5,6,8,2,5,6,8)])
})
test_that("c on detached vs", {
g <- make_ring(10)
vg <- V(g)[1:5]
vg2 <- V(g)[6:10]
vg3 <- V(g)
vg4 <- V(g)[FALSE]
vg5 <- V(g)[c(2,5,6,8)]
vg6 <- V(g)[c(2,5,6,8,2,5,6,8)]
rm(g)
gc()
expect_equivalent(c(vg, vg2), vg3)
expect_equivalent(c(vg3, vg4), vg3)
expect_equivalent(c(vg4, vg3), vg3)
expect_equivalent(c(vg5, vg5), vg6)
})
test_that("c on attached vs, names", {
g <- make_ring(10)
V(g)$name <- letters[1:10]
vg <- V(g)[1:5]
vg2 <- V(g)[6:10]
expect_equivalent(c(vg, vg2), V(g))
expect_equal(names(c(vg, vg2)), names(V(g)))
vg <- V(g)
vg2 <- V(g)[FALSE]
expect_equivalent(c(vg, vg2), V(g))
expect_equal(names(c(vg, vg2)), names(V(g)))
expect_equivalent(c(vg2, vg), V(g))
expect_equal(names(c(vg2, vg)), names(V(g)))
vg <- V(g)[c(2,5,6,8)]
expect_equivalent(c(vg, vg), V(g)[c(2,5,6,8,2,5,6,8)])
expect_equal(names(c(vg, vg)), names(V(g)[c(2,5,6,8,2,5,6,8)]))
})
test_that("c on detached vs, names", {
g <- make_ring(10)
vg <- V(g)[1:5]
vg2 <- V(g)[6:10]
vg3 <- V(g)
vg4 <- V(g)[FALSE]
vg5 <- V(g)[c(2,5,6,8)]
vg6 <- V(g)[c(2,5,6,8,2,5,6,8)]
rm(g)
gc()
expect_equivalent(c(vg, vg2), vg3)
expect_equal(names(c(vg, vg2)), names(vg3))
expect_equivalent(c(vg3, vg4), vg3)
expect_equal(names(c(vg3, vg4)), names(vg3))
expect_equivalent(c(vg4, vg3), vg3)
expect_equal(names(c(vg3, vg4)), names(vg3))
expect_equivalent(c(vg5, vg5), vg6)
expect_equal(names(c(vg5, vg5)), names(vg6))
})
test_that("union on attached vs", {
g <- make_ring(10)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
vu <- union(v1, v2)
expect_equivalent(vu, V(g))
expect_equivalent(union(V(g)), V(g))
v3 <- V(g)[FALSE]
expect_equivalent(union(V(g), v3), V(g))
expect_equivalent(union(v3, V(g), v3), V(g))
expect_equivalent(union(v3), v3)
expect_equivalent(union(v3, v3, v3), v3)
expect_equivalent(union(v3, v3), v3)
})
test_that("union on detached vs", {
g <- make_ring(10)
vg <- V(g)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
vu <- union(v1, v2)
v3 <- V(g)[FALSE]
rm(g)
gc()
expect_equivalent(vu, vg)
expect_equivalent(union(vg), vg)
expect_equivalent(union(vg, v3), vg)
expect_equivalent(union(v3, vg, v3), vg)
expect_equivalent(union(v3), v3)
expect_equivalent(union(v3, v3, v3), v3)
expect_equivalent(union(v3, v3), v3)
})
test_that("union on attached vs, names", {
g <- make_ring(10)
V(g)$name <- letters[1:10]
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
vu <- union(v1, v2)
expect_equivalent(vu, V(g))
expect_equal(names(vu), names(V(g)))
expect_equivalent(union(V(g)), V(g))
expect_equal(names(union(V(g))), names(V(g)))
v3 <- V(g)[FALSE]
expect_equivalent(union(V(g), v3), V(g))
expect_equal(names(union(V(g), v3)), names(V(g)))
expect_equivalent(union(v3, V(g), v3), V(g))
expect_equal(names(union(v3, V(g), v3)), names(V(g)))
expect_equivalent(union(v3), v3)
expect_equal(names(union(v3)), names(v3))
expect_equivalent(union(v3, v3, v3), v3)
expect_equal(names(union(v3, v3, v3)), names(v3))
expect_equivalent(union(v3, v3), v3)
expect_equal(names(union(v3, v3)), names(v3))
})
test_that("union on detached vs, names", {
g <- make_ring(10)
V(g)$name <- letters[1:10]
vg <- V(g)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
v3 <- V(g)[FALSE]
rm(g)
gc()
vu <- union(v1, v2)
expect_equivalent(vu, vg)
expect_equal(names(vu), names(vg))
expect_equivalent(union(vg), vg)
expect_equal(names(union(vg)), names(vg))
expect_equivalent(union(vg, v3), vg)
expect_equal(names(union(vg, v3)), names(vg))
expect_equivalent(union(v3, vg, v3), vg)
expect_equal(names(union(v3, vg, v3)), names(vg))
expect_equivalent(union(v3), v3)
expect_equal(names(union(v3)), names(v3))
expect_equivalent(union(v3, v3, v3), v3)
expect_equal(names(union(v3, v3, v3)), names(v3))
expect_equivalent(union(v3, v3), v3)
expect_equal(names(union(v3, v3)), names(v3))
})
test_that("intersection on attached vs", {
g <- make_ring(10)
vg <- V(g)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
v3 <- V(g)[FALSE]
v4 <- V(g)[1:3]
v12 <- V(g)[6:7]
v13 <- V(g)[FALSE]
v14 <- V(g)[1:3]
v24 <- V(g)[FALSE]
vi1 <- intersection(v1, v2)
expect_equivalent(vi1, v12)
vi2 <- intersection(v1, v3)
expect_equivalent(vi2, v13)
vi3 <- intersection(v1, v4)
expect_equivalent(vi3, v14)
vi4 <- intersection(v1, vg)
expect_equivalent(vi4, v1)
vi5 <- intersection(v2, v4)
expect_equivalent(vi5, v24)
vi6 <- intersection(v3, vg)
expect_equivalent(vi6, v3)
})
test_that("intersection on detached vs", {
g <- make_ring(10)
vg <- V(g)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
v3 <- V(g)[FALSE]
v4 <- V(g)[1:3]
v12 <- V(g)[6:7]
v13 <- V(g)[FALSE]
v14 <- V(g)[1:3]
v24 <- V(g)[FALSE]
rm(g)
gc()
vi1 <- intersection(v1, v2)
expect_equivalent(vi1, v12)
vi2 <- intersection(v1, v3)
expect_equivalent(vi2, v13)
vi3 <- intersection(v1, v4)
expect_equivalent(vi3, v14)
vi4 <- intersection(v1, vg)
expect_equivalent(vi4, v1)
vi5 <- intersection(v2, v4)
expect_equivalent(vi5, v24)
vi6 <- intersection(v3, vg)
expect_equivalent(vi6, v3)
})
test_that("intersection on attached vs, names", {
g <- make_ring(10)
V(g)$name <- letters[1:10]
vg <- V(g)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
v3 <- V(g)[FALSE]
v4 <- V(g)[1:3]
v12 <- V(g)[6:7]
v13 <- V(g)[FALSE]
v14 <- V(g)[1:3]
v24 <- V(g)[FALSE]
vi1 <- intersection(v1, v2)
expect_equivalent(vi1, v12)
expect_equal(names(vi1), names(v12))
vi2 <- intersection(v1, v3)
expect_equivalent(vi2, v13)
expect_equal(names(vi2), names(v13))
vi3 <- intersection(v1, v4)
expect_equivalent(vi3, v14)
expect_equal(names(vi3), names(v14))
vi4 <- intersection(v1, vg)
expect_equivalent(vi4, v1)
expect_equal(names(vi4), names(v1))
vi5 <- intersection(v2, v4)
expect_equivalent(vi5, v24)
expect_equal(names(vi5), names(v24))
vi6 <- intersection(v3, vg)
expect_equivalent(vi6, v3)
expect_equal(names(vi6), names(v3))
})
test_that("intersection on detached vs, names", {
g <- make_ring(10)
V(g)$name <- letters[1:10]
vg <- V(g)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
v3 <- V(g)[FALSE]
v4 <- V(g)[1:3]
v12 <- V(g)[6:7]
v13 <- V(g)[FALSE]
v14 <- V(g)[1:3]
v24 <- V(g)[FALSE]
rm(g)
gc()
vi1 <- intersection(v1, v2)
expect_equivalent(vi1, v12)
expect_equal(names(vi1), names(v12))
vi2 <- intersection(v1, v3)
expect_equivalent(vi2, v13)
expect_equal(names(vi2), names(v13))
vi3 <- intersection(v1, v4)
expect_equivalent(vi3, v14)
expect_equal(names(vi3), names(v14))
vi4 <- intersection(v1, vg)
expect_equivalent(vi4, v1)
expect_equal(names(vi4), names(v1))
vi5 <- intersection(v2, v4)
expect_equivalent(vi5, v24)
expect_equal(names(vi5), names(v24))
vi6 <- intersection(v3, vg)
expect_equivalent(vi6, v3)
expect_equal(names(vi6), names(v3))
})
test_that("difference on attached vs", {
g <- make_ring(10)
vg <- V(g)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
v3 <- V(g)[FALSE]
v4 <- V(g)[1:3]
vr1 <- V(g)[8:10]
vr2 <- V(g)
vr3 <- V(g)[1:5]
vr4 <- V(g)[4:7]
vr5 <- V(g)[FALSE]
vr6 <- V(g)[FALSE]
vd1 <- difference(vg, v1)
vd2 <- difference(vg, v3)
vd3 <- difference(v1, v2)
vd4 <- difference(v1, v4)
vd5 <- difference(v3, v3)
vd6 <- difference(v3, v4)
expect_equivalent(vd1, vr1)
expect_equivalent(vd2, vr2)
expect_equivalent(vd3, vr3)
expect_equivalent(vd4, vr4)
expect_equivalent(vd5, vr5)
expect_equivalent(vd6, vr6)
})
test_that("difference on detached vs", {
g <- make_ring(10)
vg <- V(g)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
v3 <- V(g)[FALSE]
v4 <- V(g)[1:3]
vr1 <- V(g)[8:10]
vr2 <- V(g)
vr3 <- V(g)[1:5]
vr4 <- V(g)[4:7]
vr5 <- V(g)[FALSE]
vr6 <- V(g)[FALSE]
rm(g)
gc()
vd1 <- difference(vg, v1)
vd2 <- difference(vg, v3)
vd3 <- difference(v1, v2)
vd4 <- difference(v1, v4)
vd5 <- difference(v3, v3)
vd6 <- difference(v3, v4)
expect_equivalent(vd1, vr1)
expect_equivalent(vd2, vr2)
expect_equivalent(vd3, vr3)
expect_equivalent(vd4, vr4)
expect_equivalent(vd5, vr5)
expect_equivalent(vd6, vr6)
})
test_that("difference on attached vs, names", {
g <- make_ring(10)
V(g)$name <- letters[1:10]
vg <- V(g)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
v3 <- V(g)[FALSE]
v4 <- V(g)[1:3]
vr1 <- V(g)[8:10]
vr2 <- V(g)
vr3 <- V(g)[1:5]
vr4 <- V(g)[4:7]
vr5 <- V(g)[FALSE]
vr6 <- V(g)[FALSE]
vd1 <- difference(vg, v1)
vd2 <- difference(vg, v3)
vd3 <- difference(v1, v2)
vd4 <- difference(v1, v4)
vd5 <- difference(v3, v3)
vd6 <- difference(v3, v4)
expect_equivalent(vd1, vr1)
expect_equal(names(vd1), names(vr1))
expect_equivalent(vd2, vr2)
expect_equal(names(vd2), names(vr2))
expect_equivalent(vd3, vr3)
expect_equal(names(vd3), names(vr3))
expect_equivalent(vd4, vr4)
expect_equal(names(vd4), names(vr4))
expect_equivalent(vd5, vr5)
expect_equal(names(vd5), names(vr5))
expect_equivalent(vd6, vr6)
expect_equal(names(vd6), names(vr6))
})
test_that("difference on detached vs, names", {
g <- make_ring(10)
V(g)$name <- letters[1:10]
vg <- V(g)
v1 <- V(g)[1:7]
v2 <- V(g)[6:10]
v3 <- V(g)[FALSE]
v4 <- V(g)[1:3]
vr1 <- V(g)[8:10]
vr2 <- V(g)
vr3 <- V(g)[1:5]
vr4 <- V(g)[4:7]
vr5 <- V(g)[FALSE]
vr6 <- V(g)[FALSE]
rm(g)
gc()
vd1 <- difference(vg, v1)
vd2 <- difference(vg, v3)
vd3 <- difference(v1, v2)
vd4 <- difference(v1, v4)
vd5 <- difference(v3, v3)
vd6 <- difference(v3, v4)
expect_equivalent(vd1, vr1)
expect_equal(names(vd1), names(vr1))
expect_equivalent(vd2, vr2)
expect_equal(names(vd2), names(vr2))
expect_equivalent(vd3, vr3)
expect_equal(names(vd3), names(vr3))
expect_equivalent(vd4, vr4)
expect_equal(names(vd4), names(vr4))
expect_equivalent(vd5, vr5)
expect_equal(names(vd5), names(vr5))
expect_equivalent(vd6, vr6)
expect_equal(names(vd6), names(vr6))
})
test_that("rev on attached vs", {
for (i in 1:10) {
g <- make_ring(10)
idx <- seq_len(i)
vg <- V(g)[idx]
vgr <- V(g)[rev(idx)]
vg2 <- rev(vg)
expect_equivalent(vg2, vgr)
}
})
test_that("rev on detached vs", {
for (i in 1:10) {
g <- make_ring(10)
idx <- seq_len(i)
vg <- V(g)[idx]
vgr <- V(g)[rev(idx)]
rm(g)
gc()
vg2 <- rev(vg)
expect_equivalent(vg2, vgr)
}
})
test_that("rev on attached vs, names", {
for (i in 1:10) {
g <- make_ring(10)
V(g)$name <- letters[1:10]
idx <- seq_len(i)
vg <- V(g)[idx]
vgr <- V(g)[rev(idx)]
vg2 <- rev(vg)
expect_equivalent(vg2, vgr)
expect_equal(names(vg2), names(vgr))
}
})
test_that("rev on detached vs, names", {
for (i in 1:10) {
g <- make_ring(10)
V(g)$name <- letters[1:10]
idx <- seq_len(i)
vg <- V(g)[idx]
vgr <- V(g)[rev(idx)]
rm(g)
gc()
vg2 <- rev(vg)
expect_equivalent(vg2, vgr)
expect_equal(names(vg2), names(vgr))
}
})
unique_tests <- list(
list(1:5, 1:5),
list(c(1,1,2:5), 1:5),
list(c(1,1,1,1), 1),
list(c(1,2,2,2), 1:2),
list(c(2,2,1,1), 2:1),
list(c(1,2,1,2), 1:2),
list(c(), c())
)
test_that("unique on attached vs", {
sapply(unique_tests, function(d) {
g <- make_ring(10)
vg <- unique(V(g)[ d[[1]] ])
vr <- V(g)[ d[[2]] ]
expect_equivalent(vg, vr)
})
})
test_that("unique on detached vs", {
sapply(unique_tests, function(d) {
g <- make_ring(10)
vg <- V(g)[ d[[1]] ]
vr <- V(g)[ d[[2]] ]
rm(g)
gc()
vg <- unique(vg)
expect_equivalent(vg, vr)
})
})
test_that("unique on attached vs, names", {
sapply(unique_tests, function(d) {
g <- make_ring(10)
V(g)$name <- letters[1:10]
vg <- unique(V(g)[ d[[1]] ])
vr <- V(g)[ d[[2]] ]
expect_equivalent(vg, vr)
})
})
test_that("unique on detached vs, names", {
sapply(unique_tests, function(d) {
g <- make_ring(10)
V(g)$name <- letters[1:10]
vg <- V(g)[ d[[1]] ]
vr <- V(g)[ d[[2]] ]
rm(g)
gc()
vg <- unique(vg)
expect_equivalent(vg, vr)
})
}) |
context("Data Version management")
test_that("data changes but version out of sync", {
file <- system.file("extdata", "tests", "subsetCars.Rmd",
package = "DataPackageR"
)
file2 <- system.file("extdata", "tests", "extra.rmd",
package = "DataPackageR"
)
expect_null(
datapackage_skeleton(
name = "subsetCars",
path = tempdir(),
code_files = c(file),
force = TRUE,
r_object_names = c("cars_over_20")
)
)
package_build(file.path(tempdir(), "subsetCars"))
config <- yml_find(file.path(tempdir(), "subsetCars"))
config <- yml_add_files(config, "extra.rmd")
config <- yml_add_objects(config, "pressure")
file.copy(file2, file.path(tempdir(), "subsetCars", "data-raw"))
yml_write(config)
pkg <- desc::desc(file.path(tempdir(), "subsetCars"))
pkg$set("DataVersion", "0.0.0")
pkg$write()
package_build(file.path(tempdir(), "subsetCars"))
expect_equal(grep("Changed: cars_over_20",readLines(file.path(tempdir(), "subsetCars","NEWS.md"))),4)
unlink(file.path(tempdir(), "subsetCars"),
recursive = TRUE,
force = TRUE
)
}) |
test_that("bootstrap_dfm works with character and corpus objects", {
txt <- c(textone = "This is a sentence. Another sentence. Yet another.",
texttwo = "Premiere phrase. Deuxieme phrase.",
textthree = "Sentence three is really short.")
corp <- corpus(txt,
docvars = data.frame(country = c("UK", "USA", "UK"),
year = c(1990, 2000, 2005)))
set.seed(10)
bs1 <- bootstrap_dfm(corp, n = 10)
expect_equal(bs1[[1]], dfm(tokens(corp)))
bs2 <- bootstrap_dfm(txt, n = 10, verbose = TRUE)
expect_identical(bs2[[1]],
dfm(tokens(corp, include_docvars = FALSE)))
expect_identical(
featnames(bs2[[1]]),
featnames(bs2[[2]])
)
expect_identical(
docnames(bs2[[1]]),
docnames(bs2[[2]])
)
expect_error(bootstrap_dfm(txt, n = -1),
"The value of n must be between 0 and Inf")
expect_error(bootstrap_dfm(corp, n = -1),
"The value of n must be between 0 and Inf")
})
test_that("bootstrap_dfm works as planned with dfm", {
txt <- c(textone = "This is a sentence. Another sentence. Yet another.",
texttwo = "Premiere phrase. Deuxieme phrase.")
corp <- corpus(txt,
docvars = data.frame(country = c("UK", "USA"), year = c(1990, 2000)))
dfmt <- dfm(tokens(corpus_reshape(corp, to = "sentences")))
set.seed(10)
bs1 <- bootstrap_dfm(dfmt, n = 3, verbose = FALSE)
expect_equivalent(bs1[[1]],
dfm(tokens(corp)))
bs2 <- bootstrap_dfm(txt, n = 3, verbose = FALSE)
expect_identical(bs2[[1]],
dfm(tokens(corp, include_docvars = FALSE)))
expect_identical(
featnames(bs2[[1]]),
featnames(bs2[[2]])
)
expect_identical(
docnames(bs2[[1]]),
docnames(bs2[[2]])
)
})
test_that("verbose messages work", {
txt <- c(textone = "This is a sentence. Another sentence. Yet another.",
texttwo = "Premiere phrase. Deuxieme phrase.",
textthree = "Sentence three is really short.")
expect_message(
bootstrap_dfm(txt, n = 1, verbose = TRUE),
"Segmenting the .+ into sentences"
)
expect_message(
bootstrap_dfm(txt, n = 1, verbose = TRUE),
"resampling and forming dfms: 0"
)
}) |
BANOVA.ordMultiNormal <-
function(l1_formula = 'NA', l2_formula = 'NA', data, id, l1_hyper, l2_hyper, burnin, sample, thin, adapt, conv_speedup, jags){
cat('Model initializing...\n')
if (l1_formula == 'NA'){
stop("Formula in level 1 is missing or not correct!")
}else{
mf1 <- model.frame(formula = l1_formula, data = data)
y <- model.response(mf1)
if (class(y) != 'integer'){
warning("The response variable must be integers (data class also must be 'integer')..")
y <- as.integer(as.character(y))
warning("The response variable has been converted to integers..")
}
}
single_level = F
if (l2_formula == 'NA'){
single_level = T
DV_sort <- sort(unique(y))
n_categories <- length(DV_sort)
if (n_categories < 3) stop('The number of categories must be greater than 2!')
if (DV_sort[1] != 1 || DV_sort[n_categories] != n_categories) stop('Check if response variable follows categorical distribution!')
n.cut <- n_categories - 1
for (i in 1:ncol(data)){
if(class(data[,i]) != 'factor' && class(data[,i]) != 'numeric' && class(data[,i]) != 'integer') stop("data class must be 'factor', 'numeric' or 'integer'")
if ((class(data[,i]) == 'numeric' | class(data[,i]) == 'integer') & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id))
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.ordmultiNormal(dMatrice$X, dMatrice$Z, n.cut, l1_hyper, l2_hyper, conv_speedup)
JAGS.data <- dump.format(list(n = n, y = y, X = dMatrice$X, n.cut = n.cut))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters, JAGS.model$monitor.cutp),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
n_p_cutp <- length(JAGS.model$monitor.cutp)
index_cutp_param<- array(0,dim = c(n_p_cutp,1))
for (i in 1:n_p_cutp)
index_cutp_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitor.cutp[i])
if (length(index_cutp_param) > 1)
samples_cutp_param <- result$mcmc[[1]][,index_cutp_param]
else
samples_cutp_param <- matrix(result$mcmc[[1]][,index_cutp_param], ncol = 1)
cat('Constructing ANOVA/ANCOVA tables...\n')
dMatrice$Z <- array(1, dim = c(1,1), dimnames = list(NULL, ' '))
attr(dMatrice$Z, 'assign') <- 0
attr(dMatrice$Z, 'varNames') <- " "
samples_l2_param <- NULL
anova.table <- table.ANCOVA(samples_l2_param, dMatrice$Z, dMatrice$X, samples_l1_param, error = pi^2/6)
coef.tables <- table.coefficients(samples_l1_param, JAGS.model$monitorl1.parameters, colnames(dMatrice$Z), colnames(dMatrice$X),
attr(dMatrice$Z, 'assign') + 1, attr(dMatrice$X, 'assign') + 1, samples_cutp_param)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$Z, 'varNames'),
l2_names = attr(dMatrice$X, 'varNames'))
conv <- conv.geweke.heidel(samples_l1_param, colnames(dMatrice$Z), colnames(dMatrice$X))
mf2 <- NULL
class(conv) <- 'conv.diag'
cat('Done.\n')
}else{
mf2 <- model.frame(formula = l2_formula, data = data)
DV_sort <- sort(unique(y))
n_categories <- length(DV_sort)
if (n_categories < 2) stop('The number of categories must be greater than 1!')
if (DV_sort[1] != 1 || DV_sort[n_categories] != n_categories) stop('Check if response variable follows categorical distribution!')
n.cut <- n_categories - 1
for (i in 1:ncol(data)){
if(class(data[,i]) != 'factor' && class(data[,i]) != 'numeric' && class(data[,i]) != 'integer') stop("data class must be 'factor', 'numeric' or 'integer'")
if ((class(data[,i]) == 'numeric' | class(data[,i]) == 'integer') & length(unique(data[,i])) <= 3){
data[,i] <- as.factor(data[,i])
warning("Variables(levels <= 3) have been converted to factors")
}
}
n <- nrow(data)
uni_id <- unique(id)
num_id <- length(uni_id)
new_id <- rep(0, length(id))
for (i in 1:length(id))
new_id[i] <- which(uni_id == id[i])
id <- new_id
dMatrice <- design.matrix(l1_formula, l2_formula, data = data, id = id)
JAGS.model <- JAGSgen.ordmultiNormal(dMatrice$X, dMatrice$Z, n.cut, l2_hyper = l2_hyper, conv_speedup = conv_speedup)
JAGS.data <- dump.format(list(n = n, id = id, M = num_id, y = y, X = dMatrice$X, Z = dMatrice$Z, n.cut = n.cut))
result <- run.jags (model = JAGS.model$sModel, data = JAGS.data, inits = JAGS.model$inits, n.chains = 1,
monitor = c(JAGS.model$monitorl1.parameters, JAGS.model$monitorl2.parameters, JAGS.model$monitor.cutp),
burnin = burnin, sample = sample, thin = thin, adapt = adapt, jags = jags, summarise = FALSE,
method="rjags")
samples <- result$mcmc[[1]]
n_p_l2 <- length(JAGS.model$monitorl2.parameters)
index_l2_param<- array(0,dim = c(n_p_l2,1))
for (i in 1:n_p_l2)
index_l2_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl2.parameters[i])
if (length(index_l2_param) > 1)
samples_l2_param <- result$mcmc[[1]][,index_l2_param]
else
samples_l2_param <- matrix(result$mcmc[[1]][,index_l2_param], ncol = 1)
colnames(samples_l2_param) <- colnames(result$mcmc[[1]])[index_l2_param]
n_p_l1 <- length(JAGS.model$monitorl1.parameters)
index_l1_param<- array(0,dim = c(n_p_l1,1))
for (i in 1:n_p_l1)
index_l1_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitorl1.parameters[i])
if (length(index_l1_param) > 1)
samples_l1_param <- result$mcmc[[1]][,index_l1_param]
else
samples_l1_param <- matrix(result$mcmc[[1]][,index_l1_param], ncol = 1)
colnames(samples_l1_param) <- colnames(result$mcmc[[1]])[index_l1_param]
n_p_cutp <- length(JAGS.model$monitor.cutp)
index_cutp_param<- array(0,dim = c(n_p_cutp,1))
for (i in 1:n_p_cutp)
index_cutp_param[i] <- which(colnames(result$mcmc[[1]]) == JAGS.model$monitor.cutp[i])
if (length(index_cutp_param) > 1)
samples_cutp_param <- result$mcmc[[1]][,index_cutp_param]
else
samples_cutp_param <- matrix(result$mcmc[[1]][,index_cutp_param], ncol = 1)
cat('Constructing ANOVA/ANCOVA tables...\n')
anova.table <- table.ANCOVA(samples_l1_param, dMatrice$X, dMatrice$Z, samples_l2_param)
coef.tables <- table.coefficients(samples_l2_param, JAGS.model$monitorl2.parameters, colnames(dMatrice$X), colnames(dMatrice$Z),
attr(dMatrice$X, 'assign') + 1, attr(dMatrice$Z, 'assign') + 1, samples_cutp_param)
pvalue.table <- table.pvalue(coef.tables$coeff_table, coef.tables$row_indices, l1_names = attr(dMatrice$X, 'varNames'),
l2_names = attr(dMatrice$Z, 'varNames'))
conv <- conv.geweke.heidel(samples_l2_param, colnames(dMatrice$X), colnames(dMatrice$Z))
class(conv) <- 'conv.diag'
cat('Done...\n')
}
return(list(anova.table = anova.table,
coef.tables = coef.tables,
pvalue.table = pvalue.table,
conv = conv,
dMatrice = dMatrice, samples_l1_param = samples_l1_param, samples_l2_param = samples_l2_param, samples_cutp_param = samples_cutp_param, data = data,
mf1 = mf1, mf2 = mf2,JAGSmodel = JAGS.model$sModel, single_level = single_level, model_name = "BANOVA.ordMultinomial"))
} |
pauseTypes <- c('Pause', 'SwitchingPause',
'GrpPause', 'GrpSwitchingPause')
categories <- c('Vocalisation', 'SwitchingVocalisation', 'Pause', 'SwitchingPause',
'GrpPause', 'GrpSwitchingPause',
'GrpVocalisation')
catDescriptions <- array(dim=length(categories),dimnames=list(categories),
data=c('Vocalisation', 'Switching Vocalisation', 'Pause', 'Switching pause',
'Group pause', 'Group switching Pause',
'Group vocalisation'))
staticMatrix <- function (matrix, limit=1000, digits=4, history=F) {
exp <- 2
ma <- matrix
mb <- ma %*% matrix
if (history)
mseries <- list(ma, mb)
while (exp < limit && !all(round(ma,digits=digits) == round(mb, digits=digits))) {
exp <- exp + 1
ma <- mb
mb <- ma %*% matrix
if (history)
mseries[[exp]] <- mb
}
if (!history)
mseries <- list(matrix, mb)
if (exp == limit)
print(paste("staticMatrix: exp limit reached before convergence at matrix^",exp, sep=""))
else
print(paste("staticMatrix: values converged for matrix^",exp, sep=""))
class(mseries) <- 'matrixseries'
return(mseries)
}
matrixExp <- function(matrix, exp, mmatrix=matrix) {
if (exp < 1){
warning("matrixExp only accepts positive values")
}
i <- 1
while (i < exp){
i <- i + 1
mmatrix <- mmatrix %*% matrix
}
return(mmatrix)
}
plot.matrixseries <- function(x, ...,
par=list(), interact=F)
{
mseries <- x
op <- par(no.readonly = TRUE); on.exit(par(op))
par(par)
matrix <- startmatrix(mseries)
convpoint <- length(mseries)
mm <- mseries[[convpoint]]
taillen <- round(convpoint/4)
limit <- convpoint + taillen
mseries <- c(mseries,
lapply(1:taillen,
function(y){mm <<- mm %*% matrix}))
plot(sapply(1:limit, function(x){mseries[[x]][1,1]}), axes=F,
type='l', ylim=c(0,1), xlab='iteration',
ylab='amount of speech (steady-state value)',
...)
axis(1)
axis(2)
offs = limit/20
y = limit
names <- rownames(matrix)
for (j in 1:ncol(matrix)) {
y <- y - offs
print(paste("Plotting convergence for col ",j))
text(y, mseries[[limit]][1,j]+.02, labels=names[j])
for (i in 1:nrow(matrix)) {
if (i == 1 && j == 1)
next;
cseries <- sapply(1:limit, function(x){mseries[[x]][i,j]})
lines(cseries, col=j)
}
if (interact)
locator(1)
}
mseries
}
startmatrix <- function(mseries) UseMethod('startmatrix')
startmatrix.default <- function(mseries){
warning(paste("startmatrix() does not know how to handle object of class ",
class(mseries)))
}
startmatrix.matrixseries <- function(mseries){
mseries[[1]]
}
anonymise <- function(vd) UseMethod('anonymise')
anonymise.vocaldia <- function(vd){
excluded <- c(categories, "Grp", "Floor")
ordspk <- sort(vd$tdarray[!names(vd$tdarray) %in% excluded], decreasing=T)
idx <- pmatch(names(ordspk), names(vd$tdarray))
spkvars <- paste(rep("s",length(ordspk)), LETTERS[1:length(ordspk)], sep='')
names(vd$tdarray)[idx] <- spkvars
idx <- pmatch(names(ordspk), dimnames(vd$ttarray)[[1]])
dimnames(vd$ttarray)[[1]][idx] <- spkvars
idx <- pmatch(names(ordspk), dimnames(vd$ttarray)[[2]])
dimnames(vd$ttarray)[[2]][idx] <- spkvars
return(vd)
}
anonymise.default <- function(vd){
warning(paste("anonymise() does not know how to handle object of class ",
class(vd), '. Try passing a vocaldia.'))
}
identifyPauses <- function(vocvector){
vocvector <- as.character(vocvector)
indices <- which(vocvector=='Floor')
laindex <- length(vocvector)
vocvector <- as.character(vocvector)
for (i in indices){
if (i == 1 || i == laindex){
vocvector[i] <- 'Pause'
next
}
if (vocvector[i-1] == 'Grp' || vocvector[i-1] == 'GrpVocalisation'){
if (vocvector[i+1] == 'Grp' || vocvector[i+1] == 'GrpVocalisation')
vocvector[i] <- 'GrpPause'
else
vocvector[i] <- 'GrpSwitchingPause'
next
}
if (vocvector[i-1] == vocvector[i+1])
vocvector[i] <- 'Pause'
else
vocvector[i] <- 'SwitchingPause'
}
vocvector
}
identifyVocalisations <- function(vocvector, idswitchvoc=T){
vocvector <- as.character(vocvector)
vocvector <- identifyGrpVocalisations(vocvector)
vi <- which(!(vocvector %in% c(pauseTypes,categories,'Floor','Grp')))
if (idswitchvoc){
vsi <- vi[which(sapply(1:(length(vi)-1),
function(i){
vi[i+1]==vi[i]+1 &&
vocvector[vi[i]]!=vocvector[vi[i+1]]
}))]
vocvector[vi] <- 'Vocalisation'
vocvector[vsi] <- 'SwitchingVocalisation'
}
else
vocvector[vi] <- 'Vocalisation'
vocvector
}
identifyGrpVocalisations <- function(vocvector){
vocvector <- as.character(vocvector)
grpindices <- which(vocvector=='Grp')
vocvector[grpindices] <- 'GrpVocalisation'
vocvector
}
getPofAgivenB <- function(a, b, ttarray){
if (! all(c(a,b) %in% names(ttarray[1,])))
0
else
ttarray[b,a]
}
getEntropy <- function (distribution){
PtimesLOG2 <- distribution * log((1 / distribution), 2)
sum(PtimesLOG2[!is.na(PtimesLOG2)])
}
plot.vocaldia <- function(x, ...){
x
if (requireNamespace('igraph', quietly = TRUE)){
g <- igraph.vocaldia(x)
plot(g, layout=igraph::layout.fruchterman.reingold(g), ...)
return(g)
}
warning(paste('Package igraph not installed. Try installing igraph or "require(igraph)" if installed.'))
}
igraph.vocaldia <- function(vd, ...){
if (requireNamespace('igraph', quietly = TRUE)){
g <- igraph::graph.adjacency(vd$ttarray, weighted=T)
igraph::V(g)$label <- names(vd$ttarray[1,])
igraph::E(g)$label <- round(igraph::E(g)$weight,digits=3)
igraph::V(g)$size <- 25*exp(vd$tdarray)
g$layout <- igraph::layout.kamada.kawai(g)
return(g)
}
else
warning(paste('Package igraph not supported. Try installing igraph or "require(igraph)" if installed.'))
}
write.vocaldia <- function(vd, file="", ...){
o <- toDotNotation(vd, ...)
o <- paste('
if (file!="")
cat("Writing ", file, '\n')
cat(o, file=file)
}
toDotNotation <- function(vd, individual=T, varsizenode=T,
shape='circle',
fontsize=16, rankdir='LR',
nodeattribs='fixedsize=true;',
comment="")
{
head <- paste("
"\ndigraph finite_state_machine {\n",
'shape=',shape,';',
'fontsize=', fontsize,';',
'rankdir=', rankdir, ';',
nodeattribs)
links <- ""
nodes <- dimnames(vd$ttarray)[[1]]
for (i in nodes){
if (vd$tdarray[i] == 0) next
width <- log(1000*vd$tdarray[i],base=5)
width <- if (width < .4 ) .4 else width
if (individual){
nodelabel <- i
}
else if (width < .6) {
nodelabel <- catDescriptions[i]
}
else {
nodelabel <- catDescriptions[i]
}
head <- paste(head, " ", i,
"[",
(if (varsizenode) paste("width =", width,', ') else ""),
(if (varsizenode)
sprintf("label = \"%s \\n%.3f\"",
nodelabel,
vd$tdarray[i])
else
paste("label = \"",nodelabel,"\", ")
),
if (width < .6) "fontsize=8",
"];\n")
for (j in nodes) {
if (vd$ttarray[i,j] == 0) next
links <- paste(links, " ", i, "->", j,
"[ label =", sprintf("%.3f", vd$ttarray[i,j]),
"];\n")
}
}
o <- paste(head, links, "}\n")
return(o);
} |
library(testthat)
test_that("autotest", {
autotest_sdistribution(
sdist = Uniform,
pars = list(lower = 0, upper = 1),
traits = list(valueSupport = "continuous", variateForm = "univariate", type = Reals$new()),
support = Interval$new(0, 1),
symmetry = "symmetric",
mean = 0.5,
mode = NaN,
median = 0.5,
variance = 1 / 12,
skewness = 0,
exkur = -6 / 5,
entropy = 0,
mgf = exp(1) - 1,
cf = (exp(1i) - 1) / 1i,
pgf = NaN,
pdf = dunif(1:3),
cdf = punif(1:3),
quantile = qunif(c(0.24, 0.42, 0.5))
)
})
test_that("manual", {
expect_equal(Uniform$new()$mgf(0), 1)
expect_equal(Uniform$new()$cf(0), 1)
}) |
dna2codon <- function(x, codonstart=1, code=1, ambiguity="---", ...){
if(!inherits(x, "phyDat"))stop("x needs to be of class phyDat!")
if(attr(x, "type")=="AA")stop("x needs to be a nucleotide sequence!")
if(codonstart>1){
del <- -seq_len(codonstart)
x <- subset(x, select=del, site.pattern=FALSE)
}
n_sites <- sum(attr(x, "weight"))
if( (n_sites %% 3) ){
keep <- seq_len( (n_sites %/% 3) * 3 )
x <- subset(x, select=keep, site.pattern=FALSE)
}
phyDat.codon(as.character(x), ambiguity=ambiguity, code=code, ...)
}
codon2dna <- function(x){
if(!inherits(x, "phyDat"))stop("x needs to be of class phyDat!")
phyDat.DNA(as.character(x))
}
synonymous_subs <- function(code=1, stop.codon=FALSE){
tmp <- .CODON[, as.character(code)]
label <- rownames(.CODON)
l <- length(tmp)
res <- matrix(1, 64, 64, dimnames = list(label, label))
for(i in seq_len(64)){
for(j in seq_len(64)) {
if(tmp[i] == tmp[j]) res[i, j] <- 0
}
}
res[.ONE_TRANSITION == FALSE] <- -1
if(!stop.codon){
label <- label[tmp != "*"]
res <- res[label, label]
}
res[lower.tri(res)]
}
tstv_subs <- function(code=1, stop.codon=FALSE){
tmp <- .CODON[, as.character(code)]
label <- rownames(.CODON)
res <- .SUB
if(!stop.codon){
label <- label[tmp != "*"]
res <- res[label, label]
}
res[lower.tri(res)]
} |
vecInverse <- function(a,dmnVec=NULL)
{
is.wholenumber <- function(x, tol = sqrt(.Machine$double.eps))
return(abs(x - round(x)) < tol)
a <- as.vector(a)
if (is.null(dmnVec))
{
rtlena <- sqrt(length(a))
if (!is.wholenumber(sqrt(length(a))))
stop("The input vector is not of legal length.")
dmnVec <- rep(round(rtlena),2)
}
if (!is.null(dmnVec))
{
if (length(a)!=prod(dmnVec))
stop("The input vector is not of legal length.")
}
dim(a) <- dmnVec
return(a)
} |
as_list_unnamed <- function(x, ...) {
lifecycle::deprecate_soft("0.1.1", "as_list_unnamed()", "as_list()")
UseMethod("as_list_unnamed")
}
as_list_unnamed.default <- function(x, ...) {
x <- as.list(x)
names <- names(x)
attributes(x) <- NULL
if(!is.null(names))
names(x) <- names
x
}
as_list <- function(x, ...) {
UseMethod("as_list")
}
as_list.default <- function(x, ...) {
x <- as.list(x)
names <- names(x)
attributes(x) <- NULL
if(!is.null(names))
names(x) <- names
x
} |
test_that("geom_boxplot range includes all outliers", {
dat <- data_frame(x = 1, y = c(-(1:20) ^ 3, (1:20) ^ 3) )
p <- ggplot_build(ggplot(dat, aes(x,y)) + geom_boxplot())
miny <- p$layout$panel_params[[1]]$y.range[1]
maxy <- p$layout$panel_params[[1]]$y.range[2]
expect_true(miny <= min(dat$y))
expect_true(maxy >= max(dat$y))
})
test_that("geom_boxplot works in both directions", {
dat <- data_frame(x = 1, y = c(-(1:20) ^ 3, (1:20) ^ 3) )
p <- ggplot(dat, aes(x, y)) + geom_boxplot()
x <- layer_data(p)
expect_false(x$flipped_aes[1])
p <- ggplot(dat, aes(y, x)) + geom_boxplot()
y <- layer_data(p)
expect_true(y$flipped_aes[1])
x$flipped_aes <- NULL
y$flipped_aes <- NULL
expect_identical(x, flip_data(y, TRUE))
})
test_that("geom_boxplot for continuous x gives warning if more than one x (
dat <- expand.grid(x = 1:2, y = c(-(1:5) ^ 3, (1:5) ^ 3) )
bplot <- function(aes = NULL, extra = list()) {
ggplot_build(ggplot(dat, aes) + geom_boxplot(aes) + extra)
}
expect_warning(bplot(aes(x, y)), "Continuous x aesthetic")
expect_warning(bplot(aes(x, y), facet_wrap(~x)), "Continuous x aesthetic")
expect_warning(bplot(aes(Sys.Date() + x, y)), "Continuous x aesthetic")
expect_warning(bplot(aes(x, group = x, y)), NA)
expect_warning(bplot(aes(1, y)), NA)
expect_warning(bplot(aes(factor(x), y)), NA)
expect_warning(bplot(aes(x == 1, y)), NA)
expect_warning(bplot(aes(as.character(x), y)), NA)
})
test_that("can use US spelling of colour", {
df <- data_frame(x = 1, y = c(1:5, 100))
plot <- ggplot(df, aes(x, y)) + geom_boxplot(outlier.color = "red")
gpar <- layer_grob(plot)[[1]]$children[[1]]$children[[1]]$gp
expect_equal(gpar$col, "
})
test_that("boxes with variable widths do not overlap", {
df <- data_frame(
value = 1:12,
group = rep(c("a", "b", "c"), each = 4L),
subgroup = rep(c("A", "B"), times = 6L)
)
p <- ggplot(df, aes(group, value, colour = subgroup)) +
geom_boxplot(varwidth = TRUE)
d <- layer_data(p)[c("xmin", "xmax")]
xid <- find_x_overlaps(d)
expect_false(any(duplicated(xid)))
})
test_that("boxplots with a group size >1 error", {
p <- ggplot(
data_frame(x = "one value", y = 3, value = 4:6),
aes(x, ymin = 0, lower = 1, middle = y, upper = value, ymax = 10)
) +
geom_boxplot(stat = "identity")
expect_equal(nrow(layer_data(p, 1)), 3)
expect_error(layer_grob(p, 1), "Can't draw more than one boxplot")
})
test_that("boxplot draws correctly", {
expect_doppelganger("outlier colours",
ggplot(mtcars, aes(x = factor(cyl), y = drat, colour = factor(cyl))) + geom_boxplot(outlier.size = 5)
)
}) |
test_that("S3 degree functions work as expected", {
x <- c(0, 90, 180, 360)
y <- c(0, pi / 2, pi, pi * 2)
x1 <- as_degree(x)
expect_s3_class(x1, "circumplex_degree")
expect_equal(as.numeric(x1), x)
x2 <- as_degree(as_degree(x))
expect_s3_class(x2, "circumplex_degree")
expect_equal(as.numeric(x2), x)
x3 <- as_radian(as_degree(x))
expect_s3_class(x3, "circumplex_radian")
expect_equal(as.numeric(x3), y)
y1 <- as_radian(y)
expect_s3_class(y1, "circumplex_radian")
expect_equal(as.numeric(y1), y)
y2 <- as_radian(as_radian(y))
expect_s3_class(y2, "circumplex_radian")
expect_equal(as.numeric(y2), y)
y3 <- as_degree(as_radian(y))
expect_s3_class(y3, "circumplex_degree")
expect_equal(as.numeric(y3), x)
})
test_that("The ssm display methods is working", {
skip_on_cran()
data("aw2009")
res <- ssm_analyze(aw2009, PA:NO, octants())
expect_output(print(res), "Profile \\[All\\]:")
expect_output(summary(res), "Statistical Basis:\\t Mean Scores")
expect_output(summary(res), "Bootstrap Resamples:\\t 2000")
expect_output(summary(res), "Confidence Level:\\t 0\\.95")
expect_output(summary(res), "Listwise Deletion:\\t TRUE")
expect_output(summary(res), "Scale Displacements:\\t 90 135 180 225 270 315 360 45")
data("jz2017")
res <- ssm_analyze(jz2017, PA:NO, octants(), grouping = Gender)
expect_output(print(res), "Profile \\[Female\\]:")
expect_output(print(res), "Profile \\[Male\\]:")
res <- ssm_analyze(jz2017, PA:NO, octants(),
grouping = Gender,
contrast = "model"
)
expect_output(print(res), "Contrast \\[Male - Female\\]:")
res <- ssm_analyze(jz2017, PA:NO, octants(),
measures = PARPD,
grouping = Gender, contrast = "test"
)
expect_output(print(res), "Contrast \\[PARPD: Male - Female\\]:")
expect_output(summary(res), "Statistical Basis:\\t Correlation Scores")
}) |
Kan.IC = function(a,b,mu,Sigma){
n = length(mu)
s = sqrt(diag(Sigma))
seqq = seq_len(n)
a1 = a-mu
b1 = b-mu
Sigma = sym.matrix(Sigma)
logp = pmvnormt(lower = a,upper = b,mean = mu,sigma = Sigma,uselog2 = TRUE)
prob = 2^logp
if(prob < 1e-250){
return(corrector(a,b,mu,Sigma,bw=36))
}
run = Rcppqfun_ab(a1,b1,Sigma)
qa = run$qa
qb = run$qb
q = qa-qb
muY = mu+ Sigma%*%log2ratio(q,logp)
if(
any(b < mu - 10*sqrt(diag(Sigma))) |
any(a > mu + 10*sqrt(diag(Sigma))) |
any(muY < a | muY > b)){
return(corrector(a,b,mu,Sigma,bw=36))
}
D = matrix(0,n,n)
for(i in seqq){
D[i,i] = a[i]*qa[i]
D[i,i] = D[i,i]-b[i]*qb[i]
RR = Sigma[-i,-i]-Sigma[-i,i]%*%t(Sigma[i,-i])/Sigma[i,i]
ma = mu[-i]+Sigma[-i,i]/Sigma[i,i]*a1[i]
run1 = Rcppqfun_ab(a[-i]-ma,b[-i]-ma,RR)
qa1 = run1$qa
qb1 = run1$qb
wa = qa[i]*ma+dnorm(x = a[i],mean = mu[i],sd = s[i])*RR%*%(qa1-qb1)
mb = mu[-i]+Sigma[-i,i]/Sigma[i,i]*b1[i]
run2 = Rcppqfun_ab(a[-i]-mb,b[-i]-mb,RR)
qa2 = run2$qa
qb2 = run2$qb
wb = qb[i]*mb + dnorm(x = b[i],mean = mu[i],sd = s[i])*RR%*%(qa2-qb2)
D[i,-i] = wa-wb
}
varY = Sigma + Sigma%*%log2ratio(D - q%*%t(muY),logp)
varY = (varY + t(varY))/2
EYY = varY+muY%*%t(muY)
bool = diag(varY) < 0
if(sum(bool)>0){
out = corrector(a,b,mu,Sigma,bw=36)
out$mean = muY
out$EYY = out$varcov + out$mean%*%t(out$mean)
return(out)
}
return(list(mean = muY,EYY = EYY,varcov = varY))
}
Kan.LRIC = function(a,b,mu,Sigma){
n = length(mu)
s = sqrt(diag(Sigma))
seqq = seq_len(n)
a1 = a-mu
b1 = b-mu
Sigma = sym.matrix(Sigma)
logp = pmvnormt(lower = a,upper = b,mean = mu,sigma = Sigma,uselog2 = TRUE)
prob = 2^logp
if(prob < 1e-250){
return(corrector(a,b,mu,Sigma,bw=36))
}
run = Rcppqfun(a1,b1,Sigma)
qa = run$qa
qb = run$qb
q = qa-qb
muY = mu+ Sigma%*%log2ratio(q,logp)
if(any(b < mu - 10*sqrt(diag(Sigma))) |
any(a > mu + 10*sqrt(diag(Sigma))) | any(muY < a | muY > b)){
return(corrector(a,b,mu,Sigma,bw=36))
}
D = matrix(0,n,n)
for(i in seqq){
if(a[i] != -Inf){
D[i,i] = a[i]*qa[i]
}
if(b[i] != Inf){
D[i,i] = D[i,i]-b[i]*qb[i]
}
RR = Sigma[-i,-i]-Sigma[-i,i]%*%t(Sigma[i,-i])/Sigma[i,i]
if(a[i] == -Inf){
wa = matrix(0,n-1,1)
}else
{
ma = mu[-i]+Sigma[-i,i]/Sigma[i,i]*a1[i]
run1 = Rcppqfun(a[-i]-ma,b[-i]-ma,RR)
qa1 = run1$qa
qb1 = run1$qb
wa = qa[i]*ma+dnorm(x = a[i],mean = mu[i],sd = s[i])*RR%*%(qa1-qb1)
}
if(b[i] == Inf){
wb = matrix(0,n-1,1)
}else
{
mb = mu[-i]+Sigma[-i,i]/Sigma[i,i]*b1[i]
run2 = Rcppqfun(a[-i]-mb,b[-i]-mb,RR)
qa2 = run2$qa
qb2 = run2$qb
wb = qb[i]*mb + dnorm(x = b[i],mean = mu[i],sd = s[i])*RR%*%(qa2-qb2)
}
D[i,-i] = wa-wb
}
varY = Sigma + Sigma%*%log2ratio(D - q%*%t(muY),logp)
varY = (varY + t(varY))/2
EYY = varY+muY%*%t(muY)
bool = diag(varY) < 0
if(sum(bool)>0){
out = corrector(a,b,mu,Sigma,bw=36)
out$mean = muY
out$EYY = out$varcov + out$mean%*%t(out$mean)
return(out)
}
return(list(mean = muY,EYY = EYY,varcov = varY))
}
Kan.RC = function(b,mu,Sigma){
n = length(mu)
s = sqrt(diag(Sigma))
seqq = seq_len(n)
b1 = b-mu
Sigma = sym.matrix(Sigma)
logp = pmvnormt(upper = b,mean = mu,sigma = Sigma,uselog2 = TRUE)
prob = 2^logp
if(prob < 1e-250){
return(corrector(upper = b,mu = mu,Sigma = Sigma,bw=36))
}
qb = Rcppqfun_b(b1,Sigma)
muY = mu - Sigma%*%log2ratio(qb,logp)
if(any(b < mu - 10*sqrt(diag(Sigma))) | any(muY > b)){
return(corrector(upper = b,mu = mu,Sigma = Sigma,bw=36))
}
D = matrix(0,n,n)
for(i in seqq){
D[i,i] = D[i,i]-b[i]*qb[i]
RR = Sigma[-i,-i]-Sigma[-i,i]%*%t(Sigma[i,-i])/Sigma[i,i]
mb = mu[-i]+Sigma[-i,i]/Sigma[i,i]*b1[i]
qb2 = Rcppqfun_b(b[-i]-mb,RR)
wb = qb[i]*mb - dnorm(x = b[i],mean = mu[i],sd = s[i])*RR%*%qb2
D[i,-i] = -wb
}
varY = Sigma + Sigma%*%log2ratio(D + qb%*%t(muY),logp)
varY = (varY + t(varY))/2
EYY = varY+muY%*%t(muY)
bool = diag(varY) < 0
if(sum(bool)>0){
out = corrector(upper = b,mu = mu,Sigma = Sigma,bw=36)
out$mean = muY
out$EYY = out$varcov + out$mean%*%t(out$mean)
return(out)
}
return(list(mean = muY,EYY = EYY,varcov = varY))
} |
NULL
.iotsecuretunneling$close_tunnel_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(tunnelId = structure(logical(0), tags = list(type = "string")), delete = structure(logical(0), tags = list(box = TRUE, type = "boolean"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$close_tunnel_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$describe_tunnel_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(tunnelId = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$describe_tunnel_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(tunnel = structure(list(tunnelId = structure(logical(0), tags = list(type = "string")), tunnelArn = structure(logical(0), tags = list(type = "string")), status = structure(logical(0), tags = list(type = "string")), sourceConnectionState = structure(list(status = structure(logical(0), tags = list(type = "string")), lastUpdatedAt = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")), destinationConnectionState = structure(list(status = structure(logical(0), tags = list(type = "string")), lastUpdatedAt = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure")), description = structure(logical(0), tags = list(type = "string")), destinationConfig = structure(list(thingName = structure(logical(0), tags = list(type = "string")), services = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")), timeoutConfig = structure(list(maxLifetimeTimeoutMinutes = structure(logical(0), tags = list(box = TRUE, type = "integer"))), tags = list(type = "structure")), tags = structure(list(structure(list(key = structure(logical(0), tags = list(type = "string")), value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), createdAt = structure(logical(0), tags = list(type = "timestamp")), lastUpdatedAt = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$list_tags_for_resource_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(resourceArn = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$list_tags_for_resource_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(tags = structure(list(structure(list(key = structure(logical(0), tags = list(type = "string")), value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$list_tunnels_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(thingName = structure(logical(0), tags = list(type = "string")), maxResults = structure(logical(0), tags = list(box = TRUE, type = "integer")), nextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$list_tunnels_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(tunnelSummaries = structure(list(structure(list(tunnelId = structure(logical(0), tags = list(type = "string")), tunnelArn = structure(logical(0), tags = list(type = "string")), status = structure(logical(0), tags = list(type = "string")), description = structure(logical(0), tags = list(type = "string")), createdAt = structure(logical(0), tags = list(type = "timestamp")), lastUpdatedAt = structure(logical(0), tags = list(type = "timestamp"))), tags = list(type = "structure"))), tags = list(type = "list")), nextToken = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$open_tunnel_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(description = structure(logical(0), tags = list(type = "string")), tags = structure(list(structure(list(key = structure(logical(0), tags = list(type = "string")), value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list")), destinationConfig = structure(list(thingName = structure(logical(0), tags = list(type = "string")), services = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure")), timeoutConfig = structure(list(maxLifetimeTimeoutMinutes = structure(logical(0), tags = list(box = TRUE, type = "integer"))), tags = list(type = "structure"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$open_tunnel_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(tunnelId = structure(logical(0), tags = list(type = "string")), tunnelArn = structure(logical(0), tags = list(type = "string")), sourceAccessToken = structure(logical(0), tags = list(type = "string", sensitive = TRUE)), destinationAccessToken = structure(logical(0), tags = list(type = "string", sensitive = TRUE))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$tag_resource_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(resourceArn = structure(logical(0), tags = list(type = "string")), tags = structure(list(structure(list(key = structure(logical(0), tags = list(type = "string")), value = structure(logical(0), tags = list(type = "string"))), tags = list(type = "structure"))), tags = list(type = "list"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$tag_resource_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$untag_resource_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(resourceArn = structure(logical(0), tags = list(type = "string")), tagKeys = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotsecuretunneling$untag_resource_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(), tags = list(type = "structure"))
return(populate(args, shape))
} |
context("Density map color vector")
colvector <-
rev(colorRampPalette(RColorBrewer::brewer.pal(8, "Spectral"))(25))
lgname <- rep("LG1",25)
posvector <- seq(1:25)
df <- data.frame(group=lgname,pos=posvector)
test_that("25 Colors - equal densties", {
expect_equal(lmvdencolor(df, colorin=colvector)$col, c("
"
"
"
"
}) |
context('add.fragment.coordinates');
test_that('Throws error on bad input', {
expect_error( add.fragment.coordinates( 'hello' ) );
expect_error( add.fragment.coordinates( 5 ) );
expect_error( add.fragment.coordinates( list() ) );
});
test_that('Returns same object if no columns to expand', {
input <- data.table(
x = rnorm(10),
y = rnorm(10)
);
expect_equal(
add.fragment.coordinates(input),
input
);
expect_equal(
add.fragment.coordinates( data.table() ),
data.table()
);
});
test_that('Expands bait.id correctly', {
input <- data.table(
x = rnorm(2),
bait.id = c('chr1:0-100', 'chr10:100-200')
);
expected.output <- cbind(
input,
data.table(
bait.chr = c('chr1', 'chr10'),
bait.start = c(0, 100),
bait.end = c(100, 200)
)
);
expect_equal(
add.fragment.coordinates(input),
expected.output
);
});
test_that('Expands target.id correctly', {
input <- data.table(
x = rnorm(2),
target.id = c('HPV-2:10-110', '10:100-200')
);
expected.output <- cbind(
input,
data.table(
target.chr = c('HPV-2', '10'),
target.start = c(10, 100),
target.end = c(110, 200)
)
);
expect_equal(
add.fragment.coordinates(input),
expected.output
);
});
test_that('Expands both bait.id and target.id correctly', {
input <- data.table(
x = rnorm(2),
bait.id = c('chr1:0-100', 'chr10:100-200'),
target.id = c('HPV-2:10-110', 'chr7:100-200')
);
expected.output <- cbind(
input,
data.table(
target.chr = c('HPV-2', 'chr7'),
target.start = c(10, 100),
target.end = c(110, 200),
bait.chr = c('chr1', 'chr10'),
bait.start = c(0, 100),
bait.end = c(100, 200)
)
);
expect_equal(
add.fragment.coordinates(input),
expected.output
);
}); |
summary.ov <- function(object, model_results, sig_level=0.05, progress = TRUE, ...){
temp = prep_for_plots(object, p_contours = stats::coef(summary(model_results$mod_results))[2,4])
raw_treat = object$trt_effect[which(object$es_grid<.000000001 & object$es_grid>-.000000001),
which(object$rho_grid==0)]
raw_pval = object$p_val[which(object$es_grid<.000000001 & object$es_grid>-.000000001),
which(object$rho_grid==0)]
pvals = rep(NA, nrow(temp$obs_cors))
trt_effect = rep(NA, nrow(temp$obs_cors))
pb <- progress::progress_bar$new(
format = " running simulation [:bar] :percent completed in :elapsed",
total = nrow(temp$obs_cors), clear = FALSE, width= 60)
for(i in 1:nrow(temp$obs_cors)){
calculate_exact = ov_sim(model_results = model_results,
plot_covariates = object$cov,
rho_grid = temp$obs_cors$Cor_Outcome[i],
es_grid=temp$obs_cors$ES[i],
n_reps = object$n_reps)
trt_effect[i] = calculate_exact$trt_effect[[1]]
pvals[i] = calculate_exact$p_val[[1]]
if(progress == TRUE){
pb$tick()
Sys.sleep(1 / nrow(temp$obs_cors))
}
}
effect_size_text = dplyr::case_when((raw_treat < 0 & all(trt_effect < 0)) |
raw_treat >= 0 & all(trt_effect >= 0) ~ "no sign changes",
raw_treat < 0 & all(trt_effect >= 0) |
raw_treat >=0 & all(trt_effect < 0) ~ "all sign changes",
TRUE ~ "some sign changes")
if(effect_size_text == "no sign changes"){
diff_which.max = which.max(abs(trt_effect - raw_treat))
most_extreme = trt_effect[diff_which.max]
text = paste0("The sign of the estimated effect is expected to remain consistent when simulated unobserved confounders have the same strength of association with the treatment indicator and outcome that are seen in the observed confounders. In the most extreme observed case, the estimated treatment effect shifts from ", round(raw_treat,3), " to ", round(most_extreme,3), ".")
} else if(effect_size_text == "all sign changes"){
diff_which.max = which.max(abs(trt_effect - raw_treat))
most_extreme = trt_effect[diff_which.max]
text = paste0("The sign of the estimated effect is *not* expected to be robust to unobserved confounders that have the same strength of association with the treatment indicator and outcome that are seen in any of the observed confounders. In the most extreme observed case in which the sign changes, the estimated treatment effect shifts from ", round(raw_treat,3), " to ", round(most_extreme,3), ".")
} else if(effect_size_text == "some sign changes"){
if(raw_treat < 0){
change = length(which(trt_effect >= 0))
which.change = which(trt_effect >= 0)
nochange = length(which(trt_effect < 0))
total = nrow(temp$obs_cors)
changes = temp$obs_cors$cov[which(trt_effect >=0)]
} else{
change = length(which(trt_effect < 0))
which.change = which(trt_effect < 0)
nochange = length(which(trt_effect >= 0))
total = nrow(temp$obs_cors)
changes = temp$obs_cors$cov[which(trt_effect < 0)]
}
diff_which.max = which.max(abs(trt_effect[which.change] - raw_treat))
most_extreme = trt_effect[which.change][diff_which.max]
text = paste0("The sign of the estimated effect is expected to remain consistent when simulated unobserved confounders have the same strength of associations with the treatment indicator and outcome that are seen in ", nochange, " of the ", total, " observed confounders. In the most extreme observed case in which the sign changes, the estimated treatment effect shifts from ", round(raw_treat,3), " to ", round(most_extreme,3), ". The sign of the estimate would not be expected to be preserved for unobserved confounders that have the same strength of association with the treatment indicator and outcome as ", paste(changes, collapse=", "), ".")
}
if(raw_pval < sig_level & all(pvals < sig_level)){
text_p = paste0("Statistical significance at the ", sig_level, " level is expected to be robust to unobserved confounders with strengths of associations with the treatment indicator and outcome that are seen in the observed confounders. In the most extreme observed case, the p-value would be expected to increase from ", format(round(raw_pval,3), nsmall=3), " to ", format(round(max(pvals),3), nsmall=3), ".")
} else if(raw_pval < sig_level & all(pvals > sig_level)){
text_p = paste0("Statistical significance at the ", sig_level, " level is *not* expected to be robust to unobserved confounders with strengths of associations with the treatment indicator and outcome that are seen in any of the observed confounders. In the most extreme observed case, the p-value would be expected to increase from ", format(round(raw_pval,3), nsmall=3), " to ", format(round(max(pvals),3), nsmall=3), ".")
} else if(raw_pval < sig_level & !(all(pvals<sig_level) | all(pvals >sig_level))){
nonsig = temp$obs_cors$cov[which(pvals>sig_level)]
total = nrow(temp$obs_cors)
sig_count = total - length(nonsig)
text_p = paste0("Statistical significance at the ", sig_level, " level is expected to be robust to unobserved confounders with strengths of associations with the treatment indicator and outcome that are seen in ", sig_count, " of the ", total, " observed confounders. In the most extreme observed case, the p-value would be expected to increase from ", format(round(raw_pval,3), nsmall=3), " to ", format(round(max(pvals),3), nsmall=3), ". Significance at the ", sig_level, " level would not be expected to be preserved for unobserved confounders that have the same strength of association with the treatment indicator and outcome as ", paste(nonsig, collapse=", "),".")
}
print("Recommendation for reporting the sensitivity analyses")
if(raw_pval < 0.05){
print(text)
print(text_p)
} else{
print(text)
}
} |
options(na.action=na.exclude)
options(contrasts=c('contr.treatment', 'contr.poly'))
library(survival)
test2 <- data.frame(start=c(1, 2, 5, 2, 1, 7, 3, 4, 8, 8),
stop =c(2, 3, 6, 7, 8, 9, 9, 9,14,17),
event=c(1, 1, 1, 1, 1, 1, 1, 0, 0, 0),
x =c(1, 0, 0, 1, 0, 1, 1, 1, 0, 0))
byhand <- function(beta, newx=0) {
r <- exp(beta)
loglik <- 4*beta - (log(r+1) + log(r+2) + 2*log(3*r+2) + 2*log(3*r+1) +
log(2*r +2))
u <- 1/(r+1) + 1/(3*r+1) + 2*(1/(3*r+2) + 1/(2*r+2)) -
( r/(r+2) +3*r/(3*r+2) + 3*r/(3*r+1))
imat <- r*(1/(r+1)^2 + 2/(r+2)^2 + 6/(3*r+2)^2 +
6/(3*r+1)^2 + 6/(3*r+2)^2 + 4/(2*r +2)^2)
hazard <-c( 1/(r+1), 1/(r+2), 1/(3*r+2), 1/(3*r+1), 1/(3*r+1),
1/(3*r+2), 1/(2*r +2) )
wtmat <- matrix(c(1,0,0,0,1, 0, 0,0,0,0,
0,1,0,1,1, 0, 0,0,0,0,
0,0,1,1,1, 0, 1,1,0,0,
0,0,0,1,1, 0, 1,1,0,0,
0,0,0,0,1, 1, 1,1,0,0,
0,0,0,0,0, 1, 1,1,1,1,
0,0,0,0,0,.5,.5,1,1,1), ncol=7)
wtmat <- diag(c(r,1,1,r,1,r,r,r,1,1)) %*% wtmat
x <- c(1,0,0,1,0,1,1,1,0,0)
status <- c(1,1,1,1,1,1,1,0,0,0)
xbar <- colSums(wtmat*x)/ colSums(wtmat)
n <- length(x)
hazmat <- wtmat %*% diag(hazard)
dM <- -hazmat
for (i in 1:5) dM[i,i] <- dM[i,i] +1
dM[6:7,6:7] <- dM[6:7,6:7] +.5
mart <- rowSums(dM)
resid <- dM * outer(x, xbar, '-')
score <- rowSums(resid)
scho <- colSums(resid)
scho[6:7] <- rep(mean(scho[6:7]), 2)
list(loglik=loglik, u=u, imat=imat, xbar=xbar, haz=hazard,
mart=mart, score=score, rmat=resid,
scho=scho)
}
aeq <- function(x,y) all.equal(as.vector(x), as.vector(y))
fit0 <-coxph(Surv(start, stop, event) ~x, test2, iter=0)
truth0 <- byhand(0,0)
aeq(truth0$loglik, fit0$loglik[1])
aeq(1/truth0$imat, fit0$var)
aeq(truth0$mart, fit0$resid)
aeq(truth0$scho, resid(fit0, 'schoen'))
aeq(truth0$score, resid(fit0, 'score'))
fit <- coxph(Surv(start, stop, event) ~x, test2, eps=1e-8, nocenter=NULL)
truth <- byhand(fit$coef, 0)
aeq(truth$loglik, fit$loglik[2])
aeq(1/truth$imat, fit$var)
aeq(truth$mart, fit$resid)
aeq(truth$scho, resid(fit, 'schoen'))
aeq(truth$score, resid(fit, 'score'))
test2b <- rbind(test2, test2, test2)
test2b$group <- rep(1:3, each= nrow(test2))
test2b$start <- test2b$start + test2b$group
test2b$stop <- test2b$stop + test2b$group
fit0 <- coxph(Surv(start, stop, event) ~ x + strata(group), test2b, iter=0)
aeq(3*truth0$loglik, fit0$loglik[1])
aeq(3*truth0$imat, 1/fit0$var)
aeq(rep(truth0$mart,3), fit0$resid)
aeq(rep(truth0$scho,3), resid(fit0, 'schoen'))
aeq(rep(truth0$score,3), resid(fit0, 'score'))
fit3 <- coxph(Surv(start, stop, event) ~x + strata(group), test2b, eps=1e-8)
aeq(3*truth$loglik, fit3$loglik[2])
aeq(3*truth$imat, 1/fit3$var)
aeq(rep(truth$mart,3), fit3$resid)
aeq(rep(truth$scho,3), resid(fit3, 'schoen'))
aeq(rep(truth$score,3), resid(fit3, 'score'))
resid(fit)
resid(fit, 'scor')
resid(fit, 'scho')
predict(fit, type='lp')
predict(fit, type='risk')
predict(fit, type='expected')
predict(fit, type='terms')
predict(fit, type='lp', se.fit=T)
predict(fit, type='risk', se.fit=T)
predict(fit, type='expected', se.fit=T)
predict(fit, type='terms', se.fit=T)
summary(survfit(fit))
summary(survfit(fit, list(x=2))) |
context("RP")
library(MASS)
run_data_test <- function(data, alg, r=NULL, sep=TRUE, piled=FALSE, p=.05){
result <- lapply(data, function(dat) {
if (piled) {
classifier.alg = lol.classify.nearestCentroid
classifier.return = NaN
} else {
classifier.alg = lda
classifier.return = "class"
}
result <- expect_error(lol.xval.eval(dat$X, dat$Y, r, alg=alg, classifier=classifier.alg,
classifier.return=classifier.return, k=20), NA)
if (!isTRUE(piled)) {
if (!is.null(r)) {
expect_equal(dim(result$model$Xr), c(n, r))
}
} else {
for (ylab in unique(dat$Y)) {
expect_equal(length(unique(round(result$model$Xr[dat$Y == ylab, 1]*10000))), 1)
}
}
return(result$lhats)
})
if (sep) {
expect_lt(wilcox.test(result$separable, result$unseparable, alternative="less", exact=FALSE)$p.value, p)
}
return(result)
}
suppressWarnings(RNGversion("3.5.0"))
set.seed(123456)
alg=lol.project.rp
n <- 100
d <- 6
K <- 2
data <- list(separable=lol.sims.rtrunk(n, d),
unseparable=lol.sims.xor2(n, d))
p=0.1
test_that("RP full-rank fails for r > d", {
expect_error(alg(X=data$separable$X, Y=data$separable$Y, r=d+1))
})
test_that("RP full-rank r == d", {
r <- d
run_data_test(data, alg=alg, r, p=p)
})
test_that("RP full-rank r == K+1", {
r <- K+1
run_data_test(data, alg=alg, r, p=p)
})
test_that("RP full-rank r == K", {
r <- K
run_data_test(data, alg=alg, r=r, p=p)
})
test_that("RP full-rank r == 1", {
r <- 1
run_data_test(data, alg=alg, r=r, p=p)
})
set.seed(1234)
n <- 100
d <- 110
K <- 2
data <- list(separable=lol.sims.rtrunk(n, d),
unseparable=lol.sims.xor2(n, d))
p=0.3
test_that("RP low-rank fails for r > d", {
expect_error(alg(X=data$separable$X, Y=data$separable$Y, r=d+1))
})
test_that("RP low-rank r == K+1", {
r <- K+1
run_data_test(data, alg=alg, r=r, p=p)
})
test_that("RP low-rank r == K", {
r <- K
run_data_test(data, alg=alg, r=r, p=p)
})
test_that("RP low-rank r == 1", {
r <- 1
run_data_test(data, alg=alg, r=r, p=p)
})
n <- 100
d <- 3
test_that("RP works with multi-class", {
data <- lol.sims.mean_diff(n, d, K=d+1, md=3)
expect_error(alg(X=data$X, Y=data$Y, r=d-1), NA)
}) |
"RFcop" <- function(u, v, para=NULL, rho=NULL, tau=NULL,
fit=c('rho', 'tau'), ...) {
if(is.null(para)) {
fit <- match.arg(fit)
if(is.null(tau) & is.null(rho)) {
if(fit == "rho") {
rho <- cor(u,v, method="spearman")
} else {
tau <- cor(u,v, method="kendall")
}
}
rt <- NULL
if(is.null(rho)) {
try(rt <- uniroot(function(t) { 2*t/(3-t) - tau}, interval=c(0,1)), silent=TRUE)
if(is.null(rt)) {
warning("could not uniroot the Theta from the Tau")
return(NULL)
}
para <- rt$root
names(para) <- "theta"
names(tau) <- "Kendall Tau"
return(list(para=para, tau=tau))
} else {
try(rt <- uniroot(function(t) { t*(4-3*t)/(2-t)^2 - rho}, interval=c(0,1)), silent=TRUE)
if(is.null(rt)) {
warning("could not uniroot the Theta from the Rho")
return(NULL)
}
para <- rt$root
names(para) <- "theta"
names(rho) <- "Spearman Rho"
return(list(para=para, rho=rho))
}
}
if(length(para) == 1) {
if(para < 0 | para > 1) {
warning("Parameter must be 0 <= Theta <= 1")
return(NULL)
}
tau <- 2*para/( 3-para)
rho <- para*(4-3*para)/(2-para)^2
} else {
warning("Parameter Theta can not be a vector")
return(NULL)
}
if(length(u) > 1 & length(v) > 1 & length(u) != length(v)) {
warning("length u = ", length(u), " and length v = ", length(v))
warning("longer object length is not a multiple of shorter object length, ",
"no recycling")
return(NA)
}
if(length(u) == 1) {
u <- rep(u, length(v))
} else if(length(v) == 1) {
v <- rep(v, length(u))
}
m <- 1 - para; p <- 1 + para; g <- 1:length(u)
rng <- sapply(g, function(i) range(c(u[i], v[i])))
mx <- sapply(g, function(i) max(c(u[i],v[i])))
mn <- sapply(g, function(i) min(c(u[i],v[i])))
cop <- mn + (m/p)*(u*v)^(1/m)*(1 - mx^(-p/m))
if(any(is.nan(cop))) cop[is.nan(cop)] <- mn[is.nan(cop)]
if(any(! is.finite(cop))) cop[! is.finite(cop)] <- mn[! is.finite(cop)]
return(cop)
} |
FrF2old <- function(nruns=NULL, nfactors=NULL,
factor.names = if(!is.null(nfactors)) {if(nfactors<=50) Letters[1:nfactors]
else paste("F",1:nfactors,sep="")} else NULL,
default.levels = c(-1,1), ncenter=0, center.distribute=NULL,
generators=NULL, design=NULL, resolution=NULL, select.catlg=catlg,
estimable=NULL, clear=TRUE, method="VF2", sort="natural",
res3=FALSE, max.time=60,
perm.start=NULL, perms=NULL, MaxC2=FALSE,
replications=1, repeat.only=FALSE,
randomize=TRUE, seed=NULL, alias.info=2,
blocks=1, block.name="Blocks", bbreps=replications, wbreps=1, alias.block.2fis = FALSE,
hard=NULL, check.hard=10, WPs=1, nfac.WP=0, WPfacs=NULL, check.WPs=10, ...){
creator <- sys.call()
catlg.name <- deparse(substitute(select.catlg))
nichtda <- "try-error" %in% class(try(eval(parse(text=paste(catlg.name,"[1]",sep=""))),silent=TRUE))
if (nichtda){
catlgs128 <- c("catlg128.8to15","catlg128.26to33",paste("catlg128",16:25,sep="."))
if (catlg.name %in% catlgs128){
if (!requireNamespace("FrF2.catlg128", quietly=TRUE, character.only=TRUE))
stop("Package FrF2.catlg128 is not available")
if (packageVersion("FrF2.catlg128") < numeric_version(1.2)){
if (catlg.name %in% catlgs128[c(1,3:11)])
stop("For this version of package FrF2.catlg128,\n",
"load ", catlg.name, " with the command data(", catlg.name,")\n",
"and then rerun the FrF2 command.\n",
"Alternatively, install the latest version of package FrF2.catlg128.")
else stop("You need to get the latest version of package FrF2.catlg128 for using ", catlg.name)
}
}
else stop(catlg.name, " not available")
}
if (!"catlg" %in% class(select.catlg)) stop("invalid choice for select.catlg")
if (!is.numeric(ncenter)) stop("ncenter must be a number")
if (!length(ncenter)==1) stop("ncenter must be a number")
if (!ncenter==floor(ncenter)) stop("ncenter must be an integer number")
if (is.null(center.distribute)){
if (!randomize) center.distribute <- min(ncenter, 1)
else center.distribute <- min(ncenter, 3)}
if (!is.numeric(center.distribute)) stop("center.distribute must be a number")
if (!center.distribute==floor(center.distribute)) stop("center.distribute must be an integer number")
if (center.distribute > ncenter)
stop("center.distribute can be at most ncenter")
if (randomize & center.distribute==1) warning("running all center point runs together is usually not a good idea.")
block.name <- make.names(block.name)
if (ncenter>0 & !identical(WPs,1)) stop("center points for split plot designs are not supported")
if (!(is.null(generators) | (identical(WPs,1) | !is.null(WPfacs)))) stop("generators can only be used with split-plot designs, if WPfacs are specified.")
if (!is.null(nruns)) if (ncenter>0) if (center.distribute > nruns + 1)
stop("center.distribute must not be larger than nruns+1")
if (!(is.null(design) | is.null(estimable))) stop("design and estimable must not be specified together.")
if (!(is.null(generators) | is.null(design))) stop("generators and design must not be specified together.")
if (is.null(nruns) & !(is.null(generators))) stop("If generators is specified, nruns must be given.")
if (!(is.null(generators) | is.null(estimable))) stop("generators and estimable must not be specified together.")
if (!(identical(blocks,1) | is.null(estimable))) stop("blocks and estimable must not be specified together.")
if (!(identical(WPs,1) | is.null(estimable))) stop("WPs and estimable must not be specified together.")
if (!(is.null(hard) | is.null(estimable))) stop("hard and estimable must not be specified together.")
if (!(identical(blocks,1) | identical(WPs,1))) stop("blocks and WPs must not be specified together.")
if (!(identical(blocks,1) | is.null(hard))) stop("blocks and hard must not be specified together.")
if (!(identical(WPs,1) | is.null(hard))) stop("WPs and hard must not be specified together.")
if (identical(blocks,1) & !identical(wbreps,1)) stop("wbreps must not differ from 1, if blocks = 1.")
if (!(is.null(WPfacs) | identical(WPs,1)) & is.null(design) & is.null(generators))
stop("WPfacs requires explicit definition of a design via design or generators.")
if (identical(nfac.WP,0) & is.null(WPfacs) & !identical(WPs,1))
stop("WPs whole plots require specification of whole plot factors through nfac.WP or WPfacs!")
if (!(is.null(resolution) | is.null(estimable))) stop("You can only specify resolution OR estimable.")
if (!(is.null(resolution) | is.null(nruns))) warning("resolution is ignored, if nruns is given.")
if (default.levels[1]==default.levels[2]) stop("Both default levels are identical.")
if (!(is.logical(clear) & is.logical(res3) & is.logical(MaxC2) & is.logical(repeat.only)
& is.logical(randomize) & is.logical(alias.block.2fis) ))
stop("clear, res3, MaxC2, repeat.only, randomize, and alias.block.2fis must be logicals (TRUE or FALSE).")
if (!is.numeric(max.time))
stop("max.time must be a positive maximum run time for searching a design with estimable given and clear=FALSE.")
if (!is.numeric(check.hard)) stop("check.hard must be an integer number.")
if (!is.numeric(check.WPs)) stop("check.WPs must be an integer number.")
check.hard <- floor(check.hard)
check.WPs <- floor(check.WPs)
if (!is.numeric(bbreps)) stop("bbreps must be an integer number.")
if (!is.numeric(wbreps)) stop("wbreps must be an integer number.")
if (!is.numeric(replications)) stop("replications must be an integer number.")
if (bbreps > 1 & identical(blocks,1) & !replications > 1)
stop("Use replications, not bbreps, for specifying replications for unblocked designs.")
if (!alias.info %in% c(2,3))
stop("alias.info can be 2 or 3 only.")
if (!(is.numeric(default.levels) | is.character(default.levels)))
stop("default.levels must be a numeric or character vector of length 2")
if (!length(default.levels) ==2)
stop("default.levels must be a numeric or character vector of length 2")
if (!(is.null(hard) | is.numeric(hard)))
stop("hard must be numeric.")
if (!(is.null(resolution) | is.numeric(resolution)))
stop("resolution must be numeric.")
if (is.numeric(resolution)) if(!(resolution == floor(resolution) & resolution>=3))
stop("resolution must be an integer number (at least 3), if specified.")
res.WP <- NULL
if (!is.null(design)){
if (!is.character(design)) stop("design must be a character string.")
if (!length(design)==1) stop("design must be one character string.")
if (design %in% names(select.catlg)){
cand <- select.catlg[design]
if (!is.null(nruns)) {if (!nruns==cand[[1]]$nruns)
stop("selected design does not have the desired number of runs.")}
else nruns <- cand[[1]]$nruns
if (!is.null(factor.names)) {if (!length(factor.names)==cand[[1]]$nfac)
stop("selected design does not have the number of factors specified in factor.names.")}
if (!is.null(nfactors)) {if (!nfactors==cand[[1]]$nfac)
stop("selected design does not have the number of factors specified in nfactors.")}
else nfactors <- cand[[1]]$nfac
}
else stop("invalid entry for design")
}
if (!is.null(nruns)){
k <- round(log2(nruns))
if (!2^k==nruns) stop("nruns must be a power of 2.")
if (nruns < 4 | nruns > 4096) stop("less than 4 or more than 4096 runs are not covered by FrF2.")
}
if (is.null(factor.names) & is.null(nfactors) & (is.null(nruns) | is.null(generators)) & is.null(estimable))
stop("The number of factors must be specified via nfactors, via factor.names, via estimable, through selecting
one specific catalogued design or via nruns together with generators.")
if (!is.null(factor.names) & !(is.character(factor.names) | is.list(factor.names)) )
stop("factor.names must be a character vector or a list.")
if (is.null(nfactors)) {if (!is.null(factor.names)) nfactors <- length(factor.names)
else if (!is.null(generators)) nfactors <- length(generators)+k
}
if (!is.null(estimable)) {
if (!is.character(sort)) stop("option sort must be a character string")
if (!is.character(method)) stop("option method must be a character string")
if (!sort %in% c("natural","high","low")) stop("invalid choice for option sort")
if (clear && !method %in% c("LAD","VF2")) stop("invalid choice for option method")
estimable <- estimable.check(estimable, nfactors, factor.names)
if (is.null(nfactors)) nfactors <- estimable$nfac
estimable <- estimable$estimable
if (is.null(nruns)) {
nruns <- nfactors+ncol(estimable)+1 + (nfactors+ncol(estimable)+1)%%2
if (!isTRUE(all.equal(log2(nruns) %% 1,0))) nruns <- 2^(floor(log2(nruns))+1)
k <- round(log2(nruns))
if (k<3) stop("Please specify nruns and/or nfactors. Calculated values are unreasonable.")
}
if (is.null(perm.start)) perm.start <- 1:nfactors
else if (!is.numeric(perm.start))
stop ("perm.start must be NULL or a numeric permutation vector of length nfactors.")
if (!all(sort(perm.start)==1:nfactors))
stop ("perm.start must be NULL or a numeric permutation vector of length nfactors.")
if (!is.null(perms)) {
if (!is.matrix(perms) | !is.numeric(perms)) stop("perms must be a numeric matrix.")
if (!ncol(perms)==nfactors) stop ("matrix perms must have nfactors columns.")
if (any(apply(perms,1,function(obj) any(!sort(obj)==1:nfactors))))
stop("Each row of perms must be a permutation of 1:nfactors.")
}
}
if (!nfactors==floor(nfactors))
stop("nfactors must be an integer number.")
if (!is.null(factor.names) & !length(factor.names)==nfactors)
stop("There must be nfactors factor names, if any.")
if (is.null(factor.names))
if(nfactors<=50) factor.names <- Letters[1:nfactors] else factor.names <- paste("F",1:nfactors,sep="")
if (!((is.character(default.levels) | is.numeric(default.levels)) & length(default.levels)==2) )
stop("default.levels must be a vector of 2 levels.")
if (is.list(factor.names)){
if (is.null(names(factor.names))){
if (nfactors<=50) names(factor.names) <- Letters[1:nfactors]
else names(factor.names) <- paste("F", 1:nfactors, sep="")
}
if (any(factor.names=="")) factor.names[which(factor.names=="")] <- list(default.levels)}
else {hilf <- vector("list",nfactors)
names(hilf) <- factor.names
hilf[1:nfactors]<-list(default.levels)
factor.names <- hilf}
names(factor.names) <- make.names(names(factor.names), unique=TRUE)
if (ncenter > 0) if(any(is.na(sapply(factor.names,"is.numeric"))))
stop("Center points are implemented for experiments with all factors quantitative only.")
if (!is.null(generators)){
generators <- gen.check(k, generators)
g <- nfactors - k
if (!length(generators)== g)
stop("This design in ", nruns, " runs with ", nfactors," factors requires ", g, " generators.")
res <- NA; nclear.2fis<-NA; clear.2fis<-NULL;all.2fis.clear<-NA
if (g<10) wl <- words.all(k, generators,max.length=6)
else if (g<15) wl <- words.all(k, generators,max.length=5)
else if (g<20) wl <- words.all(k, generators,max.length=4)
else if (g>=20) wl <- alias3fi(k, generators, order=2)
WLP <- NULL
if (g < 20){
WLP <- wl$WLP
res <- min(as.numeric(names(WLP)[which(WLP>0)]))
if (res==Inf) {if (g<10) res="7+"
else if (g<15) res="6+"
else if (g<20) res="5+" }
}
else{
if (!is.list(wl)) res="5+"
else{
if (length(wl$"main")>0) res="3"
else if (length(wl$"fi2")>0) res="4"
else res="5+"}
}
gen <- sapply(generators,function(obj) which(sapply(Yates[1:(nruns-1)],
function(obj2) isTRUE(all.equal(sort(abs(obj)),obj2)))))
gen <- gen*sapply(generators, function(obj) sign(obj[1]))
cand <- list(custom=list(res=res, nfac=nfactors, nruns=nruns,
gen=gen,
WLP=WLP, nclear.2fis=nclear.2fis, clear.2fis=clear.2fis, all.2fis.clear=all.2fis.clear))
class(cand) <- c("catlg","list")
}
if (!identical(blocks,1)) {
blocks <- block.check(k, blocks, nfactors, factor.names)
if (is.list(blocks)) k.block <- length(blocks)
block.auto=FALSE
map <- NULL
}
if (!is.list(blocks)){
if (blocks>1){
block.auto=TRUE
if (is.null(nruns))
stop("blocks>1 only works if nruns is specified.")
k.block <- round(log2(blocks))
if (blocks > nruns/2)
stop("There cannot be more blocks than half the run size.")
if (nfactors+blocks-1>=nruns)
stop(paste(nfactors, "factors cannot be accomodated in", nruns, "runs with", blocks, "blocks."))
ntreat <- nfactors
}
}
if (!is.null(hard)){
if (is.null(generators)){
if (is.null(nruns)){
cand <- select.catlg[which(res.catlg(select.catlg)>=resolution & nfac.catlg(select.catlg)==nfactors)]
if (length(cand)==0) {
message("full factorial design needed for achieving requested resolution")
k <- nfactors
nruns <- 2^k
cand <- list(list(gen=numeric(0)))
}
else {
nruns <- min(nruns.catlg(cand))
k <- round(log2(nruns))
cand <- cand[which(nruns.catlg(cand)==nruns)]
}
}
else {
if (nfactors > k)
cand <- select.catlg[which(nfac.catlg(select.catlg)==nfactors & nruns.catlg(select.catlg)==nruns)]
else cand <- list(list(gen=numeric(0)))
}
}
if (hard == nfactors) stop("It does not make sense to choose hard equal to nfactors.")
if (hard >= nruns/2)
warning ("Do you really need to declare so many factors as hard-to-change ?")
nfac.WP <- hard
if (hard < nruns/2){
WPs <- NA
if (length(cand[[1]]$gen) > 0)
for (i in 1:min(length(cand),check.hard)){
leftadjust.out <- leftadjust(k,cand[[i]]$gen, early=hard, show=1)
if (is.na(WPs) | WPs > 2^leftadjust.out$k.early)
WPs <- 2^leftadjust.out$k.early
}
else WPs <- 2^hard
}
if (hard>=nruns/2 | WPs==nruns) {
warning("There are so many hard-to-change factors that no good special design could be found.
Randomization has been switched off.")
randomize <- FALSE
WPs <- 1
leftadjust.out <- leftadjust(k,cand[[1]]$gen,early=hard,show=1)
generators <- leftadjust.out$gen
}
}
if (!identical(WPs,1)) {
if (is.null(nruns)) stop("WPs>1 only works if nruns is specified.")
if (WPs > nruns/2) stop("There cannot be more whole plots (WPs) than half the run size.")
k.WP <- round(log2(WPs))
if (!WPs == 2^k.WP) stop("WPs must be a power of 2.")
if (!is.null(WPfacs) & nfac.WP==0){
nfac.WP <- length(WPfacs)
if (nfac.WP < k.WP) stop("WPfacs must specify at least log2(WPs) whole plot factors.")
}
if (nfac.WP==0) stop("If WPs > 1, a positive nfac.WP or WPfacs must also be given.")
if (nfac.WP < k.WP) {
add <- k.WP - nfac.WP
names.add <- rep(list(default.levels),add)
names(names.add) <- paste("WP",(nfac.WP+1):(nfac.WP+add),sep="")
nfactors <- nfactors + add
factor.names <- c(factor.names[1:nfac.WP],names.add,factor.names[-(1:nfac.WP)])
nfac.WP <- k.WP
warning("There are fewer factors than needed for a full factorial whole plot design. ", add,
" dummy splitting factor(s) have been introduced.")
}
if (!is.null(WPfacs)) {
WPfacs <- WP.check(k, WPfacs, nfac.WP, nfactors, factor.names)
WPsnum <- as.numeric(chartr("F", " ", WPfacs))
WPsorig <- WPsnum
}
else {WPsorig <- WPsnum <- 1:nfac.WP }
}
if (!is.null(nruns)){
if (nfactors<=k & identical(blocks,1) & identical(WPs,1)) {
if (nfactors==k) aus <- fac.design(2, k, factor.names=factor.names,
replications=replications, repeat.only=repeat.only,
randomize=randomize, seed=seed)
else aus <- fac.design(2, nfactors, factor.names=factor.names,
replications=replications*2^(k-nfactors), repeat.only=repeat.only,
randomize=randomize, seed=seed)
aus <- qua.design(aus, quantitative="none", contrasts=rep("contr.FrF2",nfactors))
if (ncenter>0) aus <- add.center(aus, ncenter, distribute=center.distribute)
di <- design.info(aus)
di$creator <- creator
di <- c(di, list(FrF2.version = "1.7.2"))
design.info(aus) <- di
return(aus)
}
else {
if (nfactors < k) stop("A full factorial for nfactors factors requires fewer than nruns runs.
Please reduce the number of runs and introduce replications instead.")
if (nfactors == k) {
generators <- as.list(numeric(0))
cand <- list(custom=list(res=Inf, nfac=nfactors, nruns=nruns,
gen=numeric(0),
WLP=c(0,0,0,0), nclear.2fis=choose(k,2), clear.2fis=combn(k,2), all.2fis.clear="all"))
class(cand) <- c("catlg","list")
}
if (nfactors > nruns - 1)
stop("You can accomodate at most ",nruns-1," factors in a FrF2 design with ",nruns," runs." )
g <- nfactors - k
if (!is.null(estimable)) {
desmat <- estimable(estimable, nfactors, nruns,
clear=clear, res3=res3, max.time=max.time, select.catlg=select.catlg,
method=method,sort=sort,
perm.start=perm.start, perms=perms, order=alias.info)
design.info <- list(type="FrF2.estimable",
nruns=nruns, nfactors=nfactors, factor.names=factor.names, catlg.name = catlg.name,
map=desmat$map, aliased=desmat$aliased, clear=clear, res3=res3,
FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version)
desmat <- desmat$design
desmat <- as.matrix(sapply(desmat,function(obj) as.numeric(as.character(obj))))
rownames(desmat) <- 1:nrow(desmat)
}
else if (is.null(generators) & is.null(design))
cand <- select.catlg[nruns.catlg(select.catlg)==nruns & nfac.catlg(select.catlg)==nfactors]
block.gen <- NULL
if (!is.list(blocks)){
if (blocks > 1) {
if (g==0 | choose(nruns - 1 - nfactors, k.block) < 100000){
for (i in 1:length(cand)){
if (g==0) {blockpick.out <- try(blockpick(k, gen=0,
k.block=k.block, show=1, alias.block.2fis = alias.block.2fis),TRUE)
}
else {
if (is.null(generators))
blockpick.out <- try(blockpick(k, design=names(cand[i]),
k.block=k.block, show=1, alias.block.2fis = alias.block.2fis),TRUE)
else blockpick.out <- try(blockpick(k, gen=cand[[i]]$gen,
k.block=k.block, show=1, alias.block.2fis = alias.block.2fis),TRUE)
}
if (!"try-error" %in% class(blockpick.out)) {
blocks <- blockpick.out$blockcols
block.gen <- blocks
cand <- cand[i]
cand[[1]]$gen <- c(cand[[1]]$gen,blocks)
blocks <- nfactors+(1:k.block)
nfactors <- nfactors+k.block
g <- g+k.block
hilf <- factor.names
factor.names <- vector("list", nfactors)
factor.names[-blocks] <- hilf
factor.names[blocks] <- list(default.levels)
names(factor.names) <- c(names(hilf),paste("b",1:k.block,sep=""))
blocks <- as.list(blocks)
break
}
}
}
else{
nfactors <- nfactors+k.block
g <- g+k.block
hilf <- factor.names
factor.names <- vector("list", nfactors)
factor.names[(k.block+1):nfactors] <- hilf
factor.names[1:k.block] <- list(default.levels)
names(factor.names) <- c(paste("b",1:k.block,sep=""),paste(names(hilf)))
cand <- select.catlg[nfac.catlg(select.catlg)==nfactors & nruns.catlg(select.catlg)==nruns]
if (!(is.null(generators) & is.null(design)))
warning("For this request, generator or design specifications have been ignored,
because the block allocation procedure for big problems was used.")
for (i in 1:length(cand)){
blockpick.out <- try(blockpick.big(k, gen=cand[[i]]$gen,
k.block=k.block, show=1, alias.block.2fis = alias.block.2fis),TRUE)
if (!"try-error" %in% class(blockpick.out)) {
cand <- cand[i]
cand[[1]]$gen <- blockpick.out$gen[1,]
map <- blockpick.out$perms[1,]
blocks <- as.list(1:k.block)
block.gen <- 2^(0:(k.block-1))
break
}
}
}
if (alias.block.2fis & !is.list(blocks))
stop("no adequate block design found")
if ((!alias.block.2fis) & !is.list(blocks))
stop("no adequate block design found with 2fis unconfounded with blocks")
}
}
if (is.list(blocks)) {
hilf.gen <- c(2^(0:(k-1)), cand[[1]]$gen)
hilf.block.gen <- sapply(blocks, function(obj)
as.intBase(paste(rowSums(do.call(cbind,lapply(obj, function(obj2) digitsBase(hilf.gen[obj2],2,k))))%%2,collapse="")))
k.block.add <- length(intersect(hilf.block.gen, hilf.gen))
if (is.null(block.gen)) {
ntreat <- nfactors - k.block.add
block.gen <- hilf.block.gen
}
if (k.block > 1){
hilf <- hilf.block.gen
for (i in 2:k.block){
sel <- combn(k.block,i)
for (j in 1:ncol(sel)){
neu <- as.intBase(paste(rowSums(do.call(cbind,lapply(sel[,j], function(obj) digitsBase(hilf.block.gen[obj],2,k))))%%2,collapse=""))
if (neu %in% hilf) stop("specified blocks is invalid (dependencies)")
else hilf <- c(hilf, neu)
}
}
rm(hilf)
}
}
if (WPs > 1){
WP.auto <- FALSE
map <- 1:k
orignew <- WPsorig
if (is.null(WPfacs)){
WP.auto <- TRUE
max.res.5 <- c(1,2,3, 5, 6, 8, 11, 17)
for (i in 1:length(cand)){
if (is.null(generators)){
if (cand[[i]]$res>=5 & nfac.WP > max.res.5[k.WP]) next
if (cand[[i]]$res>=4 & nfac.WP > WPs/2) next
}
if (nfac.WP > WPs/2 | nfac.WP <= k.WP)
splitpick.out <- try(splitpick(k, cand[[i]]$gen, k.WP=k.WP, nfac.WP=nfac.WP, show=1),TRUE)
else splitpick.out <- try(splitpick(k, cand[[i]]$gen, k.WP=k.WP, nfac.WP=nfac.WP,
show=check.WPs),TRUE)
if (!"try-error" %in% class(splitpick.out)) {
WPfacs <- 1:k.WP
if (nfac.WP > k.WP) WPfacs <- c(WPfacs, (k + 1):(k+nfac.WP-k.WP))
cand <- cand[i]
cand[[1]]$gen <- splitpick.out$gen[1,]
res.WP <- splitpick.out$res.WP[1]
map <- splitpick.out$perms[1,]
break
}
}
if (is.null(res.WP)){
if (nruns >= 2^nfactors) {
res.WP <- Inf
WP.auto <- TRUE
WPfacs <- 1:k.WP
if (!k.WP == nfac.WP) stop(nfac.WP, " whole plot factors cannot be accomodated in ", (2^k.WP),
" whole plots for a full factorial. Please request smaller design with replication instead.")
cand <- list(list(gen=numeric(0)))
}
else stop("no adequate splitplot design found")
}
orignew <- WPsnum <- WPfacs
WPfacs <- paste("F",WPfacs,sep="")
}
}
}
}
else {
if (is.null(resolution) & is.null(estimable))
stop("At least one of nruns or resolution or estimable must be given.")
if (!is.null(resolution)){
cand <- select.catlg[which(res.catlg(select.catlg)>=resolution & nfac.catlg(select.catlg)==nfactors)]
if (length(cand)==0) {
message("full factorial design needed")
aus <- fac.design(2, nfactors, factor.names=factor.names,
replications=replications, repeat.only=repeat.only,
randomize=randomize, seed=seed)
for (i in 1:nfactors)
if (is.factor(aus[[i]])) contrasts(aus[[i]]) <- contr.FrF2(2)
if (ncenter>0) aus <- add.center(aus, ncenter, distribute=center.distribute)
return(aus)
}
}
else{ cand <- select.catlg[which(nfac.catlg(select.catlg)==nfactors)]
if (length(cand)==0)
stop("No design listed in catalogue ", deparse(substitute(select.catlg)), " fulfills all requirements.")
}
}
if (MaxC2 & is.null(estimable) & is.null(generators) ) {
if (!res3)
cand <- cand[which.max(sapply(cand[which(sapply(cand,
function(obj) obj$res)==max(sapply(cand, function(obj) obj$res)))],
function(obj) obj$nclear.2fis))]
else
cand <- cand[which.max(sapply(cand,
function(obj) obj$nclear.2fis))]
}
if (is.null(nruns)) {nruns <- cand[[1]]$nruns
k <- round(log2(nruns))
g <- nfactors - k}
if (is.null(estimable)){
destxt <- "expand.grid(c(-1,1)"
for (i in 2:k) destxt <- paste(destxt,",c(-1,1)",sep="")
destxt <- paste("as.matrix(",destxt,"))",sep="")
desmat <- eval(parse(text=destxt))
if (is.character(WPfacs) | is.list(blocks)) {
desmat <- desmat[,k:1]
}
if (!is.null(hard)) {
desmat <- rep(c(-1,1),each=nruns/2)
for (i in 2:k) desmat <- cbind(desmat,rep(c(1,-1,-1,1),times=(2^i)/4,each=nruns/(2^i)))
}
if (g>0)
for (i in 1:g)
desmat <- cbind(desmat, sign(cand[[1]]$gen[i][1])*apply(desmat[,unlist(Yates[abs(cand[[1]]$gen[i])])],1,prod))
if (WPs > 1) {
if (!WP.auto) {
hilf <- apply(desmat[,WPsorig,drop=FALSE],1,paste,collapse="")
if (!length(table(hilf))==WPs)
stop("The specified design creates ",
length(table(hilf)), " and not ", WPs, " whole plots.")
for (j in setdiff(1:nfactors,WPsorig))
if (!length(table(paste(hilf,desmat[,j],sep="")))>WPs)
stop("Factor ", names(factor.names)[j], " is also a whole plot factor.")
if (nfac.WP<3) res.WP <- Inf
else res.WP <- GR((3-desmat[,WPsorig,drop=FALSE])%/%2)$GR%/%1
}
}
if (is.null(rownames(desmat))) rownames(desmat) <- 1:nruns
if (is.list(blocks)) {
if (is.null(block.gen)) block.gen <- blocks
hilf <- blocks
for (i in 1:k.block) hilf[[i]] <- apply(desmat[,hilf[[i]],drop=FALSE],1,prod)
Blocks <- factor(as.numeric(factor(apply(matrix(as.character(unlist(hilf)),ncol=k.block),
1,paste,collapse=""))))
hilf <- order(Blocks, as.numeric(rownames(desmat)))
desmat <- desmat[hilf,]
Blocks <- Blocks[hilf]
contrasts(Blocks) <- contr.FrF2(levels(Blocks))
nblocks <- 2^length(blocks)
blocksize <- nruns / nblocks
block.no <- paste(Blocks,rep(1:blocksize,nblocks),sep=".")
}
if (is.character(WPfacs)) {
desmat <- desmat[,c(WPsnum,setdiff(1:nfactors,WPsnum))]
factor.names <- factor.names[c(WPsorig,setdiff(1:nfactors,WPsorig))]
plotsize <- round(nruns/WPs)
if (is.null(hard)){
hilf <- ord(cbind(desmat[,1:nfac.WP],as.numeric(rownames(desmat))))
desmat <- desmat[hilf,]
}
wp.no <- paste(rep(1:WPs,each=plotsize),rep(1:plotsize,WPs),sep=".")
}
}
if (randomize & !is.null(seed)) set.seed(seed)
if (!(is.list(blocks) | WPs > 1)){
rand.ord <- rep(1:nruns,replications)
if (replications > 1 & repeat.only) rand.ord <- rep(1:nruns,each=replications)
if (randomize & !repeat.only) for (i in 1:replications)
rand.ord[((i-1)*nruns+1):(i*nruns)] <- sample(nruns)
if (randomize & repeat.only) rand.ord <- rep(sample(1:nruns), each=replications)
}
else {
if (is.list(blocks)){
rand.ord <- rep(1:nruns, bbreps * wbreps)
if ((!repeat.only) & !randomize)
for (i in 0:(nblocks-1))
for (j in 1:wbreps)
rand.ord[(i*blocksize*wbreps+(j-1)*blocksize+1):((i+1)*blocksize*wbreps+j*blocksize)] <-
(i*blocksize+1):((i+1)*blocksize)
rand.ord <- rep(rand.ord[1:(nruns*wbreps)],bbreps)
if (repeat.only & !randomize)
for (j in 1:wbreps)
rand.ord[(i*blocksize*wbreps + (j-1)*blocksize + 1) :
(i*blocksize*wbreps + j*blocksize)] <-
sample((i%%nblocks*blocksize+1):(i%%nblocks*blocksize+blocksize))
if (wbreps > 1 & repeat.only) rand.ord <- rep(1:nruns,bbreps, each=wbreps)
if ((!repeat.only) & randomize)
for (i in 0:(nblocks*bbreps-1))
for (j in 1:wbreps)
rand.ord[(i*blocksize*wbreps + (j-1)*blocksize + 1) :
(i*blocksize*wbreps + j*blocksize)] <-
sample((i%%nblocks*blocksize+1):(i%%nblocks*blocksize+blocksize))
if (repeat.only & randomize)
for (i in 0:(nblocks*bbreps-1))
rand.ord[(i*blocksize*wbreps + 1) :
((i+1)*blocksize*wbreps)] <- rep(sample((((i%%nblocks)*blocksize)+1):
((i%%nblocks+1)*blocksize)),each=wbreps)
}
else {
rand.ord <- rep(1:nruns,replications)
if (replications > 1 & repeat.only)
rand.ord <- rep(1:nruns,each=replications)
if ((!repeat.only) & randomize){
for (i in 1:(WPs*replications))
rand.ord[((i-1)*plotsize+1):(i*plotsize)] <-
sample(rand.ord[((i-1)*plotsize+1):(i*plotsize)])
for (i in 1:replications){
if (is.null(hard)){
WPsamp <- sample(WPs)
WPsamp <- (rep(WPsamp,each=plotsize)-1)*plotsize + rep(1:plotsize,WPs)
rand.ord[((i-1)*plotsize*WPs+1):(i*plotsize*WPs)] <-
rand.ord[(i-1)*plotsize*WPs + WPsamp]
}
}
}
if (repeat.only & randomize){
for (i in 1:WPs)
rand.ord[((i-1)*plotsize*replications+1):(i*plotsize*replications)] <-
rand.ord[(i-1)*plotsize*replications +
rep(replications*(sample(plotsize)-1),each=replications) +
rep(1:2,each=plotsize)]
if (is.null(hard)){
WPsamp <- sample(WPs)
WPsamp <- (rep(WPsamp,each=plotsize*replications)-1)*plotsize*replications +
rep(1:(plotsize*replications),WPs)
rand.ord <- rand.ord[WPsamp]
}
}
}
}
orig.no <- rownames(desmat)
orig.no <- orig.no[rand.ord]
orig.no.levord <- sort(as.numeric(orig.no),index=TRUE)$ix
rownames(desmat) <- NULL
desmat <- desmat[rand.ord,]
if (is.list(blocks)) {
Blocks <- Blocks[rand.ord]
block.no <- block.no[rand.ord]
}
if (WPs > 1) wp.no <- wp.no[rand.ord]
colnames(desmat) <- names(factor.names)
if (is.list(blocks)) orig.no <- paste(orig.no,block.no,sep=".")
if (WPs > 1) orig.no <- paste(orig.no,wp.no,sep=".")
orig.no.rp <- orig.no
if (bbreps * wbreps > 1){
if (bbreps > 1) {
if (repeat.only & !is.list(blocks))
orig.no.rp <- paste(orig.no.rp, rep(1:bbreps,nruns),sep=".")
else
orig.no.rp <- paste(orig.no.rp, rep(1:bbreps,each=nruns*wbreps),sep=".")
}
if (wbreps > 1){
if (repeat.only)
orig.no.rp <- paste(orig.no.rp, rep(1:wbreps,nruns*bbreps),sep=".")
else orig.no.rp <- paste(orig.no.rp, rep(1:wbreps,each=blocksize,nblocks*bbreps),sep=".")
}
}
desdf <- data.frame(desmat)
quant <- rep(FALSE,nfactors)
for (i in 1:nfactors) {
desdf[,i] <- des.recode(desdf[,i],"-1=factor.names[[i]][1];1=factor.names[[i]][2]")
quant[i] <- is.numeric(desdf[,i])
desdf[,i] <- factor(desdf[,i],levels=factor.names[[i]])
contrasts(desdf[,i]) <- contr.FrF2(2)
}
if (is.list(blocks)) {
desdf <- cbind(Blocks, desdf)
hilf <- blocks
if (all(sapply(hilf,length)==1) & !block.auto) {
hilf <- as.numeric(hilf) + 1
levels(desdf$Blocks) <- unique(apply(desdf[,hilf,drop=FALSE],1,paste,collapse=""))
}
colnames(desdf)[1] <- block.name
hilf <- blocks
hilf <- as.numeric(hilf[which(sapply(hilf,length)==1)])
if (length(hilf)>0) {
desdf <- desdf[,-(hilf+1)]
desmat <- desmat[,-hilf]
factor.names <- factor.names[-hilf]
}
desmat <- cbind(model.matrix(~desdf[,1])[,-1],desmat)
colnames(desmat)[1:(2^k.block-1)] <- paste(block.name,1:(2^k.block-1),sep="")
if (alias.info==3)
hilf <- aliases(lm((1:nrow(desmat))~(.)^3,data=data.frame(desmat)))
else
hilf <- aliases(lm((1:nrow(desmat))~(.)^2,data=data.frame(desmat)))
if (length(hilf$aliases) > 0)
for (i in 1:length(hilf$aliases)) {
txt <- hilf$aliases[[i]]
if (length(grep(paste("^-?",block.name,sep=""),txt)) > 0)
txt <- txt[-grep(paste("^-?",block.name,sep=""),txt)]
if (length(txt)==length(grep("^-",txt))) txt <- sub("-","",txt)
hilf$aliases[[i]] <- txt
}
aliased.with.blocks <- hilf$aliases[1:(2^k.block-1)]
aliased.with.blocks <- unlist(aliased.with.blocks)
if (nfactors<=50) leg <- paste(Letters[1:ntreat],names(factor.names),sep="=")
else leg <- paste(paste("F",1:ntreat,sep=""),names(factor.names),sep="=")
if (length(aliased.with.blocks)==0) aliased.with.blocks <- "none"
else {
aliased.with.blocks <- recalc.alias.block(aliased.with.blocks, leg)
aliased.with.blocks <- aliased.with.blocks[ord(data.frame(nchar(aliased.with.blocks),aliased.with.blocks))]
}
aliased <- hilf$aliases[-(1:(2^k.block-1))]
aliased <- aliased[which(sapply(aliased,length)>1)]
if (length(aliased)>0) aliased <- struc.aliased(recalc.alias.block(aliased, leg), nfactors, alias.info)
ntreat <- ncol(desdf) - 1
if (block.auto) factor.names <- factor.names[1:ntreat]
design.info <- list(type="FrF2.blocked", block.name=block.name,
nruns=nruns, nfactors=ntreat, nblocks=nblocks, block.gen=block.gen, blocksize=blocksize,
ntreat=ntreat,factor.names=factor.names,
aliased.with.blocks=aliased.with.blocks, aliased=aliased,
bbreps=bbreps, wbreps=wbreps,
FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version)
if (!is.null(generators)) {
if (g>0)
design.info <- c(design.info,
list(base.design=paste("generator columns:", paste(cand[[1]]$gen, collapse=", "))))
else
design.info <- c(design.info,
list(base.design="full factorial"))
}
else design.info <- c(design.info, list(catlg.name = catlg.name, base.design=names(cand[1])))
design.info <- c(design.info, list(map=map))
if (bbreps>1) {
hilflev <- paste(rep(levels(desdf[,1]), each=bbreps), rep(1:bbreps, nblocks), sep=".")
desdf[,1] <- factor(paste(desdf[,1], rep(1:bbreps, each=nruns*wbreps),sep="."), levels=hilflev)
}
}
if (WPs > 1){
if (alias.info==3)
aliased <- aliases(lm((1:nrow(desmat))~(.)^3,data=data.frame(desmat)))$aliases
else
aliased <- aliases(lm((1:nrow(desmat))~(.)^2,data=data.frame(desmat)))$aliases
aliased <- aliased[which(sapply(aliased,length)>1)]
if (length(aliased) > 0){
if (nfactors<=50) leg <- paste(Letters[1:nfactors],names(factor.names),sep="=")
else leg <- paste(paste("F",1:nfactors,sep=""),names(factor.names),sep="=")
aliased <- struc.aliased(recalc.alias.block(aliased, leg), nfactors, alias.info)
}
design.info <- list(type="FrF2.splitplot",
nruns=nruns, nfactors=nfactors, nfac.WP=nfac.WP, nfac.SP=nfactors-nfac.WP,
factor.names=factor.names,
nWPs=WPs, plotsize=nruns/WPs,
res.WP=res.WP, aliased=aliased, FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version)
if (!is.null(generators))
design.info <- c(design.info,
list(base.design=paste("generator columns:",
paste(which(names(Yates)[1:(nruns-1)] %in% names(generators)), collapse=", ")), map=map,
orig.fac.order = c(orignew, setdiff(1:nfactors,orignew))))
else design.info <- c(design.info, list(catlg.name = catlg.name, base.design=names(cand[1]), map=map,
orig.fac.order = c(orignew, setdiff(1:nfactors,orignew))))
}
if (is.null(estimable) & is.null(generators) & !(is.list(blocks) | WPs > 1))
design.info <- list(type="FrF2", nruns=nruns, nfactors=nfactors, factor.names=factor.names,
catlg.name = catlg.name,
catlg.entry=cand[1], aliased = alias3fi(k,cand[1][[1]]$gen,order=alias.info),
FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version)
if ((!is.null(generators)) & !is.list(blocks) & !WPs > 1) {
if (nfactors <= 50)
names(generators) <- Letters[(k+1):nfactors]
else names(generators) <- paste("F",(k+1):nfactors, sep="")
gen.display <- paste(names(generators),sapply(generators,function(obj){
if (nfactors <= 50)
paste(if (obj[1]<0) "-" else "", paste(Letters[abs(obj)],collapse=""),sep="")
else
paste(if (obj[1]<0) "-" else "", paste(paste("F",abs(obj),sep=""),collapse=":"),sep="")}), sep="=")
design.info <- list(type="FrF2.generators", nruns=nruns, nfactors=nfactors, factor.names=factor.names, generators=gen.display,
aliased = alias3fi(k,generators,order=alias.info),
FrF2.version = sessionInfo(package="FrF2")$otherPkgs$FrF2$Version)
}
aus <- desdf
rownames(aus) <- rownames(desmat) <- 1:nrow(aus)
class(aus) <- c("design","data.frame")
attr(aus,"desnum") <- desmat
orig.no <- factor(orig.no, levels=unique(orig.no[orig.no.levord]))
orig.no.rp <- factor(orig.no.rp, levels=unique(orig.no.rp[orig.no.levord]))
if (!(is.list(blocks) | WPs > 1))
attr(aus,"run.order") <- data.frame("run.no.in.std.order"=orig.no,"run.no"=1:nrow(desmat),"run.no.std.rp"=orig.no.rp)
else attr(aus,"run.order") <- data.frame("run.no.in.std.order"=orig.no,"run.no"=1:nrow(desmat),"run.no.std.rp"=orig.no.rp)
if (design.info$type=="FrF2.blocked") {
if (design.info$wbreps==1) repeat.only <- FALSE
nfactors <- ntreat
}
if (nfactors<=50) design.info$aliased <- c(list(legend=paste(Letters[1:nfactors],names(factor.names),sep="=")),design.info$aliased)
else design.info$aliased <- c(list(legend=paste(paste("F",1:nfactors,sep=""),names(factor.names),sep="=")),design.info$aliased)
attr(aus,"design.info") <- c(design.info, list(replications=replications, repeat.only=repeat.only,
randomize=randomize, seed=seed, creator=creator))
if (ncenter>0) aus <- add.center(aus, ncenter, distribute=center.distribute)
aus
} |
test_that(".rba_api_check works", {
expect_true(object = .rba_api_check("https://google.com"))
expect_regex(obj = .rba_api_check("https://google.com/dftgyh"),
pattern = "404")
})
test_that("rba_connection_test works", {
expect_named(object = rba_connection_test(print_output = FALSE,
diagnostics = FALSE),
expected = names(.rba_stg("tests")))
})
test_that("rba_options works", {
expect_class(obj = rba_options(),
expected = "data.frame")
rba_options(timeout = 91)
expect_true(object = (getOption("rba_timeout") == 91))
expect_error(object = rba_options(verbose = 123),
regexp = "logical")
expect_error(object = rba_options(save_file = "test.txt"),
regexp = "logical")
})
test_that("rba_pages works", {
rba_test <- function(x, skip_error = NULL, ...) {
if (isTRUE(skip_error)) {
LETTERS[[x]]
} else {
paste0(LETTERS[[x]], "!", collapse = "")
}
}
expect_error(object = rba_pages(input_call = Sys.sleep(0)),
regexp = "qoute")
expect_error(object = rba_pages(input_call = quote(Sys.sleep(0))),
regexp = "rbioapi")
expect_error(object = rba_pages(input_call = quote(rba_test(3))),
regexp = "pages")
expect_error(object = rba_pages(input_call = quote(rba_test(3))),
regexp = "pages")
expect_error(object = rba_pages(input_call = quote(rba_test("pages:1:999"))),
regexp = "100")
}) |
.max.lambda <- function(X, y, weights, start, offset, family, pen.cov, n.par.cov, pen.mat, pen.mat.transform) {
n.cov <- length(n.par.cov)
eta <- as.numeric(X %*% start + offset)
mu <- family$linkinv(eta)
grad <- as.numeric((weights * (mu - y) / family$variance(mu) * family$mu.eta(eta)) %*% X / sum(weights != 0))
beta.tilde <- start - grad
beta.tilde.split <- split(beta.tilde, rep(1:n.cov, n.par.cov))
lambda.max <- numeric(length(n.par.cov))
for (j in 1:length(beta.tilde.split)) {
if (pen.cov[[j]] == "lasso") {
lambda.max[j] <- max(abs(beta.tilde.split[[j]]) / diag(pen.mat[[j]]))
} else if (pen.cov[[j]] == "grouplasso") {
lambda.max[j] <- sqrt(sum((beta.tilde.split[[j]] / diag(pen.mat[[j]]))^2))
} else if (pen.cov[[j]] == "flasso") {
lambda.max[j] <- max(abs(t(pen.mat.transform[[j]]) %*% beta.tilde.split[[j]]))
} else if (pen.cov[[j]] %in% c("gflasso", "2dflasso", "ggflasso")) {
if (nrow(pen.mat[[j]]) > ncol(pen.mat[[j]])) {
lambda.max[j] <- .min.maxnorm(A = t(pen.mat[[j]]), b = beta.tilde.split[[j]])
} else {
warning(paste0("'lambda.max' cannot be determined for predictor '", names(pen.cov)[j], "'."))
}
}
}
return(lambda.max)
}
.min.maxnorm <- function(A, b) {
x0 <- .PPF(A, b)
A.ginv <- ginv(A)
A.kernel <- round(diag(nrow = nrow(A.ginv)) - A.ginv %*% A, 10)
opt <- optim(par = 0*x0, fn = .maxnorm, method = "BFGS",
control = list(maxit = 1e6, reltol = 1e-10), x0 = x0, A.kernel = A.kernel)
return(opt$value)
}
.maxnorm <- function(z, x0, A.kernel) {
return(max(abs(x0 + A.kernel %*% z)))
}
.PPF <- function(A, b) {
m <- nrow(A)
n <- ncol(A)
if (n <= m) {
stop("Matrix 'A' is not underdetermined.")
}
xk <- ginv(A) %*% b
dk <- 0 * xk
ak <- 0
Active.Set <- which(abs(xk) == max(abs(xk)))
while (length(Active.Set) < n-m+1) {
Non.Active.Set <- (1:length(xk))[-Active.Set]
n.ASc <- n - length(Active.Set)
A.AS <- matrix(A[, Active.Set], ncol = length(Active.Set))
A.ASc <- matrix(A[, -Active.Set], ncol = n.ASc)
xk.AS <- xk[Active.Set]
if (rankMatrix(A.ASc) < m) {
break
}
dk.AS <- -sign(xk.AS)
dk.ASc <- ginv(A.ASc) %*% A.AS %*% sign(xk.AS)
dk[Active.Set] <- dk.AS
dk[-Active.Set] <- dk.ASc
a.possible.set <- rep(-1, n)
xi <- xk[Active.Set[1]]
di <- dk[Active.Set[1]]
for (j in Non.Active.Set) {
a.one <- (xi - xk[j]) / (dk[j] - di)
a.two <- (-xi - xk[j]) / (dk[j] - (-di))
a.cand <- c(a.one, a.two)
a.possible.set[j] <- ifelse(a.one < 0 & a.two < 0, -1, min(a.cand[which(a.cand > 0)]))
}
ak <- min(a.possible.set[which(a.possible.set > 0)])
xk <- xk + ak * dk
Active.Set <- which(abs(xk) == max(abs(xk)))
}
return(xk)
} |
with_blend_custom <- function(x, bg_layer, a = 0, b = 0, c = 0, d = 0,
flip_order = FALSE, alpha = NA, ...) {
UseMethod('with_blend_custom')
}
with_blend_custom.grob <- function(x, bg_layer, a = 0, b = 0, c = 0, d = 0,
flip_order = FALSE, alpha = NA, ..., id = NULL,
include = is.null(id)) {
gTree(grob = x, bg_layer = bg_layer, a = a, b = b, c = c, d = d,
flip_order = flip_order, alpha = tolower(alpha), id = id, include = isTRUE(include),
cl = c('custom_blend_grob', 'filter_grob'))
}
with_blend_custom.Layer <- function(x, bg_layer, a = 0, b = 0, c = 0, d = 0,
flip_order = FALSE, alpha = NA, ..., id = NULL,
include = is.null(id)) {
filter_layer_constructor(x, with_blend_custom, 'CustomBlendedGeom', a = a, b = b,
c = c, d = d, flip_order = flip_order, alpha = alpha, ...,
include = include, ids = list(id = id, bg_layer = bg_layer))
}
with_blend_custom.list <- function(x, bg_layer, a = 0, b = 0, c = 0, d = 0,
flip_order = FALSE, alpha = NA, ..., id = NULL,
include = is.null(id)) {
filter_list_constructor(x, with_blend_custom, 'CustomBlendedGeom', a = a, b = b,
c = c, d = d, flip_order = flip_order, alpha = alpha, ...,
include = include, ids = list(id = id, bg_layer = bg_layer))
}
with_blend_custom.ggplot <- function(x, bg_layer, a = 0, b = 0, c = 0, d = 0,
flip_order = FALSE, alpha = NA, ignore_background = TRUE,
...) {
filter_ggplot_constructor(x, with_blend_custom, bg_layer = bg_layer, a = a, b = b,
c = c, d = d, flip_order = flip_order, alpha = alpha,
..., ignore_background = ignore_background)
}
with_blend_custom.character <- function(x, bg_layer, a = 0, b = 0, c = 0, d = 0,
flip_order = FALSE, alpha = NA, ..., id = NULL,
include = is.null(id)) {
filter_character_constructor(x, with_blend_custom, 'CustomBlendedGeom', a = a,
b = b, c = c, d = d, flip_order = FALSE, alpha = alpha,
..., include = include, ids = list(id = id, bg_layer = bg_layer))
}
with_blend_custom.function <- with_blend_custom.character
with_blend_custom.formula <- with_blend_custom.character
with_blend_custom.raster <- with_blend_custom.character
with_blend_custom.nativeRaster <- with_blend_custom.character
with_blend_custom.element <- function(x, bg_layer, a = 0, b = 0, c = 0, d = 0,
flip_order = FALSE, alpha = NA, ...) {
filter_element_constructor(x, with_blend_custom, bg_layer = bg_layer, a = a,
b = b, c = c, d = d, flip_order = flip_order,
alpha = alpha, ...)
}
with_blend_custom.guide <- function(x, bg_layer, a = 0, b = 0, c = 0, d = 0,
flip_order = FALSE, alpha = NA, ...) {
filter_guide_constructor(x, with_blend_custom, bg_layer = bg_layer, a = a,
b = b, c = c, d = d, flip_order = flip_order,
alpha = alpha, ...)
}
blend_custom_raster <- function(x, bg_layer, a, b, c, d, flip_order = FALSE, alpha = NA) {
raster <- image_read(x)
dim <- image_info(raster)
bg_layer <- get_layer(bg_layer)
bg_layer <- image_read(bg_layer)
bg_layer <- image_resize(bg_layer, geometry_size_pixels(dim$width, dim$height, FALSE))
layers <- list(bg_layer, raster)
if (flip_order) layers <- rev(layers)
result <- image_composite(layers[[1]], layers[[2]], 'Mathematics',
compose_args = paste(a, b, c, d, sep = ','))
if (!is.na(alpha)) {
alpha_mask <- if (alpha == 'src') layers[[2]] else layers[[1]]
result <- image_composite(alpha_mask, result, operator = 'in')
}
x <- as.integer(result)
image_destroy(raster)
image_destroy(bg_layer)
image_destroy(result)
x
}
makeContent.custom_blend_grob <- function(x) {
ras <- rasterise_grob(x$grob)
raster <- blend_custom_raster(ras$raster, x$bg_layer, x$a, x$b, x$c, x$d, x$flip_order)
raster <- groberize_raster(raster, ras$location, ras$dimension, x$id, x$include)
setChildren(x, gList(raster))
} |
rsu.sssep.rspool <- function(k, pstar, pse, psp, se.p) {
n <- log(1 - se.p) / log(((1 - (1 - pstar)^k) * (1 - pse) + (1 - pstar)^k * psp))
return(ceiling(n))
} |
timeInfo <- function(
time = NULL,
longitude = NULL,
latitude = NULL,
timezone = NULL
) {
if ( is.null(time) ) {
stop(paste0("Required parameter 'time' is missing"))
} else if ( !is.POSIXct(time) ) {
stop(paste0("Required parameter 'time' must be of class POSIXct"))
}
if ( is.null(longitude) ) {
stop(paste0("Required parameter 'longitude' is missing"))
} else if ( !is.numeric(longitude) ) {
stop(paste0("Required parameter 'longitude' must be of class numeric"))
}
if ( is.null(latitude) ) {
stop(paste0("Required parameter 'latitude' is missing"))
} else if ( !is.numeric(latitude) ) {
stop(paste0("Required parameter 'latitude' must be of class numeric"))
}
if ( is.null(timezone) || !(timezone %in% base::OlsonNames()) ) {
timezone <- MazamaSpatialUtils::getTimezone(longitude, latitude, useBuffering = TRUE)
}
if ( is.null(timezone) || is.na(timezone) ) {
stop(paste0(
"Timezone is not recognized and land-based timezone cannot be found. ",
"Plese supply a timezone found in base::OlsonNames()."
))
}
localTime <- lubridate::with_tz(time, tzone = timezone)
coords <- matrix(c(longitude, latitude), nrow = 1)
sunrise <- maptools::sunriset(coords, localTime, direction = "sunrise", POSIXct.out = TRUE)
sunset <- maptools::sunriset(coords, localTime, direction = "sunset", POSIXct.out = TRUE)
solarnoon <- maptools::solarnoon(coords, localTime, POSIXct.out = TRUE)
sunrise <- sunrise[,2] ; sunset <- sunset[,2] ; solarnoon <- solarnoon[,2]
dayMask <- (localTime >= sunrise) & (localTime < sunset)
nightMask <- !dayMask
morningMask <- (localTime > sunrise) & (localTime <= solarnoon)
afternoonMask <- (localTime > solarnoon) & (localTime <= sunset)
Christmas_UTC <- lubridate::ymd_h("2019-12-25 00", tz = "UTC")
Christmas_localTime <- lubridate::with_tz(Christmas_UTC, tzone = timezone)
Christmas_localTime_UTC <- lubridate::force_tz(Christmas_localTime, tzone = "UTC")
lst_offset <- as.numeric(difftime(Christmas_localTime_UTC, Christmas_UTC, units = "hours"))
localStandardTime_UTC <- lubridate::with_tz(localTime, tzone = "UTC") +
lst_offset * lubridate::dhours(1)
timeInfo <- data.frame(
localStandardTime_UTC = localStandardTime_UTC,
daylightSavings = lubridate::dst(localTime),
localTime = localTime,
sunrise = sunrise,
sunset = sunset,
solarnoon = solarnoon,
day = dayMask,
morning = morningMask,
afternoon = afternoonMask,
night = nightMask
)
return(timeInfo)
}
if ( FALSE ) {
Thompson_Falls <- monitor_load(2018110307, 2018110607,
monitorIDs = "300890007_01")
time <- Thompson_Falls$data$datetime
timezone <- Thompson_Falls$meta$timezone
longitude <- Thompson_Falls$meta$longitude
latitude <- Thompson_Falls$meta$latitude
timeInfo <- timeInfo(time, longitude, latitude, timezone)
t(timeInfo[24:27,])
} |
states.check <- function(seqdata, state.order, state.equiv, with.missing=FALSE){
if(length(state.order) != length(unique(state.order)))
msg.stop("Multiple occurrences of same state in state.order: ", paste(state.order, collapse=" "))
alphabet <- alphabet(seqdata, with.missing)
inexistant_al <- which(is.na(match(state.order, alphabet)))
if(length(inexistant_al)>0 && !is.numeric(seqdata)) {
if(length(inexistant_al)>1 || !is.na(state.order[inexistant_al])) {
msg.stop("Bad state.order, states not in the alphabet: ", paste(state.order[inexistant_al], collapse=" "))
}
}
if (!is.null(state.equiv)){
if(!is.list(state.equiv)){
msg.stop("Bad state.equiv. A list is expected!")
}
equiv_al <- unlist(state.equiv)
if(length(equiv_al) != length(unique(equiv_al)))
msg.stop("Multiple occurrence of same state in state.equiv")
inexistant_al <- which(is.na(match(equiv_al, alphabet)))
if(length(inexistant_al)>0 && !is.numeric(seqdata)) {
if(length(inexistant_al)>1 || !is.na(equiv_al[inexistant_al])) {
msg.stop("Bad state.equiv, states not in the alphabet: ", paste(equiv_al[inexistant_al], collapse=" "))
}
}
if (length(unique(state.order)) < length(alphabet)){
inoncomp <- which(is.na(match(alphabet(seqdata),unique(state.order))))
state.noncomp <- alphabet(seqdata)[inoncomp]
ii.noncomp.equiv <- match(state.noncomp,equiv_al)
ii.noncomp.equiv <- ii.noncomp.equiv[!is.na(ii.noncomp.equiv)]
if(length(ii.noncomp.equiv)>0){
state.noncomp.equiv <- equiv_al[ii.noncomp.equiv]
for (i in 1:length(state.noncomp.equiv)){
for (k in 1:length(state.equiv)){
if (state.noncomp.equiv[i] %in% state.equiv[[k]] ){
ii <- match(state.equiv[[k]],state.order)
if (!is.na(ii[1])){
state.order.new <- c(state.order[1:ii[1]],state.noncomp.equiv[i])
if (length(state.order)>ii[1]) {
state.order.new <- c(state.order.new, state.order[(ii[1]+1):length(state.order)])
}
state.order <- state.order.new
} else {}
break
}
}
}
}
}
}
return(state.order)
} |
bayesQR <- function(formula=NULL, data=NULL, quantile=0.5, alasso=FALSE, normal.approx=NULL, ndraw=NULL, keep=1, prior=NULL, seed=NULL){
pandterm <- function(message) {
stop(message, call. = FALSE)
}
nqr <- length(quantile)
out <- NULL
if (!is.null(seed)){
seedval <- .Fortran("setseed",as.integer(seed))
}
if (nqr==1){
out[[1]] <- bayesQR.single(formula=formula, data=data, quantile=quantile, alasso=alasso, normal.approx=normal.approx, ndraw=ndraw, keep=keep, prior=prior)
} else {
quantile <- sort(quantile)
for (i in 1:nqr){
cat("************************************************","\n")
cat("* Start estimating quantile ", i," of ", nqr, "in total *", "\n")
cat("************************************************","\n")
out[[i]] <- bayesQR.single(formula=formula, data=data, quantile=quantile[i], alasso=alasso, normal.approx=normal.approx, ndraw=ndraw, keep=keep, prior=prior)
}
}
class(out) <- "bayesQR"
return(out)
} |
trim <- function(x) {
UseMethod("trim")
}
trim.data.frame <- function(x) {
as.data.frame(lapply(x, FUN = trim_helper))
}
trim.list <- function(x) {
lapply(x, FUN = trim_helper)
}
trim.default <- function(x) {
trim_helper(x)
}
trim_helper <- function(x) gsub("^\\s+|\\s+$", "", x) |
context("Tests for function rv.test")
test_that(desc = "Print and plot call", {
data("sanitizer")
res <- digitTests::rv.test(x = sanitizer$value, check = 'last', method = 'af', B = 500)
invisible({capture.output({ print(res) }) })
invisible({capture.output({ plot(res) }) })
expect_equal(length(res$statistic), 1)
})
test_that(desc = "Validate Datacolada[77]", {
data("sanitizer")
res <- digitTests::rv.test(x = sanitizer$value, check = 'last', method = 'af', B = 500)
expect_equal(as.numeric(res$statistic), 1.5225)
res <- digitTests::rv.test(x = sanitizer$value, check = 'last', method = 'entropy', B = 500)
expect_equal(as.numeric(res$statistic), 7.065769174)
}) |
library(OpenMx)
library(testthat)
data(demoOneFactor)
latents = c("G")
manifests = names(demoOneFactor)
m1 <- mxModel("One Factor", type = "RAM",
manifestVars = manifests, latentVars = latents,
mxPath(from = latents, to = manifests),
mxPath(from = manifests, arrows = 2, values=.2),
mxPath(from = latents, arrows = 2, free = FALSE, values = 1.0),
mxPath(from = "one", to = manifests),
mxData(cov(demoOneFactor), type='cov',
numObs=nrow(demoOneFactor), means=colMeans(demoOneFactor))
)
fm <- omxSetParameters(m1, "One Factor.M[1,1]", values = .1, free=FALSE)
expect_error(mxPowerSearch(m1, fm),
"contains 'cov' data") |
context("consume data with public visibility, selectively")
gap <- gs_gap()
test_that("We can get data from specific cells using limits", {
foo <- gap %>%
gs_read_cellfeed(ws = 5, range = cell_limits(c(3, 1), c(5, 3)),
verbose = FALSE)
expect_equal(foo$cell, paste0(LETTERS[1:3], rep(3:5, each = 3)))
foo <- gap %>%
gs_read_cellfeed(ws = "Oceania", range = cell_limits(c(2, 4), c(NA, 4)),
verbose = FALSE)
expect_true(all(grepl("^D", foo$cell)))
foo <- gap %>%
gs_read_cellfeed(ws = "Oceania", range = cell_limits(lr = c(NA, 3)),
verbose = FALSE)
expect_true(all(grepl("^[ABC][0-9]+$", foo$cell)))
})
test_that("We can get data from specific cells using rows and columns", {
foo <- gap %>% gs_read_cellfeed(ws = "Africa", range = cell_rows(2:3),
verbose = FALSE)
expect_true(all(foo$row %in% 2:3))
foo <- gap %>% gs_read_cellfeed(ws = "Africa", range = cell_rows(1),
verbose = FALSE)
expect_true(all(foo$row == 1))
foo <- gap %>% gs_read_cellfeed(ws = "Oceania", range = cell_cols(3:6),
verbose = FALSE)
expect_true(all(foo$col %in% 3:6))
foo <- gap %>% gs_read_cellfeed(ws = "Oceania", range = cell_cols(4),
verbose = FALSE)
expect_true(all(foo$col == 4))
})
test_that("We can get data from specific cells using a range", {
foo <- gap %>%
gs_read_cellfeed(ws = "Europe", range = "B3:C7", verbose = FALSE)
expect_is(foo, "tbl_df")
expect_true(all(foo$col %in% 2:3))
expect_true(all(foo$row %in% 3:7))
foo <- gap %>%
gs_read_cellfeed(ws = "Europe", range = "R3C2:R7C3", verbose = FALSE)
expect_is(foo, "tbl_df")
expect_true(all(foo$col %in% 2:3))
expect_true(all(foo$row %in% 3:7))
foo <- gap %>% gs_read_cellfeed(ws = "Europe", range = "C4", verbose = FALSE)
expect_is(foo, "tbl_df")
expect_equal(foo$col, 3)
expect_equal(foo$row, 4)
foo <- gap %>% gs_read_cellfeed(ws = "Europe", range = "R4C3", verbose = FALSE)
expect_is(foo, "tbl_df")
expect_equal(foo$col, 3)
expect_equal(foo$row, 4)
})
test_that("We decline to reshape data if there is none", {
foo <- gap %>%
gs_read_cellfeed(ws = "Oceania", range = cell_rows(1), verbose = FALSE)
expect_message(tmp <- foo %>% gs_reshape_cellfeed(), "No data to reshape!")
expect_identical(dim(tmp), rep(0L, 2))
})
test_that("We can simplify data from the cell feed", {
foo <- gap %>%
gs_read_cellfeed(ws = "Africa", range = cell_rows(2:3), verbose = FALSE)
expect_equal_to_reference(
foo %>% gs_simplify_cellfeed(),
test_path("for_reference/gap_africa_simplify_A1.rds")
)
expect_equal_to_reference(
foo %>% gs_simplify_cellfeed(notation = "R1C1"),
test_path("for_reference/gap_africa_simplify_R1C1.rds")
)
foo <- gap %>%
gs_read_cellfeed(ws = "Oceania", range = cell_cols(3), verbose = FALSE)
foo_simple <- foo %>% gs_simplify_cellfeed()
expect_equivalent(foo_simple, rep(seq(from = 1952, to = 2007, by = 5), 2))
expect_equal(names(foo_simple), paste0("C", 1:24 + 1))
foo_simple2 <- foo %>% gs_simplify_cellfeed(col_names = FALSE)
expect_is(foo_simple2, "character")
foo_simple3 <- foo %>% gs_simplify_cellfeed(col_names = TRUE)
expect_is(foo_simple3, c("numeric", "integer"))
foo_simple4 <- foo %>% gs_simplify_cellfeed(convert = FALSE)
expect_equivalent(foo_simple4,
rep(seq(from = 1952, to = 2007, by = 5), 2) %>%
as.character())
yo <- gap %>%
gs_read_cellfeed(ws = "Oceania", range = cell_cols(3), verbose = FALSE)
yo_simple <- yo %>% gs_simplify_cellfeed(convert = TRUE)
expect_is(yo_simple, c("numeric", "integer"))
})
test_that("Validation is in force for row / columns limits in the cell feed", {
mess <- "less than or equal to"
expect_error(gs_read_cellfeed(gap, range = cell_rows(1001:1003),
verbose = FALSE), mess)
expect_error(gs_read_cellfeed(gap, range = cell_rows(999:1003),
verbose = FALSE), mess)
expect_error(gs_read_cellfeed(gap, range = cell_cols(27),
verbose = FALSE), mess)
expect_error(gs_read_cellfeed(gap, range = cell_cols(24:30),
verbose = FALSE), mess)
})
test_that("query params work on the list feed", {
oceania_fancy <- gap %>%
gs_read_listfeed(ws = "Oceania",
reverse = TRUE, orderby = "gdppercap",
sq = "lifeexp > 79 or year < 1960",
verbose = FALSE)
oceania_fancy <- dplyr::select(oceania_fancy, -year, -pop)
expect_equal_to_reference(
oceania_fancy,
test_path("for_reference/gap_oceania_listfeed_query.rds")
)
})
test_that("readr parsing params are handled on the list feed", {
cspec <- do.call(readr::cols, as.list(strsplit("cccnnn", "")[[1]]))
oceania_tweaked <- gap %>%
gs_read_listfeed(ws = "Oceania",
col_names = paste0("VAR", 1:6),
col_types = cspec,
n_max = 5, skip = 1)
expect_identical(names(oceania_tweaked), paste0("VAR", 1:6))
expect_equivalent(vapply(oceania_tweaked, class, character(1)),
rep(c("character", "numeric"), each = 3))
})
test_that("comment is honored", {
skip("Subject to type discrepancies due to readr version.")
ss <- gs_ws_feed(pts_ws_feed)
ref <- dplyr::data_frame(
var1 = c(1, 3),
var2 = c(2, NA_real_)
)
expect_warning(
plain_read <- ss %>% gs_read(ws = "comment", comment = "
"1 parsing failure."
)
expect_equal(ref, plain_read)
expect_warning(
csv_read <- ss %>% gs_read_csv(ws = "comment", comment = "
"1 parsing failure."
)
expect_equal(ref, csv_read)
listfeed_read <- ss %>% gs_read_listfeed(ws = "comment", comment = "
expect_equal(ref, listfeed_read)
range_read <- ss %>% gs_read(ws = "comment", comment = "
expect_equal(ref, range_read)
}) |
test_that("Path can be derived for windows Python >= 3.0", {
paths_base <- with_mock(
"precommit::path_derive_precommit_exec_win_python3plus_candidates" = function() {
c(
fs::path_home("AppData/Roaming/Python/Python35"),
fs::path_home("AppData/Roaming/Python/Python37")
)
},
path_derive_precommit_exec_win_python3plus_base()
)
expect_equal(
paths_base,
c(
fs::path(fs::path_home(), "AppData/Roaming/Python/Python37/Scripts"),
fs::path(fs::path_home(), "AppData/Roaming/Python/Python35/Scripts")
)
)
skip_if(!is_windows())
skip_if(!not_conda())
skip_if(on_cran())
expect_match(path_derive_precommit_exec_win_python3plus_base(), "AppData/Roaming")
expect_equal(
fs::path_file(path_derive_precommit_exec_win()),
precommit_executable_file()
)
})
test_that("Warns when there are multiple installations found (2x os)", {
expect_warning(
with_mock(
"precommit::path_derive_precommit_exec_path" = function(candidate) {
fs::path_home("AppData/Roaming/Python/Python35")
},
"Sys.info" = function(...) {
c(sysname = "windows")
},
"precommit:::path_derive_precommit_exec_win" = function() {
c(
fs::path_home("AppData/Roaming/Python/Python34"),
fs::path_home("AppData/Roaming/Python/Python37")
)
},
path_derive_precommit_exec()
),
"We detected multiple pre-commit executables"
)
})
test_that("Warns when there are multiple installations found (2x path)", {
expect_warning(
with_mock(
"precommit::path_derive_precommit_exec_path" = function(candidate) {
c(
fs::path_home("AppData/Roaming/Python/Python35"),
fs::path_home("AppData/Roaming/Python/Python37")
)
},
"Sys.info" = function(...) {
c(sysname = "windows")
},
"precommit:::path_derive_precommit_exec_win" = function() {
fs::path_home("AppData/Roaming/Python/Python34")
},
path_derive_precommit_exec()
),
"We detected multiple pre-commit executables"
)
})
test_that("Warns when there are multiple installations found (path and os)", {
expect_warning(
with_mock(
"precommit::path_derive_precommit_exec_path" = function(candidate) {
fs::path_home("AppData/Roaming/Python/Python35")
},
"Sys.info" = function(...) {
c(sysname = "windows")
},
"precommit:::path_derive_precommit_exec_win" = function() {
fs::path_home("AppData/Roaming/Python/Python34")
},
path_derive_precommit_exec()
),
"We detected multiple pre-commit executables"
)
}) |
library(testthat)
test_that("medal works", {
expect_equal(
medal(1),
emoji_name[["1st_place_medal"]]
)
expect_equal(
medal(1:3),
unname(emoji_name[c("1st_place_medal", "2nd_place_medal", "3rd_place_medal")])
)
expect_equal(
medal(c("1st", "2nd", "3rd")),
unname(emoji_name[c("1st_place_medal", "2nd_place_medal", "3rd_place_medal")])
)
expect_equal(
medal(c("gold", "silver", "bronze")),
unname(emoji_name[c("1st_place_medal", "2nd_place_medal", "3rd_place_medal")])
)
expect_equal(
medal(c("gold", "nothing")),
c(emoji_name[["1st_place_medal"]], NA)
)
}) |
auc.mc <- function(x, y, method = "leave out", lo = 2, it = 100, ...){
METHODS <- c("leave out", "bootstrap", "sorted bootstrap", "constrained bootstrap", "jackknife", "jack-validate")
method <- pmatch(method, METHODS)
if (is.na(method)){
stop("invalid method")
}
if(method == 1){
ind <- lapply(seq(it), function(z) sort(sample(seq(length(x)), length(x)-lo)))
res <- sapply(ind, function(z) auc(x[z], y[z], ...))
}
else if (method == 2){
ind <- lapply(seq(it), function(z) sample(seq(length(x)), replace=TRUE))
res <- sapply(ind, function(z) auc(x, y[z], ...))
}
else if (method == 3){
ind <- lapply(seq(it), function(z) sort(sample(seq(length(x)), replace=TRUE)))
res <- sapply(ind, function(z) auc(x, y[z], ...))
}
else if (method == 4){
ind <- lapply(seq(it), function(z) unique(sort(sample(seq(length(x)), replace=TRUE))))
res <- sapply(ind, function(z) auc(x[z], y[z], ...))
}
else if (method == 5){
ind <- combs(seq(length(x)), length(x)-1)
res <- apply(ind, 1, function(z) auc(x[z], y[z], ...))
}
else if (method == 6){
ind <- lapply(c(1:lo), function(z) combs(seq(length(x)), length(x)-z))
res <- unlist(sapply(ind, function(z) apply(z, 1, function(w) auc(x[w], y[w], ...))))
}
return(res)
} |
suppressMessages(library(td))
.onWindows <- .Platform$OS.type == "windows"
if (! .onWindows) expect_error(time_series(sym="SPY", api=""))
if ((Sys.getenv("RunTDTests","") == "yes")
&& td:::.get_apikey() != ""
&& requireNamespace("xts", quietly=TRUE)) {
spy <- time_series(sym="SPY", interval="1min", outputsize=100, as="xts")
expect_true(inherits(spy, "xts"))
expect_equal(nrow(spy), 100)
} |
expected <- eval(parse(text="structure(integer(0), .Dim = 0:1)"));
test(id=0, code={
argv <- eval(parse(text="list(0:1)"));
.Internal(row(argv[[1]]));
}, o=expected); |
context("portfolio_compute")
test_that("portfolio_compute works (arg method)", {
expect_equal(portfolio_compute(investor, marketprices, method = "none"), portfolio_results[, c(1:5)])
expect_equal(portfolio_compute(investor, marketprices, method = "none", progress = TRUE), portfolio_results[, c(1:5)])
expect_equal(portfolio_compute(investor, marketprices, method = "count"), portfolio_results[, c(1:5, 6:9)])
expect_equal(portfolio_compute(investor, marketprices, method = "total"), portfolio_results[, c(1:5, 10:13)])
expect_equal(portfolio_compute(investor, marketprices, method = "value"), portfolio_results[, c(1:5, 14:17)])
expect_equal(portfolio_compute(investor, marketprices, method = "duration"), portfolio_results[, c(1:5, 18:21)], tolerance = 0.001)
expect_equal(portfolio_compute(investor, marketprices, method = "all"), portfolio_results, tolerance = 0.001)
})
test_that("portfolio_compute works (arg allow_short)", {
expect_type(portfolio_compute(investor, marketprices, allow_short = FALSE), "list")
})
test_that("portfolio_compute works (arg exact_market_prices)", {
expect_equal(
portfolio_compute(investor, marketprices, exact_market_prices = TRUE),
portfolio_compute(investor, marketprices, exact_market_prices = FALSE)
)
})
test_that("portfolio_compute works (arg time_threshold)", {
expect_equal(portfolio_compute(investor, marketprices, time_threshold = "5 mins"), portfolio_results[, 1:9], tolerance = 0.001)
expect_type(portfolio_compute(investor, marketprices, time_threshold = "30 days"), "list")
})
test_that("portfolio_compute works (arg portfolio_driven_DE)", {
expect_type(portfolio_compute(investor, marketprices, method = "all", portfolio_driven_DE = TRUE), "list")
})
test_that("portfolio_compute works (arg time_series_DE)", {
expect_type(portfolio_compute(investor, marketprices, time_series_DE = TRUE), "list")
expect_type(portfolio_compute(investor, marketprices, method = "value", time_series_DE = TRUE), "list")
expect_type(portfolio_compute(investor, marketprices, method = "all", time_series_DE = TRUE), "list")
})
test_that("portfolio_compute works (arg assets_time_series_DE)", {
expect_type(
portfolio_compute(investor, marketprices, time_series_DE = TRUE, assets_time_series_DE = "ACO"),
"list"
)
expect_type(
portfolio_compute(investor, marketprices, method = "value", time_series_DE = TRUE, assets_time_series_DE = "ACO"),
"list"
)
expect_type(
portfolio_compute(investor, marketprices, method = "all", time_series_DE = TRUE, assets_time_series_DE = "ACO"),
"list"
)
})
investor_error <- investor
names(investor_error) <- c("investors", "types", "asset", "quantity", "price", "datetime")
investor_error2 <- investor
investor_error2$type[1] <- "Buy"
marketprices_error <- marketprices
names(marketprices_error) <- c("assets", "datetime", "price")
marketprices_error2 <- marketprices
marketprices_error2 <- marketprices_error2[-c(11:60), ]
test_that("portfolio_compute works (initial checks)", {
expect_error(portfolio_compute(investor_error, marketprices))
expect_error(portfolio_compute(investor, marketprices_error))
expect_error(portfolio_compute(investor_error2, marketprices))
expect_error(portfolio_compute(investor, marketprices, method = "new"))
expect_error(portfolio_compute(investor, marketprices, time_threshold = "1 month"))
expect_warning(portfolio_compute(investor, marketprices, method = "total", time_series_DE = TRUE))
expect_warning(portfolio_compute(investor, marketprices, method = "duration", time_series_DE = TRUE))
expect_warning(portfolio_compute(investor, marketprices, method = "none", time_series_DE = TRUE))
expect_warning(portfolio_compute(investor, marketprices, portfolio_driven_DE = TRUE, time_series_DE = TRUE))
expect_warning(portfolio_compute(investor, marketprices_error2))
expect_warning(portfolio_compute(investor, marketprices, assets_time_series_DE = "AC"))
expect_error(portfolio_compute(investor, marketprices, time_series_DE = TRUE, assets_time_series_DE = "AC"))
}) |
library(sand)
data(strike)
summary(strike)
table(V(strike)$race)
mytriangle <- function(coords, v=NULL, params) {
vertex.color <- params("vertex", "color")
if (length(vertex.color) != 1 && !is.null(v)) {
vertex.color <- vertex.color[v]
}
vertex.size <- 1/200 * params("vertex", "size")
if (length(vertex.size) != 1 && !is.null(v)) {
vertex.size <- vertex.size[v]
}
symbols(x=coords[,1], y=coords[,2], bg=vertex.color,
stars=cbind(vertex.size, vertex.size, vertex.size),
add=TRUE, inches=FALSE)
}
add_shape("triangle", clip=shapes("circle")$clip,
plot=mytriangle)
V(strike)[V(strike)$race=="YS"]$shape <- "circle"
V(strike)[V(strike)$race=="YE"]$shape <- "square"
V(strike)[V(strike)$race=="OE"]$shape <- "triangle"
nv <- vcount(strike)
z <- numeric(nv)
z[c(5,15,21,22)] <- 1
V(strike)$color <- rep("white",nv)
V(strike)[z==1]$color <- "red3"
set.seed(42)
my.dist <- c(rep(1.8,4),rep(2.2,9),rep(2,11))
l <- layout_with_kk(strike)
plot(strike,layout=l,vertex.label=V(strike)$names,
vertex.label.degree=-pi/3,
vertex.label.dist=my.dist)
V(strike)[z==1]$names
rank(-betweenness(strike))[z==1]
rank(-closeness(strike))[z==1]
A <- as_adjacency_matrix(strike)
I.ex.nbrs <- as.numeric(z%*%A > 0)
V(strike)[z*I.ex.nbrs==1]$names
V(strike)[(1-z)*I.ex.nbrs==1]$names
V(strike)[z*(1-I.ex.nbrs)==1]$names
V(strike)[(1-z)*(1-I.ex.nbrs)==1]$names
O.c11 <- 10.0; O.c10 <- 7; O.c01 <- 5; O.c00 <- 1.0
c(O.c11,O.c10,O.c01)-O.c00
set.seed(41)
m <- 4
n <- 10000
I11 <- matrix(,nrow=nv,ncol=n)
I10 <- matrix(,nrow=nv,ncol=n)
I01 <- matrix(,nrow=nv,ncol=n)
I00 <- matrix(,nrow=nv,ncol=n)
for(i in 1:n){
z <- rep(0,nv)
reps.ind <- sample((1:nv),m,replace=FALSE)
z[reps.ind] <- 1
reps.nbrs <- as.numeric(z%*%A > 0)
I11[,i] <- z*reps.nbrs
I10[,i] <- z*(1-reps.nbrs)
I01[,i] <- (1-z)*reps.nbrs
I00[,i] <- (1-z)*(1-reps.nbrs)
}
I11.11 <- I11%*%t(I11)/n
I10.10 <- I10%*%t(I10)/n
I01.01 <- I01%*%t(I01)/n
I00.00 <- I00%*%t(I00)/n
names.w.space <- paste(V(strike)$names," ",sep="")
my.cex.x <- 0.75; my.cex.y <- 0.75
image(I00.00, zlim=c(0,0.7), xaxt="n", yaxt="n",
col=cm.colors(16))
mtext(side=1, text=names.w.space,at=seq(0.0,1.0,(1/23)),
las=3, cex=my.cex.x)
mtext(side=2, text=names.w.space,at=seq(0.0,1.0,1/23),
las=1, cex=my.cex.y)
mtext(side=3,text=expression("No Exposure"~(c["00"])),
at=0.5, las=1)
u <- 1/23; uo2 <- 1/46
xmat <- cbind(rep(3*u+uo2,2),rep(12*u+uo2,2))
ymat <- cbind(c(0-uo2,1+uo2),c(0-uo2,1+uo2))
matlines(xmat,ymat, lty=1, lw=1, col="black")
matlines(ymat,xmat, lty=1, lw=1, col="black")
z <- rep(0,nv)
z[c(5,15,21,22)] <- 1
reps.nbrs <- as.numeric(z%*%A > 0)
c11 <- z*reps.nbrs
c10 <- z*(1-reps.nbrs)
c01 <- (1-z)*reps.nbrs
c00 <- (1-z)*(1-reps.nbrs)
Obar.c11 <- O.c11*mean(c11/diag(I11.11))
Obar.c10 <- O.c10*mean(c10/diag(I10.10))
Obar.c01 <- O.c01*mean(c01/diag(I01.01))
Obar.c00 <- O.c00*mean(c00/diag(I00.00))
print(c(Obar.c11,Obar.c10,Obar.c01)-Obar.c00)
set.seed(42)
n <- 10000
Obar.c11 <- numeric()
Obar.c10 <- numeric()
Obar.c01 <- numeric()
Obar.c00 <- numeric()
for(i in 1:n){
z <- rep(0,nv)
reps.ind <- sample((1:nv),m,replace=FALSE)
z[reps.ind] <- 1
reps.nbrs <- as.numeric(z%*%A > 0)
c11 <- z*reps.nbrs
c10 <- z*(1-reps.nbrs)
c01 <- (1-z)*reps.nbrs
c00 <- (1-z)*(1-reps.nbrs)
Obar.c11 <- c(Obar.c11, O.c11*mean(c11/diag(I11.11)))
Obar.c10 <- c(Obar.c10, O.c10*mean(c10/diag(I10.10)))
Obar.c01 <- c(Obar.c01, O.c01*mean(c01/diag(I01.01)))
Obar.c00 <- c(Obar.c00, O.c00*mean(c00/diag(I00.00)))
}
ACE <- list(Obar.c11-Obar.c00, Obar.c10-Obar.c00,
Obar.c01-Obar.c00)
print(sapply(ACE,mean)-
c(O.c11-O.c00, O.c10-O.c00, O.c01-O.c00))
print(sapply(ACE,sd))
sapply(ACE,sd)/c(9,6,4) |
dr.fit.psir <-function(object,numdir=4,nslices=2,pool=FALSE,
slice.function=dr.slices,...){
object <- psir(object,nslices,pool,slice.function)
object$numdir <- numdir
object$method <- "psir"
class(object) <- c("psir", "sir","dr")
return(object)
}
psir <- function(object,nslices,pool,slice.function) {
Y <- dr.y(object)
X <- dr.x(object)
W <- dr.wts(object)
n <- dim(X)[1]
p <- dim(X)[2]
group.names <- unique(as.factor(object$group))
nG <- length(group.names)
G <- numeric(n)
for (j in 1:nG) G[object$group ==group.names[j]] <- j
"%^%"<-function(A,n) {
if (dim(A)[2]==1) { A^n } else {
eg<-eigen(A)
(eg$vectors) %*% diag(abs(eg$values)^n) %*% t(eg$vectors) }}
Sigma.pool <- matrix(0,p,p)
Sigma <- array(0,c(p,p,nG))
wt.cov <- function(x,w){
xbarw <- apply(x,2,function(x) sum(w*x)/sum(w))
xc <- t(apply(x,1,function(x) x-xbarw))
(1/sum(w)) * t(xc) %*% apply(xc,2,function(x) w*x)
}
slice <- if (length(nslices)==nG) nslices else rep(nslices,nG)
info <- NULL
for (k in 1:nG){
sel <- object$group == group.names[k]
info[[k]]<- slice.function(Y[sel],slice[k])
Sigma[,,k] <- wt.cov(X[sel,],W[sel])
Sigma.pool <- Sigma.pool + sum(W[sel]) *Sigma[,,k]/ n
}
slice.info <- function() info
psir1 <- function(k) {
group.sel <- object$group == group.names[k]
Z <- X[group.sel,]
y <- Y[group.sel]
n <- length(y)
Scale <- if(pool) Sigma.pool else Sigma[,,k]
z <- (Z-matrix(1,n,1)%*%apply(Z,2,mean)) %*% (Scale %^% (-1/2))
zmeans <- array(0,c(p,info[[k]]$nslices))
for (j in 1:info[[k]]$nslices) {
slice.sel <- (info[[k]]$slice.indicator==j)
if (sum(slice.sel)<1) mu <- rep(0,p)
else mu <- apply(z[slice.sel,],2,mean)
zmeans[,j] <- sqrt(sum(slice.sel)/n)*mu
}
stat <- function(gamma) {
r <- p - dim(gamma)[2]
gamma <- Scale %^% (1/2) %*% gamma
h <- info[[k]]$nslices
H <- as.matrix(qr.Q(qr(gamma), complete = TRUE)[, (p - r + 1):p])
st <- sum((t(H)%*%zmeans)^2)*n
wts <- rep(1,min(p,h-1))
wts[1:min(p,h-1)] <- 1-svd(zmeans)$d[1:min(p,h-1)]^2
return(list(st=st,wts=wts))
}
return(list(zmeans=zmeans,stat=stat))
}
zmeans <- NULL
for (k in 1:nG){zmeans <- cbind(zmeans,psir1(k)$zmeans)}
D <- svd(zmeans,p)
evectors <-
apply(Sigma.pool%^%(-1/2)%*%D$u,2,function(x)x/sqrt(sum(x^2)))
dimnames(evectors) <-
list(attr(dr.x(object),"dimnames")[[2]],
paste("Dir",1:dim(evectors)[2],sep=""))
test <- function(d) {
h <- sum(slice)
d <- min(d,h-nG)
st <- df <- pv <- 0
for (i in 0:(d-1)) {
st[i+1] <- sum(D$d[(i+1):min(p,h-nG)]^2)*n
df[i+1] <- (h-i-nG)*(p-i)
pv[i+1] <- 1 - pchisq(st[i+1], df[i+1])}
z<-data.frame(cbind(st,df,pv))
rr<-paste(0:(d-1),"D vs >= ",1:d,"D",sep="")
dimnames(z)<-list(rr,c("Stat","df","p.value"))
return(z)
}
coordinate.test <- function(H) {
r <- p-dim(H)[2]
st <- 0
wts <- 0
for (k in 1:nG) {
tp <- psir1(k)$stat(H)
st <- st+tp$st
wts <- cbind(wts,tp$wts)
}
wts <- rep(wts,r)
testr <- dr.pvalue(wts[wts>1e-5],st,a=object$chi2approx)
df <- testr$df.adj
pv <- testr$pval.adj
return(data.frame(cbind(Test=st,P.value=pv)))
}
return(c(object, list(evectors=evectors,
evalues=D$d^2,slice.info=slice.info,
test=test,coordinate.test=coordinate.test)))
}
dr.test.psir <- function(object,numdir=object$numdir,...)
object$test(numdir)
dr.coordinate.test.psir <- function(object,hypothesis,d=NULL,...) {
gamma <- if (class(hypothesis) == "formula")
coord.hyp.basis(object, hypothesis)
else as.matrix(hypothesis)
object$coordinate.test(gamma)
}
summary.psir <- function(object,...) {
ans <- summary.dr(object,...)
ans$method <- "psir"
gps<- sizes <- NULL
for (g in 1:length(a1 <- object$slice.info())){
gps<- c(gps,a1[[g]][[2]])
sizes <- c(sizes,a1[[g]][[3]])}
ans$nslices <- paste(gps,collapse=" ")
ans$sizes <- sizes
return(ans)
}
summary.psir <- function (object, ...)
{ z <- object
ans <- z[c("call")]
nd <- min(z$numdir,length(which(abs(z$evalues)>1.e-15)))
ans$evectors <- z$evectors[,1:nd]
ans$method <- "psir"
gps<- sizes <- NULL
for (g in 1:length(a1 <- object$slice.info())){
gps<- c(gps,a1[[g]][[2]])
sizes <- c(sizes,a1[[g]][[3]])}
ans$nslices <- paste(gps,collapse=" ")
ans$sizes <- sizes
ans$weights <- z$weights
sw <- sqrt(ans$weights)
y <- z$y
ans$n <- z$cases
ols.fit <- qr.fitted(object$qr,sw*(y-mean(y)))
angles <- cosangle(dr.direction(object),ols.fit)
angles <- if (is.matrix(angles)) angles[,1:nd] else angles[1:nd]
if (is.matrix(angles)) dimnames(angles)[[1]] <- z$y.name
angle.names <- if (!is.matrix(angles)) "R^2(OLS|dr)" else
paste("R^2(",dimnames(angles)[[1]],"|dr)",sep="")
ans$evalues <-rbind (z$evalues[1:nd],angles)
dimnames(ans$evalues)<-
list(c("Eigenvalues",angle.names),
paste("Dir", 1:NCOL(ans$evalues), sep=""))
ans$test <- dr.test(object,nd)
class(ans) <- "summary.dr"
ans
}
drop1.psir <- function(object,scope=NULL,...){
drop1.dr(object,scope,...) } |
plotsample <- function(data, ask = TRUE, ...) {
if (!is.data.frame(data))
data <- read.table(data, header = TRUE)
old.par <- par(no.readonly = TRUE)
on.exit(par(old.par))
i <- 1
count <- 0
while (i < length(data)) {
if (count%%6 == 0) {
count <- 0
par(mfrow = c(3, 2), omi = c(1.5, 1, 0, 1.5)/2.54)
}
plot(data[, 1], data[, i + 1], type = "l", xlab = "iteration", ylab = dimnames(data)[[2]][i +
1], ...)
par(ask = ask)
count <- count + 1
i <- i + 1
}
return(invisible())
}
plotsample.coda <- function(data, ask = TRUE, ...) {
if (!is.data.frame(data))
data <- read.table(data, header = TRUE)
data <- data[, -1]
data.mcmc <- coda::as.mcmc(data)
plot(data.mcmc, ask = ask, ...)
return(invisible())
} |
mt_gwas <- function(pleio_results, save_at = NULL){
if (!'pleio_class' %in% class(pleio_results))
stop('pleio_results should be a pleio_class object')
n_traits <- nrow(pleio_results[[1]]$betas)
n_snp <- length(pleio_results)
n <- vector()
allele_freq <- vector()
estimate <- matrix(nrow = n_snp, ncol = n_traits)
s_error <- matrix(nrow = n_snp, ncol = n_traits)
for (i in 1:n_snp){
result <- pleio_results[[i]]
n[i] <- result$n
allele_freq[i] <- result$allele_freq
estimate[i,] <- result$betas
s_error[i,] <- sqrt(diag(result$lhss))
}
t_stat <- estimate / s_error
result_list <- list()
for (j in 1:n_traits){
result_list[[j]] <- cbind(allele_freq, n, estimate[,j], s_error[,j], t_stat[,j], stats::pt(q = abs(t_stat[,j]), df = n - 2, lower.tail = F) * 2)
colnames(result_list[[j]]) <- c('allele_freq', 'n', "estimate", "se", "t value", "p value")
rownames(result_list[[j]]) <- names(pleio_results)
}
names(result_list) <- rownames(pleio_results[[1]]$betas)
if (!is.null(save_at)){
if(!is.character(save_at))
stop('Save at must be a character string with a directory or file name')
if(length(grep('.rdata', save_at, ignore.case = T)) > 0){
file_name <- strsplit(casefold(basename(save_at)), '.rdata')[[1]]
dir_name <- dirname(save_at)
}else{
if(length(grep('\\.', save_at)) > 0)
stop('The file must be .rdata')
dir_name <- save_at
file_name <- 'mt_gwas_result'
}
if(!substring(dir_name, nchar(dir_name)) == '/')
dir_name <- paste0(dir_name, '/')
if(!dir.exists(dir_name))
dir.create(dir_name)
i <- 1
while (file.exists(paste0(dir_name, file_name, '_', i, '.rdata')))
i <- i + 1
save(result_list, file = paste0(dir_name, file_name, '_', i, '.rdata'))
}
return(result_list)
} |
library(testthat)
context("Force")
test_that("All force", {
nodes <- sg_make_nodes(50)
edges <- sg_make_edges(nodes, 100)
sg <- sigmajs() %>%
sg_nodes(nodes, id, label, size) %>%
sg_edges(edges, id, source, target) %>%
sg_force() %>%
sg_force_stop()
expect_length(sg$x$force, 0)
expect_equal(sg$x$forceStopDelay, 5000)
expect_error(sg_force())
expect_error(sg_force_stop())
}) |
plot.cpm <- function(x, ...)
{
groups <- x$groups
plot.args <- list(...)
if(length(plot.args) == 0)
{plot.args$type <- "p"}
if(x$connections == "separate")
{
if(!"main" %in% names(plot.args))
{mains <- c("Positive Prediction", "Negative Prediction")
}else{mains <- plot.args$main}
}else{
if(!"main" %in% names(plot.args))
{mains <- c("Overall Prediction")
}else{mains <- plot.args$main}
}
if(!"xlab" %in% names(plot.args))
{plot.args$xlab <- "Observed Score\n(Z-score)"}
if(!"ylab" %in% names(plot.args))
{plot.args$ylab <- "Predicted Score\n(Z-score)"}
if(!"col" %in% names(plot.args))
{
cols <- ifelse(is.null(groups), c("darkorange2", "skyblue2"), c("darkorange2", "darkorange2", "skyblue2", "skyblue2"))
}else{
if(length(plot.args$col) == 2)
{cols <- rep(c(plot.args$col[1], plot.args$col[2]), 2)
}else{cols <- plot.args$col}
}
if(!"pch"%in% names(plot.args))
{
pchs <- ifelse(is.null(groups), c(16,16), c(16,1,16,1))
}else{
if(length(plot.args$pch) == 2)
{pchs <- rep(c(plot.args$pch[1], plot.args$pch[2]), 2)
}else{pchs <- plot.args$pch}
}
if(x$connections == "separate")
{
if(any(is.na(x$posPred)))
{
pos.na <- which(is.na(x$posPred))
bstat_pos <- x$behav[-pos.na]
behav_pred_pos <- x$posPred[-pos.na]
}else{
bstat_pos <- x$behav
behav_pred_pos <- x$posPred
}
if(any(is.na(x$negPred)))
{
neg.na <- which(is.na(x$negPred))
bstat_neg <- x$behav[-neg.na]
behav_pred_neg <- x$posPred[-neg.na]
}else{
bstat_neg <- x$behav
behav_pred_neg <- x$negPred
}
R_pos<-cor(behav_pred_pos,bstat_pos,use="pairwise.complete.obs")
P_pos<-cor.test(behav_pred_pos,bstat_pos)$p.value
R_neg<-cor(behav_pred_neg,bstat_neg,use="pairwise.complete.obs")
P_neg<-cor.test(behav_pred_neg,bstat_neg)$p.value
P_pos<-ifelse(round(P_pos,3)!=0,round(P_pos,3),noquote("< .001"))
P_neg<-ifelse(round(P_neg,3)!=0,round(P_neg,3),noquote("< .001"))
lower.bstat_pos <- floor(range(bstat_pos))[1]
upper.bstat_pos <- ceiling(range(bstat_pos))[2]
lower.bstat_neg <- floor(range(bstat_neg))[1]
upper.bstat_neg <- ceiling(range(bstat_neg))[2]
lower.pos.pred <- floor(range(behav_pred_pos))[1]
upper.pos.pred <- ceiling(range(behav_pred_pos))[2]
lower.neg.pred <- floor(range(behav_pred_neg))[1]
upper.neg.pred <- ceiling(range(behav_pred_neg))[2]
text.one_pos <- lower.bstat_pos - (lower.bstat_pos * .20)
text.one_neg <- lower.bstat_neg - (lower.bstat_neg * .20)
if(!is.null(groups))
{
labs_groups <- unique(groups)
n_groups <- length(labs_groups)
plot.args$col <- c(rep(cols[1],length(which(groups == labs_groups[1]))),
rep(cols[2],length(which(groups == labs_groups[2]))))
plot.args$pch <- c(rep(pchs[1],length(which(groups == labs_groups[1]))),
rep(pchs[2],length(which(groups == labs_groups[2]))))
plot.args$x <- bstat_pos
plot.args$y <- behav_pred_pos
plot.args$ylim <- c(lower.pos.pred, upper.pos.pred)
plot.args$xlim <- c(lower.bstat_pos, upper.bstat_pos)
plot.args$main <- mains[1]
dev.new()
par(mar=c(5,5,4,2))
do.call(plot, plot.args)
abline(lm(behav_pred_pos~bstat_pos))
if(R_pos>=0)
{
text.two <- upper.pos.pred - (upper.pos.pred * .20)
text(x = text.one_pos, y = text.two, labels = paste("r = ", round(R_pos,3), "\np = ", P_pos))
legend("bottomright", legend = labs_groups, col = c(cols[1], cols[2]), pch = c(pchs[1], pchs[2]))
}else if(R_pos<0)
{
text.two <- lower.pos.pred - (lower.pos.pred * .20)
text(x = text.one_pos, y = text.two, labels = paste("r = ", round(R_pos,3), "\np = ", P_pos))
legend("topright", legend = labs_groups, col = c(cols[1], cols[2]), pch = c(pchs[1], pchs[2]))
}
plot.args$col <- c(rep(cols[3],length(which(groups == labs_groups[1]))),
rep(cols[4],length(which(groups == labs_groups[2]))))
plot.args$pch <- c(rep(pchs[3],length(which(groups == labs_groups[1]))),
rep(pchs[4],length(which(groups == labs_groups[2]))))
plot.args$x <- bstat_neg
plot.args$y <- behav_pred_neg
plot.args$ylim <- c(lower.neg.pred, upper.neg.pred)
plot.args$xlim <- c(lower.bstat_neg, upper.bstat_neg)
plot.args$main <- mains[2]
dev.new()
par(mar=c(5,5,4,2))
do.call(plot, plot.args)
abline(lm(behav_pred_neg~bstat_neg))
if(R_neg>=0)
{
text.two <- upper.neg.pred - (upper.neg.pred * .20)
text(x = text.one_neg, y = text.two, labels = paste("r = ", round(R_neg,3), "\np = ", P_neg))
legend("bottomright", legend = labs_groups, col = c(cols[3], cols[4]), pch = c(pchs[3], pchs[4]))
}else if(R_neg<0)
{
text.two <- lower.neg.pred - (lower.neg.pred * .20)
text(x = text.one_neg, y = text.two, labels = paste("r = ", round(R_neg,3), "\np = ", P_neg))
legend("topright", legend = labs_groups, col = c(cols[3], cols[4]), pch = c(pchs[3], pchs[4]))
}
}else{
plot.args$col <- cols[1]
plot.args$pch <- pchs[1]
plot.args$x <- bstat_pos
plot.args$y <- behav_pred_pos
plot.args$ylim <- c(lower.pos.pred, upper.pos.pred)
plot.args$xlim <- c(lower.bstat_pos, upper.bstat_pos)
plot.args$main <- mains[1]
dev.new()
par(mar=c(5,5,4,2))
do.call(plot, plot.args)
abline(lm(behav_pred_pos~bstat_pos))
if(R_pos>=0)
{
text.two <- upper.pos.pred - (upper.pos.pred * .20)
text(x = text.one_pos, y = text.two, labels = paste("r = ", round(R_pos,3), "\np = ", P_pos))
}else if(R_pos<0)
{
text.two <- lower.pos.pred - (lower.pos.pred * .20)
text(x = text.one_pos, y = text.two, labels = paste("r = ", round(R_pos,3), "\np = ", P_pos))
}
plot.args$col <- cols[2]
plot.args$pch <- pchs[2]
plot.args$x <- bstat_neg
plot.args$y <- behav_pred_neg
plot.args$ylim <- c(lower.neg.pred, upper.neg.pred)
plot.args$xlim <- c(lower.pos.pred, upper.pos.pred)
plot.args$main <- mains[2]
dev.new()
par(mar=c(5,5,4,2))
do.call(plot, plot.args)
abline(lm(behav_pred_neg~bstat_neg))
if(R_neg>=0)
{
text.two <- upper.neg.pred - (upper.neg.pred * .20)
text(x = text.one_neg, y = text.two, labels = paste("r = ", round(R_neg,3), "\np = ", P_neg))
}else if(R_neg<0)
{
text.two <- lower.neg.pred - (lower.neg.pred * .20)
text(x = text.one_neg, y= text.two, labels = paste("r = ", round(R_neg,3), "\np = ", P_neg))
}
}
}else{
if(any(is.na(x$Pred)))
{
pos.na <- which(is.na(x$Pred))
bstat_pos <- x$behav[-pos.na]
behav_pred_pos <- x$Pred[-pos.na]
}else{
bstat_pos <- x$behav
behav_pred_pos <- x$Pred
}
R_pos<-cor(behav_pred_pos,bstat_pos,use="pairwise.complete.obs")
P_pos<-cor.test(behav_pred_pos,bstat_pos)$p.value
P_pos<-ifelse(round(P_pos,3)!=0,round(P_pos,3),noquote("< .001"))
lower.bstat_pos <- floor(range(bstat_pos))[1]
upper.bstat_pos <- ceiling(range(bstat_pos))[2]
lower.pos.pred <- floor(range(behav_pred_pos))[1]
upper.pos.pred <- ceiling(range(behav_pred_pos))[2]
text.one_pos <- lower.bstat_pos - (lower.bstat_pos * .20)
if(!is.null(groups))
{
labs_groups <- unique(groups)
n_groups <- length(labs_groups)
plot.args$col <- c(rep(cols[1],length(which(groups == labs_groups[1]))),
rep(cols[2],length(which(groups == labs_groups[2]))))
plot.args$pch <- c(rep(pchs[1],length(which(groups == labs_groups[1]))),
rep(pchs[2],length(which(groups == labs_groups[2]))))
plot.args$x <- bstat_pos
plot.args$y <- behav_pred_pos
plot.args$ylim <- c(lower.pos.pred, upper.pos.pred)
plot.args$xlim <- c(lower.bstat_pos, upper.bstat_pos)
plot.args$main <- mains[1]
dev.new()
par(mar=c(5,5,4,2))
do.call(plot, plot.args)
abline(lm(behav_pred_pos~bstat_pos))
if(R_pos>=0)
{
text.two <- upper.pos.pred - (upper.pos.pred * .20)
text(x = text.one_pos, y = text.two, labels = paste("r = ", round(R_pos,3), "\np = ", P_pos))
legend("bottomright", legend = labs_groups, col = c(cols[1], cols[2]), pch = c(pchs[1], pchs[2]))
}else if(R_pos<0)
{
text.two <- lower.pos.pred - (lower.pos.pred * .20)
text(x = text.one_pos, y = text.two, labels = paste("r = ", round(R_pos,3), "\np = ", P_pos))
legend("topright", legend = labs_groups, col = c(cols[1], cols[2]), pch = c(pchs[1], pchs[2]))
}
}else{
plot.args$col <- cols[1]
plot.args$pch <- pchs[1]
plot.args$x <- bstat_pos
plot.args$y <- behav_pred_pos
plot.args$ylim <- c(lower.pos.pred, upper.pos.pred)
plot.args$xlim <- c(lower.bstat_pos, upper.bstat_pos)
plot.args$main <- mains[1]
dev.new()
par(mar=c(5,5,4,2))
do.call(plot, plot.args)
abline(lm(behav_pred_pos~bstat_pos))
if(R_pos>=0)
{
text.two <- upper.pos.pred - (upper.pos.pred * .20)
text(x = text.one_pos, y = text.two, labels = paste("r = ", round(R_pos,3), "\np = ", P_pos))
}else if(R_pos<0)
{
text.two <- lower.pos.pred - (lower.pos.pred * .20)
text(x = text.one_pos, y = text.two, labels = paste("r = ", round(R_pos,3), "\np = ", P_pos))
}
}
}
} |
options( width=150, max.print=1000 )
library(samon, lib.loc="../../../../samlib")
trt1Results <- readRDS("RDS/treatment1Results.rds")
print(trt1Results) |
computeFST<-function(x,method="Anova",nsnp.per.bjack.block=0,sliding.window.size=0,verbose=TRUE){
if(!(method %in% c("Identity","Anova"))){stop("method should either be Identity or Anova (default)")}
if(!(is.pooldata(x)) & !(is.countdata(x))){
stop("Input data are not formatted as valid pooldata (see the popsync2pooldata, vcf2pooldata, genobaypass2pooldata and selestim2pooldata functions) or countdata (see the genobaypass2countdata and genotreemix2countdata) object\n")}
if(method=="Identity"){
if(is.countdata(x)){
snp.Q1=rowMeans(([email protected]*([email protected]) + ([email protected]@refallele.count)*([email protected]@refallele.count-1) )/([email protected]*([email protected])),na.rm=T)
hat.Q1=mean(snp.Q1,na.rm=T)
Q2.countdiff=matrix(0,x@nsnp,x@npops*(x@npops-1)/2)
Q2.counttot=matrix(0,x@nsnp,x@npops*(x@npops-1)/2)
cnt=0
for(i in 1:(x@npops-1)){
for(j in (i+1):x@npops){
cnt=cnt+1
Q2.countdiff[,cnt]=( [email protected][,i]*[email protected][,j] + ([email protected][,i][email protected][,i])*([email protected][,j][email protected][,j]))
Q2.counttot[,cnt]=([email protected][,i]*[email protected][,j])
}
}
snp.Q2=rowSums(Q2.countdiff)/rowSums(Q2.counttot)
rm(Q2.counttot,Q2.countdiff) ; gc()
hat.Q2=mean(snp.Q2,na.rm=TRUE)
}else{
Q1=([email protected]*([email protected]) + (x@[email protected])*(x@[email protected]) )/(x@readcoverage*(x@readcoverage-1))
Q1 = (1/(matrix(1,x@nsnp,x@npools) %*% diag(x@poolsizes-1)))*(Q1 %*% diag(x@poolsizes) - 1)
lambdaj=x@poolsizes*(x@poolsizes-1)
lambdaj=lambdaj/sum(lambdaj)
snp.Q1=rowSums(Q1%*%diag(lambdaj))
hat.Q1=mean(snp.Q1,na.rm=T)
rm(Q1) ; gc()
Q2=matrix(0,x@nsnp,x@npools*(x@npools-1)/2)
omegajj=rep(0,x@npools*(x@npools-1)/2)
cnt=0
for(i in 1:(x@npools-1)){
for(j in (i+1):x@npools){
cnt=cnt+1
omegajj[cnt]=x@poolsizes[i]*x@poolsizes[j]
Q2[,cnt]=( [email protected][,i]*[email protected][,j] +
(x@readcoverage[,i][email protected][,i])*(x@readcoverage[,j][email protected][,j]))/(x@readcoverage[,i]*x@readcoverage[,j])
}
}
snp.Q2=rowSums(Q2%*%diag(omegajj/sum(omegajj)))
hat.Q2=mean(snp.Q2,na.rm=TRUE)
rm(Q2) ; gc()
}
rslt=list(FST=(hat.Q1-hat.Q2)/(1-hat.Q2),snp.Q1=snp.Q1,snp.Q2=snp.Q2,snp.FST=(snp.Q1-snp.Q2)/(1-snp.Q2) )
rm(snp.Q1,snp.Q2) ; gc()
}
if (method=="Anova"){
if(is.countdata(x)){
SumNi=rowSums([email protected])
[email protected]([email protected]**2)/SumNi
Nc=rowSums(Nic)/(x@npops-1)
MSG=(rowSums([email protected]*([email protected]@refallele.count)/[email protected])) /(SumNi-x@npops)
PA=rowSums([email protected])/SumNi
MSP=(rowSums([email protected]*(([email protected]/[email protected])**2)))/(x@npops-1)
F_ST=(MSP-MSG)/(MSP+(Nc-1)*MSG)
F_ST_multi=mean(MSP-MSG,na.rm=T)/mean(MSP+(Nc-1)*MSG,na.rm=T)
rslt <- list(snp.FST = F_ST,snp.Q1 = 1 - MSG*2,snp.Q2 = 1 - MSG*2 - 2*(MSP - MSG) / Nc,FST = F_ST_multi)
snpNc=Nc
rm(F_ST,MSP,MSG) ; gc()
}else{
mtrx.n_i <- matrix(x@poolsizes,nrow = x@nsnp,ncol = x@npools,byrow = TRUE)
C_1 <- rowSums(x@readcoverage)
C_2 <- rowSums(x@readcoverage^2)
D_2 <- rowSums(x@readcoverage / mtrx.n_i + (mtrx.n_i - 1) / mtrx.n_i,na.rm = TRUE)
D_2.star <- rowSums(x@readcoverage * (x@readcoverage / mtrx.n_i + (mtrx.n_i - 1) / mtrx.n_i),na.rm = TRUE) / C_1
n_c <- (C_1 - C_2 / C_1) / (D_2 - D_2.star)
rm(C_2,mtrx.n_i) ; gc()
SSI <- 2*rowSums([email protected]*(x@[email protected])/x@readcoverage)
SA<-rowSums([email protected])/C_1
SSP<-2*rowSums(x@readcoverage*(([email protected]/x@readcoverage-SA)**2))
MSI <- SSI / (C_1 - D_2)
MSP <- SSP / (D_2 - D_2.star)
rm(C_1,D_2,D_2.star) ; gc()
F_ST <- (MSP - MSI) / (MSP + (n_c - 1) * MSI)
F_ST_multi <- sum(MSP - MSI,na.rm=T) / sum(MSP + (n_c- 1) * MSI,na.rm=T)
rslt <- list(snp.FST = F_ST,snp.Q1 = 1 - MSI,snp.Q2 = 1 - MSI - (MSP - MSI) / n_c,FST = F_ST_multi)
snpNc=n_c
rm(F_ST,MSI,MSP,n_c) ; gc()
}
snpNc[is.na(rslt$snp.Q1)|is.na(rslt$snp.Q2)]=NA
}
if(nsnp.per.bjack.block>0){
if(verbose){cat("Starting Block-Jackknife sampling\n")}
bjack.blocks=generate.jackknife.blocks(x,nsnp.per.bjack.block,verbose=verbose)
tmp.idx.sel=!is.na(bjack.blocks$snp.block.id)
tmp.snp.block.id=bjack.blocks$snp.block.id[!is.na(bjack.blocks$snp.block.id)]
if(method=="Anova"){
tmp.sampled.q1=as.vector(by(rslt$snp.Q1[tmp.idx.sel]*snpNc[tmp.idx.sel],tmp.snp.block.id,sum,na.rm=T))
tmp.sampled.q1=(sum(tmp.sampled.q1)-tmp.sampled.q1)
tmp.sampled.q2=as.vector(by(rslt$snp.Q2[tmp.idx.sel]*snpNc[tmp.idx.sel],tmp.snp.block.id,sum,na.rm=T))
tmp.sampled.q2=(sum(tmp.sampled.q2)-tmp.sampled.q2)
tmp.sampled.sumnc=as.vector(by(snpNc[tmp.idx.sel],tmp.snp.block.id,sum,na.rm=T))
tmp.sampled.sumnc=sum(tmp.sampled.sumnc)-tmp.sampled.sumnc
sampled.fst=(tmp.sampled.q1-tmp.sampled.q2) / (tmp.sampled.sumnc-tmp.sampled.q2)
}else{
tmp.sampled.q1=as.vector(by(rslt$snp.Q1[tmp.idx.sel],tmp.snp.block.id,sum,na.rm=T))
tmp.sampled.q1=(sum(tmp.sampled.q1)-tmp.sampled.q1)
tmp.sampled.q2=as.vector(by(rslt$snp.Q2[tmp.idx.sel],tmp.snp.block.id,sum,na.rm=T))
tmp.sampled.q2=(sum(tmp.sampled.q2)-tmp.sampled.q2)
tmp.snp.cnt=as.vector(by(1-(is.na(rslt$snp.Q1[tmp.idx.sel])|is.na(rslt$snp.Q2[tmp.idx.sel])),tmp.snp.block.id,sum,na.rm=T))
tmp.snp.cnt=sum(tmp.snp.cnt)-tmp.snp.cnt
sampled.fst=(tmp.sampled.q1-tmp.sampled.q2) / (tmp.snp.cnt-tmp.sampled.q2)
}
rslt[["mean.fst"]]=mean(sampled.fst)
rslt[["se.fst"]]=sd(sampled.fst)*(bjack.blocks$nblocks-1)/sqrt(bjack.blocks$nblocks)
rslt[["fst.bjack.samples"]]=sampled.fst
}
if(sliding.window.size>1){
if(verbose){cat("Start sliding-window scan\n")}
det.idx.per.chr=matrix(unlist(by(1:x@nsnp,[email protected][,1],range)),ncol=2,byrow=T)
if(nrow(det.idx.per.chr)==0){
cat("Exit function: No chr/contigs available (information on SNP contig name might not have been provided)\n")
}
det.idx.per.chr=cbind(det.idx.per.chr,det.idx.per.chr[,2]-det.idx.per.chr[,1]+1)
step=floor(sliding.window.size/2)
all.pos=all.fst=all.chr=all.cumpos=win.size=c()
tmp.cum=0
if(verbose){
n.chr.eval=sum(det.idx.per.chr[,3]>sliding.window.size)
cat(n.chr.eval,"chromosomes scanned (with more than",sliding.window.size,"SNPs)\n")
pb <- progress_bar$new(format = " [:bar] :percent eta: :eta",total = n.chr.eval, clear = FALSE, width= 60)
tmp.cnt=0
}
[email protected][,2]
for(i in 1:nrow(det.idx.per.chr)){
if(det.idx.per.chr[i,3]>sliding.window.size){
tmp.sel=det.idx.per.chr[i,1]:det.idx.per.chr[i,2]
tmp.pos=floor(rollmean(all.snp.pos[tmp.sel],k=sliding.window.size))
retained.pos=seq(1,length(tmp.pos),step)
tmp.pos=tmp.pos[retained.pos]
all.pos=c(all.pos,tmp.pos)
all.cumpos=c(all.cumpos,tmp.pos+tmp.cum)
tmp.cum=max(all.cumpos)
all.chr=c(all.chr,rep([email protected][tmp.sel[1],1],length(tmp.pos)))
if(method=="Anova"){
qq1=rollsum(rslt$snp.Q1[tmp.sel]*snpNc[tmp.sel],k=sliding.window.size,na.rm=T)[retained.pos]
qq2=rollsum(rslt$snp.Q2[tmp.sel]*snpNc[tmp.sel],k=sliding.window.size,na.rm=T)[retained.pos]
tmp.sumnc=rollsum(snpNc[tmp.sel],k=sliding.window.size,na.rm=T)[retained.pos]
tmp.fst=(qq1-qq2) / (tmp.sumnc-qq2)
}else{
qq1=rollsum(rslt$snp.Q1[tmp.sel],k=sliding.window.size,na.rm=T)[retained.pos]
qq2=rollsum(rslt$snp.Q2[tmp.sel],k=sliding.window.size,na.rm=T)[retained.pos]
tmp.snp.cnt=rollsum(1-(is.na(rslt$snp.Q1[tmp.sel])|is.na(rslt$snp.Q2[tmp.sel])),k=sliding.window.size)[retained.pos]
tmp.fst=(qq1-qq2) / (tmp.snp.cnt-qq2)
}
all.fst=c(all.fst,tmp.fst)
win.size=c(win.size,all.snp.pos[tmp.sel[retained.pos]+sliding.window.size-1]-all.snp.pos[tmp.sel[retained.pos]])
if(verbose){pb$tick()}
}
}
if(verbose){
cat("\nAverage (min-max) Window Sizes",round(mean(win.size*1e-3),1),"(",round(min(win.size*1e-3),1),"-",round(max(win.size*1e-3),1),") kb\n")
pb$terminate()}
rslt[["sliding.windows.fst"]]=data.frame(Chr=all.chr,Position=all.pos,CumulatedPosition=all.cumpos,MultiLocusFst=all.fst,stringsAsFactors=FALSE)
}
return(rslt)
} |
"tim.colors" <- function(n = 64, alpha = 1) {
orig <- c("
"
"
"
"
"
"
"
"
"
"
"
"
designer.colors( n, col=orig, alpha=alpha)
} |
rbpareto2 <-
function(n, prob, scale, shape)
{
if (max(length(prob), length(scale), length(shape)) > 1)
stop("parameters must be of length 1")
p <- runif(n)
q <- rep(0, length(p))
cases <- p > (1 - prob)
q[cases] <- rpareto2(sum(cases), scale = scale, shape = shape)
q
} |
require(atom4R, quietly = TRUE)
require(testthat)
require(XML)
require(httr)
context("SwordDataverseClient")
if(FALSE){
message("Dataverse server: sleeping during server configuration...")
Sys.sleep(time = 30)
ping <- try(status_code(GET('http://dataverse-dev.localhost:8085/')), silent = TRUE)
while(is(ping, "try-error") || ping == 500){
message("Dataverse server doesn't seem ready, sleeping 30s more...")
Sys.sleep(time = 30)
ping <- try(status_code(GET('http://dataverse-dev.localhost:8085/')), silent = TRUE)
}
message("Dataverse server ready for testing...")
initAPI <- function(){
return(
try(SwordDataverseClient$new(
hostname = "http://dataverse-dev.localhost:8085",
token = "dbf293b4-d13e-45d4-99c6-f0cf18159f0d",
logger = "DEBUG"
), silent = TRUE)
)
}
message("Dataverse SWORD API: sleeping during API configuration...")
Sys.sleep(30)
API <- initAPI()
while(is(API, "try-error")){
message("Dataverse SWORD API doesn't seem ready: sleeping 30s more...")
Sys.sleep(30)
API <- initAPI()
}
message("Dataverse SWORD API ready for testing...")
if(is(API, "SwordDataverseClient")){
test_that("list Dataverses (Sword collections)",{
testthat::skip_on_cran()
cols <- API$listCollections()
expect_is(cols, "list")
expect_true(length(cols)>0)
})
test_that("list Dataverse members",{
testthat::skip_on_cran()
members <- API$getCollectionMembers("Root")
expect_is(members, "AtomFeed")
})
test_that("create DC entry",{
testthat::skip_on_cran()
dcentry <- DCEntry$new()
dcentry$setId("my-dc-entry")
dcentry$addDCDate(Sys.time())
dcentry$addDCTitle("atom4R - Tools to read/write and publish metadata as Atom XML format")
dcentry$addDCType("Software")
creator <- DCCreator$new(value = "Blondel, Emmanuel")
dcentry$addDCCreator(creator)
dcentry$addDCSubject("R")
dcentry$addDCSubject("FAIR")
dcentry$addDCSubject("Interoperability")
dcentry$addDCSubject("Open Science")
dcentry$addDCSubject("Dataverse")
dcentry$addDCDescription("Atom4R offers tools to read/write and publish metadata as Atom XML syndication format, including Dublin Core entries. Publication can be done using the Sword API which implements AtomPub API specifications")
dcentry$addDCPublisher("GitHub")
funder <- DCContributor$new(value = "CNRS")
funder$attrs[["Type"]] <- "Funder"
dcentry$addDCContributor(funder)
contact <- DCContributor$new(value = "[email protected]")
contact$attrs[["Type"]] <- "Contact"
dcentry$addDCContributor(contact)
editor <- DCContributor$new(value = "[email protected]")
editor$attrs[["Type"]] <- "Editor"
dcentry$addDCContributor(editor)
dcentry$addDCRelation("Github repository: https://github.com/eblondel/atom4R")
relation = DCRelation$new()
dcentry$addDCRelation("CRAN repository: Not yet available")
dcentry$addDCSource("Atom Syndication format - https://www.ietf.org/rfc/rfc4287")
dcentry$addDCSource("AtomPub, The Atom publishing protocol - https://tools.ietf.org/html/rfc5023")
dcentry$addDCSource("Sword API - http://swordapp.org/")
dcentry$addDCSource("Dublin Core Metadata Initiative - https://www.dublincore.org/")
dcentry$addDCSource("Guidelines for implementing Dublin Core in XML - https://www.dublincore.org/specifications/dublin-core/dc-xml-guidelines/")
dcentry$addDCLicense("NONE")
dcentry$addDCRights("MIT License")
out <- API$createDataverseRecord("dynids", dcentry)
expect_is(out, "AtomEntry")
})
}
} |
lav_efa_pace <- function(S, nfactors = 1L, p.idx = seq_len(ncol(S)),
reflect = TRUE, order.lv.by = "none",
use.R = TRUE, theta.only = TRUE) {
S <- unname(S)
nvar <- ncol(S)
theta <- numeric(nvar)
stopifnot(nfactors < nvar / 2)
if(use.R) {
s.var <- diag(S)
R <- stats::cov2cor(S)
} else {
R <- S
}
A <- R
v.r <- integer(0L)
v.c <- integer(0L)
for(h in seq_len(nfactors)) {
mask.idx <- c(v.r, v.c)
tmp <- abs(A)
if(length(mask.idx) > 0L) {
tmp[mask.idx,] <- 0; tmp[,mask.idx] <- 0
}
diag(tmp) <- 0
idx <- which(tmp == max(tmp), arr.ind = TRUE, useNames = FALSE)[1,]
k <- idx[1]; l <- idx[2]
v.r <- c(v.r, k); v.c <- c(v.c, l)
a.kl <- A[k, l]
if(abs(a.kl) < sqrt(.Machine$double.eps)) {
out <- A; out[k,] <- 0; out[,l] <- 0
} else {
out <- A - tcrossprod(A[,l], A[k,])/a.kl
out[k,] <- A[k,]/a.kl
out[,l] <- - A[,l]/a.kl
out[k,l] <- 1/a.kl
}
A <- out
}
all.idx <- seq_len(nvar)
v.r.init <- v.r
v.c.init <- v.c
other.idx <- all.idx[-c(v.r, v.c)]
theta[other.idx] <- diag(A)[other.idx]
for(i in p.idx) {
if(i %in% other.idx) {
next
}
v.r <- integer(0L)
v.c <- integer(0L)
A <- R
for(h in seq_len(nfactors)) {
mask.idx <- c(i, v.r, v.c)
tmp <- abs(A)
tmp[mask.idx,] <- 0; tmp[,mask.idx] <- 0; diag(tmp) <- 0
idx <- which(tmp == max(tmp), arr.ind = TRUE, useNames = FALSE)[1,]
k <- idx[1]; l <- idx[2]
v.r <- c(v.r, k); v.c <- c(v.c, l)
a.kl <- A[k, l]
if(abs(a.kl) < sqrt(.Machine$double.eps)) {
out <- A; out[k,] <- 0; out[,l] <- 0
} else {
out <- A - tcrossprod(A[,l], A[k,])/a.kl
out[k,] <- A[k,]/a.kl
out[,l] <- - A[,l]/a.kl
out[k,l] <- 1/a.kl
}
A <- out
}
theta[i] <- A[i, i]
}
if(theta.only) {
if(use.R) {
theta <- theta * s.var
}
return(theta[p.idx])
}
EV <- eigen(R, symmetric = TRUE)
S.sqrt <- EV$vectors %*% sqrt(diag(EV$values)) %*% t(EV$vectors)
S.inv.sqrt <- EV$vectors %*% sqrt(diag(1/EV$values)) %*% t(EV$vectors)
RTR <- S.inv.sqrt %*% diag(theta) %*% S.inv.sqrt
EV <- eigen(RTR, symmetric = TRUE)
Omega.m <- EV$vectors[, 1L + nvar - seq_len(nfactors), drop = FALSE]
gamma.m <- EV$values[1L + nvar - seq_len(nfactors)]
Gamma.m <- diag(gamma.m, nrow = nfactors, ncol = nfactors)
LAMBDA.dot <- S.sqrt %*% Omega.m %*% sqrt(diag(nfactors) - Gamma.m)
if(use.R) {
LAMBDA <- sqrt(s.var) * LAMBDA.dot
THETA <- diag(s.var * theta)
} else {
LAMBDA <- LAMBDA.dot
THETA <- diag(theta)
}
if(reflect) {
SUM <- colSums(LAMBDA)
neg.idx <- which(SUM < 0)
if(length(neg.idx) > 0L) {
LAMBDA[, neg.idx] <- -1 * LAMBDA[, neg.idx, drop = FALSE]
}
}
if(order.lv.by == "sumofsquares") {
L2 <- LAMBDA * LAMBDA
order.idx <- base::order(colSums(L2), decreasing = TRUE)
} else if(order.lv.by == "index") {
max.loading <- apply(abs(LAMBDA), 2, max)
average.index <- sapply(seq_len(ncol(LAMBDA)), function(i)
mean(which(abs(LAMBDA[,i]) >= 0.8 * max.loading[i])))
order.idx <- base::order(average.index)
} else if(order.lv.by == "none") {
order.idx <- seq_len(ncol(LAMBDA))
} else {
stop("lavaan ERROR: order must be index, sumofsquares or none")
}
LAMBDA <- LAMBDA[, order.idx, drop = FALSE]
list(LAMBDA = LAMBDA, THETA = THETA)
} |
plot.SPF.BinBin <- function(x, Type="All.Histograms", Specific.Pi="r_0_0", Col="grey",
Box.Plot.Outliers=FALSE, Legend.Pos="topleft", Legend.Cex=1, ...){
Object <- x
if (missing(Col)) {Col = "grey"}
if (Type=="All.Histograms"){
if ((length(unique(Object$r_min1_min1))> 1) & (length(unique(Object$r_0_min1))> 1) &
(length(unique(Object$r_min1_0))> 1)){
plot(0:100, 0:100, axes=F, xlab="", ylab="", type="n", ..., xlim=c(0, 1))
par(mfrow=c(3, 3), mar = c(4.5, 7, 4, 1), oma=rep(0, times=4))
if (length(unique(Object$r_min1_min1)) > 1){
hist(Object$r_min1_min1, main="", col=Col, xlim=c(0, 1),
xlab=expression(r(-1,-1)), cex.lab=1.3)}
if (length(unique(Object$r_min1_min1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_0_min1)) > 1){
hist(Object$r_0_min1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(0,-1)))}
if (length(unique(Object$r_0_min1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_min1)) > 1){
hist(Object$r_1_min1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(1,-1)))}
if (length(unique(Object$r_1_min1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_min1_0)) > 1){
hist(Object$r_min1_0, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(-1,0)))}
if (length(unique(Object$r_min1_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_0_0)) > 1){
hist(Object$r_0_0, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(0,0)))}
if (length(unique(Object$r_0_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_0)) > 1){
hist(Object$r_1_0, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(1,0)))}
if (length(unique(Object$r_1_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_min1_1)) > 1){
hist(Object$r_min1_1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(-1,1)))}
if (length(unique(Object$r_min1_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_0_1)) > 1){
hist(Object$r_0_1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(0,1)))}
if (length(unique(Object$r_0_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_1)) > 1){
hist(Object$r_1_1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(1,1)))}
if (length(unique(Object$r_1_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
}
if ((length(unique(Object$r_min1_min1))==1) & (length(unique(Object$r_0_min1))==1) &
(length(unique(Object$r_min1_0))==1)){
plot(0:100, 0:100, axes=F, xlab="", ylab="", type="n", ..., xlim=c(0, 1))
par(mfrow=c(2, 2), mar = c(4.5, 7, 4, 1), oma=rep(0, times=4))
if (length(unique(Object$r_0_0)) > 1){
hist(Object$r_0_0, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(0,0)))}
if (length(unique(Object$r_0_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_0)) > 1){
hist(Object$r_1_0, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(1,0)))}
if (length(unique(Object$r_1_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_0_1)) > 1){
hist(Object$r_0_1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(0,1)))}
if (length(unique(Object$r_0_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_1)) > 1){
hist(Object$r_1_1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(1,1)))}
if (length(unique(Object$r_1_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
}
if ((length(unique(Object$r_min1_min1))==1) & (length(unique(Object$r_0_min1))== 1) &
(length(unique(Object$r_min1_0))> 1)){
plot(0:100, 0:100, axes=F, xlab="", ylab="", type="n", ..., xlim=c(0, 1))
par(mfrow=c(2, 3), mar = c(4.5, 7, 4, 1), oma=rep(0, times=4))
if (length(unique(Object$r_min1_0)) > 1){
hist(Object$r_min1_0, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(-1,0)))}
if (length(unique(Object$r_min1_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_0_0)) > 1){
hist(Object$r_0_0, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(0,0)))}
if (length(unique(Object$r_0_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_0)) > 1){
hist(Object$r_1_0, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(1,0)))}
if (length(unique(Object$r_1_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_min1_1)) > 1){
hist(Object$r_min1_1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(-1,1)))}
if (length(unique(Object$r_min1_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_0_1)) > 1){
hist(Object$r_0_1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(0,1)))}
if (length(unique(Object$r_0_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_1)) > 1){
hist(Object$r_1_1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(1,1)))}
if (length(unique(Object$r_1_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
}
if ((length(unique(Object$r_min1_min1))==1) & (length(unique(Object$r_0_min1))>1) &
(length(unique(Object$r_min1_0))==1)){
plot(0:100, 0:100, axes=F, xlab="", ylab="", type="n", ..., xlim=c(0, 1))
par(mfrow=c(3, 2), mar = c(4.5, 7, 4, 1), oma=rep(0, times=4))
if (length(unique(Object$r_0_min1)) > 1){
hist(Object$r_0_min1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(0,-1)))}
if (length(unique(Object$r_0_min1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_min1)) > 1){
hist(Object$r_1_min1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(1,-1)))}
if (length(unique(Object$r_1_min1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_0_0)) > 1){
hist(Object$r_0_0, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(0,0)))}
if (length(unique(Object$r_0_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_0)) > 1){
hist(Object$r_1_0, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(1,0)))}
if (length(unique(Object$r_1_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_0_1)) > 1){
hist(Object$r_0_1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(0,1)))}
if (length(unique(Object$r_0_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_1)) > 1){
hist(Object$r_1_1, main=" ", col=Col, cex.lab=1.3, xlim=c(0, 1),
xlab=expression(r(1,1)))}
if (length(unique(Object$r_1_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
}
par(mfrow=c(1, 1), c(5, 4, 4, 2) + 0.1)
}
if (Type=="All.Densities"){
plot(0:100, 0:100, axes=F, xlab="", ylab="", type="n", ..., xlim=c(0, 1))
par(mfrow=c(3, 3), mar = c(4.5, 7, 4, 1), oma=rep(0, times=4), xpd=FALSE)
if (length(unique(Object$r_min1_min1)) > 1){
plot(density(Object$r_min1_min1, na.rm=T), main=" ", col=Col, cex.lab=1.3, ..., xlim=c(0, 1),
xlab=expression(r(-1,-1)))
}
if (length(unique(Object$r_min1_min1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
mtext(side = 3, expression(paste(Delta, "T = -1")), cex=1.5, padj = -1.6)
mtext(side = 2, expression(paste(Delta, "S = -1")), cex=1.5, padj = -3.6)
if (length(unique(Object$r_0_min1)) > 1){
plot(density(Object$r_0_min1, na.rm=T), main=" ", col=Col, cex.lab=1.3, ...,xlim=c(0, 1),
xlab=expression(r(0,-1)))}
if (length(unique(Object$r_0_min1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ")}
mtext(side = 3, expression(paste(Delta, "T = 0")), cex=1.5, padj = -1.6)
if (length(unique(Object$r_1_min1)) > 1){
plot(density(Object$r_1_min1, na.rm=T), main=" ", col=Col, cex.lab=1.3, ...,xlim=c(0, 1),
xlab=expression(r(1,-1)))}
if (length(unique(Object$r_1_min1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ")}
mtext(side = 3, expression(paste(Delta, "T = 1")), cex=1.5, padj = -1.6)
if (length(unique(Object$r_min1_0)) > 1){
plot(density(Object$r_min1_0, na.rm=T), main=" ", col=Col, cex.lab=1.3, ...,xlim=c(0, 1),
xlab=expression(r(-1,0)))}
if (length(unique(Object$r_min1_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ")}
mtext(side = 2, expression(paste(Delta, "S = 0")), cex=1.5, padj = -3.6)
if (length(unique(Object$r_0_0)) > 1){
plot(density(Object$r_0_0, na.rm=T), main=" ", col=Col, cex.lab=1.3, ...,xlim=c(0, 1),
xlab=expression(r(0,0)))}
if (length(unique(Object$r_0_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ")}
if (length(unique(Object$r_1_0)) > 1){
plot(density(Object$r_1_0, na.rm=T), main=" ", col=Col, cex.lab=1.3, ...,xlim=c(0, 1),
xlab=expression(r(1,0)))}
if (length(unique(Object$r_1_0)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_min1_1)) > 1){
plot(density(Object$r_min1_1, na.rm=T), main=" ", col=Col, cex.lab=1.3, ...,xlim=c(0, 1),
xlab=expression(r(-1,1)))}
if (length(unique(Object$r_min1_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
mtext(side = 2, expression(paste(Delta, "S = 1")), cex=1.5, padj = -3.6)
if (length(unique(Object$r_0_1)) > 1){
plot(density(Object$r_0_1, na.rm=T), main=" ", col=Col, cex.lab=1.3, ...,xlim=c(0, 1),
xlab=expression(r(0,1)))}
if (length(unique(Object$r_0_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
if (length(unique(Object$r_1_1)) > 1){
plot(density(Object$r_1_1, na.rm=T), main=" ", col=Col, cex.lab=1.3, ...,xlim=c(0, 1),
xlab=expression(r(1,1)))}
if (length(unique(Object$r_1_1)) <= 1){
plot(x=0, col=0, axes=F, xlab="", ylab= " ", ...)}
par(mfrow=c(1, 1), c(5, 4, 4, 2) + 0.1)
}
if (Type=="Histogram"){
par(mfrow=c(1, 1), c(5, 4, 4, 2) + 0.1)
if (Specific.Pi == "r_min1_min1"){
if (length(unique(Object$r_min1_min1)) > 1){
hist(Object$r_min1_min1, main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(-1,-1)))}
if (length(unique(Object$r_min1_min1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_0_min1"){
if (length(unique(Object$r_0_min1)) > 1){
hist(Object$r_0_min1, main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(0,-1)))}
if (length(unique(Object$r_0_min1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_1_min1"){
if (length(unique(Object$r_1_min1)) > 1){
hist(Object$r_1_min1, main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(1,-1)))}
if (length(unique(Object$r_1_min1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_min1_0"){
if (length(unique(Object$r_min1_0)) > 1){
hist(Object$r_min1_0, main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(-1,0)))}
if (length(unique(Object$r_min1_0)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_0_0"){
if (length(unique(Object$r_0_0)) > 1){
hist(Object$r_0_0, main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(0,0)))}
if (length(unique(Object$r_0_0)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_1_0"){
if (length(unique(Object$r_1_0)) > 1){
hist(Object$r_1_0, main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(1,0)))}
if (length(unique(Object$r_1_0)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_min1_1"){
if (length(unique(Object$r_min1_1)) > 1){
hist(Object$r_min1_1, main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(-1,1)))}
if (length(unique(Object$r_min1_1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_0_1"){
if (length(unique(Object$r_0_1)) > 1){
hist(Object$r_0_1, main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(0,1)))}
if (length(unique(Object$r_0_1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_1_1"){
if (length(unique(Object$r_1_1)) > 1){
hist(Object$r_1_1, main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(1,1)))}
if (length(unique(Object$r_1_1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
}
if (Type=="Density"){
par(mfrow=c(1, 1), c(5, 4, 4, 2) + 0.1)
if (Specific.Pi == "r_min1_min1"){
if (length(unique(Object$r_min1_min1)) > 1){
plot(density(Object$r_min1_min1, na.rm=T), main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(-1,-1)))
}
if (length(unique(Object$r_min1_min1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_0_min1"){
if (length(unique(Object$r_0_min1)) > 1){
plot(density(Object$r_0_min1, na.rm=T), main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(0,-1)))}
if (length(unique(Object$r_0_min1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_1_min1"){
if (length(unique(Object$r_1_min1)) > 1){
plot(density(Object$r_1_min1, na.rm=T), main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(1,-1)))}
if (length(unique(Object$r_1_min1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_min1_0"){
if (length(unique(Object$r_min1_0)) > 1){
plot(density(Object$r_min1_0, na.rm=T), main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(-1,0)))}
if (length(unique(Object$r_min1_0)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_0_0"){
if (length(unique(Object$r_0_0)) > 1){
plot(density(Object$r_0_0, na.rm=T), main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(0,0)))}
if (length(unique(Object$r_0_0)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_1_0"){
if (length(unique(Object$r_1_0)) > 1){
plot(density(Object$r_1_0, na.rm=T), main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(1,0)))}
if (length(unique(Object$r_1_0)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_min1_1"){
if (length(unique(Object$r_min1_1)) > 1){
plot(density(Object$r_min1_1, na.rm=T), main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(-1,1)))}
if (length(unique(Object$r_min1_1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_0_1"){
if (length(unique(Object$r_0_1)) > 1){
plot(density(Object$r_0_1, na.rm=T), main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(0,1)))}
if (length(unique(Object$r_0_1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
if (Specific.Pi == "r_1_1"){
if (length(unique(Object$r_1_1)) > 1){
plot(density(Object$r_1_1, na.rm=T), main=" ", col=Col, ...,xlim=c(0, 1),
xlab=expression(r(1,1)))}
if (length(unique(Object$r_1_1)) <= 1){
cat("\nNo valid pi values were found. \n")}
}
}
if (Type=="Box.Plot"){
par(mfrow=c(1, 1), c(5, 4, 4, 2) + 0.1)
if (length(unique(Object$r_min1_min1)) > 1){
a <- cbind(Object$r_min1_min1, "a")}
if (length(unique(Object$r_min1_min1)) <= 1){
a <- cbind(NA, "a")}
if (length(unique(Object$r_0_min1)) > 1){
b <- cbind(Object$r_0_min1, "b")}
if (length(unique(Object$r_0_min1)) <= 1){
b <- cbind(NA, "b")}
if (length(unique(Object$r_1_min1)) > 1){
c <- cbind(Object$r_1_min1, "c")}
if (length(unique(Object$r_1_min1)) <= 1){
c <- cbind(NA, "c")}
if (length(unique(Object$r_min1_0)) > 1){
d <- cbind(Object$r_min1_0, "d")}
if (length(unique(Object$r_min1_0)) <= 1){
d <- cbind(NA, "d")}
if (length(unique(Object$r_0_0)) > 1){
e <- cbind(Object$r_0_0, "e")}
if (length(unique(Object$r_0_0)) <= 1){
e <- cbind(NA, "e")}
if (length(unique(Object$r_1_0)) > 1){
f <- cbind(Object$r_1_0, "f")}
if (length(unique(Object$r_1_0)) <= 1){
f <- cbind(NA, "f")}
if (length(unique(Object$r_min1_1)) > 1){
g <- cbind(Object$r_min1_1, "g")}
if (length(unique(Object$r_min1_1)) <= 1){
g <- cbind(NA, "g")}
if (length(unique(Object$r_0_1)) > 1){
h <- cbind(Object$r_0_1, "h")}
if (length(unique(Object$r_0_1)) <= 1){
h <- cbind(NA, "h")}
if (length(unique(Object$r_1_1)) > 1){
i <- cbind(Object$r_1_1, "i")}
if (length(unique(Object$r_1_1)) <= 1){
i <- cbind(NA, "i")}
data <- data.frame(rbind(a, b, c, d, e, f, g, h, i))
as.numeric.factor <- function(x) {as.numeric(levels(x))[x]}
boxplot(as.numeric.factor(data$X1) ~ data$X2, col=rep(c(2, 3, 4), times=3), names=rep(c(-1, 0, 1), each=3),
outline = Box.Plot.Outliers, xlab=expression(paste(Delta, S)), ...)
abline(v = c(3.5, 6.5), col="blue", lty=3)
legend(Legend.Pos, cex = Legend.Cex, c(expression(paste(Delta, "T=-1")), expression(paste(Delta, "T=0")), expression(paste(Delta, "T=1"))),
fill = c(2, 3, 4))
}
if (Type=="Lines.Mean"){
if (length(unique(Object$r_min1_min1)) > 1){
a <- cbind(mean(Object$r_min1_min1), "a")}
if (length(unique(Object$r_min1_min1)) <= 1){
a <- cbind(NA, "a")}
if (length(unique(Object$r_0_min1)) > 1){
b <- cbind(mean(Object$r_0_min1), "b")}
if (length(unique(Object$r_0_min1)) <= 1){
b <- cbind(NA, "b")}
if (length(unique(Object$r_1_min1)) > 1){
c <- cbind(mean(Object$r_1_min1), "c")}
if (length(unique(Object$r_1_min1)) <= 1){
c <- cbind(NA, "c")}
if (length(unique(Object$r_min1_0)) > 1){
d <- cbind(mean(Object$r_min1_0), "d")}
if (length(unique(Object$r_min1_0)) <= 1){
d <- cbind(NA, "d")}
if (length(unique(Object$r_0_0)) > 1){
e <- cbind(mean(Object$r_0_0), "e")}
if (length(unique(Object$r_0_0)) <= 1){
e <- cbind(NA, "e")}
if (length(unique(Object$r_1_0)) > 1){
f <- cbind(mean(Object$r_1_0), "f")}
if (length(unique(Object$r_1_0)) <= 1){
f <- cbind(NA, "f")}
if (length(unique(Object$r_min1_1)) > 1){
g <- cbind(mean(Object$r_min1_1), "g")}
if (length(unique(Object$r_min1_1)) <= 1){
g <- cbind(NA, "g")}
if (length(unique(Object$r_0_1)) > 1){
h <- cbind(mean(Object$r_0_1), "h")}
if (length(unique(Object$r_0_1)) <= 1){
h <- cbind(NA, "h")}
if (length(unique(Object$r_1_1)) > 1){
i <- cbind(mean(Object$r_1_1), "i")}
if (length(unique(Object$r_1_1)) <= 1){
i <- cbind(NA, "i")}
data <- data.frame(rbind(a, b, c, d, e, f, g, h, i))
as.numeric.factor <- function(x) {as.numeric(levels(x))[x]}
plot(as.numeric.factor(data$X1), col=rep(c(2, 3, 4), times=3), axes=FALSE, type="h", lwd=5,
xlab=expression(paste(Delta, S)), ylab="Mean", ...)
axis(1, at = c(1:9), labels = rep(c(-1, 0, 1), each=3))
axis(2)
box()
legend(Legend.Pos, cex = Legend.Cex, c(expression(paste(Delta, "T=-1")), expression(paste(Delta, "T=0")),
expression(paste(Delta, "T=1"))), lty=rep(1, times=3), col=c(2, 3, 4), lwd=c(5, 5, 5))
abline(v = c(3.5, 6.5), col="blue", lty=3)
}
if (Type=="Lines.Median"){
if (length(unique(Object$r_min1_min1)) > 1){
a <- cbind(median(Object$r_min1_min1), "a")}
if (length(unique(Object$r_min1_min1)) <= 1){
a <- cbind(NA, "a")}
if (length(unique(Object$r_0_min1)) > 1){
b <- cbind(median(Object$r_0_min1), "b")}
if (length(unique(Object$r_0_min1)) <= 1){
b <- cbind(NA, "b")}
if (length(unique(Object$r_1_min1)) > 1){
c <- cbind(median(Object$r_1_min1), "c")}
if (length(unique(Object$r_1_min1)) <= 1){
c <- cbind(NA, "c")}
if (length(unique(Object$r_min1_0)) > 1){
d <- cbind(median(Object$r_min1_0), "d")}
if (length(unique(Object$r_min1_0)) <= 1){
d <- cbind(NA, "d")}
if (length(unique(Object$r_0_0)) > 1){
e <- cbind(median(Object$r_0_0), "e")}
if (length(unique(Object$r_0_0)) <= 1){
e <- cbind(NA, "e")}
if (length(unique(Object$r_1_0)) > 1){
f <- cbind(median(Object$r_1_0), "f")}
if (length(unique(Object$r_1_0)) <= 1){
f <- cbind(NA, "f")}
if (length(unique(Object$r_min1_1)) > 1){
g <- cbind(median(Object$r_min1_1), "g")}
if (length(unique(Object$r_min1_1)) <= 1){
g <- cbind(NA, "g")}
if (length(unique(Object$r_0_1)) > 1){
h <- cbind(median(Object$r_0_1), "h")}
if (length(unique(Object$r_0_1)) <= 1){
h <- cbind(NA, "h")}
if (length(unique(Object$r_1_1)) > 1){
i <- cbind(median(Object$r_1_1), "i")}
if (length(unique(Object$r_1_1)) <= 1){
i <- cbind(NA, "i")}
data <- data.frame(rbind(a, b, c, d, e, f, g, h, i))
as.numeric.factor <- function(x) {as.numeric(levels(x))[x]}
plot(as.numeric.factor(data$X1), col=rep(c(2, 3, 4), times=3), axes=FALSE, type="h", lwd=5,
xlab=expression(paste(Delta, S)), ylab="Median", ...)
axis(1, at = c(1:9), labels = rep(c(-1, 0, 1), each=3))
axis(2)
box()
legend(Legend.Pos, cex = Legend.Cex, c(expression(paste(Delta, "T=-1")), expression(paste(Delta, "T=0")),
expression(paste(Delta, "T=1"))), lty=rep(1, times=3), col=c(2, 3, 4), lwd=c(5, 5, 5))
abline(v = c(3.5, 6.5), col="blue", lty=3)
}
if (Type=="Lines.Mode"){
mode <- function(data) {
x <- data
if (unique(x[1])!=0){
z <- density(x)
mode_val <- z$x[which.max(z$y)]
if (mode_val < 0){mode_val <- c(0)}
}
if (unique(x[1])==0){
model_val <- c(0)
}
fit <- list(mode_val= mode_val)
}
if (length(unique(Object$r_min1_min1)) > 1){
a <- cbind(mode(Object$r_min1_min1)$mode_val, "a")}
if (length(unique(Object$r_min1_min1)) <= 1){
a <- cbind(NA, "a")}
if (length(unique(Object$r_0_min1)) > 1){
b <- cbind(mode(Object$r_0_min1)$mode_val, "b")}
if (length(unique(Object$r_0_min1)) <= 1){
b <- cbind(NA, "b")}
if (length(unique(Object$r_1_min1)) > 1){
c <- cbind(mode(Object$r_1_min1)$mode_val, "c")}
if (length(unique(Object$r_1_min1)) <= 1){
c <- cbind(NA, "c")}
if (length(unique(Object$r_min1_0)) > 1){
d <- cbind(mode(Object$r_min1_0)$mode_val, "d")}
if (length(unique(Object$r_min1_0)) <= 1){
d <- cbind(NA, "d")}
if (length(unique(Object$r_0_0)) > 1){
e <- cbind(mode(Object$r_0_0)$mode_val, "e")}
if (length(unique(Object$r_0_0)) <= 1){
e <- cbind(NA, "e")}
if (length(unique(Object$r_1_0)) > 1){
f <- cbind(mode(Object$r_1_0)$mode_val, "f")}
if (length(unique(Object$r_1_0)) <= 1){
f <- cbind(NA, "f")}
if (length(unique(Object$r_min1_1)) > 1){
g <- cbind(mode(Object$r_min1_1)$mode_val, "g")}
if (length(unique(Object$r_min1_1)) <= 1){
g <- cbind(NA, "g")}
if (length(unique(Object$r_0_1)) > 1){
h <- cbind(mode(Object$r_0_1)$mode_val, "h")}
if (length(unique(Object$r_0_1)) <= 1){
h <- cbind(NA, "h")}
if (length(unique(Object$r_1_1)) > 1){
i <- cbind(mode(Object$r_1_1)$mode_val, "i")}
if (length(unique(Object$r_1_1)) <= 1){
i <- cbind(NA, "i")}
data <-
data.frame(rbind(a, b, c, d, e, f, g, h, i))
as.numeric.factor <- function(x) {as.numeric(levels(x))[x]}
plot(as.numeric.factor(data$X1), col=rep(c(2, 3, 4), times=3), axes=FALSE, type="h", ...,
xlab=expression(paste(Delta, S)), ylab="Mode", lwd=5)
axis(1, at = c(1:9), labels = rep(c(-1, 0, 1), each=3))
axis(2)
box()
legend(Legend.Pos, cex = Legend.Cex, c(expression(paste(Delta, "T=-1")), expression(paste(Delta, "T=0")),
expression(paste(Delta, "T=1"))), lty=rep(1, times=3), col=c(2, 3, 4), lwd=c(5, 5, 5))
abline(v = c(3.5, 6.5), col="blue", lty=3)
}
if (Type=="3D.Mean"){
if (length(unique(Object$r_min1_min1)) > 1){
a <- cbind(mean(Object$r_min1_min1), -1, -1)}
if (length(unique(Object$r_min1_min1)) <= 1){
a <- cbind(NA, -1, -1)}
if (length(unique(Object$r_0_min1)) > 1){
b <- cbind(mean(Object$r_0_min1), 0, -1)}
if (length(unique(Object$r_0_min1)) <= 1){
b <- cbind(NA, 0, -1)}
if (length(unique(Object$r_1_min1)) > 1){
c <- cbind(mean(Object$r_1_min1), 1, -1)}
if (length(unique(Object$r_1_min1)) <= 1){
c <- cbind(NA, 1, -1)}
if (length(unique(Object$r_min1_0)) > 1){
d <- cbind(mean(Object$r_min1_0), -1, 0)}
if (length(unique(Object$r_min1_0)) <= 1){
d <- cbind(NA, -1, 0)}
if (length(unique(Object$r_0_0)) > 1){
e <- cbind(mean(Object$r_0_0), 0, 0)}
if (length(unique(Object$r_0_0)) <= 1){
e <- cbind(NA, 0, 0)}
if (length(unique(Object$r_1_0)) > 1){
f <- cbind(mean(Object$r_1_0), 1, 0)}
if (length(unique(Object$r_1_0)) <= 1){
f <- cbind(NA, 1, 0)}
if (length(unique(Object$r_min1_1)) > 1){
g <- cbind(mean(Object$r_min1_1), -1, 1)}
if (length(unique(Object$r_min1_1)) <= 1){
g <- cbind(NA, -1, 1)}
if (length(unique(Object$r_0_1)) > 1){
h <- cbind(mean(Object$r_0_1), 0, 1)}
if (length(unique(Object$r_0_1)) <= 1){
h <- cbind(NA, 0, 1)}
if (length(unique(Object$r_1_1)) > 1){
i <- cbind(mean(Object$r_1_1), 1, 1)}
if (length(unique(Object$r_1_1)) <= 1){
i <- cbind(NA, 1, 1)}
data <- data.frame(rbind(a, b, c, d, e, f, g, h, i))
names(data) <- c("Y", "Delta_T", "Delta_S")
temp <- lattice::cloud(Y ~ as.factor(Delta_S) + as.factor(Delta_T), data, panel.3d.cloud=latticeExtra::panel.3dbars,
xbase=0.4, ybase=0.4, scales=list(arrows=FALSE, col=1),
par.settings = list(axis.line = list(col = "transparent")),
xlab=expression(paste(Delta, "S")), ylab=expression(paste(Delta, T)),
zlab="Mean", col.facet=rep(c(2:4), each=3))
plot(temp)
}
if (Type=="3D.Median"){
if (length(unique(Object$r_min1_min1)) > 1){
a <- cbind(median(Object$r_min1_min1), -1, -1)}
if (length(unique(Object$r_min1_min1)) <= 1){
a <- cbind(NA, -1, -1)}
if (length(unique(Object$r_0_min1)) > 1){
b <- cbind(median(Object$r_0_min1), 0, -1)}
if (length(unique(Object$r_0_min1)) <= 1){
b <- cbind(NA, 0, -1)}
if (length(unique(Object$r_1_min1)) > 1){
c <- cbind(median(Object$r_1_min1), 1, -1)}
if (length(unique(Object$r_1_min1)) <= 1){
c <- cbind(NA, 1, -1)}
if (length(unique(Object$r_min1_0)) > 1){
d <- cbind(median(Object$r_min1_0), -1, 0)}
if (length(unique(Object$r_min1_0)) <= 1){
d <- cbind(NA, -1, 0)}
if (length(unique(Object$r_0_0)) > 1){
e <- cbind(median(Object$r_0_0), 0, 0)}
if (length(unique(Object$r_0_0)) <= 1){
e <- cbind(NA, 0, 0)}
if (length(unique(Object$r_1_0)) > 1){
f <- cbind(median(Object$r_1_0), 1, 0)}
if (length(unique(Object$r_1_0)) <= 1){
f <- cbind(NA, 1, 0)}
if (length(unique(Object$r_min1_1)) > 1){
g <- cbind(median(Object$r_min1_1), -1, 1)}
if (length(unique(Object$r_min1_1)) <= 1){
g <- cbind(NA, -1, 1)}
if (length(unique(Object$r_0_1)) > 1){
h <- cbind(median(Object$r_0_1), 0, 1)}
if (length(unique(Object$r_0_1)) <= 1){
h <- cbind(NA, 0, 1)}
if (length(unique(Object$r_1_1)) > 1){
i <- cbind(median(Object$r_1_1), 1, 1)}
if (length(unique(Object$r_1_1)) <= 1){
i <- cbind(NA, 1, 1)}
data <- data.frame(rbind(a, b, c, d, e, f, g, h, i))
names(data) <- c("Y", "Delta_T", "Delta_S")
temp <- lattice::cloud(Y ~ as.factor(Delta_S) + as.factor(Delta_T), data, panel.3d.cloud=latticeExtra::panel.3dbars,
xbase=0.4, ybase=0.4, scales=list(arrows=FALSE, col=1),
par.settings = list(axis.line = list(col = "transparent")),
xlab=expression(paste(Delta, "S")), ylab=expression(paste(Delta, T)),
zlab="Median", col.facet=rep(c(2:4), each=3))
plot(temp)
}
if (Type=="3D.Mode"){
mode <- function(data) {
x <- data
if (unique(x[1])!=0){
z <- density(x)
mode_val <- z$x[which.max(z$y)]
if (mode_val < 0){mode_val <- c(0)}
}
if (unique(x[1])==0){
model_val <- c(0)
}
fit <- list(mode_val= mode_val)
}
if (length(unique(Object$r_min1_min1)) > 1){
a <- cbind(mode(Object$r_min1_min1)$mode_val, -1, -1)}
if (length(unique(Object$r_min1_min1)) <= 1){
a <- cbind(NA, -1, -1)}
if (length(unique(Object$r_0_min1)) > 1){
b <- cbind(mode(Object$r_0_min1)$mode_val, 0, -1)}
if (length(unique(Object$r_0_min1)) <= 1){
b <- cbind(NA, 0, -1)}
if (length(unique(Object$r_1_min1)) > 1){
c <- cbind(mode(Object$r_1_min1)$mode_val, 1, -1)}
if (length(unique(Object$r_1_min1)) <= 1){
c <- cbind(NA, 1, -1)}
if (length(unique(Object$r_min1_0)) > 1){
d <- cbind(mode(Object$r_min1_0)$mode_val, -1, 0)}
if (length(unique(Object$r_min1_0)) <= 1){
d <- cbind(NA, -1, 0)}
if (length(unique(Object$r_0_0)) > 1){
e <- cbind(mode(Object$r_0_0)$mode_val, 0, 0)}
if (length(unique(Object$r_0_0)) <= 1){
e <- cbind(NA, 0, 0)}
if (length(unique(Object$r_1_0)) > 1){
f <- cbind(mode(Object$r_1_0)$mode_val, 1, 0)}
if (length(unique(Object$r_1_0)) <= 1){
f <- cbind(NA, 1, 0)}
if (length(unique(Object$r_min1_1)) > 1){
g <- cbind(mode(Object$r_min1_1)$mode_val, -1, 1)}
if (length(unique(Object$r_min1_1)) <= 1){
g <- cbind(NA, -1, 1)}
if (length(unique(Object$r_0_1)) > 1){
h <- cbind(mode(Object$r_0_1)$mode_val, 0, 1)}
if (length(unique(Object$r_0_1)) <= 1){
h <- cbind(NA, 0, 1)}
if (length(unique(Object$r_1_1)) > 1){
i <- cbind(mode(Object$r_1_1)$mode_val, 1, 1)}
if (length(unique(Object$r_1_1)) <= 1){
i <- cbind(NA, 1, 1)}
data <- data.frame(rbind(a, b, c, d, e, f, g, h, i))
names(data) <- c("Y", "Delta_T", "Delta_S")
temp <- lattice::cloud(Y ~ as.factor(Delta_S) + as.factor(Delta_T), data, panel.3d.cloud=latticeExtra::panel.3dbars,
xbase=0.4, ybase=0.4, scales=list(arrows=FALSE, col=1),
par.settings = list(axis.line = list(col = "transparent")),
xlab=expression(paste(Delta, "S")), ylab=expression(paste(Delta, T)),
zlab="Mode", col.facet=rep(c(2:4), each=3))
plot(temp)
}
}
|
cor.matrix<-function(variables,with.variables,data=NULL,test=cor.test,...){
arguments <- as.list(match.call()[-1])
variables<-eval(substitute(variables),data,parent.frame())
if(length(dim(variables))<1.5){
variables<-d(variables)
fn <- arguments$variables
names(variables)<-if(is.call(fn)) format(fn) else as.character(fn)
}
if(missing(with.variables))
with.variables <-variables
else{
with.variables<-eval(substitute(with.variables),data,parent.frame())
if(length(dim(with.variables))<1.5){
with.variables<-d(with.variables)
fn <- arguments$with.variables
names(with.variables)<-if(is.call(fn)) format(fn) else as.character(fn)
}
}
cors<-list()
for(var1 in colnames(variables)){
cors[[var1]]<-list()
for(var2 in colnames(with.variables)){
tmp<-na.omit(data.frame(as.numeric(variables[[var1]]),as.numeric(with.variables[[var2]])))
names(tmp)<-c(var1,var2)
cors[[var1]][[var2]]<-test(tmp[[1]],tmp[[2]],...)
attr(cors[[var1]][[var2]],"N")<-nrow(tmp)
}
}
class(cors)<-"cor.matrix"
cors
}
print.cor.matrix<-function(x,digits=4,N=TRUE,CI=TRUE,stat=TRUE,p.value=TRUE,...){
if(is.null(x[[1]][[1]]$conf.int))
CI=FALSE
n1<-length(x)
n2<-length(x[[1]])
label.width<-7
num.rows<-6
result<-as.table(matrix(NA,nrow=n2*num.rows,ncol=n1))
r.names<-names(x[[1]])
r.name.width<-max(nchar(r.names))
if(r.name.width>20){
r.names<-formatC(r.names,width=20)
r.name.width<-20
}else
r.names<-formatC(r.names,width=r.name.width)
c.names<-names(x)
if(max(nchar(c.names))>20)
c.names<-format(names(x),width=15)
colnames(result)<-c.names
for(i in 1:n2)
rownames(result)[i*num.rows-(num.rows-1)]<-paste(formatC(r.names[i],width=r.name.width),
formatC("cor",width=label.width),sep="")
rownames(result)[rep(1:num.rows,n2)>1.5]<-formatC(rep(c("N","CI*","stat**","p-value",
paste(rep("-",r.name.width+label.width),collapse="")),n2),
width=r.name.width+label.width)
for(j in 1:n1){
for(i in (1:n2)){
result[i*num.rows-(num.rows-1),j]<-format(x[[j]][[i]]$estimate,digits=digits,...)
if(!is.null(attr(x[[j]][[i]],"N")))
result[i*num.rows-(num.rows-2),j]<-format(attr(x[[j]][[i]],"N"),...)
if(names(x[[1]])[i]==names(x)[j])
next
if(!is.null(x[[j]][[i]]$conf.int))
result[i*num.rows-(num.rows-3),j]<-paste("(",format(x[[j]][[i]]$conf.int[1],digits=digits,...),",",
format(x[[j]][[i]]$conf.int[2],digits=digits,...),")",sep="")
if(!is.null(x[[j]][[i]]$statistic)){
if(!is.null(x[[j]][[i]]$parameter)){
if(length(x[[j]][[i]]$parameter)==1)
result[i*num.rows-(num.rows-4),j]<-paste(format(x[[j]][[i]]$statistic,digits=digits,...),
" (",format(x[[j]][[i]]$parameter,digits=digits,...),")",
sep="")
else
result[i*num.rows-(num.rows-4),j]<-paste(format(x[[j]][[i]]$statistic,digits=digits,...),
" (",format(x[[j]][[i]]$parameter[1],digits=digits,...),",",
format(x[[j]][[i]]$parameter[2],digits=digits,...),")",
sep="")
}else
result[i*num.rows-(num.rows-4),j]<-format(x[[j]][[i]]$statistic,digits=digits,...)
}
if(!is.null(x[[j]][[i]]$p.value))
result[i*num.rows-(num.rows-5),j]<-format(round(x[[j]][[i]]$p.value,digits),
digits=digits,nsmall=digits,...)
}
}
display<-if(CI) rep(TRUE,num.rows*n2) else rep(1:num.rows,n2)!=3
display<-display & (if(N) rep(TRUE,num.rows*n2) else rep(1:num.rows,n2)!=2)
display<-display & (if(stat) rep(TRUE,num.rows*n2) else rep(1:num.rows,n2)!=4)
display<-display & (if(p.value) rep(TRUE,num.rows*n2) else rep(1:num.rows,n2)!=5)
cat("\n",format(x[[1]][[1]]$method, width = getOption("width"), justify = "centre"), "\n\n")
print(as.table(result[display,,drop=FALSE]))
if(stat & !is.null(x[[1]][[1]]$statistic)){
cat("\t**",names(x[[1]][[1]]$statistic)[1])
if(!is.null(x[[1]][[1]]$parameter))
if(length(x[[1]][[1]]$parameter)==1)
cat(" (",names(x[[1]][[1]]$parameter[1]),")\n",sep="")
else
cat(" (",names(x[[1]][[1]]$parameter[1]),",",names(x[[1]][[1]]$parameter[2]),")\n",sep="")
else
cat("\n")
}
if(CI & !is.null(x[[1]][[1]]$conf.int))
if(!is.null(attr(x[[1]][[1]]$conf.int,"conf.level")))
cat("\t * ",attr(x[[1]][[1]]$conf.int,"conf.level")*100,"% percent interval\n\n",sep="")
else
cat("\n")
if(!is.null(x[[1]][[1]]$alternative))
cat("\tHA:",x[[1]][[1]]$alternative,"\n\n")
else
cat("\n")
}
as.matrix.cor.matrix<-function(x,...){
n1<-length(x);
n2<-length(x[[1]])
mat<-matrix(NA,n2,n1)
for(i in 1:n2)
for(j in 1:n1)
mat[i,j]<-x[[j]][[i]]$estimate
colnames(mat)<-names(x)
rownames(mat)<-names(x[[1]])
mat
} |
context("Consistency of data sets with respect to tumor fractions")
test_that("Tumor fractions are in [0,1]", {
for (dataSet in listDataSets()) {
tfs <- listTumorFractions(dataSet)
expect_false(any(is.na(tfs)))
expect_true(all(tfs>=0))
expect_true(all(tfs<=1))
expect_true(1 %in% tfs)
}
}) |
expected <- eval(parse(text="c(NA, NA, NA, NA, NA)"));
test(id=0, code={
argv <- eval(parse(text="list(NA, 5L)"));
.Internal(`rep.int`(argv[[1]], argv[[2]]));
}, o=expected); |
library(testthat)
library(recipes)
library(dplyr)
library(modeldata)
data(biomass, package = "modeldata")
biom_tr <- biomass %>% dplyr::filter(dataset == "Training") %>% dplyr::select(-dataset, -sample)
biom_te <- biomass %>% dplyr::filter(dataset == "Testing") %>% dplyr::select(-dataset, -sample, -HHV)
data(cells, package = "modeldata")
cell_tr <- cells %>% dplyr::filter(case == "Train") %>% dplyr::select(-case)
cell_te <- cells %>% dplyr::filter(case == "Test") %>% dplyr::select(-case, -class)
load(test_path("test_pls_new.RData"))
test_that('PLS, dense loadings', {
skip_if_not_installed("mixOmics")
rec <- recipe(HHV ~ ., data = biom_tr) %>%
step_pls(all_predictors(), outcome = "HHV", num_comp = 3)
rec <- prep(rec)
expect_equal(
names(rec$steps[[1]]$res),
c("mu", "sd", "coefs", "col_norms")
)
tr_new <- juice(rec, all_predictors())
expect_equal(tr_new, bm_pls_tr)
te_new <- bake(rec, biom_te)
expect_equal(te_new, bm_pls_te)
})
test_that('PLS, sparse loadings', {
skip_if_not_installed("mixOmics")
rec <- recipe(HHV ~ ., data = biom_tr) %>%
step_pls(all_predictors(), outcome = "HHV", num_comp = 3, predictor_prop = 3/5)
rec <- prep(rec)
expect_equal(
names(rec$steps[[1]]$res),
c("mu", "sd", "coefs", "col_norms")
)
tr_new <- juice(rec, all_predictors())
expect_equal(tr_new, bm_spls_tr)
te_new <- bake(rec, biom_te)
expect_equal(te_new, bm_spls_te)
})
test_that('PLS-DA, dense loadings', {
skip_if_not_installed("mixOmics")
rec <- recipe(class ~ ., data = cell_tr) %>%
step_pls(all_predictors(), outcome = "class", num_comp = 3)
rec <- prep(rec)
expect_equal(
names(rec$steps[[1]]$res),
c("mu", "sd", "coefs", "col_norms")
)
tr_new <- juice(rec, all_predictors())
expect_equal(tr_new, cell_plsda_tr)
te_new <- bake(rec, cell_te)
expect_equal(te_new, cell_plsda_te)
})
test_that('PLS-DA, sparse loadings', {
skip_if_not_installed("mixOmics")
rec <- recipe(class ~ ., data = cell_tr) %>%
step_pls(all_predictors(), outcome = "class", num_comp = 3, predictor_prop = 50/56)
rec <- prep(rec)
expect_equal(
names(rec$steps[[1]]$res),
c("mu", "sd", "coefs", "col_norms")
)
tr_new <- juice(rec, all_predictors())
expect_equal(tr_new, cell_splsda_tr)
te_new <- bake(rec, cell_te)
expect_equal(te_new, cell_splsda_te)
})
test_that('No PLS', {
skip_if_not_installed("mixOmics")
rec <- recipe(class ~ ., data = cell_tr) %>%
step_pls(all_predictors(), outcome = "class", num_comp = 0)
rec <- prep(rec)
expect_equal(
names(rec$steps[[1]]$res),
c("x_vars", "y_vars")
)
pred_names <- summary(rec)$variable[summary(rec)$role == "predictor"]
tr_new <- juice(rec, all_predictors())
expect_equal(names(tr_new), pred_names)
te_new <- bake(rec, cell_te, all_predictors())
expect_equal(names(te_new), pred_names)
})
test_that('tidy method', {
skip_if_not_installed("mixOmics")
rec <- recipe(HHV ~ ., data = biom_tr) %>%
step_pls(all_predictors(), outcome = "HHV", num_comp = 3, id = "dork")
tidy_pre <- tidy(rec, number = 1)
exp_pre <- tibble::tribble(
~terms, ~value, ~component, ~id,
"all_predictors()", NA_real_, NA_character_, "dork"
)
expect_equal(tidy_pre, exp_pre)
rec <- prep(rec)
tidy_post <- tidy(rec, number = 1)
exp_post <-
tibble::tribble(
~terms, ~value, ~component, ~id,
"carbon", 0.82813459059393, "PLS1", "dork",
"carbon", 0.718469477422311, "PLS2", "dork",
"carbon", 0.476111929729498, "PLS3", "dork",
"hydrogen", -0.206963356355556, "PLS1", "dork",
"hydrogen", 0.642998926998282, "PLS2", "dork",
"hydrogen", 0.262836631090453, "PLS3", "dork",
"oxygen", -0.49241242430895, "PLS1", "dork",
"oxygen", 0.299176769170812, "PLS2", "dork",
"oxygen", 0.418081563632953, "PLS3", "dork",
"nitrogen", -0.122633995804743, "PLS1", "dork",
"nitrogen", -0.172719084680244, "PLS2", "dork",
"nitrogen", 0.642403301090588, "PLS3", "dork",
"sulfur", 0.11768677260853, "PLS1", "dork",
"sulfur", -0.217341766567037, "PLS2", "dork",
"sulfur", 0.521114256955661, "PLS3", "dork"
)
expect_equal(tidy_post, exp_post, tolerance = 0.01)
})
test_that('print method', {
skip_if_not_installed("mixOmics")
rec <- recipe(HHV ~ ., data = biom_tr) %>%
step_pls(all_predictors(), outcome = "HHV", num_comp = 3, id = "dork")
expect_output(print(rec), "feature extraction with all_predictors")
rec <- prep(rec)
expect_output(
print(rec),
"feature extraction with carbon, hydrogen, oxygen, nitrogen, sulfur"
)
})
test_that('keep_original_cols works', {
skip_if_not_installed("mixOmics")
pls_rec <- recipe(HHV ~ ., data = biom_tr) %>%
step_pls(all_predictors(), outcome = "HHV", num_comp = 3, keep_original_cols = TRUE)
pls_trained <- prep(pls_rec)
pls_pred <- bake(pls_trained, new_data = biom_te, all_predictors())
expect_equal(
colnames(pls_pred),
c("carbon", "hydrogen", "oxygen", "nitrogen", "sulfur",
"PLS1", "PLS2", "PLS3")
)
})
test_that('can prep recipes with no keep_original_cols', {
skip_if_not_installed("mixOmics")
pls_rec <- recipe(HHV ~ ., data = biom_tr) %>%
step_pls(all_predictors(), outcome = "HHV", num_comp = 3)
pls_rec$steps[[1]]$keep_original_cols <- NULL
expect_warning(
pls_trained <- prep(pls_rec, training = biom_tr, verbose = FALSE),
"'keep_original_cols' was added to"
)
expect_error(
pls_pred <- bake(pls_trained, new_data = biom_te, all_predictors()),
NA
)
}) |
permMultinom = function(target, dataset, xIndex, csIndex, wei = NULL, univariateModels = NULL, hash = FALSE, stat_hash = NULL,
pvalue_hash = NULL, threshold = 0.05, R = 999) {
csIndex[ which( is.na(csIndex) ) ] = 0
thres <- threshold * R + 1
if (hash) {
csIndex2 = csIndex[which(csIndex!=0)]
csIndex2 = sort(csIndex2)
xcs = c(xIndex,csIndex2)
key = paste(as.character(xcs) , collapse=" ");
if ( !is.null(stat_hash[key]) ) {
stat = stat_hash[key];
pvalue = pvalue_hash[key];
results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
}
}
pvalue = log(1)
stat = 0;
if ( !is.na( match(xIndex, csIndex) ) ) {
if ( hash) {
stat_hash[key] <- 0;
pvalue_hash[key] <- log(1);
}
results <- list(pvalue = 1, stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
}
if ( any(xIndex < 0) || any(csIndex < 0) ) {
message(paste("error in testIndLogistic : wrong input of xIndex or csIndex"))
results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
}
x = dataset[ , xIndex];
cs = dataset[ , csIndex];
if (length(cs) == 0 || any( is.na(cs) ) ) cs = NULL;
if ( length(cs) != 0 ) {
if ( is.null(dim(cs)[2]) ) {
if ( identical(x, cs) ) {
if (hash) {
stat_hash[key] <- 0;
pvalue_hash[key] <- log(1);
}
results <- list(pvalue = log(1), stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
}
} else {
for ( col in 1:dim(cs)[2] ) {
if ( identical(x, cs[, col]) ) {
if (hash) {
stat_hash[key] <- 0;
pvalue_hash[key] <- log(1);
}
results <- list(pvalue = log(1), stat = 0, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
}
}
}
}
if (length(cs) == 0) {
fit1 <- nnet::multinom(target ~ 1, trace = FALSE, weights = wei)
fit2 <- nnet::multinom(target ~ x, trace = FALSE, weights = wei)
dev2 <- fit2$deviance
stat <- fit1$deviance - dev2
if ( stat > 0 ) {
step <- 0
j <- 1
n <- length(target)
while (j <= R & step < thres ) {
xb <- sample(x, n)
bit2 <- nnet::multinom(target, xb, trace = FALSE, weights = wei)
step <- step + ( bit2$deviance < dev2 )
j <- j + 1
}
pvalue <- log( (step + 1) / (R + 1) )
} else pvalue <- log(1)
} else {
fit1 <- nnet::multinom( target ~ cs, trace = FALSE, weights = wei)
fit2 <- nnet::multinom(target ~ cs + x, trace = FALSE, weights = wei)
dev2 <- deviance(fit2)
stat <- deviance(fit1) - dev2
if (stat > 0) {
step <- 0
j <- 1
n <- length(x)
while (j <= R & step < thres ) {
xb <- sample(x, n)
bit2 <- nnet::multinom(target ~ cs + xb, trace = FALSE, weights = wei)
step <- step + ( bit2$deviance < dev2 )
j <- j + 1
}
pvalue <- log( (step + 1) / (R + 1) )
} else pvalue <- log(1)
}
if (hash) {
stat_hash[key] <- stat;
pvalue_hash[key] <- pvalue;
}
if ( is.na(pvalue) || is.na(stat) ) {
pvalue = log(1)
stat = 0;
} else {
if (hash) {
stat_hash[key] <- stat;
pvalue_hash[key] <- pvalue;
}
}
results <- list(pvalue = pvalue, stat = stat, stat_hash=stat_hash, pvalue_hash=pvalue_hash);
return(results);
} |
test_update <- function(x){
ccc <- parse(text = x)
cc <- ccc[[length(ccc)]]
set.seed(100)
if (length(ccc) > 1){
for (i in 1:(length(ccc)-1)){
eval(ccc[[i]], envir = globalenv())
}
}
a <- eval(cc)
all.equal(final(a), final(update(a)))
}
ll <- lapply(r[5:10], function(e) try(test_update(e), silent = TRUE))
failing <- which(sapply(ll, class) == "try-error")
if (length(failing[!failing %in% c(47L, 52L, 53L, 60L, 98L)]) > 0){
stop("failing cases: ", paste(failing, collapse = ", "))
} |
"plot.fitted.bsad" <- function(x, ggplot2 = TRUE, legend.position = "top", nbins = 30, ...) {
prob <- (1 - x$alpha) * 100
HPD <- x$HPD
par(...)
if (x$parametric == "none") {
if (ggplot2) {
if (HPD) {
datl <- data.frame(x = rep(x$xgrid, 3), dens = c(x$fsemi$upper, x$fsemi$mean, x$fsemi$lower),
Estimates = c(rep(paste(prob, "% HPD UCI (Semi)", sep = ""), x$nint),
rep("Posterior Mean (Semi)", x$nint),
rep(paste(prob, "% HPD LCI (Semi)", sep = ""), x$nint)))
} else {
datl <- data.frame(x = rep(x$xgrid, 3), dens = c(x$fsemi$upper, x$fsemi$mean, x$fsemi$lower),
Estimates = c(rep(paste(prob, "% Equal-tail UCI (Semi)", sep = ""), x$nint),
rep("Posterior Mean (Semi)", x$nint),
rep(paste(prob, "% Equal-tail LCI (Semi)", sep = ""), x$nint)))
}
datx = data.frame(x$x)
plt1 <- ggplot(datl)
plt1 <- plt1 + geom_histogram( data = datx, aes_string(x='x.x', y='..density..'), alpha=0.7,
bins = nbins, col="black", fill= I("grey"), inherit.aes=FALSE)
plt1 <- plt1 + aes_string(x = 'x', y = 'dens')
plt1 <- plt1 + aes_string(group = 'Estimates')
plt1 <- plt1 + aes_string(shape = 'Estimates', linetype = 'Estimates', colour = 'Estimates')
plt1 <- plt1 + geom_line(size = 0.8)
plt1 <- plt1 + xlab("")
plt1 <- plt1 + ylab("Density")
plt1 <- plt1 + theme_bw()
plt1 <- plt1 + theme(legend.position = legend.position)
plt1 <- plt1 + scale_linetype_manual(values = c("dotted", "dotted", "solid"))
plt1
} else {
ymax <- max(c(x$fsemi$upper, hist(x$x, plot = F)$density))
hist(x$x, prob = T, xlab = "", main = "", ylim = c(0, ymax), xlim = c(x$xmin, x$xmax), col = "gray95", nclass=nbins, ...)
lines(x$xgrid, x$fsemi$mean, lwd = 2, lty = 1, col = "dodgerblue")
lines(x$xgrid, x$fsemi$lower, lwd = 2, lty = 3, col = "tomato")
lines(x$xgrid, x$fsemi$upper, lwd = 2, lty = 3, col = "seagreen3")
rug(x$x, lwd = 2)
}
} else {
if (ggplot2) {
if (HPD) {
datl <- data.frame(x = rep(x$xgrid, 4),
dens = c(x$fpar$mean, x$fsemi$upper, x$fsemi$mean, x$fsemi$lower),
Estimates = c(rep("Parametric", x$nint),
rep(paste(prob, "% HPD UCI (Semi)", sep = ""), x$nint),
rep("Posterior Mean (Semi)", x$nint),
rep(paste(prob, "% HPD LCI (Semi)", sep = ""), x$nint)))
} else {
datl <- data.frame(x = rep(x$xgrid, 4),
dens = c(x$fpar$mean, x$fsemi$upper, x$fsemi$mean, x$fsemi$lower),
Estimates = c(rep("Parametric", x$nint),
rep(paste(prob, "% Equal-tail UCI (Semi)", sep = ""), x$nint),
rep("Posterior Mean (Semi)", x$nint),
rep(paste(prob, "% Equal-tail LCI (Semi)", sep = ""), x$nint)))
}
datx = data.frame(x$x)
plt1 <- ggplot(datl)
plt1 <- plt1 + geom_histogram( data = datx, aes_string(x='x.x', y='..density..'), alpha=0.7,
bins = nbins, col="black", fill= I("grey"), inherit.aes=FALSE)
plt1 <- plt1 + aes_string(x = 'x', y = 'dens')
plt1 <- plt1 + aes_string(group = 'Estimates')
plt1 <- plt1 + aes_string(shape = 'Estimates', linetype = 'Estimates', colour = 'Estimates')
plt1 <- plt1 + geom_line(size = 0.8)
plt1 <- plt1 + xlab("")
plt1 <- plt1 + ylab("Density")
plt1 <- plt1 + theme_bw()
plt1 <- plt1 + theme(legend.position = legend.position)
plt1 <- plt1 + scale_linetype_manual(values = c("dotted", "dotted", "dashed", "solid"))
plt1
} else {
ymax <- max(c(x$fsemi$upper, hist(x$x, plot = F)$density))
hist(x$x, prob = T, xlab = "", main = "", col = "gray95", ylim = c(0, ymax), xlim = c(x$xmin, x$xmax), nclass = nbins, ...)
lines(x$xgrid, x$fsemi$mean, lwd = 2, lty = 1, col = "magenta")
lines(x$xgrid, x$fsemi$upper, lwd = 2, lty = 3, col = "seagreen3")
lines(x$xgrid, x$fsemi$lower, lwd = 2, lty = 3, col = "tomato")
lines(x$xgrid, x$fpar$mean, lwd = 2, lty = 4, col = "dodgerblue")
rug(x$x, lwd = 2)
}
}
} |
expected <- eval(parse(text="structure(list(id = character(0), class = structure(\"withId\", package = \".GlobalEnv\")), .Names = c(\"id\", \"class\"))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(1+1i, 2+1.4142135623731i, 3+1.73205080756888i, 4+2i, 5+2.23606797749979i, 6+2.44948974278318i, 7+2.64575131106459i, 8+2.82842712474619i, 9+3i, 10+3.1622776601684i), id = character(0), class = structure(\"withId\", package = \".GlobalEnv\")))"));
do.call(`attributes`, argv);
}, o=expected); |
setMethod("*", c("AffLinUnivarLebDecDistribution","numeric"),
function(e1, e2) {
if (length(e2)>1) stop("length of operator must be 1")
if (isTRUE(all.equal(e2,1))) return(e1)
if (isTRUE(all.equal(e2,0)))
return(new("Dirac", location = 0))
if(.isEqual(e1@a*e2,1)&&.isEqual(e1@b,0)){
obj <- e1@X0
if(getdistrOption("simplifyD"))
obj <- simplifyD(obj)
return(obj)
}
Distr <- UnivarLebDecDistribution(
discretePart = discretePart(e1)*e2,
acPart = acPart(e1)*e2,
discreteWeight = discreteWeight(e1),
acWeight = acWeight(e1))
if(.isEqual(e1@a*e2,1)&&.isEqual(e1@b,0)){
obj <- e1@X0
if(getdistrOption("simplifyD"))
obj <- simplifyD(obj)
return(obj)
}
Symmetry <- NoSymmetry()
if(is(e1@Symmetry,"SphericalSymmetry"))
Symmetry <- SphericalSymmetry(SymmCenter(e1@Symmetry) + e2)
object <- new("AffLinUnivarLebDecDistribution",
r = Distr@r, d = Distr@d, p = Distr@p,
q = Distr@q, X0 = e1@X0, mixDistr = Distr@mixDistr,
mixCoeff = Distr@mixCoeff,
a = e1@a*e2, b = e1@b, .withSim = [email protected],
.withArith = TRUE,
.logExact = .logExact(e1), .lowerExact = .lowerExact(e1),
gaps = gaps(Distr), support = support(Distr),
Symmetry = Symmetry
)
object})
setMethod("+", c("AffLinUnivarLebDecDistribution","numeric"),
function(e1, e2) {
if (length(e2)>1) stop("length of operator must be 1")
if (isTRUE(all.equal(e2,0))) return(e1)
if(.isEqual(e1@a,1)&&.isEqual(e1@b+e2,0)){
obj <- e1@X0
if(getdistrOption("simplifyD"))
obj <- simplifyD(obj)
return(obj)
}
Distr <- UnivarLebDecDistribution(
discretePart = discretePart(e1)+e2,
acPart = acPart(e1)+e2,
discreteWeight = discreteWeight(e1),
acWeight = acWeight(e1))
if(.isEqual(e1@a,1)&&.isEqual(e1@b+e2,0)){
obj <- e1@X0
if(getdistrOption("simplifyD"))
obj <- simplifyD(obj)
return(obj)
}
Symmetry <- NoSymmetry()
if(is(e1@Symmetry,"SphericalSymmetry"))
Symmetry <- SphericalSymmetry(SymmCenter(e1@Symmetry) * e2)
object <- new("AffLinUnivarLebDecDistribution",
r = Distr@r, d = Distr@d, p = Distr@p,
q = Distr@q, X0 = e1@X0, mixDistr = Distr@mixDistr,
mixCoeff = Distr@mixCoeff,
a = e1@a, b = e1@b+e2, .withSim = [email protected],
.withArith = TRUE,
.logExact = .logExact(e1), .lowerExact = .lowerExact(e1),
gaps = gaps(Distr), support = support(Distr),
Symmetry = Symmetry
)
object}) |
funcClassPred <- c(
"ada",
"bagFDA",
"brnn",
"C5.0",
"C5.0Cost",
"C5.0Rules",
"C5.0Tree",
"CSimca",
"fda",
"FH.GBML",
"FRBCS.CHI",
"FRBCS.W",
"GFS.GCCL",
"gpls",
"hda",
"hdda",
"J48",
"JRip",
"lda",
"lda2",
"Linda",
"LMT",
"LogitBoost",
"lssvmLinear",
"lssvmPoly",
"lssvmRadial",
"lvq",
"mda",
"Mlda",
"multinom",
"nb",
"oblique.tree",
"OneR",
"ORFlog",
"ORFpls",
"ORFridge",
"ORFsvm",
"pam",
"PART",
"pda",
"pda2",
"PenalizedLDA",
"plr",
"protoclass",
"qda",
"QdaCov",
"rbf",
"rda",
"rFerns",
"RFlda",
"rocc",
"rpartCost",
"rrlda",
"RSimca",
"sda",
"sddaLDA",
"sddaQDA",
"SLAVE",
"slda",
"smda",
"sparseLDA",
"stepLDA",
"stepQDA",
"svmRadialWeights",
"vbmpRadial",
"avNNet",
"bag",
"bagEarth",
"bayesglm",
"bdk",
"blackboost",
"Boruta",
"bstLs",
"bstSm",
"bstTree",
"cforest",
"ctree",
"ctree2",
"dnn",
"earth",
"elm",
"evtree",
"extraTrees",
"gam",
"gamboost",
"gamLoess",
"gamSpline",
"gaussprLinear",
"gaussprPoly",
"gaussprRadial",
"gbm",
"gcvEarth",
"glm",
"glmboost",
"glmnet",
"glmStepAIC",
"kernelpls",
"kknn",
"knn",
"logicBag",
"logreg",
"mlp",
"mlpWeightDecay",
"nnet",
"nodeHarvest",
"parRF",
"partDSA",
"pcaNNet",
"pls",
"plsRglm",
"rbfDDA",
"rf",
"rknn",
"rknnBel",
"rpart",
"rpart2",
"RRF",
"RRFglobal",
"simpls",
"spls",
"svmBoundrangeString",
"svmExpoString",
"svmLinear",
"svmPoly",
"svmRadial",
"svmRadialCost",
"svmSpectrumString",
"treebag",
"widekernelpls",
"xyf"
) |
core_mobile_ui <- f7Page(
title = "Tab Layout",
f7TabLayout(
navbar = f7Navbar(
title="LFApp mobile analysis"
),
f7Tabs(
animated = TRUE,
id = "tabs",
f7Tab(
tabName = "Crop & Segmentation",
icon = f7Icon("tray_arrow_up"),
active = TRUE,
f7Block(
hairlines = FALSE,
strong = TRUE,
inset = FALSE,
f7Radio(inputId= "upload", label="Upload image or choose sample", choices=list("Upload image", "Sample"), selected = "Sample"),
conditionalPanel(
condition = "input.upload == 'Upload image'",
f7File(inputId = 'file1',
label = 'Upload Image',
placeholder = 'JPEG, PNG, and TIFF are supported',
accept = c(
"image/jpeg",
"image/x-png",
"image/tiff",
".jpg",
".png",
".tiff"))
)
),
f7Accordion(
f7AccordionItem(
title = "Rotate Image",
tagList(
f7Slider("rotate", label="Angle",
min=-45, max=45, value=0, scale=TRUE),
br(),
f7Segment(
f7Button(inputId="rotateCCW", label = "-90"),
f7Button(inputId="rotateCW", label = "+90"),
f7Button(inputId="fliphor", label = "FH"),
f7Button(inputId="flipver", label = "FV")
)
)
)
),
f7Block(
f7BlockTitle("Set number of strips and number of lines per strip"),
hairlines = TRUE,
strong = TRUE,
inset = FALSE,
f7Slider("strips", label="Number of strips", min=1, max=10, value=1, scale=TRUE, scaleSteps=9),
f7Slider("bands", label="Number of lines", min=2, max=6, value=2, scale=TRUE, scaleSteps=4)
),
f7Block(
f7BlockTitle("Cropping and Segmentation", size="medium"),
hairlines = TRUE,
strong = TRUE,
inset = FALSE,
plotOutput("plot1",
click = "plot_click",
dblclick = "plot_dblclick",
hover = hoverOpts("plot_hover", delay = 5000, clip = TRUE),
brush = "plot_brush"),
h5("Click and drag to select a region of interest. Double click on the selected region to zoom.", align = "center"),
uiOutput("cropButtons")
)
),
f7Tab(
tabName = "Background",
icon = f7Icon("circle_lefthalf_fill"),
active = FALSE,
f7Block(
hairlines = FALSE,
strong = TRUE,
inset = FALSE,
"Select strip: ",
f7Stepper("selectStrip", label = "", min=1, max=1, value=1, size="small"),
f7Accordion(
f7AccordionItem(
title = "Color image?",
f7Radio("channel", label="Conversion mode", choices=list("luminance", "gray", "red", "green", "blue"), selected = "luminance"),
),
),
f7Radio("invert", label="Lines darker than background?", choices=list("No", "Yes"), selected = "No"),
f7Radio("thresh", label="Threshold", choices=list("Otsu", "Quantile", "Triangle", "Li"), selected = "Otsu"),
conditionalPanel(
condition = "input.thresh == 'Quantile'",
f7Stepper(inputId = "quantile1",
label = "Probability [%]:",
value = 99,
min = 0,
max = 100,
step = 0.5,
manual = TRUE)
),
conditionalPanel(
condition = "input.thresh == 'Triangle'",
f7Stepper(inputId = "tri_offset",
label = "Offset:",
value = 0.2,
min = 0,
max = 1,
step = 0.1,
manual = TRUE)
),
f7Segment(
f7Button(inputId="threshold", label = "Apply Threshold")
)
),
uiOutput("threshPlots"),
),
f7Tab(
tabName = "Intensity Data",
icon = f7Icon("table"),
active = FALSE,
f7Block(
f7Accordion(
multiCollapse = TRUE,
f7AccordionItem(
title = "Upload existing intensity data",
f7File(inputId = 'intensFile',
label = 'Select CSV file',
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv"))
)
),
f7Block(
strong = TRUE,
f7Block(
style = "overflow-x:scroll",
DTOutput("intens")
),
f7Segment(
f7DownloadButton("downloadData", label = "Download Data"),
f7Button("deleteData", color="red", label="Delete Data")
)
)
)
)
)
)
) |
BMTfit.mle <- function(data,
start = list(p3 = 0.5, p4 = 0.5, p1 = min(data) - 0.1, p2 = max(data) + 0.1),
fix.arg = NULL, type.p.3.4 = "t w", type.p.1.2 = "c-d",
optim.method = "Nelder-Mead", custom.optim = NULL, silent = TRUE, ...){
if (!(is.vector(data) & is.numeric(data) & length(data) > 1))
stop("data must be a numeric vector of length greater than 1")
my3dots <- list(...)
if (length(my3dots) == 0)
my3dots <- NULL
if(!is.null(my3dots$weights))
stop("Estimation with weights is not considered yet")
TYPE.P.3.4 <- c("t w", "a-s")
int.type.p.3.4 <- pmatch(type.p.3.4, TYPE.P.3.4)
if (is.na(int.type.p.3.4))
stop("invalid type of parametrization for parameters 3 and 4")
if (int.type.p.3.4 == -1)
stop("ambiguous type of parametrization for parameters 3 and 4")
if(type.p.1.2 != "c-d")
stop("maximum likelihood estimation only allows parametrization \"c-d\"")
fix.arg$type.p.3.4 <- type.p.3.4
fix.arg$type.p.1.2 <- "c-d"
stnames <- names(start)
m <- length(stnames)
lower <- rep(0 + .epsilon, m)
upper <- rep(1 - .epsilon, m)
lower[stnames == "p1"] <- -Inf
upper[stnames == "p1"] <- min(data) - .epsilon
lower[stnames == "p2"] <- max(data) + .epsilon
upper[stnames == "p2"] <- Inf
if(int.type.p.3.4 == 2) {
lower[stnames == "p3"] <- -1 + .epsilon
}
if(!is.null(custom.optim))
if(custom.optim=="nlminb")
custom.optim <- .m.nlminb
mle <- fitdistrplus::mledist(data, "BMT", start = start, fix.arg = fix.arg,
optim.method = optim.method, lower = lower, upper = upper,
custom.optim = custom.optim, silent = silent, ...)
return(mle)
} |
infer_initial_trajectory <- function(space, k) {
check_numeric_matrix(space, "space", finite = TRUE)
check_numeric_vector(k, "k", whole = TRUE, finite = TRUE, range = c(1, nrow(space) - 1), length = 1)
fit <- stats::kmeans(space, k)
centers <- fit$centers
eucl_dist <- as.matrix(stats::dist(centers))
i <- j <- NULL
pts <-
crossing(
i = seq_len(k),
j = seq_len(k),
pct = seq(0, 1, length.out = 21)
) %>%
filter(i < j)
pts_space <- (1 - pts$pct) * centers[pts$i, ] + pts$pct * centers[pts$j, ]
pts$dist <- rowMeans(RANN::nn2(space, pts_space, k = 10)$nn.dist)
dendis <- pts %>% group_by(i, j) %>% summarise(dist = mean(dist)) %>% ungroup()
density_dist <- matrix(0, nrow = k, ncol = k)
density_dist[cbind(dendis$i, dendis$j)] <- dendis$dist
density_dist[cbind(dendis$j, dendis$i)] <- dendis$dist
cluster_distances <- eucl_dist * density_dist
tsp <- TSP::insert_dummy(TSP::TSP(cluster_distances))
tour <- as.vector(TSP::solve_TSP(tsp))
tour2 <- c(tour, tour)
start <- min(which(tour2 == k + 1))
stop <- max(which(tour2 == k + 1))
best_ord <- tour2[(start + 1):(stop - 1)]
init_traj <- centers[best_ord, , drop = FALSE]
init_traj
}
infer_trajectory <- function(
space,
k = 4,
thresh = .001,
maxit = 10,
stretch = 0,
smoother = "smooth_spline",
approx_points = 100
) {
check_numeric_matrix(space, "space", finite = TRUE)
init_traj <-
if (k <= 1) {
NULL
} else {
infer_initial_trajectory(space, k = k)
}
fit <- princurve::principal_curve(
as.matrix(space),
start = init_traj,
thresh = thresh,
maxit = maxit,
stretch = stretch,
smoother = smoother,
approx_points = approx_points,
trace = FALSE,
plot_iterations = FALSE
)
path <- fit$s[fit$ord, , drop = FALSE]
dimnames(path) <- list(NULL, paste0("Comp", seq_len(ncol(path))))
time <- dynutils::scale_minmax(fit$lambda)
list(
path = path,
time = time
) %>% dynutils::add_class(
"SCORPIUS::trajectory"
)
}
reverse_trajectory <- function(trajectory) {
if (!is(trajectory, "SCORPIUS::trajectory"))
stop(sQuote("trajectory"), " needs to be an object returned by infer_trajectory")
trajectory$time <- 1 - trajectory$time
trajectory$path <- trajectory$path[rev(seq_len(nrow(trajectory$path))), , drop = FALSE]
trajectory
} |
aa.specimen.frequencies <-
function(freq, seq.matrix, spec.names, seqlength){
no.spec <- nrow(seq.matrix)
letter_vector <- c("A", "C", "D", "E", "F", "G", "H", "I", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "Y")
aasequence.freq.matrix <- matrix(NA, nrow = no.spec, ncol = seqlength)
for(i in 1:seqlength){
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[1]),i] <- freq[1,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[2]),i] <- freq[2,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[3]),i] <- freq[3,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[4]),i] <- freq[4,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[5]),i] <- freq[5,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[6]),i] <- freq[6,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[7]),i] <- freq[7,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[8]),i] <- freq[8,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[9]),i] <- freq[9,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[10]),i] <- freq[10,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[11]),i] <- freq[11,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[12]),i] <- freq[12,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[13]),i] <- freq[13,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[14]),i] <- freq[14,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[15]),i] <- freq[15,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[16]),i] <- freq[16,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[17]),i] <- freq[17,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[18]),i] <- freq[18,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[19]),i] <- freq[19,i]
aasequence.freq.matrix[which(seq.matrix[,i+2] == letter_vector[20]),i] <- freq[20,i]
}
rownames(aasequence.freq.matrix) <- spec.names
return(aasequence.freq.matrix)
} |
prPropDescs <- function(x,
by,
name,
default_ref,
prop_fn,
html,
digits,
digits.nonzero,
numbers_first,
useNA,
useNA.digits,
percentage_sign,
missing_value,
names_of_missing,
NEJMstyle) {
default_ref <- prDescGetAndValidateDefaultRef(x, default_ref)
t <- by(x,
by,
FUN = prop_fn,
html = html,
digits = digits,
digits.nonzero = digits.nonzero,
number_first = numbers_first,
useNA = useNA,
useNA.digits = useNA.digits,
default_ref = default_ref,
percentage_sign = percentage_sign
)
missing_t <- sapply(t, is.null)
if (any(missing_t)) {
substitute_t <- rep(missing_value, length(t[!missing_t][[1]]))
names(substitute_t) <- names(t[!missing_t][[1]])
for (i in seq_along(t[missing_t])) {
t[missing_t][[i]] <- substitute_t
}
}
if (all(unlist(sapply(t, is.na))) & !is.null(names_of_missing)) {
substitute_t <- rep(missing_value, length(names_of_missing))
names(substitute_t) <- names_of_missing
substitute_list <- vector("list", length = length(t))
names(substitute_list) <- names(t)
for (i in seq_along(substitute_list)) {
substitute_list[[i]] <- substitute_t
}
t <- substitute_list
}
if (unique(sapply(t, length)) == 1) {
if (is.factor(x)) {
factor_name <- levels(x)[default_ref]
} else {
factor_name <- levels(factor(x))[default_ref]
}
name <- glue("{capitalize(factor_name)} {tolower(name)}")
}
if (NEJMstyle) {
percent_sign <- ifelse(html, "%", "\\%")
if (numbers_first) {
name <- glue("{name} - no ({percent_sign})")
} else {
name <- glue("{name} - {percent_sign} (no)")
}
}
if (length(t[[1]]) == 1) {
names(t[[1]][1]) <- name
}
return(t)
} |
"GMMA" <-
function(x, short=c(3,5,8,10,12,15), long=c(30,35,40,45,50,60), maType) {
x <- try.xts(x, error=as.matrix)
if(missing(maType)) {
maType <- 'EMA'
}
fn <- function(g) { do.call(maType, list(x,n=g)) }
gmma <- do.call(cbind, lapply(c(short,long), fn))
colnames(gmma) <- c(paste('short lag',short),paste('long lag',long))
reclass(gmma, x)
} |
phylomatic_tree2 <- function(taxa, get = 'GET', informat = "newick", method = "phylomatic",
storedtree = "smith2011", outformat = "newick", clean = "true")
{
url <- "http://phylodiversity.net/phylomatic/pmws"
taxa <- sapply(taxa, function(x) gsub("\\s", "_", x), USE.NAMES=FALSE)
if (length(taxa) > 1) { taxa <- paste(taxa, collapse = "\n") } else { taxa <- taxa }
args <- compact(list(taxa = taxa, informat = informat, method = method,
storedtree = storedtree, outformat = outformat, clean = clean))
get <- match.arg(get, choices=c("GET",'POST'))
out <- eval(parse(text=get))(url, query=args)
stop_for_status(out)
tt <- content(out, as="text")
outformat <- match.arg(outformat, choices=c("nexml",'newick'))
getnewick <- function(x){
tree <- gsub("\n", "", x[[1]])
read.tree(text = colldouble(tree))
}
switch(outformat,
nexml = tt,
newick = getnewick(tt))
} |
context("nodes")
x <- connect(port = Sys.getenv("TEST_ES_PORT"))
test_that("nodes_stats", {
out <- nodes_stats(x)
out2 <- nodes_stats(x, node = names(out$nodes))
if (gsub("\\.", "", x$ping()$version$number) >= 500) {
expect_equal(sort(names(out)), c("_nodes", "cluster_name", "nodes"))
} else {
expect_equal(sort(names(out)), c("cluster_name", "nodes"))
}
expect_is(out, "list")
expect_is(out2, "list")
expect_is(nodes_stats(x, metric = 'jvm'), "list")
expect_is(nodes_stats(x, metric = c('os', 'process')), "list")
expect_equal(length(nodes_stats(x, node = "$$%%$$$")$nodes), 0)
})
test_that("nodes_info", {
out <- nodes_info(x)
out2 <- nodes_info(x, node = names(out$nodes))
if (gsub("\\.", "", x$ping()$version$number) >= 500) {
expect_equal(sort(names(out)), c("_nodes", "cluster_name", "nodes"))
} else {
expect_equal(sort(names(out)), c("cluster_name", "nodes"))
}
expect_is(out, "list")
expect_is(out2, "list")
expect_is(nodes_info(x, metric = 'get'), "list")
expect_is(nodes_info(x, metric = 'jvm'), "list")
expect_is(nodes_info(x, metric = c('os', 'process')), "list")
expect_equal(length(nodes_info(x, node = "$$%%$$$")$nodes), 0)
}) |
adaptmh<-function(tab1,tab2,Gamma=1,alpha=0.05,double=FALSE,inc=0.25){
stopifnot((length(Gamma)==1)&(Gamma>=1))
stopifnot((length(alpha)==1)&(alpha>0)&(alpha<1))
stopifnot((length(inc)==1)&(inc>0))
stopifnot((double==TRUE)|(double==FALSE))
d1<-dim(tab1)
d2<-dim(tab2)
stopifnot((d1[1]==2)&(d1[2]==2)&(d2[1]==2)&(d2[2]==2))
if (length(d1)==2) tab1<-array(tab1,c(2,2,1))
if (length(d2)==2) tab2<-array(tab2,c(2,2,1))
stopifnot(sum(as.vector(tab1))>0)
stopifnot(sum(as.vector(tab2))>0)
tab1<-tab1[,,apply(tab1,3,sum)>0]
tab2<-tab2[,,apply(tab2,3,sum)>0]
if (length(dim(tab1))==2) tab1<-array(tab1,c(2,2,1))
if (length(dim(tab2))==2) tab2<-array(tab2,c(2,2,1))
check2x2xktable<-function(tab){
r1<-tab[1,1,]+tab[1,2,]
r2<-tab[2,1,]+tab[2,2,]
c1<-tab[1,1,]+tab[2,1,]
c2<-tab[1,2,]+tab[2,2,]
mc<-pmin(pmin(r1,r2),pmin(c1,c2))
if (max(mc)==0) {
warning("One of the 2x2 or 2x2xk tables is degenerate.")
stop("There is a problem with your data.")
}
}
check2x2xktable(tab1)
check2x2xktable(tab2)
adaptmhInternal<-function(tab1,tab2,gamma=gamma,alpha=alpha,double=double){
one2x2<-function(tb,gamma=gamma){
m1<-tb[1,1]+tb[1,2]
m2<-tb[2,1]+tb[2,2]
n<-tb[1,1]+tb[2,1]
mx<-min(n,m1)
mn<-max(0,n-m2)
x<-mn:mx
g<-rep(0,mx+1)
pr<-dFNCHypergeo(x,m1,m2,n,gamma)
g[(mn+1):(mx+1)]<-pr
g
}
one2x2xk<-function(tbk,gamma=gamma){
k<-dim(tbk)[3]
g<-1
for (i in 1:k){
gi<-one2x2(tbk[,,i],gamma=gamma)
g<-gconv(g,gi)
}
g
}
g1=one2x2xk(tab1,gamma=gamma)
g2=one2x2xk(tab2,gamma=gamma)
if (double){
lg1<-length(g1)
gd<-c(g1[1],as.vector(rbind(rep(0,lg1-1),g1[2:lg1])))
gboth<-gconv(gd,g2)
}
else {gboth<-gconv(g1,g2)}
val1<-(0:(length(g1)-1))
val2<-(0:(length(g2)-1))
valboth<-(0:(length(gboth)-1))
names(gboth)<-valboth
names(g1)<-val1
names(g2)<-val2
actuala<-sum(tab1[1,1,])
if (double) actualb<-(2*actuala)+sum(tab2[1,1,])
else actualb<-actuala+sum(tab2[1,1,])
jt<-outer(g1,g2,"*")
va<-outer(val1,rep(1,length(g2)),"*")
if (double){vb<-outer(2*val1,val2,"+")}
else{vb<-outer(val1,val2,"+")}
c1<-rev(cumsum(rev(g1)))
cboth<-rev(cumsum(rev(gboth)))
onealpha<-function(alpha1){
if (sum(c1<=alpha1)>=1) mina<-min(val1[c1<=alpha1]) else mina<-Inf
if (sum(cboth<=alpha1)>=1) minb<-min(valboth[cboth<=alpha1]) else minb<-Inf
if (sum(c1<=(alpha1/3))>=1) maxa<-min(val1[c1<=(alpha1/3)]) else maxa<-max(val1)
if (sum(cboth<=(alpha1/3))>=1) maxb<-min(valboth[cboth<=(alpha1/3)]) else maxb<-max(valboth)
obj<-function(a,b){
peither<-sum(jt[(va>=a)|(vb>=b)])
pb<-sum(gboth[valboth>=b])
pa<-sum(g1[val1>=a])
adif<-abs(pa-pb)
o<-c(a,b,peither,pa,pb,adif)
names(o)<-c("a","b","peither","pa","pb","adif")
o
}
o1<-NULL
if ((mina==Inf)&(minb==Inf)){
warning("At least one of your tables has such small counts that an alpha-level test at this Gamma is not informative.")
stop("Results are not significant at level alpha, but no results could be with these data and Gamma.")
}
else if ((mina<Inf)&(minb==Inf)) {
maxb<-Inf
for (a in mina:maxa){
o1<-rbind(o1,obj(a,minb))
}
}
else if ((mina==Inf)&(minb<Inf)) {
maxa<-Inf
for (b in minb:maxb){
o1<-rbind(o1,obj(mina,b))
}
}
else {
for (a in mina:maxa){
for (b in minb:maxb){
o1<-rbind(o1,obj(a,b))
}
}
}
o1<-as.data.frame(o1)
o2<-o1[o1$peither<=alpha1,]
o2<-o2[order(o2$a,o2$b),]
ua<-sort(unique(o2$a))
o3<-NULL
bestb<-Inf
for (i in 1:length(ua)){
oi<-o2[o2$a==ua[i],]
wh<-which.min(oi$b)
currentb<-oi$b[wh]
if (currentb<bestb) {
o3<-rbind(o3,oi[wh,])
bestb<-currentb
}
}
o4<-o3[which.min(o3$adif),]
o4
}
o<-NULL
for (i in 1:length(alpha)){
o<-rbind(o,onealpha(alpha[i]))
}
result<-rep("Accept at",length(alpha))
result[(actuala>=o$a)|(actualb>=o$b)]<-"Reject at"
o<-cbind(o,result,alpha)
rownames(o)<-alpha
list(A=actuala,B=actualb,result=o)
}
ninc<-floor((Gamma-1)/inc)
if (ninc==0) gammas<-1
else gammas<-c(1,1+(inc*(1:ninc)))
if (!is.element(Gamma,gammas)) gammas<-c(gammas,Gamma)
g1<-adaptmhInternal(tab1,tab2,gamma=gammas[1],alpha=alpha,double=double)
out<-g1$result
acta<-g1$A
actb<-g1$B
if (length(gammas)>=2) {
for (i in 2:length(gammas)) {
out<-rbind(out,adaptmhInternal(tab1,tab2,gamma=gammas[i],alpha=alpha,double=double)$result)
}
}
if (dim(out)[1]==1) out<-as.matrix(out,1,length(out))
out<-as.data.frame(out)
rownames(out)<-gammas
Gamma<-gammas
out<-cbind(out,Gamma)
if (!all(out$result=="Reject at")) {
first<-which(out$result=="Accept at")[1]
out<-out[1:first,]
}
list(A=acta,B=actb,result=out)
} |
cesInterN4 <- function( funcName, par, xNames, tName, data, rhoApprox ) {
coefArray <- array( par, c( length( par ), 2, 2, 2 ) )
dimnames( coefArray ) <- list( names( par ),
c( "rho_1 = 0", "rho_1 = E" ), c( "rho_2 = 0", "rho_2 = E" ),
c( "rho = 0", "rho = E" ) )
weights <- c( 0, 0, 0 )
names( weights ) <- c( "rho_1 = 0", "rho_2 = 0", "rho = 0" )
rhoNames <- c( "rho_1", "rho_2", "rho" )
permVec <- rep( 2:4, 2 )
for( i in 1:3 ) {
if( abs( par[ rhoNames[ i ] ] ) <= rhoApprox ) {
atemp <- aperm( coefArray, c( 1, permVec[ i:( i + 2 ) ] ) )
atemp[ rhoNames[ i ], 1, , ] <- 0
atemp[ rhoNames[ i ], 2, , ] <-
rhoApprox * (-1)^( par[ rhoNames[ i ] ] < 0 )
coefArray <- aperm( atemp, c( 1, permVec[ ( 5 - i ):( 7 - i ) ] ) )
weights[ i ] <- 1 - abs( par[ rhoNames[ i ] ] ) / rhoApprox
}
}
result <- 0
weightMatrix <- cbind( weights, 1 - weights )
for( i in 1:2 ) {
for( j in 1:2 ) {
for( k in 1:2 ) {
if( weightMatrix[ 1, i ] != 0 && weightMatrix[ 2, j ] != 0 &&
weightMatrix[ 3, k ] != 0 ) {
result <- result + weightMatrix[ 1, i ] * weightMatrix[ 2, j ] *
weightMatrix[ 3, k ] *
do.call( funcName, args = list( coef = coefArray[ , i, j, k ],
data = data, xNames = xNames, tName = tName ) )
}
}
}
}
return( result )
} |
fn3 <- function(ss,a,n,M){
res <- numeric(0)
s1 <- (n-sum(ss*a[-1]))/a[1]
if ((s1==0 | s1 == 1) && sum(c(s1,ss))<= M)
res <- c(s1,ss)
res
}
recursive.fn3 <- function(w,b,a,n,M){
S <- rep(0,0)
d <- 0
if(length(b)) {
for( i in seq(0,b[1]) ) {
if (length(b) >1){
d<-sum(w*a[length(a):(length(a)-length(w)+1)])+i*a[length(b)+1]
b[2] <- min(1,floor((n-d)/a[length(b)]))
}
S <- c(S, Recall( c(w,i), b[-1],a,n,M))
}
} else {
return(fn3(rev(w),a,n,M))
}
S
}
fn4 <- function(ss,a,n,M,bounds){
res <- numeric(0)
s1 <- (n-sum(ss*a[-1]))/a[1]
if (s1>=0 && s1 <= bounds[1] && s1==floor(s1) && sum(c(s1,ss))<= M)
res <- c(s1,ss)
res
}
recursive.fn4 <- function(w,b,a,n,M,bounds){
S <- rep(0,0)
d <- 0
if(length(b)) {
for( i in seq(0,b[1]) ) {
if (length(b) >1){
d<-sum(w*a[length(a):(length(a)-length(w)+1)])+i*a[length(b)+1]
b[2] <- min(bounds[length(b)],floor((n-d)/a[length(b)]))
}
S <- c(S, Recall( c(w,i), b[-1],a,n,M,bounds))
}
} else {
return(fn4(rev(w),a,n,M,bounds))
}
S
}
get.subsetsum <- function(a,n,M=NULL,problem="subsetsum01", bounds=NULL){
if (length(a) < 2) {stop("length of vector 'a' has to be more than 1")}
if (!isTRUE(all(a == floor(a))) || !isTRUE(all(a > 0))) stop("'a' must only contain positive integer values")
if (length(n) >1) {stop("'n' has to be a positive integer")}
if (!isTRUE(n == floor(n)) || !isTRUE(n > 0)) {stop("'n' has to be a positive integer")}
l <- length(a)
if (is.null(M)) M <- floor(n/min(a))
else { if (!isTRUE(M == floor(M)) || !isTRUE(M > 0)) {stop("'M' has to be a positive integer")}
if (M > l) stop("'M' has to be less or equal to the length of 'a'")
}
if (!(problem %in% c("subsetsum01", "bsubsetsum"))) stop("unknown problem is used")
if (problem=="bsubsetsum" & is.null(bounds)) stop("no upper limits for the set of indices, 'bounds', supplied to solve the bounded problem")
if (problem=="bsubsetsum" & length(bounds)!=length(a)) stop("lengths of vectors 'bounds' and 'a' must be the same")
ra <- rank(a, ties.method= "first")
a <- sort(a)
bounds <- bounds[ra]
out <-numeric(0)
if (problem=="subsetsum01"){
b <- c(min(1,floor(n/a[l])),rep(NA,l-2))
out <- recursive.fn3(numeric(0), b,a,n,M)
if (length(out)==0) {out <- NULL }
else {
dim(out) <- c(l,length(out)/l)
out <- as.matrix(out[ra,],l,length(out)/l)
rownames(out) <- paste("s", c(1:l), sep="")
colnames(out) <- paste(c("sol."), seq(1:dim(out)[2]), sep="")
}
} else if (problem=="bsubsetsum"){
b <- c(min(bounds[l],floor(n/a[l])),rep(NA,l-2))
out <- recursive.fn4(numeric(0), b,a,n,M,bounds)
if (length(out)==0) {out <- NULL }
else {
dim(out) <- c(l,length(out)/l)
out <- as.matrix(out[ra,],l,length(out)/l)
rownames(out) <- paste("s", c(1:l), sep="")
colnames(out) <- paste(c("sol."), seq(1:dim(out)[2]), sep="")
}
}
if (is.null(out)) n.sol <-0
else n.sol <- ncol(out)
object <- list()
object$p.n <- n.sol
object$solutions <- out
class(object)<-"subsetsum"
object
}
print.subsetsum <- function (x,...)
{
cat("\n")
if (is.null(x$solutions)) cat("no solutions", "\n")
else {
cat("The number of solutions: ", x$p.n, "\n", sep = "")
cat("\nSolutions:\n")
printCoefmat(x$solutions, ...)
cat("\n")
}
invisible(x)
} |
library(tidyverse)
shift <- expand.grid(c = 1:10, r = 1:40) %>%
mutate(n = row_number()) %>%
rowwise() %>%
mutate(
x = list(4 * c(c, c + 1, c + 0.5)),
y = list(c(r, r, r - 1))
) %>%
unnest(c(x, y))
ggplot(shift) +
geom_polygon(aes(x, y, group = n)) +
coord_fixed() +
theme_void() |
source("xpl-helpers.R")
source("xpl-output.R")
source("xpl-format.R")
observe({
updateSelectInput(session,
inputId = "var_anova1",
choices = names(data()),
selected = '')
updateSelectInput(session,
inputId = "var_anova2",
choices = names(data()),
selected = '')
})
observeEvent(input$finalok, {
f_data <- final_split$train[, sapply(final_split$train, is.factor)]
num_data <- final_split$train[, sapply(final_split$train, is.numeric)]
if (is.null(dim(f_data))) {
k <- final_split$train %>% map(is.factor) %>% unlist()
j <- names(which(k == TRUE))
fdata <- tibble::as_data_frame(f_data)
colnames(fdata) <- j
updateSelectInput(session, inputId = "var_anova2",
choices = names(fdata))
} else {
updateSelectInput(session, 'var_anova2', choices = names(f_data))
}
if (is.null(dim(num_data))) {
k <- final_split$train %>% map(is.numeric) %>% unlist()
j <- names(which(k == TRUE))
numdata <- tibble::as_data_frame(num_data)
colnames(numdata) <- j
updateSelectInput(session, 'var_anova1',
choices = names(numdata), selected = names(numdata))
} else if (ncol(num_data) < 1) {
updateSelectInput(session, 'var_anova1',
choices = '', selected = '')
} else {
updateSelectInput(session, 'var_anova1', choices = names(num_data))
}
})
observeEvent(input$submit_part_train_per, {
f_data <- final_split$train[, sapply(final_split$train, is.factor)]
num_data <- final_split$train[, sapply(final_split$train, is.numeric)]
if (is.null(dim(f_data))) {
k <- final_split$train %>% map(is.factor) %>% unlist()
j <- names(which(k == TRUE))
fdata <- tibble::as_data_frame(f_data)
colnames(fdata) <- j
updateSelectInput(session, inputId = "var_anova2",
choices = names(fdata))
} else {
updateSelectInput(session, 'var_anova2', choices = names(f_data))
}
if (is.null(dim(num_data))) {
k <- final_split$train %>% map(is.numeric) %>% unlist()
j <- names(which(k == TRUE))
numdata <- tibble::as_data_frame(num_data)
colnames(numdata) <- j
updateSelectInput(session, 'var_anova1',
choices = names(numdata), selected = names(numdata))
} else if (ncol(num_data) < 1) {
updateSelectInput(session, 'var_anova1',
choices = '', selected = '')
} else {
updateSelectInput(session, 'var_anova1', choices = names(num_data))
}
})
d_anova <- eventReactive(input$submit_anova, {
req(input$var_anova1)
req(input$var_anova2)
data <- final_split$train[, c(input$var_anova1, input$var_anova2)]
eval(parse(text = paste0("data$", names(data)[2], " <- as.numeric(as.character(data$", names(data)[2], "))")))
xpl_oneway_anova(data, input$var_anova1, input$var_anova2)
})
output$anova_out <- renderPrint({
d_anova()
}) |
control.simulate.network <- function(MCMC.burnin.min = 1000,
MCMC.burnin.max = 100000,
MCMC.burnin.pval = 0.5,
MCMC.burnin.add = 1,
MCMC.prop.form = ~discord + sparse,
MCMC.prop.diss = ~discord + sparse,
MCMC.prop.weights.form = "default",
MCMC.prop.weights.diss = "default",
MCMC.prop.args.form = NULL,
MCMC.prop.args.diss = NULL,
MCMC.maxedges = Inf,
MCMC.maxchanges = 1000000,
term.options = NULL,
MCMC.packagenames = c()) {
control <- list()
for(arg in names(formals(sys.function())))
control[arg] <- list(get(arg))
set.control.class("control.simulate.network")
}
control.simulate.stergm <- function(MCMC.burnin.min = NULL,
MCMC.burnin.max = NULL,
MCMC.burnin.pval = NULL,
MCMC.burnin.add = NULL,
MCMC.prop.form = NULL,
MCMC.prop.diss = NULL,
MCMC.prop.weights.form = NULL,
MCMC.prop.weights.diss = NULL,
MCMC.prop.args.form = NULL,
MCMC.prop.args.diss = NULL,
MCMC.maxedges = NULL,
MCMC.maxchanges = NULL,
term.options = NULL,
MCMC.packagenames = NULL) {
control <- list()
for(arg in names(formals(sys.function())))
control[arg] <- list(get(arg))
set.control.class("control.simulate.stergm")
} |
SelfTrain <- function(form,data,
learner, learner.pars=list(),
pred, pred.pars=list(),
thrConf=0.9,
maxIts=10,percFull=1,
verbose=FALSE)
{
N <- NROW(data)
it <- 0
sup <- which(!is.na(data[,as.character(form[[2]])]))
repeat {
it <- it+1
model <- do.call(learner,c(list(form,data[sup,]),learner.pars))
probPreds <- do.call(pred,c(list(model,data[-sup,]),pred.pars))
new <- which(probPreds[,2] > thrConf)
if (verbose) cat('IT.',it,'\t nr. added exs. =',length(new),'\n')
if (length(new)) {
data[(1:N)[-sup][new],as.character(form[[2]])] <- probPreds[new,1]
sup <- c(sup,(1:N)[-sup][new])
} else break
if (it == maxIts || length(sup)/N >= percFull) break
}
return(model)
} |
synonyms <- function(...) {
UseMethod("synonyms")
}
synonyms.default <- function(sci_id, db = NULL, rows = NA, x = NULL, ...) {
nstop(db)
pchk(x, "sci")
if (!is.null(x)) sci_id <- x
switch(
db,
itis = {
id <- process_syn_ids(sci_id, db, get_tsn, rows = rows, ...)
structure(stats::setNames(synonyms(id, ...), sci_id),
class = "synonyms", db = "itis")
},
tropicos = {
id <- process_syn_ids(sci_id, db, get_tpsid, rows = rows, ...)
structure(stats::setNames(synonyms(id, ...), sci_id),
class = "synonyms", db = "tropicos")
},
nbn = {
id <- process_syn_ids(sci_id, db, get_nbnid, rows = rows, ...)
structure(stats::setNames(synonyms(id, ...), sci_id),
class = "synonyms", db = "nbn")
},
worms = {
id <- process_syn_ids(sci_id, db, get_wormsid, rows = rows, ...)
structure(stats::setNames(synonyms(id, ...), sci_id),
class = "synonyms", db = "worms")
},
iucn = {
id <- process_syn_ids(sci_id, db, get_iucn, ...)
structure(stats::setNames(synonyms(id, ...), sci_id),
class = "synonyms", db = "iucn")
},
pow = {
id <- process_syn_ids(sci_id, db, get_pow, ...)
structure(stats::setNames(synonyms(id, ...), sci_id),
class = "synonyms", db = "pow")
},
stop("the provided db value was not recognised", call. = FALSE)
)
}
process_syn_ids <- function(input, db, fxn, ...){
g <- tryCatch(as.numeric(as.character(input)), warning = function(e) e)
if (inherits(g, "condition") && all(!grepl("ipni\\.org", input))) {
return(eval(fxn)(input, ...))
}
if (
is.numeric(g) ||
is.character(input) && all(grepl("N[HB]", input)) ||
is.character(input) && all(grepl("ipni\\.org", input)) ||
is.character(input) && all(grepl("[[:digit:]]", input))
) {
as_fxn <- switch(db,
itis = as.tsn,
tropicos = as.tpsid,
nbn = as.nbnid,
worms = as.wormsid,
iucn = as.iucn,
pow = as.pow)
if (db == "iucn") return(as_fxn(input, check = TRUE))
return(as_fxn(input, check = FALSE))
} else {
eval(fxn)(input, ...)
}
}
synonyms.tsn <- function(id, ...) {
warn_db(list(...), "itis")
fun <- function(x){
if (is.na(x)) { NA_character_ } else {
is_acc <- rit_acc_name(x, ...)
if (all(!is.na(is_acc$acceptedName))) {
accdf <- stats::setNames(
data.frame(x[1], is_acc, stringsAsFactors = FALSE),
c("sub_tsn", "acc_name", "acc_tsn", "acc_author")
)
x <- is_acc$acceptedTsn
message("Accepted name(s) is/are '",
paste0(is_acc$acceptedName, collapse = "/"), "'")
message("Using tsn(s) ", paste0(is_acc$acceptedTsn, collapse = "/"),
"\n")
} else {
accdf <- data.frame(sub_tsn = x[1], acc_tsn = x[1],
stringsAsFactors = FALSE)
}
res <- Map(function(z, w) {
tmp <- ritis::synonym_names(z)
if (NROW(tmp) == 0) {
tibble::tibble()
} else {
tmp <- stats::setNames(tmp, c('syn_author', 'syn_name', 'syn_tsn'))
cbind(w, tmp, row.names = NULL)
}
}, x, split(accdf, seq_len(NROW(accdf))))
do.call("rbind", unname(res))
}
}
stats::setNames(lapply(id, fun), id)
}
rit_acc_name <- function(x, ...) {
tmp <- ritis::accepted_names(x, ...)
if (NROW(tmp) == 0) {
data.frame(submittedtsn = x[1], acceptedName = NA, acceptedTsn = x[1],
stringsAsFactors = FALSE)
} else {
tmp
}
}
synonyms.tpsid <- function(id, ...) {
warn_db(list(...), "topicos")
fun <- function(x) {
if (is.na(x)) {
NA_character_
} else {
res <- tp_synonyms(x, ...)$synonyms
if (grepl("no syns found", res[1,1])) tibble::tibble() else res
}
}
stats::setNames(lapply(id, fun), id)
}
synonyms.nbnid <- function(id, ...) {
warn_db(list(...), "nbn")
fun <- function(x){
if (is.na(x)) {
NA_character_
} else {
res <- nbn_synonyms(x, ...)
if (length(res) == 0) tibble::tibble() else res
}
}
stats::setNames(lapply(id, fun), id)
}
synonyms.wormsid <- function(id, ...) {
warn_db(list(...), "worms")
fun <- function(x) {
if (is.na(x)) {
NA_character_
} else {
res <- tryCatch(worrms::wm_synonyms(as.numeric(x), ...),
error = function(e) e)
if (inherits(res, "error")) tibble::tibble() else res
}
}
stats::setNames(lapply(id, fun), id)
}
synonyms.iucn <- function(id, ...) {
warn_db(list(...), "iucn")
out <- vector(mode = "list", length = length(id))
for (i in seq_along(id)) {
if (is.na(id[[i]])) {
out[[i]] <- NA_character_
} else {
res <- rredlist::rl_synonyms(attr(id, "name")[i], ...)$result
out[[i]] <- if (length(res) == 0) tibble::tibble() else res
}
}
stats::setNames(out, id)
}
synonyms.pow <- function(id, ...) {
warn_db(list(...), "pow")
out <- vector(mode = "list", length = length(id))
for (i in seq_along(id)) {
if (is.na(id[[i]])) {
out[[i]] <- NA_character_
} else {
res <- pow_synonyms(id[i], ...)
out[[i]] <- if (length(res) == 0) {
tibble::tibble()
} else {
names(res)[1] <- "id"
res
}
}
}
stats::setNames(out, id)
}
synonyms.ids <- function(id, ...) {
fun <- function(x){
if (is.na(x)) {
out <- NA_character_
} else {
out <- synonyms(x, ...)
}
return( out )
}
lapply(id, fun)
}
synonyms_df <- function(x) {
UseMethod("synonyms_df")
}
synonyms_df.default <- function(x) {
stop("no 'synonyms_df' method for ", class(x), call. = FALSE)
}
synonyms_df.synonyms <- function(x) {
x <- Filter(function(z) inherits(z, "data.frame"), x)
x <- Filter(function(z) NROW(z) > 0, x)
(data.table::setDF(
data.table::rbindlist(x, use.names = TRUE, fill = TRUE, idcol = TRUE)
))
} |
create_database <- function(dbname, user, password, host) {
stopifnot(is.character(dbname), is.character(user), is.character(password), is.character(host))
drv <- dbDriver("PostgreSQL")
database_diet <- dbConnect(drv, dbname = dbname, user = user, password = password, host = host)
dbSendQuery(database_diet, "CREATE TABLE deputies (id_deputy varchar(4) NOT NULL,
nr_term_of_office int NOT NULL, surname_name varchar(50) NOT NULL,
PRIMARY KEY (id_deputy, nr_term_of_office),
CONSTRAINT uq_surname_name UNIQUE (nr_term_of_office, surname_name))")
dbSendQuery(database_diet, "CREATE TABLE votings (id_voting int NOT NULL,
nr_term_of_office int NOT NULL, nr_meeting int NOT NULL,
date_meeting date NOT NULL, nr_voting int NOT NULL,
topic_voting text NOT NULL, link_results varchar(200),
PRIMARY KEY (id_voting, nr_term_of_office))")
dbSendQuery(database_diet, "CREATE TABLE votes (id_vote int NOT NULL,
nr_term_of_office int NOT NULL, id_deputy varchar(4) NOT NULL,
id_voting int NOT NULL, vote varchar(20) NOT NULL, club varchar(50),
PRIMARY KEY (id_vote, nr_term_of_office),
FOREIGN KEY (id_deputy, nr_term_of_office) REFERENCES deputies(id_deputy, nr_term_of_office),
FOREIGN KEY (id_voting, nr_term_of_office) REFERENCES votings(id_voting, nr_term_of_office))")
dbSendQuery(database_diet, "CREATE TABLE statements (id_statement varchar(11) NOT NULL,
nr_term_of_office int NOT NULL, surname_name varchar(100) NOT NULL,
date_statement date NOT NULL, titles_order_points text NOT NULL,
statement text NOT NULL,
PRIMARY KEY (id_statement, nr_term_of_office))")
dbSendQuery(database_diet, "CREATE TABLE counter (id SERIAL PRIMARY KEY, what varchar(10) NOT NULL,
date varchar(10) NOT NULL)")
suppressWarnings(dbDisconnect(database_diet))
return(invisible(NULL))
} |
getParDepMan <- function(object, pred.var, pred.grid, pred.fun, train, progress,
parallel, paropts, ...) {
plyr::adply(pred.grid, .margins = 1, .progress = progress,
.parallel = parallel, .paropts = paropts,
.fun = function(x) {
temp <- train
temp[, pred.var] <- x
out <- pred.fun(object, newdata = temp)
if (length(out) == 1) {
stats::setNames(out, "yhat")
} else {
if (is.null(names(out))) {
stats::setNames(out, paste0("yhat.", 1L:length(out)))
} else {
stats::setNames(out, paste0("yhat.", names(out)))
}
}
}, .id = NULL)
} |
qat_analyse_lim_rule_dynamic_1d <-
function(measurement_vector, min_vector=NULL, max_vector=NULL, min_vector_name=NULL, max_vector_name=NULL, min_vector_identifier=NULL, max_vector_identifier=NULL) {
flagvector <- array(0.0, length(measurement_vector))
if(length(measurement_vector) != length(min_vector)) {
min_vector <- array(NaN, length(measurement_vector))
}
if(length(measurement_vector) != length(max_vector)) {
max_vector <- array(NaN, length(measurement_vector))
}
for (ii in 1:length(measurement_vector)) {
if (!is.na(measurement_vector[ii])) {
if (!is.na(min_vector[ii])) {
if (measurement_vector[ii] < min_vector[ii]) {
flagvector[ii] <- -1
}
}
if (!is.na(max_vector[ii])) {
if (measurement_vector[ii] > max_vector[ii]) {
flagvector[ii] <- +1
}
}
}
}
resultlist<- c(list(flagvector), list(min_vector), list(max_vector), list(min_vector_name), list(max_vector_name), list(min_vector_identifier), list(max_vector_identifier))
names(resultlist)<-c("flagvector", "min_vector", "max_vector", "min_vector_name", "max_vector_name", "min_vector_identifier", "max_vector_identifier")
return(resultlist)
} |
organization_purge <- function(id, url = get_default_url(), key = get_default_key(),
as = 'list', ...) {
res <- ckan_POST(url, 'organization_purge', list(id = id), key = key, ...)
switch(as, json = res, list = lapply(jsl(res), as.ckan_organization),
table = jsd(res))
} |
fourCellsFromXY <- function(object, xy, duplicates=TRUE) {
r <- raster(object)
stopifnot(is.matrix(xy))
return( .doFourCellsFromXY(r@ncols, r@nrows, xmin(r), xmax(r), ymin(r), ymax(r), xy, duplicates, .isGlobalLonLat(r)))
} |
context("checkRequiredCols")
library(stringi)
requiredCols <- getRequiredCols()
test_that("checkRequiredCols detects missing cols", {
cols <- stri_c("id,sire,siretype,dam,damtype,sex,numberofparentsknown,birth,",
"arrivalatcenter,death,departure,status,ancestry,fromcenter?,",
"origin")
expect_true(all(requiredCols %in% checkRequiredCols(cols, reportErrors = TRUE)))
}) |
juldate=function( date) {
if(length(date)<3)
stop('illegal date vector - must have a least 3 elements')
date = c(date,rep(0,6-length(date)))
iy = floor( date[1] )
if(iy<0 )iy = iy +1
else if(iy==0 ) stop('error - there is no year 0')
im = floor( date[2] )
day = date[3] + ( date[4] + date[5]/60.0 + date[6]/3600.0) / 24.0
if(( im<3 ) ){
iy= iy-1
im = im+12
}
a = floor(iy/100)
ry = iy
jd = floor(ry*0.25) + 365.0*(ry -1860) + floor(30.6001*(im+1.)) +
day - 105.5
if(jd>-100830.5 )jd = jd + 2 - a + floor(a/4)
return(jd)
} |
get.breaks.vector <-
function(CycleBreaksMatrix){
breaks.vector <- NULL
for(i in 1:dim(CycleBreaksMatrix)[2]){
set <- na.omit(CycleBreaksMatrix[,i])
lset <- length(set)-1
breaks.vector <- append(breaks.vector, set[1:lset])
}
return(breaks.vector)
} |
test_that("inv_simpson works", {
.act <- ds_inv_simpson(de_county, starts_with('pop_'))
.exp <- c(2.06408053773311, 2.25755787299953, 1.68145472009487)
expect_equal(.act, .exp, tolerance = 1e-6)
})
test_that("inv_simpson .name works", {
.act <- ds_inv_simpson(de_county, starts_with('pop_'), .name = 'special_name')
expect_true('special_name' %in% names(.act))
}) |
tidy.lmodel2 <- function(x, ...) {
ret <- x$regression.results[c(1:3, 5)] %>%
select(
method = Method,
Intercept,
Slope,
p.value = `P-perm (1-tailed)`
) %>%
pivot_longer(
cols = c(dplyr::everything(), -method, -p.value),
names_to = "term",
values_to = "estimate"
) %>%
arrange(method, term)
confints <- x$confidence.intervals %>%
pivot_longer(
cols = c(dplyr::everything(), -Method),
names_to = "key",
values_to = "value"
) %>%
tidyr::separate(key, c("level", "term"), "-") %>%
mutate(level = ifelse(level == "2.5%", "conf.low", "conf.high")) %>%
tidyr::pivot_wider(c(Method, term),
names_from = level,
values_from = value
) %>%
dplyr::arrange(Method) %>%
as.data.frame() %>%
select(method = Method, term, conf.low, conf.high)
ret %>%
inner_join(confints, by = c("method", "term")) %>%
select(-p.value, dplyr::everything()) %>%
as_tibble()
}
glance.lmodel2 <- function(x, ...) {
as_glance_tibble(
r.squared = x$rsquare,
theta = x$theta,
p.value = x$P.param,
H = x$H,
nobs = stats::nobs(x),
na_types = "rrrri"
)
} |
XB <- function (Xca, U, H, m)
{
if (missing(Xca))
stop("The data set must be given")
if (is.null(Xca))
stop("The data set Xca is empty")
n=nrow(Xca)
Xca=as.matrix(Xca)
if (any(is.na(Xca)))
stop("The data set Xca must not contain NA values")
if (!is.numeric(Xca))
stop("The data set Xca is not a numeric data.frame or matrix")
if (missing(U))
stop("The membership degree matrix U must be given")
if (is.null(U))
stop("The membership degree matrix U is empty")
U=as.matrix(U)
if (any(is.na(U)))
stop("The membership degree matrix U must not contain NA values")
if (!is.numeric(U))
stop("The membership degree matrix U is not numeric")
if (missing(H))
stop("The prototype matrix H must be given")
if (is.null(H))
stop("The prototype matrix H is empty")
H=as.matrix(H)
if (any(is.na(H)))
stop("The prototype matrix H must not contain NA values")
if (!is.numeric(H))
stop("The prototype matrix H is not numeric")
if (nrow(U)!=nrow(Xca))
stop("The numbers of rows of U and Xca must be the same")
if (nrow(H)!=ncol(U))
stop("The number of rows of H and the one of columns of U must be the same")
if (ncol(H)!=ncol(Xca))
stop("The numbers of columns of H and Xca must be the same")
if (ncol(U)==1)
stop("There is only k=1 cluster: the XB index is not computed")
k=ncol(U)
if (missing(m))
{
m=2
}
if (!is.numeric(m))
{
m=2
cat("The parameter of fuzziness m is not numeric: the default value m=2 will be used ",fill=TRUE)
}
if (m<=1)
{
m=2
cat("The parameter of fuzziness m must be >1: the default value m=2 will be used ",fill=TRUE)
}
xie.beni = xie_beni(X = Xca,U = U,H = H,m = m,n = n,k = k)
return(xie.beni)
} |
c2compnames<-function(cmat, ntype="aggr")
{
if(is.null(colnames(cmat)))
{colnames(cmat)<-1:ncol(cmat)}
if(!is.matrix(cmat))
{stop("cmat must be a matrix")}
if(!is.numeric(cmat))
{stop("cmat must be a numeric matric")}
if(length(ntype)!=1)
{stop("ntype must be a single character string!")}
if(!ntype %in% c("aggr", "sequ"))
{stop("ntype must be one of 'aggr', 'sequ'")}
if(ntype=="aggr")
{
cnames<-colnames(cmat)
rnames<-character(length=nrow(cmat))
for(i in 1:nrow(cmat))
{
si<-sign(cmat[i,])
wsip<-si==1
wsin<-si==(-1)
rnames[i]<-paste( "(", paste(cnames[wsip], collapse="+"), ")-(", paste(cnames[wsin], collapse="+"), ")", collapse="", sep="" )
}
}
if(ntype=="sequ")
{
cnames<-colnames(cmat)
rnames<-character(length=nrow(cmat))
for(i in 1:nrow(cmat))
{
si<-sign(cmat[i,])
wsin0<-si!=0
wsip<-si[wsin0]==1
wsin<-si[wsin0]==(-1)
nam<-cnames[wsin0]
sic<-character(length=length(nam))
sic[wsip]<-"+"
sic[wsin]<-"-"
rnames[i]<-paste(paste(sic, nam, sep=""), collapse="")
}
}
rownames(cmat)<-rnames
return(cmat)
}
IAcontrasts<-function(type, k)
{
if(!all(type %in% c("Dunnett", "Tukey", "Sequence", "Identity")))
{stop("all elements of type must be one of 'Dunnett','Tukey' or 'Sequence'")}
if ( any(c(length(k),length(type))!=2))
{stop("k and type must be vectors of length 2")}
if(!is.numeric(k) & !is.integer(k))
{stop("k must be an integer vector")}
n1<-rep(3,k[1])
names(n1)<-as.character(1:k[1])
n2<-rep(3,k[2])
names(n2)<-as.character(1:k[2])
if(type[1]!="Identity"){CM1 <- contrMat(n=n1, type=type[1])}
else{CM1<-diag(rep(1,k[1]))}
if(type[2]!="Identity"){CM2 <- contrMat(n=n2, type=type[2])}
else{CM2 <-diag(rep(1,k[2]))}
out <- kronecker(CM1, CM2)
cnames <- paste( rep(colnames(CM1), each=length(colnames(CM2))),
rep(colnames(CM2), times=length(colnames(CM1))), sep="")
colnames(out)<-cnames
return(out)
}
IAcontrastsCMAT<-function(CMAT1, CMAT2)
{
out <- kronecker(CMAT1, CMAT2)
cnames <- paste( rep(colnames(CMAT1), each=length(colnames(CMAT2))),
rep(colnames(CMAT2), times=length(colnames(CMAT1))), sep="")
colnames(out)<-cnames
return(out)
} |
eget <- function(..., coerce=TRUE, envir=parent.frame(), inherits=FALSE, mode="default", cmdArg=FALSE) {
pargs <- .parseArgs(list(...), defaults=alist(name=, default=NULL))
args <- pargs$args
if (!is.element("name", names(args))) {
argsT <- pargs$namedArgs
if (length(argsT) == 0L) {
stop("Argument 'name' is missing (or NULL).")
}
args$name <- names(argsT)[1L]
default <- argsT[[1L]]
args$default <- default
argsT <- argsT[-1L]
pargs$args <- args
pargs$namedArgs <- argsT
}
args <- Reduce(c, pargs)
name <- as.character(args$name)
.stop_if_not(length(name) == 1L)
default <- args$default
if (cmdArg) {
defaultT <- cmdArg(...)
if (!is.null(defaultT)) default <- defaultT
}
if (is.list(envir)) {
} else {
envir <- as.environment(envir)
.stop_if_not(is.environment(envir))
}
value <- default
if (is.list(envir)) {
if (is.element(name, names(envir))) {
value <- envir[[name]]
}
} else {
if (mode == "default") {
mode <- mode(value)
if (mode == "NULL") mode <- "any"
}
if (exists(name, mode=mode, envir=envir, inherits=inherits)) {
value <- get(name, mode=mode, envir=envir, inherits=inherits)
}
}
if (coerce) {
if (!identical(value, default) && !is.null(default)) {
value <- as(value, Class=class(default)[1L])
}
}
value
}
ecget <- function(..., envir=parent.frame()) {
eget(..., envir=envir, cmdArg=TRUE)
} |
prep.date <- function(x) {
if(all(is.timepoint(x)) == TRUE){
doy <- as.numeric(strftime(x, format = "%j"))
}
if(is.numeric(x)){
if(any(x <= 0) | any(x > 366)){
stop(c("Day of the year is not between 1-366"))}
doy <- x
}
doy
} |
select_all <- function(.tbl, .funs = list(), ...) {
lifecycle::signal_stage("superseded", "select_all()")
funs <- as_fun_list(.funs, caller_env(), ..., .caller = "select_all")
vars <- tbl_vars(.tbl)
syms <- vars_select_syms(vars, funs, .tbl)
select(.tbl, !!!syms)
}
rename_all <- function(.tbl, .funs = list(), ...) {
lifecycle::signal_stage("superseded", "rename_with()")
funs <- as_fun_list(.funs, caller_env(), ..., .caller = "rename_all")
vars <- tbl_vars(.tbl)
syms <- vars_select_syms(vars, funs, .tbl, strict = TRUE)
rename(.tbl, !!!syms)
}
select_if <- function(.tbl, .predicate, .funs = list(), ...) {
funs <- as_fun_list(.funs, caller_env(), ..., .caller = "select_if")
if (!is_logical(.predicate)) {
.predicate <- as_fun_list(.predicate, caller_env(), .caller = "select_if", .caller_arg = ".predicate")
}
vars <- tbl_if_vars(.tbl, .predicate, caller_env(), .include_group_vars = TRUE)
syms <- vars_select_syms(vars, funs, .tbl)
select(.tbl, !!!syms)
}
rename_if <- function(.tbl, .predicate, .funs = list(), ...) {
funs <- as_fun_list(.funs, caller_env(), ..., .caller = "rename_if")
if (!is_logical(.predicate)) {
.predicate <- as_fun_list(.predicate, caller_env(), .caller = "rename_if", .caller_arg = ".predicate")
}
vars <- tbl_if_vars(.tbl, .predicate, caller_env(), .include_group_vars = TRUE)
syms <- vars_select_syms(vars, funs, .tbl, strict = TRUE)
rename(.tbl, !!!syms)
}
select_at <- function(.tbl, .vars, .funs = list(), ...) {
vars <- tbl_at_vars(.tbl, .vars, .include_group_vars = TRUE)
funs <- as_fun_list(.funs, caller_env(), ..., .caller = "select_at")
syms <- vars_select_syms(vars, funs, .tbl)
select(.tbl, !!!syms)
}
rename_at <- function(.tbl, .vars, .funs = list(), ...) {
vars <- tbl_at_vars(.tbl, .vars, .include_group_vars = TRUE)
funs <- as_fun_list(.funs, caller_env(), ..., .caller = "rename_at")
syms <- vars_select_syms(vars, funs, .tbl, strict = TRUE)
rename(.tbl, !!!syms)
}
vars_select_syms <- function(vars, funs, tbl, strict = FALSE, error_call = caller_env()) {
if (length(funs) > 1) {
msg <- glue("`.funs` must contain one renaming function, not {length(funs)}.")
abort(msg, call = error_call)
} else if (length(funs) == 1) {
fun <- funs[[1]]
if (is_quosure(fun)) {
fun <- quo_as_function(fun)
}
syms <- if (length(vars)) {
set_names(syms(vars), fun(as.character(vars)))
} else {
set_names(syms(vars))
}
} else if (!strict) {
syms <- syms(vars)
} else {
msg <- glue("`.funs` must specify a renaming function.")
abort(msg, call = error_call)
}
group_vars <- group_vars(tbl)
group_syms <- syms(group_vars)
has_group_sym <- group_syms %in% syms
new_group_syms <- set_names(group_syms[!has_group_sym], group_vars[!has_group_sym])
c(new_group_syms, syms)
} |
ppcca.metabol <-
function(Y, Covars, minq=1, maxq=2, scale="none", epsilon = 0.1, plot.BIC=FALSE, printout=TRUE)
{
Y<-as.matrix(Y)
Covars<-as.matrix(Covars)
if (missing(Y)) {
stop("Spectral data are required to fit the PPCCA model.\n")
}
if (missing(Covars)) {
stop("Covariate data are required to fit the PPCCA model.\n ")
}
if (nrow(Y) != nrow(Covars)) {
stop("Spectral data and covariate data should have the same number of rows.\n")
}
if (missing(minq)) {
minq<- 1
}
if (missing(maxq)) {
maxq<- 2
}
if (minq > maxq) {
stop("minq can not be greater than maxq.\n")
}
if (maxq > ncol(Y)) {
stop("maxq can not be greater than the number of variables.\n")
}
if(maxq > 10)
{
cat("Warning! Model fitting may become very slow for q > 10.\n\n")
}
if (epsilon > 1) {
cat("Warning! Poor model covergence expected for epsilon > 1.\n")
}
if (epsilon < 0.0001) {
cat("Warning! Model covergence becomes very slow for epsilon < 0.0001.\n")
}
V<-4000
N<-nrow(Y)
p<-ncol(Y)
L<-ncol(Covars)
Covars<-standardize(Covars)
Covars<-rbind(rep(1, N), t(Covars))
if(p > 375)
{
stop("Spectral dimension is too large for current computation capabilities. Reduce the number of spectral bins to less than 375.")
}
Sig_q<-rep(0,maxq)
W_q<-list()
Alpha_q<-list()
U_q<-list()
AIC<-rep(0,maxq)
BIC<-rep(0,maxq)
ll<-matrix(NA,maxq,V)
lla<-matrix(NA,maxq,V)
Y<-as.matrix(scaling(Y, type=scale))
Vp<-10
C2p<-p*3
muhat<-colMeans(Y)
Yc<-sweep(Y,2,muhat,"-")
S<-(1/nrow(Yc))*(t(Yc)%*%Yc)
temp<-eigen(S)
for(q in minq:maxq)
{
Sig<-abs((1/(p-q))*sum(temp$val[(q+1):p]))
W<-temp$vec[,1:q]
scores<-t(solve((t(W)%*%W) + (Sig*diag(q)))%*%t(W)%*%t(Yc))
Alpha<-matrix(0, q, L+1)
for(i in 1:q)
{
if(L==1)
{
dat<-data.frame(cbind(scores[,i], as.matrix(Covars[2:(L+1),])))
}else{
dat<-data.frame(cbind(scores[,i], t(Covars[2:(L+1),])))
}
Alpha[i,]<-glm(dat, family=gaussian)$coef
}
tol <- epsilon+1
v <- 0
while(tol>epsilon)
{
v <- v+1
M_1<-solve(t(W)%*%W + Sig*diag(q))
u<-M_1%*%(t(W)%*%t(Yc) + Sig*(Alpha%*%Covars))
Sum_Euu<-(nrow(Yc)*Sig*M_1) + (u%*%t(u))
Alpha<-(u%*%t(Covars))%*%solve(Covars%*%t(Covars))
W<-(t(Yc)%*%t(u))%*%solve(Sum_Euu)
YWEu<-sum(diag(Yc%*%W%*%u))
MLESig<-(nrow(Yc)*sum(diag(S)) + sum(diag((t(W)%*%W)%*%Sum_Euu)) - 2*YWEu)/(p*nrow(Yc))
Sig<- c(((N*p)*MLESig + C2p)/((N*p) + Vp + 2))
Den<-rep(NA, nrow(Y))
Sigma<-W%*%t(W)+(Sig*diag(p))
mumat<-W%*%(Alpha%*%Covars) + matrix(muhat, nrow=p, ncol=N, byrow=FALSE)
for(i in 1:nrow(Y))
{
Den[i]<-(dmvnorm(Y[i,], mumat[,i], Sigma, log=TRUE))
}
ll[q,v]<-sum(Den)
converge<-Aitken(ll, lla, v, q, epsilon)
tol<-converge[[1]]
lla[q,v]<-converge[[2]]
if(v == V)
{
cat("Algorithm stopped for q = ", q,". Maximum number of iterations exceeded.\n\n")
tol<-epsilon-1
}
}
if(printout == TRUE)
{
cat("q = ", q, ": PPCCA converged.\n\n")
}
params<-(p*q) - (0.5*q*(q-1)) + (q*(L+1)) + 1
AIC[q]<-2*ll[q,v] - (2*params)
BIC[q]<-2*ll[q,v] - params*log(N)
U_q[[q]]<-u
Sig_q[q]<-Sig
W_q[[q]]<-W
Alpha_q[[q]]<-Alpha
}
qopt<-c(minq:maxq)[BIC[minq:maxq]==max(BIC[minq:maxq])]
Uopt<-t(U_q[[qopt]])
Wopt<-W_q[[qopt]]
Sigopt<-Sig_q[qopt]
Alphaopt<-Alpha_q[[qopt]]
if(plot.BIC == TRUE)
{
plot(minq:maxq, BIC[minq:maxq], type="b", xlab="q", ylab="BIC", col.lab="blue")
abline(v=qopt,col="red", lty=2)
}
list(q=qopt, sig=Sigopt, scores=Uopt, loadings=Wopt, coefficients=Alphaopt, BIC=BIC[minq:maxq], AIC=AIC[minq:maxq])
} |
ggpairs(tips, columns = 1:2, params = c(corMethod = "pearson"))
ggpairs(tips, columns = 1:2, params = c(corMethod = "kendall"))
ggpairs(tips, columns = 1:2, params = c(corMethod = "pearson"), color = "sex")
ggpairs(tips, columns = 1:2, params = c(corMethod = "kendall"), color = "sex")
ggpairs(tips, columns = 1:2, upper = list( params = list(corMethod = "kendall")))
ggpairs(tips, columns = 1:2, upper = list( params = list(corMethod = "pearson")))
ggpairs(tips, columns = 1:2, upper = list( params = list(corMethod = "pearson")), color = "sex")
ggpairs(tips, columns = 1:2, upper = list( params = list(corMethod = "kendall")), color = "sex")
swM <- swiss
colnames(swM) <- abbreviate(colnames(swiss), min=6)
swM[1,2] <- swM[7,3] <- swM[25,5] <- NA
(C. <- cov(swM))
try(cov(swM, use = "all"))
(C2 <- cov(swM, use = "complete"))
stopifnot(identical(C2, cov(swM, use = "na.or.complete")))
range(eigen(C2, only.values = TRUE)$values)
(C3 <- cov(swM, use = "pairwise"))
range(eigen(C3, only.values = TRUE)$values)
cor(mtcars[, 1:3], method = "kendall", use = "complete")[2,3]
0.7915213
cor(mtcars[, 1:3], method = "kendall", use = "pairwise")[2,3]
cor(mtcars[, 1:3], method = "kendall", use = "na.or")[2,3]
cor(mtcars$cyl, mtcars$disp, method = "kendall", use = "complete")
cor(mtcars$cyl, mtcars$disp, method = "kendall", use = "pairwise")
cor(mtcars$cyl, mtcars$disp, method = "kendall", use = "na.or")
ggally_cor(mtcars, aes(cyl, disp), corMethod = "kendall", use = "complete.obs") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.