code
stringlengths 1
13.8M
|
---|
ssd_hp <- function(x, ...) {
UseMethod("ssd_hp")
}
.ssd_hp_fitdist <- function(x, conc, ci, level, nboot, parallel, ncpus) {
chk_vector(conc)
chk_numeric(conc)
chk_number(level)
chk_range(level)
args <- as.list(x$estimate)
args$q <- conc
dist <- x$distname
what <- paste0("p", dist)
est <- do.call(what, args)
if (!ci) {
na <- rep(NA_real_, length(conc))
return(as_tibble(data.frame(
conc = conc, est = est * 100,
se = na, lcl = na, ucl = na, dist = rep(dist, length(conc)),
wt = rep(1, length(conc)),
stringsAsFactors = FALSE
)))
}
samples <- boot(x, nboot = nboot, parallel = parallel, ncpus = ncpus)
cis <- cis(samples, p = TRUE, level = level, x = conc)
as_tibble(data.frame(
conc = conc, est = est * 100,
se = cis$se * 100, lcl = cis$lcl * 100, ucl = cis$ucl * 100,
dist = dist, wt = 1, stringsAsFactors = FALSE
))
}
.ssd_hp_fitdists <- function(x, conc, ci, level, nboot, parallel, ncpus,
average) {
if (!length(x) || !length(conc)) {
no <- numeric(0)
return(as_tibble(data.frame(
conc = no, est = no, se = no,
lcl = no, ucl = no, dist = character(0),
wt = numeric(0),
stringsAsFactors = FALSE
)))
}
weight <- .ssd_gof_fitdists(x)$weight
hp <- lapply(x, ssd_hp,
conc = conc, ci = ci, level = level, nboot = nboot,
parallel = parallel, ncpus = ncpus
)
if (!average) {
hp <- mapply(function(x, y) {x$wt <- y; x}, hp, weight, USE.NAMES = FALSE,
SIMPLIFY = FALSE)
hp <- do.call("rbind", hp)
row.names(hp) <- NULL
return(as_tibble(hp))
}
hp <- lapply(hp, function(x) x[1:5])
hp <- lapply(hp, as.matrix)
hp <- Reduce(function(x, y) {
abind(x, y, along = 3)
}, hp)
suppressMessages(hp <- apply(hp, c(1, 2), weighted.mean, w = weight))
hp <- as.data.frame(hp)
hp$conc <- conc
hp$dist <- "average"
hp$wt <- 1
as_tibble(hp)
}
ssd_hp.fitdist <- function(x, conc, ci = FALSE, level = 0.95, nboot = 1000,
parallel = NULL, ncpus = 1, ...) {
chk_unused(...)
.ssd_hp_fitdist(x, conc,
ci = ci, level = level, nboot = nboot,
parallel = parallel, ncpus = ncpus
)
}
ssd_hp.fitdistcens <- function(x, conc, ci = FALSE, level = 0.95, nboot = 1000,
parallel = NULL, ncpus = 1, ...) {
chk_unused(...)
.ssd_hp_fitdist(x, conc,
ci = ci, level = level, nboot = nboot,
parallel = parallel, ncpus = ncpus
)
}
ssd_hp.fitdists <- function(x, conc, ci = FALSE, level = 0.95, nboot = 1000,
parallel = NULL, ncpus = 1,
average = TRUE, ic = "aicc", ...) {
chk_unused(...)
if(!missing(ic)) {
deprecate_warn("0.3.6", "ssdtools::ssd_hp(ic = )",
details = "AICc is used for model averaging unless the data are censored in which case AIC is used.")
}
.ssd_hp_fitdists(x, conc,
ci = ci, level = level, nboot = nboot,
parallel = parallel, ncpus = ncpus,
average = average
)
}
ssd_hp.fitdistscens <- function(x, conc, ci = FALSE, level = 0.95, nboot = 1000,
parallel = NULL, ncpus = 1,
average = TRUE, ic = "aic", ...) {
chk_unused(...)
if(!missing(ic)) {
deprecate_warn("0.3.6", "ssdtools::ssd_hp(ic = )",
details = "AICc is used for model averaging unless the data are censored in which case AIC is used.")
}
.ssd_hp_fitdists(x, conc,
ci = ci, level = level, nboot = nboot,
parallel = parallel, ncpus = ncpus, average = average
)
} |
dltCoefficientRMSError <- function(p, coor.2d){
dlt_reconstruct <- dltReconstruct(matrix(p, nrow=11, ncol=dim(coor.2d)[3]), coor.2d)
mean(dlt_reconstruct$rmse)
} |
test_that("binCI() messages",{
expect_error(binCI(-1,10),"must be non-negative")
expect_error(binCI(1,-10),"must be non-negative")
expect_error(binCI(11,10),"must not be greater than")
expect_error(binCI("a",10),"must be whole numbers")
expect_error(binCI(1,"a"),"must be whole numbers")
expect_error(binCI(c(-1,2),10),"must be non-negative")
expect_error(binCI(1,c(-1,10)),"must be non-negative")
expect_error(binCI(1.1,10),"must be whole numbers")
expect_error(binCI(1,10.1),"must be whole numbers")
expect_error(binCI(c(1,1.1),10),"must be whole numbers")
expect_error(binCI(1,c(9.1,10)),"must be whole numbers")
expect_error(binCI(c(1,10),5),"must not be greater than")
expect_error(binCI(c(1,10),c(5,9)),"must not be greater than")
expect_error(binCI(6,c(5,9)),"must not be greater than")
expect_error(binCI(6,10,type="derek"),"should be one of")
expect_error(binCI(6,10,conf.level=0),"must be between 0 and 1")
expect_error(binCI(6,10,conf.level=1),"must be between 0 and 1")
expect_error(binCI(6,10,conf.level="R"),"must be numeric")
expect_warning(binCI(6:9,10),"Can't use multiple 'type's with multiple 'x's")
expect_error(binCI(data.frame(d=6:9),10),"'x' must be a single or vector")
expect_error(binCI(2,data.frame(d=6:9)),"'n' must be a single or vector")
})
test_that("hyperCI() messages",{
expect_error(hyperCI(-1,10,5),"must all be non-negative")
expect_error(hyperCI(1,-10,5),"must all be non-negative")
expect_error(hyperCI(1,10,-5),"must all be non-negative")
expect_error(hyperCI(1,10,5),"'m' must be less than 'M'")
expect_error(hyperCI(15,5,10),"'m' must be less than 'n'")
expect_error(hyperCI("a",10,5),"must all be whole numbers")
expect_error(hyperCI(15,"a",5),"must all be whole numbers")
expect_error(hyperCI(15,10,"a"),"must all be whole numbers")
expect_error(hyperCI(20.1,10,5),"must be a whole number")
expect_error(hyperCI(15,10.1,5),"must be a whole number")
expect_error(hyperCI(15,10,5.1),"must be a whole number")
expect_error(hyperCI(c(15,15),10,5),"be a single value")
expect_error(hyperCI(15,c(10,10),5),"be a single value")
expect_error(hyperCI(15,10,c(5,5)),"be a single value")
expect_error(hyperCI(c(15,15),c(10,10),c(5,5)),"be a single value")
expect_error(hyperCI(15,10,5,conf.level=0),"must be between 0 and 1")
expect_error(hyperCI(15,10,5,conf.level=1),"must be between 0 and 1")
expect_error(hyperCI(15,10,5,conf.level="R"),"must be numeric")
})
test_that("poiCI() messages",{
expect_error(poiCI(6,type="derek"),"should be one of")
expect_error(poiCI(-1),"must be non-negative")
expect_error(poiCI(c(-1,1:3)),"must be non-negative")
expect_error(poiCI("a"),"must be a whole number")
expect_error(poiCI(1.1),"must be a whole number")
expect_error(poiCI(6,conf.level=0),"must be between 0 and 1")
expect_error(poiCI(6,conf.level=1),"must be between 0 and 1")
expect_error(poiCI(6,conf.level="R"),"must be numeric")
expect_warning(poiCI(6:9),"Can't use multiple 'type's with multiple 'x's")
expect_error(poiCI(data.frame(d=6:9)),"'x' must be a single or vector")
})
test_that("binCI() output types",{
res <- binCI(7,10)
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),3)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
expect_equal(rownames(res),c("Exact","Wilson","Asymptotic"))
res <- binCI(c(3,7),10,type="wilson")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- binCI(c(3,7),10,type="exact")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- binCI(c(3,7),10,type="asymptotic")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- binCI(7,10,verbose=TRUE)
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),3)
expect_equal(ncol(res),5)
expect_equal(colnames(res),c("x","n","proportion","95% LCI","95% UCI"))
expect_equal(rownames(res),c("Exact","Wilson","Asymptotic"))
res <- binCI(c(3,7),10,type="wilson",verbose=TRUE)
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),5)
expect_equal(colnames(res),c("x","n","proportion","95% LCI","95% UCI"))
res <- binCI(c(3,7),10,type="exact",verbose=TRUE)
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),5)
expect_equal(colnames(res),c("x","n","proportion","95% LCI","95% UCI"))
res <- binCI(c(3,7),10,type="asymptotic",verbose=TRUE)
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),5)
expect_equal(colnames(res),c("x","n","proportion","95% LCI","95% UCI"))
})
test_that("hyperCI() output types",{
res <- hyperCI(20,20,10)
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),1)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
})
test_that("poiCI() output types",{
res <- poiCI(10)
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),4)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
expect_equal(rownames(res),c("Exact","Daly","Byar","Asymptotic"))
res <- poiCI(10,type="exact")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),1)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- poiCI(10,type="daly")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),1)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- poiCI(10,type="byar")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),1)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- poiCI(10,type="asymptotic")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),1)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- poiCI(10,type=c("exact","daly"))
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
expect_equal(rownames(res),c("Exact","Daly"))
res <- poiCI(10,type="exact",verbose=TRUE)
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),1)
expect_equal(ncol(res),3)
expect_equal(colnames(res),c("x","95% LCI","95% UCI"))
expect_equal(rownames(res),"Exact")
res <- poiCI(10,type=c("exact","daly"),verbose=TRUE)
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),3)
expect_equal(colnames(res),c("x","95% LCI","95% UCI"))
expect_equal(rownames(res),c("Exact","Daly"))
res <- poiCI(10:11,type="exact")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- poiCI(10:11,type="daly")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- poiCI(10:11,type="byar")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- poiCI(10:11,type="asymptotic")
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),2)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
res <- poiCI(0)
expect_is(res,"matrix")
expect_true(is.numeric(res))
expect_equal(nrow(res),4)
expect_equal(ncol(res),2)
expect_equal(colnames(res),c("95% LCI","95% UCI"))
expect_equal(rownames(res),c("Exact","Daly","Byar","Asymptotic"))
})
test_that("binCI() compared to epitools functions",{
res <- binCI(7,10,verbose=TRUE)
res[,4:5] <- round(res[,4:5],7)
resepi <- matrix(c(7,10,0.7,0.3475471,0.9332605,
7,10,0.7,0.3967781,0.8922087,
7,10,0.7,0.4159742,0.9840258),nrow=3,byrow=TRUE)
rownames(resepi) <- c("Exact","Wilson","Asymptotic")
colnames(resepi) <- c("x","n","proportion","lower","upper")
expect_equivalent(res,resepi)
res <- binCI(5:7,10,type="wilson",verbose=TRUE)
res[,4:5] <- round(res[,4:5],7)
resepi <- matrix(c(5,10,0.5,0.2365931,0.7634069,
6,10,0.6,0.3126738,0.8318197,
7,10,0.7,0.3967781,0.8922087),nrow=3,byrow=TRUE)
colnames(resepi) <- c("x","n","proportion","lower","upper")
expect_equivalent(res,resepi)
})
test_that("poiCI() compared to epitools functions",{
res <- poiCI(10,verbose=TRUE)
res[,2] <- round(res[,2],6)
res[,3] <- round(res[,3],5)
resepi <- matrix(c(10,4.795389,18.39036,
10,4.795389,18.39036,
10,5.133753,17.74048,
10,3.802050,16.19795),nrow=4,byrow=TRUE)
rownames(resepi) <- c("Exact","Daly","Byar","Asymptotic")
colnames(resepi) <- c("x","lower","upper")
expect_equivalent(res,resepi)
res <- poiCI(5:7,type="exact",verbose=TRUE)
res[,2] <- round(res[,2],6)
res[,3] <- round(res[,3],5)
resepi <- matrix(c(5,1.623486,11.66832,
6,2.201891,13.05948,
7,2.814358,14.42268),nrow=3,byrow=TRUE)
colnames(resepi) <- c("x","lower","upper")
expect_equivalent(res,resepi)
}) |
plot.kma <- function(x, type = "data", number_of_displayed_points = 50, ...) {
if (type == "data")
plot_data(x, number_of_displayed_points)
else if (type == "warping")
plot_warping(x, number_of_displayed_points)
else
stop("Unsupported type of display for kma objects.")
}
plot_data <- function(obj, type = "data", number_of_displayed_points = 50) {
n <- dim(obj$y)[1]
d <- dim(obj$y)[2]
p <- dim(obj$y)[3]
original_grids <- 1:p %>%
purrr::map(~ obj$x[, .x, drop = FALSE]) %>%
purrr::set_names(paste0("P", 1:p)) %>%
as_tibble() %>%
dplyr::mutate(curve_id = 1:dplyr::n()) %>%
tidyr::pivot_longer(
cols = -.data$curve_id,
names_to = "point_id",
values_to = "grid"
) %>%
dplyr::mutate(type = "Original Curves")
warped_grids <- 1:p %>%
purrr::map(~ obj$x_final[, .x, drop = FALSE]) %>%
purrr::set_names(paste0("P", 1:p)) %>%
as_tibble() %>%
dplyr::mutate(curve_id = 1:dplyr::n()) %>%
tidyr::pivot_longer(
cols = -.data$curve_id,
names_to = "point_id",
values_to = "grid"
) %>%
dplyr::mutate(type = "Aligned Curves")
original_values <- 1:p %>%
purrr::map(~ {
df <- matrix(obj$y[, , .x], ncol = d)
colnames(df) <- paste("Dimension", 1:d)
as_tibble(df) %>%
dplyr::mutate(curve_id = 1:dplyr::n())
}) %>%
purrr::set_names(paste0("P", 1:p)) %>%
dplyr::bind_rows(.id = "point_id") %>%
tidyr::pivot_longer(
cols = dplyr::starts_with("Dim"),
names_to = "dimension_id",
values_to = "value"
)
center_grids <- 1:p %>%
purrr::map(~ obj$x_centers_final[, .x, drop = FALSE]) %>%
purrr::set_names(paste0("P", 1:p)) %>%
as_tibble() %>%
dplyr::mutate(curve_id = 1:dplyr::n()) %>%
tidyr::pivot_longer(
cols = -.data$curve_id,
names_to = "point_id",
values_to = "grid"
) %>%
dplyr::mutate(type = "Aligned Curves")
center_values <- 1:p %>%
purrr::map(~ {
df <- matrix(obj$y_centers_final[, , .x], ncol = d)
colnames(df) <- paste("Dimension", 1:d)
as_tibble(df) %>%
dplyr::mutate(curve_id = 1:dplyr::n())
}) %>%
purrr::set_names(paste0("P", 1:p)) %>%
dplyr::bind_rows(.id = "point_id") %>%
tidyr::pivot_longer(
cols = dplyr::starts_with("Dim"),
names_to = "dimension_id",
values_to = "value"
)
number_of_displayed_points <- min(number_of_displayed_points, p)
df <- dplyr::bind_rows(
original_values %>%
dplyr::left_join(original_grids, by = c("point_id", "curve_id")),
original_values %>%
dplyr::left_join(warped_grids, by = c("point_id", "curve_id"))
) %>%
dplyr::mutate(type = factor(.data$type, c("Original Curves", "Aligned Curves"))) %>%
dplyr::left_join(tibble(
curve_id = 1:n,
membership = as.factor(obj$labels)
), by = "curve_id") %>%
dplyr::group_by(.data$curve_id, .data$dimension_id, .data$type) %>%
dplyr::slice(seq(
from = 1,
to = dplyr::n(),
by = round((dplyr::n() - 1) / number_of_displayed_points)
)) %>%
dplyr::ungroup()
df_mean <- center_values %>%
dplyr::left_join(center_grids, by = c("point_id", "curve_id")) %>%
dplyr::mutate(
membership = as.factor(.data$curve_id),
type = factor(.data$type, c("Original Curves", "Aligned Curves"))
) %>%
dplyr::group_by(.data$curve_id, .data$dimension_id, .data$type) %>%
dplyr::slice(seq(
from = 1,
to = dplyr::n(),
by = round((dplyr::n() - 1) / number_of_displayed_points)
)) %>%
dplyr::ungroup()
df %>%
ggplot(aes(.data$grid, .data$value, group = .data$curve_id, color = .data$membership)) +
geom_line(alpha = 0.3) +
geom_line(data = df_mean, size = 1.5) +
facet_wrap(vars(.data$type, .data$dimension_id), nrow = 2, scales = "free") +
theme_bw() +
theme(legend.position = "top") +
labs(
title = "Functional Data",
subtitle = paste("Class of warping functions:", toupper(obj$warping_method)),
x = "Grid",
y = "Values",
color = "Group membership"
)
}
plot_warping <- function(obj, number_of_displayed_points = 50) {
if (obj$warping_method == "affine")
df <- data_affine(obj, number_of_displayed_points)
else if (obj$warping_method == "dilation")
df <- data_dilation(obj, number_of_displayed_points)
else if (obj$warping_method == "shift")
df <- data_shift(obj, number_of_displayed_points)
else
stop("Unsupported warping family for display.")
df %>%
tidyr::unnest(cols = .data$x:.data$y) %>%
ggplot(aes(.data$x, .data$y, color = .data$membership, group = .data$id)) +
geom_line() +
theme_bw() +
theme(legend.position = "top") +
labs(
title = "Estimated Warping Functions",
subtitle = paste("Class of warping functions:", toupper(obj$warping_method)),
x = "Original grids",
y = "Warped grids",
color = "Group membership"
)
}
data_affine <- function(obj, number_of_displayed_points = 50) {
obj$parameters %>%
`colnames<-`(c("slope", "intercept")) %>%
as_tibble() %>%
dplyr::mutate(
x = purrr::map2(
.x = .data$slope,
.y = .data$intercept,
.f = ~ seq(0, 1, length.out = number_of_displayed_points)
),
y = purrr::map2(
.x = .data$slope,
.y = .data$intercept,
.f = ~ .x * seq(0, 1, length.out = number_of_displayed_points) + .y
),
id = 1:dplyr::n(),
membership = as.factor(obj$labels)
)
}
data_dilation <- function(obj, number_of_displayed_points = 50) {
obj$parameters %>%
`colnames<-`("slope") %>%
as_tibble() %>%
dplyr::mutate(
x = purrr::map(
.x = .data$slope,
.f = ~ seq(0, 1, length.out = number_of_displayed_points)
),
y = purrr::map(
.x = .data$slope,
.f = ~ .x * seq(0, 1, length.out = number_of_displayed_points)
),
id = 1:dplyr::n(),
membership = as.factor(obj$labels)
)
}
data_shift <- function(obj, number_of_displayed_points = 50) {
obj$parameters %>%
`colnames<-`("intercept") %>%
as_tibble() %>%
dplyr::mutate(
x = purrr::map(
.x = .data$intercept,
.f = ~ seq(0, 1, length.out = number_of_displayed_points)
),
y = purrr::map(
.x = .data$intercept,
.f = ~ seq(0, 1, length.out = number_of_displayed_points) + .x
),
id = 1:dplyr::n(),
membership = as.factor(obj$labels)
)
} |
plot.interactionfor <- function(x, numpairsquant=2, numpairsqual=2, ...) {
if(is.null(x$eim.univ) & is.null(x$eim.quant) & is.null(x$eim.qual)) {
cat("Nothing to plot, because the 'interactionfor' object does not feature EIM values.", "\n")
} else {
ps <- list()
count <- 1
if (!is.null(x$eim.univ)) {
datatempuniv <- data.frame(eimuniv=x$eim.univ.sorted)
ps[[count]] <- ggplot(data=datatempuniv, aes(x=1:nrow(datatempuniv), y=.data$eimuniv)) + theme_bw() + geom_point() +
labs(x="Index of variable", y="univariable EIM values") + ggplot2::ggtitle("univariable effects") +
scale_x_continuous(breaks= scales::pretty_breaks())
count <- count+1
}
if (!is.null(x$eim.quant)) {
datatempquant <- data.frame(eimquant=x$eim.quant.sorted)
ps[[count]] <- ggplot(data=datatempquant, aes(x=1:nrow(datatempquant), y=.data$eimquant)) + theme_bw() + geom_point() +
labs(x="Index of variable pair", y="quantitative EIM values") + ggplot2::ggtitle("quantitative interaction effects") +
scale_x_continuous(breaks= scales::pretty_breaks())
count <- count+1
}
if (!is.null(x$eim.qual)) {
datatempqual <- data.frame(eimqual=x$eim.qual.sorted)
ps[[count]] <- ggplot(data=datatempqual, aes(x=1:nrow(datatempqual), y=.data$eimqual)) + theme_bw() + geom_point() +
labs(x="Index of variable pair", y="qualitative EIM values") + ggplot2::ggtitle("qualitative interaction effects") +
scale_x_continuous(breaks= scales::pretty_breaks())
count <- count+1
}
p <- ggarrange(plotlist=ps, nrow=length(ps), ncol = 1)
p <- annotate_figure(p, top = text_grob(ifelse(length(ps)==1, "Distribution of EIM values", "Distributions of EIM values"), face = "bold", size = 18))
print(p)
if (!is.null(x$eim.quant)) {
ps <- plotEffects(intobj=x, type="quant", numpairs=numpairsquant, plotit=FALSE)
if(length(ps)==1) {
readline(prompt="Press [enter] for next plot.")
p <- annotate_figure(ps[[1]], top = text_grob("Pairs with top quantitative EIM values", face = "bold", size = 18))
print(p)
} else {
for(i in seq(along=ps)) {
readline(prompt="Press [enter] for next plot.")
p <- annotate_figure(ps[[i]], top = text_grob(paste("Pairs with top quantitative EIM values - ", as.roman(i), sep=""), face = "bold", size = 18))
print(p)
}
}
}
if (!is.null(x$eim.qual)) {
ps <- plotEffects(intobj=x, type="qual", numpairs=numpairsqual, plotit=FALSE)
if(length(ps)==1) {
readline(prompt="Press [enter] for next plot.")
p <- annotate_figure(ps[[1]], top = text_grob("Pairs with top qualitative EIM values", face = "bold", size = 18))
print(p)
} else {
for(i in seq(along=ps)) {
readline(prompt="Press [enter] for next plot.")
p <- annotate_figure(ps[[i]], top = text_grob(paste("Pairs with top qualitative EIM values - ", as.roman(i), sep=""), face = "bold", size = 18))
print(p)
}
}
}
}
} |
.onLoad <- function(...) {
fabletools::register_feature(feat_stl, c("stl", "trend", "seasonal", "decomposition"))
fabletools::register_feature(feat_acf, c("acf", "autocorrelation"))
fabletools::register_feature(feat_pacf, c("pacf", "autocorrelation"))
fabletools::register_feature(feat_intermittent, c("intermittent"))
fabletools::register_feature(guerrero, c("optimisation", "boxcox"))
fabletools::register_feature(unitroot_kpss, c("test", "unitroot"))
fabletools::register_feature(unitroot_pp, c("test", "unitroot"))
fabletools::register_feature(unitroot_ndiffs, c("test", "unitroot"))
fabletools::register_feature(unitroot_nsdiffs, c("test", "seasonal", "unitroot"))
fabletools::register_feature(box_pierce, c("test", "portmanteau"))
fabletools::register_feature(ljung_box, c("test", "portmanteau"))
fabletools::register_feature(var_tiled_var, c("lumpiness", "tile"))
fabletools::register_feature(var_tiled_mean, c("stability", "tile"))
fabletools::register_feature(shift_level_max, c("roll", "slide"))
fabletools::register_feature(shift_var_max, c("roll", "slide"))
fabletools::register_feature(shift_kl_max, c("roll", "slide"))
fabletools::register_feature(feat_spectral, c("spectral"))
fabletools::register_feature(n_crossing_points, "count")
fabletools::register_feature(n_flat_spots, c("count", "rle"))
fabletools::register_feature(coef_hurst, c("coefficients"))
fabletools::register_feature(stat_arch_lm, c("test"))
invisible()
}
register_s3_method <- function(pkg, generic, class, fun = NULL) {
stopifnot(is.character(pkg), length(pkg) == 1)
stopifnot(is.character(generic), length(generic) == 1)
stopifnot(is.character(class), length(class) == 1)
if (is.null(fun)) {
fun <- get(paste0(generic, ".", class), envir = parent.frame())
} else {
stopifnot(is.function(fun))
}
if (pkg %in% loadedNamespaces()) {
registerS3method(generic, class, fun, envir = asNamespace(pkg))
}
setHook(
packageEvent(pkg, "onLoad"),
function(...) {
registerS3method(generic, class, fun, envir = asNamespace(pkg))
}
)
} |
FEL_spectrum <- function(w.length,
k = photobiology::FEL.BN.9101.165,
fill = NA_real_) {
pws <- (length(k[["kb"]]) - 1):0
fill.selector <- w.length < 250 | w.length > 900
if (is.null(fill)) {
w.length <- w.length[!fill.selector]
fill.selector <- rep(FALSE, length(w.length))
indexes <- seq_along(w.length)
} else {
indexes <- which(w.length >= 250 & w.length <= 900)
}
s.e.irrad <- numeric(length(w.length))
for (i in indexes) {
s.e.irrad[i] <- sum((k[["kb"]] * w.length[i]^pws) * k[["kc"]] /
((w.length[i] * 1e-9)^5 * (exp(0.014388 / (w.length[i] * 1e-9) / k[["TK"]]) - 1)))
}
s.e.irrad[fill.selector] <- fill
out.data <- source_spct(w.length, s.e.irrad)
comment(out.data) <- paste("Fitted spectrum for:", comment(k))
return(out.data * 1e4)
} |
DHARMa.ecdf <- function (x)
{
x <- sort(x)
n <- length(x)
if (n < 1)
stop(paste("DHARMa.ecdf - length vector < 1", x))
vals <- unique(x)
rval <- approxfun(vals, cumsum(tabulate(match(x, vals)))/ (n +1),
method = "linear", yleft = 0, yright = 1, ties = "ordered")
class(rval) <- c("ecdf", "stepfun", class(rval))
assign("nobs", n, envir = environment(rval))
attr(rval, "call") <- sys.call()
rval
}
getQuantile <- function(simulations, observed, integerResponse, method = c("PIT", "traditional"), rotation = NULL){
method = match.arg(method)
n = length(observed)
if (nrow(simulations) != n) stop("DHARMa::getquantile: wrong dimension of simulations")
nSim = ncol(simulations)
if(method == "traditional"){
if(!is.null(rotation)) stop("rotation can only be used with PIT residuals")
if(integerResponse == F){
if(any(duplicated(observed))) message("Model family was recognized or set as continuous, but duplicate values were detected in the response. Consider if you are fitting an appropriate model.")
values = as.vector(simulations)[duplicated(as.vector(simulations))]
if(length(values) > 0){
if (all(values%%1==0)){
integerResponse = T
message("Model family was recognized or set as continuous, but duplicate values were detected in the simulation - changing to integer residuals (see ?simulateResiduals for details)")
} else {
message("Duplicate non-integer values found in the simulation. If this is because you are fitting a non-inter valued discrete response model, note that DHARMa does not perform appropriate randomization for such cases.")
}
}
}
scaledResiduals = rep(NA, n)
for (i in 1:n){
if(integerResponse == T){
scaledResiduals[i] <- DHARMa.ecdf(simulations[i,] + runif(nSim, -0.5, 0.5))(observed[i] + runif(1, -0.5, 0.5))
}else{
scaledResiduals[i] <- DHARMa.ecdf(simulations[i,])(observed[i])
}
}
} else {
if(!is.null(rotation)){
if(is.character(rotation) && rotation == "estimated"){
covar = Matrix::nearPD(cov(t(simulations)))$mat
L = t(as.matrix(Matrix::chol(covar)))
}
else if(is.matrix(rotation)) L <- t(chol(rotation))
else stop("DHARMa::getQuantile - wrong argument to rotation parameter")
observed <- solve(L, observed)
simulations = apply(simulations, 2, function(a) solve(L, a))
}
scaledResiduals = rep(NA, n)
for (i in 1:n){
minSim <- mean(simulations[i,] < observed[i])
maxSim <- mean(simulations[i,] <= observed[i])
if (minSim == maxSim) scaledResiduals[i] = minSim
else scaledResiduals[i] = runif(1, minSim, maxSim)
}
}
return(scaledResiduals)
}
checkDots <- function(name, default, ...) {
args <- list(...)
if(!name %in% names(args)) {
return(default)
} else {
return(args[[name]])
}
}
securityAssertion <- function(context = "Not provided", stop = F){
generalMessage = "Message from DHARMa: During the execution of a DHARMa function, some unexpected conditions occurred. Even if you didn't get an error, your results may not be reliable. Please check with the help if you use the functions as intended. If you think that the error is not on your side, I would be grateful if you could report the problem at https://github.com/florianhartig/DHARMa/issues \n\n Context:"
if (stop == F) warning(paste(generalMessage, context))
else stop(paste(generalMessage, context))
} |
library(rjson);
Tuple = setRefClass("Tuple",
fields = list(
id="character",
comp="character",
stream="character",
task="character",
input="list",
output="vector",
anchors="vector"
));
Tuple$methods(
parse = function(json=character) {
t = fromJSON(json);
.self$id=as.character(t$id);
.self$comp=as.character(t$comp);
.self$stream=as.character(t$stream);
.self$task=as.character(t$task);
.self$input=t$tuple;
.self$output=vector(mode="character");
.self$anchors=vector(mode="character");
.self;
}
);
Storm = setRefClass("Storm",
fields = list(
tuple = "Tuple",
setup = "list",
lambda="function"
)
);
Storm$methods(
initialize = function() {
.self$lambda = function(s) {
s$log(c("skipping tuple id='",s$tuple$id,"'"));
};
.self;
}
);
Storm$methods(
run = function() {
buf = "";
x.stdin = file("stdin");
open(x.stdin);
cat(paste('{"pid": ',Sys.getpid(),'}',"\nend\n",sep=""));
cat('{"command": "emit", "anchors": [], "tuple": ["bolt initializing"]}\nend\n');
while (TRUE) {
rl = as.character(readLines(con=x.stdin,n=1,warn=FALSE));
if (length(rl) == 0) {
close(x.stdin);
break;
}
if (rl == "end" || rl == "END") {
.self$process_json(buf);
buf = "";
}
else {
buf = paste(buf,rl,"\n",sep="");
}
}
}
);
Storm$methods(
process_json = function(json=character) {
t = NULL;
if (is.list(json)) {
t = fromJSON(unlist(json));
}
else {
t = fromJSON(json);
}
if (is.list(t)) {
if (!is.null(t$tuple)) {
.self$process_tuple(json);
}
else if (!is.null(t$pidDir)) {
.self$setup = t;
.self$process_setup(t);
}
else {
}
}
}
);
Storm$methods(
process_tuple = function(json=character) {
tt = Tuple$new();
tt$parse(json);
.self$tuple = tt;
.self$lambda(.self);
}
);
Storm$methods(
process_setup = function(json=character) {
file.create(paste(json$pidDir,"/",Sys.getpid(),sep=""))
}
);
Storm$methods(
log = function(msg=character) {
cat(c(
'{',
'"command": "log",',
'"msg": "',msg,'"',
'}\n',
'end\n'
),sep="");
}
);
Storm$methods(
ack = function(tuple=Tuple) {
cat(c(
'{\n',
'\t"command": "ack",\n',
'\t"id": "',tuple$id,'"\n',
'}\n',
'end\n'
),sep="");
}
);
Storm$methods(
fail = function(tuple=Tuple) {
cat(c(
'{',
'"command": "fail",',
'"id": "',tuple$id,'"',
'}\n',
'end\n'
),sep="")
}
);
Storm$methods(
emit = function(tuple=Tuple) {
t.prefix="[";
t.suffix="]";
a.prefix="[";
a.suffix="]";
cat(c(
'{',
'"command": "emit", ',
'"anchors": ',a.prefix,toJSON(tuple$id),a.suffix,', ',
'"tuple": ',toJSON(tuple$output),
'}\n',
'end\n'
),sep="");
}
); |
systemnoise <-
function(dim, nscan, type=c("gaussian","rician"), sigma, vee=1, template, verbose=TRUE){
if(length(dim)>3){
stop("Image space with more than three dimensions is not supported.")
}
if(missing(type)){
type="gaussian"
}
if(type=="gaussian"){
noise <- array(rnorm(prod(dim)*nscan, 0, sigma), dim=c(dim,nscan))
}else{
if(type=="rician"){
noise <- array(rrice(prod(dim)*nscan, vee=vee, sigma=sigma), dim=c(dim,nscan))
} else {
stop("Specified type of system noise is unknown. Type should be gaussian or rician.")
}
}
if(!missing(template)){
if(length(dim(template))>3){
stop("Template should be a 2D or 3D array.")
}
template.time <- array(rep(template,nscan), dim=c(dim,nscan))
ix <- which(template.time!=0)
noise[-ix] <- 0
}
return(noise)
} |
theme_update <- function(...) {
theme_set(theme_get() + theme(...))
}
theme_replace <- function(...) {
theme_set(theme_get() %+replace% theme(...))
}
is.theme <- function(x) inherits(x, "theme")
print.theme <- function(x, ...) utils::str(x)
theme <- function(..., complete = FALSE, validate = TRUE) {
elements <- list(...)
if (!is.null(elements$axis.ticks.margin)) {
warning("`axis.ticks.margin` is deprecated. Please set `margin` property ",
" of `axis.text` instead", call. = FALSE)
elements$axis.ticks.margin <- NULL
}
if (validate) {
mapply(validate_element, elements, names(elements))
}
structure(elements, class = c("theme", "gganimint"),
complete = complete, validate = validate)
}
plot_theme <- function(x) {
defaults(x$theme, theme_get())
}
.theme <- (function() {
theme <- theme_gray()
list(
get = function() theme,
set = function(new) {
missing <- setdiff(names(theme_gray()), names(new))
if (length(missing) > 0) {
warning("New theme missing the following elements: ",
paste(missing, collapse = ", "), call. = FALSE)
}
old <- theme
theme <<- new
invisible(old)
}
)
})()
theme_get <- .theme$get
theme_set <- .theme$set
"%+replace%" <- function(e1, e2) {
if (!is.theme(e1) || !is.theme(e2)) {
stop("%+replace% requires two theme objects", call. = FALSE)
}
e1[names(e2)] <- e2
e1
}
add_theme <- function(t1, t2, t2name) {
if (!is.theme(t2)) {
stop("Don't know how to add ", t2name, " to a theme object",
call. = FALSE)
}
for (item in names(t2)) {
x <- t1[[item]]
y <- t2[[item]]
if (is.null(x) || inherits(x, "element_blank")) {
x <- y
} else if (is.null(y) || is.character(y) || is.numeric(y) ||
is.logical(y) || inherits(y, "element_blank")) {
x <- y
} else {
idx <- !vapply(y, is.null, logical(1))
idx <- names(idx[idx])
x[idx] <- y[idx]
}
t1[item] <- list(x)
}
attr(t1, "complete") <- attr(t1, "complete") || attr(t2, "complete")
t1
}
update_theme <- function(oldtheme, newtheme) {
if (attr(newtheme, "complete"))
return(newtheme)
newitems <- !names(newtheme) %in% names(oldtheme)
newitem_names <- names(newtheme)[newitems]
oldtheme[newitem_names] <- theme_get()[newitem_names]
old.validate <- isTRUE(attr(oldtheme, "validate"))
new.validate <- isTRUE(attr(newtheme, "validate"))
oldtheme <- do.call(theme, c(oldtheme,
complete = isTRUE(attr(oldtheme, "complete")),
validate = old.validate & new.validate))
oldtheme + newtheme
}
calc_element <- function(element, theme, verbose = FALSE) {
if (verbose) message(element, " --> ", appendLF = FALSE)
if (inherits(theme[[element]], "element_blank")) {
if (verbose) message("element_blank (no inheritance)")
return(theme[[element]])
}
if (!is.null(theme[[element]]) &&
!inherits(theme[[element]], .element_tree[[element]]$class)) {
stop(element, " should have class ", .element_tree[[element]]$class)
}
pnames <- .element_tree[[element]]$inherit
if (is.null(pnames)) {
nullprops <- vapply(theme[[element]], is.null, logical(1))
if (any(nullprops)) {
stop("Theme element '", element, "' has NULL property: ",
paste(names(nullprops)[nullprops], collapse = ", "))
}
if (verbose) message("nothing (top level)")
return(theme[[element]])
}
if (verbose) message(paste(pnames, collapse = ", "))
parents <- lapply(pnames, calc_element, theme, verbose)
Reduce(combine_elements, parents, theme[[element]])
}
combine_elements <- function(e1, e2) {
if (is.null(e2)) return(e1)
if (is.null(e1) || inherits(e2, "element_blank")) return(e2)
n <- vapply(e1[names(e2)], is.null, logical(1))
e1[n] <- e2[n]
if (is.rel(e1$size)) {
e1$size <- e2$size * unclass(e1$size)
}
e1
} |
step_num2factor <-
function(recipe,
...,
role = NA,
transform = function(x) x,
trained = FALSE,
levels,
ordered = FALSE,
skip = FALSE,
id = rand_id("num2factor")) {
if (!is_tune(ordered) & !is_varying(ordered)) {
if (!is.logical(ordered) || length(ordered) != 1)
rlang::abort("`ordered` should be a single logical variable")
}
if (rlang::is_missing(levels) || !is.character(levels)) {
rlang::abort("Please provide a character vector of appropriate length for `levels`.")
}
add_step(
recipe,
step_num2factor_new(
terms = ellipse_check(...),
role = role,
transform = transform,
trained = trained,
levels = levels,
ordered = ordered,
skip = skip,
id = id
)
)
}
step_num2factor_new <-
function(terms, role, transform, trained, levels, ordered, skip, id) {
step(
subclass = "num2factor",
terms = terms,
role = role,
transform = transform,
trained = trained,
levels = levels,
ordered = ordered,
skip = skip,
id = id
)
}
get_ord_lvls_num <- function(x, foo)
sort(unique(as.character(foo(x))))
prep.step_num2factor <- function(x, training, info = NULL, ...) {
col_names <- recipes_eval_select(x$terms, training, info)
check_type(training[, col_names])
res <- lapply(training[, col_names], get_ord_lvls_num, foo = x$transform)
res <- c(res, ..levels = list(x$levels))
ord <- rep(x$ordered, length(col_names))
names(ord) <- col_names
step_num2factor_new(
terms = x$terms,
role = x$role,
transform = x$transform,
trained = TRUE,
levels = res,
ordered = ord,
skip = x$skip,
id = x$id
)
}
make_factor_num <- function(x, lvl, ord, foo) {
y <- foo(x)
if (!is.integer(y)) {
y <- as.integer(y)
}
factor(lvl[y], levels = lvl, ordered = ord)
}
bake.step_num2factor <- function(object, new_data, ...) {
col_names <- names(object$ordered)
lvls <- object$levels[names(object$levels) == "..levels"]
object$levels <- object$levels[names(object$levels) != "..levels"]
new_data[, col_names] <-
map_df(new_data[, col_names],
make_factor_num,
lvl = lvls[[1]],
ord = object$ordered[1],
foo = object$transform)
if (!is_tibble(new_data))
new_data <- as_tibble(new_data)
new_data
}
print.step_num2factor <-
function(x, width = max(20, options()$width - 30), ...) {
cat("Factor variables from ")
printer(names(x$ordered), x$terms, x$trained, width = width)
invisible(x)
}
tidy.step_num2factor <- function(x, ...) {
term_names <- sel2char(x$terms)
p <- length(term_names)
if (is_trained(x)) {
res <- tibble(terms = term_names,
ordered = rep(x$ordered, p))
} else {
res <- tibble(terms = term_names,
ordered = rep(x$ordered, p))
}
res$id <- x$id
res
} |
expect_inherits(availability(example_isolates), "data.frame") |
ISOAbstractLogicalConsistency <- R6Class("ISOAbstractLogicalConsistency",
inherit = ISODataQualityAbstractElement,
private = list(
xmlElement = "AbstractDQ_LogicalConsistency",
xmlNamespacePrefix = "GMD"
),
public = list()
)
ISOTopologicalConsistency <- R6Class("ISOTopologicalConsistency",
inherit = ISOAbstractLogicalConsistency,
private = list(
xmlElement = "DQ_TopologicalConsistency",
xmlNamespacePrefix = "GMD"
),
public = list()
)
ISOFormatConsistency <- R6Class("ISOFormatConsistency",
inherit = ISOAbstractLogicalConsistency,
private = list(
xmlElement = "DQ_FormatConsistency",
xmlNamespacePrefix = "GMD"
),
public = list()
)
ISODomainConsistency <- R6Class("ISODomainConsistency",
inherit = ISOAbstractLogicalConsistency,
private = list(
xmlElement = "DQ_DomainConsistency",
xmlNamespacePrefix = "GMD"
),
public = list()
)
ISOConceptualConsistency <- R6Class("ISOConceptualConsistency",
inherit = ISOAbstractLogicalConsistency,
private = list(
xmlElement = "DQ_ConceptualConsistency",
xmlNamespacePrefix = "GMD"
),
public = list()
) |
anyLib <- function(pkg, force = FALSE, autoUpdate = TRUE, lib = .libPaths()[1],
loadLib = .libPaths(), source = FALSE){
opkg <- sub("_[0-9][.][0-9][.][0-9].tar.gz$", "",
sapply(pkg, function(y) lapply(strsplit(y, "/"),
function(x) x[length(x)])))
if (inherits(pkg, "character")) {
pkg <- as.list(pkg)
} else if (!inherits(pkg, "list")) {
stop("pkg has to be a package name or a list of packages names")
}
if (any(source) == TRUE) {
lapply(pkg[source], function(p){
utils::chooseCRANmirror(graphics = FALSE, 1)
utils::install.packages(p, repos = NULL, type = "source",
dependencies = TRUE, lib = lib)
})
}
pkg <- pkg[!source]
if (length(pkg) > 0) {
is.github <- sapply(pkg, function(p) !identical(grep("/", p), integer(0)))
githubP <- pkg[is.github]
notGithubP <- pkg[!is.github]
is.installedGithubP <- sapply(githubP, function(p){
mAndP <- strsplit(unlist(p), "/")[[1]]
mAndP[2] %in% utils::installed.packages(lib.loc = loadLib)[, "Package"]
})
new.pkg <- notGithubP[!(notGithubP %in%
utils::installed.packages(
lib.loc = loadLib)[, "Package"])]
if (force == TRUE) new.pkg <- notGithubP
if (length(new.pkg)) {
for (p in new.pkg) {
utils::chooseCRANmirror(graphics = FALSE, 1)
base::suppressWarnings(utils::install.packages(
p, dependencies = TRUE, lib = lib))
}
}
new.pkg <- notGithubP[!(notGithubP %in% utils::installed.packages(
lib.loc = loadLib)[, "Package"])]
if (force == TRUE) {
new.pkg <- pkg[!sapply(notGithubP,
function(p)
length(grep(
p, utils::available.packages()[,1])))]
}
if (length(new.pkg)) {
try(BiocManager::install(unlist(new.pkg), ask = FALSE,
update = autoUpdate,
lib = lib))
}
if (force == FALSE) {
for (p in githubP[!is.installedGithubP])
try(withr::with_libpaths(new = lib, devtools::install_github(p)))
} else if (force == TRUE) {
for (p in githubP)
try(withr::with_libpaths(new = lib,
devtools::install_github(p,
force = force)))
}
if (!identical(githubP, list())) {
pkg[is.github] <- sapply(strsplit(unlist(
pkg[is.github]), "/"), function(x) x[[2]])
}
}
sapply(opkg, require, character.only = TRUE, lib.loc = loadLib)
} |
library(signs)
x <- seq(-1, 1)
test_that(
"the basics work",
{
expect_equal(
signs(x, accuracy = 1),
c("\u22121", "0", "1")
)
expect_equal(
signs(x, accuracy = 1, scale = 1, format = scales::percent),
c("\u22121%", "0%", "1%")
)
expect_equal(
signs(x, accuracy = 1, add_plusses = TRUE),
c("\u22121", "0", "+1")
)
expect_equal(
signs(x, accuracy = 1, label_at_zero = "blank"),
c("\u22121", "", "1")
)
expect_equal(
signs(x, accuracy = 1, label_at_zero = "symbol"),
c("\u22121", "\u00b10", "1")
)
expect_equal(
signs(x, accuracy = .1, scale = .1, trim_leading_zeros = TRUE),
c("\u2212.1", ".0", ".1")
)
}
)
test_that(
"errors work",
{
expect_error(
signs(as.character(x)),
"`x` should be a numeric vector."
)
expect_error(
signs(x, format = "goobers"),
cat(
"`format` should be a function that returns a character vector,",
"such as `scales::number` or `as.character`.",
"Consider setting a default with",
"`options(signs.format = your_function)`."
)
)
expect_error(
signs(x, format = exp),
cat(
"`format` should be a function that returns a character vector,",
"such as `scales::number` or `as.character`.",
"Consider setting a default with",
"`options(signs.format = your_function)`."
)
)
expect_error(
signs(x, add_plusses = "TRUE"),
"`add_plusses` should be a logical vector of length 1."
)
expect_error(
signs(x, add_plusses = c(TRUE, FALSE)),
"`add_plusses` should be a logical vector of length 1."
)
expect_error(
signs(x, trim_leading_zeros = "TRUE"),
"`trim_leading_zeros` should be a logical vector of length 1."
)
expect_error(
signs(x, trim_leading_zeros = c(TRUE, FALSE)),
"`trim_leading_zeros` should be a logical vector of length 1."
)
expect_error(
signs(x, label_at_zero = TRUE),
"`label_at_zero` should be either 'none', 'blank', or 'symbol'."
)
expect_error(
signs(x, label_at_zero = c("none", "blank")),
"`label_at_zero` should be either 'none', 'blank', or 'symbol'."
)
expect_error(
signs(x, label_at_zero = "goober"),
"`label_at_zero` should be either 'none', 'blank', or 'symbol'."
)
}
)
test_that(
"formatted as zero counts as zero",
{
expect_equal(
signs(x, accuracy = 1, scale = .1, label_at_zero = "none"),
c("0", "0", "0")
)
expect_equal(
signs(x, accuracy = 1, scale = .1, label_at_zero = "blank"),
c("", "", "")
)
expect_equal(
signs(x, accuracy = 1, scale = .1, label_at_zero = "symbol"),
c("\u00b10", "\u00b10", "\u00b10")
)
}
)
test_that(
"scientific notation works",
{
expect_equal(
signs(x, accuracy = 1, scale = 1e-3, format = scales::scientific),
c("\u22121e\u221203", "0e+00", "1e\u221203")
)
expect_equal(
signs(
x,
accuracy = 1,
scale = 1e+3,
format = scales::scientific,
add_plusses = TRUE
),
c("\u22121e+03", "0e+00", "+1e+03")
)
}
)
test_that(
"janky scientific notation works",
{
expect_equal(
signs(x, accuracy = 1, suffix = "e+03", label_at_zero = "none"),
c("\u22121e+03", "0e+03", "1e+03")
)
expect_equal(
signs(x, accuracy = 1, suffix = "e+03", label_at_zero = "blank"),
c("\u22121e+03", "", "1e+03")
)
expect_equal(
signs(x, accuracy = 1, suffix = "e+03", label_at_zero = "symbol"),
c("\u22121e+03", "\u00b10e+03", "1e+03")
)
}
) |
library(quanteda)
context("double reinert classification")
mini_corpus <- head(data_corpus_inaugural, n = 2)
mini_corpus <- split_segments(mini_corpus, 5)
dtm <- dfm(tokens(mini_corpus, remove_punct = TRUE), tolower = TRUE)
dtm <- dfm_remove(dtm, stopwords("en"))
dtm <- dfm_wordstem(dtm, language = "english")
dtm <- dfm_trim(dtm, min_termfreq = 3)
res1 <- rainette(dtm, k = 5, min_segment_size = 2, min_split_members = 3)
res2 <- rainette(dtm, k = 5, min_segment_size = 3, min_split_members = 3)
res12 <- rainette2(dtm, max_k = 5, min_segment_size1 = 2, min_segment_size2 = 3, min_members = 3)
res <- rainette2(res1, res2, min_members = 2)
test_that("compute_chi2 is ok", {
tab <- matrix(c(45, 121 - 45, 257 - 45, 1213 - 121 - 257 +45), nrow = 2)
expect_equal(rainette:::compute_chi2(45, 121, 257, 1213),
chisq.test(tab)$statistic)
tab <- matrix(c(0, 12, 25, 121 - 12 - 25), nrow = 2)
expect_equal(rainette:::compute_chi2(0, 12, 25, 121),
suppressWarnings(-chisq.test(tab)$statistic))
})
test_that("get_groups is ok", {
expect_equal(dim(rainette:::get_groups(res1)), c(316, 4))
expect_equal(substr(rainette:::get_groups(res1)[[2]],3,3), as.character(res1$uce_groups[[2]]))
expect_equal(substr(rainette:::get_groups(res1)[[2]],1,2), rep("2.", length(res1$group)))
})
test_that("classes_crosstab is ok", {
g1 <- tibble(c(1,1,2,2), c(1,1,2,3))
g2 <- tibble(c(1,2,1,2), c(3,1,2,1))
colnames(g1) <- 1:2
colnames(g2) <- 1:2
n_tot <- 4
tab <- rainette:::classes_crosstab(g1, g2, n_tot)
expect_equal(nrow(tab), 25)
expect_equal(colnames(tab), c("g1", "g2", "n_both", "n1", "n2", "level1", "level2", "chi2"))
tmp <- tab %>% dplyr::filter(level1 == 2, level2 == 2, g1 == 2, g2 == 2)
expect_equal(tmp$n_both, 1)
expect_equal(tmp$n1, 1)
expect_equal(tmp$n2, 1)
expect_equal(tmp$chi2, unname(rainette:::compute_chi2(tmp$n_both, tmp$n1, tmp$n2, n_tot)))
})
test_that("filter_crosstab is ok", {
g1 <- tibble(c(1,1,1,1,2), c(1,1,2,3,3))
g2 <- tibble(c(1,1,1,1,2), c(3,1,3,1,2))
colnames(g1) <- 1:2
colnames(g2) <- 1:2
n_tot <- 5
tab <- rainette:::classes_crosstab(g1, g2, n_tot)
ftab <- rainette:::filter_crosstab(tab, g1, g2, min_members = 2, min_chi2 = 0.5)
expect_equal(nrow(ftab), 1)
expect_equal(ftab$g1, 1)
expect_equal(ftab$g2, 1)
expect_equal(ftab$n_both, 4)
expect_equal(ftab$interclass, "1x1")
expect_equal(ftab$chi2,
suppressWarnings(unname(chisq.test(matrix(c(4,0,0,1), nrow=2))$statistic)))
expect_equal(ftab$members, list(1:4))
})
test_that("cross_sizes is ok", {
tab <- tibble(interclass = c("1.1x1.1", "1.2x1.1", "2.1x2.2", "2.1x1.1"),
members = list(c(1,2,3), c(4,5,6), c(1,2), 5))
sizes <- rainette:::cross_sizes(tab)
expect_equal(sizes, structure(c(1, 1, 1, 1, 0, 1, 1, 1, 2, 0, 1, 1, 0, 1, 0, 1), .Dim = c(4L,
4L), .Dimnames = list(c("1.1x1.1", "1.2x1.1", "2.1x2.2", "2.1x1.1"
), c("1.1x1.1", "1.2x1.1", "2.1x2.2", "2.1x1.1"))))
})
test_that("next_partitions is ok", {
tab <- tibble(interclass = c("1.1x1.1", "1.2x1.1", "2.1x2.2", "2.1x1.1"),
members = list(c(1,2,3), c(4,5,6), c(1,2), 7))
sizes <- rainette:::cross_sizes(tab)
partitions <- list(colnames(sizes))
partitions[[2]] <- rainette:::next_partitions(partitions, sizes)
expect_equal(partitions[[2]], list(c("1.1x1.1", "1.2x1.1"), c("1.1x1.1", "2.1x1.1"), c("1.2x1.1",
"2.1x2.2"), c("1.2x1.1", "2.1x1.1"), c("2.1x2.2", "2.1x1.1")))
partitions[[3]] <- rainette:::next_partitions(partitions, sizes)
expect_equal(partitions[[3]], list(c("1.1x1.1", "1.2x1.1", "2.1x1.1"), c("1.2x1.1", "2.1x2.2",
"2.1x1.1")))
expect_equal(rainette:::next_partitions(partitions, sizes), NULL)
})
test_that("get_optimal_partitions is ok", {
valid <- tibble(interclass = c("1x1", "2x2", "3x3", "4x4"),
n_both = c(3, 3, 2, 1),
chi2 = c(4, 5, 10, 4),
members = list(c(1,2,3), c(4,5,6), c(1,2), 7), stringsAsFactors = FALSE)
partitions <- list(
list(c("1x1", "2x2"), c("2x2", "3x3"), c("1x1", "4x4")),
list(c("1x1", "2x2", "4x4")))
n_tot <- 7
res <- rainette:::get_optimal_partitions(partitions, valid, n_tot)
tmp <- res[res$k == 2,]
expect_equal(tmp$clusters, list(c("1x1", "2x2"), c("2x2","3x3")))
expect_equal(tmp$chi2, c(9, 15))
expect_equal(tmp$n, c(6, 5))
expect_equal(tmp$groups, list(c(1,1,1,2,2,2,NA),c(2,2,NA,1,1,1,NA)))
tmp <- res[res$k == 3,]
expect_equal(tmp$clusters, list(c("1x1", "2x2", "4x4")))
expect_equal(tmp$chi2, 13)
expect_equal(tmp$n, 7)
expect_equal(tmp$groups, list(c(1,1,1,2,2,2,3)))
})
test_that("rainette2 gives the same result on dtm and on two clustering results", {
expect_equal(res[,c("k", "chi2", "n")], res12[,c("k", "chi2", "n")])
expect_equal(res$groups, res12$groups)
expect_equal(res$clusters, res12$clusters)
})
test_that("rainette2 is ok when stopping before max_k", {
res1 <- rainette(dtm, k = 4, min_segment_size = 2, min_split_members = 30)
res2 <- rainette(dtm, k = 4, min_segment_size = 3, min_split_members = 30)
expect_message(res <- rainette2(res1, res2, max_k = 4, min_members = 50),
"^! No more partitions found, stopping at k=2")
expect_equal(max(res$k), 2)
}) |
ver_order <- function(x) {
version_components <- strsplit(x, "[^\\w]+", perl = TRUE)
Reduce(
function(list_order, position) {
nth_components <- vapply(
version_components[list_order], `[`, FUN.VALUE = character(1), position
)
empty_components_indices <- which(is.na(nth_components))
other_components_indices <- which(!is.na(nth_components))
nth_components <- nth_components[other_components_indices]
initial_number_match <- regexpr("^\\d+", nth_components)
initial_number <- as.numeric(
substring(nth_components, 1, attr(
initial_number_match, "match.length", exact = TRUE)
)
)
additional_code <- substring(nth_components, 1 + attr(
initial_number_match, "match.length", exact = TRUE)
)
code_order <- order(additional_code, na.last = TRUE)
list_order[
c(empty_components_indices,
other_components_indices[code_order][order(initial_number[code_order], na.last = TRUE)])
]
},
rev(seq_len(max(lengths(version_components)))),
init = seq_along(version_components)
)
}
ver_sort <- function(x) {
x[ver_order(x)]
} |
expected <- eval(parse(text="NULL"));
test(id=0, code={
argv <- eval(parse(text="list(\"Error in as.POSIXlt.character(x, tz, ...) : \\n character string is not in a standard unambiguous format\\n\")"));
.Internal(seterrmessage(argv[[1]]));
}, o=expected); |
TaxonOut <- function(name, lBound = 0.0, hBound = 1.0E100, takeOut,
writeTrees = T) {
opar <-par(no.readonly=TRUE)
on.exit(par(opar))
inFileName <- paste0(name, '.xml')
inFile <- readLines(inFileName)
versionLine <- readLines(inFileName,n=1)
ver <- grepl(pattern = 'version=\"1.0', x = versionLine)
ver2 <- grepl(pattern = 'version=\"2.', x = versionLine)
ver1 = F
if (ver == T & ver2 == F) {ver1 = T}
if (ver1 == T) {
endTaxaLine <- grep(pattern = "</taxa>", x = inFile, value = F)
taxaLine <- grep(pattern = "<taxon id=", x = inFile, value = T)
taxaLinePosition <- grep(pattern="<taxon id=", x = inFile, value = F)
taxaLine <- unlist(strsplit(taxaLine, "\""))
taxa <- taxaLine[c (F, T, F)]
numberTaxa <- length(taxa)
if (length(taxa) == 0) {stop(
"No date info found, check BEAST input files")}
if (is.numeric(takeOut) == F) {
valueTakeOut <- match(takeOut, taxa)
if (is.na (valueTakeOut)) {stop("Taxon name not found, check spelling")}
takeOut <- valueTakeOut
}
if (numberTaxa < takeOut) {stop("Error in taxon number")}
matchFileName <- grep(pattern = "fileName", x = inFile, value = T)
matchFileNamePosition <- grep(pattern = "fileName", x = inFile, value = F)
newFile <- inFile
taxon <- taxa[takeOut]
add1 <- grep(pattern = "</taxa>", x = newFile, value = F)
newFile [add1] <- paste0("\t</taxa>\n\n","\t<taxa id=\"leave_out\">\n",
"\t\t<taxon idref=\"",taxon,"\"/>\n\t</taxa>")
add2 <- grep(pattern = "</treeModel>", x = newFile, value = F)
newFile [add2] <- paste0(
"\n\t\t<!-- START Tip date sampling\t\t\t\t\t\t\t\t\t\t\t-->
\n\t\t<leafHeight taxon=\"",taxon,"\">\n\t\t\t<parameter id=\"age(",
taxon,")\"/>\n\t\t</leafHeight>
\n\t\t<!-- END Tip date sampling\t\t\t\t\t\t\t\t\t\t\t\t-->
\n\t</treeModel>","\n\n\t<!-- Taxon Sets\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t-->
\t<tmrcaStatistic id=\"tmrca(leave_out)\" includeStem=\"false\">
\t\t<mrca>\n\t\t\t<taxa idref=\"leave_out\"/>\n\t\t</mrca>
\t\t<treeModel idref=\"treeModel\"/>\n\t</tmrcaStatistic>")
add34 <- grep(pattern = "</operators>", x = newFile, value = F)
newFile [add34] <- paste0(
"\t\t<scaleOperator scaleFactor=\"0.9\" weight=\"1\">
\t\t\t<parameter idref=\"age(",taxon,")\"/>\n\t\t</scaleOperator>
\t</operators>")
add5 <- grep(pattern = "<prior id=\"prior\">", x = newFile, value = F)
newFile [add5] <- paste0(
"\t\t\t<prior id=\"prior\">
\t\t\t<uniformPrior lower=\"", lBound, "\" upper=\"",hBound,"\">
\t\t\t\t\t<parameter idref=\"age(",taxon,
")\"/>\n\t\t\t\t</uniformPrior>")
add6 <- grep(pattern = "<log id=\"fileLog\"", x = newFile, value = F)
keep6 <- newFile[add6 + 1]
newFile [add6 + 1] <- paste0(
"\n\t\t\t<parameter idref=\"age(",taxon,")\"/>\n",keep6)
log = paste0("\\.log")
matchLog <- grep(pattern = log, x = newFile, value = T)
matchLogPosition <- grep(pattern = log, x = newFile, value = F)
logRep <- paste0("\\.Taxon", takeOut, log)
if (length(matchLogPosition) != 0) {
newFile [matchLogPosition] <- gsub(log, logRep, matchLog)}
trees = paste0("\\.trees")
matchTrees <- grep(pattern = trees, x = newFile, value = T)
matchTreesPosition <- grep(pattern = trees, x = newFile, value = F)
treesRep <- paste0("\\.Taxon", takeOut, trees)
if (length(matchTreesPosition) != 0) {
newFile [matchTreesPosition] <- gsub(trees, treesRep, matchTrees)}
csv = paste0("\\.csv")
matchCsv <- grep(pattern = csv, x = newFile, value = T)
matchCsvPosition <- grep(pattern = csv, x = newFile, value = F)
csvRep <- paste0("\\.Taxon", takeOut, csv)
if (length(matchCsvPosition) != 0) {
newFile [matchCsvPosition] <- gsub(csv, csvRep, matchCsv)}
ops = paste0("\\.ops")
matchOps <- grep(pattern = ops, x = newFile, value = T)
matchOpsPosition <- grep(pattern = ops, x = newFile, value = F)
opsRep <- paste0("\\.Taxon", takeOut, ops)
if (length(matchOpsPosition) != 0) {
newFile [matchOpsPosition] <- gsub(ops, opsRep, matchOps)}
if (writeTrees == F) {
logA <- grep(pattern = "<logTree id=", x = newFile, value = T)
logAn <- grep(pattern = "<logTree id=", x = newFile, value = F)
newFile [logAn] <- paste0("\t\t<!-- \n", logA)
logB <- grep(pattern = "</logTree>", x = newFile, value = T)
logBn <- grep(pattern = "</logTree>", x = newFile, value = F)
newFile [logBn] <- paste0(logB, "\n", " \t\t -->")
}
out <- paste0(name, ".Taxon.", takeOut, ".xml")
cat (newFile, file = out, sep = "\n")
cat ("Taxon", takeOut, "processed \n")
}
if (ver2 == T) {
linearDates=F
numberTaxa <- length(grep('taxon=', inFile))
line <- grep(pattern = 'traitname=\"date|traitname=\'date', x = inFile)
linearDates <- grepl(pattern = 'value=', inFile[line])
if (linearDates == T) {
dateLine <- inFile[line]
step1 <- gsub('\">','',strsplit(dateLine, 'value=\"')[[1]][2])
step2 <- unlist(strsplit(step1, ","))
numberDates <- length(step2)
date <- unlist(strsplit(step2, "="))
dateHap <- date[c(T, F)]
dateHap <- dateHap[1: numberDates]
dateValues <- date[c(F, T)]
dateValues <- gsub(",$", "", dateValues)
if (is.numeric(takeOut) == F) {
valueTakeOut <- match(takeOut, dateHap)
if (is.na (valueTakeOut)) {stop("Taxon name not found, check spelling")}
takeOut <- valueTakeOut
}
if (numberTaxa < takeOut) {stop("Error in taxon number")}
dateValues <- gsub(",$", "", dateValues)
newFile <- inFile
taxon <- dateHap[takeOut]
lineTrees <- grep(pattern ="@Tree.t:", x = newFile)
lineTree <- tail(lineTrees, 1)
treeLine <- newFile[lineTree]
treePart <- tail(unlist(strsplit(treeLine, "@Tree.t:")), 1)
treeName <- head(unlist(strsplit(treePart, "\"")), 1)
addLine1 <- grep(pattern = "</prior>", x = newFile)
add1 <- tail(addLine1, n = 1)
temp1 <- newFile[add1]
newFile [add1] <- paste0(temp1,"\n","\t\t\t<distribution id=",
"\"LOOCV.prior\" spec=\"beast.math.",
"distributions.MRCAPrior\"",
" tree=\"@Tree.t:", treeName,
"\">\n","\t\t\t\t<taxonset id=\"",
"LOOCV\" spec=\"TaxonSet\">\n","\t\t\t\t\t",
"<taxon id=\"", taxon,"\" spec=\"Taxon\"/>\n",
"\t\t\t\t</taxonset>\n",
"\t\t\t\t<Uniform id=\"Uniform.",
"01\" name=\"distr\" upper=\"Infinity\"/>\n",
"\t\t\t</distribution>")
addLine2 <- grep(pattern = "</operator>", x = newFile)
add2 <- tail(addLine2, n = 1)
temp2 <- newFile[add2]
newFile [add2] <- paste0(temp2,"\n\n","\t<operator id=\"TipDatesRandom",
"Walker\" windowSize=\"1\" spec=\"TipDatesRandomWalker",
"\" taxonset=\"@LOOCV\" tree=\"@Tree.t:",
treeName,"\" weight=\"1.0\"/>")
add6 <- grep(pattern = "<logger id=\"tracelog\" ", x = newFile, value = F)
keep6 <- newFile[add6]
newFile [add6] <- paste0(keep6,"\n\t\t<log idref=\"LOOCV.prior\"/>")
log = paste0("\\.log")
matchLog <- grep(pattern = log, x = newFile, value = T)
matchLogPosition <- grep(pattern = log, x = newFile, value = F)
logRep <- paste0("\\.Taxon", takeOut, log)
if (length(matchLogPosition) != 0) {
newFile [matchLogPosition] <- gsub(log, logRep, matchLog)}
trees = paste0("\\.trees")
matchTrees <- grep(pattern = trees, x = newFile, value = T)
matchTreesPosition <- grep(pattern = trees, x = newFile, value = F)
treesRep <- paste0("\\.Taxon", takeOut, trees)
if (length(matchTreesPosition) != 0) {
newFile [matchTreesPosition] <- gsub(trees, treesRep, matchTrees)}
if (writeTrees == F) {
logA <- grep(pattern = "\\.trees", x = newFile, value = T)
logAn <- grep(pattern = "\\.trees", x = newFile, value = F)
newFile [logAn] <- paste0("\t<!-- \n ", logA)
ctr <- 0
repeat {
ctr <- ctr + 1
ctr2 <- 0
ctr2 <- logAn + ctr
temp <- grep(pattern = "</logger>", newFile[ctr2], value = F)
temp <- length(temp)
if (temp != 0) break
if (ctr == 100) stop("Error, check files, no tree block found")
}
newFile [ctr2] <- paste0("\t</logger>", "\n", "\t-->")
}
out <- paste0(name, ".Taxon", takeOut, ".xml")
cat (newFile, file = out, sep = "\n")
cat ("Taxon", takeOut, "processed \n")
}
if (linearDates == F) {
numberTaxa <- length(grep("taxon=", inFile))
line <- grep(pattern = "traitname=\"date|traitname=\'date", x = inFile)
line <- line + 1
if (length(line) == 0) {stop(
"No date info found, check BEAST input file")}
datePositions = c()
repeat {
if (length(grep("value=", inFile[line])) > 0) line <- line + 1
if (length(grep("alignment", inFile[line])) > 0) break
if (length(grep("=", inFile[line])) > 0) {
datePositions <- c(datePositions, line)}
line <- line + 1
}
numberDates <- length(datePositions)
dateLines <- inFile[datePositions]
dateLines <- trimws(dateLines)
date <- unlist(strsplit(dateLines, "="))
dateHap <- date[c(T, F)]
dateHap <- dateHap[1: numberDates]
dateValues <- date[c(F, T)]
lastLine <- length(grep("<taxa", dateValues))
if (is.numeric(takeOut) == F) {
valueTakeOut <- match(takeOut, dateHap)
if (is.na (valueTakeOut)) {stop("Taxon name not found, check spelling")}
takeOut <- valueTakeOut
}
if (numberTaxa < takeOut) {stop("Error in taxon number")}
if (lastLine == 1){
lastDate <- tail(dateValues, 2)
lastDate <- unlist(strsplit(lastDate, " "))
lastDate <- head(lastDate, 1)
dateValues <- head(dateValues, numberTaxa-1)
dateValues <- c(dateValues, lastDate)
}
dateValues <- gsub(",$", "", dateValues)
newFile <- inFile
taxon <- dateHap[takeOut]
lineTrees <- grep(pattern ="@Tree.t:", x = newFile)
lineTree <- tail(lineTrees, 1)
treeLine <- newFile[lineTree]
treePart <- tail(unlist(strsplit(treeLine, "@Tree.t:")), 1)
treeName <- head(unlist(strsplit(treePart, "\"")), 1)
addLine1 <- grep(pattern = "</prior>", x = newFile)
add1 <- tail(addLine1, n = 1)
temp1 <- newFile[add1]
newFile [add1] <- paste0(temp1,"\n","\t\t\t<distribution id=",
"\"LOOCV.prior\" spec=\"beast.math.",
"distributions.MRCAPrior\"",
" tree=\"@Tree.t:", treeName,
"\">\n","\t\t\t\t<taxonset id=\"",
"LOOCV\" spec=\"TaxonSet\">\n","\t\t\t\t\t",
"<taxon id=\"", taxon,"\" spec=\"Taxon\"/>\n",
"\t\t\t\t</taxonset>\n",
"\t\t\t\t<Uniform id=\"Uniform.",
"01\" name=\"distr\" upper=\"Infinity\"/>\n",
"\t\t\t</distribution>")
addLine2 <- grep(pattern = "</operator>", x = newFile)
add2 <- tail(addLine2, n = 1)
temp2 <- newFile[add2]
newFile [add2] <- paste0(temp2,"\n\n","\t<operator id=\"TipDatesRandom",
"Walker\" windowSize=\"1\" spec=\"TipDatesRandomWalker",
"\" taxonset=\"@LOOCV\" tree=\"@Tree.t:",
treeName,"\" weight=\"1.0\"/>")
add6 <- grep(pattern = "<logger id=\"tracelog\" ", x = newFile, value = F)
keep6 <- newFile[add6]
newFile [add6] <- paste0(keep6,"\n\t\t<log idref=\"LOOCV.prior\"/>")
log = paste0("\\.log")
matchLog <- grep(pattern = log, x = newFile, value = T)
matchLogPosition <- grep(pattern = log, x = newFile, value = F)
logRep <- paste0("\\.Taxon", takeOut, log)
if (length(matchLogPosition) != 0) {
newFile [matchLogPosition] <- gsub(log, logRep, matchLog)}
trees = paste0("\\.trees")
matchTrees <- grep(pattern = trees, x = newFile, value = T)
matchTreesPosition <- grep(pattern = trees, x = newFile, value = F)
treesRep <- paste0("\\.Taxon", takeOut, trees)
if (length(matchTreesPosition) != 0) {
newFile [matchTreesPosition] <- gsub(trees, treesRep, matchTrees)}
if (writeTrees == F) {
logA <- grep(pattern = "\\.trees", x = newFile, value = T)
logAn <- grep(pattern = "\\.trees", x = newFile, value = F)
newFile [logAn] <- paste0("\t<!-- \n ", logA)
ctr <- 0
repeat {
ctr <- ctr + 1
ctr2 <- 0
ctr2 <- logAn + ctr
temp <- grep(pattern = "</logger>", newFile[ctr2], value = F)
temp <- length(temp)
if (temp != 0) break
if (ctr == 100) stop("Error, check files, no tree block found")
}
newFile [ctr2] <- paste0("\t</logger>", "\n", "\t-->")
}
out <- paste0(name, ".Taxon", takeOut, ".xml")
cat (newFile, file = out, sep = "\n")
cat ("Taxon", takeOut, "processed \n")
}
}
if (ver1 == F & ver2 == F) {stop("Error, check BEAST input file -version not recognized")}
} |
"setValues" <- function(nodeLabel, values)
{
nodeLabel <- as.character(nodeLabel)
nodeSize <- .OpenBUGS(c("BugsRobjects.SetVariable", "BugsRobjects.GetSize"),
c("CharArray","Integer"),
c(nodeLabel,NA))[[2]]
if(nodeSize == -1)
stop(nodeLabel, " is not a node in BUGS model")
numChains <- getNumChains()
if(length(values) != nodeSize*numChains)
stop("length(values) does not correspond to the node size and number of chains")
.OpenBUGS(c("BugsRobjects.SetVariable", "BugsRobjects.SetValues"),
c("CharArray","RealArray"),
list(nodeLabel,as.double(values)))[[2]]
invisible()
} |
.arg.filter <- function(new.args, FUN=NULL, ...) {
dots <- list(...)
ans <- c(dots, new.args[!names(new.args) %in% names(dots)])
if(!is.null(FUN)) { ans <- ans[names(ans) %in% names(formals(FUN))] }
return(ans)
} |
"sokolova2021"
"ecorelevance" |
setMethod("getvcov",
signature(object = "bild"),
function (object)
{
cov<-object@covariance
cnames <- rownames(cov)
r1<-nrow(cov)
c1<-ncol(cov)
if(all(is.na(match(cnames, "omega"))) )
{ cov
}
else if (!all(is.na(match(cnames, "omega"))))
{ cov.aux<-cov[1:(r1-1),1:(c1-1)]
cov.aux
}
} ) |
sNorm <- function (N,
b0,
s) {
return (rnorm(n = N,
mean = b0,
sd = s))
}
sBinom <- function (N,
p) {
return (rbinom(n = N,
size = 1,
prob = p))
}
sMulti <- function (N,
q) {
return (sample(x = 0:2,
size = N,
replace = TRUE,
prob = c((1 - q)^2,
2 * q * (1 - q),
q^2)))
}
cNorm <- function (N,
parentData,
b0,
b1,
s) {
if (length(parentData) != length(b1)) {
stop ('parentData and b1 must have the same number of elements')
}
mParents <- length(parentData)
lmFormula <- vector(length = mParents + 1)
lmFormula[[1]] <- '~ b0'
for (e in 1:mParents) {
lmFormula[[e + 1]] <- paste0('b1[[',
e,
']] * parentData[[',
e,
']]')
}
means <- eval(as.formula(paste(lmFormula,
collapse = ' + '))[[2]])
return (rnorm(n = N,
mean = means,
sd = s))
}
cBinom <- function (N,
parentData,
b0,
b1) {
if (length(parentData) != length(b1)) {
stop ('parentData and b1 must have the same number of elements')
}
mParents <- length(parentData)
lmFormula <- vector(length = mParents + 1)
lmFormula[[1]] <- '~ b0'
for (e in 1:mParents) {
lmFormula[[e + 1]] <- paste0('b1[[',
e,
']] * parentData[[',
e,
']]')
}
linearModel <- eval(as.formula(paste(lmFormula,
collapse = ' + '))[[2]])
probs <- 1 / (1 + exp(-linearModel))
return (rbinom(n = N,
size = 1,
prob = probs))
}
cMulti <- function (N,
parentData,
b0,
b1,
q) {
if (length(parentData) != length(b1)) {
stop ('parentData and b1 must have the same number of elements')
}
mParents <- length(parentData)
lmFormula <- vector(length = mParents + 1)
lmFormula[[1]] <- '~ b0'
for (e in 1:mParents) {
lmFormula[[e + 1]] <- paste0('b1[[',
e,
']] * parentData[[',
e,
']]')
}
means <- eval(as.formula(paste(lmFormula,
collapse = ' + '))[[2]])
normalRV <- rnorm(n = N,
mean = means,
sd = 1)
lowerCutoff <- qnorm(q^2, 0, 1)
upperCutoff <- qnorm((1 - q)^2, 0, 1, lower.tail = FALSE)
U <- rep(NA, length = N)
U[normalRV < lowerCutoff] <- 0
U[normalRV > upperCutoff] <- 2
U[is.na(U)] <- 1
return (U)
} |
PAR <- function(std = "Plant") {
if (std %in% c("Plant", "McCree")) {
new_waveband(400, 700, wb.name = "PAR")
} else {
warning("'std' = '", std, "' not implemented.")
NA
}
} |
writeTIF<- function (img, file, bps = attributes(img)$bits.per.sample, twod=FALSE, reduce=TRUE, attr = attributes(img), compression="none")
{
if (is.null(bps))
if (!is.null(attr$bits.per.sample))
bps <- attr$bits.per.sample
if (is.null(bps))
bps <- 16L
imglist <- list()
if (length(dim(img)) == 3) {
Z <- dim(img)[3]
if(twod) for (i in 1:Z) imglist[[i]] <- img[, , i]/max(1,max(img[, , i]))
if(!twod) {
maxi<-max(1,max(img))
for (i in 1:Z) imglist[[i]] <- img[, , i]/maxi
}
}
if (length(dim(img)) == 4) {
C <- dim(img)[3]
Z <- dim(img)[4]
k <- 0
maxi <- 1:C
for (j in 1:C)
{
maxi[j] <- max(1,max(img[, , j, ], na.rm = TRUE))
img[,,j,]<-img[,,j,]/maxi[j]
}
for (i in 1:Z){
k <- k + 1
imglist[[k]] <- img[, , , i]
}
}
Z <- length(imglist)
ati <- attributes(img)
ati$dim <- dim(imglist[[1]])
for (i in 1:Z) attributes(imglist[[i]]) <- ati
writeTIFF(what = imglist, where = file, reduce = reduce, bits.per.sample = bps, compression=compression)
} |
egyptian_complete <- function(a, b, show = TRUE) {
stopifnot(isNatural(a), isNatural(b), length(a) == 1, length(b) == 1)
if (a >= b)
stop("Rational number 'a/b' must be smaller than 1.")
g <- GCD(a, b)
if (g > 1) {
warning("Arguments 'a', 'b' have a common divisor > 1.")
a <- a/g; b <- b/g
}
a0 <- a;
b0 <- b
noex <- 0
lb1 <- max(1 + div(b, a), 1)
ub1 <- div(3*b, a)
for (x1 in lb1:ub1) {
a1 <- a*x1 - b; b1 <- b*x1
g <- GCD(a1, b1)
a1 <- a1/g; b1 <- b1/g
if (b1 == x1) next
if (a1 == 1) {
if (show)
cat("1/", x1, " + ", "1/", b1, "\n", sep = "")
noex <- noex + 1
} else {
lb2 <- max(1 + div(b1, a1), x1)
ub2 <- div(2*b1, a1)
for (x2 in lb2:ub2) {
a2 <- a1*x2 - b1; b2 <- b1*x2
g <- GCD(a2, b2)
a2 <- a2/g; b2 <- b2/g
if (x1 == x2 || b2 == x2) next
if (a2 == 1) {
if (show)
cat("1/", x1, " + ", "1/", x2, " + ", "1/", b2, "\n", sep = "")
noex <- noex + 1
}
}
}
}
invisible(noex)
}
egyptian_methods <- function(a, b) {
stopifnot(isNatural(a), isNatural(b), length(a) == 1, length(b) == 1)
if (a >= b)
stop("Rational number 'a/b' must be smaller than 1.")
g <- GCD(a, b)
if (g > 1) {
warning("Arguments 'a', 'b' have a common divisor > 1.")
a <- a/g; b <- b/g
}
a0 <- a; b0 <- b
print_eg <- function(a, b, f) {
cat(a, "/", b, " = ", sep="")
cat("1/", f[1], sep="")
for (i in 2:length(f)) {
cat(" + 1/", f[i], sep = "")
}
}
if (a == 1) {
f <- c(b+1, b*(b+1))
print_eg(a, b, f)
cat(" (Egyptian fraction)\n")
stop("Argument 'a' shall be an integer > 1.")
}
if (a == 2) {
if (isPrime(b) && b < 12) {
f <- c(b, b+1, b*(b+1))
print_eg(a, b, f)
cat(" (Rhind Papyros)\n")
} else if (isPrime(b)) {
f <- b * c(1, 2, 3, 6)
print_eg(a, b, f)
cat(" (Rhind Papyros)\n")
} else {
fctrs <- primeFactors(b)
if (length(fctrs) == 2 && all(isPrime(fctrs))) {
f <- (fctrs[1] + 1)/2 * c(1, fctrs[1]) * fctrs[2]
print_eg(a, b, f)
cat(" (Rhind Papyros)\n")
}
}
}
res <- c()
while (a > 1) {
s <- div(b, a)
r <- mod(b, a)
res <- c(res, s+1)
a <- a - r
b <- b*(s+1)
g <- GCD(a, b)
if (g != 1) {a <- a/g; b <- b/g}
}
res <- c(res, b)
print_eg(a0, b0, res)
cat(" (Fibonacci-Sylvester)\n")
a <- a0; b <- b0
res <- c()
while (a > 1) {
p <- modinv(a, b)
res <- c(res, p*b)
a <- (p*a - 1)/b
b <- p
g <- GCD(a, b)
if (g != 1) {a <- a/g; b <- b/g}
}
res <- rev(c(res, b))
print_eg(a0, b0, res)
cat(" (Golomb-Farey)\n")
} |
FilterAUC = R6Class("FilterAUC",
inherit = Filter,
public = list(
initialize = function() {
super$initialize(
id = "auc",
task_type = "classif",
task_properties = "twoclass",
feature_types = c("integer", "numeric"),
packages = "mlr3measures",
man = "mlr3filters::mlr_filters_auc"
)
}
),
private = list(
.calculate = function(task, nfeat) {
y = task$truth() == task$positive
x = task$data(cols = task$feature_names)
score = map_dbl(x, function(x) {
keep = !is.na(x)
auc(y[keep], x[keep])
})
abs(0.5 - score)
}
)
)
mlr_filters$add("auc", FilterAUC)
auc = function(truth, prob) {
n_pos = sum(truth)
n_neg = length(truth) - n_pos
if (n_pos == 0L || n_neg == 0L) {
return(0.5)
}
r = rank(prob, ties.method = "average")
(sum(r[truth]) - n_pos * (n_pos + 1L) / 2L) / (n_pos * n_neg)
} |
.onLoad <- function(libname, pkgname) {
.jpackage(pkgname, lib.loc = libname)
} |
"boot.relimp.default.intern" <-
function (object, x = NULL, ..., b = 1000, type = "lmg", rank = TRUE, diff = TRUE,
rela = FALSE, always = NULL, groups = NULL, groupnames = NULL, fixed = FALSE,
weights = NULL, design = NULL, WW = NULL, ynam=NULL, ngroups=NULL)
{
y <- object
xcall <- x
if (is.null(x) && ncol(y) == nrow(y))
stop("Bootstrapping cannot be based on a (square) covariance matrix.")
hilf <- calc.relimp.default.intern(object,x=x,type=type,rank=rank,diff=diff,
rela=rela,always=always,groups=groups,groupnames=groupnames,
weights=weights,design=design,WW=WW,ynam=ynam,test=TRUE,ngroups=ngroups)
groupdocu <- hilf@groupdocu
alwaysnam <- hilf@alwaysnam
namen <- hilf@namen
daten <- hilf@daten
daten <- as.data.frame(daten)
y <- daten[,1]
x <- daten[,-1]
names <- colnames(daten)
p <- ncol(daten)-1
wt <- hilf@wt
nobs <- hilf@nobs
n <- nobs
always <- hilf@always
if (length(groupdocu)>0) {groups <- groupdocu[[2]];groupnames <- groupdocu[[1]]}
rm(hilf)
if (!is.logical(fixed))
stop("fixed must be a logical")
if (fixed & !(is.null(weights) & is.null(design)))
stop("weights or a survey design cannot be applied together with fixed=TRUE.")
if (is.null(names)) names <- c("y", paste("X",1:p,sep=""))
alltype <- alltype()
ausgabe <- new("relimplmboot")
ausgabe@type <- alltype[which(alltype %in% type)]
ausgabe@nobs <- nobs
ausgabe@nboot <- b
ausgabe@rank <- rank
ausgabe@diff <- diff
ausgabe@rela <- rela
ausgabe@always <- always
ausgabe@alwaysnam <- alwaysnam
ausgabe@fixed <- fixed
ausgabe@namen <- names
ausgabe@call <- sys.call(1)
if (!is.null(groups)) ausgabe@groupdocu <- groupdocu
if (!fixed) {
if (is.null(design))
booterg <- boot(cbind(wt,daten), calcrelimp.forboot, b, type = type,
diff = diff, rank = rank, rela = rela, always = always, groups=groups,
groupnames=groupnames, WW=WW, ngroups=ngroups)
else {
booterg <- boot(cbind(wt,daten), calcrelimp.forboot, 1, type = type,
diff = diff, rank = rank, rela = rela, always = always, groups=groups,
groupnames=groupnames, WW=WW, ngroups=ngroups)
desrep <- as.svrepdesign(design, type="bootstrap", replicates=b)
hilf <- withReplicates(desrep, function(wt, dat){calcrelimp.forsurvey(wt, dat[,colnames(daten)], b=b,
type=type, rela=rela, diff=diff, rank=rank, groups=groups,
groupnames=groupnames, WW=WW, ngroups=ngroups)},
return.replicates=TRUE)
booterg$t <- hilf$replicates
booterg$R <- b
booterg$strata <- as.matrix(design$strata)
ausgabe@vcov <- attr(hilf$theta,"var")
attr(hilf$theta,"var") <- NULL
booterg$t0 <- hilf$theta
}
booterg$data <- booterg$data[,-1]
ausgabe@wt <- wt
ausgabe@boot <- booterg
}
else {
linmod <- lm(data.frame(daten),qr=FALSE,model=FALSE)
e <- linmod$residuals
fit <- linmod$fitted.values
booterg <- boot(data.frame(x,fit=fit,e=e), calcrelimp.forboot.fixed, b, type = type,
diff = diff, rank = rank, rela = rela, always = always, groups=groups,
groupnames=groupnames, WW=WW, ngroups=ngroups)
booterg$data <- daten
slot(ausgabe,"boot") <- booterg
}
return(ausgabe)
} |
is_ngram <- function(x) {
if(!is.character(x))
return(FALSE)
sngram <- strsplit(x, "_")[[1]]
if(!(length(sngram) %in% c(2, 3)))
return(FALSE)
pos_inf <- ifelse(length(sngram) == 3, TRUE, FALSE)
if(pos_inf)
if(is.na(suppressWarnings(as.numeric(sngram[[1]]))) || as.numeric(sngram[[1]]) < 1)
return(FALSE)
seq <- strsplit(sngram[1 + pos_inf], ".", fixed = TRUE)[[1]]
dists <- strsplit(sngram[2 + pos_inf], ".", fixed = TRUE)[[1]]
if(length(seq) > 1) {
if(length(dists) != (length(seq) - 1))
return(FALSE)
} else {
if(length(dists) != 1)
return(FALSE)
}
TRUE
} |
mscorev <-
function (ymat, inner = 0, trim = 2.5, qu = 0.5, TonT = FALSE)
{
ymat <- as.matrix(ymat)
n <- dim(ymat)[1]
m <- dim(ymat)[2]
out <- matrix(NA, n, m)
one <- rep(1, m - 1)
difs <- array(NA, c(n, m, m - 1))
for (j in 1:m) {
difs[, j, ] <- outer(as.vector(unlist(ymat[, j])), one,
"*") - ymat[, -j]
}
ms <- as.vector(difs)
if ((trim < Inf) | (inner > 0)) {
hqu <- as.numeric(quantile(abs(ms), qu, na.rm = TRUE))
if (hqu > 0) {
ms <- ms/hqu
if ((trim < Inf) & (inner < trim)) {
ab <- pmin(1, pmax(0, (abs(ms) - inner))/(trim -
inner))
}
else if ((trim < Inf) & (inner == trim)) {
ab <- 1 * (abs(ms) > inner)
}
else {
ab <- pmax(0, abs(ms) - inner)
}
ms <- sign(ms) * ab
}
else {
warning("Error: Scale factor is zero. Increase lambda.")
}
}
ms <- array(ms, c(n, m, m - 1))
ms <- apply(ms, c(1, 2), sum, na.rm = TRUE)
ms[is.na(ymat)] <- NA
colnames(ms) <- colnames(ymat)
ni <- apply(!is.na(ymat), 1, sum)
use <- (ni >= 2) & (!is.na(ms[, 1]))
ms <- ms[use, ]
ni <- ni[use]
if (TonT) {
ms <- (ms/outer(ni - 1, rep(1, m), "*"))/(dim(ms)[1])
}
else {
ms <- ms/outer(ni, rep(1, m), "*")
}
ms
} |
dr_shell <- function (dates, name = "", N = 10000, CI = 0.95, make.plot = FALSE)
{
if (is.vector(dates) != TRUE || length(dates) != 3) stop("Check dates supplied to the function")
else if (typeof(N) != "double" || length(N) != 1 || N <= 0 || N%%1 != 0) stop("N must be a positive integer")
else if (typeof(CI) != "double" || length(CI) != 1 || CI <= 0 || CI >= 1) stop ("CI must be a number between 0 and 1")
else
{
me <- new.env()
data(marine13, package = "Bchron", envir = me)
prm1 <- me$marine13[which.min(abs(me$marine13[, 1] - (1950 - dates[1]))), 2]
prm2 <- me$marine13[which.min(abs(me$marine13[, 1] - (1950 - dates[1]))), 3]
model <- rnorm(N, prm1, prm2)
c14 <- rnorm(N, dates[2], dates[3])
delta <- c14 - model
out_list <- list(mean = mean(delta), median = median (delta), sd = sd(delta),
quantile = quantile(delta, c((1 - CI)/2, 1 - (1 - CI)/2)),
p.value = ks.test(delta,"pnorm", mean(delta), sd(delta))$p.value,
delta = delta)
if (make.plot == FALSE) return(out_list)
else
{
hist(delta, freq = FALSE, ylim = c(0, max(c(density(delta)$y,
dnorm(seq(min(delta), max(delta), length = 500), mean(delta), sd(delta))))),
main = name, xlab = "Delta R, years")
lines(seq(min(delta), max(delta), length = 500),
dnorm(seq(min(delta), max(delta), length = 500), mean(delta), sd(delta)),
col = "red")
return(out_list)
}
}
} |
collar.bls=function(S,K1,K2,r,t,sd,plot=FALSE){
all=list(S,K1,K2,r,t,sd,plot)
if(any(lapply(all,is.null)==T)) stop("Cannot input any variables as NULL.")
if(any(lapply(all,length) != 1)==T) stop("All variables must be of length 1.")
num2=list(S,K1,K2,r,t,sd)
na.num2=num2[which(lapply(num2,is.na)==F)]
if(any(lapply(na.num2,is.numeric)==F)) stop("S K1, K2, r, t, and sd must be numeric.")
if(any(lapply(all,is.na)==T)) stop("Cannot input any variables as NA.")
NA.Neg=array(c(r,S,K1,K2,t,sd))
if(any(NA.Neg<=0)) stop("All numeric variables must be positive.")
if(any(NA.Neg==Inf)) stop("Cannot input any variables as infinite.")
stopifnot(is.logical(plot))
if(K1>=K2) stop("K1 must be less than K2.")
if(K2<=S | K1>=S) stop("K2 must be > S and K1 must be < S")
d1 = (log(S/K1)+(r+sd^2/2)*t)/(sd*sqrt(t))
d2 = d1 - sd * sqrt(t)
putP = K1*exp(-r*t) * pnorm(-d2) - S*pnorm(-d1)
d1 = (log(S/K2)+(r+sd^2/2)*t)/(sd*sqrt(t))
d2 = d1 - sd * sqrt(t)
callP = S*pnorm(d1) - K2*exp(-r*t)*pnorm(d2)
stock=unique(round(seq(0,K1,length.out=6)))
stock=c(stock,round(seq(K1,K2,length.out=4)))
stock=c(stock,round(seq(K2,K2+K1,length.out=6)))
stock=unique(stock)
stock2=unique(round(c(seq(0,K1,length.out=6),seq(K2,K2+K1,length.out=6))))
payoff=rep(0,length(stock))
profit=rep(0,length(stock))
for(i in 1:length(stock)){
if(stock[i]<=K1) payoff[i]=K1-stock[i]
if(stock[i]>=K2) payoff[i]=K2-stock[i]
if(stock[i]<K2 & stock[i]>K1) payoff[i]=0
profit[i]=payoff[i]+(callP-putP)*exp(r*t)
}
if(plot==T){
plot(stock,profit,type="l",xlab="Stock Price",main="Collar\nPayoff and Profit",ylab="$",
ylim=c(min(profit,payoff),max(profit,payoff)),xaxt='n',yaxt='n',col="steelblue",lwd=2)
lines(stock,payoff,lty=2,lwd=2,col="firebrick")
abline(h=0,lty=2,col="gray")
y=round(seq(min(payoff,profit),max(payoff,profit),length.out=8))
axis(2,at=y,labels=y,las=2)
axis(1,at=if(K2-K1<7) stock2[-which(stock2==K2)] else stock2,las=2)
legend("bottomleft",c("Profit","Payoff"),lty=c(1,2),col=c("steelblue","firebrick"),lwd=c(2,2)) }
out1=data.frame(stock,payoff,profit)
names(out1)=c("Stock Price","Payoff","Profit")
out2=matrix(c(putP,callP,putP-callP),nrow=3)
rownames(out2)=c("Put (K1)","Call (K2)","Net Cost")
colnames(out2)=c("Premiums")
out=list(Payoff=out1,Premiums=out2)
return(out)
} |
Chacko_test_1xc <- function(n, printresults=TRUE) {
c0 <- length(n)
N <- sum(n)
nt <- n
t0 <- rep(1, c0)
m <- c0
notordered <- 1
while (notordered == 1) {
for (i in 1:(m - 1)) {
if (nt[i] > nt[i + 1]) {
nt[i] <- (nt[i] + nt[i + 1]) / 2
t0[i] <- t0[i] + 1
m <- m - 1
nt[(i + 1):m] <- nt[(i + 2):(m + 1)]
break
}
}
if (i == m - 1) {
notordered = 0
}
}
T0 <- 0
for (i in 1:m) {
T0 <- T0 + t0[i] * ((nt[i] - N / c0) ^ 2)
}
T0 <- T0 * c0 / N
df <- m - 1
P <- 1 - pchisq(T0, df)
if (printresults) {
print(
sprintf(
'The Chacko test: P = %7.5f, T = %5.3f (df = %i)', P, T0, df
)
, quote=FALSE
)
}
res <- data.frame(P=P, T=T0, df=df)
invisible(res)
} |
rapport.read <- function(fp, ...) {
if (missing(fp))
stop('Template file pointer not provided!')
stopifnot(is.character(fp))
l <- length(fp)
if (l == 1) {
if (grepl('^(ftp|http(s)?)://.+$', fp)) {
if (download.file(fp, tmp.fp <- tempfile(), method = 'wget') != 0)
stop('Remote template file not found!')
file <- tmp.fp
} else {
if (!grepl('.+\\.rapport$', fp, ignore.case = TRUE))
fp <- c(fp, sprintf('%s.rapport', fp))
fp <- c(fp, unlist(lapply(fp, function(file) file.path(getOption('rapport.paths'), file))), system.file('templates', fp, package = 'rapport'))
fp <- fp[file.exists(fp)]
if (length(fp) == 0)
stop('Template file not found!')
if (length(fp) > 1) {
fp <- fp[1]
warning(sprintf('Multiple templates found with given name, using: %s', fp))
}
}
txt <- readLines(fp, warn = FALSE, encoding = 'UTF-8')
} else if (l > 1) {
txt <- fp
} else {
stop('Template file pointer error :O')
}
check.tpl(txt, ...)
return(txt)
}
tpl.find <- rapport.read
rapport.tangle <- function(fp, file = "", show.inline.chunks = FALSE) {
b <- rapport.body(rapport.read(fp))
re.block.open <- "^<%=?$"
re.block.close <- "^%>$"
re.inline.open <- "<%=?"
re.inline.close <- "%>"
ind.block.open <- grep(re.block.open, b)
ind.block.close <- grep(re.block.close, b)
ind.inline.open <- grep(re.inline.open, b)
ind.inline.close <- grep(re.inline.close, b)
if (show.inline.chunks) {
if (length(ind.inline.open) != length(ind.inline.close))
stop("unmatched chunk tag(s)")
} else {
if (length(ind.block.open) != length(ind.block.close))
stop("unmatched block chunk tag(s)")
}
block.ind <- mapply(seq, from = ind.block.open, to = ind.block.close)
if (show.inline.chunks)
chunk.ind <- mapply(seq, from = ind.inline.open, to = ind.inline.close)
else
chunk.ind <- block.ind
chunk.ind <- lapply(chunk.ind, function(x) {
attr(x, "chunk.type") <- "block"
x
})
if (show.inline.chunks) {
chunk.ind[!chunk.ind %in% block.ind] <- lapply(chunk.ind[!chunk.ind %in% block.ind], function(x) {
attr(x, "chunk.type") <- "inline"
x
})
}
out <- c()
res <- lapply(chunk.ind, function(x) {
cc <- b[x]
ct <- attr(x, "chunk.type")
if (ct == "block") {
cc <- trim.space(paste0(cc[2:(length(cc) - 1)], collapse = "\n"))
out <<- c(out, "
out <<- c(out, "
out <<- c(out, "
out <<- c(out, "", cc, "")
} else {
cc <- trim.space(vgsub("(<%=?|%>)", "", str_extract_all(cc, "<%=?[^%>]+%>")[[1]]))
sapply(cc, function(x) {
out <<- c(out, "
out <<- c(out, "
out <<- c(out, "
out <<- c(out, "", x, "")
})
}
attr(cc, "chunk.type") <- ct
cc
})
out <- paste0(out, collapse = "\n")
cat(out, file = file)
invisible(res)
}
tpl.tangle <- rapport.tangle
rapport.header <- function(fp, open.tag = get.tags('header.open'), close.tag = get.tags('header.close'), ...) {
txt <- rapport.read(fp)
hopen.ind <- grep(open.tag, txt, ...)[1]
hclose.ind <- grep(close.tag, txt, ...)[1]
hsection <- txt[(hopen.ind + 1):(hclose.ind - 1)]
return(hsection)
}
tpl.header <- rapport.header
rapport.body <- function(fp, htag = get.tags('header.close'), ...) {
txt <- rapport.read(fp, ...)
h.end <- grep(htag, txt, ...)
b <- txt[(h.end + 1):length(txt)]
structure(b, class = 'rapport.body')
}
tpl.body <- rapport.body
rapport.info <- function(fp, meta = TRUE, inputs = TRUE) {
txt <- rapport.read(fp)
if (!meta & !inputs)
stop('Either "meta" or "inputs" should be set to TRUE')
res <- list()
if (meta)
res$meta <- rapport.meta(txt)
if (inputs)
res$inputs <- rapport.inputs(txt)
class(res) <- 'rapport.info'
return(res)
}
tpl.info <- rapport.info
rapport.meta <- function(fp, fields = NULL, use.header = FALSE, trim.white = TRUE) {
header <- rapport.read(fp)
if (!use.header)
header <- rapport.header(header)
h <- tryCatch({
y <- yaml.load(
string = paste0(header, collapse = "\n"),
handlers = list(
'bool
if (grepl('^(y|yes|true|on)$', x, ignore.case = TRUE))
x
else
TRUE
},
'bool
if (grepl('^(n|no|false|off)$', x, ignore.case = TRUE))
x
else
FALSE
})
)
y$meta
}, error = function(e) {
if (isTRUE(trim.white))
header <- trim.space(header)
fld <- list(
list(title = 'Title' , regex = '.+', field.length = 500),
list(title = 'Author' , regex = '.+', field.length = 100),
list(title = 'Description' , regex = '.+', short = 'desc'),
list(title = 'Email' , regex = '[[:alnum:]\\._%\\+-]+@[[:alnum:]\\.-]+\\.[[:alpha:]]{2,4}', mandatory = FALSE, short = 'email'),
list(title = 'Packages' , regex = '[[:alnum:]\\.]+((, ?[[:alnum:]+\\.]+)+)?', mandatory = FALSE),
list(title = 'Example' , regex = '.+', mandatory = FALSE)
)
if (!is.null(fields)) {
fld.title <- sapply(fld, function(x) x$title)
fields.title <- sapply(fields, function(x) x$title)
fld <- c(fld, fields)
if (any(fld %in% fields.title)) {
stopf("Duplicate metadata fields: %s", p(intersect(fld.title, fields.title), "\""))
}
}
inputs.ind <- grep("^(.+\\|){3}.+$", header)
spaces.ind <- grep("^([:space:]+|)$", header)
rm.ind <- c(inputs.ind, spaces.ind)
if (length(rm.ind) > 0)
header <- header[-rm.ind]
h <- sapply(fld, function(x) {
m <- grep(sprintf("^%s:", x$title), header)
x$x <- header[m]
do.call(extract.meta, x)
})
if (!is.null(h$packages))
if (is.string(h$packages))
h$packages <- strsplit(h$packages, " *, *")[[1]]
if (!is.null(h$example)) {
ind.start <- grep('^Example:', header)
ind <- adj.rle(grep("^[\t ]*rapport\\(.+\\)([\t ]*
ind <- ind[!ind %in% ind.start]
h$example <- c(h$example, header[ind])
}
h <- append(h, list(description = h$desc), after = 2)
h$desc <- NULL
h
})
if (!is.null(h$dataRequired)) {
h$dataRequired <- NULL
warning('"dataRequired" field is deprecated. You should remove it from the template.')
}
meta.fields <- c('title', 'description', 'author', 'email', 'packages', 'example')
meta.required <- c('title', 'description', 'author')
meta.names <- names(h)
if (!all(meta.required %in% meta.names))
stopf('Required metadata fields missing: %s', p(meta.required, wrap = "\""))
unsupported.meta <- meta.names[!meta.names %in% meta.fields]
if (length(unsupported.meta))
warningf('Unsupported metadata field(s) found: %s', p(unsupported.meta, wrap = "\""))
structure(h, class = 'rapport.meta')
}
tpl.meta <- rapport.meta
rapport.inputs <- function(fp, use.header = FALSE) {
header <- rapport.read(fp)
if (!use.header)
header <- rapport.header(header)
inputs <- tryCatch(
yaml.load(
string = paste0(header, collapse = "\n"),
handlers = list(
'bool
if (grepl('^(y|yes|true|on)$', x, ignore.case = TRUE))
x
else
TRUE
},
'bool
if (grepl('^(n|no|false|off)$', x, ignore.case = TRUE))
x
else
FALSE
})
),
error = function(e) e)
if (inherits(inputs, 'error')) {
inputs.ind <- grep("^(.+\\|){3}.+$", header)
if (length(inputs.ind) == 0)
return (structure(NULL, class = 'rapport.inputs'))
inputs.raw <- lapply(strsplit(header[inputs.ind], '|', fixed = TRUE), function(x) trim.space(x))
if (!all(sapply(inputs.raw, length) == 4))
stop('input definition error: missing fields')
inputs <- lapply(inputs.raw, function(x) {
i.name <- guess.input.name(x[1])
i.label <- guess.input.label(x[3])
i.desc <- guess.input.description(x[4])
i.type <- guess.old.input.type(x[2])
if (is.empty(i.label))
warningf('missing label for input "%s"', i.name)
if (is.empty(i.desc))
warningf('missing description for input "%s"', i.name)
c(
name = i.name,
label = i.label,
description = i.desc,
i.type
)
})
warning("Oh, no! This template has outdated input definition! You can update it by running `rapport.renew`.")
} else {
inputs <- lapply(inputs$inputs, guess.input)
}
nms <- sapply(inputs, function(x) x$name)
dupes <- duplicated(nms)
if (any(dupes))
stopf('template contains duplicate input names: %s', p(nms[dupes], wrap = "\""))
structure(inputs, class = 'rapport.inputs')
}
tpl.inputs <- rapport.inputs
rapport.example <- function(fp, index = NULL, env = .GlobalEnv) {
examples <- rapport.meta(fp)$example
n.examples <- 1:length(examples)
examples.len <- length(examples)
if (is.null(examples)) {
message('Provided template does not have any examples.')
invisible(NULL)
}
if (examples.len > 1) {
if (is.null(index)) {
opts <- c(n.examples)
catn('Enter example ID from the list below:')
catn(sprintf('\n(%s)\t%s', opts, c(examples)))
catn('(a)\tRun all examples')
catn()
i <- readline('Template ID> ')
index <- unique(strsplit(gsub(' +', '', i), ',')[[1]])
}
} else {
index <- 1
}
if (length(index) == 0 || tolower(index) == 'q')
return(invisible(NULL))
if (length(index) == 1 && tolower(index) %in% c('a', 'all'))
index <- n.examples
old.index <- index
if (!any(index %in% n.examples))
stopf('Invalid template ID found in: ', paste(setdiff(index, n.examples), collapse = ', '))
suppressWarnings(index <- as.integer(index))
if (any(is.na(index)))
stopf('Invalid template ID found in: "%s"', paste(old.index, collapse = ', '))
if (length(index) > 1)
return(lapply(examples[index], function(x) eval(parse(text = x), envir = env)))
else
eval(parse(text = examples[index]), envir = env)
}
tpl.example <- rapport.example
rapport.rerun <- function(tpl) {
if (!inherits(tpl, 'rapport'))
stop("You haven't provided a rapport template")
cl <- tpl$call
dt <- tpl$data
if (is.null(cl) || is.null(dt))
stop("Provided rapport object doesn't have included call and/or data, therefore not reproducible")
cl <- as.list(cl)
cl$data <- dt
do.call(rapport, cl)
}
tpl.rerun <- rapport.rerun
rapport <- function(fp, data = NULL, ..., env = .GlobalEnv, reproducible = FALSE, header.levels.offset = 0, graph.output = evalsOptions('graph.output'), file.name = getOption('rapport.file.name'), file.path = getOption('rapport.file.path'), graph.width = evalsOptions('width'), graph.height = evalsOptions('height'), graph.res = evalsOptions('res'), graph.hi.res = evalsOptions('hi.res'), graph.replay = evalsOptions('rapport.graph.recordplot')) {
timer <- proc.time()
txt <- rapport.read(fp)
h <- rapport.info(txt)
meta <- h$meta
inputs <- h$inputs
inputs.names <- sapply(inputs, function(x) x$name)
b <- rapport.body(txt)
e <- new.env(parent = env)
e$Pandoc.brew <- Pandoc.brew
i <- list(...)
i.names <- names(i)
data.required <- any(sapply(inputs, function(x) !x$standalone)) || (!is.null(data) && !identical(data, ''))
oldpkgs <- .packages()
pkgs <- meta$packages
file.path <- gsub('\\', '/', file.path, fixed = TRUE)
if (!is.null(pkgs)) {
pk <- suppressWarnings(suppressMessages(sapply(pkgs, require, character.only = TRUE, quietly = TRUE)))
on.exit(sapply(setdiff(.packages(), oldpkgs), function(pkg) try(
detach(paste('package', pkg, sep = ':'),
character.only = TRUE), silent = TRUE)))
nopkg <- pk == FALSE
if (any(nopkg))
stop(sprintf('Following packages are required by the template, but were not loaded: %s', p(names(pk[nopkg]), wrap = '"')), call. = NULL)
}
assign('rapport.inputs', inputs, envir = e)
assign('rapport.template', meta, envir = e)
if (length(inputs) == 0) {
if (data.required) {
if (is.null(data))
stop('"data" argument is required by the template')
else {
assign('rp.data', data, envir = e)
assign('rapport.data', data, envir = e)
}
}
} else {
input.required <- sapply(inputs, function(x) structure(x$required, .Names = x$name))
input.names <- names(input.required)
if (!all(input.names[input.required] %in% names(i)) && any(sapply(inputs, function(x) is.empty(x$value) & !identical(x$value, FALSE) & is.empty(i[[x$name]]) & x$required))) {
stopf("missing required input for %s", p(setdiff(input.names[input.required], names(i)), '"'))
}
if (data.required) {
if(is.null(data))
stop('"data" not provided, but is required')
if (!inherits(data, c('data.frame', 'rp.data')))
stop('"data" should be a "data.frame" object')
data.names <- names(data)
assign('rp.data', data, envir = e)
assign('rapport.data', data, envir = e)
}
lapply(inputs, function(x) {
input.name <- x$name
input.class <- x$class
input.length <- x$length
input.value <- x$value
user.input <- i[[input.name]]
if (isTRUE(x$matchable)) {
v <- if (is.null(user.input)) x$value else as.character(user.input)
matchable.err.msg <- sprintf('provided value `%s` not found in option list for matchable input "%s"', p(v, wrap = '"'), input.name)
if (x$allow_multiple) {
v.ind <- v %in% x$options
if (!any(v.ind))
stop(matchable.err.msg)
val <- v[v.ind]
} else {
if (!all(as.numeric(table(v)) == 1))
warning('multiple occurances found in provided value')
val <- x$options[x$options %in% v]
if (!length(val))
stop(matchable.err.msg)
}
if (input.class == 'factor')
val <- as.factor(val)
} else {
if (x$standalone) {
val <- if (is.null(user.input)) unlist(input.value) else user.input
val.length <- length(val)
} else {
if (!all(user.input %in% data.names))
stopf('provided data.frame does not contain column(s) named: %s', p(setdiff(user.input, data.names), '"'))
val <- e$rapport.data[user.input]
if (!length(val))
val <- NULL
val.length <- length(val)
}
}
check.input.value.class(val, input.class, input.name)
check.input.value(x, val, 'length')
if (!is.null(user.input)) {
if (!x$standalone && length(user.input) == 1)
val <- val[, 1]
if (!is.null(input.class))
switch(input.class,
character = {
check.input.value(x, val, 'nchar')
if (!is.null(x$regexp)) {
if (!all(grepl(x$regexp, val)))
stopf('%s input "%s" value is not matched with provided regular expression "%s"', input.name, val, x$regexp)
}
},
factor = {
check.input.value(x, val, 'nlevels')
},
integer = ,
numeric = {
if (!is.null(x$limit)) {
if (is.variable(val))
check.input.value(x, val, 'limit')
else {
if (!all(sapply(val, function(i) i > x$limit$min)) && all(sapply(val, function(i) i < x$limit$max)))
stopf('all values in %s input "%s" should fall between %s and %s', x$class, x$name, x$limit$min, x$limit$max)
}
}
})
if (is.recursive(val)) {
for (t in names(val)) {
if (label(val[, t]) == 't')
val[, t] <- structure(val[, t], label = t, name = t)
else
val[, t] <- structure(val[, t], name = t)
}
} else {
if (label(val) == 'val')
val <- structure(val, label = user.input, name = user.input)
else
val <- structure(val, name = user.input)
}
}
input.exists <- (!input.name %in% i.names && !x$required && x$standalone && length(val)) || input.name %in% i.names || !x$standalone || length(val)
if (input.exists) {
assign(input.name, val, envir = e)
assign(sprintf('%s.iname', input.name), input.name, envir = e)
assign(sprintf('%s.ilen', input.name), length(user.input), envir = e)
assign(sprintf('%s.ilabel', input.name), x$label, envir = e)
assign(sprintf('%s.idesc', input.name), x$description, envir = e)
assign(sprintf('%s.name', input.name), user.input, envir = e)
assign(sprintf('%s.len', input.name), length(val), envir = e)
}
if (is.data.frame(val))
assign(sprintf('%s.label', input.name), sapply(val, label), envir = e)
else if (is.atomic(val))
assign(sprintf('%s.label', input.name), label(val), envir = e)
else
stopf('"%s" is not a "data.frame" or an atomic vector', input.name)
})
}
if (grepl('%T', file.name))
file.name <- gsub('%T', gsub('\\\\|/|:|\\.', '-', fp), file.name, fixed = TRUE)
file.name <- gsub('--', '-', file.name, fixed = TRUE)
if (grepl('%N', file.name)) {
if (length(strsplit(sprintf('placeholder%splaceholder', file.name), '%N')[[1]]) > 2)
stop('File name contains more then 1 "%N"!')
similar.files <- list.files(file.path(file.path, 'plots'), pattern = sprintf('^%s\\.(jpeg|tiff|png|svg|bmp)$', gsub('%t', '[a-z0-9]*', gsub('%N|%n|%i', '[[:digit:]]*', file.name))))
if (length(similar.files) > 0) {
similar.files <- sub('\\.(jpeg|tiff|png|svg|bmp)$', '', similar.files)
rep <- gsub('%t|%n|%i', '[a-z0-9]*', strsplit(basename(file.name), '%N')[[1]])
`%N` <- max(as.numeric(gsub(paste(rep, collapse = '|'), '', similar.files))) + 1
} else
`%N` <- 1
file.name <- gsub('%N', `%N`, file.name, fixed = TRUE)
}
opts.bak <- options()
wd.bak <- getwd()
setwd(file.path)
evalsOptions('graph.name', file.name)
assign('.rapport.body', paste(b, collapse = '\n'), envir = e)
assign('.graph.name', file.name, envir = e)
assign('.graph.dir', evalsOptions('graph.dir'), envir = e)
assign('.graph.hi.res', graph.hi.res, envir = e)
if (grepl("w|W", .Platform$OS.type))
assign('.tmpout', 'NUL', envir = e)
else
assign('.tmpout', '/dev/null', envir = e)
report <- tryCatch(eval(parse(text = 'Pandoc.brew(text = .rapport.body, graph.name = .graph.name, graph.dir = .graph.dir, graph.hi.res = .graph.hi.res, output = .tmpout)'), envir = e), error = function(e) e)
options(opts.bak)
setwd(wd.bak)
if (inherits(report, 'error'))
stop(report$message)
report <- unlist(lapply(report, function(x) {
robj <- x$robject
rout <- robj$result
xtype <- x$type
if (xtype == 'block') {
if (any(robj$type == 'rapport'))
return(rout$report)
if (all(is.list(rout)))
if (all(sapply(rout, class) == 'rapport'))
return(unlist(lapply(rout, function(x) x$report), recursive = FALSE))
}
return(list(x))
}), recursive = FALSE)
report <- lapply(report, function(x) {
if (x$type == "heading") {
x$level <- x$level + header.levels.offset
return(x)
} else
return(x)
})
res <- list(
meta = meta,
inputs = inputs,
report = report,
call = match.call(),
time = as.numeric(proc.time() - timer)[3],
file.name = file.path(file.path, file.name)
)
if (isTRUE(reproducible)) {
res$data <- data
}
class(res) <- 'rapport'
return(res)
} |
NULL
aes <- function(x, y, ...) {
exprs <- enquos(x = x, y = y, ..., .ignore_empty = "all")
aes <- new_aes(exprs, env = parent.frame())
rename_aes(aes)
}
new_aesthetic <- function(x, env = globalenv()) {
if (is_quosure(x)) {
if (!quo_is_symbolic(x)) {
x <- quo_get_expr(x)
}
return(x)
}
if (is_symbolic(x)) {
x <- new_quosure(x, env = env)
return(x)
}
x
}
new_aes <- function(x, env = globalenv()) {
if (!is.list(x)) {
abort("`x` must be a list")
}
x <- lapply(x, new_aesthetic, env = env)
structure(x, class = "uneval")
}
print.uneval <- function(x, ...) {
cat("Aesthetic mapping: \n")
if (length(x) == 0) {
cat("<empty>\n")
} else {
values <- vapply(x, quo_label, character(1))
bullets <- paste0("* ", format(paste0("`", names(x), "`")), " -> ", values, "\n")
cat(bullets, sep = "")
}
invisible(x)
}
"[.uneval" <- function(x, i, ...) {
new_aes(NextMethod())
}
"[[<-.uneval" <- function(x, i, value) {
new_aes(NextMethod())
}
"$<-.uneval" <- function(x, i, value) {
x <- unclass(x)
x[[i]] <- value
new_aes(x)
}
"[<-.uneval" <- function(x, i, value) {
new_aes(NextMethod())
}
standardise_aes_names <- function(x) {
x <- sub("color", "colour", x, fixed = TRUE)
revalue(x, ggplot_global$base_to_ggplot)
}
rename_aes <- function(x) {
names(x) <- standardise_aes_names(names(x))
duplicated_names <- names(x)[duplicated(names(x))]
if (length(duplicated_names) > 0L) {
duplicated_message <- paste0(unique(duplicated_names), collapse = ", ")
warn(glue("Duplicated aesthetics after name standardisation: {duplicated_message}"))
}
x
}
substitute_aes <- function(x) {
x <- lapply(x, function(aesthetic) {
as_quosure(standardise_aes_symbols(quo_get_expr(aesthetic)), env = environment(aesthetic))
})
class(x) <- "uneval"
x
}
standardise_aes_symbols <- function(x) {
if (is.symbol(x)) {
name <- standardise_aes_names(as_string(x))
return(sym(name))
}
if (!is.call(x)) {
return(x)
}
x[-1] <- lapply(x[-1], standardise_aes_symbols)
x
}
aes_to_scale <- function(var) {
var[var %in% c("x", "xmin", "xmax", "xend", "xintercept")] <- "x"
var[var %in% c("y", "ymin", "ymax", "yend", "yintercept")] <- "y"
var
}
is_position_aes <- function(vars) {
aes_to_scale(vars) %in% c("x", "y")
}
aes_ <- function(x, y, ...) {
mapping <- list(...)
if (!missing(x)) mapping["x"] <- list(x)
if (!missing(y)) mapping["y"] <- list(y)
caller_env <- parent.frame()
as_quosure_aes <- function(x) {
if (is.formula(x) && length(x) == 2) {
as_quosure(x)
} else if (is.call(x) || is.name(x) || is.atomic(x)) {
new_aesthetic(x, caller_env)
} else {
abort("Aesthetic must be a one-sided formula, call, name, or constant.")
}
}
mapping <- lapply(mapping, as_quosure_aes)
structure(rename_aes(mapping), class = "uneval")
}
aes_string <- function(x, y, ...) {
mapping <- list(...)
if (!missing(x)) mapping["x"] <- list(x)
if (!missing(y)) mapping["y"] <- list(y)
caller_env <- parent.frame()
mapping <- lapply(mapping, function(x) {
if (is.character(x)) {
x <- parse_expr(x)
}
new_aesthetic(x, env = caller_env)
})
structure(rename_aes(mapping), class = "uneval")
}
aes_q <- aes_
aes_all <- function(vars) {
names(vars) <- vars
vars <- rename_aes(vars)
structure(
lapply(vars, function(x) new_quosure(as.name(x), emptyenv())),
class = "uneval"
)
}
aes_auto <- function(data = NULL, ...) {
warn("aes_auto() is deprecated")
if (is.null(data)) {
abort("aes_auto requires data.frame or names of data.frame.")
} else if (is.data.frame(data)) {
vars <- names(data)
} else {
vars <- data
}
vars <- intersect(ggplot_global$all_aesthetics, vars)
names(vars) <- vars
aes <- lapply(vars, function(x) parse(text = x)[[1]])
if (length(match.call()) > 2) {
args <- as.list(match.call()[-1])
aes <- c(aes, args[names(args) != "data"])
}
structure(rename_aes(aes), class = "uneval")
}
mapped_aesthetics <- function(x) {
if (is.null(x)) {
return(NULL)
}
is_null <- vapply(x, is.null, logical(1))
names(x)[!is_null]
}
warn_for_aes_extract_usage <- function(mapping, data) {
lapply(mapping, function(quosure) {
warn_for_aes_extract_usage_expr(get_expr(quosure), data, get_env(quosure))
})
}
warn_for_aes_extract_usage_expr <- function(x, data, env = emptyenv()) {
if (is_call(x, "[[") || is_call(x, "$")) {
if (extract_target_is_likely_data(x, data, env)) {
good_usage <- alternative_aes_extract_usage(x)
warn(glue("Use of `{format(x)}` is discouraged. Use `{good_usage}` instead."))
}
} else if (is.call(x)) {
lapply(x, warn_for_aes_extract_usage_expr, data, env)
}
}
alternative_aes_extract_usage <- function(x) {
if (is_call(x, "[[")) {
good_call <- call2("[[", quote(.data), x[[3]])
format(good_call)
} else if (is_call(x, "$")) {
as.character(x[[3]])
} else {
abort(glue("Don't know how to get alternative usage for `{format(x)}`"))
}
}
extract_target_is_likely_data <- function(x, data, env) {
if (!is.name(x[[2]])) {
return(FALSE)
}
tryCatch({
data_eval <- eval_tidy(x[[2]], data, env)
identical(data_eval, data)
}, error = function(err) FALSE)
} |
.BIN_AR_param <- list(
support = 0.1,
confidence = 0.8,
maxlen = 3,
sort_measure = "confidence",
sort_decreasing = TRUE,
apriori_control = list(),
verbose = FALSE
)
BIN_AR <- function(data, parameter = NULL) {
p <- getParameters(.BIN_AR_param, parameter)
p$apriori_control$verbose <- p$verbose
data <- data@data
rule_base <- suppressWarnings(
apriori(data,
parameter=list(support=p$support, confidence=p$confidence,
minlen=2, maxlen=p$maxlen), control=p$apriori_control)
)
if(p$sort_measure == "cxs") quality(rule_base) <- cbind(quality(rule_base),
cxs = quality(rule_base)$confidence * quality(rule_base)$support)
if(!p$sort_measure %in% names(quality(rule_base))) quality(rule_base) <-
cbind(quality(rule_base), interestMeasure(rule_base, method = p$sort_measure,
transactions = data))
rule_base <- sort(rule_base, by = p$sort_measure, decreasing=p$sort_decreasing)
if(p$verbose) cat("\nRule base size:", length(rule_base), "rules.\n")
if(length(rule_base)<1) warning("Rule base does not contain any rules. Decrease support and/or confidence!")
model <- c(list(
description = "AR: rule base",
rule_base = rule_base
), p
)
predict <- function(model, newdata, n=10, data=NULL,
type = c("topNList", "ratings", "ratingMatrix"), ...) {
type <- match.arg(type)
if(is.numeric(newdata)) {
if(is.null(data) || !is(data, "ratingMatrix"))
stop("If newdata is a user id then data needes to be the training dataset.")
newdata <- data[newdata,, drop=FALSE]
}
n <- as.integer(n)
sort_measure <- model$sort_measure
m <- is.subset(lhs(model$rule_base), newdata@data)
reclist <- list()
for(i in 1:nrow(newdata)) {
recom <- head(unique(unlist(
LIST(rhs(sort(model$rule_base[m[,i]], by=sort_measure)),
decode=FALSE))), n)
reclist[[i]] <- if(!is.null(recom)) recom else integer(0)
}
names(reclist) <- rownames(newdata)
reclist <- new("topNList", items = reclist, itemLabels = colnames(newdata), n = n)
if(type == "ratings" || type == "ratingMatrix")
return(as(as(reclist, "matrix"), "realRatingMatrix"))
return(reclist)
}
new("Recommender", method = "AR", dataType = "binaryRatingMatrix",
ntrain = nrow(data), model = model, predict = predict)
}
recommenderRegistry$set_entry(
method="AR", dataType = "binaryRatingMatrix", fun=BIN_AR,
description="Recommender based on association rules.",
parameters=.BIN_AR_param
) |
context("cluster sampling")
for (limit in 1:10) {
for (try in 1:10) {
classes <- sample(1:limit, 100, replace = T)
samp <- classes[sample_classes(classes, max(try, limit))]
test_that("cluster sampling produces equal sampling", {
expect_true(loosely_balanced(samp))
})
}
}
vec <- c(1, 2, rep(3, 97))
test_that("classes with one instance are sampled correctly", {
samp <- vec[sample_classes(vec, 30)]
expect_true(loosely_balanced(samp))
})
vec <- 1:10
test_that("case where classes must be dropped trims output", {
samp <- vec[sample_classes(vec, 7)]
expect_true(loosely_balanced(samp))
}) |
test_that("test game: constructor", {
set.seed(1)
g <- Game$new(19, 3, TRUE)
df <- g$getPurseDF()
true_df <- data.frame(Player = paste(rep("Player", 3), 0:2),
Coins = rep(0, 3))
expect_equal(df, true_df)
df <- g$getCamelDF()
true_df <- data.frame(Color = c("Green", "White", "Yellow", "Orange", "Blue"),
Space = c(1, 2, 2, 3, 1),
Height = c(1, 1, 2, 1, 2))
expect_equal(df, true_df)
expect_equal(g$getRanking(), c("Orange", "Yellow", "White", "Blue", "Green"))
df <- g$getLegBetDF()
true_df <- data.frame(Color = c("Green", "White", "Yellow", "Orange", "Blue"),
Value = rep(5,5),
nBets = rep(3, 5))
expect_equal(df, true_df)
})
test_that("test game: takeTurnMove", {
set.seed(1)
g <- Game$new(19, 3, TRUE)
g$takeTurnMove()
df <- g$getPurseDF()
true_df <- data.frame(Player = paste(rep("Player", 3), 0:2),
Coins = c(1, 0, 0))
df <- g$getCamelDF()
true_df <- data.frame(Color = c("Green", "White", "Yellow", "Orange", "Blue"),
Space = c(1, 2, 2, 3, 4),
Height = c(1, 1, 2, 1, 1))
expect_equal(df, true_df)
})
test_that("test game: takeTurnLegBet", {
set.seed(1)
g <- Game$new(19, 3, TRUE)
g$takeTurnLegBet("Blue")
df <- g$getLegBetDF()
true_df <- data.frame(Color = c("Green", "White", "Yellow", "Orange", "Blue"),
Value = c(rep(5,4), 3),
nBets = c(rep(3,4), 2))
expect_equal(df, true_df)
})
test_that("test game: evaluateBets", {
set.seed(1)
g <- Game$new(19, 3, TRUE)
g$takeTurnLegBet("Orange")
g$takeTurnLegBet("Orange")
expect_equal(g$getNMadeLegBets(), 2)
g$evaluateLegBets()
df <- g$getPurseDF()
true_df <- data.frame(Player = paste(rep("Player", 3), 0:2),
Coins = c(8, 0, 0))
expect_equal(df, true_df)
})
test_that("test game: can play more than one leg", {
g <- Game$new(19, 3, TRUE)
g$takeTurnMove()
g$takeTurnMove()
g$takeTurnMove()
g$takeTurnMove()
g$takeTurnMove()
g$takeTurnMove()
expect_equal(TRUE, TRUE)
})
test_that("test game: game ends", {
x <- system.time({
for(i in 1:10){
g <- Game$new(19, 3, FALSE)
while(!g$checkIsGameOver()){
g$takeTurnMove()
g$getCamelDF()
}
}
})
print(x)
expect_equal(TRUE, TRUE)
})
test_that("test game: place overall winner", {
g <- Game$new(19, 3, TRUE)
g$takeTurnPlaceOverallWinner("Blue")
expect_equal(g$getNOverallWinnersPlaced(), 1)
})
test_that("test game: place overall loser", {
g <- Game$new(19, 3, TRUE)
g$takeTurnPlaceOverallLoser("Blue")
expect_equal(g$getNOverallLosersPlaced(), 1)
})
test_that("test game: evaluate overall bets", {
set.seed(1)
g <- Game$new(19, 3, TRUE)
g$takeTurnPlaceOverallWinner("Orange")
g$takeTurnPlaceOverallWinner("Blue")
g$takeTurnPlaceOverallLoser("Green")
g$getRanking()
g$evaluateOverallBets()
true_df <- data.frame(Player = paste(rep("Player", 3), 0:2),
Coins = c(8, -1, 8))
expect_equal(g$getPurseDF(), true_df)
}) |
beran <- function(x,
t,
d,
dataset,
x0,
h,
local = TRUE,
testimate = NULL,
conflevel = 0L,
cvbootpars = if (conflevel == 0 && !missing(h)) NULL else controlpars()) {
dfr <-
if (missing(dataset))
na.omit(data.frame(x, t, d))
else
na.omit(dataset[, c(deparse(substitute(x)), deparse(substitute(t)), deparse(substitute(d)))])
names(dfr) <- c("x", "t", "d")
dfr$x <- as.numeric(dfr$x)
dfr$t <- as.numeric(dfr$t)
dfr$d <- as.integer(dfr$d)
nrow <- dim(dfr)[1]
ordx0 <- order(x0)
x0 <- as.numeric(x0[ordx0])
lx0 <- length(x0)
if (missing(h)) {
sm <- cvbootpars$hsmooth
h <-
if (sm > 1)
berancv(x, t, d, dfr, x0, cvbootpars)$hsmooth
else
berancv(x, t, d, dfr, x0, cvbootpars)$h
}
else {
if (local) {
if (lx0 != length(h)) stop("When 'local = TRUE', 'x0' and 'h' must have the same length")
h <- as.numeric(h[ordx0])
}
else {
h <- as.numeric(h)
}
}
lh <- length(h)
dfr <- dfr[order(dfr$t, 1 - dfr$d),]
if (conflevel < 0 | conflevel > 1) stop("'conflevel' must be a number between 0 and 1")
ltestimate <- length(testimate)
if (!is.null(testimate)) {
if (conflevel == 0)
warning("When 'testimate' is not NULL don't use the survival estimates for plotting")
else
stop("For plotting confidence bands 'testimate' must be NULL")
testimate <- as.numeric(testimate)
}
S <- .Call("berannp0",
dfr$t,
dfr$x,
dfr$d,
nrow,
x0,
lx0,
h,
lh,
local,
testimate,
ltestimate,
PACKAGE = "npcure")
if (local) {
names(S) <- paste("x", as.character(round(x0, 8)), sep = "")
}
else {
names(S) <- paste("h", as.character(round(h, 8)), sep = "")
for (i in 1:lh) {
if (lx0 == 1)
S[[i]] <- list(S[[i]])
names(S[[i]]) <- paste("x", as.character(round(x0, 8)), sep = "")
}
}
if (conflevel > 0) {
B <- cvbootpars$B
fpilot <- cvbootpars$fpilot
if (is.null(fpilot)) {
pilot <- hpilot(dfr$x, dfr$x, cvbootpars$nnfrac)
}
else
pilot <- do.call(fpilot, c(list(x0 = dfr$x), cvbootpars$dots))
probcurepilot <- as.numeric(probcure(x, t, d, dfr, dfr$x, pilot)$q)
band <- .Call("berannp0confband",
dfr$t,
dfr$x,
dfr$d,
nrow,
x0,
lx0,
h,
lh,
pilot,
probcurepilot,
1 - (1 - conflevel)/2,
B,
S,
local,
PACKAGE = "npcure")
if (local) {
names(band) <- paste("x", as.character(round(x0, 8)), sep = "")
for (i in 1:lx0) {
names(band[[i]]) <- c("lower", "upper")
}
}
else {
names(band) <- paste("h", as.character(round(h, 8)), sep = "")
for (i in 1:lh) {
names(band[[i]]) <- paste("x", as.character(round(x0, 8)), sep = "")
for (j in 1:lx0) {
names(band[[i]][[j]]) <- c("lower", "upper")
}
}
}
structure(list(type = "survival", local = local, h = h, x0 = x0, testim = dfr$t, S = S, conf = band, conflevel = conflevel), class = "npcure")
}
else {
structure(list(type = "survival", local = local, h = h, x0 = x0, testim = if (is.null(testimate)) dfr$t else testimate, S = S), class = "npcure")
}
} |
library(e1071)
duration = faithful$eruptions
plot(density(duration))
e1071::skewness(duration)
function |
data('mtcars')
mcor <-cor(mtcars)
round(mcor,digits=2)
library(xtable)
print(xtable(mcor), type='html', comment=F)
library(corrplot)
corrplot(mcor)
library(igraph)
gd <-graph(c(1,2, 2,3, 2,4, 1,4, 5,5, 3,6))
plot(gd)
gu <-graph(c(1,2, 2,3, 2,4, 1,4, 5,5, 3,6),directed=FALSE)
plot(gu,vertex.label=NA) |
partitionsNumber <- function(phylo, npart){
if (!is.rooted(phylo)) stop("The tree must be rooted !")
if (is.binary(phylo)){
update.partitionsNumber <- update.partitionsNumber.bin
} else {
if (!requireNamespace("combinat", quietly = TRUE)) {
stop("Pakage 'combinat' needed for function partitionsNumber to work on a non-binary tree. Please install it before running the function again.",
call. = FALSE)
}
update.partitionsNumber <- update.partitionsNumber.gen
}
phy <- reorder(phylo,"postorder")
ntaxa <- length(phy$tip.label)
nbrCompatiblePartitions <- init.partitionsNumber(phy,npart)
nbrCompatiblePartitions <- recursionUp(phy, nbrCompatiblePartitions, update.partitionsNumber)
attr(nbrCompatiblePartitions, "ntaxa") <- ntaxa
attr(nbrCompatiblePartitions, "npart") <- npart
class(nbrCompatiblePartitions) <- "partitionsNumber"
return(nbrCompatiblePartitions)
}
print.partitionsNumber <- function(x, ...){
cat(paste0("\nNumber of models with ", attr(x, "npart") - 1, " shifts: ", extract(x), ".\n\n"))
}
extract.partitionsNumber <- function(x,
node = attr(x, "ntaxa") + 1,
npart = attr(x, "npart"),
marked = FALSE, ...){
if (marked) return(x[node, attr(x, "npart") + npart])
return(x[node,npart])
}
init.partitionsNumber <- function(phy,npart){
ntaxa <- length(phy$tip.label)
nbrCompatiblePartitions <- matrix(NA, nrow = 1 + nrow(phy$edge), ncol = 2*npart)
nbrCompatiblePartitions[1:ntaxa, ] <- 0
nbrCompatiblePartitions[1:ntaxa, 1] <- rep(1,ntaxa)
nbrCompatiblePartitions[1:ntaxa, npart + 1] <- rep(1,ntaxa)
return(nbrCompatiblePartitions)
}
update.partitionsNumber.bin <- function(daughtersParams, ...){
npart <- dim(daughtersParams)[2]%/%2
if (npart == 1) return( c(1,1) )
nbrComp <- rep(NA, npart)
nbrMarkedComp <- rep(NA, npart)
nbrComp[1] <- 1; nbrMarkedComp[1] <- 1
left_nbrComp <- daughtersParams[1, 1:npart]
right_nbrComp <- daughtersParams[2, 1:npart]
left_nbrMarkedComp <- daughtersParams[1, (npart+1):(2*npart)]
right_nbrMarkedComp <- daughtersParams[2, (npart+1):(2*npart)]
for (k in 2:npart){
nbrComp[k] <- sum( left_nbrComp[1:(k-1)] * rev(right_nbrComp[1:(k-1)]) ) + sum( left_nbrMarkedComp[1:k] * rev(right_nbrMarkedComp[1:k]) )
nbrMarkedComp[k] <- sum( left_nbrComp[1:(k-1)] * rev(right_nbrMarkedComp[1:(k-1)]) ) + sum( right_nbrComp[1:(k-1)] * rev(left_nbrMarkedComp[1:(k-1)]) ) + sum( left_nbrMarkedComp[1:k] * rev(right_nbrMarkedComp[1:k]) )
}
nbrAdm <- c(nbrComp, nbrMarkedComp)
return(nbrAdm)
}
update.partitionsNumber.gen <- function(daughtersParams, ...){
npart <- dim(daughtersParams)[2]%/%2
if (npart == 1) return( c(1,1) )
nbrComp <- rep(NA, npart)
nbrMarkedComp <- rep(NA, npart)
nbrComp[1] <- 1; nbrMarkedComp[1] <- 1
N_daughters <- daughtersParams[, 1:npart]
A_daughters <- daughtersParams[, (npart+1):(2*npart)]
p <- dim(N_daughters)[1]
for (K in 2:npart){
N <- N_daughters[,1:K]
A <- A_daughters[,1:K]
nbrComp[K] <- sum.simplex(N, K, p) + sum.partitions(A, N, K, p, 2)
nbrMarkedComp[K] <- sum.partitions(A, N, K, p, 1)
}
nbrAdm <- c(nbrComp, nbrMarkedComp)
return(nbrAdm)
}
prod.index <- function(X,Id){
if (0 %in% Id) return(0)
return(prod(diag(X[,Id])))
}
sum.simplex <- function (NN, K, p) {
return(sum(combinat::xsimplex(p, K, fun = prod.index,
simplify = TRUE,
X = NN)))
}
sum.prod.comb <- function(I, A, N, K, p){
KK <- K + length(I) - 1
AN <- matrix(NA, nrow = p, ncol = K)
AN[I, ] <- A[I, ]
AN[-I, ] <- N[-I, ]
return(sum.simplex(AN, KK, p))
}
sum.partitions.cardFixed <- function(A, N, K, p, cardI){
return(sum(combinat::combn(p, cardI,
fun = sum.prod.comb,
simplify = TRUE,
A = A, N = N, K = K, p = p)))
}
sum.partitions <- function(A, N, K, p, m) {
return(sum(sapply(m:p, function(x) sum.partitions.cardFixed(A, N, K, p, x))))
}
complexity_break_point <- function(n){
return(floor((10 * n - 13 - sqrt(20 * n^2 - 20 * n + 9)) / 10) + 1)
} |
PlotDistribution <- function(PhyloExpressionSet,
legendName = "PS",
as.ratio = FALSE,
use.only.map = FALSE,
xlab = NULL,
ylab = NULL)
{
PhyloExpressionSet <- as.data.frame(PhyloExpressionSet)
PlotSelectedAgeDistr(ExpressionSet = PhyloExpressionSet,
gene.set = PhyloExpressionSet[ , 2],
legendName = legendName,
as.ratio = as.ratio,
use.only.map = use.only.map,
xlab = xlab,
ylab = ylab)
} |
rdistq_fit <- function(distribution, n, percentiles=c(0.05,0.5,0.95), quantiles,
relativeTolerance=0.05, tolConv=0.001, fit.weights=rep(1,length(percentiles)),
verbosity=1){
if (!requireNamespace("rriskDistributions", quietly = TRUE))
stop("Package \"rriskDistributions\" needed. Please install it, e.g. from
http://cran.r-project.org/src/contrib/Archive/rriskDistributions/",
call. = FALSE)
if(distribution=="triang"){
requiredPackage<-"mc2d"
if( !requireNamespace(requiredPackage, quietly = TRUE) )
stop("Package \"",requiredPackage,"\" needed for option distribution=", distribution, ". Please install it.",
call. = FALSE)
else
if( !paste("package",requiredPackage, sep=":") %in% search() ) attachNamespace(requiredPackage)
}
if(distribution=="gompertz"){
requiredPackage<-"eha"
if( !requireNamespace(requiredPackage, quietly = TRUE) )
stop("Package \"",requiredPackage,"\" needed for option distribution=", distribution, ". Please install it.",
call. = FALSE)
else
if( !paste("package",requiredPackage, sep=":") %in% search() ) attachNamespace(requiredPackage)
}
if(distribution=="pert"){
requiredPackage<-"mc2d"
if( !requireNamespace(requiredPackage, quietly = TRUE) )
stop("Package \"",requiredPackage,"\" needed for option distribution=", distribution, ". Please install it.",
call. = FALSE)
else
if( !paste("package",requiredPackage, sep=":") %in% search() ) attachNamespace(requiredPackage)
}
if(distribution=="tnorm"){
requiredPackage<-"msm"
if( !requireNamespace(requiredPackage, quietly = TRUE) )
stop("Package \"",requiredPackage,"\" needed for option distribution=", distribution, ". Please install it.",
call. = FALSE)
else
if( !paste("package",requiredPackage, sep=":") %in% search() ) attachNamespace(requiredPackage)
}
if ( length(percentiles) != length(quantiles) )
stop("length(percentiles) != length(quantiles)" )
if( any( any(percentiles < 0) || any(percentiles > 1) ) )
stop( "All elements of \"percentiles\" must lie between 0 and 1!")
capture.output(dists<-try(rriskDistributions::rriskFitdist.perc(p=percentiles,
q=quantiles,
show.output=TRUE,
tolConv=tolConv,
fit.weights=fit.weights)),
file=if(verbosity>1) stdout() else NULL)
if( inherits(dists, "try-error") )
stop(dists$message)
if(length(dists)==1 && is.na(dists))
stop("No distribution could be fitted at absolute convergence tolerance tolConv=", tolConv, ".")
possible_dists<-colnames(dists$results[,3:ncol(dists$results)])[which(!is.na(dists$results[1,3:ncol(dists$results)]))]
if( match(distribution, possible_dists, nomatch=0) ){
if(distribution=="norm")
x<-rnorm(n=n,
mean=dists$results[1,"norm"],
sd=dists$results[2,"norm"])
else if(distribution=="beta")
x<-rbeta(n=n,
shape1=dists$results[1,"beta"],
shape2=dists$results[2,"beta"])
else if(distribution=="cauchy")
x<-rcauchy(n=n,
location=dists$results[1,"cauchy"],
scale=dists$results[2,"cauchy"])
else if(distribution=="logis")
x<-rlogis(n=n,
location=dists$results[1,"logis"],
scale=dists$results[2,"logis"])
else if(distribution=="t")
x<-rt(n=n,
df=dists$results[1,"t"])
else if(distribution=="chisq")
x<-rchisq(n=n,
df=dists$results[1,"chisq"])
else if(distribution=="chisqnc")
x<-rchisq(n=n,
df=dists$results[1,"chisqnc"],
ncp=dists$results[2,"chisqnc"])
else if(distribution=="exp")
x<-rexp(n=n,
rate=dists$results[1,"exp"])
else if(distribution=="f")
x<-rf(n=n,
df1=dists$results[1,"f"],
df2=dists$results[2,"f"])
else if(distribution=="gamma")
x<-rgamma(n=n,
shape=dists$results[1,"gamma"],
rate=dists$results[2,"gamma"])
else if(distribution=="lnorm")
x<-rlnorm(n=n,
meanlog=dists$results[1,"lnorm"],
sdlog=dists$results[2,"lnorm"])
else if(distribution=="unif") {
x<-runif(n=n,
min=dists$results[1,"unif"],
max=dists$results[2,"unif"])
} else if(distribution=="weibull")
x<-rweibull(n=n,
shape=dists$results[1,"weibull"],
scale=dists$results[2,"weibull"])
else if(distribution=="triang")
x<-mc2d::rtriang(n=n,
min=dists$results[1,"triang"],
mode=dists$results[2,"triang"],
max=dists$results[3,"triang"])
else if(distribution=="gompertz")
x<-eha::rgompertz(n=n,
shape=dists$results[1,"gompertz"],
scale=dists$results[2,"gompertz"])
else if(distribution=="pert"){
x<-mc2d::rpert(n=n,
min=dists$results[1,"pert"],
mode=dists$results[2,"pert"],
max=dists$results[3,"pert"],
shape=dists$results[4,"pert"])
}
else if(distribution=="tnorm") {
x<-msm::rtnorm(n=n,
mean=dists$results[1,"tnorm"],
sd=dists$results[2,"tnorm"],
lower=dists$results[3,"tnorm"],
upper=dists$results[4,"tnorm"])
} else
stop("\"", distribution, "\" is not a valid distribution type.")
} else {
stop("\"", distribution, "\" distribution could not be fitted. One of the following should work:",
paste(possible_dists,collapse=", "))
}
quantiles_calc <- quantile(x=x, probs=percentiles)
percentiles_calc<-vapply(X=quantiles,
FUN.VALUE=percentiles[[1]],
FUN=function(x_) length(x[x<=x_])/n
)
for( j in seq(along=quantiles) ){
scale <- if( abs(quantiles[[j]]) > 0 ) abs(quantiles[[j]]) else NULL
if( !isTRUE( msg<-all.equal(quantiles[[j]], quantiles_calc[[j]], scale=scale, tolerance=relativeTolerance) ) ){
warning("Fitted value of ", 100*percentiles[[j]], "%-quantile: ", quantiles_calc[[j]], "\n ",
"Target value of ", 100*percentiles[[j]], "%-quantile: ", quantiles[[j]], "\n ",
"Fitted cumulative probability at value ", quantiles[[j]], " : ", percentiles_calc[[j]], "\n ",
"Target cumulative probability at value ", quantiles[[j]], " : ", percentiles[[j]], "\n ",
msg)
}
}
x
} |
test_that("Whether coordinate transformation works", {
cartesian <- data.table(X = c(0, 0, 0, 0, 0, 0, 0, 0),
Y = c(0, 0, 1, 1, 1, -1, -1, -1),
Z = c(0, 10, 0, 5, 10, 0, 5, 10))
anchor <- c(0, 0, 0)
to_test <- round(cartesian_to_polar(cartesian, anchor), 4)
polar <- data.table(zenith = c(NaN, 0, 90, 11.3099, 5.7106, 90.0000, 11.3099, 5.7106),
azimuth = c(0, 0, 90, 90, 90, 270, 270, 270),
distance = c(0.0000, 10.0000, 1.0000, 5.0990, 10.0499, 1.0000, 5.0990, 10.0499))
expect_equal(to_test, polar, info = "Transformation")
}) |
context("recordTable")
library(camtrapR)
data(camtraps)
data(recordTableSample)
camtraps_setup_blank <- camtraps
camtraps_retrieval_blank <- camtraps
camtraps_setup_blank$Setup_date[1] <- ""
camtraps_retrieval_blank$Retrieval_date[1] <- ""
recordTableSample_datetime_blank <- recordTableSample
recordTableSample_datetime_blank$DateTimeOriginal[1] <- ""
camtraps_setup_NA <- camtraps_setup_blank
camtraps_retrieval_NA <- camtraps_retrieval_blank
recordTableSample_datetime_NA <- recordTableSample_datetime_blank
camtraps_setup_NA$Setup_date[1] <- NA
camtraps_retrieval_NA$Retrieval_date[1] <- NA
recordTableSample_datetime_NA$DateTimeOriginal[1] <- NA
test_that("errors about blank values in Date/Time are correct", {
expect_error(surveyReport (recordTable = recordTableSample,
CTtable = camtraps_setup_blank,
speciesCol = "Species",
stationCol = "Station",
setupCol = "Setup_date",
retrievalCol = "Retrieval_date",
CTDateFormat = "%d/%m/%Y"),
"there are blank values in CTtable[, setupCol]", fixed = TRUE)
expect_error(surveyReport (recordTable = recordTableSample,
CTtable = camtraps_retrieval_blank,
speciesCol = "Species",
stationCol = "Station",
setupCol = "Setup_date",
retrievalCol = "Retrieval_date",
CTDateFormat = "%d/%m/%Y"),
"there are blank values in CTtable[, retrievalCol]", fixed = TRUE)
expect_error(surveyReport (recordTable = recordTableSample_datetime_blank,
CTtable = camtraps,
speciesCol = "Species",
stationCol = "Station",
setupCol = "Setup_date",
retrievalCol = "Retrieval_date",
CTDateFormat = "%d/%m/%Y"),
"there are blank values in recordTable[, recordDateTimeCol]", fixed = TRUE)
})
test_that("errors about NAs in Date/Time are correct", {
expect_error(surveyReport (recordTable = recordTableSample,
CTtable = camtraps_setup_NA,
speciesCol = "Species",
stationCol = "Station",
setupCol = "Setup_date",
retrievalCol = "Retrieval_date",
CTDateFormat = "%d/%m/%Y"),
"there are NAs in CTtable[, setupCol]", fixed = TRUE)
expect_error(surveyReport (recordTable = recordTableSample,
CTtable = camtraps_retrieval_NA,
speciesCol = "Species",
stationCol = "Station",
setupCol = "Setup_date",
retrievalCol = "Retrieval_date",
CTDateFormat = "%d/%m/%Y"),
"there are NAs in CTtable[, retrievalCol]", fixed = TRUE)
expect_error(surveyReport (recordTable = recordTableSample_datetime_NA,
CTtable = camtraps,
speciesCol = "Species",
stationCol = "Station",
setupCol = "Setup_date",
retrievalCol = "Retrieval_date",
CTDateFormat = "%d/%m/%Y"),
"there are NAs in recordTable[, recordDateTimeCol]", fixed = TRUE)
})
test_that("errors about all NAs in Date/Time are correct", {
expect_error(surveyReport (recordTable = recordTableSample,
CTtable = camtraps,
speciesCol = "Species",
stationCol = "Station",
setupCol = "Setup_date",
retrievalCol = "Retrieval_date",
CTDateFormat = "%d-%m-%Y"),
"Cannot read date format in CTtable[, setupCol]. Output is all NA.
expected: %d-%m-%Y
actual: 02/04/2009", fixed = TRUE)
expect_error(surveyReport (recordTable = recordTableSample,
CTtable = camtraps,
speciesCol = "Species",
stationCol = "Station",
setupCol = "Setup_date",
retrievalCol = "Retrieval_date",
CTDateFormat = "%d/%m/%Y",
recordDateTimeFormat = "%Y/%m/%d %H:%M:%S"),
"Cannot read datetime format in recordTable[, recordDateTimeCol]. Output is all NA.
expected: %Y/%m/%d %H:%M:%S
actual: 2009-04-21 00:40:00", fixed = TRUE)
}) |
synth.peak.error <- function(base=0.07,base.time=6, rise.time=5,
rise.factor, rise.factor2, recession.const=0.2, length.out=240,
rez.time=length.out-base.time-rise.time, err1.factor=c(1.2,1.4,1.6),
err2.factor = c(0.01,0.02,0.04), err3.factor=c(2,4,8), err4.factor =
c(9,18,27), err5.factor = c(0.1,0.2,0.4),err6.factor =c(1.5,2,3), err9.factor=c(2,3,4.5)){
n.errors <- 9
n.levels <- 6
peaks<-array(dim=c(2,n.errors,n.levels, length.out))
ref.peak <- synth.peak(base=base, base.time=base.time, rise.time=rise.time, rise.factor=rise.factor, recession.const=recession.const, length.out=length.out, rez.time=rez.time)
j=1
for(factor in err1.factor){
peaks[1,1,4-j,]<-synth.peak(rise.factor=factor*rise.factor, base=base, base.time=base.time, rise.time=rise.time, recession.const=recession.const, length.out=length.out, rez.time=rez.time)
if(factor>=rise.factor){
warning("In error type 1, factor larger than rise.factor. Adjusting for underestimation")
factor=0.95*rise.factor
}
peaks[1,1,3+j,]<-synth.peak(rise.factor=1/factor*rise.factor, base=base, base.time=base.time, rise.time=rise.time, recession.const=recession.const, length.out=length.out, rez.time=rez.time)
peaks[2,1,4-j,]<- ref.peak
peaks[2,1,3+j,]<- ref.peak
j=j+1
}
j=1
for(factor in err2.factor){
if(factor >= base){
warning("In peak type 2. err2.factor larger than base flow. Adjusting factor to avoid unexpected results")
factor <- 0.95 * base
}
peak.hight.from.base <- base*(rise.factor - 1)
rise.factor.adj <- 1+peak.hight.from.base / (base+factor)
peaks[1,2,4-j,] <- synth.peak(base=base+factor, base.time=base.time, rise.time=rise.time, rise.factor=rise.factor.adj, recession.const=recession.const, length.out=length.out, rez.time=rez.time)
rise.factor.adj <- 1+peak.hight.from.base / (base-factor)
peaks[1,2,3+j,]<-synth.peak(base=base-factor, base.time=base.time, rise.time=rise.time, rise.factor=rise.factor.adj, recession.const=recession.const, length.out=length.out, rez.time=rez.time)
peaks[2,2,4-j,]<- ref.peak
peaks[2,2,3+j,]<- ref.peak
j=j+1
}
j=1
for(factor in err3.factor){
peaks[1,3,4-j,]<-synth.peak(base=base, base.time=base.time, rise.time=rise.time, rise.factor=rise.factor, recession.const=recession.const/factor, length.out=length.out, rez.time=rez.time)
peaks[1,3,3+j,]<-synth.peak(base=base, base.time=base.time, rise.time=rise.time, rise.factor=rise.factor, recession.const=recession.const*factor, length.out=length.out, rez.time=rez.time)
if(diff(peaks[1,3,3+j,c(length.out-1, length.out)])==0){
warning("In peak type 3: very fast recession. Consider reducing err3.factor")
}
peaks[2,3,4-j,]<- ref.peak
peaks[2,3,3+j,]<- ref.peak
j=j+1
}
j=1
for(factor in err4.factor ){
peaks[1,4,4-j,]<-synth.peak(base=base, base.time=base.time+factor, rise.time=rise.time, rise.factor=rise.factor, recession.const=recession.const, length.out=length.out)
peaks[1,4,3+j,]<-synth.peak(base=base, base.time=base.time-factor, rise.time=rise.time, rise.factor=rise.factor, recession.const=recession.const, length.out=length.out)
peaks[2,4,4-j,]<- ref.peak
peaks[2,4,3+j,]<- ref.peak
j=j+1
}
plot.max=max(ref.peak)*2
to_opt<-function(par,factor){
test.peak <-synth.peak(base=base, base.time=base.time, rise.time=rise.time, rise.factor=factor*rise.factor, recession.const=par, length.out=length.out, rez.time=rez.time)
return(abs(sum(test.peak)-sum(ref.peak)))
}
j=1
for(factor in err5.factor){
r.opt<-optim(c(recession.const), to_opt, method="L-BFGS-B", lower=c(0), factor=(1+3*factor))
k_rez<-r.opt$par
peaks[1,5,4-j,]<-synth.peak(base=base, base.time=base.time, rise.time=rise.time, rise.factor=(1+3*factor)*rise.factor, recession.const=k_rez, length.out=length.out, rez.time=rez.time)
r.opt<-optim(c(0.2), to_opt, method="L-BFGS-B", lower=c(0), factor=1/(1+factor))
k_rez<-r.opt$par
peaks[1,5,3+j,]<-synth.peak(base=base, base.time=base.time, rise.time=rise.time, rise.factor=1/(1+factor)*rise.factor, recession.const=k_rez, length.out=length.out, rez.time=rez.time)
peaks[2,5,4-j,]<- ref.peak
peaks[2,5,3+j,]<- ref.peak
j=j+1
}
print("Check if peak volumes are correct for 'volume-optimized'
peaks:")
print(paste("Volume for reference peak: ", sum(ref.peak)))
print("Volumes for error peaks:")
print(rowSums(peaks[1,5,,]))
j=1
for(factor in err6.factor){
time.change=round(rise.time*factor,0)
peaks[1,6,4-j,]<-synth.peak(base=base, base.time=base.time-time.change, rise.time=rise.time+time.change, rise.factor=rise.factor, recession.const=recession.const/factor, length.out=length.out, rez.time=rez.time)
time.change=round(rise.time/factor,0)
peaks[1,6,3+j,]<-synth.peak(base=base, base.time=base.time+time.change, rise.time=rise.time-time.change, rise.factor=rise.factor, recession.const=recession.const*factor, length.out=length.out, rez.time=rez.time)
peaks[2,6,4-j,]<- ref.peak
peaks[2,6,3+j,]<- ref.peak
j=j+1
}
recession.const2=0.1*recession.const
base2=0.77*base
ref.peak4<- synth.peak(base=base2, base.time=-0.5, rise.time=0, rise.factor=rise.factor2, recession.const=recession.const2, length.out=length.out)
for(j in 1:6){
peaks[1,7,j,]<-peaks[1,2,j,]
peaks[2,7,j,]<- ref.peak4
}
j=1
for(factor in err9.factor){
peaks[1,9,4-j,]<- synth.peak(base=base2, base.time=-0.5, rise.time=0, rise.factor=rise.factor2+0.1*factor, recession.const=recession.const2/factor, length.out=length.out)
if(0.1*factor +1 >= rise.factor2){
warning("In peak type 9. (0.1*factor) >= rise.factor2 - 1. Adjusting factor to avoid unexpected results for underestimation")
factor = 9.5 * (rise.factor2-1)
}
peaks[1,9,3+j,]<- synth.peak(base=base2, base.time=-0.5, rise.time=0, rise.factor=rise.factor2-0.1*factor, recession.const=recession.const2*factor, length.out=length.out)
peaks[2,9,4-j,]<- ref.peak4
peaks[2,9,3+j,]<- ref.peak4
j=j+1
}
for(j in 1:6){
peaks[1,8,j,]<- peaks[1,9,j,]
peaks[2,8,j,]<- ref.peak
}
return(peaks)
} |
rtbs <- function(n,lambda=1,xi=1,beta=1,x=NULL,dist=dist.error("norm")) {
if(is.character(dist)) dist=dist.error(dist)
aux <- .test.tbs(lambda,xi,beta,x,type="r",n=n)
return(.rtbs(n,lambda,xi,aux$beta,aux$x,dist))
}
.rtbs <- function(n,lambda=1,xi=1,beta=1,x=NULL,dist=dist.error("norm")) {
aux2 <- c(x%*%beta)
erro <- dist$r(n,xi)
out <- exp(.g.lambda.inv(.g.lambda(aux2,lambda) + erro,lambda))
out <- ifelse(out == 0,10e-100,out)
return(out)
} |
context("finalfit function no metrics no keep")
library(finalfit)
test_that("finalfit.lm with metrics gives data.frame", {
expect_is(finalfit(colon_s, "nodes", "age.factor"), "data.frame")
})
test_that("finalfit.lmer with metrics gives data.frame", {
expect_is(finalfit(colon_s, "nodes", "age.factor", random_effect="hospital"), "data.frame")
})
test_that("finalfit.glm with metrics gives data.frame", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor"), "data.frame")
})
test_that("finalfit mixed with metrics gives data.frame", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor", random_effect="hospital"), "data.frame")
})
test_that("finalfit.coxph gives dataframe", {
expect_is(finalfit(colon_s, "Surv(time, status)", "age.factor"), "data.frame")
})
test_that("finalfit.glm with ff_remove_ref gives data.frame", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor", add_dependent_label = FALSE) %>%
ff_remove_ref(), "data.frame")
})
context("finalfit function no metrics keep models")
library(finalfit)
test_that("finalfit.lm with metrics gives data.frame", {
expect_is(finalfit(colon_s, "nodes", "age.factor", keep_models=TRUE), "data.frame")
})
test_that("finalfit.lm with metrics gives data.frame", {
expect_is(finalfit(colon_s, "nodes", "age.factor", "age.factor", keep_models=TRUE), "data.frame")
})
test_that("finalfit.lmer with metrics gives data.frame", {
expect_is(finalfit(colon_s, "nodes", "age.factor", random_effect="hospital", keep_models=TRUE), "data.frame")
})
test_that("finalfit.lmer with metrics gives data.frame", {
expect_is(finalfit(colon_s, "nodes", "age.factor", "age.factor", random_effect="hospital", keep_models=TRUE), "data.frame")
})
test_that("finalfit.glm with metrics gives data.frame", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor", keep_models=TRUE), "data.frame")
})
test_that("finalfit mixed with metrics gives data.frame", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor", random_effect="hospital", keep_models=TRUE), "data.frame")
})
test_that("finalfit.glm with metrics gives data.frame", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor", "age.factor", keep_models=TRUE), "data.frame")
})
test_that("finalfit mixed with metrics gives data.frame", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor", "age.factor", random_effect="hospital", keep_models=TRUE), "data.frame")
})
test_that("finalfit.coxph gives dataframe", {
expect_is(finalfit(colon_s, "Surv(time, status)", "age.factor", keep_models=TRUE), "data.frame")
})
test_that("finalfit.coxph gives dataframe", {
expect_is(finalfit(colon_s, "Surv(time, status)", "age.factor", "age.factor", keep_models=TRUE), "data.frame")
})
context("finalfit function no metrics no keep")
library(finalfit)
test_that("finalfit.lm with metrics gives list", {
expect_is(finalfit(colon_s, "nodes", "age.factor", metrics=TRUE), "list")
})
test_that("finalfit.lmer with metrics gives list", {
expect_is(finalfit(colon_s, "nodes", "age.factor", random_effect="hospital", metrics=TRUE), "list")
})
test_that("finalfit.glm with metrics gives list", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor", metrics=TRUE), "list")
})
test_that("finalfit mixed with metrics gives list", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor", random_effect="hospital", metrics=TRUE), "list")
})
test_that("finalfit.coxph gives dataframe", {
expect_is(finalfit(colon_s, "Surv(time, status)", "age.factor", metrics=TRUE), "list")
})
context("finalfit function metrics keep models")
library(finalfit)
test_that("finalfit.lm with metrics gives list", {
expect_is(finalfit(colon_s, "nodes", "age.factor", keep_models=TRUE, metrics=TRUE), "list")
})
test_that("finalfit.lmer with metrics gives list", {
expect_is(finalfit(colon_s, "nodes", "age.factor", random_effect="hospital", keep_models=TRUE, metrics=TRUE), "list")
})
test_that("finalfit.glm with metrics gives list", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor", keep_models=TRUE, metrics=TRUE), "list")
})
test_that("finalfit mixed with metrics gives list", {
expect_is(finalfit(colon_s, "mort_5yr", "age.factor", random_effect="hospital", keep_models=TRUE, metrics=TRUE), "list")
})
test_that("finalfit.coxph gives dataframe", {
expect_is(finalfit(colon_s, "Surv(time, status)", "age.factor", keep_models=TRUE, metrics=TRUE), "list")
})
context("summary_factorlist function")
library(finalfit)
test_that("summary_factorlist gives dataframe", {
expect_is(summary_factorlist(colon_s, "age", c("age.factor", "nodes"),
column=TRUE, total_col = TRUE, p=TRUE), "data.frame")
})
test_that("summary_factorlist gives dataframe", {
colon_s$one = 1
colon_s$one = factor(colon_s$one)
expect_is(summary_factorlist(colon_s, "one", c("age.factor", "nodes"),
column=TRUE, total_col = TRUE), "data.frame")
})
test_that("summary_factorlist gives dataframe", {
expect_is(summary_factorlist(colon_s, "mort_5yr", c("age.factor", "nodes"),
column=TRUE, total_col = TRUE, p=TRUE), "data.frame")
})
test_that("summary_factorlist gives dataframe", {
expect_is(summary_factorlist(colon_s, "rx", c("age.factor", "nodes"),
column=TRUE, total_col = TRUE, p=TRUE), "data.frame")
})
test_that("summary_factorlist gives dataframe", {
expect_is(summary_factorlist(colon_s, "extent.factor", c("age.factor", "nodes"),
column=TRUE, total_col = TRUE, p=TRUE), "data.frame")
})
test_that("summary_factorlist gives dataframe", {
colon_s$age5 = cut(colon_s$age, breaks=5)
expect_is(summary_factorlist(colon_s, "age5", c("age.factor", "nodes"),
column=TRUE, total_col = TRUE, p=TRUE), "data.frame")
})
context("summary_factorlist function with geometric mean")
library(finalfit)
test_that("summary_factorlist gives dataframe", {
expect_is(summary_factorlist(colon_s, "extent.factor", c("age.factor", "age"),
cont="geometric"), "data.frame")
})
context("summary_factorlist function with median and dep label")
library(finalfit)
test_that("summary_factorlist gives dataframe", {
expect_is(summary_factorlist(colon_s, "age", c("age.factor", "nodes"),
cont="median", add_dependent_label=TRUE, fit_id=TRUE), "data.frame")
})
test_that("summary_factorlist gives dataframe", {
colon_s$one = 1
colon_s$one = factor(colon_s$one)
expect_is(summary_factorlist(colon_s, "one", c("age.factor", "nodes"),
cont="median", add_dependent_label=TRUE, fit_id=TRUE), "data.frame")
})
test_that("summary_factorlist gives dataframe", {
expect_is(summary_factorlist(colon_s, "mort_5yr", c("age.factor", "nodes"),
cont="median", add_dependent_label=TRUE, fit_id=TRUE), "data.frame")
})
test_that("summary_factorlist gives dataframe", {
expect_is(summary_factorlist(colon_s, "rx", c("age.factor", "nodes"),
cont="median", add_dependent_label=TRUE, fit_id=TRUE), "data.frame")
})
test_that("summary_factorlist gives dataframe", {
expect_is(summary_factorlist(colon_s, "extent.factor", c("age.factor", "nodes"),
cont="median", add_dependent_label=TRUE, fit_id=TRUE), "data.frame")
})
test_that("summary_factorlist gives dataframe", {
colon_s$age5 = cut(colon_s$age, breaks=5)
expect_is(summary_factorlist(colon_s, "age5", c("age.factor", "nodes"),
cont="median", add_dependent_label=TRUE, fit_id=TRUE), "data.frame")
})
context("summary_factorlist function with survival")
library(finalfit)
test_that("summary_factorlist with survival dataframe", {
expect_is(summary_factorlist(colon_s, "Surv(time, status)", "age.factor"), "data.frame")
})
context("summary_factorlist warnings")
library(finalfit)
test_that("summary_factorlist warnings", {
expect_error(summary_factorlist(1))
expect_error(summary_factorlist(colon_s, "rx"))
})
context("summary_factorlist cont_cut")
library(finalfit)
test_that("summary_factorlist convert factor", {
expect_equal(summary_factorlist(colon_s, "mort_5yr", "sex") %>%
dim() %>%
sum(), 6)
})
test_that("summary_factorlist don't convert factor", {
expect_equal(summary_factorlist(colon_s, "mort_5yr", "sex", cont_cut=0) %>%
dim() %>%
sum(), 5)
})
context("finalfit_permute")
library(finalfit)
test_that("finalfit_permute gives a list", {
expect_is(ff_permute(
colon_s,
"nodes",
c("age.factor"),
c("obstruct.factor", "perfor.factor"),
multiple_tables = TRUE,
base_on_top = TRUE
), "list")
})
test_that("finalfit_permute gives a list", {
expect_is(ff_permute(
colon_s,
"nodes",
c("age.factor"),
c("obstruct.factor", "perfor.factor"),
multiple_tables = TRUE,
base_on_top = FALSE
), "list")
})
test_that("finalfit_permute gives a list", {
expect_is(ff_permute(
colon_s,
"nodes",
c("age.factor"),
c("obstruct.factor", "perfor.factor"),
multiple_tables = FALSE,
base_on_top = FALSE
), "data.frame")
})
test_that("finalfit_permute gives a list", {
expect_is(ff_permute(
colon_s,
"nodes",
c("age.factor"),
c("obstruct.factor", "perfor.factor"),
multiple_tables = FALSE,
base_on_top = TRUE
), "data.frame")
})
test_that("finalfit_permute gives a list", {
expect_is(ff_permute(
colon_s,
"nodes",
c("age.factor"),
c("obstruct.factor", "perfor.factor"),
multiple_tables = TRUE,
include_base_model = FALSE,
include_full_model = FALSE
), "list")
})
test_that("finalfit_permute gives a list", {
expect_is(ff_permute(
colon_s,
"nodes",
c("age.factor"),
c("obstruct.factor", "perfor.factor"),
multiple_tables = FALSE,
include_base_model = FALSE,
include_full_model = FALSE
), "data.frame")
}) |
calc.a <- function(y, mu, sf) {
n <- length(y)
if (length(mu) == 1) {
mu <- rep(mu, n)
}
if (length(sf) == 1) {
sf <- rep(sf, n)
}
a.vec <- optimize(calc.loglik.a, interval = c(0, var(y/sf)/mean(y/sf)^2),
y = y, mu = mu, sf = sf)
a <- a.vec$minimum
a.loglik <- a.vec$objective
min.a <- -calc.loglik.a(1e-05, y, mu, sf)
mle.a <- -calc.loglik.a(a, y, mu, sf)
max.a <- -calc.loglik.a(var(y/sf)/mean(y/sf)^2, y, mu, sf)
if (mle.a - min.a < 0.5) {
if (mle.a-max.a > 10) {
a.max <- uniroot(function(x) calc.loglik.a(x, y, mu, sf) + mle.a - 10,
c(1e-05, var(y/sf)/mean(y/sf)^2))$root
} else {
a.max <- var(y/sf)/mean(y/sf)^2
}
samp <- (exp((exp(ppoints(100))-1)/2)-1)*a.max
loglik <- mapply(calc.loglik.a, a = samp,
MoreArgs = list(y = y,
mu = mu,
sf = sf))
loglik2 <- exp(-loglik-min(-loglik))
loglik3 <- loglik2/sum(loglik2)
a <- mean(sample(samp, 10000, replace = TRUE, prob = loglik3))
a.loglik <- calc.loglik.a(a, y, mu, sf)
}
return(c(1/a, a.loglik))
}
calc.b <- function(y, mu, sf) {
n <- length(y)
if (length(mu) == 1) {
mu <- rep(mu, n)
}
if (length(sf) == 1) {
sf <- rep(sf, n)
}
if (sum(mu) == 0) {
return(c(0, 0))
}
b.vec <- optimize(calc.loglik.b, interval = c(0, var(y/sf)/mean(y/sf)), y = y, mu = mu,
sf = sf)
b <- b.vec$minimum
b.loglik <- b.vec$objective
min.b <- -calc.loglik.b(1e-05, y, mu, sf)
mle.b <- -calc.loglik.b(b, y, mu, sf)
max.b <- -calc.loglik.b(var(y/sf)/mean(y/sf), y, mu, sf)
if (mle.b - min.b < 0.5) {
if (mle.b-max.b > 10) {
b.max <- uniroot(function(x) calc.loglik.b(x, y, mu, sf) + mle.b - 10,
c(1e-05, var(y/sf)/mean(y/sf)))$root
} else {
b.max <- var(y/sf)/mean(y/sf)
}
samp <- (exp((exp(ppoints(100))-1)/2)-1)*b.max
loglik <- mapply(calc.loglik.b, b = samp,
MoreArgs = list(y = y,
mu = mu,
sf = sf))
loglik2 <- exp(-loglik-min(-loglik))
loglik3 <- loglik2/sum(loglik2)
b <- mean(sample(samp, 10000, replace = TRUE, prob = loglik3))
b.loglik <- calc.loglik.b(b, y, mu, sf)
}
return(c(1/b, b.loglik))
}
calc.k <- function(y, mu, sf) {
n <- length(y)
if (length(mu) == 1) {
mu <- rep(mu, n)
}
if (length(sf) == 1) {
sf <- rep(sf, n)
}
k.vec <- optimize(calc.loglik.k, interval = c(0, var(y/sf)), y = y, mu = mu,
sf = sf)
k <- k.vec$minimum
k.loglik <- k.vec$objective
min.k <- -calc.loglik.k(1e-05, y, mu, sf)
mle.k <- -calc.loglik.k(k, y, mu, sf)
max.k <- -calc.loglik.k(var(y/sf), y, mu, sf)
if (mle.k - min.k < 0.5) {
if (mle.k-max.k > 10) {
k.max <- uniroot(function(x) calc.loglik.k(x, y, mu, sf) + mle.k - 10,
c(1e-05, var(y/sf)))$root
} else {
k.max <- var(y/sf)
}
samp <- (exp((exp(ppoints(100))-1)/2)-1)*k.max
loglik <- mapply(calc.loglik.k, k = samp,
MoreArgs = list(y = y,
mu = mu,
sf = sf))
loglik2 <- exp(-loglik-min(-loglik))
loglik3 <- loglik2/sum(loglik2)
k <- mean(sample(samp, 10000, replace = TRUE, prob = loglik3))
k.loglik <- calc.loglik.k(k, y, mu, sf)
}
return(c(k, k.loglik))
} |
is_integer <- function(x) {
is.numeric(x) && x %% 1 == 0
}
is_count <- function(x) {
is_integer(x) && x > 0
}
is_date <- function(x) {
class(x) == "Date"
} |
clear_legend <- function( map_id, layer_id ) {
invoke_method( map_id, "md_clear_legend", layer_id );
}
mapdeck_legend <- function(legend_elements) UseMethod("mapdeck_legend")
mapdeck_legend.mapdeck_legend <- function( legend_elements ) jsonify::to_json(legend_elements)
mapdeck_legend.default <- function( legend_elements ) {
stop("mapdeck - mapdeck_legend will only work on objects created with legend_element")
}
legend_element <- function(
variables,
colours,
colour_type = c("fill", "stroke"),
variable_type = c("category", "gradient"),
title = "",
css = ""
) {
if( length( colours ) != length( variables ) ) {
stop("mapdeck - colours and variables should be the same length")
}
colour_type <- legend_colour_type( colour_type )
l <- list(
colour = colours
, variable = variables
, colourType = colour_type
, type = variable_type
, title = title
, css = css
)
l <- list( l )
names(l) <- colour_type
attr(l, "class") <- c("mapdeck_legend", attr(l, "class"))
return(l)
}
legend_colour_type <- function( colour_type ) {
switch(
colour_type
, "fill" = "fill_colour"
, "stroke" = "stroke_colour"
)
}
aggregation_legend <- function( legend, legend_options ) {
if( is.null( legend_options ) ) {
legend_options <- list(
css = ""
, title = "value"
, digits = 2
)
}
if( is.null( legend_options[["css"]] ) ) {
legend_options[["css"]] <- ""
}
if( is.null( legend_options[["title"]] ) ) {
legend_options[["title"]] <- "value"
}
if( is.null( legend_options[["digits"]] ) ) {
legend_options[["digits"]] <- 2
}
legend <- list(
legend = legend
, css = legend_options[["css"]]
, title = legend_options[["title"]]
, digits = legend_options[["digits"]]
)
return( legend )
} |
semMatrixAlgebra <- function(object, algebra, group, simplify = TRUE, model, endoOnly = FALSE)
{
call <- paste(deparse(substitute(object)), collapse = "")
if (grepl("\\+",call))
{
args <- unlist(strsplit(call,split="\\+"))
obs <- lapply(args,function(x)semPlotModel(eval(parse(text=x))))
object <- obs[[1]]
for (i in 2:length(obs)) object <- object + obs[[i]]
}
if ("lisrel"%in%class(object)) object <- object$matrices
if (!"semMatrixModel"%in%class(object))
{
if (missing(model))
{
if (any(grepl("(LY)|(TE)|(PS)|(BE)|(LX)|(TD)|(PH)|(GA)|(TY)|(TX)|(AL)|(KA)",deparse(substitute(algebra))))) {
model <- "lisrel"
message("model set to 'lisrel'")
} else if (any(grepl("(Lambda)|(Nu)|(Theta)|(Kappa)|(Alpha)|(Beta)|(Gamma)|(Psi)",deparse(substitute(algebra)))))
{
model <- "mplus"
message("model set to 'mplus'")
} else if (any(grepl("A|S|F",deparse(substitute(algebra)))))
{
model <- "ram"
message("model set to 'ram'")
} else stop("'model' could not be detected")
}
object <- modelMatrices(object,model,endoOnly = endoOnly)
}
stopifnot("semMatrixModel"%in%class(object))
if (missing(group)) group <- seq_len(max(sapply(object,length)))
Mats <- lapply(object,lapply,'[[','est')
Res <- list()
for (i in seq_along(group))
{
GroupMats <- lapply(Mats,'[[',i)
Res[[i]] <- eval(substitute(algebra), GroupMats)
}
if (simplify) if (length(Res)==1) Res <- Res[[1]]
return(Res)
} |
max_threshold_diffcov <- function(sample1, sample2, sig_mat1, sig_mat2){
n1 <- dim(sample1)[1]; n2 <- dim(sample2)[1]; p <- dim(sample1)[2]
a_f <- sqrt(2*log(log(p)))
b_f <- 2*log(log(p)) + 0.5*log(log(log(p))) - 0.5*log(4*3.1416/(1 - 0.05)^2)
eta <- 0.05
diag1 <- diag(sig_mat1)
diag1[diag1 <= 10^(-10)] <- 10^(-10)
diag2 <- diag(sig_mat2)
diag2[diag2 <= 10^(-10)] <- 10^(-10)
T_orig <- (colMeans(sample1) - colMeans(sample2))^2/(diag1/n1 + diag2/n2)
s_level <- T_orig[sign(T_orig) >= 0.01 & T_orig <= 2*(1 - eta)*log(p)]
s_m <- matrix(s_level, length(s_level), p, byrow = F)
T_m <- matrix((T_orig-1), length(s_level), p, byrow = T)
T_m[sign(T_m + 1 - s_m) == -1] <- 0
thr <- rowSums(T_m)
mean_thr <- 2*sqrt(s_level)*dnorm(sqrt(s_level))*p
sd_thr <- sqrt(p*(2*((sqrt(s_level))^3 + sqrt(s_level))*dnorm(sqrt(s_level)) + 4 - 4*pnorm(sqrt(s_level))) - mean_thr^2/p)
max_threshold <- max((thr-mean_thr)/sd_thr)*a_f - b_f
return(max_threshold)
} |
plotGAM <- function(gamFit, smooth.cov ,
groupCovs = NULL, orderedAsFactor = T,
rawOrFitted = F, plotCI = T) {
if (missing(gamFit)) {
stop("gamFit is missing")}
if (missing(smooth.cov)) {
stop("smooth.cov is missing")}
if (class(smooth.cov) != "character") {
stop("smooth.cov must be a character")}
if (class(groupCovs) != "character" & (!is.null(groupCovs))) {
stop("groupCovs must be a character")}
if (!(rawOrFitted == F | rawOrFitted == "raw" | rawOrFitted == "fitted")) {
stop("Wrong input for rawOrFitted")
}
fit <- fitted <- group <- se.fit <- NULL
if (base::class(gamFit)[1] != "gam") {
stop("gamFit is not a object of type gam")
}
if (base::is.null(groupCovs)) {
gam <- gamFit
temp.data <- gam$model
old.formula <- gam$formula
old.covariates <- base::as.character(old.formula)[3]
old.covariates <- base::gsub(" ", "", old.covariates)
main.smooth <- base::paste0("s(", smooth.cov)
interaction.smooth <- base::paste0("s(", smooth.cov, ",by=")
if (!base::grepl(pattern = main.smooth, old.covariates, fixed=T)) {
base::stop("smooth.cov is not included in formula for original model fit")
}
if (base::grepl(pattern = interaction.smooth, old.covariates, fixed=T)) {
base::stop("smooth.cov has an interaction term in original model fit, pass groupCovs as an argument")
}
plot.df = base::data.frame( x = base::seq(min(temp.data[smooth.cov]),
max(temp.data[smooth.cov]),
length.out=200))
base::names(plot.df) <- smooth.cov
for (i in base::names(temp.data)[-1]) {
if (i != smooth.cov) {
if (base::any(base::class(temp.data[i][,1])[1] == c("numeric", "integer","boolean"))) {
plot.df[, base::dim(plot.df)[2] + 1] <- base::mean(temp.data[i][,1])
base::names(plot.df)[base::dim(plot.df)[2]] <- i
}
else if (base::any(base::class(temp.data[i][,1])[1] == c("character", "factor","ordered"))) {
plot.df[, base::dim(plot.df)[2] + 1] <- temp.data[i][1,1]
base::names(plot.df)[base::dim(plot.df)[2]] <- i
}
else {
stop(base::paste("Unrecognized data type for",i,"please refit cluster model with different datatype"))
}
}
}
for (i in 1:dim(plot.df)[2]) {
if (class(plot.df[,i])[1] == "ordered" | class(plot.df[,i])[1] == "factor") {
warning("There are one or more factors in the model fit, please consider plotting by group since plot might be unprecise")
}
}
plot.df = base::cbind(plot.df, base::as.data.frame(mgcv::predict.gam(gam, plot.df, se.fit = TRUE)))
if (plotCI) {
plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1]))
+ ggplot2::geom_line(ggplot2::aes(y=fit), size=1)
+ ggplot2::geom_ribbon(data=plot.df, ggplot2::aes(ymax = fit+1.96*se.fit, ymin = fit-1.96*se.fit, linetype=NA), alpha = .2)
+ ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")"))
+ ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2]))
+ ggplot2::xlab(base::paste0("s(",smooth.cov,")"))
+ ggplot2::theme_bw())
}
else {
plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1]))
+ ggplot2::geom_line(ggplot2::aes(y=fit), size=1)
+ ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")"))
+ ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2]))
+ ggplot2::xlab(base::paste0("s(",smooth.cov,")"))
+ ggplot2::theme_bw())
}
if (rawOrFitted == "raw") {
plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x=purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1]))
base::return(plot)
}
else if (rawOrFitted == "fitted") {
temp.data$fitted <- gam$fitted.values
plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x=purrr::as_vector(temp.data[smooth.cov]), y=fitted))
base::return(plot)
}
else {
base::return(plot)
}
}
else if (base::is.character(groupCovs)) {
gam <- gamFit
temp.data <- gam$model
old.formula <- gam$formula
old.covariates <- base::as.character(old.formula)[3]
old.covariates <- base::gsub(" ", "", old.covariates)
main.smooth <- base::paste0("s(", smooth.cov)
interaction.smooth <- base::paste0("s(", smooth.cov, ",by=")
if(regexpr(groupCovs, as.character(old.covariates))[1] == 1) {
old.covariates <- paste0("+", old.covariates)
}
main.group <- base::paste0("+", groupCovs)
if (!base::grepl(pattern = main.group, old.covariates, fixed=T)) {
base::stop("Error groupCovs is not included as a main effect in original model, include in original fit")
}
temp.fm <- strsplit(old.covariates, split='+', fixed = T)[[1]]
for (i in 1:length(temp.fm)) {
if (grepl(main.smooth, temp.fm[i], fixed=T)) {
temp.term <- strsplit(temp.fm[i], split=',', fixed = T)[[1]]
if (length(temp.term) > 1) {
for (j in 2:length(temp.term)) {
if (grepl('=',temp.term[j])) {
if(grepl('by',temp.term[j])) {
order <- 1:length(temp.term)
order <- setdiff(order, j)
if (all(order == 1)) {
order <- c(1,2)
temp.term <- temp.term[order]
}
else {
order <- c(order, NA)
order <- order[c(1, length(order), 2:(length(order) - 1))]
order[2] <- j
temp.term <- temp.term[order]
temp.term <- gsub(pattern=")", replacement = "", x = temp.term)
temp.term[length(temp.term)]<- paste0(temp.term[length(temp.term)], ")")
}
}
}
else {
base::stop("spline containing smooth.cov has more than one variable, refit with only one")
}
}
}
temp.fm[i] <- toString(temp.term)
}
}
old.covariates <- paste0(temp.fm, collapse="+")
old.covariates <- base::gsub(" ", "", old.covariates)
if (!base::grepl(pattern = main.smooth, old.covariates, fixed=T) & base::class(temp.data[groupCovs][,1])[1] == "ordered") {
base::stop("smooth.cov is not included in formula for original model fit, model might be incorrectly parametrized")
}
else if (!base::grepl(pattern = interaction.smooth, old.covariates, fixed=T)) {
base::warning("smooth.cov has no interaction term in original model fit")
foo <- base::seq(min(temp.data[smooth.cov]), max(temp.data[smooth.cov]), length.out=200)
plot.df = base::data.frame( x = rep(foo, nlevels(as.factor(temp.data[groupCovs][,1]))))
base::names(plot.df) <- smooth.cov
plot.df$temp <- rep(levels(as.factor(temp.data[groupCovs][,1])), each = 200)
base::names(plot.df)[2] <- groupCovs
for (i in base::names(temp.data)[-1]) {
if (!(i == smooth.cov | i == groupCovs)) {
if (base::any(base::class(temp.data[i][,1])[1] == c("numeric", "integer","boolean"))) {
plot.df[, base::dim(plot.df)[2] + 1] <- base::mean(temp.data[i][,1])
base::names(plot.df)[base::dim(plot.df)[2]] <- i
} else if (base::any(base::class(temp.data[i][,1])[1] == c("character", "factor","ordered"))) {
plot.df[, base::dim(plot.df)[2] + 1] <- temp.data[i][1,1]
base::names(plot.df)[base::dim(plot.df)[2]] <- i
} else {
stop(base::paste("Unrecognized data type for",i,"please refit cluster model with different datatype"))
}
}
}
plot.df = base::cbind(plot.df, base::as.data.frame(mgcv::predict.gam(gam, plot.df, se.fit = TRUE)))
plot.df$group <- plot.df[,2]
if (plotCI) {
plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1]))
+ ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1)
+ ggplot2::geom_ribbon(data=plot.df, ggplot2::aes(ymax = fit+1.96*se.fit, ymin = fit-1.96*se.fit, col=factor(group), linetype=NA), alpha = .2)
+ ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")"))
+ ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2]))
+ ggplot2::xlab(base::paste0("s(",smooth.cov,")"))
+ ggplot2::scale_colour_discrete(name = groupCovs)
+ ggplot2::theme_bw())
} else {
plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1]))
+ ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1)
+ ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")"))
+ ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2]))
+ ggplot2::xlab(base::paste0("s(",smooth.cov,")"))
+ ggplot2::scale_colour_discrete(name = groupCovs)
+ ggplot2::theme_bw())
}
if (rawOrFitted == "raw") {
plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x=purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1], col=temp.data[groupCovs][,1]))
base::return(plot)
}
else if (rawOrFitted == "fitted") {
temp.data$fitted <- gam$fitted.values
plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x=purrr::as_vector(temp.data[smooth.cov]), y=fitted, col=temp.data[groupCovs][,1]))
base::return(plot)
}
else {
base::return(plot)
}
}
else {
main.group <- base::paste0("+", groupCovs)
if (!base::grepl(pattern = main.group, old.covariates, fixed=T)) {
base::stop("groupCovs is not included as main effect in original model, please include in original fit")
}
if (base::class(temp.data[groupCovs][,1])[1] == "ordered" & orderedAsFactor) {
base::warning("groupCovs is an ordered variable in original fit, reffiting model with groupCovs as a factor")
temp.data[groupCovs] <- as.factor(as.character(temp.data[groupCovs][,1]))
textCall <- gam$call
temp.fm.updated <- strsplit(old.covariates, split='+', fixed = T)[[1]]
index.Main <- setdiff(grep(pattern = main.smooth, x = temp.fm.updated, fixed = T),
grep(pattern = interaction.smooth, x = temp.fm.updated, fixed = T))
temp.fm.updated <- temp.fm[-index.Main]
updatedCovs <- paste0(temp.fm.updated, collapse="+")
updatedCovs <- base::gsub(" ", "", updatedCovs)
updatedformula <- stats::as.formula(paste(old.formula[2], old.formula[1], updatedCovs))
new.data <- temp.data
gam <- stats::update(gam, formula = updatedformula, data = new.data)
}
temp.data <- gam$model
old.formula <- gam$formula
old.covariates <- base::as.character(old.formula)[3]
old.covariates <- base::gsub(" ", "", old.covariates)
main.smooth <- base::paste0("s(", smooth.cov, ")")
interaction.smooth <- base::paste0("s(", smooth.cov, ",by=")
foo <- base::seq(min(temp.data[smooth.cov]), max(temp.data[smooth.cov]), length.out=200)
plot.df = base::data.frame( x = rep(foo, nlevels(temp.data[groupCovs][,1])))
base::names(plot.df) <- smooth.cov
plot.df$temp <- rep(levels(temp.data[groupCovs][,1]), each = 200)
base::names(plot.df)[2] <- groupCovs
for (i in base::names(temp.data)[-1]) {
if (!(i == smooth.cov | i == groupCovs)) {
if (base::any(base::class(temp.data[i][,1])[1] == c("numeric", "integer","boolean"))) {
plot.df[, base::dim(plot.df)[2] + 1] <- base::mean(temp.data[i][,1])
base::names(plot.df)[base::dim(plot.df)[2]] <- i
} else if (base::any(base::class(temp.data[i][,1])[1] == c("character", "factor","ordered"))) {
plot.df[, base::dim(plot.df)[2] + 1] <- temp.data[i][1,1]
base::names(plot.df)[base::dim(plot.df)[2]] <- i
} else {
stop(base::paste("Unrecognized data type for",i,"please refit cluster model with different datatype"))
}
}
}
plot.df = base::cbind(plot.df, base::as.data.frame(mgcv::predict.gam(gam, plot.df, se.fit = TRUE)))
plot.df$group <- plot.df[,2]
if (plotCI) {
plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1]))
+ ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1)
+ ggplot2::geom_ribbon(data=plot.df, ggplot2::aes(ymax = fit+1.96*se.fit, ymin = fit-1.96*se.fit, col=factor(group), linetype=NA), alpha = .2)
+ ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")"))
+ ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2]))
+ ggplot2::xlab(base::paste0("s(",smooth.cov,")"))
+ ggplot2::scale_colour_discrete(name = groupCovs)
+ ggplot2::theme_bw())
} else {
plot <- (ggplot2::ggplot(data=plot.df, ggplot2::aes(x=plot.df[,1]))
+ ggplot2::geom_line(ggplot2::aes(y=fit, col=factor(group)), size=1)
+ ggplot2::ggtitle(base::paste0(base::as.character(old.formula)[2], " vs. s(",smooth.cov,")"))
+ ggplot2::ylab(base::paste0("Predicted ", base::as.character(old.formula)[2]))
+ ggplot2::xlab(base::paste0("s(",smooth.cov,")"))
+ ggplot2::scale_colour_discrete(name = groupCovs)
+ ggplot2::theme_bw())
}
if (rawOrFitted == "raw") {
plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x= purrr::as_vector(temp.data[smooth.cov]), y=temp.data[,1], col=temp.data[groupCovs][,1]))
base::return(plot)
} else if (rawOrFitted == "fitted") {
temp.data$fitted <- gam$fitted.values
plot <- plot + ggplot2::geom_point(data = temp.data, ggplot2::aes(x= purrr::as_vector(temp.data[smooth.cov]), y=fitted, col=temp.data[groupCovs][,1]))
base::return(plot)
} else {
base::return(plot)
}
}
}
else {
stop("groupCovs is not a character or null please correct")
}
} |
print.nonp<-function(x, digits = getOption("digits"), prefix = "\t\t",...){
cat("\n")
theme<-strwrap(x$method, prefix = prefix)
if(!is.null(x$score)){
if(x$score %in% c("pearson", "spearman", "kendall"))
theme<-c(theme,paste("with",x$score,"measurement"))
else
theme<-c(theme,paste("using",x$score,"scoring"))
}
cat(theme,"\n")
out <- character()
if (!is.null(x$stat))
out <- c(out, paste(names(x$stat), "=", format(x$stat, digits = max(1L, digits - 2L))))
if (!is.null(x$pval)) {
fp <- paste(format.pval(x$pval, digits = max(1L, digits - 3L)))
if(!is.null(attr(x$pval,"type"))){
if(attr(x$pval,"type")%in%c("W","R","S"))
out <- c(out,paste(names(x$pval),switch(attr(x$pval,"type"),"W"="without replacement","S"="without replacement","R"="with replacement"),paste("method to calculate :\n\t",if(!is.null(attr(x$pval,"df"))){paste("df = ",attr(x$pval,"df"),",")}, "p-value = ",sep=""), if (startsWith(fp, "<")) fp else paste(fp)))
else
out <- c(out,paste(attr(x$pval,"type"),names(x$pval),paste("method to calculate :\n\t", if(!is.null(attr(x$pval,"df"))){paste("df = ",attr(x$pval,"df"),",")},"p-value = ",sep=""),if (startsWith(fp, "<")) fp else paste (fp)))
}
else
out <- c(out,paste(names(x$pval),paste("method to calculate :\n\t", if(!is.null(attr(x$pval,"df"))){paste("df = ",attr(x$pval,"df"),",")}, "p-value = ",sep=""), if (startsWith(fp, "<")) fp else paste(fp)))
}
cat(paste(out, collapse = "\n"),sep = "\n")
if (is.null(x$alternative)) {
cat("alternative hypothesis: \n\t")
alt.char <- switch(attr(x$null.value,"direction"), two.sided = "not equal to", less = "less than", greater = "greater than")
cat(x$null.value[1], " is ", alt.char, " ", x$null.value[2], "\n", sep = "")
}
else if(is.null(x$null.value)) cat("alternative hypothesis: \n\t",x$alternative, "\n", sep = "")
if (!is.null(x$conf.int)) {
cat(format(100 * attr(x$conf.int, "conf.level")),
"% confidence interval of p-value :\n\t",
paste("[",format(x$conf.int[1], digits = digits-3L), ",",format(x$conf.int[2], digits = digits-3L), "]",collapse = " "),
"\n", sep = "")
}
if(!is.null(x$addition)) cat("\n",x$addition)
if(!is.null(x$alternative) & !is.null(x$null.value)){warning("Alternative and null.value both exist, so output from null.value disabled.")}
cat("\n")
invisible(x)
}
plot.emcdf<-function(x,...){
data<-x
x<-data$sample
n=length(x)
max_x <- max(x)
min_x <- min(x)
rangex <- max_x - min_x
start <- min_x - rangex/n
final <- max_x + rangex/n
x1=c(start, sort(x), final)
y1=c(0, data$empirical.cdf, 1)
lower_plot <- c(0,data$lower,1)
upper_plot <- c(0,data$upper,1)
plot(x1,y1, type='S', xlab='Cycles', ylab='Probability', main='Empirical Distribution',...)
lines(x1, upper_plot, lty=2,type='S', col='red')
lines(x1, lower_plot, lty=2,type='S', col='blue')
legend("bottomright", lty=c(1,2,2), col=c('black', 'red', 'blue'), c('EM-CDF', 'Upper', 'Lower'), cex=0.8)
} |
context("Test bart_ewmv")
library(hBayesDM)
test_that("Test bart_ewmv", {
skip_on_cran()
expect_output(bart_ewmv(
data = "example", niter = 10, nwarmup = 5, nchain = 1, ncore = 1))
}) |
get_user_timeline <-
function(x,
start_tweets,
end_tweets,
bearer_token = get_bearer(),
n = 100,
file = NULL,
data_path = NULL,
export_query = TRUE,
bind_tweets = TRUE,
page_n = 100,
verbose = TRUE,
...) {
if (missing(start_tweets)) {
stop("Start time must be specified.")
}
if (missing(end_tweets)) {
stop("End time must be specified.")
}
check_data_path(data_path = data_path, file = file, bind_tweets = bind_tweets, verbose = verbose)
params <- list(
"max_results" = page_n,
"start_time" = start_tweets,
"end_time" = end_tweets,
"tweet.fields" = "attachments,author_id,context_annotations,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,public_metrics,possibly_sensitive,referenced_tweets,source,text,withheld",
"user.fields" = "created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld",
"expansions" = "author_id,entities.mentions.username,geo.place_id,in_reply_to_user_id,referenced_tweets.id,referenced_tweets.id.author_id",
"place.fields" = "contained_within,country,country_code,full_name,geo,id,name,place_type"
)
new_df <- data.frame()
for(user in x){
.vcat(verbose, "user: ", user, "\n")
endpoint_url <- paste0("https://api.twitter.com/2/users/", user, "/tweets")
new_rows <- get_tweets(params = params, endpoint_url = endpoint_url, page_token_name = "pagination_token", n = n, file = file, bearer_token = bearer_token,
export_query = export_query, data_path = data_path, bind_tweets = bind_tweets, verbose = verbose)
new_df <- dplyr::bind_rows(new_df, new_rows)
}
new_df
} |
MSR <- function(level){
x <- NULL
if(level==1){
x1 <- github.cssegisanddata.covid19(state = "Montserrat", level = 2)
x2 <- ourworldindata.org(id = "MSR")
x <- full_join(x1, x2, by = "date")
}
return(x)
} |
nonparasccs <- function(indiv, astart, aend, aevent, adrug, aedrug, kn1=12, kn2=12, sp1=NULL, sp2=NULL, data){
indiv <- eval(substitute(indiv), data, parent.frame())
astart <- eval(substitute(astart), data, parent.frame())
aend <- eval(substitute(aend), data, parent.frame())
aevent <- eval(substitute(aevent), data, parent.frame())
adrug <- eval(substitute(adrug), data, parent.frame())
aedrug <- eval(substitute(aedrug), data, parent.frame())
fdata <- data.frame("indiv"=indiv, "startob"=astart, "endob"=aend, "st_risk"=adrug, "end_risk"=aedrug, "eventday"=aevent)
fdata$st_risk <- pmax(fdata$startob, fdata$st_risk)
fdata$st_risk <- pmin(fdata$endob, fdata$st_risk)
fdata$end_risk <- pmax(fdata$startob, fdata$end_risk)
fdata$end_risk <- pmin(fdata$endob, fdata$end_risk)
fdata$st_risk <- ifelse(is.na(fdata$st_risk), fdata$endob, fdata$st_risk)
fdata$end_risk <- ifelse(is.na(fdata$end_risk), fdata$endob, fdata$end_risk)
fdata$end_risk <- pmin(fdata$endob, fdata$end_risk)
fdata$expostatus <- ifelse(fdata$eventday < fdata$st_risk | fdata$eventday > fdata$end_risk | fdata$st_risk==fdata$endob, 0, 1)
fdata$timesinceex <- fdata$eventday - fdata$st_risk
fdata$timesinceex <- ifelse(fdata$timesinceex < 0, 0, fdata$timesinceex)
fdata$timesinceex <- ifelse(fdata$timesinceex > (fdata$end_risk - fdata$st_risk), max(fdata$end_risk - fdata$st_risk), fdata$timesinceex)
knots1 <- seq(min(fdata$startob), max(fdata$endob)+0.0005, length=kn1)
data4 <- data.frame(fdata)
data4$timesincevac <- data4$eventday - data4$st_risk
data4$risklen <- data4$end_risk - data4$st_risk
data4$expostatus <- ifelse(data4$timesincevac < 0 | data4$timesincevac > data4$risklen, 0, 1)
timesincevacwithinexpo <- data4$timesincevac[data4$expostatus==1]
timesincevacwithinexpo<- c(timesincevacwithinexpo, 0, max(data4$risklen)+0.00001)
knots1ex <- seq(min(timesincevacwithinexpo), max(timesincevacwithinexpo), length=kn2)
Maevent = dmsplinedesign(fdata$eventday, knots1, 4, 0)
Maendrisk = dmsplinedesign(fdata$end_risk, knots1, 4, 0)
Mastrisk = dmsplinedesign(fdata$st_risk, knots1, 4, 0)
Mad1endrisk = dmsplinedesign(fdata$end_risk, knots1, 4, 1)
Mad1strisk = dmsplinedesign(fdata$st_risk, knots1, 4, 1)
Mad2endrisk = dmsplinedesign(fdata$end_risk, knots1, 4, 2)
Mad2strisk = dmsplinedesign(fdata$st_risk, knots1, 4, 2)
Mad3endrisk = dmsplinedesign(fdata$end_risk, knots1, 4, 3)
Mad3strisk = dmsplinedesign(fdata$st_risk, knots1, 4, 3)
Iastrisk = ispline(fdata$st_risk, knots1, 4)
Iastartobs = ispline(fdata$startob, knots1, 4)
Iaendobs = ispline(fdata$endob, knots1, 4)
Iaendrisk = ispline(fdata$end_risk, knots1, 4)
Mexeventsinceex = dmsplinedesign(fdata$timesinceex, knots1ex, 4, 0)
Iexendrisk = ispline(fdata$end_risk-fdata$st_risk, knots1ex, 4)
Iexstrisk = ispline(fdata$st_risk-fdata$st_risk, knots1ex, 4)
I1exendrisk = integrateIspline(fdata$end_risk-fdata$st_risk, knots1ex, 4, 1)
I1exstrisk = integrateIspline(fdata$st_risk-fdata$st_risk, knots1ex, 4, 1)
I2exendrisk = integrateIspline(fdata$end_risk-fdata$st_risk, knots1ex, 4, 2)
I2exstrisk = integrateIspline(fdata$st_risk-fdata$st_risk, knots1ex, 4, 2)
I3exendrisk = integrateIspline(fdata$end_risk-fdata$st_risk, knots1ex, 4, 3)
I3exstrisk = integrateIspline(fdata$st_risk-fdata$st_risk, knots1ex, 4, 3)
basisobj_age <- create.bspline.basis(knots1,kn1+2)
penaltymatrixage <- bsplinepen(basisobj_age)
basisobj_exposure <- create.bspline.basis(knots1ex,kn2+2)
penaltymatrix <- bsplinepen(basisobj_exposure)
neg.LLnex <- function(p, lambda1) {
-(sum(rowsum(log(Maevent[, 1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2), fdata$indiv))
-(sum(rowsum(log((Iaendobs%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2) - (Iastartobs%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)
), fdata$indiv)))
-(lambda1)*(t(c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)%*%penaltymatrixage%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)
)
}
llex <- function(p) {
-(sum(rowsum(log(Maevent[, 1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2), fdata$indiv))
-(sum(rowsum(log((Iaendobs%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2) - (Iastartobs%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)
), fdata$indiv)))
)
}
cv1 <- function(lambda1) {
p0 <- c(rep(1/(kn1+1), kn1+1))
outopt1 <- optim(p0, neg.LLnex, lambda1=lambda1, gr = NULL, method = c("BFGS"), hessian = TRUE)
par <- outopt1$par
hes <- outopt1$hessian
cvs <- llex(par) + sum(diag(pseudoinverse(-hes[1:(kn1+1), 1:(kn1+1)])%*%(-hes[1:(kn1+1), 1:(kn1+1)] +
((lambda1*(8*penaltymatrixage*((c(par[1:(ceiling((kn1+2+1)/2))], 1, par[((ceiling((kn1+2+1)/2))+1):(kn1+1)]))%*%t(c(par[1:(ceiling((kn1+2+1)/2))], 1, par[((ceiling((kn1+2+1)/2))+1):(kn1+1)]))) + 4*(diag(as.vector(penaltymatrixage%*%(c(par[1:(ceiling((kn1+2+1)/2))], 1, par[((ceiling((kn1+2+1)/2))+1):(kn1+1)]))^2)))))[-((ceiling((kn1+2+1)/2))+1),-((ceiling((kn1+2+1)/2))+1)]))))
return(cvs)
}
if (is.null(sp1)) {
smpar1 <- optim(0.00001, cv1, method=c("Brent"), lower = 0.00001, upper = 150000000, control = list(reltol=1e-2))
} else {
smpar1<-list("par"= sp1, "value"=cv1(sp1))
}
neg.LLna <- function(p, lambda) {
-(sum(rowsum(log(rep(1, nrow(fdata))), fdata$indiv))
+ sum(rowsum(fdata$expostatus*(log(Mexeventsinceex%*%p[1:length(p)]^2)), fdata$indiv))
-(sum(rowsum(log((fdata$st_risk - fdata$startob)
+ ((Iexendrisk%*%p[1:length(p)]^2) - (Iexstrisk%*%p[1:length(p)]^2))
+ (fdata$endob - fdata$end_risk)), fdata$indiv)))
-(lambda)*(t(p[1:length(p)]^2)%*%penaltymatrix%*%p[1:length(p)]^2)
)
}
ll <- function(p) {
-(sum(rowsum(log(rep(1, nrow(fdata))), fdata$indiv))
+ sum(rowsum(fdata$expostatus*(log(Mexeventsinceex%*%p[1:length(p)]^2)), fdata$indiv))
-(sum(rowsum(log((fdata$st_risk - fdata$startob)
+ ((Iexendrisk%*%p[1:length(p)]^2) - (Iexstrisk%*%p[1:length(p)]^2))
+ (fdata$endob - fdata$end_risk)), fdata$indiv)))
)
}
cv <- function(lambda) {
p0 <- c(rep(1/(kn2+2), kn2+2))
outopt <- optim(p0, neg.LLna, lambda=lambda, gr = NULL, method = c("BFGS"), hessian = TRUE)
cvs <- ll(outopt$par) + sum(diag((pseudoinverse(-outopt$hessian))%*%(-outopt$hessian + lambda*((8*penaltymatrix*(outopt$par%*%t(outopt$par)) ) + (4*(diag(as.vector(penaltymatrix%*%outopt$par^2))))) )))
return(cvs)
}
if (is.null(sp2)) {
smpar <- optim(15, cv, method=c("Brent"), lower = 0.00001, upper = 1500, control = list(reltol=1e-2))
} else {
smpar<-list("par"= sp2, "value"=cv(sp2))
}
neg.LL <- function(p, lambda1, lambda) {
-(sum(rowsum(log(Maevent[, 1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2), fdata$indiv))
+ sum(rowsum(fdata$expostatus*(log(Mexeventsinceex%*%p[(kn1+2):length(p)]^2)), fdata$indiv))
-(sum(rowsum(log(Iastrisk%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2 - (Iastartobs%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)
+ ((Maendrisk[,1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)*(Iexendrisk%*%p[(kn1+2):length(p)]^2) - (Mastrisk[,1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)*(Iexstrisk%*%p[(kn1+2):length(p)]^2))
- ((Mad1endrisk[,1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)*(I1exendrisk%*%p[(kn1+2):length(p)]^2) - (Mad1strisk[,1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)*(I1exstrisk%*%p[(kn1+2):length(p)]^2))
+ ((Mad2endrisk[,1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)*(I2exendrisk%*%p[(kn1+2):length(p)]^2) - (Mad2strisk[,1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)*(I2exstrisk%*%p[(kn1+2):length(p)]^2))
- ((Mad3endrisk[,1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)*(I3exendrisk%*%p[(kn1+2):length(p)]^2) - (Mad3strisk[,1:(kn1+2)]%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)*(I3exstrisk%*%p[(kn1+2):length(p)]^2))
+ (Iaendobs%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2 - Iaendrisk%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)), fdata$indiv)))
-(lambda1)*(t(c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)%*%penaltymatrixage%*%c(p[1:(ceiling((kn1+2+1)/2))], 1, p[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)
-(lambda)*(t(p[(kn1+2):length(p)]^2)%*%penaltymatrix%*%p[(kn1+2):length(p)]^2)
)
}
p0f1 <- c(rep(1/(kn1+1), kn1+1))
outoptf1 <- optim(p0f1, neg.LLnex, lambda1=smpar1$par, gr = NULL, method = c("BFGS"), hessian = TRUE)
p0f2 <- c(rep(1/(kn2+2), kn2+2))
outoptf2 <- optim(p0f2, neg.LLna, lambda=smpar$par, gr = NULL, method = c("BFGS"), hessian = TRUE)
p0f <- c(outoptf1$par, outoptf2$par)
out <- optim(p0f, neg.LL, lambda1=smpar1$par, lambda=smpar$par, gr = NULL, method = c("BFGS"), hessian = TRUE)
timesinceex <- seq(0, max(fdata$timesinceex))
M <- dmsplinedesign(timesinceex, knots1ex, 4, 0)
betas <- out$par[(kn1+2):length(out$par)]
var_cov_beta <- pseudoinverse((1/2)*(out$hessian))[(kn1+2):length(out$par), (kn1+2):length(out$par)]
var_cov_betasq <- (2*diag(betas))%*%var_cov_beta%*%(2*t(diag(betas)))
variance <- rep(0, length(timesinceex))
for (i in 1:length(timesinceex)) {
variance[i] <- t(M[i,])%*%var_cov_betasq%*%M[i,]
}
sderror <- sqrt(variance)
estimates <- (M%*%out$par[(kn1+2):length(out$par)]^2)
agessss <- seq(min(astart), max(aend))
Msplineageeffect <- dmsplinedesign(agessss, knots1, 4, 0)
ageriesti <- Msplineageeffect%*%(c(out$par[1:(ceiling((kn1+2+1)/2))], 1, out$par[((ceiling((kn1+2+1)/2))+1):(kn1+1)])^2)
nonparaSCCSoutput <- list("exposure" = estimates, "age"=ageriesti/ageriesti[1], "ageaxis"=agessss, "timesinceexpo"=timesinceex, "se"=sderror, "lambda1"=smpar1$par, "cv1"=smpar1$value, "lambda2"=smpar$par, "cv2"=smpar$value)
class(nonparaSCCSoutput) <- "nonparasccs"
return(nonparaSCCSoutput)
} |
context("nhl_games")
testthat::test_that(
"nhl_games_content has correct names", {
testthat::skip_if_offline(host = "nhl.com")
testthat::skip_if(skipRemoteTests)
res <- nhl_games_content(2017010001)[[1L]]
testthat::expect_true(all(is.element(
c("copyright", "link", "editorial", "media", "highlights"),
names(res)
)))
}
)
testthat::test_that(
"nhl_games_feed has correct names", {
testthat::skip_if_offline(host = "nhl.com")
testthat::skip_if(skipRemoteTests)
res <- nhl_games_feed(2017010001)[[1L]]
testthat::expect_true(all(is.element(
c("copyright", "gamePk", "link", "metaData", "gameData", "liveData"),
names(res)
)))
}
)
testthat::test_that(
"nhl_games_boxscore has correct names", {
testthat::skip_if_offline(host = "nhl.com")
testthat::skip_if(skipRemoteTests)
res <- nhl_games_boxscore(2017010001)[[1L]]
testthat::expect_true(all(is.element(
c("copyright", "teams", "officials"),
names(res)
)))
}
)
testthat::test_that(
"nhl_games_linescore has correct names", {
testthat::skip_if_offline(host = "nhl.com")
testthat::skip_if(skipRemoteTests)
res <- nhl_games_linescore(2017010001)[[1L]]
testthat::expect_true(all(is.element(
c(
"copyright", "currentPeriod", "currentPeriodOrdinal",
"currentPeriodTimeRemaining", "periods", "shootoutInfo",
"teams", "powerPlayStrength", "hasShootout",
"intermissionInfo", "powerPlayInfo"
),
names(res)
)))
}
) |
batchconvertjack <-
function(ndigit=3, rm.loci)
{
filelist=list.files(pattern='[.gen]$')
nbfiles=length(filelist)
for (t in 1 :nbfiles)
{
convertjack(filelist[t],ndigit,rm.loci)
}
arlfilelist=gsub(pattern='[.]gen', replacement='_jack.arp',filelist)
write.table(arlfilelist, file='batchjack.arb', quote=F, row.names=F, col.names=F, sep='\r')
} |
NULL
setClass(Class="SummaryForecastData",
representation=representation(
summaryData="matrix"
),
prototype=prototype(
summaryData=matrix(NA, nrow=0, ncol=0)
),
)
setMethod(
f="summary",
signature="FDatFitLogit",
definition=function(object,
period="calibration",
fitStatistics=c("brier", "auc", "perCorrect", "pre"),
threshold=.5,
baseModel=0,
showCoefs=TRUE,
...){
out <- compareModels(object, .period=period, .fitStatistics=fitStatistics, .threshold=threshold, .baseModel=baseModel)@fitStatistics
if(showCoefs){
coefs <- data.matrix(as.data.frame(t(plyr::aaply(object@modelParams, 1:2, function(x) {mean(x, na.rm=TRUE)}))))
coefs <- rbind(c(NA,NA), coefs)
out <- cbind(coefs, out)
}
W <- object@modelWeights
W <- c(NA, W)
out <- cbind(W, out)
rownames(out) <- c("EBMA", object@modelNames)
new("SummaryForecastData", summaryData=out)
}
)
setMethod(
f="summary",
signature="FDatFitNormal",
definition=function(object,
period="calibration",
fitStatistics=c("rmse", "mae"),
threshold=.5,
baseModel=0,
showCoefs=TRUE,
...){
out <- compareModels(object, .period=period, .fitStatistics=fitStatistics, .threshold=threshold, .baseModel=baseModel)@fitStatistics
if(showCoefs){
coefs <- data.matrix(as.data.frame(t(plyr::aaply(object@modelParams, 1:2, function(x) {mean(x, na.rm=TRUE)}))))
coefs <- rbind(c(NA,NA), coefs)
out <- cbind(coefs, out)
}
W <- object@modelWeights
W <- c(NA, W)
out <- cbind(W, out)
rownames(out) <- c("EBMA", object@modelNames)
new("SummaryForecastData", summaryData=out)
}
)
setMethod(
f="plot",
signature="FDatFitLogit",
definition=function(x, period="calibration", subset=1,
mainLabel="", xLab="", yLab="", cols=1, ...){
nDraw=1
numModels <- length(x@modelWeights)+1
modelNames <- c("EBMA", x@modelNames)
if(period=="calibration"){
.pred <- x@predCalibration; .actual <- x@outcomeCalibration
}
else{
.pred <- x@predTest; .actual <- x@outcomeTest
}
par(mgp=c(1, 0, 0), lend = 2, mar=c(1,0,1,0), mfrow=c(numModels, 1))
for (i in 1:numModels){
.miss <- is.na(.pred[,i, nDraw])
separationplot::separationplot(pred=as.vector(.pred[!.miss,i, nDraw]), actual=as.vector(.actual[!.miss]), heading=modelNames[i], newplot=F)
}
}
)
setMethod(
f="plot",
signature="FDatFitNormal",
definition=function(x, period="calibration", subset=1,
mainLabel=paste("Observation", subset), xLab="Outcome", yLab="Posterior Probability", cols=2:(length(x@modelNames)+1), ... )
{
if(x@method == "EM"){
thisDraw=1
if(period=="calibration"){
.nMod <- length(x@modelNames)
.pred <- matrix(x@predCalibration[subset,,thisDraw], ncol=.nMod+1); colnames(.pred) <- c("EBMA", x@modelNames)
.actual <- x@outcomeCalibration[subset]
} else{
.nMod <- length(x@modelNames)
.pred <- matrix(x@predTest[subset,,thisDraw], ncol=.nMod+1); colnames(.pred) <- c("EBMA", x@modelNames)
.actual <- x@outcomeTest
}
.sd <- sqrt(x@variance)
if (length(subset)>1){
for (j in 1:nrow(.pred)){
.means <- .pred[j,x@modelNames]
.miss <- is.na(.means)
.nModThis <- sum(!.miss)
.means <- .means[!.miss]
.xMin <- min(.means)-2.5*.sd; .xMax <- max(.means)+2.5*.sd
.xAxis <- seq(.xMin, .xMax, by=.01); .yAxis <- matrix(NA, .nModThis, length(.xAxis))
W <- x@modelWeights[!.miss]
for(i in 1:.nModThis){ .yAxis[i,] <- dnorm(.xAxis, mean=.means[i], sd=.sd)*W[i] }
.totals <- colSums(.yAxis)
plot(NULL, xlim=c(.xMin, .xMax), ylim=c(0,max(.totals)), main=mainLabel[j], xlab=xLab, ylab=yLab)
for(i in 1:.nModThis){lines(.xAxis, .yAxis[i,], type="l", lty=2, col=cols[i])}
lines(.xAxis, colSums(.yAxis), lwd=2)
rug(.means); rug(.pred[j,"EBMA"], lwd=3)
abline(v=.actual[j], lty=3)
}
} else {
.means <- .pred[,x@modelNames]
.miss <- is.na(.means)
.nModThis <- sum(!.miss)
.means <- .means[!.miss]
.xMin <- min(.means)-2.5*.sd
.xMax <- max(.means)+2.5*.sd
.xAxis <- seq(.xMin, .xMax, by=.01)
.yAxis <- matrix(NA, .nModThis, length(.xAxis))
W <- x@modelWeights[!.miss]
for(i in 1:.nModThis){.yAxis[i,] <- dnorm(.xAxis, mean=.means[i], sd=.sd)*W[i]}
.totals <- colSums(.yAxis)
plot(NULL, xlim=c(.xMin, .xMax), ylim=c(0,max(.totals)), main=mainLabel, xlab=xLab, ylab=yLab)
for(i in 1:.nModThis){lines(.xAxis, .yAxis[i,], type="l", lty=2, col=cols[i])}
lines(.xAxis, colSums(.yAxis))
rug(.means); rug(.pred[,"EBMA"], lwd=3)
abline(v=.actual, lty=3)
}
}
if(x@method == "gibbs"){
thisDraw <- 1
if(period=="calibration"){
.nMod <- length(x@modelNames)-1
.pred <- matrix(x@predCalibration[subset,-which(colnames(x@predCalibration)=="EBMA"),thisDraw], ncol=.nMod+1); colnames(.pred) <- c(x@modelNames)
.actual <- x@outcomeCalibration[subset]
.posteriorW <- x@posteriorWeights
} else{
.nMod <- length(x@modelNames)-1
.pred <- matrix(x@predTest[subset,-which(colnames(x@predCalibration)=="EBMA"),thisDraw], ncol=.nMod+1); colnames(.pred) <- c(x@modelNames)
.actual <- x@outcomeTest
.posteriorW <- x@posteriorWeights
}
.sd <- sqrt(x@variance)
if (length(subset)>1){
for (j in 1:nrow(.pred)){
.means <- .pred[j,x@modelNames]
.miss <- is.na(.means)
.nModThis <- sum(!.miss)
.means <- .means[!.miss]
.xMin <- min(.means)-2.5*.sd; .xMax <- max(.means)+2.5*.sd
.yAxis <- matrix(NA, .nModThis, 1000)
.maxima <- rep(NA, .nModThis)
W <- x@modelWeights[!.miss]
for(i in 1:.nModThis){
.yAxis[i,] <- rnorm(1000, mean=.means[i], sd=.sd)
.maxima[i] <- max(density(.yAxis[i,])$y)
}
.posteriorPred <- apply(.yAxis,2, FUN = function(x){.posteriorW%*%as.matrix(x)})
if(x@predType == "posteriorMedian"){.posteriorSummary <- median(.posteriorPred)}
if(x@predType == "posteriorMean"){.posteriorSummary <- mean(.posteriorPred)}
plot(NULL, xlim=c(.xMin, .xMax), ylim=c(0,max(c(density(.posteriorPred)$y,.maxima))), main=mainLabel[j], xlab=xLab, ylab=yLab)
for(i in 1:.nModThis){lines(density(.yAxis[i,]), type="l", lty=2, col=cols[i])}
lines(density(.posteriorPred), lwd=2)
rug(.means);
rug(.posteriorSummary, lwd=3)
abline(v=.actual[j], lty=3)
}
} else {
.means <- .pred[,x@modelNames]
.miss <- is.na(.means)
.nModThis <- sum(!.miss)
.means <- .means[!.miss]
.xMin <- min(.means)-2.5*.sd
.xMax <- max(.means)+2.5*.sd
.yAxis <- matrix(NA, .nModThis, 1000)
.maxima <- rep(NA, .nModThis)
W <- x@modelWeights[!.miss]
for(i in 1:.nModThis){
.yAxis[i,] <- rnorm(1000, mean=.means[i], sd=.sd)
.maxima[i] <- max(density(.yAxis[i,])$y)
}
.posteriorPred <- apply(.yAxis,2, FUN = function(x){.posteriorW%*%as.matrix(x)})
if(x@predType == "posteriorMedian"){.posteriorSummary <- median(.posteriorPred)}
if(x@predType == "posteriorMean"){.posteriorSummary <- mean(.posteriorPred)}
plot(NULL, xlim=c(.xMin, .xMax), ylim=c(0,max(c(density(.posteriorPred)$y,.maxima))), main=mainLabel, xlab=xLab, ylab=yLab)
for(i in 1:.nModThis){lines(density(.yAxis[i,]), type="l", lty=2, col=cols[i])}
lines(density(.posteriorPred), lwd=2)
rug(.means);
rug(.posteriorSummary, lwd=3)
abline(v=.actual, lty=3)
}
}
}
) |
VLF.count.pos <-
function(freq, p,seqlength){
count <- mat.or.vec(nr = 1, nc = seqlength)
for(i in 1:seqlength){
count[i] = length(which(freq[,i] < p))
}
return(count)
} |
HAC.simrep <- function(HACSObject) {
assign("N", HACSObject$N, envir = envr)
assign("Hstar", HACSObject$Hstar, envir = envr)
assign("probs", HACSObject$probs, envir = envr)
assign("perms", HACSObject$perms, envir = envr)
assign("p", HACSObject$p, envir = envr)
assign("conf.level", HACSObject$conf.level, envir = envr)
assign("subset.haps", HACSObject$subset.haps, envir = envr)
assign("prop.haps", HACSObject$prop.haps, envir = envr)
assign("subset.seqs", HACSObject$subset.seqs, envir = envr)
assign("prop.seqs", HACSObject$prop.seqs, envir = envr)
assign("input.seqs", HACSObject$input.seqs, envir = envr)
assign("progress", HACSObject$progress, envir = envr)
assign("num.iters", HACSObject$num.iters, envir = envr)
assign("filename", HACSObject$filename, envir = envr)
assign("ptm", proc.time(), envir = envr)
assign("iters", 1, envir = envr)
df <- data.frame(matrix(ncol = 6, nrow = 0))
x <- c(
"Mean number of haplotypes sampled",
"Mean number of haplotypes not sampled",
"Proportion of haplotypes sampled",
"Proportion of haplotypes not sampled",
"Mean value of N*",
"Mean number of specimens not sampled"
)
colnames(df) <- x
cat("\n Simulating haplotype accumulation...")
df <- HAC.sim(
N = envr$N,
Hstar = envr$Hstar,
probs = envr$probs,
perms = envr$perms,
p = envr$p,
subset.haps = envr$subset.haps,
prop.haps = envr$prop.haps,
subset.seqs = envr$subset.seqs,
prop.seqs = envr$prop.seqs,
input.seqs = envr$input.seqs,
conf.level = envr$conf.level,
progress = envr$progress,
num.iters = envr$num.iters,
df = df
)
amt <- proc.time() - envr$ptm
if (envr$progress == TRUE) {
if (envr$R < envr$p) {
cat("\n \n \n Desired level of haplotype recovery has not yet been reached \n")
} else {
cat(
"\n \n \n Desired level of haplotype recovery has been reached \n \n \n ---------- Finished. ----------
\n The initial guess for sampling sufficiency was N = ", paste0(envr$N), "individuals",
"\n \n The algorithm converged after", envr$iters, "iterations and took", amt[3], "s",
"\n \n The estimate of sampling sufficiency for p =", paste0(envr$p * 100, "%"), "haplotype recovery is N* = ", envr$Nstar - envr$X, "individuals \n (", paste0(envr$conf.level * 100, "%"), "CI:", paste(envr$low, envr$high, sep = "-"), ")",
"\n \n The number of additional specimens required to be sampled for p =", paste0(envr$p * 100, "%"), "haplotype recovery is \n N* - N = ", envr$Nstar - envr$X - envr$N, "individuals \n \n -------------------------------"
)
}
}
if (is.null(envr$num.iters)) {
while (envr$R < envr$p) {
df <- HAC.sim(
N = ceiling(envr$Nstar),
Hstar = envr$Hstar,
probs = envr$probs,
perms = envr$perms,
p = envr$p,
subset.haps = envr$subset.haps,
prop.haps = envr$prop.haps,
subset.seqs = envr$subset.seqs,
prop.seqs = envr$prop.seqs,
conf.level = envr$conf.level,
num.iters = envr$num.iters,
progress = envr$progress,
df = df
)
assign("iters", envr$iters + 1, envr)
amt <- proc.time() - envr$ptm
if (envr$progress == TRUE) {
if (envr$R < envr$p) {
cat("\n \n \n Desired level of haplotype recovery has not yet been reached \n")
} else {
cat(
"\n \n \n Desired level of haplotype recovery has been reached \n \n \n ---------- Finished. ----------
\n The initial guess for sampling sufficiency was N = ", paste0(envr$N), "individuals",
"\n \n The algorithm converged after", envr$iters, "iterations and took", amt[3], "s",
"\n \n The estimate of sampling sufficiency for p =", paste0(envr$p * 100, "%"), "haplotype recovery is N* = ", envr$Nstar - envr$X, "individuals \n (", paste0(envr$conf.level * 100, "%"), "CI:", paste(envr$low, envr$high, sep = "-"), ")",
"\n \n The number of additional specimens required to be sampled for p =", paste0(envr$p * 100, "%"), "haplotype recovery is \n N* - N = ", envr$Nstar - envr$X - envr$N, "individuals \n \n -------------------------------"
)
}
}
}
}
message("\n \n Type envr$ to extract simulation parameters of interest (see documentation for details)")
if (!is.null(envr$filename)) {
write.csv(df, file = paste0(tempdir(), "/", get("filename", envir = envr), ".csv"))
}
} |
HKMrhsfun <- function(blk,At,par,X,Z,rp,Rd,sigmu,hRd=NULL,dX=NULL,dZ=NULL){
ff <- matrix(list(),nrow(blk),1)
m <- length(rp)
if(!is.null(hRd)){
corrector <- 1
}else{
corrector <- 0
hRd <- matrix(0,m,1)
}
hEinvRc <- matrix(0,m,1)
EinvRc <- matrix(list(), nrow(blk),1)
rhsfree <- c()
for(p in 1:nrow(blk)){
n <- sum(blk[[p,2]])
if(blk[[p,1]] == "l"){
if(is.list(sigmu)){
EinvRc[[p,1]] <- sigmu[[p]]/Z[[p]] - X[[p]]
}else{
EinvRc[[p,1]] <- sigmu/Z[[p,1]] - X[[p,1]]
}
Rq <- Matrix(0,n,1, sparse=TRUE)
if(corrector & base::norm(par$parbarrier[[p,1]], type="2") == 0){
Rq <- dX[[p,1]] * dZ[[p,1]]/Z[[p,1]]
}else{
tmp <- par$dd[[p,1]] * Rd[[p,1]]
tmp2 <- mexMatvec(At[[p]],tmp,1)
hRd <- hRd + tmp2
}
EinvRc[[p,1]] <- EinvRc[[p,1]] - Rq
tmp2 <- mexMatvec(At[[p,1]], EinvRc[[p]],1)
hEinvRc <- hEinvRc + tmp2
}else if(blk[[p,1]] == "q"){
if(is.list(sigmu)){
EinvRc[[p]] <- qops(blk,p,sigmu[[p]], par$Zinv[[p]],3) - X[[p]]
}else{
EinvRc[[p]] <- sigmu * par$Zinv[[p]] - X[[p]]
}
Rq <- Matrix(0,n,1,sparse=TRUE)
if(corrector & base::norm(par$parbarrier[[p]], type="2") == 0){
ff[[p]] <- qops(blk,p,1/par$gamz[[p]], as.matrix(Z[[p]]),3)
hdx <- qops(blk,p,par$gamz[[p]], as.matrix(ff[[p]]),5,as.matrix(dX[[p]]))
hdz <- qops(blk,p,par$gamz[[p]],as.matrix(ff[[p]]),6,as.matrix(dZ[[p]]))
hdxdz <- Arrow(blk,p,hdx,hdz)
Rq <- qops(blk,p,par$gamz[[p]],as.matrix(ff[[p]]),6,hdxdz)
}else{
tmp <- par$dd[[p]] * Rd[[p]] +
qops(blk,p,qops(blk,p, as.matrix(Rd[[p]]), par$Zinv[[p]],1),as.matrix(X[[p]]),3) +
qops(blk,p,qops(blk,p, as.matrix(Rd[[p]]), as.matrix(X[[p]]),1),as.matrix(par$Zinv[[p]]),3)
tmp2 <- mexMatvec(At[[p,1]], tmp,1)
hRd <- hRd + tmp2
}
EinvRc[[p]] <- EinvRc[[p]] - Rq
tmp2 <- mexMatvec(At[[p,1]], EinvRc[[p]],1)
hEinvRc <- hEinvRc + tmp2
}else if(blk[[p,1]] == "s"){
if(is.list(sigmu)){
sigmuvec <- mexexpand(as.matrix(blk[[p,2]]),sigmu[[p,1]])
EinvRc[[p]] <- par$Zinv[[p,1]] %*% diag(sigmuvec,n,n) - X[[p,1]]
}else{
EinvRc[[p]] <- sigmu*par$Zinv[[p]] - X[[p]]
}
Rq <- Matrix(0,n,n, sparse=TRUE)
if(corrector & base::norm(par$parbarrier[[p]], type="2") == 0){
Rq <- Prod3(blk,p,dX[[p]], dZ[[p]], par$Zinv[[p]],0)
Rq <- 0.5*(Rq + t(Rq))
}else{
tmp <- Prod3(blk,p,X[[p]], Rd[[p]], par$Zinv[[p]],0,par$nzlistAy[[p]])
tmp <- 0.5*(tmp + t(tmp))
tmp2 <- AXfun(matrix(blk[p,],nrow=1),matrix(At[p,],nrow=1), par$permA[p,,drop=FALSE],matrix(list(tmp), nrow=1))
hRd <- hRd + tmp2
}
EinvRc[[p]] <- EinvRc[[p]] - Rq
EinvRctmp <- EinvRc
EinvRctmp[[p]] <- as.matrix(EinvRctmp[[p]])
tmp2 <- AXfun(matrix(blk[p,],nrow=1),matrix(At[p,],nrow=1),par$permA[p,,drop=FALSE],matrix(EinvRctmp[p], nrow=1))
hEinvRc <- hEinvRc + tmp2
}else if(blk[[p,1]] == "u"){
rhsfree <- rbind(rhsfree, Rd[[p]])
}
}
rhs <- rp + hRd - hEinvRc
rhs <- rbind(rhs,rhsfree)
return(list(rhs=rhs, EinvRc = EinvRc, hRd = hRd))
} |
context("trajectory")
on.exit(unlink('Rplots.pdf'))
ex1.pars <- list(y0 = 0, add = F, tlim = c(0,5), system="one.dim")
ex1.out <- do.call(trajectory, c(deriv=phaseR::example1, ex1.pars))
ex1b.pars <- list(y0 = c(0, 1, 3), add = F, tlim = c(0,5), system="one.dim")
ex1b.out <- do.call(trajectory, c(deriv=phaseR::example1, ex1b.pars))
ex10.pars <- list(y0 = c(2, 5), add = F, tlim = c(0,5))
ex10.out <- do.call(trajectory, c(deriv=phaseR::example10, ex10.pars))
ex10b.pars <- list(y0 = t(matrix(c(2, 5, -2, 4, 0, 3), nrow = 2)), add = F,
tlim = c(0,5), xlim = c(-5,5))
ex10b.out <- do.call(trajectory, c(deriv=phaseR::example10, ex10b.pars))
test_that("behavior equal to reference behavior", {
expect_equal_to_reference(ex1.out["y"], "test-trajectory_ref-ex1.rds")
expect_equal_to_reference(ex1b.out["y"], "test-trajectory_ref-ex1b.rds")
expect_equal_to_reference(ex10.out[c("x","y")], "test-trajectory_ref-ex10.rds")
expect_equal_to_reference(ex10b.out[c("x","y")], "test-trajectory_ref-ex10b.rds")
})
test_that("alternative formulation equal to reference behavior", {
ex1.alt <- function(t, state, parameters) {
with(as.list(c(state, parameters)), {
dA = 4 - A^2
list(c(dA))
})
}
ex1.alt.out <- do.call(trajectory, c(list(deriv=ex1.alt,
state.names = c("A")), ex1.pars))
expect_equal(ex1.alt.out["dy"], ex1.out["dy"])
ex1b.alt.out <- do.call(trajectory, c(list(deriv=ex1.alt,
state.names = c("A")), ex1b.pars))
expect_equal(ex1b.alt.out["dy"], ex1b.out["dy"])
ex10.alt <- function(t, state, parameters) {
with(as.list(c(state, parameters)), {
dI = -I + I^3
dN = -2 * N
list(c(dI, dN))
})
}
ex10.alt.out <- do.call(trajectory, c(list(deriv=ex10.alt,
state.names = c("I", "N")), ex10.pars))
expect_equal(ex10.alt.out[c("dx","dy")], ex10.out[c("dx","dy")])
ex10b.alt.out <- do.call(trajectory, c(list(deriv=ex10.alt,
state.names = c("I", "N")), ex10b.pars))
expect_equal(ex10b.alt.out[c("dx","dy")], ex10b.out[c("dx","dy")])
}) |
context("paxes tests")
test <- FALSE
if (test) {
setwd("~")
pdf("test-paxes.pdf")
data(narccap)
pimage(lon, lat, tasmax[, , 1], proj = "mercator", axes = FALSE)
paxes("mercator", xlim = range(lon), ylim = range(lat), col = "grey",
axis.args = list(col.axis = "blue", xat = c(-160, -100, -90, -80,
-20)))
title("blue axis with unique x spacing, grey lines")
dev.off()
} |
bootLassoOLS <- function(x, y, B = 500, type.boot = "residual", alpha = 0.05, OLS = TRUE,
cv.method = "cv", nfolds = 10, foldid, cv.OLS = TRUE, tau = 0,
parallel = FALSE, standardize = TRUE, intercept = TRUE,
parallel.boot = FALSE, ncores.boot = 1, ...){
x <- as.matrix(x)
y <- as.numeric(y)
n <- dim(x)[1]
p <- dim(x)[2]
if ((type.boot != "residual") & (type.boot != "paired")) {
stop("type.boot should take value of 'residual' or 'paired'.")
}
selectset <- rep(0, p)
Beta.Lasso <- rep(0, p)
Beta.LassoOLS <- rep(0, p)
globalfit <- glmnet(x, y, standardize = standardize, intercept = intercept, ...)
lambda <- globalfit$lambda
cvfit <- escv.glmnet(x, y, lambda = lambda, nfolds = nfolds, tau = tau, cv.OLS = cv.OLS, parallel = parallel,
standardize = standardize, intercept = intercept, ...)
if (cv.method == "cv") {
lambda.opt <- cvfit$lambda.cv
}
if (cv.method == "escv") {
lambda.opt <- cvfit$lambda.escv
}
if (cv.method == "cv1se") {
lambda.opt <- cvfit$lambda.cv1se
}
fitlasso <- predict(globalfit, type = "coefficients", s = lambda.opt)
fit.value <- predict(globalfit, newx = x, s = lambda.opt)
betalasso <- fitlasso[-1]
Beta.Lasso <- betalasso
Beta.LassoOLS <- betalasso
selectvar <- betalasso != 0
if (OLS & sum(selectvar) > 0) {
mls.obj <- mls(x[, selectvar, drop = FALSE], y, tau = tau, standardize = standardize, intercept = intercept)
Beta.LassoOLS[selectvar] <- mls.obj$beta
fit.value <- mypredict(mls.obj, newx = x[, selectvar, drop = FALSE])
}
if (type.boot == "residual") {
fit <- fit.value
residual <- y - fit
residual_center <- residual - mean(residual)
Beta.boot.Lasso <- matrix(0, nrow = B, ncol = p)
Beta.boot.LassoOLS <- matrix(0, nrow = B, ncol = p)
out <- list()
if (!parallel.boot) {
for (i in 1:B) {
out[[i]] <- list()
resam <- sample(1:n, n, replace = TRUE)
ystar <- fit + residual_center[resam]
boot.obj <- Lasso(x = x, y = ystar, lambda = lambda.opt, standardize = standardize, intercept = intercept, ...)
out[[i]][[1]] <- boot.obj$beta
if (OLS) {
boot.obj <- LassoOLS(x = x, y = ystar, lambda = lambda.opt, standardize = standardize, intercept = intercept, ...)
}
out[[i]][[2]] <- boot.obj$beta
}
} else {
resams <- matrix(sample(1:n, n*B, replace = TRUE), nrow = n)
out <- foreach(i = 1:B) %dopar% {
resam <- resams[, i]
ystar <- fit + residual_center[resam]
boot.obj <- Lasso(x = x, y = ystar, lambda = lambda.opt, standardize = standardize, intercept = intercept, ...)
beta1 <- boot.obj$beta
if (OLS) {
boot.obj <- LassoOLS(x = x, y = ystar, lambda = lambda.opt, standardize = standardize, intercept = intercept, ...)
}
beta2 <- boot.obj$beta
list(beta1 = beta1, beta2 = beta2)
}
}
for (i in 1:B) {
Beta.boot.Lasso[i,] <- out[[i]][[1]]
Beta.boot.LassoOLS[i,] <- out[[i]][[2]]
out[[i]] <- 0
}
out <- NULL
interval.Lasso <- ci(Beta.Lasso, Beta.boot.Lasso, alpha = alpha, type = "basic")
interval.LassoOLS <- ci(Beta.LassoOLS, Beta.boot.LassoOLS, alpha = alpha, type = "basic")
}
if (type.boot == "paired") {
Beta.boot.Lasso <- matrix(0, nrow = B, ncol = p)
Beta.boot.LassoOLS <- matrix(0, nrow = B, ncol = p)
out <- list()
if (!parallel.boot) {
for (i in 1:B) {
out[[i]] <- list()
resam <- sample(1:n, n, replace = TRUE)
rx <- x[resam,]
ry <- y[resam]
boot.obj <- Lasso(x = rx, y = ry, lambda = lambda.opt, standardize = standardize, intercept = intercept, ...)
out[[i]][[1]] <- boot.obj$beta
if (OLS) {
boot.obj <- LassoOLS(x = rx, y = ry, lambda = lambda.opt, standardize = standardize, intercept = intercept, ...)
}
out[[i]][[2]] <- boot.obj$beta
}
} else {
resams <- matrix(sample(1:n, n*B, replace = TRUE), nrow = n)
out <- foreach(i = 1:B) %dopar% {
resam <- resams[, i]
rx <- x[resam, ]
ry <- y[resam]
boot.obj <- Lasso(x = rx, y = ry, lambda = lambda.opt, standardize = standardize, intercept = intercept, ...)
beta1 <- boot.obj$beta
if (OLS) {
boot.obj <- LassoOLS(x = rx, y = ry, lambda = lambda.opt, standardize = standardize, intercept = intercept, ...)
}
beta2 <- boot.obj$beta
list(beta1 = beta1, beta2 = beta2)
}
}
for (i in 1:B) {
Beta.boot.Lasso[i,] <- out[[i]][[1]]
Beta.boot.LassoOLS[i,] <- out[[i]][[2]]
out[[i]] <- 0
}
out <- NULL
interval.Lasso <- ci(Beta.Lasso, Beta.boot.Lasso, alpha = alpha, type = "quantile")
interval.LassoOLS <- ci(Beta.LassoOLS, Beta.boot.LassoOLS, alpha = alpha, type = "quantile")
}
object <- list(lambda.opt = lambda.opt, Beta.Lasso = Beta.Lasso, Beta.LassoOLS = Beta.LassoOLS,
interval.Lasso = interval.Lasso, interval.LassoOLS = interval.LassoOLS)
object
} |
test_that('IEEE floating point, Fortran bind(C)', {
expect_equal(.C(glinvtestfloatIEEE01_, -Inf, NaN, NAOK=T)[[2]], 0.0)
expect_equal(.C(glinvtestfloatIEEE01_, Inf, NaN, NAOK=T)[[2]], Inf)
})
test_that('IEEE floating point, .Call(), Rmath.h', {
expect_equal(.Call(glinvtestfloatIEEE02, -Inf), 0.0)
expect_equal(.Call(glinvtestfloatIEEE02, Inf), Inf)
})
test_that('IEEE floating point, .C(), Rmath.h', {
expect_equal(.C(glinvtestfloatIEEE03, -Inf, NaN, NAOK=T)[[2]], 0.0)
expect_equal(.C(glinvtestfloatIEEE03, Inf, NaN, NAOK=T)[[2]], Inf)
}) |
test_that(
desc = "long_to_wide_converter works - spread true",
code = {
set.seed(123)
df1 <- long_to_wide_converter(
data = iris_long,
x = condition,
y = value
)
set.seed(123)
df2 <- long_to_wide_converter(
data = mtcars,
x = am,
y = wt,
paired = FALSE
)
set.seed(123)
df3 <- long_to_wide_converter(
data = bugs_long,
x = condition,
y = desire,
paired = TRUE
)
set.seed(123)
df4 <- long_to_wide_converter(
data = ggplot2::msleep,
x = vore,
y = brainwt,
paired = FALSE
)
set.seed(123)
expect_snapshot(list(df1, df2, df3, df4))
}
)
test_that(
desc = "long_to_wide_converter works - spread false",
code = {
set.seed(123)
df1 <- long_to_wide_converter(
data = iris_long,
x = condition,
y = value,
spread = FALSE
)
set.seed(123)
df2 <- long_to_wide_converter(
data = mtcars,
x = am,
y = wt,
paired = FALSE,
spread = FALSE
)
set.seed(123)
df3 <- long_to_wide_converter(
data = bugs_long,
x = condition,
y = desire,
paired = TRUE,
spread = FALSE
)
set.seed(123)
df4 <- long_to_wide_converter(
data = ggplot2::msleep,
x = vore,
y = brainwt,
paired = FALSE,
spread = FALSE
)
set.seed(123)
expect_snapshot(list(df1, df2, df3, df4))
}
)
test_that(
desc = "with rowid - without NA",
code = {
df <- structure(list(
score = c(90, 90, 72.5, 45),
condition = structure(c(1L, 2L, 2L, 1L), .Label = c("4", "5"), class = "factor"),
id = c(1L, 2L, 1L, 2L)
),
row.names = c(NA, -4L),
class = c("tbl_df", "tbl", "data.frame")
)
df1 <- arrange(df, id)
expect_equal(
long_to_wide_converter(df1, condition, score),
long_to_wide_converter(df, condition, score, id)
)
expect_equal(
long_to_wide_converter(df1, condition, score, spread = FALSE) %>%
arrange(rowid),
long_to_wide_converter(df, condition, score, id, spread = FALSE) %>%
arrange(rowid)
)
}
)
test_that(
desc = "with rowid - with NA",
code = {
df <- bugs_long
df1 <- arrange(bugs_long, subject)
expect_equal(
long_to_wide_converter(df1, condition, desire) %>%
select(-rowid),
long_to_wide_converter(df, condition, desire, subject) %>%
select(-rowid)
)
expect_equal(
long_to_wide_converter(df1, condition, desire, spread = FALSE) %>%
select(-rowid),
long_to_wide_converter(df, condition, desire, subject, spread = FALSE) %>%
select(-rowid)
)
}
) |
"ab" |
geojson_atomize <- function(x, combine = TRUE) UseMethod("geojson_atomize")
geojson_atomize.default <- function(x, combine = TRUE) {
stop("no 'geojson_atomize' method for ", class(x))
}
geojson_atomize.geo_json <- function(x, combine = TRUE) {
geojson_atomize(unclass(x), combine = combine)
}
geojson_atomize.character <- function(x, combine = TRUE) {
if (!jsonlite::validate(x)) stop("'x' not valid JSON")
geojson_atomize(structure(x, class = "json"), combine = combine)
}
geojson_atomize.json <- function(x, combine = TRUE) {
type <- stripjqr(jqr::jq(unclass(x), ".type"))
keys <- stripjqr(jqr::jq(unclass(x), "keys[]"))
if (type %in% c('Point', 'MultiPoint',
'Polygon', 'MultiPolygon',
'LineString', 'MultiLineString')) {
tmp <- jqr::jq(unclass(x), '{ "type": "Feature", "geometry": . }')
} else {
if ("features" %in% keys) {
tmp <- jqr::jq(unclass(x), ".features[]")
}
if ("geometries" %in% keys) {
tmp <- jqr::jq(unclass(x), ".geometries[]")
}
}
structure(if (combine) jqr::combine(tmp) else tmp, class = "json")
}
geojson_atomize.geo_list <- function(x, combine = TRUE) {
if (x$type %in% c('Point', 'MultiPoint',
'Polygon', 'MultiPolygon',
'LineString', 'MultiLineString')) {
list(type = "Feature", geometry = c(x))
} else {
if ("features" %in% names(x)) return(x$features)
if ("geometries" %in% names(x)) return(x$geometries)
}
}
stripjqr <- function(x) gsub('\\"', "", unclass(x)) |
valueEst <-
function (d1, d2, Y, A1, A2){
ind = (A1==d1)*(A2==d2);
num = sum (Y*ind);
denom = sum (ind);
value = num/denom;
indPosPos = (A1==1)*(A2==1);
indPosNeg = (A1==1)*(A2==-1);
indNegPos = (A1==-1)*(A2==1);
indNegNeg = (A1==-1)*(A2==-1);
valPosPos = sum (Y*indPosPos)/sum (indPosPos);
valPosNeg = sum (Y*indPosNeg)/sum (indPosNeg);
valNegPos = sum (Y*indNegPos)/sum (indNegPos);
valNegNeg = sum (Y*indNegNeg)/sum (indNegNeg);
list ("value"=value, "valPosPos"=valPosPos, "valPosNeg"=valPosNeg,
"valNegPos"=valNegPos, "valNegNeg"=valNegNeg);
} |
randwalk <- function (A, B, reps = 20, steps = 10,
iter = 10000, cores)
{
if(missing(cores))
{cores <- parallel::detectCores() - 1
}else{cores <- cores}
nameA <- as.character(substitute(A))
nameB <- as.character(substitute(B))
if("$" %in% unlist(strsplit(nameA, split = "")))
{
nameA <- unlist(strsplit(nameA, split = "\\$"))
nameA <- nameA[length(nameA)]
}
if("$" %in% unlist(strsplit(nameB, split = "")))
{
nameB <- unlist(strsplit(nameB, split = "\\$"))
nameB <- nameB[length(nameB)]
}
nA <- ncol(A)
nB <- ncol(B)
start <- steps
A <- binarize(A)
B <- binarize(B)
diag(A) <- 0
diag(B) <- 0
TA <- matrix(0,nrow=nA,ncol=nA)
TB <- matrix(0,nrow=nB,ncol=nB)
degA <- colSums(A)
degB <- colSums(B)
for(i in 1:nA)
for(j in 1:nA)
{TA[i,j] <- A[i,j]/degA[i]}
for(i in 1:nB)
for(j in 1:nB)
{TB[i,j] <- B[i,j]/degB[i]}
DA <- distance(A)
DB <- distance(B)
rw <- function(steps, nA, nB, TA, TB, DA, DB)
{
sim <- numeric(length = 2)
sim5 <- sim
uniq <- sim
results <- vector("numeric",17)
vnA <- numeric(length = steps)
vnB <- vnA
visit <- matrix(NA, nrow = 2, ncol = steps)
permA <- sample(nA, 1)
permB <- sample(nB, 1)
startingNodeA <- permA
startingNodeB <- permB
vnA[1] <- permA
vnB[1] <- permB
for(k in 2:steps)
{
cdfA <- cumsum(TA[startingNodeA,])
cdfB <- cumsum(TB[startingNodeB,])
x <- runif(1)
nA <- which(cdfA > x)[1]
nB <- which(cdfB > x)[1]
vnA[k] <- nA
vnB[k] <- nB
startingNodeA <- nA
startingNodeB <- nB
}
uA <- unique(vnA)
uB <- unique(vnB)
a <- uA[length(uA)]
b <- uB[length(uB)]
simA <- exp(-DA[vnA[1],a])
simB <- exp(-DB[vnB[1],b])
s5ind <- 5
su <- min(c(length(uA),length(uB)))
if(s5ind > su)
{s5ind <- su}
g5ind <- 5
if(g5ind > s5ind)
{g5ind <- s5ind}
simA5 <- exp(-DA[vnA[1],uA[s5ind]])
simB5 <- exp(-DB[vnB[1],uB[s5ind]])
visit[1,] <- vnA
visit[2,] <- vnB
sim[1] <- simA
sim5[1] <- simA5
uniq[1] <- length(uA)
sim[2] <- simB
sim5[2] <- simB5
uniq[2] <- length(uB)
res <- list()
res$sim <- sim
res$sim5 <- sim5
res$uniq <- uniq
res$visit <- visit
return(res)
}
steps <- seq(start, reps*10 , 10)
step.list <- list()
for(i in 1:length(steps))
{step.list[[i]] <- as.list(rep(steps[i], iter))}
pb.res <- vector("list", length = length(steps))
cl <- parallel::makeCluster(cores)
parallel::clusterExport(cl = cl, varlist = c("rw", "steps", "step.list", "nA", "nB", "reps",
"TA", "TB", "DA", "DB", "pb.res"), envir = environment())
message("Computing random walks...")
for(i in 1:length(steps))
{
message(paste("Repetition ", i, " of ", reps, " (", steps[i], " steps)", sep = ""))
pb.res[[i]] <- pbapply::pblapply(step.list[[i]], function(x){rw(x, nA, nB, TA, TB, DA, DB)})
}
parallel::stopCluster(cl)
results <- matrix(NA, nrow = reps, ncol = 17)
colnames(results) <- c("Steps",
paste("M.uniq",nameA,sep="."), paste("SD.uniq",nameA,sep="."),
paste("M.sim",nameA,sep="."), paste("SD.sim",nameA,sep="."),
paste("M.sim5",nameA,sep="."), paste("SD.sim5",nameA,sep="."),
paste("M.uniq",nameB,sep="."), paste("SD.uniq",nameB,sep="."),
paste("M.sim",nameB,sep="."), paste("SD.sim",nameB,sep="."),
paste("M.sim5",nameB,sep="."), paste("SD.sim5",nameB,sep="."),
"pu", "ps", "ps5", "g5ind")
for(i in 1:reps)
{
sim <- t(sapply(
lapply(pb.res[[i]], function(x)
{
x$sim
}),
rbind
))
sim5 <- t(sapply(
lapply(pb.res[[i]], function(x)
{
x$sim5
}),
rbind
))
uniq <- t(sapply(
lapply(pb.res[[i]], function(x)
{
x$uniq
}),
rbind
))
pu <- suppressWarnings(wilcox.test(uniq[,1],uniq[,2])$p.value)
ps <- suppressWarnings(wilcox.test(sim[,1],sim[,2])$p.value)
ps5 <- suppressWarnings(wilcox.test(sim5[,1],sim5[,2])$p.value)
results[i,1] <- steps[i]
results[i,2] <- mean(uniq[,1])
results[i,3] <- sd(uniq[,1])
results[i,4] <- mean(sim[,1])
results[i,5] <- sd(sim[,1])
results[i,6] <- mean(sim5[,1])
results[i,7] <- sd(sim5[,1])
results[i,8] <- mean(uniq[,2])
results[i,9] <- sd(uniq[,2])
results[i,10] <- mean(sim[,2])
results[i,11] <- sd(sim[,2])
results[i,12] <- mean(sim5[,2])
results[i,13] <- sd(sim5[,2])
results[i,14] <- pu
results[i,15] <- ps
results[i,16] <- ps5
results[i,17] <- 5
}
dir.pu <- ifelse(results[,"pu"] < .05,
ifelse(results[,2] > results[,8],
paste(nameA, ">", nameB),
paste(nameB, ">", nameA)),
"n.s.")
dir.ps <- ifelse(results[,"ps"] < .05,
ifelse(results[,4] > results[,10],
paste(nameA, ">", nameB),
paste(nameB, ">", nameA)),
"n.s.")
dir.ps5 <- ifelse(results[,"ps5"] < .05,
ifelse(results[,6] > results[,12],
paste(nameA, ">", nameB),
paste(nameB, ">", nameA)),
"n.s.")
short.results <- round(results[,c("Steps","pu","ps","ps5")], 3)
short.results <- ifelse(short.results < .001, "< .001", short.results)
short.results <- cbind(short.results[,1:2], dir.pu,
short.results[,3], dir.ps,
short.results[,4], dir.ps5)
colnames(short.results) <- c("Steps",
"Unique Nodes (p-value)", "Direction",
"Similarity (p-value)", "Direction",
"5-step Similarlity (p-value)", "Direction")
short.results <- as.data.frame(short.results)
res <- list()
res$long <- results
res$short <- short.results
return(res)
} |
discretize_link <- function(link, df, m_start) {
n <- nrow(df)
d <- ncol(df)
types_data <- sapply(df[1, ], class)
continu_complete_case <- !is.na(df)
if (sum(!(types_data %in% c("numeric", "factor"))) > 0) {
stop(simpleError("Unsupported data types. Columns of predictors must be numeric or factor."))
}
emap <- array(0, c(n, d))
if (d > 1) {
for (j in (1:d)) {
if (types_data[j] == "numeric") {
if (sum(is.na(link[[j]])) == 0) {
t <- predict(link[[j]], newdata = data.frame(x = df[continu_complete_case[, j], j], stringsAsFactors = TRUE), type = "probs")
if (is.vector(t)) {
t <- cbind(1 - t, t)
colnames(t) <- c("1", "2")
}
if (sum(!continu_complete_case[, j]) > 0) {
t_bis <- matrix(NA, nrow = nrow(df), ncol = ncol(t) + 1)
t_bis[continu_complete_case[, j], 1:ncol(t)] <- t
t_bis[continu_complete_case[, j], ncol(t) + 1] <- 0
t_bis[!continu_complete_case[, j], ] <- t(matrix(c(rep(0, ncol(t)), 1), nrow = ncol(t) + 1, ncol = sum(!continu_complete_case[, j])))
colnames(t_bis) <- c(colnames(t), m_start + 1)
t <- t_bis
}
} else {
t <- matrix(1, nrow = n, ncol = 1)
colnames(t) <- "1"
}
} else {
if (!is.null(link[[j]])) {
t <- prop.table.robust(t(sapply(df[, j], function(row) link[[j]][, row])), 1)
} else {
t <- matrix(1, nrow = n, ncol = 1)
colnames(t) <- "1"
}
}
emap[, j] <- unlist(apply(t, 1, function(p) names(which.max(p))))
}
} else if (types_data == "numeric") {
t <- predict(link[[1]], newdata = data.frame(x = df, stringsAsFactors = TRUE), type = "probs")
emap[, 1] <- apply(t, 1, function(p) names(which.max(p)))
} else {
t <- prop.table(t(apply(df, 1, function(row) link[[1]][, row])), 1)
emap[, 1] <- apply(t, 1, function(p) names(which.max(p)))
}
return(emap)
} |
"mymvlm" <-
function(x,y,ilms=.dFvGet()$ilm,iopt=.dFvGet()$ipt,intch=.dFvGet()$ich,nrep,
tolv=.dFvGet()$tlv,tolm=.dFvGet()$tlm,tau=.dFvGet()$tua,iseed=.dFvGet()$isd) {
if (missing(x)) messagena("x")
if (missing(y)) messagena("y")
n <- length(y)
np <- ncol(x)
nq <- np+1
ncov <- np*(np+1)/2
mdx <- nrow(x)
mdw <- (np+6)*np+2*n+2
mdi <- 3*np+1
if (missing(nrep)) nrep <- integer(1)
ierr <- integer(1)
xvol <- single(1)
xmin <- single(1)
cov <- single(ncov)
t <- single(np)
theta <- single(nq)
rs <- single(n)
d <- single(n)
itv <- integer(nq)
itm <- integer(nq)
work <- single(mdw)
iwork <- integer(mdi)
f.res <- .Fortran("mymvlmz",
x=to.single(x),
y=to.single(y),
n=to.integer(n),
np=to.integer(np),
nq=to.integer(nq),
ncov=to.integer(ncov),
mdx=to.integer(mdx),
mdw=to.integer(mdw),
mdi=to.integer(mdi),
ilms=to.integer(ilms),
iopt=to.integer(iopt),
intch=to.integer(intch),
nrep=to.integer(nrep),
tolv=to.single(tolv),
tolm=to.single(tolm),
tau=to.single(tau),
iseed=to.integer(iseed),
ierr=to.integer(ierr),
xvol=to.single(xvol),
xmin=to.single(xmin),
cov=to.single(cov),
t=to.single(t),
theta=to.single(theta),
rs=to.single(rs),
d=to.single(d),
itv=to.integer(itv),
itm=to.integer(itm),
work=to.single(work),
iwork=to.integer(iwork))
list(nrep=f.res$nrep,ierr=f.res$ierr,xvol=f.res$xvol,xmin=f.res$xmin,
cov=f.res$cov,t=f.res$t,theta=f.res$theta,rs=f.res$rs,d=f.res$d,
itv=f.res$itv,itm=f.res$itm,iseed=f.res$iseed)
} |
gc.survival<-function(coxph.obj, data, group, times, failures, max.time,
effect="ATE", iterations=1000, n.cluster=1){
if(coxph.obj$call[1] != "coxph()"){
stop("The argument \"coxph.obj\" needs to be a coxph object") }
if(length(unlist(strsplit(as.character(coxph.obj$formula[2]), ","))) != 2){
stop("The argument \"coxph.obj\" needs to be a proportional hazard model")}
form <- coxph.obj$formula
if(!is.data.frame(data) & !is.matrix(data)){
stop("The argument \"data\" needs to be a data.frame or a matrix") }
if(!is.character(group) & !is.numeric(group)){
stop("The argument \"group\" needs to be scalar or a character string") }
if(length(grep("$", form, fixed = TRUE)) > 0 | length(grep("[", form,
fixed = TRUE)) > 0){
stop("Incorrect formula specified in the argument \"coxph.obj\": don't
use the syntax data$var or data[,var]") }
if(!is.character(times)){
if(is.numeric(times)){
times <- colnames(data)[times]
}else{ stop("The argument \"times\" needs to be scalar or a character
string") } }
mod <- unique(data[,group])
if(length(mod) != 2 | ((mod[1] != 0 & mod[2] != 1) & (mod[1] != 1 & mod[2]
!= 0))){
stop("Two modalities encoded 0 (for non-treated/non-exposed patients) and
1 (for treated/exposed patients) are required in the argument \"group\"
") }
mod <- unique(data[,failures])
if(length(mod) != 2 | ((mod[1] != 0 & mod[2] != 1) & (mod[1] != 1 & mod[2]
!= 0))){
stop("Two modalities encoded 0 (for censored patients) and 1 (for
uncensored patients) are required in the argument \"failures\" ") }
if(is.na(match(effect,c("ATT","ATU","ATE"))) | length(effect)!=1){
stop("Incorrect modality specified in the argument \"effect\": only one
option among \"ATE\", \"ATT\" or \"ATU\" are possible") }
if(length(names(coxph.obj$coef)) < 2){
stop("Incorrect formula specified in the argument \"coxph.obj\": at least
2 covariables, including exposure, are requiered") }
if(is.na(match(group,names(coxph.obj$coef))) &
is.na(match(names(data)[group],names(coxph.obj$coef)))){
stop("Incorrect formula specified in the argument \"coxph.obj\": exposure
is requiered") }
if(max.time > max(data[,times], na.rm=T) | max.time < min(data[,times],
na.rm=T)){
stop("The argument \"max.time\" needs to be a number includes between the
min and the max of the vector \"times\" ") }
if(!is.null(attr(coxph.obj$terms,"specials")$strata) |
!is.null(attr(coxph.obj$terms,"specials")$tt) |
!is.null(attr(coxph.obj$terms,"specials")$cluster)){
stop("Incorrect argument in the argument \"coxph.obj\": time-transform
functions, stratification and clustering are not implemented") }
ties <- coxph.obj$method
explp <-function(coxph.obj, newdata){
return( exp(predict(coxph.obj, newdata, type="lp") +
sum(setNames(coxph.obj$means, names(coef(coxph.obj)))*coef(coxph.obj))) )
}
if(effect=="ATE"){ ttt <- which(data[,group] %in% c(0,1))
}else if(effect=="ATT"){ ttt <- which(data[,group] == 1)
}else ttt <- which(data[,group] == 0 )
d1 <- d0 <- d <- data[ttt,]
d1[,group] <- 1
d0[,group] <- 0
b <- basehaz(coxph.obj, centered=FALSE)
H0.multi <- b$hazard[b$time %in% sort(unique(d[d[,failures]==1,times]))]
T.multi <- b$time[b$time %in% sort(unique(d[d[,failures]==1,times]))]
D1 <- data.frame(
S = colMeans(exp(explp(coxph.obj,d1) %o% -H0.multi )),
T = T.multi)
D0 <- data.frame(
S = colMeans(exp(explp(coxph.obj,d0) %o% -H0.multi )),
T = T.multi)
D1$h <- differentiation(x=D1$T, fx=-1*log(D1$S))
D0$h <- differentiation(x=D0$T, fx=-1*log(D0$S))
logHR <- log(mean(D1$h/D0$h))
table.surv <- data.frame(
times=D1$T,
survival=c(D1$S,D0$S),
n.risk=c(
sapply(D1$T, function(temps) {
sum(d[d[,group]==1,times] >= temps)} ),
sapply(D0$T, function(temps) {
sum(d[d[,group]==0,times] >= temps)})),
variable=c(
rep(1,dim(D1)[1]),
rep(0,dim(D0)[1])) )
RMST1 <- rmst(D1$T, D1$S, max.time)
RMST0 <- rmst(D0$T, D0$S, max.time)
logHR.s <- RMST1.s <- RMST0.s <- rep(-99, iterations)
if(n.cluster==1){
if(effect=="ATE"){
for(i in 1:iterations){
data.b <- data[sample(1:nrow(data), size=nrow(data), replace = TRUE),]
cox.s <- coxph(form, data=data.b, ties=ties, x=TRUE, y=TRUE)
sfit <- survfit(cox.s, data=data.b, se.fit=FALSE)
.d1 <- .d0 <- data.b
.d1[,group] <- 1
.d0[,group] <- 0
.H0.multi <- sfit$cumhaz[sfit$n.event>0] * exp(-sum(cox.s$means *
coef(cox.s)))
.T.multi <- sfit$time[sfit$n.event>0]
.D1 <- data.frame(
S = colMeans(exp(explp(cox.s,.d1) %o% -.H0.multi )), T = .T.multi)
.D0 <- data.frame(
S = colMeans(exp(explp(cox.s,.d0) %o% -.H0.multi )), T = .T.multi)
logHR.s[i] <- log( mean(
differentiation(x=.D1$T, fx=-1*log(.D1$S)) /
differentiation(x=.D0$T, fx=-1*log(.D0$S))) )
RMST1.s[i] <- rmst(.D1$T, .D1$S, max.time)
RMST0.s[i] <- rmst(.D0$T, .D0$S, max.time)
}
}else{
if(effect=="ATT"){
for(i in 1:iterations){
data.b <- data[sample(1:nrow(data), size=nrow(data), replace = TRUE),]
cox.s <- coxph(form, data=data.b, ties=ties, x=TRUE, y=TRUE)
sfit <- survfit(cox.s, data=data.b, se.fit=FALSE)
.d1 <- .d0 <- data.b[data.b[,group] == 1,]
.d1[,group] <- 1
.d0[,group] <- 0
.H0.multi <- sfit$cumhaz[sfit$n.event>0] * exp(-sum(cox.s$means *
coef(cox.s)))
.T.multi <- sfit$time[sfit$n.event>0]
.D1 <- data.frame(
S = colMeans(exp(explp(cox.s,.d1) %o% -.H0.multi )), T = .T.multi)
.D0 <- data.frame(
S = colMeans(exp(explp(cox.s,.d0) %o% -.H0.multi )), T = .T.multi)
logHR.s[i] <- log( mean(
differentiation(x=.D1$T, fx=-1*log(.D1$S)) /
differentiation(x=.D0$T, fx=-1*log(.D0$S))) )
RMST1.s[i] <- rmst(.D1$T, .D1$S, max.time)
RMST0.s[i] <- rmst(.D0$T, .D0$S, max.time)
}
}else{
for(i in 1:iterations){
data.b <- data[sample(1:nrow(data), size=nrow(data), replace = TRUE),]
cox.s <- coxph(form, data=data.b, ties=ties, x=TRUE, y=TRUE)
sfit <- survfit(cox.s, data=data.b, se.fit=FALSE)
.d1 <- .d0 <- data.b[data.b[,group] == 0,]
.d1[,group] <- 1
.d0[,group] <- 0
.H0.multi <- sfit$cumhaz[sfit$n.event>0] * exp(-sum(cox.s$means *
coef(cox.s)))
.T.multi <- sfit$time[sfit$n.event>0]
.D1 <- data.frame(
S = colMeans(exp(explp(cox.s,.d1) %o% -.H0.multi )), T = .T.multi)
.D0 <- data.frame(
S = colMeans(exp(explp(cox.s,.d0) %o% -.H0.multi )), T = .T.multi)
logHR.s[i] <- log( mean(
differentiation(x=.D1$T, fx=-1*log(.D1$S)) /
differentiation(x=.D0$T, fx=-1*log(.D0$S))) )
RMST1.s[i] <- rmst(.D1$T, .D1$S, max.time)
RMST0.s[i] <- rmst(.D0$T, .D0$S, max.time)
}
}
}
}
if(n.cluster>1){
if(effect=="ATE"){
simul <- function(){
data.b <- data[sample(1:nrow(data), size=nrow(data), replace = TRUE),]
cox.s <- coxph(form, data=data.b, ties=ties, x=TRUE, y=TRUE)
sfit <- survfit(cox.s, data=data.b, se.fit=FALSE)
.d1 <- .d0 <- data.b
.d1[,group] <- 1
.d0[,group] <- 0
.H0.multi <- sfit$cumhaz[sfit$n.event>0] * exp(-sum(cox.s$means *
coef(cox.s)))
.T.multi <- sfit$time[sfit$n.event>0]
.D1 <- data.frame(
S = colMeans(exp(explp(cox.s,.d1) %o% -.H0.multi )), T = .T.multi)
.D0 <- data.frame(
S = colMeans(exp(explp(cox.s,.d0) %o% -.H0.multi )), T = .T.multi)
return(c(logHR.s = log(mean(differentiation(x=.D1$T,
fx=-1*log(.D1$S))/differentiation(x=.D0$T, fx=-1*log(.D0$S)))), RMST1.s
= rmst(.D1$T, .D1$S, max.time), RMST0.s = rmst(.D0$T, .D0$S,
max.time)))
}
}else{
if(effect=="ATT"){
simul <- function(){
data.b <- data[sample(1:nrow(data), size=nrow(data), replace = TRUE),]
cox.s <- coxph(form, data=data.b, ties=ties, x=TRUE, y=TRUE)
sfit <- survfit(cox.s, data=data.b, se.fit=FALSE)
.d1 <- .d0 <- data.b[data.b[,group] == 1,]
.d1[,group] <- 1
.d0[,group] <- 0
.H0.multi <- sfit$cumhaz[sfit$n.event>0] * exp(-sum(cox.s$means *
coef(cox.s)))
.T.multi <- sfit$time[sfit$n.event>0]
.D1 <- data.frame(
S = colMeans(exp(explp(cox.s,.d1) %o% -.H0.multi )), T = .T.multi)
.D0 <- data.frame(
S = colMeans(exp(explp(cox.s,.d0) %o% -.H0.multi )), T = .T.multi)
return(c(logHR.s = log(mean(differentiation(x=.D1$T,
fx=-1*log(.D1$S))/differentiation(x=.D0$T, fx=-1*log(.D0$S)))), RMST1.s
= rmst(.D1$T, .D1$S, max.time), RMST0.s = rmst(.D0$T, .D0$S,
max.time)))
}
}else{
simul <- function(){
data.b <- data[sample(1:nrow(data), size=nrow(data), replace = TRUE),]
cox.s <- coxph(form, data=data.b, ties=ties, x=TRUE, y=TRUE)
sfit <- survfit(cox.s, data=data.b, se.fit=FALSE)
.d1 <- .d0 <- data.b[data.b[,group] == 0,]
.d1[,group] <- 1
.d0[,group] <- 0
.H0.multi <- sfit$cumhaz[sfit$n.event>0] * exp(-sum(cox.s$means *
coef(cox.s)))
.T.multi <- sfit$time[sfit$n.event>0]
.D1 <- data.frame(
S = colMeans(exp(explp(cox.s,.d1) %o% -.H0.multi )), T = .T.multi)
.D0 <- data.frame(
S = colMeans(exp(explp(cox.s,.d0) %o% -.H0.multi )), T = .T.multi)
return(c(logHR.s = log(mean(differentiation(x=.D1$T,
fx=-1*log(.D1$S))/differentiation(x=.D0$T, fx=-1*log(.D0$S)))), RMST1.s
= rmst(.D1$T, .D1$S, max.time), RMST0.s = rmst(.D0$T, .D0$S,
max.time)))
}
}
}
if(.Platform[[1]] == "windows"){
cl <- makeCluster(n.cluster, type="PSOCK")
}else{
cl <- makeCluster(n.cluster, type="FORK")
}
registerDoParallel(cl)
clusterEvalQ(cl, {library(splines); library(survival)})
res <- NULL
res <- foreach(i = 1:iterations, .combine=rbind, .inorder=TRUE) %dopar%
{simul()}
registerDoSEQ()
stopCluster(cl)
logHR.s <- as.numeric(res[,"logHR.s"])
RMST1.s <- as.numeric(res[,"RMST1.s"])
RMST0.s <- as.numeric(res[,"RMST0.s"])
}
se.logHR <- sd(logHR.s, na.rm=TRUE)
pv <- function(x){
ztest <- mean(x)/sd(x)
return(ifelse(ztest<0,2*pnorm(ztest),2*(1-pnorm(ztest))))
}
p.value.HR <- pv(logHR.s)
if(p.value.HR==0){ p.value.HR <- "<0.001" }
ci.low.logHR <- quantile(logHR.s, probs=c(0.025), na.rm=T)
ci.upp.logHR <- quantile(logHR.s, probs=c(0.975), na.rm=T)
ci.low.RMST1 <- quantile(RMST1.s, probs=c(0.025), na.rm=T)
ci.upp.RMST1 <- quantile(RMST1.s, probs=c(0.975), na.rm=T)
ci.low.RMST0 <- quantile(RMST0.s, probs=c(0.025), na.rm=T)
ci.upp.RMST0 <- quantile(RMST0.s, probs=c(0.975), na.rm=T)
delta.s <- RMST1.s - RMST0.s
se.delta <- sd(delta.s, na.rm=TRUE)
p.value.delta <- pv(delta.s)
if(p.value.delta==0){ p.value.delta <- "<0.001" }
ci.low.delta <- quantile(delta.s, probs=c(0.025), na.rm=T)
ci.upp.delta <- quantile(delta.s, probs=c(0.975), na.rm=T)
.obj <- list(
table.surv=table.surv,
effect=effect,
max.time=data.frame(max.time=max.time),
RMST0=data.frame(estimate=RMST0, ci.lower=ci.low.RMST0,
ci.upper=ci.upp.RMST0),
RMST1=data.frame(estimate=RMST1, ci.lower=ci.low.RMST1,
ci.upper=ci.upp.RMST1),
delta=data.frame(estimate=RMST1-RMST0, std.error = se.delta,
ci.lower=ci.low.delta, ci.upper=ci.upp.delta, p.value=p.value.delta),
logHR=data.frame(estimate=logHR, std.error = se.logHR, ci.lower=ci.low.logHR,
ci.upper=ci.upp.logHR, p.value=p.value.HR) )
class(.obj) <- "survrisca"
return(.obj)
} |
library("zoo")
library("tseries")
online <- FALSE
options(prompt = "R> ")
Sys.setenv(TZ = "GMT")
suppressWarnings(RNGversion("3.5.0"))
inrusd <- read.zoo(system.file("doc", "demo1.txt", package = "zoo"), sep = "|", format="%d %b %Y")
tmp <- read.table(system.file("doc", "demo2.txt", package = "zoo"), sep = ",")
z <- zoo(tmp[, 3:4], as.Date(as.character(tmp[, 2]), format="%d %b %Y"))
colnames(z) <- c("Nifty", "Junior")
time(z)
start(z)
end(inrusd)
plain <- coredata(z)
str(plain)
m <- merge(inrusd, z, all = FALSE)
m <- merge(inrusd, z)
merge(inrusd, lag(inrusd, -1))
plot(m)
plot(m[, 2:3], plot.type = "single", col = c("red", "blue"), lwd = 2)
window(z, start = as.Date("2005-02-15"), end = as.Date("2005-02-28"))
m[as.Date("2005-03-10")]
interpolated <- na.approx(m)
m <- na.locf(m)
m
prices2returns <- function(x) 100*diff(log(x))
r <- prices2returns(m)
rollapply(r, 10, sd)
prices2returns(aggregate(m, as.yearmon, tail, 1))
nextfri <- function(x) 7 * ceiling(as.numeric(x-5+4) / 7) + as.Date(5-4)
prices2returns(aggregate(na.locf(m), nextfri, tail, 1))
zsec <- structure(1:10, index = structure(c(1234760403.968, 1234760403.969,
1234760403.969, 1234760405.029, 1234760405.029, 1234760405.03,
1234760405.03, 1234760405.072, 1234760405.073, 1234760405.073
), class = c("POSIXt", "POSIXct"), tzone = ""), class = "zoo")
to4sec <- function(x) as.POSIXct(4*ceiling(as.numeric(x)/4), origin = "1970-01-01")
aggregate(zsec, to4sec, tail, 1)
tmp <- zsec
st <- start(tmp)
Epoch <- st - as.numeric(st)
time(tmp) <- as.integer(time(tmp) + 1e-7) + Epoch
ix <- !duplicated(time(tmp), fromLast = TRUE)
merge(tmp[ix], zoo(, seq(start(tmp), end(tmp), "sec")))
intraday.discretise <- function(b, Nsec) {
st <- start(b)
time(b) <- Nsec * as.integer(time(b)+1e-7) %/% Nsec + st -
as.numeric(st)
ix <- !duplicated(time(b), fromLast = TRUE)
merge(b[ix], zoo(, seq(start(b), end(b), paste(Nsec, "sec"))))
}
intraday.discretise(zsec, 1)
library("tseries")
if(online) {
sunw <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31")
sunw2 <- get.hist.quote(instrument = "SUNW", start = "2004-01-01", end = "2004-12-31",
compression = "m", quote = "Close")
eur.usd <- get.hist.quote(instrument = "EUR/USD", provider = "oanda", start = "2004-01-01", end = "2004-12-31")
save(sunw, sunw2, eur.usd, file = "sunw.rda")
} else {
load(system.file("doc", "sunw.rda", package = "zoo"))
}
time(sunw2) <- as.yearmon(time(sunw2))
sunw3 <- aggregate(sunw[, "Close"], as.yearmon, tail, 1)
r <- prices2returns(sunw3)
is.weekend <- function(x) ((as.numeric(x)-2) %% 7) < 2
eur.usd <- eur.usd[!is.weekend(time(eur.usd))]
is.weekend <- function(x) {
x <- as.POSIXlt(x)
x$wday > 5 | x$wday < 1
}
date1 <- seq(as.Date("2001-01-01"), as.Date("2002-12-1"), by = "day")
len1 <- length(date1)
set.seed(1)
data1 <- zoo(rnorm(len1), date1)
data1q.mean <- aggregate(data1, as.yearqtr, mean)
data1q.sd <- aggregate(data1, as.yearqtr, sd)
head(cbind(mean = data1q.mean, sd = data1q.sd), main = "Quarterly")
nexttue <- function(x) 7 * ceiling(as.numeric(x - 2 + 4)/7) + as.Date(2 - 4)
data1w <- cbind(
mean = aggregate(data1, nexttue, mean),
sd = aggregate(data1, nexttue, sd)
)
head(data1w)
FUNs <- c(mean, sd)
ag <- function(z, by, FUNs) {
f <- function(f) aggregate(z, by, f)
do.call(cbind, sapply(FUNs, f, simplify = FALSE))
}
data1q <- ag(data1, as.yearqtr, c("mean", "sd"))
data1w <- ag(data1, nexttue, c("mean", "sd"))
head(data1q)
head(data1w) |
rsubbins <- function(bEdges, bCounts, m=NULL, eps1 = 0.25, eps2 = 0.75, depth = 3,
tailShape = c("onebin", "pareto", "exponential"),
nTail=16, numIterations=20, pIndex=1.160964, tbRatio=0.8) {
L <- length(bCounts)
if(!(is.na(bEdges[L]) | is.infinite(bEdges[L])))
warning("Top bin is bounded. Expect inaccurate results.\n")
if(is.null(m)) {
warning("No mean provided: expect inaccurate results.\n")
m <- sum(0.5*(c(bEdges[1:(L-1)],2.0*bEdges[L-1])+c(0, bEdges[1:(L-1)]))*bCounts/sum(bCounts))
}
tailShape <- match.arg(tailShape)
if(tailShape == "onebin")
rsubbinsNotail(bEdges, bCounts, m, eps1, eps2, depth)
else
rsubbinsTail(bEdges, bCounts, m, eps1, eps2, depth, tailShape, nTail, numIterations, pIndex, tbRatio)
}
rsubbinsTail <- function(bEdges, bCounts, m, eps1, eps2, depth,
tailShape = c("pareto", "exponential"),
nTail, numIterations, pIndex, tbRatio) {
tailShape <- match.arg(tailShape)
eps3 <- (1 - eps2) / 2
L <- length(bCounts)
tot <- sum(bCounts)
e <- c(0,bEdges[1:(L-1)],numeric(nTail))
shrinkFactor <- 1
shrinkMultiplier <- 0.995
tailCount <- bCounts[L]
bbtot <- tot-tailCount
bbMean <- sum((e[2:(L)]+e[1:(L-1)])*bCounts[1:(L-1)])/(2*bbtot)
while(m<bbMean) {
e <- e*shrinkMultiplier
bbMean <- sum((e[2:(L)]+e[1:(L-1)])*bCounts[1:(L-1)])/(2*bbtot)
shrinkFactor <- shrinkFactor*shrinkMultiplier
}
if(tailCount>0) {
L <- L+nTail-1
tailArea <- tailCount/tot
bAreas <- c(bCounts/tot, numeric(nTail-1))
tbWidth <- e[L-nTail+1]-e[L-nTail]
h <- bAreas[L-nTail]/tbWidth
if(tailShape=="pareto")
tailUnscaled <- (1:nTail)^(-1-pIndex)
else
tailUnscaled <- tbRatio^(1:nTail)
bAreas[(L-nTail+1):(L)] <- tailUnscaled/sum(tailUnscaled)*tailArea
repeat {
e[(L-nTail+2):(L+1)] <- e[L-nTail+1]+(1:(nTail))*tbWidth
bMean <- sum((e[2:(L+1)]+e[1:L])*bAreas)/2
if(bMean>m) break
tbWidth <- tbWidth*2
}
l <- 0
r <- tbWidth
for(i in 1:numIterations) {
tbWidth <- (l+r)/2
e[(L-nTail+2):(L+1)] <- e[L-nTail+1]+(1:(nTail))*tbWidth
bMean <- sum((e[2:(L+1)]+e[1:L])*bAreas)/2
if (bMean<m)
l <- tbWidth
else
r <- tbWidth
}
}
else {
L <- L-1
bAreas <- bCounts[1:L]/tot
e <- e[1:(L+1)]
}
binAreas <- bAreas
binHeights <- c(0, binAreas/(e[2:(L+1)]-e[1:L]), 0)
binEdges <- e
for(i in 1:depth){
L <- length(binEdges)
binDiffs <- binHeights[2:(L + 1)] - binHeights[1:L]
newbinHeights <- 1:(3 * (L - 1))
binWidths <- binEdges[2:L] - binEdges[1:(L-1)]
binEdges2 <- binEdges[1:(L - 1)] + binWidths * eps3
binEdges3 <- binEdges[2:L] - binWidths * eps3
binEdges <- sort(c(binEdges, binEdges2, binEdges3), decreasing = FALSE)
for(j in 1:(L-1)) {
new_middlebin_height <- (((binDiffs[j] - binDiffs[(j + 1)]) * eps1 * eps3) / eps2) + binHeights[j + 1]
if(new_middlebin_height>0)
{
newbinHeights[(3 * j - 2)] <- binHeights[j + 1] - binDiffs[j] * eps1
newbinHeights[(3 * j)] <- binHeights[(j + 1)] + binDiffs[(j + 1)] * eps1
newbinHeights[(3 * j - 1)] <- new_middlebin_height
}
else
{
newbinHeights[(3*j-2)] <- binHeights[(j+1)]
newbinHeights[(3*j)] <- binHeights[(j+1)]
newbinHeights[(3*j-1)] <- binHeights[(j+1)]
}
}
binHeights <- c(0, newbinHeights, 0)
}
L <- length(binEdges)
binWidths <- binEdges[2:L] - binEdges[1:(L-1)]
binAreas <- binWidths * binHeights[2:L]
cAreas <- vapply(1:length(binAreas), function(x){sum(binAreas[1:x])}, numeric(1))
rsubCDF <- approxfun(binEdges, c(0, cAreas), yleft=0, yright=1, rule=2)
rsubPDF <- stepfun(binEdges, binHeights)
return(list(rsubPDF=rsubPDF, rsubCDF=rsubCDF, E=binEdges[L], shrinkFactor=shrinkFactor))
}
rsubbinsNotail <- function(bEdges, bCounts, m, eps1, eps2, depth) {
eps3 <- (1 - eps2) / 2
L <- length(bCounts)
tot <- sum(bCounts)
p <- c(1,1-vapply(1:(L-1), function(x){sum(bCounts[1:x])}, numeric(1))/tot)
e <- c(0,bEdges[1:(L-1)],0)
A <- 0.5*sum((e[2:L]-e[1:(L-1)])*(p[2:L]+p[1:(L-1)]))
shrinkFactor <- 1
shrinkMultiplier <- 0.995
while(m<A) {
e <- e*shrinkMultiplier
A <- 0.5*sum((e[2:L]-e[1:(L-1)])*(p[2:L]+p[1:(L-1)]))
shrinkFactor <- shrinkFactor*shrinkMultiplier
}
E <- ifelse(p[L]>0, bEdges[L-1]+2*(m-A)/p[L], bEdges[L-1]*1.001)
e[L+1] <- E
binAreas <- bCounts/tot
binHeights <- c(0, binAreas/(e[2:(L+1)]-e[1:L]), 0)
binEdges <- e
for(i in 1:depth){
L <- length(binEdges)
binDiffs <- binHeights[2:(L + 1)] - binHeights[1:L]
newbinHeights <- 1:(3 * (L - 1))
binWidths <- binEdges[2:L] - binEdges[1:(L-1)]
binEdges2 <- binEdges[1:(L - 1)] + binWidths * eps3
binEdges3 <- binEdges[2:L] - binWidths * eps3
binEdges <- sort(c(binEdges, binEdges2, binEdges3), decreasing = FALSE)
for(j in 1:(L-1)) {
new_middlebin_height <- (((binDiffs[j] - binDiffs[(j + 1)]) * eps1 * eps3) / eps2) + binHeights[j + 1]
if(new_middlebin_height>0)
{
newbinHeights[(3 * j - 2)] <- binHeights[j + 1] - binDiffs[j] * eps1
newbinHeights[(3 * j)] <- binHeights[(j + 1)] + binDiffs[(j + 1)] * eps1
newbinHeights[(3 * j - 1)] <- new_middlebin_height
}
else
{
newbinHeights[(3*j-2)] <- binHeights[(j+1)]
newbinHeights[(3*j)] <- binHeights[(j+1)]
newbinHeights[(3*j-1)] <- binHeights[(j+1)]
}
}
binHeights <- c(0, newbinHeights, 0)
}
L <- length(binEdges)
binWidths <- binEdges[2:L] - binEdges[1:(L-1)]
binAreas <- binWidths * binHeights[2:L]
cAreas <- vapply(1:length(binAreas), function(x){sum(binAreas[1:x])}, numeric(1))
rsubCDF <- approxfun(binEdges, c(0, cAreas), yleft=0, yright=1, rule=2)
rsubPDF <- stepfun(binEdges, binHeights)
return(list(rsubPDF=rsubPDF, rsubCDF=rsubCDF, E=E, shrinkFactor=shrinkFactor))
} |
invwishrnd <- function(n,lambda){
p<-ncol(lambda)
S<-try(solve(wishrnd(n = n, Sigma = solve(lambda))), silent=TRUE)
if(inherits(S, "try-error")){
S=solve(wishrnd(n = n, Sigma = solve((lambda+diag(p)))))
}
return(S)
} |
expected <- eval(parse(text="NA_complex_"));
test(id=0, code={
argv <- eval(parse(text="list(0L, NA_real_, NA_real_)"));
.Internal(complex(argv[[1]], argv[[2]], argv[[3]]));
}, o=expected); |
library(git2r)
sessionInfo()
path <- tempfile(pattern = "git2r-")
dir.create(path)
repo <- init(path, branch = "main")
config(repo, user.name = "Author", user.email = "[email protected]")
writeLines(c("First line in file 1.", "Second line in file 1."),
file.path(path, "example-1.txt"))
add(repo, "example-1.txt")
commit(repo, "First commit message")
writeLines(c("First line in file 2.", "Second line in file 2."),
file.path(path, "example-2.txt"))
add(repo, "example-2.txt")
commit(repo, "Second commit message")
checkout(repo, "fix", create = TRUE)
writeLines(c("line First in file 1.", "Second line in file 1."),
file.path(path, "example-1.txt"))
add(repo, "example-1.txt")
commit(repo, "Third commit message")
checkout(repo, "main")
writeLines(c("First line in file 2.", "line Second in file 2."),
file.path(path, "example-2.txt"))
add(repo, "example-2.txt")
commit(repo, "Fourth commit message")
tools::assertError(merge(repo))
m <- merge(repo, "fix", TRUE, default_signature(repo))
stopifnot(identical(format(m), "Merge"))
m <- merge(repo, "fix", TRUE, default_signature(repo))
stopifnot(identical(format(m), "Already up-to-date"))
stopifnot(identical(sapply(commits(repo), function(x) length(parents(x))),
c(2L, 1L, 1L, 1L, 0L)))
stopifnot(is_merge(last_commit(repo)))
summary(last_commit(repo))
stopifnot(!file.exists(file.path(path, ".git", "MERGE_HEAD")))
unlink(path, recursive = TRUE) |
multiClusterPeaks <- structure(function
(peaks
){
stopifnot(is.data.frame(peaks))
stopifnot(is.numeric(peaks$chromStart))
stopifnot(is.numeric(peaks$chromEnd))
stopifnot(nrow(peaks) > 0)
peaks <- data.frame(peaks)[order(peaks$chromStart), ]
with(peaks, stopifnot(chromStart < chromEnd))
sample.vec <- if(is.character(peaks$sample.id)){
factor(peaks$sample.id)
}else if(is.factor(peaks$sample.id) || is.integer(peaks$sample.id)){
peaks$sample.id
}else stop("sample.id column must be character, factor, or integer")
res <- .C(
"multiClusterPeaks_interface",
as.integer(peaks$chromStart),
as.integer(peaks$chromEnd),
cluster=as.integer(peaks$chromEnd),
as.integer(nrow(peaks)),
PACKAGE="PeakSegJoint")
peaks$cluster <- res$cluster
peaks
}, ex=function(){
library(PeakSegJoint)
data(chr7.peaks, envir=environment())
library(ggplot2)
ggplot()+
geom_segment(aes(
chromStart/1e3, sample.id,
xend=chromEnd/1e3, yend=sample.id),
data=chr7.peaks)
clustered <- multiClusterPeaks(chr7.peaks)
clustered.list <- split(clustered, clustered$cluster)
clusters.list <- list()
for(cluster.name in names(clustered.list)){
clusters.list[[cluster.name]] <- with(
clustered.list[[cluster.name]], data.frame(
cluster=cluster[1],
clusterStart=as.integer(median(chromStart)),
clusterEnd=as.integer(median(chromEnd))))
}
clusters <- do.call(rbind, clusters.list)
ggplot()+
geom_segment(aes(
chromStart/1e3, sample.id,
color=factor(cluster),
xend=chromEnd/1e3, yend=sample.id),
data=clustered)+
geom_segment(aes(
clusterStart/1e3, "clusters",
color=factor(cluster),
xend=clusterEnd/1e3, yend="clusters"),
data=clusters)
}) |
test_that("calcEscore_value", {
item_1 <- new("item_1PL", difficulty = 0.5)
item_2 <- new("item_2PL", slope = 1.5, difficulty = 0.5)
item_3 <- new("item_3PL", slope = 1.0, difficulty = 0.5, guessing = 0.2)
item_4 <- new("item_PC", threshold = c(-1, 0, 1), ncat = 4)
item_5 <- new("item_GPC", slope = 1.2, threshold = c(-0.8, -1.0, 0.5), ncat = 4)
item_6 <- new("item_GR", slope = 0.9, category = c(-1, 0, 1), ncat = 4)
theta_vec <- seq(-3, 3, 1)
tol <- 1e-06
expect_equal(
log(prod(calcEscore(item_1, theta_vec))),
-9.53851,
tolerance = tol)
expect_equal(
log(prod(calcEscore(item_2, theta_vec))),
-13.02588,
tolerance = tol)
expect_equal(
log(prod(calcEscore(item_3, theta_vec))),
-5.173527,
tolerance = tol)
expect_equal(
log(prod(calcEscore(item_4, theta_vec))),
-0.1421625,
tolerance = tol)
expect_equal(
log(prod(calcEscore(item_5, theta_vec))),
0.03717596,
tolerance = tol)
expect_equal(
log(prod(calcEscore(item_6, theta_vec))),
0.8290602,
tolerance = tol)
expect_equal(
mean(log(unlist(calcEscore(itempool_science, theta_vec)))),
6.375118,
tolerance = tol)
expect_equal(
mean(log(unlist(calcEscore(itempool_reading, theta_vec)))),
4.890361,
tolerance = tol)
expect_equal(
mean(log(unlist(calcEscore(itempool_fatigue, theta_vec)))),
3.690174,
tolerance = tol)
expect_equal(
mean(log(unlist(calcEscore(itempool_bayes, theta_vec)))),
5.139598,
tolerance = tol)
}) |
vcov.elm <- function(object, complete = TRUE, ...) {
return(vcov.summary.elm(summary(object, ...), complete = complete))
} |
flash_clean_relay_events <- function(df, wide_format_relay) {
if (wide_format_relay == FALSE) {
df <- df %>%
data.frame() %>%
dplyr::select(-dplyr::matches("X\\.\\d+")) %>%
dplyr::mutate(Time = stringr::str_remove(Time, "(?<!D)[Q|q]")) %>%
dplyr::mutate(dplyr::across(
dplyr::matches("[0-9]"),
~ stringr::str_remove(.x, " ?\\[(.*)\\]")
))
varying_cols <-
names(df)[grep("(^X\\d)|(^Lap)|(^L\\d)", names(df))]
if (length(varying_cols) > 0) {
df <- flash_pivot_longer(df, varying = varying_cols)
}
} else {
df <- df %>%
dplyr::select(-dplyr::matches("X\\.\\d+")) %>%
flash_col_names() %>%
dplyr::mutate(dplyr::across(
dplyr::matches("Split_"),
~ stringr::str_remove(.x, " ?\\[(.*)\\]")
))
}
clean_relay_data <- df %>%
dplyr::mutate(Time = stringr::str_remove(Time, "(?<!D)[Q|q]")) %>%
dplyr::rename("Result" = "Time") %>%
dplyr::mutate(
Tiebreaker = dplyr::case_when(
stringr::str_detect(Result, "\\(\\d{1,2}\\.\\d{3}\\)") == TRUE ~ stringr::str_extract(Result, "\\d{1,2}\\.\\d{3}"),
TRUE ~ "NA"
)
) %>%
dplyr::mutate(Result = stringr::str_remove(Result, "\\(\\d{1,2}\\.\\d{3}\\)")) %>%
dplyr::mutate(Result = stringr::str_remove(Result, "\\\n[:upper:]{1,2}")) %>%
dplyr::na_if("NA") %>%
dplyr::mutate(dplyr::across(where(is.character), stringr::str_trim))
return(clean_relay_data)
}
relay_events <- flash_clean_relay_events |
.solveNLP.demo <-
function()
{
dataSet <- data("LPP2005REC", package="timeSeries", envir=environment())
LPP2005REC <- get(dataSet, envir=environment())
nAssets <- 6
data <- 100 * LPP2005REC[, 1:nAssets]
mu <- colMeans(data)
Sigma <- cov(data)
start <- rep(1, nAssets)/nAssets
objective <- function(x) { 0.5 * (x %*% Sigma %*% x)[[1]] }
lower <- rep(0, nAssets)
upper <- rep(1, nAssets)
mat <- rbind(
budget = rep(1, times=nAssets),
returns = colMeans(data))
matLower <- c(
budget = 1,
return = mean(data))
matUpper <- matLower
linCons <- list(mat, matLower, matUpper)
control <- list()
ans <- rdonlp2NLP(start, objective, lower, upper, linCons)
ans
ans <- rsolnpNLP(start, objective, lower, upper, linCons)
ans
ans <- rnlminb2NLP(start, objective, lower, upper, linCons)
ans
} |
provide <- function(...) {
`if`(!exists("..module..", parent.frame(), inherits = FALSE),
stop("Only use provide() in a module."))
obj_names <- as.character(match.call(expand.dots = FALSE)$...)
existing_obj_names <- get("..provide..", envir = parent.frame())
obj_names <- unique(c(existing_obj_names, obj_names))
assign("..provide..", unique(obj_names, existing_obj_names), envir = parent.frame())
invisible(NULL)
}
refer <- function(..., include = c(), exclude = c(), prefix = "", sep = "."){
`if`(!exists("..module..", parent.frame(), inherits = FALSE),
stop("Only use provide() in a module."))
private <- parent.frame()
dots <- as.character(match.call(expand.dots = FALSE)$...)
sources <- lapply(dots, get, envir = parent.frame())
names(sources) <- dots
lapply(sources, `attr<-`, "refer_include", include)
lapply(sources, `attr<-`, "refer_exclude", exclude)
`if`(deparse(substitute(prefix)) == ".",
mapply(`attr<-`, x = sources, which = list("refer_prefix"), value = dots),
lapply(sources, `attr<-`, "refer_prefix", prefix))
lapply(sources, `attr<-`, "refer_sep", sep)
assign("..refer..",
c(get("..refer..", envir = parent.frame()), sources),
parent.frame())
if (length(sources) != 0){
`if`(length(unique(private$..refer..)) < length(private$..refer..),
stop("refer() a module at most once."))
source_obj_name_list <- lapply(sources, ls, all.names = TRUE)
source_include_list <- lapply(sources, attr, which = "refer_include")
source_exclude_list <- lapply(sources, attr, which = "refer_exclude")
source_prefix_list <- lapply(sources, attr, which = "refer_prefix")
source_sep_list <- lapply(sources, attr, which = "refer_sep")
source_obj_name_list <-
mapply(function(src_obj, src_incl, src_excl){
res <- src_obj
res <- `if`(is.null(src_incl), res, intersect(res, src_incl))
res <- `if`(is.null(src_excl), res, setdiff(res, src_excl))
res
},
src_obj = source_obj_name_list,
src_incl = source_include_list,
src_excl = source_exclude_list,
SIMPLIFY = FALSE)
source_obj_name_list2 <- mapply(
function(prefix, obj_name, sep){
`if`(nchar(prefix) >= 1,
paste(prefix, obj_name, sep = sep),
obj_name)
},
prefix = source_prefix_list,
obj_name = source_obj_name_list,
sep = source_sep_list,
SIMPLIFY = FALSE)
intersect_w_others <- function(x, i){
mapply(intersect, x[-i], x[i], SIMPLIFY = FALSE)
}
source_conflict_name_list <-
if (length(source_obj_name_list2) > 1){
res <- lapply(seq_along(source_obj_name_list2),
function(i) {
intersect_w_others(x = source_obj_name_list2,
i = i)})
names(res) <- names(source_obj_name_list2)
res
} else {
list()
}
`if`(length(unique(unlist(source_conflict_name_list))) > 0,
stop(paste0("name conflict among sources: ",
paste(unique(unlist(source_conflict_name_list)),
collapse = ", "))))
target_obj_name_list <- ls(private, all.names = TRUE)
conflict_name_list <- lapply(source_obj_name_list2,
intersect,
y = target_obj_name_list)
`if`(length(unlist(conflict_name_list)) > 0,
stop(paste0("name conflict: ",
paste(c(conflict_name_list),
collapse = ", "))))
for (i in 1:length(sources)) {
mapply(assign,
x = source_obj_name_list2[[i]],
value = mget(source_obj_name_list[[i]], sources[[i]]),
envir = list(private),
SIMPLIFY = FALSE
)
}
}
invisible()
}
require <- function(package){
`if`(!exists("..module..", parent.frame(), inherits = FALSE),
stop("Only use mod::require() in a module."))
package <- substitute(package)
package <- `if`(is.character(package),package,deparse(package))
`if`(system.file("", package = package) == "",
stop(paste(package, "is not an installed package")))
private <- parent.frame()
existing_pkg_names <- get("..require..", envir = private)
pkg_names <- c(existing_pkg_names, package)
assign("..require..", pkg_names, private)
pkg_ns <- asNamespace(package)
import_list <- unique(names(pkg_ns$.__NAMESPACE__.$imports))[-1]
temp_envir <- new.env()
if (length(import_list) > 0) {
for (i in 2:length(import_list)) {
mapply(assign,
x = ls(asNamespace(import_list[i])),
value = mget(x = ls(asNamespace(import_list[i])),
envir = asNamespace(import_list[i])),
envir = list(temp_envir))
}
} else {
}
mapply(assign,
x = ls(pkg_ns),
value = mget(x = ls(pkg_ns), envir = pkg_ns),
envir = list(temp_envir))
mapply(assign,
x = ls(temp_envir),
value = mget(x = ls(temp_envir), envir = temp_envir),
envir = list(private$..link..))
invisible()
}
name <- function(name){
`if`(!exists("..module..", parent.frame(), inherits = FALSE),
stop("Only use mod::name() in a module."))
name <- as.character(substitute(name))
private <- parent.frame()
assign("..name..", name, envir = private)
invisible(name)
} |
"Brumbaugh" |
setClass(Class = "DDF.Analysis", representation(dsmodel = "formula",
criteria = "character",
truncation = "numeric",
binned.data = "logical",
cutpoints = "numeric",
analysis.strata = "data.frame",
ddf.result = "list", "VIRTUAL"))
setMethod(
f="initialize",
signature="DDF.Analysis",
definition=function(.Object, dsmodel = call(), criteria = "AIC", analysis.strata = data.frame(), truncation = 50, binned.data = FALSE, cutpoints = numeric(0)){
if(criteria %in% c("aic", "AIC", "bic", "BIC", "AICc")){
}else{
warning("This selection criteria is not currently supported (please select from 'AIC', 'BIC' or 'AICc'), the simulation is automatically changing it to AIC for this call", call. = FALSE, immediate. = TRUE)
criteria = "AIC"
}
.Object@dsmodel <- dsmodel
.Object@criteria <- criteria
.Object@truncation <- truncation
[email protected] <- binned.data
.Object@cutpoints <- cutpoints
[email protected] <- analysis.strata
[email protected]$design.id <- as.character([email protected]$design.id)
[email protected]$analysis.id <- as.character([email protected]$analysis.id)
validObject(.Object)
return(.Object)
}
)
setValidity("DDF.Analysis",
function(object){
return(TRUE)
}
)
setMethod(
f="run.analysis",
signature=c("DDF.Analysis","DDF.Data"),
definition=function(object, data, dht = FALSE, point = FALSE, warnings = list()){
dist.data <- [email protected]
dist.data <- dist.data[!is.na(dist.data),]
if(is.null(dist.data$detected)){
dist.data$detected <- rep(1, nrow(dist.data))
}
if([email protected]){
dist.data <- dist.data[dist.data$distance <= max(object@cutpoints),]
dist.data <- create.bins(dist.data, cutpoints = object@cutpoints)
if(point){
fit.model <- paste("ddf(dsmodel = ~", as.character(object@dsmodel)[2] ,", data = dist.data, method = 'ds', meta.data = list(width = ", max(object@cutpoints), ", point = TRUE, binned = TRUE, breaks = ", object@cutpoints ,"), control = list(silent = TRUE))", sep = "")
}else{
fit.model <- paste("ddf(dsmodel = ~", as.character(object@dsmodel)[2] ,", data = dist.data, method = 'ds', meta.data = list(width = ", max(object@cutpoints), ", binned = TRUE, breaks = ", object@cutpoints ,"), control = list(silent = TRUE))", sep = "")
}
}else{
if(length(object@truncation) == 0){
if(point){
model.fit <- paste("ddf(dsmodel = ~", as.character(object@dsmodel)[2] ,", data = dist.data, method = 'ds', meta.data = list(point = TRUE), control = list(silent = TRUE))", sep = "")
}else{
model.fit <- paste("ddf(dsmodel = ~", as.character(object@dsmodel)[2] ,", data = dist.data, method = 'ds', control = list(silent = TRUE))", sep = "")
}
}else{
if(point){
model.fit <- paste("ddf(dsmodel = ~", as.character(object@dsmodel)[2] ,", data = dist.data, method = 'ds', meta.data = list(point = TRUE, width = ", object@truncation,"), control = list(silent = TRUE))", sep = "")
}else{
model.fit <- paste("ddf(dsmodel = ~", as.character(object@dsmodel)[2] ,", data = dist.data, method = 'ds', meta.data = list(width = ", object@truncation,"), control = list(silent = TRUE))", sep = "")
}
}
}
W <- NULL
ddf.result <- withCallingHandlers(tryCatch(eval(parse(text = model.fit)),
error=function(e)e),
warning=function(w){W <<- w; invokeRestart("muffleWarning")})
if(any(class(ddf.result) == "error")){
warnings <- message.handler(warnings, paste("Error: ", ddf.result$message, " (Model call: ", as.character(object@dsmodel)[2], ")", sep = ""))
ddf.result <- NA
}else if(ddf.result$ds$converge != 0){
ddf.result <- NA
warnings <- message.handler(warnings, paste("The following model failed to converge: ", object@dsmodel, sep = ""))
}else if(any(predict(ddf.result)$fitted < 0)){
ddf.result <- NA
warnings <- message.handler(warnings, "Negative predictions, excluding these results")
}
if(!is.null(W)){
warnings <- message.handler(warnings, paste(W, " (Model call: ", as.character(object@dsmodel)[2], ")", sep = ""))
}
return(list(ddf.result = ddf.result, warnings = warnings))
}
) |
test_that("Running Python scripts can be interrupted", {
skip_on_cran()
skip("interrupt test failing, needs fixing")
time <- import("time", convert = TRUE)
system(paste("sleep 1 && kill -s INT", Sys.getpid()), wait = FALSE)
before <- Sys.time()
interrupted <- tryCatch(time$sleep(5), interrupt = identity)
after <- Sys.time()
expect_s3_class(interrupted, "interrupt")
diff <- difftime(after, before, units = "secs")
expect_true(diff < 2)
}) |
gen.arch.wge=function(n,alpha0,alpha, plot='TRUE',sn=0)
{
if (sn > 0) {set.seed(sn)}
q=length(alpha)
spin=1000
ntot=n+spin+q
eps<-rnorm(ntot, mean=0, sd=1);
sig2 <- rep(1, ntot)
asq=rep(0,ntot)
qp1=q+1
for (t in q) { sig2[t]=1 }
for(t in qp1:ntot) {
sig2[t]<-alpha0
for (i in 1:q) {sig2[t]=sig2[t]+alpha[i]*asq[t-i]^2}
asq[t]=eps[t]*(sig2[t])^.5}
spinq=spin+q
spinq1=spinq+1
real=asq[spinq1:ntot]
if(plot== 'TRUE') {plot(real,type='l',xlab='')}
return(real)
} |
scatterMatrix <- ufs::scatterMatrix; |
structure(list(`Study ID` = c(1, 2, 3, 4, 5), `First Name` = c("Nutmeg",
"Tumtum", "Marcus", "Trudy", "John Lee"), `Last Name` = c("Nutmouse",
"Nutmouse", "Wood", "DAG", "Walker"), `Street, City, State, ZIP` = c("14 Rose Cottage St.\nKenning UK, 323232",
"14 Rose Cottage Blvd.\nKenning UK 34243", "243 Hill St.\nGuthrie OK 73402",
"342 Elm\nDuncanville TX, 75116", "Hotel Suite\nNew Orleans LA, 70115"
), `Phone number` = c("(405) 321-1111", "(405) 321-2222", "(405) 321-3333",
"(405) 321-4444", "(405) 321-5555"), `E-mail` = c("[email protected]",
"[email protected]", "[email protected]", "[email protected]", "[email protected]"
), `Date of birth` = structure(c(12294, 12121, -13051, -6269,
-5375), class = "Date"), `Age (years)` = c(11, 11, 80, 61, 59
), Gender = c(0, 1, 1, 0, 1), `Complete?` = c(2, 2, 2, 2, 2),
`Height (cm)` = c(7, 6, 180, 165, 193.04), `Weight (kilograms)` = c(1,
1, 80, 54, 104), BMI = c(204.1, 277.8, 24.7, 19.8, 27.9),
Comments = c("Character in a book, with some guessing", "A mouse character from a good book",
"completely made up", "This record doesn't have a DAG assigned\n\nSo call up Trudy on the telephone\nSend her a letter in the mail",
"Had a hand for trouble and a eye for cash\n\nHe had a gold watch chain and a black mustache"
), Mugshot = c("mugshot-1.jpg", "mugshot-2.jpg", "mugshot-3.jpg",
"mugshot-4.jpg", "mugshot-5.jpg"), `Complete?_1` = c(1, 0,
2, 2, 0), `Race (Select all that apply) (choice=American Indian/Alaska Native)` = c(0,
0, 0, 0, 1), `Race (Select all that apply) (choice=Asian)` = c(0,
0, 0, 1, 0), `Race (Select all that apply) (choice=Native Hawaiian or Other Pacific Islander)` = c(0,
1, 0, 0, 0), `Race (Select all that apply) (choice=Black or African American)` = c(0,
0, 1, 0, 0), `Race (Select all that apply) (choice=White)` = c(1,
1, 1, 1, 0), `Race (Select all that apply) (choice=Unknown / Not Reported)` = c(0,
0, 0, 0, 1), Ethnicity = c(1, 1, 0, 1, 2), `Are interpreter services requested?` = c(0,
0, 1, NA, 0), `Complete?_2` = c(2, 0, 2, 2, 2)), row.names = c(NA,
-5L), class = "data.frame") |
tar_test("tar_toggle() interactive globals", {
skip_if_not_installed("knitr")
options <- knitr::opts_chunk$get()
options$code <- "x <- tar_toggle(1L + 1L, NULL)"
options$echo <- FALSE
options$engine <- "targets"
options$label <- "test"
options$results <- "hide"
options$tar_globals <- TRUE
options$tar_interactive <- TRUE
tar_engine_knitr(options)
expect_equal(tar_option_get("envir")$x, 2L)
})
tar_test("tar_toggle() interactive targets", {
skip_if_not_installed("knitr")
options <- knitr::opts_chunk$get()
options$code <- "tar_toggle(1L + 2L)"
options$echo <- FALSE
options$engine <- "targets"
options$label <- "test"
options$results <- "hide"
options$tar_simple <- TRUE
options$tar_globals <- FALSE
options$tar_interactive <- TRUE
tar_engine_knitr(options)
expect_equal(tar_option_get("envir")$test, 3L)
})
tar_test("tar_toggle() noninteractive", {
skip_if_not_installed("knitr")
tar_runtime$set_interactive(FALSE)
on.exit(tar_runtime$unset_interactive())
expect_equal(tar_toggle(1L, 2L), 2L)
}) |
xyplot(births ~ date, data = Births78) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.