code
stringlengths 1
13.8M
|
---|
classBreaks <- function(x, n, type = c("equal", "quantile", "std", "geometric") ) {
if(type[1] == "equal") {
return( seq(min(x), max(x), length.out=(n+1)) )
} else if(type[1] == "quantile") {
return( c(stats::quantile(x=x, probs=seq(0,1,1/10))) )
} else if(type[1] == "std") {
svar <- scale(x)
return( c((pretty(x = svar, n = n) * attr(svar, "scaled:scale")) +
attr(svar, "scaled:center")) )
} else if(type[1] == "geometric") {
breaks <- c(min(x), max(x))
r <- exp((log(max(x)) - log(min(x)))/n)
i.min <- breaks[1]
for (i in 1:(n - 1)) {
breaks <- c(breaks, i.min * r)
i.min <- i.min * r
breaks <- sort(breaks)
}
return(breaks)
} else {
stop("Not a valid statistic")
}
} |
fourfoldplot <-
function(x, color = c("
std = c("margins", "ind.max", "all.max"), margin = c(1, 2),
space = 0.2, main = NULL, mfrow = NULL, mfcol = NULL)
{
if(!is.array(x))
stop("'x' must be an array")
if(length(dim(x)) == 2L) {
x <- if(is.null(dimnames(x)))
array(x, c(dim(x), 1L))
else
array(x, c(dim(x), 1L), c(dimnames(x), list(NULL)))
}
if(length(dim(x)) != 3L)
stop("'x' must be 2- or 3-dimensional")
if(any(dim(x)[1L:2L] != 2L))
stop("table for each stratum must be 2 by 2")
dnx <- dimnames(x)
if(is.null(dnx))
dnx <- vector("list", 3L)
for(i in which(sapply(dnx, is.null)))
dnx[[i]] <- LETTERS[seq_len(dim(x)[i])]
if(is.null(names(dnx)))
i <- 1L : 3L
else
i <- which(is.null(names(dnx)))
if(any(i))
names(dnx)[i] <- c("Row", "Col", "Strata")[i]
dimnames(x) <- dnx
k <- dim(x)[3L]
if(!((length(conf.level) == 1) && is.finite(conf.level) &&
(conf.level >= 0) && (conf.level < 1)))
stop("'conf.level' must be a single number between 0 and 1")
if(conf.level == 0)
conf.level <- FALSE
std <- match.arg(std)
findTableWithOAM <- function(or, tab) {
m <- rowSums(tab)[1L]
n <- rowSums(tab)[2L]
t <- colSums(tab)[1L]
if(or == 1)
x <- t * n / (m + n)
else if(or == Inf)
x <- max(0, t - m)
else {
A <- or - 1
B <- or * (m - t) + (n + t)
C <- - t * n
x <- (- B + sqrt(B ^ 2 - 4 * A * C)) / (2 * A)
}
matrix(c(t - x, x, m - t + x, n - x), nrow = 2)
}
drawPie <- function(r, from, to, n = 500, col = NA) {
p <- 2 * pi * seq.int(from, to, length.out = n) / 360
x <- c(cos(p), 0) * r
y <- c(sin(p), 0) * r
polygon(x, y, col = col)
invisible(NULL)
}
stdize <- function(tab, std, x) {
if(std == "margins") {
if(all(sort(margin) == c(1L, 2L))) {
u <- sqrt(odds(tab)$or)
u <- u / (1 + u)
y <- matrix(c(u, 1 - u, 1 - u, u), nrow = 2L)
}
else if(margin %in% c(1, 2))
y <- proportions(tab, margin)
else
stop("incorrect 'margin' specification")
}
else if(std == "ind.max")
y <- tab / max(tab)
else if(std == "all.max")
y <- tab / max(x)
y
}
odds <- function(x) {
if(length(dim(x)) == 2L) {
dim(x) <- c(dim(x), 1L)
k <- 1
}
else
k <- dim(x)[3L]
or <- double(k)
se <- double(k)
for(i in 1 : k) {
f <- x[ , , i]
storage.mode(f) <- "double"
if(any(f == 0))
f <- f + 0.5
or[i] <- (f[1L, 1L] * f[2L, 2L]) / (f[1L, 2L] * f[2L, 1L])
se[i] <- sqrt(sum(1 / f))
}
list(or = or, se = se)
}
gamma <- 1.25
debug <- FALSE
angle.f <- c( 90, 180, 0, 270)
angle.t <- c(180, 270, 90, 360)
opar <- par(mar = c(0, 0, if(is.null(main)) 0 else 2.5, 0))
on.exit(par(opar))
byrow <- FALSE
if(!is.null(mfrow)) {
nr <- mfrow[1L]
nc <- mfrow[2L]
}
else if(!is.null(mfcol)) {
nr <- mfcol[1L]
nc <- mfcol[2L]
byrow <- TRUE
}
else {
nr <- ceiling(sqrt(k))
nc <- ceiling(k / nr)
}
if(nr * nc < k)
stop("incorrect geometry specification")
if(byrow)
indexMatrix <- expand.grid(1 : nc, 1 : nr)[, c(2, 1)]
else
indexMatrix <- expand.grid(1 : nr, 1 : nc)
totalWidth <- nc * 2 * (1 + space) + (nc - 1L) * space
totalHeight <- if(k == 1)
2 * (1 + space)
else
nr * (2 + (2 + gamma) * space) + (nr - 1L) * space
xlim <- c(0, totalWidth)
ylim <- c(0, totalHeight)
dev.hold(); on.exit(dev.flush(), add = TRUE)
plot.new()
plot.window(xlim = xlim, ylim = ylim, asp = 1)
o <- odds(x)
scale <- space / (2 * strheight("Ag"))
v <- 0.95 - max(strwidth(as.character(c(x)), cex = scale)) / 2
for(i in 1 : k) {
tab <- x[ , , i]
fit <- stdize(tab, std, x)
xInd <- indexMatrix[i, 2L]
xOrig <- 2 * xInd - 1 + (3 * xInd - 2) * space
yInd <- indexMatrix[i, 1L]
yOrig <- if(k == 1)
(1 + space)
else
(totalHeight
- (2 * yInd - 1 + ((3 + gamma) * yInd - 2) * space))
plot.window(xlim - xOrig, ylim - yOrig, asp = 1)
if(debug) {
abline(h = -1 - space)
abline(h = 1 + space)
abline(h = 1 + (1 + gamma) * space)
abline(v = -1 - space)
abline(v = 1 + space)
}
u <- 1 + space / 2
adjCorr <- 0.2
text(0, u,
paste(names(dimnames(x))[1L],
dimnames(x)[[1L]][1L],
sep = ": "),
adj = c(0.5, 0.5 - adjCorr),
cex = scale)
text(-u, 0,
paste(names(dimnames(x))[2L],
dimnames(x)[[2L]][1L],
sep = ": "),
adj = c(0.5, 0.5 - adjCorr),
cex = scale,
srt = 90)
text(0, -u,
paste(names(dimnames(x))[1L],
dimnames(x)[[1L]][2L],
sep = ": "),
adj = c(0.5, 0.5 + adjCorr),
cex = scale)
text(u, 0,
paste(names(dimnames(x))[2L],
dimnames(x)[[2L]][2L],
sep = ": "),
adj = c(0.5, 0.5 + adjCorr),
cex = scale,
srt = 90)
if(k > 1) {
text(0, 1 + (1 + gamma / 2) * space,
paste(names(dimnames(x))[3L],
dimnames(x)[[3L]][i],
sep = ": "),
cex = gamma * scale)
}
d <- odds(tab)$or
drawPie(sqrt(fit[1,1]), 90, 180, col = color[1 + (d > 1)])
drawPie(sqrt(fit[2,1]), 180, 270, col = color[2 - (d > 1)])
drawPie(sqrt(fit[1,2]), 0, 90, col = color[2 - (d > 1)])
drawPie(sqrt(fit[2,2]), 270, 360, col = color[1 + (d > 1)])
u <- 1 - space / 2
text(c(-v, -v, v, v),
c( u, -u, u, -u),
as.character(c(tab)),
cex = scale)
if(is.numeric(conf.level)) {
or <- o$or[i]
se <- o$se[i]
theta <- or * exp(stats::qnorm((1 - conf.level) / 2) * se)
tau <- findTableWithOAM(theta, tab)
r <- sqrt(c(stdize(tau, std, x)))
for(j in 1 : 4)
drawPie(r[j], angle.f[j], angle.t[j])
theta <- or * exp(stats::qnorm((1 + conf.level) / 2) * se)
tau <- findTableWithOAM(theta, tab)
r <- sqrt(c(stdize(tau, std, x)))
for(j in 1 : 4)
drawPie(r[j], angle.f[j], angle.t[j])
}
polygon(c(-1, 1, 1, -1),
c(-1, -1, 1, 1))
lines(c(-1, 1), c(0, 0))
for(j in seq.int(from = -0.8, to = 0.8, by = 0.2))
lines(c(j, j), c(-0.02, 0.02))
for(j in seq.int(from = -0.9, to = 0.9, by = 0.2))
lines(c(j, j), c(-0.01, 0.01))
lines(c(0, 0), c(-1, 1))
for(j in seq.int(from = -0.8, to = 0.8, by = 0.2))
lines(c(-0.02, 0.02), c(j, j))
for(j in seq.int(from = -0.9, to = 0.9, by = 0.2))
lines(c(-0.01, 0.01), c(j, j))
}
if(!is.null(main))
mtext(main, cex = 1.5, adj = 0.5)
return(invisible())
} |
context("Extract data")
data(james)
test_that("getProblems returns correct ordered problem names", {
expect_equal(getProblems(james), c("coconut", "maize-accession", "maize-bulk", "pea-small"))
})
test_that("getProblems respects applied filter", {
expect_equal(getProblems(james, filter = "maize"), c("maize-accession", "maize-bulk"))
})
test_that("getProblems passes additional arguments to grep", {
expect_equal(getProblems(james, filter = "Coco"), character(0))
expect_equal(getProblems(james, filter = "Coco", ignore.case = TRUE), "coconut")
})
test_that("getSearches returns correct ordered search names", {
for(p in getProblems(james)){
expect_equal(getSearches(james, p), c("Parallel Tempering", "Random Descent"))
}
})
test_that("getSearches respects applied filter", {
for(p in getProblems(james)){
expect_equal(getSearches(james, p, filter = "Descent"), "Random Descent")
}
})
test_that("getSearches passes additional arguments to grep", {
for(p in getProblems(james)){
expect_equal(getSearches(james, p, filter = "descent"), character(0))
expect_equal(getSearches(james, p, filter = "descent", ignore.case = TRUE), "Random Descent")
}
})
test_that("getSearches allows to omit problem name in case of a single problem", {
expect_error(getSearches(james), "more than one problem")
james.coco <- reduceJAMES(james, problems = "coco")
expect_equal(getSearches(james.coco), c("Parallel Tempering", "Random Descent"))
})
test_that("getSearches complains if the given problem is not found", {
expect_error(getSearches(james, "foo"), "does not contain results for problem")
})
test_that("getSearchRuns allows to omit problem name in case of a single problem", {
expect_error(getSearchRuns(james, search = "Random Descent"), "more than one problem")
james.coco <- reduceJAMES(james, problems = "coco")
getSearchRuns(james.coco, search = "Random Descent")
})
test_that("getSearchRuns allows to omit search name in case of a single search for the given problem", {
expect_error(getSearchRuns(james, problem = "coconut"), "more than one search for problem")
james.rd <- reduceJAMES(james, searches = "Descent")
getSearchRuns(james.rd, problem = "coconut")
james.rd.coco <- reduceJAMES(james.rd, problems = "coco")
getSearchRuns(james.rd.coco)
})
test_that("getSearchRuns complain when given an unknown problem", {
expect_error(getSearchRuns(james, problem = "foo"), "does not contain results for problem")
})
test_that("getSearchRuns complain when given an unknown search", {
expect_error(getSearchRuns(james, problem = "coconut", search = "bar"), "does not contain results for search")
})
test_that("getSearchRuns returns a list of the expected format", {
runs <- getSearchRuns(james, problem = "coconut", search = "Random Descent")
expect_equal(length(runs), 10)
for(run in runs){
expect_false(is.null(run$times))
expect_true(is.vector(run$times))
expect_true(is.numeric(run$times))
expect_true(all(run$times[run$times != -1] > 0))
expect_true(is.sorted(run$times))
expect_false(is.null(run$values))
expect_true(is.vector(run$values))
expect_true(is.numeric(run$values))
expect_true(is.sorted(run$values) || is.sorted(rev(run$values)))
expect_equal(length(run$times), length(run$values))
expect_false(is.null(run$best.solution))
}
})
test_that("getSearchRuns returns the correct values", {
for(p in getProblems(james)){
for(s in getSearches(james, p)){
file <- sprintf("files/search-runs-%s-%s.rds", gsub(" ", "-", p), gsub(" ", "-", s))
expect_equal_to_reference(getSearchRuns(james, p, s), file)
}
}
})
test_that("number of search runs is correctly reported", {
expect_equal(getNumSearchRuns(james, "coconut", "Random Descent"),
length(getSearchRuns(james, "coconut", "Random Descent")))
for(p in getProblems(james)){
for(s in getSearches(james, p)){
expect_equal(getNumSearchRuns(james, p, s), 10)
}
}
})
test_that("getBestSolutionValues allows to omit problem name in case of a single problem", {
expect_error(getBestSolutionValues(james, search = "Random Descent"), "more than one problem")
james.coco <- reduceJAMES(james, problems = "coco")
getBestSolutionValues(james.coco, search = "Random Descent")
})
test_that("getBestSolutionValues allows to omit search name in case of a single search for the given problem", {
expect_error(getBestSolutionValues(james, problem = "coconut"), "more than one search for problem")
james.rd <- reduceJAMES(james, searches = "Descent")
getBestSolutionValues(james.rd, problem = "coconut")
james.rd.coco <- reduceJAMES(james.rd, problems = "coco")
getBestSolutionValues(james.rd.coco)
})
test_that("getBestSolutionValues returns a numeric vector", {
for(p in getProblems(james)){
for(s in getSearches(james, p)){
best.values <- getBestSolutionValues(james, p, s)
expect_true(is.vector(best.values))
expect_true(is.numeric(best.values))
}
}
})
test_that("number of best solution values corresponds to number of runs", {
for(p in getProblems(james)){
for(s in getSearches(james, p)){
expect_equal(length(getBestSolutionValues(james, p, s)), getNumSearchRuns(james, p, s))
}
}
})
test_that("getBestSolutionValues returns the correct values", {
for(p in getProblems(james)){
for(s in getSearches(james, p)){
file <- sprintf("files/best-solution-values-%s-%s.rds", gsub(" ", "-", p), gsub(" ", "-", s))
expect_equal_to_reference(getBestSolutionValues(james, p, s), file)
}
}
})
test_that("getBestSolutions allows to omit problem name in case of a single problem", {
expect_error(getBestSolutions(james, search = "Random Descent"), "more than one problem")
james.coco <- reduceJAMES(james, problems = "coco")
getBestSolutions(james.coco, search = "Random Descent")
})
test_that("getBestSolutions allows to omit search name in case of a single search for the given problem", {
expect_error(getBestSolutions(james, problem = "coconut"), "more than one search for problem")
james.rd <- reduceJAMES(james, searches = "Descent")
getBestSolutions(james.rd, problem = "coconut")
james.rd.coco <- reduceJAMES(james.rd, problems = "coco")
getBestSolutions(james.rd.coco)
})
test_that("number of best solutions corresponds to number of runs", {
for(p in getProblems(james)){
for(s in getSearches(james, p)){
expect_equal(length(getBestSolutions(james, p, s)), getNumSearchRuns(james, p, s))
}
}
})
test_that("getBestSolutions returns the correct solutions", {
for(p in getProblems(james)){
for(s in getSearches(james, p)){
file <- sprintf("files/best-solutions-%s-%s.rds", gsub(" ", "-", p), gsub(" ", "-", s))
expect_equal_to_reference(getBestSolutions(james, p, s), file)
}
}
})
test_that("getConvergenceTimes allows to omit problem name in case of a single problem", {
expect_error(getConvergenceTimes(james, search = "Random Descent"), "more than one problem")
james.coco <- reduceJAMES(james, problems = "coco")
getConvergenceTimes(james.coco, search = "Random Descent")
})
test_that("getConvergenceTimes allows to omit search name in case of a single search for the given problem", {
expect_error(getConvergenceTimes(james, problem = "coconut"), "more than one search for problem")
james.rd <- reduceJAMES(james, searches = "Descent")
getConvergenceTimes(james.rd, problem = "coconut")
james.rd.coco <- reduceJAMES(james.rd, problems = "coco")
getConvergenceTimes(james.rd.coco)
})
test_that("number of convergence times corresponds to number of runs", {
for(p in getProblems(james)){
for(s in getSearches(james, p)){
expect_equal(length(getConvergenceTimes(james, p, s)), getNumSearchRuns(james, p, s))
}
}
})
test_that("getConvergenceTimes complains if convergence ratio is not within [0,1]", {
expect_error(getConvergenceTimes(james, "coconut", "Random Descent", r = -1), "value in [0,1]", fixed = TRUE)
expect_error(getConvergenceTimes(james, "coconut", "Random Descent", r = 1.001), "value in [0,1]", fixed = TRUE)
expect_error(getConvergenceTimes(james, "coconut", "Random Descent", r = "abc"), "value in [0,1]", fixed = TRUE)
})
test_that("getConvergenceTimes returns a numeric vector", {
for(p in getProblems(james)){
for(s in getSearches(james, p)){
best.values <- getConvergenceTimes(james, p, s)
expect_true(is.vector(best.values))
expect_true(is.numeric(best.values))
}
}
})
test_that("convergence times are greater than or equal to -1", {
for(p in getProblems(james)){
for(s in getSearches(james, p)){
conv.times <- getConvergenceTimes(james, p, s)
expect_false(any(conv.times < -1))
}
}
})
test_that("getConvergenceTimes returns the correct values", {
for(p in getProblems(james)){
for(s in getSearches(james, p)){
file <- sprintf("files/convergence-times-%s-%s.rds", gsub(" ", "-", p), gsub(" ", "-", s))
expect_equal_to_reference(getConvergenceTimes(james, p, s), file)
}
}
}) |
TPBoot.rboot <- function(object, UT, nboot, ...) {
lst <- vector(mode="list", length=2)
a3d <- array( data=0, dim=c(nboot, length(UT), 4) )
est <- TransPROB(object, UT, nboot=1, ...)
a3d[1,,] <- est[[1]]
lst[[2]] <- est[[2]]
for (i in 2:nboot) {
y <- vector(mode="list", length=1)
y[[1]] <- object[[1]][csample.int( n=nrow(object[[1]]) ),]
class(y) <- class(object)[2]
a3d[i,,] <- TransPROB(y, UT, nboot=1, ...)[[1]]
}
lst[[1]] <- a3d
return(lst)
}
TPBoot.cboot <- function(object, UT, nboot, ...) {
return( TransPROB(object, UT, nboot=nboot, ...) )
}
TransBoot.TP <- function(object, s, t, state.names, n.boot, conf.level, method.boot, ...) {
UT <- uniqueTIME(object, s, t)
n.boot <- trunc(n.boot)
lst <- TPBoot(object, UT, n.boot, ...)
class(lst) <- class(object)[2]
TPmsm <- BtoTPmsm(lst, UT, s, t, state.names, n.boot, conf.level, method.boot)
Clean(object)
return(TPmsm)
}
TPCBoot.rboot <- function(object, UT, UX, nboot, ...) {
lst <- vector(mode="list", length=2)
a4d <- array( data=0, dim=c(nboot, length(UT), length(UX), 4) )
est <- TransPROB(object, UT, UX, nboot=1, ...)
a4d[1,,,] <- est[[1]]
lst[[2]] <- est[[2]]
for (i in 2:nboot) {
y <- vector(mode="list", length=1)
y[[1]] <- object[[1]][csample.int( n=nrow(object[[1]]) ),]
class(y) <- class(object)[2]
a4d[i,,,] <- TransPROB(y, UT, UX, nboot=1, ...)[[1]]
}
lst[[1]] <- a4d
return(lst)
}
TPCBoot.cboot <- function(object, UT, UX, nboot, ...) {
return( TransPROB(object, UT, UX, nboot=nboot, ...) )
}
TransBoot.TPC <- function(object, s, t, state.names, n.boot, conf.level, method.boot, xi, ...) {
UT <- uniqueTIME(object, s, t)
UX <- uniqueCOV(object, xi)
n.boot <- trunc(n.boot)
lst <- TPCBoot(object, UT, UX, n.boot, ...)
class(lst) <- class(object)[2]
TPCmsm <- BtoTPCmsm(lst, UT, UX, s, t, xi, state.names, n.boot, conf.level, method.boot)
Clean(object)
return(TPCmsm)
} |
library(Rsymphony)
obj <- c(2.8, 5.4, 1.4, 4.2, 3.0, 6.3, 0, 0)
mat <- matrix(c(1,0,0,1,0,0,0,1,0,1,0,0,0,0,1,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,0,1,0,1,0,0,0,0,-3,0,1,0,0,0,0,-3,1), nrow = 6)
dir <- c("==", "==", "==", "<=", "<=", "<=")
rhs <- c(1, 1, 1, 0, 0, 2)
mat
max <- FALSE
types <- "B"
fac.loc <- Rsymphony_solve_LP(obj, mat, dir, rhs, types = types, max = max, write_lp = TRUE)
fac.loc
tells us that we should open both supply centers and
supply center 1 will supply shops 1 and 3 and supply center 2 will supply shop 2, for a total distance of 7.2. |
library(PUlasso)
library(Matrix)
data("simulPU")
dt=data.frame(x1=simulPU$X[,1],x2=simulPU$X[,2],y=simulPU$y,z=simulPU$z)
par(mar=c(2,2,2,2))
plot(dt$x1,dt$x2,col=adjustcolor(ifelse(simulPU$z,"red","navy"),alpha.f=0.5),pch=20,main="labelled/unlabelled",xlab="x1",ylab="x2")
legend("bottomright",bg="transparent",legend=c("labelled","unlabelled"),col=c("red","navy"),bty="n"
,text.col = c("red", "navy"),pt.bg = c("red","navy"), pch = c(20,20))
plot(dt$x1,dt$x2,col=adjustcolor(ifelse(simulPU$y,"red","blue"),alpha.f=0.5),pch=20,main="(latent) positive/negative",xlab="x1",ylab="x2")
legend("bottomright",bg="transparent",legend=c("positive","negative"),col=c("red","blue"),bty="n"
,text.col = c("red", "blue"),pt.bg = c("red","blue"), pch = c(20,20))
(fit=grpPUlasso(X=simulPU$X,z=simulPU$z,py1=simulPU$truePY1))
coef(fit, lambda=fit$lambda[30])
xnew = matrix(rnorm(10),2,5)
predict(fit,newdata = xnew,lambda = fit$lambda[30])
(cv.fit = cv.grpPUlasso(X=simulPU$X,z=simulPU$z,py1=simulPU$truePY1))
coef(cv.fit,lambda=cv.fit$lambda.1se)
phat<-predict(cv.fit,newdata = simulPU$X,lambda = cv.fit$lambda.1se,type = "response")
yhat<-1*(phat>0.5)
dt=cbind(dt,yhat)
par(mar=c(2,2,2,2))
plot(dt$x1,dt$x2,col=adjustcolor(ifelse(dt$yhat,"red","blue"),alpha.f=0.5),pch=20,main="(estimated) positive/negative",xlab="x1",ylab="x2")
legend("bottomright",bg="transparent",legend=c("hat_negative","hat_positive"),col=c("red","blue"),bty="n",text.col = c("red", "blue"),pt.bg = c("red","blue"), pch = c(20,20))
grpvec = c(1,2,2,3,3)
fit.grp = grpPUlasso(X=simulPU$X,z=simulPU$z,py1=simulPU$truePY1,group = grpvec)
coef(fit.grp,fit.grp$lambda[12:15])
sparseX <- simulPU$X
sparseX[sample(1:length(simulPU$X),size = length(simulPU$X)*0.95)]<-0
sparseX<-Matrix(sparseX)
class(sparseX)
(spfit<-grpPUlasso(sparseX,simulPU$z,simulPU$truePY1))
newx = matrix(rnorm(10),2,5)
predict(spfit,newdata = newx,lambda = spfit$lambda[10])
(fit.SVRG = grpPUlasso(X=simulPU$X,z=simulPU$z,py1=simulPU$truePY1,method="SVRG",eps = 1e-6,lambda =fit$lambda[2])) |
fh_hetop <- function(ngk, fixedcuts, p, m, gridL, gridU, Xm=NULL, Xs=NULL, seed=12345, modelfileonly = FALSE, modloc=NULL, ...){
set.seed(seed)
tmpdir <- tempdir()
if(is.null(modloc)){
modloc <- paste0(tmpdir,"/model.txt")
} else {
if(!is.character(modloc) || (length(modloc)!=1)){
stop("invalid modloc")
}
}
if(is.null(ngk)){
stop("ngk not specified")
}
if(is.null(fixedcuts)){
stop("fixedcuts not specified")
}
if(is.null(p)){
stop("p not specified")
}
if(is.null(m)){
stop("m not specified")
}
if(is.null(gridL)){
stop("gridL not specified")
}
if(is.null(gridU)){
stop("gridU not specified")
}
if(!is.numeric(ngk)){
stop("ngk must be a GxK numeric matrix of category counts")
}
if(!is.matrix(ngk)){
stop("ngk must be a GxK numeric matrix of category counts")
}
if(any(is.na(ngk))){
stop("ngk cannot contain missing values")
}
if(any(ngk < 0)){
stop("ngk must contain only non-negative values")
}
if(any(apply(ngk, 1, sum) <= 0)){
stop("ngk contains at least one row with insufficient data")
}
G <- nrow(ngk)
K <- ncol(ngk)
if(K <= 2){
stop("Function requires K >= 3 categories")
}
if(G <= 10){
warning("FH-HETOP model may not function properly with so few groups")
}
ng <- apply(ngk, 1, sum)
pg <- ng/sum(ng)
if(!is.numeric(fixedcuts)){
stop("fixedcuts must be a numeric vector of length 2")
}
if(length(fixedcuts) != 2){
stop("fixedcuts must be a numeric vector of length 2")
}
if(any(is.na(fixedcuts))){
stop("fixedcuts cannot contain missing values")
}
if(fixedcuts[1] >= fixedcuts[2]){
stop("fixedcuts[1] must be strictly less than fixedcuts[2]")
}
cuts12 <- sort(fixedcuts)
if(K == 3){
cuts <- cuts12
} else {
cuts <- c(cuts12, rep(NA, K-3))
}
if(!is.numeric(p)){
stop("p must be a numeric vector of length 2")
}
if(length(p) != 2){
stop("p must be a numeric vector of length 2")
}
if(any(is.na(p))){
stop("p cannot contain missing values")
}
if(any(abs(p - floor(p)) > 1e-8)){
stop("p must contain integer numbers of degrees of freedom")
}
if(any(p < 3)){
stop("each element of p must be at least three since Q is based on cubic splines")
}
if(!is.numeric(m)){
stop("m must be a numeric vector of length 2")
}
if(length(m) != 2){
stop("m must be a numeric vector of length 2")
}
if(any(is.na(m))){
stop("m cannot contain missing values")
}
if(any(abs(m - floor(m)) > 1e-8)){
stop("m must contain integer numbers of grid points")
}
if(any(m < p)){
stop("The model is intended to have more gridpoints than degrees of freedom; either increase 'm' or decrease 'p'")
}
if(!is.numeric(gridL)){
stop("gridL must be a numeric vector of length 2")
}
if(length(gridL) != 2){
stop("gridL must be a numeric vector of length 2")
}
if(any(is.na(gridL))){
stop("gridL cannot contain missing values")
}
if(!is.numeric(gridU)){
stop("gridU must be a numeric vector of length 2")
}
if(length(gridU) != 2){
stop("gridU must be a numeric vector of length 2")
}
if(any(is.na(gridU))){
stop("gridU cannot contain missing values")
}
if(any(gridL >= gridU)){
stop("elements of gridU must be strictly greater than elements of gridL")
}
meanX <- !is.null(Xm)
sdX <- !is.null(Xs)
if(as.integer(meanX + sdX) == 1){
stop("current implementation requires covariates be specified for neither or both of (mu, sigma)")
}
if(meanX){
if(!is.numeric(Xm)){
stop("Xm must be a numeric matrix of covariates for the group means")
}
if(!is.matrix(Xm)){
stop("Xm must be a numeric matrix of covariates for the group means")
}
if(any(is.na(Xm))){
stop("Xm cannot contain missing values")
}
if(any(abs(apply(Xm, 2, sum)) > 1e-8)){
stop("each column of Xm must sum to zero")
}
dimXm <- ncol(Xm)
}
if(sdX){
if(!is.numeric(Xs)){
stop("Xs must be a numeric matrix of covariates for the group means")
}
if(!is.matrix(Xs)){
stop("Xs must be a numeric matrix of covariates for the group means")
}
if(any(is.na(Xs))){
stop("Xs cannot contain missing values")
}
if(any(abs(apply(Xs, 2, sum)) > 1e-8)){
stop("each column of Xs must sum to zero")
}
dimXs <- ncol(Xs)
}
valid.ja <- c("inits","parameters.to.save","n.chains","n.iter","n.burnin","n.thin",
"DIC","working.directory","refresh","progress.bar","digits","RNGname",
"jags.module")
passed.ja <- list(...)
.n <- names(passed.ja)
if( (length(passed.ja) > 0) && any(!(.n %in% valid.ja)) ){
stop("The ... argument list included elements not eligible to be passed to jags()")
}
if("inits" %in% .n){
jags.inits <- passed.ja$inits
} else {
jags.inits <- NULL
}
if("parameters.to.save" %in% .n){
jags.parameters.to.save <- passed.ja$parameters.to.save
} else{
jags.parameters.to.save <- c("mu","sigma","cuts","alpha0m","alpham","alpha0s","alphas","gamma")
if(meanX && sdX){
jags.parameters.to.save <- c(jags.parameters.to.save,"beta_m","beta_s")
}
}
if("nchains" %in% .n){
jags.n.chains <- passed.ja$n.chains
if(!is.null(jags.inits) && (length(jags.inits) != jags.n.chains)){
stop("inits and n.chains arguments are inconsistent")
}
} else {
jags.n.chains <- 2
}
if("n.iter" %in% .n){
jags.n.iter <- passed.ja$n.iter
} else {
jags.n.iter <- 5000
}
if("n.burnin" %in% .n){
jags.n.burnin <- passed.ja$n.burnin
if(jags.n.burnin > jags.n.iter){
stop("n.iter and n.burnin are inconsistent")
}
} else {
jags.n.burnin <- jags.n.iter / 2
}
if("n.thin" %in% .n){
jags.n.thin <- passed.ja$n.thin
} else {
jags.n.thin <- 1
}
if("DIC" %in% .n){
jags.DIC <- passed.ja$DIC
} else {
jags.DIC <- FALSE
}
if("working.directory" %in% .n){
jags.working.directory <- passed.ja$working.directory
} else {
jags.working.directory <- NULL
}
if("refresh" %in% .n){
jags.refresh <- passed.ja$refresh
} else {
jags.refresh <- jags.n.iter / 20
}
if("progress.bar" %in% .n){
jags.progress.bar <- passed.ja$progress.bar
} else {
jags.progress.bar <- "text"
}
if("digits" %in% .n){
jags.digits <- passed.ja$digits
} else {
jags.digits <- 5
}
if("RNGname" %in% .n){
jags.RNGname <- passed.ja$RNGname
} else {
jags.RNGname <- c("Wichmann-Hill", "Marsaglia-Multicarry", "Super-Duper", "Mersenne-Twister")
}
if("jags.module" %in% .n){
jags.jags.module <- passed.ja$jags.module
} else {
jags.jags.module = c("glm","dic")
}
gridm <- seq(from = gridL[1], to = gridU[1], length=m[1])
Qm <- bs(gridm, df = p[1], degree=3, intercept=FALSE)
Qm <- matrix(c(Qm), ncol=p[1], byrow=F)
grids <- seq(from = gridL[2], to = gridU[2], length=m[2])
Qs <- bs(grids, df = p[2], degree=3, intercept=FALSE)
Qs <- matrix(c(Qs), ncol=p[2], byrow=F)
jags.data <- c("G","K","ngk","ng","cuts","m","p","Qm","Qs","gridm","grids")
if(meanX && sdX){
jags.data <- c(jags.data, "Xm","dimXm","Xs","dimXs")
}
if(is.null(jags.inits)){
jags.inits <- vector(jags.n.chains, mode="list")
for(i in 1:jags.n.chains){
.tmp <- list(locm = rep(as.integer(floor(0.5*m[1])), G),
locs = as.integer(rep(floor(0.95 * m[2]), G)),
alpha0m = rnorm(1),
alphamdev = rnorm(p[1]),
alpha0s = rnorm(1),
alphasdev = rnorm(p[2]),
gamma = 0.0)
if(meanX){
.tmp$beta_m <- rnorm(dimXm, sd=0.1)
}
if(sdX){
.tmp$beta_s <- rnorm(dimXs, sd=0.1)
}
if(K >= 4){
.tmp$cuts0 <- sort(seq(from = cuts12[2] + 1, to = cuts12[2] + 3, length=K-3))
}
jags.inits[[i]] <- .tmp
}
}
cat("model
{
for(g in 1:G){
ngk[g,1:K] ~ dmulti(pgk[g,1:K], ng[g])
pgk[g,1] <- phi( (cuts[1] - mu[g]) / sigma[g])
for(k in 2:(K-1)){
pgk[g,k] <- phi( (cuts[k] - mu[g]) / sigma[g]) - sum(pgk[g,1:(k-1)])
}
pgk[g,K] <- 1.0 - phi( (cuts[K-1] - mu[g]) / sigma[g])
mu[g] <- epsilon[g,1]
sigma[g] <- exp(epsilon[g,2])
locm[g] ~ dcat(pFm[1:m[1]])
locs[g] ~ dcat(pFs[1:m[2]])\n", file=modloc)
if( (!meanX && !sdX) ){
cat("
epsilon[g,1] <- (gamma * grids[locs[g]]) + gridm[locm[g]]
epsilon[g,2] <- grids[locs[g]]\n", file=modloc, append=TRUE)
}
if( (meanX && sdX) ){
cat("
epsilon[g,1] <- inprod(Xm[g,1:dimXm], beta_m[1:dimXm]) + (gamma * grids[locs[g]]) + gridm[locm[g]]
epsilon[g,2] <- inprod(Xs[g,1:dimXs], beta_s[1:dimXs]) + grids[locs[g]]\n", file=modloc, append=TRUE)
}
cat(" }\n", file=modloc, append=TRUE)
cat("
alpha0m ~ dnorm(0.0, 0.01)
for(i in 1:p[1]){
alphamdev[i] ~ dnorm(0.0, 0.05)
alpham[i] <- alpha0m + alphamdev[i]
}
for(i in 1:m[1]){
pFm[i] <- exp(Qm[i,1:p[1]] %*% alpham[1:p[1]])
}
alpha0s ~ dnorm(0.0, 0.01)
for(i in 1:p[2]){
alphasdev[i] ~ dnorm(0.0, 0.05)
alphas[i] <- alpha0s + alphasdev[i]
}
for(i in 1:m[2]){
pFs[i] <- exp(Qs[i,1:p[2]] %*% alphas[1:p[2]])
}
gamma ~ dnorm(0.0, 0.1)
", file=modloc, append=TRUE)
if(K >= 4){
cat("
for(k in 1:(K-3)){
cuts0[k] ~ dnorm(0.0, 0.01) I(cuts[2], )
}
tmp[1:(K-3)] <- sort(cuts0)
for(k in 1:(K-3)){
cuts[k+2] <- tmp[k]
}
", file=modloc, append=TRUE)
}
if(meanX){
cat("
for(i in 1:dimXm){
beta_m[i] ~ dnorm(0.0, 0.1)
}
", file=modloc, append=TRUE)
}
if(sdX){
cat("
for(i in 1:dimXs){
beta_s[i] ~ dnorm(0.0, 0.1)
}
", file=modloc, append=TRUE)
}
cat("}\n", file=modloc, append=TRUE)
if(modelfileonly){
return(modloc)
}
r <- jags(
model.file = modloc,
data = jags.data,
inits = jags.inits,
parameters.to.save = jags.parameters.to.save,
n.chains = jags.n.chains,
n.iter = jags.n.iter,
n.burnin = jags.n.burnin,
n.thin = jags.n.thin,
DIC = jags.DIC,
working.directory = jags.working.directory,
refresh = jags.refresh,
progress.bar = jags.progress.bar,
digits = jags.digits,
RNGname = jags.RNGname,
jags.module = jags.jags.module)
fh_hetop_extras <- list()
Finfo <- list()
Finfo$gridL <- gridL
Finfo$gridU <- gridU
Finfo$efron_p <- p
Finfo$efron_m <- m
Finfo$gridm <- gridm
Finfo$Qm <- Qm
Finfo$grids <- grids
Finfo$Qs <- Qs
fh_hetop_extras$Finfo <- Finfo; rm(Finfo)
Dinfo <- list()
Dinfo$G <- G
Dinfo$K <- K
Dinfo$ngk <- ngk
Dinfo$ng <- ng
Dinfo$fixedcuts <- fixedcuts
Dinfo$Xm <- Xm
Dinfo$Xs <- Xs
fh_hetop_extras$Dinfo <- Dinfo; rm(Dinfo)
fh_hetop_extras$waicinfo <- waic_hetop(ngk, r$BUGSoutput$sims.matrix)
ind_m <- grep("mu", colnames(r$BUGSoutput$sims.matrix))
ind_s <- grep("sigma", colnames(r$BUGSoutput$sims.matrix))
ind_c <- grep("cuts", colnames(r$BUGSoutput$sims.matrix))
ind_betam <- grep("beta_m", colnames(r$BUGSoutput$sims.matrix))
ind_betas <- grep("beta_s", colnames(r$BUGSoutput$sims.matrix))
stopifnot( (length(ind_m) == G) && (length(ind_s) == G) && length(ind_c == (K-1)) )
tmp <- lapply(1:nrow(r$BUGSoutput$sims.matrix), function(i){
mug <- r$BUGSoutput$sims.matrix[i,ind_m]
sigmag <- r$BUGSoutput$sims.matrix[i,ind_s]
cuts <- r$BUGSoutput$sims.matrix[i,ind_c]
a <- sum(pg * mug)
b <- sqrt(sum(pg * ( (mug - a)^2 + sigmag^2)))
.retval <- list(mug = (mug - a)/b,
sigmag = sigmag / b,
cutpoints = (cuts - a)/b)
if(meanX && sdX){
.retval$beta_m <- r$BUGSoutput$sims.matrix[i,ind_betam] / b
.retval$beta_s <- r$BUGSoutput$sims.matrix[i,ind_betas]
}
return(.retval)
})
fh_hetop_extras$est_star_samps <- list(mug = do.call("rbind", lapply(tmp, function(x){ x$mug })),
sigmag = do.call("rbind", lapply(tmp, function(x){ x$sigmag })),
cutpoints = do.call("rbind", lapply(tmp, function(x){ x$cutpoints })))
if(meanX && sdX){
fh_hetop_extras$est_star_samps$beta_m <- do.call("rbind", lapply(tmp, function(x){ x$beta_m }))
fh_hetop_extras$est_star_samps$beta_s <- do.call("rbind", lapply(tmp, function(x){ x$beta_s }))
}
rm(tmp); gc()
stopifnot(max(abs(sapply(1:nrow(r$BUGSoutput$sims.matrix), function(i){
sum(pg * (fh_hetop_extras$est_star_samps$mug[i,]^2 + fh_hetop_extras$est_star_samps$sigmag[i,]^2))
}) - 1)) < 1e-12)
fh_hetop_extras$est_star_mug <- triple_goal(fh_hetop_extras$est_star_samps$mug)
fh_hetop_extras$est_star_sigmag <- triple_goal(fh_hetop_extras$est_star_samps$sigmag)
r$fh_hetop_extras <- fh_hetop_extras
rm(fh_hetop_extras); gc()
return(r)
} |
bde<-function (dataPoints,dataPointsCache=NULL,estimator,b=length(sample)^{-2/5},
lower.limit=0, upper.limit=1,options=NULL){
sample <- dataPoints
x <- dataPointsCache
if (min(sample)<min(0,lower.limit)) lower.limit<-0.99*min(sample)
if (max(sample)>max(1,upper.limit)) upper.limit<-1.01*max(sample)
if (is.null(x)) x<-seq(lower.limit,upper.limit,(upper.limit - lower.limit)/100)
density<-switch(estimator,
"betakernel"= beta_aux(sample,x,b,options,lower.limit,upper.limit),
"vitale" = vitale_aux(sample,x,b,options,lower.limit,upper.limit),
"boundarykernel" = boundary_aux(sample,x,b,options,lower.limit,upper.limit),
"kakizawa" = kakizawa_aux(sample,x,b,options,lower.limit,upper.limit),
{
stop("The estimator is a mandatory parameter that has to be either 'betakernel', 'vitale', 'boundarykernel' or 'kakizawa'. Note that the parameter is case sensitive. For more information please type ?bde")
})
density
}
default<-list()
default$beta<-list()
default$beta$mod=F
default$beta$normalization='none'
default$beta$mbc='none'
default$beta$c=0.5
default$vitale<-list()
default$vitale$biasreduction=F
default$vitale$M=1
default$boundary$mu<-1
default$boundary$kernel<-"muller94"
default$boundary$correct<-F
beta_aux<-function(sample,x,b,options,lower.limit,upper.limit){
if (mode(sample)=="list") sample<-unlist(sample)
sample<-as.numeric(sample)
mod=default$beta$mod
if (!is.null(options$modified)){mod=options$modified}
if (!is.logical(mod)) stop("The 'modified' parameter used has to be a logical value. For more information please type ?bde")
normalization=default$beta$normalization
if (!is.null(options$normalization)) {normalization=options$normalization}
mbc=default$beta$mbc
if (!is.null(options$mbc)) mbc=options$mbc
c=default$beta$c
if (!is.null(options$c)) c=options$c
if (c<0 | c>1) stop("The c parameter used in the TS multiplicative bias correction technique has to be a number between 0 and 1. For more information please type ?bde")
switch(normalization,
"none" = {
switch(mbc,
"none"={
chen99Kernel(dataPoints=sample,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
b=b,modified=mod)
},
"jnl" = {
hirukawaJLNKernel(dataPoints=sample,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
b=b,modified=mod)
},
"ts" = {
hirukawaTSKernel(dataPoints=sample,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
b=b,modified=mod,c=c)
},
{
stop("Unrecognized mbc option. Valid options are 'none', 'jnl' and 'ts'. Note that the parameter is case sensitive. For more information please type ?bde")
})
},
"densitywise" = {
switch(mbc,
"none"={
macroBetaChen99Kernel(dataPoints=sample,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
b=b,modified=mod)
},
"jnl" = {
macroBetaHirukawaJLNKernel(dataPoints=sample,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
b=b,modified=mod)
},
"ts" = {
macroBetaHirukawaTSKernel(dataPoints=sample,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
b=b,modified=mod,c=c)
},
{
stop("Unrecognized mbc option. Valid options are 'none', 'jnl' and 'ts'.Note that the parameter is case sensitive. For more information please type ?bde")
})
},
"kernelwise" = {
microBetaChen99Kernel(dataPoints=sample,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
b=b,modified=mod)
},
{
stop("Unrecognized normalization option. Valid options are 'none', 'densitywise' and 'kernelwise'. Note that the parameter is case sensitive. For more information please type ?bde")
})
}
vitale_aux<-function(sample,x,b,options,lower.limit,upper.limit){
biasreduced=default$vitale$biasreduction
if (!is.null(options$biasreduced)) biasreduced=options$biasreduced
if (!is.logical(biasreduced)) stop("The 'biasreduction' parameter used has to be a logical value. For more information please type ?bde")
if (!biasreduced){
if (1/b<1) {
warning(paste("Vitales m parameter has to be an integer value, but 1/",b," is not integer. Setting it at 1. For more information please type ?bde"))
b=1
}
vitale(dataPoints=sample,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,m=round(1/b))
}else{
M=1/(2*b)
if (!is.null(options$M)) M=options$M
if (M<1) {
warning(paste("Vitale's M parameter has to be an integer value. Setting it at 1. For more information please type ?bde"))
M=1
}
brVitale(dataPoints=sample,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,m=round(1/b),M=M)
}
}
boundary_aux<-function(sample,x,b,options,lower.limit,upper.limit){
mu=default$boundary$mu
if (!is.null(options$mu)) mu=options$mu
if (!is.numeric(mu) & !(mu %in% 0:3)){
stop(paste("'mu' parameter has to be an integer between 0 and 3. For more information please type ?bde"))
}
kernel=default$boundary$kernel
if (!is.null(options$kernel)) kernel=options$kernel
correct=F
if (!is.null(options$nonegative)) correct=options$nonegative
if (!is.logical(correct)) stop(paste("'nonegative' has to be a logic value. For more information please type ?bde"))
switch(kernel,
"muller94" = {
if (!correct){
muller94BoundaryKernel(dataPoints=sample,b=b,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
mu=mu)
}else{
jonesCorrectionMuller94BoundaryKernel(dataPoints=sample,b=b,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
mu=mu)
}
},
"muller91" = {
if (!correct){
muller91BoundaryKernel(dataPoints=sample,b=b,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
mu=mu)
}else{
jonesCorrectionMuller91BoundaryKernel(dataPoints=sample,b=b,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
mu=mu)
}
},
"normalized" = {
normalizedBoundaryKernel(dataPoints=sample,b=b,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
mu=mu)
},
"none" = {
noBoundaryKernel(dataPoints=sample,b=b,dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
mu=mu)
},
{
stop(paste("'kernel' option unrecognized, valid options are 'muller94', 'muller91', 'normalized', 'none'. For more information please type ?bde"))
})
}
kakizawa_aux<-function(sample,x,b,options,lower.limit,upper.limit){
if (!is.null(options$estimator)) {
estimator=options$estimator
}else{
estimator=muller94BoundaryKernel(dataPoints=sample,b=b,mu=1,lower.limit = lower.limit,upper.limit = upper.limit)
}
if (!inherits(estimator,"BoundedDensity")) stop ("Unrecognized 'estimator' parameter. It should be an object of class 'BoundedDensity'")
gamma=0.5
if (!is.null(options$gamma)) gamma=options$gamma
if (gamma<=0 | gamma>1) stop("The 'gamma' parameter has to in the interval (0,1]")
method="b3"
if(!is.null(options$method)) method=options$method
switch(method,
"b1" = {
kakizawaB1(dataPoints=sample,m=round(1/b),dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
gamma=gamma,estimator=estimator)
},
"b2" = {
kakizawaB2(dataPoints=sample,m=round(1/b),dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
estimator=estimator)
},
"b3" = {
kakizawaB3(dataPoints=sample,m=round(1/b),dataPointsCache=x,lower.limit = lower.limit,upper.limit = upper.limit,
estimator=estimator)
},
{
stop("Unrecognized 'method' option. It should be either 'b1', 'b2' or 'b3'")
})
}
launchApp<-function (...){
shiny::runApp(system.file("App",package="bde"),...)
} |
PlotEquiMap <- function(var, lon, lat, varu = NULL, varv = NULL,
toptitle = NULL, sizetit = NULL, units = NULL,
brks = NULL, cols = NULL, bar_limits = NULL,
triangle_ends = NULL, col_inf = NULL, col_sup = NULL,
colNA = NULL, color_fun = clim.palette(),
square = TRUE, filled.continents = NULL,
coast_color = NULL, coast_width = 1, lake_color = NULL,
contours = NULL, brks2 = NULL, contour_lwd = 0.5,
contour_color = 'black', contour_lty = 1,
contour_draw_label = TRUE, contour_label_scale = 1,
dots = NULL, dot_symbol = 4, dot_size = 1,
arr_subsamp = floor(length(lon) / 30), arr_scale = 1,
arr_ref_len = 15, arr_units = "m/s",
arr_scale_shaft = 1, arr_scale_shaft_angle = 1,
axelab = TRUE, labW = FALSE,
lab_dist_x = NULL, lab_dist_y = NULL,
intylat = 20, intxlon = 20,
axes_tick_scale = 1, axes_label_scale = 1,
drawleg = TRUE, subsampleg = NULL,
bar_extra_labels = NULL, draw_bar_ticks = TRUE,
draw_separators = FALSE, triangle_ends_scale = 1,
bar_label_digits = 4, bar_label_scale = 1,
units_scale = 1, bar_tick_scale = 1,
bar_extra_margin = rep(0, 4),
boxlim = NULL, boxcol = 'purple2', boxlwd = 5,
margin_scale = rep(1, 4), title_scale = 1,
numbfig = NULL, fileout = NULL,
width = 8, height = 5, size_units = 'in',
res = 100, ...) {
excludedArgs <- c("cex", "cex.axis", "cex.lab", "cex.main", "col", "din", "fig", "fin", "lab", "las", "lty", "lwd", "mai", "mar", "mgp", "new", "oma", "ps", "tck")
userArgs <- .FilterUserGraphicArgs(excludedArgs, ...)
if (!is.null(fileout)) {
deviceInfo <- .SelectDevice(fileout = fileout, width = width, height = height, units = size_units, res = res)
saveToFile <- deviceInfo$fun
fileout <- deviceInfo$files
}
if (!is.null(dots)) {
if (!is.array(dots) || !(length(dim(dots)) %in% c(2, 3))) {
stop("Parameter 'dots' must be a logical array with two or three dimensions.")
}
if (length(dim(dots)) == 2) {
dim(dots) <- c(1, dim(dots))
}
}
if (!is.null(contours)) {
if (!is.array(contours) || !(length(dim(contours)) == 2)) {
stop("Parameter 'contours' must be a numerical array with two dimensions.")
}
}
if (!is.null(varu) && !is.null(varv)) {
if (!is.array(varu) || !(length(dim(varu)) == 2)) {
stop("Parameter 'varu' must be a numerical array with two dimensions.")
}
if (!is.array(varv) || !(length(dim(varv)) == 2)) {
stop("Parameter 'varv' must be a numerical array with two dimensions.")
}
} else if (!is.null(varu) || !is.null(varv)) {
stop("Only one of the components 'varu' or 'varv' has been provided. Both must be provided.")
}
if (!is.numeric(lon) || !is.numeric(lat)) {
stop("Parameters 'lon' and 'lat' must be numeric vectors.")
}
if (!is.array(var)) {
stop("Parameter 'var' must be a numeric array.")
}
if (length(dim(var)) > 2) {
var <- drop(var)
dim(var) <- head(c(dim(var), 1, 1), 2)
}
if (length(dim(var)) > 2) {
stop("Parameter 'var' must be a numeric array with two dimensions. See PlotMultiMap() for multi-pannel maps or AnimateMap() for animated maps.")
} else if (length(dim(var)) < 2) {
stop("Parameter 'var' must be a numeric array with two dimensions.")
}
dims <- dim(var)
transpose <- FALSE
if (!is.null(names(dims))) {
if (any(names(dims) %in% .KnownLonNames()) &&
any(names(dims) %in% .KnownLatNames())) {
if (which(names(dims) %in% .KnownLonNames()) != 1) {
transpose <- TRUE
}
}
}
if (dims[1] != length(lon) || dims[2] != length(lat)) {
if (dims[1] == length(lat) && dims[2] == length(lon)) {
transpose <- TRUE
}
}
if (transpose) {
var <- t(var)
if (!is.null(varu)) varu <- t(varu)
if (!is.null(varv)) varv <- t(varv)
if (!is.null(contours)) contours <- t(contours)
if (!is.null(dots)) dots <- aperm(dots, c(1, 3, 2))
dims <- dim(var)
}
if (length(lon) != dims[1]) {
stop("Parameter 'lon' must have as many elements as the number of cells along longitudes in the input array 'var'.")
}
if (length(lat) != dims[2]) {
stop("Parameter 'lat' must have as many elements as the number of cells along longitudes in the input array 'var'.")
}
if (!is.null(varu) && !is.null(varv)) {
if (dim(varu)[1] != dims[1] || dim(varu)[2] != dims[2]) {
stop("Parameter 'varu' must have same number of longitudes and latitudes as 'var'.")
}
if (dim(varv)[1] != dims[1] || dim(varv)[2] != dims[2]) {
stop("Parameter 'varv' must have same number of longitudes and latitudes as 'var'.")
}
}
if (is.null(toptitle) || is.na(toptitle)) {
toptitle <- ''
}
if (!is.character(toptitle)) {
stop("Parameter 'toptitle' must be a character string.")
}
if (!is.null(sizetit)) {
.warning("Parameter 'sizetit' is obsolete. Use 'title_scale' instead.")
if (!is.numeric(sizetit) || length(sizetit) != 1) {
stop("Parameter 'sizetit' must be a single numeric value.")
}
title_scale <- sizetit
}
var_limits <- c(min(var, na.rm = TRUE), max(var, na.rm = TRUE))
colorbar <- ColorBar(brks, cols, FALSE, subsampleg, bar_limits, var_limits,
triangle_ends, col_inf, col_sup, color_fun, FALSE,
extra_labels = bar_extra_labels, draw_ticks = draw_bar_ticks,
draw_separators = draw_separators,
triangle_ends_scale = triangle_ends_scale,
label_scale = bar_label_scale, title = units,
title_scale = units_scale, tick_scale = bar_tick_scale,
extra_margin = bar_extra_margin, label_digits = bar_label_digits)
brks <- colorbar$brks
cols <- colorbar$cols
col_inf <- colorbar$col_inf
col_sup <- colorbar$col_sup
bar_limits <- c(head(brks, 1), tail(brks, 1))
if (is.null(colNA)) {
if ('na_color' %in% names(attributes(cols))) {
colNA <- attr(cols, 'na_color')
if (!.IsColor(colNA)) {
stop("The 'na_color' provided as attribute of the colour vector must be a valid colour identifier.")
}
} else {
colNA <- 'pink'
}
} else if (!.IsColor(colNA)) {
stop("Parameter 'colNA' must be a valid colour identifier.")
}
if (!is.logical(square)) {
stop("Parameter 'square' must be logical.")
}
if (is.null(filled.continents)) {
if (!square) {
filled.continents <- FALSE
} else {
filled.continents <- TRUE
}
}
if (!.IsColor(filled.continents) && !is.logical(filled.continents)) {
stop("Parameter 'filled.continents' must be logical or a colour identifier.")
} else if (!is.logical(filled.continents)) {
continent_color <- filled.continents
filled.continents <- TRUE
} else if (filled.continents) {
continent_color <- gray(0.5)
}
if (is.null(coast_color)) {
if (filled.continents) {
coast_color <- continent_color
} else {
coast_color <- 'black'
}
}
if (!.IsColor(coast_color)) {
stop("Parameter 'coast_color' must be a valid colour identifier.")
}
if (!is.numeric(coast_width)) {
stop("Parameter 'coast_width' must be numeric.")
}
if (is.null(lake_color)) {
if (filled.continents) {
lake_color <- 'white'
}
} else {
if (!.IsColor(lake_color)) {
stop("Parameter 'lake_color' must be a valid colour identifier.")
}
}
if (!is.null(contours)) {
if (dim(contours)[1] != dims[1] || dim(contours)[2] != dims[2]) {
stop("Parameter 'contours' must have the same number of longitudes and latitudes as 'var'.")
}
}
if (is.null(brks2)) {
if (is.null(contours)) {
if (!square) {
brks2 <- brks
contours <- var
}
} else {
ll <- signif(min(contours, na.rm = TRUE), 2)
ul <- signif(max(contours, na.rm = TRUE), 2)
brks2 <- signif(seq(ll, ul, length.out = length(brks)), 2)
}
}
if (!is.numeric(contour_lwd)) {
stop("Parameter 'contour_lwd' must be numeric.")
}
if (!.IsColor(contour_color)) {
stop("Parameter 'contour_color' must be a valid colour identifier.")
}
if (!is.numeric(contour_lty) && !is.character(contour_lty)) {
stop("Parameter 'contour_lty' must be either a number or a character string.")
}
if (!is.logical(contour_draw_label)) {
stop("Parameter 'contour_draw_label' must be logical.")
}
if (!is.numeric(contour_label_scale)) {
stop("Parameter 'contour_label_scale' must be numeric.")
}
if (!is.null(dots)) {
if (dim(dots)[2] != dims[1] || dim(dots)[3] != dims[2]) {
stop("Parameter 'dots' must have the same number of longitudes and latitudes as 'var'.")
}
if (!is.numeric(dot_symbol) && !is.character(dot_symbol)) {
stop("Parameter 'dot_symbol' must be a numeric or character string vector.")
}
if (length(dot_symbol) == 1) {
dot_symbol <- rep(dot_symbol, dim(dots)[1])
} else if (length(dot_symbol) < dim(dots)[1]) {
stop("Parameter 'dot_symbol' does not contain enough symbols.")
}
if (!is.numeric(dot_size)) {
stop("Parameter 'dot_size' must be numeric.")
}
if (length(dot_size) == 1) {
dot_size <- rep(dot_size, dim(dots)[1])
} else if (length(dot_size) < dim(dots)[1]) {
stop("Parameter 'dot_size' does not contain enough sizes.")
}
}
if (!is.numeric(arr_subsamp)) {
stop("Parameter 'arr_subsamp' must be numeric.")
}
if (!is.numeric(arr_scale)) {
stop("Parameter 'arr_scale' must be numeric.")
}
if (!is.numeric(arr_ref_len)) {
stop("Parameter 'arr_ref_len' must be numeric.")
}
if (!is.character(arr_units)) {
stop("Parameter 'arr_units' must be character.")
}
if (!is.numeric(arr_scale_shaft)) {
stop("Parameter 'arr_scale_shaft' must be numeric.")
}
if (!is.numeric(arr_scale_shaft_angle)) {
stop("Parameter 'arr_scale_shaft_angle' must be numeric.")
}
if (!is.logical(axelab)) {
stop("Parameter 'axelab' must be logical.")
}
if (!is.logical(labW)) {
stop("Parameter 'labW' must be logical.")
}
if (!is.null(lab_dist_x)) {
if (!is.numeric(lab_dist_x)) {
stop("Parameter 'lab_dist_x' must be numeric.")
}
}
if (!is.null(lab_dist_y)) {
if (!is.numeric(lab_dist_y)) {
stop("Parameter 'lab_dist_y' must be numeric.")
}
}
if (!is.numeric(intylat)) {
stop("Parameter 'intylat' must be numeric.")
} else {
intylat <- round(intylat)
}
if (!is.numeric(intxlon)) {
stop("Parameter 'intxlon' must be numeric.")
} else {
intxlon <- round(intxlon)
}
if (!is.logical(drawleg)) {
stop("Parameter 'drawleg' must be logical.")
}
if (!is.null(boxlim)) {
if (!is.list(boxlim)) {
boxlim <- list(boxlim)
}
for (i in 1:length(boxlim)) {
if (!is.numeric(boxlim[[i]]) || length(boxlim[[i]]) != 4) {
stop("Parameter 'boxlim' must be a a numeric vector or a list of numeric vectors of length 4 (with W, S, E, N box limits).")
}
}
if (!is.character(boxcol)) {
stop("Parameter 'boxcol' must be a character string or a vector of character strings.")
} else {
if (length(boxlim) != length(boxcol)) {
if (length(boxcol) == 1) {
boxcol <- rep(boxcol, length(boxlim))
} else {
stop("Parameter 'boxcol' must have a colour for each box in 'boxlim' or a single colour for all boxes.")
}
}
}
if (!is.numeric(boxlwd)) {
stop("Parameter 'boxlwd' must be numeric.")
} else {
if (length(boxlim) != length(boxlwd)) {
if (length(boxlwd) == 1) {
boxlwd <- rep(boxlwd, length(boxlim))
} else {
stop("Parameter 'boxlwd' must have a line width for each box in 'boxlim' or a single line width for all boxes.")
}
}
}
}
if (!is.numeric(margin_scale) || length(margin_scale) != 4) {
stop("Parameter 'margin_scale' must be a numeric vector of length 4.")
}
if (!is.numeric(title_scale)) {
stop("Parameter 'title_scale' must be numeric.")
}
if (!is.numeric(axes_tick_scale)) {
stop("Parameter 'axes_tick_scale' must be numeric.")
}
if (!is.numeric(axes_label_scale)) {
stop("Parameter 'axes_label_scale' must be numeric.")
}
if (!is.null(numbfig)) {
if (!is.numeric(numbfig)) {
stop("Parameter 'numbfig' must be numeric.")
} else {
numbfig <- round(numbfig)
scale <- 1 / numbfig ** 0.3
axes_tick_scale <- axes_tick_scale * scale
axes_label_scale <- axes_label_scale * scale
title_scale <- title_scale * scale
margin_scale <- margin_scale * scale
arr_scale <- arr_scale * scale
dot_size <- dot_size * scale
contour_label_scale <- contour_label_scale * scale
contour_lwd <- contour_lwd * scale
}
}
utils::data(coastmap, package = 'GEOmap', envir = environment())
latb <- sort(lat, index.return = TRUE)
dlon <- lon[2:dims[1]] - lon[1:(dims[1] - 1)]
wher <- which(dlon > (mean(dlon) + 1))
if (length(wher) > 0) {
lon[(wher + 1):dims[1]] <- lon[(wher + 1):dims[1]] - 360
}
lonb <- sort(lon, index.return = TRUE)
latmin <- floor(min(lat) / 10) * 10
latmax <- ceiling(max(lat) / 10) * 10
lonmin <- floor(min(lon) / 10) * 10
lonmax <- ceiling(max(lon) / 10) * 10
if (min(lon) < 0) {
continents <- 'world'
} else {
continents <- 'world2'
}
if (!is.null(fileout)) {
saveToFile(fileout)
} else if (names(dev.cur()) == 'null device') {
dev.new(units = size_units, res = res, width = width, height = height)
}
if (drawleg) {
margin_scale[1] <- margin_scale[1] - 1
}
margins <- rep(0.4, 4) * margin_scale
cex_title <- 2 * title_scale
cex_axes_labels <- 1.3 * axes_label_scale
cex_axes_ticks <- -0.5 * axes_tick_scale
spaceticklab <- 0
if (axelab) {
ypos <- seq(latmin, latmax, intylat)
xpos <- seq(lonmin, lonmax, intxlon)
letters <- array('', length(ypos))
letters[ypos < 0] <- 'S'
letters[ypos > 0] <- 'N'
ylabs <- paste(as.character(abs(ypos)), letters, sep = '')
letters <- array('', length(xpos))
if (labW) {
xpos2 <- xpos
xpos2[xpos2 > 180] <- 360 - xpos2[xpos2 > 180]
}
letters[xpos < 0] <- 'W'
letters[xpos > 0] <- 'E'
if (labW) {
letters[xpos == 0] <- ' '
letters[xpos == 180] <- ' '
letters[xpos > 180] <- 'W'
xlabs <- paste(as.character(abs(xpos2)), letters, sep = '')
} else {
xlabs <- paste(as.character(abs(xpos)), letters, sep = '')
}
spaceticklab <- max(-cex_axes_ticks, 0)
margins[1] <- margins[1] + 1.2 * cex_axes_labels + spaceticklab
margins[2] <- margins[2] + 1.2 * cex_axes_labels + spaceticklab
}
bar_extra_margin[2] <- bar_extra_margin[2] + margins[2]
bar_extra_margin[4] <- bar_extra_margin[4] + margins[4]
if (toptitle != '') {
margins[3] <- margins[3] + cex_title + 1
}
if (!is.null(varu)) {
margins[1] <- margins[1] + 2.2 * units_scale
}
if (drawleg) {
layout(matrix(1:2, ncol = 1, nrow = 2), heights = c(5, 1))
}
plot.new()
par(userArgs)
par(mar = margins, cex.main = cex_title, cex.axis = cex_axes_labels,
mgp = c(0, spaceticklab, 0), las = 0)
if (is.null(userArgs$usr)) {
xlim_cal <- c(lonb$x[1] - (lonb$x[2] - lonb$x[1]) / 2,
lonb$x[length(lonb$x)] + (lonb$x[2] - lonb$x[1]) / 2)
ylim_cal <- c(latb$x[1] - (latb$x[2] - latb$x[1]) / 2,
latb$x[length(latb$x)] + (latb$x[2] - latb$x[1]) / 2)
plot.window(xlim = xlim_cal, ylim = ylim_cal, xaxs = 'i', yaxs = 'i')
} else {
plot.window(xlim = par("usr")[1:2], ylim = par("usr")[3:4], xaxs = 'i', yaxs = 'i')
}
if (axelab) {
lab_distance_y <- ifelse(is.null(lab_dist_y), spaceticklab + 0.2, lab_dist_y)
lab_distance_x <- ifelse(is.null(lab_dist_x), spaceticklab + cex_axes_labels / 2 - 0.3, lab_dist_x)
axis(2, at = ypos, labels = ylabs, cex.axis = cex_axes_labels, tcl = cex_axes_ticks,
mgp = c(0, lab_distance_y, 0))
axis(1, at = xpos, labels = xlabs, cex.axis = cex_axes_labels, tcl = cex_axes_ticks,
mgp = c(0, lab_distance_x, 0))
}
title(toptitle, cex.main = cex_title)
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], col = colNA)
col_inf_image <- ifelse(is.null(col_inf), colNA, col_inf)
col_sup_image <- ifelse(is.null(col_sup), colNA, col_sup)
if (square) {
image(lonb$x, latb$x, var[lonb$ix, latb$ix], col = c(col_inf_image, cols, col_sup_image),
breaks = c(-.Machine$double.xmax, brks, .Machine$double.xmax),
axes = FALSE, xlab = "", ylab = "", add = TRUE)
} else {
.filled.contour(lonb$x, latb$x, var[lonb$ix, latb$ix],
levels = c(.Machine$double.xmin, brks, .Machine$double.xmax),
col = c(col_inf_image, cols, col_sup_image))
}
if (!is.null(contours)) {
contour(lonb$x, latb$x, contours[lonb$ix, latb$ix], levels = brks2,
method = "edge", add = TRUE,
labcex = contour_label_scale * par("cex"),
lwd = contour_lwd, lty = contour_lty,
col = contour_color, drawlabels = contour_draw_label)
}
if (!is.null(dots)) {
data_avail <- !is.na(var)
for (counter in 1:(dim(dots)[1])) {
points <- which(dots[counter, , ] & data_avail, arr.ind = TRUE)
points(lon[points[, 1]], lat[points[, 2]],
pch = dot_symbol[counter],
cex = dot_size[counter] * 3 / sqrt(sqrt(length(var))),
lwd = dot_size[counter] * 3 / sqrt(sqrt(length(var))))
}
}
if (continents == 'world') {
xlim_conti <- c(-179.99, 179.99)
} else {
xlim_conti <- c(0.01, 359.99)
}
coast <- map(continents, interior = FALSE, wrap = TRUE,
xlim = xlim_conti, ylim = c(-89.99, 89.99),
fill = filled.continents, add = TRUE, plot = FALSE)
if (filled.continents) {
old_lwd <- par('lwd')
par(lwd = coast_width)
if (min(lon) >= 0) {
ylat <- latmin:latmax
xlon <- lonmin:lonmax
proj <- GEOmap::setPROJ(1, LON0 = mean(xlon),
LAT0 = mean(ylat), LATS = ylat, LONS = xlon)
lakes <- which(coastmap$STROKES$col == "blue")
coastmap$STROKES$col[which(coastmap$STROKES$col != "blue")] <- continent_color
coastmap$STROKES$col[lakes] <- lake_color
par(new = TRUE)
GEOmap::plotGEOmap(coastmap, PROJ = proj, border = coast_color,
add = TRUE, lwd = coast_width)
} else {
polygon(coast, col = continent_color, border = coast_color, lwd = coast_width)
}
par(lwd = old_lwd)
} else {
lines(coast, col = coast_color, lwd = coast_width)
}
box()
if (!is.null(boxlim)) {
counter <- 1
for (box in boxlim) {
if (box[1] > box[3]) {
box[1] <- box[1] - 360
}
if (length(box) != 4) {
stop(paste("The", counter, "st box defined in the parameter 'boxlim' is ill defined."))
} else if (box[2] < latmin || box[4] > latmax ||
box[1] < lonmin || box[3] > lonmax) {
stop(paste("The limits of the", counter, "st box defined in the parameter 'boxlim' are invalid."))
} else if (box[1] < 0 && box[3] > 0) {
segments(box[1], box[2], 0, box[2], col = boxcol[counter], lwd = boxlwd[counter])
segments(0, box[2], box[3], box[2], col = boxcol[counter], lwd = boxlwd[counter])
segments(box[1], box[4], 0, box[4], col = boxcol[counter], lwd = boxlwd[counter])
segments(0, box[4], box[3], box[4], col = boxcol[counter], lwd = boxlwd[counter])
segments(box[1], box[2], box[1], box[4], col = boxcol[counter],
lwd = boxlwd[counter])
segments(box[3], box[2], box[3],box[4], col = boxcol[counter],
lwd = boxlwd[counter])
} else {
rect(box[1], box[2], box[3], box[4], border = boxcol[counter], col = NULL,
lwd = boxlwd[counter], lty = 'solid')
}
counter <- counter + 1
}
}
if (!is.null(varu) && !is.null(varv)) {
lontab <- InsertDim(lonb$x, 2, length( latb$x))
lattab <- InsertDim(latb$x, 1, length( lonb$x))
varplotu <- varu[lonb$ix, latb$ix]
varplotv <- varv[lonb$ix, latb$ix]
sublon <- seq(1,length(lon), arr_subsamp)
sublat <- seq(1,length(lat), arr_subsamp)
uaux <- lontab[sublon, sublat] + varplotu[sublon, sublat] * 0.5 * arr_scale
vaux <- lattab[sublon, sublat] + varplotv[sublon, sublat] * 0.5 * arr_scale
lenshaft <- 0.18 * arr_scale * arr_scale_shaft
angleshaft <- 12 * arr_scale_shaft_angle
arrows(lontab[sublon, sublat], lattab[sublon, sublat],
uaux, vaux,
angle = angleshaft,
length = lenshaft)
posarlon <- lonb$x[1] + (lonmax - lonmin) * 0.1
posarlat <- latmin - ((latmax - latmin) + 1) / par('pin')[2] *
(spaceticklab + 0.2 + cex_axes_labels + 0.6 * units_scale) * par('csi')
arrows(posarlon, posarlat,
posarlon + 0.5 * arr_scale * arr_ref_len, posarlat,
length = lenshaft, angle = angleshaft,
xpd = TRUE)
xpdsave <- par('xpd')
par(xpd = NA)
mtext(paste(as.character(arr_ref_len), arr_units, sep = ""),
line = spaceticklab + 0.2 + cex_axes_labels + 1.2 * units_scale, side = 1,
at = posarlon + (0.5 * arr_scale * arr_ref_len) / 2,
cex = units_scale)
par(xpd = xpdsave)
}
if (drawleg) {
ColorBar(brks, cols, FALSE, subsampleg, bar_limits, var_limits,
triangle_ends, col_inf = col_inf, col_sup = col_sup,
extra_labels = bar_extra_labels, draw_ticks = draw_bar_ticks,
draw_separators = draw_separators, title = units,
title_scale = units_scale, triangle_ends_scale = triangle_ends_scale,
label_scale = bar_label_scale, tick_scale = bar_tick_scale,
extra_margin = bar_extra_margin, label_digits = bar_label_digits)
}
if (!is.null(fileout)) dev.off()
invisible(list(brks = brks, cols = cols, col_inf = col_inf, col_sup = col_sup))
} |
MUS.combine <- function(object.list) {
if (!is.list(object.list) || length(object.list)<1) {
stop("object.list must be a list with one or more MUS.evaluation.result objects.")
}
s <- 1
x <- object.list[[s]]
if (length(object.list)>1) {
x$High.value.threshold <- "-"
x$Strata <- length(object.list)
x$qty.rejected <- ifelse(x$acceptable, 0, 1)
x$qty.accepted <- ifelse(x$acceptable, 1, 0)
for (s in 2:length(object.list)) {
y <- object.list[[s]]
x$data <- rbind(x$data, y$data)
x$sample <- rbind(x$sample, y$sample)
if ("filled.sample" %in% names(x)) {
x$filled.sample <- rbind(x$filled.sample, y$filled.sample)
}
if ("high.values" %in% names(x) && class(y$high.values)=="data.frame") {
if (class(x$high.values)=="data.frame") {
x$high.values <- rbind(x$high.values, y$high.values)
} else {
x$high.values <- y$high.values
}
}
if ("filled.high.values" %in% names(x) && class(y$filled.high.values)=="data.frame") {
if (class(x$filled.high.values)=="data.frame") {
x$filled.high.values <- rbind(x$filled.high.values, y$filled.high.values)
} else {
x$filled.high.values <- y$filled.high.values
}
}
if ("sample.population" %in% names(x)) {
x$sample.population <- rbind(x$sample.population, y$sample.population)
}
if ("Results.Total" %in% names(x)) {
for (j in 1:2) {
x$Results.Total$Number.of.Errors[j] <-
x$Results.Total$Number.of.Errors[j] +
y$Results.Total$Number.of.Errors[j]
x$Results.Total$Net.upper.error.limit[j] <-
x$Results.Total$Net.upper.error.limit[j] +
y$Results.Total$Net.upper.error.limit[j]
x$Results.Total$Gross.upper.error.limit[j] <-
x$Results.Total$Gross.upper.error.limit[j] +
y$Results.Total$Gross.upper.error.limit[j]
x$Results.Sample$Number.of.Errors[j] <-
x$Results.Sample$Number.of.Errors[j] +
y$Results.Sample$Number.of.Errors[j]
x$Results.Sample$Net.upper.error.limit[j] <-
x$Results.Sample$Net.upper.error.limit[j] +
y$Results.Sample$Net.upper.error.limit[j]
x$Results.Sample$Gross.upper.error.limit[j] <-
x$Results.Sample$Gross.upper.error.limit[j] +
y$Results.Sample$Gross.upper.error.limit[j]
x$Results.High.values$Number.of.Errors[j] <-
x$Results.High.values$Number.of.Errors[j] +
y$Results.High.values$Number.of.Errors[j]
x$Results.High.values$Gross.Value.of.Errors[j] <-
x$Results.High.values$Gross.Value.of.Errors[j] +
y$Results.High.values$Gross.Value.of.Errors[j]
x$Results.Sample$Precision.Gap.widening[j] <-
x$Results.Sample$Precision.Gap.widening[j] +
y$Results.Sample$Precision.Gap.widening[j]
x$Results.Sample$Total.Precision[j] <-
x$Results.Sample$Total.Precision[j] +
y$Results.Sample$Total.Precision[j]
x$Results.Total$Net.most.likely.error[j] <-
x$Results.Total$Net.most.likely.error[j] +
y$Results.Total$Net.most.likely.error[j]
}
x$Results.Total$Total.number.of.items.examined <-
x$Results.Total$Total.number.of.items.examined +
y$Results.Total$Total.number.of.items.examined
x$Results.Sample$Sample.Size <-
x$Results.Sample$Sample.Size +
y$Results.Sample$Sample.Size
x$Results.Sample$Basic.Precision <-
x$Results.Sample$Basic.Precision +
y$Results.Sample$Basic.Precision
x$Results.High.values$Number.of.high.value.items <-
x$Results.High.values$Number.of.high.value.items +
y$Results.High.values$Number.of.high.value.items
x$Results.High.values$Net.Value.of.Errors <-
x$Results.High.values$Net.Value.of.Errors +
y$Results.High.values$Net.Value.of.Errors
x$UEL.low.error.rate <- x$UEL.low.error.rate + y$UEL.low.error.rate
x$UEL.high.error.rate <- x$UEL.high.error.rate + y$UEL.high.error.rate
if ("acceptable.low.error.rate" %in% names(x)) {
x$acceptable.low.error.rate <-
ifelse(y$acceptable.low.error.rate, x$acceptable.low.error.rate, y$acceptable.low.error.rate)
}
if ("acceptable.high.error.rate" %in% names(x)) {
x$acceptable.high.error.rate <-
ifelse(y$acceptable.high.error.rate, x$acceptable.high.error.rate, y$acceptable.high.error.rate)
}
if ("acceptable" %in% names(x)) {
x$acceptable <- ifelse(y$acceptable, x$acceptable, y$acceptable)
x$qty.rejected <- x$qty.rejected + ifelse(y$acceptable, 0, 1)
x$qty.accepted <- x$qty.accepted + ifelse(y$acceptable, 1, 0)
}
}
x$book.value <- x$book.value + y$book.value
x$tolerable.error <- x$tolerable.error + y$tolerable.error
x$expected.error <- x$expected.error + y$expected.error
x$n <- x$n + y$n
x$n.min <- x$n.min + y$n.min
}
x$combined <- TRUE
}
x
} |
qz.dtrsen <- function(T, Q, select, job = c("B", "V", "E", "N"),
want.Q = TRUE, LWORK = NULL, LIWORK = NULL){
if(!(is.double(T) && is.double(Q))){
stop("T and Q should be in double")
}
if(!(is.matrix(T) && is.matrix(Q))){
stop("T and Q should be in matrix.")
}
if(any((dim(T) != dim(Q)))){
stop("Dimensions of T and Q should be equal.")
}
if(dim(T)[1] != dim(T)[2]){
stop("Squared matrices are required.")
}
if(length(select) != ncol(T)){
stop("The select is incorrect.")
}
if(!(job[1] %in% c("B", "V", "E", "N"))){
stop("The job should be one of \"B\", \"V\", \"E\", or \"N\".")
}
JOB <- as.character(job[1])
COMPQ <- ifelse(want.Q, "V", "N")
ISELECT <- as.integer(as.logical(select))
N <- as.integer(ncol(T))
LDB <- as.integer(N)
LDQ <- as.integer(N)
WR <- double(N)
WI <- double(N)
M <- integer(1)
S <- double(1)
SEP <- double(1)
if(is.null(LWORK) || LWORK < N * (N + 1) / 2){
LWORK <- as.integer(N * (N + 1) / 2)
} else{
LWORK <- as.integer(LWORK)
}
WORK <- double(LWORK)
if(is.null(LIWORK) || LIWORK < N * (N + 1) / 4){
LIWORK <- as.integer(N * (N + 1) / 4)
} else{
LIWORK <- as.integer(LIWORK)
}
IWORK <- integer(LIWORK)
INFO <- integer(1)
ret <- .Call("R_dtrsen",
JOB, COMPQ, ISELECT, N, T, LDB, Q, LDQ,
WR, WI, M, S, SEP,
WORK, LWORK, IWORK, LIWORK, INFO,
PACKAGE = "QZ")
ret$WR <- WR
ret$WI <- WI
ret$M <- M
ret$S <- S
ret$SEP <- SEP
ret$WORK <- WORK[1]
ret$IWORK <- IWORK[1]
ret$INFO <- INFO
if(all(WI == 0)){
ret$W <- WR
} else{
ret$W <- complex(real = WR, imaginary = WI)
}
if(! want.Q){
ret$Q <- NULL
}
class(ret) <- "dtrsen"
ret
}
print.dtrsen <- function(x, digits = max(4, getOption("digits") - 3), ...){
op.org <- options()
options(digits = digits)
cat("W:\n")
print(x$W)
cat("\nT:\n")
print(x$T)
if(! is.null(x$Q)){
cat("\nQ:\n")
print(x$Q)
}
options(op.org)
invisible()
} |
runningmean <-
function(pos, value, at, window=1000, what=c("mean","sum", "median", "sd"))
{
what <- which(c("sum","mean","median","sd")==match.arg(what))
n <- length(pos)
if(length(value) != n)
stop("pos and value must have the same length\n")
if(missing(at))
at <- pos
if(any(diff(pos) < 0)) {
o <- order(pos)
pos <- pos[o]
value <- value[o]
}
if(any(diff(at) < 0)) {
o.at <- order(at)
at <- at[o.at]
reorderresult <- TRUE
}
else reorderresult <- FALSE
n.res <- length(at)
z <- .C("R_runningmean",
as.integer(n),
as.double(pos),
as.double(value),
as.integer(n.res),
as.double(at),
z=as.double(rep(0,n.res)),
as.double(window),
as.integer(what),
PACKAGE="qtlhot")$z
if(reorderresult)
z <- z[match(1:length(at), o.at)]
z
} |
"centaurea" |
.snqProfitImposeConvexityStEr <- function( estResult, rankReduction,
start, optimMethod, control, stErMethod, nRep, verbose ) {
nObs <- nrow( estResult$data )
nCoef <- length( estResult$coef$liCoef )
nAllCoef <- length( estResult$coef$allCoef )
nNetput <- length( estResult$pMeans )
nFix <- length( estResult$fMeans )
sim <- list()
if( stErMethod == "jackknife" ) {
nRep <- nObs
}
sim$coef <- matrix( NA, nCoef, nRep )
sim$allCoef <- matrix( NA, nAllCoef, nRep )
sim$status <- rep( NA, nRep )
sim$results <- list()
if( stErMethod %in% c( "jackknife", "resample" ) ) {
for( repNo in 1:nRep ) {
if( verbose >= 2 ) {
cat( repNo, " / ", nRep, sep = "" )
}
if( stErMethod == "jackknife" ) {
simData <- estResult$data[ -repNo, ]
} else if( stErMethod == "resample" ) {
simData <- estResult$data[ ceiling( runif( nObs, 0, nObs ) ), ]
}
simResult <- try( snqProfitEst( priceNames = estResult$priceNames,
quantNames = estResult$quantNames, fixNames = estResult$fixNames,
instNames = estResult$instNames, data = simData, form = estResult$form,
scalingFactors = estResult$scalingFactors,
weights = estResult$weights, method = estResult$method ),
silent = TRUE )
if( class( simResult) == "try-error" ) {
sim$status[ repNo ] <- 888
} else {
if( simResult$convexity ) {
sim$status[ repNo ] <- -1
} else {
simResult <- try( snqProfitImposeConvexity( simResult,
rankReduction = rankReduction, start = start,
optimMethod = optimMethod, control = control ),
silent = TRUE )
if( class( simResult) == "try-error" ) {
sim$status[ repNo ] <- 999
} else {
sim$status[ repNo ] <- simResult$mindist$convergence
}
}
}
if( sim$status[ repNo ] <= 0 ) {
sim$coef[ , repNo ] <- simResult$coef$liCoef
sim$allCoef[ , repNo ] <- simResult$coef$allCoef
}
if( verbose >= 3 ) {
cat( ", status: ", sim$status[ repNo ], "\n", sep = "" )
}
}
} else if( stErMethod == "coefSim" ) {
fakeResult <- list()
class( fakeResult ) <- "snqProfitEst"
fakeResult$qMeans <- estResult$qMeans
fakeResult$pMeans <- estResult$pMeans
fakeResult$fMeans <- estResult$fMeans
fakeResult$weights <- estResult$weights
fakeResult$form <- estResult$form
fakeResult$data <- estResult$data
fakeResult$normPrice <- estResult$normPrice
fakeResult$scalingFactors <- estResult$scalingFactors
for( repNo in 1:nRep ) {
if( verbose >= 2 ) {
cat( repNo, " / ", nRep, sep = "" )
}
liCoef <- mvrnorm( mu = estResult$coef$liCoef,
Sigma = estResult$coef$liCoefCov )
fakeResult$coef <- snqProfitCoef( liCoef, nNetput, nFix,
form = estResult$form, coefCov = estResult$coef$liCoefCov )
fakeResult$hessian <- snqProfitHessian( fakeResult$coef$beta,
fakeResult$pMeans, fakeResult$weights )
fakeResult$convexity <- semidefiniteness( fakeResult$hessian[
1:( nNetput - 1 ), 1:( nNetput - 1 ) ], positive = TRUE )
if( fakeResult$convexity ) {
simResult <- fakeResult
sim$status[ repNo ] <- -1
} else {
simResult <- try( snqProfitImposeConvexity( fakeResult,
rankReduction = rankReduction, start = start,
optimMethod = optimMethod, control = control ),
silent = ( verbose < 2 ) )
if( class( simResult) == "try-error" ) {
sim$status[ repNo ] <- 999
} else {
sim$status[ repNo ] <- simResult$mindist$convergence
}
}
if( sim$status[ repNo ] <= 0 ) {
sim$coef[ , repNo ] <- simResult$coef$liCoef
sim$allCoef[ , repNo ] <- simResult$coef$allCoef
}
if( verbose >= 2 ) {
cat( ", status: ", sim$status[ repNo ], "\n", sep = "" )
}
}
}
nValidRep <- sum( sim$status <= 0 )
sim$coef <- sim$coef[ , sim$status <= 0 ]
sim$allCoef <- sim$allCoef[ , sim$status <= 0 ]
sim$coefMean <- rowMeans( sim$coef )
sim$allCoefMean <- rowMeans( sim$allCoef )
sim$coefDev <- sim$coef - matrix( sim$coefMean, nCoef, nValidRep )
sim$allCoefDev <- sim$allCoef - matrix( sim$allCoefMean, nAllCoef,
nValidRep )
sim$coefVcov <- sim$coefDev %*% t( sim$coefDev )
sim$allCoefVcov <- sim$allCoefDev %*% t( sim$allCoefDev )
if( stErMethod == "jackknife" ) {
sim$coefVcov <- ( ( nValidRep - 1 ) / nValidRep ) * sim$coefVcov
sim$allCoefVcov <- ( ( nValidRep - 1 ) / nValidRep ) *
sim$allCoefVcov
} else if( stErMethod %in% c( "resample", "coefSim" ) ) {
sim$coefVcov <- sim$coefVcov / nValidRep
sim$allCoefVcov <- sim$allCoefVcov / nValidRep
}
return( sim )
} |
color_of <- function(x, ...) UseMethod("color_of")
color_of.default <- function(x, ...) {
if (length(x) == 0) {
character()
} else if (is.vector(x)) {
warning("'color_of()' not implemented for class \"", class(x)[1], "\".")
rep(NA_character_, length(x))
} else if (is.any_spct(x)) {
warning("To obtain the colour of a filter or reflector, first multiply",
" by spectral irradiance under which it is observed.")
NA_character_
}
}
color_of.numeric <- function(x,
type = "CMF",
chroma.type = type,
...) {
if (length(x) == 0) {
return(character())
}
stopifnot(all(ifelse(is.na(x), Inf, x) > 0))
if (is.character(chroma.type)) {
if (chroma.type == "CMF") {
color.out <-
w_length2rgb(x, sens = photobiology::ciexyzCMF2.spct,
color.name = NULL)
} else if (chroma.type == "CC") {
color.out <-
w_length2rgb(x, sens = photobiology::ciexyzCC2.spct, color.name = NULL)
} else {
warning("Chroma type = ", chroma.type, " not implemented for 'numeric'.")
color.out <- rep(NA_character_, length(x))
}
if (!is.null(names(x))) {
names(color.out) <- paste(names(x), chroma.type, sep = ".")
} else {
names(color.out) <- paste(names(color.out), chroma.type, sep = ".")
}
} else if (is.chroma_spct(chroma.type)) {
color.out <-
w_length2rgb(x, sens = chroma.type,
color.name = NULL)
if (!is.null(names(x))) {
names(color.out) <- paste(names(x), "chroma", sep = ".")
} else {
names(color.out) <- paste(names(color.out), "chroma", sep = ".")
}
} else {
warning("Chroma type of class \"", class(chroma.type)[1], "\" not supported.")
color.out <- rep(NA_character_, length(x))
}
color.out
}
color_of.list <- function(x,
short.names = TRUE,
type = "CMF",
chroma.type = type,
...) {
color.out <- character(0)
for (xi in x) {
color.out <- c(color.out,
color_of(xi,
short.names = short.names,
chroma.type = chroma.type,
...))
}
if (!is.null(names(x))) {
names(color.out) <- paste(names(x), chroma.type, sep = ".")
}
return(color.out)
}
color_of.waveband <- function(x,
short.names = TRUE,
type = "CMF",
chroma.type = type,
...) {
idx <- ifelse(!short.names, "name", "label")
name <- labels(x)[[idx]]
if (is.character(chroma.type)) {
if (chroma.type == "both") {
color <- list(CMF = w_length_range2rgb(range(x),
sens = photobiology::ciexyzCMF2.spct,
color.name = paste(name, "CMF", sep = ".")),
CC = w_length_range2rgb(range(x),
sens = photobiology::ciexyzCC2.spct,
color.name = paste(name, "CC", sep = ".")))
} else if (chroma.type == "CMF") {
color <- w_length_range2rgb(range(x),
sens = photobiology::ciexyzCMF2.spct,
color.name = paste(name, "CMF", sep = "."))
} else if (chroma.type == "CC") {
color <- w_length_range2rgb(range(x),
sens = photobiology::ciexyzCC2.spct,
color.name = paste(name, "CC", sep = "."))
} else {
color <- NA_character_
}
} else if (is.chroma_spct(chroma.type)) {
color <- w_length_range2rgb(range(x),
sens = chroma.type,
color.name = paste(name, "chroma", sep = "."))
} else {
warning("Chroma type of class \"", class(chroma.type)[1], "\" not supported.")
color <- NA_character_
}
return(color)
}
color_of.source_spct <- function(x,
type = "CMF",
chroma.type = type,
...) {
if (length(x) == 0) {
return(character())
}
x.name <- "source"
q2e(x, byref = TRUE)
if (is.character(chroma.type)) {
if (chroma.type == "CMF") {
s_e_irrad2rgb(x[["w.length"]], x[["s.e.irrad"]],
sens = photobiology::ciexyzCMF2.spct,
color.name = paste(x.name, "CMF", sep = "."))
} else if (chroma.type == "CC") {
s_e_irrad2rgb(x[["w.length"]], x[["s.e.irrad"]],
sens = photobiology::ciexyzCC2.spct,
color.name = paste(x.name, "CC", sep = "."))
} else if (chroma.type == "both") {
c(s_e_irrad2rgb(x[["w.length"]], x[["s.e.irrad"]],
sens = photobiology::ciexyzCMF2.spct,
color.name = paste(x.name, "CMF", sep = ".")),
s_e_irrad2rgb(x[["w.length"]], x[["s.e.irrad"]],
sens = photobiology::ciexyzCC2.spct,
color.name = paste(x.name, "CC", sep = ".")))
} else {
warning("Chroma type = ", chroma.type, " not implemented for 'source_spct'.")
color.out <- NA_character_
names(color.out) <- paste(x.name, chroma.type, sep = ".")
color.out
}
} else if (is.chroma_spct(chroma.type)) {
s_e_irrad2rgb(x[["w.length"]],
x[["s.e.irrad"]],
sens = chroma.type,
color.name = paste(x.name, "chroma", sep = "."))
} else {
warning("Chroma type of class \"", class(chroma.type)[1], "\" not supported.")
NA_character_
}
}
color_of.source_mspct <- function(x,
...,
idx = "spct.idx") {
msdply(mspct = x, color_of, ..., idx = idx, col.names = "color")
}
colour_of <- function(x, ...) {
color_of(x, ...)
}
color <- function(x, ...) {
message("Method photobiology::color() has been renamed color_of(),",
"color() is deprecated and will be removed.")
color_of(x, ...)
}
fast_color_of_wl <- function(x, type = "CMF", ...) {
stopifnot(is.numeric(x))
x <- unname(x)
if (length(x) == 0 || anyNA(x) ||
min(x) < 100 || max(x > 4000) ||
!is.character(type) ||
!type %in% c("CMF", "CC")) {
color_of.numeric(x, type)
} else {
wls.tb <- tibble::tibble(w.length = round(x, digits = 0))
dplyr::left_join(wls.tb,
wl_colors.spct,
by = "w.length")[[type]]
}
}
fast_color_of_wb <- function(x, type = "CMF", ...) {
if (is.waveband(x)) {
x <- list(x)
}
stopifnot(is.list(x) && all(sapply(x, is.waveband)))
wb.wds <- sapply(x, wl_expanse)
if (all(wb.wds < 10)) {
wb.mid <- sapply(x, midpoint)
z <- fast_color_of_wl(wb.mid, type = type)
wb.names <- sapply(x, function(x) {labels(x)[["label"]]})
color.names <- paste(wb.names, type, sep = ".")
names(z) <- color.names
z
} else {
sapply(x, color_of.waveband, type = type)
}
} |
context("test-cross-validate")
test_that("number of crossfolds is a single integer", {
expect_error(crossv_kfold(mtcars, k = "0"), "single integer")
expect_error(crossv_kfold(mtcars, k = c(1, 2)), "single integer")
})
test_that("% of observations held out for testing is between 0 and 1", {
expect_error(crossv_mc(mtcars, n = 100, test = 2), "value between")
})
test_that("number of training pairs to generate is a single integer", {
expect_error(crossv_mc(mtcars, n = c(1,2)), "single integer")
expect_error(crossv_mc(mtcars, n = "0"), "single integer")
})
test_that("crossv_kfold() and crossv_mc() return tibbles", {
out <- crossv_kfold(mtcars, 5)
expect_s3_class(out, "tbl_df")
out <- crossv_mc(mtcars, 5)
expect_s3_class(out, "tbl_df")
}) |
display_groupxy <- function(centr = TRUE, axes = "center", half_range = NULL,
col = "black", pch = 20, cex = 1, edges = NULL,
group_by = NULL, plot_xgp = TRUE, ...) {
labels <- NULL
if (!areColors(col)) col <- mapColors(col)
init <- function(data) {
half_range <<- compute_half_range(half_range, data, centr)
labels <<- abbreviate(colnames(data), 3)
}
if (!is.null(edges)) {
if (!is.matrix(edges) && ncol(edges) >= 2) {
stop("Edges matrix needs two columns, from and to, only.")
}
}
render_frame <- function() {
par(pty = "s", mar = rep(0.1, 4))
}
render_transition <- function() {
rect(-1, -1, 1, 1, col = "
}
render_data <- function(data, proj, geodesic) {
gps <- unique(group_by)
ngps <- length(gps)
if (ngps > 24) {
stop("Please choose a group with 24 or less levels.\n")
}
grid <- ceiling(sqrt(ngps + 1))
par(mfrow = c(grid, grid))
x <- data %*% proj
if (centr) x <- center(x)
x <- x / half_range
blank_plot(xlim = c(-1, 1), ylim = c(-1, 1))
draw_tour_axes(proj, labels, limits = 1, axes)
if (ngps < 2) {
points(x, col = col, pch = pch, cex = cex, new = FALSE)
if (!is.null(edges)) {
segments(
x[edges[, 1], 1], x[edges[, 1], 2],
x[edges[, 2], 1], x[edges[, 2], 2]
)
}
}
else {
for (i in 1:ngps) {
x.sub <- x[group_by == gps[i], ]
col.sub <- if (length(col) == nrow(x)) col[group_by == gps[i]] else col
pch.sub <- if (length(pch) == nrow(x)) pch[group_by == gps[i]] else pch
cex.sub <- if (length(cex) == nrow(x)) cex[group_by == gps[i]] else cex
blank_plot(xlim = c(-1, 1), ylim = c(-1, 1))
if (plot_xgp) {
points(x[group_by != gps[i], ],
col = "
pch = if (length(pch) > 1) pch[group_by != gps[i]] else pch,
cex = if (length(cex) > 1) cex[group_by != gps[i]] else cex
)
}
points(x.sub, col = col.sub, pch = pch.sub, cex = cex.sub, new = FALSE)
if (!is.null(edges)) {
segments(
x[edges[group_by == gps[i], 1], 1], x[edges[group_by == gps[i], 1], 2],
x[edges[group_by == gps[i], 2], 1], x[edges[group_by == gps[i], 2], 2]
)
}
}
}
}
list(
init = init,
render_frame = render_frame,
render_transition = render_transition,
render_data = render_data,
render_target = nul
)
}
animate_groupxy <- function(data, tour_path = grand_tour(), ...) {
animate(data, tour_path, display_groupxy(...))
par(mfrow = c(1, 1))
} |
PlausibleFormula <- function(x, ruleset=c("APCI","ESI")[1]) {
if (ruleset=="APCI") {
if (length(x)==1 && is.character(x)) {
out_name <- x
x <- CountChemicalElements(x, ele=c("C","H","N","O","P","S","Si"))
out <- TRUE
ulim <- list("C"=60, "H"=100, "N"=10, "O"=27, "P"=4, "S"=3, "Si"=12)
out <- out & all(sapply(names(ulim), function(y) { x[y]<=ulim[[y]] }), na.rm=T)
llim <- list("C"=1, "H"=4)
out <- out & all(sapply(names(llim), function(y) { x[y]>=llim[[y]] }), na.rm=T)
out <- out & x["H"]<=(1+4*x["C"])
out <- out & x["N"]<=x["C"]
out <- out & x["O"]<=x["C"]
out <- out & 6*x["P"]<=x["C"]
out <- out & 4*x["S"]<=x["C"]
out <- out & sum(x[c("N","O","P","S")])<=x["C"]
out <- out & ifelse(x["Si"]==0, TRUE, !(8*x["Si"] < x["O"]+x["N"]+x["S"]+x["P"]))
out <- out & !(x["Si"] > 2*(x["O"]+x["N"]+x["S"]+x["P"]))
out <- out & (3*x["Si"]-2 <= x["C"])
out <- out & (8*x["Si"]-3 <= x["H"])
out <- out & x["S"]*x["P"]==0
out <- out & ifelse(x["S"]==2, x["S"]<x["Si"], TRUE)
out <- out & ifelse(x["P"]>0, 2*x["P"]<=x["Si"], TRUE)
out <- out & ifelse(x["P"]>0, x["O"]>=4, TRUE)
names(out) <- out_name
} else {
out <- NA
names(out) <- paste(x, collapse="_", sep="_")
}
}
if (ruleset=="ESI") {
if (length(x)==1 && is.character(x)) {
out_name <- x
x <- CountChemicalElements(x, ele=c("C","H","N","O","P","S","Cl","K","Na"))
m <- sum(x*c(12.0, 1.007825, 14.003074, 15.994915, 30.973762, 31.972071, 34.96885, 38.96371, 22.98977))
out <- TRUE
ulim <- list("C"=2+0.07*m, "H"=6+0.14*m, "N"=5+0.01*m, "O"=3+0.03*m, "P"=min(c(8, 1+0.01*m)), "S"=4)
out <- out & all(sapply(names(ulim), function(y) { x[y]<=ulim[[y]] }), na.rm=T)
llim <- list("C"=-15+0.04*m, "H"=-10+0.03*m, "N"=0, "O"=-25+0.03*m, "P"=0, "S"=0)
out <- out & x["N"]<=(3+x["C"])
out <- out & (x["O"]-4*x["P"])<=(2+x["C"])
out <- out & x["P"]<=(1+x["C"])
out <- out & x["S"]<=(1+x["C"])
out <- out & (x["N"]+x["P"]+x["O"]-4*x["P"]+x["S"])<=(4+x["C"])
out <- out & x["S"]*x["P"]==0
out <- out & x["Na"]*x["K"]==0
out <- out & ifelse(x["P"]>0, x["O"]>=2, TRUE)
names(out) <- out_name
} else {
out <- NA
names(out) <- paste(x, collapse="_", sep="_")
}
}
return(out)
} |
context("wbt_arcosh")
test_that("Returns the inverse hyperbolic cosine (arcosh) of each values in a raster", {
skip_on_cran()
skip_if_not(check_whitebox_binary())
dem <- system.file("extdata", "DEM.tif", package = "whitebox")
ret <- wbt_arcosh(input = dem, output = "output.tif")
expect_match(ret, "Elapsed Time")
}) |
readLocalMaster <- function(){
f <- system.file("external/EnvCanadaMaster.csv", package = "CHCN")
return(read.csv(f, stringsAFactors = FALSE))
} |
flexpnr <- function(X, b, q, h, T) {
if(is.list(b)){
coefs <- b
b <- coefs[['b']]
q <- coefs[['q']]
h <- coefs[['h']]
T <- coefs[['T']]
}
a <- (b*X^q)
return(X-lamW::lambertW0(a*h*X*exp(-a*(T-h*X)))/(a*h))
}
flexpnr_fit <- function(data, samp, start, fixed, boot=FALSE, windows=FALSE) {
fr_setpara(boot, windows)
samp <- sort(samp)
dat <- data[samp,]
out <- fr_setupout(start, fixed, samp)
try_flexpnr <- try(bbmle::mle2(flexpnr_nll, start=start, fixed=fixed, data=list('X'=dat$X, 'Y'=dat$Y),
optimizer='optim', method='Nelder-Mead', control=list(maxit=5000)),
silent=T)
if (inherits(try_flexpnr, "try-error")) {
if(boot){
return(out)
} else {
stop(try_flexpnr[1])
}
} else {
for (i in 1:length(names(start))){
cname <- names(start)[i]
vname <- paste(names(start)[i], 'var', sep='')
out[cname] <- coef(try_flexpnr)[cname]
out[vname] <- vcov(try_flexpnr)[cname, cname]
}
for (i in 1:length(names(fixed))){
cname <- names(fixed)[i]
out[cname] <- as.numeric(fixed[cname])
}
if(boot){
return(out)
} else {
return(list(out=out, fit=try_flexpnr))
}
}
}
flexpnr_nll <- function(b, q, h, T, X, Y) {
if (b <= 0 || h <= 0) {return(NA)}
if (q < -1){return(NA)}
prop.exp = flexpnr(X, b, q, h, T)/X
if(any(is.complex(prop.exp))){return(NA)}
if(any(is.nan(prop.exp)) || any(is.na(prop.exp))){return(NA)}
if(any(prop.exp > 1) || any(prop.exp < 0)){return(NA)}
return(-sum(dbinom(Y, prob = prop.exp, size = X, log = TRUE)))
}
flexpnr_diff <- function(X, grp, b, q, h, T, Db, Dq, Dh) {
a <- ((b-Db*grp)*X^(q-Dq*grp))
return(X-lamW::lambertW0(a*(h-Dh*grp)*X*exp(-a*(T-(h-Dh*grp)*X)))/(a*(h-Dh*grp)))
}
flexpnr_nll_diff <- function(b, q, h, T, Db, Dq, Dh, X, Y, grp) {
if (b <= 0 || h <= 0) {return(NA)}
if (q < -1){return(NA)}
prop.exp = flexpnr_diff(X, grp, b, q, h, T, Db, Dq, Dh)/X
if(any(is.complex(prop.exp))){return(NA)}
if(any(is.nan(prop.exp)) || any(is.na(prop.exp))){return(NA)}
if(any(prop.exp > 1) || any(prop.exp < 0)){return(NA)}
return(-sum(dbinom(Y, prob = prop.exp, size = X, log = TRUE)))
} |
Predictblsm<-function(model){
est.alpha.1 = model$lsmbAlpha.1
Z.i = model$lsmbEZ.i
Z.a = model$lsmbEZ.a
D=nrow(model$lsmbVZ.1)
N=nrow(Z.i)
M=nrow(Z.a)
est.P.ia=matrix(NA,N,M)
for(i in 1:N){
for(a in 1:M){
est.P.ia[i,a]=inv.logit(est.alpha.1-sum((Z.i[i,] - Z.a[a,]) ^ 2))
}
}
return(est.P.ia)
} |
Menu.import <- function(){
designs <- listDesigns()
.activeDataSet <- ActiveDataSet()
if (length(designs) == 0){
Message(message=gettextRcmdr("There are no designs from which to choose."),
type="error")
tkfocus(CommanderWindow())
return()
}
initializeDialog(title=gettextRcmdr("Select Design"))
designsBox <- variableListBox(top, designs, title=gettextRcmdr("Designs (pick one)"),
initialSelection=if (is.null(.activeDataSet) || !.activeDataSet %in% designs) NULL
else which(.activeDataSet == designs) - 1)
onOK <- function(){
activeDataSet(getSelection(designsBox))
closeDialog()
tkfocus(CommanderWindow())
}
OKCancelHelp(helpSubject="Menu.import")
tkgrid(getFrame(designsBox), sticky="n")
tkgrid(buttonsFrame, sticky="w")
dialogSuffix(rows=2, columns=1)
} |
`jack2` <-
function(x,taxa.row=TRUE,abund=TRUE) {
if (taxa.row==FALSE) x<-t(x)
if (ncol(as.matrix(x))==1|nrow(as.matrix(x))==1) {
x <- x
m <- sum(x)
}
else if (abund==TRUE) {x <- rowSums(x)
m <- sum(x)}
else {m <-length(x[1,])
x1 <- numeric(length(x[,1]))
for (i in 1:length(x[,1])) x1[i] <- length(x[i,][x[i,]>0])
x<-x1}
q1 <- length(x[x==1])
q2 <- length(x[x==2])
so <- length(x[x>0])
soj <- so+q1*(2*(m-3)/m)-q2*((m-2)^2/(m*(m-1)))
return(soj)
} |
P_vals <- function(z, rho, Npulse, tau, k) {
P_func <- function(x) {
rho * 1 / (log(1 / (1 - rho)) - 2 * pi * complex(real = 0, imaginary = 1) * x)
}
z_vec <- matrix(0, nrow = Npulse, ncol = 1)
for (i in 1:Npulse) {
z_vec[i, 1] <- z[i]
}
if (k == 0) {
if (Npulse == 2) {
N_terms <- 5
} else if (Npulse == 3) {
N_terms <- 7
} else {
N_terms <- 8
}
int_vecs <- matrix(0, nrow = Npulse, ncol = N_terms)
for (i in 1:5) {
int_vecs[1:2, i] <- c((i - 1), -(i - 1))
}
if (Npulse >= 3) {
int_vecs[1:3, 6] <- c(2, -1, -1)
int_vecs[1:3, 7] <- c(-2, 1, 1)
}
if (Npulse >= 4) {
int_vecs[1:4, 8] <- c(1, 1, -1, -1)
}
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
if (i == 1) {
Nperms <- 1
} else {
Nperms <- length(perm_list[, 1])
}
for (m in 1:Nperms) {
if (i == 1) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * (perm_list %*% z) / tau)
} else {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * (perm_list[m, ] %*% z) / tau)
}
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
return(val)
} else if (abs(k) == 1) {
kk <- abs(k)
if (Npulse == 2) {
N_terms <- 5
} else {
N_terms <- 8
}
int_vecs <- matrix(0, nrow = Npulse, ncol = N_terms)
for (i in 1:5) {
int_vecs[1:2, i] <- sign(k) * c(kk + (i - 1), -(i - 1))
}
if (Npulse >= 3) {
int_vecs[1:3, 6] <- sign(k) * c(1, 1, -1)
int_vecs[1:3, 7] <- sign(k) * c(3, -1, -1)
int_vecs[1:3, 8] <- sign(k) * c(2, -2, 1)
}
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
return(val)
}
else if (abs(k) == 2) {
kk <- abs(k)
if (Npulse == 2) {
N_terms <- 5
} else if (Npulse == 3) {
N_terms <- 6
} else {
N_terms <- 7
}
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk + 1, -1)
int_vecs[1:2, 4] <- sign(k) * c(kk + 2, -2)
int_vecs[1:2, 5] <- sign(k) * c(kk + 3, -3)
if (Npulse >= 3) {
int_vecs[1:3, 6] <- sign(k) * c(2, -1, 1)
}
if (Npulse >= 4) {
int_vecs[1:4, 7] <- sign(k) * c(1, 1, 1, -1)
}
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
if (Npulse == 2 && i == 2) {
Nperms <- 1
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list %*% z / tau)
} else {
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
return(val)
} else if (abs(k) == 3) {
kk <- abs(k)
if (Npulse == 2) {
N_terms <- 5
} else {
N_terms <- 8
}
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk + 1, -1)
int_vecs[1:2, 4] <- sign(k) * c(kk + 2, -2)
int_vecs[1:2, 5] <- sign(k) * c(kk + 3, -3)
if (Npulse >= 3) {
int_vecs[1:3, 6] <- sign(k) * c(1, 1, 1)
int_vecs[1:3, 7] <- sign(k) * c(3, 1, -1)
int_vecs[1:3, 8] <- sign(k) * c(2, 2, -1)
}
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
if (Npulse == 3 && i == 6) {
Nperms <- 1
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list %*% z / tau)
} else {
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
return(val)
} else if (abs(k) == 4) {
kk <- abs(k)
if (Npulse == 2) {
N_terms <- 5
} else if (Npulse == 3) {
N_terms <- 7
} else {
N_terms <- 8
}
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk - 2, 2)
int_vecs[1:2, 4] <- sign(k) * c(kk + 1, -1)
int_vecs[1:2, 5] <- sign(k) * c(kk + 2, -2)
if (Npulse >= 3) {
int_vecs[1:3, 6] <- sign(k) * c(4, -1, 1)
int_vecs[1:3, 7] <- sign(k) * c(2, 1, 1)
}
if (Npulse >= 4) {
int_vecs[1:4, 8] <- sign(k) * c(1, 1, 1, 1)
}
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
if (Npulse == 4 && i == 8) {
Nperms <- 1
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list %*% z / tau)
} else if (Npulse == 2 && i == 3) {
Nperms <- 1
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list %*% z / tau)
} else {
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
return(val)
} else if (abs(k) == 5) {
kk <- abs(k)
if (Npulse == 2) {
N_terms <- 5
} else {
N_terms <- 7
}
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk - 2, 2)
int_vecs[1:2, 4] <- sign(k) * c(kk + 1, -1)
int_vecs[1:2, 5] <- sign(k) * c(kk + 2, -2)
if (Npulse >= 3) {
int_vecs[1:3, 6] <- sign(k) * c(2, 2, 1)
int_vecs[1:3, 7] <- sign(k) * c(3, 1, 1)
}
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
return(val)
} else if (abs(k) == 6) {
kk <- abs(k)
if (Npulse == 2) {
N_terms <- 6
} else {
N_terms <- 7
}
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk - 2, 2)
int_vecs[1:2, 4] <- sign(k) * c(kk - 3, 3)
int_vecs[1:2, 5] <- sign(k) * c(kk + 1, -1)
int_vecs[1:2, 6] <- sign(k) * c(kk + 2, -2)
if (Npulse >= 3) {
int_vecs[1:3, 7] <- sign(k) * c(4, 1, 1)
}
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
if (Npulse == 2 && i == 4) {
Nperms <- 1
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list %*% z / tau)
} else {
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
return(val)
} else if (abs(k) == 7) {
kk <- abs(k)
N_terms <- 6
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk - 2, 2)
int_vecs[1:2, 4] <- sign(k) * c(kk - 3, 3)
int_vecs[1:2, 5] <- sign(k) * c(kk + 1, -1)
int_vecs[1:2, 6] <- sign(k) * c(kk + 2, -2)
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
return(val)
} else if (abs(k) == 8) {
kk <- abs(k)
N_terms <- 6
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk - 2, 2)
int_vecs[1:2, 4] <- sign(k) * c(kk + 1, -1)
int_vecs[1:2, 5] <- sign(k) * c(kk - 3, +3)
int_vecs[1:2, 6] <- sign(k) * c(kk - 4, +4)
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
if (Npulse == 2 && i == 6) {
Nperm <- 1
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list %*% z / tau)
} else {
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
return(val)
} else if (abs(k) == 9) {
kk <- abs(k)
N_terms <- 5
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk + 1, -1)
int_vecs[1:2, 4] <- sign(k) * c(kk - 2, 2)
int_vecs[1:2, 5] <- sign(k) * c(kk - 3, +3)
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[i] * post_factors[i]
}
return(val)
} else if (abs(k) == 10) {
kk <- abs(k)
N_terms <- 4
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk + 1, -1)
int_vecs[1:2, 4] <- sign(k) * c(kk - 2, 2)
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
return(val)
} else if (abs(k) == 11) {
kk <- abs(k)
N_terms <- 4
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk + 1, -1)
int_vecs[1:2, 4] <- sign(k) * c(kk - 2, 2)
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[1, i] * post_factors[i]
}
out <- val
} else {
kk <- abs(k)
N_terms <- 3
int_vecs <- matrix(0, Npulse, N_terms)
int_vecs[1:2, 1] <- sign(k) * c(kk + 0, 0)
int_vecs[1:2, 2] <- sign(k) * c(kk - 1, 1)
int_vecs[1:2, 3] <- sign(k) * c(kk + 1, -1)
pre_factors <- matrix(1, ncol = N_terms, nrow = 1)
for (i in 1:N_terms) {
for (m in 1:Npulse) {
pre_factors[1, i] <- pre_factors[1, i] * P_func(int_vecs[m, i])
}
}
post_factors <- numeric(N_terms)
for (i in 1:N_terms) {
perm_list <- uperm(int_vecs[, i])
Nperms <- dim(perm_list)[1]
for (m in 1:Nperms) {
post_factors[i] <- post_factors[i] + exp(-2 * pi * complex(real = 0, imaginary = 1) * perm_list[m, ] %*% z / tau)
}
}
val <- 0
for (i in 1:N_terms) {
val <- val + pre_factors[i] * post_factors[i]
}
return(val)
}
} |
plot.hero_adjacent = function(x, ...) {
nnbrs = sapply(x$nbrs, length)
a = Matrix::sparseMatrix(i = rep(seq_along(nnbrs), times = nnbrs),
j = unlist(x$nbrs),
x = 1)
if (!requireNamespace("igraph", quietly = TRUE)) {
message("The \"igraph\" package will enhance this function. Please install it.")
graphics::image(a, ...)
} else {
g = igraph::graph_from_adjacency_matrix(a)
plot(g, layout = as.matrix(x$coords), ...)
}
} |
restxml_build <- function(request) {
request <- rest_build(request)
t <- rest_payload_type(request$params)
if (t == "structure" || t == "") {
request <- xml_build_body(request)
}
return(request)
}
restxml_unmarshal_meta <- function(request) {
request <- rest_unmarshal_meta(request)
return(request)
}
restxml_unmarshal <- function(request) {
t <- rest_payload_type(request$data)
if (t == "structure" || t == "") {
data <- decode_xml(request$http_response$body)
interface <- request$data
result_name <- paste0(request$operation$name, "Result")
request$data <- xml_unmarshal(data, interface, result_name)
} else {
request <- rest_unmarshal(request)
}
return(request)
}
restxml_unmarshal_error <- function(request) {
request <- query_unmarshal_error(request)
return(request)
} |
require(OpenMx)
A <- mxMatrix("Symm",
values = c(1.0, 0.23, 0.34, 2.0, 0.45, 3.0),
nrow = 3, ncol = 3, name = "A")
B <- mxAlgebra(solve(A), name = "B")
model <- mxModel(A, B)
model <- mxRun(model)
print(model)
omxCheckCloseEnough(model[['B']]$result,
rbind(c(1.0583, -0.097, -0.1052),
c(-0.097, 0.5265, -0.0679),
c(-0.1052, -0.0679, .3554)), 0.01) |
cptable <- function(vpar, levels=NULL, values=NULL, normalize=TRUE, smooth=0 ){
vpa <- c(.formula2char(vpar))
if (is.list(levels)){
v <- vpa[1]
if (!(v %in% names(levels)))
stop(paste0("Name ", v, " is not in the 'levels' list\n"))
levels <- levels[[v]]
}
out <- values
attributes(out) <-
list(vpa=vpa, normalize=normalize,
smooth=smooth, levels=levels)
class(out) <- "cptable_class"
out
}
cdist <- function(vpar, parm=list()){
vpa <- c(.formula2char(vpar))
out <- parm
names(out) <- c("intercept", "slope", "sd")
attr(out, "vpa") <- vpa
class(out) <- "cdist"
out
}
print.cptable_class <- function(x, ...){
v <- c(x)
dim(v) <- c(length(attr(x,"levels")), length(v) / length(attr(x, "levels")))
rownames(v) <- attr(x, "levels")
cat(sprintf("{v, pa(v)} :\n"))
str(attr(x, "vpa"))
print(v)
invisible(x)
}
summary.cptable_class <- function(object, ...){
print(object)
str(attributes(object))
invisible(object)
}
varNames.cptable_class <- function(x){
attr(x, "vpa")
}
valueLabels.cptable_class <- function(x){
out <- list(attr(x, "levels"))
nam <- attr(x, "vpa")
names(out) <- attr(x, "vpa")[1]
out
} |
test_that("doesn't break metaprogramming with quosures", {
isolate({
my_quo <- local({
local_x <- 123L
rlang::quo({
"
local_x
})
})
outer_quo <- rlang::quo({
if (!!my_quo == 123L) {
"ok"
}
})
r1 <- rlang::inject(metaReactive(!!my_quo, varname = "r1"))
r2 <- rlang::inject(metaReactive(!!my_quo * -1L, varname = "r2"))
expect_identical(r1(), 123L)
expect_identical(r2(), -123L)
expect_snapshot_output(withMetaMode(r1()))
expect_snapshot_output(withMetaMode(r2()))
result1 <- NULL
o1 <- rlang::inject(metaObserve({
result1 <<- !!outer_quo
}))
shiny:::flushReact()
expect_identical(result1, "ok")
expect_snapshot_output(withMetaMode(o1()))
})
testthat::skip_if_not_installed("shiny", "1.6.0.9000")
isolate({
out1 <- rlang::inject(metaRender(shiny::renderText, !!outer_quo))
expect_identical(out1(), "ok")
})
})
describe("metaAction", {
it("basically works", {
a <- 1
metaAction({
a <- 2
})
expect_identical(a, 2)
metaAction(quote({
a <- 3
}), quoted = TRUE)
expect_identical(a, 3)
env <- new.env()
metaAction({
a <- 4
}, env = env)
expect_identical(a, 3)
expect_identical(env[["a"]], 4)
metaAction(quote({
a <- 5
}), env = env, quoted = TRUE)
expect_identical(a, 3)
expect_identical(env[["a"]], 5)
})
it("unquotes properly", {
b <- TRUE
act <- metaAction(x <- ..(b))
expect_identical(x, TRUE)
expect_snapshot_output(withMetaMode(act()))
mr <- metaReactive({
FALSE
})
isolate({
act <- metaAction(y <- ..(mr()))
})
expect_identical(y, FALSE)
expect_snapshot_output(expandChain(act()))
})
it("errors on non-meta usage", {
ma <- metaAction({})
expect_error(ma())
})
it("can contain code that uses !!", {
ma <- metaAction({
foo <- 1
x <- rlang::expr(!!foo)
})
expect_identical(x, 1)
if (getRversion() < "3.5") {
skip("Quoted !! isn't printed properly in R3.4 and lower.")
} else {
expect_snapshot_output(withMetaMode(ma()))
}
})
it("obeys scoping rules", {
outer <- environment()
i <- 0
mr <- metaReactive({
inner <- environment()
expect_false(identical(inner, outer))
i <<- i + 1
})
isolate(mr())
expect_identical(i, 1)
mr2 <- metaReactive2({
inner <- environment()
expect_false(identical(inner, outer))
i <<- i + 1
metaExpr({
innermost <- environment()
expect_true(identical(innermost, inner))
i <<- i + 1
})
})
isolate(mr2())
expect_identical(i, 3)
withMetaMode(mr2())
expect_identical(i, 4)
})
}) |
rvmcos <- function(n, kappa1=1, kappa2=1,
kappa3=0, mu1=0, mu2=0,
method="naive")
{
if(any(c(kappa1, kappa2) < 0)) stop("kappa1 and kappa2 must be nonnegative")
if(any(mu1 < 0 | mu1 >= 2*pi)) mu1 <- prncp_reg(mu1)
if(any(mu2 < 0 | mu2 >= 2*pi)) mu2 <- prncp_reg(mu2)
if(n < 0) stop("invalid n")
if (!method %in% c("naive", "vmprop"))
stop("method must be either \'naive\' or \'vmprop\'")
if(max(length(kappa1), length(kappa2), length(kappa3),
length(mu1), length(mu2)) > 1) {
expanded <- expand_args(kappa1, kappa2, kappa3, mu1, mu2)
k1 <- expanded[[1]]; k2 <- expanded[[2]]; k3 <- expanded[[3]]
mu1 <- expanded[[4]]; mu2 <- expanded[[5]]
t(vapply(1:length(k1),
function(j) rvmcos_1par(1, k1[j], k2[j], k3[j],
mu1[j], mu2[j], "naive"), c(0, 0)))
} else {
rvmcos_1par(n, kappa1, kappa2, kappa3, mu1, mu2, method)
}
}
dvmcos <- function(x, kappa1=1, kappa2=1, kappa3=0, mu1=0,
mu2=0, log=FALSE, ...) {
if (any(c(kappa1, kappa2) < 0)) stop("kappa1 and kappa2 must be nonnegative")
if (any(mu1 < 0 | mu1 >= 2*pi)) mu1 <- prncp_reg(mu1)
if (any(mu2 < 0 | mu2 >= 2*pi)) mu2 <- prncp_reg(mu2)
if ((length(dim(x)) < 2 && length(x) != 2) || (length(dim(x)) == 2 && tail(dim(x), 1) != 2)
|| (length(dim(x)) > 2)) stop("x must either be a bivariate vector or a two-column matrix")
ell <- list(...)
if (!is.null(ell$qrnd)) {
qrnd_grid <- ell$qrnd
dim_qrnd <- dim(qrnd_grid)
if (!is.matrix(qrnd_grid) | is.null(dim_qrnd) |
dim_qrnd[2] != 2)
stop("\'qrnd\' must be a two column matrix")
n_qrnd <- dim_qrnd[1]
} else if (!is.null(ell$n_qrnd)){
n_qrnd <- round(ell$n_qrnd)
if (n_qrnd < 1)
stop("n_qrnd must be a positive integer")
qrnd_grid <- sobol(n_qrnd, 2, FALSE)
} else {
n_qrnd <- 1e4
qrnd_grid <- sobol(n_qrnd, 2, FALSE)
}
if(max(length(kappa1), length(kappa2), length(kappa3), length(mu1), length(mu2)) > 1) {
expanded <- expand_args(kappa1, kappa2, kappa3, mu1, mu2)
kappa1 <- expanded[[1]]
kappa2 <- expanded[[2]]
kappa3 <- expanded[[3]]
mu1 <- expanded[[4]]
mu2 <- expanded[[5]]
}
par.mat <- rbind(kappa1, kappa2, kappa3, mu1, mu2)
n_par <- ncol(par.mat)
if (length(x) == 2) x <- matrix(x, nrow = 1)
n_x <- nrow(x)
if (is.null(ell$force_approx_const)) {
force_approx_const <- FALSE
} else if (!is.logical(ell$force_approx_const)) {
stop("\'force_approx_const\' must be logical.")
} else {
force_approx_const <- ell$force_approx_const
}
l_const_all <- rep(0, n_par)
for(j in 1:n_par) {
if (all(!force_approx_const,
((kappa3[j] >= -5 & max(kappa1[j], kappa2[j],
abs(kappa3[j])) <= 50) |
abs(kappa3[j]) < 1e-4))) {
l_const_all[j] <- log(const_vmcos_anltc(kappa1[j], kappa2[j],
kappa3[j]))
} else {
l_const_all[j] <- log(const_vmcos_mc(kappa1[j], kappa2[j],
kappa3[j], qrnd_grid));
}
}
if (n_par == 1) {
log_den <- c(ldcos_manyx_onepar(x, kappa1, kappa2, kappa3,
mu1, mu2, l_const_all))
} else if (n_x == 1) {
log_den <- c(ldcos_onex_manypar(c(x), kappa1, kappa2, kappa3,
mu1, mu2, l_const_all))
} else {
x_set <- 1:nrow(x)
par_set <- 1:n_par
expndn_set <- expand_args(x_set, par_set)
x_set <- expndn_set[[1]]
par_set <- expndn_set[[2]]
log_den <- c(ldcos_manyx_manypar(x[x_set, ], kappa1[par_set],
kappa2[par_set], kappa3[par_set],
mu1[par_set], mu2[par_set],
l_const_all[par_set]))
}
if (log) log_den
else exp(log_den)
}
rvmcosmix <- function(n, kappa1, kappa2, kappa3,
mu1, mu2, pmix, method = "naive", ...)
{
allpar <- list(kappa1=kappa1, kappa2=kappa2, kappa3=kappa3,
mu1=mu1, mu2=mu2, pmix=pmix)
allpar_len <- listLen(allpar)
if(min(allpar_len) != max(allpar_len))
stop("component size mismatch: number of components of the input parameter vectors differ")
if(any(allpar$pmix < 0)) stop("\'pmix\' must be non-negative")
sum_pmix <- sum(allpar$pmix)
if(signif(sum_pmix, 5) != 1) {
if(sum_pmix <= 0) stop("\'pmix\' must have at least one positive element")
allpar$pmix <- allpar$pmix/sum_pmix
warning("\'pmix\' is rescaled to add up to 1")
}
if(any(c(allpar$kappa1, allpar$kappa2) < 0)) stop("kappa1 and kappa2 must be non-negative")
if(any(allpar$mu1 < 0 | allpar$mu1 >= 2*pi)) allpar$mu1 <- prncp_reg(allpar$mu1)
if(any(allpar$mu2 < 0 | allpar$mu2 >= 2*pi)) allpar$mu2 <- prncp_reg(allpar$mu2)
out <- matrix(0, n, 2)
ncomp <- allpar_len[1]
comp_ind <- cID(tcrossprod(rep(1, n), allpar$pmix), ncomp, runif(n))
for(j in seq_len(ncomp)) {
obs_ind_j <- which(comp_ind == j)
n_j <- length(obs_ind_j)
if(n_j > 0) {
out[obs_ind_j, ] <- rvmcos(n_j, kappa1[j], kappa2[j],
kappa3[j], mu1[j], mu2[j], method)
}
}
out
}
dvmcosmix <- function(x, kappa1, kappa2, kappa3,
mu1, mu2, pmix, log=FALSE, ...)
{
allpar <- list("kappa1"=kappa1, "kappa2"=kappa2, "kappa3"=kappa3,
"mu1"=mu1, "mu2"=mu2, "pmix"=pmix)
allpar_len <- listLen(allpar)
if(min(allpar_len) != max(allpar_len)) stop("component size mismatch: number of components of the input parameter vectors differ")
if(any(allpar$pmix < 0)) stop("\'pmix\' must be non-negative")
sum_pmix <- sum(allpar$pmix)
if(signif(sum_pmix, 5) != 1) {
if(sum_pmix <= 0) stop("\'pmix\' must have at least one positive element")
allpar$pmix <- allpar$pmix/sum_pmix
warning("\'pmix\' is rescaled to add up to 1")
}
if(any(c(allpar$kappa1, allpar$kappa2) <= 0)) stop("kappa1 and kappa2 must be positive")
if(any(allpar$mu1 < 0 | allpar$mu1 >= 2*pi)) allpar$mu1 <- prncp_reg(allpar$mu1)
if(any(allpar$mu2 < 0 | allpar$mu2 >= 2*pi)) allpar$mu2 <- prncp_reg(allpar$mu2)
if((length(dim(x)) < 2 && length(x) != 2) || (length(dim(x)) == 2 && tail(dim(x), 1) != 2)
|| (length(dim(x)) > 2)) stop("x must either be a bivariate vector or a two-column matrix")
ncomp <- length(kappa1)
if (length(x) == 2) x <- matrix(x, nrow=1)
allcompden <- vapply(1:ncomp,
function(j) dvmcos(x, kappa1[j], kappa2[j],
kappa3[j], mu1[j], mu2[j], FALSE, ...),
rep(0, nrow(x)))
mixden <- c(allcompden %*% pmix)
if (log) {
log(mixden)
} else {
mixden
}
}
fit_vmcosmix <- function(...)
{
fit_angmix(model="vmcos", ...)
}
vmcos_var_cor_singlepar_numeric <- function(kappa1, kappa2, kappa3, qrnd_grid) {
fn_log_vmcos_const <- function(pars) {
const_vmcos(pars[1], pars[2], pars[3], uni_rand = qrnd_grid, return_log = TRUE)
}
grad_over_const <- numDeriv::grad(fn_log_vmcos_const, c(kappa1, kappa2, kappa3))
names(grad_over_const) <- c("k1", "k2", "k3")
hess_over_const <- numDeriv::hessian(fn_log_vmcos_const, c(kappa1, kappa2, kappa3)) +
tcrossprod(grad_over_const)
dimnames(hess_over_const) <- list(c("k1", "k2", "k3"), c("k1", "k2", "k3"))
rho_fl <- unname(
((grad_over_const["k3"] - hess_over_const["k1", "k2"]) *
hess_over_const["k1", "k2"]) /
sqrt(
hess_over_const["k1", "k1"] * (1 - hess_over_const["k1", "k1"])
* hess_over_const["k2", "k2"] * (1 - hess_over_const["k2", "k2"])
)
)
rho_js <- unname(
(grad_over_const["k3"] - hess_over_const["k1", "k2"]) /
sqrt((1 - hess_over_const["k1", "k1"]) *
(1 - hess_over_const["k2", "k2"]))
)
var1 <- unname(1 - grad_over_const["k1"])
var2 <- unname(1 - grad_over_const["k2"])
list(var1 = var1, var2 = var2, rho_fl = rho_fl, rho_js = rho_js)
}
vmcos_var_cor_singlepar <- function(kappa1, kappa2, kappa3,
qrnd_grid) {
if (max(kappa1, kappa2, abs(kappa3)) > 50 |
kappa3 < 0) {
out <- vmcos_var_cor_singlepar_numeric(kappa1, kappa2,
kappa3, qrnd_grid)
} else {
out <- vmcos_var_corr_anltc(kappa1, kappa2, kappa3)
}
for (rho in c("rho_js", "rho_fl")) {
if (out[[rho]] <= -1) {
out[[rho]] <- -1
} else if (out[[rho]] >= 1) {
out[[rho]] <- 1
}
}
for (var in c("var1", "var2")) {
if (out[[var]] <= 0) {
out[[var]] <- 0
} else if (out[[var]] >= 1) {
out[[var]] <- 1
}
}
out
}
rvmcos_1par <- function(n=1, kappa1, kappa2, kappa3, mu1, mu2, method)
{
if (abs(abs(kappa3) - kappa1) < 1e-8 |
abs(abs(kappa3) - kappa2) < 1e-8)
kappa3 <- kappa3*(1+1e-6)
if (method == "vmprop") {
qrnd_grid <- sobol(1e4, 2, FALSE)
log_const_vmcos <- log(const_vmcos(kappa1, kappa2, kappa3, qrnd_grid))
log_2pi <- log(2*pi)
unimodal_y <- TRUE
phistar <- NULL
method <- "vmprop"
if (kappa3 < - kappa1*kappa2/(kappa1+kappa2+1e-16)) {
if (A_bessel(abs(kappa1+kappa3)) >
-abs(kappa1+kappa3)*kappa2/(kappa1*kappa3 + 1e-16)) {
unimodal_y <- FALSE
phistar_eqn <- function(phi) {
kappa13 <- sqrt(kappa1^2 + kappa3^2 + 2*kappa1*kappa3*cos(phi))
-kappa1*kappa3*A_bessel(kappa13)/kappa13 - kappa2
}
find_root <- uniroot.all(phistar_eqn, c(0, 2*pi))
if (is.null(find_root)) {
method <- "naive"
} else {
phistar <- find_root[1]
}
}
}
if (method == "vmprop" & unimodal_y) {
grid_0_2pi <- seq(0, 2*pi, length.out = 100)
obj_kappa_abs <- function(kappa) {
obj_kappa_phi <- function(phi) {
cos_phi <- cos(phi)
kappa13 <- sqrt(kappa1^2 + kappa3^2 + 2*kappa1*kappa3*cos_phi)
log_I_k_13 <- log(besselI(kappa13, 0))
log_target_marginal <- -log_const_vmcos + log_2pi + log_I_k_13 + kappa2*cos_phi
log_proposal <- -log_2pi - log(besselI(kappa, 0)) + kappa*cos_phi
abs(log_target_marginal - log_proposal)
}
optimize(obj_kappa_phi, c(0, 2*pi), maximum=TRUE)$objective
}
kappa_opt <- optimize(obj_kappa_abs, c(0, max(50, kappa2*2)))$minimum
log_prop_den <- function(kappa, phi) {
cos_phi <- cos(phi)
-log_2pi - log(besselI(kappa, 0)) +
kappa*cos_phi
}
max_log_prop_den <- max(log_prop_den(kappa_opt, grid_0_2pi))
obj_kappa_phi <- function(kappa, phi) {
cos_phi <- cos(phi)
kappa13 <- sqrt(kappa1^2 + kappa3^2 + 2*kappa1*kappa3*cos_phi)
log_I_k_13 <- log(besselI(kappa13, 0))
log_target_marginal <- -log_const_vmcos + log_2pi + log_I_k_13 + kappa2*cos_phi
log_proposal <- pmax(-log_2pi - log(besselI(kappa, 0)) +
kappa*cos_phi, max_log_prop_den-10)
log_target_marginal - log_proposal
}
(logK <- max(obj_kappa_phi(kappa_opt, seq(0, 2*pi, length.out = 200))))
rcos_unimodal(n, kappa1, kappa2, kappa3, mu1, mu2,
kappa_opt, log(BESSI0_C(kappa_opt)), logK,
log_const_vmcos)
}
else if (method == "vmprop" & !unimodal_y) {
mode_1 <- prncp_reg(prncp_reg.minuspi.pi(mu2)+phistar)
mode_2 <- prncp_reg(prncp_reg.minuspi.pi(mu2)-phistar)
sin_phistar <- sin(phistar)
unifpropn <- 1e-10
vmpropn <- (1-1e-10)/2
grid_0_2pi <- seq(0, 2*pi, length.out = 100)
obj_kappa_abs <- function(kappa) {
obj_kappa_phi <- function(phi) {
cos_phi <- cos(phi-mu2)
kappa13 <- sqrt(kappa1^2 + kappa3^2 + 2*kappa1*kappa3*cos_phi)
log_I_k_13 <- log(besselI(kappa13, 0))
log_target_marginal <- -log_const_vmcos + log_2pi + log_I_k_13 + kappa2*cos_phi
log_proposal <-
-log_2pi + log(exp(log(vmpropn) - log(besselI(kappa, 0)) +
kappa*cos(phi-mode_1) +
log(1+exp(kappa*(cos(phi-mode_2)
- cos(phi-mode_1))))
) + unifpropn)
abs(log_target_marginal - log_proposal)
}
max(obj_kappa_phi(grid_0_2pi))
}
(kappa_opt <- optimize(obj_kappa_abs,
c(0, max(kappa1, kappa2,
abs(kappa3))))$minimum)
log_prop_den <- function(kappa, phi) {
-log_2pi + log(exp(log(vmpropn) - log(besselI(kappa, 0)) +
kappa*cos(phi-mode_1) +
log(1+exp(kappa*(cos(phi-mode_2) - cos(phi-mode_1)))))
+ unifpropn)
}
max_log_prop_den <- max(log_prop_den(kappa_opt, grid_0_2pi))
obj_kappa_phi <- function(kappa, phi) {
cos_phi <- cos(phi-mu2)
kappa13 <- sqrt(kappa1^2 + kappa3^2 + 2*kappa1*kappa3*cos_phi)
log_I_k_13 <- log(besselI(kappa13, 0))
log_target_marginal <- -log_const_vmcos + log_2pi + log_I_k_13 + kappa2*cos_phi
log_proposal <-
pmax(-log_2pi + log(exp(log(vmpropn) - log(besselI(kappa, 0)) +
kappa*cos(phi-mode_1) +
log(1+exp(kappa*(cos(phi-mode_2) - cos(phi-mode_1)))))
+ unifpropn), max_log_prop_den-10)
log_target_marginal - log_proposal
}
(logK <- max(obj_kappa_phi(kappa_opt, seq(0, 2*pi, length.out = 200))))
exp(logK)
rcos_bimodal(n, kappa1, kappa2, kappa3, mu1, mu2,
kappa_opt, log(BESSI0_C(kappa_opt)), logK,
log_const_vmcos, mode_1, mode_2,
vmpropn, unifpropn)
}
}
else if (method == "naive") {
opt_obj <- function(k1=1, k2=1, k3=0, mu1=0, mu2=0) {
obj <- optim(c(0,0), fn = function(x) -(k1*cos(x[1]-mu1)+k2*cos(x[2]-mu2)+k3*cos(x[1]-x[2]-mu1+mu2)),
gr = function(x) -c(-k1*sin(x[1]-mu1)-k3*sin(x[1]-x[2]-mu1+mu2),
-k2*sin(x[2]-mu2)+k3*sin(x[1]-x[2]-mu1+mu2)))
-obj$value
}
upper_bd <- opt_obj(kappa1, kappa2, kappa3, mu1, mu2)
rcos_onepar(n, kappa1, kappa2, kappa3, mu1, mu2, upper_bd)
}
} |
BICqSelect <-
function(logL, n, level=0.99, mSize=1:length(logL), mComplex=function(k) k)
{
mC <- mComplex(mSize)
P<- length(logL)
stopifnot(P>2)
stopifnot(length(unique(mSize))==P)
if (!all(mSize[2:P]-mSize[1:(P-1)]>=0) && P>1) stop("Model sizes are not ordered.")
aChosen<- qchisq(level,1)
a12<- matrix(rep(NA,P*2),ncol=2)
a12[1,]<- 2*c(max((logL[2:P]-logL[1])/(mC[2:P]-mC[1])),Inf)
a12[P,]<- 2*c(0, min((logL[1:(P-1)]-logL[P])/(mC[1:(P-1)]-mC[P])))
for (k in 2:(P-1)){
i1<-1:(k-1)
i2<-(k+1):P
a12[k,]<- 2*c(max((logL[i2]-logL[k])/(mC[i2]-mC[k])),
min((logL[i1]-logL[k])/(mC[i1]-mC[k])))
}
q12 <- 1/(1+exp(a12/2)/sqrt(n))
q12 <- q12[,2:1]
ks<- rep(NA, length(aChosen))
as<- matrix(rep(NA, 2*length(aChosen)),ncol=2)
qs<- matrix(rep(NA, 2*length(aChosen)),ncol=2)
for (i in 1:length(aChosen)){
indx<- which(a12[,1]<=aChosen[i] & a12[,2]>=aChosen[i])
ks[i]<- mSize[indx]
as[i,]<- a12[indx,]
qs[i,]<- q12[indx,]
}
kaqChosen<- data.frame(k=ks, a=as, q=qs, level=level)
aqTable<- data.frame(k=mSize, a=a12, q=q12, ms=a12[,1]<=a12[,2])
colnames(aqTable)[6]="a1<=a2"
list(kHat=kaqChosen, table=aqTable)
} |
epr<-function(age=NULL,fecund=NULL,partial=NULL,pmat=pmat,M=NULL,pF=NULL, pM=NULL,MSP=40,plus=FALSE,oldest=NULL,maxF=2,incrF=0.0001){
if(is.null(age))
stop ("age vector is missing")
if(is.null(fecund))
stop (" fecund vector is missing.")
if(is.null(partial))
stop ("partial recruitment vector is missing.")
if(is.null(pmat))
stop ("pmat vector is missing.")
if(is.null(M))
stop ("M value or vector is missing")
if(is.null(pF))
stop ("pF value is missing.")
if(is.null(pM))
stop ("pM value is missing.")
if(plus==TRUE & is.null(oldest)) stop("oldest must be specified for plus group calculation.")
if(any(length(age)!=c(length(age),length(fecund),length(partial),length(pmat))))
stop("Length of vectors unequal")
if(length(M)==1) M<-rep(M,length(age))
data<-as.data.frame(cbind(age,fecund,partial,M,pmat,pF,pM))
SPR<-as.data.frame(cbind(rep(NA,ceiling(maxF/incrF)+1),
rep(NA,ceiling(maxF/incrF)+1)))
names(SPR)<-c("F","SPR")
if(plus==TRUE){
len<-oldest-min(data$age)+1
if(oldest>max(data$age)){
pdata<-data[rep(length(data$age),times=oldest-data$age[length(data$age)]), ]
pdata$age<-seq(max(data$age)+1,oldest,1)
data<-rbind(data,pdata)}
}
if(plus==FALSE) len<-max(data$age)-min(data$age)+1
F<-0
for (i in 1:length(SPR$F))
{
data$SB<-exp(-(data$partial*data$pF*F+data$pM*data$M))
data$S<-cumprod(exp(-(data$partial*F+data$M)))
data$psb[1]<-1
for(y in 2:len)
{
data$psb[y]<-data$S[y-1]
}
data$SPR<-data$psb*data$SB*data$fecund*data$pmat
SPR$SPR[i]<-sum(data$SPR)
SPR$F[i]<-F
F<-F+incrF
}
SPR$PSPR<-SPR$SPR/SPR$SPR[1]*100
sss<-NULL
getF<-function(x){
data$SB<-exp(-(data$partial*data$pF*x+data$pM*data$M))
data$S<-cumprod(exp(-(data$partial*x+data$M)))
data$psb[1]<-1
for(y in 2:len)
{
data$psb[y]<-data$S[y-1]
}
data$SPR<-data$psb*data$SB*data$fecund*data$pmat
sss<<-sum(data$SPR)
return(((sum(data$SPR)/SPR$SPR[1]*100)-MSP)^2)
}
Fsp<-optimize(getF,c(0,maxF),tol=0.0000001)[1]
ans<-NULL
ans<-matrix(NA,1L,2L)
ans<-rbind(cbind(Fsp,sss))
EPR<-SPR
names(EPR)<-c("F","EPR","PEPR")
dimnames(ans)<-list(c(paste("F at ",MSP,"%MSP",sep="")),c("F","Eggs_Per_Recruit"))
outpt<-list(ans,EPR);names(outpt)<-c("Reference_Point","F_vs_EPR")
return(outpt)
}
|
hergm.wrapper <- function(seed, hergm_list)
{
if (is.null(seed) == FALSE) set.seed(seed)
if (hergm_list$simulate == TRUE)
{
sample <- .C("Simulation",
as.integer(hergm_list$dependence),
as.integer(hergm_list$hierarchical),
as.double(hergm_list$scaling),
as.integer(hergm_list$d),
as.integer(hergm_list$d1),
as.integer(hergm_list$d2),
as.integer(hergm_list$structural),
as.integer(hergm_list$min_size),
as.integer(hergm_list$max_number),
as.integer(hergm_list$null$alpha),
as.integer(hergm_list$null$eta),
as.integer(hergm_list$null$indicator),
as.double(hergm_list$alpha),
as.double(hergm_list$alpha_shape),
as.double(hergm_list$alpha_rate),
as.double(hergm_list$eta_mean1),
as.double(hergm_list$eta_mean2),
as.double(hergm_list$cf1),
as.double(hergm_list$cf2),
as.double(hergm_list$p1),
as.double(hergm_list$p2),
as.double(hergm_list$eta_mean_mean),
as.double(hergm_list$eta_mean_precision),
as.double(hergm_list$eta_precision_shape),
as.double(hergm_list$eta_precision_rate),
as.double(hergm_list$eta),
as.integer(hergm_list$indicator),
as.integer(hergm_list$Clist$heads),
as.integer(hergm_list$Clist$tails),
as.integer(hergm_list$Clist$nedges),
as.integer(hergm_list$MCMCparams$MCMC.init.maxedges),
as.integer(hergm_list$Clist$n),
as.integer(hergm_list$Clist$dir),
as.integer(hergm_list$Clist$bipartite),
as.integer(hergm_list$Clist$nterms),
as.character(hergm_list$Clist$fnamestring),
as.character(hergm_list$Clist$snamestring),
as.character(hergm_list$MHproposal$name),
as.character(hergm_list$MHproposal$pkgname),
as.double(hergm_list$Clist$inputs),
as.double(hergm_list$Clist$inputs),
as.double(hergm_list$theta),
as.integer(hergm_list$MCMCparams$samplesize),
sample = as.double(t(hergm_list$MCMCparams$stats)),
as.integer(hergm_list$MCMCparams$burnin),
as.integer(hergm_list$MCMCparams$interval),
as.integer(hergm_list$verbose),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$attribs),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$maxout),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$maxin),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$minout),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$minin),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$condAllDegExact),
as.integer(length(hergm_list$MHproposal$arguments$constraints$bd$attribs)),
as.integer(hergm_list$maxedges),
as.integer(hergm_list$max_iteration),
as.integer(hergm_list$between),
as.double(hergm_list$mean_between),
as.integer(hergm_list$predictions),
mcmc = as.double(hergm_list$mcmc),
sample_heads = as.integer(hergm_list$sample_heads),
sample_tails = as.integer(hergm_list$sample_tails),
as.integer(hergm_list$prior_assumptions),
status = integer(1),
PACKAGE="hergm")
}
else
{
sample <- .C("Inference",
as.integer(hergm_list$model_type),
as.integer(hergm_list$dependence),
as.integer(hergm_list$hierarchical),
as.double(hergm_list$scaling),
as.integer(hergm_list$d),
as.integer(hergm_list$d1),
as.integer(hergm_list$d2),
as.integer(hergm_list$structural),
as.integer(hergm_list$min_size),
as.integer(hergm_list$max_number),
as.double(hergm_list$alpha),
as.double(hergm_list$alpha_shape),
as.double(hergm_list$alpha_rate),
as.double(hergm_list$eta_mean1),
as.double(hergm_list$eta_mean2),
as.double(hergm_list$cf1),
as.double(hergm_list$cf2),
as.double(hergm_list$p1),
as.double(hergm_list$p2),
as.double(hergm_list$eta_mean_mean),
as.double(hergm_list$eta_mean_precision),
as.double(hergm_list$eta_precision_shape),
as.double(hergm_list$eta_precision_rate),
as.integer(hergm_list$indicator),
as.integer(hergm_list$Clist$heads),
as.integer(hergm_list$Clist$tails),
as.integer(hergm_list$Clist$nedges),
as.integer(hergm_list$MCMCparams$MCMC.init.maxedges),
as.integer(hergm_list$Clist$n),
as.integer(hergm_list$Clist$dir),
as.integer(hergm_list$Clist$bipartite),
as.integer(hergm_list$Clist$nterms),
as.character(hergm_list$Clist$fnamestring),
as.character(hergm_list$Clist$snamestring),
as.character(hergm_list$MHproposal$name),
as.character(hergm_list$MHproposal$pkgname),
as.double(hergm_list$Clist$inputs),
as.double(hergm_list$Clist$inputs),
as.double(hergm_list$theta),
as.integer(hergm_list$MCMCparams$samplesize),
sample = as.double(t(hergm_list$MCMCparams$stats)),
as.integer(hergm_list$MCMCparams$burnin),
as.integer(hergm_list$MCMCparams$interval),
newnwheads = integer(hergm_list$maxedges),
newnwtails = integer(hergm_list$maxedges),
as.integer(hergm_list$verbose),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$attribs),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$maxout),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$maxin),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$minout),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$minin),
as.integer(hergm_list$MHproposal$arguments$constraints$bd$condAllDegExact),
as.integer(length(hergm_list$MHproposal$arguments$constraints$bd$attribs)),
as.integer(hergm_list$maxedges),
as.integer(hergm_list$max_iteration),
as.integer(hergm_list$between),
as.integer(hergm_list$predictions),
mcmc = as.double(hergm_list$mcmc),
as.double(hergm_list$scalefactor),
mh_accept = as.double(hergm_list$mh_accept),
as.double(hergm_list$q_i),
as.integer(hergm_list$parallel),
as.double(hergm_list$temperature),
as.integer(hergm_list$prior_assumptions),
status = integer(1),
PACKAGE="hergm")
}
sample
} |
context("pimage tests")
test <- FALSE
if (test) {
setwd("~")
pdf("test-pimage.pdf")
data(narccap)
curpar <- par(no.readonly = TRUE)
pimage(tasmax[, , 1], main = "no axis labels")
par(curpar)
pimage(z = tasmax[, , 1], main = "no axis labels")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "none", main = "no legend, lon/lat labels")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], main = "hor legend, lon/lat labels")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "vertical", main = "vert legend, lon/lat labels")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], main = "custom labels", xlab = "my xlab",
ylab = "my ylab")
data(worldMapEnv, package = "maps")
worldpoly <- maps::map("world", plot = FALSE)
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "none", lines = worldpoly,
main = "with world poly")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "none", proj = "mercator",
main = "with mercator proj")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "none", proj = "bonne",
parameters = 45, main = "with bonne projection and lines")
plines(worldpoly, proj = "bonne")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "none", proj = "bonne",
parameters = 45, main = "with bonne projection no grid", paxes.args = list(grid = FALSE))
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "none", proj = "bonne",
parameters = 45, main = "with bonne projection dashed grey grid",
paxes.args = list(col = "grey", lty = 2))
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "none", proj = "mercator",
main = "bonne projection, thick grey lines", paxes.args = list(grid = FALSE),
lines = worldpoly, lines.args = list(col = "grey", lwd = 3))
par(curpar)
data(us.cities, package = "maps")
usm <- head(us.cities)
cityxy <- list(x = usm$long, y = usm$lat)
pimage(lon, lat, z = tasmax[, , 1], legend = "none", proj = "mercator",
main = "mercator projection, solid orange points", paxes.args = list(grid = FALSE),
points = cityxy, points.args = list(col = "orange", pch = 20))
par(curpar)
data(us.cities, package = "maps")
usm <- head(us.cities)
cityxy <- list(x = usm$long, y = usm$lat)
pimage(lon, lat, z = tasmax[, , 1], legend = "none", proj = "mercator",
main = "mercator projection, orange numbered text", paxes.args = list(grid = FALSE),
text = cityxy, text.args = list(col = "orange"))
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "vertical", lratio = 0.5,
main = "wide vertical bar")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "vertical", lratio = 0.5,
main = "blue legend text", legend.axis.args = list(col = "blue",
col.axis = "blue", at = seq(280, 320, 20)))
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], legend = "vertical", proj = "bonne",
parameters = 45, xlim = c(-130, -60), ylim = c(23, 50))
plines(worldpoly, proj = "bonne")
title("USA")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], map = "world")
title("narccap with worldpoly")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], map = "county")
title("narccap with counties")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], map = "usa")
title("narccap with usa border")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], map = "state")
title("narccap with state borders")
par(curpar)
pimage(lon + 360, lat, z = tasmax[, , 1], map = "world2")
title("narccap with world2 borders")
par(curpar)
pimage(lon + 90, lat, z = tasmax[, , 1], map = "france")
title("narccap with france borders")
par(curpar)
pimage(lon + 300, lat - 80, z = tasmax[, , 1], map = "nz")
title("narccap with new zealand borders")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], map = "lakes")
title("narccap with lakes")
par(curpar)
pimage(lon + 100, lat, z = tasmax[, , 1], map = "italy")
title("narccap with italy")
par(curpar)
pimage(lon, lat, z = tasmax[, , 1], axis.args = list(col.axis = "orange",
cex.axis = 0.5))
title("orange, small axis")
reset.par()
pimage(lon, lat, z = tasmax[, , 1], proj = "mercator", axis.args = list(xat = c(-160,
-110, -80, -60, -40)))
title("custom spaced x axis")
reset.par()
pimage(lon, lat, z = tasmax[, , 1], proj = "mercator", axis.args = list(yat = c(20,
40, 45, 70)), legend.axis.args = list(col = "blue", col.axis = "blue",
at = seq(280, 320, 20)))
title("custom spaced y axis, legend axis")
dev.off()
} |
get.max_missrate <- function(preds, labels) {
DT <- data.table(y_true = labels, y_prob = preds, key = "y_prob")
cleaner <- !duplicated(DT[, "y_prob"], fromLast = TRUE)
nump <- sum(labels)
numn <- length(labels) - nump
DT[, fn_v := numn - as.numeric(cumsum(y_true == 0))]
DT[, tp_v := nump - cumsum(y_true == 1)]
DT <- DT[cleaner, ]
DT[, miss := fn_v / (tp_v + fn_v)]
best_row <- which.min(DT$miss)
if (length(best_row) > 0) {
return(c(DT$miss[best_row[1]], DT$y_prob[best_row[1]]))
} else {
return(c(-1, -1))
}
} |
classifyFun <- function(Data,classCol,selectedCols,cvType,ntrainTestFolds,nTrainFolds,modelTrainFolds,nTuneFolds,tuneFolds,foldSep,cvFraction,
ranges=NULL,tune=FALSE,cost=1,gamma=0.5,classifierName='svm',genclassifier,silent=FALSE,extendedResults = FALSE,
SetSeed=TRUE,NewData=NULL,...){
if(missing(cvType)){
if(!silent) cat("cvType was not specified, \n Using default k-folds Cross-validation \n")
cvType <- "folds"
}
if(!(cvType %in% c("holdout","folds","LOSO","LOTO"))) stop(cat("\n cvType is not one of holdout,folds or LOSO. You provided",cvType))
if(!silent) cat("\nPerforming Classification Analysis \n\n")
permittedDataClass <- c("tbl_df","matrix")
if(any(permittedDataClass %in% class(Data))){
warning(cat("the data entered is of the class ",class(Data),". Coersing it to be a dataframe. Check results"))
Data <- as.data.frame(Data)
}
if(is.character(classCol)){
predictorColNames <- classCol
classCol <- grep(predictorColNames,names(Data))
}else predictorColNames <- names(Data)[classCol]
if(missing(selectedCols)) selectedCols <- 1:length(names(Data))
ifelse(is.character(selectedCols),selectedColNames <- selectedCols,selectedColNames <- names(Data)[selectedCols])
if(!(predictorColNames %in% selectedColNames)) stop("\n Predictor Column name not present in selected column name list")
featureColNames <- selectedColNames[-match(names(Data)[classCol],selectedColNames)]
Data[,classCol] <- factor(Data[,classCol])
if(sum(is.na(Data[,predictorColNames]))>0) Data <- Data[!is.na(Data[,predictorColNames]),]
if(SetSeed) set.seed(111)
switch(cvType,
folds = {
if(!silent) cat("\nPerforming k-fold Cross-validation")
if(missing(nTrainFolds)){
if(!silent) cat(paste0("\nnTrainFolds was not specified, \n Using default value of 10 fold cross-validation (nTrainFolds = 10)\n"))
nTrainFolds <- 10
}
if(missing(ntrainTestFolds)){
if(!silent) cat(paste0("\nntrainTestFolds was not specified, \n Using default value of 10 (ntrainTestFolds = 10)\n"))
ntrainTestFolds <- 10
}
if(missing(modelTrainFolds)){
if(!silent) cat(paste0("\nmodelTrainFolds were not specified, \n Using default value of 1:",as.character(ntrainTestFolds-1),"\n"))
modelTrainFolds <- 1:(ntrainTestFolds-1)
}
if(missing(genclassifier))
if(missing(genclassifier)){
if(!silent) cat("\ngenclassifier was not specified,\n Using default value of Classifier.svm.Folds (genclassifier = Classifier.svm.Folds)\n")
genclassifier <- Classifier.svm.Folds
}
featureColNames <- selectedColNames[-grep(names(Data)[classCol],selectedColNames)]
if(tune) {
if(!(classifierName %in% c('svm','knn3'))){
stop(paste0("Tuning is currently implemented for only svm and knn3. You input the classifiername as ",classifierName))
}
if(missing(nTuneFolds)){
if(!silent) cat(paste0("\nnTuneFolds was not specified, Using default value of 3 (nTuneFolds = 3)"))
nTuneFolds <- 3
}
if(missing(tuneFolds)){
if(!silent) cat(paste0("\ntuneFold was not specified, Using default value of 1 (tuneFolds = 1)\n\n"))
tuneFolds <- 1
}
trainIndexOverall <- createFolds(Data[,classCol],list = FALSE,k = nTuneFolds)
tuneTrainData <- Data[trainIndexOverall %in% tuneFolds,]
ModelData <- Data[!(trainIndexOverall %in% tuneFolds),]
obj <- getTunedParam(tuneTrainData,classCol,classifierName,featureColNames,ranges,silent)["best.parameters"]
} else{
ModelData <- Data
obj <- data.frame(gamma=gamma,cost=cost)
}
trainTestIndex <- createFolds(ModelData[,classCol],list = FALSE,k = ntrainTestFolds)
ModelTrainData <- ModelData[trainTestIndex %in% modelTrainFolds,]
ModelTestData <- ModelData[!(trainTestIndex %in% modelTrainFolds),]
acc <- rep(NA,nTrainFolds)
accTestRun <- rep(NA,nTrainFolds)
trainIndexModel <- createFolds(ModelTrainData[,predictorColNames],list = FALSE,k = nTrainFolds)
if(!silent){
print('Begining k-fold Classification')
}
classificationResults <- list()
ConfMatrix <- list()
for (i in 1:nTrainFolds){
trainDataFold <- ModelTrainData[!trainIndexModel==i,]
testDataFold <- ModelTrainData[trainIndexModel==i,]
classificationResults[[i]] <- do.call(genclassifier,c(list(trainData=trainDataFold,testData=testDataFold,ModelTestData=ModelTestData,predictorColNames=predictorColNames,
featureColNames=featureColNames,expand.grid(obj),...)))
acc[i] = classificationResults[[i]][["acc"]]
accTestRun[i] = classificationResults[[i]][["accTest"]]
ConfMatrix[[i]] <- classificationResults[[i]][["ConfMatrix"]]
}
accTest <- mean(accTestRun,na.rm=T)
if(!silent){
print(paste("Mean CV Accuracy",signif(mean(acc),2)))
print(paste("Mean Test Accuracy",signif(mean(accTest),2)))
cat("k-fold classification Analysis:",'\nntrainTestFolds :', ntrainTestFolds,'\nmodelTrainFolds',modelTrainFolds,
"\nnTrainFolds:",nTrainFolds,"\nTest Accuracy",signif(accTest,2))
cat("\n*Legend:\nntrainTestFolds = No. of folds for training and testing dataset",
"\nmodelTrainFolds = Specific folds from the above nTrainFolds to use for training",
"\nnTrainFolds = No. of folds in which to further divide Training dataset",
"\nTest Accuracy = Mean accuracy from the Testing dataset\n")
}
},
LOSO = {
if(!silent) cat("\nPerforming Leave-one-subject-out Cross-validation \n\n")
if(missing(foldSep)) stop("No foldSep provided")
if(tune) warning("\n\n No tuning performed. Tuning is implemented for only k-fold analsyis (for now) \n\n")
if(missing(genclassifier)){
if(!silent) cat("\ngenclassifier was not specified, \n Using default value of Classifier.svm (genclassifier = Classifier.svm)\n")
genclassifier <- Classifier.svm
}
featureColNames <- selectedColNames[!selectedColNames %in% c(names(Data)[classCol],names(Data[foldSep]))]
Subs <- unique(Data[,foldSep])
obj <- data.frame(gamma=gamma,cost=cost)
accTestRun <- rep(NA,length(Subs))
classificationResults <- list()
ConfMatrix <- list()
for (i in 1:length(Subs)){
trainDataSub <- Data[Data[,foldSep]!=Subs[i],]
testDataSub <- Data[Data[,foldSep]==Subs[i],]
classificationResults[[i]] <- do.call(genclassifier,c(list(trainData=trainDataSub,testData=testDataSub,predictorColNames=predictorColNames,
featureColNames=featureColNames,expand.grid(obj),...)))
accTestRun[i] <- classificationResults[[i]][["accTest"]]
ConfMatrix[[i]] <- classificationResults[[i]][["ConfMatrix"]]
}
accTest <- mean(accTestRun,na.rm=TRUE)
if(!silent){
print(paste("Mean Test Leave-one-Subject-out Accuracy is ",signif(accTest,2)))
cat("leave-one-subject-out classification Analysis:",'\nnSubs :', length(Subs),"\nTest Accuracy",signif(accTest,2))
cat("\n*Legend:\nnSubs = No. of Subjects in the data",
"\nTest Accuracy = Mean accuracy from the Testing dataset\n")
}
},
holdout = {
if(!silent) cat("\nPerforming holdout Cross-validation")
if(tune) warning("\n\n No tuning performed. Tuning is implemented for only k-fold analsyis (for now) \n\n")
if(missing(genclassifier)){
if(!silent) cat("\ngenclassifier was not specified, \n Using default value of Classifier.svm (genclassifier = Classifier.svm)\n")
genclassifier <- Classifier.svm
}
if(missing(cvFraction)){
if(!silent) cat("\ncvFraction was not specified, \n Using default value of 0.8 (cvFraction = 0.8)\n\n")
cvFraction = 0.8
}
featureColNames <- selectedColNames[-grep(names(Data)[classCol],selectedColNames)]
index <- createDataPartition(Data[,classCol],p=cvFraction,times=1)
trainData <- Data[1:nrow(Data) %in% index$Resample1,]
testData <- Data[!(1:nrow(Data) %in% index$Resample1),]
if(!silent) cat("Proportion of Test/Train Data was : ",nrow(testData)/nrow(trainData),"\n")
obj <- data.frame(gamma=gamma,cost=cost)
classificationResults <- do.call(genclassifier,c(list(trainData=trainData,testData=testData,predictorColNames=predictorColNames,
featureColNames=featureColNames,expand.grid(obj),...)))
accTest <- classificationResults[["accTest"]]
ConfMatrix <- classificationResults[["ConfMatrix"]]
accTestRun <- NULL
if(!silent){
print(paste("Test holdout Accuracy is ",signif(accTest,2)))
cat("holdout classification Analysis:",'\ncvFraction :', cvFraction,"\nTest Accuracy",signif(mean(accTest),2))
cat("\n*Legend:\ncvFraction = Fraction of data to keep for training data",
"\nTest Accuracy = Accuracy from the Testing dataset\n")
}
},
LOTO = {
if(!silent) cat("\nPerforming Leave-one-Trial-out Cross-validation \n (Might take some time depending upon the size of dataset) \n")
if(missing(genclassifier)){
if(!silent) cat("\ngenclassifier was not specified,\n Using default value of Classifier.svm.Folds (genclassifier = Classifier.svm)\n")
genclassifier <- Classifier.svm
}
featureColNames <- selectedColNames[-grep(names(Data)[classCol],selectedColNames)]
index <- createFolds(Data[,classCol],k=nrow(Data),list=FALSE)
obj <- data.frame(gamma=gamma,cost=cost)
accTestRun <- vector()
classificationResults <- list()
ConfMatrix <- list()
for(i in seq_along(index)){
DataTrain <- Data[-i,]
DataTest <- Data[i,]
classificationResults[[i]] <- do.call(genclassifier,c(list(trainData=DataTrain,testData=DataTest,predictorColNames=predictorColNames,
featureColNames=featureColNames,expand.grid(obj),...)))
accTestRun[i] <- classificationResults[[i]][["accTest"]]
ConfMatrix[[i]] <- classificationResults[[i]][["ConfMatrix"]]
}
accTest <- mean(accTestRun,na.rm = TRUE)
if(!silent){
print(paste("Test LOTO classification Accuracy is ",signif(accTest,2)))
cat("leave-one-Trial-out classification Analysis:","\nTest Accuracy",signif(accTest,2))
cat("\n*Legend:\nTest Accuracy = Mean accuracy from the Testing dataset\n")
}
}
)
ConfusionMatrixResults <- overallConfusionMetrics(ConfMatrix)
if(!is.null(NewData)){
newDataprediction <- predictNewData(classificationResults$model,NewData,type='class')
classificationResults <- list(classificationResults=classificationResults,newDataprediction=newDataprediction)
}
if(extendedResults){
Results <- list(classificationResults = classificationResults,accTest = accTest,ConfMatrix=ConfMatrix,ConfusionMatrixResults=ConfusionMatrixResults,accTestRun = accTestRun)
return(Results)
}else return(accTest)
}
getTunedParam <- function(tuneTrainData,classCol,classifierName,featureColNames,ranges=NULL,silent=FALSE){
classifierFun <- get(classifierName)
if(missing(featureColNames)) featureColNames <- 1:length(names(tuneTrainData))
if(!silent) print('Begining Tuning Classifier')
if(classifierName=="svm"){
if (is.null(ranges)) ranges = list(gamma = 2^(-1:1), cost = 2^(2:4))
obj <- tune(classifierFun, train.y = tuneTrainData[,classCol],train.x = tuneTrainData[,featureColNames],
ranges = ranges,tunecontrol = tune.control(sampling = "fix"))
} else if(classifierName=="knn3") {
if (is.null(ranges)) ranges = 1:10
obj <- tune.knn(y = tuneTrainData[,classCol],x = tuneTrainData[,featureColNames],
k = ranges,tunecontrol = tune.control(sampling = "fix"))
}
if(!silent) print(summary(obj))
if(!silent) plot(obj)
return(obj)
}
Classifier.svm.Folds <- function(trainData,testData,ModelTestData,predictorColNames,featureColNames,...){
model <- do.call('svm',c(list(y=trainData[,predictorColNames],x=trainData[,featureColNames]),...))
pred <- predict(model, testData[,featureColNames])
acc <- sum(1 * (pred==testData[,predictorColNames]))/length(pred)
predTest <- predict(model, ModelTestData[,featureColNames])
accTest <- sum(1 * (predTest==ModelTestData[,predictorColNames]))/length(predTest)
ConfMatrix <- confusionMatrix(ModelTestData[,predictorColNames],predTest)
accList <- list(acc=acc,accTest=accTest,ConfMatrix=ConfMatrix)
return(accList)
}
Classifier.knn.Folds <- function(trainData,testData,ModelTestData,predictorColNames,featureColNames,obj,...){
model <- do.call("knn3",c(list(y=trainData[,predictorColNames],x=trainData[,featureColNames]),expand.grid(obj$best.parameters),...))
pred <- predict(model, testData[,featureColNames],type="class")
acc <- sum(1 * (pred==testData[,predictorColNames]))/length(pred)
predTest <- predict(model, ModelTestData[,featureColNames],type="class")
accTest <- sum(1 * (predTest==ModelTestData[,predictorColNames]))/length(predTest)
ConfMatrix <- confusionMatrix(ModelTestData[,predictorColNames],predTest)
accList <- list(acc=acc,accTest=accTest,ConfMatrix=ConfMatrix)
return(accList)
}
Classifier.svm <- function(trainData,testData,predictorColNames,featureColNames,...){
model <- do.call('svm',c(list(y=trainData[,predictorColNames],x=trainData[,featureColNames]),...))
pred <- predict(model, testData[,featureColNames])
accTest <- sum(1 * (pred==testData[,predictorColNames]))/length(pred)
ConfMatrix <- confusionMatrix(testData[,predictorColNames],pred)
accList <- list(accTest=accTest,ConfMatrix=ConfMatrix,model=model)
return(accList)
}
Classifier.knn <- function(trainData,testData,predictorColNames,featureColNames,obj,...){
model <- do.call("knn3",c(list(y=trainData[,predictorColNames],x=trainData[,featureColNames]),expand.grid(obj$best.parameters),...))
pred <- predict(model, testData[,featureColNames],type="class")
accTest <- sum(1 * (pred==testData[,predictorColNames]))/length(pred)
ConfMatrix <- confusionMatrix(testData[,predictorColNames],pred)
accList <- list(accTest=accTest,ConfMatrix=ConfMatrix,model=model)
return(accList)
} |
extract_alias <- function(expr) {
if (!identical(typeof(expr), "character") || !identical(length(expr), 1L)) {
stop("Unexpected input to extract_alias()", call. = FALSE)
}
expr <- trimws(expr)
bytes_in_chars <- nchar(strsplit(expr, "")[[1]], type = "bytes")
rc <- rawConnection(raw(0L), "r+")
on.exit(close(rc))
writeChar(expr, rc)
len <- seek(rc, 0L) - 1L
column_alias <- NULL
expr_without_alias <- NULL
found_as_before_alias <- FALSE
look_for_char_before_alias <- FALSE
look_for_as_keyword <- FALSE
quoted_string_at_end <- FALSE
quote_at_end <- FALSE
possible_word_at_end <- FALSE
was_in_quotes <- FALSE
in_quotes <- FALSE
step_number <- 0
step_positions <- c(rev(cumsum(bytes_in_chars)),0)[-1]
advance_positions <- 1
char_is_quote_escape <- FALSE
while(TRUE) {
if (advance_positions > 0) {
if (step_number + advance_positions > length(step_positions)) {
break;
}
step_number <- step_number + advance_positions
pos <- step_positions[step_number]
}
advance_positions <- 1
seek(rc, pos)
char <- readChar(rc, 1L)
if (char %in% quote_chars) {
if (pos == step_positions[1]) {
quote_at_end <- TRUE
}
if (!in_quotes) {
in_quotes <- TRUE
quo_char <- char
} else if (char == quo_char && !char_is_quote_escape) {
if (pos == 0) {
in_quotes <- FALSE
} else {
seek(rc, -2L, "current")
esc_quo <- c(quo_char, "\\")
if (readChar(rc, 1L, useBytes = TRUE) %in% esc_quo) {
char_is_quote_escape <- TRUE
} else {
char_is_quote_escape <- FALSE
in_quotes <- FALSE
rm(quo_char)
}
seek(rc, 1L, "current")
}
}
}
if (look_for_char_before_alias) {
if (quoted_string_at_end && !found_as_before_alias) {
seek(rc, 0)
expr_without_alias <- trimws(readChar(rc, pos + 1, useBytes = TRUE))
} else if (is_non_word_character(char, useBytes = TRUE)) {
seek(rc, 0)
expr_without_alias <- trimws(readChar(rc, pos + 1, useBytes = TRUE))
} else if (found_as_before_alias) {
seek(rc, 0)
expr_without_alias <- trimws(readChar(rc, pos + 3, useBytes = TRUE))
}
break;
}
if (
!in_quotes && !char %in% quote_chars &&
!possible_word_at_end &&
!is_whitespace_character(char) &&
!is_word_character(char)) {
break;
}
if (look_for_as_keyword) {
advance_positions <- 0
prev_char <- char
if (identical(prev_char, " ")) {
seek(rc, -2L, "current")
prev_char <- readChar(rc, 1L, useBytes = TRUE)
advance_positions <- 1
}
if (prev_char %in% c("s","S")) {
seek(rc, -2L, "current")
prev_char <- readChar(rc, 1L, useBytes = TRUE)
if (prev_char %in% c("a","A")) {
found_as_before_alias <- TRUE
advance_positions <- advance_positions + 2
} else {
advance_positions <- 0
}
} else {
advance_positions <- 0
}
look_for_as_keyword <- FALSE
if (!identical(char, ".")) {
look_for_char_before_alias <- TRUE
}
}
if (quote_at_end && was_in_quotes && !in_quotes) {
quoted_string_at_end <- TRUE
look_for_as_keyword <- TRUE
column_alias <- readChar(rc, len - pos - 2, useBytes = TRUE)
}
if (possible_word_at_end && is_non_word_character(char, useBytes = TRUE)) {
next_char <- readChar(rc, 1L)
if (is_word_start_character(next_char) && !identical(next_char, ".")) {
seek(rc, -1 * nchar(next_char, type = "bytes"), "current")
column_alias <- readChar(rc, len - pos - 1L, useBytes = TRUE)
if (char == " ") {
look_for_as_keyword <- TRUE
} else {
look_for_char_before_alias <- TRUE
}
}
advance_positions <- 0
possible_word_at_end <- FALSE
}
if (pos == step_positions[1] && is_word_character(char)) {
possible_word_at_end <- TRUE
}
was_in_quotes <- in_quotes
}
if (is.null(column_alias) || is.null(expr_without_alias)) {
expr
} else if (ends_with_operator_expecting_right_operand(expr_without_alias)) {
expr
} else if (tolower(column_alias) %in% sql_reserved_words && !quoted_string_at_end) {
expr
} else {
names(expr_without_alias) <- column_alias
expr_without_alias
}
} |
library(testthat)
escapeString <- function(s) {
t <- gsub("(\\\\)", "\\\\\\\\", s)
t <- gsub("(\n)", "\\\\n", t)
t <- gsub("(\r)", "\\\\r", t)
t <- gsub("(\")", "\\\\\"", t)
return(t)
}
prepStr <- function(s) {
t <- escapeString(s)
u <- eval(parse(text=paste0("\"", t, "\"")))
if(s!=u) stop("Unable to escape string!")
t <- paste0("\thtml <- \"", t, "\"")
utils::writeClipboard(t)
return(invisible())
}
evaluationMode <- "sequential"
processingLibrary <- "dplyr"
description <- "test: sequential dplyr"
countFunction <- "n()"
isDevelopmentVersion <- (length(strsplit(packageDescription("pivottabler")$Version, "\\.")[[1]]) > 3)
testScenarios <- function(description="test", releaseEvaluationMode="batch", releaseProcessingLibrary="dplyr", runAllForReleaseVersion=FALSE) {
isDevelopmentVersion <- (length(strsplit(packageDescription("pivottabler")$Version, "\\.")[[1]]) > 3)
if(isDevelopmentVersion||runAllForReleaseVersion) {
evaluationModes <- c("sequential", "batch")
processingLibraries <- c("dplyr", "data.table")
}
else {
evaluationModes <- releaseEvaluationMode
processingLibraries <- releaseProcessingLibrary
}
testCount <- length(evaluationModes)*length(processingLibraries)
c1 <- character(testCount)
c2 <- character(testCount)
c3 <- character(testCount)
c4 <- character(testCount)
testCount <- 0
for(evaluationMode in evaluationModes)
for(processingLibrary in processingLibraries) {
testCount <- testCount + 1
c1[testCount] <- evaluationMode
c2[testCount] <- processingLibrary
c3[testCount] <- paste0(description, ": ", evaluationMode, " ", processingLibrary)
c4[testCount] <- ifelse(processingLibrary=="data.table", ".N", "n()")
}
df <- data.frame(evaluationMode=c1, processingLibrary=c2, description=c3, countFunction=c4, stringsAsFactors=FALSE)
return(df)
}
library(dplyr)
library(lubridate)
library(pivottabler)
trains <- mutate(bhmtrains,
GbttDate=if_else(is.na(GbttArrival), GbttDeparture, GbttArrival),
GbttMonth=make_date(year=year(GbttDate), month=month(GbttDate), day=1))
trains <- filter(trains, GbttMonth>=make_date(year=2017, month=1, day=1))
context("ROW GROUP HEADER BASIC LAYOUT TESTS")
scenarios <- testScenarios("Row group header basic layout test: One group only")
for(i in 1:nrow(scenarios)) {
if(!isDevelopmentVersion) break
evaluationMode <- scenarios$evaluationMode[i]
processingLibrary <- scenarios$processingLibrary[i]
description <- scenarios$description[i]
countFunction <- scenarios$countFunction[i]
test_that(description, {
library(dplyr)
library(lubridate)
library(pivottabler)
pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode)
pt$addData(trains)
pt$addRowDataGroups("TOC", header="Train Company", addTotal=FALSE)
pt$theme <- getStandardTableTheme(pt)
pt$evaluatePivot()
html <- "<table class=\"Table\">\n <tr>\n <th class=\"LeftColumnHeader\">Train Company</th>\n <th class=\"CentreColumnHeader\"> </th>\n </tr>\n <tr>\n <th class=\"LeftCell\">Arriva Trains Wales</th>\n <td class=\"RightCell\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\">CrossCountry</th>\n <td class=\"RightCell\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\">London Midland</th>\n <td class=\"RightCell\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Virgin Trains</th>\n <td class=\"RightCell\"></td>\n </tr>\n</table>"
expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 0)
expect_identical(as.character(pt$getHtml(showRowGroupHeaders=TRUE)), html)
})
}
scenarios <- testScenarios("Row group header basic layout test: Two row groups only")
for(i in 1:nrow(scenarios)) {
if(!isDevelopmentVersion) break
evaluationMode <- scenarios$evaluationMode[i]
processingLibrary <- scenarios$processingLibrary[i]
description <- scenarios$description[i]
countFunction <- scenarios$countFunction[i]
test_that(description, {
library(dplyr)
library(lubridate)
library(pivottabler)
pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(noDataGroupNBSP=TRUE))
pt$addData(trains)
pt$addRowDataGroups("TOC", header="Train Company", addTotal=FALSE)
pt$addRowDataGroups("TrainCategory", header="Train Category", addTotal=FALSE)
pt$theme <- getStandardTableTheme(pt)
pt$evaluatePivot()
html <- "<table class=\"Table\">\n <tr>\n <th class=\"LeftColumnHeader\">Train Company</th>\n <th class=\"LeftColumnHeader\">Train Category</th>\n <th class=\"CentreColumnHeader\"> </th>\n </tr>\n <tr>\n <th class=\"LeftCell\" rowspan=\"2\">Arriva Trains Wales</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Ordinary Passenger</th>\n <td class=\"RightCell\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\" rowspan=\"2\">CrossCountry</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Ordinary Passenger</th>\n <td class=\"RightCell\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\" rowspan=\"2\">London Midland</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Ordinary Passenger</th>\n <td class=\"RightCell\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Virgin Trains</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\"></td>\n </tr>\n</table>"
expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 0)
expect_identical(as.character(pt$getHtml(showRowGroupHeaders=TRUE)), html)
})
}
scenarios <- testScenarios("Row group header basic layout test: One row group and calculation")
for(i in 1:nrow(scenarios)) {
if(!isDevelopmentVersion) break
evaluationMode <- scenarios$evaluationMode[i]
processingLibrary <- scenarios$processingLibrary[i]
description <- scenarios$description[i]
countFunction <- scenarios$countFunction[i]
test_that(description, {
library(dplyr)
library(lubridate)
library(pivottabler)
pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode)
pt$addData(trains)
pt$addRowDataGroups("TOC", header="Train Company")
pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction)
pt$theme <- getStandardTableTheme(pt)
pt$evaluatePivot()
html <- "<table class=\"Table\">\n <tr>\n <th class=\"LeftColumnHeader\">Train Company</th>\n <th class=\"CentreColumnHeader\">TotalTrains</th>\n </tr>\n <tr>\n <th class=\"LeftCell\">Arriva Trains Wales</th>\n <td class=\"RightCell\">2618</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">CrossCountry</th>\n <td class=\"RightCell\">15378</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">London Midland</th>\n <td class=\"RightCell\">32677</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Virgin Trains</th>\n <td class=\"RightCell\">5717</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Total</th>\n <td class=\"Total\">56390</td>\n </tr>\n</table>"
expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 112780)
expect_identical(as.character(pt$getHtml(showRowGroupHeaders=TRUE)), html)
})
}
scenarios <- testScenarios("Row group header basic layout test: Two row groups and calculation")
for(i in 1:nrow(scenarios)) {
if(!isDevelopmentVersion) break
evaluationMode <- scenarios$evaluationMode[i]
processingLibrary <- scenarios$processingLibrary[i]
description <- scenarios$description[i]
countFunction <- scenarios$countFunction[i]
test_that(description, {
library(dplyr)
library(lubridate)
library(pivottabler)
pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode, compatibility=list(noDataGroupNBSP=TRUE))
pt$addData(trains)
pt$addRowDataGroups("TOC", header="Train Company")
pt$addRowDataGroups("TrainCategory", header="Train Category", addTotal=FALSE)
pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction)
pt$theme <- getStandardTableTheme(pt)
pt$evaluatePivot()
html <- "<table class=\"Table\">\n <tr>\n <th class=\"LeftColumnHeader\">Train Company</th>\n <th class=\"LeftColumnHeader\">Train Category</th>\n <th class=\"CentreColumnHeader\">TotalTrains</th>\n </tr>\n <tr>\n <th class=\"LeftCell\" rowspan=\"2\">Arriva Trains Wales</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\">2062</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Ordinary Passenger</th>\n <td class=\"RightCell\">556</td>\n </tr>\n <tr>\n <th class=\"LeftCell\" rowspan=\"2\">CrossCountry</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\">15336</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Ordinary Passenger</th>\n <td class=\"RightCell\">42</td>\n </tr>\n <tr>\n <th class=\"LeftCell\" rowspan=\"2\">London Midland</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\">9736</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Ordinary Passenger</th>\n <td class=\"RightCell\">22941</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Virgin Trains</th>\n <th class=\"LeftCell\">Express Passenger</th>\n <td class=\"RightCell\">5717</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Total</th>\n <th class=\"LeftCell\"></th>\n <td class=\"Total\">56390</td>\n </tr>\n</table>"
expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 112780)
expect_identical(as.character(pt$getHtml(showRowGroupHeaders=TRUE)), html)
})
}
scenarios <- testScenarios("Row group header basic layout test: Row and column only")
for(i in 1:nrow(scenarios)) {
if(!isDevelopmentVersion) break
evaluationMode <- scenarios$evaluationMode[i]
processingLibrary <- scenarios$processingLibrary[i]
description <- scenarios$description[i]
countFunction <- scenarios$countFunction[i]
test_that(description, {
library(dplyr)
library(lubridate)
library(pivottabler)
pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode)
pt$addData(trains)
pt$addColumnDataGroups("GbttMonth", dataFormat=list(format="%B %Y"))
pt$addRowDataGroups("TOC", header="Train Company", addTotal=FALSE)
pt$theme <- getStandardTableTheme(pt)
pt$evaluatePivot()
html <- "<table class=\"Table\">\n <tr>\n <th class=\"LeftColumnHeader\">Train Company</th>\n <th class=\"CentreColumnHeader\">January 2017</th>\n <th class=\"CentreColumnHeader\">February 2017</th>\n <th class=\"CentreColumnHeader\">Total</th>\n </tr>\n <tr>\n <th class=\"LeftCell\">Arriva Trains Wales</th>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\">CrossCountry</th>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\">London Midland</th>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\"></td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Virgin Trains</th>\n <td class=\"RightCell\"></td>\n <td class=\"RightCell\"></td>\n <td class=\"Total\"></td>\n </tr>\n</table>"
expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 0)
expect_identical(as.character(pt$getHtml(showRowGroupHeaders=TRUE)), html)
})
}
scenarios <- testScenarios("Row group header basic layout test: Row, column and calculation")
for(i in 1:nrow(scenarios)) {
evaluationMode <- scenarios$evaluationMode[i]
processingLibrary <- scenarios$processingLibrary[i]
description <- scenarios$description[i]
countFunction <- scenarios$countFunction[i]
test_that(description, {
library(dplyr)
library(lubridate)
library(pivottabler)
pt <- PivotTable$new(processingLibrary=processingLibrary, evaluationMode=evaluationMode)
pt$addData(trains)
pt$addColumnDataGroups("GbttMonth", dataFormat=list(format="%B %Y"))
pt$addRowDataGroups("TOC", header="Train Company")
pt$defineCalculation(calculationName="TotalTrains", summariseExpression=countFunction)
pt$theme <- getStandardTableTheme(pt)
pt$evaluatePivot()
html <- "<table class=\"Table\">\n <tr>\n <th class=\"LeftColumnHeader\">Train Company</th>\n <th class=\"CentreColumnHeader\">January 2017</th>\n <th class=\"CentreColumnHeader\">February 2017</th>\n <th class=\"CentreColumnHeader\">Total</th>\n </tr>\n <tr>\n <th class=\"LeftCell\">Arriva Trains Wales</th>\n <td class=\"RightCell\">1402</td>\n <td class=\"RightCell\">1216</td>\n <td class=\"Total\">2618</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">CrossCountry</th>\n <td class=\"RightCell\">8033</td>\n <td class=\"RightCell\">7345</td>\n <td class=\"Total\">15378</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">London Midland</th>\n <td class=\"RightCell\">17029</td>\n <td class=\"RightCell\">15648</td>\n <td class=\"Total\">32677</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Virgin Trains</th>\n <td class=\"RightCell\">3004</td>\n <td class=\"RightCell\">2713</td>\n <td class=\"Total\">5717</td>\n </tr>\n <tr>\n <th class=\"LeftCell\">Total</th>\n <td class=\"Total\">29468</td>\n <td class=\"Total\">26922</td>\n <td class=\"Total\">56390</td>\n </tr>\n</table>"
expect_equal(sum(pt$cells$asMatrix(), na.rm=TRUE), 225560)
expect_identical(as.character(pt$getHtml(showRowGroupHeaders=TRUE)), html)
})
} |
test_that("com_segment_missingness works", {
load(system.file("extdata/meta_data.RData", package = "dataquieR"), envir =
environment())
load(system.file("extdata/study_data.RData", package = "dataquieR"), envir =
environment())
expect_warning(
r <- com_segment_missingness(study_data, meta_data, label_col = LABEL,
threshold_value = NA, direction = "high",
exclude_roles = VARIABLE_ROLES$PROCESS),
regexp = sprintf("%s|%s",
paste("Study variables: .+ARM_CUFF_0.+,",
".+USR_VO2_0.+, .+USR_BP_0.+,",
".+EXAM_DT_0.+, .+DEV_NO_0.+,",
".+LAB_DT_0.+, .+USR_SOCDEM_0.+,",
".+INT_DT_0.+, .+QUEST_DT_0.+",
"are not considered due to their",
"VARIABLE_ROLE."),
paste("threshold_value should be a single number between",
"0 and 100. Invalid value specified,",
"setting to 10%.")),
all = TRUE
)
expect_warning(
r <- com_segment_missingness(study_data, meta_data, label_col = LABEL,
threshold_value = NA, direction = "high"),
regexp = sprintf("%s|%s|%s",
paste("Study variables: .+ARM_CUFF_0.+,",
".+USR_VO2_0.+, .+USR_BP_0.+,",
".+EXAM_DT_0.+, .+DEV_NO_0.+,",
".+LAB_DT_0.+, .+USR_SOCDEM_0.+,",
".+INT_DT_0.+, .+QUEST_DT_0.+",
"are not considered due to their",
"VARIABLE_ROLE."),
paste("threshold_value should be a single number between",
"0 and 100. Invalid value specified,",
"setting to 10%."),
paste("Formal exclude_roles is used with default:",
"all process variables are not included here.")),
all = TRUE
)
expect_warning(
r <- com_segment_missingness(study_data, meta_data,
threshold_value = NA, direction = "high"),
regexp = sprintf("%s|%s|%s",
paste("Study variables: .+v00010.+,",
".+v00011.+, .+v00012.+,",
".+v00013.+, .+v00016.+,",
".+v00017.+, .+v00032.+,",
".+v00033.+, .+v00042.+",
"are not considered due to their",
"VARIABLE_ROLE."),
paste("threshold_value should be a single number between",
"0 and 100. Invalid value specified,",
"setting to 10%."),
paste("Formal exclude_roles is used with default:",
"all process variables are not included here.")),
all = TRUE
)
expect_warning(
r <- com_segment_missingness(study_data, meta_data, label_col = LABEL,
threshold_value = NA, direction = "high",
strata_vars = "CENTER_0"),
regexp = sprintf("%s|%s|%s",
paste("Study variables: .+ARM_CUFF_0.+,",
".+USR_VO2_0.+, .+USR_BP_0.+,",
".+EXAM_DT_0.+, .+DEV_NO_0.+,",
".+LAB_DT_0.+, .+USR_SOCDEM_0.+,",
".+INT_DT_0.+, .+QUEST_DT_0.+",
"are not considered due to their",
"VARIABLE_ROLE."),
paste("threshold_value should be a single number between",
"0 and 100. Invalid value specified,",
"setting to 10%."),
paste("Formal exclude_roles is used with default:",
"all process variables are not included here.")),
all = TRUE
)
meta_data2 <- meta_data
meta_data2$KEY_STUDY_SEGMENT <- NULL
expect_error(suppressWarnings(
r <- com_segment_missingness(study_data, meta_data2,
threshold_value = 10, direction = "high",
exclude_roles = c(VARIABLE_ROLES$PROCESS,
"invalid"))
),
regexp = paste("In suppressWarnings: Metadata do not contain",
"the column KEY_STUDY_SEGMENT"),
perl = TRUE
)
meta_data2 <- meta_data
meta_data2$LONG_LABEL <- NA
expect_warning(
r <- com_segment_missingness(study_data, meta_data2,
threshold_value = 10, direction = "high",
exclude_roles = c(VARIABLE_ROLES$PROCESS,
"invalid")),
regexp = sprintf("%s|%s",
paste("Specified VARIABLE_ROLE.s.:",
".+invalid.+ was not found in metadata, only:",
".+process.+ is used."),
paste("Study variables: .+v00010.+, .+v00011.+,",
".+v00012.+, .+v00013.+, .+v00016.+, .+v00017.+,",
".+v00032.+, .+v00033.+, .+v00042.+ are not",
"considered due to their VARIABLE_ROLE.")),
perl = TRUE,
all = TRUE
)
expect_warning(
r <- com_segment_missingness(study_data, meta_data,
threshold_value = 10, direction = "high",
exclude_roles = c(VARIABLE_ROLES$PROCESS,
"invalid")),
regexp = sprintf("%s|%s",
paste("Specified VARIABLE_ROLE.s.:",
".+invalid.+ was not found in metadata, only:",
".+process.+ is used."),
paste("Study variables: .+v00010.+, .+v00011.+,",
".+v00012.+, .+v00013.+, .+v00016.+, .+v00017.+,",
".+v00032.+, .+v00033.+, .+v00042.+ are not",
"considered due to their VARIABLE_ROLE.")),
perl = TRUE,
all = TRUE
)
expect_warning(
r <- com_segment_missingness(study_data, meta_data, label_col = LABEL,
threshold_value = 10, direction = "high",
exclude_roles = c(VARIABLE_ROLES$PROCESS,
"invalid")),
regexp = sprintf("%s|%s",
paste("Specified VARIABLE_ROLE.s.:",
".+invalid.+ was not found in metadata, only:",
".+process.+ is used."),
paste("Study variables: .+ARM_CUFF_0.+,",
".+USR_VO2_0.+, .+USR_BP_0.+,",
".+EXAM_DT_0.+, .+DEV_NO_0.+,",
".+LAB_DT_0.+, .+USR_SOCDEM_0.+,",
".+INT_DT_0.+, .+QUEST_DT_0.+",
"are not considered due to their",
"VARIABLE_ROLE.")),
perl = TRUE,
all = TRUE
)
expect_error(suppressWarnings(
r <- com_segment_missingness(study_data, meta_data, label_col = LABEL,
threshold_value = 10, direction = "invalid",
exclude_roles = VARIABLE_ROLES$PROCESS)
),
regexp = paste("Parameter .+direction.+ should be either .+low.+ or",
".+high.+, but not .+invalid.+."),
perl = TRUE
)
expect_error(suppressWarnings(
r <- com_segment_missingness(study_data, meta_data, label_col = LABEL,
threshold_value = 10, direction = 1:2,
exclude_roles = VARIABLE_ROLES$PROCESS)
),
regexp = paste("Parameter .+direction.+ should be of length",
"1, but not 2."),
perl = TRUE
)
expect_warning(
r <- com_segment_missingness(study_data, meta_data, label_col = LABEL,
threshold_value = 10, direction = "high",
exclude_roles = VARIABLE_ROLES$PROCESS),
regexp = paste("Study variables: .+ARM_CUFF_0.+,",
".+USR_VO2_0.+, .+USR_BP_0.+,",
".+EXAM_DT_0.+, .+DEV_NO_0.+,",
".+LAB_DT_0.+, .+USR_SOCDEM_0.+,",
".+INT_DT_0.+, .+QUEST_DT_0.+",
"are not considered due to their",
"VARIABLE_ROLE.")
)
expect_warning(
r <- com_segment_missingness(study_data, meta_data, label_col = LABEL,
threshold_value = 10, direction = "low",
exclude_roles = VARIABLE_ROLES$PROCESS),
regexp = paste("Study variables: .+ARM_CUFF_0.+,",
".+USR_VO2_0.+, .+USR_BP_0.+,",
".+EXAM_DT_0.+, .+DEV_NO_0.+,",
".+LAB_DT_0.+, .+USR_SOCDEM_0.+,",
".+INT_DT_0.+, .+QUEST_DT_0.+",
"are not considered due to their",
"VARIABLE_ROLE.")
)
expect_equal(
length(intersect(
names(r),
c("SummaryData", "SummaryPlot")
)), length(union(
names(r),
c("SummaryData", "SummaryPlot")
))
)
expect_true(abs(suppressWarnings(sum(as.numeric(as.matrix(
r$SummaryData)), na.rm = TRUE)) - 16027.23) < 2)
skip_on_cran()
skip_if_not_installed("vdiffr")
skip_if_not(capabilities()["long.double"])
vdiffr::expect_doppelganger("segment missingness plot ok",
r$SummaryPlot)
}) |
rvn_download<-function(version=NA,NetCDF=FALSE,check=FALSE,copy_path=NULL)
{
. <- NULL
download_path <- tempdir()
save_path <- system.file("extdata",package="RavenR")
if (check) {
if (file.exists(sprintf("%s/Raven.exe",save_path))) {
message(sprintf("Raven.exe found in %s", save_path))
return(TRUE)
} else {
message(sprintf("Raven.exe NOT found in %s", save_path))
return(FALSE)
}
}
if (is.null(copy_path)) {
sysinf <- Sys.info()
if (!is.null(sysinf))
{
os <- sysinf["sysname"]
if (os == "Darwin") os <- "osx"
}else{
os <- .Platform$OS.type
if (grepl("^darwin", R.version$os)) os <- "osx"
if (grepl("linux-gnu", R.version$os)) os <- "linux"
}
platform <- tolower(os)
url <- "http://raven.uwaterloo.ca/Downloads.html"
html <- paste(readLines(url), collapse="\n")
matched <- str_match_all(html, "<a href=\"(.*?)\"")[[1]]
matched<-matched[grep("a href=",matched)]
if(platform=="windows")
{
arch<-osVersion
if (length(grep("x64",arch))==1)
{
versions<-matched[grep("Win64",matched)]
versions<-str_match(versions, "Win64_\\s*(.*?)\\s*.zip")[,2]
if(NetCDF)
{
versions<-versions[grep("n",versions)]
if(length(versions)<1) stop(paste("A Raven version supporting NetCDF on: ",arch," is not available!"))
versions<-gsub("[^0-9.-]", "", versions) %>%
sort(.,decreasing=TRUE) %>%
paste("v",.,"n",sep="")
if(!is.na(version))
{
selectedVersion<-versions[paste("v",version,"n",sep="")%>% match(.,versions)]
if(is.na(selectedVersion)) stop (paste("A NetCDF version",version, "is not available for",arch,". Try either of [",paste(gsub("[^0-9.-]", "", versions),collapse=' , '),"] version(s)"))
}else{
selectedVersion<-versions[1]
}
}else{
if(length(grep('n',versions))>0) versions<-versions[-grep('n',versions)]
versions<-gsub("[^0-9.-]", "", versions)
if(length(versions)<1) stop(paste("A Raven version on: ",arch," is not available!"))
versions<-versions[!duplicated(versions)]%>% sort(.,decreasing=TRUE)%>% paste("v",.,sep="")
if(!is.na(version))
{
selectedVersion<-versions[paste("v",version,sep="")%>% match(.,versions)]
if(is.na(selectedVersion)) stop (paste("Version",version, "is not available for",arch,". Try either of [",paste(gsub("[^0-9.-]", "", versions),collapse=' , '),"] version(s)"))
}else{
selectedVersion<-versions[1]
}
}
fileName<-paste("RavenExecutableWin64_",selectedVersion,".zip",sep="")
}
if (length(grep("x86",arch))==1)
{
versions<-matched[grep("Win32",matched)]
versions<-str_match(versions, "Win32_\\s*(.*?)\\s*.zip")[,2]
if(NetCDF)
{
versions<-versions[grep("n",versions)]
if(length(versions)<1) stop(paste("A Raven version supporting NetCDF on: ",arch," is not available!"))
versions<-gsub("[^0-9.-]", "", versions) %>%
sort(.,decreasing=TRUE) %>%
paste("v",.,"n",sep="")
if(!is.na(version))
{
selectedVersion<-versions[paste("v",version,"n",sep="")%>% match(.,versions)]
if(is.na(selectedVersion)) stop (paste("A NetCDF version",version, "is not available for",arch,". Try either of [",paste(gsub("[^0-9.-]", "", versions),collapse=' , '),"] version(s)"))
}else{
selectedVersion<-versions[1]
}
}else{
if(length(grep('n',versions))>0) versions<-versions[-grep('n',versions)]
versions<-gsub("[^0-9.-]", "", versions)
if(length(versions)<1) stop(paste("A Raven version on: ",arch," is not available!"))
versions<-versions[!duplicated(versions)]%>% sort(.,decreasing=TRUE)%>% paste("v",.,sep="")
if(!is.na(version))
{
selectedVersion<-versions[paste("v",version,sep="")%>% match(.,versions)]
if(is.na(selectedVersion)) stop (paste("Version",version, "is not available for",arch,". Try either of [",paste(gsub("[^0-9.-]", "", versions),collapse=' , '),"] version(s)"))
}else{
selectedVersion<-versions[1]
}
}
fileName<-paste("RavenExecutableWin32_",selectedVersion,".zip",sep="")
}
}
if(platform=="osx")
{
versions<-matched[grep("MacOS",matched)]
versions<-str_match(versions, "MacOS_\\s*(.*?)\\s*.zip")[,2]
if(NetCDF)
{
versions<-versions[grep("n",versions)]
if(length(versions)<1) stop(paste("A Raven version supporting NetCDF on: ",arch," is not available!"))
versions<-gsub("[^0-9.-]", "", versions) %>% sort(.,decreasing=TRUE) %>% paste("v",.,"n",sep="")
if(!is.na(version))
{
selectedVersion<-versions[paste("v",version,"n",sep="")%>% match(.,versions)]
if(is.na(selectedVersion)) stop (paste("A NetCDF version",version, "is not available for",platform,". Try either of [",paste(gsub("[^0-9.-]", "", versions),collapse=' , '),"] version(s)"))
}else{
selectedVersion<-versions[1]
}
}else{
if(length(grep('n',versions))>0) versions<-versions[-grep('n',versions)]
versions<-gsub("[^0-9.-]", "", versions)
versions<-versions[!duplicated(versions)]%>% sort(.,decreasing=TRUE)%>% paste("v",.,sep="")
if(!is.na(version))
{
selectedVersion<-versions[paste("v",version,sep="")%>% match(.,versions)]
if(is.na(selectedVersion)) stop (paste("Version",version, "is not available for",platform,". Try either of [",paste(gsub("[^0-9.-]", "", versions),collapse=' , '),"] version(s)"))
}else{
selectedVersion<-versions[1]
}
}
fileName<-paste("RavenExecutableMacOS_",selectedVersion,".zip",sep="")
}
if(platform=="linux")
{
versions<-matched[grep("Linux",matched)]
versions<-str_match(versions, "Linux_\\s*(.*?)\\s*.zip")[,2]
if(NetCDF)
{
versions<-versions[grep("n",versions)]
if(length(versions)<1) stop(paste("A Raven version supporting NetCDF on: ",platform," is not available!"))
versions<-gsub("[^0-9.-]", "", versions) %>% sort(.,decreasing=TRUE) %>% paste("v",.,"n",sep="")
if(!is.na(version))
{
selectedVersion<-versions[paste("v",version,"n",sep="")%>% match(.,versions)]
if(is.na(selectedVersion)) stop (paste("A NetCDF version",version, "is not available for",platform,". Try either of [",paste(gsub("[^0-9.-]", "", versions),collapse=' , '),"] version(s)"))
}else{
selectedVersion<-versions[1]
}
}else{
if(length(grep('n',versions))>0) versions<-versions[-grep('n',versions)]
versions<-gsub("[^0-9.-]", "", versions)
versions<-versions[!duplicated(versions)]%>% sort(.,decreasing=TRUE)%>% paste("v",.,sep="")
if(!is.na(version))
{
selectedVersion<-versions[paste("v",version,sep="")%>% match(.,versions)]
if(is.na(selectedVersion)) stop (paste("Version",version, "is not available for",platform,". Try either of [",paste(gsub("[^0-9.-]", "", versions),collapse=' , '),"] version(s)"))
}else{
selectedVersion<-versions[1]
}
}
fileName<-paste("RavenExecutableLinux_",selectedVersion,".zip",sep="")
}
downloadLink<-paste("http://raven.uwaterloo.ca/files/",gsub("n","",selectedVersion),"/",fileName,sep="")
if(!RCurl::url.exists(downloadLink)) stop("Bad file url. Check the repository!")
download.file(downloadLink,paste(download_path,"/",fileName,sep=""))
unzip(zipfile=paste(download_path,"/",fileName,sep=""),exdir=download_path)
file.remove(paste(download_path,"/",fileName,sep=""))
file.remove(paste(download_path,"/","RavenManual","_",gsub("n","",selectedVersion),".pdf",sep=""))
res <- file.copy(from=paste(download_path,"/","Raven.exe",sep=""),
to=paste(save_path,"/","Raven.exe",sep=""),
overwrite=TRUE)
} else {
if (!file.exists(copy_path) ) {
stop("copy_path is not a valid file, please check")
} else {
if (rvn_substrRight(copy_path,9) != "Raven.exe") {
warning("expecting a valid Raven.exe file, file will be renamed to Raven.exe when copied to local RavenR folder.")
}
res <- file.copy(from=copy_path,
to=paste(save_path,"/","Raven.exe",sep=""),
overwrite=TRUE)
}
}
return(res)
} |
"MTPL"
"MTPL2" |
Rcpp::sourceCpp('src/PCA.cpp')
a <- big.matrix(10, 10)
b <- matrix(rnorm(50), 5, 10)
test <- crossprod(b, b)
dim(test)
test[1:5, 1:5]
crossprodEigen2(a@address, b, b)
a[1:5, 1:5]
crossprodEigen3(a@address, b, b)
a[1:5, 1:5]
b.sub <- b[, 1:3]
a.sub <- sub.big.matrix(a, 1, 3, 1, 3)
a.sub[] <- 0
crossprodEigen2(a.sub@address, b.sub, b.sub)
a.sub[,]
a[,]
a.sub[] <- 0
crossprodEigen3(a.sub@address, b.sub, b.sub)
a.sub[,]
a[,]
test <- crossprodEigen4(b.sub, b.sub) |
pastecolon=function(...){
paste(...,sep=":")
}
ggCatepillar=function(data,mapping,errorbar="se",interactive=FALSE,digits=1,flip=FALSE,use.label=TRUE,use.labels=TRUE){
xvar<-yvar<-groupvar<-colourvar<-NULL
xvar=getMapping(mapping,"x")
yvar=getMapping(mapping,"y")
if(is.null(xvar)|is.null(yvar)) warning("Both x and y aesthetics are should be mapped")
(groupname=setdiff(names(mapping),c("x","y")))
if(length(groupname)>0) (groupvar=getMapping(mapping,groupname))
name=names(mapping)
xlabels<-ylabels<-filllabels<-colourlabels<-xlab<-ylab<-colourlab<-filllab<-NULL
for(i in 1:length(name)){
(varname=paste0(name[i],"var"))
labname=paste0(name[i],"lab")
labelsname=paste0(name[i],"labels")
temp=getMapping(mapping,name[i])
assign(varname,temp)
x=eval(parse(text=paste0("data$",eval(parse(text=varname)))))
assign(labname,attr(x,"label"))
assign(labelsname,sjlabelled::get_labels(x))
}
df<-data
A=yvar
B=groupvar
C=xvar
if(is.null(B)){
dat=summarySE(df,A,C)
dat$tooltip="all"
if(length(C)==1) {
dat$label=paste0(C,": ",dat[[C]],"<br>",A,": ",round(dat[[A]],digits),
"<br>sd: ",round(dat$sd,digits),"<br>se: ",round(dat$se,digits))
} else {
dat$label=paste0(A,": ",round(dat[[A]],digits),
"<br>sd: ",round(dat$sd,digits),"<br>se: ",round(dat$se,digits))
}
} else {
dat=summarySE(df,A,c(B,C))
dat[[B]]=factor(dat[[B]])
dat$tooltip=dat[[B]]
if(length(C)==1) {
dat$label=paste0(B,": ",dat[[B]],"<br>",C,":",dat[[C]],"<br>",A,": ",round(dat[[A]],digits),
"<br>sd: ",round(dat$sd,digits),"<br>se: ",round(dat$se,digits))
} else {
dat$label=paste0(B,": ",dat[[B]],"<br>",A,": ",round(dat[[A]],digits),
"<br>sd: ",round(dat$sd,digits),"<br>se: ",round(dat$se,digits))
}
}
if(length(C)>1){
temp=Reduce(paste0,C)
dat[[temp]]=Reduce(pastecolon,dat[C])
C=temp
dat[[C]]=factor(dat[[C]])
}
dat
dat$id=1:nrow(dat)
if(class(dat[[C]])%in% c("numeric","integer")) {
mywidth=max(dat[[C]])/80
} else mywidth=0.2
if(is.null(B)) {
p<-ggplot(data=dat,aes_string(x=C,y=A,group=1,colour=C))+xlab(Reduce(pastecolon,C))
} else p<-ggplot(data=dat,aes_string(x=C,y=A,group=B,colour=B))
p<-p+ geom_path_interactive(aes_string(tooltip="tooltip",data_id="id"),position=position_dodge(width=mywidth))+
geom_point_interactive(aes_string(tooltip="label",data_id="id"),size=4,position=position_dodge(width=mywidth))
p
if(errorbar=="se"|errorbar=="sd") p<-p+eval(parse(text=paste0("geom_errorbar(aes(ymin=",A,"-",errorbar,",ymax=",
A,"+",errorbar,"),width=",mywidth,",
position=position_dodge(width=mywidth))")))
if(flip) p<-p+coord_flip()
if(use.labels) {
if(length(xvar)==1){
if(!is.null(xlabels)) {
if(is.numeric(data[[xvar[1]]])) p<-p+scale_x_continuous(breaks=1:length(xlabels),labels=xlabels)
else p<-p+scale_x_discrete(labels=xlabels)
}
}
if(!is.null(ylabels)) p<-p+scale_y_continuous(breaks=1:length(ylabels),labels=ylabels)
if(!is.null(filllabels)) p=p+scale_fill_discrete(labels=filllabels)
if(!is.null(colourlabels)) {
if(!is.numeric(data[[colourvar]])) p=p+scale_color_discrete(labels=colourlabels)
}
}
if(use.label){
if(!is.null(xlab)) p<-p+labs(x=xlab)
if(!is.null(ylab)) p<-p+labs(y=ylab)
if(!is.null(colourlab)) p<-p+labs(colour=colourlab)
if(!is.null(filllab)) p<-p+labs(fill=filllab)
}
p
if(interactive){
tooltip_css <- "background-color:white;font-style:italic;padding:10px;border-radius:10px 20px 10px 20px;"
hover_css="r:4px;cursor:pointer;stroke-width:6px;"
selected_css = "fill:
p<-girafe(ggobj=p)
p<-girafe_options(p,
opts_hover(css=hover_css),
opts_tooltip(css=tooltip_css,opacity=.75),
opts_selection(css=selected_css),
opts_zoom(min=1,max=10))
}
p
} |
setCoxModel<- function(variance=0.01, seed=NULL){
ensure_installed("survAUC")
if(!class(seed)%in%c('numeric','NULL','integer'))
stop('Invalid seed')
if(!class(variance) %in% c("numeric", "integer"))
stop('Variance must be numeric')
if(variance<0)
stop('Variance must be >= 0')
result <- list(model='fitCoxModel', param=list(variance=variance, seed=seed), name="Lasso Cox Regression")
class(result) <- 'modelSettings'
return(result)
}
fitCoxModel<- function(population, plpData, param, search='adaptive',
outcomeId, cohortId, trace=F,...){
if(length(ParallelLogger::getLoggers())==0){
logger <- ParallelLogger::createLogger(name = "SIMPLE",
threshold = "INFO",
appenders = list(ParallelLogger::createConsoleAppender(layout = ParallelLogger::layoutTimestamp)))
ParallelLogger::registerLogger(logger)
}
if (!FeatureExtraction::isCovariateData(plpData$covariateData)){
ParallelLogger::logError('Cox regression requires plpData in coo format')
stop()
}
metaData <- attr(population, 'metaData')
if(!is.null(population$indexes))
population <- population[population$indexes>0,]
attr(population, 'metaData') <- metaData
if(length(population$rowId)<200000){
plpData$covariateData <- limitCovariatesToPopulation(plpData$covariateData,
population$rowId)
} else{
plpData$covariateData <- batchRestrict(plpData$covariateData,
data.frame(rowId = population$rowId),
sizeN = 10000000)
}
variance <- 0.003
if(!is.null(param$variance )) variance <- param$variance
start <- Sys.time()
modelTrained <- fitGLMModel(population,
plpData = plpData,
modelType = "cox",
prior = Cyclops::createPrior("laplace",useCrossValidation = TRUE),
control = Cyclops::createControl(noiseLevel = ifelse(trace,"quiet","silent"), cvType = "auto",
startingVariance = variance,
tolerance = 2e-07,
cvRepetitions = 1, fold=ifelse(!is.null(population$indexes),max(population$indexes),1),
selectorType = "byRow",
threads=-1,
maxIterations = 3000,
seed=param$seed))
comp <- Sys.time() - start
varImp <- data.frame(covariateId=names(modelTrained$coefficients)[names(modelTrained$coefficients)!='(Intercept)'],
value=modelTrained$coefficients[names(modelTrained$coefficients)!='(Intercept)'])
if(sum(abs(varImp$value)>0)==0){
ParallelLogger::logWarn('No non-zero coefficients')
varImp <- NULL
} else {
varImp <- merge(as.data.frame(plpData$covariateData$covariateRef), varImp,
by='covariateId',all=T)
varImp$value[is.na(varImp$value)] <- 0
varImp <- varImp[order(-abs(varImp$value)),]
colnames(varImp)[colnames(varImp)=='value'] <- 'covariateValue'
}
prediction <- predict.plp(plpModel=list(model = modelTrained),
population = population,
plpData = plpData)
result <- list(model = modelTrained,
modelSettings = list(model='cox_lasso', modelParameters=param),
hyperParamSearch = c(priorVariance=modelTrained$priorVariance,
seed=ifelse(is.null(param$seed), 'NULL', param$seed ),
log_likelihood = modelTrained$log_likelihood),
trainCVAuc = NULL,
metaData = plpData$metaData,
populationSettings = attr(population, 'metaData'),
outcomeId=outcomeId,
cohortId=cohortId,
varImp = varImp,
trainingTime=comp,
covariateMap = NULL,
predictionTrain = prediction
)
class(result) <- 'plpModel'
attr(result, 'type') <- 'plp'
attr(result, 'predictionType') <- 'survival'
return(result)
} |
delPts <- function (dat,del=NULL,cols=c(1,2),ptsize=1,xmin=NULL,xmax=NULL,ymin=NULL,ymax=NULL,plotype=1,genplot=T,verbose=T)
{
if(verbose) cat("\n----- INTERACTIVELY IDENTIFY AND DELETE POINTS IN PLOT -----\n")
dat <- data.frame(dat)
if(length(dat) < 2) {stop("**** TERMINATING: input must have at least two columns")}
if(nrow(dat) < 2) {stop("**** TERMINATING: input must have more than one point")}
ipts <- length(dat[,1])
if(verbose) cat(" * Number of data points=", ipts,"\n")
if(!is.null(del)) pts=del
if(is.null(del))
{
if(verbose) cat(" * Select points by clicking\n")
if(verbose) cat(" Stop by pressing ESC-key (Mac) or STOP button (Windows)\n")
if(is.null(xmin)) xmin=min(dat[,cols[1]])
if(is.null(xmax)) xmax=max(dat[,cols[1]])
if(is.null(ymin)) ymin=min(dat[,cols[2]])
if(is.null(ymax)) ymax=max(dat[,cols[2]])
par(mfrow=c(1,1))
if (plotype == 1) { plot(dat[,cols[1]],dat[,cols[2]], main="Select data points for deletion (press ESC-key or STOP to exit)",xlim=c(xmin,xmax),ylim=c(ymin,ymax),bty="n",lwd=2,cex.axis=1.1,cex.lab=1.1,cex=ptsize); lines(dat[,cols[1]],dat[,cols[2]],col="red") }
if (plotype == 2) { plot(dat[,cols[1]],dat[,cols[2]], main="Select data points for deletion (press ESC-key or STOP to exit)",xlim=c(xmin,xmax),ylim=c(ymin,ymax),bty="n",cex.axis=1.1,cex.lab=1.1,cex=ptsize) }
if (plotype == 3) { plot(dat[,cols[1]],dat[,cols[2]], type="l", main="Select data points for deletion (press ESC-key or STOP to exit)",xlim=c(xmin,xmax),ylim=c(ymin,ymax),bty="n",lwd=2,cex.axis=1.1,cex.lab=1.1) }
identifyPch <- function(x, y=NULL, n=length(x), pch=19, cex, ...)
{
xy <- xy.coords(x, y); x <- xy$x; y <- xy$y
sel <- rep(FALSE, length(x)); res <- integer(0)
while(sum(sel) < n) {
ans <- identify(x[!sel], y[!sel], n=1, plot=F, ...)
if(!length(ans)) break
ans <- which(!sel)[ans]
points(x[ans], y[ans], pch = pch, cex = cex, col="blue")
sel[ans] <- TRUE
res <- c(res, ans)
}
res
}
pts <- identifyPch(dat[,cols[1]],dat[,cols[2]], cex=ptsize)
}
if(verbose)
{
cat("\nSELECTED DATA POINTS FOR DELETION:\n")
print(dat[pts,cols])
cat("\n")
}
out <- dat
out[pts,] <- NA
out <- data.frame(subset(out, !(out[,cols[2]] == "NA")))
newpts=length(out[,1])
if(verbose) cat(" * Number of data points following deletion=",newpts,"\n")
if(genplot)
{
par(mfrow=c(2,1))
if (plotype == 1) { plot(dat[,cols[1]],dat[,cols[2]], main="Original Data Series (deleted points in blue)",xlim=c(xmin,xmax),ylim=c(ymin,ymax),bty="n",lwd=2,cex.axis=1.1,cex.lab=1.1,cex=ptsize/1.5,col="gray"); lines(dat[,cols[1]],dat[,cols[2]],col="red") }
if (plotype == 2) { plot(dat[,cols[1]],dat[,cols[2]], main="Original Data Series (deleted points in blue)",xlim=c(xmin,xmax),ylim=c(ymin,ymax),bty="n",cex.axis=1.1,cex.lab=1.1,cex=ptsize/1.5,col="gray") }
if (plotype == 3) { plot(dat[,cols[1]],dat[,cols[2]], type="l", main="Original Data Series (deleted points in blue)",xlim=c(xmin,xmax),ylim=c(ymin,ymax),bty="n",lwd=2,cex.axis=1.1,cex.lab=1.1,col="gray") }
points(dat[pts,cols[1]],dat[pts,cols[2]],col="blue",pch=19,cex=ptsize/1.5)
if (plotype == 1) { plot(out[,cols[1]],out[,cols[2]], main="Edited Data Series",xlim=c(xmin,xmax),ylim=c(ymin,ymax),bty="n",lwd=2,cex.axis=1.1,cex.lab=1.1,cex=ptsize/1.5,col="gray"); lines(out[,cols[1]],out[,cols[2]],col="red") }
if (plotype == 2) { plot(out[,cols[1]],out[,cols[2]], main="Edited Data Series",xlim=c(xmin,xmax),ylim=c(ymin,ymax),bty="n",cex.axis=1.1,cex.lab=1.1,cex=ptsize/1.5,col="gray") }
if (plotype == 3) { plot(out[,cols[1]],out[,cols[2]], type="l", main="Edited Data Series",xlim=c(xmin,xmax),ylim=c(ymin,ymax),bty="n",lwd=2,cex.axis=1.1,cex.lab=1.1,col="gray") }
}
return(out)
} |
me_ <- nm_fun("TEST-drive_put")
nm_ <- nm_fun("TEST-drive_put", user_run = FALSE)
if (CLEAN) {
drive_trash(c(
))
}
if (SETUP) {
}
test_that("drive_put() works", {
skip_if_no_token()
skip_if_offline()
local_file <- tempfile(me_("foo"), fileext = ".txt")
put_file <- basename(local_file)
download_target <- tempfile(me_("download"), fileext = ".txt")
withr::defer({
unlink(local_file)
unlink(download_target)
})
defer_drive_rm(drive_find(me_("foo")))
write_utf8(c("beginning", "middle"), local_file)
local_drive_loud_and_wide()
first_put <- capture.output(
original <- drive_put(local_file),
type = "message"
)
first_put <- first_put %>%
scrub_filepath(local_file) %>%
scrub_filepath(put_file) %>%
scrub_file_id()
expect_snapshot(
write_utf8(first_put)
)
expect_dribble(original)
with_drive_quiet(
drive_download(original, path = download_target)
)
expect_identical(
read_utf8(local_file),
read_utf8(download_target)
)
cat("end", file = local_file, sep = "\n", append = TRUE)
second_put <- capture.output(
second <- drive_put(local_file),
type = "message"
)
second_put <- second_put %>%
scrub_filepath(put_file) %>%
scrub_file_id()
expect_snapshot(
write_utf8(second_put)
)
expect_identical(original$id, second$id)
with_drive_quiet(
drive_download(original, path = download_target, overwrite = TRUE)
)
expect_identical(
read_utf8(local_file),
read_utf8(download_target)
)
with_drive_quiet(
name_collider <- drive_create(basename(local_file))
)
expect_error(
drive_put(local_file),
"Multiple items"
)
}) |
setGeneric("names_RLum", function(object) {
standardGeneric("names_RLum")
})
setMethod("names_RLum",
signature = "list",
function(object) {
lapply(object, function(x) {
if (inherits(x, "RLum")) {
return(names_RLum(x))
} else{
return(x)
}
})
}) |
structree <-
function(formula,
data,
family=gaussian,
stop_criterion=c("AIC","BIC","CV","pvalue"),
splits_max=NULL,
fold=5,
alpha=0.05,
grid_value=NULL,
min_border=NULL,
ridge=FALSE,
constant_covs=FALSE,
trace=TRUE,
plot=TRUE,
k=10,
weights=NULL,
offset=NULL,
...){
UseMethod("structree")
}
print.structree <-
function(x,
...){
type <- attr(x,"type")
if(type=="catPred"){
zv <- attr(x,"which_kat")
xv <- attr(x,"which_smooth")
xv <- c(names(x$DM_kov)[!(names(x$DM_kov) %in% c(xv,zv))],xv)
} else{
slu <- attr(x,"secondlevel")
zv <- c("Intercept",attr(x,"slope"))
xv <- names(x$DM_kov)[!(names(x$DM_kov) %in% c(slu,zv))]
}
x$opts <- x$opts+1
opts <- x$opts
names(opts) <- zv
if(type=="fixedEff"){
cat("Tree Structured Clustering of observation units:\n")
} else{
cat("Tree Structured Clustering of categorical predictors:\n")
}
cat("\n")
cat("Call:",paste(strwrap(paste(deparse(x$call)),width=100),collapse="\n"),"\n")
cat("\n")
if(type=="catPred"){
cat("Variables in tree component:",paste0(zv,collapse=", "),"\n")
cat("Variables in parametric component:",paste0(xv,collapse=", "),"\n")
} else{
cat("Second-level unit:",slu,"\n")
cat("Unit specific effects for:",paste0(zv,collapse=", "),"\n")
cat("Fixed effects for:",paste0(xv,collapse=", "),"\n")
}
cat("Number of Splits:",x$which_opt-1,"\n")
cat("\n")
cat("Number of Groups:\n")
print(opts)
invisible(x)
}
coef.structree <-
function(object,
...){
if(is.null(attr(object,"which_smooth"))){
coefficients <- object$coefs_end
} else{
coefficients <- object$coefs_end
k <- attr(object,"k")
m <- summary(object$model)$m
if(length(k)==1){
k <- rep(k,m)
}
coefs_s <- tail(object$model$coefficients,sum(k-1))
which_smooth <- attr(object,"which_smooth")
v <- unlist(lapply(1:m,function(j) seq(1,k[j]-1)))
names(coefs_s) <- paste0(rep(paste0("s(",which_smooth,")."),k-1),v)
coefficients <- c(coefficients,coefs_s)
}
return(coefficients)
} |
get_inspect_pairs <- function(pairs, variable, threshold, position = NULL,
n = 11, x = attr(pairs, 'x'), y = attr(pairs, 'y')) {
o <- order(-pairs[[variable]])
if (missing(position) || is.null(position)) {
i <- which.min(abs(pairs[[variable]] - threshold))
position <- which(i == o)
}
range <- 1:n - ceiling(n/2)
sel <- position + range
sel <- sel[(sel > 0) & (sel < length(o))]
p <- pairs[o[sel], ]
structure(
list(pairs = p, x = x[p$.x], y = y[p$.y], position = sel, index = o[sel]),
class = "inspect_pairs")
}
print.inspect_pairs <- function(x, ...) {
n <- nrow(x$pairs)
for (i in seq_len(n)) {
cat("\n\033[33;7;1mPair ==============================================================\033[0m\n")
cat("Index = ", x$index[i], "\n")
cat("Position = ", x$position[i], "\n")
print(as.data.table(x$pairs[i, ]))
cat("\n\033[32;1m==== Corresponding record from x ====\033[0m\n")
print(x$x[i, ])
cat("\n\033[31;1m==== Corresponding record from y ====\033[0m\n")
print(x$y[i, ])
}
} |
getspec <- function(where = getwd(), ext = "txt", lim = c(300, 700), decimal = ".",
sep = NULL, subdir = FALSE, subdir.names = FALSE,
ignore.case = TRUE) {
lr_get_spec(
where = where, ext = ext, lim = lim, decimal = decimal, sep = sep,
subdir = subdir, subdir.names = subdir.names,
ignore.case = ignore.case
)
} |
rsurv <-
function(cov2,dat,m,accumulate=TRUE,rescale=1) {
dat[,c('tdeath')]<-rescale*dat[,c('tdeath')]
nscov2=m+1
ncov2=length(cov2)
nparms=m+ncov2;
ms<-dim(dat)[1]
na=(dat$cdeath==1)
f1=floor(dat$tdeath)+1
f2=dat$tdeath-(f1-1)
mask0=(matrix(1:m,ms,m,byrow=TRUE)==matrix(f1,ms,m))
mask1=(matrix(1:m,ms,m,byrow=TRUE)<matrix(f1,ms,m))
outfcn<-function(parms) {
if(ncov2>0) lam=matrix(parms[1:m],ms,m,byrow=TRUE)+matrix(as.matrix(dat[,cov2])%*%matrix(parms[nscov2:(m+ncov2)],ncov2,1),ms,m)
else lam=matrix(parms[1:m],ms,m,byrow=TRUE)
elam=exp(lam)
if (accumulate){
ssv=rowSums(mask0*matrix(dat$cdeath,ms,m)*lam)-rowSums(mask1*elam+(mask0*elam)*matrix(f2,ms,m))
ss=sum(ssv)
return(ss)
}
else {
elam1=exp(rowSums(mask0*matrix(dat$cdeath,ms,m)*lam))
ss=elam1*exp(-rowSums(mask1*elam+(mask0*elam)*matrix(f2,ms,m)))
return(log(ss))}
}
return(outfcn)
} |
lazfile <- system.file("extdata", "example.las", package = "rlas")
header <- read.lasheader(lazfile)
expect_equal(header[["Point Data Format ID"]], 1L)
expect_equal(header[["Number of point records"]], 30L)
expect_equal(header[["Number of points by return"]], c(26, 4, 0, 0, 0))
expect_equal(header[["System Identifier"]], "LAStools (c) by rapidlasso GmbH") |
merge_met_variable <- function(in.path,in.prefix,start_date, end_date, merge.file,
overwrite = FALSE, verbose = FALSE, ...){
start_year <- lubridate::year(start_date)
end_year <- lubridate::year(end_date)
if(nchar(in.prefix)>0) in.prefix <- paste0(in.prefix,".")
merge.nc <- ncdf4::nc_open(merge.file)
merge.vars <- names(merge.nc$var)
merge.attr <- ncdf4::ncatt_get(merge.nc,varid = merge.vars[1])
merge.time <- ncdf4::ncvar_get(merge.nc,"time")
merge.time.attr <- ncdf4::ncatt_get(merge.nc,"time")
merge.data <- ncdf4::ncvar_get(merge.nc,varid = merge.vars[1])
udunits2::ud.is.parseable(merge.time.attr$units)
origin <- "1970-01-01 00:00:00 UTC"
merge.time.std <- udunits2::ud.convert(merge.time,
merge.time.attr$units,
paste0("seconds since ",origin))
merge.time.std <- as.POSIXct(merge.time.std,tz = "UTC",origin=origin)
merge.years <- unique(lubridate::year(merge.time.std))
if(lubridate::year(merge.time.std[1]) > start_year){
PEcAn.logger::logger.error("merge.time > start_year", merge.time.std[1],start_date)
ncdf4::nc_close(merge.nc)
return(NULL)
}
if(lubridate::year(utils::tail(merge.time.std,1)) < end_year){
PEcAn.logger::logger.error("merge.time < end_year", utils::tail(merge.time.std,1),end_date)
ncdf4::nc_close(merge.nc)
return(NULL)
}
merge.dims <- names(merge.nc$dim)
byLatLon <- FALSE
if(length(grep("^lat",merge.dims))>0 & length(grep("^lon",merge.dims))>0){
byLatLon <- TRUE
}
ncdf4::nc_close(merge.nc)
if(toupper(merge.vars[1]) == "CO2"){
merge.vars[1] <- "mole_fraction_of_carbon_dioxide_in_air"
merge.data <- udunits2::ud.convert(merge.data,merge.attr$units,"mol/mol")
merge.attr$units = "mol/mol"
}
rows <- end_year - start_year + 1
results <- data.frame(file = character(rows),
host = character(rows),
mimetype = character(rows),
formatname = character(rows),
startdate = character(rows),
enddate = character(rows),
dbfile.name = in.prefix,
stringsAsFactors = FALSE)
for (year in start_year:end_year) {
old.file <- file.path(in.path, paste0(in.prefix, year, ".nc"))
merge.sel <- which(lubridate::year(merge.time.std) == year)
merge.sub <- data.frame(time=merge.time.std[merge.sel],data = merge.data[merge.sel])
nc <- ncdf4::nc_open(old.file,write = TRUE)
if(merge.vars[1] %in% names(nc$var)) {
PEcAn.logger::logger.info("variable already exists",merge.vars[1])
ncdf4::nc_close(nc)
next
}
target.time <- ncdf4::ncvar_get(nc,"time")
target.time.attr <- ncdf4::ncatt_get(nc,"time")
target.time.std <- udunits2::ud.convert(target.time,
target.time.attr$units,
paste0("seconds since ",origin))
target.time.std <- as.POSIXct(target.time.std,tz = "UTC",origin=origin)
merge.interp <- stats::approx(merge.sub$time,merge.sub$data, xout = target.time.std,
rule = 2, method = "linear", ties = mean)
var.merge <- ncdf4::ncvar_def(name = merge.vars[1], units = merge.attr$units, dim = nc$dim$time,
missval = merge.attr$`_FillValue`, verbose = verbose)
nc <- ncdf4::ncvar_add(nc = nc, v = var.merge, verbose = verbose)
ncdf4::ncvar_put(nc = nc, varid = merge.vars[1], vals = merge.interp$y)
ncdf4::nc_close(nc)
}
} |
context("window_lsm")
window <- matrix(1, nrow = 11, ncol = 11)
window_even <- matrix(1, nrow = 10, ncol = 10)
test_that("window_lsm returns a list with selected metrics", {
result <- window_lsm(landscape, window = window, what = c("lsm_l_pr", "lsm_l_joinent"))
expect_equal(names(result[[1]]), expected = c("lsm_l_joinent", "lsm_l_pr"))
expect_length(result[[1]], n = 2)
})
test_that("window_lsm takes argument", {
result <- window_lsm(landscape, window = window, what = "lsm_l_core_mn", edge_depth = 10)
expect_true(all(result[[1]][[1]][] == 0))
})
test_that("window_lsm returns works for all data types", {
expect_is(window_lsm(landscape, window = window, what = "lsm_l_pr"),
class = "list")
expect_is(window_lsm(landscape_stack, window = window, what = "lsm_l_pr"),
class = "list")
expect_is(window_lsm(landscape_brick, window = window, what = "lsm_l_pr"),
class = "list")
expect_is(window_lsm(landscape_list, window = window, what = "lsm_l_pr"),
class = "list")
})
test_that("window_lsm returns all errors", {
expect_error(window_lsm(landscape, window = window, what = "lsm_p_area"),
regexp = "'window_lsm()' is only able to calculate landscape level metrics.",
fixed = TRUE)
expect_error(window_lsm(landscape, window = window_even, what = "lsm_l_pr"),
regexp = "The window must have uneven sides.",
fixed = TRUE)
}) |
teamRunSRDeathOversPlotMatch <- function(match,t1,t2, plot=1) {
team=ball=totalRuns=total=str_extract=batsman=runs=quantile=quadrant=SRDeathOvers=NULL
ggplotly=NULL
a <-filter(match,team==t1)
a1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 16.1, 20.0))
a2 <- select(a1,ball,totalRuns,batsman,date)
a3 <- a2 %>% group_by(batsman) %>% summarise(runs=sum(totalRuns),count=n(), SRDeathOvers=runs/count*100)
x_lower <- quantile(a3$runs,p=0.66,na.rm = TRUE)
y_lower <- quantile(a3$SRDeathOvers,p=0.66,na.rm = TRUE)
plot.title <- paste(t1, " Runs vs SR in Death overs against ", t2,sep="")
if(plot == 1){
a3 %>%
mutate(quadrant = case_when(runs > x_lower & SRDeathOvers > y_lower ~ "Q1",
runs <= x_lower & SRDeathOvers > y_lower ~ "Q2",
runs <= x_lower & SRDeathOvers <= y_lower ~ "Q3",
TRUE ~ "Q4")) %>%
ggplot(aes(runs,SRDeathOvers,color=quadrant)) +
geom_text(aes(runs,SRDeathOvers,label=batsman,color=quadrant)) + geom_point() +
xlab("Runs - Death overs") + ylab("Strike rate - Death overs") +
geom_vline(xintercept = x_lower,linetype="dashed") +
geom_hline(yintercept = y_lower,linetype="dashed") +
ggtitle(plot.title)
} else if(plot == 2){
g <- a3 %>%
mutate(quadrant = case_when(runs > x_lower & SRDeathOvers > y_lower ~ "Q1",
runs <= x_lower & SRDeathOvers > y_lower ~ "Q2",
runs <= x_lower & SRDeathOvers <= y_lower ~ "Q3",
TRUE ~ "Q4")) %>%
ggplot(aes(runs,SRDeathOvers,color=quadrant)) +
geom_text(aes(runs,SRDeathOvers,label=batsman,color=quadrant)) + geom_point() +
xlab("Runs - Death overs") + ylab("Strike rate - Death overs") +
geom_vline(xintercept = x_lower,linetype="dashed") +
geom_hline(yintercept = y_lower,linetype="dashed") +
ggtitle(plot.title)
ggplotly(g)
}
} |
squareplot <- function(x,
col = gray(seq(.5,1,length=length(x))),
border=NULL,
nrows=ceiling(sqrt(sum(x))),
ncols=ceiling(sum(x)/nrows),
...
) {
draw.square <- function(x,y,w=1,...) {
polygon(x+c(0,0,w,w,0),y+c(0,w,w,0,0),...)
}
square.size = max(nrows,ncols)
plot.new()
plot.window(xlim=c(0,square.size),ylim=c(-square.size,0))
title(...)
cols = rep(col,x)
for(i in 1:sum(x)) {
x.pos = floor((i-1)/nrows)
y.pos = (i-1) %% nrows
draw.square(x.pos,-y.pos -1,col=cols[i])
}
} |
ncappc <- function(obsFile="nca_original.npctab.dta",
simFile="nca_simulation.1.npctab.dta.zip",
str1Nm=NULL,str1=NULL,
str2Nm=NULL,str2=NULL,
str3Nm=NULL,str3=NULL,
concUnit=NULL,timeUnit=NULL,doseUnit=NULL,
obsLog=FALSE,simLog=obsLog,
psnOut=TRUE,
idNmObs="ID",timeNmObs="TIME",concNmObs="DV",
idNmSim=idNmObs,timeNmSim=timeNmObs,concNmSim=concNmObs,
onlyNCA=FALSE,
AUCTimeRange=NULL,backExtrp=FALSE,
LambdaTimeRange=NULL,LambdaExclude=NULL,doseAmtNm=NULL,
adminType="extravascular",doseType="ns",doseTime=NULL,Tau=NULL,
TI=NULL,method="linearup-logdown",blqNm=NULL,blqExcl=1,
evid=TRUE,evidIncl=0,mdv=FALSE,filterNm=NULL,filterExcl=NULL,
negConcExcl=FALSE,param=c("AUClast","Cmax"),timeFormat="number",
dateColNm=NULL,dateFormat=NULL,spread="npi",
tabCol=c("AUClast","Cmax","Tmax","AUCINF_obs","Vz_obs","Cl_obs","HL_Lambda_z"),
figFormat="tiff",noPlot=FALSE,printOut=TRUE,studyName=NULL,new_data_method=TRUE,
overwrite_SIMDATA=NULL,overwrite_sim_est_file=NULL,outFileNm=NULL,
out_format = "html",
gg_theme=theme_bw(),
parallel=FALSE,
extrapolate=FALSE,
timing = FALSE,
...){
"..density.." <- "meanObs" <- "sprlow" <- "sprhgh" <- "AUClast" <-
"AUCINF_obs" <- "Cmax" <- "Tmax" <- "FCT" <- "ID" <- "STR1" <-
"STR2" <- "STR3" <- "NPDE" <- "mcil" <- "mciu" <- "sdu" <- "sducil" <-
"sduciu" <- "scale_linetype_manual" <- "scale_color_manual" <- "xlab" <-
"ylab" <- "guides" <- "guide_legend" <- "theme" <- "element_text" <-
"unit" <- "element_rect" <- "geom_histogram" <- "aes" <- "geom_vline" <-
"grid.arrange" <- "unit.c" <- "grid.grab" <- "ggsave" <- "facet_wrap" <-
"ggplot" <- "labs" <- "geom_point" <- "geom_errorbarh" <- "knit2html" <-
"knit2pdf" <- "knit" <- "file_test" <- "tail" <- "read.csv" <- "read.table" <-
"dev.off" <- "write.table" <- "head" <- "write.csv" <- "coef" <- "dist" <-
"lm" <- "median" <- "na.omit" <- "percent" <- "qchisq" <- "qnorm" <- "qt" <-
"quantile" <- "scale_y_continuous" <- "sd" <- "STRAT1" <- "STRAT2" <-
"STRAT3" <- "sdcil" <- "sdciu" <- "str" <- NSUB <- NULL
rm(list=c("..density..","meanObs","sprlow","sprhgh","AUClast","AUCINF_obs",
"Cmax","Tmax","FCT","ID","STR1","STR2","STR3","NPDE","mcil","mciu",
"sdu","sducil","sduciu","scale_linetype_manual","scale_color_manual",
"xlab","ylab","guides","guide_legend","theme","element_text","unit",
"element_rect","geom_histogram","aes","geom_vline","grid.arrange",
"unit.c","grid.grab","ggsave","facet_wrap","ggplot","labs",
"geom_point","geom_errorbarh","knit2html","knit2pdf","knit",
"file_test","tail","read.csv","read.table","dev.off","write.table",
"head","write.csv","coef","dist","lm","median","na.omit","percent",
"qchisq","qnorm","qt","quantile","scale_y_continuous","sd","STRAT1",
"STRAT2","STRAT3","sdcil","sdciu","str"))
options(warning.length=5000)
options(scipen=999)
if(!is.null(gg_theme)) theme_set(gg_theme)
usrdir <- getwd()
alwprm <- c("AUClast","AUClower_upper","AUCINF_obs","AUCINF_pred","AUMClast","Cmax","Tmax","HL_Lambda_z")
if (is.null(obsFile)){stop("Name of the file with observed data is required.")}
if (!is.data.frame(obsFile)){
if (!file_test("-f", obsFile)){stop("File for the observed data does not exist.")}
if (!psnOut){
extn <- tail(unlist(strsplit(obsFile, ".", fixed=T)), n=1)
if(extn=="csv"){indf <- read.csv(obsFile)}else{indf <- read.table(obsFile, header=T)}
}else{
message("Note: The observed data file is expected to be generated by PsN since psnOut is set to TRUE.")
indf <- read_nm_table(obsFile)
indf <- as.data.frame(indf)
}
}else{
indf <- obsFile
}
if(!onlyNCA){
if (is.null(simFile)){
message("Note: Simulated data file is not supplied. Only NCA module will be executed.")
onlyNCA <- TRUE
}else{
if (!is.data.frame(simFile) && !file_test("-f", simFile)){
message(paste0("Note: Simulated data file, ",simFile,", is not found in the working directory. Only NCA module will be executed."))
simFile <- NULL
}else{
}
}
}
obsList <- nca.check.obs(obsData=indf,
idNmObs=idNmObs, timeNmObs=timeNmObs, concNmObs=concNmObs,
doseType=doseType, doseTime=doseTime, Tau=Tau,
filterNm=filterNm, filterExcl=filterExcl,
str1Nm=str1Nm, str1=str1,
str2Nm=str2Nm, str2=str2,
str3Nm=str3Nm, str3=str3,
AUCTimeRange=AUCTimeRange, LambdaTimeRange=LambdaTimeRange,
adminType=adminType, TI=TI, doseAmtNm=doseAmtNm,
dateColNm=dateColNm, dateFormat=dateFormat, timeFormat=timeFormat,
concUnit=concUnit, timeUnit=timeUnit, doseUnit=doseUnit,
blqNm=blqNm, blqExcl=blqExcl,evid=evid, evidIncl=evidIncl, mdv=mdv)
indf <- obsList$obsData
refdf <- obsList$refdf
str1 <- obsList$str1
str2 <- obsList$str2
str3 <- obsList$str3
LambdaTimeRange <- obsList$LambdaTimeRange
TI <- obsList$TI
TInum <- obsList$TInum
dateFormat <- obsList$dateFormat
timeFormat <- obsList$timeFormat
dunit <- obsList$dunit
tunit <- obsList$tunit
cunit <- obsList$cunit
aucunit <- obsList$aucunit
aumcunit <- obsList$aumcunit
clunit <- obsList$clunit
vlunit <- obsList$vlunit
doseAmtNm <- obsList$doseAmtNm
rm(obsList)
npr <- length(param)
obsFileNm <- ifelse(is.data.frame(obsFile), deparse(substitute(obsFile)), obsFile)
outData <- data.frame()
popStrNm1 <- NULL
popStrNm2 <- NULL
popStrNm3 <- NULL
if (is.null(str1Nm) & is.null(str2Nm) & is.null(str3Nm)) {case<-1; npopStr<-0}
if (!is.null(str1Nm) & is.null(str2Nm) & is.null(str3Nm)) {case<-2; cpopStrNm<-str1Nm; npopStr<-1; popStrNm1<-str1Nm; popStr1<-str1; npopStr1<-length(str1)}
if (is.null(str1Nm) & !is.null(str2Nm) & is.null(str3Nm)) {case<-2; cpopStrNm<-str2Nm; npopStr<-1; popStrNm1<-str2Nm; popStr1<-str2; npopStr1<-length(str2)}
if (is.null(str1Nm) & is.null(str2Nm) & !is.null(str3Nm)){case<-2; cpopStrNm<-str3Nm; npopStr<-1; popStrNm1<-str3Nm; popStr1<-str3; npopStr1<-length(str3)}
if (!is.null(str1Nm) & !is.null(str2Nm) & is.null(str3Nm)){
case<-3; cpopStrNm<-paste(str1Nm,str2Nm,sep=", "); npopStr<-2; popStrNm1<-str1Nm; popStrNm2<-str2Nm; popStr1<-str1; popStr2<-str2; npopStr1<-length(str1); npopStr2<-length(str2)
}
if (!is.null(str1Nm) & is.null(str2Nm) & !is.null(str3Nm)){
case<-3; cpopStrNm<-paste(str1Nm,str3Nm,sep=", "); npopStr<-2; popStrNm1<-str1Nm; popStrNm2<-str3Nm; popStr1<-str1; popStr2<-str3; npopStr1<-length(str1); npopStr2<-length(str3)
}
if (is.null(str1Nm) & !is.null(str2Nm) & !is.null(str3Nm)){
case<-3; cpopStrNm<-paste(str2Nm,str3Nm,sep=", "); npopStr<-2; popStrNm1<-str2Nm; popStrNm2<-str3Nm; popStr1<-str2; popStr2<-str3; npopStr1<-length(str2); npopStr2<-length(str3)
}
if (!is.null(str1Nm) & !is.null(str2Nm) & !is.null(str3Nm)){
case<-4; cpopStrNm<-paste(str1Nm,str2Nm,str3Nm,sep=", ")
npopStr<-3
popStrNm1<-str1Nm; popStrNm2<-str2Nm; popStrNm3<-str3Nm
popStr1<-str1; popStr2<-str2; popStr3<-str3
npopStr1<-length(str1); npopStr2<-length(str2); npopStr3<-length(str3)
}
if (!is.null(studyName)){
txt <- paste0("Name of the study: \"",studyName,"\"")
txt <- paste(txt,paste0("Name of the file with the observed data: \"",obsFileNm,"\""),sep="\n")
}else{
txt <- paste0("Name of the file with the observed data: \"",obsFileNm,"\"")
}
txt <- paste(txt,paste0("Route of administration: ",adminType),sep="\n")
if (doseType == "ss"){
txt <- paste(txt,paste0("Dose type: steady-state with dosing interval (Tau) of",Tau),sep="\n")
}else{
txt <- paste(txt,"Dose type: non-steady-state",sep="\n")
}
txt <- paste(txt,paste0("No. of population stratification levels: ",npopStr),sep="\n")
if (case==2){
txt <- paste(txt,paste0("Population stratification column: ",cpopStrNm),sep="\n")
txt <- paste(txt,paste0("Population stratification ID within ",popStrNm1,": ",paste(popStr1,collapse=", ")),sep="\n")
}else if (case==3){
txt <- paste(txt,paste0("Population stratification columns: ",cpopStrNm),sep="\n")
txt <- paste(txt,paste0("1st level population stratification ID within ",popStrNm1,": ",paste(popStr1,collapse=", ")),sep="\n")
txt <- paste(txt,paste0("2nd level population stratification ID within ",popStrNm2,": ",paste(popStr2,collapse=", ")),sep="\n")
}else if (case==4){
txt <- paste(txt,paste0("Population stratification columns: ",cpopStrNm),sep="\n")
txt <- paste(txt,paste0("1st level population stratification ID within ",popStrNm1,": ",paste(popStr1,collapse=", ")),sep="\n")
txt <- paste(txt,paste0("2nd level population stratification ID within ",popStrNm2,": ",paste(popStr2,collapse=", ")),sep="\n")
txt <- paste(txt,paste0("3rd level population stratification ID within ",popStrNm3,": ",paste(popStr3,collapse=", ")),sep="\n")
}
concplot <- list(); histobsplot <- list(); popplot <- list(); devplot <- list(); outlierplot <- list()
forestplot <- list(); npdeplot <- list(); histnpdeplot <- list()
PopED::tic()
obs_nca <- estimate_nca(case=case,
pkData=indf,
all_data = refdf,
doseAmtNm=doseAmtNm,
dvLog = obsLog, dataType="obs",
idNm=idNmObs, timeNm=timeNmObs, concNm=concNmObs,
adminType=adminType, TI=TI,
dateColNm=dateColNm, dateFormat=dateFormat, timeFormat=timeFormat,
backExtrp=backExtrp,negConcExcl=negConcExcl,doseType=doseType,
method=method,AUCTimeRange=AUCTimeRange,LambdaTimeRange=LambdaTimeRange,
LambdaExclude=LambdaExclude,doseTime=doseTime,Tau=Tau,simFile=simFile,onlyNCA=onlyNCA,
npopStr1,npopStr2,npopStr3,
popStrNm1,popStrNm2,popStrNm3,
popStr1,popStr2,popStr3,
dunit=dunit,
extrapolate=extrapolate,
...)
nca_obs_time <- PopED::toc(echo = F)
if(timing) message("Time taken to estimate NCA parameters on observed data: ", sprintf("%.3f",nca_obs_time), " seconds.")
outData <- obs_nca$outData
pddf <- obs_nca$pddf
cdata <- obs_nca$cdata
if (!noPlot){
concplot <- dv_vs_idv(case, cdata, concplot, printOut, usrdir, figFormat,
cunit, tunit,
npopStr1, STRAT1, popStr1, popStrNm1,
npopStr2, STRAT2, popStr2, popStrNm2,
npopStr3, STRAT3, popStr3, popStrNm3)
histobsplot <- hist_nca_obs(case, outData, AUClast, AUCINF_obs, Cmax, Tmax, cunit, tunit, spread,
printOut, usrdir, figFormat, histobsplot,
npopStr1, STRAT1, popStr1, popStrNm1,
npopStr2, STRAT2, popStr2, popStrNm2,
npopStr3, STRAT3, popStr3, popStrNm3)
}
statData <- data.frame()
statPrm <- c("N","Nunique","Min","Max","Mean","Median","SD","SE","CVp","CI95l","CI95u","geoMean","gCVp")
ncaPrm <- c("C0","Tmax","Cmax","Cmax_D","Tlast","Clast","AUClast","AUMClast","MRTlast","No_points_Lambda_z",
"AUC_pBack_Ext_obs","AUC_pBack_Ext_pred","AUClower_upper","Rsq","Rsq_adjusted","Corr_XY","Lambda_z",
"HL_Lambda_z","AUCINF_obs","AUCINF_D_obs","AUC_pExtrap_obs","Vz_obs","Cl_obs","AUCINF_pred","AUCINF_D_pred",
"AUC_pExtrap_pred","Vz_pred","Cl_pred","AUMCINF_obs","AUMC_pExtrap_obs","AUMCINF_pred","AUMC_pExtrap_pred",
"MRTINF_obs","MRTINF_pred","Vss_obs","Vss_pred","Tau","Tmin","Cmin","Cavg","p_Fluctuation","Accumulation_Index","Clss")
if (case == 1){
tmpDF <- outData[,ncaPrm]
statData <- sapply(tmpDF, function(x){x<-as.numeric(as.character(x)); if(length(x[complete.cases(x)])<2){rep(NA,13)}else{out.digits(calc.stat(x[complete.cases(x)]),dig=4)}})
statData <- data.frame(statData)
if (nrow(statData) != 0) statData <- cbind(data.frame(Stat=statPrm), statData)
}
if (case == 2){
for (s1 in 1:npopStr1){
tmpDF <- outData[outData$STRAT1==popStr1[s1],ncaPrm]
tmpStat <- sapply(tmpDF, function(x){x<-as.numeric(as.character(x)); if(length(x[complete.cases(x)])<2){rep(NA,13)}else{out.digits(calc.stat(x[complete.cases(x)]),dig=4)}})
tmpStat <- data.frame(tmpStat)
if (nrow(tmpStat) == 0) next
tmpStat <- cbind(data.frame(STRAT1=popStr1[s1],Stat=statPrm), tmpStat)
statData <- rbind(statData, tmpStat)
}
names(statData)[names(statData)%in%"STRAT1"] <- popStrNm1
}
if (case == 3){
for (s1 in 1:npopStr1){
for (s2 in 1:npopStr2){
tmpDF <- outData[outData$STRAT1==popStr1[s1] & outData$STRAT2==popStr2[s2],ncaPrm]
tmpStat <- sapply(tmpDF, function(x){x<-as.numeric(as.character(x)); if(length(x[complete.cases(x)])<2){rep(NA,13)}else{out.digits(calc.stat(x[complete.cases(x)]),dig=4)}})
tmpStat <- data.frame(tmpStat)
if (nrow(tmpStat) == 0) next
tmpStat <- cbind(data.frame(STRAT1=popStr1[s1],STRAT2=popStr2[s2],Stat=statPrm), tmpStat)
statData <- rbind(statData, tmpStat)
}
}
names(statData)[names(statData)%in%c("STRAT1","STRAT2")] <- c(popStrNm1,popStrNm2)
}
if (case == 4){
for (s1 in 1:npopStr1){
for (s2 in 1:npopStr2){
for (s3 in 1:npopStr3){
tmpDF <- outData[outData$STRAT1==popStr1[s1] & outData$STRAT2==popStr2[s2] & outData$STRAT3==popStr3[s3],ncaPrm]
tmpStat <- sapply(tmpDF, function(x){x<-as.numeric(as.character(x)); if(length(x[complete.cases(x)])<2){rep(NA,13)}else{out.digits(calc.stat(x[complete.cases(x)]),dig=4)}})
tmpStat <- data.frame(tmpStat)
if (nrow(tmpStat) == 0) next
tmpStat <- cbind(data.frame(STRAT1=popStr1[s1],STRAT2=popStr2[s2],STRAT3=popStr3[s3],Stat=statPrm), tmpStat)
statData <- rbind(statData, tmpStat)
}
}
}
names(statData)[names(statData)%in%c("STRAT1","STRAT2","STRAT3")] <- c(popStrNm1,popStrNm2,popStrNm3)
}
if (printOut){
if (is.null(outFileNm) || outFileNm==""){
write.table(statData, file=paste0(usrdir,"/ObsStat.tsv"), sep="\t", col.names=T, row.names=F, quote=F)
}else{
write.table(statData, file=paste0(usrdir,"/ObsStat-",outFileNm,".tsv"), sep="\t", col.names=T, row.names=F, quote=F)
}
}
if (is.null(simFile) || onlyNCA){
if (case == 1){
names(outData)[names(outData)%in%c("ID")] <- c(idNmObs)
}
if (case == 2){
names(outData)[names(outData)%in%c("ID","STRAT1")] <- c(idNmObs,popStrNm1)
}
if (case == 3){
names(outData)[names(outData)%in%c("ID","STRAT1","STRAT2")] <- c(idNmObs,popStrNm1,popStrNm2)
}
if (case == 4){
names(outData)[names(outData)%in%c("ID","STRAT1","STRAT2","STRAT3")] <- c(idNmObs,popStrNm1,popStrNm2,popStrNm3)
}
if (case == 1) {prnTab <- head(cbind(outData[,1:2], subset(outData, select = tabCol)),50); names(prnTab)[1:2] <- names(outData)[1:2]}
if (case == 2) {prnTab <- head(cbind(outData[,1:3], subset(outData, select = tabCol)),50); names(prnTab)[1:3] <- names(outData)[1:3]}
if (case == 3) {prnTab <- head(cbind(outData[,1:4], subset(outData, select = tabCol)),50); names(prnTab)[1:4] <- names(outData)[1:4]}
if (case == 4) {prnTab <- head(cbind(outData[,1:5], subset(outData, select = tabCol)),50); names(prnTab)[1:5] <- names(outData)[1:5]}
tabUnit1 <- data.frame(NAME=c("Dose"))
tabUnit2 <- data.frame(NAME=c("C0","Tmax","Cmax","Cmax_D","Tlast","Clast","AUClast","AUMClast","MRTlast","AUClower_upper","Lambda_z","Lambda_z_lower","Lambda_z_upper","HL_Lambda_z","AUCINF_obs","AUCINF_D_obs","Vz_obs","Cl_obs","AUCINF_pred","AUCINF_D_pred","Vz_pred","Cl_pred","AUMCINF_obs","AUMCINF_pred","MRTINF_obs","MRTINF_pred","Tau","Tmin","Cmin","Cavg","AUCtau","AUMCtau","Clss","Vss_obs","Vss_pred"))
tabUnit <- rbind(tabUnit1,tabUnit2)
streamsEnv <- parent.frame()
if (exists("outData")) assign("ncaOutput", outData, envir=streamsEnv)
if (exists("statData")) assign("ObsStat", statData, envir=streamsEnv)
if (exists("concplot")) assign("concPlot", concplot, envir=streamsEnv)
if (exists("histobsplot")) assign("histobsPlot", histobsplot, envir=streamsEnv)
if (printOut){
if (is.null(outFileNm) || outFileNm==""){
write.table(outData, file=paste0(usrdir,"/ncaOutput.tsv"), sep="\t", row.names=F, col.names=T, quote=F)
}else{
write.table(outData, file=paste0(usrdir,"/ncaOutput-",outFileNm,".tsv"), sep="\t", row.names=F, col.names=T, quote=F)
}
fnOut <- list(arglist=match.call(), case=case, TXT=txt, pddf=pddf, prnTab=prnTab, spread=spread, conc=concplot, histobs=histobsplot)
}
}else{
simDir <- paste0(usrdir,"/SIMDATA")
extra_name <- paste0("-",outFileNm)
if (is.null(outFileNm) || outFileNm=="") extra_name <- ""
sim_est_file <- paste0("ncaSimEst",extra_name,".tsv.gz")
if (file.exists(sim_est_file)){
if (is.null(overwrite_sim_est_file)){
if(interactive()){
cat(paste0("\nThe file ", sim_est_file, " already exists.\n"))
cat("Please choose one of the following options:\n")
dirTest <- menu(c("Overwrite it",
"Rename and create a new one",
"Use as it is."))
} else {
dirTest <- "1"
}
}else if (overwrite_sim_est_file){
dirTest <- "1"
}else if (!overwrite_sim_est_file) {
dirTest <- "3"
}
if (dirTest == "1"){
unlink(sim_est_file)
}else if (dirTest == "2"){
print(paste0("\nRenaming ", sim_est_file, " to ", sim_est_file,"_previous\n"))
file.rename(from=sim_est_file, to=paste0(sim_est_file,"_previous"))
}else if (dirTest == "3"){
}else{
setwd(usrdir);stop("Don't know what to do with ",sim_est_file," \n")
}
}else if (file.exists(simDir)){
if (is.null(overwrite_SIMDATA)){
if(interactive()){
cat("\nDirectory \"SIMDATA\" already exists.\n")
cat("Please choose one of the following options:\n")
dirTest <- menu(c("Overwrite it",
"Rename \"SIMDATA\" and create a new one",
"Use \"SIMDATA\" as it is."))
} else {
dirTest <- "1"
}
}else if (overwrite_SIMDATA){
dirTest <- "1"
}else if (!overwrite_SIMDATA) {
dirTest <- "3"
}
if (dirTest == "1"){
unlink(simDir, recursive=TRUE)
dir.create(simDir)
}else if (dirTest == "2"){
print("\nRenaming \"SIMDATA\" to \"SIMDATA_PREVIOUS\"\n")
file.rename(from="SIMDATA", to="SIMDATA_PREVIOUS")
dir.create(simDir)
}else if (dirTest == "3"){
file_list <- list.files(path="./SIMDATA/", pattern="sim_[0-9]*.csv", full.names=T)
}else{
setwd(usrdir);stop("Don't know what to do with \"SIMDATA\" \n")
}
}else{
dirTest <- "0"
}
if (dirTest != 3){
if (is.data.frame(simFile)){
nmdf <- simFile
}else{
if (new_data_method){
message("Reading the simulated data file\n")
nmdf <- read_nm_table(simFile,sim_num = T,sim_name="NSUB")
nmdf <- data.frame(nmdf)
} else {
message("Reading the simulated data file\n")
nmdf <- nca.read.sim(simFile=simFile, MDV.rm=F)
}
}
if (printOut){
if (is.null(outFileNm) || outFileNm==""){
readr::write_delim(nmdf, file.path(usrdir,"ncaSimData.tsv.gz"), delim = "\t")
}else{
readr::write_delim(nmdf, file.path(usrdir,paste0("ncaSimData-",outFileNm,".tsv.gz")), delim = "\t")
}
}
simID <- unique(sort(nmdf$NSUB))
nsim <- length(simID)
dset <- "sim"
simList <- nca.check.sim(simData=nmdf,
idNmSim=idNmSim,timeNmSim=timeNmSim,concNmSim=concNmSim,
filterNm=filterNm,filterExcl=filterExcl,
str1Nm=str1Nm,str1=str1,
str2Nm=str2Nm,str2=str2,
str3Nm=str3Nm,str3=str3,
adminType=adminType,TI=TI,doseAmtNm=doseAmtNm,
blqNm=blqNm,blqExcl=blqExcl,
evid=evid,evidIncl=evidIncl,mdv=mdv)
nmdf <- simList$simData
srdf <- simList$simRefData
str1 <- simList$str1
str2 <- simList$str2
str3 <- simList$str3
doseAmtNm <- simList$doseAmtNm
if (!is.null(str1Nm) & is.null(str2Nm) & is.null(str3Nm)) {case<-2; cpopStrNm<-str1Nm; npopStr<-1; popStrNm1<-str1Nm; popStr1<-str1; npopStr1<-length(str1)}
if (is.null(str1Nm) & !is.null(str2Nm) & is.null(str3Nm)) {case<-2; cpopStrNm<-str2Nm; npopStr<-1; popStrNm1<-str2Nm; popStr1<-str2; npopStr1<-length(str2)}
if (is.null(str1Nm) & is.null(str2Nm) & !is.null(str3Nm)){case<-2; cpopStrNm<-str3Nm; npopStr<-1; popStrNm1<-str3Nm; popStr1<-str3; npopStr1<-length(str3)}
if (!is.null(str1Nm) & !is.null(str2Nm) & is.null(str3Nm)){
case<-3; cpopStrNm<-paste(str1Nm,str2Nm,sep=", "); npopStr<-2; popStrNm1<-str1Nm; popStrNm2<-str2Nm; popStr1<-str1; popStr2<-str2; npopStr1<-length(str1); npopStr2<-length(str2)
}
if (!is.null(str1Nm) & is.null(str2Nm) & !is.null(str3Nm)){
case<-3; cpopStrNm<-paste(str1Nm,str3Nm,sep=", "); npopStr<-2; popStrNm1<-str1Nm; popStrNm2<-str3Nm; popStr1<-str1; popStr2<-str3; npopStr1<-length(str1); npopStr2<-length(str3)
}
if (is.null(str1Nm) & !is.null(str2Nm) & !is.null(str3Nm)){
case<-3; cpopStrNm<-paste(str2Nm,str3Nm,sep=", "); npopStr<-2; popStrNm1<-str2Nm; popStrNm2<-str3Nm; popStr1<-str2; popStr2<-str3; npopStr1<-length(str2); npopStr2<-length(str3)
}
if (!is.null(str1Nm) & !is.null(str2Nm) & !is.null(str3Nm)){
case<-4; cpopStrNm<-paste(str1Nm,str2Nm,str3Nm,sep=", ")
npopStr<-3
popStrNm1<-str1Nm; popStrNm2<-str2Nm; popStrNm3<-str3Nm
popStr1<-str1; popStr2<-str2; popStr3<-str3
npopStr1<-length(str1); npopStr2<-length(str2); npopStr3<-length(str3)
}
PopED::tic()
if(parallel){
parallel <- PopED::start_parallel(parallel,...)
on.exit(if(parallel && (attr(parallel,"type")=="snow")) parallel::stopCluster(attr(parallel,"cluster")))
}
cores <- 1
if(!is.null(attr(parallel, "cores"))) cores <- attr(parallel, "cores")
message("Expected time to estimate NCA parameters on simulated data: ", sprintf("%.3f",(nca_obs_time*(1.2))*nsim/60/cores), " minutes.")
tmp_fun <- function(x,...){
out <- estimate_nca(case=case,
pkData=x,
all_data = srdf,
doseAmtNm=doseAmtNm,
dvLog = simLog, dataType="sim",
idNm=idNmSim, timeNm=timeNmSim, concNm=concNmSim,
adminType=adminType, TI=TI,
dateColNm=dateColNm, dateFormat=dateFormat, timeFormat=timeFormat,
backExtrp=backExtrp,negConcExcl=negConcExcl,doseType=doseType,
method=method,AUCTimeRange=AUCTimeRange,LambdaTimeRange=LambdaTimeRange,
LambdaExclude=LambdaExclude,doseTime=doseTime,Tau=Tau,simFile=simFile,onlyNCA=onlyNCA,
npopStr1,npopStr2,npopStr3,
popStrNm1,popStrNm2,popStrNm3,
popStr1,popStr2,popStr3,
dunit=dunit,
extrapolate=extrapolate,
...)[["outData"]]
out$NSUB <- x$NSUB[1]
return(out)
}
split_data <- split(nmdf,nmdf$NSUB)
if(parallel && (attr(parallel,"type")=="multicore")){
res <- parallel::mclapply(split_data,tmp_fun,...,mc.cores=attr(parallel, "cores"))
} else if(parallel && (attr(parallel,"type")=="snow")){
res <- parallel::parLapply(attr(parallel, "cluster"),split_data,tmp_fun,...)
} else {
res <- lapply(split_data,tmp_fun,...)
}
simData_tot <- dplyr::bind_rows(res)
tmp <- simData_tot %>% dplyr::distinct(NSUB) %>% dplyr::mutate(NSIM=row_number())
simData_tot <- dplyr::left_join(simData_tot,tmp,by="NSUB")
nca_sim_time <- PopED::toc(echo = F)
if(timing) message("Time taken to estimate NCA parameters on simulated data: ",
sprintf("%.3f",nca_sim_time/60),
" minutes.")
if (case == 1) names(simData_tot)[names(simData_tot)%in%c("ID")] <- c(idNmSim)
if (case == 2) names(simData_tot)[names(simData_tot)%in%c("ID","STRAT1")] <- c(idNmSim,popStrNm1)
if (case == 3) names(simData_tot)[names(simData_tot)%in%c("ID","STRAT1","STRAT2")] <- c(idNmSim,popStrNm1,popStrNm2)
if (case == 4) names(simData_tot)[names(simData_tot)%in%c("ID","STRAT1","STRAT2","STRAT3")] <- c(idNmSim,popStrNm1,popStrNm2,popStrNm3)
readr::write_delim(simData_tot, file.path(usrdir,sim_est_file), delim = "\t")
} else {
if (file.exists(sim_est_file)){
simData_tot <- suppressMessages(readr::read_delim(file.path(usrdir,sim_est_file),delim = "\t"))
nsim <- max(simData_tot$NSIM)
simData_tot <- as.data.frame(simData_tot)
} else if(file.exists(simDir)){
lasdf <- lapply(list.files(path = simDir, pattern="sim_[0-9]*.csv",full.names=T),function(i){read.csv(i, header=T)})
nsim <- length(lasdf)
simData_tot <- do.call(rbind, lapply(lasdf, as.data.frame))
rm(lasdf)
}
}
dasdf <- simData_tot
rm(simData_tot)
if (case==1) names(dasdf)[match(c(idNmSim),names(dasdf))] <- c("ID")
if (case==2) names(dasdf)[match(c(idNmSim,popStrNm1),names(dasdf))] <- c("ID","STRAT1")
if (case==3) names(dasdf)[match(c(idNmSim,popStrNm1,popStrNm2),names(dasdf))] <- c("ID","STRAT1","STRAT2")
if (case==4) names(dasdf)[match(c(idNmSim,popStrNm1,popStrNm2,popStrNm3),names(dasdf))] <- c("ID","STRAT1","STRAT2","STRAT3")
if (npr<=2){
hth<-14; wth<-15; phth<-7; pwth<-6
}else if (npr>2 & npr<=4){
hth<-20; wth<-16; phth<-8; pwth<-7
}else if (npr>4 & npr<=6){
hth<-26; wth<-16; phth<-9; pwth<-8
}else if (npr>6){
hth<-26; wth<-22; phth<-9; pwth<-10
}
if (!noPlot) pop_hist_list <- hist_mean_var(obs_data=outData, sim_data=dasdf,
param=param,
strat_vars=c(popStrNm1,popStrNm2,popStrNm3))
if (!onlyNCA){
devcol <- paste0("d",param)
npdecol <- paste0("npde",param)
ggOpt_forest <- list(xlab("\nNPDE"),ylab(""),
labs(title = "Forest plot of NPDE\nErrorbar = 95% confidence interval\n"),
scale_color_manual(name="",values=c("mean"="red","SD"="darkgreen")),
theme(axis.text.x = element_text(vjust=1,hjust=1,size=10),
axis.text.y = element_text(hjust=0,size=10),
strip.text.x = element_text(size=10),
legend.text = element_text(size=12),
title = element_text(size=14,face="bold"),
legend.position = "bottom", legend.direction = "horizontal",
legend.background = element_rect(),
legend.key.height = unit(1,"cm")),
facet_wrap(~type, scales="fixed", ncol=2))
OTL <- data.frame(No_of_outliers=numeric(0),ID_metric=character(0))
npde <- data.frame()
fpval <- data.frame(type=character(0),mean=numeric(0),mcil=numeric(0),mciu=numeric(0),sdu=numeric(0),sducil=numeric(0),sduciu=numeric(0),str=character(0))
}
if (case == 1){
tdasdf <- dasdf
id <- unique(tdasdf$ID)
pde <- data.frame()
metric <- ""
nout <- 0
for (i in 1:length(id)){
obsdata <- subset(outData, ID==id[i])
simdata <- subset(tdasdf, ID==id[i])
figlbl <- NULL
pdeout <- nca.pde.deviation.outlier(obsdata=obsdata,simdata=simdata,idNm="ID",id=id[i],spread=spread,figlbl=figlbl,calcparam=alwprm,diagparam=param,cunit=cunit,tunit=tunit,noPlot=noPlot,onlyNCA=onlyNCA)
pde <- rbind(pde, cbind(data.frame(ID=id[i]), pdeout$pde))
outData[outData$ID==id[i],] <- pdeout$obsdata
if (!onlyNCA && pdeout$metric != ""){
nout <- nout + 1
metric <- paste(metric,pdeout$metric,sep=", ")
if (!noPlot){
gdr <- pdeout$grob
mylegend <- pdeout$legend
lheight <- pdeout$lheight
if (printOut){
fl <- paste0(usrdir,"/Outlier_ID-",id[i])
if (figFormat=="tiff"){
eval(parse(text=paste0(figFormat,"(file=\"",fl,".",figFormat,"\",height=",hth,",width=",wth,",units=\"cm\",compression=\"lzw\",res=120)")))
}else{
eval(parse(text=paste0(figFormat,"(file=\"",fl,".",figFormat,"\",height=",hth,",width=",wth,",units=\"cm\",res=120)")))
}
suppressMessages(suppressWarnings(grid.arrange(gdr,mylegend, heights=unit.c(unit(1, "npc") - lheight, lheight))))
dev.off()
}
suppressMessages(suppressWarnings(grid.arrange(gdr,mylegend, heights=unit.c(unit(1, "npc") - lheight, lheight))))
ggr <- grid.grab()
outlierplot[[length(outlierplot)+1]] <- ggr
}
}
}
if (!onlyNCA){
if (metric != "") metric <- gsub("^, ", "", metric)
OTL <- rbind(OTL, data.frame(No_of_outlier=nout,ID_metric=metric))
npde <- rbind(npde,pde)
npde <- nca.npde(pdedata=npde,pdecol=alwprm)
npdeNm <- paste0("npde",alwprm)
for (r in 1:nrow(outData)){
if (nrow(npde[npde$ID==outData$ID[r],])!=1){
outData[r,npdeNm] <- NaN
}else{
outData[r,npdeNm] <- npde[npde$ID==outData$ID[r],npdeNm]
}
}
plotdata <- outData
if (nrow(plotdata) != 0) {
figlbl <- "All data"
if (!noPlot){
ggdev <- nca.deviation.plot(plotdata=plotdata,xvar="ID",devcol=devcol,figlbl=figlbl,spread=spread,cunit=cunit,tunit=tunit)
if (!is.null(ggdev)){
suppressMessages(suppressWarnings(print(ggdev)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/Deviation_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
devplot[[length(devplot)+1]] <- ggdev
}
}
npdeout <- nca.npde.plot(plotdata=plotdata,xvar="ID",npdecol=npdecol,figlbl=figlbl,cunit=cunit,tunit=tunit)
if (!is.null(npdeout$forestdata)) {
forestdata <- npdeout$forestdata
forestdata$str <- figlbl
fpval <- rbind(fpval, forestdata)
if (!noPlot){
npdeplot[[length(npdeplot)+1]] <- npdeout$ggnpde
suppressMessages(suppressWarnings(print(npdeout$ggnpde)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/NPDE_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
histnpdeplot[[length(histnpdeplot)+1]] <- npdeout$gghnpde
suppressMessages(suppressWarnings(print(npdeout$gghnpde)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/HistNPDE_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
}
if (!noPlot){
fpval$FCT <- paste0("mean=",signif(fpval$mean,2),"+/-CI=",signif(fpval$mcil,2),",",signif(fpval$mciu,2),", SD=",signif(fpval$sd,2),"+/-CI=",signif(fpval$sdcil,2),",",signif(fpval$sdciu,2))
xlim1 <- floor(min(fpval$mcil)); xlim2 <- ceiling(fpval$sdciu)
ggplt <- ggplot(fpval) + ggOpt_forest +
geom_point(aes(mean,str,color="mean"), show.legend=T, size=2) +
geom_errorbarh(aes(y=str,xmin=mcil,xmax=mciu),size=0.4, color="red",height=0.1) +
geom_point(aes(sd,str,color="SD"), size=2) +
geom_errorbarh(aes(y=str,xmin=sdcil,xmax=sdciu), size=0.4, color="darkgreen", height=0.1) +
geom_text(aes(label=out.digits(mean,dig=2),x=mean,y=str,color="mean",vjust=-1),size=4,show.legend=F) +
geom_text(aes(label=out.digits(mcil,dig=2),x=mcil,y=str,color="mean",vjust=-2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(mciu,dig=2),x=mciu,y=str,color="mean",vjust=-2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sd,dig=2),x=sd,y=str,color="SD",vjust=1.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sdcil,dig=2),x=sdcil,y=str,color="SD",vjust=2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sdciu,dig=2),x=sdciu,y=str,color="SD",vjust=2.5),size=4,show.legend=F)
suppressMessages(suppressWarnings(print(ggplt)))
forestplot[[length(forestplot)+1]] <- ggplt
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/ForestNPDE.",figFormat),height=hth,width=wth,units="cm",dpi=120)))
}
}
}
}
}else if (case==2){
for (s1 in 1:npopStr1){
if (nrow(dasdf[dasdf$STRAT1==popStr1[s1],]) == 0) next
tdasdf <- subset(dasdf, STRAT1==popStr1[s1])
id <- unique(tdasdf$ID)
pde <- data.frame()
metric <- ""
nout <- 0
figlbl <- paste0(popStrNm1,"-",popStr1[s1])
for (i in 1:length(id)){
obsdata <- subset(outData, ID==id[i] & STRAT1==popStr1[s1])
simdata <- subset(tdasdf, ID==id[i])
pdeout <- nca.pde.deviation.outlier(obsdata=obsdata,simdata=simdata,idNm="ID",id=id[i],spread=spread,figlbl=figlbl,calcparam=alwprm,diagparam=param,cunit=cunit,tunit=tunit,noPlot=noPlot,onlyNCA=onlyNCA)
pde <- rbind(pde, cbind(data.frame(ID=id[i],STRAT1=popStr1[s1]), pdeout$pde))
outData[(outData$ID==id[i] & outData$STRAT1==popStr1[s1]),] <- pdeout$obsdata
if (!onlyNCA && pdeout$metric != ""){
nout <- nout + 1
metric <- paste(metric,pdeout$metric,sep=", ")
if (!noPlot){
gdr <- pdeout$grob
mylegend <- pdeout$legend
lheight <- pdeout$lheight
if (printOut){
fl <- paste0(usrdir,"/Outlier_ID-",id[i],"_",figlbl)
if (figFormat=="tiff"){
eval(parse(text=paste0(figFormat,"(file=\"",fl,".",figFormat,"\",height=",hth,",width=",wth,",units=\"cm\",compression=\"lzw\",res=120)")))
}else{
eval(parse(text=paste0(figFormat,"(file=\"",fl,".",figFormat,"\",height=",hth,",width=",wth,",units=\"cm\",res=120)")))
}
suppressMessages(suppressWarnings(grid.arrange(gdr,mylegend, heights=unit.c(unit(1, "npc") - lheight, lheight))))
dev.off()
}
suppressMessages(suppressWarnings(grid.arrange(gdr,mylegend, heights=unit.c(unit(1, "npc") - lheight, lheight))))
ggr <- grid.grab()
outlierplot[[length(outlierplot)+1]] <- ggr
}
}
}
if (!onlyNCA){
if (metric != "") metric <- gsub("^, ", "", metric)
OTL <- rbind(OTL, data.frame(No_of_outlier=nout,ID_metric=metric))
npde <- rbind(npde,pde)
}
}
if (!onlyNCA){
npde <- nca.npde(pdedata=npde,pdecol=alwprm)
npdeNm <- paste0("npde",alwprm)
for (r in 1:nrow(outData)){
if (nrow(npde[(npde$ID==outData$ID[r] & npde$STRAT1==outData$STRAT1[r]),])!=1){
outData[r,npdeNm] <- NaN
}else{
outData[r,paste0("npde",alwprm)] <- npde[(npde$ID==outData$ID[r] & npde$STRAT1==outData$STRAT1[r]),paste0("npde",alwprm)]
}
}
for (s1 in 1:npopStr1){
plotdata <- subset(outData, STRAT1==popStr1[s1])
if (nrow(plotdata) == 0) next
figlbl <- paste0(popStrNm1,"-",popStr1[s1])
if (!noPlot){
ggdev <- nca.deviation.plot(plotdata=plotdata,xvar="ID",devcol=devcol,figlbl=figlbl,spread=spread,cunit=cunit,tunit=tunit)
if (!is.null(ggdev)){
suppressMessages(suppressWarnings(print(ggdev)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/Deviation_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
devplot[[length(devplot)+1]] <- ggdev
}
}
npdeout <- nca.npde.plot(plotdata=plotdata,xvar="ID",npdecol=npdecol,figlbl=figlbl,cunit=cunit,tunit=tunit)
if (is.null(npdeout$forestdata)) next
forestdata <- npdeout$forestdata
forestdata$str <- figlbl
fpval <- rbind(fpval, forestdata)
if (!noPlot){
npdeplot[[length(npdeplot)+1]] <- npdeout$ggnpde
suppressMessages(suppressWarnings(print(npdeout$ggnpde)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/NPDE_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
histnpdeplot[[length(histnpdeplot)+1]] <- npdeout$gghnpde
suppressMessages(suppressWarnings(print(npdeout$gghnpde)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/HistNPDE_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
}
}
if (!noPlot){
fpval$FCT <- paste0("mean=",signif(fpval$mean,2),"+/-CI=",signif(fpval$mcil,2),",",signif(fpval$mciu,2),", SD=",signif(fpval$sd,2),"+/-CI=",signif(fpval$sdcil,2),",",signif(fpval$sdciu,2))
xlim1 <- floor(min(fpval$mcil)); xlim2 <- ceiling(fpval$sdciu)
ggplt <- ggplot(fpval) + ggOpt_forest +
geom_point(aes(mean,str,color="mean"), show.legend=T, size=2) +
geom_errorbarh(aes(y=str,xmin=mcil,xmax=mciu),size=0.4, color="red",height=0.1) +
geom_point(aes(sd,str,color="SD"), size=2) +
geom_errorbarh(aes(y=str,xmin=sdcil,xmax=sdciu), size=0.4, color="darkgreen", height=0.1) +
geom_text(aes(label=out.digits(mean,dig=2),x=mean,y=str,color="mean",vjust=-1),size=4,show.legend=F) +
geom_text(aes(label=out.digits(mcil,dig=2),x=mcil,y=str,color="mean",vjust=-2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(mciu,dig=2),x=mciu,y=str,color="mean",vjust=-2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sd,dig=2),x=sd,y=str,color="SD",vjust=1.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sdcil,dig=2),x=sdcil,y=str,color="SD",vjust=2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sdciu,dig=2),x=sdciu,y=str,color="SD",vjust=2.5),size=4,show.legend=F)
suppressMessages(suppressWarnings(print(ggplt)))
forestplot[[length(forestplot)+1]] <- ggplt
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/ForestNPDE.",figFormat),height=hth,width=wth,units="cm",dpi=120)))
}
}
}else if (case == 3){
for (s1 in 1:npopStr1){
for (s2 in 1:npopStr2){
if (nrow(dasdf[dasdf$STRAT1==popStr1[s1] & dasdf$STRAT2==popStr2[s2],]) == 0) next
tdasdf <- subset(dasdf, STRAT1==popStr1[s1] & STRAT2==popStr2[s2])
id <- unique(tdasdf$ID)
pde <- data.frame()
metric <- ""
nout <- 0
for (i in 1:length(id)){
obsdata <- subset(outData, ID==id[i] & STRAT1==popStr1[s1] & STRAT2==popStr2[s2])
simdata <- subset(tdasdf, ID==id[i])
figlbl <- paste0(popStrNm1,"-",popStr1[s1],"_",popStrNm2,"-",popStr2[s2])
pdeout <- nca.pde.deviation.outlier(obsdata=obsdata,simdata=simdata,idNm="ID",id=id[i],spread=spread,figlbl=figlbl,calcparam=alwprm,diagparam=param,cunit=cunit,tunit=tunit,noPlot=noPlot,onlyNCA=onlyNCA)
pde <- rbind(pde, cbind(data.frame(ID=id[i],STRAT1=popStr1[s1],STRAT2=popStr2[s2]), pdeout$pde))
outData[(outData$ID==id[i] & outData$STRAT1==popStr1[s1] & outData$STRAT2==popStr2[s2]),] <- pdeout$obsdata
if (!onlyNCA && pdeout$metric != ""){
nout <- nout + 1
metric <- paste(metric,pdeout$metric,sep=", ")
if (!noPlot){
gdr <- pdeout$grob
mylegend <- pdeout$legend
lheight <- pdeout$lheight
if (printOut){
fl <- paste0(usrdir,"/Outlier_ID-",id[i],"_",figlbl)
if (figFormat=="tiff"){
eval(parse(text=paste0(figFormat,"(file=\"",fl,".",figFormat,"\",height=",hth,",width=",wth,",units=\"cm\",compression=\"lzw\",res=120)")))
}else{
eval(parse(text=paste0(figFormat,"(file=\"",fl,".",figFormat,"\",height=",hth,",width=",wth,",units=\"cm\",res=120)")))
}
suppressMessages(suppressWarnings(grid.arrange(gdr,mylegend, heights=unit.c(unit(1, "npc") - lheight, lheight))))
dev.off()
}
suppressMessages(suppressWarnings(grid.arrange(gdr,mylegend, heights=unit.c(unit(1, "npc") - lheight, lheight))))
ggr <- grid.grab()
outlierplot[[length(outlierplot)+1]] <- ggr
}
}
}
if (!onlyNCA){
if (metric != "") metric <- gsub("^, ", "", metric)
OTL <- rbind(OTL, data.frame(No_of_outlier=nout,ID_metric=metric))
npde <- rbind(npde,pde)
}
}
}
if (!onlyNCA){
npde <- nca.npde(pdedata=npde,pdecol=alwprm)
npdeNm <- paste0("npde",alwprm)
for (r in 1:nrow(outData)){
if (nrow(npde[(npde$ID==outData$ID[r] & npde$STRAT1==outData$STRAT1[r] & npde$STRAT2==outData$STRAT2[r]),])!=1){
outData[r,npdeNm] <- NaN
}else{
outData[r,paste0("npde",alwprm)] <- npde[(npde$ID==outData$ID[r] & npde$STRAT1==outData$STRAT1[r] & npde$STRAT2==outData$STRAT2[r]),paste0("npde",alwprm)]
}
}
for (s1 in 1:npopStr1){
for (s2 in 1:npopStr2){
plotdata <- subset(outData, STRAT1==popStr1[s1] & STRAT2==popStr2[s2])
if (nrow(plotdata) == 0) next
figlbl <- paste0(popStrNm1,"-",popStr1[s1],"_",popStrNm2,"-",popStr2[s2])
if (!noPlot){
ggdev <- nca.deviation.plot(plotdata=plotdata,xvar="ID",devcol=devcol,figlbl=figlbl,spread=spread,cunit=cunit,tunit=tunit)
if (!is.null(ggdev)){
suppressMessages(suppressWarnings(print(ggdev)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/Deviation_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
devplot[[length(devplot)+1]] <- ggdev
}
}
npdeout <- nca.npde.plot(plotdata=plotdata,xvar="ID",npdecol=npdecol,figlbl=figlbl,cunit=cunit,tunit=tunit)
if (is.null(npdeout$forestdata)) next
forestdata <- npdeout$forestdata
forestdata$str <- figlbl
fpval <- rbind(fpval, forestdata)
if (!noPlot){
npdeplot[[length(npdeplot)+1]] <- npdeout$ggnpde
suppressMessages(suppressWarnings(print(npdeout$ggnpde)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/NPDE_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
histnpdeplot[[length(histnpdeplot)+1]] <- npdeout$gghnpde
suppressMessages(suppressWarnings(print(npdeout$gghnpde)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/HistNPDE_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
}
}
}
if (!noPlot){
fpval$FCT <- paste0("mean=",signif(fpval$mean,2),"+/-CI=",signif(fpval$mcil,2),",",signif(fpval$mciu,2),", SD=",signif(fpval$sd,2),"+/-CI=",signif(fpval$sdcil,2),",",signif(fpval$sdciu,2))
xlim1 <- floor(min(fpval$mcil)); xlim2 <- ceiling(fpval$sdciu)
ggplt <- ggplot(fpval) + ggOpt_forest +
geom_point(aes(mean,str,color="mean"), show.legend=T, size=2) +
geom_errorbarh(aes(y=str,xmin=mcil,xmax=mciu),size=0.4, color="red",height=0.1) +
geom_point(aes(sd,str,color="SD"), size=2) +
geom_errorbarh(aes(y=str,xmin=sdcil,xmax=sdciu), size=0.4, color="darkgreen", height=0.1) +
geom_text(aes(label=out.digits(mean,dig=2),x=mean,y=str,color="mean",vjust=-1),size=4,show.legend=F) +
geom_text(aes(label=out.digits(mcil,dig=2),x=mcil,y=str,color="mean",vjust=-2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(mciu,dig=2),x=mciu,y=str,color="mean",vjust=-2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sd,dig=2),x=sd,y=str,color="SD",vjust=1.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sdcil,dig=2),x=sdcil,y=str,color="SD",vjust=2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sdciu,dig=2),x=sdciu,y=str,color="SD",vjust=2.5),size=4,show.legend=F)
suppressMessages(suppressWarnings(print(ggplt)))
forestplot[[length(forestplot)+1]] <- ggplt
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/ForestNPDE.",figFormat),height=hth,width=wth,units="cm",dpi=120)))
}
}
}else if (case == 4){
for (s1 in 1:npopStr1){
for (s2 in 1:npopStr2){
for (s3 in 1:npopStr3){
if (nrow(dasdf[dasdf$STRAT1==popStr1[s1] & dasdf$STRAT2==popStr2[s2] & dasdf$STRAT3==popStr3[s3],]) == 0) next
tdasdf <- subset(dasdf, STRAT1==popStr1[s1] & STRAT2==popStr2[s2] & STRAT3==popStr3[s3])
id <- unique(tdasdf$ID)
pde <- data.frame()
metric <- ""
nout <- 0
for (i in 1:length(id)){
obsdata <- subset(outData, ID==id[i] & STRAT1==popStr1[s1] & STRAT2==popStr2[s2] & STRAT3==popStr3[s3])
simdata <- subset(tdasdf, ID==id[i])
if (nrow(obsdata)==0 | nrow(simdata)==0) next
figlbl <- paste0(popStrNm1,"-",popStr1[s1],"_",popStrNm2,"-",popStr2[s2],"_",popStrNm3,"-",popStr3[s3])
pdeout <- nca.pde.deviation.outlier(obsdata=obsdata,simdata=simdata,idNm="ID",id=id[i],spread=spread,figlbl=figlbl,calcparam=alwprm,diagparam=param,cunit=cunit,tunit=tunit,noPlot=noPlot,onlyNCA=onlyNCA)
pde <- rbind(pde, cbind(data.frame(ID=id[i],STRAT1=popStr1[s1],STRAT2=popStr2[s2],STRAT3=popStr3[s3]), pdeout$pde))
outData[(outData$ID==id[i] & outData$STRAT1==popStr1[s1] & outData$STRAT2==popStr2[s2] & outData$STRAT3==popStr3[s3]),] <- pdeout$obsdata
if (!onlyNCA && pdeout$metric != ""){
nout <- nout + 1
metric <- paste(metric,pdeout$metric,sep=", ")
if (!noPlot){
gdr <- pdeout$grob
mylegend <- pdeout$legend
lheight <- pdeout$lheight
if (printOut){
fl <- paste0(usrdir,"/Outlier_ID-",id[i],"_",figlbl)
if (figFormat=="tiff"){
eval(parse(text=paste0(figFormat,"(file=\"",fl,".",figFormat,"\",height=",hth,",width=",wth,",units=\"cm\",compression=\"lzw\",res=120)")))
}else{
eval(parse(text=paste0(figFormat,"(file=\"",fl,".",figFormat,"\",height=",hth,",width=",wth,",units=\"cm\",res=120)")))
}
suppressMessages(suppressWarnings(grid.arrange(gdr,mylegend, heights=unit.c(unit(1, "npc") - lheight, lheight))))
dev.off()
}
suppressMessages(suppressWarnings(grid.arrange(gdr,mylegend, heights=unit.c(unit(1, "npc") - lheight, lheight))))
ggr <- grid.grab()
outlierplot[[length(outlierplot)+1]] <- ggr
}
}
}
if (!onlyNCA){
if (metric != "") metric <- gsub("^, ", "", metric)
OTL <- rbind(OTL, data.frame(No_of_outlier=nout,ID_metric=metric))
npde <- rbind(npde,pde)
}
}
}
}
if (!onlyNCA){
npde <- nca.npde(pdedata=npde,pdecol=alwprm)
npdeNm <- paste0("npde",alwprm)
for (r in 1:nrow(outData)){
if (nrow(npde[(npde$ID==outData$ID[r] & npde$STRAT1==outData$STRAT1[r] & npde$STRAT2==outData$STRAT2[r] & npde$STRAT3==outData$STRAT3[r]),])!=1){
outData[r,npdeNm] <- NaN
}else{
outData[r,paste0("npde",alwprm)] <- npde[(npde$ID==outData$ID[r] & npde$STRAT1==outData$STRAT1[r] & npde$STRAT2==outData$STRAT2[r] & npde$STRAT3==outData$STRAT3[r]),paste0("npde",alwprm)]
}
}
for (s1 in 1:npopStr1){
for (s2 in 1:npopStr2){
for (s3 in 1:npopStr3){
plotdata <- subset(outData, STRAT1==popStr1[s1] & STRAT2==popStr2[s2] & STRAT3==popStr3[s3])
if (nrow(plotdata) == 0) next
figlbl <- paste0(popStrNm1,"-",popStr1[s1],"_",popStrNm2,"-",popStr2[s2],"_",popStrNm3,"-",popStr3[s3])
if (!noPlot){
ggdev <- nca.deviation.plot(plotdata=plotdata,xvar="ID",devcol=devcol,figlbl=figlbl,spread=spread,cunit=cunit,tunit=tunit)
if (!is.null(ggdev)){
suppressMessages(suppressWarnings(print(ggdev)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/Deviation_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
devplot[[length(devplot)+1]] <- ggdev
}
}
npdeout <- nca.npde.plot(plotdata=plotdata,xvar="ID",npdecol=npdecol,figlbl=figlbl,cunit=cunit,tunit=tunit)
if (is.null(npdeout$forestdata)) next
forestdata <- npdeout$forestdata
forestdata$str <- figlbl
fpval <- rbind(fpval, forestdata)
if (!noPlot){
npdeplot[[length(npdeplot)+1]] <- npdeout$ggnpde
suppressMessages(suppressWarnings(print(npdeout$ggnpde)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/NPDE_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
histnpdeplot[[length(histnpdeplot)+1]] <- npdeout$gghnpde
suppressMessages(suppressWarnings(print(npdeout$gghnpde)))
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/HistNPDE_",figlbl,".",figFormat),height=hth,width=wth,units="cm",dpi=120)))
}
}
}
}
if (!noPlot){
fpval$FCT <- paste0("mean=",signif(fpval$mean,2),"+/-CI=",signif(fpval$mcil,2),",",signif(fpval$mciu,2),", SD=",signif(fpval$sd,2),"+/-CI=",signif(fpval$sdcil,2),",",signif(fpval$sdciu,2))
xlim1 <- floor(min(fpval$mcil)); xlim2 <- ceiling(fpval$sdciu)
ggplt <- ggplot(fpval) + ggOpt_forest +
geom_point(aes(mean,str,color="mean"), show.legend=T, size=2) +
geom_errorbarh(aes(y=str,xmin=mcil,xmax=mciu),size=0.4, color="red",height=0.1) +
geom_point(aes(sd,str,color="SD"), size=2) +
geom_errorbarh(aes(y=str,xmin=sdcil,xmax=sdciu), size=0.4, color="darkgreen", height=0.1) +
geom_text(aes(label=out.digits(mean,dig=2),x=mean,y=str,color="mean",vjust=-1),size=4,show.legend=F) +
geom_text(aes(label=out.digits(mcil,dig=2),x=mcil,y=str,color="mean",vjust=-2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(mciu,dig=2),x=mciu,y=str,color="mean",vjust=-2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sd,dig=2),x=sd,y=str,color="SD",vjust=1.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sdcil,dig=2),x=sdcil,y=str,color="SD",vjust=2.5),size=4,show.legend=F) +
geom_text(aes(label=out.digits(sdciu,dig=2),x=sdciu,y=str,color="SD",vjust=2.5),size=4,show.legend=F)
suppressMessages(suppressWarnings(print(ggplt)))
forestplot[[length(forestplot)+1]] <- ggplt
if (printOut) suppressMessages(suppressWarnings(ggsave(filename=paste0(usrdir,"/ForestNPDE.",figFormat),height=hth,width=wth,units="cm",dpi=120)))
}
}
}
statDataSim <- data.frame()
statPrm <- c("N","Nunique","Min","Max","Mean","Median","SD","SE","CVp","CI95l","CI95u","geoMean","gCVp")
ncaPrm <- c("Tmax","Cmax","AUClast","AUClower_upper","AUCINF_obs","AUC_pExtrap_obs","AUCINF_pred","AUC_pExtrap_pred","AUMClast","AUMCINF_obs","AUMC_pExtrap_obs","AUMCINF_pred","AUMC_pExtrap_pred","HL_Lambda_z","Rsq","Rsq_adjusted","No_points_Lambda_z")
if (case == 1){
tmpDF <- dasdf[,ncaPrm]
statDataSim <- sapply(tmpDF, function(x){x<-as.numeric(as.character(x)); if(length(x[complete.cases(x)])<2){rep(NA,13)}else{out.digits(calc.stat(x[complete.cases(x)]),dig=4)}})
statDataSim <- data.frame(statDataSim)
if (nrow(statDataSim) != 0) statDataSim <- cbind(data.frame(Stat=statPrm), statDataSim)
}
if (case == 2){
for (s1 in 1:npopStr1){
tmpDF <- dasdf[dasdf$STRAT1==popStr1[s1],ncaPrm]
tmpStat <- sapply(tmpDF, function(x){x<-as.numeric(as.character(x)); if(length(x[complete.cases(x)])<2){rep(NA,13)}else{out.digits(calc.stat(x[complete.cases(x)]),dig=4)}})
tmpStat <- data.frame(tmpStat)
if (nrow(tmpStat) == 0) next
tmpStat <- cbind(data.frame(STRAT1=popStr1[s1],Stat=statPrm), tmpStat)
statDataSim <- rbind(statDataSim, tmpStat)
}
names(statDataSim)[names(statDataSim)%in%"STRAT1"] <- popStrNm1
}
if (case == 3){
for (s1 in 1:npopStr1){
for (s2 in 1:npopStr2){
tmpDF <- dasdf[dasdf$STRAT1==popStr1[s1] & dasdf$STRAT2==popStr2[s2],ncaPrm]
tmpStat <- sapply(tmpDF, function(x){x<-as.numeric(as.character(x)); if(length(x[complete.cases(x)])<2){rep(NA,13)}else{out.digits(calc.stat(x[complete.cases(x)]),dig=4)}})
tmpStat <- data.frame(tmpStat)
if (nrow(tmpStat) == 0) next
tmpStat <- cbind(data.frame(STRAT1=popStr1[s1],STRAT2=popStr2[s2],Stat=statPrm), tmpStat)
statDataSim <- rbind(statDataSim, tmpStat)
}
}
names(statDataSim)[names(statDataSim)%in%c("STRAT1","STRAT2")] <- c(popStrNm1,popStrNm2)
}
if (case == 4){
for (s1 in 1:npopStr1){
for (s2 in 1:npopStr2){
for (s3 in 1:npopStr3){
tmpDF <- dasdf[dasdf$STRAT1==popStr1[s1] & dasdf$STRAT2==popStr2[s2] & dasdf$STRAT3==popStr3[s3],ncaPrm]
tmpStat <- sapply(tmpDF, function(x){x<-as.numeric(as.character(x)); if(length(x[complete.cases(x)])<2){rep(NA,13)}else{out.digits(calc.stat(x[complete.cases(x)]),dig=4)}})
tmpStat <- data.frame(tmpStat)
if (nrow(tmpStat) == 0) next
tmpStat <- cbind(data.frame(STRAT1=popStr1[s1],STRAT2=popStr2[s2],STRAT3=popStr3[s3],Stat=statPrm), tmpStat)
statDataSim <- rbind(statDataSim, tmpStat)
}
}
}
names(statDataSim)[names(statDataSim)%in%c("STRAT1","STRAT2","STRAT3")] <- c(popStrNm1,popStrNm2,popStrNm3)
}
if (printOut){
if (is.null(outFileNm) || outFileNm==""){
write.table(statDataSim, file=paste0(usrdir,"/SimStat.tsv"), sep="\t", col.names=T, row.names=F, quote=F)
}else{
write.table(statDataSim, file=paste0(usrdir,"/SimStat-",outFileNm,".tsv"), sep="\t", col.names=T, row.names=F, quote=F)
}
}
if (case == 1){
names(outData)[names(outData)%in%c("ID")] <- c(idNmObs)
}
if (case == 2){
names(outData)[names(outData)%in%c("ID","STRAT1")] <- c(idNmObs,popStrNm1)
}
if (case == 3){
names(outData)[names(outData)%in%c("ID","STRAT1","STRAT2")] <- c(idNmObs,popStrNm1,popStrNm2)
}
if (case == 4){
names(outData)[names(outData)%in%c("ID","STRAT1","STRAT2","STRAT3")] <- c(idNmObs,popStrNm1,popStrNm2,popStrNm3)
}
if (case == 1) prnTab <- head(cbind(outData[,1:2], subset(outData, select = tabCol)),50)
if (case == 2) prnTab <- head(cbind(outData[,1:3], subset(outData, select = tabCol)),50)
if (case == 3) prnTab <- head(cbind(outData[,1:4], subset(outData, select = tabCol)),50)
if (case == 4) prnTab <- head(cbind(outData[,1:5], subset(outData, select = tabCol)),50)
streamsEnv <- parent.frame()
if (exists("outData")) assign("ncaOutput", outData, envir=streamsEnv)
if (exists("statData")) assign("ObsStat", statData, envir=streamsEnv)
if (exists("statDataSim")) assign("SimStat", statDataSim, envir=streamsEnv)
if (exists("nmdf")) assign("ncaSimData", nmdf, envir=streamsEnv)
if (exists("dasdf")) assign("ncaSimEst", dasdf, envir=streamsEnv)
if (exists("concplot")) assign("concPlot", concplot, envir=streamsEnv)
if (exists("histobsplot")) assign("histobsPlot", histobsplot, envir=streamsEnv)
if (exists("popplot")) assign("popPlot", popplot, envir=streamsEnv)
if (!onlyNCA){
if (exists("devplot")) assign("devPlot", devplot, envir=streamsEnv)
if (exists("outlierplot")) assign("outlierPlot", outlierplot, envir=streamsEnv)
if (exists("forestplot")) assign("forestPlot", forestplot, envir=streamsEnv)
if (exists("npdeplot")) assign("npdePlot", npdeplot, envir=streamsEnv)
if (exists("histnpdeplot")) assign("histnpdePlot", histnpdeplot, envir=streamsEnv)
}
if (printOut){
simFileNm <- ifelse(is.data.frame(simFile), deparse(substitute(simFile)), simFile)
txt <- paste(txt,paste0("Name of the NONMEM simulation output file: \"",simFileNm,"\""),sep="\n")
txt <- paste(txt,paste0("Number of simulations performed: ",nsim),sep="\n")
if (is.null(outFileNm) || outFileNm==""){
write.table(outData, file=paste0(usrdir,"/ncaOutput.tsv"), sep="\t", row.names=F, col.names=T, quote=F)
}else{
write.table(outData, file=paste0(usrdir,"/ncaOutput-",outFileNm,".tsv"), sep="\t", row.names=F, col.names=T, quote=F)
}
if (!onlyNCA){
pddf <- cbind(pddf,OTL); names(pddf)[c((ncol(pddf)-1),ncol(pddf))] <- c("No. of outliers","Outlier IDs and outlying metrics")
fnOut <- list(arglist=match.call(), case=case, TXT=txt, pddf=pddf, prnTab=prnTab, NSIM=nsim, spread=spread, conc=concplot, histobs=histobsplot, pop=popplot, dev=devplot, outlier=outlierplot, forest=forestplot, npde=npdeplot, histnpde=histnpdeplot, phth=phth, pwth=pwth)
}else{
fnOut <- list(arglist=match.call(), case=case, TXT=txt, pddf=pddf, prnTab=prnTab, NSIM=nsim, spread=spread, conc=concplot, histobs=histobsplot, pop=popplot, phth=phth, pwth=pwth)
}
}
}
if (printOut){
misc <- system.file("misc", package = "ncappc")
if (is.null(simFile) || onlyNCA){
mdFile <- paste(misc,"ncappcReport-NCA.Rmd",sep="/")
nwFile <- paste(misc,"ncappcReport-NCA.Rnw",sep="/")
if (is.null(outFileNm) || outFileNm==""){
outNm <- paste0("ncappcReport-NCA.tex")
}else{
outNm <- paste0("ncappcReport-NCA-",outFileNm,".tex")
}
}else{
mdFile <- paste(misc,"ncappcReport-NCA-PPC.Rmd",sep="/")
nwFile <- paste(misc,"ncappcReport-NCA-PPC.Rnw",sep="/")
if (is.null(outFileNm) || outFileNm==""){
outNm <- paste0("ncappcReport-NCA-PPC.tex")
}else{
outNm <- paste0("ncappcReport-NCA-PPC-",outFileNm,".tex")
}
}
rmd_name <- "ncappc_report"
if(!is.null(outFileNm)) rmd_name <- paste0(rmd_name,"-",outFileNm)
rmd_name <- paste0(rmd_name,".Rmd")
file.copy(paste(misc,"ncappc_report.Rmd",sep="/"),rmd_name,overwrite = TRUE)
file.copy(paste(misc,"styles.tex",sep="/"),"styles.tex",overwrite = TRUE)
file.copy(paste(misc,"styles2.tex",sep="/"),"styles2.tex",overwrite = TRUE)
file.copy(paste(misc,"custom.css",sep="/"),"custom.css",overwrite = TRUE)
message("\nprocessing file:",rmd_name,"\n")
if(out_format == "html"){
out_file_name <- rmarkdown::render(rmd_name,output_format = "bookdown::html_document2",quiet = T)
}
if(out_format == "pdf"){
out_file_name <- rmarkdown::render(rmd_name,output_format = "bookdown::pdf_document2",quiet = T)
}
if(out_format == "all"){
out_file_name <- rmarkdown::render(rmd_name,output_format = "all",quiet = T)
}
if(out_format == "first"){
out_file_name <- rmarkdown::render(rmd_name,quiet = T)
}
message("Output created:\n ",paste(out_file_name,collapse = "\n "),"\n")
}
unlink(list.files(pattern = "^.*ncappcReport-.*aux$|^.*ncappcReport-.*log$|^.*ncappcReport-.*out$|^.*ncappcReport-.*toc$|^.*ncappcReport-.*md$"))
unlink(list.files(pattern = "sum.tex"))
unlink(list.files(pattern = "tab.tex"))
unlink(list.files(pattern = "knitr.sty"))
if(!exists("fnOut")) fnOut <- list()
fnOut$ncaOutput <- outData
invisible(fnOut)
} |
context("XML Functions")
compareHelpFilesWithXML <- function(){
xmlConfig <- spotGUI:::xmlGetAllConfiguredControlElements()
configComplete = T
namesConfig <- names(xmlConfig)
for(i in 1:length(namesConfig)){
inXML <- xmlConfig[[i]]
inHelp <- names(spotGUI:::getAllHelpControlListParams(namesConfig[i]))
if("types" %in% inHelp){
inXML <- c(inXML,"types")
}
if(!base::setequal(inXML,inHelp) & !(length(inHelp) == 0)){
configComplete <- F
cat(namesConfig[i],"\n
cat(paste(base::setdiff(inXML,inHelp),base::setdiff(inHelp,inXML),"\n\n"))
}
if(length(inHelp) == 0){
cat(namesConfig[i],"\n
cat("is Empty!","\n\n")
}
}
return(configComplete)
}
|
x <- SmallData$x; y <- SmallData$y
Sxx <- sum((x - mean(x))^2); Sxx
Sxy <- sum((x - mean(x)) * (y - mean(y))); Sxy
r <- 1 / 3 * sum((x - mean(x)) / sd(x) * (y - mean(y)) / sd(y)); r
slope <- r * sd(y) / sd(x); slope
intercept <- mean(y) - slope * mean(x); intercept |
data <- mtcars %>%
tibble::rownames_to_column("model") %>%
tibble::as_tibble() %>%
dplyr::mutate(
manufacturer = stringr::str_split(model, " ", simplify = TRUE)[, 1])
data$cyl[1] <- NA
data$manufacturer[2] <- NA
test_that("cat_contrast rejects a data argument that is not a dataframe", {
msg <- "The \"data\" argument is not a dataframe."
expect_error(cat_contrast(NULL, "cyl", "manufacturer", "Merc"), msg)
expect_error(cat_contrast(NA, "cyl", "manufacturer", "Merc"), msg)
expect_error(cat_contrast(1:10, "cyl", "manufacturer", "Merc"), msg)
expect_error(cat_contrast(LETTERS[1:10], "cyl", "manufacturer", "Merc"), msg)
expect_error(cat_contrast(c(TRUE, FALSE), "cyl", "manufacturer", "Merc"), msg)
expect_error(cat_contrast(list(), "cyl", "manufacturer", "Merc"), msg)
})
test_that("cat_contrast rejects a data argument that has no rows", {
msg <- "The \"data\" argument is empty."
expect_error(cat_contrast(data.frame(), "cyl", "manufacturer", "Merc"), msg)
})
test_that("cat_contrast rejects invalid row_cat arguments", {
msg <- "Invalid \"row_cat\" argument. Must be a character vector of length one."
expect_error(cat_contrast(data, NULL, "manufacturer", "Merc"), msg)
expect_error(cat_contrast(data, NA, "manufacturer", "Merc"), msg)
expect_error(cat_contrast(data, 1:10, "manufacturer", "Merc"), msg)
expect_error(cat_contrast(data, LETTERS[1:10], "manufacturer", "Merc"), msg)
expect_error(cat_contrast(data, c(TRUE, FALSE), "manufacturer", "Merc"), msg)
expect_error(cat_contrast(data, list(), "manufacturer", "Merc"), msg)
})
test_that("cat_contrast rejects a row_cat argument that is not a column in the data", {
msg <- "'notacolumn' is not a column in the dataframe."
expect_error(cat_contrast(data, "notacolumn", "manufacturer", "Merc"), msg)
})
test_that("cat_contrast rejects invalid col_cat arguments", {
msg <- "Invalid \"col_cat\" argument. Must be a character vector of length one."
expect_error(cat_contrast(data, "cyl", NULL, "Merc"), msg)
expect_error(cat_contrast(data, "cyl", NA, "Merc"), msg)
expect_error(cat_contrast(data, "cyl", 1:10, "Merc"), msg)
expect_error(cat_contrast(data, "cyl", LETTERS[1:10], "Merc"), msg)
expect_error(cat_contrast(data, "cyl", c(TRUE, FALSE), "Merc"), msg)
expect_error(cat_contrast(data, "cyl", list(), "Merc"), msg)
})
test_that("cat_contrast rejects a col_cat argument that is not a column in the data", {
msg <- "'notacolumn' is not a column in the dataframe."
expect_error(cat_contrast(data, "cyl", "notacolumn", "Merc"), msg)
})
test_that("cat_contrast rejects invalid col_group arguments", {
msg <- "Invalid \"col_group\" argument. Must be a character vector of length one."
expect_error(cat_contrast(data, "cyl", "manufacturer", NULL), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", NA), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", 1:10), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", LETTERS[1:10]), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", c(TRUE, FALSE)), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", list()), msg)
})
test_that("cat_contrast rejects a col_group argument that does not exist in col_cat", {
msg <- "The \"col_group\" 'notagroup' does not exist in the \"col_cat\" 'manufacturer'."
expect_error(cat_contrast(data, "cyl", "manufacturer", "notagroup"), msg)
})
test_that("cat_contrast rejects invalid na.rm.row arguments", {
msg <- "Invalid \"na.rm.row\" argument. Must be either TRUE or FALSE."
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.row = NULL), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.row = NA), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.row = 1), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.row = ""), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.row = 1:10), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.row = LETTERS[1:10]), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.row = c(TRUE, FALSE)), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.row = list()), msg)
})
test_that("cat_contrast rejects invalid na.rm.col arguments", {
msg <- "Invalid \"na.rm.col\" argument. Must be either TRUE or FALSE."
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.col = NULL), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.col = NA), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.col = 1), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.col = ""), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.col = 1:10), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.col = LETTERS[1:10]), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.col = c(TRUE, FALSE)), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm.col = list()), msg)
})
test_that("cat_contrast rejects invalid na.rm arguments", {
msg <- "Invalid \"na.rm\" argument. Must be either NULL, TRUE or FALSE."
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm = NA), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm = 1), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm = ""), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm = 1:10), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm = LETTERS[1:10]), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm = c(TRUE, FALSE)), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na.rm = list()), msg)
})
test_that("cat_contrast rejects invalid clean_names arguments", {
msg <- "Invalid \"clean_names\" argument. Must be either TRUE or FALSE."
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", clean_names = NULL), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", clean_names = NA), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", clean_names = 1), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", clean_names = ""), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", clean_names = 1:10), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", clean_names = LETTERS[1:10]), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", clean_names = c(TRUE, FALSE)), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", clean_names = list()), msg)
})
test_that("cat_contrast rejects invalid only arguments", {
msg <- "Invalid \"only\" argument. Must be a character vector of length one."
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", only = NULL), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", only = NA), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", only = 1), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", only = TRUE), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", only = 1:10), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", only = LETTERS[1:10]), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", only = c(TRUE, FALSE)), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", only = list()), msg)
})
test_that("cat_contrast rejects invalid other_label arguments", {
msg <- "Invalid \"other_label\" argument. Must be a character vector of length one."
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", other_label = NULL), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", other_label = NA), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", other_label = 1), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", other_label = TRUE), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", other_label = 1:10), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", other_label = LETTERS[1:10]), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", other_label = c(TRUE, FALSE)), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", other_label = list()), msg)
})
test_that("cat_contrast rejects invalid na_label arguments", {
msg <- "Invalid \"na_label\" argument. Must be a character vector of length one."
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na_label = NULL), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na_label = NA), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na_label = 1), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na_label = TRUE), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na_label = 1:10), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na_label = LETTERS[1:10]), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na_label = c(TRUE, FALSE)), msg)
expect_error(cat_contrast(data, "cyl", "manufacturer", "Merc", na_label = list()), msg)
})
test_that("cat_contrast returns correct data with defaults", {
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(data, "cyl", "manufacturer", "Merc")
expect_equal(observed, expected)
})
test_that("cat_contrast returns correct data with a valid na.rm.row argument", {
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
na.rm.row = FALSE)
expect_equal(observed, expected)
expected <- tibble::tibble(
cyl = c(8, 4, 6),
n_merc = c(3, 2, 2),
n_other = c(11, 9, 3),
n_na = c(0, 0, 1),
p_merc = c( 0.42857143, 0.28571429, 0.28571429),
p_other = c(0.47826087, 0.39130435, 0.13043478),
p_na = c(0, 0, 1))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
na.rm.row = TRUE)
expect_equal(observed, expected)
})
test_that("cat_contrast returns correct data with a valid na.rm.col argument", {
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
na.rm.col = FALSE)
expect_equal(observed, expected)
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
na.rm.col = TRUE)
expect_equal(observed, expected)
})
test_that("cat_contrast returns correct data with a valid na.rm argument", {
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
na.rm = FALSE)
expect_equal(observed, expected)
expected <- tibble::tibble(
cyl = c(8, 4, 6),
n_merc = c(3, 2, 2),
n_other = c(11, 9, 3),
p_merc = c( 0.42857143, 0.28571429, 0.28571429),
p_other = c(0.47826087, 0.39130435, 0.13043478))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
na.rm = TRUE)
expect_equal(observed, expected)
})
test_that("cat_contrast returns correct data with a valid only argument", {
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
only = "ignore")
expect_equal(observed, expected)
expected_number <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
only = "n")
expect_equal(observed, expected_number)
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
only = "number")
expect_equal(observed, expected_number)
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
only = " number ")
expect_equal(observed, expected_number)
expected_percent <- tibble::tibble(
cyl = c(8, 4, 6, NA),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
only = "p")
expect_equal(observed, expected_percent)
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
only = "percent")
expect_equal(observed, expected_percent)
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
only = " percent ")
expect_equal(observed, expected_percent)
})
test_that("cat_contrast returns correct data with a valid clean_names argument", {
data$Cyl <- data$cyl
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"Cyl",
"manufacturer",
"Merc",
clean_names = TRUE)
expect_equal(observed, expected)
expected <- tibble::tibble(
Cyl = c(8, 4, 6, NA),
n_Merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_Merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"Cyl",
"manufacturer",
"Merc",
clean_names = FALSE)
expect_equal(observed, expected)
})
test_that("cat_contrast uses option for default clean_names argument", {
data$Cyl <- data$cyl
restore_option <- getOption("tabbycat.clean_names")
options(tabbycat.clean_names = TRUE)
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"Cyl",
"manufacturer",
"Merc")
expect_equal(observed, expected)
options(tabbycat.clean_names = FALSE)
expected <- tibble::tibble(
Cyl = c(8, 4, 6, NA),
n_Merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_Merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"Cyl",
"manufacturer",
"Merc")
expect_equal(observed, expected)
options(tabbycat.clean_names = restore_option)
})
test_that("cat_contrast returns correct data with a valid na_label argument", {
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_missing = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_missing = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
na_label = "missing")
expect_equal(observed, expected)
})
test_that("cat_contrast uses option for default na_label argument", {
restore_option <- getOption("tabbycat.na_label")
options(tabbycat.na_label = "missing")
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_other = c(11, 9, 3, 1),
n_missing = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_other = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_missing = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc")
expect_equal(observed, expected)
options(tabbycat.na_label = restore_option)
})
test_that("cat_contrast returns correct data with a valid other_label argument", {
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_remainder = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_remainder = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc",
other_label = "remainder")
expect_equal(observed, expected)
})
test_that("cat_contrast uses option for default other_label argument", {
restore_option <- getOption("tabbycat.other_label")
options(tabbycat.other_label = "remainder")
expected <- tibble::tibble(
cyl = c(8, 4, 6, NA),
n_merc = c(3, 2, 2, 0),
n_remainder = c(11, 9, 3, 1),
n_na = c(0, 0, 1, 0),
p_merc = c(0.42857143, 0.28571429, 0.28571429, 0.0),
p_remainder = c(0.45833333, 0.37500000, 0.12500000, 0.04166667),
p_na = c(0, 0, 1, 0))
observed <- cat_contrast(
data,
"cyl",
"manufacturer",
"Merc")
expect_equal(observed, expected)
options(tabbycat.other_label = restore_option)
}) |
cards_info <- function(board_id){
if (!exists("key_token_exists", envir = globals)){
return(warning("Need to set the key/token using 'set_key_token()'"))
} else {
key <- globals$trello_api_key_01142021
token <- globals$trello_api_token_01142021
}
cards_info <- GET(paste0("https://api.trello.com/1/boards/", board_id, "/cards?key=", key, "&token=",token))
cards_content <- content(cards_info)
num_cards <- length(cards_content)
cards <- c()
card_id <- c()
last_modified <- c()
list <- c()
list_name <- c()
lists <- content(GET(paste0("https://api.trello.com/1/boards/", board_id, "/lists?key=", key, "&token=",token)))
for (i in 1:num_cards){
cards[i] <- cards_content[[i]]$name
card_id[i] <- cards_content[[i]]$id
last_modified[i] <- unlist(strsplit(cards_content[[i]]$dateLastActivity, "T"))[1]
list[i] <- cards_content[[i]]$idList
for (j in 1:length(lists)){
if (list[i] == lists[[j]]$id){
list_name[i] <- lists[[j]]$name
}
}
}
trello_activity <- data.frame(cards[1:num_cards], card_id[1:num_cards], last_modified[1:num_cards], list_name[1:num_cards])
colnames(trello_activity) <- c("Card", "ID", "Date last modified", "Trello List")
trello_activity
} |
context("Checking rm_citation_tex")
test_that("rm_citation_tex is removing citation strings",{
x <- c(
"I say \\parencite*{Ted2005, Moe1999} go there in \\textcite{Few2010} said to.",
"But then \\authorcite{Ware2013} siad it was so \\pcite[see][p. 22]{Get9999c}.",
"then I \\citep[p. 22]{Foo1882c} him")
expect_equivalent(rm_citation_tex(x),
c("I say go there in said to.", "But then siad it was so .", "then I him")
)
})
test_that("rm_citation_tex is extracting citation strings",{
x <- c(
"I say \\parencite*{Ted2005, Moe1999} go there in \\textcite{Few2010} said to.",
"But then \\authorcite{Ware2013} siad it was so \\pcite[see][p. 22]{Get9999c}.",
"then I \\citep[p. 22]{Foo1882c} him")
expect_equivalent(rm_citation_tex(x, extract=TRUE),
list(c("Ted2005", "Moe1999", "Few2010"), c("Ware2013", "Get9999c"
), "Foo1882c")
)
}) |
FVPA = function(y, t, q= 0.1, optns = list(error=TRUE, FVEthreshold = 0.9)){
if( (q <0) || (1 < q) ){
warning("The value of 'q' is outside [0,1]; reseting to 0.1.")
}
if(is.null(optns$error)){
stop("User provided 'optns' has to provided 'error' information.")
}
if(is.null(optns$FVEthreshold)){
stop("User provided 'optns' has to provided 'FVEthreshold' information.")
}
if(!optns$error){
stop("FVPA is irrelevant if no error is assumed")
}
if (!is.null(optns[['useBinnedData']]) && optns[['useBinnedData']] == 'FORCE') {
stop("optns$useBinnedData cannot be 'FORCE'")
}
optns[['useBinnedData']] <- 'OFF'
fpcaObjY <- FPCA(y, t, optns)
if( fpcaObjY$optns$dataType != 'Dense' ){
stop(paste0("The data has to be 'Dense' for FVPA to be relevant; the current dataType is : '", fpcaObjY$optns$dataType,"'!") )
}
yFitted <- fitted(fpcaObjY);
rawRes = GetVarianceProcess(y, t, yFitted, workGrid = fpcaObjY$workGrid, delta = 0, logarithm = FALSE )
delta = quantile(unlist(rawRes), q);
rm(rawRes)
logRes = GetVarianceProcess(y, t, yFitted, workGrid = fpcaObjY$workGrid, delta = delta, logarithm = TRUE )
fpcaObjR = FPCA(logRes, t, optns);
return( list( sigma2 = fpcaObjR$sigma2, fpcaObjY = fpcaObjY, fpcaObjR = fpcaObjR))
}
GetVarianceProcess = function(y, t, yFitted, workGrid, delta =0.0, logarithm = FALSE){
r <- list()
for (i in 1:nrow(yFitted)){
tempV = delta + ( y[[i]] - approx(x = workGrid, y = yFitted[i,], xout = t[[i]])$y )^2
if(logarithm){
r[[i]] = log(tempV);
} else {
r[[i]] = tempV;
}
}
return(r)
} |
aldvmm.getnames <- function(X,
names,
lcoef,
lcpar,
lcmp,
ncmp) {
if (lcoef[1] %in% names) {
name.beta <- c(paste(paste0(lcmp,
rep(1:ncmp, each = dim(X[[lcoef[1]]])[2])),
rep(lcoef[1],
times = ncmp,
each = dim(X[[lcoef[1]]])[2]),
rep(colnames(X[[lcoef[1]]]),
times = ncmp),
sep = "_"))
} else {
name.beta <- NULL
}
if (ncmp > 1 & lcoef[2] %in% names) {
name.delta <- c(paste(paste0(lcmp,
rep(1:(ncmp - 1),
each = dim(X[[lcoef[2]]])[2])),
rep(lcoef[2],
times = (ncmp - 1),
each = dim(X[[lcoef[2]]])[2]),
rep(colnames(X[[lcoef[2]]]),
times = ncmp - 1),
sep = "_"))
} else {
name.delta <- NULL
}
if (sum(lcpar %in% names) > 0) {
name.cpar <- c()
for (i in lcpar) {
name.cpar <- c(name.cpar, paste(paste0(lcmp, 1:ncmp),
rep(lcpar, times = ncmp),
sep = "_"))
}
} else {
name.cpar <- NULL
}
return(c(name.beta, name.delta, name.cpar))
} |
robgit_RPS <- function(X, consenso = FALSE) {
adjustament = FALSE
if (ncol(X[, , 1]) == 2) {
X <- adjustment3D(X)
adjustament = TRUE
}
tol <- 1e-09
iterTotal <- 20
Z <- X
f = nrow(Z[, , 1])
c = ncol(Z[, , 1])
r = ncol(Z[, 1, ])
res <- matrix(nrow = f, ncol = r, 0)
resme <- matrix(nrow = 1, ncol = r, 0)
restot <- 0
auxres <- matrix(nrow = f, ncol = r, 0)
auxresme <- matrix(nrow = 1, ncol = r, 0)
mejora <- matrix(nrow = f + 1, ncol = r, 0)
Y <- matrix(nrow = f, ncol = c, 0)
W <- matrix(nrow = f, ncol = c, 0)
R <- array(matrix(nrow = f, ncol = c, 0), c(f, c, r + 1), dimnames = NULL)
X <- array(matrix(nrow = f, ncol = c, 0), c(f, c, r), dimnames = NULL)
X0 <- X
E <- matrix(nrow = f, ncol = f, 0)
A <- matrix(nrow = f, ncol = f, 0)
Aux <- array(matrix(nrow = f, ncol = c, 0), c(f, c, r), dimnames = NULL)
H <- array(matrix(nrow = 3, ncol = 3, 0), c(3, 3, r), dimnames = NULL)
p <- matrix(nrow = 1, ncol = r, 1)
TR <- matrix(nrow = f, ncol = c, 0)
X <- Z
s <- 0
X <- initialFocus(X, f, r)
X <- adjustmentScale(X, r)
Y <- spatialmed_config(X)
for (k in 1:r) {
for (i in 1:f) {
res[i, k] <- norm(t(as.matrix(Y[i, ])) - t(as.matrix(X[i, , k])), "F")
}
resme[1, k] <- sum(res[, k])
}
residual <- sum(resme)
residualant <- 0
z <- 1
Aux <- X
conteo <- matrix(nrow = f + 1, ncol = r, 0)
conteomed <- matrix(nrow = 1, ncol = r, 0)
while ((z <= iterTotal) & (abs(residual - residualant) > tol)) {
for (k in 1:r) {
Aux[, , k] <- scaleSpecimen(Aux[, , k], Y)
list_out <- rotation(Aux[, , k], H[, , k], Y)
Aux[, , k] <- list_out[[1]]
H[, , k] <- list_out[[2]]
Aux[, , k] <- translation(Aux[, , k], Y, f)
for (i in 1:f) {
auxres[i, k] <- norm(t(as.matrix(Y[i, ])) - t(as.matrix(Aux[i, , k])), "F")
if (auxres[i, k] <= res[i, k]) {
conteo[i, k] <- 1
} else {
conteo[i, k] <- 0
}
}
auxresme[1, k] <- median(auxres[, k])
auxresme[1, k]
}
for (k in 1:r) {
if (auxresme[1, k] <= resme[1, k]) {
X[, , k] <- Aux[, , k]
conteomed[1, k] <- 1
} else {
conteomed[1, k] <- 0
}
}
conteo[f + 1, ] <- matrix(nrow = 1, ncol = r, 0)
conteo[f + 1, ] <- (100 * apply(conteo, 2, sum))/f
for (k in 1:r) {
for (i in 1:f) {
res[i, k] <- norm(t(as.matrix(Y[i, ])) - t(as.matrix(X[i, , k])), "F")
}
resme[1, k] <- sum(res[, k])
}
W <- Y
Y <- spatialmed_config(X)
residualant <- residual
residual <- sum(resme)
z <- (z + 1)
}
if (adjustament == TRUE) {
V <- array(matrix(nrow = f, ncol = 2, 0), c(f, 2, r + 1), dimnames = NULL)
for (i in 1:r) {
U <- X[, , i]
U <- U[, -3]
V[, , i] <- U
}
U <- Y
U <- U[, -3]
if (consenso) {
V[, , r + 1] <- U
return(V)
} else {
return(V[, , -(r + 1)])
}
} else {
R[, , 1:r] <- X
if (consenso) {
R[, , r + 1] <- Y
return(R)
} else {
return(R[, , -(r + 1)])
}
}
}
adjustment3D <- function(X) {
f <- nrow(X[, , 1])
r <- ncol(X[, 1, ])
R <- array(matrix(nrow = f, ncol = 3, 0), c(f, 3, r), dimnames = NULL)
for (i in 1:r) {
R[, , i] <- cbind(X[, , i], 0)
}
return(R)
}
adjustmentScale <- function(X, r) {
for (k in 1:r) {
s <- medland(X[, , k], 2)
X[, , k] <- X[, , k]/s
}
return(X)
}
angurot <- function(R) {
t = (sum(diag(R)) - 1)/2
v <- acos(pmin(pmax(t, -1), 1))
if (v < (-pi)) {
v <- (v + (2 * pi))
} else if (v > pi) {
v <- (v - (2 * pi))
}
return(v)
}
distAllPairsL2 <- function(X) {
q <- t(X) %*% X
n <- ncol(q)
normx <- matlab::repmat(as.matrix(apply(t(X)^2, 1, sum)), 1, n)
K <- Re(sqrtm(q * (-2) + normx + t(normx)))
K <- K - (diag(diag(K)))
return(K)
}
ejerot <- function(R) {
toler = 1e-16
for (i in 1:3) {
for (j in 1:3) {
if (abs(R[i]) < toler) {
R[i] <- 0
}
}
}
tol = 1e-11
dif = abs(R - diag(3))
count = 1
i = 1
while (i <= 3) {
j = 1
while (j <= 3) {
if (dif[[i, j]] < tol) {
count = count + 1
}
j = j + 1
}
i = i + 1
}
if (count < 9) {
H <- R - diag(3)
V <- MASS::Null(t(H) %*% H)
} else {
V <- matrix(nrow = 1, ncol = 3, 0)
V[1, 3] <- 1
}
for (i in 1:3) {
if (abs(V[i]) < tol) {
V[i] <- 0
}
}
if (V[3] < 0) {
V <- -V
}
v <- t(V)
return(V)
}
escala <- function(X, Y) {
n <- nrow(X)
P <- matrix(nrow = n, ncol = n, 1)
for (i in 1:n) {
for (j in i + 1:n) {
if (j <= n) {
P[i, j] <- norm(t(as.matrix(Y[i, ])) - t(as.matrix(Y[j, ])), "F")/norm(t(as.matrix(X[i,
])) - t(as.matrix(X[j, ])), "F")
P[j, i] <- P[i, j]
}
}
}
return(P)
}
estimorot3D <- function(X, Y, i, j) {
tol_norm = 1e-11
dim <- ncol(X)
A <- matrix(nrow = dim, ncol = dim, 0)
B <- matrix(nrow = dim, ncol = dim, 0)
v <- matrix(nrow = 1, ncol = dim, 0)
w <- matrix(nrow = 1, ncol = dim, 0)
a3 <- matrix(nrow = 1, ncol = dim, 0)
b3 <- matrix(nrow = 1, ncol = dim, 0)
if (i == j) {
R = diag(3)
} else {
A[1, ] = (X[j, ] - X[i, ])/norm(t(as.matrix(X[j, ])) - t(as.matrix(X[i, ])), "F")
B[1, ] = (Y[j, ] - Y[i, ])/norm(t(as.matrix(Y[j, ])) - t(as.matrix(Y[i, ])), "F")
v <- t(as.matrix(vector.cross(A[1, ], X[j, ])))
w <- t(as.matrix(vector.cross(B[1, ], Y[j, ])))
normav <- norm(v, "F")
normaw <- norm(w, "F")
if ((normav > tol_norm) & (normaw > tol_norm)) {
A[2, ] <- v/normav
B[2, ] <- w/normaw
norm(as.matrix(A[2, ]), "F")
a3 <- t(as.matrix(vector.cross(A[1, ], A[2, ])))
A[3, ] <- a3/norm(a3, "F")
b3 <- t(as.matrix(vector.cross(B[1, ], B[2, ])))
B[3, ] <- b3/norm(b3, "F")
R <- t(A) %*% B
} else if ((normav < tol_norm) & (normaw < tol_norm)) {
v <- t(as.matrix(vector.cross(A[1, ], B[1, ])))
w <- v
normav <- norm(v, "F")
if (normav < tol_norm) {
R <- diag(3)
} else {
A[2, ] <- v/normav
B[2, ] <- A[2, ]
a3 <- t(as.matrix(vector.cross(A[1, ], A[2, ])))
A[3, ] <- a3/norm(a3, "F")
b3 <- t(as.matrix(vector.cross(B[1, ], B[2, ])))
B[3, ] <- b3/norm(b3, "F")
R <- t(A) %*% B
}
} else {
R <- diag(3)
}
}
return(R)
}
initialFocus <- function(X, f, r) {
for (k in 1:r) {
taux <- matrix(nrow = 1, ncol = 3, 0)
taux <- spatialmed_landmark(X[, , k])
print(taux)
X[, , k] <- X[, , k] - (matrix(nrow = f, ncol = 1, 1) %*% taux)
}
return(X)
}
matrizrot <- function(a) {
H <- matrix(nrow = 2, ncol = 2, 0)
H[1, 1] <- cos(a)
H[1, 2] <- sin(a)
H[2, 1] <- -sin(a)
H[2, 2] <- cos(a)
return(H)
}
matrizrot3D <- function(e, a) {
AF <- matrix(nrow = 3, ncol = 3, 0)
Bloque <- matrix(nrow = 3, ncol = 3, 0)
R <- matrix(nrow = 3, ncol = 3, 0)
Bloque[3, 3] <- 1
Bloque[1:2, 1:2] = matrizrot(a)
V = MASS::Null(t(e))
AF[3, ] <- e
AF[1:2, ] <- t(V)
R <- t(AF) %*% Bloque %*% AF
return(R)
}
medianarep <- function(A) {
ASIND <- sindiagonal(A)
f <- nrow(A)
aux <- matrix(nrow = f, ncol = 1, 0)
for (i in 1:f) {
aux[i, 1] <- median(ASIND[i, ])
}
m <- median(aux)
return(m)
}
medland <- function(A, z) {
f <- nrow(A)
b <- matrix(nrow = (f * (f - 1))/2, ncol = 1, 0)
aux <- matrix(nrow = f, ncol = 1, 0)
k <- 1
for (i in 1:f) {
aux[i, 1] <- norm(t(as.matrix(A[i, ])), "F")
for (j in i + 1:f) {
if (j <= f) {
b[k, 1] <- norm(t(as.matrix(A[i, ])) - t(as.matrix(A[j, ])), "F")
k <- (k + 1)
}
}
}
if (z == 1) {
s <- median(aux)
}
if (z == 2) {
s <- median(b)
}
if (z == 3) {
s <- sum(aux)
}
return(s)
}
rotation <- function(X, H, Y) {
eje <- matrix(nrow = 1, ncol = 3, 0)
tita <- 0
aux_list <- rot3D(X, Y)
eje <- aux_list[[1]]
tita <- aux_list[[2]]
H <- matrizrot3D(eje, tita)
X <- X %*% H
return(list(X, H))
}
scaleSpecimen <- function(X, Y) {
E <- escala(X, Y)
ro <- medianarep(E)
X <- ro * X
return(X)
}
sindiagonal <- function(B) {
f <- nrow(B)
c <- (ncol(B) - 1)
A <- matrix(nrow = f, ncol = c, 0)
for (i in 1:f) {
for (j in 1:c) {
if (i <= j) {
A[i, j] <- B[i, j + 1]
} else {
A[i, j] <- B[i, j]
}
}
}
return(A)
}
spatialmed_config <- function(X) {
n = nrow(X[, , 1])
p = ncol(X[, , 1])
r = ncol(X[, 1, ])
A <- matrix(nrow = r, ncol = p, 0)
M <- matrix(nrow = n, ncol = p, 0)
w <- matrix(nrow = 1, ncol = r, 1)
s <- matrix(nrow = 1, ncol = r, 1)
aux <- matrix(nrow = 1, ncol = p, 0)
i <- 1
for (i in 1:n) {
for (k in 1:r) {
A[k, ] = X[i, , k]
}
aux <- spatialmed_landmark(A)
M[i, ] <- aux
aux <- matrix(nrow = 1, ncol = p, 0)
s <- matrix(nrow = 1, ncol = r, 0)
A <- matrix(nrow = r, ncol = p, 0)
}
return(M)
}
spatialmed_landmark <- function(X) {
tol = 1e-09
n <- nrow(X)
p <- ncol(X)
m <- matrix(nrow = 1, ncol = p, 0)
A <- matrix(nrow = n, ncol = p, 0)
w <- matrix(nrow = 1, ncol = n, 1)
s <- matrix(nrow = 1, ncol = n, 0)
aux <- matrix(nrow = 1, ncol = p, 0)
auxant <- matrix(nrow = 1, ncol = p, 0)
tdemu <- matrix(nrow = 1, ncol = p, 0)
rdemu <- matrix(nrow = 1, ncol = p, 0)
gamagama <- 0
sensor <- 0
A <- X
aux <- apply(A, 2, mean)
h <- 1
while ((median(abs(aux - auxant)) > tol) & (h <= 1000)) {
for (k in 1:n) {
if (norm(aux - t(as.matrix(A[k, ]))) == 0) {
s[1, k] <- tol
sensor <- 1
} else {
s[1, k] <- w[1, k]/norm(aux - t(as.matrix(A[k, ])), "F")
}
}
auxant <- aux
tdemu <- s %*% A/sum(s)
rdemu <- s %*% A
gamagama <- min(1, sensor, norm(rdemu, "F"))
aux <- (1 - gamagama) * tdemu + as.double(gamagama * aux)
h <- (h + 1)
}
m <- aux
return(m)
}
sqrtm <- function(x) {
z <- x
for (i in 1:ncol(x)) {
for (j in 1:nrow(x)) {
z[i, j] <- sqrt(as.complex(x[i, j]))
}
}
return(z)
}
translation <- function(X, Y, f) {
TR <- (Y - X)
t <- matrix(nrow = 1, ncol = 3, 0)
t <- apply(TR, 2, median)
X <- X + (matrix(nrow = f, ncol = 1, 1) %*% t(as.matrix(t)))
return(X)
}
CrossProduct3D <- function(x, y, i = 1:3) {
To3D <- function(x) head(c(x, rep(0, 3)), 3)
x <- To3D(x)
y <- To3D(y)
Index3D <- function(i) (i - 1)%%3 + 1
return(x[Index3D(i + 1)] * y[Index3D(i + 2)] - x[Index3D(i + 2)] * y[Index3D(i + 1)])
}
vector.cross <- function(a, b) {
if (length(a) != 3 || length(b) != 3) {
a = c(a, 0)
b = c(b, 0)
}
i1 <- c(2, 3, 1)
i2 <- c(3, 1, 2)
return(a[i1] * b[i2] - a[i2] * b[i1])
}
rot3D <- function(X, Y) {
eje <- matrix(nrow = 1, ncol = 3, 0)
tita <- 0
f = nrow(X)
c = ncol(X)
R <- matrix(nrow = c, ncol = c, 0)
E <- array(matrix(nrow = f, ncol = c, 0), c(f, c, f), dimnames = NULL)
ejes <- matrix(nrow = f, ncol = c, 0)
efinal <- matrix(nrow = 1, ncol = c, 0)
ejaux <- matrix(nrow = 1, ncol = 3, 0)
Teta <- matrix(nrow = f, ncol = f, 0)
for (i in 1:f) {
for (j in 1:f) {
R <- estimorot3D(X, Y, i, j)
valEje <- ejerot(R)
E[j, , i] <- valEje
E[i, , j] <- valEje
valAng <- angurot(R)
Teta[j, i] <- valAng
Teta[i, j] <- -(valAng)
}
}
v <- matrix(nrow = 1, ncol = 3, 0)
h <- 1
for (i in 1:f) {
v <- apply(E[, , i], 2, median)
while ((norm(t(as.matrix(v)), "F") < 0.001) & (h < f)) {
if (E[h, 3, i] == 1) {
} else if (E[h, 1, i] < 0) {
E[h, , i] <- -E[h, , i]
}
h <- (h + 1)
v <- (apply(E[, , i], 2, median))
}
h <- 1
ejes[i, ] <- v/norm(t(as.matrix(v)), "F")
v <- matrix(nrow = 1, ncol = 3, 0)
}
w <- matrix(nrow = 1, ncol = 3, 0)
for (k in 1:3) {
w[1, k] <- median(ejes[, k])
}
w <- w/norm(w, "F")
eje <- w
tita <- medianarep(Teta)
return(list(eje, tita))
} |
test_that("test the fit_cumhist fails", {
expect_s3_class(fit_cumhist(br_singleblock, state="State", duration="Duration", chains = 0), "cumhist")
expect_error(fit_cumhist(data=NULL, state="State", duration="Duration", chains = 0))
expect_error(fit_cumhist(list(br_singleblock), state="State", duration="Duration", chains = 0))
expect_error(fit_cumhist(br_singleblock, duration="Duration", chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", tau = -1, chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", tau = c(0.5, 0.5), chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", tau = "RANDOM", chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", mixed_state = -1, chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", mixed_state = 2, chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", mixed_state = c(0.5, 0.5), chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", mixed_state = "RANDOM", chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", history_init = -1, chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", history_init = 1.1, chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", history_init = c(0.2, 0.2, 0.2), chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", history_init = "one-half", chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", history_priors = c(1, 1), chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", history_priors = list(c(1, 1)), chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", history_priors = list("tau" = c(1, 1, 2)), chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", intercept_priors = list(c(1, 1)), chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", intercept_priors = c(1, 1), chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", intercept_priors = c(1, 1, 1, 1), family = "normal", chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", fixed_effects = "LogTime", chains = 0))
expect_error(fit_cumhist(br_singleblock, state="State", duration="Duration", random_effect = "Participant", chains = 0))
}) |
.get_ncp_F <- function(f, df, df_error, conf.level = 0.9) {
if (!is.finite(f) || !is.finite(df) || !is.finite(df_error)) {
return(c(NA, NA))
}
alpha <- 1 - conf.level
probs <- c(alpha / 2, 1 - alpha / 2)
lambda <- f * df
ncp <- suppressWarnings(stats::optim(
par = 1.1 * rep(lambda, 2),
fn = function(x) {
p <- stats::pf(q = f, df, df_error, ncp = x)
abs(max(p) - probs[2]) +
abs(min(p) - probs[1])
},
control = list(abstol = 1e-09)
))
f_ncp <- sort(ncp$par) / df
if (f <= stats::qf(probs[1], df, df_error)) {
f_ncp[2] <- 0
}
if (f <= stats::qf(probs[2], df, df_error)) {
f_ncp[1] <- 0
}
return(f_ncp)
}
.get_ncp_t <- function(t, df_error, conf.level = 0.95) {
alpha <- 1 - conf.level
probs <- c(alpha / 2, 1 - alpha / 2)
ncp <- suppressWarnings(optim(
par = 1.1 * rep(t, 2),
fn = function(x) {
p <- pt(q = t, df = df_error, ncp = x)
abs(max(p) - probs[2]) +
abs(min(p) - probs[1])
},
control = list(abstol = 1e-09)
))
t_ncp <- unname(sort(ncp$par))
return(t_ncp)
}
.get_ncp_chi <- function(chi, df, conf.level = 0.95) {
alpha <- 1 - conf.level
probs <- c(alpha / 2, 1 - alpha / 2)
ncp <- suppressWarnings(stats::optim(
par = 1.1 * rep(chi, 2),
fn = function(x) {
p <- stats::pchisq(q = chi, df, ncp = x)
abs(max(p) - probs[2]) +
abs(min(p) - probs[1])
},
control = list(abstol = 1e-09)
))
chi_ncp <- sort(ncp$par)
if (chi <= stats::qchisq(probs[1], df)) {
chi_ncp[2] <- 0
}
if (chi <= stats::qchisq(probs[2], df)) {
chi_ncp[1] <- 0
}
chi_ncp
} |
est.made <- function(X, k=round(sqrt(ncol(X))), maxdim=min(ncol(X),15), combine=c("mean","median","vote")){
aux.typecheck(X)
n = nrow(X)
D = as.matrix(dist(X))
diag(D) = Inf
Dsort = apply(D, 2, sort)
Rk = as.vector(Dsort[k,])
Rk2 = as.vector(Dsort[ceiling(k/2),])
dhat = log(2)/(log(Rk/Rk2))
combine = match.arg(combine)
estdim = switch(combine,
mean = max(round(mean(pmin(dhat,maxdim))),1),
median = max(round(median(pmin(dhat,maxdim))),1),
vote = max(as.integer(names(which.max(table(round(dhat)))[1])),1)
)
result = list()
result$estdim = estdim
result$estloc = dhat
return(result)
} |
qc.from.regionwise.df <- function(rdf, z_threshold=2.8, verbosity=0L, num_bad_regions_allowed=1L) {
dt = rdf;
table_type = colnames(dt)[1];
table_type_parts = strsplit(table_type, ".", fixed=T)[[1]];
if(length(table_type_parts) == 3L) {
hemi = table_type_parts[1];
atlas = table_type_parts[2];
measure = table_type_parts[3];
} else {
hemi = atlas = measure = NULL;
}
metadata = list('hemi'=hemi, 'atlas'=atlas, 'measure'=measure);
subjects = dt[[table_type]];
dt[[table_type]] = NULL;
region_means = as.list(mapply(mean, dt));
region_sds = as.list(mapply(sd, dt));
mean_dists_z = dt;
region_names = colnames(dt);
num_outlier_subjects_per_region = list();
for(region_name in region_names) {
mean_dist = region_means[[region_name]] - dt[[region_name]];
mean_dist_z = mean_dist / region_sds[[region_name]];
mean_dist_z[is.nan(mean_dist_z)] = 0;
mean_dists_z[[region_name]] = mean_dist_z;
outlier_subjects_pos = subjects[which(mean_dist_z > z_threshold)]
outlier_subjects_neg = subjects[which(mean_dist_z < -z_threshold)]
num_pos = length(outlier_subjects_pos);
num_neg = length(outlier_subjects_neg);
num_outlier_subjects_per_region[[region_name]] = (num_pos + num_neg);
if((num_pos + num_neg) > 0) {
if(verbosity >= 2L) {
cat(sprintf("Region '%s': found %d outlier subjects (%d pos, %d neg).\n", region_name, num_pos + num_neg, num_pos, num_neg));
}
}
}
subject_is_outlier_in_region = matrix((as.integer(mean_dists_z > z_threshold | mean_dists_z < -z_threshold)), ncol=ncol(dt));
subject_num_outlier_regions = rowSums(subject_is_outlier_in_region, na.rm = TRUE);
potentially_failed_subjects = c();
for(subject_idx in seq(length(subjects))) {
subject_id = subjects[subject_idx];
num_outlier_regions = subject_num_outlier_regions[subject_idx];
if(num_outlier_regions > 0L) {
outlier_regions = region_names[subject_is_outlier_in_region[subject_idx,] == 1L];
if(verbosity >= 2L) {
cat(sprintf("Subject '%s' (
} else if(verbosity >= 1L) {
cat(sprintf("Subject '%s' (
}
if(num_outlier_regions > num_bad_regions_allowed) {
potentially_failed_subjects = c(potentially_failed_subjects, subject_id);
}
}
}
return(list("failed_subjects"=potentially_failed_subjects, "mean_dists_z"=mean_dists_z, "num_outlier_subjects_per_region"=num_outlier_subjects_per_region, "metadata"=metadata));
}
qc.from.segstats.table <- function(filepath, ...) {
rdf = read.table(filepath, sep='\t', header=TRUE, stringsAsFactors=FALSE);
return(qc.from.regionwise.df(rdf, ...));
}
qc.from.segstats.tables <- function(filepath_lh, filepath_rh, ...) {
if(is.null(filepath_lh) & is.null(filepath_lh)) {
stop("No more than one of 'filepath_lh' and 'filepath_rh' can be NULL.");
}
res_hl = list();
if(! is.null(filepath_lh)) {
res_hl$lh = qc.from.segstats.table(filepath_lh, ...);
}
if(! is.null(filepath_rh)) {
res_hl$rh = qc.from.segstats.table(filepath_rh, ...);
}
return(res_hl);
}
qc.for.group <- function(subjects_dir, subjects_list, measure, atlas, hemi='both', ...) {
if( ! hemi %in% c('lh', 'rh', 'both')) {
stop("Parameter 'hemi' must be one of 'lh', 'rh', or 'both'.");
}
res_hl = list();
if(hemi %in% c('lh', 'both')) {
rdf = group.agg.atlas.native(subjects_dir, subjects_list, measure, 'lh', atlas);
table_type = sprintf("%s.%s.%s", 'lh', atlas, measure);
colnames(rdf)[1] = table_type;
res_hl$lh = qc.from.regionwise.df(rdf, ...);
}
if(hemi %in% c('lh', 'both')) {
rdf = group.agg.atlas.native(subjects_dir, subjects_list, measure, 'rh', atlas);
table_type = sprintf("%s.%s.%s", 'rh', atlas, measure);
colnames(rdf)[1] = table_type;
res_hl$rh = qc.from.regionwise.df(rdf, ...);
}
return(res_hl);
}
qc.vis.failcount.by.region <- function(qc_res, atlas, subjects_dir=fsaverage.path(), subject_id='fsaverage', ...) {
lh_data = getIn(qc_res, c('lh' , 'num_outlier_subjects_per_region'));
rh_data = getIn(qc_res, c('rh' , 'num_outlier_subjects_per_region'));
num_colors_needed = max(as.integer(lh_data), as.integer(rh_data));
makecmap_options = mkco.heat();
makecmap_options$n = num_colors_needed;
return(invisible(vis.region.values.on.subject(subjects_dir, subject_id, atlas, lh_region_value_list=lh_data, rh_region_value_list=rh_data, makecmap_options=makecmap_options, ...)));
} |
"incr_matrix0" |
informationBondIndex <- function(g) {
if (class(g)[1] != "graphNEL")
stop("'g' has to be a 'graphNEL' object")
stopifnot(.validateGraph(g))
m <- numEdges(g)
bonds <- .edgeDataMatrix(g, "bond")
bonds <- bonds[upper.tri(bonds)]
eqcls <- as.numeric(table(bonds[bonds != 0]))
m * log2(m) - sum(eqcls * log2(eqcls))
} |
`func.trim.RPD` <- function(data, trim = 0.25, deriv = c(0,1))
{
depth.RPD(data, trim = trim, deriv = deriv)$mtrim
} |
testthat::context("urls")
sec <- scratch_file()
testthat::describe('urls',{
skip_if_not_rstudio()
testthat::skip_on_travis()
it('empty',{
urlr()
rstudioapi::documentSave(sec$id)
testthat::expect_equal(readLines(sec$path,warn = FALSE),'[]()')
set_text(sec = sec)
})
it('no description bad link',{
set_text('text',sec = sec, mark = entire_document)
urlr()
rstudioapi::documentSave(sec$id)
testthat::expect_equal(readLines(sec$path,warn = FALSE),'[](
set_text(sec = sec)
})
it('description bad link',{
set_text('aaa text',sec = sec, mark = entire_document)
urlr()
rstudioapi::documentSave(sec$id)
testthat::expect_equal(readLines(sec$path,warn = FALSE),'[aaa](
set_text(sec = sec)
})
it('no description good link',{
set_text('http://www.text.com',sec = sec, mark = entire_document)
urlr()
rstudioapi::documentSave(sec$id)
testthat::expect_equal(readLines(sec$path,warn = FALSE),'[http://www.text.com](http://www.text.com)')
set_text(sec = sec)
})
it('single word description good link',{
set_text('text http://www.text.com',sec = sec, mark = entire_document)
urlr()
rstudioapi::documentSave(sec$id)
testthat::expect_equal(readLines(sec$path,warn = FALSE),'[text](http://www.text.com)')
set_text(sec = sec)
})
it('multiple word description good link',{
set_text('more text http://www.text.com',sec = sec, mark = entire_document)
urlr()
rstudioapi::documentSave(sec$id)
testthat::expect_equal(readLines(sec$path,warn = FALSE),'[more text](http://www.text.com)')
set_text(sec = sec)
})
}) |
PCC.Stemma <-
function(x,
omissionsAsReadings = FALSE,
limit = 0,
recoverNAs = TRUE,
layout_as_stemma = FALSE,
ask = TRUE,
verbose = FALSE) {
tableVariantes = x
edgelistGlobal = NULL
models = matrix(
nrow = nrow(tableVariantes),
ncol = 0,
dimnames = list(dimnames(tableVariantes)[[1]]))
modelsByGroup = matrix(
nrow = 1,
ncol = 0,
dimnames = list("Models")
)
fullDatabase = tableVariantes
collateDbs <- function(x,y){
myCols = colnames(y)
for(i in seq_len(length(myCols))){
if(myCols[i] %in% colnames(x)){
x[, myCols[i]] = y[,i]
} else {
x = cbind(x, y[,i, drop = FALSE])
}
}
return(x)
}
counter = 0
while (ncol(tableVariantes) > 3) {
counter = counter + 1
pccdisagreement = PCC.disagreement(tableVariantes, omissionsAsReadings = omissionsAsReadings)
pccBuildGroup = PCC.buildGroup(pccdisagreement, limit = limit, ask = ask)
if (identical(pccBuildGroup$groups, list())) {
message("No group was found. Unable to build stemma.")
if (!is.null(edgelistGlobal)) {
myNetwork = igraph::graph_from_edgelist(edgelistGlobal[,1:2, drop = FALSE], directed = TRUE)
if(layout_as_stemma){
myLayout = layout_as_stemma(edgelistGlobal)
}
else{
myLayout = layout_as_tree(myNetwork)
}
igraph::V(myNetwork)$color = "orange"
igraph::V(myNetwork)[grep('^{', igraph::V(myNetwork)$name, perl=TRUE)]$color = "grey"
igraph::plot.igraph(myNetwork, layout=myLayout)
output = as.list(NULL)
output$fullDatabase = fullDatabase
output$database = tableVariantes
output$edgelist = edgelistGlobal
output$models = models
output$modelsByGroup = modelsByGroup
return(output)
} else {
return()
}
}
pccReconstructModel = PCC.reconstructModel(
pccBuildGroup,
omissionsAsReadings = omissionsAsReadings,
recoverNAs = recoverNAs,
ask = ask,
verbose = verbose
)
tableVariantes = pccReconstructModel$database
fullDatabase = collateDbs(fullDatabase, tableVariantes)
if (!exists("tableVariantes")) {
stop("No database found.")
return(tableVariantes)
}
edgelistGlobal = rbind(edgelistGlobal, pccReconstructModel$edgelist)
models = cbind(models,pccReconstructModel$models)
modelsByGroup = cbind(modelsByGroup,pccReconstructModel$modelsByGroup)
}
if (is.null(tableVariantes)) {
myNetwork = igraph::graph_from_edgelist(edgelistGlobal[,1:2, drop = FALSE], directed = TRUE)
if(layout_as_stemma){
myLayout = layout_as_stemma(edgelistGlobal)
}
else{
myLayout = layout_as_tree(myNetwork)
}
igraph::V(myNetwork)$color = "orange"
igraph::V(myNetwork)[grep('^{', igraph::V(myNetwork)$name, perl=TRUE)]$color = "grey"
igraph::plot.igraph(myNetwork, layout=myLayout)
output = as.list(NULL)
output$fullDatabase = fullDatabase
output$database = tableVariantes
output$edgelist = edgelistGlobal
output$models = models
output$modelsByGroup = modelsByGroup
return(output)
}
if (ncol(tableVariantes) > 1) {
if(ask){
myNetwork = igraph::graph_from_edgelist(edgelistGlobal[,1:2, drop = FALSE], directed = TRUE)
if(layout_as_stemma){
myLayout = layout_as_stemma(edgelistGlobal)
} else{
myLayout = layout_as_tree(myNetwork)
}
igraph::V(myNetwork)$color = "orange"
igraph::V(myNetwork)[grep('^{', igraph::V(myNetwork)$name, perl=TRUE)]$color = "grey"
igraph::plot.igraph(myNetwork, layout=myLayout)
writeLines(
"There is now less than four manuscripts in the database.\nStemma building has now lost in accuracy. \nDo you want to continue anyway (take last step with caution) ?\n Y/N\n"
)
answered = FALSE
while (answered == FALSE) {
answer = readline("(Y/N)")
if (answer != "N" && answer != "Y") {
print("Please enter Y (yes) or N (no).")
}
if (answer == "N") {
output = as.list(NULL)
output$fullDatabase = fullDatabase
output$database = tableVariantes
output$edgelist = edgelistGlobal
output$models = models
output$modelsByGroup = modelsByGroup
return(output)
}
if (answer == "Y") {
answered = TRUE
}
}
}
if(ask==FALSE || answer == "Y"){
counter = counter + 1
pccdisagreement = PCC.disagreement(tableVariantes, omissionsAsReadings = omissionsAsReadings)
pccBuildGroup = PCC.buildGroup(pccdisagreement, limit = limit, ask = ask)
pccReconstructModel = PCC.reconstructModel(
pccBuildGroup,
omissionsAsReadings = omissionsAsReadings,
recoverNAs = recoverNAs,
ask = ask,
verbose = verbose
)
tableVariantes = pccReconstructModel$database
fullDatabase = collateDbs(fullDatabase, tableVariantes)
models = cbind(models,pccReconstructModel$models)
modelsByGroup = cbind(modelsByGroup,pccReconstructModel$modelsByGroup)
myNetworkCert = igraph::graph_from_edgelist(edgelistGlobal[,1:2, drop = FALSE], directed = TRUE)
igraph::E(myNetworkCert)$lty = 1
myNetworkUncert = igraph::graph_from_edgelist(pccReconstructModel$edgelist[,1:2, drop = FALSE], directed = TRUE)
igraph::E(myNetworkUncert)$lty = 3
myNetwork = igraph::union(myNetworkCert, myNetworkUncert, byname=TRUE)
igraph::E(myNetwork)$lty = ifelse(is.na(igraph::E(myNetwork)$lty_1),
igraph::E(myNetwork)$lty_2,igraph::E(myNetwork)$lty_1)
edgelistGlobal = rbind(edgelistGlobal, pccReconstructModel$edgelist)
if(layout_as_stemma){
myLayout = layout_as_stemma(edgelistGlobal)
}
else{
myLayout = layout_as_tree(myNetwork)
}
igraph::V(myNetwork)$color = "orange"
igraph::V(myNetwork)[grep('^{', igraph::V(myNetwork)$name, perl=TRUE)]$color = "grey"
igraph::plot.igraph(myNetwork, layout=myLayout, main="Final stemma")
output = as.list(NULL)
output$fullDatabase = fullDatabase
output$database = tableVariantes
output$edgelist = edgelistGlobal
output$models = models
output$modelsByGroup = modelsByGroup
return(output)
}
} else {
output = as.list(NULL)
output$fullDatabase = fullDatabase
output$database = tableVariantes
output$edgelist = edgelistGlobal
output$models = models
output$modelsByGroup = modelsByGroup
return(output)
}
} |
`modify_transMat` <- function(trans, split.transitions){
trans_tmp <- trans
companions <- c()
split.transitions <- sort(split.transitions)
split.states <- sapply(split.transitions, function(x) which(trans == x, arr.ind=TRUE)[,2])
for(j in 1:ncol(trans)){
check_trans <- trans[!is.na(trans[,j]),j] %in% split.transitions
if(sum(check_trans) %in% c(0, length(check_trans))){
add_col <- TRUE
for(i in 1:nrow(trans)){
if(!is.na(trans[i,j])){
if(j %in% split.states){
if(add_col){
trans_tmp <- cbind(trans_tmp, NA)
colnames(trans_tmp)[ncol(trans_tmp)] <- paste0(colnames(trans_tmp)[j], ".e")
colnames(trans_tmp)[j] <- paste0(colnames(trans_tmp)[j], ".p")
trans_tmp <- rbind(trans_tmp, NA)
rownames(trans_tmp)[nrow(trans_tmp)] <- paste0(rownames(trans_tmp)[j], ".e")
rownames(trans_tmp)[j] <- paste0(rownames(trans_tmp)[j], ".p")
companions[j] <- ncol(trans_tmp)
add_col <- FALSE
}
if(trans_tmp[i,j] %in% split.transitions){
trans_tmp[i, ncol(trans_tmp)] <- trans_tmp[i,j] + 1
}
}
}
}
}
else{
trans_tmp <- cbind(trans_tmp, trans_tmp[,j])
last_col <- ncol(trans_tmp)
colnames(trans_tmp)[last_col] <- paste0(colnames(trans_tmp)[j], "")
remove_values <- trans_tmp[,last_col] %in% split.transitions
trans_tmp[remove_values, last_col] <- NA
trans_tmp <- rbind(trans_tmp, NA)
rownames(trans_tmp)[nrow(trans_tmp)] <- paste0(rownames(trans_tmp)[j], "")
remove_values <- !(trans_tmp[,j] %in% split.transitions)
remove_values <- remove_values & !is.na(trans_tmp[,j])
trans_tmp[remove_values, j] <- NA
trans_tmp <- cbind(trans_tmp, NA)
colnames(trans_tmp)[ncol(trans_tmp)] <- paste0(colnames(trans_tmp)[j], ".e")
colnames(trans_tmp)[j] <- paste0(colnames(trans_tmp)[j], ".p")
trans_tmp <- rbind(trans_tmp, NA)
rownames(trans_tmp)[nrow(trans_tmp)] <- paste0(rownames(trans_tmp)[j], ".e")
rownames(trans_tmp)[j] <- paste0(rownames(trans_tmp)[j], ".p")
companions[j] <- ncol(trans_tmp)
trans_tmp[, ncol(trans_tmp)] <- trans_tmp[,j] + 1
}
}
comp_vek <- which(!is.na(companions))
ordered_cols <- setdiff(1:ncol(trans_tmp), c(comp_vek, companions[comp_vek]))
ordered_cols <- c(ordered_cols, unlist(lapply(comp_vek, function(x) c(x, companions[x]))))
trans_tmp <- trans_tmp[ordered_cols, ordered_cols]
val <- 1
for(i in 1:nrow(trans_tmp)){
for(j in 1:ncol(trans_tmp)){
if(!is.na(trans_tmp[i,j])){
trans_tmp[i,j] <- val
val <- val+1
}
}
}
names(dimnames(trans_tmp)) <- names(dimnames(trans))
return(trans_tmp)
} |
library(grid)
library(gridSVG)
tg <- grob(name="tg", cl="timegrob")
timegrob <- function(x) {
textGrob(paste("text generated at", Sys.time(), sep="\n"),
gp=x$gp, name=x$name)
}
drawDetails.timegrob <- function(x, ...) {
grid.draw(timegrob(x))
}
grid.draw(tg)
bt <- grob(x=unit(.5, "npc"), y=unit(.5, "npc"),
label="hi", name="bt", cl="boxedtext")
boxedtext <- function(x) {
tg <- textGrob(x$label, x$x, x$y,
name=paste(x$name, "text", sep="."))
rg <- rectGrob(x$x, x$y,
width=grobWidth(tg) + unit(2, "mm"),
height=grobHeight(tg) + unit(2, "mm"),
name=paste(x$name, "rect", sep="."))
gTree(children=gList(tg, rg), gp=x$gp, name=x$name)
}
drawDetails.boxedtext <- function(x, ...) {
grid.draw(boxedtext(x))
}
grid.draw(bt)
primToDev.timegrob <- function(x, dev) {
primToDev(timegrob(x), dev)
}
grid.newpage()
grid.draw(tg)
gridToSVG("simpleclass.svg")
library(XML)
simpleclasssvg <- xmlParse("simpleclass.svg")
cat(saveXML(simpleclasssvg))
primToDev.boxedtext <- function(x, dev) {
primToDev(boxedtext(x), dev)
}
grid.newpage()
grid.draw(bt)
gridToSVG("notsimpleclass.svg")
notsimpleclasssvg <- xmlParse("notsimpleclass.svg")
cat(saveXML(notsimpleclasssvg))
animate.timegrob <- function(x, ...) {
tg <- timegrob(x)
tg$animationSets <- x$animationSets
tg$groupAnimationSets <- x$groupAnimationSets
animate(tg, ...)
}
grid.newpage()
grid.draw(tg)
grid.animate("tg", x=c(.3, .7))
gridToSVG("animsimpleclass.svg")
animsimpleclasssvg <- xmlParse("animsimpleclass.svg")
cat(saveXML(animsimpleclasssvg))
animate.boxedtext <- function(x, ...) {
bt <- boxedtext(x)
bt$groupAnimationSets <- x$groupAnimationSets
animate(bt, ...)
btrect <- getGrob(bt, "bt.rect")
btrect$animationSets <- x$animationSets
animate(btrect, ...)
bttext <- getGrob(bt, "bt.text")
bttext$animationSets <- x$animationSets
animate(bttext, ...)
}
grid.newpage()
grid.draw(bt)
grid.animate("bt", x=c(.3, .7))
grid.animate("bt", visibility=c("visible", "hidden"),
begin=1, duration=0.1, group=TRUE)
gridToSVG("animnotsimpleclass.svg")
animnotsimpleclasssvg <- xmlParse("animnotsimpleclass.svg")
cat(saveXML(animnotsimpleclasssvg))
garnish.timegrob <- function(x, ...) {
tg <- timegrob(x)
tg$attributes <- x$attributes
tg$groupAttributes <- x$groupAttributes
garnish(tg, ...)
}
grid.newpage()
grid.draw(tg)
grid.garnish("tg", onmousedown="alert('ouch')")
gridToSVG("garnishsimpleclass.svg")
garnishsimpleclasssvg <- xmlParse("garnishsimpleclass.svg")
cat(saveXML(garnishsimpleclasssvg))
garnish.boxedtext <- function(x, ...) {
bt <- boxedtext(x)
bt$attributes <- x$attributes
bt$groupAttributes <- x$groupAttributes
garnish(bt, ...)
}
grid.newpage()
grid.draw(bt)
grid.garnish("bt", onmousedown="alert('ouch')")
grid.garnish("bt", onmouseover=c(bt.text="alert('watch it!')"),
group=FALSE)
gridToSVG("garnishnotsimpleclass.svg")
garnishnotsimpleclasssvg <- xmlParse("garnishnotsimpleclass.svg")
cat(saveXML(garnishnotsimpleclasssvg)) |
penfa <- function(model = NULL,
data = NULL,
group = NULL,
pen.shrink = "alasso",
pen.diff = "none",
eta = list("shrink" = c("lambda" = 0.01), "diff" = c("none" = 0)),
strategy = "auto",
...){
start.time0 <- start.time <- proc.time()[3]
timing <- list()
mc <- match.call(expand.dots = TRUE)
syntax <- model
dotdotdot <- list(...)
if(is.character(model)) {
FLAT <- ParseModelString(model)
}else if(is.null(model)) {
stop("penfa ERROR: model is NULL.")
}
ov.names <- partable_vnames(FLAT, type = "ov")
opt <- penfaOptions()
ok.names <- names(opt)
dot.names <- names(dotdotdot)
wrong.idx <- which(!dot.names %in% ok.names)
if(length(wrong.idx) > 0L) {
idx <- wrong.idx[1L]
stop("penfa ERROR: unknown argument `", dot.names[idx],"'")
}
opt <- utils::modifyList(opt, dotdotdot)
opt$pen.shrink <- pen.shrink
opt$pen.diff <- pen.diff
opt$eta <- eta
opt$strategy <- strategy
if(opt$information %in% c("fisher", "hessian")) {
} else {
stop("penfa ERROR: unknown argument \"", opt$information,"\". Information must be either \"fisher\" or \"hessian\".\n")
}
if(opt$strategy %in% c("fixed", "auto")) {
} else {
stop("penfa ERROR: strategy must be either \"auto\" or \"fixed\".\n")
}
pen.set <- c("none", "lasso", "alasso", "scad", "mcp", "ridge")
opt.pen <- c(opt$pen.shrink, opt$pen.diff)
for(pen.cd in 1:length(opt.pen)){
if(opt.pen[pen.cd] %in% pen.set){
}else{
stop("penfa ERROR: unknown argument \"", opt.pen[pen.cd],"\". Penalty must be either \"lasso\", \"alasso\", \"scad\", \"mcp\", \"ridge\" or \"none\".\n")
}
}
if(!is.list(opt$eta)){
stop("penfa ERROR: \"eta\" should be a list. See ?penfa for details.\n")
}else{
if(!(length(opt$eta)==2)){
stop("penfa ERROR: \"eta\" should be a two-dimensional list. See ?penfa for details.\n")
}
if(all(names(opt$eta) %in% c("shrink", "diff"))){
if(!(names(opt$eta)[1] == "shrink" & names(opt$eta[2]) == "diff")){
opt$eta <- opt$eta[c(2,1)]
}
} else{
stop("penfa ERROR: \"eta\" arguments should be named \"shrink\" and \"diff\". See ?penfa for details.\n")
}
}
if(is.null(group) & (pen.diff != "none" | any(names(opt$eta$diff) != "none"))){
stop("penfa ERROR: difference penalty only allowed in a multiple-group analysis.\n")
}
pmat.set <- c("none", "lambda", "psi", "phi", "tau", "kappa")
pmat.opt <- unlist(lapply(opt$eta, names))
pmat.cond <- pmat.opt %in% pmat.set
if(all(pmat.cond)){
}else{
idx.wrong.pmat <- which(pmat.cond == FALSE)[1]
stop("penfa ERROR: unknown argument \"", pmat.opt[idx.wrong.pmat],"\". Parameter matrix must be any of \"lambda\", \"psi\", \"phi\", \"tau\", \"kappa\" or \"none\".\n")
}
if(pen.shrink != "none" && any(pmat.opt[grep("shrink", names(pmat.opt))] == "none")){
stop("penfa ERROR: a ", pen.shrink, " penalty was requested for shrinkage, but no elements to
penalize were specified. Please specify a matrix to be penalized in \"eta\" or set
pen.shrink = \"none\" for no shrinkage penalization. ")
}
if(pen.diff != "none" && any(pmat.opt[grep("diff", names(pmat.opt))] == "none")){
stop("penfa ERROR: a ", pen.diff, " difference penalty was requested, but no elements to
penalize were specified. Please specify a matrix to be penalized in \"eta\" or set
pen.diff = \"none\" for no invariance penalization. ")
}
if(any(unlist(opt$eta) < 0)){
stop("penfa ERROR: tuning parameters must be non-negative.\n")
}
if(!is.logical(opt$meanstructure)){
stop("penfa ERROR: \"meanstructure\" must be either TRUE or FALSE.\n")
}
if(!is.logical(opt$int.ov.free)){
stop("penfa ERROR: \"int.ov.free\" must be either TRUE or FALSE.\n")
}
if(!is.logical(opt$int.lv.free)){
stop("penfa ERROR: \"int.lv.free\" must be either TRUE or FALSE.\n")
}
if(!is.logical(opt$orthogonal)){
stop("penfa ERROR: \"orthogonal\" must be either TRUE or FALSE.\n")
}
if(!is.logical(opt$std.lv)){
stop("penfa ERROR: \"std.lv\" must be either TRUE or FALSE.\n")
}
if(!is.logical(opt$auto.fix.first)){
stop("penfa ERROR: \"auto.fix.first\" must be either TRUE or FALSE.\n")
}
if(!is.logical(opt$auto.fix.single)){
stop("penfa ERROR: \"auto.fix.single\" must be either TRUE or FALSE.\n")
}
if(!is.logical(opt$std.ov)){
stop("penfa ERROR: \"std.ov\" must be either TRUE or FALSE.\n")
}
if(!is.logical(opt$verbose)){
stop("penfa ERROR: \"verbose\" must be either TRUE or FALSE.\n")
}
if(!is.logical(opt$warn)){
stop("penfa ERROR: \"warn\" must be either TRUE or FALSE.\n")
}
if(!is.logical(opt$debug)){
stop("penfa ERROR: \"debug\" must be either TRUE or FALSE.\n")
}
if(!is.numeric(opt$optim.dx.tol)){
stop("penfa ERROR: \"optim.dx.tol\" must be numeric.\n")
}
if(!is.numeric(opt$a.scad)){
stop("penfa ERROR: \"a.scad\" must be numeric.\n")
}
if(!is.numeric(opt$a.mcp)){
stop("penfa ERROR: \"a.mcp\" must be numeric.\n")
}
if(!is.numeric(opt$a.alasso)){
stop("penfa ERROR: \"a.alasso\" must be numeric.\n")
}
if(!is.numeric(opt$cbar)){
stop("penfa ERROR: \"cbar\" must be numeric.\n")
}
if(!is.numeric(opt$gamma)){
stop("penfa ERROR: \"gamma\" must be numeric.\n")
}else{
if(opt$gamma < 1){
stop("penfa ERROR: \"gamma\" cannot be < 1.\n")
}
}
if(opt$debug){
opt$verbose <- opt$warn <- TRUE
}
ctrl.trust.opt.check <- names(opt$control) %in% c("rinit", "rmax", "iterlim", "fterm", "mterm")
if(all(ctrl.trust.opt.check)){
if(any(names(opt$control) %in% "rinit")){
rinit.idx <- which(names(opt$control) == "rinit")
if(!is.numeric(opt$control[[rinit.idx]])){
stop("penfa ERROR: \"rinit\" must be numeric.\n")
}
}
if(any(names(opt$control) %in% "rmax")){
rmax.idx <- which(names(opt$control) == "rmax")
if(!is.numeric(opt$control[[rmax.idx]])){
stop("penfa ERROR: \"rmax\" must be numeric.\n")
}
}
if(any(names(opt$control) %in% "iterlim")){
iterlim.idx <- which(names(opt$control) == "iterlim")
if(!is.numeric(opt$control[[iterlim.idx]])){
stop("penfa ERROR: \"iterlim\" must be numeric.\n")
}
}
if(any(names(opt$control) %in% "fterm")){
fterm.idx <- which(names(opt$control) == "fterm")
if(!is.numeric(opt$control[[fterm.idx]])){
stop("penfa ERROR: \"fterm\" must be numeric.\n")
}
}
if(any(names(opt$control) %in% "mterm")){
mterm.idx <- which(names(opt$control) == "mterm")
if(!is.numeric(opt$control[[mterm.idx]])){
stop("penfa ERROR: \"mterm\" must be numeric.\n")
}
}
}else{
idx.wrong.trust.opt <- which(ctrl.trust.opt.check == FALSE)[1]
stop("penfa ERROR: unknown argument \"", names(unlist(opt$control)[idx.wrong.trust.opt]),"\". Control options must be any of \"rinit\", \"rmax\", \"iterlim\", \"fterm\", \"mterm\".\n")
}
if(any(FLAT$op == "~1")){
opt$meanstructure <- TRUE
if(opt$information == "hessian"){
stop("penfa ERROR: the formula contains intercept-like formulas, currently not supported
with Hessian matrix; please specify information = \"fisher\". \n")
}
}
if((opt$meanstructure | opt$int.ov.free | opt$int.lv.free) && opt$information == "hessian"){
stop("penfa ERROR: meanstructure estimation currently not supported with Hessian matrix;
please specify information = \"fisher\". \n")
}
if(!is.null(group) & opt$meanstructure == TRUE & opt$information == "hessian"){
stop("penfa ERROR: multiple-group analysis with meanstructure estimation currently not
supported with Hessian matrix; please specify information = \"fisher\". \n")
}
if(!is.null(group) && is.null(dotdotdot$meanstructure)){
opt$meanstructure <- TRUE
if(opt$information == "hessian"){
stop("penfa ERROR: multiple-group analysis with meanstructure estimation currently not
supported with Hessian matrix; please specify information = \"fisher\". \n")
}
}
options <- opt
timing$Options <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
moddata <- penfaData(data = data, group = group, ov.names = ov.names, options = options)
timing$Data <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
if(options$debug){
cat(" [DEBUG] : Data \n")
print(str(moddata))
}
partable <- ParTable(model = FLAT, ngroups = moddata@ngroups, meanstructure = options$meanstructure,
int.ov.free = options$int.ov.free, int.lv.free = options$int.lv.free,
orthogonal = options$orthogonal, std.lv = options$std.lv,
auto.fix.first = options$auto.fix.first, auto.fix.single = options$auto.fix.single,
debug = options$debug, warn = options$warn, as.data.frame. = FALSE)
junk <- partable_check(partable, warn = TRUE)
pta <- partable_attributes(partable)
timing$ParTable <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
samplestats <- samplestats_from_data(moddata = moddata, meanstructure = options$meanstructure,
debug = options$debug, verbose = options$verbose)
timing$SampleStats <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
if (options$debug) {
cat(" [DEBUG] : SampleStats \n")
print(str(samplestats))
}
if(!is.null(group) & (pen.diff != "none" | any(names(options$eta$diff) != "none")) & samplestats@ngroups > 2){
stop("penfa ERROR: The difference penalty is currently implemented with only 2 groups.
Please get in touch to check progress on future extensions. \n")
}
if(options$user.start & !is.null(options$start.val)){
START <- rep(0, times = length(partable$id))
START[partable$free == 0] <- partable$ustart[partable$free == 0]
START[partable$free != 0] <- options$start.val
START[partable$free != 0 & !is.na(partable$ustart)] <- partable$ustart[partable$free != 0 & !is.na(partable$ustart)]
}else{
START <- get_start(partable = partable, samplestats = samplestats,
debug = options$debug)
}
START <- start_check_cov(partable = partable, start = START)
partable$start <- START
timing$start <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
model <- get_model(partable = partable, options = options)
if(options$information == "hessian"){
rescov.idx <- which(partable$lhs %in% ov.names &
partable$rhs %in% ov.names &
partable$op == "~~" &
partable$lhs != partable$rhs)
if(length(rescov.idx) > 0){
stop("penfa ERROR: the current Hessian implementation does not allow for residual covariances.
please specify information = \"fisher\".")
}
}
timing$Model <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
if(options$pen.shrink == "alasso" | options$pen.diff == "alasso"){
if(is.null(options$weights)){
if(options$verbose)
cat("Computing weights for alasso (ML estimates)...")
tmp <- list();
tmp$pen.shrink <- tmp$pen.diff <- "none"
tmp$eta <- list("shrink" = c("none" = 0), "diff" = c("none" = 0))
tmp$verbose <- FALSE; tmp$strategy <- "fixed"
tmp.arg <- utils::modifyList(options, tmp)
unpen.mod <- try(do.call(penfa, args = c(tmp.arg, list(model = syntax, data = data, group = group))),
silent = TRUE)
if(unpen.mod@Vcov$admissibility == FALSE){
cat("\n The unpenalized model produced an inadmissible solution\n")
cat(" Trying to get the weights from an L2-norm regularized model with automatic procedure...\n")
tmp.arg$pen.shrink <- "ridge"; tmp.arg$strategy <- "auto"
tmp.arg$eta <- list("shrink" = c("lambda" = 0.005), "diff" = c("none" = 0))
unpen.mod <- try(do.call(penfa, args = c(c(tmp.arg, list(model = syntax, data = data, group = group)))),
silent = TRUE)
if(unpen.mod@Vcov$admissibility == FALSE){
stop("penfa ERROR: Could not compute the weights for alasso; please provide a vector of
weights via the 'weights' argument or check the model")
}
}
weights <- unpen.mod@Optim$x
options$weights <- weights
if(options$verbose)
cat(" done.\n")
}
}else{
weights <- NULL
}
timing$weights <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
modpenalty <- get_penfaPenalty(model = model, options = options)
partable$type <- character(length(partable$lhs))
partable$type[which( partable$free == 0L)] <- "fixed"
partable$type[which( partable$free %in% unique(unlist([email protected])))] <- "pen"
partable$type[which( partable$type=="")] <- "free"
partable$penalty <- character(length(partable$lhs))
shrink.idxpar.set <- unique(unlist([email protected]$shrink))
diff.idxpar.set <- unique(unlist([email protected]$diff))
shrink.diff.idxpar.set <- intersect(shrink.idxpar.set, diff.idxpar.set)
partable$penalty[which( partable$type != "pen")] <- "none"
partable$penalty[which( partable$free %in% shrink.idxpar.set)] <- "shrink"
partable$penalty[which( partable$free %in% diff.idxpar.set)] <- "diff"
partable$penalty[which( partable$free %in% shrink.diff.idxpar.set) ] <- "shrink + diff"
partable <- partable[c("id","lhs", "op", "rhs", "user", "group", "type",
"penalty", "free", "ustart", "start")]
if(options$debug){
cat(" [DEBUG] : ParTable \n")
print(as.data.frame(partable))
}
timing$penalty <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
x <- NULL
Sigma.hat <- computeSigmaHat(model, debug=options$debug)
is.pdef <- is.Pdef(mat = Sigma.hat, ngroups = samplestats@ngroups)
for(g in 1:samplestats@ngroups){
if(!is.pdef[g]){
group.txt <- ifelse(samplestats@ngroups > 1, paste(" in group ",g,".",sep=""), ".")
if(options$debug){
print(Sigma.hat[[g]])
}
stop("penfa ERROR: initial model-implied Sigma is not positive definite;\n
check the model and/or starting parameters", group.txt)
x <- START
attr(x, "converged") <- FALSE
attr(x, "iterations") <- 0L
attr(x, "control") <- options@control
attr(x, "fx.pen") <- as.numeric(NA)
}
}
if([email protected] > 0L) {
x <- model_estimate(model = model, samplestats = samplestats, moddata = moddata,
modpenalty = modpenalty, options = options)
}
model <- model_set_parameters(model, x = x)
partable$est <- model_get_parameters(model = model, type = "user", extra = TRUE)
lhs.op.rhs <- data.frame("lhs" = partable$lhs, "op" = partable$op, "rhs" = partable$rhs, "free" = partable$free)
lhs.op.rhs.free <- subset(lhs.op.rhs, partable$free > 0)
x.names <- partable_labels(partable, type = "free")
if(!attr(x, "converged") && options$warn){
warning("penfa WARNING: the trust-region optimizer warns that a solution has NOT been found.
The penalized model did not converge, see ?penfa help page for possible reasons.")
}
modoptim <- list()
x2 <- x; attributes(x2) <- NULL
modoptim$x <- x2; names(modoptim$x) <- x.names
modoptim$npar <- length(x)
modoptim$converged <- attr(x, "converged")
modoptim$iterations <- attr(x, "iterations")
modoptim$fx.pen <- as.vector(attr(x, "fx.pen"))
modoptim$fx.unpen <- as.vector(attr(x, "l"))
modoptim$logl.pen <- - modoptim$fx.pen
modoptim$logl.unpen <- - modoptim$fx.unpen
modoptim$dx.pen <- attr(x, "dx.pen")
modoptim$hessian.pen <- attr(x, "hessian.pen")
modoptim$control <- attr(x, "control")
modoptim$npd <- attr(x, "npd")
rownames(modoptim$dx.pen) <- x.names
rownames(modoptim$hessian.pen) <- colnames(modoptim$hessian.pen) <- x.names
if(options$verbose){
modoptim$argpath <- attr(x, "argpath")
modoptim$argtry <- attr(x, "argtry")
modoptim$type <- attr(x, "type")
modoptim$accept <- attr(x, "accept")
modoptim$radii <- attr(x, "radii")
modoptim$rho <- attr(x, "rho")
modoptim$fx.val <- attr(x, "fx.val")
modoptim$fx.valtry <- attr(x, "fx.valtry")
modoptim$change <- attr(x, "change")
modoptim$stepnorm <- attr(x, "stepnorm")
}
[email protected][["S.h1"]] <- attr(x, "S.h1")
[email protected][["S.h2"]] <- attr(x, "S.h2")
[email protected][["S.h"]] <- attr(x, "S.h")
[email protected][["SS.shrink"]] <- attr(x, "SS.shrink")
[email protected][["SS.diff"]] <- attr(x, "SS.diff")
rownames([email protected]$S.h2) <- x.names
rownames([email protected]$S.h) <- colnames([email protected]$S.h) <- x.names
class([email protected]$S.h) <- c("penfaPenMat", "matrix", "array")
[email protected]$SS.shrink <- lapply([email protected]$SS.shrink, function(x) {
rownames(x) <- colnames(x) <- x.names; class(x) <- c("penfaPenMat", "matrix", "array"); x} )
[email protected]$SS.diff <- lapply([email protected]$SS.diff, function(x) {
rownames(x) <- colnames(x) <- x.names; class(x) <- c("penfaPenMat", "matrix", "array"); x} )
timing$optim <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
implied <- list()
implied <- model_implied(model)
timing$implied <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
solution <- c("gradient" = NA, "hessian" = NA)
conv.c <- convcheck(model = model, options = options, modoptim = modoptim)
solution[1] <- conv.c[1]
if(options$strategy == "fixed"){
admis <- is_Admissible(model = model, verbose = options$verbose)
}else{
admis <- is_Admissible(model = model, verbose = FALSE)
}
VCOV <- NULL
check.eig <- NA
if([email protected] > 0L && attr(x, "converged") && all(conv.c)){
if(options$verbose & options$strategy == "fixed")
cat("Computing VCOV ...")
tmp <- posdef(omega = modoptim$hessian.pen)
check.eig <- tmp$check.eigen
if(check.eig){
warning("penfa WARNING: The variance-covariance matrix of the estimated parameters
was not positive definite ... corrected to make it positive definite.")
}
solution[2] <- !check.eig
VCOV <- tmp$res.inv
rownames(VCOV) <- colnames(VCOV) <- x.names
if(options$verbose & options$strategy == "fixed")
cat(" done.\n")
}
vcov <- list(information = options$information, vcov = VCOV, solution = solution,
pdef = !check.eig, admissibility = admis)
std.errs <- model_vcov_se(model = model, partable = partable, VCOV = VCOV)
if(!is.null(VCOV)){
partable$se <- std.errs$se
vcov[["se"]] <- std.errs$x.se
vcov[["ci"]] <- compute_CI(param = modoptim$x, VCOV = VCOV, std.err = std.errs$x.se,
modpenalty = modpenalty, options = options)
}
timing$vcov <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
edf.single <- edf <- influence.mat <- IC <- NULL
if(!is.null(VCOV)){
edf.info <- compute_edf(VCOV = VCOV, modoptim = modoptim,
modpenalty = modpenalty,
options = options)
edf.single <- edf.info$edf.single
edf <- edf.info$edf
influence.mat <- edf.info$influence.mat
IC <- compute_IC(modoptim = modoptim, samplestats = samplestats, dgf = edf)
}
inference <- list(edf.single = edf.single, edf = edf,
influence.mat = influence.mat, IC = IC)
final <- new("penfa",
version = as.character(utils::packageVersion("penfa")),
call = mc,
timing = timing,
Options = options,
ParTable = partable,
pta = pta,
Data = moddata,
SampleStats = samplestats,
Model = model,
Optim = modoptim,
Penalize = modpenalty,
Implied = implied,
Vcov = vcov,
Inference = inference,
external = list())
if(options$strategy == "auto"){
auto <- automatic(model = final, data = data,
syntax = syntax, group = group)
optimal.eta <- auto$tuning
iter <- auto$iter
iterlim <- auto$iterlim
iter.inner <- auto$iter.inner
conv <- auto$conv
tol <- auto$tol
gamma <- auto$gamma
R <- auto$R
auto.l <- list("optimal.eta" = optimal.eta, "conv" = conv,
"gamma" = gamma, "iter" = iter,
"iter.inner" = iter.inner, "iterlim" = iterlim,
"tol" = tol, "R" = R)
final <- auto$model
final@Options$verbose <- options$verbose
final@Options$user.start <- FALSE
final@Options$start.val <- NULL
if(final@Options$verbose){
conv.auto.c <- convcheck(model = final,
options = final@Options,
modoptim = final@Optim)
admis <- is_Admissible(model = final@Model,
verbose = final@Options$verbose)
if(final@[email protected] > 0L && all(conv.auto.c) == TRUE && !is.null(final@Vcov$vcov) && conv==TRUE){
edf.info <- compute_edf(VCOV = final@Vcov$vcov,
modoptim = final@Optim,
modpenalty = final@Penalize,
options = final@Options)
}
}
final@Options$strategy <- final@Penalize@strategy <- "auto"
if(length(optimal.eta) > 0)
final@Penalize@automatic <- auto.l
timing$auto <- (proc.time()[3] - start.time)
start.time <- proc.time()[3]
}
timing$total <- (proc.time()[3] - start.time0)
final@timing <- timing
return(final)
} |
overall.sv <- function(margins, M, vo, type = "copR", c.gam2 = NULL){
if(type == "copR"){
BivD <- M$BivD
if(M$surv == TRUE) BivD <- "N"
if(BivD == "T" && margins[1] %in% c(M$m2,M$m3) && margins[2] %in% c(M$m2,M$m3) ){
if( margins[1] %in% c(M$m2) && margins[2] %in% c(M$m2) ) start.v <- c(vo$gam1$coefficients, vo$gam2$coefficients, vo$log.sig2.1, vo$log.sig2.2, vo$dof.st, vo$i.rho)
if( margins[1] %in% c(M$m3) && margins[2] %in% c(M$m3) ) start.v <- c(vo$gam1$coefficients, vo$gam2$coefficients, vo$log.sig2.1, vo$log.sig2.2, vo$log.nu.1, vo$log.nu.2, vo$dof.st, vo$i.rho)
if( margins[1] %in% c(M$m2) && margins[2] %in% c(M$m3) ) start.v <- c(vo$gam1$coefficients, vo$gam2$coefficients, vo$log.sig2.1, vo$log.sig2.2, vo$log.nu.2, vo$dof.st, vo$i.rho)
if( margins[1] %in% c(M$m3) && margins[2] %in% c(M$m2) ) start.v <- c(vo$gam1$coefficients, vo$gam2$coefficients, vo$log.sig2.1, vo$log.sig2.2, vo$log.nu.1, vo$dof.st, vo$i.rho)
}else{
if( margins[1] %in% c(M$m2,M$m2d) && margins[2] %in% c(M$m2,M$m2d) ) start.v <- c(vo$gam1$coefficients,vo$gam2$coefficients, vo$log.sig2.1, vo$log.sig2.2, vo$i.rho)
if( margins[1] %in% c(M$m3) && margins[2] %in% c(M$m3) ) start.v <- c(vo$gam1$coefficients,vo$gam2$coefficients, vo$log.sig2.1, vo$log.sig2.2, vo$log.nu.1, vo$log.nu.2, vo$i.rho)
if( margins[1] %in% c(M$m2,M$m2d) && margins[2] %in% c(M$m3) ) start.v <- c(vo$gam1$coefficients,vo$gam2$coefficients, vo$log.sig2.1, vo$log.sig2.2, vo$log.nu.2, vo$i.rho)
if( margins[1] %in% c(M$m3) && margins[2] %in% c(M$m2) ) start.v <- c(vo$gam1$coefficients,vo$gam2$coefficients, vo$log.sig2.1, vo$log.sig2.2, vo$log.nu.1, vo$i.rho)
if( margins[1] %in% c(M$m2) && margins[2] %in% c(M$bl) ) start.v <- c(vo$gam1$coefficients,vo$gam2$coefficients, vo$log.sig2.1, vo$i.rho)
if( margins[1] %in% c(M$m3) && margins[2] %in% c(M$bl) ) start.v <- c(vo$gam1$coefficients,vo$gam2$coefficients, vo$log.sig2.1, vo$log.nu.1, vo$i.rho)
if(margins[1] %in% c(M$m1d,M$bl) && margins[2] %in% c(M$m1d,M$bl)) start.v <- c(vo$gam1$coefficients, vo$gam2$coefficients, vo$i.rho)
if(margins[1] %in% c(M$m1d) && margins[2] %in% c(M$m2,M$m2d)) start.v <- c(vo$gam1$coefficients, vo$gam2$coefficients, vo$log.sig2.2, vo$i.rho)
if(margins[1] %in% c(M$m1d) && margins[2] %in% c(M$m3)) start.v <- c(vo$gam1$coefficients, vo$gam2$coefficients, vo$log.sig2.2, vo$log.nu.2, vo$i.rho)
if(margins[1] %in% c(M$m2d) && margins[2] %in% c(M$m2d) ) start.v <- c(vo$gam1$coefficients, vo$gam2$coefficients, vo$log.sig2.1, vo$log.sig2.2, vo$i.rho)
}
}
if(type == "copSS"){
if(margins[2] %in% c(M$m1d)) start.v <- c(vo$gam1$coefficients, c.gam2, vo$i.rho)
if(margins[2] %in% c(M$m2,M$m2d)) start.v <- c(vo$gam1$coefficients, c.gam2, vo$log.sig2.2, vo$i.rho)
if(margins[2] %in% M$m3) start.v <- c(vo$gam1$coefficients, c.gam2, vo$log.sig2.2, vo$log.nu.2, vo$i.rho)
}
start.v
} |
brier <- function(fit, times, newdata, ties=TRUE) {
if (fit$method == "efron")
s0 <- survfit(fit$y ~1, se.fit=FALSE, ctype=2, stype=2)
else s0 <- survfit(fit$y ~1, se.fit=FALSE, stype=1)
if (missing(times)) times <- s0$time[s0$n.event >0]
p0 <- 1- summary(s0, times, extend=TRUE)$surv
s1 <- survfit(fit, newdata= fit$call$data, se.fit=FALSE)
p1 <- 1- summary(s1, times, extend=TRUE)$surv
ny <- ncol(fit$y)
dtime <- fit$y[,ny-1]
dstat <- fit$y[,ny]
n <- length(dtime)
ntime <- length(times)
if (ties) {
mindiff <- min(diff(sort(unique(dtime))))
dtime <- dtime + ifelse(dstat==0, mindiff/2, 0)
}
c0 <- survfit0(survfit(Surv(dtime, 1-dstat) ~ 1))
b0 <- b1 <- matrix(0, nrow=n, ncol=ntime)
wt <- rep(1/n, n)
brier <- matrix(0, ntime, 2)
for (i in 1:ntime) {
indx <- findInterval(pmin(dtime, times[i]), c0$time)
wt <- ifelse(dtime < times[i] & dstat==0, 0, 1/c0$surv[indx])
b0[,i] <- ifelse(dtime > times[i], p0[i]^2, (dstat- p0[i])^2)
b1[,i] <- ifelse(dtime > times[i], p1[i,]^2, (dstat- p1[i,])^2)
brier[i,] <- c(sum(wt*b0[,i]), sum(wt*b1[,i]))/ sum(wt)
}
dimnames(brier) <- list(times, c("NULL", "Model"))
list(brier=brier, b0= b0, b1=b1, time=times)
} |
forest.seq <- function(x,y){
A <- (x$Bmax/x$B0)^x$nu-1
B.t <- x$Bmax/(1+A*exp(-x$r*x$nu*x$t))^(1/x$nu)
dB.t <- x$r*B.t*(1-(B.t/x$Bmax)^x$nu)
max.dB <- max(dB.t)
pos.max <- which(dB.t==max.dB)
B.max <- B.t[pos.max]
t.max <- x$t[pos.max]
B.max.f <- x$Bmax/(1+x$nu)^(1/x$nu)
max.dB.f <- x$Bmax*x$r*x$nu/(1+x$nu)^((x$nu+1)/x$nu)
CO2.t <- B.t*0.5*44/12
dCO2.t <- dB.t*0.5*44/12
max.dCO2 <- 0.5*(44/12)*max.dB
CO2.max <- 0.5*(44/12)* B.max
tCO2.emiss <- y$P*10^-3*y$kgCO2.kWh*8760*y$C*10^-3
area <- tCO2.emiss/max.dCO2
ymax <- max(CO2.t)
par(mar = c(5,5,2,5))
matplot(x$t,CO2.t,type="l", ylim=c(0,ymax),
xlab="Years",ylab="CO2 sequestered (t/ha)",lty=1,col=1)
par(new=T)
ymax <- 1.4*max(dCO2.t)
plot(x$t,dCO2.t, axes=F, type="l", ylim=c(0,ymax), xlab=NA,
ylab=NA,lty=2,col=1)
axis(side=4); mtext(side=4, line=3, "Seq Rate (tCO2/(yr ha))")
legend('topright',legend=c("Seq CO2","Seq Rate"),lty=1:2,col=1,bg='white',cex=0.7)
return(list(yr.max=t.max,B.i=B.max.f,max.dCO2=max.dCO2,
tCO2.emiss=tCO2.emiss,area=area))
} |
testthat::context('Testing WMM...')
keyFields <- c('testID', 'wmmVersion')
vectorFields <- c('x', 'y', 'z')
vectorDotFields <- paste0(vectorFields, 'Dot')
testFields <- c(
vectorFields,
vectorDotFields
)
calculatedFields <- paste0(testFields, 'Calculated')
testthatFields <- c(keyFields, testFields)
testthat::test_that("warns: is in the blackout zone", {
for (rn in which(testData$h < 2000)) {
testthat::expect_warning(
testData[
rn
, (calculatedFields) := GetMagneticFieldWMM(
lon = lon,
lat = lat,
height = height * 1e3,
time = year,
wmmVersion = wmmVersion
)
, by = testID
]
, "Location is in the blackout zone")
}
})
testthat::test_that("warns: is approaching the blackout zone", {
for (rn in which(testData$h >= 2000 & testData$h < 6000)) {
testthat::expect_warning(
testData[
rn
, (calculatedFields) := GetMagneticFieldWMM(
lon = lon,
lat = lat,
height = height * 1e3,
time = year,
wmmVersion = wmmVersion
)
, by = testID
]
, "Location is approaching the blackout zone")
}
})
testthat::test_that("no warnings", {
testthat::expect_silent(
testData[
h >= 6000
, (calculatedFields) := GetMagneticFieldWMM(
lon = lon,
lat = lat,
height = height * 1e3,
time = year,
wmmVersion = wmmVersion
)
, by = testID
])
})
testthat::test_that("nothing missed", {
expect_false(anyNA(testData[, c(calculatedFields), with = FALSE]))
})
calculatedData <- data.table::copy(testData)[
, mget(c(keyFields, calculatedFields))
]
data.table::setnames(
calculatedData,
calculatedFields,
testFields
)
testthat::context('Testing WMM main field benchmarks...')
testthat::test_that('WMM Test Values, Not 2005', {
expect_true(
all.equal(
testData[
wmmVersion != 'WMM2005'
, mget(vectorFields)
],
calculatedData[
wmmVersion != 'WMM2005'
, mget(vectorFields)
],
tolerance = 5e-6
)
)
})
testthat::test_that('WMM Test Values, 2005 only', {
expect_true(
all.equal(
testData[
wmmVersion == 'WMM2005'
, mget(vectorFields)
],
calculatedData[
wmmVersion == 'WMM2005'
, mget(vectorFields)
],
tolerance = 5e-5
)
)
})
testthat::context('Testing WMM secular variation field benchmarks...')
testthat::test_that('WMM Test Values (secular), not 2005', {
expect_true(
all.equal(
testData[
wmmVersion != 'WMM2005'
, mget(vectorDotFields)
],
calculatedData[
wmmVersion != 'WMM2005'
, mget(vectorDotFields)
],
tolerance = 1e-3
)
)
})
testthat::test_that('WMM Test Values (secular), 2005 only', {
expect_true(
all.equal(
testData[
wmmVersion == 'WMM2005'
, mget(vectorDotFields)
],
calculatedData[
wmmVersion == 'WMM2005'
, mget(vectorDotFields)
],
tolerance = 1e-2
)
)
}) |
sim_base <- function(data = base_id(100, 100)) {
new("sim_setup", base = data, simName = "")
}
sim_base_lm <- function() {
sim_base() %>%
sim_gen_x(0, 4, name = "x") %>%
sim_gen_e(0, 4, name = "e") %>%
sim_resp(function(dat) mutate_(dat, y = "100 + x + e"))
}
sim_base_lmm <- function() {
sim_base_lm() %>% sim_gen_v(0, 1, name = "v") %>%
sim_resp(function(dat) mutate_(dat, y = "y + v"))
}
sim_base_lmc <- function() {
sim_base_lm() %>% sim_gen_ec()
}
sim_base_lmmc <- function() {
sim_base_lmm() %>%
sim_gen_ec() %>%
sim_gen_vc()
} |
context("test-coord-flip.r")
test_that("secondary labels are correctly turned off", {
expect_doppelganger("turning off secondary title with coord_flip",
ggplot(mtcars, aes(x = mpg, y = cyl)) +
geom_point() +
scale_x_continuous(sec.axis = dup_axis(guide = guide_axis(title = NULL))) +
coord_flip()
)
}) |
RNode <- R6Class("RNode", portable = FALSE, class = FALSE)
RNode$set("private", ".val", NULL)
RNode$set("private", ".next", NULL)
RNode$set("private", ".prev", NULL)
RNode$set("public", "initialize", function(val){ .val <<- val })
RNode$set("public", "setNext", function(node){ .next <<- node })
RNode$set("public", "setPrev", function(node){ .prev <<- node })
RNode$set("active", "Val", function(){ return(.val) })
RNode$set("active", "Prev", function(){ return(.prev) })
RNode$set("active", "Next", function(){ return(.next) }) |
mdmb_extract_coef <- function(mod)
{
if ("coef" %in% names(mod) ){
c1 <- mod$coef
} else {
c1 <- mod$coefficients
}
return(c1)
} |
{}
LOGNAME <- "__log__"
get_log <- function(data, logger=NULL){
store <- attr(data, which=LOGNAME, exact=TRUE)
dataset <- as.character(substitute(data))
if ( is.null(store) || ( !is.null(store) & length(ls(store))==0 )){
return(NULL)
}
loggers <- ls(store)
if (is.null(logger)){
if ( length(loggers) == 1 ){
return(store[[loggers]])
} else {
stopf("Dataset has multiple loggers attached. Specify one of: %s"
, paste(sprintf("'%s'",loggers), collapse=","))
}
}
if ( is.null(store[[logger]]) ){
stopf("Dataset is not logged by '%s'", logger)
}
store[[logger]]
}
has_log <- function(data){
!is.null(attr(data,LOGNAME))
}
start_log <- function(data, logger=simple$new(), label=NULL){
if ( is.null(attr(data, LOGNAME)) ){
attr(data, LOGNAME) <- new.env()
}
store <- attr(data, LOGNAME)
newlogger <- class(logger)[[1]]
if ( newlogger %in% ls(store) ){
warnf("Can not add second logger of class '%s'. Ignoring", newlogger)
return(invisible(data))
}
if ( "label" %in% ls(logger) ){
dataset <- as.character(substitute(data))
lab <- if (!is.null(label)) paste(label,collapse="")
else if (length(dataset) == 1) dataset
else ""
logger$label <- lab
}
store[[ class(logger)[[1]] ]] <- logger
invisible(data)
}
remove_log <- function(data, logger){
store <- attr(data, LOGNAME)
if ( is.null(store) ) return(data)
rm(list=logger, envir=store)
if (length(ls(store)) == 0)
attr(data, LOGNAME) <- NULL
data
}
all_loggers <- function(data){
store <- attr(data,LOGNAME)
if (is.null(store)) character(0)
else ls(store)
}
dump_log <- function(data, logger=NULL,stop=TRUE, ...){
if ( is.null(logger) ) logger <- all_loggers(data)
for ( lggr in logger ){
log <- get_log(data, logger=lggr)
log$dump(...)
if (stop) return(invisible(remove_log(data,logger=logger)))
}
invisible(data)
}
stop_log <- function(data, logger=NULL, dump=TRUE, ...){
if (is.null(logger)) logger <- all_loggers(data)
for ( lggr in logger ){
log <- get_log(data, logger = lggr)
if (isTRUE(dump)) log$dump(...)
if (is.function(log$stop)) log$stop()
remove_log(data, lggr)
}
invisible(data)
}
`%>>%` <- function(lhs, rhs){
store <- attr(lhs, LOGNAME)
rhs <- substitute(rhs)
out <- pipe(lhs, rhs, env=parent.frame())
meta <- list(
expr = as.expression(rhs)
, src = as.character(as.expression(rhs))
)
if ( has_log(lhs) ){
for (lggr in all_loggers(lhs)){
log <- get_log(lhs, lggr)
log$add(meta=meta, input=lhs, output=out)
}
}
if ( has_log(lhs) &&
!as.character(rhs[[1]]) %in% c("dump_log","remove_log","stop_log") &&
!has_log(out)){
attr(out,LOGNAME) <- store
}
out
}
`%L>%` <- `%>>%` |
test_that("dtm_stats returns expect output", {
out <- dtm_stats(dtm.bse,
richness = TRUE,
distribution = TRUE,
central = TRUE,
character = TRUE,
simplify = TRUE)
expect_equal(dim(out), as.integer(c(1L, 26L)) )
expect_type(out, "list")
expect_equal(unlist(out$n_docs), nrow(dtm.bse))
expect_equal(unlist(out$n_types), ncol(dtm.bse))
expect_equal(unlist(out$n_tokens), sum(dtm.bse))
out <- dtm_stats(dtm.bse)
expect_equal(length(out), 5L)
expect_equal(dim(out[[1]]), as.integer(c(5L, 2L)) )
expect_equal(dim(out[[2]]), as.integer(c(4L, 2L)) )
expect_equal(dim(out[[3]]), as.integer(c(10L, 2L)) )
expect_equal(dim(out[[4]]), as.integer(c(4L, 2L)) )
expect_equal(dim(out[[5]]), as.integer(c(3L, 2L)) )
expect_type(out, "list")
expect_equal(as.character(out[[1]][1,2]), as.character(nrow(dtm.bse)))
expect_equal(as.character(out[[1]][3,2]), as.character(ncol(dtm.bse)))
expect_equal(as.character(out[[1]][4,2]), as.character(sum(dtm.bse)))
out <- dtm_stats(dtm.dgc,
richness = TRUE,
distribution = TRUE,
central = TRUE,
character = TRUE,
simplify = TRUE)
expect_equal(dim(out), as.integer(c(1L, 26L)) )
expect_type(out, "list")
expect_equal(unlist(out$n_docs), nrow(dtm.bse))
expect_equal(unlist(out$n_types), ncol(dtm.bse))
expect_equal(unlist(out$n_tokens), sum(dtm.bse))
out <- dtm_stats(dtm.dgc)
expect_equal(dim(out[[1]]), as.integer(c(5L, 2L)) )
expect_equal(dim(out[[2]]), as.integer(c(4L, 2L)) )
expect_equal(dim(out[[3]]), as.integer(c(10L, 2L)) )
expect_equal(dim(out[[4]]), as.integer(c(4L, 2L)) )
expect_equal(dim(out[[5]]), as.integer(c(3L, 2L)) )
expect_type(out, "list")
expect_equal(as.character(out[[1]][1,2]), as.character(nrow(dtm.bse)))
expect_equal(as.character(out[[1]][3,2]), as.character(ncol(dtm.bse)))
expect_equal(as.character(out[[1]][4,2]), as.character(sum(dtm.bse)))
})
test_that("dtm_stats returns basic output alone", {
out <- dtm_stats(dtm=dtm.bse,
richness = FALSE,
distribution = FALSE,
central = FALSE,
character = FALSE,
simplify = FALSE)
expect_type(out, "list")
expect_equal(length(out), as.integer(1L))
expect_equal(dim(out[[1]]), as.integer(c(5L, 2L)) )
})
test_that("dtm_melter works on both base and sparse", {
out_a <- dtm_melter(dtm=dtm.bse)
out_b <- dtm_melter(dtm=dtm.dgc)
expect_type(out_a, "list")
expect_type(out_b, "list")
expect_equal(ncol(out_a), as.integer(3L))
expect_equal(ncol(out_b), as.integer(3L))
expect_equal(out_a, out_b)
expect_equal(sum(out_a$count), sum(dtm.bse))
expect_equal(sum(out_b$count), sum(dtm.dgc))
})
test_that("dtm_builder produces identical dtm to cast_dtm", {
my.corpus <- data.frame(
text = c("I hear babies crying I watch them grow",
"They’ll learn much more than I'll ever know",
"And I think to myself",
"What a wonderful world",
"Yes I think to myself",
"What a wonderful world"),
line_id = paste0("line", 1:6))
my.corpus$clean_text <- tolower(gsub("'|’", "", my.corpus$text) )
dtm.a <- my.corpus %>%
dtm_builder(clean_text, line_id)
dtm.b <- dtm_builder(my.corpus, text=clean_text, doc_id=line_id)
dtm.c <- my.corpus %>%
dplyr::mutate(clean_text = gsub("'|’", "", text),
clean_text = tolower(clean_text)) %>%
dtm_builder(clean_text, line_id)
dtm.tidy <- my.corpus %>%
tidytext::unnest_tokens(word, clean_text) %>%
dplyr::count(line_id, word, sort = TRUE) %>%
tidytext::cast_dtm(line_id, word, n)
expect_identical(dim(dtm.a), dim(dtm.b) )
expect_identical(dim(dtm.a), dim(dtm.c) )
expect_identical(dim(dtm.b), dim(dtm.c) )
expect_identical(dim(dtm.a), dim(dtm.tidy) )
expect_identical(sum(dtm.a), sum(dtm.b) )
expect_identical(sum(dtm.a), sum(dtm.c) )
expect_identical(sum(dtm.b), sum(dtm.c) )
expect_identical(sum(dtm.a), sum(dtm.tidy) )
expect_identical(as.vector(colnames(dtm.a)),
as.vector(colnames(dtm.b)))
expect_identical(as.vector(colnames(dtm.a)),
as.vector(colnames(dtm.c)))
expect_identical(as.vector(colnames(dtm.b)),
as.vector(colnames(dtm.c)))
expect_identical(as.vector(sort(colnames(dtm.a))),
as.vector(sort(colnames(dtm.tidy))))
})
test_that("dtm_builder error/message if last row is blank", {
my.corpus <- data.frame(
my_text = c("I hear babies crying I watch them grow",
"They'll learn much more than I'll ever know",
"And I think to myself",
"What a wonderful world",
"Yes I think to myself",
"What a wonderful world"),
line_id = paste0("line", 1:6))
my.corpus$my_text[6] <- ""
expect_error(
expect_message( dtm_builder(my.corpus, my_text, line_id) ) )
})
test_that("dtm_builder works with vocab", {
vocab <- vocab_builder(corpus, text)
new.vocab <- vocab[!vocab %in% c("moon")]
expect_identical(
dim(dtm_builder(corpus, text, doc_id,
vocab = new.vocab) ),
as.integer(c(10, 43))
)
expect_identical(
dim(dtm_builder(corpus, text, doc_id,
vocab = new.vocab, chunk=4L) ),
as.integer(c(19, 43))
)
expect_identical(
dim(dtm_builder(corpus, text, doc_id,
vocab = new.vocab)),
as.integer(c(10, 43))
)
expect_error(
expect_message(
dtm_builder(corpus, text, doc_ids,
vocab = c("hear", "babies",
"world", "picklespit"))))
expect_error(
expect_message(
dtm_builder(corpus, text, doc_ids,
vocab = new.vocab, chunk=5L) ))
expect_error(
expect_message(
dtm_builder(corpus, text, doc_ids,
vocab = new.vocab) ))
})
test_that("dtm_builder error/message if doc_id is wrong...", {
my.corpus <- data.frame(
my_text = c("I hear babies crying I watch them grow",
"They'll learn much more than I'll ever know",
"And I think to myself",
"What a wonderful world",
"Yes I think to myself",
"What a wonderful world"),
line_id = paste0("line", 1:6))
expect_error(
expect_message(
dtm_builder(my.corpus, my_text, doc_id=line_ids) ))
})
test_that("dtm_builder chunks correctly", {
chunk <- 3L
dtm.e <- corpus %>%
dtm_builder(text, doc_id, chunk = chunk)
expect_equal(sum(dtm.e[1,]), chunk)
dtm.f <- corpus %>%
dtm_builder(text, doc_id)
expect_equal(sum(dtm.e), sum(dtm.f))
chunk <- 100L
dtm.g <- corpus %>%
dtm_builder(text, doc_id, chunk = chunk)
expect_equal(sum(dtm.g[1,]), sum(dtm.f))
})
test_that("dtm resampler creates DTM of the same dimensions", {
out <- dtm_resampler(dtm.dgc, alpha=0.2)
expect_s4_class(out, "dgCMatrix")
expect_identical(dim(out), dim(dtm.dgc))
expect_equal(sum(out), sum(dtm.dgc)*0.2, tolerance=0.1)
out <- dtm_resampler(dtm.dgc, alpha=0.5)
expect_s4_class(out, "dgCMatrix")
expect_identical(dim(out), dim(dtm.dgc))
expect_equal(sum(out), sum(dtm.dgc)*0.5, tolerance=0.1)
out <- dtm_resampler(dtm.dgc, alpha=0.7)
expect_s4_class(out, "dgCMatrix")
expect_identical(dim(out), dim(dtm.dgc))
expect_equal(sum(out), sum(dtm.dgc)*0.7, tolerance=0.1)
out <- dtm_resampler(dtm.dgc, alpha=1)
expect_s4_class(out, "dgCMatrix")
expect_identical(dim(out), dim(dtm.dgc))
expect_equal(sum(out), sum(dtm.dgc)*1, tolerance=0.1)
out <- dtm_resampler(dtm.dgc, n=20)
expect_s4_class(out, "dgCMatrix")
expect_true( all(rowSums(out) == 20) )
out <- dtm_resampler(dtm.dgc)
expect_s4_class(out, "dgCMatrix")
expect_true( all(rowSums(out) == rowSums(dtm.dgc)) )
expect_equal(sum(out), sum(dtm.dgc))
expect_warning(dtm_resampler(dtm.dgc, alpha=0.5, n=20))
})
test_that("dtm_stopper returns expected output", {
dtm.a <- corpus %>%
dtm_builder(text, doc_id)
dtm.a <- cbind(dtm.a, as.matrix(empty <- rep(0, nrow(dtm.a))) )
dtm.a <- cbind(dtm.a, as.matrix(rep(0, nrow(dtm.a))))
expect_identical(
dim(dtm_stopper(dtm.a, stop_list = c("choose", "moon"))),
as.integer(c(10, 44)))
expect_identical(
dim(dtm_stopper(dtm.a, stop_list = c("We", "we", "moon"), ignore_case = FALSE)),
as.integer(c(10, 43)))
expect_identical(
dim(dtm_stopper(dtm.a, stop_termfreq = c(2L, 5L)) ),
as.integer(c(10, 12)))
expect_identical(
dim(dtm_stopper(dtm.a, stop_termfreq = c(1L, 2L) )),
as.integer(c(10, 35)))
expect_identical(
dim(dtm_stopper(dtm.a, stop_termfreq = c(0.04, 0.99) )),
as.integer(c(10, 7)))
expect_identical(
dim(dtm_stopper(dtm.a, stop_docfreq = c(0.2, 0.99) )),
as.integer(c(10, 13)))
expect_identical(
dim(dtm_stopper(dtm.a, stop_docfreq = c(0.1, 0.4) )),
as.integer(c(10, 43)))
expect_identical(
dim(dtm_stopper(dtm.a, stop_docfreq = c(1L, 3L) )),
as.integer(c(10, 39)))
expect_identical(
dim(dtm_stopper(dtm.a, stop_hapax = TRUE)),
as.integer(c(10, 13)))
expect_identical(
dim(dtm_stopper(dtm.a, stop_null = TRUE)),
as.integer(c(10, 46)))
expect_error(expect_message(dtm_stopper(dtm.a, stop_termfreq = c("picklespit")) ))
expect_error(expect_message(dtm_stopper(dtm.a, stop_docfreq = c("picklespit")) ))
expect_error(expect_message(dtm_stopper(dtm.a)))
expect_error(expect_message(dtm_stopper(as.matrix(dtm.a))))
})
test_that(".convert_dtm_to_dgCMatrix convert all dtms to dgCMatrix", {
expect_s4_class(.convert_dtm_to_dgCMatrix(dtm.bse), "dgCMatrix")
expect_s4_class(.convert_dtm_to_dgCMatrix(dtm.dgc), "dgCMatrix")
expect_s4_class(.convert_dtm_to_dgCMatrix(dtm.dfm), "dgCMatrix")
expect_s4_class(.convert_dtm_to_dgCMatrix(dtm.tm), "dgCMatrix")
expect_s4_class(.convert_dtm_to_dgCMatrix(dtm.tdm), "dgCMatrix")
})
test_that("dtm resampler works on output of .prep_cmd_INPUT", {
out <- .prep_cmd_INPUT(dtm=dtm.dgc[,1:35],
cw = cw.oov,
cv = NULL,
wv = fake_word_vectors_oov,
missing = "stop")
dtm.samp <- dtm_resampler(out$DTM, alpha=1)
expect_s4_class(dtm.samp, "dgCMatrix")
expect_equal(nrow(dtm.samp), nrow(out$DTM))
expect_equal(ncol(dtm.samp), ncol(out$DTM))
}) |
"concordCOP" <- function(cop=NULL, para=NULL, cop2=NULL, para2=NULL, ...) {
if(is.null(cop)) {
warning("must have copula argument specified, returning NULL")
return(NULL)
}
if(is.null(cop2)) {
warning("must provide the second copula [and optional parameters]")
return()
}
tauCOP(cop=cop, para=para, cop2=cop2, para2=para2, ...)
}
"tauCOP" <-
function(cop=NULL, para=NULL,
cop2=NULL, para2=NULL, as.sample=FALSE, brute=FALSE, delta=0.002, ...) {
if(as.sample) {
if(is.null(para)) {
warning("Sample Kendall's Tau desired but para is NULL, ",
"returning NULL")
return(NULL)
}
if(length(names(para)) != 2) {
warning("para argument must be data.frame having only two columns, ",
"returning NULL")
return(NULL)
}
return(cor(para[,1], para[,2], method="kendall"))
}
if(is.null(cop)) {
warning("must have copula argument specified, returning NULL")
return(NULL)
}
if(is.null(cop2)) {
cop2 <- cop
para2 <- para
}
us <- vs <- seq(.Machine$double.eps, 1-.Machine$double.eps, delta)
if(brute) {
Q <- sum(sapply(us, function(u) {
sum(sapply(vs, function(v) {
return( derCOP(u,v, cop=cop, para=para, ...) *
derCOP2(u,v, cop=cop2, para=para2, ...))
}))
}))
Q <- 4*(0.5 - Q*delta^2) - 1
if(Q > 1) Q <- 1
if(Q < -1) Q <- -1
return(Q)
}
myint <- NULL
try(myint <- integrate(function(u) {
sapply(u,function(u) {
integrate(function(v) {
derCOP( u,v, cop=cop, para=para, ...) *
derCOP2( u,v, cop=cop2, para=para2, ...)}, 0,1)$value
})}, 0,1))
if(is.null(myint)) {
warning("error on dual partial derivative integration ",
"(copula singularity?), swapping copulas (Nelsen corollary ",
"5.1.2)")
try(myint <- integrate(function(u) {
sapply(u,function(u) {
integrate(function(v) {
derCOP( u,v, cop=cop2, para=para2, ...)*
derCOP2( u,v, cop=cop, para=para, ...)}, 0,1)$value
})}, 0,1))
if(is.null(myint)) {
warning("another error on dual partial derivative integration ",
"(again copula singularity?), kicking over to integration ",
"of the Kendall Function")
tau<-3-4*integrate(function(f) kfuncCOP(f,cop=cop,para=para),0,1)$value
return(tau)
}
}
Q <- 4*(0.5 - myint$value) - 1
if(Q > 1) Q <- 1
if(Q < -1) Q <- -1
return(Q)
} |
skip_on_cran()
params <-
list(run_tests = FALSE)
library(multinma)
nc <- switch(tolower(Sys.getenv("_R_CHECK_LIMIT_CORES_")),
"true" =, "warn" = 2,
parallel::detectCores())
options(mc.cores = nc)
head(dietary_fat)
diet_net <- set_agd_arm(dietary_fat,
study = studyc,
trt = trtc,
r = r,
E = E,
trt_ref = "Control",
sample_size = n)
diet_net
summary(normal(scale = 100))
diet_fit_FE <- nma(diet_net,
trt_effects = "fixed",
prior_intercept = normal(scale = 100),
prior_trt = normal(scale = 100))
diet_fit_FE
plot_prior_posterior(diet_fit_FE)
summary(normal(scale = 100))
summary(half_normal(scale = 5))
diet_fit_RE <- nowarn_on_ci(
nma(diet_net,
trt_effects = "random",
prior_intercept = normal(scale = 10),
prior_trt = normal(scale = 10),
prior_het = half_normal(scale = 5))
)
diet_fit_RE
plot_prior_posterior(diet_fit_RE, prior = c("trt", "het"))
(dic_FE <- dic(diet_fit_FE))
(dic_RE <- dic(diet_fit_RE))
plot(dic_FE)
plot(dic_RE)
pred_FE <- predict(diet_fit_FE,
baseline = distr(qnorm, mean = -3, sd = 1.77^-0.5),
type = "response")
pred_FE
plot(pred_FE)
pred_RE <- predict(diet_fit_RE,
baseline = distr(qnorm, mean = -3, sd = 1.77^-0.5),
type = "response")
pred_RE
plot(pred_RE)
pred_FE_studies <- predict(diet_fit_FE, type = "response")
pred_FE_studies
plot(pred_FE_studies) + ggplot2::facet_grid(Study~., labeller = ggplot2::label_wrap_gen(width = 10))
library(testthat)
library(dplyr)
tol <- 0.05
tol_dic <- 0.1
diet_FE_releff <- as.data.frame(relative_effects(diet_fit_FE))
test_that("FE relative effects", {
expect_equivalent(diet_FE_releff$mean, -0.01, tolerance = tol)
expect_equivalent(diet_FE_releff$sd, 0.054, tolerance = tol)
expect_equivalent(diet_FE_releff$`2.5%`, -0.11, tolerance = tol)
expect_equivalent(diet_FE_releff$`50%`, -0.01, tolerance = tol)
expect_equivalent(diet_FE_releff$`97.5%`, 0.10, tolerance = tol)
})
diet_RE_releff <- as.data.frame(relative_effects(diet_fit_RE))
test_that("RE relative effects", {
expect_equivalent(diet_RE_releff$mean, -0.02, tolerance = tol)
expect_equivalent(diet_RE_releff$sd, 0.09, tolerance = tol)
expect_equivalent(diet_RE_releff$`2.5%`, -0.19, tolerance = tol)
expect_equivalent(diet_RE_releff$`50%`, -0.01, tolerance = tol)
expect_equivalent(diet_RE_releff$`97.5%`, 0.16, tolerance = tol)
})
diet_RE_sd <- as.data.frame(summary(diet_fit_RE, pars = "tau"))
test_that("RE heterogeneity SD", {
expect_equivalent(diet_RE_sd$mean, 0.13, tolerance = tol)
expect_equivalent(diet_RE_sd$sd, 0.12, tolerance = tol)
expect_equivalent(diet_RE_sd$`2.5%`, 0.00, tolerance = tol)
expect_equivalent(diet_RE_sd$`50%`, 0.10, tolerance = tol)
expect_equivalent(diet_RE_sd$`97.5%`, 0.43, tolerance = tol)
})
test_that("FE DIC", {
expect_equivalent(dic_FE$resdev, 23.32, tolerance = tol_dic)
expect_equivalent(dic_FE$pd, 10.9, tolerance = tol_dic)
expect_equivalent(dic_FE$dic, 33.2, tolerance = tol_dic)
})
test_that("RE DIC", {
expect_equivalent(dic_RE$resdev, 21.5, tolerance = tol_dic)
expect_equivalent(dic_RE$pd, 13.3, tolerance = tol_dic)
expect_equivalent(dic_RE$dic, 34.8, tolerance = tol_dic)
})
diet_pred_FE <- as.data.frame(pred_FE)
test_that("FE predicted probabilities", {
expect_equivalent(diet_pred_FE$mean, c(0.06, 0.06), tolerance = tol_dic)
expect_equivalent(diet_pred_FE$sd, c(0.04, 0.04), tolerance = tol_dic)
expect_equivalent(diet_pred_FE$`2.5%`, c(0.01, 0.01), tolerance = tol_dic)
expect_equivalent(diet_pred_FE$`50%`, c(0.05, 0.05), tolerance = tol_dic)
expect_equivalent(diet_pred_FE$`97.5%`, c(0.18, 0.18), tolerance = tol_dic)
})
diet_pred_RE <- as.data.frame(pred_RE)
test_that("RE predicted probabilities", {
expect_equivalent(diet_pred_RE$mean, c(0.06, 0.06), tolerance = tol_dic)
expect_equivalent(diet_pred_RE$sd, c(0.04, 0.04), tolerance = tol_dic)
expect_equivalent(diet_pred_RE$`2.5%`, c(0.01, 0.01), tolerance = tol_dic)
expect_equivalent(diet_pred_RE$`50%`, c(0.05, 0.05), tolerance = tol_dic)
expect_equivalent(diet_pred_RE$`97.5%`, c(0.18, 0.18), tolerance = tol_dic)
}) |
update_mu <- function(clusters, pdat, nclust, dim, lambda1, lambda2, ngenes, delta){
center_store <- replicate(n =dim, expr = {matrix(rep(NA, nclust*ngenes),
ncol=nclust)},
simplify = F)
for(k in 1:nclust){
nk_vec <- nd_vec <- rep(NA, dim)
mean_mat <- matrix(rep(0, dim*ngenes), ncol=dim)
for(d in 1:dim){
clus_ind <- which(clusters[[d]] == k)
nk_vec[d] <- length(clus_ind)
nd_vec[d] <- length(clusters[[d]])
if(nk_vec[d] > 1){
mean_mat[,d] <- rowMeans(pdat[[d]][,clus_ind, drop = FALSE])
} else {
mean_mat[,d] <- 0
}
}
if (sum(nk_vec) > 0){
mu_mat <- matrix(rep(0, dim*(ngenes )), ncol=dim)
EQ <- matrix(rep(0, nrow(mean_mat)*ncol(mean_mat)),
ncol=ncol(mean_mat))
v <- matrix(rep(0, nrow(mean_mat)*(ncol(mean_mat)-1)),
ncol=(ncol(mean_mat)-1))
pens <- pen_calculator(lambda1 = lambda1, lambda2 = lambda2,
nk = nk_vec, delta = delta)
pen1 <- pens[[1]]
pen2 <- pens[[2]]
mu_mat <- mu_solver(d = dim, mu = mu_mat, v = v, EQ = EQ, dim = dim,
x = mean_mat, nk = nk_vec, p1 = pen1, p2 = pen2,
delta = delta)
for(d in 1:dim){
center_store[[d]][,k] <- mu_mat[,d]
}
} else {
for(d in 1:dim){
center_store[[d]][,k] <- 0
}
}
}
return(center_store)
} |
tam_mml_sufficient_statistics_R <- function( nitems, maxK, resp, resp.ind,
pweights, cA, col.index)
{
cResp <- (resp +1) *resp.ind
cResp <- cResp[, col.index ]
cResp <- 1 * ( cResp==matrix( rep(1:(maxK), nitems), nrow(cResp),
ncol(cResp), byrow=TRUE ) )
if ( stats::sd(pweights) > 0 ){
ItemScore <- as.vector( t( colSums( cResp * pweights ) ) %*% cA )
} else {
ItemScore <- as.vector( t( colSums( cResp) ) %*% cA )
}
res <- list(cResp=cResp, ItemScore=ItemScore)
return(res)
} |
na_interpolation <- function(x, option = "linear", maxgap = Inf, ...) {
data <- x
if (!is.null(dim(data)[2]) && dim(data)[2] > 1) {
for (i in 1:dim(data)[2]) {
if (!anyNA(data[, i])) {
next
}
tryCatch(data[, i] <- na_interpolation(data[, i], option, maxgap), error = function(cond) {
warning(paste("imputeTS: No imputation performed for column", i, "because of this", cond), call. = FALSE)
})
}
return(data)
}
else {
missindx <- is.na(data)
if (!anyNA(data)) {
return(x)
}
if (any(class(data) == "tbl")) {
data <- as.vector(as.data.frame(data)[, 1])
}
if (sum(!missindx) < 2) {
warning("No imputation performed: Input data needs at least 2 non-NA data points for applying na_interpolation")
return(x)
}
if (!is.null(dim(data)[2]) && !dim(data)[2] == 1) {
warning("No imputation performed: Wrong input type for parameter x")
return(x)
}
if (!is.null(dim(data)[2])) {
data <- data[, 1]
}
if (!is.numeric(data)) {
warning("No imputation performed: Input x is not numeric")
return(x)
}
n <- length(data)
allindx <- 1:n
indx <- allindx[!missindx]
data_vec <- as.vector(data)
if (option == "linear") {
interp <- stats::approx(indx, data_vec[indx], 1:n, rule = 2, ...)$y
}
else if (option == "spline") {
interp <- stats::spline(indx, data_vec[indx], n = n, ...)$y
}
else if (option == "stine") {
interp <- stinepack::stinterp(indx, data_vec[indx], 1:n, ...)$y
if (any(is.na(interp))) {
interp <- na_locf(interp, na_remaining = "rev")
}
}
else {
stop("No imputation performed: Wrong parameter 'option' given. Value must be either 'linear', 'spline' or 'stine'.")
}
data[missindx] <- interp[missindx]
if (is.finite(maxgap) && maxgap >= 0) {
rlencoding <- rle(is.na(x))
rlencoding$values[rlencoding$lengths <= maxgap] <- FALSE
en <- inverse.rle(rlencoding)
data[en == TRUE] <- NA
}
if (!is.null(dim(x)[2])) {
x[, 1] <- data
return(x)
}
return(data)
}
} |
ER_var_f <- function(erdat, innes, er_est, binomial_var=FALSE){
if(binomial_var){
erdat <- erdat %>%
mutate(pdot = .data$transect_n/.data$transect_Nc) %>%
mutate(ER_var = sum(((1-.data$pdot)/.data$pdot^2)*.data$transect_n,
na.rm=TRUE)) %>%
mutate(ER_var = if_else(is.infinite(.data$ER_var), 0, .data$ER_var)) %>%
mutate(ER_var_Nhat = .data$ER_var/sum(.data$Covered_area)^2) %>%
mutate(ER_var_Nhat = ifelse(length(unique(.data$Sample.Label))>1,
.data$ER_var_Nhat, 0))
erdat$pdot <- NULL
}else{
if(er_est %in% c("O2", "O3")){
warning(paste("Using the", er_est,
"encounter rate variance estimator, assuming that",
"sorting on Sample.Label is meaningful"))
if(!is.numeric(erdat$Sample.Label)){
warning("Additionally, Sample.Label is not numeric, this may cause additional issues")
}
erdat <- erdat %>%
mutate(.originalorder = 1:nrow(erdat)) %>%
arrange(.data$Sample.Label)
}
if(innes){
erdat <- erdat %>%
mutate(ER_var = varn(.data$Effort, .data$transect_Nc, type=er_est)) %>%
mutate(ER_var = ifelse(length(unique(.data$Sample.Label))>1,
.data$ER_var,
0)) %>%
mutate(ER_var_Nhat = varn(.data$Effort/(sum(.data$Effort)*
unique(.data$Area)/
sum(.data$Covered_area)),
.data$transect_Nc, type=er_est)) %>%
mutate(ER_var_Nhat = ifelse(length(unique(.data$Sample.Label))>1,
.data$ER_var_Nhat,
0))
}else{
erdat <- erdat %>%
mutate(ER_var = varn(.data$Effort, .data$transect_n_observations,
type=er_est)) %>%
mutate(ER_var = ifelse(length(unique(.data$Sample.Label))>1,
.data$ER_var, 0)) %>%
mutate(ER_var_Nhat = ((.data$Area/sum(.data$Covered_area))*
.data$Nc*sum(.data$Effort))^2 *
.data$ER_var/
sum(.data$transect_n_observations)^2) %>%
mutate(ER_var_Nhat = ifelse(length(unique(.data$Sample.Label))>1,
.data$ER_var_Nhat,
0))
}
}
erdat <- erdat %>%
mutate(ER_var_Nhat = ifelse(is.na(.data$ER_var_Nhat) |
is.nan(.data$ER_var_Nhat),
0, .data$ER_var_Nhat))
if(er_est %in% c("O2", "O3")){
erdat <- erdat %>%
arrange(.data$.originalorder)
erdat$.originalorder <- NULL
}
return(erdat)
} |
if (requiet("testthat") && requiet("insight") && requiet("parameters") && requiet("nlme") && requiet("lme4")) {
data("sleepstudy")
model <- lme(Reaction ~ Days,
random = ~ 1 + Days | Subject,
data = sleepstudy
)
test_that("model_parameters.lme", {
params <- model_parameters(model, effects = "fixed")
expect_equal(params$SE, c(6.8245, 1.5458), tolerance = 1e-3)
expect_equal(
colnames(params),
c("Parameter", "Coefficient", "SE", "CI", "CI_low", "CI_high", "t", "df_error", "p", "Effects")
)
})
test_that("model_parameters.lme", {
params <- model_parameters(model, effects = "all")
expect_equal(params$Coefficient, c(251.4051, 10.46729, 24.74024, 5.9221, 0.066, 25.59184), tolerance = 1e-3)
expect_equal(params$SE, c(6.82452, 1.54578, NA, NA, NA, NA), tolerance = 1e-3)
expect_equal(
colnames(params),
c(
"Parameter", "Coefficient", "SE", "CI", "CI_low", "CI_high", "t",
"df_error", "p", "Effects", "Group"
)
)
})
} |
library(Rmpi)
mpi.comm.get.parent(2)
if (!mpi.comm.is.null(2))
mpi.intercomm.merge(2,1,1)
master <- function(){
if (mpi.comm.size(1) > 0)
stop("There are some slaves running on comm 1")
slave<-system.file("Rslaves.sh",package="Rmpi")
Rscript <- system.file("demo","masterslavePI.R",package="Rmpi")
tmp <- paste(Sys.getpid(), "+", 1, sep="")
arg <- c(Rscript, tmp, "nolog", R.home())
mpi.comm.spawn(slave=slave,slavearg=arg )
mpi.intercomm.merge(2,0,1)
out <- mpi.reduce(0)
mpi.comm.free()
out
}
slave <- function(n){
totalcpu <- mpi.comm.size(0)
id <- mpi.comm.rank(0)+1
mypi <- 4*sum(1/(1+((seq(id,n,totalcpu)-.5)/n)^2))/n
mpi.reduce(mypi)
mpi.comm.free()
mpi.exit()
}
n<- 10000
if (mpi.is.master()){
master()
} else {
slave(n)
} |
PCH1 <- function (type, x, nc, cumss, nmix, openval0, PIA0, PIAJ, intervals) {
J <- length(intervals)+1
one <- function(n) {
p <- getp (n, x, openval0, PIA0)
phij <- getphij (n, x, openval0, PIAJ, intervals)
beta <- getbeta (type, n, x, openval0, PIAJ, intervals, phij)
pdt <- 0
for (b in 1:J) {
for (d in b:J) {
pbd <- beta[b]
if (d>b)
pbd <- pbd * prod (phij[b:(d-1)])
pbd <- pbd * (1-phij[d]);
ptmp <- 1
for (j in b:d) {
s <- (cumss[j]+1) : cumss[j+1]
ptmp <- ptmp * prod(1 - p[s])
}
pdt = pdt + pbd * (1 - ptmp)
}
}
pdt
}
sapply(1:nc, one)
}
pr0njmx <- function (n, x, cumss, jj, mm, binomN, PIA0, gk0, Tsk) {
pjm <- array(1, dim = c(jj, mm))
kk <- dim(Tsk)[1]
for (j in 1:jj) {
s <- (cumss[j]+1) : cumss[j+1]
S <- length(s)
csk <- PIA0[1,n,s, ,x, drop = FALSE]
cski <- rep(as.numeric(csk),mm)
i <- cbind(cski, rep(rep(1:kk, each = S), mm), rep(1:mm, each = S*kk))
gsk <- array(0, dim=c(S, kk, mm))
gsk[cski>0] <- gk0[i]
size <- t(Tsk[,s])
pjm[j, ] <- if (binomN %in% c(-2,0)) {
apply(gsk, 3, function(x) exp(-sum(size * x)))
}
else if (all(size==1)) {
apply(1-gsk,3, prod)
}
else {
apply(1-gsk, 3, function(x) prod (x^size))
}
}
pjm
}
PCH1secr <- function (type, individual, x, nc, jj, cumss, kk, mm, openval0, PIA0, PIAJ,
gk0, binomN, Tsk, intervals, moveargsi, movementcode, sparsekernel,
edgecode, usermodel, kernel, mqarray, cellsize, r0) {
One <- function (n) {
pjm <- pr0njmx(n, x, cumss, jj, mm, binomN, PIA0, gk0, Tsk)
phij <- getphij (n, x, openval0, PIAJ, intervals)
beta <- getbeta (type, n, x, openval0, PIAJ, intervals, phij)
if (movementcode>1) {
moveargsi <- pmax(moveargsi,0)
moveargs <- getmoveargs (n, x, openval0, PIAJ, intervals, moveargsi)
kernelp <- fillkernelC ( jj, movementcode-2, sparsekernel, kernel,
usermodel, cellsize, r0, moveargsi, moveargs, normalize = TRUE)
}
pdt <- 0
for (b in 1:jj) {
for (d in b:jj) {
pbd <- beta[b]
if (d>b)
pbd <- pbd * prod (phij[b:(d-1)])
pbd <- pbd * (1-phij[d]);
if (movementcode==0) {
prodpj <- apply(pjm[b:d,, drop = FALSE], 2, prod)
prw0 <- sum(prodpj) / mm
}
else if (movementcode==1) {
sumpm <- apply(pjm[,,drop=FALSE], 1, sum )
prw0 <- prod(sumpm[b:d]) / mm
}
else {
pm <- pjm[b, ] / mm
if (d>b) {
for (j in (b+1):d) {
pm <- convolvemq(j-1, kernelp, edgecode, mqarray, pm)
pm <- pm * pjm[j, ]
}
}
prw0 <- sum(pm)
}
pdt <- pdt + pbd * (1 - prw0)
}
}
pdt
}
if (individual) {
sapply(1:nc, One)
}
else {
rep(One(1), nc)
}
} |
add.col <-
function(inputA, inputB, add, according){
if(!is.data.frame(inputA)){
inputA <- as.data.frame(inputA)
}
if(ncol(inputA)==1){
inputA <- data.frame(seq(1:nrow(inputA)),inputA)
colnames(inputA) <- c("col0", colnames(inputA))
}
colaccordA <- which(colnames(inputA)==according)
if (is.null(colaccordA)){
stop(paste("There is no column called \"",according,"\"in inputA"))
}
inputA <- inputA[order(as.character(inputA[,colaccordA])),]
speciesA <- table(as.character(inputA[,colaccordA]))
inputA.species.uniq <- names(speciesA)
if(!is.data.frame(inputB)){
inputB <- as.data.frame(inputB)
}
if(ncol(inputB)==1){
inputB <- data.frame(seq(1:nrow(inputA)),inputA)
colnames(inputB) <- c("col0", colnames(inputB))
}
colaccordB <- which(colnames(inputB)==according)
if (is.null(colaccordB)){
stop(paste("There is no column called \"",according,"\"in inputB"))
}
inputB.species <- as.character(inputB[,colaccordB])
coladd <- which(colnames(inputB)==add)
if (!any(colnames(inputB)==add)){
stop(paste("There is no colum called \"", add ,"\"in inputB, please check!"))
}
inputB.add <- as.character(inputB[,coladd])
result.add <- rep(NA, length(inputA.species.uniq))
for (i in 1:length(inputA.species.uniq)){
for (j in 1:length(inputB.species)){
if (inputA.species.uniq[i] == inputB.species[j])
result.add[i] <- inputB.add[j];
}
}
addeddata <- rep(result.add, speciesA)
result <- data.frame(inputA, addeddata)
colnames(result) <- c(colnames(inputA), add)
if(any(is.na(add))){
rownum <- is.na(result$add)
cat("Warning: NA are found in the results, please check!\n")
error <- result[rownum,]
error1 <- head(error)
print(error1)
}
return(result)
} |
set.seed(123)
x <- runif(10, 1, 5)
test_that("SAVF_score provides proper messages and warnings", {
expect_that(SAVF_score(x, x_low = 5, x_high = 1, rho = .653), throws_error())
expect_that(SAVF_score(x, x_low = 1, x_high = 5, rho = c(.653, .5)), throws_error())
})
test_that("SAVF_score has correct dimensions and output type", {
expect_equal(SAVF_score(x, x_low = 1, x_high = 5, rho = .653) %>% length(), 10)
expect_true(SAVF_score(x, x_low = 1, x_high = 5, rho = .653) %>% is.numeric())
expect_true(SAVF_score(x, x_low = 1, x_high = 5, rho = .653) %>% is.atomic())
})
test_that("SAVF_score computes correctly", {
expect_equal(SAVF_score(x, x_low = 1, x_high = 5, rho = .653) %>% round(2) %>% .[[1]], 0.57)
expect_equal(SAVF_score(x, x_low = 2, x_high = 4, rho = .75) %>% round(2) %>% .[[1]], 0.14)
}) |
stat_density <- function(mapping = NULL, data = NULL,
geom = "area", position = "stack",
...,
bw = "nrd0",
adjust = 1,
kernel = "gaussian",
n = 512,
trim = FALSE,
na.rm = FALSE,
orientation = NA,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = StatDensity,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
bw = bw,
adjust = adjust,
kernel = kernel,
n = n,
trim = trim,
na.rm = na.rm,
orientation = orientation,
...
)
)
}
StatDensity <- ggproto("StatDensity", Stat,
required_aes = "x|y",
default_aes = aes(x = after_stat(density), y = after_stat(density), fill = NA, weight = NULL),
setup_params = function(data, params) {
params$flipped_aes <- has_flipped_aes(data, params, main_is_orthogonal = FALSE, main_is_continuous = TRUE)
has_x <- !(is.null(data$x) && is.null(params$x))
has_y <- !(is.null(data$y) && is.null(params$y))
if (!has_x && !has_y) {
abort("stat_density() requires an x or y aesthetic.")
}
params
},
extra_params = c("na.rm", "orientation"),
compute_group = function(data, scales, bw = "nrd0", adjust = 1, kernel = "gaussian",
n = 512, trim = FALSE, na.rm = FALSE, flipped_aes = FALSE) {
data <- flip_data(data, flipped_aes)
if (trim) {
range <- range(data$x, na.rm = TRUE)
} else {
range <- scales[[flipped_names(flipped_aes)$x]]$dimension()
}
density <- compute_density(data$x, data$weight, from = range[1],
to = range[2], bw = bw, adjust = adjust, kernel = kernel, n = n)
density$flipped_aes <- flipped_aes
flip_data(density, flipped_aes)
}
)
compute_density <- function(x, w, from, to, bw = "nrd0", adjust = 1,
kernel = "gaussian", n = 512) {
nx <- length(x)
if (is.null(w)) {
w <- rep(1 / nx, nx)
} else {
w <- w / sum(w)
}
if (nx < 2) {
warn("Groups with fewer than two data points have been dropped.")
return(new_data_frame(list(
x = NA_real_,
density = NA_real_,
scaled = NA_real_,
ndensity = NA_real_,
count = NA_real_,
n = NA_integer_
), n = 1))
}
dens <- stats::density(x, weights = w, bw = bw, adjust = adjust,
kernel = kernel, n = n, from = from, to = to)
new_data_frame(list(
x = dens$x,
density = dens$y,
scaled = dens$y / max(dens$y, na.rm = TRUE),
ndensity = dens$y / max(dens$y, na.rm = TRUE),
count = dens$y * nx,
n = nx
), n = length(dens$x))
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.