code
stringlengths 1
13.8M
|
---|
`ensembleItime` <-
function (x) {
UseMethod("ensembleItime")
} |
context("Testing Bounds")
test_that("Significance level of bounds",
{
data("darfur")
model <- lm(peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village, data = darfur)
out <- ovb_bounds(model, treatment = "directlyharmed", benchmark_covariates = "female")
plot.env$treatment <- NULL
expect_error(add_bound_to_contour(out))
expect_error(add_bound_to_contour(model = model, benchmark_covariates = "female"))
out.g <- ovb_bounds(model, treatment = "directlyharmed", benchmark_covariates = list(female = "female"))
out2 <- structure(list(bound_label = "1x female", r2dz.x = 0.00916428667504862,
r2yz.dx = 0.12464092303637, treatment = "directlyharmed",
adjusted_estimate = 0.0752202712144491,
adjusted_se = 0.0218733277437572, adjusted_t = 3.43890386024675,
adjusted_lower_CI = 0.0322829657274445, adjusted_upper_CI = 0.118157576701454),
row.names = c(NA, -1L), class = c("ovb_bounds","data.frame"))
expect_equivalent(out, out2)
expect_equivalent(out2, out.g)
out <- ovb_bounds(model, treatment = "directlyharmed", benchmark_covariates = "female", alpha = 0.2)
out2 <- structure(list(bound_label = "1x female", r2dz.x = 0.00916428667504862,
r2yz.dx = 0.12464092303637, treatment = "directlyharmed",
adjusted_estimate = 0.0752202712144491,
adjusted_se = 0.0218733277437572, adjusted_t = 3.43890386024675,
adjusted_lower_CI = 0.0471648038348768, adjusted_upper_CI = 0.103275738594021),
row.names = c(NA, -1L),
class = c("ovb_bounds", "data.frame"))
expect_equivalent(out, out2)
out <- ovb_bounds(model, treatment = "directlyharmed", benchmark_covariates = "female", alpha = 1)
expect_equal(out$adjusted_estimate, out$adjusted_lower_CI)
expect_equal(out$adjusted_estimate, out$adjusted_upper_CI)
})
test_that("Bounds error",
{
expect_error(ovb_partial_r2_bound.numeric(r2dxj.x = "a", r2yxj.dx = .2))
expect_error(ovb_partial_r2_bound.numeric(r2dxj.x = .1, r2yxj.dx = 2))
expect_warning(ovb_partial_r2_bound.numeric(r2dxj.x = .1, r2yxj.dx = 1))
expect_error(ovb_partial_r2_bound.numeric(r2dxj.x = 1, r2yxj.dx = .1))
data("darfur")
model <- lm(peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village, data = darfur)
expect_error(ovb_partial_r2_bound.lm(model = model, treatment = 2, benchmark_covariates = "female"))
expect_error(ovb_partial_r2_bound.lm(model = model, treatment = "directlyharmed", benchmark_covariates = 2))
expect_error(ovb_partial_r2_bound.lm(model = model, treatment = c("a","b"),
benchmark_covariates = 2))
expect_error(ovb_partial_r2_bound.lm(model = model, treatment = "directlyharmed",
benchmark_covariates = list(1)))
expect_error(ovb_partial_r2_bound.lm(model = model, treatment = "directlyharmed",
benchmark_covariates = list(a = 1, c= "a")))
})
test_that("Bounds warning",
{
model <- lm(peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village, data = darfur)
b1 <- ovb_bounds(model, treatment = "directlyharmed", benchmark_covariates = "female")
ovb_contour_plot(model, treatment = "female")
expect_warning(add_bound_to_contour(b1))
expect_warning(add_bound_to_contour(model = model,
treatment = "directlyharmed",
benchmark_covariates = "female"))
b1 <- ovb_bounds(model, treatment = "directlyharmed", benchmark_covariates = "female")
ovb_contour_plot(model, treatment = "female", sensitivity.of = "t-value")
expect_warning(add_bound_to_contour(b1))
b2 <- ovb_partial_r2_bound(.1, .1)
add_bound_to_contour(b2)
})
test_that("Group benchmarks",
{
model <- lm(peacefactor ~ directlyharmed + age + farmer_dar + herder_dar +
pastvoted + hhsize_darfur + female + village, data = darfur)
check1 <- ovb_contour_plot(model = model,
treatment = "directlyharmed",
benchmark_covariates = list(`fem+past` = c("female", "pastvoted")))
out <- sensemakr(model = model,
treatment = "directlyharmed",
benchmark_covariates = list(`fem+past` = c("female", "pastvoted")))
check2 <- plot(out)
expect_equal(check1, check2)
})
test_that("Group benchmarks - simulations",
{
rm(list = ls())
set.seed(10)
n <- 1e3
z1 <- resid_maker(n, rep(1, n))
z2 <- resid_maker(n, z1)
x1 <- resid_maker(n, cbind(z1, z2))
x2 <- resid_maker(n, cbind(z1, z2, x1))
d <- 2*x1 + 1*x2 + 2*z1 + 1*z2 + resid_maker(n, cbind(z1, z2, x1, x2))*5
y <- 2*x1 + 1*x2 + 2*z1 + 1*z2 + resid_maker(n, cbind(z1, z2, x1, x2, d))*5
model <- lm(y ~ d + x1 + x2)
r2yx <- group_partial_r2(lm(y ~ d + x1 + x2), covariates = c("x1", "x2"))
r2yz <- group_partial_r2(lm(y ~ d + z1 + z2), covariates = c("z1", "z2"))
ky <- r2yz/r2yx
r2dz <- group_partial_r2(lm(d ~ z1 + z2), covariates = c("z1", "z2"))
r2dx <- group_partial_r2(lm(d ~ x1 + x2), covariates = c("x1", "x2"))
kd <- r2dz/r2dx
out <- sensemakr(model = model, treatment = "d", benchmark_covariates = list(X = c("x1", "x2")), kd =kd, ky= ky)
expect_equivalent(out$bounds$adjusted_estimate, 0)
rm(list = ls())
rcoef <- function() runif(1, -2, 2)
n <- 1e3
z1 <- resid_maker(n, rep(1, n))
z2 <- resid_maker(n, z1)
x1 <- resid_maker(n, cbind(z1, z2))
x2 <- resid_maker(n, cbind(z1, z2, x1))
d <- rcoef()*x1 + rcoef()*x2 + rcoef()*z1 + rcoef()*z2 + resid_maker(n, cbind(z1, z2, x1, x2))*5
y <- rcoef()*x1 + rcoef()*x2 + rcoef()*z1 + rcoef()*z2 + resid_maker(n, cbind(z1, z2, x1, x2, d))*5
model <- lm(y ~ d + x1 + x2)
r2yx <- group_partial_r2(lm(y ~ d + x1 + x2), covariates = c("x1", "x2"))
r2yz <- group_partial_r2(lm(y ~ d + z1 + z2), covariates = c("z1", "z2"))
ky <- r2yz/r2yx
r2dz <- group_partial_r2(lm(d ~ z1 + z2), covariates = c("z1", "z2"))
r2dx <- group_partial_r2(lm(d ~ x1 + x2), covariates = c("x1", "x2"))
kd <- r2dz/r2dx
out <- sensemakr(model = model, treatment = "d", benchmark_covariates = list(X = c("x1", "x2")), kd =kd, ky= ky)
full.model <- lm(y ~ d + x1 + x2 + z1 + z2)
true_r2yz.dx <- group_partial_r2(full.model, covariates = c("z1", "z2"))
full.model.d <-lm(d ~ x1 + x2 + z1 + z2)
true_r2dz.x <- group_partial_r2(full.model.d, covariates = c("z1", "z2"))
expect_equal(out$bounds$r2dz.x, true_r2dz.x)
expect_true(out$bounds$r2yz.dx > true_r2yz.dx)
})
test_that("Factor treatment and factor benchmarks",{
data(mtcars)
mtcars$cyl <- as.factor(mtcars$cyl)
mtcars$gear <- as.factor(mtcars$gear)
model <- lm(mpg ~ cyl + gear, data = mtcars)
sens <- sensemakr(model, treatment = "cyl6", benchmark_covariates = list(gear = c("gear4", "gear5")))
sens
coef.summ <- coef(summary(model))
t.value <- coef.summ["cyl6", "t value"]
rv <- robustness_value(t.value, model$df.residual)
rv.check <- sens$sensitivity_stats$rv_q
expect_equal(rv, rv.check)
r2y <- group_partial_r2(model, covariates = c("gear4", "gear5"))
mtcars <- cbind(mtcars, model.matrix(~cyl + gear + 0, data = mtcars))
treat.model <- lm(cyl6 ~ cyl8 + gear4 + gear5, data= mtcars)
r2d <- group_partial_r2(treat.model, covariates = c("gear4", "gear5"))
bounds <- sensemakr:::ovb_partial_r2_bound.numeric(r2dxj.x = r2d, r2yxj.dx = r2y)
bounds.check <- sens$bounds
expect_equal(bounds$r2dz.x, bounds.check$r2dz.x)
expect_equal(bounds$r2yz.dx, bounds.check$r2yz.dx)
adj.est<- adjusted_estimate(model, treatment = "cyl6", r2dz.x = bounds$r2dz.x, r2yz.dx = bounds$r2yz.dx)
expect_equivalent(adj.est, bounds.check$adjusted_estimate)
}) |
if (!isGeneric("safs")) {
setGeneric("safs")
}
setMethod("safs", signature(x = "Speclib"),
definition = function(x,
y,
cutoff = .95,
returnData = TRUE,
na.rm = FALSE,
...)
{
y_missing <- missing(y)
if (y_missing)
{
y <- .getResponseVar(x,
advice = c("safs", "setResponse",
"This is only required if you do not specify 'y'."))
}
useSIAsPredicants <- !is.na(.getPredicantVar(x, stopifmissing = FALSE))[1]
x_dat <- as.data.frame(spectra(x))
if (is.finite(cutoff))
{
x_dat <- x_dat[, -findCorrelation(cor(x_dat), cutoff)]
x_dat <- as.data.frame(x_dat)
}
spec_nam <- names(x_dat)
if (useSIAsPredicants)
{
addVar <- .getPredicantVar(x)
if (na.rm)
{
valid_data <- apply(addVar, 2, function(x) all(is.finite(x)))
if (any(!valid_data))
{
cat(paste("Remove following variables because at least one sample is not finite:\n"))
print(names(addVar)[!valid_data])
addVar <- addVar[,valid_data]
}
}
x_dat <- cbind(x_dat, addVar)
if (nlevels(as.factor(names(x_dat))) != ncol(x_dat))
{
print(names(x_dat))
stop("Names in predictor data.frame not unique")
}
}
dots <- list(...)
res <- if (!any(names(dots) == "safsControl"))
safs(x_dat, y, safsControl = safsControl(functions = rfSA), ...)
else
safs(x_dat, y, ...)
if (!returnData)
return(res)
pred <- res$optVariables
x <- x[,sapply(spec_nam, FUN = function(x, pred) any(pred == x), pred), usagehistory = FALSE]
if (useSIAsPredicants)
{
warning(paste("SI data.frame will only contain relevant variables",
if (y_missing) " and the response variable", ".", sep = ""))
if (y_missing)
pred <- c(pred, names(SI(x))[.getCaretParameter(x, "response")])
cols_keep <- sapply(names(SI(x)), FUN = function(x, pred) any(pred == x), pred)
if (sum(cols_keep) > 0)
{
if (sum(cols_keep) == 1)
{
tmp <- as.data.frame(matrix(SI(x)[,cols_keep], ncol = 1))
names(tmp) <- names(SI(x))[cols_keep]
} else {
tmp <- SI(x)[,sapply(names(SI(x)), FUN = function(x, pred) any(pred == x), pred)]
}
SI(x) <- tmp
}
x <- .updateCaretParameters(x, c("response", "predictor"))
}
x <- .setCaretParameter(x, "safs_result", res)
usagehistory(x) <- "Supervised feature selection using simulated annealing"
return(x)
})
setMethod("safs", signature(x = "Nri"),
definition = function(x,
y,
cutoff = .95,
returnData = TRUE,
na.rm = FALSE,
...)
{
y_missing <- missing(y)
if (y_missing)
{
y <- .getResponseVar(x,
advice = c("safs", "setResponse",
"This is only required if you do not specify 'y'."))
}
useSIAsPredicants <- !is.na(.getPredicantVar(x, stopifmissing = FALSE))[1]
nri_vals_all <- as.data.frame(x)
if (is.finite(cutoff))
{
nri_vals <- nri_vals_all[, -findCorrelation(cor(nri_vals_all), cutoff)]
} else {
nri_vals <- nri_vals_all
}
nri_vals <- as.data.frame(nri_vals)
if (useSIAsPredicants)
{
addVar <- .getPredicantVar(x)
if (na.rm)
{
valid_data <- apply(addVar, 2, function(x) all(is.finite(x)))
if (any(!valid_data))
{
cat(paste("Remove following variables because at least one sample is not finite:\n"))
print(names(addVar)[!valid_data])
addVar <- addVar[,valid_data]
}
}
nri_vals <- cbind(nri_vals, addVar)
if (nlevels(as.factor(names(nri_vals))) != ncol(nri_vals))
{
print(names(nri_vals))
stop("Names in predictor data.frame not unique")
}
}
dots <- list(...)
res <- if (!any(names(dots) == "safsControl"))
safs(nri_vals, y, safsControl = safsControl(functions = rfSA), ...)
else
safs(nri_vals, y, ...)
if (!returnData)
return(res)
pred <- res$optVariables
is.pred.col <- sapply(names(nri_vals_all), FUN = function(x, pred) any(pred == x), pred)
values <- numeric(length = length(x@nri@values))
values[] <- NA
incr <- length(x@nri@values)/nrow(nri_vals)
for (i in 1:ncol(nri_vals_all))
{
if (is.pred.col[i])
{
index <- seq(i, length(values), incr)
values[index] <- nri_vals_all[,i]
}
}
x@nri <- distMat3D(values, ncol = ncol(x@nri), nlyr = nrow(nri_vals))
if (useSIAsPredicants)
{
warning(paste("SI data.frame will only contain relevant variables",
if (y_missing) " and the response variable", ".", sep = ""))
if (y_missing)
pred <- c(pred, names(SI(x))[.getCaretParameter(x, "response")])
cols_keep <- sapply(names(SI(x)), FUN = function(x, pred) any(pred == x), pred)
if (sum(cols_keep) > 0)
{
if (sum(cols_keep) == 1)
{
tmp <- as.data.frame(matrix(SI(x)[,cols_keep], ncol = 1))
names(tmp) <- names(SI(x))[cols_keep]
} else {
tmp <- SI(x)[,sapply(names(SI(x)), FUN = function(x, pred) any(pred == x), pred)]
}
SI(x) <- tmp
}
x <- .updateCaretParameters(x, c("response", "predictor"))
}
return(.setCaretParameter(x, "safs_result", res))
})
setMethod("safs", signature(x = "Specfeat"),
definition = function(x,
y,
cutoff = .95,
returnData = TRUE,
na.rm = FALSE,
...)
{
x <- .as.speclib.specfeat(x, na.rm = na.rm)
if (missing(y))
{
return(safs(x, cutoff = cutoff, returnData = returnData, na.rm = na.rm, ...))
} else {
return(safs(x, y, cutoff = cutoff, returnData = returnData, na.rm = na.rm, ...))
}
})
get_safs <- function(x)
.getCaretParameter(x, "safs_result") |
summary.radf_obj <- function(object, cv = NULL, ...) {
cv <- cv %||% retrieve_crit(object)
assert_class(cv, "radf_cv")
assert_match(object, cv)
ret <- summary_radf(cv, object, ...)
ret %>%
add_attr(
minw = get_minw(object),
lag = get_lag(object),
method = get_method(cv),
iter = get_iter(cv)
) %>%
add_class("sm_radf")
}
summary_radf <- function(cv, ...){
UseMethod("summary_radf")
}
summary_radf.sb_cv <- function(cv, object, ...) {
ret <- list()
ret[["panel"]] <- tidy_join(object, cv, panel = TRUE) %>%
pivot_wider(names_from = sig, values_from = crit) %>%
select(-id)
ret
}
summary_radf.mc_cv <- summary_radf.wb_cv <- function(cv, object, ...) {
ret <- list()
snames <- series_names(object)
sm <- tidy_join(object, cv) %>%
pivot_wider(names_from = sig, values_from = crit)
for (nms in snames) {
ret[[nms]] <- filter(sm, id == nms) %>%
select(-id)
}
ret
}
print.sm_radf <- function(x, ...) {
iter_char <- if (is_mc(x)) "nrep" else "nboot"
cat_line()
cat_rule(
left = glue("Summary (minw = {get_minw(x)}, lag = {get_lag(x)})"),
right = glue("{get_method(x)} ({iter_char} = {get_iter(x)})")
)
cat_line()
print.listof(x, ...)
} |
catminat<-function(species_list,TRAITS,catminat_df,similar=FALSE){
res<-new("results")
if(is.null(TRAITS)){
res@results<-NULL
}else{
if(similar){
DF<-lapply(species_list,function(x){
catminat_df[grep(x,catminat_df$species_name),c("species_name",TRAITS)]
}
)
DF<-ldply(DF)
}else{
DF<-catminat_df[catminat_df$species_name%in%species_list,c("species_name",TRAITS)]
}
DF<-unique(DF)
row.names(DF)<-DF$species_name
DF<-DF[,TRAITS,drop=FALSE]
res@results<-DF
}
stringa<-"Julve, P., 1998 ff. - Baseflor. Index botanique, \303\251cologique et chorologique de la flore de France. Version : 26 November 2014 . http://perso.wanadoo.fr/philippe.julve/catminat.htm"
Encoding(stringa)<-"unicode"
res@bibliography<-stringa
return(res)
} |
qphi <- function(p, M, k0, k1, s=2, onesided=FALSE){
lower = -1
upper = 10
maxnumIter = 500
numIter = 1
p_cal_lower = suppressWarnings(pphi(lower, M, k0, k1, s, onesided))
p_cal_upper = suppressWarnings(pphi(upper, M, k0, k1, s, onesided))
while((p_cal_lower-p)*(p_cal_upper-p)>0 && numIter < maxnumIter){
if(p_cal_lower>p){
lower = lower*1.1
p_cal_lower = suppressWarnings(pphi(lower, M, k0, k1, s, onesided))
}
if(p_cal_upper < p){
upper = upper*1.1
p_cal_upper = suppressWarnings(pphi(upper, M, k0, k1, s, onesided))
}
numIter = numIter + 1
}
q = mean(c(lower,upper))
p_cal = suppressWarnings(pphi(q, M, k0, k1, s, onesided))
error = (p_cal-p)/p
numIter = 1
while(abs(error) > 1e-5 && numIter < maxnumIter){
if(error > 0){
upper = q
q = mean(c(lower,upper))
p_cal = suppressWarnings(pphi(q, M, k0, k1, s, onesided))
error = (p_cal-p)/p
}else{
lower = q
q = mean(c(lower,upper))
p_cal = suppressWarnings(pphi(q, M, k0, k1, s, onesided))
error = (p_cal-p)/p
}
numIter = numIter + 1
}
if(numIter < maxnumIter){
return(q)
}else{
return("Bisection fails, choose another lower or upper bound to try again")
}
} |
print.FHtestrcp <-
function (x, digits = max(options()$digits - 4, 3), ...)
{
saveopt <- options(digits = digits)
on.exit(options(saveopt))
if (!inherits(x, "FHtestrcp"))
stop("Object is not of class FHtestrcp")
cat("\n")
writeLines(x$information)
cat("\n")
cat(x$data.name, sep = "\n")
cat("\n")
otmp <- x$obs
etmp <- x$exp
temp <- cbind(x$n, x$diff)
dimnames(temp) <- list(names(x$n), c("N", "O-E"))
print(temp)
if (length(grep("exact", x$information)) == 1) {
cat("\nStatistic= ", format(round(x$statistic, 1)), ", p-value= ",
format(signif(x$pvalue, digits)), "\n", sep = "")
} else if (substr(x$information, 2, 2) == "K") {
cat("\nChisq= ", format(round(x$statistic, 1)), " on ",
length(x$n) - 1, " degrees of freedom, p-value= ",
format(signif(x$pvalue, digits)), "\n", sep = "")
} else cat("\nStatistic Z= ", format(round(x$statistic, 1)),
", p-value= ", format(signif(x$pvalue, digits)), "\n",
sep = "")
if (length(grep("Monte", x$information)) == 1)
cat(format(100 * attr(x$p.conf.int, "conf.level")), "percent confidence interval on p-value: ",
format(c(x$p.conf.int[1], x$p.conf.int[2])), "\n")
cat(x$alt.phrase, sep = "\n")
cat("\n")
invisible(x)
} |
plot.demonoid <- function(x, BurnIn=0, Data=NULL, PDF=FALSE, Parms=NULL,
FileName = paste0("laplacesDemon-plot_", format(Sys.time(), "%Y-%m-%d_%T"), ".pdf"), ...)
{
if(missing(x)) stop("The x argument is required.")
if(is.null(Data)) stop("The Data argument is NULL.")
if(BurnIn >= nrow(x$Posterior1)) BurnIn <- 0
Stat.at <- BurnIn + 1
if(is.null(Parms)) {Posterior <- x$Posterior1}
else {
Parms <- sub("\\[","\\\\[",Parms)
Parms <- sub("\\]","\\\\]",Parms)
Parms <- sub("\\.","\\\\.",Parms)
if(length(grep(Parms[1], colnames(x$Posterior1))) == 0)
stop("Parameter in Parms does not exist.")
keepcols <- grep(Parms[1], colnames(x$Posterior1))
if(length(Parms) > 1) {
for (i in 2:length(Parms)) {
if(length(grep(Parms[i],
colnames(x$Posterior1))) == 0)
stop("Parameter in Parms does not exist.")
keepcols <- c(keepcols,
grep(Parms[i], colnames(x$Posterior1)))}}
Posterior <- as.matrix(x$Posterior1[,keepcols])
colnames(Posterior) <- colnames(x$Posterior1)[keepcols]}
if(PDF == TRUE) {
pdf(FileName)
par(mfrow=c(3,3))
}
else {par(mfrow=c(3,3), ask=TRUE)}
for (j in 1:ncol(Posterior))
{
plot(Stat.at:x$Thinned.Samples,
Posterior[Stat.at:x$Thinned.Samples,j],
type="l", xlab="Thinned Samples", ylab="Value",
main=colnames(Posterior)[j])
panel.smooth(Stat.at:x$Thinned.Samples,
Posterior[Stat.at:x$Thinned.Samples,j], pch="")
plot(density(Posterior[Stat.at:x$Thinned.Samples,j]),
xlab="Value", main=colnames(Posterior)[j])
polygon(density(Posterior[Stat.at:x$Thinned.Samples,j]),
col="black", border="black")
abline(v=0, col="red", lty=2)
if(!is.constant(Posterior[Stat.at:x$Thinned.Samples,j])) {
z <- acf(Posterior[Stat.at:x$Thinned.Samples,j], plot=FALSE)
se <- 1/sqrt(length(Posterior[Stat.at:x$Thinned.Samples,j]))
plot(z$lag, z$acf, ylim=c(min(z$acf,-2*se),1), type="h",
main=colnames(Posterior)[j], xlab="Lag",
ylab="Correlation")
abline(h=(2*se), col="red", lty=2)
abline(h=(-2*se), col="red", lty=2)
}
else {plot(0,0, main=paste(colnames(Posterior)[j],
"is a constant."))}
}
plot(Stat.at:length(x$Deviance),
x$Deviance[Stat.at:length(x$Deviance)],
type="l", xlab="Thinned Samples", ylab="Value", main="Deviance")
panel.smooth(Stat.at:length(x$Deviance),
x$Deviance[Stat.at:length(x$Deviance)], pch="")
plot(density(x$Deviance[Stat.at:length(x$Deviance)]),
xlab="Value", main="Deviance")
polygon(density(x$Deviance[Stat.at:length(x$Deviance)]), col="black",
border="black")
abline(v=0, col="red", lty=2)
if(!is.constant(x$Deviance[Stat.at:length(x$Deviance)])) {
z <- acf(x$Deviance[Stat.at:length(x$Deviance)], plot=FALSE)
se <- 1/sqrt(length(x$Deviance[Stat.at:length(x$Deviance)]))
plot(z$lag, z$acf, ylim=c(min(z$acf,-2*se),1), type="h",
main="Deviance", xlab="Lag", ylab="Correlation")
abline(h=(2*se), col="red", lty=2)
abline(h=(-2*se), col="red", lty=2)
}
else {plot(0,0, main="Deviance is a constant.")}
if(is.vector(x$Monitor)) {J <- 1; nn <- length(x$Monitor)}
else if(is.matrix(x$Monitor)) {
J <- ncol(x$Monitor); nn <- nrow(x$Monitor)}
for (j in 1:J)
{
plot(Stat.at:nn, x$Monitor[Stat.at:nn,j],
type="l", xlab="Thinned Samples", ylab="Value",
main=Data[["mon.names"]][j])
panel.smooth(Stat.at:nn, x$Monitor[Stat.at:nn,j], pch="")
plot(density(x$Monitor[Stat.at:nn,j]),
xlab="Value", main=Data[["mon.names"]][j])
polygon(density(x$Monitor[Stat.at:nn,j]), col="black",
border="black")
abline(v=0, col="red", lty=2)
if(!is.constant(x$Monitor[Stat.at:nn,j])) {
z <- acf(x$Monitor[Stat.at:nn,j], plot=FALSE)
se <- 1/sqrt(length(x$Monitor[Stat.at:nn,j]))
plot(z$lag, z$acf, ylim=c(min(z$acf,-2*se),1), type="h",
main=Data[["mon.names"]][j], xlab="Lag",
ylab="Correlation")
abline(h=(2*se), col="red", lty=2)
abline(h=(-2*se), col="red", lty=2)
}
else {plot(0,0, main=paste(Data[["mon.names"]][j],
"is a constant."))}
}
if(nrow(x$CovarDHis) > 1) {
if(x$Algorithm %in% c("Adaptive Hamiltonian Monte Carlo",
"Hamiltonian Monte Carlo with Dual-Averaging",
"No-U-Turn Sampler")) {
plot(x$CovarDHis[,1], type="l", xlab="Adaptations",
main="Step-Size", ylab=expression(epsilon))}
else {
if(x$Algorithm %in% c("Oblique Hyperrectangle Slice Sampler",
"Univariate Eigenvector Slice Sampler"))
title <- "Eigenvectors"
else if(x$Algorithm %in% c("Metropolis-Adjusted Langevin Algorithm"))
title <- "Lambda"
else if(x$Algorithm %in% c("Componentwise Hit-And-Run Metropolis",
"Hit-And-Run Metropolis"))
title <- "Proposal Distance"
else if(x$Algorithm %in% c("Adaptive Griddy-Gibbs",
"Adaptive Metropolis-within-Gibbs",
"Sequential Adaptive Metropolis-within-Gibbs",
"Updating Sequential Adaptive Metropolis-within-Gibbs"))
title <- "Proposal S.D."
else if(x$Algorithm %in% c("Differential Evolution Markov Chain"))
title <- "Z"
else if(x$Algorithm %in% c("Adaptive Factor Slice Sampler",
"Refractive Sampler"))
title <- "Step-Size"
else title <- "Proposal Variance"
Diff <- abs(diff(x$CovarDHis))
adaptchange <- matrix(NA, nrow(Diff), 3)
for (i in 1:nrow(Diff)) {
adaptchange[i,1:3] <- as.vector(quantile(Diff[i,],
probs=c(0.025, 0.500, 0.975)))}
plot(1:nrow(Diff), adaptchange[,2],
ylim=c(min(adaptchange), max(adaptchange)),
type="l", col="red", xlab="Adaptations",
ylab="Absolute Difference", main=title,
sub="Median=Red, Interval=Transparent Red")
polygon(c(1:nrow(Diff),rev(1:nrow(Diff))),
c(adaptchange[,1], rev(adaptchange[,3])),
col=rgb(255, 0, 0, 50, maxColorValue=255),
border=FALSE)
lines(adaptchange[,2], col="red")}
}
if(PDF == TRUE) dev.off()
} |
library(testthat)
library(ARTool)
context("artlm.con")
test_that("artlm.con matches with art.con",{
data(Higgins1990Table5, package = "ARTool")
m = art(DryMatter ~ Moisture*Fertilizer, data=Higgins1990Table5)
expect_equal(
summary(art.con(m, "Moisture")),
summary(contrast(emmeans(artlm.con(m, "Moisture"), ~ Moisture), method="pairwise"))
)
expect_equal(
summary(art.con(m, "Moisture:Fertilizer")),
summary(contrast(emmeans(artlm.con(m, "Moisture:Fertilizer"), ~ MoistureFertilizer), method="pairwise"))
)
m = art(DryMatter ~ Moisture*Fertilizer + (1|Tray), data=Higgins1990Table5)
expect_equal(
summary(art.con(m, "Moisture")),
summary(contrast(emmeans(artlm.con(m, "Moisture"), ~ Moisture), method="pairwise"))
)
expect_equal(
summary(art.con(m, "Moisture:Fertilizer")),
summary(contrast(emmeans(artlm.con(m, "Moisture:Fertilizer"), ~ MoistureFertilizer), method="pairwise"))
)
m = art(DryMatter ~ Moisture*Fertilizer + (1|Tray), data = tibble::as_tibble(Higgins1990Table5))
expect_equal(
summary(art.con(m, "Moisture")),
summary(contrast(emmeans(artlm.con(m, "Moisture"), ~ Moisture), method="pairwise"))
)
data(ElkinAB, package = "ARTool")
m = art(Y ~ A*B + Error(S), data=ElkinAB)
expect_equal(
summary(art.con(m, "A")),
summary(contrast(emmeans(artlm.con(m, "A"), ~ A), method="pairwise"))
)
expect_equal(
summary(art.con(m, "A:B")),
summary(contrast(emmeans(artlm.con(m, "A:B"), ~ AB), method="pairwise"))
)
})
test_that("artlm.con matches with artlm in single-factor case",{
m = art(DryMatter ~ Moisture*Fertilizer, data=Higgins1990Table5)
expect_equal(
summary(contrast(emmeans(artlm.con(m, "Moisture"), ~ Moisture), method="pairwise")),
summary(contrast(emmeans(artlm(m, "Moisture"), ~ Moisture), method="pairwise"))
)
m = art(DryMatter ~ Moisture*Fertilizer + (1|Tray), data=Higgins1990Table5)
expect_equal(
summary(contrast(emmeans(artlm.con(m, "Moisture"), ~ Moisture), method="pairwise")),
summary(contrast(emmeans(artlm(m, "Moisture"), ~ Moisture), method="pairwise"))
)
m = art(DryMatter ~ Moisture*Fertilizer + Error(Tray), data=Higgins1990Table5)
expect_equal(
summary(contrast(emmeans(artlm.con(m, "Moisture"), ~ Moisture), method="pairwise")),
summary(contrast(emmeans(artlm(m, "Moisture"), ~ Moisture), method="pairwise"))
)
}) |
ms_simplify <- function(input, keep = 0.05, method = NULL, weighting = 0.7,
keep_shapes = FALSE, no_repair = FALSE, snap = TRUE,
explode = FALSE, force_FC = TRUE, drop_null_geometries = TRUE,
snap_interval = NULL, sys = FALSE, sys_mem = 8) {
UseMethod("ms_simplify")
}
ms_simplify.character <- function(input, keep = 0.05, method = NULL, weighting = 0.7,
keep_shapes = FALSE, no_repair = FALSE,
snap = TRUE, explode = FALSE, force_FC = TRUE,
drop_null_geometries = TRUE, snap_interval = NULL, sys = FALSE, sys_mem = 8) {
input <- check_character_input(input)
ms_simplify_json(input = input, keep = keep, method = method,
weighting = weighting, keep_shapes = keep_shapes,
no_repair = no_repair, snap = snap, explode = explode,
force_FC = force_FC, drop_null_geometries = drop_null_geometries,
snap_interval = snap_interval, sys = sys, sys_mem = sys_mem)
}
ms_simplify.geo_json <- function(input, keep = 0.05, method = NULL, weighting = 0.7,
keep_shapes = FALSE, no_repair = FALSE,
snap = TRUE, explode = FALSE, force_FC = TRUE,
drop_null_geometries = TRUE, snap_interval = NULL, sys = FALSE, sys_mem = 8) {
ms_simplify_json(input = input, keep = keep, method = method,
weighting = weighting, keep_shapes = keep_shapes,
no_repair = no_repair, snap = snap, explode = explode,
force_FC = force_FC, drop_null_geometries = drop_null_geometries,
snap_interval = snap_interval, sys = sys, sys_mem = sys_mem)
}
ms_simplify.geo_list <- function(input, keep = 0.05, method = NULL,
weighting = 0.7, keep_shapes = FALSE,
no_repair = FALSE, snap = TRUE, explode = FALSE,
force_FC = TRUE, drop_null_geometries = TRUE,
snap_interval = NULL, sys = FALSE, sys_mem = 8) {
geojson <- geo_list_to_json(input)
ret <- ms_simplify_json(input = geojson, keep = keep, method = method,
weighting = weighting, keep_shapes = keep_shapes,
no_repair = no_repair, snap = snap, explode = explode,
force_FC = force_FC, drop_null_geometries = drop_null_geometries,
snap_interval = snap_interval, sys = sys, sys_mem = sys_mem)
geojsonio::geojson_list(ret)
}
ms_simplify.SpatialPolygons <- function(input, keep = 0.05, method = NULL, weighting = 0.7,
keep_shapes = FALSE, no_repair = FALSE,
snap = TRUE, explode = FALSE,
force_FC = TRUE, drop_null_geometries = TRUE,
snap_interval = NULL, sys = FALSE, sys_mem = 8) {
if (!is(input, "Spatial")) stop("input must be a spatial object")
call <- make_simplify_call(keep = keep, method = method, weighting = weighting,
keep_shapes = keep_shapes, no_repair = no_repair,
snap = snap, explode = explode, drop_null_geometries = !keep_shapes,
snap_interval = snap_interval)
ms_sp(input, call, sys = sys, sys_mem = sys_mem)
}
ms_simplify.SpatialLines <- ms_simplify.SpatialPolygons
ms_simplify.sf <- function(input, keep = 0.05, method = NULL, weighting = 0.7,
keep_shapes = FALSE, no_repair = FALSE,
snap = TRUE, explode = FALSE,
force_FC = TRUE, drop_null_geometries = TRUE,
snap_interval = NULL, sys = FALSE, sys_mem = 8) {
if (!all(sf::st_geometry_type(input) %in%
c("LINESTRING", "MULTILINESTRING", "POLYGON", "MULTIPOLYGON"))) {
stop("ms_simplify can only operate on (multi)polygons and (multi)linestrings",
call. = FALSE)
}
call <- make_simplify_call(keep = keep, method = method, weighting = weighting,
keep_shapes = keep_shapes, no_repair = no_repair,
snap = snap, explode = explode,
drop_null_geometries = !keep_shapes,
snap_interval = snap_interval)
ms_sf(input, call, sys = sys, sys_mem = sys_mem)
}
ms_simplify.sfc <- ms_simplify.sf
ms_simplify_json <- function(input, keep, method, weighting, keep_shapes, no_repair, snap,
explode, force_FC, drop_null_geometries, snap_interval, sys, sys_mem) {
call <- make_simplify_call(keep = keep, method = method, weighting = weighting,
keep_shapes = keep_shapes, no_repair = no_repair,
snap = snap, explode = explode, drop_null_geometries = drop_null_geometries,
snap_interval = snap_interval)
ret <- apply_mapshaper_commands(data = input, command = call, force_FC = force_FC, sys = sys, sys_mem = sys_mem)
ret
}
make_simplify_call <- function(keep, method, weighting, keep_shapes, no_repair,
snap, explode, drop_null_geometries, snap_interval) {
if (keep > 1 || keep <= 0) stop("keep must be > 0 and <= 1")
if (!is.null(snap_interval)) {
if (!is.numeric(snap_interval)) stop("snap_interval must be a numeric")
if (snap_interval < 0) stop("snap_interval must be >= 0")
}
if (is.null(method)) {
method <- ""
} else if (method == "vis") {
method <- "visvalingam"
} else if (!method == "dp") {
stop("method should be one of 'vis', 'dp', or NULL (to use the default weighted Visvalingam method)")
}
if (!is.numeric(weighting)) stop("weighting needs to be numeric.")
if (explode) explode <- "-explode" else explode <- NULL
if (snap && !is.null(snap_interval)) snap_interval <- paste0("snap-interval=", snap_interval)
if (snap) snap <- "snap" else snap <- NULL
if (keep_shapes) keep_shapes <- "keep-shapes" else keep_shapes <- NULL
if (no_repair) no_repair <- "no-repair" else no_repair <- NULL
if (drop_null_geometries) drop_null <- "-filter remove-empty" else drop_null <- NULL
call <- list(explode, snap, snap_interval, "-simplify",
keep = format(keep, scientific = FALSE), method,
weighting = paste0("weighting=",format(weighting, scientific = FALSE)),
keep_shapes, no_repair, drop_null)
call
}
ms_de_unit <- function(input) {
input_columns_units <- vapply(input, inherits, "units", FUN.VALUE = logical(1))
if(any(input_columns_units)) {
units_column_names <- names(input_columns_units)[input_columns_units]
msg <- paste0("Coercing these 'units' columns to class numeric: ",
paste(units_column_names, collapse = ", "))
warning(msg)
for(i in units_column_names) {
input[[i]] <- as.numeric(input[[i]])
}
}
input
} |
randomSubsets <- function(n, h, nsamp = 500) replicate(nsamp, sample.int(n, h))
hyperplaneSubsets <- function(x, y, h, nsamp = 500) {
d <- dim(x)
x <- addIntercept(x)
subsets <- randomSubsets(d[1], d[2], nsamp)
subsets <- apply(subsets, 2, function(i, x) {
xi <- x[i, , drop=FALSE]
theta <- try(hyperplane(xi), silent=TRUE)
while(inherits(theta, "try-error") && length(i) < d[1]) {
ind <- (seq_len(d[1]))[-i]
new <- if(length(ind) > 1) sample(ind, 1) else ind
i <- c(i, new)
xi <- rbind(xi, x[new,])
theta <- try(hyperplane(xi), silent=TRUE)
}
if(inherits(theta, "try-error")) {
sample.int(d[1], h)
} else {
residuals <- y - x %*% theta
findSmallest(abs(residuals), h)
}
}, x)
}
sparseSubsets <- function(x, y, lambda, h, nsamp = 500, normalize = TRUE,
intercept = TRUE, eps = .Machine$double.eps,
use.Gram = TRUE) {
n <- length(y)
subsets <- randomSubsets(n, 3, nsamp)
subsets <- .Call("R_sparseSubsets", R_x=x, R_y=y, R_lambda=lambda,
R_h=h, R_subsets=subsets, R_normalize=normalize,
R_intercept=intercept, R_eps=eps, R_useGram=use.Gram,
PACKAGE = "robustHD")
} |
NULL
get.zmq.ldflags <- function(arch = '', package = "pbdZMQ"){
if(arch == "/i386" || arch == "/x64"){
file.name <- paste("./libs", arch, "/", sep = "")
dir.path <- tools::file_path_as_absolute(
system.file(file.name, package = package))
zmq.ldflags <- paste("-L\"", dir.path, "\" -lzmq", sep = "")
} else{
file.name <- paste("./etc", arch, "/Makeconf", sep = "")
file.path <- tools::file_path_as_absolute(
system.file(file.name, package = package))
ret <- scan(file.path, what = character(), sep = "\n", quiet = TRUE)
arg <- "SYSTEM_ZMQ_LIBDIR"
id <- grep(paste("^", arg, " = ", sep = ""), ret)
sys.zmq.ld <- gsub(paste("^", arg, " = (.*)", sep = ""), "\\1", ret[id[1]])
arg <- "EXTERNAL_ZMQ_LDFLAGS"
id <- grep(paste("^", arg, " = ", sep = ""), ret)
ext.zmq.ld <- gsub(paste("^", arg, " = (.*)", sep = ""), "\\1", ret[id[1]])
arg <- "ENABLE_INTERNAL_ZMQ"
id <- grep(paste("^", arg, " = ", sep = ""), ret)
en.int.zmq <- gsub(paste("^", arg, " = (.*)", sep = ""), "\\1", ret[id[1]])
if((sys.zmq.ld == "" && ext.zmq.ld == "") || en.int.zmq == "yes"){
file.name <- paste("./libs", arch, "/", sep = "")
dir.path <- tools::file_path_as_absolute(
system.file(file.name, package = package))
if(Sys.info()[['sysname']] == "Darwin"){
lib.osx <- list.files(dir.path, pattern = "libzmq\\.(.*)\\.dylib")
i.ver <- gsub("libzmq\\.(.*)\\.dylib", "\\1", lib.osx)
i.ver <- max(as.integer(i.ver))
zmq.ldflags <- paste("-L\"", dir.path, "\" -lzmq.", i.ver, sep = "")
} else{
zmq.ldflags <- paste("-L\"", dir.path, "\" -lzmq", sep = "")
}
} else{
arg <- "ZMQ_LDFLAGS"
id <- grep(paste("^", arg, " = ", sep = ""), ret)
zmq.ldflags <- gsub(paste("^", arg, " = (.*)", sep = ""), "\\1",
ret[id[1]])
}
}
cat(zmq.ldflags)
invisible(zmq.ldflags)
}
get.zmq.cppflags <- function(arch = '', package = "pbdZMQ"){
if(arch == "/i386" || arch == "/x64"){
file.name <- paste("./zmq", arch, "/include", sep = "")
dir.path <- tools::file_path_as_absolute(
system.file(file.name, package = package))
zmq.cppflags <- paste("-I\"", dir.path, "\"", sep = "")
} else{
file.name <- paste("./etc", arch, "/Makeconf", sep = "")
file.path <- tools::file_path_as_absolute(
system.file(file.name, package = package))
ret <- scan(file.path, what = character(), sep = "\n", quiet = TRUE)
arg <- "SYSTEM_ZMQ_INCLUDEDIR"
id <- grep(paste("^", arg, " = ", sep = ""), ret)
sys.zmq.inc <- gsub(paste("^", arg, " = (.*)", sep = ""), "\\1", ret[id[1]])
arg <- "EXTERNAL_ZMQ_INCLUDE"
id <- grep(paste("^", arg, " = ", sep = ""), ret)
ext.zmq.inc <- gsub(paste("^", arg, " = (.*)", sep = ""), "\\1", ret[id[1]])
arg <- "ENABLE_INTERNAL_ZMQ"
id <- grep(paste("^", arg, " = ", sep = ""), ret)
en.int.zmq <- gsub(paste("^", arg, " = (.*)", sep = ""), "\\1", ret[id[1]])
if((sys.zmq.inc == "" && ext.zmq.inc == "") || en.int.zmq == "yes"){
file.name <- paste("./zmq", arch, "/include/", sep = "")
dir.path <- tools::file_path_as_absolute(
system.file(file.name, package = package))
zmq.cppflags <- paste("-I\"", dir.path, "\"", sep = "")
} else{
arg <- "ZMQ_INCLUDE"
id <- grep(paste("^", arg, " = ", sep = ""), ret)
zmq.cppflags <- gsub(paste("^", arg, " = (.*)", sep = ""), "\\1",
ret[id[1]])
}
arg <- "GET_SYSTEM_ZMQ_430"
id <- grep(paste("^", arg, " = ", sep = ""), ret)
sys.zmq.430 <- gsub(paste("^", arg, " = (.*)", sep = ""), "\\1",
ret[id[1]])
chk.zmq.h.430 <- "no"
if(sys.zmq.430 == "no"){
path.zmq.h <- gsub("^-I(.*)$", "\\1", zmq.cppflags)
path.zmq.h <- gsub("^\\\"(.*)\\\"$", "\\1", path.zmq.h)
f.zmq.h <- paste(path.zmq.h, "/zmq.h", sep = "")
ret.zmq.h <- scan(f.zmq.h, what = character(), sep = "\n", quiet = TRUE)
id.major <- grep("^
id.minor <- grep("^
v.major <- gsub("^
ret.zmq.h[id.major])
v.minor <- gsub("^
ret.zmq.h[id.minor])
if(v.major >=4 && v.minor >= 3){
chk.zmq.h.430 <- "yes"
}
}
if((sys.zmq.430 == "yes" && en.int.zmq != "yes") || chk.zmq.h.430 == "yes"){
zmq.cppflags <- paste(zmq.cppflags, " -DENABLE_DRAFTS=ON", sep = "")
}
}
cat(zmq.cppflags)
invisible(zmq.cppflags)
}
test.load.zmq <- function(arch = '', package = "pbdZMQ"){
file.name <- paste("./libs", arch, "/", sep = "")
dir.path <- tools::file_path_as_absolute(
system.file(file.name, package = package))
files <- c("libzmq.so", "libzmq.so.dSYM", "libzmq.dylib", "libzmq.4.dylib",
"libzmq.5.dylib", "libzmq.dll")
for(i.file in files){
fn <- paste(dir.path, "/", i.file, sep = "")
if(file.exists(fn)){
ret <- try(dyn.load(fn, local = FALSE), silent = TRUE)
print(ret)
cat("\n")
}
}
invisible(NULL)
}
get.pbdZMQ.ldflags <- function(arch = '', package = "pbdZMQ"){
file.name <- paste("./libs", arch, "/", sep = "")
dir.path <- tools::file_path_as_absolute(
system.file(file.name, package = package))
if(arch == "/i386" || arch == "/x64"){
pbdZMQ.ldflags <- paste(dir.path, "/pbdZMQ.dll", sep = "")
} else{
pbdZMQ.ldflags <- paste(dir.path, "/pbdZMQ.so", sep = "")
}
cat(pbdZMQ.ldflags)
invisible(pbdZMQ.ldflags)
} |
if (.Platform$OS.type == "windows") {
PATH = paste0(getwd(), path.expand("\\term_matrix_file.csv"))
PATH_txt = paste0(getwd(), path.expand("\\term_matrix_file.txt"))
}
if (.Platform$OS.type == "unix") {
PATH = paste0(getwd(), path.expand("/term_matrix_file.csv"))
PATH_txt = paste0(getwd(), path.expand("/term_matrix_file.txt"))
}
docs = as.vector(read.csv(PATH, header = FALSE, stringsAsFactors = F)[, 1])
context('term matrix class')
while(T) {
testthat::test_that("in case that the 'triplet_data' method is called before the 'Term_Matrix' method is run, it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$triplet_data() )
})
testthat::test_that("the 'triplet_data' method returns a list of length four", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
out = init$triplet_data()
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( length(out) == 4 && inherits(out, "list") )
})
testthat::test_that("in case that the 'global_term_weights' method is called before the 'Term_Matrix' method is run, it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$global_term_weights() )
})
testthat::test_that("in case that the 'document_term_matrix' parameter is set to FALSE, it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = FALSE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$global_term_weights() )
})
testthat::test_that("the 'global_term_weights' method returns a list of length two", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
out = init$global_term_weights()
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( length(out) == 2 && inherits(out, "list") )
})
testthat::test_that("in case that both vector_data and file_data are NULL it returns an error", {
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( sparse_term_matrix$new(vector_data = NULL, file_data = NULL, document_term_matrix = TRUE) )
})
testthat::test_that("in case that both vector_data and file_data are not NULL it returns an error", {
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( sparse_term_matrix$new(vector_data = docs, file_data = PATH, document_term_matrix = TRUE) )
})
testthat::test_that("in case that the vector_data parameter is not a vector of documents it returns an error", {
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( sparse_term_matrix$new(vector_data = list(), file_data = NULL, document_term_matrix = TRUE) )
})
testthat::test_that("in case that the file_data parameter is not a valid path to a file it returns an error", {
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( sparse_term_matrix$new(vector_data = NULL, file_data = "/invalid/path", document_term_matrix = TRUE) )
})
testthat::test_that("in case that the document_term_matrix parameter is not logical it returns an error", {
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = 'TRUE') )
})
testthat::test_that("in case that the sort_terms parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = 'FALSE', to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the to_lower parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = 'FALSE', to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the to_upper parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = 'FALSE', utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the utf_locale parameter is not a character string it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = NULL, remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the remove_char parameter is not a character string it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = NULL, remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the remove_punctuation_string parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = 'FALSE', remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the remove_punctuation_vector parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = 'FALSE',
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the remove_numbers parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = 'FALSE', trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the trim_token parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = 'FALSE', split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the split_string parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = 'FALSE', split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the split_separator parameter is not a character string it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = NULL, remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the remove_stopwords parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = NULL, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the language parameter is not one of the available it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "INVALID",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the min_num_char parameter is less than 1 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 0, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the max_num_char parameter is less than the min_num_char it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = -Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the stemmer parameter is not one of the available it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = 'NULL', min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the min_n_gram parameter is less than 1 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 0, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the max_n_gram parameter is less than 1 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 0, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the min_n_gram is greater than the max_n_gram parameter it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 3, max_n_gram = 2, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the skip_n_gram parameter is less than 1 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 0, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the skip_distance parameter is less than 0 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = -1, n_gram_delimiter = " ",
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the n_gram_delimiter parameter is not a character string it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = NULL,
print_every_rows = 1000, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the print_every_rows parameter is less than 1 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 0, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the normalize parameter is not one of c(l1, l2) it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = 'NULL', tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the tf_idf parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = 'FALSE',
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the threads parameter is less than 1 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 0, verbose = FALSE) )
})
testthat::test_that("in case that the verbose parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix(sort_terms = FALSE, to_lower = FALSE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = FALSE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = 'FALSE') )
})
testthat::test_that("in case that either the to_lower or the to_upper parameter is TRUE and the language is other than english then a warning will be printed to the console", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_warning( init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "greek",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the data is a vector of documents and the document_term_matrix parameter is TRUE it returns a sparse document_term_matrix with the correct number of rows (documents)", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = TRUE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res, "dgCMatrix") && nrow(res) == length(docs) )
})
testthat::test_that("in case that the data is a vector of documents AND the document_term_matrix parameter is TRUE AND a user defined list of stopwords is given, it returns a sparse
document_term_matrix with the correct number of rows (documents)", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = c("a", "this", "is"), language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res, "dgCMatrix") && nrow(res) == length(docs) )
})
testthat::test_that("in case that the data is a vector of documents and the document_term_matrix parameter is FALSE it returns a sparse term_document_matrix with the correct number of columns (documents)", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = FALSE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res, "dgCMatrix") && ncol(res) == length(docs) )
})
testthat::test_that("in case that the data input is a path to a file and the document_term_matrix parameter is TRUE it returns a sparse document_term_matrix with the correct number of rows (documents)", {
init = sparse_term_matrix$new(vector_data = NULL, file_data = PATH_txt, document_term_matrix = TRUE)
res = suppressWarnings(init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE))
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res, "dgCMatrix") && nrow(res) == length(docs) )
})
testthat::test_that("in case that the data input is a path to a file and the document_term_matrix parameter is FALSE it returns a sparse term_document_matrix with the correct number of columns (documents)", {
init = sparse_term_matrix$new(vector_data = NULL, file_data = PATH_txt, document_term_matrix = FALSE)
res = suppressWarnings(init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE))
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res, "dgCMatrix") && ncol(res) == length(docs) )
})
testthat::test_that("in case that the Term_Matrix method is not run in first place it returns an error", {
init1 = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init1$Term_Matrix_Adjust(sparsity_thresh = 1.0) )
})
testthat::test_that("in case that sparsity_thresh is not numeric it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix_Adjust(sparsity_thresh = NULL) )
})
testthat::test_that("in case that sparsity_thresh is less than or equal to 0.0 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix_Adjust(sparsity_thresh = 0.0) )
})
testthat::test_that("in case that sparsity_thresh is greater than 1.0 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix_Adjust(sparsity_thresh = 1.00001) )
})
testthat::test_that("in case that sparsity_thresh gives an empty matrix it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$Term_Matrix_Adjust(sparsity_thresh = 0.1) )
})
testthat::test_that("it returns a reduced sparse matrix in case that the sparsity_thresh is less than 1.0 and the document_term_matrix parameter is TRUE", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
res_sp = init$Term_Matrix_Adjust(sparsity_thresh = 0.8)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res, "dgCMatrix") && inherits(res_sp, "dgCMatrix") && ncol(res) > ncol(res_sp) )
})
testthat::test_that("it returns a reduced sparse matrix in case that the sparsity_thresh is less than 1.0 and the document_term_matrix parameter is FALSE", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = FALSE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
res_sp = init$Term_Matrix_Adjust(sparsity_thresh = 0.8)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res, "dgCMatrix") && inherits(res_sp, "dgCMatrix") && nrow(res) > nrow(res_sp) )
})
testthat::test_that("in case that the Term_Matrix method is not run in first place it returns an error", {
init1 = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init1$term_associations(Terms = c("the"), keep_terms = 10, verbose = FALSE) )
})
testthat::test_that("in case that Terms is not a character vector it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$term_associations(Terms = NULL, keep_terms = 10, verbose = FALSE) )
})
testthat::test_that("in case that Terms is a character vector with length less than 1 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$term_associations(Terms = character(0), keep_terms = 10, verbose = FALSE) )
})
testthat::test_that("in case that keep_terms is not a numeric value it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$term_associations(Terms = c("the", "and"), keep_terms = list(), verbose = FALSE) )
})
testthat::test_that("in case that keep_terms is a numeric value less than 1 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$term_associations(Terms = c("the", "and"), keep_terms = 0, verbose = FALSE) )
})
testthat::test_that("in case that the verbose parameter is not a boolean it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$term_associations(Terms = c("the", "and"), keep_terms = NULL, verbose = 'FALSE') )
})
testthat::test_that("it returns the correct output in case of a single term", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
target_term = "is"
single_out = init$term_associations(Terms = target_term, keep_terms = NULL, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(single_out, c("data.table","data.frame")) && nrow(single_out) == ncol(res) - 1 && ncol(single_out) == 2 && sum(colnames(single_out) %in% c('term', 'correlation')) == 2 && !target_term %in% single_out$term )
})
testthat::test_that("it returns the correct output in case of a single term ( if term-document-matrix is TRUE )", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = FALSE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
target_term = "is"
single_out = init$term_associations(Terms = target_term, keep_terms = NULL, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(single_out, c("data.table","data.frame")) && nrow(single_out) == nrow(res) - 1 && ncol(single_out) == 2 && sum(colnames(single_out) %in% c('term', 'correlation')) == 2 && !target_term %in% single_out$term )
})
testthat::test_that("it returns the correct output in case that the Term_Matrix_Adjust method is called first", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = FALSE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
res1 = init$Term_Matrix_Adjust(sparsity_thresh = 0.85)
target_term = "of"
single_out = init$term_associations(Terms = target_term, keep_terms = NULL, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(single_out, c("data.table","data.frame")) && nrow(single_out) == nrow(res1) - 1 && ncol(single_out) == 2 && sum(colnames(single_out) %in% c('term', 'correlation')) == 2 && !target_term %in% single_out$term )
})
testthat::test_that("it returns the correct output in case of a multiple terms", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
tmp_terms = c("is", "a")
mult_out = init$term_associations(Terms = tmp_terms, keep_terms = NULL, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( sum(unlist(lapply(1:length(mult_out), function(x) inherits(mult_out[[x]], c("data.table","data.frame")) && nrow(mult_out[[x]]) == ncol(res) - 1 && ncol(mult_out[[x]]) == 2 &&
sum(colnames(mult_out[[x]]) %in% c('term', 'correlation')) == 2 && !tmp_terms[x] %in% mult_out[[x]]$term))) == length(tmp_terms) )
})
testthat::test_that("it returns the correct output in case of a multiple terms ( if term-document-matrix is FALSE )", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = FALSE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
tmp_terms = c("is", "a")
mult_out = init$term_associations(Terms = tmp_terms, keep_terms = NULL, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( sum(unlist(lapply(1:length(mult_out), function(x) inherits(mult_out[[x]], c("data.table","data.frame")) && nrow(mult_out[[x]]) == nrow(res) - 1 && ncol(mult_out[[x]]) == 2 &&
sum(colnames(mult_out[[x]]) %in% c('term', 'correlation')) == 2 && !tmp_terms[x] %in% mult_out[[x]]$term))) == length(tmp_terms) )
})
testthat::test_that("in case that the Term_Matrix method is not run in first place it returns an error", {
init1 = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init1$most_frequent_terms(keep_terms = NULL, threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the keep_terms parameter is not a numeric value it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$most_frequent_terms(keep_terms = 'NULL', threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the keep_terms parameter is less than 1 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$most_frequent_terms(keep_terms = 0, threads = 1, verbose = FALSE) )
})
testthat::test_that("in case that the threads parameter is less than 1 it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$most_frequent_terms(keep_terms = 1, threads = 0, verbose = FALSE) )
})
testthat::test_that("in case that the verbose parameter is not logical it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$most_frequent_terms(keep_terms = 1, threads = 1, verbose = 'FALSE') )
})
testthat::test_that("in case that either the normalize parameter is not NULL or the tf_idf parameter is TRUE it returns an error", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = T,
threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_error( init$most_frequent_terms(keep_terms = 1, threads = 1, verbose = FALSE) )
})
testthat::test_that("it returns the correct output if the keep_terms parameter is NULL", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
res_freq = init$most_frequent_terms(keep_terms = NULL, threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res_freq, c("data.table","data.frame")) && nrow(res_freq) == ncol(res) && ncol(res_freq) == 2 && sum(colnames(res_freq) %in% c('term', 'frequency')) == 2 )
})
testthat::test_that("it returns the correct output if the keep_terms parameter is a numeric value", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
tmp_keep = 5
res_freq = init$most_frequent_terms(keep_terms = tmp_keep, threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res_freq, c("data.table","data.frame")) && nrow(res_freq) == tmp_keep && ncol(res_freq) == 2 && sum(colnames(res_freq) %in% c('term', 'frequency')) == 2 )
})
testthat::test_that("it returns the correct output if the Term_Matrix_Adjust method is called first", {
init = sparse_term_matrix$new(vector_data = docs, file_data = NULL, document_term_matrix = TRUE)
res = init$Term_Matrix(sort_terms = FALSE, to_lower = TRUE, to_upper = FALSE, utf_locale = "", remove_char = "", remove_punctuation_string = FALSE, remove_punctuation_vector = FALSE,
remove_numbers = FALSE, trim_token = FALSE, split_string = TRUE, split_separator = " \r\n\t.,;:()?!//", remove_stopwords = FALSE, language = "english",
min_num_char = 1, max_num_char = Inf, stemmer = NULL, min_n_gram = 1, max_n_gram = 1, skip_n_gram = 1, skip_distance = 0, n_gram_delimiter = " ",
print_every_rows = 100, normalize = NULL, tf_idf = FALSE,
threads = 1, verbose = FALSE)
res1 = init$Term_Matrix_Adjust(sparsity_thresh = 0.85)
res_freq = init$most_frequent_terms(keep_terms = NULL, threads = 1, verbose = FALSE)
cat("test-term_matrix_triplet_data_global_term_weights.R : test id", cnt_tsts, "\n")
cnt_tsts <<- cnt_tsts + 1
testthat::expect_true( inherits(res_freq, c("data.table","data.frame")) && nrow(res_freq) == ncol(res1) && ncol(res_freq) == 2 && sum(colnames(res_freq) %in% c('term', 'frequency')) == 2 )
})
break
} |
set.seed(123)
n <- 20
cgnp_pair <- sample_correlated_gnp_pair(n=n, corr=0.8, p=0.5)
A <- cgnp_pair$graph1
B <- igraph::induced_subgraph(cgnp_pair$graph2, 1:10)
sim_rect <- matrix(runif(10 * n), n)
sim_sq <- pad(sim_rect, 0, n - 10)
gm(A, B, start = "bari", sim = sim_rect, method = "indefinite")
gm(A, B, start = "bari", sim = sim_sq, method = "indefinite")
gm(A, B, start = "bari", seeds = 1:3, sim = sim_sq, method = "indefinite")
gm(A, B, start = "bari", sim = NULL, method = "indefinite")
test_that(
"error on wrong rectangular dim",
{
expect_error({
sim_bad <- matrix(runif(10 * n - 10), n - 10)
gm(A, B, start = "bari", sim = sim_bad, method = "indefinite")
},
"Non square similarity matrices.*")
}
)
test_that(
"error on wrong square dim",
{
expect_error({
sim_bad <- matrix(runif(10 * 10), 10)
gm(A, B, start = "bari", sim = sim_bad, method = "indefinite")
},
"Square similarity matrices.*")
}
) |
wClassNoPunct <- function(wclass, lang, abs=NULL){
word.tags <- kRp.POS.tags(lang, list.classes=TRUE, tags="words")
wclass.num <- summary(as.factor(wclass))
wclass.nopunct <- names(wclass.num)[names(wclass.num) %in% word.tags]
wclass.punct <- names(wclass.num)[!names(wclass.num) %in% word.tags]
wclass.nopunct.num <- wclass.num[wclass.nopunct]
wclass.punct.num <- wclass.num[wclass.punct]
wclass.nopunct.num <- wclass.nopunct.num[order(wclass.nopunct.num, decreasing=TRUE)]
if(is.null(abs)){
wclass.nopunct.num <- rbind(wclass.nopunct.num, 100 * wclass.nopunct.num / sum(wclass.nopunct.num))
rownames(wclass.nopunct.num) <- c("num", "pct")
} else {
wclass.nopunct.num <- rbind(wclass.nopunct.num, 100 * wclass.nopunct.num / sum(wclass.nopunct.num), 100 * wclass.nopunct.num / abs)
rownames(wclass.nopunct.num) <- c("num", "pct", "pct.abs")
}
wclass.nopunct.num <- t(wclass.nopunct.num)
if(length(wclass.punct) != 0){
if(ncol(wclass.nopunct.num) > 2){
wclass.nopunct.num <- rbind(wclass.nopunct.num, cbind(wclass.punct.num, NA, NA))
} else {
wclass.nopunct.num <- rbind(wclass.nopunct.num, cbind(wclass.punct.num, NA))
}
} else {}
return(wclass.nopunct.num)
}
setMethod("summary", signature(object="kRp.text"), function(object, index=NA, feature=NULL, flat=FALSE){
if(identical(feature, "freq")){
stopifnot(hasFeature(object, "freq"))
summary.table <- t(data.frame(
sentences=describe(object)[["sentences"]],
avg.sentence.length=describe(object)[["avg.sentc.length"]],
words=describe(object)[["words"]],
avg.word.length=describe(object)[["avg.word.length"]],
all.characters=describe(object)[["all.chars"]],
letters=describe(object)[["letters"]][["all"]],
lemmata=describe(object)[["lemmata"]],
questions=describe(object)[["questions"]],
exclamations=describe(object)[["exclam"]],
semicolon=describe(object)[["semicolon"]],
colon=describe(object)[["colon"]],
stringsAsFactors=FALSE))
colnames(summary.table) <- "freq"
return(summary.table)
} else if(identical(feature, "lex_div")){
stopifnot(hasFeature(object, "lex_div"))
object_lexdiv <- corpusLexDiv(object)
if(length(object_lexdiv) > 1){
summary.table <- t(as.data.frame(
lapply(
object_lexdiv,
summary,
flat=TRUE
)
))
} else {
summary.table <- summary(object_lexdiv[[1]], flat=flat)
}
return(summary.table)
} else if(identical(feature, "readability")){
stopifnot(hasFeature(object, "readability"))
object_rdb <- corpusReadability(object)
if(length(object_rdb) > 1){
summary.table <- t(as.data.frame(
lapply(
object_rdb,
summary,
flat=TRUE
)
))
} else {
summary.table <- summary(object_rdb[[1]], flat=flat)
}
return(summary.table)
} else {
Row.names <- NULL
desc <- describe(object)
lang <- language(object)
tokens <- taggedText(object)
wclass.nopunct.num <- wClassNoPunct(wclass=tokens[["wclass"]], lang=lang)
if(hasFeature(object, "diff")){
wclass.orig.order <- order(order(rownames(wclass.nopunct.num)))
if(isTRUE(is.na(index))){
wclass.index <- !tokens[["equal"]]
} else if(is.character(index)){
if(length(index) > 1){
stop(simpleError(paste0("If \"index\" is character, it must be a single value!")))
} else {}
diffObj <- diffText(object)
if(index %in% colnames(diffObj[["transfmt.equal"]])){
indexPosition <- which(colnames(diffObj[["transfmt.equal"]]) %in% index)
if(length(indexPosition) > 1){
warning(paste0("Index \"", index,"\" found multiple times, using last occurrence only!"), call.=FALSE)
indexPosition <- max(indexPosition)
} else {}
} else {
stop(simpleError(paste0("Transformation data \"", index,"\" not found in object!")))
}
wclass.index <- !diffObj[["transfmt.equal"]][[indexPosition]]
} else {
wclass.index <- index
}
wclass.nopunct.num.transfmt <- wClassNoPunct(wclass=tokens[wclass.index,"wclass"], lang=lang, abs=desc[["words"]])
colnames(wclass.nopunct.num.transfmt) <- c("num.transfmt", "pct.transfmt", "pct.transfmt.abs")
wclass.nopunct.num <- merge(wclass.nopunct.num, wclass.nopunct.num.transfmt, all=TRUE, by='row.names', sort=FALSE, suffixes=c("", ".transfmt"))
rownames(wclass.nopunct.num) <- wclass.nopunct.num[["Row.names"]]
wclass.nopunct.num <- subset(wclass.nopunct.num, select=-Row.names)
wclass.nopunct.num <- wclass.nopunct.num[order(rownames(wclass.nopunct.num))[wclass.orig.order],]
wclass.nopunct.num[["pct.transfmt.wclass"]] <- wclass.nopunct.num[["num.transfmt"]] * 100 / wclass.nopunct.num[["num"]]
wclass.nopunct.num[is.nan(wclass.nopunct.num[["pct.transfmt.wclass"]]), "pct.transfmt.wclass"] <- 0
} else {}
cat(
"\n Sentences: ", desc[["sentences"]], "\n",
" Words: ", desc[["words"]], " (", round(desc[["avg.sentc.length"]], digits=2), " per sentence)\n",
" Letters: ", desc[["letters"]][["all"]], " (", round(desc[["avg.word.length"]], digits=2), " per word)\n\n Word class distribution:\n\n",
sep="")
return(wclass.nopunct.num)
}
}) |
gen.example <- function(){
set.seed(1)
n <- 600
bmi <- stats::rchisq(n, df = 6)
bmi <- round(16 + (40-16)/(max(bmi)-min(bmi)) * (bmi-min(bmi)), digits = 1)
age <- stats::rnorm(n)
age <- round(40 + (80-40)/(max(age)-min(age)) * (age-min(age)), digits = 0)
breastfeed <- sample(c('yes', 'no'), n, TRUE, c(.85, .15))
parity <- sample(0:5, n, TRUE, c(.05, 0.15, 0.45, 0.3, 0.03, 0.02))
p53 <- sample(1:3, n, TRUE, c(.3, .3, .4))
subtype <- sample(c('A', 'B', 'C'), n, TRUE, c(.65, .2, .15))
dat <- data.frame(subj.id = paste0('SID-',1:n), density = 0, bmi, age, breastfeed, parity, p53, subtype, stringsAsFactors = FALSE)
mm <- model.matrix(density~I(age >= 50 & age < 60) + I(age >= 60) + as.factor(breastfeed) + I(parity > 0) + I(p53 !=1)*I(subtype != 'A'), data=dat)
para <- c(1, 0.1, 0.2, -0.1, -0.3, 0.05, 0., 0.15)
dat$density <- exp(as.vector(mm %*% para) + stats::rnorm(n, sd = sqrt(0.05)))
int <- dat[1:200, ]
ext1 <- dat[201:400, c('subj.id', 'density', 'age', 'parity', 'subtype')]
ext2 <- dat[201:300, c('subj.id', 'density', 'age', 'breastfeed', 'subtype')]
ext3 <- dat[301:600, c('subj.id', 'density', 'p53', 'subtype')]
int$age_50to59 <- I(int$age >= 50 & int$age < 60)+1-1
int$age_gt60 <- I(int$age >= 60)+1-1
formula <- as.formula(log(density) ~ age_50to59 + age_gt60 + breastfeed + parity + as.factor(p53)*I(subtype=='A'))
fit0 <- glm(formula, data = int, family = 'gaussian')
fit1 <- glm(log(density) ~ I(age < 60) + I(parity > 0) + subtype, data = ext1, family = 'gaussian')
fit2 <- glm(log(density) ~ I(age >= 70) + breastfeed + subtype, data = ext2, family = 'gaussian')
fit31 <- glm(log(density) ~ as.factor(p53), data = ext3, family = 'gaussian')
fit32 <- glm(log(density) ~ subtype, data = ext3, family = 'gaussian')
summary(fit0)
summary(fit1)
summary(fit2)
cbind(colnames(mm), para)
model <- list()
model[[1]] <- list(formula='log(density) ~ I(age >= 70) + breastfeed + subtype',
info=data.frame(var = names(coef(fit2))[2:4],
bet = coef(fit2)[2:4]))
model[[2]] <- list(formula='log(density) ~ subtype',
info=data.frame(var = names(coef(fit32))[-1],
bet = coef(fit32)[-1]))
n1 <- nrow(ext1)
n2 <- nrow(ext2)
n3 <- nrow(ext3)
n0 <- length(intersect(ext1$subj.id, ext3$subj.id))
nsample <- matrix(c(n1, n0, n0, n3), 2, 2)
form <- formula
dat <- int
lt <- list(form = form, dat = dat, model = model, nsample = nsample)
lt
} |
require("DiceKriging")
require("testthat")
set.seed(1)
test_that.km <- function(model, trend.coef=NULL, covariance.sd2=NULL, covariance.range.val=NULL, covariance.nugget=NULL, covariance.eta=NULL, precision=1e-4) {
if (!is.null(trend.coef))
test_that(desc = "Check kriging trend",
expect_true(max(abs(([email protected] - trend.coef)/trend.coef)) < precision))
if (!is.null(covariance.sd2))
test_that(desc = "Check kriging variance",
expect_true(abs(model@covariance@sd2 - covariance.sd2)/covariance.sd2 < precision))
if (!is.null(covariance.range.val))
test_that(desc = "Check kriging range",
expect_true(max(abs((model@[email protected] - covariance.range.val)/covariance.range.val)) < precision))
if (!is.null(covariance.nugget))
test_that(desc = "Check kriging nugget",
expect_true(max(abs((model@covariance@nugget - covariance.nugget)/covariance.nugget)) < precision))
if (!is.null(covariance.eta))
test_that(desc = "Check kriging scaling",
expect_true(max(abs((model@covariance@eta - covariance.eta)/covariance.eta)) < precision))
}
context("Checking km examples: 2D example - Branin-Hoo function")
d <- 2; n <- 16
design.fact <- expand.grid(x1=seq(0,1,length=4), x2=seq(0,1,length=4))
y <- apply(design.fact, 1, branin)
m1 <- km(design=design.fact, response=y,
control=list(trace=FALSE))
test_that.km(m1,trend.coef = 306.5783,covariance.sd2 = 145556.6,covariance.range.val = c(0.8254355,2.0000000))
m2 <- km(~.^2, design=design.fact, response=y,
control=list(trace=FALSE))
test_that.km(m2, trend.coef = c(579.5111, -402.8916, -362.0008, 431.2314), covariance.sd2 = 87350.78, covariance.range.val = c(0.7917705,2.0000000))
m1.loo = leaveOneOut.km(m1,type="UK")
m1.loo.test = list(mean = c(286.993256592263, 61.1933200186092, 13.3103372396603, 6.71932528464657, 165.248905907798, 19.0053295402084,
27.2225325208522, 7.83789496814171, 59.1350192499509, 36.8594545864432, 90.067237851829, 54.0537533395973,
27.9241365199806, 97.621906142958, 202.264052547859, 153.096609124748),
sd = c(10.772546332554, 5.74056179816984, 5.74056179817999, 10.7725463324928, 4.30907401785216, 2.300089162552,
2.30008916257098, 4.30907401785217, 4.30907401784204,2.30008916257098, 2.30008916257098, 4.30907401783865,
10.7725463325132, 5.74056179815971, 5.74056179814956, 10.7725463325064))
test_that(desc="Test leaveOneOut",expect_that(max(abs(m1.loo.test$mean-m1.loo$mean))<1e-6, is_true()))
test_that(desc="Test leaveOneOut",expect_that(max(abs(m1.loo.test$sd-m1.loo$sd))<1e-6, is_true()))
m2.loo = leaveOneOut.km(m2,type="UK")
m2.loo.test = list(mean = c(295.42310365247, 58.7310677087344, 15.7232029614909, 0.759894555079001, 162.564378157371, 19.7760351639429,
26.4708895401928, 9.63275693530611, 61.6951516883825, 36.1471579561365, 90.7566139900235, 52.5073354395038,
20.6033936837633, 99.6133571193964, 200.349297345504, 157.171599505827),
sd = c(9.40690817620207, 4.88889794440375, 4.8888979444158, 9.40690817630557, 3.66940746999634, 1.9439593480655,
1.9439593480619, 3.66940747003794, 3.66940746999794, 1.94395934805049, 1.94395934807647, 3.66940747003195,
9.40690817621748, 4.88889794440019, 4.88889794440971, 9.40690817632347))
test_that(desc="Test leaveOneOut",expect_that(max(abs(m2.loo.test$mean-m2.loo$mean))<1e-6, is_true()))
test_that(desc="Test leaveOneOut",expect_that(max(abs(m2.loo.test$sd-m2.loo$sd))<1e-6, is_true()))
context("Checking km examples results: 1D example with penalized MLE")
n <- 6; d <- 1
x <- seq(from=0, to=10, length=n)
y <- sin(x)
t <- seq(0,10, length=100)
epsilon <- 1e-3
model <- km(formula<- ~1, design=data.frame(x=x), response=data.frame(y=y),
covtype="gauss", penalty=list(fun="SCAD", value=3), nugget=epsilon,
control=list(trace=FALSE))
test_that.km(model, trend.coef = -0.5586176, covariance.sd2 = 3.35796, covariance.range.val = 2.417813, covariance.nugget = 0.001)
p <- predict(model, data.frame(x=t), "UK", bias.correct=TRUE)
p.test = list(mean = c(-3.33066907387547e-16, 0.103668583556765,
0.204106764415468, 0.301735270357276, 0.395756768311479, 0.485384515282419,
0.569851151220041, 0.648417561574452, 0.720381694694425, 0.785087216109229,
0.841931880366164, 0.890375501555915, 0.929947405986085, 0.960253254668741,
0.980981129345181, 0.991906783620992, 0.992897970333583, 0.983917767397483,
0.965026836913487, 0.936384566102604, 0.898249053426139, 0.850975918849646,
0.795015933354937, 0.73091147924265, 0.659291869232534, 0.580867568592383,
0.496423380244189, 0.406810667751401, 0.312938705039622, 0.215765254418146,
0.116286485745949, 0.0155263592432038, -0.0854743976639361, -0.185669583082299,
-0.284018942575723, -0.379499577893206, -0.471117200190948, -0.557917087546549,
-0.638994610661276, -0.713505196652745, -0.780673608644263, -0.83980242832094,
-0.890279639583468, -0.931585223704922, -0.963296689783487, -0.985093478570262,
-0.996760192713487, -0.998188621869706, -0.989378546759103, -0.970437321859351,
-0.941578251818738, -0.903117791614111, -0.855471614783334, -0.799149607542319,
-0.73474985908724, -0.662951729736852, -0.584508088662155, -0.500236821676946,
-0.411011716841405, -0.317752841402879, -0.221416527826267, -0.122985089336235,
-0.0234563865111159, 0.0761666339406344, 0.174886308980496, 0.271720421685087,
0.365712045055562, 0.455938961810148, 0.541522561823235, 0.621636126948619,
0.69551242194443, 0.76245051997177, 0.821821801531807, 0.873075076596748,
0.915740790936399, 0.9494342891014, 0.97385811805448, 0.988803366903467,
0.994150049448424, 0.989866547180333, 0.976008140836365, 0.952714668511005,
0.920207357536033, 0.878784885778434, 0.828818735577156, 0.770747910172976,
0.705073088118135, 0.632350295735319, 0.553184181193531, 0.468220976160377,
0.378141232269578, 0.283652419816319, 0.185481475183269, 0.0843673815421025,
-0.0189461355818289, -0.123717720189388, -0.229215232199558,
-0.334722260961891, -0.439544244726991, -0.544021110889371),
sd = c(1.37722860163619e-16, 0.055938047354605, 0.0717239075944272,
0.0885333491721034, 0.103479571632164, 0.11558566074085,
0.124535231655531, 0.130284178908033, 0.132926953513156,
0.132643474051053, 0.129675361680544, 0.124314691041382,
0.116899579170262, 0.107815385655198, 0.0975029505547555,
0.086477898723425, 0.0753678296196528, 0.0649731906768246,
0.0563321548096111, 0.0506662341718909, 0.0489421469571659,
0.0511448312539402, 0.0561923009414814, 0.0626840730368677,
0.0694846347505854, 0.075822706651813, 0.0812033992665197,
0.0853179155081378, 0.0879856320787734, 0.0891211458796282,
0.0887162707338793, 0.0868307797971652, 0.0835888470871021,
0.0791801846304929, 0.073866202141622, 0.067992148964746,
0.0620049698687374, 0.056469588561222, 0.052056108560131,
0.0494397154112441, 0.0490738072493008, 0.0509543226071206,
0.0546149617347237, 0.0593642281895726, 0.064524637090391,
0.0695406284760611, 0.0739914572527713, 0.077571596936056,
0.0800691406401005, 0.0813503165577205, 0.0813503165577172,
0.0800691406401005, 0.0775715969360595, 0.0739914572527677,
0.0695406284760611, 0.064524637090391, 0.059364228189577,
0.0546149617347237, 0.050954322607131, 0.0490738072493116,
0.0494397154112548, 0.0520561085601361, 0.0564695885612173,
0.0620049698687245, 0.067992148964746, 0.0738662021416293,
0.0791801846304862, 0.0835888470871022, 0.0868307797971652,
0.0887162707338762, 0.0891211458796311, 0.0879856320787612,
0.0853179155081378, 0.0812033992665066, 0.07582270665182,
0.0694846347505701, 0.0626840730368719, 0.0561923009414766,
0.0511448312539402, 0.0489421469571659, 0.0506662341718909,
0.0563321548096158, 0.0649731906768328, 0.0753678296196563,
0.0864778987234313, 0.097502950554761, 0.107815385655201,
0.116899579170262, 0.12431469104138, 0.129675361680544, 0.132643474051059,
0.13292695351316, 0.130284178908038, 0.124535231655527, 0.115585660740852,
0.103479571632161, 0.0885333491720974, 0.071723907594431,
0.055938047354605, 0))
test_that(desc="Test predict",expect_equal(p$mean,p.test$mean))
test_that(desc="Test predict",expect_equal(p$sd,p.test$sd))
context("Checking km examples results: 1D example with known trend and known or unknown covariance parameters")
x <- c(0, 0.4, 0.6, 0.8, 1);
y <- c(-0.3, 0, -0.8, 0.5, 0.9)
theta <- 0.01; sigma <- 3; trend <- c(-1,2)
model <- km(~x, design=data.frame(x=x), response=data.frame(y=y),
covtype="matern5_2", coef.trend=trend, coef.cov=theta,
coef.var=sigma^2,
control=list(trace=FALSE))
t <- seq(from=0, to=1, by=0.005)
p <- predict(model, newdata=data.frame(x=t), type="SK")
p.test=list(mean = c(-0.3, -0.409945600307312, -0.613204123817726,
-0.771785710062141, -0.862937846603047, -0.905542849815739, -0.920593604659762,
-0.921829914451626, -0.916656040817311, -0.908661891267655, -0.899474346347788,
-0.889796659403621, -0.879922358335064, -0.869970682858201, -0.859989036423894,
-0.8499959345099, -0.839998503637175, -0.829999452876737, -0.819999801133533,
-0.809999928100776, -0.799999974130126, -0.789999990732495, -0.779999996693293,
-0.769999998824458, -0.759999999583497, -0.749999999852888, -0.739999999948188,
-0.729999999981801, -0.719999999993623, -0.709999999997771, -0.699999999999222,
-0.689999999999729, -0.679999999999906, -0.669999999999967, -0.659999999999989,
-0.649999999999996, -0.639999999999999, -0.63, -0.62, -0.61,
-0.6, -0.59, -0.58, -0.57, -0.56, -0.549999999999999, -0.539999999999997,
-0.529999999999991, -0.519999999999973, -0.509999999999923, -0.499999999999778,
-0.489999999999363, -0.479999999998178, -0.4699999999948, -0.459999999985197,
-0.449999999957968, -0.439999999880999, -0.429999999664131, -0.419999999055227,
-0.409999997352141, -0.399999992608608, -0.389999979457365, -0.37999994318101,
-0.369999843679068, -0.359999572467764, -0.3499988384314, -0.339996867549684,
-0.329991623673772, -0.319977816667161, -0.309941902686749, -0.299849813242225,
-0.28961768321933, -0.27904458309066, -0.267665689843322, -0.254455315617075,
-0.237297957090211, -0.212267956172299, -0.17336734573204, -0.115201178233636,
-0.044270171516375, 0, -0.024270171516375, -0.0752011782336362,
-0.113367345732041, -0.132267956172301, -0.137297957090217, -0.134455315617091,
-0.127665689843368, -0.119044583090795, -0.109617683219717, -0.099849813243336,
-0.0899419026899333, -0.0799778166762707, -0.0699916236997703,
-0.0599968676237009, -0.04999883864156, -0.0399995730627685,
-0.0299998453584138, -0.019999947904877, -0.00999999269665746,
-2.95655697764231e-08, 0.00999989993468188, 0.0199997168498212,
0.0299992187312075, 0.0399978624578226, 0.0499941921990326, 0.0599843377632238,
0.069958118374058, 0.0798890833376284, 0.0897095134343814, 0.0992490662113485,
0.108088416096727, 0.115222915453328, 0.118328449216618, 0.112276578085377,
0.0864897854510566, 0.0213397808614965, -0.113163271339799, -0.34399410883182,
-0.638649142418125, -0.8, -0.618649142418125, -0.30399410883182,
-0.0531632713397988, 0.101339780861496, 0.186489785451056, 0.232276578085373,
0.258328449216605, 0.275222915453288, 0.288088416096611, 0.299249066211015,
0.309709513433426, 0.319889083334896, 0.329958118366258, 0.339984337741019,
0.349994192135985, 0.359997862279321, 0.369999218227404, 0.379999715432661,
0.389999895962894, 0.399999959347342, 0.409999976489389, 0.419999966866637,
0.429999920160188, 0.439999785638878, 0.44999941900554, 0.459998433700825,
0.469995811810887, 0.479988908324471, 0.48997095134019, 0.499924906620002,
0.509808841609278, 0.519522291545196, 0.528832844921614, 0.537227657808521,
0.5436489785451, 0.546133978086148, 0.541683672866019, 0.527600589116818,
0.507135085758187, 0.5, 0.527135085758188, 0.567600589116818,
0.60168367286602, 0.62613397808615, 0.643648978545105, 0.657227657808536,
0.668832844921656, 0.679522291545317, 0.689808841609626, 0.699924906621001,
0.709970951343056, 0.71998890833267, 0.729995811834286, 0.73999843376744,
0.749999419194684, 0.759999786174382, 0.769999921671599, 0.779999971118118,
0.789999988404753, 0.799999992608608, 0.809999988404753, 0.819999971118118,
0.829999921671599, 0.839999786174382, 0.849999419194684, 0.85999843376744,
0.869995811834286, 0.87998890833267, 0.889970951343056, 0.899924906621002,
0.909808841609626, 0.919522291545317, 0.928832844921656, 0.937227657808536,
0.943648978545105, 0.946133978086149, 0.94168367286602, 0.927600589116818,
0.907135085758187, 0.9),
sd = c(0, 1.6793050315316, 2.55516566296315, 2.87721515634081,
2.97102004245279, 2.99394356557226, 2.99884689620796, 2.99979565539401,
2.99996576899956, 2.99999451876546, 2.99999915414755, 2.99999987342633,
2.99999998154624, 2.99999999736889, 2.99999999963204, 2.9999999999494,
2.99999999999315, 2.99999999999908, 2.99999999999988, 2.99999999999998,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2.99999999999998,
2.99999999999988, 2.99999999999908, 2.99999999999315, 2.9999999999494,
2.99999999963204, 2.99999999736889, 2.99999998154624, 2.99999987342633,
2.99999915414755, 2.99999451876546, 2.99996576899956, 2.99979565539401,
2.99884689620796, 2.99394356557226, 2.97102004245279, 2.87721515634081,
2.55516566296315, 1.6793050315316, 0, 1.6793050315316, 2.55516566296315,
2.87721515634081, 2.97102004245279, 2.99394356557226, 2.99884689620796,
2.99979565539401, 2.99996576899956, 2.99999451876546, 2.99999915414755,
2.99999987342633, 2.99999998154624, 2.99999999736889, 2.99999999963204,
2.9999999999494, 2.99999999999315, 2.99999999999908, 2.99999999999988,
2.99999999999998, 3, 2.99999999999998, 2.99999999999988, 2.99999999999908,
2.99999999999315, 2.9999999999494, 2.99999999963204, 2.99999999736889,
2.99999998154624, 2.99999987342633, 2.99999915414755, 2.99999451876546,
2.99996576899956, 2.99979565539401, 2.99884689620796, 2.99394356557226,
2.97102004245279, 2.87721515634081, 2.55516566296315, 1.6793050315316,
0, 1.6793050315316, 2.55516566296315, 2.87721515634081, 2.97102004245279,
2.99394356557226, 2.99884689620796, 2.99979565539401, 2.99996576899956,
2.99999451876546, 2.99999915414755, 2.99999987342633, 2.99999998154624,
2.99999999736889, 2.99999999963204, 2.9999999999494, 2.99999999999315,
2.99999999999908, 2.99999999999988, 2.99999999999998, 3, 2.99999999999998,
2.99999999999988, 2.99999999999908, 2.99999999999315, 2.9999999999494,
2.99999999963204, 2.99999999736889, 2.99999998154624, 2.99999987342633,
2.99999915414755, 2.99999451876546, 2.99996576899956, 2.99979565539401,
2.99884689620796, 2.99394356557226, 2.97102004245279, 2.87721515634081,
2.55516566296315, 1.6793050315316, 0, 1.6793050315316, 2.55516566296315,
2.87721515634081, 2.97102004245279, 2.99394356557226, 2.99884689620796,
2.99979565539401, 2.99996576899956, 2.99999451876546, 2.99999915414755,
2.99999987342633, 2.99999998154624, 2.99999999736889, 2.99999999963204,
2.9999999999494, 2.99999999999315, 2.99999999999908, 2.99999999999988,
2.99999999999998, 3, 2.99999999999998, 2.99999999999988, 2.99999999999908,
2.99999999999315, 2.9999999999494, 2.99999999963204, 2.99999999736889,
2.99999998154624, 2.99999987342633, 2.99999915414755, 2.99999451876546,
2.99996576899956, 2.99979565539401, 2.99884689620796, 2.99394356557226,
2.97102004245279, 2.87721515634081, 2.55516566296315, 1.6793050315316, 0))
test_that(desc="Test predict",expect_equal(p$mean,p.test$mean))
test_that(desc="Test predict",expect_equal(p$sd,p.test$sd))
context("Checking km examples results: Kriging with noisy observations (heterogeneous noise variance)")
fundet <- function(x){
return((sin(10*x)/(1+x)+2*cos(5*x)*x^3+0.841)/1.6)
}
level <- 0.5; epsilon <- 0.1
theta <- 1/sqrt(30); p <- 2; n <- 10
x <- seq(0,1, length=n)
MC_numbers <- c(10,50,50,290,25,75,300,10,40,150)
noise.var <- 3/MC_numbers
y <- fundet(x) + noise.var*rnorm(length(x))
model <- km(y~1, design=data.frame(x=x), response=data.frame(y=y),
covtype="gauss", coef.trend=0, coef.cov=theta, coef.var=1,
noise.var=noise.var,
control=list(trace=FALSE))
t <- seq(0,1,by=0.01)
p <- predict.km(model, newdata=data.frame(x=t), type="SK")
p.test = list(mean=c(0.539334747148277, 0.586647044674522, 0.633654722392378, 0.679929639445603,
0.725032146520035, 0.76851701239259, 0.809939706096152, 0.848862926253087,
0.884863259581319, 0.917537843577757, 0.946510904204198, 0.971440038235026,
0.992022111884504, 1.00799865243506, 1.01916061776519, 1.02535243976294,
1.02647525135751, 1.02248922297386, 1.01341495221093, 0.999333869999283,
0.980387646904218, 0.956776604070301, 0.9287571540107, 0.896638316492772,
0.860777373649944, 0.821574745689538, 0.779468183753871, 0.734926389283163,
0.688442179356868, 0.640525324773073, 0.59169519196919, 0.542473321284192,
0.493376072589807, 0.444907465129216, 0.397552331718294, 0.351769898564123,
0.307987891159104, 0.266597254366536, 0.227947561289564, 0.19234317117567,
0.16004018180712, 0.131244206895013, 0.106108994229466, 0.0847358860015263,
0.067174109021187, 0.0534218696840629, 0.0434282166177865, 0.0370956230593633,
0.0342832312338992, 0.0348106923531448, 0.0384625283391518, 0.04499293500192,
0.0541309411535644, 0.0655858340206116, 0.0790527583232632, 0.0942183945394055,
0.110766621187819, 0.128384066487297, 0.146765456523336, 0.1656186701334,
0.184669415155653, 0.203665446515514, 0.222380253873431, 0.24061615522411,
0.258206742887227, 0.275018639686927, 0.290952535661456, 0.305943489205345,
0.319960490905191, 0.333005303219061, 0.345110604257797, 0.356337478906972,
0.366772315006854, 0.376523175895532, 0.385715732926623, 0.394488852219889,
0.402989938540434, 0.411370145522012, 0.419779565200525, 0.428362510821178,
0.437253005021073, 0.446570580747562, 0.456416494719598, 0.46687044303276,
0.477987855893409, 0.489797833769091, 0.502301770857379, 0.51547269415915,
0.52925532809377, 0.543566876039111, 0.558298491954252, 0.573317397873672,
0.588469587048248, 0.603583038305923, 0.618471355209542, 0.632937734124466,
0.64677915861476, 0.659790713814218, 0.671769913623502, 0.682520935728924,
0.691858664392208),
sd=c(0.377029458451379, 0.353477635741769, 0.331048780750455, 0.309901789954737,
0.290194209894752, 0.272078140711739, 0.255693335726301, 0.241156971388702,
0.228550243358871, 0.217903121026768, 0.209180023038072, 0.202270201518728,
0.196986396115609, 0.193073449055664, 0.190225693933524, 0.188109475678877,
0.186386324483874, 0.184733202947482, 0.182858030705805, 0.180510369041955,
0.17748818331955, 0.173641976171823, 0.168877543352864, 0.163158408232265,
0.156508809270597, 0.149018011275447, 0.140846648943365, 0.132235611420845,
0.123517178517844, 0.11512572777864, 0.107599737842161, 0.101557254845469,
0.0976194088289012, 0.0962714353566698, 0.0977066069260894, 0.101752687919136,
0.107939608904669, 0.115653145670172, 0.124274628914087, 0.133258903590641,
0.142159563724345, 0.150626545790194, 0.158394033615692, 0.165267084194709,
0.171109726773692, 0.175834882207011, 0.179395709724203, 0.181777922609756,
0.18299276787915, 0.183070560424202, 0.18205483806674, 0.179997341432579,
0.176954116156102, 0.172983084635437, 0.168143445517905, 0.162497243795756,
0.156113433919499, 0.149074759545596, 0.141487817200238, 0.133496739715259,
0.125300892938463, 0.117176389739067, 0.109499017316081, 0.102760375180372,
0.0975580180680758, 0.0945294254198149, 0.094211568198508, 0.0968685832496973,
0.102397003846006, 0.110380425208506, 0.12023962124095, 0.131371888401085,
0.143228876118868, 0.155342329216061, 0.167323289645481, 0.178852522758449,
0.189670189557165, 0.199567202683516, 0.20837840113671, 0.215977000068187,
0.22226973231672, 0.22719226116034, 0.230704645851273, 0.232786831193859,
0.233434297578214, 0.232654148383716, 0.230462031132744, 0.226880394359816,
0.221938688196329, 0.21567625058695, 0.208148830747982, 0.199440062098813,
0.189679808332715, 0.179072247643501, 0.167937686154268, 0.156772333879503,
0.146325713173994, 0.137675771860785, 0.132232680285778, 0.13154331895153,
0.136834814016462))
test_that(desc="Test predict",expect_equal(p$mean,p.test$mean))
test_that(desc="Test predict",expect_equal(p$sd,p.test$sd))
context("Checking km examples results: Kriging with non-linear scaling on Xiong et al.'s function")
f11_xiong <- function(x){
return( sin(30*(x - 0.9)^4)*cos(2*(x - 0.9)) + (x - 0.9)/2)
}
t <- seq(0,1,,300)
f <- f11_xiong(t)
doe <- data.frame(x=seq(0,1,,20))
resp <- f11_xiong(doe)
knots <- list( c(0,0.5,1) )
m <- km(design=doe, response=resp, scaling=TRUE, gr=TRUE,
knots=knots, covtype="matern5_2", coef.var=1, coef.trend=0,
control=list(trace=FALSE))
test_that.km(m, covariance.eta = c(17.6113829, 2.4169448,0.8873958), precision=1e-4)
p <- predict(m, data.frame(x=t), "UK", bias.correct=TRUE)
p.test = list(mean=c(-0.6181866493757, -0.619384327994964, -0.617544523595288, -0.612923071362958,
-0.605845139548477, -0.596671063973597, -0.5857719188513, -0.573512506951456,
-0.560239960336162, -0.546276545346517, -0.531915583696315, -0.517419652595045,
-0.503020424530901, -0.48891966269035, -0.475291009762516, -0.462282303092248,
-0.450018223374948, -0.438603069295669, -0.42812274959666, -0.418645515567079,
-0.410222490091608, -0.402888224309673, -0.396661205967063, -0.391544260046136,
-0.387524798637093, -0.384574889326519, -0.382651120532267, -0.381694248922229,
-0.381628618885048, -0.382361347422901, -0.383781270163437, -0.385757645719527,
-0.388138619983493, -0.390750112138151, -0.39339879496282, -0.395878591204417,
-0.397976974292908, -0.399480772708841, -0.400181725829701, -0.399882006665258,
-0.39839989913914, -0.395575795258101, -0.39127865957273, -0.3854130938907,
-0.377927123515424, -0.368820816728299, -0.358155841284965, -0.346066054910513,
-0.33276910000895, -0.318572838493337, -0.303859639167353, -0.289060874908515,
-0.274635057702686, -0.261049657449351, -0.24876576473141, -0.238224905538517,
-0.229837438656032, -0.223972068333405, -0.220946089591973, -0.221016054175952,
-0.224368604223206, -0.231111270339583, -0.24126307264834, -0.254744799000975,
-0.271369340122068, -0.290841799346952, -0.312780978672547, -0.336744665077429,
-0.362250734912443, -0.388794612006908, -0.415863768733658, -0.44294984162595,
-0.46955883415162, -0.495219795913324, -0.519492297338891, -0.541972959729411,
-0.562301250572315, -0.58016471181062, -0.595303753045532, -0.607516110964843,
-0.616660528928325, -0.622654732051651, -0.625466489130159, -0.62510481364984,
-0.621612795849773, -0.615061819013151, -0.605546931866299, -0.593183182715417,
-0.578102749616398, -0.560452725215194, -0.54039343557363, -0.518097189866798,
-0.493747372773389, -0.467537804093884, -0.439672300960193, -0.410364383850582,
-0.379836606390905, -0.348317278525024, -0.316035481422044, -0.283216733342154,
-0.250079473593566, -0.216832238706492, -0.18367142428487, -0.150779543024492,
-0.118323903822031, -0.0864556491104871, -0.0553090978625722,
-0.025001350370222, 0.00436788182654946, 0.0327162514325693,
0.0599785818530151, 0.0861065136495609, 0.111067500215288, 0.134842073141954,
0.157420631276143, 0.17880074278872, 0.198984948559774, 0.217978999387435,
0.235790468125003, 0.252427685264059, 0.267898952858084, 0.282211997182547,
0.295373625258048, 0.3073895544446, 0.318264387829763, 0.328001711173836,
0.336604289799667, 0.34407438300404, 0.350414777597394, 0.355630963113317,
0.359733138904088, 0.362737619456597, 0.364667717790052, 0.365554190300026,
0.365435316966647, 0.364356682516446, 0.36237071675713, 0.35953604575857,
0.355916699693483, 0.351581217897373, 0.346601686947497, 0.341052743241555,
0.335010567551571, 0.328551867513987, 0.321752661075919, 0.314686950737844,
0.307425655285841, 0.300035827577346, 0.292580112854382, 0.285116407162208,
0.27766204250694, 0.270041862952395, 0.262242107025742, 0.254283613101952,
0.246187224420236, 0.237973694135407, 0.22966359627162, 0.22127724230822,
0.212834603129049, 0.204355235204216, 0.195858207012237, 0.187362026833072,
0.178884575211622, 0.17044304226518, 0.162053869619148, 0.153732696771108,
0.145494311686322, 0.137352605442916, 0.129320530751226, 0.121410064183481,
0.113632171952961, 0.105996779097326, 0.0985127419209676, 0.0911878235616712,
0.084028673156181, 0.0770408295665373, 0.0702287931929301, 0.0635961260874189,
0.0571455481314747, 0.0508790277534277, 0.0447978674345578, 0.0389027842294168,
0.0331939855252174, 0.0276712402481287, 0.0223339457174205, 0.0171811903426216,
0.012211812341782, 0.00742445466112723, 0.00281761625927527,
-0.00161030008117329, -0.00586094412986754, -0.00993599177390887,
-0.0138371466425015, -0.0175661490456186, -0.0211247843624052,
-0.0245148907297168, -0.0277383660603413, -0.0307971744181088,
-0.0336933517779194, -0.0364290111936353, -0.0390063474041107,
-0.0414276408938766, -0.043695261437668, -0.0458116711464816,
-0.0477794270378376, -0.0496011831495988, -0.0512796917672645,
-0.0528178004990926, -0.0542184449995801, -0.0554846412842739,
-0.0566194783879771, -0.0576261113543447, -0.0585077545441052,
-0.0592676752434355, -0.0599091875622562, -0.0604356466079271,
-0.0608504429197739, -0.0611569971574735, -0.0613587550243052,
-0.0614591824230813, -0.0614617608275543, -0.0613699828459608,
-0.0611873466596634, -0.0609173445435782, -0.0605634478750595,
-0.0601290929642404, -0.0596176680799324, -0.0590325016143571,
-0.0583768513313831, -0.0576538946484541, -0.0568667199002712,
-0.056018318538126, -0.0551115782169636, -0.0541492767282164,
-0.053134076733538, -0.0520685212602773, -0.0509550299185329,
-0.0497958959771331, -0.0485932893203502, -0.0473492739893414,
-0.0460658305532157, -0.0447448768083503, -0.0433882866015425,
-0.0419979068691594, -0.0405755729807539, -0.0391231224764197,
-0.037642407279874, -0.0361353044671106, -0.0346037256676119,
-0.0330496251735891, -0.0314750068279022, -0.029881929758972,
-0.0282725130298932, -0.0266489379356994, -0.0250134308116316,
-0.0233682159255298, -0.0217154651520595, -0.0200572529111883,
-0.0183955162365097, -0.0167320196916362, -0.0150683248582279,
-0.0134057641334375, -0.0117454185846687, -0.0100880996189366,
-0.00843433422987598, -0.00678435360090385, -0.00513808484810206,
-0.00349514569129573, -0.00185484187708767, -0.00021617168983519,
0.00142213417059717, 0.00306154084187579, 0.00470363940656769,
0.00635008412999384, 0.00800253644346121, 0.0096626152789829,
0.0113318533696893, 0.0130116591535249, 0.0147032839285056, 0.0164077939210321,
0.01812604694847, 0.0198586733609143, 0.0216060609695321, 0.0233683436753124,
0.0251453936053517, 0.026936821616966, 0.0287420016740626, 0.0305601077090647,
0.0323901483514226, 0.0342309984794159, 0.0360814277847514, 0.0379401265308031,
0.039805728677887, 0.0416768325421688, 0.0435520191471147, 0.0454298684185662,
0.0473089733708269, 0.0491879524196559, 0.0510654599590658, 0.052940195323104
),
sd=c(5.40521927259871e-09, 0.0278955268448099, 0.0527585896172703,
0.0739907998166573, 0.0911593329653399, 0.103979113019168, 0.112298629160489,
0.116088760303684, 0.115434249987665, 0.110527531524034, 0.101664573762998,
0.0892423550839467, 0.0737575014939018, 0.0558055602221966, 0.0360803469228653,
0.0153728564251457, 0.00543056383264634, 0.0253804824448798,
0.0436243232213521, 0.0594847396849461, 0.0724484332714464, 0.0821529857215723,
0.0883749441803885, 0.0910191504001311, 0.090109354682045, 0.0857800864787522,
0.0782696560953018, 0.0679140679135962, 0.0551415471531945, 0.0404673284002107,
0.0244883430773698, 0.00787751923542965, 0.00862301047745113,
0.0242523811374775, 0.0383578795645493, 0.0504259263091857, 0.060073235236072,
0.0670380051926555, 0.0711714614319289, 0.0724298026008374, 0.0708666151632932,
0.0666257608974258, 0.0599346743115707, 0.0510979442963852, 0.0404910063063968,
0.0285537455708464, 0.0157838237623598, 0.00272962748301085,
0.0100194860268291, 0.0218917845732854, 0.0324154436456769, 0.041226072210972,
0.0480604358327453, 0.0527500887865998, 0.0552149089868492, 0.0554566080881815,
0.0535522815305141, 0.0496480244197844, 0.0439525957426021, 0.036731076282206,
0.0282984402728045, 0.0190129534423633, 0.00926933292299627,
0.000508314633666543, 0.00987887094446615, 0.0184394549981615,
0.025868805193392, 0.0319263863521959, 0.0364476944644532, 0.0393392568502533,
0.0405733622311219, 0.0401825961301444, 0.0382542477369581, 0.0349246297860518,
0.0303733273987832, 0.0248173713629215, 0.0185053195971253, 0.0117112320949676,
0.00472854851496484, 0.00213608466720373, 0.00857703536284724,
0.0143320779778923, 0.01920010213466, 0.0230382212933763, 0.0257579258195494,
0.0273209044938779, 0.027734593873248, 0.0270475309664019, 0.0253445760290491,
0.0227420566204376, 0.0193828688312309, 0.0154315601428472, 0.0110694129370792,
0.00648955128236172, 0.00189211244663229, 0.00252062580429939,
0.00655821986761304, 0.0100680349620087, 0.0129397490195468,
0.0151023575824548, 0.0165208562061587, 0.0171926877066967, 0.0171440201894679,
0.0164259252930565, 0.0151105180215727, 0.0132871086353029, 0.0110584070205879,
0.00853681248148238, 0.00584081822587245, 0.0030915617872107,
0.000409564033737249, 0.00208876593896904, 0.00430216449017573,
0.00615645492601835, 0.00760391452504312, 0.00862060533720077,
0.00920357645564576, 0.00936798525194681, 0.00914419573867131,
0.00857490906518254, 0.00771237319010031, 0.00661571005253904,
0.00534839078003959, 0.00397588338780098, 0.00256349360766343,
0.00117441883154567, 0.000131960472590607, 0.00130221158917693,
0.00229518025109844, 0.00308525654371616, 0.00366061098970859,
0.00402110530459799, 0.00417623390728292, 0.00414313350870577,
0.00394469727146971, 0.00360782388655352, 0.00316182448568462,
0.00263700322359383, 0.00206342123657317, 0.00146984871518563,
0.000882906106068735, 0.000326393111302364, 0.00017919945124684,
0.000617502861537928, 0.000978176647015097, 0.00125681052512315,
0.00145375833407683, 0.00157304170827566, 0.00162136080526537,
0.00160722109959803, 0.00153974554393112, 0.00142436837949148,
0.00126633761399362, 0.00107215305790654, 0.000849243596628756,
0.000605830445054434, 0.000350781121539972, 9.34557230022058e-05,
0.000156461894606401, 0.000389530359206717, 0.000597578015332369,
0.000773965170886398, 0.000913601489404074, 0.00101294403454977,
0.00106997595903501, 0.00108416608705489, 0.00105641026773893,
0.000988955608436533, 0.000885308725116187, 0.00075012910692986,
0.000589108661666367, 0.000408838589325305, 0.000216665045473663,
2.05358786258385e-05, 0.000171195663440373, 0.00035049470042588,
0.000510462170714594, 0.00064547147590016, 0.000751196250130842,
0.00082461791854646, 0.000864013024818227, 0.000868921373466751,
0.000840096400322934, 0.000779439245878901, 0.000689917932191898,
0.000575472935835753, 0.000440910388231675, 0.000291784190593147,
0.00013426865201414, 2.49759352367094e-05, 0.000179029580407467,
0.000321463534618553, 0.000446854479379327, 0.000550845208077309,
0.000630162898882065, 0.000682619492371508, 0.000707094717834278,
0.00070350298582261, 0.000672745558617544, 0.000616649392677178,
0.000537893952064388, 0.000439927185715771, 0.000326871812311767,
0.000203423136934822, 7.47399457217233e-05, 5.36703955013989e-05,
0.000176223765368053, 0.000287924529942511, 0.000384636393809221,
0.000463108413248862, 0.000520981923362827, 0.00055678272003298,
0.000569899274228118, 0.000560548166050523, 0.0005297280036614,
0.000479163051962901, 0.00041123769638931, 0.000328922784868723,
0.000235694860014172, 0.000135449388533949, 3.24094344400267e-05,
6.89750596878059e-05, 0.000164340771316577, 0.000249916380224616,
0.000322641253834587, 0.000380175530727422, 0.000420898010528653,
0.000443892364955128, 0.000448922521742606, 0.00043639830101167,
0.000407332408300389, 0.000363289826996956, 0.000306330563905879,
0.000238946643657319, 0.000163994227643533, 8.46218434857493e-05,
4.19605289148908e-06, 7.37936649095409e-05, 0.000146060736710977,
0.000209846922736215, 0.000262963820935719, 0.000303793912147134,
0.000331282275677673, 0.000344919445923973, 0.000344716229990787,
0.000331171444458688, 0.000305233497624261, 0.000268256691983734,
0.000221953047406635, 0.000168340390248118, 0.000109687473029649,
4.84569757950173e-05, 1.27524710410294e-05, 7.13034155784107e-05,
0.000124811915473892, 0.000171320676715324, 0.00020930911251436,
0.000237689136521643, 0.000255794183156826, 0.000263361980089882,
0.00026051181346646, 0.000247717087779459, 0.000225773936214625,
0.000195766598363813, 0.000159030220130916, 0.000117111705794583,
7.17292720886261e-05, 2.47314354002609e-05, 2.19442339162618e-05,
6.63678680666483e-05, 0.000106831375282275, 0.000141922537176468,
0.000170527257494718, 0.000191826601721701, 0.000205289795982779,
0.000210663613661126, 0.000207958686742575, 0.000197433290365047,
0.00017957513853237, 0.000155081669579709, 0.000124839293810563,
8.99020365281582e-05, 5.14700095128775e-05, 1.08682044601612e-05,
3.04760387232468e-05, 7.11069314639068e-05, 0.000109651244740311,
0.000144843205375932, 0.000175529086439696, 0.000200670149077007,
0.000219344018510228, 0.000230744672357331, 0.000234181207482184,
0.000229075585637918, 0.000214959535503335, 0.000191470767953811,
0.000158348663688514, 0.000115429547853075, 6.26416716073123e-05,
5.4052192726006e-09))
test_that(desc="Test predict",expect_that(max(abs(p$mean-p.test$mean))<1e-6, is_true()))
test_that(desc="Test predict",expect_that(max(abs(p$sd-p.test$sd))<1e-6, is_true())) |
data_dir <- file.path("..", "testdata")
tempfile_nc <- function() {
tempfile_helper("daymin_")
}
file_out <- tempfile_nc()
daymin("SIS", file.path(data_dir, "ex_dayx.nc"), file_out)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
expected_data <- c(250,251,250,251,252,250,251,
252,250,251,252,250,251,250,
250,251,250,250,251,250,250,
251,250,250,251,250,251,252,
250,251,252,250,251,252,250,
251,250,250,251,250,250,251,
250,250,251,250,250,251,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,251,250,250,251,250,
250,251,250,251,252,250,251,
252,250,251,250,250,251,250,
250,251,250,250,251,250,250,
251,250,250,251,250,251,252,
250,251,252,250,251,250,250,
251,250,250,251,250,250,251)
expected <- array(expected_data, dim = c(7, 7, 3))
expect_equivalent(actual, expected)
})
test_that("variable attributes are correct", {
actual <- ncatt_get(file, "SIS", "units")$value
expect_equal(actual, "W m-2")
actual <- ncatt_get(file, "SIS", "_FillValue")$value
expect_equal(actual, -999)
actual <- ncatt_get(file, "SIS", "standard_name")$value
expect_equal(actual, "SIS_standard")
actual <- ncatt_get(file, "SIS", "long_name")$value
expect_equal(actual, "Surface Incoming Shortwave Radiation")
actual <- ncatt_get(file, "SIS", "missing_value")$value
expect_equal(actual, 0)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
actual <- ncatt_get(file, "SIS", "standard_name")$value
expect_equal(actual, "SIS_standard")
actual <- ncatt_get(file, "SIS", "long_name")$value
expect_equal(actual, "Surface Incoming Shortwave Radiation")
actual <- ncatt_get(file, "SIS", "units")$value
expect_equal(actual, "W m-2")
actual <- ncatt_get(file, "SIS", "_FillValue")$value
expect_equal(actual, -999)
actual <- ncatt_get(file, "SIS", "cmsaf_info")$value
expect_equal(actual, "cmsafops::daymin for variable SIS")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149028, 149040, 149064)))
})
nc_close(file)
file_out <- tempfile_nc()
daymin("SIS", file.path(data_dir, "ex_dayx.nc"), file_out, nc34 = 4)
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
expected_data <- c(250,251,250,251,252,250,251,
252,250,251,252,250,251,250,
250,251,250,250,251,250,250,
251,250,250,251,250,251,252,
250,251,252,250,251,252,250,
251,250,250,251,250,250,251,
250,250,251,250,250,251,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,251,250,250,251,250,
250,251,250,251,252,250,251,
252,250,251,250,250,251,250,
250,251,250,250,251,250,250,
251,250,250,251,250,251,252,
250,251,252,250,251,250,250,
251,250,250,251,250,250,251)
expected <- array(expected_data, dim = c(7, 7, 3))
expect_equivalent(actual, expected)
})
test_that("variable attributes are correct", {
actual <- ncatt_get(file, "SIS", "units")$value
expect_equal(actual, "W m-2")
actual <- ncatt_get(file, "SIS", "_FillValue")$value
expect_equal(actual, -999)
actual <- ncatt_get(file, "SIS", "standard_name")$value
expect_equal(actual, "SIS_standard")
actual <- ncatt_get(file, "SIS", "long_name")$value
expect_equal(actual, "Surface Incoming Shortwave Radiation")
actual <- ncatt_get(file, "SIS", "missing_value")$value
expect_equal(actual, 0)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149028, 149040, 149064)))
})
nc_close(file)
file_out <- tempfile_nc()
test_that("error is thrown if ncdf version is wrong", {
expect_error(
daymin("SIS", file.path(data_dir, "ex_dayx.nc"), file_out, nc34 = 7),
"nc version must be in c(3, 4), but was 7", fixed = TRUE
)
})
file_out <- tempfile_nc()
test_that("ncdf version NULL throws an error", {
expect_error(
daymin("SIS",
file.path(data_dir, "ex_dayx.nc"),
file_out, nc34 = NULL),
"nc_version must not be NULL"
)
})
file_out <- tempfile_nc()
test_that("warning is shown if var does not exist", {
expect_warning(daymin("notExist",
file.path(data_dir, "ex_dayx.nc"),
file_out),
"Variable 'notExist' not found. Variable 'SIS' will be used instead.")
})
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
expected_data <- c(250,251,250,251,252,250,251,
252,250,251,252,250,251,250,
250,251,250,250,251,250,250,
251,250,250,251,250,251,252,
250,251,252,250,251,252,250,
251,250,250,251,250,250,251,
250,250,251,250,250,251,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,251,250,250,251,250,
250,251,250,251,252,250,251,
252,250,251,250,250,251,250,
250,251,250,250,251,250,250,
251,250,250,251,250,251,252,
250,251,252,250,251,250,250,
251,250,250,251,250,250,251)
expected <- array(expected_data, dim = c(7, 7, 3))
expect_equivalent(actual, expected)
})
test_that("variable attributes are correct", {
actual <- ncatt_get(file, "SIS", "units")$value
expect_equal(actual, "W m-2")
actual <- ncatt_get(file, "SIS", "_FillValue")$value
expect_equal(actual, -999)
actual <- ncatt_get(file, "SIS", "standard_name")$value
expect_equal(actual, "SIS_standard")
actual <- ncatt_get(file, "SIS", "long_name")$value
expect_equal(actual, "Surface Incoming Shortwave Radiation")
actual <- ncatt_get(file, "SIS", "missing_value")$value
expect_equal(actual, 0)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149028, 149040, 149064)))
})
nc_close(file)
file_out <- tempfile_nc()
test_that("error is thrown if variable is NULL", {
expect_error(
daymin(NULL,
file.path(data_dir, "ex_dayx.nc"),
file_out),
"variable must not be NULL"
)
})
file_out <- tempfile_nc()
test_that("warning is shown if var is empty", {
expect_warning(daymin("",
file.path(data_dir, "ex_dayx.nc"),
file_out),
"Variable '' not found. Variable 'SIS' will be used instead.")
})
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
expected_data <- c(250,251,250,251,252,250,251,
252,250,251,252,250,251,250,
250,251,250,250,251,250,250,
251,250,250,251,250,251,252,
250,251,252,250,251,252,250,
251,250,250,251,250,250,251,
250,250,251,250,250,251,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,251,250,250,251,250,
250,251,250,251,252,250,251,
252,250,251,250,250,251,250,
250,251,250,250,251,250,250,
251,250,250,251,250,251,252,
250,251,252,250,251,250,250,
251,250,250,251,250,250,251)
expected <- array(expected_data, dim = c(7, 7, 3))
expect_equivalent(actual, expected)
})
test_that("variable attributes are correct", {
actual <- ncatt_get(file, "SIS", "units")$value
expect_equal(actual, "W m-2")
actual <- ncatt_get(file, "SIS", "_FillValue")$value
expect_equal(actual, -999)
actual <- ncatt_get(file, "SIS", "standard_name")$value
expect_equal(actual, "SIS_standard")
actual <- ncatt_get(file, "SIS", "long_name")$value
expect_equal(actual, "Surface Incoming Shortwave Radiation")
actual <- ncatt_get(file, "SIS", "missing_value")$value
expect_equal(actual, 0)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149028, 149040, 149064)))
})
nc_close(file)
file_out <- tempfile_nc()
test_that("error is thrown if input file does not exist", {
expect_error(
daymin("SIS",
file.path(data_dir, "xemaple1.nc"),
file_out),
"Input file does not exist")
})
file_out <- tempfile_nc()
test_that("error is thrown if input filename is empty", {
expect_error(
daymin("SIS", "", file_out),
"Input file does not exist")
})
file_out <- tempfile_nc()
test_that("error is thrown if input filename is NULL", {
expect_error(
daymin("SIS", NULL, file_out),
"Input filepath must be of length one and not NULL"
)
})
file_out <- tempfile_nc()
cat("test\n", file = file_out)
test_that("error is thrown if output file already exists", {
expect_error(
daymin("SIS",
file.path(data_dir, "ex_dayx.nc"),
file_out),
paste0("File '",
file_out,
"' already exists. Specify 'overwrite = TRUE' if you want to overwrite it."),
fixed = TRUE
)
expect_equal(readLines(con = file_out), "test")
})
file_out <- tempfile_nc()
cat("test\n", file = file_out)
test_that("no error is thrown if overwrite = TRUE", {
expect_error(
daymin("SIS",
file.path(data_dir, "ex_dayx.nc"),
file_out,
overwrite = TRUE
),
NA
)
})
file <- nc_open(file_out)
test_that("data is correct", {
actual <- ncvar_get(file)
expected_data <- c(250,251,250,251,252,250,251,
252,250,251,252,250,251,250,
250,251,250,250,251,250,250,
251,250,250,251,250,251,252,
250,251,252,250,251,252,250,
251,250,250,251,250,250,251,
250,250,251,250,250,251,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,250,250,250,250,250,
250,250,251,250,250,251,250,
250,251,250,251,252,250,251,
252,250,251,250,250,251,250,
250,251,250,250,251,250,250,
251,250,250,251,250,251,252,
250,251,252,250,251,250,250,
251,250,250,251,250,250,251)
expected <- array(expected_data, dim = c(7, 7, 3))
expect_equivalent(actual, expected)
})
test_that("variable attributes are correct", {
actual <- ncatt_get(file, "SIS", "units")$value
expect_equal(actual, "W m-2")
actual <- ncatt_get(file, "SIS", "_FillValue")$value
expect_equal(actual, -999)
actual <- ncatt_get(file, "SIS", "standard_name")$value
expect_equal(actual, "SIS_standard")
actual <- ncatt_get(file, "SIS", "long_name")$value
expect_equal(actual, "Surface Incoming Shortwave Radiation")
actual <- ncatt_get(file, "SIS", "missing_value")$value
expect_equal(actual, 0)
})
test_that("attributes are correct", {
actual <- ncatt_get(file, "lon", "units")$value
expect_equal(actual, "degrees_east")
actual <- ncatt_get(file, "lon", "long_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "standard_name")$value
expect_equal(actual, "longitude")
actual <- ncatt_get(file, "lon", "axis")$value
expect_equal(actual, "X")
actual <- ncatt_get(file, "lat", "units")$value
expect_equal(actual, "degrees_north")
actual <- ncatt_get(file, "lat", "long_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "standard_name")$value
expect_equal(actual, "latitude")
actual <- ncatt_get(file, "lat", "axis")$value
expect_equal(actual, "Y")
actual <- ncatt_get(file, "time", "units")$value
expect_equal(actual, "hours since 1983-01-01 00:00:00")
actual <- ncatt_get(file, "time", "long_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "standard_name")$value
expect_equal(actual, "time")
actual <- ncatt_get(file, "time", "calendar")$value
expect_equal(actual, "standard")
global_attr <- ncatt_get(file, 0)
expect_equal(length(global_attr), 1)
actual <- names(global_attr[1])
expect_equal(actual, "Info")
actual <- global_attr[[1]]
expect_equal(actual, "Created with the CM SAF R Toolbox.")
})
test_that("coordinates are correct", {
actual <- ncvar_get(file, "lon")
expect_identical(actual, array(seq(5, 8, 0.5)))
actual <- ncvar_get(file, "lat")
expect_identical(actual, array(seq(45, 48, 0.5)))
actual <- ncvar_get(file, "time")
expect_equal(actual, array(c(149028, 149040, 149064)))
})
nc_close(file) |
sample.df <- function (df, size, replace=FALSE, sort=FALSE, prob=NULL) {
if(!is(df, "data.frame")) stop("first argument must be a data frame")
N <- nrow(df)
if (!missing(prob)) {
if (length(prob) != N) stop("prob= argument must provide weigths for all rows of the data frame")
}
idx.sample <- sample.int(N, size, replace=replace, prob=prob)
if (sort) idx.sample <- sort(idx.sample)
df[idx.sample, , drop=FALSE]
} |
epGraphs <-
function(res,x_axis=1,y_axis=2,epPlotInfo=NULL,DESIGN=NULL,fi.col=NULL,fi.pch=NULL,fj.col=NULL,fj.pch=NULL,col.offset=NULL,constraints=NULL,xlab=NULL,ylab=NULL,main=NULL,contributionPlots=TRUE,correlationPlotter=TRUE,graphs=TRUE){
pca.types <- c('epPCA','epMDS','epGPCA')
ca.types <- c('epCA','epMCA')
if(class(res)[1] == "expoOutput"){
if(length(res)==2){
epPlotInfo <- res$Plotting.Data
}
res <- res$ExPosition.Data
}
if(!(class(res)[1] %in% c(pca.types,ca.types))){
stop("Unknown ExPosition class. Plotting has stopped.")
}
if(!is.null(epPlotInfo) && (class(epPlotInfo)[1] != "epGraphs")){
stop("Unknown epPlotInfo class. Plotting has stopped.")
}
if(!is.null(epPlotInfo)){
if( !(nrow(res$fi)==nrow(epPlotInfo$fi.col)) ){
print('$fi Dimension mismatch. epPlotInfo will be reset.')
epPlotInfo <- list(fi.col=NULL,fi.pch=NULL,fj.col=NULL,fj.pch=NULL,constraints=NULL)
}
if( (!(class(res)[1]=='epMDS')) && !(nrow(res$fj)==nrow(epPlotInfo$fj.col)) ){
print('$fj Dimension mismatch. epPlotInfo will be reset.')
epPlotInfo <- list(fi.col=NULL,fi.pch=NULL,fj.col=NULL,fj.pch=NULL,constraints=NULL)
}
}else{
epPlotInfo <- list(fi.col=NULL,fi.pch=NULL,fj.col=NULL,fj.pch=NULL,constraints=NULL)
}
if(is.null(main)){
main <- deparse(substitute(res))
}
if(length(unlist(strsplit(main,"")))>40){
main <- "Results"
}
if(is.null(xlab)){
xlab <- paste("Component ",x_axis," variance: ", round(res$t[x_axis],3), "%",sep="")
}
if(is.null(ylab)){
ylab <- paste("Component ",y_axis," variance: ", round(res$t[y_axis],3), "%",sep="")
}
if( (!is.null(col.offset)) && is.numeric(col.offset)){
if(col.offset > 1){
col.offset <- col.offset / as.numeric(paste(c(1,rep(0,nchar(as.character(col.offset)))),collapse=""))
}
}
if(length(fi.col)==1){
fi.col <- as.matrix(rep(fi.col,nrow(res$fi)))
}else if(is.null(fi.col) && !is.null(DESIGN)){
fi.col <- createColorVectorsByDesign(DESIGN,offset=col.offset)$oc
}else if(is.null(fi.col) && !is.null(epPlotInfo$fi.col)){
fi.col <- epPlotInfo$fi.col
}
if(is.null(fi.col)){
fi.col <- createColorVectorsByDesign(matrix(1,nrow(res$fi),1),offset=col.offset)$oc
}
if(nrow(fi.col)!=nrow(res$fi)){
print('Incorrect fi.col. Creating default colors.')
fi.col <- createColorVectorsByDesign(matrix(1,nrow(res$fi),1),offset=col.offset)$oc
}
if(length(fi.pch)==1){
fi.pch <- as.matrix(rep(fi.pch,nrow(res$fi)))
}else if(is.null(fi.pch) && !is.null(epPlotInfo$fi.pch)){
fi.pch <- epPlotInfo$fi.pch
}
if(is.null(fi.pch)){
fi.pch <- as.matrix(rep(21,nrow(res$fi)))
}
if(nrow(fi.pch)!=nrow(res$fi)){
print('Incorrect fi.pch. Creating default pch.')
fi.pch <- as.matrix(rep(21,nrow(res$fi)))
}
if(class(res)[1]!='epMDS'){
if(length(fj.col)==1){
fj.col <- as.matrix(rep(fj.col,nrow(res$fj)))
}else if(is.null(fj.col) && !is.null(epPlotInfo$fj.col)){
fj.col <- epPlotInfo$fj.col
}
if(is.null(fj.col)){
fj.col <- createColorVectorsByDesign(matrix(1,nrow(res$fj),1),hsv=FALSE)$oc
}
if(nrow(fj.col)!=nrow(res$fj)){
print('Incorrect fj.col. Creating default colors.')
fj.col <- createColorVectorsByDesign(matrix(1,nrow(res$fj),1),hsv=FALSE)$oc
}
if(length(fj.pch)==1){
fj.pch <- as.matrix(rep(fj.pch,nrow(res$fj)))
}else if(is.null(fj.pch) && !is.null(epPlotInfo$fj.pch)){
fj.pch <- epPlotInfo$fj.pch
}
if(is.null(fj.pch)){
fj.pch <- as.matrix(rep(21,nrow(res$fj)))
}
if(nrow(fj.pch)!=nrow(res$fj)){
print('Incorrect fj.pch. Creating default pch.')
fj.pch <- as.matrix(rep(21,nrow(res$fj)))
}
}
if(is.null(constraints) && !is.null(epPlotInfo$constraints)){
constraints <- epPlotInfo$constraints
}
constraints <- calculateConstraints(results=res,x_axis=x_axis,y_axis=y_axis,constraints=constraints)
if(graphs){
fi.plot.info <- prettyPlot(res$fi,x_axis=x_axis,y_axis=y_axis,col=fi.col,axes=TRUE,xlab=xlab,ylab=ylab,main=main,constraints=constraints,pch=fi.pch,contributionCircles=TRUE,contributions=res$ci,dev.new=TRUE)
if(!(class(res)[1]=='epMDS')){
fj.plot.info <- prettyPlot(res$fj,x_axis=x_axis,y_axis=y_axis,col=fj.col,axes=TRUE,xlab=xlab,ylab=ylab,main=main,constraints=constraints,pch=fj.pch,contributionCircles=TRUE,contributions=res$cj,dev.new=TRUE)
}
if(contributionPlots){
contributionBars(res$fi,res$ci,x_axis=x_axis,y_axis=y_axis,main=main,col=fi.plot.info$col)
if(!(class(res)[1]=='epMDS')){
contributionBars(res$fj,res$cj,x_axis=x_axis,y_axis=y_axis,main=main,col=fj.plot.info$col)
}
}
if(correlationPlotter && class(res)[1]%in%pca.types){
if(class(res)[1]=='epMDS'){
correlationPlotter(res$X,res$fi,col=fi.col,pch=fi.pch,x_axis=x_axis,y_axis=y_axis,xlab=xlab,ylab=ylab,main=main)
}else{
correlationPlotter(res$X,res$fi,col=fj.col,pch=fj.pch,x_axis=x_axis,y_axis=y_axis,xlab=xlab,ylab=ylab,main=main)
}
}
}
if(class(res)[1]=='epMDS'){
epPlotInfo <- list(fi.col=fi.col,fi.pch=fi.pch,fj.col=fi.col,fj.pch=fi.pch,constraints=constraints)
}else{
epPlotInfo <- list(fi.col=fi.col,fi.pch=fi.pch,fj.col=fj.col,fj.pch=fj.pch,constraints=constraints)
}
class(epPlotInfo) <- c("epGraphs", "list")
return(epPlotInfo)
} |
context("replacement costs")
test_that("maximum obj", {
skip_on_cran()
skip_if_not(any_solvers_installed())
projects <- tibble::tibble(name = c("P1", "P2", "P3", "P4"),
success = c(0.95, 0.96, 0.94, 1.00),
F1 = c(0.91, 0.00, 0.80, 0.10),
F2 = c(0.00, 0.92, 0.80, 0.10),
F3 = c(0.00, 0.00, 0.00, 0.10),
A1 = c(TRUE, FALSE, FALSE, FALSE),
A2 = c(FALSE, TRUE, FALSE, FALSE),
A3 = c(FALSE, FALSE, TRUE, FALSE),
A4 = c(FALSE, FALSE, FALSE, TRUE))
actions <- tibble::tibble(name = c("A1", "A2", "A3", "A4"),
cost = c(0.10, 0.10, 0.15, 0))
features <- tibble::tibble(name = c("F1", "F2", "F3"))
p <- problem(projects, actions, features, "name", "success", "name", "cost",
"name", FALSE) %>%
add_max_richness_objective(budget = 0.26) %>%
add_binary_decisions()
s <- data.frame(A1 = 1, A2 = 0, A3 = 1, A4 = 1)
r <- replacement_costs(p, s)
expect_is(r, "tbl_df")
expect_equal(nrow(r), 4)
expect_equal(r$name, p$action_names())
expect_equal(r$cost, c(0.25, NA_real_, 0.2, Inf))
expect_equal(r$obj, c((0.94 * 0.8) + (0.96 * 0.92) + (1.0 * 0.1),
NA_real_,
(0.91 * 0.95) + (0.96 * 0.92) + (1.0 * 0.1),
Inf))
expect_equal(r$rep_cost, ((0.91 * 0.95) +
(0.94 * 0.8) +
(1.0 * 0.1)) - r$obj)
})
test_that("minimum obj", {
skip_on_cran()
skip_if_not(any_solvers_installed())
projects <- tibble::tibble(name = c("P1", "P2", "P3", "P4"),
success = c(0.95, 0.96, 0.94, 1.00),
F1 = c(0.91, 0.00, 0.80, 0.10),
F2 = c(0.00, 0.92, 0.80, 0.10),
F3 = c(0.00, 0.00, 0.00, 0.10),
A1 = c(TRUE, FALSE, FALSE, FALSE),
A2 = c(FALSE, TRUE, FALSE, FALSE),
A3 = c(FALSE, FALSE, TRUE, FALSE),
A4 = c(FALSE, FALSE, FALSE, TRUE))
actions <- tibble::tibble(name = c("A1", "A2", "A3", "A4"),
cost = c(0.10, 0.10, 0.15, 0))
features <- tibble::tibble(name = c("F1", "F2", "F3"),
target = c(0.2, 0.2, 0.05))
p <- problem(projects, actions, features, "name", "success", "name", "cost",
"name", FALSE) %>%
add_min_set_objective() %>%
add_absolute_targets("target") %>%
add_binary_decisions()
s <- data.frame(A1 = 1, A2 = 0, A3 = 1, A4 = 1)
r <- replacement_costs(p, s)
expect_is(r, "tbl_df")
expect_equal(nrow(r), 4)
expect_equal(r$name, p$action_names())
expect_equal(r$cost, c(0.15, NA_real_, 0.2, Inf))
expect_equal(r$obj, c(0.15, NA_real_, 0.2, Inf))
expect_equal(r$rep_cost, r$obj - 0.25)
})
test_that("invalid arguments", {
data(sim_projects, sim_actions, sim_features)
p <- problem(sim_projects, sim_actions, sim_features, "name", "success",
"name", "cost", "name", FALSE) %>%
add_max_richness_objective(0.16) %>%
add_binary_decisions()
solution <- as.data.frame(matrix(rep(1, p$number_of_actions()), nrow = 1,
dimnames = list(NULL, p$action_names())))
if (identical(Sys.getenv("NOT_CRAN"), "true"))
expect_is(replacement_costs(p, solution), "tbl_df")
expect_error({
replacement_costs(
problem(sim_projects, sim_actions, sim_features, "name", "success",
"name", "cost", "name"), solution)
})
expect_error({
replacement_costs(p, as.matrix(solution))
})
expect_error({
s <- solution
s[[1]] <- NA_real_
replacement_costs(p, s)
})
expect_error({
s <- solution
s[[1]] <- "a"
replacement_costs(p, s)
})
expect_error({
s <- solution
replacement_costs(p, solution[, -1, drop = FALSE])
})
expect_error({
replacement_costs(p, solution, NA_integer_)
})
expect_error({
replacement_costs(p, solution, "a")
})
expect_error({
replacement_costs(p, solution, TRUE)
})
}) |
get_variables <- function(subjectId, level = NULL, year = NULL, sort = c("id","-id","subjectId", "-subjectId"),
lang = c("pl","en"), ...) {
if (!is.character(subjectId)) {
stop("subjectId has to be string value.")
}
if (nchar_length(subjectId) == 0 || is.null(subjectId)) {
stop("subjectId cannot be empty.")
}
dir <- "variables"
sort <- match.arg(sort)
lang <- match.arg(lang)
filters <- list("subject-Id" = subjectId, year = year, level = level, sort = sort, lang = lang)
df <- page_download(dir, id = "", filters, ...)
df
} |
set.model.functions <-
function(model) {
d.sum.of.mixtures <- NULL
backtransform.par <- NULL
stochprof.results <- NULL
transform.par <- NULL
calculate.ci <- NULL
d.sum.of.types <- NULL
draw.parameters <- NULL
get.range <- NULL
penalty.constraint <- NULL
r.sum.of.mixtures <- NULL
stochprof.search <- NULL
mix.d.sum.of.mixtures <- NULL
rm(d.sum.of.mixtures)
rm(backtransform.par)
rm(stochprof.results)
rm(transform.par)
rm(calculate.ci)
rm(d.sum.of.types)
rm(draw.parameters)
rm(get.range)
rm(penalty.constraint)
rm(r.sum.of.mixtures)
rm(stochprof.search)
rm(mix.d.sum.of.mixtures)
if (model=="LN-LN") {
backtransform.par <<- backtransform.par.LNLN
calculate.ci <<- calculate.ci.LNLN
d.sum.of.mixtures <<- d.sum.of.mixtures.LNLN
mix.d.sum.of.mixtures <<- mix.d.sum.of.mixtures.LNLN
d.sum.of.types <<- d.sum.of.types.LNLN
draw.parameters <<- draw.parameters.LNLN
get.range <<- get.range.LNLN
penalty.constraint <<- penalty.constraint.LNLN
r.sum.of.mixtures <<- r.sum.of.mixtures.LNLN
stochprof.results <<- stochprof.results.LNLN
stochprof.search <<- stochprof.search.LNLN
transform.par <<- transform.par.LNLN
mix.d.sum.of.mixtures <<- mix.d.sum.of.mixtures.LNLN
}
else if (model=="rLN-LN") {
backtransform.par <<- backtransform.par.rLNLN
calculate.ci <<- calculate.ci.rLNLN
d.sum.of.mixtures <<- d.sum.of.mixtures.rLNLN
mix.d.sum.of.mixtures <<- mix.d.sum.of.mixtures.rLNLN
d.sum.of.types <<- d.sum.of.types.rLNLN
draw.parameters <<- draw.parameters.rLNLN
get.range <<- get.range.rLNLN
penalty.constraint <<- penalty.constraint.rLNLN
r.sum.of.mixtures <<- r.sum.of.mixtures.rLNLN
stochprof.results <<- stochprof.results.rLNLN
stochprof.search <<- stochprof.search.rLNLN
transform.par <<- transform.par.rLNLN
mix.d.sum.of.mixtures <<- mix.d.sum.of.mixtures.rLNLN
}
else if (model=="EXP-LN") {
backtransform.par <<- backtransform.par.EXPLN
calculate.ci <<- calculate.ci.EXPLN
d.sum.of.mixtures <<- d.sum.of.mixtures.EXPLN
mix.d.sum.of.mixtures <<- mix.d.sum.of.mixtures.EXPLN
draw.parameters <<- draw.parameters.EXPLN
get.range <<- get.range.EXPLN
penalty.constraint <<- penalty.constraint.EXPLN
r.sum.of.mixtures <<- r.sum.of.mixtures.EXPLN
stochprof.results <<- stochprof.results.EXPLN
stochprof.search <<- stochprof.search.EXPLN
transform.par <<- transform.par.EXPLN
mix.d.sum.of.mixtures <<- mix.d.sum.of.mixtures.EXPLN
}
} |
NonCumHaz<-function(x, t=NA, plot=FALSE){
if(!(any(class(x)=="survfit")||is.numeric(x))) {warning("x needs to be a numeric vector or a survfit-object!")}
if(is.na(t) && plot && (!any(class(x)=="survfit"))) {warning("plot can not be produced, because time referrence is missing!")}
if(is.numeric(x)){
output<-numeric(length(x))
for (i in 1:(length(x)-1)) output[i] <- x[1+i]-x[i]
if(plot) {o1<-plot(output[1:(length(output)-1)]~t[1:(length(output)-1)], xlab="Time", ylab="Hazard", type ="l")}
}
if(any(class(x)=="survfit")){
my.cumhaz<-x$cumhaz
my.cumhaz<-c(0,my.cumhaz)
my.hazard<-c()
for (i in 1:(length(my.cumhaz)-1)) my.hazard[i] <- my.cumhaz[1+i]-my.cumhaz[i]
if(plot) {o1<-plot(my.hazard[1:(length(my.hazard)-1)]~x$time[1:(length(my.hazard)-1)], xlab="Time", ylab="Hazard", type ="l")}
output<-my.hazard
}
return(output)
} |
print.degross = function(x,...){
print(x$degross.data)
cat("\nFitted moments of order 1 to 4:\n")
print(x$M.j[,1:4])
temp = with(x,round(c(edf=edf,aic=aic,bic=bic,log.evidence=log.evidence),1))
cat("\nGlobal fit statistics:\n")
print(temp)
} |
tar_load <- function(
names,
branches = NULL,
meta = tar_meta(targets_only = TRUE, store = store),
strict = TRUE,
silent = FALSE,
envir = parent.frame(),
store = targets::tar_config_get("store")
) {
force(meta)
force(envir)
names <- tar_tidyselect_eval(rlang::enquo(names), meta$name)
tar_load_raw(
names = names,
branches = branches,
meta = meta,
strict = strict,
silent = silent,
envir = envir,
store = store
)
} |
errorcorr <- function(dataset, indnr, x, y, f, xterms, yterms, nrterms, z, zterms, v, vterms)
{
if (indnr == 2)
{
procdata <- preprocess_data(indnr, x, y)
xv <- procdata$allX
yv <- procdata$allY
chx <- procdata$tiChX
chy <- procdata$tiChY
for (i in 1:length(xv))
{
Yprime <- f(rbind(xv[i], yv[i]))
IncPredX <- Yprime[1]
IncPredY <- Yprime[2]
}
errorX <- chx - IncPredX
errorY <- chy - IncPredY
errorXtmp <- errorX
errorYtmp <- errorY
errorX <- (errorXtmp - mean(errorXtmp, na.rm=TRUE))/sd(errorXtmp, na.rm=TRUE)
errorY <- (errorYtmp - mean(errorYtmp, na.rm=TRUE))/sd(errorYtmp, na.rm=TRUE)
covmat <- matrix(c(mean(errorX*errorX, na.rm=TRUE), mean(errorX*errorY, na.rm=TRUE),
mean(errorY*errorX, na.rm=TRUE), mean(errorY*errorY, na.rm=TRUE)),
nrow=2, byrow=TRUE)
covmattmp <- covmat
covmat <- solve(covmattmp)
print(covmat)
invx <- xv^(-1)
invy <- yv^(-1)
idx1 = which(is.infinite(invx))
idx2 = which(is.infinite(invy))
invx[idx1] <- NA
invy[idx2] <- NA
input <- cbind(rep(1, length(xv)), invx, invy, xv, yv, invx*invy, xv*invy, yv*invx,
xv*yv, xv^2, invx^2, yv^2, invy^2, xv^3, yv^3, invx^3, invy^3)
Xterms <- input
Yterms <- input
Xterms <- Xterms[, xterms]
Yterms <- Yterms[, yterms]
chmatr <- c(chx, chy)
allincmatr <- chmatr
xtkron <- matrix(c(covmat[1, 1]*t(Xterms), covmat[1, 2]*t(Xterms),
covmat[2, 1]*t(Yterms), covmat[2, 2]*t(Yterms)), nrow=nrterms, byrow=TRUE)
xtkronx <- matrix(c(covmat[1, 1]*t(Xterms)%*%Xterms, covmat[1, 2]*t(Xterms)%*%Yterms,
covmat[2, 1]*t(Yterms)%*%Xterms, covmat[2, 2]*t(Yterms)%*%Yterms),
nrow=nrterms, ncol=nrterms, byrow=TRUE)
betapred <- ginv(xtkronx)%*%xtkron%*%allincmatr
print(betapred)
}
if (indnr == 3)
{
procdata <- preprocess_data(indnr, x, y, z)
xv <- procdata$allX
yv <- procdata$allY
zv <- procdata$allZ
chx <- procdata$tiChX
chy <- procdata$tiChY
chz <- procdata$tiChZ
for (i in 1:length(xv))
{
Yprime <- f(rbind(xv[i], yv[i], zv[i]))
IncPredX <- Yprime[1]
IncPredY <- Yprime[2]
IncPredZ <- Yprime[3]
}
errorX <- chx - IncPredX
errorY <- chy - IncPredY
errorZ <- chz - IncPredZ
errorXtmp <- errorX
errorYtmp <- errorY
errorZtmp <- errorZ
errorX <- (errorXtmp - mean(errorXtmp, na.rm=TRUE))/sd(errorXtmp, na.rm=TRUE)
errorY <- (errorYtmp - mean(errorYtmp, na.rm=TRUE))/sd(errorYtmp, na.rm=TRUE)
errorZ <- (errorZtmp - mean(errorZtmp, na.rm=TRUE))/sd(errorZtmp, na.rm=TRUE)
covmat <- matrix(c(mean(errorX*errorX, na.rm=TRUE), mean(errorX*errorY, na.rm=TRUE),
mean(errorX*errorZ, na.rm=TRUE), mean(errorY*errorX, na.rm=TRUE),
mean(errorY*errorY, na.rm=TRUE), mean(errorY*errorZ, na.rm=TRUE),
mean(errorZ*errorX, na.rm=TRUE), mean(errorZ*errorY, na.rm=TRUE),
mean(errorZ*errorZ, na.rm=TRUE)), nrow=3, byrow=TRUE)
covmattmp <- covmat
covmat <- solve(covmat)
print(covmat)
invx <- xv^(-1)
invy <- yv^(-1)
invz <- yv^(-1)
idx1 = which(is.infinite(invx))
idx2 = which(is.infinite(invy))
idx3 = which(is.infinite(invz))
invx[idx1] <- NA
invy[idx2] <- NA
invz[idx3] <- NA
input <- cbind(rep(1, length(xv)), invx, invy, invz, xv, yv, zv, invx*invy, invy*invz, invx*invz,
xv*yv, yv*zv, xv*zv, xv*invy, yv*invx, xv*invz, zv*invx, yv*invz, zv*invy, xv*invy*invz,
yv*invx*invz, zv*invx*invy, xv*yv*invz, yv*zv*invx, xv*zv*invy, xv*yv*zv, invx*invy*invz,
xv^2, invx^2, yv^2, invy^2, zv^2, invz^2, xv^3, yv^3, zv^3, invx^3, invy^3, invz^3)
Xterms <- input
Yterms <- input
Zterms <- input
Xterms <- Xterms[, xterms]
Yterms <- Yterms[, yterms]
Zterms <- Zterms[, zterms]
chmatr <- c(chx, chy, chz)
allincmatr <- chmatr
xtkron <- matrix(c(covmat[1, 1]*t(Xterms), covmat[1, 2]*t(Xterms),
covmat[1, 3]*t(Xterms), covmat[2, 1]*t(Yterms),
covmat[2, 2]*t(Yterms), covmat[2, 3]*t(Yterms),
covmat[3, 1]*t(Zterms), covmat[3, 2]*t(Zterms),
covmat[3, 3]*t(Zterms)), nrow=nrterms, byrow=TRUE)
xtkronx <- matrix(c(covmat[1, 1]*t(Xterms)%*%Xterms, covmat[1, 2]*t(Xterms)%*%Yterms,
covmat[1, 3]*t(Xterms)%*%Zterms, covmat[2, 1]*t(Yterms)%*%Xterms,
covmat[2, 2]*t(Yterms)%*%Yterms, covmat[2, 3]*t(Yterms)%*%Zterms,
covmat[3, 1]*t(Zterms)%*%Xterms, covmat[3, 2]*t(Zterms)%*%Yterms,
covmat[3, 3]*t(Zterms)%*%Zterms), nrow=nrterms, ncol=nrterms, byrow=TRUE)
betapred <- ginv(xtkronx)%*%xtkron%*%allincmatr
print(betapred)
}
if (indnr == 4)
{
procdata <- preprocess_data(indnr, x, y, z, v)
xv <- procdata$allX
yv <- procdata$allY
zv <- procdata$allZ
vv <- procdata$allV
chx <- procdata$tiChX
chy <- procdata$tiChY
chz <- procdata$tiChZ
chv <- procdata$tiChV
for (i in 1:length(xv))
{
Yprime <- f(rbind(xv[i], yv[i], zv[i], vv[i]))
IncPredX <- Yprime[1]
IncPredY <- Yprime[2]
IncPredZ <- Yprime[3]
IncPredV <- Yprime[4]
}
errorX <- chx - IncPredX
errorY <- chy - IncPredY
errorZ <- chz - IncPredZ
errorV <- chv - IncPredV
errorXtmp <- errorX
errorYtmp <- errorY
errorZtmp <- errorZ
errorVtmp <- errorV
errorX <- (errorXtmp - mean(errorXtmp, na.rm=TRUE))/sd(errorXtmp, na.rm=TRUE)
errorY <- (errorYtmp - mean(errorYtmp, na.rm=TRUE))/sd(errorYtmp, na.rm=TRUE)
errorZ <- (errorZtmp - mean(errorZtmp, na.rm=TRUE))/sd(errorZtmp, na.rm=TRUE)
errorV <- (errorVtmp - mean(errorVtmp, na.rm=TRUE))/sd(errorVtmp, na.rm=TRUE)
covmat <- matrix(c(mean(errorX*errorX, na.rm=TRUE), mean(errorX*errorY, na.rm=TRUE),
mean(errorX*errorZ, na.rm=TRUE), mean(errorX*errorV, na.rm=TRUE),
mean(errorY*errorX, na.rm=TRUE), mean(errorY*errorY, na.rm=TRUE),
mean(errorY*errorZ, na.rm=TRUE), mean(errorY*errorV, na.rm=TRUE),
mean(errorZ*errorX, na.rm=TRUE), mean(errorZ*errorY, na.rm=TRUE),
mean(errorZ*errorZ, na.rm=TRUE), mean(errorZ*errorV, na.rm=TRUE),
mean(errorV*errorX, na.rm=TRUE), mean(errorV*errorY, na.rm=TRUE),
mean(errorV*errorZ, na.rm=TRUE), mean(errorV*errorV, na.rm=TRUE)),
nrow=4, byrow=TRUE)
covmattmp <- covmat
covmat <- solve(covmat)
print(covmat)
invx <- xv^(-1)
invy <- yv^(-1)
invz <- yv^(-1)
invv <- vv^(-1)
idx1 = which(is.infinite(invx))
idx2 = which(is.infinite(invy))
idx3 = which(is.infinite(invz))
idx4 = which(is.infinite(invv))
invx[idx1] <- NA
invy[idx2] <- NA
invz[idx3] <- NA
invv[idx4] <- NA
input <- cbind(rep(1, length(xv)), invx, invy, invz, invv, xv, yv, zv, vv, invx*invy, invy*invz, invx*invz,
invx*invv, invy*invv, invz*invv, xv*yv, yv*zv, xv*zv, xv*vv, yv*vv, zv*vv, xv*invy, yv*invx,
xv*invz, zv*invx, yv*invz, zv*invy, xv*invv, vv*invx, yv*invv, vv*invy, zv*invv, vv*invz,
xv*invy*invz, yv*invx*invz, zv*invx*invy, vv*invx*invy, vv*invx*invz, vv*invy*invz, xv*invy*invv,
xv*invz*invv, yv*invx*invv, yv*invz*invv, zv*invx*invv, zv*invy*invv, xv*yv*invz, yv*zv*invx,
zv*xv*invy, xv*yv*invv, yv*zv*invv, zv*xv*invv, xv*vv*invz, yv*vv*invz, yv*vv*invx, zv*vv*invx,
vv*xv*invy, vv*zv*invy, xv*yv*zv, xv*yv*vv, xv*vv*zv, vv*yv*zv, invx*invy*invz, invx*invy*invv,
invx*invv*invz, invv*invy*invz, xv*invv*invy*invz, yv*invx*invv*invz, zv*invx*invy*invv,
vv*invx*invy*invz, xv*yv*zv*invv, xv*yv*vv*invz, xv*vv*zv*invy, vv*yv*zv*invx, xv*yv*invv*invz,
xv*zv*invv*invy, xv*vv*invy*invz, yv*zv*invv*invx, yv*vv*invz*invx, zv*vv*invx*invy,
invx*invy*invz*invv, xv*yv*zv*vv, xv^2, invx^2, yv^2, invy^2, zv^2, invz^2, vv^2, invv^2,
xv^3, yv^3, zv^3, vv^3, invx^3, invy^3, invz^3, invv^3)
Xterms <- input
Yterms <- input
Zterms <- input
Vterms <- input
Xterms <- Xterms[, xterms]
Yterms <- Yterms[, yterms]
Zterms <- Zterms[, zterms]
Vterms <- Vterms[, vterms]
chmatr <-c(chx, chy, chz, chv)
allincmatr <- chmatr
xtkron <- matrix(c(covmat[1, 1]*t(Xterms), covmat[1, 2]*t(Xterms),
covmat[1, 3]*t(Xterms), covmat[1, 4]*t(Xterms),
covmat[2, 1]*t(Yterms), covmat[2, 2]*t(Yterms),
covmat[2, 3]*t(Yterms), covmat[2, 4]*t(Yterms),
covmat[3, 1]*t(Zterms), covmat[3, 2]*t(Zterms),
covmat[3, 3]*t(Zterms), covmat[3, 4]*t(Zterms),
covmat[4, 1]*t(Vterms), covmat[4, 2]*t(Vterms),
covmat[4, 3]*t(Vterms), covmat[4, 4]*t(Vterms)),
nrow=nrterms, byrow=TRUE)
xtkronx <- matrix(c(covmat[1, 1]*t(Xterms)%*%Xterms, covmat[1, 2]*t(Xterms)%*%Yterms,
covmat[1, 3]*t(Xterms)%*%Zterms, covmat[1, 4]*t(Xterms)%*%Vterms,
covmat[2, 1]*t(Yterms)%*%Xterms, covmat[2, 2]*t(Yterms)%*%Yterms,
covmat[2, 3]*t(Yterms)%*%Zterms, covmat[2, 4]*t(Yterms)%*%Vterms,
covmat[3, 1]*t(Zterms)%*%Xterms, covmat[3, 2]*t(Zterms)%*%Yterms,
covmat[3, 3]*t(Zterms)%*%Zterms, covmat[3, 4]*t(Zterms)%*%Vterms,
covmat[4, 1]*t(Vterms)%*%Xterms, covmat[4, 2]*t(Vterms)%*%Yterms,
covmat[4, 3]*t(Vterms)%*%Zterms, covmat[4, 4]*t(Vterms)%*%Vterms),
nrow=nrterms, ncol=nrterms, byrow=TRUE)
betapred <- ginv(xtkronx)%*%xtkron%*%allincmatr
print(betapred)
}
}
|
download_distribute <- function(files,
repositories=list("/p/projects/rd3mod/inputdata/output"=NULL),
modelfolder=".",
additionalDelete=NULL,
debug=FALSE) {
cdir <- getwd()
setwd(modelfolder)
on.exit(setwd(cdir))
file2destination <- getfiledestinations()
message("Delete old data in input folders ... ")
delete_olddata(file2destination)
if(!is.null(additionalDelete)) delete_olddata(additionalDelete)
message("done!\n")
filemap <- download_unpack(input=files, targetdir="input", repositories=repositories, debug=debug)
low_res <- get_info("input/info.txt","^\\* Output ?resolution:",": ")
copy_input(x=file2destination, sourcepath="input", suffix=low_res, move=!debug)
return(filemap)
} |
grnn.partial <- function(net, i, plot = TRUE) {
if (class(net) != "General Regression Neural Net") stop("net needs to be a GRNN.", call. = F)
if (i > ncol(net$x)) stop("the selected variable is out of bound.", call. = F)
if (!(plot %in% c(T, F))) stop("the plot input is not correct.", call. = F)
xname <- colnames(net$x)[i]
xi <- sort(unique(net$x[, i]))
partial <- function(x_i) {
x <- net$x
x[, i] <- rep(x_i, length(net$y))
return(data.frame(x = x_i, p = mean(grnn.predict(net, x))))
}
cls <- parallel::makeCluster(min(length(xi), parallel::detectCores() - 1), type = "PSOCK")
obj <- c("net", "grnn.fit", "grnn.predone", "grnn.predict")
parallel::clusterExport(cls, obj, envir = environment())
rst <- Reduce(rbind, parallel::parLapply(cls, xi, partial))
parallel::stopCluster(cls)
if (plot == T) {
plot(rst[, 1], rst[, 2], type = "b", lty = 4, lwd = 3, ylab = '', xlab = xname,
main = "Partial Dependence", pch = 16, cex = 1.5, col = "royalblue", cex.main = 1, cex.lab = 1, yaxt = 'n')
rug(rst[, 1], col = 'green4', ticksize = 0.03, lwd = 3)
} else {
return(rst)
}
} |
xDewma.arl <- function(l, c, delta, zr=0, hs=0, sided="one", limits="fix", mode="Gan", m=NULL, q=1, r=40, with0=FALSE) {
if (l<=0 || l>1)
stop("l has to be between 0 and 1")
if (c<=0)
stop("c has to be positive")
if (zr>c & sided=="one")
stop("wrong reflexion border")
if ( (sided=="two" & abs(hs)>c) | (sided=="one" & (hs<zr | hs>c)) )
stop("wrong headstart")
if (r<4)
stop("r is too small")
ctyp <- pmatch(sided, c("one", "two")) - 1
if (is.na(ctyp))
stop("invalid ewma type")
ltyp <- -1 + pmatch(limits,
c("fix","vacl","fir","both","Steiner","Knoth","fink","fixW","fixC"))
if (is.na(ltyp))
stop("invalid limits type")
cmode <- pmatch(mode, c("Gan", "Knoth", "Waldmann")) - 1
if (is.na(cmode))
stop("invalid algorithm mode")
if ( is.null(m) ) {
m <- 0
} else { if ( m<1 ) stop("m is too small") }
q <- round(q)
if (q<1)
stop("wrong change point position (q)")
arl <- .C("xDewma_arl",as.integer(ctyp),as.double(l),
as.double(c),as.double(zr),as.double(hs),
as.double(delta),as.integer(ltyp),as.integer(m),as.integer(r),
as.integer(with0),as.integer(cmode),as.integer(q),
ans=double(length=1),PACKAGE="spc")$ans
names(arl) <- "arl"
return (arl)
} |
retistruct.cli <- function(dataset, cpu.time.limit=Inf, outputdir=NA,
device="pdf", ...) {
status <- 0
setTimeLimit(cpu=cpu.time.limit)
syst <- system.time(out <- tryCatch(retistruct.cli.process(dataset,
outputdir=outputdir, device=device, ...),
error=function(e) {return(e)}))
mess <- "Success"
if (inherits(out, "error")) {
mess <- as.character(out)
if (grepl("reached CPU time limit", mess)) {
status <- 1
} else {
status <- 2
}
}
return(list(status=status, time=syst["user.self"], mess=mess))
}
retistruct.cli.process <- function(dataset, outputdir=NA, device="pdf"
) {
warn.opt <- getOption("warn")
options(warn=1)
r <- retistruct.read.dataset(dataset)
r <- retistruct.read.markup(r)
r <- retistruct.reconstruct(r)
retistruct.save.recdata(r)
if (!is.na(outputdir)) {
message("Producing figures")
retistruct.cli.figure(dataset, outputdir, device=device)
}
message("Exporting to matlab")
retistruct.export.matlab(r)
options(warn=warn.opt)
}
retistruct.cli.basepath <- function(dataset) {
basepath <- gsub("\\./", "", dataset)
basepath <- gsub("/", "_", basepath)
basepath <- gsub(" ", "_", basepath)
return(basepath)
}
retistruct.cli.figure <- function(dataset,
outputdir, device="pdf", width=6, height=6,
res=100) {
suppressMessages(r <- retistruct.read.recdata(list(dataset=dataset), check=FALSE))
units <- NULL
if (device!="pdf") {
height <- height*res
width <- width*res
}
suffix <- paste(".", device, sep="")
dev <- switch(device,
pdf=grDevices::pdf,
png=grDevices::png,
jpeg=grDevices::jpeg,
tiff=grDevices::tiff)
if (is.null(dev)) {
stop(paste("Device", device, "is not supported"))
}
if (!is.null(r)) {
basepath <- retistruct.cli.basepath(dataset)
dev(file=file.path(outputdir, paste(basepath, "-flat", suffix, sep="")),
width=width, height=height)
par(mar=c(1, 1, 1, 1))
flatplot(r, axt="n",
datapoints=TRUE,
landmarks=TRUE,
markup=FALSE,
stitch=TRUE,
grid=TRUE,
mesh=FALSE,
strain=FALSE)
title(dataset)
dev.off()
dev(file=file.path(outputdir, paste(basepath, "-polar-kde", suffix, sep="")),
width=width, height=height)
par(mar=c(2, 2, 2, 2))
projection(r, datapoint.contours=TRUE, grouped.contours=FALSE)
title(paste("KDE:", dataset))
if (!is.null(r$EOD)) {
polartext(paste("OD displacement:", format(r$EOD, digits=3, nsmall=2), "deg"))
}
dev.off()
dev(file=file.path(outputdir, paste(basepath, "-polar-kr", suffix, sep="")),
width=width, height=height)
par(mar=c(2, 2, 2, 2))
projection(r, datapoint.contours=FALSE, grouped.contours=TRUE)
title(paste("KR:", dataset))
if (!is.null(r$EOD)) {
polartext(paste("OD displacement:", format(r$EOD, digits=3, nsmall=2), "deg"))
}
dev.off()
dev(file=file.path(outputdir, paste(basepath, "-strain", suffix, sep="")),
width=width, height=height)
par(mar=c(1, 1, 1, 1))
flatplot(r, axt="n",
datapoints=FALSE,
landmarks=FALSE,
markup=FALSE,
stitch=FALSE,
grid=FALSE,
mesh=FALSE,
strain=TRUE)
title(dataset)
dev.off()
dev(file=file.path(outputdir, paste(basepath, "-strain-lvsL", suffix, sep="")),
width=width, height=height)
par(mar=c(3.0, 3.0, 1.5, 0.5))
par(mgp=c(1.5, 0.5, 0))
par(tcl=-0.3)
lvsLplot(r)
title(dataset)
dev.off()
}
} |
design.info.design <- function(){
command <- paste("design.info(",ActiveDataSet(),")")
doItAndPrint(command)
} |
calcSeCox <- function(object, times, nTimes, type, diag,
Lambda0, object.n, object.time, object.eXb, object.strata, nStrata,
new.n, new.eXb, new.LPdata, new.strata, new.survival,
nVar.lp, export, store.iid){
if(is.iidCox(object)){
store.iid <- object$iid$store.iid
iid.object <- selectJump(object$iid, times = times, type = type)
}else{
iid.object <- iidCox(object, tau.hazard = times, store.iid = store.iid, return.object = FALSE)
}
if(diag){
nTimes <- 1
}
new.strata <- as.numeric(new.strata)
Lambda0$strata <- as.numeric(Lambda0$strata)
if("hazard" %in% type){Lambda0$hazard <- lapply(1:nStrata,function(s){Lambda0$hazard[Lambda0$strata==s][Lambda0$oorder.times]})}
if("cumhazard" %in% type || "survival" %in% type){Lambda0$cumhazard <- lapply(1:nStrata,function(s){Lambda0$cumhazard[Lambda0$strata==s][Lambda0$oorder.times]})}
if(is.null(attr(export,"factor"))){
rm.list <- TRUE
factor <- list(matrix(1, nrow = new.n, ncol = nTimes))
}else{
rm.list <- FALSE
factor <- attr(export, "factor")
}
out <- list()
if("se" %in% export){
if("cumhazard" %in% type){out$cumhazard.se <- matrix(NA, nrow = new.n, ncol = nTimes)}
if("survival" %in% type){out$survival.se <- matrix(NA, nrow = new.n, ncol = nTimes)}
}
if("iid" %in% export){
if("hazard" %in% type){out$hazard.iid <- array(NA, dim = c(object.n, nTimes, new.n))}
if("cumhazard" %in% type){out$cumhazard.iid <- array(NA, dim = c(object.n, nTimes, new.n))}
if("survival" %in% type){out$survival.iid <- array(NA, dim = c(object.n, nTimes, new.n))}
}
if("average.iid" %in% export){
if("cumhazard" %in% type){out$cumhazard.average.iid <- matrix(0, nrow = object.n, ncol = nTimes)}
if("survival" %in% type){out$survival.average.iid <- matrix(0, nrow = object.n, ncol = nTimes)}
}
if(store.iid[[1]] == "minimal"){
resCpp <- calcSeMinimalCox_cpp(seqTau = times,
newSurvival = if("survival" %in% type){new.survival}else{new.survival <- matrix(NA)},
hazard0 = if("hazard" %in% type){Lambda0$hazard}else{list(NA)},
cumhazard0 = if("cumhazard" %in% type || "survival" %in% type){Lambda0$cumhazard}else{list(NA)},
newX = new.LPdata,
neweXb = new.eXb,
IFbeta = iid.object$IFbeta,
Ehazard0 = iid.object$calcIFhazard$Elambda0,
cumEhazard0 = iid.object$calcIFhazard$cumElambda0,
hazard_iS0 = iid.object$calcIFhazard$lambda0_iS0,
cumhazard_iS0 = iid.object$calcIFhazard$cumLambda0_iS0,
delta_iS0 = iid.object$calcIFhazard$delta_iS0,
sample_eXb = iid.object$calcIFhazard$eXb,
sample_time = iid.object$obstime,
indexJumpSample_time = lapply(iid.object$calcIFhazard$time1,
function(iTime){prodlim::sindex(jump.times = iTime, eval.times = iid.object$obstime)-1}),
jump_time = iid.object$calcIFhazard$time1,
indexJumpTau = lapply(iid.object$calcIFhazard$time1,
function(iTime){prodlim::sindex(jump.times = iTime, eval.times = times)-1}),
lastSampleTime = iid.object$etime.max,
newdata_index = lapply(1:nStrata,
function(iS){which(new.strata == iS)-1}),
factor = factor,
nTau = nTimes, nNewObs = new.n, nSample = object.n, nStrata = nStrata, p = nVar.lp,
diag = diag, exportSE = "se" %in% export, exportIF = "iid" %in% export, exportIFmean = "average.iid" %in% export,
exportHazard = "hazard" %in% type, exportCumhazard = "cumhazard" %in% type, exportSurvival = "survival" %in% type,
debug = 0)
if("iid" %in% export){
if("hazard" %in% type){out$hazard.iid <- aperm(resCpp$IF_hazard, perm = c(1,3,2))}
if("cumhazard" %in% type){out$cumhazard.iid <- aperm(resCpp$IF_cumhazard, perm = c(1,3,2))}
if("survival" %in% type){out$survival.iid <- aperm(resCpp$IF_survival, perm = c(1,3,2))}
}
if("se" %in% export){
if("cumhazard" %in% type){out$cumhazard.se <- resCpp$SE_cumhazard}
if("survival" %in% type){out$survival.se <- resCpp$SE_survival}
}
if("average.iid" %in% export){
if(rm.list){
if("hazard" %in% type){out$hazard.average.iid <- matrix(resCpp$IFmean_hazard[[1]], nrow = object.n, ncol = nTimes)}
if("cumhazard" %in% type){out$cumhazard.average.iid <- matrix(resCpp$IFmean_cumhazard[[1]], nrow = object.n, ncol = nTimes)}
if("survival" %in% type){out$survival.average.iid <- matrix(resCpp$IFmean_survival[[1]], nrow = object.n, ncol = nTimes)}
}else{
if("hazard" %in% type){out$hazard.average.iid <- lapply(resCpp$IFmean_hazard, function(iVec){matrix(iVec, nrow = object.n, ncol = nTimes)})}
if("cumhazard" %in% type){out$cumhazard.average.iid <- lapply(resCpp$IFmean_cumhazard, function(iVec){matrix(iVec, nrow = object.n, ncol = nTimes)})}
if("survival" %in% type){out$survival.average.iid <- lapply(resCpp$IFmean_survival, function(iVec){matrix(iVec, nrow = object.n, ncol = nTimes)})}
}
}
}else if("iid" %in% export || "se" %in% export){
if(nVar.lp>0){
X_IFbeta_mat <- tcrossprod(iid.object$IFbeta, new.LPdata)
}
if( diag || (nVar.lp==0) ){
for(iStrata in 1:nStrata){
indexStrata <- which(new.strata==iStrata)
if(length(indexStrata)==0){next}
iPrevalence <- length(indexStrata)/new.n
if("hazard" %in% type){
if (diag) {
if(nVar.lp==0){
iIFhazard <- iid.object$IFhazard[[iStrata]][,indexStrata,drop=FALSE]
}else{
iIFhazard <- rowMultiply_cpp(iid.object$IFhazard[[iStrata]][,indexStrata,drop=FALSE] + rowMultiply_cpp(X_IFbeta_mat[,indexStrata,drop=FALSE],
scale = Lambda0$hazard[[iStrata]][indexStrata]),
scale = new.eXb[indexStrata])
}
}else{
iIFhazard <- iid.object$IFhazard[[iStrata]]
tiIFhazard <- t(iIFhazard)
}
}
if("cumhazard" %in% type || "survival" %in% type){
if (diag) {
if(nVar.lp==0){
iIFcumhazard <- iid.object$IFcumhazard[[iStrata]][,indexStrata,drop=FALSE]
}else{
iIFcumhazard <- rowMultiply_cpp(iid.object$IFcumhazard[[iStrata]][,indexStrata,drop=FALSE] + rowMultiply_cpp(X_IFbeta_mat[,indexStrata,drop=FALSE], scale = Lambda0$cumhazard[[iStrata]][indexStrata]),
scale = new.eXb[indexStrata])
}
if("survival" %in% type && ("iid" %in% export || "average.iid" %in% export)){
iIFsurvival <- rowMultiply_cpp(-iIFcumhazard, scale = new.survival[indexStrata,])
}
}else{
iIFcumhazard <- iid.object$IFcumhazard[[iStrata]]
tiIFcumhazard <- t(iIFcumhazard)
if("survival" %in% type && ("iid" %in% export || "average.iid" %in% export)){
iIFsurvival <- rowMultiply_cpp(-iIFcumhazard, scale = new.survival[indexStrata[1],])
tiIFsurvival <- t(iIFsurvival)
}
}
}
if(diag){
if("iid" %in% export){
if("hazard" %in% type){out$hazard.iid[,1,indexStrata] <- iIFhazard}
if("cumhazard" %in% type){out$cumhazard.iid[,1,indexStrata] <- iIFcumhazard}
if("survival" %in% type){out$survival.iid[,1,indexStrata] <- iIFsurvival}
}
if("se" %in% export){
iSEcumhazard <- sqrt(colSums(iIFcumhazard^2))
if("cumhazard" %in% type){out$cumhazard.se[indexStrata,1] <- iSEcumhazard}
if("survival" %in% type){out$survival.se[indexStrata,1] <- iSEcumhazard * new.survival[indexStrata,1]}
}
if("average.iid" %in% export){
if("hazard" %in% type){out$hazard.average.iid[,1] <- out$hazard.average.iid[,1] + rowSums(iIFhazard)/new.n}
if("cumhazard" %in% type){out$cumhazard.average.iid[,1] <- out$cumhazard.average.iid[,1] + rowSums(iIFcumhazard)/new.n}
if("survival" %in% type){out$survival.average.iid[,1] <- out$survival.average.iid[,1] + rowSums(iIFsurvival)/new.n}
}
}else{
if("se" %in% export){
iSEcumhazard <- sqrt(colSums(iIFcumhazard^2))
if("survival" %in% type){
iSEsurvival <- iSEcumhazard * new.survival[indexStrata[1],]
}
}
for(iObs in indexStrata){
if("iid" %in% export){
if("hazard" %in% type){out$hazard.iid[,,iObs] <- iIFhazard}
if("cumhazard" %in% type){out$cumhazard.iid[,,iObs] <- iIFcumhazard}
if("survival" %in% type){out$survival.iid[,,iObs] <- iIFsurvival}
}
if("se" %in% export){
if("cumhazard" %in% type){out$cumhazard.se[iObs,] <- iSEcumhazard}
if("survival" %in% type){out$survival.se[iObs,] <- iSEsurvival}
}
}
if("average.iid" %in% export){
if("hazard" %in% type){out$hazard.average.iid <- out$hazard.average.iid + iIFhazard * iPrevalence}
if("cumhazard" %in% type){out$cumhazard.average.iid <- out$cumhazard.average.iid + iIFcumhazard * iPrevalence}
if("survival" %in% type){out$survival.average.iid <- out$survival.average.iid + iIFsurvival * iPrevalence}
}
}
}
}else{
for(iObs in 1:new.n){
iObs.strata <- new.strata[iObs]
if("hazard" %in% type){
iIFhazard <- (new.eXb[iObs] * (iid.object$IFhazard[[iObs.strata]] + crossprod(t(X_IFbeta_mat[,iObs,drop=FALSE]),Lambda0$hazard[[iObs.strata]])))
}
if("cumhazard" %in% type || "survival" %in% type){
iIFcumhazard <- new.eXb[iObs] * (iid.object$IFcumhazard[[iObs.strata]] + crossprod(t(X_IFbeta_mat[,iObs,drop=FALSE]), Lambda0$cumhazard[[iObs.strata]]))
}
if("survival" %in% type && ("iid" %in% export || "average.iid" %in% export)){
iIFsurvival <- rowMultiply_cpp(-iIFcumhazard, scale = new.survival[iObs,])
}
if("iid" %in% export){
if("hazard" %in% type){out$hazard.iid[,,iObs] <- iIFhazard}
if("cumhazard" %in% type){out$cumhazard.iid[,,iObs] <- iIFcumhazard}
if("survival" %in% type){out$survival.iid[,,iObs] <- iIFsurvival}
}
if("se" %in% export){
iSEcumhazard <- sqrt(colSums(iIFcumhazard^2))
if("cumhazard" %in% type){out$cumhazard.se[iObs,] <- iSEcumhazard}
if("survival" %in% type){out$survival.se[iObs,] <- iSEcumhazard * new.survival[iObs,,drop=FALSE]}
}
if("average.iid" %in% export){
if("hazard" %in% type){out$hazard.average.iid <- out$hazard.average.iid + iIFhazard/new.n}
if("cumhazard" %in% type){out$cumhazard.average.iid <- out$cumhazard.average.iid + iIFcumhazard/new.n}
if("survival" %in% type){out$survival.average.iid <- out$survival.average.iid + iIFsurvival/new.n}
}
}
}
}else if("average.iid" %in% export){
new.Ustrata <- sort(unique(new.strata))
new.nStrata <- length(new.Ustrata)
new.indexStrata <- lapply(new.Ustrata, function(iStrata){
which(new.strata==iStrata) - 1
})
new.prevStrata <- sapply(new.indexStrata, length)/new.n
attr(new.LPdata,"levels") <- NULL
if(is.null(new.survival)){
new.survival <- matrix()
}
if("hazard" %in% type){
outRcpp.hazard <- calcAIFsurv_cpp(ls_IFcumhazard = iid.object$IFhazard[new.Ustrata],
IFbeta = iid.object$IFbeta,
cumhazard0 = Lambda0$hazard[new.Ustrata],
survival = matrix(0),
eXb = new.eXb,
X = new.LPdata,
prevStrata = new.prevStrata,
ls_indexStrata = new.indexStrata,
factor = factor,
nTimes = nTimes,
nObs = object.n,
nStrata = new.nStrata,
nVar = nVar.lp,
diag = diag,
exportCumHazard = TRUE,
exportSurvival = FALSE)
}
if(("cumhazard" %in% type) || ("survival" %in% type)){
outRcpp.cumhazard <- calcAIFsurv_cpp(ls_IFcumhazard = iid.object$IFcumhazard[new.Ustrata],
IFbeta = iid.object$IFbeta,
cumhazard0 = Lambda0$cumhazard[new.Ustrata],
survival = new.survival,
eXb = new.eXb,
X = new.LPdata,
prevStrata = new.prevStrata,
ls_indexStrata = new.indexStrata,
factor = factor,
nTimes = nTimes,
nObs = object.n,
nStrata = new.nStrata,
nVar = nVar.lp,
diag = diag,
exportCumHazard = ("cumhazard" %in% type),
exportSurvival = ("survival" %in% type))
}
if("hazard" %in% type){
if(rm.list){
out$hazard.average.iid <- matrix(outRcpp.hazard[[1]][[1]], nrow = object.n, ncol = nTimes)
}else{
out$hazard.average.iid <- lapply(outRcpp.hazard[[1]], function(iMat){matrix(iMat, nrow = object.n, ncol = nTimes)})
}
}
if("cumhazard" %in% type){
if(rm.list){
out$cumhazard.average.iid <- matrix(outRcpp.cumhazard[[1]][[1]], nrow = object.n, ncol = nTimes)
}else{
out$cumhazard.average.iid <- lapply(outRcpp.cumhazard[[1]], function(iMat){matrix(iMat, nrow = object.n, ncol = nTimes)})
}
}
if("survival" %in% type){
if(rm.list){
out$survival.average.iid <- matrix(outRcpp.cumhazard[[2]][[1]], nrow = object.n, ncol = nTimes)
}else{
out$survival.average.iid <- lapply(outRcpp.cumhazard[[2]], function(iMat){matrix(iMat, nrow = object.n, ncol = nTimes)})
}
}
}
return(out)
}
selectJump <- function(IF, times, type){
if(any(times<0)){warning("selectJump may not handle correctly negative times")}
nStrata <- length(IF$time)
for(iStrata in 1:nStrata){
if(IF$store.iid == "minimal"){
isJump <- times %in% IF$time[[iStrata]]
indexJump <- prodlim::sindex(jump.times = c(0,IF$time[[iStrata]]), eval.times = times)
if(NROW(IF$calcIFhazard$Elambda0[[iStrata]])>0){
IF$calcIFhazard$Elambda0[[iStrata]] <- rowMultiply_cpp(cbind(0,IF$calcIFhazard$Elambda0[[iStrata]])[,indexJump,drop=FALSE], scale = isJump)
}else{
IF$calcIFhazard$Elambda0[[iStrata]] <- matrix(NA, nrow = 0, ncol = length(isJump))
}
if(NROW(IF$calcIFhazard$cumElambda0[[iStrata]])>0){
IF$calcIFhazard$cumElambda0[[iStrata]] <- cbind(0,IF$calcIFhazard$cumElambda0[[iStrata]])[,indexJump,drop=FALSE]
}else{
IF$calcIFhazard$cumElambda0[[iStrata]] <- matrix(NA, nrow = 0, ncol = length(isJump))
}
IF$calcIFhazard$lambda0_iS0[[iStrata]] <- IF$calcIFhazard$lambda0_iS0[[iStrata]] * (IF$calcIFhazard$time1[[iStrata]] <= max(times))
IF$calcIFhazard$cumLambda0_iS0[[iStrata]] <- IF$calcIFhazard$cumLambda0_iS0[[iStrata]] * (IF$calcIFhazard$time1[[iStrata]] <= max(times))
}else{
if("hazard" %in% type){
match.times <- match(times, table = IF$time[[iStrata]])
match.times[is.na(match.times)] <- 0
if(any(times > IF$etime.max[[iStrata]])){
match.times[times > IF$etime.max[[iStrata]]] <- NA
}
IF$IFhazard[[iStrata]] <- subsetIndex(IF$IFhazard[[iStrata]], index = match.times, default = 0, col = TRUE)
}
if("cumhazard" %in% type || "survival" %in% type){
indexJump <- prodlim::sindex(jump.times = IF$time[[iStrata]], eval.times = times)
if(any(times > IF$etime.max[[iStrata]])){
indexJump[times > IF$etime.max[[iStrata]]] <- NA
}
IF$IFcumhazard[[iStrata]] <- subsetIndex(IF$IFcumhazard[[iStrata]], index = indexJump, default = 0, col = TRUE)
}
}
IF$time[[iStrata]] <- times
}
return(IF)
} |
suppressPackageStartupMessages(library("argparse"))
parser = ArgumentParser()
parser$add_argument("--infercnv_obj", help="infercnv_obj file", required=TRUE, nargs=1)
args = parser$parse_args()
library(infercnv)
library(tidyverse)
library(futile.logger)
infercnv_obj_file = args$infercnv_obj
infercnv_obj = readRDS(infercnv_obj_file)
expr_vals <- [email protected]
sd_trend_info = infercnv:::.i3HMM_get_sd_trend_by_num_cells_fit(infercnv_obj)
mu = sd_trend_info$mu
sigma = sd_trend_info$sigma
sds = c()
ngenes = nrow(expr_vals)
tumor_samples = infercnv_obj@observation_grouped_cell_indices
print(tumor_samples)
num_tumor_samples = length(tumor_samples)
print(num_tumor_samples)
mean_vals_df = NULL;
z_p_val = 0.05
num_cells_to_empirical_sd = list()
nrounds=100
ncells_partitions = seq (1,100,5)
for (ncells in ncells_partitions) {
means = c()
message(sprintf("num cells: %g", ncells))
cells_counted = 0;
for(i in 1:nrounds) {
rand.gene = sample(1:ngenes, size=1)
rand.sample = sample(1:num_tumor_samples, size=1)
vals = sample(expr_vals[rand.gene, tumor_samples[[rand.sample]] ], size=ncells, replace=T)
m_val = mean(vals)
means = c(means, m_val)
cells_counted = cells_counted + length(vals)
}
means.sd = sd(means)
means.mean = mean(means)
num_cells_to_empirical_sd[[ ncells ]] = means.sd
df = data.frame(num_cells=ncells, vals=means)
message(sprintf("plotting ncells distribution: %g", ncells))
data.want = df
p = data.want %>% ggplot(aes(vals, fill=num_cells)) +
geom_density(alpha=0.3) +
ggtitle(sprintf("num_cells: %g", ncells))
p = p +
stat_function(fun=dnorm, color='black', args=list('mean'=means.mean,'sd'=means.sd))
alpha=0.05
ks_delta = infercnv:::get_HoneyBADGER_setGexpDev(gexp.sd=sd_trend_info$sigma, k_cells=ncells, alpha=alpha, plot=T)
left_mean = means.mean - ks_delta
message("left_mean: ", left_mean)
p = p +
stat_function(fun=dnorm, color='blue', args=list('mean'=left_mean,'sd'=means.sd))
right_mean = means.mean + ks_delta
message("right_mean: ", right_mean)
p = p +
stat_function(fun=dnorm, color='blue', args=list('mean'=right_mean,'sd'=means.sd))
plot(p)
} |
mle.getPtDist=function(p1.optBS,ptID,p2.optBS,ptID2,data_mx,ranks,p1,
thresholdDiff,adj_mat) {
if (length(p1.optBS)!=length(p2.optBS)){
return("Error: Pt1 Subset different size from Pt2.")}
if (is.null(ranks)) {return("Error: Must specify ranks")}
G = vector(mode="list", length=nrow(data_mx))
names(G) = rownames(data_mx)
res.p1 = mle.getEncodingLength(p1.optBS, NULL, ptID, G)
res.p2 = mle.getEncodingLength(p2.optBS, NULL, ptID, G)
dirSim = stat.getDirSim(ptID, ptID2, length(p1.optBS), data_mx)
p1.e=p2.e=p12.e=c()
bits_fixed=log2(choose(length(G),1))
for (k in seq_len(length(p1.optBS))) {
p1.e[k]=res.p1[which.max(res.p1[seq_len(k),"d.score"]),"IS.alt"]+
bits_fixed*(k-which.max(res.p1[seq_len(k),"d.score"]))
p2.e[k]=res.p2[which.max(res.p2[seq_len(k),"d.score"]),"IS.alt"]+
bits_fixed*(k-which.max(res.p2[seq_len(k),"d.score"]))
p1.sig.nodes_cpy=names(sort(abs(data_mx[,ptID]),
decreasing=TRUE)[seq_len(length(p1.optBS))])
p2.sig.nodes_cpy=names(sort(abs(data_mx[,ptID2]),
decreasing=TRUE)[seq_len(length(p2.optBS))])
p1.sig.nodes_k = names(which(p1.optBS[[k]]==1))
p2.sig.nodes_k = names(which(p2.optBS[[k]]==1))
while (length(p1.sig.nodes_k)<k) {
p1.sig.nodes_k = unique(c(p1.sig.nodes_k, p1.sig.nodes_cpy[1]))
p1.sig.nodes_cpy = p1.sig.nodes_cpy[-1]
}
while (length(p2.sig.nodes_k)<k) {
p2.sig.nodes_k = unique(c(p2.sig.nodes_k, p2.sig.nodes_cpy[1]))
p2.sig.nodes_cpy = p2.sig.nodes_cpy[-1]
}
p12.sig.nodes_k=vapply(unique(c(p1.sig.nodes_k, p2.sig.nodes_k)),
trimws, character(1))
p12.optBS = mle.getPtBSbyK(p12.sig.nodes_k, ranks)
res = mle.getEncodingLength(p12.optBS, NULL, NULL, G)
p12.e[k] = res[which.max(res[,"d.score"]), "IS.alt"] +
log2(choose(length(G), 1))*(length(p12.sig.nodes_k)-
which.max(res[,"d.score"]))
}
ncd=(p12.e-apply(cbind(p1.e,p2.e),1,min))/apply(cbind(p1.e,p2.e),1,max)
ncd[which(ncd<0)]=0
return(list(p1.e=p1.e, p2.e=p2.e, p12.e=p12.e, dirSim=dirSim, NCD=ncd))
} |
'dse15c' |
brm_multiple <- function(formula, data, family = gaussian(), prior = NULL,
data2 = NULL, autocor = NULL, cov_ranef = NULL,
sample_prior = c("no", "yes", "only"),
sparse = NULL, knots = NULL, stanvars = NULL,
stan_funs = NULL, silent = 1, recompile = FALSE,
combine = TRUE, fit = NA, seed = NA,
file = NULL, file_refit = "never", ...) {
combine <- as_one_logical(combine)
file_refit <- match.arg(file_refit, file_refit_options())
if (!is.null(file)) {
if (file_refit == "on_change") {
stop2("file_refit = 'on_change' is not supported for brm_multiple yet.")
}
if (!combine) {
stop2("Cannot use 'file' if 'combine' is FALSE.")
}
if (file_refit != "always") {
fits <- read_brmsfit(file)
if (!is.null(fits)) {
return(fits)
}
}
}
silent <- validate_silent(silent)
recompile <- as_one_logical(recompile)
data_name <- substitute_name(data)
if (inherits(data, "mids")) {
require_package("mice", version = "3.0.0")
data <- lapply(seq_len(data$m), mice::complete, data = data)
} else if (!is_data_list(data)) {
stop2("'data' must be a list of data.frames.")
}
if (!is.null(data2)) {
if (!is_data2_list(data2)) {
stop2("'data2' must be a list of named lists.")
}
if (length(data2) != length(data)) {
stop2("'data2' must have the same length as 'data'.")
}
}
if (is.brmsfit(fit)) {
class(fit) <- setdiff(class(fit), "brmsfit_multiple")
} else {
args <- nlist(
formula, data = data[[1]], family, prior, data2 = data2[[1]],
autocor, cov_ranef, sample_prior, sparse, knots, stanvars,
stan_funs, silent, seed, ...
)
args$chains <- 0
if (silent < 2) {
message("Compiling the C++ model")
}
fit <- suppressMessages(do_call(brm, args))
}
dots <- list(...)
if (isTRUE(dots$chains == 0) || isTRUE(dots$iter == 0)) {
class(fit) <- c("brmsfit_multiple", class(fit))
return(fit)
}
fits <- futures <- rhats <- vector("list", length(data))
for (i in seq_along(data)) {
futures[[i]] <- future::future(
update(fit, newdata = data[[i]], data2 = data2[[i]],
recompile = recompile, silent = silent, ...),
packages = "brms", seed = TRUE
)
}
for (i in seq_along(data)) {
if (silent < 2) {
message("Fitting imputed model ", i)
}
fits[[i]] <- future::value(futures[[i]])
rhats[[i]] <- data.frame(as.list(rhat(fits[[i]])))
if (any(rhats[[i]] > 1.1, na.rm = TRUE)) {
warning2("Imputed model ", i, " did not converge.")
}
}
if (combine) {
fits <- combine_models(mlist = fits, check_data = FALSE)
attr(fits$data, "data_name") <- data_name
fits$rhats <- do_call(rbind, rhats)
class(fits) <- c("brmsfit_multiple", class(fits))
}
if (!is.null(file)) {
fits <- write_brmsfit(fits, file)
}
fits
}
combine_models <- function(..., mlist = NULL, check_data = TRUE) {
models <- c(list(...), mlist)
check_data <- as_one_logical(check_data)
if (!length(models)) {
stop2("No models supplied to 'combine_models'.")
}
for (i in seq_along(models)) {
if (!is.brmsfit(models[[i]])) {
stop2("Model ", i, " is no 'brmsfit' object.")
}
models[[i]] <- restructure(models[[i]])
}
ref_formula <- formula(models[[1]])
ref_pars <- variables(models[[1]])
ref_mf <- model.frame(models[[1]])
for (i in seq_along(models)[-1]) {
if (!is_equal(formula(models[[i]]), ref_formula)) {
stop2("Models 1 and ", i, " have different formulas.")
}
if (!is_equal(variables(models[[i]]), ref_pars)) {
stop2("Models 1 and ", i, " have different parameters.")
}
if (check_data && !is_equal(model.frame(models[[i]]), ref_mf)) {
stop2(
"Models 1 and ", i, " have different data. ",
"Set 'check_data' to FALSE to turn off checking of the data."
)
}
}
sflist <- lapply(models, "[[", "fit")
models[[1]]$fit <- rstan::sflist2stanfit(sflist)
models[[1]]
}
is_data_list <- function(x) {
is.list(x) && is.vector(x)
}
is_data2_list <- function(x) {
is.list(x) && all(ulapply(x, function(y) is.list(y) && is_named(y)))
}
warn_brmsfit_multiple <- function(x, newdata = NULL) {
if (is.brmsfit_multiple(x) && is.null(newdata)) {
warning2(
"Using only the first imputed data set. Please interpret the results ",
"with caution until a more principled approach has been implemented."
)
}
invisible(x)
} |
NULL
ModeFilter <- function(x, ...)
{
UseMethod("ModeFilter")
}
ModeFilter.formula <- function(formula,
data,
...)
{
if(!is.data.frame(data)){
stop("data argument must be a data.frame")
}
modFrame <- model.frame(formula,data)
attr(modFrame,"terms") <- NULL
ret <- ModeFilter.default(x=modFrame,...,classColumn = 1)
ret$call <- match.call(expand.dots = TRUE)
ret$call[[1]] <- as.name("ModeFilter")
cleanData <- data
if(!is.null(ret$repIdx)){
cleanData[ret$repIdx,which(colnames(cleanData)==colnames(modFrame)[1])] <- ret$repLab
}
ret$cleanData <- cleanData[setdiff(1:nrow(cleanData),ret$remIdx),]
return(ret)
}
ModeFilter.default <- function(x,
type = "classical",
noiseAction = "repair",
epsilon = 0.05,
maxIter = 100,
alpha = 1,
beta = 1,
classColumn = ncol(x),
...)
{
if(!is.data.frame(x)){
stop("data argument must be a data.frame")
}
if(!classColumn%in%(1:ncol(x))){
stop("class column out of range")
}
if(!is.factor(x[,classColumn])){
stop("class column of data must be a factor")
}
if(!type%in%c("classical","iterative","weighted")){
stop("the argument 'type' must be set to 'classical', 'iterative' or 'weighted'")
}
if(!noiseAction%in%c("repair","remove")){
stop("the argument 'noiseAction' must be set to 'repair' or 'remove'")
}
if(epsilon>1 | epsilon<0){
stop("argument 'epsilon' must range between 0 and 1")
}
similarity <- sapply(1:nrow(x),function(i){c(rep(NA,i-1),
sapply(i:nrow(x),function(j){exp(-alpha*distt(x[i,-classColumn],x[j,-classColumn])^2)}))})
for(i in 1:(nrow(x)-1)){
for(j in (i+1):nrow(x)){
similarity[i,j] <- similarity[j,i]
}
}
labels <- levels(x[,classColumn])
if(type=="classical"){
newClass <- sapply(1:nrow(x),function(i){
sumsPerClass <- sapply(labels,function(label){
sum(similarity[x[,classColumn]==label,i])+exp(-beta)*sum(similarity[x[,classColumn]!=label,i])
})
labels[nnet::which.is.max(sumsPerClass)]
})
}
if(type=="iterative"){
currentClass <- as.character(x[,classColumn])
k <- 1
convergenceRate <- 1.1
while(k <= maxIter & convergenceRate > epsilon){
oldClass <- currentClass
currentClass <- sapply(1:nrow(x),function(i){
sumsPerClass <- sapply(labels,function(label){
sum(similarity[currentClass==label,i])+exp(-beta)*sum(similarity[currentClass!=label,i])
})
labels[nnet::which.is.max(sumsPerClass)]
})
k <- k+1
convergenceRate <- sum(currentClass!=oldClass)/length(currentClass)
}
newClass <- currentClass
}
if(type=="weighted"){
weights <- sapply(1:nrow(x),function(i){
(sum(similarity[i,x[,classColumn]==x[i,classColumn]])+exp(-beta)*sum(similarity[i,x[,classColumn]!=x[i,classColumn]]))/sum(similarity[i,])
})
newClass <- sapply(1:nrow(x),function(i){
sumsPerClass <- sapply(labels,function(label){
indexEq <- x[,classColumn]==label
sum(similarity[indexEq,i]*weights[indexEq])+exp(-beta)*sum(similarity[!indexEq,i]*weights[!indexEq])
})
labels[nnet::which.is.max(sumsPerClass)]
})
}
if(noiseAction=="remove"){
remIdx <- which(newClass!=x[,classColumn])
repIdx <- NULL
repLab <- NULL
cleanData <- x[setdiff(1:nrow(x),remIdx),]
}
if(noiseAction=="repair"){
remIdx <- NULL
repIdx <- which(newClass!=x[,classColumn])
repLab <- factor(newClass[repIdx], levels = labels)
cleanData <- x
cleanData[,classColumn] <- newClass
}
parameters <- list(type = type,
noiseAction = noiseAction,
maxIter = maxIter,
alpha = alpha,
beta = beta)
call <- match.call()
call[[1]] <- as.name("ModeFilter")
ret <- list(cleanData = cleanData,
remIdx = remIdx,
repIdx=repIdx,
repLab=repLab,
parameters=parameters,
call = call,
extraInf = NULL
)
class(ret) <- "filter"
return(ret)
} |
VAR.Rmat <-
function(p,k,restrict,type="const")
{
info = restrict[,1:3,drop=F]
if(type=="none") add <- 0
if(type=="const") add <- 1
if(type=="const+trend") add <-2
M = p*(k^2)+add*k - nrow(info)
Rmat = diag(M);
rmat = matrix(0,nrow=p*(k^2)+add*k)
mat1 <- rep(1:k,k)
mat2 <- rep(1:k,each=k)
mat3 <- rep(1:p,each=k^2)
position <- cbind(mat3,mat1,mat2)
tem1=numeric()
for (i in 1:nrow(position)){
for (j in 1:nrow(info)){
tem = prod(as.numeric(position[i,] == info[j,]))
if (tem == 1) tem1=c(tem1,i)}}
for(i in 1:length(tem1)){
index = tem1[i]
if(index == 1) Rmat <- rbind(matrix(0,ncol=M),Rmat)
else{
if(index <= nrow(Rmat)) Rmat <- rbind(Rmat[1:(index-1),,drop=F],matrix(0,ncol=M),Rmat[index:nrow(Rmat),,drop=F])
if(index > nrow(Rmat)) Rmat <- rbind(Rmat,matrix(0,ncol=M)) }
}
if(ncol(restrict) == 4) rmat[tem1,] = restrict[,4]
index1 = rowSums(Rmat)
index2 = 1
Cmat=matrix(0,nrow=nrow(restrict),ncol=p*k^2+add*k)
for (i in 1:length(index1))
if (index1[i] == 0) {Cmat[index2,i] = 1; index2=index2+1}
cmat = matrix(0,nrow=nrow(restrict))
if(ncol(restrict) == 4) cmat = matrix(restrict[,4])
return(list(Rmat=Rmat,rvec=rmat,Cmat=Cmat,cvec=cmat))
} |
loess.psa<-function(response, treatment = NULL,
propensity = NULL, family = "gaussian", span = .7, degree=1, minsize=5,
xlim=c(0,1), colors = c('dark blue','dark green','blue','dark green'),
legend.xy = "topleft", legend = NULL, int = 10,
lines = TRUE, strata.lines = TRUE, rg = TRUE,
xlab="Estimated Propensity Scores", ylab="Response", pch = c(16,1), ...){
if(is.vector(response)){
rtp<-data.frame(response,treatment,propensity)}else{
rtp<-as.data.frame(response)
dimnames(rtp)[2]<-list(c("response","treatment","propensity"))}
if(is.null(treatment)){treatment<-response[,2]}
sut<-sort(unique(treatment))
response<-rtp[,1]
treatment<-rtp[,2]
propensity<-rtp[,3]
loess.0<-loess(rtp$r~rtp$p, subset = treatment == sut[1], family = family, span = span, degree=degree)
loess.1<-loess(rtp$r~rtp$p, subset = treatment == sut[2], family = family, span = span, degree=degree)
plot(rtp$p,rtp$r,type="n",xlim=range(rtp$p),xlab=xlab,ylab=ylab)
points(rtp$p[treatment==sut[1]],rtp$r[treatment==sut[1]],col=colors[1],pch = pch[1], ... )
points(rtp$p[treatment==sut[2]],rtp$r[treatment==sut[2]],col=colors[2],pch = pch[2], ...)
li<-length(int)
if(strata.lines){int2 <- int
if(li == 1){int2 <- quantile(propensity, seq(0, 1, 1/int))
li <- length(int2)
}
for(i in 1:li){abline(v = int2[i], lwd = .5, lty = 3, col = "dark grey")}
}
n0<-length(rtp$p[treatment==sut[1]])
n1<-length(rtp$p[treatment==sut[2]])
rtp.p.0<-rtp$p[treatment==sut[1]]
rtp.p.1<-rtp$p[treatment==sut[2]]
if(lines){ord.0<-order(rtp.p.0)
ord.1<-order(rtp.p.1)
lines(rtp.p.0[ord.0],loess.0$f[ord.0],cex=.6,col=colors[3], lwd = 1.5, lty = 1)
lines(rtp.p.1[ord.1],loess.1$f[ord.1],col=colors[4], lwd = 1.5, lty = 2)}
else{points(rtp$p[treatment==sut[1]],loess.0$f,pch=3,cex=.6,col=colors[3])
points(rtp$p[treatment==sut[2]],loess.1$f,pch=4,cex=.6,col=colors[4])}
if(is.null(legend)){legend<-sut}
legend(x = legend.xy, y = NULL, legend = legend, fill = colors[1:2], bty = "n")
if(rg){
rug(rtp$p[treatment==sut[1]], ticksize=.02, side=1, col=colors[1])
rug(rtp$r[treatment==sut[1]], ticksize=.02, side=2, col=colors[1])
rug(rtp$p[treatment==sut[2]], ticksize=.02, side=3, col=colors[2])
rug(rtp$r[treatment==sut[2]], ticksize=.02, side=4, col=colors[2])
box()
}
ed <- length(int)
if(ed==1){prop.labels<-as.numeric(cut(propensity, quantile(propensity, seq(0, 1, 1/int)),
include.lowest = TRUE, labels = FALSE)); nint<-int; dp<-0}
if(ed>1){
if(int[1]==0 & int[ed]==1){subints<-int; nint<-ed-1; dp<-0}
if(int[1] >0 & int[ed]==1){subints<-c(0,int); nint<-ed; dp<-1}
if(int[1]==0 & int[ed] <1){subints<-c(int,1); nint<-ed; dp<-2}
if(int[1] >0 & int[ed] <1){subints<-c(0,int,1); nint<-ed+1; dp<-3}
prop.labels<-as.numeric(cut(propensity,breaks=subints,include.lowest = TRUE, labels = FALSE))
}
table.plt<-table(prop.labels,treatment)
ttable.plt<-table.plt[,1]*table.plt[,2]
flag.0<-1
for(i in 1:nint){flag.0<-flag.0*ttable.plt[i]}
if(flag.0 == 0) print("Warning: Some strata-treatment levels have no cases. Redefine 'int'.")
o<-order(treatment)
prop.labels<-prop.labels[o]
resp.o<-response[o]
ncontrol<-table(treatment)[1]
ntreat<-table(treatment)[2]
means.0<-tapply(loess.0$fitted,prop.labels[1:ncontrol],mean)
var.0<-tapply(resp.o[1:ncontrol],prop.labels[1:ncontrol],var)
ncp1<-ncontrol+1
ncpnt<-ncontrol+ntreat
means.1<-tapply(loess.1$fitted,prop.labels[ncp1:ncpnt],mean)
var.1<-tapply(resp.o[ncp1:ncpnt],prop.labels[ncp1:ncpnt],var)
diff.means<-means.1-means.0
counts.0<-table(prop.labels[1:ncontrol])
counts.1<-table(prop.labels[(ncontrol+1):(ncontrol+ntreat)])
indicator.0<-NULL
indicator.1<-NULL
for(i in 1:nint)if(as.logical(counts.0[i]< minsize)){indicator.0<-c(indicator.0,0)}else{indicator.0<-c(indicator.0,1)}
for(i in 1:nint)if(as.logical(counts.1[i]< minsize)){indicator.1<-c(indicator.1,0)}else{indicator.1<-c(indicator.1,1)}
wts<-(counts.0+counts.1)*indicator.0*indicator.1
mash<-cbind(var.0,var.1,counts.0,counts.1,indicator.0,indicator.1)
mash<-na.omit(mash)
sum.wtd.var<-(mash[,1]/mash[,3] + mash[,2]/mash[,4])*mash[,5]*mash[,6]
nused.int<-sum(indicator.0*indicator.1)
out.table<-cbind(counts.0,counts.1,means.0,means.1,diff.means)
colnames(out.table)<-c(paste("counts.",sut[1],sep=""), paste("counts.",sut[2],sep=""),
paste("means.",sut[1],sep=""), paste("means.",sut[2],sep=""), "diff.means")
if(dp==0){dee <- sum((wts*diff.means),na.rm=TRUE)/sum(wts)
sd.wt <- ((sum(sum.wtd.var))^.5)/nused.int}
if(dp==1){dee <- sum((wts[-1]*diff.means[-1]),na.rm=TRUE)/sum(wts[-1])
sd.wt <- ((sum(sum.wtd.var[-1]))^.5)/nused.int
out.table<-out.table[-1,]
rownames(out.table)<-1:(nint-1)}
if(dp==2){dee <- sum((wts[-nint]*diff.means[-nint]),na.rm=TRUE)/sum(wts[-nint])
sd.wt <- ((sum(sum.wtd.var[-nint]))^.5)/nused.int
out.table <- out.table[-nint,]
rownames(out.table)<-1:(nint-1)}
if(dp==3){dee <- sum((wts[-c(1,nint)]*diff.means[-c(1,nint)]),na.rm=TRUE)/sum(wts[-c(1,nint)])
sd.wt <- ((sum(sum.wtd.var[-c(1,nint)]))^.5)/nused.int
out.table<-out.table[-c(1,nint),]
rownames(out.table)<-1:(nint-2)}
int.test<-c(5,10,15)
effect.test<-c(1,1,dee)
res<-cbind(int.test,effect.test)
it<-1
if(ed == 1) it<-int[1]
if(it == 15){
indx<-0
for(i in c(5,10)){
indx<-indx+1
prop.labels<-as.numeric(cut(propensity, quantile(propensity, seq(0, 1, 1/i)),
include.lowest = TRUE, labels = FALSE))
nint<-i
o<-order(treatment)
prop.labels<-prop.labels[o]
resp.o<-response[o]
ncontrol<-table(treatment)[1]
ntreat<-table(treatment)[2]
means.0<-tapply(loess.0$fitted,prop.labels[1:ncontrol],mean)
ncp1<-ncontrol+1
ncpnt<-ncontrol+ntreat
means.1<-tapply(loess.1$fitted,prop.labels[ncp1:ncpnt],mean)
difff.means<-means.1-means.0
counts.0<-table(prop.labels[1:ncontrol])
counts.1<-table(prop.labels[(ncontrol+1):(ncontrol+ntreat)])
indicator.0<-NULL
indicator.1<-NULL
for(i in 1:nint)if(as.logical(counts.0[i]< minsize)){indicator.0<-c(indicator.0,0)}else{indicator.0<-c(indicator.0,1)}
for(i in 1:nint)if(as.logical(counts.1[i]< minsize)){indicator.1<-c(indicator.1,0)}else{indicator.1<-c(indicator.1,1)}
wtts<-(counts.0+counts.1)*indicator.0*indicator.1
res[indx,2] <- sum((wtts*difff.means),na.rm=TRUE)/sum(wtts)
}
flag<-FALSE
err<-.05*(sd(response))
if(abs(res[1,2]-res[2,2]) > err) flag<-TRUE
if(abs(res[1,2]-res[3,2]) > err) flag<-TRUE
if(abs(res[2,2]-res[3,2]) > err) flag<-TRUE
if(flag) print("Warning: Effect size estimate unstable with changes in number of strata")
if(flag) print(res)
}
CI95<-c(dee-2*sd.wt,dee+2*sd.wt)
out<-list(dee, sd.wt, CI95, out.table)
names(out)<-c("ATE", "se.wtd", "CI95", "summary.strata")
return(out)
} |
bhl_gettitleitems <- function(...) {
.Defunct(new = "bhl_gettitlemetadata", package = "rbhl",
msg = "see ?bhl_gettitlemetadata")
} |
summary_tamaan_3pl_loclca <- function(object)
{
cat("*******************************\n")
cat("Cluster locations\n")
tam_round_data_frame_print(obji=object$locs, digits=3)
summary_tamaan_3pl_lcaprobs(object=object)
summary_tamaan_3pl_class_item_average(object=object)
} |
shift.up <- function( A, rows = 1, fill = 0 )
{
if ( !is.matrix( A ) ) {
stop( "argument A is not a matrix" )
}
if ( !is.numeric( A ) ) {
stop( "argument A is not a numeric matrix" )
}
if ( rows != trunc( rows ) )
stop( "Arguments rows is not an integer" )
if ( rows < 0 )
stop( "Argument rows is not positive" )
if ( !is.numeric( fill ) )
stop( "Argument fill is not numeric" )
if ( rows > 0 )
return( shift.up( rbind( A[2:nrow(A),], rep( fill, ncol(A) ) ),
rows - 1, fill ) )
return( A )
} |
exportAsGDAL <-
function(grid, shift, resolution, directory=getwd(), filename="grid.tif", drivername="GTiff"){
requireNamespace("rgdal")
direc <- unlist(strsplit(directory,""))
if (direc[length(direc)] != "/"){
direc <- c(direc, "/")
}
directory <- ""
for (i in 1:length(direc)){
directory <- paste(directory,direc[i], sep="")
}
dimension <- dim(grid)
values <- lat <- long <- vector(mode="numeric", length=dimension[1]*dimension[2])
count <- 1
for (m in 1:dimension[1]){
for ( n in 1:dimension[2]){
values[count] <- grid[m,n]
long[count] <- shift[1] + resolution*(m-1)
lat[count] <- shift[2] + resolution*(n-1)
count <- count + 1
}
}
result <- data.frame(values=values)
points <- sp::SpatialPoints(data.frame(long=long, lat=lat), proj4string=sp::CRS("+proj=longlat +datum=WGS84"))
result.spatial <- sp::SpatialPixelsDataFrame(points, result)
result.gdal <- as(result.spatial, "SpatialGridDataFrame")
rgdal::writeGDAL(result.gdal, fname=paste(directory,filename, sep=""), drivername=drivername)
} |
sffs <- function(profile_data, sens, sp = 1, max_k = 2, loo = TRUE, class = 2, averaging = "one.sided", weighted = FALSE, verbosity = FALSE) {
if (averaging == "one.sided") {
if(class == 2){
return(sffsBinary(profile_data, sens, sp, max_k, loo, verbosity))
}
else if(class > 2 && weighted == FALSE){
return(sffsCategory(profile_data, sens, sp, max_k, loo, class, verbosity))
}else{
return(sffsCategoryWeighted(profile_data, sens, sp, max_k, loo, class, verbosity))
}
} else if (averaging == "two.sided") {
if(class == 2){
return(sffsBinary1(profile_data, sens, sp, max_k, loo, verbosity))
}
else if(class > 2 && weighted == FALSE ){
return(sffsCategory1(profile_data, sens, sp, max_k, loo, class, verbosity))
}else{
return(sffsCategoryWeighted1(profile_data, sens, sp, max_k, loo, class, verbosity))
}
}
} |
get.box <- function(bathy,x1,x2,y1,y2,width,locator=FALSE,ratio=FALSE,...) {
if (class(bathy) != "bathy") stop("The matrix provided is not of class bathy")
if (width<=0) stop("Width must be a positive number")
if (!locator & (missing(x1)|missing(x2)|missing(y1)|missing(y2))) stop("You need to either use locator=TRUE or specify values for x1, x2, y1 and y2")
as.numeric(rownames(bathy)) -> lon
as.numeric(colnames(bathy)) -> lat
if (locator) {
pts <- locator(n=2,type="o",...)
if (length(pts$x) == 1) stop("Please choose two points from the map")
x1 <- pts$x[1]
x2 <- pts$x[2]
y1 <- pts$y[1]
y2 <- pts$y[2]
}
alpha <- -atan((x2-x1)/(y2-y1))
p1.x <- x1 + cos(alpha)*width/2
p2.x <- x2 + cos(alpha)*width/2
p3.x <- x2 - cos(alpha)*width/2
p4.x <- x1 - cos(alpha)*width/2
p1.y <- y1 + sin(alpha)*width/2
p2.y <- y2 + sin(alpha)*width/2
p3.y <- y2 - sin(alpha)*width/2
p4.y <- y1 - sin(alpha)*width/2
which.min(abs(lon-p1.x)) -> p1x
which.min(abs(lat-p1.y)) -> p1y
which.min(abs(lon-p4.x)) -> p4x
which.min(abs(lat-p4.y)) -> p4y
which.min(abs(lon-p2.x)) -> p2x
which.min(abs(lat-p2.y)) -> p2y
which.min(abs(lon-p3.x)) -> p3x
which.min(abs(lat-p3.y)) -> p3y
if (p1x==p4x | p1y==p4y) {
coord1 <- matrix(as.vector(bathy[p1x:p4x, p1y:p4y]),ncol=length(p1y:p4y),nrow=length(p1x:p4x),dimnames=list(lon[p1x:p4x],lat[p1y:p4y]))
coord1 <- cbind(as.numeric(dimnames(coord1)[[1]]),as.numeric(dimnames(coord1)[[2]]))
} else {
coord1 <- diag.bathy(bathy[p1x:p4x,p1y:p4y],coord=TRUE)
}
if (p2x==p3x | p2y==p3y) {
coord2 <- matrix(as.vector(bathy[p2x:p3x, p2y:p3y]),ncol=length(p2y:p3y),nrow=length(p2x:p3x),dimnames=list(lon[p2x:p3x],lat[p2y:p3y]))
coord2 <- cbind(as.numeric(dimnames(coord2)[[1]]),as.numeric(dimnames(coord2)[[2]]))
} else {
coord2 <- diag.bathy(bathy[p2x:p3x,p2y:p3y],coord=TRUE)
}
n1 <- nrow(coord1)
n2 <- nrow(coord2)
if (n1<n2) coord2 <- coord2[1:nrow(coord1),]
if (n1>n2) coord1 <- coord1[1:nrow(coord2),]
tr <- cbind(coord1,coord2)
out <- apply(tr,1,function(x) get.transect(x1=x[1],x2=x[3],y1=x[2],y2=x[4],mat=bathy,distance=TRUE))
di <- round(out[[1]][,3],2)
prof <- sapply(out,function(x) x[,4])
if (is.list(prof)) {
nr <- sapply(prof,length)
prof <- sapply(prof, function(x) x<-x[1:min(nr)])
}
rownames(prof) <- round(di[1:nrow(prof)])
colnames(prof) <- round(seq(from=-width/2,to=width/2,len=min(n1,n2)),2)
deg2km <- function(x1, y1, x2, y2) {
x1 <- x1*pi/180
y1 <- y1*pi/180
x2 <- x2*pi/180
y2 <- y2*pi/180
dx <- x2-x1
dy <- y2-y1
fo <- sin(dy/2)^2 + cos(y1) * cos(y2) * sin(dx/2)^2
fos <- 2 * asin(min(1,sqrt(fo)))
return(6371 * fos)
}
d <- max(as.numeric(rownames(prof)))
pmax <- -min(prof)/1000
w <- deg2km(p1.x,p1.y,p4.x,p4.y)
ratios <- round(c(w/d,pmax/d),3)
if (!locator)
lines(c(x1,x2),c(y1,y2),type="o",...)
lines(c(p1.x,p2.x,p3.x,p4.x,p1.x),c(p1.y,p2.y,p3.y,p4.y,p1.y),...)
if (ratio) return(list(depth=prof,ratios=ratios)) else return(prof)
} |
library(testthat)
library(gghighlight)
test_check("gghighlight") |
print.ORci <- function(x, ...)
{
attr(x, "conf.level") <- NULL
attr(x, "class") <- NULL
print(x, ...)
} |
ISOAbstractThematicAccuracy <- R6Class("ISOAbstractThematicAccuracy",
inherit = ISODataQualityAbstractElement,
private = list(
xmlElement = "AbstractDQ_ThematicAccuracy",
xmlNamespacePrefix = "GMD"
),
public = list()
)
ISOQuantitativeAttributeAccuracy <- R6Class("ISOQuantitativeAttributeAccuracy",
inherit = ISOAbstractThematicAccuracy,
private = list(
xmlElement = "DQ_QuantitativeAttributeAccuracy",
xmlNamespacePrefix = "GMD"
),
public = list()
)
ISONonQuantitativeAttributeAccuracy <- R6Class("ISONonQuantitativeAttributeAccuracy",
inherit = ISOAbstractThematicAccuracy,
private = list(
xmlElement = "DQ_NonQuantitativeAttributeAccuracy",
xmlNamespacePrefix = "GMD"
),
public = list()
)
ISOThematicClassificationCorrectness <- R6Class("ISOThematicClassificationCorrectness",
inherit = ISOAbstractTemporalAccuracy,
private = list(
xmlElement = "DQ_ThematicClassificationCorrectness",
xmlNamespacePrefix = "GMD"
),
public = list()
) |
library(gemma2)
context("Testing calc_sigma")
readr::read_tsv(system.file("extdata", "mouse100.pheno.txt", package = "gemma2"), col_names = FALSE) -> pheno
phe16 <- as.matrix(pheno[, c(1, 6)])
as.matrix(readr::read_tsv(system.file("extdata", "mouse100.cXX.txt", package = "gemma2"), col_names = FALSE)[, 1:100]) -> kinship
eigen2(kinship) -> eout
eout$values -> eval
eout$vectors -> U
V_g <- diag(c(1.91352, 0.530827))
V_e <- diag(c(0.320028, 0.561589))
X <- t(rep(1, 100)) %*% U
ep_out <- eigen_proc(V_g, V_e)
ep_out[[1]] -> logdet_Ve
ep_out[[2]] -> UltVeh
ep_out[[3]] -> UltVehi
ep_out[[4]] -> D_l
cq_out <- calc_qi(eval, D_l, X)
cq_out[[1]] -> Qi
co_out <- calc_omega(eval, D_l)
co_out[[1]] -> OmegaU
co_out[[2]] -> OmegaE
calc_sigma(eval, D_l, X, OmegaU, OmegaE, UltVeh, Qi) -> cs_out
cs_out[[1]] -> Sigma_ee
cs_out[[2]] -> Sigma_uu
test_that("Results of gemma2 equal those of GEMMA v 0.97", {
expect_equal(Sigma_ee, diag(c(18.559, 12.3672)), tolerance = 0.0001)
expect_equal(Sigma_uu, diag(c(82.2973, 41.9238)), tolerance = 0.0001)
}) |
NULL
tidy.ml_model_multilayer_perceptron_classification <- function(x,
...) {
num_layers <- length(x$model$layers)
weight_param <- NULL
weight_param <- purrr::map_dbl(seq_len(num_layers - 1), function(e) {
(x$model$layers[e] + 1) * x$model$layers[e + 1]
})
weight_param <- c(0, cumsum(weight_param))
weight_matrix <- list()
weight_matrix <- purrr::map(seq_len(length(weight_param) - 1), function(e) {
matrix(x$model$weights[(weight_param[e] + 1):weight_param[e + 1]],
nrow = x$model$layers[e] + 1,
ncol = x$model$layers[e + 1],
byrow = TRUE
)
})
layers <- purrr::map_chr(seq_len(num_layers - 1), function(e) {
paste0("layer_", e)
})
dplyr::tibble(layers, weight_matrix)
}
augment.ml_model_multilayer_perceptron_classification <- function(x, newdata = NULL,
...) {
broom_augment_supervised(x, newdata = newdata)
}
glance.ml_model_multilayer_perceptron_classification <- function(x, ...) {
num_layers <- length(x$model$layers)
input <- x$model$layers[1]
output <- x$model$layers[num_layers]
hidden <- x$model$layers[c(-1, -num_layers)]
names(hidden) <- purrr::map_chr(1:(num_layers - 2), function(e) {
paste0("hidden_", e, "_units")
})
c(
input_units = input,
hidden,
output_units = output
) %>%
as.list() %>%
dplyr::as_tibble()
} |
expected <- eval(parse(text="c(9223372036853727232, 1152921504606322688, 144115188075593728, 18014398509350912, 2251799813619712, 281474976677888, 35184372072448, 4398046502912, 549755809792, 68719474688.0001, 8589933568.00012, 1073741312.00024, 134217472.000488, 16777088.0009765, 2097088.00195271, 262112.00390339, 32752.0077931403, 4088.01549822222, 508.030458722825, 62.0579095299303, 7.10126282473794, 0.647385390948634, 0.0298849244167557, 0.000248025715892034, 4.59473369343568e-08, 3.20995645613222e-15, 2.68891929680868e-29, 2.94813344459608e-57, 5.271814156706e-113, 2.44544336199516e-224, 0)"));
test(id=0, code={
argv <- eval(parse(text="list(c(9.5367431640625e-07, 1.9073486328125e-06, 3.814697265625e-06, 7.62939453125e-06, 1.52587890625e-05, 3.0517578125e-05, 6.103515625e-05, 0.0001220703125, 0.000244140625, 0.00048828125, 0.0009765625, 0.001953125, 0.00390625, 0.0078125, 0.015625, 0.03125, 0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024), 3, 1)"));
.Internal(besselK(argv[[1]], argv[[2]], argv[[3]]));
}, o=expected); |
ledoit_wolf <- function(Y, ...){
if (!requireNamespace("nlshrink", quietly = TRUE)) {
stop("Please install the '", "nlshrink", "' package.")
}
Sigma <- nlshrink::linshrink_cov(as.matrix(Y))
R <- cov2cor(Sigma)
Rinv <- solve(R)
return(Rinv)
} |
td <- data.frame(
lettres = letters[1:10],
values = 1:10,
stringsAsFactors = FALSE
)
correct <-
structure(
c(
"Length:10 ",
"Class :character ",
"Mode :character ",
NA,
NA,
NA,
"Min. : 1.00 ",
"1st Qu.: 3.25 ",
"Median : 5.50 ",
"Mean : 5.50 ",
"3rd Qu.: 7.75 ",
"Max. :10.00 "
),
.Dim = c(6L, 2L),
.Dimnames = list(c("", "", "", "", "", ""), c(" lettres", " values")),
class = "table"
)
actual <- summary(td)
expect_identical(actual, correct) |
library(shiny)
attach(readRDS("data.rds"))
lapply(`_packages`, library, character.only = TRUE)
if (exists("_before")) {
`_before`()
}
if (!exists("_server")) {
`_server` <- function(input, output, session) {}
}
shinyApp(`_ui`, `_server`, enableBookmarking = `_bookmark`) |
expected_val <-
function (model, sig2, alpha = NULL, psi = NULL, time_span = c(0, 10),
quantile = FALSE, plot = FALSE, labels = TRUE, bm_col = "darkgoldenrod1",
ou_col = "firebrick2", da_col = "navy", exval_lwd = 5, ylim = NULL,...)
{
if(model %in% c("BM_null", "OU_null", "DA_null", "DA_OU", "DA_BM", "OU_BM")==FALSE) {
stop("Spell check: you've entered a model that doesn't match the models accepted by this function")
}
if (length(time_span) == 1) {
time <- time_span
}
if (length(time_span) > 2) {
time <- time_span
}
if (length(time_span) == 2) {
time = seq(0, time_span[2], (time_span[2]/10000))
}
if(model == "BM_null") {
V <- sig2 * time * 2
u = rep(0, length(time))
exdiv <- ((2 * V)/pi)^0.5
}
if(model == "OU_null") {
V <- (sig2/(alpha)) * (1 - exp(-2 * alpha * time))
u = rep(0, length(time))
exdiv <- ((2 * V)/pi)^0.5
}
if(model == "DA_null") {
V <- (sig2/(alpha)) * (1 - exp(-2 * alpha * time))
u <- psi * (1 - exp(-alpha * time))
exdiv <- sqrt((2 * V)/pi) * exp(-(u^2)/(2 * V)) + u * (2 * pnorm((u/sqrt(2 * V)) * sqrt(2)) - 1)
}
if(model == "DA_OU") {
V = V2 = (sig2/(alpha)) * (1 - exp(-2 * alpha * time))
u = rep(0, length(time))
u2 = psi * (1 - exp(-alpha * time))
exdiv <- ((2 * V)/pi)^0.5
exdiv2 <- sqrt((2 * V2)/pi) * exp(-(u2^2)/(2 * V2)) + u2 * (2 * pnorm((u2/sqrt(2 * V2)) * sqrt(2)) - 1)
}
if(model == "DA_BM") {
V <- sig2 * time * 2
u <- rep(0, length(time))
exdiv <- ((2 * V)/pi)^0.5
V2 <- (sig2/(alpha)) * (1 - exp(-2 * alpha * time))
u2 <- psi * (1 - exp(-alpha * time))
exdiv2 <- sqrt((2 * V2)/pi) * exp(-(u2^2)/(2 * V2)) + u2 * (2 * pnorm((u2/sqrt(2 * V2)) * sqrt(2)) - 1)
}
if(model == "OU_BM") {
V <- sig2 * time * 2
u = u2 = rep(0, length(time))
V2 <- (sig2/(alpha)) * (1 - exp(-2 * alpha * time))
exdiv <- ((2 * V)/pi)^0.5
exdiv2 <- ((2 * V2)/pi)^0.5
}
if (quantile == TRUE) {
qs = c(0.025, seq(0.1, 0.9, 0.1), 0.975)
quantiles = lapply(qs, FUN = truncnorm::qtruncnorm, a = 0, mean = u, sd = sqrt(V))
res <- matrix(NA, length(time), 13)
colnames(res) <- c("time", "Expectation", "q025", "q10","q20",
"q30", "q40", "q50", "q60", "q70", "q80", "q90",
"q975")
res[, 1] <- time
res[, 2] <- exdiv
for (i in 3:13) res[, i] = quantiles[[i - 2]]
if(model %in% c("DA_OU", "DA_BM", "OU_BM")) {
quantiles2 = lapply(qs, FUN = truncnorm::qtruncnorm, a = 0, mean = u2, sd = sqrt(V2))
res2 = res[,-1]
colnames(res2) = paste("model2_", colnames(res)[-1], sep="")
res2[,1] <- exdiv2
for (i in 2:12) res2[, i] = quantiles2[[i - 1]]
res = cbind(res, res2)
}
} else {
res <- matrix(NA, length(time), 2)
colnames(res) <- c("time", "Expected_Abs_Diff")
res[, 1] <- time
res[, 2] <- exdiv
if(model %in% c("DA_OU", "DA_BM", "OU_BM")) {
res = cbind(res, exdiv2)
colnames(res)[3] = "Expected_Abs_Diff_model2"
}
}
if (plot == TRUE) {
if (quantile == TRUE) {
x = length(quantiles)
time.plot = c(time, sort(time, decreasing=T))
y.m1 <- c(res[,"q025"], sort(res[,"q975"], decreasing=T))
if(model %in% c("DA_OU", "DA_BM", "OU_BM")) {
y.m2 <- c(res[,"model2_q025"], sort(res[,"model2_q975"], decreasing=T))
if(is.null(ylim)) ylim=c(0, max(c(quantiles[[x]],quantiles2[[x]]),na.rm=TRUE)*1.2)
if(model=="DA_OU") {
plot(res[,"model2_Expectation"] ~ time, type="l", ann=FALSE, col=da_col, lwd=exval_lwd, ylim=ylim, ...)
lines(res[,"Expectation"] ~ time, lty=1, col=ou_col, lwd=exval_lwd)
polygon(time.plot, y.m2, col = adjustcolor(da_col, alpha.f=0.2), border = NA)
polygon(time.plot, y.m1, col = adjustcolor(ou_col, alpha.f=0.2), border = NA)
}
if(model=="OU_BM") {
plot(res[,"Expectation"] ~ time, type="l", ann=FALSE, col=bm_col, lwd=exval_lwd, ylim=ylim, ...)
lines(res[,"model2_Expectation"] ~ time, lty=1, col=ou_col, lwd=exval_lwd)
polygon(time.plot, y.m2, col = adjustcolor(ou_col, alpha.f=0.2), border = NA)
polygon(time.plot, y.m1, col = adjustcolor(bm_col, alpha.f=0.2), border = NA)
}
if(model=="DA_BM") {
if(max(quantiles[[x]], na.rm=T) > max(quantiles2[[x]], na.rm=T)) {
plot(res[,"Expectation"] ~ time, type="l", ann=FALSE, col=bm_col, lwd=exval_lwd, ylim=ylim, ...)
lines(res[,"model2_Expectation"] ~ time, lty=1, col=da_col, lwd=exval_lwd)
} else {
plot(res[,"model2_Expectation"] ~ time, type="l", ann=FALSE, col=da_col, lwd=exval_lwd, ylim=ylim, ...)
lines(res[,"Expectation"] ~ time, lty=1, col=bm_col, lwd=exval_lwd)
}
polygon(time.plot, y.m1, col = adjustcolor(bm_col, alpha.f=0.2), border = NA)
polygon(time.plot, y.m2, col = adjustcolor(da_col, alpha.f=0.2), border = NA)
}
} else {
if(is.null(ylim)) ylim=c(0, max(quantiles[[x]],na.rm=TRUE)*1.2)
if(model=="BM_null") {
plot(exdiv ~ time, type="l", ann=FALSE, col=bm_col, lwd=exval_lwd, ylim=ylim, ...)
polygon(time.plot, y.m1, col = adjustcolor(bm_col, alpha.f=0.2), border = NA)
}
if(model=="OU_null") {
plot(exdiv ~ time, type="l", ann=FALSE, col=ou_col, lwd=exval_lwd, ylim=ylim, ...)
polygon(time.plot, y.m1, col = adjustcolor(ou_col, alpha.f=0.2), border = NA)
}
if(model=="DA_null") {
plot(exdiv ~ time, type="l", ann=FALSE, col=da_col, lwd=exval_lwd, ylim=ylim, ...)
polygon(time.plot, y.m1, col = adjustcolor(da_col, alpha.f=0.2), border = NA)
}
}
}
if (quantile == FALSE) {
if(model %in% c("DA_OU", "OU_BM", "DA_BM")) {
if(is.null(ylim)) ylim=c(0, max(c(exdiv,exdiv2),na.rm=TRUE)*1.2)
} else {
if(is.null(ylim)) ylim=c(0, max(exdiv,na.rm=TRUE)*1.2)
}
if(model=="DA_OU") {
plot(exdiv2 ~ time, type="l", ann=FALSE, col=da_col, lwd=exval_lwd, ylim=ylim, ...)
lines(exdiv ~ time, col=ou_col, lty=1, lwd=exval_lwd)
}
if(model=="OU_BM") {
plot(exdiv ~ time, type="l", ann=FALSE, col=bm_col, lwd=exval_lwd, ylim=ylim, ...)
lines(exdiv2 ~ time, col=ou_col, lty=1, lwd=exval_lwd)
}
if(model=="DA_BM") {
if(max(exdiv,na.rm=TRUE) > max(exdiv2, na.rm=TRUE)) {
plot(exdiv ~ time, type="l", ann=FALSE, col=bm_col, lwd=exval_lwd, ylim=ylim, ...)
lines(exdiv2 ~ time, col=da_col, lty=1, lwd=exval_lwd)
} else {
plot(exdiv2 ~ time, type="l", ann=FALSE, col=da_col, lwd=exval_lwd, ylim=ylim, ...)
lines(exdiv ~ time, col=bm_col, lty=1, lwd=exval_lwd)
}
}
if(model=="DA_null") plot(exdiv ~ time, type="l", ann=FALSE, col=da_col, lwd=exval_lwd, ylim=ylim, ...)
if(model=='OU_null') plot(exdiv ~ time, type="l", ann=FALSE, col=ou_col, lwd=exval_lwd, ylim=ylim, ...)
if(model=="BM_null") plot(exdiv ~ time, type="l", ann=FALSE, col=bm_col, lwd=exval_lwd, ylim=ylim, ...)
}
if (labels == TRUE) {
title(xlab = "Age of Lineage Pair")
title(ylab = "Trait Divergence")
}
}
return(res)
} |
speech = readLines("your/path/to/HOF/speeches/1939GeorgeHermanRuth.txt")
library(tm)
myCorpus = Corpus(VectorSource(speech))
myCorpus = tm_map(myCorpus, removePunctuation)
dtm = DocumentTermMatrix(myCorpus)
sum(dtm)
speechLength = data.frame(speech=character(0), words=numeric(0))
speechFiles = list.files(path="your/path/to/HOF/speeches/")
for(speechFile in speechFiles){
speech = readLines(paste("your/path/to/HOF/speeches/", speechFile, sep=""))
myCorpus = Corpus(VectorSource(speech))
myCorpus = tm_map(myCorpus, removePunctuation)
dtm = DocumentTermMatrix(myCorpus)
speechLine = data.frame(speech = speechFile, words=sum(dtm))
speechLength = rbind(speechLength, speechLine)
}
speechLength$year = as.numeric(substr(speechLength$speech, 1, 4))
library(ggplot2)
ggplot(data=speechLength, aes(x=year, y=words)) +
geom_point() +
geom_smooth()
speech = readLines("your/path/to/HOF/speeches/1971LeroyRobertPaige.txt")
myCorpus = Corpus(VectorSource(speech))
myCorpus = tm_map(myCorpus, tolower)
myCorpus = tm_map(myCorpus, removePunctuation)
myCorpus = tm_map(myCorpus, removeNumbers)
myCorpus = tm_map(myCorpus, removeWords, stopwords("english"))
library(wordcloud)
set.seed(1234)
wordcloud(myCorpus, min.freq = 3, rot.per=0, scale=c(3,.3)) |
pdf("fig1.pdf", width=7, height=7)
ptplot(1:3 + 2:3 ~ strata(sex)/(age + trt) + ns(ht/wt, df=4) / common + shared)
dev.off() |
context("Lowpass Test")
p <- maxample("pop")
test_that("lowpass performs proper calculations", {
dat20 <- new("magpie", .Data = structure(c(959.55885559599, 1482.98153190583,
1016.10215637913, 1498.22710355891, 1124.07386946257, 1526.47912463378,
1274.05397151945, 1564.06542027954, 1453.69856012463, 1607.07162185219,
1649.34145568655, 1652.33305222601, 1847.51308354974, 1697.82128947219,
2036.2117975872, 1742.39786194564, 2205.87893781679, 1785.24256306564,
2350.05785703802, 1825.37093631359, 2465.68152576388, 1861.51245252909,
2552.91053574485, 1892.35240763826, 2614.49349387643, 1916.92025740035,
2654.7374190261, 1934.85056911315, 2678.291126338, 1946.35308978183,
2688.9922783188, 1951.91585988556), .Dim = c(2L, 16L, 1L),
.Dimnames = list(i = c("AFR", "CPA"),
t = c("y1995", "y2005", "y2015", "y2025", "y2035",
"y2045", "y2055", "y2065", "y2075", "y2085",
"y2095", "y2105", "y2115", "y2125", "y2135",
"y2145"), scenario = "A2")))
expect_equivalent(lowpass(p[1:2, , 1], i = 20), dat20)
expect_identical(lowpass(p[1:2, 1:5, ]), lowpass(p[1:2, c(5, 3, 1, 2, 4), ]))
expect_warning(lowpass(p, fix = "start"), "does modify the total sum")
expect_error(lowpass(p, fix = "blablub"), "not available")
expect_identical(lowpass(p, i = 0), p)
expect_identical(lowpass(c(5, 3, 21, 8)), c(4.5, 8, 13.25, 11.25))
expect_identical(lowpass(c(5, 3, 21, 8), altFilter = 1:2), c(4.5, 9, 13.25, 11.25))
expect_identical(as.vector(lowpass(setYears(as.magpie(c(5, 3, 21, 8), temporal = 1), 1:4), altFilter = 1:2)),
lowpass(c(5, 3, 21, 8), altFilter = 1:2))
}) |
slim.lq.ladm.scr.btr <- function(Y, X, q, lambda, nlambda, n, d, maxdf, rho, max.ite, prec, intercept, verbose)
{
if(verbose==TRUE)
cat("LQ norm regrelarized regression (q =", q, ") with screening.\n")
XY = crossprod(X,Y)
beta = matrix(0,nrow=d,ncol=nlambda)
ite.int = rep(0,nlambda)
ite.int1 = rep(0,nlambda)
ite.int2 = rep(0,nlambda)
if(intercept) {
intcep=1
}else{
intcep=0
}
if(d>n){
if(n<=3){
num.scr1 = n
num.scr2 = n
}else{
num.scr1 = ceiling(n/log(n))
num.scr2 = n-1
}
}else{
if(d<=3){
num.scr1 = d
num.scr2 = d
}else{
num.scr1 = ceiling(sqrt(d))
num.scr2 = ceiling(d/log(d))
}
}
order0 = order(XY,decreasing = TRUE)
idx.scr = order0; num.scr = length(idx.scr)
idx.scr1 = order0[1:num.scr1]
idx.scr2 = order0[1:num.scr2]
X1 = X[,idx.scr]
XX = crossprod(X1)
gamma = max(colSums(abs(XX)))
str=.C("slim_lq_ladm_scr_btr", as.double(Y), as.double(X), as.double(XX),
as.double(beta), as.integer(n), as.integer(d), as.double(rho),
as.integer(ite.int), as.integer(ite.int1), as.integer(ite.int2),
as.integer(num.scr1), as.integer(num.scr2),
as.integer(idx.scr), as.integer(idx.scr1), as.integer(idx.scr2),
as.double(gamma), as.double(lambda),
as.integer(nlambda), as.integer(max.ite), as.double(prec),
as.integer(intcep), as.double(q), PACKAGE="flare")
beta.list = vector("list", nlambda)
for(i in 1:nlambda){
beta.i = unlist(str[4])[((i-1)*d+1):(i*d)]
beta.list[[i]] = beta.i
}
ite.int = unlist(str[8])
ite.int1 = unlist(str[9])
ite.int2 = unlist(str[10])
ite = list()
ite[[1]] = ite.int1
ite[[2]] = ite.int2
ite[[3]] = ite.int
return(list(beta=beta.list, ite=ite))
} |
context('mirtTwo')
test_that('poly', {
modp1 <- mirt(Science, 1, verbose=FALSE)
expect_is(modp1, 'SingleGroupClass')
expect_equal(extract.mirt(modp1, 'df'), 239)
cfs <- as.numeric(do.call(c, coef(modp1)))
expect_equal(cfs, c(1.041, 4.864, 2.64, -1.466, 1.226, 2.924, 0.901, -2.266, 2.296, 5.238, 2.216, -1.965, 1.095, 3.348, 0.992, -1.688, 0, 1),
tolerance = 1e-2)
C2 <- M2(modp1, type = 'C2')
expect_equal(C2$M2, 19.17929, tolerance=1e-4)
expect_equal(C2$p, 6.84337e-05, tolerance=1e-4)
modp2 <- mirt(Science, 1, 'sequential', verbose=FALSE)
expect_is(modp2, 'SingleGroupClass')
expect_equal(extract.mirt(modp2, 'df'), 239)
cfs <- as.numeric(do.call(c, coef(modp2)))
expect_equal(cfs, c(0.997414,4.831609,2.750703,-1.365844,1.067633,2.815793,1.104466,-1.87485,2.132679,5.021663,2.223683,-1.784284,0.9942698,3.287169,1.12849,-1.308458,0,1),
tolerance = 1e-2)
expect_equal(logLik(modp2), -1609.768, tolerance = 1e-4)
modLouis <- mirt(Science, 1, SE=T, SE.type='Louis', verbose=FALSE)
expect_is(modp1, 'SingleGroupClass')
cfs <- as.numeric(do.call(c, coef(modLouis, printSE=TRUE)))
expect_equal(cfs, c(1.04236, 0.18838, 4.86544, 0.49088, 2.64044, 0.22267, -1.46621, 0.15868, 1.22569, 0.18189, 2.924, 0.23928, 0.90115, 0.14289, -2.26661, 0.20308, 2.29058, 0.48269, 5.22988, 0.72817, 2.21201, 0.3564, -1.96222, 0.32209, 1.09557, 0.18336, 3.34845, 0.27659, 0.9919, 0.14053, -1.68846, 0.16864, 0, NA, 1, NA),
tolerance = 1e-3)
expect_equal(modLouis@OptimInfo$condnum, 98.26492, tolerance = 1e-2)
modsandwich <- mirt(Science, 1, SE=T, SE.type='sandwich.Louis', verbose=FALSE)
expect_is(modsandwich, 'SingleGroupClass')
cfs <- as.numeric(do.call(c, coef(modsandwich, printSE=TRUE)))
expect_equal(cfs, c(1.04236, 0.23843, 4.86544, 0.46794, 2.64044, 0.24659, -1.46621, 0.17162, 1.22569, 0.1922, 2.924, 0.24655, 0.90115, 0.14592, -2.26661, 0.19899, 2.29058, 0.52026, 5.22988, 0.80736, 2.21201, 0.373, -1.96222, 0.33683, 1.09557, 0.22701, 3.34845, 0.29203, 0.9919, 0.14491, -1.68846, 0.18015, 0, NA, 1, NA),
tolerance = 1e-3)
expect_equal(extract.mirt(modsandwich, 'condnum'), 141.5391, tolerance = 1e-2)
modsandwich <- mirt(Science, 1, SE=T, SE.type='sandwich', verbose=FALSE)
expect_is(modsandwich, 'SingleGroupClass')
cfs <- as.numeric(do.call(c, coef(modsandwich, printSE=TRUE)))
expect_equal(cfs, c(1.04236, 0.23843, 4.86544, 0.46794, 2.64044, 0.24659, -1.46621, 0.17162, 1.22569, 0.1922, 2.924, 0.24655, 0.90115, 0.14592, -2.26661, 0.19899, 2.29058, 0.52026, 5.22988, 0.80736, 2.21201, 0.373, -1.96222, 0.33683, 1.09557, 0.22701, 3.34845, 0.29203, 0.9919, 0.14491, -1.68846, 0.18015, 0, NA, 1, NA),
tolerance = 1e-3)
expect_equal(extract.mirt(modsandwich, 'condnum'), 141.5346, tolerance = 1e-2)
modOakes <- mirt(Science, 1, SE=T, SE.type='Oakes', verbose=FALSE)
expect_equal(modOakes@OptimInfo$condnum, 97.8644, tolerance = 1e-4)
modp1 <- mirt(Science, 1, verbose=FALSE)
expect_is(modp1, 'SingleGroupClass')
expect_equal(extract.mirt(modp1, 'df'), 239)
cfs <- as.numeric(do.call(c, coef(modp1)))
expect_equal(cfs, c(1.041, 4.864, 2.64, -1.466, 1.226, 2.924, 0.901, -2.266, 2.296, 5.238, 2.216, -1.965, 1.095, 3.348, 0.992, -1.688, 0, 1),
tolerance = 1e-2)
vals <- mirt(Science, 1, large = 'return', verbose=FALSE)
modp1 <- mirt(Science, 1, large = vals, verbose=FALSE)
expect_is(modp1, 'SingleGroupClass')
cfs <- as.numeric(do.call(c, coef(modp1)))
expect_equal(cfs, c(1.041, 4.864, 2.64, -1.466, 1.226, 2.924, 0.901, -2.266, 2.296, 5.238, 2.216, -1.965, 1.095, 3.348, 0.992, -1.688, 0, 1),
tolerance = 1e-2)
modp1 <- mirt(Science, 1, SE=TRUE, SE.type = 'SEM', verbose=FALSE)
expect_is(modp1, 'SingleGroupClass')
expect_equal(extract.mirt(modp1, 'condnum'), 108.8042, tolerance = 1e-2)
cfs <- as.numeric(do.call(c, coef(modp1)))
expect_equal(cfs, c(1.041, 0.656, 1.425, 4.863, 3.849, 5.876, 2.639, 2.196, 3.083, -1.466, -1.782, -1.149, 1.226, 0.887, 1.565, 2.924, 2.45, 3.398, 0.901, 0.614, 1.188, -2.266, -2.639, -1.894, 2.3, 1.325, 3.275, 5.244, 3.804, 6.685, 2.218, 1.488, 2.949, -1.967, -2.605, -1.329, 1.094, 0.727, 1.461, 3.347, 2.801, 3.893, 0.991, 0.717, 1.266, -1.688, -2.018, -1.357, 0, NA, NA, 1, NA, NA),
tolerance = 1e-2)
modp2 <- mirt(Science, 2, verbose=FALSE)
expect_is(modp2, 'SingleGroupClass')
expect_equal(modp2@Fit$df, 236)
cfs <- as.numeric(do.call(c, coef(modp2, verbose=FALSE)))
expect_equal(abs(cfs), abs(c(-1.3278,0.1081,5.1934,2.8583,-1.5996,-0.8762,1.8783,3.7248,1.1598,-2.9225,-1.4614,1.1639,4.6495,1.951,-1.7322,-1.7397,0,4.0053,1.2008,-2.0548,0,0,1,0,1)),
tolerance = 1e-2)
modp3 <- mirt(Science, 1, constrain = list(c(1,5)), parprior = list(c(4,'norm',0,1)), verbose=FALSE)
expect_is(modp3, 'SingleGroupClass')
cfs <- as.numeric(do.call(c, coef(modp3, verbose = FALSE)))
expect_true(mirt:::closeEnough(cfs - c(1.134,4.964,2.711,-1.473,1.134,2.865,0.882,-2.205,2.211,5.136,2.171,-1.91,1.129,3.383,1.006,-1.7,0,1),
-1e-2, 1e-2))
newmodel <- mirt.model('F = 1-4
CONSTRAIN = (1-2,a1)
PRIOR = (1, d1, norm, 4, 1)')
modp3 <- mirt(Science, newmodel, verbose=FALSE)
expect_is(modp3, 'SingleGroupClass')
cfs <- as.numeric(do.call(c, coef(modp3, verbose = FALSE)))
expect_true(mirt:::closeEnough(cfs - c(1.132,4.795,2.677,-1.507,1.132,2.856,0.874,-2.211,2.216,5.127,2.16,-1.927,1.128,3.374,0.999,-1.707,0,1),
-1e-2, 1e-2))
modOakes <- mirt(Science, newmodel, SE=T, SE.type='Oakes', verbose=FALSE)
expect_equal(modOakes@OptimInfo$condnum, 106.0775, tolerance = 1e-4)
modp4 <- mirt(Science, 1, itemtype = c(rep('graded',3), 'nominal'), verbose=FALSE)
expect_is(modp4, 'SingleGroupClass')
cfs <- as.numeric(do.call(c, coef(modp4, verbose = FALSE)))
expect_equal(cfs, c(1.0408, 4.862, 2.6387, -1.4664, 1.2063, 2.9083, 0.8958, -2.254, 2.3376, 5.2972, 2.2404, -1.9886, 0.7986, 0, 1.0782, 1.7756, 3, 0, 2.1964, 2.9637, 1.6742, 0, 1),
tolerance = 1e-2)
modp5 <- mirt(Science, 1, itemtype = c(rep('graded',3), 'gpcm'), SE = TRUE, SE.type = 'SEM', verbose=FALSE)
expect_is(modp5, 'SingleGroupClass')
cfs <- as.numeric(do.call(c, coef(modp5, verbose = FALSE)))
expect_equal(cfs, c(1.057,0.659,1.454,4.876,3.908,5.844,2.65,2.206,3.093,-1.472,-1.799,-1.146,1.219,0.865,1.573,2.918,2.444,3.391,0.9,0.615,1.185,-2.263,-2.662,-1.864,2.254,1.244,3.265,5.177,3.606,6.747,2.19,1.395,2.985,-1.942,-2.587,-1.298,0.771,0.441,1.1,0,NA,NA,1,NA,NA,2,NA,NA,3,NA,NA,0,NA,NA,2.16,1.537,2.782,2.973,2.276,3.671,1.767,1.128,2.407,0,NA,NA,1,NA,NA),
tolerance = 1e-2)
modp6 <- mirt(Science, 1, dentype="empiricalhist", verbose = FALSE, TOL=1e-3)
expect_is(modp6, 'SingleGroupClass')
cfs <- as.numeric(do.call(c, coef(modp6, verbose = FALSE)))
expect_equal(cfs, c(0.856,5.072,2.639,-1.35,1.095,2.951,0.968,-2.181,2.601,5.541,2.634,-1.752,0.988,3.443,1.058,-1.595,0,1),
tolerance = 1e-2)
fm0 <- fscores(modp1, method='EAP', response.pattern = c(1,2,3,4), full.scores=FALSE)
expect_equal(as.numeric(fm0[,c('F1','SE_F1')]), c(-0.3494903, 0.6004922), tolerance=1e-4)
fm1 <- fscores(modp1, verbose = FALSE, full.scores=FALSE)
expect_is(fm1, 'matrix')
expect_true(mirt:::closeEnough(fm1[1:6,'F1'] - c(-2.7488324, -1.4190140, -0.7154329, -0.4453752, -2.5438490, -1.2481072), -1e-2, 1e-2))
fm1b <- fscores(modp1, verbose = FALSE, full.scores=TRUE)
expect_equal(cor(fm1b, rowSums(Science))[1], .969, tolerance = .02)
fm2 <- fscores(modp2, rotate = 'oblimin', verbose = FALSE, full.scores=FALSE)
expect_is(fm2, 'matrix')
expect_true(mirt:::closeEnough(abs(as.numeric(fm2[1:6,c('F1','F2')])) -
c(2.5966,1.8668,0.6578,1.1597,2.4204,0.7001,2.412,0.8689,0.0258,0.2609,2.3376,1.4844),
-1e-2, 1e-2))
fm3 <- fscores(modp3, rotate = 'oblimin', full.scores = TRUE, verbose = FALSE)
expect_is(fm3, 'matrix')
fm4 <- fscores(modp4, verbose = FALSE, full.scores=FALSE)
expect_is(fm4, 'matrix')
expect_true(mirt:::closeEnough(fm4[1:6,'F1'] - c(-2.7320802, -1.4459303, -0.7910009, -0.5438761, -2.5310045, -1.1434060), -1e-2, 1e-2))
fm5 <- fscores(modp5, verbose = FALSE, full.scores=FALSE)
expect_is(fm5, 'matrix')
expect_true(mirt:::closeEnough(fm5[1:6,'F1'] - c(-2.7249561, -1.4446593, -0.7364399, -0.5627047, -2.5174376, -1.1732461), -1e-2, 1e-2))
resmat <- residuals(modp3, type = 'Q3', Theta = fm3[,'F'], verbose = FALSE)
expect_equal(as.numeric(resmat), c(1,-0.209,-0.283,0.057,-0.209,1,-0.149,-0.235,-0.283,-0.149,1,-0.33,0.057,-0.235,-0.33,1), tolerance=1e-2)
resmatLD <- residuals(modp3, type = 'LD', verbose = FALSE)
expect_equal(as.numeric(resmatLD), c(NA,23.88453,12.78836,22.16431,-0.1425131,NA,10.44856,22.30602,-0.1042807,0.09425936,NA,17.52566,0.1372851,-0.1377233,-0.1220769,NA), tolerance=1e-2)
resmatG2 <- residuals(modp3, type = 'LDG2', verbose = FALSE)
expect_equal(as.numeric(resmatG2), c(NA,21.11214,10.52294,19.91545,-0.1339869,NA,10.25686,17.55354,-0.09459427,0.0933907,NA,18.39732,0.1301342,-0.122174,-0.1250759,NA), tolerance=1e-2)
cof1 <- coef(modp1)
expect_is(cof1, 'list')
cof2 <- coef(modp2, verbose = FALSE)
expect_is(cof2, 'list')
IP1 <- itemplot(modp1, 1)
IP2 <- itemplot(modp2, 1)
expect_is(IP1, 'trellis')
expect_is(IP2, 'trellis')
fit <- suppressMessages(itemfit(modp2, c('S_X2', 'Zh')))
expect_equal(fit$Zh, c(1.413226, 2.455924, 4.125340, 3.887814), tolerance=1e-4)
expect_equal(fit$S_X2, c(3.941804,10.58528,6.913239,10.11068), tolerance=1e-4)
fs <- fscores(modp1, method = 'WLE', verbose=FALSE, full.scores=FALSE)
expect_equal(as.numeric(fs[1:3, 5:6]), c(-5.7024116, -2.1162737, -1.1386969, 1.5797286,
0.6321478, 0.6544024), tolerance = 1e-4)
if(FALSE){
rm(list=ls())
set.seed(1234)
a <- matrix(rep(1, 10))
d <- matrix(c(1,0.5,-.5,-1), 10, 4, byrow = TRUE)
cc <- seq(-1, 1, length.out=10)
data <- simdata(a, d + cc, 2000, itemtype = rep('graded',10))
sv <- mirt(data, 1, itemtype = 'grsm', pars = 'values', verbose=FALSE)
sv[,'value'] <- c(as.vector(t(cbind(a,d,cc))),0,1)
save(data, sv, file = 'tests/tests/testdata/rst.rds')
}
load('testdata/rst.rds')
grsm <- mirt(data, 1, itemtype = 'grsm', pars = sv, calcNull= FALSE, verbose=FALSE, TOL=1e-5)
rsm <- mirt(data, 1, itemtype = 'rsm', calcNull= FALSE, verbose=FALSE, TOL = 1e-3)
expect_is(grsm, 'SingleGroupClass')
expect_is(rsm, 'SingleGroupClass')
cfs <- as.numeric(do.call(c, coef(grsm, verbose = FALSE)))
expect_equal(cfs, c(0.958,1,0.491,-0.543,-1.034,-1,0.986,1,0.491,-0.543,-1.034,-0.765,0.993,1,0.491,-0.543,-1.034,-0.543,1.026,1,0.491,-0.543,-1.034,-0.272,0.994,1,0.491,-0.543,-1.034,-0.104,0.986,1,0.491,-0.543,-1.034,0.18,0.956,1,0.491,-0.543,-1.034,0.405,1.039,1,0.491,-0.543,-1.034,0.579,0.963,1,0.491,-0.543,-1.034,0.879,0.946,1,0.491,-0.543,-1.034,1.137,0,1),
tolerance = 1e-2)
cfs <- as.numeric(do.call(c, coef(rsm, verbose = FALSE)))
expect_equal(cfs, c(1,1.3931,-0.479,1.2474,-0.7059,0,1,1.3931,-0.479,1.2474,-0.7059,0.0779,1,1.3931,-0.479,1.2474,-0.7059,0.164,1,1.3931,-0.479,1.2474,-0.7059,0.2547,1,1.3931,-0.479,1.2474,-0.7059,0.321,1,1.3931,-0.479,1.2474,-0.7059,0.4254,1,1.3931,-0.479,1.2474,-0.7059,0.504,1,1.3931,-0.479,1.2474,-0.7059,0.5722,1,1.3931,-0.479,1.2474,-0.7059,0.6694,1,1.3931,-0.479,1.2474,-0.7059,0.7629,0,0.134),
tolerance = 1e-2)
expect_equal(extract.mirt(rsm, 'df'), 9765610)
expect_equal(extract.mirt(grsm, 'df'), 9765601)
graded <- mirt(data, 1, verbose = FALSE)
gM2 <- M2(graded, calcNull=TRUE)
expect_equal(gM2$M2, 16.68317, tolerance = 1e-4)
expect_equal(gM2$df, 5)
expect_equal(gM2$CFI, .9723554, tolerance = 1e-4)
expect_equal(gM2$SRMSR, 0.01984457, tolerance = 1e-4)
Theta <- matrix(seq(-4,4,.01))
x <- extract.item(modp1, 1)
iinfo <- iteminfo(x, Theta)
expect_is(iinfo, 'numeric')
iinfo <- iteminfo(x, Theta, total.info=FALSE)
expect_is(iinfo, 'matrix')
tinfo <- testinfo(modp1, Theta)
expect_is(tinfo, 'numeric')
ER <- fscores(modp2, returnER = TRUE)
expect_equal(as.numeric(ER), c(0.4882546, 0.5099054), tolerance=1e-4)
suppressWarnings(ER2 <- fscores(modp2, returnER = TRUE, mean = c(-1, 1), cov = matrix(c(1.5,1,1,2), 2)))
expect_equal(as.numeric(ER2), c(0.3905138, 0.4797115), tolerance=1e-4)
}) |
print.ufRisk <- function(x, ...) {
if (attr(x, "function") == "trafftest") {
cat(" ", fill = TRUE)
cat("
cat("
cat("
cat(" ", fill = TRUE)
cat("
df <- data.frame(Zone = c("Green zone:", "Yellow zone:", "Red zone:"),
Probability = c("p < 95%", "95% <= p < 99.99%", "p >= 99.99%"))
print.data.frame(df, row.names = FALSE, quote = FALSE, right = FALSE)
cat(" ", fill = TRUE)
pot.vals = c(x[["pot_VaR.v"]], x[["pot_VaR.e"]], round(x[["br.sum"]], 4))
p.vals <- c(x[["p_VaR.v"]], x[["p_VaR.e"]], x[["p_ES"]])
WAD <- round(x[["WAD"]], 4)
result <- rep(NA, times = 3)
result[p.vals < 0.95] <- "Green zone"
result[p.vals >= 0.95 & p.vals < 0.9999] <- "Yellow zone"
result[p.vals >= 0.9999] <- "Red zone"
p.vals <- round(p.vals, 4)
cat(paste0("
cat(" Number of violations:", pot.vals[1], fill = TRUE)
cat(" p = ", p.vals[[1]], ": ", result[[1]], fill = TRUE, sep = "")
cat(" ", fill = TRUE)
cat(paste0("
cat(" Number of violations:", pot.vals[2], fill = TRUE)
cat(" p = ", p.vals[[2]], ": ", result[[2]], fill = TRUE, sep = "")
cat(" ", fill = TRUE)
cat(paste0("
cat(" Number of weighted violations:", pot.vals[3], fill = TRUE)
cat(" p = ", p.vals[[3]], ": ", result[[3]], fill = TRUE, sep = "")
cat(" ", fill = TRUE)
cat("
cat(" WAD = ", WAD, fill = TRUE, sep = "")
}
if (attr(x, "function") == "covtest") {
cat(" ", fill = TRUE)
cat("
cat("
cat("
cat(" ", fill = TRUE)
cat("
cat(" ", fill = TRUE)
cat("H0: w = ", x$p, sep = "", fill = TRUE)
cat("p_[uc] = ", round(x$p.uc, 4), sep = "", fill = TRUE)
cat(" ", fill = TRUE)
cat("
cat(" ", fill = TRUE)
cat("H0: w_[00] = w[10]", sep = "", fill = TRUE)
cat("p_[ind] = ", round(x$p.ind, 4), sep = "", fill = TRUE)
cat(" ", fill = TRUE)
cat("
cat(" ", fill = TRUE)
cat("H0: w_[00] = w_[10] = ", x$p, sep = "", fill = TRUE)
cat("p_[cc] = ", round(x$p.cc, 4), sep = "", fill = TRUE)
}
} |
are_equal_mcmcs <- function(
mcmc_1, mcmc_2
) {
beautier::check_mcmc(mcmc_1)
beautier::check_mcmc(mcmc_2)
mcmc_1$chain_length == mcmc_2$chain_length &&
mcmc_1$store_every == mcmc_2$store_every &&
mcmc_1$pre_burnin == mcmc_2$pre_burnin &&
mcmc_1$n_init_attempts == mcmc_2$n_init_attempts &&
mcmc_1$sample_from_prior == mcmc_2$sample_from_prior &&
beautier::are_equal_tracelogs(mcmc_1$tracelog, mcmc_2$tracelog) &&
beautier::are_equal_screenlogs(mcmc_1$screenlog, mcmc_2$screenlog) &&
beautier::are_equal_treelogs(mcmc_1$treelog, mcmc_2$treelog)
} |
library(network)
set.seed(1702)
data("flo")
data("emon")
net <- network.initialize(5)
net
nmat <- matrix(rbinom(25, 1, 0.5), nr = 5, nc = 5)
net <- network(nmat, loops = TRUE)
net
summary(net)
all(nmat == net[,])
net <- as.network(nmat, loops = TRUE)
all(nmat == net[,])
nflo <- network(flo, directed = FALSE)
nflo
nflo[9,]
nflo[9,1]
nflo[9,4]
is.adjacent(nflo, 9, 1)
is.adjacent(nflo, 9, 4)
network.size(nflo)
network.edgecount(nflo)
network.density(nflo)
has.loops(nflo)
is.bipartite(nflo)
is.directed(nflo)
is.hyper(nflo)
is.multiplex(nflo)
as.sociomatrix(nflo)
all(nflo[,]==as.sociomatrix(nflo))
all(as.matrix(nflo)==as.sociomatrix(nflo))
as.matrix(nflo,matrix.type="edgelist")
net <- network.initialize(5,loops=TRUE)
net[nmat>0] <- 1
all(nmat==net[,])
net[,] <- 0
net[,] <- nmat
all(nmat==net[,])
net[,] <- 0
for(i in 1:5)
for(j in 1:5)
if(nmat[i,j])
net[i,j] <- 1
all(nmat==net[,])
net[,] <- 0
add.edges(net,row(nmat)[nmat>0],col(nmat)[nmat>0])
all(nmat==net[,])
net[,] <- as.numeric(nmat[,])
all(nmat==net[,])
net<-network.initialize(5)
add.edge(net,2,3)
net[,]
add.edges(net,c(3,5),c(4,4))
net[,]
net[,2]<-1
net[,]
delete.vertices(net,4)
net[,]
add.vertices(net,2)
net[,]
get.edges(net,1)
get.edges(net,2,neighborhood="in")
get.edges(net,1,alter=2)
get.edgeIDs(net,1)
get.edgeIDs(net,2,neighborhood="in")
get.edgeIDs(net,1,alter=2)
get.neighborhood(net,1)
get.neighborhood(net,2,type="in")
net[2,3]<-0
net[2,3]==0
delete.edges(net,get.edgeIDs(net,2,neighborhood="in"))
net[,]
net <- network.initialize(5)
set.network.attribute(net, "boo", 1:10)
net %n% "hoo" <- letters[1:7]
list.network.attributes(net)
get.network.attribute(net,"boo")
net %n% "hoo"
delete.network.attribute(net,"boo")
list.network.attributes(net)
set.vertex.attribute(net,"boo",1:5)
net %v% "hoo" <- letters[1:5]
list.vertex.attributes(net)
get.vertex.attribute(net,"boo")
net %v% "hoo"
delete.vertex.attribute(net,"boo")
list.vertex.attributes(net)
net <- network(nmat)
set.edge.attribute(net,"boo",sum(nmat):1)
set.edge.value(net,"hoo",matrix(1:25,5,5))
net %e% "woo" <- matrix(rnorm(25),5,5)
net[,,names.eval="zoo"] <- nmat*6
list.edge.attributes(net)
get.edge.attribute(get.edges(net,1),"boo")
get.edge.value(net,"hoo")
net %e% "woo"
as.sociomatrix(net,"zoo")
delete.edge.attribute(net,"boo")
list.edge.attributes(net)
MtSHloc<-emon$MtStHelens%v%"Location"
MtSHimat<-cbind(MtSHloc%in%c("L","B"),MtSHloc%in%c("NL","B"))
MtSHbyloc<-network(MtSHimat,matrix="incidence",hyper=TRUE,directed=FALSE,
loops=TRUE)
MtSHbyloc%v%"vertex.names"<-emon$MtStHelens%v%"vertex.names"
MtSHbyloc
plot(nflo, displaylabels = TRUE, boxed.labels = FALSE)
plot(nflo, displaylabels = TRUE, mode = "circle")
op<-par(no.readonly=TRUE)
par(mfcol=c(1,2),mar=c(1,1,1,1),cex=0.5)
plot(nflo, displaylabels = TRUE,boxed.labels = TRUE)
plot(nflo, displaylabels = TRUE, mode = "circle")
par(op)
plot(emon$MtSi)
plot(emon$MtSi)
library(sna)
network.layout.degree <- function(d, layout.par){
id <- degree(d, cmode = "indegree")
od <- degree(d, cmode = "outdegree")
cbind(id, od)
}
plot(emon$MtStHelens, mode = "degree", displaylabels = TRUE,
boxed.labels = FALSE, suppress.axes = FALSE, label.cex = 0.5,
xlab = "Indegree", ylab = "Outdegree", label.col = 3)
plot(emon$MtStHelens, mode = "degree", displaylabels = TRUE,
boxed.labels = FALSE, suppress.axes = FALSE, label.cex = 0.5,
xlab = "Indegree", ylab = "Outdegree", label.col = 3)
plot(MtSHbyloc, displaylabels = TRUE, label =
c(network.vertex.names(MtSHbyloc), "Local", "Non-Local"),
boxed.labels = FALSE, label.cex = rep(c(0.5, 1), times = c(27, 2)),
label.col = rep(c(3, 4), times = c(27, 2)), vertex.col = rep(c(2, 5),
times = c(27, 2)))
plot(MtSHbyloc, displaylabels = TRUE, label =
c(network.vertex.names(MtSHbyloc), "Local", "Non-Local"),
boxed.labels = FALSE, label.cex = rep(c(0.5, 1), times = c(27, 2)),
label.col = rep(c(3, 4), times = c(27, 2)), vertex.col = rep(c(2, 5),
times = c(27, 2)))
rnbernexp <- function(n, nv, p = 0.5, onset.hazard = 1,
termination.hazard = 1){
nets <- list()
for(i in 1:n)
nets[[i]] <- .Call("rnbernexp_R", network.initialize(nv,
directed = FALSE), p, onset.hazard, termination.hazard,
PACKAGE = "networkapi.example")
if(i > 1)
nets
else
nets[[1]]
} |
reviewr_datatable <- function(.data, dom = 'ftip', column_filter = 'top', search_term = '') {
DT::datatable(data = .data,
extensions = list('Scroller' = NULL),
options = list(dom = dom,
scrollX = TRUE,
deferRender = TRUE,
scrollY = '600px',
scroller = TRUE,
searchHighlight = TRUE,
search = list(regex = TRUE,
caseInsensitive = TRUE,
search = search_term)
),
rownames = F,
selection = 'single',
escape = F,
filter = column_filter,
class = 'cell-border strip hover'
)
}
NULL
navigation_message <- function(id) {
ns <- NS(id)
tagList(
uiOutput(ns('nav_message'))
)
}
all_patient_search_dt <- function(id) {
ns <- NS(id)
tagList(
DT::dataTableOutput(ns('all_patient_search_dt')) %>% withSpinner() ,
uiOutput(ns('data_model_message'))
)
}
chart_review_subject_info <- function(id) {
ns <- NS(id)
tagList(
uiOutput(ns('subject_info')) %>% withSpinner(type = 7, proxy.height = 100, size = .5)
)
}
chart_review_navigation <- function(id) {
ns <- NS(id)
arrowed <- paste0(
"$(document).on('keydown', function(event){",
" var key = event.which;",
" if(event.metaKey && event.altKey && key === 188){",
" Shiny.setInputValue('",id,"-arrowLeft', true, {priority: 'event'});",
" } else if(event.metaKey && event.altKey && key === 190){",
" Shiny.setInputValue('",id,"-arrowRight', true, {priority: 'event'});",
" }",
"});"
)
tagList(
tags$head(tags$script(HTML(arrowed))),
div(id = ns('jump_no_abstraction_div'),
selectizeInput(inputId = ns('subject_id'),
width = '100%',
label = 'Jump to Subject ID:',
choices = NULL,
selected = NULL,
options = list(create = FALSE,
placeholder = '<empty>'
)
)
),
shinyjs::hidden(
div(id = ns('jump_abstraction_div'),
pickerInput(inputId = ns('subject_id_2'),
label = 'Jump to Subject ID:',
choices = NULL,
selected = NULL,
choicesOpt = list(content = NULL),
options = pickerOptions(title = '<empty>',
virtualScroll = TRUE
)
)
)
),
fluidRow(
actionButton(inputId = ns('prev_subject'), label = '<-- Previous', width = '120px'),
actionButton(inputId = ns('next_subject'), label = 'Next -->', width = '120px'),
style = 'display:flex;justify-content:center;flex-wrap:wrap;'
)
)
}
navigation_server <- function(id, database_vars, data_model_vars, abstract_vars, parent_session) {
moduleServer(
id,
function(input, output, session) {
ns <- session$ns
navigation_vars <- reactiveValues(
dt_proxy = NULL,
all_patients = NULL,
all_patients_max_rows = NULL,
row_ids = NULL,
subject_ids = NULL,
selected_row = 0,
message = HTML('Please complete Setup to connect to a patient database.')
)
output$nav_message <- renderUI({ navigation_vars$message })
subject_vars <- reactiveValues(
selected_subject_id = NULL,
selected_subject_status = NULL
)
observeEvent(data_model_vars$table_functions, ignoreNULL = F, ignoreInit = T, {
if(is.null(data_model_vars$table_functions) == TRUE) {
message('Resetting patient navigation.')
navigation_vars$dt_proxy <- NULL
navigation_vars$all_patients <- NULL
navigation_vars$all_patients_max_rows = NULL
navigation_vars$row_ids = NULL
navigation_vars$subject_ids = NULL
navigation_vars$selected_row = 0
navigation_vars$message = HTML('Please complete Setup to connect to a patient database.')
updateSelectizeInput(session = session,
inputId = 'subject_id',
choices = navigation_vars$subject_ids,
server = T
)
updatePickerInput(session = session,
inputId = 'subject_id_2',
choices = navigation_vars$subject_ids
)
subject_vars$selected_subject_info <- NULL
subject_vars$selected_subject_id = NULL
} else {
message('Retrieving "all patients" table...')
navigation_vars$dt_proxy <- DT::dataTableProxy(outputId = ns('all_patient_search_dt'), session = parent_session)
all_patients_args <- list(table_map = data_model_vars$table_map,
db_connection = database_vars()$db_con
)
navigation_vars$all_patients <- rlang::exec(data_model_vars$all_patients_table %>%
pull('function_name'),
!!!all_patients_args
)
navigation_vars$all_patients_max_rows <- nrow(navigation_vars$all_patients)
navigation_vars$row_ids <- navigation_vars$all_patients %>%
mutate(row_id = row_number()) %>%
pull(.data$row_id)
navigation_vars$subject_ids <- setNames(navigation_vars$row_ids, navigation_vars$all_patients$ID)
updateSelectizeInput(session = session,
inputId = 'subject_id',
choices = navigation_vars$subject_ids,
server = T
)
navigation_vars$message <- HTML('To select a patient, please click the desired Subject ID from the table below:')
message('Complete')
}
})
output$all_patient_search_dt <- DT::renderDataTable({
if(is.null(navigation_vars$all_patients)) {
dplyr::tibble(.rows = 0) %>%
reviewr_datatable()
} else if (abstract_vars()$is_configured == 'yes') {
navigation_vars$all_patients %>%
left_join(abstract_vars()$all_review_status) %>%
dplyr::mutate_at(vars(dplyr::last_col(1), dplyr::last_col()), tidyr::replace_na, '<em>Review Not Started</em>') %>%
rename('Subject ID' = .data$ID) %>%
reviewr_datatable() %>%
formatStyle('Subject ID',
color = '
cursor = 'pointer',
textAlign = 'left'
)
} else {
navigation_vars$all_patients %>%
rename('Subject ID' = .data$ID) %>%
reviewr_datatable() %>%
formatStyle('Subject ID',
color = '
cursor = 'pointer',
textAlign = 'left'
)
}
})
observeEvent(input$all_patient_search_dt_rows_all, {
req(input$all_patient_search_dt_rows_all)
if(navigation_vars$selected_row == 0){
navigation_vars$selected_row <- 1
}
DT::selectRows(navigation_vars$dt_proxy, navigation_vars$selected_row)
})
output$data_model_message <- renderText({
req(database_vars()$is_connected == 'yes')
data_model_vars$message
})
observeEvent(abstract_vars()$previous_selected_instrument_complete_val, ignoreInit = T, {
if (abstract_vars()$previous_selected_instrument_complete_val %>% rlang::is_empty() == T ) {
subject_vars$selected_subject_status <- NULL
} else {
subject_vars$selected_subject_status <- if(abstract_vars()$previous_selected_instrument_complete_val == 0) { img(src = 'www/status_incomplete.png', style='width: 20px')
} else if(abstract_vars()$previous_selected_instrument_complete_val == 1) { img(src = 'www/status_unverified.png', style='width: 20px')
} else if(abstract_vars()$previous_selected_instrument_complete_val == 2) { img(src = 'www/status_complete.png', style='width: 20px')
} else {return(NULL)}
}
})
output$subject_info <- renderUI({
if(is.null(subject_vars$selected_subject_info)) {
tagList(
HTML('Please complete Setup to connect to a patient database.')
)
} else if (abstract_vars()$is_configured == 'yes') {
tagList(
div(h3(glue::glue('Subject ID: {subject_vars$selected_subject_id}'),
style='padding:0px;'
),
style='display:inline-block;vertical-align:middle'
),
div(subject_vars$selected_subject_status,
style='display:inline-block;vertical-align:middle'
),
div(renderTable(subject_vars$selected_subject_info %>%
left_join(abstract_vars()$all_review_status) %>%
select(-dplyr::last_col() ) %>%
dplyr::mutate_at(vars(dplyr::last_col()), tidyr::replace_na, '<em>Review Not Started</em>') %>%
mutate_all(as.character) %>%
select(-.data$ID),
width = '100%', align = 'l', digits = 0,
sanitize.text.function=identity
),
style='height:115px; overflow-y: scroll; scrollbar-width: thin;'
)
)
} else {
tagList(
div(h3(glue::glue('Subject ID: {subject_vars$selected_subject_id}'),
style='padding:0px;'
),
style='display:inline-block;vertical-align:middle'
),
renderTable(subject_vars$selected_subject_info %>%
mutate_all(as.character) %>%
select(-.data$ID),
width = '100%', align = 'l', digits = 0
)
)
}
})
observeEvent(input$all_patient_search_dt_rows_selected, {
req(input$all_patient_search_dt_rows_selected != navigation_vars$selected_row)
navigation_vars$selected_row <- input$all_patient_search_dt_rows_selected
})
observeEvent(input$all_patient_search_dt_cell_clicked, {
req(input$all_patient_search_dt_cell_clicked$value, input$all_patient_search_dt_cell_clicked$col == 0)
updateTabItems(parent_session, 'main_tabs', selected = 'chart_review')
})
observeEvent(navigation_vars$selected_row, {
req(navigation_vars$all_patients)
updateSelectizeInput(session = session,
inputId = 'subject_id',
choices = navigation_vars$subject_ids,
selected = navigation_vars$selected_row,
server = T)
if(abstract_vars()$is_configured == 'yes'){
updatePickerInput(session = session,
inputId = 'subject_id_2',
choices = navigation_vars$subject_ids,
selected = navigation_vars$selected_row,
choicesOpt = list(content = navigation_vars$individual_review_status %>%
unite(col = 'picker_html', sep = '<br>') %>%
pull(.data$picker_html)
)
)
}
subject_vars$selected_subject_info <- navigation_vars$all_patients %>%
slice(navigation_vars$selected_row)
subject_vars$selected_subject_id <- subject_vars$selected_subject_info %>%
pull(.data$ID)
DT::selectRows(navigation_vars$dt_proxy, navigation_vars$selected_row)
Sys.sleep(2)
shinyjs::enable('prev_subject')
shinyjs::enable('next_subject')
shinyjs::enable('subject_id')
shinyjs::enable('subject_id_2')
shinyjs::enable('all_patient_search_dt_rows_selected')
})
observeEvent(input$prev_subject, {
shinyjs::disable('prev_subject')
shinyjs::disable('next_subject')
shinyjs::disable('subject_id')
shinyjs::disable('all_patient_search_dt_rows_selected')
temp <- navigation_vars$selected_row - 1
if(temp < 1) {
navigation_vars$selected_row <- navigation_vars$all_patients_max_rows
} else {
navigation_vars$selected_row <- temp
}
})
observeEvent(input$arrowLeft, {
req(navigation_vars$all_patients)
shinyjs::disable('prev_subject')
shinyjs::disable('next_subject')
shinyjs::disable('subject_id')
shinyjs::disable('all_patient_search_dt_rows_selected')
temp <- navigation_vars$selected_row - 1
if(temp < 1) {
navigation_vars$selected_row <- navigation_vars$all_patients_max_rows
} else {
navigation_vars$selected_row <- temp
}
})
observeEvent(input$next_subject, {
shinyjs::disable('prev_subject')
shinyjs::disable('next_subject')
shinyjs::disable('subject_id')
shinyjs::disable('all_patient_search_dt_rows_selected')
temp <- navigation_vars$selected_row + 1
if(temp > navigation_vars$all_patients_max_rows) {
navigation_vars$selected_row <- 1
} else {
navigation_vars$selected_row <- temp
}
})
observeEvent(input$arrowRight, {
req(navigation_vars$all_patients)
shinyjs::disable('prev_subject')
shinyjs::disable('next_subject')
shinyjs::disable('subject_id')
shinyjs::disable('all_patient_search_dt_rows_selected')
temp <- navigation_vars$selected_row + 1
if(temp > navigation_vars$all_patients_max_rows) {
navigation_vars$selected_row <- 1
} else {
navigation_vars$selected_row <- temp
}
})
observeEvent(input$subject_id, ignoreInit = T, {
req(input$subject_id != '')
if(as.integer(input$subject_id) != navigation_vars$selected_row) {
shinyjs::disable('prev_subject')
shinyjs::disable('next_subject')
shinyjs::disable('subject_id')
shinyjs::disable('all_patient_search_dt_rows_selected')
navigation_vars$selected_row <- as.integer(input$subject_id) }
})
observeEvent(input$subject_id_2, ignoreInit = T, {
req(input$subject_id_2 != '')
if(as.integer(input$subject_id_2) != navigation_vars$selected_row) {
shinyjs::disable('prev_subject')
shinyjs::disable('next_subject')
shinyjs::disable('subject_id_2')
shinyjs::disable('all_patient_search_dt_rows_selected')
navigation_vars$selected_row <- as.integer(input$subject_id_2) }
})
observeEvent(abstract_vars()$is_configured, {
if(abstract_vars()$is_configured == 'yes') {
shinyjs::hide(id = 'jump_no_abstraction_div')
shinyjs::show(id = 'jump_abstraction_div')
} else if (abstract_vars()$is_configured == 'no') {
shinyjs::hide(id = 'jump_abstraction_div')
shinyjs::show(id = 'jump_no_abstraction_div')
}
})
observeEvent(c(navigation_vars$all_patients, abstract_vars()$all_review_status), {
req(navigation_vars$all_patients, abstract_vars()$all_review_status)
navigation_vars$individual_review_status <- navigation_vars$all_patients %>%
left_join(abstract_vars()$all_review_status) %>%
select(c(.data$ID, 'Review Status' = dplyr::last_col())) %>%
dplyr::mutate_at(vars(dplyr::last_col()), tidyr::replace_na, '<em>Review Not Started</em>')
updatePickerInput(session = session,
inputId = 'subject_id_2',
choices = navigation_vars$subject_ids,
selected = navigation_vars$selected_row,
choicesOpt = list(content = navigation_vars$individual_review_status %>%
unite(col = 'picker_html', sep = '<br>') %>%
pull(.data$picker_html)
)
)
})
return(subject_vars)
}
)
} |
dropSubsets.unordered <- function(subcascades=NULL, sets = NULL, neighborhood = 'direct', type = 'any')
{
if(is.null(subcascades))
return(NULL)
if(!inherits(subcascades, 'Subcascades'))
stop(errorStrings('subcascades'))
if(is.null(sets))
return(subcascades)
if(is.numeric(sets) & is.vector(sets))
sets <- list(sets)
if(!is.list(sets))
{
stop(errorStrings('sets.classes'))
}else{
if(!all(sapply(sets, function(x){is.numeric(x)&is.vector(x)})))
stop(errorStrings('sets.classes'))
}
if(!(neighborhood %in% c('direct','indirect')))
stop(errorStrings('neighborhood'))
if(!(type %in% c('all','any')))
stop(errorStrings('type'))
subcascades <- subcascades[sapply(subcascades, function(x){!is.null(x)})]
if(length(subcascades)==0)
return(NULL)
sizes.subcascades <- sapply(names(subcascades), function(x){as.numeric(strsplit(x,'.', fixed =TRUE)[[1]][2])})
sizes.sets <- sapply(sets, function(x){length(x)})
change <- switch( neighborhood,
'indirect' = sizes.subcascades <= max(sizes.sets),
'direct' = sizes.subcascades <= max(sizes.sets))
sets <- sapply(sets, function(x){paste(x,collapse = '>')})
sets <- unique(sets)
nms.sub <-names(subcascades)
subcascades <- lapply(1:length(subcascades), function(i){
casc <- subcascades[[i]]
if(change[i])
{
nms <- sapply(rownames(casc), function(x){
x <- strsplit(x,'>')[[1]]
numCl <- length(x)
paste(rep(paste('(',paste(x,collapse = '|'),'){1}',sep = ''), numCl), collapse = '>',sep = '')
})
nms <- switch( neighborhood,
'indirect' = paste('^([[:digit:]]+>)*',gsub('>', '(>[[:digit:]]+)*>',nms),'(>[[:digit:]]+)*$', sep = ''),
'direct' = paste('^([[:digit:]]+>)*',nms,'(>[[:digit:]]+)*$', sep = ''))
if(type == 'any')
{
keep <- !sapply(nms, function(exp){any(regexpr(pattern = exp, text = sets)>0)})
}else{
keep <- !sapply(nms, function(exp){all(regexpr(pattern = exp, text = sets)>0)})
}
if(sum(keep)==0)
{
return(NULL)
}else{
casc[keep,,drop=FALSE]
}
}else{
casc
}
})
names(subcascades) <- nms.sub
subcascades <- subcascades[sapply(subcascades, function(x){!is.null(x)})]
if(length(subcascades)==0)
{
return(NULL)
}else{
class(subcascades) <- 'Subcascades'
return(subcascades)
}
} |
knitr::opts_knit$set(root.dir = ".")
knitr::opts_chunk$set(collapse = TRUE, warning = TRUE)
set.seed(445)
library("experDesign")
library("experDesign")
metadata <- expand.grid(height = seq(60, 80, 5),
weight = seq(100, 300, 50),
sex = c("Male","Female"))
head(metadata, 15)
size_data <- nrow(metadata)
size_batch <- 24
(batches <- optimum_batches(size_data, size_batch))
(size <- optimum_subset(size_data, batches))
sizes_batches(size_data, size, batches)
d <- design(metadata, size_batch)
batch_names(d)
r <- replicates(metadata, size_batch, 5)
lengths(r)
r
s <- spatial(r, metadata, rows = LETTERS[1:6], columns = 1:4)
head(s)
report <- inspect(r, metadata)
report2 <- inspect(s, report, index_name = "position")
head(report2)
n <- 99
samples <- 100
unbalanced <- data.frame(Classroom = rep(c("A", "B"), each = samples/2),
Sex = c(rep("M", n), rep("F", samples-n)),
Age = rnorm(samples, mean = 25, sd = 3))
table(unbalanced)[, , 1:5]
i <- design(unbalanced, 15)
rowMeans(evaluate_index(i, unbalanced)["entropy", , ])
evaluate_orig(unbalanced)["entropy", ]
apply(evaluate_index(i, unbalanced)["entropy", , ], 1, sd)
data(survey, package = "MASS")
head(survey)
samples <- extreme_cases(survey, size = 10)
survey[samples, ]
sessionInfo() |
g.conv.actlog = function(qwindow, qwindow_dateformat="%d-%m-%Y") {
time2numeric = function(x) {
x = unlist(x)
c2t = function(x2) {
tmp = as.numeric(unlist(strsplit(as.character(x2),":")))
hourinday = tmp[1] + (tmp[2]/60)
return(hourinday)
}
out = as.numeric(sapply(x,c2t))
return(out)
}
extract_names = function(x) {
tmp = names(unlist(x))
tmp2 = gsub(pattern = "[.].*|_|-",replacement = "",x = tmp)
return(tmp2)
}
actlog = read.csv(file = qwindow)
actlog = actlog[which(actlog[,1] != ""),]
actlog_vec = unlist(actlog)
datecols = grep(pattern = "date|Date|DATE", x = colnames(actlog), value = FALSE)
if (length(datecols) > 0) {
exampledates = unlist(actlog[,datecols])
exampledates = exampledates[which(!is.na(exampledates))]
} else {
exampledates = c()
}
actlog_vec = sapply(actlog_vec, function(x) !all(is.na(as.Date(as.character(x),format=qwindow_dateformat))))
Ndates = length(which(actlog_vec == TRUE))
dim(actlog_vec) = c(nrow(actlog),ncol(actlog))
qwindow = data.frame(ID = rep(0,Ndates), date = rep("",Ndates))
qwindow$qwindow_times = qwindow$qwindow_values = qwindow$qwindow_numes = c()
cnt = 1
for (i in 1:nrow(actlog)) {
datei = which(actlog_vec[i,] == TRUE)
Ndays = length(datei)
if (Ndays > 0) {
qwindow$ID[cnt:(cnt+Ndays-1)] = rep(actlog[i,1],Ndays)
qwindow$date[cnt:(cnt+Ndays-1)] = as.character(as.Date(as.character(actlog[i,datei]),format=qwindow_dateformat))
datei = c(datei,max(which(actlog[i,] != "")) + 1)
for (j in 1:(length(datei)-1)) {
k = cnt+j-1
if ((datei[j+1] - datei[j]) >= 2) {
qwindow$qwindow_times[k] = list(actlog[i,(datei[j]+1):(datei[j+1]-1)])
qwindow$qwindow_values[k] = list(time2numeric(qwindow$qwindow_times[k]))
qwindow$qwindow_names[k] = list(extract_names(qwindow$qwindow_times[k]))
unlisted_qv = unlist(qwindow$qwindow_values[k])
unlisted_qt = unlist(qwindow$qwindow_times[k])
unlisted_qn = unlist(qwindow$qwindow_names[k])
if (length(which(is.na(unlisted_qv) == FALSE)) > 0) {
if (min(unlisted_qv, na.rm = TRUE) > 0) {
qwindow$qwindow_values[k] = list(c(0, unlisted_qv))
qwindow$qwindow_times[k] = list(c("00:00", unlisted_qt))
qwindow$qwindow_names[k] = list(c("daystart", unlisted_qn))
}
if (max(unlisted_qv, na.rm = TRUE) < 24) {
qwindow$qwindow_values[k] = list(c(unlist(qwindow$qwindow_values[k]), 24))
qwindow$qwindow_times[k] = list(c(unlist(qwindow$qwindow_times[k]), "24:00"))
qwindow$qwindow_names[k] = list(c(unlist(qwindow$qwindow_names[k]),"dayend"))
}
}
} else {
qwindow$qwindow_values[k] = list("")
qwindow$qwindow_names[k] = list("")
qwindow$qwindow_times[k] = list("")
}
}
cnt = cnt + Ndays
}
}
if (is.na(as.Date(qwindow$date[1],format="%y-%m-%d")) == FALSE) {
qwindow$date = as.Date(qwindow$date,format="%y-%m-%d")
} else {
qwindow$date = as.Date(qwindow$date)
}
if (is.na(qwindow$date[1]) == TRUE | class(qwindow$date[1]) != "Date") {
if (length(exampledates) > 0) {
warning(paste0("\n Date not recognised in activity diary. We expect format ",
qwindow_dateformat, " but we see ", paste0(head(exampledates), collapse=" "),
". You need to update the qwindow_dateformat argument, and check",
" that dates are in a consistent format."))
} else {
warning("\n Date not recognised in activity diary")
}
}
return(qwindow)
} |
modEvAmethods <- function(fun) {
if (fun %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 (fun == "threshMeasures") return(thresh.measures)
else if (fun == "multModEv") {
bin.measures <- c("HL", "HL.p", "RMSE")
return (c("Prevalence", "AUC", "MeanPrecision", "AUCPR", thresh.measures, bin.measures, "Miller.int", "Miller.slope"))
}
}
else if (fun == "getBins") return(c("round.prob", "prob.bins", "size.bins", "n.bins", "quantiles"))
else if (fun == "optiThresh") return(c("each", "preval", "0.5", "maxKappa", "minSensSpecDiff", "maxSensSpecSum", "maxTSS"))
} |
capture_requests <- function(expr, simplify = TRUE) {
start_capturing(simplify)
on.exit(stop_capturing())
eval.parent(expr)
}
start_capturing <- function(simplify = TRUE) {
req_tracer <- substitute(
{
redactor <- get_current_redactor()
if (exists("mock_resp") && !is.null(mock_resp)) {
resp <- mock_resp
}
if (!exists("resp") || inherits(resp, "error")) {
warning(
"Request errored; no captured response file saved",
call. = FALSE
)
} else {
save_response(
redactor(resp),
file = build_mock_url(redactor(req)),
simplify = simplify
)
}
},
list(simplify = simplify)
)
trace_httr2("req_perform", exit = req_tracer)
invisible(.mockPaths())
}
save_response <- function(response, file, simplify = TRUE) {
dst_file <- file.path(.mockPaths()[1], file)
mkdir_p(dst_file)
ct <- resp_content_type(response)
status <- resp_status(response)
if (simplify && status == 200 && ct %in% names(CONTENT_TYPE_TO_EXT)) {
cont <- resp_body_string(response)
if (ct == "application/json") {
cont <- prettify(cont)
}
dst_file <- paste(dst_file, CONTENT_TYPE_TO_EXT[[ct]], sep = ".")
cat_wb(cont, file = dst_file)
} else if (simplify && status == 204) {
dst_file <- paste0(dst_file, ".204")
cat_wb("", file = dst_file)
} else {
dst_file <- paste0(dst_file, ".R")
file <- paste0(file, ".R")
text_types <- c(
"application/json",
"application/x-www-form-urlencoded", "application/xml",
"text/csv", "text/html", "text/plain",
"text/tab-separated-values", "text/xml"
)
if (is.raw(response$body) && ct %in% text_types && length(response$body)) {
cont <- resp_body_string(response)
response$body <- substitute(charToRaw(cont))
} else if (inherits(response$body, c("httr2_path", "httr_path"))) {
downloaded_file <- paste0(dst_file, "-FILE")
file.copy(response$body, downloaded_file)
file <- paste0(file, "-FILE")
response$body <- substitute(structure(find_mock_file(file),
class = c("httr2_path", "httr_path")
))
}
f <- file(dst_file, "wb", encoding = "UTF-8")
on.exit(close(f))
dput(response, file = f)
}
verbose_message("Writing ", normalizePath(dst_file))
return(dst_file)
}
stop_capturing <- function() {
untrace_httr2("req_perform")
invisible()
}
mkdir_p <- function(filename) {
dir.create(dirname(filename), showWarnings = FALSE, recursive = TRUE)
}
cat_wb <- function(x, file, ...) {
f <- file(file, "wb", encoding = "UTF-8")
on.exit(close(f))
cat(enc2utf8(x), file = f, ...)
}
verbose_message <- function(...) {
if (isTRUE(getOption("httptest2.verbose", FALSE))) {
message(...)
}
} |
codonToAAthree <- function(codon){
if(grepl('TCA', codon, ignore.case = TRUE)){return('Ser')}
else if(grepl('TCC', codon, ignore.case = TRUE)){return('Ser')}
else if(grepl('TCG', codon, ignore.case = TRUE)){return('Ser')}
else if(grepl('TCT', codon, ignore.case = TRUE)){return('Ser')}
else if(grepl('TTC', codon, ignore.case = TRUE)){return('Phe')}
else if(grepl('TTT', codon, ignore.case = TRUE)){return('Phe')}
else if(grepl('TTA', codon, ignore.case = TRUE)){return('Leu')}
else if(grepl('TTG', codon, ignore.case = TRUE)){return('Leu')}
else if(grepl('TAC', codon, ignore.case = TRUE)){return('Tyr')}
else if(grepl('TAT', codon, ignore.case = TRUE)){return('Tyr')}
else if(grepl('TAA', codon, ignore.case = TRUE)){return('Stop')}
else if(grepl('TAG', codon, ignore.case = TRUE)){return('Stop')}
else if(grepl('TGC', codon, ignore.case = TRUE)){return('Cys')}
else if(grepl('TGT', codon, ignore.case = TRUE)){return('Cys')}
else if(grepl('TGA', codon, ignore.case = TRUE)){return('Stop')}
else if(grepl('TGG', codon, ignore.case = TRUE)){return('Trp')}
else if(grepl('CTA', codon, ignore.case = TRUE)){return('Leu')}
else if(grepl('CTC', codon, ignore.case = TRUE)){return('Leu')}
else if(grepl('CTG', codon, ignore.case = TRUE)){return('Leu')}
else if(grepl('CTT', codon, ignore.case = TRUE)){return('Leu')}
else if(grepl('CCA', codon, ignore.case = TRUE)){return('Pro')}
else if(grepl('CCC', codon, ignore.case = TRUE)){return('Pro')}
else if(grepl('CCG', codon, ignore.case = TRUE)){return('Pro')}
else if(grepl('CCT', codon, ignore.case = TRUE)){return('Pro')}
else if(grepl('CAC', codon, ignore.case = TRUE)){return('His')}
else if(grepl('CAT', codon, ignore.case = TRUE)){return('His')}
else if(grepl('CAA', codon, ignore.case = TRUE)){return('Gln')}
else if(grepl('CAG', codon, ignore.case = TRUE)){return('Gln')}
else if(grepl('CGA', codon, ignore.case = TRUE)){return('Arg')}
else if(grepl('CGC', codon, ignore.case = TRUE)){return('Arg')}
else if(grepl('CGG', codon, ignore.case = TRUE)){return('Arg')}
else if(grepl('CGT', codon, ignore.case = TRUE)){return('Arg')}
else if(grepl('ATA', codon, ignore.case = TRUE)){return('Ile')}
else if(grepl('ATC', codon, ignore.case = TRUE)){return('Ile')}
else if(grepl('ATT', codon, ignore.case = TRUE)){return('Ile')}
else if(grepl('ATG', codon, ignore.case = TRUE)){return('Met')}
else if(grepl('ACA', codon, ignore.case = TRUE)){return('Thr')}
else if(grepl('ACC', codon, ignore.case = TRUE)){return('Thr')}
else if(grepl('ACG', codon, ignore.case = TRUE)){return('Thr')}
else if(grepl('ACT', codon, ignore.case = TRUE)){return('Thr')}
else if(grepl('AAC', codon, ignore.case = TRUE)){return('Asn')}
else if(grepl('AAT', codon, ignore.case = TRUE)){return('Asn')}
else if(grepl('AAA', codon, ignore.case = TRUE)){return('Lys')}
else if(grepl('AAG', codon, ignore.case = TRUE)){return('Lys')}
else if(grepl('AGC', codon, ignore.case = TRUE)){return('Ser')}
else if(grepl('AGT', codon, ignore.case = TRUE)){return('Ser')}
else if(grepl('AGA', codon, ignore.case = TRUE)){return('Arg')}
else if(grepl('AGG', codon, ignore.case = TRUE)){return('Arg')}
else if(grepl('GTA', codon, ignore.case = TRUE)){return('Val')}
else if(grepl('GTC', codon, ignore.case = TRUE)){return('Val')}
else if(grepl('GTG', codon, ignore.case = TRUE)){return('Val')}
else if(grepl('GTT', codon, ignore.case = TRUE)){return('Val')}
else if(grepl('GCA', codon, ignore.case = TRUE)){return('Ala')}
else if(grepl('GCC', codon, ignore.case = TRUE)){return('Ala')}
else if(grepl('GCG', codon, ignore.case = TRUE)){return('Ala')}
else if(grepl('GCT', codon, ignore.case = TRUE)){return('Ala')}
else if(grepl('GAC', codon, ignore.case = TRUE)){return('Asp')}
else if(grepl('GAT', codon, ignore.case = TRUE)){return('Asp')}
else if(grepl('GAA', codon, ignore.case = TRUE)){return('Glu')}
else if(grepl('GAG', codon, ignore.case = TRUE)){return('Glu')}
else if(grepl('GGA', codon, ignore.case = TRUE)){return('Gly')}
else if(grepl('GGC', codon, ignore.case = TRUE)){return('Gly')}
else if(grepl('GGG', codon, ignore.case = TRUE)){return('Gly')}
else if(grepl('GGT', codon, ignore.case = TRUE)){return('Gly')}
else {stop(paste("Bad code: ", codon, ". code should only contains three of 'A','T','G','C'",sep=""))}
} |
LDAKPC <- function(x,y, n.pc,usekernel = FALSE, fL = 0,kernel.name = "rbfdot", kpar=list(0.001), kernel="gaussian",threshold = 1e-5,...){
LDAKPC <- list()
class(LDAKPC) <- "Linear Discriminant Analysis of Kernel principle components"
LDAKPC.train <- kernlab::kpca(~.,data=x,kernel = kernel.name,
kpar = kpar,
th = threshold,...)
if (is.null(n.pc)){
LDAKPC.rotation.train <- as.data.frame(LDAKPC.train@rotated)
} else {
LDAKPC.rotation.train <- as.data.frame(LDAKPC.train@rotated[,1:n.pc])}
lda.rotation.train <- MASS::lda(LDAKPC.rotation.train,y,CV=FALSE,...)
LDs <- as.matrix(LDAKPC.rotation.train) %*% as.matrix(lda.rotation.train$scaling)
labels <- as.factor(y)
LDAKPC$kpca<- LDAKPC.train
LDAKPC$kpc=LDAKPC.rotation.train
LDAKPC$LDAKPC<- lda.rotation.train
LDAKPC$LDs <- LDs
LDAKPC$label <- labels
LDAKPC$n.pc=n.pc
return(LDAKPC)
}
predict.LDAKPC <- function(object,prior=NULL, testData,...){
n.pc=object$n.pc
if(is.null(prior)==TRUE){
prior=object$LDAKPC$prior
}
predict.kpca <- kernlab::predict(object = object$kpca,
testData)[,1:n.pc]
predicted_LDs <- predict.kpca %*% as.matrix(object$LDAKPC$scaling)
predict.lda <- function(object, newdata, prior = object$prior, dimen,
method = c("plug-in", "predictive", "debiased"), ...)
{
if(!inherits(object, "lda")) stop("object not of class \"lda\"")
if(!is.null(Terms <- object$terms)) {
Terms <- delete.response(Terms)
if(missing(newdata)) newdata <- model.frame(object)
else {
newdata <- model.frame(Terms, newdata, na.action=na.pass,
xlev = object$xlevels)
if (!is.null(cl <- attr(Terms, "dataClasses")))
.checkMFClasses(cl, newdata)
}
x <- model.matrix(Terms, newdata, contrasts = object$contrasts)
xint <- match("(Intercept)", colnames(x), nomatch = 0L)
if(xint > 0L) x <- x[, -xint, drop = FALSE]
} else {
if(missing(newdata)) {
if(!is.null(sub <- object$call$subset))
newdata <-
eval.parent(parse(text = paste(deparse(object$call$x,
backtick = TRUE),
"[", deparse(sub, backtick = TRUE),",]")))
else newdata <- eval.parent(object$call$x)
if(!is.null(nas <- object$call$na.action))
newdata <- eval(call(nas, newdata))
}
if(is.null(dim(newdata)))
dim(newdata) <- c(1L, length(newdata))
x <- as.matrix(newdata)
}
if(ncol(x) != ncol(object$means)) stop("wrong number of variables")
if(length(colnames(x)) > 0L &&
any(colnames(x) != dimnames(object$means)[[2L]]))
warning("variable names in 'newdata' do not match those in 'object'")
ng <- length(object$prior)
if(!missing(prior)) {
if(any(prior < 0) || round(sum(prior), 5) != 1) stop("invalid 'prior'")
if(length(prior) != ng) stop("'prior' is of incorrect length")
}
means <- colSums(prior*object$means)
scaling <- object$scaling
x <- scale(x, center = means, scale = FALSE) %*% scaling
dm <- scale(object$means, center = means, scale = FALSE) %*% scaling
method <- match.arg(method)
dimen <- if(missing(dimen)) length(object$svd) else min(dimen, length(object$svd))
N <- object$N
if(method == "plug-in") {
dm <- dm[, 1L:dimen, drop = FALSE]
dist <- matrix(0.5 * rowSums(dm^2) - log(prior), nrow(x),
length(prior), byrow = TRUE) - x[, 1L:dimen, drop=FALSE] %*% t(dm)
dist <- exp( -(dist - apply(dist, 1L, min, na.rm=TRUE)))
} else if (method == "debiased") {
dm <- dm[, 1L:dimen, drop=FALSE]
dist <- matrix(0.5 * rowSums(dm^2), nrow(x), ng, byrow = TRUE) -
x[, 1L:dimen, drop=FALSE] %*% t(dm)
dist <- (N - ng - dimen - 1)/(N - ng) * dist -
matrix(log(prior) - dimen/object$counts , nrow(x), ng, byrow=TRUE)
dist <- exp( -(dist - apply(dist, 1L, min, na.rm=TRUE)))
} else {
dist <- matrix(0, nrow = nrow(x), ncol = ng)
p <- ncol(object$means)
X <- x * sqrt(N/(N-ng))
for(i in 1L:ng) {
nk <- object$counts[i]
dev <- scale(X, center = dm[i, ], scale = FALSE)
dev <- 1 + rowSums(dev^2) * nk/(N*(nk+1))
dist[, i] <- prior[i] * (nk/(nk+1))^(p/2) * dev^(-(N - ng + 1)/2)
}
}
posterior <- dist / drop(dist %*% rep(1, ng))
nm <- names(object$prior)
cl <- factor(nm[max.col(posterior)], levels = object$lev)
dimnames(posterior) <- list(rownames(x), nm)
list(class = cl, posterior = posterior, x = x[, 1L:dimen, drop = FALSE])
}
predict.LDAKPC <- predict.lda(object$LDAKPC,prior,
newdata = predict.kpca)
return(list(predicted_LDs=predicted_LDs,predict.LDAKPC=predict.LDAKPC))
} |
context("Chained creation and traversion")
createDom <- function() {
doc <- Document$new()
doc$setRootElement(Element$new(name="class"))
root <- doc$getRootElement()
e1 <- Element$new(name="student")
e1$setAttribute(name="rollno", value="393")
e1c1 <- Element$new(name="firstname")
e1c1$setText("Dinkar")
e1$addContent(e1c1)
e1c2 <- Element$new(name="lastname")$setText("Kad")
e1$addContent(e1c2)
e1$addContent(Element$new(name="nickname")$setText("dinkar"))
e1$addContent(Element$new(name="marks")$setText("85"))
root$addContent(e1)
root$addContent(Element$new(name="student")$setAttribute(name="rollno",value="493")
$addContent(Element$new(name="firstname")$setText("Vaneet"))
$addContent(Element$new(name="lastname")$setText("Gupta"))
$addContent(Element$new(name="nickname")$setText("vinni"))
$addContent(Element$new(name="marks")$setText("95"))
)
return(doc)
}
test_that("Chained creation and traversion works", {
document <- createDom()
rootName <- document$getRootElement()$getName()
expect_equal(info="Root element from document", rootName, "class")
expect_equal(capture_output(print(paste("Root element :", rootName))), "[1] \"Root element : class\"");
classElement <- document$getRootElement();
studentList <- classElement$getChildren();
expect_equal(info="Number of elements", length(classElement$getContent()), 2)
expect_equal(info="Number of children are", length(studentList), 2)
printp <- function(...) {
print(paste(...))
}
output <- capture.output({
for (student in studentList) {
print("-------------------------")
printp("Current Element :", student$getName())
printp("Student roll no : ", student$getAttribute("rollno") )
printp("First Name : ", student$getChild("firstname")$getText())
printp("Last Name : ", student$getChild("lastname")$getText())
printp("Nick Name : ", student$getChild("nickname")$getText())
printp("Marks : ", student$getChild("marks")$getText())
}
})
expect <- c(
'[1] "-------------------------"',
'[1] "Current Element : student"',
'[1] "Student roll no : 393"',
'[1] "First Name : Dinkar"',
'[1] "Last Name : Kad"',
'[1] "Nick Name : dinkar"',
'[1] "Marks : 85"',
'[1] "-------------------------"',
'[1] "Current Element : student"',
'[1] "Student roll no : 493"',
'[1] "First Name : Vaneet"',
'[1] "Last Name : Gupta"',
'[1] "Nick Name : vinni"',
'[1] "Marks : 95"'
)
expect_equal(output, expect)
}) |
context("Validate elements")
test_that("validate_elements returns TRUE when valid", {
X <- data.frame(E306 = as.integer(c(0, 1011, 9999, 9998, 4500)),
E347 = c("0001", "A998", "1987", "1980", "2020"),
stringsAsFactors = FALSE)
expect_true(all(validate_elements(X)))
})
test_that("validate_elements returns FALSE when invalid", {
X <- data.frame(E306 = as.integer(c(0, 1011, 999, 9998)))
expect_false(all(validate_elements(X, .progress_cat = TRUE)))
})
test_that("prop_elements and count_elements", {
X <- data.table(E319 = c("X1200", "X999", "99999", "A9998"),
E327 = c(1L, 3L, 31L, 33L),
E339 = c(-1, -2, -3, -4),
E355 = c(1L, 1L, 1L, 5L))
expected_prop <- c(0.75, 1, 0, 1)
names(expected_prop) <- names(X)
expect_identical(prop_elements_valid(X),
expected_prop)
expected_count <- c(1, 0, 4, 0)
names(expected_count) <- names(X)
expect_equal(count_elements_invalid(X),
expected_count)
})
test_that("Element E493 prepared as expected", {
expect_identical(heims_data_dict$E493$ad_hoc_prepare(as.integer(c(c(0, 10e3),
c(seq.int(2, 11) * 10e3 + 2002),
c(20004, 30017)))),
as.integer(c(c(0, 10e3),
c(seq.int(2, 11) * 10e3 + 2002),
29999, 39999)))
})
test_that("DOB less than current year", {
skip("Not yet implemented")
skip_if_not(file.exists("~/Students/cache/enrol_2005_2015.fst"))
library(fst)
library(data.table)
enrols <- setDT(read.fst("~/Students/cache/enrol_2005_2015.fst"))
rename_heims(enrols)
enrols[, .(DOB, Ref_year)] %>%
.[, DOB := as.Date()]
})
test_that("Valid elements for TER return TRUE or FALSE as expected", {
x <- c(31L, 29L)
y <- heims_data_dict$E369$ad_hoc_prepare(x)
expect_true(heims_data_dict$E369$valid(y[1]))
expect_true(heims_data_dict$E369$mark_missing(y[2]))
}) |
plot.pda.fd = function(x, whichdim=1,npts=501,...)
{
if (!inherits(x, "pda.fd")) stop("First argument is not of class pda.fd.")
rangval = x$resfdlist[[1]]$basis$rangeval
m = length(x$resfdlist)
tfine = seq(rangval[1],rangval[2],length.out=npts)
whichdim=unique(sort(whichdim))
bwtlist = x$bwtlist
if(m == 1){
d = length(bwtlist)
if(whichdim == 3){
par(mfrow=c(d,1))
for(i in 1:d){
titlestr = paste('Coefficient for Derivative',i-1)
plot(bwtlist[[i]]$fd,main=titlestr,...)
}
}
else{
betamat = matrix(0,npts,d)
legendstr = c()
for(i in 1:d){
betamat[,i] = eval.fd(tfine,bwtlist[[i]]$fd)
legendstr = c(legendstr,paste('Deriv',i))
}
xlabstr = names(bwtlist[[1]]$fd$fdnames)[[1]]
ylabstr = names(bwtlist[[1]]$fd$fdnames)[[3]]
matplot(tfine,betamat,type='l',lty=c(1:d),xlab=xlabstr,ylab=ylabstr,...)
legend(x='topleft',legend=legendstr,lty=c(1:d),...)
}
}
else{
d = length(bwtlist[[1]][[1]])
xlabstr = names(bwtlist[[1]][[1]][[1]]$fd$fdnames)[[1]]
ylabstr = names(bwtlist[[1]][[1]][[1]]$fd$fdnames)[[3]]
betamat = array(0,c(npts,m,m,d))
legendstr = array('',c(m,m,d))
for(i in 1:m){
for(j in 1:m){
for(k in 1:d){
betamat[,i,j,k] = eval.fd(tfine,bwtlist[[i]][[j]][[k]]$fd)
legendstr[i,j,k] = paste('var',i,'eq',j,'deriv',k)
}
}
}
if(length(whichdim)==1){
if(whichdim==1){
par(mfrow=c(m,1))
for(i in 1:m){
tbetamat = matrix(betamat[,i,,],npts,m*d,byrow=FALSE)
tlegendstr = as.vector(legendstr[i,,])
matplot(tfine,tbetamat,type='l',lty=c(1:(d*m)),col=c(1:(d*m)),xlab=xlabstr,ylab=ylabstr,...)
legend(x='topleft',legend=tlegendstr,lty=c(1:(d*m)),col=c(1:(d*m)),...)
}
}
if(whichdim==2){
par(mfrow=c(m,1))
for(j in 1:m){
tbetamat = matrix(betamat[,,j,],npts,m*d,byrow=FALSE)
tlegendstr = as.vector(legendstr[,j,])
matplot(tfine,tbetamat,type='l',lty=c(1:(d*m)),col=c(1:(d*m)),xlab=xlabstr,ylab=ylabstr,...)
legend(x='topleft',legend=tlegendstr,lty=c(1:(d*m)),col=c(1:(d*m)),...)
}
}
if(whichdim==3){
par(mfrow=c(d,1))
for(k in 1:d){
tbetamat = matrix(betamat[,,,k],npts,m*m,byrow=FALSE)
tlegendstr = as.vector(legendstr[,,k])
matplot(tfine,tbetamat,type='l',lty=c(1:(m*m)),col=c(1:(m*m)),xlab=xlabstr,ylab=ylabstr,...)
legend(x='topleft',legend=tlegendstr,lty=c(1:(m*m)),col=c(1:(m*m)),...)
}
}
}
else if(length(whichdim)==2){
if(whichdim[1]==1){
if(whichdim[2]==2){
par(mfrow=c(m,m))
for(i in 1:m){
for(j in 1:m){
matplot(tfine,betamat[,i,j,],type='l',lty=c(1:d),col=c(1:d),xlab=xlabstr,ylab=ylabstr,...)
legend(x='topleft',legend=legendstr[i,j,],lty=c(1:d),col=c(1:d),...)
}
}
}
if(whichdim[2]==3){
par(mfrow=c(m,d))
for(i in 1:m){
for(k in 1:d){
matplot(tfine,betamat[,i,,k],type='l',lty=c(1:m),col=c(1:m),xlab=xlabstr,ylab=ylabstr,...)
legend(x='topleft',legend=legendstr[i,,k],lty=c(1:m),col=c(1:m),...)
}
}
}
}
else{
par(mfrow=c(m,d))
for(j in 1:m){
for(k in 1:d){
matplot(tfine,betamat[,,j,k],type='l',lty=c(1:m),col=c(1:m),xlab=xlabstr,ylab=ylabstr,...)
legend(x='topleft',legend=legendstr[,j,k],lty=c(1:m),col=c(1:m),...)
}
}
}
}
else{
for(j in 1:m){
dev.new()
par(mfrow=c(m,d))
for(i in 1:m){
for(k in 1:d){
plot(bwtlist[[i]][[j]][[k]]$fd,main=legendstr[i,j,k],...)
}
}
}
}
}
} |
exptol.int <- function (x, alpha = 0.05, P = 0.99, side = 1, type.2 = FALSE)
{
if (side != 1 && side != 2) {
stop(paste("Must specify a one-sided or two-sided procedure!",
"\n"))
}
if (side == 2)
alpha <- alpha/2
n <- length(x)
l.hat <- mean(x)
if (type.2) {
mx <- max(x)
r <- n - sum(x == mx)
}
else r <- n
if (side == 2) {
lower <- 2 * r * l.hat * log(2/(1 + P))/qchisq(1 - alpha,
df = 2 * r)
upper <- 2 * r * l.hat * log(2/(1 - P))/qchisq(alpha,
df = 2 * r)
alpha <- 2 * alpha
}
else {
lower <- 2 * r * l.hat * log(1/P)/qchisq(1 - alpha, df = 2 *
r)
upper <- 2 * r * l.hat * log(1/(1 - P))/qchisq(alpha,
df = 2 * r)
}
temp <- data.frame(cbind(alpha, P, l.hat, lower, upper))
if (side == 2) {
colnames(temp) <- c("alpha", "P", "lambda.hat", "2-sided.lower",
"2-sided.upper")
}
else {
colnames(temp) <- c("alpha", "P", "lambda.hat", "1-sided.lower",
"1-sided.upper")
}
temp
} |
skewness.GB2 <-
function(b,a,p,q){
skewnessGB2<-rep(NA,length(b))
for(j in 1:length(b)){
fmGB2<- km.GB2(b[j],a[j],p[j],q[j],k=1)
smGB2<- km.GB2(b[j],a[j],p[j],q[j],k=2)
tmGB2<- km.GB2(b[j],a[j],p[j],q[j],k=3)
if(-a[j]*p[j]<3&a[j]*q[j]>3){
skewnessGB2[j] <- (tmGB2-3*fmGB2*(smGB2-fmGB2^2)-fmGB2^3)/(smGB2-fmGB2^2)^(3/2)
} else print(paste("-ap=",-a[j]*p[j],"and aq=",a[j]*q[j]))
}
return(skewnessGB2)
} |
test_that("vec_restore() returns a tune_results subclass if `x` retains tune_results structure", {
for (x in helper_tune_results) {
expect_identical(vec_restore(x, x), x)
expect_s3_class_tune_results(vec_restore(x, x))
}
})
test_that("vec_restore() returns bare tibble if `x` loses tune_results structure", {
for (x in helper_tune_results) {
col <- x[1]
row <- x[0,]
expect_s3_class_bare_tibble(vec_restore(col, x))
expect_s3_class_bare_tibble(vec_restore(row, x))
}
})
test_that("vec_ptype2() is working", {
for (x in helper_tune_results) {
tbl <- tibble::tibble(x = 1)
df <- data.frame(x = 1)
expect_identical(vec_ptype2(x, x), vec_ptype2(new_bare_tibble(x), new_bare_tibble(x)))
expect_identical(vec_ptype2(x, tbl), vec_ptype2(new_bare_tibble(x), tbl))
expect_identical(vec_ptype2(tbl, x), vec_ptype2(tbl, new_bare_tibble(x)))
expect_identical(vec_ptype2(x, df), vec_ptype2(new_bare_tibble(x), df))
expect_identical(vec_ptype2(df, x), vec_ptype2(df, new_bare_tibble(x)))
}
})
test_that("vec_cast() is working", {
for (x in helper_tune_results) {
tbl <- new_bare_tibble(x)
df <- as.data.frame(tbl)
expect_error(vec_cast(x, x), class = "vctrs_error_incompatible_type")
expect_identical(vec_cast(x, tbl), tbl)
expect_error(vec_cast(tbl, x), class = "vctrs_error_incompatible_type")
expect_identical(vec_cast(x, df), df)
expect_error(vec_cast(df, x), class = "vctrs_error_incompatible_type")
}
})
test_that("vec_ptype() returns a bare tibble", {
for (x in helper_tune_results) {
expect_identical(vec_ptype(x), vec_ptype(new_bare_tibble(x)))
expect_s3_class_bare_tibble(vec_ptype(x))
}
})
test_that("vec_slice() generally returns a bare tibble", {
for (x in helper_tune_results) {
expect_identical(vec_slice(x, 0), vec_slice(new_bare_tibble(x), 0))
expect_s3_class_bare_tibble(vec_slice(x, 0))
}
})
test_that("vec_slice() can return a tune_results if all rows are selected", {
for (x in helper_tune_results) {
expect_identical(vec_slice(x, TRUE), x)
expect_s3_class_tune_results(vec_slice(x, TRUE))
}
})
test_that("vec_c() returns a bare tibble", {
for (x in helper_tune_results) {
tbl <- new_bare_tibble(x)
expect_identical(vec_c(x), vec_c(tbl))
expect_identical(vec_c(x, x), vec_c(tbl, tbl))
expect_identical(vec_c(x, tbl), vec_c(tbl, tbl))
expect_s3_class_bare_tibble(vec_c(x))
expect_s3_class_bare_tibble(vec_c(x, x))
}
})
test_that("vec_rbind() returns a bare tibble", {
for (x in helper_tune_results) {
tbl <- new_bare_tibble(x)
expect_identical(vec_rbind(x), vec_rbind(tbl))
expect_identical(vec_rbind(x, x), vec_rbind(tbl, tbl))
expect_identical(vec_rbind(x, tbl), vec_rbind(tbl, tbl))
expect_s3_class_bare_tibble(vec_rbind(x))
expect_s3_class_bare_tibble(vec_cbind(x, x))
}
})
test_that("vec_cbind() returns a bare tibble", {
for (x in helper_tune_results) {
tbl <- new_bare_tibble(x)
expect_identical(vec_cbind(x), vec_cbind(tbl))
expect_identical(vec_cbind(x, x), vec_cbind(tbl, tbl))
expect_identical(vec_cbind(x, tbl), vec_cbind(tbl, tbl))
expect_s3_class_bare_tibble(vec_cbind(x))
expect_s3_class_bare_tibble(vec_cbind(x, x))
}
}) |
rec.ev.sim <-
function(n, foltime, dist.ev, anc.ev, beta0.ev, dist.cens=rep("weibull",length(beta0.cens)), anc.cens, beta0.cens, z=NULL, beta=NA, x=NA,
lambda=NA, max.ep=Inf, priskb=0, max.old=0)
{
if (length(anc.ev) != length(beta0.ev)) stop("Wrong number of parameters")
if (length(anc.cens) != length(beta0.cens)) stop("Wrong number of parameters")
if (length(anc.ev) != length(dist.ev)) stop("Wrong number of parameters")
if (priskb > 1 || priskb < 0) stop("Wrong proportion of left-censured individuals")
if (max.old < 0) stop("Wrong maximum time before follow-up")
if (!is.na(x) && is.na(beta)) stop("Wrong specification of covariables!")
if (is.na(x) && !is.na(beta)) stop("Wrong specification of covariables")
if (!is.null(z) && !all(lapply(z, function(x) x[1]) %in% c("unif","weibull","invgauss", "gamma","exp")))
stop("Wrong specification of z")
if (!is.null(z) && any(lapply(z, function(x) length(x)) != 3))
{
if(any(lapply(z[lapply(z, function(x) length(x)) != 3], function(x) length(x)) != 2)) stop("Wrong specification of z")
if(any(lapply(z[lapply(z, function(x) length(x)) != 3], function(x) length(x)) == 2))
{
for (i in 1:length(z[lapply(z, function(x) length(x)) == 2]))
{
if (z[lapply(z, function(x) length(x)) == 2][[i]][1] != "exp") stop("Wrong specification of z")
}
}
}
if(!is.null(z) && any(lapply(z, function(x) x[1]) == "unif"))
{
for (i in 1:length(z[lapply(z, function(x) x[1]) == "unif"]))
{
if (as.numeric(z[lapply(z, function(x) x[1]) == "unif"][[i]][2])-as.numeric(z[lapply(z, function(x) x[1]) == "unif"][[i]][3]) >= 0)
stop("Wrong specification of z")
if (as.numeric(z[lapply(z, function(x) x[1]) == "unif"][[i]][2]) < 0) stop("Wrong specification of z")
}
}
sim.data <- list()
eff <- vector()
un.ncens <- runif(n, 0, foltime)
un.cens <- runif(n, -max.old, 0)
ncens <- as.integer(priskb*n)
nncens <- as.integer(n - ncens)
max.time <- max(foltime, max.old)
eff[1] <- 0
if (nncens != 0)
{
for (i in 1:nncens)
{
if (!is.na(x[1]))
{
for (k in 1:length(x))
{
if (x[[k]][1] == "unif") eff[k] <- runif(1,as.numeric(x[[k]][2]),as.numeric(x[[k]][3]))
if (x[[k]][1] == "normal") eff[k] <- rnorm(1,as.numeric(x[[k]][2]),as.numeric(x[[k]][3]))
if (x[[k]][1] == "bern") eff[k] <- rbinom(1,1,as.numeric(x[[k]][2]))
}
}
sim.data[[i]] <- rec.ev.ncens.sim(foltime, anc.ev, beta0.ev, anc.cens, beta0.cens, z, beta, eff,
lambda, dist.ev, dist.cens, max.ep, un.ncens[i], i, max.time)
}
}
if (ncens != 0)
{
i <- nncens + 1
repeat
{
if (!is.na(x[1]))
{
for (k in 1:length(x))
{
if (x[[k]][1] == "unif") eff[k] <- runif(1,as.numeric(x[[k]][2]),as.numeric(x[[k]][3]))
if (x[[k]][1] == "normal") eff[k] <- rnorm(1,as.numeric(x[[k]][2]),as.numeric(x[[k]][3]))
if (x[[k]][1] == "bern") eff[k] <- rbinom(1,1,as.numeric(x[[k]][2]))
}
}
sim.data[[i]] <- rec.ev.cens.sim(foltime, anc.ev, beta0.ev, anc.cens, beta0.cens, z, beta, eff,
lambda, dist.ev, dist.cens, max.ep, un.cens[i],i, max.time)
if (dim(sim.data[[i]])[1] != 0)
{
i <- i + 1
}
if (i == n + 1) break
}
}
sim.data <- do.call(rbind, sim.data)
class(sim.data) <- c("rec.ev.data.sim", "data.frame")
attr(sim.data, "n") <- n
attr(sim.data, "foltime") <- foltime
attr(sim.data, "ndist") <- length(dist.ev)
return(sim.data)
} |
build_spm12_first_level_spec = function(
scans = NULL,
outdir = NULL,
units = c("scans", "secs"),
slice_timed = TRUE,
nslices = NULL,
ref_slice = NULL,
tr,
condition_mat = NULL,
condition_list = NULL,
regressor_mat = NULL,
regressor_list = NULL,
hpf = 128,
time_deriv = FALSE,
disp_deriv = FALSE,
interactions = FALSE,
global_norm = c("None", "Scaling"),
mthresh = 0.8,
mask = NULL,
correlation = c("AR(1)", "none", "FAST"),
n_time_points = NULL,
verbose = TRUE,
overwrite = TRUE,
...
) {
if (is.null(outdir)) {
outdir = tempfile()
dir.create(outdir, showWarnings = FALSE)
}
spm_mat = file.path(outdir, "SPM.mat")
if (file.exists(spm_mat)) {
if (!overwrite) {
stop(paste0(
"SPM.mat exists in outdir specified, but ",
"overwrite = FALSE")
)
} else {
file.remove(spm_mat)
}
}
units = match.arg(units)
units = convert_to_matlab(units)
if (!is.null(scans)) {
if (slice_timed) {
if (is.null(nslices) || is.null(ref_slice)) {
msg = paste0(
"If the data is slice-time corrected, nslices and ",
"ref_slice must be specified!")
stop(msg)
}
} else {
if (is.null(nslices)) {
nslices = 16
}
if (is.null(ref_slice)) {
nslices = 8
}
}
scans = filename_check(scans)
if (is.null(n_time_points)) {
time_points = ntime_points(scans)
if (verbose) {
message("
}
n_time_points = length(time_points)
} else {
time_points = seq(n_time_points)
}
filename = paste0(scans, ",", time_points)
filename = rvec_to_matlabcell(
filename,
transpose = FALSE,
sep = "\n")
}
time_deriv = as.numeric(time_deriv)
disp_deriv = as.numeric(disp_deriv)
derivatives = c(time_deriv, disp_deriv)
class(derivatives) = "rowvec"
derivatives = convert_to_matlab(derivatives)
interactions = as.logical(interactions)
interactions = as.integer(interactions) + 1L
correlation = match.arg(correlation)
correlation = convert_to_matlab(correlation)
global_norm = match.arg(global_norm)
global_norm = convert_to_matlab(global_norm)
if (!is.null(mask)) {
mask = filename_check(mask)
class(mask) = "cell"
mask = rvec_to_matlabcell(mask, sep = "")
} else {
mask = rvec_to_matlabcell("", sep = "")
}
if ( (is.null(condition_mat) && is.null(condition_list))
|| (!is.null(condition_mat) && !is.null(condition_list)) ) {
msg = paste0("Either condition_mat or condition_list",
" must be specified, but not both!")
stop(msg)
}
if ( (is.null(regressor_mat) && is.null(regressor_list))
|| (!is.null(regressor_mat) && !is.null(regressor_list)) ) {
msg = paste0("Either regressor_mat or regressor_list",
" must be specified, but not both!")
stop(msg)
}
sess = list(
scans = filename
)
if (!is.null(condition_mat)) {
condition_mat = normalizePath(condition_mat)
class(condition_mat) = "cell"
condition_mat = convert_to_matlab(condition_mat, sep = "")
sess$cond = paste0("struct('name', {}, 'onset', {},",
" 'duration', {}, ",
"'tmod', {}, 'pmod', {}, ",
"'orth', {});")
sess$multi = condition_mat
} else {
condition_list = spm12_condition_list(condition_list)
names(condition_list) = paste0("cond", names(condition_list))
sess = c(sess,
condition_list)
sess$multi = "{''}"
}
if (!is.null(regressor_mat)) {
regressor_mat = normalizePath(regressor_mat)
class(regressor_mat) = "cell"
regressor_mat = convert_to_matlab(regressor_mat, sep = "")
sess$regress = paste0("struct('name', {}, 'val', {});")
sess$multi_reg = regressor_mat
} else {
regressor_list = spm12_regressor_list(
regressor_list,
n_time_points = n_time_points)
names(regressor_list) = paste0("regress", names(regressor_list))
sess = c(sess,
regressor_list)
sess$multi_reg = "{''}"
}
xoutdir = outdir
class(outdir) = "cell"
outdir = convert_to_matlab(outdir)
sess$hpf = hpf
spm = list(
stats = list(
fmri_spec = list(
dir = outdir,
timing = list(
units = units,
RT = tr,
fmri_t = nslices,
fmri_t0 = ref_slice
),
sess = sess,
fact = "struct('name', {}, 'levels', {})",
bases = list(
hrf = list(
derivs = derivatives
)
),
volt = interactions,
global = global_norm,
mthresh = mthresh,
mask = mask,
cvi = correlation
)
)
)
spm = list(spm = spm)
class(spm) = "matlabbatch"
script = matlabbatch_to_script(spm, ...)
L = list(
spm = spm,
script = script)
L$outfile = L$spm_mat = spm_mat
L$outdir = xoutdir
return(L)
}
spm12_first_level_spec = function(
...,
outdir = NULL,
add_spm_dir = TRUE,
spmdir = spm_dir(verbose = verbose,
install_dir = install_dir),
clean = TRUE,
verbose = TRUE,
overwrite = TRUE,
install_dir = NULL
){
install_spm12(verbose = verbose,
install_dir = install_dir)
L = build_spm12_first_level_spec(
outdir = outdir,
verbose = verbose,
...)
outdir = L$outdir
spm = L$spm
if (verbose) {
message("
}
res = run_matlabbatch(
spm,
add_spm_dir = add_spm_dir,
clean = clean,
verbose = verbose,
spmdir = spmdir)
if (res != 0) {
warning("Result was not zero!")
}
L$result = res
return(L)
} |
summarymcmc<-function(output, name='MCMC'){
summary = list(name=name, estimates = output$means, estimates_of_functional = output$functionalmeans, acceptance_rate = output$acceptrate,
time_elapsed=output$runtime, phase_length=output$sumchain)
return(summary)
} |
group.STDERR <-
function(x,data) {
return(group.UCL(x,data,FUN=STDERR))
} |
pull_modeltime_residuals <- function(object) {
UseMethod("pull_modeltime_residuals")
}
pull_modeltime_residuals.model_fit <- function(object) {
if (is_modeltime_model(object)) {
ret <- object$fit$data %>% tibble::as_tibble()
} else {
ret <- NA
}
return(ret)
}
pull_modeltime_residuals.workflow <- function(object) {
if (is_modeltime_model(object)) {
ret <- object$fit$fit$fit$data %>% tibble::as_tibble()
} else {
ret <- NA
}
return(ret)
} |
vm2_mle <- function(data, model = c("vmsin", "vmcos"), ...) {
model <- model[1]
dots <- list(...)
data <- data.matrix(data)
call <- match.call()
if (is.null(dots$method)) {
dots$method <- "L-BFGS-B"
}
method <- dots$method
if (model == "vmsin") {
lpd_grad_model_indep_1comp <- function(par_vec_lscale) {
par_vec <- c(exp(par_vec_lscale[1:2]), par_vec_lscale[3:5])
lpd_grad <- matrix(NA, 6, 1)
lpd_grad <- signif(
suppressWarnings(grad_llik_vmsin_C(data, par_vec))*
c(par_vec[1:2], rep(1, 4)),
8
)
list(lpr = (lpd_grad[6]), grad = lpd_grad[1:5])
}
start_par_gen <- start_par_vmsin
hessian_fn <- function(par_vec) {
numDeriv::hessian(
func = function(par_vec) {
-grad_llik_vmsin_C(data, par_vec)[6]
},
x = par_vec
)
}
}
else if (model == "vmcos") {
ell <- dots[c("qrnd_grid", "n_qrnd")]
if (!is.null(ell$qrnd)) {
qrnd_grid <- ell$qrnd
dim_qrnd <- dim(qrnd_grid)
if (!is.matrix(qrnd_grid) | is.null(dim_qrnd) |
dim_qrnd[2] != 2)
stop("qrnd_grid must be a two column matrix")
n_qrnd <- dim_qrnd[1]
} else if (!is.null(ell$n_qrnd)){
n_qrnd <- round(ell$n_qrnd)
if (n_qrnd < 1)
stop("n_qrnd must be a positive integer")
qrnd_grid <- sobol(n_qrnd, 2, FALSE)
} else {
n_qrnd <- 1e4
qrnd_grid <- sobol(n_qrnd, 2, FALSE)
}
lpd_grad_model_indep_1comp <- function(par_vec_lscale) {
par_vec <- c(exp(par_vec_lscale[1:2]), par_vec_lscale[3:5])
lpd_grad <- matrix(NA, 6, 1)
lpd_grad[] <- signif(
suppressWarnings(grad_llik_vmcos_C(data, par_vec, qrnd_grid)) *
c(par_vec[1:2], rep(1, 4)),
8
)
list(lpr = (lpd_grad[6]), grad = lpd_grad[1:5])
}
start_par_gen <- start_par_vmcos
hessian_fn <- function(par_vec) {
numDeriv::hessian(
func = function(par_vec) {
-grad_llik_vmcos_C(data, par_vec, qrnd_grid)[6]
},
x = par_vec
)
}
}
else if (model == "indep") {
lpd_grad_model_indep_1comp <- function(par_vec_lscale) {
par_vec <- c(exp(par_vec_lscale[1:2]), 0, par_vec_lscale[4:5])
lpd_grad_parts <- lapply(
1:2,
function(j) {
signif(
suppressWarnings(grad_llik_univm_C(data[, j], par_vec[c(j, 3+j)]))*
c(par_vec[j], 1, 1),
8
)
}
)
lpr <- sum(sapply(lpd_grad_parts, "[", 3))
grad <- rep(0, 5)
for (j in 1:2) {
grad[c(j, 3+j)] <- lpd_grad_parts[[j]][1:2]
}
list(lpr = lpr, grad = grad)
}
start_par_gen <- function(dat) {
pars_by_dim <- lapply(1:2, function(j) start_par_vm(dat[, j]))
pars <- numeric(5)
for (j in 1:2) {
pars[c(j, 3+j)] <- pars_by_dim[[j]][1:2]
}
pars
}
hessian_fn <- function(par_vec) {
numDeriv::hessian(
func = function(par_vec) {
-sum(
sapply(
1:2,
function(j) grad_llik_univm_C(data[, j], par_vec[c(j, 3+j)])[3]
)
)
},
x = par_vec
)
}
}
start <- start_par_gen(data)
names(start) <- c("log_kappa1", "log_kappa2", "kappa3", "mu1", "mu2")
start_lscale <- start
start_lscale[c("log_kappa1", "log_kappa2")] <-
log(start[c("log_kappa1", "log_kappa2")])
opt <- optim(
par = start_lscale,
fn = function(par_lscale) {
-lpd_grad_model_indep_1comp(par_lscale)$lpr
},
gr = function(par_lscale) {
-lpd_grad_model_indep_1comp(par_lscale)$grad
},
lower = c(rep(-Inf, 3), 0, 0),
upper = c(rep(Inf, 3), 2*pi, 2*pi),
method = method
)
est_par <- opt$par
names(est_par)[1:2] <- c("kappa1", "kappa2")
est_par[c("kappa1", "kappa2")] <- exp(est_par[c("kappa1", "kappa2")])
hess <- hessian_fn(par_vec = est_par)
dimnames(hess) <- list(names(est_par), names(est_par))
if (model == "indep") {
vcov <- matrix(0, 5, 5)
dimnames(vcov) <- dimnames(hess)
vcov[-3, -3] <- solve(hess[-3, -3])
} else {
vcov <- solve(hess)
}
res <- methods::new(
"mle",
call = call,
coef = est_par,
fullcoef = unlist(est_par),
vcov = vcov,
min = opt$value,
details = opt,
minuslogl = function(kappa1, kappa2, kappa3, mu1, mu2) {
par_lscale <- c(log(kappa1), log(kappa2), kappa3, mu1, mu2)
-lpd_grad_model_indep_1comp(par_lscale)$lpr
},
nobs = nrow(data),
method = method
)
res
} |
files <- system("ls *.xml", intern=TRUE)
print("testing parsing only")
parses <- sapply(files, function(x){
out <- try(xmlParse(x))
if(is(out, "try-error"))
out <- x
else {
free(out)
out = "success"
}
out
})
fails <- parses[parses!="success"]
works <- files[parses == "success"]
writeLines(fails, "unparseable.txt")
print("testing parsing only")
treebase <- sapply(works,
function(x){
print(x)
tree <- try(nexml_read(x, "nexml"))
if(is(tree, "try-error"))
out = "read failed:"
else {
tree <- try(as(tree, "phylo"))
if(is(tree, "try-error"))
out = "conversion failed:"
else
out = "success"
}
rm(tree)
out
})
save(list=ls(), file = "RNeXML_test_results.rda")
table(treebase) |
estimateSd <- function(y, method=c("Hall", "von Neumann")){
method <- match.arg(method)
if (method=="von Neumann"){
y <- stats::na.omit(y)
dy <- diff(y)
Sd <- stats::mad(dy)/sqrt(2)
} else if (method=="Hall") {
Y <- as.matrix(y)
n <- nrow(Y)
wei <- c(0.1942, 0.2809, 0.3832, -0.8582)
Y1 <- Y[-c(n-2, n-1, n),, drop=FALSE]*wei[1]
Y2 <- Y[-c(1, n-1, n),, drop=FALSE]*wei[2]
Y3 <- Y[-c(1, 2, n),, drop=FALSE]*wei[3]
Y4 <- Y[-c(1, 2, 3),, drop=FALSE]*wei[4]
Sd <- sqrt(colMeans((Y1+Y2+Y3+Y4)^2, na.rm=TRUE))
}
return (Sd)
} |
processAncStates <-
function(path,
state_labels = NULL,
labels_as_numbers = FALSE,
missing_to_NA = TRUE) {
tree <- readTrees(path)
t <- tree[[1]][[1]]
include_start_states <- FALSE
if ("anc_state_1" %in% names(t@data)) {
} else if ("start_state_1" %in% names(t@data) &&
"end_state_1" %in% names(t@data)) {
include_start_states <- TRUE
} else {
stop(
"tree file does not contain expected state labels:
[\'anc_state\'] or [\'start_state\' and \'end_state\']"
)
}
t <-
.assign_state_labels(t,
state_labels,
include_start_states,
labels_as_numbers,
missing_to_NA)
t <- .set_pp_factor_range(t, include_start_states)
return(t)
} |
library(fredr)
knitr::opts_chunk$set(
fig.width = 7,
fig.height = 5,
eval = fredr_has_key(),
collapse = TRUE,
comment = "
)
library(fredr)
fredr_releases()
fredr_releases_dates()
fredr_releases_dates(
sort_order = "asc",
order_by = "release_id"
)
fredr_release(release_id = 11L)
fredr_release_dates(release_id = 11L)
fredr_release_series(release_id = 10L)
fredr_release_series(
release_id = 10L,
filter_variable = "frequency",
filter_value = "Monthly",
order_by = "popularity",
sort_order = "desc",
limit = 10L
)
fredr_release_tags(
release_id = 10L,
tag_group_id = "geo",
order_by = "popularity",
sort_order = "desc"
)
fredr_release_related_tags(
release_id = 10L,
tag_names = "bls",
tag_group_id = "freq",
exclude_tag_names = "annual",
order_by = "popularity",
sort_order = "desc"
)
fredr_release_sources(release_id = 10L)
cpi_tbl <- fredr_release_tables(release_id = 10L)
cpi_tbl
library(dplyr)
library(tibble)
cpi_tbl %>%
slice(2) %>%
deframe()
fredr_release_tables(
release_id = 10L,
element_id = 36712L
) |
message("\nTesting get_patient_info")
test_that("Structure of patients value", {
skip_on_cran()
patients_tcga <- get_patient_info("TCGA-BRCA")
expect_equal(length(patients_tcga), 3)
expect_equal(ncol(patients_tcga$patients), 6)
expect_true(nrow(patients_tcga$patients) > 50)
expect_true(length(patients_tcga$content) > 50)
expect_equal(class(patients_tcga$response), "response")
})
test_that("Number of all patients", {
skip_on_cran()
patients_all <- get_patient_info()
expect_true(nrow(patients_all$patients) > 5000)
expect_true("TCGA-OL-A6VO" %in% patients_all$patients$patient_id)
expect_true("TCGA-OL-A6VO" %in% patients_all$patients$patient_name)
expect_true("F" %in% patients_all$patients$patient_sex)
expect_true("TCGA-BRCA" %in% patients_all$patients$collection)
})
test_that("Number of BRCA patients", {
skip_on_cran()
patients_tcga <- get_patient_info("TCGA-BRCA")
expect_true(nrow(patients_tcga$patients) > 50)
expect_true("TCGA-OL-A6VO" %in% patients_tcga$patients$patient_id)
})
test_that("Individual BRCA patient", {
skip_on_cran()
patients_all <- get_patient_info()
pid <- "TCGA-OL-A6VO"
one_patient <- patients_all$patients[which(patients_all$patients$patient_id == pid), ]
expect_identical(pid, as.character(one_patient[1, "patient_name"]))
expect_identical("F", as.character(one_patient[1, "patient_sex"]))
expect_identical("TCGA-BRCA", as.character(one_patient[1, "collection"]))
expect_equal(NA, one_patient[1, "patient_dob"])
expect_equal(NA, one_patient[1, "patient_ethnic_group"])
})
test_that("Invalid collection name", {
skip_on_cran()
expect_warning(patients <- get_patient_info("fake collection"))
suppressWarnings(patients <- get_patient_info("fake collection"))
expect_equal(length(patients$content), 0)
}) |
context("char_class")
test_that(
"char_class wraps in class token",
{
expected <- as.regex("[abc]")
actual <- char_class("a", "b", "c")
expect_equal(actual, expected)
}
)
context("negated_char_class")
test_that(
"negated_char_class wraps in class token with ^",
{
expected <- as.regex("[^abc]")
actual <- negated_char_class("a", "b", "c")
expect_equal(actual, expected)
}
) |
cv_linear2ph <- function (Y_unval=NULL, Y=NULL, X_unval=NULL, X=NULL, Z=NULL, Bspline=NULL, data=NULL, nfolds=5, MAX_ITER=2000, TOL=1E-4, verbose=FALSE) {
storage.mode(MAX_ITER) = "integer"
storage.mode(TOL) = "double"
storage.mode(nfolds) = "integer"
if (missing(data)) {
stop("No dataset is provided!")
}
if (missing(Y_unval)) {
stop("The error-prone response Y_unval is not specified!")
} else {
vars_ph1 = Y_unval
}
if (missing(X_unval)) {
stop("The error-prone covariates X_unval is not specified!")
} else {
vars_ph1 = c(vars_ph1, X_unval)
}
if (missing(Bspline)) {
stop("The B-spline basis is not specified!")
} else {
vars_ph1 = c(vars_ph1, Bspline)
}
if (missing(Y)) {
stop("The accurately measured response Y is not specified!")
}
if (missing(X)) {
stop("The validated covariates in the second-phase are not specified!")
}
if (length(X_unval) != length(X)) {
stop("The number of columns in X_unval and X is different!")
}
if (!missing(Z)) {
vars_ph1 = c(vars_ph1, Z)
}
id_exclude = c()
for (var in vars_ph1) {
id_exclude = union(id_exclude, which(is.na(data[,var])))
}
if (verbose) {
print(paste("There are", nrow(data), "observations in the dataset."))
print(paste(length(id_exclude), "observations are excluded due to missing Y_unval, X_unval, or Z."))
}
if (length(id_exclude) > 0) {
data = data[-id_exclude,]
}
n = nrow(data)
if (verbose) {
print(paste("There are", n, "observations in the analysis."))
}
id_phase1 = which(is.na(data[,Y]))
for (var in X) {
id_phase1 = union(id_phase1, which(is.na(data[,var])))
}
if (verbose) {
print(paste("There are", n-length(id_phase1), "observations validated in the second phase."))
}
if (nfolds >= 3) {
if (verbose) {
print(paste0(nfolds, "-folds cross-validation will be performed."))
}
} else {
stop("nfolds needs to be greater than or equal to 3!")
}
Y_unval_vec = c(as.vector(data[-id_phase1,Y_unval]), as.vector(data[id_phase1,Y_unval]))
storage.mode(Y_unval_vec) = "double"
X_unval_mat = rbind(as.matrix(data[-id_phase1,X_unval]), as.matrix(data[id_phase1,X_unval]))
storage.mode(X_unval_mat) = "double"
Bspline_mat = rbind(as.matrix(data[-id_phase1,Bspline]), as.matrix(data[id_phase1,Bspline]))
storage.mode(Bspline_mat) = "double"
Y_vec = as.vector(data[-id_phase1,Y])
storage.mode(Y_vec) = "double"
X_mat = as.matrix(data[-id_phase1,X])
storage.mode(X_mat) = "double"
if (!is.null(Z)) {
Z_mat = rbind(as.matrix(data[-id_phase1,Z]), as.matrix(data[id_phase1,Z]))
storage.mode(Z_mat) = "double"
}
if (is.null(Z)) {
Z_mat = rep(1., n)
} else {
Z_mat = cbind(1, Z_mat)
}
idx_fold = c(sample(1:nfolds, size = length(Y_vec), replace = TRUE),
sample(1:nfolds, size = length(id_phase1), replace = TRUE))
pred_loglik = rep(NA, nfolds)
converge = rep(NA, nfolds)
for (fold in 1:nfolds) {
Train = as.numeric(idx_fold != fold)
res = .TwoPhase_MLE0_MEXY_CV_loglik(Y_unval_vec, X_unval_mat, Y_vec, X_mat, Z_mat, Bspline_mat, MAX_ITER, TOL, Train)
pred_loglik[fold] = res$pred_loglike
converge[fold] = !res$flag_nonconvergence
if (pred_loglik[fold] == -999.) {
pred_loglik[fold] = NA
}
}
avg_pred_loglik = mean(pred_loglik, na.rm = TRUE)
res_final = list(avg_pred_loglik=avg_pred_loglik, pred_loglik=pred_loglik, converge=converge)
res_final
} |
library(bayesAB)
context('dists')
dummyDist <- plotDist('norm', 'Normal', c('mu', 'sd'))
dummyDist2 <- plotDist('norm', 'Normal', c('mu', 'sd'))
test_that("Failures based on inputs", {
expect_error(dinvgamma(5, -1, 5), "Shape or scale parameter negative")
})
test_that("Closure madness", {
expect_equal(dummyDist, dummyDist2)
expect_identical(environment(dummyDist)$distArgs, environment(dummyDist2)$distArgs)
expect_equal(environment(dummyDist)$name, 'Normal')
expect_equal(formals(dummyDist), as.pairlist(alist(mu =, sd =)))
})
test_that("Success", {
expect_equal(plotPoisson(1)$labels$y, 'PDF')
expect_equal(plotPareto(1, 1)$labels$y, 'PDF')
expect_equal(plotNormal(1, 1)$labels$y, 'PDF')
expect_equal(plotGamma(1, 1)$labels$y, 'PDF')
expect_equal(plotBeta(1, 1)$labels$y, 'PDF')
expect_equal(plotInvGamma(1, 1)$labels$y, 'PDF')
expect_equal(plotLogNormal(1, 1)$labels$y, 'PDF')
expect_equal(qinvgamma(1 - (.Machine$double.eps) / 2, 2, 2), Inf)
expect_equal(dpareto(c(0, 1, 2), 1, 1), c(0, 0, .25))
expect_equal(dpareto(c(5, 15), 20, 3), c(0, 0))
expect_equal(max(plotNormalInvGamma(3, 100, 51, 216)$data$sig_sq), qgamma(.99, 51, 216) * 100)
expect_equal(plotNormalInvGamma(3, 1, 1, 1)$labels$y, 'sig_sq')
}) |
wrap <- function(f, pre, post, envir = parent.frame()) {
fmls <- formals(f)
called_fmls <- stats::setNames(lapply(names(fmls), as.symbol), names(fmls))
f_call <- as.call(c(substitute(f), called_fmls))
pre <- substitute(pre)
post <- substitute(post)
fun <- eval(bquote(function(args) {
.(pre)
.retval <- .(f_call)
.(post)
}, as.environment(list(f_call = f_call, pre = pre, post = post))))
formals(fun) <- fmls
environment(fun) <- envir
fun
} |
library(httpcache)
options(width=120)
system.time(a <- GET("https://httpbin.org/get"))
system.time(b <- GET("https://httpbin.org/get"))
identical(a, b)
clearCache()
startLog()
a <- GET("http://httpbin.org/get")
b <- GET("http://httpbin.org/get")
library(httptest) |
NULL
methods::setGeneric("fast_extract",
signature = methods::signature("x", "y"),
function(x, y, ...) standardGeneric("fast_extract"))
methods::setMethod(
"fast_extract",
signature(x = "Raster", y = "SpatialPolygons"),
function(x, y, fun = "mean", ...) {
fast_extract(x, sf::st_as_sf(y), fun, ...)
})
methods::setMethod(
"fast_extract",
signature(x = "Raster", y = "SpatialPoints"),
function(x, y, fun = "mean", ...) {
fast_extract(x, sf::st_as_sf(y), fun, ...)
})
methods::setMethod(
"fast_extract",
signature(x = "Raster", y = "SpatialLines"),
function(x, y, fun = "mean", ...) {
fast_extract(x, sf::st_as_sf(y), fun, ...)
})
methods::setMethod(
"fast_extract",
signature(x = "Raster", y = "sfc"),
function(x, y, fun = "mean", ...) {
fast_extract(x, sf::st_sf(y), fun, ...)
})
methods::setMethod(
"fast_extract",
signature(x = "Raster", y = "sf"),
function(x, y, fun = "mean", ...) {
assertthat::assert_that(
inherits(x, "Raster"),
inherits(y, "sf"),
assertthat::is.string(fun),
sf::st_crs(x@crs) == sf::st_crs(y),
intersecting_extents(x, y))
assertthat::assert_that(all(!geometry_classes(y) %in%
c("GEOMETRYCOLLECTION", "MULTIPOINT")))
assertthat::assert_that(fun %in% c("mean", "sum"))
if (identical(fun, "mean")) fun2 <- mean
if (identical(fun, "sum")) fun2 <- sum
sf::st_crs(y) <- sf::st_crs(NA_character_)
x@crs <- sp::CRS(NA_character_)
geomc <- geometry_classes(y)
out <- matrix(NA_real_, nrow = nrow(y), ncol = raster::nlayers(x))
point_idx <- grepl("POINT", geomc, fixed = TRUE)
if (any(point_idx)) {
out[point_idx, ] <- as.matrix(raster::extract(
x = x, y = y[point_idx, ], fun = fun2, df = TRUE,
na.rm = FALSE)[, -1, drop = FALSE])
}
line_idx <- grepl("LINE", geomc, fixed = TRUE)
if (any(line_idx)) {
out[line_idx, ] <- as.matrix(raster::extract(
x = x, y = y[line_idx, ], fun = fun2, df = TRUE,
na.rm = FALSE)[, -1, drop = FALSE])
}
poly_idx <- grepl("POLYGON", geomc, fixed = TRUE)
if (any(poly_idx)) {
if (raster::canProcessInMemory(x, n = 1, verbose = FALSE)) {
out[poly_idx, ] <-
rcpp_summarize_exactextractr(exactextractr::exact_extract(
x, y[poly_idx, ], fun = NULL, progress = FALSE),
nrow = sum(poly_idx), ncol = raster::nlayers(x), fun = fun)
} else {
out[poly_idx, ] <-
as.matrix(exactextractr::exact_extract(x, y[poly_idx, ], fun = fun,
progress = TRUE))
}
}
out[abs(out) < 1e-10] <- 0
out
}
) |
library(sf)
library(dplyr)
old_quiet <- getOption("quiet", default=0)
NZ_buffer30 <- hm_get_test("buffer")
test_that("Using s2", {
expect_true(sf_use_s2())
})
test_that("Grid creation", {
options("quiet" = 0)
rg <- make_route_grid(NZ_buffer30, "NZ lat-long at 500km",
target_km = 500, classify = TRUE,
lat_min = -49, lat_max = -32,
long_min = 162, long_max = 182)
expect_equal(rg@name, "NZ lat-long at 500km")
expect_known_value(subset(rg@points, select = -xy),
"known/NZ_500km_grid_points")
expect_known_value(subset(rg@lattice, select = -geometry),
"known/NZ_500km_grid_lattice")
})
test_that("Grid creation messaging", {
options("quiet" = 1)
expect_message(make_route_grid(NZ_buffer30, "NZ lat-long at 300km",
target_km = 300, classify = TRUE,
lat_min = -49, lat_max = -32,
long_min = 162, long_max = 182),
"(lattice)|(Classified)|(Calculated)")
})
options("quiet" = old_quiet) |
.packageName <- 'sindyr'
finite_difference = function(x, S) {
n = length(x)
fdx <- vector(length = n)
fdx[1] = (x[2]-x[1])/S
for (i in 3:(n-1)) {
fdx[i-2] = (x[i] - x[i-2]) / (2*S)
}
fdx[n] = (x[n] - x[n - 1]) / S
return(fdx)
} |
df_raw <- data.frame(a = 1:2, b = 2:3)
varLabels_raw <- data.frame(varName = c("a", "b"), varLabel = c("variable a", "variable b"), stringsAsFactors = FALSE)
valLabels_raw <- data.frame(varName = c("a", "a", "b", "b"), value = c(1, 2, 2, 3), valLabel = c("one", "two", "very", "few"), missings = rep("valid", 4), stringsAsFactors = FALSE)
test_that("Checks for import_raw", {
iris$Species <- as.factor(iris$Species)
expect_error(import_raw(df = iris), "At least one of the variables in df is a factor. All meta information on value level has to be stored in valLabels.")
varLabels_raw_fac <- data.frame(varName = c("a", "b"), varLabel = c("variable a", "variable b"), stringsAsFactors = TRUE)
expect_error(import_raw(df = df_raw, varLabels = varLabels_raw_fac), "One of the variables in varLabels is a factor.")
valLabels_raw <- data.frame(varName = c("a", "a", "b", "b"), value = c(1, 2, 2, 3), valLabel = c("one", "two", "very", "few"), missings = rep("valid", 4))
expect_error(import_raw(df = df_raw, varLabels = varLabels_raw_fac, valLabels = valLabels_raw), "One of the variables in varLabels is a factor.")
expect_error(import_raw(df = df_raw, mtcars), "varLabels needs to contain the variables 'varName' and 'varLabel'.")
expect_error(import_raw(df = df_raw, varLabels_raw, mtcars), "valLabels needs to contain the variables 'varName', 'value', 'valLabel' and 'missings'.")
varLabels_raw_nam <- data.frame(varName = c("a", "d"), varLabel = c("variable a", "variable b"), stringsAsFactors = FALSE)
expect_error(import_raw(df = df_raw, varLabels = varLabels_raw_nam), "The following variables are not in the data df: d")
valLabels_raw_nam <- data.frame(varName = c("a", "d"), value = c(1, 2, 2, 3), valLabel = c("one", "two", "very", "few"), missings = rep("valid", 4), stringsAsFactors = FALSE)
expect_error(import_raw(df = df_raw, varLabels = varLabels_raw, valLabels = valLabels_raw_nam), "The following variables are not in the data df: d")
varLabels_raw_dup <- data.frame(varName = c("a", "b", "a"), varLabel = c("variable a", "variable b", NA), stringsAsFactors = FALSE)
expect_error(import_raw(df = df_raw, varLabels = varLabels_raw_dup), "The following variables have duplicated rows in varLabels: a")
valLabels_raw_miss <- data.frame(varName = c("a", "a", "b", "b"), value = c(1, 2, 2, 3), valLabel = c("one", "two", "very", "few"), missings = rep("vali", 4), stringsAsFactors = FALSE)
expect_error(import_raw(df = df_raw, varLabels = varLabels_raw, valLabels = valLabels_raw_miss), "All values in column 'missings' of valLabels must be either 'valid' or 'miss'.")
})
test_that("import_raw", {
out1 <- import_raw(df = df_raw, varLabels = varLabels_raw)
expect_equal(out1$dat, df_raw)
expect_equal(out1$labels$varLabel, c("variable a", "variable b"))
out <- import_raw(df = df_raw, varLabels = varLabels_raw, valLabels = valLabels_raw)
expect_equal(out$dat, df_raw)
expect_equal(out$labels$varLabel, c(rep("variable a", 2), rep("variable b", 2)))
expect_equal(out$labels$labeled, rep("yes", 4))
df <- data.frame(ID = 1:4, sex = c(0, 0, 1, 1), forename = c("Tim", "Bill", "Ann", "Chris"), stringsAsFactors = FALSE)
varLabels <- data.frame(varName = c("ID", "sex", "forename"), varLabel = c("Person Identifier", "Sex as self reported", "forename provided by teacher"), stringsAsFactors = FALSE)
valLabels <- data.frame(varName = rep("sex", 3), value = c(0, 1, -99), valLabel = c("male", "female", "missing - omission"), missings = c("valid", "valid", "miss"), stringsAsFactors = FALSE)
out2 <- import_raw(df = df, varLabels = varLabels, valLabels = valLabels)
expect_equal(out2$labels$value, c(NA, -99, 0, 1, NA))
expect_equal(out2$labels$valLabel, c(NA, "missing - omission", "male", "female", NA))
expect_equal(out2$labels$labeled, c("no", "yes", "yes", "yes", "no"))
})
test_that("import_raw with tibbles", {
out1 <- import_raw(df = df_raw, varLabels = varLabels_raw, valLabels = valLabels_raw)
df_raw <- tibble::as_tibble(df_raw)
varLabels_raw <- tibble::as_tibble(varLabels_raw)
valLabels_raw <- tibble::as_tibble(valLabels_raw)
out2 <- import_raw(df = df_raw, varLabels = varLabels_raw, valLabels = valLabels_raw)
expect_equal(out1, out2)
}) |
"airy_Ai" <- function(x, mode=0, give=FALSE, strict=TRUE){
x.vec <- as.vector(x)
attr <- attributes(x)
jj <- .C("airy_Ai_e",
as.double(x.vec),
as.integer(length(x.vec)),
as.integer(mode),
val=as.double(x.vec),
err=as.double(x.vec),
status=as.integer(0*x.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_Bi" <- function(x, mode=0, give=FALSE, strict=TRUE){
x.vec <- as.vector(x)
attr <- attributes(x)
jj <- .C("airy_Bi_e",
as.double(x.vec),
as.integer(length(x.vec)),
as.integer(mode),
val=as.double(x.vec),
err=as.double(x.vec),
status=as.integer(0*x.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_Ai_scaled" <- function(x, mode=0, give=FALSE, strict=TRUE){
x.vec <- as.vector(x)
attr <- attributes(x)
jj <- .C("airy_Ai_scaled_e",
as.double(x.vec),
as.integer(length(x.vec)),
as.integer(mode),
val=as.double(x.vec),
err=as.double(x.vec),
status=as.integer(0*x.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_Bi_scaled" <- function(x, mode=0, give=FALSE, strict=TRUE){
x.vec <- as.vector(x)
attr <- attributes(x)
jj <- .C("airy_Bi_scaled_e",
as.double(x.vec),
as.integer(length(x.vec)),
as.integer(mode),
val=as.double(x.vec),
err=as.double(x.vec),
status=as.integer(0*x.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_Ai_deriv" <- function(x, mode=0, give=FALSE, strict=TRUE){
x.vec <- as.vector(x)
attr <- attributes(x)
jj <- .C("airy_Ai_deriv_e",
as.double(x.vec),
as.integer(length(x.vec)),
as.integer(mode),
val=as.double(x.vec),
err=as.double(x.vec),
status=as.integer(0*x.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_Bi_deriv" <- function(x, mode=0, give=FALSE, strict=TRUE){
x.vec <- as.vector(x)
attr <- attributes(x)
jj <- .C("airy_Bi_deriv_e",
as.double(x.vec),
as.integer(length(x.vec)),
as.integer(mode),
val=as.double(x.vec),
err=as.double(x.vec),
status=as.integer(0*x.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_Ai_deriv_scaled" <- function(x, mode=0, give=FALSE, strict=TRUE){
x.vec <- as.vector(x)
attr <- attributes(x)
jj <- .C("airy_Ai_deriv_scaled_e",
as.double(x.vec),
as.integer(length(x.vec)),
as.integer(mode),
val=as.double(x.vec),
err=as.double(x.vec),
status=as.integer(0*x.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_Bi_deriv_scaled" <- function(x, mode=0, give=FALSE, strict=TRUE){
x.vec <- as.vector(x)
attr <- attributes(x)
jj <- .C("airy_Bi_deriv_scaled_e",
as.double(x.vec),
as.integer(length(x.vec)),
as.integer(mode),
val=as.double(x.vec),
err=as.double(x.vec),
status=as.integer(0*x.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_zero_Ai" <- function(n, give=FALSE, strict=TRUE){
n.vec <- as.vector(pmax(n,1))
attr <- attributes(n)
jj <- .C("airy_zero_Ai_e",
as.integer(n.vec),
as.integer(length(n.vec)),
val=as.double(n.vec),
err=as.double(n.vec),
status=as.integer(n.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
val[n<1] <- NA
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_zero_Bi" <- function(n, give=FALSE, strict=TRUE){
n.vec <- as.vector(pmax(n,1))
attr <- attributes(n)
jj <- .C("airy_zero_Bi_e",
as.integer(n.vec),
as.integer(length(n.vec)),
val=as.double(n.vec),
err=as.double(n.vec),
status=as.integer(n.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
val[n<1] <- NA
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_zero_Ai_deriv" <- function(n, give=FALSE, strict=TRUE){
n.vec <- as.vector(pmax(n,1))
attr <- attributes(n)
jj <- .C("airy_zero_Ai_deriv_e",
as.integer(n.vec),
as.integer(length(n.vec)),
val=as.double(n.vec),
err=as.double(n.vec),
status=as.integer(n.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
val[n<1] <- NA
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
}
"airy_zero_Bi_deriv" <- function(n, give=FALSE, strict=TRUE){
n.vec <- as.vector(pmax(n,1))
attr <- attributes(n)
jj <- .C("airy_zero_Bi_deriv_e",
as.integer(n.vec),
as.integer(length(n.vec)),
val=as.double(n.vec),
err=as.double(n.vec),
status=as.integer(n.vec),
PACKAGE="gsl"
)
val <- jj$val
err <- jj$err
status <- jj$status
attributes(val) <- attr
attributes(err) <- attr
attributes(status) <- attr
if(strict){
val <- strictify(val,status)
}
val[n<1] <- NA
if(give){
return(list(val=val,err=err,status=status))
} else {
return(val)
}
} |
toXML2_images = function(images, verbose = FALSE, display_progress = TRUE, title_progress = "") {
assert(verbose, alw = c(TRUE, FALSE))
if(verbose) message("creating images node")
assert(images, cla = "IFC_images")
bgm = grep("^bgmean", names(images))
bgs = grep("^bgstd", names(images))
satc = grep("^satcount", names(images))
satp = grep("^satpercent", names(images))
lapply(1:nrow(images), FUN=function(i) {
xml_new_node(name = "SO",
attrs = c("id" = num_to_string(images[i, "id"]),
"imgIFD" = num_to_string(images[i, "imgIFD"]),
"mskIFD" = num_to_string(images[i, "mskIFD"]),
"spIFD" = num_to_string(images[i, "spIFD"]),
"w" = num_to_string(images[i, "w"]),
"l" = num_to_string(images[i, "l"]),
"fs" = num_to_string(images[i, "fs"]),
"cl" = num_to_string(images[i, "cl"]),
"ct" = num_to_string(images[i, "ct"]),
"objCenterX" = num_to_string(images[i, "objCenterX"]),
"objCenterY" = num_to_string(images[i, "objCenterY"]),
"bgmean" = paste0(num_to_string(unlist(images[i, bgm])), collapse = "|"),
"bgstd" = paste0(num_to_string(unlist(images[i, bgs])), collapse = "|"),
"satcount" = paste0(num_to_string(unlist(images[i, satc])), collapse = "|"),
"satpercent" = paste0(num_to_string(unlist(images[i, satp])), collapse = "|")))
})
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.