code
stringlengths 1
13.8M
|
---|
knitr::opts_chunk$set(echo = TRUE, fig.width = 7, fig.height = 5)
library(qtl2)
library(qtl2fst)
iron <- read_cross2(system.file("extdata", "iron.zip", package="qtl2"))
pr <- calc_genoprob(iron, error_prob=0.002)
apr <- genoprob_to_alleleprob(pr)
tmpdir <- file.path(tempdir(), "iron_genoprob")
dir.create(tmpdir)
fpr <- fst_genoprob(pr, "pr", tmpdir, quiet=TRUE)
fapr <- fst_genoprob(apr, "apr", tmpdir, quiet=TRUE)
list.files(tmpdir)
names(fpr)
apr_X <- fapr[["X"]]
dim(apr_X)
apr_X <- fapr$X
dim(apr_X)
selected_ind <- subset(fapr, ind=1:20, chr=c("2","3"))
dim(fapr)
fapr_sub1 <- fapr[1:20, c("2","3")][["3"]]
fapr_sub2 <- fapr[,"2"]
fapr_sub23 <- fapr[,c("2","3")]
fapr_subX <- fapr[,"X"]
dim(subset(fapr, mar=1:30))
dim(fapr[ , , dimnames(fapr)$mar$X[1:2]])
fapr_sub223 <- cbind(fapr_sub2,fapr_sub23)
f23a <- fapr[1:20, c("2","3")]
f23b <- fapr[40:79, c("2","3")]
f23 <- rbind(f23a, f23b)
markers <- dimnames(fapr$X)[[3]][1:2]
dim(fapr[,,markers]$X)
markers <- dimnames(fapr$X)[[3]]
dim(fapr$X[,,markers[1:2]])
fapr2 <- fst_genoprob(subset(apr, chr="2"), "aprx", tmpdir, quiet=TRUE)
fapr3 <- fst_genoprob(subset(apr, chr="3"), "aprx", tmpdir, quiet=TRUE)
fapr32 <- cbind(fapr3,fapr2)
dim(fapr32)
list.files(tmpdir)
names(unclass(fapr))
unclass(fapr)$fst
sapply(unclass(fapr)[c("ind","chr","mar")], length)
fapr23 <- subset(fapr, chr=c("2","3"))
dim(fapr23)
dim(fst_restore(fapr23))
fst_path(fpr)
fpr_newpath <- replace_path(fpr, tempdir())
fpr <- calc_genoprob_fst(iron, "pr", tmpdir, error_prob=0.002, overwrite=TRUE)
fapr <- genoprob_to_alleleprob_fst(pr, "apr", tmpdir, overwrite=TRUE)
Xcovar <- get_x_covar(iron)
scan_pr <- scan1(fpr, iron$pheno, Xcovar=Xcovar)
find_peaks(scan_pr, iron$pmap, threshold=4)
coef16 <- scan1coef(fpr[,"16"], iron$pheno[,1])
blup16 <- scan1blup(fpr[,"16"], iron$pheno[,1])
unlink(tmpdir)
|
knitr::opts_chunk$set(collapse = T, comment = "
options(tibble.print_min = 4, tibble.print_max = 4)
library(eurlex)
library(dplyr)
query_dir <- elx_make_query(resource_type = "directive")
dirs <- elx_make_query(resource_type = "directive", include_date = TRUE, include_force = TRUE) %>%
elx_run_query() %>%
rename(date = `callret-3`)
results <- dirs %>% select(-force,-date)
query_dir %>%
cat()
elx_make_query(resource_type = "caselaw") %>%
cat()
elx_make_query(resource_type = "manual", manual_type = "SWD") %>%
cat()
elx_make_query(resource_type = "directive", include_date = TRUE, include_force = TRUE) %>%
cat()
elx_make_query(resource_type = "recommendation", include_date = TRUE, include_lbs = TRUE) %>%
cat()
elx_make_query(resource_type = "any",
directory = "18",
sector = 3) %>%
cat()
as_tibble(results)
head(results$type,5)
results %>%
distinct(type)
rec_eurovoc <- elx_make_query("recommendation", include_eurovoc = TRUE, limit = 10) %>%
elx_run_query()
rec_eurovoc %>%
select(celex, eurovoc)
eurovoc_lookup <- elx_label_eurovoc(uri_eurovoc = rec_eurovoc$eurovoc)
print(eurovoc_lookup)
rec_eurovoc %>%
left_join(eurovoc_lookup)
eurovoc_lookup <- elx_label_eurovoc(uri_eurovoc = rec_eurovoc$eurovoc,
alt_labels = TRUE,
language = "sk")
rec_eurovoc %>%
left_join(eurovoc_lookup) %>%
select(celex, eurovoc, labels)
elx_fetch_data(url = results$work[1], type = "title")
library(purrr)
dir_titles <- results[1:10,] %>%
mutate(title = map_chr(work, elx_fetch_data, "title")) %>%
as_tibble() %>%
select(celex, title)
print(dir_titles)
library(ggplot2)
dirs %>%
count(force) %>%
ggplot(aes(x = force, y = n)) +
geom_col()
dirs %>%
filter(!is.na(force)) %>%
mutate(date = as.Date(date)) %>%
ggplot(aes(x = date, y = celex)) +
geom_point(aes(color = force), alpha = 0.1) +
theme(axis.text.y = element_blank(),
axis.line.y = element_blank(),
axis.ticks.y = element_blank())
dirs_1970_title <- dirs %>%
filter(between(as.Date(date), as.Date("1970-01-01"), as.Date("1980-01-01")),
force == "true") %>%
mutate(title = map_chr(work,elx_fetch_data,"title")) %>%
as_tibble()
print(dirs_1970_title)
library(tidytext)
library(wordcloud)
dirs_1970_title %>%
select(celex,title) %>%
unnest_tokens(word, title) %>%
count(celex, word, sort = TRUE) %>%
filter(!grepl("\\d", word)) %>%
bind_tf_idf(word, celex, n) %>%
with(wordcloud(word, tf_idf, max.words = 40, scale = c(1.8,0.1)))
|
BLE_SRS <- function(ys, N, m=NULL, v=NULL, sigma=NULL, n=NULL){
mes_1 <- "parameter 'm' (prior mean) not informed, sample mean used in estimations"
mes_2 <- "parameter 'sigma' (prior variability) not informed, sample variance used in estimations"
mes_3 <- "parameter 'v' (prior variance of an element) not informed, (10^100 * mean(ys)) used in estimations (non-informative prior)"
mes_4 <- "sample mean informed instead of sample observations, parameters 'n' and 'sigma' will be necessary"
if(length(ys)==1){
message(mes_4)
if( (is.null(sigma)) | is.null(n) ){
stop("ys of length 1 requires not null parameters 'sigma' and 'n'")
}
ys <- rep(ys, n)
}
if (is.null(m)){
message(mes_1)
m <- mean(ys)
}
if(is.null(sigma)){
message(mes_2)
sigma <- sqrt(var(ys))
}
if(is.null(v)){
message(mes_3)
v <- 10^100 * mean(ys)}
if(v < sigma^2){
stop("prior variance (parameter 'v') too small")
}
xs <- create1(ys)
a <- m
Vs <- diag(xs)*(sigma^2)
c <- v - sigma^2
R <- c
x_nots <- rep(1,N - length(ys))
V_nots <- diag(x_nots)*(sigma^2)
return(BLE_Reg(ys,xs,a,R,Vs,x_nots,V_nots))
}
BLE_SSRS <- function(ys, h, N, m=NULL, v=NULL, sigma=NULL){
mes_1 <- "parameter 'm' (prior mean) not informed, sample mean used in estimations"
mes_2 <- "parameter 'sigma' (prior variability) not informed, sample variance used in estimations"
mes_3 <- "parameter 'v' (prior variance of an element) not informed, (10^100 * mean(ys)) used in estimations (non-informative prior)"
mes_4 <- "sample means informed instead of sample observations, parameter 'sigma' will be necessary"
H <- length(h)
if(H == 1){stop("only 1 strata defined, try using the BLE_SRS() function")}
if(length(ys)!=sum(h)){
if(length(ys)!=length(h)){
stop("length of 'ys' incompatable with 'h'")
}
else{
message(mes_4)
if(is.null(sigma)){
stop("not null parameter 'sigma' required")
}
ys <- rep(ys, h)
}
}
marker <- c(1)
for(i in 2:H){
marker <- c(marker, marker[i-1] + h[i-1])
}
if (is.null(m)){
message(mes_1)
m <- c(mean(ys[1:h[1]]))
for(i in 2:H-1){
M <- mean(ys[marker[i]:(marker[i+1] - 1)])
m <- c(m, M)
}
M <- mean(ys[marker[H] : length(ys)])
m <- c(m, M)
}
if(is.null(sigma)){
message(mes_2)
s <- c(var(ys[1:h[1]]))
for(i in 2:H-1){
S <- var(ys[marker[i]:(marker[i+1] - 1)])
s <- c(s, S)
}
S <- var(ys[marker[H] : length(ys)])
s <- c(s, S)
sigma <- sqrt(s)
}
if(is.null(v)){
message(mes_3)
v <- c()
for(i in 1:H){
V <- 10^100 * m[i]
v <- c(v, V)
}
}
for (i in 1:H) {
if(v[i] < sigma[i]^2){
stop("prior variance (parameter 'v') too small")
}
}
aux <- rep(1, h[1])
for(i in 2:H){
zero <- rep(0, sum(h))
one <- rep(1, h[i])
aux <- c(aux, zero, one)
}
xs <- matrix(aux,nrow = sum(h),ncol=H)
out <- N-h
aux_out <- rep(1, out[1])
for(i in 2:H){
zero <- rep(0, sum(out))
one <- rep(1, out[i])
aux_out <- c(aux_out, zero, one)
}
x_nots <- matrix(aux_out,nrow = sum(out),ncol=H)
Vs <- diag(h[1])*(sigma[1])^2
for (i in 2:H) {
V <- diag(h[i])*(sigma[i])^2
Vs <- bdiag(Vs,V)
}
Vs <- as.matrix(Vs)
k <- N[1] - h[1]
V_nots <- diag(k)*(sigma[1])^2
for (i in 2:H) {
k <- N[i] - h[i]
V <- diag(k)*(sigma[i])^2
V_nots <- bdiag(V_nots,V)
}
V_nots <- as.matrix(V_nots)
a <- m
c <- v - sigma^2
R <- c*diag(H)
return(BLE_Reg(ys,xs,a,R,Vs,x_nots,V_nots))
}
BLE_Ratio <- function(ys, xs, x_nots, m=NULL, v=NULL, sigma=NULL, n=NULL){
mes_1 <- "parameter 'm' (prior mean) not informed, sample mean used in estimations"
mes_2 <- "parameter 'sigma' (prior variability) not informed, sample variance used in estimations"
mes_3 <- "parameter 'v' (prior variance of an element) not informed, (10^100 * mean(ys)) used in estimations (non-informative prior)"
mes_4 <- "sample means informed instead of sample observations, parameters 'n' and 'sigma' will be necessary"
if(length(ys) != length(xs)){
stop("dimensions of ys and xs are different")
}
if(length(ys)==1){
message(mes_4)
if( (is.null(sigma)) | is.null(n) ){
stop("ys of length 1 requires not null parameters 'sigma' and 'n'")
}
ys <- rep(ys, n)
xs <- rep(xs, n)
}
z <- ys/xs
if (is.null(m)){
message(mes_1)
m <- mean(ys)/mean(xs)
}
if(is.null(sigma)){
message(mes_2)
sigma <- sqrt(var(z))
}
if(is.null(v)){
message(mes_3)
v <- 10^100 * mean(ys)}
if(v < sigma^2){
stop("prior variance (parameter 'v') too small")
}
Vs <- diag(xs)*(sigma^2)
V_nots <- diag(x_nots)*(sigma^2)
a <- m
c <- v - sigma^2
R <- c
return(BLE_Reg(ys,xs,a,R,Vs,x_nots,V_nots))
}
|
scan.zones = function(coords, pop, ubpop = 0.5, longlat = FALSE) {
arg_check_scan_zones(coords, pop, ubpop, longlat)
d = sp::spDists(as.matrix(coords), longlat = longlat)
nn = nnpop(d, pop, ubpop)
zones = nn2zones(nn)
return(zones[distinct(zones)])
}
arg_check_scan_zones = function(coords, pop,
ubpop, longlat) {
arg_check_coords(coords)
N = nrow(coords)
arg_check_pop(pop, N)
arg_check_ubpop(ubpop)
arg_check_longlat(longlat)
}
|
context("test-againstDotC")
test_that("int", {
cc <- .C("TEST_times2_int", a = 2L, r = integer(1),
PACKAGE = "dotCall64")
dc <- .C64("TEST_times2_int", c("int", "int"), a = 2L, r = integer(1),
INTENT = c("rw", "rw"),
PACKAGE = "dotCall64")
expect_equal(cc, dc, label = "[values]")
expect_equal(lapply(cc, typeof), lapply(dc, typeof),
label = "[types]")
})
test_that("double", {
cc <- .C("TEST_times2_double", a = 2.2, r = double(1),
PACKAGE = "dotCall64")
dc <- .C64("TEST_times2_double", c("double", "double"),
a = 2.2, r = double(1),
INTENT = c("rw", "rw"),
PACKAGE = "dotCall64")
expect_equal(cc, dc, label = "[values]")
expect_equal(lapply(cc, typeof), lapply(dc, typeof),
label = "[types]")
})
test_that("referenced-integer", {
input <- 2L
cc <- .C("TEST_times2_int", a = input, r = input,
PACKAGE = "dotCall64")
dc <- .C64("TEST_times2_int", c("int", "int"),
a = input, r = input,
INTENT = c("rw", "rw"),
PACKAGE = "dotCall64")
expect_equal(cc, dc, label = "[values]")
expect_equal(lapply(cc, typeof), lapply(dc, typeof),
label = "[types]")
expect_identical(input, 2L)
})
test_that("referenced-double", {
input <- 2.2
cc <- .C("TEST_times2_double", a = input, r = input,
PACKAGE = "dotCall64")
dc <- .C64("TEST_times2_double", c("double", "double"),
a = input, r = input,
INTENT = c("rw", "rw"),
PACKAGE = "dotCall64")
expect_equal(cc, dc, label = "[values]")
expect_equal(lapply(cc, typeof), lapply(dc, typeof),
label = "[types]")
expect_identical(input, 2.2)
})
|
spec_hist <- function(x, width = 200, height = 50, res = 300,
breaks = "Sturges",
same_lim = TRUE, lim = NULL,
xaxt = 'n', yaxt = 'n', ann = FALSE,
col = "lightgray", border = NULL,
dir = if (is_latex()) rmd_files_dir() else tempdir(),
file = NULL,
file_type = if (is_latex()) "pdf" else svglite::svglite,
...) {
if (is.list(x)) {
if (same_lim & is.null(lim)) {
lim <- base::range(unlist(x), na.rm=TRUE)
}
dots <- listify_args(x, width, height, res, breaks,
lim, xaxt, yaxt, ann, col, border,
dir, file, file_type,
lengths = c(1, length(x)))
return(do.call(Map, c(list(f = spec_hist), dots)))
}
if (is.null(x)) return(NULL)
if (is.null(lim)) {
lim <- base::range(x, na.rm=TRUE)
}
if (!dir.exists(dir)) {
dir.create(dir)
}
file_ext <- dev_chr(file_type)
if (is.null(file)) {
file <- normalizePath(
tempfile(pattern = "hist_", tmpdir = dir, fileext = paste0(".", file_ext)),
winslash = "/", mustWork = FALSE)
}
graphics_dev(filename = file, dev = file_type,
width = width, height = height, res = res,
bg = "transparent")
curdev <- grDevices::dev.cur()
on.exit(grDevices::dev.off(curdev), add = TRUE)
graphics::par(mar = c(0, 0, 0.2, 0), lwd=0.5)
graphics::hist(x, breaks = breaks, xlim = lim, border = border,
xaxt = xaxt, yaxt = yaxt, ann = ann, col = col, ...)
grDevices::dev.off(curdev)
out <- make_inline_plot(
file, file_ext, file_type,
width, height, res,
del = TRUE)
return(out)
}
spec_boxplot <- function(x, width = 200, height = 50, res = 300,
add_label = FALSE, label_digits = 2,
same_lim = TRUE, lim = NULL,
xaxt = 'n', yaxt = 'n', ann = FALSE,
col = "lightgray", border = NULL,
boxlty = 0, medcol = "red", medlwd = 1,
dir = if (is_latex()) rmd_files_dir() else tempdir(),
file = NULL,
file_type = if (is_latex()) "pdf" else svglite::svglite,
...) {
if (is.list(x)) {
if (same_lim & is.null(lim)) {
lim <- base::range(unlist(x), na.rm=TRUE)
}
dots <- listify_args(x, width, height, res,
add_label, label_digits,
lim, xaxt, yaxt, ann, col, border,
dir, file, file_type,
lengths = c(1, length(x)))
return(do.call(Map, c(list(f = spec_boxplot), dots)))
}
if (is.null(x)) return(NULL)
if (is.null(lim)) {
lim <- base::range(x, na.rm=TRUE)
lim[1] <- lim[1] - (lim[2] - lim[1]) / 10
lim[2] <- (lim[2] - lim[1]) / 10 + lim[2]
}
if (!dir.exists(dir)) {
dir.create(dir)
}
file_ext <- dev_chr(file_type)
if (is.null(file)) {
file <- normalizePath(
tempfile(pattern = "boxplot_", tmpdir = dir, fileext = paste0(".", file_ext)),
winslash = "/", mustWork = FALSE)
}
graphics_dev(filename = file, dev = file_type,
width = width, height = height, res = res,
bg = "transparent")
curdev <- grDevices::dev.cur()
on.exit(grDevices::dev.off(curdev), add = TRUE)
graphics::par(mar = c(0, 0, 0, 0))
graphics::boxplot(x, horizontal = TRUE, ann = ann, frame = FALSE, bty = 'n', ylim = lim,
col = col, border = border,
boxlty = boxlty, medcol = medcol, medlwd = medlwd,
axes = FALSE, outcex = 0.2, whisklty = 1,
...)
if (add_label) {
x_median <- round(median(x, na.rm = T), label_digits)
x_min <- round(min(x, na.rm = T), label_digits)
x_max <- round(max(x, na.rm = T), label_digits)
graphics::text(x_median, y = 1.4, labels = x_median, cex = 0.5)
graphics::text(x_min, y = 0.6, labels = x_min, cex = 0.5)
graphics::text(x_max, y = 0.6, labels = x_max, cex = 0.5)
}
grDevices::dev.off(curdev)
out <- make_inline_plot(
file, file_ext, file_type,
width, height, res,
del = TRUE)
return(out)
}
is_latex <- knitr::is_latex_output
rmd_files_dir <- function(create = TRUE) {
curr_file_name <- sub("\\.[^\\.]*$", "", knitr::current_input())
dir_name <- paste0(curr_file_name, "_files")
if (!dir.exists(dir_name) & create) dir.create(dir_name)
fig_dir_name <- file.path(dir_name, "figure-latex/")
if (!dir.exists(fig_dir_name) & create) dir.create(fig_dir_name)
return(fig_dir_name)
}
spec_plot <- function(x, y = NULL, width = 200, height = 50, res = 300,
same_lim = TRUE, xlim = NULL, ylim = NULL,
xaxt = 'n', yaxt = 'n', ann = FALSE,
col = "lightgray", border = NULL,
frame.plot = FALSE, lwd = 2,
pch = ".", cex = 2, type = "l", polymin = NA,
minmax = list(pch = ".", cex = cex, col = "red"),
min = minmax, max = minmax,
dir = if (is_latex()) rmd_files_dir() else tempdir(),
file = NULL, file_type = if (is_latex()) "pdf" else svglite::svglite,
...) {
if (is.list(x)) {
lenx <- length(x)
if (same_lim) {
if (is.null(xlim)) {
xlim <- base::range(unlist(x), na.rm = TRUE)
}
if (is.null(ylim) && !is.null(y)) {
ylim <- base::range(c(unlist(y), polymin), na.rm = TRUE)
}
}
if (is.null(y)) {
y <- list(y)
} else if (length(y) != lenx) {
stop("'x' and 'y' are not the same length")
}
dots <- listify_args(x, y = y, width, height, res,
xlim, ylim, xaxt, yaxt, ann, col, border, frame.plot,
lwd, pch, cex, type, polymin, minmax, min, max,
dir, file, file_type,
lengths = c(1, lenx))
return(do.call(Map, c(list(f = spec_plot), dots)))
}
if (is.null(x)) return(NULL)
if (is.null(y) || !length(y)) {
y <- x
x <- seq_along(y)
if (!is.null(xlim) && is.null(ylim)) {
ylim <- range(c(xlim, polymin), na.rm = TRUE)
xlim <- range(x)
}
}
if (is.null(xlim)) {
xlim <- base::range(x, na.rm = TRUE)
}
if (is.null(ylim) && !is.null(y)) {
ylim <- base::range(c(y, polymin), na.rm = TRUE)
}
if (is.null(min)) min <- minmax
if (is.null(max)) max <- minmax
expand <- c(
if (!is.null(min) && length(min)) -0.04 else 0,
if (!is.null(max) && length(max)) +0.04 else 0)
xlim <- xlim + diff(xlim) * expand
ylim <- ylim + diff(ylim) * expand
if (!dir.exists(dir)) {
dir.create(dir)
}
file_ext <- dev_chr(file_type)
if (is.null(file)) {
file <- normalizePath(
tempfile(pattern = "plot_", tmpdir = dir, fileext = paste0(".", file_ext)),
winslash = "/", mustWork = FALSE)
}
graphics_dev(filename = file, dev = file_type,
width = width, height = height, res = res,
bg = "transparent")
curdev <- grDevices::dev.cur()
on.exit(grDevices::dev.off(curdev), add = TRUE)
graphics::par(mar = c(0, 0, 0, 0), lwd = lwd)
dots <- list(...)
if (!is.na(polymin) && "angle" %in% names(dots)) {
angle <- dots$angle
dots$angle <- NULL
} else angle <- 45
do.call(graphics::plot,
c(list(x, y, type = if (is.na(polymin)) type else "n",
xlim = xlim, ylim = ylim,
xaxt = xaxt, yaxt = yaxt, ann = ann, col = col,
frame.plot = frame.plot, cex = cex, pch = pch),
dots))
if (!is.na(polymin)) {
lty <- if ("lty" %in% names(dots)) dots$lty else graphics::par("lty")
graphics::polygon(c(x[1], x, x[length(x)]), c(polymin, y, polymin),
border = NA, col = col, angle = angle, lty = lty,
xpd = if ("xpd" %in% names(dots)) dots$xpd else NA)
}
if (!is.null(min) && length(min)) {
if (!"xpd" %in% names(min)) min$xpd <- NA
ind <- which.min(y)
do.call(graphics::points, c(list(x[ind], y[ind]), min))
}
if (!is.null(max) && length(max)) {
if (!"xpd" %in% names(max)) max$xpd <- NA
ind <- which.max(y)
do.call(graphics::points, c(list(x[ind], y[ind]), max))
}
grDevices::dev.off(curdev)
out <- make_inline_plot(
file, file_ext, file_type,
width, height, res,
del = TRUE)
return(out)
}
spec_pointrange <- function(
x, xmin, xmax, vline = NULL,
width = 200, height = 50, res = 300,
same_lim = TRUE, lim = NULL,
xaxt = 'n', yaxt = 'n', ann = FALSE,
col = "red", cex = 0.3, frame.plot = FALSE,
dir = if (is_latex()) rmd_files_dir() else tempdir(),
file = NULL,
file_type = if (is_latex()) "pdf" else svglite::svglite, ...) {
if (length(x) > 1) {
if (same_lim & is.null(lim)) {
all_range <- c(unlist(xmin), unlist(xmax))
lim <- base::range(all_range, na.rm=TRUE)
lim <- lim + c(-0.04 * diff(lim), 0.04 * diff(lim))
}
dots <- listify_args(
x = as.list(x), xmin = as.list(xmin), xmax = as.list(xmax), vline,
width, height, res,
lim, xaxt, yaxt, ann, col, cex, frame.plot,
dir, file, file_type,
lengths = c(1, length(x)),
passthru = c("x", "xmin", "xmax"))
return(do.call(Map, c(list(f = spec_pointrange), dots)))
}
if (is.null(x)) return(NULL)
if (is.null(lim)) {
one_range <- unlist(c(xmin, xmax))
lim <- base::range(one_range, na.rm=TRUE)
lim <- lim + c(-0.04 * diff(lim), 0.04 * diff(lim))
}
if (!dir.exists(dir)) {
dir.create(dir)
}
file_ext <- dev_chr(file_type)
if (is.null(file)) {
file <- normalizePath(
tempfile(pattern = "pointrange_", tmpdir = dir, fileext = paste0(".", file_ext)),
winslash = "/", mustWork = FALSE)
}
graphics_dev(filename = file, dev = file_type,
width = width, height = height, res = res,
bg = "transparent")
curdev <- grDevices::dev.cur()
on.exit(grDevices::dev.off(curdev), add = TRUE)
graphics::par(mar = c(0, 0, 0.2, 0), lwd=1,
ann = ann, xaxt = xaxt, yaxt = yaxt)
graphics::plot(x, 0, type = "p", pch = ".",
xlim = lim, frame.plot = frame.plot)
graphics::arrows(xmin, 0, xmax, 0, cex / 15, angle = 90, code = 3)
graphics::points(x, 0, col = col, type = "p", pch = 15, cex = cex)
if (!is.null(vline)) {
graphics::abline(v = vline, lty = 3)
}
grDevices::dev.off(curdev)
out <- make_inline_plot(
file, file_ext, file_type,
width, height, res,
del = TRUE)
return(out)
}
|
NULL
qqplot.lagged <- function(x=rnorm(1000),y=rnorm(1000),z=NULL,when=1:length(x),lag=1,pch=1,...){
if (lag<=0) {
stop("Error in qqplot.lagged: lag less than 1!!")
}
if (is.data.frame(x)) {
xdata <- x
x <- xdata[,1]
y <- xdata[,2]
if (ncol(xdata)>2) {
z <- list()
for (i in 1:(ncol(xdata)-2)) {
z[[i]] <- xdata[,i+2]
}
}
}
xl <- array(0,length(x)-lag+1)
yl <- array(0,length(y)-lag+1)
if (is.list(z)) {
pch <- 1:(length(z)+1)
zl <- list()
for (i in 1:length(z)) {
zl[[i]] <- array(0,length(z[[i]])-lag+1)
}
}
for (l in 0:(lag-1)) {
xl <- xl+x[(lag-l):(length(x)-l)]
yl <- yl+y[(lag-l):(length(y)-l)]
if (is.list(z)) {
for (i in 1:length(z)) {
zl[[i]] <- zl[[i]]+z[[i]][(lag-l):(length(z[[i]])-l)]
}
}
}
whenl <- when[when>=lag]-lag+1
out <- qqplot(xl[whenl],yl[whenl],pch=pch[1],...)
if (is.list(z)) {
xs <- sort(xl[whenl])
for (i in 1:length(z)) {
zs <- sort(zl[[i]][whenl])
points(xs,zs,pch=pch[i+1],...)
}
}
return(0)
}
|
sample_wtatage <- function(wta_file_in, outfile, dat_list, ctl_file_in,
years, fill_fnc = fill_across, fleets,
cv_wtatage = NULL){
if(is.null(cv_wtatage)) stop('specify cv_wtatage in case file')
cat('cv_wtatage is', cv_wtatage, '\n')
if(is.null(fleets)) return(NULL)
agecomp <- dat_list$agecomp[dat_list$agecomp$Lbin_lo== -1,]
cat('sample size is ', unique(agecomp$Nsamp), '\n')
agebin_vector <- dat_list$agebin_vector
mlacomp <- dat_list$MeanSize_at_Age_obs
if(is.null(mlacomp)) stop("No mean length-at-age data found in dat_list")
ss_version <- get_ss_ver_file(ctl_file_in)
ctl <-SS_parlines(ctl_file_in, version = ss_version)
wta_file_in <- readLines(wta_file_in)
wta_file_in <- gsub(" ", replacement=" ", x=wta_file_in)
xx <- grep(x=wta_file_in, "
if(length(xx)!=1) stop("Failed to read in wtatage file")
header <- unlist(strsplit(wta_file_in[xx], " "))
header[-(1:6)] <- paste("age",header[-(1:6)],sep="")
wtatage <- wta_file_in[(xx+1):length(wta_file_in)]
wtatage <- as.data.frame(matrix(as.numeric(unlist(strsplit(wtatage, split=" "))),
nrow=length(wtatage), byrow=TRUE))
names(wtatage) <- gsub("
wtatage$yr <- abs(wtatage$yr)
if(2 %in% unique(wtatage$fleet) == FALSE){
ones <- wtatage[wtatage$fleet == 1, ]
twos <- ones
twos$fleet <- 2
wtatage <- rbind(wtatage, twos)
}
age0 <- wtatage[!duplicated(wtatage$fleet),c("fleet","age0")]
wtatage.new.list <- list(1, 2)
unsampled.wtatage <- list(1, 2, 3)
unsampled.wtatage[[1]] <- wtatage[which(wtatage$fleet == -2), ]
unsampled.wtatage[[2]] <- wtatage[which(wtatage$fleet == -1), ]
unsampled.wtatage[[3]] <- wtatage[which(wtatage$fleet == 0), ]
unsampled.wtatage <- lapply(unsampled.wtatage,
function(x){
x$yr <- -x$yr
return(x)
})
for(fl in fleets) {
wtatage.new.list[[fl]] <- as.data.frame(matrix(NA,nrow=length(years[[fl]]),ncol=ncol(wtatage)))
names(wtatage.new.list[[fl]]) <- names(wtatage)
row.names(wtatage.new.list[[fl]]) <- as.character(years[[fl]])
if(length(years[[fl]]) == 1) {
if(fl <= years[[fl]]) stop("You must designate an earlier fleet to copy from.\n")
wtatage.new.list[[fl]] <- wtatage.new.list[[years[[fl]]]]
wtatage.new.list[[fl]]$fleet <- fl
} else {
for(yr in years[[fl]]) {
agecomp.temp <- agecomp[agecomp$Yr==yr & agecomp$FltSvy == fl, ]
if(nrow(agecomp.temp)==0) {stop("No age comp observations for year",yr,"and fleet",fl,"\n")}
age.means <- as.numeric(agecomp.temp[-(1:9)])
age.Nsamp <- as.numeric(agecomp.temp$Nsamp)
age.samples <- rmultinom(n = 1, size = age.Nsamp, prob = age.means)
names(mlacomp)[3] <- 'FltSvy'
mla.means <- as.numeric(mlacomp[mlacomp$Yr==yr & mlacomp$FltSvy==fl,
paste0("a", agebin_vector)])
CV.growth <- cv_wtatage
Wtlen1 <- ctl[ctl$Label=="Wtlen_1_Fem", "INIT"]
Wtlen2 <- ctl[ctl$Label=="Wtlen_2_Fem", "INIT"]
sds <- mla.means*CV.growth
lengths.list <- as.list(seq(seq_len(nrow(age.samples))))
weights.list <- lengths.list
for(ii in seq_len(nrow(age.samples)))
{
lengths.list[[ii]] <- suppressWarnings(rnorm(n = age.samples[ii], mean = mla.means[ii], sd = sds[ii]))
weights.list[[ii]] <- Wtlen1 * lengths.list[[ii]] ^ Wtlen2
}
samp.wtatage <- sapply(weights.list, mean)
prefix <- wtatage[wtatage$yr==yr & wtatage$fleet==1,1:5]
tmp.fl <- fl
wtatage.new.means <- c(unlist(prefix), tmp.fl, age0[age0$fleet == 1, 'age0'],
samp.wtatage
)
wtatage.new.list[[fl]][as.character(yr), ] <- wtatage.new.means
}
}
}
wtatage.complete <- lapply(wtatage.new.list,fill_fnc,minYear=dat_list$styr,maxYear=dat_list$endyr)
Nlines <- sum(unlist(lapply(unsampled.wtatage, nrow)))
Nlines <- Nlines + sum(unlist(lapply(wtatage.complete, nrow)))
if(is.null(outfile)) cat(dat_list$Nages,"
wtatage.final <- list()
if(is.null(outfile)) cat("
wtatage.final[[1]] <- unsampled.wtatage[[1]]
if(!is.null(outfile)) write.table(unsampled.wtatage[[1]], file=outfile, append=TRUE, row.names=F, col.names=F)
if(!is.null(outfile)) cat("\n
wtatage.final[[2]] <- unsampled.wtatage[[2]]
if(!is.null(outfile)) write.table(unsampled.wtatage[[2]], file=outfile, append=TRUE, row.names=F, col.names=F)
if(!is.null(outfile)) cat("\n
wtatage.final[[3]] <- unsampled.wtatage[[3]]
if(!is.null(outfile)) write.table(unsampled.wtatage[[3]], file=outfile, append=TRUE, row.names=F, col.names=F)
for(i in fleets) {
if(!is.null(outfile)) cat("\n
wtatage.final[[i+3]] <- wtatage.complete[[i]]
wtatage.final[[i+3]]$yr <- -1 * wtatage.final[[i+3]]$yr
if(!is.null(outfile)) write.table(wtatage.final[[i+3]], file=outfile, append=TRUE, row.names=F, col.names=F)
}
endline <- data.frame(t(c(-9999, 1, 1, 1, 1, rep(0, dat_list$Nages))))
if(!is.null(outfile)) write.table(endline, file = outfile, append = TRUE,
row.names = FALSE, col.names = FALSE)
return(invisible(wtatage.final))
}
|
summary.robmixglm <- function(object, ...) {
if (!inherits(object, "robmixglm"))
stop("Use only with 'robmixglm' objects.\n")
out <- list()
out$logLik <- logLik(object)
out$AIC <- AIC(object)
out$BIC <- BIC(object)
coefficients <- matrix(object$fit@coef,ncol=1)
coefficients[,1] <- ifelse(!(object$coef.names=="Outlier p."),coefficients[,1],1.0/(1.0+exp(-coefficients)))
lastnames <- 2
if (object$family %in% c("gaussian","gamma","nbinom")) lastnames <- 3
coef.se <- sqrt(diag(object$fit@vcov))
coef.se[(length(coefficients[,1])-lastnames+1):length(coefficients[,1])] <- NA
coefficients <- cbind(coefficients,coef.se)
coefficients <- cbind(coefficients,coefficients[,1]/coefficients[,2])
coefficients <- cbind(coefficients,2*(1-pnorm(abs(coefficients[,3]))))
dimnames(coefficients)[[1]] <- object$coef.names
dimnames(coefficients)[[2]] <- c("Estimate","Std. Error","z value","Pr(>|z|)")
out$coefficients <- coefficients
class(out) <- "summary.robmixglm"
out
}
|
"linked_sim"
"linked_sim_matrix"
"linked_sim_type"
|
ksResidualDistributions <- function(Y, predicted, E, verbose){
uniqueE <- unique(E)
numUniqueE <- length(uniqueE)
residuals <- Y - predicted
pvalue <- 1
for(e in 1:numUniqueE){
pvalue <- min(pvalue, ks.test( residuals[which(E == uniqueE[e])], residuals[which(E != uniqueE[e])] )$p.value)
if(numUniqueE == 2) break
}
bonfAdjustment <- if(numUniqueE == 2) 1 else numUniqueE
pvalue <- pvalue*bonfAdjustment
if(verbose)
cat(paste("\np-value: ", pvalue))
list(pvalue = pvalue)
}
|
influencePlot <- function(model, ...){
UseMethod("influencePlot")
}
influencePlot.lm <- function(model, scale=10,
xlab="Hat-Values", ylab="Studentized Residuals",
id=TRUE, ...){
id <- applyDefaults(id, defaults=list(method="noteworthy", n=2, cex=1, col=carPalette()[1], location="lr"), type="id")
if (isFALSE(id)){
id.n <- 0
id.method <- "none"
labels <- id.cex <- id.col <- id.location <- NULL
}
else{
labels <- id$labels
if (is.null(labels)) labels <- names(na.omit(residuals(model)))
id.method <- id$method
id.n <- if ("identify" %in% id.method) Inf else id$n
id.cex <- id$cex
id.col <- id$col
id.location <- id$location
}
hatval <- hatvalues(model)
rstud <- rstudent(model)
if (missing(labels)) labels <- names(rstud)
cook <- sqrt(cooks.distance(model))
scale <- scale/max(cook, na.rm=TRUE)
p <- length(coef(model))
n <- sum(!is.na(rstud))
plot(hatval, rstud, xlab=xlab, ylab=ylab, type='n', ...)
abline(v=c(2, 3)*p/n, lty=2)
abline(h=c(-2, 0, 2), lty=2)
points(hatval, rstud, cex=scale*cook, ...)
if(id.method == "noteworthy"){
which.rstud <- order(abs(rstud), decreasing=TRUE)[1:id.n]
which.cook <- order(cook, decreasing=TRUE)[1:id.n]
which.hatval <- order(hatval, decreasing=TRUE)[1:id.n]
which.all <- union(which.rstud, union(which.cook, which.hatval))
id.method <- which.all
}
noteworthy <- if (!isFALSE(id)) showLabels(hatval, rstud, labels=labels, method=id.method,
n=id.n, cex=id.cex, col=id.col, location = id.location)
else NULL
if (length(noteworthy > 0)){
result <- data.frame(StudRes=rstud[noteworthy], Hat=hatval[noteworthy],
CookD=cook[noteworthy]^2)
if (is.numeric(noteworthy)) rownames(result) <- labels[noteworthy]
return(result)
}
else return(invisible(NULL))
}
influencePlot.lmerMod <- function(model, ...){
influencePlot.lm(model, ...)
}
|
visEnrichment <- function (e, nodes_query=NULL, num_top_nodes=5, path.mode=c("all_shortest_paths","shortest_paths","all_paths"), data.type=c("adjp","pvalue","zscore"), height=7, width=7, margin=rep(0.1,4), colormap=c("yr","bwr","jet","gbr","wyr","br","rainbow","wb","lightyellow-orange"), ncolors=40, zlim=NULL, colorbar=T, colorbar.fraction=0.1, newpage=T, layout.orientation=c("left_right","top_bottom","bottom_top","right_left"), node.info=c("both", "none", "term_id", "term_name", "full_term_name"), graph.node.attrs=NULL, graph.edge.attrs=NULL, node.attrs=NULL)
{
path.mode <- match.arg(path.mode)
data.type <- match.arg(data.type)
layout.orientation <- match.arg(layout.orientation)
node.info<- match.arg(node.info)
if (class(e) != "Eoutput"){
stop("The function must apply to 'Eoutput' object.\n")
}
if(class(suppressWarnings(try(dcRDataLoader(paste('onto.', e@ontology, sep=''), verbose=F), T)))=="try-error"){
g <- ''
eval(parse(text=paste("g <- get(load('", e@ontology,"'))", sep="")))
}else{
g <- dcRDataLoader(paste('onto.', e@ontology, sep=''), verbose=F)
}
if(class(g)=="Onto"){
g <- dcConverter(g, from='Onto', to='igraph', verbose=F)
}
num_top_nodes <- as.integer(num_top_nodes)
num_all <- length(pvalue(e))
if(is.null(nodes_query)){
if(num_top_nodes<1 & num_top_nodes>num_all){
num_top_nodes <- min(5, num_all)
}
nodes_query <- names(sort(pvalue(e))[1:num_top_nodes])
}else{
ind <- match(nodes_query, V(g)$name)
nodes_query <- nodes_query[!is.na(ind)]
if(length(nodes_query)==0){
warnings("Nodes/terms in your query are not found in the ontology!\nInstead, the top 5 significant terms (in terms of p-value) will be used.\n")
if(num_top_nodes<1 & num_top_nodes>num_all){
num_top_nodes <- min(5, num_all)
}
nodes_query <- names(sort(pvalue(e))[1:num_top_nodes])
}
}
subg <- dnet::dDAGinduce(g, nodes_query, path.mode=path.mode)
msg <- ''
if(data.type=="adjp"){
data <- -1*log10(adjp(e))
msg <- '-1*log10(adjusted p-values)'
}else if(data.type=="pvalue"){
data <- -1*log10(pvalue(e))
msg <- '-1*log10(p-values)'
}else{
data <- zscore(e)
msg <- 'z-scores'
}
if(sum(is.infinite(data))>0){
data[is.infinite(data)] <- max(data[is.finite(data)])
}
if(is.null(node.attrs)){
nodes.highlight <- rep("black", length(nodes_query))
names(nodes.highlight) <- nodes_query
nodes.fontcolor <- rep("blue", length(nodes_query))
names(nodes.fontcolor) <- nodes_query
nodes.fontsize <- rep(18, length(nodes_query))
names(nodes.fontsize) <- nodes_query
node.attrs <- list(color=nodes.highlight, fontsize=nodes.fontsize)
}
agDAG <- dnet::visDAG(g=subg, data=data, height=height, width=width, margin=margin, colormap=colormap, ncolors=ncolors, zlim=zlim, colorbar=colorbar, colorbar.fraction=colorbar.fraction, newpage=newpage, layout.orientation=layout.orientation, node.info=node.info, graph.node.attrs=graph.node.attrs, graph.edge.attrs=graph.edge.attrs, node.attrs=node.attrs)
message(sprintf("Ontology '%s' containing %d nodes/terms (including %d in query; also highlighted in frame) has been shown in your screen, with colorbar indicating %s", e@ontology, vcount(subg), length(nodes_query), msg), appendLF=T)
invisible(agDAG)
}
|
`disttransform` <-
function(x, method="hellinger") {
x <- as.matrix(x)
METHODS <- c("hellinger", "chord", "profiles", "chi.square", "log", "square", "pa",
"Braun.Blanquet", "Domin", "Hult", "Hill", "fix", "coverscale.log", "dispweight")
method <- match.arg(method,METHODS)
switch(method, hellinger = {
x <- decostand(x,"hellinger")
}, profiles = {
x <- decostand(x,"total")
}, chord = {
x2 <- x^2
rowtot <- apply(x2,1,sum)
for (i in 1:length(rowtot)) {if (rowtot[i]==0) {rowtot[i] <- 1}}
rowtot <- rowtot^0.5
x <- x/rowtot
}, chi.square = {
x <- decostand(x, "chi.square")
}, log = {
x <- log(x+1)
}, square = {
x <- x^0.5
}, pa = {
x <- decostand(x, "pa")
}, Braun.Blanquet = {
x <- coverscale(x, "Braun.Blanquet")
}, Domin = {
x <- coverscale(x, "Domin")
}, Hult = {
x <- coverscale(x, "Hult")
}, Hill = {
x <- coverscale(x, "Hill")
}, fix = {
x <- coverscale(x, "fix")
}, coverscale.log = {
x <- coverscale(x, "log")
}, dispweight = {
x <- dispweight(x)
})
for (i in 1:ncol(x)) {x[,i] <- as.numeric(x[,i])}
x <- data.frame(x)
return(x)
}
|
context("Test galah_config")
test_that("galah_config sets default options", {
skip_on_cran()
options(galah_config = NULL)
expect_equal(galah_config()$verbose, TRUE)
})
vcr::use_cassette("logger_config", {
test_that("galah_config checks download_id", {
galah_config(verbose = TRUE)
expect_error(galah_config(download_reason_id = 17))
expect_message(galah_config(download_reason_id = "testing"))
expect_message(galah_config(download_reason_id = "Testing"))
expect_error(galah_config(download_reason_id = "tsting"))
galah_config(verbose = FALSE)
})
})
test_that("galah_config checks inputs", {
expect_error(galah_config(caching = "value"))
expect_error(galah_config(verbose = "value"))
expect_error(galah_config(email = 4))
expect_error(galah_config(cache_directory = "non/existent/dir"))
expect_error(galah_config(bad_option = "value"))
expect_error(galah_config(atlas = "world"))
expect_silent(galah_config(verbose = FALSE, atlas = "Australia"))
expect_error(galah_config(run_checks = "value"))
expect_silent(galah_config(run_checks = TRUE))
})
|
test_that("MCMC: linear binary logit", {
n_chains <- 2
link <- "logit"
data <- dreamer_data_linear_binary(
n_cohorts = c(10, 20, 30),
dose = c(1, 3, 5),
b1 = 1,
b2 = 2,
link = link
)
mcmc <- dreamer_mcmc(
data,
mod = model_linear_binary(
mu_b1 = 0,
sigma_b1 = 1,
mu_b2 = 0,
sigma_b2 = 1,
link = link
),
n_iter = 5,
silent = TRUE,
convergence_warn = FALSE,
n_chains = n_chains
)
assert_mcmc_format(mcmc, n_chains)
test_posterior(
mcmc,
doses = c(1, 3, 2),
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
true_responses = rlang::expr(ilogit(b1 + b2 * dose))
)
test_posterior(
mcmc,
doses = c(1, 3, 2),
reference_dose = .5,
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
true_responses = rlang::expr(
ilogit(b1 + b2 * dose) - ilogit(b1 + b2 * reference_dose)
)
)
})
test_that("MCMC: linear binary probit", {
n_chains <- 2
link <- "probit"
data <- dreamer_data_linear_binary(
n_cohorts = c(10, 20, 30),
dose = c(1, 3, 5),
b1 = 1,
b2 = 2,
link = link
)
mcmc <- dreamer_mcmc(
data,
mod = model_linear_binary(
mu_b1 = 0,
sigma_b1 = 1,
mu_b2 = 0,
sigma_b2 = 1,
link = link
),
n_iter = 5,
silent = TRUE,
convergence_warn = FALSE,
n_chains = n_chains
)
assert_mcmc_format(mcmc, n_chains)
test_posterior(
mcmc,
doses = c(1, 3, 2),
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
true_responses = rlang::expr(iprobit(b1 + b2 * dose))
)
test_posterior(
mcmc,
doses = c(1, 3, 2),
reference_dose = .5,
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
true_responses = rlang::expr(
iprobit(b1 + b2 * dose) - iprobit(b1 + b2 * reference_dose)
)
)
})
test_that("MCMC: linear binary logit long linear", {
n_chains <- 2
t_max <- 4
times <- c(0, 2, 4)
link <- "logit"
data <- dreamer_data_linear_binary(
n_cohorts = c(10, 20, 30),
dose = c(1, 3, 5),
b1 = 1,
b2 = 2,
link = link,
longitudinal = "linear",
a = .5,
times = times,
t_max = t_max
)
mcmc <- dreamer_mcmc(
data,
mod = model_linear_binary(
mu_b1 = 0,
sigma_b1 = 1,
mu_b2 = 0,
sigma_b2 = 1,
link = link,
longitudinal = model_longitudinal_linear(0, 1, t_max)
),
n_iter = 5,
silent = TRUE,
convergence_warn = FALSE,
n_chains = n_chains
)
assert_mcmc_format(mcmc, n_chains, times)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
a = 10:1 / 100,
true_responses = rlang::expr(ilogit(a + time / !!t_max * (b1 + b2 * dose)))
)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
reference_dose = .5,
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
a = 10:1 / 100,
true_responses = rlang::expr(
ilogit(a + (time / !!t_max) * (b1 + b2 * dose)) -
ilogit((a + time / !!t_max * (b1 + b2 * reference_dose)))
)
)
})
test_that("MCMC: linear binary probit long linear", {
n_chains <- 2
t_max <- 4
times <- c(0, 2, 4)
link <- "probit"
data <- dreamer_data_linear_binary(
n_cohorts = c(10, 20, 30),
dose = c(1, 3, 5),
b1 = 1,
b2 = 2,
link = link,
longitudinal = "linear",
a = .5,
times = times,
t_max = t_max
)
mcmc <- dreamer_mcmc(
data,
mod = model_linear_binary(
mu_b1 = 0,
sigma_b1 = 1,
mu_b2 = 0,
sigma_b2 = 1,
link = link,
longitudinal = model_longitudinal_linear(0, 1, t_max)
),
n_iter = 5,
silent = TRUE,
convergence_warn = FALSE,
n_chains = n_chains
)
assert_mcmc_format(mcmc, n_chains, times)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
a = 10:1 / 100,
true_responses = rlang::expr(iprobit(a + time / !!t_max * (b1 + b2 * dose)))
)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
reference_dose = .5,
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
a = 10:1 / 100,
true_responses = rlang::expr(
iprobit(a + (time / !!t_max) * (b1 + b2 * dose)) -
iprobit((a + time / !!t_max * (b1 + b2 * reference_dose)))
)
)
})
test_that("MCMC: linear binary logit long ITP", {
n_chains <- 2
t_max <- 4
times <- c(0, 2, 4)
link <- "logit"
data <- dreamer_data_linear_binary(
n_cohorts = c(10, 20, 30),
dose = c(1, 3, 5),
b1 = 1,
b2 = 2,
link = link,
longitudinal = "linear",
a = .5,
times = times,
t_max = t_max
)
mcmc <- dreamer_mcmc(
data,
mod = model_linear_binary(
mu_b1 = 0,
sigma_b1 = 1,
mu_b2 = 0,
sigma_b2 = 1,
link = link,
longitudinal = model_longitudinal_itp(0, 1, t_max = t_max)
),
n_iter = 5,
silent = TRUE,
convergence_warn = FALSE,
n_chains = n_chains
)
assert_mcmc_format(mcmc, n_chains, times)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
a = 10:1 / 100,
c1 = seq(.1, 3, length = 10) / 100,
true_responses = rlang::expr(
ilogit(
a + (1 - exp(- c1 * time)) / (1 - exp(- c1 * !!t_max)) *
(b1 + b2 * dose)
)
)
)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
reference_dose = .5,
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
a = 10:1 / 100,
c1 = seq(.1, 3, length = 10) / 100,
true_responses = rlang::expr(
ilogit(
a + (1 - exp(- c1 * time)) / (1 - exp(- c1 * !!t_max)) *
(b1 + b2 * dose)
) -
ilogit(
a + (1 - exp(- c1 * time)) / (1 - exp(- c1 * !!t_max)) *
(b1 + b2 * reference_dose)
)
)
)
})
test_that("MCMC: linear binary probit long ITP", {
n_chains <- 2
t_max <- 4
times <- c(0, 2, 4)
link <- "probit"
data <- dreamer_data_linear_binary(
n_cohorts = c(10, 20, 30),
dose = c(1, 3, 5),
b1 = 1,
b2 = 2,
link = link,
longitudinal = "linear",
a = .5,
times = times,
t_max = t_max
)
mcmc <- dreamer_mcmc(
data,
mod = model_linear_binary(
mu_b1 = 0,
sigma_b1 = 1,
mu_b2 = 0,
sigma_b2 = 1,
link = link,
longitudinal = model_longitudinal_itp(0, 1, t_max = t_max)
),
n_iter = 5,
silent = TRUE,
convergence_warn = FALSE,
n_chains = n_chains
)
assert_mcmc_format(mcmc, n_chains, times)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
a = 10:1 / 100,
c1 = seq(.1, 3, length = 10) / 100,
true_responses = rlang::expr(
iprobit(
a + (1 - exp(- c1 * time)) / (1 - exp(- c1 * !!t_max)) *
(b1 + b2 * dose)
)
)
)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
reference_dose = .5,
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
a = 10:1 / 100,
c1 = seq(.1, 3, length = 10) / 100,
true_responses = rlang::expr(
iprobit(
a + (1 - exp(- c1 * time)) / (1 - exp(- c1 * !!t_max)) *
(b1 + b2 * dose)
) -
iprobit(
a + (1 - exp(- c1 * time)) / (1 - exp(- c1 * !!t_max)) *
(b1 + b2 * reference_dose)
)
)
)
})
test_that("MCMC: linear binary logit long IDP", {
n_chains <- 2
t_max <- 4
times <- c(0, 2, 4)
link <- "logit"
data <- dreamer_data_linear_binary(
n_cohorts = c(10, 20, 30),
dose = c(1, 3, 5),
b1 = 1,
b2 = 2,
link = link,
longitudinal = "linear",
a = .5,
times = times,
t_max = t_max
)
mcmc <- dreamer_mcmc(
data,
mod = model_linear_binary(
mu_b1 = 0,
sigma_b1 = 1,
mu_b2 = 0,
sigma_b2 = 1,
link = link,
longitudinal = model_longitudinal_idp(0, 1, t_max = t_max)
),
n_iter = 5,
silent = TRUE,
convergence_warn = FALSE,
n_chains = n_chains
)
assert_mcmc_format(mcmc, n_chains, times)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
a = 10:1 / 100,
c1 = seq(.1, 3, length = 10) / 100,
c2 = seq(-.1, -.02, length = 10) / 100,
d1 = seq(3, 4, length = 10) / 100,
d2 = seq(4, 5, length = 10) / 100,
gam = seq(.2, .33, length = 10) / 100,
true_responses = rlang::expr(
ilogit(
a + (b1 + b2 * dose) * (
(1 - exp(- c1 * time)) / (1 - exp(- c1 * d1)) * (time < d1) +
(1 - gam * (1 - exp(- c2 * (time - d1))) /
(1 - exp(- c2 * (d2 - d1)))) * (d1 <= time & time <= d2) +
(1 - gam) * (time > d2)
)
)
)
)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
reference_dose = .5,
prob = c(.25, .75),
a = 10:1 / 100,
b1 = 1:10 / 100,
b2 = 2:11 / 100,
c1 = seq(.1, 3, length = 10) / 100,
c2 = seq(-.1, -.02, length = 10) / 100,
d1 = seq(3, 4, length = 10) / 100,
d2 = seq(4, 5, length = 10) / 100,
gam = seq(.2, .33, length = 10) / 100,
true_responses = rlang::expr(
ilogit(
a + (b1 + b2 * dose) * (
(1 - exp(- c1 * time)) / (1 - exp(- c1 * d1)) * (time < d1) +
(1 - gam * (1 - exp(- c2 * (time - d1))) /
(1 - exp(- c2 * (d2 - d1)))) * (d1 <= time & time <= d2) +
(1 - gam) * (time > d2)
)
) -
ilogit(
(
a + (b1 + b2 * reference_dose) * (
(1 - exp(- c1 * time)) / (1 - exp(- c1 * d1)) * (time < d1) +
(1 - gam * (1 - exp(- c2 * (time - d1))) /
(1 - exp(- c2 * (d2 - d1)))) * (d1 <= time & time <= d2) +
(1 - gam) * (time > d2)
)
)
)
)
)
})
test_that("MCMC: linear binary probit long IDP", {
n_chains <- 2
t_max <- 4
times <- c(0, 2, 4)
link <- "probit"
data <- dreamer_data_linear_binary(
n_cohorts = c(10, 20, 30),
dose = c(1, 3, 5),
b1 = 1,
b2 = 2,
link = link,
longitudinal = "linear",
a = .5,
times = times,
t_max = t_max
)
mcmc <- dreamer_mcmc(
data,
mod = model_linear_binary(
mu_b1 = 0,
sigma_b1 = 1,
mu_b2 = 0,
sigma_b2 = 1,
link = link,
longitudinal = model_longitudinal_idp(0, 1, t_max = t_max)
),
n_iter = 5,
silent = TRUE,
convergence_warn = FALSE,
n_chains = n_chains
)
assert_mcmc_format(mcmc, n_chains, times)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
prob = c(.25, .75),
b1 = 1:10 / 100,
b2 = 2:11 / 100,
a = 10:1 / 100,
c1 = seq(.1, 3, length = 10) / 100,
c2 = seq(-.1, -.02, length = 10) / 100,
d1 = seq(3, 4, length = 10) / 100,
d2 = seq(4, 5, length = 10) / 100,
gam = seq(.2, .33, length = 10) / 100,
true_responses = rlang::expr(
iprobit(
a + (b1 + b2 * dose) * (
(1 - exp(- c1 * time)) / (1 - exp(- c1 * d1)) * (time < d1) +
(1 - gam * (1 - exp(- c2 * (time - d1))) /
(1 - exp(- c2 * (d2 - d1)))) * (d1 <= time & time <= d2) +
(1 - gam) * (time > d2)
)
)
)
)
test_posterior(
mcmc,
doses = c(1, 3, 2),
times = c(1, 5, 2),
reference_dose = .5,
prob = c(.25, .75),
a = 10:1 / 100,
b1 = 1:10 / 100,
b2 = 2:11 / 100,
c1 = seq(.1, 3, length = 10) / 100,
c2 = seq(-.1, -.02, length = 10) / 100,
d1 = seq(3, 4, length = 10) / 100,
d2 = seq(4, 5, length = 10) / 100,
gam = seq(.2, .33, length = 10) / 100,
true_responses = rlang::expr(
iprobit(
a + (b1 + b2 * dose) * (
(1 - exp(- c1 * time)) / (1 - exp(- c1 * d1)) * (time < d1) +
(1 - gam * (1 - exp(- c2 * (time - d1))) /
(1 - exp(- c2 * (d2 - d1)))) * (d1 <= time & time <= d2) +
(1 - gam) * (time > d2)
)
) -
iprobit(
(
a + (b1 + b2 * reference_dose) * (
(1 - exp(- c1 * time)) / (1 - exp(- c1 * d1)) * (time < d1) +
(1 - gam * (1 - exp(- c2 * (time - d1))) /
(1 - exp(- c2 * (d2 - d1)))) * (d1 <= time & time <= d2) +
(1 - gam) * (time > d2)
)
)
)
)
)
})
|
lists_users <- function(user = NULL, reverse = FALSE, token = NULL, parse = TRUE) {
params <- list(
reverse = reverse
)
params[[user_type(user)]] <- user
r <- TWIT_get(token, "/1.1/lists/list", params)
if (parse) {
r <- as_lists_users(r)
r <- as.data.frame(r)
}
r
}
|
emmacheck <- function(x, graph, fn1 = NULL, fn2 = NULL, fn3 = NULL, fn4 = NULL, nresp=1)
{
x$yspace <- estimateModel(x,graph,nresp=nresp)
x$yspace[x$tested,] <- as.data.frame(x$ypop)
d <- distance(x$xpop,x$xspace,x$yspace,x$weight,x$opt)
Gb.pred <- which.min(d$fit)
if(! Gb.pred %in% x$tested){
x$add <- 1
print("PERFORM THE FOLLOWING ADDITIONAL EXPERIMENT:")
print(x$xspace[Gb.pred,])
x$xpop <- rbind(x$xpop,x$xspace[Gb.pred,])
x$tested <- c(x$tested,Gb.pred)
x$ypop <- rbind(x$ypop,rep(0,ncol(x$ypop)))
if (!is.null(fn1)) x$ypop[nrow(x$ypop),1] <- fn1(x$xspace[Gb.pred,])
if (!is.null(fn2)) x$ypop[nrow(x$ypop),2] <- fn2(x$xspace[Gb.pred,])
if (!is.null(fn3)) x$ypop[nrow(x$ypop),3] <- fn3(x$xspace[Gb.pred,])
if (!is.null(fn4)) x$ypop[nrow(x$ypop),4] <- fn4(x$xspace[Gb.pred,])
if (is.null(fn1)) {
ypop <- NULL
print("ADD THE MEASURED RESPONSE VALUES TO ypop")
}
}
return(x)
}
|
maxent <- function (constr, states, prior, tol = 1e-07, lambda = FALSE)
{
if (is.vector(constr))
{
means.names <- names(constr)
constr <- matrix(constr, 1, length(constr))
dimnames(constr) <- list("set1", means.names)
}
if (is.data.frame(constr))
constr <- as.matrix(constr)
if (!is.numeric(constr))
stop("constr must only contain numeric values\\n")
if (!is.numeric(tol))
stop("tol must be numeric\\n")
if (!is.logical(lambda))
stop("lambda must be logical\\n")
if (is.vector(states))
{
s.names <- names(states)
states <- matrix(states, nrow = 1, ncol = length(states))
dimnames(states) <- list("constraint", s.names)
}
if (is.data.frame(states))
states <- as.matrix(states)
if (!is.numeric(states))
stop("states must only contain numeric values\\n")
if (any(states <= 0))
stop("states cannot contain zero or negative values\\n")
if (dim(states)[2] == 1 && dim(states)[1] > 1)
states <- t(states)
s.names <- dimnames(states)[[2]]
c.names <- dimnames(states)[[1]]
set.names <- dimnames(constr)[[1]]
n.states <- dim(states)[2]
n.traits <- dim(states)[1]
n.sets <- dim(constr)[1]
if (n.traits != dim(constr)[2])
stop("number of constraints in constr should be equal to number of constraints in states\\n")
if (missing(prior))
{
prior <- matrix(1/n.states, n.sets, n.states)
dimnames(prior) <- list(set.names, s.names)
}
if (is.vector(prior))
{
if (length(prior) != n.states)
{
stop("number of states in prior should be equal to number in states\\n")
}
if (n.sets == 1)
{
prior <- matrix(prior, 1, length(prior))
dimnames(prior) <- list("set1", s.names)
}
else
{
prior <- matrix(rep(prior, n.sets), n.sets, length(prior), byrow = T)
dimnames(prior) <- list(set.names, s.names)
}
}
if (is.data.frame(prior))
prior <- as.matrix(prior)
if (!is.numeric(prior))
stop("prior must only contain numeric values\\n")
if (dim(prior)[2] == 1 && dim(prior)[1] > 1)
prior <- t(prior)
if (dim(prior)[2] != n.states)
stop("number of states in prior should be equal to number in states\\n")
if (dim(prior)[1] > 1 && dim(prior)[1] != n.sets)
stop("number of rows in prior should be 1 or equal to number of rows in constr\\n")
if (dim(prior)[1] == 1)
{
prior <- matrix(rep(prior[1, ], n.sets), n.sets, ncol(prior), byrow = T)
}
if (any(prior < 0 | prior > 1))
{
stop("prior must contain probabilities between 0 and 1\\n")
}
prior <- t(apply(prior, 1, function(x) x/sum(x)))
dimnames(prior) <- list(set.names, s.names)
if (any(is.na(constr)) || any(is.na(states)) || any(is.na(prior)))
{
stop("no NA's allowed\\n")
}
allprobs <- matrix(NA, n.sets, n.states)
dimnames(allprobs) <- list(set.names, s.names)
moments <- matrix(NA, n.sets, n.traits)
dimnames(moments) <- list(set.names, c.names)
entropy <- rep(NA, n.sets)
names(entropy) <- set.names
iter <- rep(NA, n.sets)
names(iter) <- set.names
if (lambda)
{
lambdas <- matrix(NA, n.sets, n.traits + 2)
dimnames(lambdas) <- list(set.names, c("intercept", c.names, "prior"))
}
for (i in 1:n.sets)
{
itscale <- .Fortran("itscale5", as.double(t(states)), as.integer(n.states), as.integer(n.traits), as.double(constr[i, ]), as.double(prior[i, ]), prob = double(n.states), entropy = double(1), niter = integer(1), as.double(tol), moments = double(n.traits), PACKAGE = "rexpokit")
allprobs[i, ] <- itscale$prob
moments[i, ] <- itscale$moments
entropy[i] <- itscale$entropy
iter[i] <- itscale$niter
if (lambda)
{
lambdas[i, ] <- coef(lm(log(itscale$prob) ~ t(states) + log(prior[i, ])))
}
}
res <- list()
if (n.sets == 1)
{
res$prob <- allprobs[1, ]
res$moments <- moments[1, ]
names(entropy) <- NULL
res$entropy <- entropy
names(iter) <- NULL
res$iter <- iter
if (lambda)
res$lambda <- lambdas[1, ]
res$constr <- constr[1, ]
res$states <- states
res$prior <- prior[1, ]
} else {
res$prob <- allprobs
res$moments <- moments
res$entropy <- entropy
res$iter <- iter
if (lambda)
res$lambda <- lambdas
res$constr <- constr
res$states <- states
res$prior <- prior
}
return(res)
}
|
patches_frm2amira<-function(path_folder_frm,path_amira_folder){
dir.create(path_amira_folder)
for(m in 1:length(list.files(path_folder_frm))){
first<-readLines(paste(path_folder_frm,list.files(path_folder_frm)[m],sep="/"))
first_pos<-which(substr(first,1,9)=="<pointset")+1
first_range<-which(first[(first_pos+1)]=="</pointset>")
curves_pos<-first_pos[-first_range]
for(j in 1:length(curves_pos)){
temp_num<-strsplit(first[curves_pos[j]-1],"")
temp_num2<-which(is.na(as.numeric(temp_num[[1]]))==FALSE)
if(length(temp_num2)==1){
pos_num<-as.numeric(temp_num[[1]][length(temp_num[[1]])-2])}
if(length(temp_num2)!=1){
pos_num<-as.numeric(paste(temp_num[[1]][temp_num2],sep=""))
pos_num<-pos_num[1]*10+pos_num[2]
}
patch_i<-as.matrix(read.table(paste(path_folder_frm,path_amira_folder,sep="/"),
skip=curves_pos[j], nrows=pos_num))
lista<-list(patch_i)
names(lista)<-paste("patch",j,list.files(path_folder_frm)[m])
export_amira(lista,path_amira_folder)
}
}
}
|
context('Equilibrium computation')
library(GPareto)
library(copula)
library(DiceDesign)
test_that("KS equilibrium computation is correct", {
xgrid <- seq(0,1,length.out = 101)
Xgrid <- as.matrix(expand.grid(xgrid, xgrid))
Z <- P2(Xgrid)
PF <- nonDom(Z)
Shadow <- apply(PF, 2, min)
Nadir <- apply(PF, 2, max)
KSeq <- GPGame:::getKS(Z = Z, Nadir = Nadir, Shadow = Shadow)
KSeq2 <- GPGame:::getKS_cpp(Z, Nadir, Shadow)
expect_equal(KSeq$id, KSeq2)
ratios <- (matrix(Nadir, nrow = nrow(PF), ncol = ncol(PF), byrow = TRUE) - PF) %*% diag(1/(Nadir - Shadow))
KS_ref <- PF[which.max(apply(ratios, 1, min)),, drop = FALSE]
expect_equal(KSeq$KS, KS_ref)
set.seed(1)
nvar <- 5
n <- 2e6
Z <- matrix(rnorm(n * nvar), n)
Z <- t(apply(Z, 1, function(x) return(-abs(x)/sqrt(sum(x^2)))))
Shadow <- rep(-1, nvar)
Nadir <- rep(0, nvar)
KS_ref <- matrix(rep(- 1/sqrt(nvar), nvar), nrow = 1)
KSeq <- GPGame:::getKS(Z = Z, Nadir = Nadir, Shadow = Shadow)
KSeq2 <- GPGame:::getKS_cpp(Z = Z, Nadir = Nadir, Shadow = Shadow)
expect_equal(KSeq$id, KSeq2)
expect_equal(KSeq$KS, KS_ref, tol = 1e-2)
})
test_that("CKS equilibrium computation is correct", {
nvar <- 2
n <- 1e4
Xgrid <- matrix(runif(n * nvar), n)
Z <- P2(Xgrid)
Shadow <- rep(0, nvar)
Nadir <- rep(1, nvar)
library(copula)
U <- pobs(Z)
KS_U <- GPGame:::getKS(U, Nadir = Nadir, Shadow = Shadow)
PF <- nonDom(U)
CKSeq <- GPGame:::getCKS(Z = Z, Nadir = Nadir, Shadow = Shadow)
expect_equal(Z[KS_U$id,,drop = FALSE], CKSeq$CKS)
set.seed(3)
nvar <- 3
n <- 1e3
U <- matrix(rnorm(n * nvar), n)
U <- t(apply(U, 1, function(x) return(if(sum(x^2) < 1) return(-abs(x)) else return(-abs(x)/sqrt(sum(x^2)))))) + 1
PF_u <- nonDom(U)
Shadow <- rep(0, nvar)
Nadir <- rep(1, nvar)
Z <- U
Z[,1] <- qbeta(U[,1], 2.3 , 0.5)
Z[,2] <- qbeta(U[,2], 2 , 1.5)
Z[,3] <- qbeta(U[,3], 0.75, 1.2)
PF <- nonDom(Z)
CKS_ref <- GPGame:::getKS(Z = U, Nadir = Nadir, Shadow = Shadow)
CKSeq <- GPGame:::getCKS(Z = Z, Nadir = Nadir, Shadow = Shadow)
expect_equal(CKSeq$id, CKS_ref$id)
U2 <- matrix(rnorm(n * nvar), n)
U2 <- t(apply(U2, 1, function(x) return(if(sum(x^2) < 1) return(-abs(x)) else return(-abs(x)/sqrt(sum(x^2)))))) + 1
Z2 <- U2
Z2[,1] <- qbeta(U2[,1], 2.3 , 0.5)
Z2[,2] <- qbeta(U2[,2], 2 , 1.5)
Z2[,3] <- qbeta(U2[,3], 0.75, 1.2)
CKS_U2 <- GPGame:::getCKS(Z2, Nadir = Nadir, Shadow = Shadow)
CKS_U2_kweights <- GPGame:::getCKS(Z, Nadir = Nadir, Shadow = Shadow, Zred = Z2)
expect_equal(CKS_U2$CKS, CKS_U2_kweights$CKS)
})
test_that("getEquilibrium works as intended", {
set.seed(1)
nvar <- 3
n <- 60
design <- lhsDesign(n = n, dimension = nvar, seed = 42)$design
response <- DTLZ2(design)
KS_ref <- matrix(rep(1/sqrt(nvar), nvar), nrow = 1)
CKS_ref_cop <- matrix(c(0.533, 0.533, 0.533), nrow = 1)
CKS_ref <- matrix(c(0.423, 0.42, 0.80), nrow = 1)
models <- list(km(~1, design = design, response = response[,1]),
km(~1, design = design, response = response[,2]),
km(~1, design = design, response = response[,3]))
nsamp <- 1e4
Xsamp <- matrix(runif(nsamp * nvar), nsamp)
preds <- t(predict_kms(models, newdata = Xsamp, type = "UK")$mean)
KSp <- getEquilibrium(Z = preds, nobj = 3, equilibrium = "KSE", return.design = TRUE)
CKSp <- getEquilibrium(Z = preds, nobj = 3, equilibrium = "CKSE", return.design = TRUE)
expect_equal(KSp$NEPoff, KS_ref, tol = 5e-2)
expect_equal(CKSp$NEPoff, CKS_ref, tol = 1e-2)
kweights <- list()
for(u in 1:3){
kn <- covMat1Mat2(models[[u]]@covariance, Xsamp, design)
Knn <- try(chol2inv(chol(covMat1Mat2(models[[u]]@covariance, design, design) + diag(1e-6, nrow(design)))))
kweights <- c(kweights, list(kn %*% Knn))
}
CKSp2 <- getEquilibrium(Z = response, nobj = 3, equilibrium = "CKSE", return.design = TRUE, kweights = kweights)
CKS_emp_ref <- response[which.min(rowSums(sweep(response, 2, CKS_ref, "-")^2)),, drop = FALSE]
expect_equal(CKSp2$NEPoff, CKS_emp_ref)
nsim <- 7
Simus <- NULL
for(u in 1:3){
Simus <- rbind(Simus, simulate(models[[u]], newdata = Xsamp[1:1000,], nsim = nsim, cond = TRUE, checkNames = FALSE))
}
Simus <- t(Simus)
KS_sim <- getEquilibrium(Simus, nobj = 3, equilibrium = "KSE", return.design = TRUE)
CKS_sim <- getEquilibrium(Simus, nobj = 3, equilibrium = "CKSE", return.design = TRUE)
for(u in 1:nsim){
expect_equal(KS_sim$NEPoff[u,, drop = FALSE], getEquilibrium(Simus[,seq(u, nsim*3, by = nsim)], nobj = 3, equilibrium = "KSE", return.design = FALSE))
expect_equal(CKS_sim$NEPoff[u,, drop = FALSE], getEquilibrium(Simus[,seq(u, nsim*3, by = nsim)], nobj = 3, equilibrium = "CKSE", return.design = FALSE))
}
kweights2 <- list()
for(u in 1:3){
kn <- covMat1Mat2(models[[u]]@covariance, Xsamp, Xsamp[1:1000,])
Knn <- try(chol2inv(chol(covMat1Mat2(models[[u]]@covariance, Xsamp[1:1000,], Xsamp[1:1000,]) + diag(1e-6, 1000))))
kweights2 <- c(kweights2, list(kn %*% Knn))
}
CKS_sim2 <- getEquilibrium(Simus, nobj = 3, equilibrium = "CKSE", return.design = TRUE, kweights = kweights2)
expect_equal(KS_sim$NEPoff, matrix(KS_ref, nrow = nsim, ncol = nvar, byrow = TRUE), tol = 5e-2)
expect_equal(CKS_sim$NEPoff, matrix(CKS_ref, nrow = nsim, ncol = nvar, byrow = TRUE), tol = 5e-2)
expect_equal(CKS_sim2$NEPoff, matrix(CKS_ref, nrow = nsim, ncol = nvar, byrow = TRUE), tol = 5e-2)
})
|
gdm_calc_loglikelihood <- function(irtmodel, skillspace, b, a, centerintercepts, centerslopes, TD, Qmatrix,
Ngroup, pi.k, delta.designmatrix, delta, G, theta.k, D, mean.constraint, Sigma.constraint,
standardized.latent, p.aj.xi, group, ind.group, weights, thetaDes, I, K, gwt0, dat,
resp.ind.list, use.freqpatt, p.xi.aj, TP )
{
b <- gdm_est_b_centerintercepts( b=b, centerintercepts=centerintercepts, TD=TD, Qmatrix=Qmatrix )
if (irtmodel=="2PL"){
a <- gdm_est_a_centerslopes( a=a, centerslopes=centerslopes, Qmatrix=Qmatrix, TD=TD )
}
if ( skillspace=="loglinear" ){
res <- gdm_est_skillspace( Ngroup=Ngroup, pi.k=pi.k, Z=delta.designmatrix, G=G, delta=delta, estimate=FALSE )
pi.k <- res$pi.k
delta <- res$delta
}
if ( skillspace=="normal" ){
res <- gdm_est_normalskills( pi.k=pi.k, theta.k=theta.k, irtmodel=irtmodel, G=G, D=D,
mean.constraint=mean.constraint, Sigma.constraint=Sigma.constraint,
standardized.latent=standardized.latent, p.aj.xi=p.aj.xi, group=group, ind.group=ind.group,
weights=weights, b=b, a=a )
pi.k <- res$pi.k
b <- res$b
a <- res$a
}
if ( skillspace=="est" ){
thetaDes <- theta.k
}
probs <- gdm_calc_prob( a=a, b=b, thetaDes=thetaDes, Qmatrix=Qmatrix, I=I, K=K, TP=TP, TD=TD )
res.hwt <- gdm_calc_posterior( probs=probs, gwt0=gwt0, dat=dat, I=I, resp.ind.list=resp.ind.list )
p.xi.aj <- res.hwt$hwt
res <- gdm_calc_deviance( G=G, use.freqpatt=use.freqpatt, ind.group=ind.group, p.xi.aj=p.xi.aj,
pi.k=pi.k, weights=weights )
ll <- res$ll
res <- list(ll=ll, pi.k=pi.k, theta.k=theta.k, thetaDes=thetaDes, a=a, b=b, delta=delta)
return(res)
}
|
convert_hundreds <- function(x) {
if (!length(x)) return(character(0))
hundreds_place <- tens_place <- ones_place <- dash <- rep("", length(x))
class(x) <- "numeric"
x[is.na(x)] <- 0
hundreds_place[x >= 100] <- paste0(digits[x[x >= 100] %/% 100], " hundred ")
x <- x %% 100
tens_place[x >= 20] <- tens[x[x >= 20] %/% 10]
x[x >= 20] <- x[x >= 20] %% 10
ones_place[x > 0] <- digits[x[x > 0]]
dash[tens_place != "" & ones_place != ""] <- "-"
x[] <- trimws(paste0(hundreds_place, tens_place, dash, ones_place))
x
}
|
NULL
paste8 <- function(..., sep = " ", collapse = NULL) {
args <- c(
lapply(list(...), enc2utf8),
list(
sep = if (is.null(sep)) sep else enc2utf8(sep),
collapse = if (is.null(collapse)) collapse else enc2utf8(collapse)
)
)
do.call(paste, args)
}
concat8 <- function(...) {
enc2utf8(paste0(...))
}
registerMethods <- function(methods) {
lapply(methods, function(method) {
pkg <- method[[1]]
generic <- method[[2]]
class <- method[[3]]
func <- get(paste(generic, class, sep="."))
if (pkg %in% loadedNamespaces()) {
registerS3method(generic, class, func, envir = asNamespace(pkg))
}
setHook(
packageEvent(pkg, "onLoad"),
function(...) {
registerS3method(generic, class, func, envir = asNamespace(pkg))
}
)
})
}
.onLoad <- function(...) {
registerMethods(list(
c("knitr", "knit_print", "html"),
c("knitr", "knit_print", "shiny.tag"),
c("knitr", "knit_print", "shiny.tag.list")
))
assign("obj_address", getFromNamespace("sexp_address", "rlang"), environment(.onLoad))
}
depListToNamedDepList <- function(dependencies) {
if (inherits(dependencies, "html_dependency"))
dependencies <- list(dependencies)
if (is.null(names(dependencies))) {
names(dependencies) <- sapply(dependencies, `[[`, "name")
}
return(dependencies)
}
resolveDependencies <- function(dependencies, resolvePackageDir = TRUE) {
deps <- resolveFunctionalDependencies(dependencies)
depnames <- vapply(deps, function(x) x$name, character(1))
depvers <- numeric_version(vapply(deps, function(x) x$version, character(1)))
return(lapply(unique(depnames), function(depname) {
sorted <- order(ifelse(depnames == depname, TRUE, NA), depvers,
na.last = NA, decreasing = TRUE)
dep <- deps[[sorted[[1]]]]
if (resolvePackageDir && !is.null(dep$package)) {
dir <- dep$src$file
if (!is.null(dir)) dep$src$file <- system_file(dir, package = dep$package)
dep$package <- NULL
}
dep
}))
}
subtractDependencies <- function(dependencies, remove, warnOnConflict = TRUE) {
dependencies <- resolveFunctionalDependencies(dependencies)
depnames <- vapply(dependencies, function(x) x$name, character(1))
if (is.character(remove)) {
rmnames <- remove
} else {
remove <- resolveFunctionalDependencies(remove)
rmnames <- vapply(remove, function(x) x$name, character(1))
}
matches <- depnames %in% rmnames
if (warnOnConflict && !is.character(remove)) {
for (loser in dependencies[matches]) {
winner <- remove[[head(rmnames == loser$name, 1)]]
if (compareVersion(loser$version, winner$version) > 0) {
warning(sprintf(paste("The dependency %s %s conflicts with",
"version %s"), loser$name, loser$version, winner$version
))
}
}
}
return(dependencies[!matches])
}
dropNulls <- function(x) {
x[!vapply(x, is.null, FUN.VALUE=logical(1))]
}
nullOrEmpty <- function(x) {
length(x) == 0
}
dropNullsOrEmpty <- function(x) {
x[!vapply(x, nullOrEmpty, FUN.VALUE=logical(1))]
}
isResolvedTag <- function(x) {
inherits(x, "shiny.tag") && length(x$.renderHooks) == 0
}
isTag <- function(x) {
inherits(x, "shiny.tag")
}
print.shiny.tag <- function(x, browse = is.browsable(x), ...) {
if (browse)
html_print(x)
else
print(HTML(as.character(x)), ...)
invisible(x)
}
format.shiny.tag <- function(x, ..., singletons = character(0), indent = 0) {
as.character(renderTags(x, singletons = singletons, indent = indent)$html)
}
as.character.shiny.tag <- function(x, ...) {
as.character(renderTags(x)$html)
}
as.character.html <- function(x, ...) {
as.vector(enc2utf8(x))
}
print.shiny.tag.list <- function(x, ...) {
if (isTRUE(attr(x, "print.as.list", exact = TRUE))) {
attr(x, "print.as.list") <- NULL
class(x) <- setdiff(class(x), "shiny.tag.list")
return(print(x))
}
print.shiny.tag(x, ...)
}
format.shiny.tag.list <- format.shiny.tag
as.character.shiny.tag.list <- as.character.shiny.tag
print.html <- function(x, ..., browse = is.browsable(x)) {
if (browse)
html_print(x)
else
cat(x, "\n", sep = "")
invisible(x)
}
format.html <- function(x, ...) {
as.character(x)
}
normalizeText <- function(text) {
if (!is.null(attr(text, "html", TRUE)))
text
else
htmlEscape(text, attribute=FALSE)
}
tagList <- function(...) {
lst <- dots_list(...)
class(lst) <- c("shiny.tag.list", "list")
return(lst)
}
tagFunction <- function(func) {
if (!is.function(func) || length(formals(func)) != 0) {
stop("`func` must be a function with no arguments")
}
structure(func, class = "shiny.tag.function")
}
tagAddRenderHook <- function(tag, func, replace = FALSE) {
if (!is.function(func) || length(formals(func)) == 0) {
stop("`func` must be a function that accepts at least 1 argument")
}
tag$.renderHooks <-
if (isTRUE(replace)) {
list(func)
} else {
append(tag$.renderHooks, list(func))
}
tag
}
tagAppendAttributes <- function(tag, ..., .cssSelector = NULL) {
throw_if_tag_function(tag)
if (!is.null(.cssSelector)) {
return(
tagQuery(tag)$
find(.cssSelector)$
addAttrs(...)$
allTags()
)
}
newAttribs <- dropNullsOrEmpty(dots_list(...))
if (any(!nzchar(names2(newAttribs)))) {
stop(
"At least one of the new attribute values did not have a name.\n",
"Did you forget to include an attribute name?"
)
}
tag$attribs <- c(tag$attribs, newAttribs)
tag
}
tagHasAttribute <- function(tag, attr) {
throw_if_tag_function(tag)
result <- attr %in% names(tag$attribs)
result
}
tagGetAttribute <- function(tag, attr) {
throw_if_tag_function(tag)
attribs <- tag$attribs
attrIdx <- which(attr == names(attribs))
if (length(attrIdx) == 0) {
return (NULL)
}
result <- attribs[attrIdx]
if (anyNA(result)) {
na_idx <- is.na(result)
if (all(na_idx)) {
return(NA)
}
result <- result[!na_idx]
}
if (all(vapply(result, is.atomic, logical(1)))) {
vals <- vapply(result, function(val) {
val <- as.character(val)
if (length(val) > 1) {
val <- paste0(val, collapse = " ")
}
val
}, character(1))
result <- paste0(vals, collapse = " ")
} else {
names(result) <- NULL
}
result
}
tagAppendChild <- function(tag, child, .cssSelector = NULL) {
throw_if_tag_function(tag)
if (!is.null(.cssSelector)) {
return(
tagAppendChildren(tag, child, .cssSelector = .cssSelector)
)
}
tag$children[[length(tag$children)+1]] <- child
tag
}
tagAppendChildren <- function(tag, ..., .cssSelector = NULL, list = NULL) {
throw_if_tag_function(tag)
children <- unname(c(dots_list(...), list))
if (!is.null(.cssSelector)) {
return(
tagQuery(tag)$
find(.cssSelector)$
append(!!!children)$
allTags()
)
}
tag$children <- unname(c(tag$children, children))
tag
}
tagSetChildren <- function(tag, ..., .cssSelector = NULL, list = NULL) {
throw_if_tag_function(tag)
children <- unname(c(dots_list(...), list))
if (!is.null(.cssSelector)) {
return(
tagQuery(tag)$
find(.cssSelector)$
empty()$
append(!!!children)$
allTags()
)
}
tag$children <- children
tag
}
tagInsertChildren <- function(tag, after, ..., .cssSelector = NULL, list = NULL) {
throw_if_tag_function(tag)
children <- unname(c(dots_list(...), list))
if (!is.null(.cssSelector)) {
return(
tagQuery(tag)$
find(.cssSelector)$
each(function(x, i) {
tagInsertChildren(x, after = after, !!!children)
})$
allTags()
)
}
tag$children <- unname(append(tag$children, children, after))
tag
}
throw_if_tag_function <- function(tag) {
if (is_tag_function(tag))
stop("`tag` can not be a `tagFunction()`")
}
names(known_tags) <- known_tags
NULL
tags <- lapply(known_tags, function(tagname) {
new_function(
args = exprs(... = , .noWS = NULL, .renderHook = NULL),
expr({
validateNoWS(.noWS)
contents <- dots_list(...)
tag(!!tagname, contents, .noWS = .noWS, .renderHook = .renderHook)
}),
env = asNamespace("htmltools")
)
})
rm(known_tags)
p <- tags$p
h1 <- tags$h1
h2 <- tags$h2
h3 <- tags$h3
h4 <- tags$h4
h5 <- tags$h5
h6 <- tags$h6
a <- tags$a
br <- tags$br
div <- tags$div
span <- tags$span
pre <- tags$pre
code <- tags$code
img <- tags$img
strong <- tags$strong
em <- tags$em
hr <- tags$hr
tag <- function(`_tag_name`, varArgs, .noWS = NULL, .renderHook = NULL) {
validateNoWS(.noWS)
varArgsNames <- names2(varArgs)
named_idx <- nzchar(varArgsNames)
attribs <- dropNullsOrEmpty(varArgs[named_idx])
children <- unname(varArgs[!named_idx])
st <- list(name = `_tag_name`,
attribs = attribs,
children = children)
if (!is.null(.noWS)) {
st$.noWS <- .noWS
}
if (!is.null(.renderHook)) {
if (!is.list(.renderHook)) {
.renderHook <- list(.renderHook)
}
st$.renderHooks <- .renderHook
}
structure(st, class = "shiny.tag")
}
isTagList <- function(x) {
is.list(x) && (inherits(x, "shiny.tag.list") || identical(class(x), "list"))
}
noWSOptions <- c("before", "after", "after-begin", "before-end", "outside", "inside")
validateNoWS <- function(.noWS) {
if (!all(.noWS %in% noWSOptions)) {
stop("Invalid .noWS option(s) '", paste(.noWS, collapse="', '") ,"' specified.")
}
}
tagWrite <- function(tag, textWriter, indent=0, eol = "\n") {
if (length(tag) == 0)
return (NULL)
if (!isTag(tag) && isTagList(tag)) {
tag <- dropNullsOrEmpty(flattenTags(tag))
lapply(tag, tagWrite, textWriter, indent)
return (NULL)
}
nextIndent <- if (is.numeric(indent)) indent + 1 else indent
indent <- if (is.numeric(indent)) indent else 0
indentText <- paste(rep(" ", indent*2), collapse="")
textWriter$writeWS(indentText)
if (is.character(tag)) {
.noWS <- attr(tag, "noWS", exact = TRUE)
if ("before" %in% .noWS || "outside" %in% .noWS) {
textWriter$eatWS()
}
textWriter$write(normalizeText(tag))
if ("after" %in% .noWS || "outside" %in% .noWS) {
textWriter$eatWS()
}
textWriter$writeWS(eol)
return (NULL)
}
.noWS <- tag$.noWS
if ("before" %in% .noWS || "outside" %in% .noWS) {
textWriter$eatWS()
}
textWriter$write(concat8("<", tag$name))
attribs <- flattenTagAttribs(lapply(tag$attribs, as.character))
attribNames <- names2(attribs)
if (any(!nzchar(attribNames))) {
stop(
"A tag's attribute value did not have a name.\n",
"Did you forget to name all of your attribute values?"
)
}
for (attrib in attribNames) {
attribValue <- attribs[[attrib]]
if (length(attribValue) > 1) {
attribValue <- concat8(attribValue, collapse = " ")
}
if (!is.na(attribValue)) {
if (is.logical(attribValue)) {
attribValue <- tolower(attribValue)
}
text <- htmlEscape(attribValue, attribute=TRUE)
textWriter$write(concat8(" ", attrib,"=\"", text, "\""))
}
else {
textWriter$write(concat8(" ", attrib))
}
}
children <- dropNullsOrEmpty(flattenTags(tag$children))
if (length(children) > 0) {
textWriter$write(">")
if ((length(children) == 1) && is.character(children[[1]]) ) {
textWriter$write(concat8(normalizeText(children[[1]]), "</", tag$name, ">"))
}
else {
if ("after-begin" %in% .noWS || "inside" %in% .noWS) {
textWriter$eatWS()
}
textWriter$writeWS("\n")
for (child in children)
tagWrite(child, textWriter, nextIndent)
textWriter$writeWS(indentText)
if ("before-end" %in% .noWS || "inside" %in% .noWS) {
textWriter$eatWS()
}
textWriter$write(concat8("</", tag$name, ">"))
}
}
else {
if (tag$name %in% c("area", "base", "br", "col", "command", "embed", "hr",
"img", "input", "keygen", "link", "meta", "param",
"source", "track", "wbr")) {
textWriter$write("/>")
}
else {
textWriter$write(concat8("></", tag$name, ">"))
}
}
if ("after" %in% .noWS || "outside" %in% .noWS) {
textWriter$eatWS()
}
textWriter$writeWS(eol)
}
renderTags <- function(x, singletons = character(0), indent = 0) {
x <- tagify(x)
singletonInfo <- takeSingletons(x, singletons)
headInfo <- takeHeads(singletonInfo$ui)
deps <- resolveDependencies(findDependencies(singletonInfo$ui, tagify = FALSE))
headIndent <- if (is.numeric(indent)) indent + 1 else indent
headHtml <- doRenderTags(headInfo$head, indent = headIndent)
bodyHtml <- doRenderTags(headInfo$ui, indent = indent)
return(list(head = headHtml,
singletons = singletonInfo$singletons,
dependencies = deps,
html = bodyHtml))
}
doRenderTags <- function(x, indent = 0) {
assertNotTagEnvLike(x, "doRenderTags")
textWriter <- WSTextWriter()
tagWrite(x, textWriter, indent)
textWriter$eatWS()
HTML(textWriter$readAll())
}
rewriteTags <- function(ui, func, preorder) {
assertNotTagEnvLike(ui, "rewriteTags")
if (preorder)
ui <- func(ui)
if (isTag(ui)) {
ui$children[] <- lapply(ui$children, rewriteTags, func, preorder)
} else if (isTagList(ui)) {
ui[] <- lapply(ui, rewriteTags, func, preorder)
}
if (!preorder)
ui <- func(ui)
return(ui)
}
NULL
surroundSingletons <- local({
surroundSingleton <- function(uiObj) {
if (is.singleton(uiObj)) {
sig <- digest(uiObj, "sha1")
uiObj <- singleton(uiObj, FALSE)
return(tagList(
HTML(sprintf("<!--SHINY.SINGLETON[%s]-->", sig)),
uiObj,
HTML(sprintf("<!--/SHINY.SINGLETON[%s]-->", sig))
))
} else {
uiObj
}
}
function(ui) {
rewriteTags(ui, surroundSingleton, TRUE)
}
})
takeSingletons <- function(ui, singletons=character(0), desingleton=TRUE) {
result <- rewriteTags(ui, function(uiObj) {
if (is.singleton(uiObj)) {
sig <- digest(uiObj, "sha1")
if (sig %in% singletons)
return(NULL)
singletons <<- append(singletons, sig)
if (desingleton)
uiObj <- singleton(uiObj, FALSE)
return(uiObj)
} else {
return(uiObj)
}
}, TRUE)
return(list(ui=result, singletons=singletons))
}
takeHeads <- function(ui) {
headItems <- list()
result <- rewriteTags(ui, function(uiObj) {
if (isTag(uiObj) && tolower(uiObj$name) == "head") {
headItems <<- append(headItems, uiObj$children)
return(NULL)
}
return(uiObj)
}, FALSE)
return(list(ui=result, head=headItems))
}
findDependencies <- function(tags, tagify = TRUE) {
if (isTRUE(tagify)) {
tags <- tagify(tags)
}
deps <- resolveFunctionalDependencies(htmlDependencies(tags))
children <- if (is.list(tags)) {
if (isTag(tags)) {
tags$children
} else {
tags
}
}
childDeps <- unlist(lapply(children, findDependencies, tagify = FALSE), recursive = FALSE, use.names = FALSE)
c(childDeps, deps)
}
resolveFunctionalDependencies <- function(dependencies) {
if (!length(dependencies)) {
return(dependencies)
}
dependencies <- asDependencies(dependencies)
dependencies <- lapply(dependencies, function(dep) {
if (is_tag_function(dep)) {
dep <- dep()
}
if (isTag(dep) || inherits(dep, "shiny.tag.list")) {
warning(
"It appears attachDependencies() has been used to attach a tagFunction()",
"that returns a shiny.tag/shiny.tag.list, which is considered poor practice",
"since those tags will never actually get rendered", call. = FALSE
)
return(findDependencies(dep))
}
asDependencies(dep)
})
unlist(dependencies, recursive = FALSE, use.names = FALSE)
}
HTML <- function(text, ..., .noWS = NULL) {
htmlText <- c(text, as.character(dots_list(...)))
htmlText <- paste8(htmlText, collapse=" ")
attr(htmlText, "html") <- TRUE
attr(htmlText, "noWS") <- .noWS
class(htmlText) <- c("html", "character")
htmlText
}
withTags <- function(code, .noWS = NULL) {
if (!is.null(.noWS)) {
.noWSWithTags <- .noWS
tags <- lapply(tags, function(tag) {
function(..., .noWS = .noWSWithTags) {
tag(..., .noWS = .noWS)
}
})
}
eval(substitute(code), envir = as.list(tags), enclos = parent.frame())
}
tagify <- function(x) {
rewriteTags(x, function(uiObj) {
if (isResolvedTag(uiObj) || isTagList(uiObj) || is.character(uiObj))
return(uiObj)
else
tagify(as.tags(uiObj))
}, FALSE)
}
flattenTags <- function(x) {
assertNotTagEnvLike(x, "flattenTags")
if (isTag(x)) {
list(x)
} else if (isTagList(x)) {
if (length(x) == 0) {
x
} else {
ret <- unlist(lapply(x, flattenTags), recursive = FALSE)
mostattributes(ret) <- attributes(x)
ret
}
} else if (is.character(x)){
list(x)
} else {
flattenTags(as.tags(x))
}
}
flattenTagsRaw <- function(x) {
relocateHtmlDeps <- function(z, type) {
zDeps <- htmlDependencies(z)
zDepsLen <- length(zDeps)
if (zDepsLen == 0) return(z)
switch(type,
"tag" = {
children <- z[["children"]]
childrenLen <- length(children)
if (is.null(children)) {
z[["children"]] <- zDeps
} else {
z[["children"]][(childrenLen + 1):(childrenLen + zDepsLen)] <- zDeps
}
},
"tagList" = {
zLen <- length(z)
z[(zLen + 1):(zLen + zDepsLen)] <- zDeps
},
stop("unknown type: ", type)
)
htmlDependencies(z) <- NULL
z
}
if (isTagEnv(x)) {
list(x)
} else if (isTag(x)) {
x <- relocateHtmlDeps(x, type = "tag")
list(x)
} else if (isTagList(x)) {
ret <- unlist(lapply(x, flattenTagsRaw), recursive = FALSE)
mostattributes(ret) <- attributes(x)
ret <- relocateHtmlDeps(ret, type = "tagList")
ret
} else {
list(x)
}
}
combineKeys <- function(x) {
if (anyNA(x)) {
na_idx <- is.na(x)
if (all(na_idx)) {
return(NA)
}
x <- x[!na_idx]
}
unlist(x, recursive = FALSE, use.names = FALSE)
}
flattenTagAttribs <- function(attribs) {
attribs <- dropNullsOrEmpty(attribs)
attribNames <- names(attribs)
if (anyDuplicated(attribNames)) {
uniqueAttribNames <- sort(unique(attribNames))
attribs <- lapply(uniqueAttribNames, function(name) {
obj <- attribs[attribNames == name]
combineKeys(obj)
})
names(attribs) <- uniqueAttribNames
}
attribs
}
as.tags <- function(x, ...) {
UseMethod("as.tags")
}
as.tags.default <- function(x, ...) {
if (is.list(x)) {
tagList(!!!unclass(x))
} else {
tagList(as.character(x))
}
}
as.tags.html <- function(x, ...) {
x
}
as.tags.shiny.tag <- function(x, ...) {
if (isResolvedTag(x)) {
return(x)
}
hook <- x$.renderHooks[[1]]
x$.renderHooks[[1]] <- NULL
y <- hook(x)
as.tags(y)
}
as.tags.shiny.tag.list <- function(x, ...) {
x
}
as.tags.shiny.tag.function <- function(x, ...) {
x()
}
as.tags.list <- function(x, ...) {
tagList(!!!x)
}
as.tags.character <- function(x, ...) {
tagList(x)
}
as.tags.html_dependency <- function(x, ...) {
attachDependencies(tagList(), x)
}
htmlPreserve <- function(x) {
html_preserve(x, inline = "auto")
}
html_preserve <- function(x, inline = "auto") {
x <- paste(x, collapse = "\n")
if (!nzchar(x)) {
return(x)
}
if (!getOption("htmltools.preserve.raw", FALSE)) {
return(sprintf("<!--html_preserve-->%s<!--/html_preserve-->", x))
}
if (identical(inline, "auto")) {
inline <- grepl(x, "\n", fixed = TRUE)
}
if (inline) {
sprintf("`%s`{=html}", x)
} else {
sprintf("\n```{=html}\n%s\n```\n", x)
}
}
withTemporary <- function(env, x, value, expr, unset = FALSE) {
if (exists(x, envir = env, inherits = FALSE)) {
oldValue <- get(x, envir = env, inherits = FALSE)
on.exit(
assign(x, oldValue, envir = env, inherits = FALSE),
add = TRUE)
} else {
on.exit(
rm(list = x, envir = env, inherits = FALSE),
add = TRUE
)
}
if (!missing(value) && !isTRUE(unset))
assign(x, value, envir = env, inherits = FALSE)
else {
if (exists(x, envir = env, inherits = FALSE))
rm(list = x, envir = env, inherits = FALSE)
}
force(expr)
}
withPrivateSeed <- local({
ownSeed <- NULL
function(expr) {
withTemporary(.GlobalEnv, ".Random.seed",
ownSeed, unset=is.null(ownSeed), {
tryCatch({
expr
}, finally = {ownSeed <<- .Random.seed})
}
)
}
})
extractPreserveChunks <- function(strval) {
startmarker <- "<!--html_preserve-->"
endmarker <- "<!--/html_preserve-->"
startmarker_len <- nchar(startmarker)
endmarker_len <- nchar(endmarker)
pattern <- "<!--/?html_preserve-->"
if (length(strval) != 1)
strval <- paste(strval, collapse = "\n")
startmatches <- gregexpr(startmarker, strval, fixed = TRUE)[[1]]
endmatches <- gregexpr(endmarker, strval, fixed = TRUE)[[1]]
matches <- c(startmatches, endmatches)
o <- order(matches)
matches <- matches[o]
lengths <- c(
attr(startmatches, "match.length", TRUE),
attr(endmatches, "match.length", TRUE)
)[o]
if (unique(matches)[[1]] == -1)
return(list(value = strval, chunks = character(0)))
boundary_type <- lengths == startmarker_len
preserve_level <- cumsum(ifelse(boundary_type, 1, -1))
if (any(preserve_level < 0) || tail(preserve_level, 1) != 0) {
stop("Invalid nesting of html_preserve directives")
}
is_top_level <- 1 == (preserve_level + c(0, preserve_level[-length(preserve_level)]))
preserved <- character(0)
top_level_matches <- matches[is_top_level]
for (i in seq.int(length(top_level_matches) - 1, 1, by = -2)) {
start_outer <- top_level_matches[[i]]
start_inner <- start_outer + startmarker_len
end_inner <- top_level_matches[[i+1]]
end_outer <- end_inner + endmarker_len
id <- withPrivateSeed(
paste("preserve", paste(
format(as.hexmode(sample(256, 8, replace = TRUE)-1), width=2),
collapse = ""),
sep = "")
)
preserved[id] <- gsub(pattern, "", substr(strval, start_inner, end_inner-1))
strval <- paste(
substr(strval, 1, start_outer - 1),
id,
substr(strval, end_outer, nchar(strval)),
sep="")
substr(strval, start_outer, end_outer-1) <- id
}
list(value = strval, chunks = preserved)
}
restorePreserveChunks <- function(strval, chunks) {
strval <- enc2utf8(strval)
chunks <- enc2utf8(chunks)
for (id in names(chunks))
strval <- gsub(id, chunks[[id]], strval, fixed = TRUE, useBytes = TRUE)
Encoding(strval) <- 'UTF-8'
strval
}
NULL
knit_print.shiny.tag <- function(x, ..., inline = FALSE) {
x <- tagify(x)
output <- surroundSingletons(x)
deps <- resolveDependencies(findDependencies(x, tagify = FALSE), resolvePackageDir = FALSE)
content <- takeHeads(output)
head_content <- doRenderTags(tagList(content$head))
meta <- if (length(head_content) > 1 || head_content != "") {
list(structure(head_content, class = "shiny_head"))
}
meta <- c(meta, deps)
knitr::asis_output(
html_preserve(format(content$ui, indent=FALSE), inline),
meta = meta)
}
knit_print.html <- function(x, ..., inline = FALSE) {
deps <- resolveDependencies(findDependencies(x, tagify = FALSE))
knitr::asis_output(html_preserve(as.character(x), inline),
meta = if (length(deps)) list(deps))
}
knit_print.shiny.tag.list <- knit_print.shiny.tag
includeHTML <- function(path) {
lines <- readLines(path, warn=FALSE, encoding='UTF-8')
return(HTML(paste8(lines, collapse='\n')))
}
includeText <- function(path) {
lines <- readLines(path, warn=FALSE, encoding='UTF-8')
return(paste8(lines, collapse='\n'))
}
includeMarkdown <- function(path) {
html <- markdown::markdownToHTML(path, fragment.only=TRUE)
Encoding(html) <- 'UTF-8'
return(HTML(html))
}
includeCSS <- function(path, ...) {
lines <- readLines(path, warn=FALSE, encoding='UTF-8')
args <- dots_list(...)
if (is.null(args$type))
args$type <- 'text/css'
return(do.call(tags$style,
c(list(HTML(paste8(lines, collapse='\n'))), args)))
}
includeScript <- function(path, ...) {
lines <- readLines(path, warn=FALSE, encoding='UTF-8')
return(tags$script(HTML(paste8(lines, collapse='\n')), ...))
}
singleton <- function(x, value = TRUE) {
attr(x, "htmltools.singleton") <- if (isTRUE(value)) TRUE else NULL
return(x)
}
is.singleton <- function(x) {
isTRUE(attr(x, "htmltools.singleton"))
}
validateCssUnit <- function(x) {
if (is.null(x) || is.na(x))
return(x)
if (length(x) > 1 || (!is.character(x) && !is.numeric(x)))
stop('CSS units must be a single-element numeric or character vector')
if (is.character(x) && nchar(x) > 0 && gsub("\\d*", "", x) == "")
x <- as.numeric(x)
pattern <-
"^(auto|inherit|fit-content|calc\\(.*\\)|((\\.\\d+)|(\\d+(\\.\\d+)?))(%|in|cm|mm|ch|em|ex|rem|pt|pc|px|vh|vw|vmin|vmax))$"
if (is.character(x) &&
!grepl(pattern, x)) {
stop('"', x, '" is not a valid CSS unit (e.g., "100%", "400px", "auto")')
} else if (is.numeric(x)) {
x <- paste(x, "px", sep = "")
}
x
}
css <- function(..., collapse_ = "") {
props <- dots_list(...)
if (length(props) == 0) {
return(NULL)
}
if (is.null(names(props)) || any(names(props) == "")) {
stop("cssList expects all arguments to be named")
}
props[] <- lapply(props, paste, collapse = " ")
props <- props[!sapply(props, empty)]
if (length(props) == 0) {
return(NULL)
}
names(props) <- gsub("[._]", "-", tolower(gsub("([A-Z])", "-\\1", names(props))))
important <- ifelse(grepl("!$", names(props), perl = TRUE), " !important", "")
names(props) <- sub("!$", "", names(props), perl = TRUE)
paste0(names(props), ":", props, important, ";", collapse = collapse_)
}
empty <- function(x) {
length(x) == 0 || (is.character(x) && !any(nzchar(x)))
}
|
validity.amigaDisk <- function(object) {
NUMBER_OF_SECTORS <- NUMBER_OF_SECTORS_DD
if (object@type == "HD") NUMBER_OF_SECTORS <- NUMBER_OF_SECTORS_HD
if (typeof(object@data) != "raw") return (F)
if (typeof(object@type) != "character") return (F)
if (length(object@type) != 1) return (F)
if (typeof([email protected]) != "integer") return (F)
if (length([email protected]) != 1) return (F)
if ([email protected] < 0 || [email protected] > NUMBER_OF_SECTORS*NUMBER_OF_SIDES*NUMBER_OF_CYLINDERS) return (F)
if (!(object@type %in% c("DD", "HD"))) return (F)
if (length(object@data) != BLOCK_SIZE*NUMBER_OF_SECTORS*NUMBER_OF_SIDES*NUMBER_OF_CYLINDERS) return (F)
return(T)
}
setClass("amigaDisk",
representation(data = "raw", type = "character", current.dir = "integer"),
prototype(data = raw(NUMBER_OF_CYLINDERS*NUMBER_OF_SECTORS_DD*NUMBER_OF_SIDES*BLOCK_SIZE),
type = "DD",
current.dir = 880L),
validity = validity.amigaDisk)
setGeneric("calculate.checksum", function(x, block, chcksm.pos = 21, as.raw = T) standardGeneric("calculate.checksum"))
setMethod("calculate.checksum", c("amigaDisk", "numeric"), function(x, block, chcksm.pos = 21, as.raw = T) {
x <- amigaBlock(x, block)
calculate.checksum(x@data, NULL, chcksm.pos, as.raw)
})
setMethod("calculate.checksum", c("raw", "ANY"), function(x, block, chcksm.pos = 21, as.raw = T) {
checksum <- 0
for(i in seq(1, BLOCK_SIZE, by = 4)) {
if (i != chcksm.pos) {
checksum <- checksum + rawToAmigaInt(x[i:(i + 3)], 32, F)
if (checksum >= 0x100000000)
checksum <- checksum %% 0x100000000
}
}
checksum <- 0x100000000 - checksum
checksum <- checksum %% 0x100000000
if (as.raw) return(amigaIntToRaw(checksum, 32, F)) else return (checksum)
})
setGeneric("read.adf", function(file) standardGeneric("read.adf"))
setMethod("read.adf", "character", function(file){
file <- file[[1]]
con <- file(file, "rb")
adf <- read.adf(con)
close(con)
return(adf)
})
setMethod("read.adf", "ANY", function(file){
con <- file
if (!("connection" %in% class(con))) stop ("argument con is not a file connection!")
con_info <- summary(con)
if (!(con_info$text == "binary" && con_info$`can read` == "yes")) stop("Unsuitable connection provided. read.adf() requires a binary connection from which can be read.")
dat <- readBin(con, "raw", NUMBER_OF_SECTORS_HD*NUMBER_OF_CYLINDERS*NUMBER_OF_SIDES*BLOCK_SIZE, endian = "big")
tp <- NULL
if (length(dat) == NUMBER_OF_SECTORS_DD*NUMBER_OF_CYLINDERS*NUMBER_OF_SIDES*BLOCK_SIZE) tp <- "DD"
if (length(dat) == NUMBER_OF_SECTORS_HD*NUMBER_OF_CYLINDERS*NUMBER_OF_SIDES*BLOCK_SIZE) tp <- "HD"
if (is.null(tp)) stop ("Unexpected file size.")
adf <- methods::new("amigaDisk", data = dat, type = tp)
test_byte <- readBin(con, "raw", 1, endian = "big")
if (length(test_byte) > 0) stop ("Unexpected file size.")
return(adf)
})
setGeneric("read.adz", function(file) standardGeneric("read.adz"))
setMethod("read.adz", "character", function(file){
file <- file[[1]]
con <- gzfile(file, "rb")
adf <- read.adf(con)
close(con)
return(adf)
})
setGeneric("write.adf", def = function(x, file){
standardGeneric("write.adf")
})
setMethod("write.adf", c("amigaDisk", "ANY"), function(x, file) {
con <- file
if (!("connection" %in% class(con))) stop ("argument con is not a file connection!")
con_info <- summary(con)
if (!(con_info$text == "binary" && con_info$`can write` == "yes")) stop("Unsuitable connection provided. write.module() requires a connection to which binary data can be written.")
writeBin(x@data, con, endian = "big")
invisible()
})
setMethod("write.adf", c("amigaDisk", "character"), function(x, file) {
con <- file(file, "wb")
write.adf(x, con)
close(con)
invisible()
})
setGeneric("write.adz", def = function(x, file) standardGeneric("write.adz"))
setMethod("write.adz", c("amigaDisk", "character"), function(x, file) {
con <- gzfile(file, "wb")
write.adf(x, con)
close(con)
invisible()
})
setMethod("show", "amigaDisk", function(object) {
print(object)
})
setMethod("print", "amigaDisk", function(x, ...){
cat(paste("\nAmiga (", x@type ,") Disk File:\n", sep = ""))
is.dos <- is.amigaDOS(x)
cat(paste("\tType:\t\t\t" , c("Non-", "")[1 + is.bootable(x)], "bootable ", c("Non-DOS", "DOS")[1 + is.dos], "\n", sep = ""))
if (is.dos) {
ri <- root.info(x)
bi <- boot.info(x)
NUMBER_OF_SECTORS <- NUMBER_OF_SECTORS_DD
if (x@type == "HD") NUMBER_OF_SECTORS <- NUMBER_OF_SECTORS_HD
disk.full <- 100*(length(bitmap.info(x)) + 2)/(NUMBER_OF_SIDES*NUMBER_OF_CYLINDERS*NUMBER_OF_SECTORS)
dir.cache <- bi$flag$dir.cache.mode
intl <- bi$flag$intl.mode
if (dir.cache) intl <- TRUE
cat(paste("\tVolume name:\t\t" , ri$diskname, "\n", sep = ""))
cat(sprintf("\tpercentage full:\t%0.1f%%\n", disk.full))
cat(paste("\tFast File System:\t" , bi$flag$fast.file.system, "\n", sep = ""))
cat(paste("\tInternational mode:\t" , intl, "\n", sep = ""))
cat(paste("\tDirect cache mode:\t" , dir.cache, "\n", sep = ""))
}
return(invisible(NULL))
})
setGeneric("is.amigaDOS", function(x) standardGeneric("is.amigaDOS"))
setMethod("is.amigaDOS", "amigaDisk", function(x) {
root.id <- get.root.id(x)
bb <- boot.info(x)
ri <- NULL
try(ri <- root.info(x), T)
result <- T
why <- NULL
notes <- NULL
if (bb$disk.type != "DOS") {
result <- F
why <- c(why, "Disk type is not labeled as 'DOS'")
}
if (x@data[[4]] > as.raw(0x05)) {
result <- F
why <- c(why, "Unknown or unsupported file system flags")
}
if (bb$rootblock != root.id) notes <- c(notes, "Uncommon pointer to rootblock")
if (is.null(ri)) {
result <- F
why <- c(why, "Invalid root block")
} else {
if (length(ri$type) == 0 || ri$type != "T_HEADER") {
result <- F
why <- c(why, "Root block is not of type 'T_HEADER'")
}
if (ri$checksum != calculate.checksum(x, root.id, as.raw = F)) {
result <- F
why <- c(why, "Root block checksum failed")
}
if (length(ri$sec_type) == 0 || ri$sec_type != "ST_ROOT") {
result <- F
why <- c(why, "Root block not found")
}
}
attributes(result)$why <- why
attributes(result)$notes <- notes
return (result)
})
setGeneric("is.bootable", function(x) standardGeneric("is.bootable"))
setMethod("is.bootable", "amigaDisk", function(x) {
bb <- boot.info(x)
result <- T
why <- NULL
notes <- NULL
if (bb$disk.type != "DOS") {
result <- F
why <- c(why, "disk type is not labeled as 'DOS'")
}
if (bb$checksum != calculate.boot.checksum(x, as.raw = F)) {
result <- F
why <- c(why, "Boot block checksum failed")
}
attributes(result)$why <- why
attributes(result)$notes <- notes
return (result)
})
root.info <- function(x) {
root.id <- get.root.id(x)
root <- amigaBlock(x, root.id)
ht_length <- BLOCK_SIZE/4 - 56
r_datetime <- rawToAmigaDate(root@data[ht_length*4 + 133:144])
v_datetime <- rawToAmigaDate(root@data[ht_length*4 + 185:196])
c_datetime <- rawToAmigaDate(root@data[ht_length*4 + 197:208])
name_len <- rawToAmigaInt(root@data[ht_length*4 + 145], 8, F)
name_len[name_len > 30] <- 30
name_len[name_len < 1] <- 1
result <- list(
type = TYPES$type[TYPES$value == rawToAmigaInt(root@data[1:4], 32, F)],
headerkey = rawToAmigaInt(root@data[5:8], 32, F),
highseq = rawToAmigaInt(root@data[9:12], 32, F),
htsize = rawToAmigaInt(root@data[13:16], 32, F),
first_data = rawToAmigaInt(root@data[17:20], 32, F),
checksum = rawToAmigaInt(root@data[21:24], 32, F),
ht = unlist(lapply(1:ht_length, function(y) rawToAmigaInt(root@data[(y*4 + 21):(y*4 + 24)], 32, F))),
bm_flag = all(root@data[ht_length*4 + 25:28] == as.raw(c(0xff, 0xff, 0xff, 0xff))),
bm_pages = unlist(lapply(1:25, function(y) rawToAmigaInt(root@data[(ht_length*4 + y*4 + 25):(ht_length*4 + y*4 + 28)], 32, F))),
bm_ext = rawToAmigaInt(root@data[ht_length*4 + 129:132], 32, F),
r_datetime = r_datetime,
name_len = name_len,
diskname = rawToChar(root@data[ht_length*4 + 146:(name_len + 145)]),
unused1 = root@data[ht_length*4 + 176],
unused2 = root@data[ht_length*4 + 177:184],
v_datetime = v_datetime,
c_datetime = c_datetime,
next_hash = rawToAmigaInt(root@data[ht_length*4 + 209:212], 32, F),
parent_dir = rawToAmigaInt(root@data[ht_length*4 + 213:216], 32, F),
extension = rawToAmigaInt(root@data[ht_length*4 + 217:220], 32, F),
sec_type = SEC_TYPES$type[SEC_TYPES$value == rawToAmigaInt(root@data[ht_length*4 + 221:224], 32, F)]
)
result$diskname <- substr(result$diskname, 1, result$name_len)
return(result)
}
header.info <- function(x, hash.table) {
result <- lapply(hash.table, function(ht) {
hblock <- amigaBlock(x, ht)
ht_length <- BLOCK_SIZE/4 - 56
days <- rawToAmigaInt(hblock@data[ht_length*4 + 133:136], 32, F)
mins <- rawToAmigaInt(hblock@data[ht_length*4 + 137:140], 32, F)
ticks <- rawToAmigaInt(hblock@data[ht_length*4 + 141:144], 32, F)
datetime <- days*24*60*60 + mins*60 + ticks/50
datetime <- as.POSIXct(datetime, tz = "UTC", origin = "1978-01-01 00:00:00")
name_len <- rawToAmigaInt(hblock@data[ht_length*4 + 145], 8, F)
name_len[name_len > 30] <- 30
name_len[name_len < 1] <- 1
header <- list(
type = TYPES$type[TYPES$value == rawToAmigaInt(hblock@data[1:4], 32, F)],
header_key = rawToAmigaInt(hblock@data[5:8], 32, F),
high_seq = rawToAmigaInt(hblock@data[9:12], 32, F),
data_size = rawToAmigaInt(hblock@data[13:16], 32, F),
first_data = rawToAmigaInt(hblock@data[17:20], 32, F),
checksum = rawToAmigaInt(hblock@data[21:24], 32, F),
datablocks = unlist(lapply(1:ht_length, function(y) rawToAmigaInt(hblock@data[(y*4 + 21):(y*4 + 24)], 32, F))),
unused1 = rawToAmigaInt(hblock@data[ht_length*4 + 25:28], 32, F),
UID = rawToAmigaInt(hblock@data[ht_length*4 + 29:32], 32, F),
GID = rawToAmigaInt(hblock@data[ht_length*4 + 33:36], 32, F),
protect = as.logical(rawToBits(hblock@data[ht_length*4 + 33:36])),
bytesize = rawToAmigaInt(hblock@data[ht_length*4 + 37:40], 32, F),
comm_len = rawToAmigaInt(hblock@data[ht_length*4 + 41], 8, F),
comment = rawToCharDot(hblock@data[ht_length*4 + 42:120]),
unused2 = hblock@data[ht_length*4 + 121:132],
datetime = datetime,
name_len = name_len,
file_name = rawToChar(hblock@data[ht_length*4 + 146:(145 + name_len)]),
unused3 = hblock@data[ht_length*4 + 176],
unused4 = hblock@data[ht_length*4 + 177:180],
real_entry = rawToAmigaInt(hblock@data[ht_length*4 + 181:184], 32, F),
next_link = rawToAmigaInt(hblock@data[ht_length*4 + 185:188], 32, F),
unused5 = hblock@data[ht_length*4 + 189:208],
hash_chain = rawToAmigaInt(hblock@data[ht_length*4 + 209:212], 32, F),
parent = rawToAmigaInt(hblock@data[ht_length*4 + 213:216], 32, F),
extension = rawToAmigaInt(hblock@data[ht_length*4 + 217:220], 32, F),
sec_type = SEC_TYPES$type[SEC_TYPES$value == rawToAmigaInt(hblock@data[ht_length*4 + 221:224], 32, F)]
)
header$file_name <- substr(header$file_name, 1, header$name_len)
return(header)
})
return(result)
}
setGeneric("current.adf.dir<-", function(x, value) standardGeneric("current.adf.dir<-"))
setGeneric("current.adf.dir", function(x) standardGeneric("current.adf.dir"))
setMethod("current.adf.dir", "amigaDisk", function(x){
root.id <- get.root.id(x)
ri <- root.info(x)
dir <- paste0(ri$diskname, ":")
dir2 <- ""
if ([email protected] != root.id) {
dir3 <- [email protected]
safeguard <- 0
while (T) {
hi <- header.info(x, dir3)[[1]]
dir3 <- hi$parent
dir2 <- paste0(hi$file_name, "/", dir2)
if (dir3 %in% c(0, root.id)) break
safeguard <- safeguard + 1
if (safeguard > NUMBER_OF_SECTORS_HD*NUMBER_OF_CYLINDERS*NUMBER_OF_SIDES) stop("Seems like I'm stuck in an infinite loop.")
}
}
return(paste0(dir, dir2))
})
setReplaceMethod("current.adf.dir", c("amigaDisk", "character"), function(x, value){
value <- value[[1]]
header.id <- find.file.header(x, value)
hi <- header.info(x, header.id)[[1]]
if (!(hi$sec_type %in% c("ST_USERDIR", "ST_ROOT"))) stop ("value doesn't specify a directory")
[email protected] <- as.integer(header.id)
methods::validObject(x)
return(x)
})
setGeneric("list.adf.files", function(x, path) standardGeneric("list.adf.files"))
setMethod("list.adf.files", c("amigaDisk", "missing"), function(x, path){
fi <- file.info(x, [email protected])
result <- unlist(lapply(fi, function(x) x$file_name))
if (is.null(result)) result <- character(0)
return(result)
})
setMethod("list.adf.files", c("amigaDisk", "character"), function(x, path){
header.id <- find.file.header(x, path)
fi <- file.info(x, header.id)
unlist(lapply(fi, function(x) x$file_name))
})
setGeneric("get.adf.file", function(x, source, destination) standardGeneric("get.adf.file"))
setMethod("get.adf.file", c("amigaDisk", "character", "missing"), function(x, source, destination) {
.get.adf.file(x, source)
})
setMethod("get.adf.file", c("amigaDisk", "character", "character"), function(x, source, destination) {
.get.adf.file(x, source, destination)
})
setMethod("get.adf.file", c("amigaDisk", "character", "ANY"), function(x, source, destination) {
.get.adf.file(x, source, destination)
})
.get.adf.file <- function(x, source, destination) {
if (!is.amigaDOS(x)) stop("Not a DOS disk!")
bi <- boot.info(x)
ffs <- bi$flag$fast.file.system
hi <- header.info(x, find.file.header(x, source))[[1]]
if (hi$sec_type != "ST_FILE") stop( "Provided path does not refer to a file.")
filesize <- hi$bytesize
db <- rev(hi$datablocks[hi$datablocks != 0])
while (hi$extension != 0) {
hi <- header.info(x, hi$extension)[[1]]
db <- c(db, rev(hi$datablocks[hi$datablocks != 0]))
}
dat <- lapply(db, function(db.i) {
if (ffs) {
amigaBlock(x, db.i)@data
} else {
amigaBlock(x, db.i)@data[25:512]
}
})
dat <- do.call(c, dat)[0:filesize]
if (missing(destination)) {
return(dat)
} else {
if (class(destination)[[1]] == "character") {
destination <- destination[[1]]
con <- file(destination, "wb")
writeBin(dat, con)
close(con)
} else {
if (!("connection" %in% class(destination))) stop ("argument destination is not a file connection!")
con_info <- summary(destination)
if (!(con_info$text == "binary" && con_info$`can write` == "yes")) stop("Unsuitable connection provided. get.adf.file() requires a binary connection to which data can be written.")
writeBin(dat, destination)
}
return (invisible(NULL))
}
}
setGeneric("adf.disk.name", function(x) standardGeneric("adf.disk.name"))
setGeneric("adf.disk.name<-", function(x, value) standardGeneric("adf.disk.name<-"))
setMethod("adf.disk.name", "amigaDisk", function(x) {
if (!is.amigaDOS(x)) stop("x is not a DOS formatted disk!")
ri <- root.info(x)
return(ri$diskname)
})
setReplaceMethod("adf.disk.name", c("amigaDisk", "character"), function(x, value){
value <- value[[1]]
if (nchar(value) == 0) stop("Name should be at least 1 character long.")
if (nchar(value) > 30) {
warning("Provided name is too long. It will be truncated.")
value <- substr(value, 1, 30)
}
if (grepl("[:]|[/]", value)) stop("Disk name is not allowed to contain characters ':' or '/'.")
value <- charToRaw(value)
ht_length <- BLOCK_SIZE/4 - 56
root.id <- get.root.id(x)
rblock <- amigaBlock(x, root.id)
rblock@data[ht_length*4 + 145] <- amigaIntToRaw(length(value), 8, F)
rblock@data[ht_length*4 + 146:(length(value) + 145)] <- value
amigaBlock(x, root.id) <- rblock
rblock@data[21:24] <- calculate.checksum(x, root.id, as.raw = T)
amigaBlock(x, root.id) <- rblock
return(x)
})
find.file.header <- function(x, filename) {
if (filename == "") return([email protected])
root.id <- get.root.id(x)
boot <- boot.info(x)
intl <- boot$flag$intl.mode
if (boot$flag$dir.cache.mode) intl <- T
cur.dir <- [email protected]
fun <- function(x, b = intl) intl_toupper(x, b)
diskname <- fun(adf.disk.name(x))
if (is.null(filename)) return (root.id)
filename <- fun(as.character(filename))
result <- lapply(filename, function(f) {
hasdevname <- grepl(":", f, fixed = T)
f <- unlist(strsplit(f, ":", fixed = T))
if (length(f) > 2) stop("Multiple colons in file name.")
if (length(f) == 1) {
if (hasdevname && f != "DF0" && f != diskname) stop("Unknown devicename")
if (hasdevname && (f == "DF0" || f == diskname)) return(root.id)
path <- unlist(strsplit(f, "/", fixed=T))
if (any(diff(which(path != "")) > 1)) stop("unexpected double slashes in path")
count.up <- sum(path == "")
j <- 0
while (j != count.up) {
if (cur.dir == root.id) stop("Can't go further down the directory tree than the disk's root.")
info <- header.info(x, cur.dir)
cur.dir <- info[[1]]$parent
j <- j + 1
}
path <- path[path != ""]
} else {
if (f[[1]] != "DF0" && f[[1]] != diskname) stop("Unknown devicename")
f <- f[[2]]
cur.dir <- root.id
path <- unlist(strsplit(f, "/", fixed = T))
if (any(path == "")) stop ("unexpected double slashes in path")
}
lapply(path, function(pt) {
header <- header.info(x, cur.dir)[[1]]
if (header$sec_type == "ST_ROOT" || header$sec_type == "ST_USERDIR") {
block <- header$datablocks[hash.name(pt, intl) + 1]
} else {
block <- header$header_key
}
safeguard <- 0
while (T) {
hi <- header.info(x, block)[[1]]
if (fun(hi$file_name) == fun(pt)) break
if (hi$hash_chain == 0) break
block <- hi$hash_chain
safeguard <- safeguard + 1
if (safeguard > NUMBER_OF_SECTORS_HD*NUMBER_OF_CYLINDERS*NUMBER_OF_SIDES) stop("Seems like I'm stuck in an infinite loop.")
}
if (fun(hi$file_name) == fun(pt)) {
cur.dir <<- hi$header_key
} else {
stop("File/Path not found...")
}
})
return(cur.dir)
})
return (unlist(result))
}
setGeneric("blank.amigaDOSDisk", function(diskname,
disktype = c("DD", "HD"),
filesystem = c("OFS", "FFS"),
international = F,
dir.cache = F,
bootable = T,
creation.date = Sys.time()) standardGeneric("blank.amigaDOSDisk"))
setMethod("blank.amigaDOSDisk", "character",
function(diskname,
disktype,
filesystem,
international,
dir.cache,
bootable,
creation.date) {
disktype <- match.arg(disktype, c("DD", "HD"))
filesystem <- match.arg(filesystem, c("OFS", "FFS"))
filesystem <- filesystem == "FFS"
international <- as.logical(international[[1]])
dir.cache <- as.logical(dir.cache[[1]])
root.id <- get.root.id(disktype)
if (dir.cache && !international) stop ("International mode should be explicitly set to TRUE when directory cache mode is set to TRUE.")
if (dir.cache) international <- FALSE
boot <- charToRaw("DOS")
boot <- c(boot, packBits(rev(c(rep(F, 5),
dir.cache,
international,
filesystem))),
raw(4),
amigaIntToRaw(root.id, 32))
if (bootable) boot <- c(boot, unlist(adfExplorer::boot.block.code$assembled))
boot <- c(boot, raw(BLOCK_SIZE - length(boot)))
checksum <- calculate.boot.checksum.dat(boot)
boot[5:8] <- checksum
boot <- methods::new("amigaBlock", data = boot)
disk <- methods::new("amigaDisk")
amigaBlock(disk, 0) <- boot
create <- amigaDateToRaw(creation.date)
ht_length <- BLOCK_SIZE/4 - 56
rblock <- c(TYPES$value[TYPES$type == "T_HEADER"],
rep(0, 2),
ht_length,
0,
0,
rep(0, ht_length),
0x100000000 - 1,
root.id + 1,
rep(0, 25),
rep(0,3),
16777216,
rep(0, 9),
rep(0, 8),
ifelse(dir.cache, root.id + 2, 0),
SEC_TYPES$value[SEC_TYPES$type == "ST_ROOT"])
rblock <- amigaIntToRaw(rblock, 32)
rblock[ht_length*4 + 133:144] <- create
rblock[ht_length*4 + 185:196] <- create
rblock[ht_length*4 + 197:208] <- create
rblock[21:24] <- calculate.checksum(rblock)
rblock <- methods::new("amigaBlock", data = c(rblock, raw(BLOCK_SIZE - length(rblock))))
amigaBlock(disk, root.id) <- rblock
adf.disk.name(disk) <- diskname
NUMBER_OF_SECTORS <- ifelse(disktype == "DD", NUMBER_OF_SECTORS_DD, NUMBER_OF_SECTORS_HD)
bitmap <- rep(T, NUMBER_OF_CYLINDERS*NUMBER_OF_SIDES*NUMBER_OF_SECTORS)
bitmap[root.id + 0:1 - 1] <- F
if (dir.cache) bitmap[root.id + 1] <- F
bitmap <- bitmapToRaw(bitmap)
bitmap <- c(raw(4), bitmap, raw(BLOCK_SIZE - length(bitmap) - 4))
bitmap[1:4] <- calculate.checksum(bitmap, chcksm.pos = 1)
bmblock <- methods::new("amigaBlock", data = bitmap)
amigaBlock(disk, root.id + 1) <- bmblock
if (dir.cache) {
dc <- .make.dir.cache.block(data.frame(), root.id, root.id + 2)[[1]]
dcblock <- methods::new("amigaBlock", data = dc)
amigaBlock(disk, root.id + 2) <- dcblock
}
return (disk)
})
setGeneric("allocate.amigaBlock", function(x, number) standardGeneric("allocate.amigaBlock"))
setMethod("allocate.amigaBlock", c("amigaDisk", "missing"), function(x, number) {
allocate.amigaBlock(x, 1)
})
setMethod("allocate.amigaBlock", c("amigaDisk", "numeric"), function(x, number) {
NUMBER_OF_SECTORS <- NUMBER_OF_SECTORS_DD
if (x@type == "HD") NUMBER_OF_SECTORS <- NUMBER_OF_SECTORS_HD
maxblock <- NUMBER_OF_SECTORS*NUMBER_OF_CYLINDERS*NUMBER_OF_SIDES
number <- round(number[[1]])
if (number < 1) stop("Number of blocks to be allocated should be at least 1.")
root.id <- get.root.id(x@type)
bm <- bitmap.info(x)
idx <- c(root.id:(maxblock - 1), 2:(root.id -1))
idx <- idx[!(idx %in% bm)]
if (number > length(idx)) stop("Cannot allocate sufficient blocks.")
return(idx[1:number])
})
setGeneric("reserve.amigaBlock", function(x, blocks) standardGeneric("reserve.amigaBlock"))
setMethod("reserve.amigaBlock", c("amigaDisk", "numeric"), function(x, blocks) {
NUMBER_OF_SECTORS <- ifelse(x@type == "DD", NUMBER_OF_SECTORS_DD, NUMBER_OF_SECTORS_HD)
ri <- root.info(x)
bitmap <- rep(T, NUMBER_OF_CYLINDERS*NUMBER_OF_SIDES*NUMBER_OF_SECTORS)
bitmap[c(bitmap.info(x), blocks) - 1] <- F
bitmap <- bitmapToRaw(bitmap)
bitmap <- c(raw(4), bitmap, raw(BLOCK_SIZE - length(bitmap) - 4))
bitmap[1:4] <- calculate.checksum(bitmap, chcksm.pos = 1)
bm <- ri$bm_pages[ri$bm_pages != 0]
if (length(bm) > 1) stop("unexpected multiple bitmap blocks found on disk, only the first will be updated.")
bm <- bm[[1]]
x@data[bm*BLOCK_SIZE + 1:BLOCK_SIZE] <- bitmap
return(x)
})
setGeneric("clear.amigaBlock", function(x, blocks) standardGeneric("clear.amigaBlock"))
setMethod("clear.amigaBlock", c("amigaDisk", "numeric"), function(x, blocks) {
NUMBER_OF_SECTORS <- ifelse(x@type == "DD", NUMBER_OF_SECTORS_DD, NUMBER_OF_SECTORS_HD)
ri <- root.info(x)
bitmap <- rep(T, NUMBER_OF_CYLINDERS*NUMBER_OF_SIDES*NUMBER_OF_SECTORS)
bitmap[bitmap.info(x) - 1] <- F
bitmap[blocks - 1] <- T
bitmap <- bitmapToRaw(bitmap)
bitmap <- c(raw(4), bitmap, raw(BLOCK_SIZE - length(bitmap) - 4))
bitmap[1:4] <- calculate.checksum(bitmap, chcksm.pos = 1)
bm <- ri$bm_pages[ri$bm_pages != 0]
if (length(bm) > 1) stop("unexpected multiple bitmap blocks found on disk, only the first will be updated.")
bm <- bm[[1]]
x@data[bm*BLOCK_SIZE + 1:BLOCK_SIZE] <- bitmap
return(x)
})
|
`itemFitPlot` <- function(raschResult, itemSet, useItemNames = TRUE,
fitStat = "infit", plotTitle="Item Fit Plot",
xlab, ylab, xlim, ylim, refLines,
col = c("black","white"), colTheme,
gDevice, file){
if(! missing(colTheme)){
if(colTheme=="dukes"){
col <- c("
} else if(colTheme=="spartans"){
col <- c("
} else if(colTheme=="cavaliers"){
col <- c("
} else if(colTheme=="greys"){
col <- c("black","lightgrey")
} else {
col <- c("black","white")
}
}
if(missing(ylab)) ylab <- "Difficulty"
if(missing(itemSet)){
itemSet <- 1:raschResult$i.stat$n.i
} else{
nameSet <- colnames(raschResult$item.par$delta) %in% itemSet
if(any(nameSet)) itemSet <- nameSet
}
fitV <- raschResult$item.par$in.out[itemSet,fitStat]
if(fitStat=="infit"){
refBump <- .1
if(missing(xlab)) xlab <- "Infit"
if(missing(refLines)) refLines <- c(.7,1.3)
} else if(fitStat=="outfit"){
refBump <- .1
if(missing(xlab)) xlab <- "Outfit"
if(missing(refLines)) refLines <- c(.7,1.3)
} else if(fitStat=="in.Z"){
refBump <- .2
if(missing(xlab)) xlab <- "Standardized Infit"
if(missing(refLines)) refLines <- c(-2,2)
} else{
refBump <- .2
fitStat <- "out.Z"
if(missing(xlab)) xlab <- "Standardized Outfit"
if(missing(refLines)) refLines <- c(-2,2)
}
if(missing(xlim)){
xlim <- range(fitV)
xlim[1] <- xlim[1] - .1
xlim[2] <- xlim[2] + .1
if(xlim[1] > refLines[1]) xlim[1] <- refLines[1] - refBump
if(xlim[2] < refLines[2]) xlim[2] <- refLines[2] + refBump
}
if(useItemNames){
itemNames <- colnames(raschResult$item.par$delta)[itemSet]
} else{
itemNames <- paste(itemSet)
}
myWidth <- 4
if(missing(gDevice)) gDevice <- "screen"
if(gDevice == "screen"){
dev.new(width=myWidth)
} else if(gDevice=="jpg" | gDevice=="jpeg"){
if(missing(file)) file <- "itemFitPlot.jpg"
jpeg(width=480*myWidth/5, filename=file)
} else if(gDevice=="png"){
if(missing(file)) file <- "itemFitPlot.png"
png(width=480*myWidth/5, filename=file)
}
plot(fitV, raschResult$item.par$delta.i[itemSet],
xlim=xlim, type="n", xlab=xlab, ylab=ylab, main=plotTitle)
polygon(c(refLines[2],refLines[2],500,500),c(-500,500,500,-500),col=col[2])
polygon(c(refLines[1],refLines[1],-500,-500),c(-500,500,500,-500),col=col[2])
text(fitV, raschResult$item.par$delta.i[itemSet], col=col[1], labels=itemNames)
abline(v=refLines)
if(gDevice != "screen") dev.off()
}
|
library(forecastML)
library(dplyr)
library(lubridate)
test_that("create_windows with dates is correct", {
dates <- seq(as.Date("2015-01-01"), as.Date("2020-12-01"), by = "1 month")
data <- data.frame(
"outcome" = 1:length(dates),
"feature" = 1:length(dates) * 2
)
data_test <- data
lookback <- 1:12
data_test <- forecastML::create_lagged_df(data_test, horizons = 3, lookback = lookback,
dates = dates, frequency = "1 month")
window_length <- 1
windows <- forecastML::create_windows(data_test, window_length = window_length)
testthat::expect_identical(windows$start, windows$stop)
})
test_that("create_windows with the same start and stop date for 1 unit of time is correct", {
dates <- seq(as.Date("2015-01-01"), as.Date("2020-12-01"), by = "1 month")
data <- data.frame(
"outcome" = 1:length(dates),
"feature" = 1:length(dates) * 2
)
data_test <- data
lookback <- 1:12
data_test <- forecastML::create_lagged_df(data_test, horizons = 3, lookback = lookback,
dates = dates, frequency = "1 month")
window_length <- 1
windows <- forecastML::create_windows(data_test, window_length = window_length)
testthat::expect_identical(windows$start, windows$stop)
})
test_that("create_windows length and skip with dates is correct", {
dates <- seq(as.Date("2015-01-01"), as.Date("2020-12-01"), by = "1 month")
data <- data.frame(
"outcome" = 1:length(dates),
"feature" = 1:length(dates) * 2
)
data_test <- data
lookback <- 1:12
data_test <- forecastML::create_lagged_df(data_test, horizons = 3, lookback = lookback,
dates = dates, frequency = "1 month")
window_start_true <- as.Date(c("2017-01-01", '2019-05-01'))
window_stop_true <- as.Date(c("2018-03-01", '2019-07-01'))
windows <- forecastML::create_windows(data_test, window_start = window_start_true,
window_stop = window_stop_true)
testthat::expect_true(all(windows$start == window_start_true))
testthat::expect_true(all(windows$stop == window_stop_true))
})
|
context("core functions return expected objects")
api_root <- "https://echodata.epa.gov/echo/"
set_redactor(function (response) {
response %>%
gsub_response(api_root, "api/", fixed = TRUE)
})
set_requester(function (request) {
request %>%
gsub_request(api_root, "api/", fixed = TRUE)
})
with_mock_api({
test_that("core functions return tbl_df", {
expect_is(
echoAirGetFacilityInfo(
p_pid = "NC0000003706500036",
output = "df",
qcolumns = "3,4,5"
),
"tbl_df"
)
expect_is(echoSDWGetMeta(verbose = FALSE),
"tbl_df")
expect_is(echoGetCAAPR(p_id = '110000350174'),
"tbl_df")
expect_is(echoGetEffluent(p_id = "tx0124362",
parameter_code = "50050"),
"tbl_df")
expect_is(echoGetReports(
program = "caa",
p_id = '110000350174',
verbose = FALSE
),
"tbl_df")
expect_is(
echoGetReports(
program = "cwa",
p_id = "tx0124362",
parameter_code = "50050",
verbose = FALSE
),
"tbl_df"
)
expect_is(echoSDWGetSystems(
p_co = "Brazos",
p_st = "tx",
verbose = FALSE
),
"tbl_df")
expect_is(
echoWaterGetFacilityInfo(
p_pid = "ALR040033",
output = "df",
qcolumns = "3,4,5"
),
"tbl_df"
)
expect_is(echoWaterGetParams(term = "Oxygen, dissolved"),
"tbl_df")
expect_is(echoWaterGetParams(code = "00300"), "tbl_df")
expect_is(
echoGetFacilities(
program = "cwa",
p_pid = "ALR040033",
output = "df",
qcolumns = "1,2,3"
),
"tbl_df"
)
})
})
with_mock_api({
test_that("core functions return sf", {
expect_is(
echoAirGetFacilityInfo(
p_pid = "NC0000003706500036",
output = "sf",
verbose = FALSE
),
"sf"
)
expect_is(echoWaterGetFacilityInfo(p_pid = "ALR040033", output = "sf"),
"sf")
})
})
|
pairwiseModelAnova =
function (fits, ...)
{
fits = list(fits, ...)
n = length(fits)
N = n*(n-1)/2
Y = data.frame(Model=rep("A",n),
Call=rep("A",n),
stringsAsFactors=FALSE)
for(i in 1:n)
{
Y[i,]= deparse(formula(fits[[i]]))
}
Z = data.frame(Comparison = rep("A", N),
Df.diff = rep(NA, N),
RSS.diff = rep(NA, N),
F = rep(NA, N),
p.value = rep(NA, N),
stringsAsFactors=FALSE)
k=0
for(i in 1:(n-1)){
for(j in (i+1):n){
k=k+1
Namea = as.character(i)
Nameb = as.character(j)
av = anova(fits[[i]], fits[[j]])
Z[k,] =c(paste0(Namea, " - ", Nameb, " = 0"),
as.numeric(av$Df[2]),
signif(as.numeric(av$"Sum of Sq"[2], digits=4)),
signif(as.numeric(av$F[2], digits=4)),
signif(as.numeric(av$"Pr(>F)"[2], digits=4))
)
}
}
X = data.frame(Comparison = rep("A", N),
Df.diff = rep(NA, N),
LogLik.diff= rep(NA, N),
Chi.sq = rep(NA, N),
p.value = rep(NA, N),
stringsAsFactors=FALSE)
k=0
for(i in 1:(n-1)){
for(j in (i+1):n){
k=k+1
Namea = as.character(i)
Nameb = as.character(j)
lr = lrtest(fits[[i]], fits[[j]])
X[k,] =c(paste0(Namea, " - ", Nameb, " = 0"),
as.numeric(lr$Df[2]),
signif(as.numeric(lr$LogLik[2])-as.numeric(lr$LogLik[1]),
digits=4),
signif(as.numeric(lr$Chisq[2]), digits=4),
signif(as.numeric(lr$"Pr(>Chisq)"[2]), digits=4)
)
}
}
W = list(Y, Z, X)
names(W) = c("Models",
"Anova.test.table",
"Likelihood.ratio.test.table")
return(W)
}
|
is_corpus_df <- function(corpus) {
stopifnot(inherits(corpus, "data.frame"),
ncol(corpus) >= 2,
all(names(corpus)[1L:2L] == c("doc_id", "text")),
is.character(corpus$doc_id),
is.character(corpus$doc_id),
nrow(corpus) > 0)
TRUE
}
corpus_df_as_corpus_vector <- function(corpus) {
if (is_corpus_df(corpus)) {
out <- corpus$text
names(out) <- corpus$doc_id
} else {
stop("Not a corpus data.frame")
}
out
}
|
svc <- paws::cloudhsm()
|
contract_phenocam = function(data,
internal = TRUE,
no_padding = FALSE,
out_dir = tempdir()) {
if(class(data) != "phenocamr"){
if(file.exists(data)){
data = read_phenocam(data)
on_disk = TRUE
} else {
stop("not a valid PhenoCam data frame or file")
}
} else {
on_disk = FALSE
}
df = data$data
if (!no_padding){
loc = seq(2, 366, 3)
df = df[which(as.numeric(df$doy) %in% loc), ]
} else {
df = df[which(!is.na(df$image_count)),]
}
data$data = df
if(on_disk | !internal ){
write_phenocam(data, out_dir = out_dir)
} else {
class(data) = "phenocamr"
return(data)
}
}
|
library(ggplot2)
library(dplyr)
library(ggthemes)
tread_PME_local<- format_results(teste_PME) %>%
mutate( local = "Local", dataset = "PME") %>%
mutate_each('as.character', period) %>%
mutate_each(funs(rm_mb),size) %>%
mutate_each("as.numeric", time)
tread_POF_local <- mutate(teste_read_POF, local = "Local", dataset = "POF") %>%
rename(ft = file)%>%
mutate_each("as.character", period) %>%
mutate_each(funs(rm_mb), size) %>%
mutate_each("as.numeric", time) %>%
mutate_each("as.logical", error)
tread_PNADContinua_local<- teste_PNADContinua %>% format_results() %>%
mutate( local = "Local", dataset = "PNADContinua")%>%
mutate_each('as.character', period) %>%
mutate_each(funs(rm_mb),size) %>%
mutate_each("as.numeric", time)
tread_CensoEducacaoSuperior_local<- teste_read_CensoEducacaoSuperior %>% format_results %>%
mutate( local = "Local", dataset = "CensoEducacaoSuperior")%>%
mutate_each('as.character', period) %>%
mutate_each(funs(rm_mb),size) %>%
mutate_each("as.numeric", time)
tread_PNAD_local<- teste_read_PNAD %>% format_results %>%
mutate( local = "Local", dataset = "PNAD")%>%
mutate_each('as.character', period) %>%
mutate_each(funs(rm_mb),size) %>%
mutate_each("as.numeric", time)
tread_CENSO_servidor <- teste_CensoIBGE_sstata2local_read %>%
rename(period = year) %>% format_results %>%
mutate_each('as.character', period) %>%
mutate(dataset= "CENSO", local = "Servidor")
all_tests<- lapply(ls()[grepl(ls(), pattern = "tread")],get) %>% bind_rows
lapply(ls()[grepl(ls(), pattern = "teste_read")],get) %>% lapply(str)->x
gdata<- filter(all_tests, !is.na(error) | error != TRUE) %>% mutate(key = paste0(dataset,"-",ft))
gdata<- filter(gdata,!(time < 60 & period == 2000))
plot3<-
ggplot(gdata %>% filter(time<60 & !error & dataset != "CENSO") , aes(x = size, y = time, color = key)) +
geom_point() + labs(title = "Desempenho das bases de dados com tempo de carregamento menor que 1 minuto", x = "Tamanho(em Mb)", y = "Tempo de carregamento( em s)") +
facet_grid(~dataset) + scale_color_hue(guide = FALSE) + theme(plot.title = element_text(size = 15, hjust = 0, vjust = 1, margin = margin(10,10,25,10)))
plot4<-
ggplot(gdata %>% filter(time>60 & !error & dataset != "CENSO") , aes(x = size, y = time, color = key)) +
geom_point() + labs(title = "Desempenho das bases de dados com tempo de carregamento menor que 1 minuto", x = "Tamanho(em Mb)", y = "Tempo de carregamento( em s)") +
facet_grid(~dataset) + scale_color_hue(guide = FALSE) + theme(plot.title = element_text(size = 15, hjust = 0, vjust = 1, margin = margin(10,10,25,10)))
|
lasso_deltas <- function(X, y, lambda = NULL, verbose = FALSE, alpha = 1, rank_fn = order_plain, k = ncol(X))
{
if (k < ncol(X))
{
fsel <- rank_fn(X, y)[1:k]
X <- X[, fsel, drop = FALSE]
}
if (is.null(lambda))
{
lasso.fit <- cv.glmnet(x = X, y = y, alpha = alpha, nlambda = 500, family = "multinomial")
}
else
{
lasso.fit <- cv.glmnet(x = X, y = y, alpha = alpha, lambda = lambda,
family = "multinomial", nfolds = 5)
}
if (verbose)
message("The best lambda chosen by CV: ", lasso.fit$lambda.min ,"\n")
betas <- coef(lasso.fit, s = "lambda.min")
mbetas <- as.matrix(Reduce(cbind, betas))
deltas <- mbetas[, -1, drop = FALSE] - mbetas[, 1]
return (deltas)
}
|
rvec2 <-
function(x, y, n, j, k, e1, e2)
{
R <- array(0, 5)
jp1 <- j + 1
kp1 <- k + 1
y1j <- sum(y[1:j])
yjk <- sum(y[jp1:k])
ykn <- sum(y[kp1:n])
xy1j <- sum(x[1:j] * y[1:j])
xyjk <- sum(x[jp1:k] * y[jp1:k])
x2yjk <- sum(x[jp1:k]^2 * y[jp1:k])
xykn <- sum(x[kp1:n] * y[kp1:n])
R[1] <- e1 * (y1j + ykn) + e2 * yjk
R[2] <- e1 * (xy1j + x[j] * ykn) + e2 * x[j] * yjk
R[3] <- e1 * (x[k] - x[j]) * ykn + e2 * (xyjk - x[j] * yjk)
R[4] <- e1 * (x[k]^2 - x[j]^2) * ykn + e2 * (x2yjk - x[j]^2 * yjk)
R[5] <- e1 * (xykn - x[k] * ykn)
list(r = R)
}
|
db_compute.AthenaConnection <- function(con,
table,
sql,
...) {
in_schema <- pkg_method("in_schema", "dbplyr")
if(athena_unload()){
stop(
"Unable to create table when `noctua_options(unload = TRUE)`. Please run `noctua_options(unload = FALSE)` and try again.",
call. = FALSE
)
}
table <- athena_query_save(con, sql, table, ...)
ll <- db_detect(con, table)
in_schema(ll[["dbms.name"]], ll[["table"]])
}
athena_query_save <- function(con, sql, name ,
file_type = c("NULL","csv", "tsv", "parquet", "json", "orc"),
s3_location = NULL,
partition = NULL,
compress = TRUE,
...){
stopifnot(is.null(s3_location) || is.s3_uri(s3_location))
file_type = match.arg(file_type)
tt_sql <- SQL(paste0("CREATE TABLE ", paste0('"',unlist(strsplit(name,"\\.")),'"', collapse = '.'),
" ", ctas_sql_with(partition, s3_location, file_type, compress), "AS ",
sql, ";"))
res <- dbExecute(con, tt_sql, unload = FALSE)
dbClearResult(res)
return(name)
}
db_copy_to.AthenaConnection <- function(con, table, values,
overwrite = FALSE, append = FALSE,
types = NULL, partition = NULL,
s3_location = NULL,
file_type = c("csv", "tsv", "parquet"),
compress = FALSE,
max_batch = Inf, ...){
types <- types %||% dbDataType(con, values)
names(types) <- names(values)
file_type = match.arg(file_type)
dbWriteTable(conn = con, name = table, value = values,
overwrite = overwrite, append = append,
field.types = types, partition = partition,
s3.location = s3_location, file.type = file_type,
compress = compress,
max.batch = max_batch)
return(table)
}
dbplyr_edition.AthenaConnection <- function(con) 2L
NULL
athena_conn_desc <- function(con){
info <- dbGetInfo(con)
profile <- if(!is.null(info$profile_name)) paste0(info$profile_name, "@")
paste0("Athena ",info$paws," [",profile,info$region_name,"/", info$dbms.name,"]")
}
db_connection_describe.AthenaConnection <- function(con) {
athena_conn_desc(con)
}
NULL
athena_explain <- function(con, sql, format = "text", type=NULL, ...){
if(athena_unload()){
stop(
"Unable to explain query plan when `noctua_options(unload = TRUE)`. Please run `noctua_options(unload = FALSE)` and try again.",
call. = FALSE
)
}
format <- match.arg(format, c("text", "json"))
if(!is.null(type)) {
type <- match.arg(type, c("LOGICAL", "DISTRIBUTED", "VALIDATE", "IO"))
format <- NULL
}
build_sql <- pkg_method("build_sql", "dbplyr")
dplyr_sql <- pkg_method("sql", "dbplyr")
build_sql(
"EXPLAIN ",
if (!is.null(format)) dplyr_sql(paste0("(FORMAT ", format, ") ")),
if (!is.null(type)) dplyr_sql(paste0("(TYPE ", type, ") ")),
dplyr_sql(sql),
con = con
)
}
sql_query_explain.AthenaConnection <- athena_explain
sql_query_fields.AthenaConnection <- function(con, sql, ...) {
if(inherits(sql, "ident")) {
return(sql)
} else {
dbplyr_query_select <- pkg_method("dbplyr_query_select", "dbplyr")
sql_subquery <- pkg_method("sql_subquery", "dplyr")
dplyr_sql <- pkg_method("sql", "dplyr")
return(dbplyr_query_select(con, dplyr_sql("*"), sql_subquery(con, sql), where = dplyr_sql("0 = 1")))
}
}
sql_escape_date.AthenaConnection <- function(con, x) {
dbQuoteString(con, x)
}
sql_escape_datetime.AthenaConnection <- function(con, x) {
str = dbQuoteString(con, x)
return(gsub("^date ", "timestamp ", str))
}
db_desc.AthenaConnection <- function(x) {
return(athena_conn_desc(x))
}
db_explain.AthenaConnection <- function(con, sql, ...){
sql <- athena_explain(con, sql, ...)
expl <- dbGetQuery(con, sql, unload = FALSE)
out <- utils::capture.output(print(expl))
paste(out, collapse = "\n")
}
athena_query_fields_ident <- function(con, sql){
if (grepl("\\.", sql)) {
schema_parts <- gsub('"', "", strsplit(sql, "\\.")[[1]])
} else {
schema_parts <- c(con@info$dbms.name, gsub('"', "", sql))
}
tryCatch(
output <- con@ptr$glue$get_table(
DatabaseName = schema_parts[1],
Name = schema_parts[2])$Table
)
col_names = vapply(output$StorageDescriptor$Columns, function(y) y$Name, FUN.VALUE = character(1))
partitions = vapply(output$PartitionKeys,function(y) y$Name, FUN.VALUE = character(1))
return(c(col_names, partitions))
}
db_query_fields.AthenaConnection <- function(con, sql, ...) {
if(inherits(sql, "ident")) {
return(athena_query_fields_ident(con, sql))
} else {
sql_select <- pkg_method("sql_select", "dplyr")
sql_subquery <- pkg_method("sql_subquery", "dplyr")
dplyr_sql <- pkg_method("sql", "dplyr")
sql <- sql_select(con, dplyr_sql("*"), sql_subquery(con, sql), where = dplyr_sql("0 = 1"))
qry <- dbSendQuery(con, sql)
on.exit(dbClearResult(qry))
res <- dbFetch(qry, 0)
return(names(res))
}
}
|
"print.humpfit" <-
function(x, ...)
{
cat("\nHump-backed Null model of richness vs. productivity\n\n")
cat("Family:", family(x)$family,"\n")
cat("Link function: Fisher diversity\n\n")
cat("Coefficients:\n\n")
print(coef(x))
cat("\nDeviance", deviance(x), "with", df.residual(x))
cat(" residual degrees of freedom\n")
invisible(x)
}
|
setGeneric("compare", function(e1, e2, comparison, target) { standardGeneric("compare") })
NULL
setGeneric("%i>%", function(e1, e2) { standardGeneric("%i>%") })
setGeneric("%i<%", function(e1, e2) { standardGeneric("%i<%") })
setGeneric("%i>=%", function(e1, e2) { standardGeneric("%i>=%") })
setGeneric("%i<=%", function(e1, e2) { standardGeneric("%i<=%") })
setGeneric("%i==%", function(e1, e2) { standardGeneric("%i==%") })
setGeneric("%i!=%", function(e1, e2) { standardGeneric("%i!=%") })
matchTemplate <- function(image, template, method, mask = NULL, target = "new") {
if (!isImage(image))
stop("This is not an Image object.")
if (template$nrow() > image$nrow() | template$ncol() > image$ncol())
stop("The dimensions of 'template' must be not greater than that of 'image'.")
if (template$nchan() != image$nchan() | template$depth() != image$depth())
stop("'template' must have the same number of channels and bit depth as 'image'.")
meth <- switch(method,
"SQDIFF" = 0,
"SQDIFF_NORMED" = 1,
"CCORR" = 2,
"CCORR_NORMED" = 3,
"CCOEFF" = 4,
"CCOEFF_NORMED" = 5,
stop("Unsupported method.")
)
if (!is.null(mask) & meth == 5) {
mask <- NULL
warning("This method does not support masks. The mask is ignored.")
}
if (isImage(target)) {
if (target$nchan() != 1 | target$depth() != "32F")
stop("'target' must be a single channel, 32F Image object.")
if (target$nrow() != (image$nrow() - template$nrow() + 1) |
target$ncol() != (image$ncol() - template$ncol() + 1))
stop("Incorrect 'target' dimensions.")
if (is.null(mask)) {
`_matchTemplateNoMask`(image, template, meth, target)
} else {
if (!all(template$dim() == mask$dim()))
stop("'mask' and 'template' must have the same dimensions.")
if (mask$nchan() != template$nchan() & mask$nchan() != 1)
stop("'mask' must either have one channel or the same number of channels as 'template'.")
if (mask$depth() != "8U" & mask$depth() != "32F")
stop("'mask' must either be a 8U or 32F Image object.")
`_matchTemplate`(image, template, meth, mask, target)
}
} else if (target == "new") {
out <- zeros(image$nrow() - template$nrow() + 1,
image$ncol() - template$ncol() + 1,
1, "32F")
if (is.null(mask)) {
`_matchTemplateNoMask`(image, template, meth, out)
} else {
if (!all(template$dim() == mask$dim()))
stop("'mask' and 'template' must have the same dimensions.")
if (mask$nchan() != template$nchan() & mask$nchan() != 1)
stop("'mask' must either have one channel or the same number of channels as 'template'.")
if (mask$depth() != "8U" & mask$depth() != "32F")
stop("'mask' must either be a 8U or 32F Image object.")
`_matchTemplate`(image, template, meth, mask, out)
}
out
} else {
stop("Invalid target.")
}
}
inRange <- function(image, low = 0, up = 255, target = "new") {
if (!isImage(image))
stop("'image' is not an Image object.")
low <- rep(low, length.out = image$nchan())
up <- rep(up, length.out = image$nchan())
if (isImage(target)) {
`_inRange`(image, low, up, target)
} else if (target == "new") {
out <- zeros(nrow(image), ncol(image), 1, "8U")
`_inRange`(image, low, up, out)
out
} else {
stop("Invalid target.")
}
}
|
context("EQ-5D-Y")
test_that("EQ-5D-Y Slovenia gives correct answer", {
expect_equal(eq5dy(c(MO=1,SC=1,UA=1,PD=1,AD=1), "Slovenia"), 1)
expect_equal(eq5dy(c(MO=1,SC=1,UA=1,PD=1,AD=2), "Slovenia"), 0.883)
expect_equal(eq5dy(c(MO=1,SC=2,UA=3,PD=2,AD=1), "Slovenia"), 0.469, tolerance = .0011)
expect_equal(eq5dy(c(MO=2,SC=1,UA=2,PD=1,AD=2), "Slovenia"), 0.694)
expect_equal(eq5dy(c(MO=2,SC=2,UA=2,PD=2,AD=2), "Slovenia"), 0.485, tolerance = .0011)
expect_equal(eq5dy(c(MO=2,SC=3,UA=2,PD=3,AD=2), "Slovenia"), 0.010)
expect_equal(eq5dy(c(MO=3,SC=1,UA=1,PD=3,AD=3), "Slovenia"), -0.148)
expect_equal(eq5dy(c(MO=3,SC=3,UA=3,PD=2,AD=2), "Slovenia"), -0.128, tolerance = .0011)
expect_equal(eq5dy(c(MO=3,SC=3,UA=3,PD=3,AD=3), "Slovenia"), -0.691)
})
test_that("EQ-5D-Y Japan gives correct answer", {
expect_equal(eq5dy(c(MO=1,SC=1,UA=1,PD=1,AD=1), "Japan"), 1)
expect_equal(eq5dy(c(MO=1,SC=2,UA=1,PD=1,AD=1), "Japan"), 0.957)
expect_equal(eq5dy(c(MO=2,SC=2,UA=2,PD=2,AD=2), "Japan"), 0.753)
expect_equal(eq5dy(c(MO=3,SC=3,UA=3,PD=3,AD=3), "Japan"), 0.288, tolerance = .0011)
})
context("EQ-5D-Y Incorrect params")
test_that("EQ-5D-Y throws error for incorrect parameters", {
expect_error(eq5dy(c(MO=1,SC=2,UA=5,PD=2,AD=1), "Slovenia"))
expect_error(eq5dy(c(M0=1,SC=2,UA=5,PD=2,AD=1), "Slovenia"))
expect_error(eq5dy(c(MO=1,SC=2,UA=3,PD=2,AD=1), "Liechtenstein"))
})
|
add_minimum_distance <- function(data) {
if (length(attributes(data)$ps_data_type) > 0 && attributes(data)$ps_data_type %in% c("dyad_year", "leader_dyad_year")) {
if (length(attributes(data)$ps_system) > 0 && attributes(data)$ps_system == "cow") {
cow_mindist %>%
rename(ccode1 = .data$ccode2,
ccode2 = .data$ccode1) %>%
bind_rows(cow_mindist, .) -> hold_cow
data %>%
left_join(., hold_cow) -> data
return(data)
} else if (length(attributes(data)$ps_system) > 0 && attributes(data)$ps_system == "gw") {
gw_mindist %>%
rename(gwcode1 = .data$gwcode2,
gwcode2 = .data$gwcode1) %>%
bind_rows(gw_mindist, .) -> hold_gw
data %>%
left_join(., hold_gw) -> data
return(data)
} else {
stop("add_minimum_distance() requires either Correlates of War ('cow') or Gleditsch-Ward ('gw') as system type.")
}
} else if (length(attributes(data)$ps_data_type) > 0 && attributes(data)$ps_data_type %in% c("state_year", "leader_year")) {
if (length(attributes(data)$ps_system) > 0 && attributes(data)$ps_system == "cow") {
cow_mindist %>%
group_by(.data$ccode1, .data$year) %>%
summarize(minmindist = min(.data$mindist, na.rm = TRUE)) %>%
ungroup() %>%
rename(ccode = .data$ccode1) %>%
left_join(data, .) -> data
return(data)
} else if (length(attributes(data)$ps_system) > 0 && attributes(data)$ps_system == "gw") {
gw_mindist %>%
group_by(.data$gwcode1, .data$year) %>%
summarize(minmindist = min(.data$mindist, na.rm = TRUE)) %>%
ungroup() %>%
rename(gwcode = .data$gwcode1) %>%
left_join(data, .) -> data
return(data)
} else {
stop("add_minimum_distance() requires either Correlates of War ('cow') or Gleditsch-Ward ('gw') as system type.")
}
} else {
stop("add_minimum_distance() requires a data/tibble with attributes$ps_data_type of state_year or dyad_year. Try running create_dyadyears() or create_stateyears() at the start of the pipe.")
}
}
|
transform_puni <- function(res.fe, res.es, side)
{
if(side == "left")
{
est <- res.es$est * -1
tmp <- res.es$ci.ub
ci.ub <- res.es$ci.lb * -1
ci.lb <- tmp * -1
est.fe <- res.fe$est.fe * -1
tmp <- res.fe$ci.ub.fe
ci.ub.fe <- res.fe$ci.lb.fe * -1
ci.lb.fe <- tmp * -1
se.fe <- res.fe$se.fe
zval.fe <- res.fe$zval.fe * -1
} else
{
est <- res.es$est
ci.lb <- res.es$ci.lb
ci.ub <- res.es$ci.ub
est.fe <- res.fe$est.fe
ci.lb.fe <- res.fe$ci.lb.fe
ci.ub.fe <- res.fe$ci.ub.fe
se.fe <- res.fe$se.fe
zval.fe <- res.fe$zval.fe
}
return(data.frame(est = est, ci.lb = ci.lb, ci.ub = ci.ub, est.fe = est.fe,
zval.fe = zval.fe, ci.lb.fe = ci.lb.fe, ci.ub.fe = ci.ub.fe,
se.fe = se.fe))
}
|
VDJ_Vgene_usage_stacked_barplot <- function(VDJ,
HC.gene.number,
Fraction.HC,
LC.Vgene,
LC.gene.number,
Fraction.LC,
platypus.version){
Vgene <- NULL
Percentage <- NULL
Nr_of_VDJ_chains <- NULL
Nr_of_VJ_chains <- NULL
sample_id <- NULL
Sample <- NULL
Frequency <- NULL
if (missing(Fraction.HC)) Fraction.HC <- 0
if (missing(HC.gene.number)) HC.gene.number <- 10
if (missing(LC.Vgene)) LC.Vgene <- FALSE
if (missing(Fraction.LC)) Fraction.LC <- 0
if (missing(LC.gene.number)) LC.gene.number <- 10
VDJ.matrix <- VDJ
VDJ <- NULL
Vgene_usage_plot <- list()
HC_Vgene_usage <- list()
HC_Vgene_usage_top <- list()
HC_Vgene_usage_fraction <- list()
if(missing(platypus.version)) platypus.version <- "v3"
if(platypus.version == "v2"){
clonotype.list <- VDJ.matrix
for (i in 1:length(clonotype.list)){
HC_Vgene_usage[[i]] <- as.data.frame(table(clonotype.list[[i]]$HC_vgene))
colnames(HC_Vgene_usage[[i]]) <- c("Vgene", "Frequency")
for (j in 1:nrow(HC_Vgene_usage[[i]])){
HC_Vgene_usage[[i]]$Percentage[j] <- HC_Vgene_usage[[i]]$Frequency[j]/sum(HC_Vgene_usage[[i]]$Frequency)*100
}
ranks <- order(-HC_Vgene_usage[[i]]$Frequency)
HC_Vgene_usage[[i]] <- HC_Vgene_usage[[i]][ranks,]
HC_Vgene_usage_fraction[[i]] <- HC_Vgene_usage[[i]][which(HC_Vgene_usage[[i]]$Percentage > Fraction.HC),]
}
HC_Vgene_names <- do.call("rbind",HC_Vgene_usage_fraction)
HC_Vgene_names <- as.vector(unique(HC_Vgene_names$Vgene))
for(i in 1:length(clonotype.list)){
HC_Vgene_usage[[i]] <- HC_Vgene_usage[[i]][HC_Vgene_usage[[i]]$Vgene %in% HC_Vgene_names,]
}
HC_Vgene_usage_all <- do.call("rbind", HC_Vgene_usage)
unique_Vgene <- unique(HC_Vgene_usage_all$Vgene)
HC_Vgene_usage_all_unique <- data.frame("Vgene"= rep("", length(unique_Vgene)), "Frequency"= rep(0, length(unique_Vgene)))
HC_Vgene_usage_all_unique$Vgene <- unique_Vgene
for (i in 1:length(unique_Vgene)){
HC_Vgene_usage_all_unique[i,"Percentage"] <- mean(HC_Vgene_usage_all[which(HC_Vgene_usage_all$Vgene == HC_Vgene_usage_all_unique$Vgene[i]),]$Percentage)
}
ranks <- order(-HC_Vgene_usage_all_unique$Frequency)
HC_Vgene_usage_all_unique <- HC_Vgene_usage_all_unique[ranks,]
top_Vgenes <- HC_Vgene_usage_all_unique$Vgene[1:HC.gene.number]
for(i in 1:length(clonotype.list)){
HC_Vgene_usage_top[[i]] <- data.frame("Vgene"=rep("", length(top_Vgenes)), "Frequency"=rep(0, length(top_Vgenes)))
HC_Vgene_usage_top[[i]]$Vgene <- top_Vgenes
for (j in 1:nrow(HC_Vgene_usage_top[[i]])){
if (HC_Vgene_usage_top[[i]]$Vgene[j] %in% HC_Vgene_usage[[i]]$Vgene == TRUE){
HC_Vgene_usage_top[[i]]$Frequency[j] <- HC_Vgene_usage[[i]][which(HC_Vgene_usage[[i]]$Vgene == paste0(HC_Vgene_usage_top[[i]]$Vgene[j])),]$Frequency
}
}
for (j in 1:nrow(HC_Vgene_usage_top[[i]])){
HC_Vgene_usage_top[[i]]$Percentage[j] <- HC_Vgene_usage_top[[i]]$Frequency[j]/sum(HC_Vgene_usage_top[[i]]$Frequency)*100
}
}
for (i in 1:length(HC_Vgene_usage_top)){
HC_Vgene_usage_top[[i]]$Sample <- as.character(i)
}
plotting_df <- do.call("rbind",HC_Vgene_usage_top)
plotting_df <- plotting_df[!is.na(plotting_df$Vgene), ]
Vgene_usage_plot[[1]] <- ggplot2::ggplot(plotting_df, ggplot2::aes(fill = Vgene, y=Frequency, x=Sample)) +
ggplot2::geom_bar(position="fill", stat="identity", color="black", width = 0.7) +
ggplot2::theme_bw() + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, vjust = 0.5, hjust=1)) +
ggplot2::ylab("% of unique clones") + ggplot2::scale_y_continuous(expand = c(0,0))
if(LC.Vgene ==TRUE){
LC_Vgene_usage <- list()
LC_Vgene_usage_top <- list()
LC_Vgene_usage_fraction <- list()
for (i in 1:length(clonotype.list)){
LC_Vgene_usage[[i]] <- as.data.frame(table(clonotype.list[[i]]$LC_vgene))
colnames(LC_Vgene_usage[[i]]) <- c("Vgene", "Frequency")
for (j in 1:nrow(LC_Vgene_usage[[i]])){
LC_Vgene_usage[[i]]$Percentage[j] <- LC_Vgene_usage[[i]]$Frequency[j]/sum(LC_Vgene_usage[[i]]$Frequency)*100
}
ranks <- order(-LC_Vgene_usage[[i]]$Frequency)
LC_Vgene_usage[[i]] <- LC_Vgene_usage[[i]][ranks,]
LC_Vgene_usage_fraction[[i]] <- LC_Vgene_usage[[i]][which(LC_Vgene_usage[[i]]$Percentage > Fraction.LC),]
}
LC_Vgene_names <- do.call("rbind",LC_Vgene_usage_fraction)
LC_Vgene_names <- as.vector(unique(LC_Vgene_names$Vgene))
for(i in 1:length(clonotype.list)){
LC_Vgene_usage[[i]] <- LC_Vgene_usage[[i]][LC_Vgene_usage[[i]]$Vgene %in% LC_Vgene_names,]
}
LC_Vgene_usage_all <- do.call("rbind", LC_Vgene_usage)
unique_Vgene <- unique(LC_Vgene_usage_all$Vgene)
LC_Vgene_usage_all_unique <- data.frame("Vgene"= rep("", length(unique_Vgene)), "Frequency"= rep(0, length(unique_Vgene)))
LC_Vgene_usage_all_unique$Vgene <- unique_Vgene
for (i in 1:length(unique_Vgene)){
LC_Vgene_usage_all_unique[i,"Percentage"] <- mean(LC_Vgene_usage_all[which(LC_Vgene_usage_all$Vgene == LC_Vgene_usage_all_unique$Vgene[i]),]$Percentage)
}
ranks <- order(-LC_Vgene_usage_all_unique$Frequency)
LC_Vgene_usage_all_unique <- LC_Vgene_usage_all_unique[ranks,]
top_Vgenes <- LC_Vgene_usage_all_unique$Vgene[1:LC.gene.number]
for(i in 1:length(clonotype.list)){
LC_Vgene_usage_top[[i]] <- data.frame("Vgene"=rep("", length(top_Vgenes)), "Frequency"=rep(0, length(top_Vgenes)))
LC_Vgene_usage_top[[i]]$Vgene <- top_Vgenes
for (j in 1:nrow(LC_Vgene_usage_top[[i]])){
if (LC_Vgene_usage_top[[i]]$Vgene[j] %in% LC_Vgene_usage[[i]]$Vgene == TRUE){
LC_Vgene_usage_top[[i]]$Frequency[j] <- LC_Vgene_usage[[i]][which(LC_Vgene_usage[[i]]$Vgene == paste0(LC_Vgene_usage_top[[i]]$Vgene[j])),]$Frequency
}
}
for (j in 1:nrow(LC_Vgene_usage_top[[i]])){
LC_Vgene_usage_top[[i]]$Percentage[j] <- LC_Vgene_usage_top[[i]]$Frequency[j]/sum(LC_Vgene_usage_top[[i]]$Frequency)*100
}
}
for (i in 1:length(LC_Vgene_usage_top)){
LC_Vgene_usage_top[[i]]$Sample <- as.character(i)
}
plotting_df <- do.call("rbind",LC_Vgene_usage_top)
plotting_df <- plotting_df[!is.na(plotting_df$Vgene), ]
Vgene_usage_plot[[1]] <- ggplot2::ggplot(plotting_df, ggplot2::aes(fill = Vgene, y=Frequency, x=Sample)) +
ggplot2::geom_bar(position="fill", stat="identity", color="black", width = 0.7) +
ggplot2::theme_bw() + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, vjust = 0.5, hjust=1)) +
ggplot2::ylab("% of unique clones") + ggplot2::scale_y_continuous(expand = c(0,0))
}
return(Vgene_usage_plot)
} else if(platypus.version == "v3"){
VDJ.matrix <- subset(VDJ.matrix, Nr_of_VDJ_chains == 1 & Nr_of_VJ_chains == 1)
clonotype.list <- list()
for(i in 1:length(unique(VDJ.matrix$sample_id))){
clonotype.list[[i]] <- subset(VDJ.matrix, sample_id == unique(VDJ.matrix$sample_id)[i])
clonotype.list[[i]] <- clonotype.list[[i]][duplicated(clonotype.list[[i]]$clonotype_id_10x) == F,]
}
names(clonotype.list) <- unique(VDJ.matrix$sample_id)
message(paste0("Sample order: ", paste0(unique(VDJ.matrix$sample_id), collapse = " ; ")))
if(LC.Vgene == F){
Vgene_usage_plot <- list()
HC_Vgene_usage <- list()
HC_Vgene_usage_top <- list()
HC_Vgene_usage_fraction <- list()
for (i in 1:length(clonotype.list)){
HC_Vgene_usage[[i]] <- as.data.frame(table(clonotype.list[[i]]$VDJ_vgene))
colnames(HC_Vgene_usage[[i]]) <- c("Vgene", "Frequency")
for (j in 1:nrow(HC_Vgene_usage[[i]])){
HC_Vgene_usage[[i]]$Percentage[j] <- HC_Vgene_usage[[i]]$Frequency[j]/sum(HC_Vgene_usage[[i]]$Frequency)*100
}
ranks <- order(-HC_Vgene_usage[[i]]$Frequency)
HC_Vgene_usage[[i]] <- HC_Vgene_usage[[i]][ranks,]
HC_Vgene_usage_fraction[[i]] <- HC_Vgene_usage[[i]][which(HC_Vgene_usage[[i]]$Percentage > Fraction.HC),]
}
HC_Vgene_names <- do.call("rbind",HC_Vgene_usage_fraction)
HC_Vgene_names <- as.vector(unique(HC_Vgene_names$Vgene))
for(i in 1:length(clonotype.list)){
HC_Vgene_usage[[i]] <- HC_Vgene_usage[[i]][HC_Vgene_usage[[i]]$Vgene %in% HC_Vgene_names,]
}
HC_Vgene_usage_all <- do.call("rbind", HC_Vgene_usage)
unique_Vgene <- unique(HC_Vgene_usage_all$Vgene)
HC_Vgene_usage_all_unique <- data.frame("Vgene"= rep("", length(unique_Vgene)), "Frequency"= rep(0, length(unique_Vgene)))
HC_Vgene_usage_all_unique$Vgene <- unique_Vgene
for (i in 1:length(unique_Vgene)){
HC_Vgene_usage_all_unique[i,"Percentage"] <- mean(HC_Vgene_usage_all[which(HC_Vgene_usage_all$Vgene == HC_Vgene_usage_all_unique$Vgene[i]),]$Percentage)
}
ranks <- order(-HC_Vgene_usage_all_unique$Frequency)
HC_Vgene_usage_all_unique <- HC_Vgene_usage_all_unique[ranks,]
top_Vgenes <- HC_Vgene_usage_all_unique$Vgene[1:HC.gene.number]
for(i in 1:length(clonotype.list)){
HC_Vgene_usage_top[[i]] <- data.frame("Vgene"=rep("", length(top_Vgenes)), "Frequency"=rep(0, length(top_Vgenes)))
HC_Vgene_usage_top[[i]]$Vgene <- top_Vgenes
for (j in 1:nrow(HC_Vgene_usage_top[[i]])){
if (HC_Vgene_usage_top[[i]]$Vgene[j] %in% HC_Vgene_usage[[i]]$Vgene == TRUE){
HC_Vgene_usage_top[[i]]$Frequency[j] <- HC_Vgene_usage[[i]][which(HC_Vgene_usage[[i]]$Vgene == paste0(HC_Vgene_usage_top[[i]]$Vgene[j])),]$Frequency
}
}
for (j in 1:nrow(HC_Vgene_usage_top[[i]])){
HC_Vgene_usage_top[[i]]$Percentage[j] <- HC_Vgene_usage_top[[i]]$Frequency[j]/sum(HC_Vgene_usage_top[[i]]$Frequency)*100
}
}
for (i in 1:length(HC_Vgene_usage_top)){
HC_Vgene_usage_top[[i]]$Sample <- as.character(i)
}
plotting_df <- do.call("rbind",HC_Vgene_usage_top)
plotting_df <- plotting_df[!is.na(plotting_df$Vgene), ]
Vgene_usage_plot[[1]] <- ggplot2::ggplot(plotting_df, ggplot2::aes(fill = Vgene, y=Frequency, x=Sample)) +
ggplot2::geom_bar(position="fill", stat="identity", color="black", width = 0.7) +
ggplot2::theme_bw() + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, vjust = 0.5, hjust=1)) +
ggplot2::ylab("% of unique clones") + ggplot2::scale_y_continuous(expand = c(0,0)) + ggplot2::ggtitle(paste0("IgH V gene stacked"))
}else if(LC.Vgene ==TRUE){
LC_Vgene_usage <- list()
LC_Vgene_usage_top <- list()
LC_Vgene_usage_fraction <- list()
for (i in 1:length(clonotype.list)){
LC_Vgene_usage[[i]] <- as.data.frame(table(clonotype.list[[i]]$VJ_vgene))
colnames(LC_Vgene_usage[[i]]) <- c("Vgene", "Frequency")
for (j in 1:nrow(LC_Vgene_usage[[i]])){
LC_Vgene_usage[[i]]$Percentage[j] <- LC_Vgene_usage[[i]]$Frequency[j]/sum(LC_Vgene_usage[[i]]$Frequency)*100
}
ranks <- order(-LC_Vgene_usage[[i]]$Frequency)
LC_Vgene_usage[[i]] <- LC_Vgene_usage[[i]][ranks,]
LC_Vgene_usage_fraction[[i]] <- LC_Vgene_usage[[i]][which(LC_Vgene_usage[[i]]$Percentage > Fraction.LC),]
}
LC_Vgene_names <- do.call("rbind",LC_Vgene_usage_fraction)
LC_Vgene_names <- as.vector(unique(LC_Vgene_names$Vgene))
for(i in 1:length(clonotype.list)){
LC_Vgene_usage[[i]] <- LC_Vgene_usage[[i]][LC_Vgene_usage[[i]]$Vgene %in% LC_Vgene_names,]
}
LC_Vgene_usage_all <- do.call("rbind", LC_Vgene_usage)
unique_Vgene <- unique(LC_Vgene_usage_all$Vgene)
LC_Vgene_usage_all_unique <- data.frame("Vgene"= rep("", length(unique_Vgene)), "Frequency"= rep(0, length(unique_Vgene)))
LC_Vgene_usage_all_unique$Vgene <- unique_Vgene
for (i in 1:length(unique_Vgene)){
LC_Vgene_usage_all_unique[i,"Percentage"] <- mean(LC_Vgene_usage_all[which(LC_Vgene_usage_all$Vgene == LC_Vgene_usage_all_unique$Vgene[i]),]$Percentage)
}
ranks <- order(-LC_Vgene_usage_all_unique$Frequency)
LC_Vgene_usage_all_unique <- LC_Vgene_usage_all_unique[ranks,]
top_Vgenes <- LC_Vgene_usage_all_unique$Vgene[1:LC.gene.number]
for(i in 1:length(clonotype.list)){
LC_Vgene_usage_top[[i]] <- data.frame("Vgene"=rep("", length(top_Vgenes)), "Frequency"=rep(0, length(top_Vgenes)))
LC_Vgene_usage_top[[i]]$Vgene <- top_Vgenes
for (j in 1:nrow(LC_Vgene_usage_top[[i]])){
if (LC_Vgene_usage_top[[i]]$Vgene[j] %in% LC_Vgene_usage[[i]]$Vgene == TRUE){
LC_Vgene_usage_top[[i]]$Frequency[j] <- LC_Vgene_usage[[i]][which(LC_Vgene_usage[[i]]$Vgene == paste0(LC_Vgene_usage_top[[i]]$Vgene[j])),]$Frequency
}
}
for (j in 1:nrow(LC_Vgene_usage_top[[i]])){
LC_Vgene_usage_top[[i]]$Percentage[j] <- LC_Vgene_usage_top[[i]]$Frequency[j]/sum(LC_Vgene_usage_top[[i]]$Frequency)*100
}
}
for (i in 1:length(LC_Vgene_usage_top)){
LC_Vgene_usage_top[[i]]$Sample <- as.character(i)
}
plotting_df <- do.call("rbind",LC_Vgene_usage_top)
plotting_df <- plotting_df[!is.na(plotting_df$Vgene), ]
Vgene_usage_plot[[1]] <- ggplot2::ggplot(plotting_df, ggplot2::aes(fill = Vgene, y=Frequency, x=Sample)) +
ggplot2::geom_bar(position="fill", stat="identity", color="black", width = 0.7) +
ggplot2::theme_bw() + ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, vjust = 0.5, hjust=1)) +
ggplot2::ylab("% of unique clones") + ggplot2::scale_y_continuous(expand = c(0,0)) + ggplot2::ggtitle(paste0("IgK/L V gene stacked"))
}
}
}
|
library(ape)
library(nLTT)
library(testit)
newick <- "((A:1,B:1):1,C:2);"
phylogeny <- ape::read.tree(text = newick)
plot(phylogeny)
add.scale.bar()
nltt_plot(phylogeny)
nltt <- nLTT::get_phylogeny_nltt_matrix(phylogeny)
print(nltt)
nltt_plot(phylogeny)
points(nltt, pch = 19, col = "red")
nltt <- nLTT::get_phylogeny_nltt_matrix(phylogeny)
stretch_matrix <- nLTT::stretch_nltt_matrix(
nltt, dt = 0.25, step_type = "upper"
)
print(stretch_matrix)
nltt_plot(phylogeny)
points(nltt, pch = 19, col = "red")
points(stretch_matrix, pch = 19, col = "blue")
newick <- "((A:1,B:1):1,(C:1,D:1):1);"
phylogeny <- ape::read.tree(text = newick)
plot(phylogeny)
add.scale.bar()
nltt_plot(phylogeny)
nltt <- nLTT::get_phylogeny_nltt_matrix(phylogeny)
print(nltt)
nltt_plot(phylogeny)
points(nltt, pch = 19, col = "red")
nltt <- nLTT::get_phylogeny_nltt_matrix(phylogeny)
stretch_matrix <- nLTT::stretch_nltt_matrix(
nltt, dt = 0.25, step_type = "upper"
)
print(stretch_matrix)
nltt_plot(phylogeny)
points(nltt, pch = 19, col = "red")
points(stretch_matrix, pch = 19, col = "blue")
newick <- paste0("((((XD:1,ZD:1):1,CE:2):1,(FE:2,EE:2):1):4,((AE:1,BE:1):1,",
"(WD:1,YD:1):1):5);"
)
phylogeny <- ape::read.tree(text = newick)
plot(phylogeny)
add.scale.bar()
nltt_plot(phylogeny)
nltt <- nLTT::get_phylogeny_nltt_matrix(phylogeny)
print(nltt)
nltt_plot(phylogeny)
points(nltt, pch = 19, col = "red")
nltt <- nLTT::get_phylogeny_nltt_matrix(phylogeny)
nltt_plot(phylogeny)
stretch_matrix <- nLTT::stretch_nltt_matrix(
nltt, dt = 0.05, step_type = "upper"
)
points(nltt, pch = 19, col = "red")
points(stretch_matrix, pch = 19, col = "blue")
|
DME <- function(juv_proxy, adu_proxy, adu_mass, scale_fac = 3) {
j.scale <- juv_proxy^scale_fac
a.scale <- adu_proxy^scale_fac
j.prop <- j.scale/a.scale
j.mass <- adu_mass*j.prop
return(j.mass)
}
|
mouseOverHtmlFile <- function(myCoor, pngFileNa, HtmFileNa=NULL, mouseOverTxt=NULL, displSi=c(800,600),
colNa=NULL, tit="", myHtmTit="", myComment=NULL, textAtStart=NULL, textAtEnd=NULL, pxDiam=5,
addLinks=NULL, linkExt=NULL, htmlExt="htm", callFrom=NULL, silent=FALSE){
myCoorTy <- NULL
fxNa <- wrMisc::.composeCallName(callFrom, newNa="mouseOverHtmlFile")
if(length(dim(myCoor)) !=2) stop(" Expecting matrix or data.frame")
if(nrow(myCoor) <1) stop(" 'myCoor' seems to be empty !")
if(!is.data.frame(myCoor)) myCoor <- as.data.frame(myCoor, stringsAsFactors=FALSE)
if(is.null(myComment)) myComment <- c(" Produced by R using createHtmlWithPointsIdentif()", " from package WRmisc, ",Sys.Date())
.corPath <- function(x,asHtml=TRUE) {
if(length(grep("ming.32",R.Version()$platform)) >0) {
x <- gsub("\\\\", "/", x)
if(asHtml & length(grep("[[:upper:]]:", substr(x,1,2))) >0) {
x <- paste("file:///",x,sep="") }
} else if(asHtml & length(grep("^/",x)) >0) x <- paste("file:///",x,sep="")
x }
colN2 <- rep(NA,5)
names(colN2) <- c("ID","x","y","mouseOver","link")
potIDname <- wrMisc::.plusLowerCaps(c("ID","Id","Ident","Identifier","UniqID","uniqID","UniqueID"))
potXname <- wrMisc::.plusLowerCaps(c("xPix","xPred","coorX","htmlX","xCoor","dataX","X"))
potYname <- wrMisc::.plusLowerCaps(c("yPix","yPred","coorY","htmlY","yCoor","dataY","Y"))
potMouseOvname <- wrMisc::.plusLowerCaps(c("mouseOver","mouseInfo","Mouse","Mou","Hint","Name","fullName","FullName","Combined","CustName","custName","Info"))
potLinkname <- wrMisc::.plusLowerCaps(c("LINK","Link","Li","Http","WWW","AddLink","addLink"))
if(length(colNa) ==2) colN2[2:3] <- colNa else if(length(colNa) >2) colN2[1:length(colNa)] <- colNa
if(length(colNa) <1) {
if(ncol(myCoor)==2) colN2[2:3] <- colnames(myCoor) else {
remColNa <- colnames(myCoor)
if(any(potIDname %in% remColNa)) {aa <- .serachColName(remColNa,potIDname,plusLowerCaps=FALSE,returnList=TRUE)
remColNa <- aa$remainNa; colN2[1] <- aa$foundNa}
if(any(potXname %in% remColNa)) {aa <- .serachColName(remColNa,potXname,plusLowerCaps=FALSE,returnList=TRUE)
remColNa <- aa$remainNa; colN2[2] <- aa$foundNa}
if(any(potYname %in% remColNa)) {aa <- .serachColName(remColNa,potYname,plusLowerCaps=FALSE,returnList=TRUE)
remColNa <- aa$remainNa; colN2[3] <- aa$foundNa}
if(any(potMouseOvname %in% remColNa)) {aa <- .serachColName(remColNa,potMouseOvname,plusLowerCaps=FALSE,returnList=TRUE)
remColNa <- aa$remainNa; colN2[4] <- aa$foundNa}
if(any(potLinkname %in% remColNa)) {aa <- .serachColName(remColNa,potLinkname,plusLowerCaps=FALSE,returnList=TRUE)
remColNa <- aa$remainNa; colN2[5] <- aa$foundNa}}}
myCoor <- data.frame(myCoor[,colN2[which(!is.na(colN2))]], stringsAsFactors=FALSE)
if(is.na(colN2[1])) {
myCoor$ID <- if(is.null(rownames(myCoor))) 1:nrow(myCoor) else rownames(myCoor)
colN2[1] <- "ID"
if(!silent) message(fxNa," using column '",colnames(myCoor[colN2[1]]),"' for mouse-over")
}
if(!identical(mouseOverTxt,FALSE)) if(is.null(mouseOverTxt)) {
if(is.na(colN2[4])) {
myCoor$mouseOver <- myCoor[,colN2[1]]
if(!silent) message(fxNa," using column '",colnames(myCoor[colN2[1]]),"' for mouse-over")
colN2[4] <- "mouseOver" }
} else { if(length(mouseOverTxt) ==nrow(myCoor) & length(unique(mouseOverTxt)) > 1) {
myCoor$mouseOver <- mouseOverTxt } else {
if(!silent) message(fxNa,"Ignoring invalid entry for 'mouseOverTxt' (expecting length ",nrow(myCoor)," but found ",length(mouseOverTxt),")")
myCoor$mouseOver <- myCoor[,"ID"]
} }
if(identical(addLinks,TRUE)) {
myCoor$link <- myCoor[,if(is.na(colN2[5])) colN2[1] else colN2[5]]
colN2[5] <- "addLinks" } else {
if(length(addLinks) >0) {if(length(addLinks) ==nrow(myCoor) & length(unique(addLinks)) > 1 & max(nchar(addLinks),na.rm=TRUE) >0) {
myCoor$link <- addLinks
colN2[5] <- "addLinks" } else {
if(!silent) message(fxNa," invalid entry for 'addLinks' (expecting length ",nrow(myCoor)," but found ",length(addLinks),")")}}}
if(length(linkExt) >0) if(nchar(linkExt) >0) {
chExt <- grep(paste(linkExt,"$",sep=""), myCoor$link)
if(length(chExt) < nrow(myCoor) & length(chExt) >0) myCoor$link[chExt] <- paste(myCoor$link[chExt],linkExt,sep="")
}
if(!file.exists(pngFileNa)) stop("Cannot find file which should be used for embedding image into html !")
msg <- " 'displSi' : Expecting numeric vector of lengt 2 (for display size in px in html) !"
if(!is.numeric(displSi) | length(displSi) <2) stop(msg)
if(length(HtmFileNa) !=1) HtmFileNa <- pngFileNa
baseFiNa <- sub(".PNG$","",sub(".png$","",sub(".htm$","",sub(".html$","",HtmFileNa))))
if(nchar(HtmFileNa)== nchar(baseFiNa)) {
htmlExt <- if(length(htmlExt) <0) "" else htmlExt[1]
if(!silent) message(fxNa," setting file-name + extension to : ",baseFiNa,".",htmlExt)
} else {
htmlExt <- substr(HtmFileNa, unlist(regexec("\\.htm",HtmFileNa)), nchar(HtmFileNa))}
HtmFileNa <- wrMisc::.checkFileNameExtensions(baseFiNa, htmlExt)
.convTxtToHtmPar <- function(txt){
txt <- as.character(txt)
nLi <- length(txt)
apply(matrix(c(rep("<p>",nLi), txt,rep("</p>",nLi)), nrow=nLi), 1, paste, collapse="") }
htmVec <- c('<!DOCTYPE html>','<html lang="en">','<head>','<meta charset="utf-8">')
htmTit <- paste(c('<title>',myHtmTit,'</title>'),collapse="")
htmVec <- c(htmVec,htmTit,"</head>","<body>")
htmCom <- paste(c("<!-- ",myComment,"-->"),collapse="")
htmGraTit <- if(is.null(tit)) NULL else paste(c("<h2>",tit,"</h2>"),collapse="")
htmVec <- c(htmVec,htmCom,htmGraTit)
if(!is.null(textAtStart)) htmVec <- c(htmVec,.convTxtToHtmPar(textAtStart))
htmImg <- paste(c('<img src="',.corPath(pngFileNa),'" alt="wrGraph_imageForMouseOver" usemap="
displSi[1],'px;height:',displSi[2],'px">'),collapse="")
htmVec <- c(htmVec,htmImg,'<map name="colormap">')
ar1 <- '<area title="'
ar3 <- 'shape="circle" coords="'
ar5 <- ' alt="'
ar7 <- '"'
htmCor <- data.frame(ar1,na1=myCoor[,colN2[4]],'" ',ar3,corX=myCoor[,colN2[2]],
',',corY=myCoor[,colN2[3]],',',diam=pxDiam,naZ='"',stringsAsFactors=FALSE)
if(!is.na(colN2[5])) htmCor <- data.frame(htmCor[,-1*ncol(htmCor)],na2='" href="',na3=.corPath(myCoor$link),'"',stringsAsFactors=FALSE)
htmCor <- cbind(htmCor,last=" >")
htmCor <- as.character(apply(htmCor,1,paste,collapse=""))
htmVec <- c(htmVec,htmCor,"</map>")
if(!is.null(textAtEnd)) htmVec <- c(htmVec,.convTxtToHtmPar(textAtEnd))
htmVec <- c(htmVec,"</body>","</html>")
if(is.null(HtmFileNa)) HtmFileNa <- paste(sub(".png$","",pngFileNa),".html",sep="")
if(file.exists(HtmFileNa) & !silent) message(fxNa," BEWARE, file '",HtmFileNa,"' will be overwritten !")
tryWrite <- try(cat(paste(htmVec,collpse="\n"),file=HtmFileNa))
if(class(tryWrite) =="try-error") warning(fxNa," PROBLEM : couldn't write Html file '",
HtmFileNa,"' ! (file open ? check path,rights etc)")
}
.serachColName <- function(x,searchColNa, plusLowerCaps=TRUE,returnList=TRUE,callFrom=NULL) {
fxNa <- wrMisc::.composeCallName(callFrom, newNa=".serachColName")
x <- if(length(dim(x)) >1) colnames(x) else as.character(x)
if(length(x) <1) return(NULL) else {
errMsg <- "argument 'searchColNa' is emty or all NA !"
if(length(searchColNa) <1) stop(errMsg)
chNa <- is.na(searchColNa)
if(any(chNa)) {if(all(chNa)) stop(errMsg) else searchColNa <- searchColNa[which(!chNa)]}
if(plusLowerCaps) searchColNa <- wrMisc::.plusLowerCaps(searchColNa)
out <- wrMisc::naOmit(match(searchColNa,x))
if(length(out) <1) stop("none of the terms found")
if(returnList) list(foundNa=x[out[1]],remainNa=x[-out]) else out[1] }}
|
plot.see_check_model <- function(x,
style = theme_lucid,
colors = c("
...) {
p <- list()
panel <- attr(x, "panel")
check <- attr(x, "check")
size_point <- attr(x, "dot_size")
size_line <- attr(x, "line_size")
show_labels <- attr(x, "show_labels") %||% TRUE
size_text <- attr(x, "text_size")
alpha_level <- attr(x, "alpha")
dot_alpha_level <- attr(x, "dot_alpha")
detrend <- attr(x, "detrend")
if (missing(style) && !is.null(attr(x, "theme"))) {
theme_style <- unlist(strsplit(attr(x, "theme"), "::", fixed = TRUE))
style <- get(theme_style[2], asNamespace(theme_style[1]))
}
if (missing(colors)) {
colors <- attr(x, "colors")
}
if (is.null(colors)) {
colors <- c("
}
colors <- unname(colors)
if (is.null(alpha_level)) {
alpha_level <- .2
}
if (is.null(dot_alpha_level)) {
dot_alpha_level <- .8
}
if (is.null(check)) check <- "all"
if ("NCV" %in% names(x) && !is.null(x$NCV) && any(c("ncv", "linearity", "all") %in% check)) {
p$NCV <- .plot_diag_linearity(
x$NCV,
size_point,
size_line,
alpha_level,
theme_style = style,
colors = colors,
dot_alpha_level = dot_alpha_level
)
}
if ("HOMOGENEITY" %in% names(x) && !is.null(x$HOMOGENEITY) && any(c("homogeneity", "all") %in% check)) {
p$HOMOGENEITY <- .plot_diag_homogeneity(
x$HOMOGENEITY,
size_point,
size_line,
alpha_level,
theme_style = style,
colors = colors,
dot_alpha_level = dot_alpha_level
)
}
if ("VIF" %in% names(x) && !is.null(x$VIF) && any(c("vif", "all") %in% check)) {
p$VIF <- .plot_diag_vif(
x$VIF,
theme_style = style,
colors = colors
)
}
if ("INFLUENTIAL" %in% names(x) && !is.null(x$INFLUENTIAL) && any(c("outliers", "influential", "all") %in% check)) {
p$OUTLIERS <- .plot_diag_outliers_new(
x$INFLUENTIAL,
show_labels = show_labels,
size_text = size_text,
size_line = size_line,
theme_style = style,
colors = colors,
dot_alpha_level = dot_alpha_level
)
}
if ("QQ" %in% names(x) && !is.null(x$QQ) && any(c("qq", "all") %in% check)) {
p$QQ <- .plot_diag_qq(
x$QQ,
size_point,
size_line,
alpha_level = alpha_level,
detrend = detrend,
theme_style = style,
colors = colors,
dot_alpha_level = dot_alpha_level
)
}
if ("NORM" %in% names(x) && !is.null(x$NORM) && any(c("normality", "all") %in% check)) {
p$NORM <- .plot_diag_norm(
x$NORM,
size_line,
alpha_level = alpha_level,
theme_style = style,
colors = colors
)
}
if ("REQQ" %in% names(x) && !is.null(x$REQQ) && any(c("reqq", "all") %in% check)) {
ps <- .plot_diag_reqq(
x$REQQ,
size_point,
size_line,
alpha_level = alpha_level,
theme_style = style,
colors = colors,
dot_alpha_level = dot_alpha_level
)
for (i in 1:length(ps)) {
p[[length(p) + 1]] <- ps[[i]]
}
}
if (panel) {
plots(p, n_columns = 2)
} else {
return(p)
}
}
.plot_diag_vif <- function(x,
theme_style = theme_lucid,
colors = unname(social_colors(c("green", "blue", "red")))) {
ylim <- max(x$y, na.rm = TRUE)
if (ylim < 10) ylim <- 10
x$group <- factor(x$group, levels = c("low", "moderate", "high"))
levels(x$group) <- c("low (< 5)", "moderate (< 10)", "high (>= 10)")
names(colors) <- c("low (< 5)", "moderate (< 10)", "high (>= 10)")
p <- ggplot2::ggplot(x, ggplot2::aes(x = .data$x, y = .data$y, fill = .data$group))
if (ylim > 5) {
p <- p + ggplot2::geom_rect(
xmin = -Inf,
xmax = Inf,
ymin = 0,
ymax = 5,
fill = colors[1],
color = NA,
alpha = .025
)
p <- p + ggplot2::geom_rect(
xmin = -Inf,
xmax = Inf,
ymin = 5,
ymax = ifelse(ylim > 10, 10, ylim),
fill = colors[2],
color = NA,
alpha = .025
)
}
if (ylim > 10) {
p <- p + ggplot2::geom_rect(
xmin = -Inf,
xmax = Inf,
ymin = 10,
ymax = ylim,
fill = colors[3],
color = NA,
alpha = .025
)
}
p <- p +
ggplot2::geom_col(width = 0.7) +
ggplot2::labs(
title = "Collinearity",
subtitle = "Higher bars (>5) indicate potential collinearity issues",
x = NULL,
y = "Variance Inflation Factor (VIF)",
fill = NULL
) +
ggplot2::scale_fill_manual(values = colors) +
theme_style(
base_size = 10,
plot.title.space = 3,
axis.title.space = 5
) +
ggplot2::ylim(c(0, ylim)) +
ggplot2::theme(
legend.position = "bottom",
legend.margin = ggplot2::margin(0, 0, 0, 0),
legend.box.margin = ggplot2::margin(-5, -5, -5, -5)
)
if ("facet" %in% colnames(x)) {
p <- p + ggplot2::facet_wrap(~facet, nrow = 1, scales = "free")
}
p
}
.plot_diag_norm <- function(x,
size_line,
alpha_level = .2,
theme_style = theme_lucid,
colors = unname(social_colors(c("green", "blue", "red")))) {
ggplot2::ggplot(x, ggplot2::aes(x = .data$x)) +
ggplot2::geom_ribbon(
mapping = ggplot2::aes(ymin = 0, ymax = .data$y),
colour = NA,
fill = colors[2],
alpha = alpha_level
) +
ggplot2::geom_line(
mapping = ggplot2::aes(y = .data$curve),
colour = colors[1],
size = size_line
) +
ggplot2::labs(
x = "Residuals",
y = "Density",
title = "Normality of Residuals",
subtitle = "Distribution should be close to the normal curve"
) +
theme_style(
base_size = 10,
plot.title.space = 3,
axis.title.space = 5
) +
ggplot2::scale_y_continuous(labels = NULL)
}
.plot_diag_qq <- function(x,
size_point,
size_line,
alpha_level = .2,
detrend = FALSE,
theme_style = theme_lucid,
colors = unname(social_colors(c("green", "blue", "red"))),
dot_alpha_level = .8) {
if (requireNamespace("qqplotr", quietly = TRUE)) {
qq_stuff <- list(
qqplotr::stat_qq_band(alpha = alpha_level, detrend = detrend),
qqplotr::stat_qq_line(
size = size_line,
colour = colors[1],
detrend = detrend
),
qqplotr::stat_qq_point(
shape = 16,
stroke = 0,
size = size_point,
colour = colors[2],
alpha = dot_alpha_level,
detrend = detrend
)
)
y_lab <- "Sample Quantiles"
} else {
message(
"For confidence bands",
if (isTRUE(detrend)) " and detrending",
", please install `qqplotr`."
)
qq_stuff <- list(
ggplot2::geom_qq(
shape = 16, stroke = 0,
size = size_point,
colour = colors[2]
),
ggplot2::geom_qq_line(
size = size_line,
colour = colors[1]
)
)
y_lab <- "Sample Quantiles"
}
ggplot2::ggplot(x, ggplot2::aes(sample = .data$y)) +
qq_stuff +
ggplot2::labs(
title = "Normality of Residuals",
subtitle = "Dots should fall along the line",
y = y_lab,
x = "Standard Normal Distribution Quantiles"
) +
theme_style(
base_size = 10,
plot.title.space = 3,
axis.title.space = 5
)
}
.plot_diag_pp <- function(x,
size_point,
size_line,
alpha_level = .2,
detrend = FALSE,
theme_style = theme_lucid,
colors = unname(social_colors(c("green", "blue", "red"))),
dot_alpha_level = .8) {
if (requireNamespace("qqplotr", quietly = TRUE)) {
p_plot <- ggplot2::ggplot(x, ggplot2::aes(sample = .data$res)) +
qqplotr::stat_pp_band(alpha = alpha_level, detrend = detrend) +
qqplotr::stat_pp_line(
size = size_line,
colour = colors[1],
detrend = detrend
) +
qqplotr::stat_pp_point(
shape = 16, stroke = 0,
size = size_point,
colour = colors[2],
alpha = dot_alpha_level,
detrend = detrend
)
} else if (requireNamespace("MASS", quietly = TRUE)) {
message(
"For confidence bands",
if (isTRUE(detrend)) " and detrending",
", please install `qqplotr`."
)
x$probs <- stats::ppoints(x$res)
dparms <- MASS::fitdistr(x$res, densfun = "normal")
x$y <- do.call(stats::pnorm, c(list(q = x$res), dparms$estimate))
p_plot <- ggplot2::ggplot(x, ggplot2::aes(x = .data$probs, y = .data$y)) +
ggplot2::geom_abline(
slope = 1,
size = size_line,
colour = colors[1]
) +
geom_point2(
colour = colors[2],
size = size_point,
alpha = dot_alpha_level
)
} else {
stop("Package 'qqplotr' OR 'MASS' required for PP-plots. Please install one of them.", call. = FALSE)
}
p_plot +
ggplot2::labs(
title = "Normality of Residuals (PP plot)",
subtitle = "Dots should fall along the line",
y = "Cummulative Probability",
x = "Probability Points"
) +
theme_style(
base_size = 10,
plot.title.space = 3,
axis.title.space = 5
)
}
.plot_diag_homogeneity <- function(x,
size_point,
size_line,
alpha_level = .2,
theme_style = theme_lucid,
colors = unname(social_colors(c("green", "blue", "red"))),
dot_alpha_level = .8) {
ggplot2::ggplot(x, ggplot2::aes(x = .data$x, .data$y)) +
geom_point2(
colour = colors[2],
size = size_point,
alpha = dot_alpha_level
) +
ggplot2::stat_smooth(
method = "loess",
se = TRUE,
alpha = alpha_level,
formula = y ~ x,
size = size_line,
colour = colors[1]
) +
ggplot2::labs(
title = "Homogeneity of Variance",
subtitle = "Reference line should be flat and horizontal",
y = expression(sqrt("|Std. residuals|")),
x = "Fitted values"
) +
theme_style(
base_size = 10,
plot.title.space = 3,
axis.title.space = 5
)
}
.plot_diag_linearity <- function(x,
size_point,
size_line,
alpha_level = .2,
theme_style = theme_lucid,
colors = unname(social_colors(c("green", "blue", "red"))),
dot_alpha_level = .8) {
ggplot2::ggplot(x, ggplot2::aes(x = .data$x, y = .data$y)) +
geom_point2(
colour = colors[2],
size = size_point,
alpha = dot_alpha_level
) +
ggplot2::geom_smooth(
method = "loess",
se = TRUE,
formula = y ~ x,
alpha = alpha_level,
size = size_line,
colour = colors[1]
) +
ggplot2::geom_hline(yintercept = 0, linetype = "dashed") +
ggplot2::labs(
x = "Fitted values",
y = "Residuals",
title = "Linearity",
subtitle = "Reference line should be flat and horizontal"
) +
theme_style(
base_size = 10,
plot.title.space = 3,
axis.title.space = 5
)
}
.plot_diag_reqq <- function(x,
size_point,
size_line,
panel = TRUE,
alpha_level = .2,
theme_style = theme_lucid,
colors = unname(social_colors(c("green", "blue", "red"))),
dot_alpha_level = .8) {
lapply(names(x), function(i) {
dat <- x[[i]]
p <- ggplot2::ggplot(dat, ggplot2::aes(x = .data$x, y = .data$y)) +
ggplot2::labs(
x = "Theoretical Quantiles",
y = "RE Quantiles",
title = sprintf("Normality of Random Effects (%s)", i),
subtitle = "Dots should be plotted along the line"
) +
ggplot2::stat_smooth(
method = "lm",
alpha = alpha_level,
size = size_line,
formula = y ~ x,
colour = colors[1]
) +
ggplot2::geom_errorbar(
ggplot2::aes(ymin = .data$conf.low, ymax = .data$conf.high),
width = 0,
colour = colors[2],
alpha = dot_alpha_level
) +
geom_point2(
colour = colors[2],
size = size_point,
alpha = dot_alpha_level
) +
theme_style(
base_size = 10,
plot.title.space = 3,
axis.title.space = 5
)
if (nlevels(dat$facet) > 1 && isTRUE(panel)) {
p <- p + ggplot2::facet_wrap(~facet, scales = "free")
}
p
})
}
|
lrpage <- tabItem(tabName = "lr",
h2("Likelihood ratios"),
"The method available here (formula 10 from Simel et al) allows for many scenarios. The appropriate proportions should be entered.",
tags$br(),
"Groups here refer to e.g. the disease status.",
tags$br(),
"To compute for the positive likelihood ratio, enter the sensitivity in the proportion for group 1 and 1 - specificity in the proportion for group 2.",
tags$br(),
"To compute for the negative likelihood ratio, enter 1-sensitivity in the proportion for group 1 and specificity in the proportion for group 2.",
tags$br(),
"The method can also be used for conditional likelihoods by using the appropriate proportions (e.g. the proportion of positive or negative tests against inconclusive ones, i.e. yields), analogous to the simple case described above.",
h4("Please enter the following"),
sliderInput("lr_prev", "Prevalence",
min = 0, max = 1, value = .5),
sliderInput("lr_p1", "Proportion of events in group 1",
min = 0, max = 1, value = .5),
sliderInput("lr_p2", "Proportion of events in group 2",
min = 0, max = 1, value = .4),
h4("Please enter one of the following"),
numericInput("lr_n", "Total sample size",
value = NULL),
"The number in each group (e.g. diseased and healthy) is calculated from this as sample size * prevalence (group 1, which might be diseased people) and sample size * 1-prevalence.",
numericInput("lr_ciwidth", "Confidence interval width",
value = NULL, min = 0, max = 1),
h4("Results"),
verbatimTextOutput("lr_out"),
tableOutput("lr_tab"),
"Code to replicate in R:",
verbatimTextOutput("lr_code"),
h4("References"),
"Simel, DL, Samsa, GP and Matchar, DB (1991) Likelihood ratios with confidence: Sample size estimation for diagnostic test studies. ", tags$i("J Clin Epidemiol"), "44(8), 763-770, DOI 10.1016/0895-4356(91)90128-v"
)
lr_fn <- function(input, code = FALSE){
if(is.na(input$lr_n) & is.na(input$lr_ciwidth)) {
cat("Awaiting 'number of observations' or 'confidence interval width'")
} else {
z <- ifelse(is.na(input$lr_n),
paste0("conf.width = ", input$lr_ciwidth),
paste0("n = ", input$lr_n))
x <- paste0("prec_lr(prev = ", input$lr_prev,
", p1 = ", input$lr_p1,
", p2 = ", input$lr_p2,
", ", z,
", conf.level = ", input$conflevel,
")")
if(code){
cat(x)
} else {
eval(parse(text = x))
}
}
}
|
context("Checking misc: model diagnostic functions for rma.mv()")
source("settings.r")
dat1 <- dat.konstantopoulos2011
dat1 <- dat1[dat1$district %in% c(11, 12, 18, 71, 108, 644),]
rownames(dat1) <- 1:nrow(dat1)
dat1$yi[dat1$district %in% 12] <- NA
dat1$yi[dat1$district %in% 18 & dat1$school == 2] <- NA
dat1$yi[dat1$district %in% 108] <- dat1$yi[dat1$district %in% 108] + 1
dat1$district11 <- ifelse(dat1$district == 11, 1, 0)
dat1$study53 <- ifelse(dat1$study == 53, 1, 0)
dat1$study54 <- ifelse(dat1$study == 54, 1, 0)
dat1$study55 <- ifelse(dat1$study == 55, 1, 0)
dat1$study56 <- ifelse(dat1$study == 56, 1, 0)
dat2 <- dat1[c(23, 2, 6, 3, 19, 14, 20, 12, 21, 9, 13, 7, 11, 8, 10, 22, 18, 1, 5, 4, 17, 15, 16),]
res1 <- suppressWarnings(rma.mv(yi, vi, mods = ~ district11 + study53 + study54 + study55 + study56, random = ~ 1 | district/school, data=dat1, slab=study, sparse=sparse))
res2 <- suppressWarnings(rma.mv(yi, vi, mods = ~ district11 + study53 + study54 + study55 + study56, random = ~ 1 | district/school, data=dat2, slab=study, sparse=sparse))
test_that("model diagnostic functions work with 'na.omit'.", {
skip_on_cran()
options(na.action="na.omit")
sav1 <- rstandard(res1)
sav2 <- rstandard(res2)
sav2 <- sav2[match(sav1$slab, sav2$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$resid), rep(FALSE,18))
sav1 <- rstandard(res1, cluster=dat1$district)
sav2 <- rstandard(res2, cluster=dat2$district)
sav2$obs <- sav2$obs[match(sav1$obs$slab, sav2$obs$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$obs$resid), rep(FALSE,18))
expect_equivalent(is.na(sav1$cluster$X2), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- rstudent(res1)
sav2 <- rstudent(res2)
sav2 <- sav2[match(sav1$slab, sav2$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$resid), c(rep(FALSE,14), rep(TRUE,4)))
sav1 <- rstudent(res1, cluster=dat1$district)
sav2 <- rstudent(res2, cluster=dat2$district)
sav2$obs <- sav2$obs[match(sav1$obs$slab, sav2$obs$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$obs$resid), c(rep(TRUE,4), rep(FALSE,10), rep(TRUE,4)))
expect_equivalent(is.na(sav1$cluster$X2), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- rstudent(res1, cluster=dat1$district, parallel="snow")
sav2 <- rstudent(res2, cluster=dat2$district, parallel="snow")
sav2$obs <- sav2$obs[match(sav1$obs$slab, sav2$obs$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$obs$resid), c(rep(TRUE,4), rep(FALSE,10), rep(TRUE,4)))
expect_equivalent(is.na(sav1$cluster$X2), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- rstudent(res1, cluster=dat1$district, reestimate=FALSE)
sav2 <- rstudent(res2, cluster=dat2$district, reestimate=FALSE)
sav2$obs <- sav2$obs[match(sav1$obs$slab, sav2$obs$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$obs$resid), c(rep(TRUE,4), rep(FALSE,10), rep(TRUE,4)))
expect_equivalent(is.na(sav1$cluster$X2), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- rstudent(res1, cluster=dat1$district, parallel="snow", reestimate=FALSE)
sav2 <- rstudent(res2, cluster=dat2$district, parallel="snow", reestimate=FALSE)
sav2$obs <- sav2$obs[match(sav1$obs$slab, sav2$obs$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$obs$resid), c(rep(TRUE,4), rep(FALSE,10), rep(TRUE,4)))
expect_equivalent(is.na(sav1$cluster$X2), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- cooks.distance(res1)
sav2 <- cooks.distance(res2)
sav2 <- sav2[match(names(sav1), names(sav2))]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1), c(rep(FALSE,14), rep(TRUE,4)))
sav1 <- cooks.distance(res1, cluster=dat1$district)
sav2 <- cooks.distance(res2, cluster=dat2$district)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- cooks.distance(res1, cluster=dat1$district, parallel="snow")
sav2 <- cooks.distance(res2, cluster=dat2$district, parallel="snow")
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- cooks.distance(res1, cluster=dat1$district, reestimate=FALSE)
sav2 <- cooks.distance(res2, cluster=dat2$district, reestimate=FALSE)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- cooks.distance(res1, cluster=dat1$district, parallel="snow", reestimate=FALSE)
sav2 <- cooks.distance(res2, cluster=dat2$district, parallel="snow", reestimate=FALSE)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- dfbetas(res1)
sav2 <- dfbetas(res2)
sav2 <- sav2[match(rownames(sav1), rownames(sav2)),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$intrcpt), c(rep(FALSE,14), rep(TRUE,4)))
sav1 <- dfbetas(res1, cluster=dat1$district)
sav2 <- dfbetas(res2, cluster=dat2$district)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$intrcpt), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- dfbetas(res1, cluster=dat1$district, parallel="snow")
sav2 <- dfbetas(res2, cluster=dat2$district, parallel="snow")
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$intrcpt), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- dfbetas(res1, cluster=dat1$district, reestimate=FALSE)
sav2 <- dfbetas(res2, cluster=dat2$district, reestimate=FALSE)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$intrcpt), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- dfbetas(res1, cluster=dat1$district, parallel="snow", reestimate=FALSE)
sav2 <- dfbetas(res2, cluster=dat2$district, parallel="snow", reestimate=FALSE)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$intrcpt), c(TRUE, rep(FALSE,3), TRUE))
sav1 <- ranef(res1)
sav2 <- ranef(res2)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$district$intrcpt), rep(FALSE,5))
expect_equivalent(is.na(sav1$`district/school`$intrcpt), rep(FALSE,18))
})
test_that("model diagnostic functions work with 'na.pass'.", {
skip_on_cran()
options(na.action="na.pass")
sav1 <- rstandard(res1)
sav2 <- rstandard(res2)
sav2 <- sav2[match(sav1$slab, sav2$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$resid), c(rep(FALSE,4), rep(TRUE,4), FALSE, TRUE, rep(FALSE,13)))
sav1 <- rstandard(res1, cluster=dat1$district)
sav2 <- rstandard(res2, cluster=dat2$district)
sav2$obs <- sav2$obs[match(sav1$obs$slab, sav2$obs$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$obs$resid), c(rep(FALSE,4), rep(TRUE,4), FALSE, TRUE, rep(FALSE,13)))
expect_equivalent(is.na(sav1$cluster$X2), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- rstudent(res1)
sav2 <- rstudent(res2)
sav2 <- sav2[match(sav1$slab, sav2$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$resid), c(rep(FALSE,4), rep(TRUE,4), FALSE, TRUE, rep(FALSE,9), rep(TRUE,4)))
sav1 <- rstudent(res1, cluster=dat1$district)
sav2 <- rstudent(res2, cluster=dat2$district)
sav2$obs <- sav2$obs[match(sav1$obs$slab, sav2$obs$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$obs$resid), c(rep(TRUE,8), FALSE, TRUE, rep(FALSE,9), rep(TRUE,4)))
expect_equivalent(is.na(sav1$cluster$X2), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- rstudent(res1, cluster=dat1$district, parallel="snow")
sav2 <- rstudent(res2, cluster=dat2$district, parallel="snow")
sav2$obs <- sav2$obs[match(sav1$obs$slab, sav2$obs$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$obs$resid), c(rep(TRUE,8), FALSE, TRUE, rep(FALSE,9), rep(TRUE,4)))
expect_equivalent(is.na(sav1$cluster$X2), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- rstudent(res1, cluster=dat1$district, reestimate=FALSE)
sav2 <- rstudent(res2, cluster=dat2$district, reestimate=FALSE)
sav2$obs <- sav2$obs[match(sav1$obs$slab, sav2$obs$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$obs$resid), c(rep(TRUE,8), FALSE, TRUE, rep(FALSE,9), rep(TRUE,4)))
expect_equivalent(is.na(sav1$cluster$X2), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- rstudent(res1, cluster=dat1$district, parallel="snow", reestimate=FALSE)
sav2 <- rstudent(res2, cluster=dat2$district, parallel="snow", reestimate=FALSE)
sav2$obs <- sav2$obs[match(sav1$obs$slab, sav2$obs$slab),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$obs$resid), c(rep(TRUE,8), FALSE, TRUE, rep(FALSE,9), rep(TRUE,4)))
expect_equivalent(is.na(sav1$cluster$X2), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- cooks.distance(res1)
sav2 <- cooks.distance(res2)
sav2 <- sav2[match(names(sav1), names(sav2))]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1), c(rep(FALSE,4), rep(TRUE,4), FALSE, TRUE, rep(FALSE,9), rep(TRUE,4)))
sav1 <- cooks.distance(res1, cluster=dat1$district)
sav2 <- cooks.distance(res2, cluster=dat2$district)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- cooks.distance(res1, cluster=dat1$district, parallel="snow")
sav2 <- cooks.distance(res2, cluster=dat2$district, parallel="snow")
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- cooks.distance(res1, cluster=dat1$district, reestimate=FALSE)
sav2 <- cooks.distance(res2, cluster=dat2$district, reestimate=FALSE)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- cooks.distance(res1, cluster=dat1$district, parallel="snow", reestimate=FALSE)
sav2 <- cooks.distance(res2, cluster=dat2$district, parallel="snow", reestimate=FALSE)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- dfbetas(res1)
sav2 <- dfbetas(res2)
sav2 <- sav2[match(rownames(sav1), rownames(sav2)),]
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$intrcpt), c(rep(FALSE,4), rep(TRUE,4), FALSE, TRUE, rep(FALSE,9), rep(TRUE,4)))
sav1 <- dfbetas(res1, cluster=dat1$district)
sav2 <- dfbetas(res2, cluster=dat2$district)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$intrcpt), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- dfbetas(res1, cluster=dat1$district, parallel="snow")
sav2 <- dfbetas(res2, cluster=dat2$district, parallel="snow")
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$intrcpt), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- dfbetas(res1, cluster=dat1$district, reestimate=FALSE)
sav2 <- dfbetas(res2, cluster=dat2$district, reestimate=FALSE)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$intrcpt), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- dfbetas(res1, cluster=dat1$district, parallel="snow", reestimate=FALSE)
sav2 <- dfbetas(res2, cluster=dat2$district, parallel="snow", reestimate=FALSE)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$intrcpt), c(rep(TRUE,2), rep(FALSE,3), TRUE))
sav1 <- ranef(res1)
sav2 <- ranef(res2)
expect_equivalent(sav1, sav2)
expect_equivalent(is.na(sav1$district$intrcpt), c(FALSE, TRUE, rep(FALSE,4)))
expect_equivalent(is.na(sav1$`district/school`$intrcpt), c(rep(FALSE,4), rep(TRUE,4), FALSE, TRUE, rep(FALSE,13)))
options(na.action="na.omit")
})
rm(list=ls())
|
R.Version()$version.string
set.seed(1)
n<- 258
y<- rexp(2*n,rate=1/60.5932)
cured<- rbinom(2*n,1,0.60)
y[cured==1]<- 100
status<-rep(1,2*n)
status[cured==1]<-0
z<-rep(c(1,2),each=n)
IsaSimData<-data.frame(y=y,z=z,status=status)
|
ts_shiny_types <- function(){
engine <- engine_get()
if(engine == "npm"){
cli::cli_alert_warning(
"Installing types with npm may fail, try with yarn. See {.code engine_set}"
)
}
engine <- engine_get()
cmd <- engine_install_cmd()
cli::cli_alert(
"Run the following from your terminal"
)
cli::cli_text(
"{.code {engine} {cmd} rstudio/shiny}"
)
}
ts_get_types <- function(..., versions = NULL){
types <- c(...)
if(length(types) == 0)
stop("No types specified", call. = FALSE)
if(is.null(versions)){
engine_install(types, scope = "dev")
return()
}
if(length(types) != length(versions))
stop("Number of types does not match the number of versions")
types <- paste0(types, "@", versions)
engine_install(types, scope = "dev")
}
ts_get_type <- function(type, version = NULL){
if(missing(type))
stop("Missing type", call. = FALSE)
if(!is.null(version))
type <- sprintf("%s@%s", type, version)
arg <- sprintf("@types/%s", type)
engine_install(arg)
}
|
library(Pareto)
context("test functions PiecewisePareto")
test_that("PiecewisePareto_Layer_Mean", {
expect_equal(PiecewisePareto_Layer_Mean(8000, 2000, t = 1000, alpha = 2), 400)
expect_equal(PiecewisePareto_Layer_Mean(8000, 2000, t = 5000, alpha = 2, truncation = 10000), 4666.66666666667)
expect_equal(PiecewisePareto_Layer_Mean(c(8000, 2000), c(2000, 1000), t = 5000, alpha = 2, truncation = 10000), c(4666.66666666667, 2000))
expect_equal(PiecewisePareto_Layer_Mean(c(8000, 2000), c(2000, 1000), t = c(1000, 3000, 5000), alpha = c(1, 2, 3), truncation = 10000), c(976.89367953673514, 1098.61228866810916))
})
test_that("PiecewisePareto_Layer_SM", {
expect_equal(PiecewisePareto_Layer_SM(8000, 2000, t = 1000, alpha = 2), 1618875.8248682)
expect_equal(PiecewisePareto_Layer_SM(8000, 2000, t = 5000, alpha = 2, truncation = 10000), 23543145.370663)
expect_equal(PiecewisePareto_Layer_SM(c(1000, 8000), c(1000, 2000), t = c(1000, 3000, 5000), alpha = c(1, 2, 3), truncation = 10000), c(613705.63888010941, 3300236.16730614332))
})
test_that("PiecewisePareto_Layer_Var", {
expect_equal(PiecewisePareto_Layer_Var(8000, 2000, 2, t = 1000), 1458875.8248682)
expect_equal(PiecewisePareto_Layer_Var(8000, 2000, 2, t = 5000, truncation = 10000), 1765367.59288524)
expect_equal(PiecewisePareto_Layer_Var(c(1000, 8000), c(1000, 2000), t = c(1000, 3000, 5000), alpha = c(1, 2, 3), truncation = 10000), c(133252.62496190792, 2345914.90618732199))
})
test_that("qPiecewisePareto", {
expect_equal(qPiecewisePareto((1:9) * 0.1, c(1000,2000), c(1,2)), c(1111.1111111111111, 1250.0000000000000,
1428.5714285714287, 1666.6666666666667, 2000.0000000000000, 2236.0679774997902,
2581.9888974716114, 3162.2776601683800, 4472.1359549995805))
})
test_that("pPiecewisePareto", {
expect_equal(pPiecewisePareto(c(1:4) * 1000, t = (1:3) * 1000, alpha = 1:3, truncation = 4000), c(0, 0.5, 0.77777777777777779, 1))
})
test_that("dPiecewisePareto", {
expect_equal(dPiecewisePareto(c(1:4) * 1000, t = (1:3) * 1000, alpha = 1:3, truncation = 4000), c(0.001, 0.0005, 0.00022222222222222221, 0))
})
test_that("dPiecewisePareto", {
expect_equal(qPiecewisePareto(c(1:4) * 0.2, t = (1:3) * 1000, alpha = 1:3, truncation = 4000), c(1250.0000000000000, 1666.6666666666667, 2236.0679774997902, 3060.1459631738917))
})
test_that("rPiecewisePareto with truncation wd", {
set.seed(1972)
NumberOfSimulations <- 1000000
t <- c(1000,3000,5000)
Cover <- 8000
AttPoint <- 2000
truncation <- 6000
alpha <- c(0.7,1.5,2)
truncation_type ="wd"
expect_equal(PiecewisePareto_Layer_Mean(Cover, AttPoint, t, alpha, truncation = truncation, truncation_type = truncation_type), 868.729076663466)
losses <- rPiecewisePareto(NumberOfSimulations, t, alpha, truncation = truncation, truncation_type = truncation_type)
xs_losses <- pmin(Cover, pmax(0, losses - AttPoint))
mean(xs_losses)
ratio <- round(mean(xs_losses) / PiecewisePareto_Layer_Mean(Cover, AttPoint, t, alpha, truncation = truncation, truncation_type = truncation_type), 2)
expect_equal(ratio, 1)
})
test_that("rPiecewisePareto with truncation lp", {
set.seed(1972)
NumberOfSimulations <- 1000000
t <- c(1000,3000,5000)
Cover <- 8000
AttPoint <- 2000
truncation <- 6000
alpha <- c(0.7,1.5,2)
truncation_type ="lp"
expect_equal(PiecewisePareto_Layer_Mean(Cover, AttPoint, t, alpha, truncation = truncation, truncation_type = truncation_type), 1255.52081303827)
losses <- rPiecewisePareto(NumberOfSimulations, t, alpha, truncation = truncation, truncation_type = truncation_type)
xs_losses <- pmin(Cover, pmax(0, losses - AttPoint))
mean(xs_losses)
ratio <- round(mean(xs_losses) / PiecewisePareto_Layer_Mean(Cover, AttPoint, t, alpha, truncation = truncation, truncation_type = truncation_type), 2)
expect_equal(ratio, 1)
})
test_that("rPiecewisePareto without truncation", {
set.seed(1972)
NumberOfSimulations <- 1000000
t <- c(1000,3000,5000)
Cover <- 8000
AttPoint <- 2000
alpha <- c(0.7,1.5,2)
expect_equal(PiecewisePareto_Layer_Mean(Cover, AttPoint, t, alpha), 1696.1079667876)
losses <- rPiecewisePareto(NumberOfSimulations, t, alpha)
xs_losses <- pmin(Cover, pmax(0, losses - AttPoint))
mean(xs_losses)
ratio <- round(mean(xs_losses) / PiecewisePareto_Layer_Mean(Cover, AttPoint, t, alpha), 2)
expect_equal(ratio, 1)
})
test_that("Pareto_ML_Estimator_alpha", {
losses <- c(2021.37427270114, 1144.4154953111, 1263.31435215882, 2159.17623012884, 1597.37248664761, 1272.28453257,
2914.10585100956, 1304.18266162408, 1120.50113120055, 2127.70698437685, 2060.81683374026, 2039.7843971136,
1888.54098901941, 2124.60113577822, 1861.90023645773, 1061.42587835879, 1096.87195504782, 2741.00486150546,
3599.51085744179, 1944.00791988792, 4801.21672397748, 2011.17712322692, 1614.38016727125, 1366.00934974079,
2740.17455761229, 3696.80509791037, 1519.32575139179, 2673.72771069715, 1377.97530890359, 2747.57267315656,
2962.51959921929, 2970.06262726659, 3849.91766409146, 1011.07955688529, 2142.35280378138, 2363.88639730512,
1585.05201649176, 1519.87964078085, 4152.85247579578, 1145.85174532018, 1045.70673772088, 2035.21218839728,
2265.69458584306, 1259.17343777875, 1276.43540240796, 1156.59174646013, 2213.19952527109, 2090.8925597549,
1599.32662288134, 1748.10607173994, 1110.83766088527, 4216.9888129572, 1987.10180900716, 2848.75495497778,
2459.33207487438, 1057.30210620244, 2613.23427141216, 4267.61547888255, 2110.3988745262, 1608.79852597768,
3299.23731214781, 1598.18841764305, 1867.71915473237, 1025.8298666397, 1714.23234124254, 2344.71364141762,
1415.68319510445, 1529.97435270215, 1236.57055448752, 2466.0269323041, 1091.02769697244, 2408.02293167307,
3106.53753930817, 2461.21276690245, 3262.03972168424, 4127.01858195009, 1181.45647693256, 2915.05440240728,
2819.40842718265, 1079.96118940952, 3652.61964913811, 3731.17802733447, 4689.68469988139, 3430.45722285605,
1700.45433736218, 2269.02625009652, 3545.91823730921, 3112.72960104325, 2757.85209289505, 1073.92628882837,
3697.84111140716, 2567.88718258095, 2624.17812649749, 2430.48340413282, 2399.39130252127, 1194.87342560877,
1733.25071770226, 2177.58393770677, 2313.84456911248, 2561.30080556934)
expect_equal(round(PiecewisePareto_ML_Estimator_Alpha(losses, c(1000, 2000, 3000)), 5), c(0.81259, 2.65715, 4.42204))
expect_equal(round(PiecewisePareto_ML_Estimator_Alpha(losses, c(1000, 2000, 3000), truncation = 5000, truncation_type = "lp"), 5), c(0.81259, 2.65715, 1.35691))
expect_equal(round(PiecewisePareto_ML_Estimator_Alpha(losses, c(1000, 2000, 3000), truncation = 5000, truncation_type = "wd"), 5), c(0.59649, 1.50625, 0.98904))
reporting_thresholds <- rep(1000, length(losses))
reporting_thresholds[1] <- 1500
reporting_thresholds[4] <- 1500
expect_equal(round(PiecewisePareto_ML_Estimator_Alpha(losses, c(1000, 2000, 3000), reporting_thresholds = reporting_thresholds), 5), c(0.82524, 2.65715, 4.42204))
censored <- rep(FALSE, length(losses))
censored [1:3] <- TRUE
expect_equal(round(PiecewisePareto_ML_Estimator_Alpha(losses, c(1000, 2000, 3000), reporting_thresholds = reporting_thresholds, is.censored = censored), 5),
c(0.78686, 2.58902, 4.42204))
expect_equal(round(PiecewisePareto_ML_Estimator_Alpha(losses, c(1000, 2000, 3000),
reporting_thresholds = reporting_thresholds, is.censored = censored,
truncation = 5000, truncation_type = "lp"), 5),
c(0.78686, 2.58902, 1.35691))
expect_equal(round(PiecewisePareto_ML_Estimator_Alpha(losses, c(1000, 2000, 3000),
reporting_thresholds = reporting_thresholds, is.censored = censored,
truncation = 5000, truncation_type = "wd"), 5),
c(0.51603, 1.24380, 0.74810))
w <- rep(1, length(losses))
w[1:2] <- 2
w[3] <- 5
losses2 <- c(losses, losses[1:2], rep(losses[3], 4))
expect_equal(PiecewisePareto_ML_Estimator_Alpha(losses, c(1000, 2000, 3000), weights = w), PiecewisePareto_ML_Estimator_Alpha(losses2, c(1000, 2000, 3000)))
expect_equal(PiecewisePareto_ML_Estimator_Alpha(losses, c(1000, 2000, 3000), weights = w, truncation = 5000, truncation_type = "lp"), PiecewisePareto_ML_Estimator_Alpha(losses2, c(1000, 2000, 3000), truncation = 5000, truncation_type = "lp"))
expect_equal(PiecewisePareto_ML_Estimator_Alpha(losses, c(1000, 2000, 3000), weights = w, truncation = 5000, truncation_type = "wd"), PiecewisePareto_ML_Estimator_Alpha(losses2, c(1000, 2000, 3000), truncation = 5000, truncation_type = "wd"))
})
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(ROCaggregator)
library(ROCR)
library(pracma)
library(stats)
set.seed(13)
create_dataset <- function(n){
positive_labels <- n %/% 2
negative_labels <- n - positive_labels
y = c(rep(0, negative_labels), rep(1, positive_labels))
x1 = rnorm(n, 10, sd = 1)
x2 = c(rnorm(positive_labels, 2.5, sd = 2), rnorm(negative_labels, 2, sd = 2))
x3 = y * 0.3 + rnorm(n, 0.2, sd = 0.3)
data.frame(x1, x2, x3, y)[sample(n, n), ]
}
node_1 <- create_dataset(sample(300:400, 1))
node_2 <- create_dataset(sample(300:400, 1))
node_3 <- create_dataset(sample(300:400, 1))
glm.fit <- glm(
y ~ x1 + x2 + x3,
data = rbind(node_1, node_2),
family = binomial,
)
get_roc <- function(dataset){
glm.probs <- predict(glm.fit,
newdata = dataset,
type = "response")
pred <- prediction(glm.probs, c(dataset$y))
perf <- performance(pred, "tpr", "fpr")
perf_p_r <- performance(pred, "prec", "rec")
list(
"fpr" = [email protected][[1]],
"tpr" = [email protected][[1]],
"prec" = [email protected][[1]],
"thresholds" = [email protected][[1]],
"negative_count"= sum(dataset$y == 0),
"total_count" = nrow(dataset),
"auc" = performance(pred, measure = "auc")
)
}
roc_node_1 <- get_roc(node_1)
roc_node_2 <- get_roc(node_2)
roc_node_3 <- get_roc(node_3)
fpr <- list(roc_node_1$fpr, roc_node_2$fpr, roc_node_3$fpr)
tpr <- list(roc_node_1$tpr, roc_node_2$tpr, roc_node_3$tpr)
thresholds <- list(
roc_node_1$thresholds, roc_node_2$thresholds, roc_node_3$thresholds)
negative_count <- c(
roc_node_1$negative_count, roc_node_2$negative_count, roc_node_3$negative_count)
total_count <- c(
roc_node_1$total_count, roc_node_2$total_count, roc_node_3$total_count)
roc_aggregated <- roc_curve(fpr, tpr, thresholds, negative_count, total_count)
roc_auc <- trapz(roc_aggregated$fpr, roc_aggregated$tpr)
sprintf("ROC AUC aggregated from each node's results: %f", roc_auc)
precision_recall_aggregated <- precision_recall_curve(
fpr, tpr, thresholds, negative_count, total_count)
precision_recall_auc <- -trapz(
precision_recall_aggregated$recall, precision_recall_aggregated$pre)
sprintf(
"Precision-Recall AUC aggregated from each node's results: %f",
precision_recall_auc
)
roc_central_case <- get_roc(rbind(node_1, node_2, node_3))
sprintf(
"ROC AUC using ROCR with all the data centrally available: %f",
[email protected][[1]]
)
precision_recall_auc <- trapz(
roc_central_case$tpr,
ifelse(is.nan(roc_central_case$prec), 1, roc_central_case$prec)
)
sprintf(
"Precision-Recall AUC using ROCR with all the data centrally available: %f",
precision_recall_auc
)
plot(roc_aggregated$fpr,
roc_aggregated$tpr,
main="ROC curve",
xlab = "False Positive Rate",
ylab = "True Positive Rate",
cex=0.3,
col="blue",
)
library(pROC, warn.conflicts = FALSE)
get_proc <- function(dataset){
glm.probs <- predict(glm.fit,
newdata = dataset,
type = "response")
roc_obj <- roc(c(dataset$y), c(glm.probs))
list(
"fpr" = 1 - roc_obj$specificities,
"tpr" = roc_obj$sensitivities,
"thresholds" = roc_obj$thresholds,
"negative_count"= sum(dataset$y == 0),
"total_count" = nrow(dataset),
"auc" = roc_obj$auc
)
}
roc_obj_node_1 <- get_proc(node_1)
roc_obj_node_2 <- get_proc(node_2)
roc_obj_node_3 <- get_proc(node_3)
fpr <- list(roc_obj_node_1$fpr, roc_obj_node_2$fpr, roc_obj_node_3$fpr)
tpr <- list(roc_obj_node_1$tpr, roc_obj_node_2$tpr, roc_obj_node_3$tpr)
thresholds <- list(
roc_obj_node_1$thresholds, roc_obj_node_2$thresholds, roc_obj_node_3$thresholds)
negative_count <- c(
roc_obj_node_1$negative_count, roc_obj_node_2$negative_count, roc_obj_node_3$negative_count)
total_count <- c(
roc_obj_node_1$total_count, roc_obj_node_2$total_count, roc_obj_node_3$total_count)
roc_aggregated <- roc_curve(fpr, tpr, thresholds, negative_count, total_count)
roc_auc <- trapz(roc_aggregated$fpr, roc_aggregated$tpr)
sprintf("ROC AUC aggregated from each node's results: %f", roc_auc)
roc_central_case <- get_proc(rbind(node_1, node_2, node_3))
sprintf(
"ROC AUC using pROC with all the data centrally available: %f",
roc_central_case$auc
)
|
dist_ll <- function(y, hurd = Inf, lam = NULL, size = 1, mu = NULL, xi = NULL, sigma = NULL,
dist = c("poisson", "nb", "lognormal", "gpd"),
g.x = F, log = T){
trunc1 <- ifelse(g.x, hurd - 1, 0)
trunc2 <- ifelse(g.x, Inf, hurd - 1)
f <- match.arg(dist)
ll <- switch(f,
poisson = dpois(y, lam, log = T) - log(ppois(trunc2, lam) - ppois(trunc1, lam)),
nb = dnbinom(y, size = size, mu = mu, log = T) - log(pnbinom(trunc2, size = size, mu = mu) - pnbinom(trunc1, size = size, mu = mu)),
lognormal = mlnorm(y, meanlog = mu, sdlog = sqrt(mu+mu^2/size), log = T) - log(plnorm(trunc2 + 0.5, meanlog = mu, sdlog = sqrt(mu+mu^2/size)) - plnorm(trunc1 + 0.5, meanlog = mu, sdlog = sqrt(mu+mu^2/size))),
gpd = mgpd(y, trunc1 + 1, sigma, xi, log = T) - log(pgpd(trunc2 + 0.5, trunc1 + 1, sigma, xi)))
if(log){return(ll)}
else{return(exp(ll))}
}
|
context("Analytic results")
no_w <- 100
no_sp <- 2
p <- newTraitParams(no_sp = no_sp, perfect_scaling = TRUE, no_w = no_w)
p@species_params$pred_kernel_type <- "truncated_lognormal"
n0 <- p@initial_n
n0[] <- 0
n_pp <- p@initial_n_pp
n_pp[] <- p@resource_params$kappa * p@w_full^(-p@resource_params$lambda)
sp <- 1
sigma <- p@species_params$sigma[sp]
beta <- p@species_params$beta[sp]
gamma <- p@species_params$gamma[sp]
q <- p@species_params$q[sp]
n <- p@species_params$n[sp]
lm2 <- p@resource_params$lambda - 2
test_that("getEncounter approximates analytic result when feeding on resource only", {
e <- getEncounter(p, n0, n_pp)[sp, ] * p@w^(lm2 - q)
expect_equivalent(e, rep(e[1], length(e)))
Dx <- p@w[2] / p@w[1] - 1
dx <- log(p@w[2] / p@w[1])
encounter_analytic <- p@resource_params$kappa * exp(lm2^2 * sigma^2 / 2) *
beta^lm2 * sqrt(2 * pi) * sigma * gamma *
Dx / dx
expect_equivalent(e[1], encounter_analytic, tolerance = 1e-3)
Beta <- log(beta)
x_full <- log(p@w_full)
dx <- x_full[2] - x_full[1]
i <- 100
ear <- 0
for (j in 1:(i - 1)) {
ear <- ear + p@w_full[j]^(2 - p@resource_params$lambda) *
exp(-(x_full[i] - x_full[j] - Beta)^2 / (2 * sigma^2))
}
ear <- ear * p@resource_params$kappa * p@w_full[i]^(p@resource_params$lambda - 2) * dx * gamma
expect_equivalent(e[1], ear * Dx / dx)
})
test_that("getDiet approximates analytic result when feeding on resource only", {
n <- p@initial_n
n[] <- rep(p@resource_params$kappa * p@w^(-p@resource_params$lambda), each = 2)
n_pp <- p@initial_n_pp
n_pp[] <- p@resource_params$kappa * p@w_full^(-p@resource_params$lambda)
p0 <- setInteraction(p, interaction = matrix(0, nrow = no_sp, ncol = no_sp))
diet <- getDiet(p0, n, n_pp, proportion = FALSE)[sp, , ]
expect_true(all(diet[, 1:2] == 0))
diet_coeff <- diet[, 3] * p@w^(lm2 - q)
expect_equivalent(diet_coeff, rep(diet_coeff[1], no_w))
feeding_level <- getFeedingLevel(p0, n0, n_pp)[sp, ]
encounter <- getEncounter(p0, n0, n_pp)[sp, ]
expect_equivalent(diet[, 3], encounter * (1 - feeding_level))
})
test_that("getFeedingLevel approximates analytic result", {
f <- getFeedingLevel(p)[sp, ]
expect_equivalent(f, rep(f[1], length(f)),
tolerance = 1e-12, check.names = FALSE)
expect_equivalent(f[1], 0.6, tolerance = 2e-2, check.names = FALSE)
})
|
library(mapview)
expect_equal(mapview:::col2Hex("black"), "
expect_equal(mapview:::col2Hex("black", alpha = TRUE), "
expect_equal(mapview:::standardColor(breweries), "
expect_equal(mapview:::standardColor(trails), "
expect_equal(mapview:::luminence("black"), 0)
expect_equal(mapview:::luminence("white"), 1)
|
RL4 <- function(nsubj, seqs=c("TR","RT"), blocksize, seed=runif(1,max=1E7),
randctrl=TRUE, pmethod=c("normal","exact","cc"), alpha=0.025)
{
pmethod <- match.arg(pmethod)
if (length(nsubj)>1) {
subj <- nsubj
nsubj <- length(subj)
} else {
subj <- 1:nsubj
}
seed <- as.integer(seed)
if(is.na(seed)) seed <- 0
set.seed(seed)
nseq <- length(seqs)
if(missing(blocksize)) blocksize <- 2*nseq
if(blocksize[1]>nsubj) {
blocksize <- 0
warning("Blocksize >
" Blocksize adapted to ", nsubj,".", call. = FALSE )
}
if (any(blocksize==0)) {
blocksize <- nsubj
} else {
blocksize[blocksize<nseq] <- nseq
if (any(nseq*(blocksize%/%nseq) != blocksize)) {
blocksize <- nseq*(blocksize%/%nseq)
blocksize[blocksize<nseq] <- nseq
warning("Blocksize is not a multiple of sequences!",
" Blocksize adapted to ", blocksize,".", call. = FALSE )
blocksize <- unique(blocksize)
}
}
rlv <- rlv(nsubj, nseq, blocksize)
rl <- rlv$rl
runs.p <- runs.pvalue(rl, pmethod=pmethod)
maxrlen <- max(rle(rl)$lengths)
xm <- matrix(rl[1:(nseq*(nsubj%/%nseq))], nrow=nseq)
allblocksequal <- ncol(unique(xm,MARGIN=2))
if (randctrl){
iter <- 0
while(runs.p < alpha | allblocksequal==1){
msg <- paste("runs.p= ", format(runs.p, digits=4),
". Recreating randomlist.", sep="")
if (allblocksequal==1) msg <-
"All nseq blocks equal. Recreating randomlist."
message(msg)
seed <- seed + as.integer(runif(1,max=100))
set.seed(seed)
iter <- iter + 1
rlv <- rlv(nsubj, nseq, blocksize)
rl <- rlv$rl
runs.p <- runs.pvalue(rl, pmethod=pmethod)
maxrlen <- max(rle(rl)$lengths)
if (iter>=2) break
}
} else {
if (allblocksequal==1){
warning("Recurrent pattern of sequences detected.")
}
}
bsv <- rlv$bsv
rlc <- seqs[rl]
ns <- table(rlc)
nsequal <- (ns - ns[1]) == 0
if (!all(nsequal)){
msg <- paste(" ", names(ns))
msg2 <- paste(" ", ns)
warning("Unbalanced design!", "
msg, ":", msg2, call. = FALSE)
}
rl <- data.frame(subject=subj, seqno=rl, sequence=rlc, stringsAsFactors=FALSE)
ns <- t(as.matrix(ns))
nsv <- as.vector(ns)
names(nsv) <- colnames(ns)
if (length(unique(bsv))==1) bsv <- bsv[1]
rlret <- list(rl=rl, seed=seed, blocksize=bsv,
ninseqs=nsv, runs.pvalue=runs.p, date=Sys.time())
class(rlret) <- "rl4"
return(rlret)
}
rlv <- function(nsubj, nseq, blocksize)
{
seqsn <- 1:nseq
n <- 0
rl <- vector(mode="numeric")
bsv <- vector(mode="numeric")
while (n<nsubj){
bs <- ifelse(length(blocksize)>1, sample(blocksize,1), blocksize[1])
bs <- ifelse((nsubj-n) < bs, nsubj-n, bs)
rpp <- ifelse(nseq*bs%/%nseq != bs, bs%/%nseq+1, bs%/%nseq)
rlb <- sample(rep(seqsn, rpp), bs)
rl <- c(rl, rlb)
bsv <- c(bsv, bs)
n <- n + bs
}
rl <- rl[1:nsubj]
return(list(rl=rl, bsv=bsv))
}
|
.keep_phases <- function(data,
phases = c(1, 2),
set.phases = TRUE,
pvar = "phase") {
source_attributes <- attributes(data)
warning <- character(0)
if (class(phases) %in% c("character", "numeric", "integer")) {
if (!length(phases) == 2) {
stop("Phases argument not set correctly.")
}
phases_A <- phases[1]
phases_B <- phases[2]
}
if (class(phases) == "list") {
phases_A <- phases[[1]]
phases_B <- phases[[2]]
}
phases_total <- c(phases_A, phases_B)
N <- length(data)
design_list <- list()
dropped_cases <- numeric(0)
for(case in 1:N) {
design <- rle(as.character(data[[case]][, pvar]))
if (class(phases_total) == "character") {
select_A <- which(design$values %in% phases_A)
select_B <- which(design$values %in% phases_B)
} else {
select_A <- phases_A
select_B <- phases_B
}
if (class(phases_total) != "character") {
if (any(phases_total > length(design$values))) {
warning <- c(warning, paste0("Phase(s) not found. Case ", case, " dropped.\n"))
dropped_cases <- c(dropped_cases, case)
next
}
}
if (class(phases_total) == "character") {
tmp <- sapply(phases_total, function(x) sum(x == design$values) > 1)
if (any(tmp)) {
stop(
paste0(
"Selected phase ", paste(names(tmp[tmp])),
" occure several times. Please give number of phases instead of characters."
)
)
}
tmp <- sapply(phases_total, function(x) any(x == design$values))
if (!all(tmp)) {
warning <- c(
warning, paste0("Phase(s) ", names(tmp[!tmp]), " not found. Case ", case, " dropped.\n")
)
dropped_cases <- c(dropped_cases, case)
next
}
}
design$start <- c(1, cumsum(design$lengths) + 1)[1:length(design$lengths)]
design$stop <- cumsum(design$lengths)
class(design) <- "list"
A <- unlist(lapply(select_A, function(x) design$start[x]:design$stop[x]))
B <- unlist(lapply(select_B, function(x) design$start[x]:design$stop[x]))
data[[case]][,pvar] <- as.character(data[[case]][, pvar])
if (set.phases) {
data[[case]][A ,pvar] <- "A"
data[[case]][B ,pvar] <- "B"
}
data[[case]] <- data[[case]][c(A, B),]
design_list[[case]] <- design
}
if (length(warning) > 0) warning(paste0(warning, collapse = " "))
if (length(dropped_cases > 0)) {
data <- data[-dropped_cases]
design_list <- design_list[-dropped_cases]
source_attributes$names <- source_attributes$names[-dropped_cases]
if (length(data) == 0) stop("No case remained.")
}
attributes(data) <- source_attributes
out <- list(
data = data,
designs = design_list,
N = N,
phases_A = phases_A,
phases_B = phases_B
)
class(out) <- c("sc_keepphases")
out
}
|
context("High-level-UI")
test_that("Names and [[", {
test_file <- tempfile(fileext=".h5")
file.h5 <- H5File$new(test_file, mode="w")
test1 <- file.h5$create_group("test1")
test2 <- test1$create_group("test2")
test3 <- file.h5$create_group("test3")
expect_equal(names(file.h5), c("test1", "test3"))
expect_equal(file.h5$names, c("test1", "test3"))
expect_equal(names(test1), "test2")
expect_equal(names(test2), character(0))
test4 <- file.h5[["test1", dataset_access_pl=h5const$H5P_DEFAULT]]
expect_equal(test1$get_obj_name(), test4$get_obj_name())
test.error <- try(file.h5[["asdf"]], silent=TRUE)
expect_true(inherits(test.error, "try-error"))
expect_true(inherits(try(file.h5[["test1"]] <- test2, silent=TRUE), "try-error"))
file.h5[["test_hard_link"]] <- test1
test_hard_link <- file.h5[["test_hard_link"]]
expect_equal(test_hard_link$obj_info(), test1$obj_info())
robj <- matrix(as.integer(1:20), ncol=4)
test_dataset <- test1$create_dataset("test_dataset", robj)
file.h5[["dataset_hard_link"]] <- test_dataset
test_dataset_hl <- file.h5[["dataset_hard_link"]]
expect_equal(test_dataset_hl$obj_info(), test_dataset$obj_info())
file.h5[["test_type"]] <- h5types$H5T_NATIVE_INT64
expect_true(h5types$H5T_NATIVE_INT64$equal(file.h5[["test_type"]]))
file.h5[["test_dataset2"]] <- robj
expect_equal(file.h5[["test_dataset2"]]$read(), robj)
file.h5$close_all()
file.remove(test_file)
})
index_logical <- c(TRUE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE)
index_regular <- c(3, 4, 5, 6)
index_regular2 <- c(3, 5, 7, 9)
index_positive <- c(1, 5, 6, 10, 15)
index_ident <- c(1, 3, 3, 6)
index_ident2 <- c(1, 3, 5, 1)
index_decreasing <- c(5, 4, 2, 1)
index_negative_all <- -index_regular
index_negative_some <- c(1, 3, -2, 5, 6)
index_large <- c(1, 20)
index_empty <- list(quote(expr=))
example_indices <- list(index_logical,
index_regular,
index_regular2,
index_positive,
index_ident,
index_ident2,
index_decreasing,
index_negative_all,
index_large,
quote(expr=),
NULL)
test_that("args_regularity_evaluation to selection", {
a <- 4
example_calls <- list(call(":", a, 8),
call("seq_len", 6),
call("seq", from=4, to=9, by=2),
call("seq", from=4, length.out=4, by=1),
call(":", -2, 2),
expression(1:5 / 10 * 2))
check_for_func_res <- lapply(example_calls, hdf5r:::check_arg_for_hyperslab_func, envir=sys.frame())
expect_equal(check_for_func_res, list(c(4, 1, 1, 5), c(1, 1, 1, 6), c(4, 3, 2, 1), c(4, 1, 1, 4), c(NA, NA, NA, NA), c(NA, NA, NA, NA)))
ds_dims <- rep(10, length(example_indices))
example_indices_regularity <- hdf5r:::args_regularity_evaluation(example_indices, ds_dims, envir=sys.frame())
NA_hyperslab_row <- c(NA, NA, NA, NA)
example_indices_intended_output <- list(
args_in=example_indices,
args_point=list(c(1, 3, 4, 6, 10), NULL, NULL, index_positive, unique(index_ident), NULL, sort(index_decreasing),
seq_len(10)[index_negative_all], NULL, NULL, numeric(0)),
is_hyperslab=c(FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE, FALSE),
hyperslab=matrix(c(NA_hyperslab_row, c(3, 1, 1, 4), c(3, 4, 2, 1), NA_hyperslab_row, NA_hyperslab_row, c(1, 3, 2, 1),
NA_hyperslab_row, NA_hyperslab_row, c(1, 2, 19, 1), c(1, 1, 1, 10), NA_hyperslab_row),
byrow=TRUE, ncol=4, dimnames=list(NULL, c("start", "count", "stride", "block"))),
result_dims_pre_shuffle=c(5, 4, 4, 5, 3, 3, 4, 6, 2, 10, 0),
result_dims_post_shuffle=c(5, 4, 4, 5, 4, 4, 4, 6, 2, 10, 0),
max_dims=c(10, 6, 9, 15, 6, 5, 5, 10, 20, 10, -Inf),
needs_reshuffle=c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE),
reshuffle=list(NULL, NULL, NULL, NULL, c(1, 2, 2, 3), c(1, 2, 3, 1), c(4, 3, 2, 1), NULL, NULL, NULL, NULL)
)
expect_equal(example_indices_regularity, example_indices_intended_output)
expect_error(hdf5r:::args_regularity_evaluation(list(index_negative_some), ds_dims=10, envir=sys.frame()))
only_points_regularity <- hdf5r:::args_regularity_evaluation(list(index_positive, index_positive), ds_dims=c(10, 10), envir=sys.frame())
mixed_regularity <- hdf5r:::args_regularity_evaluation(list(index_regular, index_positive), ds_dims=c(10, 10), envir=sys.frame())
only_hyperslab_regularity <- hdf5r:::args_regularity_evaluation(list(index_regular, index_regular2, quote(expr=)),
ds_dims=c(10, 10, 10), envir=sys.frame())
only_points_selection <- hdf5r:::regularity_eval_to_selection(only_points_regularity)
mixed_selection <- hdf5r:::regularity_eval_to_selection(mixed_regularity)
only_hyperslab_selection <- hdf5r:::regularity_eval_to_selection(only_hyperslab_regularity)
expect_equal(only_points_selection, structure(matrix(c(rep(index_positive, times=5), rep(index_positive, each=5)), ncol=2), class="point_selection"))
mixed_selection_array <- array(0, dim=c(2, 5, 4))
mixed_selection_array[1,,] <- rep(c(3, 1, 1, 4), each=5)
mixed_selection_array[2,,] <- 1
mixed_selection_array[2,,1] <- index_positive
expect_equal(mixed_selection, structure(mixed_selection_array, class="hyperslab_selection"))
only_hyperslab_array <- array(0, dim=c(3, 1, 4))
only_hyperslab_array[1,,] <- c(3, 1, 1, 4)
only_hyperslab_array[2,,] <- c(3, 4, 2, 1)
only_hyperslab_array[3,,] <- c(1, 1, 1, 10)
expect_equal(only_hyperslab_selection, structure(only_hyperslab_array, class="hyperslab_selection"))
})
test_that("subset_h5.H5S", {
h5s_obj <- H5S$new(type="simple", dims=c(15, 15, 20), maxdims=c(15, 15, 20))
subset_h5.H5S(h5s_obj, seq_len(3), seq(2,4,by=3), 5:9)
expect_equal(h5s_obj$get_select_type(), h5const$H5S_SEL_HYPERSLABS)
expect_equal(h5s_obj$get_select_hyper_blocklist(), matrix(c(1,3,2,2,5,9), nrow=2, dimnames=list(c("block_1_start", "block_1_end"), NULL)))
subset_h5.H5S(h5s_obj, seq_len(3), seq(2,4,by=3), c(1,2,4))
expect_equal(h5s_obj$get_select_type(), h5const$H5S_SEL_POINTS)
expect_error(h5s_obj[16, 1, 1], "The following coordinates are outside the dataset dimensions: 1")
foo <- h5s_obj[1:3, NULL, c(1,2,4)]
expect_equal(h5s_obj$get_select_type(), h5const$H5S_SEL_NONE)
foo <- h5s_obj[,,]
subset_h5.H5S(h5s_obj, seq_len(3), NULL, c(1,2,4))
expect_equal(h5s_obj$get_select_type(), h5const$H5S_SEL_NONE)
h5s_logical <- subset_h5.H5S(h5s_obj, index_logical, , )
expect_equal(h5s_logical$get_select_type(), h5const$H5S_SEL_HYPERSLABS)
h5s_regular <- subset_h5.H5S(h5s_obj, index_regular, ,)
expect_equal(h5s_regular$get_select_type(), h5const$H5S_SEL_HYPERSLABS)
h5s_positive <- subset_h5.H5S(h5s_obj, index_positive, ,)
expect_equal(h5s_positive$get_select_type(), h5const$H5S_SEL_HYPERSLABS)
h5s_ident <- subset_h5.H5S(h5s_obj, index_ident, ,)
expect_equal(h5s_ident$get_select_type(), h5const$H5S_SEL_HYPERSLABS)
h5s_ident2 <- subset_h5.H5S(h5s_obj, index_ident2, ,)
expect_equal(h5s_ident$get_select_type(), h5const$H5S_SEL_HYPERSLABS)
h5s_decreasing <- subset_h5.H5S(h5s_obj, index_decreasing, ,)
expect_equal(h5s_decreasing$get_select_type(), h5const$H5S_SEL_HYPERSLABS)
h5s_negative_all <- subset_h5.H5S(h5s_obj, index_negative_all, ,)
expect_equal(h5s_negative_all$get_select_type(), h5const$H5S_SEL_HYPERSLABS)
expect_error(subset_h5.H5S(h5s_obj, index_negative_some, ,), regexp=".*not all subscripts are either positive or negative")
expect_error(subset_h5.H5S(h5s_obj, index_large, ,), "The following coordinates are outside the dataset dimensions:.*")
h5s_logical_double <- subset_h5.H5S(h5s_obj, index_logical, index_logical, )
expect_equal(h5s_logical_double$get_select_type(), h5const$H5S_SEL_HYPERSLABS)
h5s_logical_triple <- subset_h5.H5S(h5s_obj, index_logical, index_logical, index_logical)
expect_equal(h5s_logical_double$get_select_type(), h5const$H5S_SEL_POINTS)
h5s_logical_regular <- subset_h5.H5S(h5s_obj, index_logical, , index_regular)
expect_equal(h5s_logical_regular$get_select_type(), h5const$H5S_SEL_HYPERSLABS)
subset_h5.H5S(h5s_obj, seq_len(3), NULL, c(1,2,4))
expect_equal(h5s_obj$get_select_type(), h5const$H5S_SEL_NONE)
})
test_that("subset_h5.H5D", {
test_file <- tempfile(fileext=".h5")
file.h5 <- H5File$new(test_file, mode="w")
robj <- matrix(as.integer(1:100), ncol=10)
file.h5[["test"]] <- robj
test <- file.h5[["test"]]
indices_test <- list(
1:10,
10:1,
c(1,2,3,4),
c(4, 3, 2, 1),
c(1, 3, 5, 7),
c(7, 5, 3, 1),
c(1, 2, 5, 9),
c(9, 5, 2, 1),
c(1:10, 1:10),
c(1, 2, 2, 2, 3, 4, 5),
c(-1, -2, -3),
c(-1, -3, -4))
for(ind1 in indices_test) {
for(ind2 in indices_test) {
expect_equal(test[ind1, ind2], robj[ind1, ind2])
}
}
expect_equal(test[1:3, 2:4], robj[1:3, 2:4])
expect_equal(test[c(1,3,4),], robj[c(1,3,4),])
test[1:3, 2:4] <- 1:9
expect_equal(test[1:3, 2:4], matrix(1:9, ncol=3))
test[11:15, ] <- 1:50
expect_equal(as.vector(test[11:15,]), 1:50)
get_1 <- function(i, ds) {
return(ds[i,])
}
expect_equal(get_1(11, test), c(1, 6, 11, 16, 21, 26, 31, 36, 41, 46))
test2 <- file.h5$create_dataset("test_array", dtype=h5types$H5T_NATIVE_INT, space=H5S$new("simple", dims=c(10,10,100)),
chunk_dims=c(10,10,1))
pos_list <- list(1)
test2[,,pos_list[[1]]] <- 1:100
expect_equal(test2[,,1], matrix(1:100, ncol=10))
expect_error(test2[11, ,], "The following coordinates are outside the dataset dimensions: 1")
expect_equal(test[, NULL], matrix(numeric(0), ncol=0, nrow=15))
robj_onedim = 1:10
file.h5[["onedim"]] <- robj_onedim
test_onedim <- file.h5[["onedim"]]
expect_equal(test_onedim[1:5], robj_onedim[1:5])
expect_equal(test_onedim[c(1, 3)], robj_onedim[c(1, 3)])
expect_equal(test_onedim[c(2, 4)], robj_onedim[c(2, 4)])
for(ind1 in indices_test) {
expect_equal(test_onedim[ind1], robj_onedim[ind1])
}
file.h5$close_all()
file.remove(test_file)
})
test_that("hyperslab_to_points", {
expect_equal(hdf5r:::hyperslab_to_points(c(2,2,2,1)), c(2,4))
})
test_that("attributes", {
test_file <- tempfile(fileext=".h5")
file.h5 <- H5File$new(test_file, mode="w")
robj1 <- matrix(as.integer(1:10), ncol=2)
robj2 <- paste("Test", 1:10)
h5attr(file.h5, "integer") <- robj1
h5attr(file.h5, "character") <- robj2
expect_equal(sort(h5attr_names(file.h5)), sort(c("integer", "character")))
all_attr <- h5attributes(file.h5)
expect_equal(all_attr$integer, robj1)
expect_equal(all_attr$character, robj2)
expect_equal(h5attr(file.h5, "integer"), robj1)
expect_equal(h5attr(file.h5, "character"), robj2)
h5attr(file.h5, "integer") <- robj2
expect_equal(h5attr(file.h5, "integer"), robj2)
file.h5$close_all()
file.remove(test_file)
})
test_that("Subsetting dimensions, drop and write", {
test_file <- tempfile(fileext=".h5")
file.h5 <- H5File$new(test_file, mode="w")
ex_array <- array(1:60, dim=c(3,4,5))
file.h5[["ex_array"]] <- ex_array
ex_arr_ds <- file.h5[["ex_array"]]
expect_equal(ex_arr_ds[2,,], ex_array[2,,])
expect_equal(ex_arr_ds[,2,], ex_array[,2,])
expect_equal(ex_arr_ds[,,2], ex_array[,,2])
expect_equal(ex_arr_ds[2,,, drop=FALSE], ex_array[2,,, drop=FALSE])
expect_equal(ex_arr_ds[,2,, drop=FALSE], ex_array[,2,, drop=FALSE])
expect_equal(ex_arr_ds[,,2, drop=FALSE], ex_array[,,2, drop=FALSE])
ex_arr_ds[,,] <- 1
ex_array[,,] <- 1
expect_equal(ex_array[,,], ex_arr_ds[,,])
ex_arr_ds[,,] <- c(1,2,3)
ex_array[,,] <- c(1,2,3)
expect_equal(ex_array[,,], ex_arr_ds[,,])
ex_array2 <- array(as.numeric(seq_len(15 * 15* 20)), dim=c(15, 15, 20))
file.h5[["ex_array2"]] <- ex_array2
ex_array2_ds <- file.h5[["ex_array2"]]
copy_change_test_reset_array <- function(hdf5_ds, r_ds, index) {
expect_equal(hdf5_ds[index,,], r_ds[index,,])
r_ds_changed <- r_ds
replace_vals <- runif(length(r_ds[index,,]))
r_ds_changed[index, ,] <- replace_vals
hdf5_ds[index, ,] <- replace_vals
hdf5_ds_read <- hdf5_ds[index, ,]
hdf5_ds[, ,] <- r_ds
expect_equal(hdf5_ds_read, r_ds_changed[index, ,])
return(invisible(NULL))
}
copy_change_test_reset_array(ex_array2_ds, ex_array2, index_logical)
copy_change_test_reset_array(ex_array2_ds, ex_array2, index_regular)
copy_change_test_reset_array(ex_array2_ds, ex_array2, index_regular2)
copy_change_test_reset_array(ex_array2_ds, ex_array2, index_positive)
copy_change_test_reset_array(ex_array2_ds, ex_array2, index_ident)
copy_change_test_reset_array(ex_array2_ds, ex_array2, index_ident2)
copy_change_test_reset_array(ex_array2_ds, ex_array2, index_decreasing)
copy_change_test_reset_array(ex_array2_ds, ex_array2, index_negative_all)
expect_equal(ex_array2_ds[,,], ex_array2[,,])
expect_error(ex_array2_ds[index_large, ], "Number of arguments not equal to number of dimensions: 2 vs. 3")
expect_error(ex_array2_ds[index_negative_some, ,], "In index 1 not all subscripts are either positive or negative")
expect_error(ex_array2_ds[index_large,, ], "The following coordinates are outside the dataset dimensions:.*")
expect_equal(ex_array2_ds[index_logical, index_logical,], ex_array2[index_logical, index_logical,])
expect_equal(ex_array2_ds[index_logical, index_logical, index_logical], ex_array2[index_logical, index_logical, index_logical])
expect_equal(ex_array2_ds[index_logical, , index_regular], ex_array2[index_logical, , index_regular])
ex_cpd <- data.frame(a=LETTERS[1:15], b=1:15, stringsAsFactors = FALSE)
file.h5[["ex_cpd"]] <- ex_cpd
ex_cpd_ds <- file.h5[["ex_cpd"]]
copy_change_test_reset_cpd <- function(hdf5_cpd, r_cpd, index) {
hdf5_cpd[] <- r_cpd
hdf5_cpd_read <- hdf5_cpd[index]
rownames(hdf5_cpd_read) <- NULL
r_cpd_read <- r_cpd[index,]
rownames(r_cpd_read) <- NULL
expect_equal(hdf5_cpd_read, r_cpd_read)
r_cpd_changed <- r_cpd
replace_length <- nrow(r_cpd[index,])
replace_vals <- data.frame(a=sample(LETTERS, size=replace_length), b=sample(1:50, size=replace_length), stringsAsFactors = FALSE)
r_cpd_changed[index,] <- replace_vals
hdf5_cpd[index] <- replace_vals
hdf5_cpd_read <- hdf5_cpd[]
hdf5_cpd[] <- r_cpd
expect_equal(hdf5_cpd_read, r_cpd_changed[,])
return(invisible(NULL))
}
copy_change_test_reset_cpd(ex_cpd_ds, ex_cpd, index_logical)
copy_change_test_reset_cpd(ex_cpd_ds, ex_cpd, index_regular)
copy_change_test_reset_cpd(ex_cpd_ds, ex_cpd, index_regular2)
copy_change_test_reset_cpd(ex_cpd_ds, ex_cpd, index_positive)
copy_change_test_reset_cpd(ex_cpd_ds, ex_cpd, index_ident)
copy_change_test_reset_cpd(ex_cpd_ds, ex_cpd, index_decreasing)
copy_change_test_reset_cpd(ex_cpd_ds, ex_cpd, index_negative_all)
expect_error(ex_cpd_ds[index_large, ], "Number of arguments not equal to number of dimensions: 2 vs. 1")
expect_error(ex_cpd_ds[index_negative_some], "In index 1 not all subscripts are either positive or negative")
expect_error(ex_cpd_ds[index_large], "The following coordinates are outside the dataset dimensions:.*")
h5s_finite_maxdims <- H5S$new(type="simple", dims=c(5, 10, 15), maxdims=c(10, 15, 20))
h5d_finite_maxdims <- file.h5$create_dataset(name="ds_finite_maxdims", dtype=h5types$H5T_NATIVE_DOUBLE, space=h5s_finite_maxdims)
h5d_finite_maxdims[10, ,1:10 ] <- 1:100
expect_equal(h5d_finite_maxdims$dims, c(10, 10, 15))
expect_error({h5d_finite_maxdims[11, , ] <- 151:300}, regexp="The following coordinates are larger than the largest possible dataset dimensions \\(maxdims\\): 1")
file.h5$close_all()
file.remove(test_file)
})
test_that("Check if index is ok before expand", {
test_file <- tempfile(fileext=".h5")
file.h5 <- H5File$new(test_file, mode="w")
ex_dset <- array(81, dim=c(9,9))
file.h5[["dset"]] <- ex_dset
dset <- file.h5[["dset"]]
expect_error({dset[10:11, 9] <- matrix(rep(0, 2*9), nrow = 2)})
expect_equal(dset$dims, c(9,9))
file.h5$close_all()
file.remove(test_file)
})
|
print_anova <- function(
x
, intercept = FALSE
, observed = NULL
, es = "ges"
, mse = getOption("papaja.mse")
, in_paren = FALSE
) {
validate(x, check_class = "data.frame", check_NA = FALSE)
validate(x, check_class = "apa_variance_table", check_NA = FALSE)
validate(intercept, check_class = "logical", check_length = 1)
if(!is.null(observed)) validate(observed, check_class = "character")
if(!is.null(es)) {
validate(es, check_class = "character")
es <- sort(es, decreasing = TRUE)
}
validate(in_paren, check_class = "logical", check_length = 1)
rownames(x) <- sanitize_terms(x$term)
x <- add_effect_sizes(
x = x
, es = es
, observed = observed
, mse = mse
, intercept = intercept
)
if(!intercept) x <- x[x$term != "(Intercept)", ]
x$statistic <- printnum(x$statistic, digits = 2)
x$p.value <- printp(x$p.value)
x$df <- print_df(x$df)
x$df_res <- print_df(x$df_res)
for(i in es) {x[[i]] <- printnum(x[[i]], digits = 3, gt1 = FALSE)}
if(mse) x$mse <- printnum(x$mse, digits = 2)
cols <- intersect(
c("term", "statistic","df", "df_res", "mse", "p.value", es)
, colnames(x)
)
anova_table <- data.frame(x[, cols], row.names = NULL)
anova_table[["term"]] <- prettify_terms(anova_table[["term"]])
correction_type <- attr(x, "correction")
statistic <- attr(x, "statistic")
if(is.null(statistic)) statistic <- "F"
if(is.null(anova_table$df_res)) statistic <- "chisq"
names(es) <- es
renamers <- c(
term = "Effect"
, statistic = statistic
, df = if(is.null(anova_table$df_res)){ "df" } else { "df1" }
, df_res = "df2"
, mse = "MSE"
, p.value = "p"
, es
)
colnames(anova_table) <- renamers[colnames(anova_table)]
class(anova_table) <- "data.frame"
if(!is.null(correction_type) && correction_type != "none") {
variable_label(anova_table) <- c(
"Effect" = "Effect"
, "F" = "$F$"
, "chisq" = "$\\Chi^2$"
, "df" = "$\\mathit{df}"
, "df1" = paste0("$\\mathit{df}_1^{", correction_type, "}$")
, "df2" = paste0("$\\mathit{df}_2^{", correction_type, "}$")
, "p" = "$p$"
, "pes" = "$\\hat{\\eta}^2_p$"
, "ges" = "$\\hat{\\eta}^2_G$"
, "es" = "$\\hat{\\eta}^2$"
, "MSE" = "$\\mathit{MSE}$"
)[colnames(anova_table)]
} else {
variable_label(anova_table) <- c(
"Effect" = "Effect"
, "F" = "$F$"
, "chisq" = "$\\Chi^2$"
, "df" = "$\\mathit{df}"
, "df1" = "$\\mathit{df}_1$"
, "df2" = "$\\mathit{df}_2$"
, "p" = "$p$"
, "pes" = "$\\hat{\\eta}^2_p$"
, "ges" = "$\\hat{\\eta}^2_G$"
, "es" = "$\\hat{\\eta}^2$"
, "MSE" = "$\\mathit{MSE}$"
)[colnames(anova_table)]
}
apa_res <- apa_print_container()
apa_res$statistic <- paste0(
c("F" = "$F", "chisq" = "$\\Chi^2")[statistic]
, if(!is.null(x$df)) { "(" } else { NULL }
, x$df
, if(!is.null(x$df_res)) { ", " } else { NULL }
, x$df_res
, if(!is.null(x$df)) { ")" } else { NULL }
, " = "
, x$statistic
, if(mse) { "$, $\\mathit{MSE} = " } else { NULL }
, if(mse) { x$mse } else { NULL }
, "$, $p "
, add_equals(x$p.value)
, "$"
)
if(in_paren) apa_res$statistic <- in_paren(apa_res$statistic)
names(apa_res$statistic) <- rownames(x)
apa_res$statistic <- as.vector(apa_res$statistic, mode = "list")
if(!is.null(es)) {
apa_res$estimate <- apply(x, 1, function(y) {
apa_est <- c()
if("pes" %in% es) {
apa_est <- c(apa_est, paste0("$\\hat{\\eta}^2_p = ", y["pes"], "$"))
}
if("ges" %in% es) {
apa_est <- c(apa_est, paste0("$\\hat{\\eta}^2_G = ", y["ges"], "$"))
}
if("es" %in% es) {
apa_est <- c(apa_est, paste0("$\\hat{\\eta}^2 = ", y["es"], "$"))
}
apa_est <- paste(apa_est, collapse = ", ")
})
apa_res$full_result <- paste(apa_res$statistic, apa_res$estimate, sep = ", ")
names(apa_res$full_result) <- names(apa_res$estimate)
apa_res[] <- lapply(apa_res, as.list)
}
apa_res$table <- sort_terms(as.data.frame(anova_table), "Effect")
class(apa_res$table) <- c("apa_results_table", "data.frame")
apa_res
}
|
expected <- eval(parse(text="structure(c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, FALSE), .Dim = c(5L, 2L), .Dimnames = list(NULL, c(\"VAR1\", \"VAR3\")))"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE), .Dim = c(5L, 2L), .Dimnames = list(NULL, c(\"VAR1\", \"VAR3\"))))"));
do.call(`!`, argv);
}, o=expected);
|
simple_table <- function(data, colnames = TRUE, rownames = FALSE) {
if (!is.data.frame(data)) {
stop("simple_table: `data` must be a data.frame", call. = FALSE)
}
if (ncol(data) == 0) {
return(NULL)
}
header <- NULL
if (isTRUE(colnames) && !is.null(colnames(data))) {
header <- lapply(colnames(data), html$th)
if (isTRUE(rownames)) {
header <- c(list(html$th("")), header)
}
header <- html$tr(header)
}
rows <- lapply(seq(nrow(data)), function(rownum) {
row <- lapply(as.character(data[rownum, ]), html$td)
if (isTRUE(rownames)) {
row <- c(list(html$td(rownames(data[rownum, ]))), row)
}
html$tr(row)
})
html$table(c(list(header), rows))
}
|
setClass(Class = "MxFitFunctionRow",
representation = representation(
rowAlgebra = "MxCharOrNumber",
rowResults = "MxCharOrNumber",
units = "character",
filteredDataRow = "MxCharOrNumber",
existenceVector = "MxCharOrNumber",
reduceAlgebra = "MxCharOrNumber",
data = "MxCharOrNumber",
dims = "character",
dataColumns = "numeric",
dataRowDeps = "integer"),
contains = "MxBaseFitFunction")
setMethod("initialize", signature("MxFitFunctionRow"),
function(.Object, ...) {
.Object <- callNextMethod()
.Object@rowAlgebra <- ..1
.Object@rowResults <- ..2
.Object@units <- ..3
.Object@filteredDataRow <- ..4
.Object@existenceVector <- ..5
.Object@reduceAlgebra <- ..6
.Object@dims <- ..7
.Object@data <- as.integer(NA)
.Object@expectation <- as.integer(NA)
.Object
})
setMethod("genericFitNewEntities", signature("MxFitFunctionRow"),
function(.Object) {
if (is.na(.Object@rowResults) && is.na(.Object@filteredDataRow) && is.na(.Object@existenceVector)) {
return(NULL)
} else {
a <- .Object@rowResults
b <- .Object@filteredDataRow
c <- .Object@existenceVector
retval <- c(a, b, c)
retval <- as.character(na.omit(retval))
return(retval)
}
}
)
setMethod("genericFitDependencies", signature("MxFitFunctionRow"),
function(.Object, flatModel, dependencies) {
dependencies <- callNextMethod()
reduceAlgebra <- .Object@reduceAlgebra
rowAlgebra <- .Object@rowAlgebra
rowResults <- .Object@rowResults
dependencies <- imxAddDependency(reduceAlgebra, .Object@name, dependencies)
dependencies <- imxAddDependency(rowAlgebra, rowResults, dependencies)
return(dependencies)
})
setMethod("qualifyNames", signature("MxFitFunctionRow"),
function(.Object, modelname, namespace) {
.Object <- callNextMethod()
.Object@rowAlgebra <- imxConvertIdentifier(.Object@rowAlgebra,
modelname, namespace)
.Object@rowResults <- imxConvertIdentifier(.Object@rowResults,
modelname, namespace)
.Object@filteredDataRow <- imxConvertIdentifier(.Object@filteredDataRow,
modelname, namespace)
.Object@existenceVector <- imxConvertIdentifier(.Object@existenceVector,
modelname, namespace)
.Object@reduceAlgebra <- imxConvertIdentifier(.Object@reduceAlgebra,
modelname, namespace)
.Object@data <- imxConvertIdentifier(.Object@data,
modelname, namespace)
return(.Object)
})
setMethod("genericFitRename", signature("MxFitFunctionRow"),
function(.Object, oldname, newname) {
.Object@rowAlgebra <- renameReference(.Object@rowAlgebra, oldname, newname)
.Object@reduceAlgebra <- renameReference(.Object@reduceAlgebra, oldname, newname)
.Object@data <- renameReference(.Object@data, oldname, newname)
return(.Object)
})
setMethod("genericFitFunConvert", signature("MxFitFunctionRow"),
function(.Object, flatModel, model, labelsData, dependencies) {
.Object <- callNextMethod()
modelname <- imxReverseIdentifier(model, .Object@name)[[1]]
name <- .Object@name
dataName <- .Object@data
if(is.na(dataName)) {
msg <- paste("The MxFitFunctionRow fit function",
"does not have a dataset associated with it in model",
omxQuotes(modelname))
stop(msg, call. = FALSE)
}
mxDataObject <- flatModel@datasets[[dataName]]
if (mxDataObject@type != 'raw') {
msg <- paste("The dataset associated with the MxFitFunctionRow fit function",
"in model", omxQuotes(modelname), "is not raw data.")
stop(msg, call. = FALSE)
}
dataRowDeps <- union(dependencies[[.Object@filteredDataRow]], dependencies[[.Object@existenceVector]])
dataRowDeps <- sapply(dataRowDeps, doLocateIndex, flatModel, flatModel@name, USE.NAMES=FALSE)
dataRowDeps <- as.integer(dataRowDeps)
.Object@rowAlgebra <- imxLocateIndex(flatModel, .Object@rowAlgebra, name)
.Object@rowResults <- imxLocateIndex(flatModel, .Object@rowResults, name)
.Object@filteredDataRow <- imxLocateIndex(flatModel, .Object@filteredDataRow, name)
.Object@existenceVector <- imxLocateIndex(flatModel, .Object@existenceVector, name)
.Object@reduceAlgebra <- imxLocateIndex(flatModel, .Object@reduceAlgebra, name)
.Object@data <- imxLocateIndex(flatModel, dataName, name)
.Object@dataColumns <- generateRowDataColumns(flatModel, .Object@dims, dataName)
.Object@dataRowDeps <- dataRowDeps
if (length(mxDataObject@observed) == 0) {
.Object@data <- as.integer(NA)
}
return(.Object)
})
generateRowDataColumns <- function(flatModel, expectedNames, dataName) {
retval <- numeric(length(expectedNames))
dataColumnNames <- dimnames(flatModel@datasets[[dataName]]@observed)[[2]]
for(i in 1:length(expectedNames)) {
targetName <- expectedNames[i]
index <- match(targetName, dataColumnNames)
if(is.na(index)) {
msg <- paste("The column name", omxQuotes(targetName),
"in the expected covariance matrix",
"of the MxFitFunctionRow fit function in model",
omxQuotes(flatModel@name),
"cannot be found in the column names of the data.")
stop(msg, call. = FALSE)
}
retval[i] <- index - 1L
}
return(retval)
}
setMethod("genericFitAddEntities", "MxFitFunctionRow",
function(.Object, job, flatJob, labelsData) {
name <- .Object@name
modelname <- job@name
rowAlgebraName <- .Object@rowAlgebra
rowResultsName <- .Object@rowResults
filteredDataRowName <- .Object@filteredDataRow
existenceVectorName <- .Object@existenceVector
reduceAlgebraName <- .Object@reduceAlgebra
dimnames <- .Object@dims
[email protected] <- TRUE
filteredDataRow <- flatJob[[filteredDataRowName]]
if (!is.null(filteredDataRow)) {
msg <- paste("The filteredDataRow cannot have name",
omxQuotes(filteredDataRowName),
"because this entity already exists in the model")
stop(msg, call. = FALSE)
}
filteredDataRow <- mxMatrix('Full', nrow = 1, ncol = length(dimnames))
[email protected] <- FALSE
job[[filteredDataRowName]] <- filteredDataRow
flatJob[[filteredDataRowName]] <- filteredDataRow
if (!is.na(existenceVectorName)) {
existenceVector <- job[[existenceVectorName]]
if (!is.null(existenceVector)) {
msg <- paste("The existenceVector cannot have name",
omxQuotes(existenceVectorName),
"because this entity already exists in the model")
stop(msg, call. = FALSE)
}
existenceVector <- mxMatrix('Full', nrow = 1, ncol = length(dimnames), values = 1)
[email protected] <- FALSE
job[[existenceVectorName]] <- existenceVector
flatJob[[existenceVectorName]] <- existenceVector
}
rowAlgebra <- job[[rowAlgebraName]]
if (is.null(rowAlgebra)) {
msg <- paste("The rowAlgebra with name",
omxQuotes(rowAlgebraName),
"is not defined in the model")
stop(msg, call. = FALSE)
}
tuple <- evaluateMxObject(rowAlgebraName, flatJob, labelsData, new.env(parent = emptyenv()))
result <- tuple[[1]]
if (nrow(result) != 1) {
msg <- paste("The rowAlgebra with name",
omxQuotes(rowAlgebraName),
"does not evaluate to a row vector")
stop(msg, call. = FALSE)
}
if (is.na(.Object@data)) {
msg <- paste("The MxFitFunctionRow fit function",
"does not have a dataset associated with it in model",
omxQuotes(modelname))
stop(msg, call.=FALSE)
}
mxDataObject <- flatJob@datasets[[.Object@data]]
rows <- nrow(mxDataObject@observed)
cols <- ncol(result)
rowResults <- job[[rowResultsName]]
if (!is.null(rowResults)) {
msg <- paste("The rowResults cannot have name",
omxQuotes(rowResultsName),
"because this entity already exists in the model")
stop(msg, call. = FALSE)
}
rowResults <- mxMatrix('Full', nrow = rows, ncol = cols)
[email protected] <- FALSE
job[[rowResultsName]] <- rowResults
reduceAlgebra <- job[[reduceAlgebraName]]
if (is.null(reduceAlgebra)) {
msg <- paste("The reduceAlgebra with name",
omxQuotes(reduceAlgebraName),
"is not defined in the model")
stop(msg, call. = FALSE)
}
return(job)
}
)
setMethod("genericFitInitialMatrix", "MxFitFunctionRow",
function(.Object, flatModel) {
reduceAlgebraName <- .Object@reduceAlgebra
labelsData <- imxGenerateLabels(flatModel)
tuple <- evaluateMxObject(reduceAlgebraName, flatModel, labelsData, new.env(parent = emptyenv()))
result <- tuple[[1]]
return(result)
}
)
checkStringArgument <- function(arg, name) {
if (single.na(arg)) {
arg <- as.character(NA)
} else if (length(unlist(strsplit(arg, imxSeparatorChar, fixed = TRUE))) > 1) {
stop(paste("the", omxQuotes(name), "argument cannot contain the",
omxQuotes(imxSeparatorChar),
"character"))
}
if (!(is.vector(arg) &&
(typeof(arg) == 'character') &&
(length(arg) == 1))) {
stop("the", omxQuotes(name), "argument is not a string")
}
return(arg)
}
mxFitFunctionRow <- function(rowAlgebra, reduceAlgebra, dimnames, rowResults = "rowResults",
filteredDataRow = "filteredDataRow", existenceVector = "existenceVector", units="-2lnL") {
if (missing(rowAlgebra) || typeof(rowAlgebra) != "character") {
stop("the 'rowAlgebra' argument is not a string (the name of the row-by-row algebra)")
}
if (missing(reduceAlgebra) || typeof(reduceAlgebra) != "character") {
stop("the 'reduceAlgebra' argument is not a string (the name of the reduction algebra)")
}
if (missing(dimnames) || typeof(dimnames) != "character") {
stop("the 'dimnames' argument is not a string (the column names from the data set)")
}
if (any(is.na(dimnames))) {
stop("NA values are not allowed for 'dimnames' vector")
}
rowResults <- checkStringArgument(rowResults, "rowResults")
filteredDataRow <- checkStringArgument(filteredDataRow, "filteredDataRow")
existenceVector <- checkStringArgument(existenceVector, "existenceVector")
return(new("MxFitFunctionRow", rowAlgebra, rowResults, units,
filteredDataRow, existenceVector, reduceAlgebra, dimnames))
}
printSlot <- function(object, slotName) {
val <- slot(object, slotName)
if (single.na(val)) {
msg <- paste('$', slotName, ' : NA \n', sep = '')
} else {
msg <- paste('$', slotName, ' : ',omxQuotes(val), '\n', sep = '')
}
cat(msg)
}
displayRowFitFunction <- function(fitfunction) {
cat("MxFitFunctionRow", omxQuotes(fitfunction@name), '\n')
cat("$rowAlgebra :", omxQuotes(fitfunction@rowAlgebra), '\n')
cat("$units: ", omxQuotes(fitfunction@units), '\n')
printSlot(fitfunction, "rowResults")
printSlot(fitfunction, "filteredDataRow")
printSlot(fitfunction, "existenceVector")
printSlot(fitfunction, "reduceAlgebra")
if (length(fitfunction@result) == 0) {
cat("$result: (not yet computed) ")
} else {
cat("$result:\n")
}
print(fitfunction@result)
invisible(fitfunction)
}
setMethod("print", "MxFitFunctionRow", function(x,...) {
displayRowFitFunction(x)
})
setMethod("show", "MxFitFunctionRow", function(object) {
displayRowFitFunction(object)
})
|
context("Parallelization works")
test_that("predict.caretEnsemble works in parallel", {
skip_on_cran()
X_reg <- model.matrix(~ ., iris[, -1])
X_reg_big <- do.call(rbind, lapply(1:100, function(x) X_reg))
Y_reg <- iris[, 1]
expect_warning(ens_reg <- caretEnsemble(caretList(X_reg, Y_reg, methodList=c("lm", "glm"))))
expect_warning(pred_reg <- predict(ens_reg, newdata = X_reg))
expect_warning(pred_reg2 <- predict(ens_reg, newdata = X_reg_big))
expect_equal(pred_reg, pred_reg2[1:length(pred_reg)])
expect_warning(pred_reg <- predict(ens_reg, newdata = X_reg, se = TRUE))
expect_warning(pred_reg2 <- predict(ens_reg, newdata = X_reg_big, se = TRUE))
row.names(pred_reg) <- NULL
row.names(pred_reg2) <- NULL
expect_equal(pred_reg, pred_reg2[1:nrow(pred_reg), ])
expect_warning(pred_reg <- predict(ens_reg, newdata = X_reg, se = TRUE, return_weights = TRUE))
expect_warning(
pred_reg2 <- predict(
ens_reg, newdata = X_reg_big, se = TRUE, return_weights = TRUE
)
)
row.names(pred_reg) <- NULL
row.names(pred_reg2) <- NULL
expect_equal(pred_reg$fit, pred_reg2$fit[1:length(pred_reg$fit)])
})
|
tpairs <-
function(dat, vars, contr, dep, wid, p.adjust.methods="none", paired=FALSE, ...){
dat$newfactor=apply(data.frame(dat[,vars]), 1, function(x){paste(x, collapse="_")})
dat$newfactor=factor(dat$newfactor)
dat=aggregate(dat[,dep], list(dat$newfactor, dat[,wid]), mean)
names(dat)=c("newfactor", "wid", dep)
contrast.names=NULL
p.values=NULL
t.values=NULL
df=NULL
mean.1=NULL
mean.2=NULL
if (contr[[1]][[1]]=="all"){
combs=combn(levels(dat$newfactor),2)
contr=list(NULL)
length(contr)=dim(combs)[2]
for (k in 1:dim(combs)[2]){
contr[[k]]=combs[,k]
}
}
for (i in 1:length(contr)){
res=t.test(dat[dat$newfactor%in%contr[[i]][[1]],dep],dat[dat$newfactor%in%contr[[i]][[2]],dep], paired=paired,...)
contrast.names=c(contrast.names, paste(contr[[i]][[1]], "vs", contr[[i]][[2]], sep=" "))
p.values=c(p.values, res$p.value)
t.values=c(t.values, res$statistic)
df=c(df, res$parameter)
mean.1=c(mean.1, mean(dat[dat$newfactor%in%contr[[i]][[1]],dep]))
mean.2=c(mean.2, mean(dat[dat$newfactor%in%contr[[i]][[2]],dep]))
}
p.values.corr=round(p.adjust(p.values, p.adjust.methods),3)
results=data.frame(contr=contrast.names, p.value=p.values.corr, t.value=t.values, df=df, mean.1=mean.1, mean.2)
attr(results, "p.corr")=p.adjust.methods
cat("p values adjustment = ", p.adjust.methods, "\n")
return(results)
}
|
library(vortexR)
library(vortexRdata)
context("test Ne_Nadults")
test_that("test Ne", {
pac.dir <- system.file("extdata", "pacioni", package="vortexRdata")
data(pac.clas.Ne, pac.clas)
suppressMessages(NeAll <- Ne(data=pac.clas, scenarios="all", gen=2.54, yr0=50,
yrt=120, save2disk=FALSE))
expect_equal(pac.clas.Ne , NeAll)
})
test_that("test Nadults", {
pac.dir <- system.file("extdata", "pacioni", package="vortexRdata")
data(pac.clas.Nadults, pac.yr)
suppressMessages(NadultAll <- Nadults(data=pac.yr[[2]], scenarios="all",
gen=2.54, yr0=50, yrt=120,
save2disk=FALSE))
expect_equal(pac.clas.Nadults, NadultAll)
})
|
atsmeans<-function(data,family=c("gaussian","binomial")[1],
method=c("Gest","IPW")[1],
digits=NULL,common=FALSE,conf=TRUE,
alpha=0.05,plot=FALSE,
title="Strategy values with confidence interval",color="forestgreen",
ylab="Strategy value",
xlab=NULL,xtext=NULL,pch=15,cex=2,lwd=3,
ylim=NULL,mar=NULL,cex.axis=1,line=NULL){
D<-as.data.frame(data)
FA<-family
Ma<-method
Com<-common
Al<-alpha
if (is.null(D$O1)) {Base<-0} else {Base<-1}
Nstage<-nstage(data=D)
Umat<-em(data=D,method=Ma)
Val<-Umat$value
Vmat<-evcmat(data=D,family=FA,
method=Ma,common=Com)
se<-sqrt(diag(Vmat))
CIs<-atsci(eumat=Umat,evmat=Vmat,alpha=Al)
if (conf==FALSE) {Umat<-data.frame(Umat,se)} else
if (conf==TRUE) {Umat<-data.frame(Umat,se,CIs)}
message(paste("$value: estimated strategy values
(with confidence intervals)",
"$vmat: variance-covariance matrix
of estimated strategy values \n",
sep="\n"))
if (Nstage==1 && Base==0) {
message("A strategy is
defined as a single-stage
decision making (d0) for A1 at baseline")
opar<-par(mar=c(4,4,4,3))
on.exit(par(opar))} else
if (Nstage==1 && Base==1) {
message(paste("A strategy is defined as a vector of
single-stage decision makings (d0,d1),",
"each of which corresponds to a
possible outcome of baseline evulation (O1). \n",
"d0 is the stage-1 decision making
for A1, conditioning on O1=0",
"d1 is the stage-1 decision making
for A1, conditioning on O1=1",
sep="\n"))
opar<-par(mar=c(5,4,4,3))
on.exit(par(opar))
} else
if (Nstage==2 && Base==0) {
message(paste("A strategy is defined as a vector of
decision makings (d0;d00,d01) for 2 stages \n",
"d0 is the stage-1 decision making for A1",
"d00 is the stage-2 decision making for A2,
conditioning on A1=d0 and O2=0",
"d01 is the stage-2 decision making for A2,
conditioning on A1=d0 and O2=0",
sep="\n"))
opar<-par(mar=c(6,4,4,3))
on.exit(par(opar))
} else
if (Nstage==2 && Base==1) {
message(paste("A strategy is defined as a vector of decision
makings (d0,d1;d00,d01,d10,d11) \n",
"d0 is the stage-1 decision making conditioning on O1=0",
"d1 is the stage-1 decision making conditioning on O1=1",
"d00 is the stage-2 decision making conditioning
on A1=d0 and O2=0",
"d01 is the stage-2 decision making conditioning
on A1=d0 and O2=0",
"d00 is the stage-2 decision making conditioning
on A1=d1 and O2=0",
"d01 is the stage-2 decision making conditioning
on A1=d1 and O2=0",
sep="\n"))
opar<-par(mar=c(7,4,4,3))
on.exit(par(opar))
} else
if (Nstage==3 && Base==0) {
message(paste("A strategy is defined
as a vector of decision makings
(d0;d00,d01;d000,d001,d010,d111) \n",
"d0 is the stage-1 decision making",
"d00 is the stage-2 decision making conditioning on
A1=d0 and O2=0",
"d01 is the stage-2 decision making conditioning on
A1=d0 and O2=0",
"d000 is the stage-3 decision making conditioning on
A1=d0, O2=0, A3=d00 and O3=0",
"d001 is the stage-3 decision making conditioning on
A1=d0, O2=0, A3=d00 and O3=1",
"d010 is the stage-3 decision making conditioning on
A1=d0, O2=1, A3=d01 and O3=0",
"d011 is the stage-3 decision making conditioning on
A1=d0, O2=1, A3=d01 and O3=1",
sep="\n"))
opar<-par(mar=c(8,4,4,3))
on.exit(par(opar))
}
if (plot==TRUE) {atsciplot(uimat=Umat,
nstage=Nstage,baseline=Base,title=title,
col=color,ylab=ylab,xlab=xlab,
pch=pch,cex=cex,lwd=lwd,xtext=xtext,
lim=ylim,mar=mar,cex.axis=cex.axis,
line=line)}
if (is.null(digits)) {
outcome<-list(value=Umat,vmat=Vmat)
attr(outcome,'class') <- c('myclass','list')
return(outcome)}
else {
outcome<-list(value=round(Umat,digits),
vmat=round(Vmat,digits))
attr(outcome,'class') <- c('myclass','list')
return(outcome)}
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(MicroMoB)
library(ggplot2)
library(data.table)
library(parallel)
patches <- 1
tmax <- 1e2
M <- 120
p <- 0.9
lambda <- M*(1-p)
nu <- 25
f <- 0.3
eggs <- nu * f * M
molt <- 0.1
surv <- 0.9
L <- lambda * ((1/molt) - 1) + eggs
K <- - (lambda * L) / (lambda - L*molt*surv)
mod <- make_MicroMoB(tmax = tmax, p = patches)
setup_aqua_BH(model = mod, stochastic = FALSE, molt = molt, surv = surv, K = K, L = L)
setup_mosquito_RM(model = mod, stochastic = FALSE, f = f, q = 0.9, eip = 10, p = p, psi = diag(1), nu = nu, M = M, Y = 0, Z = 0)
out_det <- matrix(data = NaN, nrow = tmax + 1, ncol = 3)
out_det[1L, ] <- c(mod$aqua$L, mod$aqua$A, mod$mosquito$M)
while (mod$global$tnow <= tmax) {
step_aqua(model = mod)
step_mosquitoes(model = mod)
out_det[mod$global$tnow + 1L, ] <- c(mod$aqua$L, mod$aqua$A, mod$mosquito$M)
mod$global$tnow <- mod$global$tnow + 1L
}
out_sto <- mclapply(X = 1:10, FUN = function(runid) {
mod <- make_MicroMoB(tmax = tmax, p = patches)
setup_aqua_BH(model = mod, stochastic = TRUE, molt = molt, surv = surv, K = K, L = L)
setup_mosquito_RM(model = mod, stochastic = TRUE, f = f, q = 0.9, eip = 10, p = p, psi = diag(1), nu = nu, M = M, Y = 0, Z = 0)
out_run <- matrix(data = NaN, nrow = tmax + 1, ncol = 3)
out_run[1L, ] <- c(mod$aqua$L, mod$aqua$A, mod$mosquito$M)
while (mod$global$tnow <= tmax) {
step_aqua(model = mod)
step_mosquitoes(model = mod)
out_run[mod$global$tnow + 1L, ] <- c(mod$aqua$L, mod$aqua$A, mod$mosquito$M)
mod$global$tnow <- mod$global$tnow + 1L
}
out_run <- as.data.frame(out_run)
out_run$run <- as.integer(runid)
return(out_run)
})
out_det <- as.data.table(out_det)
out_det[, "Day" := 0:tmax]
out_det <- melt(out_det, id.vars = "Day", variable.name = "Stage", value.name = "Count")
levels(out_det$Stage) <- c("L", "A", "M")
out_sto <- do.call(rbind, out_sto)
out_sto <- as.data.table(out_sto)
out_sto <- melt(out_sto, id.vars = "run", variable.name = "Stage", value.name = "Count")
out_sto[, "Day" := 0:tmax, by = c("run", "Stage")]
levels(out_sto$Stage) <- c("L", "A", "M")
ggplot(data = out_sto) +
geom_line(aes(x = Day, y = Count, color = Stage, group = run), alpha = 0.35) +
geom_line(data = out_det, mapping = aes(x = Day, y = Count, color = Stage)) +
facet_wrap(. ~ Stage, scales = "free")
|
par(mar = c(0, 0, 0, 0), mfrow = c(1, 2))
plot.new()
rect(0, 0, 1, 1, col = "lightgray", border = NA)
rect(.1, .1, .9, .9, col = "white")
rect(.1 + .08, .1 + .1, .9 - .04, .9 - .08,
col = "lightgray", lty = 2)
text(.5, .95, "外边界")
text(.5, .86, "图形区域")
text(.5, .5, "作图区域")
par(cex = .7)
text(.05, .55, "oma[2]")
text(.95, .5, "oma[4]")
text(.5, .05, "oma[1]")
text(.14, .45, "mar[2]")
text(.5, .15, "mar[1]")
par(cex = 1)
plot.new()
rect(0, 0, 1, 1, col = "lightgray", border = NA)
rect(.1, .1, .5, .9, col = "white")
rect(.5, .1, .9, .9, col = "white")
rect(.1 + .08, .1 + .1, .5 - .04, .9 - .08,
col = "lightgray", lty = 2)
text(.5, .95, "外边界")
text(.31, .7, "图 1")
text(.31, .5, "当前作图区域", cex = .7)
text(.72, .75, "图 2")
text(.5, .05, "oma[1]", cex = .7)
|
stackFromStore <- function(filepaths, dpID, site="all",
startdate=NA, enddate=NA,
pubdate=NA, timeIndex="all",
level="dp04", var=NA,
zipped=FALSE, package="basic",
load=TRUE, nCores=1) {
if(any(!file.exists(filepaths))) {
stop("Files not found in specified file paths.")
}
if(regexpr("DP[1-4]{1}[.][0-9]{5}[.]00[0-9]{1}",dpID)[1]!=1) {
stop(paste(dpID, "is not a properly formatted data product ID. The correct format is DP
}
if(substr(dpID, 5, 5) == "3" & dpID!="DP1.30012.001"){
stop("This is an AOP data product, files are not tabular and cannot be stacked.")
}
if(dpID == "DP1.10017.001" & package != 'basic'){
saveUnzippedFiles = TRUE
writeLines("Note: Digital hemispheric photos (in NEF format) cannot be stacked; only the CSV metadata files will be stacked.\n")
}
if(!is.na(startdate)) {
if(regexpr("[0-9]{4}-[0-9]{2}", startdate)!=1) {
stop("startdate and enddate must be either NA or valid dates in the form YYYY-MM")
}
}
if(!is.na(enddate)) {
if(regexpr("[0-9]{4}-[0-9]{2}", enddate)!=1) {
stop("startdate and enddate must be either NA or valid dates in the form YYYY-MM")
}
}
if(!is.na(pubdate)) {
if(regexpr("[0-9]{4}-[0-9]{2}-[0-9]{2}", pubdate)!=1) {
stop("pubdate must be either NA or a valid date in the form YYYY-MM-DD")
}
}
if(!package %in% c("basic","expanded")) {
stop("package must be either basic or expanded.")
}
if(length(filepaths)>1) {
if(dpID=="DP4.00200.001") {
if(load==FALSE) {
stop("Writing to local directory is not available for DP4.00200.001. Use load=TRUE and assign to a variable name.")
} else {
if(timeIndex=="all") {
avg <- NA
} else {
avg <- timeIndex
}
return(stackEddy(filepath=filepaths, level=level, avg=avg, var=var))
}
} else {
if(load==TRUE) {
savepath <- "envt"
} else {
savepath <- NA
}
return(stackByTable(filepaths, savepath=savepath, dpID=dpID, package=package))
}
}
if(length(filepaths)==1) {
files <- list.files(filepaths, full.names=T, recursive=T)
files <- files[grep(dpID, files)]
varFiles <- files[grep("[.]variables[.]", files)]
if(length(varFiles)==0 & dpID!="DP4.00200.001") {
stop("Variables file not found; required for stacking. Re-download data, or download additional data, to get variables file.")
}
if(zipped==T) {
files <- files[grep(".zip$", files)]
stop("Files must be unzipped to use this function. Zip file handling may be added in a future version.")
} else {
files <- files[grep(".zip$", files, invert=T)]
}
if(length(files)==0) {
stop("No files found meeting all input criteria.")
}
if(dpID=="DP4.00200.001") {
if(!identical(site, "all")) {
files <- files[grep(paste(site, collapse="|"), files)]
}
files <- files[grep(package, files)]
tabs1 <- "DP4.00200.001.nsae"
} else {
varDates <- regmatches(basename(varFiles),
regexpr("[0-9]{8}T[0-9]{6}Z", basename(varFiles)))
if(is.na(pubdate)) {
varFile <- varFiles[grep(max(varDates, na.rm=T), varFiles)][1]
} else {
pubdateP <- as.POSIXct(pubdate, format="%Y-%m-%d", tz="GMT")
varDatesP <- as.POSIXct(varDates, format="%Y%m%dT%H%M%SZ", tz="GMT")
if(length(which(varDatesP <= pubdateP))==0) {
stop(paste("No files published before pubdate ", pubdate, sep=""))
}
varInd <- which(varDatesP==max(varDatesP[which(varDatesP <= pubdateP)], na.rm=T))[1]
varFile <- varFiles[varInd]
}
v <- utils::read.csv(varFile, header=T, stringsAsFactors=F)
vTabs <- unique(v$table)
vTypes <- unlist(lapply(vTabs, function(x) {
vx <- v$downloadPkg[which(v$table==x)]
if(all(vx=="none")) {"none"} else {
vx <- vx[which(vx!="none")]
}
if(all(vx=="basic")) {"basic"} else {
if(all(vx=="expanded")) {"expanded"} else {"both"}
}
}))
if(package=="expanded") {
tabs1 <- vTabs
} else {
if(package=="basic") {
tabs1 <- vTabs[which(vTypes %in% c("basic","both"))]
} else {
stop("Package must be basic or expanded.")
}
}
tabs <- c(tabs1, "validation", "variables", "readme",
"categoricalCodes", "sensor_positions")
files <- files[grep(paste(paste("[.]", tabs, "[.]", sep=""), collapse="|"), files)]
if(any(vTypes=="both")) {
bothTabs <- vTabs[which(vTypes=="both")]
bothFiles <- files[grep(paste(paste("[.]", bothTabs, "[.]", sep=""),
collapse="|"), files)]
if(package=="expanded") {
remFiles <- bothFiles[grep("basic", bothFiles)]
} else {
remFiles <- bothFiles[grep("expanded", bothFiles)]
}
files <- files[which(!files %in% remFiles)]
}
tabCheck <- unlist(lapply(tabs1, function(x) {
if(length(grep(paste("[.]", x, "[.]", sep=""), files))>0) {
TRUE
} else {
FALSE
}
}))
if(any(!tabCheck)) {
warning(paste("Some expected data tables are not present in the files to be stacked. Stacking will proceed with available tables, but check for mismatched input criteria, e.g. attempting to stack expanded package from an archive containing only the basic package. The missing tables are", paste(tabs1[!tabCheck], collapse=" ")))
}
}
pubmat <- regexpr("[0-9]{8}T[0-9]{6}Z", basename(files))
pubdates <- sapply(regmatches(basename(files), pubmat, invert=NA), "[", 2)
pubdates <- as.POSIXct(pubdates, format="%Y%m%dT%H%M%SZ", tz="GMT")
if(!is.na(pubdate)) {
pubdate <- as.POSIXct(pubdate, format="%Y-%m-%d", tz="GMT")
files <- files[union(which(pubdates <= pubdate), which(is.na(pubdates)))]
} else {
pubdate <- max(pubdates, na.rm=T)
}
for(i in tabs1) {
filesub <- files[grep(paste("[.]", i, "[.]", sep=""), files)]
filesuborig <- filesub
sitemat <- regexpr("[.][A-Z]{4}[.]", basename(filesub))
sitesactual <- regmatches(basename(filesub), sitemat)
sitesactual <- gsub(".", "", sitesactual, fixed=T)
if(length(sitesactual)==0) {
files <- files
} else {
datemat <- regexpr("[0-9]{4}-[0-9]{2}", basename(filesub))
datadates <- regmatches(basename(filesub), datemat)
if(length(datadates)==0) {
files <- files
} else {
if(!is.na(startdate) & !is.na(enddate)) {
filesub <- filesub[which(datadates >= startdate & datadates <= enddate)]
} else if(!is.na(startdate)) {
filesub <- filesub[which(datadates >= startdate)]
} else if(!is.na(enddate)) {
filesub <- filesub[which(datadates <= enddate)]
}
datemat <- regexpr("[0-9]{4}-[0-9]{2}", basename(filesub))
monthsactual <- regmatches(basename(filesub), datemat)
pubmatsub <- regexpr("[0-9]{8}T[0-9]{6}Z", basename(filesub))
pubdatesub <- sapply(regmatches(basename(filesub), pubmatsub, invert=NA), "[", 2)
pubdatesub <- as.POSIXct(pubdatesub, format="%Y%m%dT%H%M%SZ", tz="GMT")
sitemat <- regexpr("[.][A-Z]{4}[.]", basename(filesub))
sitesactual <- regmatches(basename(filesub), sitemat)
sitesactual <- gsub(".", "", sitesactual, fixed=T)
sitedates <- numeric()
for(j in unique(sitesactual)) {
if(!identical(site, "all") & !j %in% site) {
next
} else {
sitemonths <- monthsactual[which(sitesactual==j)]
for(k in unique(sitemonths)) {
sitemonthfiles <- filesub[intersect(grep(j, filesub), grep(k, filesub))]
sitemonthpubs <- pubdatesub[intersect(grep(j, filesub), grep(k, filesub))]
maxdate <- max(sitemonthpubs[which(sitemonthpubs <= pubdate)])
if(length(maxdate)==0) {
sitedates <- sitedates
} else {
maxdateindex <- which(pubdatesub==maxdate)
sitedates <- c(sitedates, maxdateindex)
}
}
}
}
filesubsub <- filesub[sitedates]
files <- files[union(which(files %in% filesubsub),
which(!files %in% filesuborig))]
}
}
}
if(timeIndex!="all" & dpID!="DP4.00200.001") {
if(all(table_types$tableTMI[which(table_types$productID==dpID)]==0)) {
stop(paste("timeIndex is only a valid input for sensor data. ", dpID,
" is not a time-aggregated product.", sep=""))
}
if(!timeIndex %in% table_types$tableTMI[which(table_types$productID==dpID)]) {
stop(paste(timeIndex, " is not a valid time interval for ", dpID,
". Use function getTimeIndex() to find valid time intervals.", sep=""))
}
tabInd <- grep("min", files, fixed=T)
timeInd <- union(grep(paste(timeIndex, "min", sep=""), files, fixed=T),
grep(paste(timeIndex, "_min", sep=""), files, fixed=T))
dropInd <- setdiff(tabInd, timeInd)
files <- files[-dropInd]
}
if(length(files)==0) {
stop("No files found meeting all input criteria.")
}
if(dpID=="DP4.00200.001") {
if(load==FALSE) {
stop("Writing to local directory is not available for DP4.00200.001. Use load=TRUE and assign to a variable name.")
} else {
if(timeIndex=="all") {
avg <- NA
} else {
avg <- timeIndex
}
return(stackEddy(filepath=files, level=level, avg=avg, var=var))
}
} else {
if(load==TRUE) {
savepath <- "envt"
} else {
savepath <- NA
}
return(stackByTable(files, savepath=savepath, saveUnzippedFiles=T, nCores=nCores,
dpID=dpID, package=package))
}
}
}
|
ProbBasedMethodology <- R6::R6Class(
classname = "ProbBasedMethodology",
portable = TRUE,
inherit = Methodology,
public = list(
initialize = function(required.metrics = c("MCC", "PPV")) {
if (any(is.null(required.metrics),
!is.character(required.metrics),
length(required.metrics) < 2)) {
stop("[", class(self)[1], "][FATAL] Invalid values of required.metrics. Aborting...")
}
super$initialize(required.metrics = required.metrics)
},
compute = function(raw.pred, prob.pred, positive.class, negative.class) {
if (is.null(raw.pred) || !is.list(raw.pred)) {
stop("[", class(self)[1], "][FATAL] Raw.pred parameter must be defined ",
"as 'list' type. Aborting...")
}
if (!all(self$getRequiredMetrics() %in% names(raw.pred))) {
stop("[", class(self)[1], "][FATAL] Raw.pred parameter must have required metrics. ",
paste(self$getRequiredMetrics(), collapse = " "), ". Aborting...")
}
if (is.null(prob.pred) || !is.list(prob.pred)) {
stop("[", class(self)[1], "][FATAL] Prob.pred parameter must be defined ",
"as 'list' type. Aborting...")
}
if (!all(self$getRequiredMetrics() %in% names(prob.pred))) {
stop("[", class(self)[1], "][FATAL] Prob.pred parameter must have required metrics. ",
paste(self$getRequiredMetrics(), collapse = " "), ". Aborting...")
}
if (is.null(positive.class) || (!is.character(positive.class) && !is.numeric(positive.class))) {
stop("[", class(self)[1], "][FATAL] Positive class parameter must be defined. Aborting...")
}
if (is.null(negative.class) || (!is.character(negative.class) && !is.numeric(negative.class))) {
stop("[", class(self)[1], "][FATAL] Negative class parameter must be defined. Aborting...")
}
Reduce(prod, prob.pred[which(names(prob.pred) %in% self$getRequiredMetrics())])
}
)
)
|
context("API endpoints")
test_that("format catches and all_results tests", {
testthat::skip_on_cran()
old_config <- if(file.exists("rdhs.json")) "rdhs.json" else NULL
cli <- new_rand_client()
dat <- api_timeout_safe_test(
dhs_data_updates(
client = cli, lastUpdate = "20150901", all_results = FALSE
), cli
)
dat2 <- api_timeout_safe_test(
dhs_data_updates(
client = cli, lastUpdate = "20150901", all_results = FALSE
), cli
)
expect_identical(dat, dat2)
dat <- api_timeout_safe_test(
dhs_datasets(f = "xml", all_results = FALSE), cli
)
expect_error(api_timeout_safe_test(
dhs_data(
indicatorIds = "ML_FEVT_C_AMasfafasfL",
surveyYearStart = 202231231306,
breakdown = "subParTyping"
), cli
)
)
dat <- api_timeout_safe_test(
dhs_datasets(
surveyIds = "laksjdoash,dasjd", f = "xml", all_results = FALSE
), cli
)
expect_error(api_timeout_safe_test(dhs_countries(countryIds = "SE"), cli))
dat <- api_timeout_safe_test(
dhs_indicators(), cli
)
datasets <- api_timeout_safe_test(
dhs_datasets(), cli
)
set_rdhs_config(data_frame = "data.table::as.data.table", prompt = FALSE)
library(data.table)
dat <- api_timeout_safe_test(
dhs_countries(
countryIds = "TZ", surveyYearStart = "2010", all_results = FALSE
), cli
)
expect_true(inherits(dat, "data.table"))
Sys.setenv("rdhs_DATA_TABLE" = FALSE)
if(is.null(old_config)){
file.remove("rdhs.json")
}
})
test_that("geojson works", {
testthat::skip("geojson test too heavy an API test")
testthat::skip_on_cran()
testthat::skip_on_travis()
skip_if_slow_API()
d <- api_timeout_safe_test(
dhs_data(countryIds = "SN",
surveyYearStart = 2014,
breakdown = "subnational",
returnGeometry = TRUE,
f = "geojson"), cli
)
expect_true(inherits(d, "list"))
expect_equal(names(d), c("crs", "type", "features"))
expect_true(d$features %>% length > 100)
d <- api_timeout_safe_test(
dhs_data(countryIds = "SN",
indicatorIds = "FE_FRTR_W_A15",
surveyYearStart = 2014,
breakdown = "subnational",
returnGeometry = TRUE,
f = "geojson"), cli
)
expect_true(inherits(d, "list"))
expect_equal(names(d), c("crs", "type", "features"))
expect_true(d$features %>% length < 100)
})
test_that("dhs_countries works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_countries(
countryIds = "SN", surveyYearStart = "2010", all_results = FALSE
), cli
)
expect_identical(dat$UNAIDS_CountryCode[1], "SEN")
dat <- api_timeout_safe_test(
dhs_countries(
countryIds = c("EG", "SN"),
surveyYearStart = "1991", surveyYearEnd = "2006",
surveyType = "DHS", surveyCharacteristicIds = "32"
), cli
)
expect_identical(dat$ISO3_CountryCode[1:2], c("EGY", "SEN"))
dat <- api_timeout_safe_test(
dhs_countries(tagIds = "1", all_results = FALSE), cli
)
expect_true(any(dat$SubregionName %in% "South Asia"))
})
test_that("dhs_data works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_data(
countryIds = "EG", indicatorIds = "FE_FRTR_W_TFR",
selectSurveys = "latest", all_results = FALSE
), cli
)
expect_true(is.numeric(dat$DataId[1]))
dat <- api_timeout_safe_test(
dhs_data(surveyIds = "SN2010DHS", all_results = FALSE), cli
)
expect_true(any(dat$DataId > 30000))
dat <- api_timeout_safe_test(
dhs_data(
selectSurveys = "byIndicator", indicatorIds = "FE_CEBA_W_CH0",
surveyCharacteristicIds = "32", all_results = FALSE
), cli
)
expect_true(is.numeric(dat$DataId[1]))
dat <- api_timeout_safe_test(
dhs_data(surveyYear = "2010", surveyType = "DHS", all_results = FALSE), cli
)
expect_true(is.numeric(dat$DataId[1]))
dat <- api_timeout_safe_test(
dhs_data(surveyCharacteristicIds = "32", all_results = FALSE), cli
)
expect_true(is.numeric(dat$DataId[1]))
dat <- api_timeout_safe_test(
dhs_data(
breakdown = "subnational", countryIds = "AZ",
all_results = FALSE
), cli
)
expect_true(any(dat$CharacteristicLabel %in% "Baku"))
})
test_that("dhs_dataUpdates works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_data_updates(lastUpdate = "20150901", all_results = FALSE), cli
)
expect_true(any(dat$SurveyId %in% "TL2016DHS"))
dat <- api_timeout_safe_test(
dhs_data_updates(f = "html", all_results = FALSE), cli
)
expect_true(class(dat) == "response")
})
test_that("dhs_datasets works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_datasets(
countryIds = "EG", selectSurveys = "latest",
surveyYearStart = 2000, surveyYearEnd = 2016,
surveyType = "DHS", all_results = FALSE
), cli
)
expect_true(any(dat$FileName %in% "EGGE42FL.zip"))
dat <- api_timeout_safe_test(
dhs_datasets(fileType = "KR", all_results = FALSE), cli
)
expect_true(any(dat$FileType %in% "Children's Recode"))
})
test_that("dhs_indicators works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_indicators(
countryIds = "EG", all_results = FALSE,
indicatorIds = "FE_FRTR_W_TFR"
), cli
)
expect_identical(dat$ShortName[1], "TFR 15-49")
dat <- api_timeout_safe_test(
dhs_indicators(
surveyIds = "SN2010DHS", surveyYearStart = "2006", all_results = FALSE,
surveyYearEnd = "2015"
), cli
)
expect_true(any(dat$MeasurementType %in% "Rate"))
dat <- api_timeout_safe_test(
dhs_indicators(
surveyType = "DHS", surveyCharacteristicIds = "32",
tagIds = "1", all_results = FALSE
), cli
)
expect_true(any(dat$DenominatorWeightedId %in% "FP_CUSM_W_NUM"))
})
test_that("dhs_info works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_info(infoType = "version", all_results = FALSE), cli
)
expect_identical(dat$InfoType, "Version")
dat <- api_timeout_safe_test(
dhs_info(infoType = "citation", all_results = FALSE), cli
)
expect_identical(dat$InfoType, "Citation")
})
test_that("dhs_publications works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_publications(
countryIds = "EG", all_results = FALSE,
selectSurveys = "latest"
), cli
)
expect_true(any(dat$SurveyYear %in% 2015))
dat <- api_timeout_safe_test(
dhs_publications(
surveyYearStart = "2006", surveyYearEnd = "2016",
all_results = FALSE
), cli
)
expect_true(any(dat$PublicationSize %in% 926663))
dat <- api_timeout_safe_test(
dhs_publications(
surveyType = "DHS", surveyCharacteristicIds = "32",
all_results = FALSE, tagIds = 1
), cli
)
expect_true(any(dat$PublicationTitle %in% "Final Report"))
})
test_that("dhs_survey_characteristics works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_survey_characteristics(
countryIds = "EG",
surveyYearStart = 2000, surveyYearEnd = 2016,
surveyType = "DHS", all_results = FALSE
), cli
)
alc <- which(dat$SurveyCharacteristicID == 16)
expect_equal(dat$SurveyCharacteristicID[alc], 16)
expect_equal(dat$SurveyCharacteristicName[alc], "Abortion")
dat <- api_timeout_safe_test(
dhs_survey_characteristics(surveyYearStart = "1991",
surveyType = "DHS")
)
expect_true(any(dat$SurveyCharacteristicName %in% "Abortion"))
})
test_that("dhs_surveys works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_surveys(
countryIds = "EG",
surveyYearStart = 2000, surveyYearEnd = 2016,
surveyType = "DHS", all_results = FALSE
), cli
)
expect_true(any(dat$NumberofHouseholds %in% 16957))
dat <- api_timeout_safe_test(
dhs_surveys(surveyType = "DHS", all_results = FALSE), cli
)
dat <- api_timeout_safe_test(
dhs_surveys(surveyStatus = "Ongoing", all_results = FALSE), cli
)
expect_identical(dat$SurveyStatus[1], "Ongoing")
})
test_that("dhs_tags works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_tags(indicatorIds = "FE_FRTR_W_TFR", all_results = FALSE), cli
)
expect_equal(dim(dat)[2], 4)
dat <- api_timeout_safe_test(
dhs_tags(countryIds = "SN", all_results = FALSE), cli
)
expect_true(any(dat$TagName %in% "DHS Mobile"))
})
test_that("dhs_uiUpdates works", {
testthat::skip_on_cran()
skip_if_slow_API()
dat <- api_timeout_safe_test(
dhs_ui_updates(lastUpdate = "20150901", all_results = FALSE), cli
)
expect_true(any(dat$Interface %in% "Surveys"))
})
test_that("post api tidy", {
if (file.exists("rdhs.json")) {
conf <- read_rdhs_config_file("rdhs.json")
if (is.null(conf$email)){
expect_true(file.remove("rdhs.json"))
}
} else {
expect_true(TRUE)
}
})
|
plot.phylo4d <- function (x, trait = names(tdata(p4d)), center = TRUE, scale = TRUE,
plot.type = "barplot", tree.ladderize = FALSE, tree.type = "phylogram",
tree.ratio = NULL, tree.xlim = NULL, tree.open.angle = 0,
tree.open.crown = TRUE, show.tip = TRUE, tip.labels = NULL,
tip.col = "black", tip.cex = 1, tip.font = 3, tip.adj = 0,
data.xlim = NULL, bar.lwd = 10, bar.col = "grey35",
show.data.axis = TRUE, dot.col = "black", dot.pch = 20,
dot.cex = 2, cell.col = topo.colors(100), show.color.scale = TRUE,
show.trait = TRUE, trait.labels = NULL, trait.col = "black",
trait.cex = 1, trait.font = 1, trait.bg.col = "grey90",
error.bar.sup = NULL, error.bar.inf = NULL, error.bar.col = 1,
show.box = FALSE, grid.vertical = TRUE, grid.horizontal = FALSE,
grid.col = "grey25", grid.lty = "dashed", ...)
{
p4d <- x
orderGrArg <- function (x, n.tips, n.traits, new.order, tips, default)
{
x.dep <- deparse(substitute(x))
if (is.vector(x)) {
if (is.null(names(x))) {
x <- rep(x, length.out = n.tips)
x <- x[new.order]
}
else {
if (any(tips %in% names(x))) {
y <- rep(default, n.tips)
names(y) <- tips
y[names(x)] <- x[names(x)]
x <- y[tips]
}
else {
stop(paste("Phylogenetic tips do not match with names of",
x.dep))
}
}
}
if (is.matrix(x)) {
if (is.null(rownames(x))) {
x <- x[new.order, ]
}
else {
if (any(tips %in% rownames(x))) {
y <- matrix(default, nrow = nrow(x), ncol = ncol(x))
rownames(y) <- tips
y[rownames(x), ] <- x[rownames(x), ]
x <- y[tips, ]
}
else {
stop(paste("Phylogenetic tips do not match with row names of",
x.dep))
}
}
}
x <- matrix(x, nrow = n.tips, ncol = n.traits)
return(x)
}
layouterize <- function (n.traits, show.tip)
{
if (show.tip) {
res <- matrix(c(n.traits + 2, 1:(n.traits + 1)), nrow = 1)
}
else {
res <- matrix(c(n.traits + 1, 1:(n.traits)), nrow = 1)
}
return(res)
}
layouterizeRatio <- function (tree.ratio, n.traits, show.tip)
{
if (!is.null(tree.ratio)) {
if (show.tip) {
res <- c(tree.ratio, rep((1 - tree.ratio)/(n.traits +
1), n.traits + 1))
}
else {
res <- c(tree.ratio, rep((1 - tree.ratio)/n.traits,
n.traits))
}
}
else {
if (show.tip) {
res <- rep(1, n.traits + 1)
}
else {
res <- rep(1, n.traits)
}
}
return(res)
}
matchTipsAndTraits <- function (x, p4d = NULL, p4d.tips = NULL, p4d.traits = NULL,
subset = TRUE)
{
if (!is.null(p4d) & is(p4d, "phylo4d")) {
p4d.tips <- tipLabels(p4d)
p4d.traits <- colnames(tdata(p4d))
}
if (!all(p4d.tips %in% rownames(x))) {
stop("Rows names of !!! do not match with tips names")
}
if (!all(p4d.traits %in% colnames(x))) {
stop("Columns names of !!! do not match with traits names")
}
if (subset) {
x <- x[p4d.tips, p4d.traits]
}
return(x)
}
plotPhyloDisabled <- function (x, type = "phylogram", use.edge.length = TRUE,
node.pos = NULL, show.tip.label = TRUE, show.node.label = FALSE,
edge.color = "black", edge.width = 1, edge.lty = 1,
font = 3, cex = par("cex"), adj = NULL, srt = 0, no.margin = FALSE,
root.edge = FALSE, label.offset = 0, underscore = FALSE,
x.lim = NULL, y.lim = NULL, direction = "rightwards",
lab4ut = NULL, tip.color = "black", plot = TRUE, rotate.tree = 0,
open.angle = 0, node.depth = 1, ...)
{
Ntip <- length(x$tip.label)
if (Ntip < 2) {
warning("found less than 2 tips in the tree")
return(NULL)
}
if (any(tabulate(x$edge[, 1]) == 1))
stop("there are single (non-splitting) nodes in your tree; you may need to use collapse.singles()")
Nedge <- dim(x$edge)[1]
Nnode <- x$Nnode
if (any(x$edge < 1) || any(x$edge > Ntip + Nnode))
stop("tree badly conformed; cannot plot. Check the edge matrix.")
ROOT <- Ntip + 1
type <- match.arg(type, c("phylogram", "cladogram",
"fan", "unrooted", "radial"))
direction <- match.arg(direction, c("rightwards", "leftwards",
"upwards", "downwards"))
if (is.null(x$edge.length))
use.edge.length <- FALSE
if (type %in% c("unrooted", "radial") || !use.edge.length ||
is.null(x$root.edge) || !x$root.edge)
root.edge <- FALSE
if (type == "fan" && root.edge) {
warning("drawing root edge with type = 'fan' is not yet supported")
root.edge <- FALSE
}
phyloORclado <- type %in% c("phylogram", "cladogram")
horizontal <- direction %in% c("rightwards", "leftwards")
xe <- x$edge
if (phyloORclado) {
phyOrder <- attr(x, "order")
if (is.null(phyOrder) || phyOrder != "cladewise") {
x <- reorder(x)
if (!identical(x$edge, xe)) {
ereorder <- match(x$edge[, 2], xe[, 2])
if (length(edge.color) > 1) {
edge.color <- rep(edge.color, length.out = Nedge)
edge.color <- edge.color[ereorder]
}
if (length(edge.width) > 1) {
edge.width <- rep(edge.width, length.out = Nedge)
edge.width <- edge.width[ereorder]
}
if (length(edge.lty) > 1) {
edge.lty <- rep(edge.lty, length.out = Nedge)
edge.lty <- edge.lty[ereorder]
}
}
}
yy <- numeric(Ntip + Nnode)
TIPS <- x$edge[x$edge[, 2] <= Ntip, 2]
yy[TIPS] <- 1:Ntip
}
z <- reorder(x, order = "postorder")
if (phyloORclado) {
if (is.null(node.pos))
node.pos <- if (type == "cladogram" && !use.edge.length)
2
else 1
if (node.pos == 1)
yy <- node.height(x, clado.style = FALSE)
else {
xx <- node.depth(x) - 1
yy <- node.height(x, clado.style = TRUE)
}
if (!use.edge.length) {
if (node.pos != 2)
xx <- node.depth(x) - 1
xx <- max(xx) - xx
}
else {
xx <- node.depth.edgelength(x)
}
}
else {
twopi <- 2 * pi
rotate.tree <- twopi * rotate.tree/360
if (type != "unrooted") {
TIPS <- x$edge[which(x$edge[, 2] <= Ntip), 2]
xx <- seq(0, twopi * (1 - 1/Ntip) - twopi * open.angle/360,
length.out = Ntip)
theta <- double(Ntip)
theta[TIPS] <- xx
theta <- c(theta, numeric(Nnode))
}
switch(type, fan = {
theta <- node.height(x)
if (use.edge.length) {
r <- node.depth.edgelength(x)
} else {
r <- node.depth(x)
r <- 1/r
}
theta <- theta + rotate.tree
xx <- r * cos(theta)
yy <- r * sin(theta)
}, unrooted = {
nb.sp <- node.depth(x)
XY <- if (use.edge.length) ape::unrooted.xy(Ntip,
Nnode, z$edge, z$edge.length, nb.sp, rotate.tree) else ape::unrooted.xy(Ntip,
Nnode, z$edge, rep(1, Nedge), nb.sp, rotate.tree)
xx <- XY$M[, 1] - min(XY$M[, 1])
yy <- XY$M[, 2] - min(XY$M[, 2])
}, radial = {
r <- node.depth(x)
r[r == 1] <- 0
r <- 1 - r/Ntip
theta <- node.height(x) + rotate.tree
xx <- r * cos(theta)
yy <- r * sin(theta)
})
}
if (phyloORclado) {
if (!horizontal) {
tmp <- yy
yy <- xx
xx <- tmp - min(tmp) + 1
}
if (root.edge) {
if (direction == "rightwards")
xx <- xx + x$root.edge
if (direction == "upwards")
yy <- yy + x$root.edge
}
}
if (no.margin)
par(mai = rep(0, 4))
if (show.tip.label)
nchar.tip.label <- nchar(x$tip.label)
max.yy <- max(yy)
if (is.null(x.lim)) {
if (phyloORclado) {
if (horizontal) {
x.lim <- c(0, NA)
pin1 <- par("pin")[1]
strWi <- strwidth(x$tip.label, "inches",
cex = cex)
xx.tips <- xx[1:Ntip] * 1.04
alp <- try(uniroot(function(a) max(a * xx.tips +
strWi) - pin1, c(0, 1e+06))$root, silent = TRUE)
if (is.character(alp))
tmp <- max(xx.tips) * 1.5
else {
tmp <- if (show.tip.label)
max(xx.tips + strWi/alp)
else max(xx.tips)
}
if (show.tip.label)
tmp <- tmp + label.offset
x.lim[2] <- tmp
}
else x.lim <- c(1, Ntip)
}
else switch(type, fan = {
if (show.tip.label) {
offset <- max(nchar.tip.label * 0.018 * max.yy *
cex)
x.lim <- range(xx) + c(-offset, offset)
} else x.lim <- range(xx)
}, unrooted = {
if (show.tip.label) {
offset <- max(nchar.tip.label * 0.018 * max.yy *
cex)
x.lim <- c(0 - offset, max(xx) + offset)
} else x.lim <- c(0, max(xx))
}, radial = {
if (show.tip.label) {
offset <- max(nchar.tip.label * 0.03 * cex)
x.lim <- c(-1 - offset, 1 + offset)
} else x.lim <- c(-1, 1)
})
}
else if (length(x.lim) == 1) {
x.lim <- c(0, x.lim)
if (phyloORclado && !horizontal)
x.lim[1] <- 1
if (type %in% c("fan", "unrooted") && show.tip.label)
x.lim[1] <- -max(nchar.tip.label * 0.018 * max.yy *
cex)
if (type == "radial")
x.lim[1] <- if (show.tip.label)
-1 - max(nchar.tip.label * 0.03 * cex)
else -1
}
if (phyloORclado && direction == "leftwards")
xx <- x.lim[2] - xx
if (is.null(y.lim)) {
if (phyloORclado) {
if (horizontal)
y.lim <- c(1, Ntip)
else {
y.lim <- c(0, NA)
pin2 <- par("pin")[2]
strWi <- strwidth(x$tip.label, "inches",
cex = cex)
yy.tips <- yy[1:Ntip] * 1.04
alp <- try(uniroot(function(a) max(a * yy.tips +
strWi) - pin2, c(0, 1e+06))$root, silent = TRUE)
if (is.character(alp))
tmp <- max(yy.tips) * 1.5
else {
tmp <- if (show.tip.label)
max(yy.tips + strWi/alp)
else max(yy.tips)
}
if (show.tip.label)
tmp <- tmp + label.offset
y.lim[2] <- tmp
}
}
else switch(type, fan = {
if (show.tip.label) {
offset <- max(nchar.tip.label * 0.018 * max.yy *
cex)
y.lim <- c(min(yy) - offset, max.yy + offset)
} else y.lim <- c(min(yy), max.yy)
}, unrooted = {
if (show.tip.label) {
offset <- max(nchar.tip.label * 0.018 * max.yy *
cex)
y.lim <- c(0 - offset, max.yy + offset)
} else y.lim <- c(0, max.yy)
}, radial = {
if (show.tip.label) {
offset <- max(nchar.tip.label * 0.03 * cex)
y.lim <- c(-1 - offset, 1 + offset)
} else y.lim <- c(-1, 1)
})
}
else if (length(y.lim) == 1) {
y.lim <- c(0, y.lim)
if (phyloORclado && horizontal)
y.lim[1] <- 1
if (type %in% c("fan", "unrooted") && show.tip.label)
y.lim[1] <- -max(nchar.tip.label * 0.018 * max.yy *
cex)
if (type == "radial")
y.lim[1] <- if (show.tip.label)
-1 - max(nchar.tip.label * 0.018 * max.yy * cex)
else -1
}
if (phyloORclado && direction == "downwards")
yy <- y.lim[2] - yy
if (phyloORclado && root.edge) {
if (direction == "leftwards")
x.lim[2] <- x.lim[2] + x$root.edge
if (direction == "downwards")
y.lim[2] <- y.lim[2] + x$root.edge
}
asp <- if (type %in% c("fan", "radial", "unrooted"))
1
else NA
L <- list(type = type, use.edge.length = use.edge.length,
node.pos = node.pos, node.depth = node.depth, show.tip.label = show.tip.label,
show.node.label = show.node.label, font = font, cex = cex,
adj = adj, srt = srt, no.margin = no.margin, label.offset = label.offset,
x.lim = x.lim, y.lim = y.lim, direction = direction,
tip.color = tip.color, Ntip = Ntip, Nnode = Nnode)
assign("last_plot.phylo", c(L, list(edge = xe, xx = xx,
yy = yy)), envir = ape::.PlotPhyloEnv)
return(L)
}
p4 <- phylobase::extractTree(p4d)
phy <- as(p4, "phylo")
if (tree.ladderize) {
phy <- ladderize(phy)
}
new.order <- phy$edge[, 2][!phy$edge[, 2] %in% phy$edge[,
1]]
tips <- phy$tip.label[new.order]
n.tips <- length(tips)
X <- tdata(p4d, type = "tip")
X <- X[new.order, trait]
X <- scale(X, center = center, scale = scale)
X <- as.data.frame(X)
colnames(X) <- trait
n.traits <- ncol(X)
if (is.numeric(trait)) {
trait <- names(tdata(p4d))[trait]
}
tree.type <- match.arg(tree.type, c("phylogram", "cladogram",
"fan"))
plot.type <- match.arg(plot.type, c("barplot", "dotplot",
"gridplot"))
if (!is.null(error.bar.inf)) {
error.bar.inf <- as.matrix(error.bar.inf)
error.bar.inf[is.na(error.bar.inf)] <- 0
error.bar.inf <- matchTipsAndTraits(error.bar.inf, p4d.tips = tips,
p4d.traits = trait)
}
if (!is.null(error.bar.sup)) {
error.bar.sup <- as.matrix(error.bar.sup)
error.bar.sup[is.na(error.bar.sup)] <- 0
error.bar.sup <- matchTipsAndTraits(error.bar.sup, p4d.tips = tips,
p4d.traits = trait)
}
if (!is.null(error.bar.inf)) {
arrow.inf <- X
arrow.inf[X > 0] <- X[X > 0] - error.bar.inf[X > 0]
arrow.inf[X < 0] <- X[X < 0] + error.bar.inf[X < 0]
}
if (!is.null(error.bar.sup)) {
arrow.sup <- X
arrow.sup[X > 0] <- X[X > 0] + error.bar.sup[X > 0]
arrow.sup[X < 0] <- X[X < 0] - error.bar.sup[X < 0]
}
if (is.null(data.xlim)) {
if (center & scale) {
data.xlim <- matrix(rep(NA, n.traits * 2), nrow = 2,
dimnames = list(c("xlim.min", "xlim.max"),
trait))
if (!is.null(error.bar.inf) & !is.null(error.bar.sup)) {
data.xlim[1, ] <- floor(min(arrow.inf, arrow.sup,
na.rm = TRUE))
data.xlim[2, ] <- ceiling(max(arrow.inf, arrow.sup,
na.rm = TRUE))
}
else if (!is.null(error.bar.inf)) {
data.xlim[1, ] <- floor(min(arrow.inf, na.rm = TRUE))
data.xlim[2, ] <- ceiling(max(arrow.inf, na.rm = TRUE))
}
else if (!is.null(error.bar.sup)) {
data.xlim[1, ] <- floor(min(arrow.sup, na.rm = TRUE))
data.xlim[2, ] <- ceiling(max(arrow.sup, na.rm = TRUE))
}
else {
data.xlim[1, ] <- floor(min(X, na.rm = TRUE))
data.xlim[2, ] <- ceiling(max(X, na.rm = TRUE))
}
}
else {
data.xlim <- matrix(NA, nrow = 2, ncol = n.traits,
dimnames = list(c("xlim.min", "xlim.max"),
trait))
data.xlim[1, ] <- apply(X, 2, min, na.rm = TRUE)
data.xlim[1, apply(X, 2, min, na.rm = TRUE) * apply(X,
2, max, na.rm = TRUE) > 0 & apply(X, 2, min,
na.rm = TRUE) > 0] <- 0
data.xlim[2, ] <- apply(X, 2, max, na.rm = TRUE)
data.xlim[2, apply(X, 2, min, na.rm = TRUE) * apply(X,
2, max, na.rm = TRUE) > 0 & apply(X, 2, max,
na.rm = TRUE) < 0] <- 0
if (!is.null(error.bar.inf) & !is.null(error.bar.sup)) {
data.xlim[1, ] <- apply(cbind(apply(arrow.inf,
2, min, na.rm = TRUE), apply(arrow.sup, 2,
min)), 1, min, na.rm = TRUE)
data.xlim[2, ] <- apply(cbind(apply(arrow.inf,
2, max, na.rm = TRUE), apply(arrow.sup, 2,
max)), 1, max, na.rm = TRUE)
}
else {
if (!is.null(error.bar.inf)) {
data.xlim[1, ] <- apply(cbind(apply(arrow.inf,
2, min, na.rm = TRUE), data.xlim[1, ]), 1,
min, na.rm = TRUE)
data.xlim[2, ] <- apply(cbind(apply(arrow.inf,
2, max, na.rm = TRUE), data.xlim[2, ]), 1,
max, na.rm = TRUE)
}
if (!is.null(error.bar.sup)) {
data.xlim[1, ] <- apply(cbind(apply(arrow.sup,
2, min, na.rm = TRUE), data.xlim[1, ]), 1,
min, na.rm = TRUE)
data.xlim[2, ] <- apply(cbind(apply(arrow.sup,
2, max, na.rm = TRUE), data.xlim[2, ]), 1,
max, na.rm = TRUE)
}
}
}
}
else if (is.vector(data.xlim) & length(data.xlim) == 2) {
data.xlim <- matrix(rep(data.xlim, n.traits), nrow = 2,
dimnames = list(c("xlim.min", "xlim.max"),
trait))
}
else if (is.matrix(data.xlim)) {
if (isTRUE(all.equal(dim(data.xlim), c(2, n.traits)))) {
rownames(data.xlim) <- c("xlim.min", "xlim.max")
colnames(data.xlim) <- trait
}
else {
stop("Invalid 'data.xlim' argument: wrong matrix dimensions")
}
}
else {
stop("Invalid 'data.xlim' argument")
}
ylim <- c(1, n.tips)
if (plot.type == "barplot") {
bar.col <- orderGrArg(bar.col, n.tips = n.tips, n.traits = n.traits,
new.order = new.order, tips = tips, default = "grey35")
}
if (plot.type == "dotplot") {
dot.col <- orderGrArg(dot.col, n.tips = n.tips, n.traits = n.traits,
new.order = new.order, tips = tips, default = 1)
dot.pch <- orderGrArg(dot.pch, n.tips = n.tips, n.traits = n.traits,
new.order = new.order, tips = tips, default = 1)
dot.cex <- orderGrArg(dot.cex, n.tips = n.tips, n.traits = n.traits,
new.order = new.order, tips = tips, default = 1)
}
if (!is.null(error.bar.inf) | !is.null(error.bar.sup)) {
error.bar.col <- orderGrArg(error.bar.col, n.tips = n.tips,
n.traits = n.traits, new.order = new.order, tips = tips,
default = 1)
}
if (is.null(tip.labels)) {
tip.labels <- tips
}
else {
tip.labels <- orderGrArg(tip.labels, n.tips = n.tips,
n.traits = n.traits, new.order = new.order, tips = tips,
default = "")
}
tip.col <- orderGrArg(tip.col, n.tips = n.tips, n.traits = n.traits,
new.order = new.order, tips = tips, default = 1)
tip.cex <- orderGrArg(tip.cex, n.tips = n.tips, n.traits = n.traits,
new.order = new.order, tips = tips, default = 1)
tip.font <- orderGrArg(tip.font, n.tips = n.tips, n.traits = n.traits,
new.order = new.order, tips = tips, default = 3)
if (is.null(trait.labels)) {
trait.labels <- trait
}
trait.labels <- rep(trait.labels, length.out = n.traits)
trait.col <- rep(trait.col, length.out = n.traits)
trait.cex <- rep(trait.cex, length.out = n.traits)
trait.font <- rep(trait.font, length.out = n.traits)
trait.bg.col <- rep(trait.bg.col, length.out = n.traits)
if (is.null(tree.xlim)) {
tree.xlim <- plotPhyloDisabled(phy, type = tree.type,
show.tip.label = FALSE, x.lim = NULL, y.lim = NULL,
no.margin = FALSE, direction = "rightwards",
plot = FALSE, ...)$x.lim
}
par.mar0 <- par("mar")
par.lend0 <- par("lend")
par.xpd0 <- par("xpd")
if (tree.type == "phylogram" | tree.type == "cladogram") {
if (plot.type %in% c("barplot", "dotplot")) {
lay <- layouterize(n.traits = n.traits, show.tip = show.tip)
lay.w <- layouterizeRatio(tree.ratio = tree.ratio,
n.traits = n.traits, show.tip = show.tip)
}
if (plot.type == "gridplot") {
lay <- layouterize(n.traits = 1, show.tip = show.tip)
lay.w <- layouterizeRatio(tree.ratio = tree.ratio,
n.traits = 1, show.tip = show.tip)
}
layout(lay, widths = lay.w)
par(xpd = FALSE, mar = c(5, 1, 4, 0), lend = 1)
fig.traits <- vector("list", n.traits)
names(fig.traits) <- trait
if (plot.type %in% c("barplot", "dotplot")) {
for (i in 1:n.traits) {
plot.new()
plot.window(xlim = data.xlim[, i], ylim = ylim)
fig.traits[[i]] <- par("fig")
rect(par("usr")[1], par("usr")[3] -
(3 * par("cxy")[2]), par("usr")[2],
par("usr")[4], col = trait.bg.col[i],
border = NA, xpd = TRUE)
if (show.box) {
box()
}
if (grid.vertical) {
grid(NULL, NA, col = grid.col, lty = grid.lty)
abline(v = 0, lty = "solid", col = grid.col)
}
else {
abline(v = 0, lty = "solid", col = grid.col)
}
if (grid.horizontal) {
abline(h = 1:n.tips, col = grid.col, lty = grid.lty)
}
if (plot.type == "barplot") {
segments(x0 = 0, x1 = X[, i], y0 = 1:n.tips,
lwd = bar.lwd, col = bar.col[, i])
}
if (plot.type == "dotplot") {
points(x = X[, i], y = 1:n.tips, col = dot.col[,
i], pch = dot.pch[, i], cex = dot.cex[, i])
}
options(warn = -1)
if (!is.null(error.bar.inf)) {
arrows(x0 = X[, i], x1 = arrow.inf[, i], y0 = 1:n.tips,
lwd = 1, col = error.bar.col, angle = 90,
length = 0.04)
}
if (!is.null(error.bar.sup)) {
arrows(x0 = X[, i], x1 = arrow.sup[, i], y0 = 1:n.tips,
lwd = 1, col = error.bar.col, angle = 90,
length = 0.04)
}
options(warn = 1)
if (show.data.axis) {
axis(1)
}
if (show.trait) {
mtext(trait.labels[i], side = 1, line = 3,
las = par("las"), col = trait.col[i],
cex = trait.cex[i], font = trait.font[i])
}
}
}
if (plot.type == "gridplot") {
plot.new()
rect(par("usr")[1], par("usr")[3] - (3 *
par("cxy")[2]), par("usr")[2], par("usr")[4],
col = trait.bg.col[1], border = NA, xpd = TRUE)
data.xlim[1, ] <- 0
data.xlim[2, ] <- n.traits
plot.window(xlim = data.xlim[, 1], ylim = ylim)
fig.traits[[1]] <- par("fig")
image(x = 0:n.traits, y = 1:n.tips, z = t(X), col = cell.col,
add = TRUE, xlab = "", ylab = "",
yaxs = FALSE, xaxs = FALSE)
if (show.box) {
box()
}
if (grid.horizontal) {
abline(h = seq(1.5, n.tips - 0.5), col = grid.col,
lty = grid.lty)
}
if (grid.vertical) {
abline(v = seq(1, n.traits - 1), col = grid.col,
lty = grid.lty)
}
if (show.trait) {
mtext(trait.labels, at = seq(0.5, (n.traits -
0.5)), side = 1, line = 1, las = par("las"),
col = trait.col, cex = trait.cex, font = trait.font)
}
}
if (show.tip) {
plot.new()
tip.xlim <- c(-1, 1)
if (tip.adj < 0.5)
tip.xlim[1] <- -tip.adj/0.5
if (tip.adj > 0.5)
tip.xlim[2] <- -2 * tip.adj + 2
plot.window(xlim = tip.xlim, ylim = ylim)
text(x = 0, y = 1:n.tips, labels = tip.labels, adj = tip.adj,
col = tip.col, cex = tip.cex, font = tip.font)
fig.tip <- par("fig")
}
else {
fig.tip <- NULL
tip.xlim <- NULL
}
plot.phylo(phy, type = tree.type, show.tip.label = FALSE,
x.lim = tree.xlim, y.lim = NULL, no.margin = FALSE,
direction = "rightwards", ...)
fig.tree <- par("fig")
if (plot.type == "gridplot" & show.color.scale) {
par(new = TRUE)
plt.init <- par("plt")
par(plt = c(par("plt")[1] + 0.05, par("plt")[2] -
0.2, 0.07, 0.1))
plot.new()
breaks <- seq(min(X), max(X), length.out = (length(cell.col) +
1))
scale.xlim <- range(breaks)
scale.ylim <- c(0, 1)
plot.window(xlim = scale.xlim, ylim = scale.ylim)
for (i in 1:length(cell.col)) {
polygon(c(breaks[i], breaks[i + 1], breaks[i +
1], breaks[i]), c(0, 0, 1, 1), col = cell.col[i],
border = NA)
}
axis(1)
par(plt = plt.init)
}
assign("last_barplotp4d", list(plot.type = plot.type,
show.tip = show.tip, layout = lay, fig.tree = fig.tree,
fig.traits = fig.traits, fig.tip = fig.tip, tree.xlim = tree.xlim,
data.xlim = data.xlim, tip.xlim = tip.xlim, ylim = ylim,
par.mar0 = par.mar0), envir = ape::.PlotPhyloEnv)
layout(1)
}
if (tree.type == "fan") {
par(lend = 1)
if (is.null(tree.ratio)) {
if (show.tip) {
tree.ratio <- 1/(n.traits + 2)
}
else {
tree.ratio <- 1/(n.traits + 1)
}
}
plot.phylo(phy, type = tree.type, show.tip.label = FALSE,
x.lim = tree.xlim * (1/tree.ratio), y.lim = NULL,
no.margin = TRUE, open.angle = tree.open.angle, rotate.tree = 0,
...)
lp <- get("last_plot.phylo", envir = ape::.PlotPhyloEnv)
length.phylo <- max(sqrt(lp$xx^2 + lp$yy^2))
if (show.tip) {
length.gr0 <- (min(par("usr")[2] - par("usr")[1],
par("usr")[4] - par("usr")[3])/2 -
length.phylo)/(n.traits + 1)
}
else {
length.gr0 <- (min(par("usr")[2] - par("usr")[1],
par("usr")[4] - par("usr")[3])/2 -
length.phylo)/n.traits
}
length.intergr <- 0.2 * length.gr0
length.gr <- length.gr0 - length.intergr
theta <- atan2(lp$xx[1:n.tips], lp$yy[1:n.tips])[new.order]
theta[theta > (pi/2)] <- -pi - (pi - theta[theta > (pi/2)])
cos.t <- cos(pi/2 - theta)
sin.t <- sin(pi/2 - theta)
theta.real.open <- diff(c(min(theta), max(theta)))
real.open <- theta.real.open * 180/pi
if (tree.open.crown) {
theta.soft <- pi/2 - seq(-5, real.open + 5, length.out = 300) *
pi/180
}
else {
theta.soft <- pi/2 - seq(0, 360) * pi/180 + 10 *
pi/180
}
cos.tsoft <- cos(pi/2 - theta.soft)
sin.tsoft <- sin(pi/2 - theta.soft)
for (i in 1:n.traits) {
length.ring1 <- length.phylo + length.intergr * i +
length.gr * (i - 1) - 0.3 * length.intergr
length.ring2 <- length.phylo + length.intergr * i +
length.gr * i + 0.3 * length.intergr
xx1 <- length.ring1 * cos.tsoft
xx2 <- length.ring2 * cos.tsoft
yy1 <- length.ring1 * sin.tsoft
yy2 <- length.ring2 * sin.tsoft
polygon(c(xx1, rev(xx2)), c(yy1, rev(yy2)), col = trait.bg.col[i],
border = NA)
if (abs(sign(min(data.xlim[, i])) + sign(max(data.xlim[,
i]))) == 2) {
scaling.factor <- length.gr/max(abs(min(data.xlim[,
i])), abs(max(data.xlim[, i])))
}
else {
scaling.factor <- length.gr/diff(c(min(data.xlim[,
i]), max(data.xlim[, i])))
}
X.scale <- X[, i] * scaling.factor
data.xlim.scale <- data.xlim[, i] * scaling.factor
if (!is.null(error.bar.inf)) {
arrow.inf.scale <- arrow.inf[, i] * scaling.factor
}
if (!is.null(error.bar.sup)) {
arrow.sup.scale <- arrow.sup[, i] * scaling.factor
}
if (plot.type == "barplot" | plot.type == "dotplot") {
length.baseline <- (length.phylo + length.intergr *
i + length.gr * (i - 1) + ifelse(min(data.xlim.scale) <
0, abs(min(data.xlim.scale)), 0))
length.baseline <- rep(length.baseline, n.tips)
length.values <- length.baseline + X.scale
if (!is.null(error.bar.inf)) {
length.arrow.inf <- length.baseline + arrow.inf.scale
}
if (!is.null(error.bar.sup)) {
length.arrow.sup <- length.baseline + arrow.sup.scale
}
length.baseline <- rep(length.baseline, length.out = length(cos.tsoft))
lines(length.baseline * cos.tsoft, length.baseline *
sin.tsoft, lwd = 1)
if (grid.horizontal) {
segments(x0 = length.ring1 * cos.t, x1 = length.ring2 *
cos.t, y0 = length.ring1 * sin.t, y1 = length.ring2 *
sin.t, col = grid.col, lty = grid.lty)
}
if ((show.data.axis | grid.vertical)) {
if (tree.open.crown) {
theta.ax <- theta.soft[1]
}
else {
if (show.trait) {
theta.ax <- theta[1] + (360 - real.open) *
(1/3) * pi/180
}
else {
theta.ax <- theta[1] + (360 - real.open) *
(1/2) * pi/180
}
}
cos.tax <- cos(pi/2 - theta.ax)
sin.tax <- sin(pi/2 - theta.ax)
nint.ticks <- round((length.gr/min(par("usr")[2] -
par("usr")[1], par("usr")[4] -
par("usr")[3]))/3 * 100) - 1
if (min(data.xlim.scale) <= 0 & max(data.xlim.scale) >=
0) {
ticks <- axisTicks(c(min(data.xlim.scale)/scaling.factor,
max(data.xlim.scale)/scaling.factor), log = FALSE,
nint = nint.ticks)
}
else {
if (abs(min(data.xlim.scale)) > max(data.xlim.scale)) {
ticks <- axisTicks(c(0, min(data.xlim.scale)/scaling.factor),
log = FALSE, nint = nint.ticks)
}
else {
ticks <- axisTicks(c(0, max(data.xlim.scale)/scaling.factor),
log = FALSE, nint = nint.ticks)
}
}
ticks <- ifelse(ticks > max(data.xlim.scale)/scaling.factor,
NA, ticks)
length.ticks <- length.baseline[1] + ticks *
scaling.factor
if (grid.vertical) {
for (j in 1:length(length.ticks)) {
lines(length.ticks[j] * cos.tsoft, length.ticks[j] *
sin.tsoft, col = grid.col, lty = grid.lty)
}
}
if (show.data.axis) {
segments(x0 = length.ring1 * cos.tax, x1 = length.ring2 *
cos.tax, y0 = length.ring1 * sin.tax, y1 = length.ring2 *
sin.tax, lwd = 20, col = trait.bg.col[i])
text(x = length.ticks * cos.tax, y = length.ticks *
sin.tax, labels = ticks, cex = tip.cex)
}
}
}
if (plot.type == "barplot") {
length.baseline <- rep(length.baseline, length.out = length(cos.t))
segments(x0 = length.baseline * cos.t, x1 = length.values *
cos.t, y0 = length.baseline * sin.t, y1 = length.values *
sin.t, lwd = bar.lwd, col = bar.col[, i])
}
if (plot.type == "dotplot") {
length.baseline <- rep(length.baseline, length.out = length(cos.t))
points(x = length.values * cos.t, y = length.values *
sin.t, col = dot.col[, i], pch = dot.pch[,
i], cex = dot.cex[, i])
}
if (plot.type == "gridplot") {
nc <- length(cell.col)
X.cut <- as.numeric(cut(as.matrix(X), nc))
grid.colors <- cell.col[X.cut]
grid.colors <- matrix(grid.colors, ncol = n.traits)
theta.grid1 <- theta + pi/2 - (theta[1] + theta[2])/2
theta.grid2 <- theta - pi/2 + (theta[1] + theta[2])/2
for (k in 1:length(theta)) {
tile.x1 <- length.ring1 * cos(pi/2 - seq(theta.grid1[k],
theta.grid2[k], length.out = 25))
tile.x2 <- length.ring2 * cos(pi/2 - seq(theta.grid1[k],
theta.grid2[k], length.out = 25))
tile.y1 <- length.ring1 * sin(pi/2 - seq(theta.grid1[k],
theta.grid2[k], length.out = 25))
tile.y2 <- length.ring2 * sin(pi/2 - seq(theta.grid1[k],
theta.grid2[k], length.out = 25))
polygon(c(tile.x1, rev(tile.x2)), c(tile.y1,
rev(tile.y2)), col = grid.colors[k, i], border = NA)
}
if (grid.horizontal) {
segments(x0 = length.ring1 * cos(pi/2 - theta.grid1),
y0 = length.ring1 * sin(pi/2 - theta.grid1),
x1 = length.ring2 * cos(pi/2 - theta.grid1),
y1 = length.ring2 * sin(pi/2 - theta.grid1),
col = grid.col, lty = grid.lty)
segments(x0 = length.ring1 * cos(pi/2 - theta.grid2[length(theta.grid2)]),
y0 = length.ring1 * sin(pi/2 - theta.grid2[length(theta.grid2)]),
x1 = length.ring2 * cos(pi/2 - theta.grid2[length(theta.grid2)]),
y1 = length.ring2 * sin(pi/2 - theta.grid2[length(theta.grid2)]),
col = grid.col, lty = grid.lty)
}
if (grid.vertical) {
if (i > 1) {
lines((length.ring1 - length.intergr/2 +
0.3 * length.intergr) * cos.tsoft, (length.ring1 -
length.intergr/2 + 0.3 * length.intergr) *
sin.tsoft, col = grid.col, lty = grid.lty)
}
}
}
if (plot.type == "barplot" | plot.type == "dotplot") {
options(warn = -1)
if (!is.null(error.bar.inf)) {
arrows(x0 = length.values * cos.t, x1 = length.arrow.inf *
cos.t, y0 = length.values * sin.t, y1 = length.arrow.inf *
sin.t, lwd = 1, col = error.bar.col, angle = 90,
length = 0.04)
}
if (!is.null(error.bar.sup)) {
arrows(x0 = length.values * cos.t, x1 = length.arrow.sup *
cos.t, y0 = length.values * sin.t, y1 = length.arrow.sup *
sin.t, lwd = 1, col = error.bar.col, angle = 90,
length = 0.04)
}
options(warn = 1)
}
if (show.box) {
if (tree.open.crown) {
lines(c(xx1, rev(xx2)), c(yy1, rev(yy2)), col = 1)
}
else {
lines(xx1, yy1, col = 1)
lines(xx2, yy2, col = 1)
}
}
if (show.trait) {
if (tree.open.crown) {
theta.trait <- theta.soft[length(theta.soft)]
}
else {
if (show.data.axis & (plot.type == "barplot" |
plot.type == "dotplot")) {
theta.trait <- theta[length(theta)] - (360 -
real.open) * (1/3) * pi/180
}
else {
theta.trait <- theta[length(theta)] - (360 -
real.open) * (1/2) * pi/180
}
}
cos.ttrait <- cos(pi/2 - theta.trait)
sin.ttrait <- sin(pi/2 - theta.trait)
segments(x0 = length.ring1 * cos.ttrait, x1 = length.ring2 *
cos.ttrait, y0 = length.ring1 * sin.ttrait,
y1 = length.ring2 * sin.ttrait, lwd = 20, col = trait.bg.col[i])
text(x = (length.ring1 + length.ring2)/2 * cos.ttrait,
y = (length.ring1 + length.ring2)/2 * sin.ttrait,
labels = trait.labels[i], col = trait.col[i],
cex = trait.cex[i], font = trait.font[i], srt = ifelse(theta.trait >
0 | theta.trait < -pi, (pi/2 - theta.trait) *
180/pi, (-pi/2 - theta.trait) * 180/pi))
}
}
if (show.tip) {
length.tipsline <- (length.phylo + length.intergr *
(n.traits + 1) + length.gr * (n.traits))
tip.xlim <- c(-1, 1)
if (tip.adj < 0.5)
tip.xlim[1] <- -tip.adj/0.5
if (tip.adj > 0.5)
tip.xlim[2] <- -2 * tip.adj + 2
for (i in 1:n.tips) {
text(x = length.tipsline * cos.t[i], y = length.tipsline *
sin.t[i], labels = tip.labels[i], adj = ifelse(theta[i] >
0 | theta[i] < -pi, 0, 1), col = tip.col[i],
cex = tip.cex[i], font = tip.font[i], srt = ifelse(theta[i] >
0 | theta[i] < -pi, (pi/2 - theta[i]) * 180/pi,
(-pi/2 - theta[i]) * 180/pi))
}
}
}
par(mar = par.mar0, xpd = par.xpd0, lend = par.lend0)
invisible()
}
|
setMethod("print", "sysModel",
function(x, ...)
{
cat("System of Equations Model\n")
cat("*************************\n")
type <- gsub("s", "", is(x)[1])
cat("Moment type: ", strsplit(type, "G")[[1]][1], "\n",
sep = "")
cat("Covariance matrix: ", x@vcov, sep = "")
if (x@vcov == "HAC") {
option <- x@vcovOptions
cat(" with ", option$kernel, " kernel and ")
if (is.numeric(option$bw))
cat("Fixed bandwidth (", round(option$bw, 3), ")", sep = "")
else cat(option$bw, " bandwidth", sep = "")
}
cat("\n")
d <- modelDims(x)
for (i in 1:length(d$eqnNames))
cat(d$eqnNames[i], ": coefs=", d$k[i],
", moments=", d$q[i], ", number of Endogenous: ",
sum(d$isEndo[[i]]), "\n", sep="")
cat("Sample size: ", d$n, "\n")
})
setMethod("show", "sysModel", function(object) print(object))
setMethod("modelDims", "slinearModel",
function(object) {
list(q=object@q, k=object@k, n=object@n, parNames=object@parNames,
momNames=object@momNames, eqnNames=object@eqnNames,
isEndo=object@isEndo)
})
setMethod("modelDims", "snonlinearModel",
function(object) {
list(k=object@k, q=object@q, n=object@n, parNames=object@parNames,
momNames=object@momNames, theta0=object@theta0,
fRHS=object@fRHS, fLHS=object@fLHS, eqnNames=object@eqnNames,
isEndo=object@isEndo)
})
setMethod("setCoef", signature("sysModel"),
function(model, theta) {
spec <- modelDims(model)
k <- sum(spec$k)
if (!is.list(theta))
{
if (length(theta) != k)
stop(paste("Wrong number of coefficients (should be ",
k, ")", sep=""))
if (!is.null(names(theta)))
{
parNames <- do.call("c", spec$parNames)
if (any(duplicated(names(theta))))
stop("Cannot have more than one coefficient with the same name")
chk <- !(names(theta) %in% parNames)
if (any(chk))
{
mes <- "The following coefficients have invalid name: "
mes <- paste(mes, paste(names(theta)[chk], collapse=", ",
sep=""), sep="")
stop(mes)
}
theta <- theta[match(parNames, names(theta))]
}
theta <- .tetReshape(theta, spec$eqnNames, spec$parNames)
} else {
if (length(theta) != length(spec$eqnNames))
stop("Wrong number of equations")
if (is.null(names(theta)))
{
names(theta) <- spec$eqnNames
} else {
if(!all(names(theta) %in% spec$eqnNames))
stop("Wrong equation names")
theta <- theta[match(spec$eqnNames,names(theta))]
}
chk <- sapply(1:length(theta), function(i)
length(theta[[i]]) == length(spec$parNames[[i]]))
if (!all(chk))
{
mes <- "Wrong number of coefficients in the following equation: "
mes <- paste(mes, paste(names(theta)[!chk], collapse=", ", sep=""),
sep="")
stop(mes)
}
theta <- lapply(1:length(theta), function(i) {
ti <- theta[[i]]
if (is.null(names(ti)))
{
names(ti) <- spec$parNames[[i]]
} else {
if (!all(names(ti) %in% spec$parNames[[i]]))
stop(paste("Wrong coefficient names in equation ",
names(theta)[i], sep=""))
ti <- ti[match(spec$parNames[[i]], names(ti))]
}
ti})
names(theta) <- spec$eqnNames
}
theta
})
setMethod("[", c("sysModel", "missing", "list"),
function(x, i, j){
if (length(j) != length(x@q))
stop("j must be a list with a length equals to the number of equations")
spec <- modelDims(x)
x@SUR <- FALSE
if (x@sameMom)
{
chk <- sapply(j[-1], function(ji) identical(ji, j[[1]]))
if (!all(chk))
x@sameMom <- FALSE
}
for (s in 1:length(j))
{
if (length(j[[s]]) > 0)
{
q <- spec$q[s]
if (!all(abs(j[[s]]) %in% (1:q)))
stop("SubMoment must be between 1 and q")
momNames <- spec$momNames[[s]][j[[s]]]
if (length(momNames)<spec$k[s])
{
error <- paste("Equation", s, "is under-identified")
stop(error)
}
if (momNames[1] == "(Intercept)")
{
f <- reformulate(momNames[-1], NULL, TRUE)
} else {
f <- reformulate(momNames, NULL, FALSE)
}
attr(f, ".Environment")<- .GlobalEnv
x@q[s] <- length(momNames)
x@instT[[s]] <- terms(f)
x@momNames[[s]] <- momNames
}
}
x
})
setMethod("[", c("snonlinearModel", "numeric", "missing"),
function(x, i, j){
i <- unique(as.integer(i))
spec <- modelDims(x)
neqn <- length(spec$k)
if (!all(abs(i) %in% (1:neqn)))
stop("Selected equations out of range")
x@fLHS <- x@fLHS[i]
x@fRHS <- x@fRHS[i]
if (length(x@fLHS) == 0)
stop("Removed too many equations; the model is empty")
x@instT <- x@instT[i]
x@k=x@k[i]
x@q <- x@q[i]
x@parNames <- x@parNames[i]
x@momNames <- x@momNames[i]
x@eqnNames <- x@eqnNames[i]
x@theta0 <- x@theta0[i]
x@varNames <- x@varNames[i]
x@isEndo <- x@isEndo[i]
x@SUR <- FALSE
if (length(x@q) > 1)
return(x)
instF <- model.frame(x@instT[[1]], x@data)
varN <- c(all.vars(x@fLHS[[1]]), all.vars(x@fRHS[[1]]))
varN <- varN[!(varN%in%names(x@theta0[[1]]))]
modelF <- x@data[,varN, drop=FALSE]
new("nonlinearModel", instF=instF, modelF=modelF, q=x@q[[1]],
fLHS=x@fLHS[[1]], fRHS=x@fRHS[[1]], theta0=x@theta0[[1]],
k=x@k[[1]], parNames=x@parNames[[1]], momNames=x@momNames[[1]],
vcov=x@vcov, n=spec$n,vcovOptions=x@vcovOptions,
centeredVcov=x@centeredVcov, varNames=x@varNames[[1]],
isEndo=x@isEndo[[1]], survOptions=x@survOptions, smooth=FALSE)
})
setMethod("[", c("slinearModel", "numeric", "missing"),
function(x, i, j){
i <- unique(as.integer(i))
spec <- modelDims(x)
neqn <- length(spec$k)
if (!all(abs(i) %in% (1:neqn)))
stop("Selected equations out of range")
x@modelT <- x@modelT[i]
if (length(x@modelT) == 0)
stop("Removed too many equations; the model is empty")
x@instT <- x@instT[i]
x@k=x@k[i]
x@q <- x@q[i]
x@parNames <- x@parNames[i]
x@momNames <- x@momNames[i]
x@eqnNames <- x@eqnNames[i]
x@varNames <- x@varNames[i]
x@isEndo <- x@isEndo[i]
x@SUR <- FALSE
if (length(x@q) > 1)
return(x)
instF <- model.frame(x@instT[[1]], x@data)
modelF <- model.frame(x@modelT[[1]], x@data)
new("linearModel", instF=instF, modelF=modelF, q=x@q[[1]],
k=x@k[[1]], parNames=x@parNames[[1]], momNames=x@momNames[[1]],
vcov=x@vcov, n=spec$n, vcovOptions=x@vcovOptions,
centeredVcov=x@centeredVcov, varNames=x@varNames[[1]],
isEndo=x@isEndo[[1]],survOptions=x@survOptions,
sSpec=new("sSpec"), smooth=FALSE)
})
setMethod("[", c("sysModel", "numeric", "list"),
function(x, i, j){
x <- x[i]
if (!inherits(x, "sysModel"))
{
if (length(j)>1)
warning("length(j)>1, only the first element used")
x[,j[[1]]]
} else {
x[,j]
}
})
setMethod("[", c("sysModel", "missing", "missing"),
function(x, i, j) x)
setMethod("subset", "sysModel",
function(x, i) {
x@data <- x@data[i,,drop=FALSE]
if (!is.null(x@vcovOptions$cluster))
{
if (!is.null(dim(x@vcovOptions$cluster)))
x@vcovOptions$cluster <- x@vcovOptions$cluster[i]
else
x@vcovOptions$cluster <- x@vcovOptions$cluster[i,,drop=FALSE]
}
x@n <- nrow(x@data)
x})
setGeneric("merge")
setMethod("merge", c("linearModel", "linearModel"),
function(x, y, ...) {
all <- c(list(x), y, list(...))
cl <- sapply(all, class)
if (any(cl != "linearModel"))
stop("Can only merge linearModel with other linearModel models")
n <- sapply(all, function(s) modelDims(s)$n)
if (any(n[-1L] != n[1L]))
stop("You can only merge models with the same number of observations")
k <- sapply(all, function(s) modelDims(s)$k)
q <- sapply(all, function(s) modelDims(s)$q)
parNames <- lapply(all, function(s) modelDims(s)$parNames)
momNames <- lapply(all, function(s) modelDims(s)$momNames)
varNames <- lapply(all, function(s) s@varNames)
isEndo <- lapply(all, function(s) s@isEndo)
instT <- lapply(all, function(s) terms(s@instF))
modelT <- lapply(all, function(s) terms(s@modelF))
dat <- do.call(cbind, lapply(all, function(s) cbind(s@modelF, s@instF)))
dat <- dat[,!duplicated(colnames(dat))]
eqnNames <- paste("Eqn", 1:length(all), sep="")
new("slinearModel", data=dat, instT=instT, modelT=modelT,
eqnNames=eqnNames, vcov=x@vcov, vcovOptions=x@vcovOptions,
centeredVcov = x@centeredVcov, k=k, q=q, n=n[1], parNames=parNames,
momNames=momNames, sameMom=FALSE, isEndo=isEndo, varNames=varNames,
SUR=FALSE,survOptions=x@survOptions,
sSpec=new("sSpec"), smooth=FALSE)
})
setMethod("merge", c("nonlinearModel", "nonlinearModel"),
function(x, y, ...) {
all <- c(list(x), y, list(...))
cl <- sapply(all, class)
if (any(cl != "nonlinearModel"))
stop("Can only merge nonlinearModel with oter nonlinearModel models")
n <- sapply(all, function(s) modelDims(s)$n)
if (any(n[-1L] != n[1L]))
stop("You can only merge models with the same number of observations")
fRHS <- lapply(all, function(s) s@fRHS)
fLHS <- lapply(all, function(s) s@fLHS)
k <- sapply(all, function(s) modelDims(s)$k)
q <- sapply(all, function(s) modelDims(s)$q)
parNames <- lapply(all, function(s) modelDims(s)$parNames)
momNames <- lapply(all, function(s) modelDims(s)$momNames)
varNames <- lapply(all, function(s) s@varNames)
isEndo <- lapply(all, function(s) s@isEndo)
instT <- lapply(all, function(s) terms(s@instF))
theta0 <- lapply(all, function(s) s@theta0)
eqnNames <- paste("Eqn", 1:length(all), sep="")
dat <- do.call(cbind, lapply(all, function(s) cbind(s@modelF, s@instF)))
dat <- dat[,!duplicated(colnames(dat))]
new("snonlinearModel", data=dat, instT=instT,
theta0=theta0,fRHS=fRHS,eqnNames=eqnNames,
fLHS=fLHS, vcov=x@vcov, vcovOptions=x@vcovOptions,
centeredVcov = x@centeredVcov, k=k, q=q,
n=n[1], parNames=parNames, isEndo=isEndo, varNames=varNames,
momNames=momNames, sameMom=FALSE, SUR=FALSE,
survOptions=x@survOptions, sSpec=new("sSpec"), smooth=FALSE)
})
setMethod("merge", c("snonlinearModel", "nonlinearModel"),
function(x, y, ...) {
all <- c(list(y), list(...))
cl <- sapply(all, class)
if (any(cl != "nonlinearModel"))
stop("Can only merge nonlinearModel with oter nonlinearModel models")
n <- sapply(all, function(s) modelDims(s)$n)
spec <- modelDims(x)
if (any(n != spec$n))
stop("You can only merge models with the same number of observations")
fRHS <- c(spec$fRHS, lapply(all, function(s) modelDims(s)$fRHS))
fLHS <- c(spec$fLHS, lapply(all, function(s) modelDims(s)$fLHS))
k <- c(spec$k, sapply(all, function(s) modelDims(s)$k))
q <- c(spec$q, sapply(all, function(s) modelDims(s)$q))
parNames <- c(spec$parNames, lapply(all, function(s) modelDims(s)$parNames))
momNames <- c(spec$momNames, lapply(all, function(s) modelDims(s)$momNames))
varNames <- c(x@varNames, lapply(all, function(s) s@varNames))
isEndo <- c(x@isEndo, lapply(all, function(s) s@isEndo))
instT <- c(x@instT, lapply(all, function(s) terms(s@instF)))
theta0 <- c(spec$theta0, lapply(all, function(s) modelDims(s)$theta0))
eqNames <- x@eqnNames
eqnNames <- c(eqNames, paste("Eqn",
(length(eqNames)+1):length(fRHS), sep=""))
dat <- do.call(cbind, lapply(all, function(s) cbind(s@modelF, s@instF)))
dat <- dat[,!duplicated(colnames(dat))]
new("snonlinearModel", data=dat, instT=instT,
theta0=theta0,fRHS=fRHS,eqnNames=eqnNames,
fLHS=fLHS, vcov=x@vcov,vcovOptions=x@vcovOptions,
centeredVcov = x@centeredVcov, k=k, q=q,
n=n[1], parNames=parNames, isEndo=isEndo, varNames=varNames,
momNames=momNames, sameMom=FALSE, SUR=FALSE,
survOptions=x@survOptions, sSpec=new("sSpec"), smooth=FALSE)
})
setMethod("merge", c("slinearModel", "linearModel"),
function(x, y, ...) {
all <- c(list(y), list(...))
cl <- sapply(all, class)
if (any(cl != "linearModel"))
stop("Can only merge linearModel with other linearModel models")
n <- sapply(all, function(s) modelDims(s)$n)
spec <- modelDims(x)
if (any(n != spec$n))
stop("You can only merge models with the same number of observations")
k <- c(spec$k, sapply(all, function(s) modelDims(s)$k))
q <- c(spec$q, sapply(all, function(s) modelDims(s)$q))
parNames <- c(spec$parNames, lapply(all, function(s) modelDims(s)$parNames))
momNames <- c(spec$momNames, lapply(all, function(s) modelDims(s)$momNames))
varNames <- c(x@varNames, lapply(all, function(s) s@varNames))
isEndo <- c(x@isEndo, lapply(all, function(s) s@isEndo))
instT <- c(x@instT, lapply(all, function(s) terms(s@instF)))
modelT <- c(x@modelT, lapply(all, function(s) terms(s@modelF)))
dat <- do.call(cbind, lapply(all, function(s) cbind(s@modelF, s@instF)))
dat <- dat[,!duplicated(colnames(dat))]
eqNames <- x@eqnNames
eqnNames <- c(eqNames, paste("Eqn",
(length(eqNames)+1):length(instT), sep=""))
new("slinearModel", data=dat, instT=instT, modelT=modelT,
eqnNames=eqnNames, vcov=x@vcov, vcovOptions=x@vcovOptions,
centeredVcov = x@centeredVcov, k=k, q=q, n=n[1], parNames=parNames,
momNames=momNames, sameMom=FALSE, isEndo=isEndo, varNames=varNames,
SUR=FALSE, survOptions=x@survOptions, sSpec=new("sSpec"), smooth=FALSE)
})
setMethod("residuals", "sysModel",
function(object, theta) {
neqn <- length(object@eqnNames)
r <- sapply(1:neqn, function(i) residuals(object[i], theta[[i]]))
colnames(r) <- object@eqnNames
r
})
setMethod("Dresiduals", "sysModel",
function(object, theta) {
neqn <- length(object@eqnNames)
if (missing(theta))
r <- sapply(1:neqn, function(i) Dresiduals(object[i]))
else
r <- sapply(1:neqn, function(i) Dresiduals(object[i], theta[[i]]))
names(r) <- object@eqnNames
r
})
setMethod("evalMoment", "sysModel",
function(object, theta) {
neqn <- length(object@eqnNames)
gt <- lapply(1:neqn, function(i) evalMoment(object[i], theta[[i]]))
names(gt) <- object@eqnNames
gt
})
setMethod("evalDMoment", "sysModel",
function(object, theta) {
neqn <- length(object@eqnNames)
if (missing(theta))
dgt <- lapply(1:neqn, function(i) evalDMoment(object[i]))
else
dgt <- lapply(1:neqn, function(i) evalDMoment(object[i], theta[[i]]))
names(dgt) <- object@eqnNames
dgt
})
setMethod("model.matrix", "slinearModel",
function(object, type = c("regressors", "instruments")) {
type <- match.arg(type)
mm <- lapply(1:length(object@eqnNames), function(i)
model.matrix(object[i], type))
names(mm) <- object@eqnNames
mm
})
setMethod("model.matrix", "snonlinearModel",
function(object, type = c("regressors", "instruments"))
{
type <- match.arg(type)
if (type == "regressors")
stop("no model.matrix of type regressors for nonlinear Model. set type to 'instruments' to get the matrix of instruments")
mm <- lapply(1:length(object@eqnNames), function(i)
model.matrix(object[i], type))
names(mm) <- object@eqnNames
mm
})
.SigmaZZ <- function(ZZ, Sigma, dimr, dimc=NULL, lowerTri=FALSE, isSym=TRUE)
{
r1 <- 1
c1 <- 1
if (is.null(dimc))
dimc <- dimr
for (i in 1:length(dimr))
{
r2 <- sum(dimr[1:i])
start <- ifelse(isSym, i, 1)
for (j in start:length(dimc))
{
c2 <- sum(dimc[1:j])
ZZ[r1:r2, c1:c2] <- ZZ[r1:r2, c1:c2]*Sigma[i,j]
c1 <- c1+dimc[j]
}
r1 <- r1+dimr[i]
c1 <- ifelse(isSym, sum(dimc[1:i])+1, 1)
}
if (lowerTri && isSym)
ZZ[lower.tri(ZZ)] <- t(ZZ)[lower.tri(ZZ)]
ZZ
}
setMethod("evalWeights", "sysModel",
function(object, theta = NULL, w="optimal", wObj=NULL)
{
spec <- modelDims(object)
sameMom <- object@sameMom
n <- object@n
neqn <- length(spec$eqnNames)
if (is.matrix(w))
{
if (!all(dim(w) == sum(spec$q)))
stop("The weights matrix has the wrong dimension")
}
if (is.matrix(w) || (w == "ident"))
{
return(new("sysMomentWeights", type="weights",momNames=object@momNames,
wSpec=list(), w=w, Sigma=NULL, sameMom=sameMom,
eqnNames=object@eqnNames))
}
if (w != "optimal")
stop("w is either 'ident', 'optimal' or a matrix")
if (object@vcov == "iid")
{
e <- residuals(object, theta)
type <- "iid"
Sigma <- chol(crossprod(e)/n)
if (!is.null(wObj))
{
if (wObj@type != "iid")
stop("wObj must come from a model with iid errors")
if (ncol(wObj@w$qr) != spec$q[1])
stop("The qr decomposition has the wrong dimension")
w <- wObj@w
} else {
Z <- model.matrix(object, type="instruments")
if (sameMom)
{
w <- qr(Z[[1]]/sqrt(n))
} else {
w <- crossprod(do.call(cbind,Z))/n
}
}
} else if (object@vcov == "MDS") {
type <- "MDS"
gt <- evalMoment(object, theta)
w <- qr(do.call(cbind, gt)/sqrt(n))
Sigma <- NULL
} else {
stop("Only identity, iid and MDS if allowed for now")
}
return(new("sysMomentWeights", type=type,momNames=object@momNames,
wSpec=list(), w=w, Sigma=Sigma, sameMom=sameMom,
eqnNames=object@eqnNames))
})
setMethod("evalGmmObj", signature("sysModel", "list", "sysMomentWeights"),
function(object, theta, wObj, ...)
{
gt <- evalMoment(object, theta)
gt <- lapply(gt, function(g) colMeans(g))
gt <- do.call("c", gt)
n <- object@n
obj <- quadra(wObj, gt)
n*obj
})
setMethod("evalGmm", signature("sysModel"),
function(model, theta, wObj=NULL, ...) {
Call <- try(match.call(call=sys.call(sys.parent())), silent=TRUE)
if (inherits(Call,"try-error"))
Call <- NULL
theta <- setCoef(model, theta)
if (is.null(wObj))
wObj <- evalWeights(model, theta)
new("sgmmfit", theta=theta, convergence=NULL, convIter=NULL,
call=Call, type="eval", wObj=wObj, niter=0L, efficientGmm=FALSE,
model=model)
})
setMethod("modelResponse", signature("slinearModel"),
function(object)
{
neqn <- length(object@eqnNames)
Y <- lapply(1:neqn, function(i) modelResponse(object[i]))
Y
})
.GListToMat <- function(G, full=FALSE)
{
if (full)
return(do.call(rbind, G))
dimG <- sapply(G, dim)
Gmat <- matrix(0, sum(dimG[1,]), sum(dimG[2,]))
r1 <- 1
c1 <- 1
for (i in 1:length(G)) {
r2 <- sum(dimG[1,1:i])
c2 <- sum(dimG[2,1:i])
Gmat[r1:r2, c1:c2] <- as.matrix(G[[i]])
r1 <- r1 + dimG[1,i]
c1 <- sum(dimG[2,1:i]) + 1
}
Gmat
}
.tetReshape <- function(theta, eqnNames, parNames)
{
if (is.list(theta))
{
theta2 <- do.call("c", theta)
k <- sapply(parNames, length)
tn <- paste(rep(eqnNames, k), ".", do.call("c", parNames),
sep = "")
names(theta2) <- tn
} else {
k <- cumsum(sapply(parNames, length))
names(theta) <- do.call("c", parNames)
theta2 <- list(theta[1:k[1]])
if (length(k)>1)
theta2[2:length(k)] <- lapply(2:length(k),
function(i) theta[(k[i-1]+1):k[i]])
names(theta2) <- eqnNames
}
theta2
}
setMethod("solveGmm", c("slinearModel", "sysMomentWeights"),
function(object, wObj, theta0 = NULL) {
if (wObj@type=="iid" && object@sameMom)
return(ThreeSLS(object, Sigma=wObj@Sigma, qrZ=wObj@w, coefOnly=TRUE))
spec <- modelDims(object)
Y <- modelResponse(object)
Z <- model.matrix(object, type="instruments")
Syz <- lapply(1:length(Y),
function(i) colMeans(Y[[i]]*Z[[i]]))
Syz <- do.call("c", Syz)
G <- evalDMoment(object)
G <- .GListToMat(G)
T1 <- quadra(wObj, G)
T2 <- quadra(wObj, G, Syz)
theta <- -solve(T1, T2)
theta <- .tetReshape(theta, object@eqnNames, object@parNames)
list(theta=theta, convergence=NULL)
})
setMethod("solveGmm", signature("snonlinearModel", "sysMomentWeights"),
function (object, wObj, theta0 = NULL, ...)
{
if (is.null(theta0))
theta0 <- modelDims(object)$theta0
else
theta0 <- setCoef(object, theta0)
g <- function(theta, wObj, object){
spec <- modelDims(object)
theta <- .tetReshape(theta, object@eqnNames, spec$parNames)
evalGmmObj(object, theta, wObj)
}
dg <- function(theta, wObj, object) {
spec <- modelDims(object)
theta <- .tetReshape(theta, object@eqnNames, spec$parNames)
gt <- evalMoment(object, theta)
gt <- do.call(cbind, gt)
n <- nrow(gt)
gt <- colMeans(gt)
G <- evalDMoment(object, theta)
full <- all(sapply(1:length(G), function(i) ncol(G[[i]])==sum(spec$k)))
G <- .GListToMat(G, full)
obj <- 2 * n * quadra(wObj, G, gt)
obj
}
spec <- modelDims(object)
theta0 <- .tetReshape(theta0, object@eqnNames, spec$parNames)
res <- optim(par = theta0, fn = g, gr = dg, method = "BFGS",
object = object, wObj = wObj, ...)
theta <- .tetReshape(res$par, spec$eqnNames, spec$parNames)
list(theta = theta, convergence = res$convergence)
})
setMethod("vcov", signature("sysModel"),
function(object, theta){
spec <- modelDims(object)
q <- spec$q
if (object@vcov == "MDS")
{
gt <- evalMoment(object, theta)
gt <- do.call(cbind, gt)
if (object@centeredVcov)
gt <- scale(gt, scale=FALSE)
w <- crossprod(gt)/nrow(gt)
} else if (object@vcov == "iid") {
e <- residuals(object, theta)
Sigma <- crossprod(e)/nrow(e)
Z <- model.matrix(object, "instrument")
if (object@sameMom)
{
w <- kronecker(Sigma, crossprod(Z[[1]])/nrow(e))
} else {
Z <- crossprod(do.call(cbind,Z))/nrow(e)
w <- .SigmaZZ(Z, Sigma, q)
}
} else {
stop("not yet implemented for HAC")
}
wn <- paste(rep(spec$eqnNames, q), ".", do.call("c", spec$momNames),
sep = "")
dimnames(w) <- list(wn,wn)
w
})
setMethod("tsls", "slinearModel",
function(model)
{
Call <- try(match.call(call=sys.call(sys.parent())), silent=TRUE)
if (inherits(Call,"try-error"))
Call <- NULL
neqn <- length(model@eqnNames)
res <- lapply(1:neqn, function(i) tsls(model[i]))
w <- lapply(1:neqn, function(i) quadra(res[[i]]@wObj))
w <- .GListToMat(w)
wObj <- evalWeights(model, w=w)
theta <- lapply(res, coef)
names(theta) <- model@eqnNames
new("stsls", theta=theta, convergence=NULL, convIter=NULL,
call=Call, type="tsls", wObj=wObj, niter=1L,
efficientGmm=FALSE, model=model)
})
setGeneric("ThreeSLS", function(model, ...) standardGeneric("ThreeSLS"))
setMethod("ThreeSLS", "slinearModel",
function(model, coefOnly=FALSE, qrZ=NULL, Sigma=NULL) {
Call <- try(match.call(call=sys.call(sys.parent())), silent=TRUE)
if (inherits(Call,"try-error"))
Call <- NULL
if (!inherits(model, "slinearModel"))
stop("3SLS is for slinearModel classes")
if (!model@sameMom)
stop("For 3SLS, the instruments must be the same in each equation")
efficientGmm <- model@vcov == "iid"
spec <- modelDims(model)
n <- spec$n
neqn <- length(model@eqnNames)
x <- model.matrix(model)
y <- modelResponse(model)
if (is.null(qrZ))
{
z <- model.matrix(model[1], "instruments")
qrZ <- qr(z/sqrt(n))
} else {
if (!inherits(qrZ,"qr"))
stop("qrZ must be the qr decomposition of Z")
if (ncol(qrZ$qr) != length(spec$momNames[[1]]))
stop("The qr decomposition has the wrong dimension")
}
if (is.null(Sigma))
{
theta <- lapply(1:neqn, function(i) lm.fit(qr.fitted(qrZ, x[[i]]),
y[[i]])$coefficients)
e <- residuals(model, theta)
Sigma <- chol(crossprod(e)/n)
} else {
if (!all(Sigma[lower.tri(Sigma)] == 0))
stop("Sigma must be a cholesky and therefore upper tiangular")
}
if (model@SUR)
{
xhat <- do.call(cbind, x)
type <- "SUR"
} else {
xhat <- qr.fitted(qrZ, do.call(cbind, x))
type <- "3SLS"
}
iSigma <- chol2inv(Sigma)
y <- do.call(cbind,y)
A <- crossprod(xhat)
A <- .SigmaZZ(A, iSigma, spec$k, spec$k, TRUE)
C <- crossprod(xhat, y)
C <- .SigmaZZ(C, iSigma, spec$k, rep(1, neqn), FALSE, FALSE)
C <- rowSums(C)
theta <- .tetReshape(solve(A, C), model@eqnNames, spec$parNames)
if (coefOnly)
return(list(theta=theta, convergence=NULL))
wObj <- new("sysMomentWeights", w=qrZ, Sigma=Sigma, type="iid",
momNames=spec$momNames,
wSpec=list(), sameMom=TRUE, eqnNames=model@eqnNames)
new("sgmmfit", theta=theta, convergence=NULL,
convIter=rep(NULL, neqn), call=Call, type=type, wObj=wObj,
niter=2L, efficientGmm=efficientGmm, model=model)
})
setMethod("gmmFit", signature("sysModel"), valueClass="sgmmfit",
function(model, type=c("twostep", "iter","cue", "onestep"),
itertol=1e-7, initW=c("ident", "tsls", "EbyE"), weights="optimal",
itermaxit=100, efficientWeights=FALSE, theta0=NULL,
EbyE=FALSE, ...)
{
Call <- try(match.call(call=sys.call(sys.parent())), silent=TRUE)
if (inherits(Call,"try-error"))
Call <- NULL
chk <- validObject(model)
type <- match.arg(type)
initW <- match.arg(initW)
i <- 1L
chk <- validObject(model, TRUE)
if (!chk)
stop("model is not a valid moment Model object")
if (is.character(weights) && !(weights%in%c("optimal","ident")))
stop("weights is a matrix or one of 'optimal' or 'ident'")
spec <- modelDims(model)
if (all(spec$q==spec$k))
{
weights <- "ident"
type <- "onestep"
EbyE <- TRUE
} else if (type == "onestep" && !is.matrix(weights)) {
weights <- "ident"
EbyE <- TRUE
} else if (is.matrix(weights) || inherits(weights,"sysMomentWeights")) {
type <- "onestep"
EbyE <- FALSE
} else if (weights == "ident") {
type <- "onestep"
EbyE <- TRUE
}
if (EbyE)
{
neqn <- length(model@eqnNames)
res <- lapply(1:neqn, function(i)
gmmFit(model[i], type=type, weights=weights,itertol=itertol,
initW=initW, itermaxit=itermaxit,
efficientWeights=efficientWeights, theta0=theta0, ...))
theta <- lapply(res, coef)
convergence <- sapply(res, function(r) r@convergence)
if (is.list(convergence))
convergence <- do.call("c", convergence)
convIter <- sapply(res, function(r) r@convIter)
niter <- sapply(res, function(r) r@niter)
if (is.list(convIter))
convIter <- do.call("c", convIter)
type <- paste("EBE", type, sep="")
efficientGmm <- FALSE
if (is.character(weights) && weights=="ident")
{
wObj <- evalWeights(model, NULL, "ident")
} else {
wObj <- lapply(res, function(r) quadra(r@wObj))
wObj <- .GListToMat(wObj)
wObj <- evalWeights(model, w=wObj)
}
ans <- new("sgmmfit", theta=theta, convergence=convergence,
convIter=convIter, call=Call, type=type, wObj=wObj,
niter=niter, efficientGmm=efficientGmm, model=model)
return(ans)
}
if (type == "onestep")
{
if (inherits(weights,"sysMomentWeights"))
wObj <- weights
else
wObj <- evalWeights(model, w=weights)
res <- solveGmm(model, wObj, theta0, ...)
convergence <- res$convergence
efficientGmm <- efficientWeights
ans <- new("sgmmfit", theta=res$theta,
convergence=convergence, convIter=NULL, type=type,
wObj=wObj, model=model, call=Call, niter=i,
efficientGmm=efficientGmm)
return(ans)
}
if (type == "twostep")
{
itermaxit <- 1
if (inherits(model, "slinearModel"))
{
if (model@vcov=="iid" && !model@sameMom && !model@SUR)
type <- "FIVE"
if (initW=="tsls" && model@vcov=="iid" && model@sameMom)
{
obj <- ThreeSLS(model)
obj@call <- Call
}
}
}
if (initW=="tsls")
{
theta0 <- try(coef(tsls(model)), silent=TRUE)
if (inherits(theta0,"try-error"))
stop("Cannot get the initial weights using 2SLS")
} else if (initW == "EbyE") {
neqn <- length(model@eqnNames)
res <- lapply(1:neqn, function(i)
gmmFit(model[i], type=type, weights=weights,itertol=itertol,
itermaxit=itermaxit,
efficientWeights=efficientWeights, theta0=theta0, ...))
theta0 <- lapply(res, coef)
} else {
wObj <- evalWeights(model, NULL, "ident")
theta0 <- solveGmm(model, wObj, theta0, ...)$theta
}
bw <- model@vcovOptions$bw
if (type != "cue")
{
while(TRUE)
{
if (i>1 && model@vcov=="iid")
wObj0 <- wObj
else
wObj0 <- NULL
wObj <- evalWeights(model, theta0, "optimal", wObj0)
if (model@vcov=="HAC" && is.character(model@bw))
model@vcovOptions$bw <- wObj@wSpec$bw
res <- solveGmm(model, wObj, theta0, ...)
theta1 <- res$theta
convergence <- res$convergence
tet0 <- do.call("c", theta0)
dif1 <- do.call("c", theta1)-tet0
crit <- sqrt(sum(dif1^2))/(1+sqrt(sum(tet0^2)))
if (crit < itertol & type=="iter")
{
convIter <- 0
break
}
i <- i + 1L
theta0 <- theta1
if (i>itermaxit)
{
if (type %in% c("twostep", "FIVE"))
convIter <- NULL
else
convIter <- 1
break
}
}
} else {
convIter <- NULL
if (model@vcov=="HAC" && is.character(bw))
{
w <- vcov(model, theta0)
model@vcovOptions$bw <- attr(w, "Spec")$bw
}
if (model@vcov == "iid")
wObj0 <- evalWeights(model, theta0)
else
wObj0 <- NULL
obj <- function(theta, model, wObj0, spec)
{
theta <- .tetReshape(theta, model@eqnNames,
spec$parNames)
wObj <- evalWeights(model, theta, "optimal", wObj0)
evalGmmObj(model, theta, wObj)
}
res <- optim(do.call("c",theta0), obj, model=model, wObj0=wObj0,
spec=spec, ...)
theta1 <- .tetReshape(res$par, model@eqnNames,spec$parNames)
convergence <- res$convergence
wObj <- evalWeights(model, theta1, "optimal", wObj0)
}
model@vcovOptions$bw <- bw
new("sgmmfit", theta=theta1, convergence=convergence,
convIter=convIter, call=Call, type=type, wObj=wObj,
niter=i, efficientGmm=TRUE, model=model)
})
|
asRules <- function(model, compact=FALSE, ...) UseMethod("asRules")
asRules.rpart <- function(model, compact=FALSE, classes=NULL, ...)
{
if (!inherits(model, "rpart")) stop(Rtxt("Not a legitimate rpart tree"))
rtree <- length(attr(model, "ylevels")) == 0
target <- as.character(attr(model$terms, "variables")[2])
frm <- model$frame
names <- row.names(frm)
ylevels <- attr(model, "ylevels")
ds.size <- model$frame[1,]$n
if (rtree)
ordered <- rev(sort(frm$n, index=TRUE)$ix)
else
ordered <- rev(sort(frm$yval2[,5], index=TRUE)$ix)
for (i in ordered)
{
if (frm[i,1] == "<leaf>")
{
if (rtree)
yval <- frm[i,]$yval
else
yval <- ylevels[frm[i,]$yval]
if (is.null(classes) || yval %in% classes)
{
cover <- frm[i,]$n
pcover <- round(100*cover/ds.size)
if (! rtree) prob <- frm[i,]$yval2[,5]
cat("\n")
pth <- rpart::path.rpart(model, nodes=as.numeric(names[i]), print.it=FALSE)
pth <- unlist(pth)[-1]
if (! length(pth)) pth <- "True"
if (compact)
{
cat(sprintf("R%03s ", names[i]))
if (rtree)
cat(sprintf("[%2.0f%%,%0.2f]", pcover, prob))
else
cat(sprintf("[%2.0f%%,%0.2f]", pcover, prob))
cat(sprintf(" %s", pth), sep="")
}
else
{
cat(sprintf(Rtxt(" Rule number: %s "), names[i]))
if (rtree)
cat(sprintf("[%s=%s cover=%d (%.0f%%)]\n",
target, yval, cover, pcover))
else
cat(sprintf("[%s=%s cover=%d (%.0f%%) prob=%0.2f]\n",
target, yval, cover, pcover, prob))
cat(sprintf(" %s\n", pth), sep="")
}
}
}
}
cat("\n")
invisible(ordered)
}
|
costing_model <- function(type, ...) {
costing <- jsonlite::unbox(type)
costing_options <- list(...)
costing_options <- Filter(function(df) nrow(df) > 0L, costing_options)
if (length(costing_options) == 0L)
return(list(costing = costing))
costing_options <- lapply(
costing_options,
jsonlite::unbox
)
structure(
list(
costing = costing,
costing_options = costing_options),
class = "mz_costing_model"
)
}
mz_costing <- list(
pedestrian = function(...) {
costing_model("pedestrian", pedestrian = data.frame(...))},
auto = function(...) {
costing_model("auto", auto = data.frame(...))},
bicycle = function(...) {
costing_model("bicycle", bicycle = data.frame(...))},
multimodal = function(transit = NULL, pedestrian = NULL) {
transit <- data.frame(transit)
pedestrian <- data.frame(pedestrian)
costing_model("multimodal", transit = transit, pedestrian = pedestrian)
}
)
costopt <- function(x, validate = assertthat::is.number) {
assertthat::assert_that(validate(x))
jsonlite::unbox(x)
}
mz_costing_options <- list(
pedestrian = list(
walking_speed = function(speed) list(walking_speed = costopt(speed)),
walkway_factor = function(factor) list(walkway_factor = costopt(factor)),
alley_factor = function(factor) list(alley_factor = costopt(factor)),
driveway_factor = function(factor) list(driveway_factor = costopt(factor)),
step_penalty = function(seconds) list(step_penalty = costopt(seconds))
),
auto = list(
maneuver_penalty = function(penalty) list(maneuver_penalty = costopt(penalty)),
gate_cost = function(cost) list(gate_cost = costopt(cost)),
toll_booth_cost = function(cost) list(toll_booth_cost = costopt(cost)),
toll_booth_penalty = function(penalty) list(toll_booth_penalty = costopt(penalty)),
ferry_cost = function(cost) list(ferry_cost = costopt(cost)),
use_ferry = function(value) list(use_ferry = costopt(value)),
country_crossing_cost = function(cost) list(country_crossing_cost = costopt(cost)),
country_crossing_penalty = function(penalty) list(country_crossing_penalty = costopt(penalty))
),
bicycle = list(
maneuver_penalty = function(penalty) list(maneuver_penalty = costopt(penalty)),
gate_cost = function(cost) list(gate_cost = costopt(cost)),
country_crossing_cost = function(cost) list(country_crossing_cost = costopt(cost)),
country_crossing_penalty = function(penalty) list(country_crossing_penalty = costopt(penalty)),
bicycle_type = function(type) list(bicycle_type = costopt(bicycle_type, assertthat::is.string)),
cycling_speed = function(speed) list(cycling_speed = costopt(speed)),
use_roads = function(propensity) list(use_roads = costopt(propensity)),
use_hills = function(propensity) list(use_hills = costopt(propensity))
),
transit = list(
use_bus = function(value) list(use_bus = costopt(value)),
use_rail = function(value) list(use_rail = costopt(value)),
use_transfers = function(value) list(use_transfers = costopt(value)),
transit_start_end_max_distance = function(distance) list(transit_start_end_max_distance = costopt(distance)),
transit_transfer_max_distance = function(distance) list(transit_transfer_max_distance = costopt(distance))
)
)
|
build_site_github_pages <- function(pkg = ".",
...,
dest_dir = "docs",
clean = TRUE,
install = FALSE,
new_process = FALSE) {
pkg <- as_pkgdown(pkg, override = list(destination = dest_dir))
if (clean) {
rule("Cleaning files from old site", line = 1)
clean_site(pkg)
}
build_site(pkg, preview = FALSE, install = install, new_process = new_process, ...)
build_github_pages(pkg)
invisible()
}
build_github_pages <- function(pkg = ".") {
rule("Extra files for GitHub pages")
pkg <- as_pkgdown(pkg)
write_if_different(pkg, "", ".nojekyll", check = FALSE)
cname <- cname_url(pkg$meta$url)
if (is.null(cname)) {
return(invisible())
}
write_if_different(pkg, cname, "CNAME", check = FALSE)
invisible()
}
cname_url <- function(url) {
if (is.null(url))
return(NULL)
pieces <- xml2::url_parse(url)
if (!pieces$path %in% c("", "/"))
return(NULL)
pieces$server
}
|
tok_lst = list(c('the', 'the', 'tokens', 'of', 'first', 'document'),
c('the', 'tokens', 'of', 'of', 'second', 'document'),
c('the', 'tokens', 'of', 'third', 'third', 'document'))
vec_clust = rep(1:6, 3)
context('cluster-frequency function')
while(T) {
testthat::test_that("in case that the verbose parameter is not a boolean, it returns an error", {
cat("test-cluster_frequency.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( cluster_frequency(tok_lst, vec_clust, verbose = 'TRUE') )
})
testthat::test_that("it returns the correct output", {
res = cluster_frequency(tok_lst, vec_clust)
cat("test-cluster_frequency.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res, 'list') && inherits(res[[1]], "data.table") && length(res) == length(tok_lst) )
})
break
}
|
library(fredr)
knitr::opts_chunk$set(
fig.width = 7,
fig.height = 5,
eval = fredr_has_key(),
collapse = TRUE,
comment = "
)
library(fredr)
fredr_category(category_id = 0L)
fredr_category(category_id = 97L)
fredr_category_children(category_id = 0L)
fredr_category_children(category_id = 1L)
fredr_category_related(category_id = 0L)
fredr_category_related(category_id = 4L)
fredr_category_series(
category_id = 97L,
limit = 100L,
order_by = "last_updated",
filter_variable = "frequency",
filter_value = "Quarterly"
)
fredr_category_series(
category_id = 32992L,
order_by = "frequency",
sort_order = "desc",
tag_names = "usa",
exclude_tag_names = "gnp"
)
fredr_category_tags(
category_id = 6L,
tag_group_id = "src"
)
fredr_category_tags(
category_id = 1L,
search_text = "usa",
order_by = "popularity",
sort_order = "desc"
)
fredr_category_related_tags(
category_id = 1L,
tag_names = "business;monthly",
exclude_tag_names = "rate",
order_by = "name"
)
|
Frank.Pareto = function(n,Theta,Alpha1,Alpha2,Gamma1,Gamma2) {
if (n < 1 | n != round(n)) {stop("sample size n must be greater than or equal to 1 (integer)")}
if (Theta == 0) {stop("Theta cannot be zero")}
if (Alpha1 <= 0) {stop("Alpha1 must be positive")}
if (Alpha2 <= 0) {stop("Alpha2 must be positive")}
if (Gamma1 <= 0) {stop("Gamma1 must be positive")}
if (Gamma2 <= 0) {stop("Gamma2 must be positive")}
U = runif(n)
a = runif(n)
V = (-1/Theta)*log(1+a*(exp(-Theta)-1)/(exp(-Theta*U)-a*(exp(-Theta*U)-1)))
X = (1/Alpha1)*(U^(-1/Gamma1)-1)
Y = (1/Alpha2)*(V^(-1/Gamma2)-1)
return(cbind(X,Y))
}
|
getpxqx <- function(Lx)
{
px <- Lx[-1] / Lx[-length(Lx)]
cbind(x=0:(length(Lx)-2), px=px, qx=1-px)
}
frac <- function(x) x-floor(x)
gettpx <- function(Lx, x, k, fractional=c("linear", "balducci", "constant"))
{
fractional <- match.arg(fractional, c("linear", "balducci", "constant"))
Flinear <- function(k)
{
pxleft <- Lx[floor(x)+floor(k)+1] / Lx[floor(x)+1]
pxright <- Lx[floor(x)+ceiling(k)+1] / Lx[floor(x)+1]
pxleft *(1-frac(k)) + frac(k)*pxright
}
Fbalducci <- function(k)
{
kpx <- Lx[floor(x)+floor(k)+1] / Lx[floor(x)+1]
pxk <- Lx[floor(x)+ceiling(k)+1] / Lx[floor(x)+floor(k)+1]
qxk <- 1-pxk
kpx* pxk/(1-(1-frac(k))*qxk)
}
Fconstant <- function(k)
{
kpx <- Lx[floor(x)+floor(k)+1] / Lx[floor(x)+1]
pxk <- Lx[floor(x)+ceiling(k)+1] / Lx[floor(x)+floor(k)+1]
kpx * pxk^frac(k)
}
if(fractional == "linear")
res <- sapply(k, Flinear)
else if(fractional == "balducci")
res <- sapply(k, Fbalducci)
else
res <- sapply(k, Fconstant)
res[k < 0] <- NaN
res
}
gettqx <- function(Lx, x, k, fractional=c("linear", "balducci", "constant"))
{
1-gettpx(Lx, x, k, fractional=c("linear", "balducci", "constant"))
}
getkpxqxk <- function(Lx, x)
{
matx <- getpxqx(Lx)
pxplus <- matx[,"px"][(x+1):length(matx[,"px"])]
cbind(k=0:length(pxplus), kpx=c(1, cumprod(pxplus)),
qxplusk=c(1-pxplus, 1))
}
|
download_ionicons <- function(version = "dev"){
if(version == "dev"){
url <- "https://github.com/ionic-team/ionicons/archive/master.zip"
}
else{
url <- glue("https://github.com/ionic-team/ionicons/archive/{version}.zip")
}
meta <- jsonlite::read_json("https://raw.githubusercontent.com/ionic-team/ionicons/master/package.json")
install_icon_zip(
"ionicons", url, c("src", "svg"),
meta = list(name = "Ionicons", version = meta$version, licence = meta$license)
)
invisible(ionicons)
}
ionicons <- new_icon_set(
"ionicons",
function(name){
icon_fn$get(name)
}
)
|
test_that("dropFeatures", {
fns = getTaskFeatureNames(multiclass.task)
task2 = dropFeatures(multiclass.task, fns[1])
expect_equal(length(getTaskFeatureNames(task2)), 3L)
})
|
check_gaps <- function(x){
if (any(has_gaps(x)$.gaps)) {
abort(sprintf("%s contains implicit gaps in time. You should check your data and convert implicit gaps into explicit missing values using `tsibble::fill_gaps()` if required.", deparse(substitute(x))))
}
}
check_regular <- function(x){
if (!is_regular(x)) {
abort(sprintf("%s is an irregular time series, which this decomposition does not support. You should consider if your data can be made regular, and use `tsibble::update_tsibble(%s, regular = TRUE)` if appropriate.", deparse(substitute(x)), deparse(substitute(x))))
}
}
check_ordered <- function(x){
if (!is_ordered(x)) {
abort(sprintf("%s is an unordered time series. To use this decomposition, you first must sort the data in time order using `dplyr::arrange(%s, %s)`",
deparse(substitute(x)), paste(c(deparse(substitute(x)), key_vars(x)), collapse = ", "), as_string(index(x))))
}
}
all_tsbl_checks <- function(.data){
check_gaps(.data)
check_regular(.data)
check_ordered(.data)
if(NROW(.data) == 0){
abort("There is no data to decompose. Please provide a dataset with at least one observation.")
}
}
|
micombine.cor <- function( mi.res, variables=NULL,
conf.level=.95, method="pearson", nested=FALSE, partial=NULL )
{
if (class(mi.res)=="data.frame"){
mi.res <- list( mi.res )
}
if ( class(mi.res)=="nested.datlist" ){
nested <- TRUE
}
if (! nested ){
mi.list <- datlist_create(mi.res)
}
if (nested ){
mi.list <- nested.datlist_create(mi.res)
}
Nimp <- attr( mi.list, "Nimp")
N <- attr( mi.list, "nobs_datasets")
vars <- attr(mi.list, "variables")
if (is.null(variables)){
variables <- vars
}
VV <- length(variables)
N_partial <- 0
if (!is.null(partial)){
if (! class(partial)=="formula"){
partial <- as.formula( paste0(" ~ ", paste0( partial, collapse="+")))
}
}
if (is.character(variables)){
if ( ! nested ){
variables <- which( vars %in% variables )
}
if ( nested ){
variables <- which( vars %in% variables )
}
}
dfr <- NULL
for ( i in 1:(VV-1) ){
for (j in (i+1):VV){
if (i !=j ){
ii <- variables[i]
jj <- variables[j]
if ( i !=j){
if ( ! nested ){
cor.ii.jj <- unlist( lapply( mi.list, FUN=function(dat){
dat_ii <- dat[,ii]
dat_jj <- dat[,jj]
if ( ! is.null(partial) ){
fm <- paste0( "dat_ii ", paste( partial, collapse=" ") )
mod_ii <- stats::lm( as.formula(fm), data=dat )
rii <- resid(mod_ii)
mii <- as.numeric(names( mod_ii$residuals))
dat_ii <- NA*dat_ii
dat_ii[ mii ] <- rii
fm <- paste0( "dat_jj ", paste( partial, collapse=" ") )
mod_jj <- stats::lm( as.formula(fm), data=dat )
rjj <- resid(mod_jj)
mjj <- as.numeric(names( mod_jj$residuals))
dat_jj <- NA*dat_jj
dat_jj[ mjj ] <- rjj
N_partial <- length( coef(mod_jj) ) - 1
}
stats::cor( dat_ii, dat_jj, method=method,
use="pairwise.complete.obs" )
} ) )
}
if ( nested){
cor.ii.jj <- lapply( mi.list, FUN=function(mm){
lapply( mm, FUN=function(dat){
if ( ! is.null(partial) ){
fm <- paste0( "dat_ii ", paste( partial, collapse=" ") )
mod_ii <- stats::lm( as.formula(fm), data=dat )
rii <- resid(mod_ii)
mii <- as.numeric(names( mod_ii$residuals))
dat_ii <- NA*dat_ii
dat_ii[ mii ] <- rii
fm <- paste0( "dat_jj ", paste( partial, collapse=" ") )
mod_jj <- stats::lm( as.formula(fm), data=dat )
rjj <- resid(mod_jj)
mjj <- as.numeric(names( mod_jj$residuals))
dat_jj <- NA*dat_jj
dat_jj[ mjj ] <- rjj
N_partial <- length( coef(mod_jj) ) - 1
}
dat_ii <- dat[,ii]
dat_jj <- dat[,jj]
stats::cor( dat_ii, dat_jj, method=method,
use="pairwise.complete.obs")
} ) } )
}
res.ii.jj <- micombine_cor_compute( cor.list=cor.ii.jj, N=N,
conf.level=conf.level, nested=nested,
Nimp=Nimp, N_partial=N_partial)
dfr <- rbind( dfr, c( ii, jj, res.ii.jj ) )
}
}
}
}
dfr1 <- dfr
dfr <- rbind( dfr, dfr1[, c(2,1,seq(3,ncol(dfr) )) ] )
dfr <- data.frame( "variable1"=vars[ dfr[,1] ],
"variable2"=vars[ dfr[,2] ], dfr[, -c(1:2) ] )
class(dfr) <- "data.frame"
m1 <- vector2matrix( index1=dfr$variable1, index2=dfr$variable2,
val=dfr$r, empty_val=1 )
attr(dfr,"r_matrix") <- m1
m1 <- vector2matrix( index1=dfr$variable1, index2=dfr$variable2,
val=dfr$rse, empty_val=NA )
attr(dfr,"rse_matrix") <- m1
return(dfr)
}
|
library("testthat")
library("mgcv")
library("gratia")
library("gamm4")
test_that("difference_smooths() works for a gam model", {
expect_silent(ds <- difference_smooths(su_m_factor_by, smooth = "s(x2)"))
expect_s3_class(ds, c("difference_smooth", "tbl_df", "tbl", "data.frame"))
plt <- draw(ds)
expect_doppelganger("draw difference_smooths gam", plt)
})
test_that("difference_smooths() works for a gam model fixed scales", {
expect_silent(ds <- difference_smooths(su_m_factor_by, smooth = "s(x2)"))
expect_s3_class(ds, c("difference_smooth", "tbl_df", "tbl", "data.frame"))
plt <- draw(ds, scales = "fixed")
expect_doppelganger("draw difference_smooths gam fixed scales", plt)
})
test_that("difference_smooths() works for a gam model fixed scales", {
expect_silent(ds <- difference_smooths(su_m_factor_by, smooth = "s(x2)"))
expect_s3_class(ds, c("difference_smooth", "tbl_df", "tbl", "data.frame"))
plt <- draw(ds, ref_line = TRUE)
expect_doppelganger("draw difference_smooths gam ref line", plt)
})
test_that("difference_smooths() works for a bam model", {
skip_on_cran()
expect_silent(ds <- difference_smooths(su_m_factor_by_bam,
smooth = "s(x2)"))
expect_s3_class(ds, c("difference_smooth", "tbl_df", "tbl", "data.frame"))
plt <- draw(ds)
expect_doppelganger("draw difference_smooths bam", plt)
})
test_that("difference_smooths() works for a gamm model", {
skip_on_cran()
skip_on_os(c("windows", "mac"))
expect_silent(ds <- difference_smooths(su_m_factor_by_gamm,
smooth = "s(x2)"))
expect_s3_class(ds, c("difference_smooth", "tbl_df", "tbl", "data.frame"))
plt <- draw(ds)
expect_doppelganger("draw difference_smooths gamm", plt)
})
test_that("difference_smooths() works for a gamm4 model", {
skip_on_cran()
skip_on_os(c("windows", "mac"))
expect_silent(ds <- difference_smooths(su_m_factor_by_gamm4,
smooth = "s(x2)"))
expect_s3_class(ds, c("difference_smooth", "tbl_df", "tbl", "data.frame"))
plt <- draw(ds)
expect_doppelganger("draw difference_smooths gamm4", plt)
})
|
creategrid <- function(dnpoint){
require(tcltk)
require(tkrplot)
if (is.null(class(dnpoint)) | class(dnpoint) != "dnpoint") {
cat("Argument is not of class 'dnpoint' \n")
return(invisible())
}
nsp <- length(dnpoint$Label)
long <- dnpoint$Points[,2]
lat <- dnpoint$Points[,3]
xlims <- range(long)
xlims <- xlims + c(-0.1*diff(xlims), 0.1*diff(xlims))
ylims <- range(lat)
ylims <- ylims + c(-0.1*diff(ylims), 0.1*diff(ylims))
origin <- NULL
xorvar <- tclVar(round(xlims[1], 3))
yorvar <- tclVar(round(ylims[2], 3))
latres <- longres <- 0
ncols <- tclVar("10")
nlins <- tclVar("10")
longgr <- tclVar(round(diff(xlims)/10, 3))
latgr <- tclVar(round(diff(ylims)/10, 3))
currentx <- tclVar()
currenty <- tclVar()
maxrich <- tclVar()
gridx <- gridy <- c()
modpar <- function(ruta) {
options(warn = -1)
if(ruta > 0) {
n <- as.integer(tclvalue(ncols))
if(is.na(n)) {tclvalue(ncols) <- 1; tkrreplot(img); return()}
if(ruta == 1) tclvalue(ncols) <- as.character(aux <- n + 1)
if(ruta == 2) tclvalue(ncols) <- as.character(aux <- n - 1)
if(ruta == 3) tclvalue(ncols) <- as.character(aux <- n)
if(aux < 1) tclvalue(ncols) <- "1"
if(aux > 9999) tclvalue(ncols) <- "9999"
tkrreplot(img)
}
if(ruta < 0) {
n <- as.integer(tclvalue(nlins))
if(is.na(n)) {tclvalue(nlins) <- 1; tkrreplot(img); return()}
if(ruta == -1) tclvalue(nlins) <- as.character(aux <- n + 1)
if(ruta == -2) tclvalue(nlins) <- as.character(aux <- n - 1)
if(ruta == -3) tclvalue(nlins) <- as.character(aux <- n)
if(aux < 1) tclvalue(nlins) <- "1"
if(aux > 9999) tclvalue(nlins) <- "9999"
tkrreplot(img)
}
}
curpos <- function (x, y) {
x <- as.numeric(x)
y <- as.numeric(y)
width <- as.numeric(tclvalue(tkwinfo("reqwidth",img)))
height <- as.numeric(tclvalue(tkwinfo("reqheight",img)))
if(any(c(x < 0, x > width, y < 0, y > height))) {return()}
rangeX <- diff(range(gridx))
rangeY <- diff(range(gridy))
auxx <- x/width
nx <- gridx[1] + auxx*rangeX
auxy <- y/height
ny <- gridy[1] - auxy*rangeY
return(c(nx, ny))
}
drawgrid <- function() {
gridx <<- seq(xlims[1], xlims[2], length.out = as.integer(tclvalue(ncols)) + 1)
gridy <<- seq(ylims[2], ylims[1], length.out = as.integer(tclvalue(nlins)) + 1)
tclvalue(latgr) <<- as.character(round(diff(ylims)/as.integer(tclvalue(nlins)), 3))
tclvalue(longgr) <<- as.character(round(diff(xlims)/as.integer(tclvalue(ncols)), 3))
par(bg = "cyan")
plot.new()
par(plt = c(0,1,0,1))
par(usr = c(xlims, ylims))
points(long, lat, pch = 19, xlab = "", ylab = "", col = "red")
abline(v = gridx, h = gridy)
if(!is.null(origin)) abline(v = origin[1], h = origin[2], col = 3, lwd = 2)
}
movegrid <- function(x, y) {
origin <<- c(x, y)
tclvalue(xorvar) <<- as.character(round(x, 3))
tclvalue(yorvar) <<- as.character(round(y, 3))
tkrreplot(img)
}
fixnewor <- function() {
if(is.na(as.numeric(tclvalue(xorvar)))) {
tkmessageBox(message= "Your NW_corner (x) is ambiguous. Previous value recovered", icon="warning")
tclvalue(xorvar) <<- as.character(round(xlims[1], 3))
}
if(is.na(as.numeric(tclvalue(yorvar)))) {
tkmessageBox(message= "Your NW_corner (y) is ambiguous. Previous value recovered", icon="warning")
tclvalue(yorvar) <<- as.character(round(ylims[2], 3))
}
auxx <- as.numeric(tclvalue(xorvar))
auxy <- as.numeric(tclvalue(yorvar))
if(auxx > max(long)) {
tkmessageBox(message= "Your NW_corner is beyond the right limit of data. Previous value recovered", icon="warning")
tclvalue(xorvar) <<- as.character(round(xlims[1], 3))
}
if(auxy < min(lat)) {
tkmessageBox(message= "Your NW_corner is below the bottom of data. Previous value recovered", icon="warning")
tclvalue(yorvar) <<- as.character(round(ylims[2], 3))
}
xlims[1] <<- round(as.numeric(tclvalue(xorvar)), 3)
ylims[2] <<- round(as.numeric(tclvalue(yorvar)), 3)
origin <<- NULL
tkrreplot(img)
}
changecell <- function(ruta) {
options(warn = -1)
if(ruta == 1) {
celh <- as.numeric(tclvalue(longgr))
if(is.na(celh)) {modpar(3); return()}
if(celh < (aux <- max(long) - xlims[1])) {
p <- ceiling(aux/celh)
xlims[2] <<- xlims[1] + p*celh
tclvalue(ncols) <<- as.character(p)
longres <<- celh
}
modpar(3)
}
if(ruta == 2) {
celv <- as.numeric(tclvalue(latgr))
if(is.na(celv)) {modpar(-3); return()}
if(celv < (aux <- ylims[2] - min(lat))) {
p <- ceiling(aux/celv)
ylims[1] <<- ylims[2] - p*celv
tclvalue(nlins) <<- as.character(p)
latres <<- celv
}
modpar(-3)
}
}
modalDialog <- function(title, question, entryInit, entryWidth = 20,
returnValOnCancel = "ID_CANCEL") {
dlg <- tktoplevel()
tkwm.deiconify(dlg)
tkgrab.set(dlg)
tkfocus(dlg)
tkwm.title(dlg, title)
textEntryVarTcl <- tclVar(paste(entryInit))
textEntryWidget <- tkentry(dlg, width = paste(entryWidth),
textvariable = textEntryVarTcl)
tkgrid(tklabel(dlg, text = " "))
tkgrid(tklabel(dlg, text = question), textEntryWidget)
tkgrid(tklabel(dlg, text = " "))
ReturnVal <- returnValOnCancel
onOK <- function() {
ReturnVal <<- tclvalue(textEntryVarTcl)
tkgrab.release(dlg)
tkdestroy(dlg)
tkfocus(tt)
}
onCancel <- function() {
ReturnVal <<- returnValOnCancel
tkgrab.release(dlg)
tkdestroy(dlg)
tkfocus(tt)
}
OK.but <- tkbutton(dlg, text = " OK ", command = onOK)
Cancel.but <- tkbutton(dlg, text = " Cancel ", command = onCancel)
tkgrid(OK.but, Cancel.but)
tkgrid(tklabel(dlg, text = " "))
tkfocus(dlg)
tkbind(dlg, "<Destroy>", function() {tkgrab.release(dlg); tkfocus(tt)})
tkbind(textEntryWidget, "<Return>", onOK)
tkwait.window(dlg)
return(ReturnVal)
}
outtable <- function() {
ngrx <- as.integer(tclvalue(ncols))
ngry <- as.integer(tclvalue(nlins))
if(diff(xlims) > 0) gridx <- seq(xlims[1], xlims[2], length.out = ngrx + 1) else gridx <- xlims + c(-1, 1)
if(diff(ylims) > 0) gridy <- seq(ylims[2], ylims[1], length.out = ngry + 1) else gridy <- ylims + c(1, -1)
difx <- diff(gridx)
dify <- diff(gridy)
cornersi <- expand.grid(1:ngrx, 1:ngry)
dntable <- matrix(0, nrow = nsp, ncol = nrow(cornersi))
rownames(dntable) <- dnpoint$Label
for(pts in 1:length(long)) {
auxx <- long[pts] - gridx
auxy <- lat[pts] - gridy
celx <- which(diff((auxx > 0) + 2*(auxx < 0))!=0)
cely <- which(diff((auxy > 0) + 2*(auxy < 0))!=0)
celocc <- celx[1] + (cely - 1)*ngrx
if(length(celx) == 2) celocc <- c(celocc, celx[2] + (cely - 1)*ngrx)
dntable[dnpoint$Points[pts, 1],celocc] <- 1
}
sel <- which(apply(dntable, 2, sum)>0)
cornersi[sel,1]-> xleft
cornersi[sel,2] + 1 -> ybottom
cornersi[sel, 1] + 1 -> xright
cornersi[sel,2] -> ytop
outobj <- list(dntable = dntable[, sel, drop = FALSE], xleft = xleft, ybottom = ybottom, xright = xright, ytop = ytop, ncells = c(ngrx, ngry))
return(outobj)
}
launchout <- function() {
ReturnVal <- modalDialog("Save data into an object", "Enter the variable name", "outgr")
if (ReturnVal == "ID_CANCEL") return()
out <- outtable()
outobj <- data.frame(rbind(colid = out$xleft, rowid = out$ytop, out$dntable))
assign(ReturnVal, outobj, envir = .GlobalEnv)
tkmessageBox(title = "Out", message = paste("The object ", ReturnVal, "holds your grid data"))
}
drawrich <- function(occmap){
gridx <- seq(xlims[1], xlims[2], length.out = as.integer(tclvalue(ncols)) + 1)
gridy <- seq(ylims[2], ylims[1], length.out = as.integer(tclvalue(nlins)) + 1)
par(bg = "white")
plot.new()
par(plt = c(0,1,0,1))
par(usr = c(xlims, ylims))
totrich <- apply(occmap$dntable, 2, sum)
rel <- totrich/max(totrich)
tclvalue(maxrich) <<- max(totrich)
rect(gridx[occmap$xleft], gridy[occmap$ybottom], gridx[occmap$xright], gridy[occmap$ytop], col = gray(1- rel))
abline(v = gridx, h = gridy, col = 2)
}
constructpdf <- function(){
filename <- tclvalue(tkgetSaveFile(initialfile = "Rplots.pdf",
defaultextension = ".pdf", title = "Save graph...",
filetypes = "{PDF {.pdf}} {{All Files} {*.*}}"))
if (filename != "") pdf(file = filename) else { tkrreplot(richplot); return()}
outdn <- outtable()
plot(rep(1, 4), 1:4, type = "n", xlab = "", ylab = "", axes = FALSE, main = "MAP OF OCCUPIED CELLS")
text(1, 1, paste("Grid of ", tclvalue(ncols), "cols and ", tclvalue(nlins), "rows"))
text(1, 2, paste("Northwest corner at: (", tclvalue(xorvar), ", ", tclvalue(yorvar), ")"))
text(1, 3, paste("Cell Width = ", tclvalue(longgr), "units and Cell Height = ", tclvalue(latgr), "units"))
text(1, 4, paste("Gray tones proportional to richness by cell\nHighest richness (black cell[s]) = ", tclvalue(maxrich)))
drawrich(outdn)
dev.off()
}
tt<-tktoplevel()
tkwm.title(tt, "Grid creator")
leftframe <- tkframe(tt, relief = "groove", borderwidth = 2)
rightframe <- tkframe(tt, relief = "groove", borderwidth = 2)
gridframe <- tkframe(leftframe, relief = "groove", borderwidth = 2)
outputframe <- tkframe(leftframe, relief = "groove", borderwidth = 2)
plotframe <- tkframe(leftframe)
cols <- tkentry(gridframe, width="6", textvariable = ncols)
lins <- tkentry(gridframe, width="6", textvariable = nlins)
xorigen <- tkentry(gridframe, width = "6", textvariable = xorvar)
yorigen <- tkentry(gridframe, width = "6", textvariable = yorvar)
xsize <- tkentry(gridframe, width="6", textvariable = longgr)
ysize <- tkentry(gridframe, width="6", textvariable = latgr)
addcol <- tkbutton(gridframe, text = "+", command = function(...) modpar(1))
subtractcol <- tkbutton(gridframe, text = "-", command = function(...) modpar(2))
addlin <- tkbutton(gridframe, text = "+", command = function(...) modpar(-1))
subtractlin <- tkbutton(gridframe, text = "-", command = function(...) modpar(-2))
img <- tkrplot(plotframe, fun = drawgrid, hscale=1.5,vscale=1.5)
richplot <- tkrplot(rightframe, function() drawrich(outtable()), hscale=1.2,vscale=1.2)
outButton <- tkbutton(outputframe, text = "Create object", command = launchout)
refreshButton <- tkbutton(outputframe, text = "Full extent",
command = function(){xlims <<- range(long)
xlims <<- xlims + c(-0.1*diff(xlims), 0.1*diff(xlims))
ylims <<- range(lat)
ylims <<- ylims + c(-0.1*diff(ylims), 0.1*diff(ylims))
tclvalue(xorvar) <<- as.character(round(xlims[1],3))
tclvalue(yorvar) <<- as.character(round(ylims[2], 3))
tkrreplot(img)
})
richButton <- tkbutton(rightframe, text = "Refresh richness map", command = function() tkrreplot(richplot))
pdfButton <- tkbutton(rightframe, text = " Save pdf report ", command = function() {tkrreplot(richplot); constructpdf()})
clipButton <- tkbutton(outputframe, text = "Copy to clipboard", command = function() tkrreplot(img))
xpos <- tklabel(outputframe, textvariable = currentx)
ypos <- tklabel(outputframe, textvariable = currenty)
mrich <- tklabel(rightframe, textvariable = maxrich, font = 13)
tkgrid(tklabel(gridframe, text = "GRID PARAMETERS", font = "Times 14", foreground = "blue"), columnspan = 4)
tkgrid(tklabel(gridframe, text = "
tkgrid(tklabel(gridframe, text = "
tkgrid.configure(subtractlin,sticky="e", ipadx = 4)
tkgrid.configure(addlin,sticky="w", ipadx = 2)
tkgrid.configure(subtractcol,sticky="e", ipadx = 4)
tkgrid.configure(addcol,sticky="w", ipadx = 2)
tkgrid(tklabel(gridframe, text = "Cell Size"), columnspan = 4)
tkgrid(tklabel(gridframe, text = "width ="), xsize, tklabel(gridframe, text = "height ="), ysize)
tkgrid(tklabel(gridframe, text = "NW Corner"), columnspan = 4)
tkgrid(tklabel(gridframe, text = " x ="), xorigen, tklabel(gridframe, text = " y ="), yorigen)
tkgrid(tklabel(outputframe, text = "GENERAL ACTIONS", font = "Times 14", foreground = "blue"), columnspan = 2)
tkgrid(outButton, columnspan = 2)
tkgrid(refreshButton, columnspan = 2)
tkgrid(clipButton, columnspan = 2)
tkgrid(tklabel(outputframe, text = "Current Position (x, y)", font = "Times 12"), columnspan = 2)
tkgrid(xpos, ypos)
tkgrid(gridframe,outputframe)
tkgrid(img)
tkgrid(plotframe, columnspan = 2)
tkgrid(tklabel(rightframe, text = "OUTPUT DETAILS", font = "Times 14", foreground = "blue"))
tkgrid(richButton)
tkgrid(pdfButton)
tkgrid(tklabel(rightframe, text = ""))
tkgrid(richplot)
tkgrid(tklabel(rightframe, text = "Maximum recorded richness (black cells)", font = 13))
tkgrid(mrich)
tkgrid(leftframe, rightframe)
tkbind(img, "<B1-Motion>", function(x, y) {
aa <- curpos(x, y)
if(!is.null(aa)) movegrid(aa[1], aa[2])})
tkbind(img, "<ButtonRelease-1>", fixnewor)
tkbind(img, "<Motion>", function(x, y) {
aa <- curpos(x, y)
tclvalue(currentx) <<- round(aa[1], 3)
tclvalue(currenty) <<- round(aa[2], 3)})
tkbind(img, "<Leave>", function() {tclvalue(currentx) <<- ""; tclvalue(currenty) <<- ""})
tkbind(cols, "<KeyPress-Return>", function() {modpar(3); tkfocus(lins)})
tkbind(lins, "<KeyPress-Return>", function() {modpar(-3); tkfocus(cols)})
tkbind(cols, "<FocusOut>", function() modpar(3))
tkbind(lins, "<FocusOut>", function() modpar(-3))
tkbind(xsize, "<KeyPress-Return>", function() {changecell(1); tkfocus(ysize)})
tkbind(ysize, "<KeyPress-Return>", function() {changecell(2); tkfocus(xsize)})
tkbind(xsize, "<FocusOut>", function() changecell(1))
tkbind(ysize, "<FocusOut>", function() changecell(2))
tkbind(xorigen, "<KeyPress-Return>", function() {fixnewor(); tkfocus(yorigen)})
tkbind(yorigen, "<KeyPress-Return>", function() {fixnewor(); tkfocus(xorigen)})
tkbind(xorigen, "<FocusOut>", fixnewor)
tkbind(yorigen, "<FocusOut>", fixnewor)
}
|
library(plotmo)
library(earth)
data(ozone1)
library(randomForest)
oz <- ozone1[, c("O3", "humidity", "temp")]
set.seed(2018)
rf.mod <- randomForest(O3 ~ ., data=oz)
|
safely_select_variables <- function(safe_extractor, data, y = NULL, which_y = NULL, class_pred = NULL, verbose = TRUE) {
if (class(safe_extractor) != "safe_extractor") {
stop(paste0("No applicable method for 'safely_select_variables' applied to an object of class '", class(safe_extractor), "'."))
}
if (is.null(data)) {
stop("No data provided!")
}
if (is.null(y) & is.null(which_y)) {
stop("Specify either y or which_y argument!")
}
if (! is.null(which_y)) {
y <- tryCatch(
{
data[,which_y]
},
error = function(cond) {
stop("The 'y' variable is not in the dataset!")
message(cond)
}
)
if (is.character(which_y)) {
data <- data[, colnames(data) != which_y]
data <- data[, colnames(data) != paste0(which_y, "_new")]
} else {
data <- data[, -which_y]
}
}
if (is.factor(y)) {
if (! is.null(class_pred)) {
if (is.character(class_pred)) {
if (! class_pred %in% levels(y)) {
cat("There is no such a level in response vector! Using first level instead.\n")
class_pred <- levels(y)[1]
}
} else {
if (! class_pred %in% 1:length(levels(y))) {
cat("There is no such a level in response vector! Using first level instead.\n")
class_pred <- levels(y)[1]
}
}
} else {
class_pred <- levels(y)[1]
}
}
term_names <- names(safe_extractor$variables_info)
term_names <- term_names[term_names != which_y]
term_names_new <- sapply(term_names, function(x) paste0(x, "_new"))
term_names_new_present <- intersect(colnames(data), term_names_new)
if (length(term_names_new_present) == 0) {
data <- safely_transform_data(safe_extractor, data, verbose = FALSE)
term_names_new_present <- intersect(colnames(data), term_names_new)
}
var_best <- term_names
if (verbose == TRUE) {
pb <- txtProgressBar(min = 0, max = length(term_names), style = 3)
}
if (is.factor(y)) {
for (var_temp in term_names) {
if (paste0(var_temp, "_new") %in% colnames(data)) {
var_checked <- c(setdiff(var_best, var_temp), paste0(var_temp, "_new"))
model_best <- glm((y == class_pred) ~ ., data = as.data.frame(data[, var_best]), family = binomial(link = 'logit'))
model_checked <- glm((y == class_pred) ~ ., data = as.data.frame(data[, var_checked]), family = binomial(link = 'logit'))
if (AIC(model_checked) < AIC(model_best)) {
var_best <- var_checked
}
}
if (verbose == TRUE) {
setTxtProgressBar(pb, which(term_names == var_temp))
}
}
} else {
for (var_temp in term_names) {
if (paste0(var_temp, "_new") %in% colnames(data)) {
var_checked <- c(setdiff(var_best, var_temp), paste0(var_temp, "_new"))
model_best <- lm(y ~ ., data = as.data.frame(data[, var_best]))
model_checked <- lm(y ~ ., data = as.data.frame(data[, var_checked]))
if (AIC(model_checked) < AIC(model_best)) {
var_best <- var_checked
}
}
if (verbose == TRUE) {
setTxtProgressBar(pb, which(term_names == var_temp))
}
}
}
if (verbose == TRUE) {
close(pb)
}
return(var_best)
}
|
shrinkDSM <- function(formula,
data,
mod_type = "double",
delta,
S,
group,
subset,
niter = 10000,
nburn = round(niter/2),
nthin = 1,
learn_a_xi = TRUE,
learn_a_tau = TRUE,
a_xi = 0.1,
a_tau = 0.1,
learn_c_xi = TRUE,
learn_c_tau = TRUE,
c_xi = 0.1,
c_tau = 0.1,
a_eq_c_xi = FALSE,
a_eq_c_tau = FALSE,
learn_kappa2_B = TRUE,
learn_lambda2_B = TRUE,
kappa2_B = 20,
lambda2_B = 20,
hyperprior_param,
sv_param,
MH_tuning,
display_progress = TRUE){
assert(missing(group) || length(group) == nrow(data), "Grouping indicator, group, has to be omitted or the same length as data")
assert(length(delta) == nrow(data), "Status indicator, delta, has to be the same length as data")
mf <- match.call(expand.dots = FALSE)
m <- match(x = c("formula", "data", "subset"),
table = names(mf), nomatch = 0L)
mf <- mf[c(1L, m)]
mf$drop.unused.levels <- TRUE
mf[[1L]] <- quote(stats::model.frame)
mf <- eval(expr = mf, envir = parent.frame())
for(name in names(mf)){
assert(!any(class(mf[[name]]) %in% c("POSIXct", "POSIXt","Date")), "No date variables allowed as predictors")
}
y <- model.response(mf, "numeric")
mt <- attr(x = mf, which = "terms")
z <- model.matrix(object = mt, data = mf)
colnames(z)[colnames(z) == "(Intercept)"] <- "Intercept"
assert(!any(is.na(y)), "No NA values are allowed in survival time")
assert(all(y>0), "Survival times must be positive. Zeros are not allowed.")
assert(!any(is.na(z)), "No NA values are allowed in covariates")
assert(mod_type %in% c("double", "triple", "ridge"), "Allowed model types are: ridge, double, and triple")
default_hyper <- list(c0 = 2.5,
g0 = 5,
G0 = 5 / (2.5 - 1),
e1 = 0.001,
e2 = 0.001,
d1 = 0.001,
d2 = 0.001,
beta_a_xi = 10,
beta_a_tau = 10,
alpha_a_xi = 5,
alpha_a_tau = 5,
beta_c_xi = 2,
beta_c_tau = 2,
alpha_c_xi = 5,
alpha_c_tau = 5)
if (!missing(group)) {
group <- checkvalues(group)
default_hyper$sigma2_phi <- rep(1, length(unique(group$values)))
} else {
group_sort <- c(0)
default_hyper$sigma2_phi <- c(0)
}
default_hyper_sv <- list(Bsigma_sv = 1,
a0_sv = 5,
b0_sv = 1.5)
default_tuning_par <- list(a_xi_adaptive = TRUE,
a_xi_tuning_par = 1,
a_xi_target_rate = 0.44,
a_xi_max_adapt = 0.01,
a_xi_batch_size = 50,
a_tau_adaptive = TRUE,
a_tau_tuning_par = 1,
a_tau_target_rate = 0.44,
a_tau_max_adapt = 0.01,
a_tau_batch_size = 50,
c_xi_adaptive = TRUE,
c_xi_tuning_par = 1,
c_xi_target_rate = 0.44,
c_xi_max_adapt = 0.01,
c_xi_batch_size = 50,
c_tau_adaptive = TRUE,
c_tau_tuning_par = 1,
c_tau_target_rate = 0.44,
c_tau_max_adapt = 0.01,
c_tau_batch_size = 50)
if (missing(hyperprior_param)) {
hyperprior_param <- default_hyper
} else {
hyperprior_param <- list_merger(default_hyper, hyperprior_param)
}
if (missing(sv_param)) {
sv_param <- default_hyper_sv
} else {
sv_param <- list_merger(default_hyper_sv, sv_param)
}
if (missing(MH_tuning)) {
MH_tuning <- default_tuning_par
} else {
MH_tuning <- list_merger(default_tuning_par, MH_tuning)
}
to_test_num <- list(lambda2_B = lambda2_B,
kappa2_B = kappa2_B,
a_xi = a_xi,
a_tau = a_tau,
c_xi = c_xi,
c_tau = c_tau)
if(!missing(group)) {
cond = length(hyperprior_param$sigma2_phi) == length(unique(group$values)) && all(!sapply(hyperprior_param$sigma2_phi, numeric_input_bad))
assert(cond, "all elements of sigma2_phi have to be positive real numbers")}
if (missing(hyperprior_param) == FALSE){
to_test_num <- c(to_test_num, hyperprior_param[names(hyperprior_param) != "sigma2_phi"])
}
if (missing(sv_param) == FALSE){
to_test_num <- c(to_test_num, sv_param)
}
if (missing(MH_tuning) == FALSE){
to_test_num <- c(to_test_num, MH_tuning[!grepl("(batch|adaptive)", names(MH_tuning))])
}
bad_inp <- sapply(to_test_num, numeric_input_bad)
if (any(bad_inp)){
stand_names <- c(names(default_hyper), names(default_hyper_sv), "lambda2_B", "kappa2_B", "a_xi", "a_tau", "c_xi", "c_tau")
bad_inp_names <- names(to_test_num)[bad_inp]
bad_inp_names <- bad_inp_names[bad_inp_names %in% stand_names]
stop(paste0(paste(bad_inp_names, collapse = ", "),
ifelse(length(bad_inp_names) == 1, " has", " have"),
" to be a real, positive number"))
}
if (any(0 > MH_tuning[grepl("rate", names(MH_tuning))] | MH_tuning[grepl("rate", names(MH_tuning))] > 1)) {
stop("all target_rate parameters in MH_tuning have to be > 0 and < 1")
}
to_test_int <- c(niter = niter,
nburn = nburn,
nthin = nthin,
MH_tuning[grepl("batch", names(MH_tuning))])
bad_int_inp <- sapply(to_test_int, int_input_bad)
if (any(bad_int_inp)){
bad_inp_names <- names(to_test_int)[bad_int_inp]
stop(paste0(paste(bad_inp_names, collapse = ", "),
ifelse(length(bad_inp_names) == 1, " has", " have"),
" to be a single, positive integer"))
}
if ((niter - nburn) < 2){
stop("niter has to be larger than or equal to nburn + 2")
}
if (nthin == 0){
stop("nthin can not be 0")
}
if ((niter - nburn)/2 < nthin){
stop("nthin can not be larger than (niter - nburn)/2")
}
to_test_bool <- c(learn_lambda2_B = learn_lambda2_B,
learn_kappa2_B = learn_kappa2_B,
learn_a_xi = learn_a_xi,
learn_a_tau = learn_a_tau,
display_progress = display_progress,
MH_tuning[grepl("adaptive", names(MH_tuning))])
bad_bool_inp <- sapply(to_test_bool, bool_input_bad)
if (any(bad_bool_inp)){
bad_inp_names <- names(to_test_bool)[bad_bool_inp]
stop(paste0(paste(bad_inp_names, collapse = ", "),
ifelse(length(bad_inp_names) == 1, " has", " have"),
" to be a single logical value"))
}
if (inherits(formula, "formula") == FALSE){
stop("formula is not of class formula")
}
d <- ncol(z)
if (!is.null(colnames(z))){
col_names <- colnames(z)
} else {
col_names <- as.character(1:d)
}
order <- order(y, decreasing = TRUE)
y_sort <- y[order]
z_sort <- z[order, ]
if(!missing(group)){
group_sort <- group$values[order]
}
if(2 %in% delta){delta <- delta - 1}
assert(all(delta %in% c(0,1)),
"delta must contain only 0/1, 1/2, or TRUE/FALSE")
z_sort <- as.matrix(z_sort)
delta_sort <- as.matrix(as.integer(delta[order]))
runtime <- system.time({
res <- do_shrinkDSM(y_sort,
z_sort,
mod_type,
delta_sort,
S,
group_sort,
niter,
nburn,
nthin,
hyperprior_param$d1,
hyperprior_param$d2,
hyperprior_param$e1,
hyperprior_param$e2,
hyperprior_param$sigma2_phi,
learn_lambda2_B,
learn_kappa2_B,
lambda2_B,
kappa2_B,
learn_a_xi,
learn_a_tau,
a_xi,
a_tau,
learn_c_xi,
learn_c_tau,
c_xi,
c_tau,
a_eq_c_xi,
a_eq_c_tau,
MH_tuning$a_xi_tuning_par,
MH_tuning$a_tau_tuning_par,
MH_tuning$c_xi_tuning_par,
MH_tuning$c_tau_tuning_par,
hyperprior_param$beta_a_xi,
hyperprior_param$beta_a_tau,
hyperprior_param$alpha_a_xi,
hyperprior_param$alpha_a_tau,
hyperprior_param$beta_c_xi,
hyperprior_param$beta_c_tau,
hyperprior_param$alpha_c_xi,
hyperprior_param$alpha_c_tau,
sv_param$Bsigma_sv,
sv_param$a0_sv,
sv_param$b0_sv,
display_progress,
unlist(MH_tuning[grep("adaptive", names(MH_tuning))]),
unlist(MH_tuning[grep("target", names(MH_tuning))]),
unlist(MH_tuning[grep("max", names(MH_tuning))]),
unlist(MH_tuning[grep("size", names(MH_tuning))]))
})
if(display_progress == TRUE){
cat("Timing (elapsed): ", file=stderr())
cat(runtime["elapsed"], file=stderr())
cat(" seconds.\n", file=stderr())
cat(round((niter + nburn)/runtime[3]), "iterations per second.\n\n", file=stderr())
cat("Converting results to coda objects and summarizing draws... ", file=stderr())
}
res[sapply(res, function(x) 0 %in% dim(x))] <- NULL
res$MH_diag[sapply(res$MH_diag, function(x) 0 %in% dim(x))] <- NULL
res$priorvals <- c(hyperprior_param,
sv_param,
a_xi = a_xi,
a_tau = a_tau,
lambda2_B = lambda2_B,
kappa2_B = kappa2_B)
res[["model"]] <- list()
res$model$z <- z
res$model$y <- y
res$model$formula <- formula
res$model$xlevels <- .getXlevels(mt, mf)
res$model$terms <- mt
res$model$model <- mf
nsave <- floor((niter - nburn)/nthin)
for (i in names(res)){
attr(res[[i]], "type") <- ifelse(nsave %in% dim(res[[i]]), "sample", "stat")
if (attr(res[[i]], "type") == "sample"){
if (i == "phi"){
colnames(res[[i]]) <- paste0(i, unique(group_sort))
} else if (dim(res[[i]])[2] == d){
colnames(res[[i]]) <- paste0(i, "_", col_names)
} else if (dim(res[[i]])[2] == 2 * d) {
colnames(res[[i]]) <- paste0(i, "_", rep(col_names, 2))
} else {
colnames(res[[i]]) <- i
}
}
if (attr(res[[i]], "type") == "sample"){
if (is.na(dim(res[[i]])[3]) == FALSE){
dat <- res[[i]]
res[[i]] <- list()
for (j in 1:dim(dat)[2]){
res[[i]][[j]] <- as.mcmc(t(dat[, j, ]), start = niter - nburn, end = niter, thin = nthin)
colnames(res[[i]][[j]]) <- paste0(i, "_", j, "_", 1:ncol(res[[i]][[j]]))
class(res[[i]][[j]]) <- c("mcmc.dsm.tvp", "mcmc")
attr(res[[i]][[j]], "S") <- S
attr(res[[i]][[j]], "lastsurvtime") <- max(res$model$y)
attr(res[[i]][[j]], "type") <- "sample"
}
if (length(res[[i]]) == 1){
res[[i]] <- res[[i]][[j]]
}
attr(res[[i]], "type") <- "sample"
if (dim(dat)[2] > 1){
names(res[[i]]) <- colnames(dat)
}
} else {
res[[i]] <- as.mcmc(res[[i]], start = niter - nburn, end = niter, thin = nthin)
}
}
if (is.list(res[[i]]) == FALSE & attr(res[[i]], "type") == "sample") {
if (i != "theta_sr" & i != "beta") {
res$summaries[[i]] <- t(apply(res[[i]], 2, function(x){
obj <- as.mcmc(x, start = niter - nburn, end = niter, thin = nthin)
ESS <- tryCatch(coda::effectiveSize(obj),
error = function(err) {
warning("Calculation of effective sample size failed for one or more variable(s). This can happen if the prior placed on the model induces extreme shrinkage.")
return(NA)
}, silent = TRUE)
return(c("mean" = mean(obj),
"sd" = sd(obj),
"median" = median(obj),
"HPD" = HPDinterval(obj)[c(1, 2)],
"ESS" = round(ESS)))
}))
} else if (i == "theta_sr") {
res$summaries[[i]] <- t(apply(res[[i]], 2, function(x){
obj <- as.mcmc(abs(x), start = niter - nburn, end = niter, thin = nthin)
ESS <- tryCatch(coda::effectiveSize(obj),
error = function(err) {
warning("Calculation of effective sample size failed for one or more variable(s). This can happen if the prior placed on the model induces extreme shrinkage.")
return(NA)
}, silent = TRUE)
return(c("mean" = mean(obj),
"sd" = sd(obj),
"median" = median(obj),
"HPD" = HPDinterval(obj)[c(1, 2)],
"ESS" = round(ESS)))
}))
}
}
}
if (display_progress == TRUE) {
cat("Done!\n", file = stderr())
}
attr(res, "class") <- "shrinkDSM"
attr(res, "S") <- S
attr(res, "lastsurvtime") <- max(res$model$y)
if (!missing(group)) {
attr(res, "group") <- group
}
attr(res, "learn_a_xi") <- learn_a_xi
attr(res, "learn_a_tau") <- learn_a_tau
attr(res, "learn_kappa2_B") <- learn_kappa2_B
attr(res, "learn_lambda2_B") <- learn_lambda2_B
attr(res, "niter") <- niter
attr(res, "nburn") <- nburn
attr(res, "nthin") <- nthin
attr(res, "colnames") <- col_names
return(res)
}
|
tam_dtnorm <- function(x, mean=0, sd=1, lower=-Inf, upper=Inf, log=FALSE)
{
ret <- numeric(length(x))
ret[x < lower | x > upper] <- if (log) { -Inf } else { 0 }
ret[upper < lower] <- NaN
ind <- x >=lower & x <=upper
if (any(ind)) {
denom <- stats::pnorm(q=upper, mean=mean, sd=sd) - stats::pnorm(q=lower, mean=mean, sd=sd)
xtmp <- stats::dnorm(x=x, mean=mean, sd=sd, log=log)
if (log)
xtmp <- xtmp - log(denom)
else xtmp <- xtmp/denom
ret[x >=lower & x <=upper] <- xtmp[ind]
}
return(ret)
}
|
set_linkingInfo.l_serialaxes <- function(loon.grob, output.grob,
linkedInfo, linkedStates, tabPanelName,
order, loonWidgetsInfo, ...) {
if(length(linkedStates) > 0) {
loon.grob_showArea <- get_showArea(loon.grob)
output.grob_showArea <- get_showArea(output.grob)
color <- if("color" %in% linkedStates) {
linkedColor <- linkedInfo$color[order]
NAid <- is.na(linkedColor)
if(any(NAid)) {
linkedColor[NAid] <- loonWidgetsInfo$color[NAid]
linkedColor
} else linkedColor
} else loonWidgetsInfo$color
selected <- if("selected" %in% linkedStates) {
linkedselected <- linkedInfo$selected[order]
NAid <- is.na(linkedselected)
if(any(NAid)) {
linkedselected[NAid] <- loonWidgetsInfo$selected[NAid]
linkedselected
} else linkedselected
} else loonWidgetsInfo$selected
active <- if("active" %in% linkedStates) {
linkedactive <- linkedInfo$active[order]
NAid <- is.na(linkedactive)
if(any(NAid)) {
linkedactive[NAid] <- loonWidgetsInfo$active[NAid]
linkedactive
} else linkedactive
} else loonWidgetsInfo$active
size <- if("size" %in% linkedStates) {
linkedsize <- linkedInfo$size[order]
NAid <- is.na(linkedsize)
if(any(NAid)) {
linkedsize[NAid] <- loonWidgetsInfo$size[NAid]
linkedsize
} else linkedsize
} else loonWidgetsInfo$size
loon.grob_axesGpath <- if(get_axesLayout(loon.grob) == "parallel") "parallelAxes" else "radialAxes"
output.grob_axesGpath <- if(get_axesLayout(output.grob) == "parallel") "parallelAxes" else "radialAxes"
new.loon.grob <- grid::getGrob(loon.grob, loon.grob_axesGpath)
new.output.grob <- grid::getGrob(output.grob, output.grob_axesGpath)
lapply(seq(loonWidgetsInfo$N),
function(i) {
loon.grobi <- new.loon.grob$children[[i]]
output.grobi <- new.output.grob$children[[i]]
if("color" %in% linkedStates & !is.null(color)) {
grobi_color <- color[i]
} else {
grobi_color <- if(loon.grob_showArea) {
loon.grobi$gp$fill
} else loon.grobi$gp$col
}
grobi_size <- if("size" %in% linkedStates & !is.null(size)) {
size[i]
} else {
loon.grobi$gp$lwd
}
loon.grobi <- grid::editGrob(
grob = loon.grobi,
gp = if(loon.grob_showArea) {
gpar(fill = grobi_color, col = NA)
} else {
gpar(col = grobi_color, lwd = grobi_size)
}
)
output.grobi <- grid::editGrob(
grob = output.grobi,
gp = if(output.grob_showArea) {
gpar(fill = grobi_color, col = NA)
} else {
gpar(col = grobi_color, lwd = grobi_size)
}
)
if("active" %in% linkedStates) {
loon.grobi <- if(!active[i]) {
do.call(grob, getGrobArgs(loon.grobi))
} else {
if(loon.grob_showArea) {
do.call(grid::polygonGrob, getGrobArgs(loon.grobi))
} else {
do.call(grid::linesGrob, getGrobArgs(loon.grobi))
}
}
output.grobi <- if(!active[i]) {
do.call(grob, getGrobArgs(output.grobi))
} else {
if(output.grob_showArea) {
do.call(grid::polygonGrob, getGrobArgs(output.grobi))
} else {
do.call(grid::linesGrob, getGrobArgs(output.grobi))
}
}
}
new.loon.grob$children[[i]] <<- loon.grobi
new.output.grob$children[[i]] <<- if("selected" %in% linkedStates & selected[i]) {
grid::editGrob(
grob = output.grobi,
gp = if(output.grob_showArea) {
gpar(fill = select_color(), col = NA)
} else {
gpar(col = select_color(), lwd = grobi_size)
}
)
} else output.grobi
}
)
loon.grob <- grid::setGrob(
gTree = loon.grob,
gPath = loon.grob_axesGpath,
newGrob = new.loon.grob
)
output.grob <- grid::setGrob(
gTree = output.grob,
gPath = output.grob_axesGpath,
newGrob = new.output.grob
)
output.grob <- reorder_grob(output.grob,
index = which(selected),
axesGpath = output.grob_axesGpath)
loonWidgetsInfo$color <- color
loonWidgetsInfo$size <- size
loonWidgetsInfo$selected <- selected
loonWidgetsInfo$active <- active
}
list(
output.grob = output.grob,
loon.grob = loon.grob,
loonWidgetsInfo = loonWidgetsInfo
)
}
|
huff.attrac <-
function (huffdataset, origins, locations, attrac, dist,
lambda = -2, dtype= "pow", lambda2 = NULL,
localmarket_dataset, origin_id, localmarket,
location_dataset, location_id, location_total,
tolerance = 5, output = "matrix", show_proc = FALSE,
check_df = TRUE)
{
if (check_df == TRUE)
{
if (exists(as.character(substitute(huffdataset)))) {
checkdf(huffdataset, origins, locations, attrac, dist)
}
else {
stop(paste("Dataset", as.character(substitute(huffdataset))), " not found", call. = FALSE)
}
if (exists(as.character(substitute(localmarket_dataset)))) {
checkdf(localmarket_dataset, origin_id, localmarket)
}
else {
stop(paste("Dataset", as.character(substitute(localmarket_dataset))), " not found", call. = FALSE)
}
if (exists(as.character(substitute(location_dataset)))) {
checkdf(location_dataset, location_id, location_total)
}
else {
stop(paste("Dataset", as.character(substitute(location_dataset))), " not found", call. = FALSE)
}
}
sort_i_j <- order(huffdataset[[origins]], huffdataset[[locations]])
huffworkfile <- huffdataset[sort_i_j,]
origins_single <- levels(as.factor(as.character(huffdataset[[origins]])))
origins_count <- nlevels(as.factor(as.character(huffdataset[[origins]])))
locations_single <- levels(as.factor(as.character(huffdataset[[locations]])))
locations_count <- nlevels(as.factor(as.character(huffdataset[[locations]])))
huffworkfile <- merge (huffdataset, localmarket_dataset, by.x = origins, by.y = origin_id)
huff_shares <- huff.shares(huffworkfile, origins, locations, attrac, dist, lambda = lambda, dtype = dtype, lambda2 = lambda2, check_df = FALSE)
huff_total <- shares.total(huff_shares, origins, locations, "p_ij", localmarket, check_df = FALSE)
huff_total_suppdata <- merge (huff_total, location_dataset, by.x="suppliers_single", by.y=location_id)
locations_attrac <- paste0(huffdataset[[locations]], ":", huffdataset[[attrac]])
locations_attrac_fac <- levels(as.factor(locations_attrac))
locations_attrac_split <- strsplit(locations_attrac_fac, ":")
locations_attrac_df <- data.frame(do.call(rbind, locations_attrac_split))
colnames(locations_attrac_df) <- c("suppliers_single", names(huffworkfile[attrac]))
huff_total_suppdata_complete <- merge (huff_total_suppdata, locations_attrac_df)
k <- 0
total_obs <- vector()
total_exp1 <- vector()
total_exp2 <- vector()
attrac_new <- vector()
attrac_old <- vector()
attrac_new_opt <- vector()
diff_rel_old <- vector()
diff_rel_new <- vector()
a <- vector()
b <- vector()
for (k in 1:locations_count)
{
attrac_old[k] <- as.numeric(as.character(huff_total_suppdata_complete[[attrac]][k]))
total_obs[k] <- huff_total_suppdata_complete[[location_total]][k]
if (show_proc == TRUE) cat("Processing location", locations_single[k], "...", "\n")
total_exp1[k] <- huff_total_suppdata_complete$sum_E_j[k]
diff_rel_old[k] <- (total_exp1[k]-total_obs[k])/total_obs[k]*100
if (abs(diff_rel_old[k]) > tolerance)
{
attrac_new[k] <- 0
huffworkfile[huffworkfile[[locations]] == locations_single[k],][[attrac]] <- attrac_new[k]
huff_shares_new <- huff.shares(huffworkfile, origins, locations, attrac, dist, lambda = lambda, dtype = dtype, lambda2 = lambda2, check_df = FALSE)
huff_total_new <- shares.total(huff_shares_new, origins, locations, "p_ij", localmarket, check_df = FALSE)
total_exp2[k] <- huff_total_new$sum_E_j[k]
diff_rel_new[k] <- (total_exp2[k]-total_obs[k])/total_obs[k]*100
b[k] <- (attrac_new[k]-attrac_old[k])/(total_exp2[k]-total_exp1[k])
a[k] <- b[k] * total_exp2[k] - attrac_new[k]
attrac_new_opt[k] <- a[k] + b[k] * total_obs[k]
}
else
{
attrac_new_opt[k] <- as.numeric(as.character(huff_total_suppdata_complete[[attrac]][k]))
}
huffworkfile[huffworkfile[[locations]] == locations_single[k],][[attrac]] <- attrac_new_opt[k]
huff_shares_new <- huff.shares(huffworkfile, origins, locations, attrac, dist, check_df = FALSE)
}
huff_attrac <- data.frame(huff_total_suppdata_complete$suppliers_single, attrac_new_opt)
colnames(huff_attrac) <- c("suppliers_single", "attrac_new_opt")
cat("\n")
if (output == "matrix")
{
return(huff_shares_new)
}
if (output == "attrac")
{
return(huff_attrac)
}
if (output == "total")
{
huff_total_new <- shares.total(huff_shares_new, origins, locations, "p_ij", localmarket, check_df = FALSE)
huff_total_new$total_obs <- total_obs
huff_total_new$diff <- huff_total_new$total_obs-huff_total_new$sum_E_j
huff_total_new_output <- merge (huff_total_new, huff_attrac)
return(huff_total_new_output)
}
}
|
power_prop_test <- function (n = NULL, p1 = NULL, p2 = NULL, sig.level = 0.05, power = NULL, ratio=1,
alternative = c("two.sided", "one.sided"),
tol = .Machine$double.eps^0.25)
{
if (sum(sapply(list(n, p1, p2, power, sig.level, ratio), is.null)) != 1)
stop("exactly one of 'n', 'p1', 'p2', 'power', 'sig.level', and 'ratio' must be NULL")
if (!is.null(sig.level) && !is.numeric(sig.level) || any(0 > sig.level | sig.level > 1))
stop("'sig.level' must be numeric in [0, 1]")
if (!is.null(ratio) && ratio <= 0)
stop("ratio between group sizes must be positive")
alternative <- match.arg(alternative)
tside <- switch(alternative, one.sided = 1, two.sided = 2)
p.body <- quote({
qu <- qnorm(sig.level/tside, lower.tail = FALSE)
d <- abs(p1 - p2)
q1 <- 1 - p1
q2 <- 1 - p2
pbar <- (p1 + ratio*p2)/(1+ratio)
qbar <- 1 - pbar
( qnorm(sig.level/tside)* sqrt(pbar*qbar*(1+ratio)) + qnorm(1-power)* sqrt(ratio*p1*q1 + p2*q2) )^2 / (ratio*d^2)
})
if (is.null(n))
n <- eval(p.body)
else if (is.null(power))
power <- uniroot(function(power) eval(p.body) - n, c(0.00001, .99999),
tol = tol, extendInt = "upX")$root
else if (is.null(p1))
p1 <- uniroot(function(p1) eval(p.body) - n, c(0,
p2), tol = tol, extendInt = "yes")$root
else if (is.null(p2))
p2 <- uniroot(function(p2) eval(p.body) - n, c(p1,
1), tol = tol, extendInt = "yes")$root
else if (is.null(ratio))
ratio <- uniroot(function(ratio) eval(p.body) - n, c(2/n, 1e+07))$root
else if (is.null(sig.level))
sig.level <- uniroot(function(sig.level) eval(p.body) -
n, c(1e-10, 1 - 1e-10), tol = tol, extendInt = "upX")$root
else stop("internal error", domain = NA)
if (ratio!=1) {
n <- c(n, n*ratio)
}
NOTE <- ifelse(ratio==1, "n is number in *each* group", "n is vector of number in each group")
METHOD <- ifelse(ratio==1,
"Two-sample comparison of proportions power calculation",
"Two-sample comparison of proportions power calculation with unequal sample sizes")
structure(list(n = n, p1 = p1, p2 = p2, sig.level = sig.level,
power = power, alternative = alternative, note = NOTE,
method = METHOD), class = "power.htest")
}
|
AutoBestBW <-
function (x, filter.number = 1, family = "DaubExPhase", smooth.dev = var,
AutoReflect = TRUE, tol = 0.01, maxits = 200,
plot.it = FALSE, verbose = 0, ReturnAll=FALSE)
{
EWS <- ewspec3(x = x, filter.number = filter.number, family = family,
smooth.dev = smooth.dev,
AutoReflect = AutoReflect, WPsmooth.type = "wavelet")$S
J <- EWS$nlevels
Jmax <- J - 1
Jmin <- round(J/2)
specerr <- function(S1, S2, levs) {
ans <- 0
for (i in 1:length(levs)) {
d1 <- accessD(S1, lev = levs[i])
d2 <- accessD(S2, lev = levs[i])
ans <- ans + sum((d1 - d2)^2)
}
return(ans)
}
its <- 0
R <- 0.61803399
C <- 1 - R
ax <- 10
cx <- round(0.6 * length(x))
bx <- round(cx/2)
x0 <- ax
x3 <- cx
if (abs(cx - bx) > abs(bx - ax)) {
x1 <- bx
x2 <- round(bx + C * (cx - bx))
}
else {
x2 <- bx
x1 <- round(bx - C * (bx - ax))
}
fa.ews <- ewspec3(x = x, filter.number = filter.number, family = family,
smooth.dev = smooth.dev, AutoReflect = AutoReflect, WPsmooth.type = "RM",
binwidth = ax)$S
fb.ews <- ewspec3(x = x, filter.number = filter.number, family = family,
smooth.dev = smooth.dev, AutoReflect = AutoReflect, WPsmooth.type = "RM",
binwidth = bx)$S
fc.ews <- ewspec3(x = x, filter.number = filter.number, family = family,
smooth.dev = smooth.dev, AutoReflect = AutoReflect, WPsmooth.type = "RM",
binwidth = cx)$S
f1.ews <- ewspec3(x = x, filter.number = filter.number, family = family,
smooth.dev = smooth.dev, AutoReflect = AutoReflect, WPsmooth.type = "RM",
binwidth = x1)$S
f2.ews <- ewspec3(x = x, filter.number = filter.number, family = family,
smooth.dev = smooth.dev, AutoReflect = AutoReflect, WPsmooth.type = "RM",
binwidth = x2)$S
fa <- specerr(fa.ews, EWS, Jmin:Jmax)
fb <- specerr(fb.ews, EWS, Jmin:Jmax)
fc <- specerr(fc.ews, EWS, Jmin:Jmax)
f1 <- specerr(f1.ews, EWS, Jmin:Jmax)
f2 <- specerr(f2.ews, EWS, Jmin:Jmax)
xkeep <- c(ax, cx, x1, x2)
fkeep <- c(fa, fc, f1, f2)
if (plot.it == TRUE) {
plot(c(ax, bx, cx), c(fa, fb, fc))
text(c(x1, x2), c(f1, f2), lab = c("1", "2"))
}
cnt <- 3
while ((abs(x3 - x0) > tol * (abs(x1) + abs(x2))) && its <= maxits) {
if (verbose > 0) {
cat("x0=", x0, "x1=", x1, "x2=", x2, "x3=", x3, "\n")
cat("f1=", f1, "f2=", f2, "\n")
}
if (f2 < f1) {
x0 <- x1
x1 <- x2
x2 <- round(R * x1 + C * x3)
f1 <- f2
f2.ews <- ewspec3(x = x, filter.number = filter.number,
family = family, smooth.dev = smooth.dev, AutoReflect = AutoReflect,
WPsmooth.type = "RM", binwidth = x2)$S
f2 <- specerr(f2.ews, EWS, Jmin:Jmax)
if (verbose == 2) {
cat("SSQ: ", signif(f2, 3), "\n")
}
else if (verbose == 1)
cat(".")
xkeep <- c(xkeep, x2)
fkeep <- c(fkeep, f2)
if (plot.it == TRUE)
text(x2, f2, lab = as.character(cnt))
cnt <- cnt + 1
}
else {
x3 <- x2
x2 <- x1
x1 <- round(R * x2 + C * x0)
f2 <- f1
f1.ews <- ewspec3(x = x, filter.number = filter.number,
family = family, smooth.dev = smooth.dev, AutoReflect = AutoReflect,
WPsmooth.type = "RM", binwidth = x1)$S
f1 <- specerr(f1.ews, EWS, Jmin:Jmax)
if (verbose == 2)
cat("SSQ: ", signif(f1, 3), "\n")
else if (verbose == 1)
cat(".")
xkeep <- c(xkeep, x1)
fkeep <- c(fkeep, f1)
if (plot.it == TRUE)
text(x1, f1, lab = as.character(cnt))
cnt <- cnt + 1
}
its <- its + 1
}
if (its > maxits)
warning(paste("AutoBestBW: exceeded maximum number of iterations: ", maxits))
if (f1 < f2)
ans <- x1
else ans <- x2
if (ReturnAll == FALSE)
return(ans)
else {
l <- list(ans=ans, EWS.wavelet=EWS, EWS.linear=f1.ews)
return(l)
}
}
|
library(rgdal); library(ggmap)
dsn <- system.file('extdata', package = 'ggsn')
map <- readOGR(dsn, 'sp')
map@data$id <- 1:nrow(map@data)
map.ff <- fortify(map, region = 'id')
map.df <- merge(map.ff, map@data, by = 'id')
sp <- get_map(bbox(map) * matrix(rep(c(1.001, 0.999), e = 2), ncol = 2),
source = 'osm')
sp2 <- get_map('são paulo state',
source = 'google')
ggmap(sp, extent = 'device') +
geom_polygon(data = map.df, aes(long, lat, group = group, fill = nots),
alpha = .7) +
coord_equal()+
geom_path(data = map.df, aes(long, lat, group = group)) +
scalebar(map.df, dist = 5, dd2km = T, model = 'WGS84') +
north(map.df) +
scale_fill_brewer(name = 'Animal abuse\nnotifications', palette = 8) +
theme(legend.position = c(0.9, 0.35))
ggmap(sp2, extent = 'device') +
geom_polygon(data = map.df, aes(long, lat, group = group, fill = nots),
alpha = .7) +
coord_equal()+
geom_path(data = map.df, aes(long, lat, group = group)) +
scalebar(map.df, dist = 5, dd2km = T, model = 'WGS84') +
north(map.df) +
scale_fill_brewer(name = 'Animal abuse\nnotifications', palette = 8) +
theme(legend.position = c(0.9, 0.35))
ggmap(sp, extent = 'device') +
geom_polygon(data = map.df, aes(long, lat, group = group, fill = nots),
colour = 'black', alpha = .5) +
coord_equal()+
scalebar(x.min = bbox(map)[1, 1], x.max = bbox(map)[1, 2],
y.min = bbox(map)[2, 1], y.max = bbox(map)[2, 2],
dist = 5, dd2km = T, model = 'WGS84') +
north(x.min = bbox(map)[1, 1], x.max = bbox(map)[1, 2],
y.min = bbox(map)[2, 1], y.max = bbox(map)[2, 2])
ggmap(sp) +
geom_polygon(data = map.df, aes(long, lat, group = group, fill = nots),
alpha = .7) +
coord_equal()
sp <- get_map(matrix(c(-46.652, -23.551, -46.645, -23.545), ncol = 2),
source = 'osm')
ggmap(sp)
|
"jdbcTimeDate" <-
function(data) {
format <- "%Y-%m-%d %H:%M:%OS3"
as.character(data, format=format)
}
|
airnow_loadDaily <- function(parameter = 'PM2.5',
baseUrl = 'https://haze.airfire.org/monitoring/latest/RData',
dataDir = NULL) {
validParams <- c("PM2.5")
if ( !parameter %in% validParams ) {
paramsString <- paste(validParams, collapse=", ")
stop(paste0("'", parameter,
"' is not a supported parameter. Use 'parameter = ",
paramsString, "'"), call.=FALSE)
}
filename <- paste0("airnow_", parameter, "_latest45.RData")
ws_monitor <- MazamaCoreUtils::loadDataFile(filename, baseUrl, dataDir)
return(ws_monitor)
}
|
covid_deflator <- function(data_covid, deflator.file) {
if (sum(class(data_covid) == "tbl_df") > 0) {
if (!(FALSE %in% (c("Ano", "V1013", "UF") %in% names(data_covid)))) {
data_covid <- data_covid[, !names(data_covid) %in% c("Habitual", "Efetivo", "CO3"), drop=FALSE]
deflator <- suppressMessages(readxl::read_excel(deflator.file))
colnames(deflator)[c(1:3)] <- c("Ano", "V1013", "UF")
if (class(data_covid$Ano) == "integer") {
deflator$Ano <- as.integer(deflator$Ano)
}
else {
deflator$Ano <- as.character(as.integer(deflator$Ano))
}
if (class(data_covid$V1013) == "integer") {
deflator$V1013 <- as.integer(deflator$V1013)
}
else {
deflator$V1013 <- as.character(as.integer(deflator$V1013))
}
if (class(data_covid$UF) == "integer") {
deflator$UF <- as.integer(deflator$UF)
}
else {
deflator$UF <- as.factor(deflator$UF)
if (identical(intersect(levels(deflator$UF), levels(as.factor(data_covid$UF))), character(0)) & length(levels(deflator$UF)) == length(levels(as.factor(data_covid$UF)))) {
levels(deflator$UF) <- levels(as.factor(data_covid$UF))
}
}
data_covid <- merge(x=data_covid, y=deflator, by.x=c("Ano", "V1013", "UF"), by.y=c("Ano", "V1013", "UF"), all.x=TRUE, all.y=FALSE)
if (!(FALSE %in% (c("ID_DOMICILIO") %in% names(data_covid)))) {
data_covid <- data_covid[order(data_covid$Estrato, data_covid$ID_DOMICILIO, data_covid$A001),]
}
else {
data_covid <- data_covid[order(data_covid$Estrato, data_covid$UPA, data_covid$V1008, data_covid$A001),]
}
data_covid <- tibble::as_tibble(data_covid)
}
else {
message("Merge variables required for adding deflator variables are missing.")
}
}
else {
message("The microdata object is not of the tibble class or sample design was already defined for microdata, so adding deflator variables is not possible.")
}
return(data_covid)
}
|
fread.OTU <- function(file, sep="auto") {
input <- data.table::fread(file, na.strings=c("",".","NA"))
df <- as.data.frame(input)
rownames(df) <- df[,1]
df <- df[, -1]
valid.OTU(df)
df$taxonomy <- as.character(df$taxonomy)
return(df)
}
read.OTU <- function(file, sep=",") {
df <- read.table(file, sep=sep, header=T, row.names=1,
na.strings=c("",".","NA"))
valid.OTU(df)
df$taxonomy <- as.character(df$taxonomy)
return(df)
}
fread.meta <- function(file, sep="auto") {
input <- data.table::fread(file, na.strings=c("",".","NA"))
df <- as.data.frame(input)
rownames(df) <- df[,1]
df <- df[, -1]
return(df)
}
read.meta <- function(file, sep=",") {
input <- read.table(file, header=TRUE, row.names=1, sep=sep,
na.strings=c("",".","NA"))
return(input)
}
write.data <- function(data, file) {
file <- .ensure.filepath(file, "csv")
write.csv(data, file=file, quote=FALSE)
}
|
setMethod(Ops, signature(e1 = "magpie", e2 = "magpie"),
function(e1, e2) {
e2 <- magpie_expand(e2, e1)
e1 <- magpie_expand(e1, e2)
if (length(e1) == 0) return(e1)
if (length(e2) == 0) return(e2)
if (any(unlist(dimnames(e1)) != unlist(dimnames(e2)))) {
stop("MAgPIE objects after MAgPIE object expansion do not agree in dimnames! magpie_expand seems to be bugged!")
}
return(new("magpie", callGeneric([email protected], [email protected])))
}
)
setMethod(Ops, signature(e1 = "magpie", e2 = "numeric"),
function(e1, e2) {
return(new("magpie", callGeneric([email protected], e2)))
}
)
setMethod(Ops, signature(e1 = "numeric", e2 = "magpie"),
function(e1, e2) {
return(new("magpie", callGeneric(e1, [email protected])))
}
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.