code
stringlengths 1
13.8M
|
---|
dprime_compare <-
function(correct, total, protocol, conf.level=0.95,
statistic = c("likelihood", "Pearson", "Wald.p", "Wald.d"),
estim = c("ML", "weighted.avg"))
{
stat <- match.arg(statistic)
estim <- match.arg(estim)
stopifnot(is.numeric(conf.level) && length(conf.level) == 1 &&
0 < conf.level && conf.level < 1)
.data <- dprime_table(correct, total, protocol)
dExp.list <- dprime_estim(data=.data, estim=estim)
res1 <- dprime_testStat(data=.data, res=dExp.list,
conf.level=conf.level, dprime0=0,
statistic="likelihood")
res2 <- dprime_compareStat(data=.data, dExp=dExp.list$dExp,
statistic=stat)
res <- c(res2, list(data=.data, coefficients=coef(res1),
conf.level=res1$conf.level,
conf.int=res1$conf.int, estim=estim,
conf.method=res1$conf.method))
class(res) <- "dprime_compare"
res
}
dprime_test <-
function(correct, total, protocol, conf.level = 0.95,
dprime0 = 0,
statistic = c("likelihood", "Wald"),
alternative = c("difference", "similarity", "two.sided",
"less", "greater"),
estim = c("ML", "weighted.avg"))
{
stat <- match.arg(statistic)
alt <- match.arg(alternative)
estim <- match.arg(estim)
stopifnot(is.numeric(conf.level) && length(conf.level) == 1 &&
0 < conf.level && conf.level < 1)
stopifnot(is.numeric(dprime0) && length(dprime0) == 1 &&
dprime0 >= 0)
z <- 1
if(isTRUE(all.equal(dprime0, 0)) &&
!alt %in% c("difference", "greater"))
stop("'alternative' has to be 'difference'/'greater' if 'dprime0' is 0")
if(alt == "difference") alt <- "greater"
if(alt == "similarity") alt <- "less"
.data <- dprime_table(correct, total, protocol)
dExp.list <- dprime_estim(data=.data, estim=estim)
res <-
dprime_testStat(data=.data, res=dExp.list, conf.level=conf.level,
dprime0=dprime0, statistic=stat)
res <- c(res, dExp.list, list(data=.data, alternative=alt))
res$p.value <- normalPvalue(res$stat.value, alternative=alt)
class(res) <- "dprime_test"
res
}
posthoc <- function(x, ...) {
UseMethod("posthoc")
}
posthoc.dprime_compare <-
function(x, alpha = .05,
test = c("pairwise", "common", "base", "zero"),
base = 1,
alternative = c("two.sided", "less", "greater"),
statistic = c("likelihood", "Wald"),
padj.method = c("holm", "bonferroni", "none"), ...)
{
stat <- match.arg(statistic)
alt <- match.arg(alternative)
p.meth <- match.arg(padj.method[1], p.adjust.methods)
stopifnot(round(base) == base)
base <- as.integer(round(base))
dprime0 <- 0
if(is.character(test)) {
test <- match.arg(test)
} else if(is.numeric(test)) {
dprime0 <- test
test <- "value"
stopifnot(length(dprime0) == 1 && dprime0 >= 0)
} else stop("'test' has to be numeric or character")
N <- NROW(x$data)
if(test == "base") dprime0 <- x$data[base, "dhat"]
fit <- getPosthoc(data=x$data, base=base, dprime0=dprime0,
type=test, statistic=stat)
coef <- fit$coef.table
pval <- normalPvalue(fit$statistic, alternative=alt)
coef[["p-value"]] <- p.adjust(pval, method=p.meth)
res <- c(x, list(posthoc=coef, test=test,
padj.method=p.meth, base=base,
posthoc.stat=statistic))
res$alternative <- alt
if(test == "pairwise" && alt == "two.sided") {
signifs <- setNames(coef[["p-value"]] < alpha, rownames(coef))
ia.res <- insert_absorb(signifs, decreasing=TRUE)
letterOrder <- order(as.numeric(substring(names(ia.res$Letters), 6)))
res$Letters <- ia.res$Letters[letterOrder]
}
if(!test %in% c("pairwise", "common"))
res$dprime0 <- dprime0
class(res) <- c(paste0("posthoc.", class(x)), class(x))
res
}
posthoc.dprime_test <- posthoc.dprime_compare
dprime_table <-
function(correct, total, protocol, restrict.above.guess = TRUE)
{
stopifnot(is.numeric(correct) && is.numeric(total))
stopifnot(all(is.finite(c(correct, total))))
if(is.factor(protocol))
protocol <- as.character(protocol)
if(!is.character(protocol))
stop("'protocol' should be a factor or a character vector")
stopifnot(is.logical(restrict.above.guess))
restrict.above.guess <- restrict.above.guess[1]
stopifnot(all(correct == round(correct)))
correct <- as.integer(round(correct))
stopifnot(all(total == round(total)))
total <- as.integer(round(total))
stopifnot(length(correct) == length(total))
stopifnot(length(correct) == length(protocol))
stopifnot(length(correct) >= 1)
stopifnot(all(correct <= total) && all(correct >= 0) &&
all(total > 0))
protValid <- c("triangle", "duotrio", "threeAFC", "twoAFC", "tetrad")
stopifnot(all(protocol %in% protValid))
.data <- data.frame("correct"=correct, "total"=total,
"protocol"=protocol, stringsAsFactors=FALSE)
rownames(.data) <- paste("group", 1:NROW(.data), sep="")
x <- correct
n <- total
pHat <- correct/total
if(restrict.above.guess) {
pG <- ifelse(protocol %in% c("duotrio", "twoAFC"), 1/2, 1/3)
OK <- pHat > pG
pHat[!OK] <- pG[!OK]
}
.data$pHat <- pHat
.data$se.pHat <- se.pHat <- sqrt(pHat * (1 - pHat) / total)
.data$dprime <- sapply(1:NROW(.data), function(i)
psyinv(pHat[i], protocol[i]))
se.dprime <- sapply(1:NROW(.data), function(i) {
se.pHat[i] / psyderiv(.data$dprime[i], protocol[i]) })
se.dprime[!is.finite(se.dprime)] <- NA
.data$se.dprime <- se.dprime
.data
}
dprime_estim <-
function(data, estim = c("ML", "weighted.avg"))
{
estim <- match.arg(estim)
res <- list(estim=estim)
if(estim == "ML") {
fit <- nlminb(start=1, objective=dprime_nll, df=data, lower=0)
res$dExp <- fit$par
res$se.dExp <-
if(fit$par < 1e-4) NA
else
as.vector(sqrt(1/hessian(func=dprime_nll, x=fit$par, df=data)))
res$nll.dExp <- fit$objective
}
if(estim == "weighted.avg") {
dprime <- data$dprime
se.dprime <- data$se.dprime
if(!all(is.finite(c(dprime, se.dprime))))
stop("Boundary cases occured: use 'estim = ML' instead")
w <- se.dprime^2
w.prime <- w / sum(w)
res$dExp <- sum(dprime / w) / sum(1 / w)
res$se.dExp <- sqrt(sum(w.prime^2 * w))
}
res
}
dprime_nll <- function(dp, df) {
meth <- as.character(df[, 3])
nll.i <- sapply(1:nrow(df), function(i) {
- dbinom(x=df[i, 1], size=df[i, 2],
prob=psyfun(dp, method=meth[i]), log=TRUE) } )
sum(nll.i)
}
dprime_testStat <-
function(data, res, conf.level=0.95, dprime0=0,
statistic = c("likelihood", "Wald"))
{
stat <- match.arg(statistic)
dExp <- res$dExp
se.dExp <- res$se.dExp
if(stat == "likelihood") {
nll.0 <- dprime_nll(dprime0, data)
if(is.null(nll.dExp <- res$nll.dExp))
nll.dExp <- dprime_nll(dExp, data)
LR <- 2 * (nll.0 - nll.dExp)
statis <- sign(dExp - dprime0) * sqrt(abs(LR))
}
if(stat == "Wald") {
if(!all(is.finite(c(dExp, se.dExp))))
stop("Boundary cases occured: use 'statistic = likelihood' instead",
call.=FALSE)
statis <- (dExp - dprime0) / se.dExp
}
a <- (1 - conf.level)/2
ci <- dExp + c(1, -1) * qnorm(a) * se.dExp
ci <- delimit(ci, 0, Inf)
.coef <- data.frame(dExp, se.dExp, ci[1], ci[2])
colnames(.coef) <- c("Estimate", "Std. Error", "Lower", "Upper")
rownames(.coef) <- "d-prime"
list(coefficients=.coef, stat.value=statis, conf.int=ci,
statistic=stat, dprime0=dprime0, conf.level=conf.level,
conf.method="Wald")
}
dprime_compareStat <-
function(data, dExp,
statistic = c("likelihood", "Pearson", "Wald.p", "Wald.d"))
{
stat <- match.arg(statistic)
x <- data$correct
n <- data$total
O <- c(x, n-x)
prot <- as.character(data$protocol)
if(stat == "likelihood") {
pExp <- sapply(prot, function(x) psyfun(dExp, method = x))
E <- n * c(pExp, 1 - pExp)
X <- 2 * sum(O * log(O/E))
}
if(stat == "Pearson") {
pExp <- sapply(prot, function(x) psyfun(dExp, method = x))
E <- n * c(pExp, 1 - pExp)
X <- sum( (O - E)^2 / E)
}
if(stat == "Wald.p") {
pExp <- sapply(prot, function(x) psyfun(dExp, method = x))
X <- sum( (data$pHat - pExp)^2/(data$pHat * (1 - data$pHat) / n))
}
if(stat == "Wald.d") {
dprime <- data$dprime
se.dprime <- data$se.dprime
if(!all(is.finite(c(dprime, se.dprime))))
stop("Boundary cases occured: use 'likelihood' or 'Pearson' instead")
X <- sum( ((dprime - dExp)/se.dprime)^2 )
}
df <- NROW(data) - 1
pval <-
if(df >= 1) pchisq(X, df=NROW(data)-1, lower.tail=FALSE)
else NA
list(stat.value=X, df=df, p.value=pval, statistic=stat)
}
getPosthoc <-
function(data, base = 1, dprime0 = 0,
type = c("pairwise", "common", "base", "zero", "value"),
statistic = c("likelihood", "Wald"), ...)
{
type <- match.arg(type)
stat <- match.arg(statistic)
N <- NROW(data)
nll.alt0 <- sapply(1:N, function(i)
dprime_nll(data$dprime[i], df=data[i, 1:3]))
if(type %in% c("pairwise", "base")) {
K <- switch(EXPR = type,
"pairwise" = contrMat(setNames(1:N, rownames(data)),
type="Tukey"),
"base" = contrMat(setNames(1:N, rownames(data)),
type="Dunnett", base=base))
coef <- data.frame("Estimate" = K %*% data[, "dprime"])
coef$"Std. Error" <- sqrt(abs(K) %*% data[, "se.dprime"]^2)
if(stat == "likelihood") {
select.list <- lapply(1:nrow(K), function(i) which(K[i, ] != 0))
nll.0 <- sapply(select.list, function(sel) {
nlminb(start=1, objective=dprime_nll, df=data[sel, ],
lower=0)$objective })
nll.alt <- sapply(select.list, function(sel) sum(nll.alt0[sel]))
LR <- -2 * (nll.alt - nll.0)
statis <- sign(K %*% data[, "dprime"]) * sqrt(abs(LR))
}
else
statis <- coef[, "Estimate"] / coef[, "Std. Error"]
}
else {
coef <- data[, c("dprime", "se.dprime")]
colnames(coef) <- c("Estimate", "Std. Error")
pd0 <- sapply(1:N, function(i) {
meth <- data$protocol[i]
pg <- ifelse(meth %in% c("duotrio", "twoAFC"), .5, 1/3)
pc <- psyfun(dprime0, method=meth)
pc2pd(pc, pg)
})
discrim.list <- lapply(1:N, function(i) {
discrim(data[i, 1], data[i, 2], method=data[i, 3], pd0=pd0[i],
statistic=stat) })
coef$"Lower" <- sapply(discrim.list, function(dl) coef(dl)[3, 3] )
coef$"Upper" <- sapply(discrim.list, function(dl) coef(dl)[3, 4] )
if(type == "common") {
fit2 <- nlminb(start=1, objective=dprime_nll, df=data, lower=0)
nll.0c <- fit2$objective
alt <- sapply(seq_len(nrow(data)), function(sel) {
nlminb(start=1, objective=dprime_nll, df=data[-sel, ],
lower=0)$objective })
nll.altc <- alt + nll.alt0
LR <- -2 * (nll.altc - nll.0c)
statis <- sign(data[, "dprime"] - dprime0) * sqrt(abs(LR))
}
else
statis <- sapply(discrim.list, "[[", "stat.value")
}
list(statistic=statis, coef.table=coef)
}
print.dprime_compare <-
function(x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\n\tTest of multiple d-primes:\n\n")
Estim <- if(x$estim == "ML") "Maximum likelihood" else
"Weighted average"
cat(paste("Estimation method: ",
Estim, "\n", sep=""))
cat(paste(format(x$conf.level, digits=2), "% ",
"two-sided confidence interval method: ",
x$conf.method, "\n", sep=""))
cat("\nEstimate of common d-prime:\n")
print(x$coefficients, quote = FALSE, digits = digits, ...)
cat("\nSignificance test:\n")
cat(" Null hypothesis: All d-primes are equal\n")
cat(" Alternative: At least 2 d-primes are different\n")
stat.chr <- if(x$statistic == "likelihood")
"Likelihood Ratio" else x$statistic
cat(paste(" Chi-square statistic (", stat.chr,") = ",
format(x$stat.value, digits=digits), ", df = ", x$df,
"\n p-value = ", format.pval(x$p.value), "\n", sep=""))
cat("\n")
invisible(x)
}
print.dprime_test <-
function(x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\n\tTest of common d-prime:\n\n")
Estim <- if(x$estim == "ML") "Maximum likelihood" else
"Weighted average"
cat(paste("Estimation method: ",
Estim, "\n", sep=""))
cat(paste(format(x$conf.level, digits=2), "% ",
"two-sided confidence interval method: ",
x$conf.method, "\n", sep=""))
cat("\nEstimate of common d-prime:\n")
print(x$coefficients, quote = FALSE, digits = digits, ...)
cat("\nSignificance test:\n")
stat.chr <- if(x$statistic == "likelihood")
"Likelihood root" else "Wald"
alt.chr <- switch(x$alternative,
"two.sided" = "different from",
"greater" = "greater than",
"less" = "less than",
"similarity" = "less than",
"difference" = "greater than")
cat(paste(" ", stat.chr, " statistic = ",
format(x$stat.value, digits=digits),
", p-value: ", format.pval(x$p.value, digits=digits),
"\n", sep=""))
cat(paste(" Alternative hypothesis: d-prime is", alt.chr,
format(x$dprime0, digits=digits), "\n"))
cat("\n")
invisible(x)
}
print.posthoc.dprime_compare <-
function(x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\n\tPost-hoc comparison of d-primes:\n\n")
if(x$test == "pairwise")
cat("Pairwise d-prime differences:\n")
else if(x$test == "base")
cat(paste("Differences to group ", x$base, ":\n", sep=""))
else
cat("Group-wise d-primes:\n")
ph.mat <- x$posthoc
ph.mat["p-value"] <- format.pval(ph.mat$"p-value", digits=digits)
print(ph.mat, quote = FALSE, digits = digits, ...)
cat("---\n")
if(x$padj.method == "none")
cat("p-values are not adjusted for multiplicity\n")
else
cat(paste("p-values are adjusted with ", x$padj.method,
"'s method\n", sep=""))
cat("\n")
cat("Alternative hypotheses:\n")
alt.mess <- switch(x$alternative,
"two.sided" = "different from",
"greater" = "greater than",
"less" = "less than")
if(x$test == "pairwise")
cat(paste(" pairwise differences are", alt.mess, "zero\n"))
if(x$test == "common")
cat(paste(" d-primes are", alt.mess, "common d-prime\n"))
if(x$test == "base")
cat(paste(" d-primes differences are", alt.mess, "zero\n"))
if(x$test %in% c("zero", "value"))
cat(paste(" d-primes are", alt.mess,
format(x$dprime0, digits=digits), "\n"))
if(x$test == "pairwise" && !is.null(x$Letters)) {
cat("\nLetter display based on pairwise comparisons:\n ")
print(x$Letters)
}
cat("\n")
invisible(x)
}
print.posthoc.dprime_test <- print.posthoc.dprime_compare
insert_absorb <- function( x, Letters=c(letters, LETTERS), separator=".", decreasing = decreasing ){
obj_x <- deparse(substitute(x))
namx <- names(x)
namx <- gsub(" ", "", names(x))
if(length(namx) != length(x))
stop("Names required for ", obj_x)
split_names <- strsplit(namx, "-")
stopifnot( sapply(split_names, length) == 2 )
comps <- t(as.matrix(as.data.frame(split_names)))
rownames(comps) <- names(x)
lvls <- unique(as.vector(comps))
n <- length(lvls)
lmat <- array(TRUE, dim=c(n,1), dimnames=list(lvls, NULL) )
if( sum(x) == 0 ){
ltrs <- rep(get_letters(1, Letters=Letters, separator=separator), length(lvls) )
names(ltrs) <- lvls
colnames(lmat) <- ltrs[1]
msl <- ltrs
ret <- list(Letters=ltrs, monospacedLetters=msl, LetterMatrix=lmat)
class(ret) <- "multcompLetters"
return(ret)
}
else{
signifs <- comps[x,,drop=FALSE]
absorb <- function(m){
for(j in 1:(ncol(m)-1)){
for(k in (j+1):ncol(m)){
if( all(m[which(m[,k]),k] & m[which(m[,k]),j]) ){
m <- m[,-k, drop=FALSE]
return(absorb(m))
}
else if( all(m[which(m[,j]),k] & m[which(m[,j]),j]) ){
m <- m[,-j, drop=FALSE]
return(absorb(m))
}
}
}
return(m)
}
for( i in 1:nrow(signifs) ){
tmpcomp <- signifs[i,]
wassert <- which(lmat[tmpcomp[1],] & lmat[tmpcomp[2],])
if(any(wassert)){
tmpcols <- lmat[,wassert,drop=FALSE]
tmpcols[tmpcomp[2],] <- FALSE
lmat[tmpcomp[1],wassert] <- FALSE
lmat <- cbind(lmat, tmpcols)
colnames(lmat) <- get_letters( ncol(lmat), Letters=Letters,
separator=separator)
if(ncol(lmat) > 1){
lmat <- absorb(lmat)
colnames(lmat) <- get_letters( ncol(lmat), Letters=Letters,
separator=separator )
}
}
}
}
lmat <- lmat[,order(apply(lmat, 2, sum))]
lmat <- sweepLetters(lmat)
lmat <- lmat[,names(sort(apply(lmat,2, function(x) return(min(which(x))))))]
colnames(lmat) <- get_letters( ncol(lmat), Letters=Letters,
separator=separator)
lmat <- lmat[,order(apply(lmat, 2, sum))]
lmat <- sweepLetters(lmat)
lmat <- lmat[,names(sort(apply(lmat,2, function(x) return(min(which(x)))),
decreasing = decreasing))]
colnames(lmat) <- get_letters( ncol(lmat), Letters=Letters,
separator=separator)
ltrs <- apply(lmat,1,function(x) return(paste(names(x)[which(x)], sep="", collapse="") ) )
msl <- matrix(ncol=ncol(lmat), nrow=nrow(lmat))
for( i in 1:nrow(lmat) ){
msl[i,which(lmat[i,])] <- colnames(lmat)[which(lmat[i,])]
absent <- which(!lmat[i,])
if( length(absent) < 2 ){
if( length(absent) == 0 )
next
else{
msl[i,absent] <- paste( rep(" ", nchar(colnames(lmat)[absent])), collapse="" )
}
}
else{
msl[i,absent] <- unlist( lapply( sapply( nchar(colnames(lmat)[absent]),
function(x) return(rep( " ",x)) ),
paste, collapse="") )
}
}
msl <- apply(msl, 1, paste, collapse="")
names(msl) <- rownames(lmat)
ret <- list( Letters=ltrs, monospacedLetters=msl, LetterMatrix=lmat,
aLetters = Letters, aseparator = separator )
class(ret) <- "multcompLetters"
return(ret)
}
sweepLetters <- function(mat, start.col=1, Letters=c(letters, LETTERS), separator="."){
stopifnot( all(start.col %in% 1:ncol(mat)) )
locked <- matrix(rep(0,ncol(mat)*nrow(mat)), ncol=ncol(mat))
cols <- 1:ncol(mat)
cols <- cols[c( start.col, cols[-start.col] )]
if( any(is.na(cols) ) )
cols <- cols[-which(is.na(cols))]
for( i in cols){
tmp <- matrix(rep(0,ncol(mat)*nrow(mat)), ncol=ncol(mat))
tmp[which(mat[,i]),] <- mat[which(mat[,i]),]
one <- which(tmp[,i]==1)
if( all(apply(tmp[,-i,drop=FALSE], 1, function(x) return( any(x==1) ))) ){
next
}
for( j in one ){
if( locked[j,i] == 1 ){
next
}
chck <- 0
lck <- list()
for( k in one ){
if( j==k ){
next
}
else{
rows <- tmp[c(j,k),]
dbl <- rows[1,] & rows[2,]
hit <- which(dbl)
hit <- hit[-which(hit==i)]
dbl <- rows[1,-i,drop=FALSE] & rows[2,-i,drop=FALSE]
if( any(dbl) ){
chck <- chck + 1
lck[[chck]] <- list(c(j,hit[length(hit)]), c(k,hit[length(hit)]))
}
}
}
if( (chck == (length(one)-1)) && chck != 0 ){
for( k in 1:length(lck) ){
locked[ lck[[k]][[1]][1], lck[[k]][[1]][2] ] <- 1
locked[ lck[[k]][[2]][1], lck[[k]][[2]][2] ] <- 1
}
mat[j,i] <- FALSE
}
}
if(all(mat[,i]==FALSE)){
mat <- mat[,-i,drop=FALSE]
colnames(mat) <- get_letters( ncol(mat), Letters=Letters, separator=separator)
return(sweepLetters(mat, Letters=Letters, separator=separator))
}
}
onlyF <- apply(mat, 2, function(x) return(all(!x)))
if( any(onlyF) ){
mat <- mat[,-which(onlyF),drop=FALSE]
colnames(mat) <- get_letters( ncol(mat), Letters=Letters, separator=separator)
}
return( mat )
}
get_letters <- function( n, Letters=c(letters, LETTERS), separator="." ){
n.complete <- floor(n / length(Letters))
n.partial <- n %% length(Letters)
lett <- character()
separ=""
if( n.complete > 0 ){
for( i in 1:n.complete ){
lett <- c(lett, paste(separ, Letters, sep="") )
separ <- paste( separ, separator, sep="" )
}
}
if(n.partial > 0 )
lett <- c(lett, paste(separ, Letters[1:n.partial], sep="") )
return(lett)
} |
library(treeman)
library(testthat)
tree <- randTree(100, wndmtrx=sample(c(TRUE, FALSE), 1))
context('Testing \'TreeMan Class\'')
test_that('vaildObject() works', {
expect_true(validObject(tree))
tree@ndlst[['n2']][['id']] <- 'oh oh.... invalid ID'
expect_error(validObject(tree))
})
test_that('[[ works', {
nd <- sample(names(tree@ndlst), 1)
nd <- tree[[nd]]
expect_that(class(nd)[[1]], equals('Node'))
})
test_that('[ works', {
expect_error(tree['not a valid slot name'])
expect_type(tree['age'], 'double')
expect_type(tree['ultr'], 'logical')
expect_that(tree['ntips'], equals(100))
expect_that(tree['nnds'], equals(99))
}) |
xsplineTangent.s1pos.s2neg.noA0.A3.y <- function(px0, px1, px2, px3, py0, py1, py2, py3, s1, s2, t) {
(((((1/(1 + s1) * ((t + s1)/(1 + s1)) + ((t + s1)/(1 +
s1)) * (1/(1 + s1))) * ((t + s1)/(1 + s1)) + ((t + s1)/(1 +
s1)) * ((t + s1)/(1 + s1)) * (1/(1 + s1))) * (10 - (2 * (1 +
s1) * (1 + s1)) + (2 * (2 * (1 + s1) * (1 + s1)) - 15) *
((t + s1)/(1 + s1)) + (6 - (2 * (1 + s1) * (1 + s1))) * ((t +
s1)/(1 + s1)) * ((t + s1)/(1 + s1))) + ((t + s1)/(1 + s1)) *
((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1)) * ((2 * (2 * (1 +
s1) * (1 + s1)) - 15) * (1/(1 + s1)) + ((6 - (2 * (1 + s1) *
(1 + s1))) * (1/(1 + s1)) * ((t + s1)/(1 + s1)) + (6 - (2 *
(1 + s1) * (1 + s1))) * ((t + s1)/(1 + s1)) * (1/(1 + s1))))) *
py2 - ((1 - t) * ((1 - t) * ((1 - t) * ((1 - t) * (4 - 5 *
(-s2)) + (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))) +
(8 - 12 * (-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) *
(4 - 5 * (-s2))))) + (2 * (-s2) + (1 - t) * (8 - 12 *
(-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))))) +
((-s2) + (1 - t) * (2 * (-s2) + (1 - t) * (8 - 12 * (-s2) +
(1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2))))))) *
py1 + (((-s2) + (t - 1) * (2 * (-s2) + (t - 1) * (t - 1) *
(-2 * (-s2) - (t - 1) * (-s2)))) + (t - 1) * ((2 * (-s2) +
(t - 1) * (t - 1) * (-2 * (-s2) - (t - 1) * (-s2))) + (t -
1) * (((t - 1) + (t - 1)) * (-2 * (-s2) - (t - 1) * (-s2)) -
(t - 1) * (t - 1) * (-s2)))) * py3)/(0 + (1 - t) * ((-s2) +
(1 - t) * (2 * (-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) *
(14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))))) + ((t +
s1)/(1 + s1)) * ((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1)) *
(10 - (2 * (1 + s1) * (1 + s1)) + (2 * (2 * (1 + s1) * (1 +
s1)) - 15) * ((t + s1)/(1 + s1)) + (6 - (2 * (1 + s1) *
(1 + s1))) * ((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1))) +
(t - 1) * ((-s2) + (t - 1) * (2 * (-s2) + (t - 1) * (t -
1) * (-2 * (-s2) - (t - 1) * (-s2))))) - (0 * py0 + (1 -
t) * ((-s2) + (1 - t) * (2 * (-s2) + (1 - t) * (8 - 12 *
(-s2) + (1 - t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))))) *
py1 + ((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1)) * ((t + s1)/(1 +
s1)) * (10 - (2 * (1 + s1) * (1 + s1)) + (2 * (2 * (1 + s1) *
(1 + s1)) - 15) * ((t + s1)/(1 + s1)) + (6 - (2 * (1 + s1) *
(1 + s1))) * ((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1))) *
py2 + (t - 1) * ((-s2) + (t - 1) * (2 * (-s2) + (t - 1) *
(t - 1) * (-2 * (-s2) - (t - 1) * (-s2)))) * py3) * (((1/(1 +
s1) * ((t + s1)/(1 + s1)) + ((t + s1)/(1 + s1)) * (1/(1 +
s1))) * ((t + s1)/(1 + s1)) + ((t + s1)/(1 + s1)) * ((t +
s1)/(1 + s1)) * (1/(1 + s1))) * (10 - (2 * (1 + s1) * (1 +
s1)) + (2 * (2 * (1 + s1) * (1 + s1)) - 15) * ((t + s1)/(1 +
s1)) + (6 - (2 * (1 + s1) * (1 + s1))) * ((t + s1)/(1 + s1)) *
((t + s1)/(1 + s1))) + ((t + s1)/(1 + s1)) * ((t + s1)/(1 +
s1)) * ((t + s1)/(1 + s1)) * ((2 * (2 * (1 + s1) * (1 + s1)) -
15) * (1/(1 + s1)) + ((6 - (2 * (1 + s1) * (1 + s1))) * (1/(1 +
s1)) * ((t + s1)/(1 + s1)) + (6 - (2 * (1 + s1) * (1 + s1))) *
((t + s1)/(1 + s1)) * (1/(1 + s1)))) - ((1 - t) * ((1 - t) *
((1 - t) * ((1 - t) * (4 - 5 * (-s2)) + (14 * (-s2) - 11 +
(1 - t) * (4 - 5 * (-s2)))) + (8 - 12 * (-s2) + (1 -
t) * (14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2))))) +
(2 * (-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) * (14 *
(-s2) - 11 + (1 - t) * (4 - 5 * (-s2)))))) + ((-s2) +
(1 - t) * (2 * (-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) *
(14 * (-s2) - 11 + (1 - t) * (4 - 5 * (-s2))))))) + (((-s2) +
(t - 1) * (2 * (-s2) + (t - 1) * (t - 1) * (-2 * (-s2) -
(t - 1) * (-s2)))) + (t - 1) * ((2 * (-s2) + (t - 1) *
(t - 1) * (-2 * (-s2) - (t - 1) * (-s2))) + (t - 1) * (((t -
1) + (t - 1)) * (-2 * (-s2) - (t - 1) * (-s2)) - (t - 1) *
(t - 1) * (-s2)))))/(0 + (1 - t) * ((-s2) + (1 - t) * (2 *
(-s2) + (1 - t) * (8 - 12 * (-s2) + (1 - t) * (14 * (-s2) -
11 + (1 - t) * (4 - 5 * (-s2)))))) + ((t + s1)/(1 + s1)) *
((t + s1)/(1 + s1)) * ((t + s1)/(1 + s1)) * (10 - (2 * (1 +
s1) * (1 + s1)) + (2 * (2 * (1 + s1) * (1 + s1)) - 15) *
((t + s1)/(1 + s1)) + (6 - (2 * (1 + s1) * (1 + s1))) * ((t +
s1)/(1 + s1)) * ((t + s1)/(1 + s1))) + (t - 1) * ((-s2) +
(t - 1) * (2 * (-s2) + (t - 1) * (t - 1) * (-2 * (-s2) -
(t - 1) * (-s2)))))^2)
} |
tNSS.SD <- function(x, n.cuts = NULL)
{
dim_x <- dim(x)
r <- length(dim_x) - 1
n <- dim_x[r + 1]
if(length(dim_x) == 2){
Xmu <- rowMeans(x)
returnlist <- NSS.SD(t(x), n.cut = n.cuts)
returnlist$S <- t(returnlist$S)
returnlist2 <- list(S = returnlist$S,
W = returnlist$W,
EV = returnlist$EV,
n.cuts = returnlist$n.cut,
Xmu = Xmu,
datatype = "ts")
class(returnlist2) <- c("tbss", "bss")
return(returnlist2)
}
if(any(is.null(n.cuts))){
n.cuts <- c(0, floor((n + 1)/2), n)
}
slices <- as.numeric(cut(1:n, breaks = n.cuts, labels = 1:2))
Xmu <- apply(x, 1:r, mean)
x_center <- tensorCentering(x)
W_list <- vector("list", r)
for(m in 1:r)
{
x_slice_1 <- arraySelectLast(x_center, (slices == 1))
x_slice_2 <- arraySelectLast(x_center, (slices == 2))
mMAC_1 <- mModeCovariance(x_slice_1, m, center = TRUE)
symm_mMAC_1 <- 0.5*(mMAC_1 + t(mMAC_1))
mMAC_2 <- mModeCovariance(x_slice_2, m, center = TRUE)
symm_mMAC_2 <- 0.5*(mMAC_2 + t(mMAC_2))
eig_mMAC_1 <- eigen(mMAC_1, symmetric = TRUE)
mMAC_1_root <- eig_mMAC_1$vectors%*%diag(eig_mMAC_1$values^(-1/2))%*%t(eig_mMAC_1$vectors)
eig_final <- eigen(tcrossprod(crossprod(mMAC_1_root, mMAC_2), mMAC_1_root), symmetric = TRUE)
U <- eig_final$vectors
W_list[[m]] <- crossprod(U, mMAC_1_root)
}
S <- x_center
for(m in 1:r)
{
S <- tensorTransform(S, W_list[[m]], m)
}
returnlist <- list(S = S,
W = W_list,
EV = eig_final$values,
n.cuts = n.cuts,
Xmu = Xmu,
datatype = "ts")
class(returnlist) <- c("tbss", "bss")
return(returnlist)
} |
setClass("dictionary2", contains = "list",
slots = c(
meta = "list"
),
prototype = prototype(
meta = list(system = list(),
object = list(),
user = list())
)
)
setValidity("dictionary2", function(object) {
validate_dictionary(object)
})
validate_dictionary <- function(dict) {
attrs <- attributes(dict)
dict <- unclass(dict)
if (is.null(names(dict))) {
stop("Dictionary elements must be named: ",
paste(unlist(dict, recursive = TRUE), collapse = " "))
}
if (any(names(dict) == "")) {
unnamed <- dict[which(names(dict) == "")]
stop("Unnamed dictionary entry: ",
paste(unlist(unnamed, use.names = FALSE), collapse = " "))
}
if (field_object(attrs)[["separator"]] == "") {
stop("Concatenator cannot be null or an empty string")
}
check_entries(dict)
}
check_entries <- function(dict) {
for (i in seq_along(dict)) {
entry <- dict[[i]]
is_category <- vapply(entry, is.list, logical(1))
if (any(!is_category)) {
word <- unlist(entry[!is_category], use.names = FALSE)
if (!is.character(word) || any(is.na(word))) {
stop("Non-character entries found in dictionary key \'", names(dict[i]), "\'")
}
}
if (any(is_category)) {
category <- entry[is_category]
check_entries(category)
}
}
}
dictionary <- function(x, file = NULL, format = NULL,
separator = " ",
tolower = TRUE, encoding = "utf-8") {
UseMethod("dictionary")
}
dictionary.default <- function(x, file = NULL, format = NULL,
separator = " ",
tolower = TRUE, encoding = "utf-8") {
if (!missing(x) & is.null(file))
stop("x must be a list if file is not specified")
separator <- check_character(separator, min_nchar = 1)
tolower <- check_logical(tolower)
formats <- c(cat = "wordstat",
dic = "LIWC",
ykd = "yoshikoder",
lcd = "yoshikoder",
lc3 = "lexicoder",
yml = "YAML")
if (!file.exists(file))
stop("File does not exist: ", file)
if (is.null(format)) {
ext <- stri_trans_tolower(tools::file_ext(file))
if (ext %in% names(formats)) {
format <- formats[[ext]]
} else {
stop("Unknown dictionary file extension: ", ext)
}
} else {
format <- match.arg(format, formats)
}
if (format == "wordstat") {
x <- read_dict_wordstat(file, encoding)
} else if (format == "LIWC") {
x <- read_dict_liwc(file, encoding)
} else if (format == "yoshikoder") {
x <- read_dict_yoshikoder(file)
} else if (format == "lexicoder") {
x <- read_dict_lexicoder(file)
} else if (format == "YAML") {
x <- yaml::yaml.load_file(file, as.named.list = TRUE)
x <- list2dictionary(x)
}
if (tolower) x <- lowercase_dictionary_values(x)
x <- merge_dictionary_values(x)
build_dictionary2(x, separator = separator)
}
dictionary.list <- function(x, file = NULL, format = NULL,
separator = " ",
tolower = TRUE, encoding = "utf-8") {
separator <- check_character(separator, min_nchar = 1)
tolower <- check_logical(tolower)
if (!is.null(file) || !is.null(format) || encoding != "utf-8")
stop("cannot specify file, format, or encoding when x is a list")
x <- list2dictionary(x)
if (tolower) x <- lowercase_dictionary_values(x)
x <- replace_dictionary_values(x, separator, " ")
x <- merge_dictionary_values(x)
build_dictionary2(x, separator = separator)
}
dictionary.dictionary2 <- function(x, file = NULL, format = NULL,
separator = " ",
tolower = TRUE, encoding = "utf-8") {
x <- as.dictionary(x)
dictionary(as.list(x), separator = separator, tolower = tolower,
encoding = encoding)
}
setMethod("as.list",
signature = c("dictionary2"),
function(x, flatten = FALSE, levels = 1:100) {
x <- as.dictionary(x)
if (flatten) {
result <- flatten_dictionary(x, levels)
attributes(result)[setdiff(names(attributes(result)), "names")] <- NULL
return(result)
} else {
simplify_dictionary(x)
}
})
as.dictionary <- function(x, format = c("tidytext"), separator = " ", tolower = FALSE) {
UseMethod("as.dictionary")
}
as.dictionary.default <- function(x, format = c("tidytext"), separator = " ", tolower = FALSE) {
check_class(class(x), "as.dictionary")
}
as.dictionary.dictionary2 <- function(x, ...) {
check_dots(...)
upgrade_dictionary2(x)
}
as.dictionary.data.frame <- function(x, format = c("tidytext"), separator = " ", tolower = FALSE) {
format <- match.arg(format)
separator <- check_character(separator)
tolower <- check_logical(tolower)
if (format == "tidytext") {
if (!all(c("word", "sentiment") %in% names(x)))
stop("data.frame must contain word and sentiment columns")
if ("lexicon" %in% names(x) && length(unique(x[["lexicon"]])) > 1)
warning("multiple values found in a \'lexicon\' column; ",
"you may be mixing different dictionaries")
if (all(is.na(x[["sentiment"]])))
stop("sentiment values are missing")
}
dictionary(split(as.character(x$word), factor(x$sentiment)),
separator = separator, tolower = tolower)
}
is.dictionary <- function(x) {
is(x, "dictionary2")
}
setMethod("print", signature(x = "dictionary2"),
function(x,
max_nkey = quanteda_options("print_dictionary_max_nkey"),
max_nval = quanteda_options("print_dictionary_max_nval"),
show_summary = quanteda_options("print_dictionary_summary"),
...) {
x <- as.dictionary(x)
max_nkey <- check_integer(max_nkey, min = -1)
max_nval <- check_integer(max_nval, min = -1)
show_summary <- check_logical(show_summary)
check_dots(...)
if (show_summary) {
depth <- dictionary_depth(x)
lev <- if (depth > 1L) " primary" else ""
nkey <- length(names(x))
cat("Dictionary object with ", nkey, lev, " key entr",
if (nkey == 1L) "y" else "ies", sep = "")
if (lev != "") cat(" and ", depth, " nested levels", sep = "")
cat(".\n")
}
invisible(print_dictionary(x, 1, max_nkey, max_nval, show_summary, ...))
})
setMethod("show", signature(object = "dictionary2"), function(object) print(object))
print_dictionary <- function(entry, level = 1,
max_nkey, max_nval, show_summary, ...) {
nkey <- length(entry)
entry <- unclass(entry)
if (max_nkey >= 0)
entry <- head(unclass(entry), max_nkey)
if (!length(entry)) return()
is_category <- vapply(entry, is.list, logical(1))
category <- entry[is_category]
pad <- rep(" ", level - 1)
word <- unlist(entry[!is_category], use.names = FALSE)
if (length(word)) {
if (max_nval < 0)
max_nval <- length(word)
cat(pad, "- ", paste(head(word, max_nval), collapse = ", "), sep = "")
nval_rem <- length(word) - max_nval
if (nval_rem > 0)
cat(" [ ... and ", format(nval_rem, big.mark = ","), " more ]", sep = "")
cat("\n", sep = "")
}
for (i in seq_along(category)) {
cat(pad, "- [", names(category[i]), "]:\n", sep = "")
print_dictionary(category[[i]], level + 1, max_nkey, max_nval, show_summary)
}
nkey_rem <- nkey - length(entry)
if (nkey_rem > 0) {
cat(pad, "[ reached max_nkey ... ", format(nkey_rem, big.mark = ","), " more key",
if (nkey_rem > 1) "s", " ]\n", sep = "")
}
}
setMethod("[",
signature = c("dictionary2", i = "index"),
function(x, i) {
x <- as.dictionary(x)
x <- unclass(x)
attrs <- attributes(x)
is_category <- vapply(x[i], function(y) is.list(y), logical(1))
result <- build_dictionary2(x[i][is_category],
separator = field_object(attrs, "separator"),
valuetype = field_object(attrs, "valuetype"))
meta(result) <- attrs[["meta"]][["user"]]
result@meta$object <- attrs[["meta"]][["object"]]
result
})
setMethod("[[",
signature = c("dictionary2", i = "index"),
function(x, i) {
x <- as.dictionary(x)
x <- unclass(x)
attrs <- attributes(x)
is_category <- vapply(x[[i]], function(y) is.list(y), logical(1))
if (all(is_category == FALSE)) {
unlist(x[[i]], use.names = FALSE)
} else {
build_dictionary2(x[[i]][is_category],
separator = field_object(attrs, "separator"),
valuetype = field_object(attrs, "valuetype"))
}
})
`$.dictionary2` <- function(x, name) {
x[[name]]
}
setMethod("c",
signature = c("dictionary2"),
function(x, ...) {
x <- as.dictionary(x)
attrs <- attributes(x)
y <- list(...)
if (length(y) == 0)
return(x)
result <- c(unclass(x), unclass(y[[1]]))
if (length(y) > 1) {
for (i in 2:length(y)) {
result <- c(result, unclass(y[[i]]))
}
}
result <- merge_dictionary_values(result)
build_dictionary2(result,
valuetype = field_object(attrs, "valuetype"),
separator = field_object(attrs, "separator"))
})
split_values <- function(dict, concatenator_dictionary, concatenator_tokens) {
key <- rep(names(dict), lengths(dict))
value <- unlist(dict, use.names = FALSE)
is_multi <- stri_detect_fixed(value, concatenator_dictionary)
if (any(is_multi)) {
result <- vector("list", length(value) + sum(is_multi))
l <- !seq_along(result) %in% (seq_along(value) + cumsum(is_multi))
result[l] <- stri_split_fixed(value[is_multi], concatenator_dictionary)
result[!l] <- as.list(stri_replace_all_fixed(value,
concatenator_dictionary,
concatenator_tokens))
names(result) <- key[rep(seq_along(value), 1 + is_multi)]
} else {
result <- as.list(stri_replace_all_fixed(value,
concatenator_dictionary,
concatenator_tokens))
names(result) <- key
}
return(result)
}
flatten_dictionary <- function(dict, levels = 1:100, level = 1,
key_parent = "", dict_flat = list()) {
dict <- unclass(dict)
for (i in seq_along(dict)) {
key <- names(dict[i])
entry <- dict[[i]]
if (key == "" || !length(entry)) next
if (level %in% levels) {
if (key_parent != "") {
key_entry <- paste(key_parent, key, sep = ".")
} else {
key_entry <- key
}
} else {
key_entry <- key_parent
}
is_category <- vapply(entry, is.list, logical(1))
dict_flat[[key_entry]] <-
c(dict_flat[[key_entry]],
unlist(entry[!is_category], use.names = FALSE))
dict_flat <- flatten_dictionary(entry[is_category], levels,
level + 1, key_entry, dict_flat)
}
dict_flat <- dict_flat[names(dict_flat) != ""]
attributes(dict_flat, FALSE) <- attributes(dict)
return(dict_flat)
}
lowercase_dictionary_values <- function(dict) {
dict <- unclass(dict)
for (i in seq_along(dict)) {
if (is.list(dict[[i]])) {
dict[[i]] <- lowercase_dictionary_values(dict[[i]])
} else {
if (is.character(dict[[i]])) {
dict[[i]] <- stri_trans_tolower(dict[[i]])
}
}
}
dict
}
replace_dictionary_values <- function(dict, from, to) {
dict <- unclass(dict)
for (i in seq_along(dict)) {
if (is.list(dict[[i]])) {
dict[[i]] <- replace_dictionary_values(dict[[i]], from, to)
} else {
if (is.character(dict[[i]])) {
dict[[i]] <- stri_replace_all_fixed(dict[[i]], from, to)
}
}
}
return(dict)
}
merge_dictionary_values <- function(dict) {
if (is.null(names(dict))) return(dict)
if (any(duplicated(names(dict)))) {
dict <- lapply(split(dict, names(dict)), function(x) {
names(x) <- NULL
unlist(x, recursive = FALSE)
})
}
for (i in seq_along(dict)) {
dict_temp <- dict[[i]]
if (is.null(names(dict_temp))) {
dict[[i]] <- list(unlist_character(dict_temp, use.names = FALSE))
} else {
is_value <- names(dict_temp) == ""
dict[[i]] <- merge_dictionary_values(dict_temp[!is_value])
if (any(is_value)) {
dict[[i]] <- c(
dict[[i]],
list(unlist_character(dict_temp[is_value], use.names = FALSE))
)
}
}
}
return(dict)
}
list2dictionary <- function(dict) {
for (i in seq_along(dict)) {
if (is.list(dict[[i]])) {
dict[[i]] <- list2dictionary(dict[[i]])
} else {
if (is.character(dict[[i]])) {
dict[[i]] <- list(unique(stri_trim_both(stri_enc_toutf8(dict[[i]]))))
} else {
dict[[i]] <- list(dict[[i]])
}
}
}
return(dict)
}
NULL
read_dict_lexicoder <- function(path) {
lines <- stri_read_lines(path, encoding = "utf-8")
lines <- stri_trim_both(lines)
lines_yaml <- ifelse(stri_detect_regex(lines, "^\\+"),
stri_replace_all_regex(lines, "^+(.+)$", '"$1":'),
stri_replace_all_regex(lines, "^(.+)$", ' - "$1"'))
lines_yaml <- stri_replace_all_regex(lines_yaml, "[[:control:]]", "")
yaml <- paste0(lines_yaml, collapse = "\n")
dict <- yaml::yaml.load(yaml, as.named.list = TRUE)
dict <- list2dictionary(dict)
return(dict)
}
read_dict_wordstat <- function(path, encoding = "utf-8") {
lines <- stri_read_lines(path, encoding = encoding)
lines <- stri_trim_right(lines)
lines_yaml <- ifelse(stri_detect_regex(lines, " \\(\\d\\)$"),
stri_replace_all_regex(lines, "^(\\t*)(.+) \\(\\d\\)$", '$1- "$2"'),
stri_replace_all_regex(lines, "^(\\t*)(.+)$", '$1- "$2": '))
lines_yaml <- stri_replace_all_regex(lines_yaml, "\t", " ")
lines_yaml <- stri_replace_all_regex(lines_yaml, "[[:control:]]", "")
yaml <- paste0(lines_yaml, collapse = "\n")
dict <- yaml::yaml.load(yaml, as.named.list = TRUE)
dict <- list2dictionary_wordstat(dict, FALSE)
return(dict)
}
list2dictionary_wordstat <- function(entry, omit = TRUE, dict = list()) {
if (omit) {
for (i in seq_along(entry)) {
key <- names(entry[i])
if (is.list(entry[i])) {
dict[[key]] <- list2dictionary_wordstat(entry[[i]], FALSE)
}
}
} else {
if (length(entry)) {
is_category <- vapply(entry, is.list, logical(1))
category <- entry[is_category]
for (i in seq_along(category)) {
dict <- list2dictionary_wordstat(category[[i]], TRUE, dict)
}
dict[[length(dict) + 1]] <- unlist(entry[!is_category], use.names = FALSE)
}
}
return(dict)
}
remove_empty_keys <- function(dict) {
for (i in rev(seq_along(dict))) {
if (identical(dict[[i]], list(character(0)))) {
message("note: removing empty key: ", paste(names(dict[i]), collapse = ", "))
dict <- dict[i * -1]
} else {
if (!is.character(dict[[i]])) {
dict[[i]] <- remove_empty_keys(dict[[i]])
}
}
}
return(dict)
}
nest_dictionary <- function(dict, depth) {
if (length(dict) != length(depth))
stop("Depth vectot must have the same length as dictionary")
depth_max <- max(depth)
while (depth_max > 1) {
i_max <- which(depth == depth_max)
for (i in i_max) {
i_parent <- tail(which(head(depth, i - 1) < depth_max), 1)
if (!length(dict[[i_parent]][[1]]))
dict[[i_parent]][[1]] <- NULL
dict[[i_parent]] <- c(dict[[i_parent]], dict[i])
}
dict <- dict[i_max * -1]
depth <- depth[i_max * -1]
depth_max <- max(depth)
}
return(dict)
}
read_dict_liwc <- function(path, encoding = "utf-8") {
line <- stri_read_lines(path, encoding = encoding)
tab <- stri_extract_first_regex(line, "^\t+")
line <- stri_trim_both(line)
line <- line[line != ""]
section <- which(line == "%")
if (length(section) < 2) {
stop("Start and end of a category legend should be marked by '%' but none were found")
}
line_key <- line[(section[1] + 1):(section[2] - 1)]
tab_key <- tab[(section[1] + 1):(section[2] - 1)]
line_value <- line[(section[2] + 1):(length(line))]
has_oftag <- stri_detect_fixed(line_value, "<of>")
if (any(has_oftag)) {
catm("note: ", sum(has_oftag), " term",
if (sum(has_oftag) > 1L) "s" else "",
" ignored because contains unsupported <of> tag\n", sep = "")
line_value <- line_value[!has_oftag]
}
has_paren <- stri_detect_regex(line_value, "\\(.+\\)")
if (any(has_paren)) {
catm("note: ignoring parenthetical expressions in lines:\n")
for (i in which(has_paren))
catm(" [line ", i + section[2] + 1, "] ", line_value[i], "\n", sep = "")
line_value <- stri_replace_all_regex(line_value, "\\(.+\\)", " ")
}
line_key <- stri_replace_all_regex(line_key, "(\\d+)\\s+", "$1\t")
key_id <- as.integer(stri_extract_first_regex(line_key, "\\d+"))
key <- stri_extract_last_regex(line_key, "[^\t]+")
depth <- ifelse(is.na(tab_key), 0, stri_length(tab_key)) + 1
line_value <- stri_replace_all_regex(line_value, "\\s+(\\d+)", "\t$1")
value <- stri_extract_first_regex(line_value, "[^\t]+")
line_value <- stri_replace_first_regex(line_value, ".+?\t", "")
values_id <- stri_extract_all_regex(line_value, "\\d+")
value_id <- as.integer(unlist(values_id, use.names = FALSE))
value_rep <- rep(value, lengths(values_id))
key <- stri_trim_both(stri_replace_all_regex(key, "[[:control:]]", ""))
value <- stri_trim_both(stri_replace_all_regex(value, "[[:control:]]", ""))
key_match <- key[match(value_id, key_id)]
is_undef <- is.na(key_match)
if (any(is_undef)) {
catm("note: ignoring undefined categories:\n")
for (i in which(is_undef))
catm(" ", value_id[i], " for ", value_rep[i], "\n", sep = "")
}
dict <- split(value_rep, factor(key_match, levels = key))
dict <- lapply(dict, function(x) sort(unique(x)))
dict <- list2dictionary(dict)
if (any(depth != max(depth))) {
dict <- nest_dictionary(dict, depth)
}
dict <- remove_empty_keys(dict)
dict
}
read_dict_yoshikoder <- function(path) {
xml <- xml2::read_xml(path)
root <- xml2::xml_find_first(xml, paste0("/", "dictionary"))
dict <- nodes2list(root)
dict <- list2dictionary(dict)
return(dict)
}
nodes2list <- function(node, dict = list()) {
nodes <- xml2::xml_find_all(node, "cnode")
if (length(nodes)) {
for (i in seq_along(nodes)) {
key <- xml2::xml_attrs(nodes[[i]])["name"]
dict[[key]] <- nodes2list(nodes[[i]], dict)
}
} else {
dict <- unname(unlist(xml2::xml_attrs(xml2::xml_find_all(node, "pnode"), "name")))
}
return(dict)
}
as.yaml <- function(x) {
UseMethod("as.yaml")
}
as.yaml.dictionary2 <- function(x) {
yaml <- yaml::as.yaml(simplify_dictionary(x, TRUE), indent.mapping.sequence = TRUE)
yaml <- stri_enc_toutf8(yaml)
return(yaml)
}
simplify_dictionary <- function(entry, omit = TRUE, dict = list()) {
entry <- unclass(entry)
if (omit) {
dict <- simplify_dictionary(entry, FALSE)
} else {
if (length(entry)) {
is_category <- vapply(entry, is.list, logical(1))
category <- entry[is_category]
if (any(is_category)) {
for (i in seq_along(category)) {
dict[[names(category[i])]] <-
simplify_dictionary(category[[i]], TRUE, dict)
}
dict[["__"]] <- unlist(entry[!is_category], use.names = FALSE)
} else {
dict <- unlist(entry, use.names = FALSE)
}
}
}
return(dict)
}
dictionary_depth <- function(dict, depth = -1) {
dict <- unclass(dict)
if (is.list(dict) && length(dict) > 0) {
return(max(unlist(lapply(dict, dictionary_depth, depth = depth + 1))))
} else {
return(depth)
}
}
has_multiword <- function(dict) {
any(stri_detect_fixed(unlist(dict, use.names = FALSE), attr(dict, "concatenator")))
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(bbreg)
fit <- bbreg(agreement ~ priming + eliciting, data = WT)
fit
fit_beta <- bbreg(agreement ~ priming + eliciting, data = WT, model = "beta")
fit_beta
fit_priming <- bbreg(agreement ~ priming + eliciting | priming, data = WT)
fit_priming
fit_priming_eliciting <- bbreg(agreement ~ priming + eliciting | priming + eliciting, data = WT)
fit_priming_eliciting
summary(fit)
summary(fit_beta)
summary(fit_priming)
fit_cloglog <- bbreg(agreement ~ priming + eliciting, data = WT, link.mean = "cloglog")
fit_cloglog
fit_cloglog_sqrt <- bbreg(agreement ~ priming + eliciting, data = WT,
link.mean = "cloglog", link.precision = "sqrt")
fit_cloglog_sqrt
fit_priming_sqrt <- bbreg(agreement ~ priming + eliciting| priming, data = WT,
link.precision = "sqrt")
fit_priming_sqrt
fitted_means <- fitted(fit)
head(fitted_means)
fitted_variances <- fitted(fit, type = "variance")
head(fitted_variances)
new_data_example <- data.frame(priming = c(0,0,1), eliciting = c(0,1,1))
predict(fit_priming_eliciting, newdata = new_data_example)
predict(fit_priming_eliciting, newdata = new_data_example, type = "variance")
predict(fit, newdata = new_data_example)
predict(fit, newdata = new_data_example, type = "variance")
predict_without_newdata <- predict(fit)
identical(predict_without_newdata, fitted_means)
fit_envelope <- bbreg(agreement ~ priming + eliciting, envelope = 300, data = WT)
summary(fit_envelope)
plot(fit)
plot(fit_envelope, which = 2)
plot(fit, which = c(1,4), ask = FALSE) |
backgroundCondition <- function(lower = NULL, upper = NULL,
center = NULL, radius = NULL,
transparent = NULL,
alpha_channel = FALSE,
quietly = TRUE) {
if (!isTRUE(alpha_channel)) {
alpha_channel <- NULL
}
args_list <- list(lower = lower, upper = upper,
center = center, radius = radius,
transparent = transparent,
alpha_channel = alpha_channel)
null_count <- which(!unlist(lapply(args_list, is.null)))
null_count <- paste(null_count, collapse = "")
combos <- data.frame(vec = c("",
"12", "34",
"5", "125", "345",
"56", "1256", "3456"),
category = c("none",
"rect", "sphere",
"none", "rect", "sphere",
rep("transparent", 3)))
category_idx <- match(null_count, combos$vec)
if (is.na(category_idx)) {
warning("Could not parse background parameters; no pixels will be masked")
category <- "none"
} else {
category <- combos$category[category_idx]
}
if (category == "transparent") {
bg_condition <- "transparent"
class(bg_condition) <- "bg_t"
msg <- "Using transparency to mask pixels"
} else if (category == "rect") {
bg_condition <- list(lower = lower, upper = upper)
class(bg_condition) <- "bg_rect"
msg <- paste("Masking pixels in range:\n",
paste("R: ", paste(lower[1], "-", upper[1], sep = ""),
"; G: ", paste(lower[2], "-", upper[2], sep = ""),
"; B: ", paste(lower[3], "-", upper[3], sep = ""),
sep = ""))
} else if (category == "sphere") {
bg_condition <- list(center = center, radius = radius)
class(bg_condition) <- "bg_sphere"
msg <- paste("Masking pixels in range:\n",
paste("Center: ", paste(center, collapse = ", "),
" +/- ", radius * 100, "%", sep = ""))
} else if (category == "none") {
bg_condition <- NA
class(bg_condition) <- "bg_none"
msg <- "Using all pixels"
} else {
stop("uh oh!!")
}
if (!quietly) { message(msg) }
return(bg_condition)
} |
HTestimator<-function(y,pik)
{
if(any(is.na(pik))) stop("there are missing values in pik")
if(any(is.na(y))) stop("there are missing values in y")
if(length(y)!=length(pik)) stop("y and pik have different sizes")
crossprod(y,1/pik)
} |
meta.retrieval <- function(db = "refseq",
kingdom,
group = NULL,
type = "genome",
restart_at_last = TRUE,
reference = FALSE,
combine = FALSE,
path = NULL) {
division <- subgroup <- NULL
subfolders <- getKingdoms(db = db)
if (!is.element(kingdom, subfolders))
stop(paste0(
"Please select a valid kingdom: ",
paste0(subfolders, collapse = ", ")
), call. = FALSE)
if (!is.null(group))
if (!is.element(group, getGroups(kingdom = kingdom, db = db)))
stop(
"Please specify a group that is supported by getGroups().
Your specification '",
group,
"' does not exist in getGroups(kingdom = '",
kingdom,
"', db = '",
db,
"'). Maybe you used a different db argument in getGroups()?",
call. = FALSE
)
if (!is.element(type,
c("genome", "proteome", "CDS","cds", "gff",
"rna", "assemblystats", "gtf", "rm")))
stop(
"Please choose either type: type = 'genome', type = 'proteome',
type = 'CDS', type = 'gff', type = 'gtf',
type = 'rna', type = 'rm', or type = 'assemblystats'.",
call. = FALSE
)
if (!is.element(db, c("refseq", "genbank", "ensembl")))
stop(
"Please select einter db = 'refseq', db = 'genbank', or
db = 'ensembl'.",
call. = FALSE
)
if ((stringr::str_to_upper(type) == "CDS") && (db == "genbank"))
stop("Genbank does not store CDS data. Please choose 'db = 'refseq''.",
call. = FALSE)
if ((type == "gtf") && (is.element(db, c("genbank", "refseq"))))
stop("GTF files are only available for type = 'ensembl' and type = 'ensemblgebomes'.")
if (type == "assemblystats" &&
!is.element(db, c("refseq", "genbank")))
stop(
"Unfortunately, assembly stats files are only available for
db = 'refseq' and db = 'genbank'.",
call. = FALSE
)
if (combine && type != "assemblystats")
stop(
"Only option type = 'assemblystats' can use combine = TRUE. Please
specify: type = 'assemblystats' and combine = TRUE.",
call. = FALSE
)
if ((type == "rm") && (!is.element(db, c("refseq", "genbank"))))
stop("Repeat Masker output files can only be retrieved from 'refseq'",
" or 'genbank'.", call. = FALSE)
if (is.element(db, c("refseq", "genbank"))) {
if (is.null(group)) {
assembly.summary.file <-
getSummaryFile(db = db, kingdom = kingdom)
FinalOrganisms <-
unique(assembly.summary.file$organism_name)
}
if (!is.null(group)) {
groups.selection <-
listGroups(kingdom = kingdom,
db = db,
details = TRUE)
groups.selection <-
dplyr::filter(groups.selection, subgroup %in% group)
FinalOrganisms <- unique(groups.selection$organism_name)
}
}
if (db == "ensembl") {
summary.file <- get.ensembl.info()
FinalOrganisms <- unique(summary.file$name)
FinalOrganisms <-
stringr::str_replace_all(FinalOrganisms, "_", " ")
stringr::str_sub(FinalOrganisms, 1, 1) <-
stringr::str_to_upper(stringr::str_sub(FinalOrganisms, 1, 1))
}
if (db == "ensemblgenomes") {
summary.file <- get.ensemblgenome.info()
summary.file <-
dplyr::filter(summary.file, division == kingdom)
FinalOrganisms <- unique(summary.file$accession)
}
if (is.null(group))
message(paste0(
"Starting meta retrieval of all ",
type,
" files for kingdom: ",
kingdom,
" from database: ", db,
"."
))
if (!is.null(group))
message(
paste0(
"Starting meta retrieval of all ",
type,
" files within kingdom '",
kingdom,
"' and subgroup '",
group,"' ",
" from database: ",
db,
"."
)
)
message("\n")
if (!is.null(path)) {
if (!file.exists(path)) {
message("Generating folder ", path, " ...")
dir.create(path, recursive = TRUE)
}
if (!file.exists(file.path(path, "documentation")))
dir.create(file.path(path, "documentation"))
} else {
if (!file.exists(kingdom)) {
message("Generating folder ", kingdom, " ...")
dir.create(kingdom, recursive = TRUE)
}
if (!file.exists(file.path(kingdom, "documentation")))
dir.create(file.path(kingdom, "documentation"))
}
paths <- vector("character", length(FinalOrganisms))
if (is.element(db, c("refseq", "genbank"))) {
if (type == "genome") internal_type <- "genomic"
if (type == "proteome") internal_type <- "protein"
if (stringr::str_to_upper(type) == "CDS") internal_type <- "cds"
if (type == "gff") internal_type <- "genomic"
if (type == "gtf") internal_type <- db
if (type == "rna") internal_type <- "rna"
if (type == "rm") internal_type <- "rm"
if (type == "assemblystats") internal_type <- "assembly"
if (!is.null(path)) {
.existingOrgs <- existingOrganisms(path = path, .type = internal_type)
} else {
.existingOrgs <- existingOrganisms(path = kingdom, .type = internal_type)
}
}
if (db == "ensembl") {
if (type == "genome") internal_type <- "dna"
if (type == "proteome") internal_type <- "pep"
if (stringr::str_to_upper(type) == "CDS") internal_type <- "cds"
if (type == "gff") internal_type <- "ensembl"
if (type == "gtf") internal_type <- "ensembl"
if (type == "rna") internal_type <- "ncrna"
if (!is.null(path)) {
.existingOrgs <- existingOrganisms_ensembl(path = path, .type = internal_type)
} else {
.existingOrgs <- existingOrganisms_ensembl(path = kingdom, .type = internal_type)
}
}
if (db == "ensemblgenomes") {
if (type == "genome") internal_type <- "dna"
if (type == "proteome") internal_type <- "pep"
if (stringr::str_to_upper(type) == "CDS") internal_type <- "cds"
if (type == "gff") internal_type <- "ensemblgenomes"
if (type == "gtf") internal_type <- "ensemblgenomes"
if (type == "rna") internal_type <- "ncrna"
if (!is.null(path)) {
.existingOrgs <- existingOrganisms_ensembl(path = path, .type = internal_type)
} else {
.existingOrgs <- existingOrganisms_ensembl(path = kingdom, .type = internal_type)
}
}
if (length(.existingOrgs) > 0) {
if (restart_at_last) {
FinalOrganisms <- dplyr::setdiff(FinalOrganisms, .existingOrgs)
if (length(FinalOrganisms) > 0) {
message("Skipping already downloaded species: ", paste0(.existingOrgs, collapse = ", "))
message("\n")
}
}
}
if (length(FinalOrganisms) > 0) {
if (type == "genome") {
if (is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getGenome(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = kingdom)
message("\n")
}
}
if (!is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getGenome(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = path)
message("\n")
}
}
}
if (type == "proteome") {
if (is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getProteome(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = kingdom)
message("\n")
}
}
if (!is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getProteome(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = path)
message("\n")
}
}
}
if (stringr::str_to_upper(type) == "CDS") {
if (is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getCDS(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = kingdom)
message("\n")
}
}
if (!is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getCDS(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = path)
message("\n")
}
}
}
if (type == "gff") {
if (is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getGFF(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = kingdom)
message("\n")
}
}
if (!is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getGFF(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = path)
message("\n")
}
}
}
if (type == "gtf") {
if (is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getGTF(db = db,
organism = FinalOrganisms[i],
path = kingdom)
message("\n")
}
}
if (!is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getGTF(db = db,
organism = FinalOrganisms[i],
path = path)
message("\n")
}
}
}
if (type == "rm") {
if (is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getRepeatMasker(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = kingdom)
message("\n")
}
}
if (!is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getRepeatMasker(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = path)
message("\n")
}
}
}
if (type == "rna") {
if (is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
paths[i] <- getRNA(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = kingdom)
message("\n")
}
}
if (!is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
getRNA(db = db,
organism = FinalOrganisms[i],
reference = reference,
path = path)
message("\n")
}
}
}
if (type == "assemblystats") {
stats.files <- vector("list", length(FinalOrganisms))
if (is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
if (combine) {
stats.files[i] <- list(
getAssemblyStats(
db = db,
organism = FinalOrganisms[i],
reference = reference,
path = kingdom,
type = "import"
)
)
names(stats.files[i]) <- FinalOrganisms[i]
message("\n")
} else {
paths[i] <- getAssemblyStats(
db = db,
organism = FinalOrganisms[i],
reference = reference,
path = kingdom
)
message("\n")
}
}
}
if (!is.null(path)) {
for (i in seq_len(length(FinalOrganisms))) {
if (combine) {
stats.files[i] <- list(
getAssemblyStats(
db = db,
organism = FinalOrganisms[i],
reference = reference,
path = path,
type = "import"
)
)
names(stats.files[i]) <- FinalOrganisms[i]
} else {
paths[i] <- getAssemblyStats(
db = db,
reference = reference,
organism = FinalOrganisms[i],
path = path
)
}
}
}
}
if (!is.null(path)) {
meta_files <- list.files(path)
meta_files <- meta_files[stringr::str_detect(meta_files, "doc_")]
file.rename(from = file.path(path, meta_files), to = file.path(path, "documentation", meta_files))
doc_tsv_files <- file.path(path,"documentation", meta_files[stringr::str_detect(meta_files, "[.]tsv")])
summary_log <- dplyr::bind_rows(lapply(doc_tsv_files, function(data) {
if (fs::file_size(data) > 0)
suppressMessages(readr::read_tsv(data))
}))
readr::write_excel_csv(summary_log, file.path(path, "documentation", paste0(kingdom, "_summary.csv")))
message("A summary file (which can be used as supplementary information file in publications) containig retrieval information for all ",kingdom," species has been stored at '",file.path(path, "documentation", paste0(kingdom, "_summary.csv")),"'.")
} else {
meta_files <- list.files(kingdom)
meta_files <- meta_files[stringr::str_detect(meta_files, "doc_")]
file.rename(from = file.path(kingdom, meta_files), to = file.path(kingdom, "documentation", meta_files))
doc_tsv_files <- file.path(kingdom,"documentation", meta_files[stringr::str_detect(meta_files, "[.]tsv")])
summary_log <- dplyr::bind_rows(lapply(doc_tsv_files, function(data) {
if (fs::file_size(data) > 0)
suppressMessages(readr::read_tsv(data))
}))
readr::write_excel_csv(summary_log, file.path(kingdom, "documentation", paste0(kingdom, "_summary.csv")))
message("A summary file (which can be used as supplementary information file in publications) containig retrieval information for all ",kingdom," species has been stored at '",file.path(kingdom, "documentation", paste0(kingdom, "_summary.csv")),"'.")
}
if (combine) {
stats.files <- dplyr::bind_rows(stats::na.omit(stats.files))
message("Finished meta retieval process.")
return(stats.files)
}
message("Finished meta retieval process.")
return(paths[!is.element(paths, c("FALSE", "Not available"))])
} else {
if (!is.null(path)) {
meta_files <- list.files(path)
meta_files <- meta_files[stringr::str_detect(meta_files, "doc_")]
file.rename(from = file.path(path, meta_files), to = file.path(path, "documentation", meta_files))
doc_tsv_files <- file.path(path,"documentation", meta_files[stringr::str_detect(meta_files, "[.]tsv")])
summary_log <- dplyr::bind_rows(lapply(doc_tsv_files, function(data) {
if (fs::file_size(data) > 0)
suppressMessages(readr::read_tsv(data))
}))
readr::write_excel_csv(summary_log, file.path(path, "documentation", paste0(kingdom, "_summary.csv")))
message("A summary file (which can be used as supplementary information file in publications) containig retrieval information for all ",kingdom," species has been stored at '",file.path(path, "documentation", paste0(kingdom, "_summary.csv")),"'.")
} else {
meta_files <- list.files(kingdom)
meta_files <- meta_files[stringr::str_detect(meta_files, "doc_")]
file.rename(from = file.path(kingdom, meta_files), to = file.path(kingdom, "documentation", meta_files))
doc_tsv_files <- file.path(kingdom,"documentation", meta_files[stringr::str_detect(meta_files, "[.]tsv")])
summary_log <- dplyr::bind_rows(lapply(doc_tsv_files, function(data) {
if (fs::file_size(data) > 0)
suppressMessages(readr::read_tsv(data))
}))
readr::write_excel_csv(summary_log, file.path(kingdom, "documentation", paste0(kingdom, "_summary.csv")))
message("A summary file (which can be used as supplementary information file in publications) containig retrieval information for all ",kingdom," species has been stored at '",file.path(kingdom, "documentation", paste0(kingdom, "_summary.csv")),"'.")
}
message("The ", type,"s of all species have already been downloaded! You are up to date!")
}
} |
get_swsheet <- function() {
futile.logger::flog.info("Loading 'single_cell_software.csv'...")
swsheet <- readr::read_csv("single_cell_software.csv",
col_types = readr::cols(
.default = readr::col_logical(),
Name = readr::col_character(),
Platform = readr::col_character(),
DOIs = readr::col_character(),
PubDates = readr::col_character(),
Code = readr::col_character(),
Description = readr::col_character(),
License = readr::col_character(),
Added = readr::col_date(format = ""),
Updated = readr::col_date(format = "")
))
}
get_pkgs <- function() {
`%>%` <- magrittr::`%>%`
futile.logger::flog.info("Getting package repositories...")
futile.logger::flog.info("Getting Bioconductor package list...")
bioc.url <- "https://bioconductor.org/packages/release/bioc/"
bioc.pkgs <- xml2::read_html(bioc.url) %>%
rvest::html_nodes("table") %>%
rvest::html_nodes("a") %>%
rvest::html_text()
names(bioc.pkgs) <- stringr::str_to_lower(bioc.pkgs)
futile.logger::flog.info("Getting CRAN package list...")
cran.url <- "https://cran.r-project.org/web/packages/available_packages_by_name.html"
cran.pkgs <- xml2::read_html(cran.url) %>%
rvest::html_nodes("a") %>%
rvest::html_text() %>%
setdiff(LETTERS)
names(cran.pkgs) <- stringr::str_to_lower(cran.pkgs)
futile.logger::flog.info("Getting PyPI package list...")
pypi.pkgs <- xml2::read_html("https://pypi.python.org/simple/") %>%
rvest::html_nodes("a") %>%
rvest::html_text()
names(pypi.pkgs) <- stringr::str_to_lower(pypi.pkgs)
futile.logger::flog.info("Getting Anaconda package list...")
pages <- xml2::read_html("https://anaconda.org/anaconda/repo") %>%
rvest::html_nodes(".unavailable:nth-child(2)") %>%
rvest::html_text() %>%
stringr::str_split(" ") %>%
unlist()
pages <- as.numeric(pages[4])
conda.pkgs <- pbapply::pbsapply(seq_len(pages), function(p) {
url <- paste0("https://anaconda.org/anaconda/repo?sort=_name&sort_order=asc&page=",
p)
xml2::read_html(url) %>%
rvest::html_nodes(".packageName") %>%
rvest::html_text()
})
conda.pkgs <- unlist(conda.pkgs)
names(conda.pkgs) <- stringr::str_to_lower(conda.pkgs)
pkgs <- list(BioC = bioc.pkgs,
CRAN = cran.pkgs,
PyPI = pypi.pkgs,
Conda = conda.pkgs)
}
get_descriptions <- function() {
futile.logger::flog.info("Getting category descriptions...")
descs <- jsonlite::read_json("docs/data/descriptions.json",
simplifyVector = TRUE)
} |
setClass("VanderPol", slots = c(
mu = "numeric"
),
contains = c("ODE")
)
setMethod("initialize", "VanderPol", function(.Object, ...) {
.Object@mu <- 1.0
.Object@state <- vector("numeric", 3)
return(.Object)
})
setMethod("getState", "VanderPol", function(object, ...) {
return(object@state)
})
setMethod("getRate", "VanderPol", function(object, state, ...) {
object@rate[1] <- state[2]
object@rate[2] <- object@mu* (1 - state[1]^2) * state[2] - state[1]
object@rate[3] <- 1
object@rate
})
VanderPol <- function(y1, y2) {
VanderPol <- new("VanderPol")
VanderPol@state[1] = y1
VanderPol@state[2] = y2
VanderPol@state[3] = 0
return(VanderPol)
} |
expected <- eval(parse(text="FALSE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(\"BunchKaufman\", class = structure(\"signature\", package = \"methods\"), .Names = \"x\", package = \"methods\"), structure(\"Matrix\", .Names = \"x\", package = \"Matrix\", class = structure(\"signature\", package = \"methods\")), TRUE, TRUE, TRUE, TRUE, FALSE)"));
.Internal(identical(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]], argv[[7]]));
}, o=expected); |
NULL
qc_fails <- function(object, element = c("sample", "module"), compact = TRUE){
.check_object(object)
element <- match.arg(element)
qc_problems (object, element = element, status = "FAIL", compact = compact)
}
qc_warns <- function(object, element = c("sample", "module"), compact = TRUE){
.check_object(object)
element <- match.arg(element)
qc_problems (object, element = element, status = "WARN", compact = compact)
}
qc_problems <- function(object,
element = c("sample", "module"),
name = NULL,
status = c("FAIL", "WARN"),
compact = TRUE)
{
.check_object(object)
element <- match.arg(element)
not_element <- base::setdiff(c("sample", "module"), element)
if(!all(status %in% c("FAIL", "WARN")))
stop("status should be one of c('FAIL', 'WARN')")
sample <- nb_problems <- module <- NULL
status. <- status
problems <- object %>%
dplyr::filter(status %in% status.) %>%
dplyr::select(sample, module, status)
if(nrow(problems) == 0){
message("There is no problem. All samples pass the QC tests.")
return(problems)
}
if(!is.null(name)){
all.valid.names <- c(problems$sample, problems$module) %>%
unique()
name <- grep(pattern= paste(name, collapse = "|"), all.valid.names,
ignore.case = TRUE, value = TRUE) %>%
unique()
if(length(name) == 0) stop("Incorect names provided.")
problems <- problems %>%
dplyr::filter(sample %in% name | module %in% name)
if(missing(compact)) compact <- FALSE
}
nb_problems <- problems %>%
dplyr::group_by_(element) %>%
dplyr::summarise(nb_problems = n()) %>%
dplyr::arrange(desc(nb_problems))
module <- sample <- NULL
if(element == "sample") .formula <- module~sample
else
.formula <- sample~module
modules_with_problem <- stats::aggregate(.formula, data = problems,
paste, collapse = ", ")
if(compact)
left_join(nb_problems, modules_with_problem, by = element)
else
left_join(problems, nb_problems, by = element) %>%
dplyr::arrange_("desc(nb_problems)", element, "status") %>%
dplyr::select_(element, "nb_problems", not_element, "status")
} |
mr_format <- function(rsid, xbeta, ybeta, xse, yse) {
if (missing(rsid)) {
rsid <- 1:length(ybeta)
message("SNP id variable generated equal to row number in data frame")
}
datm <- data.frame(rsid, xbeta, ybeta, xse, yse)
names(datm) <-
c("rsid",
"beta.exposure",
"beta.outcome",
"se.exposure",
"se.outcome")
class(datm) <- append(class(datm), "mr_format")
return(datm)
} |
selection_criteria <-
function(x, K, G){
K <- x$K
G <- x$G
lb <- x$info$lb
penKG <- penalty(x)
BIC <- lb - penKG
ent_ZW <- x$info$ent_ZW
vICL <- BIC - ent_ZW
a_tilde <- x$info$a_tilde
return(cbind(vICL = vICL, BIC = BIC, penKG = penKG, lb = lb, entZW = ent_ZW, K = K, G = G))
} |
context("layers")
test_call_succeeds("layer_input", {
layer_input(shape = c(32))
input <- layer_input(shape = c(32), ragged = TRUE)
})
test_call_succeeds("layer_dense", {
layer_dense(keras_model_sequential(), 32, input_shape = c(784))
})
test_call_succeeds("layer_activation", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_activation('relu')
})
test_call_succeeds("layer_activation_relu", required_version = "2.2.0", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_activation_relu()
})
test_call_succeeds("layer_activation_selu", required_version = "2.2.0", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_activation_selu()
})
test_call_succeeds("layer_activation_leaky_relu", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_activation_leaky_relu()
})
test_call_succeeds("layer_activation_parametric_relu", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_activation_parametric_relu()
})
test_call_succeeds("layer_activation_thresholded_relu", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_activation_thresholded_relu()
})
test_call_succeeds("layer_activation_elu", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_activation_elu()
})
test_call_succeeds("layer_activity_regularization", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_activity_regularization()
})
test_call_succeeds("layer_dropout", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_dropout(rate = 0.5, noise_shape = c(1))
})
test_call_succeeds("layer_spatial_dropout_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_spatial_dropout_1d(rate = 0.5)
})
test_call_succeeds("layer_spatial_dropout_2d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_spatial_dropout_2d(rate = 0.5)
})
test_call_succeeds("layer_spatial_dropout_3d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,2,2,4)) %>%
layer_spatial_dropout_3d(rate = 0.5)
})
test_call_succeeds("layer_lambda", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_lambda(function(t) t, output_shape = c(784))
})
test_call_succeeds("layer_masking", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_masking(mask_value = 0.5)
})
test_call_succeeds("layer_repeat_vector", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_repeat_vector(3)
})
test_call_succeeds("layer_reshape", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16))
})
test_call_succeeds("layer_permute", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_permute(dims = c(1))
})
test_call_succeeds("layer_flatten", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_flatten()
})
test_call_succeeds("layer_conv_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_conv_1d(filters = 3, kernel_size = 2)
})
test_call_succeeds("layer_conv_2d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_conv_2d(filters = 3, kernel_size = c(2, 2))
})
test_call_succeeds("layer_conv_3d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,2,2,4)) %>%
layer_conv_3d(filters = 3, kernel_size = c(2, 2, 2))
})
test_call_succeeds("layer_conv_1d_transpose", {
if (tensorflow::tf_version() < "2.3") skip("Needs TF >= 2.3")
keras_model_sequential() %>%
layer_dense(32, input_shape = 100) %>%
layer_reshape(target_shape = c(8,4)) %>%
layer_conv_1d_transpose(filters = 3, kernel_size = 2)
})
test_call_succeeds("layer_conv_2d_transpose", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_conv_2d_transpose(filters = 3, kernel_size = c(2, 2))
})
test_call_succeeds("layer_conv_3d_transpose", required_version = "2.0.6", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,2,2,4)) %>%
layer_conv_3d_transpose(filters = 3, kernel_size = c(2, 2, 2))
})
test_call_succeeds("layer_separable_conv_2d", {
if (is_tensorflow_implementation()) {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_separable_conv_2d(filters = 4, kernel_size = c(2,2))
}
})
test_call_succeeds("layer_depthwise_conv_2d", required_version = "2.1.5", {
if (is_tensorflow_implementation()) {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_depthwise_conv_2d(kernel_size = c(2,2))
}
})
if(tf_version() >= "2.8")
test_call_succeeds("layer_depthwise_conv_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(4, -1)) %>%
layer_depthwise_conv_1d(kernel_size = 2)
})
if(tf_version() >= "2.6")
test_call_succeeds("layer_conv_lstm_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_conv_lstm_1d(filters = 3, kernel_size = c(2))
})
test_call_succeeds("layer_conv_lstm_2d", {
keras_model_sequential() %>%
layer_dense(16, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,2,2,2)) %>%
layer_conv_lstm_2d(filters = 3, kernel_size = c(1, 1))
})
if(tf_version() >= "2.6")
test_call_succeeds("layer_conv_lstm_3d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,2,2,2,2)) %>%
layer_conv_lstm_3d(filters = 3, kernel_size = c(1, 1, 2))
})
test_call_succeeds("layer_upsampling_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_upsampling_1d()
})
test_call_succeeds("layer_upsampling_2d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_upsampling_2d()
})
test_call_succeeds("layer_upsampling_3d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,2,2)) %>%
layer_upsampling_3d()
})
test_call_succeeds("layer_zero_padding_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_zero_padding_1d()
})
test_call_succeeds("layer_zero_padding_2d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_zero_padding_2d()
})
test_call_succeeds("layer_zero_padding_3d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,2,2)) %>%
layer_zero_padding_3d()
})
test_call_succeeds("layer_cropping_1d", {
skip_if_cntk()
keras_model_sequential() %>%
layer_dense(64, input_shape = c(784)) %>%
layer_reshape(target_shape = c(4,16)) %>%
layer_cropping_1d()
})
test_call_succeeds("layer_cropping_2d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_cropping_2d()
})
test_call_succeeds("layer_cropping_3d", {
skip_if_cntk()
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,2,2)) %>%
layer_cropping_3d()
})
test_call_succeeds("layer_max_pooling_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_max_pooling_1d()
})
test_call_succeeds("layer_max_pooling_2d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_max_pooling_2d()
})
test_call_succeeds("layer_max_pooling_3d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,2,2,4)) %>%
layer_max_pooling_3d()
})
test_call_succeeds("layer_average_pooling_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_average_pooling_1d()
})
test_call_succeeds("layer_average_pooling_2d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_average_pooling_2d()
})
test_call_succeeds("layer_average_pooling_3d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,2,2,4)) %>%
layer_average_pooling_3d()
})
test_call_succeeds("layer_global_average_pooling_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_global_average_pooling_1d()
})
test_call_succeeds("layer_global_average_pooling_2d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_global_average_pooling_2d()
})
test_call_succeeds("layer_global_average_pooling_3d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,2,2,4)) %>%
layer_global_average_pooling_3d()
})
test_call_succeeds("layer_global_max_pooling_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_global_max_pooling_1d()
})
test_call_succeeds("layer_global_max_pooling_2d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_global_max_pooling_2d()
})
test_call_succeeds("layer_global_max_pooling_3d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,2,2,4)) %>%
layer_global_max_pooling_3d()
})
test_call_succeeds("layer_locally_connected_1d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_locally_connected_1d(filters = 3, kernel_size = 2)
})
test_call_succeeds("layer_locally_connected_2d", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,4,4)) %>%
layer_locally_connected_2d(filters = 3, kernel_size = c(2, 2))
})
test_call_succeeds("layer_simple_rnn", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_simple_rnn(units = 2)
})
test_call_succeeds("layer_gru", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_gru(units = 2)
})
test_call_succeeds("layer_lstm", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_lstm(units = 2)
})
test_call_succeeds("layer_embedding", {
keras_model_sequential() %>%
layer_embedding(1000, 64, input_length = 10)
})
get_merge_inputs <- function() {
c(layer_input(shape = c(4, 5)),
layer_input(shape = c(4, 5)),
layer_input(shape = c(4, 5)))
}
test_call_succeeds("layer_add", {
merge_inputs <- get_merge_inputs()
output <- layer_add(merge_inputs)
keras_model(merge_inputs, output)
output <- layer_add()(merge_inputs)
keras_model(merge_inputs, output)
})
test_call_succeeds(required_version = "2.0.7", "layer_subtract", {
merge_inputs <- c(layer_input(shape = c(4, 5)),
layer_input(shape = c(4, 5)))
output <- layer_subtract(merge_inputs)
keras_model(merge_inputs, output)
output <- layer_subtract()(merge_inputs)
keras_model(merge_inputs, output)
})
test_call_succeeds("layer_multiply", {
merge_inputs <- get_merge_inputs()
output <- layer_multiply(merge_inputs)
keras_model(merge_inputs, output)
output <- layer_multiply()(merge_inputs)
keras_model(merge_inputs, output)
})
test_call_succeeds("layer_maximum", {
merge_inputs <- get_merge_inputs()
output <- layer_maximum(merge_inputs)
keras_model(merge_inputs, output)
output <- layer_maximum()(merge_inputs)
keras_model(merge_inputs, output)
})
test_call_succeeds("layer_minumum", required_version = "2.0.9", {
merge_inputs <- get_merge_inputs()
output <- layer_minimum(merge_inputs)
keras_model(merge_inputs, output)
output <- layer_minimum()(merge_inputs)
keras_model(merge_inputs, output)
})
test_call_succeeds("layer_average", {
merge_inputs <- get_merge_inputs()
output <- layer_average(merge_inputs)
keras_model(merge_inputs, output)
output <- layer_average()(merge_inputs)
keras_model(merge_inputs, output)
})
test_call_succeeds("layer_concatenate", {
merge_inputs <- get_merge_inputs()
output <- layer_concatenate(merge_inputs)
keras_model(merge_inputs, output)
output <- layer_concatenate()(merge_inputs)
keras_model(merge_inputs, output)
})
test_call_succeeds("layer_batch_normalization", {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_batch_normalization()
})
test_call_succeeds("layer_gaussian_noise", {
skip_if_cntk()
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_gaussian_noise(stddev = 0.5)
})
test_call_succeeds("layer_gaussian_dropout", {
skip_if_cntk()
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_gaussian_dropout(rate = 0.5)
})
test_call_succeeds("layer_alpha_dropout", required_version = "2.0.6", {
skip_if_cntk()
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(2,16)) %>%
layer_alpha_dropout(rate = 0.5)
})
test_call_succeeds("time_distributed", {
keras_model_sequential() %>%
time_distributed(layer_dense(units = 8), input_shape = c(10, 16))
})
test_call_succeeds("bidirectional", {
keras_model_sequential() %>%
bidirectional(layer_lstm(units = 10, return_sequences = TRUE), input_shape = c(5, 10)) %>%
bidirectional(layer_lstm(units = 10)) %>%
layer_dense(units = 5) %>%
layer_activation(activation = "softmax")
})
test_call_succeeds("layer_activation_softmax", required_version = "2.1.3", {
if (is_tensorflow_implementation()) {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_activation_softmax()
}
})
test_call_succeeds("layer_separable_conv_1d", required_version = "2.1.3", {
if (is_tensorflow_implementation()) {
keras_model_sequential() %>%
layer_dense(32, input_shape = c(784)) %>%
layer_reshape(target_shape = c(4, 8)) %>%
layer_separable_conv_1d(filters = 4, kernel_size = c(4))
}
})
test_call_succeeds('layer_attention',{
if (is_tensorflow_implementation() && tensorflow::tf_version() >= "1.14"){
input_1 = layer_input(shape=c(4,5))
input_2 = layer_input(shape=c(4,5))
layer_attention(c(input_1,input_2))
}
})
test_call_succeeds("layer_dense_features", required_version = "2.1.3", {
if (is_tensorflow_implementation() && tensorflow::tf_version() >= "1.14") {
fc <- list(tensorflow::tf$feature_column$numeric_column("mpg"))
input <- list(mpg = layer_input(1))
out <- input %>%
layer_dense_features(feature_columns = fc)
feature_layer <- layer_dense_features(feature_columns = fc)
model <- keras_model_sequential(list(
feature_layer,
layer_dense(units = 1)
))
model %>% compile(loss = "mae", optimizer = "adam")
model %>% fit(x = list(mpg = 1:10), y = 1:10, verbose = 0)
}
})
test_succeeds("Can serialize a model that contains dense_features", {
if (tensorflow::tf_version() < "2.0")
skip("TensorFlow 2.0 is required.")
fc <- list(tensorflow::tf$feature_column$numeric_column("mpg"))
input <- list(mpg = layer_input(1))
out <- input %>%
layer_dense_features(feature_columns = fc)
feature_layer <- layer_dense_features(feature_columns = fc)
model <- keras_model_sequential(list(
feature_layer,
layer_dense(units = 1)
))
model %>% compile(loss = "mae", optimizer = "adam")
model %>% fit(x = list(mpg = 1:10), y = 1:10, verbose = 0)
pred <- predict(model, list(mpg = 1:10))
fname <- tempfile()
save_model_tf(model, fname)
loaded <- load_model_tf(fname)
pred2 <- predict(loaded, list(mpg = 1:10))
expect_equal(pred, pred2)
}) |
ResamplingVariance=function(output,pi,type=c("total","mean"),option=1,N=NULL,pij=NULL,str=NULL,clu=NULL,srswr=FALSE){
if(!is.list(output)){stop("output must be a list.")}
if(any(is.na(output))){stop("There are missing values in output.")}
if(!is.character(type)){stop("type must be a character")}
if((type!="total")&(type!="mean")){stop("The value of type must be total or mean.")}
if((option<1)|(option>3)){stop("The value of option must be between 1 and 3.")}
if(!is.logical(srswr)){srswr=as.logical(srswr)}
if((srswr!=TRUE)&(srswr!=FALSE)){stop("The value of srswr must be TRUE or FALSE")}
if((is.null(pij))&(option!=1)){
warning("If you do not introduce pij you must choose the jackknife method. The output given is done with the jackknife method without strata nor cluster.")
option=1
}
if(is.null(N)){
N=round(sum(1/pi))
}
if(option==1){
strata=FALSE
if(!is.null(str)){
strata=TRUE
if(!is.factor(str)){str=as.factor(str)}
}
cluster=FALSE
if(!is.null(clu)){
cluster=TRUE
if(!is.factor(clu)){clu=as.factor(clu)}
}
if((strata==FALSE)&(cluster==FALSE)){
Rve=JackknifeVariance(length(pi),output$TransformedVariable,pi)
}
if((strata==TRUE)&(cluster==FALSE)){
nh=table(str)
ve=vector()
for(i in levels(str)){
ve[i]=JackknifeVariance(nh[i],output$TransformedVariable[str==i],pi[str==i],strata)
}
Rve=sum(ve)
}
if((strata==FALSE)&(cluster==TRUE)){
Rve=JackknifeVariance(length(levels(clu)),output$TransformedVariable,pi,cluster=cluster,clu=clu)
}
if((strata==TRUE)&(cluster==TRUE)){
ve=vector()
for(i in levels(str)){
cl_sti=droplevels(clu[str==i])
ve[i]=JackknifeVariance(nlevels(cl_sti),output$TransformedVariable[str==i],pi[str==i],strata,cluster,cl_sti)
}
Rve=sum(ve)
}
if(type=="mean"){
if(length(N)!=1){stop("N must be a scalar.")}
if(N<0){stop("N must be a positive number.")}
Rve=Rve/N^2
}
}
if(option==2){
Rve=EscobarBergerVariance(N,output$TransformedVariable,pi,pij,type)
}
if(option==3){
Rve=CampbellBergerSkinnerVariance(N,output$TransformedVariable,pi,pij,type)
}
if(srswr==TRUE){
Rve=Rve/(1-mean(pi))
}
return(Rve)
} |
fv_dsc_box_rank <- function(width = 12, collapsible = T, collapsed = F) {
box(title = HTML('<p style="font-size:120%;">Deep Statistical Comparison (DSC)
analysis - Ranking per Function</p>'),
width = width, solidHeader = T, status = "primary",
collapsible = collapsible, collapsed = collapsed,
sidebarPanel(
width = 3,
selectInput('FV_Stats.DSC.ID', 'IDs to compare', choices = NULL,
selected = NULL, multiple = T),
selectInput('FV_Stats.DSC.Funcid', 'Functions to use', choices = NULL,
selected = NULL, multiple = T),
selectInput('FV_Stats.DSC.Dim', 'Dimensions to use', choices = NULL,
selected = NULL, multiple = T),
hr(),
numericInput('FV_Stats.DSC.Alpha_rank',
label = "Threshold for statistical significance",
value = 0.05, min = 0, max = 0.5),
numericInput('FV_Stats.DSC.Epsilon_rank',
label = "Threshold for practical significance (pDSC)",
value = 0) %>%
shinyInput_label_embed(
custom_icon() %>%
bs_embed_popover(
title = "Practical Significance", content = Pdsc_info,
placement = "auto"
)
),
numericInput('FV_Stats.DSC.MCsamples_rank',
label = "Number of monte carlo samples to use in the DSC procdure",
value = 0) %>%
shinyInput_label_embed(
custom_icon() %>%
bs_embed_popover(
title = "Monte Carlo Samples", content = Pdsc_mc_info,
placement = "auto"
)
),
selectInput("FV_Stats.DSC.Test_rank", "Test Type",
choices = c("Anderson-Darling", "Kolmogorov-Smirnov"),
selected = "Anderson-Darling"),
actionButton('FV_Stats.DSC.Create_rank', 'Create Ranking'),
hr(),
selectInput('FV_Stats.DSC.Format_rank', label = 'Select the figure format',
choices = supported_fig_format, selected = supported_fig_format[[1]]),
downloadButton('FV_Stats.DSC.Download_rank', label = 'Download the figure'),
selectInput('FV_Stats.DSC.TableFormat_rank', label = 'Select the table format',
choices = supported_table_format, selected = supported_table_format[[1]]),
downloadButton('FV_Stats.DSC.Download_rank_table', label = 'Download the raw ranking data')
),
mainPanel(
width = 9,
HTML_P("The <b>DSC</b> comparison is described in the paper: 'DSCTool: A web-service-based
framework for statistical comparison of stochastic optimization algorithms.' by
T. Eftimov et al.
This is the first of 3 parts of the process: the per-function ranking procedure.
The two other processes are the omnibus test and the post-hoc processing,
which are shown in the two boxes below this one.
Note that both of these are impacted by the settings selected for this
ranking procedure!"),
HTML_P("The chosen <b>budget values</b> per (function, dimension)-pair are as follows
(double click an entry to edit it):"),
DT::dataTableOutput("FV_Stats.DSC.Targets"),
hr(),
HTML_P("The results of the ranking are shown in the following plot, using the visualization techniques
as described in the paper: 'PerformViz: A Machine Learning Approach to Visualize and
Understand the Performance of Single-objective Optimization
Algorithms' By T. Eftimov et al. Performviz allows one to clearly see,
from a single plot, which algorithms are most suited for a given problem,
the influence of each problem on the overall algorithm performance and
similarities among both algorithms and problems."),
plotOutput("FV_Stats.DSC.PerformViz", height = "800px")
)
)
}
fv_dsc_box_omni <- function(width = 12, collapsible = T, collapsed = F) {
box(title = HTML('<p style="font-size:120%;">Deep Statistical Comparison (DSC)
analysis - Omnibus Test</p>'),
width = width, solidHeader = T, status = "primary",
collapsible = collapsible, collapsed = collapsed,
sidebarPanel(
width = 3,
selectInput('FV_Stats.DSC.Omni_options', "Select which statistical test to use",
choices = NULL, selected = NULL),
numericInput('FV_Stats.DSC.Alpha_omni',
label = "Threshold for statistical significance",
value = 0.05, min = 0, max = 0.5),
actionButton('FV_Stats.DSC.Create_omni', 'Perform Omnibus Test')
),
mainPanel(
width = 9,
HTML_P('This is the result of the omnibus test on the data from the ranking procedure above.
Note that this test has to be performed before doing the post-hoc comparison!'),
hr(),
textOutput('FV_Stats.DSC.Output_omni')
)
)
}
fv_dsc_box_posthoc <- function(width = 12, collapsible = T, collapsed = F) {
box(title = HTML('<p style="font-size:120%;">Deep Statistical Comparison (DSC)
analysis - Posthoc comparison</p>'),
width = width, solidHeader = T, status = "primary",
collapsible = collapsible, collapsed = collapsed,
sidebarPanel(
width = 3,
selectInput('FV_Stats.DSC.Posthoc_test', 'Post-hoc Test', choices =
c('friedman', 'friedman-aligned-rank'),
selected = 'friedman', multiple = F),
selectInput('FV_Stats.DSC.Posthoc_method', 'Post-hoc P-value Correction Method', choices =
c('Holm', 'Hochberg', 'unadjusted P'),
selected = 'Holm', multiple = F),
numericInput('FV_Stats.DSC.Alpha_posthoc',
label = "Threshold for statistical significance",
value = 0.05, min = 0, max = 0.5),
actionButton('FV_Stats.DSC.Create_posthoc', 'Create Comparison'),
hr(),
selectInput('FV_Stats.DSC.Format', label = 'Select the figure format',
choices = supported_fig_format, selected = supported_fig_format[[1]]),
downloadButton('FV_Stats.DSC.Download', label = 'Download the figure'),
hr(),
selectInput('FV_Stats.DSC.TableFormat', label = 'Select the table format',
choices = supported_table_format, selected = supported_table_format[[1]]),
downloadButton('FV_Stats.DSC.DownloadTable', label = 'Download the table')
),
mainPanel(
width = 9,
HTML_P("The results of the post-hoc comparison are:"),
plotlyOutput.IOHanalyzer("FV_Stats.DSC.PosthocViz"),
DT::dataTableOutput('FV_Stats.DSC.PosthocTable')
)
)
}
rt_dsc_box_rank <- function(width = 12, collapsible = T, collapsed = F) {
box(title = HTML('<p style="font-size:120%;">Deep Statistical Comparison (DSC)
analysis - Ranking per Function</p>'),
width = width, solidHeader = T, status = "primary",
collapsible = collapsible, collapsed = collapsed,
sidebarPanel(
width = 3,
selectInput('RT_Stats.DSC.ID', 'Algorithms to compare', choices = NULL,
selected = NULL, multiple = T),
selectInput('RT_Stats.DSC.Funcid', 'Functions to use', choices = NULL,
selected = NULL, multiple = T),
selectInput('RT_Stats.DSC.Dim', 'Dimensions to use', choices = NULL,
selected = NULL, multiple = T),
hr(),
selectInput('RT_Stats.DSC.Value_type', "Select which type of hitting times to use",
choices = c('PAR-10', 'ERT', 'Remove-na', 'PAR-1')),
numericInput('RT_Stats.DSC.Alpha_rank',
label = "Threshold for statistical significance",
value = 0.05, min = 0, max = 0.5),
numericInput('RT_Stats.DSC.Epsilon_rank',
label = "Threshold for practical significance (pDSC)",
value = 0) %>%
shinyInput_label_embed(
custom_icon() %>%
bs_embed_popover(
title = "Practical Significance", content = Pdsc_info,
placement = "auto"
)
),
numericInput('RT_Stats.DSC.MCsamples_rank',
label = "Number of monte carlo samples to use in the DSC procdure",
value = 0) %>%
shinyInput_label_embed(
custom_icon() %>%
bs_embed_popover(
title = "Monte Carlo Samples", content = Pdsc_mc_info,
placement = "auto"
)
),
selectInput("RT_Stats.DSC.Test_rank", "Test Type",
choices = c("Anderson-Darling", "Kolmogorov-Smirnov"),
selected = "Anderson-Darling"),
actionButton('RT_Stats.DSC.Create_rank', 'Create Ranking'),
hr(),
selectInput('RT_Stats.DSC.Format_rank', label = 'Select the figure format',
choices = c("pdf"), selected = 'pdf'),
downloadButton('RT_Stats.DSC.Download_rank', label = 'Download the figure'),
selectInput('RT_Stats.DSC.TableFormat_rank', label = 'Select the table format',
choices = c('csv','tex'), selected = 'csv'),
downloadButton('RT_Stats.DSC.Download_rank_table', label = 'Download the raw ranking data')
),
mainPanel(
width = 9,
HTML_P("The <b>DSC</b> comparison is described in the paper: 'DSCTool: A web-service-based
framework for statistical comparison of stochastic optimization algorithms.' by
T. Eftimov et al.
This is the first of 3 parts of the process: the per-function ranking procedure.
The two other processes are the omnibus test and the post-hoc processing,
which are shown in the two boxes below this one.
Note that both of these are impacted by the settings selected for this
ranking procedure!"),
HTML_P("The chosen <b>budget values</b> per (function, dimension)-pair are as follows
(double click an entry to edit it):"),
DT::dataTableOutput("RT_Stats.DSC.Targets"),
hr(),
HTML_P("The results of the ranking are shown in the following plot, using the visualization techniques
as described in the paper: 'PerformViz: A Machine Learning Approach to Visualize and
Understand the Performance of Single-objective Optimization
Algorithms' By T. Eftimov et al. Performviz allows one to clearly see,
from a single plot, which algorithms are most suited for a given problem,
the influence of each problem on the overall algorithm performance and
similarities among both algorithms and problems."),
plotOutput("RT_Stats.DSC.PerformViz", height = "800px")
)
)
}
rt_dsc_box_omni <- function(width = 12, collapsible = T, collapsed = F) {
box(title = HTML('<p style="font-size:120%;">Deep Statistical Comparison (DSC)
analysis - Omnibus Test</p>'),
width = width, solidHeader = T, status = "primary",
collapsible = collapsible, collapsed = collapsed,
sidebarPanel(
width = 3,
selectInput('RT_Stats.DSC.Omni_options', "Select which statistical test to use",
choices = NULL, selected = NULL),
numericInput('RT_Stats.DSC.Alpha_omni',
label = "Threshold for statistical significance",
value = 0.05, min = 0, max = 0.5),
actionButton('RT_Stats.DSC.Create_omni', 'Perform Omnibus Test')
),
mainPanel(
width = 9,
HTML_P('This is the result of the omnibus test on the data from the ranking procedure above.
Note that this test has to be performed before doing the post-hoc comparison!'),
hr(),
textOutput('RT_Stats.DSC.Output_omni')
)
)
}
rt_dsc_box_posthoc <- function(width = 12, collapsible = T, collapsed = F) {
box(title = HTML('<p style="font-size:120%;">Deep Statistical Comparison (DSC)
analysis - Posthoc comparison</p>'),
width = width, solidHeader = T, status = "primary",
collapsible = collapsible, collapsed = collapsed,
sidebarPanel(
width = 3,
selectInput('RT_Stats.DSC.Posthoc_test', 'Post-hoc Test', choices =
c('friedman', 'friedman-aligned-rank'),
selected = 'friedman', multiple = F),
selectInput('RT_Stats.DSC.Posthoc_method', 'Post-hoc Method', choices =
c('Holm', 'Hochberg', 'unadjusted P'),
selected = 'Holm', multiple = F),
numericInput('RT_Stats.DSC.Alpha_posthoc',
label = "Threshold for statistical significance",
value = 0.05, min = 0, max = 0.5),
actionButton('RT_Stats.DSC.Create_posthoc', 'Create Comparison'),
hr(),
selectInput('RT_Stats.DSC.Format', label = 'Select the figure format',
choices = supported_fig_format, selected = supported_fig_format[[1]]),
downloadButton('RT_Stats.DSC.Download', label = 'Download the figure'),
hr(),
selectInput('RT_Stats.DSC.TableFormat', label = 'Select the table format',
choices = supported_table_format, selected = supported_table_format[[1]]),
downloadButton('RT_Stats.DSC.DownloadTable', label = 'Download the table')
),
mainPanel(
width = 9,
HTML_P("The results of the post-hoc comparison are:"),
plotlyOutput.IOHanalyzer("RT_Stats.DSC.PosthocViz"),
DT::dataTableOutput('RT_Stats.DSC.PosthocTable')
)
)
} |
library(buildmer)
library(testthat)
test_that('buildgls',{
skip_on_cran()
library(nlme)
vowels$event <- with(vowels,interaction(participant,word))
model <- buildgls(f1 ~ timepoint*following,correlation=corAR1(form=~1|event),data=vowels)
buildmer:::testthat.compare.df(model@p$results,'buildgls')
}) |
buildModelClass <- function(x, var.names, init.cond, model.parms, probWeights,
emigrRule, prop.func = NULL, state.var = NULL,
infl.var = NULL, state.change.matrix = NULL) UseMethod("buildModelClass") |
context("test-cell_combos")
user_opts <- faux_options("sep", "verbose", "plot", "connection")
on.exit(faux_options(user_opts))
test_that("0 factors", {
expect_equal(cell_combos(list()), "y")
expect_equal(cell_combos(list(), "DV"), "DV")
})
test_that("1 factor", {
fac <- list(c(A = "A", B = "B", C = "C"))
expect_equal(cell_combos(fac), LETTERS[1:3])
fac <- list(pet = c(cat = "Has a Cat", dog = "Has a Dog"))
expect_equal(cell_combos(fac), c("cat", "dog"))
})
test_that("2 factors", {
factors <- list(pet = c(cat = "a cat", dog = "a dog"),
time = c(day = "the day", night = "the night"))
cells <- cell_combos(factors)
expect_equal(cells, c("cat_day", "cat_night", "dog_day", "dog_night"))
})
test_that("3 factors", {
factors <- list(pet = c(dog = "a dog", cat = "a cat"),
time = c(day = "the day", night = "the night"),
condition = c(A = "AA", B = "BB"))
cells <- cell_combos(factors)
expect_equal(cells, c("dog_day_A", "dog_day_B",
"dog_night_A", "dog_night_B",
"cat_day_A", "cat_day_B",
"cat_night_A", "cat_night_B"))
})
test_that("sep", {
faux_options(sep = ".")
factors <- list(pet = c(dog = "a dog", cat = "a cat"),
time = c(day = "the day", night = "the night"),
condition = c(A = "AA", B = "BB"))
cells <- cell_combos(factors)
expect_equal(cells, c("dog.day.A", "dog.day.B",
"dog.night.A", "dog.night.B",
"cat.day.A", "cat.day.B",
"cat.night.A", "cat.night.B"))
factors <- list(A = c(A.1 = "A.1", A.2 = "A.2"),
B = c(B_1 = "B_1", B_2 = "B_2"))
cells <- cell_combos(factors)
expect_equal(cells, c("A.1.B_1", "A.1.B_2", "A.2.B_1", "A.2.B_2"))
faux_options(sep = "_")
cells <- cell_combos(factors)
expect_equal(cells, c("A.1_B_1", "A.1_B_2", "A.2_B_1", "A.2_B_2"))
}) |
context("simplify_rules")
test_that("simplify rules works", {
rules <- validator( x > 0
, if (x > 0) y == 1
, A %in% c("a1", "a2")
, if (A == "a1") y > 1
)
rules_s <- simplify_rules(rules)
exprs_s <- to_exprs(rules_s)
expect_equal(length(exprs_s), 3)
expect_equal(exprs_s$V1, quote(x > 0))
expect_equal(exprs_s$.const_y, quote(y == 1))
expect_equal(exprs_s$.const_A, quote(A == "a2"))
}) |
gamRR.boot=function(
fit,
ref,
est,
data,
n.points=10,
n.boot=50,
plot=TRUE,
ylim=NULL){
ref=data.frame(t(ref))
form=as.character(fit$formula)
x.list=strsplit(form[3],"\\+")[[1]]
x.list=gsub(" ","",x.list)
x.list=sapply(strsplit(x.list,"\\,"),"[",1)
x.list=gsub("s\\(","",x.list)
x.list=gsub("as.factor\\(","",x.list)
x.list=gsub("factor\\(","",x.list)
x.list=gsub("offset\\(","",x.list)
x.list=gsub("log\\(","",x.list)
x.list=gsub("\\)","",x.list)
if(length(names(ref))!=length(x.list)){
stop("The number of variables in the 'ref' argument is not equal to those in the model!")
}
if(any(!(names(ref) %in% x.list))){
stop("Some variables in the 'ref' argument are not in the model!")
}
rrref=predict(fit,type="response",newdata=ref)
rangE=range(data[,est])
est.seq=seq(from=rangE[1],to=rangE[2],length.out=n.points)
seq.ind=which(abs(est.seq-as.numeric(ref[est]))==min(abs(est.seq-as.numeric(ref[est]))))
est.seq[seq.ind]=as.numeric(ref[est])
ndata=matrix(rep(0,n.points*length(names(ref))),ncol=length(names(ref)))
ndata=data.frame(ndata)
names(ndata)=names(ref)
ndata[,est]=est.seq
ndata[,-match(est,names(ref))]=ref[,-match(est,names(ref))]
dzc.boot=function(data.boot,i){
fit.boot=gam(fit$formula,family=fit$family,method=fit$method,data=data.boot[i,])
c(predict(fit.boot,type="response",newdata=ndata)/as.numeric(rrref))
}
rr.boot=boot(data=data,statistic=dzc.boot,R=n.boot,stype="i")
t=data.frame(t(rr.boot$t))
rr=apply(t,1,FUN="mean")
rr.se=apply(t,1,FUN="sd")
rr.l=rr-1.96*rr.se
rr.u=rr+1.96*rr.se
rr[seq.ind]=1
rr.l[seq.ind]=1
rr.u[seq.ind]=1
if(plot){
if(is.null(ylim)){ylim=c(min(rr.l),max(rr.u))}
plot(spline(est.seq,rr,xmax=as.numeric(ref[,est])),type="l",xlim=c(min(est.seq),max(est.seq)),ylim=ylim,xlab=est,ylab="RR")
lines(spline(est.seq,rr.l,xmax=as.numeric(ref[,est])),lty=2)
lines(spline(est.seq,rr.u,xmax=as.numeric(ref[,est])),lty=2)
lines(spline(est.seq,rr,xmin=as.numeric(ref[,est])),lty=1)
lines(spline(est.seq,rr.l,xmin=as.numeric(ref[,est])),lty=2)
lines(spline(est.seq,rr.u,xmin=as.numeric(ref[,est])),lty=2)
}
xy=data.frame(x=est.seq,rr=rr,u=rr.u,l=rr.l)
return(xy)
} |
retrieve_calanguize_genomes <- function(target.dir,
method = "auto",
unzip = getOption("unzip")){
assertthat::assert_that(is.character(target.dir),
length(url) == 1)
if(!dir.exists(target.dir)){
dir.create(target.dir, recursive = TRUE)
} else {
filelist <- dir(target.dir, full.names = TRUE)
unlink(filelist, recursive = TRUE, force = TRUE)
}
url <- "https://github.com/fcampelo/CALANGO/raw/master/inst/extdata/calanguize_genomes.zip"
res1 <- utils::download.file(url,
quiet = TRUE,
destfile = paste0(target.dir, "/tmpdata.zip"),
cacheOK = FALSE,
method = method)
if(res1 != 0) stop("Error downloading file \n", url)
utils::unzip(paste0(target.dir, "/tmpdata.zip"),
unzip = unzip,
exdir = target.dir)
unlink(paste0(target.dir, "/__MACOSX"), recursive = TRUE, force = TRUE)
file.remove(paste0(target.dir, "/tmpdata.zip"))
invisible(TRUE)
} |
theme_edi <- function(base_size = 14, base_family = "Helvetica") {
half_line <- base_size/2
theme(line = element_line(colour = "black", size = 0.5, linetype = 1,
lineend = "butt"),
rect = element_rect(fill = "white", colour = "black", size = 0.5,
linetype = 1),
text = element_text(family = base_family, face = "plain",
colour = "black",
size = base_size,
lineheight = 0.9,
hjust = 0.5, vjust = 0.5, angle = 0, margin = margin(),
debug = FALSE),
axis.line = element_line(),
axis.line.x = element_blank(),
axis.line.y = element_blank(),
axis.text = element_text(size = rel(1.1),
colour = "grey30"),
axis.text.x = element_text(margin = margin(t = 0.8 * half_line/2),
vjust = 0, face = 'bold'),
axis.text.y = element_text(margin = margin(r = 0.8 * half_line/2),
hjust = 1, vjust = 1, face = 'bold'),
axis.ticks = element_line(colour = "black"),
axis.ticks.length = unit(half_line/2, "pt"),
axis.title.x = element_text(size = rel(1.2),
margin = margin(t = 0.8 * half_line,
b = 0.8 * half_line/2)),
axis.title.y = element_text(size = rel(1.2),
angle = 90,
margin = margin(r = 0.8 * half_line,
l = 0.8 * half_line/2)),
legend.background = element_rect(colour = NA),
legend.spacing = unit(0.4, "cm"),
legend.spacing.x = NULL,
legend.spacing.y = NULL,
legend.margin = margin(0.2, 0.2, 0.2, 0.2, "cm"),
legend.key = element_blank(),
legend.key.size = unit(1.2, "lines"),
legend.key.height = NULL,
legend.key.width = NULL,
legend.text = element_text(size = rel(0.8)),
legend.text.align = NULL,
legend.title = element_text(hjust = 0),
legend.title.align = NULL,
legend.position = "right",
legend.direction = NULL,
legend.justification = "center",
legend.box = NULL,
panel.background = element_rect(fill = "white", colour = NA),
panel.border = element_rect(fill = NA, colour = "grey50"),
panel.grid.major = element_line(colour = "grey90"),
panel.grid.minor = element_blank(),
panel.spacing = unit(half_line, "pt"),
panel.spacing.x = NULL,
panel.spacing.y = NULL,
panel.ontop = FALSE,
strip.background = element_blank(),
strip.text = element_text(colour = "grey10", size = rel(1.2), face = 'bold'),
strip.text.x = element_text(margin = margin(t = half_line,
b = half_line)),
strip.text.y = element_text(angle = -90, margin = margin(l = half_line,
r = half_line)),
strip.switch.pad.grid = unit(0.1, "cm"),
strip.switch.pad.wrap = unit(0.1, "cm"),
plot.background = element_rect(colour = "white"),
plot.title = element_text(size = rel(1.2), hjust = 0, vjust = 1,
margin = margin(b = half_line * 1.2)),
plot.subtitle = element_text(size = rel(0.9), hjust = 0, vjust = 1,
margin = margin(b = half_line * 0.9)),
plot.caption = element_text(size = rel(0.9), hjust = 1,
vjust = 1, margin = margin(t = half_line * 0.9)),
plot.margin = margin(half_line, half_line, half_line, half_line),
complete = TRUE
)
} |
`gq.summary` <- function(gq.output,burnin=0,quantiles=c(0.01,0.025,0.25,0.50,0.75,0.975,0.99))
{
if (!is.null(gq.output$draws)){
ndraws <- nrow(gq.output$draws$mu)
gq.output <- list(gq.output)
} else {
if (is.null(gq.output[[1]]$draws)){
stop("gq.output must be either a list of or a single return object from 'Analyze'")
}
ndraws <- nrow(gq.output[[1]]$draws$mu)
}
if ((burnin<0)||(burnin>=ndraws)){
stop("Invalid burn-in period")
}
gq.draws <- mcmc.list(mcmc(1))
for (i in 1:length(gq.output)){
tmp.chain <- cbind(gq.output[[i]]$draws$mu[(burnin+1):ndraws,],
gq.output[[i]]$draws$Sigma[(burnin+1):ndraws,],
gq.output[[i]]$draws$NNs[(burnin+1):ndraws,],
gq.output[[i]]$draws$LAMBDA[(burnin+1):ndraws,],
gq.output[[i]]$draws$TURNOUT[(burnin+1):ndraws,],
gq.output[[i]]$draws$GAMMA[(burnin+1):ndraws,])
gq.draws[[i]] <- mcmc(tmp.chain)
}
return(summary(gq.draws,quantiles=quantiles))
} |
summary.nparcomp <-
function(object,...)
{
cat("\n", "
"-", "Alternative Hypothesis: ", object$text.Output,"\n",
"-", "Estimation Method: Global Pseudo ranks","\n",
"-", "Type of Contrast", ":", object$input$type, "\n", "-", "Confidence Level:",
object$input$conf.level*100,"%", "\n", "-", "Method", "=", object$AsyMethod, "\n","\n",
"-", "Estimation Method: Pairwise rankings","\n", "\n",
"
"\n", "p(a,b)", ">", "1/2", ":", "b tends to be larger than a","\n",
"
"\n")
cat( "
print(object$Data.Info)
cat("\n", "
print(object$Contrast)
cat("\n", "
print(object$Analysis)
cat("\n", "
print(object$Overall)
if (object$input$weight.matrix == TRUE){
cat("\n", "
print(object$Weight.Matrix)
cat("\n", "
print(object$AllPairs)
}
if (object$input$correlation == TRUE){
cat("\n", "
print(object$Covariance)
cat("\n", "
print(object$Correlation)
}
cat("\n", "
} |
f.influence <- function(io, i, j){
if(!"InputOutput" %in% class(io)) stop('io should be of "InputOutput" class. See ?as.inputoutput')
if(length(i) != length(j)) stop("i must be the same length as j")
n <- dim(io$L)[1]
if(length(i) >= n) stop("Field of Influence is only defined up to n-1 terms, where n =
if(length(i) > 1){
k <- length(i)
A <- matrix(0, nrow = n, ncol = n)
for(s in 1:k){
for(r in 1:k){
L = io$L
Lij <- L[i[s], j[r]]
A <- 1/(k-1)*( (-1)^(s+r+1) * Lij * f.influence(io, i[-s], j[-r])) + A
}
}
return(A)
}
else if(length(i) == 1){
L.j <- io$L[, j]
Li. <- io$L[i, ]
matrix(L.j, ncol = 1) %*% matrix(Li., nrow = 1)
}
} |
m.infos.nest.lmerMod <- function(x,
my,
forminter,
which,
fl1,
fl2,
sig.level,
aux_mt,
...)
{
aux_m.inf <- aggregate(forminter,
data = x@frame,
function(x) c(min = min(x),
max = max(x),
sd = sd(x),
se = sd(x)/length(x)))
aux_m.inf1 <- data.frame(aux_m.inf[names(aux_m.inf) != my],
means = aux_mt$coef[,1],
aux_m.inf[[my]][,1:2],
'linf_sd' = aux_mt$coef[,1] - aux_m.inf[[my]][,3],
'lsup_sd' = aux_mt$coef[,1] + aux_m.inf[[my]][,3],
'linf_se' = aux_mt$coef[,1] - abs(qt(sig.level,aux_mt$coef[,3]))*aux_m.inf[[my]][,4],
'lsup_se' = aux_mt$coef[,1] + abs(qt(sig.level,aux_mt$coef[,3]))*aux_m.inf[[my]][,4],
'linf_sepool' = aux_mt$coef[,1] - abs(qt(sig.level,aux_mt$coef[,3]))*aux_mt$coef[,2],
'lsup_sepool' = aux_mt$coef[,1] + abs(qt(sig.level,aux_mt$coef[,3]))*aux_mt$coef[,2])
aux_m.inf2 <- aux_m.inf1[order(aux_m.inf1[['means']],
decreasing = TRUE),]
nf1 <- unlist(strsplit(which,
split = ':'))[1]
nf2 <- unlist(strsplit(which,
split = ':'))[2]
nf3 <- unlist(strsplit(which,
split = ':'))[3]
if(is.null(fl2)){
f2 <- levels(x@frame[[nf1]])[fl1]
aux_m.inf21 <- subset(aux_m.inf2,
eval(parse(text = nf1)) == f2)
m.inf <- list(Means = aux_m.inf21[,c(1:3)],
mm = aux_m.inf21[,c(1:2,4:5)],
sd = aux_m.inf21[,c(1:2,6:7)],
ic = aux_m.inf21[,c(1:2,8:9)],
icpool = aux_m.inf21[,c(1:2,10:11)])
} else {
f2 <- levels(x@frame[[nf2]])[fl2]
f3 <- levels(x@frame[[nf1]])[fl1]
aux_m.inf21 <- subset(aux_m.inf2,
eval(parse(text = nf1)) == f3 & eval(parse(text = nf2)) == f2)
m.inf <- list(Means = aux_m.inf21[,c(1:4)],
mm = aux_m.inf21[,c(1:3,5:6)],
sd = aux_m.inf21[,c(1:3,7:8)],
ic = aux_m.inf21[,c(1:3,9:10)],
icpool = aux_m.inf21[,c(1:3,11:12)])
}
} |
dby <- function(data,INPUT,...,ID=NULL,ORDER=NULL,SUBSET=NULL,SORT=0,COMBINE=!REDUCE,NOCHECK=FALSE,ARGS=NULL,NAMES,COLUMN=FALSE,REDUCE=FALSE,REGEX=mets.options()$regex,ALL=TRUE) {
if (missing(INPUT)) INPUT <- .~1
val <- substitute(INPUT)
INPUT <- try(eval(val),silent=TRUE)
funs <- substitute(list(...))[-1]
if (inherits(INPUT,"try-error")) {
INPUT <- as.formula(paste0(".~1|",deparse(val)))
}
if (inherits(INPUT,c("formula","character"))) {
INPUT <- procformdata(INPUT,sep="\\|",data=data,na.action=na.pass,do.filter=FALSE,regex=REGEX,specials="order")
if (is.null(ID)) ID <- INPUT$predictor
if (is.null(SUBSET)) {
if (length(INPUT$group)!=0)
SUBSET <- INPUT$group[[1]]
}
if (is.null(ORDER)) {
if (length(INPUT$specials$order)!=0)
ORDER <- INPUT$specials$order[[1]]
}
INPUT <- INPUT$response
}
if (inherits(ID,"formula")) ID <- model.frame(ID,data=data,na.action=na.pass)
if (inherits(ORDER,"formula")) ORDER <- model.frame(ORDER,data=data,na.action=na.pass)
if (inherits(SUBSET,"formula")) SUBSET <- model.frame(SUBSET,data=data,na.action=na.pass)
if (is.null(INPUT)) {
INPUT <- ID
ID <- NULL
}
noID <- FALSE
if (length(ID)==0) {
noID <- TRUE
ID = rep(1,NROW(INPUT))
}
group <- NULL
if (!COMBINE || length(funs)==0) group <- ID
if (NCOL(ID)>1) ID <- interaction(ID)
if (is.data.frame(ID)) {
ID <- as.numeric(ID[,1,drop=TRUE])
} else {
ID <- as.numeric(ID)
}
if (is.data.frame(ORDER)) {
ORDER <- ORDER[,1,drop=TRUE]
}
if (!NOCHECK) {
if (length(ORDER)>0) {
ord <- order(ID,ORDER,decreasing=SORT,method="radix")
} else {
ord <- order(ID,decreasing=SORT,method="radix")
}
numerics <- unlist(lapply(INPUT[1,],is.numeric))
INPUT <- as.matrix(INPUT[ord,which(numerics),drop=FALSE])
ID <- ID[ord]
if (is.null(group)) data <- data[ord,,drop=FALSE]
else {
if (is.vector(group)) group <- group[ord]
else group <- group[ord,,drop=FALSE]
}
na.idx <- which(is.na(ID))
} else {
INPUT <- as.matrix(INPUT)
}
if (length(SUBSET)>0) {
SUBSET <- which(as.matrix(SUBSET))
INPUT <- INPUT[SUBSET,,drop=FALSE]
ID <- ID[SUBSET]
}
if (length(funs)==0) {
if (noID) return(INPUT)
return(cbind(INPUT,group))
}
if (NROW(INPUT)>0) {
resl <- lapply(funs, function(fun_) {
env <- new.env()
isfun <- tryCatch(is.function(eval(fun_)),error=function(...) FALSE)
if (isfun) {
env$fun_ <- eval(fun_)
if (length(ARGS)>0) {
fun_ <- eval(fun_)
ff <- function(...) do.call(fun_,c(list(...),ARGS))
expr <- quote(ff(x))
} else {
expr <- quote(fun_(x))
}
} else {
expr <- fun_
}
.ApplyBy2(INPUT,ID,F=expr,Env=env,Argument="x",Columnwise=COLUMN)
})
res <- Reduce(cbind,resl)
} else {
resl <- NULL
res <- NULL
}
dn <- NULL
if (missing(NAMES)) {
a <- match.call(expand.dots=FALSE)
ff <- lapply(a[["..."]],deparse)
fn <- lapply(ff,deparse)
dn <- names(ff)
if (is.null(dn)) dn <- rep("",length(ff))
idx <- which(dn=="")
if (length(idx)>0) {
newn <- unlist(ff[idx])
dn[idx] <- newn[seq_along(idx)]
fcall <- grepl("^function",dn)
if (any(fcall))
dn[which(fcall)] <- which(fcall)
}
numcolf <- unlist(lapply(resl, NCOL))
nn <- c()
if (COLUMN) {
colnames(INPUT)
dn <- unlist(lapply(dn, function(x) paste(x,colnames(INPUT),sep=".")))
}
for (i in seq_along(resl)) {
nc <- numcolf[i]
curnam <- dn[i]
if (COLUMN) {
nc <- nc/NCOL(INPUT)
pos <- NCOL(INPUT)*(i-1)+1
pos <- seq(pos,pos+NCOL(INPUT)-1)
curnam <- dn[pos]
}
if (nc>1) {
nn <- c(nn, unlist(lapply(curnam, function(x) paste0(x,seq(nc)))))
}
else nn <- c(nn,curnam)
}
NAMES <- nn
}
try(colnames(res) <- NAMES,silent=TRUE)
numidx <- grep("^[0-9]",colnames(res))
if (length(numidx)>0)
colnames(res)[numidx] <- paste0("_",colnames(res)[numidx])
if (!NOCHECK && length(na.idx)>0) {
res[na.idx,] <- NA
}
cl <- attr(resl[[1L]],"clustersize")
if (COMBINE) {
if (is.null(NAMES) & is.null(res) & length(dn)>0) {
res <- matrix(NA,nrow(data),length(dn))
colnames(res) <- dn
}
nn <- colnames(res)
nc <- ifelse(is.null(res), 0, ncol(res))
res0 <- matrix(NA,nrow(data),nc)
colnames(res0) <- nn
didx <- which(colnames(data)%in%nn)
if (length(didx)>0) {
ridx <- match(colnames(data)[didx],nn)
res0[,ridx] <- as.matrix(data[,didx])
data <- data[,-didx,drop=FALSE]
}
if (length(SUBSET)>0) {
res0[SUBSET,] <- res
res <- cbind(data,res0)
} else {
if (!is.null(res))
res <- cbind(data,res)
else
res <- data
}
} else {
if (!noID) {
if (length(SUBSET)>0) group <- group[SUBSET,,drop=FALSE]
res <- cbind(group,res)
}
}
if (REDUCE!=0) {
if (REDUCE<0) {
idx <- cumsum(cl)
} else {
idx <- cumsum(c(1,cl[-length(cl)]))
}
res <- res[unique(idx),,drop=FALSE]
if (NROW(res)==1) {
rownames(res) <- ""
} else {
rownames(res) <- NULL
}
}
if (!ALL) {
return(res[SUBSET,,drop=FALSE])
}
return(res)
}
"dby<-" <- function(data,INPUT,...,value) {
cl <- match.call()
cl[[1L]] <- substitute(dby)
a <- substitute(value)
if (inherits(value,"formula")) {
cl["value"] <- NULL
names(cl)[names(cl)=="INPUT"] <- ""
cl[["INPUT"]] <- value
} else {
if (is.list(value)) {
cl[which(names(cl)=="value")] <- NULL
start <- length(cl)
for (i in seq_along(value)) {
cl[start+i] <- value[i]
}
if (length(names(value))>0)
names(cl)[start+seq_along(value)] <- names(value)
} else {
names(cl)[which(names(cl)=="value")] <- ""
}
}
eval.parent(cl)
}
dby2 <- function(data,INPUT,...) {
cl <- match.call()
cl[[1L]] <- substitute(dby)
cl[["COLUMN"]] <- TRUE
eval.parent(cl)
}
"dby2<-" <- function(data,INPUT,...,value) {
cl <- match.call()
cl[[1L]] <- substitute(`dby<-`)
cl[["COLUMN"]] <- TRUE
eval.parent(cl)
}
dbyr <- function(data,INPUT,...,COLUMN=FALSE) {
cl <- match.call()
cl[[1L]] <- substitute(`dby`)
cl[["REDUCE"]] <- TRUE
cl[["COLUMN"]] <- COLUMN
eval.parent(cl)
} |
sa_2d_plot <- function(sa_obj, history, large_sa, path = tempdir()) {
params <-
sa_obj %>%
collect_metrics() %>%
select(.iter, cost, rbf_sigma) %>%
arrange(.iter)
init <-
params %>%
filter(.iter == 0)
svm_roc <-
large_sa %>%
collect_metrics()
large_plot <-
svm_roc %>%
ggplot(aes(x = rbf_sigma, y = cost)) +
geom_raster(aes(fill = mean), show.legend = FALSE) +
scale_x_log10() +
scale_y_continuous(trans = "log2") +
scale_fill_distiller(palette = "Blues") +
theme_minimal() +
theme(
legend.position = "bottom",
legend.key.width = grid::unit(2, "cm"),
plot.title = element_text(hjust = 0.5)
) +
guides(title.position = "bottom") +
labs(x = "rbf_sigma\n\n\n\n", title = "ROC AUC surface") +
coord_fixed(ratio = 1/2.5)
base_plot <-
large_plot +
geom_point(data = init, pch = 4, cex = 4)
num_init <- nrow(init)
num_iter <- max(history$.iter)
nms <- purrr::map_chr(1:nrow(history), ~ tempfile())
for (i in (num_init + 1):nrow(history)) {
current_iter <- history$.iter[i]
current_res <- current_param_path(history, current_iter)
current_best <- current_res %>% dplyr::filter(results == "new best")
ttl <- paste0("Iteration ", current_iter)
text_just <-
case_when(
history$results[i] == "restart from best" ~0.00,
history$results[i] == "discard suboptimal" ~ 0.25,
history$results[i] == "accept suboptimal" ~ 0.50,
history$results[i] == "better suboptimal" ~ 0.75,
history$results[i] == "new best" ~ 1.00
)
tmp <- history
tmp$results <- gsub(" suboptimal", "\nsuboptimal", tmp$results)
tmp$results <- gsub(" best", "\nbest", tmp$results)
new_plot <-
base_plot +
geom_point(
data = current_res %>% slice(n()),
size = 3,
col = "green"
) +
geom_path(
data = current_res,
alpha = .5,
arrow = arrow(length = unit(0.1, "inches"))
) +
ggtitle(ttl, subtitle = tmp$results[i]) +
theme(plot.subtitle = element_text(hjust = text_just))
if (nrow(current_best) > 0) {
new_plot <-
new_plot +
geom_point(data = current_best, size = 1/3)
}
print(new_plot)
}
invisible(NULL)
}
current_param_path <- function(x, iter) {
x <-
x %>%
dplyr::filter(.iter <= iter)
ind <- nrow(x)
param_path <- ind
while(length(ind) > 0) {
ind <- which(x$.config == x$.parent[ind])
param_path <- c(param_path, ind)
}
x %>% dplyr::slice(rev(param_path))
} |
znegbin <- setRefClass("Zelig-negbin",
contains = "Zelig",
field = list(simalpha = "list"
))
znegbin$methods(
initialize = function() {
callSuper()
.self$fn <- quote(MASS::glm.nb)
.self$name <- "negbin"
.self$authors <- "Kosuke Imai, Gary King, Olivia Lau"
.self$packageauthors <- "William N. Venables, and Brian D. Ripley"
.self$year <- 2008
.self$category <- "count"
.self$description <- "Negative Binomial Regression for Event Count Dependent Variables"
.self$outcome <- "discrete"
.self$wrapper <- "negbin"
.self$acceptweights <- TRUE
}
)
znegbin$methods(
zelig = function(formula, data, ..., weights=NULL, by = NULL, bootstrap = FALSE) {
.self$zelig.call <- match.call(expand.dots = TRUE)
.self$model.call <- .self$zelig.call
callSuper(formula=formula, data=data, ..., weights=weights, by = by, bootstrap = bootstrap)
rse <- lapply(.self$zelig.out$z.out, (function(x) vcovHC(x, type = "HC0")))
.self$test.statistics<- list(robust.se = rse)
}
)
znegbin$methods(
param = function(z.out, method="mvn") {
simalpha.local <- z.out$theta
if(identical(method,"mvn")){
simparam.local <- mvrnorm(n = .self$num, mu = coef(z.out),
Sigma = vcov(z.out))
simparam.local <- list(simparam = simparam.local, simalpha = simalpha.local)
return(simparam.local)
} else if(identical(method,"point")){
return(list(simparam = t(as.matrix(coef(z.out))), simalpha = simalpha.local))
}
}
)
znegbin$methods(
qi = function(simparam, mm) {
coeff <- simparam$simparam
alpha <- simparam$simalpha
inverse <- family(.self$zelig.out$z.out[[1]])$linkinv
eta <- coeff %*% t(mm)
theta <- matrix(inverse(eta), nrow=nrow(coeff))
ev <- theta
pv <- matrix(NA, nrow=nrow(theta), ncol=ncol(theta))
for (i in 1:ncol(ev))
pv[, i] <- rnegbin(nrow(ev), mu = ev[i, ], theta = alpha[i])
return(list(ev = ev, pv = pv))
}
)
znegbin$methods(
mcfun = function(x, b0=0, b1=1, ..., sim=TRUE){
mu <- exp(b0 + b1 * x)
if(sim){
y <- rnbinom(n=length(x), 1, mu=mu)
return(y)
}else{
return(mu)
}
}
) |
create.barplot <- function(
formula, data, groups = NULL, stack = FALSE, filename = NULL, main = NULL, main.just = 'center',
main.x = 0.5, main.y = 0.5, main.cex = 3, xlab.label = tail(sub('~', '', formula[-2]), 1),
ylab.label = tail(sub('~', '', formula[-3]), 1), xlab.cex = 2, ylab.cex = 2, xlab.col = 'black',
ylab.col = 'black', xlab.top.label = NULL, xlab.top.cex = 2, xlab.top.col = 'black',
xlab.top.just = 'center', xlab.top.x = 0.5, xlab.top.y = 0, abline.h = NULL, abline.v = NULL,
abline.lty = 1, abline.lwd = NULL, abline.col = 'black', axes.lwd = 1, add.grid = FALSE, xgrid.at = xat,
ygrid.at = yat, grid.lwd = 5, grid.col = NULL, xaxis.lab = TRUE, yaxis.lab = TRUE, xaxis.col = 'black',
yaxis.col = 'black', xaxis.fontface = 'bold', yaxis.fontface = 'bold', xaxis.cex = 1.5, yaxis.cex = 1.5,
xaxis.rot = 0, yaxis.rot = 0, xaxis.tck = 1, yaxis.tck = 1, xlimits = NULL, ylimits = NULL, xat = TRUE,
yat = TRUE, layout = NULL, as.table = FALSE, x.spacing = 0, y.spacing = 0, x.relation = 'same',
y.relation = 'same', top.padding = 0.5, bottom.padding = 1, right.padding = 1, left.padding = 1,
key.bottom = 0.1, ylab.axis.padding = 0.5, xlab.axis.padding = 0.5, col = 'black', border.col = 'black',
border.lwd = 1, plot.horizontal = FALSE, background.col = 'transparent', origin = 0, reference = TRUE,
box.ratio = 2, sample.order = 'none', group.labels = FALSE, key = list(text = list(lab = c(''))),
legend = NULL, add.text = FALSE, text.labels = NULL, text.x = NULL, text.y = NULL, text.col = 'black',
text.cex = 1, text.fontface = 'bold', strip.col = 'white', strip.cex = 1, y.error.up = NULL,
y.error.down = y.error.up, y.error.bar.col = 'black', error.whisker.width = width / (nrow(data) * 4),
error.bar.lwd = 1, error.whisker.angle = 90, add.rectangle = FALSE, xleft.rectangle = NULL, ybottom.rectangle = NULL,
xright.rectangle = NULL, ytop.rectangle = NULL, col.rectangle = 'grey85', alpha.rectangle = 1,
line.func = NULL, line.from = 0, line.to = 0, line.col = 'transparent', line.infront = TRUE,
text.above.bars = list(labels = NULL, padding = NULL, bar.locations = NULL, rotation = 0),
raster = NULL, raster.vert = TRUE, raster.just = 'center', raster.width.dim = unit(2 / 37, 'npc'),
height = 6, width = 6, size.units = 'in', resolution = 1600, enable.warnings = FALSE,
description = 'Created with BoutrosLab.plotting.general', style = 'BoutrosLab', preload.default = 'custom',
use.legacy.settings = FALSE, inside.legend.auto = FALSE, disable.factor.sorting = FALSE
) {
tryCatch({
dir.name <- '/.mounts/labs/boutroslab/private/BPGRecords/Objects';
if (!dir.exists(dir.name)) {
dir.create(dir.name);
}
funcname <- 'create.barplot';
print.to.file(dir.name, funcname, data, filename);
},
warning = function(w) {
},
error = function(e) {
});
rectangle.info <- list(
xright = xright.rectangle,
xleft = xleft.rectangle,
ytop = ytop.rectangle,
ybottom = ybottom.rectangle
);
text.info <- list(
labels = text.labels,
x = text.x,
y = text.y,
col = text.col,
cex = text.cex,
fontface = text.fontface
);
if (!is.null(yat) && length(yat) == 1) {
if (yat == 'auto') {
if (stack == TRUE) {
s <- split(data, data[toString(formula[[3]])]);
final.list <- list();
for (x in 1:length(s)) {
final.list[[x]] <- sum(s[[x]][toString(formula[[2]])]);
}
out <- auto.axis(final.list, log.scaled = FALSE);
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else {
out <- auto.axis(unlist(data[toString(formula[[2]])]));
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
else if (yat == 'auto.linear') {
if (stack == TRUE) {
s <- split(data, data[toString(formula[[3]])]);
final.list <- list();
for (x in 1:length(s)) {
final.list[[x]] <- sum(s[[x]][toString(formula[[2]])]);
}
out <- auto.axis(final.list, log.scaled = FALSE);
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
else {
out <- auto.axis(unlist(data[toString(formula[[2]])]), log.scaled = FALSE);
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
else if (yat == 'auto.log') {
out <- auto.axis(unlist(data[toString(formula[[2]])]), log.scaled = TRUE);
data[toString(formula[[2]])] <- out$x;
yat <- out$at;
yaxis.lab <- out$axis.lab;
}
}
if (!is.null(xat) && length(xat) == 1) {
if (xat == 'auto') {
if (stack == TRUE) {
s <- split(data, data[toString(formula[[3]])]);
final.list <- list();
for (x in 1:length(s)) {
final.list[[x]] <- sum(s[[x]][toString(formula[[2]])]);
}
out <- auto.axis(final.list, log.scaled = FALSE);
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else {
out <- auto.axis(unlist(data[toString(formula[[3]])]));
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
else if (xat == 'auto.linear') {
if (stack == TRUE) {
s <- split(data, data[toString(formula[[3]])]);
final.list <- list();
for (x in 1:length(s)) {
final.list[[x]] <- sum(s[[x]][toString(formula[[2]])]);
}
out <- auto.axis(final.list, log.scaled = FALSE);
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
else {
out <- auto.axis(unlist(data[toString(formula[[3]])]), log.scaled = FALSE);
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
else if (xat == 'auto.log') {
out <- auto.axis(unlist(data[toString(formula[[3]])]), log.scaled = TRUE);
data[toString(formula[[3]])] <- out$x;
xat <- out$at;
xaxis.lab <- out$axis.lab;
}
}
tryCatch(
expr = {
if (is.null(formula)) { stop(); }
as.formula(formula);
},
error = function(message) {
stop('Invalid formula.');
}
);
if (preload.default == 'paper') {
}
else if (preload.default == 'web') {
}
groups.new <- eval(substitute(groups), data, parent.frame());
if (!is.null(groups.new) && 1 == length(col) && col == 'grey') {
col <- grey(1:nlevels(as.factor(groups.new)) / nlevels(as.factor(groups.new)));
}
if ('|' %in% all.names(formula)) {
variable <- sub('^\\s+', '', unlist(strsplit(toString(formula[length(formula)]), '\\|'))[2]);
if (variable %in% names(data)) {
cond.class <- class(data[, variable]);
if (cond.class %in% c('integer', 'numeric')) {
warning(
'Numeric values detected for conditional variable. If text labels are desired, please convert conditional variable to character.'
);
}
rm(cond.class);
}
}
trellis.object <- lattice::barchart(
formula,
data,
panel = function(x, y, subscripts, groups = groups.new, ...) {
if (add.rectangle) {
panel.rect(
xleft = rectangle.info$xleft,
ybottom = rectangle.info$ybottom,
xright = rectangle.info$xright,
ytop = rectangle.info$ytop,
col = col.rectangle,
alpha = alpha.rectangle,
border = NA
);
}
if (!is.null(text.above.bars$labels)) {
if (!is.null(groups.new)) {
stop("Argument 'text.above.bars' does not work with grouped plots.");
}
if (plot.horizontal) {
panel.text(
x[text.above.bars$bar.locations] + text.above.bars$padding,
text.above.bars$bar.locations,
text.above.bars$labels,
srt = text.above.bars$rotation
);
}
else {
panel.text(
text.above.bars$bar.locations,
y[text.above.bars$bar.locations] + text.above.bars$padding,
text.above.bars$labels,
srt = text.above.bars$rotation
);
}
}
if (add.grid) {
panel.abline(
v = BoutrosLab.plotting.general::generate.at.final(
at.input = xgrid.at,
limits = xlimits,
data.vector = data$x
),
h = BoutrosLab.plotting.general::generate.at.final(
at.input = ygrid.at,
limits = ylimits,
data.vector = data$y
),
col = if (is.null(grid.col)) { trellis.par.get('reference.line')$col } else { grid.col },
lwd = grid.lwd,
);
}
panel.barchart(x, y, subscripts = subscripts, groups = groups.new, border = border.col, lwd = border.lwd, ..., origin = origin);
if (length(line.func) > 0 && !line.infront) {
panel.curve(expr = line.func, from = line.from, to = line.to, col = line.col);
}
panel.abline(h = abline.h, lty = abline.lty, lwd = abline.lwd, col = abline.col);
panel.abline(v = abline.v, lty = abline.lty, lwd = abline.lwd, col = abline.col);
if (length(line.func) > 0 && line.infront) {
panel.curve(expr = line.func, from = line.from, to = line.to, col = line.col);
}
if (add.text) {
panel.text(
x = text.info$x,
y = text.info$y,
labels = text.info$labels,
col = text.info$col,
cex = text.info$cex,
fontface = text.info$fontface
);
}
if (!is.null(y.error.up)) {
if (!is.null(groups)) {
num.groups <- length(subscripts) / length(unique(groups));
group.num <- (subscripts - 1) %/% num.groups;
if (length(unique(group.num)) %% 2 == 1) {
group.num <- group.num - trunc(length(unique(group.num)) / 2);
}
else {
number.of.groups <- trunc(length(unique(group.num)) / 2);
subtr <- 1 + 2 * (number.of.groups - 1);
group.num <- group.num * 2 - subtr;
}
offset <- (6 / (nrow(data) * 4)) * (group.num) * (1.75 - (0.85 * (length(unique(groups)) + 1) %% 2));
}
else {
offset <- 0;
}
if (!plot.horizontal) {
panel.arrows(
x0 = as.numeric(x) + offset,
y0 = y + y.error.up,
x1 = as.numeric(x) + offset,
y1 = y - y.error.down,
length = error.whisker.width,
angle = error.whisker.angle,
ends = 'both',
col = y.error.bar.col,
lwd = error.bar.lwd
);
}
else {
panel.arrows(
y0 = as.numeric(y) + offset,
x0 = x + y.error.up,
y1 = as.numeric(y) + offset,
x1 = x - y.error.down,
length = error.whisker.width,
angle = error.whisker.angle,
ends = 'both',
col = y.error.bar.col,
lwd = error.bar.lwd
);
}
}
if (!is.null(raster)) {
if (raster.vert) {
grid.raster(
raster,
x = x,
y = 0,
height = y,
just = raster.just,
default.units = 'native',
width = raster.width.dim
);
}
else {
grid.raster(
raster,
x = 0,
width = x,
y = y,
just = raster.just,
default.units = 'native',
height = raster.width.dim
);
}
}
},
horizontal = plot.horizontal,
main = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = main,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = main.cex,
just = main.just,
x = main.x,
y = main.y
)
),
xlab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.label,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = xlab.cex,
col = xlab.col
)
),
xlab.top = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = xlab.top.label,
cex = xlab.top.cex,
col = xlab.top.col,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
just = xlab.top.just,
x = xlab.top.x,
y = xlab.top.y
)
),
ylab = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
label = ylab.label,
fontface = if ('Nature' == style) { 'plain' } else { 'bold' },
cex = ylab.cex,
col = ylab.col
)
),
scales = list(
x = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = xaxis.lab,
cex = xaxis.cex,
rot = xaxis.rot,
col = xaxis.col,
limits = xlimits,
at = xat,
tck = xaxis.tck,
relation = x.relation,
fontface = if ('Nature' == style) { 'plain' } else { xaxis.fontface },
alternating = FALSE
)
),
y = BoutrosLab.plotting.general::get.defaults(
property = 'fontfamily',
use.legacy.settings = use.legacy.settings || ('Nature' == style),
add.to.list = list(
labels = yaxis.lab,
cex = yaxis.cex,
rot = yaxis.rot,
col = yaxis.col,
limits = ylimits,
at = yat,
tck = yaxis.tck,
relation = y.relation,
fontface = if ('Nature' == style) { 'plain' } else { yaxis.fontface },
alternating = FALSE
)
)
),
between = list(
x = x.spacing,
y = y.spacing
),
par.settings = list(
axis.line = list(
lwd = axes.lwd,
col = if ('Nature' == style) { 'transparent' } else { 'black' }
),
layout.heights = list(
top.padding = top.padding,
main = if (is.null(main)) { 0.3 } else { 1 },
main.key.padding = 0.1,
key.top = 0.1,
key.axis.padding = 0.1,
axis.top = 0.7,
axis.bottom = 1.0,
axis.xlab.padding = xlab.axis.padding,
xlab = 1,
xlab.key.padding = 0.1,
key.bottom = key.bottom,
key.sub.padding = 0.1,
sub = 0.1,
bottom.padding = bottom.padding
),
layout.widths = list(
left.padding = left.padding,
key.left = 0,
key.ylab.padding = 0.5,
ylab = 1,
ylab.axis.padding = ylab.axis.padding,
axis.left = 1,
axis.panel = 0.3,
strip.left = 0.3,
panel = 1,
between = 1,
axis.right = 1,
axis.key.padding = 1,
key.right = 1,
right.padding = right.padding
),
strip.background = list(
col = strip.col
),
panel.background = list(
col = background.col
)
),
par.strip.text = list(
cex = strip.cex
),
col = col,
layout = layout,
as.table = as.table,
key = key,
legend = legend,
pretty = TRUE,
stack = stack,
reference = reference,
box.ratio = box.ratio
);
if (disable.factor.sorting == TRUE) {
sorting.param <- '';
if (plot.horizontal) {
sorting.param <- 'y';
if (is.null(trellis.object$y.scales$labels) || (is.logical(trellis.object$y.scales$labels[1]) && trellis.object$y.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args[[1]][[sorting.param]]));
trellis.object$y.scales$labels <- default.labels;
}
}
else {
sorting.param <- 'x';
if (is.null(trellis.object$x.scales$labels) || (is.logical(trellis.object$x.scales$labels[1]) && trellis.object$x.scales$labels[1] == TRUE)) {
default.labels <- unique(as.character(trellis.object$panel.args[[1]][[sorting.param]]));
trellis.object$x.scales$labels <- default.labels;
}
}
unique.mapping <- list();
count <- 1;
for (x in trellis.object$panel.args[[1]][[sorting.param]]) {
if (is.null(unique.mapping[[as.character(x)]])) {
unique.mapping[as.character(x)] <- count;
count <- count + 1;
}
}
temp.data <- as.character(trellis.object$panel.args[[1]][[sorting.param]]);
for (x in 1:length(temp.data)) {
temp.data[x] <- as.character(unique.mapping[as.character(trellis.object$panel.args[[1]][[sorting.param]][[x]])][[1]]);
}
trellis.object$panel.args[[1]][[sorting.param]] <- as.numeric(temp.data);
}
if (inside.legend.auto) {
extra.parameters <- list('data' = data, 'plot.horizontal' = plot.horizontal, 'formula' = formula, 'groups' = groups,
'stack' = stack, 'ylimits' = trellis.object$y.limits, 'xlimits' = trellis.object$x.limits);
coords <- c();
coords <- .inside.auto.legend('create.barplot', filename, trellis.object, height, width, extra.parameters);
trellis.object$legend$inside$x <- coords[1];
trellis.object$legend$inside$y <- coords[2];
}
if (group.labels) {
num.groups <- length(trellis.object$panel.args[[1]]$x) / length(unique(trellis.object$panel.args[[1]]$x));
intialaddition <- (1 / 3) / num.groups;
additions <- intialaddition * 2;
newxat <- NULL;
if (is.logical(trellis.object$x.scales$at)) {
trellis.object$x.scales$at <- c(1:length(unique(trellis.object$panel.args[[1]]$x)));
}
for (i in trellis.object$x.scales$at) {
for (j in c(1:num.groups)) {
newxat <- c(newxat, i - 1 / 3 + intialaddition + additions * (j - 1));
}
}
trellis.object$x.scales$at <- newxat;
}
if (is.null(sample.order) || is.na(sample.order)) { sample.order <- 'none'; }
if (sample.order[1] != 'none') {
for (i in 1:length(trellis.object$panel.args)) {
if (!plot.horizontal) {
num.bars <- length(unique(trellis.object$panel.args[[1]]$x));
if (length(unique(sample.order)) == num.bars) {
if (length(xaxis.lab) == 1 && xaxis.lab) {
ordering <- rev(match(sample.order, trellis.object$panel.args[[i]]$x));
}
else {
ordering <- rev(match(sample.order, trellis.object$x.scales$labels));
}
}
if (length(sample.order) == 1) {
if (sample.order == 'decreasing') {
ordering <- order(trellis.object$panel.args[[1]]$y[c(1:num.bars)]);
}
if (sample.order == 'increasing') {
ordering <- rev(order(trellis.object$panel.args[[1]]$y[c(1:num.bars)]));
}
}
if (xat != TRUE) {
newxat <- NULL;
for (j in rev(ordering)) {
if (length(which(xat == j) > 0)) {
newxat <- c(newxat, which(rev(ordering) == j));
}
else { newxat <- c(newxat, 0); }
}
trellis.object$x.scales$at <- newxat;
}
if (length(xaxis.lab) == 1 && xaxis.lab) {
trellis.object$x.scales$labels <- rep(
trellis.object$panel.args[[i]]$x[rev(ordering)],
length(trellis.object$panel.args[[1]]$x) / num.bars
);
}
else {
trellis.object$x.scales$labels <- rev(trellis.object$x.scales$labels[rev(ordering)]);
warning('WARNING: the label order you specified has been reordered.');
}
for (j in 0:(length(trellis.object$panel.args[[1]]$x) / num.bars - 1)) {
trellis.object$panel.args[[i]]$y[c( (1 + j * num.bars) : (num.bars * (j + 1) ) )] <- rev(
trellis.object$panel.args[[i]]$y[ordering + num.bars * j]
);
trellis.object$panel.args[[i]]$x <- rep(1:length(ordering), length(trellis.object$panel.args[[1]]$x) / num.bars);
}
}
else {
num.bars <- length(unique(trellis.object$panel.args[[1]]$y));
if (length(unique(sample.order)) == num.bars) {
if (length(yaxis.lab) == 1 && yaxis.lab) {
ordering <- rev(match(sample.order, sort(sample.order)[trellis.object$panel.args[[i]]$y]));
}
else {
ordering <- rev(match(sample.order, sort(sample.order)[trellis.object$y.scales$labels]));
}
}
if (length(sample.order) == 1 && sample.order == 'decreasing') {
ordering <- order(trellis.object$panel.args[[1]]$x[c(1:num.bars)]);
}
if (length(sample.order) == 1 && sample.order == 'increasing') {
ordering <- rev(order(trellis.object$panel.args[[1]]$x[c(1:num.bars)]));
}
if (yat != TRUE) {
newyat <- NULL;
for (j in rev(ordering)) {
if (length(which(yat == j) > 0)) {
newyat <- c(newyat, which(rev(ordering) == j));
}
else {
newyat <- c(newyat, 0);
}
}
trellis.object$y.scales$at <- newyat;
}
if (length(yaxis.lab) == 1 && yaxis.lab) {
trellis.object$y.scales$labels <- rep(
trellis.object$panel.args[[i]]$y[ordering],
length(trellis.object$panel.args[[1]]$y) / num.bars
);
}
else {
trellis.object$y.scales$labels <- rev(trellis.object$y.scales$labels[ordering]);
warning('WARNING: the label order you specified has been reordered.');
}
for (j in 0:(length(trellis.object$panel.args[[1]]$y) / num.bars - 1)) {
trellis.object$panel.args[[i]]$x[c( (1 + j * num.bars) : (num.bars * (j + 1) ) )] <- rev(
trellis.object$panel.args[[i]]$x[ordering + num.bars * j]
);
trellis.object$panel.args[[i]]$y <- rep(1:length(ordering), length(trellis.object$panel.args[[1]]$y) / num.bars);
}
}
}
y.error.up <- y.error.up[rev(ordering)];
y.error.down <- y.error.down[rev(ordering)];
}
if ('Nature' == style) {
trellis.object$axis <- function(side, line.col = 'black', ...) {
if (side %in% c('bottom', 'left')) {
axis.default(side = side, line.col = 'black', ...);
lims <- current.panel.limits();
panel.abline(h = lims$ylim[1], v = lims$xlim[1]);
}
}
if (resolution < 1200) {
resolution <- 1200;
warning('Setting resolution to 1200 dpi.');
}
warning('Nature also requires italicized single-letter variables and
en-dashes for ranges and negatives. See example in documentation for how to do this.');
warning('Avoid red-green colour schemes, create TIFF files, do not outline the figure or legend.');
}
else if ('BoutrosLab' == style) {
}
else {
warning("The style parameter only accepts 'Nature' or 'BoutrosLab'.");
}
return(
BoutrosLab.plotting.general::write.plot(
trellis.object = trellis.object,
filename = filename,
height = height,
width = width,
size.units = size.units,
resolution = resolution,
enable.warnings = enable.warnings,
description = description
)
);
} |
Hadamard <- function(a){
H=1/sqrt(2) * matrix(c(1,1,1,-1),nrow=2,ncol=2)
result <-H%*%a
result
} |
context("PipeOpColApply")
test_that("apply general tests", {
op = PipeOpColApply$new()
expect_pipeop(op)
task = mlr_tasks$get("iris")
expect_datapreproc_pipeop_class(PipeOpColApply, task = task,
constargs = list(param_vals = list(applicator = as.character)))
expect_datapreproc_pipeop_class(PipeOpColApply, task = mlr_tasks$get("pima"),
constargs = list(param_vals = list(applicator = as.numeric)))
})
test_that("apply results look as they should", {
po = PipeOpColApply$new()
task = mlr_tasks$get("iris")
po$param_set$values = list(applicator = as.character)
expect_equal(
po$train(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(do.call(cbind, lapply(iris[1:4], as.character)))
)
expect_equal(
po$predict(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(do.call(cbind, lapply(iris[1:4], as.character)))
)
po$param_set$values = list(applicator = Vectorize(as.character))
expect_equal(
po$train(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(do.call(cbind, lapply(iris[1:4], as.character)))
)
expect_equal(
po$predict(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(do.call(cbind, lapply(iris[1:4], as.character)))
)
po$param_set$values = list(applicator = function(x) x^2)
expect_equal(
po$train(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(do.call(cbind, lapply(iris[1:4], function(x) x^2)))
)
expect_equal(
po$predict(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(do.call(cbind, lapply(iris[1:4], function(x) x^2)))
)
po$param_set$values = list(applicator = Vectorize(function(x) x^2))
expect_equal(
po$train(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(do.call(cbind, lapply(iris[1:4], function(x) x^2)))
)
expect_equal(
po$predict(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(do.call(cbind, lapply(iris[1:4], function(x) x^2)))
)
tomean = function(x) rep(mean(x), length(x))
po$param_set$values = list(applicator = tomean)
expect_equal(
po$train(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(do.call(cbind, lapply(iris[1:4], tomean)))
)
expect_equal(
po$predict(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(do.call(cbind, lapply(iris[1:4], tomean)))
)
po$param_set$values = list(applicator = Vectorize(tomean))
expect_equal(
po$train(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(iris[1:4])
)
expect_equal(
po$predict(list(task))[[1]]$data(cols = colnames(iris[1:4])),
as.data.table(iris[1:4])
)
po$param_set$values = list(applicator = as.character, affect_columns = selector_grep("^Sepal"))
expect_equal(
po$train(list(task))[[1]]$data(cols = colnames(iris[1:4])),
cbind(as.data.table(do.call(cbind, lapply(iris[1:2], as.character))), iris[3:4])
)
expect_equal(
po$predict(list(task))[[1]]$data(cols = colnames(iris[1:4])),
cbind(as.data.table(do.call(cbind, lapply(iris[1:2], as.character))), iris[3:4])
)
po$param_set$values = list(applicator = Vectorize(as.character), affect_columns = selector_grep("^Sepal"))
expect_equal(
po$train(list(task))[[1]]$data(cols = colnames(iris[1:4])),
cbind(as.data.table(do.call(cbind, lapply(iris[1:2], as.character))), iris[3:4])
)
expect_equal(
po$predict(list(task))[[1]]$data(cols = colnames(iris[1:4])),
cbind(as.data.table(do.call(cbind, lapply(iris[1:2], as.character))), iris[3:4])
)
})
test_that("empty task", {
task = tsk("iris")$filter(0L)
po = PipeOpColApply$new()
po$param_set$values$applicator = function(x) as.integer(x)
train_out = po$train(list(task))[[1L]]
expect_data_table(train_out$data(), nrows = 0L)
expect_true(all(train_out$feature_types$type == "integer"))
predict_out = po$predict(list(task))[[1L]]
expect_data_table(predict_out$data(), nrows = 0L)
expect_true(all(predict_out$feature_types$type == "integer"))
})
test_that("multiple column output", {
task = tsk("iris")
po = PipeOpColApply$new()
po$param_set$values$applicator = function(x) cbind(floor(x), ceiling(x))
train_out = po$train(list(task))[[1L]]
expect_setequal(train_out$feature_names, as.vector(t(outer(task$feature_names, c(".V1", ".V2"), FUN = "paste0"))))
expect_equal(
train_out$data(cols = train_out$feature_names),
as.data.table(map(task$data(cols = task$feature_names), .f = function(x) cbind(floor(x), ceiling(x))))
)
expect_equal(train_out, po$predict(list(task))[[1L]])
po$param_set$values$applicator = function(x) cbind(floor = floor(x), ceiling = ceiling(x))
train_out = po$train(list(task))[[1L]]
expect_setequal(train_out$feature_names, as.vector(t(outer(task$feature_names, c(".floor", ".ceiling"), FUN = "paste0"))))
expect_equal(
train_out$data(cols = train_out$feature_names),
as.data.table(map(task$data(cols = task$feature_names), .f = function(x) cbind(floor = floor(x), ceiling = ceiling(x))))
)
expect_equal(train_out, po$predict(list(task))[[1L]])
po$param_set$values$applicator = function(x) data.frame(floor(x), ceiling(x))
train_out = po$train(list(task))[[1L]]
expect_setequal(train_out$feature_names, as.vector(t(outer(task$feature_names, c(".floor.x.", ".ceiling.x."), FUN = "paste0"))))
expect_equal(
train_out$data(cols = train_out$feature_names),
as.data.table(map(task$data(cols = task$feature_names), .f = function(x) data.frame(floor(x), ceiling(x))))
)
expect_equal(train_out, po$predict(list(task))[[1L]])
po$param_set$values$applicator = function(x) data.frame(floor = floor(x), ceiling = ceiling(x))
train_out = po$train(list(task))[[1L]]
expect_setequal(train_out$feature_names, as.vector(t(outer(task$feature_names, c(".floor", ".ceiling"), FUN = "paste0"))))
expect_equal(
train_out$data(cols = train_out$feature_names),
as.data.table(map(task$data(cols = task$feature_names), .f = function(x) data.frame(floor = floor(x), ceiling = ceiling(x))))
)
expect_equal(train_out, po$predict(list(task))[[1L]])
po$param_set$values$applicator = function(x) data.table(floor(x), ceiling(x))
train_out = po$train(list(task))[[1L]]
expect_setequal(train_out$feature_names, as.vector(t(outer(task$feature_names, c(".V1", ".V2"), FUN = "paste0"))))
expect_equal(
train_out$data(cols = train_out$feature_names),
as.data.table(map(task$data(cols = task$feature_names), .f = function(x) data.table(floor(x), ceiling(x))))
)
expect_equal(train_out, po$predict(list(task))[[1L]])
po$param_set$values$applicator = function(x) data.table(floor = floor(x), ceiling = ceiling(x))
train_out = po$train(list(task))[[1L]]
expect_setequal(train_out$feature_names, as.vector(t(outer(task$feature_names, c(".floor", ".ceiling"), FUN = "paste0"))))
expect_equal(
train_out$data(cols = train_out$feature_names),
as.data.table(map(task$data(cols = task$feature_names), .f = function(x) data.table(floor = floor(x), ceiling = ceiling(x))))
)
expect_equal(train_out, po$predict(list(task))[[1L]])
}) |
netmigration <- function(mort, fert, startyearpop=mort, mfratio = 1.05)
{
if (class(mort) != "demogdata" | class(fert) != "demogdata")
stop("Inputs not demogdata objects")
if (mort$type != "mortality")
stop("mort not mortality data")
if (fert$type != "fertility")
stop("fert not fertility data")
yrs <- mort$year[sort(match(fert$year, mort$year))]
yrs <- yrs[sort(match(startyearpop$year,yrs))]
if(max(startyearpop$year) > max(yrs))
startyearpop <- extract.years(startyearpop, c(yrs,max(yrs)+1))
else
{
startyearpop <- extract.years(startyearpop, yrs)
yrs <- sort(unique(pmin(yrs, max(yrs)-1)))
}
mort <- extract.years(mort, yrs)
fert <- extract.years(fert, yrs)
n <- length(yrs)
p <- length(mort$age)
B <- colSums(fert$pop$female * fert$rate$female/1000)
Bf <- B * 1/(1 + mfratio)
Bm <- B * mfratio/(1 + mfratio)
nsr.f <- 1 - lifetable(mort, "female", max.age = max(mort$age))$rx
nsr.m <- 1 - lifetable(mort, "male", max.age = max(mort$age))$rx
oldest.f <- colSums(as.matrix(startyearpop$pop$female[(p - 1):p, ]))
oldest.m <- colSums(as.matrix(startyearpop$pop$male[(p - 1):p, ]))
if (n > 1)
{
Df <- nsr.f * rbind(Bf, startyearpop$pop$female[1:(p - 2), -n - 1], oldest.f[-n - 1])
Dm <- nsr.m * rbind(Bm, startyearpop$pop$male[1:(p - 2), -n - 1], oldest.m[-n - 1])
} else
{
Df <- nsr.f * c(Bf, startyearpop$pop$female[1:(p - 2), -n - 1], oldest.f[-n - 1])
Dm <- nsr.m * c(Bm, startyearpop$pop$male[1:(p - 2), -n - 1], oldest.m[-n - 1])
}
Dm[is.na(Dm) | Dm < 0] <- 0
Df[is.na(Df) | Df < 0] <- 0
Mf <- Mm <- matrix(NA, nrow = p, ncol = n)
for (j in 1:n)
{
current <- extract.years(startyearpop, years = yrs[j] + 1)
prev <- extract.years(startyearpop, years = yrs[j])
Mf[, j] <- current$pop$female - c(Bf[j], prev$pop$female[1:(p - 2), ], oldest.f[j]) + Df[, j]
Mm[, j] <- current$pop$male - c(Bm[j], prev$pop$male[1:(p - 2), ], oldest.m[j]) + Dm[, j]
}
mig <- extract.years(startyearpop, years = yrs)
mig$rate$female <- Mf
mig$rate$male <- Mm
mig$rate$total <- Mm + Mf
mig$pop$total <- mig$pop$male + mig$pop$female
mig$lambda <- 1
dimnames(mig$rate$male) <- dimnames(mig$rate$female) <- dimnames(mig$rate$total) <- dimnames(mig$pop$male)
mig$type <- "migration"
return(mig)
}
pop.sim <- function(mort, fert = NULL, mig = NULL, firstyearpop, N = 100, mfratio = 1.05, bootstrap = FALSE)
{
no.mortality <- FALSE
no.fertility <- is.null(fert)
no.migration <- is.null(mig)
if (!no.mortality)
{
if (class(mort) != "fmforecast2")
stop("Inputs not fmforecast2 objects")
if (mort$female$type != "mortality" | mort$male$type != "mortality")
stop("mort not based on mortality data")
}
if (!no.fertility)
{
if (class(fert)[1] != "fmforecast")
stop("Inputs not fmforecast objects")
if (fert$type != "fertility")
stop("fert not based on fertility data")
}
if (!no.migration)
{
if (class(mig) != "fmforecast2")
stop("Inputs not fmforecast2 objects")
if (mig$male$type != "migration" | mig$female$type != "migration")
stop("mig not based on migration data")
}
firstyr <- mort$male$year
if (!no.fertility)
firstyr <- intersect(firstyr, fert$year)
if (!no.migration)
firstyr <- intersect(firstyr, mig$male$year)
firstyr <- min(firstyr)
pop <- extract.years(firstyearpop, firstyr)$pop
firstyearpop$age <- as.integer(firstyearpop$age)
mort$male$age <- as.integer(mort$male$age)
mig$male$age <- as.integer(mig$male$age)
if (!no.migration)
{
if (!identical(firstyearpop$age, mig$male$age))
stop("Please ensure that migration and population data have the same age dimension")
}
if (!no.mortality)
{
if (!identical(firstyearpop$age, mort$male$age))
stop("Please ensure that mortality and population data have the same age dimension")
}
p <- length(firstyearpop$age)
hm <- hf <- h <- Inf
if (!no.mortality)
{
mort.sim <- simulate(mort, nsim = N, bootstrap = bootstrap)
hm <- length(mort$male$year)
}
if (!no.fertility)
{
fert.sim <- simulate(fert, nsim = N, bootstrap = bootstrap)
hf <- length(fert$year)
}
if (!no.migration)
{
mig.sim <- simulate(mig, nsim = N, bootstrap = bootstrap)
h <- length(mig$male$year)
nm <- length(mig$male$model$year)
}
h <- min(hm, hf, h)
if (!no.fertility)
fage <- is.element(rownames(pop$female), fert$age)
pop.f <- pop.m <- array(0, c(p, h, N))
dimnames(pop.f) <- dimnames(pop.m) <- list(mort$female$age, 1:h, 1:N)
advance <- function(x0, x)
{
n <- length(x)
newx <- c(x0, x[1:(n - 2)], x[n - 1] + x[n])
}
for (i in 1:N)
{
popf <- round(c(pop$female))
popm <- round(c(pop$male))
for (j in 1:h)
{
if (no.migration)
{
netf <- netm <- 0
Rf <- popf
Rm <- popm
} else
{
netf <- round(mig.sim$female[, j, i] + mig$female$model$res$y[, sample(1:nm, 1)])
netm <- round(mig.sim$male[, j, i] + mig$male$model$res$y[, sample(1:nm, 1)])
Rf <- pmax(popf + 0.5 * c(netf[2:(p - 1)], 0.5 * netf[p], 0.5 * netf[p]), 0)
Rm <- pmax(popm + 0.5 * c(netm[2:(p - 1)], 0.5 * netm[p], 0.5 * netm[p]), 0)
}
Rt <- firstyearpop
Rt$type <- "mortality"
Rt$lambda <- 0
Rt$year <- 1
Rt$rate$female <- matrix(mort.sim$female[, j, i], ncol = 1)
Rt$rate$male <- matrix(mort.sim$male[, j, i], ncol = 1)
Rt$pop$female <- matrix(Rf, ncol = 1)
Rt$pop$male <- matrix(Rm, ncol = 1)
Rt$rate$total <- Rt$pop$total <- NULL
colnames(Rt$pop$male) <- colnames(Rt$pop$female) <- colnames(Rt$rate$male) <- colnames(Rt$rate$female) <- "1"
rownames(Rt$pop$male) <- rownames(Rt$pop$female) <- rownames(Rt$rate$male) <- rownames(Rt$rate$female) <- Rt$age
nsr.f <- 1 - lifetable(Rt, "female", max.age = max(Rt$age))$rx
nsr.m <- 1 - lifetable(Rt, "male", max.age = max(Rt$age))$rx
cohDf <- pmax(nsr.f[c(2:p, p)] * Rf, 0)
cohDm <- pmax(nsr.m[c(2:p, p)] * Rm, 0)
Rf2 <- advance(0, Rf - cohDf)
Rm2 <- advance(0, Rm - cohDm)
Ef <- 0.5 * (Rf + Rf2)
Em <- 0.5 * (Rm + Rm2)
Df <- rpois(rep(1, p), Ef * mort.sim$female[, j, i])
Dm <- rpois(rep(1, p), Em * mort.sim$male[, j, i])
cohDf[2:(p - 2)] <- 0.5 * (Df[2:(p - 2)] + Df[3:(p - 1)])
cohDm[2:(p - 2)] <- 0.5 * (Dm[2:(p - 2)] + Dm[3:(p - 1)])
cohDf[p - 1] <- 0.5 * Df[p - 1] + Df[p]
cohDm[p - 1] <- 0.5 * Dm[p - 1] + Dm[p]
cohDf[p] <- cohDm[p] <- 0
Rf2 <- advance(0, Rf - cohDf)
Rm2 <- advance(0, Rm - cohDm)
if (no.fertility)
B <- 0
else
{
lambda <- 0.5 * (Rf[fage] + Rf2[fage]) * fert.sim[, j, i]/1000
B <- sum(rpois(rep(1, length(fert$age)), lambda))
}
Bm <- rbinom(1, B, mfratio/(1 + mfratio))
Bf <- B - Bm
RfB <- pmax(Bf + 0.5 * netf[1], 0)
RmB <- pmax(Bm + 0.5 * netm[1], 0)
cohDfB <- pmax(nsr.f[1] * RfB, 0)
cohDmB <- pmax(nsr.m[1] * RmB, 0)
Rf20 <- RfB - cohDfB
Rm20 <- RmB - cohDmB
Ef0 <- 0.5 * (Rf[1] + Rf20)
Em0 <- 0.5 * (Rm[1] + Rm20)
Df0 <- rpois(1, Ef0 * mort.sim$female[1, j, i])
Dm0 <- rpois(1, Em0 * mort.sim$male[1, j, i])
f0f <- cohDfB/(Ef0 * mort.sim$female[1, j, i])
f0m <- cohDmB/(Em0 * mort.sim$male[1, j, i])
cohDfB <- f0f * Df0
cohDmB <- f0m * Dm0
cohDf[1] <- (1 - f0f) * Df0 + 0.5 * Df[1]
cohDm[1] <- (1 - f0m) * Dm0 + 0.5 * Dm[1]
Rf2 <- advance(RfB - cohDfB, Rf - cohDf)
Rm2 <- advance(RmB - cohDmB, Rm - cohDm)
popf <- round(pmax(Rf2 + 0.5 * netf, 0))
popm <- round(pmax(Rm2 + 0.5 * netm, 0))
pop.f[, j, i] <- popf
pop.m[, j, i] <- popm
}
}
dimnames(pop.m)[[2]] <- dimnames(pop.m)[[2]] <- firstyr + (1:h)-1
return(list(male = pop.m, female = pop.f))
}
deaths <- function(x)
{
if (class(x) != "demogdata" | x$type != "mortality")
stop("Not a mortality object")
npop <- length(x$rate)
out <- list()
for (i in 1:npop)
{
out[[i]] <- round(x$rate[[i]] * x$pop[[i]])
out[[i]][is.na(out[[i]])] <- 0
}
names(out) <- names(x$rate)
return(out)
}
births <- function(x)
{
if (class(x) != "demogdata" | x$type != "fertility")
stop("Not a fertility object")
out <- round(x$rate[[1]] * x$pop[[1]]/1000)
out[is.na(out)] <- 0
return(out)
} |
abc.a.coefs <-
function(indices, splitting=FALSE) {
a.coefs.nominal <- function (p = NULL, ...)
{ if (p > 1)
{
a.coefs.mat <- matrix(nrow=p,ncol=2^p)
for (i in 1:p) {
a.coefs.mat[i,] <- rep(c(1,0), times = c(2^(p-i),2^(p-i)))
}
a.coefs.mat <- a.coefs.mat[,-c(2^p)]
} else {
a.coefs.mat <- matrix(1,ncol=1,nrow=1)
}
return (a.coefs.mat)
}
a.coefs.ordinal <- function (p = NULL, ...)
{ if (p > 1)
{
if (p > 2)
{ a.coefs.mat <- diag(p)
for (i in 1:(p-2))
{ m <- matrix(0,ncol=p, nrow=p-i)
for (j in 1:(i+1)) { m <- m + cbind (matrix(0,ncol=j-1,nrow=p-i), diag (p-i), matrix(0,ncol=i-j+1,nrow=p-i)) }
a.coefs.mat <- cbind(a.coefs.mat, t(m))
}
a.coefs.mat <- cbind(a.coefs.mat,1)
}
else { a.coefs.mat <- cbind (diag (2), c(1,1)) }
} else {
a.coefs.mat <- matrix(1,ncol=1,nrow=1)
}
return (a.coefs.mat) }
index1 <- indices[[1]]
index2 <- indices[[2]]
A <- matrix(0,ncol=0,nrow=0)
if (splitting==TRUE){
for (i in 1:length(index1)) {
if ( index2[i]<0 ) { B <- a.coefs.nominal(p=index1[i])[,-1]
B <- B[,which(B[1,]==1)]
A <- bdiag(A,B)}
if ( index2[i]==0) { A <- bdiag(A,matrix(0,ncol=0,nrow=index1[i])) }
if ( index2[i]>0 ) { B <- a.coefs.ordinal(p=index1[i])[,-(sum(1:index1[i]))]
B <- B[,which(B[1,]==1)]
A <- bdiag(A,B)}
} } else {
for (i in 1:length(index1)) {
if ( index2[i]<0 ) { A <- bdiag(A,a.coefs.nominal(p=index1[i])) }
if ( index2[i]==0) { A <- bdiag(A,matrix(0,ncol=0,nrow=index1[i])) }
if ( index2[i]>0 ) { A <- bdiag(A,a.coefs.ordinal(p=index1[i])) }
} }
a.coefs.mat<-as.matrix(A)
return(a.coefs.mat)
} |
garchsk_construct<-function(params,data){
T<-length(data)
mu <- rep(base::mean(data),T)
h <- rep(stats::var(data),T)
sk <- rep(skewness(data),T)
ku <- rep(kurtosis(data),T)
para_m<-params[1]
para_h<-params[2:4]
para_sk<-params[5:7]
para_ku<-params[8:10]
for(t in 2:T){
mu[t]<-para_m * data[t-1]
h[t]<-para_h %*% c(1,(data[t-1]-mu[t-1])^2,h[t-1])
sk[t]<-para_sk %*% c(1,((data[t-1]-mu[t-1])/sqrt(h[t-1]))^3,sk[t-1])
ku[t]<-para_ku %*% c(1,((data[t-1]-mu[t-1])/sqrt(h[t-1]))^4,ku[t-1])
}
return(list(mu=mu,h=h,sk=sk,ku=ku))
}
garchsk_lik<-function(params,data){
T<-length(data)
t <- 2:T
likelihoods <- numeric(0)
GARCHSK <- garchsk_construct(params,data)
mu = GARCHSK$mu[t]
h = GARCHSK$h[t]
sk = GARCHSK$sk[t]
ku = GARCHSK$ku[t]
std<-(data[t]-mu)/sqrt(h)
f <- log((1 + (sk/6)*(std^3 - 3*std) + ((ku-3)/24)*(std^4 - 6*(std^2)+3))^2)
g <- log(1 + (sk^2)/6 + ((ku-3)^2)/24)
likelihoods <- -0.5*(log(h) + std^2 ) + f - g
likelihoods <- - likelihoods
LLF <-sum(likelihoods)
if( is.nan(LLF) ){
LLF <- 1e+06
}
return(LLF)
}
garchsk_ineqfun<-function(params,data){
para_m<-params[1]
para_h<-params[2:4]
para_sk<-params[5:7]
para_ku<-params[8:10]
return(c(para_m,para_h,para_sk[-1],para_ku,sum(para_h[-1]),sum(para_sk[-1]),sum(para_ku[-1])))
}
garchsk_est<-function(data){
X <- data[-length(data)]
Y <- data[-1]
a1 <- stats::cov(Y,X)/stats::var(X)
b1 <- 0.01
b2 <- 0.90
b0 <- (1-(b1+b2))*stats::var(data)
c1 <- 0.01
c2 <- 0.7
c0 <- (1-(c1+c2))*skewness(data)
d1 <- 0.01
d2 <- 0.80
d0 <- (1-(d1+d2))*(kurtosis(data))
init <-c(a1,b0,b1,b2,c0,c1,c2,d0,d1,d2)
aLB<-c(-1)
bLB<-c(0,rep(0,length(b1)),rep(0,length(b2)))
cLB<-c(rep(-1,length(c1)),rep(-1,length(c2)))
dLB<-c(0,rep(0,length(d1)),rep(0,length(d2)))
sumbLB<-c(0)
sumcLB<-c(-1)
sumdLB<-c(0)
ineqLB<-c(aLB,bLB,cLB,dLB,sumbLB,sumcLB,sumdLB)
aUB<-c(1)
bUB<-c(Inf,rep(1,length(b1)),rep(1,length(b2)))
cUB<-c(rep(1,length(c1)),rep(1,length(c2)))
dUB<-c(Inf,rep(1,length(d1)),rep(1,length(d2)))
sumbUB<-c(1)
sumcUB<-c(1)
sumdUB<-c(1)
ineqUB<-c(aUB,bUB,cUB,dUB,sumbUB,sumcUB,sumdUB)
sol<-Rsolnp::solnp(pars=init , fun=garchsk_lik, ineqfun = garchsk_ineqfun, ineqLB = ineqLB, ineqUB = ineqUB, data=data)
params<-sol$par
loglik<-sol$values
loglik<-loglik[length(loglik)]
hessian<-sol$hessian[1:length(params),1:length(params)]
stderrors <- sqrt(1/length(data)*diag(hessian))
tstats <- params/stderrors
AIC <- -2*loglik + 2*length(params)
BIC <- -2*loglik + length(params)*log(length(data))
return(list(params=params,stderrors=stderrors,tstats=tstats,loglik=loglik,AIC=AIC,BIC=BIC))
}
garchsk_fcst<-function(params,data,max_forecast=20){
T<-length(data)
t <- 2:T
GARCHSK <- garchsk_construct(params,data)
mu = GARCHSK$mu[t]
h = GARCHSK$h[t]
sk = GARCHSK$sk[t]
ku = GARCHSK$ku[t]
para_m<-params[1]
para_h<-params[2:4]
para_sk<-params[5:7]
para_ku<-params[8:10]
T<-length(h)
mu_fcst<-para_m * data[T]
h_fcst<-para_h %*% c(1,(data[T]-mu[T])^2,h[T])
sk_fcst<-para_sk %*% c(1,((data[T]-mu[T])/sqrt(h[T]))^3,sk[T])
ku_fcst<-para_ku %*% c(1,((data[T]-mu[T])/sqrt(h[T]))^4,ku[T])
for(i in 2:max_forecast){
mu_fcst<-c(h_fcst, para_m * h_fcst[i-1])
h_fcst<-c(h_fcst, para_h[1] + sum(para_h[-1] * h_fcst[i-1]))
sk_fcst<-c(sk_fcst, para_sk[1] + sum(para_sk[-1] * sk_fcst[i-1]))
ku_fcst<-c(ku_fcst, para_ku[1] + sum(para_ku[-1] * ku_fcst[i-1]))
}
return(list(mu_fcst=mu_fcst,h_fcst=h_fcst,sk_fcst=sk_fcst,ku_fcst=ku_fcst))
} |
NULL
wordcloud2Output <- function(outputId, width = "100%", height = "400px") {
htmlwidgets::shinyWidgetOutput(outputId, "wordcloud2", width, height, package = "wordcloud2")
}
renderWordcloud2 <- function(expr, env = parent.frame(), quoted = FALSE) {
if (!quoted) { expr <- substitute(expr) }
htmlwidgets::shinyRenderWidget(expr, wordcloud2Output, env, quoted = TRUE)
} |
observe({
validate(
need(!is.null(rawData_data$data), "Please select a data set")
)
rawData <- rawData()
chem_site <- rawData$chem_site
chemical_summary <- chemical_summary()
siteToFind <- unique(chemical_summary$site)
if(length(siteToFind) == 1){
chem_site <- chem_site[chem_site$SiteID == siteToFind,]
}
catType = as.numeric(input$radioMaxGroup)
meanEARlogic <- as.logical(input$meanEAR)
sum_logic <- as.logical(input$sumEAR)
maxEARWords <- ifelse(meanEARlogic,"Mean","Max")
category <- c("Biological","Chemical","Chemical Class")[catType]
mapDataList <- mapDataINFO()
mapData <- mapDataList$mapData
pal <- mapDataList$pal
if(length(siteToFind) == 1){
mapData <- mapData %>%
dplyr::filter(SiteID == siteToFind)
}
map <- leaflet::leafletProxy("mymap", data = mapData) %>%
leaflet::clearMarkers() %>%
leaflet::addCircleMarkers(lat=~dec_lat, lng=~dec_lon,
popup=paste0('<b>',mapData$`Short Name`,"</b><br/><table>",
"<tr><td>",maxEARWords,": </td><td>",sprintf("%.1f",mapData$meanMax),'</td></tr>',
"<tr><td>Number of Samples: </td><td>",mapData$count,'</td></tr>',
'</table>') ,
fillColor = ~pal(meanMax),
fillOpacity = 0.8,
radius = ~sizes,
stroke=FALSE,
opacity = 0.8) %>%
leaflet::fitBounds(~min(dec_lon), ~min(dec_lat),
~max(dec_lon), ~max(dec_lat))
sum_words <- ifelse(sum_logic, "Sum of","Max")
if(length(siteToFind) > 1){
map <- map %>% leaflet::clearControls()
map <- leaflet::addLegend(map,pal = pal,
position = 'bottomleft',
values=~meanMax,
opacity = 0.8,
labFormat = leaflet::labelFormat(digits = 2),
title = paste(sum_words,category,"EAR<br>",
maxEARWords,"at site"))
}
map
})
output$mapFooter <- renderUI({
validate(
need(!is.null(rawData_data$data), "Please select a data set")
)
chemical_summary <- chemical_summary()
nSamples <- dplyr::select(chemical_summary,site,date) %>%
dplyr::distinct() %>%
dplyr::group_by(site) %>%
dplyr::summarize(count = dplyr::n())
HTML(paste0("<h5>Size range represents number of samples. Ranges from ", min(nSamples$count,na.rm = TRUE),
" - ",
max(nSamples$count,na.rm = TRUE),"</h5>"))
})
mapDataINFO <- reactive({
rawData <- rawData()
chem_site <- rawData$chem_site
chemical_summary <- chemical_summary()
catType = as.numeric(input$radioMaxGroup)
category <- c("Biological","Chemical","Chemical Class")[catType]
meanEARlogic <- as.logical(input$meanEAR)
sum_logic <- as.logical(input$sumEAR)
siteToFind <- unique(chemical_summary$site)
mapDataList <- map_tox_data(chemical_summary,
chem_site = chem_site,
category = category,
mean_logic = meanEARlogic,
sum_logic = sum_logic)
if(length(siteToFind) == 1){
if(!is.null(latest_map)){
mapDataList <- latest_map
}
}
latest_map <<- mapDataList
shinyAce::updateAceEditor(session, editorId = "mapCode_out", value = mapCode() )
return(mapDataList)
})
mapCode <- reactive({
catType = as.numeric(input$radioMaxGroup)
plot_ND = input$plot_ND
category <- c("Biological","Chemical","Chemical Class")[catType]
mapCode <- paste0(rCodeSetup(),"
make_tox_map(chemical_summary,
chem_site = tox_list$chem_site,
category = '",category,"',
mean_logic = ",as.logical(input$meanEAR),")")
return(mapCode)
}) |
diff <- function(x, ...) UseMethod("diff")
diff.default <- function(x, lag = 1L, differences = 1L, ...)
{
ismat <- is.matrix(x)
xlen <- if(ismat) dim(x)[1L] else length(x)
if (length(lag) != 1L || length(differences) > 1L ||
lag < 1L || differences < 1L)
stop("'lag' and 'differences' must be integers >= 1")
if (lag * differences >= xlen)
return(x[0L])
r <- unclass(x)
i1 <- -seq_len(lag)
if (ismat)
for (i in seq_len(differences))
r <- r[i1, , drop = FALSE] -
r[-nrow(r):-(nrow(r)-lag+1L), , drop = FALSE]
else
for (i in seq_len(differences))
r <- r[i1] - r[-length(r):-(length(r)-lag+1L)]
class(r) <- oldClass(x)
r
} |
qweibull3 <-
function(p,shape,scale=1,thres=0,lower.tail=TRUE,log.p=FALSE)
{
if(log.p) p <- exp(p)
if(!lower.tail) p <- 1 - p
xF <- thres+qweibull(p,shape,scale)
return(xF)
} |
simgraph_data <- function(nsims = 1000, posigma = 50, dims = 250, kinship = "2C") {
if (!kinship %in% c("PO", "FS", "HS", "AV", "GG", "HAV", "GGG", "1C", "1C1", "2C", "GAV")) {
stop("Invalid Kinship Category")
}
nsims <- nsims
posigma <- posigma
dims <- dims
f0x <- runif(nsims, 0, dims)
f0y <- runif(nsims, 0, dims)
f1ax <- rnorm(nsims, 0, posigma) + f0x
f1ay <- rnorm(nsims, 0, posigma) + f0y
f1bx <- rnorm(nsims, 0, posigma) + f0x
f1by <- rnorm(nsims, 0, posigma) + f0y
f1cx <- rnorm(nsims, 0, posigma) + f0x
f1cy <- rnorm(nsims, 0, posigma) + f0y
f2ax <- rnorm(nsims, 0, posigma) + f1ax
f2ay <- rnorm(nsims, 0, posigma) + f1ay
f2bx <- rnorm(nsims, 0, posigma) + f1bx
f2by <- rnorm(nsims, 0, posigma) + f1by
f3ax <- rnorm(nsims, 0, posigma) + f2ax
f3ay <- rnorm(nsims, 0, posigma) + f2ay
f3bx <- rnorm(nsims, 0, posigma) + f2bx
f3by <- rnorm(nsims, 0, posigma) + f2by
if (kinship == "PO") {
k1x <- f0x
k1y <- f0y
k2x <- f1ax
k2y <- f1ay
}
if (kinship == "FS" | kinship == "HS") {
k1x <- f1ax
k1y <- f1ay
k2x <- f1bx
k2y <- f1by
}
if (kinship == "AV" | kinship == "HAV") {
k1x <- f2ax
k1y <- f2ay
k2x <- f1bx
k2y <- f1by
}
if (kinship == "GG") {
k1x <- f0x
k1y <- f0y
k2x <- f2ax
k2y <- f2ay
}
if (kinship == "1C") {
k1x <- f2ax
k1y <- f2ay
k2x <- f2bx
k2y <- f2by
}
if (kinship == "GGG") {
k1x <- f0x
k1y <- f0y
k2x <- f3ax
k2y <- f3ay
}
if (kinship == "GAV") {
k1x <- f3ax
k1y <- f3ay
k2x <- f1bx
k2y <- f1by
}
if (kinship == "1C1") {
k1x <- f3ax
k1y <- f3ay
k2x <- f2bx
k2y <- f2by
}
if (kinship == "2C") {
k1x <- f3ax
k1y <- f3ay
k2x <- f3bx
k2y <- f3by
}
kindist <- round(sqrt((k1x - k2x)^2 + (k1y - k2y)^2), digits = 1)
kinmidx <- (k1x + k2x) / 2
kinmidy <- (k1y + k2y) / 2
result <- tibble(
f0x = f0x, f0y = f0y, f1ax = f1ax, f1ay = f1ay,
f1bx = f1bx, f1by = f1by, f1cx = f1cx, f1cy = f1cy,
f2ax = f2ax, f2ay = f2ay, f2bx = f2bx, f2by = f2by,
f3ax = f3ax, f3ay = f3ay, f3bx = f3bx, f3by = f3by,
kindist = kindist, kinmidx = kinmidx, kinmidy = kinmidy,
k1x = k1x, k1y = k1y, k2x = k2x, k2y = k2y,
posigma = posigma, dims = dims, kinship = kinship
)
return(result)
} |
get_city_data <- function(x, region, date) {
if (is(x, "nCov2019")) {
stats <- x[region, ]
} else {
stats <- extract_history(x, region, date)
}
names(stats)[1] <- 'NAME'
return(stats)
}
extract_history <- function(x, province, date) {
if (missing(province)) {
df <- summary(x)[, c('province','time','cum_confirm')]
} else {
df <- x[province, c('city','time','cum_confirm')]
}
df <- df[df$time == as.Date(date, "%Y-%m-%d"), c(1,3)]
names(df) <- c("name", "confirm")
return(df)
}
extract_province <- function(object, i, by) {
if (i == 'global') {
res = object$global
return(res)
}
d <- object$areaTree[1,"children"][[1]]
name = d[[1]]
if (is.character(i)) {
i <- which(name == i)
}
stats <- d[i, "children"][[1]]
cbind(name=stats$name, stats[[by]])
}
.get_qq_data <- function() {
url <- 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5'
x <- suppressWarnings(readLines(url, encoding="UTF-8"))
y <- jsonlite::fromJSON(x)
data = jsonlite::fromJSON(y$data)
url2 <- 'https://view.inews.qq.com/g2/getOnsInfo?name=disease_other'
x2 <- suppressWarnings(readLines(url2, encoding="UTF-8"))
y2 = jsonlite::fromJSON(x2, flatten = TRUE)
y2 = jsonlite::fromJSON(y2$data,flatten = T)
data$dailyHistory <- y2$dailyHistory
data$chinaDayList <- y2$chinaDayList
data$chinaDayAddList <- y2$chinaDayAddList
url3 <- 'https://api.inews.qq.com/newsqa/v1/automation/foreign/country/ranklist'
x3 <- suppressWarnings(readLines(url3, encoding="UTF-8"))
y3 = jsonlite::fromJSON(x3, flatten = TRUE)$data
df <- y3[c('name','confirm','suspect','dead','heal')]
df$deadRate <- round(df$dead*100/df$confirm,2)
df$healRate <- round(df$heal*100/df$confirm,2)
df$showRate <- 'FALSE'
df$showHeal <- 'FALSE'
name <- data$areaTree[1]$name
idx = c("name","confirm","suspect","dead","heal","deadRate","healRate","showRate","showHeal")
CN <- cbind(name = name, data$areaTree$total)[1, ][,idx]
data$global = rbind(CN, df)
return(data)
}
fill_scale_continuous <- function(palette = "Reds") {
cols = RColorBrewer::brewer.pal(6, palette)
breaks = c(1, 10, 100, 1000, 10000, 100000, 1000000, 10000000)
scale_fill_gradient(low=cols[1], high=cols[6],
na.value='white', trans='log',
breaks=breaks, labels=breaks)
}
discrete_breaks <- c(1,10,100,500,10^3,10^4, 10^5, 10^6,10^7)
fill_scale_discrete <- function(palette = "Reds") {
scale_fill_brewer(palette=palette, name='confirm',
na.translate = FALSE,
breaks = c('[1,10)', '[10,100)', '[100,500)',
'[500,1e+03)', '[1e+03,1e+04)', '[1e+04,1e+05)',
'[1e+05,1e+06]','[1e+06,1e+07]'),
labels = c("<10", "10-100", "100-500", "500-1000",
"1000-10000", "10000-100000","100000-1000000",
">1000000"))
}
which_lang <- function(lang) {
lang <- match.arg(lang, c("auto","zh", "en"))
if (lang == "auto") {
locale <- Sys.getlocale('LC_CTYPE')
locale <- sub("^(\\w+)\\W.*", "\\1", locale)
if (tolower(locale) %in% c("chinese", "zh")) {
lang <- 'zh'
} else {
lang <- 'en'
}
}
return(lang)
}
check_network <- function(url) {
status = tryCatch({
httr::HEAD(url)$status
}, error= function(e) {
message(e)
FALSE
})
status
} |
pex_acf <- function(tseq, lambda, rho) {
exp(-abs(tseq/lambda)^rho)
} |
pgpa <- function(x , para = c(1, 1, 1)) {
u <- cdfgpa(x , para)
return(u)
} |
to_basic.GeomXspline <- to_basic.GeomXspline2 <-
getFromNamespace("to_basic.GeomLine", asNamespace("plotly"))
to_basic.GeomBkde2d <-
getFromNamespace("to_basic.GeomDensity2d", asNamespace("plotly"))
to_basic.GeomStateface <- function(data, prestats_data, layout, params, p, ...) {
prefix_class(data, "GeomText")
}
prefix_class <- function(x, y) {
structure(x, class = unique(c(y, class(x))))
} |
Election.getStageCandidates <-
function (stageId, electionId) {
Election.getStageCandidates.basic <- function (.stageId, .electionId) {
request <- "Election.getStageCandidates?"
inputs <- paste("&stageId=",.stageId,"&electionId=",.electionId,sep="")
output <- pvsRequest6(request,inputs)
output$stageId <- .stageId
output$electionId <- .electionId
output
}
output.list <- lapply(stageId, FUN= function (y) {
lapply(electionId, FUN= function (s) {
Election.getStageCandidates.basic(.stageId=y, .electionId=s)
}
)
}
)
output.list <- redlist(output.list)
output <- dfList(output.list)
output
} |
create_synthetic_data <- function(n_proteins,
frac_change,
n_replicates,
n_conditions,
method = "effect_random",
concentrations = NULL,
median_offset_sd = 0.05,
mean_protein_intensity = 16.88,
sd_protein_intensity = 1.4,
mean_n_peptides = 12.75,
size_n_peptides = 0.9,
mean_sd_peptides = 1.7,
sd_sd_peptides = 0.75,
mean_log_replicates = -2.2,
sd_log_replicates = 1.05,
effect_sd = 2,
dropout_curve_inflection = 14,
dropout_curve_sd = -1.2,
additional_metadata = TRUE) {
n_change <- round(n_proteins * frac_change)
sampled_protein_intensities <- stats::rnorm(
n = n_proteins,
mean = mean_protein_intensity,
sd = sd_protein_intensity
)
sampled_n_peptides <- stats::rnbinom(n = n_proteins * 3, size = size_n_peptides, mu = mean_n_peptides)
sampled_n_peptides <- sampled_n_peptides[sampled_n_peptides > 0][1:n_proteins]
sampled_peptide_sd <- stats::rnorm(n = n_proteins * 2, mean = mean_sd_peptides, sd = sd_sd_peptides)
sampled_peptide_sd <- sampled_peptide_sd[sampled_peptide_sd > 0][1:n_proteins]
proteins <- tibble::tibble(
protein = paste0("protein_", 1:n_proteins),
n = sampled_n_peptides,
mean = sampled_protein_intensities,
sd = sampled_peptide_sd
) %>%
dplyr::group_by(.data$protein) %>%
dplyr::mutate(peptide_intensity_mean = list(round(
stats::rnorm(
n = .data$n,
mean = .data$mean,
sd = .data$sd
),
digits = 4
))) %>%
tidyr::unnest(.data$peptide_intensity_mean) %>%
dplyr::mutate(peptide = paste0(
"peptide_", stringr::str_extract(
.data$protein,
pattern = "\\d+"
),
"_", 1:dplyr::n()
)) %>%
dplyr::mutate(replicate_sd = round(stats::rlnorm(
n = 1,
meanlog = mean_log_replicates,
sdlog = sd_log_replicates
),
digits = 4
)) %>%
dplyr::select(-c(.data$mean, .data$sd))
proteins_replicates <- proteins %>%
dplyr::group_by(.data$peptide) %>%
dplyr::mutate(condition = list(sort(rep(paste0("condition_", 1:n_conditions), n_replicates)))) %>%
tidyr::unnest(c(.data$condition)) %>%
dplyr::mutate(sample = paste0("sample_", 1:(n_conditions * n_replicates))) %>%
dplyr::ungroup() %>%
dplyr::mutate(peptide_intensity = stats::rnorm(
n = dplyr::n(),
mean = .data$peptide_intensity_mean,
sd = .data$replicate_sd
))
n_peptides <- length(unique(proteins_replicates$peptide))
offset <- rep(
stats::rnorm(n_conditions * n_replicates,
mean = 0,
sd = median_offset_sd
),
n_peptides
)
if (method == "effect_random") {
proteins_replicates_change <- proteins_replicates %>%
dplyr::mutate(change = stringr::str_extract(.data$protein, pattern = "\\d+") %in% 1:n_change) %>%
dplyr::group_by(.data$protein) %>%
dplyr::mutate(n_change_peptide = ifelse(.data$change == TRUE, ceiling(stats::rgamma(1, shape = 0.7, rate = 0.4)), 0)) %>%
dplyr::mutate(n_change_peptide = ifelse(.data$n_change_peptide >= .data$n,
.data$n,
.data$n_change_peptide
)) %>%
dplyr::mutate(change_peptide = .data$change & stringr::str_extract(
.data$peptide,
pattern = "\\d+$"
) %in%
1:unique(.data$n_change_peptide)) %>%
dplyr::mutate(effect = stats::rnorm(dplyr::n(), mean = 0, sd = effect_sd)) %>%
dplyr::mutate(effect = ifelse(.data$change_peptide == TRUE, .data$effect, 0)) %>%
dplyr::group_by(.data$condition, .data$peptide) %>%
dplyr::mutate(effect = rep(.data$effect[1], n_replicates)) %>%
dplyr::mutate(peptide_intensity = .data$peptide_intensity + .data$effect) %>%
dplyr::bind_cols(offset = offset) %>%
dplyr::ungroup() %>%
dplyr::mutate(peptide_intensity = .data$peptide_intensity + .data$offset) %>%
dplyr::select(-c(
.data$peptide_intensity_mean,
.data$replicate_sd,
.data$effect,
.data$n,
.data$n_change_peptide,
.data$offset
))
}
if (method == "dose_response") {
condition_concentration <- tibble::tibble(
condition = paste0("condition_", 1:n_conditions),
concentration = concentrations
)
proteins_replicates_change <- proteins_replicates %>%
dplyr::mutate(change = stringr::str_extract(.data$protein, pattern = "\\d+") %in% 1:n_change) %>%
dplyr::group_by(.data$protein) %>%
dplyr::mutate(n_change_peptide = ifelse(.data$change == TRUE, ceiling(stats::rgamma(1,
shape = 0.7,
rate = 0.4
)), 0)) %>%
dplyr::mutate(n_change_peptide = ifelse(.data$n_change_peptide >= .data$n,
.data$n,
.data$n_change_peptide
)) %>%
dplyr::mutate(change_peptide = .data$change & stringr::str_extract(
.data$peptide,
pattern = "\\d+$"
) %in%
1:unique(.data$n_change_peptide)) %>%
dplyr::left_join(condition_concentration, by = "condition") %>%
dplyr::mutate(effect_total = stats::rnorm(dplyr::n(), mean = 0, sd = effect_sd)) %>%
dplyr::mutate(effect_total = ifelse(.data$change_peptide == TRUE, .data$effect_total, 0)) %>%
dplyr::group_by(.data$peptide) %>%
dplyr::mutate(effect_total = rep(.data$effect_total[1], (n_replicates * n_conditions))) %>%
dplyr::ungroup() %>%
dplyr::mutate(b = sample(c(
stats::rlnorm(dplyr::n(),
meanlog = 0.6,
sdlog = 0.4
),
-rlnorm(dplyr::n(),
meanlog = 0.6,
sdlog = 0.4
)
),
size = dplyr::n()
)) %>%
dplyr::mutate(c = stats::rlnorm(dplyr::n(),
meanlog = log(mean(concentrations) / 2),
sdlog = abs(log(mean(concentrations) / 2) / 3)
)) %>%
dplyr::mutate(b = ifelse(.data$change_peptide == TRUE, .data$b, 0)) %>%
dplyr::mutate(c = ifelse(.data$change_peptide == TRUE, .data$c, 0)) %>%
dplyr::group_by(.data$peptide) %>%
dplyr::mutate(b = rep(.data$b[1], (n_replicates * n_conditions))) %>%
dplyr::mutate(c = rep(.data$c[1], (n_replicates * n_conditions))) %>%
dplyr::mutate(effect = ifelse(.data$change_peptide == TRUE,
.data$effect_total * (1 + (-1 / (1 + (.data$concentration / .data$c)^.data$b))),
0
)) %>%
dplyr::mutate(peptide_intensity = .data$peptide_intensity + .data$effect) %>%
dplyr::bind_cols(offset = offset) %>%
dplyr::ungroup() %>%
dplyr::mutate(peptide_intensity = .data$peptide_intensity + .data$offset) %>%
dplyr::select(-c(
.data$peptide_intensity_mean,
.data$replicate_sd,
.data$n,
.data$n_change_peptide,
.data$effect,
.data$effect_total,
.data$b,
.data$c,
.data$offset
))
}
proteins_replicates_change_missing <- proteins_replicates_change %>%
dplyr::mutate(dropout_probability = stats::pnorm(.data$peptide_intensity,
mean = dropout_curve_inflection,
sd = -dropout_curve_sd,
lower.tail = FALSE
)) %>%
dplyr::ungroup() %>%
dplyr::mutate(peptide_intensity_missing = ifelse(stats::runif(dplyr::n()) > .data$dropout_probability,
.data$peptide_intensity,
NA
)) %>%
dplyr::select(-.data$dropout_probability) %>%
dplyr::group_by(.data$peptide) %>%
dplyr::mutate(isna = sum(!is.na(.data$peptide_intensity_missing))) %>%
dplyr::filter(.data$isna > 0) %>%
dplyr::select(-.data$isna) %>%
dplyr::ungroup()
if (additional_metadata == FALSE) {
return(proteins_replicates_change_missing)
}
if (additional_metadata == TRUE) {
coverage_sampled <- stats::rgamma(nrow(proteins_replicates_change_missing) * 2, shape = 1.2, rate = 0.05)
coverage_sampled <- coverage_sampled[coverage_sampled <= 100]
coverage_data <- proteins_replicates_change_missing %>%
dplyr::mutate(coverage = coverage_sampled[1:dplyr::n()]) %>%
dplyr::group_by(.data$protein) %>%
dplyr::mutate(coverage = rep(.data$coverage[1], dplyr::n())) %>%
dplyr::mutate(coverage_peptide = .data$coverage / dplyr::n_distinct(.data$peptide)) %>%
dplyr::group_by(.data$sample, .data$protein) %>%
dplyr::mutate(coverage = sum(!is.na(.data$peptide_intensity_missing)) * .data$coverage_peptide) %>%
dplyr::select(-.data$coverage_peptide) %>%
dplyr::ungroup()
missed_cleavage_sampled <- stats::rpois(nrow(proteins_replicates_change_missing) * 2, 0.28)
missed_cleavage_sampled <- missed_cleavage_sampled[missed_cleavage_sampled < 3]
missed_cleavages_data <- coverage_data %>%
dplyr::mutate(n_missed_cleavage = missed_cleavage_sampled[1:dplyr::n()]) %>%
dplyr::group_by(.data$peptide) %>%
dplyr::mutate(n_missed_cleavage = rep(.data$n_missed_cleavage[1], dplyr::n())) %>%
dplyr::ungroup()
charge_sampled <- round(stats::rgamma(nrow(proteins_replicates_change_missing) * 2,
shape = 13.06,
rate = 5.63
))
charge_sampled <- charge_sampled[charge_sampled > 0 & charge_sampled < 7]
charge_data <- missed_cleavages_data %>%
dplyr::mutate(charge = charge_sampled[1:dplyr::n()]) %>%
dplyr::group_by(.data$peptide) %>%
dplyr::mutate(charge = rep(.data$charge[1], dplyr::n())) %>%
dplyr::ungroup()
peptide_types <- c(rep("fully-tryptic", 11), rep("semi-tryptic", 8), rep("non-tryptic", 1))
peptide_type_data <- charge_data %>%
dplyr::mutate(pep_type = sample(peptide_types, size = dplyr::n(), replace = TRUE)) %>%
dplyr::group_by(.data$peptide) %>%
dplyr::mutate(pep_type = rep(.data$pep_type[1], dplyr::n())) %>%
dplyr::ungroup()
peak_width_sampled <- stats::rgamma(nrow(proteins_replicates_change_missing),
shape = 10.4,
rate = 36.21
)
peak_width_data <- peptide_type_data %>%
dplyr::mutate(peak_width = peak_width_sampled) %>%
dplyr::mutate(retention_time = stats::runif(n = dplyr::n(), min = 0, max = 120)) %>%
dplyr::group_by(.data$peptide) %>%
dplyr::mutate(peak_width = rep(.data$peak_width[1], dplyr::n())) %>%
dplyr::mutate(retention_time = rep(.data$retention_time[1], dplyr::n())) %>%
dplyr::ungroup()
peak_width_data
}
} |
options(width=80)
options(continue=' ')
library(integIRTy)
data(OV)
ls()
controlList <- list(Expr_N, Methy_N, CN_N)
tumorList <- list(Expr_T, Methy_T, CN_T)
testObject <- function(object) {
exists(as.character(substitute(object)))
}
if(!testObject(runFromRaw)) {
runFromRaw <- intIRTeasyRunFromRaw(platforms=tumorList,
platformsCtr=controlList,
assayType=c("Expr", "Methy", "CN"),
permutationMethod="gene sampling")
}
class(runFromRaw)
attributes(runFromRaw)
panel.hist <- function(x, ...) {
usr <- par("usr"); on.exit(par(usr))
par(usr = c(usr[1:2], 0, 1.5) )
h <- hist(x, breaks=50, plot = FALSE)
breaks <- h$breaks; nB <- length(breaks)
y <- h$counts; y <- y/max(y)
rect(breaks[-nB], 0, breaks[-1], y, col="cyan", ...)
}
panel.cor <- function(x, y, digits=2, prefix="", cex.cor) {
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r <- abs(cor(x, y, use='complete.obs'))
txt <- format(c(r, 0.123456789), digits=digits)[1]
txt <- paste(prefix, txt, sep="")
if(missing(cex.cor)) cex <- 0.6/strwidth(txt)
text(0.5, 0.5, txt, cex = cex)
}
panel.smooth <- function(...){
par(new=TRUE);
smoothScatter(...)
abline(0, 1, col=2, lty=2)
}
runFromRaw_ScoreMat <- runFromRaw$estimatedScoreMat
pairs(runFromRaw_ScoreMat, lower.panel=panel.cor, upper.panel=panel.smooth,
labels=c('Expression', 'Methylation', 'Copy \n Number', 'Integrated'),
cex.labels=1.2, gap=1.7)
if(!testObject(binDat_CN)){
binDat_expr <- dichotomize(Expr_T, Expr_N, assayType='Expr')
binDat_methy <- dichotomize(Methy_T, Methy_N, assayType='Methy')
binDat_CN <- dichotomize(CN_T, CN_N, assayType='CN')
}
if(!testObject(fit2PL_CN)){
fit2PL_Expr <- fitOnSinglePlat(binDat_expr, model=3)
fit2PL_Methy <- fitOnSinglePlat(binDat_methy, model=3)
fit2PL_CN <- fitOnSinglePlat(binDat_CN, model=3)
}
dffclt_expr <- coef(fit2PL_Expr$fit)[, 'Dffclt']
dscrmn_expr <- coef(fit2PL_Expr$fit)[, 'Dscrmn']
dffclt_methy <- coef(fit2PL_Methy$fit)[, 'Dffclt']
dscrmn_methy <- coef(fit2PL_Methy$fit)[, 'Dscrmn']
dffclt_CN <- coef(fit2PL_CN$fit)[, 'Dffclt']
dscrmn_CN <- coef(fit2PL_CN$fit)[, 'Dscrmn']
if(!testObject(score_expr)){
score_expr <- computeAbility(binDat_expr, dscrmn=dscrmn_expr,
dffclt=dffclt_expr)
score_methy <- computeAbility(binDat_methy, dscrmn=dscrmn_methy,
dffclt=dffclt_methy)
score_CN <- computeAbility(binDat_CN, dscrmn=dscrmn_CN,
dffclt=dffclt_CN)
}
if(!testObject(score_integrated)){
score_integrated <- computeAbility(respMat=cbind(binDat_expr,
binDat_methy, binDat_CN),
dscrmn=c(dscrmn_expr, dscrmn_methy, dscrmn_CN),
dffclt=c(dffclt_expr, dffclt_methy, dffclt_CN))
}
all(score_integrated==runFromRaw_ScoreMat[, 4])
getwd()
sessionInfo() |
matrix_conversion <- function(data) {
if(is(data,"matrix")){
return(data)
}else if(is(data,"data.frame")){
data <- as.matrix(data)
return(data)
}else if(is(data,"ts")){
return(data)
}else if(is(data,"xts")){
return(data)
}else if(is(data,"zoo")){
return(data)
}else{
stop("Cannot convert input data to class 'matrix'")
}
} |
r2Transformer.default<-function(eta,mat)
{
aa=(mat^(1/eta)/(1/eta))
res=getmm2sum(aa)
return(res)
}
r2Transformer=function(mat, low=0.0001, upp=1000)
{
res.eta=optimize(r2Transformer.default, mat=mat,lower=low, upper=upp)
mat2=mat^(1/res.eta$minimum)/(1/res.eta$minimum)
rownames(mat2)=rownames(mat)
colnames(mat2) = colnames(mat)
res=list(res.eta=res.eta, eta=res.eta$minimum, mat2=mat2)
invisible(res)
} |
test_that("auto_fselector function works", {
afs = auto_fselector(method = "random_search", learner = lrn("classif.rpart"), resampling = rsmp ("holdout"),
measure = msr("classif.ce"), term_evals = 50, batch_size = 10)
expect_class(afs, "AutoFSelector")
expect_class(afs$instance_args$terminator, "TerminatorEvals")
afs = auto_fselector(method = "random_search", learner = lrn("classif.rpart"), resampling = rsmp ("holdout"),
measure = msr("classif.ce"), term_time = 50, batch_size = 10)
expect_class(afs, "AutoFSelector")
expect_class(afs$instance_args$terminator, "TerminatorRunTime")
afs = auto_fselector(method = "random_search", learner = lrn("classif.rpart"), resampling = rsmp ("holdout"),
measure = msr("classif.ce"), term_evals = 10, term_time = 50, batch_size = 10)
expect_class(afs, "AutoFSelector")
expect_class(afs$instance_args$terminator, "TerminatorCombo")
}) |
convert_legacy <- function(x) {
UseMethod("convert_legacy", x)
}
convert_legacy.vp <- function(x) {
assert_that(inherits(x, "vp"))
names(x$data) <- sub("HGHT", "height", names(x$data))
x
}
convert_legacy.vpts <- function(x) {
assert_that(inherits(x, "vpts"))
names(x) <- sub("heights", "height", names(x))
names(x) <- sub("dates", "datetime", names(x))
x
} |
library("testthat")
library("gratia")
library("mgcv")
library("ggplot2")
test_that("draw() works with continuous by", {
plt <- draw(su_m_cont_by)
expect_doppelganger("continuous by-variable smmoth", plt)
})
test_that("draw() works with continuous by and fixed scales", {
plt <- draw(su_m_cont_by, scales = "fixed")
expect_s3_class(plt, "ggplot")
})
test_that("evaluate_smooth() works with continuous by", {
withr::local_options(lifecycle_verbosity = "quiet")
sm <- evaluate_smooth(su_m_cont_by, "s(x2)")
expect_s3_class(sm, "evaluated_1d_smooth")
})
test_that("is_by_smooth() is TRUE with continuous by", {
expect_true(is_by_smooth(su_m_cont_by[["smooth"]][[1]]))
})
test_that("is_factor_by_smooth() is FALSE with continuous by", {
expect_false(is_factor_by_smooth(su_m_cont_by[["smooth"]][[1]]))
})
test_that("is_continuous_by_smooth() is TRUE with continuous by", {
expect_true(is_continuous_by_smooth(su_m_cont_by[["smooth"]][[1]]))
})
test_that("get_by_smooth works", {
sm <- get_by_smooth(su_m_factor_by, "s(x2)", level = "1")
expect_s3_class(sm, "mgcv.smooth")
expect_equal(sm, su_m_factor_by[["smooth"]][[1L]])
sm <- get_by_smooth(su_m_factor_by_gamm, "s(x2)", level = "1")
expect_s3_class(sm, "mgcv.smooth")
expect_equal(sm, su_m_factor_by_gamm[["gam"]][["smooth"]][[1L]])
expect_error(get_by_smooth(su_m_factor_by, "s(x4)", level = "1"),
"The requested smooth 's(x4)' is not a by smooth.",
fixed = TRUE)
expect_error(get_by_smooth(su_m_factor_by, "s(x2)"),
"No value provided for argument 'level':", fixed = TRUE)
expect_error(get_by_smooth(su_m_factor_by, "s(x2)", level = "4"),
"Invalid 'level' for smooth 's(x2)'.",
fixed = TRUE)
})
test_that("draw.gam works with select and parametric = TRUE", {
plt <- draw(su_m_factor_by, select = 's(x2):fac1', parametric = TRUE)
expect_doppelganger("draw.gam-user-select-and-parametric-true",
plt)
}) |
est_pwmcov <- function(x, order = 0:3, distr = NULL, distr.trim = c(0, 0)) {
if (inherits(x, c("PWMs", "TLMoments", "parameters", "quantiles")))
stop("est_pwmcov is only for data vectors or matrices. ")
if (is.double(order)) order <- as.integer(order)
if (!is.integer(order)) stop("order has to be integer type!")
if (!is.null(distr) && distr != "gev")
stop("distr has to be NULL (nonparametric) or \"gev\"")
if (!is.null(distr) && (!are.integer.like(distr.trim[1], distr.trim[2]) | length(distr.trim) != 2))
stop("If distr is not NULL, distr.trim has to be a integer-like vector of length 2. ")
UseMethod("est_pwmcov")
}
est_pwmcov.numeric <- function(x, order = 0:3, distr = NULL, distr.trim = c(0, 0)) {
if (is.null(distr)) {
r <- stats::cov(pseudo(x, order))
} else {
p <- parameters(TLMoments(x, leftrim = distr.trim[1], rightrim = distr.trim[2], na.rm = TRUE), distr)
if (p["shape"] >= .5) {
warning("estimated shape parameter is too high. ")
r <- matrix(Inf, nrow = length(order), ncol = length(order))
} else {
r <- parametricPWMCov(distr, order, scale = p["scale"], shape = p["shape"])
}
}
rownames(r) <- colnames(r) <- buildNames("beta", order)
out <- r / sum(!is.na(x))
attr(out, "distribution") <- distr
out
}
est_pwmcov.matrix <- function(x, order = 0:3, distr = NULL, distr.trim = c(0, 0)) {
J <- ncol(x)
pseudos <- lapply(1L:J, function(i) pseudo(x[, i], order))
sigma <- stats::cov(do.call("cbind", pseudos), use = "pairwise.complete.obs")
rownames(sigma) <- colnames(sigma) <- buildNames("beta", order, 1:J)
if (!is.null(distr)) {
xl <- lapply(1:ncol(x), function(i) x[, i])
p <- parameters(TLMoments(xl, leftrim = distr.trim[1], rightrim = distr.trim[2], na.rm = TRUE), distr)
r <- lapply(p, function(p) {
parametricPWMCov(distr, order, scale = p["scale"], shape = p["shape"])
})
sigma <- blockdiag_list(r, sigma)
}
rs <- apply(x, 2, function(y) sum(!is.na(y))/length(y))
vorf <- do.call(rbind, lapply(1:J, function(i) {
do.call(cbind, lapply(1:J, function(j) {
matrix(min(c(rs[i], rs[j]))/(rs[i] * rs[j]), nrow = length(order), ncol = length(order))
}))
}))
out <- vorf*sigma / max(apply(x, 2, function(y) sum(!is.na(y))))
attr(out, "distribution") <- distr
out
} |
massageExamples <-
function(pkg, files, outFile = stdout(), use_gct = FALSE,
addTiming = FALSE, ..., commentDonttest = TRUE)
{
if(dir.exists(files[1L])) {
old <- Sys.getlocale("LC_COLLATE")
Sys.setlocale("LC_COLLATE", "C")
files <- sort(Sys.glob(file.path(files, "*.R")))
Sys.setlocale("LC_COLLATE", old)
}
if(is.character(outFile)) {
out <- file(outFile, "wt")
on.exit(close(out))
cntFile <- paste0(outFile, "-cnt")
} else {
out <- outFile
cntFile <- NULL
}
count <- 0L
lines <- c(paste0('pkgname <- "', pkg, '"'),
'source(file.path(R.home("share"), "R", "examples-header.R"))',
if (use_gct) {
gct_n <- as.integer(Sys.getenv("_R_CHECK_GCT_N_", "0"))
if(!is.na(gct_n) && gct_n > 0L)
sprintf("gctorture2(%s)", gct_n)
else "gctorture(TRUE)"
},
"options(warn = 1)")
cat(lines, sep = "\n", file = out)
if(.Platform$OS.type == "windows")
cat("options(pager = \"console\")\n", file = out)
if(addTiming) {
cat("base::assign(\".ExTimings\", \"", pkg,
"-Ex.timings\", pos = 'CheckExEnv')\n", sep="", file = out)
cat("base::cat(\"name\\tuser\\tsystem\\telapsed\\n\", file=base::get(\".ExTimings\", pos = 'CheckExEnv'))\n", file = out)
cat("base::assign(\".format_ptime\",",
"function(x) {",
" if(!is.na(x[4L])) x[1L] <- x[1L] + x[4L]",
" if(!is.na(x[5L])) x[2L] <- x[2L] + x[5L]",
" options(OutDec = '.')",
" format(x[1L:3L], digits = 7L)",
"},",
"pos = 'CheckExEnv')\n", sep = "\n", file = out)
cat("
}
if(pkg == "tcltk") {
if(capabilities("tcltk")) cat("require('tcltk')\n\n", file = out)
else cat("q()\n\n", file = out)
} else if(pkg != "base")
cat("library('", pkg, "')\n\n", sep = "", file = out)
cat("base::assign(\".oldSearch\", base::search(), pos = 'CheckExEnv')\n", file = out)
cat("base::assign(\".old_wd\", base::getwd(), pos = 'CheckExEnv')\n",
file = out)
for(file in files) {
nm <- sub("\\.R$", "", basename(file))
nm <- gsub("[^- .a-zA-Z0-9_]", ".", nm, perl = TRUE, useBytes = TRUE)
if (pkg == "grDevices" && nm == "postscript") next
if (pkg == "graphics" && nm == "text") next
if(!file.exists(file))
stop("file ", file, " cannot be opened", domain = NA)
lines <- readLines(file)
have_examples <- any(grepl("_ Examples _|
lines, perl = TRUE, useBytes = TRUE))
com <- grep("^
lines1 <- if(length(com)) lines[-com] else lines
have_par <- any(grepl("[^a-zA-Z0-9.]par\\(|^par\\(",
lines1, perl = TRUE, useBytes = TRUE))
have_contrasts <- any(grepl("options\\(contrasts",
lines1, perl = TRUE, useBytes = TRUE))
if(have_examples)
cat("cleanEx()\nnameEx(\"", nm, "\")\n", sep = "", file = out)
cat("
cat("flush(stderr()); flush(stdout())\n\n", file = out)
if(addTiming)
cat("base::assign(\".ptime\", proc.time(), pos = \"CheckExEnv\")\n",
file = out)
if (commentDonttest) {
dont_test <- FALSE
for (line in lines) {
if(any(grepl("^[[:space:]]*
perl = TRUE, useBytes = TRUE))) {
dont_test <- TRUE
count <- count + 1L
}
if(!dont_test) cat(line, "\n", sep = "", file = out)
if(any(grepl("^[[:space:]]*
perl = TRUE, useBytes = TRUE)))
dont_test <- FALSE
}
} else
for (line in lines) cat(line, "\n", sep = "", file = out)
if(addTiming) {
cat("base::assign(\".dptime\", (proc.time() - get(\".ptime\", pos = \"CheckExEnv\")), pos = \"CheckExEnv\")\n", file = out)
cat("base::cat(\"", nm, "\", base::get(\".format_ptime\", pos = 'CheckExEnv')(get(\".dptime\", pos = \"CheckExEnv\")), \"\\n\", file=base::get(\".ExTimings\", pos = 'CheckExEnv'), append=TRUE, sep=\"\\t\")\n", sep = "", file = out)
}
if(have_par)
cat("graphics::par(get(\"par.postscript\", pos = 'CheckExEnv'))\n", file = out)
if(have_contrasts)
cat("base::options(contrasts = c(unordered = \"contr.treatment\",",
"ordered = \"contr.poly\"))\n", sep="", file = out)
}
cat(readLines(file.path(R.home("share"), "R", "examples-footer.R")),
sep = "\n", file = out)
if(count && !is.null(cntFile)) writeLines(as.character(count), cntFile)
}
Rdiff <- function(from, to, useDiff = FALSE, forEx = FALSE,
nullPointers = TRUE, Log = FALSE)
{
clean <- function(txt)
{
if(!length(txt)) return(txt)
if(length(top <- grep("^(R version|R : Copyright|R Under development)",
txt, perl = TRUE, useBytes = TRUE)) &&
length(bot <- grep("quit R.$", txt, perl = TRUE, useBytes = TRUE)))
txt <- txt[-(top[1L]:bot[1L])]
ll <- grep("</HEADER>", txt, fixed = TRUE, useBytes = TRUE)
if(length(ll)) txt <- txt[-seq_len(max(ll))]
ll <- grep("<FOOTER>", txt, fixed = TRUE, useBytes = TRUE)
if(length(ll)) txt <- txt[seq_len(max(ll) - 1L)]
if(forEx) {
ll <- grep('".old_wd"', txt, fixed = TRUE, useBytes = TRUE)
if(length(ll)) txt <- txt[-ll]
}
nl <- length(txt)
if(nl > 3L && startsWith(txt[nl-2L], "> proc.time()"))
txt <- txt[1:(nl-3L)]
txt <- txt[(cumsum(txt == ">
cumsum(txt == ">
if (nullPointers) {
txt <- gsub("<(environment|bytecode|pointer|promise): [x[:xdigit:]]+>", "<\\1: 0>", txt)
txt <- sub("<hashtable.*>", "<hashtable output>", txt)
}
txt <- .canonicalize_quotes(txt)
if(.Platform$OS.type == "windows") {
txt <- gsub(paste0("(",rawToChar(as.raw(0x91)),"|",rawToChar(as.raw(0x92)),")"),
"'", txt, perl = TRUE, useBytes = TRUE)
txt <- gsub(paste0("(",rawToChar(as.raw(0x93)),"|",rawToChar(as.raw(0x94)),")"),
'"', txt, perl = TRUE, useBytes = TRUE)
}
txt <- txt[!grepl('options(pager = "console")', txt,
fixed = TRUE, useBytes = TRUE)]
pat <- '(^Time |^Loading required package|^Package [A-Za-z][A-Za-z0-9]+ loaded|^<(environment|promise|pointer|bytecode):|^/CreationDate |^/ModDate |^/Producer |^End.Don\'t show)'
txt[!grepl(pat, txt, perl = TRUE, useBytes = TRUE)]
}
clean2 <- function(txt)
{
eoh <- grep("^> options\\(warn = 1\\)$", txt)
if(length(eoh)) txt[-(1L:eoh[1L])] else txt
}
left <- clean(readLines(from))
right <- clean(readLines(to))
if (forEx) {
left <- clean2(left)
left <- filtergrep("[.](format_|)ptime", left, useBytes = TRUE)
right <- clean2(right)
}
if (!useDiff && (length(left) == length(right))) {
bleft <- gsub("[[:space:]]*$", "", left)
bright <- gsub("[[:space:]]*$", "", right)
bleft <- gsub("[[:space:]]+", " ", bleft)
bright <- gsub("[[:space:]]+", " ", bright)
if(all(bleft == bright))
return(if(Log) list(status = 0L, out = character()) else 0L)
cat("\n")
diff <- bleft != bright
for(i in which(diff))
cat(i,"c", i, "\n< ", left[i], "\n", "---\n> ", right[i], "\n",
sep = "")
if (Log) {
i <- which(diff)
out <- paste0(i,"c", i, "\n< ", left[i], "\n", "---\n> ", right[i])
list(status = 1L, out = out)
} else 1L
} else {
out <- character()
if(!useDiff) {
cat("\nfiles differ in number of lines:\n")
out <- "files differ in number of lines"
}
a <- tempfile("Rdiffa")
writeLines(left, a)
b <- tempfile("Rdiffb")
writeLines(right, b)
if (Log) {
tf <- tempfile()
status <- system2("diff", c("-bw", shQuote(a), shQuote(b)),
stdout = tf, stderr = tf)
list(status = status, out = c(out, readLines(tf)))
} else system(paste("diff -bw", shQuote(a), shQuote(b)))
}
}
testInstalledPackages <-
function(outDir = ".", errorsAreFatal = TRUE,
scope = c("both", "base", "recommended"),
types = c("examples", "tests", "vignettes"),
srcdir = NULL, Ropts = "", ...)
{
ow <- options(warn = 1)
on.exit(ow)
scope <- match.arg(scope)
status <- 0L
pkgs <- character()
known_packages <- .get_standard_package_names()
if (scope %in% c("both", "base"))
pkgs <- known_packages$base
if (scope %in% c("both", "recommended"))
pkgs <- c(pkgs, known_packages$recommended)
mc.cores <- as.integer(Sys.getenv("TEST_MC_CORES", "1"))
if (.Platform$OS.type != "windows" &&
!is.na(mc.cores) && mc.cores > 1L) {
do_one <- function(pkg) {
if(is.null(srcdir) && pkg %in% known_packages$base)
srcdir <- R.home("tests/Examples")
testInstalledPackage(pkg, .Library, outDir, types, srcdir, Ropts, ...)
}
res <- parallel::mclapply(pkgs, do_one, mc.cores = mc.cores,
mc.preschedule = FALSE)
res <- unlist(res) != 0L
if (any(res)) {
for(i in which(res))
warning(gettextf("testing '%s' failed", pkgs[i]),
domain = NA, call. = FALSE, immediate. = TRUE)
if (errorsAreFatal)
stop(sprintf(ngettext(sum(res), "%d of the package tests failed",
"%d of the package tests failed",
domain = "R-tools"), sum(res)),
domain = NA, call. = FALSE)
}
} else {
for (pkg in pkgs) {
if(is.null(srcdir) && pkg %in% known_packages$base)
srcdir <- R.home("tests/Examples")
res <- testInstalledPackage(pkg, .Library, outDir, types, srcdir, Ropts, ...)
if (res) {
status <- 1L
msg <- gettextf("testing '%s' failed", pkg)
if (errorsAreFatal) stop(msg, domain = NA, call. = FALSE)
else warning(msg, domain = NA, call. = FALSE, immediate. = TRUE)
}
}
}
invisible(status)
}
testInstalledPackage <-
function(pkg, lib.loc = NULL, outDir = ".",
types = c("examples", "tests", "vignettes"),
srcdir = NULL, Ropts = "", ...)
{
types <- match.arg(types, c("examples", "tests", "vignettes"), several.ok=TRUE)
pkgdir <- find.package(pkg, lib.loc)
owd <- setwd(outDir)
on.exit(setwd(owd))
strict <- as.logical(Sys.getenv("R_STRICT_PACKAGE_CHECK", "FALSE"))
if ("examples" %in% types) {
message(gettextf("Testing examples for package %s", sQuote(pkg)),
domain = NA)
Rfile <- .createExdotR(pkg, pkgdir, silent = TRUE, ...)
if (length(Rfile)) {
outfile <- paste0(pkg, "-Ex.Rout")
failfile <- paste0(outfile, ".fail")
savefile <- paste0(outfile, ".prev")
if (file.exists(outfile)) file.rename(outfile, savefile)
unlink(failfile)
cmd <- paste(shQuote(file.path(R.home("bin"), "R")),
"CMD BATCH --vanilla --no-timing", Ropts,
shQuote(Rfile), shQuote(failfile))
if (.Platform$OS.type == "windows") Sys.setenv(R_LIBS="")
else cmd <- paste("R_LIBS=", cmd)
res <- system(cmd)
if (res) return(invisible(1L)) else file.rename(failfile, outfile)
savefile <- paste0(outfile, ".save")
if (!is.null(srcdir)) savefile <- file.path(srcdir, savefile)
else {
tfile <- file.path(pkgdir, "tests", "Examples" , savefile)
if(!file.exists(savefile) && file.exists(tfile))
savefile <- tfile
}
if (file.exists(savefile)) {
if (file.exists(savefile)) {
message(gettextf(" comparing %s to %s ...",
sQuote(outfile), sQuote(basename(savefile))),
appendLF = FALSE, domain = NA)
cmd <-
sprintf("invisible(tools::Rdiff('%s','%s',TRUE,TRUE))",
outfile, savefile)
out <- R_runR(cmd, "--vanilla --no-echo")
if(length(out)) {
if(strict)
message(" ERROR")
else
message(" NOTE")
writeLines(paste0(" ", out))
if(strict)
stop(" ",
"results differ from reference results")
} else {
message(" OK")
}
}
} else {
prevfile <- paste0(outfile, ".prev")
if (file.exists(prevfile)) {
message(gettextf(" comparing %s to %s ...",
sQuote(outfile), sQuote(basename(prevfile))),
appendLF = FALSE, domain = NA)
cmd <-
sprintf("invisible(tools::Rdiff('%s','%s',TRUE,TRUE))",
outfile, prevfile)
out <- R_runR(cmd, "--vanilla --no-echo")
if(length(out)) {
message(" NOTE")
writeLines(paste0(" ", out))
} else {
message(" OK")
}
}
}
} else
warning(gettextf("no examples found for package %s", sQuote(pkg)),
call. = FALSE, domain = NA)
}
if ("tests" %in% types && dir.exists(d <- file.path(pkgdir, "tests"))) {
this <- paste0(pkg, "-tests")
unlink(this, recursive = TRUE)
dir.create(this)
file.copy(Sys.glob(file.path(d, "*")), this, recursive = TRUE)
setwd(this)
message(gettextf("Running specific tests for package %s",
sQuote(pkg)), domain = NA)
Rfiles <- dir(".", pattern="\\.[rR]$")
for(f in Rfiles) {
message(gettextf(" Running %s", sQuote(f)), domain = NA)
outfile <- sub("rout$", "Rout", paste0(f, "out"))
cmd <- paste(shQuote(file.path(R.home("bin"), "R")),
"CMD BATCH --vanilla --no-timing", Ropts,
shQuote(f), shQuote(outfile))
cmd <- if (.Platform$OS.type == "windows") paste(cmd, "LANGUAGE=C")
else paste("LANGUAGE=C", cmd)
res <- system(cmd)
if (res) {
file.rename(outfile, paste0(outfile, ".fail"))
return(invisible(1L))
}
savefile <- paste0(outfile, ".save")
if (file.exists(savefile)) {
message(gettextf(" comparing %s to %s ...",
sQuote(outfile), sQuote(savefile)),
appendLF = FALSE, domain = NA)
res <- Rdiff(outfile, savefile)
if (!res) message(" OK")
}
}
setwd(owd)
}
if ("vignettes" %in% types && dir.exists(file.path(pkgdir, "doc"))) {
message(gettextf("Running vignettes for package %s", sQuote(pkg)),
domain = NA)
writeLines(format(checkVignettes(pkg, lib.loc = lib.loc,
latex = FALSE, weave = TRUE)))
}
invisible(0L)
}
.runPackageTestsR <- function(...)
{
cat("\n");
status <- .runPackageTests(...)
q("no", status = status)
}
.runPackageTests <-
function(use_gct = FALSE, use_valgrind = FALSE, Log = NULL,
stop_on_error = TRUE, ...)
{
tlim <- Sys.getenv("_R_CHECK_ONE_TEST_ELAPSED_TIMEOUT_",
Sys.getenv("_R_CHECK_TESTS_ELAPSED_TIMEOUT_",
Sys.getenv("_R_CHECK_ELAPSED_TIMEOUT_")))
tlim <- get_timeout(tlim)
if (!is.null(Log)) Log <- file(Log, "wt")
WINDOWS <- .Platform$OS.type == "windows"
td0 <- as.numeric(Sys.getenv("_R_CHECK_TIMINGS_"))
theta <-
as.numeric(Sys.getenv("_R_CHECK_TEST_TIMING_CPU_TO_ELAPSED_THRESHOLD_",
NA_character_))
if (is.na(td0)) td0 <- Inf
print_time <- function(t1, t2, Log)
{
td <- t2 - t1
if(td[3L] < td0) td2 <- ""
else {
td2 <- if (td[3L] > 600) {
td <- td/60
if(WINDOWS) sprintf(" [%dm]", round(td[3L]))
else sprintf(" [%dm/%dm]", round(sum(td[-3L])), round(td[3L]))
} else {
if(WINDOWS) sprintf(" [%ds]", round(td[3L]))
else sprintf(" [%ds/%ds]", round(sum(td[-3L])), round(td[3L]))
}
}
message(td2, domain = NA)
if (!is.null(Log)) cat(td2, "\n", sep = "", file = Log)
}
runone <- function(f)
{
message(gettextf(" Running %s", sQuote(f)),
appendLF = FALSE, domain = NA)
if(!is.null(Log))
cat(" Running ", sQuote(f), sep = "", file = Log)
outfile <- sub("rout$", "Rout", paste0(f, "out"))
cmd <- paste(shQuote(file.path(R.home("bin"), "R")),
"CMD BATCH --vanilla",
if(use_valgrind) "--debugger=valgrind",
shQuote(f), shQuote(outfile))
if (WINDOWS) {
Sys.setenv(LANGUAGE="C")
Sys.setenv(R_TESTS="startup.Rs")
} else
cmd <- paste("LANGUAGE=C", "R_TESTS=startup.Rs", cmd)
t1 <- proc.time()
res <- system(cmd, timeout = tlim)
t2 <- proc.time()
print_time(t1, t2, Log)
if (!WINDOWS && !is.na(theta)) {
td <- t2 - t1
cpu <- sum(td[-3L])
if(cpu >= pmax(theta * td[3L], 1)) {
ratio <- round(cpu/td[3L], 1L)
msg <- sprintf("Running R code in %s had CPU time %g times elapsed time\n",
sQuote(f), ratio)
cat(msg)
if (!is.null(Log)) cat(msg, file = Log)
}
}
if (res) {
if(identical(res, 124L)) report_timeout(tlim)
file.rename(outfile, paste0(outfile, ".fail"))
return(1L)
}
savefile <- paste0(outfile, ".save")
if (file.exists(savefile)) {
message(gettextf(" Comparing %s to %s ...",
sQuote(outfile), sQuote(savefile)),
appendLF = FALSE, domain = NA)
if(!is.null(Log))
cat(" Comparing ", sQuote(outfile), " to ",
sQuote(savefile), " ...", sep = "", file = Log)
if(!is.null(Log)) {
ans <- Rdiff(outfile, savefile, TRUE, Log = TRUE)
writeLines(ans$out)
writeLines(ans$out, Log)
res <- ans$status
} else res <- Rdiff(outfile, savefile, TRUE)
if (!res) {
message(" OK")
if(!is.null(Log)) cat(" OK\n", file = Log)
}
}
0L
}
file.copy(file.path(R.home("share"), "R", "tests-startup.R"), "startup.Rs")
if (use_gct) cat("gctorture(TRUE)" , file = "startup.Rs", append = TRUE)
nfail <- 0L
Rinfiles <- dir(".", pattern="\\.Rin$")
for(f in Rinfiles) {
Rfile <- sub("\\.Rin$", ".R", f)
message(" Creating ", sQuote(Rfile), domain = NA)
if (!is.null(Log))
cat(" Creating ", sQuote(Rfile), "\n", sep = "", file = Log)
cmd <- paste(shQuote(file.path(R.home("bin"), "R")),
"CMD BATCH --no-timing --vanilla --no-echo", f)
if (system(cmd)) {
warning("creation of ", sQuote(Rfile), " failed", domain = NA)
if (!is.null(Log))
cat("Warning: creation of ", sQuote(Rfile), " failed\n",
sep = "", file = Log)
} else if (file.exists(Rfile)) nfail <- nfail + runone(Rfile)
if (nfail > 0) return(nfail)
}
Rfiles <- dir(".", pattern="\\.[rR]$")
for(f in Rfiles) {
nfail <- nfail + runone(f)
if (nfail > 0 && stop_on_error) return(nfail)
}
if (!is.null(Log)) close(Log)
return(nfail)
}
.createExdotR <-
function(pkg, pkgdir, silent = FALSE, use_gct = FALSE, addTiming = FALSE,
..., commentDontrun = TRUE, commentDonttest = TRUE)
{
Rfile <- paste0(pkg, "-Ex.R")
db <- Rd_db(basename(pkgdir), lib.loc = dirname(pkgdir))
if (!length(db)) {
message("no parsed files found")
return(invisible(NULL))
}
if (!silent) message(" Extracting from parsed Rd's ",
appendLF = FALSE, domain = NA)
files <- names(db)
if (pkg == "grDevices")
files <- files[!grepl("^(unix|windows)/", files)]
filedir <- tempfile()
dir.create(filedir)
on.exit(unlink(filedir, recursive = TRUE))
cnt <- 0L
for(f in files) {
nm <- sub("\\.[Rr]d$", "", basename(f))
Rd2ex(db[[f]],
file.path(filedir, paste0(nm, ".R")),
defines = NULL, commentDontrun = commentDontrun,
commentDonttest = commentDonttest)
cnt <- cnt + 1L
if(!silent && cnt %% 10L == 0L)
message(".", appendLF = FALSE, domain = NA)
}
if (!silent) message()
nof <- length(Sys.glob(file.path(filedir, "*.R")))
if(!nof) return(invisible(NULL))
massageExamples(pkg, filedir, Rfile, use_gct, addTiming,
commentDonttest = commentDonttest, ...)
invisible(Rfile)
}
testInstalledBasic <- function(scope = c("basic", "devel", "both", "internet"))
{
scope <- match.arg(scope)
oLCcoll <- Sys.getlocale("LC_COLLATE") ; on.exit(Sys.setlocale("LC_COLLATE", oLCcoll))
Sys.setlocale("LC_COLLATE", "C")
tests1 <- c("eval-etc", "simple-true", "arith-true", "lm-tests",
"ok-errors", "method-dispatch", "array-subset",
"p-r-random-tests", "d-p-q-r-tst-2",
"any-all", "structure", "d-p-q-r-tests")
tests2 <- c("complex", "print-tests", "lapack", "datasets", "datetime",
"iec60559")
tests3 <- c("reg-tests-1a", "reg-tests-1b", "reg-tests-1c", "reg-tests-2",
"reg-tests-1d",
"reg-examples1", "reg-examples2", "reg-packages",
"p-qbeta-strict-tst",
"reg-IO", "reg-IO2", "reg-plot", "reg-S4", "reg-BLAS")
runone <- function(f, diffOK = FALSE, inC = TRUE)
{
f <- paste0(f, ".R")
if (!file.exists(f)) {
if (!file.exists(fin <- paste0(f, "in")))
stop("file ", sQuote(f), " not found", domain = NA)
message("creating ", sQuote(f), domain = NA)
cmd <- paste(shQuote(file.path(R.home("bin"), "R")),
"--vanilla --no-echo -f", fin)
if (system(cmd))
stop("creation of ", sQuote(f), " failed", domain = NA)
cat("\n", file = f, append = TRUE)
on.exit(unlink(f))
}
message(" running code in ", sQuote(f), domain = NA)
outfile <- sub("rout$", "Rout", paste0(f, "out"))
cmd <- paste(shQuote(file.path(R.home("bin"), "R")),
"CMD BATCH --vanilla --no-timing",
shQuote(f), shQuote(outfile))
extra <- paste("LANGUAGE=en", "LC_COLLATE=C",
"R_DEFAULT_PACKAGES=", "SRCDIR=.")
if (inC) extra <- paste(extra, "LC_ALL=C")
if (.Platform$OS.type == "windows") {
Sys.setenv(LANGUAGE="C")
Sys.setenv(R_DEFAULT_PACKAGES="")
Sys.setenv(LC_COLLATE="C")
Sys.setenv(SRCDIR=".")
} else cmd <- paste(extra, cmd)
res <- system(cmd)
if (res) {
file.rename(outfile, paste0(outfile, ".fail"))
message("FAILED")
return(1L)
}
savefile <- paste0(outfile, ".save")
if (file.exists(savefile)) {
message(gettextf(" comparing %s to %s ...",
sQuote(outfile), sQuote(savefile)),
appendLF = FALSE, domain = NA)
res <- Rdiff(outfile, savefile, TRUE)
if (!res) message(" OK")
else if (!diffOK) return(1L)
}
0L
}
owd <- setwd(file.path(R.home(), "tests"))
on.exit(setwd(owd), add=TRUE)
if (scope %in% c("basic", "both")) {
message("running strict specific tests", domain = NA)
for (f in tests1) if (runone(f)) return(1L)
message("running sloppy specific tests", domain = NA)
for (f in tests2) runone(f, TRUE)
message("running regression tests", domain = NA)
for (f in tests3) {
if (runone(f)) return(invisible(1L))
if (f == "reg-plot") {
message(" comparing 'reg-plot.pdf' to 'reg-plot.pdf.save' ...",
appendLF = FALSE, domain = NA)
res <- Rdiff("reg-plot.pdf", "reg-plot.pdf.save")
if(res != 0L) message("DIFFERED") else message("OK")
}
}
runone("reg-translation", inC=FALSE)
runone("reg-tests-3", TRUE)
runone("reg-examples3", TRUE)
message("running tests of plotting Latin-1", domain = NA)
message(" expect failure or some differences if not in a Latin or UTF-8 locale", domain = NA)
runone("reg-plot-latin1", TRUE, inC=FALSE)
message(" comparing 'reg-plot-latin1.pdf' to 'reg-plot-latin1.pdf.save' ...",
appendLF = FALSE, domain = NA)
res <- Rdiff("reg-plot-latin1.pdf", "reg-plot-latin1.pdf.save")
if(res != 0L) message("DIFFERED") else message("OK")
}
if (scope %in% c("devel", "both")) {
message("running tests of date-time printing\n expect platform-specific differences", domain = NA)
runone("datetime2")
message("running tests of consistency of as/is.*", domain = NA)
runone("isas-tests")
message("running tests of random deviate generation -- fails occasionally")
runone("p-r-random-tests", TRUE)
message("running tests demos from base and stats", domain = NA)
if (runone("demos")) return(invisible(1L))
if (runone("demos2")) return(invisible(1L))
message("running tests of primitives", domain = NA)
if (runone("primitives")) return(invisible(1L))
message("running regexp regression tests", domain = NA)
if (runone("utf8-regex", inC = FALSE)) return(invisible(1L))
if (runone("PCRE")) return(invisible(1L))
message("running tests of CRAN tools", domain = NA)
if (runone("CRANtools")) return(invisible(1L))
message("running tests to possibly trigger segfaults", domain = NA)
if (runone("no-segfault")) return(invisible(1L))
}
if (scope %in% "internet") {
message("running tests of Internet functions", domain = NA)
runone("internet")
message("running more Internet and socket tests", domain = NA)
runone("internet2")
runone("libcurl")
}
invisible(0L)
}
detachPackages <- function(pkgs, verbose = TRUE)
{
pkgs <- pkgs[pkgs %in% search()]
if(!length(pkgs)) return()
if(verbose){
msg <- paste("detaching", paste(sQuote(pkgs), collapse = ", "))
cat("", strwrap(msg, exdent = 2L), "", sep = "\n")
}
isPkg <- startsWith(pkgs,"package:")
for(item in pkgs[!isPkg]) {
pos <- match(item, search())
if(!is.na(pos)) .detach(pos)
}
pkgs <- pkgs[isPkg]
if(!length(pkgs)) return()
deps <- lapply(pkgs, function(x) if(exists(".Depends", x, inherits = FALSE)) get(".Depends", x) else character())
names(deps) <- pkgs
unload <- nzchar(Sys.getenv("_R_CHECK_UNLOAD_NAMESPACES_"))
exclusions <- c("grid", "tcltk")
exclusions <- paste0("package:", exclusions)
while(length(deps)) {
unl <- unlist(deps)
for(i in seq_along(deps)) {
this <- names(deps)[i]
if(.rmpkg(this) %in% unl) next else break
}
try(detach(this, character.only = TRUE,
unload = unload && (this %notin% exclusions),
force = TRUE))
deps <- deps[-i]
}
}
.Rdiff <- function(no.q = FALSE)
{
options(showErrorCalls=FALSE)
Usage <- function() {
cat("Usage: R CMD Rdiff FROM-FILE TO-FILE EXITSTATUS",
"",
"Diff R output files FROM-FILE and TO-FILE discarding the R startup message,",
"where FROM-FILE equal to '-' means stdin.",
"",
"Options:",
" -h, --help print this help message and exit",
" -v, --version print version info and exit",
"",
"Report bugs at <https://bugs.R-project.org>.",
sep = "\n")
}
do_exit <-
if(no.q)
function(status = 0L) (if(status) stop else message)(
".Rdiff() exit status ", status)
else
function(status = 0L) q("no", status = status, runLast = FALSE)
args <- commandArgs(TRUE)
if (!length(args)) {
Usage()
do_exit(1L)
}
args <- paste(args, collapse=" ")
args <- strsplit(args,'nextArg', fixed = TRUE)[[1L]][-1L]
if (length(args) == 1L) {
if(args[1L] %in% c("-h", "--help")) { Usage(); do_exit(0) }
if(args[1L] %in% c("-v", "--version")) {
cat("R output diff: ",
R.version[["major"]], ".", R.version[["minor"]],
" (r", R.version[["svn rev"]], ")\n", sep = "")
cat("",
.R_copyright_msg(2000),
"This is free software; see the GNU General Public License version 2",
"or later for copying conditions. There is NO warranty.",
sep = "\n")
do_exit(0)
}
Usage()
do_exit(1L)
}
if (length(args) == 0L) {
Usage()
do_exit(1L)
}
exitstatus <- as.integer(args[3L])
if(is.na(exitstatus))
exitstatus <- 0L
left <- args[1L]
if(left == "-") left <- "stdin"
status <- Rdiff(left, args[2L], useDiff = TRUE)
if(status) status <- exitstatus
do_exit(status)
} |
test_that("check_files works", {
expect_identical(check_files(character(0)), character(0))
expect_invisible(check_files(character(0)))
expect_identical(
check_files(character(0), exists = TRUE),
check_files(character(0), exists = TRUE)
)
expect_invisible(check_files(character(0), exists = TRUE))
tmp <- withr::local_tempfile()
expect_identical(check_files(tmp, exists = FALSE), check_files(tmp, exists = FALSE))
expect_invisible(check_files(tmp, exists = FALSE))
writeLines(tmp, text = "some test data")
expect_identical(check_files(tmp, exists = TRUE), check_files(tmp, exists = TRUE))
expect_invisible(check_files(tmp, exists = TRUE))
})
test_that("check_files errors", {
expect_chk_error(check_files(NA_character_))
tmp <- withr::local_tempfile()
expect_chk_error(
check_files(tmp),
"^`tmp` must specify existing files [(]'.*' can't be found[)][.]$"
)
expect_chk_error(
check_files(tempdir()),
"^`tempdir[(][)]` must specify files [(]'.*' is a directory[)][.]$"
)
expect_chk_error(
check_files(tempdir(), exists = FALSE),
"^`tempdir[(][)]` must specify files [(]'.*' is a directory[)][.]$"
)
writeLines(tmp, text = "some test data")
expect_chk_error(
check_files(tmp, exists = FALSE),
"^`tmp` must not specify existing files [(]'.*' exists[)][.]$"
)
}) |
library(dplyr, warn.conflicts = FALSE)
library(tidyr, warn.conflicts = FALSE) |
format_depend <- function(package, version, remote_provider,
verbose = FALSE) {
dep <- list(
"@type" = "SoftwareApplication",
identifier = package,
name = package
)
if (version != "*") {
dep$version <- version
}
dep$provider <- guess_provider(package, verbose)
sameAs <- get_sameAs(dep$provider, remote_provider, dep$identifier)
if (! is.null(sameAs)) {
dep$sameAs <- sameAs
}
return(dep)
}
get_sameAs <- function(provider, remote_provider, identifier) {
url_generators <- list(
"Comprehensive R Archive Network (CRAN)" = get_url_cran_package,
"BioConductor" = get_url_bioconductor_package
)
if (remote_provider != "") {
get_url_github(gsub("github::", "", remote_provider))
} else if (! is.null(provider) && provider$name %in% names(url_generators)) {
url_generators[[provider$name]](identifier)
}
}
parse_depends <- function(deps, verbose = FALSE) {
purrr::pmap(
list(deps$package, deps$version, deps$remote_provider),
format_depend,
verbose = verbose
)
}
guess_dep_id <- function(dep) {
if (dep$name == "R") {
return("https://www.r-project.org")
}
url_generators <- list(
"cran.r-project.org" = get_url_cran_package_2,
"www.bioconductor.org" = get_url_bioconductor_package_2
)
if (! is.null(dep$provider)) {
provider_url <- dep$provider$url
is_matching <- sapply(names(url_generators), grepl, x = provider_url)
if (any(is_matching)) {
url_generators[[which(is_matching)[1]]](provider_url, dep$identifier)
}
}
}
add_remote_to_dep <- function(package, remotes) {
remote_providers <- grep(paste0("/", package, "$"), remotes, value = TRUE)
if (length(remote_providers)) remote_providers else ""
}
get_sys_links <- function(pkg, description = "", verbose = FALSE) {
if (verbose) {
cli::cat_bullet("Getting sysreqs URL from sysreqs API", bullet = "continue")
}
data <- get_url_rhub("get", unique(c(
get_rhub_json_names("pkg", pkg),
get_rhub_json_names("map", utils::URLencode(description, reserved = TRUE))
)))
if (verbose) {
cli::cat_bullet("Got sysreqs URL from sysreqs API!", bullet = "tick")
}
data
}
get_rhub_json_names <- function(a, b) {
sapply(
X = jsonlite::fromJSON(get_url_rhub(a, b), simplifyVector = FALSE),
FUN = names
)
}
format_sys_req <- function(url) {
list("@type" = "SoftwareApplication", identifier = url)
}
parse_sys_reqs <- function(pkg, sys_reqs, verbose = FALSE) {
if(!pingr::is_online()) return(NULL)
urls <- get_sys_links(pkg, description = sys_reqs, verbose)
purrr::map(urls, format_sys_req)
} |
searchIPA <- function(x = NULL , search = c("feature", "xsampa")) {
if (is.null(x)) return(ipa_xsampa)
stopifnot(search[1] %in% c("feature", "xsampa"))
if (search[1] == "feature") {
idx <- str_detect(ipa_xsampa$Name, x)
} else {
idx <- str_detect(ipa_xsampa$XSAMPA, x)
}
return(ipa_xsampa[idx, ])
} |
`lines.procrustes` <-
function(x, type=c("segments", "arrows"), choices=c(1,2),
truemean = FALSE, ...)
{
type <- match.arg(type)
X <- x$X[,choices, drop=FALSE]
Y <- x$Yrot[, choices, drop=FALSE]
if (truemean) {
X <- sweep(X, 2, x$xmean[choices], "+")
Y <- sweep(Y, 2, x$xmean[choices], "+")
}
if (type == "segments")
ordiArgAbsorber(X[,1], X[,2], Y[,1], Y[,2], FUN = segments, ...)
else
ordiArgAbsorber(X[,1], X[,2], Y[,1], Y[,2], FUN = arrows, ...)
invisible()
} |
setMethod("show",
signature("abmodel"),
function(object) {
cat("Ensemble of bagged trees\n")
cat("No of trees:", length(object@base_models), ".\n")
cat("Target variable: ", get_target(object@form), ".\n")
if (object@dynamic_selection == "none") {
cat("Without dynamic selection.\n")
} else {
cat("With dynamic selection method:",
object@dynamic_selection, ".\n")
}
})
setMethod("predict",
signature("abmodel"),
function(object, newdata) {
switch(object@dynamic_selection,
"ola" = {
cat("Using OLA method to dynamically",
"predict new instances...\n")
OLA(object@form,
object@base_models,
object@data,
newdata,
5)
},
"knora-e" = {
cat("Using KNORA-E method to dynamically",
"predict new instances...\n")
KNORA.E(object@form,
object@base_models,
object@data,
newdata,
5)
},
"none" = {
cat("Using majority voting method",
"to predict new instances...\n")
Y_hat <- sapply(object@base_models, predict, newdata)
apply(Y_hat, 1, majority_voting)
})
}) |
setGeneric("clearSheet",
function(object, sheet) standardGeneric("clearSheet"))
setMethod("clearSheet",
signature(object = "workbook", sheet = "numeric"),
function(object, sheet) {
xlcCall(object, "clearSheet", as.integer(sheet - 1))
invisible()
}
)
setMethod("clearSheet",
signature(object = "workbook", sheet = "character"),
function(object, sheet) {
xlcCall(object, "clearSheet", sheet)
invisible()
}
) |
library(MSEtool)
test.results <- paste0(Sys.Date(), 'MSEtool_V', packageVersion("MSEtool"), '.xml')
options(testthat.output_file = test.results)
testthat::test_dir('tests/manual/test-code', reporter = "junit")
rmarkdown::render(input='tests/manual/Test_Report.Rmd',
params=list(results.file=file.path('test-code',test.results)))
options(testthat.output_file = NULL)
testthat::test_file("tests/manual/test-code/test-checkPopDynamics.R")
testthat::test_file("tests/manual/test-code/test-Data2csv.R")
testthat::test_file("tests/manual/test-code/test-Data_Functions.R")
testthat::test_file("tests/manual/test-code/test-Data_Plotting.R")
testthat::test_file("tests/manual/test-code/test-Fease_Functions.R")
testthat::test_file("tests/manual/test-code/test-Import_Data.R")
testthat::test_file("tests/manual/test-code/test-MPs.R")
testthat::test_file("tests/manual/test-code/test-MSE_functions.R")
testthat::test_file("tests/manual/test-code/test-MSE_Plotting.R")
testthat::test_file("tests/manual/test-code/test-OM_functions.R")
testthat::test_file("tests/manual/test-code/test-OM_init_doc.R")
testthat::test_file("tests/manual/test-code/test-OM_Plotting.R")
testthat::test_file("tests/manual/test-code/test-PMobjects.R")
testthat::test_file("tests/manual/test-code/test-RealIndices.R")
testthat::test_file("tests/manual/test-code/test-runMSE.R")
testthat::test_file("tests/manual/test-code/test-slotDescription.R") |
probbit <-
function(m,csi){dbinom(0:(m-1),m-1,1-csi)} |
capture <- function(x, etc, err) {
capt.width <- [email protected]
if(capt.width) {
opt.set <- try(width.old <- options(width=capt.width), silent=TRUE)
if(inherits(opt.set, "try-error")) {
warning(
"Unable to set desired width ", capt.width, ", (",
conditionMessage(attr(opt.set, "condition")), ");",
"proceeding with existing setting."
)
} else on.exit(options(width.old))
}
capt.file <- tempfile()
on.exit(unlink(capt.file), add=TRUE)
res <- try({
capture.output(eval(x, etc@frame), file=capt.file)
obj.out <- readLines(capt.file)
})
if(inherits(res, "try-error"))
err(
"Failed attempting to get text representation of object: ",
conditionMessage(attr(res, "condition"))
)
html_ent_sub(res, etc@style)
}
capt_print <- function(target, current, etc, err, extra){
dots <- extra
if(getRversion() >= "3.2.0") {
print.match <- try(
match.call(
get("print", envir=etc@frame, mode='function'),
as.call(c(list(quote(print), x=NULL), dots)),
envir=etc@frame
) )
} else {
print.match <- try(
match.call(
get("print", envir=etc@frame),
as.call(c(list(quote(print), x=NULL), dots))
) )
}
if(inherits(print.match, "try-error"))
err("Unable to compose `print` call")
names(print.match)[[2L]] <- ""
tar.call <- cur.call <- print.match
if(length(dots)) {
if(!is.null([email protected])) tar.call[[2L]] <- [email protected]
if(!is.null([email protected])) cur.call[[2L]] <- [email protected]
[email protected] <- deparse(tar.call)[[1L]]
[email protected] <- deparse(cur.call)[[1L]]
}
tar.call.q <- if(is.call(target) || is.symbol(target))
call("quote", target) else target
cur.call.q <- if(is.call(current) || is.symbol(current))
call("quote", current) else current
if(!is.null(target)) tar.call[[2L]] <- tar.call.q
if(!is.null(current)) cur.call[[2L]] <- cur.call.q
if((!is.null(dim(target)) || !is.null(dim(current)))) {
cur.capt <- capture(cur.call, etc, err)
tar.capt <- capture(tar.call, etc, err)
etc <- set_mode(etc, tar.capt, cur.capt)
} else {
etc <- if(etc@mode == "auto") sideBySide(etc) else etc
cur.capt <- capture(cur.call, etc, err)
tar.capt <- capture(tar.call, etc, err)
}
if(isTRUE(etc@guides)) etc@guides <- guidesPrint
if(isTRUE(etc@trim)) etc@trim <- trimPrint
diff.out <- line_diff(target, current, tar.capt, cur.capt, etc=etc, warn=TRUE)
[email protected] <- "print"
diff.out
}
capt_str <- function(target, current, etc, err, extra){
dots <- extra
frame <- etc@frame
line.limit <- [email protected]
if("object" %in% names(dots))
err("You may not specify `object` as part of `extra`")
if(getRversion() < "3.2.0") {
str.match <- match.call(
str_tpl,
call=as.call(c(list(quote(str), object=NULL), dots))
)
} else {
str.match <- match.call(
str_tpl,
call=as.call(c(list(quote(str), object=NULL), dots)), envir=etc@frame
)
}
names(str.match)[[2L]] <- ""
if(etc@mode == "auto") etc <- sideBySide(etc)
eval_try <- function(match.list, index, envir)
tryCatch(
eval(match.list[[index]], envir=envir),
error=function(e)
err("Error evaluating `", index, "` arg: ", conditionMessage(e))
)
auto.mode <- FALSE
max.level.supplied <- FALSE
if(
max.level.pos <- match("max.level", names(str.match), nomatch=0L)
) {
max.level.eval <- eval_try(str.match, "max.level", etc@frame)
if(identical(max.level.eval, "auto")) {
auto.mode <- TRUE
str.match[["max.level"]] <- NA
} else {
max.level.supplied <- TRUE
}
} else {
str.match[["max.level"]] <- NA
auto.mode <- TRUE
max.level.pos <- length(str.match)
max.level.supplied <- FALSE
}
wrap <- FALSE
if("strict.width" %in% names(str.match)) {
res <- eval_try(str.match, "strict.width", etc@frame)
wrap <- is.character(res) && length(res) == 1L && !is.na(res) &&
nzchar(res) && identical(res, substr("wrap", 1L, nchar(res)))
}
if(auto.mode) {
msg <-
"Specifying `%s` may cause `str` output level folding to be incorrect"
if("comp.str" %in% names(str.match)) warning(sprintf(msg, "comp.str"))
if("indent.str" %in% names(str.match)) warning(sprintf(msg, "indent.str"))
}
tar.call <- cur.call <- str.match
tar.call.q <- if(is.call(target) || is.symbol(target))
call("quote", target) else target
cur.call.q <- if(is.call(current) || is.symbol(current))
call("quote", current) else current
if(!is.null(target)) tar.call[[2L]] <- tar.call.q
if(!is.null(current)) cur.call[[2L]] <- cur.call.q
capt.width <- [email protected]
has.diff <- has.diff.prev <- FALSE
tar.capt <- capture(tar.call, etc, err)
tar.lvls <- str_levels(tar.capt, wrap=wrap)
cur.capt <- capture(cur.call, etc, err)
cur.lvls <- str_levels(cur.capt, wrap=wrap)
prev.lvl.hi <- lvl <- max.depth <- max(tar.lvls, cur.lvls)
prev.lvl.lo <- 0L
first.loop <- TRUE
safety <- 0L
warn <- TRUE
if(isTRUE(etc@guides)) etc@guides <- guidesStr
if(isTRUE(etc@trim)) etc@trim <- trimStr
tar.str <- tar.capt
cur.str <- cur.capt
diff.obj <- diff.obj.full <- line_diff(
target, current, tar.str, cur.str, etc=etc, warn=warn
)
if(!max.level.supplied) {
repeat{
if((safety <- safety + 1L) > max.depth && !first.loop)
stop(
"Logic Error: exceeded list depth when comparing structures; contact ",
"maintainer."
)
if(!first.loop) {
tar.str <- tar.capt[tar.lvls <= lvl]
cur.str <- cur.capt[cur.lvls <= lvl]
diff.obj <- line_diff(
target, current, tar.str, cur.str, etc=etc, warn=warn
)
}
if([email protected]) warn <- FALSE
has.diff <- suppressWarnings(any(diff.obj))
if(first.loop && !has.diff) break
first.loop <- FALSE
if(line.limit[[1L]] < 1L) break
line.len <- diff_line_len(
diff.obj@diffs, etc=etc, tar.capt=tar.str, cur.capt=cur.str
)
if(!has.diff && prev.lvl.hi - lvl > 1L) {
prev.lvl.lo <- lvl
lvl <- lvl + as.integer((prev.lvl.hi - lvl) / 2)
tar.call[[max.level.pos]] <- lvl
cur.call[[max.level.pos]] <- lvl
next
} else if(!has.diff) {
diff.obj <- diff.obj.full
lvl <- NULL
break
}
if(line.len <= line.limit[[1L]]) {
break
}
if(lvl - prev.lvl.lo > 1L) {
prev.lvl.hi <- lvl
lvl <- lvl - as.integer((lvl - prev.lvl.lo) / 2)
tar.call[[max.level.pos]] <- lvl
cur.call[[max.level.pos]] <- lvl
next
}
diff.obj <- diff.obj.full
lvl <- NULL
break
}
} else {
tar.str <- tar.capt[tar.lvls <= max.level.eval]
cur.str <- cur.capt[cur.lvls <= max.level.eval]
lvl <- max.level.eval
diff.obj <- line_diff(target, current, tar.str, cur.str, etc=etc, warn=warn)
}
if(auto.mode && !is.null(lvl) && lvl < max.depth) {
str.match[[max.level.pos]] <- lvl
} else if (!max.level.supplied || is.null(lvl)) {
str.match[[max.level.pos]] <- NULL
}
tar.call <- cur.call <- str.match
if(!is.null([email protected])) tar.call[[2L]] <- [email protected]
if(!is.null([email protected])) cur.call[[2L]] <- [email protected]
if(is.null([email protected]))
diff.obj@[email protected] <- deparse(tar.call)[[1L]]
if(is.null([email protected]))
diff.obj@[email protected] <- deparse(cur.call)[[1L]]
[email protected] <- count_diffs(diff.obj.full@diffs)
[email protected] <- "str"
diff.obj
}
capt_chr <- function(target, current, etc, err, extra){
tar.capt <- if(!is.character(target))
do.call(as.character, c(list(target), extra), quote=TRUE) else target
cur.capt <- if(!is.character(current))
do.call(as.character, c(list(current), extra), quote=TRUE) else current
if((tt <- typeof(tar.capt)) != 'character')
stop("Coercion of `target` did not produce character object (", tt, ").")
if((tc <- typeof(cur.capt)) != 'character')
stop("Coercion of `current` did not produce character object (", tc, ").")
tar.capt <- c(tar.capt)
cur.capt <- c(cur.capt)
if(anyNA(tar.capt)) tar.capt[is.na(tar.capt)] <- "NA"
if(anyNA(cur.capt)) cur.capt[is.na(cur.capt)] <- "NA"
etc <- set_mode(etc, tar.capt, cur.capt)
if(isTRUE(etc@guides)) etc@guides <- guidesChr
if(isTRUE(etc@trim)) etc@trim <- trimChr
diff.out <- line_diff(
target, current, html_ent_sub(tar.capt, etc@style),
html_ent_sub(cur.capt, etc@style), etc=etc
)
[email protected] <- "chr"
diff.out
}
capt_deparse <- function(target, current, etc, err, extra){
dep.try <- try({
tar.capt <- do.call(deparse, c(list(target), extra), quote=TRUE)
cur.capt <- do.call(deparse, c(list(current), extra), quote=TRUE)
})
if(inherits(dep.try, "try-error"))
err("Error attempting to deparse object(s)")
etc <- set_mode(etc, tar.capt, cur.capt)
if(isTRUE(etc@guides)) etc@guides <- guidesDeparse
if(isTRUE(etc@trim)) etc@trim <- trimDeparse
diff.out <- line_diff(
target, current, html_ent_sub(tar.capt, etc@style),
html_ent_sub(cur.capt, etc@style), etc=etc
)
[email protected] <- "deparse"
diff.out
}
capt_file <- function(target, current, etc, err, extra) {
tar.capt <- try(do.call(readLines, c(list(target), extra), quote=TRUE))
if(inherits(tar.capt, "try-error")) err("Unable to read `target` file.")
cur.capt <- try(do.call(readLines, c(list(current), extra), quote=TRUE))
if(inherits(cur.capt, "try-error")) err("Unable to read `current` file.")
etc <- set_mode(etc, tar.capt, cur.capt)
if(isTRUE(etc@guides)) etc@guides <- guidesFile
if(isTRUE(etc@trim)) etc@trim <- trimFile
diff.out <- line_diff(
tar.capt, cur.capt, html_ent_sub(tar.capt, etc@style),
html_ent_sub(cur.capt, etc@style), etc=etc
)
[email protected] <- "file"
diff.out
}
capt_csv <- function(target, current, etc, err, extra){
tar.df <- try(do.call(read.csv, c(list(target), extra), quote=TRUE))
if(inherits(tar.df, "try-error")) err("Unable to read `target` file.")
if(!is.data.frame(tar.df))
err("`target` file did not produce a data frame when read")
cur.df <- try(do.call(read.csv, c(list(current), extra), quote=TRUE))
if(inherits(cur.df, "try-error")) err("Unable to read `current` file.")
if(!is.data.frame(cur.df))
err("`current` file did not produce a data frame when read")
capt_print(tar.df, cur.df, etc, err, extra)
}
set_mode <- function(etc, tar.capt, cur.capt) {
stopifnot(is(etc, "Settings"), is.character(tar.capt), is.character(cur.capt))
if(etc@mode == "auto") {
if(
any(
nchar2(cur.capt, [email protected]) > [email protected]
) ||
any(
nchar2(tar.capt, [email protected]) > [email protected]
)
) {
etc@mode <- "unified"
} }
if(etc@mode == "auto") etc <- sideBySide(etc)
etc
} |
skip_on_cran()
test_that("list_oml_data_sets", {
tab = list_oml_data_sets(limit = 10)
expect_data_table(tab, nrows = 10, min.cols = 10)
expect_names(names(tab), type = "strict",
must.include = c("data_id", "name", "version", "status", "NumberOfFeatures"))
expect_data_table(list_oml_data_sets(data_id = c(9, 11)), nrows = 2)
expect_data_table(list_oml_data_sets(data_id = 1), nrows = 0L, ncols = 0L)
expect_data_table(list_oml_data_sets(data_id = 999999999), nrows = 0L)
}) |
if (!isGeneric('read_gpx ')) {
setGeneric('read_gpx ', function(x, ...)
standardGeneric('read_gpx '))
}
read_gpx <- function(file, layers=c("waypoints", "tracks", "routes", "track_points", "route_points")) {
if (!all(layers %in% c("waypoints", "tracks", "routes", "track_points", "route_points"))) stop("Incorrect layer(s)", call. = FALSE)
}
comp_ll_proj4 <- function(x) {
proj <- datum <- nodefs <- "FALSE"
allWGS84 <- as.vector(c("+init=epsg:4326", "+proj=longlat", "+datum=WGS84", "+no_defs", "+ellps=WGS84", "+towgs84=0,0,0"))
s <- as.vector(strsplit(x," "))
for (i in seq(1:length(s[[1]]))) {
if (s[[1]][i] == "+init=epsg:4326") {
proj <- datum <- nodefs <- "TRUE"
}
if (s[[1]][i] == "+proj=longlat") {
proj <- "TRUE"
}
if (s[[1]][i] == "+no_defs") {
nodefs <- "TRUE"
}
if (s[[1]][i] == "+datum=WGS84") {
datum <- "TRUE"
}
}
if (proj == "TRUE" & nodefs == "TRUE" & datum == "TRUE") {
ret <- TRUE
} else {
ret = FALSE
}
return(ret)
}
sp_line <- function(Y_coords,
X_coords,
ID = "ID",
proj4="+proj=longlat +datum=WGS84 +no_defs",
export=FALSE,
runDir) {
line <- sp::SpatialLines(list(sp::Lines(sp::Line(cbind(Y_coords,X_coords)), ID = ID)))
sp::proj4string(line) <- sp::CRS(proj4)
if (export) {
maptools::writeLinesShape(line,file.path(runDir,paste0(ID,"home.shp")))
}
return(line)
}
sp_point <- function(lon,
lat,
ID="point",
proj4="+proj=longlat +datum=WGS84 +no_defs",
export=FALSE,
runDir=runDir) {
point = cbind(lon,lat)
point = sp::SpatialPoints(point)
point = sp::SpatialPointsDataFrame(point, as.data.frame(ID))
sp::proj4string(point) <- sp::CRS(proj4)
if (export) {
maptools::writeLinesShape(ID,file.path(runDir,paste0(ID,".shp")))
}
return(point)
}
maxpos_on_line <- function(dem,line){
mask <- dem
raster::values(mask) <- NA
mask <- raster::rasterize(line,mask)
mask2 <- mask*dem
idx = raster::which.max(mask2)
maxPos = raster::xyFromCell(mask2,idx)
return(maxPos)
}
fun_multiply <- function(x)
{
band1 <- x[,,1]
band2 <- x[,,2]
result <- band1*band2
result <- array(result,dim=c(dim(x)[1],dim(x)[2],1))
return(result)
}
fun_whichmax <- function(mask,value) {
raster::xyFromCell(value,which.max(mask * value))
}
getPopupStyle <- function() {
fl <- system.file("templates/popup.brew", package = "mapview")
pop <- readLines(fl)
end <- grep("<%=pop%>", pop)
return(paste(pop[1:(end-2)], collapse = ""))
}
if ( !isGeneric("initProj") ) {
setGeneric("initProj", function(x, ...)
standardGeneric("initProj"))
}
initProj <- function(projRootDir=getwd(), projFolders=c("log/","control/","run/","data/")) {
projRootDir <- gsub("\\\\", "/", path.expand(projRootDir))
if (substr(projRootDir,nchar(projRootDir) - 1,nchar(projRootDir)) != "/") {
projRootDir <- paste0(projRootDir,"/")
}
if (file.exists(paste0(projRootDir,"fp-data/log/pathes.R"))) {file.remove(paste0(projRootDir,"fp-data/log/pathes.R"))}
for (folder in projFolders) {
if (!file.exists(file.path(projRootDir,folder))) {
dir.create(file.path(projRootDir,folder), recursive = TRUE)}
value <- paste0(projRootDir,folder)
name <- substr(folder,1,nchar(folder) )
S<-strsplit(x =name ,split = "/")
varName<-paste0("pto_",S[[1]][lengths(S)])
writePathes(varName, value,paste0(projRootDir,"fp-data/log/pathes.R"))
}
writePSCmd(projRootDir = projRootDir)
}
makeGlobalVar <- function(name,value) {
newname <- gsub("/", "_", name)
assign(newname, value, inherits = TRUE)
}
writePathes <- function(name,value,fn) {
utils::write.table(paste0(name,' <- "', value,'"'),fn,quote = FALSE,row.names = FALSE, col.names = FALSE ,append = TRUE)
}
writePSCmd <- function(goal = "ortho",
projRootDir,
imgPath = "img-data/FLIGHT1/level1/rgb",
projName = "tmp.psx",
alignQuality = "2",
orthoRes = "0.02",
refPre= "PhotoScan.GenericPreselection",
EPSG = "4326",
preset_RU = "50",
preset_RE = "1",
preset_PA = "10",
loop_RU = "5",
loop_RE = "10",
loop_PA = "2",
dc_quality ="MediumQuality",
filter_mode = "AggressiveFiltering",
passes = 15) {
fn<-paste0(projRootDir,"fp-data/log/basicPSWorkflow.py")
if (goal == "ortho") goal <- "singleOrtho"
if (goal == "dense") goal <- "singleDense"
flightname<-strsplit(projRootDir,split = "/")[[1]][lengths(strsplit(projRootDir,split = "/"))]
script <- paste(system.file(package="uavRmp"), "python/basicPSWorkflow.py", sep = "/")
goal <- paste0('goal = ','"',goal,'"')
imgPath <- paste0('imgPath = ','"',projRootDir,imgPath,'"')
projName = paste0('projName = ','"',flightname,'.psx"')
alignQuality = paste0("alignQuality = ",alignQuality)
orthoRes = paste0("orthoRes = ",orthoRes)
refPre = paste0("refPre = ",refPre)
crs = paste0('crs = ',' PhotoScan.CoordinateSystem(','"EPSG::', EPSG,'")')
preset_RU = paste0("preset_RU = ",preset_RU)
preset_RE = paste0("preset_RE = ",preset_RE)
preset_PA = paste0("preset_PA = ",preset_PA)
loop_RU = paste0("loop_RU = ",loop_RU)
loop_RE = paste0("loop_RE = ",loop_RE)
loop_PA = paste0("loop_PA = ",loop_PA)
filter_mode = paste0("filter_mode = ",paste0("PhotoScan.",filter_mode))
dc_quality = paste0("dc_quality = ",paste0("PhotoScan.",dc_quality))
passes = paste0("passes = ",passes)
brew::brew(script,fn)
}
file_move <- function(from, to,pattern="*") {
todir <- gsub("\\\\", "/", path.expand(to))
todir <- path.expand(to)
fromdir <- path.expand(from)
if (!isTRUE(file.info(todir)$isdir)) dir.create(todir, recursive=TRUE)
list<-list.files(path.expand(fromdir),pattern = pattern)
result<-file.rename(from = paste0(from,"/",list), to = todir)
}
copyDir <- function(fromDir, toProjDir, pattern="*") {
toDir <- gsub("\\\\", "/", path.expand(toProjDir))
toDir <- path.expand(toDir)
fromDir <- path.expand(fromDir)
if (!isTRUE(file.info(toDir)$isdir)) dir.create(toDir, recursive=TRUE)
list<-list.files(path.expand(fromDir),pattern = pattern)
result<-file.copy(from = paste0(fromDir,"/",list), to = toDir, overwrite = TRUE,recursive = TRUE,copy.date =TRUE)
}
createTempDataTransfer <- function (){
tmpPath <- tempfile(pattern="007")
dir.create(tmpPath)
return(tmpPath)
}
vecDrawInternal <- function(tmpPath, x = NULL) {
deps<-digiDependencies(tmpPath)
sizing = htmlwidgets::sizingPolicy(
browser.fill = TRUE,
viewer.fill = TRUE,
viewer.padding = 5
)
htmlwidgets::createWidget(
name = 'vecDraw',
x,
dependencies = deps,
sizingPolicy = sizing,
package = 'uavRmp'
)
}
vecDrawOutput <- function(outputId, width = '100%', height = '800px') {
htmlwidgets::shinyWidgetOutput(outputId, 'vecDraw', width, height, package = 'uavRmp')
}
rendervecDraw<- function(expr, env = parent.frame(), quoted = FALSE) {
projViewOutput<-NULL
if (!quoted) {
expr <- substitute(expr)
}
htmlwidgets::shinyRenderWidget(expr, projViewOutput, env, quoted = TRUE)
}
digiDependencies <- function(tmpPath) {
data_dir <- paste0(tmpPath,sep=.Platform$file.sep)
list(
htmltools::htmlDependency(name = "crs",
version = "1",
src = c(file = tmpPath),
script = list("crs.js")),
htmltools::htmlDependency(name = "jsondata",
version = "1",
src = c(file = tmpPath),
script = list("jsondata")),
htmltools::htmlDependency(
name = "leaflet-draw",
version= "0.7.3",
src = c(file = tmpPath),
script = list("leaflet.draw.js"),
stylesheet=list("leaflet.draw.css")
)
)
}
digiDependencies <- function(tmpPath) {
data_dir <- paste0(tmpPath,sep=.Platform$file.sep)
list(
htmltools::htmlDependency(name = "crs",
version = "1",
src = c(file = tmpPath),
script = list("crs.js")),
htmltools::htmlDependency(name = "jsondata",
version = "1",
src = c(file = tmpPath),
script = list("jsondata")),
htmltools::htmlDependency(
name = "leaflet-draw",
version= "0.7.3",
src = c(file = tmpPath),
script = list("leaflet.draw.js"),
stylesheet=list("leaflet.draw.css")
)
)
}
createTempDataTransfer <- function (){
tmpPath <- tempfile(pattern="007")
dir.create(tmpPath)
return(tmpPath)
}
vecDrawInternal <- function(tmpPath, x = NULL) {
deps<-digiDependencies(tmpPath)
sizing = htmlwidgets::sizingPolicy(
browser.fill = TRUE,
viewer.fill = TRUE,
viewer.padding = 5
)
htmlwidgets::createWidget(
name = 'vecDraw',
x,
dependencies = deps,
sizingPolicy = sizing,
package = 'uavRmp'
)
} |
plot.diagram <-
function(x, diagLim = NULL, dimension = NULL, col = NULL, rotated = FALSE,
barcode = FALSE, band = NULL, lab.line = 2.2, colorBand = "pink",
colorBorder = NA, add = FALSE, ...) {
if (!is.null(diagLim) && (!is.numeric(diagLim) || length(diagLim) != 2)) {
stop("diagLim should be a vector of length 2")
}
if (!is.null(dimension) && (!is.numeric(dimension) ||
length(dimension) != 1 || any(dimension < 0))) {
stop("dimension should be a nonnegative integer")
}
if (!is.logical(rotated)) {
stop("rotated should be logical")
}
if (!is.logical(barcode)) {
stop("barcode should be logical")
}
if (!is.null(band) && (!is.numeric(band) || length(band) != 1)) {
stop("band should be a number")
}
if (!is.logical(add)) {
stop("add should be logical")
}
if (any(class(x) != "diagram") && is.numeric(x)) {
x <- matrix(x, ncol = 3, dimnames = list(NULL, colnames(x)))
}
if (is.null(diagLim) || any(diagLim == -Inf) || any(diagLim == Inf)) {
if (any(class(x) == "diagram")) {
diagLim <- attributes(x)[["scale"]]
} else {
nonInf <- which(
x[, 2] != Inf & x[, 2] != -Inf & x[, 3] != Inf & x[, 3] != -Inf)
if (length(nonInf) > 0) {
diagLim <- c(min(x[nonInf, 2:3]), max(x[nonInf, 2:3]))
} else {
diagLim <- c(0,0)
}
}
}
x[x[, 2] < diagLim[1], 2] <- diagLim[1]
x[x[, 3] < diagLim[1], 3] <- diagLim[1]
x[x[, 2] > diagLim[2], 2] <- diagLim[2]
x[x[, 3] > diagLim[2], 3] <- diagLim[2]
sublevel <- TRUE
if (any(colnames(x)[3] == "Birth")) {
sublevel <- FALSE
}
if (!is.null(dimension)) {
x <- x[which(x[, 1] == dimension), , drop = FALSE]
}
if (is.null(match.call()[["pch"]])) {
symb <- x[, 1]
for (i in seq(along = symb)) {
if (symb[i] == 0) {
symb[i] <- 16
} else if (symb[i] == 1) {
symb[i] <- 2
} else if (symb[i] == 2) {
symb[i] <- 5
} else if (symb[i] == 5) {
symb[i] <- 1
}
}
} else {
symb <- match.call()[["pch"]]
}
if (is.null(col)){
col <- x[, 1] + 1
for (i in seq(along = x[, 1])) {
if (x[i, 1] == 2) {
col[i] <- 4
}
if (x[i, 1] == 3) {
col[i] <- 3
}
}
}
if (barcode) {
if (length(col) == 1) {
col <- rep(col, nrow(x))
}
maxD <- max(x[, 1])
minD <- min(x[, 1])
if (maxD > 0) {
sortedDiag <- x
sortedCol <- col
posD <- which(x[, 1] == minD)
lD <- 0
for (dd in (minD):maxD) {
oldlD <- lD
posD <- which(x[,1] == dd)
if (length(posD) != 0) {
lD <- oldlD + length(posD)
sortedDiag[(oldlD + 1):(lD), ] <- x[posD, ]
sortedCol[(oldlD + 1):(lD)] <- col[posD]
}
}
x <- sortedDiag
col <- sortedCol
}
left <- x[, 2]
right <- x[, 3]
n <- length(left)
Bmax <- max(right)
Bmin <- min(left)
graphics::plot(c(Bmin, Bmax), c(1, n + 1), type = "n", xlab = "",
ylab = "", xlim = c(Bmin, Bmax), ylim = c(0, n + 1), xaxt = "n",
yaxt = "n", ...)
graphics::axis(1)
graphics::title(xlab = "time", line = lab.line)
lwid <- rep(2,n)
ltype <- rep(1,n)
if (!is.null(band)){
for(i in seq_len(n)) {
if ((x[i, 3] - x[i, 2]) <= band) {
ltype[i] <- 3
lwid[i] <- 1.5
}
}
}
graphics::segments(left, 1:n, right, 1:n, lwd = lwid, lty = ltype,
col = col)
} else{
if (rotated == TRUE) {
if (add == FALSE) {
graphics::plot(0, 0,type = "n", axes = FALSE, xlim = diagLim,
ylim = diagLim, xlab = " ", ylab = " ", ...)
}
if (!is.null(band)) {
graphics::polygon(c(0, diagLim[2] + 1, diagLim[2] + 1, 0),
c(0, 0, band, band), col = colorBand, lwd = 1.5,
border = colorBorder)
}
graphics::points((x[, 2] + x[, 3]) / 2, (x[, 3]-x[, 2]) / 2, col = col,
pch = symb, lwd = 2, cex = 1)
} else{
if (add == FALSE) {
graphics::plot(0, 0, type = "n", axes = FALSE, xlim = diagLim,
ylim = diagLim, xlab = " ", ylab = " ", ...)
}
if (!is.null(band)) {
graphics::polygon(
c(diagLim[1] - 1, diagLim[2] + 1, diagLim[2] + 1, diagLim[1] - 1),
c(diagLim[1] - 1,diagLim[2] + 1, diagLim[2] + 1 + band,
diagLim[1] - 1 + band),
col = colorBand, lwd = 1.5, border = colorBorder)
}
graphics::points(x[, 2], x[, 3], pch = symb, lwd = 2, cex = 1, col = col)
graphics::abline(0, 1)
}
if (add==FALSE){
graphics::axis(1)
graphics::axis(2)
if (sublevel) {
if (!rotated) {
graphics::title(main = "", xlab = "Birth", ylab = "Death",
line = lab.line)
} else {
graphics::title(main = "", ylab = "(Death-Birth)/2",
xlab = "(Death+Birth)/2", line = lab.line)
}
}
if (!sublevel) {
if (!rotated) {
graphics::title(main = "", xlab = "Death", ylab = "Birth",
line = lab.line)
} else {
graphics::title(main = "", ylab = "(Birth-Death)/2",
xlab = "(Death+Birth)/2", line = lab.line)
}
}
}
}
} |
AssignQualification <-
assignqual <-
AssignQualifications <-
AssociateQualificationWithWorker <-
function (qual = NULL, workers, value = 1,
notify = FALSE, name = NULL, description = NULL,
keywords = NULL, status = NULL, retry.delay = NULL,
test = NULL, answerkey = NULL, test.duration = NULL,
auto = NULL, auto.value = NULL,
verbose = getOption('pyMTurkR.verbose', TRUE)) {
GetClient()
if (!is.null(qual) & is.factor(qual)) {
qual <- as.character(qual)
}
if (is.factor(workers)) {
workers <- as.character(workers)
}
if (is.factor(value)) {
value <- as.character(value)
}
if (!is.logical(notify) == TRUE) {
stop("SendNotification must be TRUE or FALSE.")
}
if (length(value) == 1) {
value <- rep(value[1], length(workers))
} else if (!length(value) == length(workers)) {
stop("Number of values is not 1 nor length(workers)")
}
for (i in 1:length(value)) {
if (is.null(value[i]) || is.na(value[i]) || value[i]=='') {
warning("Value ", i," not assigned; value assumed to be 1")
value[i] <- as.integer(1)
} else if(is.na(as.integer(value[i]))) {
stop("value ", i," is not or cannot be coerced to integer")
}
}
worker <- NULL
batch <- function(worker, value) {
response <- try(pyMTurkR$Client$associate_qualification_with_worker(
QualificationTypeId = qual,
WorkerId = worker,
IntegerValue = as.integer(value),
SendNotification = as.logical(notify)
), silent = !verbose)
if(class(response) == "try-error") {
return(data.frame(valid = FALSE))
}
else response$valid = TRUE
if(verbose & response$valid)
message("Qualification (", qual, ") Assigned to worker ", worker)
return(invisible(response))
}
if (!is.null(name)) {
if (!is.null(qual))
stop("Cannot specify QualificationTypeId and properties of new QualificationType")
if (is.null(description))
stop("No Description provided for QualificationType")
if (is.null(status) || !status == "Active") {
warning("QualificationTypeStatus set to 'Active'")
status <- "Active"
}
type <- CreateQualificationType(name = name, description = description,
keywords = keywords, status = status, retry.delay = retry.delay,
test = test, answerkey = answerkey, test.duration = test.duration,
auto = auto, auto.value = auto.value)
qual <- as.character(type$QualificationTypeId)
}
qual.value <- value
Qualifications <- emptydf(length(workers), 5,
c("WorkerId", "QualificationTypeId", "Value", "Notified", "Valid"))
for (i in 1:length(workers)) {
x <- batch(workers[i], value[i])
if (is.null(x$valid)) {
x$valid <- FALSE
}
Qualifications[i, ] = c(workers[i], qual, value[i], notify, x$valid)
}
Qualifications$Valid <- factor(Qualifications$Valid, levels=c('TRUE','FALSE'))
return(Qualifications)
} |
order.optimal <- function(dist, merge) {
if (!inherits(dist,"dist"))
stop(paste(sQuote("dist"),"not of class dist"))
if (!is.matrix(merge))
stop(paste(sQuote("merge"),"not a matrix"))
if (length(dim(merge)) != 2)
stop(paste(sQuote("merge"),"invalid"))
if (dim(merge)[1] != attr(dist,"Size")-1)
stop(paste(sQuote("dist"),"and",sQuote("merge"),"do not conform"))
if (!is.double(dist))
storage.mode(dist) <- "double"
storage.mode(merge) <- "integer"
obj <- .Call(R_order_optimal, dist, merge)
names(obj) <- c("merge","order","length")
names(obj$order) <- attr(dist,"Labels")
obj
}
order.length <- function(dist, order) {
if (!inherits(dist,"dist"))
stop(paste(sQuote("dist"),"not of class dist"))
if (missing(order))
order <- 1:attr(dist, "Size")
else {
if (length(order) != attr(dist,"Size"))
stop(paste(sQuote("order"),"invalid lenght"))
}
if (!is.double(dist))
storage.mode(dist) <- "double"
if (!is.integer(order))
storage.mode(order) <- "integer"
x <- .Call(R_order_length, dist, order)
x
}
order.greedy <- function(dist) {
if (!inherits(dist, "dist"))
stop(paste(sQuote("dist"),"not of class dist"))
if (!is.double(dist))
storage.mode(dist) <- "double"
obj <- .Call(R_order_greedy, dist)
names(obj) <- c("merge", "order", "height");
obj
} |
cape2mpp <- function(data_obj, geno_obj = NULL){
geno_locale <- which(names(data_obj) == "geno")
if(length(geno_locale) > 0){
geno <- data_obj$geno
}else{
geno <- geno_obj$geno
}
geno_array <- array(NA, dim = c(nrow(geno),2,ncol(geno)))
geno_array[,1,] <- 1-geno
geno_array[,2,] <- geno
dimnames(geno_array) <- list(rownames(geno), c("A", "B"), colnames(geno))
names(dimnames(geno_array)) <- c("mouse", "allele" ,"locus")
geno_obj$geno <- geno_array
data_obj$geno <- NULL
data_obj$marker_names <- NULL
geno_names <- list(rownames(data_obj$pheno), c("A", "B"), colnames(geno))
names(geno_names) <- c("mouse", "allele", "locus")
data_obj$geno_names <- geno_names
results <- list("data_obj" = data_obj, "geno_obj" = geno_obj)
return(results)
} |
ec.gfld <- function(
obj, whichseries=1, nsigma=3,jointboo=TRUE, epsboo=TRUE,
filename="whatever",xvec,yvec,cal,lar=0.025,...)
{
if(jointboo==TRUE){mywidth<-2*5.83}else{mywidth<-5.83}
if(epsboo==TRUE){myfilename<-paste0(filename,".eps");
setEPS(); postscript(file=myfilename,width=mywidth, height=4.13)
}else{
myfilename<-paste0(filename,".pdf")
pdf(file=myfilename,width=mywidth, height=4.13)}
if(jointboo==TRUE){par(mfcol=c(1,2))}
ec.gfl(obj,whichseries,nsigma,xvec,yvec,cal,lar,...)
if(jointboo==FALSE){dev.off();myfilename2<-paste0("D",myfilename);
if(epsboo==TRUE){setEPS();
postscript(file=myfilename2,width=mywidth, height=4.13)
}else{
pdf(file=myfilename2,width=mywidth, height=4.13)}}
ec.gfd(obj,whichseries,nsigma,xvec,yvec,cal,lar,...)
dev.off()
} |
test_that("expected behavior", {
vcr::use_cassette(name = "get_citation", {
ref <- get_citation(get_network_by_id(18))
netws <- get_collection(search_networks("lagoon"))
ref2 <- get_citation(netws)
})
expect_equal(length(ref), 1)
expect_equal(length(ref2), 2)
expect_true(grepl("^@article", ref))
expect_true(grepl("^@article", ref2[1]))
expect_true(grepl("^@book", ref2[2]))
}) |
readinteger <- function()
{
n <- readline(prompt="Enter an integer: ")
return(as.integer(n))
}
print(readinteger()) |
rse = function(truth, response, na_value = NaN, ...) {
assert_regr(truth, response = response, na_value = na_value)
v = var(truth)
if (v < TOL) {
return(na_value)
}
sum(se(truth, response)) / (v * (length(truth) - 1L))
}
add_measure(rse, "Relative Squared Error", "regr", 0, Inf, TRUE) |
caThreshold_at_specificity <- function(controlData,
userFormula,
control_specificity,
new_covariates) {
if(!is.numeric(control_specificity)) {
control_specificity <- as.numeric(control_specificity)
}
if(sum(control_specificity>1)>0 | sum(control_specificity<0)>0) {
stop("control_specificity should be between 0 and 1!")
}
rqfit <- NULL
if (length(control_specificity) == 1) {
expr1 <- paste0("rqfit <- rq(", userFormula, ", tau = ", control_specificity, ", data = controlData)")
eval(parse(text = expr1))
new_thres <- predict.rq(rqfit, newdata = new_covariates)
} else {
new_thres <- c()
for(j in 1:length(control_specificity)) {
expr1 <- paste0("rqfit <- rq(", userFormula, ", tau = ", control_specificity[j], ", data = controlData)")
eval(parse(text = expr1))
tmp <- predict.rq(rqfit, newdata = new_covariates)
new_thres <- cbind(new_thres, tmp)
}
colnames(new_thres) = paste0("control_spec=", control_specificity)
}
return(new_thres)
} |
get.pkg_search_paths <- function(pkg, vrs) {
if (pkg %in% base_pkg()) {
libp <- .libPaths()
default_lib <- libp[length(libp)]
full_path <- paste0(default_lib , "/", pkg)
return(full_path)
}
rv <- as.character(getRversion())
rv <- gsub("\\.\\d+(-w)?$", "", rv)
pkg_search_paths <- paste0(get.groundhog.folder(), "/R-", rv, "/", pkg, "_", vrs)
return(pkg_search_paths)
} |
coef.ml_g_fit <- function(object, ...) {
object$beta.hat[-length(object$beta.hat)]
} |
traplot1 <- function(x, col=NULL, lty=1, style=c("gray", "plain"), ...){
style <- match.arg(style)
nchains <- nchain(x)
if (is.null(col)){
col <- mcmcplotsPalette(nchains)
}
xx <- as.vector(time(x))
yy <- do.call("cbind", as.list(x))
if (style=="plain"){
matplot(xx, yy, type="l", col=col, lty=lty, ...)
}
if (style=="gray"){
matplot(xx, yy, type="n", xaxt="n", yaxt="n", bty="n", ...)
.graypr()
matlines(xx, yy, col=col, lty=lty)
}
} |
.axion_elec_name_to_xy <- function(name, plateinfo) {
max_well_row <- plateinfo$n_well_r
max_elec_row <- plateinfo$n_elec_r
max_elec_col <- plateinfo$n_elec_c
well_r <- max_well_row - match(substring(name, 1, 1), LETTERS)
well_c <- as.integer(substring(name, 2, 2)) - 1
elec_r <- as.integer(substring(name, 5, 5)) - 1
elec_c <- as.integer(substring(name, 4, 4)) - 1
gap <- 1
spacing <- 200
well_wid <- (max_elec_col + gap) * spacing
well_ht <- (max_elec_row + gap) * spacing
x <- (well_c * well_wid) + (elec_c * spacing)
y <- (well_r * well_ht) + (elec_r * spacing)
cbind(x, y)
}
.axion_spike_sum <- function(spikes) {
len <- length(spikes)
all_range <- sapply(spikes, range)
nspikes <- sum(sapply(spikes, length))
min <- min(all_range[1, ])
max <- max(all_range[2, ])
str <- sprintf("summary: %d electrodes %d spikes, min %.4f max %.4f",
len, nspikes, min, max)
c(nelectrodes = len, nspikes = nspikes, time.min = min, time.max = max)
}
.axion_spikes_to_df <- function(spikes) {
names <- names(spikes)
names(spikes) <- NULL
nspikes <- sapply(spikes, length)
data.frame(elec = rep(names, times = nspikes), time = unlist(spikes))
}
.axion_guess_well_number <- function(channels) {
well_r <- match(substring(channels, 1, 1), LETTERS)
well_c <- as.integer(substring(channels, 2, 2))
elec_r <- as.integer(substring(channels, 5, 5))
elec_c <- as.integer(substring(channels, 4, 4))
max_well_r <- max(well_r)
max_well_c <- max(well_c)
max_elec_r <- max(elec_r)
max_elec_c <- max(elec_c)
nplates <- length(.axion_plateinfo)
well <- 0
for (i in 1:nplates) {
plateinfo <- .axion_plateinfo[[i]]
if (max_well_r <= plateinfo$n_well_r &&
max_well_c <= plateinfo$n_well_c &&
max_elec_r <= plateinfo$n_elec_r &&
max_elec_c <= plateinfo$n_elec_c) {
well <- plateinfo$n_well
break;
}
}
if (well == 0) {
stop("Cannot guess number of wells on plate.")
}
well
}
.axion_electrodes_on_well <- function(well, electrodes) {
matches <- grep(well, electrodes)
electrodes[matches]
}
.axion_elec_to_well <- function(elec) {
substring(elec, 1, 2)
}
.get_array_info <- function(data) {
pos <- data$epos; rownames(pos) <- data$names
array <- data$array
if (any(grep("^Axion 48", array))) {
xlim <- c(-100, 7900)
ylim <- c(0, 6000)
spacing <- 200
corr_breaks <- 0
} else if (any(grep("^Axion 12", array))) {
xlim <- c(-100, 7200)
ylim <- c(0, 5400)
spacing <- 200
corr_breaks <- 0
}
array <- as.character(array)
layout <- list(xlim = xlim, ylim = ylim, spacing = spacing,
pos = pos, array = array)
class(layout) <- "mealayout"
list(layout = layout, corr_breaks = corr_breaks)
}
.filter_channel_names <- function(spikes, ids) {
if (any(is.character(ids)))
ids <- .names_to_indexes(names(spikes), ids)
spikes[ids]
}
.names_to_indexes <- function(names, elems, allow_na=FALSE, allow_regex=TRUE) {
if (is.null(elems)) {
return(1:length(names))
}
if (isTRUE(all.equal("-", elems[1]))) {
invert <- TRUE
elems <- elems[- 1]
} else {
invert <- FALSE
}
indexes <- match(elems, names)
if (allow_regex) {
which_na <- which(is.na(indexes))
if (any(which_na)) {
regex_elems <- elems[which_na]
new_indexes <- lapply(regex_elems, function(r){
grep(r, names)
})
new_indexes <- unique(unlist(new_indexes))
indexes <- indexes[- which_na]
indexes <- c(indexes, new_indexes)
}
allow_na <- TRUE
}
if (!allow_na) {
if (any(is.na(indexes)))
stop("some indexes not found.")
}
if (invert)
indexes <- setdiff(1:(length(names)), indexes)
indexes
} |
plotTranscripts <- function(chrom, chromstart = NULL, chromend = NULL,
assembly = "hg38",
fill = c("
colorbyStrand = TRUE, strandSplit = FALSE,
boxHeight = unit(2, "mm"), spaceWidth = 0.02,
spaceHeight = 0.3, limitLabel = TRUE,
fontsize = 8,
labels = "transcript", stroke = 0.1, bg = NA,
x = NULL, y = NULL, width = NULL,
height = NULL, just = c("left", "top"),
default.units = "inches", draw = TRUE,
params = NULL) {
errorcheck_plotTranscripts <- function(transcriptPlot, labels, fill) {
regionErrors(chromstart = transcriptPlot$chromstart,
chromend = transcriptPlot$chromend)
if (!labels %in% c(NULL, "transcript", "gene", "both")) {
stop("Invalid \'labels\' input. Options are \'NULL\', ",
"\'transcript\', \'gene\', or \'both\'.", call. = FALSE)
}
checkColorby(fill = fill,
colorby = FALSE)
}
strand_scale <- function(strandSplit, height) {
if (strandSplit == TRUE) {
yscale <- c(-height / 2, height / 2)
} else {
yscale <- c(0, height)
}
return(yscale)
}
transcriptsInternal <- parseParams(
params = params,
defaultArgs = formals(eval(match.call()[[1]])),
declaredArgs = lapply(match.call()[-1], eval.parent, n = 2),
class = "transcriptsInternal"
)
transcriptsInternal$just <-
justConversion(just = transcriptsInternal$just)
transcripts <- structure(list(
chrom = transcriptsInternal$chrom,
chromstart = transcriptsInternal$chromstart,
chromend = transcriptsInternal$chromend,
assembly = transcriptsInternal$assembly,
x = transcriptsInternal$x,
y = transcriptsInternal$y,
width = transcriptsInternal$width,
height = transcriptsInternal$height,
just = transcriptsInternal$just,
grobs = NULL
), class = "transcripts")
attr(x = transcripts, which = "plotted") <- transcriptsInternal$draw
if (is.null(transcripts$chrom)) {
stop("argument \"chrom\" is missing, with no default.",
call. = FALSE
)
}
check_placement(object = transcripts)
errorcheck_plotTranscripts(
transcriptPlot = transcripts,
labels = transcriptsInternal$labels,
fill = transcriptsInternal$fill
)
transcripts$assembly <-
parseAssembly(assembly = transcripts$assembly)
transcripts <- defaultUnits(
object = transcripts,
default.units = transcriptsInternal$default.units
)
transcriptsInternal$boxHeight <- misc_defaultUnits(
value = transcriptsInternal$boxHeight,
name = "boxHeight",
default.units = transcriptsInternal$default.units
)
buildData <- geneData(object = transcripts,
objectInternal = transcriptsInternal)
transcripts <- buildData[[1]]
transcriptsInternal <- buildData[[2]]
data <- transcriptsInternal$data
data$length <- data$TXEND - data$TXSTART
if (transcriptsInternal$colorbyStrand == TRUE) {
if (length(transcriptsInternal$fill) == 1) {
posCol <- transcriptsInternal$fill
negCol <- transcriptsInternal$fill
} else {
posCol <- transcriptsInternal$fill[1]
negCol <- transcriptsInternal$fill[2]
}
pos <- data[which(data$TXSTRAND == "+"), ]
pos$color <- rep(posCol, nrow(pos))
neg <- data[which(data$TXSTRAND == "-"), ]
neg$color <- rep(negCol, nrow(neg))
data <- rbind(pos, neg)
} else {
data$color <- rep(transcriptsInternal$fill[1], nrow(data))
}
if (transcriptsInternal$strandSplit == TRUE) {
posStrand <- data[which(data$TXSTRAND == "+"), ]
minStrand <- data[which(data$TXSTRAND == "-"), ]
}
currentViewports <- current_viewports()
vp_name <- paste0(
"transcripts",
length(grep(
pattern = "transcripts",
x = currentViewports
)) + 1
)
if (is.null(transcripts$x) | is.null(transcripts$y)) {
height <- 0.5
yscale <- strand_scale(
strandSplit = transcriptsInternal$strandSplit,
height = height
)
vp <- viewport(
height = unit(0.5, "snpc"), width = unit(1, "snpc"),
x = unit(0.5, "npc"), y = unit(0.5, "npc"),
clip = "on",
xscale = transcriptsInternal$xscale,
yscale = yscale,
just = "center",
name = vp_name
)
if (transcriptsInternal$draw == TRUE) {
vp$name <- "transcripts1"
grid.newpage()
}
} else {
addViewport(vp_name)
page_coords <- convert_page(object = transcripts)
height <- convertHeight(page_coords$height,
unitTo = get("page_units",
envir = pgEnv
),
valueOnly = TRUE
)
yscale <- strand_scale(
strandSplit = transcriptsInternal$strandSplit,
height = height
)
vp <- viewport(
height = page_coords$height, width = page_coords$width,
x = page_coords$x, y = page_coords$y,
clip = "on",
xscale = transcriptsInternal$xscale,
yscale = yscale,
just = transcriptsInternal$just,
name = vp_name
)
}
backgroundGrob <- rectGrob(gp = gpar(
fill = transcriptsInternal$bg,
col = NA
), name = "background")
assign("transcript_grobs", gTree(vp = vp, children = gList(backgroundGrob)),
envir = pgEnv
)
if (is.null(transcriptsInternal$labels)) {
textHeight <- unit(0, "npc")
} else {
textHeight <- heightDetails(textGrob(
label = "A",
gp = gpar(fontsize = transcriptsInternal$fontsize)
))
}
if (is.null(transcripts$x) & is.null(transcripts$y)) {
pushViewport(vp)
boxHeight <- convertHeight(transcriptsInternal$boxHeight,
unitTo = "npc", valueOnly = TRUE
)
spaceHeight <- boxHeight * (transcriptsInternal$spaceHeight)
textHeight <- convertHeight(textHeight,
unitTo = "npc",
valueOnly = TRUE
)
upViewport()
unit <- "npc"
} else {
boxHeight <- convertHeight(transcriptsInternal$boxHeight,
unitTo = get("page_units", envir = pgEnv),
valueOnly = TRUE
)
spaceHeight <- boxHeight * (transcriptsInternal$spaceHeight)
textHeight <- convertHeight(textHeight,
unitTo = get("page_units", envir = pgEnv),
valueOnly = TRUE
)
unit <- get("page_units", envir = pgEnv)
}
maxRows <- floor(height / (boxHeight + spaceHeight +
textHeight + 0.25 * textHeight))
wiggle <- abs(transcripts$chromend - transcripts$chromstart) *
transcriptsInternal$spaceWidth
if (transcriptsInternal$strandSplit == FALSE) {
repData <- data[duplicated(data$TXNAME) == FALSE, ]
repData <- defaultGenePriorities(
data = repData,
assembly = transcripts$assembly,
transcript = TRUE
)
rowData <- assignRows(data = repData[,c("TXSTART", "TXEND", "TXID")],
maxRows = maxRows,
wiggle = wiggle,
rowCol = 3,
limitLabel = transcriptsInternal$limitLabel,
gTree = "transcript_grobs")
rowData <- suppressMessages(dplyr::left_join(
x = data,
y = rowData[,c("row", "TXID")],
by = "TXID"
))
rowData$y <- rowData$row * (boxHeight + spaceHeight + textHeight +
0.25 * textHeight)
} else {
repPos <- posStrand[duplicated(posStrand$TXNAME) == FALSE, ]
repMin <- minStrand[duplicated(minStrand$TXNAME) == FALSE, ]
repPos <- defaultGenePriorities(
data = repPos,
assembly = transcripts$assembly,
transcript = TRUE
)
repMin <- defaultGenePriorities(
data = repMin,
assembly = transcripts$assembly,
transcript = TRUE
)
posData <- assignRows(data = repPos[,c("TXSTART", "TXEND", "TXID")],
maxRows = floor(maxRows / 2),
wiggle = wiggle, rowCol = 3,
limitLabel = transcriptsInternal$limitLabel,
gTree = "transcript_grobs")
minData <- assignRows(data = repMin[,c("TXSTART", "TXEND", "TXID")],
maxRows = floor(maxRows / 2),
wiggle = wiggle, rowCol = 3,
limitLabel = transcriptsInternal$limitLabel,
gTree = "transcript_grobs",
side = "bottom")
posData <- suppressMessages(dplyr::left_join(
x = posStrand,
y = posData[,c("row", "TXID")],
by = "TXID"
))
minData <- suppressMessages(dplyr::left_join(
x = minStrand,
y = minData[,c("row", "TXID")],
by = "TXID"
))
posData$y <- (0.5 * spaceHeight) + posData$row *
(boxHeight + spaceHeight + textHeight + 0.25 * textHeight)
minData$y <- ((0.5 * spaceHeight + boxHeight + textHeight +
0.25 * textHeight) + minData$row *
(boxHeight + spaceHeight +
textHeight + 0.25 * textHeight)) * -1
rowData <- rbind(posData, minData)
}
if (nrow(rowData) > 0) {
if ((transcripts$chromend - transcripts$chromstart) >= 25000000) {
transcriptLine <- rectGrob(
x = rowData$TXSTART,
y = rowData$y,
width = rowData$TXEND - rowData$TXSTART,
height = boxHeight,
just = c("left", "bottom"),
gp = gpar(
fill = rowData$color,
col = rowData$color,
lwd = transcriptsInternal$stroke
),
default.units = "native"
)
} else {
transcriptLine <- rectGrob(
x = rowData$TXSTART,
y = rowData$y + 0.5 * boxHeight,
width = rowData$TXEND - rowData$TXSTART,
height = boxHeight * 0.2,
just = "left",
gp = gpar(
fill = rowData$color,
col = rowData$color,
lwd = transcriptsInternal$stroke
),
default.units = "native"
)
transcriptExons <- rectGrob(
x = rowData$EXONSTART,
y = rowData$y + 0.5 * boxHeight,
width = rowData$EXONEND - rowData$EXONSTART,
height = boxHeight * 0.65,
just = "left",
gp = gpar(fill = rowData$color, col = NA),
default.units = "native"
)
assign("transcript_grobs",
addGrob(get("transcript_grobs", envir = pgEnv),
child = transcriptExons
),
envir = pgEnv
)
cdsData <- rowData[which(!is.na(rowData$CDSSTART)), ]
if (nrow(cdsData) > 0) {
transcriptCds <- rectGrob(
x = cdsData$CDSSTART,
y = cdsData$y + 0.5 * boxHeight,
width = cdsData$CDSEND - cdsData$CDSSTART,
height = boxHeight,
just = "left",
gp = gpar(
fill = cdsData$color,
col = cdsData$color,
lwd = 1.25
),
default.units = "native"
)
assign("transcript_grobs",
addGrob(get("transcript_grobs", envir = pgEnv),
child = transcriptCds
),
envir = pgEnv
)
}
}
assign("transcript_grobs",
addGrob(get("transcript_grobs", envir = pgEnv),
child = transcriptLine
),
envir = pgEnv
)
if (!is.null(transcriptsInternal$labels)) {
transcriptNames <- rowData[duplicated(rowData$TXNAME) == FALSE, ]
transcriptNames$labelLoc <- rowMeans(
transcriptNames[c("TXSTART", "TXEND")]
)
if (transcriptsInternal$labels == "transcript") {
label <- transcriptNames$TXNAME
} else if (transcriptsInternal$labels == "gene") {
label <- transcriptNames[[
transcripts$assembly$display.column]]
} else {
label <- paste0(
transcriptNames[[
transcripts$assembly$display.column]],
":", transcriptNames$TXNAME
)
}
checkedLabels <- apply(data.frame(
"label" = label,
"labelLoc" =
transcriptNames$labelLoc
),
1, cutoffLabel,
fontsize = transcriptsInternal$fontsize,
xscale = transcriptsInternal$xscale,
vp = vp, unit = unit
)
transcriptNames$label <- checkedLabels
transcriptNames <- transcriptNames[!is.na(transcriptNames$label), ]
if (nrow(transcriptNames) > 0) {
transcript_names <- textGrob(
label = transcriptNames$label,
x = transcriptNames$labelLoc,
y = transcriptNames$y + boxHeight + textHeight * 0.25,
just = "bottom",
gp = gpar(
col = transcriptNames$color,
fontsize = transcriptsInternal$fontsize
),
default.units = "native",
check.overlap = TRUE
)
assign("transcript_grobs",
addGrob(get("transcript_grobs", envir = pgEnv),
child = transcript_names
),
envir = pgEnv
)
}
}
}
if (transcriptsInternal$draw == TRUE) {
grid.draw(get("transcript_grobs", envir = pgEnv))
}
transcripts$grobs <- get("transcript_grobs", envir = pgEnv)
message("transcripts[", vp$name, "]")
invisible(transcripts)
} |
SetTextContrastColor = function(color)
{
ifelse( mean(grDevices::col2rgb(color)) > 127, "black", "white")
} |
sd_neighbor = function (data_year = "2019", school_district = NULL, table_vars = c('Name', 'Enrollment', 'Poverty Rate', 'Percent Nonwhite', 'Local Revenue PP', 'State Revenue PP', 'Type')) {
dist_list <- neigh_diff(data_year='2019', diff_var="Percentage Point Difference in Poverty Rate", type = "all") %>%
dplyr::mutate(NCESID_1 = stringr::str_pad(NCESID_1, 7, pad="0"),
NCESID_2 = stringr::str_pad(NCESID_2, 7, pad="0"))
dist_list_1 <- dist_list %>%
dplyr::select(NCESID = NCESID_1) %>%
dplyr::distinct()
dist_list_2 <- dist_list %>%
dplyr::select(NCESID = NCESID_2) %>%
dplyr::distinct()
listid <- dplyr::bind_rows(dist_list_1, dist_list_2) %>%
dplyr::distinct()
ncesid <- listid$NCESID
to_pull <- c("District Name",
"District Enrollment, CCD",
"District Poverty Rate",
"District Percent Nonwhite",
"District Local Revenue PP",
"District State Revenue PP",
"District Level",
"Neighbor Name",
"Neighbor Enrollment, CCD",
"Neighbor Poverty Rate",
"Neighbor Percent Nonwhite",
"Neighbor Local Revenue PP",
"Neighbor State Revenue PP",
"Neighbor Level")
to_default <- c('Name', 'Enrollment', 'Poverty Rate', 'Percent Nonwhite', 'Local Revenue PP', 'State Revenue PP', "Type")
print_names <- c("Name",
"County",
"Enrollment",
"Percent FRL",
"Poverty Rate",
"Percent Nonwhite",
"Local Revenue PP",
"State Revenue PP",
"Total Revenue PP",
"Median Household Income",
"Median Property Value",
"Type")
good <- c('Name', 'County', 'Enrollment', 'Poverty Rate', 'Percent Nonwhite', 'Percent FRL',
'Local Revenue PP', 'State Revenue PP', 'Total Revenue PP',
'Median Household Income', 'Median Property Value', 'Type')
if (as.numeric(data_year)<2013) {
message("Error: Master datasets are only available for years 2013 through 2019")
}
else if (as.numeric(data_year)>2019) {
message("Error: Master datasets are only available for years 2013 through 2019")
}
else if (is.null(school_district)) {
message( "To generate a table, specify a school district by its NCESID.
If you do not know the NCESID of a school district, use masterpull() to search for your district.")
}
else if(school_district %in% ncesid == FALSE) {
message( "The district you specified is not available. To generate a table, specify a school district by its NCESID.
If you do not know the NCESID of a school district, use masterpull() to search for your district.")
}
else if(setequal(intersect(table_vars, good), table_vars) == FALSE){
message("Use one or more of the following variables to generate a table:
table_vars = c('Name', 'County', 'Enrollment', 'Poverty Rate', 'Percent Nonwhite', 'Percent FRL',
'Local Revenue PP', 'State Revenue PP', 'Total Revenue PP',
'Median Property Value', 'Median Household Income', 'Type')")
}
else {
school_district
select_cols <- if (!setequal(table_vars, to_default)) {
for (i in 1:length(table_vars)) {
table_iterate <- table_vars[i]
if ("Name" %in% table_iterate) {
temp_vars <- c("District Name", "Neighbor Name")
}
else if ("Enrollment" %in% table_iterate) {
temp_vars <- c("District Enrollment, CCD", "Neighbor Enrollment, CCD")
}
else if ("County" %in% table_iterate) {
temp_vars <- c("District County", "Neighbor County")
}
else if ("Percent FRL" %in% table_iterate) {
temp_vars <- c("District Percent FRL", "Neighbor Percent FRL")
}
else if ("Poverty Rate" %in% table_iterate) {
temp_vars <- c("District Poverty Rate", "Neighbor Poverty Rate")
}
else if ("Percent Nonwhite" %in% table_iterate) {
temp_vars <- c("District Percent Nonwhite", "Neighbor Percent Nonwhite")
}
else if ("Local Revenue PP" %in% table_iterate) {
temp_vars <- c("District Local Revenue PP", "Neighbor Local Revenue PP")
}
else if ("State Revenue PP" %in% table_iterate) {
temp_vars <- c("District State Revenue PP", "Neighbor State Revenue PP")
}
else if ("Total Revenue PP" %in% table_iterate) {
temp_vars <- c("District Total Revenue PP", "Neighbor Total Revenue PP")
}
else if ("Median Household Income" %in% table_iterate){
temp_vars <- c("District MHI", "Neighbor MHI")
}
else if("Median Property Value" %in% table_iterate) {
temp_vars <- c("District MPV", "Neighbor MPV")
}
else if("Type" %in% table_iterate) {
temp_vars <- c("District Level", "Neighbor Level")
}
else {
print(print_names)
message("Please see above for variables you can use to generate a table")
}
if(i == 1) {
additional_vars <- temp_vars
}
else{
additional_vars <- rbind(additional_vars, temp_vars)
}
}
additional_vars <- as.vector(t(additional_vars))
}
else {
to_pull
}
table_data <- neigh_diff(data_year, diff_var="Percentage Point Difference in Poverty Rate", type = "all") %>%
dplyr::mutate(NCESID_1 = stringr::str_pad(NCESID_1, 7, pad="0"),
NCESID_2 = stringr::str_pad(NCESID_2, 7, pad="0")) %>%
dplyr::filter(NCESID_1 == school_district | NCESID_2 == school_district) %>%
dplyr::mutate(code = ifelse(NCESID_1 == school_district, 1,
ifelse(NCESID_2 == school_district, 2, 0))) %>%
dplyr::select(all_of(select_cols), code)
dist1 <- table_data %>%
dplyr::filter(code==1) %>%
dplyr::select(matches("District") | matches("code")) %>%
dplyr::distinct()
dist2 <- table_data %>%
dplyr::filter(code==2) %>%
dplyr::select(matches("Neighbor") | matches("code")) %>%
dplyr::distinct()
colnames(dist1) <- sub("District ", "", colnames(dist1))
colnames(dist2) <- sub("Neighbor ", "", colnames(dist2))
dist <- bind_rows(dist1, dist2)
table_data_dist <- table_data %>%
dplyr::select(-matches("District")) %>%
dplyr::select(-code, everything())
colnames(table_data_dist) <- sub("Neighbor ", "", colnames(table_data_dist))
table_data_neighb <- table_data %>%
dplyr::select(-matches("Neighbor")) %>%
dplyr::select(-code, everything())
colnames(table_data_neighb) <- sub("District ", "", colnames(table_data_neighb))
table_reform <- bind_rows(dist, table_data_dist, table_data_neighb) %>%
dplyr::distinct() %>%
dplyr::select(-code) %>%
dplyr::distinct()
if (nrow(table_reform)==1) {
message("NOTE:: Your table has one row because the school district does not have any neighbors of the same type. For more information on neighbor types, see neigh_diff documentation.")
}
else(
message("")
)
table_reform <- if (!is.null(table_reform$`Percent Nonwhite`)) {
table_reform <- table_reform %>%
dplyr::mutate(`Percent Nonwhite` = scales::percent(round2(`Percent Nonwhite`, 2), accuracy = 1L))
} else {
table_reform
}
table_reform <- if (!is.null(table_reform$`Poverty Rate`)) {
table_reform <- table_reform %>%
dplyr::mutate(`Poverty Rate` = scales::percent(round2(`Poverty Rate`, 2), accuracy = 1L ))
} else {
table_reform
}
table_reform <- if (!is.null(table_reform$`Percent FRL`)) {
table_reform <- table_reform %>%
dplyr::mutate(`Percent FRL` = scales::percent(round2(`Percent FRL`, 2), accuracy = 1L ))
} else {
table_reform
}
table_reform <- if (!is.null(table_reform$`Local Revenue PP`)) {
table_reform <- table_reform %>%
dplyr::mutate(`Local Revenue PP` = scales::dollar(round2(`Local Revenue PP`, 0)))
} else {
table_reform
}
table_reform <- if (!is.null(table_reform$`State Revenue PP`)) {
table_reform <- table_reform %>%
dplyr::mutate(`State Revenue PP` = scales::dollar(round2(`State Revenue PP`, 0)))
} else {
table_reform
}
table_reform <- if (!is.null(table_reform$`Total Revenue PP`)) {
table_reform <- table_reform %>%
dplyr::mutate(`Total Revenue PP` = scales::dollar(round2(`Total Revenue PP`, 0)))
} else {
table_reform
}
table_reform <- if (!is.null(table_reform$`MHI`)) {
table_reform <- table_reform %>%
dplyr::mutate(MHI = scales::dollar(round2(MHI, 0)))
} else {
table_reform
}
table_reform <- if (!is.null(table_reform$`MPV`)) {
table_reform <- table_reform %>%
dplyr::mutate(MPV = scales::dollar(round2(MPV, 0)))
} else {
table_reform
}
table_reform <- if (!is.null(table_reform$`Enrollment, CCD`)) {
table_reform <- table_reform %>%
dplyr::mutate(`Enrollment, CCD` = scales::comma(`Enrollment, CCD`))
}
else {
table_reform
}
search_for_these <- c("Name", "County",
"Local Revenue PP", "State Revenue PP", "Total Revenue PP",
"Enrollment, CCD",
"Percent FRL",
"Percent Nonwhite",
"Poverty Rate",
"MPV", "MHI", "Level")
replace_with_these <- c("Name", "County",
"Local Revenue, Per Pupil", "State Revenue, Per Pupil", "Total Revenue, Per Pupil",
"Enrollment",
"Percent FRL",
"Percent Nonwhite",
"Poverty Rate",
"Median Property Value", "Median Household Income", "Type")
found <- match(colnames(table_reform), search_for_these, nomatch = 0)
colnames(table_reform)[colnames(table_reform) %in% search_for_these] <- replace_with_these[found]
NameId = table_reform$Name[1]
NameId = substr(NameId, 0, 30)
return(table_reform)
}
} |
"cnvrt.coords" <-
function(x,y=NULL,input=c('usr','plt','fig','dev','tdev')) {
warning('this function is now depricated, use grconvertX instead')
input <- match.arg(input)
xy <- xy.coords(x,y, recycle=TRUE)
cusr <- par('usr')
cplt <- par('plt')
cfig <- par('fig')
cdin <- par('din')
comi <- par('omi')
cdev <- c(comi[2]/cdin[1],(cdin[1]-comi[4])/cdin[1],
comi[1]/cdin[2],(cdin[2]-comi[3])/cdin[2])
if(input=='usr'){
usr <- xy
plt <- list()
plt$x <- (xy$x-cusr[1])/(cusr[2]-cusr[1])
plt$y <- (xy$y-cusr[3])/(cusr[4]-cusr[3])
fig <- list()
fig$x <- plt$x*(cplt[2]-cplt[1])+cplt[1]
fig$y <- plt$y*(cplt[4]-cplt[3])+cplt[3]
dev <- list()
dev$x <- fig$x*(cfig[2]-cfig[1])+cfig[1]
dev$y <- fig$y*(cfig[4]-cfig[3])+cfig[3]
tdev <- list()
tdev$x <- dev$x*(cdev[2]-cdev[1])+cdev[1]
tdev$y <- dev$y*(cdev[4]-cdev[3])+cdev[3]
return( list( usr=usr, plt=plt, fig=fig, dev=dev, tdev=tdev ) )
}
if(input=='plt') {
plt <- xy
usr <- list()
usr$x <- plt$x*(cusr[2]-cusr[1])+cusr[1]
usr$y <- plt$y*(cusr[4]-cusr[3])+cusr[3]
fig <- list()
fig$x <- plt$x*(cplt[2]-cplt[1])+cplt[1]
fig$y <- plt$y*(cplt[4]-cplt[3])+cplt[3]
dev <- list()
dev$x <- fig$x*(cfig[2]-cfig[1])+cfig[1]
dev$y <- fig$y*(cfig[4]-cfig[3])+cfig[3]
tdev <- list()
tdev$x <- dev$x*(cdev[2]-cdev[1])+cdev[1]
tdev$y <- dev$y*(cdev[4]-cdev[3])+cdev[3]
return( list( usr=usr, plt=plt, fig=fig, dev=dev, tdev=tdev ) )
}
if(input=='fig') {
fig <- xy
plt <- list()
plt$x <- (fig$x-cplt[1])/(cplt[2]-cplt[1])
plt$y <- (fig$y-cplt[3])/(cplt[4]-cplt[3])
usr <- list()
usr$x <- plt$x*(cusr[2]-cusr[1])+cusr[1]
usr$y <- plt$y*(cusr[4]-cusr[3])+cusr[3]
dev <- list()
dev$x <- fig$x*(cfig[2]-cfig[1])+cfig[1]
dev$y <- fig$y*(cfig[4]-cfig[3])+cfig[3]
tdev <- list()
tdev$x <- dev$x*(cdev[2]-cdev[1])+cdev[1]
tdev$y <- dev$y*(cdev[4]-cdev[3])+cdev[3]
return( list( usr=usr, plt=plt, fig=fig, dev=dev, tdev=tdev ) )
}
if(input=='dev'){
dev <- xy
fig <- list()
fig$x <- (dev$x-cfig[1])/(cfig[2]-cfig[1])
fig$y <- (dev$y-cfig[3])/(cfig[4]-cfig[3])
plt <- list()
plt$x <- (fig$x-cplt[1])/(cplt[2]-cplt[1])
plt$y <- (fig$y-cplt[3])/(cplt[4]-cplt[3])
usr <- list()
usr$x <- plt$x*(cusr[2]-cusr[1])+cusr[1]
usr$y <- plt$y*(cusr[4]-cusr[3])+cusr[3]
tdev <- list()
tdev$x <- dev$x*(cdev[2]-cdev[1])+cdev[1]
tdev$y <- dev$y*(cdev[4]-cdev[3])+cdev[3]
return( list( usr=usr, plt=plt, fig=fig, dev=dev, tdev=tdev ) )
}
if(input=='tdev'){
tdev <- xy
dev <- list()
dev$x <- (tdev$x-cdev[1])/(cdev[2]-cdev[1])
dev$y <- (tdev$y-cdev[3])/(cdev[4]-cdev[3])
fig <- list()
fig$x <- (dev$x-cfig[1])/(cfig[2]-cfig[1])
fig$y <- (dev$y-cfig[3])/(cfig[4]-cfig[3])
plt <- list()
plt$x <- (fig$x-cplt[1])/(cplt[2]-cplt[1])
plt$y <- (fig$y-cplt[3])/(cplt[4]-cplt[3])
usr <- list()
usr$x <- plt$x*(cusr[2]-cusr[1])+cusr[1]
usr$y <- plt$y*(cusr[4]-cusr[3])+cusr[3]
tdev <- list()
tdev$x <- dev$x*(cdev[2]-cdev[1])+cdev[1]
tdev$y <- dev$y*(cdev[4]-cdev[3])+cdev[3]
return( list( usr=usr, plt=plt, fig=fig, dev=dev, tdev=tdev ) )
}
} |
"pargpaRC" <-
function(lmom, zeta=1, xi=NULL,
lower=-1, upper=20, checklmom=TRUE,...) {
para <- rep(NA,3)
names(para) <- c("xi","alpha","kappa")
if(length(lmom$source) == 1 && lmom$source == "TLmoms") {
if(lmom$trim != 0) {
warning("Attribute of TL-moments is not trim=0--can not complete parameter estimation")
return()
}
}
if(length(lmom$L1) == 0) {
lmom <- lmorph(lmom)
}
if(checklmom & ! are.lmom.valid(lmom)) {
warning("B-type L-moments are invalid")
return()
}
L1 <- lmom$L1
L2 <- lmom$L2
T3 <- lmom$TAU3
"mr" <- function(r,z,k) { (1 - (1-z)^(r+k))/(r+k) }
"ft3" <- function(x) {
mr1 <- mr(1,zeta,x)
mr2 <- mr(2,zeta,x)
mr3 <- mr(3,zeta,x)
tau3 <- (mr1 - 3*mr2 + 2*mr3)/(mr1 - mr2)
return( abs(T3 - tau3) )
}
"fl2" <- function(x,lhs) {
mr1 <- mr(1,zeta,x)
mr2 <- mr(2,zeta,x)
rhs <- mr1/(mr1 - mr2)
return( abs(lhs - rhs) )
}
if(is.null(xi)) {
optim <- optimize(ft3, lower=lower, upper=upper)
K <- optim$minimum
mr1 <- mr(1, zeta, K)
mr2 <- mr(2, zeta, K)
para[3] <- K
para[2] <- L2/(mr1 - mr2)
para[1] <- L1 - para[2]*mr1
}
else {
LHS <- (L1 - xi)/L2
optim <- optimize(fl2, lower=lower, upper=upper, lhs=LHS)
K <- optim$minimum
mr1 <- mr(1, zeta, K)
mr2 <- mr(2, zeta, K)
para[3] <- K
para[2] <- L2/(mr1 - mr2)
para[1] <- xi
}
names(optim$objective) <- NULL
z <- list(type="gpa",
para=para, zeta=zeta, source="pargpaRC",
optim=optim)
return(z)
} |
method = "GenSA"
control = list(maxit = 100)
MaxMC:::get_control(method = method, control = control) |
library(testit)
assert(
'find_globals() identifies global variables',
identical(find_globals('x=1'), character(0)),
identical(find_globals('a=1; b=a; d=qwer'), 'qwer'),
identical(find_globals('a=function(){f=2;g}'), 'g'),
identical(find_globals('z=function(){y=1};y'), 'y'),
identical(find_globals(c('a=1%*%1%o%2 %in% d', 'b=d%%10+3%/%2-z[1:3]')), c('d', 'z'))
)
assert(
'find_symbols() identifies all symbols',
find_symbols('x = x + 1; rnorm(1, std = z)') %==% c('x', 'rnorm', 'z')
)
knit_lazy = function(lazy = TRUE) {
in_dir(tempdir(), {
txt = c(sprintf('```{r test, cache=TRUE, cache.lazy=%s}', lazy),
'x1 = Sys.time()', '```')
knit(text = txt, quiet = TRUE)
x2 = x1
Sys.sleep(0.1)
knit(text = txt, quiet = TRUE)
x1 == x2
})
}
assert(
'cache.lazy = TRUE/FALSE works',
knit_lazy(TRUE), knit_lazy(FALSE)
)
knit_code$set(a = 1, b = 2, c = 3)
assert('dep_prev() sets dependencies on previous chunks', {
(dep_list$get() %==% list())
dep_prev()
(dep_list$get() %==% list(a = c('b', 'c'), b = 'c'))
})
dep_list$restore()
knit_code$restore() |
"boa.menu.stats" <-
function()
{
mtitle <- "\nDESCRIPTIVE STATISTICS MENU\n---------------------------"
choices <- c("Back",
"---------------------------------------+",
"Autocorrelations |",
"Correlation Matrix |",
"Highest Probability Density Intervals |",
"Summary Statistics |",
"Options... |",
"---------------------------------------+")
idx <- 1
while(idx > 0) {
idx <- menu(choices, title = mtitle)
switch(idx,
"1" = idx <- -1,
"2" = NULL,
"3" = boa.print.acf(),
"4" = boa.print.cor(),
"5" = boa.print.hpd(),
"6" = boa.print.stats(),
"7" = boa.menu.setpar("Descriptive"),
"8" = NULL
)
}
return(abs(idx))
} |
tailindex_plain <- function(sevdist){
return(switch(sevdist$par[[6]],
"gpd" = sevdist$par[[5]][3],
"lgamma" = 1 / sevdist$par[[5]][2],
"gh" = 1 / sevdist$par[[5]][2],
"lnorm" = 0,
"weibull" = 0))
}
tailindex_spliced <- function(sevdist){
return(switch(sevdist$par[[1]][[6]],
"gpd" = sevdist$par[[1]][[5]][3],
"lgamma" = 1 / sevdist$par[[1]][[5]][2],
"gh" = 1 / sevdist$par[[1]][[5]][2],
"lnorm" = 0,
"weibull" = 0))
}
tailindex_mixing <- function(sevdist){
return(switch(sevdist$par[[1]][[6]],
"gpd" = sevdist$par[[1]][[5]][3],
"lgamma" = 1 / sevdist$par[[1]][[5]][2],
"gh" = 1 / sevdist$par[[1]][[5]][2],
"lnorm" = 0,
"weibull" = 0))
}
sevdist_xi_plain <- function(xi, sevdist){
sevdist_tmp <- sevdist
if(sevdist$par[[6]] == "gpd"){
sevdist_tmp$par[[5]][3] <- xi
} else if(sevdist$par[[6]] %in% c("lgamma", "gh")){
sevdist_tmp$par[[5]][2] <- 1/xi
}
sevdist_tmp$par[[2]] <- function(q) {evaluate("p", sevdist_tmp$par[[6]], sevdist_tmp$par[[5]], q)}
sevdist_tmp$par[[3]] <- function(p) {evaluate("q", sevdist_tmp$par[[6]], sevdist_tmp$par[[5]], p)}
return(sevdist_tmp)
}
sevdist_xi_spliced <- function(xi, sevdist){
sevdist_tmp <- sevdist
if(sevdist$par[[1]][[6]] == "gpd"){
sevdist_tmp$par[[1]][[5]][3] <- xi
} else if(sevdist$par[[1]][[6]] %in% c("lgamma", "gh")){
sevdist_tmp$par[[1]][[5]][2] <- 1/xi
}
pdisttail <- function(q) {do.call(paste0("p", sevdist_tmp$par[[1]][[6]]), c(list(q), sevdist_tmp$par[[1]][[5]]))}
qdisttail <- function(p) {do.call(paste0("q", sevdist_tmp$par[[1]][[6]]), c(list(p), sevdist_tmp$par[[1]][[5]]))}
sevdist_tmp$par[[1]][[2]] <- function(q) {ifelse(q>sevdist_tmp$thresh, (pdisttail(q) - pdisttail(sevdist_tmp$thresh))/(1-pdisttail(sevdist_tmp$thresh)), 0)}
sevdist_tmp$par[[1]][[3]] <- function(p) {qdisttail(pdisttail(sevdist_tmp$thresh) + p * (1 - pdisttail(sevdist_tmp$thresh)))}
return(sevdist_tmp)
}
sevdist_xi_mixing <- function(xi, sevdist){
sevdist_tmp <- sevdist
if(sevdist$par[[1]][[6]] == "gpd"){
sevdist_tmp$par[[1]][[5]][3] <- xi
} else if(sevdist$par[[1]][[6]] %in% c("lgamma", "gh")){
sevdist_tmp$par[[1]][[5]][2] <- 1/xi
}
pdisttail <- function(q) {do.call(paste0("p", sevdist_tmp$par[[1]][[6]]), c(list(q), sevdist_tmp$par[[1]][[5]]))}
qdisttail <- function(p) {do.call(paste0("q", sevdist_tmp$par[[1]][[6]]), c(list(p), sevdist_tmp$par[[1]][[5]]))}
sevdist_tmp$par[[1]][[2]] <- function(q) {evaluate("p", sevdist$par[[1]][[6]], sevdist_tmp$par[[1]][[4]], q)}
sevdist_tmp$par[[1]][[3]] <- function(p) {evaluate("q", sevdist$par[[1]][[6]], sevdist_tmp$par[[1]][[4]], p)}
return(sevdist_tmp)
}
correction_high <- function(xi, sevdist, type, mean_freq, disp_freq, alpha){
sevdist_xi <- do.call(paste("sevdist_xi", as.character(type), sep = "_"), list(xi, sevdist))
basic_SLA <- qsevdist(1 - (1-alpha)/mean_freq, sevdist_xi)
c_xi <- (1-xi) /2 /gamma(1-2/xi) * (gamma(1-1/xi)^2)
return((mean_freq + disp_freq -1) * (1-alpha) / mean_freq * basic_SLA * c_xi / (1-1/xi))
}
correction_low <- function(xi, sevdist, type, mean_freq, disp_freq){
sevdist_xi <- do.call(paste("sevdist_xi", as.character(type), sep = "_"), list(xi, sevdist))
mean_sev <- try(pracma::quadinf(function(x){1-psevdist(x, sevdist_xi)}, xa = 0, xb = Inf)$Q, silent=TRUE)
return((mean_freq + disp_freq -1) * mean_sev)
}
correction_1 <- function(xi, sevdist, type, mean_freq, disp_freq, alpha){
sevdist_xi <- do.call(paste("sevdist_xi", as.character(type), sep = "_"), list(xi, sevdist))
basic_SLA <- qsevdist(1 - (1-alpha)/mean_freq, sevdist_xi)
return((mean_freq + disp_freq -1) * pracma::integral(function(x){1-psevdist(x, sevdist_xi)}, xmin = 0, xmax = basic_SLA, method = "Kronrod"))
}
spline_SLA <- function(sevdist, xi_low, xi_high, type, mean_freq, disp_freq, alpha){
grid_xi_high <- seq(xi_high, xi_high + 0.2, 0.05)
grid_xi_low <- seq(xi_low - 0.2, xi_low, 0.05)
grid_xi <- c(grid_xi_low, 1, grid_xi_high)
spline_high <- sapply(grid_xi_high, correction_high, sevdist, type, mean_freq, disp_freq, alpha)
spline_low <- sapply(grid_xi_low, correction_low, sevdist, type, mean_freq, disp_freq)
spline_1 <- correction_1(1, sevdist, type, mean_freq, disp_freq, alpha)
spline_values <- c(spline_low, spline_1, spline_high)
correct_spline <- try(splinefun(grid_xi, spline_values, method = "hyman"), silent=TRUE)
return(correct_spline)
}
sla <- function(opriskmodel, alpha, xi_low = 0.8, xi_high = 1.2, plot = FALSE){
approx <- list()
for(cell in 1:length(opriskmodel)){
approx[[cell]] <- list()
approx[[cell]]$interpolation <- FALSE
cell_type <- (opriskmodel[[cell]]$sevdist)$type
mean_freq <- switch(opriskmodel[[cell]]$freqdist[[1]],
"pois" = opriskmodel[[cell]]$freqdist[[2]],
"nbinom" = opriskmodel[[cell]]$freqdist[[2]][1]*(1-opriskmodel[[cell]]$freqdist[[2]][2])/opriskmodel[[cell]]$freqdist[[2]][2])
disp_freq <- switch(opriskmodel[[cell]]$freqdist[[1]],
"pois" = 1,
"nbinom" = 1/opriskmodel[[cell]]$freqdist[[2]][2])
simple_VaR <- qsevdist(1 - (1-alpha)/mean_freq, opriskmodel[[cell]]$sevdist)
mean_sev <- try(pracma::quadinf(function(x){x*dsevdist(x, opriskmodel[[cell]]$sevdist)}, xa = 0, xb = Inf)$Q, silent=FALSE)
tailindex <- do.call(paste("tailindex", as.character(cell_type), sep = "_"), list(opriskmodel[[cell]]$sevdist))
if(!is.null(tailindex)){
if(tailindex <= xi_low){
correction <- (mean_freq + disp_freq -1) * mean_sev
} else if(tailindex >= xi_high){
c_xi <- (1-tailindex) /2 /gamma(1-2/tailindex) * (gamma(1-1/tailindex)^2)
correction <- (mean_freq + disp_freq -1) * (1-alpha) / mean_freq * simple_VaR * c_xi / (1-1/tailindex)
} else if(tailindex == 1){
correction <- (mean_freq + disp_freq -1) * (pracma::integral(function(x){1-psevdist(x, opriskmodel[[cell]]$sevdist)}, xmin = 0, xmax = simple_VaR, method = "Kronrod"))
} else {
correction_spline <- spline_SLA(opriskmodel[[cell]]$sevdist, xi_low, xi_high, cell_type, mean_freq, disp_freq, alpha)
xi_high_tmp <- xi_high
xi_low_tmp <- xi_low
while(class(correction_spline) == "try-error"){
xi_high_tmp <- xi_high_tmp + 0.05
xi_low_tmp <- xi_low_tmp - 0.05
correction_spline <- spline_SLA(opriskmodel[[cell]]$sevdist, xi_low_tmp, xi_high_tmp, cell_type, mean_freq, disp_freq, alpha)
}
correction <- correction_spline(tailindex)
approx[[cell]]$interpolation <- TRUE
}
if(approx[[cell]]$interpolation == TRUE && plot == TRUE) {
grid_high <- seq(1.005, 1.5, 0.01)
grid_low <- seq(0.5, 0.995, 0.01)
grid <- c(grid_low, 1, grid_high)
correction_high_values <- sapply(grid_high, correction_high, opriskmodel[[cell]]$sevdist, cell_type, mean_freq, disp_freq, alpha)
correction_low_values <- sapply(grid_low, correction_low, opriskmodel[[cell]]$sevdist, cell_type, mean_freq, disp_freq)
plot(grid_low, correction_low_values,
xlim=c(0.5, 1.5),
ylim=c(min(correction_low_values, correction_high_values), max(correction_low_values, correction_high_values)),
type="l", col="royalblue", lwd = 2,
xlab = expression(xi), ylab = "SLA correction term")
lines(grid_high, correction_high_values, col="royalblue", lwd = 2)
abline(v = 1, lty = "dashed")
if(!exists("xi_low_tmp")){
xi_low_tmp <- xi_low
xi_high_tmp <- xi_high
}
curve(correction_spline, from = xi_low_tmp, to = xi_high_tmp, lty = "dashed",
col="darkorange4", lwd = 2, add = TRUE)
points(1, correction_spline(1), col = "darkorange", pch = 19)
}
}
else{
correction <- (mean_freq + disp_freq -1) * mean_sev
if(!is.numeric(correction)) correction <- 0
approx[[cell]]$interpolation <- FALSE
}
approx[[cell]]$value <- simple_VaR + correction
}
output = NULL
for(i in 1:length(approx)){
output = rbind(output, c(approx[[i]]$value, as.character(approx[[i]]$interpolation)))
}
cat("OpRiskmodel - SLA: ", alpha*100, "% \n")
cat("----------------------------------------------\n")
colnames(output) = c("VaR", "Interpolation")
rownames(output) = paste("Cell", c(seq(1, length(approx), by=1)), ": ")
prmatrix(output, quote = FALSE)
} |
ES.SE <- function(data, p = 0.95,
se.method = c("IFiid","IFcor","IFcorAdapt","IFcorPW","BOOTiid","BOOTcor")[1:2],
cleanOutliers = FALSE, fitting.method = c("Exponential", "Gamma")[1], d.GLM.EN = 5,
freq.include = c("All","Decimate","Truncate")[1], freq.par = 0.5,
corOut = c("none","retCor","retIFCor", "retIFCorPW")[1],
return.coef = FALSE,
...){
if(is.null(dim(data)) || ncol(data) == 1)
point.est <- ES(data, alpha.ES = 1-p) else
point.est <- apply(data, 2, function(x) ES(x, alpha.ES = 1-p))
if(is.null(se.method)){
return(point.est)
} else{
SE.out <- list(ES = point.est)
for(mymethod in se.method){
SE.out[[mymethod]] <- EstimatorSE(data, estimator.fun = "ES", alpha.ES = 1-p,
se.method = mymethod,
cleanOutliers = cleanOutliers,
fitting.method = fitting.method, d.GLM.EN = d.GLM.EN,
freq.include = freq.include, freq.par = freq.par,
return.coef = return.coef,
...)
}
SE.out <- Add_Correlations(SE.out = SE.out, data = data, cleanOutliers = cleanOutliers, corOut = corOut, IF.func = IF.ES, ...)
return(SE.out)
}
} |
library(MixSIAR)
mix.filename <- system.file("extdata", "lake_consumer.csv", package = "MixSIAR")
mix <- load_mix_data(filename=mix.filename,
iso_names=c("d13C","d15N"),
factors=NULL,
fac_random=NULL,
fac_nested=NULL,
cont_effects="Secchi.Mixed")
source.filename <- system.file("extdata", "lake_sources.csv", package = "MixSIAR")
source <- load_source_data(filename=source.filename,
source_factors=NULL,
conc_dep=FALSE,
data_type="raw",
mix)
discr.filename <- system.file("extdata", "lake_discrimination.csv", package = "MixSIAR")
discr <- load_discr_data(filename=discr.filename, mix)
calc_area(source=source,mix=mix,discr=discr) |
"dk_sim" |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
set.seed(42)
require(MultIS)
dat <- read.table(file = "example_readouts.csv",
sep = ",", header = TRUE, row.names = 1, check.names = FALSE)
dat <- as.matrix(dat)
class(dat) <- c(class(dat), "timeseries")
knitr::kable(dat[1:10,], row.names = TRUE, digits = 2)
plot(dat)
filteredDat <- MultIS::filter_at_tp_biggest_n(dat, at = "720", n = 10L)
plot(filteredDat)
similarityMatrix <- MultIS::get_similarity_matrix(dat, parallel = FALSE)
is1 = which.max(unlist(
lapply(1:(ncol(similarityMatrix) - 2),
function(i) {
similarityMatrix[i, i + 1] +
(1 - similarityMatrix[i + 1, i + 2])
})
))
is2 = is1 + 1
is3 = is1 + 2
r2 = round(summary(stats::lm(y ~ 0 + x, data = data.frame(
x = dat[is1, ], y = dat[is2, ])))$r.squared, 3)
p1 <- MultIS::plot_rsquare(dat, is1, is2) +
ggplot2::ggtitle(label = bquote(R^2 == .(r2))) +
ggplot2::theme(plot.title = ggplot2::element_text(hjust = 0.5))
r2 = round(summary(stats::lm(y ~ 0 + x, data = data.frame(
x = dat[is2, ], y = dat[is3, ])))$r.squared, 3)
p2 <- MultIS::plot_rsquare(dat, is2, is3) +
ggplot2::ggtitle(label = bquote(R^2 == .(r2))) +
ggplot2::theme(plot.title = ggplot2::element_text(hjust = 0.5))
gridExtra::grid.arrange(p1, p2, ncol = 2)
similarityMatrix <- MultIS::get_similarity_matrix(dat, parallel = FALSE)
plot(similarityMatrix)
clusterObjC2 <- MultIS::reconstruct(readouts = dat,
target_communities = 2,
method = "kmedoids",
cluster_obj = TRUE,
sim = similarityMatrix)
clusterObjC4 <- MultIS::reconstruct(readouts = dat,
target_communities = 4,
method = "kmedoids",
cluster_obj = TRUE,
sim = similarityMatrix)
p1 <- plot(clusterObjC2)
p2 <- plot(clusterObjC4)
gridExtra::grid.arrange(p1, p2, ncol = 2)
bestNrCluster <- MultIS::find_best_nr_cluster(
data = dat,
sim = similarityMatrix,
method_reconstruction = "kmedoids",
method_evaluation = "silhouette",
return_all = TRUE)
plotDf <- data.frame(
k = as.numeric(names(bestNrCluster)),
score = as.numeric(bestNrCluster)
)
ggplot2::ggplot(plotDf, ggplot2::aes(x = k, y = score, group = 1)) +
ggplot2::geom_line() +
ggplot2::geom_point(ggplot2::aes(col = (score == max(score)))) +
ggplot2::scale_color_manual(values = c("TRUE" = "
ggplot2::theme_bw() +
ggplot2::theme(legend.position = "none")
bestNrCluster <- MultIS::find_best_nr_cluster(
data = dat,
sim = similarityMatrix,
method_reconstruction = "kmedoids",
method_evaluation = "silhouette",
return_all = FALSE)
clusterObjBest <- MultIS::reconstruct(
readouts = dat,
target_communities = bestNrCluster,
method = "kmedoids",
cluster_obj = TRUE,
sim = similarityMatrix)
plot(clusterObjBest)
load("example.RData")
str(simData, max.level = 1)
knitr::kable(simData$barcodeReadouts[1:10,], digits = 2, row.names = TRUE)
p1 <- plot(simData$clone_counts) + ggplot2::ggtitle("Basic clonal simulation")
p2 <- plot(simData$clone_readouts) + ggplot2:: ggtitle("Added clonal differences")
p3 <- plot(simData$is_counts) + ggplot2::ggtitle("Superimposition of integration sites")
p4 <- plot(simData$is_readouts) + ggplot2::ggtitle("Added measurement noise")
gridExtra::grid.arrange(p1, p2, p3, p4, ncol = 2, nrow = 2)
mapping <- data.frame(Clone = unique(simData$mapping[,"Clone"]))
mapping$IS <- sapply(mapping$Clone, function(e) {
paste(summary(simData$mapping[simData$mapping[, "Clone"] == e, "IS"])[c("Min.", "Max.")], collapse = " - ")
})
knitr::kable(mapping)
similarityMatrix <- MultIS::get_similarity_matrix(simData$is_readouts,
parallel = FALSE)
aris <- sapply(3:12, function(k) {
clusterObj <- MultIS::reconstruct(simData$is_readouts,
target_communities = k,
cluster_obj = TRUE,
sim = similarityMatrix)
mclust::adjustedRandIndex(clusterObj$mapping[,"Clone"],
simData$mapping[,"Clone"])
})
arisDF <- data.frame(
k = 3:12,
ARI = aris,
stringsAsFactors = F
)
ggplot2::ggplot(arisDF, ggplot2::aes(x = k, y = ARI, colour = col)) +
ggplot2::geom_line(colour = "black") +
ggplot2::geom_point(size = 4, ggplot2::aes(color = (ARI == max(ARI)))) +
ggplot2::scale_color_manual(values = c("TRUE" = "
ggplot2::scale_x_continuous(breaks = 3:12) +
ggplot2::theme_bw() +
ggplot2::theme(legend.position = "none",
text = ggplot2::element_text(size = 16)) |
"PBI" |
has_other_issues_details <- function(parsed, ...) {
pkg <- all_packages(parsed)
res <- lapply(parsed, function(x) {
other_issues_pth <- xml2::xml_find_all(x, ".//h3/a/following::p[1]//a")
issue_type <- xml2::xml_text(other_issues_pth)
issue_url <- xml2::xml_text(xml2::xml_find_all(other_issues_pth, "@href"))
tibble::tibble(
result = "other_issue", check = issue_type,
flavors = NA_character_,
message = paste0("See: <", issue_url, ">")
)
})
pkgs <- rep(unlist(pkg), vapply(res, function(x) nrow(x) %||% 0L, integer(1)))
res <- do.call("rbind", res)
res <- cbind(package = pkgs, res, stringsAsFactors = FALSE)
tibble::as_tibble(res)
}
cran_details_from_web <- function(pkg, ...) {
parsed <- read_cran_web_from_pkg(pkg)
issue_test <- has_other_issues_details(parsed)
all_p <- mapply(function(x, pkg_nm) {
p <- xml2::xml_find_all(x, ".//p")
p <- strsplit(xml2::xml_text(x), "\n")
p <- unlist(p)
p <- p[nzchar(p)]
p <- gsub(intToUtf8(160), " ", p)
chk_idx <- grep("^Check:", p)
vrs_idx <- grep("^Version:", p)
res_idx <- grep("^Result:", p)
flv_idx <- grep("^Flavors?:", p)
if (!identical(length(chk_idx), length(res_idx)) &&
!identical(length(chk_idx), length(flv_idx))) {
stop("File an issue on Github indicating the name of your package.")
}
msg <- mapply(function(c, v, r, f) {
tibble::tibble(
version = gsub("^Version: ", "", p[v]),
result = gsub("^Result: ", "", p[r]),
check = gsub("^Check: ", "", p[c]),
flavors = gsub("^Flavors?: ", "", p[f]),
n_flavors = length(unlist(gregexpr(",", p[f]))) + 1,
message = paste(gsub("^\\s+", " ", p[(r + 1):(f - 1)]), collapse = "\n")
)
}, chk_idx, vrs_idx, res_idx, flv_idx, SIMPLIFY = FALSE, USE.NAMES = FALSE)
r <- do.call("rbind", msg)
if (!is.null(r)) {
r <- cbind(package = rep(pkg_nm, nrow(r)), r, stringsAsFactors = FALSE)
} else {
r <- tibble::add_row(default_cran_details,
package = pkg_nm,
version = paste(unique(get_cran_table(parsed[pkg_nm])$version), collapse = ", "),
result = "OK",
check = "",
flavors = "",
n_flavors = n_cran_flavors(),
message = ""
)
}
}, parsed, names(parsed), SIMPLIFY = FALSE)
res <- do.call("rbind", all_p)
.iss <- tibble::tibble(
package = issue_test$package,
version = rep("", nrow(issue_test)),
result = issue_test$result,
check = issue_test$check,
flavors = issue_test$flavors,
n_flavors = NA_integer_,
message = issue_test$message
)
res <- rbind(res, .iss)
tibble::as_tibble(res[order(res$package), ])
}
cran_details_from_crandb <- function(pkg, ...) {
dt <- get_cran_rds_file("details", ...)
issues <- get_cran_rds_file("issues", ...)
col_is_factor <- vapply(dt, is.factor, logical(1))
for (i in seq_along(col_is_factor)) {
if (col_is_factor[i]) {
dt[[i]] <- as.character(dt[[i]])
}
}
dt <- dt[dt[["package"]] %in% pkg, ]
dt$status <- gsub("WARNING", "WARN", dt$status)
.res <- default_cran_details
for (.p in unique(dt$package)) {
dt_p <- dt[dt$package == .p, ]
for (.v in unique(dt_p$version)) {
dt_v <- dt_p[dt_p$version == .v, ]
for (.c in unique(dt_v$check)) {
dt_c <- dt_v[dt_v$check == .c, ]
for (.s in unique(dt_c$status)) {
dt_s <- dt_c[dt_c$status == .s, ]
.res <- tibble::add_row(.res,
package = .p,
version = .v,
result = .s %~~% "",
check = .c,
flavors = paste(dt_s$flavor, collapse = ", ") %~~% "",
n_flavors = length(dt_s$flavor),
message = gsub("\\n", "\n ", paste(" ", dt_s$output[1]))
)
}
}
}
}
.res$check <- replace(.res$check, .res$check == "*", "")
issues <- issues[issues[["package"]] %in% pkg, ]
issues <- tibble::as_tibble(issues)
.iss <- tibble::tibble(
package = as.character(issues$package),
version = as.character(issues$version),
result = rep("other_issue", nrow(issues)),
check = as.character(issues$kind),
flavors = character(nrow(issues)),
n_flavors = integer(nrow(issues)),
message = as.character(issues$href)
)
res <- rbind(.res, .iss)
convert_nas(res[order(res$package), ], replace_with = "")
}
cran_details <- function(pkg, src = c("website", "crandb"),
...) {
if (!is.character(pkg)) {
stop(sQuote("pkg"), " is not a string.", call. = FALSE)
}
src <- match.arg(src, c("website", "crandb"))
if (identical(src, "website")) {
res <- cran_details_from_web(pkg)
} else if (identical(src, "crandb")) {
res <- cran_details_from_crandb(pkg, ...)
}
class(res) <- c("cran_details", class(res))
attr(res, "pkgs") <- pkg
res
}
render_flavors <- function(x) {
if (!is.na(x)) {
res <- unlist(strsplit(x, ", "))
paste(" ", clisymbols::symbol$pointer, res, "\n")
} else {
""
}
}
filter_pkg_not_ok <- function(res) {
res[res[["result"]] != "OK", ]
}
filter_pkg_ok <- function(res) {
not_ok <- filter_pkg_not_ok(res)
res[!res$package %in% not_ok$package, ]
}
summary.cran_details <- function(object, show_log = TRUE, print_ok = TRUE, ...) {
res_ok <- filter_pkg_ok(object)
if (nrow(res_ok) > 0 && print_ok) {
print_all_clear(res_ok[["package"]])
}
res_not_ok <- filter_pkg_not_ok(object)
if (nrow(res_not_ok) < 1) {
return(invisible(object))
}
mapply(
function(package, result, check, flavors, message) {
cmpt <- foghorn_components[[result]]
if (show_log) {
msg <- message
} else {
msg <- character(0)
}
cat(
cmpt$color(paste0(
cmpt$symbol, " ",
crayon::bold(paste0(package, " - ", result)),
": ", check
)), "\n",
render_flavors(flavors), "\n",
msg, "\n\n",
sep = ""
)
}, res_not_ok$package, tolower(res_not_ok$result), res_not_ok$check,
res_not_ok$flavors, res_not_ok$message
)
invisible(object)
}
summary_cran_details <- function(pkg, src = c("website", "crandb"),
show_log = TRUE, print_ok = TRUE, ...) {
res <- cran_details(pkg = pkg, src = src, ...)
summary(res, show_log = show_log, print_ok = print_ok)
} |
testthat::test_that("Test checkRange for invaild value for variable interval", code = {
M <- c(3, 6, 2)
testthat::expect_error(checkRange(M, 1:10),
info = "Test checkRange for invaild value for variable interval"
)
})
testthat::test_that("Test checkRange valid value", code = {
testthat::expect_invisible(checkRange(1:5, interval = c(1, 5), inclusion = c(TRUE, TRUE)))
}) |
checkTS <- function(TS, distbounds = c(-Inf, Inf)) {
if (!is.list(TS)) {
TS <- list(TS)
}
att <- attributes(TS[[1]])
margdist <- att$margdist
margarg <- att$margarg
p0 <- att$p0
acsvalue <- att$acsvalue
ac <- sapply(TS, function(x) acf(x, plot = F)$acf)
out <- data.frame(mean = c(popmean(margdist,
margarg,
distbounds = distbounds,
p0 = p0),
sapply(TS, mean)),
sd = c(popsd(margdist,
margarg,
distbounds = distbounds,
p0 = p0),
sapply(TS, sd)),
skew = c(popskew(margdist,
margarg,
distbounds = distbounds,
p0 = p0),
sapply(TS, function(x) sample.moments(x,
raw = F,
central = F,
coef = T)$coefficients[2])),
p0 = c(p0,
sapply(TS, function(x) length(which(x == 0))/length(x))),
acf_t1 = c(acsvalue[2],
ac[2,]),
acf_t2 = c(acsvalue[3],
ac[3,]),
acf_t3 = c(acsvalue[4],
ac[4,]))
row.names(out) <- c('expected', paste0('simulation', seq_along(TS)))
out <- round(out, 2)
structure(.Data = as.matrix(out),
class = c('checkTS', 'matrix'),
margdist = margdist,
margarg = margarg,
p0 = p0)
}
plot.checkTS <- function(x, ...) {
att <- attributes(x)
margdist <- att$margdist
margarg <- att$margarg
p0 <- att$p0
dta <- melt(as.data.table(x = x,
keep.rownames = TRUE),
id.vars = 'rn')
dta.e <- dta[which(dta$rn == 'expected'),]
dta.s <- dta[which(dta$rn != 'expected'),]
p <- ggplot() +
geom_boxplot(data = dta.s,
aes_string(x = 'variable',
y = 'value',
group = 'variable')) +
geom_point(data = dta.e,
aes_string(x = 'variable',
y = 'value',
group = 'variable'),
size = 2,
colour = 'red1') +
facet_wrap('variable',
scales = 'free',
nrow = 1) +
labs(x = '',
y = '',
title = paste('Marginal =', margdist),
subtitle = paste(paste(names(margarg),
'=',
margarg,
collapse = '; '),
paste('\np0 =',
p0),
collapse = ' ')) +
theme_gray() +
theme(legend.position = 'bottom',
strip.background = element_rect(fill = 'grey5'),
strip.text = element_text(colour = 'grey95'),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
return(p)
} |
library(mistr)
unifdist <- function(min = 0, max = 1){
if (!is.numeric(min) || !is.numeric(max)){
stop("parameters must be a numeric")
}
if (min >= max){
stop("min must be smaller than max")
}
x <- list(parameters = list(min = min, max = max),
type = "Uniform",
support = list(from = min, to = max))
class(x) <- c("unifdist", "contdist", "standist",
"univdist", "dist")
x
}
dunifdist <- function(min = 1, max = 6){
if (!is.numeric(min) || !is.numeric(max)){
stop("parameters must be a numeric")
}
if (min >= max){
stop("min must be smaller than max")
}
if (min%%1 != 0 || max%%1 != 0){
stop("min and max must be integers")
}
new_dist(name = "Discrete uniform",
from = min, to = max, by = 1)
}
pdunif <- function(q, min = 0, max = 1,
lower.tail = TRUE,
log.p = FALSE){
q <- round(q, 7)
z <- ifelse(q < min, 0,
ifelse(q >= max, 1,
(floor(q) - min + 1)/(max - min + 1)))
if(!lower.tail) z <- 1 - z
if(log.p) log(z) else z
}
D <- dunifdist(1, 6)
p(D, 4)
plim(D, 4)
atan.univdist <- function(x){
trafo(x, type = "init",
trans = quote(atan(X)),
invtrans = quote(tan(X)),
print = quote(atan(X)),
deriv = quote(1+tan(X)^2),
operation = "atan")
}
ataNorm <- atan(normdist())
library(ggplot2)
autoplot(ataNorm)
ataNorm
log(2+ataNorm)
atan.trans_univdist <- function(x){
if (last_history(x, "operation") == "tan") {
return(trafo(x, type = "go_back"))
} else {
return(trafo(x, type = "new",
trans = quote(atan(X)),
invtrans = quote(tan(X)),
print = quote(atan(X)),
deriv = quote(1+tan(X)^2),
operation = "atan"))
}
}
`+.dunifdist` <- function(e1, e2){
if (is.dist(e1)) {
O <- e1
x <- e2
} else {
O <- e2
x <- e1
}
dunifdist(min = parameters(O)["min"] + x,
max = parameters(O)["max"] + x)
}
D2 <- atan(D+5)
D2
p(D2, c(1.41, 1.43, 1.45, 1.47)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.