code
stringlengths 1
13.8M
|
---|
library(checkargs)
context("isIntegerOrInfScalarOrNull")
test_that("isIntegerOrInfScalarOrNull works for all arguments", {
expect_identical(isIntegerOrInfScalarOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isIntegerOrInfScalarOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isIntegerOrInfScalarOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isIntegerOrInfScalarOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isIntegerOrInfScalarOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isIntegerOrInfScalarOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isIntegerOrInfScalarOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isIntegerOrInfScalarOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isIntegerOrInfScalarOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isIntegerOrInfScalarOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isIntegerOrInfScalarOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isIntegerOrInfScalarOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isIntegerOrInfScalarOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isIntegerOrInfScalarOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isIntegerOrInfScalarOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isIntegerOrInfScalarOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isIntegerOrInfScalarOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isIntegerOrInfScalarOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
}) |
setMethodS3("fitC1C2Peaks", "PairedPSCBS", function(fit, ..., tol=0.05, onError=c("error", "warning", "skip"), verbose=FALSE) {
onError <- match.arg(onError);
verbose <- Arguments$getVerbose(verbose);
if (verbose) {
pushState(verbose);
on.exit(popState(verbose));
}
verbose && enter(verbose, "Fitting the relationship between peaks in C1 and C2");
d1d2 <- fitC1C2Densities(fit, orderBy="x");
pList <- d1d2$pList;
verbose && print(verbose, pList);
D <- outer(pList$C1$x, pList$C2$x, FUN="-");
idxs <- which(abs(D) < tol, arr.ind=TRUE);
verbose && print(verbose, idxs);
if (nrow(idxs) < 2) {
msg <- sprintf("Cannot fit relationship between C1 and C2. Too few common peaks: %d", nrow(idxs));
if (onError == "error") {
plotC1C2Grid(fit);
throw(msg);
}
if (onError == "warning") {
warning(msg);
}
msg <- sprintf("Skipping fitting the relationship between peaks in C1 and C2. %s", msg);
verbose && cat(verbose, msg);
warning(msg);
verbose && exit(verbose);
return(NULL);
}
c1 <- pList$C1$x[idxs[,1]];
c2 <- pList$C2$x[idxs[,2]];
dd <- cbind(pList$C1$density[idxs[,1]], pList$C2$density[idxs[,2]]);
dd <- rowSums(dd^2);
w <- dd / sum(dd);
verbose && print(verbose, cbind(c1=c1, c2=c2, weights=w));
f <- lm(c2 ~ 1 + c1, weights=w);
verbose && print(verbose, f);
a <- coef(f)[1];
b <- coef(f)[2];
params <- list(a=a, b=b);
verbose && print(verbose, params);
res <- list(fit=f, params=params);
verbose && str(verbose, res);
verbose && exit(verbose);
res;
})
setMethodS3("fitC1C2Densities", "PairedPSCBS", function(fit, adjust=0.2, tol=0.05, orderBy=c("density", "x"), ...) {
orderBy <- match.arg(orderBy);
data <- extractC1C2(fit);
n <- data[,4, drop=TRUE];
n <- sqrt(n);
w <- n/sum(n, na.rm=TRUE);
adjust <- 0.2;
dList <- list();
for (cc in 1:2) {
y <- data[,cc];
ok <- is.finite(y) & is.finite(w);
y <- y[ok];
wt <- w[ok]/sum(w[ok]);
d <- density(y, weights=wt, adjust=adjust);
dList[[cc]] <- d;
}
names(dList) <- colnames(data)[1:2];
type <- NULL; rm(list="type");
pList <- lapply(dList, FUN=function(d) {
p <- .findPeaksAndValleys(d, tol=tol);
p <- subset(p, type == "peak");
p <- p[order(p[[orderBy]], decreasing=c("x"=FALSE, "density"=TRUE)[orderBy]),,drop=FALSE];
});
names(pList) <- names(dList);
return(list(dList=dList, pList=pList));
}) |
test_that("with and without title", {
expect_snapshot({
pillar(add_special(10^(1:6)))
pillar(add_special(10^(1:6)), title = "crayon")
pillar(add_special(10^(1:6)), title = "short")
pillar(add_special(10^(1:6)), title = "somewhat_wider")
pillar(add_special(10^(1:6)), title = "exactly_fifteen")
pillar(add_special(10^(1:6)), title = "absolutely_breaking_all_sensible_boundaries", width = 18)
})
}) |
context("Test main functions")
test_that("test zones",{
x <- system.file("extdata", "yangambi.png",
package = "foto",
mustWork = TRUE)
expect_output(str(foto(x = raster::raster(x), plot = FALSE)))
expect_output(str(foto(x = raster::brick(x), plot = FALSE)))
expect_output(str(foto(x = x, plot = FALSE)))
expect_output(str(foto(x = raster::raster(x), plot = TRUE)))
expect_error(foto())
expect_error(foto(x = "./no_image.png"))
expect_error(foto(x = raster::raster(x),
plot = FALSE,
method = "xx"))
})
test_that("test mw",{
r <- raster::crop(raster::raster(system.file("extdata", "yangambi.png",
package = "foto",
mustWork = TRUE)),
raster::extent(1,30,1,30))
expect_output(str(foto(r,
plot = FALSE,
window_size = 25,
method = "mw")))
})
test_that("test normalization",{
x <- c(1,5,10)
expect_output(str(normalize(x)))
expect_error(normalize())
}) |
raw_moment <- function(f, order) {
x_tbl <- meta_x_tbl(f)
switch(
meta_type(f),
discrete = dotprod(x_tbl[["x"]]^order, x_tbl[["prob"]]),
continuous = raw_moment_con(x_tbl, order)
)
}
raw_moment_con <- function(x_tbl, k) {
n <- nrow(x_tbl)
x_l <- x_tbl[["x"]][-n]
x_r <- x_tbl[["x"]][-1]
x_l_k <- x_l^k
x_l_k1 <- x_l_k * x_l
x_r_k <- x_r^k
x_r_k1 <- x_r_k * x_r
y_l <- x_tbl[["y"]][-n]
y_r <- x_tbl[["y"]][-1]
coeffs <- compute_piecelin_density_coeffs(x_tbl, seq_len(n - 1))
piece_moments <- coeffs[["slope"]] * (x_r_k1 * x_r - x_l_k1 * x_l) / (k + 2) +
coeffs[["intercept"]] * (x_r_k1 - x_l_k1) / (k + 1)
approx_piece_moments <- (x_r - x_l) * (x_l_k * y_l + x_r_k * y_r) / 2
diff_x_is_small <- (x_r - x_l <= 1e-3) & (pmax(y_l, y_r) >= 1e3)
piece_moments[diff_x_is_small] <- approx_piece_moments[diff_x_is_small]
sum(piece_moments)
}
compute_density_crossings <- function(f, g) {
op <- options(pdqr.assert_args = FALSE)
on.exit(options(op))
compute_piecequad_crossings(piecequad_density(f), piecequad_density(g))
}
piecequad_density <- function(f) {
x_tbl <- meta_x_tbl(f)
n <- nrow(x_tbl)
coeffs <- compute_piecelin_density_coeffs(x_tbl, seq_len(n - 1))
list(
x = x_tbl[["x"]],
a = rep(0, n - 1),
b = coeffs[["slope"]],
c = coeffs[["intercept"]]
)
}
compute_cdf_crossings <- function(f, g) {
op <- options(pdqr.assert_args = FALSE)
on.exit(options(op))
compute_piecequad_crossings(piecequad_cdf(f), piecequad_cdf(g))
}
piecequad_cdf <- function(f) {
x_tbl <- meta_x_tbl(f)
n <- nrow(x_tbl)
x_l <- x_tbl[["x"]][-n]
coeffs <- compute_piecelin_density_coeffs(x_tbl, seq_len(n - 1))
slope <- coeffs[["slope"]]
inter <- coeffs[["intercept"]]
list(
x = x_tbl[["x"]],
a = 0.5 * slope,
b = inter,
c = x_tbl[["cumprob"]][-n] - (0.5 * slope * x_l + inter) * x_l
)
}
compute_piecequad_crossings <- function(piecequad_1, piecequad_2) {
pair <- piecequad_pair_regrid(piecequad_1, piecequad_2)
grid <- pair[[1]][["x"]]
x_l <- grid[-length(grid)]
x_r <- grid[-1]
a <- pair[[1]][["a"]] - pair[[2]][["a"]]
b <- pair[[1]][["b"]] - pair[[2]][["b"]]
c <- pair[[1]][["c"]] - pair[[2]][["c"]]
quad_solutions <- solve_piecequad(a, b, c, x_l, x_r)
x_quad_1 <- quad_solutions[["solution_1"]]
x_quad_2 <- quad_solutions[["solution_2"]]
x_lin <- na_outside(-c / b, x_l, x_r)
is_const_sol <- is_zero(c)
is_const_sol[!is_const_sol] <- NA
x_const_1 <- x_l[is_const_sol]
x_const_2 <- x_r[is_const_sol]
is_quad <- !is_zero(a)
is_lin <- !(is_quad | is_zero(b))
is_const <- !(is_quad | is_lin)
res <- c(
x_quad_1[is_quad], x_quad_2[is_quad],
x_lin[is_lin],
x_const_1[is_const], x_const_2[is_const]
)
sort(unique(res[is.finite(res)]))
}
piecequad_pair_regrid <- function(piecequad_1, piecequad_2) {
x_1 <- piecequad_1[["x"]]
x_2 <- piecequad_2[["x"]]
left <- max(min(x_1), min(x_2))
right <- min(max(x_1), max(x_2))
if (left > right) {
num <- numeric(0)
return(list(
piecequad_1 = list(x = num, a = num, b = num, c = num),
piecequad_2 = list(x = num, a = num, b = num, c = num)
))
}
grid <- sort(union(x_1, x_2))
grid <- grid[(grid >= left) & (grid <= right)]
list(
piecequad_1 = piecequad_regrid(grid, piecequad_1),
piecequad_2 = piecequad_regrid(grid, piecequad_2)
)
}
piecequad_regrid <- function(grid, piecequad) {
grid <- rep(grid, length.out = max(2, length(grid)))
mids <- 0.5 * (grid[-1] + grid[-length(grid)])
inds <- findInterval(mids, piecequad[["x"]], all.inside = TRUE)
list(
x = grid,
a = piecequad[["a"]][inds],
b = piecequad[["b"]][inds],
c = piecequad[["c"]][inds]
)
}
solve_piecequad <- function(a, b, c, x_l, x_r) {
a_new <- a
b_new <- 2 * a * x_l + b
c_new <- (a * x_l + b) * x_l + c
discr_sqrt <- na_sqrt(b_new^2 - 4 * a_new * c_new)
t_sol_1 <- (-b_new + discr_sqrt) / (2 * a_new)
t_sol_2 <- (-b_new - discr_sqrt) / (2 * a_new)
x_sol_1 <- na_outside(x_l + t_sol_1, x_l, x_r)
x_sol_2 <- na_outside(x_l + t_sol_2, x_l, x_r)
list(solution_1 = x_sol_1, solution_2 = x_sol_2)
}
na_sqrt <- function(x) {
res <- rep(NA_real_, length(x))
x_is_pos <- is.finite(x) & (x >= 0)
res[x_is_pos] <- sqrt(x[x_is_pos])
res
}
na_outside <- function(x, left, right) {
x[!is.na(x) & ((x < left) | (x > right))] <- NA
x
}
approx_discrete <- function(f) {
assert_pdqr_fun(f)
n_grid <- get_approx_discrete_n_grid_option()
if (meta_type(f) == "continuous") {
disable_asserting_locally()
f <- form_retype(
form_regrid(f, n_grid = n_grid, method = "x"),
type = "discrete", method = "piecelin"
)
}
f
}
get_approx_discrete_n_grid_option <- function() {
n_grid <- getOption("pdqr.approx_discrete_n_grid")
enable_asserting_locally()
assert_type(
n_grid, is_single_number, min_val = 1,
x_name = 'Option "pdqr.approx_discrete_n_grid"',
type_name = "single number not less than 1"
)
n_grid
} |
library(act)
t <- examplecorpus@transcripts[[1]]
path <- tempfile(pattern = t@name, tmpdir = tempdir(),
fileext = ".srt")
\dontrun{
path <- file.path("PATH_TO_AN_EXISTING_FOLDER_ON_YOUR_COMPUTER",
paste(t@name, ".srt", sep=""))
}
act::export_srt(t=t, outputPath=path) |
expected <- eval(parse(text="FALSE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(list(age = 60), .Names = \"age\", row.names = c(NA, -1L), class = \"data.frame\"), \"numeric\")"));
.Internal(is.vector(argv[[1]], argv[[2]]));
}, o=expected); |
test_that("function works for each input type", {
d <- getBillSponsors("2007-08", "HB 1001", type = "df")
l <- getBillSponsors("2007-08", "HB 1001", type = "list")
x <- getBillSponsors("2007-08", "HB 1001", type = "xml")
expect_true(any(class(d) == "data.frame",is.null(d)))
expect_true(any(typeof(l) == "list",is.null(l)))
expect_true(any(typeof(x[[1]]) == "externalptr",is.null(x)))
})
test_that("function handles vector inputs", {
bills <- c("HB 1001", "HB 1002")
d <- getBillSponsors("2007-08", bills, type = "df")
l <- getBillSponsors("2007-08", bills, type = "list")
x <- getBillSponsors("2007-08", bills, type = "xml")
expect_true(any(identical(unique(d$BillId),bills),is.null(d)))
expect_true(any(identical(names(l),bills),is.null(l)))
expect_true(any(identical(names(x),paste("2007-08", bills, sep = "//")),is.null(x)))
})
test_that("function checks for proper formatting", {
expect_error(getBillSponsors("2007-2008", "1001"))
expect_error(getBillSponsors("2007-08", "1001"))
expect_error(getBillSponsors("1989-90", "HB 1001"))
}) |
file.edit(fname2)
source(fname2) |
context("publications")
test_that("publications basic functionality works", {
vcr::use_cassette("publications", {
aa <- publications(tsn = 70340)
})
expect_is(aa, "data.frame")
expect_is(aa, "tbl_df")
expect_is(aa$isbn, "character")
expect_gt(NROW(aa), 0)
})
test_that("publications - xml works", {
vcr::use_cassette("publications-xml", {
aa <- publications(tsn = 70340, wt = "xml")
})
expect_is(aa, "character")
expect_match(aa, "xmlns")
})
test_that("publications - raw JSON works", {
vcr::use_cassette("publications-json", {
aa <- publications(tsn = 70340, raw = TRUE)
})
expect_is(aa, "character")
expect_false(grepl("xmlns", aa))
})
test_that("publications fails well", {
expect_error(publications(), "\"tsn\" is missing")
expect_error(publications(tsn = 70340, wt = "ffa"), "'wt' must be one of")
vcr::use_cassette("publications-fails-well", {
expect_error(publications(tsn = "Asdfasdfa"),
"Bad Request \\(HTTP 400\\)", class = "error")
})
}) |
c33f <-
function(mati,b_hat,g_hat,k,amp){
c33 <- (mati[2,2] * g_hat^2 - 2 * mati[2,3] * b_hat * g_hat + mati[3,3]*b_hat^2) / (k * amp^2)
return(c33)
} |
initialize_non_glu <- function(module, input_dim, output_dim) {
gain_value <- sqrt((input_dim + output_dim)/sqrt(4*input_dim))
torch::nn_init_xavier_normal_(module$weight, gain = gain_value)
}
initialize_glu <- function(module, input_dim, output_dim) {
gain_value <- sqrt((input_dim + output_dim)/sqrt(input_dim))
torch::nn_init_xavier_normal_(module$weight, gain = gain_value)
}
gbn <- torch::nn_module(
"gbn",
initialize = function(input_dim, virtual_batch_size=128, momentum=0.01) {
self$input_dim <- input_dim
self$virtual_batch_size <- virtual_batch_size
self$bn = torch::nn_batch_norm1d(self$input_dim, momentum=momentum)
},
forward = function(x) {
chunks <- x$chunk(as.integer(ceiling(x$shape[1] / self$virtual_batch_size)), 1)
res <- lapply(chunks, self$bn)
torch::torch_cat(res, dim=1)
}
)
tabnet_encoder <- torch::nn_module(
"tabnet_encoder",
initialize = function(input_dim, output_dim,
n_d=8, n_a=8,
n_steps=3, gamma=1.3,
n_independent=2, n_shared=2, epsilon=1e-15,
virtual_batch_size=128, momentum=0.01,
mask_type="sparsemax") {
self$input_dim <- input_dim
self$output_dim <- output_dim
self$n_d <- n_d
self$n_a <- n_a
self$n_steps <- n_steps
self$gamma <- gamma
self$epsilon <- epsilon
self$n_independent <- n_independent
self$n_shared <- n_shared
self$virtual_batch_size <- virtual_batch_size
self$mask_type <- mask_type
self$initial_bn <- torch::nn_batch_norm1d(self$input_dim, momentum=momentum)
if (self$n_shared > 0) {
shared_feat_transform <- torch::nn_module_list()
for (i in seq_len(self$n_shared)) {
if (i == 1) {
shared_feat_transform$append(torch::nn_linear(
self$input_dim,
2*(n_d + n_a),
bias = FALSE)
)
} else {
shared_feat_transform$append(torch::nn_linear(
n_d + n_a, 2*(n_d + n_a), bias = FALSE
))
}
}
} else {
shared_feat_transform <- NULL
}
self$initial_splitter <- feat_transformer(
self$input_dim, n_d+n_a, shared_feat_transform,
n_glu_independent=self$n_independent,
virtual_batch_size=self$virtual_batch_size,
momentum=momentum
)
self$feat_transformers <- torch::nn_module_list()
self$att_transformers <- torch::nn_module_list()
for (step in seq_len(n_steps)) {
transformer <- feat_transformer(self$input_dim, n_d+n_a, shared_feat_transform,
n_glu_independent=self$n_independent,
virtual_batch_size=self$virtual_batch_size,
momentum=momentum)
attention <- attentive_transformer(n_a, self$input_dim,
virtual_batch_size=self$virtual_batch_size,
momentum=momentum,
mask_type=self$mask_type)
self$feat_transformers$append(transformer)
self$att_transformers$append(attention)
}
},
forward = function(x, prior) {
res <- torch::torch_tensor(0, device = x$device)
x <- self$initial_bn(x)
M_loss <- 0
att <- self$initial_splitter(x)[, (self$n_d + 1):N]
steps_output <- list()
for (step in seq_len(self$n_steps)) {
M <- self$att_transformers[[step]](prior, att)
M_loss <- M_loss + torch::torch_mean(torch::torch_sum(
torch::torch_mul(M, torch::torch_log(M + self$epsilon)),
dim = 2
))
prior <- torch::torch_mul(self$gamma - M, prior)
masked_x <- torch::torch_mul(M, x)
out <- self$feat_transformers[[step]](masked_x)
d <- torch::nnf_relu(out[.., 1:(self$n_d)])
steps_output[[step]] <- d
res <- torch::torch_add(res, d)
att <- out[, (self$n_d + 1):N]
}
M_loss <- M_loss/self$n_steps
list(res, M_loss, steps_output)
},
forward_masks = function(x) {
x <- self$initial_bn(x)
prior <- torch::torch_ones(x$shape, device = x$device)
M_explain <- torch::torch_zeros(x$shape, device = x$device)
att <- self$initial_splitter(x)[, (self$n_d+1):N]
masks <- list()
for (step in seq_len(self$n_steps)) {
M <- self$att_transformers[[step]](prior, att)
masks[[step]] <- M
prior <- torch::torch_mul(self$gamma - M, prior)
masked_x <- torch::torch_mul(M, x)
out <- self$feat_transformers[[step]](masked_x)
d <- torch::nnf_relu(out[.., 1:(self$n_d)])
step_importance <- torch::torch_sum(d, dim=2)
M_explain <- M_explain + torch::torch_mul(M, step_importance$unsqueeze(dim=2))
att <- out[, (self$n_d+1):N]
}
list(M_explain, masks)
}
)
tabnet_decoder <- torch::nn_module(
"tabnet_decoder",
initialize = function(input_dim, n_d=8,
n_steps=3, n_independent=2, n_shared=2,
virtual_batch_size=128, momentum=0.02) {
self$input_dim <- input_dim
self$n_d <- n_d
self$n_steps <- n_steps
self$n_independent <- n_independent
self$n_shared <- n_shared
self$virtual_batch_size <- virtual_batch_size
self$feat_transformers <- torch::nn_module_list()
self$reconstruction_layers <- torch::nn_module_list()
if (self$n_shared > 0) {
shared_feat_transform <- torch::nn_module_list()
for (i in seq_len(self$n_shared)) {
if (i == 1) {
shared_feat_transform$append(torch::nn_linear(
n_d, 2 * n_d, bias = FALSE)
)
} else {
shared_feat_transform$append(torch::nn_linear(
n_d, 2 * n_d, bias = FALSE)
)
}
}
} else {
shared_feat_transform <- NULL
}
for (step in seq_len(n_steps)) {
transformer <- feat_transformer(n_d, n_d, shared_feat_transform,
n_glu_independent=self$n_independent,
virtual_batch_size=self$virtual_batch_size,
momentum=momentum)
self$feat_transformers$append(transformer)
reconstruction_layer <- torch::nn_linear(n_d, self$input_dim, bias = FALSE)
initialize_non_glu(reconstruction_layer, n_d, self$input_dim)
self$reconstruction_layers$append(reconstruction_layer)
}
},
forward = function(steps_output) {
res <- torch::torch_tensor(0, device = steps_output[[1]]$device)
for (step_nb in seq_along(steps_output)) {
x <- self$feat_transformers[[step_nb]](steps_output[[step_nb]])
x <- self$reconstruction_layers[[step_nb]](steps_output[[step_nb]])
res <- torch::torch_add(res, x)
}
res
},
)
tabnet_pretrainer <- torch::nn_module(
"tabnet_pretrainer",
initialize = function(input_dim, pretraining_ratio=0.2,
n_d=8, n_a=8,
n_steps=3, gamma=1.3,
cat_idxs=c(), cat_dims=c(),
cat_emb_dim=1, n_independent=2,
n_shared=2, epsilon=1e-15,
virtual_batch_size=128, momentum=0.01,
mask_type="sparsemax") {
self$input_dim <- input_dim
self$pretraining_ratio <- pretraining_ratio
self$.check <- torch::nn_parameter(torch::torch_tensor(1, requires_grad = TRUE))
self$n_d <- n_d
self$n_a <- n_a
self$n_steps <- n_steps
self$gamma <- gamma
self$cat_idxs <- cat_idxs
self$cat_dims <- cat_dims
self$cat_emb_dim <- cat_emb_dim
self$epsilon <- epsilon
self$n_independent <- n_independent
self$n_shared <- n_shared
self$mask_type <- mask_type
self$initial_bn <- torch::nn_batch_norm1d(self$input_dim, momentum=momentum)
if (self$n_steps <= 0)
stop("n_steps should be a positive integer.")
if (self$n_independent == 0 && self$n_shared == 0)
stop("n_shared and n_independant can't be both zero.")
self$virtual_batch_size <- virtual_batch_size
self$embedder <- embedding_generator(input_dim, cat_dims, cat_idxs, cat_emb_dim)
self$post_embed_dim <- self$embedder$post_embed_dim
self$masker = random_obfuscator(self$pretraining_ratio)
self$encoder = tabnet_encoder(
input_dim=self$post_embed_dim,
output_dim=self$post_embed_dim,
n_d=n_d,
n_a=n_a,
n_steps=n_steps,
gamma=gamma,
n_independent=n_independent,
n_shared=n_shared,
epsilon=epsilon,
virtual_batch_size=virtual_batch_size,
momentum=momentum,
mask_type=mask_type
)
self$decoder = tabnet_decoder(
self$post_embed_dim,
n_d=n_d,
n_steps=n_steps,
n_independent=n_independent,
n_shared=n_shared,
virtual_batch_size=virtual_batch_size,
momentum=momentum
)
},
forward = function(x) {
embedded_x <- self$embedder(x)
if (self$training) {
masker_out_lst <- self$masker(embedded_x)
obf_vars <- masker_out_lst[[2]]
prior <- 1 - obf_vars
steps_out <- self$encoder(masker_out_lst[[1]], prior)[[3]]
res <- self$decoder(steps_out)
list(res,
embedded_x,
obf_vars)
} else {
prior <- torch::torch_ones(size = x$shape, device = x$device)
steps_out <- self$encoder(embedded_x, prior)[[3]]
res <- self$decoder(steps_out)
list(res,
embedded_x,
torch::torch_ones(embedded_x$shape, device = x$device))
}
},
forward_masks = function(x) {
embedded_x <- self$embedder(x)
self$encoder$forward_masks(embedded_x)
}
)
tabnet_no_embedding <- torch::nn_module(
"tabnet_no_embedding",
initialize = function(input_dim, output_dim,
n_d=8, n_a=8,
n_steps=3, gamma=1.3,
n_independent=2, n_shared=2, epsilon=1e-15,
virtual_batch_size=128, momentum=0.02,
mask_type="sparsemax") {
self$input_dim <- input_dim
self$output_dim <- output_dim
self$n_d <- n_d
self$n_a <- n_a
self$n_steps <- n_steps
self$gamma <- gamma
self$epsilon <- epsilon
self$n_independent <- n_independent
self$n_shared <- n_shared
self$virtual_batch_size <- virtual_batch_size
self$mask_type <- mask_type
self$initial_bn <- torch::nn_batch_norm1d(self$input_dim, momentum=0.01)
self$encoder <- tabnet_encoder(
input_dim=input_dim,
output_dim=output_dim,
n_d=n_d,
n_a=n_a,
n_steps=n_steps,
gamma=gamma,
n_independent=n_independent,
n_shared=n_shared,
epsilon=epsilon,
virtual_batch_size=virtual_batch_size,
momentum=momentum,
mask_type=mask_type
)
self$final_mapping <- torch::nn_linear(n_d, output_dim, bias=FALSE)
initialize_non_glu(self$final_mapping, n_d, output_dim)
},
forward = function(x) {
prior <- torch::torch_ones(size = x$shape, device = x$device)
self_encoder_lst <- self$encoder(x, prior)
steps_output <- self_encoder_lst[[1]]
M_loss <- self_encoder_lst[[2]]
res <- torch::torch_sum(torch::torch_stack(steps_output, dim=1), dim=1)
res <- self$final_mapping(res)
list(res, M_loss)
},
forward_masks = function(x) {
self$encoder$forward_masks(x)
}
)
tabnet_nn <- torch::nn_module(
"tabnet",
initialize = function(input_dim, output_dim, n_d=8, n_a=8,
n_steps=3, gamma=1.3, cat_idxs=c(), cat_dims=c(), cat_emb_dim=1,
n_independent=2, n_shared=2, epsilon=1e-15,
virtual_batch_size=128, momentum=0.02,
mask_type="sparsemax") {
self$cat_idxs <- cat_idxs
self$cat_dims <- cat_dims
self$cat_emb_dim <- cat_emb_dim
self$.check <- torch::nn_parameter(torch::torch_tensor(1, requires_grad = TRUE))
self$input_dim <- input_dim
self$output_dim <- output_dim
self$n_d <- n_d
self$n_a <- n_a
self$n_steps <- n_steps
self$gamma <- gamma
self$epsilon <- epsilon
self$n_independent <- n_independent
self$n_shared <- n_shared
self$mask_type <- mask_type
if (self$n_steps <= 0)
stop("n_steps should be a positive integer.")
if (self$n_independent == 0 && self$n_shared == 0)
stop("n_shared and n_independant can't be both zero.")
self$virtual_batch_size <- virtual_batch_size
self$embedder <- embedding_generator(input_dim, cat_dims, cat_idxs, cat_emb_dim)
self$post_embed_dim <- self$embedder$post_embed_dim
self$tabnet <- tabnet_no_embedding(self$post_embed_dim, output_dim, n_d, n_a, n_steps,
gamma, n_independent, n_shared, epsilon,
virtual_batch_size, momentum, mask_type)
},
forward = function(x) {
x <- self$embedder(x)
self$tabnet(x)
},
forward_masks = function(x) {
x <- self$embedder(x)
self$tabnet$forward_masks(x)
}
)
attentive_transformer <- torch::nn_module(
"attentive_transformer",
initialize = function(input_dim, output_dim,
virtual_batch_size=128,
momentum=0.02,
mask_type="sparsemax") {
self$fc <- torch::nn_linear(input_dim, output_dim, bias=FALSE)
initialize_non_glu(self$fc, input_dim, output_dim)
self$bn <- gbn(output_dim, virtual_batch_size=virtual_batch_size,
momentum=momentum)
if (mask_type == "sparsemax")
self$selector <- torch::nn_contrib_sparsemax(dim=-1)
else if (mask_type == "entmax")
self$selector <- entmax(dim=-1)
else
stop("Please choose either sparsemax or entmax as masktype")
},
forward = function(priors, processed_feat) {
x <- self$fc(processed_feat)
x <- self$bn(x)
x <- torch::torch_mul(x, priors)
x <- self$selector(x)
x
}
)
feat_transformer <- torch::nn_module(
"feat_transformer",
initialize = function(input_dim, output_dim, shared_layers, n_glu_independent,
virtual_batch_size=128, momentum=0.02) {
params <- list(
'n_glu'= n_glu_independent,
'virtual_batch_size'= virtual_batch_size,
'momentum'= momentum
)
if (is.null(shared_layers)) {
self$shared <- torch::nn_identity()
is_first <- TRUE
} else {
self$shared <- glu_block(input_dim, output_dim,
first=TRUE,
shared_layers=shared_layers,
n_glu=length(shared_layers),
virtual_batch_size=virtual_batch_size,
momentum=momentum)
is_first <- FALSE
}
if (n_glu_independent == 0) {
self$specifics <- torch::nn_identity()
} else {
if (is_first)
spec_input_dim <- input_dim
else
spec_input_dim <- output_dim
self$specifics <- do.call(glu_block, append(
list(spec_input_dim, output_dim, first = is_first),
params
))
}
},
forward = function(x) {
x <- self$shared(x)
x <- self$specifics(x)
x
}
)
glu_block <- torch::nn_module(
"glu_block",
initialize = function(input_dim, output_dim, n_glu=2, first=FALSE,
shared_layers=NULL,
virtual_batch_size=128, momentum=0.02) {
self$first <- first
self$shared_layers <- shared_layers
self$n_glu <- n_glu
self$glu_layers <- torch::nn_module_list()
params = list(
'virtual_batch_size'= virtual_batch_size,
'momentum'= momentum
)
if (length(shared_layers) > 0)
fc <- shared_layers[[1]]
else
fc <- NULL
self$glu_layers$append(do.call(glu_layer, append(
list(input_dim, output_dim, fc = fc),
params
)))
if (self$n_glu >= 2) {
for (glu_id in 2:(self$n_glu)) {
if (length(shared_layers) > 0)
fc <- shared_layers[[glu_id]]
else
fc <- NULL
self$glu_layers$append(do.call(glu_layer, append(
list(output_dim, output_dim, fc = fc),
params
)))
}
}
},
forward = function(x) {
scale <- torch::torch_sqrt(torch::torch_tensor(0.5, device = x$device))
if (self$first) {
x <- self$glu_layers[[1]](x)
layers_left <- seq_len(self$n_glu)[-1]
} else {
layers_left <- seq_len(self$n_glu)
}
for (glu_id in layers_left) {
x <- torch::torch_add(x, self$glu_layers[[glu_id]](x))
x <- x*scale
}
x
}
)
glu_layer <- torch::nn_module(
"glu_layer",
initialize = function(input_dim, output_dim, fc=NULL,
virtual_batch_size=128, momentum=0.02) {
self$output_dim <- output_dim
if (!is.null(fc))
self$fc <- fc
else
self$fc <- torch::nn_linear(input_dim, 2*output_dim, bias = FALSE)
initialize_glu(self$fc, input_dim, 2*output_dim)
self$bn <- gbn(2*output_dim, virtual_batch_size=virtual_batch_size,
momentum=momentum)
},
forward = function(x) {
x <- self$fc(x)
x <- self$bn(x)
out <- torch::torch_mul(
x[, 1:self$output_dim],
torch::torch_sigmoid(x[, (self$output_dim+1):N])
)
out
}
)
embedding_generator <- torch::nn_module(
"embedding_generator",
initialize = function(input_dim, cat_dims, cat_idxs, cat_emb_dim) {
if (length(cat_dims) == 0 || length(cat_idxs) == 0) {
self$skip_embedding <- TRUE
self$post_embed_dim <- input_dim
return(invisible(NULL))
}
self$skip_embedding <- FALSE
if (length(cat_emb_dim) == 1)
self$cat_emb_dims <- rep(cat_emb_dim, length(cat_idxs))
else
self$cat_emb_dims <- cat_emb_dim
if (length(self$cat_emb_dims) != length(cat_dims)){
msg = "cat_emb_dim and cat_dims must be lists of same length, got {length(self$cat_emb_dims)} and {length(cat_dims)}"
stop(msg)
}
self$post_embed_dim <- as.integer(input_dim + sum(self$cat_emb_dims) - length(self$cat_emb_dims))
self$embeddings <- torch::nn_module_list()
sorted_idx <- order(cat_idxs)
cat_dims <- cat_dims[sorted_idx]
self$cat_emb_dims <- self$cat_emb_dims[sorted_idx]
for (i in seq_along(cat_dims)) {
self$embeddings$append(
torch::nn_embedding(
cat_dims[i],
self$cat_emb_dims[i]
)
)
}
self$continuous_idx <- rep(TRUE, input_dim)
self$continuous_idx[cat_idxs] <- FALSE
},
forward = function(x) {
if (self$skip_embedding) {
return(x)
}
cols <- list()
cat_feat_counter <- 1
for (i in seq_along(self$continuous_idx)) {
if (self$continuous_idx[i]) {
cols[[i]] <- x[,i]$to(dtype = torch::torch_float())$view(c(-1, 1))
} else {
cols[[i]] <- self$embeddings[[cat_feat_counter]](x[, i]$to(dtype = torch::torch_long()))
cat_feat_counter <- cat_feat_counter + 1
}
}
post_embeddings <- torch::torch_cat(cols, dim=2)
post_embeddings
}
)
random_obfuscator <- torch::nn_module(
"random_obfuscator",
initialize = function(pretraining_ratio) {
if (pretraining_ratio <= 0 || pretraining_ratio >= 1) {
pretraining_ratio <- 0.5
}
self$pretraining_ratio <- pretraining_ratio
},
forward = function(x) {
ones <- torch::torch_ones(size = x$shape, device="cpu")
obfuscated_vars <- torch::torch_bernoulli(self$pretraining_ratio * ones)$to(device=x$device)
masked_input = torch::torch_mul(1 - obfuscated_vars, x)
list(masked_input, obfuscated_vars)
}
) |
test_that("read_builtin works", {
expect_error(read_builtin(AirPassengers, "datasets"))
expect_error(read_builtin("nasa", "readr"))
if (!"dplyr" %in% loadedNamespaces()) {
expect_error(read_builtin("starwars"))
}
expect_true(is.data.frame(read_builtin("BOD", "datasets")))
if ("datasets" %in% loadedNamespaces()) {
expect_true(is.data.frame(read_builtin("BOD")))
}
}) |
PredictivePosterior.TSPNDE <- function (n1,
m2,
u2,
logitP.fixed,
p,
U,
mu,
sigma) {
s <- length(n1)
t <- length(u2)
p.bkp <- p
Theta <- lapply(1:nrow(p),function(i) lnTheta(mu[i,],sigma[i,],s,t))
simData <- lapply(1:nrow(p),function(i) simTSPNDE(n1,U[i,],p[i,],Theta[[i]]))
discrep <- t(sapply(1:nrow(p),function(k){
temp1.o <- sqrt(m2[,1:t]) - sqrt(n1 * t(t(Theta[[k]]) * p[k,1:t]))
notmissing <- !is.na(temp1.o)
d1.m2.o <- sum(temp1.o^2,na.rm=TRUE)
temp1.s <- sqrt(simData[[k]]$m2[,1:t]) - sqrt(n1 * t(t(Theta[[k]]) * p[k,1:t]))
d1.m2.s <- sum(temp1.s[notmissing]^2,na.rm=TRUE)
temp2.o <- sqrt(u2) - sqrt(U[k,] * p[k,1:t])
notmissing <- !is.na(temp2.o)
d1.u2.o <- sum(temp2.o^2,na.rm=TRUE)
temp2.s <- sqrt(simData[[k]]$u2) - sqrt(U[k,] * p[k,1:t])
d1.u2.s <- sum(temp2.s[notmissing]^2,na.rm=TRUE)
d2.m2.o <- -2 * sum(sapply(1:s,function(i){
cellProbs <- Theta[[k]][i,] * p[k,1:t]
cellProbs <- c(cellProbs,1-sum(cellProbs))
stats::dmultinom(m2[i,],n1[i],cellProbs,log=TRUE)
}))
notmissing <- !is.na(u2)
d2.u2.o <- -2 * sum(stats::dbinom(u2[notmissing],U[k,notmissing],p[k,notmissing],log=TRUE))
d2.o <- d2.m2.o + d2.u2.o
d2.m2.s <- -2 * sum(sapply(1:s,function(i){
cellProbs <- Theta[[k]][i,] * p[k,1:t]
cellProbs <- c(cellProbs,1-sum(cellProbs))
stats::dmultinom(simData[[k]]$m2[i,],n1[i],cellProbs,log=TRUE)
}))
d2.u2.s <- -2 * sum(stats::dbinom(simData[[k]]$u2[notmissing],U[k,notmissing],p[k,notmissing],log=TRUE))
d2.s <- d2.m2.s + d2.u2.s
c(d1.m2.o, d1.m2.s, d2.m2.o, d2.m2.s,
d1.u2.o, d1.u2.s, d2.u2.o, d2.u2.s,
d1.m2.o+d1.u2.o, d1.m2.s+d1.u2.s, d2.o, d2.s)
}))
discrep
}
lnTheta <- function(mu,sigma,s,t){
tmp <- t(sapply(1:s,function(i){
tmp1 <- stats::pnorm(log(1:(t-i+1)),mu[i],sigma[i]) -
stats::pnorm(log(1:(t-i+1)-1),mu[i],sigma[i])
c(rep(0,i-1),tmp1)
}))
}
simTSPNDE <- function(n1,U,p,Theta){
s <- length(n1)
t <- length(U)
m2 <- t(sapply(1:length(n1),function(i){
cellProbs <- Theta[i,] * p
cellProbs <- c(cellProbs,1-sum(cellProbs))
stats:rmultinom(1,n1[i],cellProbs)[1:t]
}))
m2 <- cbind(m2,n1-apply(m2,1,sum))
u2 <- stats::rbinom(t,U,p)
return(list(m2=m2,u2=u2))
} |
twoMarkerDistribution <- function(x, id, partialmarker1, partialmarker2, rho, loopBreakers = NULL,
eliminate = 99, verbose = TRUE) {
if(is.pedList(x)) {
if(is.marker(partialmarker1) || is.marker(partialmarker2))
stop2("When `x` has multiple components, the partial markers must be attached")
pednr = getComponent(x, id, checkUnique = TRUE)
x = x[[pednr]]
}
if(!is.ped(x))
stop2("Input is not a pedigree")
if(!isCount(eliminate, minimum = 0))
stop2("`eliminate` must be a nonnegative integer")
m1 = partialmarker1
if (!is.marker(m1)) {
if(length(m1) != 1)
stop2("`partialmarker1` must have length 1")
m1 = getMarkers(x, markers = m1)[[1]]
}
m2 = partialmarker2
if (!is.marker(m2)) {
if(length(m2) != 1)
stop2("`partialmarker2` must have length 1")
m2 = getMarkers(x, markers = m2)[[1]]
}
if (!is.null(x$LOOP_BREAKERS))
stop2("`ped` objects with pre-broken loops are not allowed as input to `twoMarkerDistribution`")
if (!identical(chrom(m1), chrom(m2)))
stop2("Partial markers are on different chromosomes: ", toString(c(chrom(m1), chrom(m2))))
onX = isXmarker(m1)
XandMale = onX && getSex(x, id) == 1
if (verbose) {
cat("Known genotypes:\n")
df = as.data.frame(setMarkers(x, list(m1, m2)))[-(2:4)]
df = cbind(df, arrow = "", stringsAsFactors = FALSE)
df$arrow[internalID(x, id)] = " <==="
names(df)[4] = ""
print(df, row.names = FALSE)
cat("\nAllele frequencies, marker 1:\n")
print(data.frame(as.list(afreq(m1)), check.names = FALSE), row.names = FALSE)
cat("\nAllele frequencies, marker 2:\n")
print(data.frame(as.list(afreq(m2)), check.names = FALSE), row.names = FALSE)
cat("\nRecombination rate :", rho)
cat("\nChromosome type :", ifelse(onX, "X-linked", "autosomal"))
cat("\nTarget individual :", id, "\n")
}
starttime = Sys.time()
grid.subset = fastGrid(c(genoCombinations(x, m1, id, make.grid = FALSE),
genoCombinations(x, m2, id, make.grid = FALSE)))
if (x$UNBROKEN_LOOPS) {
x = breakLoops(setMarkers(x, list(m1, m2)), loopBreakers = loopBreakers, verbose = verbose)
m1 = x$MARKERS[[1]]
m2 = x$MARKERS[[2]]
}
int.id = internalID(x, id)
allgenos1 = allGenotypes(nAlleles(m1))
allgenos2 = allGenotypes(nAlleles(m2))
alleles1 = alleles(m1)
alleles2 = alleles(m2)
if (XandMale) {
geno.names = list(alleles1, alleles2)
}
else {
gt1.strings = paste(alleles1[allgenos1[, 1]], alleles1[allgenos1[, 2]], sep = "/")
gt2.strings = paste(alleles2[allgenos2[, 1]], alleles2[allgenos2[, 2]], sep = "/")
geno.names = list(gt1.strings, gt2.strings)
}
probs = array(0, dim = lengths(geno.names, use.names = FALSE), dimnames = geno.names)
probs.subset = grid.subset
if(XandMale) {
homoz1 = which(allgenos1[,1] == allgenos1[,2])
homoz2 = which(allgenos2[,1] == allgenos2[,2])
probs.subset[, 1] = match(probs.subset[, 1], homoz1)
probs.subset[, 2] = match(probs.subset[, 2], homoz2)
}
marginal = likelihood2(x, marker1 = m1, marker2 = m2, rho = rho, eliminate = eliminate)
if (marginal == 0)
stop2("Partial marker data is impossible")
if(verbose) {
cat("Marginal likelihood:", marginal, "\n")
cat("Calculations needed:", nrow(grid.subset), "\n")
}
probs[probs.subset] = apply(grid.subset, 1, function(allg_rows) {
m1[int.id, ] = allgenos1[allg_rows[1], ]
m2[int.id, ] = allgenos2[allg_rows[2], ]
likelihood2(x, marker1 = m1, marker2 = m2, rho = rho, eliminate = eliminate)
})
totalTime = format(Sys.time() - starttime, digits = 3)
if(verbose)
cat("\nAnalysis finished in", totalTime, "\n")
probs/marginal
} |
Rain <- list()
Rain$rain <- as.matrix(read.csv("Rain_rain.csv", header = FALSE)) + 1
Rain$months <- as.matrix(read.csv("Rain_months.csv", header = FALSE))
save(Rain, file="Rain.RData") |
validate.plinkfiles <- function(geno.files){
if(!is.data.frame(geno.files) && !is.matrix(geno.files)){
msg <- 'geno.files should be a data frame'
stop(msg)
}
if(is.matrix(geno.files)){
geno.files <- as.data.frame(geno.files)
}
colnames(geno.files) <- convert.header(colnames(geno.files), c('fam', 'bim', 'bed'))
if(!all(c('fam', 'bim', 'bed') %in% colnames(geno.files))){
msg <- 'geno.files should be a data frame with columns \'fam\', \'bim\', \'bed\''
stop(msg)
}
geno.files <- geno.files[, c('fam', 'bim', 'bed')]
fam <- geno.files$fam
cc <- rep('NULL', 6)
cc[1] <- 'character'
for(f in fam){
re <- try(tmp <- read.table(f, header = FALSE, as.is = TRUE, colClasses = cc, nrows = 1e3))
if("try-error" %in% class(re)){
msg <- paste0('Cannot load ', f)
stop(msg)
}
rm(tmp)
gc()
}
bim <- geno.files$bim
cc <- rep('NULL', 6)
cc[2] <- 'character'
for(b in bim){
re <- try(tmp <- read.table(b, header = FALSE, as.is = TRUE, colClasses = cc, nrows = 1e3))
if("try-error" %in% class(re)){
msg <- paste0('Cannot load ', b)
stop(msg)
}
rm(tmp)
gc()
}
geno.files
} |
whm <- function(yy, xx, var.function = "power", tuning.para = 1.345, ite = 5){
c <- tuning.para
Y <- as.matrix(yy)
n <- length(Y)
z <- c()
rlm.model <- rlm(yy ~ xx -1, k = c)
X <- as.matrix(rlm.model$x)
switch(var.function,
"power"={
est <- function(x){sum(chi((Y-mu)/(phi*abs(mu)^x))*log(abs(mu)))}
var.func <- function(mu, esti, phi){phi*abs(mu)^esti}
est_phi <- function(x){sum(chi((Y-mu)/(x*abs(mu)^esti)))}
},
"exponential"={
est <- function(x){sum(chi((Y-mu)/(phi*exp(x*abs(mu))))*abs(mu))}
var.func <- function(mu, esti, phi){phi*exp(esti*abs(mu))}
est_phi <- function(x){sum(chi((Y-mu)/(x*exp(esti*abs(mu)))))}
},
stop("Wrong function name")
)
mu <- rlm.model$fitted.values
phi <- 1
for(i in 1: ite){
esti<- uniroot(est,c(-2,2))$root
phi <- uniroot(est_phi,c(0,2))$root
pearson_res <- (Y-mu) / (var.func(mu, esti, phi))
w_i <- as.vector((psi.Huber(pearson_res, c)/(pearson_res)))
W <- pmin(as.vector(w_i / (var.func(mu, esti, phi)))^2, 1)
B_est <- solve(crossprod(X,W*X), crossprod(X,W*Y))
mu <- X %*% B_est
}
pearson_res <- (Y-mu) / (var.func(mu, esti, phi))
p<- length(B_est)
psip <- dpsi.Huber(pearson_res,c)
mn <-mean(psip)
K <- 1 + p/n * var(psip)/(mn^2)
CC <- solve(t(X)%*% diag(as.vector(1 / (var.func(mu, esti, phi))))^2 %*% X)
vcov.mod<-(1/(n-p))*sum(psi.Huber(pearson_res,c)^2)/mn^2*K^2*CC
sum_table <- data.frame(Estimate = B_est, Std.Error=sqrt(diag(vcov.mod)))
sum_table$t_value <- sum_table$Estimate/sum_table$Std.Error
sum_table<- round(sum_table[,-5], digits = 5)
z$coefficients <- B_est
z$residuals <- (Y-mu)
z$fitted.values <- mu
z$vcov <- vcov.mod
z$summary <-sum_table
z$model <- cbind(yy,X)
z$tuningpara <- list(c = c)
z$varpara <-data.frame(gamma=esti, phi= phi)
cat("Summary : \n ")
print(z$summary)
cat("\n Tuning parameter:",c)
z
} |
context("profile information metrics")
test_that(".pii works", {
x <- .pii(i = rep(1, 10), baseline = TRUE, numericDigits = 4)
expect_equal(x, 1L)
x <- .pii(i = c(1:10), baseline = TRUE, numericDigits = 4)
expect_equal(x, 2L)
x <- .pii(i = letters, baseline = TRUE, numericDigits = 4)
expect_equal(x, 3.615, tolerance = 0.001)
})
test_that("basic operation", {
a <- data.frame(id = 'A', top = 0, bottom = 100, p = 5)
b <- data.frame(id = 'B', top = c(0, 10, 20, 30, 40, 50), bottom = c(10, 20, 30, 40, 50, 100), p = rep(5, times = 6))
x <- rbind(a, b)
depths(x) <- id ~ top + bottom
p <- profileInformationIndex(x, vars = c('p'), method = 'sum')
expect_equal(as.vector(p), c(3, 4.3), tolerance = 0.1)
p <- profileInformationIndex(x, vars = c('p'), method = 'mean')
expect_equal(as.vector(p), c(0, 0.458), tolerance = 0.1)
p <- profileInformationIndex(x, vars = c('p'), method = 'median')
expect_equal(as.vector(p), c(0, 0.529), tolerance = 0.1)
p <- profileInformationIndex(x, vars = c('p'), method = 'sum', baseline = FALSE)
expect_equal(as.vector(p), c(29, 62))
p <- profileInformationIndex(x, vars = c('p'), method = 'mean', baseline = FALSE)
expect_equal(as.vector(p), c(8.666, 19.666), tolerance = 0.1)
p <- profileInformationIndex(x, vars = c('p'), method = 'median', baseline = FALSE)
expect_equal(as.vector(p), c(8, 23))
}) |
test_that("top_n returns n rows", {
test_df <- data.frame(x = 1:10, y = 11:20)
top_four <- test_df %>% top_n(4, y)
expect_equal(dim(top_four), c(4, 2))
})
test_that("top_n() handles missing `wt`", {
df <- data.frame(x = c(10, 4, 1, 6, 3, 1, 1))
expect_message(
regexp = "Selecting by x",
expect_identical(top_n(df, 2)$x, c(10, 6))
)
})
test_that("top_n() handles calls", {
expect_identical(top_n(mtcars, 2, -disp), top_n(mtcars, -2, disp))
})
test_that("top_n() quotes n", {
expect_snapshot(res1 <- top_n(mtcars, n() * .5))
expect_snapshot(res2 <- top_n(mtcars, 16))
expect_identical(res1, res2)
})
test_that("top_frac() is a shorthand for top_n(n()*)", {
expect_identical(top_n(mtcars, n() * .5, disp), top_frac(mtcars, .5, disp))
expect_snapshot(res1 <- top_n(mtcars, n() * .5))
expect_snapshot(res2 <- top_frac(mtcars, .5))
}) |
ctiList <- function(x, cond){
cond <- noblanks(cond)
condListed <- extract_asf(cond)
csfLengths <- lengths(condListed)
ff <- hstrsplit(condListed, c("<*->", "+", "*"),
relist = FALSE, fixed = c(FALSE, TRUE, TRUE))
if (x$type == "mv") ff[] <- sub("=[0-9]+", "", as.vector(ff))
ll <- as.vector(rowsum(collapse(attr(ff, "lengths"), 2:3)[[1]],
rep(seq_along(csfLengths), csfLengths)))
nmsList <- C_relist_Char(toupper(as.vector(ff)), ll)
nmsList <- lapply(nmsList, function(x) sort.default(unique.default(x)))
nmsStrings <- C_mconcat(nmsList, "\r")
uNmsStrings <- unique(nmsStrings)
uNmsList <- strsplit(uNmsStrings, "\r", fixed = TRUE)
if (!all(unique(unlist(uNmsList)) %in% names(x$nVal))){
uNmsList[] <- lapply(uNmsList, intersect, names(x$nVal))
}
indices <- match(nmsStrings, uNmsStrings)
tbls <- lapply(uNmsList, function(nms) selectFactors(x, nms))
structure(c(
x[c("type", "resp_nms", "nVal", "uniqueValues")],
list(scores = x$scores[0, , drop = FALSE],
conds = cond,
tbls = tbls,
indices = indices)),
class = "ctiList")
}
useCtiList <- function(cti, maxnrow = getOption("ctiListLimit")){
sepflag <- getOption("useCtiList")
if (sepflag %in% c(TRUE, FALSE))
return(sepflag)
prod(cti$nVal) > maxnrow
}
selectFactors <- function(x, nms){
if (setequal(names(x$nVal), nms)) return(x)
innms <- names(x$nVal)
x$nVal <- x$nVal[nms]
x$uniqueValues <- x$uniqueValues[nms]
x$config <- x$config[nms]
keepValues <- unique(unlist(x$config, use.names = FALSE))
x$resp_nms <- x$resp_nms[if (x$type == "mv") keepValues else match(nms, innms)]
x$config[] <- C_relist_Int(seq_along(keepValues), x$nVal)
x$valueId <- x$valueId[, nms, drop = FALSE]
x$valueId[] <- match(x$valueId, keepValues)
rownames(x$valueId) <- NULL
x$scores <- x$scores[, keepValues, drop = FALSE]
if (anyDuplicated(x$scores)>0){
rows <- do.call(paste, c(asplit(x$scores, 2), list(sep = "\r")))
urows <- unique(rows)
rowId <- match(rows, unique(rows))
urows <- match(seq_along(urows), rowId)
x$valueId <- x$valueId[urows, , drop = FALSE]
x$scores <- x$scores[urows, , drop = FALSE]
x$freq <- as.vector(rowsum(x$freq, rowId))
}
x
}
getPos <- function(x){
out <- integer(length(x$conds))
b <- 0
for (i in seq_along(x$tbls)){
pos <- which(x$indices == i)
out[pos] <- b + seq_along(pos)
b <- b + length(pos)
}
out
}
`[.ctiList` <- function(x, i){
out <- x
out$conds <- x$conds[i]
out$indices <- x$indices[i]
uInd <- unique(out$indices)
out$tbls <- out$tbls[uInd]
out$indices <- match(out$indices, uInd)
out
}
full.ct.ctiList <- function(x, ...){
x$tbls[] <- lapply(x$tbls, full.ct.cti)
x$freq <- prod(x$nVal)
x
}
.det.ctiList <- function(x, cond = x$conds,
what = c("inus", "cyclic", "exhaustiveness", "faithfulness", "coherence", "redundant"),
available = what, cycle.type = "factor", in.csf = FALSE){
out <- mapply(.det.cti,
x = x$tbls, cond = split(x$conds, x$indices),
MoreArgs = list(what = what, available = available, cycle.type = cycle.type,
in.csf = in.csf),
SIMPLIFY = FALSE, USE.NAMES = FALSE)
out <- do.call(rbind, out)
out[getPos(x), , drop = FALSE]
}
.inus.ctiList <- function(x, cond, qtypes,
full = FALSE, const.ok = FALSE, csf.info = FALSE){
out0 <- mapply(.inus.cti,
x = x$tbls, cond = split(x$conds, x$indices),
qtypes = split(qtypes, x$indices),
MoreArgs = list(full = full, const.ok = const.ok, csf.info = csf.info),
SIMPLIFY = FALSE, USE.NAMES = FALSE)
out <- do.call(c, out0)
out <- out[getPos(x)]
if (csf.info){
csf.info <- do.call(rbind, lapply(out0, attr, "csf.info"))
csf.info <- csf.info[getPos(x), , drop = FALSE]
attr(out, "csf.info") <- csf.info
}
out
}
.redund.ctiList <- function(x, cond, simplify = TRUE, full = FALSE, names = TRUE){
out <- mapply(.redund.cti, x = x$tbls, cond = split(x$conds, x$indices),
MoreArgs = list(simplify = FALSE, full = full, names = names),
SIMPLIFY = FALSE, USE.NAMES = FALSE)
out <- unlist(out, recursive = FALSE)[getPos(x)]
if (simplify && length(ul <- unique(lengths(out, use.names = FALSE))) == 1L){
nms <- names(out)
out <- matrix(unlist(out, use.names = FALSE), ncol = ul, byrow = TRUE)
if (names) rownames(out) <- nms
}
out
}
exff.ctiList <- function(x, cond, num = TRUE, names = TRUE,
cti.full = full.ct(x, cond = cond),
...){
cti <- lapply(x$tbls, unique_cti_cs)
out <- mapply(calcExff,
cti, cti.full = cti.full$tbls, cond = split(x$conds, x$indices),
MoreArgs = list(num = num, names = names),
SIMPLIFY = FALSE, USE.NAMES = FALSE)
out <- do.call(rbind, out)
out[getPos(x), , drop = FALSE]
}
.minCsf.ctiList <- function(x, cond = x$conds, verbose = FALSE, ...){
rr <- .redund.ctiList(x, cond, full = TRUE, simplify = FALSE)
anyRed <- m_any(rr)
if (verbose){
n.asf <- lengths(rr, use.names = FALSE)
cat("csf-length ", n.asf[1], ": ",
sum(anyRed), " of ", length(cond), " csf are reducible ",
sep = "")
}
noRed <- names(rr)[!anyRed]
if (!any(anyRed)){
if (verbose) cat("\n")
return(noRed)
}
withRed <- rr[anyRed]
condNew <- .redCsf(withRed)
condNewOrigin <- which(anyRed)[attr(condNew, "orig")]
dups <- duplicated(condNew)
if (verbose) cat("(", sum(!dups), " uniques)\n", sep = "")
x$conds <- condNew[!dups]
x$indices <- x$indices[condNewOrigin][!dups]
if (!all(seq_along(x$tbls) %in% x$indices)){
used <- intersect(seq_along(x$tbls), x$indices)
x$tbls <- x$tbls[used]
x$indices <- match(x$indices, used)
}
recurs <- .minCsf.ctiList(x, verbose = verbose)
c(recurs, noRed)
} |
dwtest <- function(formula, order.by = NULL, alternative = c("greater", "two.sided", "less"),
iterations = 15, exact = NULL, tol = 1e-10, data = list())
{
dname <- paste(deparse(substitute(formula)))
alternative <- match.arg(alternative)
if(!inherits(formula, "formula")) {
if(!is.null(w <- weights(formula))) {
if(!isTRUE(all.equal(as.vector(w), rep(1L, length(w)))))
stop("weighted regressions are not supported")
}
X <- if(is.matrix(formula$x))
formula$x
else model.matrix(terms(formula), model.frame(formula))
y <- if(is.vector(formula$y))
formula$y
else model.response(model.frame(formula))
} else {
mf <- model.frame(formula, data = data)
y <- model.response(mf)
X <- model.matrix(formula, data = data)
}
if(!is.null(order.by))
{
if(inherits(order.by, "formula")) {
z <- model.matrix(order.by, data = data)
z <- as.vector(z[,ncol(z)])
} else {
z <- order.by
}
X <- as.matrix(X[order(z),])
y <- y[order(z)]
}
n <- nrow(X)
if(is.null(exact)) exact <- (n < 100)
k <- ncol(X)
res <- lm.fit(X,y)$residuals
dw <- sum(diff(res)^2)/sum(res^2)
Q1 <- chol2inv(qr.R(qr(X)))
if(n < 3) {
warning("not enough observations for computing a p value, set to 1")
pval <- 1
} else {
if(exact)
{
A <- diag(c(1,rep(2, n-2), 1))
A[abs(row(A)-col(A))==1] <- -1
MA <- diag(rep(1,n)) - X %*% Q1 %*% t(X)
MA <- MA %*% A
ev <- eigen(MA)$values[1:(n-k)]
if(any(Im(ev)>tol)) warning("imaginary parts of eigenvalues discarded")
ev <- Re(ev)
ev <- ev[ev>tol]
pdw <- function(dw) .Fortran("pan", as.double(c(dw,ev)), as.integer(length(ev)),
as.double(0), as.integer(iterations), x=double(1), PACKAGE = "lmtest")$x
pval <- switch(alternative,
"two.sided" = (2*min(pdw(dw), 1-pdw(dw))),
"less" = (1 - pdw(dw)),
"greater" = pdw(dw))
if(is.na(pval) || ((pval > 1) | (pval < 0)))
{
warning("exact p value cannot be computed (not in [0,1]), approximate p value will be used")
exact <- FALSE
}
}
if(!exact)
{
if(n < max(5, k)) {
warning("not enough observations for computing an approximate p value, set to 1")
pval <- 1
} else {
AX <- matrix(as.vector(filter(X, c(-1, 2, -1))), ncol = k)
AX[1,] <- X[1,] - X[2,]
AX[n,] <- X[n,] - X[(n-1),]
XAXQ <- t(X) %*% AX %*% Q1
P <- 2*(n-1) - sum(diag(XAXQ))
Q <- 2*(3*n - 4) - 2* sum(diag(crossprod(AX) %*% Q1)) + sum(diag(XAXQ %*% XAXQ))
dmean <- P/(n-k)
dvar <- 2/((n-k)*(n-k+2)) * (Q - P*dmean)
pval <- switch(alternative,
"two.sided" = (2*pnorm(abs(dw-dmean), sd=sqrt(dvar), lower.tail = FALSE)),
"less" = pnorm(dw, mean = dmean, sd = sqrt(dvar), lower.tail = FALSE),
"greater" = pnorm(dw, mean = dmean, sd = sqrt(dvar)))
}
}
}
alternative <- switch(alternative,
"two.sided" = "true autocorrelation is not 0",
"less" = "true autocorrelation is less than 0",
"greater" = "true autocorrelation is greater than 0")
names(dw) <- "DW"
RVAL <- list(statistic = dw, method = "Durbin-Watson test",
alternative = alternative, p.value= pval, data.name=dname)
class(RVAL) <- "htest"
return(RVAL)
} |
isNaOrStringVectorOrNull <- function(argument, default = NULL, stopIfNot = FALSE, n = NA, message = NULL, argumentName = NULL) {
checkarg(argument, "S", default = default, stopIfNot = stopIfNot, nullAllowed = TRUE, n = NA, naAllowed = TRUE, emptyStringAllowed = TRUE, message = message, argumentName = argumentName)
} |
logregBY <- BYlogreg <- function(x0,y, intercept=1, const=0.5,kmax=1000,maxhalf=10)
{
sigmamin=0.0001
if (!is.numeric(y))
y <- as.numeric(y)
if (!is.null(dim(y))) {
if (ncol(y) != 1)
stop("y is not onedimensional")
y <- as.vector(y)
}
n <- length(y)
x0<-as.matrix(x0)
if (nrow(x0) != n)
stop("Number of observations in x and y not equal")
na.x <- !is.finite(rowSums(x0))
na.y <- !is.finite(y)
ok <- !(na.x | na.y)
if (!all(ok)) {
x0 <- x0[ok, , drop = FALSE]
y <- y[ok]
}
n <- nrow(x0)
if (n == 0)
stop("All observations have missing values!")
p<-ncol(x0)
family <- binomial()
p<-dim(x0)[2]
zz<-rep(0,p)
for (i in 1:p)
{zz[i]<-sum((x0[,i]==0)|(x0[,i]==1))}
tt<-which(zz!=n)
p1<-length(tt)
x0=as.matrix(x0,n,p)
x00<-x0[,tt]
if(p1==1)
{rdx<-abs(x00-median(x00))/mad(x00)
wrd<-(rdx<=qnorm(.9875))}
if(p1>1)
{
mcdx <- robustbase::covMcd(x00,alpha=.75)
rdx <- mahalanobis(x00,center=mcdx$center,cov=mcdx$cov)
vc<-qchisq(0.975,p)
wrd<-(rdx<=vc)}
if(p1==0)
{wrd=1:n}
if (intercept==1)
{out<-glm(y[wrd]~x0[wrd,], family = family)
x <- cbind(Intercept = 1, x0)}
if (intercept==0)
{out<-glm(y[wrd]~x0[wrd,]-1, family = family)
x<-x0}
gstart<-out$coeff
p=ncol(x)
sigmastart=1/sqrt(sum(gstart^2))
xistart=gstart*sigmastart
stscores=x %*% xistart
oldobj=mean(phiBY3(stscores/sigmastart,y,const))
kstep=1
jhalf=1
while (( kstep < kmax) & (jhalf<maxhalf))
{
optimsig=optimize(sigmaBY3,lower=0,upper=10^3,y=y,s=stscores,c3=const)
sigma1=optimsig$minimum
if (sigma1<sigmamin)
{
print("Explosion");kstep=kmax
}
else
{
gamma1=xistart/sigma1
scores=stscores/sigma1
newobj=mean(phiBY3(scores,y,const))
oldobj=newobj
gradBY3=apply((derphiBY3(scores,y,const)%*%t(rep(1,p)))*x,2,mean)
h=-gradBY3+(sum(gradBY3*xistart) *xistart)
finalstep=h/sqrt(sum(h^2))
xi1=xistart+finalstep
xi1=xi1/(sum(xi1^2))
scores1=(x%*%xi1)/sigma1
newobj=mean(phiBY3(scores1,y,const))
hstep=1
jhalf=1
while ((jhalf <=maxhalf) & (newobj>oldobj))
{
hstep=hstep/2
xi1=xistart+finalstep*hstep
xi1=xi1/sqrt(sum(xi1^2))
scores1=x%*%xi1/sigma1
newobj=mean(phiBY3(scores1,y,const))
jhalf=jhalf+1
}
if ((jhalf==maxhalf+1) & (newobj>oldobj))
{
} else
{ jhalf=1
xistart=xi1
oldobj=newobj
stscores=x%*% xi1
kstep=kstep+1
}
}
}
if (kstep == kmax)
{print("No convergence")
resultat=list(convergence=F,objective=0,coef=t(rep(NA,p)))
resultat}
else
{
gammaest=xistart/sigma1
stander=sterby3(x,y,const,gammaest)
fitted.linear<- x%*%gammaest
fitted.linear<-pmin(fitted.linear,1e2)
fitted.values<-exp(fitted.linear)/(1+exp(fitted.linear))
residual.deviances<-sign(y-fitted.values)*sqrt(-2*(y*log(fitted.values)+(1-y)*log(1-fitted.values)))
result <-list(convergence=TRUE,objective=oldobj, coefficients=gammaest, standard.deviation=stander,fitted.values=t(fitted.values), residual.deviances= t(residual.deviances))
result
}
}
phiBY3=function(s,y,c3)
{
s=as.double(s)
dev=log(1+exp(-abs(s)))+abs(s)*((y-0.5)*s<0)
res=rhoBY3(dev,c3)+GBY3Fs(s,c3)+GBY3Fsm(s,c3)
res
}
rhoBY3 <- function(t,c3)
{
(t*exp(-sqrt(c3))*as.numeric(t <= c3))+
(((exp(-sqrt(c3))*(2+(2*sqrt(c3))+c3))-(2*exp(-sqrt(t))*(1+sqrt(t))))*as.numeric(t >c3))
}
psiBY3 <- function(t,c3)
{
(exp(-sqrt(c3))*as.numeric(t <= c3))+(exp(-sqrt(t))*as.numeric(t >c3))
}
derpsiBY3 <- function(t,c3)
{
(0*as.numeric(t <= c3))+(-(exp(-sqrt(t))/(2*sqrt(t)))*as.numeric(t >c3))
}
sigmaBY3<-function(sigma,s,y,c3)
{
mean(phiBY3(s/sigma,y,c3))
}
derphiBY3=function(s,y,c3)
{
Fs= exp(-(log(1+exp(-abs(s)))+abs(s)*(s<0)))
ds=Fs*(1-Fs)
dev=log(1+exp(-abs(s)))+abs(s)*((y-0.5)*s<0)
Gprim1=log(1+exp(-abs(s)))+abs(s)*(s<0)
Gprim2=log(1+exp(-abs(s)))+abs(s)*(s>0)
-psiBY3(dev,c3)*(y-Fs)+((psiBY3(Gprim1,c3)-psiBY3(Gprim2,c3))*ds)
}
der2phiBY3=function(s,y,c3)
{
s=as.double(s)
Fs= exp(-(log(1+exp(-abs(s)))+abs(s)*(s<0)))
ds=Fs*(1-Fs)
dev=log(1+exp(-abs(s)))+abs(s)*((y-0.5)*s<0)
Gprim1=log(1+exp(-abs(s)))+abs(s)*(s<0)
Gprim2=log(1+exp(-abs(s)))+abs(s)*(s>0)
der2=(derpsiBY3(dev,c3)*(Fs-y)^2)+(ds*psiBY3(dev,c3))
der2=der2+(ds*(1-2*Fs)*(psiBY3(Gprim1,c3)-psiBY3(Gprim2,c3)))
der2=der2-(ds*((derpsiBY3(Gprim1,c3)*(1-Fs))+(derpsiBY3(Gprim2,c3)*Fs)))
der2
}
GBY3Fs <- function(s,c3)
{
Fs= exp(-(log(1+exp(-abs(s)))+abs(s)*(s<0)))
resGinf=exp(0.25)*sqrt(pi)*(pnorm(sqrt(2)*(0.5+sqrt(-log(Fs))))-1)
resGinf=(resGinf+(Fs*exp(-sqrt(-log(Fs)))))*as.numeric(s <= -log(exp(c3)-1))
resGsup=((Fs*exp(-sqrt(c3)))+(exp(0.25)*sqrt(pi)*(pnorm(sqrt(2)*(0.5+sqrt(c3)))-1)))*as.numeric(s > -log(exp(c3)-1))
resG=resGinf+resGsup
resG
}
GBY3Fsm <- function(s,c3)
{
Fsm=exp(-(log(1+exp(-abs(s)))+abs(s)*(s>0)))
resGinf=exp(0.25)*sqrt(pi)*(pnorm(sqrt(2)*(0.5+sqrt(-log(Fsm))))-1)
resGinf=(resGinf+(Fsm*exp(-sqrt(-log(Fsm)))))*as.numeric(s >= log(exp(c3)-1))
resGsup=((Fsm*exp(-sqrt(c3)))+(exp(0.25)*sqrt(pi)*(pnorm(sqrt(2)*(0.5+sqrt(c3)))-1)))*as.numeric(s < log(exp(c3)-1))
resG=resGinf+resGsup
resG
}
sterby3 <- function(z,y,const,estim)
{
n=dim(z)[[1]]
p=dim(z)[[2]]
argum=z %*% estim
matM=matrix(data=0,nrow=p,ncol=p)
for (i in 1:n)
{
matM=matM+(der2phiBY3(argum[i],y[i],const) * (z[i,] %*% t(z[i,])))
}
matM=matM/n
matMinv=solve(matM)
IFsquar=matrix(data=0,nrow=p,ncol=p)
for (i in 1:n)
{
IFsquar=IFsquar+((derphiBY3(argum[i],y[i],const))^2 * (z[i,] %*% t(z[i,])))
}
IFsquar=IFsquar/n
asvBY=matMinv %*% IFsquar %*% t(matMinv)
sqrt(diag(asvBY))/sqrt(n)
} |
library(stringr)
library(tableschema.r)
library(testthat)
library(config)
library(foreach)
context("types.castObject")
TESTS <- list(
list('default', list(), list()),
list('default', '{}', helpers.from.json.to.list('{}')),
list('default', '{"key": "value"}', list('key' = 'value')),
list('default', '["key", "value"]', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))),
list('default', 'string', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))),
list('default', 1, config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))),
list('default', '3.14', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))),
list('default', '', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))),
list('default', matrix(1:4, nrow = 2), config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))),
list('default', NULL, config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r"))),
list('default', '[["id", "name"],["1", "ab"]]', config::get("ERROR", file = system.file("config/config.yml", package = "tableschema.r")))
)
foreach(j = seq_along(TESTS) ) %do% {
TESTS[[j]] <- setNames(TESTS[[j]], c("format", "value", "result"))
test_that(str_interp('format "${TESTS[[j]]$format}" should check "${TESTS[[j]]$value}" as "${TESTS[[j]]$result}"'), {
expect_equal(types.castObject(TESTS[[j]]$format, TESTS[[j]]$value), TESTS[[j]]$result)
})
} |
trimpartt<-function(x,con){
trimpartt<-sum(con*x)
trimpartt
} |
library(tinytest)
library(ggiraph)
library(ggplot2)
library(xml2)
source("setup.R")
{
eval(test_geom_layer, envir = list(name = "geom_spoke_interactive"))
} |
folds <- function(x, nfolds=5L, stratified=FALSE, seed=NULL){
FoldID <- NULL
Target <- NULL
if(is(x, "data.table")){
if(stratified != FALSE){
if(!stratified %in% colnames(x)) stop("Argument stratified must be FALSE or match the name of a column in the given data.table")
foldIDs <- folds(x=x[[stratified]], nfolds=nfolds, stratified=TRUE, seed=seed)
} else{
foldIDs <- folds(x=seq_len(nrow(x)), nfolds=nfolds, stratified=FALSE, seed=seed)
}
return(split(x, foldIDs))
}
if(length(x) == 1 & x[1] > 1 & x[1] %% 1 == 0){
return(folds(rep(x = 1L, x), nfolds = nfolds, stratified = FALSE, seed = seed))
}
set.seed(seed)
if(stratified){
if(is.numeric(x)){
dt <- data.table(Target=floor((frank(-x, ties.method="random") - 1) / nfolds))
} else{
dt <- data.table(Target=x)
}
dt[, FoldID := (sample(.N, .N) - 1L) %% nfolds + 1L, by=Target]
foldIDs <- dt$FoldID
} else{
foldIDs <- (sample(length(x), length(x)) - 1L) %% nfolds + 1L
}
return(foldIDs)
} |
ggInterval_hist<-function(data = NULL,mapping = aes(NULL),method="equal-bin",bins=10,
plotAll = FALSE){
argsNum<-length(mapping)
args<-lapply(mapping[1:argsNum],FUN=rlang::get_expr)
this.x <- args$x ; this.y <- args$y
ggSymData <- testData(data)
iData <- ggSymData$intervalData
if(plotAll){
if(!is.null(this.x) | !is.null(this.y)){
warning("Using plotAll presentation cannot specify variables.")
}
}else{
testXY(iData,this.x,this.y)
}
p<-dim(iData)[2]
n<-dim(iData)[1]
if(method=="equal-bin" & bins>200 & bins<=1000){
warning("Bins are too large that will lead the figure to be fuzzy.")
}else if(method=="equal-bin" & bins>1000){
stop("Bins are too large that will lead the figure to be fuzzy.")
}
if("ggESDA" %in% class(data)){data <- iData}
with(data,{
plotVarNum <- NULL
mmd <- data.frame(NULL)
if(plotAll){
numericData <- unlist(lapply(data.frame(iData[1:dim(iData)[2]]) ,FUN = is.sym.interval))
iData <- iData[,which(numericData)]
attr <- colnames(iData)
for(i in 1:length(attr)){
mmd[i, "minimal"]<-min(iData[[i]]$min)
mmd[i, "maximal"]<-max(iData[[i]]$max)
}
}else{
if(any(unlist(lapply(as.data.frame(data[,1:p]),FUN=identical,x=eval(this.x))))){
attr<-which(unlist(lapply(as.data.frame(data[,1:p]),FUN=identical,x=eval(this.x))))
attr<-names(attr)
}else if(any(unlist(lapply(as.data.frame(data[,1:p]),FUN=identical,x=eval(this.y))))){
attr<-which(unlist(lapply(as.data.frame(data[,1:p]),FUN=identical,x=eval(this.y))))
attr<-names(attr)
}else{
stop("ERROR : Cannot find variables in aes(...)")
}
if(p==1){
attr = colnames(data)
}
if(all(!is.numeric(data[[attr]]) , !RSDA::is.sym.interval(data[[attr]]))){
stop("ERROR : Variables in histogram can only be numeric.")
}
mmd[1, "minimal"]<-min(iData[[attr]]$min)
mmd[1, "maximal"]<-max(iData[[attr]]$max)
}
if(method=="unequal-bin"){
plotData <- NULL ; intervalDf = NULL
for(u in 1:nrow(mmd)){
d<-as.data.frame(iData[[attr[u]]])
temp<-seq(mmd[u, "minimal"], mmd[u, "maximal"],0.01)
f <- matrix(0,nrow=length(temp),ncol=n+1)
f[,1]<-temp
for (i in 1:n){
start<-length(which(round(f[,1],2)<=round(d[i,1],2)))
end<-length(which(round(f[,1],2)<=round(d[i,2],2)))
f[start:end,i+1]<-1
}
f<-cbind(temp,apply(f[,-1],1,FUN=sum))
x<-f[1,2]
y<-1
for (i in 1:(dim(f)[1]-1)){
if(f[i,2]!=f[i+1,2]){
y<-append(y,f[i+1,2])
x<-append(x,i)
x<-append(x,i+1)
}
}
x<-append(x,length(temp))
x<-t(matrix(x,nrow=2))
x1<-f[x[,1],1]
x2<-f[x[,2],1]
plotData<-rbind(plotData,
data.frame(x1,x2,y1=0,y2=y/n,group=factor(attr[u])))
tempDf <- data.frame(start = rep(NA, length(x1)),
end = rep(NA, length(x1)))
tempDf[1:length(x1), "start"] <- round(x1,2)
tempDf[1:length(x1), "end"] <- round(x2,2)
intervalDf <- rbind(intervalDf, tempDf)
}
intervalDf <- intervalDf[order(intervalDf$start), ]
temp <- paste(intervalDf$start, intervalDf$end, sep = ":")
nameList <- paste0("[",temp,"]")
midP <- (plotData$x1 + plotData$x2)/2
xyLocation <- c(which(names(mapping) == "x"), which(names(mapping) == "y"))
if(length(xyLocation) != 0){
usermapping <- mapping[-xyLocation]
}else{
usermapping <- mapping
}
mymapping <- list(mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2),fill="grey",col="black")
allmapping <-as.list(structure(as.expression(c(usermapping,mymapping)),class="uneval"))
base <- ggplot(data=plotData,aes(x1,y1))+
do.call(geom_rect,allmapping)+
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
if(plotAll){
base <- base + facet_grid(group ~ .) +
labs(x = "", y="frequency") +
scale_x_continuous(n.breaks = 8)
}else{
base <- base + labs(x=attr,y="frequency")+
scale_x_continuous(breaks = midP, labels=nameList)
}
return(base)
}else if(method=="equal-bin"){
myhist <- NULL ; intervalDf <- NULL
for(i in 1:nrow(mmd)){
dist<-(mmd[i, "maximal"]-mmd[i, "minimal"])/bins
interval<-seq(mmd[i, "minimal"],mmd[i, "maximal"],dist)
f <- NULL
f <- matrix(nrow=length(iData[[attr[i]]]),ncol=bins)
for (obs in 1:length(iData[[attr[i]]])){
a<-iData[[attr[i]]][obs]$min
b<-iData[[attr[i]]][obs]$max
for(area in 1:bins){
headIn<-a %>% between(interval[area],interval[area+1])
tailIn<-b %>% between(interval[area],interval[area+1])
contain<-interval[area] %>% between(a,b)
if(headIn|tailIn|contain){
temp<-sort(c(a,b,interval[area],interval[area+1]))
f[obs,area]<-(temp[3]-temp[2])/(b-a)
}else{
f[obs,area]<-0
}
}
}
nInt <- length(interval)
interval <- round(interval,2)
tempDf <- data.frame(start = rep(NA, nInt-1),
end = rep(NA, nInt-1))
tempDf[1:(nInt-1), "start"] <- interval[1:(nInt-1)]
tempDf[1:(nInt-1), "end"] <- interval[2:nInt]
intervalDf <- rbind(intervalDf, tempDf)
myhist<-rbind(myhist,
data.frame(interval=interval[1:bins],
frequency=apply(f,2,FUN=sum),
group = factor(attr[i])))
}
myhist <- cbind(myhist, intervalDf)
intervalDf <- intervalDf[order(intervalDf$start), ]
temp <- paste(intervalDf$start, intervalDf$end, sep = ":")
nameList <- paste0("[",temp,"]")
myhist$frequency <- myhist$frequency/n
xyLocation <- c(which(names(mapping) == "x"), which(names(mapping) == "y"))
if(length(xyLocation) != 0){
usermapping <- mapping[-xyLocation]
}else{
usermapping <- mapping
}
mymapping <- list(stat="identity",
mapping=aes(alpha=0.5,fill=gray.colors(bins*length(attr))),col="black")
allmapping <-as.list(structure(as.expression(c(usermapping,mymapping)),class="uneval"))
if(plotAll){
mymapping <- list(mapping=aes(xmin=start, xmax=end, ymin=0, ymax=frequency),fill="grey",col="black")
allmapping <-as.list(structure(as.expression(c(usermapping,mymapping)),class="uneval"))
base <- ggplot(data=myhist)+
do.call(geom_rect,allmapping) +
facet_grid(group ~ .) +
labs(x = "", y="frequency") +
scale_x_continuous(n.breaks = 8)
}else{
base <- ggplot(data=myhist, aes(x=factor(interval),y=frequency))+
do.call(geom_histogram,allmapping)+
scale_fill_manual(values=rep("black",bins*length(attr)))+
guides(colour = FALSE, alpha = FALSE,fill=FALSE)+
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))+
labs(x=attr)+
scale_x_discrete(labels = nameList)
}
return(base)
}else{
stop(paste0("ERROR : Unrecognize method : ",method," ."))
}
})
} |
has_intercept <- function(x, verbose = TRUE) {
f <- find_formula(x)
if (is_multivariate(x)) {
lapply(f, .check_for_intercept, verbose = verbose)
} else {
.check_for_intercept(f, verbose)
}
}
.check_for_intercept <- function(f, verbose = TRUE) {
if (!is.null(f$conditional)) {
f_terms <- stats::terms(f$conditional)
intercept <- as.vector(attr(f_terms, "intercept"))
return(intercept == 1)
} else if (verbose) {
warning(format_message("Cannot extract terms from model formula."), call. = FALSE)
}
} |
tvgarch <- function (y, order.g = 1, order.h = c(1,1,0), xtv = NULL,
xreg = NULL, initial.values = list(), opt = 2,
turbo = FALSE, trace = FALSE)
{
n <- length(y)
y.index <- index(y)
if (!is.null(order.g) && order.g == 0) order.g <- NULL
npar.h <- 1 + sum(order.h)
if (!is.null(xreg)) {
xreg <- as.matrix(xreg)
npar.h <- npar.h + NCOL(xreg)
}
robse.par.h <- numeric(npar.h)
maxpqr <- max(order.h)
if (!is.null(order.g)) {
if (!is.null(xtv)){
xtv <- matrix(xtv, n, 1)
if (is.null(colnames(xtv))) colnames(xtv) <- "xtv"
}
if (is.null(xtv)) {
xtv <- matrix((1:n)/n, n, 1)
colnames(xtv) <- "time"
xtv <- as.zoo(xtv, order.by = y.index)
}
s <- length(order.g)
npar.g <- 1 + 2 * s + sum(order.g)
}
'
Initial values
'
if (!is.null(order.g)) {
if (is.null(initial.values$intercept.g)) intercept.g <- 1
else intercept.g <- initial.values$intercept.g
if (is.null(initial.values$size)) size <- rep(0.1, s)
else size <- initial.values$size
if (is.null(initial.values$speed)) speed <- rep(1, s)
else speed <- initial.values$speed
if (is.null(initial.values$location)) {
location <- NULL
for (i in 1:s) {
if (order.g[i] == 1) location <- c(location, mean(xtv))
if (order.g[i] > 1) {
location <- c(location, seq(from = min(xtv)+0.5*sd(xtv),
to = max(xtv)-0.5*sd(xtv),
by = (max(xtv)-min(xtv) -
sd(xtv))/(order.g[i]-1)))
}
}
}
else location <- initial.values$location
if (s != length(size)) {
stop("Mismatch between the number of transition
functions, s, and the number of initial size values.")
}
if (s != length(speed)) {
stop("Mismatch between the number of transition functions, s, and the
number of initial speed values.")
}
if (sum(order.g) != length(location)) {
stop("Mismatch between order.gand the initial location values.")
}
}
if (is.null(initial.values$intercept.h)) intercept.h <- 0.1
if (!is.null(initial.values$intercept.h)) {
intercept.h <- initial.values$intercept.h
}
if (is.null(initial.values$arch)) arch <- rep(0.1/order.h[2], order.h[2])
if (!is.null(initial.values$arch)) arch <- initial.values$arch
if (order.h[2] != length(arch)) {
stop("Mismatch between the number of ARCH-type parameters, q, and the arch
initial values.")
}
if (order.h[1] != 0) {
if (is.null(initial.values$garch)) garch <- rep(0.7/order.h[1], order.h[1])
else garch <- initial.values$garch
if (order.h[1] != length(garch)) {
stop("Mismatch between the number of GARCH-type parameters, p, and the
garch initial values.")
}
}
if (order.h[1] == 0) garch <- NULL
if (order.h[3] != 0) {
if (is.null(initial.values$asym)) asym <- rep(0.02/order.h[3], order.h[3])
if (!is.null(initial.values$asym)) asym <- initial.values$asym
if (order.h[3] != length(asym)) {
stop("Mismatch between the number of GJR-type parameters, r, and the asym
initial values.")
}
}
if (order.h[3] == 0) asym <- NULL
if (!is.null(xreg)) {
if (is.null(initial.values$par.xreg)) par.xreg <- rep(0.01, NCOL(xreg))
if (!is.null(initial.values$par.xreg)) par.xreg <- initial.values$par.xreg
if (NCOL(xreg) != length(par.xreg)) {
stop("Mismatch between the number of covariates, X, and the par.xreg
initial values.")
}
}
if (is.null(xreg)) par.xreg <- NULL
'
Vector of initial parameters for h component
'
names.h <- c("intercept.h", paste("arch", paste(seq(1:order.h[2]), sep = ""),
sep = ""))
ini.par.h <- c(intercept.h, arch)
if (order.h[1] != 0) {
names.h <- c(names.h, paste("garch", paste(seq(1:order.h[1]), sep = ""),
sep = ""))
ini.par.h <- c(ini.par.h, garch)
}
if (order.h[3] != 0) {
names.h <- c(names.h, paste("asym", paste(seq(1:order.h[3]), sep = ""),
sep = ""))
ini.par.h <- c(ini.par.h, asym)
}
if (!is.null(xreg)) {
if (!is.null(colnames(xreg))) names.h <- c(names.h, colnames(xreg))
else names.h <- c(names.h, paste("xreg", paste(seq(1:NCOL(xreg)), sep = ""),
sep = ""))
ini.par.h <- c(ini.par.h, par.xreg)
}
if (length(ini.par.h) != npar.h) {
stop("Check initial parameters in the h component.")
}
initial.h <- matrix(ini.par.h, 1, npar.h)
colnames(initial.h) <- names.h
rownames(initial.h) <- "Value:"
if (trace == TRUE) {
cat("\n Initial parameters in the h component\n\n")
print(round(initial.h, 4))
}
'
g component and maximization by parts
'
g <- y
g[1:n] <- 1
if (!is.null(order.g)) {
'
Vector of initial parameters for g component
'
ini.par.g <- c(intercept.g, size, speed, location)
names.g <-
c("intercept.g", paste("size", paste(seq(1:s), sep = ""), sep = ""),
paste("speed", paste(seq(1:s), sep = ""), sep = ""))
for (i in 1:s) {
if (s == 1) {
names.g <- c(names.g, paste("location",
paste(seq(1:max(order.g[i])), sep = ""),
sep = ""))
}
else {
names.g <- c(names.g, paste("location", paste(i, sep = ""),
paste(seq(1:max(order.g[i])), sep = ""),
sep = ""))
}
}
if (length(ini.par.g) != npar.g) {
stop("Check initial parameters in the g component.")
}
initial.g <- matrix(ini.par.g, 1, npar.g)
colnames(initial.g) <- names.g
rownames(initial.g) <- "Value:"
if (trace == TRUE) {
cat("\n Initial parameters in the g component:\n\n")
print(round(initial.g, 4))
}
'
Parameter constraints for g component and iter = 0
'
r <- diag(npar.g)
r1 <- r[1,]
ui.g <- r1
ci.g <- 1e-5
if (s == 1) {
r2 <- r[2,]
r2[1] <- 1
ui.g <- rbind(ui.g, r2)
ci.g <- c(ci.g, 1e-5)
}
if (s > 1) {
r.size <- combos(s)$binary
r3 <- matrix(0, nrow(r.size), npar.g)
r3[,1] <- 1
r3[,2:(s+1)] <- r.size
ui.g <- rbind(ui.g, r3)
ci.g <- c(ci.g, rep(1e-5, nrow(r.size)))
}
r4 <- r[(2+s):(2*s+1),]
r5 <- r[(2*s+2):npar.g,]
ui.g <- rbind(ui.g, r4, -r4, r5, -r5)
if (opt != 2) ci.g <- c(ci.g, rep(1e-5, s), rep(-250, s), rep(min(xtv)+1e-3,
sum(order.g)),
rep(-max(xtv)+1e-3, sum(order.g)))
if (opt == 2) ci.g <- c(ci.g, rep(log(1e-5), s), rep(-log(250), s),
rep(min(xtv)+1e-3, sum(order.g)), rep(-max(xtv)+1e-3,
sum(order.g)))
if (any(order.g > 1)) {
for (i in which(order.g > 1)) {
r6 <- -r[(1+2*s+sum(order.g[1:i]) -
order.g[i]+1):(1+2*s+sum(order.g[1:i])-1),] +
r[(1+2*s+sum(order.g[1:i])-order.g[i]+2):(1+2*s+sum(order.g[1:i])),]
ui.g <- rbind(ui.g, r6)
ci.g <- c(ci.g, rep(0, order.g[i]-1))
}
}
'
Maximization by parts: estimating initial TV parameters
'
iter <- 0
h <- rep(1, n)
iter0.fit.g <- constrOptim(theta = ini.par.g, f = tvObj, grad = NULL,
ui = ui.g, ci = ci.g, y = y, order.g = order.g,
xtv = xtv, opt = opt, fixed.h = h, iter0 = TRUE,
flag = 1)
par.hat0.g <- iter0.fit.g$par
g[1:n] <- tvObj(par.g = iter0.fit.g$par, fixed.par.g = NULL, xtv = xtv,
opt = opt, order.g = order.g, fixed.h = h, y = y,
iter0 = TRUE, flag = 2)
estimates <- matrix(par.hat0.g, 1, length(names.g))
colnames(estimates) <- names.g
rownames(estimates) <- "Value:"
if (trace == TRUE) {
cat("\n Initial estimation for the g component:\n\n")
if (turbo == TRUE) print(round(estimates[1,], 4))
else print(round(estimates, 4))
}
'
Parameter constraints for g component and iter > 0
'
par.hat.g <- par.hat0.g[-c(1,(s+2):(2*s+1))]
par.hat0.g <- par.hat0.g[c(1,(s+2):(2*s+1))]
r <- diag(length(par.hat.g))
ui.g <- rbind(r[(s+1):(npar.g-s-1),], -r[(s+1):(npar.g-s-1),])
ci.g <- c(rep(min(xtv)+1e-3, sum(order.g)), rep(-max(xtv)+1e-3,
sum(order.g)))
if (s == 1) {
r1 <- r[1,]
ui.g <- rbind(ui.g, r1)
ci.g <- c(ci.g, -par.hat0.g[1]+1e-5)
}
if (s > 1) {
r.size <- combos(s)$binary
r1 <- matrix(0, nrow(r.size), length(par.hat.g))
r1[,1:s] <- r.size
ui.g <- rbind(ui.g, r1)
ci.g <- c(ci.g, rep(-par.hat0.g[1]+1e-5, nrow(r.size)))
}
if (any(order.g > 1)) {
for(i in which(order.g > 1)){
r2 <- -r[(s+sum(order.g[1:i])-order.g[i]+1):(s+sum(order.g[1:i])-1),] +
r[(s+sum(order.g[1:i])-order.g[i]+2):(s+sum(order.g[1:i])),]
ui.g <- rbind(ui.g, r2)
ci.g <- c(ci.g, rep(0, order.g[i]-1))
}
}
'
Iterative estimation
'
iter <- iter + 1
maxiter <- 1000
phi <- y/sqrt(g)
par.hat.h <- ini.par.h
repeat{
if (trace == TRUE) {
cat(" \n\n")
cat("Iteration round:",iter, "\n\n")
}
'
Estimating GJR-GARCH-X parameters:
'
iter.fit.h <- garchx(y = phi, order = order.h, xreg = xreg,
initial.values = par.hat.h)
h <- garchxRecursion(pars = as.numeric(iter.fit.h$par), aux = iter.fit.h)
if (iter > 1) conv.h <- max(abs(par.hat.h-iter.fit.h$par))
par.hat.h <- iter.fit.h$par
if (trace == TRUE) {
cat("Estimates (h component):", par.hat.h, "\n")
cat("Likelihood:", logLik.garchx(iter.fit.h), "\n")
}
'
Estimating TV parameters:
'
iter.fit.g <- constrOptim(theta = par.hat.g, f = tvObj, grad = NULL,
ui = ui.g, ci = ci.g, fixed.par.g = par.hat0.g,
y = y, order.g = order.g, xtv = xtv, opt = opt,
fixed.h = h, iter0 = FALSE, flag = 1)
conv.g <- max(abs(par.hat.g - iter.fit.g$par))
par.hat.g <- iter.fit.g$par
g[1:n] <- tvObj(par.g = par.hat.g, fixed.par.g = par.hat0.g, xtv = xtv,
opt = opt, order.g = order.g, fixed.h = h, y = y,
iter0 = FALSE, flag = 2)
phi <- y/sqrt(g)
if (trace == TRUE) {
cat("Estimates (g component):", par.hat.g, "\n")
cat("Likelihood:", - iter.fit.g$value, "\n")
if (iter > 1) cat("Max. convergence:", max(conv.h, conv.g), "\n")
}
'
Next round
'
iter <- iter + 1
if (iter > 2) {
if (iter >= maxiter || max(conv.g, conv.h) < 1e-5){
if (iter == maxiter) {
warning("Convergence has not been reached after ",
paste(maxiter, sep = "")," iterations.")
}
break
}
}
}
par.hat.g <- c(par.hat0.g[1], iter.fit.g$par[1:s], par.hat0.g[-1],
iter.fit.g$par[-(1:s)])
if (turbo == TRUE) {
vcov.g <- NULL
robse.par.g <- rep(NA_real_, length(par.hat.g))
}
if (turbo == FALSE) {
'
TV variance-covariance matrix:
'
vcov.g <- matrix(NA_real_, npar.g, npar.g)
rownames(vcov.g) <- names.g
colnames(vcov.g) <- names.g
jac.g <- jacobian(func = tvObj, x = iter.fit.g$par,
fixed.par.g = par.hat0.g, xtv = xtv, opt = opt,
order.g = order.g, fixed.h = h, y = y, iter0 = FALSE,
flag = 0)
J.g <- crossprod(jac.g)
H.g <- optimHess(par = iter.fit.g$par, fn = tvObj,
fixed.par.g = par.hat0.g, xtv = xtv, opt = opt,
order.g = order.g, fixed.h = h, y = y, iter0 = FALSE,
flag = 1)
solHG <- solve(-H.g)
vcov.iter <- solHG %*% J.g %*% solHG
vcov.g[c(2:(s+1),(2*s+2):npar.g),c(2:(s+1),(2*s+2):npar.g)] <- vcov.iter
robse.par.g <- sqrt(diag(vcov.g))
}
'
TV final parameter estimates:
'
estimates.g <- as.matrix(rbind(par.hat.g, robse.par.g))
rownames(estimates.g) <- c("Estimate:", "Std. Error:")
colnames(estimates.g) <- names.g
}
'
Final GJR-GARCH-X estimation
'
iter.fit.h <- garchx(y = y/sqrt(g), order = order.h, xreg = xreg,
initial.values = ini.par.h)
aux.h <- iter.fit.h
h <- garchxRecursion(pars = as.numeric(iter.fit.h$par), aux = iter.fit.h)
if (turbo == TRUE) {
vcov.h <- NULL
robse.par.h <- rep(NA_real_, length(iter.fit.h$par))
}
if (turbo == FALSE) {
'
GJR-GARCH-X variance-covariance matrix:
'
vcov.h <- vcov.garchx(iter.fit.h)
robse.par.h <- sqrt(diag(vcov.h))
}
'
GJR-GARCH-X final parameter estimates:
'
estimates.h <- as.matrix(rbind(iter.fit.h$par, robse.par.h))
rownames(estimates.h) <- c("Estimate:", "Std. Error:")
colnames(estimates.h) <- names.h
'
TV-GJR-GARCH-X output:
'
sigma2 <- as.matrix(h*g)
colnames(sigma2) <- "sigma2"
logLik <- sum(dnorm(x = y, mean = 0, sd = sqrt(sigma2), log = TRUE))
residuals <- as.matrix(y/sqrt(sigma2))
colnames(residuals) <- "innovations"
results <- list(par.h = estimates.h[1,], se.h = estimates.h[2,],
names.h = names.h, sigma2 = sigma2, residuals = residuals,
h = h, g = g, logLik = logLik, vcov.h = vcov.h,
message.h = iter.fit.h$message, order.g = order.g,
order.h = order.h, xreg = xreg, y = y, y.index = y.index,
date = date(), turbo = turbo, aux.h = aux.h)
if (!is.null(order.g)) {
results$par.g = estimates.g[1,]
results$se.g = estimates.g[2,]
results$names.g = names.g
results$vcov.g = vcov.g
results$message.g = iter.fit.g$message
results$xtv = xtv
results$opt = opt
results$iter = iter
}
class(results) <- "tvgarch"
return(results)
} |
setGeneric("getformula", function(x) standardGeneric("getformula"),
package = "btergm")
setMethod("getformula", signature = className("ergm", "ergm"),
definition = function(x) x$formula)
setMethod("getformula", signature = className("btergm", "btergm"),
definition = function(x) x@formula)
setMethod("getformula", signature = className("mtergm", "btergm"),
definition = function(x) x@formula)
setMethod("getformula", signature = className("tbergm", "btergm"),
definition = function(x) x@formula) |
setConstructorS3("AbstractCNData", function(chromosome=NULL, x=NULL, y=NULL, ..., name=NULL, .virtuals=NULL) {
if (!is.null(chromosome)) {
if (is.data.frame(chromosome)) {
data <- chromosome
chromosome <- data$chromosome
x <- data$x
y <- data$y
}
args <- list(...)
keep <- !sapply(args, FUN=is.null)
args <- args[keep]
if (is.null(y)) {
y <- args$y
args$y <- NULL
}
} else {
args <- NULL
}
this <- extend(RawGenomicSignals(chromosome=chromosome, x=x, y=y, name=name), "AbstractCNData")
this <- setVirtualColumnFunctions(this, .virtuals)
if (length(args) > 0) {
class <- class(this)
for (key in names(args)) {
values <- args[[key]]
this[[key]] <- values
}
class(this) <- class
}
this
})
setMethodS3("getPlatform", "AbstractCNData", function(this, ...) {
attr(this, "platform")
})
setMethodS3("setPlatform", "AbstractCNData", function(this, platform, ...) {
platform <- Arguments$getCharacter(platform)
attr(this, "platform") <- platform
invisible(this)
})
setMethodS3("getChipType", "AbstractCNData", function(this, fullname=TRUE, ...) {
chipType <- attr(this, "chipType")
if (!fullname) {
chipType <- gsub(",.*", "", chipType)
}
chipType
})
setMethodS3("setChipType", "AbstractCNData", function(this, chipType, ...) {
chipType <- Arguments$getCharacter(chipType)
attr(this, "chipType") <- chipType
invisible(this)
})
setMethodS3("getLocusData", "AbstractCNData", function(this, ...) {
as.data.frame(this)
})
setMethodS3("hasKnownPositions", "AbstractCNData", function(this, ...) {
data <- as.data.frame(this, ...)
ok <- (!is.na(data$chromosome) & !is.na(data$x))
ok
}, protected=TRUE)
setMethodS3("orderAlongGenome", "AbstractCNData", function(this, ...) {
sort(this, ...)
}, protected=TRUE)
setMethodS3("findLargeGaps", "AbstractCNData", function(chromosome, ...) {
pkg <- "PSCBS"
require(pkg, character.only=TRUE) || throw("Package not loaded: ", pkg)
this <- chromosome
data <- as.data.frame(this, ...)
findLargeGaps(chromosome=data$chromosome, x=data$x, ...)
}) |
kfunc <- function(dist_mat,start,end,step,Lt,n,w){
breaks <- seq(start,end,step)
t1 <- (n-1)/Lt
k_values <- sapply(breaks,function(dist){
int_mat <- t(t(dist_mat<=dist) * w)
diag(int_mat) <- 0
tot <- (rowSums(int_mat))
k <- t1 * sum(tot)
return(k)
})
return(k_values)
}
gfunc <- function(dist_mat,start,end,step,width,Lt,n,w){
breaks <- seq(start,end,step)
width <- width/2
t1 <- (n-1)/Lt
k_values <- sapply(breaks,function(dist){
int_mat <- t(t(dist_mat<=dist+width & dist_mat>=dist-width) * w)
diag(int_mat) <- 0
tot <- (rowSums(int_mat))
k <- t1 * sum(tot)
return(k)
})
return(k_values)
}
cross_kfunc <- function(dist_mat,start,end,step,Lt,na,nb,wa,wb){
breaks <- seq(start,end,step)
t1 <- (na/Lt)
k_values <- sapply(breaks,function(dist){
int_mat <- sweep((dist_mat<=dist), MARGIN = 2, FUN = "*", wa)
int_mat <- sweep(int_mat,MARGIN = 1, FUN = "*", wb)
tot <- (rowSums(int_mat))
k <- t1 * sum(tot)
return(k)
})
return(k_values)
}
cross_gfun <- function(dist_mat,start,end,step,width,Lt,na,nb,wa,wb){
breaks <- base::seq(from = start,to = end, by = step)
width <- width/2
t1 <- (na/Lt)
g_values <- sapply(breaks,function(dist){
d1 <- dist + width
d2 <- dist - width
int_mat <- (dist_mat <= d1 & dist_mat >= d2)
int_mat <- base::sweep(int_mat, MARGIN = 2, FUN = "*", wa)
int_mat <- base::sweep(int_mat,MARGIN = 1, FUN = "*", wb)
tot <- rowSums(int_mat)
k <- t1 * sum(tot)
return(k)
})
return(g_values)
}
randomize_distmatrix2 <- function(graph, edge_df, n, resolution, nsim, start_vert = NULL){
edit_edge <- subset(edge_df, edge_df$weight > resolution)
all_names <- names(igraph::V(graph))
vertices_and_distances <- lapply(1:nrow(edit_edge), function(i){
this_edge <- edit_edge[i,]
start_node <- all_names[this_edge$start_oid]
end_node <- all_names[this_edge$end_oid]
dists <- rep(resolution, floor(this_edge$weight/resolution))
if(sum(dists) == this_edge$weight){
dists <- dists[1:(length(dists)-1)]
}
names(dists) <- paste("fict",i,1:length(dists), sep="_")
return(data.frame(starts = c(start_node, names(dists)),
ends = c(names(dists), end_node),
weight = c(dists, this_edge$weight - sum(dists))))
})
all_elements <- do.call(rbind, vertices_and_distances)
all_elements <- subset(all_elements,all_elements$weight>0)
new_graph <- igraph::graph_from_data_frame(all_elements, directed = FALSE)
tot_graph <- igraph::union(graph,new_graph, byname = TRUE)
ws <- igraph::E(tot_graph)
df_tmp <- data.frame("w1" = ws$weight_1,
"w2" = ws$weight_2)
df_tmp[is.na(df_tmp$w1),"w1"] <- 0
df_tmp[is.na(df_tmp$w2),"w2"] <- 0
tot_graph <- igraph::set_edge_attr(tot_graph, "weight",
value = df_tmp$w1 + df_tmp$w2,
index = igraph::E(tot_graph))
verts <- as.numeric(igraph::V(tot_graph))
dist_matrices <- lapply(1:nsim, function(i){
new_vert <- sample(verts,size = n, replace = F)
if (is.null(start_vert)){
dist_mat <- igraph::distances(tot_graph,v = new_vert, to = new_vert)
}else{
dist_mat <- igraph::distances(tot_graph,v = start_vert, to = new_vert)
}
})
return(dist_matrices)
}
randomize_distmatrix <- function(graph, edge_df, n, start_vert = NULL){
vec_runif <- Vectorize(runif, vectorize.args = c("max"))
sel_edges_id <- sample(edge_df$edge_id,
size = n, replace = TRUE,
prob = 1/edge_df$weight * edge_df$probs)
sel_edges <- edge_df[sel_edges_id,]
sel_edges_len <- sel_edges$weight
start_oids <- sel_edges$start_oid
end_oids <- sel_edges$end_oid
all_names <- names(igraph::V(graph))
start_names <- all_names[start_oids]
end_names <- all_names[end_oids]
dists <- vec_runif(n=1,min = 0, max = sel_edges_len)
new_vert <- paste0(rep("virt_"),seq_len(length(dists)))
df <- data.frame(start = c(start_names,new_vert),
end = c(new_vert,end_names),
weight = c(dists,(sel_edges_len - dists)))
new_graph <- igraph::graph_from_data_frame(df, directed = FALSE)
tot_graph <- igraph::union(graph,new_graph, byname = TRUE)
ws <- igraph::E(tot_graph)
df_tmp <- data.frame("w1" = ws$weight_1,
"w2" = ws$weight_2)
df_tmp[is.na(df_tmp$w1),"w1"] <- 0
df_tmp[is.na(df_tmp$w2),"w2"] <- 0
tot_graph <- igraph::set_edge_attr(tot_graph, "weight",
value = df_tmp$w1 + df_tmp$w2,
index = igraph::E(tot_graph))
if (is.null(start_vert)){
dist_mat <- igraph::distances(tot_graph,v = new_vert, to = new_vert)
}else{
dist_mat <- igraph::distances(tot_graph,v = start_vert, to = new_vert)
}
return(dist_mat)
}
kfunctions <- function(lines, points, start, end, step, width, nsim, conf_int = 0.05, digits = 2, tol = 0.1, resolution = NULL, agg = NULL, verbose = TRUE){
if (verbose){
print("Preparing data ...")
}
n <- nrow(points)
points$goid <- seq_len(nrow(points))
points$weight <- rep(1,nrow(points))
points <- clean_events(points,digits,agg)
probs <- NULL
if(is.null(probs)){
lines$probs <- 1
}else{
lines$probs <- probs
}
lines$length <- gLength(lines,byid = TRUE)
lines <- subset(lines, lines$length>0)
lines$oid <- seq_len(nrow(lines))
if (verbose){
print("Snapping points on lines ...")
}
snapped_events <- snapPointsToLines2(points,lines,idField = "oid")
new_lines <- split_lines_at_vertex(lines, snapped_events,
snapped_events$nearest_line_id, tol)
if (verbose){
print("Building graph ...")
}
new_lines$length <- gLength(new_lines,byid = TRUE)
new_lines <- subset(new_lines,new_lines$length>0)
new_lines <- remove_loop_lines(new_lines,digits)
new_lines$oid <- seq_len(nrow(new_lines))
new_lines <- new_lines[c("length","oid","probs")]
Lt <- gLength(new_lines)
new_lines$weight <- gLength(new_lines, byid = TRUE)
graph_result <- build_graph(new_lines,digits = digits,
line_weight = "weight",
attrs = TRUE)
graph <- graph_result$graph
nodes <- graph_result$spvertices
graph_result$spedges$probs <- igraph::get.edge.attribute(graph_result$graph,
name = "probs")
snapped_events$vertex_id <- closest_points(snapped_events, nodes)
dist_mat <- igraph::distances(graph,v = snapped_events$vertex_id,
to = snapped_events$vertex_id)
if (verbose){
print("Calculating k and g functions ...")
}
k_vals <- kfunc(dist_mat,start,end,step,Lt,n,w = snapped_events$weight)
g_vals <- gfunc(dist_mat,start,end,step,width,Lt,n,w = snapped_events$weight)
if (verbose){
print("Calculating the simulations ...")
}
w <- rep(1,times = n)
if(verbose){
pb <- txtProgressBar(min = 0, max = nsim, style = 3)
}
if (is.null(resolution)==FALSE){
dist_matrices <- randomize_distmatrix2(graph = graph_result$graph,
edge_df = graph_result$spedges,
n = n,
resolution = resolution,
nsim = nsim)
all_values <- lapply(1:nsim,function(i){
dist_mat <- dist_matrices[[i]]
k_vals <- kfunc(dist_mat,start,end,step,Lt,n,w = w)
g_vals <- gfunc(dist_mat,start,end,step,width,Lt,n,w = w)
if(verbose){
setTxtProgressBar(pb, i)
}
return(cbind(k_vals,g_vals))
})
}else{
all_values <- lapply(1:nsim,function(i){
dist_mat <- randomize_distmatrix(graph_result$graph,graph_result$spedges,n)
k_vals <- kfunc(dist_mat,start,end,step,Lt,n,w = w)
g_vals <- gfunc(dist_mat,start,end,step,width,Lt,n,w = w)
if(verbose){
setTxtProgressBar(pb, i)
}
return(cbind(k_vals,g_vals))
})
}
k_mat <- do.call(cbind,lapply(all_values,function(i){return(i[,1])}))
g_mat <- do.call(cbind,lapply(all_values,function(i){return(i[,2])}))
upper <- 1-conf_int / 2
lower <- conf_int / 2
k_stats <- apply(k_mat,MARGIN = 1, function(i){
return(quantile(i,probs = c(lower,upper)))
})
g_stats <- apply(g_mat,MARGIN = 1, function(i){
return(quantile(i,probs = c(lower,upper)))
})
plot_df <- data.frame(
"obs_k" = k_vals,
"lower_k" = k_stats[1,],
"upper_k" = k_stats[2,],
"obs_g" = g_vals,
"lower_g" = g_stats[1,],
"upper_g" = g_stats[2,],
"distances" = seq(start,end,step)
)
plotk <- ggplot(plot_df)+
geom_ribbon(aes_string(x = "distances", ymin="lower_k",ymax = "upper_k"),
fill = grDevices::rgb(0.1,0.1,0.1), alpha=0.4)+
geom_path(aes_string(x = "distances", y = "lower_k"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "upper_k"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "obs_k"), col="blue")+
labs(x = "distances",
y = "empirical K-function")
plotg <- ggplot(plot_df)+
geom_ribbon(aes_string(x = "distances", ymin="lower_g", ymax = "upper_g"),
fill = grDevices::rgb(0.1,0.1,0.1),alpha=0.4, )+
geom_path(aes_string(x = "distances", y = "lower_g"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "upper_g"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "obs_g"), col="blue")+
labs(x = "distances",
y = "empirical G-function")
return(list(
"plotk" = plotk,
"plotg" = plotg,
"values" = plot_df
))
}
kfunctions.mc <- function(lines, points, start, end, step, width, nsim, conf_int = 0.05, digits = 2 ,tol = 0.1, resolution = 50, agg = NULL, verbose = TRUE){
if(verbose){
print("Preparing data ...")
}
n <- nrow(points)
points$goid <- seq_len(nrow(points))
points$weight <- rep(1,nrow(points))
points <- clean_events(points,digits,agg)
probs <- NULL
if(is.null(probs)){
lines$probs <- 1
}else{
lines$probs <- probs
}
lines$length <- gLength(lines,byid = TRUE)
lines <- subset(lines, lines$length>0)
lines$oid <- seq_len(nrow(lines))
if(verbose){
print("Snapping points on lines ...")
}
snapped_events <- snapPointsToLines2(points,lines,idField = "oid")
new_lines <- split_lines_at_vertex(lines, snapped_events,
snapped_events$nearest_line_id, tol)
if(verbose){
print("Building graph ...")
}
new_lines$length <- gLength(new_lines,byid = TRUE)
new_lines <- subset(new_lines,new_lines$length>0)
new_lines <- remove_loop_lines(new_lines,digits)
new_lines$oid <- seq_len(nrow(new_lines))
new_lines <- new_lines[c("length","oid","probs")]
Lt <- gLength(new_lines)
graph_result <- build_graph(new_lines,digits = digits,line_weight = "length", attrs = TRUE)
graph_result$spedges$probs <- igraph::get.edge.attribute(graph_result$graph,
name = "probs")
graph <- graph_result$graph
nodes <- graph_result$spvertices
snapped_events$vertex_id <- closest_points(snapped_events, nodes)
dist_mat <- igraph::distances(graph,v = snapped_events$vertex_id,
to = snapped_events$vertex_id)
if(verbose){
print("Calculating k and g functions ...")
}
k_vals <- kfunc(dist_mat,start,end,step,Lt,n,w = snapped_events$weight)
g_vals <- gfunc(dist_mat,start,end,step,width,Lt,n,w = snapped_events$weight)
if(verbose){
print("Calculating the simulations ...")
}
w <- rep(1,times = n)
sim_seq <- 1:nsim
graph <- graph_result$graph
edgesdf <- graph_result$spedges@data
if (is.null(resolution)){
if(verbose){
progressr::with_progress({
p <- progressr::progressor(along = sim_seq)
all_values <- future.apply::future_lapply(sim_seq, function(i){
dist_mat <- randomize_distmatrix(graph, edgesdf, n)
k_vals <- kfunc(dist_mat,start,end,step,Lt,n,w = w)
g_vals <- gfunc(dist_mat,start,end,step,width,Lt,n,w = w)
return(cbind(k_vals,g_vals))
},future.packages = c("igraph"))
})
}else{
all_values <- future.apply::future_lapply(sim_seq, function(i){
dist_mat <- randomize_distmatrix(graph, edgesdf, n)
k_vals <- kfunc(dist_mat,start,end,step,Lt,n,w = w)
g_vals <- gfunc(dist_mat,start,end,step,width,Lt,n,w = w)
return(cbind(k_vals,g_vals))
},future.packages = c("igraph"))
}
}else{
if(verbose){
print("generating the randomized distance matrices...")
}
dist_mats <- randomize_distmatrix2(graph, edgesdf,
n = n, nsim = nsim,
resolution = resolution)
if(verbose){
print("calculating the k and g functions for the randomized matrices..")
}
all_values <- future.apply::future_lapply(dist_mats, function(dist_mat){
k_vals <- kfunc(dist_mat,start,end,step,Lt,n,w = w)
g_vals <- gfunc(dist_mat,start,end,step,width,Lt,n,w = w)
return(cbind(k_vals,g_vals))
},future.packages = c("igraph"))
}
k_mat <- do.call(cbind,lapply(all_values,function(i){return(i[,1])}))
g_mat <- do.call(cbind,lapply(all_values,function(i){return(i[,2])}))
lower <- 1-conf_int/2
upper <- conf_int/2
k_stats <- apply(k_mat,MARGIN = 1, function(i){
return(quantile(i,probs = c(lower,upper)))
})
g_stats <- apply(g_mat,MARGIN = 1, function(i){
return(quantile(i,probs = c(lower,upper)))
})
plot_df <- data.frame(
"obs_k" = k_vals,
"upper_k" = k_stats[1,],
"lower_k" = k_stats[2,],
"obs_g" = g_vals,
"upper_g" = g_stats[1,],
"lower_g" = g_stats[2,],
"distances" = seq(start,end,step)
)
plotk <- ggplot(plot_df)+
geom_ribbon(aes_string(x = "distances", ymin="lower_k", ymax = "upper_k"),
fill = grDevices::rgb(0.1,0.1,0.1),alpha=0.4, )+
geom_path(aes_string(x = "distances", y = "lower_k"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "upper_k"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "obs_k"), col="blue")+
labs(x = "distances",
y = "empirical K-function")
plotg <- ggplot(plot_df)+
geom_ribbon(aes_string(x = "distances", ymin="lower_g", ymax = "upper_g"),
fill = grDevices::rgb(0.1,0.1,0.1),alpha=0.4, )+
geom_path(aes_string(x = "distances", y = "lower_g"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "upper_g"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "obs_g"), col="blue")+
labs(x = "distances",
y = "empirical G-function")
return(list(
"plotk" = plotk,
"plotg" = plotg,
"values" = plot_df
))
}
cross_kfunctions <- function(lines, pointsA, pointsB, start, end, step, width, nsim, conf_int = 0.05, digits = 2, tol = 0.1, resolution = NULL, agg = NULL, verbose = TRUE){
if(verbose){
print("Preparing data ...")
}
na <- nrow(pointsA)
nb <- nrow(pointsB)
probs <- NULL
pointsA$weight <- rep(1,nrow(pointsA))
pointsA <- clean_events(pointsA,digits,agg)
pointsA$goid <- seq_len(nrow(pointsA))
pointsB$weight <- rep(1,nrow(pointsB))
pointsB <- clean_events(pointsB,digits,agg)
pointsB$goid <- seq_len(nrow(pointsB))
if(is.null(probs)){
lines$probs <- 1
}else{
lines$probs <- probs
}
lines$length <- gLength(lines,byid = TRUE)
lines <- subset(lines, lines$length>0)
lines$oid <- seq_len(nrow(lines))
if(verbose){
print("Snapping points on lines ...")
}
pointsA$type <- "A"
pointsB$type <- "B"
all_events <- rbind(pointsA[c("type","goid","weight")],
pointsB[c("type","goid","weight")])
snapped_events <- snapPointsToLines2(all_events, lines, idField = "oid")
new_lines <- split_lines_at_vertex(lines, snapped_events,
snapped_events$nearest_line_id, tol)
if(verbose){
print("Building graph ...")
}
new_lines$length <- gLength(new_lines ,byid = TRUE)
new_lines <- subset(new_lines, new_lines$length>0)
new_lines <- remove_loop_lines(new_lines, digits)
new_lines$oid <- seq_len(nrow(new_lines))
new_lines <- new_lines[c("length","oid","probs")]
Lt <- gLength(new_lines)
graph_result <- build_graph(new_lines,digits = digits,
line_weight = "length", attrs = TRUE)
graph_result$spedges$probs <- igraph::get.edge.attribute(graph_result$graph,
name = "probs")
graph <- graph_result$graph
nodes <- graph_result$spvertices
snapped_events$vertex_id <- closest_points(snapped_events, nodes)
snappedA <- subset(snapped_events, snapped_events$type == "A")
snappedB <- subset(snapped_events, snapped_events$type == "B")
dist_mat <- igraph::distances(graph,v = snappedB$vertex_id,
to = snappedA$vertex_id, mode = "out")
if(verbose){
print("Calculating k and g functions ...")
}
k_vals <- cross_kfunc(dist_mat,start,end,step,Lt,na,nb,snappedA$weight,snappedB$weight)
g_vals <- cross_gfun(dist_mat,start,end,step,width,Lt,na,nb,snappedA$weight,snappedB$weight)
if(verbose){
print("Calculating the simulations ...")
pb <- txtProgressBar(min = 0, max = nsim, style = 3)
}
w <- rep(1,times = na)
if (is.null(resolution)==FALSE){
dist_matrices <- randomize_distmatrix2(graph = graph_result$graph,
edge_df = graph_result$spedges,
n = na,
start_vert = snappedB$vertex_id,
resolution = resolution,
nsim = nsim)
all_values <- lapply(1:nsim,function(i){
dist_mat <- dist_matrices[[i]]
k_vals <- cross_kfunc(dist_mat,start,end,step,Lt,na,nb,w,snappedB$weight)
g_vals <- cross_gfun(dist_mat,start,end,step,width,Lt,na,nb,w,snappedB$weight)
if(verbose){
setTxtProgressBar(pb, i)
}
return(cbind(k_vals,g_vals))
})
}else{
all_values <- lapply(1:nsim,function(i){
dist_mat <- randomize_distmatrix(graph_result$graph,graph_result$spedges,
na,start_vert = snappedB$vertex_id)
k_vals <- cross_kfunc(dist_mat,start,end,step,Lt,na,nb,w,snappedB$weight)
g_vals <- cross_gfun(dist_mat,start,end,step,width,Lt,na,nb,w,snappedB$weight)
if(verbose){
setTxtProgressBar(pb, i)
}
return(cbind(k_vals,g_vals))
})
}
k_mat <- do.call(cbind,lapply(all_values,function(i){return(i[,1])}))
g_mat <- do.call(cbind,lapply(all_values,function(i){return(i[,2])}))
upper <- 1-conf_int / 2
lower <- conf_int / 2
k_stats <- apply(k_mat,MARGIN = 1, function(i){
return(quantile(i,probs = c(lower,upper)))
})
g_stats <- apply(g_mat,MARGIN = 1, function(i){
return(quantile(i,probs = c(lower,upper)))
})
plot_df <- data.frame(
"obs_k" = k_vals,
"lower_k" = k_stats[1,],
"upper_k" = k_stats[2,],
"obs_g" = g_vals,
"lower_g" = g_stats[1,],
"upper_g" = g_stats[2,],
"distances" = seq(start,end,step)
)
plotk <- ggplot(plot_df)+
geom_ribbon(aes_string(x = "distances", ymin = "lower_k", ymax = "upper_k"),
fill = rgb(0.1,0.1,0.1),alpha=0.4, )+
geom_path(aes_string(x = "distances", y = "lower_k"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "upper_k"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "obs_k"), col="blue")+
labs(x = "distances",
y = "empirical cross-K-function")
plotg <- ggplot(plot_df)+
geom_ribbon(aes_string(x = "distances", ymin = "lower_g", ymax = "upper_g"),
fill = rgb(0.1,0.1,0.1),alpha=0.4, )+
geom_path(aes_string(x = "distances", y = "lower_g"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "upper_g"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "obs_g"), col="blue")+
labs(x = "distances",
y = "empirical cross-G-function")
return(list(
"plotk" = plotk,
"plotg" = plotg,
"values" = plot_df
))
}
cross_kfunctions.mc <- function(lines, pointsA, pointsB, start, end, step, width, nsim, conf_int = 0.05, digits = 2, tol = 0.1, resolution = NULL, agg = NULL, verbose = TRUE){
if(verbose){
print("Preparing data ...")
}
na <- nrow(pointsA)
nb <- nrow(pointsB)
probs <- NULL
pointsA$weight <- rep(1,nrow(pointsA))
pointsA <- clean_events(pointsA,digits,agg)
pointsA$goid <- seq_len(nrow(pointsA))
pointsB$weight <- rep(1,nrow(pointsB))
pointsB <- clean_events(pointsB,digits,agg)
pointsB$goid <- seq_len(nrow(pointsB))
if(is.null(probs)){
lines$probs <- 1
}else{
lines$probs <- probs
}
lines$length <- gLength(lines,byid = TRUE)
lines <- subset(lines, lines$length>0)
lines$oid <- seq_len(nrow(lines))
if(verbose){
print("Snapping points on lines ...")
}
pointsA$type <- "A"
pointsB$type <- "B"
all_events <- rbind(pointsA[c("type","goid","weight")],
pointsB[c("type","goid","weight")])
snapped_events <- snapPointsToLines2(all_events, lines, idField = "oid")
new_lines <- split_lines_at_vertex(lines, snapped_events,
snapped_events$nearest_line_id, tol)
if(verbose){
print("Building graph ...")
}
new_lines$length <- gLength(new_lines,byid = TRUE)
new_lines <- subset(new_lines,new_lines$length>0)
new_lines <- remove_loop_lines(new_lines,digits)
new_lines$oid <- seq_len(nrow(new_lines))
new_lines <- new_lines[c("length","oid","probs")]
Lt <- gLength(new_lines)
graph_result <- build_graph(new_lines,digits = digits,
line_weight = "length", attrs = TRUE)
graph_result$spedges$probs <- igraph::get.edge.attribute(graph_result$graph,
name = "probs")
graph <- graph_result$graph
nodes <- graph_result$spvertices
snapped_events$vertex_id <- closest_points(snapped_events, nodes)
snappedA <- subset(snapped_events, snapped_events$type == "A")
snappedB <- subset(snapped_events, snapped_events$type == "B")
dist_mat <- igraph::distances(graph,v = snappedB$vertex_id,
to = snappedA$vertex_id)
if(verbose){
print("Calculating k and g functions ...")
}
k_vals <- cross_kfunc(dist_mat, start, end, step, Lt, na, nb,
snappedA$weight, snappedB$weight)
g_vals <- cross_gfun(dist_mat, start, end, step, width, Lt, na,
nb, snappedA$weight, snappedB$weight)
if(verbose){
print("Calculating the simulations ...")
}
w <- rep(1,times = na)
sim_seq <- 1:nsim
if (is.null(resolution)){
progressr::with_progress({
p <- progressr::progressor(along = sim_seq)
all_values <- future.apply::future_lapply(sim_seq,function(i){
dist_mat <- randomize_distmatrix(graph_result$graph,
graph_result$spedges,
na, start_vert = snappedB$vertex_id)
k_vals <- cross_kfunc(dist_mat, start, end, step, Lt, na, nb,
w, snappedB$weight)
g_vals <- cross_gfun(dist_mat, start, end, step, width, Lt, na, nb,
w,snappedB$weight)
return(cbind(k_vals,g_vals))
},future.packages = c("igraph","base"))
})
}else{
if(verbose){
print("calculating the randomized distance matrices...")
}
dist_matrices <- randomize_distmatrix2(graph = graph_result$graph,
edge_df = graph_result$spedges,
n = na,
start_vert = snappedB$vertex_id,
resolution = resolution,
nsim = nsim)
if(verbose){
print("calculating the k and g functions for the randomized matrices..")
}
all_values <- future.apply::future_lapply(dist_matrices,function(dist_mat){
k_vals <- cross_kfunc(dist_mat, start, end, step, Lt, na, nb,
w, snappedB$weight)
g_vals <- cross_gfun(dist_mat, start, end, step, width, Lt, na, nb,
w,snappedB$weight)
return(cbind(k_vals,g_vals))
},future.packages = c("igraph","base"))
}
k_mat <- do.call(cbind,lapply(all_values,function(i){return(i[,1])}))
g_mat <- do.call(cbind,lapply(all_values,function(i){return(i[,2])}))
upper <- 1-conf_int / 2
lower <- conf_int / 2
k_stats <- apply(k_mat,MARGIN = 1, function(i){
return(quantile(i,probs = c(lower,upper)))
})
g_stats <- apply(g_mat,MARGIN = 1, function(i){
return(quantile(i,probs = c(lower,upper)))
})
plot_df <- data.frame(
"obs_k" = k_vals,
"lower_k" = k_stats[1,],
"upper_k" = k_stats[2,],
"obs_g" = g_vals,
"lower_g" = g_stats[1,],
"upper_g" = g_stats[2,],
"distances" = seq(start,end,step)
)
plotk <- ggplot(plot_df)+
geom_ribbon(aes_string(x = "distances", ymin = "lower_k", ymax = "upper_k"),
fill = rgb(0.1,0.1,0.1),alpha=0.4, )+
geom_path(aes_string(x = "distances", y = "lower_k"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "upper_k"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "obs_k"), col="blue")+
labs(x = "distances",
y = "empirical cross-K-function")
plotg <- ggplot(plot_df)+
geom_ribbon(aes_string(x = "distances", ymin = "lower_g", ymax = "upper_g"),
fill = rgb(0.1,0.1,0.1),alpha=0.4, )+
geom_path(aes_string(x = "distances", y = "lower_g"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "upper_g"), col="black",
linetype="dashed")+
geom_path(aes_string(x = "distances", y = "obs_g"), col="blue")+
labs(x = "distances",
y = "empirical cross-G-function")
return(list(
"plotk" = plotk,
"plotg" = plotg,
"values" = plot_df
))
} |
print.AT <- function(x, ...){
if(x$triv == FALSE){
if(x$type != "naive" && !(x$mar2 %in% x$bl) && x$eq == 1){
es <- format(x$Effects, digits = 3, trim=TRUE)
cat("\n")
print(es)
cat("\n")
}else{
if(x$mar2 %in% x$bl || ( !(x$mar2 %in% x$bl) && x$eq == 1) ) es <- format(x$res*100, digits = 3, trim=TRUE)
if(!(x$mar2 %in% x$bl) && x$eq == 2) es <- format(x$res, digits = 3, trim=TRUE)
if(x$mar2 %in% x$bl || ( !(x$mar2 %in% x$bl) && x$eq == 1) ) cat("\nTreatment effect (%) with ",(1-x$prob.lev)*100,"% interval:\n\n",sep="")
if( !(x$mar2 %in% x$bl) && x$eq == 2) cat("\nTreatment effect with ",(1-x$prob.lev)*100,"% interval:\n\n",sep="")
if(x$Model != "ROY") cat(es[2]," (",es[1],",",es[3],")\n\n",sep="")
}
}
if(x$triv == TRUE){
es <- format(x$res*100, digits = 3, trim=TRUE)
cat("\nTreatment effect (%) with ",(1-x$prob.lev)*100,"% interval:\n\n",sep="")
cat(es[2]," (",es[1],",",es[3],")\n\n",sep="")
}
if(x$Model == "ROY"){
es <- format(x$res, digits = 3, trim=TRUE)
cat("\nMarginal effect with ",(1-x$prob.lev)*100,"% interval:\n\n",sep="")
cat(es[2]," (",es[1],",",es[3],")\n\n",sep="")
}
invisible(x)
} |
sl.sim <- function(decTable, file, header = TRUE, sep = ",", ...) {
sl <- read.table(file, header, sep, ...)
out <- lapply(1:nrow(sl), function(i){
info <- sl[i, ][!is.na(sl[i, ])]
n.info <- length(info)
dec.sim(info[3:n.info], decTable, info[1], info[2])
})
if(nrow(sl) > 1) {
class(out) <- c("sl.sim", "dec.sim")
} else {
class(out) <- "dec.sim"
}
return(out)
} |
find_response <- function(x, combine = TRUE, ...) {
UseMethod("find_response")
}
find_response.default <- function(x, combine = TRUE, ...) {
f <- find_formula(x, verbose = FALSE)
if (is.null(f)) {
return(NULL)
}
if (is_multivariate(f)) {
resp <- unlist(lapply(f, function(i) .safe_deparse(i$conditional[[2L]])))
} else {
resp <- .safe_deparse(f$conditional[[2L]])
}
check_cbind(resp, combine, model = x)
}
find_response.model_fit <- function(x, combine = TRUE, ...) {
find_response(x$fit, combine = combine, ...)
}
find_response.bfsl <- function(x, combine = TRUE, ...) {
resp <- find_response.default(x, combine = combine)
if (is.null(resp)) {
resp <- "y"
}
resp
}
find_response.selection <- function(x, combine = TRUE, ...) {
f <- find_formula(x, verbose = FALSE)
resp <- c(
.safe_deparse(f$conditional$selection[[2L]]),
.safe_deparse(f$conditional$outcome[[2L]])
)
check_cbind(resp, combine, model = x)
}
find_response.mediate <- function(x, combine = TRUE, ...) {
f <- find_formula(x, verbose = FALSE)
if (is.null(f)) {
return(NULL)
}
resp <- c(.safe_deparse(f$mediator$conditional[[2L]]), .safe_deparse(f$outcome$conditional[[2L]]))
check_cbind(resp, combine, model = x)
}
find_response.mjoint <- function(x, combine = TRUE, component = c("conditional", "survival", "all"), ...) {
component <- match.arg(component)
f <- find_formula(x, verbose = FALSE)
if (is.null(f)) {
return(NULL)
}
conditional <- unlist(lapply(f[grepl("^conditional", names(f))], function(i) .safe_deparse(i[[2L]])))
survial <- .safe_deparse(f$survival[[2L]])
resp <- switch(component,
"conditional" = conditional,
"survial" = survial,
"all" = c(conditional, survial)
)
unlist(lapply(resp, check_cbind, combine = combine, model = x))
}
find_response.joint <- function(x,
combine = TRUE,
component = c("conditional", "survival", "all"),
...) {
component <- match.arg(component)
f <- find_formula(x, verbose = FALSE)
if (is.null(f)) {
return(NULL)
}
conditional <- .safe_deparse(f$conditional[[2L]])
survial <- .safe_deparse(f$survival[[2L]])
resp <- switch(component,
"conditional" = conditional,
"survial" = survial,
"all" = c(conditional, survial)
)
unlist(lapply(resp, check_cbind, combine = combine, model = x))
}
check_cbind <- function(resp, combine, model) {
if (!combine && inherits(model, "DirichletRegModel")) {
resp <- model$varnames
} else if (!combine && any(grepl("cbind\\((.*)\\)", resp))) {
resp <- .extract_combined_response(resp, "cbind")
} else if (!combine && any(grepl("Surv\\((.*)\\)", resp))) {
resp <- .extract_combined_response(resp, "Surv")
} else if (!combine && any(grepl("Hist\\((.*)\\)", resp))) {
resp <- .extract_combined_response(resp, "Hist")
} else if (!combine && any(grepl("Event\\((.*)\\)", resp))) {
resp <- .extract_combined_response(resp, "Event")
} else if (!combine && any(grepl("Curv\\((.*)\\)", resp))) {
resp <- .extract_combined_response(resp, "Curv")
} else if (!combine && any(grepl("MMO\\((.*)\\)", resp))) {
resp <- .extract_combined_response(resp, "MMO")
} else if (!combine && any(grepl("MMO2\\((.*)\\)", resp))) {
resp <- .extract_combined_response(resp, "MMO2")
} else if (!combine && any(grepl("/", resp, fixed = TRUE))) {
resp <- strsplit(resp, split = "/", fixed = TRUE)
resp <- gsub("(I|\\(|\\))", "", .trim(unlist(resp)))
} else if (any(.string_contains("|", resp))) {
r1 <- .trim(sub("(.*)\\|(.*)", "\\1", resp))
r2 <- .trim(sub("(.*)\\|(.*)\\(([^,)]*).*", "\\3", resp))
r_resp <- .trim(unlist(strsplit(resp, "|", fixed = TRUE))[2])
if (grepl("^resp_thres", r_resp)) {
r3 <- .trim(sub("=", "", sub("(.*)\\(([^=)]*)(.*)\\)", "\\3", r_resp)))
names(r3) <- r3
numeric_values <- suppressWarnings(as.numeric(r2))
r2 <- r2[is.na(numeric_values)]
if (length(r2)) {
r2 <- c(r2, r3)
} else {
r2 <- r3
}
}
resp <- c(r1, r2)
} else if (!combine && any(grepl("+", resp, fixed = TRUE))) {
resp <- strsplit(resp, split = "+", fixed = TRUE)
resp <- gsub("(I|\\(|\\))", "", .trim(unlist(resp)))
}
if (inherits(model, "clogit") && grepl("^rep\\(", resp[1]) && length(resp) == 3) {
resp <- c(paste0(resp[1], resp[2]), resp[3])
}
.remove_pattern_from_names(resp, ignore_asis = TRUE)
}
.extract_combined_response <- function(resp, pattern) {
if (pattern %in% c("MMO", "MMO2") && !grepl(paste0("^", pattern, "\\((.*),(.*)\\)"), resp)) {
resp <- gsub(paste0("^", pattern, "\\((.*)\\)"), "\\1", resp)
} else {
resp <- sub(sprintf("%s\\(([^,].*)([\\)].*)", pattern), "\\1", resp)
resp <- strsplit(resp, split = ",", fixed = TRUE)
resp <- .trim(unlist(resp))
}
if (any(.string_contains("-", resp[2]))) {
resp[2] <- .trim(sub("(.*)(\\-)(.*)", "\\1", resp[2]))
}
resp
} |
NULL
.onLoad <- function(libname, pkgname) {
while (".needs" %in% search()) detach(.needs)
sysfile <- system.file("extdata", "promptUser", package = "needs")
promptUser <- as.logical(scan(sysfile, quiet = T))
options(needs.promptUser = promptUser)
if (getOption("needs.promptUser")) {
if (interactive()) {
q <- "Should `needs` load itself when it's... needed?\n (this is recommended)"
choices <- sample(c("Yes", "No"))
yes <- choices[utils::menu(choices, title = q)] == "Yes"
if (isTRUE(yes)) {
siteProfile <- if (is.na(Sys.getenv("R_PROFILE", unset = NA))) {
file.path(Sys.getenv("R_HOME"), "etc", "Rprofile.site")
} else {
Sys.getenv("R_PROFILE")
}
if (!file.exists(siteProfile)) {
file.create(siteProfile)
}
cxn <- file(siteProfile)
lines <- readLines(cxn)
if (!any(grepl("^[:blank:]*autoload\\(\"needs\", \"needs\"\\)", lines))) {
write('\n\nautoload("needs", "needs")\n\n', file = siteProfile, append = T)
}
close(cxn)
}
options(needs.promptUser = F)
write(0, file = sysfile)
}
}
}
.onAttach <- function(libname, pkgname) {
if (getOption("needs.promptUser") && !interactive()) {
packageStartupMessage("\nLoad `package:needs` in an interactive session to set auto-load flag\n")
}
} |
vfold_cv <- function(data, v = 10, repeats = 1,
strata = NULL, breaks = 4, pool = 0.1, ...) {
if(!missing(strata)) {
strata <- tidyselect::vars_select(names(data), !!enquo(strata))
if(length(strata) == 0) strata <- NULL
}
strata_check(strata, data)
if (repeats == 1) {
split_objs <- vfold_splits(data = data, v = v,
strata = strata, breaks = breaks, pool = pool)
} else {
for (i in 1:repeats) {
tmp <- vfold_splits(data = data, v = v, strata = strata, pool = pool)
tmp$id2 <- tmp$id
tmp$id <- names0(repeats, "Repeat")[i]
split_objs <- if (i == 1)
tmp
else
rbind(split_objs, tmp)
}
}
split_objs$splits <- map(split_objs$splits, rm_out)
cv_att <- list(v = v, repeats = repeats, strata = !is.null(strata))
new_rset(splits = split_objs$splits,
ids = split_objs[, grepl("^id", names(split_objs))],
attrib = cv_att,
subclass = c("vfold_cv", "rset"))
}
vfold_splits <- function(data, v = 10, strata = NULL, breaks = 4, pool = 0.1) {
if (!is.numeric(v) || length(v) != 1)
stop("`v` must be a single integer.", call. = FALSE)
n <- nrow(data)
if (is.null(strata)) {
folds <- sample(rep(1:v, length.out = n))
idx <- seq_len(n)
indices <- split_unnamed(idx, folds)
} else {
stratas <- tibble::tibble(idx = 1:n,
strata = make_strata(getElement(data, strata),
breaks = breaks,
pool = pool))
stratas <- split_unnamed(stratas, stratas$strata)
stratas <- purrr::map(stratas, add_vfolds, v = v)
stratas <- dplyr::bind_rows(stratas)
indices <- split_unnamed(stratas$idx, stratas$folds)
}
indices <- lapply(indices, default_complement, n = n)
split_objs <- purrr::map(indices, make_splits, data = data, class = "vfold_split")
tibble::tibble(splits = split_objs,
id = names0(length(split_objs), "Fold"))
}
add_vfolds <- function(x, v) {
x$folds <- sample(rep(1:v, length.out = nrow(x)))
x
}
print.vfold_cv <- function(x, ...) {
cat("
class(x) <- class(x)[!(class(x) %in% c("vfold_cv", "rset"))]
print(x, ...)
} |
expected <- eval(parse(text="FALSE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(\"lattice\", .Names = \"\"), FALSE, FALSE, NA)"));
.Internal(`duplicated`(argv[[1]], argv[[2]], argv[[3]], argv[[4]]));
}, o=expected); |
source("ESEUR_config.r")
pal_col=rainbow(3)
hair=read.csv(paste0(ESEUR_dir, "evolution/robinson1976a.csv.xz"), as.is=TRUE)
hair$total=rowSums(hair[ , -1])
plot(hair$year, 100*hair$clean_shaven/hair$total, type="l", col=pal_col[1],
xaxs="i", yaxs="i",
ylim=c(0, 90),
xlab="Year", ylab="Percentage\n")
lines(loess.smooth(hair$year, 100*hair$beard/hair$total, span=0.1), col=pal_col[2])
lines(loess.smooth(hair$year, 100*hair$mustache/hair$total, span=0.1), col=pal_col[3])
legend(x="topleft", legend=c("Clean shaven", "Beard", "Mustache"), bty="n", fill=pal_col, cex=1.2) |
register_extendr <- function(path = ".", quiet = FALSE, force = FALSE, compile = NA) {
pkg_name <- pkg_name(path)
if (!isTRUE(quiet)) {
ui_i("Generating extendr wrapper functions for package: {.pkg {pkg_name}}.")
}
entrypoint_c_file <- rprojroot::find_package_root_file("src", "entrypoint.c", path = path)
if (!file.exists(entrypoint_c_file)) {
ui_throw(
"Unable to register the extendr module.",
c(
bullet_x("Could not find file {.file src/entrypoint.c }."),
bullet_o("Are you sure this package is using extendr Rust code?")
)
)
}
outfile <- rprojroot::find_package_root_file("R", "extendr-wrappers.R", path = path)
path <- rprojroot::find_package_root_file(path = path)
if (isTRUE(is.na(compile))) {
compile <- needs_compilation(path, quiet) || pkgbuild::needs_compile(path)
}
if (isTRUE(compile)) {
pkgbuild::compile_dll(
path = path,
force = TRUE,
quiet = quiet
)
}
library_path <- get_library_path(path)
if (!file.exists(library_path)) {
msg <- "{library_path} doesn't exist"
if (isTRUE(compile)) {
ui_throw(msg)
} else {
ui_throw(
msg,
bullet_i("You need to compile first, try {.code register_rextendr(compile = TRUE)}.")
)
}
}
if (!isTRUE(force) && length(find_newer_files_than(outfile, library_path)) > 0) {
rel_path <- pretty_rel_path(outfile, path)
ui_i("{.file {rel_path}} is up-to-date. Skip generating wrapper functions.")
return(invisible(character(0L)))
}
tryCatch(
make_wrappers_externally(
module_name = pkg_name,
package_name = pkg_name,
outfile = outfile,
path = path,
use_symbols = TRUE,
quiet = quiet
),
error = function(e) {
ui_throw(
"Failed to generate wrapper functions.",
bullet_x(e[["message"]])
)
}
)
invisible(normalizePath(outfile))
}
make_wrappers <- function(module_name, package_name, outfile,
path = ".", use_symbols = FALSE, quiet = FALSE) {
wrapper_function <- glue("wrap__make_{module_name}_wrappers")
x <- .Call(
wrapper_function,
use_symbols = use_symbols,
package_name = package_name,
PACKAGE = package_name
)
x <- stringi::stri_split_lines1(x)
write_file(
text = x,
path = outfile,
search_root_from = path,
quiet = quiet
)
}
make_wrappers_externally <- function(module_name, package_name, outfile,
path, use_symbols = FALSE, quiet = FALSE) {
func <- function(path, make_wrappers, quiet,
module_name, package_name, outfile,
use_symbols, ...) {
library_path <- file.path(path, "src", paste0(package_name, .Platform$dynlib.ext))
lib <- dyn.load(library_path)
on.exit(dyn.unload(lib[["path"]]), add = TRUE)
make_wrappers(
module_name = module_name,
package_name = package_name,
outfile = outfile,
path = path,
use_symbols = use_symbols,
quiet = quiet
)
}
args <- list(
path = rprojroot::find_package_root_file(path = path),
make_wrappers = make_wrappers,
module_name = module_name,
package_name = package_name,
outfile = outfile,
use_symbols = use_symbols,
quiet = quiet
)
invisible(callr::r(func, args = args, show = !isTRUE(quiet)))
} |
NULL
NULL
methods::setGeneric("add_linear_penalties",
signature = methods::signature("x", "penalty", "data"),
function(x, penalty, data)
standardGeneric("add_linear_penalties"))
methods::setMethod("add_linear_penalties",
methods::signature("ConservationProblem", "ANY", "character"),
function(x, penalty, data) {
assertthat::assert_that(
inherits(x$data$cost, c("data.frame", "Spatial", "sf")),
msg = paste("argument to data is a character and planning units",
"specified in x are not a data.frame, Spatial, or sf object"))
assertthat::assert_that(
is.numeric(penalty), assertthat::noNA(penalty),
number_of_zones(x) == length(penalty),
assertthat::noNA(data), number_of_zones(x) == length(data))
assertthat::assert_that(
all(data %in% names(x$data$cost)),
msg = paste("argument to data is not a field name in the planning units",
"specified in x"))
d <- x$data$cost
if (inherits(d, "Spatial")) {
d <- as.matrix(d@data[, data, drop = FALSE])
} else if (inherits(d, "sf")) {
d <- as.matrix(sf::st_drop_geometry(d)[, data, drop = FALSE])
} else {
d <- as.matrix(d[, data, drop = FALSE])
}
assertthat::assert_that(
is.numeric(d),
msg = paste("argument to data correspond to non-numeric fields in",
"the planning unit data associated with x"))
assertthat::assert_that(
assertthat::noNA(d),
msg = paste("argument to data correspond to fields with NA values in",
"the planning unit data associated with x"))
add_linear_penalties(x, penalty, d)
})
methods::setMethod("add_linear_penalties",
methods::signature("ConservationProblem", "ANY", "numeric"),
function(x, penalty, data) {
assertthat::assert_that(
is.numeric(penalty), assertthat::noNA(penalty),
number_of_zones(x) == length(penalty),
assertthat::noNA(data), number_of_total_units(x) == length(data))
add_linear_penalties(x, penalty, matrix(data, ncol = 1))
})
methods::setMethod("add_linear_penalties",
methods::signature("ConservationProblem", "ANY", "matrix"),
function(x, penalty, data) {
assertthat::assert_that(
is.numeric(penalty), assertthat::noNA(penalty),
number_of_zones(x) == length(penalty),
assertthat::noNA(c(data)),
number_of_total_units(x) == nrow(data),
number_of_zones(x) == ncol(data))
add_linear_penalties(x, penalty, methods::as(data, "dgCMatrix"))
})
methods::setMethod("add_linear_penalties",
methods::signature("ConservationProblem", "ANY", "Matrix"),
function(x, penalty, data) {
assertthat::assert_that(
is.numeric(penalty), assertthat::noNA(penalty),
number_of_zones(x) == length(penalty),
assertthat::noNA(c(data)),
number_of_total_units(x) == nrow(data),
number_of_zones(x) == ncol(data))
add_linear_penalties(x, penalty, methods::as(data, "dgCMatrix"))
})
methods::setMethod("add_linear_penalties",
methods::signature("ConservationProblem", "ANY", "Raster"),
function(x, penalty, data) {
assertthat::assert_that(
inherits(x, "ConservationProblem"),
inherits(data, "Raster"),
is.numeric(penalty), assertthat::noNA(penalty),
number_of_zones(x) == raster::nlayers(data),
number_of_zones(x) == length(penalty),
inherits(x$data$cost, c("sf", "Spatial", "Raster")))
if (inherits(x$data$cost, c("sf", "Spatial"))) {
d <- fast_extract(data, x$data$cost, fun = "sum")
} else {
assertthat::assert_that(is_comparable_raster(x$data$cost, data[[1]]))
d <- as.matrix(raster::as.data.frame(data))
}
d[is.na(d)] <- 0
add_linear_penalties(x, penalty, methods::as(d, "dgCMatrix"))
})
methods::setMethod("add_linear_penalties",
methods::signature("ConservationProblem", "ANY", "dgCMatrix"),
function(x, penalty, data) {
assertthat::assert_that(
inherits(x, "ConservationProblem"),
is.numeric(penalty), isTRUE(all(is.finite(penalty))),
number_of_zones(x) == length(penalty),
is.numeric(data@x), all(is.finite(data@x),
number_of_total_units(x) == nrow(data),
number_of_zones(x) == ncol(data)))
if (number_of_zones(x) == 1) {
p <- numeric_parameter("penalty", penalty)
} else {
p <- numeric_parameter_array("penalty", penalty, x$zone_names())
}
x$add_penalty(pproto(
"LinearPenalty",
Penalty,
name = "Linear penalties",
data = list(data = data),
parameters = parameters(p),
apply = function(self, x, y) {
assertthat::assert_that(inherits(x, "OptimizationProblem"),
inherits(y, "ConservationProblem"))
p <- self$parameters$get("penalty")
if (inherits(p, "data.frame")) p <- p[[1]]
if (min(abs(p)) > 1e-50) {
indices <- y$planning_unit_indices()
d <- self$get_data("data")[indices, , drop = FALSE]
rcpp_apply_linear_penalties(x$ptr, p, d)
}
invisible(TRUE)
}))
}) |
library(devtools)
library(microbenchmark)
library(ggplot2)
library(sf)
library(stars)
library(mapview)
library(rnaturalearth)
library(spData)
library(raster)
options(viewer=NULL)
if (FALSE) {
dev_mode()
install_github("mtennekes/tmap")
dev_mode(path = "~/R-dev_old")
install_github("mtennekes/tmap@895c4d4295")
}
data("world")
w <- rnaturalearth::ne_download(scale = 10, type = 'countries', returnclass = "sf")
granule = system.file("sentinel/S2A_MSIL1C_20180220T105051_N0206_R051_T32ULE_20180221T134037.zip", package = "starsdata")
s2 = paste0("SENTINEL2_L1C:/vsizip/", granule, "/S2A_MSIL1C_20180220T105051_N0206_R051_T32ULE_20180221T134037.SAFE/MTD_MSIL1C.xml:10m:EPSG_32632")
(p = read_stars(s2, proxy = TRUE))
p = st_set_crs(p, 32632)
(p2 = read_stars(s2, RasterIO = list(nXSize = 3000, nYSize = 3000)))
p2 = st_set_crs(p2, 32632)
r <- as(p2, "Raster")
prec_file = system.file("nc/test_stageiv_xyt.nc", package = "stars")
(prec = read_ncdf(prec_file, curvilinear = c("lon", "lat"), ignore_bounds = TRUE))
prec1_4 = dplyr::slice(prec, time, 1:4)
data(land, package = "tmap")
rm(p2, prec); gc()
mb <- list()
mb$sf <- microbenchmark(times = 5,
plot(world[, "lifeExp"]),
plot(w[, "ECONOMY"]))
str(mb$sf)
dev.off(dev.list()["RStudioGD"])
mb$stars <- microbenchmark(times = 5,
plot(p),
plot(prec1_4))
dev.off(dev.list()["RStudioGD"])
mb$raster <- microbenchmark(times = 5,
plot(r),
plot(land))
dev.off(dev.list()["RStudioGD"])
mb$mapview <- microbenchmark(times = 3,
print(mapview(world, z = "lifeExp")),
print(mapview(w, z = "ECONOMY")),
print(mapview(r[[1]], homebutton = FALSE)))
mb_tmap = function(version) {
if (version %in% c("cran_plot", "cran_view")) {
microbenchmark(times = 3,
print(tm_shape(world) + tm_polygons("lifeExp") + tm_layout(title = version)),
print(tm_shape(w) + tm_polygons("ECONOMY")),
print(tm_shape(r) + tm_raster()),
print(tm_shape(land) + tm_raster()))
} else {
microbenchmark(times = 3,
print(tm_shape(world) + tm_polygons("lifeExp") + tm_layout(title = version)),
print(tm_shape(w) + tm_polygons("ECONOMY")),
print(tm_shape(p) + tm_raster()),
print(tm_shape(r) + tm_raster()),
print(tm_shape(prec1_4) + tm_raster()),
print(tm_shape(land) + tm_raster()))
}
}
library(tmap)
tmap_mode("plot")
mb$tmap_CRAN_plot = mb_tmap(version = "cran_plot")
dev.off(dev.list()["RStudioGD"])
tmap_mode("view")
mb$tmap_CRAN_view = mb_tmap(version = "cran_view")
gc()
detach("package:tmap", unload = TRUE)
dev_mode(TRUE)
library(tmap)
tmap_mode("plot")
mb$tmap_new_plot = mb_tmap(version = "new_plot")
dev.off(dev.list()["RStudioGD"])
tmap_mode("view")
mb$tmap_new_view = mb_tmap(version = "new_view")
mbs = do.call(rbind, mb)
autoplot(mbs) |
"ggthemes_data" |
search_songs=function(api_key,artist=NA,artist_id=NA,title=NA,hotttnesss=T,style=NA,artist_location=T,
combined=NA,sort=NA,audio_summary=F,partner=NA,min_name=NA,discovery=T,
max_name=NA,min_val=NA,max_val=NA,start=NA,results=15,mode=NA,key=NA,currency=T,
description=NA,rank_type="relevance",mood=NA,familiarity=T,
song_type=NA,artist_start_year_before=NA,artist_start_year_after=NA,
artist_end_year_before=NA,artist_end_year_after=NA)
{
url=paste("http://developer.echonest.com/api/v4/song/search?api_key=",api_key,"&format=json",sep="")
final=""
if(results>100)
{
stop("results should be less than or equal to 100")
}
if(!is.na(artist))
{
artist=gsub(" ","+",artist)
url=paste(url,"&artist=",artist,sep="")
}
if(!is.na(artist_id))
{
url=paste(url,"&artist_id=",artist_id,sep="")
}
if(!is.na(combined))
{
combined=gsub(" ","+",combined)
url=paste(url,"&combined=",combined,sep="")
}
if(!is.na(description))
{
description=gsub(" ","+",description)
url=paste(url,"&description=",description,sep="")
}
if(!is.na(song_type))
{
song_type=gsub(" ","+",song_type)
url=paste(url,"&song_type=",song_type,sep="")
}
if(!is.na(mood))
{
mood=gsub(" ","+",mood)
url=paste(url,"&mood=",mood,sep="")
}
if(!is.na(mode))
{
mode=gsub(" ","+",mode)
url=paste(url,"&mode=",mode,sep="")
}
if(!is.na(key))
{
key=gsub(" ","+",key)
url=paste(url,"&key=",key,sep="")
}
if(hotttnesss)
{
url=paste(url,"&bucket=song_hotttnesss&bucket=song_hotttnesss_rank&bucket=artist_hotttnesss&bucket=artist_hotttnesss_rank",sep="")
}
if(familiarity)
{
url=paste(url,"&bucket=artist_familiarity&bucket=artist_familiarity_rank",sep="")
}
if(currency)
{
url=paste(url,"&bucket=song_currency&bucket=song_currency_rank",sep="")
}
if(discovery)
{
url=paste(url,"&bucket=artist_discovery&bucket=artist_discovery_rank",sep="")
}
if(audio_summary)
{
url=paste(url,"&bucket=audio_summary",sep="")
}
if(artist_location)
{
url=paste(url,"&bucket=artist_location",sep="")
}
if(!is.na(sort))
{
url=paste(url,"&sort=",sort,sep="")
}
if(!is.na(partner))
{
url=paste(url,"&bucket=id:",partner,"&limit=true",sep="")
}
if(!is.na(style))
{
url=paste(url,"&style=",style,sep="")
}
if(!is.na(min_name))
{
len=length(min_name)
for(i in 1:len)
{
url=paste(url,"&",min_name[i],"=",min_val[i],sep="")
}
}
if(!is.na(max_name))
{
len=length(max_name)
for(i in 1:len)
{
url=paste(url,"&",max_name[i],"=",max_val[i],sep="")
}
}
url=paste(url,"&rank_type=",rank_type,sep="")
if(!is.na(title))
{
title=gsub(" ","+",title)
url=paste(url,"&title=",title,sep="")
}
if(!is.na(artist_start_year_before))
{
url=paste(url,"&artist_start_year_before=",artist_start_year_before,sep="")
}
if(!is.na(artist_start_year_after))
{
url=paste(url,"&artist_start_year_after=",artist_start_year_after,sep="")
}
if(!is.na(artist_end_year_before))
{
url=paste(url,"&artist_end_year_before=",artist_end_year_before,sep="")
}
if(!is.na(artist_end_year_after))
{
url=paste(url,"&artist_end_year_after=",artist_end_year_after,sep="")
}
if(!is.na(start))
{
url=paste(url,"&start=",start,sep="")
}
url=paste(url,"&results=",results,sep="")
rd=getURL(url)
rd=fromJSON(rd)
rd$response$songs
} |
survey.region.dht <- function(Nhat.by.sample, samples, width, left, point){
Effort.by.region <- by(samples$Effort, samples$Region.Label, sum)
if(point){
CoveredArea <- pi*as.vector(Effort.by.region)*width^2 -
pi*as.vector(Effort.by.region)*left^2
}else{
CoveredArea <- 2*as.vector(Effort.by.region)*(width-left)
}
Nhat.by.sample <- merge(Nhat.by.sample,
data.frame(Region.Label=names(Effort.by.region),
CoveredArea=CoveredArea,
Effort=as.vector(Effort.by.region)),
by.x="Region.Label",
by.y="Region.Label",
all.x=TRUE)
Nhat.by.sample$Nhat <- Nhat.by.sample$Nhat*Nhat.by.sample$Area/
Nhat.by.sample$CoveredArea
return(Nhat.by.sample)
} |
data.root <- function(d, y, c, my_env)
{
initval <- my_env$initval
ch <- my_env$ch
distr <- my_env$obj["distr"]
if(distr == "weibull")
{
r <- my_env$obj[["params"]]["shape"]
t <- my_env$obj[["params"]]["scale"]
g <- 0
g1r <- zipfR::Cgamma(1+1/r)
g2r <- zipfR::Cgamma(1+2/r)
A <- (t^2)*g2r*(exp(-1*((d-y+initval-g)/t)^r) - exp(-1*((d+initval-g)/t)^r))
B <- zipfR::Rgamma(((2/r)+1), ((d-y+initval-g)/t)^r, .Machine$double.xmin) -
zipfR::Rgamma(((2/r)+1), ((d+initval-g)/t)^r, .Machine$double.xmin)
C <- t*g1r*(zipfR::Rgamma(((1/r)+1), ((d-y+initval-g)/t)^r, .Machine$double.xmin) -
zipfR::Rgamma(((1/r)+1), ((d+initval-g)/t)^r, .Machine$double.xmin))
calc <- (A*B-(C^2))*(c)
}
if(distr == "gamma")
{
r <- my_env$obj[["params"]]["shape"]
f <- my_env$obj[["params"]]["rate"]
t <- 1/f
g <- 0
A <- (t^2)*r*(r+1)*(zipfR::Rgamma(r,(d-y+initval-g)/t)-
zipfR::Rgamma(r,(d+initval-g)/t))
B <- zipfR::Rgamma((r+2),(d-y+initval-g)/t)-
zipfR::Rgamma((r+2),(d+initval-g)/t)
C <- t*r*(zipfR::Rgamma((r+1),(d-y+initval-g)/t)-
zipfR::Rgamma((r+1),(d+initval-g)/t))
calc <- (A*B-(C^2))*(c)
}
if(distr == "exp")
{
lambda <- my_env$obj[["params"]]["rate"]
A <- exp(-1*lambda*(d-y+initval))
B <- (1/(lambda^2))*((1-exp(-1*lambda*y))^2)
C <- (y^2)*exp(-1*lambda*y)
calc <- ((A^2)*(B-C))*(c)
}
if(distr == "norm")
{
mu <- my_env$obj[["params"]]["mean"]
sigma <- my_env$obj[["params"]]["sd"]
A <- erf((d+initval-mu)/(sigma*sqrt(2)))-erf((d-y+initval-mu)/(sigma*sqrt(2)))
B <- ((d-y+initval-mu)/sigma)*exp(-1*(((d-y+initval-mu)/(sigma*sqrt(2)))^2)) -
((d+initval-mu)/sigma)*exp(-1*(((d+initval-mu)/(sigma*sqrt(2)))^2))
C <- exp(-1*(((d-y+initval-mu)/(sigma*sqrt(2)))^2)) -
exp(-1*(((d+initval-mu)/(sigma*sqrt(2)))^2))
calc <- (((sigma^2)/(2*sqrt(2*pi)))*A*B + 0.25*(sigma^2)*(A^2) -
((sigma^2)/(2*pi))*(C^2))*(c)
}
if(distr == "lnorm")
{
mu <- my_env$obj[["params"]]["meanlog"]
sigma <- my_env$obj[["params"]]["sdlog"]
A = (erf((log(d+initval)-mu-2*(sigma^2))/(sigma*sqrt(2))) -
erf((log(d-y+initval)-mu-2*(sigma^2))/(sigma*sqrt(2))))
B = (erf((log(d+initval)-mu)/(sigma*sqrt(2))) -
erf((log(d-y+initval)-mu)/(sigma*sqrt(2))))
C = (erf((log(d+initval)-mu-(sigma^2))/(sigma*sqrt(2))) -
erf((log(d-y+initval)-mu-(sigma^2))/(sigma*sqrt(2))))
calc = (0.25*exp(2*mu+2*(sigma^2))*A*B - 0.25*exp(2*mu +
(sigma^2))*(C^2))*(c)
}
if(distr == "cauchy")
{
mu <- my_env$obj[["params"]]["location"]
sig <- my_env$obj[["params"]]["scale"]
xh = (d+initval)
xh1 = (d-y+initval)
wh = (1/pi)*(atan((xh1+y-mu)/sig) - atan((xh1-mu)/sig))
muh = (1/(2*(atan((xh1+y-mu)/sig) -
atan((xh1-mu)/sig))))*(sig*log((xh1+y-mu)^2+sig^2) +
2*mu*atan((xh1+y-mu)/sig) - sig*log((xh1-mu)^2+sig^2) -
2*mu*atan((xh1-mu)/sig))
sig2h = (1/(atan((xh1+y-mu)/sig) -
atan((xh1-mu)/sig)))*(mu*sig*log((xh1+y-mu)^2+sig^2) +
(mu^2-sig^2)*atan((xh1+y-mu)/sig) + sig*(xh1+y) -
mu*sig*log((xh1-mu)^2+sig^2) -
(mu^2-sig^2)*atan((xh1-mu)/sig) - sig*xh1) - muh^2
calc = ((1/(pi^2))*(atan((xh1+y-mu)/sig) -
atan((xh1-mu)/sig))*(mu*sig*log((xh1+y-mu)^2+sig^2) +
(mu^2-sig^2)*atan((xh1+y-mu)/sig) +
sig*(xh1+y) - mu*sig*log((xh1-mu)^2+sig^2) -
(mu^2-sig^2)*atan((xh1-mu)/sig) - sig*xh1) -
((1/(4*pi^2))*((sig*log((xh1+y-mu)^2+sig^2) +
2*mu*atan((xh1+y-mu)/sig) -
sig*log((xh1-mu)^2+sig^2) -
2*mu*atan((xh1-mu)/sig)))^2))*(c)
}
if(distr == "triangle")
{
a <- my_env$obj[["params"]]["min"]
b <- my_env$obj[["params"]]["max"]
c <- my_env$obj[["params"]]["mode"]
eps = 1e-10
if(initval==0)
{
initval <- initval+eps
}
else{initval <- initval}
xh = d+initval
xh1 = d-y+initval
wh1 = (y*(y+2*(xh1-a)))/((b-a)*(c-a))
muh1 = ((2/3)*(y^2)+2*y*xh1-a*y+2*(xh1-a)*xh1)/(y+2*(xh1-a))
sig2h1 = ((y^2)*((y^2)+6*y*(xh1-a)+6*(xh1-a)^2))/(18*(y+2*(xh1-a))^2)
wh2 = (y*(2*(b-xh1)-y))/((b-a)*(b-c))
muh2 = (3*(b-xh1)*y-3*y*xh1+6*(b-xh1)*xh1-2*y^2)/(3*(2*(b-xh1)-y))
sig2h2 = ((y^2)*(6*(b-xh1)^2-6*y*(b-xh1)+y^2))/((18*(2*(b-xh1)-y)^2))
if(d <= c)
{
calc = ((wh1^2)*sig2h1)*(c)
}
if(d > c)
{
calc = ((wh2^2)*sig2h2)*(c)
}
}
if(distr == "rtriangle")
{
a <- my_env$obj[["params"]]["min"]
b <- my_env$obj[["params"]]["max"]
eps = 1e-10
if(initval==0)
{
initval <- initval+eps
}
else{initval <- initval}
xh = d+initval
xh1 = d-y+initval
wh = (y*(2*(b-xh1)-y))/((b-a)^2)
muh = (3*b*(y+2*xh1) - 2*(y^2+3*y*xh1) + 3*(xh1^2))/(3*(2*(b-xh1)-y))
sig2h = ((y^2)*(y^2-6*(b-xh1)*y+6*((b-xh1)^2)))/(18*((2*(b-xh1)-y)^2))
calc = ((wh^2)*(sig2h))*(c)
}
if(distr == "unif")
{
minn <- my_env$obj[["params"]]["min"]
maxx <- my_env$obj[["params"]]["max"]
xh = d+initval
xh1 = d-y+initval
wh = y/(maxx-minn)
muh = (y+2*xh1)/2
sig2h = (y^2)/12
calc = ((wh^2)*(sig2h))*(c)
}
if(distr == "pareto")
{
a <- my_env$obj[["params"]]["shape"]
s <- my_env$obj[["params"]]["scale"]
xh <- d+initval
xh1 <- d-y+initval
Wh <- (s/(xh1+s))^a - (s/((y+xh1)+s))^a
A = ((y+xh1+s)^(2-a))/(2-a)
B = (2*s*(y+xh1+s)^(1-a))/(1-a)
C = ((s^2)*(y+xh1+s)^(-a))/a
D = ((xh1+s)^(2-a))/(2-a)
E = (2*s*(xh1+s)^(1-a))/(1-a)
G = ((s^2)*(xh1+s)^(-a))/a
H = (a*(y+xh1)+s)/((y+xh1+s)^a)
I = (a*xh1+s)/((xh1+s)^a)
calc = ((a*s^a)*Wh*(A-B-C-D+E+G) - ((s^(2*a))/((1-a)^2))*(H-I)^2)*(c)
}
if(calc < 0 || is.nan(calc) || is.na(calc))
{
rtval <- -1
}
else
{
rtval <- sqrt(calc)
}
return(rtval)
} |
"power.grouped" <-
function(n = NULL, m, X = NULL, theta, sigma, sign.level = 0.05,
type.power = c("conditional", "marginal"), MC.iter = 10,
type.lik = c("original", "approximate"), gr.mech = c("rounding", "equispaced"),
dist.t, dist.x, power. = NULL, limits = c(10, 3000)){
if(sum(sapply(list(n, power.), is.null)) != 1)
stop("exactly one of the ", sQuote("n"), " and ", sQuote("power."), " must be NULL")
if(is.null(n) && type.power == "conditional")
stop(sQuote("type.power"), " must be ", sQuote("marginal"), ": sample size calculations are based on the marginal power formulas")
if(is.null(n) && !is.null(X)) n <- nrow(X)
if(missing(dist.x) && length(theta) != 2 && type.power == "marginal")
stop("distributional assumptions about the extra covariates must be made")
if(is.null(X) && missing(dist.t))
stop("exactly one of the ", sQuote("X"), " and ", sQuote("dist.t"), " must be given")
if(!is.null(sign.level) && !is.numeric(sign.level) || any(sign.level < 0 | sign.level > 1))
stop(sQuote("sign.level"), " must be numeric in [0, 1]")
if(!is.null(X) && nrow(X) != n)
stop(sQuote("n"), " does not equal the number of the rows of X")
gr.mech <- match.arg(gr.mech)
type.power <- match.arg(type.power)
type.lik <- match.arg(type.lik)
if(!is.null(X) && type.power == "marginal")
stop("the type of power calculation cannot be marginal when ", sQuote("X"), " is given")
if(is.null(X) && type.power == "conditional")
stop("the type of power calculation cannot be conditional")
tpower <- switch(type.power, conditional = 1, marginal = 2)
tlik <- switch(type.lik, original = 1, approximate = 2)
pow. <- if(tpower == 1 && tlik == 1)
quote({cond.power.orig(X = X, theta = theta, sigma = sigma, m = m,
a = sign.level, grouping.mech = gr.mech)}) else
if(tpower == 1 && tlik == 2)
quote({cond.power.approx(X = X, theta = theta, sigma = sigma, m = m,
a = sign.level, grouping.mech = gr.mech)}) else
if(tpower == 2 && tlik == 1)
quote({marg.power.orig(MC = MC.iter, n = n, m = m, theta = theta, sigma = sigma,
a = sign.level, dist.t = dist.t, dist.x = dist.x, grouping.mech = gr.mech)[[1]]}) else
if(tpower == 2 && tlik == 2)
quote({marg.power.approx(MC = MC.iter, n = n, m = m, theta = theta, sigma = sigma,
a = sign.level, dist.t = dist.t, dist.x = dist.x, grouping.mech = gr.mech)[[1]]})
nn <- if(tlik ==1 ) quote({uniroot(samplesize.orig, interval = limits, p. = power., MC = MC.iter, theta = theta,
sigma = sigma, m = m, a = sign.level, dist.t = dist.t, dist.x = dist.x,
grouping.mech = gr.mech, tol = 1e-01, maxiter = 20)$root}) else
if(tlik == 2) quote({uniroot(samplesize.approx, interval = limits, p. = power., MC = MC.iter, theta = theta,
sigma = sigma, m = m, a = sign.level, dist.t = dist.t, dist.x = dist.x,
grouping.mech = gr.mech, tol = 1e-01, maxiter = 20)$root})
if(is.null(power.)) power. <- eval(pow.)
if(is.null(n)) n <- eval(nn)
structure(list(n = round(n), m = m, theta = theta, sigma = sigma, sign.level = sign.level,
type.power = type.power, type.lik = type.lik, power. = power., grouping.mech = gr.mech),
class = "power.grouped")
} |
gSlc <- function(formula,data = NULL,random = NULL,family,control = gSlc.control())
{
nBurn <- control$nBurn
nKept <- control$nKept
nThin <- control$nThin
fixedEffPriorVar <- control$fixedEffPriorVar
sdPriorScale <- control$sdPriorScale
numBasis <- control$numBasis
preTransfData <- control$preTransfData
msgCode <- control$msgCode
formularInformation <- readFormula(formula)
responseName <- formularInformation$response
linPredNames <- formularInformation$lvar
splPredNames <- formularInformation$svar
basisSizes <- formularInformation$nbas
numLinCompons <- length(linPredNames)
numSplCompons <- length(splPredNames)
if (is.null(data)) y <- get(responseName,pos=1)
if (!is.null(data)) y <- data[,responseName]
if (length(linPredNames)>0)
{
XlinPreds <- NULL ; namesXlinPreds <- NULL
for (jLin in 1:numLinCompons)
{
if (is.null(data)) currPred <- get(linPredNames[jLin],pos=1)
if (!is.null(data)) currPred <- data[,linPredNames[jLin]]
if (!is.character(currPred))
{
XlinPreds <- cbind(XlinPreds,currPred)
namesXlinPreds <- c(namesXlinPreds,linPredNames[jLin])
}
if (is.character(currPred))
{
suqcurrPred <- sort(unique(currPred)) ; baseChar <- suqcurrPred[1] ;
numLevs <- length(suqcurrPred)
if (length(suqcurrPred)==1) stop("Factor has all levels equal.")
XcurrPred <- NULL ; namesXcurrPred <- NULL
for (jLev in 2:numLevs)
{
XcurrPred <- cbind(XcurrPred,as.numeric(currPred==suqcurrPred[jLev]))
namesXcurrPred <- c(namesXcurrPred,paste(suqcurrPred[jLev],"VS",suqcurrPred[1],sep=""))
}
XcurrPred <- as.data.frame(XcurrPred)
XlinPreds <- cbind(XlinPreds,XcurrPred)
namesXlinPreds <- c(namesXlinPreds,namesXcurrPred)
}
}
names(XlinPreds) <- namesXlinPreds
XlinPreds <- as.matrix(XlinPreds)
numLinCompons <- ncol(XlinPreds)
linPredNames <- namesXlinPreds
}
if (length(linPredNames)==0) XlinPreds <- NULL
if (length(splPredNames)>0)
{
XsplPreds <- NULL
for (jSpl in 1:length(splPredNames))
{
if (is.null(data)) XsplPreds <- cbind(XsplPreds,get(splPredNames[jSpl],pos=1))
if (!is.null(data)) XsplPreds <- cbind(XsplPreds,data[,splPredNames[jSpl]])
}
XsplPreds <- as.matrix(XsplPreds)
}
if (length(splPredNames)==0) XsplPreds <- NULL
if (preTransfData)
{
XlinPredsOrig <- XlinPreds
XsplPredsOrig <- XsplPreds
if (numLinCompons>0)
for (jLin in 1:numLinCompons)
{
minCurr <- min(XlinPreds[,jLin]) ; maxCurr <- max(XlinPreds[,jLin])
XlinPreds[,jLin] <- (XlinPreds[,jLin] - minCurr)/(maxCurr - minCurr)
}
if (numSplCompons>0)
for (jSpl in 1:numSplCompons)
{
minCurr <- min(XsplPreds[,jSpl]) ; maxCurr <- max(XsplPreds[,jSpl])
XsplPreds[,jSpl] <- (XsplPreds[,jSpl] - minCurr)/(maxCurr - minCurr)
}
}
if (!is.null(numBasis))
{
if (length(numBasis)==1) numBasis <- rep(numBasis,numSplCompons)
if (length(numBasis)!=numSplCompons)
stop("The length of numSplCompons must match the number of smooth functions.\n")
}
if (is.null(numBasis))
{
numBasis <- rep(NA,numSplCompons)
for (jSpl in 1:numSplCompons)
numBasis[jSpl] <- min(25,round(length(unique(XsplPreds[,jSpl]))/4))
}
if (!is.null(random))
{
idnumPresent <- TRUE
if (is.list(random))
{
r.names <- names(random)
idnumName <- c(unlist(lapply(random,function(x) all.vars(formula(x)))),r.names)
if (is.null(data)) idnumOrig <- get(idnumName,pos=1)
if (!is.null(data)) idnumOrig <- data[,idnumName]
}
else
idnumOrig <- NULL
idnum <- match(idnumOrig,unique(idnumOrig))
numGps <- length(unique(idnum))
}
else
{
idnum <- NULL
idnumPresent <- FALSE
}
X <- cbind(1,XlinPreds,XsplPreds)
blockInds <- list(1:ncol(X))
blkIndStt <- ncol(X) + 1
if (numSplCompons == 0)
Zspl <- NULL
if (numSplCompons == 0)
{
range.x.list <- NULL
intKnots.list <- NULL
ncZspl <- NULL
}
if (numSplCompons > 0)
{
range.x.list <- vector("list",numSplCompons)
intKnots.list <- vector("list",numSplCompons)
ncZspl <- NULL ; Zspl <- NULL
for (jSpl in 1:numSplCompons)
{
xCurr <- XsplPreds[,jSpl]
range.xVal <- c(min(xCurr),max(xCurr))
numIntKnotsVal <- numBasis[jSpl] - 2
intKnots <- as.numeric(quantile(unique(xCurr),seq(0,1,length=numIntKnotsVal+2)
[-c(1,numIntKnotsVal+2)]))
Zcurr <- ZOSull(xCurr,intKnots=intKnots,range.x=range.xVal)
range.x.list[[jSpl]] <- attr(Zcurr,"range.x")
intKnots.list[[jSpl]] <- attr(Zcurr,"intKnots")
ncZspl <- c(ncZspl,ncol(Zcurr))
Zspl <- cbind(Zspl,Zcurr)
blkIndEnd <- blkIndStt + ncol(Zcurr) - 1
blockInds <- c(blockInds,list(blkIndStt:blkIndEnd))
blkIndStt <- blkIndEnd + 1
}
}
if (idnumPresent)
blockInds <- c(blockInds,list(blkIndStt:(blkIndStt+numGps-1)))
Cspl <- cbind(X,Zspl)
CsplTy <- as.numeric(crossprod(Cspl,y))
lenbki <- length(blockInds)
lenssq <- lenbki - 1
Ahyp <- rep(sdPriorScale,lenssq)
ssqbeta <- fixedEffPriorVar
sttEntry <- function(x) return(x[1])
endEntry <- function(x) return(x[length(x)])
ibkstt <- unlist(lapply(blockInds,sttEntry))
ibkend <- unlist(lapply(blockInds,endEntry))
nMCMC <- nBurn + nKept
numObs <- length(y)
ncCspl <- ncol(Cspl)
idPres <- idnumPresent
if (idPres==0)
{
idnum <- 1 ; numGps <- 1
nVec <- 1 ; lennu <- ncCspl
idStt <- 1 ; idEnd <- 1
}
if (idPres==1)
{
numGps <- length(unique(idnum))
nVec <- as.numeric(table(idnum))
lennu <- ncCspl + numGps
idEnd <- c((1:numObs)[diff(idnum)==1],numObs)
idStt <- idEnd - nVec + 1
}
xnu <- matrix(0,lennu,nMCMC)
sigsq <- matrix(1,lenssq,nMCMC)
xnucur <- rep(0,lennu)
lnumn1 <- lennu - 1
if (family=="binomial") ifam <- 1
if (family=="poisson") ifam <- 2
gparm <- rep(0,2)
xncnoj <- rep(0,lnumn1)
buSpl <- rep(0,ncCspl)
idxSpl <- rep(0,ncCspl)
betauO <- rep(0,lennu)
uSbj <- rep(0,numGps)
uSbjO <- rep(0,numGps)
idxSbj <- rep(0,numGps)
aux <- matrix(1,lenssq,nMCMC)
ssqnu <- c(rep(ssqbeta,ncol(X)),rep(1,lennu-ncol(X)))
cat("\n")
cat("=====================\n")
cat("Welcome to gammSlice.\n")
cat("=====================\n\n")
cat("Rudimentary progress reports available from\n")
cat("inside the Fortran 77 'engine room' according\n")
cat("to the control parameter 'msgCode'.\n\n")
if (msgCode==0)
cat("Currently msgCode = 0 leading to no reporting.\n")
if (msgCode==1)
{
cat("Currently msgCode = 1 (the default) leading to\n")
cat("reporting for percentages 1,2,...,10\n")
cat("and then for percentages 20,30,...,100.\n")
Sys.sleep(3)
}
if (msgCode==2)
{
cat("Currently msgCode = 2 leading to reporting\n")
cat("for percentages 1,2,...,100.\n")
Sys.sleep(3)
}
if (msgCode==3)
{
cat("Currently msgCode = 3 leading to reporting\n")
cat("for percentages 10,20,...,100.\n")
Sys.sleep(3)
}
cat("\n")
F77obj <- .Fortran("gslcmc",as.double(y),as.double(Cspl),as.double(CsplTy),
as.double(Ahyp),as.integer(ibkstt),as.integer(ibkend),
as.integer(nMCMC),as.integer(numObs),as.integer(ncCspl),
as.integer(idPres),as.integer(idnum),as.integer(numGps),
as.integer(idStt),as.integer(idEnd),as.integer(nVec),
xnu=as.double(xnu),sigsq=as.double(sigsq),as.double(xnucur),
as.integer(lennu),as.integer(lenbki),as.integer(lenssq),
as.integer(lnumn1),as.integer(ifam),as.double(gparm),
as.double(xncnoj),as.double(buSpl),as.double(betauO),
as.integer(idxSpl),as.double(uSbj),as.double(uSbjO),
as.integer(idxSbj),as.double(aux),as.double(ssqnu),
as.integer(msgCode))
cat("\n")
nuMCMC <- matrix(F77obj$xnu,lennu,nMCMC)
sigsqMCMC <- matrix(F77obj$sigsq,lenssq,nMCMC)
nuMCMC <- nuMCMC[,-(1:nBurn)]
sigsqMCMC <- sigsqMCMC[,-(1:nBurn)]
if (is.vector(sigsqMCMC)) sigsqMCMC <- t(as.matrix(sigsqMCMC))
nKept <- ncol(nuMCMC) ; nKeptPostThin <- floor(nKept/nThin)
indsFromThinning <- 1 + nThin*(0:nKeptPostThin)
if (max(indsFromThinning)>nKept)
indsFromThinning <- indsFromThinning[-length(indsFromThinning)]
nuMCMC <- nuMCMC[,indsFromThinning]
sigsqMCMC <- sigsqMCMC[,indsFromThinning]
if (is.vector(sigsqMCMC)) sigsqMCMC <- t(as.matrix(sigsqMCMC))
nuOut <- t(nuMCMC)
sigmaSquaredOut <- t(sigsqMCMC)
betaOut <- NULL
if (numLinCompons>0)
{
betaOut <- nuOut[,2:(1+numLinCompons)]
if (is.vector(betaOut)) betaOut <- t(as.matrix(betaOut))
if (nrow(betaOut)==1) betaOut <- t(betaOut)
}
if (!idnumPresent)
{
if (numSplCompons==0) modelType <- "linOnly"
if ((numLinCompons==0)&(numSplCompons>0)) modelType <- "pureAdd"
if ((numLinCompons>0)&(numSplCompons>0)) modelType <- "linAdd"
}
if (idnumPresent)
{
if (numSplCompons==0) modelType <- "linOnlyMix"
if ((numLinCompons==0)&(numSplCompons>0)) modelType <- "pureAddMix"
if ((numLinCompons>0)&(numSplCompons>0)) modelType <- "linAddMix"
}
if (preTransfData)
{
XlinPreds <- XlinPredsOrig
XsplPreds <- XsplPredsOrig
}
outObj <- list(nu=nuOut,beta=betaOut,sigmaSquared=sigmaSquaredOut,
y=y,XlinPreds=XlinPreds,linPredNames=linPredNames,
XsplPreds=XsplPreds,splPredNames=splPredNames,Zspl=Zspl,ncZspl=ncZspl,
range.x.list=range.x.list,intKnots.list=intKnots.list,family=family,
modelType=modelType,preTransfData=preTransfData)
class(outObj) <- "gSlc"
return(outObj)
} |
model.data = function (lmobj, lhs = FALSE) {
fcall = lmobj$call
m = match(c("formula", "data", "subset", "weights"), names(fcall), 0L)
fcall = fcall[c(1L, m)]
fcall[[1L]] = as.name("model.frame")
trms = terms(lmobj)
if (!lhs)
trms = delete.response(trms)
vars = all.vars(trms)
if(!is.null(dat <- lmobj$data))
dat[, vars, drop = FALSE]
else {
form = reformulate(vars)
fcall$formula = update(trms, form)
env = environment(trms)
if (is.null(env))
env = parent.frame()
eval(fcall, env, parent.frame())
}
}
contour.lm = function(x, form, at, bounds, zlim,
xlabs, hook, plot.it=TRUE, atpos = 1, decode=TRUE,
image=FALSE, img.col=terrain.colors(50), ...)
{
if (!missing(at)) {
if (is.null(names(at)))
stop("'at' must be a NAMED list of values used for surface slices")
}
if (!missing(bounds)) {
if (is.null(names(bounds)))
stop("'bounds' must be a NAMED list of bounds for each variable")
}
.decode.value = function(cname, cval) {
if (decode && !is.null(forms)) {
if (is.null(form <- forms[[cname]]))
cval
else {
inf = .parse.coding(forms[[cname]])
inf$const[1] + cval * inf$const[2]
}
}
else
cval
}
lmobj = x
data = model.data(lmobj)
if(inherits(form,"formula")) {
if (length(form)==2) {
vars = all.vars(form[[2]])
n = length(vars)
if (n < 2) stop("Need at least two variables")
form = list()
elt = 1
for (i in 1:(n-1))
for (j in (i+1):n) {
form[[elt]] = formula(paste(vars[j],vars[i],sep="~"))
elt = elt + 1
}
}
else {
yvars = all.vars(form[[2]])
xvars = all.vars(form[[3]])
form = list()
elt = 1
for (i in 1:length(xvars))
for (j in 1:length(yvars)) {
form[[elt]] = formula(paste(yvars[j],xvars[i],sep="~"))
elt = elt + 1
}
}
}
vars = sort(unique(as.character(sapply(form, all.vars))))
dots = list(...)
if (!is.null(dots$ylab))
message("'ylab' ignored. Specify axis labels using 'xlabs'")
if(!missing(xlabs) && length(xlabs) < length(vars))
stop("'xlabs' does not contain enough labels" )
forms = NULL
if (inherits(lmobj, "rsm")) {
forms = codings(lmobj)
if (missing(xlabs) && !is.null(forms)) {
if(!decode)
xlabs = sapply(vars, function(v)
paste(as.character(forms[[v]][2:3]), collapse=" = "))
else {
xlabs = sapply(vars, function(v) all.vars(forms[[v]][[3]])[1])
}
}
else if (missing(xlabs))
xlabs = vars
}
else if (missing(xlabs))
xlabs = vars
tmp = lapply(data, function(var) {
if (is.factor(var)) factor(levels(var))
else mean(var)
})
orig.atnm = NULL
if (!missing(at)) {
orig.atnm = names(at)
for (nm in orig.atnm) {
numflag = is.numeric(tmp[[nm]])
if (numflag) tmp[[nm]] = as.numeric(at[[nm]])
else tmp[[nm]] = at[[nm]]
}
}
at = tmp
tmp = lapply(data, function(x) if (is.numeric(x)) range(x))
if (!missing(bounds))
for (nm in names(bounds))
if (length(bounds[[nm]]) > 1)
tmp[[nm]] = bounds[[nm]]
bounds = lapply(tmp, function(x) {
if (length(x) == 2) seq(x[1], x[2], length=26)
else if (length(x) == 3) seq(x[1], x[2], length=x[3])
else x
})
isnum = sapply(at, is.numeric)
allnum = names(at)[isnum]
plot.data = list()
lbls = rep("", length(form))
z.rng = NULL
for (i in 1:length(form)) {
AT = at
v = all.vars(form[[i]])
bad = which(!(v %in% names(data)))
if (length(bad) > 0)
stop("Unknown variable(s) encountered in 'form': ",
paste(v[bad], collapse = ", "), call. = FALSE)
if (length(unique(v)) == 1) next
y = AT[[v[1]]] = bounds[[v[1]]]
x = AT[[v[2]]] = bounds[[v[2]]]
newdata = do.call(expand.grid, AT)
ord = order(newdata[[v[1]]], newdata[[v[2]]])
newdata = newdata[ord, ]
z = predict (lmobj, newdata = newdata)
rep = length(z) / length(x) / length(y)
if (rep > 1)
z = apply(matrix(z, nrow=rep), 2, mean)
z.rng = range (c (z.rng, z))
if (!missing(zlim)) {
z[z > zlim[2]] = NA
z[z < zlim[1]] = NA
}
vnames = c(x=v[2], y=v[1])
labs = c(xlabs[sapply(vnames, charmatch, vars)], vnames, "")
lbls[i] = paste(labs[3], labs[4], sep=" ~ ")
if (atpos != 0) {
atidx = setdiff(allnum, vnames)
if (length(atidx) > 0) {
atlabs = NULL
if (length(atidx) > 0) {
atvals = round(sapply(atidx, function(v) .decode.value(v, at[[v]])), 2)
if (decode && !is.null(forms)) {
dclabs = sapply(atidx, function(x) {
f = forms[[x]]
if (is.null(f)) x
else {
info = .parse.coding(f)
info[[1]][2]
}
})
atlabs = paste(dclabs, atvals, sep=" = ")
}
else
atlabs = paste(atidx, atvals, sep = " = ")
}
facidx = setdiff(orig.atnm, atidx)
faclabs = paste(facidx, unlist(at[facidx]), sep = " = ")
atlabs = c(atlabs, faclabs)
atlabs = paste(atlabs, collapse = ", ")
labs[5] = paste("Slice at", atlabs)
if (atpos < 3)
labs[atpos] = paste(labs[atpos], "\n", labs[5], sep = "")
}
}
y = .decode.value(v[1], y)
x = .decode.value(v[2], x)
plot.data[[i]] = list(x=x, y=y,
z=matrix(z, nrow=length(x)), labs=labs)
}
names(plot.data) = lbls
if (missing (zlim)) zlim = z.rng
for (i in 1:length(lbls))
plot.data[[i]]$zlim = zlim
if (plot.it) for (i in 1:length(form)) {
dat = plot.data[[i]]
if (!missing(hook))
if (!is.null(hook$pre.plot)) hook$pre.plot(dat$labs)
args = list(x=dat$x, y=dat$y, z=dat$z, col=img.col, zlim = dat$zlim, ...)
args$xlab = dat$labs[1]
args$ylab = dat$labs[2]
if (image) {
do.call("image", args)
args$add = TRUE
args$xlab = args$ylab = args$col = NULL
do.call("contour", args)
}
else {
args$col = NULL
do.call("contour", args)
if (atpos == 3)
title(sub = labs[5])
}
if (!missing(hook))
if (!is.null(hook$post.plot)) hook$post.plot(dat$labs)
}
invisible(plot.data)
}
image.lm = function(x, form, at, bounds, zlim, xlabs, hook, atpos=1, decode=TRUE, ...) {
plot.data = contour.lm(x, form, at, bounds, zlim, xlabs, atpos=atpos, decode=decode, plot.it=FALSE)
for (i in 1:length(plot.data)) {
dat = plot.data[[i]]
if (!missing(hook))
if (!is.null(hook$pre.plot)) hook$pre.plot(dat$labs)
image(dat$x, dat$y, dat$z,
xlab = dat$labs[1], ylab = dat$labs[2], zlim = dat$zlim, ...)
if (atpos == 3)
title(sub = dat$labs[5])
if (!missing(hook))
if (!is.null(hook$post.plot)) hook$post.plot(dat$labs)
}
invisible(plot.data)
}
persp.lm = function(x, form, at, bounds, zlim, zlab,
xlabs, col = "white", contours=NULL, hook, atpos=3, decode = TRUE,
theta = -25, phi = 20, r = 4, border = NULL, box = TRUE,
ticktype = "detailed", ...)
{
draw.cont.line = function(line) {
if (cont.varycol) {
cont.col = col
if (length(col) > 1) cont.col = col[cut(c(line$level, dat$zlim), length(col))][1]
}
lines(trans3d(line$x, line$y, cont.z, transf),
col=cont.col, lwd=cont.lwd)
}
plot.data = contour.lm(x, form, at, bounds, zlim, xlabs, atpos=atpos, plot.it=FALSE)
transf = list()
if (missing(zlab)) zlab = ""
facet.col = col
cont = !is.null(contours)
if (mode(contours) == "logical") cont = contours
cont.first = cont
cont.z = cz = plot.data[[1]]$zlim[1]
cont.col = 1
cont.varycol = FALSE
cont.lwd = 1
if (is.character(contours)) {
idx = charmatch(contours, c("top","bottom", "colors"), 0)
if (idx == 1) {
cont.first = FALSE
cont.z = plot.data[[1]]$zlim[2]
}
else if (idx == 2) {}
else if (idx == 3) {
cont.varycol = TRUE
if (length(col) < 2) col = rainbow(40)
}
else
cont.col = contours
}
else if (is.list(contours)) {
if(!is.null(contours$z)) cz = contours$z
if (is.numeric(cz)) cont.z = cz
else if (cz=="top") {
cont.first = FALSE
cont.z = plot.data[[1]]$zlim[2]
}
if(!is.null(contours$col)) cont.col = contours$col
if(!is.null(contours$lwd)) cont.lwd = contours$lwd
if(charmatch(cont.col, "colors", 0) == 1) {
cont.varycol = TRUE
if (length(col) < 2) col = rainbow(40)
}
}
for (i in 1:length(plot.data)) {
dat = plot.data[[i]]
cont.lines = NULL
if (!missing(hook))
if (!is.null(hook$pre.plot)) hook$pre.plot(dat$labs)
if (cont) cont.lines = contourLines(dat$x, dat$y, dat$z)
if (cont && cont.first) {
transf = persp(dat$x, dat$y, dat$z, zlim=dat$zlim, theta=theta, phi=phi, r=r, col = NA, border=NA, box=FALSE, ...)
lapply(cont.lines, draw.cont.line)
par(new=TRUE)
}
if (length(col) > 1) {
nrz = nrow(dat$z)
ncz = ncol(dat$z)
zfacet = dat$z[-1,-1] + dat$z[-1,-ncz] + dat$z[-nrz,-1] + dat$z[-nrz,-ncz]
zfacet = c(zfacet/4, dat$zlim)
facet.col = cut(zfacet, length(col))
facet.col = col[facet.col]
}
transf = persp(dat$x, dat$y, dat$z,
xlab=dat$labs[1], ylab=dat$labs[2], zlab=zlab,
zlim=dat$zlim, col=facet.col, border=border, box=box, theta=theta, phi=phi, r=r, ticktype=ticktype, ...)
if (atpos == 3)
title(sub = dat$labs[5], ...)
if (cont && !cont.first)
lapply(cont.lines, draw.cont.line)
if (!missing(hook))
if (!is.null(hook$post.plot)) hook$post.plot(dat$labs)
plot.data[[i]]$transf = transf
}
invisible(plot.data)
} |
optim.step1.2 <-
function(dat, coef, random.eff){
lam=dat$lam
lam0=which(lam==0)
lam1=which(lam==1)
n.lam0=length(lam0)
n.lam1=length(lam1)
dfs=dat$dfs
n.coef=length(coef)
A=coef[1]
B=coef[2]
beta=coef[3:(n.coef-4)]
ss0=coef[n.coef-3]
ss1=coef[n.coef-2]
rho=coef[n.coef-1]
sigma=coef[n.coef]
b=random.eff[, 1]
d=random.eff[, 2]
optimdat=dat$dat
dimdat=dim(optimdat)
nn=dimdat[1]
ids=unique(optimdat[,1])
mm=length(ids)
D=as.matrix(optimdat[,4:(sum(dfs)+4)])
Z=matrix(0, nrow=nn, ncol=mm)
for(i in 1:mm){
id.x=(optimdat[,1]==ids[i])
ni=sum(id.x)
t1=rep(1, ni)
Z[id.x,i]=t1
}
Sigma=matrix(c(ss0^2,rho*ss0*ss1,rho*ss0*ss1,ss1^2),2,2)/(sigma^2)
Gi=solve(t(chol(Sigma)))
G=kronecker(diag(mm), Gi)
delta=0.1
w=rep(0, 2*mm)
while(delta>0.00001) {
DDt=D%*%as.matrix(beta)
f0.1=-as.matrix(A*exp(Z%*%b))/(1+exp(-log(DDt)/(B*exp(Z%*%d))))
GG=c(seq(1, mm, 1)*2-1)
GG2=c(seq(1, mm, 1)*2)
w[GG]=b
w[GG2]=d
f0.2=G%*%w
f0=as.matrix(rbind(f0.1, f0.2))
y=as.matrix(rbind(as.matrix(optimdat[,3]), as.matrix(rep(0, 2*mm))))
nn.new=dim(y)[1]
f0.A.1=-as.matrix(exp(Z%*%b))/(1+exp(-log(DDt)/(B*exp(Z%*%d))))
f0.A=as.matrix(rbind(f0.A.1, as.matrix(rep(0, 2*mm))))
f0.B.1=-f0.1*(1+exp(-log(DDt)/(B*exp(Z%*%d))))^(-1)*exp(-log(DDt)/(B*exp(Z%*%d)))*(log(DDt)/exp(Z%*%d))*B^(-2)
f0.B=as.matrix(rbind(f0.B.1, as.matrix(rep(0, 2*mm))))
f0.beta.miss=f0.1*(1+exp(-log(DDt)/(B*exp(Z%*%d))))^(-1)*exp(-log(DDt)/(B*exp(Z%*%d)))*((DDt)*(B*exp(Z%*%d)))^(-1)
applyftn1=function(x){x*f0.beta.miss}
f0.beta.1=apply(D, 2, applyftn1)
f0.beta.2=matrix(0, nrow=2*mm, ncol=(dim(D)[2]-n.lam0))
f0.beta.0=as.matrix(f0.beta.1[,lam0])
f0.beta.c=f0.beta.1[,lam1]
f0.beta.0=rbind(f0.beta.0, matrix(0, nrow=2*mm, ncol=n.lam0))
f0.beta.c=rbind(f0.beta.c, f0.beta.2)
applyftn2=function(x){x*f0.1}
f0.b.1=apply(Z, 2, applyftn2)
f0.b.2=G[,GG]
f0.b=rbind(f0.b.1, f0.b.2)
f0.d.1=f0.1*(1+exp(-log(DDt)/(B*exp(Z%*%d))))^(-1)*exp(-log(DDt)/(B*exp(Z%*%d)))*(log(DDt)/(B*exp(Z%*%d)))
applyftn3=function(x){x*f0.d.1}
f0.d.1=apply(-Z, 2, applyftn3)
f0.d.2=G[,GG2]
f0.d=rbind(f0.d.1, f0.d.2)
y.new=y-f0+f0.beta.c%*%beta[lam1]
X1=cbind(f0.A, f0.B, f0.beta.0, f0.b, f0.d)
X2=f0.beta.c
I=diag(nn.new)
beta.new=cls(y.new, (I-Px(X1))%*%X2)
y.part.hat=X2%*%beta.new$betahat
y.part1.hat=y.new-y.part.hat
increment=as.numeric(solve(t(X1)%*%X1)%*%t(X1)%*%y.part1.hat)
A=increment[1]+A
B=increment[2]+B
temp=beta
if(n.lam0!=0){
beta[lam0]=increment[3:(2+n.lam0)]+beta[lam0]
}
beta[lam1]=beta.new$betahat
b=b+increment[(3+n.lam0):(length(increment)-mm)]
d=d+increment[(length(increment)-mm+1):length(increment)]
diff.beta=abs(temp-beta)
delta=max(abs(increment), diff.beta)
}
y.hat=-as.matrix(A*exp(Z%*%b))/(1+exp(-log(D%*%beta)/(B*exp(Z%*%d))))
Zhat=matrix(0, nrow=nn, ncol=2*mm)
applyftn2=function(x){x*y.hat}
Zhat[,GG]=apply(Z, 2, applyftn2)
f0.d.1=y.hat*(1+exp(-log(D%*%beta)/(B*exp(Z%*%d))))^(-1)*exp(-log(D%*%beta)/(B*exp(Z%*%d)))*(log(D%*%beta)/(B*exp(Z%*%d)))
applyftn3=function(x){x*f0.d.1}
Zhat[,GG2]=apply(-Z, 2, applyftn3)
time=optimdat[,2]
ww=optimdat[,3]-y.hat
Dt=round(log(D%*%beta), 8)
colnames(Dt)="Dt"
id=as.matrix(Z%*%c(1:mm))
colnames(id)="id"
DAMAGE_Y=as.matrix(optimdat[,3])
res.dat=cbind(id=id, TIME=optimdat[,2], Dt=Dt , DAMAGE_Y=DAMAGE_Y)
colnames(res.dat)=c("id", "TIME", "Dt", "DAMAGE_Y")
newdata=as.data.frame(res.dat)
random.eff=cbind(b, d)
coef=c(A, B, beta, ss0, ss1, rho, sigma)
res=list(coef=coef, random.eff=random.eff, yhat=y.hat, Zhat=Zhat, time=time, residual=ww, dat=dat, newdata=newdata)
return(res)
} |
findintercorr_cont_pois <- function(method, constants, rho_cont_pois, lam,
nrand = 100000, seed = 1234) {
Sigma_cont_pois <- matrix(1, nrow = nrow(rho_cont_pois),
ncol = ncol(rho_cont_pois))
for (i in 1:nrow(rho_cont_pois)) {
for (j in 1:ncol(rho_cont_pois)) {
Sigma_cont_pois[i, j] <-
rho_cont_pois[i, j]/(chat_pois(lam[j], n_unif = nrand, seed = seed) *
power_norm_corr(constants[i, ], method))
}
}
return(Sigma_cont_pois)
} |
"oo_maya_lamps" |
knitr::opts_chunk$set(echo = TRUE,comment = "
fig.height = 4,fig.align = "center",
eval = TRUE)
library(MASS)
library(kableExtra)
generate_data = function(n, p, V, Utrue, err_sd=0.01, pi=NULL){
if (is.null(pi)) {
pi = rep(1, length(Utrue))
}
assertthat::are_equal(length(pi), length(Utrue))
for (j in 1:length(Utrue)) {
assertthat::are_equal(dim(Utrue[j]), c(p, p))
}
pi <- pi / sum(pi)
which_U <- sample(1:length(pi), n, replace=TRUE, prob=pi)
Beta = matrix(0, nrow=n, ncol=p)
for(i in 1:n){
Beta[i,] = mvrnorm(1, rep(0, p), Utrue[[which_U[i]]])
}
Shat = matrix(err_sd, nrow=n, ncol=p, byrow = TRUE)
E = mvrnorm(n, rep(0, p), Shat[1,]^2 * V)
Bhat = Beta + E
return(list(B = Beta, Bhat=Bhat, Shat = Shat, whichU = which_U))
}
set.seed(1)
n = 2000
R = 5
V = diag(R)
U0 = matrix(0, R, R)
U1 = matrix(1, R, R)
U2 = U0; U2[1:2,1:2] = 4
U3 = U0; U3[5,5] = 4
simdata = generate_data(n, R, V, list(U0=U0, U1=U1, U2=U2, U3 = U3), err_sd = 1)
library(mashr)
data = mash_set_data(simdata$Bhat, simdata$Shat)
data.L = mash_update_data(data, ref = 'mean')
U.c = cov_canonical(data.L)
m.1by1 = mash_1by1(data.L)
strong = get_significant_results(m.1by1)
U.pca = cov_pca(data.L,2,subset=strong)
U.ed = cov_ed(data.L, U.pca, subset=strong)
m = mash(data.L, c(U.c,U.ed), algorithm.version = 'R')
print(get_loglik(m),digits=10)
length(get_significant_results(m))
null.ind = which(simdata$whichU %in% c(1,2)) |
sirt_add_increment <- function(x, pos, value)
{
y <- x
y[pos] <- x[pos] + value
return(y)
} |
enerscape <- function(
dem,
m,
unit = "joule",
neigh = 16,
method = "ARC",
v = NULL
) {
if (is.null(dem) | is.null(m)) {
stop("Missing mandatory input - see ?enerscape::enerscape for details")
}
if (class(dem) != "RasterLayer") {
stop("Digital elevation model must be a RaterLayer")
}
if (!unit %in% c("joule", "kcal")) {
stop("unit must be one of 'joule' or 'kcal'")
}
work_in_kcal <- ifelse(unit == "kcal", TRUE, FALSE)
en_res <- raster::res(dem)[1]
message(" - Raster cells are assumed to have same horizontal and vertical",
" resolution and with planar coordinate reference system (e.g. UTM)")
message(" | Calculating slope")
height <- suppressWarnings(
gdistance::transition(dem,
function(x) {
x[2] - x[1]
},
directions = neigh,
symm = FALSE)
)
slope <- gdistance::geoCorrection(height, scl = FALSE)
slope <- atan(slope) * 180 / pi
adj <- raster::adjacent(dem,
1:(raster::ncell(dem)),
pairs = TRUE,
directions = neigh)
message(" | Calculating work")
work <- slope
if (method == "ARC") {
work[adj] <- .calc_arc(slope[adj], m, work_in_kcal)
} else if (method == "cycling") {
if (is.null(v)) {
stop("Argument v must be specified")
} else {
v <- v / 3.6
}
work[adj] <- .calc_cycling(height[adj], slope[adj], m, v, work_in_kcal)
zeros <- Matrix::which(work@transitionMatrix < 0, arr.ind = TRUE)
rw <- zeros[, 1]
cl <- zeros[, 2]
work@transitionMatrix[rw, cl] <- 0
} else {
stop("Argument method must be 'ARC' or 'cycling'")
}
message(" | Calculating conductance (1 / work)")
cond <- slope
if (method == "ARC") {
cond[adj] <- .calc_arc_cond(slope[adj], m, work_in_kcal)
} else if (method == "cycling") {
cond[adj] <- .calc_cycling_cond(height[adj], slope[adj], m, v, work_in_kcal)
zeros <- Matrix::which(cond@transitionMatrix < 0, arr.ind = TRUE)
rw <- zeros[, 1]
cl <- zeros[, 2]
val <- max(cond@transitionMatrix) * 10
} else {
stop("Argument method must be 'ARC' or 'cycling'")
}
s <- gdistance::raster(slope, "colSums") / neigh
w <- gdistance::raster(work, "colSums") / neigh
if (method == "cycling") {
w[w < 0] <- 0
}
con <- gdistance::raster(cond, "colSums") / neigh
ans <- raster::stack(dem, s, w, con)
names(ans) <- c("DEM", "Slope", "EnergyScape", "Conductance")
ans <- list(neighbors = neigh,
mass = m,
rasters = ans,
cond_tr = cond)
class(ans) <- "enerscape"
message(" - Do not use slope with negative values for distance calculations")
return(ans)
} |
require(xts)
require(PerformanceAnalytics)
require(gdata)
require(FinancialInstrument)
require(quantmod)
currency("USD")
filesroot = "~/Data/MSCI"
if (!file.exists(filesroot))
dir.create(filesroot, mode="0777")
if (!file.exists(paste(filesroot, "/.incoming", sep="")))
dir.create(paste(filesroot, "/.incoming", sep=""), mode="0777")
setwd(paste(filesroot, "/.incoming", sep=""))
if(!file.exists("historyIndex.xls"))
stop(paste("No spreadsheet exists. Download the spreadsheet to be processed from http://www.msci.com into ", filesroot, "/.incoming", sep=""))
x = read.xls("historyIndex.xls", pattern="Date")
x = x[-((dim(x)[1]-15):dim(x)[1]),]
x.dates = paste(substring(x[,1],1,6),substring(x[,1],7,10))
ISOdates = as.Date(x.dates, format="%b %d %Y")
symbolNames = colnames(x[,-1])
description = paste("MSCI", gsub(pattern = "\\.", replacement = " ", symbolNames))
description = gsub(pattern = " ", replacement = " ", description)
symbolNames = gsub(pattern = ".Standard.*", replacement = "", symbolNames)
symbolNames = paste("MSCI.", symbolNames, ".M.IDX", sep="")
symbolNames = gsub(pattern = "\\.\\.", replacement = "\\.", symbolNames)
for(i in 1:length(symbolNames)) {
dir.create(paste(filesroot, symbolNames[i], sep="/"), showWarnings = FALSE,
recursive = FALSE, mode = "0777")
}
print("Processing columns as symbols...")
for( i in 1:length(symbolNames)){
x.xts = as.xts(as.numeric(sub(",","", x[,i+1], fixed=TRUE)), order.by=ISOdates)
R.xts = Return.calculate(x.xts)
x.xts = cbind(x.xts, R.xts)
index(x.xts) = as.Date(as.yearmon(index(x.xts)), frac=1)
colnames(x.xts)=c(paste(symbolNames[i],".Close", sep=""), paste(symbolNames[i], ".Returns", sep=""))
xtsAttributes(x.xts) <- list(Description = paste(description[i], "Index"))
save(x.xts, file=paste(filesroot, symbolNames[i], paste(symbolNames[i], ".rda", sep=""), sep="/"))
instrument(symbolNames[i], currency="USD", multiplier=1, tick_size=.01, start_date=head(index(x.xts),1), description=paste(description[i], "Index", sep=""), data="CR", source="MSCI", frequency="Monthly", assign_i=TRUE)
print(paste(symbolNames[i], description[i]))
}
setSymbolLookup.FI(base_dir=filesroot, split_method='common')
getSymbols("MSCI.WORLD.M.IDX")
getSymbols(symbolNames)
chartSeries(Cl(MSCI.WORLD.M.IDX), theme="white")
head(MSCI.WORLD.M.IDX) |
test_that("devRatePlot returns NULL",{
xx <- seq(from = 4, to = 35, by = 1)
yy <- c(0.0011177457, 0.0000000000, 0.0027744302, 0.0004460741, 0.0020882305,
0.0048659816, 0.0046385278, 0.0083962283, 0.0089383489, 0.0076518397,
0.0109503542, 0.0111564471, 0.0150364540, 0.0165235404, 0.0189938734,
0.0238332060, 0.0229612488, 0.0271481105, 0.0292819680, 0.0346557231,
0.0360398266, 0.0397014187, 0.0413783578, 0.0439369633, 0.0481031628,
0.0489109593, 0.0515116666, 0.0539285523, 0.0533571975, 0.0552395531,
0.0552867174, 0.0534671900)
testNLS <- devRateModel(eq = lamb_92, temp = xx, devRate = yy,
startValues = list(list(Rm = 0.05393, Tmax = 33.4000, To = 10.7500), list(T1 = 3.377000)))
res <- devRatePlot(
eq = lamb_92,
nlsDR = testNLS,
rangeT = 10,
optText = TRUE,
spe = TRUE)
expect_equal(
object = res,
expected = NULL
)
xx <- seq(from = 0, to = 50, by = 1)
yy <- c(0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00, 0.000000e+00,
3.243648e-03, 7.814825e-04, 5.814596e-03, 9.819378e-03, 7.814990e-03,
0.000000e+00, 5.430783e-05, 1.056332e-02, 0.000000e+00, 1.295533e-02,
0.000000e+00, 0.000000e+00, 7.823721e-03, 1.247843e-03, 5.706782e-03,
8.286514e-03, 7.482038e-03, 2.459962e-02, 5.102975e-03, 3.485625e-02,
3.060154e-02, 1.493131e-02, 2.509750e-02, 2.822221e-02, 2.497632e-02,
3.772156e-02, 3.043415e-02, 3.034768e-02, 3.756987e-02, 5.572242e-02,
5.400489e-02, 5.740899e-02, 4.994192e-02, 5.559589e-02, 5.372400e-02,
4.867726e-02, 5.998619e-02, 4.504179e-02, 2.689224e-02, 4.373311e-02,
4.414157e-02, 3.948465e-02, 3.335472e-02, 4.921421e-02, 3.708899e-02,
1.838826e-02)
testNLS <- devRateModel(eq = taylor_81, temp = xx, devRate = yy,
startValues = list(Rm = 0.0550, Tm = 37.2000, To = 8.8000))
res <- devRatePlot(
eq = taylor_81,
nlsDR = testNLS,
rangeT = 10,
optText = TRUE,
spe = TRUE)
expect_equal(
object = res,
expected = NULL
)
rawDevEggs <- matrix(c(10, 0.031, 10, 0.039, 15, 0.047, 15, 0.059, 15.5, 0.066,
13, 0.072, 16, 0.083, 16, 0.100, 17, 0.100, 20, 0.100, 20, 0.143, 25, 0.171,
25, 0.200, 30, 0.200, 30, 0.180, 35, 0.001), ncol = 2, byrow = TRUE)
testNLS <- devRateModel(eq = stinner_74, temp = rawDevEggs[,1], devRate = rawDevEggs[,2],
startValues = list(list(C = 0.1, k1 = 4, k2 = -0.2), list(Topt = 30)))
res <- devRatePlot(
eq = stinner_74,
nlsDR = testNLS,
rangeT = 10,
optText = TRUE,
spe = TRUE)
expect_equal(
object = res,
expected = NULL
)
rawDevEggs <- matrix(c(10, 0.031, 10, 0.039, 15, 0.047, 15, 0.059, 15.5, 0.066,
13, 0.072, 16, 0.083, 16, 0.100, 17, 0.100, 20, 0.100, 20, 0.143, 25, 0.171,
25, 0.200, 30, 0.200, 30, 0.180), ncol = 2, byrow = TRUE)
testNLS <- devRateModel(eq = campbell_74, temp = rawDevEggs[,1], devRate = rawDevEggs[,2],
startValues = list(aa = 0, bb = 0))
res <- devRatePlot(
eq = campbell_74,
nlsDR = testNLS,
rangeT = 10,
optText = TRUE,
spe = TRUE)
expect_equal(
object = res,
expected = NULL
)
rawDevEggs <- matrix(c(10, 0.031, 10, 0.039, 15, 0.047, 15, 0.059, 15.5, 0.066,
13, 0.072, 16, 0.083, 16, 0.100, 17, 0.100, 20, 0.100, 20, 0.143, 25, 0.171,
25, 0.200, 30, 0.200, 30, 0.180), ncol = 2, byrow = TRUE)
testNLS <- devRateModel(eq = davidson_44, temp = rawDevEggs[,1], devRate = rawDevEggs[,2],
startValues = list(aa = 5, bb = -0.2, K = 0.3))
res <- devRatePlot(
eq = davidson_44,
nlsDR = testNLS,
rangeT = 10,
optText = TRUE,
spe = TRUE)
expect_equal(
object = res,
expected = NULL
)
rawDevEggs <- matrix(c(10, 0.031, 10, 0.039, 15, 0.047, 15, 0.059, 15.5, 0.066,
13, 0.072, 16, 0.083, 16, 0.100, 17, 0.100, 20, 0.100, 20, 0.143, 25, 0.171,
25, 0.200, 30, 0.200, 30, 0.180, 35, 0.001), ncol = 2, byrow = TRUE)
testNLS <- devRateModel(eq = janisch_32, temp = rawDevEggs[,1], devRate = rawDevEggs[,2],
startValues = list(Dmin = 5, Topt = 30, aa = 0.2, bb = 0.1))
res <- devRatePlot(
eq = janisch_32,
nlsDR = testNLS,
rangeT = 10,
optText = TRUE,
spe = TRUE)
expect_equal(
object = res,
expected = NULL
)
xx <- seq(from = 0, to = 33, by = 1)
yy <- c(0.0005252046, 0.0002251286, 0.0006460717, 0.0017880213, 0.0015611891,
0.0012853886, 0.0010841702, 0.0000000000, 0.0029119885, 0.0051535582,
0.0049455628, 0.0049839564, 0.0042565719, 0.0075039314, 0.0073359365,
0.0069161169, 0.0104414407, 0.0109888804, 0.0121261595, 0.0153213235,
0.0147817972, 0.0193366467, 0.0202140539, 0.0221893465, 0.0260741628,
0.0275310077, 0.0298545694, 0.0317042536, 0.0332244901, 0.0302047526,
0.0292701892, 0.0267738132, 0.0155003324, 0.0011891955)
testNLS <- devRateModel(eq = logan6_76, temp = xx, devRate = yy,
startValues = list(phi = 0.000800, bb = 0.169, Tmax = 33.003, deltaT = 3.895))
res <- devRatePlot(
eq = logan6_76,
nlsDR = testNLS,
rangeT = 10,
optText = TRUE,
spe = TRUE)
expect_equal(
object = res,
expected = NULL
)
xx <- seq(from = 0, to = 33, by = 1)
yy <- c(0.0005252046, 0.0002251286, 0.0006460717, 0.0017880213, 0.0015611891,
0.0012853886, 0.0010841702, 0.0000000000, 0.0029119885, 0.0051535582,
0.0049455628, 0.0049839564, 0.0042565719, 0.0075039314, 0.0073359365,
0.0069161169, 0.0104414407, 0.0109888804, 0.0121261595, 0.0153213235,
0.0147817972, 0.0193366467, 0.0202140539, 0.0221893465, 0.0260741628,
0.0275310077, 0.0298545694, 0.0317042536, 0.0332244901, 0.0302047526,
0.0292701892, 0.0267738132, 0.0155003324, 0.0011891955)
testNLS <- devRateModel(eq = logan6_76, temp = xx, devRate = yy,
startValues = list(phi = 0.000800, bb = 0.169, Tmax = 33.003, deltaT = 3.895))
res <- devRatePlot(
eq = logan6_76,
nlsDR = testNLS,
rangeT = 10,
optText = TRUE,
spe = FALSE)
expect_equal(
object = res,
expected = NULL
)
}) |
outlierMap <- function(res, title = "Robust PCA", col = "black",
pch = 16, labelOut = TRUE, id = 3,
xlim = NULL, ylim = NULL, cex = 1,
cex.main=1.2, cex.lab=NULL, cex.axis=NULL){
if(is.null(res$sd)) { SD = res$SD } else { SD = res$sd }
if(is.null(res$cutoff.sd)) { cutoffSD = res$cutoffSD } else {
cutoffSD = res$cutoff.sd }
if(is.null(res$od)) { OD = res$OD } else { OD = res$od }
if(is.null(res$cutoff.od)) { cutoffOD = res$cutoffOD } else {
cutoffOD = res$cutoff.od }
if(is.null(SD)) stop(" No score distances are given.")
if(is.null(cutoffSD)) stop(
" No cutoff for score distances is given.")
if(is.null(OD)) stop(" No orthogonal distances are given.")
if(is.null(cutoffOD)) stop(
" No cutoff for orthogonal distances is given.")
if (is.null(xlim)) {
xlim <- c(0, max(SD) * 1.1)
}
if (is.null(ylim)) {
ylim <- c(0, max(OD) * 1.1)
}
if (is.null(pch)) {
pch <- ifelse(is.null(col), 1, 16)
}
if (is.null(col)) {
col <- "black"
}
mycex = cex
mycex.main = 1
if(!is.null(cex.main)) { mycex.main = cex.main }
mycex.lab = 1
if(!is.null(cex.lab)) { mycex.lab = cex.lab }
mycex.axis = 1
if(!is.null(cex.axis)) { mycex.axis = cex.axis }
if (is.list(col)) {
for (i in seq_len(length(col))) {
if (i == 1) {
plot(SD[col[[i]]$index], OD[col[[i]]$index],
xlab = "", ylab = "", main = "", pch = pch,
col = col[[i]]$col, xlim = xlim, ylim = ylim,
cex=mycex, cex.axis = mycex.axis)
}
points(SD[col[[i]]$index], OD[col[[i]]$index], pch = pch,
col = col[[i]]$col, cex=mycex)
}
}
else {
plot(SD, OD, xlab = "", ylab = "", main = "", pch = pch,
col = col, xlim = xlim, ylim = ylim, cex=mycex,
cex.axis = mycex.axis)
}
title(main = title, line = 1, cex.main = mycex.main)
title(ylab = "Orthogonal distance", line = 2.3, cex.lab = mycex.lab)
title(xlab = "Score distance", line = 2.3, cex.lab = mycex.lab)
abline(v = cutoffSD)
abline(h = cutoffOD)
if (labelOut) {
labelDD_cw(SD, OD, id.n.SD = id, id.n.OD = id)
}
}
labelDD_cw <- function(x,y,id.n.SD=3,id.n.OD=3,off=0.02)
{
xrange <- graphics::par("usr")
xrange <- xrange[2] - xrange[1]
if (id.n.SD > 0 && id.n.OD > 0) {
n <- length(x)
indexSD <- sort(x, index.return = TRUE)$ix
indexSD <- indexSD[(n - id.n.SD + 1):n]
indexOD <- sort(y, index.return = TRUE)$ix
indexOD <- indexOD[(n - id.n.OD + 1):n]
lab <- indexOD
if (is.character(names(y))) {
lab <- names(y[indexOD])
}
graphics::text(x[indexOD] - off * xrange, y[indexOD], lab)
lab <- indexSD
if (is.character(names(x))) {
lab <- names(x[indexSD])
}
graphics::text(x[indexSD] - off * xrange, y[indexSD], lab)
}
} |
summary.sglg <- function(object, ...) {
if (object$semi == FALSE & object$censored == FALSE) {
cat(" -------------------------------------------------------------- ")
cat("\n Semi-parametric generalized log-gamma regression model \n")
cat(" --------------------------------------------------------------\n")
cat(" Sample size: ", length(object$y_est))
cat(" Censored: ")
print(object$censored)
cat("\n ------------------------ Location model ---------------------- \n\n")
cat(" ---------- Parametric component ----------\n\n")
p <- object$p
Estimate <- object$mu
StdErr <- object$st_error[1:p]
tval <- Estimate/StdErr
p.value <- object$p.values[1:p]
table <- cbind(Estimate, StdErr, tval, p.value)
colnames(table) <- c("Estimate", "Std.Err", "z-value", "Pr(>|z|)")
rownames(table) <- colnames(object$X)
printCoefmat(table, P.values = TRUE, has.Pvalue = TRUE, digits = 5,
signif.legend = FALSE, tst.ind = c(2, 3))
cat("\n -------------------- Scale parameter -------------------- \n\n")
Estimate <- object$sigma
StdErr <- object$st_error[p + 1]
tval <- Estimate/StdErr
p.value <- object$p.values[p + 1]
table <- cbind(Estimate, StdErr, tval, p.value)
colnames(table) <- c("Estimate", "Std.Err", "z-value", "Pr(>|z|)")
rownames(table) <- colnames("sigma")
printCoefmat(table, P.values = TRUE, has.Pvalue = TRUE, digits = 5,
signif.legend = FALSE, tst.ind = c(2, 3))
cat("\n -------------------- Shape parameter -------------------- \n\n")
Estimate <- object$lambda
StdErr <- object$st_error[p + 2]
tval <- Estimate/StdErr
p.value <- object$p.values[p + 2]
table <- cbind(Estimate, StdErr, tval, p.value)
colnames(table) <- c("Estimate", "Std.Err", "z-value", "Pr(>|z|)")
rownames(table) <- colnames("lambda")
printCoefmat(table, P.values = TRUE, has.Pvalue = TRUE, digits = 5,
signif.legend = TRUE, tst.ind = c(2, 3))
cat(" ------------------------------------------------------------\n\n")
cat(" Deviance: ", round(object$deviance, digits = 2), "\n\n")
cat(" ------ Penalized Log-likelihood ------\n\n")
cat(" Log-lik: ", round(object$llglg, digits = 2), "\n\n")
cat(" ------ Information criterion ------\n\n")
cat(" AIC: ", round(object$AIC, digits = 2), "\n")
cat(" BIC: ", round(object$BIC, digits = 2), "\n\n")
cat(" --------------------------------------------------------------\n")
}
if (object$semi == FALSE & object$censored == TRUE) {
cat(" -------------------------------------------------------------- ")
cat("\n Semi-parametric generalized log-gamma regression model \n")
cat(" --------------------------------------------------------------\n")
cat(" Sample size: ", length(object$y_est))
cat(" Censored: ")
print(object$censored)
cat(" Percentage of censored observations: ")
print(object$per.censo)
cat("\n ------------------------ Location model ---------------------- \n\n")
cat(" ---------- Parametric component ----------\n\n")
p <- object$p
Estimate <- object$mu
StdErr <- object$st_error[1:p]
tval <- Estimate/StdErr
p.value <- object$p.values[1:p]
table <- cbind(Estimate, StdErr, tval, p.value)
colnames(table) <- c("Estimate", "Std.Err", "z-value", "Pr(>|z|)")
rownames(table) <- colnames(object$X)
printCoefmat(table, P.values = TRUE, has.Pvalue = TRUE, digits = 5,
signif.legend = FALSE, tst.ind = c(2, 3))
cat("\n -------------------- Scale parameter -------------------- \n\n")
Estimate <- object$sigma
StdErr <- object$st_error[p + 1]
tval <- Estimate/StdErr
p.value <- object$p.values[p + 1]
table <- cbind(Estimate, StdErr, tval, p.value)
colnames(table) <- c("Estimate", "Std.Err", "z-value", "Pr(>|z|)")
rownames(table) <- colnames("sigma")
printCoefmat(table, P.values = TRUE, has.Pvalue = TRUE, digits = 5,
signif.legend = FALSE, tst.ind = c(2, 3))
cat(" ------------------------------------------------------------\n\n")
cat(" Shape: ", round(object$lambda, digits = 2), "\n\n")
cat(" Deviance: ", round(object$deviance, digits = 2), "\n\n")
cat(" ------ Penalized Log-likelihood ------\n\n")
cat(" Log-lik: ", round(object$llglg, digits = 2), "\n\n")
cat(" ------ Information criterion ------\n\n")
cat(" AIC: ", round(object$AIC, digits = 2), "\n")
cat(" BIC: ", round(object$BIC, digits = 2), "\n\n")
cat(" --------------------------------------------------------------\n")
}
if (object$semi == TRUE & object$censored == FALSE) {
cat(" -------------------------------------------------------------- ")
cat("\n Semi-parametric generalized log-gamma regression model \n")
cat(" --------------------------------------------------------------\n")
cat(" Sample size: ", length(object$y_est))
cat(" Censored: ")
print(object$censored)
cat("\n ------------------------ Location model ---------------------- \n\n")
cat(" ---------- Parametric component ----------\n\n")
p <- object$p
Estimate <- object$mu[1:p]
StdErr <- object$st_error[1:p]
tval <- Estimate/StdErr
p.value <- object$p.values[1:p]
table <- cbind(Estimate, StdErr, tval, p.value)
colnames(table) <- c("Estimate", "Std.Err", "z-value", "Pr(>|z|)")
rownames(table) <- colnames(object$X)
printCoefmat(table, P.values = TRUE, has.Pvalue = TRUE, digits = 5,
signif.legend = FALSE, tst.ind = c(2, 3))
cat("\n ---------- Non-parametric component ----------\n\n")
Knot <- object$Knot
Smoothp <- object$alpha
d.f <- round(object$d.f.npc,4)
BasisD <- Knot
table <- cbind(Smoothp, BasisD)
cat(" Type of basis: ", as.character(object$basis),"\n\n")
cat(" Degrees of freedom: ", as.character(d.f),"\n\n")
colnames(table) <- c("Smooth parameter", "Basis dimension")
rownames(table) <- colnames(object$npc)
printCoefmat(table)
cat("\n -------------------- Scale parameter -------------------- \n\n")
Estimate <- object$sigma
Tknot <- sum(Knot)
StdErr <- object$st_error[p + Tknot + 1]
tval <- Estimate/StdErr
p.value <- object$p.values[p + Tknot + 1]
table <- cbind(Estimate, StdErr, tval, p.value)
colnames(table) <- c("Estimate", "Std.Err", "z-value", "Pr(>|z|)")
rownames(table) <- colnames("sigma")
printCoefmat(table, P.values = TRUE, has.Pvalue = TRUE, digits = 5,
signif.legend = FALSE, tst.ind = c(2, 3))
cat("\n -------------------- Shape parameter -------------------- \n\n")
Estimate <- object$lambda
StdErr <- object$st_error[p + Tknot + 2]
tval <- Estimate/StdErr
p.value <- object$p.values[p + Tknot + 2]
table <- cbind(Estimate, StdErr, tval, p.value)
colnames(table) <- c("Estimate", "Std.Err", "z-value", "Pr(>|z|)")
rownames(table) <- colnames("lambda")
printCoefmat(table, P.values = TRUE, has.Pvalue = TRUE, digits = 5,
signif.legend = TRUE, tst.ind = c(2, 3))
cat(" ------------------------------------------------------------\n\n")
cat(" Deviance: ", round(object$deviance, digits = 2), "\n\n")
cat(" ------ Penalized Log-likelihood ------\n\n")
cat(" Log-lik: ", round(object$llglg, digits = 2), "\n\n")
cat(" ------ Information criterion ------\n\n")
cat(" AIC: ", round(object$AIC, digits = 2), "\n")
cat(" BIC: ", round(object$BIC, digits = 2), "\n\n")
cat(" --------------------------------------------------------------\n")
}
if (object$semi == TRUE & object$censored == TRUE) {
cat(" -------------------------------------------------------------- ")
cat("\n Semi-parametric generalized log-gamma regression model \n")
cat(" --------------------------------------------------------------\n")
cat(" Sample size: ", length(object$y_est))
cat(" Censored: ")
print(object$censored)
cat("\n ------------------------ Location model ---------------------- \n\n")
cat(" ---------- Parametric component ----------\n\n")
p <- object$p
Estimate <- object$mu[1:p]
StdErr <- object$st_error[1:p]
tval <- Estimate/StdErr
p.value <- object$p.values[1:p]
table <- cbind(Estimate, StdErr, tval, p.value)
colnames(table) <- c("Estimate", "Std.Err", "z-value", "Pr(>|z|)")
rownames(table) <- colnames(object$X)
printCoefmat(table, P.values = TRUE, has.Pvalue = TRUE, digits = 5,
signif.legend = FALSE, tst.ind = c(2, 3))
cat(" ---------- Non-parametric component ----------\n\n")
Knot <- object$Knot
Smoothp <- object$alpha
d.f <- object$d.f.npc
BasisD <- Knot
table <- cbind(Smoothp, BasisD, d.f)
colnames(table) <- c("Smooth parameter", "Basis dimension", "d.f")
rownames(table) <- colnames(object$npc)
printCoefmat(table)
cat("\n -------------------- Scale parameter -------------------- \n\n")
Estimate <- object$sigma
Tknot <- sum(Knot)
StdErr <- object$st_error[p + Tknot + 1]
tval <- Estimate/StdErr
p.value <- object$p.values[p + Tknot + 1]
table <- cbind(Estimate, StdErr, tval, p.value)
colnames(table) <- c("Estimate", "Std.Err", "z-value", "Pr(>|z|)")
rownames(table) <- colnames("sigma")
printCoefmat(table, P.values = TRUE, has.Pvalue = TRUE, digits = 5,
signif.legend = FALSE, tst.ind = c(2, 3))
cat(" ------------------------------------------------------------\n\n")
cat(" Shape: ", round(object$lambda, digits = 2), "\n\n")
cat(" Deviance: ", round(object$deviance, digits = 2), "\n\n")
cat(" ------ Penalized Log-likelihood ------\n\n")
cat(" Log-lik: ", round(object$llglg, digits = 2), "\n\n")
cat(" ------ Information criterion ------\n\n")
cat(" AIC: ", round(object$AIC, digits = 2), "\n")
cat(" BIC: ", round(object$BIC, digits = 2), "\n\n")
cat(" --------------------------------------------------------------\n")
}
} |
docx_reference_img <- function( x, src){
x <- part_reference_img(x, src, "doc_obj")
x
}
part_reference_img <- function( x, src, part){
src <- unique( src )
x[[part]]$relationship()$add_img(src, root_target = "media")
img_path <- file.path(x$package_dir, "word", "media")
dir.create(img_path, recursive = TRUE, showWarnings = FALSE)
file.copy(from = src, to = file.path(x$package_dir, "word", "media", basename(src)))
x
}
wml_link_images <- function(x, str){
wml_part_link_images(x, str, "doc_obj")
}
wml_part_link_images <- function(x, str, part){
ref <- x[[part]]$relationship()$get_data()
ref <- ref[ref$ext_src != "",]
doc <- as_xml_document(str)
for(id in seq_along(ref$ext_src) ){
xpth <- paste0("//w:drawing",
"[wp:inline/a:graphic/a:graphicData/pic:pic/pic:blipFill/a:blip",
sprintf( "[contains(@r:embed,'%s')]", ref$ext_src[id]),
"]")
src_nodes <- xml_find_all(doc, xpth)
blip_nodes <- xml_find_all(src_nodes, "wp:inline/a:graphic/a:graphicData/pic:pic/pic:blipFill/a:blip")
xml_attr(blip_nodes, "r:embed") <- ref$id[id]
}
as.character(doc)
} |
library(knitr)
library(rgl)
library(ggsci)
library(tidyverse)
library(magrittr)
rgl::setupKnitr()
options(rgl.useNULL=TRUE)
rgl::par3d("family" = "serif")
opts_chunk$set(
collapse = TRUE,
comment = "
warning=FALSE, message=FALSE, include = TRUE,
out.width = "99%", fig.width = 8, fig.align = "center", fig.asp = 0.62
)
if (!requireNamespace("rmarkdown", quietly = TRUE) || !rmarkdown::pandoc_available("1.14")) {
warning(call. = FALSE, "These vignettes assume rmarkdown and pandoc version 1.14 (or higher). These were not found. Older versions will not work.")
knitr::knit_exit()
}
library(gMOIP)
view <- matrix( c(0.333316594362259, 0.938472270965576, -0.0903875231742859, 0, 0.83994072675705, -0.339126199483871, -0.423665106296539, 0, -0.428250730037689, 0.0652943551540375, -0.901297807693481, 0, 0, 0, 0, 1), nc = 4)
loadView(v = view)
set.seed(1234)
pts <- genNDSet(3, 100, argsSphere = list(below = FALSE), dubND = FALSE)
pts <- classifyNDSet(pts[,1:3])
head(pts)
ini3D(argsPlot3d = list(xlim = c(min(pts[,1])-2,max(pts[,1])+2),
ylim = c(min(pts[,2])-2,max(pts[,2])+2),
zlim = c(min(pts[,3])-2,max(pts[,3])+2)))
plotPoints3D(pts[pts$se,1:3], argsPlot3d = list(col = "red"))
plotPoints3D(pts[!pts$sne,1:3], argsPlot3d = list(col = "black"))
plotPoints3D(pts[!pts$us,1:3], argsPlot3d = list(col = "blue"))
plotCones3D(pts[,1:3], rectangle = TRUE, argsPolygon3d = list(alpha = 1, color = "cornflowerblue"))
plotHull3D(pts[,1:3], addRays = TRUE, argsPolygon3d = list(alpha = 0.25, color = "red"), useRGLBBox = TRUE)
finalize3D(argsAxes3d = list(edges = "bbox"))
loadView(v = view)
pts <- genNDSet(3, 50, argsSphere = list(below = TRUE), dubND = FALSE)
pts <- classifyNDSet(pts[,1:3])
ini3D(argsPlot3d = list(xlim = c(min(pts[,1])-2,max(pts[,1])+2),
ylim = c(min(pts[,2])-2,max(pts[,2])+2),
zlim = c(min(pts[,3])-2,max(pts[,3])+2)))
plotPoints3D(pts[pts$se,1:3], argsPlot3d = list(col = "red"))
plotPoints3D(pts[!pts$sne,1:3], argsPlot3d = list(col = "black"))
plotPoints3D(pts[!pts$us,1:3], argsPlot3d = list(col = "blue"))
plotCones3D(pts[,1:3], rectangle = TRUE, argsPolygon3d = list(alpha = 1, color = "cornflowerblue"))
plotHull3D(pts[,1:3], addRays = TRUE, argsPolygon3d = list(alpha = 0.25, color = "red"), useRGLBBox = TRUE)
finalize3D(argsAxes3d = list(edges = "bbox"))
pts <- matrix(c(0,0,1, 0,1,0, 1,0,0, 0.5,0.2,0.5, 0.25,0.5,0.25), ncol = 3, byrow = TRUE)
open3d()
ini3D(argsPlot3d = list(xlim = c(min(pts[,1])-2,max(pts[,1])+2),
ylim = c(min(pts[,2])-2,max(pts[,2])+2),
zlim = c(min(pts[,3])-2,max(pts[,3])+2)))
plotHull3D(pts, addRays = TRUE, argsPolygon3d = list(alpha = 0.5), useRGLBBox = TRUE)
pts <- classifyNDSet(pts[,1:3])
pts
plotPoints3D(pts[pts$se,1:3], argsPlot3d = list(col = "red"))
plotPoints3D(pts[!pts$sne,1:3], argsPlot3d = list(col = "black"))
plotPoints3D(pts[!pts$us,1:3], argsPlot3d = list(col = "blue"))
plotCones3D(pts[,1:3], rectangle = TRUE, argsPolygon3d = list(alpha = 1))
finalize3D()
rglwidget(reuse = F)
pts <- genNDSet(3,50, dubND = FALSE)[,1:3]
open3d()
ini3D(argsPlot3d = list(xlim = c(0,max(pts$z1)+2),
ylim = c(0,max(pts$z2)+2),
zlim = c(0,max(pts$z3)+2)))
plotHull3D(pts, addRays = TRUE, argsPolygon3d = list(alpha = 0.5))
pts <- classifyNDSet(pts[,1:3])
pts
plotPoints3D(pts[pts$se,1:3], argsPlot3d = list(col = "red"))
plotPoints3D(pts[!pts$sne,1:3], argsPlot3d = list(col = "black"))
plotPoints3D(pts[!pts$us,1:3], argsPlot3d = list(col = "blue"))
finalize3D()
rglwidget(reuse = F)
rm(list = ls(all.names = TRUE)) |
cluster_iteration_sum_sse <- function(data, P, Q) {
np <- ncol(P)
nq <- ncol(Q)
cluster_sses <- numeric(np * nq)
ind <- 1
for(i in 1:nq) {
for(j in 1:np) {
q_proto <- which(Q[, i] == 1)
p_proto <- which(P[, j] == 1)
proto_mean <- mean(data[q_proto, p_proto], na.rm = TRUE)
cluster_sses[ind] <- sum((data[q_proto, p_proto] - proto_mean) ^ 2, na.rm = TRUE)
ind <- ind + 1
}
}
return(sum(cluster_sses, na.rm = TRUE))
} |
IRT.cv <- function(object, ...)
{
UseMethod("IRT.cv")
} |
parseGeneAttrs <- function(rootNode)
{
i <- 0
res <- xmlApply(rootNode,function(child)
{
i <<- i + 1
attrs <- xmlAttrs(child)
name <- unname(attrs["name"])
if (name == "" | is.na(name))
name <- paste(xmlName(child),i,sep="_")
logic <- xmlFindNode(child,"simulationLogic")
initVal <- NULL
if (is.null(logic))
{
warning(paste("Gene ",name," does not specify a simulation logic, assuming AND!",sep=""))
logic <- "AND"
}
else
{
logic <- logic[[1]]
params <- xmlFindNode(logic,"simParameters")
if (!is.null(params))
{
for (param in xmlChildren(params[[1]]))
{
pa <- xmlAttrs(param)
if (pa["name"] == "initVal")
{
initVal <- as.numeric(pa["value"])
if (initVal != 0 & initVal != 1)
{
warning("Initial value for gene ",name," is neither 0 nor 1 and is ignored!",sep="")
initVal <- NULL
}
break
}
}
}
logic <- unname(xmlAttrs(logic)["type"])
}
list(id=unname(attrs["id"]),
name=adjustGeneNames(name),logic=logic,initVal=initVal,inputs=NULL)
})
}
parseAllGenes <- function(rootNode)
{
genes <- unlist(xmlApply(rootNode,parseGeneAttrs),recursive=FALSE)
names(genes) <- lapply(genes,function(gene)gene$id)
return(genes)
}
parseAllLinks <- function(rootNode,geneList)
{
for (link in xmlChildren(rootNode))
{
attrs <- xmlAttrs(link)
if (is.na(attrs["sign"]))
{
warning(paste("The link between \"",geneList[[attrs["src"]]]$name,
"\" and \"",geneList[[attrs["targ"]]]$name,
"\" is not specified as an enhancer or suppressor and is therefore ignored!",sep=""))
}
else
{
geneList[[attrs["targ"]]]$input[[length(geneList[[attrs["targ"]]]$input) + 1]] <-
list(input=unname(attrs["src"]),sign=attrs["sign"])
}
}
return(geneList)
}
loadBioTapestry <- function(file, symbolic=FALSE)
{
doc <- xmlRoot(xmlTreeParse(file))
genome <- xmlFindNode(doc,"genome",throwError=TRUE)[[1]]
nodes <- xmlFindNode(genome,"nodes",throwError=TRUE)[[1]]
geneList <- parseAllGenes(nodes)
links <- xmlFindNode(genome,"links",throwError=TRUE)[[1]]
geneList <- parseAllLinks(links,geneList)
genes <- unname(sapply(geneList,function(gene)gene$name))
geneIds <- names(geneList)
fixed <- rep(-1L,length(genes))
i <- 0
interactions <- lapply(geneList,function(gene)
{
i <<- i + 1
input <- sapply(gene$input,function(inp)
{
which(geneIds == inp$input)
})
if (length(input) == 0)
{
if (!is.null(gene$initVal))
{
input <- 0
func <- gene$initVal
fixed[i] <<- func
expr <- func
}
else
{
input <- i
func <- c(0,1)
expr <- gene$name
}
}
else
{
inputSigns <- sapply(gene$input,function(inp)inp$sign)
if (!symbolic || gene$logic == "XOR")
{
tt <- as.matrix(allcombn(2,length(input)) - 1)
func <- as.integer(switch(gene$logic,
AND = {
apply(tt,1,function(assignment)
{
res <- 1
for (i in seq_along(assignment))
{
if (inputSigns[i] == "+")
res <- res & assignment[i]
else
res <- res & !assignment[i]
if (!res)
break
}
res
})
},
OR = {
apply(tt,1,function(assignment)
{
res <- 0
for (i in seq_along(assignment))
{
if (inputSigns[i] == "+")
res <- res | assignment[i]
else
res <- res | !assignment[i]
if (res)
break
}
res
})
},
XOR = {
apply(tt,1,function(assignment)
{
res <- assignment[1]
for (i in 2:length(assignment))
{
res <- xor(res,assignment[i])
}
res
})
},
stop(paste("Unknown Boolean operator \"",
gene$logic,"\"!",sep=""))
))
}
literals <- mapply(function(gene,sign)
{
if (sign == "+")
gene
else
paste("!",gene,sep="")
}, genes[input], inputSigns)
expr <- switch(gene$logic,
AND = {
paste(literals,collapse=" & ")
},
OR = {
paste(literals,collapse=" | ")
},
XOR = {
getDNF(func,genes[input])
}
)
}
if (symbolic)
return(parseBooleanFunction(expr,varNames=genes))
else
return(list(input=input,func=func,expression=expr))
})
names(interactions) <- genes
fixed <- as.integer(fixed)
names(fixed) <- genes
net <- list(genes=genes,interactions=interactions,fixed=fixed)
if (symbolic)
{
net$timeDelays <- apply(sapply(net$interactions,maxTimeDelay,genes=net$genes),1,max)
net$internalStructs <- .Call("constructNetworkTrees_R",net)
class(net) <- "SymbolicBooleanNetwork"
}
else
class(net) <- "BooleanNetwork"
return(net)
} |
quantCI <- function(x, q, alpha, method=c("exact", "approximate")){
method <- match.arg(method)
x <- sort(x)
n <- length(x)
if(method == "exact"){
results <- exactBeta(n, q, alpha)
u1 <- results[[1]]
u2 <- results[[2]]
}else if(method == "approximate"){
pn=(n+1)*q
qn=(n+1)*(1-q)
u1 <- qbeta(alpha/2, pn, qn)
u2 <- qbeta(1 - alpha/2, pn, qn)
}else{
stop("A method must be entered")
}
a <- c(q, u1, u2)
z <- (n+1)*a
j <- floor(z)
g <- z - j
y <- c()
for(r in 1:3){
if(j[r]==0){
y[r] <- x[1]
}else if(j[r] > n){
y[r] <- x[n]
}else{
y[r] <- (1-g[r])*x[j[r]] + g[r]*x[j[r]+1]
}
}
tbl <- c(y[1],y[2],y[3])
names(tbl) <- paste(as.character(a[c(1:3)]*100),"th percentile ", sep = "")
return(list(u1 = u1, u2 = u2, lower.ci = tbl[2], qx = tbl[1], upper.ci = tbl[3]))
} |
context('Adding new individuals')
test_that('age',{
contestants <- data.frame(id = letters[1:4],
period = 1,
convention1 = as.Date(
c('1994-01-01', '1990-01-01', '1991-01-01', '1992-01-01')
))
new.order <- DynaRankR:::add_new_ids_age(new.ids = 'a', working.ranks = letters[2:4],
contestants = contestants, period = 1)
expect_identical(new.order[4], 'a')
})
test_that('tenure',{
contestants <- data.frame(id = letters[1:4],
period = 1,
convention1 = as.Date(
c('1994-01-01', '1990-01-01', '1991-01-01', '1992-01-01')
))
new.order <- DynaRankR:::add_new_ids_tenure(new.ids = 'a', working.ranks = letters[2:4],
contestants = contestants, period = 1)
expect_identical(new.order[4], 'a')
})
test_that('mri',{
contestants <- data.frame(id = letters[1:4],
period = 1,
convention1 = c('b', 'o', 'f', 'g'))
new.order <- DynaRankR:::add_new_ids_mri(new.ids = 'a', working.ranks = letters[2:4],
contestants = contestants, period = 1)
expect_identical(new.order[2], 'a')
})
test_that('phys.attr',{
contestants <- data.frame(id = letters[1:4],
period = 1,
convention1 = c(45, 55, 34, 23))
new.order <- DynaRankR:::add_new_ids_phys_attr(new.ids = 'a', working.ranks = letters[2:4],
contestants = contestants, period = 1)
expect_identical(new.order[2], 'a')
})
test_that('age elo',{
contestants <- data.frame(id = letters[1:4],
period = 1,
convention1 = as.Date(
c('1994-01-01', '1990-01-01', '1991-01-01', '1992-01-01')
))
current.scores <- data.frame(id = letters[2:4],
score = c(100, 80, 60))
id.score <- DynaRankR:::add_new_ids_age_elo(new.ids = 'a',
contestants = contestants, period = 1,
current.scores = current.scores)
expect_identical(id.score[1,2], 60)
})
test_that('tenure elo',{
contestants <- data.frame(id = letters[1:4],
period = 1,
convention1 = as.Date(
c('1994-01-01', '1990-01-01', '1991-01-01', '1992-01-01')
))
current.scores <- data.frame(id = letters[2:4],
score = c(100, 80, 60))
id.scores <- DynaRankR:::add_new_ids_tenure_elo(new.ids = 'a',
contestants = contestants, period = 1,
current.scores = current.scores)
expect_equal(id.scores[1,2], as.numeric(quantile(c(100,80,60), 0)))
})
test_that('mri elo',{
contestants <- data.frame(id = letters[1:4],
period = 1,
convention1 = c('b', 'o', 'f', 'g'),stringsAsFactors = FALSE)
current.scores <- data.frame(id = letters[2:4],
score = c(100, 80, 60))
ids.score <- DynaRankR:::add_new_ids_mri_elo(new.ids = 'a', current.scores = current.scores,
contestants = contestants, period = 1)
expect_equal(ids.score[1,2], 99.9)
})
test_that('phys.attr elo',{
contestants <- data.frame(id = letters[1:4],
period = 1,
convention1 = c(45, 55, 34, 23))
current.scores <- data.frame(id = letters[2:4],
score = c(100, 80, 60))
id.scores <- DynaRankR:::add_new_ids_phys_attr_elo(new.ids = 'a', current.scores = current.scores,
contestants = contestants, period = 1)
expect_equal(id.scores[1,2], as.numeric(quantile(c(100,80,60), 0.66666666667)))
}) |
advectionF <- function(id, ...) {
.args <- list(...)
do.call(paste0('advectionF', id), args = .args)
}
advectionF2 <- function(id, arglist) {
do.call(paste0('advectionF', id), args = arglist)
}
advectionFuniform <- function(spacepoints, u, v) {
d <- nrow(spacepoints)
return( data.frame(u = rep(u, d), v = rep(v, d)) )
}
advectionFrotation <- function(spacepoints, x0, y0, a, b) {
x <- spacepoints[,1] - x0
y <- spacepoints[,2] - y0
u <- a * y
v <- (-b * x)
return( data.frame(u = u, v = v) )
}
advectionFspiral <- function(spacepoints, x0, y0, a, b, rotation = 1) {
x <- spacepoints[,1] - x0
y <- spacepoints[,2] - y0
if (rotation == 1) {
u <- ( b * y - a * x)
v <- (-a * x - b * y)
}
if (rotation == 2) {
u <- (-a * x - b * y)
v <- ( a * x - b * y)
}
return( data.frame(u = u, v = v) )
}
advectionFspiralCE <- function(spacepoints, a, C) {
xaux <- spacepoints[,1]
yaux <- spacepoints[,2]
x <- (xaux - min(xaux)) / diff(range(xaux))
y <- (yaux - min(yaux)) / diff(range(yaux))
dPPdx <- (sin(C * pi * x) * (C * pi) * (1 - x)^2 - (1 - cos(C * pi * x)) *
(2 * (1 - x))) * ((1 - cos(C * pi * y)) * (1 - y)^2)
dPPdy <- ((1 - cos(C * pi * x)) * (1 - x)^2) * (sin(C * pi * y) * (C * pi) *
(1 - y)^2 - (1 - cos(C * pi * y)) * (2 * (1 - y)))
u <- -a * dPPdy
v <- a * dPPdx
return( data.frame(u = u, v = v) )
}
advectionFradial <- function(spacepoints, x0, y0, a, b) {
x <- spacepoints[,1] - x0
y <- spacepoints[,2] - y0
u <- a * x
v <- b * y
return( data.frame(u = u, v = v) )
}
advectionFhyperbolic <- function(spacepoints, x0, y0, a, b) {
x <- spacepoints[,1] - x0
y <- spacepoints[,2] - y0
u <- a * y
v <- b * x
return( data.frame(u = u, v = v) )
} |
"_PACKAGE"
if(getRversion() >= "2.15.1") globalVariables(c(".", "alpha", "")) |
output$genderBar <- renderEcharts4r({
if (!is.null(input$ageGenderOptionRegion) & !is.null(input$ageGenderOptionDateRange)) {
dt <- GLOBAL_VALUE$signateDetail.ageGenderData
updateDay <- max(dt$公表日, na.rm = T)
dt[年代 == "", 年代 := "不明"]
genderAgeMaster <- data.table(
年代 = rep(c("不明", "00代", "> 90代", paste0(seq(1:8), "0代")), 3),
性別 = c(rep("男性", 11), rep("女性", 11), rep("不明", 11))
)
if (input$ageGenderOptionRegion != "全国") {
dt <- dt[受診都道府県 %in% input$ageGenderOptionRegion]
}
dt <- dt[公表日 >= input$ageGenderOptionDateRange[1] & 公表日 <= input$ageGenderOptionDateRange[2]]
dt <- merge(genderAgeMaster, dt[, .(人数 = .N), by = c("年代", "性別")], all.x = T)
dt[is.na(人数), 人数 := 0]
forPlot <- reshape(dt, idvar = "年代", timevar = "性別", direction = "wide")[order(年代)][, male_minus := -人数.男性]
maleCount <- sum(forPlot$人数.男性, na.rm = T)
femaleCount <- sum(forPlot$人数.女性, na.rm = T)
unknownCount <- sum(forPlot$人数.不明, na.rm = T)
totalCount <- maleCount + femaleCount + unknownCount
forPlot$年代 <- suppressWarnings(i18n$t(forPlot$年代))
forPlot %>%
e_chart(年代) %>%
e_bar(male_minus, stack = "1", name = i18n$t("男性"), itemStyle = list(color = darkNavy)) %>%
e_bar(人数.女性, stack = "1", name = i18n$t("女性"), itemStyle = list(color = middleRed)) %>%
e_x_axis(axisTick = list(show = F), axisLabel = list(inside = T)) %>%
e_labels(position = "inside", formatter = htmlwidgets::JS("
function(params) {
let count = params.value[0]
if(count < 0) {
count = -count
}
return(count)
}
")) %>%
e_y_axis(show = F) %>%
e_flip_coords() %>%
e_tooltip(
formatter = htmlwidgets::JS(paste0("
function(params) {
let count = params[0].value[0]
if(count < 0) {
count = -count
}
const total = Number(count) + Number(params[1].value[0])
return(`${params[0].value[1]} ", i18n$t("合計:"), "${total} (", i18n$t("総計の"), "${Math.round(total/", totalCount, "*100, 4)}%)
<hr>", i18n$t("男性:"), "${count} (${params[0].value[1]}", i18n$t("の"), "${Math.round(count/total*100, 4)}%)
<br>", i18n$t("女性:"), "${params[1].value[0]} (${params[0].value[1]}", i18n$t("の"), "${Math.round(params[1].value[0]/total*100, 4)}%)
`)
}
")),
trigger = "axis",
axisPointer = list(type = "shadow")
) %>%
e_title(
text = sprintf(
i18n$t("男性:%s人 (%s%%)、女性:%s人 (%s%%)\n不明:%s人 (%s%%)、計:%s人"),
maleCount, round(maleCount / totalCount * 100, 2), femaleCount, round(femaleCount / totalCount * 100, 2),
unknownCount, round(unknownCount / totalCount * 100, 2), totalCount
),
subtext = paste0(i18n$t("集計時間:"), updateDay),
textStyle = list(fontSize = 11),
subtextStyle = list(fontSize = 9)
) %>%
e_legend(top = "15%", right = "5%", selectedMode = F, orient = "vertical") %>%
e_grid(bottom = "0%", right = "0%", left = "0px")
}
})
output$ageGenderOption <- renderUI({
region <- as.list(c("全国", prefectureNameMapJa))
names(region) <- c(i18n$t("全国"), prefectureNameMap[[languageSetting]])
tagList(
pickerInput(
inputId = "ageGenderOptionRegion",
label = i18n$t("都道府県"),
choices = region
),
dateRangeInput(
"ageGenderOptionDateRange",
label = i18n$t("公表日"),
start = min(GLOBAL_VALUE$signateDetail.ageGenderData$公表日, na.rm = T),
end = Sys.Date(),
min = min(GLOBAL_VALUE$signateDetail.ageGenderData$公表日, na.rm = T),
max = Sys.Date(),
separator = " - ",
format = i18n$t("yyyy年m月d日"),
language = languageSetting
)
)
}) |
get.cycle.minimums <-
function(dataset, CycleBreaks, cyclemat, rowLimit=NULL){
close.cycle <- NULL
for(i in 1:dim(cyclemat)[2]){
close.cycle <- append(close.cycle, which.max(cyclemat[,i]))
}
if(is.null(rowLimit)){
limits <- NULL
for(i in 1:dim(CycleBreaks)[2]){
set1 <- na.omit(CycleBreaks[,i])
ncycles <- length(set1)-1
limits <- append(limits, ncycles)
}
rowLimit <- max(limits)
}
closebreaks <- NULL
start <- 1
for(i in 1:dim(CycleBreaks)[2]){
set1 <- na.omit(CycleBreaks[,i])
nbreaks <- length(set1)
ncycles <- nbreaks-1
open <- CycleBreaks[1:ncycles, i]
end <- start + ncycles - 1
close <- close.cycle[start:end]
set2 <- open + close
closebreaks <- add.col(closebreaks, set2, rowLimit)
start <- end + 1
}
return(list(closebreaks=closebreaks, close.cycle=close.cycle))
} |
options(warn = 1, keep.source = TRUE, error = quote({
status.end("ERROR")
}))
status.start <- function(name) {
cat(paste(name, format(Sys.time(), "%F %T"), sep="\t"), file=file.path(settings$outdir, "STATUS"), append=TRUE)
}
status.end <- function(status="DONE") {
cat(paste("", format(Sys.time(), "%F %T"), status, "\n", sep="\t"), file=file.path(settings$outdir, "STATUS"), append=TRUE)
}
library(PEcAn.all)
library(PEcAn.assim.sequential)
library(PEcAn.visualization)
library(PEcAn.allometry)
library(mvtnorm)
library(rjags)
library(reshape2)
library(PEcAn.LINKAGES)
settings <- read.settings("pecan.SDA.xml")
load('~/linkages_lyford_summary_v6.Rdata')
row.keep <- list()
spp.params.default <- read.csv(system.file("spp_matrix.csv", package = "linkages"))
for(i in 1:15){
row.keep[[i]]<-grep(rownames(ab_mat)[i],spp.params.default[,2])[1]
}
dist.mat<-spp.params.default[unlist(row.keep),]
dist.mat<-dist.mat[-9,]
rownames(dist.mat)<-dist.mat[,1]
dist(dist.mat,method="canberra")
new.names <- spp.params.default[unlist(row.keep),1]
new.names[2] <- spp.params.default[18,1]
rm.spp <- which(is.na(new.names))
new.names<-new.names[-rm.spp]
ab_mat<-ab_mat[-rm.spp,]
rownames(ab_mat)<- paste0("AGB.pft.",new.names)
obs.mean <- list()
for(i in 1:ncol(ab_mat)){
obs.mean[[i]] <- ab_mat[,i]
}
cov_array<-cov_array[-rm.spp,-rm.spp,]
colnames(cov_array)<-new.names
rownames(cov_array)<-new.names
obs.cov <- list()
for(i in 1:dim(cov_array)[3]){
obs.cov[[i]] <- cov_array[,,i]
}
years<-1960:2014
names(obs.mean) <- paste0(years,'/12/31')
for(i in 1:14){
plot(ab_mat[i,],typ='l',main=new.names[i])
lines(ab_mat[i,]*cov_array[i,i,])
lines(ab_mat[i,]*cov_array[i,i,])
lines(ab_mat[i,]*(cov_array[i,i,]+1))
}
status.start("IC")
IC = matrix(NA,as.numeric(settings$state.data.assimilation$n.ensemble),length(settings$pfts))
status.end()
status.start("EnKF")
sda.enkf(settings=settings, obs.mean = obs.mean,
obs.cov = obs.cov, IC = IC, Q = NULL)
status.end() |
library(hamcrest)
expected <- c(0x1.29fffffffffffp+8 + 0x0p+0i, 0x1.34c0161bc286bp+5 + -0x1.e549f5d1f6ef6p+7i,
-0x1.e3f2fa9d806b6p+6 + -0x1.2b2724a2962fbp+3i, 0x1.58796d01633a2p+6 + 0x1.824f5d8fbb5d2p+4i,
0x1.e0a897011f022p+2 + -0x1.642eb042923a2p+7i, -0x1.8628765d213c2p+7 + -0x1.882f853218ae4p+5i,
-0x1.412a5b7e75bebp+6 + 0x1.fd54e1d6b6343p+6i, 0x1.028e81545ce16p+5 + 0x1.a91304f85c4ap+5i,
-0x1.2a01d266073fp+4 + 0x1.06cdf6d020175p+4i, -0x1.1748b1bec8b43p+3 + 0x1.2b228c001af96p+6i,
0x1.0a3b1a8d47fd9p+6 + 0x1.14bc32e421259p+6i, 0x1.8fb9e7b5810acp+6 + -0x1.e88a8cc6e37ep+1i,
0x1.b6458c4c406c2p+5 + -0x1.20cbd6031a3c2p+6i, -0x1.0b045a1b30b3p+4 + -0x1.d935001996203p+5i,
-0x1.8f5cf0faa45adp+3 + -0x1.a6dbf605f0ap+3i, 0x1.68412946115ccp+2 + -0x1.3dd4fdbdaa25p+5i,
-0x1.c3681561a470ap+5 + -0x1.96ce418480b85p+5i, -0x1.47f87b47c9d3ap+6 + 0x1.0a7ac80c6184p+5i,
-0x1.c60a1773b2cc4p+0 + 0x1.2f46ea8184116p+6i, 0x1.47ab38d9f868p+5 + 0x1.fad34ca28e393p+3i,
-0x1.b4a55a851afa8p+1 + -0x1.d89ff8ae871b2p+2i, -0x1.bd616ca8e2fbp-1 + 0x1.3cde8038795a7p+5i,
0x1.fd6f04bf267b9p+5 + 0x1.59c788a516871p+4i, 0x1.73a39e87b69afp+5 + -0x1.e44b87218b8b8p+5i,
-0x1.40bc7b8a42c1p+5 + -0x1.a4b7be076d213p+5i, -0x1.24f4e866a684fp+5 + 0x1.7078beb8d7ddp+4i,
0x1.53794598dc5bbp+4 + 0x1.66cef91ebec1ep+3i, -0x1.2c85718658cp+3 + -0x1.08b936f615b86p+5i,
-0x1.8fa373466e2c2p+5 + 0x1.138aa00486409p+4i, 0x1.810133e3b496ap+3 + 0x1.e892692dc985ep+5i,
0x1.d4845433e620fp+5 + -0x1.3671831394441p+1i, -0x1.990872355277cp+0 + -0x1.66371d818d69bp+5i,
-0x1.02f83cdf6c424p+5 + 0x1.e6ce8f43c39dep+3i, 0x1.16c0870f6b7bap+5 + 0x1.fda387815bd6dp+4i,
0x1.449ebdfb77454p+5 + -0x1.78507cf5502b2p+5i, -0x1.73da3144a2fdap+5 + -0x1.77a86a118e889p+5i,
-0x1.5298f8aa3b04fp+5 + 0x1.2f9386dc9b2dcp+5i, 0x1.dd68932a68211p+4 + 0x1.a5107880d031ap+4i,
0x1.6a015547c1d2p+2 + -0x1.d2d5bece3049bp+4i, -0x1.2f3b32f1536e8p+5 + 0x1.0e8d6cf8eddfp+3i,
0x1.bb12dd400fcf4p+2 + 0x1.8a41f28a4fb7ap+5i, 0x1.9f61922beaffep+5 + 0x1.e77c609706bb3p+2i,
0x1.4a578a6f2eefap+4 + -0x1.5186fb5447b21p+5i, -0x1.dc924e29ef926p+4 + -0x1.3781d60710c32p+4i,
-0x1.325027af858eep+2 + 0x1.b84ce394aae8cp+4i, 0x1.35cdfe00f6757p+5 + -0x1.a946b0efac051p+3i,
-0x1.9e1a48e323ccp+4 + -0x1.c7c2bb2fce06ap+5i, -0x1.233e119f4d19fp+6 + 0x1.d44d085ef130ep+4i,
0x1.8b10308fe5cb8p+4 + 0x1.356905afe401cp+6i, 0x1.065530a2e7338p+6 + -0x1.3d10bdc563b59p+4i,
-0x1.987c8b7202cf6p+4 + -0x1.5670160ce6b9ap+5i, -0x1.821eb1476b3fbp+4 + 0x1.652c9018c052fp+5i,
0x1.07b7f61349827p+6 + 0x1.534c777f1623ep+4i, 0x1.e4aeac23f6d7fp+4 + -0x1.2867567354f54p+6i,
-0x1.0226e4494dfdcp+6 + -0x1.245cdd134087bp+5i, -0x1.bee4636c3813ep+4 + 0x1.717a947f6999fp+5i,
0x1.0b924e6fc2893p+5 + 0x1.ebffbda18b6a2p+1i, -0x1.8c573fcea09f1p+4 + -0x1.253a411503e8p+5i,
-0x1.b1ddd43dff207p+5 + 0x1.493885e39bc38p+5i, 0x1.1978d3369e164p+5 + 0x1.18c8c61e9c9bep+6i,
0x1.0598cf9558ca9p+6 + -0x1.f81f34d7dafacp+3i, -0x1.84344fa968574p+2 + -0x1.2ce64d1633e44p+5i,
-0x1.c58d54d68de2p+2 + 0x1.490390142b883p+4i, 0x1.86fb75ae46288p+5 + -0x1.857479fdba04p+1i,
0x1.46fda6b6ccde9p+3 + -0x1.0ad5ac89a4ab5p+6i, -0x1.e110db1b8c31fp+5 + -0x1.d175dc0703eaap+4i,
-0x1.0c3e030c01392p+5 + 0x1.243b22883e09ep+5i, 0x1.0290deab6713dp+4 + 0x1.17f1f0e19acfap+4i,
-0x1.fc8fb26f1c256p+2 + -0x1.052873765df05p+4i, -0x1.3363359ebf576p+5 + 0x1.7289792de7458p+4i,
0x1.0104a774deddcp+4 + 0x1.05022117c7c63p+6i, 0x1.29f2f30f84a4ep+6 + 0x1.33f2ced3d4777p+2i,
0x1.028fe130629e2p+4 + -0x1.df9c04cfd5cfp+5i, -0x1.2c030fdaf7a4bp+5 + -0x1.6e641e268f5c2p+1i,
0x1.b1ce6cbf7f095p+4 + 0x1.b53f2741829e5p+4i, 0x1.106ed1fd25b8bp+5 + -0x1.a52a58fb692d5p+5i,
-0x1.ddf51c367689dp+5 + -0x1.735ce50425b3cp+5i, -0x1.964786df69f92p+5 + 0x1.8dfbfe2a3eb02p+5i,
0x1.115678a34f43cp+5 + 0x1.46f9867dfe841p+5i, 0x1.41563cf2a9fa4p+4 + -0x1.aca36e79cdbcdp+4i,
-0x1.1c4563955fca4p+5 + -0x1.2d26bfbbea4p-2i, 0x1.604874e973af8p+2 + 0x1.b8c87df78bcp+5i,
0x1.16d6273695de8p+6 + 0x1.1ffaf5478790cp+2i, 0x1.18d7195ddf032p+4 + -0x1.0feda9ecbf93dp+6i,
-0x1.adf8625dd16aep+5 + -0x1.2dc77695f3a3ap+4i, -0x1.61b4e2aec962p+2 + 0x1.40ee409cbd7e1p+5i,
0x1.237f25790bcaap+5 + -0x1.b215bd9501e4fp+3i, -0x1.b20f3c39838ecp+4 + -0x1.5865505db0fd9p+5i,
-0x1.aac6c17458f49p+5 + 0x1.c61b4369437d2p+4i, 0x1.2cd9be0089952p+4 + 0x1.c9619ea2eca6fp+5i,
0x1.7da1a2ab9fdb4p+5 + -0x1.39a161e0c03afp+3i, -0x1.ef06e36ec95f2p+3 + -0x1.e3f2e57634952p+4i,
-0x1.40ad70542f9aep+4 + 0x1.2e55131570468p+5i, 0x1.f08041845d6d4p+5 + 0x1.a14bbcd056641p+4i,
0x1.401ccbc6e82bcp+5 + -0x1.1e46fda8945dp+6i, -0x1.009cb540009fcp+6 + -0x1.68f79fe56475ap+5i,
-0x1.0935cdf886dbdp+5 + 0x1.9a39119e90a9ep+5i, 0x1.67da36205ec8p+5 + 0x1.299fa3911ef92p+3i,
-0x1.da55fa0fd8c41p+3 + -0x1.8b0027455db94p+5i, -0x1.e175166dfb982p+5 + 0x1.d05f1d24ba18cp+4i,
0x1.dfb4796166f6bp+4 + 0x1.0e7a7e8c5312ap+6i, 0x1.f96e6cc347897p+5 + -0x1.84f7042cddacep+4i,
-0x1.7850b2a6637e4p+4 + -0x1.81693ee81fd91p+5i, -0x1.0910b7e578ab4p+5 + 0x1.018bb794ac606p+5i,
0x1.5edf33f7e6e06p+5 + 0x1.9edffc9f365c5p+4i, 0x1.851bea912875dp+4 + -0x1.9525d785f0496p+5i,
-0x1.a0632bc2f44d8p+5 + -0x1.670b3a2d1ab6cp+4i, -0x1.2f4df3d125a26p+4 + 0x1.98de328db0c7cp+5i,
0x1.7fd21682f5c63p+5 + 0x1.d352863333c0cp+3i, 0x1.ddee0eb9a7066p+2 + -0x1.55482799ca59fp+5i,
-0x1.3a42cf14bddf7p+5 + 0x1.9b31975066c98p+1i, 0x1.8975690d234c5p+3 + 0x1.4b8da95e4e5a5p+5i,
0x1.6ffa1e1946e6ap+5 + -0x1.b63ce0033d4b2p+3i, -0x1.085e25efe1152p+3 + -0x1.7307d83a2e8e8p+5i,
-0x1.42bc922b10d6p+5 + 0x1.84fc1b684fabp+1i, 0x1.3338a3950396ap+2 + 0x1.f8cd54b4389a8p+4i,
0x1.a5e2a08e6ade2p+4 + -0x1.02048a0faac65p+4i, -0x1.0b820aa988943p+5 + -0x1.eafbf2cc20bfep+4i,
-0x1.6453d192e711dp+5 + 0x1.73d3f0f1adf54p+5i, 0x1.6da2a5dbdcd7ep+5 + 0x1.c62c98919efadp+5i,
0x1.9ba1dc33f6253p+5 + -0x1.1626043fed37ap+5i, -0x1.e66a821b6648ap+4 + -0x1.98b801fb383f8p+4i,
0x1.f1ce0c5bd3ae8p+1 + 0x1.6110a3b2df8a8p+5i, 0x1.0dddde1c7e5a9p+6 + -0x1.f5d51b7111ae3p+3i,
-0x1.68cdd25311f64p+2 + -0x1.405e7fecbe86ap+6i, -0x1.19ac79b42979ep+6 + -0x1.6ffb816dad6e2p+3i,
-0x1.16916a97c5db2p+4 + 0x1.68359b07cc9c2p+5i, 0x1.5d07028e818aap+4 + 0x1.276e16317aa4ep+2i,
-0x1.33be05a0dd002p+4 + -0x1.0f0fec0ac63b5p+4i, -0x1.09bd26437966ap+5 + 0x1.2579d5dd637dep+5i,
0x1.124ef1105165p+5 + 0x1.c0d7f8e08071dp+5i, 0x1.02f1b1f874d12p+6 + -0x1.059d1dc1fbb07p+4i,
-0x1.3079743de2be8p+1 + -0x1.9e7526a5f440ep+5i, -0x1.e7cb1375b1a2p+4 + 0x1.d131e46a415e2p+2i,
0x1.ad15523fac32cp+4 + 0x1.3152109dab8bdp+4i, 0x1.6a5d70cfa8b52p+4 + -0x1.67d6d6b5bde7p+5i,
-0x1.94930ecf9aaf9p+5 + -0x1.ff1d9777fcda3p+4i, -0x1.1615939eb9436p+5 + 0x1.5eaf6988e26cep+5i,
0x1.0557755527ee9p+5 + 0x1.82e251467903dp+4i, 0x1.a0a07242c993p+0 + -0x1.ba8087a63283cp+4i,
-0x1.1ebec29cbf53bp+5 + 0x1.6128d86a0beep+4i, 0x1.03fd18325ce8cp+5 + 0x1.a745c6532710ap+5i,
0x1.00489f5fee84p+6 + -0x1.8d1010063dce5p+4i, -0x1.3bc865b727c9ep+3 + -0x1.cef5cd10bb686p+5i,
-0x1.2e8775e02d727p+5 + 0x1.d2e41027726fp+1i, 0x1.9228d3022c097p+3 + 0x1.20f420a67703p+4i,
0x1.52362d903dd9ep+3 + -0x1.e715264c2d6f2p+4i, -0x1.6a1ab93710f1fp+5 + -0x1.1ebfdb7864a41p+4i,
-0x1.06a809c4d81ep+5 + 0x1.74fdf63acc6eep+5i, 0x1.076bae4d6a868p+5 + 0x1.49b42b02f6889p+5i,
0x1.feb0813709a21p+4 + -0x1.0459b38b7a7c2p+4i, -0x1.e0149565d3d94p+3 + -0x1.2c78f3cc60368p+3i,
0x1.d6ac65ade0388p+2 + 0x1.197d8f7e39f54p+5i, 0x1.f1816dd2a5b16p+5 + -0x1.000a12dc96358p+2i,
0x1.a1f32cb8df62p+3 + -0x1.2ca15bb9eab26p+6i, -0x1.0dc59ef95e2b9p+6 + -0x1.798d1bc2b5a76p+4i,
-0x1.af03dec64681ap+3 + 0x1.8f08d6620f7e5p+5i, 0x1.3055626151dc9p+5 + -0x1.d3a6c61a86b16p+3i,
-0x1.695fd673bae58p+5 + -0x1.3d0735cb76e8dp+5i, -0x1.8cf08a40dde7dp+5 + 0x1.e7172bfafbb38p+5i,
0x1.b60d2bca497aap+5 + 0x1.aaf992a946bcap+5i, 0x1.35c3f57f14e91p+5 + -0x1.2897dea047ccep+5i,
-0x1.b66312ae1f05ep+4 + -0x1.3b456e19622cap+3i, 0x1.bac2344823c9dp+3 + 0x1.19d1660eadb1ap+5i,
0x1.97b9f86ae9f66p+5 + -0x1.0ac79264f094dp+4i, -0x1.d73b3f80e55a8p+0 + -0x1.d3272051aa5a1p+5i,
-0x1.9dec0b0adeec6p+5 + -0x1.cd8b12fb575d6p+3i, -0x1.2c65d7bbe8c6ap+4 + 0x1.2e31567e6e844p+5i,
0x1.adc5dabaf8492p+4 + 0x1.0725062e75825p+3i, -0x1.70f5dab2c1a76p+3 + -0x1.a7ef15674e94fp+4i,
-0x1.311519fc5ed52p+5 + 0x1.d25250f58ea43p+4i, 0x1.0d66182b15503p+5 + 0x1.b0798fc7a376ep+5i,
0x1.e4e880f5dbd1cp+5 + -0x1.87a638e2e20e6p+4i, -0x1.b8c0dbe7382a2p+3 + -0x1.93a23fe038f5cp+5i,
-0x1.e89ebbc22bc6ap+4 + 0x1.e84ccd0f64004p+3i, 0x1.f79647d46cc8ep+4 + 0x1.e65e7cb871794p+3i,
0x1.b1454684b7688p+3 + -0x1.ad1a140def94ap+5i, -0x1.16adcfb6715ccp+6 + -0x1.87c1f033f54f1p+4i,
-0x1.33d294d91c3b4p+5 + 0x1.1abc3191dc454p+6i, 0x1.c2e4666d6ac2ap+5 + 0x1.49d7b9a96fc88p+5i,
0x1.6e5a30881d08cp+4 + -0x1.35d0c38d44374p+5i, -0x1.168eb40e7edd8p+5 + 0x1.41d6226f4c79ep+3i,
0x1.22b23aaf6cb19p+5 + 0x1.87fbdddbd47acp+5i, 0x1.05ced40652939p+6 + -0x1.3c362da4e3bb4p+5i,
-0x1.8c07613a343bap+4 + -0x1.fcf807281c50bp+5i, -0x1.3b5fc5f9c427fp+5 + 0x1.888bce3cd753p+3i,
0x1.113e5317a8108p+4 + 0x1.0fea943c9c7d4p+3i, -0x1.099606adc447ep+3 + -0x1.28c9a950682fap+5i,
-0x1.c62f0948ec865p+5 + 0x1.61ee2f26c5aap-1i, -0x1.7c4de24852d8ep+4 + 0x1.d92d1a4f8a538p+5i,
0x1.3e9ab7c28fdccp+5 + 0x1.5ccc3d176898ep+5i, 0x1.3d35f1462e2dep+5 + -0x1.c11672322a514p+3i,
-0x1.682ec8305164p+2 + -0x1.b151ba4c35dcfp+3i, 0x1.8fbbfb0cd980ep+3 + 0x1.79e22f1a14866p+4i,
0x1.9f0b85728d204p+5 + -0x1.207bc48105f67p+4i, -0x1.124dc09635363p+2 + -0x1.0641fdfbacc86p+6i,
-0x1.b6c67c3c80b62p+5 + -0x1.50dc5082082eap+3i, -0x1.578e08807e5c2p+3 + 0x1.e9e19499ef159p+4i,
0x1.866798cca567p+3 + -0x1.392faddcba9a8p+2i, -0x1.8ddb5e0f3ef5bp+4 + -0x1.a1cde67b309b9p+3i,
-0x1.02fa2082d336dp+5 + 0x1.0c2178f682a95p+5i, 0x1.6d4b309ccb03fp+4 + 0x1.b34954c9158ap+5i,
0x1.de7d1788f7193p+5 + -0x1.d71ba425ae81p+0i, 0x1.140af66737267p+3 + -0x1.5c91a779af33bp+5i,
-0x1.47c073cd727b9p+4 + 0x1.11abd49a2eee4p+2i, 0x1.01de665dbb664p+5 + 0x1.336c8d2da3ce8p+3i,
0x1.f8223aa49a16bp+3 + -0x1.b52faf5966da6p+5i, -0x1.ccb3034ab6c8bp+5 + -0x1.c02f249cbeedep+4i,
-0x1.fa8179f016e3fp+4 + 0x1.55d7e4ba23585p+5i, 0x1.7b68149f63fcdp+4 + 0x1.2ddcf888dd89cp+4i,
-0x1.8b682e689993p+2 + -0x1.148bc46bbde75p+4i, -0x1.f8e5e3a13f8p+4 + 0x1.bda38e29334b5p+4i,
0x1.e01a07e043d77p+4 + 0x1.c3e4e34c4f522p+5i, 0x1.16a5f783b005ep+6 + -0x1.96d30a96571c8p+3i,
0x1.24ac18441e29dp+2 + -0x1.cc43296b05092p+5i, -0x1.d6d76f54fc2a6p+4 + -0x1.8848db00f9818p+0i,
0x1.6f622fcc24f78p+4 + 0x1.da8954865a8cp+2i, 0x1.441933dc80c6cp+2 + -0x1.9b52201019ebfp+5i,
-0x1.01c1286758b47p+6 + -0x1.22911d18504dcp+4i, -0x1.f2140d9fab0b2p+4 + 0x1.b68d4cdce3154p+5i,
0x1.f2987f76090b9p+4 + 0x1.cf54f8ef11f3ep+4i, 0x1.09a29348ed987p+3 + -0x1.8fe55c0c8d426p+3i,
-0x1.cb122080644fp+3 + 0x1.19951cd2162fdp+4i, 0x1.c995b64d933c2p+4 + 0x1.1070c9a8794c4p+5i,
0x1.a14b6dec25b4ap+5 + -0x1.165fcde17437cp+4i, 0x1.373c653b37d9p+1 + -0x1.a141691bb30e7p+5i,
-0x1.232b9898535c5p+5 + -0x1.5c0ac96c3aa37p+3i, -0x1.facd12edd9bap-2 + 0x1.468641e3848efp+4i,
0x1.0520142441229p+4 + -0x1.4d8612940beacp+4i, -0x1.4114726a00df2p+5 + -0x1.8fb1a40a2452cp+4i,
-0x1.3345889a4326fp+5 + 0x1.7e936392c3e2cp+5i, 0x1.50e4f4c660182p+5 + 0x1.654faca16f868p+5i,
0x1.17f6b4c7406ap+5 + -0x1.f3088d904f63fp+4i, -0x1.c23e031b4b441p+4 + -0x1.9222bf01ea524p+3i,
0x1.fea2bd2b9d654p+2 + 0x1.32261126501a8p+5i, 0x1.a85860586fe6p+5 + -0x1.bfed2f3bc429ep+3i,
-0x1.977d1ee8f0834p+2 + -0x1.dbc8a08de0dd2p+5i, -0x1.a54239f6c9902p+5 + -0x1.000beb23fe4a8p+2i,
-0x1.b5f3315afa506p+2 + 0x1.2ac2dedb49e5p+5i, 0x1.655a5953ad84fp+4 + -0x1.18aa3ea8b7c2p+1i,
-0x1.46d410ac933c3p+4 + -0x1.068359152a3d8p+4i, -0x1.7875ac15cb298p+4 + 0x1.2b91bf78a71f3p+5i,
0x1.47717654ad55ep+5 + 0x1.2414a3db6298bp+5i, 0x1.3fe6a4dc1e1d8p+5 + -0x1.d623c8edda492p+4i,
-0x1.016d9a22fea36p+4 + -0x1.9d538e41a923ep+4i, -0x1.ac8e5e7b9fb8p+1 + 0x1.f0c018c09027dp+3i,
0x1.c221e7f5ae2e3p+4 + -0x1.3e8712b111788p+3i, -0x1.5997e77de910cp+2 + -0x1.4da2bc2c2cf6ap+5i,
-0x1.631868a2fd106p+5 + -0x1.65736f7a7097ap+3i, -0x1.a1dfcce2d4339p+4 + 0x1.0d4d76b4e904fp+5i,
0x1.14c5bb0847ec4p+4 + 0x1.b3f121c2f0f0ap+4i, 0x1.7e997b992835ep+3 + -0x1.276780617da1ap+3i,
-0x1.363d3902391f7p+4 + 0x1.145b11e81fe04p+3i, 0x1.1a4a264fb2d5dp+4 + 0x1.5223e7718d0d2p+5i,
0x1.d854a3e4a3ccp+5 + -0x1.312aafd37c88fp+3i, 0x1.a053ab905af3p+1 + -0x1.bdc677510f6b5p+5i,
-0x1.264be9fc93758p+5 + -0x1.084f41297017p+2i, 0x1.55a75d8de9babp+3 + 0x1.23e3e47598babp+4i,
0x1.6d59608088eep+3 + -0x1.f60f247542a3p+4i, -0x1.6cf0807674608p+5 + -0x1.06a36635d1518p+4i,
-0x1.9bf49ad023555p+4 + 0x1.737da90c2708ep+5i, 0x1.183c70f61ab74p+5 + 0x1.d5424f9907143p+4i,
0x1.493c76de2712cp+4 + -0x1.565d3ddb31f53p+4i, -0x1.289a7210c8ca1p+4 + -0x1.c39c608c259bp+1i,
0x1.163eb8452bebep+3 + 0x1.e3bcde67f0fd8p+4i, 0x1.728c2387bc744p+5 + -0x1.c22ac7aab6648p+2i,
0x1.e9fd3dbce4adp+1 + -0x1.aa33483f8bf35p+5i, -0x1.77f95b660c936p+5 + -0x1.69617d72d6c8cp+3i,
-0x1.b36a4afa1a034p+2 + 0x1.0b22812477cb3p+5i, 0x1.57e8756d4b668p+4 + -0x1.380bd0e3c58e4p+3i,
-0x1.f77c6f01e25ap+4 + -0x1.2f47b2d73ceecp+4i, -0x1.c1f72609ecef3p+4 + 0x1.7243cfec926f1p+5i,
0x1.5cdb14e6bbc2dp+5 + 0x1.494ebdc434209p+5i, 0x1.5dc4cee00977p+5 + -0x1.9ad021e3fc2b4p+4i,
-0x1.23d9e6ad62dc3p+3 + -0x1.d80b7e5f1ca08p+4i, -0x1.1935fc5f28036p+3 + 0x1.3783478038047p+3i,
0x1.b3cbf28076eebp+4 + -0x1.dada79feaeeap+0i, 0x1.f5f11ec08a318p+1 + -0x1.7dd2f64e16454p+5i,
-0x1.cdb5fc09dfeb5p+5 + -0x1.246b0328968ep+4i, -0x1.b578702dd5cfep+4 + 0x1.aa84d545ac624p+5i,
0x1.482861283f623p+5 + 0x1.487ebad3f480ep+4i, -0x1.40e87bbf5b96p+1 + -0x1.0d45284893b85p+5i,
-0x1.462a963bbdd96p+5 + 0x1.d1293cc468949p+4i, 0x1.4e87943a93893p+5 + 0x1.cd145986d8924p+5i,
0x1.0c8459a2bbd28p+6 + -0x1.1b70474418db6p+5i, -0x1.6a111f5050162p+4 + -0x1.c7c9a215d9049p+5i,
-0x1.04469627e30d6p+5 + 0x1.425ce02b92c92p+4i, 0x1.fe40fad721d84p+4 + 0x1.384f9d2a084fcp+3i,
-0x1.1d96fab4ef7cp-1 + -0x1.82517f776e6aep+5i, -0x1.c9c0232447278p+5 + -0x1.26f0b55cc803p+0i,
-0x1.bf9fb9815046ep+2 + 0x1.a003a28a95aaap+5i, 0x1.1378fe93861b2p+5 + 0x1.aa4b27d2181dap+2i,
-0x1.874c0a40262ep+2 + -0x1.f1eed9be841d4p+3i, -0x1.2a207eb4734b6p+3 + 0x1.a073666929a16p+4i,
0x1.30557b5284efdp+5 + 0x1.34fb3e986c5a1p+4i, 0x1.0db7b88a1929cp+5 + -0x1.fdc59719b3abp+4i,
-0x1.a13bcbc0bca69p+3 + -0x1.286f68b63e3d8p+5i, -0x1.9295738f70bb3p+4 + -0x1.76802bdc30ef7p+1i,
-0x1.274bcd77d95aep+2 + 0x1.b71e09574d04p+2i, -0x1.28d968f4d1f08p+2 + -0x1.0e3c90d625facp+3i,
-0x1.af28f94f2b486p+4 + -0x1.b5aec2a8d48p-7i, -0x1.3e905ba2a0959p+4 + 0x1.23b75ab3d8095p+5i,
0x1.b8d8f87c4caap+4 + 0x1.4583a10ddbedcp+5i, 0x1.5ae1fc65dee36p+5 + -0x1.dae0ec4976f1cp+2i,
0x1.65d8b6dceec68p+1 + -0x1.7228c902c9292p+4i, 0x1.8ea94fa87d9b8p+1 + 0x1.6485853ed2018p+3i,
0x1.40be461433697p+5 + -0x1.a827cff9839b8p+3i, -0x1.10686636734a8p+1 + -0x1.de47a0dd18de4p+5i,
-0x1.ad88830ec772p+5 + -0x1.e3c4a71fb53b4p+3i, -0x1.28dd8e3612e46p+4 + 0x1.a45339eef720ap+4i,
-0x1.c943a1beb98p+0 + 0x1.30adf2c01456p-2i, -0x1.cbba61979a753p+4 + 0x1.1bdc89c1d7234p+3i,
-0x1.537563bf219d8p+3 + 0x1.69c9c01136f85p+5i, 0x1.03a510502df62p+5 + 0x1.3847c44439692p+5i,
0x1.8be18acbb34b3p+5 + 0x1.3d0716fbe529cp+0i, 0x1.a7987c18e86bfp+4 + -0x1.029c9efccac16p+5i,
-0x1.6672d838ce834p+2 + -0x1.4730d63c8cae7p+4i, 0x1.690c7d10e5decp+3 + -0x1.2057ccd8c826p+2i,
0x1.37ef56de53e56p+3 + -0x1.56eeadf8888ddp+5i, -0x1.ad5bddf233c3ap+5 + -0x1.08779481542e9p+5i,
-0x1.5ec371de1b51fp+5 + 0x1.59620a5c8e7cep+5i, 0x1.a9e06580718eep+4 + 0x1.fb812c506ce34p+4i,
0x1.df19468536078p+1 + -0x1.55969003a4866p+4i, -0x1.09cd3474a37abp+5 + 0x1.4e09652ff94acp+4i,
0x1.9c35756eafd58p+4 + 0x1.961158fc584f7p+5i, 0x1.b7a08de48d811p+5 + -0x1.8e4ca2d19b606p+3i,
0x1.08a68f23ee29p+0 + -0x1.369b2ce64773p+5i, -0x1.dc5efaeff5c8dp+3 + 0x1.a4cd3df178be8p-1i,
0x1.0650df15d0448p+4 + 0x1.353fc6db3053p+0i, 0x1.1260684c3154p+2 + -0x1.06364c966c4f6p+5i,
-0x1.418b881e7db8p+5 + -0x1.1be68b0c7237cp+4i, -0x1.f618bda5e2ee7p+4 + 0x1.28b6acf5bbeeep+5i,
0x1.b5c3a912efa03p+4 + 0x1.250cc8d839281p+5i, 0x1.ce07bdc448f19p+4 + -0x1.2c7efe04b2c83p+4i,
-0x1.4070df13559e5p+4 + -0x1.71b4c46365c1ep+3i, 0x1.1419e1cd561ep+2 + 0x1.05e4acb191dbdp+5i,
0x1.7f8bac1dd14fcp+5 + -0x1.3b4ae08a1d7a2p+3i, -0x1.a51ec33d94a74p+2 + -0x1.b1675e2f0ce96p+5i,
-0x1.7b537944044e4p+5 + 0x1.7b2c5072090aap+1i, 0x1.8bd5d9c4a7e3cp+2 + 0x1.fce9e0dd4fa83p+4i,
0x1.ea6a40847e692p+3 + -0x1.2dea82ae97e94p+4i, -0x1.2f9b159e8fce4p+5 + -0x1.c5a62008ce34cp+2i,
-0x1.8ae74e24914e6p+3 + 0x1.a7e6a0b9b21fap+5i, 0x1.9de0fe44253bep+5 + 0x1.8c94b3e429585p+4i,
0x1.cda6e29d761dp+4 + -0x1.0ca52987106dcp+5i, -0x1.bbdbff550ef06p+3 + -0x1.f8e6a0a59f00bp+3i,
0x1.4a7351f5fec9cp+2 + 0x1.2af9f13ea66cdp+3i, 0x1.542c0891e3b51p+4 + -0x1.feb576dc6aff8p+3i,
-0x1.05e97d22bea1ap+3 + -0x1.2184010bbe59ap+5i, -0x1.42580449d2613p+5 + -0x1.4da8f74c8a30cp+3i,
-0x1.7a4bafa5315d6p+4 + 0x1.e4356d9b19f78p+4i, 0x1.db14c0a44e3cap+3 + 0x1.2610be098193ep+4i,
-0x1.61fdd8a529874p+2 + -0x1.23da26a7bd692p+3i, -0x1.6101f927496bfp+4 + 0x1.0274861f8ce28p+5i,
0x1.4c820b0ebd43ep+5 + 0x1.66b9bcc4a2203p+5i, 0x1.bcc84abc7548ap+5 + -0x1.c4529455544cbp+4i,
-0x1.1a8be7283a30ap+3 + -0x1.4974aedad6c11p+5i, -0x1.74b6f150f5deep+3 + 0x1.c48eb7124dd3cp+1i,
0x1.00261fb43872cp+4 + -0x1.4767822149fc4p+3i, -0x1.56b17e5c2f81ap+3 + -0x1.0600e6f36d09p+5i,
-0x1.33f05e4d1b6d5p+5 + -0x1.739bb7b56da5cp+2i, -0x1.7b5a94d070c8p+4 + 0x1.c82ad0e7b7bbbp+4i,
0x1.5bcedbfcd7d07p+3 + 0x1.c0884dd10fdf8p+4i, 0x1.d7704166a3976p+3 + -0x1.3cdad0d3f9dap+0i,
-0x1.606af547aeac6p+3 + 0x1.3967a249624dcp+2i, 0x1.a33384d0269ccp+3 + 0x1.18b6462a1e045p+5i,
0x1.b165638530facp+5 + -0x1.dd3e3b4c4c7c8p+1i, 0x1.58ab161324721p+3 + -0x1.abce7c554aadcp+5i,
-0x1.25ff5cb3ba9fap+5 + -0x1.a6845186c704cp+3i, 0x1.0db6cc5e70294p+0 + 0x1.3a105ae401a2bp+4i,
0x1.afac2a24bccb8p+3 + -0x1.6c2f7d48cc0bep+4i, -0x1.3a5957493c0ffp+5 + -0x1.2accc381da34dp+4i,
-0x1.bb1dfd534b1a1p+4 + 0x1.549f670e2d3ddp+5i, 0x1.03b1021f70ea9p+5 + 0x1.e0ae6ec9231d5p+4i,
0x1.2a9d1e7c07ee2p+4 + -0x1.236155c4eb8cep+4i, -0x1.a45a503ea338ep+3 + 0x1.209eaa74b42bp+1i,
0x1.26cec49861ae2p+4 + 0x1.6233ee2fb0acep+4i, 0x1.227bc5ff6846fp+5 + -0x1.2e5753dd7caedp+4i,
-0x1.a306521d2d15ep+2 + -0x1.56e76bbada3ap+5i, -0x1.2baa0385befa6p+5 + -0x1.b0dadcf938d1ep+2i,
-0x1.6ca67d651b85ep+3 + 0x1.8df9a59bc7acdp+4i, 0x1.9a737b4cbbd9ap+3 + 0x1.0ee2201bdfb2cp+2i,
-0x1.775a0cc13cd7bp+3 + -0x1.1314588767f3cp+3i, -0x1.f7d3287823e4p+3 + 0x1.b23ee7ca4abbcp+4i,
0x1.ee6d4c62cc528p+4 + 0x1.c75885136106ep+4i, 0x1.0a4b85e1087bcp+5 + -0x1.5578d91aa34d5p+4i,
-0x1.4483e325254e5p+3 + -0x1.664f4a81d7414p+4i, -0x1.87861134e4b3p+1 + 0x1.4d52730b118ebp+3i,
0x1.6ee107139282ep+4 + -0x1.383ec90347a6p+3i, -0x1.f7cd2afc5096cp+2 + -0x1.266ae74239d99p+5i,
-0x1.4359ecfdf2c18p+5 + -0x1.40e0e0cf7479p+2i, -0x1.1d9fb2d89f1c4p+4 + 0x1.d745ca5fb5df6p+4i,
0x1.337c3a1cd86c8p+3 + 0x1.2f71cd78275f2p+4i, 0x1.0d3a165cd7d8cp+2 + 0x1.2c3b9014b23a8p+2i,
-0x1.2325a649998p-7 + 0x1.0670e2fe2bcc2p+4i, 0x1.8b46d71b768bbp+4 + 0x1.5cf341778cceap+4i,
0x1.5016745af6a6p+5 + -0x1.9a29d5fc76dcp+3i, 0x1.bfc7b769ea61ep+2 + -0x1.58295cb9e6179p+5i,
-0x1.9984e96dca1fap+4 + -0x1.d99b22e6a482ap+3i, -0x1.582b694154aeap+1 + 0x1.660c731dbd308p+2i,
-0x1.41a519f21b3p+1 + -0x1.43b9d3984c911p+4i, -0x1.2e3b7af678e22p+5 + -0x1.ee932717a4098p+1i,
-0x1.ff54154c87c84p+3 + 0x1.3268e32ed4cp+5i, 0x1.6191a67295df4p+4 + 0x1.42ef0a047b7aap+4i,
0x1.0f2e1abb2d474p+3 + -0x1.59c0913aa3e84p+1i, 0x1.86cadd2b6a516p+1 + 0x1.8237bf8058cecp+3i,
0x1.78da3238cef74p+4 + 0x1.10a8d47673edcp+3i, 0x1.7b09f5e936c8cp+4 + -0x1.ec124160932fap+3i,
0x1.1e37214fab31cp+2 + -0x1.a9cd43f6ee916p+4i, -0x1.f3120ef41a5p+3 + -0x1.2ea3378d74226p+4i,
-0x1.292499e7b0008p+4 + 0x1.b9f0590b5b4dp+0i, -0x1.c742f1201f62p+1 + 0x1.a5025fe024b84p+2i,
-0x1.e08b624b3dc0ap+2 + -0x1.0548b50c3b31p+2i, -0x1.51636c228930fp+4 + 0x1.beea790a5cfcdp+3i,
0x1.089692b0f99ffp+3 + 0x1.289258694d67ep+5i, 0x1.45bc83b115a5cp+5 + 0x1.da83c98d89bd4p+1i,
0x1.1566190ebc5cp+3 + -0x1.e593ab1c22d65p+4i, -0x1.09fb67a124ef8p+4 + 0x1.121fdbb0d317p+0i,
0x1.37532f478a22bp+4 + 0x1.64ecba2afd828p+3i, 0x1.e138025d5b396p+3 + -0x1.108439fdd8b58p+5i,
-0x1.3030e72b898d6p+5 + -0x1.4c57b23609c6bp+4i, -0x1.4d0d3965dc722p+4 + 0x1.04a42311bf8dep+5i,
0x1.775747fa26c65p+4 + 0x1.6b3beec23a43cp+3i, -0x1.a853a124679f5p+2 + -0x1.2ae36869a2886p+4i,
-0x1.85653b9691e5ep+4 + 0x1.90411cf2c28c5p+4i, 0x1.01a6be200e088p+5 + 0x1.265335908d344p+5i,
0x1.568683d56aedap+5 + -0x1.8e8baa613dbe5p+4i, -0x1.b0a831e8f7c15p+3 + -0x1.078be3b1bef74p+5i,
-0x1.8e8d25aa06782p+3 + 0x1.6960c1bbd952ep+3i, 0x1.48ad8eff411f3p+4 + -0x1.151b31d0cc9c8p+2i,
-0x1.f19ade6a576b4p+2 + -0x1.031d8fd2f0677p+5i, -0x1.22f8a30b6463p+5 + -0x1.42db3d6c8932p+0i,
-0x1.c65e54d9a8b71p+3 + 0x1.ba26a0b824bc4p+4i, 0x1.3dc5a7113e783p+3 + 0x1.3a01ab571ec24p+4i,
0x1.5a61b51868515p+3 + 0x1.111be0d909914p+2i, 0x1.be710d5af5a7p+0 + 0x1.8cc9751159a04p+2i,
0x1.fca5f132e0efp+3 + 0x1.19ed47bf05b8ep+4i, 0x1.2f0985e4174a8p+5 + -0x1.2810f80f75068p+3i,
0x1.79251897db93ep+2 + -0x1.52154dab731dp+5i, -0x1.d118aa5857b94p+4 + -0x1.bc1668ae4121cp+3i,
-0x1.c47ae522b1614p+2 + 0x1.47d34392e0cap+3i, -0x1.42e62d6e1d2ep+0 + -0x1.39f6cca8d2a65p+3i,
-0x1.9f208c22d885bp+4 + -0x1.45c61a15bc3p-2i, -0x1.7eea8356c903bp+3 + 0x1.f09b6a9d5c21cp+4i,
0x1.538f00c24fe41p+4 + 0x1.6f89db5a2138bp+4i, 0x1.5d381a695f6c3p+4 + -0x1.0c160eefb7941p+2i,
0x1.3c54a7f25b134p+2 + -0x1.f038d55300996p+2i, 0x1.bba6a878f67a4p+2 + 0x1.ecc43eeee14p+0i,
0x1.16bb9fdacd39p+4 + -0x1.3780fb902c7b6p+3i, -0x1.5e2b88db673ap-1 + -0x1.b738f6554761dp+4i,
-0x1.90ffbe56cccd4p+4 + -0x1.42cfe7f1fc734p+3i, -0x1.a063b6416bd81p+3 + 0x1.b234a9f125dp+3i,
0x1.64a0fa5d66c6p+0 + 0x1.28ef25e6121bp+2i, -0x1.71901e08121fap+3 + 0x1.3beb1b384357p+1i,
-0x1.99ad813e2d984p+2 + 0x1.91e61b24c9f06p+4i, 0x1.894ecd3e006cap+4 + 0x1.58516d99c19aep+4i,
0x1.c431d60becc0dp+4 + -0x1.2ba2a2331d386p+3i, 0x1.b9dba96f8e228p+2 + -0x1.27c9978577fdep+4i,
-0x1.b44d289c059p-3 + -0x1.34f771e7a938ep+3i, 0x1.19777a9b1fa38p+1 + -0x1.5b6e3087b0de4p+3i,
-0x1.ae0c0ca9b3848p+2 + -0x1.197f3b200cdf1p+4i, -0x1.8ff4c9194c5a6p+4 + -0x1.0594ed5dcc7eep+3i,
-0x1.690f63698e49fp+4 + 0x1.418db644691e6p+4i, 0x1.d31616c16bb04p+2 + 0x1.970cd35a49ecap+4i,
0x1.a34800eebf6e7p+3 + 0x1.f97238412cc6p+0i, -0x1.5c23a6ccfb45p+1 + 0x1.598851df7356cp+2i,
0x1.ba958fff44e5p+3 + 0x1.3303cac634a9p+4i, 0x1.01a10b6e44f33p+5 + -0x1.3e4d6cc83709p+2i,
0x1.654ad938e47fbp+3 + -0x1.d31d0300b784fp+4i, -0x1.b4d590410188cp+3 + -0x1.293c2ba1bd7dep+4i,
-0x1.69ecaf0015d2p+3 + -0x1.2dbcd26b1dep-5i, -0x1.2c6acd639434p+0 + -0x1.0b661997e167cp+2i,
-0x1.17d48c712695p+4 + -0x1.4fed9b3e258d4p+3i, -0x1.afdb015631db2p+4 + 0x1.526e58de8102ap+4i,
0x1.ca5c7522cb6c6p+3 + 0x1.2300b6bb4dd8fp+5i, 0x1.dec68a6294585p+4 + -0x1.45eb09fe411f8p+2i,
-0x1.58f1dad60356p+2 + -0x1.608fba872d409p+3i, 0x1.696c2d6ae650cp+2 + 0x1.270ce4971cdf6p+4i,
0x1.0d64d4998f04cp+5 + -0x1.0599a729f9e08p+3i, 0x1.370203a0cb8ep+0 + -0x1.2d4a13e52f98p+5i,
-0x1.b5e7fcf87455fp+4 + -0x1.6167c75db9fa2p+3i, -0x1.9055b12b45e78p+3 + 0x1.5005e1c433c3ep+3i,
-0x1.37660e3bacf98p+1 + 0x1.0d3b875866c42p+2i, -0x1.22d27b4b1a4d4p+3 + 0x1.b9947f3543fp+1i,
-0x1.23c4bde4c21cap+3 + 0x1.1c7b397c98dfap+4i, 0x1.a0f400c006826p+3 + 0x1.a7da2f581caf7p+4i,
0x1.0c5ae37036fdap+5 + 0x1.7db397c0e732ap+1i, 0x1.f1ce65a306644p+3 + -0x1.74443e7e7b0a6p+4i,
-0x1.4e378e2b353ap+2 + -0x1.6fcc6dc348838p+3i, 0x1.c87f5d2174684p+2 + -0x1.0cd8a84b55978p+2i,
0x1.208d2e4fd39ap+1 + -0x1.9e93efc0e142ep+4i, -0x1.f955feeaacd35p+4 + -0x1.25689123e436fp+4i,
-0x1.f1d62ff1d1eb4p+4 + 0x1.4d97e1f55ee82p+4i, 0x1.8e8806aa16f3p+0 + 0x1.d5e58b9d2bbc8p+4i,
0x1.695eeaed12a6ap+3 + 0x1.5c34434d08a18p+3i, 0x1.025c1531db91p+2 + 0x1.5fb87cc0eaccbp+3i,
0x1.3361c63245855p+4 + 0x1.268bd35ba116cp+4i, 0x1.29b1eb908cc18p+5 + -0x1.c8685383f7338p+2i,
0x1.6d1602986caa6p+3 + -0x1.21a2925c84c01p+5i, -0x1.25f6a3a093f76p+4 + -0x1.0950dffd56d0ep+4i,
-0x1.201c79da13938p+1 + 0x1.6f9d0b85ad24p-1i, -0x1.90d80154aed1p+1 + -0x1.486cdca538074p+4i,
-0x1.177c842a22682p+5 + -0x1.d2efe5f0c2af8p+2i, -0x1.559e54a793fbep+4 + 0x1.e76bb03ea0dcbp+4i,
0x1.34f42a901e23ap+3 + 0x1.8ce29acfd0398p+4i, 0x1.53532c33c9e6cp+3 + 0x1.76ad07c7dff2cp+3i,
0x1.f2ddddb223a68p+3 + 0x1.881ff5d8f715cp+3i, 0x1.80b4080ca10f4p+4 + 0x1.1a2072211e2ep+0i,
0x1.63dbf91e24518p+4 + -0x1.b73b1c45bc328p+3i, 0x1.1ec72d0e3037p+3 + -0x1.d01deb4c502d9p+4i,
-0x1.22f97ea3a9a96p+4 + -0x1.7c2a1ec0e2a2p+4i, -0x1.334b6c6c7585p+4 + 0x1.05cf0fbd038ep+1i,
-0x1.4e191dc91fd4p+2 + 0x0p+0i, -0x1.334b6c6c75848p+4 + -0x1.05cf0fbd0386p+1i,
-0x1.22f97ea3a9a8ap+4 + 0x1.7c2a1ec0e2a1ap+4i, 0x1.1ec72d0e3037p+3 + 0x1.d01deb4c502dp+4i,
0x1.63dbf91e2451p+4 + 0x1.b73b1c45bc328p+3i, 0x1.80b4080ca10f4p+4 + -0x1.1a2072211e29p+0i,
0x1.f2ddddb223a68p+3 + -0x1.881ff5d8f7168p+3i, 0x1.53532c33c9e6ep+3 + -0x1.76ad07c7dff3p+3i,
0x1.34f42a901e23ap+3 + -0x1.8ce29acfd0395p+4i, -0x1.559e54a793fbap+4 + -0x1.e76bb03ea0dc6p+4i,
-0x1.177c842a22682p+5 + 0x1.d2efe5f0c2af4p+2i, -0x1.90d80154aed1p+1 + 0x1.486cdca538076p+4i,
-0x1.201c79da13938p+1 + -0x1.6f9d0b85ad2p-1i, -0x1.25f6a3a093f74p+4 + 0x1.0950dffd56d0ep+4i,
0x1.6d1602986caa9p+3 + 0x1.21a2925c84c01p+5i, 0x1.29b1eb908cc18p+5 + 0x1.c8685383f734p+2i,
0x1.3361c63245853p+4 + -0x1.268bd35ba1166p+4i, 0x1.025c1531db9p+2 + -0x1.5fb87cc0eacccp+3i,
0x1.695eeaed12a64p+3 + -0x1.5c34434d08a18p+3i, 0x1.8e8806aa16f5p+0 + -0x1.d5e58b9d2bbc8p+4i,
-0x1.f1d62ff1d1eafp+4 + -0x1.4d97e1f55ee82p+4i, -0x1.f955feeaacd3p+4 + 0x1.25689123e4372p+4i,
0x1.208d2e4fd39bp+1 + 0x1.9e93efc0e142dp+4i, 0x1.c87f5d217469p+2 + 0x1.0cd8a84b5597p+2i,
-0x1.4e378e2b353a4p+2 + 0x1.6fcc6dc348834p+3i, 0x1.f1ce65a30664dp+3 + 0x1.74443e7e7b0a4p+4i,
0x1.0c5ae37036fd8p+5 + -0x1.7db397c0e7348p+1i, 0x1.a0f400c006828p+3 + -0x1.a7da2f581cafbp+4i,
-0x1.23c4bde4c21cap+3 + -0x1.1c7b397c98df7p+4i, -0x1.22d27b4b1a4d4p+3 + -0x1.b9947f3543fp+1i,
-0x1.37660e3bacf8p+1 + -0x1.0d3b875866c46p+2i, -0x1.9055b12b45e78p+3 + -0x1.5005e1c433c44p+3i,
-0x1.b5e7fcf87455fp+4 + 0x1.6167c75db9fa6p+3i, 0x1.370203a0cb8ep+0 + 0x1.2d4a13e52f98p+5i,
0x1.0d64d4998f04cp+5 + 0x1.0599a729f9e0ep+3i, 0x1.696c2d6ae651p+2 + -0x1.270ce4971cdf6p+4i,
-0x1.58f1dad603558p+2 + 0x1.608fba872d401p+3i, 0x1.dec68a6294583p+4 + 0x1.45eb09fe41202p+2i,
0x1.ca5c7522cb6c4p+3 + -0x1.2300b6bb4dd8ep+5i, -0x1.afdb015631db7p+4 + -0x1.526e58de8102cp+4i,
-0x1.17d48c712694fp+4 + 0x1.4fed9b3e258dap+3i, -0x1.2c6acd639439p+0 + 0x1.0b661997e1671p+2i,
-0x1.69ecaf0015d22p+3 + 0x1.2dbcd26b1e4p-5i, -0x1.b4d590410189p+3 + 0x1.293c2ba1bd7e2p+4i,
0x1.654ad938e47fdp+3 + 0x1.d31d0300b785p+4i, 0x1.01a10b6e44f33p+5 + 0x1.3e4d6cc837096p+2i,
0x1.ba958fff44e58p+3 + -0x1.3303cac634a94p+4i, -0x1.5c23a6ccfb46p+1 + -0x1.598851df73582p+2i,
0x1.a34800eebf6edp+3 + -0x1.f97238412ccap+0i, 0x1.d31616c16baf8p+2 + -0x1.970cd35a49ecbp+4i,
-0x1.690f63698e49ep+4 + -0x1.418db644691ep+4i, -0x1.8ff4c9194c5a9p+4 + 0x1.0594ed5dcc7f8p+3i,
-0x1.ae0c0ca9b3854p+2 + 0x1.197f3b200cdf4p+4i, 0x1.19777a9b1fa28p+1 + 0x1.5b6e3087b0decp+3i,
-0x1.b44d289c058p-3 + 0x1.34f771e7a9395p+3i, 0x1.b9dba96f8e236p+2 + 0x1.27c9978577fdep+4i,
0x1.c431d60becc0ep+4 + 0x1.2ba2a2331d386p+3i, 0x1.894ecd3e006cbp+4 + -0x1.58516d99c19aep+4i,
-0x1.99ad813e2d988p+2 + -0x1.91e61b24c9f09p+4i, -0x1.71901e08121fep+3 + -0x1.3beb1b38435bp+1i,
0x1.64a0fa5d66c8p+0 + -0x1.28ef25e6121ap+2i, -0x1.a063b6416bd86p+3 + -0x1.b234a9f125cffp+3i,
-0x1.90ffbe56cccd8p+4 + 0x1.42cfe7f1fc738p+3i, -0x1.5e2b88db6738p-1 + 0x1.b738f65547624p+4i,
0x1.16bb9fdacd39p+4 + 0x1.3780fb902c7b8p+3i, 0x1.bba6a878f67a8p+2 + -0x1.ecc43eeee13ep+0i,
0x1.3c54a7f25b134p+2 + 0x1.f038d55300992p+2i, 0x1.5d381a695f6bfp+4 + 0x1.0c160eefb7929p+2i,
0x1.538f00c24fe3ap+4 + -0x1.6f89db5a21387p+4i, -0x1.7eea8356c902ep+3 + -0x1.f09b6a9d5c212p+4i,
-0x1.9f208c22d8858p+4 + 0x1.45c61a15bc3p-2i, -0x1.42e62d6e1d3p+0 + 0x1.39f6cca8d2a62p+3i,
-0x1.c47ae522b15fep+2 + -0x1.47d34392e0cap+3i, -0x1.d118aa5857b96p+4 + 0x1.bc1668ae41218p+3i,
0x1.79251897db934p+2 + 0x1.52154dab731cep+5i, 0x1.2f0985e4174a9p+5 + 0x1.2810f80f75068p+3i,
0x1.fca5f132e0eecp+3 + -0x1.19ed47bf05b8fp+4i, 0x1.be710d5af5a9p+0 + -0x1.8cc97511599fcp+2i,
0x1.5a61b51868516p+3 + -0x1.111be0d90991p+2i, 0x1.3dc5a7113e786p+3 + -0x1.3a01ab571ec25p+4i,
-0x1.c65e54d9a8b71p+3 + -0x1.ba26a0b824bbep+4i, -0x1.22f8a30b6462fp+5 + 0x1.42db3d6c8932p+0i,
-0x1.f19ade6a576c8p+2 + 0x1.031d8fd2f0674p+5i, 0x1.48ad8eff411eep+4 + 0x1.151b31d0cc9ccp+2i,
-0x1.8e8d25aa06778p+3 + -0x1.6960c1bbd9531p+3i, -0x1.b0a831e8f7c12p+3 + 0x1.078be3b1bef71p+5i,
0x1.568683d56aedap+5 + 0x1.8e8baa613dbe4p+4i, 0x1.01a6be200e086p+5 + -0x1.265335908d345p+5i,
-0x1.85653b9691e5ep+4 + -0x1.90411cf2c28c6p+4i, -0x1.a853a124679f2p+2 + 0x1.2ae36869a2886p+4i,
0x1.775747fa26c6p+4 + -0x1.6b3beec23a439p+3i, -0x1.4d0d3965dc721p+4 + -0x1.04a42311bf8ddp+5i,
-0x1.3030e72b898d6p+5 + 0x1.4c57b23609c6cp+4i, 0x1.e138025d5b392p+3 + 0x1.108439fdd8b58p+5i,
0x1.37532f478a23p+4 + -0x1.64ecba2afd83p+3i, -0x1.09fb67a124efcp+4 + -0x1.121fdbb0d31bp+0i,
0x1.1566190ebc5ccp+3 + 0x1.e593ab1c22d65p+4i, 0x1.45bc83b115a5ap+5 + -0x1.da83c98d89be8p+1i,
0x1.089692b0f99f7p+3 + -0x1.289258694d678p+5i, -0x1.51636c228930cp+4 + -0x1.beea790a5cfc4p+3i,
-0x1.e08b624b3dc0cp+2 + 0x1.0548b50c3b308p+2i, -0x1.c742f1201f63p+1 + -0x1.a5025fe024b82p+2i,
-0x1.292499e7b000ap+4 + -0x1.b9f0590b5b4ap+0i, -0x1.f3120ef41a503p+3 + 0x1.2ea3378d7422ap+4i,
0x1.1e37214fab318p+2 + 0x1.a9cd43f6ee913p+4i, 0x1.7b09f5e936c89p+4 + 0x1.ec124160933p+3i,
0x1.78da3238cef78p+4 + -0x1.10a8d47673edap+3i, 0x1.86cadd2b6a50cp+1 + -0x1.8237bf8058ce6p+3i,
0x1.0f2e1abb2d46cp+3 + 0x1.59c0913aa3e82p+1i, 0x1.6191a67295df6p+4 + -0x1.42ef0a047b7a6p+4i,
-0x1.ff54154c87c88p+3 + -0x1.3268e32ed4cp+5i, -0x1.2e3b7af678e24p+5 + 0x1.ee932717a40bp+1i,
-0x1.41a519f21b2f8p+1 + 0x1.43b9d3984c90dp+4i, -0x1.582b694154adap+1 + -0x1.660c731dbd2fcp+2i,
-0x1.9984e96dca1f7p+4 + 0x1.d99b22e6a482ap+3i, 0x1.bfc7b769ea632p+2 + 0x1.58295cb9e6178p+5i,
0x1.5016745af6a63p+5 + 0x1.9a29d5fc76dbep+3i, 0x1.8b46d71b768bcp+4 + -0x1.5cf341778cceap+4i,
-0x1.2325a64997p-7 + -0x1.0670e2fe2bcc3p+4i, 0x1.0d3a165cd7d8cp+2 + -0x1.2c3b9014b23b8p+2i,
0x1.337c3a1cd86c4p+3 + -0x1.2f71cd78275f6p+4i, -0x1.1d9fb2d89f1c4p+4 + -0x1.d745ca5fb5df4p+4i,
-0x1.4359ecfdf2c1ap+5 + 0x1.40e0e0cf7479p+2i, -0x1.f7cd2afc5099p+2 + 0x1.266ae74239d9dp+5i,
0x1.6ee1071392831p+4 + 0x1.383ec90347a6cp+3i, -0x1.87861134e4b3p+1 + -0x1.4d52730b118eep+3i,
-0x1.4483e325254eep+3 + 0x1.664f4a81d7418p+4i, 0x1.0a4b85e1087bfp+5 + 0x1.5578d91aa34dap+4i,
0x1.ee6d4c62cc526p+4 + -0x1.c75885136106fp+4i, -0x1.f7d3287823e2ep+3 + -0x1.b23ee7ca4abb3p+4i,
-0x1.775a0cc13cd7p+3 + 0x1.1314588767f34p+3i, 0x1.9a737b4cbbd9p+3 + -0x1.0ee2201bdfb2cp+2i,
-0x1.6ca67d651b862p+3 + -0x1.8df9a59bc7ac4p+4i, -0x1.2baa0385befap+5 + 0x1.b0dadcf938d0ap+2i,
-0x1.a306521d2d156p+2 + 0x1.56e76bbada398p+5i, 0x1.227bc5ff6846dp+5 + 0x1.2e5753dd7cae8p+4i,
0x1.26cec49861ae2p+4 + -0x1.6233ee2fb0ac9p+4i, -0x1.a45a503ea3394p+3 + -0x1.209eaa74b42b8p+1i,
0x1.2a9d1e7c07eep+4 + 0x1.236155c4eb8cdp+4i, 0x1.03b1021f70ea8p+5 + -0x1.e0ae6ec9231d6p+4i,
-0x1.bb1dfd534b19dp+4 + -0x1.549f670e2d3dcp+5i, -0x1.3a5957493c1p+5 + 0x1.2accc381da34fp+4i,
0x1.afac2a24bccbcp+3 + 0x1.6c2f7d48cc0c3p+4i, 0x1.0db6cc5e702dcp+0 + -0x1.3a105ae401a2cp+4i,
-0x1.25ff5cb3ba9f9p+5 + 0x1.a6845186c7054p+3i, 0x1.58ab161324723p+3 + 0x1.abce7c554aad6p+5i,
0x1.b165638530fa8p+5 + 0x1.dd3e3b4c4c7cp+1i, 0x1.a33384d0269c8p+3 + -0x1.18b6462a1e042p+5i,
-0x1.606af547aeac7p+3 + -0x1.3967a249624e4p+2i, 0x1.d7704166a396dp+3 + 0x1.3cdad0d3f9dap+0i,
0x1.5bcedbfcd7d06p+3 + -0x1.c0884dd10fdf4p+4i, -0x1.7b5a94d070c82p+4 + -0x1.c82ad0e7b7bbap+4i,
-0x1.33f05e4d1b6d4p+5 + 0x1.739bb7b56da6p+2i, -0x1.56b17e5c2f818p+3 + 0x1.0600e6f36d08fp+5i,
0x1.00261fb43872ap+4 + 0x1.4767822149fc4p+3i, -0x1.74b6f150f5deep+3 + -0x1.c48eb7124dd5p+1i,
-0x1.1a8be7283a30cp+3 + 0x1.4974aedad6c0fp+5i, 0x1.bcc84abc7548bp+5 + 0x1.c4529455544cbp+4i,
0x1.4c820b0ebd44p+5 + -0x1.66b9bcc4a2207p+5i, -0x1.6101f927496c6p+4 + -0x1.0274861f8ce28p+5i,
-0x1.61fdd8a529864p+2 + 0x1.23da26a7bd68ep+3i, 0x1.db14c0a44e3b8p+3 + -0x1.2610be0981938p+4i,
-0x1.7a4bafa5315cep+4 + -0x1.e4356d9b19f6fp+4i, -0x1.42580449d261p+5 + 0x1.4da8f74c8a30ep+3i,
-0x1.05e97d22bea14p+3 + 0x1.2184010bbe598p+5i, 0x1.542c0891e3b54p+4 + 0x1.feb576dc6aff4p+3i,
0x1.4a7351f5feca4p+2 + -0x1.2af9f13ea66cap+3i, -0x1.bbdbff550eeffp+3 + 0x1.f8e6a0a59f00ap+3i,
0x1.cda6e29d761cep+4 + 0x1.0ca52987106dcp+5i, 0x1.9de0fe44253bep+5 + -0x1.8c94b3e429581p+4i,
-0x1.8ae74e24914e6p+3 + -0x1.a7e6a0b9b21fcp+5i, -0x1.2f9b159e8fce5p+5 + 0x1.c5a62008ce364p+2i,
0x1.ea6a40847e692p+3 + 0x1.2dea82ae97e9cp+4i, 0x1.8bd5d9c4a7e4cp+2 + -0x1.fce9e0dd4fa89p+4i,
-0x1.7b537944044e7p+5 + -0x1.7b2c5072090aap+1i, -0x1.a51ec33d94a66p+2 + 0x1.b1675e2f0ce99p+5i,
0x1.7f8bac1dd14fcp+5 + 0x1.3b4ae08a1d798p+3i, 0x1.1419e1cd561d8p+2 + -0x1.05e4acb191dbap+5i,
-0x1.4070df13559e5p+4 + 0x1.71b4c46365c1cp+3i, 0x1.ce07bdc448f1dp+4 + 0x1.2c7efe04b2c7fp+4i,
0x1.b5c3a912efap+4 + -0x1.250cc8d839282p+5i, -0x1.f618bda5e2ee7p+4 + -0x1.28b6acf5bbeecp+5i,
-0x1.418b881e7db81p+5 + 0x1.1be68b0c7237cp+4i, 0x1.1260684c31534p+2 + 0x1.06364c966c4f6p+5i,
0x1.0650df15d044ap+4 + -0x1.353fc6db304ep+0i, -0x1.dc5efaeff5c84p+3 + -0x1.a4cd3df178c88p-1i,
0x1.08a68f23ee2ep+0 + 0x1.369b2ce647732p+5i, 0x1.b7a08de48d816p+5 + 0x1.8e4ca2d19b606p+3i,
0x1.9c35756eafd5ep+4 + -0x1.961158fc584fcp+5i, -0x1.09cd3474a37b1p+5 + -0x1.4e09652ff94bp+4i,
0x1.df19468536068p+1 + 0x1.55969003a486cp+4i, 0x1.a9e06580718f4p+4 + -0x1.fb812c506ce3ep+4i,
-0x1.5ec371de1b52p+5 + -0x1.59620a5c8e7cdp+5i, -0x1.ad5bddf233c3p+5 + 0x1.08779481542e3p+5i,
0x1.37ef56de53e4ap+3 + 0x1.56eeadf8888d8p+5i, 0x1.690c7d10e5de8p+3 + 0x1.2057ccd8c8268p+2i,
-0x1.6672d838ce82p+2 + 0x1.4730d63c8cae5p+4i, 0x1.a7987c18e86b9p+4 + 0x1.029c9efccac12p+5i,
0x1.8be18acbb34aep+5 + -0x1.3d0716fbe52cp+0i, 0x1.03a510502df6p+5 + -0x1.3847c44439692p+5i,
-0x1.537563bf219d3p+3 + -0x1.69c9c01136f83p+5i, -0x1.cbba61979a751p+4 + -0x1.1bdc89c1d7232p+3i,
-0x1.c943a1beb982p+0 + -0x1.30adf2c01454p-2i, -0x1.28dd8e3612e4ap+4 + -0x1.a45339eef720ap+4i,
-0x1.ad88830ec771ep+5 + 0x1.e3c4a71fb53aep+3i, -0x1.1068663673498p+1 + 0x1.de47a0dd18de2p+5i,
0x1.40be461433699p+5 + 0x1.a827cff9839b6p+3i, 0x1.8ea94fa87d9cp+1 + -0x1.6485853ed202p+3i,
0x1.65d8b6dceec88p+1 + 0x1.7228c902c9292p+4i, 0x1.5ae1fc65dee32p+5 + 0x1.dae0ec4976f02p+2i,
0x1.b8d8f87c4ca98p+4 + -0x1.4583a10ddbed8p+5i, -0x1.3e905ba2a095ap+4 + -0x1.23b75ab3d8092p+5i,
-0x1.af28f94f2b481p+4 + 0x1.b5aec2a8d58p-7i, -0x1.28d968f4d1f18p+2 + 0x1.0e3c90d625fbp+3i,
-0x1.274bcd77d959fp+2 + -0x1.b71e09574d034p+2i, -0x1.9295738f70bb2p+4 + 0x1.76802bdc30f14p+1i,
-0x1.a13bcbc0bca67p+3 + 0x1.286f68b63e3d6p+5i, 0x1.0db7b88a1929ap+5 + 0x1.fdc59719b3aaep+4i,
0x1.30557b5284efep+5 + -0x1.34fb3e986c5ap+4i, -0x1.2a207eb4734b4p+3 + -0x1.a073666929a17p+4i,
-0x1.874c0a40262ecp+2 + 0x1.f1eed9be841d4p+3i, 0x1.1378fe93861b2p+5 + -0x1.aa4b27d2181e4p+2i,
-0x1.bf9fb98150478p+2 + -0x1.a003a28a95aaep+5i, -0x1.c9c023244727bp+5 + 0x1.26f0b55cc807p+0i,
-0x1.1d96fab4ef7ap-1 + 0x1.82517f776e6acp+5i, 0x1.fe40fad721d86p+4 + -0x1.384f9d2a084ecp+3i,
-0x1.04469627e30d1p+5 + -0x1.425ce02b92c92p+4i, -0x1.6a111f505015ep+4 + 0x1.c7c9a215d9046p+5i,
0x1.0c8459a2bbd28p+6 + 0x1.1b70474418db5p+5i, 0x1.4e87943a93894p+5 + -0x1.cd145986d8926p+5i,
-0x1.462a963bbdd97p+5 + -0x1.d1293cc468948p+4i, -0x1.40e87bbf5b96p+1 + 0x1.0d45284893b84p+5i,
0x1.482861283f62p+5 + -0x1.487ebad3f4809p+4i, -0x1.b578702dd5cfdp+4 + -0x1.aa84d545ac623p+5i,
-0x1.cdb5fc09dfeb6p+5 + 0x1.246b0328968e1p+4i, 0x1.f5f11ec08a308p+1 + 0x1.7dd2f64e16456p+5i,
0x1.b3cbf28076ef1p+4 + 0x1.dada79feaeedp+0i, -0x1.1935fc5f2802ep+3 + -0x1.3783478038052p+3i,
-0x1.23d9e6ad62dcfp+3 + 0x1.d80b7e5f1ca09p+4i, 0x1.5dc4cee009774p+5 + 0x1.9ad021e3fc2b9p+4i,
0x1.5cdb14e6bbc2ap+5 + -0x1.494ebdc434209p+5i, -0x1.c1f72609ecefp+4 + -0x1.7243cfec926f1p+5i,
-0x1.f77c6f01e25ap+4 + 0x1.2f47b2d73cee6p+4i, 0x1.57e8756d4b65ep+4 + 0x1.380bd0e3c58d3p+3i,
-0x1.b36a4afa1a038p+2 + -0x1.0b22812477caep+5i, -0x1.77f95b660c934p+5 + 0x1.69617d72d6c8dp+3i,
0x1.e9fd3dbce4aep+1 + 0x1.aa33483f8bf36p+5i, 0x1.728c2387bc746p+5 + 0x1.c22ac7aab6654p+2i,
0x1.163eb8452bec6p+3 + -0x1.e3bcde67f0fdbp+4i, -0x1.289a7210c8ca3p+4 + 0x1.c39c608c2599p+1i,
0x1.493c76de2713p+4 + 0x1.565d3ddb31f52p+4i, 0x1.183c70f61ab74p+5 + -0x1.d5424f990714dp+4i,
-0x1.9bf49ad02355fp+4 + -0x1.737da90c27091p+5i, -0x1.6cf080767460ap+5 + 0x1.06a36635d151cp+4i,
0x1.6d59608088ee8p+3 + 0x1.f60f247542a34p+4i, 0x1.55a75d8de9bb4p+3 + -0x1.23e3e47598baep+4i,
-0x1.264be9fc93758p+5 + 0x1.084f41297017p+2i, 0x1.a053ab905af4cp+1 + 0x1.bdc677510f6aep+5i,
0x1.d854a3e4a3cb8p+5 + 0x1.312aafd37c889p+3i, 0x1.1a4a264fb2d59p+4 + -0x1.5223e7718d0cdp+5i,
-0x1.363d3902391f5p+4 + -0x1.145b11e81fe06p+3i, 0x1.7e997b992835ep+3 + 0x1.276780617da0ep+3i,
0x1.14c5bb0847ecp+4 + -0x1.b3f121c2f0f05p+4i, -0x1.a1dfcce2d4337p+4 + -0x1.0d4d76b4e904dp+5i,
-0x1.631868a2fd106p+5 + 0x1.65736f7a70971p+3i, -0x1.5997e77de9114p+2 + 0x1.4da2bc2c2cf67p+5i,
0x1.c221e7f5ae2e4p+4 + 0x1.3e8712b11179p+3i, -0x1.ac8e5e7b9fb78p+1 + -0x1.f0c018c09028p+3i,
-0x1.016d9a22fea37p+4 + 0x1.9d538e41a9238p+4i, 0x1.3fe6a4dc1e1d6p+5 + 0x1.d623c8edda49ap+4i,
0x1.47717654ad56p+5 + -0x1.2414a3db6298dp+5i, -0x1.7875ac15cb29dp+4 + -0x1.2b91bf78a71f3p+5i,
-0x1.46d410ac933c2p+4 + 0x1.068359152a3d6p+4i, 0x1.655a5953ad847p+4 + 0x1.18aa3ea8b7c6p+1i,
-0x1.b5f3315afa4f6p+2 + -0x1.2ac2dedb49e4ep+5i, -0x1.a54239f6c98fep+5 + 0x1.000beb23fe4a6p+2i,
-0x1.977d1ee8f0844p+2 + 0x1.dbc8a08de0dd2p+5i, 0x1.a85860586fe5ep+5 + 0x1.bfed2f3bc42ap+3i,
0x1.fea2bd2b9d668p+2 + -0x1.32261126501a9p+5i, -0x1.c23e031b4b44p+4 + 0x1.9222bf01ea526p+3i,
0x1.17f6b4c74069dp+5 + 0x1.f3088d904f63ep+4i, 0x1.50e4f4c66018p+5 + -0x1.654faca16f865p+5i,
-0x1.3345889a4326cp+5 + -0x1.7e936392c3e2cp+5i, -0x1.4114726a00df5p+5 + 0x1.8fb1a40a24528p+4i,
0x1.0520142441226p+4 + 0x1.4d8612940beb6p+4i, -0x1.facd12edd994p-2 + -0x1.468641e3848f2p+4i,
-0x1.232b9898535c8p+5 + 0x1.5c0ac96c3aa3p+3i, 0x1.373c653b37d7cp+1 + 0x1.a141691bb30ebp+5i,
0x1.a14b6dec25b49p+5 + 0x1.165fcde17437cp+4i, 0x1.c995b64d933c7p+4 + -0x1.1070c9a8794cp+5i,
-0x1.cb122080644e1p+3 + -0x1.19951cd216303p+4i, 0x1.09a29348ed989p+3 + 0x1.8fe55c0c8d41dp+3i,
0x1.f2987f76090b4p+4 + -0x1.cf54f8ef11f3ep+4i, -0x1.f2140d9fab0b1p+4 + -0x1.b68d4cdce3155p+5i,
-0x1.01c1286758b48p+6 + 0x1.22911d18504d9p+4i, 0x1.441933dc80c7p+2 + 0x1.9b52201019ecp+5i,
0x1.6f622fcc24f7ap+4 + -0x1.da8954865a8acp+2i, -0x1.d6d76f54fc2a3p+4 + 0x1.8848db00f9812p+0i,
0x1.24ac18441e296p+2 + 0x1.cc43296b05092p+5i, 0x1.16a5f783b005ep+6 + 0x1.96d30a96571c4p+3i,
0x1.e01a07e043d7ep+4 + -0x1.c3e4e34c4f526p+5i, -0x1.f8e5e3a13f807p+4 + -0x1.bda38e29334bep+4i,
-0x1.8b682e689994p+2 + 0x1.148bc46bbde79p+4i, 0x1.7b68149f63fcbp+4 + -0x1.2ddcf888dd89ap+4i,
-0x1.fa8179f016e43p+4 + -0x1.55d7e4ba23585p+5i, -0x1.ccb3034ab6c8ap+5 + 0x1.c02f249cbeeep+4i,
0x1.f8223aa49a16cp+3 + 0x1.b52faf5966da4p+5i, 0x1.01de665dbb662p+5 + -0x1.336c8d2da3ceep+3i,
-0x1.47c073cd727b7p+4 + -0x1.11abd49a2eeep+2i, 0x1.140af6673726ap+3 + 0x1.5c91a779af33bp+5i,
0x1.de7d1788f7194p+5 + 0x1.d71ba425ae848p+0i, 0x1.6d4b309ccb041p+4 + -0x1.b34954c9158a3p+5i,
-0x1.02fa2082d336cp+5 + -0x1.0c2178f682a99p+5i, -0x1.8ddb5e0f3ef6p+4 + 0x1.a1cde67b309bdp+3i,
0x1.866798cca566cp+3 + 0x1.392faddcba9bfp+2i, -0x1.578e08807e5c2p+3 + -0x1.e9e19499ef15ep+4i,
-0x1.b6c67c3c80b68p+5 + 0x1.50dc5082082e2p+3i, -0x1.124dc0963537bp+2 + 0x1.0641fdfbacc8ap+6i,
0x1.9f0b85728d20ap+5 + 0x1.207bc48105f6ep+4i, 0x1.8fbbfb0cd981p+3 + -0x1.79e22f1a14872p+4i,
-0x1.682ec83051638p+2 + 0x1.b151ba4c35dcfp+3i, 0x1.3d35f1462e2d7p+5 + 0x1.c11672322a508p+3i,
0x1.3e9ab7c28fdc8p+5 + -0x1.5ccc3d1768989p+5i, -0x1.7c4de24852d86p+4 + -0x1.d92d1a4f8a532p+5i,
-0x1.c62f0948ec864p+5 + -0x1.61ee2f26c5b4p-1i, -0x1.099606adc4478p+3 + 0x1.28c9a950682f8p+5i,
0x1.113e5317a8107p+4 + -0x1.0fea943c9c7cfp+3i, -0x1.3b5fc5f9c427dp+5 + -0x1.888bce3cd7526p+3i,
-0x1.8c07613a343bcp+4 + 0x1.fcf807281c506p+5i, 0x1.05ced40652937p+6 + 0x1.3c362da4e3bb2p+5i,
0x1.22b23aaf6cb18p+5 + -0x1.87fbdddbd47aap+5i, -0x1.168eb40e7edd8p+5 + -0x1.41d6226f4c79ep+3i,
0x1.6e5a30881d085p+4 + 0x1.35d0c38d44373p+5i, 0x1.c2e4666d6ac2ap+5 + -0x1.49d7b9a96fc84p+5i,
-0x1.33d294d91c3b2p+5 + -0x1.1abc3191dc454p+6i, -0x1.16adcfb6715cdp+6 + 0x1.87c1f033f54fp+4i,
0x1.b1454684b7682p+3 + 0x1.ad1a140def948p+5i, 0x1.f79647d46cc8dp+4 + -0x1.e65e7cb87179p+3i,
-0x1.e89ebbc22bc64p+4 + -0x1.e84ccd0f63ffap+3i, -0x1.b8c0dbe738292p+3 + 0x1.93a23fe038f56p+5i,
0x1.e4e880f5dbd18p+5 + 0x1.87a638e2e20e4p+4i, 0x1.0d66182b155p+5 + -0x1.b0798fc7a376ap+5i,
-0x1.311519fc5ed52p+5 + -0x1.d25250f58ea44p+4i, -0x1.70f5dab2c1a76p+3 + 0x1.a7ef15674e94fp+4i,
0x1.adc5dabaf849p+4 + -0x1.0725062e7581fp+3i, -0x1.2c65d7bbe8c67p+4 + -0x1.2e31567e6e843p+5i,
-0x1.9dec0b0adeec4p+5 + 0x1.cd8b12fb575cfp+3i, -0x1.d73b3f80e55bp+0 + 0x1.d3272051aa5a2p+5i,
0x1.97b9f86ae9f6ap+5 + 0x1.0ac79264f094cp+4i, 0x1.bac2344823c9bp+3 + -0x1.19d1660eadb1ep+5i,
-0x1.b66312ae1f066p+4 + 0x1.3b456e19622d4p+3i, 0x1.35c3f57f14e94p+5 + 0x1.2897dea047ccfp+5i,
0x1.b60d2bca497a8p+5 + -0x1.aaf992a946bcap+5i, -0x1.8cf08a40dde7ap+5 + -0x1.e7172bfafbb38p+5i,
-0x1.695fd673bae56p+5 + 0x1.3d0735cb76e89p+5i, 0x1.3055626151dc6p+5 + 0x1.d3a6c61a86b12p+3i,
-0x1.af03dec646812p+3 + -0x1.8f08d6620f7e3p+5i, -0x1.0dc59ef95e2b8p+6 + 0x1.798d1bc2b5a74p+4i,
0x1.a1f32cb8df61cp+3 + 0x1.2ca15bb9eab26p+6i, 0x1.f1816dd2a5b16p+5 + 0x1.000a12dc96344p+2i,
0x1.d6ac65ade03ap+2 + -0x1.197d8f7e39f54p+5i, -0x1.e0149565d3d95p+3 + 0x1.2c78f3cc60362p+3i,
0x1.feb0813709a1cp+4 + 0x1.0459b38b7a7c4p+4i, 0x1.076bae4d6a868p+5 + -0x1.49b42b02f688bp+5i,
-0x1.06a809c4d81e2p+5 + -0x1.74fdf63acc6fp+5i, -0x1.6a1ab93710f23p+5 + 0x1.1ebfdb7864a46p+4i,
0x1.52362d903dda8p+3 + 0x1.e715264c2d6fbp+4i, 0x1.9228d3022c0a5p+3 + -0x1.20f420a677031p+4i,
-0x1.2e8775e02d728p+5 + -0x1.d2e41027726ep+1i, -0x1.3bc865b727cap+3 + 0x1.cef5cd10bb682p+5i,
0x1.00489f5fee83fp+6 + 0x1.8d1010063dce4p+4i, 0x1.03fd18325ce8dp+5 + -0x1.a745c6532710ap+5i,
-0x1.1ebec29cbf53cp+5 + -0x1.6128d86a0bee6p+4i, 0x1.a0a07242c98d8p+0 + 0x1.ba8087a63283bp+4i,
0x1.0557755527ee9p+5 + -0x1.82e251467903cp+4i, -0x1.1615939eb943ap+5 + -0x1.5eaf6988e26cfp+5i,
-0x1.94930ecf9aafbp+5 + 0x1.ff1d9777fcda4p+4i, 0x1.6a5d70cfa8b58p+4 + 0x1.67d6d6b5bde72p+5i,
0x1.ad15523fac334p+4 + -0x1.3152109dab8bdp+4i, -0x1.e7cb1375b1a1cp+4 + -0x1.d131e46a415e6p+2i,
-0x1.3079743de2beap+1 + 0x1.9e7526a5f441p+5i, 0x1.02f1b1f874d15p+6 + 0x1.059d1dc1fbb07p+4i,
0x1.124ef11051655p+5 + -0x1.c0d7f8e080723p+5i, -0x1.09bd26437967p+5 + -0x1.2579d5dd637e4p+5i,
-0x1.33be05a0ddp+4 + 0x1.0f0fec0ac63b6p+4i, 0x1.5d07028e818a1p+4 + -0x1.276e16317aa3cp+2i,
-0x1.16916a97c5daap+4 + -0x1.68359b07cc9bcp+5i, -0x1.19ac79b42979ap+6 + 0x1.6ffb816dad6ddp+3i,
-0x1.68cdd25311f5ap+2 + 0x1.405e7fecbe868p+6i, 0x1.0dddde1c7e5a5p+6 + 0x1.f5d51b7111ae3p+3i,
0x1.f1ce0c5bd3aep+1 + -0x1.6110a3b2df8a3p+5i, -0x1.e66a821b66484p+4 + 0x1.98b801fb383f6p+4i,
0x1.9ba1dc33f624ep+5 + 0x1.1626043fed37bp+5i, 0x1.6da2a5dbdcd7cp+5 + -0x1.c62c98919efaap+5i,
-0x1.6453d192e711cp+5 + -0x1.73d3f0f1adf53p+5i, -0x1.0b820aa988944p+5 + 0x1.eafbf2cc20bfcp+4i,
0x1.a5e2a08e6ade4p+4 + 0x1.02048a0faac6ap+4i, 0x1.3338a39503986p+2 + -0x1.f8cd54b4389aap+4i,
-0x1.42bc922b10d63p+5 + -0x1.84fc1b684fac8p+1i, -0x1.085e25efe1154p+3 + 0x1.7307d83a2e8ebp+5i,
0x1.6ffa1e1946e69p+5 + 0x1.b63ce0033d4aep+3i, 0x1.8975690d234c7p+3 + -0x1.4b8da95e4e5ap+5i,
-0x1.3a42cf14bddf1p+5 + -0x1.9b31975066cbp+1i, 0x1.ddee0eb9a7067p+2 + 0x1.55482799ca598p+5i,
0x1.7fd21682f5c5fp+5 + -0x1.d352863333bfbp+3i, -0x1.2f4df3d125a2p+4 + -0x1.98de328db0c79p+5i,
-0x1.a0632bc2f44d6p+5 + 0x1.670b3a2d1ab68p+4i, 0x1.851bea912875cp+4 + 0x1.9525d785f0496p+5i,
0x1.5edf33f7e6e08p+5 + -0x1.9edffc9f365c2p+4i, -0x1.0910b7e578ab6p+5 + -0x1.018bb794ac607p+5i,
-0x1.7850b2a6637e6p+4 + 0x1.81693ee81fd9p+5i, 0x1.f96e6cc347898p+5 + 0x1.84f7042cddacfp+4i,
0x1.dfb4796166f6ap+4 + -0x1.0e7a7e8c53129p+6i, -0x1.e175166dfb984p+5 + -0x1.d05f1d24ba18ap+4i,
-0x1.da55fa0fd8c45p+3 + 0x1.8b0027455db9ap+5i, 0x1.67da36205ec84p+5 + -0x1.299fa3911ef91p+3i,
-0x1.0935cdf886dbep+5 + -0x1.9a39119e90a9cp+5i, -0x1.009cb540009fap+6 + 0x1.68f79fe564758p+5i,
0x1.401ccbc6e82b8p+5 + 0x1.1e46fda8945cdp+6i, 0x1.f08041845d6dp+5 + -0x1.a14bbcd05663bp+4i,
-0x1.40ad70542f9a6p+4 + -0x1.2e55131570468p+5i, -0x1.ef06e36ec95fcp+3 + 0x1.e3f2e5763495p+4i,
0x1.7da1a2ab9fdb4p+5 + 0x1.39a161e0c03a8p+3i, 0x1.2cd9be008994fp+4 + -0x1.c9619ea2eca71p+5i,
-0x1.aac6c17458f49p+5 + -0x1.c61b4369437d3p+4i, -0x1.b20f3c39838ecp+4 + 0x1.5865505db0fd8p+5i,
0x1.237f25790bcaap+5 + 0x1.b215bd9501e5ep+3i, -0x1.61b4e2aec9622p+2 + -0x1.40ee409cbd7e2p+5i,
-0x1.adf8625dd16bp+5 + 0x1.2dc77695f3a39p+4i, 0x1.18d7195ddf031p+4 + 0x1.0feda9ecbf94p+6i,
0x1.16d6273695debp+6 + -0x1.1ffaf5478790ap+2i, 0x1.604874e973afep+2 + -0x1.b8c87df78bc05p+5i,
-0x1.1c4563955fca4p+5 + 0x1.2d26bfbbea44p-2i, 0x1.41563cf2a9f9cp+4 + 0x1.aca36e79cdbcap+4i,
0x1.115678a34f43cp+5 + -0x1.46f9867dfe83ep+5i, -0x1.964786df69f94p+5 + -0x1.8dfbfe2a3eb02p+5i,
-0x1.ddf51c36768ap+5 + 0x1.735ce50425b3fp+5i, 0x1.106ed1fd25b8cp+5 + 0x1.a52a58fb692d5p+5i,
0x1.b1ce6cbf7f098p+4 + -0x1.b53f2741829e4p+4i, -0x1.2c030fdaf7a4ap+5 + 0x1.6e641e268f5ep+1i,
0x1.028fe130629e2p+4 + 0x1.df9c04cfd5cf2p+5i, 0x1.29f2f30f84a5p+6 + -0x1.33f2ced3d4784p+2i,
0x1.0104a774deddfp+4 + -0x1.05022117c7c65p+6i, -0x1.3363359ebf574p+5 + -0x1.7289792de7464p+4i,
-0x1.fc8fb26f1c26dp+2 + 0x1.052873765df07p+4i, 0x1.0290deab67141p+4 + -0x1.17f1f0e19acfep+4i,
-0x1.0c3e030c01396p+5 + -0x1.243b22883e0a3p+5i, -0x1.e110db1b8c32ap+5 + 0x1.d175dc0703ebp+4i,
0x1.46fda6b6ccdefp+3 + 0x1.0ad5ac89a4ab4p+6i, 0x1.86fb75ae46284p+5 + 0x1.857479fdba048p+1i,
-0x1.c58d54d68ddfep+2 + -0x1.490390142b88p+4i, -0x1.84344fa968552p+2 + 0x1.2ce64d1633e3ep+5i,
0x1.0598cf9558ca6p+6 + 0x1.f81f34d7daf9cp+3i, 0x1.1978d3369e15ep+5 + -0x1.18c8c61e9c9bap+6i,
-0x1.b1ddd43dff206p+5 + -0x1.493885e39bc35p+5i, -0x1.8c573fcea09f2p+4 + 0x1.253a411503e7dp+5i,
0x1.0b924e6fc2892p+5 + -0x1.ebffbda18b658p+1i, -0x1.bee4636c38138p+4 + -0x1.717a947f6999dp+5i,
-0x1.0226e4494dfdap+6 + 0x1.245cdd1340878p+5i, 0x1.e4aeac23f6d7fp+4 + 0x1.2867567354f54p+6i,
0x1.07b7f61349826p+6 + -0x1.534c777f1623dp+4i, -0x1.821eb1476b3fcp+4 + -0x1.652c9018c053p+5i,
-0x1.987c8b7202cf9p+4 + 0x1.5670160ce6b98p+5i, 0x1.065530a2e7336p+6 + 0x1.3d10bdc563b6p+4i,
0x1.8b10308fe5cb2p+4 + -0x1.356905afe401ap+6i, -0x1.233e119f4d19ep+6 + -0x1.d44d085ef1307p+4i,
-0x1.9e1a48e323cbep+4 + 0x1.c7c2bb2fce066p+5i, 0x1.35cdfe00f6751p+5 + 0x1.a946b0efac05p+3i,
-0x1.325027af858dap+2 + -0x1.b84ce394aae83p+4i, -0x1.dc924e29ef922p+4 + 0x1.3781d60710c32p+4i,
0x1.4a578a6f2eef6p+4 + 0x1.5186fb5447b2p+5i, 0x1.9f61922beaffep+5 + -0x1.e77c609706bbp+2i,
0x1.bb12dd400fcfep+2 + -0x1.8a41f28a4fb79p+5i, -0x1.2f3b32f1536e7p+5 + -0x1.0e8d6cf8eddecp+3i,
0x1.6a015547c1d1cp+2 + 0x1.d2d5bece3049ep+4i, 0x1.dd68932a68213p+4 + -0x1.a5107880d031cp+4i,
-0x1.5298f8aa3b04fp+5 + -0x1.2f9386dc9b2dap+5i, -0x1.73da3144a2fdap+5 + 0x1.77a86a118e889p+5i,
0x1.449ebdfb77458p+5 + 0x1.78507cf5502b5p+5i, 0x1.16c0870f6b7bbp+5 + -0x1.fda387815bd78p+4i,
-0x1.02f83cdf6c426p+5 + -0x1.e6ce8f43c39dap+3i, -0x1.99087235527bp+0 + 0x1.66371d818d696p+5i,
0x1.d4845433e6208p+5 + 0x1.3671831394474p+1i, 0x1.810133e3b4974p+3 + -0x1.e892692dc9856p+5i,
-0x1.8fa373466e2c2p+5 + -0x1.138aa00486414p+4i, -0x1.2c85718658c02p+3 + 0x1.08b936f615b8ap+5i,
0x1.53794598dc5c1p+4 + -0x1.66cef91ebec1cp+3i, -0x1.24f4e866a684dp+5 + -0x1.7078beb8d7dd2p+4i,
-0x1.40bc7b8a42c11p+5 + 0x1.a4b7be076d212p+5i, 0x1.73a39e87b69aep+5 + 0x1.e44b87218b8b5p+5i,
0x1.fd6f04bf267bcp+5 + -0x1.59c788a51687p+4i, -0x1.bd616ca8e2fep-1 + -0x1.3cde8038795aap+5i,
-0x1.b4a55a851afe4p+1 + 0x1.d89ff8ae87191p+2i, 0x1.47ab38d9f867ep+5 + -0x1.fad34ca28e37fp+3i,
-0x1.c60a1773b2c6p+0 + -0x1.2f46ea8184119p+6i, -0x1.47f87b47c9d3fp+6 + -0x1.0a7ac80c61848p+5i,
-0x1.c3681561a470ap+5 + 0x1.96ce418480b86p+5i, 0x1.68412946115ap+2 + 0x1.3dd4fdbdaa24fp+5i,
-0x1.8f5cf0faa45a8p+3 + 0x1.a6dbf605f0a1bp+3i, -0x1.0b045a1b30b2cp+4 + 0x1.d935001996201p+5i,
0x1.b6458c4c406cp+5 + 0x1.20cbd6031a3c2p+6i, 0x1.8fb9e7b5810aap+6 + 0x1.e88a8cc6e37d8p+1i,
0x1.0a3b1a8d47fdbp+6 + -0x1.14bc32e42125ap+6i, -0x1.1748b1bec8b47p+3 + -0x1.2b228c001af99p+6i,
-0x1.2a01d266073f5p+4 + -0x1.06cdf6d020176p+4i, 0x1.028e81545ce19p+5 + -0x1.a91304f85c49dp+5i,
-0x1.412a5b7e75beep+6 + -0x1.fd54e1d6b6344p+6i, -0x1.8628765d213c4p+7 + 0x1.882f853218aeap+5i,
0x1.e0a897011f00ap+2 + 0x1.642eb042923a4p+7i, 0x1.58796d01633a8p+6 + -0x1.824f5d8fbb5dbp+4i,
-0x1.e3f2fa9d806bap+6 + 0x1.2b2724a2962f9p+3i, 0x1.34c0161bc287p+5 + 0x1.e549f5d1f6efap+7i
)
assertThat(stats:::fft(z=c(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0.25991722556023, 1.74008277443977, 1.37184215616,
0.62815784384, 0, 0.797828680160094, 0.202171319839906, 0, 1.81948989300014,
0.646208854539964, 0.577623678139958, 1.95667757431994, 0.577615013880049,
0.82309143088024, 2.59929355523971, 0.68953128022001, 1.04692396356016,
2.26354475621983, 3.20575552920042, 2.9386525563996, 3.85559191439998,
2.74006544592015, 1.66786140312014, 1.66788739589974, 2.92418575505997,
1.16245043204012, 1.11190760208009, 1.72564196587979, 4.15884889416003,
3.08662752284023, 3.75452358299974, 2.4151472533203, 0.945864296419714,
0.638988450259987, 21.0902030679414, 2.85563523569883, 1.08304331347982,
0.971118382879965, 0.584835418160054, 0.555953801040047, 0.859210780799899,
0.696751684500015, 0.555953801040019, 0.747294514459966, 0.808659286580081,
0.555962465299928, 0.635378248119991, 0.920575552920056, 0.555953801040047,
0.555962465299885, 0.967508180740012, 0.588445620300035, 0.555953801040047,
0.855600578659917, 0, 0, 0, 0.812269488720091, 0.187730511279909,
0, 0, 0, 0, 0, 0, 0, 0, 0.703972088780006, 0.296027911219994,
0, 0, 0, 0, 0, 0.483749758240066, 0.555962465299956, 0.960287776459978,
0.595666024580055, 0.404333975419945, 0, 0, 0, 0, 0.81948989300011,
0.18051010699989, 0, 0.931406159340042, 0.0685938406599576, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.935016361480024, 0.0649836385199762,
0, 0, 0, 0, 0, 0.714802695200007, 0.285197304799993, 0, 0.826710297280073,
0.173289702719927, 0, 0, 0, 0.0505428299599942, 0.949457170040006,
0, 0, 0, 0, 0.548733396760099, 1.4512666032399, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.613717035280047,
0.386282964719953, 0, 0.725633301620007, 0.274366698379993, 0,
0, 0.393503368999973, 0.606496631000027, 0, 0, 0, 0, 0, 0, 0,
0, 0.285197304799993, 0.714802695200007, 0, 0, 0, 0, 0.509021173220106,
0.555962465299928, 0.935016361479967, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1.2490952834001, 0.931406159339957, 0.819498557259948,
0.73646390803998, 0.55595380104009, 0.70758229091993, 0, 0, 0,
0.960287776460063, 0.555953801040062, 0.483758422499875, 0, 0,
0.368223289760181, 1.63177671023982, 0.740074110179989, 0.555953801040062,
0.703972088779949, 0.851981712260113, 0.555962465299899, 0.592055822439988,
0, 1.03970355928004, 0.960296440719958, 0, 33.483706436942, 19.704015410078,
0.812278152979957, 0.743684312319999, 0.256315687680001, 0, 0.855591914400065,
0.555962465299956, 0.588445620299979, 0.967508180740083, 0.555953801040062,
0.714811359459645, 2.76172665876021, 1.27075649623998, 1.30323965124018,
2.42600385251984, 0, 0.606496631000027, 1.39350336899997, 5.15521269924045,
1.25995188259952, 0.584835418160026, 3.88447353152014, 1.69674302023998,
1.58485274667987, 1.83393070156001, 0.638988450260058, 0.555953801040005,
0.805057748699937, 2.25271414980023, 1.36100288547993, 1.38628296471984,
1.72562463736017, 2.36824928253947, 2.90612608010036, 1.94945717003998,
2.17327237420022, 1.8772704557598, 0, 4.49819056680008, 3.29601924696021,
3.20579018623971, 0.754514918739972, 1.79782868016019, 3.44765640109983,
0.866422520820095, 0.978347451419893, 1.15523002776001, 0, 0,
0.270765160500048, 2.72923483949995, 2.58483541816031, 2.02165254857994,
2.39351203325975, 0, 0.628157843839972, 1.37184215616003, 3.48013089184019,
1.37185948467982, 1.14800962347999, 2.94584696790002, 0.0541530320999755,
0.281595766919907, 2.71840423308009, 0.64981905668003, 0.967499516480245,
2.38268142683972, 0.761735323019991, 0.873642925100114, 1.36462175187989,
0, 0.859210780800026, 1.14078921919997, 0, 0.541512992480136,
0.555962465299842, 0.902524542220021, 0, 0.41876611972009, 1.58123388027991,
0, 0, 0, 2.63175938172003, 1.2346718033599, 1.13356881492007,
0, 0, 0.101085659920045, 0.898914340079955, 0, 0, 0, 0, 0.324909528340015,
0.675090471659985, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.884473531520086,
0.115526468479914, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
, identicalTo( expected, tol = 1e-6 ) ) |
require(quadprog)
na <- 20L
ns <- 60L
R <- array(rnorm(ns*na, mean = 0.005, sd = 0.015),
dim = c(ns,na))
mu <- colMeans(R)
rf <- 0.0001
mu2 <- mu - rf
Q <- cov(R)
B <- array(mu2, dim = c(1L,na))
b <- 1
result <- solve.QP(Dmat = Q,
dvec = rep(0,na),
Amat = t(B),
bvec = b,
meq = 1L)
w <- as.matrix(result$solution/sum(result$solution))
SR <- t(w) %*% mu2 / sqrt(t(w) %*% Q %*% w)
sum(w)
t(w) %*% mu >= rf
R2 <- R - rf
ones <- array(1, dim = c(ns,1L))
solR <- lm(ones~-1 + R2)
w2 <- coef(solR); w2 <- w2/sum(w2)
stopifnot(all.equal(as.numeric(w),as.numeric(w2)))
w3 <- solve(Q,mu2)
w3 <- w3/sum(w3)
stopifnot(all.equal(as.numeric(w2),as.numeric(w3))) |
d=canc%>%filter(cancer=="CML")%>%print(n=13)
d%>%summarize(n=n(),na=sum(is.na(surv)),prct=100*na/n)
d=d%>%mutate(status=as.numeric(COD>0),surv=(surv+0.5)/12)
d=d%>%select(yrdx,agedx,sex,surv,status)%>%print(n=13)
(D=msd(d,mrt,brkst=c(0,0.5,1,2,3,4,5,6,8),brksy=c(1973,1990,2005,2015)))
gx=xlab("Years Since CML Diagnosis")
gy=ylab("Relative Risk of Mortality")
myt=theme(legend.text=element_text(size=12),strip.text=element_text(size=12))
D%>%ggplot(aes(x=t,y=RR,col=Years))+facet_grid(.~sex)+gp+gl+gx+gy+gh+
svts+jco+tc(14)+ltb+ltp+sbb+ylim(c(0,NA))+geRR+myt
ggsave("~/Results/tutorial/CMLmortEx1A.pdf",width=4.5,height=3)
labs=c("1973-1990","1991-2005","2006-2015")
d=d%>%mutate(yrg=cut(yrdx,c(1972,1990,2005,2015),labels=labs))%>%print(n=13)
fit=survfit(Surv(surv,status)~yrg+sex,data=d)
gy=ylab("Survival Probability")
ggsurvplot_facet(fit,d,facet.by="sex",legend.title="",xlim=c(0,12),
short.panel.labs=T)+svts+jco+sbb+myt+gx+gy
ggsave("~/Results/tutorial/CMLsurvEx1B.pdf",width=4.5,height=3) |
wait_for_http <- function(url, timeout = 5000, interval = 100) {
end <- Sys.time() + timeout / 1000.0
try_1 <- function(timeout) {
h <- new_handle(url = url, connecttimeout = timeout)
m <- new_pool()
multi_add(h, pool = m)
out <- tryCatch(
multi_run(timeout = timeout, pool = m),
error = function(e) { print (e) ; FALSE }
)
if (identical(out, FALSE)) return(FALSE)
out$success == 1
}
remaining <- end - Sys.time()
while (remaining > 0) {
if (try_1(as.numeric(remaining))) return(TRUE)
Sys.sleep(interval / 1000.0)
remaining <- end - Sys.time()
}
FALSE
} |
function(
x, y,
deprecated=FALSE,
...
){
if(!requireNamespace("DODO")){
stop("The DODO package is required")
}
if(!DODO::check_dodo_connection()){
stop(
"You need to connect to a DODO database using",
" the DODO::connect_to_dodo() function"
)
}
x$lid <- paste(x$source, x$identifier, sep=":")
y$lid <- paste(y$source, y$identifier, sep=":")
convTable <- dplyr::tibble()
for(xcondition in unique(x$condition)){
for(ycondition in unique(y$condition)){
if(ycondition==xcondition){
convTable <- dplyr::bind_rows(convTable, DODO::convert_concept(
from=setdiff(union(x$lid, y$lid), NA),
from.concept=xcondition,
to.concept=xcondition,
deprecated=deprecated
) %>%
dplyr::select(-"deprecated") %>%
dplyr::mutate(
fcondition=xcondition,
tcondition=xcondition
)
)
}else{
convTable <- dplyr::bind_rows(convTable, DODO::convert_concept(
from=setdiff(x$lid, NA),
from.concept=xcondition,
to.concept=ycondition,
deprecated=deprecated
) %>%
dplyr::select(-"deprecated") %>%
dplyr::mutate(
fcondition=xcondition,
tcondition=ycondition
)
)
convTable <- dplyr::bind_rows(convTable, DODO::convert_concept(
from=setdiff(y$lid, NA),
from.concept=ycondition,
to.concept=xcondition,
deprecated=deprecated
) %>%
dplyr::select(-"deprecated") %>%
dplyr::mutate(
fcondition=ycondition,
tcondition=xcondition
)
)
}
}
}
toRet <- dplyr::bind_rows(
dplyr::left_join(
x, convTable, by=c("lid"="from", "condition"="fcondition")
) %>%
dplyr::rename(
"lid_x"="lid", "lid_y"="to",
"condition_x"="condition", "condition_y"="tcondition"
),
dplyr::left_join(
x, convTable, by=c("lid"="to", "condition"="tcondition")
) %>%
dplyr::rename(
"lid_x"="lid", "lid_y"="from",
"condition_x"="condition", "condition_y"="fcondition"
)
)
toRet <- dplyr::right_join(
toRet, y,
by=c("lid_y"="lid", "condition_y"="condition"),
suffix=c("_x", "_y")
) %>%
dplyr::select(-lid_x, -lid_y) %>%
dplyr::distinct()
return(toRet)
} |
SNK.test <-
function (y, trt, DFerror, MSerror, alpha=0.05, group=TRUE,main = NULL,console=FALSE)
{
name.y <- paste(deparse(substitute(y)))
name.t <- paste(deparse(substitute(trt)))
clase<-c("aov","lm")
if(is.null(main))main<-paste(name.y,"~", name.t)
if("aov"%in%class(y) | "lm"%in%class(y)){
if(is.null(main))main<-y$call
A<-y$model
DFerror<-df.residual(y)
MSerror<-deviance(y)/DFerror
y<-A[,1]
ipch<-pmatch(trt,names(A))
nipch<- length(ipch)
for(i in 1:nipch){
if (is.na(ipch[i]))
return(if(console)cat("Name: ", trt, "\n", names(A)[-1], "\n"))
}
name.t<- names(A)[ipch][1]
trt <- A[, ipch]
if (nipch > 1){
trt <- A[, ipch[1]]
for(i in 2:nipch){
name.t <- paste(name.t,names(A)[ipch][i],sep=":")
trt <- paste(trt,A[,ipch[i]],sep=":")
}}
name.y <- names(A)[1]
}
junto <- subset(data.frame(y, trt), is.na(y) == FALSE)
Mean<-mean(junto[,1])
CV<-sqrt(MSerror)*100/Mean
medians<-tapply.stat(junto[,1],junto[,2],stat="median")
for(i in c(1,5,2:4)) {
x <- tapply.stat(junto[,1],junto[,2],function(x)quantile(x)[i])
medians<-cbind(medians,x[,2])
}
medians<-medians[,3:7]
names(medians)<-c("Min","Max","Q25","Q50","Q75")
means <- tapply.stat(junto[,1],junto[,2],stat="mean")
sds <- tapply.stat(junto[,1],junto[,2],stat="sd")
nn <- tapply.stat(junto[,1],junto[,2],stat="length")
means<-data.frame(means,std=sds[,2],r=nn[,2],medians)
names(means)[1:2]<-c(name.t,name.y)
ntr<-nrow(means)
Tprob <- qtukey(1-alpha,2:ntr, DFerror)
nr <- unique(nn[,2])
if(console) {
cat("\nStudy:", main)
cat("\n\nStudent Newman Keuls Test\nfor",name.y,"\n")
cat("\nMean Square Error: ",MSerror,"\n\n")
cat(paste(name.t,",",sep="")," means\n\n")
print(data.frame(row.names = means[,1], means[,2:6]))
}
if(length(nr) == 1 ) sdtdif <- sqrt(MSerror/nr)
else {
nr1 <- 1/mean(1/nn[,2])
sdtdif <- sqrt(MSerror/nr1)
}
SNK <- Tprob * sdtdif
names(SNK)<-2:ntr
snk<-data.frame(Table=Tprob,CriticalRange=SNK)
if ( group & length(nr) == 1 & console){
cat("\nAlpha:",alpha,"; DF Error:",DFerror,"\n")
cat("\nCritical Range\n")
print(SNK)
}
if ( group & length(nr) != 1 & console) cat("\nGroups according to probability of means differences and alpha level(",alpha,")\n")
if ( length(nr) != 1) snk<-NULL
Omeans<-order(means[,2],decreasing = TRUE)
Ordindex<-order(Omeans)
comb <-utils::combn(ntr,2)
nn<-ncol(comb)
dif<-rep(0,nn)
LCL<-dif
UCL<-dif
sig<-NULL
pvalue<-dif
odif<-dif
for (k in 1:nn) {
i<-comb[1,k]
j<-comb[2,k]
dif[k]<-means[i,2]-means[j,2]
nx<-abs(i-j)+1
odif[k] <- abs(Ordindex[i]- Ordindex[j])+1
pvalue[k]<- round(1-ptukey(abs(dif[k])/sdtdif,odif[k],DFerror),4)
LCL[k] <- dif[k] - SNK[odif[k]-1]
UCL[k] <- dif[k] + SNK[odif[k]-1]
sig[k]<-" "
if (pvalue[k] <= 0.001) sig[k]<-"***"
else if (pvalue[k] <= 0.01) sig[k]<-"**"
else if (pvalue[k] <= 0.05) sig[k]<-"*"
else if (pvalue[k] <= 0.1) sig[k]<-"."
}
if(!group){
tr.i <- means[comb[1, ],1]
tr.j <- means[comb[2, ],1]
comparison<-data.frame("difference" = dif, pvalue=pvalue,"signif."=sig,LCL,UCL)
rownames(comparison)<-paste(tr.i,tr.j,sep=" - ")
if(console){cat("\nComparison between treatments means\n\n")
print(comparison)}
groups=NULL
}
if (group) {
comparison=NULL
Q<-matrix(1,ncol=ntr,nrow=ntr)
p<-pvalue
k<-0
for(i in 1:(ntr-1)){
for(j in (i+1):ntr){
k<-k+1
Q[i,j]<-p[k]
Q[j,i]<-p[k]
}
}
groups <- orderPvalue(means[, 1], means[, 2],alpha, Q,console)
names(groups)[1]<-name.y
if(console) {
cat("\nMeans with the same letter are not significantly different.\n\n")
print(groups)
}
}
parameters<-data.frame(test="SNK",name.t=name.t,ntr = ntr,alpha=alpha)
statistics<-data.frame(MSerror=MSerror,Df=DFerror,Mean=Mean,CV=CV)
rownames(parameters)<-" "
rownames(statistics)<-" "
rownames(means)<-means[,1]
means<-means[,-1]
output<-list(statistics=statistics,parameters=parameters, snk=snk,
means=means,comparison=comparison,groups=groups)
class(output)<-"group"
invisible(output)
} |
.modEvAmethods <-
function(arg) {
if (arg %in% c("threshMeasures", "multModEv")) {
thresh.measures <- c("CCR", "Misclass", "Sensitivity", "Specificity", "Omission", "Commission", "Precision", "Recall", "PPP", "NPP", "UPR", "OPR", "PPI", "PAI", "kappa", "TSS", "NMI", "F1score", "OddsRatio")
if (arg == "threshMeasures") return(thresh.measures)
else if (arg == "multModEv") return (c("Preval", "AUC", "MeanPrecision", "AUCPR", thresh.measures))
}
else if (arg == "bin") return(c("round.prob", "prob.bins", "size.bins", "n.bins", "quantiles"))
else if (arg == "threshold") return(c("each", "preval", "0.5", "maxKappa", "minSensSpecDiff", "maxSensSpecSum", "maxTSS"))
} |
get_dists <- function(x, i, j = NULL, return_indices = FALSE){
j_supplied <- !is.null(j)
if(is.null(return_indices)){
stop("return_indices must be TRUE or FALSE.")
}
return_indices <- as.logical(return_indices)[1]
if(is.na(return_indices)){stop("return_indices cannot be NA.")}
if(
is.null(x) ||
!((length(class(x)) == 1) && (class(x) == "dist"))
){
stop(
"
x must be an object of class 'dist'.
"
)
}
size <- attr(x,"Size")
if(is.null(i)){
stop("Argument i cannot be NULL.")
}
if(!is.null(j)){
if(
!(
(length(class(i)) == 1) && (length(class(j)) == 1) &&
((class(i) == "numeric") || (class(i) == "integer")) &&
((class(j) == "numeric") || (class(j) == "integer")) &&
all(as.integer(i) == i) && all(as.integer(j) == j) &&
(length(i) == length(j))
)
){
stop(
"
If both i and j are supplied, then both must be equal length integer or
numeric vectors.
"
)
}else{
i <- matrix(c(i,j), ncol = 2)
}
}
if(
!(
(
(class(i) == "matrix") &&
((class(i[1]) == "numeric") || (class(i[1]) == "integer")) &&
all(as.integer(i) == i) &&
all((i >= 1) & (i <= size))
)
)
){
if(j_supplied){
stop("Vector arguments i and j must be integers between 1 and
attr(x, 'Size')")
}else{
stop(
"i must be a two column matrix filled with integers between 1 and
attr(x, 'Size'), inclusive"
)
}
}
left_smaller <- i[,1] < i[,2]
right_smaller <- !left_smaller
s <- numeric(nrow(i))
b <- s
s[left_smaller] <- i[left_smaller,1]
s[right_smaller] <- i[right_smaller,2]
b[left_smaller] <- i[left_smaller,2]
b[right_smaller] <- i[right_smaller,1]
linear_index <- 0.5*size*(size-1)-0.5*(size-s)*(size-s-1)-(size-b)
linear_index[s == b] <- NA
output <- x[linear_index]
output[is.na(output)] <- 0
if(return_indices){
output <- matrix(c(s,b,output), ncol = 3)
colnames(output) <- c("Small_Index","Large_Index","Distance")
}
return(output)
} |
downloadAEMETstationlist <- function(api){
opt = meteospain::aemet_options(api_key = api)
data_sf = meteospain::get_stations_info_from("aemet", opt)
data_sp = as(data_sf, "Spatial")
data_sp@data = data_sp@data[,c("altitude", "station_id","station_name")]
names(data_sp@data) = c("elevation", "ID", "name")
row.names(data_sp@data) <- data_sp@data$ID
colnames(data_sp@coords)<-c("long", "lat")
rownames(data_sp@coords) <- data_sp@data$ID
return(data_sp)
}
downloadSMCstationlist <- function(api, date = NULL){
if(is.null(date)) date = Sys.Date()
opt = meteospain::meteocat_options(api_key = api, start_date = as.Date(date))
data_sf = meteospain::get_stations_info_from("meteocat", opt)
data_sp = as(data_sf, "Spatial")
data_sp@data = data_sp@data[,c("altitude", "station_id","station_province","station_name")]
names(data_sp@data) = c("elevation", "ID","province", "name")
row.names(data_sp@data) <- data_sp@data$ID
colnames(data_sp@coords)<-c("long", "lat")
rownames(data_sp@coords) <- data_sp@data$ID
return(data_sp)
}
downloadMGstationlist <- function() {
opt = meteospain::meteogalicia_options()
data_sf = meteospain::get_stations_info_from("meteogalicia", opt)
data_sp = as(data_sf, "Spatial")
data_sp@data = data_sp@data[,c("altitude", "station_id","station_province","station_name")]
names(data_sp@data) = c("elevation", "ID","province", "name")
row.names(data_sp@data) <- data_sp@data$ID
colnames(data_sp@coords)<-c("long", "lat")
rownames(data_sp@coords) <- data_sp@data$ID
return(data_sp)
}
downloadMETEOCLIMATICstationlist <- function(station_id = 'ESCAT') {
opt <- meteospain::meteoclimatic_options(stations = station_id)
data_sf <- meteospain::get_stations_info_from("meteoclimatic", opt)
data_sp <- as(data_sf, "Spatial")
data_sp@data <- data_sp@data[,c("station_id","station_name")]
names(data_sp@data) <- c("ID", "name")
row.names(data_sp@data) <- data_sp@data$ID
colnames(data_sp@coords)<-c("long", "lat")
rownames(data_sp@coords) <- data_sp@data$ID
return(data_sp)
} |
cancor <- function(x, ...) {
UseMethod("cancor", x)
}
cancor.formula <- function(formula, data, subset, weights,
na.rm = TRUE,
method = "gensvd",
...) {
formula <- update(formula, . ~ . - 1)
cl <- match.call()
cl$formula <- formula
mf <- match.call(expand.dots = FALSE)
mf$formula <- formula
m <- match(c("formula", "data", "subset", "weights"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf[[1L]] <- as.name("model.frame")
mf <- eval(mf, parent.frame())
mt <- attr(mf, "terms")
y <- model.response(mf, "numeric")
w <- as.vector(model.weights(mf))
if (!is.null(w) && !is.numeric(w))
stop("'weights' must be a numeric vector")
x <- model.matrix(mt, mf, contrasts)
z <- cancor.default(x, y, weights=w, na.rm=na.rm, ...)
z$call <- cl
z$terms <- mt
z
}
Var <- function(x, na.rm = TRUE, use, weights) {
if(missing(weights) || is.null(weights))
res <- var(x, na.rm=na.rm, use=use)
else {
if (na.rm) {
if (!pmatch(use, "complete")) warning("Use of weights only supports use='complete'")
OK <- complete.cases(x)
x <- x[OK,]
}
res <- cov.wt(x, wt=weights)$cov
}
res
}
cancor.default <- function (x, y,
weights,
X.names = colnames(x),
Y.names = colnames(y),
row.names = rownames(x),
xcenter = TRUE, ycenter = TRUE,
xscale = FALSE, yscale = FALSE,
ndim=min(p,q),
set.names=c("X", "Y"),
prefix=c("Xcan", "Ycan"),
na.rm = TRUE,
use = if (na.rm) "complete" else "pairwise",
method = "gensvd",
...
)
{
X <- as.matrix(x)
Y <- as.matrix(y)
p <- ncol(X)
q <- ncol(Y)
n <- length(complete.cases(X,Y))
if(!missing(weights)) n <- n - sum(weights==0)
C <- Var(cbind(X, Y), na.rm = TRUE, use=use, weights=weights)
Cxx <- C[1:p, 1:p]
Cyy <- C[-(1:p), -(1:p)]
Cxy <- C[1:p, -(1:p)]
res <- gensvd(Cxy, Cxx, Cyy, nu=ndim, nv=ndim)
names(res) <- c("cor", "xcoef", "ycoef")
colnames(res$xcoef) <- paste(prefix[1], 1:ndim, sep="")
colnames(res$ycoef) <- paste(prefix[2], 1:ndim, sep="")
scores <- can.scores(X, Y, res$xcoef, res$ycoef)
colnames(scores$xscores) <- paste(prefix[1], 1:ndim, sep="")
colnames(scores$yscores) <- paste(prefix[2], 1:ndim, sep="")
structure <- can.structure(X, Y, scores, use=use)
result <- list(cancor = res$cor,
names = list(X = X.names, Y = Y.names,
row.names = row.names, set.names=set.names),
ndim = ndim,
dim = list(p=p, q=q, n=n),
coef = list(X = res$xcoef, Y= res$ycoef),
scores = list(X = scores$xscores, Y=scores$yscores),
X = X, Y = Y,
weights = if (missing(weights)) NULL else weights,
structure = structure)
class(result) <- "cancor"
return(result)
}
can.scores <- function (X, Y, xcoef, ycoef)
{
X.aux = scale(X, center=TRUE, scale=FALSE)
Y.aux = scale(Y, center=TRUE, scale=FALSE)
X.aux[is.na(X.aux)] = 0
Y.aux[is.na(Y.aux)] = 0
xscores = X.aux %*% xcoef
yscores = Y.aux %*% ycoef
return(list(xscores = xscores, yscores = yscores))
}
can.structure <- function (X, Y, scores, use="complete.obs") {
xscores <- scores$xscores
yscores <- scores$yscores
X.xscores = cor(X, xscores, use = use)
Y.xscores = cor(Y, xscores, use = use)
X.yscores = cor(X, yscores, use = use)
Y.yscores = cor(Y, yscores, use = use)
return(list(
X.xscores = X.xscores,
Y.xscores = Y.xscores,
X.yscores = X.yscores,
Y.yscores = Y.yscores))
}
gensvd <- function (Rxy, Rxx, Ryy, nu=p, nv=q)
{
p <- dim(Rxy)[1]
q <- dim(Rxy)[2]
if (missing(Rxx)) Rxx <- diag(p)
if (missing(Ryy)) Ryy <- diag(q)
if (dim(Rxx)[1] != dim(Rxx)[2]) stop("Rxx must be square")
if (dim(Ryy)[1] != dim(Ryy)[2]) stop("Ryy must be square")
s <- min(p, q)
if (max(abs(Rxx - t(Rxx)))/max(abs(Rxx)) > 1e-10) {
warning("Rxx not symmetric.")
Rxx <- (Rxx + t(Rxx))/2
}
if (max(abs(Ryy - t(Ryy)))/max(abs(Ryy)) > 1e-10) {
warning("Ryy not symmetric.")
Ryy <- (Ryy + t(Ryy))/2
}
Rxxinv <- solve(chol(Rxx))
Ryyinv <- solve(chol(Ryy))
Dform <- t(Rxxinv) %*% Rxy %*% Ryyinv
if (p >= q) {
result <- svd(Dform, nu=nu, nv=nv)
values <- result$d
Xmat <- Rxxinv %*% result$u
Ymat <- Ryyinv %*% result$v
}
else {
result <- svd(t(Dform), nu=nv, nv=nu)
values <- result$d
Xmat <- Rxxinv %*% result$v
Ymat <- Ryyinv %*% result$u
}
gsvdlist <- list(values=values, Xmat=Xmat, Ymat=Ymat)
return(gsvdlist)
}
stars <- function(p, width=30) {
p <- p/sum(p)
reps <- round(p * width / max(p))
res1 <- sapply(reps, function(x) paste(rep('*', x), sep="", collapse=""))
res2 <- sapply(reps, function(x) paste(rep(' ', width-x), sep="", collapse=""))
res <- paste(res1, res2, sep="")
res
}
print.cancor <- function(x, digits=max(getOption("digits") - 2, 3), ...) {
names <- x$names
cat("\nCanonical correlation analysis of:\n")
cat( "\t", x$dim$p, " ", names$set.names[1], " variables: ", paste(names$X, collapse=', '), "\n")
cat(" with\t", x$dim$q, " ", names$set.names[2], " variables: ", paste(names$Y, collapse=', '), "\n")
cat("\n")
canr <- x$cancor
lambda <- canr^2 / (1-canr^2)
pct = 100*lambda / sum(lambda)
cum = cumsum(pct)
stwidth <- getOption("width") - 40
scree <- stars(pct, width = min(30, stwidth))
canrdf <- data.frame("CanR"=canr, "CanRSQ"=canr^2, "Eigen"=lambda, "percent"=pct, "cum"=cum, "scree"=scree)
print(canrdf, digits=4)
tests <- Wilks.cancor(x)
print(tests, digits=digits)
invisible(x)
}
summary.cancor <- function(object, digits=max(getOption("digits") - 2, 3), ...) {
names <- object$names
print(object, digits=digits, ...)
cat("\nRaw canonical coefficients\n")
cat("\n ", names$set.names[1], " variables: \n")
print(object$coef$X, digits=digits)
cat("\n ", names$set.names[2], " variables: \n")
print(object$coef$Y, digits=digits)
}
scores <- function(x, ...) {
UseMethod("scores")
}
scores.cancor <- function(x, type=c("x", "y", "both", "list", "data.frame"), ...) {
type <- match.arg(type)
switch(type,
x = x$scores$X,
y = x$scores$Y,
both = x$scores,
list = x$scores,
data.frame = data.frame(x$scores$X, x$scores$Y)
)
}
coef.cancor <- function(object, type=c("x", "y", "both", "list"), standardize=FALSE, ...) {
coef <- object$coef
if (standardize) {
coef$X <- diag(sqrt(diag(cov(object$X)))) %*% coef$X
coef$Y <- diag(sqrt(diag(cov(object$Y)))) %*% coef$Y
rownames(coef$X) <- rownames(object$coef$X)
rownames(coef$Y) <- rownames(object$coef$Y)
}
type <- match.arg(type)
switch(type,
x = coef$X,
y = coef$Y,
both = list(coef$X, coef$Y),
list = list(coef$X, coef$Y)
)
} |
"modeG"<-function(postG, threshold=0){
id<-rownames(postG[[1]])
G<-as.list(1:length(postG))
names(G)<-names(postG)
n<-sum(postG[[1]][1,])
for(i in 1:length(G)){
an<-allele.names(as.genotype(colnames(postG[[i]])))
G[[i]]<-as.genotype(colnames(postG[[i]])[apply(postG[[i]],1,which.max)], alleles=an)
G[[i]][which(apply(postG[[i]],1,max)/n < threshold)]<-NA
}
list(G=G, id=id)
}
|
library(testthat)
library(rly)
context("Grammar with bad literal characters")
Parser <- R6::R6Class("Parser",
public = list(
tokens = c('NAME','NUMBER', 'PLUS','MINUS','TIMES','DIVIDE','EQUALS', 'LPAREN','RPAREN'),
precedence = list(c('left','+','-'),
c('left','*','/','MINUS'),
c('right','UMINUS')),
names = new.env(hash=TRUE),
p_statement_assign = function(doc='statement : NAME EQUALS expression', p) {
self$names[[as.character(p$get(2))]] <- p$get(4)
},
p_statement_expr = function(doc='statement : expression', p) {
cat(p$get(2))
cat('\n')
},
p_expression_binop = function(doc="expression : expression '+' expression
| expression '-' expression
| expression '*' expression
| expression '/' expression
| expression '**' expression", p) {
if(p$get(3) == '+') p$set(1, p$get(2) + p$get(4))
else if(p$get(3) == '-') p$set(1, p$get(2) - p$get(4))
else if(p$get(3) == '*') p$set(1, p$get(2) * p$get(4))
else if(p$get(3) == '/') p$set(1, p$get(2) / p$get(4))
},
p_expression_uminus = function(doc='expression : MINUS expression %prec UMINUS', p) {
p$set(1, -p$get(3))
},
p_expression_group = function(doc='expression : LPAREN expression RPAREN', p) {
p$set(1, p$get(3))
},
p_expression_number = function(doc='expression : NUMBER', p) {
p$set(1, p$get(2))
},
p_expression_name = function(doc='expression : NAME', p) {
p$set(1, self$names[[as.character(p$get(2))]])
},
p_error = function(p) {
cat(sprintf("Syntax error at '%s'", p$value))
}
)
)
test_that("literal", {
expect_output(expect_error(rly::yacc(Parser), "\\[YaccError\\]Unable to build parser"),
"ERROR .* \\[GrammarError\\]p_expression_binop: Literal token '\\*\\*' in rule expression may only be a single character")
}) |
context("Checking clean")
test_that("clean gives the desired output",{
x <- "I go \r\n to the \tnext line"
expect_true(clean(x) == "I go to the next line")
}) |
print.seqem <- function(x, ...) {
print(x$Imputed.DataFrames)
} |
`dist2Mats` <-
function(mat1,mat2,method,p=2){
n.row<-nrow(mat1)
mat<-rbind(mat1,mat2)
vec.dist<-dist(mat,method=method,p=p)
mat<-as.matrix(vec.dist)
mat[1:n.row,(n.row+1):nrow(mat)]
} |
rm(list=ls())
sources <- c("costFunctionReg.R","sigmoid.R",
"plotData.R","plotDecisionBoundary.R",
"mapFeature.R","predict.R")
for (i in 1:length(sources)) {
cat(paste("Loading ",sources[i],"\n"))
source(sources[i])
}
data <- read.table('ex2data2.txt', sep = ',')
X <- data[,c(1,2)]; y <- data[,3]
X <- as.matrix(X)
plotData(X, y,axLables = c('Microchip Test 1','Microchip Test 2'),
legLabels = c("y = 1","y = 0"))
X <- mapFeature(X[,1], X[,2])
initial_theta <- rep(0,dim(X)[2])
lambda <- 1
cost <- costFunctionReg(X, y, lambda)(initial_theta)
grd <- gradReg(X,y, lambda)(initial_theta)
cat(sprintf('Cost at initial theta (zeros): %f\n', cost))
cat(sprintf('\nProgram paused. Press enter to continue.\n'))
line <- readLines(con = stdin(),1)
initial_theta <- rep(0,dim(X)[2])
lambda <- 0
optimRes <- optim(par = initial_theta,
fn = costFunctionReg(X,y,lambda),
gr = gradReg(X,y,lambda),
method="BFGS",
control = list(maxit = 400))
theta <- optimRes$par
J <- optimRes$value
plotDecisionBoundary(theta, X, y, axLables = c('Microchip Test 1','Microchip Test 2'),
legLabels = c("y = 1","y = 0"))
p <- predict(theta, X)
cat(sprintf('Train Accuracy: %f\n', mean(p == y) * 100)) |
db_connection <- function(system_name = NULL,
db_type,
headless = FALSE,
from_env = TRUE,
settings = NULL,
timeout = 30,
logfile_dir = NULL,
lib_path = NULL) {
db_con <- NULL
stopifnot(
is.character(db_type),
is.logical(headless),
is.logical(from_env),
ifelse(is.null(settings), TRUE, is.list(settings)),
is.numeric(timeout),
ifelse(is.null(logfile_dir), TRUE, dir.exists(logfile_dir)),
ifelse(is.null(lib_path), TRUE, file.exists(lib_path))
)
error <- FALSE
tryCatch({
if (isTRUE(!is.null(settings) && is.list(settings))) {
from_env <- FALSE
}
if (isTRUE(from_env)) {
stopifnot(is.character(system_name))
system_name_uppercase <- toupper(system_name)
dbname <- Sys.getenv(paste0(system_name_uppercase, "_DBNAME"))
host <- Sys.getenv(paste0(system_name_uppercase, "_HOST"))
port <- Sys.getenv(paste0(system_name_uppercase, "_PORT"))
user <- Sys.getenv(paste0(system_name_uppercase, "_USER"))
password <- Sys.getenv(paste0(system_name_uppercase, "_PASSWORD"))
} else if (isFALSE(from_env)) {
stopifnot(is.list(settings),
length(settings) >= 4)
dbname <- settings$dbname
host <- settings$host
port <- settings$port
user <- settings$user
password <- settings$password
}
db_type <- toupper(db_type)
necessary_vars <- c("host", "port", "user", "password")
if (db_type != "ORACLE") {
necessary_vars <- c(necessary_vars, "dbname")
}
for (param in necessary_vars) {
if (!exists(param) ||
get(param) == "" || is.null(get(param))) {
feedback(
print_this = paste0("Missing '", param, "' for db-connection."),
type = "Error",
findme = "f762a865c8",
logfile_dir = logfile_dir,
headless = headless
)
error <<- TRUE
}
}
if (!error && db_type == "ORACLE") {
if (is.null(lib_path)) {
if (isTRUE(from_env)) {
lib_path <- Sys.getenv(paste0(system_name_uppercase, "_DRIVER"))
} else {
lib_path <- settings$lib_path
}
}
stopifnot(lib_path != "" || !is.null(lib_path))
drv <- RJDBC::JDBC("oracle.jdbc.OracleDriver",
classPath = lib_path)
if (isTRUE(from_env)) {
sid <- Sys.getenv(paste0(system_name_uppercase, "_SID"))
} else if (isFALSE(from_env)) {
sid <- settings$sid
}
if (is.null(sid) || sid == "") {
if (is.null(dbname) || dbname == "") {
feedback(
print_this = "Missing SID for db-connection to oracle.",
type = "Error",
findme = "0bba010a4a",
logfile_dir = logfile_dir,
headless = headless
)
error <<- TRUE
stop()
} else {
feedback(
print_this = paste0(
"`SID` is empty. Using the `dbname` ('",
dbname,
"') instead. But this might be wrong or cause errors!"
),
type = "Warning",
logfile_dir = logfile_dir,
headless = headless,
findme = "e38041e91c"
)
sid <- dbname
}
}
url <-
paste0("jdbc:oracle:thin:@//", host, ":", port, "/", sid)
db_con <- tryCatch({
conn <- DBI::dbConnect(
drv = drv,
url = url,
user = user,
password = password
)
conn
}, error = function(e) {
feedback(
print_this = paste0("Error while connection to oracle: ", e),
type = "Error",
logfile_dir = logfile_dir,
headless = headless,
findme = "0a50850ccd"
)
error <<- TRUE
conn <- NULL
return(conn)
})
} else if (!error && db_type == "POSTGRES") {
drv <- RPostgres::Postgres()
db_con <- tryCatch({
conn <- RPostgres::dbConnect(
drv = drv,
dbname = dbname,
host = host,
port = port,
user = user,
password = password,
connect_timeout = timeout
)
conn
}, error = function(e) {
feedback(
print_this = paste0("Error while connection to postgres: ", e),
type = "Error",
logfile_dir = logfile_dir,
headless = headless,
findme = "0a50850ccd"
)
error <<- TRUE
conn <- NULL
return(conn)
})
}
if (error || is.null(db_con)) {
feedback(
"DB connection error",
findme = "9431c8c61f",
logfile_dir = logfile_dir,
headless = headless,
type = "Error"
)
error <- TRUE
}
},
error = function(cond) {
feedback(
print_this = paste0("Error while trying to establish a db-connection: ",
cond),
type = "Error",
logfile_dir = logfile_dir,
headless = headless,
findme = "c16b60a6ff"
)
return(NULL)
})
if (error) {
DIZutils::feedback(
print_this = paste0(
"Error while trying to establish the db conncection.",
" Maybe the logging above is helpful for debugging?"
),
type = "Error",
findme = "29294c19e3",
logfile_dir = logfile_dir,
headless = headless
)
}
return(db_con)
} |
EmpiricalSemivariogram <-
function(ssn.object, varName,
nlag = 20, directions = c(0,45,90,135),
tolerance = 22.5, inc = 0, maxlag = 1e32, nlagcutoff = 1,
EmpVarMeth = "MethMoment")
{
if(class(ssn.object) == "influenceSSN") ssn.object <- ssn.object$ssn.object
data <- ssn.object@obspoints@SSNPoints[[1]]@point.data
var <- varName
x <- ssn.object@obspoints@SSNPoints[[1]]@point.coords[,1]
y <- ssn.object@obspoints@SSNPoints[[1]]@point.coords[,2]
n1 <- length(data[,1])
distance <- sqrt( ( matrix(x,nrow=n1,ncol=1) %*%
matrix(rep(1,times=n1),nrow=1,ncol=n1) -
matrix(rep(1,times=n1),nrow=n1,ncol=1) %*%
matrix(x,nrow=1,ncol=n1) )^2 +
( matrix(y,nrow=n1,ncol=1) %*%
matrix(rep(1,times=n1),nrow=1,ncol=n1) -
matrix(rep(1,times=n1),nrow=n1,ncol=1) %*%
matrix(y,nrow=1,ncol=n1) )^2 )
difx <- -(matrix(y,nrow=n1,ncol=1) %*%
matrix(rep(1,times=n1),nrow=1,ncol=n1) -
matrix(rep(1,times=n1),nrow=n1,ncol=1) %*%
matrix(y,nrow=1,ncol=n1))
signind <- -(matrix(x,nrow=n1,ncol=1) %*%
matrix(rep(1,times=n1),nrow=1,ncol=n1) -
matrix(rep(1,times=n1),nrow=n1,ncol=1) %*%
matrix(x,nrow=1,ncol=n1)) < 0
distance <- distance*1.0000000001
theta.deg <- acos(difx/distance)*180/pi
theta.deg[signind] <- 360-theta.deg[signind]
diff2 <- ( matrix(data[,var],nrow=n1,ncol=1) %*%
matrix(rep(1,times=n1),nrow=1,ncol=n1) -
matrix(rep(1,times=n1),nrow=n1,ncol=1) %*%
matrix(data[,var],nrow=1,ncol=n1) )^2
sqrtdiff <- sqrt(abs( matrix(data[,var],nrow=n1,ncol=1) %*%
matrix(rep(1,times=n1),nrow=1,ncol=n1) -
matrix(rep(1,times=n1),nrow=n1,ncol=1) %*%
matrix(data[,var],nrow=1,ncol=n1) ) )
if(EmpVarMeth == "CovMean") temp4cov <- data[,var] - mean(data[,var])
else temp4cov <- data[,var]
covprod <- (matrix(temp4cov,nrow=n1,ncol=1) %*%
matrix(rep(1,times=n1),nrow=1,ncol=n1)) *
(matrix(rep(1,times=n1),nrow=n1,ncol=1) %*%
matrix(temp4cov,ncol=n1,nrow=1))
distance <- matrix(distance, ncol = 1)
theta.deg <- matrix(theta.deg, ncol = 1)
diff2 <- matrix(diff2, ncol = 1)
sqrtdiff <- matrix(sqrtdiff, ncol = 1)
covprod <- matrix(covprod, ncol = 1)
indmax <- distance <= maxlag
distance <- distance[indmax,]
theta.deg <- theta.deg[indmax,]
diff2 <- diff2[indmax,]
sqrtdiff <- sqrtdiff[indmax,]
covprod <- covprod[indmax,]
maxd<-max(distance)
if( inc <= 0) inc <- maxd/nlag
ind <- distance==0
ndir <- length(directions)
store.results <- matrix(data = NA, ncol = 6,
dimnames = list(NULL, c("distance", "gamma", "np", "azimuth", "hx", "hy")))
for (j in 1:ndir) {
for ( i in 1:nlag){
if( (directions[j]-tolerance)<0 && (directions[j]+tolerance)>0 )
ind1 <- theta.deg >= 360+directions[j]-tolerance |
theta.deg < directions[j]+tolerance
else if( (directions[j]+tolerance)>360 && (directions[j]-tolerance)<360 )
ind1 <- theta.deg < directions[j]+tolerance-360 |
theta.deg >= directions[j]-tolerance
else
ind1 <- theta.deg >= directions[j]-tolerance &
theta.deg < directions[j]+tolerance
ind<-distance>(i-1)*inc & distance<=i*inc &
!is.na(theta.deg) & ind1
nclass <- sum(ind)
if(EmpVarMeth == "MethMoment") cv <- mean(diff2[ind])
if(EmpVarMeth == "RobustMean") cv <- ((mean(sqrtdiff[ind]))^4)/(.457 + .494/sum(ind))
if(EmpVarMeth == "RobustMedian") cv <- (median(sqrtdiff[ind]))^4/.457
if(EmpVarMeth == "Covariance" | EmpVarMeth == "CovMean") cv <- mean(covprod[ind])
mean.dis <- mean(distance[ind])
if(nclass > 0) store.results<-rbind(store.results,
c(mean.dis,cv,nclass,directions[j],0,0))
}
}
store.results[,"hx"]<-store.results[,"distance"]*sin(store.results[,"azimuth"]*pi/180)
store.results[,"hy"]<-store.results[,"distance"]*cos(store.results[,"azimuth"]*pi/180)
store.results[,"gamma"]<-store.results[,"gamma"]/2
ind <- store.results[,"np"] >= nlagcutoff
store.results <- store.results[ind,]
ind <- !is.na(store.results[,"hx"])
store.results <- store.results[ind,]
store.results <- as.data.frame(store.results)
class(store.results) <- "EmpiricalSemivariogramSSN"
store.results
} |
library(gpuR)
context("Custom OpenCL")
current_context <- set_device_context("cpu")
library(Rcpp)
set.seed(123)
ORDER <- 4
Aint <- matrix(sample(seq(10), ORDER^2, replace=TRUE), nrow=ORDER, ncol=ORDER)
Bint <- matrix(sample(seq(10), ORDER^2, replace=TRUE), nrow=ORDER, ncol=ORDER)
igpuA <- vclMatrix(Aint, type="integer")
igpuB <- vclMatrix(Bint, type="integer")
igpuC <- vclMatrix(0L, 4, 4, type="integer")
test_that("Custom OpenCL GEMM Kernel", {
has_cpu_skip()
Cint <- Aint %*% Bint
kernel <- system.file("CL", "basic_gemm.cl", package = "gpuR")
cl_args <- setup_opencl(c("vclMatrix", "vclMatrix", "vclMatrix"),
toupper(c("in", "in", "inout")),
list("iMatMult","iMatMult","iMatMult"),
list("A", "B", "C"))
custom_opencl(kernel, cl_args, type = "integer")
basic_gemm(igpuA, igpuB, igpuC)
expect_equivalent(igpuC[,], Cint,
info="integer matrix elements not equivalent")
})
setContext(current_context) |
"fitted.symcoca" <- function(object, which = c("y1","y2"), ...) {
`getFitted` <- function(x, take) {
TAKE <- ifelse(take == "Y", 1L, 2L)
rsum <- x$rowsum[[TAKE]]
csum <- x$colsum[[TAKE]]
tot <- sum(rsum)
exp <- rsum %*% t(csum) / tot
Yhat <- exp * (1 + (x$scores$site[[take]] %*%
t(x$scores$species[[take]])))
rownames(Yhat) <- rownames(x$scores$site[[take]])
Yhat
}
which <- selectWhich(which)
out <- list()
nam <- character(0)
if ("Y" %in% which) {
out$Y <- getFitted(object, take = "Y")
nam <- c(nam, object$nam.dat$namY)
}
if ("X" %in% which) {
out$X <- getFitted(object, take = "X")
nam <- c(nam, object$nam.dat$namX)
}
out$nam.dat <- nam
names(out$nam.dat) <- c("namY","namX")[c("Y","X") %in% which]
class(out) <- "fitted.symcoca"
out
} |
readVarColumns <- function(fiName, path=NULL, sep="\t", header=TRUE, emptyFields=NA, refCo=NULL, supNa=NULL, silent=FALSE, callFrom=NULL) {
fxNa <- .composeCallName(callFrom, newNa="readVarColumns")
fiName <- if(length(path) >0) {if(nchar(path) >0) file.path(path, fiName) else fiName} else fiName
if(!file.exists(fiName)) { dataOK <- FALSE
warning(" PROBLEM : Can't find file '",fiName,"'")
} else {
dataOK <- TRUE
if(length(header) !=1) header <- FALSE
if(!is.logical(header)) { dataOK <- FALSE
warning(fxNa," Invalid command: argument 'header' should be logical and of length=1")} }
if(dataOK) {
out <- try(scan(fiName, what="character", sep="\n"), silent=TRUE)
if("try-error" %in% class(out)) { dataOK <- FALSE
warning(fxNa," Did NOT succed reading file '",fiName,"'")}}
if(dataOK) {
out <- strsplit(out, sep)
maxCo <- max(sapply(out, length))
out <- t(sapply(out, function(x,maxC) {if(length(x)==maxC) x else {z <- rep("",maxC); z[1:length(x)] <- x; z}}, maxC=maxCo))
supPep <- which(out[1,]=="")
if(length(supNa) !=1) { supNa0 <- min(supPep ,na.rm=TRUE)
supNa <- if(supNa0 >1) out[1, min(supPep, na.rm=TRUE) -1] else ((1:ncol(out))[-supPep])[1]}
out[1, supPep] <- paste(supNa, 1 +1:length(supPep),sep="_")
if(nrow(out) <2) { dataOK <- FALSE
warning(" PROBLEM : data seem to be empty (header only ?)")} }
if(dataOK) {
testNum <- function(x) all(length(grep("(^([0-9]+)|(^[+-][0-9]+)|(^\\.[0-9]+))((\\.[0-9]+)?)(([eE][+-]?[0-9]+)?)$",x)) ==length(x))
numCol <- apply(out[-1,], 2, testNum)
if(length(refCo) !=1) {refCo <- min(which(!numCol))
if(isFALSE(silent)) message(fxNa," setting 'refCo' to '",out[1,refCo],"'")}
dupNa <- duplicated(out[1,])
useLi <- if(header) 2:nrow(out) else 1:nrow(out)
colNa <- if(header) {if(any(dupNa)) correctToUnique(out[1,]) else out[1,]} else NULL
dupNa <- duplicated(out[useLi,refCo])
rowNa <- if(any(dupNa)) correctToUnique(out[useLi,refCo]) else out[useLi,refCo]
if(header) out <- out[-1,]
if(length(dim(out)) <2) out <- matrix(out, nrow=1, dimnames=list(rowNa, names(out))) else dimnames(out) <- list(rowNa,colNa)
out } }
|
treeSlice<-function(tree,slice=NULL,trivial=FALSE,prompt=FALSE,...){
if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".")
if(hasArg(orientation)) orientation<-list(...)$orientation
else orientation<-"tipwards"
if(prompt){
cat("Inside prompt.\n")
plotTree(tree,mar=c(3.1,rep(0.1,3)),...)
axis(1)
cat("Click at the tree height where cutting is desired...\n")
flush.console()
xy<-unlist(locator(1))
slice<-xy[1]
cat(paste("Slice height is ",signif(slice,6),". Thank you!\n",sep=""))
flush.console()
lines(rep(slice,2),par()$usr[3:4],lty="dashed")
obj<-get("last_plot.phylo",envir=.PlotPhyloEnv)
X<-cbind(obj$xx[obj$edge[,1]],obj$xx[obj$edge[,2]])
y<-obj$yy[obj$edge[,2]]
if(trivial){
for(i in 1:nrow(X)) if(X[i,1]<slice&&X[i,2]>slice)
points(slice,y[i],pch=19)
} else {
for(i in 1:nrow(X))
if(X[i,1]<slice&&X[i,2]>slice&&obj$edge[i,2]>Ntip(tree))
points(slice,y[i],pch=19)
}
}
tree<-reorder(tree)
H<-nodeHeights(tree)
edges<-which(H[,2]>slice&H[,1]<slice)
nodes<-tree$edge[edges,2]
if(orientation=="tipwards"){
if(!trivial) nodes<-nodes[nodes>length(tree$tip)]
trees<-list()
class(trees)<-"multiPhylo"
for(i in 1:length(nodes)){
if(nodes[i]>Ntip(tree)){
trees[[i]]<-extract.clade(tree,node=nodes[i])
trees[[i]]$root.edge<-H[which(tree$edge[,2]==nodes[i]),2]-slice
} else {
z<-list(edge=matrix(c(2,1),1,2),
edge.length=H[which(tree$edge[,2]==nodes[i]),2]-slice,
tip.label=tree$tip.label[nodes[i]],Nnode=1L)
class(z)<-"phylo"
trees[[i]]<-z
}
}
return(trees)
} else if(orientation=="rootwards"){
obj<-tree
obj$node.label<-1:obj$Nnode+Ntip(obj)
if(any(nodes<=Ntip(obj))){
tips<-nodes[nodes<=Ntip(obj)]
tips<-obj$tip.label[tips]
nodes<-nodes[nodes>Ntip(obj)]
} else tips<-NULL
if(length(nodes)>0){
for(i in 1:length(nodes)){
nn<-which(obj$node.label==nodes[i])+Ntip(obj)
parent<-getParent(obj,nn)
bp<-slice-nodeheight(obj,parent)
obj<-splitTree(obj,list(node=nn,bp=bp))[[1]]
obj$tip.label[obj$tip.label=="NA"]<-nodes[i]
}
}
if(!is.null(tips[1])){
for(i in 1:length(tips)){
nn<-which(obj$tip.label==tips[i])
parent<-getParent(obj,nn)
obj$edge.length[which(obj$edge[,2]==nn)]<-slice-nodeheight(obj,parent)
}
}
return(obj)
}
}
getParent<-function(tree,node){
ind<-which(tree$edge[,2]==node)
if(length(ind)>0) pp<-tree$edge[which(tree$edge[,2]==node),1]
else {
pp<-NULL
cat("node is the root. returning NULL\n")
}
pp
}
|
Return <- COUNTIF(iris$Species,"virginica")
expect_equal(Return,50L) |
local_edition(3)
test_that("file.path.ci returns correctly no matter the case", {
tmp_dir <- withr::local_tempdir()
expect_equal(file.path.ci(tmp_dir, "global.R"), file.path(tmp_dir, "global.R"))
withr::local_dir(tmp_dir)
expect_equal_file <- function(file, tmp_dir, default = file) {
withr::local_file(file); xfun::write_utf8("
expect_equal(file.path.ci(!!tmp_dir, "global.R"), file.path(!!tmp_dir, !!default))
}
expect_equal_file("global.R", tmp_dir)
if (xfun::is_linux()) expect_equal_file("global.r", tmp_dir)
expect_equal_file("global.R", "donotexist")
expect_equal_file("global.Rmd", tmp_dir, "global.R")
})
test_that("set_current_theme() informs shiny::getCurrentTheme()", {
expect_null(shiny::getCurrentTheme())
theme <- bslib::bs_theme()
set_current_theme(theme)
expect_equal(theme, shiny::getCurrentTheme())
set_current_theme(NULL)
expect_null(shiny::getCurrentTheme())
}) |
context("captions")
library(utils)
library(xml2)
library(officer)
library(rmarkdown)
rmd_str <- c("```{r setup, include=FALSE}", "knitr::opts_chunk$set(echo=FALSE)",
"```", "", "```{r libs}", "library(flextable)", "```", "", "Table \\@ref(tab:table1).",
"", "```{r table1, tab.cap=\"a table caption\", tab.cap.style=\"Table Caption\"}",
"df <- head(iris)", "ft <- flextable(df)", "ft", "```", "", "Table \\@ref(tab:table2).",
"", "```{r table2}", "ft <- set_caption(", " x = ft, ", " caption =\"a table caption\", ",
" style = \"Table Caption\")", "ft", "```", "")
rmd_str <-
c("---",
"title: flextable",
"---", rmd_str)
rmd_file <- tempfile(fileext = ".Rmd")
writeLines(rmd_str, rmd_file)
test_that("word_document2 captions", {
skip_if_not_installed("bookdown")
skip_if_not(pandoc_version() >= numeric_version("2"))
template <- tempfile(fileext = ".docx")
print(read_docx(), target = template)
render(rmd_file, output_format = bookdown::word_document2(reference_docx=template),
output_file = "caption.docx", quiet = TRUE)
dir_xml <- tempfile(pattern = "xml_tmp")
officer::unpack_folder(file.path(dirname(rmd_file), "caption.docx"), dir_xml)
xml_file <- file.path(dir_xml, "/word/document.xml" )
x <- read_xml(xml_file)
style_nodes <- xml_find_all(x, "/w:document/w:body/w:tbl/preceding-sibling::*[1]/w:pPr/w:pStyle[@w:val='TableCaption']")
expect_length(style_nodes, 2)
txt_nodes <- xml_find_all(x, "/w:document/w:body/w:tbl/preceding-sibling::*[1]/w:r/w:t")
expect_equal(
sum(xml_text(txt_nodes) %in% "a table caption"),
2
)
})
test_that("html_document2 captions", {
skip_if_not_installed("bookdown")
skip_if_not(pandoc_version() >= numeric_version("2"))
render(rmd_file, output_format = bookdown::html_document2(),
output_file = "caption.html", quiet = TRUE)
doc <- read_html(file.path(dirname(rmd_file), "caption.html"))
captions_ids <- xml_find_all(doc, "//table/caption//span")
expect_equal(xml_attr(captions_ids, "id"), c("tab:table1", "tab:table2"))
txt <- gsub("[\n\r]+", "", xml_text(xml_find_all(doc, "//table/caption")))
expect_equal(txt, c("Table 1: a table caption", "Table 2: a table caption"))
})
rmd_str <-
c("```{r include=FALSE}", "knitr::opts_chunk$set(echo=FALSE)",
"library(flextable)", "```", "", "```{r tab.id=\"table1\", tab.cap=\"a table caption\", tab.cap.style=\"Table Caption\"}",
"df <- head(airquality)", "ft <- flextable(df)", "ft", "```",
"", "```{r table2}", "library(officer)", "autonum <- run_autonum(seq_id = \"tab\", bkm = \"mtcars\")",
"ft <- set_caption(ft, caption =\"a table caption\", autonum = autonum, style = \"Table Caption\")",
"ft", "```")
rmd_str <-
c("---",
"title: flextable",
"---", rmd_str)
rmd_file <- tempfile(fileext = ".Rmd")
writeLines(rmd_str, rmd_file)
test_that("word_document captions", {
skip_if_not(pandoc_version() >= numeric_version("2"))
template <- tempfile(fileext = ".docx")
print(read_docx(), target = template)
render(rmd_file, output_format = rmarkdown::word_document(reference_docx=template),
output_file = "caption.docx", quiet = TRUE)
dir_xml <- tempfile(pattern = "xml_tmp")
officer::unpack_folder(file.path(dirname(rmd_file), "caption.docx"), dir_xml)
xml_file <- file.path(dir_xml, "/word/document.xml" )
x <- read_xml(xml_file)
xml_find_all(x, "/w:document/w:body/w:tbl/preceding-sibling::w:p[1]/w:bookmarkStart[@w:name='table1']")
bookmarks <- xml_find_all(x, "/w:document/w:body/w:tbl/preceding-sibling::w:p[1]/w:bookmarkStart")
expect_length(bookmarks, 2)
expect_equal(xml_attr(bookmarks, "name"), c("table1", "mtcars"))
wordfields <- xml_find_all(x, "/w:document/w:body/w:tbl/preceding-sibling::w:p[1]/w:r/w:instrText")
expect_equal(xml_text(wordfields), c("SEQ tab \\* Arabic", "SEQ tab \\* Arabic"))
}) |
context("specify")
one_nonshift_mean <- mtcars_df %>% specify(response = mpg)
one_nonshift_prop <- mtcars_df %>% specify(response = am, success = "1")
two_means_boot <- mtcars_df %>% specify(mpg ~ am)
two_props_boot <- mtcars_df %>% specify(am ~ vs, success = "1")
slope_boot <- mtcars_df %>% specify(mpg ~ hp)
test_that("auto `type` works (specify)", {
expect_equal(attr(one_nonshift_mean, "type"), "bootstrap")
expect_equal(attr(one_nonshift_prop, "type"), "bootstrap")
expect_equal(attr(two_means_boot, "type"), "bootstrap")
expect_equal(attr(two_props_boot, "type"), "bootstrap")
expect_equal(attr(slope_boot, "type"), "bootstrap")
})
test_that("data argument", {
expect_error(specify(blah ~ cyl))
expect_error(specify(1:3))
expect_is(mtcars_df, "data.frame")
expect_error(specify(mtcars_df, mtcars_df$mpg))
})
test_that("response and explanatory arguments", {
expect_error(specify(mtcars_df, response = blah), "response.*cannot be found")
expect_error(
specify(mtcars_df, response = "blah"), "response.*bare.*not a string"
)
expect_error(
specify(mtcars_df, formula = mpg ~ blah), "explanatory.*cannot be found"
)
expect_error(specify(mtcars_df, blah2 ~ cyl), "response.*cannot be found")
expect_error(specify(mtcars_df),
"Please supply a response variable that is not `NULL`.")
expect_error(specify(mtcars_df, formula = mpg ~ mpg), "different")
expect_error(
specify(mtcars_df, formula = "mpg" ~ cyl), "response.*bare.*not a string"
)
expect_error(
specify(mtcars_df, formula = mpg ~ "cyl"), "explanatory.*bare.*not a string"
)
expect_silent(specify(mtcars_df, formula = mpg ~ cyl))
expect_error(specify(mtcars_df, formula = NULL ~ cyl),
"Please supply a response variable that is not `NULL`.")
})
test_that("success argument", {
expect_error(specify(mtcars_df, response = vs, success = 1))
expect_error(specify(mtcars_df, response = vs, success = "bogus"))
expect_error(specify(mtcars_df, response = mpg, success = "1"))
expect_error(specify(mtcars_df, response = cyl, success = "4"))
expect_error(specify(mtcars_df, response = am))
})
test_that("sensible output", {
expect_equal(ncol(specify(mtcars_df, formula = mpg ~ NULL)), 1)
expect_equal(ncol(specify(mtcars_df, formula = mpg ~ wt)), 2)
expect_equal(class(specify(mtcars_df, formula = mpg ~ wt))[1], "infer")
})
test_that("formula argument is a formula", {
expect_error(specify(mtcars_df, formula = "vs", success = 1))
expect_error(specify(mtcars, am, success = "1"))
expect_error(specify(mtcars, response = am, "1"))
expect_silent({
mtcars %>%
dplyr::mutate(am = factor(am)) %>%
specify(response = am, success = "1")
})
})
test_that("is_complete works", {
some_missing <- data.frame(vec = c(NA, 2, 3))
expect_warning(specify(some_missing, response = vec))
})
test_that("specify doesn't have NSE issues (
expect_silent(specify(tibble(x = 1:10), x ~ NULL))
})
test_that("specify messages when dropping unused levels", {
expect_message(
gss %>%
dplyr::filter(partyid %in% c("rep", "dem")) %>%
specify(age ~ partyid),
"Dropping unused factor levels c\\(\"ind\", \"other\""
)
expect_message(
gss %>%
dplyr::filter(partyid %in% c("rep", "dem")) %>%
specify(partyid ~ age),
"Dropping unused factor levels c\\(\"ind\", \"other\""
)
expect_message(
gss %>%
dplyr::filter(partyid %in% c("rep", "dem")) %>%
specify(partyid ~ NULL),
"Dropping unused factor levels c\\(\"ind\", \"other\""
)
expect_silent(
gss %>%
dplyr::filter(partyid %in% c("rep", "dem")) %>%
specify(age ~ NULL)
)
})
test_that("user can specify multiple explanatory variables", {
x <- gss %>% specify(hours ~ sex + college)
expect_true(inherits(x, "infer"))
expect_true(inherits(explanatory_variable(x), "tbl_df"))
expect_true(inherits(explanatory_name(x), "character"))
expect_true(inherits(explanatory_expr(x), "call"))
expect_equal(explanatory_name(x), c("sex", "college"))
expect_equal(response_name(x), "hours")
}) |
STLginhom <- function(X,lambda,normalize=FALSE,r=NULL,t=NULL,nxy=10){
if (!inherits(X, "stlpp")) stop("X should be from class stlpp")
Y <- as.lpp.stlpp(X)
l <- domain(Y)
tleng <- summary(l)$totlength
n <- npoints(Y)
a <- X$time[1]
b <- X$time[2]
trange <- b-a
timev <- X$data$t
sdist <- pairdist(Y)
tdist <- as.matrix(dist(timev))
toler <- default.linnet.tolerance(l)
ml <- matrix(1, n, n)
for (j in 1:n) {
ml[-j, j] <- countends(l, Y[-j], sdist[-j, j], toler = toler)
}
mtplus <- matrix(timev, n, n, byrow = T) + tdist
mtminus <- matrix(timev, n, n, byrow = T) - tdist
mtedge <- (mtplus <= b) + (mtminus >= a)
diag(mtedge) <- 1
lamden <- outer(lambda,lambda,FUN = "*")
edgetl <- mtedge * ml * lamden
maxs <- 0.7*max(sdist[!is.infinite(sdist)])
maxt <- 0.7*(trange/2)
if(is.null(r)) r <- seq((maxs/nxy),maxs,by=(maxs-(maxs/nxy))/(nxy-1))
if(is.null(t)) t <- seq((maxt/nxy),maxt,by=(maxt-(maxt/nxy))/(nxy-1))
g <- matrix(NA, nrow = nxy, ncol = nxy)
no <- sdist == 0 & tdist == 0 | sdist==Inf | sdist>maxs | tdist>maxt
bwl <- bw.nrd0(as.numeric(sdist[!no]))
bwt <- bw.nrd0(as.numeric(tdist[!no]))
for (i in 1:length(r)) {
for (j in 1:length(t)) {
outl <- dkernel(as.numeric(sdist[!no] - r[i]),
sd = bwl)
outt <- dkernel(as.numeric(tdist[!no] - t[j]),
sd = bwt)
g1 <- outl * outt/(edgetl[!no])
g[i, j] <- sum(g1[!is.na(g1) & !is.infinite(g1)])
}
}
if(normalize){
revrho <- outer(1/lambda,1/lambda,FUN = "*")
appx <- (tleng*trange)/(sum(revrho[lower.tri(revrho, diag = FALSE)])*2)
gval <- g * appx
}
else {
gval <- g/(tleng*trange)
}
gout <- list(ginhom = gval, gtheo = matrix(rep(1, length(t) *
length(r)), ncol = nxy), r = r, t = t)
class(gout) <- c("sumstlpp")
attr(gout,"nxy") <- nxy
return(gout)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.