code
stringlengths 1
13.8M
|
---|
LR2 <- function (g1, g2, n.num, n.den=n.num, p, M, kappa.num, kappa.den=c(1,0,0),
alpha, theta=0, silent=FALSE, beta=0.5){
num <- lik2(g1, g2, n=n.num, p, M, kappa.num, alpha, theta, beta)
den <- lik2(g1, g2, n=n.den, p, M, kappa.den, alpha, theta, beta)
if(silent){
homo1 <- g1[1]==g1[2]
homo2 <- g2[1]==g2[2]
S <- length(p)
if(homo1 & !homo2){
num <- num+lik2(c(g1[1],S), g2, n=n.num, p, M, kappa.num, alpha, theta, beta)
den <- den+lik2(c(g1[1],S), g2, n=n.den, p, M, kappa.den, alpha, theta, beta)
}
if(!homo1 & homo2){
num <- num+lik2(g1, c(g2[1],S), n=n.num, p, M, kappa.num, alpha, theta, beta)
den <- den+lik2(g1, c(g2[1],S), n=n.den, p, M, kappa.den, alpha, theta, beta)
}
if(homo1 & homo2){
num <- num+lik2(c(g1[1],S), g2, n=n.num, p, M, kappa.num, alpha, theta, beta)+
lik2(g1, c(g2[1],S), n=n.num, p, M, kappa.num, alpha, theta, beta)+
lik2(c(g1[1],S), c(g2[1],S), n=n.num, p, M, kappa.num, alpha, theta, beta)
den <- den+lik2(c(g1[1],S), g2, n=n.den, p, M, kappa.den, alpha, theta, beta)+
lik2(g1, c(g2[1],S), n=n.den, p, M, kappa.den, alpha, theta, beta)+
lik2(c(g1[1],S), c(g2[1],S), n=n.den, p, M, kappa.den, alpha, theta, beta)
}
}
LR <- num/den
list(numerator=num, denominator=den, LR=LR)
} |
.__JOB_REGISTRY__. <- new.env(parent = emptyenv())
"_PACKAGE" |
plot.tfer = function(x,
ptype = c("density", "freq", "hist"),
xlab = "n",
main = "",
col = "red",
...) {
if (is.numeric(ptype)) {
ptype = switch(ptype + 1, "d", "f", "h")
warning(
"This usage is deprecated. Please use ptype = \"density\", ptype = \"freq\", or ptype = \"hist\" in the future"
)
}
ptype = match.arg(ptype)
if (ptype == "density") {
probs = tprob(x)
nmax = length(probs) - 1
b = barplot(
probs,
xlab = xlab,
ylab = "Probability",
main = main,
col = col,
names.arg = FALSE,
xaxs = "i",
yaxs = "i",
ylim = c(0, max(probs) * 1.05),
axes = FALSE,
...
)
axis(2)
axis(
1,
at = c(b[1], b[nmax + 1]),
tick = FALSE,
labels = c(0, nmax)
)
box()
} else if (ptype == "freq") {
v = getValues(x)
m = max(v)
counts = tabulate(v + 1, m + 1)
nmax = length(counts) - 1
b = barplot(
counts,
xlab = xlab,
ylab = "Frequency",
main = main,
col = col,
names.arg = FALSE,
xaxs = "i",
yaxs = "i",
ylim = c(0, ceiling(max(counts) * 1.05)),
axes = FALSE,
...
)
axis(2)
axis(
1,
at = c(b[1], b[nmax + 1]),
tick = FALSE,
labels = c(0, nmax)
)
box()
} else {
hist(getValues(x),
xlab = xlab,
col = col,
main = main,
...)
}
} |
test_that("check whether the simulation recordes are outputted as required",{
data(en.vir)
data<-data.frame(species=rep("Acosmeryx anceus",3),
Lon=c(145.380,145.270,135.461),
Lat=c(-16.4800,-5.2500,-16.0810))
absent.points<-pseudo.absent.points(data,en.vir=en.vir,outputNum=100)
expect_equal(nrow(absent.points$lonlat),100)
expect_equal(nrow(absent.points$envir),100)
})
test_that("test the expect error throwed when matching bad format",{
data(en.vir)
data<-data.frame(species=rep("Acosmeryx anceus",3),
Lon=c(145.380,145.270,135.461))
expect_error(pseudo.absent.points(data,en.vir=en.vir,outputNum=100))
}) |
test_that("compareModelResults() works", {
kwb.hantush:::compareModelResults()
}) |
checkParms <- function(mod, se.max = 25, simplify = TRUE, ...) {
UseMethod("checkParms", mod)
}
checkParms.default <- function(mod, se.max = 25, simplify = TRUE, ...) {
stop("\nFunction not yet defined for this object class\n")
}
checkParms.unmarkedFit <- function(mod, se.max = 25, simplify = TRUE, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
parm.names <- sapply(var.names, FUN = function(i) unlist(strsplit(i, split = "\\("))[1], simplify = TRUE)
parm.id <- unique(parm.names)
matSE <- data.frame(SEs = SEs, variable = var.names, parameter = parm.names)
if(identical(simplify, TRUE)) {
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
parmSE <- as.character(matSE[which(matSE$variable == nameSE), "parameter"])
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
parmSE <- as.character(matSE[which(matSE$SEs == maxSE), "parameter"])
}
rownames(out.result) <- parmSE
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
}
if(identical(simplify, FALSE)) {
out.result <- data.frame(variable = rep(NA, length(parm.id)),
max.se = rep(NA, length(parm.id)),
n.high.se = rep(NA, length(parm.id)))
rownames(out.result) <- parm.id
for(j in parm.id) {
mat.parm <- matSE[matSE$parameter %in% j, ]
maxSE <- max(mat.parm$SEs)
out.result[j, "max.se"] <- maxSE
nameSE <- as.character(mat.parm[which(mat.parm$SEs == maxSE), "variable"])
if(is.nan(maxSE)) {
nan.var <- as.character(mat.parm[is.nan(mat.parm$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
}
out.result[j, "variable"] <- nameSE
out.result[j, "n.high.se"] <- length(which(mat.parm$SEs > se.max))
}
}
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.betareg <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.clm <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.clmm <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.coxme <- function(mod, se.max = 25, ...) {
SEs <- extractSE(mod)
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.coxph <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.glm <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.glmmTMB <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)$cond))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.gls <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.gnls <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.hurdle <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.lm <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.lme <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.lmekin <- function(mod, se.max = 25, ...) {
SEs <- extractSE(mod)
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.maxlikeFit <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.merMod <- function(mod, se.max = 25, ...) {
SEs <- extractSE(mod)
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.lmerModLmerTest <- function(mod, se.max = 25, ...) {
SEs <- extractSE(mod)
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.multinom <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.nlme <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.nls <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.polr <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.rlm <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.survreg <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.vglm <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
checkParms.zeroinfl <- function(mod, se.max = 25, ...) {
SEs <- sqrt(diag(vcov(mod)))
var.names <- names(SEs)
matSE <- data.frame(SEs = SEs, variable = var.names)
out.result <- data.frame(variable = rep(NA, 1),
max.se = rep(NA, 1),
n.high.se = rep(NA, 1))
maxSE <- max(SEs)
if(is.nan(maxSE)) {
nan.var <- as.character(matSE[is.nan(matSE$SEs), "variable"])
if(length(nan.var) == 1) {
nameSE <- nan.var
} else {nameSE <- nan.var[1]}
} else {
nameSE <- as.character(matSE[which(matSE$SEs == maxSE), "variable"])
}
rownames(out.result) <- "beta"
out.result[, "variable"] <- nameSE
out.result[, "max.se"] <- maxSE
out.result[, "n.high.se"] <- length(which(matSE$SEs > se.max))
out <- list(model.class = class(mod), se.max = se.max, result = out.result)
class(out) <- "checkParms"
return(out)
}
print.checkParms <- function(x, digits = 2, ...) {
out.frame <- x$result
out.frame$max.se <- round(out.frame$max.se, digits = digits)
print(out.frame)
} |
matching <- function(z, score, replace=FALSE){
n <- length(score)
nt <- sum(z)
nc <- sum(1-z)
ind.t <- c(1:n)[z==1]
ind.c <- c(1:n)[z==0]
cnts <- rep(0, n)
cnts[z==1] = rep(1,nt)
scorec <- score[z == 0]
scoret <- score[z == 1]
if (replace){
dist = abs(outer(scoret,scorec,FUN="-"))
mins = apply(dist,1,min)
matches = dist - mins
matches[matches!=0] = 1
matches = 1 - matches
if(sum(matches)>nt){
for(i in c(1:nt)[apply(matches,1,sum)>1]){
matches_i <- c(1:nc)[matches[i,]==1]
nmi <- length(matches_i)
matches[i,matches_i] <- sample(c(1,rep(0,nmi-1)),nmi,replace=FALSE)
}
}
ind.cm <- matches %*% ind.c
cnts[z==0] <- apply(matches,2,sum)
match.ind <- c(ind.t, ind.cm)
out <- list(match.ind = match.ind, cnts = cnts, matches = matches)
}
if (!replace){
pairs = rep(NA,n)
match.ind <- rep(0, n)
tally <- 0
for (i in ind.t) {
available <- (1:n)[(z == 0) & (match.ind == 0)]
j <- available[order(abs(score[available] - score[i]))[1]]
cnts[j] <- 1
match.ind[i] <- j
match.ind[j] <- i
tally <- tally + 1
pairs[c(i, j)] <- tally
}
out <- list(match.ind = match.ind, cnts = cnts, pairs = pairs)
}
return(out)
} |
IF.lmer = function(
full, data, B = 100, REML = TRUE, method = c("marginal", "conditional"),
cpus = parallel::detectCores(), lftype = c("abscoef", "tvalue")) {
lme4 <- NULL
rm(lme4)
method = match.arg(method)
if (method == "marginal") {
if(lftype =="abscoef") {
return(IF.lm(full, data, B, lftype ="abscoef", cpus))
}else{
return(IF.lm(full, data, B, lftype ="pvalue", cpus))
}
}
mf = function(formula, data) lmer(formula, data, REML = REML)
lftype = match.arg(lftype)
lf = switch(lftype,
abscoef = function(res) abs(fixef(res))[-1],
tvalue = function(res) abs(summary(res)$coefficients[-1,3]))
bs = bootstrap.lmer(B, full, data, REML)
sfInit(parallel = TRUE, cpus = cpus)
sfExportAll()
sfLibrary(lme4)
invisiblefence_old(mf, full, data, lf, bs)
} |
ISRaD.getdata <- function(directory, dataset = "full", extra = FALSE, force_download = FALSE) {
dataURL <- "https://github.com/International-Soil-Radiocarbon-Database/ISRaD/raw/master/ISRaD_data_files/database/ISRaD_database_files.zip"
if (!dataset %in% c("full", "flux", "interstitial", "incubation", "fraction", "layer")) {
stop('Dataset parameter not recognized. Options are c("full", "flux", "interstitial", "incubation", "fraction", "layer")')
}
if (!"ISRaD_database_files" %in% list.files(directory)) {
message("\n ISRaD_database_files not found...")
message("\n Downloading database files from: ", dataURL, "\n")
download.file(dataURL, file.path(directory, "ISRaD_database_files.zip"))
message("\n Unzipping database files to", file.path(directory, "ISRaD_database_files"), "...\n")
unzip(file.path(directory, "ISRaD_database_files.zip"), exdir = file.path(directory, "ISRaD_database_files"))
}
if (force_download) {
message("\n Replacing ISRaD_database_files ...")
message("\n Downloading database files from: ", dataURL, "\n")
download.file(dataURL, file.path(directory, "ISRaD_database_files.zip"))
message("\n Removing old database files in ", file.path(directory, "ISRaD_database_files"), "...\n")
reviewed <- menu(c("Yes", "No"), title = "Are you sure you want to replace these with the newest version? You can copy them to a new directory now if you want keep them.")
print(reviewed)
if (reviewed == 1) {
for (f in list.files(file.path(directory, "ISRaD_database_files"), full.names = TRUE)) {
file.remove(f)
}
} else {
stop("Ok, keeping the old files. You can run again without force_download=T to load.")
}
message("\n Unzipping database files to ", file.path(directory, "ISRaD_database_files"), "...\n")
unzip(file.path(directory, "ISRaD_database_files.zip"), exdir = file.path(directory, "ISRaD_database_files"))
}
database_files <- list.files(file.path(directory, "ISRaD_database_files"), full.names = TRUE)
if (extra) {
data_type <- "ISRaD_extra_"
} else {
data_type <- "ISRaD_data_"
}
if (dataset != "full") {
file <- database_files[intersect(grep(data_type, database_files), grep(dataset, database_files))]
v <- gsub(".+_(v.+)\\..+", "\\1", file)
data <- read.csv(file)
attributes(data)$version <- v
message("\n Loading ", file, "\n")
message("\n This data is from ISRaD ", attributes(data)$version, "\n")
}
if (dataset == "full") {
file <- database_files[intersect(grep(data_type, database_files), grep(".rda", database_files))]
data <- load(file)
data <- get(data)
message("\n Loading ", file, "\n")
message("\n This data is from ISRaD ", attributes(data)$version, "\n")
}
return(data)
} |
context("check that BioCro output is summarized correctly")
ref_output <- mock_run()
ref_met <- read.csv("data/US-Bo1.2004.csv", nrows=7*24)
ref_leaf1 <- max(ref_output$Leaf[ref_output$DayofYear == 1])
ref_soil5 <- sum(ref_output$SoilEvaporation[ref_output$DayofYear == 5])
ref_mat <- mean(ref_met$Temp)
metpath <- "data/US-Bo1"
settings <- PEcAn.settings::read.settings("data/pecan.biocro.xml")
settings$database$bety <- do.call(
PEcAn.DB::get_postgres_envvars,
settings$database$bety)
config <- PEcAn.settings::prepare.settings(settings)
config$pft$type$genus <- "Salix"
config$run$start.date <- as.POSIXct("2004-01-01")
config$run$end.date <- as.POSIXct("2004-01-07")
config$simulationPeriod$dateofplanting <- as.POSIXct("2004-01-01")
config$simulationPeriod$dateofharvest <- as.POSIXct("2004-01-07") |
roxy_tag_parse.roxy_tag_md <- function(x) tag_toggle(x)
roxy_tag_parse.roxy_tag_noMd <- function(x) tag_toggle(x)
markdown_env <- new.env(parent = emptyenv())
markdown_on <- function(value = NULL) {
if (!is.null(value)) {
assign("markdown-support", isTRUE(value), envir = markdown_env)
}
return(isTRUE(markdown_env$`markdown-support`))
}
markdown_activate <- function(tags) {
names <- purrr::map_chr(tags, "tag")
has_md <- "md" %in% names
has_nomd <- "noMd" %in% names
if (has_md && has_nomd) {
roxy_tag_warning(tags[[1]], "Both @md and @noMd, no markdown parsing")
}
md <- roxy_meta_get("markdown", FALSE)
if (has_md) md <- TRUE
if (has_nomd) md <- FALSE
markdown_on(md)
} |
ISIranks <- function(x, sortbyID = TRUE) {
foo <- function(X) data.frame(id = colnames(X),
ISIrank = 1:length(colnames(X)))
temp <- lapply(X = x, FUN = foo)
temp <- lapply(temp, function(X) X[order(X[, 1]), ] )
res <- data.frame(ID = temp[[1]][, 1], avg = NA)
for (i in 1:length(temp)) {
res <- cbind(res, temp[[i]][, 2])
colnames(res)[ncol(res)] <- paste0("rnkg", i)
}
res$avg <- rowMeans(res[, 3:ncol(res), drop = FALSE])
if (!sortbyID) res <- res[order(res$avg), ]
rownames(res) <- NULL
return(res)
} |
context("LITO")
test_that("Error handling", {
expect_error(lito(30e3, max_lito = c(445, 450)))
expect_error(lmito(30e3, fy.year = "2011-12"),
regexp = "fy.year.*Only these values are supported")
})
test_that("LITO", {
expect_equal(lito(income = c(25e3, 30e3),
max_lito = c(400, 500),
lito_taper = c(0.015, 0.015),
min_bracket = c(37000, 37000)),
c(400, 500))
expect_equal(lito(30e3, max_lito = 445, min_bracket = 37000),
445)
expect_equal(lito(38000, max_lito = 1000, min_bracket = 37000, lito_taper = 0.5),
500)
})
test_that("LMITO", {
expect_equal(lmito(income = seq(30e3, 130e3, 10e3),
fy.year = "2018-19"),
c(200, 290, 530, 530, 530, 530, 530, 380, 230, 80, 0))
expect_equal(lmito(income = seq(30e3, 130e3, 10e3),
fy.year = "2019-20",
first_offset = 255,
thresholds = c(37e3, 48e3, 90e3, 126e3),
taper = c(0, 0.075, 0, -0.03)),
c(255, 480, 1080, 1080, 1080, 1080, 1080, 780, 480, 180, 0)
)
})
test_that("WATR: ALP Budget Reply 2018", {
expect_equal(watr(seq(20e3, 120e3, by = 5e3)),
c(000, 350,
350, 350,
508, 770,
928, 928,
928, 928,
928, 928,
928, 928,
928, 796,
665, 534,
402, 271,
140),
tolerance = 2)
}) |
context("DAISIE_sim_core_constant_rate")
test_that("Clean run should be silent", {
set.seed(42)
n_mainland_species <- 1
sim_time <- 10
clado_rate <- 1.0
ext_rate <- 0.1
carr_cap <- 4
imm_rate <- 1.0
ana_rate <- 1.0
area_pars <- DAISIE::create_area_pars(
max_area = 1,
current_area = 1,
proportional_peak_t = 0,
total_island_age = 0,
sea_level_amplitude = 0,
sea_level_frequency = 0,
island_gradient_angle = 0)
hyper_pars <- create_hyper_pars(d = 0, x = 0)
nonoceanic_pars <- c(0, 0)
expect_silent(
DAISIE:::DAISIE_sim_core_constant_rate(
time = sim_time,
mainland_n = n_mainland_species,
pars = c(clado_rate, ext_rate, carr_cap, imm_rate, ana_rate),
area_pars = area_pars,
hyper_pars = hyper_pars,
nonoceanic_pars = nonoceanic_pars
)
)
})
test_that("A non-oceanic run with non-zero sampling should have native
species on the island", {
area_pars <- DAISIE::create_area_pars(
max_area = 1,
current_area = 1,
proportional_peak_t = 0,
total_island_age = 0,
sea_level_amplitude = 0,
sea_level_frequency = 0,
island_gradient_angle = 0)
hyper_pars <- create_hyper_pars(d = 0, x = 0)
nonoceanic_sim <- DAISIE:::DAISIE_sim_core_constant_rate(
time = 0.4,
mainland_n = 1000,
pars = c(
2.550687345,
2.683454548,
10.0,
0.00933207,
1.010073119),
area_pars = area_pars,
hyper_pars = hyper_pars,
nonoceanic_pars = c(0.1, 0.9)
)
expect_gt(nonoceanic_sim$stt_table[1, 2], 0)
expect_gt(nonoceanic_sim$stt_table[1, 3], 0)
})
test_that("DAISIE_sim_core output is correct", {
time <- 1
mainland_n <- 100
set.seed(5)
area_pars <- DAISIE::create_area_pars(
max_area = 1,
current_area = 1,
proportional_peak_t = 0,
total_island_age = 0,
sea_level_amplitude = 0,
sea_level_frequency = 0,
island_gradient_angle = 0)
nonoceanic_pars <- c(0, 0)
hyper_pars <- create_hyper_pars(d = 0, x = 0)
sim_core <- DAISIE:::DAISIE_sim_core_constant_rate(
time = time,
mainland_n = mainland_n,
pars = c(2, 2, 20, 0.1, 1),
area_pars = area_pars,
hyper_pars = hyper_pars,
nonoceanic_pars = nonoceanic_pars
)
expect_true(is.matrix(sim_core$stt_table))
expect_true(sim_core$stt_table[1, 1] == time)
expect_true(sim_core$stt_table[nrow(sim_core$stt_table), 1] == 0)
expect_true(is.numeric(sim_core$taxon_list[[1]]$branching_times))
expect_true(is.numeric(sim_core$taxon_list[[1]]$stac))
expect_true(is.numeric(sim_core$taxon_list[[1]]$missing_species))
expect_true(length(sim_core$taxon_list) == 2)
expect_true("branching_times" %in% names(sim_core$taxon_list[[1]]))
expect_true("stac" %in% names(sim_core$taxon_list[[1]]))
expect_true("missing_species" %in% names(sim_core$taxon_list[[1]]))
})
test_that("DAISIE_sim_core with land-bridge starting at time = 0 for CS uses
the second parameter set at time = 0", {
area_pars <- DAISIE::create_area_pars(
max_area = 1,
current_area = 1,
proportional_peak_t = 0,
total_island_age = 0,
sea_level_amplitude = 0,
sea_level_frequency = 0,
island_gradient_angle = 0)
hyper_pars <- create_hyper_pars(d = 0, x = 0)
expect_silent(
DAISIE:::DAISIE_sim_core_constant_rate_shift(
time = 10,
mainland_n = 1,
pars = c(1, 1, 10, 0.1, 1, 2, 2, 20, 0.2, 1),
shift_times = 10,
area_pars = area_pars,
hyper_pars = hyper_pars
)
)
})
test_that("DAISIE_sim_core fails when pars[4] == 0 &&
nonoceanic_pars[1] == 0", {
area_pars <- DAISIE::create_area_pars(
max_area = 1,
current_area = 1,
proportional_peak_t = 0,
total_island_age = 0,
sea_level_amplitude = 0,
sea_level_frequency = 0,
island_gradient_angle = 0)
nonoceanic_pars <- c(0, 0)
hyper_pars <- create_hyper_pars(d = 0, x = 0)
expect_error(
DAISIE:::DAISIE_sim_core_constant_rate(
time = 1,
mainland_n = 100,
pars = c(2, 2, 20, 0, 1),
area_pars = area_pars,
hyper_pars = hyper_pars,
nonoceanic_pars = nonoceanic_pars
)
)
}) |
test_that("return_results() works when $ego is `srvyr` object", {
x <- make_egor(5, 32)
x$ego$sampling_weight <- sample(1:10/10, 5, replace = TRUE)
ego_design(x) <- list(weight = "sampling_weight")
res <- composition(x, age)
res <- res$variables
expect_error(egor:::return_results(x, res), NA)
})
test_that("return_results() works when $ego is NOT a `srvyr` object", {
x <- make_egor(5, 32)
res <- composition(x, age)
expect_error(egor:::return_results(x, res), NA)
}) |
dtt_feb29_to_28 <- function(x) {
if (!vld_s3_class(x, "Date") && !vld_s3_class(x, "POSIXct")) {
chkor_vld(vld_s3_class(x, "Date"), vld_s3_class(x, "POSIXct"))
}
wch <- which(dtt_month(x) == 2L & dtt_day(x) == 29L)
dtt_day(x[wch]) <- 28L
x
} |
fuzzy.GK<- function(X,
K,
m,
gamma,
rho,
max.iteration,
threshold,
member.init,
RandomNumber=0,
print.result=0)
{
if(missing(X))
return("Data Unknown\n")
if(missing(K)||K<2||!is.numeric(K))
{
K<-2
cat("Default K=2\n")
}
if(missing(gamma)){
gamma<-0
cat("Default Gamma (0) will be used\n")
}
if(missing(rho)){
rho<-rep(1,K)
cat("Default rho will be used\n")
}
if(missing(m)||m<1||!is.numeric(m))
{
m<-1.5
cat("Fuzzyfier unidentified/error/less than 1. Default Fuzzyfier (1.5) will be used.\n")
}
if(missing(max.iteration)||!is.numeric(max.iteration))
{
max.iteration<-1000
cat("Maximum Iteration 1000 will be used.\n")
}
if(missing(threshold)||!is.numeric(threshold))
{
threshold<-1e-9
cat("Default threshold 1e-9 will be used.\n")
}
data.X <- as.matrix(X)
n <- nrow(data.X)
p <- ncol(data.X)
if(missing(member.init))
{
if (RandomNumber <= 0 || !is.numeric(RandomNumber))
{
member.init<-membership(K=K,n=n)
} else
member.init<-membership(K=K,n=n,RandomNumber = RandomNumber)
} else if(!is.membership(member.init))
{
member.init<-as.matrix(member.init)
if(ncol(member.init)!=K ||
nrow(member.init)!=n)
{
cat("Membership not applicable with other parameter")
if (RandomNumber <= 0 || !is.numeric(RandomNumber))
{
member.init<-membership(K=K,n=n)
} else
member.init<-membership(K=K,n=n,RandomNumber = RandomNumber)
} else member.init<-membership(member.init,K=K,n=n)
} else
{
if(ncol(member(member.init))!=K||nrow(member(member.init))!=n)
{
cat("Membership not applicable with other parameter")
if (RandomNumber <= 0 || !is.numeric(RandomNumber))
{
member.init<-membership(K=K,n=n)
} else
member.init<-membership(K=K,n=n,RandomNumber = RandomNumber)
} else
member.init<-as.membership(member.init)
}
U<-member(member.init)
V <- matrix(0,K,p)
D <- matrix(0,n,K)
F <- array(0,c(p,p,K))
iteration<-1
cat("\n")
repeat{
cat("\r",paste("iteration:\t",iteration))
U.old <- U
D.old <-D
V.old<-V
V <- t(U ^ m) %*% data.X / colSums(U ^ m)
for (k in 1:K)
{
F[,,k] = as.matrix(0,p,p)
F.bantu <- F[,,k]
for (i in 1:n)
{
F.bantu = (U[i,k] ^ m) * (data.X[i,] - V[k,]) %*% t((data.X[i,] - V[k,]))+F.bantu
}
F.bantu = F.bantu / sum(U[,k] ^ m)
F.bantu = (1 - gamma) * F.bantu + (gamma * (det(cov(data.X))) ^ (1 / p)) * diag(p)
if (kappa(F.bantu) > 10 ^ 15)
{
eig <- eigen(F.bantu)
eig.values <- eig$values
eig.vec <- eig$vectors
eig.val.max <- max(eig.values)
eig.values[eig.values*( 10 ^ 15 ) < eig.val.max]=eig.val.max/ ( 10 ^ 15)
F.bantu = eig.vec %*% diag(eig.values) %*% solve(eig.vec)
}
detMat= det(F.bantu)
for (i in 1:n)
{
D[i,k] = t(data.X[i,] - V[k,]) %*% (
(rho[k] * (detMat ^ (1 / p)))*ginv(F.bantu,tol=0)) %*% (data.X[i,] -V[k,])
}
}
for (i in 1:n)
{
U[i,] <- 1 /
(((D[i,]) ^ (1 / (m - 1))) *
sum((1 / (D[i,])) ^ (1 /(m - 1))))
}
if(any(is.na(U))==T||any(is.infinite(U))==T)
{
U<-U.old
V<-V.old
D<-D.old
}
for (i in 1:n)
for (k in 1:K) {
if (U[i,k] < 0)
U[i,k] = 0
else if (U[i,k] > 1)
U[i,k] = 1
}
func.obj = sum(U ^ m * D)
iteration = iteration + 1
if((max(abs(U.old - U)) <= threshold) ||
(iteration > max.iteration))
break
}
rownames(U)<-rownames(X)
label<-apply(U, 1,
function(x) which.max(x))
result<-new("fuzzycluster",
member=U,
centroid=V,
func.obj=func.obj,
distance=D,
hard.label=label,
call.func=as.character(deparse(match.call())),
fuzzyfier=m,
method.fuzzy="Gustafson Kessel Clustering"
)
cat("\nFinish :)\n")
if(print.result==1)
show(result)
return(result)
} |
make_window_reg <- function() {
parsnip::set_new_model("window_reg")
parsnip::set_model_mode("window_reg", "regression")
parsnip::set_model_engine("window_reg", mode = "regression", eng = "window_function")
parsnip::set_dependency("window_reg", eng = "window_function", pkg = "modeltime")
parsnip::set_model_arg(
model = "window_reg",
eng = "window_function",
parsnip = "id",
original = "id",
func = list(pkg = "modeltime", fun = "id"),
has_submodel = FALSE
)
parsnip::set_model_arg(
model = "window_reg",
eng = "window_function",
parsnip = "window_size",
original = "window_size",
func = list(pkg = "dials", fun = "window_size"),
has_submodel = FALSE
)
parsnip::set_encoding(
model = "window_reg",
eng = "window_function",
mode = "regression",
options = list(
predictor_indicators = "none",
compute_intercept = FALSE,
remove_intercept = FALSE,
allow_sparse_x = FALSE
)
)
parsnip::set_fit(
model = "window_reg",
eng = "window_function",
mode = "regression",
value = list(
interface = "data.frame",
protect = c("x", "y"),
func = c(fun = "window_function_fit_impl"),
defaults = list()
)
)
parsnip::set_pred(
model = "window_reg",
eng = "window_function",
mode = "regression",
type = "numeric",
value = list(
pre = NULL,
post = NULL,
func = c(fun = "predict"),
args =
list(
object = rlang::expr(object$fit),
new_data = rlang::expr(new_data)
)
)
)
} |
test_that("Caching works", {
schedule_1 <- get_retrosheet("schedule", 1995, cache = "testdata")
schedule_1a <- get_retrosheet("schedule", 1995, cache = "testdata/")
roster_1 <- get_retrosheet("roster", 1995, cache = "testdata")
game_1 <- get_retrosheet("game", 2012, cache = "testdata")
play_1 <- get_retrosheet("play", 2012, "SFN", cache = "testdata")
schedule_2 <- get_retrosheet("schedule", 1995)
roster_2 <- get_retrosheet("roster", 1995)
game_2 <- get_retrosheet("game", 2012)
play_2 <- get_retrosheet("play", 2012, "SFN")
expect_equal(schedule_1, schedule_2)
expect_equal(schedule_1, schedule_1a)
expect_equal(roster_1, roster_2)
expect_equal(game_1, game_2)
expect_equal(play_1, play_2)
expect_message(get_retrosheet("schedule", 1995, cache = "testdata"), "Using local cache: testdata/schedule/1995SKED.ZIP")
})
test_that("Schedule downloading works", {
schedule <- get_retrosheet(type = "schedule", year = 1995, cache = "testdata")
schedule_unnamed <- get_retrosheet("schedule", 1995, cache = "testdata")
schedule_splits <- get_retrosheet(type = "schedule", year = 1995, schedSplit = "TimeOfDay")
schedule_splits_some_named <- get_retrosheet("schedule", 1995, schedSplit = "TimeOfDay")
expect_equal(nrow(schedule), 2016)
expect_equal(schedule_splits, schedule_splits_some_named)
expect_equal(length(schedule_splits), 3)
expect_equal(nrow(schedule_splits[[3]]), 1355)
expect_equal(sum(unlist(lapply(schedule_splits, nrow), recursive = TRUE)), nrow(schedule))
expect_equal(schedule, schedule_unnamed)
})
test_that("Roster downloading works", {
roster <- get_retrosheet("roster", 1995, cache = "testdata")
expect_equal(length(roster), 28)
expect_equal(nrow(roster[[1]]), 40)
expect_equal(nrow(roster$TOR), 39)
})
test_that("Game downloading works", {
game <- get_retrosheet("game", 2012, cache = "testdata")
expect_equal(length(game), 161)
expect_equal(nrow(game), 2430)
})
test_that("Play downloading works", {
play <- get_retrosheet("play", 2012, "SFN", cache = "testdata")
expect_equal(length(play), 81)
expect_equal(nrow(play[[1]]$play), 68)
expect_equal(nrow(play[[1]]$sub), 4)
expect_equal(nrow(play[[1]]$start), 18)
expect_equal(nrow(play[[1]]$info), 26)
})
test_that("Data is cleaned up as expected", {
game <- get_retrosheet("game", 2012, cache = "testdata")
expect_true("data.frame" %in% class(game))
expect_equal(class(game$Date), "Date")
expect_false(any(game$Completion == "", na.rm = TRUE))
expect_false(any(game$Forfeit == "", na.rm = TRUE))
expect_false(any(game$Protest == "", na.rm = TRUE))
schedule <- get_retrosheet(type = "schedule", year = 1995, cache = "testdata")
expect_true("data.frame" %in% class(schedule))
expect_equal(class(schedule$Date), "Date")
expect_equal(class(schedule$GameNo), "integer")
expect_warning(
get_retrosheet("schedule", 1995, schedSplit = "TimeOfDay", stringsAsFactors = TRUE, cache = "testdata")
)
})
unlink("testdata", recursive = TRUE) |
Make_main_bar_legend_t <- function(Main_bar_data, Q, show_num, ratios, customQ, number_angles,
ebar, ylabel, ymax, scale_intersections, text_scale, attribute_plots,
treatment_var, fill.trt){
bottom_margin <- (-1)*0.65
if(is.null(attribute_plots) == FALSE){
bottom_margin <- (-1)*0.45
}
if(length(text_scale) > 1 && length(text_scale) <= 6){
y_axis_title_scale <- text_scale[1]
y_axis_tick_label_scale <- text_scale[2]
intersection_size_number_scale <- text_scale[6]
}
else{
y_axis_title_scale <- text_scale
y_axis_tick_label_scale <- text_scale
intersection_size_number_scale <- text_scale
}
if(is.null(Q) == F){
inter_data <- Q
if(nrow(inter_data) != 0){
inter_data <- inter_data[order(inter_data$x), ]
}
else{inter_data <- NULL}
}
else{inter_data <- NULL}
if(is.null(ebar) == F){
elem_data <- ebar
if(nrow(elem_data) != 0){
elem_data <- elem_data[order(elem_data$x), ]
}
else{elem_data <- NULL}
}
else{elem_data <- NULL}
Main_bar_data_all = data.frame(x= sort(unique(Main_bar_data$x)),
freq = tapply(Main_bar_data$freq, Main_bar_data$x, FUN=sum))
if(is.null(ymax) == T){
ten_perc <- ((max(Main_bar_data$freq)) * 0.1)
ymax <- max(Main_bar_data_all$freq) + ten_perc
}
if(ylabel == "Intersection Size" && scale_intersections != "identity"){
ylabel <- paste("Intersection Size", paste0("( ", scale_intersections, " )"))
}
if(scale_intersections == "log2"){
Main_bar_data$freq <- round(log2(Main_bar_data$freq), 2)
ymax <- log2(ymax)
}
if(scale_intersections == "log10"){
Main_bar_data$freq <- round(log10(Main_bar_data$freq), 2)
ymax <- log10(ymax)
}
Main_bar_data$x = max(Main_bar_data$x) - Main_bar_data$x +1
Main_bar_data_all$x = max(Main_bar_data_all$x) - Main_bar_data_all$x + 1
if (fill.trt){
Main_bar_data$trt = as.factor(Main_bar_data$trt)
Main_bar_plot <- (ggplot(data = Main_bar_data, aes_string(x = "x", y = "freq"))
+ geom_bar(aes_string(fill = "trt"), stat = "identity", width = 0.6)
+ scale_fill_manual(values = c("
} else{
Main_bar_plot <- (ggplot(data = Main_bar_data, aes_string(x = "x", y = "freq"))
+ geom_bar(stat = "identity", width = 0.6))
}
Main_bar_plot <- (Main_bar_plot
+ scale_y_continuous(trans = scale_intersections,
position = "right",
expand = c(0,0))
+ coord_flip(ylim = c(0,ymax*1.15))
+ scale_x_continuous(limits = c(0,(max(Main_bar_data$x)+1)),
expand = c(0,0),
breaks = NULL)
+ xlab(NULL) + ylab(ylabel)
+ labs(title = NULL, fill = "Treatment")
+ guides(fill = guide_legend(title.position="top", title.hjust =0.5))
+ theme(axis.line.x = element_line(),
panel.background = element_rect(fill = "white"),
legend.text = element_text(vjust = 0.5, size = 7*y_axis_title_scale),
legend.title = element_text(vjust = 0.5, size = 8.3*y_axis_title_scale),
legend.direction = "horizontal",
legend.key.size = unit(1, "line"),
axis.title.x.top = element_text(vjust = 0, size = 8.3*y_axis_title_scale),
axis.text.x.top = element_text(vjust = 0.3, size = 7*y_axis_tick_label_scale, color = "gray0"),
plot.margin = unit(c(0.5,0.5,0.5,0.5), "lines"),
panel.border = element_blank()))
legend <- g_legend(Main_bar_plot)
return(legend)
} |
pbtapply <-
function (X, INDEX, FUN = NULL, ..., default = NA, simplify = TRUE,
cl = NULL)
{
FUN <- if (!is.null(FUN))
match.fun(FUN)
if (!is.list(INDEX))
INDEX <- list(INDEX)
INDEX <- lapply(INDEX, as.factor)
nI <- length(INDEX)
if (!nI)
stop("'INDEX' is of length zero")
if (!all(lengths(INDEX) == length(X)))
stop("arguments must have same length")
namelist <- lapply(INDEX, levels)
extent <- lengths(namelist, use.names = FALSE)
cumextent <- cumprod(extent)
if (cumextent[nI] > .Machine$integer.max)
stop("total number of levels >= 2^31")
storage.mode(cumextent) <- "integer"
ngroup <- cumextent[nI]
group <- as.integer(INDEX[[1L]])
if (nI > 1L)
for (i in 2L:nI) group <- group + cumextent[i - 1L] *
(as.integer(INDEX[[i]]) - 1L)
if (is.null(FUN))
return(group)
levels(group) <- as.character(seq_len(ngroup))
class(group) <- "factor"
ans <- split(X, group)
names(ans) <- NULL
index <- as.logical(lengths(ans))
ans <- pblapply(X = ans[index], FUN = FUN, ..., cl = cl)
ansmat <- array(if (simplify && all(lengths(ans) == 1L)) {
ans <- unlist(ans, recursive = FALSE, use.names = FALSE)
if (!is.null(ans) && is.na(default) && is.atomic(ans))
vector(typeof(ans))
else default
}
else vector("list", prod(extent)), dim = extent, dimnames = namelist)
if (length(ans)) {
ansmat[index] <- ans
}
ansmat
} |
plot_cont<-function(sim = temp.interpolated,
sim.start = "2017-06-06",
sim.end = "2017-06-15",
legend.title = "T \u00B0C",
min.depth = 0,max.depth = 13,by.value = 0.5,
nlevels = 20,
plot.save = TRUE,
file_name = "Contour_temp.png",
height = 5, width = 8, ppi = 150){
date<-seq.Date(from = as.Date(sim.start,format="%Y-%m-%d"),
to = as.Date(sim.end,format="%Y-%m-%d"),
by="day")
index<-match(seq(lubridate::year(date)[1],lubridate::year(date)[length(date)],by=1),lubridate::year(date))
color.palette <- function(n) hcl.colors(n,"RdBu",rev=TRUE)
if(plot.save)
{
png(filename = file_name,height = height*ppi,width = width*ppi)
}
filled.contour(x=seq(1,ncol(sim),by=1),
y=seq(min.depth,max.depth,by=by.value),
z=t(sim),
ylim = c(max.depth,min.depth),
zlim = c(min(sim,na.rm=TRUE),max(sim,na.rm = TRUE)),
nlevels = nlevels,
color.palette = function(n)hcl.colors(n,"RdBu",rev=TRUE),
plot.axes = {
axis(3,mgp=c(1,0.25,0),tcl=-0.1, cex.axis=1.8, lwd=0.5,
at=seq(1,ncol(sim),by=1)[c(1,index)], labels=lubridate::year(date[c(1,index)]))
axis(2,mgp=c(1,0.4,0),tcl=-0.2, cex.axis=1.8, cex.lab=0.8,lwd=0.5)
mtext("Depth (m)",side=2,line=1.3,las=0,cex = 1.8)},
key.title = {
par(cex.main=1.3); title(main=legend.title)
})
if(plot.save){
dev.off()
}
} |
aboot <- function(x, strata = NULL, tree = "upgma", distance = "nei.dist",
sample = 100, cutoff = 0, showtree = TRUE, missing = "mean",
mcutoff = 0, quiet = FALSE, root = NULL, ...){
if (!is.null(strata)){
if (!is.genind(x)){
warning("Sorry, the strata argument can only be used with genind objects.")
} else {
x <- genind2genpop(x, pop = strata, quiet = TRUE, process.other = FALSE)
}
}
if (is.matrix(x)){
if (is.null(rownames(x))) rownames(x) <- .genlab("", nrow(x))
if (is.null(colnames(x))) colnames(x) <- .genlab("L", ncol(x))
xboot <- x
} else if (!is(x, "genlight") && x@type == "PA") {
xboot <- x@tab
colnames(xboot) <- locNames(x)
rownames(xboot) <- if (is.genpop(x)) popNames(x) else indNames(x)
} else if (is(x, "gen")) {
if (is.genind(x)) {
if (missing %in% c("loci", "geno", "ignore")){
x <- missingno(x, missing, quiet = quiet, cutoff = mcutoff)
missing <- "asis"
}
}
distname <- as.character(substitute(distance))
if (length(distname) == 1 && distname %in% "diss.dist"){
if (missing == "mean"){
missing <- "asis"
warning("Sorry, missing = 'mean' is incompatible with diss.dist(), setting missing to 'asis'.",
call. = FALSE)
}
xboot <- new("bootgen", x, na = missing, freq = FALSE)
} else {
xboot <- new("bootgen", x, na = missing, freq = TRUE)
}
} else if (is(x, "genlight")){
xboot <- x
my_dists <- c("diss.dist", "nei.dist", "prevosti.dist", "edwards.dist",
"reynolds.dist", "rogers.dist", "provesti.dist")
wrong_dist <- any(as.character(substitute(distance)) %in% my_dists)
if (wrong_dist){
warning("Sorry, distance from genlight objects can only be calculated by bitwise.dist.")
distance <- bitwise.dist
}
} else {
stop("Sorry, x must be a genind, genpop, or genlight object.")
}
treefunk <- tree_generator(tree, distance, ...)
xtree <- treefunk(xboot)
if (any(xtree$edge.len < 0)){
xtree <- fix_negative_branch(xtree)
warning(negative_branch_warning())
}
treechar <- paste(substitute(tree), collapse = "")
if (is.null(root)) {
root <- ape::is.ultrametric(xtree)
}
nodelabs <- boot.phylo(xtree, xboot, treefunk, B = sample, rooted = root,
quiet = quiet)
nodelabs <- (nodelabs/sample)*100
nodelabs <- ifelse(nodelabs >= cutoff, nodelabs, NA)
if (!is.genpop(x)){
if (is.matrix(x)){
xtree$tip.label <- rownames(x)
} else if (!is.null(indNames(x))) {
xtree$tip.label <- indNames(x)
}
} else {
xtree$tip.label <- popNames(x)
}
xtree$node.label <- nodelabs
if (showtree) {
poppr.plot.phylo(xtree, treechar, root)
}
return(xtree)
}
diversity_stats <- function(z, H = TRUE, G = TRUE, lambda = TRUE, E5 = TRUE, ...){
E.5 <- function(x){
H <- vegan::diversity(x)
G <- vegan::diversity(x, "inv")
(G - 1)/(exp(H) - 1)
}
BASIC_FUNS <- list(H = vegan::diversity,
G = function(x) vegan::diversity(x, "inv"),
lambda = function(x) vegan::diversity(x, "simp"),
E.5 = E.5)
FUNS <- c(BASIC_FUNS, list(...))
STATS <- names(FUNS)
STATS <- STATS[c(H, G, lambda, E5, rep(TRUE, length(list(...))))]
boot <- is.null(dim(z))
nrows <- ifelse(boot, 1, nrow(z))
if (boot){
dims <- list(NULL, Index = STATS)
} else {
dims <- list(Pop = rownames(z), Index = STATS)
}
mat <- matrix(nrow = nrows, ncol = length(STATS), dimnames = dims)
for (i in STATS){
if (i == "E.5" && H && G){
mat[, i] <- (mat[, "G"] - 1)/(exp(mat[, "H"]) - 1)
} else {
mat[, i] <- FUNS[[i]](z)
}
}
return(drop(mat))
}
diversity_boot <- function(tab, n, n.boot = 1L, n.rare = NULL, H = TRUE,
G = TRUE, lambda = TRUE, E5 = TRUE, ...){
if (!is.null(n.rare)){
FUN <- rare_sim_boot
mle <- n.rare
} else {
FUN <- multinom_boot
mle <- n.boot
}
res <- apply(tab, 1, boot_per_pop, rg = FUN, n = n, mle = mle, H = H, G = G,
lambda = lambda, E5 = E5, ...)
return(res)
}
diversity_ci <- function(tab, n = 1000, n.boot = 1L, ci = 95, total = TRUE,
rarefy = FALSE, n.rare = 10, plot = TRUE, raw = TRUE,
center = TRUE, ...){
allowed_objects <- c("genind", "genclone", "snpclone")
if (!is.matrix(tab) & inherits(tab, allowed_objects)){
tab <- mlg.table(tab, total = total, plot = FALSE)
}
rareval <- NULL
if (rarefy){
rareval <- max(min(rowSums(tab)), n.rare)
msg <- paste("\nSamples for rarefaction:", rareval)
message(msg)
} else {
if (center == TRUE){
msg <- paste("\nConfidence Intervals have been centered around observed",
"statistic.\nPlease see ?diversity_ci for details.\n")
message(msg)
} else if (n.boot > 2){
msg <- paste("\nTake caution in interpreting the results.\nWhile sampling",
n.boot, "samples will produce a confidence interval,\nit",
"might be unclear what the correct interpretation should be.\n")
message(msg)
}
}
res <- diversity_boot(tab, n, n.rare = rareval, n.boot = n.boot, ...)
orig <- get_boot_stats(res)
statnames <- colnames(orig)
CI <- get_all_ci(res, ci = ci, index_names = statnames,
center = if (rarefy) FALSE else center,
btype = if (rarefy) "percent" else "normal",
bci = if (rarefy) FALSE else TRUE)
est <- get_boot_se(res, "mean")
out <- list(obs = orig, est = est, CI = CI, boot = res)
if (plot) {
boot_plot(res = res,
orig = orig,
CI = if (rarefy) NULL else CI
)
}
out <- if (raw) out else do.call("pretty_info", out)
return(out)
} |
all_params_dtrng <- function(station_code, dtrng, param = NULL, trace = TRUE, Max = NULL){
tictoc::tic()
serv <- "http://cdmo.baruch.sc.edu/webservices2/requests.cfc?wsdl"
tz <- time_vec(station_code = station_code, tz_only = TRUE)
obsmin <- as.POSIXct(dtrng[1], format = '%m/%d/%Y', tz = tz)
end_obs <- obsmin + 1
out_all <- NULL
if(trace) cat('Importing...\n\n')
while(end_obs > obsmin){
web_args = list(
method = 'exportAllParamsDateRangeXMLNew',
station_code = station_code,
mindate = dtrng[1],
maxdate = dtrng[2]
)
if(!is.null(param)) web_args$param <- param
dat <- try({
httr::GET(
serv,
query = web_args
)
}, silent = TRUE)
if('try-error' %in% class(dat))
stop('Error retrieving data, check metadata for station availability.')
out <- parser(dat)
if(nrow(out) == 0)
stop('Empty data frame, check metadata for station availability')
parm <- substring(station_code, 6)
nms <- param_names(parm)[[parm]]
out[, 'datetimestamp'] <- time_vec(out[, 'datetimestamp'], station_code)
out <- out[order(out$datetimestamp), ]
out <- data.frame(
datetimestamp = out$datetimestamp,
out[, tolower(names(out)) %in% nms, drop = FALSE],
row.names = 1:nrow(out)
)
names(out) <- tolower(names(out))
end_obs <- min(out$datetimestamp)
max_obs <- max(out$datetimestamp)
if(trace) cat('\t', as.character(as.Date(max_obs) - 1), 'to', as.character(as.Date(end_obs)), '\n')
if(!is.null(out_all)){
if(end_obs == min(out_all$datetimestamp)) break
}
out_all <- rbind(out_all, out)
out_all <- unique(out_all[order(out_all$datetimestamp), ])
if(!is.null(Max)){
if(nrow(out_all) >= Max){
out_all <- out_all[(1 + nrow(out_all) - Max):nrow(out_all), ]
break
}
}
dtrng[2] <- as.character(as.Date(end_obs))
dtrng[2] <- paste0(substr(dtrng[2], 6, nchar(dtrng[2])), '/', substr(dtrng[2], 1, 4))
dtrng[2] <- gsub('-', '/', dtrng[2])
}
parms <- nms[!grepl('^f_', nms)]
out <- out_all
out[, names(out) %in% parms] <- apply(out[, names(out) %in% parms, drop = FALSE], 2, as.numeric)
row.names(out) <- 1:nrow(out)
out <- swmpr(out, station_code)
if(trace){
cat('\n')
cat(nrow(out), 'records, ')
tictoc::toc()
}
return(out)
} |
library(dplyr)
library(reshape2)
load("ce.RData")
test_that("compute_U", {
}) |
context("Test for lets.addvar")
data(PAM)
data(temp)
tempstack <- stack(temp, temp)
test_that("lets.addvar works fine", {
PAM_temp_mean <- lets.addvar(PAM, temp)
expect_true(is.matrix(PAM_temp_mean))
expect_true(ncol(as.matrix(PAM_temp_mean)) == (ncol(PAM[[1]]) + 1))
})
test_that("lets.addvar works fine, different fun", {
PAM_temp_mean <- lets.addvar(PAM, temp, fun = sd)
expect_true(is.matrix(PAM_temp_mean))
expect_true(ncol(as.matrix(PAM_temp_mean)) == (ncol(PAM[[1]]) + 1))
})
test_that("lets.addvar works fine, onlyvar = TRUE", {
PAM_temp_mean <- lets.addvar(PAM, temp, onlyvar = TRUE)
expect_true(is.matrix(PAM_temp_mean))
expect_true(ncol(as.matrix(PAM_temp_mean)) == 1)
})
test_that("lets.addvar works fine, multiple rasters", {
PAM_temp_mean <- lets.addvar(PAM, tempstack)
expect_true(is.matrix(PAM_temp_mean))
expect_true(ncol(as.matrix(PAM_temp_mean)) == (ncol(PAM[[1]]) + 2))
}) |
jobAdd <- function(name, status = "", progressUnits = 0L, actions = NULL, running = FALSE,
autoRemove = TRUE, show = TRUE) {
callFun("addJob", name = name,
status = status,
progressUnits = progressUnits,
actions = actions,
running = running,
autoRemove = autoRemove,
show = show)
}
jobRemove <- function(job) {
callFun("removeJob", job = job)
}
jobSetProgress <- function(job, units) {
callFun("setJobProgress", job = job, units = units)
}
jobAddProgress <- function(job, units) {
callFun("addJobProgress", job = job, units = units)
}
jobSetStatus <- function(job, status) {
callFun("setJobStatus", job = job, status = status)
}
jobSetState <- function(job, state = c("idle", "running", "succeeded", "cancelled", "failed")) {
callFun("setJobState", job = job, state = state)
}
jobAddOutput <- function(job, output, error = FALSE) {
callFun("addJobOutput", job = job, output = output, error = error)
}
jobRunScript <- function(path, name = NULL, encoding = "unknown", workingDir = NULL,
importEnv = FALSE, exportEnv = "") {
path <- normalizePath(path, winslash = "/", mustWork = TRUE)
callFun("runScriptJob", path = path,
name = name,
encoding = encoding,
workingDir = workingDir,
importEnv = importEnv,
exportEnv = exportEnv)
} |
mlexp <- function(x, na.rm = FALSE, ...) {
if (na.rm) x <- x[!is.na(x)] else assertthat::assert_that(!anyNA(x))
ml_input_checker(x)
assertthat::assert_that(min(x) >= 0)
rate <- 1 / mean(x)
object <- c(rate = rate)
class(object) <- "univariateML"
attr(object, "model") <- "Exponential"
attr(object, "density") <- "stats::dexp"
attr(object, "logLik") <- length(x) * (log(rate) - 1)
attr(object, "support") <- c(0, Inf)
attr(object, "n") <- length(x)
attr(object, "call") <- match.call()
object
} |
FindContrasts <- function(x, y, tree, method = "gls", denominator = 1,
cores = 1, cl = NULL) {
assertthat::assert_that(is.data.frame(x),
is.data.frame(y),
class(tree) %in% c("phylo", "multiPhylo"),
method %in% c("pic", "gls"),
is.null(denominator) | is.numeric(denominator),
is.null(denominator) | all(denominator > 0))
tmp_x <- x[, 1]
names(tmp_x) <- rownames(x)
if (method == "pic") {
contrast_x <- ape::pic(x = tmp_x, phy = tree)
if (!is.null(denominator)) y <- sweep(y, MARGIN = 1, denominator, `/`)
message("Computing contrasts")
if (.Platform$OS.type == "windows"){
models <- parallel::parLapply(cl = cl,
X = y,
fun = function(tmpy, tree, cx, nx){
names(tmpy) <- nx
cy <- ape::pic(tmpy, phy = tree)
mod <- stats::lm(cy ~ cx + 0)
return(summary(mod)$coefficients[1, 4])},
tree = tree,
cx = contrast_x,
nx = rownames(x))
} else {
models <- pbmcapply::pbmclapply(y,
function(tmpy, tree, cx, nx){
names(tmpy) <- nx
cy <- ape::pic(tmpy, phy = tree)
mod <- stats::lm(cy ~ cx - 1)
return(summary(mod)$coefficients[1, 4])},
tree = tree,
cx = contrast_x,
nx = rownames(x),
mc.preschedule = TRUE,
mc.cores = cores)
}
} else if (method == "gls") {
if (!is.null(denominator)) {
y <- sweep(y, MARGIN = 1, denominator, `/`) * 10^6
}
tmpfun <- function(tmpy, tmpx, nx, tree){
if(any(tmpy == 0)){
model <- nlme::gls(tmp_y ~ tmp_x,
data = as.data.frame(cbind(tmpx, tmpy)),
correlation = ape::corPagel(value = 1,
phy = tree),
control = list(singular.ok = TRUE))
return(as.numeric(summary(model)$coefficients[2]))
} else {
return(1)
}}
if (.Platform$OS.type == "windows"){
models <- parallel::parLapply(cl = cl,
X = y,
fun = tmpfun,
tmpx = tmp_x,
nx = rownames(x),
tree = tree)
} else {
models <- pbmcapply::pbmclapply(X = y,
FUN = tmpfun,
tmpx = tmp_x,
nx = rownames(x),
tree = tree,
mc.preschedule = TRUE,
mc.cores = cores)
}
} else{
stop("'", method,"' is not a recognized method in CALANGO::FindContrasts()")
}
models <- unlist(models)
return(sort(models, decreasing = FALSE))
} |
knitr::opts_chunk$set(collapse = TRUE, comment = "
library("mlrCPO")
set.seed(123)
base = knitr::opts_knit$get("output.dir")
file = sys.frame(min(grep("^knitr::knit$|^knit$", sapply(sys.calls(), function(x) as.character(x)[1]))))$input
file = basename(file)
path = file.path(base, file)
rpath = gsub("\\.[^.]*$", ".R", path)
knitr::knit_hooks$set(document = function(x) {
if (file_test("-f", rpath)) {
lines = readLines(rpath)
lines = gsub(" *(\n|$)", "\\1", lines)
cat(lines, file = rpath, sep = "\n", append = FALSE)
}
x
})
fullfile = file
allfiles = list.files(path = base, pattern = ".*\\.Rmd$")
stopifnot(file %in% allfiles)
fileinfolist = list()
for (cf in allfiles) {
ismain = TRUE
if (grepl("^z_", cf)) {
infoslot = gsub("^z_", "", cf)
infoslot = gsub("_terse\\.Rmd$", "", infoslot)
subslot = "compact"
} else {
infoslot = gsub("^a_", "", cf)
infoslot = gsub("\\.Rmd$", "", infoslot)
subslot = "main"
}
content = scan(paste(base, cf, sep = "/"), what = "character", quiet = TRUE)
pos = min(c(which(content == "title:"), Inf))
if (is.infinite(pos)) {
stop(sprintf("parsing error: %s", cf))
}
infolist = list(title = content[pos + 1], url = cf, iscurrent = cf == file)
applist = list(infolist)
names(applist) = subslot
fileinfolist[[infoslot]] = c(fileinfolist[[infoslot]], applist)
}
linkify = function(info, title) {
if (info$iscurrent) {
title
} else {
sprintf("[%s](%s)", title, gsub("\\.Rmd$", ".html", info$url))
}
}
for (idx in seq_along(fileinfolist)) {
content = fileinfolist[[sort(names(fileinfolist))[idx]]]
if (!is.null(content$compact)) {
if (paste(sub("[0-9]\\. ", "", content$main$title), "(No Output)") != sub("^z ", "", content$compact$title)) {
stop(sprintf("File %s and its compact version %s have incompatible titles\nThe compact version must be paste(main_title, \"(No Output)\"). Is: '%s', expected: '%s'",
content$main$url, content$compact$url, content$compact$title, paste(content$main$title, "(No Output)")))
}
line = sprintf("%s (%s)", linkify(content$main, content$main$title), linkify(content$compact, "compact version"))
} else {
line = linkify(content$main, content$main$title)
}
cat(sprintf("%s. %s\n", idx, line))
if (content$main$iscurrent || content$compact$iscurrent) {
fullfile = content$main$url
}
}
fullpath = file.path(base, fullfile)
printToc = function(print.level = 3) {
owncontent = readLines(fullpath)
tripletic = grepl("^```", owncontent)
owncontent = owncontent[cumsum(tripletic) %% 2 == 0]
headlines = grep("^
headlevels = nchar(gsub(" .*", "", headlines))
headlines = gsub("^[
links = gsub("[^-a-z. ]", "", tolower(headlines))
links = gsub(" +", "-", links)
links = gsub("-$", "", links)
if (!sum(headlevels <= print.level)) {
return(invisible(NULL))
}
cat("<h", headlevels[1], ">Table of Contents</h", headlevels[1], ">\n<div id=\"TOC\">\n", sep = "")
lastlevel = headlevels[1] - 1
for (idx in seq_along(headlines)) {
line = headlines[idx]
level = headlevels[idx]
link = links[idx]
if (level > print.level) {
next
}
if (level < headlevels[1]) {
stop("First headline level must be the lowest one used, but '", line, "' is lower.")
}
lvldiff = level - lastlevel
if (lvldiff > 1) {
stop("Cannot jump headline levels. Error on: ", line)
}
if (lvldiff > 0) {
cat("<ul>")
} else {
cat("</li>\n")
}
if (lvldiff < 0) {
for (l in seq_len(-lvldiff)) {
cat("</ul></li>")
}
}
cat("<li><a href=\"
lastlevel = level
}
lvldiff = lastlevel - headlevels[1]
cat("</li></ul>\n</div>\n")
}
options(width = 80)
replaceprint = function(ofunc) {
force(ofunc)
function(x, ...) {
cu = capture.output({ret = ofunc(x, ...)})
cu = grep("time: [-+e0-9.]{1,6}", cu, value = TRUE, invert = TRUE)
cat(paste(cu, collapse = "\n"))
if (!grepl("\n$", tail(cu, 1))) {
cat("\n")
}
ret
}
}
for (pfunc in grep("print\\.", ls(asNamespace("mlr")), value = TRUE)) {
ofunc = get(pfunc, asNamespace("mlr"))
assign(pfunc, replaceprint(ofunc))
}
printToc(4)
!cpoPca()
xmpSample = makeCPORetrafoless("exsample",
pSS(fraction: numeric[0, 1]),
dataformat = "df.all",
cpo.trafo = function(data, target, fraction) {
newsize = round(nrow(data) * fraction)
row.indices = sample(nrow(data), newsize)
data[row.indices, ]
})
cpo = xmpSample(0.01)
iris %>>% cpo
xmpSampleHeadless = makeCPORetrafoless("exsample",
pSS(fraction: numeric[0, 1]),
dataformat = "df.all",
cpo.trafo = {
newsize = round(nrow(data) * fraction)
row.indices = sample(nrow(data), newsize)
data[row.indices, ]
})
xmpFilterVar = makeCPO("exemplvar",
pSS(n.col: integer[0, ]),
dataformat = "numeric",
cpo.train = function(data, target, n.col) {
cat("*** cpo.train ***\n")
sapply(data, var, na.rm = TRUE)
},
cpo.retrafo = function(data, control, n.col) {
cat("*** cpo.retrafo ***\n")
cat("Control:\n")
print(control)
cat("\n")
greatest = order(-control)
data[greatest[seq_len(n.col)]]
})
cpo = xmpFilterVar(2)
(trafd = head(iris) %>>% cpo)
head(iris %>>% cpo)
head(iris %>>% retrafo(trafd))
getCPOTrainedState(retrafo(trafd))
xmpFilterVarFunc = makeCPO("exemplvar.func",
pSS(n.col: integer[0, ]),
dataformat = "numeric",
cpo.retrafo = NULL,
cpo.train = function(data, target, n.col) {
cat("*** cpo.train ***\n")
ctrl = sapply(data, var, na.rm = TRUE)
function(x) {
cat("*** cpo.retrafo ***\n")
cat("Control:\n")
print(ctrl)
cat("\ndata:\n")
print(data)
cat("target:\n")
print(target)
greatest = order(-ctrl)
x[greatest[seq_len(n.col)]]
}
})
cpo = xmpFilterVarFunc(2)
(trafd = head(iris) %>>% cpo)
getCPOTrainedState(retrafo(trafd))
xmpAsNum = makeCPO("asnum",
cpo.train = NULL,
cpo.retrafo = function(data) {
data.frame(lapply(data, as.numeric))
})
cpo = xmpAsNum()
(trafd = head(iris) %>>% cpo)
getCPOTrainedState(retrafo(trafd))
xmpPca = makeCPOExtendedTrafo("simple.pca",
pSS(n.col: integer[0, ]),
dataformat = "numeric",
cpo.trafo = function(data, target, n.col) {
cat("*** cpo.trafo ***\n")
pcr = prcomp(as.matrix(data), center = FALSE, scale. = FALSE, rank = n.col)
control = pcr$rotation
pcr$x
},
cpo.retrafo = function(data, control, n.col) {
cat("*** cpo.retrafo ***\n")
as.matrix(data) %*% control
})
cpo = xmpPca(2)
(trafd = head(iris) %>>% cpo)
tail(iris) %>>% retrafo(trafd)
getCPOTrainedState(retrafo(trafd))
xmpPcaFunc = makeCPOExtendedTrafo("simple.pca.func",
pSS(n.col: integer[0, ]),
dataformat = "numeric",
cpo.retrafo = NULL,
cpo.trafo = function(data, target, n.col) {
cat("*** cpo.trafo ***\n")
pcr = prcomp(as.matrix(data), center = FALSE, scale. = FALSE, rank = n.col)
cpo.retrafo = function(data) {
cat("*** cpo.retrafo ***\n")
as.matrix(data) %*% pcr$rotation
}
pcr$x
})
cpo = xmpPcaFunc(2)
(trafd = head(iris) %>>% cpo)
getCPOTrainedState(retrafo(trafd))$pcr$x
xmpMetaLearn = makeCPOTargetOp("xmp.meta",
pSS(lrn: untyped),
dataformat = "task",
properties.target = c("classif", "twoclass"),
predict.type.map = c(response = "response", prob = "prob"),
cpo.train = function(data, target, lrn) {
cat("*** cpo.train ***\n")
lrn = setPredictType(lrn, "prob")
train(lrn, data)
},
cpo.retrafo = function(data, target, control, lrn) {
cat("*** cpo.retrafo ***\n")
prediction = predict(control, target)
tname = getTaskTargetNames(target)
tdata = getTaskData(target)
tdata[[tname]] = factor(prediction$data$response == prediction$data$truth)
makeClassifTask(getTaskId(target), tdata, tname, positive = "TRUE",
fixup.data = "no", check.data = FALSE)
},
cpo.train.invert = function(data, control, lrn) {
cat("*** cpo.train.invert ***\n")
predict(control, newdata = data)$data
},
cpo.invert = function(target, control.invert, predict.type, lrn) {
cat("*** cpo.invert ***\n")
if (predict.type == "prob") {
outmat = as.matrix(control.invert[grep("^prob\\.", names(control.invert))])
revmat = outmat[, c(2, 1)]
outmat * target[, "prob.TRUE", drop = TRUE] +
revmat * target[, "prob.FALSE", drop = TRUE]
} else {
stopifnot(levels(target) == c("FALSE", "TRUE"))
numeric.prediction = as.numeric(control.invert$response)
numeric.res = ifelse(target == "TRUE",
numeric.prediction,
3 - numeric.prediction)
factor(levels(control.invert$response)[numeric.res],
levels(control.invert$response))
}
})
cpo = xmpMetaLearn(makeLearner("classif.logreg"))
set.seed(12)
split = makeResampleInstance(hout, pid.task)
train.task = subsetTask(pid.task, split$train.inds[[1]])
test.task = subsetTask(pid.task, split$predict.inds[[1]])
trafd = train.task %>>% cpo
attributes(trafd)
head(getTaskData(trafd))
model = train(makeLearner("classif.logreg", predict.type = "prob"), train.task)
head(predict(model, train.task)$data[c("truth", "response")])
retr = test.task %>>% retrafo(trafd)
attributes(retr)
retr.df = getTaskData(test.task, target.extra = TRUE)$data %>>% retrafo(trafd)
names(attributes(retr.df))
ext.model = train("classif.svm", trafd)
ext.pred = predict(ext.model, retr)
newpred = invert(inverter(retr), ext.pred)
performance(newpred)
cpo.learner = cpo %>>% makeLearner("classif.svm")
cpo.model = train(cpo.learner, train.task)
lrnpred = predict(cpo.model, test.task)
performance(lrnpred)
xmpMetaLearn = makeCPOTargetOp("xmp.meta.fnc",
pSS(lrn: untyped),
dataformat = "task",
properties.target = c("classif", "twoclass"),
predict.type.map = c(response = "response", prob = "prob"),
cpo.retrafo = NULL, cpo.train.invert = NULL, cpo.invert = NULL,
cpo.train = function(data, target, lrn) {
cat("*** cpo.train ***\n")
lrn = setPredictType(lrn, "prob")
model = train(lrn, data)
cpo.retrafo = function(data, target) {
cat("*** cpo.retrafo ***\n")
prediction = predict(model, target)
tname = getTaskTargetNames(target)
tdata = getTaskData(target)
tdata[[tname]] = factor(prediction$data$response == prediction$data$truth)
makeClassifTask(getTaskId(target), tdata, tname, positive = "TRUE",
fixup.data = "no", check.data = FALSE)
}
cpo.train.invert = function(data) {
cat("*** cpo.train.invert ***\n")
prediction = predict(model, newdata = data)$data
function(target, predict.type) {
cat("*** cpo.invert ***\n")
if (predict.type == "prob") {
outmat = as.matrix(prediction[grep("^prob\\.", names(prediction))])
revmat = outmat[, c(2, 1)]
outmat * target[, "prob.TRUE", drop = TRUE] +
revmat * target[, "prob.FALSE", drop = TRUE]
} else {
stopifnot(levels(target) == c("FALSE", "TRUE"))
numeric.prediction = as.numeric(prediction$response)
numeric.res = ifelse(target == "TRUE",
numeric.prediction,
3 - numeric.prediction)
factor(levels(prediction$response)[numeric.res],
levels(prediction$response))
}
}
}
})
xmpRegCenter = makeCPOTargetOp("xmp.center",
constant.invert = TRUE,
cpo.train.invert = NULL,
dataformat = "df.feature",
properties.target = "regr",
cpo.train = function(data, target) {
mean(target[[1]])
},
cpo.retrafo = function(data, target, control) {
target[[1]] = target[[1]] - control
target
},
cpo.invert = function(target, predict.type, control.invert) {
target + control.invert
})
cpo = xmpRegCenter()
train.task = subsetTask(bh.task, 150:155)
getTaskTargets(train.task)
predict.task = subsetTask(bh.task, 156:160)
getTaskTargets(predict.task)
trafd = train.task %>>% cpo
getTaskTargets(trafd)
getTaskTargets(predict.task)
retr = retrafo(trafd)
predict.traf = predict.task %>>% retr
getTaskTargets(predict.traf)
model = train("regr.lm", trafd)
pred = predict(model, predict.traf)
pred
invert(inverter(predict.traf), pred)
model = train("regr.lm", train.task)
predict(model, predict.task)
getCPOTrainedCapability(retr)
invert(retr, pred)
xmpLogRegr = makeCPOTargetOp("log.regr",
constant.invert = TRUE,
properties.target = "regr",
cpo.train = NULL, cpo.train.invert = NULL,
cpo.retrafo = function(data, target) {
target[[1]] = log(target[[1]])
target
},
cpo.invert = function(target, predict.type) {
exp(target)
})
cpo = xmpLogRegr()
trafd = train.task %>>% cpo
getTaskTargets(trafd)
retr = retrafo(trafd)
predict.traf = predict.task %>>% retr
getTaskTargets(predict.traf)
model = train("regr.lm", trafd)
pred = predict(model, predict.traf)
pred
invert(inverter(predict.traf), pred)
invert(retr, pred)
xmpSynCPO = makeCPOExtendedTargetOp("syn.cpo",
properties.target = "regr",
cpo.trafo = function(data, target) {
cat("*** cpo.trafo ***\n")
target[[1]] = target[[1]] + 1
control = "control created in cpo.trafo"
control.invert = "control.invert created in cpo.trafo"
target
},
cpo.retrafo = function(data, target, control) {
cat("*** cpo.retrafo ***", "control is:", deparse(control), sep = "\n")
control.invert = "control.invert created in cpo.retrafo"
if (!is.null(target)) {
cat("target is non-NULL, performing transformation\n")
target[[1]] = target[[1]] - 1
return(target)
} else {
cat("target is NULL, no transformation (but control.invert was created)\n")
return(NULL)
}
},
cpo.invert = function(target, control.invert, predict.type) {
cat("*** invert ***", "control.invert is:", deparse(control.invert),
sep = "\n")
target
})
cpo = xmpSynCPO()
trafd = train.task %>>% cpo
getTaskTargets(trafd)
retrafd = train.task %>>% retrafo(trafd)
getTaskTargets(retrafd)
retrafd = getTaskData(train.task, target.extra = TRUE)$data %>>% retrafo(trafd)
inv = invert(inverter(trafd), 1:6)
inv = invert(inverter(retrafd), 1:6)
oscipen = options("scipen")
options(scipen = 10)
learners = list(
logreg = makeLearner("classif.logreg"),
svm = makeLearner("classif.svm"),
cpo = xmpMetaLearn(makeLearner("classif.logreg")) %>>%
makeLearner("classif.svm")
)
configureMlr(show.info = FALSE, show.learner.output = FALSE)
perfs = sapply(learners, function(lrn) {
unname(replicate(20, resample(lrn, pid.task, cv10)$aggr))
})
configureMlr()
boxplot(perfs)
pvals = c(
logreg = t.test(perfs[, "logreg"], perfs[, "cpo"], "greater")$p.value,
svm = t.test(perfs[, "svm"], perfs[, "cpo"], "greater")$p.value
)
round(p.adjust(pvals), 3)
options(scipen = oscipen$scipen) |
ExampleFX =function(JSON = FALSE)
{
requireNamespace("Trading")
tr1 = Trading::FxForward(external_id = "ext_1",Notional=10000,MtM=30,ccyPair="EUR/USD",Si=0,Ei=10,BuySell='Buy')
tr2 = Trading::FxForward(external_id = "ext_2",Notional=20000,MtM=-20,ccyPair="EUR/USD",Si=0,Ei=4,BuySell='Sell')
tr3 = Trading::FxForward(external_id = "ext_3",Notional=5000,MtM=50,ccyPair="GBP/USD",Si=1,Ei=11,BuySell='Sell')
trades= list(tr1,tr2,tr3)
csas = list()
colls = list()
tree = runExampleCalcs(trades, csas, colls)
if(JSON==TRUE)
{
requireNamespace("jsonlite")
return(jsonlite::toJSON(as.list(tree[[1]])))
}
else
{ return(tree[[1]])}
} |
morphomapTri2sects<-function(cp,mp){
mat<-matrix(NA,ncol=3,nrow=dim(cp)[1]*2)
totsec<-rbind(cp,mp)
extpoi<-1:dim(cp)[1]
intpoi<-(dim(mp)[1]+1):dim(totsec)[1]
counter<-0
for(i in 1:length(extpoi)){
if(i!=length(extpoi)){
mati<-c(extpoi[i],intpoi[i],extpoi[i+1])
mati2<-c(intpoi[i],intpoi[i+1],extpoi[i+1])
}
if(i==length(extpoi)){
mati<-c(extpoi[i],intpoi[i],extpoi[1])
mati2<-c(intpoi[i],intpoi[1],extpoi[1])
}
counter<-counter+1
mat[counter,]<-mati
counter<-counter+1
mat[counter,]<-mati2
}
out<-list("matrix"=totsec,"tri"=mat)
return(out)
} |
"jameson_buchanan" <- as.formula("
LOG10N~(flora==1)*((t<=lag_1)*LOG10N0_1+
((t>lag_1)&(t<tmax))*(LOG10N0_1 + mumax_1/log(10)*(t-lag_1))+
(t>=tmax)*(LOG10N0_1 +mumax_1/log(10)*(tmax-lag_1)))+
(flora==2)*((t<=lag_2)*LOG10N0_2+
((t>lag_2)&(t<tmax))*(LOG10N0_2 + mumax_2/log(10)*(t-lag_2))+
(t>=tmax)*(LOG10N0_2 +mumax_2/log(10)*(tmax-lag_2)))")
"jameson_baranyi" <- as.formula("
LOG10N ~ (flora==1)* ( (t<=tmax)*(LOG10N0_1 + mumax_1 * t/log(10) + log10(exp(-mumax_1 * t) *
(1 - exp(-mumax_1 * lag_1)) + exp(-mumax_1 * lag_1))) +
(t>tmax) * (LOG10N0_1 + mumax_1 * tmax/log(10) + log10(exp(-mumax_1 * tmax) *
(1 - exp(-mumax_1 * lag_1)) + exp(-mumax_1 * lag_1))) ) +
(flora==2)* ( (t<=tmax)*(LOG10N0_2 + mumax_2 * t/log(10) + log10(exp(-mumax_2 * t) *
(1 - exp(-mumax_2 * lag_2)) + exp(-mumax_2 * lag_2))) +
(t>tmax) * (LOG10N0_2 + mumax_2 * tmax/log(10) + log10(exp(-mumax_2 * tmax) *
(1 - exp(-mumax_2 * lag_2)) + exp(-mumax_2 * lag_2))) ) ")
"jameson_without_lag" <- as.formula("
LOG10N~(flora==1)*( (t<tmax)*(LOG10N0_1 + mumax_1/log(10)*t)+
(t>=tmax)*(LOG10N0_1 +mumax_1/log(10)*tmax))+
(flora==2)*( (t<tmax)*(LOG10N0_2 + mumax_2/log(10)*t)+
(t>=tmax)*(LOG10N0_2 +mumax_2/log(10)*tmax))") |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(caracas)
inline_code <- function(x) {
x
}
if (!has_sympy()) {
knitr::opts_chunk$set(eval = FALSE)
inline_code <- function(x) {
deparse(substitute(x))
}
}
n_2 <- as_sym("2")
n_pi <- as_sym("pi", declare_symbols = FALSE)
x <- sqrt(n_2) * n_pi
x
N(x)
N(x, 5)
N(x, 50)
as.character(N(x, 50))
mpmath <- reticulate::import('mpmath')
mpmath$mp$dps <- 30
z <- mpmath$mpc(real = '1.0', imag = '63.453')
zeta_z <- mpmath$zeta(z)
zeta_z
as.character(zeta_z$real)
as.character(zeta_z$imag) |
gboot_variogram<-function(data,var,model,B=1000){
Distance=Semivariance=NULL
if(is.geodata(data) == T){
}else{
stop("Object data is not of the class geodata")
}
if(isTRUE(class(var) == "variogram")){
}else{
stop("Object var is not of the class variogram")
}
if(isTRUE(class(model)[1] == "variomodel") & isTRUE(class(model)[2] == "variofit")){
}else{
stop("Object model is not of the class variomodel/variofit")
}
if(B >0 ){
}else{
stop("Object B must be positive")
}
model_name<-substr(model$cov.model,1,3)
models<-c("sph","exp","gau")
if(model_name %in% models){
}else{
stop("This functions only accepts the following models: gaussian, spherical and exponential")
}
quiet<-function(x){
invisible(capture.output(x))}
if(model_name=="gau" ){
gboot_predict<-function(u,c0,c1,a){
ifelse(u==0,0,c0+c1*(1-exp(-3*(u/a)^2)))
}
}
if(model_name=="exp"){
gboot_predict<-function(u,c0,c1,a){
ifelse(u==0,0,c0+c1*(1-exp(-3*u/a)))
}
}
if(model_name=="sph"){
gboot_predict<-function(u,c0,c1,a){
ifelse(u==0,0,
ifelse(u>a,c0+c1,c0+c1*(1.5*u/a-.5*(u/a)^3)))
}
}
max_dist<-var$max.dist
x<-var$u
c0<-model$nugget
c1<-model$cov.pars[1]
a<-model$cov.pars[2]
y<-var$v
pars_or<-data.frame(C0=c0,
Sill=c0+c1,
C1=c1,
a=a,
PR=model$practicalRange)
bin<-length(var$u)
var_df<-matrix(0,
nrow=B,
ncol=bin)
pars<-data.frame(C0=rep(0,B),
C1=rep(0,B),
a=rep(0,B),
Sill=rep(0,B),
`Pratical Range`=rep(0,B))
error_or<-y-gboot_predict(x,c0,c1,a)
var_new<-var
for(i in 1:B ){
error_new<-sample((error_or-mean(error_or)),length(error_or),replace = T)
var_new$v<-gboot_predict(x,c0,c1,a)+error_new
var_df[i,]<-var_new$v
quiet(mod_new<-variofit(var_new,ini.cov.pars=c(c1,a),
nugget=c0,
cov.model=model_name))
pars[i,]<-c(as.numeric(summary(mod_new)$estimated.pars[1]),
sum(as.numeric(c(summary(mod_new)$estimated.pars)[1:2])),
as.numeric(c(summary(mod_new)$estimated.pars[2:3])),
mod_new$practicalRange)
}
var_df<-as.data.frame(var_df)
names(var_df)<-paste("Class",letters[1:bin])
var_df<-gather(var_df,Distance,Semivariance)
var_df$B<-rep(1:B,bin)
var_aux<-data.frame(Distance=paste("Class",letters[1:bin]),Semivariance=var$v)
var_aux$Length<-var$u
names(pars)<-c("Nugget","Sill","Contribution","Range","Practical Range")
names(pars_or)<-c("Nugget","Sill","Contribution","Range","Practical Range")
return(list(variogram_boot=var_df,
variogram_or=var_aux,
pars_boot=pars,
pars_or=pars_or))
} |
NMixPlugDensJoint2 <- function(x, ...)
{
UseMethod("NMixPlugDensJoint2")
} |
PairPlot <- function(d, meas_vars, title,
...,
group_var = NULL,
alpha = 1,
palette = "Dark2",
point_color = 'darkgray') {
check_frame_args_list(...,
frame = d,
name_var_list = c(meas_vars, group_var),
title = title,
funname = "WVPlots::PairPlot")
controlTable <- data.frame(expand.grid(meas_vars, meas_vars,
stringsAsFactors = FALSE))
colnames(controlTable) <- c("x", "y")
controlTable <- cbind(
data.frame(pair_key = paste(controlTable[[1]], controlTable[[2]]),
stringsAsFactors = FALSE),
controlTable)
d_aug = cdata::rowrecs_to_blocks(
d,
controlTable,
columnsToCopy = group_var)
splt <- strsplit(d_aug$pair_key, split = " ", fixed = TRUE)
d_aug$xv <- vapply(splt, function(si) si[[1]], character(1))
d_aug$yv <- vapply(splt, function(si) si[[2]], character(1))
d_aug$xv <- factor(as.character(d_aug$xv),
meas_vars)
d_aug$yv <- factor(as.character(d_aug$yv),
meas_vars)
x <- y <- NULL
plt = ggplot2::ggplot(d_aug, ggplot2::aes(x=x, y=y))
if(length(group_var) == 1) {
plt = plt +
ggplot2::geom_point(ggplot2::aes_string(color=group_var), alpha=alpha)
} else {
plt = plt + ggplot2::geom_point(alpha=alpha, color=point_color)
}
plt = plt +
ggplot2::facet_grid(yv~xv, scale = "free") +
ggplot2::ggtitle(title) +
ggplot2::ylab(NULL) +
ggplot2::xlab(NULL)
if(!is.null(palette)) {
plt = plt + ggplot2::scale_color_brewer(palette = palette)
}
plt
} |
AORKF_t = function(Y,mu_0,Sigma_0=NULL,A,C,Sigma_Add,Sigma_Inn,s=2,epsilon=0.000001)
{
p = nrow(Sigma_Add)
q = nrow(Sigma_Inn)
if (is.null(p)){
stop("Sigma_Add must be a matrix.")
}
if (is.null(q)){
stop("Sigma_Inn must be a matrix.")
}
for (ii in 1:length(Y)){
Y[[ii]] = as.matrix(Y[[ii]])
if (nrow( Y[[ii]]) != p){
stop("all observations must be of the same number of rows as Sigma_Add.")
}
if (ncol( Y[[ii]]) != 1){
stop("all observations must have exactly one column,")
}
}
mu_0 = as.matrix(mu_0)
if (nrow(mu_0) != q){
stop("mu_0 must be of the same number of rows as Sigma_Add.")
}
if (ncol(mu_0) != 1){
stop("mu_0 must have 1 column.")
}
if (ncol(Sigma_Add) != p){
stop("Sigma_Add needs to be a square matrix.")
}
if (ncol(Sigma_Inn) != q){
stop("Sigma_Inn needs to be a square matrix.")
}
if (nrow(C) != p){
stop("C must have the same number of rows as the observations")
}
if (ncol(C) != q){
stop("The number of columns of C must equal the dimensions of the hidden state")
}
if (nrow(A) != q){
stop("A must have the same number of rows as the hidden states")
}
if (ncol(A) != q){
stop("The number of columns of A must equal the dimensions of the hidden state")
}
if (epsilon <= 0){
stop ("epsilon must be greater than 0.")
}
if (!isSymmetric(Sigma_Inn)){
stop("Sigma_Inn must be positive definite.")
}
if (sum(eigen(Sigma_Inn)$values <= 0) > 0 ){
stop("Sigma_Inn must be positive definite.")
}
if (!isSymmetric(Sigma_Add)){
stop("Sigma_Add must be positive definite.")
}
if (sum(eigen(Sigma_Add)$values <= 0) > 0 ){
stop("Sigma_Add must be positive definite.")
}
if(is.null(Sigma_0)){
New_Matrix = C
Full_Matrix = C
Rank = 0
repeat {
Rank = Rank+1
if(Rank > q+5) {
break
}
if( rankMatrix(Full_Matrix) == q ) {
break
}
New_Matrix = New_Matrix %*% A
Full_Matrix = rbind(Full_Matrix,New_Matrix)
}
if (Rank >q){
stop("The system has to be observable to infer Sigma_0.")
}
Final_Sigma = Sigma_Limit(diag(1,nrow = q),C,A,Sigma_Inn,Sigma_Add,epsilon)
Sigma_0 = Final_Sigma
}
if (nrow(Sigma_0) != q){
stop("Sigma_0 must have the same number of rows as the hidden states.")
}
if (ncol(Sigma_0) != q){
stop("The number of columns of Sigma_0 must equal the dimensions of the hidden state.")
}
if (!isSymmetric(Sigma_0)){
stop("Sigma_0 must be positive definite.")
}
if (sum(eigen(Sigma_0)$values <= 0) > 0 ){
stop("Sigma_0 must be positive definite.")
}
if (s <= 1){
stop ("s must be greater than 1.")
}
b = matrix(rep(0,q),ncol=1)
d = matrix(rep(0,p),ncol=1)
algo_output = aorkf_t_list(mu_0,Sigma_0,Y,A,b,C,d,Sigma_Add,Sigma_Inn,s,epsilon)
if (is.null(algo_output)){
stop("User interrupt.")
}
output = list()
output[["Y"]] = Y
output[["A"]] = A
output[["C"]] = C
output[["Sigma_Inn"]] = Sigma_Inn
output[["Sigma_Add"]] = Sigma_Add
output[["States"]] = algo_output
output["Type"] = "AO"
return(structure(output,class="rkf"))
} |
.onAttach <- function(...) {
packageStartupMessage('Super Learner')
packageStartupMessage('Version: ', utils::packageDescription('SuperLearner')$Version)
packageStartupMessage('Package created on ', utils::packageDescription('SuperLearner')$Date, '\n')
} |
tcplConf <- function (drvr = NULL, user = NULL, pass = NULL, host = NULL,
db = NULL) {
check <- function(x) length(x) == 1 && is.character(x)
setop <- function(x) {
xn <- deparse(substitute(x))
if (is.na(x)) x <- NA_character_
if (check(x)) {
p <- list(x)
names(p) <- paste0("TCPL_", toupper(xn))
do.call(what = options, p)
} else {
warning("Invalid '", xn, ",' no changes made to TCPL_", toupper(xn))
}
}
if (!is.null(user)) setop(user)
if (!is.null(pass)) setop(pass)
if (!is.null(host)) setop(host)
if (!is.null(db)) setop(db)
if (!is.null(drvr)) {
if (!drvr %in% c( "MySQL", "tcplLite")) {
stop(drvr, " is not a supported database driver. Must be ",
"'MySQL' or 'tcplLite.'")
}
if (drvr == "MySQL") {
options("TCPL_DRVR" = "MySQL")
mxp <- tcplQuery("SHOW VARIABLES LIKE 'max_allowed_packet'")$Value
mxp <- as.numeric(mxp)
if (mxp < 1073741824) {
warning("The 'max_allowed_packet' MySQL server setting is set to ",
mxp, " bytes. It is recommended that you increase it to ",
"1073741824 bytes to ensure larger queries run without error.")
}
}
if (drvr == "tcplLite") {
tcplLiteInit()
options("TCPL_DRVR" = "tcplLite")
}
}
} |
gmdl.dof <- function (sigmahat, n, DoF, yhat)
{
SS <- sigmahat^2
denominator <- DoF * SS
FF <- (yhat)/(DoF * SS)
FF[FF == 0] = Inf
gmdl_temp <- (n/2) * log(SS) + (DoF/2) * log(FF) + (1/2) * log(n)
return(gmdl_temp)
} |
demo_data
demo_data_long <- combiroc_long(data = demo_data) |
clr_saturate <- function(col, shift = 0.5) {
col <- color(col)
if (!(length(shift) == 1 || (length(shift) == length(col)))) {
stop("`shift` must be of length 1 or the same length as `col`.")
}
hsl <- decode_colour(col, to = "hsl")
hsl[, 2] <- pro_transform(hsl[, 2], 100, shift)
rgb <- convert_colour(hsl, "hsl", "rgb")
color(encode_colour(rgb_norm(rgb)))
}
clr_desaturate <- function(col, shift = 0.5) {
col <- color(col)
if (!(length(shift) == 1 || (length(shift) == length(col)))) {
stop("`shift` must be of length 1 or the same length as `col`.")
}
hsl <- decode_colour(col, to = "hsl")
hsl[, 2] <- pro_transform(hsl[, 2], 0, shift)
rgb <- convert_colour(hsl, "hsl", "rgb")
color(encode_colour(rgb_norm(rgb)))
} |
cat("
imput_locf_traj <- function(traj){
if(all(is.na(traj))){
warning("[Imputation:locf] There is only NA on this trajectory, impossible to impute\n")
return(traj)
}else{
if(all(!is.na(traj))){return(traj)}else{}
}
nonMissing <- !is.na(traj)
valNonMissing <- which(nonMissing)
return(traj[c(valNonMissing[1],valNonMissing)][cumsum(nonMissing)+1])
}
imput_locf <- function(longData){
return(t(apply(longData,1,imput_locf_traj)))
}
imput_nocb <- function(longData){
return(imput_locf(longData[,ncol(longData):1,drop=FALSE])[,ncol(longData):1,drop=FALSE])
}
imput_trajMean_traj <- function(traj){
if(all(is.na(traj))){
warning("[Imputation:trajMean] There is only NA on this trajectory, impossible to impute\n")
return(traj)
}else{
if(all(!is.na(traj))){return(traj)}else{}
}
traj[is.na(traj)] <- mean(traj,na.rm=TRUE)
return(traj)
}
imput_trajMean <- function(longData){
return(t(apply(longData,1,imput_trajMean_traj)))
}
imput_trajMedian_traj <- function(traj){
if(all(is.na(traj))){
warning("[Imputation:trajMedian] There is only NA on this trajectory, impossible to impute\n")
return(traj)
}else{
if(all(!is.na(traj))){return(traj)}else{}
}
traj[is.na(traj)] <- median(traj,na.rm=TRUE)
return(traj)
}
imput_trajMedian <- function(longData){
return(t(apply(longData,1,imput_trajMedian_traj)))
}
imput_trajHotDeck_traj <- function(traj){
if(all(is.na(traj))){
warning("[Imputation:trajHotDeck] There is only NA on this trajectory, impossible to impute\n")
return(traj)
}else{
if(all(!is.na(traj))){return(traj)}else{}
}
missing <- is.na(traj)
nbPos <- sum(!missing)
alea <- floor(runif(length(traj)-nbPos,min=1,max=nbPos+1))
traj[missing] <- sapply(alea,function(x)traj[cumsum(!missing)==x & !missing])
return(traj)
}
imput_trajHotDeck <- function(longData){
return(t(apply(longData,1,imput_trajHotDeck_traj)))
}
imput_spline_traj <- function(traj){
if(all(is.na(traj))){
warning("[Imputation:spline] There is only NA on this trajectory, impossible to impute\n")
return(traj)
}else{
if(all(!is.na(traj))){return(traj)}else{}
}
traj <- splinefun(traj)(1:length(traj))
return(traj)
}
imput_spline <- function(longData){
return(t(apply(longData,1,imput_spline_traj)))
} |
coxed.gam <- function(cox.model, newdata=NULL, k=-1, coef=NULL, b.ind=NULL, warn=TRUE) {
if(!is.null(coef)){
y.bs <- cox.model$y[b.ind,1]
failed.bs <- cox.model$y[b.ind,2]
cox.model$coefficients <- coef
}
y <- cox.model$y[,1]
failed <- cox.model$y[,2]
exp.xb <- exp(predict(cox.model, type="lp"))
if(!is.null(coef)) exp.xb.bs <- exp.xb[b.ind]
gam.data <- data.frame(y=y, failed=failed, rank.xb = rank(exp.xb))
if(!is.null(coef)){
gam.data.bs <- data.frame(y=y.bs, failed=failed.bs, rank.xb = rank(exp.xb.bs))
gam.model <- gam(y ~ s(rank.xb, bs = "cr", k = k), data = subset(gam.data.bs, failed == 1))
} else {
gam.model <- gam(y ~ s(rank.xb, bs = "cr", k = k), data = subset(gam.data, failed == 1))
}
gam.data <- dplyr::mutate(gam.data,
rank.y = rank(y),
gam_fit = predict(gam.model, newdata=gam.data),
gam_fit_se = predict(gam.model, newdata=gam.data, se.fit=TRUE)$se.fit,
gam_fit_95lb = gam_fit + qnorm(.025)*gam_fit_se,
gam_fit_95ub = gam_fit + qnorm(.975)*gam_fit_se)
if(!is.null(newdata)){
exp.xb2 <- exp(predict(cox.model, newdata=newdata, type="lp"))
rank.xb <- rank.predict(x=exp.xb2, v=exp.xb, warn=warn)
} else rank.xb <- rank(exp.xb)
expect.duration <- predict(gam.model, newdata = data.frame(rank.xb = rank.xb),
type = "response")
return(list(gam.model = gam.model,
gam.data = gam.data,
exp.dur = expect.duration))
} |
acontext("mixtureKNN data set")
data(mixtureKNN)
mixtureKNN$Bayes.error$text.V1.prop <- 0
mixtureKNN$Bayes.error$text.V2.bottom <- -2
mixtureKNN$other.error$text.V1.prop <- 0
mixtureKNN$Bayes.error$text.V1.error <- -2.6
mixtureKNN$other.error$text.V1.error <- -2.6
classifier.linetypes <- c(
Bayes="dashed",
KNN="solid")
label.colors <- c(
"0"="
"1"="
set.colors <-
c(test="
validation="
Bayes="
train="black")
errorPlot <- ggplot()+
ggtitle("Select number of neighbors")+
theme_bw()+
theme_animint(height=500)+
geom_text(aes(min.neighbors, error.prop,
color=set, label="Bayes"),
showSelected="classifier",
hjust=1,
data=mixtureKNN$Bayes.segment)+
geom_segment(aes(min.neighbors, error.prop,
xend=max.neighbors, yend=error.prop,
color=set, linetype=classifier),
showSelected="classifier",
data=mixtureKNN$Bayes.segment)+
scale_color_manual(values=set.colors, breaks=names(set.colors))+
scale_fill_manual(values=set.colors)+
guides(fill="none", linetype="none")+
scale_linetype_manual(values=classifier.linetypes)+
ylab("Misclassification Errors")+
scale_x_continuous(
"Number of Neighbors",
limits=c(-1, 30),
breaks=c(1, 10, 20, 29))+
geom_ribbon(aes(neighbors, ymin=mean-sd, ymax=mean+sd,
fill=set),
showSelected=c("classifier","set"),
alpha=0.5,
data=mixtureKNN$validation.error)+
geom_line(aes(neighbors, mean, color=set, linetype=classifier),
showSelected="classifier",
data=mixtureKNN$validation.error)+
geom_line(aes(neighbors, error.prop, group=set, color=set,
linetype=classifier),
showSelected="classifier",
data=mixtureKNN$other.error)+
geom_tallrect(aes(xmin=neighbors-1, xmax=neighbors+1),
clickSelects="neighbors",
alpha=0.5,
data=mixtureKNN$validation.error)
errorPlot
scatterPlot <- ggplot()+
ggtitle("Mis-classification errors in train set")+
theme_bw()+
theme_animint(width=500, height=500)+
xlab("Input feature 1")+
ylab("Input feature 2")+
coord_equal()+
scale_color_manual(values=label.colors)+
scale_linetype_manual(values=classifier.linetypes)+
geom_point(aes(V1, V2, color=label),
showSelected="neighbors",
size=0.2,
data=mixtureKNN$show.grid)+
geom_path(aes(V1, V2, group=path.i, linetype=classifier),
showSelected="neighbors",
size=1,
data=mixtureKNN$pred.boundary)+
geom_path(aes(V1, V2, group=path.i, linetype=classifier),
color=set.colors[["test"]],
size=1,
data=mixtureKNN$Bayes.boundary)+
geom_point(aes(V1, V2, color=label,
fill=prediction),
showSelected="neighbors",
size=3,
shape=21,
data=mixtureKNN$show.points)+
scale_fill_manual(values=c(error="black", correct="transparent"))+
geom_text(aes(text.V1.error, text.V2.bottom, label=paste(set, "Error:")),
data=mixtureKNN$Bayes.error,
hjust=0)+
geom_text(aes(text.V1.prop, text.V2.bottom, label=sprintf("%.3f", error.prop)),
data=mixtureKNN$Bayes.error,
hjust=1)+
geom_text(aes(text.V1.error, V2.bottom, label=paste(set, "Error:")),
showSelected="neighbors",
data=mixtureKNN$other.error,
hjust=0)+
geom_text(aes(text.V1.prop, V2.bottom, label=sprintf("%.3f", error.prop)),
showSelected="neighbors",
data=mixtureKNN$other.error,
hjust=1)+
geom_text(aes(V1, V2,
label=paste0(
neighbors,
" nearest neighbor",
ifelse(neighbors==1, "", "s"),
" classifier")),
showSelected="neighbors",
data=mixtureKNN$show.text)
scatterPlot+
facet_wrap("neighbors")+
theme(panel.margin=grid::unit(0, "lines"))
viz.neighbors <- list(
error=errorPlot,
data=scatterPlot,
first=list(neighbors=7)
)
info <- animint2HTML(viz.neighbors)
get_nodes <- function(html=getHTML()){
line.list <- getNodeSet(html, "//g[@class='geom2_segment_error']//line")
rect.list <- getNodeSet(
html, "//svg[@id='plot_error']//rect[@class='border_rect']")
rect.attr.mat <- sapply(rect.list, xmlAttrs)
rect.x <- as.numeric(rect.attr.mat["x",])
rect.width <- as.numeric(rect.attr.mat["width",])
rect.right <- rect.x + rect.width
line.attr.mat <- sapply(line.list, xmlAttrs)
list(
ribbon=getNodeSet(html, "//g[@class='geom3_ribbon_error']//path"),
validation=getNodeSet(html, "//g[@class='geom4_line_error']//path"),
train.test=getNodeSet(html, "//g[@class='geom5_line_error']//path"),
Bayes=line.list,
Bayes.x2=if(is.matrix(line.attr.mat))as.numeric(line.attr.mat["x2",]),
border.right=rect.right,
boundary.KNN=getNodeSet(html, "//g[@class='geom8_path_data']//path"),
boundary.Bayes=getNodeSet(html, "//g[@class='geom9_path_data']//path")
)
}
before <- get_nodes(info$html)
test_that("1 <path> rendered for validation error band", {
expect_equal(length(before$ribbon), 1)
})
test_that("1 <path> rendered for validation error mean", {
expect_equal(length(before$validation), 1)
})
test_that("2 <path> rendered for train/test error", {
expect_equal(length(before$train.test), 2)
})
test_that("1 <line> rendered for Bayes error", {
expect_equal(length(before$Bayes), 1)
})
test_that("Bayes error <line> inside of border_rect", {
expect_less_than(before$Bayes.x2, before$border.right)
})
test_that("6 <path> rendered for KNN boundary", {
expect_equal(length(before$boundary.KNN), 6)
})
test_that("2 <path> rendered for Bayes boundary", {
expect_equal(length(before$boundary.Bayes), 2)
})
clickID("plot_data_classifier_variable_Bayes")
click1 <- get_nodes()
test_that("first click, 1 <path> rendered for validation error band", {
expect_equal(length(click1$ribbon), 1)
})
test_that("first click, 1 <path> rendered for validation error mean", {
expect_equal(length(click1$validation), 1)
})
test_that("first click, 2 <path> rendered for train/test error", {
expect_equal(length(click1$train.test), 2)
})
test_that("first click, Bayes error disappears", {
expect_equal(length(click1$Bayes), 0)
})
test_that("first click, 6 <path> rendered for KNN boundary", {
expect_equal(length(click1$boundary.KNN), 6)
})
test_that("first click, Bayes boundary disappears", {
expect_equal(length(click1$boundary.Bayes), 0)
})
clickID("plot_data_classifier_variable_KNN")
click2 <- get_nodes()
test_that("second click, validation error band disappears", {
expect_equal(length(click2$ribbon), 0)
})
test_that("second click, validation error mean disappears", {
expect_equal(length(click2$validation), 0)
})
test_that("second click, train/test error disappears", {
expect_equal(length(click2$train.test), 0)
})
test_that("second click, Bayes error still gone", {
expect_equal(length(click2$Bayes), 0)
})
test_that("second click, KNN boundary disappears", {
expect_equal(length(click2$boundary.KNN), 0)
})
test_that("second click, Bayes boundary still gone", {
expect_equal(length(click2$boundary.Bayes), 0)
}) |
library(testthat)
source('createTwoKeyData.R')
context("DateComparisons")
test_that("ComparisonOfEqualDates", {
dts <- createDateDataset()
dfTableA <- dts[[1]]
dfTableB <- dts[[2]]
ABcomparison <- rCompare(dfTableA, dfTableB, keys = c("color"))
expect_true(ABcomparison$matches[1] == "DATEA")
expect_true(names(ABcomparison$mismatches)[1] == "DATEB")
expect_true(nrow(ABcomparison$mismatches[[1]]) == 5)
expect_true(all(ABcomparison$mismatches$DATEB$diffAB < 0))
expect_true(all(ABcomparison$mismatches$DATEB$diffAB > -21))
})
test_that("ComparisonOfPOSIXDates", {
dts <- createDateDataset()
dfTableA <- dts[[1]]
dfTableB <- dts[[2]]
dfTableA$dateA <- as.POSIXct.Date(dfTableA$dateA)
dfTableA$dateB <- as.POSIXct.Date(dfTableA$dateB)
dfTableB$dateA <- as.POSIXct.Date(dfTableB$dateA)
dfTableB$dateB <- as.POSIXct.Date(dfTableB$dateB)
ABcomparison <- rCompare(dfTableA, dfTableB, keys = c("color"))
expect_true(ABcomparison$matches[1] == "DATEA")
expect_true(names(ABcomparison$mismatches)[1] == "DATEB")
expect_true(nrow(ABcomparison$mismatches[[1]]) == 5)
expect_true(all(ABcomparison$mismatches$DATEB$diffAB < 0))
expect_true(all(ABcomparison$mismatches$DATEB$diffAB > -21))
})
test_that("ComparisonOfMixedDates", {
dts <- createDateDataset()
dfTableA <- dts[[1]]
dfTableB <- dts[[2]]
dfTableA$dateA <- as.POSIXct.Date(dfTableA$dateA)
dfTableA$dateB <- as.POSIXct.Date(dfTableA$dateB)
ABcomparison <- rCompare(dfTableA, dfTableB, keys = c("color"))
expect_true(length(ABcomparison$matches) == 0)
expect_true(names(ABcomparison$mismatches)[1] == "DATEA")
expect_true(names(ABcomparison$mismatches)[2] == "DATEB")
expect_true(all(ABcomparison$mismatches$DATEA$diffAB == ""))
expect_true(all(ABcomparison$mismatches$DATEB$diffAB == ""))
dfTableB$dateA <- as.POSIXct.Date(dfTableB$dateA)
ABcomparison <- rCompare(dfTableA, dfTableB, keys = c("color"))
expect_true(ABcomparison$matches[1] == "DATEA")
expect_true(names(ABcomparison$mismatches)[1] == "DATEB")
expect_true(all(ABcomparison$mismatches$DATEB$diffAB == ""))
dfTableB$dateB <- as.POSIXct.Date(dfTableB$dateB)
ABcomparison <- rCompare(dfTableA, dfTableB, keys = c("color"))
expect_true(ABcomparison$matches[1] == "DATEA")
expect_true(names(ABcomparison$mismatches)[1] == "DATEB")
expect_true(all(ABcomparison$mismatches$DATEB$diffAB < 0))
expect_true(all(ABcomparison$mismatches$DATEB$diffAB > -21))
}) |
"sequence_table_repl" |
register_class("tis")
ts_tis_dts <- function(x) {
stopifnot(requireNamespace("tis"))
x.ts <- ts_ts(x)
x.tis <- tis::as.tis(x.ts)
colnames(x.tis) <- colnames(x.ts)
x.tis
}
ts_dts.tis <- function(x) {
stopifnot(requireNamespace("tis"))
ts_dts(as.ts(x))
}
ts_tis <- function(x) {
stopifnot(ts_boxable(x))
if (relevant_class(x) == "tis") {
return(x)
}
ts_tis_dts(ts_dts(x))
} |
expect_bernoulli <- function(object, J, ok, epsilon=1e-3,...) {
act <- testthat::quasi_label(rlang::enquo(object), arg = "object")
if (is.null(colnames(J)))
testthat::fail("J must have column names")
if (length(ok)>1)
testthat::fail("ok must be one string")
if (!any(colnames(J)==ok))
testthat::fail("At least one of the column names of J must match the string in ok")
{
o <- order(J[1,])
if (J[1,o[1]]>0) testthat::fail("Buckets must cover [0,1]")
last <- J[2,o[1]]
for (i in 2:(dim(J)[2])){
if (last<=J[1,o[i]])
testthat::fail("Buckets must be overlapping")
last <- max(last,J[2,o[i]])
}
if (last<1)
testthat::fail("Buckets must cover [0,1]")
}
res <- simctest::mctest(gen=object,J=J, epsilon=epsilon,...)
if (res$decision ==ok){
return(invisible(act$val))
}
message <- sprintf("Test returned bucket [%g,%g], called '%s', not a bucket called '%s'.",res$decision.interval[1],res$decision.interval[2],res$decision, ok)
testthat::fail(message)
} |
plot_FV_post_beta_kmom=function(data,years=10,lwd=1.5,lty=1){
appo=rep(NA,years)
for (i in 1:years) {
appo[i]=FV_post_beta_kmom(data,i)
}
appo[1]=1
anni=c(1:years)
plot(appo,type="b",col="red",lwd=lwd, lty=lty, xlim=c(0,years+1),ylim=c(min(appo),max(appo)),xlab="Time", ylab="Final Expexted Value",main="Final Expected Value (annuity-immediate)")
if (length(anni)<20) text(anni+0.2, appo, round(appo, 2), cex=0.7)
} |
NULL
deprecated <- function(old, new) {
assign(old, new, envir = asNamespace(packageName()))
}
deprecated("add.edges", add_edges)
deprecated("add.vertex.shape", add_shape)
deprecated("add.vertices", add_vertices)
deprecated("adjacent.triangles", count_triangles)
deprecated("articulation.points", articulation_points)
deprecated("aging.prefatt.game", sample_pa_age)
deprecated("aging.ba.game", sample_pa_age)
deprecated("aging.barabasi.game", sample_pa_age)
deprecated("alpha.centrality", alpha_centrality)
deprecated("are.connected", are_adjacent)
deprecated("asPhylo", as_phylo)
deprecated("asPhylo.communities", as_phylo.communities)
deprecated("asPhylo.igraphHRG", as_phylo.igraphHRG)
deprecated("assortativity.degree", assortativity_degree)
deprecated("assortativity.nominal", assortativity_nominal)
deprecated("asymmetric.preference.game", sample_asym_pref)
deprecated("authority.score", authority_score)
deprecated("autocurve.edges", curve_multiple)
deprecated("average.path.length", mean_distance)
deprecated("ba.game", sample_pa)
deprecated("barabasi.game", sample_pa)
deprecated("betweenness.estimate", estimate_betweenness)
deprecated("biconnected.components", biconnected_components)
deprecated("bipartite.mapping", bipartite_mapping)
deprecated("bipartite.projection", bipartite_projection)
deprecated("bipartite.projection.size", bipartite_projection_size)
deprecated("bipartite.random.game", sample_bipartite)
deprecated("blockGraphs", graphs_from_cohesive_blocks)
deprecated("bonpow", power_centrality)
deprecated("callaway.traits.game", sample_traits_callaway)
deprecated("canonical.permutation", canonical_permutation)
deprecated("centralization.betweenness", centr_betw)
deprecated("centralization.betweenness.tmax", centr_betw_tmax)
deprecated("centralization.closeness", centr_clo)
deprecated("centralization.closeness.tmax", centr_clo_tmax)
deprecated("centralization.degree", centr_degree)
deprecated("centralization.degree.tmax", centr_degree_tmax)
deprecated("centralization.evcent", centr_eigen)
deprecated("centralization.evcent.tmax", centr_eigen_tmax)
deprecated("centralize.scores", centralize)
deprecated("cited.type.game", sample_cit_types)
deprecated("citing.cited.type.game", sample_cit_cit_types)
deprecated("clique.number", clique_num)
deprecated("closeness.estimate", estimate_closeness)
deprecated("cluster.distribution", component_distribution)
deprecated("clusters", components)
deprecated("code.length", code_len)
deprecated("cohesive.blocks", cohesive_blocks)
deprecated("connect.neighborhood", connect)
deprecated("contract.vertices", contract)
deprecated("convex.hull", convex_hull)
deprecated("count.multiple", count_multiple)
deprecated("cutat", cut_at)
deprecated("decompose.graph", decompose)
deprecated("degree.distribution", degree_distribution)
deprecated("degree.sequence.game", sample_degseq)
deprecated("delete.edges", delete_edges)
deprecated("delete.vertices", delete_vertices)
deprecated("dendPlot", plot_dendrogram)
deprecated("dendPlot.communities", plot_dendrogram.communities)
deprecated("dendPlot.igraphHRG", plot_dendrogram.igraphHRG)
deprecated("dominator.tree", dominator_tree)
deprecated("dyad.census", dyad_census)
deprecated("ecount", gsize)
deprecated("edge.betweenness", edge_betweenness)
deprecated("edge.betweenness.community", cluster_edge_betweenness)
deprecated("edge.betweenness.estimate", estimate_edge_betweenness)
deprecated("edge.connectivity", edge_connectivity)
deprecated("edge.disjoint.paths", edge_disjoint_paths)
deprecated("establishment.game", sample_traits)
deprecated("evcent", eigen_centrality)
deprecated("farthest.nodes", farthest_vertices)
deprecated("fastgreedy.community", cluster_fast_greedy)
deprecated("forest.fire.game", sample_forestfire)
deprecated("get.adjedgelist", as_adj_edge_list)
deprecated("get.adjlist", as_adj_list)
deprecated("get.adjacency", as_adjacency_matrix)
deprecated("get.data.frame", as_data_frame)
deprecated("get.edge.attribute", edge_attr)
deprecated("get.edgelist", as_edgelist)
deprecated("get.graph.attribute", graph_attr)
deprecated("get.incidence", as_incidence_matrix)
deprecated("get.stochastic", stochastic_matrix)
deprecated("get.vertex.attribute", vertex_attr)
deprecated("graph.adhesion", adhesion)
deprecated("graph.adjacency", graph_from_adjacency_matrix)
deprecated("graph.adjlist", graph_from_adj_list)
deprecated("graph.atlas", graph_from_atlas)
deprecated("graph.automorphisms", automorphisms)
deprecated("graph.bfs", bfs)
deprecated("graph.bipartite", make_bipartite_graph)
deprecated("graph.cohesion", cohesion)
deprecated("graph.complementer", complementer)
deprecated("graph.compose", compose)
deprecated("graph.coreness", coreness)
deprecated("graph.data.frame", graph_from_data_frame)
deprecated("graph.de.bruijn", make_de_bruijn_graph)
deprecated("graph.density", edge_density)
deprecated("graph.disjoint.union", disjoint_union)
deprecated("graph.dfs", dfs)
deprecated("graph.difference", difference)
deprecated("graph.diversity", diversity)
deprecated("graph.edgelist", graph_from_edgelist)
deprecated("graph.eigen", spectrum)
deprecated("graph.empty", make_empty_graph)
deprecated("graph.extended.chordal.ring", make_chordal_ring)
deprecated("graph.formula", graph_from_literal)
deprecated("graph.full", make_full_graph)
deprecated("graph.full.bipartite", make_full_bipartite_graph)
deprecated("graph.full.citation", make_full_citation_graph)
deprecated("graph.graphdb", graph_from_graphdb)
deprecated("graph.incidence", graph_from_incidence_matrix)
deprecated("graph.isocreate", graph_from_isomorphism_class)
deprecated("graph.kautz", make_kautz_graph)
deprecated("graph.knn", knn)
deprecated("graph.laplacian", laplacian_matrix)
deprecated("graph.lattice", make_lattice)
deprecated("graph.lcf", graph_from_lcf)
deprecated("graph.maxflow", max_flow)
deprecated("graph.mincut", min_cut)
deprecated("graph.motifs", motifs)
deprecated("graph.motifs.est", sample_motifs)
deprecated("graph.motifs.no", count_motifs)
deprecated("graph.neighborhood", make_ego_graph)
deprecated("graph.star", make_star)
deprecated("graph.strength", strength)
deprecated("graph.tree", make_tree)
deprecated("graph.union", union.igraph)
deprecated("graph.ring", make_ring)
deprecated("graphlets.candidate.basis", graphlet_basis)
deprecated("graphlets.project", graphlet_proj)
deprecated("growing.random.game", sample_growing)
deprecated("grg.game", sample_grg)
deprecated("has.multiple", any_multiple)
deprecated("hrg.consensus", consensus_tree)
deprecated("hrg.create", hrg)
deprecated("hrg.dendrogram", hrg_tree)
deprecated("hrg.game", sample_hrg)
deprecated("hrg.fit", fit_hrg)
deprecated("hrg.predict", predict_edges)
deprecated("hub.score", hub_score)
deprecated("igraph.arpack.default", arpack_defaults)
deprecated("igraph.console", console)
deprecated("igraph.eigen.default", eigen_defaults)
deprecated("igraph.sample", sample_seq)
deprecated("igraph.version", igraph_version)
deprecated("igraphdemo", igraph_demo)
deprecated("igraphtest", igraph_test)
deprecated("independence.number", ivs_size)
deprecated("independent.vertex.sets", ivs)
deprecated("infomap.community", cluster_infomap)
deprecated("induced.subgraph", induced_subgraph)
deprecated("interconnected.islands.game", sample_islands)
deprecated("is.bipartite", is_bipartite)
deprecated("is.chordal", is_chordal)
deprecated("is.connected", is_connected)
deprecated("is.dag", is_dag)
deprecated("is.degree.sequence", is_degseq)
deprecated("is.directed", is_directed)
deprecated("is.graphical.degree.sequence", is_graphical)
deprecated("is.hierarchical", is_hierarchical)
deprecated("is.igraph", is_igraph)
deprecated("is.loop", which_loop)
deprecated("is.matching", is_matching)
deprecated("is.maximal.matching", is_max_matching)
deprecated("is.minimal.separator", is_min_separator)
deprecated("is.multiple", which_multiple)
deprecated("is.mutual", which_mutual)
deprecated("is.named", is_named)
deprecated("is.separator", is_separator)
deprecated("is.simple", is_simple)
deprecated("is.weighted", is_weighted)
deprecated("k.regular.game", sample_k_regular)
deprecated("label.propagation.community", cluster_label_prop)
deprecated("largest.cliques", largest_cliques)
deprecated("largest.independent.vertex.sets", largest_ivs)
deprecated("lastcit.game", sample_last_cit)
deprecated("layout.auto", layout_nicely)
deprecated("layout.bipartite", layout_as_bipartite)
deprecated("layout.davidson.harel", layout_with_dh)
deprecated("layout.drl", layout_with_drl)
deprecated("layout.gem", layout_with_gem)
deprecated("layout.graphopt", layout_with_graphopt)
deprecated("layout.grid", layout_on_grid)
deprecated("layout.mds", layout_with_mds)
deprecated("layout.merge", merge_coords)
deprecated("layout.norm", norm_coords)
deprecated("layout.star", layout_as_star)
deprecated("layout.sugiyama", layout_with_sugiyama)
deprecated("leading.eigenvector.community", cluster_leading_eigen)
deprecated("line.graph", make_line_graph)
deprecated("list.edge.attributes", edge_attr_names)
deprecated("list.graph.attributes", graph_attr_names)
deprecated("list.vertex.attributes", vertex_attr_names)
deprecated("maxcohesion", max_cohesion)
deprecated("maximal.cliques", max_cliques)
deprecated("maximal.cliques.count", count_max_cliques)
deprecated("maximal.independent.vertex.sets", maximal_ivs)
deprecated("minimal.st.separators", min_st_separators)
deprecated("maximum.bipartite.matching", max_bipartite_match)
deprecated("maximum.cardinality.search", max_cardinality)
deprecated("minimum.size.separators", min_separators)
deprecated("minimum.spanning.tree", mst)
deprecated("mod.matrix", modularity_matrix)
deprecated("multilevel.community", cluster_louvain)
deprecated("neighborhood", ego)
deprecated("neighborhood.size", ego_size)
deprecated("nexus.get", nexus_get)
deprecated("nexus.info", nexus_info)
deprecated("nexus.list", nexus_list)
deprecated("nexus.search", nexus_search)
deprecated("no.clusters", count_components)
deprecated("optimal.community", cluster_optimal)
deprecated("page.rank", page_rank)
deprecated("path.length.hist", distance_table)
deprecated("permute.vertices", permute)
deprecated("piecewise.layout", layout_components)
deprecated("plotHierarchy", plot_hierarchy)
deprecated("power.law.fit", fit_power_law)
deprecated("preference.game", sample_pref)
deprecated("read.graph", read_graph)
deprecated("remove.edge.attribute", delete_edge_attr)
deprecated("remove.graph.attribute", delete_graph_attr)
deprecated("remove.vertex.attribute", delete_vertex_attr)
deprecated("running.mean", running_mean)
deprecated("sbm.game", sample_sbm)
deprecated("scgGrouping", scg_group)
deprecated("scgNormEps", scg_eps)
deprecated("scgSemiProjectors", scg_semi_proj)
deprecated("set.edge.attribute", set_edge_attr)
deprecated("set.graph.attribute", set_graph_attr)
deprecated("set.vertex.attribute", set_vertex_attr)
deprecated("shortest.paths", distances)
deprecated("showtrace", show_trace)
deprecated("spinglass.community", cluster_spinglass)
deprecated("stCuts", st_cuts)
deprecated("stMincuts", st_min_cuts)
deprecated("static.fitness.game", sample_fitness)
deprecated("static.power.law.game", sample_fitness_pl)
deprecated("subgraph.centrality", subgraph_centrality)
deprecated("tkplot.canvas", tk_canvas)
deprecated("tkplot.center", tk_center)
deprecated("tkplot.close", tk_close)
deprecated("tkplot.export.postscript", tk_postscript)
deprecated("tkplot.fit.to.screen", tk_fit)
deprecated("tkplot.getcoords", tk_coords)
deprecated("tkplot.off", tk_off)
deprecated("tkplot.reshape", tk_reshape)
deprecated("tkplot.rotate", tk_rotate)
deprecated("tkplot.setcoords", tk_set_coords)
deprecated("topological.sort", topo_sort)
deprecated("triad.census", triad_census)
deprecated("unfold.tree", unfold_tree)
deprecated("vcount", gorder)
deprecated("vertex.connectivity", vertex_connectivity)
deprecated("vertex.disjoint.paths", vertex_disjoint_paths)
deprecated("walktrap.community", cluster_walktrap)
deprecated("watts.strogatz.game", sample_smallworld)
deprecated("write.graph", write_graph)
deprecated("graph.famous", make_famous_graph)
deprecated("igraph.from.graphNEL", graph_from_graphnel)
deprecated("igraph.to.graphNEL", as_graphnel)
deprecated("getIgraphOpt", igraph_opt)
deprecated("igraph.options", igraph_options)
deprecated("graph.intersection", intersection)
deprecated("exportPajek", export_pajek)
deprecated("get.diameter", get_diameter)
deprecated("get.all.shortest.paths", all_shortest_paths)
deprecated("get.shortest.paths", shortest_paths)
deprecated("graph", make_graph)
deprecated("vertex.shapes", shapes)
deprecated("igraph.shape.noclip", shape_noclip)
deprecated("igraph.shape.noplot", shape_noplot)
deprecated("create.communities", make_clusters) |
tol <- 1e-6
data(minke, package="Distance")
minke$Region.Label <- as.factor(minke$Region.Label)
whale.trunc <- 1.5
minke_noobj <- minke
minke$object <- NA
minke$object[!is.na(minke$distance)] <- 1:nrow(minke[!is.na(minke$distance),])
make_old_summ_cluster <- function(object){
object$Region <- as.factor(object$Region)
object$CoveredArea <- object$Covered_area
object$se.ER <- sqrt(object$ER_var)
object$cv.ER <- object$ER_CV
object$se.mean <- sqrt(object$group_var)
object$mean.size <- object$group_mean
class(object) <- "data.frame"
summ <- object[, c("Region", "Area", "CoveredArea", "Effort", "n", "k",
"ER", "se.ER", "cv.ER")]
return(summ)
}
make_old_abund_individual <- function(object){
object$Label <- as.factor(object$Region)
object$Region <- NULL
object$Estimate <- object$Abundance
object$cv <- object$Abundance_CV
object$se <- object$Abundance_se
object$lcl <- object$LCI
object$ucl <- object$UCI
object$df <- object$df
class(object) <- "data.frame"
object[, c("Label", "Estimate", "se", "cv", "lcl", "ucl", "df")]
}
context("minke")
test_that("South works",{
skip_on_cran()
whales <- minke[minke$Region.Label=="South",]
dat <- unflatten(whales)
dat$obs$Region.Label <- NULL
dat$sample$Region <- dat$sample$Region.Label
dat$region$Region <- dat$region$Region.Label
dat$sample$Region.Label <- NULL
dat$region$Region.Label <- NULL
whale.full.strat1 <- ds(whales, truncation=whale.trunc,
key="hr", adjustment=NULL)
whale.full.strat1$ddf$data$Region.Label <- NULL
fs_st1 <- with(dat, dht2(whale.full.strat1$ddf, obs, sample, region,
strat_formula=~Region))
whale.full.strat1$dht$individuals$summary$k <-
whale.full.strat1$dht$individuals$summary$k[1]
expect_equal(whale.full.strat1$dht$individuals$summary,
make_old_summ_cluster(fs_st1), tolerance=tol)
old <- whale.full.strat1$dht$individuals$N
old$Estimate <- as.numeric(old$Estimate)
old$cv <- as.numeric(old$cv)
old$ucl <- as.numeric(old$ucl)
old$lcl <- as.numeric(old$lcl)
old$df <- as.numeric(old$df)
old$Label <- as.factor("South")
expect_equal(old, make_old_abund_individual(fs_st1), tolerance=tol)
})
test_that("North works",{
skip_on_cran()
whales <- minke[minke$Region.Label=="North",]
dat <- unflatten(whales)
dat$obs$Region.Label <- NULL
dat$sample$Region <- dat$sample$Region.Label
dat$region$Region <- dat$region$Region.Label
dat$sample$Region.Label <- NULL
dat$region$Region.Label <- NULL
whale.full.strat1 <- ds(whales, truncation=whale.trunc,
key="hr", adjustment=NULL)
whale.full.strat1$ddf$data$Region.Label <- NULL
fs_st1 <- with(dat, dht2(whale.full.strat1$ddf, obs, sample, region,
strat_formula=~Region))
whale.full.strat1$dht$individuals$summary$k <-
whale.full.strat1$dht$individuals$summary$k[1]
expect_equal(whale.full.strat1$dht$individuals$summary,
make_old_summ_cluster(fs_st1), tolerance=tol)
old <- whale.full.strat1$dht$individuals$N
old$Estimate <- as.numeric(old$Estimate)
old$cv <- as.numeric(old$cv)
old$ucl <- as.numeric(old$ucl)
old$lcl <- as.numeric(old$lcl)
old$df <- as.numeric(old$df)
old$Label <- as.factor("North")
expect_equal(old, make_old_abund_individual(fs_st1), tolerance=tol)
})
test_that("Combined works",{
skip_on_cran()
whales <- minke
whales$Region.Label <- as.factor("Total")
whales$Area <- sum(unique(whales$Area))
dat <- unflatten(whales)
dat$obs$Region.Label <- NULL
dat$sample$Region <- dat$sample$Region.Label
dat$region$Region <- dat$region$Region.Label
dat$sample$Region.Label <- NULL
dat$region$Region.Label <- NULL
whale.full.strat1 <- ds(whales, truncation=whale.trunc,
key="hr", adjustment=NULL)
whale.full.strat1$ddf$data$Region.Label <- NULL
fs_st1 <- with(dat, dht2(whale.full.strat1$ddf, obs, sample,
region, strat_formula=~Region))
whale.full.strat1$dht$individuals$summary$k <-
whale.full.strat1$dht$individuals$summary$k[1]
expect_equal(whale.full.strat1$dht$individuals$summary,
make_old_summ_cluster(fs_st1), tolerance=tol)
old <- whale.full.strat1$dht$individuals$N
old$Estimate <- as.numeric(old$Estimate)
old$cv <- as.numeric(old$cv)
old$ucl <- as.numeric(old$ucl)
old$lcl <- as.numeric(old$lcl)
old$df <- as.numeric(old$df)
old$Label <- as.factor(old$Label)
expect_equal(old, make_old_abund_individual(fs_st1), tolerance=tol)
})
test_that("stratification", {
skip_on_cran()
whales <- minke
cp <- seq(0, 1.5, length=8)
expect_warning(wmr <- ds(whales, truncation=whale.trunc,
key="hr", adjustment=NULL, cutpoints=cp),
"Some distances were outside bins and have been removed.")
expect_warning(whale.full.strat1 <- ds(whales, truncation=whale.trunc,
key="hr", adjustment=NULL,
cutpoints=cp),
"Some distances were outside bins and have been removed.")
result <- ddf(dsmodel = ~mcds(key = "hr", formula = ~1),
data = whale.full.strat1$ddf$data, method = "ds",
meta.data = list(width = 1.5, binned=TRUE, breaks=cp),
control=list(initial=list(shape=log(2.483188),
scale=log(0.7067555)),
nofit=TRUE))
whale.full.strat1 <- result
fs_st1 <- dht2(whale.full.strat1, flatfile=whales,
strat_formula=~Region.Label)
expect_equal(fs_st1$Abundance, c(12564, 3768, 16333), tol=1e-3)
expect_equal(fs_st1$LCI, c(5658, 2239, 8619), tol=1e-3)
expect_equal(fs_st1$UCI, c(27901, 6343, 30949), tol=1e-3)
expect_equal(fs_st1$ER_CV[1:2], c(36.54, 22.48)/100, tol=1e-2)
expect_equal(fs_st1$Abundance_CV, c(38.31, 25.27, 30.82)/100, tol=1e-2)
expect_equal(fs_st1$df, c(13.29, 18.97, 15.83), tol=1e-2)
})
test_that("flat minke works", {
skip_on_cran()
strat.spec <- ds(minke_noobj, key="hr", formula=~Region.Label, tru=1.5)
fromdht2 <- dht2(strat.spec, flatfile=minke_noobj,
strat_formula=~Region.Label)
expect_equal(strat.spec$dht$individuals$N$Estimate,
fromdht2$Abundance)
expect_equal(strat.spec$dht$individuals$N$se,
fromdht2$Abundance_se, tol=1e-4)
})
test_that("minke dht vs dht2", {
skip_on_cran()
uf <- unflatten(minke)
mfit <- ds(minke, key="hr", formula=~Region.Label, tru=1.5)
dht_old <- dht(mfit$ddf, uf$region.table, uf$sample.table,
options=list(ervar="R2", varflag=1))
fromdht2 <- dht2(mfit, flatfile=minke,
strat_formula=~Region.Label)
expect_equal(dht_old$individuals$N$Estimate,
fromdht2$Abundance)
expect_equal(dht_old$individuals$N$se,
fromdht2$Abundance_se, tol=1e-4)
dht_old <- dht(mfit$ddf, uf$region.table, uf$sample.table,
options=list(ervar="R2", varflag=2))
fromdht2 <- dht2(mfit, flatfile=minke, strat_formula=~Region.Label, innes=TRUE)
expect_equal(dht_old$individuals$N$Estimate,
fromdht2$Abundance)
expect_equal(dht_old$individuals$N$se,
fromdht2$Abundance_se, tol=1e-4)
})
test_that("area=0, flat minke works", {
skip_on_cran()
minke_noobj$Area <- 0
strat.spec <- ds(minke_noobj, key="hr", formula=~Region.Label, tru=1.5)
fromdht2 <- dht2(strat.spec, flatfile=minke_noobj,
strat_formula=~Region.Label)
expect_equal(strat.spec$dht$individuals$D$Estimate,
fromdht2$Abundance)
expect_equal(strat.spec$dht$individuals$D$se,
fromdht2$Abundance_se, tol=1e-4)
expect_equal(strat.spec$dht$individuals$summary$se.ER, sqrt(fromdht2$ER_var),
tol=1e-3)
}) |
calcul_tx_evol_global <-
function(data,var1,var2)
{
msg_error1<-msg_error2<-msg_error3 <- NULL
if(any(class(data)!="data.frame")) msg_error1 <- "Les donnees doivent etre dans un data.frame / "
if(!any(names(data) %in% var1)) msg_error2 <- "La variable identifiant les donnees n'existe pas dans la table des donnees / "
if(!any(names(data) %in% var2)) msg_error3 <- "La variable identifiant les donnees n'existe pas dans la table des donnees / "
if(any(!is.null(msg_error1),!is.null(msg_error2),!is.null(msg_error3)))
{
stop(simpleError(paste0(msg_error1,msg_error2,msg_error3)))
}
if(any(data[,var1] %in% 0))
{
data[data[,var1] %in% 0,var1] <- 0.0001
}
data$TEG <- ((data[,var2]-data[,var1])/data[,var1])*100
return(data)
} |
getLocData <-
function(country=NULL,StudyUnitId=NULL){
if(!is.null(StudyUnitId)&!is.null(country)) stop('Cannot use both StudyUnitId and country at the same time')
out <- runURL(paste('?id=', StudyUnitId,
'&country=', country, sep=''), 'l')
if(length(out)==0){
if(!is.null(StudyUnitId)) warning('No Data returned for this StudyUnitId(s).')
if(!is.null(country)) warning('No Data returned for this country(s). Ensure you have capitalised appropriately')
}
return(out)
} |
dtt_month_decimal <- function(x, ...) {
UseMethod("dtt_month_decimal")
}
dtt_month_decimal.Date <- function(x, ...) {
dtt_month(x) + (dtt_day_decimal(x) - 1) / dtt_days_in_month(x)
}
dtt_month_decimal.POSIXct <- function(x, ...) {
dtt_month(x) + (dtt_day_decimal(x) - 1) / dtt_days_in_month(x)
} |
getmin=function(lambda,cvm,cvsd){
cvmin=min(cvm,na.rm=TRUE)
idmin=cvm<=cvmin
lambda.min=max(lambda[idmin],na.rm=TRUE)
idmin=match(lambda.min,lambda)
semin=(cvm+cvsd)[idmin]
idmin=cvm<=semin
lambda.1se=max(lambda[idmin],na.rm=TRUE)
list(lambda.min=lambda.min,lambda.1se=lambda.1se)
}
|
test_that("can retrieve multiple users", {
users <- c("hadleywickham", "jennybryan")
out <- get_favorites(users, n = 20)
expect_s3_class(out, "data.frame")
expect_true(is.character(out$created_at))
expect_equal(unique(out$favorited_by), users)
})
test_that("get_favorites returns tweets data", {
n <- 100
x <- get_favorites("kearneymw", n = n)
expect_equal(is.data.frame(x), TRUE)
expect_named(x)
expect_true("id" %in% names(x))
expect_gt(nrow(x), 10)
expect_gt(ncol(x), 15)
expect_true(is.data.frame(users_data(x)))
})
test_that("favorites warns on a locked user", {
expect_warning(gtf <- get_favorites("515880511"),
"Skipping unauthorized account: 515880511")
})
test_that("favorites warns on a banned user", {
expect_warning(gtf <- get_favorites("realdonaldtrump"),
"Skipping unauthorized account: realdonaldtrump")
})
test_that("favorites warns on a locked user but continues", {
expect_warning(gtf <- get_favorites(c("515880511" = "bhs928",
"no_idea" = "Lluis_Revilla")),
"Skipping unauthorized account: bhs928")
expect_gt(nrow(gtf), 2)
expect_true(all(gtf$favorited_by == "Lluis_Revilla"))
}) |
draw.steps = function(
slice,
start,
end,
startColumns = "start",
endColumns = "end",
maxDepth = 100,
label = TRUE,
labelStrand = FALSE,
labelCex = 1,
labelSrt = 0,
labelAdj = "center",
labelOverflow = TRUE,
labelFamily = "sans",
colorVal = "
colorFun = function() NULL,
border = "
cex.lab = 1,
spacing = 0.1,
bty = "o",
...
) {
if(is.numeric(start)) start <- as.integer(start)
if(is.numeric(end)) end <- as.integer(end)
if(!is.integer(start)) stop("'start' must be integer or numeric")
if(!is.integer(end)) stop("'end' must be integer or numeric")
if(!is.data.frame(slice)) stop("'slice' must be a data.frame")
if(!"start" %in% names(slice)) stop("'slice' needs a 'start' column")
if(!"end" %in% names(slice)) stop("'slice' needs a 'end' column")
draw.bg(
start = start,
end = end,
...
)
errorMessage <- NA
if(nrow(slice) == 0) {
errorMessage <- "No feature in the region"
} else {
boxes <- data.frame(
start.plot = as.integer(slice[[ startColumns[1] ]]),
end.plot = as.integer(slice[[ endColumns[1] ]]),
label = slice$name,
stringsAsFactors = FALSE
)
boxes <- yline(
boxes = boxes,
start = start,
end = end,
label = label,
labelStrand = labelStrand,
labelCex = labelCex,
labelSrt = labelSrt,
labelAdj = labelAdj,
labelOverflow = labelOverflow,
maxDepth = maxDepth
)
if(is(boxes, "error")) {
errorMessage <- boxes
} else {
slice$plotLine <- boxes$yline
maxLine <- max(boxes$yline) + 1L
if(is.na(colorVal)) {
environment(colorFun) <- environment()
color <- colorFun()
} else {
color <- rep(colorVal, nrow(slice))
}
if(identical(border, "color")) border <- color
x <- NULL
for(i in 1:length(startColumns)) x <- cbind(x, slice[[ startColumns[i] ]], slice[[ startColumns[i] ]])
for(i in length(endColumns):1) x <- cbind(x, slice[[ endColumns[i] ]], slice[[ endColumns[i] ]])
y <- NULL
step <- 1 / length(startColumns)
for(i in 1:length(startColumns)) y <- c(y, step*(i-1), step*i)
step <- 1 / length(endColumns)
for(i in length(endColumns):1) y <- c(y, step*i, step*(i-1))
for(i in 1:nrow(slice)) {
graphics::polygon(
x = x[i,],
y = (y * (1 - spacing) + spacing / 2 + slice[i,"plotLine"]) / maxLine,
border = border,
col = color[i]
)
}
if(isTRUE(label)) {
charHeight <- graphics::yinch(graphics::par("cin")[2]) * labelCex
graphics::rect(
xleft = boxes$start.lab,
xright = boxes$end.lab,
ybottom = (boxes$yline + 0.1) / maxLine,
ytop = (boxes$yline + 0.1) / maxLine + charHeight,
col = "
border = border
)
if(isTRUE(labelStrand)) {
boxes[ boxes$strand == "-" , "label" ] <- sprintf("< %s", boxes[ boxes$strand == "-" , "label" ])
boxes[ boxes$strand == "+" , "label" ] <- sprintf("%s >", boxes[ boxes$strand == "+" , "label" ])
}
args <- with(
boxes[ (isTRUE(label) && isTRUE(labelOverflow)) | !boxes$overflow ,],
list(
x = (boxes$start.lab + boxes$end.lab) / 2,
y = (boxes$yline + 0.1) / maxLine + charHeight/2,
label = label,
col = "
adj = c(0.5, 0.5),
cex = labelCex,
srt = labelSrt
)
)
if(labelFamily == "Hershey") { args$vfont <- c("sans serif", "bold")
} else { args$family <- labelFamily
}
do.call(graphics::text, args)
}
}
}
if(!is.na(errorMessage)) {
graphics::text(
x = mean(graphics::par("usr")[1:2]),
y = mean(graphics::par("usr")[3:4]),
label = errorMessage,
col = "
adj = c(0.5, 0.5),
cex = cex.lab
)
}
graphics::box(
which = "plot",
col = "
bty = bty
)
} |
vis.concurvity <- function(model, type="estimate"){
cc <- concurvity(model, full=FALSE)[[type]]
diag(cc) <- NA
layout(matrix(1:2, ncol=2), widths=c(5,1))
opar <- par(mar=c(5, 6, 5, 0) + 0.1)
image(z=cc, x=1:ncol(cc), y=1:nrow(cc), ylab="", xlab="",
axes=FALSE, asp=1, zlim=c(0,1))
axis(1, at=1:ncol(cc), labels = colnames(cc), las=2, lwd=0)
axis(2, at=1:nrow(cc), labels = rownames(cc), las=2, lwd=0)
opar <- par(mar=c(5, 0, 4, 3) + 0.1)
image(t(matrix(rep(seq(0, 1, len=100), 2), ncol=2)),
x=1:3, y=1:101, zlim=c(0,1), axes=FALSE, xlab="", ylab="")
axis(4, at=seq(1,101,len=5), labels = round(seq(0,1,len=5),1), las=2)
par(opar)
} |
mw_multipart <- function(type = "multipart/form-data") {
type
function(req, res) {
ct <- req$get_header("Content-Type") %||% ""
if (!any(vapply(
paste0("^", type),
function(x) grepl(x, ct),
logical(1)))) return("next")
parts <- str_trim(strsplit(ct, ";", fixed = TRUE)[[1]])
bnd <- grep("boundary=", parts, value = TRUE)[1]
if (is.na(bnd)) return("next")
bnd <- sub("^boundary=", "", bnd)
tryCatch({
mp <- parse_multipart(req$.body, bnd)
req$form <- list()
req$files <- list()
for (p in mp) {
if (is.null(p$filename)) {
req$form[[p$name]] <- rawToChar(p$value)
} else {
req$files[[p$name]] <- list(filename = p$filename, value = p$value)
}
}
}, error = function(err) NULL)
"next"
}
}
parse_multipart <- function(body, boundary) {
boundary <- paste0("--", boundary)
boundary_length <- nchar(boundary)
indexes <- grepRaw(boundary, body, fixed = TRUE, all = TRUE)
if (!length(indexes)) stop("Boundary was not found in the body.")
if (length(indexes) == 1) {
if (length(body) < (boundary_length + 5)) {
return(list())
} else {
stop("The 'boundary' was only found once in the ",
"multipart/form-data message. It should appear at ",
"least twice. The request-body might be truncated.")
}
}
parts <- list()
for (i in seq_along(utils::head(indexes, -1))) {
from <- indexes[i] + boundary_length
to <- indexes[i + 1] -1
parts[[i]] <- body[from:to]
}
out <- lapply(parts, multipart_sub)
names(out) <- vapply(
out,
function(x) as.character(x$name),
character(1)
)
out
}
multipart_sub <- function(bodydata) {
splitchar <- grepRaw("\\r\\n\\r\\n|\\n\\n|\\r\\r", bodydata)
if (!length(splitchar)) {
stop("Invalid multipart subpart:\n\n", rawToChar(bodydata))
}
headers <- bodydata[1:(splitchar-1)]
headers <- str_trim(rawToChar(headers))
headers <- gsub("\r\n", "\n", headers)
headers <- gsub("\r", "\n", headers)
headerlist <- unlist(lapply(strsplit(headers, "\n")[[1]], str_trim))
dispindex <- grep("^Content-Disposition:", headerlist)
if (!length(dispindex)) {
stop("Content-Disposition header not found:", headers)
}
dispheader <- headerlist[dispindex]
m <- regexpr("; name=\\\"(.*?)\\\"", dispheader)
if (m < 0)
stop('failed to find the name="..." header')
namefield <- unquote(sub(
"; name=",
"",
regmatches(dispheader, m),
fixed = TRUE
))
m <- regexpr("; filename=\\\"(.*?)\\\"", dispheader)
if (m < 0) {
filenamefield = NULL
} else {
filenamefield <- unquote(sub(
"; filename=",
"",
regmatches(dispheader, m),
fixed = TRUE
))
}
splitval <- grepRaw("\\r\\n\\r\\n|\\n\\n|\\r\\r", bodydata, value=TRUE)
start <- splitchar + length(splitval)
if (identical(utils::tail(bodydata, 2), charToRaw("\r\n"))) {
end <- length(bodydata) - 2
} else {
end <- length(bodydata) - 1
}
list (
name = namefield,
value = bodydata[start:end],
filename = filenamefield
)
} |
exchangesStack <- function(x,
stack = "default",
area = NULL, mcYear = "average",
dateRange = NULL, colors = NULL,
yMin = NULL, yMax = NULL, customTicks=NULL,
main = NULL, ylab = NULL, unit = c("MWh", "GWh", "TWh"),
compare = NULL, compareOpts = list(),
interactive = getInteractivity(),
legend = TRUE, legendId = sample(1e9, 1),
groupId = legendId,
updateLegendOnMouseOver = TRUE,
legendItemsPerRow = 5,
width = NULL, height = NULL,
xyCompare = c("union", "intersect"),
h5requestFiltering = list(),
stepPlot = FALSE, drawPoints = FALSE,
timeSteph5 = "hourly",
mcYearh5 = NULL,
tablesh5 = c("areas", "links"),
language = "en",
hidden = NULL,
refStudy = NULL,
...) {
exchangesStackValHidden <- c("H5request", "timeSteph5", "mcYearhH5", "mcYear", "main",
"dateRange", "unit", "area", "legend", "stepPlot", "drawPoints")
exchangesStackValCompare <- c("mcYear", "main", "unit", "area", "legend", "stepPlot", "drawPoints")
listParamsCheck <- list(
x = x,
compare = compare,
interactive = interactive,
language = language,
hidden = hidden,
valHidden = exchangesStackValHidden,
valCompare = exchangesStackValCompare,
mcYear = mcYear,
h5requestFiltering = h5requestFiltering,
compareOptions = compareOpts
)
listParamsCheck <- .check_params_A_get_cor_val(listParamsCheck)
x <- listParamsCheck$x
compare <- listParamsCheck$compare
compareOptions <- listParamsCheck$compareOptions
h5requestFiltering <- listParamsCheck$h5requestFiltering
mcYear <- listParamsCheck$mcYear
xyCompare <- match.arg(xyCompare)
unit <- match.arg(unit)
init_area <- area
init_dateRange <- dateRange
processFun <- function(x) {
.check_x_antaresData(x)
if(!is.null(attributes(x$areas)$hvdcAreas)){
x <- hvdcModification(x, removeHvdcAreas = TRUE, reafectLinks = TRUE)
}
row <- NULL
if (is(x, "antaresDataTable")) {
if (!attr(x, "type") == "links") stop("'x' should contain link data")
} else if (is(x, "antaresDataList")) {
if (is.null(x$links)) stop("'x' should contain link data")
if (!is.null(x$areas) && !is.null(x$areas$`ROW BAL.`)) {
if ("mcYear" %in% names(x$areas)) {
row <- x$areas[, .(area, link = paste(area, " - ROW"), timeId, mcYear,
flow = - `ROW BAL.`, to = "ROW", direction = 1)]
} else {
row <- x$areas[, .(area, link = paste(area, " - ROW"), timeId,
flow = - `ROW BAL.`, to = "ROW", direction = 1)]
}
}
x <- x$links
}
displayMcYear <- !attr(x, "synthesis") && length(unique(x$mcYear)) > 1
timeStep <- attr(x, "timeStep")
opts <- simOptions(x)
dataDateRange <- as.Date(.timeIdToDate(range(x$timeId), timeStep, opts))
if (length(init_dateRange) < 2) init_dateRange <- dataDateRange
linksDef <- getLinks(namesOnly = FALSE, withDirection = TRUE, opts = opts)
linksDef <- linksDef[link %in% x$link]
areaList <- linksDef[, unique(area)]
if (is.null(init_area)) init_area = areaList[1]
plotFun <- function(id, area, dateRange, unit, mcYear, legend, stepPlot, drawPoints, main, stack, updateLegendOnMouseOver , yMin, yMax, customTicks) {
a <- area
linksDef <- getLinks(area, opts = simOptions(x), namesOnly = FALSE,
withDirection = TRUE)
if(stack != "default") stackOpts <- .aliasToStackExchangesOptions(stack)
dt <- x
if (mcYear == "average") {
dt <- synthesize(dt)
if (!is.null(row)) row <- row[, .(flow = mean(flow)), by = .(area, link, timeId, to, direction)]
} else if ("mcYear" %in% names(x)) {
mcy <- mcYear
dt <- dt[mcYear == mcy]
if (!is.null(row)) row <- row[mcYear == mcy, .(area, link, timeId, flow, to, direction)]
}else{
.printWarningMcYear()
}
if ("annual" %in% attr(dt, "timeStep")){
dateRange <- NULL
}
flux_name <- .getColumnsLanguage("FLOW LIN.", language = language)
if (!flux_name %in% colnames(dt)){
flux_name <- "FLOW LIN."
}
if (!is.null(dateRange)){
dt <- merge(dt[as.Date(.timeIdToDate(timeId, timeStep, simOptions(x))) %between% dateRange,
.(link, timeId, flow = get(flux_name))],
linksDef, by = "link")
} else {
dt <- merge(dt[, .(link, timeId, flow = get(flux_name))], linksDef, by = "link")
}
if (!is.null(row)) {
if (!is.null(dateRange)){
row <- row[as.Date(.timeIdToDate(timeId, timeStep, simOptions(x))) %between% dateRange]
}
dt <- rbind(dt, row[area == a])
}
dt[, flow := flow * direction / switch(unit, MWh = 1, GWh = 1e3, TWh = 1e6)]
if (nrow(dt) == 0){return(combineWidgets(.getLabelLanguage("No data",language)))}
dt <- dcast(dt, timeId ~ to, value.var = "flow")
if (is.null(main) | isTRUE(all.equal("", main))){
main <- paste(.getLabelLanguage("Flows from/to", language), area)
}
if (is.null(ylab)){
ylab <- sprintf(.getLabelLanguage("Flows (%s)", language), unit)
}
if (is.null(colors)) {
colors <- substring(rainbow(ncol(dt) - 1, s = 0.7, v = 0.7), 1, 7)
}
else {
colors <- rev(rep(colors, length.out = ncol(dt)- 1))
}
if (stack != "default"){
g <- try(.plotExchangesStack(dt,
stackOpts$variables,
stackOpts$colors,
stackOpts$lines,
stackOpts$lineColors,
stackOpts$lineWidth,
opts=simOptions(x),
timeStep=timeStep,
main = main,
unit = unit,
legendId = legendId + id - 1,
groupId = groupId,
updateLegendOnMouseOver = updateLegendOnMouseOver,
dateRange = dateRange,
yMin=yMin , yMax=yMax , customTicks=customTicks,
stepPlot = stepPlot, drawPoints = drawPoints, language = language), silent = TRUE)
}
else{
g <- .plotStack(dt, timeStep, opts, colors,
legendId = legendId + id - 1, groupId = groupId,
main = main, ylab = ylab, updateLegendOnMouseOver = updateLegendOnMouseOver,
yMin=yMin , yMax=yMax , customTicks=customTicks,,stepPlot = stepPlot,
drawPoints = drawPoints, language = language, type = "Exchanges")
}
if ("try-error" %in% class(g)){
return (
combineWidgets(paste0(.getLabelLanguage("Can't visualize stack", language), " '", stack, "'<br>", g[1]))
)
}
if (legend & !"ramcharts_base" %in% class(g)) {
if (stack != "default"){
legend <- prodStackExchangesLegend(stack, legendItemsPerRow, legendId = legendId + id - 1,
language = language)}
else{
legend <- tsLegend(names(dt)[-1], colors, types = "area",
legendItemsPerRow = legendItemsPerRow,
legendId = legendId + id - 1)
}
} else legend <- NULL
combineWidgets(g, footer = legend, width = width, height = height)
}
list(
plotFun = plotFun,
areaList = areaList,
area = init_area,
dataDateRange = dataDateRange,
dateRange = init_dateRange,
displayMcYear = displayMcYear,
x = x
)
}
if (!interactive) {
listParamH5NoInt <- list(
timeSteph5 = timeSteph5,
mcYearh5 = mcYearh5,
tablesh5 = tablesh5,
h5requestFiltering = h5requestFiltering
)
params <- .getParamsNoInt(x = x,
refStudy = refStudy,
listParamH5NoInt = listParamH5NoInt,
compare = compare,
compareOptions = compareOptions,
processFun = processFun)
L_w <- lapply(seq_along(params$x), function(i){
myData <- params$x[[i]]
myData$plotFun(i, myData$area, params$x[[1]]$dateRange, unit,
mcYear, legend, stepPlot, drawPoints, main, stack, updateLegendOnMouseOver, yMin, yMax, customTicks)
} )
return(combineWidgets(list = L_w))
}
table <- NULL
mcYearH5 <- NULL
paramsH5 <- NULL
sharerequest <- NULL
timeStepdataload <- NULL
timeSteph5 <- NULL
x_in <- NULL
x_tranform <- NULL
meanYearH5 <- NULL
manipulateWidget(
{
.tryCloseH5()
if(!is.null(params)){
ind <- .id %% length(params$x)
if(ind == 0) ind <- length(params$x)
widget <- params$x[[ind]]$plotFun(.id, area, dateRange, unit, mcYear, legend, stepPlot, drawPoints, main,
stack, updateLegendOnMouseOver, yMin, yMax, customTicks)
controlWidgetSize(widget, language)
} else {
combineWidgets(.getLabelLanguage("No data for this selection", language))
}
},
x = mwSharedValue(x),
h5requestFiltering = mwSharedValue({h5requestFiltering}),
x_in = mwSharedValue({
.giveListFormat(x)
}),
paramsH5 = mwSharedValue({
.h5ParamList(X_I = x_in, xyCompare = xyCompare, h5requestFilter = h5requestFiltering)
}),
H5request = mwGroup(
label = .getLabelLanguage("H5request", language),
timeSteph5 = mwSelect(
{
if (length(paramsH5) > 0){
choices = paramsH5$timeStepS
names(choices) <- sapply(choices, function(x) .getLabelLanguage(x, language))
choices
} else {
NULL
}
},
value = if (.initial) paramsH5$timeStepS[1] else NULL,
label = .getLabelLanguage("timeStep", language),
multiple = FALSE, .display = !"timeSteph5" %in% hidden
),
mcYearH5 = mwSelectize(
choices = {
ch <- c("Average" = "", paramsH5[["mcYearS"]])
names(ch)[1] <- .getLabelLanguage("Average", language)
ch
},
value = {
if (.initial){paramsH5[["mcYearS"]][1]}else{NULL}
},
label = .getLabelLanguage("mcYears to be imported", language),
multiple = TRUE, options = list(maxItems = 4),
.display = (!"mcYearH5" %in% hidden & !meanYearH5)
),
meanYearH5 = mwCheckbox(value = FALSE,
label = .getLabelLanguage("Average mcYear", language),
.display = !"meanYearH5" %in% hidden),
.display = {
any(unlist(lapply(x_in, .isSimOpts))) & !"H5request" %in% hidden
}
),
sharerequest = mwSharedValue({
if (length(meanYearH5) > 0){
if (meanYearH5){
list(timeSteph5_l = timeSteph5, mcYearh_l = NULL, tables_l = NULL)
} else {
list(timeSteph5_l = timeSteph5, mcYearh_l = mcYearH5, tables_l = NULL)
}
} else {
list(timeSteph5_l = timeSteph5, mcYearh_l = mcYearH5, tables_l = NULL)
}
}),
x_tranform = mwSharedValue({
areas <- "all"
links <- "all"
if (length(paramsH5$h5requestFilt[[1]]) > 0){
areas <- NULL
links <- NULL
}
resXT <- .get_x_transform(x_in = x_in,
sharerequest = sharerequest,
refStudy = refStudy,
h5requestFilter = paramsH5$h5requestFilter,
areas = areas,
links = links)
resXT
}),
mcYear = mwSelect({
allMcY <- .compareOperation(lapply(params$x, function(vv){
unique(vv$x$mcYear)
}), xyCompare)
allMcY=c("average",allMcY)
names(allMcY) <- allMcY
if (is.null(allMcY)){
allMcY <- "average"
names(allMcY) <- .getLabelLanguage("average", language)
}
allMcY
},
value = {
if (.initial) mcYear
else NULL
},
.display = {
!"mcYear" %in% hidden
},
label = .getLabelLanguage("mcYear to be displayed", language)
),
area = mwSelect({
if (!is.null(params)){
as.character(.compareOperation(lapply(params$x, function(vv){
unique(vv$areaList)
}), xyCompare))
}
},
value = {
if (.initial){
if (!is.null(area)){
area
} else {
if (!is.null(params)){
as.character(.compareOperation(lapply(params$x, function(vv){
unique(vv$areaList)
}), xyCompare))[1]
} else {
NULL
}
}
}
else NULL
}, label = .getLabelLanguage("area", language), .display = !"area" %in% hidden),
dateRange = mwDateRange(value = {
if (.initial){
res <- NULL
if (!is.null(params)){
res <- c(.dateRangeJoin(params = params, xyCompare = xyCompare, "min", tabl = NULL),
.dateRangeJoin(params = params, xyCompare = xyCompare, "max", tabl = NULL))
}
if (!is.null(attributes(params$x[[1]]$x)$timeStep)){
if (attributes(params$x[[1]]$x)$timeStep == "hourly"){
if (params$x[[1]]$dateRange[2] - params$x[[1]]$dateRange[1] > 7){
res[1] <- params$x[[1]]$dateRange[2] - 7
}
}
}
res
}else{NULL}
},
min = {
if (!is.null(params)){
if (attributes(params$x[[1]]$x)$timeStep != "annual"){
.dateRangeJoin(params = params, xyCompare = xyCompare, "min", tabl = table)
} else {
NULL
}
}
},
max = {
if (!is.null(params)){
if (attributes(params$x[[1]]$x)$timeStep != "annual"){
.dateRangeJoin(params = params, xyCompare = xyCompare, "max", tabl = table)
} else {
NULL
}
}
},
language = eval(parse(text = "language")),
separator = " : ",
.display = timeStepdataload != "annual" & !"dateRange" %in% hidden,
label = .getLabelLanguage("dateRange", language)
),
stack = mwSelect(c("default",names(pkgEnv$exchangesStackAliases)), stack,
label = .getLabelLanguage("stack", language), .display = !"stack" %in% hidden),
unit = mwSelect(c("MWh", "GWh", "TWh"), unit, label = .getLabelLanguage("unit", language),
.display = !"unit" %in% hidden),
yMin= mwNumeric(value=yMin,label="yMin",
.display = !"yMin" %in% hidden),
yMax= mwNumeric(value=yMax,label="yMax",
.display = !"yMax" %in% hidden),
legend = mwCheckbox(legend, label = .getLabelLanguage("legend", language),
.display = !"legend" %in% hidden),
stepPlot = mwCheckbox(stepPlot, label = .getLabelLanguage("stepPlot", language),
.display = !"stepPlot" %in% hidden),
drawPoints = mwCheckbox(drawPoints, label = .getLabelLanguage("drawPoints", language),
.display = !"drawPoints" %in% hidden),
updateLegendOnMouseOver = mwCheckbox(updateLegendOnMouseOver, label =.getLabelLanguage("updateLegendOnMouseOver", language),
.display = !"updateLegendOnMouseOver" %in% hidden),
timeStepdataload = mwSharedValue({
attributes(x_tranform[[1]])$timeStep
}),
main = mwText(main, label = .getLabelLanguage("title", language),
.display = !"main" %in% hidden),
params = mwSharedValue({
.getDataForComp(x_tranform, NULL, compare, compareOpts,
processFun = processFun)
}),
.compare = {
compare
},
.compareOpts = {
compareOptions
},
...
)
}
.aliasToStackExchangesOptions <- function(variables) {
if (! variables %in% names(pkgEnv$exchangesStackAliases)) {
stop("Unknown alias '", variables, "'.")
}
pkgEnv$exchangesStackAliases[[variables]]
}
.plotExchangesStack <- function(x, variables, colors, lines, lineColors, lineWidth, opts, timeStep,
main = NULL, unit = "MWh", legendId = "",
groupId = legendId, width = NULL, height = NULL, dateRange = NULL, yMin=NULL, yMax=NULL, customTicks = NULL,
stepPlot = FALSE, drawPoints = FALSE, updateLegendOnMouseOver=TRUE, language = "en", type = "Exchanges") {
formulas <- append(variables, lines)
variables <- names(variables)
lines <- names(lines)
dt <- data.table(timeId = x$timeId)
for (n in names(formulas)) {
dt[, c(n) := x[, eval(formulas[[n]]) / switch(unit, MWh = 1, GWh = 1e3, TWh = 1e6)]]
}
p <- .plotStack(dt, timeStep, opts, colors, lines, lineColors, lineWidth, legendId,
groupId,
main = main, ylab = sprintf("Flows (%s)", unit),
width = width, height = height, dateRange = dateRange, yMin = yMin, yMax = yMax, customTicks= customTicks,
stepPlot = stepPlot, drawPoints = drawPoints, updateLegendOnMouseOver=updateLegendOnMouseOver , language = language, type = type)
p
}
prodStackExchangesLegend <- function(stack = "default",
legendItemsPerRow = 5, legendId = "", language = "en") {
stackOpts <- .aliasToStackExchangesOptions(stack)
if (!is.null(stackOpts$variables)) {
names(stackOpts$variables) <- sapply(names(stackOpts$variables), function(x){
.getColumnsLanguage(x, language)
})
}
if (!is.null(stackOpts$lines)) {
names(stackOpts$lines) <- sapply(names(stackOpts$lines), function(x){
.getColumnsLanguage(x, language)
})
}
tsLegend(
labels = c(names(stackOpts$variables), names(stackOpts$lines)),
colors = c(stackOpts$colors, stackOpts$lineColors),
types = c(rep("area", length(stackOpts$variables)), rep("line", length(stackOpts$lines))),
legendItemsPerRow = legendItemsPerRow,
legendId = legendId
)
} |
is.conformal <- function(h)
{
is.helly(dual_hypergraph(remove.isolates(h)))
}
is.bi.conformal <- function(h)
{
if(!is.conformal(h)) return(FALSE)
is.conformal(dual_hypergraph(h))
} |
HwdS <-
function (x)
{
n <- length(x)
J <- IsPowerOfTwo(n)
if (is.na(J))
stop("Length of x is not a power of two")
ans <- vector("list", J)
for (j in (J - 1):0) {
cf <- 2^(-(J - j)/2)
f <- c(rep(-cf, 2^(J - j - 1)), rep(cf, 2^(J - j - 1)))
ans[[j + 1]] <- getridofendNA(filter(x = x, filter = f, sides = 2))
}
ans[[1]] <- rep(0, n)
answdS <- wd(rep(0, n), filter.number = 1, family = "DaubExPhase",
type = "station")
for (j in (J - 1):0) answdS <- putD(answdS, lev = j, ans[[j +
1]])
answdS
} |
DAMOCLES_all_loglik_choosepar <- function(trparsopt,
idparsopt,
trparsfix,
idparsfix,
idparsequal,
phy,
patrait,
edgeTList,
locatenode,
pchoice,
methode,
model,
verbose)
{
trpars1 = rep(0,3 * (model == -1) + 2 * (model == 0) + 10 * (model == 0.1 | model == 0.2) + 8 * (model == 1) + 12 * (model == 2 | model == 2.2))
trpars1[idparsopt] = trparsopt
if(length(idparsfix) != 0)
{
trpars1[idparsfix] = trparsfix
}
if(length(idparsequal) > 0)
{
trpars1[idparsequal] = trpars1[idparsequal - 1 - (model == 2 | model == 2.2) - (model == 1) * (idparsequal <= 4) + (model == 2 | model == 2.2) * (idparsequal == 10)]
}
if(max(trpars1) > 1 | min(trpars1) < 0 | ((model == 2 | model == 2.2) & max(trpars1[9:12]) > 0.5))
{
loglik = -Inf
} else {
pars1 = trpars1/(1 - trpars1)
if(model < 3)
{
loglik = DAMOCLES_all_loglik(phy = phy,pa = patrait,pars = pars1,pchoice = pchoice,edgeTList = edgeTList,methode = methode,model = model,Mlist = NULL, verbose = verbose)
} else
{
loglik = DAMOCLES_DD_loglik(phy = phy,pa = patrait,pars = pars1,pchoice = pchoice,locatenode = locatenode,methode = methode,verbose = verbose)
}
}
return(loglik)
}
DAMOCLES_ML <- DAMOCLES_all_ML <- function(
phy,
pa,
initparsopt,
idparsopt = 1:length(initparsopt),
parsfix = NULL,
idparsfix = NULL,
idparsequal = NULL,
pars2 = c(1E-3,1E-4,1E-5,1000),
optimmethod = 'subplex',
pchoice = 0,
edgeTList = NULL,
methode = 'analytical',
model = 0,
verbose = FALSE)
{
locatenode <- NULL
if(model < 3)
{
edgeTList = DAMOCLES_check_edgeTList(phy,edgeTList)
} else
{
locatenode <- DAMOCLES_check_locatenode(phy,locatenode)
}
patrait = pa
if(model == -1)
{
numpars = 3
namepars = c("mu","gamma_0","gamma_1")
}
if(model == 0 | model == 0.1 | model == 0.2)
{
numpars = 2
namepars = c("mu","gamma_0")
}
if(model == 1)
{
numpars = 8
namepars = c("mu_0","gamma_0","mu_1","gamma_1","q_0_to_1","q_1_to_0","r_0","r_1")
}
if(model == 2 | model == 2.2)
{
numpars = 12
namepars = c("mu_1","gamma_1","mu_2","gamma_2","q_0_to_2","q_2_to_0","q_1_to_2","q_2_to_1","r_0","r_1","r_2","r_3")
}
if(model == 3)
{
numpars = 3
namepars = c("mu","gamma_0","K")
}
if(is.matrix(patrait) == 0)
{
patrait = matrix(c(phy$tip.label,patrait),nrow = length(patrait),ncol = 2 + (model > 0))
}
out2 = -1
idpars = sort(c(idparsopt,idparsfix,idparsequal))
if(length(idpars) != numpars)
{
stop("Incorrect number of parameters specified.\n")
} else {
if(prod(idpars == (1:numpars)) != 1)
{
cat("The parameters to be optimized and fixed are incoherent.\n")
} else {
cat('\nYou are running model',model,"\n")
if(length(namepars[idparsopt]) == 0) { optstr = "nothing" } else { optstr = namepars[idparsopt] }
cat("You are optimizing",optstr,"\n")
if(length(namepars[idparsfix]) == 0) { fixstr = "nothing" } else { fixstr = namepars[idparsfix] }
cat("You are fixing",fixstr,"\n")
if(model > 0 & model < 3)
{
if(length(namepars[idparsequal]) == 0) { fixstr = "nothing" } else { fixstr = namepars[idparsequal] }
cat("You are setting",fixstr,"equal to their counterparts.\n")
}
trparsopt = initparsopt/(1 + initparsopt)
if(model == 0.1 | model == 0.2)
{
parsfix = c(parsfix,0.5,0.5,0.5,0.5,0,0,0,0)
idparsfix = c(idparsfix,3:10)
}
trparsfix = parsfix/(1 + parsfix)
trparsfix[parsfix == Inf] = 1
utils::flush.console()
initloglik = DAMOCLES_all_loglik_choosepar(trparsopt = trparsopt,trparsfix = trparsfix,idparsopt = idparsopt,idparsfix = idparsfix,idparsequal = idparsequal,phy = phy,patrait = patrait,edgeTList = edgeTList,locatenode = locatenode,methode = methode,pchoice = pchoice,model = model, verbose = verbose)
cat("The loglikelihood for the initial parameter values is",initloglik,"\n")
utils::flush.console()
if(initloglik == -Inf)
{
cat("The initial parameter values have a likelihood that is equal to 0 or below machine precision. Try again with different initial values.\n")
out = -1
return(out)
}
cat("Optimizing ...\n")
optimpars = pars2
utils::flush.console()
out = DDD::optimizer(optimmethod = optimmethod,
optimpars = optimpars,
fun = DAMOCLES_all_loglik_choosepar,
trparsopt = trparsopt,
trparsfix = trparsfix,
idparsopt = idparsopt,
idparsfix = idparsfix,
idparsequal = idparsequal,
phy = phy,
patrait = patrait,
edgeTList = edgeTList,
locatenode = locatenode,
methode = methode,
pchoice = pchoice,
model = model,
verbose = verbose)
if(out$conv > 0)
{
cat("Optimization has not converged. Try again with different starting values.\n")
} else {
MLtrpars = unlist(out$par)
MLpars = DDD::roundn(MLtrpars/(1 - MLtrpars),14)
out$par = list(MLpars)
MLpars1 = rep(0,numpars)
MLpars1[idparsopt] = MLpars
if(length(idparsfix) != 0)
{
MLpars1[idparsfix] = parsfix
}
if(length(idparsequal) != 0)
{
MLpars1[idparsequal] = MLpars1[idparsequal - 1 - (model == 2 | model == 2.2) - (model == 1) * (idparsequal <= 4) + (model == 2 | model == 2.2) * (idparsequal == 10)]
}
ML = as.numeric(unlist(out$fvalues))
if(model == -1)
{
out2 = data.frame(mu = MLpars1[1], gamma_0 = MLpars1[2], gamma_1 = MLpars1[3], loglik = ML, df = length(initparsopt), conv = unlist(out$conv))
s1 = sprintf('Maximum likelihood parameter estimates: mu: %f, gamma_0: %f, gamma_1: %f',MLpars1[1],MLpars1[2],MLpars1[3])
}
if(model == 0 | model == 0.1 | model == 0.2)
{
out2 = data.frame(mu = MLpars1[1], gamma_0 = MLpars1[2], loglik = ML, df = length(initparsopt), conv = unlist(out$conv))
s1 = sprintf('Maximum likelihood parameter estimates: mu: %f, gamma_0: %f',MLpars1[1],MLpars1[2])
}
if(model == 1)
{
out2 = data.frame(mu_0 = MLpars1[1], gamma_0 = MLpars1[2], mu_1 = MLpars1[3], gamma_1 = MLpars1[4], q_0_to_1 = MLpars1[5], q_1_to_0 = MLpars1[6], r_0 = MLpars1[7], r_1 = MLpars1[8], loglik = ML, df = length(initparsopt), conv = unlist(out$conv))
s1 = sprintf('Maximum likelihood parameter estimates: mu_0: %f, gamma_0: %f, mu_1: %f, gamma_1: %f, q_0_to_1: %f, q_1_to_0: %f, r_0: %f, r_1: %f',MLpars1[1],MLpars1[2],MLpars1[3],MLpars1[4],MLpars1[5],MLpars1[6],MLpars1[7],MLpars1[8])
}
if(model == 2 | model == 2.2)
{
out2 = data.frame(mu_1 = MLpars1[1], gamma_1 = MLpars1[2], mu_2 = MLpars1[3], gamma_2 = MLpars1[4], q_0_to_2 = MLpars1[5], q_2_to_0 = MLpars1[6], q_1_to_2 = MLpars1[7], q_2_to_1 = MLpars1[8], r_0 = MLpars1[9], r_1 = MLpars1[10], r_2 = MLpars1[11], r_3 = MLpars1[12], loglik = ML, df = length(initparsopt), conv = unlist(out$conv))
s1 = sprintf('Maximum likelihood parameter estimates: mu_1: %f, gamma_1: %f, mu_2: %f, gamma_2: %f, q_0_to_2: %f, q_2_to_0: %f, q_1_to_2: %f, q_2_to_1: %f, r_0: %f, r_1: %f, r_2: %f, r_3: %f',MLpars1[1],MLpars1[2],MLpars1[3],MLpars1[4],MLpars1[5],MLpars1[6],MLpars1[7],MLpars1[8],MLpars1[9],MLpars1[10],MLpars1[11],MLpars1[12])
}
s2 = sprintf('Maximum loglikelihood: %f',out$fvalues)
cat("\n",s1,"\n",s2,"\n\n")
}
}
}
return(invisible(out2))
} |
calibration <- function(formula, data = NULL, blanks = NULL, weights = NULL,
model = "lm", check_assumptions = TRUE, ...) {
if (missing(formula) || (length(formula) != 3L) || (length(attr(terms(formula[-2L]),
"term.labels")) != 1L))
stop("'formula' missing or incorrect")
mf <- model.frame(formula, data)
newdata <- mf[mf[2L] != 0, ]
if (is.null(blanks)) blanks <- mf[mf[2L] == 0, 1]
if (!is.null(weights) & length(weights) == 1 & is.character(weights)) {
newweights <- with(newdata, eval(parse(text = weights)))
} else {
if (is.null(weights) | length(weights) == nrow(newdata)) {
newweights <- weights
} else {
stop("'weights' needs to be a single character value or a numeric vector ",
"of the same length as non-zero concentration data (without blanks)")
}
}
model <- do.call(model, list(formula = formula, data = newdata, weights = newweights, ...))
model$call <- match.call(expand.dots = F)
model$formula <- formula
cal <- structure(list(), class = "calibration")
cal$model <- model
cal$adj.r.squared <- summary(model)$adj.r.squared
if (is.null(cal$adj.r.squared)) cal$adj.r.squared <- NA
cal$data <- data
cal$blanks <- blanks
cal$lod <- lod(cal)
cal$loq <- loq(cal)
cal$relerr <- relerr(cal)
if (is.null(weights) & check_assumptions) {
swt <- shapiro.test(model$residuals)
bpt <- bptest(model)
cat("Check for normality of residuals\n")
print(swt)
cat("Check for homoscedasticity of residuals\n")
print(bpt)
if (swt$p.value < 0.05 || bpt$p.value < 0.05)
warning("model assumptions may not be met; double check graphically and ",
"consider using a weighted model instead")
}
return(cal)
}
print.calibration <- function(x, ...) {
print(x$model, ...)
cat(paste0("Adjusted R-squared: ", signif(x$adj.r.squared, 4), "\n"))
cat(paste0("Sum relative error: ", signif(sum(abs(x$relerr)), 4), "\n"))
cat("\n")
cat("Blanks:\n")
print(x$blanks)
cat("\n")
print(signif(rbind(x$lod, x$loq), 3))
}
summary.calibration <- function(object, ...) {
summary(object$model, ...)
}
plot.calibration <- function(x, interval = "conf", level = 0.95, ...) {
model <- x$model
conc <- model$model[,2]
new <- data.frame(conc = seq(min(conc), max(conc), length.out = 100 * length(conc)))
names(new) <- all.vars(model$formula)[2]
pred <- data.frame(new, predict(x$model, new, interval = interval, level = level))
plot(model$formula, data = model$model, ...)
lines(pred[, 2] ~ pred[, 1])
tryCatch(
{
lines(pred[, 3] ~ pred[, 1], lty = 2)
lines(pred[, 4] ~ pred[, 1], lty = 2)
}, error = function(e) invisible()
)
}
lod <- function(object, ...) {
UseMethod("lod")
}
lod.default <- function(object, ...) {
stop("object needs to be of class 'calibration'")
}
lod.calibration <- function(object, blanks = NULL, alpha = 0.01, level = 0.05,
...) {
model <- object$model
conc <- model$model[,2]
n <- length(conc)
m <- mean(table(conc))
digs <- max(nchar(gsub("(.*\\.)|([0]*$)", "", as.character(conc)))) + 1
if (m != round(m)) warning("measurement replicates of unequal size; ",
"LOD estimation might be incorrect")
if (n <= model$rank) stop("data points less than degrees of freedom")
b <- coef(model)[2]
if (is.null(blanks)) blanks <- object$blanks
if (length(blanks) > 1) {
sl <- sd(blanks) / b
val <- sl * -qt(alpha, n - 1) * sqrt(1/n + 1/m)
} else {
if (length(blanks) == 1) {
message("only one blank value supplied; LOD is estimated from the calibration curve")
} else {
message("no blanks provided; LOD is estimated from the calibration curve")
}
sx0 <- summary(model)$sigma / b
Qx <- sum((conc - mean(conc))^2) / m
val <- sx0 * -qt(alpha, n - model$rank) * sqrt(1/n + 1/m + (mean(conc))^2 / Qx)
}
res <- c(val, .conf(n, level) * val)
matrix(round(res, digs), nrow = 1, dimnames = list("LOD", names(res)))
}
loq <- function(object, ...)
UseMethod("loq")
loq.default <- function(object, ...) {
stop("object needs to be of class 'calibration'")
}
loq.calibration <- function(object, blanks = NULL, alpha = 0.01, k = 3,
level = 0.05, maxiter = 10, ...) {
model <- object$model
conc <- model$model[,2]
n <- length(conc)
m <- mean(table(conc))
digs <- max(nchar(gsub("(.*\\.)|([0]*$)", "", as.character(conc)))) + 1
if (m != round(m)) warning("measurement replicates of unequal size; ",
"LOQ estimation might be incorrect")
if (n <= model$rank) stop("data points less than degrees of freedom")
b <- coef(model)[2]
sx0 <- summary(model)$sigma / b
Qx <- sum((conc - mean(conc))^2) / m
if (is.null(blanks)) blanks <- object$blanks
val <- k * lod(object, blanks, alpha, level)[1]
for (i in 1:maxiter) {
prval <- val
val <- k * sx0 * -qt(alpha/2, n - model$rank) *
sqrt(1/n + 1/m + (val - mean(conc))^2 / Qx)
if (round(prval, digs) == round(val, digs)) break
}
res <- c(val, .conf(n, level) * val)
matrix(round(res, digs), nrow = 1, dimnames = list("LOQ", names(res)))
}
.conf <- function(n, level = 0.05) {
kappa <- sqrt((n - 1) / qchisq(c(1 - level/2, level/2), n - 1))
names(kappa) <- c('lwr', 'upr')
return(kappa)
} |
confint.ate <- function(object,
parm = NULL,
level = 0.95,
n.sim = 1e4,
estimator = object$estimator,
contrasts = object$contrasts,
allContrasts = object$allContrasts,
meanRisk.transform = "none",
diffRisk.transform = "none",
ratioRisk.transform = "none",
seed = NA,
ci = object$inference$se,
band = object$inference$band,
p.value = TRUE,
method.band = "maxT-simulation",
alternative = "two.sided",
bootci.method = "perc",
...){
if(object$inference$se == FALSE && object$inference$band == FALSE){
message("No confidence interval is computed \n",
"Set argument \'se\' to TRUE when calling the ate function \n")
return(object)
}
if(any(contrasts %in% object$contrasts == FALSE)){
stop("Incorrect values for the argument \'contrasts\' \n",
"Possible values: \"",paste(object$contrasts,collapse="\" \""),"\" \n")
}
if(!is.null(allContrasts)){
if(any(allContrasts %in% object$contrasts == FALSE)){
stop("Incorrect values for the argument \'allContrasts\' \n",
"Possible values: \"",paste(object$contrasts,collapse="\" \""),"\" \n")
}
if(any(interaction(allContrasts[1,],allContrasts[2,]) %in% interaction(object$allContrasts[1,],object$allContrasts[2,]) == FALSE)){
stop("Incorrect combinations for the argument \'allContrasts\' \n",
"Possible combinations: \"",paste(interaction(object$allContrasts[1,],object$allContrasts[2,]),collapse="\" \""),"\" \n")
}
if(!is.matrix(allContrasts) || NROW(allContrasts)!=2){
stop("Argument \'allContrasts\' must be a matrix with 2 rows \n")
}
}
estimator <- match.arg(estimator, object$estimator, several.ok = TRUE)
meanRisk.transform <- match.arg(meanRisk.transform, c("none","log","loglog","cloglog"))
diffRisk.transform <- match.arg(diffRisk.transform, c("none","atanh"))
ratioRisk.transform <- match.arg(ratioRisk.transform, c("none","log"))
bootci.method <- match.arg(bootci.method, c("norm","basic","stud","perc","wald","quantile"))
bootstrap <- object$inference$bootstrap
rm.col <- c("se","lower","upper","p.value","quantileBand","lowerBand","upperBand","adj.p.value")
out <- list(meanRisk = data.table::copy(object$meanRisk[,.SD,.SDcols = setdiff(names(object$meanRisk),rm.col)]),
diffRisk = data.table::copy(object$diffRisk[,.SD,.SDcols = setdiff(names(object$diffRisk),rm.col)]),
ratioRisk = data.table::copy(object$ratioRisk[,.SD,.SDcols = setdiff(names(object$ratioRisk),rm.col)]),
inference = object$inference,
inference.allContrasts = allContrasts,
inference.contrasts = contrasts,
transform = c("meanRisk" = meanRisk.transform,
"diffRisk" = diffRisk.transform,
"ratioRisk" = ratioRisk.transform))
out$inference["conf.level"] <- level
out$inference["ci"] <- ci
out$inference["p.value"] <- p.value
out$inference["alternative"] <- alternative
out$inference["band"] <- band
if(bootstrap){
out$inference["bootci.method"] <- bootci.method
}else if(band){
out$inference["method.band"] <- method.band
out$inference["n.sim"] <- n.sim
}
out$meanRisk[,c("se") := as.numeric(NA)]
out$diffRisk[,c("se") := as.numeric(NA)]
out$ratioRisk[,c("se") := as.numeric(NA)]
if(ci){
out$meanRisk[,c("lower","upper") := as.numeric(NA)]
out$diffRisk[,c("lower","upper",if(p.value){"p.value"}) := as.numeric(NA)]
out$ratioRisk[,c("lower","upper",if(p.value){"p.value"}) := as.numeric(NA)]
}
if(band>0){
if(method.band %in% c("bonferroni","maxT-integration","maxT-simulation")){
out$meanRisk[,c("quantileBand","lowerBand","upperBand") := as.numeric(NA)]
out$diffRisk[,c("quantileBand","lowerBand","upperBand") := as.numeric(NA)]
out$ratioRisk[,c("quantileBand","lowerBand","upperBand") := as.numeric(NA)]
}
if(p.value){
out$diffRisk[,c("adj.p.value") := as.numeric(NA)]
out$ratioRisk[,c("adj.p.value") := as.numeric(NA)]
}
}
if(bootstrap){
if(band && !identical(method.band,"none")){
stop("Adjustment for multiple comparisons not implemented for the boostrap. \n")
}
if(!identical(alternative,"two.sided")){
stop("Only two sided tests are implemented for the boostrap. \n")
}
if(!identical(out$inference.contrasts,object$contrasts)){
stop("Argument \'contrast\' is not available when using boostrap. \n")
}
if(!identical(out$inference.allContrasts,object$allContrasts)){
stop("Argument \'allContrast\' is not available when using boostrap. \n")
}
out <- confintBoot.ate(object, estimator = estimator, out = out, seed = seed)
}else{
out <- confintIID.ate(object, estimator = estimator, out = out, seed = seed)
}
return(out)
}
confintBoot.ate <- function(object, estimator, out, seed){
name.estimate <- names(object$boot$t0)
n.estimate <- length(name.estimate)
contrasts <- out$inference.contrasts
n.contrasts <- length(contrasts)
allContrasts <- out$inference.allContrasts
n.allContrasts <- NCOL(allContrasts)
collapse.allContrasts <- interaction(allContrasts[1,],allContrasts[2,])
index <- 1:n.estimate
conf.level <- out$inference$conf.level
alpha <- 1-conf.level
bootci.method <- out$inference$bootci.method
p.value <- out$inference$p.value
ci <- out$inference$ci
slot.boot.ci <- switch(bootci.method,
"norm" = "normal",
"basic" = "basic",
"stud" = "student",
"perc" = "percent",
"bca" = "bca")
index.lowerCI <- switch(bootci.method,
"norm" = 2,
"basic" = 4,
"stud" = 4,
"perc" = 4,
"bca" = 4)
index.upperCI <- switch(bootci.method,
"norm" = 3,
"basic" = 5,
"stud" = 5,
"perc" = 5,
"bca" = 5)
test.NA <- !is.na(object$boot$t)
test.Inf <- !is.infinite(object$boot$t)
n.boot <- colSums(test.NA*test.Inf)
boot.se <- sqrt(apply(object$boot$t, 2, var, na.rm = TRUE))
boot.mean <- colMeans(object$boot$t, na.rm = TRUE)
if(ci){
try.CI <- try(ls.CI <- lapply(index, function(iP){
if(n.boot[iP]==0){
return(c(lower = NA, upper = NA))
}else if(bootci.method == "wald"){
return(c(lower = as.double(object$boot$t0[iP] + qnorm(alpha/2) * boot.se[iP]),
upper = as.double(object$boot$t0[iP] - qnorm(alpha/2) * boot.se[iP])
))
}else if(bootci.method == "quantile"){
return(c(lower = as.double(quantile(object$boot$t[,iP], probs = alpha/2, na.rm = TRUE)),
upper = as.double(quantile(object$boot$t[,iP], probs = 1-(alpha/2), na.rm = TRUE))
))
}else{
if (requireNamespace("boot",quietly=TRUE)){
out <- boot::boot.ci(object$boot,
conf = conf.level,
type = bootci.method,
index = iP)[[slot.boot.ci]][index.lowerCI:index.upperCI]
}else{
stop("Package 'boot' requested to obtain confidence intervals, but not installed.")
}
return(setNames(out,c("lower","upper")))
}
}),silent=TRUE)
if (class(try.CI)[1]=="try-error"){
warning("Could not construct bootstrap confidence limits")
boot.CI <- matrix(rep(NA,2*length(index)),ncol=2)
} else{
boot.CI <- do.call(rbind,ls.CI)
}
}
if(p.value){
null <- setNames(rep(NA,length(name.estimate)),name.estimate)
null[grep("^diff", name.estimate)] <- 0
null[grep("^ratio", name.estimate)] <- 1
boot.p <- sapply(index, function(iP){
iNull <- null[iP]
if(is.na(iNull)){return(NA)}
iEstimate <- object$boot$t0[iP]
iSE <- boot.se[iP]
if(n.boot[iP]==0){
return(NA)
}else if(bootci.method == "wald"){
return(2*(1-stats::pnorm(abs((iEstimate-iNull)/iSE))))
}else if(bootci.method == "quantile"){
if(iEstimate > iNull){
return(mean(object$boot$t[,iP] > iNull))
}else if(iEstimate < iNull){
return(mean(object$boot$t[,iP] < iNull))
}else{
return(1)
}
}else{
p.value <- boot2pvalue(x = object$boot$t[,iP],
null = iNull,
estimate = iEstimate,
alternative = "two.sided",
FUN.ci = function(p.value, sign.estimate, ...){
side.CI <- c(index.lowerCI,index.upperCI)[2-sign.estimate]
if (requireNamespace("boot",quietly=TRUE)){
boot::boot.ci(object$boot,
conf = 1-p.value,
type = bootci.method,
index = iP)[[slot.boot.ci]][side.CI]
}else{
stop("Package 'boot' requested to obtain confidence intervals, but not installed.")
}
})
return(p.value)
}
})
}
vcov.meanRisk <- setNames(vector(mode = "list", length = length(estimator)), estimator)
vcov.diffRisk <- setNames(vector(mode = "list", length = length(estimator)), estimator)
vcov.ratioRisk <- setNames(vector(mode = "list", length = length(estimator)), estimator)
for(iE in 1:length(estimator)){
iEstimator <- estimator[iE]
indexMean <- grep(paste0("^mean.",iEstimator),name.estimate)
indexDiff <- grep(paste0("^difference.",iEstimator),name.estimate)
indexRatio <- grep(paste0("^ratio.",iEstimator),name.estimate)
out$meanRisk[iEstimator, c("estimate.boot") := boot.mean[indexMean], on = "estimator"]
out$diffRisk[iEstimator, c("estimate.boot") := boot.mean[indexDiff], on = "estimator"]
out$ratioRisk[iEstimator, c("estimate.boot") := boot.mean[indexRatio], on = "estimator"]
out$meanRisk[iEstimator, c("se") := boot.se[indexMean], on = "estimator"]
out$diffRisk[iEstimator, c("se") := boot.se[indexDiff], on = "estimator"]
out$ratioRisk[iEstimator, c("se") := boot.se[indexRatio], on = "estimator"]
vcov.meanRisk[[iEstimator]] <- setNames(lapply(contrasts, function(iC){
var(object$boot$t[,grep(paste0(iC,"$"),name.estimate[indexMean], value = TRUE),drop=FALSE])
}), contrasts)
vcov.diffRisk[[iEstimator]] <- setNames(lapply(collapse.allContrasts, function(iC){
var(object$boot$t[,grep(paste0(iC,"$"),name.estimate[indexDiff], value = TRUE),drop=FALSE])
}), collapse.allContrasts)
vcov.ratioRisk[[iEstimator]] <- setNames(lapply(collapse.allContrasts, function(iC){
var(object$boot$t[,grep(paste0(iC,"$"),name.estimate[indexRatio], value = TRUE),drop=FALSE])
}), collapse.allContrasts)
if(ci){
out$meanRisk[iEstimator, c("lower","upper") := list(boot.CI[indexMean,"lower"],boot.CI[indexMean,"upper"]), on = "estimator"]
out$diffRisk[iEstimator, c("lower","upper") := list(boot.CI[indexDiff,"lower"],boot.CI[indexDiff,"upper"]), on = "estimator"]
out$ratioRisk[iEstimator, c("lower","upper") := list(boot.CI[indexRatio,"lower"],boot.CI[indexRatio,"upper"]), on = "estimator"]
}
if(p.value){
out$diffRisk[iEstimator, c("p.value") := boot.p[indexDiff], on = "estimator"]
out$ratioRisk[iEstimator, c("p.value") := boot.p[indexRatio], on = "estimator"]
}
}
if(attr(object$estimator,"TD")){
setcolorder(out$meanRisk, neworder = c("estimator","time","landmark","treatment","estimate","estimate.boot","se","lower","upper"))
setcolorder(out$diffRisk, neworder = c("estimator","time","landmark","A","B","estimate.A","estimate.B","estimate","estimate.boot","se","lower","upper","p.value"))
setcolorder(out$ratioRisk, neworder = c("estimator","time","landmark","A","B","estimate.A","estimate.B","estimate","estimate.boot","se","lower","upper","p.value"))
}else{
setcolorder(out$meanRisk, neworder = c("estimator","time","treatment","estimate","estimate.boot","se","lower","upper"))
setcolorder(out$diffRisk, neworder = c("estimator","time","A","B","estimate.A","estimate.B","estimate","estimate.boot","se","lower","upper","p.value"))
setcolorder(out$ratioRisk, neworder = c("estimator","time","A","B","estimate.A","estimate.B","estimate","estimate.boot","se","lower","upper","p.value"))
}
data.table::setattr(out$meanRisk, name = "vcov", value = vcov.meanRisk)
data.table::setattr(out$diffRisk, name = "vcov", value = vcov.diffRisk)
data.table::setattr(out$ratioRisk, name = "vcov", value = vcov.ratioRisk)
return(out)
}
confintIID.ate <- function(object, estimator, out, seed){
n.estimator <- length(estimator)
if(is.null(object$iid) || any(sapply(object$iid[estimator],is.null))){
stop("Cannot re-compute standard error or confidence bands without the iid decomposition \n",
"Set argument \'iid\' to TRUE when calling the ate function \n")
}
times <- object$eval.times
n.times <- length(times)
contrasts <- out$inference.contrasts
n.contrasts <- length(contrasts)
allContrasts <- out$inference.allContrasts
n.allContrasts <- NCOL(allContrasts)
collapse.allContrasts <- interaction(allContrasts[1,],allContrasts[2,])
n.obs <- max(stats::na.omit(object$n[-1]))
conf.level <- out$inference$conf.level
alternative <- out$inference$alternative
ci <- out$inference$ci
band <- out$inference$band
method.band <- out$inference$method.band
p.value <- out$inference$p.value
n.sim <- out$inference$n.sim
meanRisk.transform <- out$transform["meanRisk"]
diffRisk.transform <- out$transform["diffRisk"]
ratioRisk.transform <- out$transform["ratioRisk"]
vcov.meanRisk <- setNames(vector(mode = "list", length = length(estimator)), estimator)
vcov.diffRisk <- setNames(vector(mode = "list", length = length(estimator)), estimator)
vcov.ratioRisk <- setNames(vector(mode = "list", length = length(estimator)), estimator)
for(iE in 1:n.estimator){
iEstimator <- estimator[iE]
estimate.mR <- matrix(NA, nrow = n.contrasts, ncol = n.times)
iid.mR <- array(NA, dim = c(n.obs, n.times, n.contrasts))
for(iC in 1:n.contrasts){
estimate.mR[iC,] <- object$meanRisk[list(iEstimator,contrasts[iC]), .SD$estimate, on = c("estimator","treatment")]
iid.mR[,,iC] <- object$iid[[iEstimator]][[contrasts[iC]]]
}
se.mR <- t(sqrt(apply(iid.mR^2, MARGIN = 2:3, sum)))
CIBP.mR <- transformCIBP(estimate = estimate.mR,
se = se.mR,
iid = iid.mR,
null = NA,
conf.level = conf.level,
alternative = "two.sided",
n.sim = n.sim,
seed = seed,
type = meanRisk.transform,
min.value = switch(meanRisk.transform,
"none" = 0,
"log" = NULL,
"loglog" = NULL,
"cloglog" = NULL),
max.value = switch(meanRisk.transform,
"none" = 1,
"log" = 1,
"loglog" = NULL,
"cloglog" = NULL),
ci = ci,
band = band,
method.band = method.band,
p.value = FALSE)
vcov.meanRisk[[iEstimator]] <- setNames(vector(mode = "list", length = n.contrasts), contrasts)
for(iC in 1:n.contrasts){
iRowIndex <- which((out$meanRisk$estimator==iEstimator)*(out$meanRisk$treatment==contrasts[iC])==1)
out$meanRisk[iRowIndex, c("se") := se.mR[iC,]]
if(ci){
out$meanRisk[iRowIndex, c("lower","upper") := list(CIBP.mR$lower[iC,],CIBP.mR$upper[iC,])]
}
if((band>0) && (method.band %in% c("bonferroni","maxT-integration","maxT-simulation"))){
out$meanRisk[iRowIndex, c("quantileBand","lowerBand","upperBand") := list(CIBP.mR$quantileBand[iC],CIBP.mR$lowerBand[iC,],CIBP.mR$upperBand[iC,])]
}
if(n.times==1){
vcov.meanRisk[[iEstimator]][[iC]] <- sum(iid.mR[,,iC]^2)
}else{
vcov.meanRisk[[iEstimator]][[iC]] <- crossprod(iid.mR[,,iC])
}
}
estimate.dR <- matrix(NA, nrow = n.allContrasts, ncol = n.times)
iid.dR <- array(NA, dim = c(n.obs, n.times, n.allContrasts))
for(iC in 1:n.allContrasts){
estimate.dR[iC,] <- object$diffRisk[list(iEstimator,allContrasts[1,iC],allContrasts[2,iC]), .SD$estimate, on = c("estimator","A","B")]
iid.dR[,,iC] <- object$iid[[iEstimator]][[allContrasts[2,iC]]] - object$iid[[iEstimator]][[allContrasts[1,iC]]]
}
se.dR <- t(sqrt(apply(iid.dR^2, MARGIN = 2:3, sum)))
CIBP.dR <- transformCIBP(estimate = estimate.dR,
se = se.dR,
iid = iid.dR,
null = 0,
conf.level = conf.level,
alternative = alternative,
n.sim = n.sim,
seed = seed,
type = diffRisk.transform,
min.value = switch(diffRisk.transform,
"none" = -1,
"atanh" = NULL),
max.value = switch(diffRisk.transform,
"none" = 1,
"atanh" = NULL),
ci = ci,
band = band,
method.band = method.band,
p.value = p.value)
vcov.diffRisk[[iEstimator]] <- setNames(vector(mode = "list", length = n.allContrasts), collapse.allContrasts)
for(iC in 1:n.allContrasts){
iRowIndex <- which((out$diffRisk$estimator==iEstimator)*(out$diffRisk$A==allContrasts[1,iC])*(out$diffRisk$B==allContrasts[2,iC])==1)
out$diffRisk[iRowIndex, c("se") := se.dR[iC,]]
if(ci){
out$diffRisk[iRowIndex, c("lower","upper") := list(CIBP.dR$lower[iC,],CIBP.dR$upper[iC,])]
if(p.value){
out$diffRisk[iRowIndex, c("p.value") := CIBP.dR$p.value[iC,]]
}
}
if(band>0){
if(method.band %in% c("bonferroni","maxT-integration","maxT-simulation")){
out$diffRisk[iRowIndex, c("quantileBand","lowerBand","upperBand") := list(CIBP.dR$quantileBand[iC],CIBP.dR$lowerBand[iC,],CIBP.dR$upperBand[iC,])]
}
if(p.value){
out$diffRisk[iRowIndex, c("adj.p.value") := CIBP.dR$adj.p.value[iC,]]
}
}
if(n.times==1){
vcov.diffRisk[[iEstimator]][[iC]] <- sum(iid.dR[,,iC]^2)
}else{
vcov.diffRisk[[iEstimator]][[iC]] <- crossprod(iid.dR[,,iC])
}
}
estimate.rR <- matrix(NA, nrow = n.allContrasts, ncol = n.times)
iid.rR <- array(NA, dim = c(n.obs, n.times, n.allContrasts))
for(iC in 1:n.allContrasts){
estimate.rR[iC,] <- object$ratioRisk[list(iEstimator,allContrasts[1,iC],allContrasts[2,iC]), .SD$estimate, on = c("estimator","A","B")]
factor1 <- object$meanRisk[list(iEstimator, allContrasts[1,iC]),.SD$estimate, on = c("estimator","treatment")]
factor2 <- object$meanRisk[list(iEstimator, allContrasts[2,iC]),.SD$estimate, on = c("estimator","treatment")]
term1 <- rowMultiply_cpp(object$iid[[iEstimator]][[allContrasts[2,iC]]],
scale = 1/factor1)
term2 <- rowMultiply_cpp(object$iid[[iEstimator]][[allContrasts[1,iC]]],
scale = factor2/factor1^2)
iid.rR[,,iC] <- term1 - term2
}
se.rR <- t(sqrt(apply(iid.rR^2, MARGIN = 2:3, sum)))
CIBP.rR <- transformCIBP(estimate = estimate.rR,
se = se.rR,
iid = iid.rR,
null = 1,
conf.level = conf.level,
alternative = alternative,
n.sim = n.sim,
seed = seed,
type = ratioRisk.transform,
min.value = switch(ratioRisk.transform,
"none" = 0,
"log" = NULL),
max.value = NULL,
ci = ci,
band = band,
method.band = method.band,
p.value = p.value)
vcov.ratioRisk[[iEstimator]] <- setNames(vector(mode = "list", length = n.allContrasts), collapse.allContrasts)
for(iC in 1:n.allContrasts){
iRowIndex <- which((out$ratioRisk$estimator==iEstimator)*(out$ratioRisk$A==allContrasts[1,iC])*(out$ratioRisk$B==allContrasts[2,iC])==1)
out$ratioRisk[iRowIndex, c("se") := se.rR[iC,]]
if(ci){
out$ratioRisk[iRowIndex, c("lower","upper") := list(CIBP.rR$lower[iC,],CIBP.rR$upper[iC,])]
if(p.value){
out$ratioRisk[iRowIndex, c("p.value") := CIBP.rR$p.value[iC,]]
}
}
if(band>0){
if(method.band %in% c("bonferroni","maxT-integration","maxT-simulation")){
out$ratioRisk[iRowIndex, c("quantileBand","lowerBand","upperBand") := list(CIBP.rR$quantileBand[iC],CIBP.rR$lowerBand[iC,],CIBP.rR$upperBand[iC,])]
}
if(p.value){
out$ratioRisk[iRowIndex, c("adj.p.value") := CIBP.rR$adj.p.value[iC,]]
}
}
if(n.times==1){
vcov.ratioRisk[[iEstimator]][[iC]] <- sum(iid.rR[,,iC]^2)
}else{
vcov.ratioRisk[[iEstimator]][[iC]] <- crossprod(iid.rR[,,iC])
}
}
}
data.table::setattr(out$meanRisk, name = "vcov", value = vcov.meanRisk)
data.table::setattr(out$diffRisk, name = "vcov", value = vcov.diffRisk)
data.table::setattr(out$ratioRisk, name = "vcov", value = vcov.ratioRisk)
return(out)
} |
Vardsgr <-
function (ndpts,kvar1,kdv1,rdes) {
res<-.Fortran("vdg",as.integer(ndpts),as.integer(kvar1),as.integer(kdv1),
as.double(rdes),vdgr=double(84))
return(res$vdgr)
} |
fpeq <- function(xinit, fn, merit,
method=c("pure", "UR", "vH", "RRE", "MPE", "SqRRE", "SqMPE"),
control=list(), stepfunc, argstep, silent=TRUE, order.method=1, ...)
{
method <- match.arg(method, c("pure","UR", "vH", "RRE", "MPE", "SqRRE", "SqMPE"))
if(method %in% c("SqRRE", "SqMPE"))
{
order.method <- ifelse(order.method == 1, 2, order.method)
method <- substr(method, 3, 5)
}
if(method == "UR")
{
if(missing(fn) || missing(xinit) || missing(stepfunc) || missing(merit))
stop("missing parameters for UR method")
if(!missing(argstep))
finalstep <- function(x) stepfunc(x, argstep)
else
finalstep <- stepfunc
}
if(method == "vH")
if(missing(fn) || missing(xinit) || missing(merit))
stop("missing parameters for vH method")
noitercount <- FALSE
inner.counts.fpfn <- c(0, 0)
inner.iter.fpfn <- 0
wrapfn <- function(x)
{
fx <- fn(x)
inner.counts.fpfn <<- inner.counts.fpfn + fx$counts
inner.iter.fpfn <<- inner.iter.fpfn + fx$iter
fx$par
}
if(!is.null(merit))
{
inner.counts.merit <- c(0, 0)
inner.iter.merit <- 0
wrapmerit <- function(x, ...)
{
vx <- merit(x, ...)
inner.counts.merit <<- inner.counts.merit + vx$counts
inner.iter.merit <<- inner.iter.merit + vx$iter
vx$value
}
}else
{
wrapmerit <- NULL
inner.counts.merit <- inner.iter.merit <- 0
}
con <- list(sigma=9/10, beta=1/2, tol=1e-6, maxit=100, echo=0)
namc <- names(con)
con[namc <- names(control)] <- control
confpiter <- list(tol=1e-6, maxiter=100, trace=FALSE)
if(!is.null(control$tol))
confpiter$tol <- control$tol
if(!is.null(control$maxit))
confpiter$maxiter <- control$maxit
if(!is.null(control$trace))
confpiter$trace <- control$trace
consquarem <- list(tol=1e-6, maxiter=100, trace=FALSE, K=order.method,
method=ifelse(order.method==1, 1*(method == "RRE")+2*(method == "MPE"), method))
if(!is.null(control$tol))
consquarem$tol <- control$tol
if(!is.null(control$maxit))
consquarem$maxiter <- control$maxit
if(!is.null(control$trace))
consquarem$trace <- control$trace
if(method == "pure" && !is.null(wrapmerit))
{
myGNE <- try( pureFP(xinit, wrapfn, wrapmerit, control=con, ...),
silent=silent)
}
if(method == "pure" && is.null(wrapmerit))
{
myGNE <- try( fpiter(xinit, wrapfn, wrapmerit, control=confpiter, ...),
silent=silent)
if(!is(myGNE,"try-error"))
{
if(!silent)
print(myGNE)
myGNE$value <- max(abs(fn(myGNE$par)$par))
myGNE$counts <- c(fn=myGNE$fpevals, merit=myGNE$objfevals)
myGNE$code <- 1*(myGNE$convergence == 0) + 4*(myGNE$fpevals[1] >= confpiter$maxiter)
myGNE$code <- myGNE$code + 2*(myGNE$convergence != 0 & myGNE$fpevals[1] <= consquarem$maxiter)
}
}
if(method == "UR")
{
myGNE <- try( relaxationAlgoUR(xinit, finalstep, wrapfn, wrapmerit,
control=con, ...), silent=silent)
}
if(method == "vH")
{
myGNE <- try( relaxationAlgoVH(xinit, wrapfn, wrapmerit,
control=con, ...), silent=silent)
}
if(method %in% c("RRE","MPE","SqRRE","SqMPE") && !is.null(wrapmerit))
{
myGNE <- try( extrapolFP(xinit, wrapfn, wrapmerit,
control=con, method=method, ...), silent=FALSE)
}
if(method %in% c("RRE","MPE","SqRRE","SqMPE") && is.null(wrapmerit))
{
myGNE <- try( squarem(xinit, wrapfn, control=consquarem, ...), silent=FALSE)
if(!is(myGNE,"try-error"))
{
if(!silent)
print(myGNE)
myGNE$value <- max(abs(fn(myGNE$par)$par))
myGNE$counts <- c(fn=myGNE$fpevals, merit=myGNE$objfevals)
myGNE$code <- 1*(myGNE$convergence == 0) + 4*(myGNE$fpevals[1] > consquarem$maxiter)
myGNE$code <- myGNE$code + 2*(myGNE$convergence != 0 & myGNE$fpevals[1] <= consquarem$maxiter)
}
}
if(!is(myGNE,"try-error"))
res <- list(par=myGNE$par, value=myGNE$value,
outer.counts=myGNE$counts, outer.iter=myGNE$counts[1],
code=myGNE$code, inner.iter=inner.iter.fpfn+inner.iter.merit,
inner.counts=inner.counts.fpfn+inner.counts.merit,
message=myGNE$message)
else
res <- list(par= NA, value=NA, outer.counts=NA, outer.iter=NA, code=100,
message=paste("Error in the fixed-point problem:", myGNE, "."),
inner.counts=NA, inner.iter=NA)
res
}
pureFP <- function(xinit, fn, merit, control, ...)
{
echo <- control$echo
maxit <- control$maxit
tol <- control$tol
k <- 1
xk_1 <- xinit
xk <- fn(xk_1)
xkp1 <- fn(xk)
merit_xk <- merit(xk, y=xkp1)
if(echo >= 1)
cat("**** k", k, "\n x_k", xk, "\n")
if(echo >= 2)
cat(" m(x_k)", merit_xk, "\n")
while( abs( merit_xk ) > tol && k < maxit)
{
xk_1 <- xk
k <- k+1
xk <- xkp1
xkp1 <- fn(xk)
merit_xk <- merit(xk, y=xkp1)
if(echo >= 1)
cat("**** k", k, "\n x_k", xk, "\n")
if(echo >= 2)
cat(" m(x_k)", merit_xk, "\n")
}
list(par = xk, value=merit_xk , counts=c(fn=k+1, merit=k+1), iter = k,
code=(k >= maxit)*4 + (abs(merit_xk) <= tol)*1 + (max(abs(xk - xk_1)/abs(xk)) <= tol)*2)
}
relaxationAlgoUR <- function(xinit, stepfunc, fn, merit, control, ...)
{
echo <- control$echo
maxit <- control$maxit
tol <- control$tol
k <- 1
xk_1 <- xinit
alphak <- stepfunc(k)
xk <- (1-alphak) * xk_1 + alphak * fn(xk_1)
if(!is.null(merit))
merit_xk <- merit(xk)
else
merit_xk <- max(abs(xk - xk_1))
if(echo >= 1)
cat("**** k", k, "\n x_k", xk, "\n")
if(echo >= 2)
cat(" m(x_k)", merit_xk, "\n")
if(echo >= 3)
cat("step size", alphak, "\n\n")
while( abs( merit_xk ) > tol && k < maxit)
{
xk_1 <- xk
k <- k+1
alphak <- stepfunc(k)
xk <- (1-alphak) * xk_1 + alphak * fn(xk_1)
if(!is.null(merit))
merit_xk <- merit(xk)
else
merit_xk <- max(abs(xk - xk_1))
if(echo >= 1)
cat("**** k", k, "\n x_k", xk, "\n")
if(echo >= 2)
cat(" m(x_k)", merit_xk, "\n")
if(echo >= 3)
cat("step size", alphak, "\n\n")
}
list(par = xk, value=merit_xk , counts=c(fn=k+1, merit=k+1), iter = k,
code=(k >= maxit)*4 + (abs(merit_xk) <= tol)*1 + (max(abs(xk - xk_1)/abs(xk)) <= tol)*2)
}
relaxationAlgoVH <- function(xinit, fn, merit, control, ...)
{
sigma <- control$sigma
beta <- control$beta
tol <- control$tol
echo <- control$echo
maxit <- control$maxit
k <- 0
xk_1 <- xinit
xk <- fn(xk_1)
merit_xk <- merit(xk)
counts <- c(fn=1, merit=1)
if(echo >= 1)
cat("**** k", k, "\n x_k", xk, "\n")
if(echo >= 2)
cat(" m(x_k)", merit_xk, "\n")
while( abs( merit_xk ) > tol && k < maxit)
{
k <- k+1
xk_1 <- xk
dk <- fn(xk) - xk
normdk <- sqrt(sum(dk^2))
merit_xk <- merit(xk)
tk <- 1
l <- 0
merit_xktkdk <- merit(xk + tk*dk)
while( merit_xktkdk > merit_xk - sigma * tk^2 * normdk^2 )
{
tk <- tk * beta
merit_xktkdk <- merit(xk + tk*dk)
if(echo >= 3)
{
cat(l, "\t", merit_xktkdk, "\t <= ")
cat(merit_xk - sigma * tk^2 * normdk^2, "?\t")
cat("tk", tk, "\n\n")
}
l <- l+1
}
xk <- xk_1 + tk * dk
merit_xk <- merit_xktkdk
if(echo >= 1)
cat("**** k", k, "\n x_k", xk, "\n")
if(echo >= 2)
cat(" m(x_k)", merit_xk, "\n")
counts <- counts+1
counts[2] <- counts[2]+l
}
list(par = xk, value=merit_xk , counts=counts, iter = k,
code=(k >= maxit)*4 + (abs(merit_xk) <= tol)*1 + (max(abs(xk - xk_1)/abs(xk)) <= tol)*2)
}
extrapolFP <- function(xinit, fn, merit, control, method, ...)
{
echo <- control$echo
maxit <- control$maxit
tol <- control$tol
k <- 1
xk_1 <- xinit
xk <- fn(xk_1)
merit_xk <- merit(xk)
counts <- c(fn=1, merit=1)
if(echo >= 1)
cat("**** k", k, "\n x_k", xk, "\n")
if(echo >= 2)
cat(" m(x_k)", merit_xk, "\n")
while( abs( merit_xk ) > tol && k < maxit)
{
xk_1 <- xk
k <- k+1
xk <- fn(xk_1)
xkp1 <- fn(xk)
Delta1_xk <- xk - xk_1
Delta2_xk <- xkp1 - 2*xk + xk_1
if(method == "RRE" || method == "SqRRE")
mystep <- crossprod(Delta2_xk, Delta1_xk) / crossprod(Delta2_xk, Delta2_xk)
if(method == "MPE" || method == "SqMPE")
mystep <- crossprod(Delta1_xk, Delta1_xk) / crossprod(Delta1_xk, Delta2_xk)
if(is.nan(mystep) || is.infinite(mystep))
{
warning("Delta square xk is too small: Use the last iterate.")
xk <- xkp1
}else if(substr(method, 1, 2) == "Sq")
{
xk <- xk_1 - 2*Delta1_xk * mystep + Delta2_xk * mystep^2
}else
{
xk <- xk_1 - Delta1_xk * mystep
}
merit_xk <- merit(xk)
if(echo >= 1)
cat("**** k", k, "\n x_k", xk, "\n")
if(echo >= 2)
cat(" m(x_k)", merit_xk, "\n")
if(echo >= 3)
cat(" Delta(xk)", Delta1_xk, "\n", "Delta^2(xk)", Delta2_xk, "\n\n")
counts <- counts + c(2,1)
}
list(par = xk, value=merit_xk , counts=counts, iter = k,
code=(k >= maxit)*4 + (abs(merit_xk) <= tol)*1 + (max(abs(xk - xk_1)/abs(xk)) <= tol)*2)
} |
so_PharmMLRef_new <- function() {
obj = .Call("r_so_PharmMLRef_new")
}
so_PharmMLRef_copy <- function(self) {
.Call("r_so_PharmMLRef_copy", self)
}
so_PharmMLRef_free <- function(self) {
.Call("r_so_PharmMLRef_free", self)
}
so_PharmMLRef_ref <- function(self) {
.Call("r_so_PharmMLRef_ref", self)
}
so_PharmMLRef_unref <- function(self) {
.Call("r_so_PharmMLRef_unref", self)
}
so_PharmMLRef_get_name <- function(self) {
.Call("r_so_PharmMLRef_get_name", self)
}
so_PharmMLRef_set_name <- function(self, value) {
.Call("r_so_PharmMLRef_set_name", self, value)
}
so_PharmMLRef_get_id <- function(self) {
.Call("r_so_PharmMLRef_get_id", self)
}
so_PharmMLRef_set_id <- function(self, value) {
.Call("r_so_PharmMLRef_set_id", self, value)
}
so_PharmMLRef_get_Description <- function(self) {
.Call("r_so_PharmMLRef_get_Description", self)
}
so_PharmMLRef_set_Description <- function(self, value) {
.Call("r_so_PharmMLRef_set_Description", self, value)
}
name_acc <- function(value)
{
if (!isnull(.self$.cobj)) {
if (missing(value)) {
so_PharmMLRef_get_name(.self$.cobj)
} else {
stopifnot(is.character(value), length(value) == 1)
so_PharmMLRef_set_name(.self$.cobj, value)
}
}
}
id_acc <- function(value)
{
if (!isnull(.self$.cobj)) {
if (missing(value)) {
so_PharmMLRef_get_id(.self$.cobj)
} else {
stopifnot(is.character(value), length(value) == 1)
so_PharmMLRef_set_id(.self$.cobj, value)
}
}
}
Description_acc <- function(value)
{
if (!isnull(.self$.cobj)) {
if (missing(value)) {
so_PharmMLRef_get_Description(.self$.cobj)
} else {
if (!is(value, "character")) {
stop("object must be of type 'character'")
}
so_PharmMLRef_set_Description(.self$.cobj, value)
}
}
}
so_PharmMLRef = setRefClass("so_PharmMLRef",
fields=list(
name = name_acc,
id = id_acc,
Description = Description_acc,
.cobj = "externalptr"
),
methods=list(
copy = function() {
copy = so_PharmMLRef_copy(.self$.cobj)
so_PharmMLRef$new(cobj=copy)
},
initialize = function(cobj) {
if (missing(cobj)) {
.cobj <<- so_PharmMLRef_new()
} else {
.cobj <<- cobj
}
},
finalize = function() {
so_PharmMLRef_unref(.self$.cobj)
}
)
) |
forcingsSymb <- function(type =c("Gauss", "Fermi", "1-Fermi", "MM", "Signal", "Dose"), parameters = NULL) {
type <- match.arg(type)
fn1 <- "(.5*(1.-tanh(.5*k*(time-T1))))"
fn2 <- "(.5*(1.+tanh(.5*k*(time-T2))))"
integral <- "(Tduration/(exp(20)-1))"
k <- "(20/Tduration)"
T1 <- "(Tlag+Tinit)"
T2 <- "(Tlag+Tinit+Tduration)"
INPUT <- paste0("Dose*(", fn1, ")*(", fn2, ")/", integral)
INPUT <- replaceSymbols(c("k", "T1", "T2"), c(k, T1, T2), INPUT)
INPUT <- paste0("(", INPUT, ")")
fun <- switch(type,
"Gauss" = "(scale*exp(-(time-mu)^2/(2*tau^2))/(tau*2.506628))",
"Fermi" = "(scale/(exp((time-mu)/tau)+1))",
"1-Fermi" = "(scale*exp((time-mu)/tau)/(exp((time-mu)/tau)+1))",
"MM" = "(slope*time/(1 + slope*time/vmax))",
"Signal" = "(max1*max2*(1-exp(-time/tau1))*exp(-time*tau2))",
"Dose" = INPUT
)
if(!is.null(parameters)) {
fun <- replaceSymbols(names(parameters), parameters, fun)
}
return(fun)
}
getCoefficients <- function(char, symbol) {
pdata <- getParseData(parse(text = char, keep.source = TRUE))
pdata <- pdata[pdata$terminal == TRUE, ]
symbolPos <- which(pdata$text == symbol)
coefficients <- rep(1, length(symbolPos))
hasCoefficient <- rep(FALSE, length(symbolPos))
hasCoefficient[symbolPos > 1] <- (pdata$text[symbolPos[symbolPos > 1] - 1] == "*")
coefficients[hasCoefficient] <- pdata$text[symbolPos[hasCoefficient]-2]
return(as.numeric(coefficients))
}
resolveRecurrence <- function (variables) {
if(length(variables) > 1) {
for (i in 1:(length(variables) - 1)) {
newvariables <- c(variables[1:i],
unlist(replaceSymbols(names(variables)[i],
paste("(", variables[i], ")", sep = ""),
variables[(i + 1):length(variables)])))
names(newvariables) <- names(variables)
variables <- newvariables
}
}
return(variables)
}
nullZ <- function(A, tol=sqrt(.Machine$double.eps)) {
ret <- rref(A)
ret[[1]] -> R
ret[[2]] -> pivcol
n <- ncol(A)
r <- length(pivcol)
nopiv <- 1:n
nopiv <- nopiv[-pivcol]
Z <- mat <- matrix(0, nrow = n, ncol = n-r)
if ( n>r ) {
Z[nopiv,] <- diag(1, n-r, n-r)
if ( r>0 ) {
Z[pivcol,] <- -R[1:r,nopiv]
}
}
return (Z)
}
rref <- function(A, tol=sqrt(.Machine$double.eps), verbose=FALSE, fractions=FALSE){
if ((!is.matrix(A)) || (!is.numeric(A)))
stop("argument must be a numeric matrix")
m <- nrow(A)
n <- ncol(A)
i <- 1
j <- 1
pivcol <- c()
while ((i <= m) & (j <= n)){
which <- which.max(abs(A[i:m,j]))
k <- i+which-1
pivot <- A[k, j]
if ( abs(pivot) <= tol ) {
A[i:m,j] =matrix(0,m-i+1,1)
j <- j+1
} else {
pivcol <- cbind(pivcol,j)
A[cbind(i,k),j:n] = A[cbind(k, i),j:n];
A[i,j:n] = A[i,j:n]/A[i,j];
otherRows <- 1:m
otherRows <- otherRows[-i]
for (u in otherRows) {
A[u,j:n] = A[u,j:n] - A[u,j]*A[i,j:n];
}
i = i + 1;
j = j + 1;
}
}
return (list(A,pivcol))
} |
besag_newell <-
function(geo, population, cases, expected.cases=NULL, k, alpha.level){
if(is.null(expected.cases)){
p <- sum(cases)/sum(population)
expected.cases <- population*p
}
geo.results <- zones(geo, population, 1)
nearest.neighbors <- geo.results$nearest.neighbors
distance <- geo.results$dist
n.zones <- length(unlist(nearest.neighbors))
results <- besag_newell_internal(cases, expected.cases, nearest.neighbors,
n.zones, k)
p.values <- results$observed.p.values
m.values <- results$observed.m.values
k.values <- results$observed.k.values
signif.indices <- order(p.values)[1:sum(p.values <= alpha.level)]
signif.p.values <- p.values[signif.indices]
signif.m.values <- m.values[signif.indices]
signif.k.values <- k.values[signif.indices]
if(length(signif.indices) == 0){
clusters <- NULL
} else {
clusters <- vector("list", length=length(signif.indices))
for( i in 1:length(clusters) ){
cluster <- order(distance[signif.indices[i],])[1:signif.m.values[i]]
new.cluster <- list(
location.IDs.included = cluster,
population = sum(population[cluster]),
number.of.cases = sum(cases[cluster]),
expected.cases = sum(expected.cases[cluster]),
SMR = sum(cases[cluster])/sum(expected.cases[cluster]),
p.value = signif.p.values[i]
)
clusters[[i]] <- new.cluster
}
}
results <- list(
clusters=clusters,
p.values=p.values,
m.values=m.values,
observed.k.values=k.values
)
return(results)
} |
checkArgument <- function(argumentCheckMode, checkDataTypes, className, methodName, argumentValue, isMissing,
allowMissing=FALSE, allowNull=FALSE, allowedClasses=NULL, mustBeAtomic=FALSE, allowedListElementClasses=NULL, listElementsMustBeAtomic=FALSE,
allowedValues=NULL, minValue=NULL, maxValue=NULL, maxLength=NULL) {
if(argumentCheckMode==0) return(invisible())
argumentName <- substitute(argumentValue)
if(is.null(className)||(length(className)==0)) classPrefix <- ""
else classPrefix <- paste0(className, "$")
if(isMissing&(!allowMissing)) stop(paste0(classPrefix, methodName, "(): ", argumentName, " must be specified"), call. = FALSE)
if(is.null(argumentValue)&&(!allowNull)) stop(paste0(classPrefix, methodName, "(): ", argumentName, " must not be null"), call. = FALSE)
if(argumentCheckMode==1) return(invisible())
if((argumentCheckMode==4)||((argumentCheckMode==3)&&(checkDataTypes==TRUE))) {
if((!is.null(argumentValue))&&(!is.null(allowedClasses))&&(length(allowedClasses)>0)) {
cls <- class(argumentValue)
if(length(intersect(allowedClasses, cls)) == 0) {
if(length(allowedClasses) > 1) {
stop(paste0(classPrefix, methodName, "(): ", argumentName, " must be one of the following types: (",
paste(allowedClasses, sep="", collapse = ", "), "). Type encountered: ",
paste(cls, collapse=", "), "."), call. = FALSE)
}
else {
stop(paste0(classPrefix, methodName, "(): ", argumentName, " must be of type ", allowedClasses, ". ",
"Type encountered: ", paste(cls, sep="", collapse=", "), "."), call. = FALSE)
}
}
if(("list" %in% allowedClasses)&&("list" %in% cls)) {
if(!is.null(allowedListElementClasses)) {
invalidTypes <- list()
nonAtomicTypes <- list()
if(length(argumentValue)>0) {
for(i in 1:length(argumentValue))
{
if(is.null(argumentValue[[i]])) next
if(length(allowedListElementClasses)>0) {
elementTypes <- class(argumentValue[[i]])
if(length(intersect(allowedListElementClasses, elementTypes)) == 0) { invalidTypes[[length(invalidTypes)+1]] <- elementTypes }
}
if(listElementsMustBeAtomic==TRUE) {
if(!is.atomic(argumentValue[[i]])) nonAtomicTypes[[length(nonAtomicTypes)+1]] <- class(argumentValue[[i]])
}
}
if(length(invalidTypes)>0)
stop(paste0(classPrefix, methodName, "(): [", paste(unlist(invalidTypes), collapse=", "), "] is/are invalid data types for the ", argumentName,
" argument. Elements of the ", argumentName, " list must be one of the following types: [",
paste(allowedListElementClasses, collapse=", "), "]"), call. = FALSE)
if(length(nonAtomicTypes>0))
stop(paste0(classPrefix, methodName, "(): [", paste(unlist(invalidTypes), collapse=", "), "] is/are invalid data types for the ", argumentName,
" argument. Elements of the ", argumentName, " list must be atomic."), call. = FALSE)
}
}
}
}
if((mustBeAtomic==TRUE)&&!(is.atomic(argumentValue))) {
stop(paste0(classPrefix, methodName, "(): ", argumentName, " must be one of the atomic data types"), call. = FALSE)
}
}
if(argumentCheckMode>=2) {
if(!is.null(allowedValues)) {
invalidValues <- setdiff(argumentValue, allowedValues)
if(length(invalidValues)>0)
stop(paste0(classPrefix, methodName, "(): [", paste(invalidValues, collapse=", "), "] is/are invalid values for the ", argumentName,
" argument. ", argumentName, " must be one of the following values: [", paste(allowedValues, collapse=", "), "]"), call. = FALSE)
}
if((!is.null(minValue))&&(!is.null(argumentValue))) {
if(any(argumentValue < minValue)) {
stop(paste0(classPrefix, methodName, "(): ", argumentName, " must be greater than or equal to ", minValue), call. = FALSE)
}
}
if((!is.null(maxValue))&&(!is.null(argumentValue))) {
if(any(argumentValue > maxValue)) {
stop(paste0(classPrefix, methodName, "(): ", argumentName, " must be less than or equal to ", maxValue), call. = FALSE)
}
}
if(!is.null(allowedClasses)) {
if("character" %in% allowedClasses) {
if(!is.null(maxLength)) {
if(any(nchar(argumentValue)>maxLength)) {
stop(paste0(classPrefix, methodName, "(): ", argumentName, " must have length less than or equal to ", maxLength, " characters"), call. = FALSE)
}
}
}
}
}
return(invisible())
} |
library(testthat)
library(rly)
context("Bad state declaration")
Lexer <- R6::R6Class("Lexer",
public = list(
tokens = c('NUMBER', 'PLUS','MINUS'),
states = list(c('comment')),
t_PLUS = '\\+',
t_MINUS = '-',
t_NUMBER = '\\d+',
t_ignore = " \t",
t_comment = function(re='/\\*', t) {
cat('comment\n')
t$lexer$begin('Entering comment state')
},
t_comment_body_part = function(re='(.|\\n)*\\*/', t) {
cat(sprintf("comment body %s\n", t$value))
t$lexer$begin('INITIAL')
},
t_error = function(t) { }
)
)
test_that("comment", {
expect_output(expect_error(rly::lex(Lexer), "Can't build lexer"),
"ERROR .* Invalid state specifier\\. Must be a tuple \\(statename,'exclusive\\|inclusive'\\)")
}) |
`maesparunall` <-
function(whichrows=NA, runfile=NA, whichcols=NA, quiet=FALSE, extrafiles="", ...){
if(is.na(runfile))runfile <- file.choose()
inputdat <- read.csv(runfile)
if(all(is.na(whichrows)))whichrows <- 1:nrow(inputdat)
returnlist <- list()
for(i in 1:length(whichrows)){
runmaespa(whichrow=whichrows[i], whichcols=whichcols, runfile=runfile, ...)
returnlist$dayresult[[i]] <- readdayflux()
returnlist$hrresult[[i]] <- readhrflux()
if(file.exists("watbal.dat"))returnlist$watbal[[i]] <- readwatbal()
for(j in 1:length(extrafiles)){
if(!file.exists(extrafiles[j]))next
if(extrafiles[j]=="watbal.dat")next
dat <- read.table(extrafiles[j])
datname <- gsub(".[a-z]*$", "", extrafiles[j])
returnlist[[datname]][[i]] <- dat
}
if(!quiet)cat("Row", i, "out of", length(whichrows), "completed\n")
}
return(returnlist)
} |
dust <- function(object, ...)
{
UseMethod("dust")
}
dust.default <- function(object, ...,
tidy_df = FALSE, keep_rownames = FALSE,
glance_foot = FALSE, glance_stats = NULL,
col_pairs = 2, byrow = FALSE,
descriptors = "term",
numeric_level = c("term", "term_plain", "label"),
label = NULL,
caption = NULL,
caption_number = getOption("pixied_caption_number", TRUE),
justify = getOption("pixie_justify", "center"),
float = getOption("pixie_float", TRUE),
longtable = getOption("pixie_longtable", FALSE),
hhline = getOption("pixie_hhline", FALSE),
bookdown = getOption("pixie_bookdown", FALSE),
border_collapse = getOption("pixie_border_collapse", "collapse"),
tabcolsep = getOption("pixie_tabcolsep", 6),
fixed_header = getOption("pixie_fixed_header", FALSE),
html_preserve = getOption("pixie_html_preserve", TRUE))
{
coll <- checkmate::makeAssertCollection()
descriptors <- checkmate::matchArg(x = descriptors,
choices = c("term", "term_plain", "label",
"level", "level_detail"),
several.ok = TRUE,
add = coll)
if (!inherits(object, "data.frame") | tidy_df)
{
tidy_object <- broom::tidy(object, ...)
}
else if (inherits(object, "data.frame"))
{
if (inherits(object, "data.table"))
{
object <- as.data.frame(object)
}
if (keep_rownames)
{
tidy_object <- cbind(rownames(object),
object)
rownames(tidy_object) <- NULL
tidy_object[, 1] <- as.character(tidy_object[, 1])
names(tidy_object)[1] <- ".rownames"
}
else
{
tidy_object <- object
}
}
if (!inherits(object, "data.frame") & any(!descriptors %in% "term"))
{
nms <- names(tidy_object)
tidy_object <- tidy_levels_labels(object,
descriptors = descriptors,
numeric_level = numeric_level,
argcheck = coll) %>%
dplyr::left_join(x = tidy_object,
y = .,
by = c("term" = "term"))
if ("label" %in% names(tidy_object))
{
is_intercept <- grepl(pattern = "([(]|)Intercept([)]|)",
x = tidy_object[["term"]])
tidy_object[["label"]][is_intercept] <-
tidy_object[["term"]][is_intercept]
}
if ("term_plain" %in% names(tidy_object))
{
is_intercept <- grepl(pattern = "([(]|)Intercept([)]|)",
x = tidy_object[["term"]])
tidy_object[["label"]][is_intercept] <-
tidy_object[["term_plain"]][is_intercept]
}
if (!"term" %in% descriptors)
{
nms <- nms[!nms %in% "term"]
}
tidy_object <- tidy_object[unique(c(descriptors, nms))]
}
checkmate::reportAssertions(coll)
head <- as.data.frame(t(names(tidy_object)),
stringsAsFactors=FALSE)
names(head) <- names(tidy_object)
if (glance_foot)
{
foot <- glance_foot(object,
col_pairs = col_pairs,
total_cols = ncol(tidy_object),
glance_stats = glance_stats,
byrow = byrow) %>%
component_table()
}
else
{
foot <- NULL
}
structure(list(head = component_table(head, tidy_object),
body = component_table(tidy_object),
interfoot = NULL,
foot = foot,
border_collapse = border_collapse,
caption = caption,
caption_number = caption_number,
label = label,
justify = justify,
float = float,
longtable = longtable,
table_width = 6,
tabcolsep = tabcolsep,
hhline = hhline,
bookdown = bookdown,
fixed_header = fixed_header,
include_fixed_header_css = FALSE,
fixed_header_param =
list(
fixed_header_class_name = "pixie-fixed",
scroll_body_height = 300,
scroll_body_height_units = "px",
scroll_body_background_color = "white",
fixed_header_height = 20,
fixed_header_height_units = "px",
fixed_header_text_height = 10,
fixed_header_text_height_units = "px",
fixed_header_background_color = "white"
),
html_preserve = html_preserve,
print_method = pixiedust_print_method()),
class = "dust")
}
dust.grouped_df <- function(object, ungroup = TRUE, ...)
{
if (ungroup)
{
dust.default(as.data.frame(object), ...)
}
else
{
split_var <- attr(object, "var")
object <- as.data.frame(object)
object <- split(object, object[, as.character(split_var)])
dust.list(object, ...)
}
}
dust.list <- function(object, ...)
{
structure(
lapply(X = object,
FUN = dust,
...),
class = "dust_list"
)
}
component_table <- function(tbl, object)
{
if (missing(object)) object <- tbl
Classes <- data.frame(col_name = colnames(object),
col_class = vapply(object, primaryClass, character(1)),
stringsAsFactors=FALSE)
tab <- gather_tbl(tbl)
tab <- dplyr::left_join(tab, cell_attributes_frame(nrow(tbl), ncol(tbl)),
by = c("row" = "row", "col" = "col"))
tab <- dplyr::left_join(tab, Classes,
by = c("col_name" = "col_name"))
return(tab)
}
gather_tbl <- function(tbl)
{
tbl_name <- names(tbl)
tbl[["row"]] <- seq_len(nrow(tbl))
dplyr::mutate_(tbl, row = ~1:n()) %>%
tidyr::gather_("col", "value",
gather_cols=names(tbl)[!names(tbl) %in% "row"]) %>%
dplyr::mutate_(col_name = ~factor(col, colnames(tbl)),
col = ~as.numeric(col_name),
col_name = ~as.character(col_name),
value = ~as.character(value))
}
cell_attributes_frame <- function(nrow, ncol)
{
frame <-
expand.grid(row = 1:nrow,
col = 1:ncol,
fn = NA,
round = "",
bold = FALSE,
italic = FALSE,
halign = "",
valign = "",
bg = "",
font_family = "",
font_color = "",
font_size = "",
font_size_units = "",
left_border = "",
right_border = "",
top_border = "",
bottom_border = "",
height = "",
height_units = "",
width = "",
width_units = "",
replace = NA,
rotate_degree = "",
sanitize = FALSE,
sanitize_args = "",
pad = "",
rowspan = 1L,
colspan = 1L,
na_string = NA,
stringsAsFactors=FALSE)
frame[["html_row"]] <- frame[["row"]]
frame[["html_col"]] <- frame[["col"]]
frame[["merge_rowval"]] <- frame[["row"]]
frame[["merge_colval"]] <- frame[["col"]]
frame[["merge"]] <- FALSE
frame
}
primaryClass <- function(x)
{
acceptedClasses <- c("integer", "double", "numeric",
"character", "factor", "logical")
class_vector <- class(x)
class_vector[class_vector %in% acceptedClasses][1]
} |
testthat::context("test run HMC-v4")
library(testthat)
suppressMessages(library(magi))
set.seed(Sys.time())
kerneltype <- sample(c("compact1","rbf","matern"),1)
nobs <- 26
noise <- 0.05
VRtrue <- read.csv(system.file("testdata/FN.csv", package="magi"))
pram.true <- list(
abc=c(0.2,0.2,3),
rphi=c(0.9486433, 3.2682434),
vphi=c(1.9840824, 1.1185157),
sigma=noise
)
fn.true <- VRtrue[seq(1,401,by=2),]
fn.true$time <- seq(0,20,0.1)
fn.sim <- fn.true
myseed <- sample(1e10, 1)
myseed <- 123
set.seed(myseed)
fn.sim[,1:2] <- fn.sim[,1:2]+rnorm(length(unlist(fn.sim[,1:2])), sd=noise)
tvec.full <- fn.sim$time
fn.sim.all <- fn.sim
fn.sim[-seq(1,nrow(fn.sim), length=nobs),] <- NaN
fn.sim.obs <- fn.sim[seq(1,nrow(fn.sim), length=nobs),]
tvec.nobs <- fn.sim$time[seq(1,nrow(fn.sim), length=nobs)]
config <- list(
nobs = nobs,
noise = noise,
kernel = kerneltype,
seed = myseed,
npostplot = 5
)
foo <- outer(tvec.full, t(tvec.full),'-')[,1,]
r <- abs(foo)
r2 <- r^2
signr <- -sign(foo)
foo <- outer(tvec.nobs, t(tvec.nobs),'-')[,1,]
r.nobs <- abs(foo)
r2.nobs <- r.nobs^2
signr.nobs <- -sign(foo)
magi:::phisigllikC( c(1.9840824, 1.1185157, 0.9486433, 3.2682434, noise), data.matrix(fn.sim[!is.nan(fn.sim[,1]),1:2]), r.nobs, kerneltype)
fn <- function(par) -magi:::phisigllikC( par, data.matrix(fn.sim[!is.nan(fn.sim[,1]),1:2]), r.nobs, kerneltype)$value
gr <- function(par) -as.vector(magi:::phisigllikC( par, data.matrix(fn.sim[!is.nan(fn.sim[,1]),1:2]), r.nobs, kerneltype)$grad)
marlikmap <- optim(rep(1,5), fn, gr, method="L-BFGS-B", lower = 0.0001)
cursigma <- marlikmap$par[5]
testthat::test_that("phisigllik in R is the same as phisigllikC in C", {
phisigllikOutR <- magi:::phisigllik(marlikmap$par, data.matrix(fn.sim.obs[,1:2]), r.nobs, signr.nobs, TRUE, kerneltype)
phisigllikOutC <- magi:::phisigllikC( marlikmap$par, data.matrix(fn.sim.obs[,1:2]), r.nobs, kerneltype)
testthat::expect_equal(as.numeric(phisigllikOutR), phisigllikOutC$value, tolerance = 1e-5)
testthat::expect_equal(attr(phisigllikOutR,"grad"), as.numeric(phisigllikOutC$grad),
tolerance = 1e-5)
})
testthat::test_that("xthetallik in R is the same as in C", {
xthetallikOurR <- magi:::xthetallik( data.matrix(fn.true[seq(1,nrow(fn.true), length=nobs), 1:2]),
c(0.2, 0.2, 3),
calCov(marlikmap$par[1:2], r.nobs, signr.nobs, kerneltype=kerneltype),
calCov(marlikmap$par[3:4], r.nobs, signr.nobs, kerneltype=kerneltype),
cursigma,
data.matrix(fn.sim.obs[,1:2]),
T)
xthetallikOurC <- magi:::xthetallikC( data.matrix(fn.sim.obs[,1:2]),
calCov(marlikmap$par[1:2], r.nobs, signr.nobs, kerneltype=kerneltype),
calCov(marlikmap$par[3:4], r.nobs, signr.nobs, kerneltype=kerneltype),
cursigma,
c(data.matrix(fn.true[seq(1,nrow(fn.true), length=nobs), 1:2]), 0.2, 0.2, 3))
logliknoODEOutR <- magi:::logliknoODE( data.matrix(fn.true[seq(1,nrow(fn.true), length=nobs), 1:2]),
calCov(marlikmap$par[1:2], r.nobs, signr.nobs, kerneltype=kerneltype),
calCov(marlikmap$par[3:4], r.nobs, signr.nobs, kerneltype=kerneltype),
cursigma,
data.matrix(fn.sim.obs[,1:2]))
loglikOutR <- magi:::loglik( data.matrix(fn.true[seq(1,nrow(fn.true), length=nobs), 1:2]),
c(0.2, 0.2, 3),
calCov(marlikmap$par[1:2], r.nobs, signr.nobs, kerneltype=kerneltype),
calCov(marlikmap$par[3:4], r.nobs, signr.nobs, kerneltype=kerneltype),
cursigma,
data.matrix(fn.sim.obs[,1:2]))
testthat::expect_equal(as.numeric(xthetallikOurR), xthetallikOurC$value, tolerance = 1e-5)
testthat::expect_equal(attr(xthetallikOurR, "grad"), as.numeric(xthetallikOurC$grad),
tolerance = 1e-5)
testthat::expect_equal(attr(logliknoODEOutR,"components")[,-2],
attr(loglikOutR,"components")[,-2],
tolerance = 1e-5)
})
if(interactive()){
curCovV <- calCov(marlikmap$par[1:2], r, signr, bandsize=20, kerneltype=kerneltype)
curCovR <- calCov(marlikmap$par[3:4], r, signr, bandsize=20, kerneltype=kerneltype)
cursigma <- marlikmap$par[5]
startVR <- rbind(magi:::getMeanCurve(fn.sim.obs$time, fn.sim.obs$Vtrue, fn.sim.obs$time,
t(marlikmap$par[1:2]), sigma.mat=rep(cursigma,nrow(fn.sim.obs)), kerneltype),
magi:::getMeanCurve(fn.sim.obs$time, fn.sim.obs$Rtrue, fn.sim.obs$time,
t(marlikmap$par[3:4]), sigma.mat=rep(cursigma,nrow(fn.sim.obs)), kerneltype))
startVR <- t(startVR)
nfold.pilot <- ceiling(nobs/40)
nobs.pilot <- nobs%/%nfold.pilot
numparam.pilot <- nobs.pilot*2+3
n.iter.pilot <- 50
if(kerneltype=="matern"){
pilotstepsize <- 0.001
}else if(kerneltype=="rbf"){
pilotstepsize <- 0.00001
}else if(kerneltype=="compact1"){
pilotstepsize <- 0.0001
}
stepLow.scaler.pilot <- matrix(NA, n.iter.pilot, nfold.pilot)
stepLow.scaler.pilot[1,] <- pilotstepsize
apr.pilot <- accepts.pilot <- matrix(NA, n.iter.pilot, nfold.pilot)
apr.pilot[1,] <- accepts.pilot[1,] <- 0
rstep.pilot <- array(NA, dim=c(numparam.pilot, n.iter.pilot, nfold.pilot))
rstep.pilot[,1,] <- stepLow.scaler.pilot[1,]
xth.pilot <- array(NA, dim=c(numparam.pilot, n.iter.pilot, nfold.pilot))
lliklist.pilot <- matrix(NA, n.iter.pilot, nfold.pilot)
id.pilot <- matrix(1:(nfold.pilot*nobs.pilot), nobs.pilot, byrow = T)
it.pilot <- 1
for(it.pilot in 1:nfold.pilot){
accepts <- c()
stepLow <- rep(stepLow.scaler.pilot[1,it.pilot], nobs.pilot*2+3)
fn.sim.pilot <- fn.sim.obs[id.pilot[,it.pilot],]
pilotSignedDist <- outer(fn.sim.pilot$time, t(fn.sim.pilot$time),'-')[,1,]
xth.pilot[,1,it.pilot] <- c(startVR[id.pilot[,it.pilot],],rep(1,3))
pilotCovV <- calCov(marlikmap$par[1:2], abs(pilotSignedDist), -sign(pilotSignedDist), kerneltype=kerneltype)
pilotCovR <- calCov(marlikmap$par[3:4], abs(pilotSignedDist), -sign(pilotSignedDist), kerneltype=kerneltype)
t <- 2
for (t in 2:n.iter.pilot) {
rstep <- runif(length(stepLow), stepLow, 2*stepLow)
foo <- magi:::xthetaSample(data.matrix(fn.sim.pilot[,1:2]), list(pilotCovV, pilotCovR), cursigma,
xth.pilot[,t-1,it.pilot], rstep, 20, T)
xth.pilot[,t,it.pilot] <- foo$final
accepts.pilot[t,it.pilot] <- foo$acc
apr.pilot[t,it.pilot] <- foo$apr
stepLow.scaler.pilot[t,it.pilot] <- tail(stepLow,1)
rstep.pilot[,t,it.pilot] <- rstep
if (mean(tail(accepts.pilot[1:t,it.pilot],100)) > 0.9) {
stepLow <- stepLow * 1.01
}else if (mean(tail(accepts.pilot[1:t,it.pilot],100)) < 0.6) {
stepLow <- stepLow * .99
}
lliklist.pilot[t,it.pilot] <- foo$lpr
}
}
x <- apply(xth.pilot[-(1:(2*nobs.pilot)),,,drop=FALSE], c(1,3), plot)
startTheta <- apply(xth.pilot[(nobs.pilot*2+1):(nobs.pilot*2+3),-(1:(dim(xth.pilot)[[2]]/2)),], 1, mean)
stepLow <- mean(stepLow.scaler.pilot[rbind(0,diff(accepts.pilot))==1])/nfold.pilot^2
steptwopart <- apply(rstep.pilot, 1, function(x) sum(x*(apr.pilot>0.8))/sum(apr.pilot>0.8))
mean(steptwopart[1:(2*nobs.pilot)])
mean(tail(steptwopart,3))
scalefac <- apply(xth.pilot[,-(1:(dim(xth.pilot)[[2]]/2)),,drop=FALSE], c(1,3), sd)
scalefacV <- as.vector(t(scalefac[1:nobs.pilot,]))
scalefacV <- c(scalefacV, rep(mean(scalefacV), nobs-nobs.pilot*nfold.pilot))
scalefacR <- as.vector(t(scalefac[(nobs.pilot+1):(2*nobs.pilot),]))
scalefacR <- c(scalefacR, rep(mean(scalefacR), nobs-nobs.pilot*nfold.pilot))
scalefacTheta <- rowMeans(tail(scalefac,3))
scalefac <- c(scalefacV, scalefacR, scalefacTheta)
scalefac <- scalefac/mean(scalefac)
nall <- nrow(fn.sim)
numparam <- nall*2+3
n.iter <- 50
xth.formal <- matrix(NA, n.iter, numparam)
obs.ind <- seq(1,nrow(fn.sim),length=nobs)
C.Vxx <- curCovV$C[obs.ind,obs.ind]
C.Vxmx <- curCovV$C[-obs.ind,obs.ind]
C.Vxmxm <- curCovV$C[-obs.ind,-obs.ind]
C.Rxx <- curCovR$C[obs.ind,obs.ind]
C.Rxmx <- curCovR$C[-obs.ind,obs.ind]
C.Rxmxm <- curCovR$C[-obs.ind,-obs.ind]
CV <- C.Vxmxm - C.Vxmx %*% solve(C.Vxx) %*% t(C.Vxmx)
CR <- C.Rxmxm - C.Rxmx %*% solve(C.Rxx) %*% t(C.Rxmx)
CV[upper.tri(CV)] <- t(CV)[upper.tri(CV)]
CR[upper.tri(CR)] <- t(CR)[upper.tri(CR)]
V_upsamp <- MASS::mvrnorm(1,C.Vxmx %*% solve(C.Vxx) %*% startVR[,1], CV)
R_upsamp <- MASS::mvrnorm(1,C.Rxmx %*% solve(C.Rxx) %*% startVR[,2], CR)
fullstartVR <- rep(NA, numparam-3)
fullstartVR[c(obs.ind,nall+obs.ind)] <- startVR
fullstartVR[-c(obs.ind,nall+obs.ind)] <- c(V_upsamp, R_upsamp)
xth.formal[1,] <- c(fullstartVR,startTheta)
xth.formal[1,] <- c(fn.true$Vtrue,fn.true$Rtrue, pram.true$abc)
lliklist <- stepLow.scaler <- accepts <- rep(NA, n.iter)
accepts[1] <- 0
stepLow.scaler[1] <- stepLow
fullscalefac <- rep(NA, numparam)
fullscalefac[c(obs.ind,nall+obs.ind,(2*nall+1):(2*nall+3))] <- scalefac
for (ii in 2:numparam) {
if (is.na(fullscalefac[ii])) {
fullscalefac[ii] <- fullscalefac[ii-1]
}
}
stepLow <- stepLow.scaler[1]*fullscalefac * nobs/nall
if(kerneltype=="matern"){
stepLow <- stepLow*0.4
}else if(kerneltype=="rbf"){
stepLow <- stepLow*0.08
}else if(kerneltype=="compact1"){
stepLow <- stepLow*0.3
}
burnin <- as.integer(n.iter*0.3)
n.iter.approx <- n.iter*0.9
for (t in 2:n.iter) {
rstep <- runif(length(stepLow), stepLow, 2*stepLow)
if(t < n.iter.approx){
foo <- magi:::xthetaSample(data.matrix(fn.sim[,1:2]), list(curCovV, curCovR), cursigma,
xth.formal[t-1,], rstep, 1000, T, loglikflag = "band")
}else{
foo <- magi:::xthetaSample(data.matrix(fn.sim[,1:2]), list(curCovV, curCovR), cursigma,
xth.formal[t-1,], rstep, 1000, T, loglikflag = "usual")
}
xth.formal[t,] <- foo$final
accepts[t] <- foo$acc
stepLow.scaler[t] <- mean(stepLow)
if (t < burnin & t > 10) {
if (mean(tail(accepts[1:t],100)) > 0.9) {
stepLow <- stepLow * 1.005
} else if (mean(tail(accepts[1:t],100)) < 0.6) {
stepLow <- stepLow * .995
}
}
lliklist[t] <- foo$lpr
}
gpode <- list(abc=xth.formal[-(1:burnin), (nall*2+1):(nall*2+3)],
sigma=rep(marlikmap$par[5], n.iter-burnin),
rphi=matrix(marlikmap$par[3:4], ncol=2,nrow=n.iter-burnin,byrow=T),
vphi=matrix(marlikmap$par[1:2], ncol=2,nrow=n.iter-burnin,byrow=T),
rtrue=xth.formal[-(1:burnin), (nall+1):(nall*2)],
vtrue=xth.formal[-(1:burnin), 1:nall],
lp__=lliklist[-(1:burnin)],
lglik=lliklist[-(1:burnin)])
gpode$fode <- sapply(1:length(gpode$lp__), function(t)
with(gpode, magi:::fODE(abc[t,], cbind(vtrue[t,],rtrue[t,]))), simplify = "array")
fn.true$dVtrue = with(c(fn.true,pram.true), abc[3] * (Vtrue - Vtrue^3/3.0 + Rtrue))
fn.true$dRtrue = with(c(fn.true,pram.true), -1.0/abc[3] * (Vtrue - abc[1] + abc[2]*Rtrue))
fn.sim$time <- fn.sim.all$time
magi:::plotPostSamples(paste0(tempdir(), "/test-run-HMCv4-",kerneltype,".pdf"),
fn.true, fn.sim, gpode, pram.true, config)
} |
context("test-sc_within")
test_that("sc_within defaults to vector", {
x <- sc_within(
hue = "red",
light = 1:2
)
expect_equal(class(x), "character")
expect_equal(length(x), 2)
})
test_that("sc_within returns ggplot", {
x <- sc_within(
hue = "red",
light = 1:2,
return = "plot"
)
expect_equal(is(x), "gg")
})
test_that("sc_within returns table", {
x <- sc_within(
hue = "red",
light = 1:2,
return = "table"
)
expect_true(is.data.frame(x))
})
test_that("sc_* match sc_within", {
expect_equal(sc_red(), sc_within("red"))
expect_equal(sc_orange(), sc_within("orange"))
expect_equal(sc_yellow(), sc_within("yellow"))
expect_equal(sc_green(), sc_within("green"))
expect_equal(sc_teal(), sc_within("teal"))
expect_equal(sc_blue(), sc_within("blue"))
expect_equal(sc_violet(), sc_within("violet"))
expect_equal(sc_pink(), sc_within("pink"))
expect_equal(sc_grey(), sc_within("grey"))
}) |
act.options.default <- list (
act.excamplecorpusURL = " http://www.romanistik.uni-freiburg.de/ehmer/files/digitalhumanities/act_examplecorpus.zip",
act.updateX = TRUE,
act.showprogress = TRUE,
act.path.praat = "",
act.path.sendpraat = "",
act.path.elan = "",
act.fileformats.video = c("mp4", "mov"),
act.fileformats.audio = c("wav", "aif", "aiff", "mp3"),
act.ffmpeg.command.main = 'ffmpeg -i "INFILEPATH" -ss TIMESTART -t TIMEDURATION OPTIONS -y "OUTFILEPATH" -hide_banner',
act.ffmpeg.command.fastVideoPostioning = 'ffmpeg -ss TIMESTARTMINUS10SECONDS -i "INFILEPATH" -ss 10.000 -t TIMEDURATION OPTIONS -y "OUTFILEPATH" -hide_banner',
act.ffmpeg.command.audioCutsAsMP3 = 'ffmpeg -i "INFILEPATH" -ss TIMESTART -t TIMEDURATION OPTIONS -y "OUTFILEPAT" -hide_banner',
act.ffmpeg.exportchannels.fromColumnName = "channels",
act.import.readEmptyIntervals = FALSE,
act.import.scanSubfolders = TRUE,
act.import.storeFileContentInTranscript = TRUE,
act.export.foldergrouping1.fromColumnName = "resultID",
act.export.foldergrouping2.fromColumnName = "",
act.export.filename.fromColumnName = "resultID",
act.separator_between_intervals = "&",
act.separator_between_tiers = "
act.separator_between_words = "^\\s|\\|\\'|\\
act.wordCountRegEx = '(?<=[^|\\b])[A-z\\u00C0-\\u00FA\\-\\:]+(?=\\b|\\s|_|$)'
)
options_show <- function () {
cat("options", fill=TRUE)
cat(" Program", fill=TRUE)
cat(" act.excamplecorpusURL : ",paste("'", options()$act.excamplecorpusURL,"'",sep="", collapse=""), fill=TRUE)
cat(" act.showprogress : ",paste("'", options()$act.showprogress,"'",sep="", collapse=""), fill=TRUE)
cat(" act.updateX : ",paste("'", options()$act.updateX,"'",sep="", collapse=""), fill=TRUE)
cat(" Paths", fill=TRUE)
cat(" act.path.praat : ",paste("'", options()$act.path.praat,"'",sep="", collapse=""), fill=TRUE)
cat(" act.path.sendpraat : ",paste("'", options()$act.path.sendpraat, "'",sep="", collapse=""),fill=TRUE)
cat(" act.path.elan : ",paste("'", options()$act.path.elan, "'",sep="", collapse=""),fill=TRUE)
cat("", fill=TRUE)
cat(" File formats", fill=TRUE)
cat(" act.fileformats.video : ",paste("'", options()$act.fileformats.video, "'",sep="", collapse=""),fill=TRUE)
cat(" act.fileformats.audio : ",paste("'", options()$act.fileformats.audio, "'",sep="", collapse=""),fill=TRUE)
cat("", fill=TRUE)
cat(" FFMPEG commands and options", fill=TRUE)
cat(" act.ffmpeg.command : ",paste("'", options()$act.ffmpeg.command,"'",sep="", collapse=""), fill=TRUE)
cat(" act.ffmpeg.command.fastVideoPostioning : ",paste("'", options()$act.ffmpeg.command.fastVideoPostioning, "'",sep="", collapse=""),fill=TRUE)
cat(" act.ffmpeg.command.audio : ",paste("'", options()$act.ffmpeg.command.audio, "'",sep="", collapse=""),fill=TRUE)
cat(" act.ffmpeg.command.UsefastVideoPostioning : ",paste("'", options()$act.ffmpeg.command.UsefastVideoPostioning, "'",sep="", collapse=""),fill=TRUE)
cat(" act.ffmpeg.exportchannels.fromColumnName : ",paste("'", options()$act.ffmpeg.exportchannels.fromColumnName, "'",sep="", collapse=""),fill=TRUE)
cat("", fill=TRUE)
cat(" Import annotation files", fill=TRUE)
cat(" act.import.readEmptyIntervals : ", options()$act.import.readEmptyIntervals, fill=TRUE)
cat(" act.import.scanSubfolders : ", options()$act.import.scanSubfolders, fill=TRUE)
cat(" act.import.storeFileContentInTranscript : ", options()$act.import.scanSubfolders, fill=TRUE)
cat("", fill=TRUE)
cat(" Export", fill=TRUE)
cat(" act.export.foldergrouping1.fromColumnName : ",paste("'", options()$act.export.foldergrouping1.fromColumnName,"'",sep="", collapse=""), fill=TRUE)
cat(" act.export.foldergrouping2.fromColumnName : ",paste("'", options()$act.export.foldergrouping2.fromColumnName,"'",sep="", collapse=""), fill=TRUE)
cat(" act.export.filename.fromColumnName : ",paste("'", options()$act.export.filename.fromColumnName, "'",sep="", collapse=""),fill=TRUE)
cat("", fill=TRUE)
cat(" Miscellaneous", fill=TRUE)
cat(" act.separator_between_intervals : ",paste("'", options()$act.separator_between_intervals, "'",sep="", collapse=""),fill=TRUE)
cat(" act.separator_between_tiers : ",paste("'", options()$act.separator_between_tiers, "'",sep="", collapse=""),fill=TRUE)
cat(" act.separator_between_words : ",paste("'", options()$act.separator_between_words, "'",sep="", collapse=""),fill=TRUE)
cat(" act.wordCountRegEx : ",paste("'", options()$act.wordCountRegEx, "'",sep="", collapse=""), fill=TRUE)
}
options_delete <- function() {
options(act.excamplecorpusURL = NULL)
options(act.showprogress = NULL)
options(act.updateX = NULL)
options(act.path.praat = NULL)
options(act.path.sendpraat = NULL)
options(act.path.elan = NULL)
options(act.fileformats.video = NULL)
options(act.fileformats.audio = NULL)
options(act.ffmpeg.command.main = NULL)
options(act.ffmpeg.command.fastVideoPostioning = NULL)
options(act.ffmpeg.command.audioCutsAsMP3 = NULL)
options(act.ffmpeg.exportchannels.fromColumnName= NULL)
options(act.import.readEmptyIntervals = NULL)
options(act.import.scanSubfolders = NULL)
options(act.import.storeFileContentInTranscript = NULL)
options(act.export.foldergrouping1.fromColumnName= NULL)
options(act.export.foldergrouping2.fromColumnName= NULL)
options(act.export.filename.fromColumnName = NULL)
options(act.separator_between_intervals = NULL)
options(act.separator_between_tiers = NULL)
options(act.separator_between_words = NULL)
options(act.wordCountRegEx = NULL)
}
options_reset <- function () {
options(act.options.default[2:length(act.options.default)])
} |
test_that("got_chars list hasn't changed", {
expect_known_value(got_chars, reference_file("got_chars.rds"))
})
test_that("got_chars JSON gives rise to same list as the built-in", {
skip_if_not_installed("jsonlite")
expect_identical(
got_chars,
jsonlite::fromJSON(got_chars_json(),
simplifyDataFrame = FALSE
)
)
}) |
eqsCorr <-
function(eqs)
{
options(warn=-1)
eqs <- eqsCov(eqs)
eqs <- cov2cor(eqs)
return(eqs)
} |
"xSub_census_multiple_raw" |
.isMissing_str <- function(x) {
any(is.na(x) | x == "")
}
.isMissing_num <- function(x) {
any(is.na(x) | is.nan(x) | is.infinite(x))
}
.countUnique <- function(x) {
length(unique(x))
} |
transf.rtoz <- function(xi, ...)
atanh(xi)
transf.ztor <- function(xi, ...)
tanh(xi)
transf.logit <- function(xi, ...)
qlogis(xi)
transf.ilogit <- function(xi, ...)
plogis(xi)
transf.arcsin <- function(xi, ...)
asin(sqrt(xi))
transf.iarcsin <- function(xi, ...) {
zi <- sin(xi)^2
zi[xi < 0] <- 0
zi[xi > asin(1)] <- 1
return(c(zi))
}
transf.pft <- function(xi, ni, ...) {
xi <- xi*ni
zi <- 1/2*(asin(sqrt(xi/(ni+1))) + asin(sqrt((xi+1)/(ni+1))))
return(c(zi))
}
transf.ipft <- function(xi, ni, ...) {
zi <- suppressWarnings(1/2 * (1 - sign(cos(2*xi)) * sqrt(1 - (sin(2*xi)+(sin(2*xi)-1/sin(2*xi))/ni)^2)))
zi <- ifelse(is.nan(zi), NA, zi)
zi[xi > transf.pft(1,ni)] <- 1
zi[xi < transf.pft(0,ni)] <- 0
return(c(zi))
}
transf.ipft.hm <- function(xi, targs, ...) {
if (is.null(targs) || (is.list(targs) && is.null(targs$ni)))
stop("Need to specify the sample sizes via the 'targs' argument.", call.=FALSE)
if (is.list(targs)) {
ni <- targs$ni
} else {
ni <- ni
}
nhm <- 1/(mean(1/ni, na.rm=TRUE))
zi <- suppressWarnings(1/2 * (1 - sign(cos(2*xi)) * sqrt(1 - (sin(2*xi)+(sin(2*xi)-1/sin(2*xi))/nhm)^2)))
zi <- ifelse(is.nan(zi), NA, zi)
zi[xi > transf.pft(1,nhm)] <- 1
zi[xi < transf.pft(0,nhm)] <- 0
return(c(zi))
}
transf.isqrt <- function(xi, ...) {
zi <- xi*xi
zi[xi < 0] <- 0
return(c(zi))
}
transf.irft <- function(xi, ti, ...) {
zi <- 1/2*(sqrt(xi) + sqrt(xi + 1/ti))
return(c(zi))
}
transf.iirft <- function(xi, ti, ...) {
zi <- (1/ti - 8*xi^2 + 16*ti*xi^4)/(16*xi^2*ti)
zi <- ifelse(is.nan(zi), NA, zi)
zi[xi < transf.irft(0,ti)] <- 0
zi[zi <= .Machine$double.eps] <- 0
return(c(zi))
}
transf.ahw <- function(xi, ...) {
zi <- 1 - (1-xi)^(1/3)
return(c(zi))
}
transf.iahw <- function(xi, ...) {
zi <- 1 - (1-xi)^3
zi <- ifelse(is.nan(zi), NA, zi)
zi[xi > 1] <- 1
zi[xi < 0] <- 0
return(c(zi))
}
transf.abt <- function(xi, ...) {
zi <- -log(1-xi)
return(c(zi))
}
transf.iabt <- function(xi, ...) {
zi <- 1 - exp(-xi)
zi <- ifelse(is.nan(zi), NA, zi)
zi[xi < 0] <- 0
return(c(zi))
}
transf.ztor.int <- function(xi, targs=NULL, ...) {
if (is.null(targs$tau2))
targs$tau2 <- 0
if (is.null(targs$lower))
targs$lower <- xi-5*sqrt(targs$tau2)
if (is.null(targs$upper))
targs$upper <- xi+5*sqrt(targs$tau2)
toint <- function(zval, xi, tau2)
tanh(zval) * dnorm(zval, mean=xi, sd=sqrt(tau2))
cfunc <- function(xi, tau2, lower, upper)
integrate(toint, lower=lower, upper=upper, xi=xi, tau2=tau2)$value
if (targs$tau2 == 0) {
zi <- transf.ztor(xi)
} else {
zi <- mapply(xi, FUN=cfunc, tau2=targs$tau2, lower=targs$lower, upper=targs$upper)
}
return(c(zi))
}
transf.exp.int <- function(xi, targs=NULL, ...) {
if (is.null(targs$tau2))
targs$tau2 <- 0
if (is.null(targs$lower))
targs$lower <- xi-5*sqrt(targs$tau2)
if (is.null(targs$upper))
targs$upper <- xi+5*sqrt(targs$tau2)
toint <- function(zval, xi, tau2)
exp(zval) * dnorm(zval, mean=xi, sd=sqrt(tau2))
cfunc <- function(xi, tau2, lower, upper)
integrate(toint, lower=lower, upper=upper, xi=xi, tau2=tau2)$value
if (targs$tau2 == 0) {
zi <- exp(xi)
} else {
zi <- mapply(xi, FUN=cfunc, tau2=targs$tau2, lower=targs$lower, upper=targs$upper)
}
return(c(zi))
}
transf.ilogit.int <- function(xi, targs=NULL, ...) {
if (is.null(targs$tau2))
targs$tau2 <- 0
if (is.null(targs$lower))
targs$lower <- xi-5*sqrt(targs$tau2)
if (is.null(targs$upper))
targs$upper <- xi+5*sqrt(targs$tau2)
toint <- function(zval, xi, tau2)
plogis(zval) * dnorm(zval, mean=xi, sd=sqrt(tau2))
cfunc <- function(xi, tau2, lower, upper)
integrate(toint, lower=lower, upper=upper, xi=xi, tau2=tau2)$value
if (targs$tau2 == 0) {
zi <- transf.ilogit(xi)
} else {
zi <- mapply(xi, FUN=cfunc, tau2=targs$tau2, lower=targs$lower, upper=targs$upper)
}
return(c(zi))
}
transf.dtou1 <- function(xi, ...) {
u2i <- pnorm(abs(xi)/2)
return((2*u2i - 1) / u2i)
}
transf.dtou2 <- function(xi, ...)
pnorm(xi/2)
transf.dtou3 <- function(xi, ...)
pnorm(xi)
transf.dtocles <- function(xi, ...)
pnorm(xi/sqrt(2))
transf.dtorpb <- function(xi, n1i, n2i, ...) {
if (missing(n1i) || missing(n2i)) {
hi <- 4
} else {
if (length(n1i) != length(n2i))
stop("Length of 'n1i' does not match length of 'n2i'.", call.=FALSE)
if (length(n1i) != length(xi))
stop("Length of 'n1i' and 'n2i' does not match length of 'xi'.", call.=FALSE)
mi <- n1i + n2i - 2
hi <- mi / n1i + mi / n2i
}
return(xi / sqrt(xi^2 + hi))
}
transf.dtobesd <- function(xi, ...) {
rpbi <- xi / sqrt(xi^2 + 4)
return(0.50 + rpbi/2)
}
transf.dtomd <- function(xi, targs=NULL, ...) {
if (is.null(targs) || (is.list(targs) && is.null(targs$sd)))
stop("Need to specify a standard deviation value via the 'targs' argument.", call.=FALSE)
if (is.list(targs)) {
sd <- targs$sd
} else {
sd <- targs
}
if (length(sd) != 1L)
stop("Specify a single standard deviation value via the 'targs' argument.", call.=FALSE)
return(xi * sd)
}
transf.logortord <- function(xi, pc, ...) {
if (length(pc) == 1L)
pc <- rep(pc, length(xi))
if (length(xi) != length(pc))
stop("Length of 'xi' does not match length of 'pc'.", call.=FALSE)
if (any(pc < 0) || any(pc > 1))
stop("The control group risk 'pc' must be between 0 and 1.", call.=FALSE)
return(exp(xi)*pc / (1 - pc + pc * exp(xi)) - pc)
}
transf.logortorr <- function(xi, pc, ...) {
if (length(pc) == 1L)
pc <- rep(pc, length(xi))
if (length(xi) != length(pc))
stop("Length of 'xi' does not match length of 'pc'.", call.=FALSE)
if (any(pc < 0) || any(pc > 1))
stop("The control group risk 'pc' must be between 0 and 1.", call.=FALSE)
return(exp(xi) / (pc * (exp(xi) - 1) + 1))
} |
library(testthat)
library(alluvial)
test_check("alluvial") |
library(ptm)
context("Abundance DB")
test_that("abundance() works properly", {
skip_on_cran()
skip_on_travis()
a <- abundance(id = 'A0AVT1')
b <- abundance(id = 'A0AVT1', 'jurkat')
c <- abundance(id = 'A0AVT1', 'hela')
d <- abundance(id = 'P30034')
e <- abundance(id = 'P010091')
f <- abundance(id = 'G1T1T4')
if (!is.null(a)){
expect_is(a, 'numeric')
expect_equal(attributes(a)$units, "ppm")
expect_equal(attributes(a)$species, "Homo sapiens")
expect_equal(attributes(a)$string, "A0AVT1")
expect_equivalent(a, 63.7)
}
if (!is.null(b)){
expect_is(b, 'numeric')
expect_equal(attributes(b)$units, "ppm")
expect_equal(attributes(b)$species, "Homo sapiens")
expect_equal(attributes(b)$string, "A0AVT1")
expect_equivalent(b, 27.4)
}
if (!is.null(c)){
expect_is(c, 'numeric')
expect_equal(attributes(c)$units, "ppm")
expect_equal(attributes(c)$species, "Homo sapiens")
expect_equal(attributes(c)$string, "A0AVT1")
expect_equivalent(c, 29.3)
}
if (!is.null(d)){
expect_is(d, 'numeric')
expect_equal(attributes(d)$units, "ppm")
expect_equal(attributes(d)$species, "Sus scrofa")
expect_equal(attributes(d)$string, "P30034")
expect_equivalent(d, 26.9)
}
expect_is(e, 'NULL')
expect_is(f, 'NULL')
}) |
QTLModelSIM <- function(x, mppData, trait, cross.mat, Q.eff, VCOV,
plot.gen.eff){
QTL <- inc_mat_QTL(x = x, mppData = mppData, Q.eff = Q.eff, order.MAF = TRUE)
QTL.el <- dim(QTL)[2]
ref.name <- colnames(QTL)
if(VCOV == "h.err"){
model <- tryCatch(expr = lm(trait ~ - 1 + cross.mat + QTL),
error = function(e) NULL)
if (is.null(model)){
if(plot.gen.eff) {
if(Q.eff == "cr"){ results <- c(0, rep(1, mppData$n.cr))
} else { results <- c(0, rep(1, mppData$n.par)) }
} else { results <- 0 }
} else {
if(!("QTL" %in% rownames(anova(model)))){
if(plot.gen.eff) {
if(Q.eff == "cr"){ results <- c(0, rep(1, mppData$n.cr))
} else { results <- c(0, rep(1, mppData$n.par)) }
} else { results <- 0 }
} else {
if(plot.gen.eff){
gen.eff <- QTL_pval(mppData = mppData, model = model,
Q.eff = Q.eff, x = x)
results <- c(-log10(anova(model)$Pr[2]), gen.eff)
} else { results <- -log10(anova(model)$Pr[2]) }
}
}
} else if ((VCOV == "h.err.as") || (VCOV == "cr.err")){
} else if ((VCOV == "pedigree") || (VCOV == "ped_cr.err")){
}
return(results)
} |
{}
newdeducorrect <- function(corrected, corrections, status, Call=sys.call(-1) ){
if ( missing(corrections) ){
corrections <- data.frame(
row=numeric(0),
variable=character(0),
old=character(0),
new=character(0)
)
}
if (missing(status)){
status <- data.frame(
status = rep(NA,nrow(corrected))
)
}
corrsummary <- array(0,dim=c(1,ncol(corrected)+1),dimnames=list(NULL,c(colnames(corrected),'sum')))
if (nrow(corrections) > 0){
corrsummary <- addmargins(table(corrections$variable, useNA="no"))
rownames(corrections) <- NULL
}
structure(
list(
corrected = corrected,
corrections = corrections,
status = status,
timestamp = date(),
call = Call,
generatedby = if ( is.list(Call) ) { Call[[1]][[1]] } else { Call[[1]] },
user = getUsername()
),
class = c("deducorrect","list"),
statsummary = addmargins(table(status$status, useNA="ifany")),
corrsummary = corrsummary
)
}
print.deducorrect <- function(x, ...){
cat(paste(" deducorrect object generated by '",
x$generatedby, "'", " on ",x$timestamp, sep=""))
cat(paste("\n slots: ",paste(paste("$",names(x),sep=""), collapse=", ")))
cat("\n\n Record status:")
print(attr(x,"statsummary"))
cat("\n Variables corrected:\n")
print(attr(x,"corrsummary"))
} |
divide <- function(data, bounds = bound(), divider = list(hbar), level = 1, cascade = 0, max_wt = NULL) {
d <- partd(divider[[1]])
if (ncol(data) == d + 1) {
return(divide_once(data, bounds, divider[[1]], level, max_wt))
}
parent_data <- margin(data, rev(seq_len(d)))
parent_data <- parent_data[, c(rev(seq_len(d)), d + 1)]
parent <- divide_once(parent_data, bounds, divider[[1]], level, max_wt)
parentc <- parent
parentc$l <- parent$l + cascade
parentc$b <- parent$b + cascade
parentc$r <- parent$r + cascade
parentc$t <- parent$t + cascade
if (is.null(max_wt)) {
max_wt <- max(margin(data, d + 1, seq_len(d))$.wt, na.rm = TRUE)
}
pieces <- as.list(dlply(data, seq_len(d)))
children <- ldply(seq_along(pieces), function(i) {
piece <- pieces[[i]]
partition <- divide(piece[, -seq_len(d)], parentc[i, ], divider[-1],
level = level + 1, cascade = cascade, max_wt = max_wt)
labels <- piece[rep(1, nrow(partition)), 1:d, drop = FALSE]
cbind(labels, partition)
})
rbind.fill(parent, children)
}
divide_once <- function(data, bounds, divider, level = 1, max_wt = NULL) {
d <- partd(divider)
if (d > 1) {
data[-ncol(data)] <- lapply(data[-ncol(data)], addNA, ifany = TRUE)
wt <- tapply(data$.wt, data[-ncol(data)], identity)
data <- as.data.frame.table(wt, responseName = ".wt")
} else {
wt <- data$.wt
}
wt <- prop(wt)
if (is.null(max_wt)) max_wt <- max(wt, na.rm = TRUE)
partition <- divider(wt, bounds, max = max_wt)
cbind(data, partition, level = level)
} |
write_sol <- function(sol,file_name,title=NULL,append=TRUE,force_std_fmt=TRUE){
if(is.null(title)) title <- attr(sol,'title')
if(is.null(title)) title <- 'General DSSAT Soil Input File'
comments <- attr(sol,'comments')
if(force_std_fmt | is.null(attr(sol,'v_fmt'))){
attr(sol,'v_fmt') <- v_fmt_sol()
}
if(is.null(attr(sol,'tier_info'))){
attr(sol,'tier_info') <- tier_info_sol() %>%
{.[map_lgl(.,~{any(. != "SLB" & . %in% names(sol))})]}
}
sol_out <- 1:nrow(sol) %>%
map(~{sol[.,]}) %>%
map(write_soil_profile) %>%
unlist()
if(!append){
sol_out <- title %>%
str_c('*SOILS: ',.) %>%
c(.,comments,sol_out)
}
write(sol_out,file_name,append = append)
return(invisible())
} |
library(testthat)
library(recipes)
library(dplyr)
iris_rec <- recipe( ~ ., data = iris)
test_that('basic usage', {
rec <-
iris_rec %>%
step_arrange(desc(Sepal.Length), 1/Petal.Length)
prepped <- prep(rec, training = iris %>% slice(1:75))
dplyr_train <-
iris %>%
as_tibble() %>%
slice(1:75) %>%
dplyr::arrange(desc(Sepal.Length), 1/Petal.Length)
rec_train <- juice(prepped)
expect_equal(dplyr_train, rec_train)
dplyr_test <-
iris %>%
as_tibble() %>%
slice(76:150) %>%
dplyr::arrange(desc(Sepal.Length), 1/Petal.Length)
rec_test <- bake(prepped, iris %>% slice(76:150))
expect_equal(dplyr_test, rec_test)
})
test_that('quasiquotation', {
sort_vars <- c("Sepal.Length", "Petal.Length")
sort_vars <- syms(sort_vars)
rec_1 <-
iris_rec %>%
step_arrange(!!!sort_vars)
prepped_1 <- prep(rec_1, training = iris %>% slice(1:75))
dplyr_train <-
iris %>%
as_tibble() %>%
slice(1:75) %>%
arrange(Sepal.Length, Petal.Length)
rec_1_train <- juice(prepped_1)
expect_equal(dplyr_train, rec_1_train)
})
test_that('no input', {
no_inputs <-
iris_rec %>%
step_arrange() %>%
prep(training = iris) %>%
juice(composition = "data.frame")
expect_equal(no_inputs, iris)
})
test_that('printing', {
rec <- iris_rec %>% step_arrange(Sepal.Length)
expect_output(print(rec))
expect_output(prep(rec, training = iris, verbose = TRUE))
}) |
mlnormal_ic <- function( dev, beta, theta, N, G, posterior_obj )
{
ic <- list( "deviance"=as.vector(dev), N=N, G=G)
ic$loglike <- - dev / 2
ic$np.beta <- length(beta)
ic$np.theta <- length(theta)
ic$np <- ic$np.beta + ic$np.theta
ic$AIC <- dev + 2*ic$np
ic$log_prior <- posterior_obj$log_prior
ic$log_posterior <- posterior_obj$log_posterior
return(ic)
} |
context("Test clmi")
test_that("clmi throws errors correctly", {
lod.var <- toy_data$lod
expect_error(clmi("poll ~ case_cntrl + smoking + gender, toy_data", lod, 1))
expect_error(clmi(poll ~ case_cntrl + smoking + gender, toy_data, lodu, 1))
expect_error(clmi(poll ~ case_cntrl + smoking + gender, toy_data, NULL, 1))
expect_error(clmi(a * poll ~ case_cntrl + smoking + gender, toy_data,
lod, 1))
a <- 2
fn <- function(x) a * x
expect_true(!is.null(clmi(fn(poll) ~ case_cntrl + smoking + gender, toy_data,
lod, 1)))
expect_error(clmi(poll ~ case_cntrl + smoking + gender, "toy_data", lod, 1))
expect_error(clmi(poll ~ case_cntrl + smoking + gender, toy_data, lod, "a"))
expect_error(clmi(poll ~ case_cntrl + smoking + gender, toy_data, lod, 1, 0))
expect_error(clmi(poll ~ case_cntrl + smoking + gender, toy_data, lod,
1, c(2, 4)))
df <- toy_data
df$lod <- NULL
expect_error(clmi(poll ~ case_cntrl + smoking + gender, df, lod, 1))
df <- toy_data
df$poll <- log(df$poll)
expect_error(clmi(poll ~ case_cntrl + smoking + gender, df, lod, 1))
df <- toy_data
df$smoking[1] <- NA
expect_error(clmi(poll ~ case_cntrl + smoking + gender, df, lod, 1))
df <- toy_data
df$gender <- as.factor(df$gender)
expect_error(clmi(poll ~ case_cntrl + smoking + gender, df, lod, 1))
}) |
context("expectedVariables")
test_that("expectedVariables",
{
Net <- HydeNetwork(~ wells +
pe | wells +
d.dimer | pregnant*pe +
angio | pe +
treat | d.dimer*angio +
death | pe*treat,
data = PE) %>%
setDecisionNodes(treat, angio)
expect_equal(expectedVariables(Net, treat, TRUE),
c("d.dimer", "angio"))
}) |
expected <- eval(parse(text="TRUE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30), .Tsp = c(1960.08333333333, 1961.66666666667, 12), class = \"ts\"), \"ts\", FALSE)"));
.Internal(`inherits`(argv[[1]], argv[[2]], argv[[3]]));
}, o=expected); |
if (require("rstanarm") && require("testthat") && require("bayestestR") && require("emmeans")) {
set.seed(300)
model <- stan_glm(extra ~ group, data = sleep, refresh = 0)
em_ <- emmeans(model, ~group)
c_ <- pairs(em_)
emc_ <- emmeans(model, pairwise ~ group)
all_ <- rbind(em_, c_)
all_summ <- summary(all_)
set.seed(4)
model_p <- unupdate(model, verbose = FALSE)
set.seed(300)
test_that("emmGrid hdi", {
xhdi <- hdi(all_, ci = 0.95)
expect_equal(xhdi$CI_low, all_summ$lower.HPD, tolerance = 0.1)
expect_equal(xhdi$CI_high, all_summ$upper.HPD, tolerance = 0.1)
xhdi2 <- hdi(emc_, ci = 0.95)
expect_equal(xhdi$CI_low, xhdi2$CI_low)
})
test_that("emmGrid point_estimate", {
xpest <- point_estimate(all_, centrality = "all", dispersion = TRUE)
expect_equal(xpest$Median, all_summ$emmean, tolerance = 0.1)
xpest2 <- point_estimate(emc_, centrality = "all", dispersion = TRUE)
expect_equal(xpest$Median, xpest2$Median)
})
test_that("emmGrid ci", {
xci <- ci(all_, ci = 0.9)
expect_equal(length(xci$CI_low), 3)
expect_equal(length(xci$CI_high), 3)
})
test_that("emmGrid equivalence_test", {
xeqtest <- equivalence_test(all_, ci = 0.9, range = c(-0.1, 0.1))
expect_equal(length(xeqtest$ROPE_Percentage), 3)
expect_equal(length(xeqtest$ROPE_Equivalence), 3)
})
test_that("emmGrid estimate_density", {
xestden <- estimate_density(c_, method = "logspline", precision = 5)
expect_equal(length(xestden$x), 5)
})
test_that("emmGrid map_estimate", {
xmapest <- map_estimate(all_, method = "kernel")
expect_equal(length(xmapest$MAP_Estimate), 3)
})
test_that("emmGrid p_direction", {
xpd <- p_direction(all_, method = "direct")
expect_equal(length(xpd$pd), 3)
})
test_that("emmGrid p_map", {
xpmap <- p_map(all_, precision = 2^9)
expect_equal(length(xpmap$p_MAP), 3)
})
test_that("emmGrid p_rope", {
xprope <- p_rope(all_, range = c(-0.1, 0.1))
expect_equal(length(xprope$p_ROPE), 3)
})
test_that("emmGrid p_significance", {
xsig <- p_significance(all_, threshold = c(-0.1, 0.1))
expect_equal(length(xsig$ps), 3)
})
test_that("emmGrid rope", {
xrope <- rope(all_, range = "default", ci = .9)
expect_equal(length(xrope$ROPE_Percentage), 3)
})
test_that("emmGrid describe_posterior", {
expect_equal(
describe_posterior(all_)$median,
describe_posterior(emc_)$median
)
expect_equal(
describe_posterior(all_, bf_prior = model_p, test = "bf")$log_BF,
describe_posterior(emc_, bf_prior = model_p, test = "bf")$log_BF
)
})
test_that("emmGrid bayesfactor_parameters", {
skip_on_cran()
set.seed(4)
expect_equal(
bayesfactor_parameters(all_, prior = model, verbose = FALSE),
bayesfactor_parameters(all_, prior = model_p, verbose = FALSE)
)
emc_p <- emmeans(model_p, pairwise ~ group)
xbfp <- bayesfactor_parameters(all_, prior = model_p, verbose = FALSE)
xbfp2 <- bayesfactor_parameters(emc_, prior = model_p, verbose = FALSE)
xbfp3 <- bayesfactor_parameters(emc_, prior = emc_p, verbose = FALSE)
expect_equal(xbfp$log_BF, xbfp2$log_BF)
expect_equal(xbfp$log_BF, xbfp3$log_BF)
w <- capture_warnings(bayesfactor_parameters(all_))
expect_match(w[1], "Prior")
expect_match(w[2], "40")
expect_error(bayesfactor_parameters(regrid(all_), prior = model))
})
test_that("emmGrid bayesfactor_restricted", {
skip_on_cran()
skip_on_ci()
set.seed(4)
hyps <- c("`1` < `2`", "`1` < 0")
xrbf <- bayesfactor_restricted(em_, prior = model_p, hypothesis = hyps)
expect_equal(length(xrbf$log_BF), 2)
expect_equal(length(xrbf$p_prior), 2)
expect_equal(length(xrbf$p_posterior), 2)
expect_warning(bayesfactor_restricted(em_, hypothesis = hyps))
xrbf2 <- bayesfactor_restricted(emc_, prior = model_p, hypothesis = hyps)
expect_equal(xrbf, xrbf2)
})
test_that("emmGrid si", {
skip_on_cran()
set.seed(4)
xrsi <- si(all_, prior = model_p, verbose = FALSE)
expect_equal(length(xrsi$CI_low), 3)
expect_equal(length(xrsi$CI_high), 3)
xrsi2 <- si(emc_, prior = model_p, verbose = FALSE)
expect_equal(xrsi$CI_low, xrsi2$CI_low)
expect_equal(xrsi$CI_high, xrsi2$CI_high)
})
set.seed(333)
df <- data.frame(
G = rep(letters[1:3], each = 2),
Y = rexp(6)
)
fit_bayes <- stan_glm(Y ~ G,
data = df,
family = Gamma(link = "identity"),
refresh = 0
)
fit_bayes_prior <- unupdate(fit_bayes, verbose = FALSE)
bayes_sum <- emmeans(fit_bayes, ~G)
bayes_sum_prior <- emmeans(fit_bayes_prior, ~G)
test_that("emmGrid bayesfactor_parameters", {
set.seed(333)
xsdbf1 <- bayesfactor_parameters(bayes_sum, prior = fit_bayes, verbose = FALSE)
xsdbf2 <- bayesfactor_parameters(bayes_sum, prior = bayes_sum_prior, verbose = FALSE)
expect_equal(xsdbf1$log_BF, xsdbf2$log_BF, tolerance = 0.1)
})
test_that("emmGrid bayesfactor_parameters / describe w/ nonlinear models", {
skip_on_cran()
model <- stan_glm(vs ~ mpg,
data = mtcars,
family = "binomial",
refresh = 0
)
probs <- emmeans(model, "mpg", type = "resp")
link <- emmeans(model, "mpg")
probs_summ <- summary(probs)
link_summ <- summary(link)
xhdi <- hdi(probs, ci = 0.95)
xpest <- point_estimate(probs, centrality = "median", dispersion = TRUE)
expect_equal(xhdi$CI_low, probs_summ$lower.HPD, tolerance = 0.1)
expect_equal(xhdi$CI_high, probs_summ$upper.HPD, tolerance = 0.1)
expect_equal(xpest$Median, probs_summ$prob, tolerance = 0.1)
xhdi <- hdi(link, ci = 0.95)
xpest <- point_estimate(link, centrality = "median", dispersion = TRUE)
expect_equal(xhdi$CI_low, link_summ$lower.HPD, tolerance = 0.1)
expect_equal(xhdi$CI_high, link_summ$upper.HPD, tolerance = 0.1)
expect_equal(xpest$Median, link_summ$emmean, tolerance = 0.1)
})
} |
rotateScale3D <- function(rot_angles = c(0,0,0),
scale_factors = c(1,1,1)){
rot_angles <- unlist(rot_angles)
yaw <- rot_angles[1]
pitch <- rot_angles[2]
roll <- rot_angles[3]
scale_factors <- unlist(scale_factors)
V <- diag(scale_factors, nrow = 3, ncol = 3)
rotate3D(yaw, pitch, roll) %*% V
} |
makeMAList <- function(mat, MAfac, useF=c("R","G"), isLog=TRUE, silent=FALSE, callFrom=NULL){
fxNa <- .composeCallName(callFrom, newNa="makeMAList")
chPa <- requireNamespace("limma", quietly=TRUE)
if(!chPa) {return(NULL); warning(fxNa,"Package 'limma' not found ! Please install from Bioconductor")
} else {
if(!all(useF %in% MAfac & length(useF) ==2 & length(MAfac) >1)) stop(" Argument 'useF' should describe 2 elements of 'MAfac'")
if(!isLog) {
if(any(mat <0) & !silent) message(fxNa,"Negative values will create NAs at log2-transformation !") }
out <- try(limma::MA.RG(if(isLog) list(R=2^mat[,which(MAfac==useF[1])], G=2^mat[,which(MAfac==useF[2])]) else {
list(R=mat[,which(MAfac==useF[1])], G=mat[,which(MAfac==useF[2])])}, bc.method="subtract", offset=0), silent=TRUE)
if("try-error" %in% class(out)) {warning("UNABLE to run limma::MA.RG() '!"); out <- NULL}
out } }
.allRatios <- function(dat,ty="log2",colNaSep="_") {
out <- matrix(nrow=nrow(dat), ncol=choose(ncol(dat),2))
pwCoor <- upperMaCoord(ncol(dat))
out <- apply(pwCoor, 1, function(x) dat[,x[1]]/dat[,x[2]])
colnames(out) <- apply(pwCoor,1,function(x) paste(colnames(dat)[x[1]],colnames(dat)[x[2]], sep=colNaSep))
if(identical(ty,"log2")) out <- log2(out)
if(identical(ty,"log10")) out <- log10(out)
if(identical(ty,"log")) out <- log(out)
out }
.allRatioMatr1to2 <- function(x, y, asLog2=TRUE, sumMeth="mean", callFrom=NULL){
fxNa <- .composeCallName(callFrom,newNa=".allRatioMatr1to2")
xDimNa <- dimnames(x)
yDimNa <- dimnames(y)
if(length(xDimNa) <1) x <- matrix(x, ncol=1, dimnames=list(rownames(x),"x1"))
if(length(yDimNa) <1) y <- matrix(y, ncol=1, dimnames=list(rownames(y),"y1"))
if(nrow(x) != nrow(y)) stop(fxNa," number of rows in 'x' and 'y' must be equal !")
out <- apply(x, 2, function(da,re) matrix(rep(da,ncol(re)), ncol=ncol(re))/re, re=y)
if(!is.list(out)) out <- list(out)
if(asLog2) out <- lapply(out,log2)
out <- if(identical(sumMeth,"mean")) lapply(out,rowMeans) else lapply(out,function(x) apply(x, 1, stats::median,na.rm=TRUE))
nLen <- sapply(out,length)
if(length(unique(nLen)) >1 | any(nLen <1)) message(fxNa," strange format of results, length of lists: ",
paste(nLen,collapse=" "))
out <- out[which(nLen >0)]
out <- if(length(out) >1) matrix(unlist(out), nrow=nrow(x), dimnames=xDimNa) else out[[1]]
out }
.getAmean <- function(dat,grp) {
if(length(levels(grp)) <2) stop(" problem: 'grp' as factor should have at least 2 levels")
if(length(grp) != ncol(dat)) stop(" problem: length of 'grp' should match numbe of columns in 'dat'")
if(!is.factor(grp)) grp <- as.factor(grp)
out <- matrix(nrow=nrow(dat), ncol=length(levels(grp)), dimnames=list(rownames(dat), levels(grp)))
for(i in 1:length(levels(grp))) out[,i] <- rowMeans(dat[,which(grp==levels(grp)[i])],na.rm=TRUE)
out }
.getAmean2 <- function(dat,comp) as.matrix(apply(comp,1,function(co,x) rowMeans(x[,co],na.rm=TRUE),dat))
.getMvalue2 <- function(dat,comp) as.matrix(apply(comp,1,function(co,x) diff(t(x[,co])),dat))
|
dhist <- function(x, a = 5 * iqr(x), nbins = grDevices::nclass.Sturges(x), rx = range(x, na.rm = TRUE),
eps = 0.15, xlab = "x", plot = TRUE, lab.spikes = TRUE) {
if (is.character(nbins)) {
nbins <- switch(casefold(nbins),
sturges = grDevices::nclass.Sturges(x),
fd = grDevices::nclass.FD(x),
scott = grDevices::nclass.scott(x),
stop("Nclass method not recognized"))
} else {
if (is.function(nbins)) {
nbins <- nbins(x)
}
}
x <- sort(x[!is.na(x)])
if (a == 0) {
a <- diff(range(x)) / 1e+08
}
if (a != 0 & a != Inf) {
n <- length(x)
h <- (rx[2] + a - rx[1]) / nbins
ybr <- rx[1] + h * (0:nbins)
yupper <- x + (a * seq_len(n)) / n
ylower <- yupper - a / n
cmtx <- cbind(cut(yupper, breaks = ybr),
cut(yupper, breaks = ybr, left.include = TRUE),
cut(ylower, breaks = ybr),
cut(ylower, breaks = ybr, left.include = TRUE))
cmtx[1, 3] <- cmtx[1, 4] <- 1
cmtx[n, 1] <- cmtx[n, 2] <- nbins
checksum <- (cmtx[, 1] + cmtx[, 2] + cmtx[, 3] + cmtx[, 4]) %% 4
straddlers <- (1:n)[checksum == 2]
if (length(straddlers) > 0) {
counts <- table(c(1:nbins, cmtx[-straddlers, 1]))
} else {
counts <- table(c(1:nbins, cmtx[, 1]))
}
counts <- counts - 1
if (length(straddlers) > 0) {
for (i in straddlers) {
binno <- cmtx[i, 1]
theta <- ((yupper[i] - ybr[binno]) * n) / a
counts[binno - 1] <- counts[binno - 1] + (1 - theta)
counts[binno] <- counts[binno] + theta
}
}
xbr <- ybr
xbr[-1] <- ybr[-1] - (a * cumsum(counts)) / n
spike <- eps * diff(rx)/nbins
flag.vec <- c(diff(xbr) < spike, FALSE)
if (sum(abs(diff(xbr)) <= spike) > 1) {
xbr.new <- xbr
counts.new <- counts
diff.xbr <- abs(diff(xbr))
amt.spike <- diff.xbr[length(diff.xbr)]
for (i in rev(2:length(diff.xbr))) {
if (diff.xbr[i - 1] <= spike & diff.xbr[i] <= spike & !is.na(diff.xbr[i])) {
amt.spike <- amt.spike + diff.xbr[i - 1]
counts.new[i - 1] <- counts.new[i - 1] + counts.new[i]
xbr.new[i] <- NA
counts.new[i] <- NA
flag.vec[i - 1] <- TRUE
} else {
amt.spike <- diff.xbr[i - 1]
}
}
flag.vec <- flag.vec[!is.na(xbr.new)]
flag.vec <- flag.vec[-length(flag.vec)]
counts <- counts.new[!is.na(counts.new)]
xbr <- xbr.new[!is.na(xbr.new)]
} else {
flag.vec <- flag.vec[-length(flag.vec)]
}
widths <- abs(diff(xbr))
heights <- counts/widths
}
bin.size <- length(x) / nbins
cut.pt <- unique(c(min(x) - abs(min(x)) / 1000,
stats::approx(seq(length(x)), x, seq_len(nbins - 1) * bin.size, rule = 2)$y, max(x)))
aa <- graphics::hist(x, breaks = cut.pt, plot = FALSE, probability = TRUE)
if (a == Inf) {
heights <- aa$counts
xbr <- aa$breaks
}
amt.height <- 3
q75 <- stats::quantile(heights, 0.75)
if (sum(flag.vec) != 0) {
amt <- max(heights[!flag.vec])
ylim.height <- amt * amt.height
ind.h <- flag.vec & heights > ylim.height
flag.vec[heights < ylim.height * (amt.height - 1) / amt.height] <- FALSE
heights[ind.h] <- ylim.height
}
amt.txt <- 0
end.y <- (-10000)
if (plot) {
graphics::barplot(heights, abs(diff(xbr)),
space = 0, density = -1,
xlab = xlab, plot = TRUE,
xaxt = "n", yaxt = "n")
at <- pretty(xbr)
graphics::axis(1, at = at - xbr[1], labels = as.character(at))
if (lab.spikes) {
if (sum(flag.vec) >= 1) {
usr <- graphics::par("usr")
for (i in seq(length(xbr) - 1)) {
if (!flag.vec[i]) {
amt.txt <- 0
if (xbr[i] - xbr[1] < end.y) {
amt.txt <- 1
}
} else {
amt.txt <- amt.txt + 1
end.y <- xbr[i] - xbr[1] + 3 * graphics::par("cxy")[1]
}
if (flag.vec[i]) {
txt <- paste0(" ", format(round(counts[i]/sum(counts) * 100)), "%")
graphics::par(xpd = TRUE)
graphics::text(xbr[i + 1] - xbr[1],
ylim.height - graphics::par("cxy")[2] * (amt.txt -1), txt, adj = 0)
}
}
} else print("no spikes or more than one spike")
}
return(invisible(list(heights = heights, xbr = xbr)))
} else {
return(list(heights = heights, xbr = xbr, counts = counts))
}
}
iqr <- function(x) {
return(diff(stats::quantile(x, c(0.25, 0.75), na.rm = TRUE)))
}
plot_data <- function(trait.data, base.plot = NULL, ymax) {
if (is.null(base.plot)) {
base.plot <- ggplot2::ggplot()
}
n.pts <- nrow(trait.data)
if (n.pts == 1) {
ymax <- ymax / 16
} else if (n.pts < 5) {
ymax <- ymax / 8
} else {
ymax <- ymax / 4
}
y.pts <- seq(0, ymax, length.out = 1 + n.pts)[-1]
if (!"ghs" %in% names(trait.data)) {
trait.data$ghs <- 1
}
plot.data <- data.frame(x = trait.data$Y,
y = y.pts,
se = trait.data$se,
control = !trait.data$trt == 1 & trait.data$ghs == 1)
new.plot <- base.plot +
ggplot2::geom_point(
data = plot.data,
ggplot2::aes(x = .data$x, y = .data$y, color = .data$control)) +
ggplot2::geom_segment(
data = plot.data,
ggplot2::aes(
x = .data$x - .data$se, y = .data$y,
xend = .data$x + .data$se, yend = .data$y,
color = .data$control)) +
ggplot2::scale_color_manual(values = c("black", "grey")) +
ggplot2::theme(legend.position = "none")
return(new.plot)
}
theme_border <- function(type = c("left", "right", "bottom", "top", "none"),
colour = "black", size = 1, linetype = 1) {
type <- match.arg(type, several.ok = TRUE)
structure(function(x = 0, y = 0, width = 1, height = 1, ...) {
xlist <- c()
ylist <- c()
idlist <- c()
if ("bottom" %in% type) {
xlist <- append(xlist, c(x, x + width))
ylist <- append(ylist, c(y, y))
idlist <- append(idlist, c(1, 1))
}
if ("top" %in% type) {
xlist <- append(xlist, c(x, x + width))
ylist <- append(ylist, c(y + height, y + height))
idlist <- append(idlist, c(2, 2))
}
if ("left" %in% type) {
xlist <- append(xlist, c(x, x))
ylist <- append(ylist, c(y, y + height))
idlist <- append(idlist, c(3, 3))
}
if ("right" %in% type) {
xlist <- append(xlist, c(x + width, x + width))
ylist <- append(ylist, c(y, y + height))
idlist <- append(idlist, c(4, 4))
}
grid::polylineGrob(x = xlist, y = ylist,
id = idlist, ...,
default.units = "npc",
gp = grid::gpar(lwd = size,
col = colour,
lty = linetype), )
}, class = "theme", type = "box", call = match.call())
} |
pictogram<-function(icon,n,grouplabels="",
hicons=20,vspace=0.5,labprop=0.2,labelcex=1) {
if(is.list(icon)) {
licon<-icon
} else {
licon<-list(icon)
for (i in 2:length(n)) {
licon[[i]]<-icon
}
}
library(reshape)
sumn<-sum(n)
group<-untable(df=matrix((1:length(n)),ncol=1),num=n)
vicons<-ceiling(n/hicons)
allv<-sum(vicons)
tail<-n%%hicons
devaspect<-dev.size(units="px")[1]/dev.size(units="px")[2]
xlength<-1
getdim<-function(z) {
aspect<-dim(z)[1]/dim(z)[2]
return(aspect)
}
all.ylengths<-unlist(lapply(licon,getdim))
ylength<-max(all.ylengths)
all.ylengths<-untable(df=matrix(all.ylengths,ncol=1),num=n)
ytop<-allv*ylength
if(devaspect*hicons<allv) warning("Icons may extend above the top of the graph")
iconrow<-as.vector(as.matrix(rbind(rep(hicons,length(vicons)),tail)))
reprow<-as.vector(as.matrix(rbind((vicons-1),rep(1,length(vicons)))))
perrow<-untable(df=matrix(iconrow,ncol=1),num=reprow)
spacing<-NULL
for (i in 1:(length(n))) {
spacing<-c(spacing,rep((i-1)*vspace*ylength,n[i]))
}
y0<-spacing+(ylength*untable(df=matrix((1:allv)-1,ncol=1),num=perrow))
y1<-y0+all.ylengths
x0<-NULL
for (i in 1:(length(perrow))) {
x0<-c(x0,(0:(perrow[i]-1)))
}
x1<-x0+xlength
leftplot<-floor(-(labprop*hicons))
plot(c(leftplot,hicons),c(0,(devaspect*hicons)),
type="n",bty="n",ylab="",xlab="",xaxt="n",yaxt="n")
lines(x=c(0,0),y=c(min(y0)-(ylength/2),max(y1)+(ylength/2)))
for (i in 1:sumn) {
rasterImage(image=licon[[group[i]]],xleft=x0[i],xright=x1[i],
ytop=y1[i],ybottom=y0[i])
}
ylabpos<-rep(NA,length(n))
for (i in 1:length(n)) {
ylabpos[i]<-(max(y1[group==i])+min(y0[group==i]))/2
}
text(x=leftplot/2,y=ylabpos,labels=grouplabels,cex=labelcex)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.