code
stringlengths 1
13.8M
|
---|
poisson.blaker.acc <- function(x,p,type=c("orig","unimod"),acc.tol=1e-10,...) {
if (x < 0) stop("Parameter x = ",x, " wrong!")
if (acc.tol <= 0) stop("Numerical tolerance ",acc.tol," nonpositive!")
type <- match.arg(type)
if (type != "orig" && type != "unimod") stop("Unknown type ",type,"!")
m <- length(p)
if (m < 1) stop("Empty vector p!")
if (m < 2) {
acc <- poisson.blaker.acc.single.p(x,p,type=type,acc.tol=acc.tol,...)
return(acc)
}
else {
if (max(p[2:m]-p[1:(m-1)]) <= 0) stop("Vector p not increasing!")
aq <- sapply(p,poisson.blaker.acc.single.p,x=x,acc.tol=acc.tol,output="both",...=...)
acc <- aq[1,]
if (type == "orig") {
return(acc)
}
if (type == "unimod") {
q1 <- aq[2,]
p.hat <- x
ind1 <- p <= p.hat
ind <- (ind1 & (q1 > c(-Inf,q1[1:(m-1)]))) |
(!ind1 & (q1 < c(q1[2:m],Inf)))
acc[ind] <- sapply(p[ind],poisson.blaker.acc.single.p,x=x,type=type,acc.tol=acc.tol,...=...)
m1 <- length(which(ind1))
if (m1 > 1) {
acc[1:m1] <- cummax(acc[1:m1])
}
if (m1 < m - 1) {
acc[m:(m1+1)] <- cummax(acc[m:(m1+1)])
}
return(acc)
}
}
}
|
pairs_power <- function(data, decimals = 2){
pairs.panels(var.numericas(data), digits = decimals, bg='black', ellipses=FALSE, smooth=FALSE,
lm=TRUE, cex.cor = 0.5, cex.main=0.1, pch=20, main='',
hist.col = gg_color_hue(3)[3], oma=c(1,1,1,1))
}
|
'
Authors
Torsten Pook, [email protected]
Copyright (C) 2017 -- 2020 Torsten Pook
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
'
compute.costs <- function(population, phenotyping.costs = 10, genotyping.costs = 100, fix.costs= 0, fix.costs.annual = 0,
profit.per.bv = 1, database=NULL, gen=NULL, cohorts=NULL,
interest.rate = 1, base.gen=1){
database <- get.database(population, gen=gen, database=database, cohorts=cohorts)
generation <- max(database[,1])
t <- length(phenotyping.costs)
if(t != (2*generation)){
if(t == 1){
phenotyping.costs <- matrix(phenotyping.costs, nrow=generation, ncol=2)
}
if(t==generation){
phenotyping.costs <- matrix(phenotyping.costs, nrow=generation, ncol=2, byrow=FALSE)
}
if(t==2){
phenotyping.costs <- matrix(phenotyping.costs, nrow=generation, ncol=2, byrow=TRUE)
if(generation==2){
warning("Specify if phenotyping.costs are per generation or per sex. Default use: Gender")
}
}
}
t <- length(genotyping.costs)
if(t != (2*generation)){
if(t == 1){
genotyping.costs <- matrix(genotyping.costs, nrow=generation, ncol=2)
}
if(t==generation){
genotyping.costs <- matrix(genotyping.costs, nrow=generation, ncol=2, byrow=FALSE)
}
if(t==2){
genotyping.costs <- matrix(genotyping.costs, nrow=generation, ncol=2, byrow=TRUE)
if(generation==2){
warning("Specify if genotyping.costs are per generation or per sex. Default use: Gender")
}
}
}
t <- length(profit.per.bv)
if(t != (2*generation)){
if(t == 1){
profit.per.bv <- matrix(profit.per.bv, nrow=generation, ncol=2)
}
if(t==generation){
profit.per.bv <- matrix(profit.per.bv, nrow=generation, ncol=2, byrow=FALSE)
}
if(t==2){
profit.per.bv <- matrix(profit.per.bv, nrow=generation, ncol=2, byrow=TRUE)
if(generation==2){
warning("Specify if profit.per.bv are per generation or per sex. Default use: Gender")
}
}
}
if(length(fix.costs.annual)!=generation){
fix.costs.annual <- rep(fix.costs.annual, length.out=generation)
}
if(interest.rate!=1){
phenotyping.costs <- phenotyping.costs * (interest.rate ^ (1:generation-base.gen))
genotyping.costs <- genotyping.costs * (interest.rate ^ (1:generation-base.gen))
profit.per.bv <- profit.per.bv * (interest.rate ^ (1:generation-base.gen))
fix.costs.annual <- fix.costs.annual * (interest.rate ^ (1:generation-base.gen))
}
costs_pheno <- costs_geno <- profit_bv <-numeric(nrow(database))
for(index in 1:nrow(database)){
activ <- database[index,]
for(index2 in activ[3]:activ[4]){
costs_pheno[index] <- costs_pheno[index] + population$breeding[[activ[1]]][[activ[2]]][[index]][[15]] * phenotyping.costs[activ[1], activ[2]]
costs_geno[index] <- costs_geno[index] + population$breeding[[activ[1]]][[activ[2]]][[index]][[16]] * genotyping.costs[activ[1], activ[2]]
profit_bv[index] <- profit_bv[index] + population$breeding[[activ[1]]][[activ[2]+6]][1,index] * profit.per.bv[activ[1], activ[2]]
}
}
costs_pergroup <- costs_pheno + costs_geno
gains_group <- (profit_bv) - (costs_pheno) - (costs_geno)
timest <- unique(database[,1])
gains_year <- numeric(length(timest))
t <- 1
for(index in timest){
gains_year[t] <- sum(gains_group[which(database[,1]==index)]) + fix.costs.annual[index]
t <- t + 1
}
oldpar <- graphics::par(no.readonly=TRUE)
on.exit(graphics::par(oldpar))
graphics::par(mfrow=(c(1,2)))
graphics::plot(timest, gains_year, main="Gains per Year", xlab="generation", ylab="gains")
graphics::abline(h=0)
graphics::plot(gains_group, main="Gains per Cohort", xlab="cohort", ylab="gains", xaxt="n")
graphics::axis(1, at=1:length(gains_group), labels=cohorts)
graphics::abline(h=0)
total <- sum(gains_year) - fix.costs
return(total)
}
|
test_that("Not interactive", {
expect_error(go_insane())
})
|
NULL
Comp <- function(map = lapply, fun=NULL){
structure(
function(loop, ...){
mapfun <- attr(sys.function(), "mapfun")
fun <- attr(sys.function(), "fun")
ret <- eval(parse(text=.parse_for(substitute(loop), mapfun=mapfun, ...)))
if (is.null(fun)) return(ret)
fun(ret)
}, mapfun=map, fun=fun, class=c("Comprehension", "function")
)
}
List <- structure(function(loop, clust=NULL, fun=NULL){
if (is.null(clust)){mapfun <- lapply
} else { mapfun <- function(X, FUN) parallel::parLapply(clust, X, FUN)}
CURR_ENV <- environment()
pt <- parse(text=.parse_for(substitute(loop), mapfun=mapfun))
parent.env(CURR_ENV) <- sys.frame()
ret <- eval(pt, CURR_ENV)
if (is.null(fun)) return(ret)
fun(ret)
}, mapfun = lapply, class = c("Comprehension", "function"))
Env <- structure(function(loop, clust=NULL){
if (is.null(clust)){mapfun <- lapply
} else {mapfun <- function(X, FUN) parallel::parLapply(clust, X, FUN)}
CURR_ENV <- environment()
pt <- parse(text=.parse_for(substitute(loop), mapfun=mapfun))
parent.env(CURR_ENV) <- sys.frame()
as.environment(eval(pt, CURR_ENV))
}, mapfun = lapply, fun = as.environment, class = c("Comprehension", "function"))
Vec <- structure(function(loop, clust=NULL, drop.names = FALSE){
mapfun <- sapply
if (!is.null(clust)) mapfun <- function(X, FUN, ...) parallel::parSapply(clust, X, FUN, ...)
CURR_ENV <- environment()
pt <- parse(text=.parse_for(substitute(loop), mapfun=mapfun))
parent.env(CURR_ENV) <- sys.frame()
ret <- eval(pt, CURR_ENV)
if (drop.names) return(as.vector(flatten(ret)))
.save_names(ret, function(i){as.vector(flatten(i))})
}, mapfun = sapply, fun = function(i){as.vector(flatten(i))}, class = c("Comprehension", "function"))
Num <- structure(function(loop, clust=NULL, drop.names = FALSE){
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parallel::parSapply(clust, X, FUN, ...)}
CURR_ENV <- environment()
pt <- parse(text=.parse_for(substitute(loop), mapfun=mapfun))
parent.env(CURR_ENV) <- sys.frame()
ret <- eval(pt, CURR_ENV)
if (drop.names) return(as.numeric(flatten(ret)))
.save_names(ret, function(i){as.numeric(flatten(i))})
}, mapfun = sapply, fun = function(i){as.numeric(flatten(i))}, class = c("Comprehension", "function"))
Chr <- structure(function(loop, clust=NULL, drop.names = FALSE){
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parallel::parSapply(clust, X, FUN, ...)}
CURR_ENV <- environment()
pt <- parse(text=.parse_for(substitute(loop), mapfun=mapfun))
parent.env(CURR_ENV) <- sys.frame()
ret <- eval(pt, CURR_ENV)
if (drop.names) return(as.character(flatten(ret)))
.save_names(ret, function(i){as.character(flatten(i))})
}, mapfun = sapply, fun = function(i){as.character(flatten(i))}, class = c("Comprehension", "function"))
Logical <- structure(function(loop, clust=NULL, drop.names = FALSE){
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parallel::parSapply(clust, X, FUN, ...)}
CURR_ENV <- environment()
pt <- parse(text=.parse_for(substitute(loop), mapfun=mapfun))
parent.env(CURR_ENV) <- sys.frame()
ret <- eval(pt, CURR_ENV)
if (drop.names) return(as.logical(flatten(ret)))
.save_names(ret, function(i){as.logical(flatten(i))})
}, mapfun = sapply, fun = function(i){as.logical(flatten(i))}, class = c("Comprehension", "function"))
Mat <- structure(function(loop, clust=NULL, by.col=TRUE){
if (is.null(clust)){
if (by.col){mapfun <- function(x, f, ...) sapply(cols(x), f, ...)
} else {mapfun <- function(x, f, ...) sapply(rows(x), f, ...)}
mapfun <- sapply
} else {
if (by.col){mapfun <- function(x, f, ...) parallel::parSapply(clust, cols(x), f, ...)
} else {mapfun <- function(x, f, ...) parallel::parSapply(clust, rows(x), f, ...)}
}
CURR_ENV <- environment()
pt <- parse(text=.parse_for(substitute(loop), mapfun=mapfun))
parent.env(CURR_ENV) <- sys.frame()
as.matrix(eval(pt, CURR_ENV))
}, mapfun = function(x, f, ...) sapply(cols(x), f, ...), fun = as.matrix, class = c("Comprehension", "function"))
DF <- structure(function(loop, clust=NULL){
if (is.null(clust)){mapfun <- lapply
} else {mapfun <- function(X, FUN) parallel::parLapply(clust, X, FUN)}
CURR_ENV <- environment()
pt <- parse(text=.parse_for(substitute(loop), mapfun=mapfun))
parent.env(CURR_ENV) <- sys.frame()
as.data.frame(eval(pt, CURR_ENV))
}, mapfun = lapply, fun = as.data.frame, class = c("Comprehension", "function"))
.. <- structure(
function(..., clust=NULL, type=Vec, simplify=TRUE){
dots <- eval(substitute(alist(...)))
fun <- attr(type, "fun")
if (is.null(clust)){mapfun <- attr(type, "mapfun")
} else {
mfun <- attr(type, "mapfun")
if (identical(mfun, sapply)){
mapfun <- function(X, FUN) parSapply(clust, X, FUN)
} else {function(X, FUN) parLapply(clust, X, FUN)}
}
l <- lapply(dots, function(i){
e <- eval(parse(text=.parse_for(i, mapfun=mapfun)))
if (is.null(fun)) return(e)
fun(e)
})
if (length(dots) == 1){l <- l[[1]]
} else if (simplify){l <- Reduce(c, l)}
l
},
class = c("VecGen", "function")
)
NULL
All <- structure(function(..., clust=NULL, na.rm=FALSE){
dots <- eval(substitute(alist(...)))
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parSapply(clust, X, FUN, ...)}
all(sapply(dots, function(i) all(eval(parse(text=.parse_for(i, mapfun=mapfun))), na.rm=na.rm)), na.rm=na.rm)
}, class = c("Comprehension", "function"))
Any <- structure(function(..., clust=NULL, na.rm=FALSE){
dots <- eval(substitute(alist(...)))
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parSapply(clust, X, FUN, ...)}
any(sapply(dots, function(i) any(eval(parse(text=.parse_for(i, mapfun=mapfun))), na.rm=na.rm)), na.rm=na.rm)
}, class = c("Comprehension", "function"))
None <- structure(function(..., clust=NULL, na.rm=FALSE){
dots <- eval(substitute(alist(...)))
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parSapply(clust, X, FUN, ...)}
!any(sapply(dots, function(i) any(eval(parse(text=.parse_for(i, mapfun=mapfun))), na.rm=na.rm)), na.rm=na.rm)
}, class = c("Comprehension", "function"))
Sum <- structure(function(..., clust=NULL, na.rm=FALSE){
dots <- eval(substitute(alist(...)))
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parSapply(clust, X, FUN, ...)}
sum(sapply(dots, function(i) sum(eval(parse(text=.parse_for(i, mapfun=mapfun))), na.rm=na.rm)), na.rm=na.rm)
}, class = c("Comprehension", "function"))
Prod <- structure(function(..., clust=NULL, na.rm=FALSE){
dots <- eval(substitute(alist(...)))
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parSapply(clust, X, FUN, ...)}
prod(sapply(dots, function(i) prod(eval(parse(text=.parse_for(i, mapfun=mapfun))), na.rm=na.rm)), na.rm=na.rm)
}, class = c("Comprehension", "function"))
Min <- structure(function(..., clust=NULL, na.rm=FALSE){
dots <- eval(substitute(alist(...)))
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parSapply(clust, X, FUN, ...)}
min(sapply(dots, function(i) min(eval(parse(text=.parse_for(i, mapfun=mapfun))), na.rm=na.rm)), na.rm=na.rm)
}, class = c("Comprehension", "function"))
Max <- structure(function(..., clust=NULL, na.rm=FALSE){
dots <- eval(substitute(alist(...)))
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parSapply(clust, X, FUN, ...)}
max(sapply(dots, function(i) max(eval(parse(text=.parse_for(i, mapfun=mapfun))), na.rm=na.rm)), na.rm=na.rm)
}, class = c("Comprehension", "function"))
Mean <- structure(function(..., clust=NULL, na.rm=FALSE, trim=0){
dots <- eval(substitute(alist(...)))
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parSapply(clust, X, FUN, ...)}
mean(sapply(dots, function(i) mean(eval(parse(text=.parse_for(i, mapfun=mapfun))), na.rm=na.rm, trim=trim)), na.rm=na.rm, trim=trim)
}, class = c("Comprehension", "function"))
Stats <- structure(function(..., clust=NULL, na.rm=FALSE, trim=0){
dots <- eval(substitute(alist(...)))
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parSapply(clust, X, FUN, ...)}
x <- Reduce(c, sapply(dots, function(i) eval(parse(text=.parse_for(i, mapfun=mapfun)))))
q <- quantile(x, probs=seq(0,1,0.25), na.rm=na.rm, names=FALSE)
list(
min = q[1],
q1 = q[2],
med = q[3],
q3 = q[4],
max = q[5],
mean = mean(x, na.rm=na.rm, trim=trim),
sd = sd(x, na.rm=na.rm)
)
}, class = c("Comprehension", "function"))
Paste <- structure(function(..., clust=NULL, collapse=""){
dots <- eval(substitute(alist(...)))
if (is.null(clust)){mapfun <- sapply
} else {mapfun <- function(X, FUN, ...) parSapply(clust, X, FUN, ...)}
paste(sapply(dots, function(i) paste(eval(parse(text=.parse_for(i, mapfun=mapfun))), collapse=collapse)), collapse=collapse)
}, class = c("Comprehension", "function"))
|
umxEFA <- function(x = NULL, factors = NULL, data = NULL, scores = c("none", 'ML', 'WeightedML', 'Regression'), minManifests = NA,
rotation = c("varimax", "promax", "none"), return = c("model", "loadings"), report = c("markdown", "html"), summary = FALSE, name = "efa", digits = 2, n.obs = NULL, covmat = NULL){
rotation = xmu_match.arg(rotation, c("varimax", "promax", "none"), check = FALSE)
scores = match.arg(scores)
return = match.arg(return)
if (!is.null(data)){
if(!is.null(covmat) || !is.null(n.obs)){
stop("umxEFA: covmat and n.obs must be empty when using 'data =' ...")
}
if(!is.null(x)){
if (inherits(x,"formula")){
if(is.null(data)){
stop(paste("If you provide a formula in x to select variable, data must contain a dataframe"))
} else {
x = all.vars(x)
data = data[, x]
name = "EFA"
}
} else if(length(x) > 1) {
umx_check_names(x, data)
data = data[,x]
name = "EFA"
}else{
name = x
}
}else{
name = "EFA"
}
} else if(!is.null(covmat) || !is.null(n.obs)){
stop("With cov data, you may as well be using factanal()...")
if(!is.null(data)){
stop("You can't offer up both a data.frame and a covmat.")
}
} else {
if(!is.null(x)){
if(is.data.frame(x)){
data = x
}else if (is.matrix(x)){
data = as.data.frame(x)
}
} else if(is.null(data)){
stop("You need to provide a data.frame to analyze: This can be in x, or data, or covmat")
}
name = "EFA"
}
data = umx_scale(data)
if(is.null(factors)){
stop("You need to request at least 1 latent factor, e.g.: factors = 4")
} else if( length(factors) == 1 && class(factors) == "numeric"){
factors = paste0("F", c(1:factors))
}else{
}
manifests = names(data)
m1 = umxRAM(model = name, data = data, autoRun = FALSE,
umxPath(factors, to = manifests, connect = "unique.bivariate"),
umxPath(v.m. = manifests),
umxPath(v1m0 = factors)
)
nFac = length(factors)
nManifests = length(manifests)
if(nFac > 1){
for(i in 2:nFac){
m1$A$free[1:(i-1) , factors[i]] = FALSE
m1$A$values[1:(i-1), factors[i]] = 0
}
}
for(i in seq_along(manifests)) {
thisManifest = manifests[i]
m1$S$lbound[thisManifest, thisManifest] = 0
}
m1 = mxRun(m1)
if(rotation != "none" && nFac > 1){
oldLoadings = loadings.MxModel(m1)
newLoadings = eval(parse(text = paste0(rotation, "(oldLoadings)")))
if(!umx_set_silent(silent=TRUE)){
print("Rotation results")
print(newLoadings)
rm = newLoadings$rotmat
print("Factor Correlation Matrix")
print(solve(t(rm) %*% rm))
}
m1$A$values[manifests, factors] = newLoadings$loadings[1:nManifests, 1:nFac]
} else if(!umx_set_silent(silent=TRUE)){
print("Results")
print(loadings(m1))
newLoadings = loadings.MxModel(m1)
}
if(summary){
umxSummary(m1, digits = digits, report = report);
}
if(scores != "none"){
factorScores = umxFactorScores(m1, type = scores, minManifests = minManifests)
return(factorScores)
}
if(return == "loadings"){
invisible(newLoadings)
}else if(return == "model"){
invisible(m1)
}else{
stop("polite error: Not sure what ", omxQuotes(return), " is to return it" )
}
}
umxFactanal <- umxEFA
umxFactorScores <- function(model, type = c('ML', 'WeightedML', 'Regression'), minManifests = NA, return = c("Scores", "StandardErrors")) {
type = match.arg(type)
return = match.arg(return)
suppressMessages({
scores = mxFactorScores(model, type = type, minManifests = minManifests)
})
out = scores[ , , return, drop = FALSE]
out = data.frame(out)
names(out) <- dimnames(scores)[[2]]
return(out)
}
umxTwoStage <- function(formula= Y ~ X, instruments = ~qtl, data, subset, weights, contrasts= NULL, name = "tsls", ...) {
umx_check(is.null(contrasts), "stop", "Contrasts not supported yet in umxTwoStage: email maintainer('umx') to prioritize")
if(!class(formula) == "formula"){
stop("formula must be a formula")
}
allForm = all.vars(terms(formula))
if(length(allForm) != 2){
stop("I'm currently limited to 1 DV, 1 IV, and 1 instrument: 'formula' had ", length(allForm), " items")
}
DV = allForm[1]
Xvars = all.vars(delete.response(terms(formula)))
inst = all.vars(terms(instruments))
if(length(inst) != 1){
stop("I'm currently limited to 1 DV, 1 IV, and 1 instrument: 'instruments' had ", length(allForm), " items")
}
manifests <- c(allForm, inst)
latentErr <- paste0("e", allForm)
umx_check_names(manifests, data = data, die = TRUE)
IVModel = umxRAM("IV Model", data = data,
umxPath(inst , to = Xvars),
umxPath(Xvars, to = DV),
umxPath(v.m. = inst),
umxPath(var = latentErr),
umxPath(latentErr, to = allForm, fixedAt = 1),
umxPath(unique.bivariate = latentErr, values = 0.2, labels = paste0("phi", length(latentErr)) ),
umxPath(means = c(Xvars, DV))
)
return(IVModel)
}
umxMR <- umxTwoStage
|
context("HierarchicalModel")
test_that("Tau_square_Est", {
New_result <- robu(effectsize ~ followup,
data = hierdat, studynum = studyid, var.eff.size = var,
modelweights ="HIER",small = T)
expect_equivalent(New_result$mod_info$tau.sq[1,1], 0.06541402)
})
test_that("Omega_square_Est", {
New_result <- robu(effectsize ~ followup,
data = hierdat, studynum = studyid, var.eff.size = var,
modelweights ="HIER",small = T)
expect_equivalent(New_result$mod_info$omega.sq[1,1], 0.16360794)
})
test_that("Coef_Est", {
New_result <- robu(effectsize ~ followup,
data = hierdat, studynum = studyid, var.eff.size = var,
modelweights ="HIER",small = T)
expect_equivalent(as.vector(New_result$b.r), c(0.2610277292, -0.0001810645))
})
test_that("df_Est", {
New_result <- robu(effectsize ~ followup,
data = hierdat, studynum = studyid, var.eff.size = var,
modelweights ="HIER",small = F)
expect_equivalent(as.vector(New_result$dfs), 13)
New_result <- robu(effectsize ~ followup,
data = hierdat, studynum = studyid, var.eff.size = var,
modelweights ="HIER",small = T)
expect_equivalent(as.vector(New_result$dfs), c(3.1683243, 1.5765336))
})
|
context('Prepare CFBI solver')
load(file = quickLookup("test_CFBI_starting.Rdata"))
suppressWarnings(RNGversion("3.5.0"))
set.seed(101010)
starting_dfm <- getStartingCFBI(
new_param_list = new_param_list,
glmer_fit = glmer_fit,
alphas = alphas,
CFBI_numstart = CFBI_numstart
)
testthat::test_that(
desc = "Test that starting CFBI dataframes are identical",
testthat::expect_equal(
object = starting_dfm,
expected = starting_dfm_orig,
tolerance = helper_tol,
check.attributes = TRUE
)
)
|
make.table2 = function(table.of = NULL,
split = NULL,
plot = TRUE,
xlab = table.of,
ylab = "counts",
title = table.of,
barcolor = "grey",
barfill = "darkgrey"){
data("books", package = "litRiddle", envir = environment())
books <- get("books", envir = environment())
data("respondents", package = "litRiddle", envir = environment())
respondents <- get("respondents", envir = environment())
data("reviews", package = "litRiddle", envir = environment())
reviews <- get("reviews", envir = environment())
dat = combine.all()
dat = as.data.frame(dat)
if (length(unique(dat[,split])) > 31) {
message("The 'split-by' variable has many unique values, which will ",
"make the output \nvery hard to process. Please provide",
"a 'split-by' variable that contains \nless unique values.")
} else {
col1 = dat[, table.of]
col2 = dat[, split]
dat = data.frame(col1, col2)
table2 = table(dat[, 2], dat[, 1])
if(exists("table2") & plot == TRUE){
g = ggplot(dat, aes(x = dat[,1]))
g = g + facet_wrap(~dat[,2], scales = "free_x")
g = g + geom_bar(colour = barcolor, fill = barfill)
g = g + xlab(xlab) + ylab(ylab) + ggtitle(title)
plot(g)
return(table2)
} else if(exists("table2")){
return(table2)
}
}
}
|
conditionalranking = function(I,bsrkr){
rank_RE=bsrkr[I!=0]
rank_BE=bsrkr[I==0]
tau01=sapply(seq_len(length(rank_BE)), function(i) (sum(rank_BE[i]>rank_RE)))
tau01=length(rank_RE)-tau01
return(tau01)
}
|
context("test-scenarios")
test_that("uptake_pct_govtarget(1,1) should be 0.04768831", {
expect_equal(uptake_pct_govtarget(1,1), 0.04768831)
expect_error(uptake_pct_govtarget(LETTERS, letters))
expect_message(uptake_pct_govtarget(1001, 2, verbose = TRUE))
})
test_that("uptake_pct_godutch(1,1) should be round(0.341359, digits = 5)", {
expect_equal(round(uptake_pct_godutch(1,1), digits = 2),
0.37)
expect_error(uptake_pct_godutch(LETTERS, letters))
expect_message(uptake_pct_godutch(1001, 2, verbose = TRUE))
})
|
dbind <-
function(a,b){
out1<-cbind(a,matrix(0,nrow(a),ncol(b)))
out2<-cbind(matrix(0,nrow(b),ncol(a)),b)
out<-rbind(out1,out2)
out
}
|
cv.MLGL <- function(X, y, nfolds = 5, lambda = NULL, hc = NULL, weightLevel = NULL, weightSizeGroup = NULL, loss = c("ls", "logit"), intercept = TRUE, sizeMaxGroup = NULL, verbose = FALSE, ...) {
loss <- match.arg(loss)
.checkParameters(X, y, hc, lambda, weightLevel, weightSizeGroup, intercept, verbose, loss, sizeMaxGroup)
if (!is.numeric(nfolds) | (length(nfolds) != 1)) {
stop("nfolds must be an integer greater than 3.")
}
if (!.is.wholenumber(nfolds) | nfolds <= 2 | nfolds > nrow(X)) {
stop("nfolds must be an integer greater than 3.")
}
n <- nrow(X)
p <- ncol(X)
tcah <- rep(NA, 3)
if (is.null(hc)) {
if (verbose) {
cat("Computing hierarchical clustering...")
}
t1 <- proc.time()
d <- dist(t(X))
hc <- hclust(d, method = "ward.D2")
t2 <- proc.time()
tcah <- t2 - t1
if (verbose) {
cat("DONE in ", tcah[3], "s\n")
}
}
if (verbose) {
cat("Preliminary step...")
}
t1 <- proc.time()
prelim <- preliminaryStep(hc, weightLevel, weightSizeGroup, sizeMaxGroup)
Xb <- X[, prelim$var]
t2 <- proc.time()
if (verbose) {
cat("DONE in ", (t2 - t1)[3], "s\n")
}
if (verbose) {
cat("Computing group-lasso...")
}
t1 <- proc.time()
res <- cv.gglasso(Xb, y, prelim$group, pf = prelim$weight, nfolds = nfolds, lambda = lambda, intercept = intercept, loss = loss, ...)
t2 <- proc.time()
tgglasso <- t2 - t1
if (verbose) {
cat("DONE in ", tgglasso[3], "s\n")
}
res$name <- NULL
res$gglasso.fit <- NULL
res$cvlower <- res$cvlo
res$cvlo <- NULL
res$time <- c(tcah[3], tgglasso[3])
names(res$time) <- c("hclust", "glasso")
class(res) <- "cv.MLGL"
return(res)
}
|
env_returnMeanBiofilmThickness <-
function(xmlResultFile)
{
return(xmlResultFile[[1]][[1]][[1]][[1]])
}
|
rnd_init_maps<-function(){
Lx <- 113
Ly <- 114
p <- 0.5
A <- 0.7
plt <- TRUE
dirs <- 4
n<- Lx*Ly
layer <- raster::raster(nrows = Lx, ncols = Ly, xmn = 688075, xmx = 690925, ymn = 4173950, ymx = 4176775)
raster::values(layer) <- rep(0, Lx*Ly)
raster::values(layer)[sample.int(Lx*Ly, round(Lx*Ly*p))] <- 1
clumped <- raster::clump(layer, directions=dirs, gaps = FALSE)
ncluster <- max(raster::values(clumped), na.rm = TRUE)
types <- factor(c(0,1))
numTypes <- as.numeric(types)
clustertype <- sample(numTypes, ncluster, replace = TRUE, prob = c(1-A,A))
raster::values(clumped) <- clustertype[raster::values(clumped)]
cellsUnassigned <- (1:n)[is.na(raster::values(clumped))]
cellsAssigned <- (1:n)[!is.na(raster::values(clumped))]
tempadj <- raster::adjacent(clumped, cellsUnassigned, cellsAssigned, directions = 8)
tempadj <- split(tempadj[,2], tempadj[,1])
fillinType <- function (adjcells) {
type <- raster::values(clumped)[adjcells]
type <- factor(type)
freq <- tabulate(type)
result <- as.numeric(levels(type)[freq == max(freq)])
if (length(result)>1)
result <- sample (result, 1)
result
}
filled <- sapply(tempadj, fillinType)
filledCells <- as.numeric(names(filled))
raster::values(clumped)[filledCells] <- filled
notfilledCells <- cellsUnassigned[!(cellsUnassigned %in% filledCells)]
randomType <- sample(numTypes, length(notfilledCells), replace = TRUE, prob = c(1-A,A))
raster::values(clumped)[notfilledCells] <- randomType
layer <- raster::raster(nrows = Lx, ncols = Ly, xmn = 688075, xmx = 690925, ymn = 4173950, ymx = 4176775)
raster::values(layer) <- rep(0, Lx*Ly)
raster::values(layer)[sample.int(Lx*Ly, round(Lx*Ly*p))] <- 1
clumped2 <- raster::clump(layer, directions=dirs, gaps = FALSE)
ncluster <- max(raster::values(clumped2), na.rm = TRUE)
types <- factor(c(0,1))
numTypes <- as.numeric(types)
clustertype <- sample(numTypes, ncluster, replace = TRUE, prob = c(1-A,A))
raster::values(clumped2) <- clustertype[raster::values(clumped2)]
cellsUnassigned <- (1:n)[is.na(raster::values(clumped2))]
cellsAssigned <- (1:n)[!is.na(raster::values(clumped2))]
tempadj <- raster::adjacent(clumped2, cellsUnassigned, cellsAssigned, directions = 8)
tempadj <- split(tempadj[,2], tempadj[,1])
fillinType <- function (adjcells) {
type <- raster::values(clumped2)[adjcells]
type <- factor(type)
freq <- tabulate(type)
result <- as.numeric(levels(type)[freq == max(freq)])
if (length(result)>1)
result <- sample (result, 1)
result
}
filled <- sapply(tempadj, fillinType)
filledCells <- as.numeric(names(filled))
raster::values(clumped2)[filledCells] <- filled
notfilledCells <- cellsUnassigned[!(cellsUnassigned %in% filledCells)]
randomType <- sample(numTypes, length(notfilledCells), replace = TRUE, prob = c(1-A,A))
raster::values(clumped2)[notfilledCells] <- randomType
c3<<-NULL
c3<<-clumped + clumped2
c3<-get('c3')
}
|
CSDCD.random=function(num.var,num.sample,x.mat,y.vec,d.Star){
p=num.var
n=num.sample
design.Mat=x.mat
y.sim=y.vec
lambda=d.Star
thru.data=75
tot.it=thru.data*n
alpha=matrix(NA,tot.it,n)
nu.mat=matrix(NA,tot.it,p)
alpha[1,]=rep(0,n)
nu.mat[1,]=(alpha[1,]%*%design.Mat*(1/lambda))/n
for(r in 1:thru.data){
random.seq=sample(1:n, n,replace = FALSE)
for(k in 1:n){
t=(r-1)*n+k
if(r==1){
t=(r-1)*n+k+1
}
delta.alpha=-(alpha[t-1,random.seq[k]]+t(nu.mat[t-1,])%*%design.Mat[random.seq[k],]-y.sim[random.seq[k]])/(1+(sum(design.Mat[random.seq[k],]**2*(1/lambda))/(2*n)))
alpha[t,]=alpha[t-1,]+delta.alpha
nu.mat[t,]=nu.mat[t-1,]+(delta.alpha/n)*design.Mat[random.seq[k],]*(1/lambda)
}
}
colMeans(nu.mat[(tot.it/2):tot.it,])
}
|
setMethod("initModelClass", signature(model="mass"),
function (model)
{
model@clpdep <- (model@weight || model@lclp0 || model@lclpequ)
model@ncomp <- length(model@peakpar) + if(model@extracomp) 1 else 0
model@ncolc <- model@ncomp
model
})
|
source("ESEUR_config.r")
library("ape")
pal_col=rainbow(3)
ft=read.csv(paste0(ESEUR_dir, "sourcecode/journal-pone-0078871.csv.xz"), as.is=TRUE)
ct=sapply(1:nrow(ft), function(X) unlist(strsplit(ft$Character.trait[X], split="")))
ct=data.frame(ct, stringsAsFactors=FALSE)
names(ct)=ft$Source
ct=data.frame(sapply(ct, function(X) as.numeric(X)))
ct_phy=njs(dist(t(ct), method="binary"))
tip_col=mapvalues(ft$ATU, unique(ft$ATU), pal_col)
plot(ct_phy, type="unrooted", cex=1.0, edge.color=point_col, tip.color=tip_col)
|
library(hamcrest)
test.data.assign <- function() {
value <- new("MethodDefinition")
[email protected] <- function(x) length(x)
assertThat(typeof(value), identicalTo("closure"))
assertThat(attr(value, 'class')[1], identicalTo("MethodDefinition"))
}
test.data.assign.attribs.preserved <- function() {
data <- c(x='vector')
attr(data, 'foo') <- 'bar'
object <- new("signature")
[email protected] <- data
assertThat(names(object), identicalTo("x"))
assertThat(attr(object, 'foo'), identicalTo("bar"))
}
test.data.matrix <- function() {
setClass(
"Interval",
representation( type = "character" ),
prototype(matrix( 0, 0, 2 )),
contains = "matrix")
i <- new("Interval")
[email protected] <- matrix(1:4, nrow=2)
assertThat([email protected], identicalTo(matrix(1:4, nrow=2)))
}
|
context("plotD3")
source("objects_for_tests.R")
test_that("plotD3_residual", {
expect_is(plotD3(mr_rf, type = "residual", variable = "x2"), "r2d3")
expect_is(plotD3_residual(mr_glm, smooth = TRUE, point_count = 5, variable = "x2"), "r2d3")
expect_is(plotD3_residual(mr_glm, std_residuals = TRUE), "r2d3")
expect_is(plotD3_residual(mr_rf, variable = "x2"), "r2d3")
expect_is(plotD3_residual(mr_rf, mr_glm, single_plot = FALSE, scale_plot = TRUE), "r2d3")
expect_error(plotD3_residual(mr_lm, points = FALSE, smooth = FALSE))
expect_error(plotD3_residual(list(1,2,3)))
})
test_that("plotD3_autocorrelation", {
expect_is(plotD3(mr_glm, type = "autocorrelation"), "r2d3")
expect_is(plotD3_autocorrelation(mr_rf, mr_glm, smooth = TRUE, point_count = 5), "r2d3")
expect_is(plotD3_autocorrelation(mr_glm), "r2d3")
expect_is(plotD3_autocorrelation(mr_rf, mr_glm, single_plot = FALSE, scale_plot = TRUE), "r2d3")
expect_is(plotD3_autocorrelation(mr_rf, mr_glm, smooth = TRUE, point_count = 5), "r2d3")
expect_error(plotD3_autocorrelation(mr_glm, points = FALSE, smooth = FALSE))
expect_error(plotD3_autocorrelation(list(1,2,3)))
})
test_that("plotD3_prediction", {
expect_is(plotD3(mr_glm, type = "prediction"), "r2d3")
expect_is(plotD3_prediction(mr_glm, smooth = TRUE, point_count = 5, variable = "x2"), "r2d3")
expect_is(plotD3_prediction(mr_rf), "r2d3")
expect_is(plotD3_prediction(mr_rf, mr_glm, single_plot = FALSE, scale_plot = TRUE), "r2d3")
expect_error(plotD3_prediction(au_lm, points = FALSE, smooth = FALSE))
expect_error(plotD3_prediction(glm_mr, rf_mr))
expect_error(plotD3_prediction(list(1,2,3)))
})
test_that("plotD3_scalelocation", {
expect_is(plotD3(mr_rf, type = "scalelocation"), "r2d3")
expect_is(plotD3_scalelocation(mr_glm, smooth = TRUE, point_count = 5), "r2d3")
expect_is(plotD3_scalelocation(mr_glm, peaks = TRUE), "r2d3")
expect_is(plotD3_scalelocation(mr_rf), "r2d3")
expect_is(plotD3_scalelocation(mr_rf, mr_glm, single_plot = FALSE, scale_plot = TRUE), "r2d3")
expect_error(plotD3_scalelocation(mr_glm, points = FALSE, smooth = FALSE))
expect_error(plotD3_scalelocation(list(1,2,3)))
})
test_that("plotD3_cooksdistance", {
expect_is(plotD3(cd_lm, type = "cooksdistance"), "r2d3")
expect_is(plotD3_cooksdistance(cd_lm, cd_rf), "r2d3")
expect_is(plotD3_cooksdistance(cd_rf, cd_lm, single_plot = FALSE), "r2d3")
expect_is(plotD3_cooksdistance(cd_rf, cd_lm, single_plot = TRUE, scale_plot = TRUE), "r2d3")
expect_error(plotD3_cooksdistance(list(1,2,3)))
})
test_that("plotD3_lift", {
expect_is(plotD3(ev_glm, type = "lift"), "r2d3")
expect_is(plotD3_lift(ev_glm), "r2d3")
expect_is(plotD3_lift(ev_glm, ev_rf, scale_plot = TRUE), "r2d3")
})
test_that("plotD3_rec", {
expect_is(plotD3(mr_glm, type = "rec"), "r2d3")
expect_is(plotD3_rec(mr_glm), "r2d3")
expect_is(plotD3_rec(mr_glm, mr_rf, scale_plot = TRUE), "r2d3")
})
test_that("plotD3_acf", {
expect_is(plotD3(mr_glm, type = "acf"), "r2d3")
expect_is(plotD3_acf(mr_glm), "r2d3")
expect_is(plotD3_acf(mr_glm, mr_rf, scale_plot = TRUE), "r2d3")
expect_is(plotD3_acf(mr_glm, mr_rf, scale_plot = TRUE, alpha = 0.1), "r2d3")
})
test_that("plotD3_halfnormal", {
expect_is(plotD3(hn_glm, type = "halfnormal"), "r2d3")
expect_is(plotD3_halfnormal(hn_glm), "r2d3")
expect_is(plotD3_halfnormal(hn_glm, hn_rf, scale_plot = TRUE), "r2d3")
})
test_that("plotD3_roc", {
expect_is(plotD3(ev_glm, type = "roc"), "r2d3")
expect_is(plotD3_roc(ev_glm), "r2d3")
expect_is(plotD3_roc(ev_glm, ev_rf, scale_plot = TRUE), "r2d3")
})
test_that("plotD3_rroc", {
expect_is(plotD3(mr_glm, type = "rroc"), "r2d3")
expect_is(plotD3_rroc(mr_glm), "r2d3")
expect_is(plotD3_rroc(mr_glm, mr_rf, scale_plot = TRUE), "r2d3")
})
|
`write.Data` <-
function(x,FileNameExtension="Data"){
if (length(x)==3){
fillmat <- matrix("",nrow=nrow(x[[2]]),ncol=ncol(x[[3]]))
upperpart <- cbind(fillmat,as.matrix(x[[2]]))
upperpart[1:nrow(upperpart),ncol(x[[3]])] <- rownames(x[[2]])
lowerpart <- cbind(as.matrix(x[[3]]),x[[1]])
lowerpart <- rbind(colnames(lowerpart),lowerpart)
alldat <- rbind(upperpart,lowerpart)
colnames(alldat) <- colnames(lowerpart)
write.table(alldat,file=paste(labels(x)[1],".txt",sep="")
,sep="\t",,row.names=F,col.names=F)
}
if (length(x)==4){
fillmat <- matrix("",nrow=nrow(x[[3]]),ncol=ncol(x[[4]]))
upperpart <- cbind(fillmat,as.matrix(x[[3]]))
upperpart[1:nrow(upperpart),ncol(x[[4]])] <- rownames(x[[3]])
lowerpart <- cbind(as.matrix(x[[4]]),x[[1]])
lowerpart <- rbind(colnames(lowerpart),lowerpart)
lowerpartII <- cbind(as.matrix(x[[4]]),x[[2]])
lowerpartII <- rbind(colnames(lowerpart),lowerpartII)
alldat <- rbind(upperpart,lowerpart)
alldat[1:nrow(x[[3]]),ncol(x[[4]])] <- rownames(x[[3]])
alldatII <- rbind(upperpart,lowerpartII)
alldatII[1:nrow(x[[3]]),ncol(x[[4]])] <- rownames(x[[3]])
colnames(alldat) <- colnames(lowerpart)
colnames(alldatII) <- colnames(lowerpart)
write.table(alldat,file=paste(FileNameExtension,labels(x)[1],".txt",sep="")
,sep="\t",row.names=F,col.names=F)
write.table(alldatII,file=paste(FileNameExtension,labels(x)[2],".txt",sep="")
,sep="\t",row.names=F,col.names=F)
}
}
|
plot.SimulInactivation <- function(x, y=NULL, ...,
make_gg = TRUE, plot_temp = FALSE,
label_y1 = "logN",
label_y2 = "Temperature",
ylims = NULL) {
if (make_gg) {
if (plot_temp) {
min_time <- min(x$simulation$time)
max_time <- max(x$simulation$time)
max_count <- max(x$simulation$logN, na.rm = TRUE)
tt <- seq(min_time, max_time, length = 100)
min_temp <- min(x$temp_approximations$temp(tt))
max_temp <- max(x$temp_approximations$temp(tt))
if (max_temp == min_temp) {
max_temp <- max_temp + 1
min_temp <- min_temp - 1
}
slope <- (max_count)/(max_temp - min_temp)
intercept <- (min_temp * (max_count-0)/(max_temp - min_temp) - 0)
p <- x$simulation %>%
mutate(temperature = x$temp_approximations$temp(.data$time),
fake_temp = .data$temperature * slope - intercept) %>%
ggplot() +
geom_line(aes_string(x = "time", y = "logN"), linetype = 2) +
geom_line(aes_string(x = "time", y = "fake_temp"))
if (is.null(ylims)) {
ylims <- c(0, max_count)
}
p + scale_y_continuous(limits = ylims,
name = label_y1,
sec.axis = sec_axis(~(. + intercept)/slope,
name = label_y2))
} else {
p <- ggplot(x$simulation) +
geom_line(aes_string(x = "time", y = "logN")) +
ylab(label_y1)
if (!is.null(ylims)) {
p <- p + ylim(ylims)
}
p
}
} else {
plot(logN ~ time, data = x$simulation, type = "l", ...)
}
}
plot.IsoFitInactivation <- function(x, y=NULL, ..., make_gg = FALSE) {
if (!make_gg) {
death_data <- x$data
model_data <- get_isothermal_model_data(x$model)
for (each_temp in unique(death_data$temp)) {
temp_indexes <- death_data$temp == each_temp
my_data <- death_data[temp_indexes, ]
plot(log_diff ~ time, data = my_data, ...)
max_time <- max(my_data$time)
times <- seq(0, max_time, length= 100)
arguments_call <- c(list(time = times, temp = each_temp), x$parameters)
prediction <- do.call(model_data$prediction, arguments_call)
lines(times, prediction)
title(paste("Temperature:", each_temp))
}
} else {
x$data %>%
mutate(prediction = predict(x$nls, newdata = x$data)) %>%
ggplot(aes_string(x = "time")) +
geom_point(aes_string(y = "log_diff")) +
geom_line(aes_string(y = "prediction"), linetype = 2) +
facet_wrap("temp", scales = "free")
}
}
plot.FitInactivation <- function(x, y=NULL, ..., make_gg = TRUE,
plot_temp = FALSE,
label_y1 = "logN",
label_y2 = "Temperature",
ylims = NULL) {
death_data <- x$data
if (!("logN" %in% names(death_data))) {
death_data$logN <- log10(death_data$N)
}
if (make_gg) {
maxlogN0 <- max(c(x$data$logN,
log10(x$best_prediction$model_parameters$N0)))
if (is.null(ylims)) {
ylims <- c(0, ceiling(maxlogN0))
}
pred_plot <- plot(x$best_prediction, plot_temp = plot_temp,
label_y1 = label_y1, label_y2 = label_y2,
ylims = ylims)
p <- pred_plot +
geom_point(data = death_data, aes_string(x = "time", y = "logN"))
return(p)
} else {
min_logN_data <- min(death_data$logN, na.rm = TRUE)
min_logN_pred <- min(x$best_prediction$simulation$logN, na.rm = TRUE)
min_logN <- min(c(min_logN_data, min_logN_pred))
max_logN_data <- max(death_data$logN, na.rm = TRUE)
max_logN_pred <- max(x$best_prediction$simulation$logN, na.rm = TRUE)
max_logN <- max(c(max_logN_data, max_logN_pred))
ylim <- c(floor(min_logN), ceiling(max_logN))
plot(x$best_prediction, ylim = ylim, make_gg = FALSE, ...)
points(logN ~ time, data = death_data)
}
}
plot.FitInactivationMCMC <- function(x, y=NULL, ..., make_gg = TRUE,
plot_temp = FALSE,
label_y1 = "logN",
label_y2 = "Temperature",
ylims = NULL) {
plot.FitInactivation(x, make_gg = make_gg, plot_temp = plot_temp,
label_y1 = label_y1,
label_y2 = label_y2,
ylims = ylims,
...)
}
plot.PredInactivationMCMC <- function(x, y=NULL, ..., make_gg = TRUE) {
if (make_gg) {
if (!names(x)[2] == "mean"){
stop("ggplot plots not available for PredInactivationMCMC objects without
quantiles calculated. Generate base plot instead.")
}
x$mean <- log10(x[ , 2])
x$median <- log10(x[ , 3])
x$lower <- log10(x[ , 4])
x$upper <- log10(x[ , 5])
p <- ggplot(x, aes_string(x = "times")) +
geom_ribbon(aes_string(ymax = "upper", ymin = "lower"), alpha = 0.6, fill = "
geom_line(aes_string(y = "mean"), linetype = 2, colour = "darkblue") +
geom_line(aes_string(y = "median"), linetype = 3, colour = "darkblue") +
ylab("logN") + xlab("time")
return(p)
} else {
max_N <- max(x[1, 2:ncol(x)])
min_N <- min(x[nrow(x), 2:ncol(x)])
y_lim <- c(floor(log10(min_N)), ceiling(log10(max_N)))
if ("mean" %in% names(x)) {
plot(log10(mean) ~ times, data = x, type = 'l',
ylab = "logN", ylim = y_lim, ...)
} else {
plot(x$times, log10(x[ , 2]), type = "l", ...)
}
for (i in 3:ncol(x)) {
lines(x$times, log10(x[ , i]), type = 'l', lty = i-1, col = i-1)
}
if ("mean" %in% names(x)) {
legend("topright", names(x[-1]), lty = 1:(ncol(x)-1), col = 1:(ncol(x)-1))
}
}
}
|
context("tp_refs")
test_that("tp_refs returns the correct class", {
skip_on_cran()
vcr::use_cassette("tp_refs", {
ttt <- suppressMessages(tp_refs(id = 25509881))
}, preserve_exact_body_bytes = TRUE)
expect_that(ttt, is_a("data.frame"))
})
|
context("MfTrapezoidalSup")
test_that("MfTrapezoidalSup constructor error", {
expect_error(NewMfTrapezoidalSup())
expect_error(NewMfTrapezoidalSup(1, 0))
expect_error(NewMfTrapezoidalSup(0, 0))
})
test_that("MfTrapezoidalSup degrees", {
mf <- NewMfTrapezoidalSup(0, 1)
expect_equal(mf$degree(0), 0)
expect_equal(mf$degree(0.5), 0.5)
expect_equal(mf$degree(1), 1)
})
test_that("MfTrapezoidalSup equality", {
mf1 <- NewMfTrapezoidalSup(0, 1)
mf2 <- NewMfTrapezoidalSup(0, 1)
mf3 <- NewMfTrapezoidalSup(0, 2)
expect_equal(mf1, mf2)
expect_not_equal(mf1, mf3)
})
test_that("MfTrapezoidalSup to_string", {
mf <- NewMfTrapezoidalSup(0, 1)
mf$label <- "foo"
expect_equal(mf$to_string(), "mf_trapezoidal_sup(\"foo\", 0, 1)")
})
|
"genRetFct" <- function(fct, parmVec, notFixed)
{
}
|
.inRStudio = function() {
requireNamespace("rstudioapi", quietly = TRUE) &&
!is(tryCatch(rstudioapi::versionInfo(), error = function(x) x),
"error")
}
.analysisFileOrNA = function() {
if(.inRStudio())
tryCatch(rstudioapi::getSourceEditorContext()[["path"]],
error = function(x) NA_character_)
else
NA_character_
}
.rstudioProjOrNA = function() {
proj = NA_character_
if(.inRStudio()) {
proj = rstudioapi::getActiveProject()
if(is.null(proj)) proj = NA_character_
}
proj
}
|
context("Test MQE_proc")
library(testthat)
library(mppR)
Ref_res <- c(0.000000, -1.732895, -1.732895, -3.064966, -3.064966, -6.127131)
data(mppData)
res <- MQE_proc(pop.name = "USNAM", trait.name = "ULA",
mppData = mppData, Q.eff = c('cr', 'par', 'anc', 'biall'),
output.loc = tempdir(), verbose = FALSE)
test_that('MQE_test', {
expect_equal(object = res$QTL.effects$Q1$Effect,
expected = Ref_res, tolerance = .0001)
})
|
test_that("distance works", {
expect_equivalent(round(track_distance(c(0, 0, 1, 0), c(0, 1, 1, 0)), digits = 2L),
c(NA, 110574.39, 111302.65, 156899.57))
})
|
sf_submit_query_bulk <- function(job_id,
soql,
api_type = c("Bulk 1.0"),
verbose = FALSE){
api_type <- match.arg(api_type)
bulk_query_url <- make_bulk_query_url(job_id, api_type = api_type)
f <- tempfile()
cat(soql, file=f)
httr_response <- rPOST(url = bulk_query_url,
headers = c("Content-Type"="text/csv; charset=UTF-8"),
body = upload_file(path=f, type='text/txt'))
if(verbose){
make_verbose_httr_message(httr_response$request$method,
httr_response$request$url,
httr_response$request$headers,
sprintf("Uploaded TXT file: %s", f))
}
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding="UTF-8")
resultset <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('//batchInfo') %>%
map_df(xml_nodeset_to_df) %>%
type_convert(col_types = cols())
return(resultset)
}
sf_query_result_bulk <- function(job_id,
batch_id = NULL,
result_id = NULL,
guess_types = TRUE,
bind_using_character_cols = deprecated(),
batch_size = 50000,
api_type = c("Bulk 1.0", "Bulk 2.0"),
verbose = FALSE){
api_type <- match.arg(api_type)
if(is_present(bind_using_character_cols)) {
deprecate_warn("1.0.0",
"salesforcer::sf_query_result_bulk(bind_using_character_cols)",
details = paste0("The `bind_using_character_cols` functionality ",
"will always be `TRUE` going forward. Per the ",
"{readr} package, we have to read as character ",
"and then invoke `type_convert()` in order to ",
"use all values in a column to guess its type."))
}
if(api_type == "Bulk 2.0"){
resultset <- sf_query_result_bulk_v2(job_id = job_id,
guess_types = guess_types,
batch_size = batch_size,
locator = NULL,
api_type = api_type,
verbose = verbose)
} else {
resultset <- sf_query_result_bulk_v1(job_id = job_id,
batch_id = batch_id,
result_id = result_id,
guess_types = guess_types,
api_type = api_type,
verbose = verbose)
}
return(resultset)
}
sf_query_result_bulk_v1 <- function(job_id,
batch_id = NULL,
result_id = NULL,
guess_types = TRUE,
bind_using_character_cols = deprecated(),
api_type = c("Bulk 1.0"),
verbose = FALSE){
api_type <- match.arg(api_type)
if(is_present(bind_using_character_cols)) {
deprecate_warn("1.0.0",
"salesforcer::sf_query_result_bulk_v1(bind_using_character_cols)",
details = paste0("The `bind_using_character_cols` functionality ",
"will always be `TRUE` going forward. Per the ",
"{readr} package, we have to read as character ",
"and then invoke `type_convert()` in order to ",
"use all values in a column to guess its type."))
}
bulk_query_result_url <- make_bulk_query_result_url(job_id, batch_id, result_id, api_type)
httr_response <- rGET(url = bulk_query_result_url)
if(verbose){
make_verbose_httr_message(httr_response$request$method,
httr_response$request$url,
httr_response$request$headers)
}
catch_errors(httr_response)
content_type <- httr_response$headers$`content-type`
if (grepl('xml', content_type)) {
response_text <- content(httr_response, type="text/plain", encoding="UTF-8")
resultset <- as_tibble(xmlToList(response_text))
} else if(grepl('text/csv', content_type)) {
response_text <- content(httr_response, type="text", encoding="UTF-8")
if(response_text == "Records not found for this query"){
resultset <- tibble()
} else {
resultset <- read_csv(response_text, col_types = cols(.default = col_character()))
}
} else {
message(sprintf("Unhandled content-type: %s", content_type))
resultset <- content(httr_response, as="parsed", encoding="UTF-8")
}
if(is.tbl(resultset)){
resultset <- resultset %>%
sf_reorder_cols() %>%
sf_guess_cols(guess_types)
}
return(resultset)
}
sf_query_result_bulk_v2 <- function(job_id,
guess_types = TRUE,
bind_using_character_cols = deprecated(),
batch_size = 50000,
locator = NULL,
api_type = c("Bulk 2.0"),
verbose = FALSE){
api_type <- match.arg(api_type)
if(is_present(bind_using_character_cols)) {
deprecate_warn("1.0.0",
"salesforcer::sf_query_result_bulk_v2(bind_using_character_cols)",
details = paste0("The `bind_using_character_cols` functionality ",
"will always be `TRUE` going forward. Per the ",
"{readr} package, we have to read as character ",
"and then invoke `type_convert()` in order to ",
"use all values in a column to guess its type."))
}
bulk_query_result_url <- make_bulk_query_result_url(job_id, api_type=api_type)
query_params <- list(locator=locator, maxRecords=batch_size)
bulk_query_result_url <- parse_url(bulk_query_result_url)
bulk_query_result_url$query <- query_params
bulk_query_result_url <- build_url(bulk_query_result_url)
httr_response <- rGET(url = bulk_query_result_url, headers = c("Accept"="text/csv"))
if(verbose){
make_verbose_httr_message(httr_response$request$method,
httr_response$request$url,
httr_response$request$headers)
}
catch_errors(httr_response)
content_type <- httr_response$headers$`content-type`
if(grepl('text/csv', content_type)) {
response_text <- content(httr_response, as="text", encoding="UTF-8")
resultset <- read_csv(response_text, col_types = cols(.default = col_character()))
} else {
message(sprintf("Unexpected content-type: %s", content_type))
resultset <- content(httr_response, as="parsed", encoding="UTF-8")
}
locator <- httr_response$headers$`sforce-locator`
if(!is.null(locator) && locator != "null"){
next_records <- sf_query_result_bulk_v2(job_id = job_id,
guess_types = guess_types,
batch_size = batch_size,
locator = locator,
api_type = api_type,
verbose = verbose)
resultset <- safe_bind_rows(list(resultset, next_records))
}
if(is.tbl(resultset)){
resultset <- resultset %>%
sf_reorder_cols() %>%
sf_guess_cols(guess_types)
}
return(resultset)
}
sf_query_bulk_v1 <- function(soql,
object_name = NULL,
queryall = FALSE,
guess_types = TRUE,
bind_using_character_cols = deprecated(),
interval_seconds = 3,
max_attempts = 200,
control = list(...), ...,
api_type = "Bulk 1.0",
verbose = FALSE){
if(is.null(object_name)){
object_name <- guess_object_name_from_soql(soql)
}
listed_objects <- sf_list_objects()
valid_object_names <- sapply(listed_objects$sobjects, FUN=function(x){x$name})
if(!object_name %in% valid_object_names){
stop(sprintf(paste0("The supplied object name (%s) does not exist or ",
"the user does not have permission to view"), object_name),
call.=FALSE)
}
api_type <- match.arg(api_type)
control_args <- return_matching_controls(control)
control_args$api_type <- api_type
this_operation <- if(queryall) "queryall" else "query"
control_args$operation <- this_operation
if(is_present(bind_using_character_cols)) {
deprecate_warn("1.0.0",
"salesforcer::sf_query_bulk_v1(bind_using_character_cols)",
details = paste0("The `bind_using_character_cols` functionality ",
"will always be `TRUE` going forward. Per the ",
"{readr} package, we have to read as character ",
"and then invoke `type_convert()` in order to ",
"use all values in a column to guess its type."))
}
job_info <- sf_create_job_bulk(operation = this_operation,
object_name = object_name,
api_type = api_type,
control = control_args,
verbose = verbose, ...)
batch_query_info <- sf_submit_query_bulk(job_id = job_info$id,
soql = soql,
api_type = api_type,
verbose = verbose)
status_complete <- FALSE
z <- 1
Sys.sleep(interval_seconds)
while (z < max_attempts & !status_complete){
if (verbose){
message(paste0("Attempt
}
Sys.sleep(interval_seconds)
batch_query_status <- sf_batch_status_bulk(job_id = batch_query_info$jobId,
batch_id = batch_query_info$id,
api_type = api_type,
verbose = verbose)
if(batch_query_status$state == 'Failed'){
stop(batch_query_status$stateMessage)
} else if(batch_query_status$state == "Completed"){
status_complete <- TRUE
} else if(batch_query_status$state == "NotProcessed") {
job_batches <- sf_job_batches_bulk(batch_query_status$jobId,
api_type = api_type,
verbose = verbose)
batch_query_info <- job_batches %>%
filter(across(any_of("state"), ~(.x != 'NotProcessed')))
if(all(batch_query_info$state == "Completed")){
status_complete <- TRUE
}
} else {
z <- z + 1
}
}
if (!status_complete) {
message("The query took too long to complete. Aborting job now.")
message("Consider increasing the `max_attempts` and/or `interval_seconds` arguments.")
resultset <- sf_abort_job_bulk(job_info$id, api_type=api_type, verbose=verbose)
} else {
resultset <- list()
for(i in 1:nrow(batch_query_info)){
batch_query_details <- sf_batch_details_bulk(job_id = batch_query_info$jobId[i],
batch_id = batch_query_info$id[i],
api_type = api_type,
verbose = verbose)
resultset[[i]] <- sf_query_result_bulk(job_id = batch_query_info$jobId[i],
batch_id = batch_query_info$id[i],
result_id = batch_query_details$result,
guess_types = guess_types,
api_type = api_type,
verbose = verbose)
}
resultset <- safe_bind_rows(resultset)
close_job_info <- sf_close_job_bulk(job_info$id,
api_type = api_type,
verbose = verbose)
}
if(is.tbl(resultset)){
resultset <- resultset %>%
sf_reorder_cols() %>%
sf_guess_cols(guess_types)
}
return(resultset)
}
sf_query_bulk_v2 <- function(soql,
object_name = NULL,
queryall = FALSE,
guess_types = TRUE,
bind_using_character_cols = deprecated(),
interval_seconds = 3,
max_attempts = 200,
control = list(...), ...,
api_type = "Bulk 2.0",
verbose = FALSE){
if(!is.null(object_name)){
listed_objects <- sf_list_objects()
valid_object_names <- sapply(listed_objects$sobjects, FUN=function(x){x$name})
if(!object_name %in% valid_object_names){
stop(sprintf(paste0("The supplied object name (%s) does not exist or ",
"the user does not have permission to view"), object_name),
call.=FALSE)
}
}
api_type <- match.arg(api_type)
control_args <- return_matching_controls(control)
control_args$api_type <- api_type
this_operation <- if(queryall) "queryall" else "query"
control_args$operation <- this_operation
if(is_present(bind_using_character_cols)) {
deprecate_warn("1.0.0",
"salesforcer::sf_query_bulk_v2(bind_using_character_cols)",
details = paste0("The `bind_using_character_cols` functionality ",
"will always be `TRUE` going forward. Per the ",
"{readr} package, we have to read as character ",
"and then invoke `type_convert()` in order to ",
"use all values in a column to guess its type."))
}
if(!is.null(control_args$QueryOptions$batchSize)){
batch_size <- control_args$QueryOptions$batchSize
control_args$QueryOptions <- NULL
} else {
batch_size <- 50000
}
job_info <- sf_create_job_bulk(operation = this_operation,
soql = soql,
object_name = object_name,
api_type = api_type,
control = control_args,
verbose = verbose, ...)
status_complete <- FALSE
z <- 1
Sys.sleep(interval_seconds)
while (z < max_attempts & !status_complete){
if (verbose){
message(paste0("Attempt
}
Sys.sleep(interval_seconds)
query_status <- sf_get_job_bulk(job_info$id, api_type=api_type, query_operation=TRUE)
if(query_status$state == 'Failed'){
stop(query_status$errorMessage)
} else if(query_status$state == "JobComplete"){
status_complete <- TRUE
} else {
z <- z + 1
}
}
if (!status_complete) {
message("The query took too long to complete. Aborting job now.")
message("Consider increasing the `max_attempts` and/or `interval_seconds` arguments.")
res <- sf_abort_job_bulk(job_info$id, api_type=api_type, verbose=verbose)
} else {
res <- sf_query_result_bulk(job_id = job_info$id,
guess_types = guess_types,
batch_size = batch_size,
api_type = api_type,
verbose = verbose)
}
return(res)
}
sf_run_bulk_query <- function(soql,
object_name = NULL,
queryall = FALSE,
guess_types = TRUE,
bind_using_character_cols = deprecated(),
interval_seconds = 3,
max_attempts = 200,
control = list(...), ...,
api_type = c("Bulk 2.0", "Bulk 1.0"),
verbose = FALSE){
api_type <- match.arg(api_type)
control_args <- return_matching_controls(control)
control_args$api_type <- api_type
control_args$operation <- if(queryall) "queryall" else "query"
if(is_present(bind_using_character_cols)) {
deprecate_warn("1.0.0",
"salesforcer::sf_run_bulk_query(bind_using_character_cols)",
details = paste0("The `bind_using_character_cols` functionality ",
"will always be `TRUE` going forward. Per the ",
"{readr} package, we have to read as character ",
"and then invoke `type_convert()` in order to ",
"use all values in a column to guess its type."))
}
if(api_type == "Bulk 2.0"){
resultset <- sf_query_bulk_v2(soql = soql,
object_name = object_name,
queryall = queryall,
guess_types = guess_types,
interval_seconds = interval_seconds,
max_attempts = max_attempts,
control = control_args, ...,
api_type = api_type,
verbose = verbose)
} else {
resultset <- sf_query_bulk_v1(soql = soql,
object_name = object_name,
queryall = queryall,
guess_types = guess_types,
interval_seconds = interval_seconds,
max_attempts = max_attempts,
control = control_args, ...,
api_type = api_type,
verbose = verbose)
}
return(resultset)
}
sf_query_bulk <- sf_run_bulk_query
|
bttree <- function(formula, data, na.action, cluster,
type = "loglin", ref = NULL, undecided = NULL, position = NULL, ...)
{
cl <- match.call(expand.dots = TRUE)
control <- mob_control(...)
btcontrol <- list(type = type, ref = ref, undecided = undecided, position = position)
m <- match.call(expand.dots = FALSE)
m$fit <- btfit
m$control <- control
for(n in names(btcontrol)) if(!is.null(btcontrol[[n]])) m[[n]] <- btcontrol[[n]]
if("..." %in% names(m)) m[["..."]] <- NULL
m[[1L]] <- as.name("mob")
rval <- eval(m, parent.frame())
rval$info$call <- cl
class(rval) <- c("bttree", class(rval))
return(rval)
}
btfit <- function(y, x = NULL, start = NULL, weights = NULL, offset = NULL,
cluster = NULL, ..., estfun = FALSE, object = FALSE)
{
if(!(is.null(x) || NCOL(x) == 0L)) warning("x not used")
if(!is.null(offset)) warning("offset not used")
rval <- btmodel(y, weights = weights, ..., vcov = object)
rval <- list(
coefficients = rval$coefficients,
objfun = -rval$loglik,
estfun = if(estfun) estfun.btmodel(rval) else NULL,
object = if(object) rval else NULL
)
return(rval)
}
print.bttree <- function(x,
title = "Bradley-Terry tree", objfun = "negative log-likelihood", ...)
{
partykit::print.modelparty(x, title = title, objfun = objfun, ...)
}
predict.bttree <- function(object, newdata = NULL,
type = c("worth", "rank", "best", "node"), ...)
{
type <- match.arg(type)
if(type == "node") return(partykit::predict.modelparty(object, newdata = newdata, type = "node", ...))
if(is.null(newdata)) newdata <- model.frame(object)
pred <- switch(type,
"worth" = function(obj, ...) rbind(itempar(obj)),
"rank" = function(obj, ...) rbind(rank(-itempar(obj))),
"best" = function(obj, ...) {
wrth <- itempar(obj)
factor(names(wrth)[which.max(wrth)], levels = names(wrth))
}
)
partykit::predict.modelparty(object, newdata = newdata, type = pred, ...)
}
plot.bttree <- function(x, terminal_panel = node_btplot,
tp_args = list(...), tnex = NULL, drop_terminal = NULL, ...)
{
if(is.null(tnex)) tnex <- if(is.null(terminal_panel)) 1L else 2L
if(is.null(drop_terminal)) drop_terminal <- !is.null(terminal_panel)
partykit::plot.modelparty(x, terminal_panel = terminal_panel,
tp_args = tp_args, tnex = tnex, drop_terminal = drop_terminal, ...)
}
|
print_progress <- function(iter.times, showpars){
if(!any("show.iters" == names(showpars))) showpars$show.iters <- "numbers"
if(!any("showevery" == names(showpars))) showpars$showevery <- 10
iter <- sum(iter.times != 0)
assertthat::assert_that(
assertthat::is.count(showpars$showevery),
length(showpars$show.iters) == 1,
showpars$show.iters %in% c("dots", "numbers", "none"),
length(showpars$showevery) == 1)
if (showpars$show.iters != "none"){
if (iter == 1) cat("\nMOEA/D running: ")
if (iter %% showpars$showevery == 0){
if (showpars$show.iters == "dots") cat(".")
if (showpars$show.iters == "numbers") cat("\nIteration:", iter,
" | Elapsed time:",
iter.times[iter],
"seconds")
}
}
}
|
edge_nn <- function(DT = NULL,
id = NULL,
coords = NULL,
timegroup,
splitBy = NULL,
threshold = NULL,
returnDist = FALSE) {
N <- NULL
if (is.null(DT)) {
stop('input DT required')
}
if (!is.null(threshold)) {
if (!is.numeric(threshold)) {
stop('threshold must be numeric')
}
if (threshold <= 0) {
stop('threshold must be greater than 0')
}
}
if (is.null(id)) {
stop('ID field required')
}
if (length(coords) != 2) {
stop('coords requires a vector of column names for coordinates X and Y')
}
if (missing(timegroup)) {
stop('timegroup required')
}
if (any(!(
c(timegroup, id, coords, splitBy) %in% colnames(DT)
))) {
stop(paste0(
as.character(paste(setdiff(
c(timegroup, id, coords, splitBy),
colnames(DT)
), collapse = ', ')),
' field(s) provided are not present in input DT'
))
}
if (any(!(DT[, vapply(.SD, is.numeric, TRUE), .SDcols = coords]))) {
stop('coords must be numeric')
}
if (!is.null(timegroup)) {
if (any(unlist(lapply(DT[, .SD, .SDcols = timegroup], class)) %in%
c('POSIXct', 'POSIXlt', 'Date', 'IDate', 'ITime', 'character'))) {
warning(
strwrap(
prefix = " ",
initial = "",
x = 'timegroup provided is a date/time
or character type, did you use group_times?'
)
)
}
}
if (is.null(timegroup) && is.null(splitBy)) {
splitBy <- NULL
} else {
splitBy <- c(splitBy, timegroup)
if (DT[, .N, by = c(id, splitBy, timegroup)][N > 1, sum(N)] != 0) {
warning(
strwrap(
prefix = " ",
initial = "",
x = 'found duplicate id in a
timegroup and/or splitBy -
does your group_times threshold match the fix rate?'
)
)
}
}
DT[, {
distMatrix <-
as.matrix(stats::dist(.SD[, 2:3], method = 'euclidean'))
diag(distMatrix) <- NA
if (is.null(threshold)) {
wm <- apply(distMatrix, MARGIN = 2, which.min)
} else {
distMatrix[distMatrix > threshold] <- NA
wm <- apply(distMatrix, MARGIN = 2,
function(x) ifelse(sum(!is.na(x)) > 0, which.min(x), NA))
}
if (returnDist) {
w <- wm + (length(wm) * (as.numeric(names(wm)) - 1))
l <- list(ID = .SD[[1]][as.numeric(names(wm))],
NN = .SD[[1]][wm],
distance = distMatrix[w])
} else {
l <- list(ID = .SD[[1]][as.numeric(names(wm))],
NN = .SD[[1]][wm])
}
l
},
by = splitBy, .SDcols = c(id, coords)]
}
|
"as.membership"<-function(member){
ifelse(is.membership(member),
return(member),
return(membership(member,
K=ncol(member),
n=nrow(member))))
}
|
fun1()
fun2()
fun3()
fun4(1)
fun4(1L)
|
"perform" <- function(data)
{
k <- 0
for(j in 1:nrow(data)) {
k <- k + data[j, j]
}
total <- sum(data)
wrong <- total - k
correct <- (k/total) * 100
wrong <- wrong/total * 100
labcol <- c("correct %", "incorrect %")
m <- cbind(correct, wrong)
dimnames(m) <- list(NULL, labcol)
m
}
|
context("lsat_scene_files")
ub <- "https://s3-us-west-2.amazonaws.com/landsat-pds/L8"
url1 <- paste0(ub, "/010/117/LC80101172015002LGN00/index.html")
url2 <- paste0(ub, "/026/039/LC80260392015002LGN00/index.html")
test_that("lsat_scene_files, n_max parameter usage", {
skip_on_cran()
a <- lsat_scene_files(url1)
expect_is(a, "data.frame")
expect_named(a, c('file', 'size'))
expect_is(a$file, "character")
expect_is(a$size, "character")
b <- lsat_scene_files(url2)
expect_is(b, "data.frame")
expect_named(b, c('file', 'size'))
expect_is(b$file, "character")
expect_is(b$size, "character")
})
test_that("lsat_scene_files, fails well", {
expect_error(lsat_scene_files("asdfadf"), "input needs to be a URL")
})
test_that("lsat_scene_files, curl options work", {
expect_error(lsat_scene_files(url1, timeout_ms = 10),
"Timeout was reached")
})
|
partUtil <- function(obs,query,ncl,th,xcoord='x',ycoord='y',tcoord='t',fac=1.0)
{
batchTime <- function(range,th,cutoff=0.3){
max <- floor(range/(2*th))
nbin<-seq(2,max)
overlap <- 2*th+pmax(nbin-2,0)*2*th
pct <- overlap/range
if (min(pct)>=0.3){
index <- 1
}
else{
index <- max(which(pct<0.3))
}
nbin[index]
}
timeRange <- (range(query[,tcoord],obs[,tcoord],na.rm=T))+c(-1e-10,.001)
lonr <- range(query[,xcoord],obs[,xcoord])+c(-1e-10,.001)
latr <- range(query[,ycoord],obs[,ycoord])+c(-1e-10,.001)
batch.Time <- batchTime(diff(timeRange),th[2])
batch.Space <- ceiling(ncl*fac/batch.Time)
batch.X <- ceiling(sqrt(batch.Space))
batch.Y <- ceiling(sqrt(batch.Space))
tstampb <- seq(timeRange[1],timeRange[2],len=batch.Time+1)
tsid <- findInterval(query[,tcoord],tstampb)
lonb <- seq(lonr[1],lonr[2],len=batch.X+1)
latb <- seq(latr[1],latr[2],len=batch.Y+1)
lonid <- findInterval(query[,xcoord],lonb)
latid <- findInterval(query[,ycoord],latb)
query.id <- expand.grid(x=unique(lonid),y=unique(latid),t=unique(tsid))
obsInt <- function(bins,th)
{
nbatch <- length(bins)-1
tstampo <- cbind(bins[-(nbatch+1)],bins[-1])
tstampo[-1,1]<- tstampo[-1,1]-th
tstampo[-(nbatch),2]<- tstampo[-(nbatch),2]+th
tstampo
}
tstampo<- obsInt(tstampb,th[2])
latbo <- obsInt(latb,th[1])
lonbo <- obsInt(lonb,th[1])
findInt <- function(x)
{
id1 <- which(obs[,tcoord]<tstampo[x[3],2] & obs[,tcoord]>tstampo[x[3],1])
if(length(id1)>0){
tmp <- obs[id1,]
id2 <- which(tmp[,xcoord]<lonbo[x[1],2] & tmp[,xcoord]>lonbo[x[1],1])
if(length(id2)>0){
tmp2 <- tmp[id2,]
id3 <- which(tmp2[,ycoord]<latbo[x[2],2] & tmp2[,ycoord]>latbo[x[2],1])
if(length(id3)>0){r <- id1[id2[id3]]}
else{r <- NULL}
}
else{
r <- NULL
}
}
else{
r <- NULL
}
r
}
tolist <- function(x)
{
if(class(x)=="list"){
r <- x
}
else if(is.null(dim(x))){
r <- split(x,seq(along=x))
}
else if(length(dim(x))==2){
r <- split(x, rep(1:ncol(x), each = nrow(x)))
}
else{
stop(x," is not a matrix or vector")
}
r
}
query.list <- apply(query.id,1,function(x) which(lonid==x[1]&latid==x[2]&tsid==x[3]))
query.list <- tolist(query.list)
obs.list <- apply(query.id,1,findInt)
obs.list <- tolist(obs.list)
nQuery <- sapply(query.list,length)
list(query=query.list[nQuery>0],obs=obs.list[nQuery>0])
}
partSpUtil <- function(obs,query,ncl,th,xcoord='x',ycoord='y',fac=1.2){
batch.Space <- ceiling(ncl*fac)
batch.X <- ceiling(sqrt(batch.Space))
batch.Y <- ceiling(sqrt(batch.Space))
lonr <- range(query[,xcoord])+c(-1e-10,.001)
latr <- range(query[,ycoord])+c(-1e-10,.001)
lonb <- seq(lonr[1],lonr[2],len=batch.X+1)
latb <- seq(latr[1],latr[2],len=batch.Y+1)
lonid <- findInterval(query[,xcoord],lonb)
latid <- findInterval(query[,ycoord],latb)
query.id <- expand.grid(x=unique(lonid),y=unique(latid))
obsInt <- function(bins,th)
{
nbatch <- length(bins)-1
tstampo <- cbind(bins[-(nbatch+1)],bins[-1])
tstampo[-1,1]<- tstampo[-1,1]-th
tstampo[-(nbatch),2]<- tstampo[-(nbatch),2]+th
tstampo
}
latbo <- obsInt(latb,th)
lonbo <- obsInt(lonb,th)
findInt <- function(x)
{
id1 <- rep(1:nrow(obs))
if(length(id1)>0){
tmp <- obs[id1,]
id2 <- which(tmp[,xcoord]<lonbo[x[1],2] & tmp[,xcoord]>lonbo[x[1],1])
if(length(id2)>0){
tmp2 <- tmp[id2,]
id3 <- which(tmp2[,ycoord]<latbo[x[2],2] & tmp2[,ycoord]>latbo[x[2],1])
if(length(id3)>0){r <- id1[id2[id3]]}
else{r <- NULL}
}
else{
r <- NULL
}
}
else{
r <- NULL
}
r
}
tolist <- function(x)
{
if(class(x)=="list"){
r <- x
}
else if(is.null(dim(x))){
r <- split(x,seq(along=x))
}
else if(length(dim(x))==2){
r <- split(x, rep(1:ncol(x), each = nrow(x)))
}
else{
stop(x," is not a matrix or vector")
}
r
}
query.list <- apply(query.id,1,function(x) which(lonid==x[1]&latid==x[2]))
query.list <- tolist(query.list)
obs.list <- apply(query.id,1,findInt)
obs.list <- tolist(obs.list)
nQuery <- sapply(query.list,length)
list(query=query.list[nQuery>0],obs=obs.list[nQuery>0])
}
|
NULL
setMethod("dbGetInfo", signature("DBIMockConnection"), function(dbObj, ...) {
path <- make_path(dbObj@path, "conInfo", "")
return(read_file(find_file(path)))
})
setMethod(
"dbWriteTable", signature("DBIMockConnection", "character", "data.frame"),
function(conn, name, value, ...) return(TRUE)
)
setMethod(
"dbRemoveTable", signature("DBIMockConnection", "character"),
function(conn, name, ...) return(TRUE)
)
setMethod("dbColumnInfo", signature("DBIMockResult"), function(res, ...) {
path <- make_path(res@path, "columnInfo", res@hash)
return(read_file(find_file(path)))
})
setMethod("dbGetInfo", signature("DBIMockResult"), function(dbObj, ...) {
path <- make_path(dbObj@path, "resultInfo", dbObj@hash)
return(read_file(find_file(path)))
})
|
create_test_treelog <- function(
filename = create_temp_treelog_filename(),
log_every = 1000,
mode = "tree",
sanitise_headers = FALSE,
sort = "none"
) {
beautier::create_treelog(
filename = filename,
log_every = log_every,
mode = mode,
sanitise_headers = sanitise_headers,
sort = sort
)
}
|
expected <- eval(parse(text="c(11354, 11382, 11413)"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(11354, 11382, 11413), class = \"Date\"))"));
do.call(`xtfrm`, argv);
}, o=expected);
|
output$doc_info <- shiny::renderText({
display_document_info(session_variables$data_day, min_rad)
})
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
message=FALSE,
warning=FALSE
)
library(igraph)
library(signnet)
el <- matrix(c(1,"a",1,"b",1,"c",2,"a",2,"b"),ncol = 2,byrow = TRUE)
g <- graph_from_edgelist(el,directed = FALSE)
E(g)$sign <- c(1,1,-1,1,-1)
V(g)$type <- c(FALSE,TRUE,TRUE,TRUE,FALSE)
knitr::include_graphics("small_signed2mode.png")
A <- as_incidence_signed(g)
R <- A%*%t(A)
C <- t(A)%*%A
R
C
gu <- as_unsigned_2mode(g,primary = TRUE)
gu
pu <- bipartite_projection(gu,which = "true")
pu <- delete_edge_attr(pu,"weight")
pu
ps <- as_signed_proj(pu)
as_data_frame(ps,"edges")
|
table2x2 <- function(x,digits=1,stats=c("table","rd","rr","or","chisq","fisher")){
if (class(x)[1]=="data.frame"){
table2x2 <- as.matrix(x)
} else{
if ("matrix"%in%class(x)||"table" %in% class(x)){
if ("table"%in%class(x)){table2x2 <- as.matrix(x)}
else table2x2 <- x
} else{
stop("first argument `x' must be a matrix or a data.frame")
}
}
if (NROW(x)!=2) stop("Matrix must have exactly 2 rows")
if (NCOL(x)!=2) stop("Matrix must have exactly 2 columns")
a <- table2x2[1,1]
b <- table2x2[1,2]
c <- table2x2[2,1]
d <- table2x2[2,2]
p1 <- a/(a+b)
p2 <- c/(c+d)
out <- list(table2x2=table2x2,stats=stats)
if ("rd" %in% stats){
rd <- (p1-p2)
se.rd <- sqrt(p1*(1-p1)/(a+b)+p2*(1-p2)/(c+d))
rd.lower <- rd - qnorm(1-0.05/2)*se.rd
rd.upper <- rd + qnorm(1-0.05/2)*se.rd
out <- c(out,list(rd=rd,se.rd=se.rd,rd.lower=rd.lower,rd.upper=rd.upper))
}
if ("rr" %in% stats){
rr <- p1/p2
se.rr <- sqrt((1-p1)/a+(1-p2)/c)
rr.lower <- rr * exp(- qnorm(1-0.05/2) * se.rr)
rr.upper <- rr * exp( qnorm(1-0.05/2) * se.rr)
out <- c(out,list(rr=rr,se.rr=rr,rr.lower=rr.lower,rr.upper=rr.upper))
}
if ("or" %in% stats){
or <- (a*d)/(b*c)
se.or <- sqrt(1/a+1/b+1/c+1/d)
or.lower <- exp(log(or) - qnorm(1-0.05/2)*se.or)
or.upper <- exp(log(or) + qnorm(1-0.05/2)*se.or)
out <- c(out,list(or=or,se.or=se.or,or.lower=or.lower,or.upper=or.upper))
}
class(out) <- "table2x2"
out
}
|
dlc <- function(X, maxk) {
n <- dim(X)[1]
D <- matrix(0, n, n)
rownames(D) <- 1:n
colnames(D) <- 1:n
result <- sapply(1:(n - 1), function(x) dia(X, x, n))
result <- do.call("c", result)
D[lower.tri(D)] <- result
D <- t(D)
D[lower.tri(D)] <- result
L <- matrix(0, n - 1, maxk - 1)
rownames(L) <- 2:n
colnames(L) <- 2:maxk
C <- matrix(0, n - 1, maxk - 1)
rownames(C) <- 2:n
colnames(C) <- 2:maxk
diag(C) <- 2:maxk
lc <- sapply(
3:n,
function(x) {
c(
min(D[1, 1:(x - 1)] + D[2:x, x]),
which.min(D[1, 1:(x - 1)] + D[2:x, x])[1] + 1
)
}
)
L[as.character(3:n), "2"] <- lc[1, ]
C[as.character(3:n), "2"] <- lc[2, ]
for (j in 3:maxk) {
lc <- sapply(
(j + 1):n,
function(x) {
c(
min(L[(j:x) - 2, j - 2] + D[j:x, x]),
which.min(L[(j:x) - 2, j - 2] + D[j:x, x])[1] + j - 1
)
}
)
L[as.character((j + 1):n), as.character(j)] <- lc[1, ]
C[as.character((j + 1):n), as.character(j)] <- lc[2, ]
}
list("D" = D, "L" = L, "C" = C)
}
|
null_permute <- function(var) {
function(df) {
df[[var]] <- sample(df[[var]])
df
}
}
|
context("Test integral scores")
test_that("Expected sample size is computed correctly",{
null <- PointMassPrior(.0, 1)
alternative <- PointMassPrior(.4, 1)
dist <- Normal()
design_rp2 <- rpact::getDesignInverseNormal(
kMax = 2, alpha = 0.05, beta = 0.2, futilityBounds = 0, typeOfDesign = "P")
res <- rpact::getSampleSizeMeans(
design_rp2, normalApproximation = TRUE, alternative = .4)
char <- rpact::getDesignCharacteristics(design_rp2)
n1 <- res$numberOfSubjects1[1, 1]
n2 <- res$numberOfSubjects1[2, 1] - n1
c1f <- qnorm(char$futilityProbabilities) +
sqrt(res$numberOfSubjects1[1]) * .4 / sqrt(2)
c1e <- design_rp2$criticalValues[1]
f <- function(z){
w1 <- 1 / sqrt(2)
w2 <- sqrt(1 - w1^2)
out <- (design_rp2$criticalValues[2] - w1 * z) / w2
return(out)
}
x <- adoptr:::GaussLegendreRule(5)$nodes
h <- (c1e - c1f) / 2
x <- h * x + (h + c1f)
design_gs <<- TwoStageDesign(
n1,
c1f,
c1e,
rep(n2, 5),
sapply(x, f))
sim_alt <<- simulate(
design_gs, nsim = 1e4, dist = Normal(), theta = .4, seed = 59)
sim_null <<- simulate(
design_gs, nsim = 1e4, dist = Normal(), theta = .0, seed = 59)
expect_equal(
res$expectedNumberOfSubjectsH1/2,
evaluate(ExpectedSampleSize(dist, alternative), design_gs, optimization = TRUE),
tolerance = .1, scale = 1)
expect_equal(
res$expectedNumberOfSubjectsH1/2,
evaluate(ExpectedSampleSize(dist, alternative),
design_gs, specific = FALSE, optimization = TRUE),
tolerance = .1, scale = 1)
expect_equal(
res$expectedNumberOfSubjectsH1/2,
evaluate(expected(ConditionalSampleSize(), dist, null), design_gs, optimization = TRUE),
tolerance = .1, scale = 1)
expect_equal(
res$expectedNumberOfSubjectsH0/2,
evaluate(expected(ConditionalSampleSize(), dist, null),
design_gs, specific = FALSE, optimization = TRUE),
tolerance = .1, scale = 1)
})
test_that("Power is computed correctly for example design", {
pow <- Power(Normal(), PointMassPrior(.4, 1))
expect_equal(
evaluate(pow, design_gs),
.8,
tolerance = 1e-2, scale = 1)
expect_equal(
evaluate(pow, design_gs, specific = FALSE),
.8,
tolerance = 1e-2, scale = 1)
expect_equal(
mean(sim_alt[, "reject"]),
.8,
tolerance = 1e-2, scale = 1)
})
test_that("Type one error is computed correctly for example design", {
toer <- Power(Normal(), PointMassPrior(.0, 1))
expect_equal(
evaluate(toer, design_gs),
.05,
tolerance = 1e-3, scale = 1)
expect_equal(
evaluate(toer, design_gs, specific = FALSE),
.05,
tolerance = 1e-3, scale = 1)
expect_equal(
mean(sim_null[, "reject"]),
.05,
tolerance = 1e-3, scale = 1)
})
|
cv.npmr <-
function(X, Y, lambda = exp(seq(7, -2)), s = 0.1/max(X), eps = 1e-6,
group = NULL, accelerated = TRUE, B.init = NULL, b.init = NULL,
foldid = NULL, nfolds = 10) {
if (is.null(dim(Y))) {
colnames = sort(unique(Y))
Y = model.matrix(~ as.factor(Y) - 1)
colnames(Y) = colnames
}
if (is.null(foldid)) foldid = sample(rep(1:nfolds, length = nrow(X)))
nfolds = length(unique(foldid))
if (nrow(X) != nrow(Y)) {
stop('X and Y do not have matching numbers of observations')
} else if (nrow(X) != length(foldid)) {
stop('X and foldid do not have matching numbers of observations')
}
error = matrix(NA, nfolds, length(lambda))
for (fold in unique(foldid)) {
fit = npmr(X[foldid != fold, ], Y[foldid != fold, ], lambda,
s = s, eps = eps, group = group, accelerated = accelerated,
B.init = B.init, b.init = b.init)
for (l in 1:length(lambda)) {
error[sort(unique(foldid)) == fold, l] =
sum(-log(rowSums(predict(fit, X[foldid == fold, ])[, , l]*
Y[foldid == fold, ])))
}
}
lambda.min = lambda[which.min(colSums(error))]
if (lambda.min == min(lambda)) {
warning('lambda chosen through CV is smallest lambda')
} else if (lambda.min == max(lambda)) {
warning('lambda chosen through CV is largest lambda')
}
fit = list(call = match.call(), error = colSums(error),
fit = npmr(X, Y, lambda.min, s = s, eps = eps, group = group,
accelerated = accelerated, B.init = B.init, b.init = b.init),
lambda.min = lambda.min, lambda = lambda, n = nrow(X))
class(fit) = "cv.npmr"
return(fit)
}
|
Tarone.test <- function(N, M) {
if(!(all(N == as.integer(N)))) { stop("Error: Number of trials should be integers"); }
if(min(N) < 1) { stop("Error: Number of trials should be positive"); }
if(!(all(M == as.integer(M)))) { stop("Error: Count values should be integers"); }
if(min(M) < 0) { stop("Error: Count values cannot be negative"); }
if(any(M > N)) { stop("Error: Observed count value exceeds number of trials"); }
method <- "Tarone's Z test";
data.name <- paste0(deparse(substitute(M)), " successes from ",
deparse(substitute(N)), " trials");
null.value <- 0;
attr(null.value, "names") <- "dispersion parameter";
alternative <- "greater";
estimate <- sum(M)/sum(N);
attr(estimate, "names") <- "proportion parameter";
S <- ifelse(estimate == 1, sum(N),
sum((M - N*estimate)^2/(estimate*(1 - estimate))));
statistic <- (S - sum(N))/sqrt(2*sum(N*(N-1)));
attr(statistic, "names") <- "z";
p.value <- 2*pnorm(-abs(statistic), 0, 1);
attr(p.value, "names") <- NULL;
TEST <- list(method = method, data.name = data.name,
null.value = null.value, alternative = alternative,
estimate = estimate, statistic = statistic, p.value = p.value);
class(TEST) <- "htest";
TEST;
}
|
NULL
latin_square <- function(n, randomise = TRUE) {
out <- matrix(nrow = n, ncol = n)
out[1,] <- if(randomise) sample(1:n) else 1:n
for(i in 2:n) {
out[i,] <- lag_vector(out[i - 1, ])
}
if(randomise) {
out <- out[, sample(1:n)]
out <- out[sample(1:n), ]
}
out
}
latin_rectangle <- function(nr, nc, nt, randomise = TRUE) {
r1 <- ceiling(nr/nt)
r2 <- ceiling(nc/nt)
out <- do.call("rbind", lapply(1:r1, function(i) {
do.call("cbind",
lapply(1:r2, function(j) {
latin_square(nt, randomise = randomise)
}
))
}))
out <- out[1:nr, 1:nc]
res1 <- apply(out, 1, function(x) table(factor(x, 1:nt)))
res2 <- apply(out, 2, function(x) table(factor(x, 1:nt)))
diff1 <- apply(res1, 2, function(x) max(x) - min(x))
diff2 <- apply(res2, 2, function(x) max(x) - min(x))
if(randomise && (any(diff1 > 1) | any(diff2 > 1))) return(latin_rectangle(nr, nc, nt, randomise))
out
}
latin_array <- function(dim, nt, randomise = TRUE) {
ndim <- length(dim)
if(ndim == 2) return(latin_rectangle(dim[1], dim[2], nt, randomise))
r <- ceiling(dim[ndim]/nt)
dim_ext <- c(dim[-ndim], r * nt)
out <- array(dim = dim_ext)
out <- assign_array(out, 1, 1, latin_array(dim_ext[-1], nt, randomise))
for(i in 2:dim[1]) {
out <- assign_array(out, 1, i, lag_array(index_array(out, 1, i - 1), 1))
}
if(randomise) {
for(i in seq_along(dim[-ndim])) {
out <- sample_array(out, i)
}
}
out
}
lag_vector <- function(x) {
x[c(2:length(x), 1L)]
}
lag_array <- function(array, i) {
da <- dim(array)
index <- lapply(seq(length(da)), function(x) bquote())
index[[i]] <- c(2:da[i], 1L)
do.call("[", c(list(array), index))
}
assign_array <- function(array, m, i, value) {
da <- dim(array)
index <- lapply(seq(length(da)), function(x) ifelse(x %in% m, i, bquote()))
do.call("[<-", c(list(array), index, list(value)))
}
sample_array <- function(array, i) {
da <- dim(array)
index <- lapply(seq(length(da)), function(x) if(x==i) sample(1:da[i]) else bquote())
do.call("[", c(list(array), index))
}
index_array <- function(array, m, i) {
da <- dim(array)
index <- lapply(seq(length(da)), function(x) if(x %in% m) i else bquote())
do.call("[", c(list(array), index))
}
|
test_that("exb_to_df", {
file_name <- system.file("extdata", "test.exb", package = "phonfieldwork")
df1 <- exb_to_df(file_name)
expect_true(nrow(df1) == 8)
})
|
initialize.icm <- function(param, init, control) {
dat <- list()
dat$param <- param
dat$init <- init
dat$control <- control
dat$attr <- list()
numeric.init <- init[which(sapply(init, class) == "numeric")]
n <- do.call("sum", numeric.init)
dat$attr$active <- rep(1, n)
if (dat$param$groups == 1) {
dat$attr$group <- rep(1, n)
} else {
g2inits <- grep(".g2", names(numeric.init))
g1inits <- setdiff(1:length(numeric.init), g2inits)
nG1 <- sum(sapply(g1inits, function(x) init[[x]]))
nG2 <- sum(sapply(g2inits, function(x) init[[x]]))
dat$attr$group <- c(rep(1, nG1), rep(2, max(0, nG2)))
}
dat <- init_status.icm(dat)
dat <- do.call(control[["prevalence.FUN"]], list(dat, at = 1))
return(dat)
}
init_status.icm <- function(dat) {
type <- dat$control$type
group <- dat$attr$group
nGroups <- dat$param$groups
nG1 <- sum(group == 1)
nG2 <- sum(group == 2)
i.num <- dat$init$i.num
r.num <- dat$init$r.num
i.num.g2 <- dat$init$i.num.g2
r.num.g2 <- dat$init$r.num.g2
status <- rep("s", nG1 + nG2)
status[sample(which(group == 1), size = i.num)] <- "i"
if (nGroups == 2) {
status[sample(which(group == 2), size = i.num.g2)] <- "i"
}
if (type == "SIR") {
status[sample(which(group == 1 & status == "s"), size = r.num)] <- "r"
if (nGroups == 2) {
status[sample(which(group == 2 & status == "s"), size = r.num.g2)] <- "r"
}
}
dat$attr$status <- status
idsInf <- which(status == "i")
infTime <- rep(NA, length(status))
if (dat$param$vital == TRUE && dat$param$di.rate > 0) {
infTime[idsInf] <- -rgeom(n = length(idsInf), prob = dat$param$di.rate) + 2
} else {
if (dat$control$type == "SI" || dat$param$rec.rate == 0) {
infTime[idsInf] <- ssample(1:(-dat$control$nsteps + 2),
length(idsInf), replace = TRUE)
} else {
if (nGroups == 1) {
infTime[idsInf] <- ssample(1:(-round(1 / dat$param$rec.rate) + 2),
length(idsInf), replace = TRUE)
}
if (nGroups == 2) {
infG1 <- which(status == "i" & group == 1)
infTime[infG1] <- ssample(1:(-round(1 / dat$param$rec.rate) + 2),
length(infG1), replace = TRUE)
infG2 <- which(status == "i" & group == 2)
infTime[infG2] <- ssample(1:(-round(1 / dat$param$rec.rate.g2) + 2),
length(infG2), replace = TRUE)
}
}
}
dat$attr$infTime <- infTime
return(dat)
}
|
lognormal_error_checks <- function(effect_vals, hist_control_data, rand_control_diff, censor_value, alpha) {
hist_chk <- class(hist_control_data)
rcp_chk <- is.null(rand_control_diff)
for (eff_val in effect_vals) {
if (!is.numeric(eff_val))
stop("historic_sim() requires effect_vals to be numeric.")
if (eff_val <= 0)
stop("For Lognormal, historic_sim() requires effect_vals to represent Mean Ratios which must be positive numbers")
}
if (hist_chk == "data.frame") {
colnamevals <- colnames(hist_control_data)
colnamechk <- (colnamevals == c("id", "treatment", "event_time", "status"))
if (sum(colnamechk) != 4) {
stop("historic_sim() requires hist_control_data to have columns: id, treatment, event_time, and status.")
}
if (sum(colnamechk) == 4) {
if (!is.numeric(hist_control_data$event_time)) {
stop("historic_sim() requires hist_control_data$event_time to be positive numeric data.")
}
if (is.numeric(hist_control_data$event_time)) {
if (min(hist_control_data$event_time) <= 0) {
stop("historic_sim() requires hist_control_data$event_time to be positive numeric data.")
}
}
if (!is.numeric(hist_control_data$treatment)) {
stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.")
}
if (is.numeric(hist_control_data$treatment)) {
trt_levels <- names(table(hist_control_data$treatment))
if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) {
stop("historic_sim() requires hist_control_data$treatment to be numeric 0/1 data.")
}
}
if (!is.numeric(hist_control_data$status)) {
stop("historic_sim() requires hist_control_data$status to be numeric 0/1 data.")
}
if (is.numeric(hist_control_data$status)) {
trt_levels <- names(table(hist_control_data$status))
if (length(trt_levels) > 2 | (trt_levels[1] != "0" & trt_levels[2] != "1")) {
stop("historic_sim() requires hist_control_data$status to be numeric 0/1 data.")
}
}
}
}
if (rcp_chk == FALSE) {
for (rand_cp in rand_control_diff) {
if (!is.numeric(rand_cp))
stop("historic_sim() requires rand_control_diff to be numeric.")
if (rand_cp <= 0)
stop("historic_sim() requires rand_control_diff to be Mean Ratios, so they must be positive.")
}
}
if (!is.null(censor_value) == TRUE) {
if (!is.numeric(censor_value))
stop("historic_sim() requires censor_value to be numeric.")
if (censor_value <= 0)
stop("historic_sim() requires censor_value to be positive.")
}
if (!is.null(alpha) == TRUE) {
if (!is.numeric(alpha))
stop("historic_sim() requires alpha to be numeric.")
if (alpha <= 0 | alpha >= 1)
stop("historic_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.")
}
}
lognormal_error_checks_simple <- function(effect_vals, control_parms, censor_value, alpha) {
chk_parm_lgth <- length(control_parms)
for (eff_val in effect_vals) {
if (!is.numeric(eff_val))
stop("simple_sim() requires effect_vals to be numeric.")
if (eff_val <= 0)
stop("For Lognormal, simple_sim() requires effect_vals to represent Mean Ratios which must be positive numbers")
}
if (chk_parm_lgth != 2) {
stop("simple_sim() requires two elements in control_parms, first=Lognormal mu parameter for rlnorm(), second= Lognormal sd parameter for rlnorm()")
}
if (chk_parm_lgth == 2) {
if (!is.numeric(control_parms[1]))
stop("simple_sim() requires Lognormal mu parameter for controls to be numeric.")
if (!is.numeric(control_parms[2]))
stop("simple_sim() requires Lognormal sd parameter for controls to be numeric.")
if (control_parms[2] <= 0)
stop("simple_sim() requires Lognormal sd parameter for controls to be positive.")
}
if (!is.null(censor_value) == TRUE) {
if (!is.numeric(censor_value))
stop("simple_sim() requires censor_value to be numeric.")
if (censor_value <= 0)
stop("simple_sim() requires censor_value to be positive.")
}
if (!is.null(alpha) == TRUE) {
if (!is.numeric(alpha))
stop("simple_sim() requires alpha to be numeric.")
if (alpha <= 0 | alpha >= 1)
stop("simple_sim() requires alpha to be between 0 and 1 but not equal to 0 or 1.")
}
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(textrecipes)
library(tokenizers)
abc <- c("The Bank is a place where you put your money;",
"The Bee is an insect that gathers honey.")
tokenize_words(abc)
tokenize_ngrams(abc, n = 2)
tokenize_ngrams(abc, n = 3)
tokenize_ngrams(abc, n = 1)
tokenize_ngrams(abc, n = 3, ngram_delim = "_")
abc_tibble <- tibble(text = abc)
rec <- recipe(~ text, data = abc_tibble) %>%
step_tokenize(text, token = "ngrams") %>%
step_tokenfilter(text) %>%
step_tf(text)
abc_ngram <- rec %>%
prep() %>%
juice()
abc_ngram
names(abc_ngram)
abc_tibble <- tibble(text = abc)
rec <- recipe(~ text, data = abc_tibble) %>%
step_tokenize(text, token = "ngrams", options = list(n = 2,
ngram_delim = "_")) %>%
step_tokenfilter(text) %>%
step_tf(text)
abc_ngram <- rec %>%
prep() %>%
juice()
abc_ngram
names(abc_ngram)
abc_tibble <- tibble(text = abc)
bigram <- function(x) {
tokenizers::tokenize_ngrams(x, lowercase = FALSE, n = 2, ngram_delim = ".")
}
rec <- recipe(~ text, data = abc_tibble) %>%
step_tokenize(text, custom_token = bigram) %>%
step_tokenfilter(text) %>%
step_tf(text)
abc_ngram <- rec %>%
prep() %>%
juice()
abc_ngram
names(abc_ngram)
abc_tibble <- tibble(text = abc)
rec <- recipe(~ text, data = abc_tibble) %>%
step_tokenize(text) %>%
step_ngram(text, num_tokens = 3) %>%
step_tokenfilter(text) %>%
step_tf(text)
abc_ngram <- rec %>%
prep() %>%
juice()
abc_ngram
names(abc_ngram)
abc_tibble <- tibble(text = abc)
rec <- recipe(~ text, data = abc_tibble) %>%
step_tokenize(text) %>%
step_stem(text) %>%
step_ngram(text, num_tokens = 3) %>%
step_tokenfilter(text) %>%
step_tf(text)
abc_ngram <- rec %>%
prep() %>%
juice()
abc_ngram
names(abc_ngram)
|
contextmenuDependency <- function() {
list(
htmltools::htmlDependency(
"lfx-contextmenu", version = "1.0.0",
src = system.file("htmlwidgets/lfx-contextmenu", package = "leaflet.extras2"),
script = c("leaflet.contextmenu.js",
"leaflet.contextmenu-bindings.js"),
stylesheet = "leaflet.contextmenu.css"
)
)
}
addContextmenu <- function(map) {
map$dependencies <- c(map$dependencies, contextmenuDependency())
leaflet::invokeMethod(map, NULL, "addContextmenu")
}
showContextmenu <- function(map, lat=NULL, lng=NULL, data=leaflet::getMapData(map)) {
pts <- leaflet::derivePoints(data, lng, lat, missing(lng), missing(lat), "showContextmenu")
leaflet::invokeMethod(map, NULL, "showContextmenu", pts)
}
hideContextmenu <- function(map) {
leaflet::invokeMethod(map, NULL, "hideContextmenu")
}
addItemContextmenu <- function(map, option) {
if (utils::packageVersion("leaflet") < "2.0.4") {
warning("The `addItemContextmenu` function requires leaflet `2.0.4` to correctly register callbacks.")
}
leaflet::invokeMethod(map, NULL, "addItemContextmenu", option)
}
insertItemContextmenu <- function(map, option, index) {
if (utils::packageVersion("leaflet") < "2.0.4") {
warning("The `insertItemContextmenu` function requires leaflet `2.0.4` to correctly register callbacks.")
}
leaflet::invokeMethod(map, NULL, "insertItemContextmenu", option, index)
}
removeItemContextmenu <- function(map, index) {
leaflet::invokeMethod(map, NULL, "removeItemContextmenu", index)
}
setDisabledContextmenu <- function(map, index, disabled=TRUE) {
leaflet::invokeMethod(map, NULL, "setDisabledContextmenu", index, disabled)
}
removeallItemsContextmenu <- function(map) {
leaflet::invokeMethod(map, NULL, "removeallItemsContextmenu")
}
menuItem <- function(text, callback=NULL, ...) {
list(text=text,
callback=leaflet::JS(callback),
...)
}
mapmenuItems <- function(...) {
list(...)
}
markermenuItems <- function(...) {
list(list(...))
}
|
NULL
fit_hrg <- function(graph, hrg=NULL, start=FALSE, steps=0) {
if (!is_igraph(graph)) { stop("Not a graph object") }
if (is.null(hrg)) {
hrg <- list(left=c(), right=c(), prob=c(), edges=c(),
vertices=c())
}
hrg <- lapply(hrg[c("left","right","prob","edges","vertices")],
as.numeric)
start <- as.logical(start)
steps <- as.integer(steps)
on.exit( .Call(C_R_igraph_finalizer) )
res <- .Call(C_R_igraph_hrg_fit, graph, hrg, start, steps)
if (igraph_opt("add.vertex.names") && is_named(graph)) {
res$names <- V(graph)$name
}
class(res) <- "igraphHRG"
res
}
consensus_tree <- consensus_tree
hrg <- hrg
hrg_tree <- hrg_tree
sample_hrg <- sample_hrg
predict_edges <- function(graph, hrg=NULL, start=FALSE, num.samples=10000,
num.bins=25) {
if (!is_igraph(graph)) { stop("Not a graph object") }
if (is.null(hrg)) {
hrg <- list(left=c(), right=c(), prob=c(), edges=c(),
vertices=c())
}
hrg <- lapply(hrg[c("left","right","prob","edges","vertices")],
as.numeric)
start <- as.logical(start)
num.samples <- as.integer(num.samples)
num.bins <- as.integer(num.bins)
on.exit( .Call(C_R_igraph_finalizer) )
res <- .Call(C_R_igraph_hrg_predict, graph, hrg, start, num.samples,
num.bins)
res$edges <- matrix(res$edges, ncol=2, byrow=TRUE)
class(res$hrg) <- "igraphHRG"
res
}
as.igraph <- function(x, ...)
UseMethod("as.igraph")
as.igraph.igraphHRG <- function(x, ...) {
ovc <- length(x$left)+1L
ivc <- ovc-1L
ll <- ifelse(x$left < 0, -x$left + ovc, x$left + 1)
rr <- ifelse(x$right < 0, -x$right + ovc, x$right + 1)
edges <- c(rbind(seq_len(ivc)+ovc, ll), rbind(seq_len(ivc)+ovc, rr))
res <- graph(edges)
V(res)$name <- c(if (!is.null(x$names)) x$names else as.character(1:ovc),
paste0("g", 1:ivc))
V(res)$prob <- c(rep(NA, ovc), x$prob)
res$name <- "Fitted HRG"
res
}
buildMerges <- function(object) {
S <- numeric()
vcount <- length(object$left)+1
nMerge <- vcount-1
merges <- matrix(0, nrow=vcount-1, ncol=3)
mptr <- 1
S[length(S)+1] <- -1
prev <- NULL
while (length(S) != 0) {
curr <- S[length(S)]
if (is.null(prev) ||
(prev < 0 && object$left[-prev] == curr) ||
(prev < 0 && object$right[-prev] == curr)) {
if (curr < 0) { S <- c(S, object$left[-curr]) }
} else if (curr < 0 && object$left[-curr] == prev) {
S <- c(S, object$right[-curr])
} else {
if (curr < 0) {
merges[mptr,] <- c(object$left[-curr], object$right[-curr], curr)
mptr <- mptr + 1
}
S <- S[-length(S)]
}
prev <- curr
}
merges
}
as.dendrogram.igraphHRG <- function(object, hang=0.01, ...) {
nMerge <- length(object$left)
merges <- buildMerges(object)
.memberDend <- function(x) {
r <- attr(x,"x.member")
if(is.null(r)) {
r <- attr(x,"members")
if(is.null(r)) r <- 1:1
}
r
}
oHgt <- 1:nrow(merges)
hMax <- oHgt[length(oHgt)]
mynames <- if (is.null(object$names)) 1:(nMerge+1) else object$names
z <- list()
for (k in 1:nMerge) {
x <- merges[k,1:2]
if (any(neg <- x >= 0)) {
h0 <- if (hang < 0) 0 else max(0, oHgt[k] - hang * hMax)
}
if (all(neg)) {
zk <- as.list(x+1)
attr(zk, "members") <- 2L
attr(zk, "midpoint") <- 1/2
objlabels <- mynames[x+1]
attr(zk[[1]], "label") <- objlabels[1]
attr(zk[[2]], "label") <- objlabels[2]
attr(zk[[1]], "members") <- attr(zk[[2]], "members") <- 1L
attr(zk[[1]], "height") <- attr(zk[[2]], "height") <- h0
attr(zk[[1]], "leaf") <- attr(zk[[2]], "leaf") <- TRUE
} else if (any(neg)) {
X <- paste0("g", -x)
isL <- x[1] >= 0
zk <- if (isL) list(x[1]+1, z[[X[2]]]) else list(z[[X[1]]], x[2]+1)
attr(zk, "members") <- attr(z[[X[1+isL]]], "members") + 1L
attr(zk, "midpoint") <-
(.memberDend(zk[[1]]) + attr(z[[X[1+isL]]], "midpoint"))/2
attr(zk[[2 - isL]], "members") <- 1L
attr(zk[[2 - isL]], "height") <- h0
attr(zk[[2 - isL]], "label") <- mynames[x[2 - isL]+1]
attr(zk[[2 - isL]], "leaf") <- TRUE
} else {
X <- paste0("g", -x)
zk <- list(z[[X[1]]], z[[X[2]]])
attr(zk, "members") <- attr(z[[X[1]]], "members") +
attr(z[[X[2]]], "members")
attr(zk, "midpoint") <- (attr(z[[X[1]]], "members") +
attr(z[[X[1]]], "midpoint") +
attr(z[[X[2]]], "midpoint"))/2
}
attr(zk, "height") <- oHgt[k]
z[[k <- paste0("g", -merges[k,3])]] <- zk
}
z <- z[[k]]
class(z) <- "dendrogram"
z
}
as.hclust.igraphHRG <- function(x, ...) {
merge3 <- buildMerges(x)
map <- order(-merge3[,3])
merge <- merge3[,1:2]
gs <- which(merge < 0)
merge[ gs] <- map[ -merge[gs] ]
merge[-gs] <- -merge[-gs]-1
map2 <- numeric(nrow(merge))
mergeInto <- merge
for (i in 1:nrow(merge)) {
mr <- mergeInto[i,]
mr[mr > 0] <- -map2[mr[mr>0]]
mergeInto[i,] <- -mr
map2[i] <- -mr[1]
}
n <- nrow(merge)+1
hcass <- .C("igraphhcass2", n=as.integer(n),
ia=as.integer(mergeInto[,1]),
ib=as.integer(mergeInto[,2]),
order=integer(n), iia=integer(n), iib=integer(n))
mynames <- if (is.null(x$names)) 1:n else x$names
res <- list(merge=merge, height=1:nrow(merge), order=hcass$order,
labels=mynames, method=NA_character_,
dist.method=NA_character_)
class(res) <- "hclust"
res
}
as_phylo.igraphHRG <- function(x, ...) {
ovc <- length(x$left)+1L
ivc <- ovc-1L
ll <- ifelse(x$left < 0, -x$left + ovc, x$left + 1)
rr <- ifelse(x$right < 0, -x$right + ovc, x$right + 1)
edge <- matrix(rbind(seq_len(ivc)+ovc, ll, seq_len(ivc)+ovc, rr),
ncol=2, byrow=TRUE)
edge.length <- rep(0.5, nrow(edge))
labels <- if (is.null(x$names)) 1:ovc else x$names
obj <- list(edge=edge, edge.length=edge.length/2, tip.label=labels,
Nnode=ivc)
class(obj) <- "phylo"
reorder(obj)
}
plot_dendrogram.igraphHRG <- function(x, mode=igraph_opt("dend.plot.type"), ...) {
if (mode=="auto") {
have_ape <- requireNamespace("ape", quietly = TRUE)
mode <- if (have_ape) "phylo" else "hclust"
}
if (mode=="hclust") {
hrgPlotHclust(x, ...)
} else if (mode=="dendrogram") {
hrgPlotDendrogram(x, ...)
} else if (mode=="phylo") {
hrgPlotPhylo(x, ...)
}
}
hrgPlotHclust <- function(x, rect=0, colbar=rainbow(rect), hang=.01,
ann=FALSE, main="", sub="", xlab="", ylab="",
...) {
hc <- as.hclust(x)
ret <- plot(hc, hang=hang, ann=ann, main=main, sub=sub, xlab=xlab,
ylab=ylab, ...)
if (rect > 0) {
rect.hclust(hc, k=rect, border=colbar)
}
invisible(ret)
}
hrgPlotDendrogram <- function(x, ...) {
plot(as.dendrogram(x), ...)
}
hrgPlotPhylo <- function(x, colbar=rainbow(11, start=.7, end=.1),
edge.color=NULL, use.edge.length=FALSE, ...) {
vc <- length(x$left)+1
phy <- as_phylo(x)
br <- seq(0,1,length=length(colbar)) ; br[1] <- -1
cc <- as.integer(cut(x$prob[phy$edge[,1] - vc], breaks=br))
if (is.null(edge.color)) { edge.color <- colbar[cc] }
plot(phy, edge.color=edge.color, use.edge.length=use.edge.length, ...)
}
print.igraphHRG <- function(x, type=c("auto", "tree", "plain"),
level=3, ...) {
type <- igraph.match.arg(type)
if (type=="auto") {
type <- if (length(x$left <= 100)) "tree" else "plain"
}
if (type=="tree") {
return(print1.igraphHRG(x, level=level, ...))
} else {
return(print2.igraphHRG(x, ...))
}
}
print1.igraphHRG <- function(x, level=3, ...) {
cat(sep="", "Hierarchical random graph, at level ", level, ":\n")
.depth <- function(b, l) {
l[2] <- max(l[2], nchar(format(x$prob[b], digits=2)))
if (l[1]==level) { return(l) }
if (x$left[b] < 0 && x$right[b] < 0) {
l1 <- .depth(-x$left[b], c(l[1]+1, l[2]))
l2 <- .depth(-x$right[b], c(l[1]+1, l[2]))
return(pmax(l1,l2))
}
if (x$left[b] < 0) { return(.depth(-x$left[b], c(l[1]+1, l[2]))) }
if (x$right[b] < 0) { return(.depth(-x$right[b], c(l[1]+1, l[2]))) }
return(l)
}
cs <- .depth(1, c(1, 0))
pw <- cs[2]
cs <- cs[1] * 3
vw <- nchar(as.character(length(x$left)+1))
sp <- paste(collapse="", rep(" ", cs+pw+2+2))
nn <- if (is.null(x$names)) seq_len(length(x$left)+1) else x$names
.children <- function(b) {
res <- c()
if (x$left[b] < 0) {
res <- c(res, .children(-x$left[b]))
} else {
res <- c(x$left[b]+1, res)
}
if (x$right[b] < 0) {
res <- c(res, .children(-x$right[b]))
} else {
res <- c(x$right[b]+1, res)
}
return(res)
}
.plot <- function(b, l, ind = "") {
if (b != 1) {
he <- format(paste(sep="", ind, "'- g", b), width=cs)
ind <- paste(" ", ind)
} else {
he <- format(paste(sep="", ind, "g", b), width=cs)
}
gol <- x$left[b] < 0 && l < level
gor <- x$right[b] < 0 && l < level
ch1 <- character()
if (!gol && x$left[b] < 0) {
ch1 <- c(ch1, paste(sep="", "g", -x$left[b]))
}
if (!gor && x$right[b] < 0) {
ch1 <- c(ch1, paste(sep="", "g", -x$right[b]))
}
ch2 <- numeric()
if (!gol) {
if (x$left[b] < 0) { ch2 <- c(ch2, .children(-x$left[b])) }
if (x$left[b] >= 0) { ch2 <- c(ch2, x$left[b] + 1) }
}
if (!gor) {
if (x$right[b] < 0) { ch2 <- c(ch2, .children(-x$right[b])) }
if (x$right[b] >= 0) { ch2 <- c(ch2, x$right[b] + 1) }
}
ch2 <- as.character(nn[ch2])
lf <- gsub(" ", "x", format(ch2, width=vw), fixed=TRUE)
lf <- paste(collapse=" ", lf)
lf <- strwrap(lf, width=getOption("width") - cs - pw - 3 - 2)
lf <- gsub("x", " ", lf, fixed=TRUE)
if (length(lf) > 1) {
lf <- c(lf[1], paste(sp, lf[-1]))
lf <- paste(collapse="\n", lf)
}
op <- paste(sep="", format(he, width=cs),
" p=", format(x$prob[b], digits=2, width=pw, justify="left"),
" ", paste(collapse=" ", lf))
cat(op, fill=TRUE)
if (x$left[b] < 0 && l < level) .plot(-x$left[b], l+1, ind)
if (x$right[b] < 0 && l < level) .plot(-x$right[b], l+1, ind)
}
if (length(x$left) > 0) .plot(b=1, l=1)
invisible(x)
}
print2.igraphHRG <- function(x, ...) {
cat("Hierarchical random graph:\n")
bw <- ceiling(log10(length(x$left)+1))+1
p <- format(x$prob, digits=1)
pw <- 4 + max(nchar(p))
nn <- if (is.null(x$names)) seq_len(length(x$left)+1) else x$names
op <- sapply(seq_along(x$left), function(i) {
lc <- if (x$left[i] < 0) {
paste(sep="", "g", -x$left[i])
} else {
nn[x$left[i]+1]
}
rc <- if (x$right[i] < 0) {
paste(sep="", "g", -x$right[i])
} else {
nn[x$right[i]+1]
}
paste(sep="", format(paste(sep="", "g", i), width=bw),
format(paste(sep="", " p=", p[i]), width=pw),
"-> ", lc, " ", rc)
})
op <- format(op, justify="left")
cat(op, sep=" ", fill=TRUE)
invisible(x)
}
print.igraphHRGConsensus <- function(x, ...) {
cat("HRG consensus tree:\n")
n <- length(x$parents) - length(x$weights)
mn <- if (is.null(x$names)) seq_len(n) else x$names
id <- c(mn, paste(sep="", "g", seq_along(x$weights)))
ch <- tapply(id, x$parents, c)[-1]
bw <- nchar(as.character(length(x$weights)))
vw <- max(nchar(id))
op <- sapply(seq_along(x$weights), function(i) {
mych <- format(ch[[i]], width=vw)
if (length(ch[[i]])*(vw+1) + bw + 4 > getOption("width")) {
mych <- gsub(" ", "x", mych, fixed=TRUE)
mych <- paste(collapse=" ", mych)
pref <- paste(collapse="", rep(" ", bw+5))
mych <- strwrap(mych, width=getOption("width") - bw - 4,
initial="", prefix=pref)
mych <- gsub("x", " ", mych, fixed=TRUE)
mych <- paste(collapse="\n", mych)
} else {
mych <- paste(collapse=" ", mych)
}
paste(sep="", "g", format(i, width=bw), " -> ", mych)
})
if (max(nchar(op)) < (getOption("width")-4)/2) {
op <- format(op, justify="left")
cat(op, sep=" ", fill=TRUE)
} else {
cat(op, sep="\n")
}
invisible(x)
}
"
B-1 p=0
'- B-3 p=1 6
'- B-7 p=1 2
'- B-5 p=1 1 5
'- B-6 p=1 7
'- B-2 p=1 4
'- B-4 p=1 3 8
B-1 p=0 B-3 B-6 6 2 1 5 7 4 3 8
B-1 p=0
'+ B-3 p=1 B-7 6 2 1 5
'+ B-6 p=1 B-2 7 4 3 8
B-1 p=0
'- B-3 p=1 6
'+ B-7 p=1 B-5 2 1 5
'- B-6 p=1 7
'+ B-2 p=1 B-4 4 3 8
B-1 p=0 B-3 B-6
B-2 p=1 B-4 4
B-3 p=1 B-7 6
B-4 p=1 3 8
B-5 p=1 1 5
B-6 p=1 B-2 7
B-7 p=1 B-5 2
"
|
source("ESEUR_config.r")
library(igraph)
library(jsonlite)
library(plyr)
plot_wide()
get_transition=function(df)
{
t=ldply(df$neighbours, function(n) data.frame(stateName=n["stateName"], button=n["button"]))
res=data.frame(from=df$stateName, to=t$stateName, button=t$button)
return(res)
}
alaris=fromJSON(paste0(ESEUR_dir, "probability/Patrick_Oladimeji-alaris.json"))
t_fsm=adply(alaris$"device spec", 1, get_transition)
fsm=data.frame(from=t_fsm$from, to=t_fsm$to, button=t_fsm$button)
fsm_graph=graph.data.frame(fsm, directed=TRUE)
V(fsm_graph)$frame.color=NA
V(fsm_graph)$color="yellow"
V(fsm_graph)$size=3
V(fsm_graph)$label.cex=0.9
E(fsm_graph)$color="red"
E(fsm_graph)$arrow.size=0.2
par(cex=0.9)
plot(fsm_graph, edge.width=0.3, edge.curved=TRUE)
|
TPES_purity <- function(ID,
SEGfile,
SNVsReadCountsFile,
ploidy,
RMB = 0.47,
maxAF = 0.55,
minCov = 10,
minAltReads = 5,
minSNVs = 10)
{
colnames(SEGfile) <- c('ID','chrom','loc.start','loc.end','num.mark','seg.mean')
if(ID %in% SEGfile$ID){
SEGfile <- SEGfile[which(SEGfile$ID == ID),]
} else {stop(paste0(ID, ' is not in the SEGfile\n'))}
if(ID %in% SNVsReadCountsFile$sample){
SNVsReadCountsFile <- SNVsReadCountsFile[which(SNVsReadCountsFile$sample == ID),]
} else {stop(paste0(ID, ' is not in the SNVsReadCountsFile\n'))}
if(ID %in% ploidy$sample){
ploidy <- ploidy[which(ploidy$sample == ID),]$ploidy
} else {stop(paste0(ID, ' is not in the ploidy file\n'))}
log2shift <- round(-log2(ploidy/2),3)
SEGfile$log2.plCorr <- SEGfile$seg.mean - log2shift
purityTable <- data.frame(row.names = ID, stringsAsFactors = F)
purityTable$sample <- ID
purityTable$purity <- NA
purityTable$purity.min <- NA
purityTable$purity.max <- NA
purityTable$n.segs <- NA
purityTable$n.SNVs <- NA
purityTable$RMB <- NA
purityTable$BandWidth <- NA
purityTable$log <- NA
SEGfile <- SEGfile[which(gsub('chr', '', SEGfile$chr) %in% seq(1,22,1)), ]
SEGfile <- SEGfile[which(SEGfile$log2.plCorr >= -0.1 &
SEGfile$log2.plCorr <= 0.1), ]
if (nrow(SEGfile) == 0){
purityTable$log <- 'no available segments'
warning(paste0(ID, ' no CN neutral segments are available'), call. = F)
return(purityTable)}
SNVsReadCountsFile$cov <- SNVsReadCountsFile$ref.count + SNVsReadCountsFile$alt.count
SNVsReadCountsFile$AF <- SNVsReadCountsFile$alt.count / SNVsReadCountsFile$cov
SNVsReadCountsFile <- SNVsReadCountsFile[which(SNVsReadCountsFile$cov >= minCov &
SNVsReadCountsFile$alt.count >= minAltReads), ]
SNVsReadCountsFile <- SNVsReadCountsFile[which(gsub('chr', '', SNVsReadCountsFile$chr) %in% seq(1,22,1)), ]
if (nrow(SNVsReadCountsFile) == 0){
purityTable$n.SNVs <- 0
purityTable$log <- 'no SNVs available'
warning(paste0(ID, ': no SNVs available\n'), call. = F)
return(purityTable)}
SNVsReadCountsFile <- do.call(rbind,lapply(seq(1,nrow(SNVsReadCountsFile),1), function(j){
segPos <- getSegmentsPos(SNVsReadCountsFile$chr[j],
SNVsReadCountsFile$start[j],
SNVsReadCountsFile$end[j],
SEGfile[,c('chrom', 'loc.start', 'loc.end')])
if (length(segPos) == 1){
return(SNVsReadCountsFile[j,,drop=F])}}))
if (is.null(SNVsReadCountsFile)){
purityTable$n.SNVs <- 0
purityTable$log <- 'no SNVs available in CN neutral segments'
warning(paste0(ID, ': no SNVs available in CN neutral segments\n'), call. = F)
return(purityTable)}
SNVsReadCountsFile <- SNVsReadCountsFile[which(SNVsReadCountsFile$AF <= maxAF),]
if (nrow(SNVsReadCountsFile) == 0){
purityTable$n.SNVs <- 0
purityTable$log <- paste0('no SNVs available with maxAF = ', maxAF)
warning(paste0(ID, ': no SNVs available with maxAF = ', maxAF, '\n'), call. = F)
return(purityTable)}
bwRange <- seq(0.010, 0.080, 0.001)
nModes <- sapply(bwRange, function(bw){
return(nr.modes(stats::density(SNVsReadCountsFile$AF, bw=bw, na.rm=T)$y))})
if (length(which(nModes == 2)) >= 2 ){
bwOptim <- bwRange[min(which(nModes == 2))]
}else if (1 %in% nModes){
bwOptim <- bwRange[min(which(nModes == 1))]
}else{
purityTable$log <- 'no suitable bandwidth'
warning(paste0(ID, ': no suitable bandwidth was found\n'), call. = F)
return(purityTable)}
if (length(SNVsReadCountsFile$AF) > minSNVs){
purityTable$n.SNVs <- length(SNVsReadCountsFile$AF)
} else {
purityTable$log <- 'no SNVs available'
warning(paste0(ID, ': no SNVs available; required ', minSNVs, "\n"), call. = F)
return(purityTable)}
Peaks <- findPeaks(AF = SNVsReadCountsFile$AF, bw = bwOptim)
if (nrow(Peaks) == 0){
purityTable$log <- 'no peaks found'
warning(paste0(ID, ': no peaks found'), call. = F)
return(purityTable)
} else {
clonalPeak <- unlist(Peaks[nrow(Peaks),])[1]
}
if (clonalPeak < RMB){
min <- findMin(AF = SNVsReadCountsFile$AF, bw = bwOptim)
} else {
SNVsReadCountsFile <- SNVsReadCountsFile[which(SNVsReadCountsFile$AF <= RMB),]
if (nrow(SNVsReadCountsFile) == 0){
purityTable$n.SNVs <- 0
purityTable$log <- 'no SNVs available below RMB value'
warning(paste0(ID, ': no SNVs available below RMB value\n'), call. = F)
return(purityTable)}
nModes <- sapply(bwRange, function(bw){
return(nr.modes(stats::density(SNVsReadCountsFile$AF, bw = bw, na.rm = T)$y))})
if (length(which(nModes == 2)) >= 2){
bwOptim <- bwRange[min(which(nModes == 2))]
} else if (1 %in% nModes){
bwOptim <- bwRange[min(which(nModes == 1))]
} else{
purityTable$log <- 'no suitable bandwidth'
warning(paste0(ID, 'no suitable bandwidth\n'), call. = F)
return(purityTable)}
if (length(SNVsReadCountsFile$AF) > minSNVs){
purityTable$n.SNVs <- length(SNVsReadCountsFile$AF)
} else {
purityTable$log <- 'no SNVs available'
warning(paste0(ID, ': no SNVs available; required ', minSNVs, '\n'), call. = F)
return(purityTable)}
Peaks <- findPeaks(AF = SNVsReadCountsFile$AF, bw = bwOptim)
if (nrow(Peaks) == 0){
warning(paste0(ID, ' no peaks found'), call. = F)
return(purityTable)
} else {
clonalPeak <- unlist(Peaks[nrow(Peaks),])[1]
}
if (clonalPeak < RMB){
min <- findMin(AF = SNVsReadCountsFile$AF, bw = bwOptim)
} else {
purityTable$purity <- 1
purityTable$purity.min <- 1
purityTable$purity.max <- 1
purityTable$n.segs <- nrow(SEGfile)
purityTable$n.SNVs <- nrow(SNVsReadCountsFile)
purityTable$RMB <- RMB
purityTable$BandWidth <- bwOptim
purityTable$log <- 'computation ok'
return(purityTable)
}
}
if (length(colnames(min)) == 0){
clonalAF <- SNVsReadCountsFile$AF
} else{
clonalAF <- SNVsReadCountsFile$AF[which(SNVsReadCountsFile$AF > min[1,])]
if (length(clonalAF) < minSNVs){
purityTable$n.SNVs <- length(clonalAF)
purityTable$log <- 'no putative clonal SNVs available'
warning(paste0(ID, ': ', length(clonalAF), ' putative clonal SNVs available; required ',
minSNVs, '\n'), call. = F)
return(purityTable)
}
}
purityTable$purity <- round((clonalPeak/RMB),2)
purityTable$purity.min <- round(((stats::quantile(stats::ecdf(clonalAF))[2])/RMB),2)
purity.max <- round(((stats::quantile(stats::ecdf(clonalAF))[4])/RMB),2)
if(purity.max > 1){
purityTable$purity.max <- 1
} else {
purityTable$purity.max <- purity.max
}
purityTable$n.segs <- nrow(SEGfile)
purityTable$n.SNVs <- length(clonalAF)
purityTable$RMB <- RMB
purityTable$BandWidth <- bwOptim
purityTable$log <- 'computation ok'
return(purityTable)
}
|
create.dendrogram <- function(
x, clustering.method = 'diana', cluster.dimension = 'col', distance.method = 'correlation',
cor.method = 'pearson', force.clustering = FALSE, same.as.matrix = FALSE
) {
if (same.as.matrix) {
x <- t(apply(x, 2, rev));
}
if (length(cluster.dimension) > 1) { stop('Only handles one cluster dimension at a time.'); }
dd <- 0;
distance.matrix <- 0;
if (cluster.dimension %in% c('col', 'column', 'cols', 'columns')) {
if (dim(x)[2] > 6000 && !force.clustering) {
stop('Unclusterable matrix: dim(data.cluster)[2] = ', dim(x)[2]);
}
if ('correlation' == distance.method) {
distance.matrix <- as.dist(1 - cor(x, use = 'pairwise', method = cor.method));
}
else if (distance.method %in% c('euclidean', 'maximum', 'manhattan', 'canberra', 'binary', 'minkowski', 'jaccard')) {
distance.matrix <- dist(t(x), method = distance.method);
}
else {
stop('Unknown distance.method: ', distance.method);
}
}
else if (cluster.dimension %in% c('row', 'rows')) {
if (dim(x)[1] > 6000 && !force.clustering) {
stop('Unclusterable matrix: dim(data.cluster)[1] = ', dim(x)[1]);
}
if ('correlation' == distance.method) {
distance.matrix <- as.dist(1 - cor(t(x), use = 'pairwise', method = cor.method));
}
else if (distance.method %in% c('euclidean', 'maximum', 'manhattan', 'canberra', 'binary', 'minkowski', 'jaccard')) {
distance.matrix <- dist(x, method = distance.method);
}
else {
stop('Unknown distance.method: ', distance.method);
}
}
else {
stop('Unknown cluster.dimension for create.dendrogram: ', cluster.dimension);
}
if (any(is.na(distance.matrix))) {
stop('Unclusterable matrix: some distances are NULL or NA.');
}
if ('diana' == clustering.method) {
dd <- as.dendrogram(as.hclust(diana(x = distance.matrix)));
}
else if (clustering.method %in% c('ward', 'ward.D', 'ward.D2', 'single', 'complete', 'average', 'mcquitty', 'median', 'centroid')) {
dd <- as.dendrogram(hclust(d = distance.matrix, method = clustering.method));
}
else {
stop('Unknown clustering method: ', clustering.method);
}
return(dd);
}
|
simapply <- function(x, FUN, ...) {
L <- .sims.as.list(x)
Args <- .Primitive("c")(list(FUN=FUN, SIMPLIFY=FALSE, USE.NAMES=FALSE), list(L))
Args$MoreArgs <- list(...)
S <- do.call(mapply, Args)
r <- rvsims(S)
if (isTRUE(all.equal(dim(r), dim(x)))) {
dimnames(r) <- dimnames(x)
}
return(r)
}
|
plot.ivregDecision <-
function(x, xaxes = TRUE, yaxes = TRUE,
xaxes.label = TRUE, yaxes.label = TRUE, legend = TRUE, ...){
delta1 = as.numeric(colnames(x))
delta2 = as.numeric(rownames(x))
z1 = matrix(NA, nrow(x), ncol(x))
z1[x == '-'] = 0
z1[x == '+'] = 1
z1[x == '*'] = 2
z1[x == '**'] = 3
colslist = gray(c(30, 20, 15, 5)/32)
cols = colslist[1+as.numeric(names(table(z1)))]
image(delta1, delta2, t(z1), col = cols, xlab = '', ylab = '', axes = F, ...)
xaxs = pretty(delta1)
yaxs = pretty(delta2)
if(xaxes) axis(1, at = xaxs , labels = xaxs, ...)
if(yaxes) axis(2, at = yaxs , labels = yaxs, ...)
if(xaxes.label) mtext(expression(delta[1]), side=1, line=2.2, ...)
if(yaxes.label) mtext(expression(delta[2]), side=2, line=2.2, ...)
range = max(delta1) - min(delta1)
if(legend)
mtext(text = c("\u25A0", "no evidence", "\u25A0", "only OLS rejects",
"\u25A0", "one piece of evidence", "\u25A0", "two pieces of evidence"),
col = as.vector(rbind(colslist, gray(0))),
at = min(delta1) + range*(-.07 + cumsum(c(-.01, .1, .11, .12, .13, .165, .17, .165))),
line = 1, cex = c(1.5, .99)[rep(1:2, 4)] )
}
|
test_that("tx_pvls_den works", {
expect_identical(
tx_pvls_den(
ndr_example,
status = "default",
ref = lubridate::ymd("2021-03-31")
),
ndr_example %>%
subset(current_status_28_days == "Active" &
!patient_has_died %in% TRUE &
!patient_transferred_out %in% TRUE &
lubridate::as_date("2021-03-31") - art_start_date >=
lubridate::period(6, "months") &
dplyr::if_else(
current_age < 20,
lubridate::as_date("2021-03-31") -
date_of_current_viral_load <=
lubridate::period(6, "months"),
lubridate::as_date("2021-03-31") -
date_of_current_viral_load <=
lubridate::period(1, "year")
))
)
})
|
dicp <-
function(y, X, res, term = NULL) {
n <- length(y)
beta <- res$Beta
sigma2 <- res$Sigma2
niter <- length(sigma2)
if(is.null(term)) {
term <- inf_criteria(y, X, res)
}
logterm <- log(term)
logtermsum <- apply(logterm, 1, sum)
deviance <- -2*mean(logtermsum)
betahat <- apply(beta,2,mean)
sigma2hat <- mean(sigma2)
d <- -2*sum(dnorm(y, X%*%betahat, sqrt(sigma2hat), log = TRUE))
pd <- deviance - d
DIC <- deviance + pd
res <- list()
res$pD <- pd
res$DIC <- DIC
res
}
|
remove <- function(packages, remotes=c()) {
sandbox({
desc <- getDesc()
for (package in packages) {
if (!desc$has_dep(package)) {
stop(paste0("Cannot find package '", package, "' in DESCRIPTION file"))
}
desc$del_dep(package)
}
if (length(remotes) > 0) {
for (remote in remotes) {
desc$del_remotes(remote)
}
}
installHelper(desc=desc)
for (package in packages) {
success(paste0("Removed ", package, "!"))
}
})
}
|
list.order <- function(.data, ..., keep.names = FALSE, na.last = TRUE) {
result <- list.order.internal(.data, dots(...), parent.frame(), na.last = na.last)
if (keep.names) setnames(result, names(.data)) else result
}
list.sort <- function(.data, ..., na.last = NA) {
.data[list.order.internal(.data, dots(...), parent.frame(), na.last = na.last)]
}
|
context ("sp-osm")
test_that ("multipolygon", {
x_sf <- sf::st_read ("../osm-multi.osm",
layer = "multipolygons", quiet = TRUE)
x_sp <- as (x_sf, "Spatial")
q0 <- opq (bbox = c(1, 1, 5, 5))
x <- osmdata_sp (q0, "../osm-multi.osm")$osm_multipolygons
x <- x [, which (names (x) %in% names (x_sp))]
x_sp <- x_sp [, which (names (x_sp) %in% names (x))]
rownames (slot (x, "data")) <- rownames (slot (x_sp, "data"))
slot (x, "proj4string") <- slot (x_sp, "proj4string")
names (slot (x, "polygons")) <- NULL
names (slot (slot (x, "polygons")[[1]], "Polygons")) <- NULL
np <- length (slot (slot (x, "polygons")[[1]], "Polygons"))
for (i in seq (np)) {
rownames (slot (slot (slot (x, "polygons")[[1]],
"Polygons")[[i]], "coords")) <- NULL
colnames (slot (slot (slot (x, "polygons")[[1]],
"Polygons")[[i]], "coords")) <- NULL
dimnames (slot (slot (slot (x, "polygons")[[1]],
"Polygons")[[i]], "coords")) <- NULL
}
for (i in seq (np)) {
pi <- slot (slot (x, "polygons")[[1]], "Polygons") [[i]]
pi_sp <- slot (slot (x_sp, "polygons")[[1]],
"Polygons") [[i]]
xyi <- slot (pi, "coords")
xyi_sp <- slot (pi_sp, "coords")
expect_identical (attributes (xyi), attributes (xyi_sp))
}
})
test_that ("multilinestring", {
x_sf <- sf::st_read ("../osm-multi.osm",
layer = "multilinestrings", quiet = TRUE)
x_sp <- as (x_sf, "Spatial")
q0 <- opq (bbox = c(1, 1, 5, 5))
x <- osmdata_sp (q0, "../osm-multi.osm")$osm_multilines
x <- x [, which (names (x) %in% names (x_sp))]
x_sp <- x_sp [, which (names (x_sp) %in% names (x))]
rownames (slot (x, "data")) <- rownames (slot (x_sp, "data"))
slot (x, "proj4string") <- slot (x_sp, "proj4string")
names (slot (x, "lines")) <- NULL
names (slot (slot (x, "lines")[[1]], "Lines")) <- NULL
np <- length (slot (slot (x, "lines")[[1]], "Lines"))
for (i in seq (np)) {
rownames (slot (slot (slot (x, "lines")[[1]],
"Lines")[[i]], "coords")) <- NULL
colnames (slot (slot (slot (x, "lines")[[1]],
"Lines")[[i]], "coords")) <- NULL
dimnames (slot (slot (slot (x, "lines")[[1]],
"Lines")[[i]], "coords")) <- NULL
}
for (i in seq (np)) {
pi <- slot (slot (x, "lines")[[1]], "Lines") [[i]]
pi_sp <- slot (slot (x_sp, "lines")[[1]], "Lines") [[i]]
xyi <- slot (pi, "coords")
xyi_sp <- slot (pi_sp, "coords")
expect_identical (attributes (xyi), attributes (xyi_sp))
}
})
test_that ("ways", {
x_sf <- sf::st_read ("../osm-ways.osm",
layer = "lines", quiet = TRUE)
x_sp <- as (x_sf, "Spatial")
q0 <- opq (bbox = c(1, 1, 5, 5))
x <- osmdata_sp (q0, "../osm-ways.osm")$osm_lines
x <- x [, which (names (x) %in% names (x_sp))]
x_sp <- x_sp [, which (names (x_sp) %in% names (x))]
np <- length (slot (slot (x, "lines")[[1]], "Lines"))
for (i in seq (np)) {
rownames (slot (slot (slot (x, "lines")[[1]],
"Lines")[[i]], "coords")) <- NULL
colnames (slot (slot (slot (x, "lines")[[1]],
"Lines")[[i]], "coords")) <- NULL
dimnames (slot (slot (slot (x, "lines")[[1]],
"Lines")[[i]], "coords")) <- NULL
}
for (i in seq (np)) {
pi <- slot (slot (x, "lines")[[1]], "Lines") [[i]]
pi_sp <- slot (slot (x_sp, "lines")[[1]], "Lines") [[i]]
xyi <- slot (pi, "coords")
xyi_sp <- slot (pi_sp, "coords")
expect_identical (attributes (xyi), attributes (xyi_sp))
}
})
|
outline <- function(from,
md_list = FALSE,
md_eq = FALSE,
md_braces = FALSE,
md_bookdown = FALSE,
md_maxlevel = '') {
mdlength <- length(from)
yaml_loc <- grep('^[-+]{3,} *$', from)
if (length(yaml_loc) > 1) from <- from[-(yaml_loc[1]:yaml_loc[2])]
codeloc4backsticks <- grep('^````', from)
if (length(codeloc4backsticks) > 0){
from <- from[!sapply(1:mdlength, function(x) rmvcode(index = x, loc = codeloc4backsticks))]
}
codeloc3backsticks <- grep('^```', from)
if (length(codeloc3backsticks) > 0){
from <- from[!sapply(1:mdlength, function(x) rmvcode(index = x, loc = codeloc3backsticks))]
}
if (md_list){
from <- list2heading(from)
}
headingloc <- grep(paste0('^
if (!md_braces){
from[headingloc] <- gsub(pattern = '\\{.*\\}', '', from[headingloc])
}
from[headingloc] <- gsub(pattern = '[-
eq_loc <- NA
if (md_eq && any(grepl('^\\$\\$', from))) {
eq_begin <- grep('^\\$\\$', from)
eq_end <- grep('\\$\\$$', from)
eq_loc <- get_eqloc(eq_begin, eq_end)
}
heading <- from[headingloc]
if (md_bookdown) {
part_loc <- c(grep('^
grep('^
grep('^
)
if (length(part_loc) > 0) {
heading[part_loc] <- gsub(' \\(PART\\)', '', heading[part_loc])
heading[part_loc] <- gsub(' \\(APPENDIX\\)', '', heading[part_loc])
lower_loc <- (part_loc[1] + 1):length(heading)
lower_loc <- lower_loc[!lower_loc %in% part_loc]
heading[lower_loc] <- paste0('
}
}
if (!is.na(eq_loc[1])){
heading <- c(heading, from[eq_loc])[order(c(headingloc, eq_loc))]
}
return(heading)
}
md2mm <- function(from = NA,
root = 'mindr',
md_list = FALSE,
md_braces = FALSE,
md_bookdown = FALSE,
md_eq = FALSE,
md_maxlevel = '') {
md <- outline(from = from,
md_list = md_list,
md_eq = md_eq,
md_braces = md_braces,
md_bookdown = md_bookdown,
md_maxlevel = md_maxlevel)
mm <- mdtxt2mmtxt(from = md, root = root, md_eq = md_eq)
return(mm)
}
mm2md <- function(from = NA) {
mm <- gsub('/>', '</node>', from)
loc_link <- grep('LINK="([^\"]*)"', mm)
links <- gsub('LINK="([^\"]*)"', '\\1', regmatches(mm, gregexpr('LINK="[^\"]*"', mm)))
for (i in loc_link) mm[i] <- gsub('TEXT="([^"]*)"', paste0('TEXT=\"[\\1](', links[i], ')\"'), mm[i])
mm <- paste0(mm, collapse = '')
node_begin <- unlist(gregexpr('<node', mm))
node_end <- unlist(gregexpr('</node', mm))
node_sign <- c(rep(1, length(node_begin)), rep(-1, length(node_end)))
node_loc <- c(node_begin, node_end)
node_loc <- node_loc[-c(1, length(node_loc))]
node_sign <- node_sign[-c(1, length(node_sign))]
node_sign <- node_sign[order(node_loc)]
node_level <- cumsum(node_sign)[node_sign == 1]
headers <- gsub('TEXT="([^"]*)"', '\\1', regmatches(mm, gregexpr('TEXT="[^"]*"', mm))[[1]])
md <- paste(sapply(node_level, function(x) paste0(rep('
md <- c(paste('Title:', headers[1]), md)
md <- gsub('&', '&', md)
md <- gsub('"', '"', md)
return(md)
}
r2md <- function(from = NA) {
headerloc <- grep('^
from[headerloc] <- gsub(pattern = '[
from[headerloc] <- gsub('^
rfile_temp <- tempfile(pattern = "file", tmpdir = tempdir(), fileext = ".R")
writeLines(text = from, rfile_temp, useBytes = TRUE)
knitr::spin(hair = rfile_temp, knit = FALSE)
file.remove(rfile_temp)
md <- readLines(paste0(rfile_temp, 'md'), encoding = 'UTF-8')
return(md)
}
md2r <- function(from = NA, r_seclabel = ' --------', r_chunkheading = FALSE) {
rmdfile_temp <- tempfile(pattern = "file", tmpdir = tempdir(), fileext = ".Rmd")
writeLines(from, rmdfile_temp, useBytes = TRUE)
rfile_temp <- gsub('.Rmd$', '.R', rmdfile_temp)
knitr::purl(rmdfile_temp, output = rfile_temp, documentation = 2, quiet = TRUE)
rtext <- readLines(rfile_temp, encoding = 'UTF-8')
file.remove(c(rfile_temp, rmdfile_temp))
rtext <- gsub(pattern = "^
rtext <- gsub("^(
rtext <- gsub("^
rtext <- gsub(pattern = "^
rtext <- rtext[rtext != '']
rtext[rtext == "
return(rtext)
}
dir2md <- function(from = '.', dir_files = TRUE, dir_all = TRUE, dir_excluded = NA) {
tree <- if (dir_files) {
list.files(from, all.files = dir_all, recursive = TRUE, include.dirs = TRUE)
} else {
list.dirs(from, full.names = FALSE)[-1]
}
if (!is.na(dir_excluded[1])) tree <- tree[!grepl(paste(paste0('^', dir_excluded), collapse = '|'), tree)]
tree_node <- basename(tree)
tree_level <- sapply(tree, function(x) length(gregexpr('/', x)[[1]])) + 1
tree_level[!grepl('/', tree)] <- 1
tree_pre <- strrep('
md <- paste(tree_pre, tree_node)
return(md)
}
md2dir <- function(from = NA, dir_to = 'mindr', md_list = FALSE, md_bookdown = TRUE, dir_quiet = FALSE){
if (is.na(dir_to)) dir_to <- 'mindr'
if (dir.exists(dir_to)) return(warning(dir_to, ' already exists! Please use another folder name for "dir_to =" and try again.'))
md <- outline(from = from,
md_list = md_list,
md_eq = FALSE,
md_braces = FALSE,
md_bookdown = md_bookdown)
md <- gsub('\\[(.+)\\]\\(.+\\)', '\\1', md)
titles <- gsub('^
oldheadings <- gsub('^(
oldheadings[!grepl('^(
heading_level <- nchar(oldheadings)
level_change <- diff(heading_level)
n <- length(md)
dirs <- character(length = n)
dirs[1] <- titles[1]
for (i in 2:n) {
if (level_change[i - 1] == 0) dirs[i] <- file.path(dirname(dirs[i-1]), titles[i])
if (level_change[i - 1] == 1) dirs[i] <- file.path(dirs[i-1], titles[i])
if (level_change[i - 1] < 0) {
dirs[i] <- dirname(dirs[i-1])
for (j in 1:abs(level_change[i - 1])) dirs[i] <- dirname(dirs[i])
dirs[i] <- ifelse(dirs[i] == '.', titles[i], file.path(dirs[i], titles[i]))
}
}
dirs <- c(dir_to, file.path(dir_to, dirs))
for (i in dirs) {
dir.create(i)
if (!dir_quiet) message('Generated directory: ', i)
}
}
markmap <- function(from = '.', root = NA, input_type = c('auto', 'markdown', 'mindmap', 'R', 'dir'),
md_list = FALSE, md_eq = FALSE, md_braces = FALSE, md_bookdown = FALSE, md_maxlevel = '',
dir_files = TRUE, dir_all = TRUE, dir_excluded = NA,
widget_name = NA, widget_width = NULL, widget_height = NULL, widget_elementId = NULL, widget_options = markmapOption(preset = 'colorful')
) {
input_type <- match.arg(input_type, c('auto', 'markdown', 'mindmap', 'R', 'dir'))
if (input_type == 'auto') input_type <- guess_type(from)
if (input_type == 'mindmap') {
md <- mm2md(from = from)
} else{
if (input_type == 'markdown') md <- outline(from = from, md_list = md_list, md_eq = md_eq, md_braces = md_braces, md_bookdown = md_bookdown, md_maxlevel = md_maxlevel)
if (input_type == 'R') md <- outline(r2md(from = from), md_list = md_list, md_eq = md_eq, md_braces = md_braces, md_bookdown = md_bookdown, md_maxlevel = md_maxlevel)
if (input_type == 'dir') {
md <- outline(dir2md(from = from, dir_files = dir_files, dir_all = dir_all, dir_excluded = dir_excluded),
md_maxlevel = md_maxlevel)
if (is.na(root)) root <- basename(from)
}
}
md <- c(paste('
data <- paste(md, collapse = '\n')
x <- list(data = data, options = widget_options)
htmlwidgets::createWidget(
name = 'markmap',
x,
width = widget_width,
height = widget_height,
sizingPolicy = htmlwidgets::sizingPolicy(
defaultWidth = '100%',
defaultHeight = 400,
padding = 0,
browser.fill = TRUE
),
package = 'mindr',
elementId = widget_elementId
)
}
markmapOption <- function(preset = NULL,
nodeHeight = 20,
nodeWidth = 180,
spacingVertical = 10,
spacingHorizontal = 120,
duration = 750,
layout = 'tree',
color = 'gray',
linkShape = 'diagonal',
renderer = 'boxed',
...) {
if (!is.null(preset) &&
(preset == 'default' | preset == 'colorful')) {
filterNULL(list(preset = preset, autoFit = TRUE))
} else{
if (is.null(layout) || (layout != 'tree')) {
warning('Currenly, only tree layout is supported. Changing to tree layout...')
layout = 'tree'
}
filterNULL(
list(
nodeHeight = nodeHeight,
nodeWidth = nodeWidth,
spacingVertical = spacingVertical,
spacingHorizontal = spacingHorizontal,
duration = duration,
layout = 'tree',
color = color,
linkShape = linkShape,
renderer = renderer,
autoFit = TRUE,
...
)
)
}
}
|
simulate.hhh4 <- function (object,
nsim=1,
seed=NULL,
y.start=NULL,
subset=1:nrow(object$stsObj),
coefs=coef(object),
components=c("ar","ne","end"),
simplify=nsim>1,
...)
{
if(!exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE))
runif(1)
if(is.null(seed))
RNGstate <- get(".Random.seed", envir = .GlobalEnv)
else {
R.seed <- get(".Random.seed", envir = .GlobalEnv)
set.seed(seed)
RNGstate <- structure(seed, kind = as.list(RNGkind()))
on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv))
}
cl <- match.call()
theta <- if (missing(coefs)) coefs else checkCoefs(object, coefs)
stopifnot(subset >= 1, subset <= nrow(object$stsObj))
lag.ar <- object$control$ar$lag
lag.ne <- object$control$ne$lag
maxlag <- max(lag.ar, lag.ne)
nUnits <- object$nUnit
if (is.null(y.start)) {
y.means <- ceiling(colMeans(observed(object$stsObj)[subset,,drop=FALSE]))
y.start <- matrix(y.means, maxlag, nUnits, byrow=TRUE)
} else {
if (is.vector(y.start)) y.start <- t(y.start)
if (ncol(y.start) != nUnits)
stop(sQuote("y.start"), " must have nUnits=", nUnits, " columns")
if (nrow(y.start) < maxlag)
stop("need 'y.start' values for lag=", maxlag, " initial time points")
}
if (is.null(object$terms))
object$terms <- terms.hhh4(object)
exppreds <- get_exppreds_with_offsets(object, subset = subset, theta = theta)
model <- terms.hhh4(object)
psi <- splitParams(theta,model)$overdisp
if (length(psi) > 1)
psi <- psi[model$indexPsi]
neweights <- getNEweights(object, coefW(theta))
stopifnot(length(components) > 0, components %in% c("ar", "ne", "end"))
getComp <- function (comp) {
exppred <- exppreds[[comp]]
if (comp %in% components) exppred else "[<-"(exppred, value = 0)
}
ar <- getComp("ar")
ne <- getComp("ne")
end <- getComp("end")
simcall <- quote(
simHHH4(ar, ne, end, psi, neweights, y.start, lag.ar, lag.ne)
)
if (!simplify) {
res0 <- object$stsObj[subset,]
setObserved <- function (observed) {
res0@observed[] <- observed
res0
}
simcall <- call("setObserved", simcall)
}
res <- if (nsim==1) eval(simcall) else
replicate(nsim, eval(simcall),
simplify=if (simplify) "array" else FALSE)
if (simplify) {
dimnames(res)[1:2] <- list(subset, colnames(model$response))
attr(res, "initial") <- y.start
attr(res, "stsObserved") <- object$stsObj[subset,]
class(res) <- "hhh4sims"
}
attr(res, "call") <- cl
attr(res, "seed") <- RNGstate
res
}
simHHH4 <- function(ar,
ne,
end,
psi,
neW,
start,
lag.ar = 1,
lag.ne = lag.ar
)
{
nTime <- nrow(end)
nUnits <- ncol(end)
size <- if (length(psi) == 0 ||
isTRUE(all.equal(psi, 0, check.attributes=FALSE))) {
NULL
} else {
if (!length(psi) %in% c(1, nUnits))
stop("'length(psi)' must be ",
paste(unique(c(1, nUnits)), collapse = " or "),
" (number of units)")
1/psi
}
rdistr <- if (is.null(size)) {
rpois
} else {
function(n, mean) rnbinom(n, mu = mean, size = size)
}
if (all(ar + ne == 0)) {
if (!is.null(size))
size <- matrix(size, nTime, nUnits, byrow = TRUE)
return(matrix(rdistr(length(end), end), nTime, nUnits))
}
wSumNE <- if (is.null(neW) || all(neW == 0)) {
function (y, W) numeric(nUnits)
} else function (y, W) .colSums(W * y, nUnits, nUnits)
mu <- y <- matrix(0, nTime, nUnits)
y <- rbind(start, y)
nStart <- nrow(y) - nrow(mu)
timeDependentWeights <- length(dim(neW)) == 3
if (!timeDependentWeights) neWt <- neW
for(t in seq_len(nTime)){
if (timeDependentWeights) neWt <- neW[,,t]
mu[t,] <-
ar[t,] * y[nStart+t-lag.ar,] +
ne[t,] * wSumNE(y[nStart+t-lag.ne,], neWt) +
end[t,]
y[nStart+t,] <- rdistr(nUnits, mu[t,])
}
y[-seq_len(nStart),,drop=FALSE]
}
checkCoefs <- function (object, coefs, reparamPsi=TRUE)
{
theta <- coef(object, reparamPsi=reparamPsi)
if (length(coefs) != length(theta))
stop(sQuote("coefs"), " must be of length ", length(theta))
names(coefs) <- names(theta)
coefs
}
"[.hhh4sims" <- function (x, i, j, ..., drop = FALSE)
{
xx <- NextMethod("[", drop = drop)
if (nargs() == 2L)
return(xx)
attr(xx, "initial") <- attr(x, "initial")
attr(xx, "stsObserved") <- attr(x, "stsObserved")
subset_hhh4sims_attributes(xx, i, j)
}
subset_hhh4sims_attributes <- function (x, i, j)
{
if (!missing(i))
attr(x, "stsObserved") <- attr(x, "stsObserved")[i,]
if (!missing(j)) {
attr(x, "stsObserved") <- suppressMessages(attr(x, "stsObserved")[, j])
is.na(attr(x, "stsObserved")@neighbourhood) <- TRUE
attr(x, "initial") <- attr(x, "initial")[, j, drop = FALSE]
}
x
}
aggregate.hhh4sims <- function (x, units = TRUE, time = FALSE, ..., drop = FALSE)
{
ax <- attributes(x)
if (time) {
res <- colSums(x)
if (isTRUE(units)) {
res <- colSums(res)
} else if (!identical(FALSE, units)) {
stopifnot(length(units) == dim(x)[2])
res <- t(rowSumsBy.matrix(t(res), units))
}
} else {
if (isTRUE(units)) {
res <- apply(X = x, MARGIN = c(1L, 3L), FUN = sum)
if (!drop) {
dim(res) <- c(ax$dim[1L], 1L, ax$dim[3L])
dnres <- ax$dimnames
dnres[2L] <- list(NULL)
dimnames(res) <- dnres
attr(res, "initial") <- as.matrix(rowSums(ax$initial))
attr(res, "stsObserved") <- aggregate(ax$stsObserved, by = "unit")
class(res) <- "hhh4sims"
}
} else if (!identical(FALSE, units)) {
stopifnot(length(units) == dim(x)[2])
groupnames <- names(split.default(seq_along(units), units))
res <- apply(X = x, MARGIN = 3L, FUN = rowSumsBy.matrix, by = units)
dim(res) <- c(ax$dim[1L], length(groupnames), ax$dim[3L])
dnres <- ax$dimnames
dnres[2L] <- list(groupnames)
dimnames(res) <- dnres
if (!drop) {
attr(res, "initial") <- rowSumsBy.matrix(ax$initial, units)
attr(res, "stsObserved") <- rowSumsBy.sts(ax$stsObserved, units)
class(res) <- "hhh4sims"
}
} else {
return(x)
}
}
res
}
rowSumsBy.matrix <- function (x, by, na.rm = FALSE)
{
dn <- dim(x)
res <- vapply(X = split.default(x = seq_len(dn[2L]), f = by),
FUN = function (idxg)
.rowSums(x[, idxg, drop = FALSE],
dn[1L], length(idxg), na.rm = na.rm),
FUN.VALUE = numeric(dn[1L]), USE.NAMES = TRUE)
if (dn[1L] == 1L) t(res) else res
}
rowSumsBy.sts <- function (x, by, na.rm = FALSE)
{
.sts(epoch = x@epoch, freq = x@freq, start = x@start,
observed = rowSumsBy.matrix(x@observed, by, na.rm),
state = rowSumsBy.matrix(x@state, by, na.rm) > 0,
alarm = rowSumsBy.matrix(x@alarm, by, na.rm) > 0,
populationFrac = rowSumsBy.matrix(x@populationFrac, by, na.rm),
epochAsDate = x@epochAsDate, multinomialTS = x@multinomialTS)
}
|
test_BO <- function() {
suppressWarnings({
synthFrame <- function(n,censorD) {
stringReps = c(rep('a',100),rep('b',100),'c',rep('d',20))
d <- data.frame(xN1=runif(n),
xN2=runif(n),
xN3=0.0,
xL1=sample(c(TRUE,FALSE),size=n,replace=TRUE),
xL2=sample(c(TRUE,FALSE,NA),size=n,replace=TRUE),
xL3=FALSE,
xS1=sample(stringReps,size=n,replace=TRUE),
xS2=sample(c(stringReps,NA),size=n,replace=TRUE),
xS3='a',
xF1=sample(as.factor(c(100:200)),size=n,replace=TRUE),
xF2=sample(as.factor(c('a','b','c','d',NA)),size=n,replace=TRUE),
xF3=as.factor(c('a')),
xI1=sample(as.integer(c(1,2,3)),size=n,replace=TRUE),
xI2=sample(as.integer(c(1,2,3,NA)),size=n,replace=TRUE),
xI3=as.integer(c(1)),
xU1=NA,
stringsAsFactors=FALSE)
now <- Sys.time()
d$t1 <- as.POSIXct(now+ceiling(as.numeric(now)*runif(n)/10))
d$t2 <- as.POSIXlt(now+ceiling(as.numeric(now)*runif(n)/10))
d[sample(1:n,5,replace=T),'xN2'] <- NA
d[sample(1:n,5,replace=T),'xN2'] <- NaN
d[sample(1:n,5,replace=T),'t1'] <- NA
d[sample(1:n,5,replace=T),'t2'] <- NA
if(censorD) {
dFree <- rowSums(as.matrix(sapply(d,function(c) {ifelse(is.na(c),0,ifelse(as.character(c)=='d',1.0,0.0))})))<=0
d <- d[dFree,]
n <- dim(d)[[1]]
}
toNum <- function(v) {
if(class(v)[[1]]=='character') {
v <- as.factor(v)
}
v <- as.numeric(v)
meanY <- mean(v,na.rm=TRUE)
if(is.na(meanY)) {
meanY <- 0.0
}
v[is.na(v)] <- meanY
v <- v - meanY
range <- max(1,max(v)-min(v))
v <- v/range
v
}
dN <- as.matrix(sapply(d,toNum))
d$yN <- rowSums(dN) + runif(n)
d$yC <- d$yN >= median(d$yN)
d
}
set.seed(26236)
dTrain <- synthFrame(200,TRUE)
dTest <- synthFrame(20,FALSE)
vars <- setdiff(colnames(dTrain),c('yN','yC'))
verbose=FALSE
for(smFactor in c(0.0,0.5)) {
for(scale in c(FALSE,TRUE)) {
if(verbose) {
print(paste('**********************',smFactor,scale))
print('
}
treatmentsN <- designTreatmentsN(dTrain,vars,'yN',smFactor=smFactor,
rareCount=2,rareSig=0.5,
verbose=verbose)
dTrainNTreated <- prepare(treatmentsN,dTrain,pruneSig=0.99,
scale=scale,
check_for_duplicate_frames=FALSE)
nvars <- setdiff(colnames(dTrainNTreated),'yN')
if(scale) {
expect_true(max(abs(vapply(dTrainNTreated[,nvars],mean,numeric(1))))<1.0e-5)
expect_true(max(abs(1-
vapply(nvars,
function(c) {
lm(paste('yN',c,sep='~'),
data=dTrainNTreated)$coefficients[[2]]},
numeric(1))))<1.0e-5)
}
modelN <- lm(paste('yN',paste(nvars,collapse=' + '),sep=' ~ '),
data=dTrainNTreated)
dTestNTreated <- prepare(treatmentsN,dTest,pruneSig=0.99,scale=scale,
check_for_duplicate_frames=FALSE)
dTestNTreated$pred <- predict(modelN,newdata=dTestNTreated)
if(verbose) {
print(summary(modelN))
}
if(verbose) {
print('
}
treatmentsC <- designTreatmentsC(dTrain,vars,'yC',TRUE,smFactor=smFactor,
catScaling=TRUE,
verbose=verbose)
dTrainCTreated <- prepare(treatmentsC,dTrain,pruneSig=0.99,scale=scale,
check_for_duplicate_frames=FALSE)
cvars <- setdiff(colnames(dTrainCTreated),'yC')
if(scale) {
expect_true(max(abs(vapply(dTrainCTreated[,cvars],mean,numeric(1))))<1.0e-5)
expect_true(max(abs(1-
vapply(cvars,
function(c) {
glm(paste('yC',c,sep='~'),family=binomial,
data=dTrainCTreated)$coefficients[[2]]},
numeric(1))))<1.0e-5)
}
modelC <- glm(paste('yC',paste(cvars,collapse=' + '),sep=' ~ '),
data=dTrainCTreated,family=binomial(link='logit'))
dTestCTreated <- prepare(treatmentsC,dTest,pruneSig=0.99,scale=scale,
check_for_duplicate_frames=FALSE)
dTestCTreated$pred <- predict(modelC,newdata=dTestCTreated,type='response')
if(verbose) {
print(summary(modelC))
}
}
}
})
invisible(NULL)
}
test_BO()
|
knitr::opts_chunk$set(collapse = TRUE, comment = "
library(openEBGM)
data(caers_raw)
head(caers_raw, 4)
dat <- tidyr::separate_rows(caers_raw, SYM_One.Row.Coded.Symptoms, sep = ", ")
dat[1:4, c("RA_Report..", "PRI_Reported.Brand.Product.Name",
"SYM_One.Row.Coded.Symptoms")]
dat$id <- dat$RA_Report..
dat$var1 <- dat$PRI_Reported.Brand.Product.Name
dat$var2 <- dat$SYM_One.Row.Coded.Symptoms
dat$strat_gender <- dat$CI_Gender
table(dat$strat_gender, useNA = "always")
dat$age_yrs <-
ifelse(dat$CI_Age.Unit == "Day(s)", dat$CI_Age.at.Adverse.Event / 365,
ifelse(dat$CI_Age.Unit == "Decade(s)", dat$CI_Age.at.Adverse.Event * 10,
ifelse(dat$CI_Age.Unit == "Month(s)", dat$CI_Age.at.Adverse.Event / 12,
ifelse(dat$CI_Age.Unit == "Week(s)", dat$CI_Age.at.Adverse.Event / 52,
ifelse(dat$CI_Age.Unit == "Year(s)", dat$CI_Age.at.Adverse.Event,
NA)))))
dat$strat_age <- ifelse(is.na(dat$age_yrs), "unknown",
ifelse(dat$age_yrs < 18, "under_18",
"18_plus"))
table(dat$strat_age, useNA = "always")
vars <- c("id", "var1", "var2", "strat_gender", "strat_age")
dat[1:5, vars]
|
.html_entities <- list(
symbol = c("&", "<", ">"),
name = c("&", "<", ">")
)
html_decode <- function(x) {
for (i in seq_along(.html_entities$symbol)) {
x <- gsub(.html_entities$name[i], .html_entities$symbol[i], x, fixed = TRUE)
}
x
}
html_encode <- function(x) {
for (i in seq_along(.html_entities$symbol)) {
x <- gsub(.html_entities$symbol[i], .html_entities$name[i], x, fixed = TRUE)
}
x
}
|
setMetabolicRate <- function(params, metab = NULL, p = NULL,
reset = FALSE, ...) {
assert_that(is(params, "MizerParams"),
is.flag(reset))
if (!is.null(p)) {
assert_that(is.numeric(p))
params <- set_species_param_default(params, "p", p)
}
species_params <- params@species_params
if (reset) {
if (!is.null(metab)) {
warning("Because you set `reset = TRUE`, the value you provided ",
"for `metab` will be ignored and a value will be ",
"calculated from the species parameters.")
metab <- NULL
}
comment(params@metab) <- NULL
}
if (!is.null(metab)) {
if (is.null(comment(metab))) {
if (is.null(comment(params@metab))) {
comment(metab) <- "set manually"
} else {
comment(metab) <- comment(params@metab)
}
}
assert_that(is.array(metab),
identical(dim(metab), dim(params@metab)))
if (!is.null(dimnames(metab)) &&
!all(dimnames(metab)[[1]] == species_params$species)) {
stop("You need to use the same ordering of species as in the ",
"params object: ", toString(species_params$species))
}
assert_that(all(metab >= 0))
params@metab[] <- metab
comment(params@metab) <- comment(metab)
params@time_modified <- lubridate::now()
return(params)
}
params <- set_species_param_default(params, "k", 0)
params@species_params$ks <- get_ks_default(params)
metab <-
sweep(outer(params@species_params$p, params@w,
function(x, y) y ^ x),
1, params@species_params$ks, "*") +
outer(params@species_params$k, params@w)
if (!is.null(comment(params@metab))) {
if (different(metab, params@metab)) {
message("The metabolic rate has been commented and therefore will ",
"not be recalculated from the species parameters.")
}
return(params)
}
params@metab[] <- metab
params@time_modified <- lubridate::now()
return(params)
}
getMetabolicRate <- function(params) {
params@metab
}
metab <- function(params) {
params@metab
}
`metab<-` <- function(params, value) {
setMetabolicRate(params, metab = value)
}
|
context("check various minor things")
test_that("print as log", {
ft <- flextable(iris)
expect_output(print(ft, preview = "log"), "a flextable object")
expect_output(print(ft, preview = "log"), "header has 1 row")
expect_output(print(ft, preview = "log"), "body has 150 row")
})
|
knitr::opts_chunk$set(echo = TRUE)
library(dplyr)
library(matsbyname)
U <- matrix(1:4, ncol = 2, dimnames = list(c("p1", "p2"), c("i1", "i2"))) %>%
setrowtype("Products") %>% setcoltype("Industries")
U
difference_byname(0, U)
unaryapply_byname(`-`, U)
divide <- function(x, divisor){
x/divisor
}
m <- matrix(c(1:4), nrow = 2, ncol = 2, dimnames = list(c("r1", "r2"), c("c1", "c2"))) %>%
setrowtype("row") %>% setcoltype("col")
m
elementapply_byname(divide, a = m, row = 1, col = 1, .FUNdots = list(divisor = 2))
U <- matrix(1:4, ncol = 2, dimnames = list(c("p1", "p2"), c("i1", "i2"))) %>%
setrowtype("Products") %>% setcoltype("Industries")
U
Y <- matrix(1:4, ncol = 2, dimnames = list(c("p2", "p1"), c("i2", "i1"))) %>%
setrowtype("Products") %>% setcoltype("Industries")
Y
sum_byname(U, Y)
binaryapply_byname(`+`, U, Y)
cumapply_byname(sum_byname, list(1, 2, 3, 4))
cumapply_byname(hadamardproduct_byname, list(1, 2, 3, 4))
|
SpecAbunChao1 <-
function(data, k, conf){
data <- as.numeric(data)
f <- function(i, data){length(data[which(data == i)])}
basicAbun <- function(data, k){
x <- data[which(data != 0)]
n <- sum(x)
D <- length(x)
n_rare <- sum(x[which(x <= k)])
D_rare <- length(x[which(x <= k)])
if (n_rare != 0){
C_rare <- 1 - f(1, x)/n_rare
} else {
C_rare = 1
}
n_abun <- n - n_rare
D_abun <- length(x[which(x > k)])
j <- c(1:k)
a1 <- sum(sapply(j, function(j)j*(j - 1)*f(j, x)))
a2 <- sum(sapply(j, function(j)j*f(j, x)))
if (C_rare != 0){
gamma_rare_hat_square <- max(D_rare/C_rare*a1/a2/(a2 - 1) - 1, 0)
gamma_rare_1_square <- max(gamma_rare_hat_square*(1 + (1 - C_rare)/C_rare*a1/(a2 - 1)), 0)
}else{
gamma_rare_hat_square <- 0
gamma_rare_1_square <- 0
}
CV_rare <- sqrt(gamma_rare_hat_square)
CV1_rare <- sqrt(gamma_rare_1_square)
BASIC.DATA <- matrix(paste(c("n", "D", "k", "n_rare", "D_rare", "C_rare", "CV_rare", "CV1_rare", "n_abun", "D_abun"),
round(c(n, D, k, n_rare, D_rare, C_rare, CV_rare, CV1_rare, n_abun, D_abun), 1),
sep = "="), ncol = 1)
colnames(BASIC.DATA) <- c("Value")
rownames(BASIC.DATA) <- c("Number of observed individuals", "Number of observed species","Cut-off point",
"Number of observed in dividuals for rare species", "Number of observed species for rare species",
"Estimation of the sample converage for rare species",
"Estimation of CV for rare species in ACE", "Estimation of CV1 for rare species in ACE-1",
"Number of observed species for abundant species", "Number of observed species for abundant species")
return(list(BASIC.DATA, n, D, n_rare, D_rare, C_rare, CV_rare, CV1_rare, n_abun, D_abun))
}
z <- -qnorm((1 - conf)/2)
n <- basicAbun(data, k)[[2]]
D <- basicAbun(data, k)[[3]]
n_rare <- basicAbun(data, k)[[4]]
D_rare <- basicAbun(data, k)[[5]]
C_rare <- basicAbun(data, k)[[6]]
CV_rare <- basicAbun(data, k)[[7]]
CV1_rare <- basicAbun(data, k)[[8]]
n_abun <- basicAbun(data, k)[[9]]
D_abun <- basicAbun(data, k)[[10]]
x <- data[which(data != 0)]
if (f(1, x) > 0 & f(2, x) > 0){
S_Chao1 <- D + (n - 1)/n*f(1, x)^2/(2*f(2, x))
var_Chao1 <- f(2, x)*((n - 1)/n*(f(1, x)/f(2, x))^2/2 +
((n - 1)/n)^2*(f(1, x)/f(2, x))^3 + ((n - 1 )/n)^2*(f(1, x)/f(2, x))^4/4)
t <- S_Chao1 - D
K <- exp(z*sqrt(log(1 + var_Chao1/t^2)))
CI_Chao1 <- c(D + t/K, D + t*K)
} else if (f(1, x) > 1 & f(2, x) == 0){
S_Chao1 <- D + (n - 1)/n*f(1, x)*(f(1, x) - 1)/(2*(f(2, x) + 1))
var_Chao1 <- (n - 1)/n*f(1, x)*(f(1, x) - 1)/2 +
((n - 1)/n)^2*f(1, x)*(2*f(1, x) - 1)^2/4 - ((n - 1)/n)^2*f(1, x)^4/4/S_Chao1
t <- S_Chao1 - D
K <- exp(z*sqrt(log(1 + var_Chao1/t^2)))
CI_Chao1 <- c(D + t/K, D + t*K)
} else {
S_Chao1 <- D
i <- c(1:max(x))
i <- i[unique(x)]
var_obs <- sum(sapply(i, function(i)f(i, x)*(exp(-i) - exp(-2*i)))) -
(sum(sapply(i, function(i)i*exp(-i)*f(i, x))))^2/n
var_Chao1 <- var_obs
P <- sum(sapply(i, function(i)f(i, x)*exp(-i)/D))
CI_Chao1 <- c(max(D, D/(1 - P) - z*sqrt(var_obs)/(1 - P)), D/(1 - P) + z*sqrt(var_obs)/(1 - P))
}
table <- matrix(c(S_Chao1, sqrt(var_Chao1), CI_Chao1), ncol = 4)
colnames(table) <- c("Estimate", "Est_s.e.", paste(conf*100,"% Lower Bound"), paste(conf*100,"% Upper Bound"))
rownames(table) <- "Chao1 (Chao, 1984)"
return(table)
}
|
getObsRelationshipsDF <- function(ssn, pid, junk, ind, ob, ob_by_locID, bin) {
ob.j.r <- data.frame(ob_by_locID[ind, c("pid", "locID")], junk,
stringsAsFactors = FALSE)
ob.j.r$fc <- as.logical(ob.j.r$fc)
rownames(ob.j.r)<- ob.j.r$pid
ob.j.r$junc.rid <- bin$rid[match(ob.j.r$binaryID, bin$binaryID)]
reps <- as.numeric(ob_by_locID$locID)
ob.j <- ob.j.r[reps,]
rownames(ob.j) <- paste(rownames(ob), ".fc", sep = "")
ob.j$pid <- ob_by_locID$pid
ob.j$juncDist <- [email protected]$DistanceUpstream[match(ob.j$junc.rid, [email protected]$SegmentID)]
ob.j$upDist.j <- ssn@obspoints@SSNPoints[[1]]@network.point.coords$DistanceUpstream[
match(ob.j$pid, as.numeric(rownames(ssn@obspoints@SSNPoints[[1]]@network.point.coords)))]
ob.j
}
|
`rclust` <-
function(dist, clusters = 2, runs = 10, counter = FALSE) {
if (runs == 1) return(relational.clustering(dist, clusters))
else {
rc2return <- NULL
rc2 <- sum(dist)
for (i in 1:runs) {
npart <- relational.clustering(dist, clusters)
if (i%%10==0 && counter==TRUE) print(paste('Calculating run number ',i,sep=''))
if (length(npart) == 1) {
next(i)
}
nd <- as.matrix(dist)
n<-dim(nd)[1]
nd[upper.tri(nd, diag = TRUE)] <- 0
inout <- matrix(0,n,n)
inout <- outer(1:n, 1:n, function(i, j) npart[i]!=npart[j])
inout<-as.matrix(as.dist(inout))
sumin <- sum(nd[which(inout==1)])
sumn<-sum(1:(n-1))
np <- sumin/(sumn-sum(inout))
if (np < rc2) {
rc2return <- npart
rc2 <- np
}
}
}
return(rc2return)
}
|
test_that("Check Project Found", {
create_temp_compendium()
expect_equal(get_package_name(), "pkgtest")
})
|
find.subset <- function(subsets.matrix, subset) {
subset = as.vector(subset)
len = length(subset)
if(len == 0)
stop("Empty atrributes subset.")
if(dim(subsets.matrix)[2] != len)
stop("Incorrect dimensions.")
if(dim(subsets.matrix)[1] == 0)
return(as.integer(NULL))
cond = rep(TRUE, dim(subsets.matrix)[1])
for(i in 1:len)
cond = cond & (subsets.matrix[,i] == subset[i])
return(which(cond))
}
create.children <- function(parent, direction = c("forward", "backward", "both"), omit.func = NULL ) {
direction = match.arg(direction)
if(!is.null(omit.func)) {
omit.func = match.fun(omit.func)
}
cols = length(parent)
if(cols <= 0)
stop("Parent attribute set cannot be empty.")
m1 = NULL
m2 = NULL
if(direction == "forward" || direction == "both") {
rows = cols - sum(parent)
if(rows > 0) {
m1 = matrix(parent, ncol = cols, nrow = rows, byrow = TRUE)
current_row = 1
current_col = 1
repeat {
if(current_col > cols || current_row > rows)
break()
if(m1[current_row, current_col] == 0) {
m1[current_row, current_col] = 1
current_row = current_row + 1
}
current_col = current_col + 1
}
}
}
if(direction == "backward" || direction == "both") {
rows = sum(parent)
if(rows > 1) {
m2 = matrix(parent, ncol = cols, nrow = rows, byrow = TRUE)
current_row = 1
current_col = 1
repeat {
if(current_col > cols || current_row > rows)
break()
if(m2[current_row, current_col] == 1) {
m2[current_row, current_col] = 0
current_row = current_row + 1
}
current_col = current_col + 1
}
}
}
m = rbind(m1, m2)
if(is.null(m))
return(m)
if(!is.null(omit.func)) {
rows_to_omit = apply(m, 1, omit.func)
return(m[!rows_to_omit,, drop = FALSE])
} else {
return(m)
}
}
find.best <- function(results, subset = rep(TRUE, length(results))) {
best = list(
result = NULL,
idx = NULL
)
w = which(subset)
if(length(w) > 0) {
children_results = results[w]
max_idx = which.max(children_results)
best$result = children_results[max_idx]
best$idx = w[max_idx]
}
return(best)
}
|
ResScanOutput <- function(sites_clusters, pval_clusters, centres_clusters, radius_clusters, areas_clusters, system, sites_coord, data, method){
res <- list(sites_clusters = sites_clusters, pval_clusters = pval_clusters,
centres_clusters = centres_clusters, radius_clusters = radius_clusters,
areas_clusters = areas_clusters, system = system, sites_coord = sites_coord, data = data, method = method)
oldClass(res) <- "ResScanOutput"
return(res)
}
ResScanOutputUni <- function(sites_clusters, pval_clusters, centres_clusters, radius_clusters, areas_clusters, system, sites_coord, data, method){
res <- ResScanOutput(sites_clusters, pval_clusters, centres_clusters, radius_clusters, areas_clusters, system, sites_coord, data, method)
oldClass(res) <- append(oldClass(res), "ResScanOutputUni")
return(res)
}
ResScanOutputMulti <- function(sites_clusters, pval_clusters, centres_clusters, radius_clusters, areas_clusters, system, variable_names = NULL, sites_coord, data, method){
res <- ResScanOutput(sites_clusters, pval_clusters, centres_clusters, radius_clusters, areas_clusters, system, sites_coord, data, method)
if(is.null(variable_names)){
res["variable_names"] <- list(NULL)
}else{
res[["variable_names"]] <- variable_names
}
oldClass(res) <- append(oldClass(res), "ResScanOutputMulti")
return(res)
}
ResScanOutputUniFunct <- function(sites_clusters, pval_clusters, centres_clusters, radius_clusters, areas_clusters, system, times = NULL, sites_coord, data, method){
res <- ResScanOutput(sites_clusters, pval_clusters, centres_clusters, radius_clusters, areas_clusters, system, sites_coord, data, method)
if(is.null(times)){
res["times"] <- list(NULL)
}else{
res[["times"]] <- times
}
oldClass(res) <- append(oldClass(res), "ResScanOutputUniFunct")
return(res)
}
ResScanOutputMultiFunct <- function(sites_clusters, pval_clusters, centres_clusters, radius_clusters, areas_clusters, system, times = NULL, variable_names = NULL, sites_coord, data, method){
res <- ResScanOutput(sites_clusters, pval_clusters, centres_clusters, radius_clusters, areas_clusters, system, sites_coord, data, method)
if(is.null(times)){
res["times"] <- list(NULL)
}else{
res[["times"]] <- times
}
if(is.null(variable_names)){
res["variable_names"] <- list(NULL)
}else{
res[["variable_names"]] <- variable_names
}
oldClass(res) <- append(oldClass(res), "ResScanOutputMultiFunct")
return(res)
}
|
time_group("Kamada-Kawai layout")
time_that("KK layout is fast, connected", replications=10,
init = { library(igraph); set.seed(42) },
reinit = { g <- sample_pa(400) },
{ layout_with_kk(g, maxiter=500) })
time_that("KK layout is fast, unconnected", replications=10,
init = { library(igraph); set.seed(42) },
reinit = { g <- sample_gnm(400, 400) },
{ layout_with_kk(g, maxiter=500) })
time_that("KK layout is fast for large graphs", replications=10,
init = { library(igraph); set.seed(42) },
reinit = { g <- sample_pa(3000) },
{ layout_with_kk(g, maxiter=500) })
|
gemSecurityPricingExample <- function(...) sdm2(...)
|
loonGrob.l_ts <- function(target, name = NULL, gp = NULL, vp = NULL){
loonGrob.l_compound(target,
name = if (!is.null(name)) name else "time series decomposition",
gp = gp, vp = vp)
}
|
seqici <- function(seqdata, with.missing=FALSE, silent=TRUE) {
if (!inherits(seqdata,"stslist"))
stop("data is NOT a sequence object, see seqdef function to create one")
if(!silent) message(" [>] computing complexity index for ",nrow(seqdata)," sequences ...")
trans <- seqtransn(seqdata, with.missing=with.missing, norm=TRUE)
ient <- suppressMessages(
seqient(seqdata, with.missing=with.missing, norm=TRUE)
)
comp.index <- sqrt(trans * ient)
colnames(comp.index) <- "C"
return(comp.index)
}
|
funcc_show_bicluster_hscore <- function(fun_mat,res_input){
biclust_n <- NULL
col_palette = c(RColorBrewer::brewer.pal(9, 'Set1'),
RColorBrewer::brewer.pal(12, 'Set3'),
RColorBrewer::brewer.pal(8, 'Set2'),
RColorBrewer::brewer.pal(8, 'Accent'),
RColorBrewer::brewer.pal(8, 'Dark2'),
RColorBrewer::brewer.pal(9, 'PiYG'),
RColorBrewer::brewer.pal(9, 'PuOr'),
RColorBrewer::brewer.pal(9, 'RdBu'),
RColorBrewer::brewer.pal(9, 'PRGn'),
RColorBrewer::brewer.pal(9, 'Pastel1'),
RColorBrewer::brewer.pal(8, 'Pastel2'),
RColorBrewer::brewer.pal(9, 'BrBG'),
RColorBrewer::brewer.pal(11, 'Spectral'),
RColorBrewer::brewer.pal(8,'RdGy'),
RColorBrewer::brewer.pal(8,'RdBu'),
RColorBrewer::brewer.pal(8,'PRGn'),
RColorBrewer::brewer.pal(8,'PiYG'),
RColorBrewer::brewer.pal(8,'Oranges'),
RColorBrewer::brewer.pal(8,'Blues'),
RColorBrewer::brewer.pal(8,'RdGy'),
RColorBrewer::brewer.pal(8,'Greens'),
RColorBrewer::brewer.pal(6,'BuPu'),
RColorBrewer::brewer.pal(6,'BuGn'),
RColorBrewer::brewer.pal(9,'Paired'),
RColorBrewer::brewer.pal(9,'Paired'),
RColorBrewer::brewer.pal(9,'Paired'),
RColorBrewer::brewer.pal(9,'Paired'),
RColorBrewer::brewer.pal(9,'Paired'))
res <- res_input[[1]]
param <- res_input[[2]]
biclust <- data.frame(biclust_n=numeric(),h_score=numeric(),dim=numeric())
for(i in 1:res@Number){
logr <- res@RowxNumber[,i]
logc <- res@NumberxCol[i,]
fun_mat_prova <- array(fun_mat[logr,logc,],dim = c(sum(logr),sum(logc),dim(fun_mat)[3]))
dist_mat <- evaluate_mat_dist(fun_mat_prova,param$template.type, param$alpha, param$beta, param$const_alpha, param$const_beta, param$shift.alignement, param$shift.max, param$max.iter)
h_score <- ccscore_fun(dist_mat)
dim <- sum(res@RowxNumber[,i])*sum(res@NumberxCol[i,])
biclust_i <- data.frame(biclust_n=i,h_score=h_score,dim=dim)
biclust <- rbind(biclust,biclust_i)
}
grDevices::dev.new()
g <- ggplot2::ggplot(biclust,ggplot2::aes(x=dim,y=h_score,color=factor(biclust_n)))+
ggplot2::geom_point(size=3) + ggplot2::scale_color_manual(values=col_palette) +
ggplot2::xlab('Dimension') + ggplot2::ylab('H score') + ggplot2::labs(color='Bi-Cluster')
print(g)
}
|
expected <- eval(parse(text="81L"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(-Inf, -Inf, 0, 0, 1, 2, Inf, Inf, Inf, -Inf, -Inf, 0, 0.5, 1, 2, Inf, Inf, Inf, -Inf, -Inf, -Inf, 0, 1, 2, 2, Inf, Inf, -Inf, -Inf, -Inf, 0, 0.8, 1.6, Inf, Inf, Inf, -Inf, -Inf, -Inf, 0.5, 1.3, Inf, Inf, Inf, Inf, -Inf, -Inf, -Inf, 0.5, 1.4, Inf, Inf, Inf, Inf, -Inf, -Inf, -Inf, 0.5, 1.2, 1.9, Inf, Inf, Inf, -Inf, -Inf, -Inf, 0.499999999999999, 1.33333333333333, Inf, Inf, Inf, Inf, -Inf, -Inf, -Inf, 0.5, 1.325, Inf, Inf, Inf, Inf), .Dim = c(9L, 9L), .Dimnames = list(c(\"20%\", \"30%\", \"40%\", \"50%\", \"60%\", \"70%\", \"80%\", \"90%\", \"100%\"), NULL)))"));
do.call(`length`, argv);
}, o=expected);
|
context("parse: delay")
test_that("missing variables in delay", {
expect_error(odin_parse({
ylag <- delay(x, 10)
initial(y) <- 0.5
deriv(y) <- y + ylag
}), "Missing variable in delay expression", class = "odin_error")
expect_error(odin_parse({
ylag <- delay(x + y, 10)
initial(y) <- 0.5
deriv(y) <- y + ylag
}), "Missing variable in delay expression", class = "odin_error")
expect_error(odin_parse({
ylag <- delay(x + z, 10)
initial(y) <- 0.5
deriv(y) <- y + ylag
}), "Missing variables in delay expression", class = "odin_error")
})
test_that("delay call validation", {
expect_error(odin_parse_(quote(a <- 1 + delay(1))),
"delay() must be the only call on the rhs",
fixed = TRUE, class = "odin_error")
expect_error(odin_parse_(quote(a <- delay(1))),
"delay() requires two or three arguments",
fixed = TRUE, class = "odin_error")
expect_error(odin_parse_(quote(a <- delay(1, 2, 3, 4))),
"delay() requires two or three arguments",
fixed = TRUE, class = "odin_error")
expect_error(odin_parse_(quote(a <- delay(delay(1, 2), 2))),
"delay() may not be nested",
fixed = TRUE, class = "odin_error")
expect_error(odin_parse_(quote(a <- delay(2, delay(1, 2)))),
"delay() may not be nested",
fixed = TRUE, class = "odin_error")
expect_error(odin_parse_(quote(a <- delay(y + t, 2))),
"delay() may not refer to time",
fixed = TRUE, class = "odin_error")
})
test_that("delay check", {
expect_error(ir_parse_expr(quote(deriv(x) <- delay(y, 1)), NULL, NULL),
"delay() only valid for non-special variables",
fixed = TRUE, class = "odin_error")
expect_error(ir_parse_expr(quote(initial(x) <- delay(y, 1)), NULL, NULL),
"delay() only valid for non-special variables",
fixed = TRUE, class = "odin_error")
expect_error(ir_parse_expr(quote(dim(x) <- delay(y, 1)), NULL, NULL),
"delay() only valid for non-special variables",
fixed = TRUE, class = "odin_error")
})
test_that("more parse errors", {
expect_error(odin_parse({
x <- y + b
ylag <- delay(x, 10)
initial(y) <- 0.5
deriv(y) <- y + ylag
}), "Missing variable in delay expression: b (for delay ylag)",
fixed = TRUE, class = "odin_error")
})
test_that("prevent multiline delay", {
expect_error(
odin_parse({
deriv(a[]) <- i
initial(a[]) <- (i - 1) / 10
dim(a) <- 5
alt[] <- user()
dim(alt) <- length(a)
tmp[1] <- delay(a[1], 2, alt[1])
tmp[2:5] <- delay(a[i], 2, alt[i])
dim(tmp) <- length(a)
output(tmp[]) <- TRUE
}),
"delay() may only be used on a single-line array",
fixed = TRUE, class = "odin_error")
})
|
logD0Func=function(genoVec, alpha, beta)
{
n0=sum(genoVec==0, na.rm=TRUE)
n1=sum(genoVec==1, na.rm=TRUE)
n2=sum(genoVec==2, na.rm=TRUE)
alpha0=2*n2+n1+alpha
beta0=2*n0+n1+beta
tt1=lbeta(a=alpha0, b=beta0)
tt2=lbeta(a=alpha, b=beta)
logD0=n1*log(2)+tt1-tt2
res=list(logD0=logD0, alpha0=alpha0, beta0=beta0)
return(res)
}
QFunc=function(par, genoMat, wMat, piVec, memSubjs, bVec=rep(3,3))
{
alpha=par[1]
beta=par[2]
logpi=log(piVec)
const1=lgamma(sum(bVec, na.rm=TRUE))-lgamma(bVec[1])-lgamma(bVec[2])-
lgamma(bVec[3])
const2=sum((bVec-1)*logpi, na.rm=TRUE)
tt1=sum(wMat%*%logpi, na.rm=TRUE)
ttp=apply(genoMat, 1, function(x) {
ttres=logD.pFunc(x,memSubjs=memSubjs,
alpha=alpha, beta=beta)$logD.p})
tt0=apply(genoMat, 1, function(x) {
ttres=logD0Func(x,alpha=alpha, beta=beta)$logD0
return(ttres)})
ttn=apply(genoMat, 1, function(x) {
ttres=logD.nFunc(x, memSubjs=memSubjs,
alpha=alpha, beta=beta)$logD.n
return(ttres)})
tt2=sum(wMat[,1]*ttn, na.rm=TRUE)+
sum(wMat[,2]*tt0, na.rm=TRUE) +
sum(wMat[,3]*ttp, na.rm=TRUE)
myQ = tt1+tt2+const1+const2
return(myQ)
}
dQFunc=function(par, genoMat, wMat, piVec, memSubjs, bVec=rep(3,3))
{
alpha=par[1]
beta=par[2]
tt=apply(genoMat, 1, dlogD0Func, alpha=alpha, beta=beta)
res1=sum(tt[1,]*wMat[,2], na.rm=TRUE)
res2=sum(tt[2,]*wMat[,2], na.rm=TRUE)
res=c(res1, res2)
return(res)
}
dlogD0Func=function(genoVec, alpha, beta)
{
n0=sum(genoVec==0, na.rm=TRUE)
n1=sum(genoVec==1, na.rm=TRUE)
n2=sum(genoVec==2, na.rm=TRUE)
alpha0=2*n2+n1+alpha
beta0=2*n0+n1+beta
tt0=digamma(alpha0+beta0)
tt=digamma(alpha+beta)
d.alpha=digamma(alpha0)-tt0- digamma(alpha)+tt
d.beta=digamma(beta0)-tt0- digamma(beta)+tt
res=c(d.alpha, d.beta)
return(res)
}
logD.pFunc=function(genoVec, memSubjs, alpha, beta)
{
genoVec.ca=genoVec[which(memSubjs==1)]
genoVec.co=genoVec[which(memSubjs==0)]
res.x=logD0Func(genoVec.ca, alpha, beta)
lcx=res.x$logD0
alpha.x=res.x$alpha0
beta.x=res.x$beta0
res.y=logD0Func(genoVec.co, alpha, beta)
lcy=res.y$logD0
alpha.y=res.y$alpha0
beta.y=res.y$beta0
tmpFunc=function(vy, alpha.x, beta.x,
alpha.y, beta.y)
{
tt1=pbeta(vy, shape1=alpha.x, shape2=beta.x)
tt2=dbeta(x=vy, shape1=alpha.y, shape2=beta.y)
return(tt1*tt2)
}
res.int=integrate(f=tmpFunc, lower=0, upper=1,
alpha.x=alpha.x, beta.x=beta.x,
alpha.y=alpha.y, beta.y=beta.y)
prVxVy=1-res.int$value
if(prVxVy<0)
{
prVxVy = abs(prVxVy)
}
if(prVxVy<1.0e-300)
{
prVxVy=1.0e-300
}
logD.p=log(2)+lcx+lcy+log(prVxVy)
res=list(logD.p=logD.p,
alpha.x=alpha.x, beta.x=beta.x,
alpha.y=alpha.y, beta.y=beta.y)
return(res)
}
logD.nFunc=function(genoVec, memSubjs, alpha, beta)
{
genoVec.ca=genoVec[which(memSubjs==1)]
genoVec.co=genoVec[which(memSubjs==0)]
res.x=logD0Func(genoVec.ca, alpha, beta)
lcx=res.x$logD0
alpha.x=res.x$alpha0
beta.x=res.x$beta0
res.y=logD0Func(genoVec.co, alpha, beta)
lcy=res.y$logD0
alpha.y=res.y$alpha0
beta.y=res.y$beta0
tmpFunc=function(vy, alpha.x, beta.x,
alpha.y, beta.y)
{
tt1=pbeta(vy, shape1=alpha.x, shape2=beta.x)
tt2=dbeta(x=vy, shape1=alpha.y, shape2=beta.y)
return(tt1*tt2)
}
res.int=integrate(f=tmpFunc, lower=0, upper=1,
alpha.x=alpha.x, beta.x=beta.x,
alpha.y=alpha.y, beta.y=beta.y)
prVxVy=res.int$value
if(prVxVy<0)
{
prVxVy= abs(prVxVy)
}
if(prVxVy<1.0e-300)
{
prVxVy=1.0e-300
}
logD.n=log(2)+lcx+lcy+log(prVxVy)
res=list(logD.n=logD.n,
alpha.x=alpha.x, beta.x=beta.x,
alpha.y=alpha.y, beta.y=beta.y)
return(res)
}
estMemSNPs.default=function(genoMat, memSubjs,
alpha.p=2, beta.p=5, pi.p=0.1,
alpha0=2, beta0=5, pi0=0.8,
alpha.n=2, beta.n=5, pi.n=0.1,
method = "FDR",
fdr = 0.05,
verbose=FALSE)
{
nSNPs=nrow(genoMat)
wMat=matrix(NA, nrow=nSNPs, ncol=3)
colnames(wMat)=c("w-", "wEE", "w+")
memSNPs=rep(NA, nSNPs)
for(g in 1:nSNPs)
{
geno.g=genoMat[g,]
logD.p=logD.pFunc(genoVec=geno.g,
memSubjs=memSubjs,
alpha=alpha.p, beta=beta.p)$logD.p
logD0=logD0Func(genoVec=geno.g,
alpha=alpha0, beta=beta0)$logD0
logD.n=logD.nFunc(genoVec=geno.g,
memSubjs=memSubjs,
alpha=alpha.p, beta=beta.p)$logD.n
logVec=c(logD.n, logD0, logD.p)
max.log=max(logVec, na.rm=TRUE)
logdiff=logVec-max.log
diff=exp(logdiff)
piVec=c(pi.n, pi0, pi.p)
pidiff=piVec*diff
denom=sum(pidiff, na.rm=TRUE)
wMat[g,]=pidiff/denom
memSNPs[g]=which.max(wMat[g,])-2
}
if(method=="FDR")
{
memSNPs=callSNP(wmat=wMat, fdr=fdr)
}
memSNPs2=as.numeric(memSNPs != 0)
res=list(wMat=wMat, memSNPs=memSNPs,
memSNPs2=memSNPs2)
invisible(res)
}
estMemSNPs.oneSetHyperPara=function(
es,
var.memSubjs="memSubjs",
eps=1.0e-3,
MaxIter=50,
bVec=rep(3,3),
pvalAdjMethod="none",
method = "FDR",
fdr = 0.05,
verbose=FALSE)
{
pDat=pData(es)
memSubjs=pDat[, c(var.memSubjs)]
tt=table(memSubjs)
nm=names(tt)
tt=sort(nm)
if(!identical(tt, c("0","1")))
{
stop("memSubjs should be binary taking only values 0 or 1!")
}
fDat=fData(es)
pDat=pData(es)
genoMat=exprs(es)
fmla=as.formula(paste("~", var.memSubjs, sep=""))
design=model.matrix(fmla, data=pDat)
fit = lmFit(genoMat, design)
ebFit = eBayes(fit)
pval = ebFit$p.value[, 2]
p.adj = p.adjust(pval, method=pvalAdjMethod)
stats = ebFit$t[, 2]
nSNPs=length(stats)
memGenes.ini=rep("EE", nSNPs)
memGenes.ini[which(stats>0 & p.adj < 0.05)] = "+"
memGenes.ini[which(stats<0 & p.adj < 0.05)] = "-"
memGenes2=rep(1, nSNPs)
memGenes2[which(memGenes.ini == "EE")]=0
frame.unsorted=data.frame(stats=stats, pval=pval, p.adj=p.adj)
res.limma=list(ebFit=ebFit, frame.unsorted=frame.unsorted,
memGenes.ini=memGenes.ini, memGenes2=memGenes2)
nSNPs2=nrow(genoMat)
theta.hat=rep(NA, nSNPs2)
nTotal=ncol(genoMat)
for(g2 in 1:nSNPs2)
{
x=genoMat[g2,]
theta.hat[g2]=(2*sum(x==2, na.rm=TRUE)+sum(x==1, na.rm=TRUE))/(2*nTotal)
}
n.p=sum(memGenes.ini=="+", na.rm=TRUE)
n.n=sum(memGenes.ini=="-", na.rm=TRUE)
n.0=sum(memGenes.ini=="EE", na.rm=TRUE)
nSNPs2=length(memGenes.ini)
piVec = c(n.n, n.0, n.p)/nSNPs2
names(piVec)= c("-", "EE", "+")
piVec.ini=piVec
if(verbose)
{
cat("\ninitial pi>>\n")
print(piVec)
cat("\n")
cat("\nnSNPs*pi.ini>>\n")
print(nSNPs2*piVec)
cat("\n")
cat("\ntable(memGenes.ini>>\n")
print(table(memGenes.ini, useNA="ifany"))
cat("\n")
}
est.MLE02=est.alpha.beta.MLE(x=theta.hat)
alpha02=est.MLE02$res.moment[1]
beta02=est.MLE02$res.moment[2]
loop=0
diff = 10000
while(loop < MaxIter)
{
loop = loop + 1
res.est2=estMemSNPs.default(genoMat=genoMat, memSubjs=memSubjs,
alpha.p=alpha02, beta.p=beta02, pi.p=piVec[3],
alpha0=alpha02, beta0=beta02, pi0=piVec[2],
alpha.n=alpha02, beta.n=beta02, pi.n=piVec[1],
method = method, fdr=fdr,
verbose=FALSE)
wMat=res.est2$wMat
piVec.new=apply(wMat, 2, function(x) {
tt=sum(x,na.rm=TRUE)
numer=tt+bVec[1]-1
denom=nSNPs2+sum(bVec, na.rm=TRUE)-3
return(numer/denom)
})
diff=sum((piVec-piVec.new)^2, na.rm=TRUE)
if(diff<eps)
{
break
}
piVec=piVec.new
}
wMat=res.est2$wMat
memSNPs=res.est2$memSNPs
memSNPs2=res.est2$memSNPs2
if(verbose)
{
cat("\ndiff=", diff, "\n")
cat("\nloop=", loop, ", MaxIter=", MaxIter, "\n")
cat("\nfinal pi>>\n")
print(piVec.new)
cat("\n")
cat("\nnSNPs*pi.final>>\n")
print(nSNPs2*piVec.new)
cat("\n")
cat("table(memSNPs)>>\n")
print(table(memSNPs, useNA="ifany"))
cat("\n")
}
res=list(
wMat=wMat,
memSNPs=memSNPs,
memSNPs2=memSNPs2,
piVec.ini=piVec.ini,
piVec=piVec.new,
alpha=alpha02,
beta=beta02,
loop=loop,
diff=diff,
res.limma=res.limma)
invisible(res)
}
estMemSNPs=function(
es,
var.memSubjs="memSubjs",
eps=1.0e-3,
MaxIter=50,
bVec=rep(3,3),
pvalAdjMethod="fdr",
method = "FDR",
fdr = 0.05,
verbose=FALSE)
{
pDat=pData(es)
memSubjs=pDat[, c(var.memSubjs)]
tt=table(memSubjs)
nm=names(tt)
tt=sort(nm)
if(!identical(tt, c("0","1")))
{
stop("memSubjs should be binary taking only values 0 or 1!")
}
fDat=fData(es)
pDat=pData(es)
genoMat=exprs(es)
fmla=as.formula(paste("~", var.memSubjs, sep=""))
design=model.matrix(fmla, data=pDat)
fit = lmFit(genoMat, design)
ebFit = eBayes(fit)
pval = ebFit$p.value[, 2]
p.adj = p.adjust(pval, method=pvalAdjMethod)
stats = ebFit$t[, 2]
nSNPs=length(stats)
memGenes.ini=rep("EE", nSNPs)
memGenes.ini[which(stats>0 & p.adj < 0.05)] = "+"
memGenes.ini[which(stats<0 & p.adj < 0.05)] = "-"
memGenes2=rep(1, nSNPs)
memGenes2[which(memGenes.ini == "EE")]=0
frame.unsorted=data.frame(stats=stats, pval=pval, p.adj=p.adj)
res.limma=list(ebFit=ebFit, frame.unsorted=frame.unsorted,
memGenes.ini=memGenes.ini, memGenes2=memGenes2)
memSNPs2.snpTest=res.limma$memGenes2
genoMat=exprs(es)
nSNPs2=nrow(genoMat)
genoMat.ca=genoMat[, which(memSubjs==1)]
genoMat.co=genoMat[, which(memSubjs==0)]
theta.ca.hat=rep(NA, nSNPs2)
theta.co.hat=rep(NA, nSNPs2)
theta.hat=rep(NA, nSNPs2)
nTotal=ncol(genoMat)
for(g2 in 1:nSNPs2)
{
x.ca=genoMat.ca[g2,]
x.co=genoMat.co[g2,]
x=genoMat[g2,]
theta.hat[g2]=(2*sum(x==2)+sum(x==1))/(2*nTotal)
theta.ca.hat[g2]=(2*sum(x.ca==2)+sum(x.ca==1))/(2*nTotal)
theta.co.hat[g2]=(2*sum(x.co==2)+sum(x.co==1))/(2*nTotal)
}
pos.p=which(memSNPs2.snpTest==1 & theta.ca.hat>theta.co.hat)
est.MLE.p=est.alpha.beta.MLE(x=theta.hat[pos.p])
alpha.p=est.MLE.p$res.moment[1]
beta.p=est.MLE.p$res.moment[2]
pos0=which(memSNPs2.snpTest==0)
est.MLE0=est.alpha.beta.MLE(x=theta.hat[pos0])
alpha0=est.MLE0$res.moment[1]
beta0=est.MLE0$res.moment[2]
pos.n=which(memSNPs2.snpTest==1 & theta.ca.hat<theta.co.hat)
est.MLE.n=est.alpha.beta.MLE(x=theta.hat[pos.n])
alpha.n=est.MLE.n$res.moment[1]
beta.n=est.MLE.n$res.moment[2]
piVec = c(length(pos.n), length(pos0), length(pos.p))/nSNPs2
loop=0
diff = 10000
while(loop < MaxIter)
{
loop = loop + 1
res.est2=estMemSNPs.default(genoMat=genoMat, memSubjs=memSubjs,
alpha.p=alpha.p, beta.p=beta.p, pi.p=piVec[3],
alpha0=alpha0, beta0=beta0, pi0=piVec[2],
alpha.n=alpha.n, beta.n=beta.n, pi.n=piVec[1],
method = method, fdr=fdr,
verbose=FALSE)
wMat=res.est2$wMat
piVec.new=apply(wMat, 2, function(x) {
tt=sum(x,na.rm=TRUE)
numer=tt+bVec[1]-1
denom=nSNPs2+sum(bVec)-3
return(numer/denom)
})
diff=sum((piVec-piVec.new)^2)
if(diff<eps)
{
break
}
piVec=piVec.new
}
res=list(
wMat=res.est2$wMat,
memSNPs=res.est2$memSNPs,
memSNPs2=res.est2$memSNPs2,
piVec=piVec,
alpha.p=alpha.p,
beta.p=beta.p,
alpha0=alpha0,
beta0=beta0,
alpha.n=alpha.n,
beta.n=beta.n,
loop=loop,
diff=diff,
res.limma=res.limma)
invisible(res)
}
|
las <- lidR:::generate_las(2000)
f1 <- ~list(Zmean = mean(Z))
f2 <- ~list(meanZ = mean(Z), maxZ = max(Z))
expected_bbox <- sf::st_bbox(c(xmin = 0, xmax = 100, ymin = 0, ymax = 100), crs = st_crs(las))
expected_bbox2 <- sf::st_bbox(c(xmin = -10, xmax = 110, ymin = -10, ymax = 110), crs = st_crs(las))
slr = lidR:::raster_class()
mlr = lidR:::raster_multilayer_class()
test_that("pixel_metrics returns a named raster", {
x <- pixel_metrics(las, f1)
expect_true(is(x, slr))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equivalent(lidR:::raster_size(x), c(5,5,1))
expect_equivalent(sf::st_bbox(x), expected_bbox)
expect_equal(lidR:::raster_names(x), "Zmean")
})
test_that("pixel_metrics returns a named multilayers raster", {
x <- pixel_metrics(las, f2)
y <- pixel_metrics(las, f1)
expect_true(is(x, mlr))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equivalent(lidR:::raster_size(x), c(5,5,2))
expect_equivalent(sf::st_bbox(x), expected_bbox)
expect_equal(lidR:::raster_names(x), c("meanZ", "maxZ"))
})
test_that("pixel_metrics return raster terra or stars", {
x <- pixel_metrics(las, f2, pkg = "raster")
expect_true(is(x, "RasterBrick"))
x <- pixel_metrics(las, f2, pkg = "terra")
expect_true(is(x, "SpatRaster"))
x <- pixel_metrics(las, f2, pkg = "stars")
expect_true(is(x, "stars"))
})
test_that("pixel_metrics returns a raster aligned with the start option", {
x <- pixel_metrics(las, f1, start = c(10,10))
expect_true(is(x, slr))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equivalent(lidR:::raster_size(x), c(6,6, 1))
expect_equivalent(sf::st_bbox(x), expected_bbox2)
expect_equal(lidR:::raster_names(x), "Zmean")
})
test_that("pixel_metrics returns a named multilayers raster", {
x <- pixel_metrics(las, f2)
expect_true(is(x, mlr))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equivalent(lidR:::raster_size(x), c(5,5,2))
expect_equivalent(sf::st_bbox(x), expected_bbox)
expect_equal(lidR:::raster_names(x), c("meanZ", "maxZ"))
})
test_that("pixel_metrics returns a named multilayers raster aligned with the start option", {
x <- pixel_metrics(las, f2, start = c(10,10))
expect_true(is(x, mlr))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equivalent(lidR:::raster_size(x), c(6,6,2))
expect_equivalent(sf::st_bbox(x), expected_bbox2)
expect_equal(lidR:::raster_names(x), c("meanZ", "maxZ"))
})
test_that("pixel_metrics returns a raster -- tricky case", {
las2 <- filter_poi(las, X < 20 | X > 70)
out <- pixel_metrics(las2, f1)
expect_equivalent(lidR:::raster_size(out), c(5,5,1))
expect_equal(lidR:::raster_res(out), c(20, 20))
las2 <- filter_poi(las, (X < 20 | X > 70) & (Y < 20 | Y > 70))
out <- pixel_metrics(las2, f1, 10)
expect_equivalent(lidR:::raster_size(out), c(10,10,1))
expect_equal(lidR:::raster_res(out), c(10, 10))
})
test_that("pixel_metrics return a raster -- tricky case", {
las2 <- filter_poi(las, (X < 20 | X > 80) & (Y < 20 | Y > 80))
out <- pixel_metrics(las2, f2, 10)
expect_equivalent(lidR:::raster_size(out), c(10,10,2))
expect_equal(lidR:::raster_res(out), c(10, 10))
})
test_that("pixel_metrics accepts both an expression or a formula", {
x <- pixel_metrics(las, list(mean(Z), max(Z)), 20)
y <- pixel_metrics(las, ~list(mean(Z), max(Z)), 20)
expect_equal(x, y)
})
test_that("pixel_metrics splits by echo type", {
x <- pixel_metrics(las, f1, by_echo = c("first"))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equivalent(lidR:::raster_size(x), c(5,5,1))
expect_equivalent(sf::st_bbox(x), expected_bbox)
expect_equal(lidR:::raster_names(x), "Zmean.first")
x <- pixel_metrics(las, f1, by_echo = c("first", "lastofmany"))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equivalent(lidR:::raster_size(x), c(5,5,2))
expect_equivalent(sf::st_bbox(x), expected_bbox)
expect_equal(lidR:::raster_names(x), c("Zmean.first", "Zmean.lastofmany"))
x <- pixel_metrics(las, f2, by_echo = c("all", "first", "lastofmany"))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equivalent(lidR:::raster_size(x), c(5,5,6))
expect_equivalent(sf::st_bbox(x), expected_bbox)
expect_equal(lidR:::raster_names(x), c("meanZ", "maxZ", "meanZ.first", "maxZ.first", "meanZ.lastofmany", "maxZ.lastofmany"))
})
test_that("3 way to compute with first returns are giving the same", {
x1 <- pixel_metrics(filter_last(megaplot), f1, 20)
x2 <- pixel_metrics(megaplot, f1, 20, filter = ~ReturnNumber == NumberOfReturns)
expect_equal(x1, x2)
})
las <- filter_first(megaplot)
las@data$Intensity <- NULL
ctg <- megaplot_ctg
opt_chunk_size(ctg) <- 260
opt_chunk_alignment(ctg) <- c(160, 160)
opt_chunk_buffer(ctg) <- 0
opt_progress(ctg) <- FALSE
opt_select(ctg) <- "xyz"
opt_filter(ctg) <- "-keep_first"
bb <- as.list(round(st_bbox(las)))
bb$xmin <- bb$xmin - 160
bb$xmax <- bb$xmax - 160
bb <- sf::st_bbox(unlist(bb), crs <- st_crs(las))
stars1 <- stars::st_as_stars(bb, dx = 15, inside = TRUE)
raster1 <- as(stars1, "Raster")
bb <- as.list(st_bbox(las))
bb$xmin <- bb$xmin - 360
bb$xmax <- bb$xmax - 360
bb <- sf::st_bbox(unlist(bb), crs <- st_crs(las))
stars2 <- stars::st_as_stars(bb, dx = 15, inside = TRUE)
raster2 <- as(stars2, "Raster")
test_that("pixel_metric returns the same both with LAScatalog and LAS", {
m1 <- pixel_metrics(ctg, f1, 20)
m2 <- pixel_metrics(las, f1, 20)
expect_equivalent(m1, m2, tolerance = 3e-8)
m1 <- pixel_metrics(ctg, f2, 20)
m2 <- pixel_metrics(las, f2, 20)
expect_equivalent(m1, m2, tolerance = 3e-8)
m1 <- pixel_metrics(ctg, f1, 20, start = c(10,10))
m2 <- pixel_metrics(las, f1, 20, start = c(10,10))
expect_equivalent(m1, m2, tolerance = 3e-8)
})
test_that("pixel_metric works with a RasterLayer as input instead of a resolution", {
m <- pixel_metrics(las, f1, raster1)
expect_true(is(m, "RasterLayer"))
expect_equivalent(sf::st_bbox(m), sf::st_bbox(raster1))
expect_equal(sum(!is.na(m[])), 75L)
expect_equal(sum(is.na(m[])), 150L)
expect_warning(m <- pixel_metrics(las, f1, raster2), "Bounding boxes are not intersecting")
expect_true(is(m, "RasterLayer"))
expect_equivalent(sf::st_bbox(m), sf::st_bbox(raster2))
expect_equal(sum(is.na(m[])), 225)
})
test_that("pixel_metric works with a stars as input instead of a resolution", {
m <- pixel_metrics(las, f1, stars1)
expect_true(is(m, "stars"))
expect_equal(sf::st_bbox(m), sf::st_bbox(raster1))
expect_equal(sum(!is.na(m[[1]])), 75L)
expect_equal(sum(is.na(m[[1]])), 150L)
expect_warning(m <- pixel_metrics(las, f1, stars2), "Bounding boxes are not intersecting")
expect_equal(sf::st_bbox(m), sf::st_bbox(raster2))
expect_equal(sum(is.na(m[[1]])), 225)
})
test_that("predefined metric set work both with a LAS and LAScatalog", {
las <- random_500_points
expect_error(pixel_metrics(las, .stdmetrics_z), NA)
expect_error(pixel_metrics(las, .stdmetrics_i), NA)
expect_error(pixel_metrics(las, .stdmetrics_rn), NA)
expect_error(pixel_metrics(las, .stdmetrics_ctrl), NA)
expect_error(pixel_metrics(las, .stdshapemetrics), NA)
expect_error(pixel_metrics(ctg, .stdmetrics_z), NA)
})
test_that("Using a non empty layout return correct output (
ldr <- filter_poi(megaplot, ScanAngleRank >= -3, ScanAngleRank <= 3 )
ref <- lidR:::raster_layout(ldr, 20, format = "stars")
ref[[1]][] <- 10
m <- pixel_metrics(ldr, mean(Z), ref)
expect_equal(sum(is.na(m[[1]])), 52L)
})
test_that("grid_metrics is backward compatible", {
x <- grid_metrics(las, f1)
expect_true(is(x, "RasterLayer"))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equal(dim(x), c(13,12,1))
expect_true(sf::st_crs(x) == st_crs(las))
expect_equal(names(x), "Zmean")
expect_equal(mean(x[], na.rm = T), 13.459, tolerance = 0.001)
x <- grid_metrics(las, f2)
expect_true(is(x, "RasterBrick"))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equal(dim(x), c(13,12,2))
expect_true(sf::st_crs(x) == st_crs(las))
expect_equal(names(x), c("meanZ", "maxZ"))
expect_equal(mean(x$meanZ[], na.rm = T), 13.459, tolerance = 0.001)
x <- grid_metrics(las, f1, by_echo = c("first", "lastofmany"))
expect_true(is(x, "RasterBrick"))
expect_equal(lidR:::raster_res(x), c(20,20))
expect_equal(dim(x), c(13,12,2))
expect_true(sf::st_crs(x) == st_crs(las))
expect_equal(names(x), c("Zmean.first", "Zmean.lastofmany"))
expect_equal(mean(x$Zmean.first[], na.rm = T), 13.459, tolerance = 0.001)
expect_true(all(is.na(x$Zmean.lastofmany[])))
m1 <- grid_metrics(ctg, f1, 20)
m2 <- grid_metrics(las, f1, 20)
expect_equivalent(m1, m2)
expect_equal(names(m2), "Zmean")
m1 <- grid_metrics(ctg, f2, 20)
m2 <- grid_metrics(las, f2, 20)
expect_equivalent(m1, m2)
expect_equal(names(m2), c("meanZ", "maxZ"))
})
|
"get.direction.unitv" <- function(alpha, beta) {
cb = cos(beta)
c(cb * sin(alpha), cb * cos(alpha), sin(beta))
}
"vgm.panel.xyplot" <-
function (x, y, subscripts, type = "p", pch = plot.symbol$pch,
col, col.line = plot.line$col, col.symbol = plot.symbol$col,
lty = plot.line$lty, cex = plot.symbol$cex, ids, lwd = plot.line$lwd,
model = model, direction = direction, labels, shift = shift, mode = mode, ...)
{
x <- as.numeric(x)
y <- as.numeric(y)
if (length(x) > 0) {
if (!missing(col)) {
if (missing(col.line))
col.line <- col
if (missing(col.symbol))
col.symbol <- col
}
plot.symbol <- trellis.par.get("plot.symbol")
plot.line <- trellis.par.get("plot.line")
lpoints(x = x, y = y, cex = cex, col = col.symbol, pch = pch, type = type, ...)
if (!is.null(labels))
ltext(x = x + shift * max(x), y = y, labels = labels[subscripts])
if (mode == "direct") {
if (!missing(model) && !is.null(model)) {
ang.hor <- pi * (direction[1]/180)
ang.ver <- pi * (direction[2]/180)
dir <- get.direction.unitv(ang.hor, ang.ver)
ret <- variogramLine(model, max(x), dir = dir)
llines(x = ret$dist, y = ret$gamma, lty = lty, col = col.line, lwd = lwd)
}
} else if (mode == "cross") {
id <- as.character(ids[subscripts][1])
if (!missing(model) && !is.null(model)) {
if (inherits(model, "gstat"))
m = model$model
else
m = model
if (!is.list(m))
stop("model argument not of class gstat or list")
if (is.list(m) && !is.null(m[[id]])) {
ang.hor <- pi * (direction[1]/180)
ang.ver <- pi * (direction[2]/180)
dir <- get.direction.unitv(ang.hor, ang.ver)
ret <- variogramLine(m[[id]], max(x), dir = dir)
llines(x = ret$dist, y = ret$gamma, lty = lty, col = col.line, lwd = lwd)
}
}
} else if (mode == "directional") {
if (!missing(model) && !is.null(model)) {
dir <- c(1, 0, 0)
if (!missing(direction)) {
ang.hor <- pi * (direction[subscripts][1]/180.0)
dir <- get.direction.unitv(ang.hor, 0)
}
ret <- variogramLine(model, max(x), dir = dir)
llines(x = ret$dist, y = ret$gamma, lty = lty, col = col.line, lwd = lwd)
}
}
}
}
|
calcRelativeCoords <- function(coords, minLat, minLon) {
if (max(coords@exact$lat) < 180) {
relativeCoords <- data.frame(
lat = (coords@exact$lat - minLat) * 111000,
lon = (coords@exact$lon - minLon) * 72000
)
}
else {
relativeCoords <- data.frame(
lat = (coords@exact$lat - minLat),
lon = (coords@exact$lon - minLon)
)
}
return(relativeCoords)
}
|
ROCs.tcf <- function(method = "full", T, Dvec, V = NULL, rhoEst = NULL, piEst = NULL, cps){
methodtemp <- substitute(me, list(me = method))
okMethod <- c("full", "fi", "msi", "ipw", "spe", "knn")
if(length(methodtemp) > 1) stop(gettextf("Please, choose one method from %s", paste(sQuote(okMethod), collapse = ", ")), domain = NA)
if (!is.character(methodtemp)) methodtemp <- deparse(methodtemp)
if (!is.element(methodtemp, okMethod)){
stop(gettextf("the required method \"%s\" is not available; it should be one of %s", methodtemp, paste(sQuote(okMethod), collapse = ", ")),
domain = NA)
}
if(missing(T)) stop("argument \"T\" is missing \n")
if(!inherits(T, "numeric") | any(is.na(T))) stop("variable \"T\" must be a numeric vector and not include NA values")
method_name <- toupper(methodtemp)
if(missing(Dvec)) stop("argument \"Dvec\" is missing \n")
if(!inherits(Dvec, "matrix") | ncol(Dvec) != 3 | !all(is.element(na.omit(Dvec), c(0,1)))) stop("variable \"Dvec\" must be a binary matrix with 3 columns")
if(length(T) != nrow(Dvec)) stop(gettextf("arguments imply differing number of observation: %d", length(T)), gettextf(", %d", nrow(Dvec)), domain = NA)
if(!is.null(rhoEst)){
if(!is.element(class(rhoEst), c("prob_dise", "prob_dise_knn")))
stop("\"rhoEst\" not a result of rhoMlogit or rhoKNN \n")
if(is.element(class(rhoEst), c("prob_dise_knn"))){
if(is.null(rhoEst$K)) stop("The \"rhoEst\" is a list and contains results of rho corresponding to many K! \n Please, choose one result of them \n")
}
}
if(!is.null(piEst)){
if(!is.element(class(piEst), c("prob_veri")))
stop("\"piEst\" not a result of psglm \n")
}
tcfCal <- function(tt, dd, cp, weight, methodd){
thet.hat <- colSums(dd)/weight
names(thet.hat) <- c()
beta.func <- function(tt, dd, ctp, weight){
bet <- numeric(4)
bet[1] <- sum((tt >= ctp[1])*dd[,1])/weight
bet[2] <- sum((tt >= ctp[1])*dd[,2])/weight
bet[3] <- sum((tt >= ctp[2])*dd[,2])/weight
bet[4] <- sum((tt >= ctp[2])*dd[,3])/weight
return(bet)
}
if(!is.matrix(cp)){
bet.hat <- beta.func(tt = tt, dd = dd, ctp = cp, weight = weight)
res <- numeric(3)
res[1] <- 1 - bet.hat[1]/thet.hat[1]
res[2] <- (bet.hat[2] - bet.hat[3])/thet.hat[2]
res[3] <- bet.hat[4]/thet.hat[3]
attr(res, "beta") <- bet.hat
attr(res, "theta") <- thet.hat
attr(res, "cp") <- cp
attr(res, "name") <- methodd
names(res) <- c("TCF1", "TCF2", "TCF3")
class(res) <- "tcfs"
}
else{
res <- list()
bet.hat <- t(apply(cp, 1, beta.func, tt = tt, dd = dd, weight = weight))
temp <- matrix(0, nrow = nrow(cp), ncol = 3)
temp[,1] <- 1 - bet.hat[,1]/thet.hat[1]
temp[,2] <- (bet.hat[,2] - bet.hat[,3])/thet.hat[2]
temp[,3] <- bet.hat[,4]/thet.hat[3]
colnames(temp) <- c("TCF1", "TCF2", "TCF3")
for(i in 1:nrow(cp)){
temp1 <- temp[i,]
attr(temp1, "beta") <- bet.hat[i,]
attr(temp1, "theta") <- thet.hat
attr(temp1, "cp") <- cp[i,]
attr(temp1, "name") <- methodd
res[[i]] <- temp1
class(res[[i]]) <- "tcfs"
}
}
return(res)
}
nsize <- length(T)
if(method == "full"){
if(any(is.na(Dvec))){
stop("The", method_name, "method can not access the NA values of disease status")
}
else{
ans <- tcfCal(T, Dvec, cps, weight = nsize, methodd = method_name)
}
}
if(method == "fi"){
if(is.null(rhoEst)) stop("argument \"rhoEst\" is needed for ", method_name, "estimator")
else{
ans <- tcfCal(T, rhoEst$values, cps, weight = nsize, methodd = method_name)
}
}
if(method %in% c("msi", "knn")){
if(is.null(rhoEst) | is.null(V)) stop("argument \"rhoEst\" is needed for ", method_name, "estimator")
else{
Dvectemp <- Dvec
if(any(is.na(Dvec))) Dvectemp[is.na(Dvec)] <- 99
Dmsi <- Dvectemp*V + (1 - V)*rhoEst$values
ans <- tcfCal(T, Dmsi, cps, weight = nsize, methodd = method_name)
}
}
if(method == "ipw"){
if(is.null(piEst) | is.null(V)) stop("argument \"piEst\" is needed for ", method_name, "estimator")
else{
Dvectemp <- Dvec
if(any(is.na(Dvec))) Dvectemp[is.na(Dvec)] <- 99
Dipw <- Dvectemp*V/piEst$values
ans <- tcfCal(T, Dipw, cps, weight = sum(V/piEst$values), methodd = method_name)
}
}
if(method == "spe"){
if(is.null(rhoEst) | is.null(V) | is.null(piEst)) stop("arguments \"rhoEst\" and \"piEst\" are needed for ", method_name, " estimator")
else{
Dvectemp <- Dvec
if(any(is.na(Dvec))) Dvectemp[is.na(Dvec)] <- 99
Dspe <- Dvectemp*V/piEst$values - (V/piEst$values - 1)*rhoEst$values
ans <- tcfCal(T, Dspe, cps, weight = nsize, methodd = method_name)
}
}
ans
}
ROCs <- function(method = "full", T, Dvec, V, A = NULL, rhoEst = NULL, piEst = NULL,
ncp = 100, plot = TRUE, ellipsoid = FALSE, cpst = NULL,
level = 0.95, sur.col = c("gray40", "green"), BOOT = FALSE,
nR = 250, parallel = FALSE,
ncpus = ifelse(parallel, detectCores()/2, NULL), ...){
methodtemp <- substitute(me, list(me = method))
okMethod <- c("full", "fi", "msi", "ipw", "spe", "knn")
if(length(methodtemp) > 1) stop(gettextf("Please, choose one method from %s", paste(sQuote(okMethod), collapse = ", ")), domain = NA)
if (!is.character(methodtemp)) methodtemp <- deparse(methodtemp)
if (!is.element(methodtemp, okMethod)){
stop(gettextf("the required method \"%s\" is not available; it should be one of %s", methodtemp, paste(sQuote(okMethod), collapse = ", ")),
domain = NA)
}
if(missing(T)) stop("argument \"T\" is missing \n")
if(class(T) != "numeric" | any(is.na(T))) stop("variable \"T\" must be a numeric vector and not include NA values")
name_diagnostic <- substitute(T)
if (!is.character(name_diagnostic)) {
name_diagnostic <- deparse(name_diagnostic)
}
name_diagnostic <- unlist(strsplit(name_diagnostic, NULL))
if(any(name_diagnostic %in% c("$"))){
id.name <- which(name_diagnostic %in% c("$"))
name_diagnostic <- paste(name_diagnostic[(id.name[1] + 1) : length(name_diagnostic)],
collapse = "")
}
else name_diagnostic <- paste(name_diagnostic, collapse = "")
method_name <- toupper(methodtemp)
if(missing(Dvec)) stop("argument \"Dvec\" is missing \n")
if(isFALSE("matrix" %in% class(Dvec)) | ncol(Dvec) != 3 | !all(is.element(na.omit(Dvec), c(0,1)))) stop("variable \"Dvec\" must be a binary matrix with 3 columns")
if(length(T) != nrow(Dvec)) stop(gettextf("arguments imply differing number of observation: %d", length(T)), gettextf(", %d", nrow(Dvec)), domain = NA)
Dvec.flag <- any(is.na(Dvec))
if(ellipsoid & is.null(cpst)) stop("argument \"cpst\" is required to construct the ellipsoidal confidence region of TCFs")
if(!is.null(rhoEst)){
if(!is.element(class(rhoEst), c("prob_dise", "prob_dise_knn")))
stop("\"rhoEst\" not a result of rhoMlogit or rhoKNN \n")
if(is.element(class(rhoEst), c("prob_dise_knn"))){
if(is.null(rhoEst$K)) stop("The \"rhoEst\" is a list and contains results of rhoKNN corresponding to many K! \n Please, choose one result of them \n")
}
}
if(!is.null(piEst)){
if(!is.element(class(piEst), c("prob_veri")))
stop("\"piEst\" not a result of psglm \n")
}
if(missing(V)){
if(methodtemp != "full" | Dvec.flag) stop("argument \"V\" is missing, in addition, the method is not \"full\" or argument \"Dvec\" includes NA")
cat("Hmm, look likes the full data\n")
cat("Number of observation:", length(T), "\n")
cat("The verification status is not available\n")
cat("You are working on FULL or Complete Case approach\n")
cat("The diagnostic test:", name_diagnostic, "\n")
cat("Processing .... \n")
flush.console()
V <- NULL
}
else{
if(all(V == 0) | !all(is.element(V, c(0,1))) ) stop("There are mistakes in \"V\". Please, check your input and see whether it is correct or not")
if(nrow(Dvec) != length(V) | length(T) != length(V)) stop(gettextf("arguments imply differing number of observation: %d", length(T)), gettextf(", %d", nrow(Dvec)), domain = NA)
if(all(V == 1)){
if(methodtemp != "full" | Dvec.flag) stop("Please, check your inputs and see whether they are correct or not.\n If you want to estimate Complete Case approach, please, remove the missing values in the \n data set and try again with the option of \"full\" method.")
cat("Hmm, look likes the full data\n")
cat("Number of observation:", length(T), "\n")
cat("All subjects underwent the verification process\n")
cat("You are working on FULL or Complete Case approach\n")
cat("The diagnostic test:", name_diagnostic, "\n")
cat("Processing .... \n")
flush.console()
}
else{
rv <- mean(V)
if(!Dvec.flag){
cat("Warning: There are no NA values in variable Dvec, while", paste(round(rv*100), "%", sep = ""), "of the subjects receive disease verification. \n")
cat("BE CAREFULL OF YOUR INPUT AND RESULTS \n")
cat("Number of observation:", length(T), "\n")
cat("You required estimate ROC surface using", method_name, "approach \n")
cat("The diagnostic test:", name_diagnostic, "\n")
cat("Processing .... \n")
flush.console()
}
else{
cat("Hmm, look likes the incomplete data\n")
cat("Number of observation:", length(T), "\n")
cat(paste(round(rv*100), "%", sep = ""), "of the subjects receive disease verification. \n")
cat("You required estimate ROC surface using", method_name, "approach \n")
cat("The diagnostic test:", name_diagnostic, "\n")
if(ellipsoid){
cat("The ellipsoidal confidence region(s) of TCFs are also constructed \n")
if(!is.matrix(cpst) & !is.vector(cpst)) stop("The cut points should be a vector, which has two elements, or matrix, which has two columns.")
if(is.vector(cpst)){
if(length(cpst) != 2 | cpst[1] > cpst[2]) stop("The first cut point must be less than the second one.")
}
if(is.matrix(cpst)){
if(ncol(cpst) != 2 | any(cpst[,1] > cpst[,2])) stop("the first column must be less than or equal to the second column.")
}
}
cat("Processing .... \n")
flush.console()
}
}
}
cp <- c(-Inf, seq(min(T), max(T), length.out = ncp - 2), Inf)
cp1 <- rep(cp, seq(ncp - 1, 0, by = -1))
cp2 <- c()
for(i in 1:(ncp - 1)){
cp2 <- c(cp2, cp[-c(1:i)])
}
cpoint <- cbind(cp1, cp2)
ROCpoint <- ROCs.tcf(method = methodtemp, T = T, Dvec = Dvec, V = V,
rhoEst = rhoEst, piEst = piEst, cps = cpoint)
ROCpoint <- matrix(unlist(ROCpoint), ncol = 3, byrow = TRUE)
colnames(ROCpoint) <- c("TCF1", "TCF2", "TCF3")
rownames(ROCpoint) <- paste("(",round(cp1, 3)," , " ,round(cp2, 3), ")", sep = "")
ct1 <- numeric(ncp - 1)
for(i in 1:(ncp - 1)){
ct1[i] <- i*ncp - i*(i + 1)/2
}
tcf1 <- matrix(ROCpoint[ct1, 1], ncp - 1, ncp - 1, byrow = FALSE)
tcf3 <- matrix(ROCpoint[1:(ncp - 1), 3], ncp - 1, ncp - 1, byrow = TRUE)
tcf2 <- matrix(0, nrow = ncp - 1, ncol = ncp - 1)
tcf2[lower.tri(tcf2, diag = TRUE)] <- ROCpoint[, 2]
tcf2 <- t(tcf2)
res <- list()
res$vals <- ROCpoint
res$cpoint <- cpoint
res$ncp <- ncp
if(plot){
open3d()
par3d(windowRect = 50 + c(0, 0, 640, 640))
plot3d(0, 0, 0, type = "n", box = FALSE, xlab = " ", ylab = " ", zlab = " ",
xlim = c(0,1), ylim = c(0,1), zlim = c(0,1), ...)
surface3d(tcf1, tcf3, tcf2, col = sur.col[1], alpha = 0.5, ...)
if(any(c("full","fi", "msi", "ipw", "spe") %in% methodtemp)){
title_plot <- paste(toupper(methodtemp), "estimator")
}
if("knn" %in% methodtemp){
title_plot <- paste(rhoEst$K, "NN-",
switch(rhoEst$type, "eucli" = "Euclidean",
"manha" = "Manhattan", "canber" = "Canberra",
"lagran" = "Lagrange", "mahala" = "Mahalanobis"),
sep = "")
}
title3d(main = title_plot, xlab = "TCF1",
ylab = "TCF3", zlab = "TCF2", line = 3)
play3d(spin3d(axis = c(0, 0, 1), rpm = 12.25), duration = 2)
play3d(spin3d(axis = c(0, 1, 0), rpm = 0.3), duration = 2)
}
if(ellipsoid){
shade.ellips <- function(orgi, sig, lev){
t1 <- sig[2, 2]
sig[2, 2] <- sig[3, 3]
sig[3, 3] <- t1
t1 <- sig[1, 2]
sig[1, 2] <- sig[1, 3]
sig[1, 3] <- t1
sig[lower.tri(sig)] <- sig[upper.tri(sig)]
ellips <- ellipse3d(sig, centre = orgi[c(1,3,2)], t = sqrt(qchisq(lev, 3)))
return(ellips)
}
res$cpst <- cpst
if(is.vector(cpst)){
tcf.orgi <- ROCs.tcf(method = methodtemp, T = T, Dvec = Dvec, V = V,
rhoEst = rhoEst, piEst = piEst, cps = cpst)
tcf.sig <- asyCovTCF(tcf.orgi, T = T, Dvec = Dvec, V = V,
rhoEst = rhoEst, piEst = piEst, BOOT = BOOT,
nR = nR, parallel = parallel, ncpus = ncpus)
sig.test <- rcond(tcf.sig)
res$tcf <- tcf.orgi
if(sig.test < .Machine$double.eps){
cat("The asymptotic variance-covariance matrix of TCFs at the cut point",
paste("(",cpst[1],", ",cpst[2],")", sep = ""), "is not singular!\n")
cat("The ellipsoidal confidence region is not available!\n")
if(!BOOT & methodtemp != "full") cat("Try again with bootstrap process!\n")
plot3d(tcf.orgi[1], tcf.orgi[3], tcf.orgi[2], type = "s", col = "red",
radius = 0.01, add = TRUE, ...)
res$message <- 0
}
else{
res$message <- 1
ellip.tcf <- shade.ellips(tcf.orgi, tcf.sig, level)
plot3d(ellip.tcf, box = FALSE, col = sur.col[2], alpha = 0.5, xlim = c(0,1),
ylim = c(0, 1), zlim = c(0, 1), xlab = " ", ylab = " ", zlab = " ",
add = TRUE, ...)
plot3d(tcf.orgi[1], tcf.orgi[3], tcf.orgi[2], type = "s", col = "red",
radius = 0.01, add = TRUE, ...)
}
}
if(is.matrix(cpst)){
res$tcf <- matrix(0, nrow = nrow(cpst), ncol = 3,
dimnames = list(paste("(", round(cpst[,1], 3), " , " ,
round(cpst[,2], 3), ")", sep = ""),
c("TCF1", "TCF2", "TCF3")))
res$message <- numeric(nrow(cpst))
for(i in 1:nrow(cpst)){
tcf.orgi <- ROCs.tcf(method = methodtemp, T = T, Dvec = Dvec, V = V,
rhoEst = rhoEst, piEst = piEst, cps = cpst[i,])
tcf.sig <- asyCovTCF(tcf.orgi, T = T, Dvec = Dvec, V = V, rhoEst = rhoEst,
piEst = piEst, BOOT = BOOT, nR = nR,
parallel = parallel, ncpus = ncpus)
sig.test <- rcond(tcf.sig)
res$tcf[i,] <- tcf.orgi
if(sig.test < .Machine$double.eps){
cat("The asymptotic variance-covariance matrix of TCFs at the cut points",
paste("(",cpst[i,1],", ",cpst[i,2],")", sep = ""), "is not singular!\n")
cat("The ellipsoidal confidence region is not available!\n")
if(!BOOT & methodtemp != "full") cat("Try again with bootstrap process!\n")
plot3d(tcf.orgi[1], tcf.orgi[3], tcf.orgi[2], type = "s", col = "red",
radius = 0.01, add = TRUE, ...)
res$message[i] <- 0
}
else{
res$message[i] <- 1
ellip.tcf <- shade.ellips(tcf.orgi, tcf.sig, level)
plot3d(ellip.tcf, box = FALSE, col = sur.col[2], alpha = 0.5, xlim = c(0, 1),
ylim = c(0, 1), zlim = c(0, 1), xlab = " ", ylab = " ", zlab = " ",
add = TRUE, ...)
plot3d(tcf.orgi[1], tcf.orgi[3], tcf.orgi[2], type = "s", col = "red",
radius = 0.01, add = TRUE, ...)
}
}
}
}
cat("DONE\n")
cat("===============================================================\n")
selec.ord <- order(rowSums(ROCpoint) - 1, decreasing = TRUE)
cat("Some values of TCFs:\n")
print(ROCpoint[selec.ord[1:6],], 3)
cat("\n")
if(ellipsoid){
cat("Some information for Ellipsoidal Confidence Region(s):\n")
cat("Confidence level:", level,"\n")
if(is.vector(cpst)){
cat("TCFs at", paste("(", cpst[1], ", ", cpst[2], ")", sep = ""),"are:\n")
temp <- tcf.orgi
attributes(temp) <- NULL
names(temp) <- c("TCF1", "TCF2", "TCF3")
print(temp, 3)
}
if(is.matrix(cpst)){
colnames(res$tcf) <- c("TCF1", "TCF2", "TCF3")
rownames(res$tcf) <- paste("(",round(cpst[,1], 3)," , ",round(cpst[,2], 3),")",
sep = "")
cat("TCFs at", rownames(res$tcf), "are:\n")
print(res$tcf, 3)
}
}
cat("===============================================================\n")
invisible(res)
}
|
mr_ivw_stan <- function(data,
prior = 1,
n.chains = 3,
n.burn = 1000,
n.iter = 5000,
seed = 12345,
...) {
rstan_check()
if ("MRInput" %in% class(data)) {
data <- mrinput_mr_format(data)
}
if (!("mr_format" %in% class(data))) {
stop(
'The class of the data object must be "mr_format", please resave the object with the output of e.g. object <- mr_format(object).'
)
}
datam <- list(
n = nrow(data),
xbeta = data[, 2] / data[, 5],
ybeta = data[, 3] / data[, 5],
prior = prior
)
ivwfit <- rstan::sampling(
object = stanmodels$mrivw,
data = datam,
pars = c("estimate"),
chains = n.chains,
warmup = n.burn,
iter = n.iter,
seed = seed,
control = list(adapt_delta = 0.999, max_treedepth = 15),
...
)
return(ivwfit)
}
|
source(system.file(file.path('tests', 'testthat', 'test_utils.R'), package = 'nimble'))
context("Testing of CAR distributions")
RwarnLevel <- options('warn')$warn
options(warn = 1)
nimbleVerboseSetting <- nimbleOptions('verbose')
nimbleOptions(verbose = FALSE)
nimbleProgressBarSetting <- nimbleOptions('MCMCprogressBar')
nimbleOptions(MCMCprogressBar = FALSE)
test_that('dcar_normal sampling', {
cat('===== Starting MCMC test dcar_normal sampling. =====')
code <- nimbleCode({
alpha0 ~ dflat()
S[1:N] ~ car.normal(adj[1:L], weights[1:L], num[1:N], 3)
for(i in 1:N)
mu[i] <- alpha0 + S[i]
for(i in 1:2) {
log(lambda[i]) <- mu[i]
Y[i] ~ dpois(lambda[i])
}
Y[3] ~ dnorm(mu[3], 3)
ymean4 <- 5*mu[4]
Y[4] ~ dnorm(ymean4, 7)
ymean5 <- 2*mu[5]
Y[5] ~ dnorm(ymean5, 1)
})
constants <- list(N = 6,
num = c(3,4,4,3,2,2),
adj = c(2,3,4, 1,3,5,6, 1,2,4,5, 1,3,6, 2,3, 2,4),
weights = rep(1, 18),
L = 18)
data <- list(Y = c(10,12,15,20,24))
inits <- list(alpha0 = 0,
S = c(0,0,0,0,0,0))
Rmodel <- nimbleModel(code, constants, data, inits)
conf <- configureMCMC(Rmodel)
Rmcmc <- buildMCMC(conf)
Cmodel <- compileNimble(Rmodel)
Cmcmc <- compileNimble(Rmcmc, project = Rmodel)
niter <- 20
set.seed(0); Rmcmc$run(niter)
set.seed(0); Cmcmc$run(niter)
Rsamples <- as.matrix(Rmcmc$mvSamples)
Csamples <- as.matrix(Cmcmc$mvSamples)
sampleNames <- colnames(Rsamples)
expect_true(all(Rsamples[, sampleNames] - Csamples[, sampleNames] == 0),
info = 'agreement between R and C sampling of dcar_normal')
expect_lt(max(abs(as.numeric(Csamples[20, sampleNames]) -
c(1.639127, 1.815422, 1.676655, 5.099797, 2.345276, 7.018026, 2.696936))), 1e-6,
label = 'exact sample values for dcar_normal')
})
test_that('dcar_proper density evaluation', {
cat('===== Starting test dcar_proper density evaluations. =====')
x <- c(1, 3, 3, 4)
mu <- rep(3, 4)
adj <- c(2, 1,3, 2,4, 3)
num <- c(1, 2, 2, 1)
lp <- 0.004158475
expect_equal(dcar_proper(x, mu, adj=adj, num=num, tau=1, gamma=0), lp,
info = 'C density evaluation for dcar_proper() omitting C and M')
weights <- rep(1, 6)
CM <- as.carCM(adj, weights, num)
C <- CM$C
M <- CM$M
expect_equal(dcar_proper(x, mu, C, adj, num, M, tau=1, gamma=0), lp,
info = 'C density evaluation for dcar_proper() weights all one')
weights <- c(2, 2, 3, 3, 4, 4)
CM2 <- as.carCM(adj, weights, num)
C2 <- CM2$C
M2 <- CM2$M
lp2 <- 0.001050636
expect_equal(dcar_proper(x, mu, C2, adj, num, M2, tau=1, gamma=0), lp2,
info = 'C density evaluation for dcar_proper() weights different')
})
test_that('dcar_proper sampling', {
cat('===== Starting MCMC test dcar_proper sampling. =====')
code <- nimbleCode({
tau ~ dgamma(0.001, 0.001)
gamma ~ dunif(-1, 1)
x[1:N] ~ dcar_proper(mu[1:N], adj=adj[1:L], num=num[1:N], tau=tau, gamma=gamma)
y[1] ~ dnorm(x[1], 1)
y[2] ~ dnorm(3*x[2] + 5, 10)
y[3] ~ dnorm(x[3]^2, 1)
y[4] ~ dnorm(x[4]^2, 10)
})
mu <- 1:4
adj <- c(2, 1, 3, 2, 4, 3)
num <- c(1, 2, 2, 1)
tau <- 1
gamma <- 0
y <- c(3, 6, 8, 10)
x <- rep(0, 4)
constants <- list(mu = mu, adj = adj, num = num, N = 4, L = 6)
data <- list(y = y)
inits <- list(tau = tau, gamma = gamma, x = x)
Rmodel <- nimbleModel(code, constants, data, inits)
Cmodel <- compileNimble(Rmodel)
lp <- -574.964
expect_lt(abs(calculate(Rmodel) - lp), 1E-5,
label = 'calculate for dcar_proper()')
expect_lt(abs(calculate(Cmodel) - lp), 1E-5,
label = 'calculate for dcar_proper(), compiled')
weights <- rep(1, 6)
CM <- as.carCM(adj, weights, num)
C <- CM$C
M <- CM$M
Q <- tau * diag(1/M) %*% (diag(4) - gamma*CAR_calcCmatrix(C, adj, num))
lp <- dmnorm_chol(x, mu, chol = chol(Q), prec_param = TRUE, log = TRUE)
expect_equal(calculate(Rmodel, 'x[1:4]'), lp,
info = 'R density evaluation for dcar_proper()')
expect_equal(calculate(Cmodel, 'x[1:4]'), lp,
info = 'C density evaluation for dcar_proper()')
set.seed(0); xnew <- rmnorm_chol(n = 1, mu, chol = chol(Q), prec_param = TRUE)
set.seed(0); simulate(Rmodel, 'x[1:4]')
set.seed(0); simulate(Cmodel, 'x[1:4]')
expect_equal(xnew, Rmodel$x, info = 'R dcar_proper() simulate function')
expect_equal(xnew, Cmodel$x, info = 'R dcar_proper() simulate function')
Rmodel$x <- x
Cmodel$x <- x
conf <- configureMCMC(Rmodel)
conf$addMonitors('x')
Rmcmc <- buildMCMC(conf)
Cmcmc <- compileNimble(Rmcmc, project = Rmodel)
niter <- 20
set.seed(0); Rmcmc$run(niter)
set.seed(0); Cmcmc$run(niter)
Rsamples <- as.matrix(Rmcmc$mvSamples)
Csamples <- as.matrix(Cmcmc$mvSamples)
sampleNames <- colnames(Rsamples)
expect_true(all(Rsamples[, sampleNames] - Csamples[, sampleNames] == 0),
info = 'agreement between R and C sampling of dcar_proper')
expect_lt(max(abs(as.numeric(Csamples[20, sampleNames]) -
c(-0.86201288, 0.07689823, 2.04074467, 0.24380342, 3.00405982, -3.25336913))), 1e-6,
label = 'exact sample values for dcar_proper')
})
test_that('dcar_proper gives correct likelihood with singular Cmatrix', {
nHabRows <- nHabCols <- 5
adj <- NULL
numadj <- NULL
numHabWindows <- nHabRows * nHabCols
for(i in 1:numHabWindows){
{
lenadj <- length(adj)
if(i == 1) adj <- c(adj, c(2, nHabCols + 1))
else if((2 <= i) & (i <= nHabCols - 1)) adj <- c(adj, c(i-1, i+1, i+nHabCols))
else if(i == nHabCols) adj <- c(adj, c(i-1, i+nHabCols))
else if(i %in% c(1:(nHabRows-2)*nHabCols+1)) adj <- c(adj, c(i-nHabCols, i+1, i+nHabCols))
else if(i %in% c(2:(nHabRows-1)*nHabCols)) adj <- c(adj, c(i-nHabCols, i-1, i+nHabCols))
else if(i == (nHabRows-1)*nHabCols+1) adj <- c(adj, c(i-nHabCols, i+1))
else if(((nHabRows-1)*nHabCols+2 <= i) & (i <= nHabCols*nHabRows-1)) adj <- c(adj, c(i-nHabCols, i-1, i+1))
else if(i == nHabCols*nHabRows) adj <- c(adj, c(i-nHabCols, i-1))
else adj <- c(adj, c(i-nHabCols, i-1, i+1, i+nHabCols))
numadj[i] <- length(adj) - lenadj
}
}
num <- numadj
tau <- 1
gamma <- 0.5
mu <- rep(0, numHabWindows)
x <- rep(0, numHabWindows)
C <- CAR_calcC(adj, num)
M <- CAR_calcM(num)
Cmatrix <- CAR_calcCmatrix(C, adj, num)
CovMatrix <- solve(diag(numHabWindows) - gamma*Cmatrix) %*% diag(M) / tau
lp_true <- (2*pi)^(-numHabWindows/2) * det(CovMatrix)^(-1/2)
lp_dcar <- dcar_proper(x, mu = mu, adj = adj, num = num, tau = tau, gamma = gamma)
expect_equal(lp_true, lp_dcar)
set.seed(0)
xnew <- rcar_proper(n = 1, mu = mu, adj = adj, num = num, tau = tau, gamma = gamma)
expect_true(all(round(xnew, 8) == c(0.60896921, -0.18071413, 0.86723430, 0.87426463, 0.66326831, -0.95558320, -0.56113360, -0.22185377, 0.14990019, 1.37682998, 0.32056427, -0.48639310, -0.65728773, -0.16961897, -0.30264915, -0.23875949, 0.10629314, -0.40382663, 0.18898157, -0.72969397, -0.09361655, 0.25556273, 0.16314071, 0.46935282, -0.04233136)))
})
test_that('CAR conjugacy checking new skipExpansionsNode system', {
code <- nimbleCode({
S[1:N] ~ dcar_normal(adj[1:L], weights[1:L], numneighbours[1:N], 1)
for(i in 1:K) {
beta[i] ~ dnorm(0, 1)
}
for(i in 1:N){
eta[i] <- inprod(beta[1:K], x[1:K])
mu[i] <- S[i] + eta[i]
y[i] ~ dnorm(mu[i], 1)
}
})
N <- 3
L <- 4
K <- 7
constants <- list(N=N, L=L, K=K, adj=c(2,1,3,2), weights=rep(1,L), numneighbours=c(1,2,1))
data <- list(y = rep(0,N))
inits <- list(S = rep(0,N), beta = rep(0,K), x=1:K)
Rmodel <- nimbleModel(code, constants, data, inits)
conf <- configureMCMC(Rmodel)
Rmcmc <- buildMCMC(conf)
expect_true(class(Rmcmc) == 'MCMC')
expect_true(conf$samplerConfs[[8]]$name == 'CAR_normal')
expect_true(class(Rmcmc$samplerFunctions$contentsList[[8]]$componentSamplerFunctions$contentsList[[1]]) == 'CAR_scalar_conjugate')
expect_true(class(Rmcmc$samplerFunctions$contentsList[[8]]$componentSamplerFunctions$contentsList[[2]]) == 'CAR_scalar_conjugate')
expect_true(class(Rmcmc$samplerFunctions$contentsList[[8]]$componentSamplerFunctions$contentsList[[3]]) == 'CAR_scalar_conjugate')
compiledList <- compileNimble(list(model=Rmodel, mcmc=Rmcmc))
Cmodel <- compiledList$model; Cmcmc <- compiledList$mcmc
set.seed(0); Rsamples <- runMCMC(Rmcmc, 10)
set.seed(0); Csamples <- runMCMC(Cmcmc, 10)
expectedSamples <- c(0.97357331, 0.07601302, 0.10439196, -0.37719856, 0.15912985, 0.03509085, -0.01162275, 0.17958068, -0.34811805, 0.10319592)
Rcolnames <- colnames(Rsamples)
expect_true(all(round(as.numeric(Rsamples[10,Rcolnames]),8) == expectedSamples))
expect_true(all(round(as.numeric(Csamples[10,Rcolnames]),8) == expectedSamples))
})
options(warn = RwarnLevel)
nimbleOptions(verbose = nimbleVerboseSetting)
nimbleOptions(MCMCprogressBar = nimbleProgressBarSetting)
|
PremiumFrac<-function(px1,x,m,k,i=0.04,data,prop=1,effect="yes",assumption){
dig<-getOption("digits")
on.exit(options(digits = dig))
options(digits = 15)
if(k==1){
premium<-px1/a(x,0,m,k,i,data,prop,assumption,1)
return(premium)
}else{
if(effect=="yes"){
Annualpremium<-px1/a(x,0,m,k,i,data,prop,assumption,1)
return(Annualpremium)
}else{
if(effect=="no" && k>1 && k<=12){
Annualpremiumnofrac<-px1/a(x,0,m,1,i,data,prop,assumption,1)
v<-1/(1+i)
d<-Rate_converter(i,"i",1,"d",1,"frac")
fk<-Rate_converter(i,"i",1,"f",k,"frac")
Annualpremium<-Annualpremiumnofrac*(fk/d)
return(Annualpremium)
}else{
stop("Check effect or value of k")
}
}
}
}
|
FitGev <- function(data, method='Nelder-Mead', start, varest=FALSE)
{
param <- NULL
varcov <- NULL
stderr <- NULL
numdata <- length(data)
if(missing(data) || numdata == 0 || !is.numeric(data))
stop('insert a numeric vector of data')
momest <- MomEst(data, numdata)
location <- momest$location
scale <- momest$scale
shape <- momest$shape
if(shape >= 0) shape <- .1
else shape <- -.1
param <- list(location=location, scale=scale, shape=shape)
parnames <- c('location', 'scale', 'shape')
if(!missing(start))
{
if(!is.list(start))
stop('start need to be named list of starting values')
for(i in 1 : length(start))
{
namestart <- names(start[i])
if(!any(namestart == parnames))
stop('insert location, scale and shape as a named list')
param[namestart] <- start[namestart]
}
if(param$scale < 0)
param$scale <- scale
}
param <- unlist(param)
fitted <- optim(param, GevLogLik, data=data, method=method, numdata=numdata,
control=list(fnscale=-1, reltol=1e-14, maxit=1e8), hessian=varest)
if(varest)
{
varcov <- - try(solve(fitted$hessian), silent = TRUE)
if(!is.matrix(varcov))
{
varcov <- 'none'
stderr <- 'none'
}
else
{
stderr <- diag(varcov)
if(any(stderr < 0))
stderr <- 'none'
else
stderr <- sqrt(stderr)
}
}
return(list(param=fitted$par, varcov=varcov, stderr=stderr))
}
Dist2Dist <- function(data, from='Gev', to='sFrechet', loc=NULL, scale=NULL, shape=NULL)
{
Dist2Dist <- NULL
if(missing(data) || !is.numeric(data))
stop('insert a numeric vector of data')
dimdata <- dim(data)
if(is.null(dimdata))
{
numdata <- length(data)
if(numdata==0)
stop('insert a numeric vector of data')
numcoord <- 1
dimdata <- c(numdata, numcoord)
dim(data) <- dimdata
numparam <- numdata
}
else
{
if(length(dimdata)==2)
{
numdata <- dimdata[1]
numcoord <- dimdata[2]
}
if(length(dimdata)==3)
{
numdata <- dimdata[3]
numcoord <- prod(dimdata[1:2])
}
numparam <- numcoord
}
if(is.null(loc)) loc <- double(numcoord)
else if(!is.numeric(loc) || !length(loc)==numparam)
stop('insert a numeric vector of locations\n')
if(is.null(scale)) scale <- double(numcoord) + 1
else if(!is.numeric(scale) || !length(scale)==numparam)
stop('insert a numeric vector of scales\n')
if(is.null(shape)) shape <- double(numcoord)
else if(!is.numeric(shape) || !length(shape)==numparam)
stop('insert a numeric vector of shapes\n')
Mle <- function(x)
return(as.double(FitGev(x)$param))
if(from=='Gev')
{
type <- switch(to,
Uniform=0,
sFrechet=1,
sGumbel=2,
sWeibull=3,
Gev=4)
if(is.null(type))
stop('insert a valid distribution name\n')
param <- apply(data, 2, Mle)
Dist2Dist <- .C('Dist2Dist', as.double(data), as.double(param[1,]), as.double(param[2,]),
as.double(param[3,]), as.integer(numdata), as.integer(numcoord),
as.double(loc), as.double(scale), as.double(shape), as.integer(type),
res=double(numdata * numcoord), DUP=TRUE, NAOK=TRUE)$res
}
if(from=='sFrechet')
{
type <- switch(to, Gev=5)
if(is.null(type))
stop('insert a valid distribution name\n')
param <- rep(1, 3)
Dist2Dist <- .C('Dist2Dist', as.double(data), as.double(param[1]), as.double(param[2]),
as.double(param[3]), as.integer(numdata), as.integer(numcoord),
as.double(loc), as.double(scale), as.double(shape), as.integer(type),
res=double(numdata * numcoord), DUP=TRUE, NAOK=TRUE)$res
}
if(from=='sGumbel')
{
type <- switch(to, Gev=6)
if(is.null(type))
stop('insert a valid distribution name\n')
param <- rep(1, 3)
Dist2Dist <- .C('Dist2Dist', as.double(data), as.double(param[1]), as.double(param[2]),
as.double(param[3]), as.integer(numdata), as.integer(numcoord),
as.double(loc), as.double(scale), as.double(shape), as.integer(type),
res=double(numdata * numcoord), DUP=TRUE, NAOK=TRUE)$res
}
if(from=='sWeibull')
{
type <- switch(to, Gev=7)
if(is.null(type))
stop('insert a valid distribution name\n')
param <- rep(1, 3)
Dist2Dist <- .C('Dist2Dist', as.double(data), as.double(param[1]), as.double(param[2]),
as.double(param[3]), as.integer(numdata), as.integer(numcoord),
as.double(loc), as.double(scale), as.double(shape), as.integer(type),
res=double(numdata * numcoord), DUP=TRUE, NAOK=TRUE)$res
}
dim(Dist2Dist) <- dimdata
return(Dist2Dist)
}
GevLogLik <- function(data, numdata, param)
{
result <- .C('GevLogLik', as.double(data), as.integer(numdata), as.double(param),
res=double(1), DUP=TRUE, NAOK=TRUE)$res
return(result)
}
MomEst <- function(data, n)
{
scale <- sqrt(6 * var(data)) / pi
location <- mean(data) - 0.58 * scale
k <- round(.5 * n)
mind <- min(data)
if(mind < 0) data <- data - mind
data <- sort(data)
delta <- log(data[n-0:(k-1)] / data[n-k])
M1 <- sum(delta) / k
M2 <- sum(delta^2) / k
shape <- M1 + 1 - .5 * (M2 / (M2 - M1^2))
return(list(location=location, scale=scale, shape=shape))
}
|
test_that("If user selects no, database not updated", {
skip_on_cran()
f <- file()
options(GSODR_connection = f)
ans <- "no"
write(ans, f)
expect_error(update_station_list())
options(GSODR_connection = stdin())
close(f)
})
test_that("update_station_list() downloads and imports proper file", {
skip_on_cran()
f <- file()
options(GSODR_connection = f)
ans <- "yes"
write(ans, f)
expect_message(update_station_list())
load(system.file("extdata", "isd_history.rda", package = "GSODR"))
expect_equal(ncol(isd_history), 11)
expect_named(
isd_history,
c(
"STNID",
"NAME",
"LAT",
"LON",
"CTRY",
"STATE",
"BEGIN",
"END",
"COUNTRY_NAME",
"ISO2C",
"ISO3C"
)
)
expect_equal(options("timeout")[[1]], 60)
options(GSODR_connection = stdin())
close(f)
})
|
analyseBINdata <-
function(obj_pickBIN, nfchn, nlchn, bg="late", me=2.0,
distp="p", kph=NULL, kdc=NULL, dcr=NULL,
FR.fchn=NULL, FR.mchn=NULL, FR.lchn=NULL,
signal.type="LxTx", outfile=NULL) {
UseMethod("analyseBINdata")
}
analyseBINdata.default <-
function(obj_pickBIN, nfchn, nlchn, bg="late", me=2.0,
distp="p", kph=NULL, kdc=NULL, dcr=NULL,
FR.fchn=NULL, FR.mchn=NULL, FR.lchn=NULL,
signal.type="LxTx", outfile=NULL) {
stopifnot(class(obj_pickBIN)=="pickBIN",
names(obj_pickBIN)==c("BINdata","agID"),
length(nfchn)==1L, is.numeric(nfchn),
length(nlchn)==1L, is.numeric(nlchn),
length(bg)==1L, bg %in% c("early", "late"),
length(me)==1L, is.numeric(me),
length(distp)==1L, distp %in% c("p","op"),
is.null(kph) || (length(kph)==1L && is.numeric(kph)),
is.null(kdc) || (length(kdc)==1L && is.numeric(kdc)),
is.null(dcr) || (length(dcr)==1L && is.numeric(dcr)),
is.null(FR.fchn) || is.numeric(FR.fchn),
is.null(FR.mchn) || is.numeric(FR.mchn),
is.null(FR.lchn) || is.numeric(FR.lchn),
length(signal.type)==1L, signal.type %in% c("LxTx", "Lx", "Tx"),
is.null(outfile) || (length(outfile)==1L && is.character(outfile)))
if (is.null(obj_pickBIN$agID)) {
stop("Error: set force.matrix=FALSE in function pickBINdata()!")
}
if (distp=="op") {
if (is.null(kph) || is.null(kdc) || is.null(dcr)) {
stop("Error: parameter [kph,kdc,dcr] should be provided!")
}
}
recordList <- obj_pickBIN$BINdata
nList <- length(recordList)
analyseSig <- function(sigData, n_fchn, n_lchn) {
NPoints <- attr(sigData, "NPoints")
Delay <- attr(sigData, "Delay")
Off <- attr(sigData, "Off")
On <- NPoints - Delay - Off
if (On<=1L) return(rep(NA,7L))
Low <- attr(sigData, "Low")
High <- attr(sigData, "High")
vstep <- (High-Low)/NPoints
IRRTime <- attr(sigData, "IRRTime")
if (!is.null(FR.fchn) && !is.null(FR.mchn) && !is.null(FR.lchn)) {
range_FR.fchn <- range(FR.fchn)
if (range_FR.fchn[1L]<1L) range_FR.fchn[1L] <- 1L
if (range_FR.fchn[2L]>On) range_FR.fchn[2L] <- On
range_FR.mchn <- range(FR.mchn)
if (range_FR.mchn[1L]<1L) range_FR.mchn[1L] <- 1L
if (range_FR.mchn[2L]>On) range_FR.mchn[2L] <- On
range_FR.lchn <- range(FR.lchn)
if (range_FR.lchn[1L]<1L) range_FR.lchn[1L] <- 1L
if (range_FR.lchn[2L]>On) range_FR.lchn[2L] <- On
n_FR.fchn <- range_FR.fchn[2L] - range_FR.fchn[1L] + 1L
n_FR.mchn <- range_FR.mchn[2L] - range_FR.mchn[1L] + 1L
n_FR.lchn <- range_FR.lchn[2L] - range_FR.lchn[1L] + 1L
kf <- n_FR.lchn/n_FR.fchn
km <- n_FR.lchn/n_FR.mchn
all_On_channels <- (Delay+1L):(Delay+On)
photon_FR.fchn <- sum((sigData[all_On_channels])[range_FR.fchn[1L]:range_FR.fchn[2L]])
photon_FR.mchn <- sum((sigData[all_On_channels])[range_FR.mchn[1L]:range_FR.mchn[2L]])
photon_FR.lchn <- sum((sigData[all_On_channels])[range_FR.lchn[1L]:range_FR.lchn[2L]])
photon_FR.lchn_f <- n_FR.fchn*mean((sigData[all_On_channels])[range_FR.lchn[1L]:range_FR.lchn[2L]])
photon_FR.lchn_m <- n_FR.mchn*mean((sigData[all_On_channels])[range_FR.lchn[1L]:range_FR.lchn[2L]])
net_photon_FR.fchn <- photon_FR.fchn - photon_FR.lchn_f
net_photon_FR.mchn <- photon_FR.mchn - photon_FR.lchn_m
if (abs(net_photon_FR.fchn)<=.Machine$double.eps^0.5) net_photon_FR.fchn <- 1.0e-5
if (abs(net_photon_FR.mchn)<=.Machine$double.eps^0.5) net_photon_FR.mchn <- 1.0e-5
FR <- net_photon_FR.fchn / net_photon_FR.mchn
if (distp=="p") {
rse_net_photon_FR.fchn <- sqrt(photon_FR.fchn+photon_FR.lchn_f/kf)/abs(net_photon_FR.fchn)
rse_net_photon_FR.mchn <- sqrt(photon_FR.mchn+photon_FR.lchn_m/km)/abs(net_photon_FR.mchn)
} else if (distp=="op") {
vdif <- kdc^2L-kph^2L
rse_net_photon_FR.fchn <- sqrt(kph^2L*photon_FR.fchn+vdif*dcr*n_FR.fchn*vstep+
(kph^2L*photon_FR.lchn+vdif*dcr*n_FR.lchn*vstep)/kf^2L)/net_photon_FR.fchn
rse_net_photon_FR.mchn <- sqrt(kph^2L*photon_FR.mchn+vdif*dcr*n_FR.mchn*vstep+
(kph^2L*photon_FR.lchn+vdif*dcr*n_FR.lchn*vstep)/km^2L)/net_photon_FR.mchn
}
rse_net_photon_FR.fchn <- sqrt(rse_net_photon_FR.fchn^2L+(me/100.0)^2L)
rse_net_photon_FR.mchn <- sqrt(rse_net_photon_FR.mchn^2L+(me/100.0)^2L)
seFR <- abs(FR)*sqrt(rse_net_photon_FR.fchn^2L+rse_net_photon_FR.mchn^2L)
} else {
FR <- seFR <- NA
}
if (n_fchn<On) {
Lx <- sum(sigData[(Delay+1L):(Delay+n_fchn)])
n_fchn <- n_fchn
} else {
Lx <- sum(sigData[(Delay+1L):(Delay+On-1L)])
n_fchn <- On-1L
}
if (bg=="early" && n_lchn<=(On-n_fchn)) {
bLx <- n_fchn*mean(sigData[(Delay+n_fchn+1L):(Delay+n_fchn+n_lchn)])
sum_bLx <- sum(sigData[(Delay+n_fchn+1L):(Delay+n_fchn+n_lchn)])
n_lchn <- n_lchn
} else if (bg=="late" && n_lchn<=(On-n_fchn)) {
bLx <- n_fchn*mean(sigData[(Delay+On-n_lchn+1L):(Delay+On)])
sum_bLx <- sum(sigData[(Delay+On-n_lchn+1L):(Delay+On)])
n_lchn <- n_lchn
} else {
bLx <- n_fchn*mean(sigData[(Delay+n_fchn+1L):(Delay+On)])
sum_bLx <- sum(sigData[(Delay+n_fchn+1L):(Delay+On)])
n_lchn <- On-n_fchn
}
k <- n_lchn/n_fchn
netLx <- Lx-bLx
if (abs(netLx)<=.Machine$double.eps^0.5) netLx <- 1.0e-5
if (distp=="p") {
var_Lx <- Lx
var_bLx <- bLx/k
} else if (distp=="op") {
vdif <- kdc^2L-kph^2L
var_Lx <- kph^2L*Lx+vdif*dcr*n_fchn*vstep
var_bLx <- (kph^2L*sum_bLx+vdif*dcr*n_lchn*vstep)/k^2L
}
rse_netLx <- sqrt(var_Lx+var_bLx)/abs(netLx)
rse_netLx <- sqrt(rse_netLx^2L+(me/100.0)^2L)
values <- c(IRRTime, Lx, sqrt(var_Lx), bLx, sqrt(var_bLx), netLx, rse_netLx, FR, seFR)
return(values)
}
NO <- obj_pickBIN$agID[,"NO",drop=TRUE]
LxTx_list <- vector(length=length(NO), mode="list")
LnTn.curve <- list()
for (i in seq(NO)) {
iRecord <- recordList[[i]]
length_iRecord <- length(iRecord)
Ln_NPoints <- attr(iRecord[[1L]], "NPoints")
if (Ln_NPoints>0L) {
Ln_Low <- attr(iRecord[[1L]], "Low")
Ln_High <- attr(iRecord[[1L]], "High")
Ln_vstep <- (Ln_High-Ln_Low)/Ln_NPoints
iLn_curve_x <- seq(from=Ln_vstep, to=Ln_High, by=Ln_vstep)
iLn_curve_y <- as.numeric(iRecord[[1L]])
} else {
iLn_curve_x <- iLn_curve_y <- NA
}
if (length_iRecord>=2L) {
Tn_NPoints <- attr(iRecord[[2L]], "NPoints")
if (Tn_NPoints>0L) {
Tn_Low <- attr(iRecord[[2L]], "Low")
Tn_High <- attr(iRecord[[2L]], "High")
Tn_vstep <- (Tn_High-Tn_Low)/Tn_NPoints
iTn_curve_x <- seq(from=Tn_vstep, to=Tn_High, by=Tn_vstep)
iTn_curve_y <- as.numeric(iRecord[[2L]])
} else {
iTn_curve_x <- iTn_curve_y <- NA
}
} else {
iTn_curve_x <- iTn_curve_y <- NA
}
characterNO <- paste("NO", i, sep="")
LnTn.curve[[characterNO]] <- list("Ln.x"=iLn_curve_x, "Ln.y"=iLn_curve_y,
"Tn.x"=iTn_curve_x, "Tn.y"=iTn_curve_y)
i_matrix <- c()
for (j in seq(length_iRecord)) {
i_matrix <- rbind(i_matrix, analyseSig(iRecord[[j]], nfchn, nlchn))
}
colnames(i_matrix) <- c("IRRTime","OSL","seOSL","BG","seBG","netOSL","rse.netOSL","FR","seFR")
LxTx_list[[i]] <- i_matrix
}
Position <- obj_pickBIN$agID[,"Position",drop=TRUE]
Grain <- obj_pickBIN$agID[,"Grain",drop=TRUE]
SARdata <- ALLdata <- data.frame(stringsAsFactors=FALSE)
Tn3BG_vec <- rseTn_vec <-
TnBG.ratio_vec <- seTnBG.ratio_vec <-
FR_vec <- seFR_vec <- c()
Tn_vec <- seTn_vec <- c()
TxTn <- list()
agID <- c()
accept_characterNO <- c()
for (i in seq(NO)) {
iLxTx <- LxTx_list[[i]]
selectedIndex <- which(is.finite(iLxTx[,"IRRTime",drop=TRUE]) &
is.finite(iLxTx[,"netOSL",drop=TRUE]) &
is.finite(iLxTx[,"rse.netOSL",drop=TRUE]))
iLxTx <- iLxTx[selectedIndex,,drop=FALSE]
nr <- nrow(iLxTx)
nc <- ncol(iLxTx)
if (nr==0L) {
cat(paste("[NO=",NO[i],",Position=",Position[i],",Grain=",Grain[i],
"]: analysis failed!\n",sep=""))
} else if (nr==1L) {
cat(paste("[NO=",NO[i],",Position=",Position[i],",Grain=",Grain[i],
"]: only one Lx[Tx] (omitted)!\n",sep=""))
} else if (!(selectedIndex[1L]==1L && selectedIndex[2L]==2L)) {
cat(paste("[NO=",NO[i],",Position=",Position[i],",Grain=",Grain[i],
"]: analysis failed!\n",sep=""))
} else {
accept_characterNO <- c(accept_characterNO, paste("NO", i, sep=""))
if (nr%%2L!=0L) {
cat(paste("[NO=",NO[i],",Position=",Position[i],",Grain=",Grain[i],
"]: unpaired Lx-Tx (omit the last Lx[Tx])!\n",sep=""))
iLxTx <- iLxTx[-nr,,drop=FALSE]
}
nPairedLxTx <- nrow(iLxTx)/2L
iNO <- rep(NO[i], nPairedLxTx)
iPosition <- rep(Position[i], nPairedLxTx)
iGrain <- rep(Grain[i], nPairedLxTx)
if (nPairedLxTx==1L) {
iSAR.Cycle <- "N"
} else {
iSAR.Cycle <- c("N", paste("R",seq(nPairedLxTx-1L),sep=""))
}
Dose <-
Init <- seInit <- BG <- seBG <- netLx <- rse_netLx <-
TInit <- seTInit <- TBG <- seTBG <- netTx <- rse_netTx <-
TFR <- seTFR <- LxTx <- seLxTx <- vector(length=nPairedLxTx)
for (j in seq(nPairedLxTx)) {
Dose[j] <- iLxTx[2L*j-1L,"IRRTime"]
Init[j] <- iLxTx[2L*j-1L,"OSL"]
seInit[j] <- iLxTx[2L*j-1L,"seOSL"]
BG[j] <- iLxTx[2L*j-1L,"BG"]
seBG[j] <- iLxTx[2L*j-1L,"seBG"]
netLx[j] <- iLxTx[2L*j-1L,"netOSL"]
rse_netLx[j] <- iLxTx[2L*j-1L,"rse.netOSL"]
TInit[j] <- iLxTx[2L*j,"OSL"]
seTInit[j] <- iLxTx[2L*j,"seOSL"]
TBG[j] <- iLxTx[2L*j,"BG"]
seTBG[j] <- iLxTx[2L*j,"seBG"]
netTx[j] <- iLxTx[2L*j,"netOSL"]
rse_netTx[j] <- iLxTx[2L*j,"rse.netOSL"]
TFR[j] <- iLxTx[2L*j,"FR"]
seTFR[j] <- iLxTx[2L*j,"seFR"]
LxTx[j] <- netLx[j]/netTx[j]
seLxTx[j] <- abs(LxTx[j])*sqrt((rse_netLx[j])^2L+(rse_netTx[j])^2L)
}
Tn3BG_vec <- c(Tn3BG_vec, netTx[1L]>0.0 && netTx[1L]>3.0*seTBG[1L])
rseTn_vec <- c(rseTn_vec, rse_netTx[1L]*100.0)
TnBG.ratio_vec <- c(TnBG.ratio_vec, TInit[1L]/TBG[1L])
useitpass <- abs(TInit[1L]/TBG[1L])*sqrt((seTInit[1L]/TInit[1L])^2L+(seTBG[1L]/TBG[1L])^2L)
seTnBG.ratio_vec <- c(seTnBG.ratio_vec, useitpass)
FR_vec <- c(FR_vec, TFR[1L])
seFR_vec <- c(seFR_vec, seTFR[1L])
Tn_vec <- c(Tn_vec, netTx[1L])
seTn_vec <- c(seTn_vec, abs(netTx[1L])*rse_netTx[1L])
characterNO <- paste("NO", i, sep="")
TxTn[[characterNO]] <- netTx/netTx[1L]
agID <- rbind(agID, c(NO[i], Position[i], Grain[i]))
if (signal.type=="LxTx") {
DataFrame1 <- data.frame(iNO, iSAR.Cycle, Dose, LxTx, seLxTx,
stringsAsFactors=FALSE)
} else if (signal.type=="Lx") {
DataFrame1 <- data.frame(iNO, iSAR.Cycle, Dose, netLx, abs(netLx)*rse_netLx,
stringsAsFactors=FALSE)
} else if (signal.type=="Tx") {
DataFrame1 <- data.frame(iNO, iSAR.Cycle, Dose, netTx, abs(netTx)*rse_netTx,
stringsAsFactors=FALSE)
}
SARdata <- rbind(SARdata, DataFrame1)
if (!is.null(outfile)) {
DataFrame2 <- data.frame(iNO, iPosition, iGrain,
iSAR.Cycle, Dose,
Init, seInit, BG, seBG, netLx, abs(netLx)*rse_netLx,
TInit, seTInit, TBG, seTBG, netTx, abs(netTx)*rse_netTx,
LxTx, seLxTx,
stringsAsFactors=FALSE)
ALLdata <- rbind(ALLdata, DataFrame2)
}
}
}
if (nrow(SARdata)==0L) stop("Error: no SAR data can be returned!")
LnTn.curve <- LnTn.curve[accept_characterNO]
if (!is.null(outfile)) {
rownames(ALLdata) <- NULL
colnames(ALLdata) <- c("NO","Position","Grain",
"SAR.Cycle","Dose",
"Init","seInit","BG","seBG","Lx","seLx",
"TInit","seTInit","TBG","seTBG","Tx","seTx",
"LxTx","seLxTx")
write.csv(ALLdata, file=paste(outfile, ".csv", sep=""))
}
rownames(SARdata) <- NULL
if (signal.type=="LxTx") {
colnames(SARdata) <- c("NO","SAR.Cycle","Dose","LxTx","seLxTx")
} else if (signal.type=="Lx") {
colnames(SARdata) <- c("NO","SAR.Cycle","Dose","Lx","seLx")
} else if (signal.type=="Tx") {
colnames(SARdata) <- c("NO","SAR.Cycle","Dose","Tx","seTx")
}
criteria <- cbind(Tn3BG_vec, TnBG.ratio_vec, seTnBG.ratio_vec, rseTn_vec, FR_vec, seFR_vec)
rownames(criteria) <- NULL
colnames(criteria) <- c("Tn3BG", "TnBG.ratio", "seTnBG.ratio", "rseTn", "FR", "seFR")
Tn <- cbind(Tn_vec, seTn_vec)
rownames(Tn) <- NULL
colnames(Tn) <- c("Tn", "seTn")
rownames(agID) <- NULL
colnames(agID) <- c("NO","Position","Grain")
output <- list("SARdata"=SARdata,
"criteria"=criteria,
"Tn"=Tn,
"LnTn.curve"=LnTn.curve,
"TxTn"=TxTn,
"agID"=agID)
class(output) <- "analyseBIN"
invisible(output)
}
|
meta.niceplot<-function(metadat,sumtype="taxa",level="main",p,p.adjust,phyla.col="rainbow",
phyla.select=c("actinobacteria","bacteroidetes","cyanobacteria","firmicutes","fusobacteria","proteobacteria","verrucomicrobia",".thermi."),
col.select=c("
est.break=c(-Inf, -1,-0.5,-0.1,0,0.1,0.5,1, Inf), est.break.label=c("<-1", "[-1,-0.5)","[-0.5,-0.1)","[-0.1,0)", "[0,0.1)", "[0.1,0.5)", "[0.5,1)", ">=1"),
neg.palette="PuBu", pos.palette="YlOrRd",
p.sig.heat="no",p.break=c(0,0.0001,0.05,1),p.break.label=c("**","*",""),
p.pool.break=c(0,0.05,1), p.pool.break.label=c("[0,0.05)","[0.05,1]"),
padjust.pool.break=c(0,0.1,1), padjust.pool.break.label=c("[0,0.1)","[0.1,1]"),
forest.est.shape=c("17","16"), forest.est.col=c("red", "black"),forest.col="by.pvalue",
leg.key.size=1,leg.text.size=8,heat.text.x.size=8,heat.text.x.angle=0,forest.axis.text.y=8,forest.axis.text.x=8,
heat.forest.width.ratio = c(1,1),point.ratio=c(3,1),line.ratio=c(2,1)){
test<-metadat$taxsig.all
test$taxa<-test$id
test$taxa<-gsub("k__bacteria.p__","",test$taxa)
test$esticat<-cut(test$estimate, breaks=est.break,
labels=est.break.label)
test$esticol<-plyr::mapvalues(test$esticat,from=est.break.label,
to=c(rev(RColorBrewer::brewer.pal(((length(est.break)-1)/2)+1, neg.palette)[-1]),RColorBrewer::brewer.pal(((length(est.break)-1)/2)+1, pos.palette)[-1]))
test$esticat<-gdata::drop.levels(test$esticat, reorder=FALSE)
test$esticol<-gdata::drop.levels(test$esticol, reorder=FALSE)
poplev<-levels(factor(test$pop))
test$pop[is.na(test$pop)]<-"Pooled"
test$pop<-factor(test$pop,levels=c(poplev[poplev!="Pooled"],"Pooled"))
if (sumtype=="taxa"){
if (level=="main"){
test<-test[order(test$taxa,decreasing = FALSE),]
test$taxas<-factor(test$taxa,levels=unique(test$taxa))
test$plotvar<-test$taxas
}
if (level=="sub"){
test$taxas<-sub(".c__.*f__", " ",as.character(test$taxa))
test<-test[order(test$taxa,decreasing = FALSE),]
test$taxas<-factor(test$taxas,levels=unique(test$taxas))
test$taxa<-factor(test$taxa,levels=unique(test$taxa))
test$plotvar<-test$taxas
}
}
if (sumtype=="path"){
test<-test[order(test$taxa,decreasing = FALSE),]
test$taxas<-factor(test$taxa,levels=unique(test$taxa))
test$plotvar<-test$taxas
}
test$study[is.na(test$study)]<-"Meta_analysis"
if (p.sig.heat=="yes"){
test$pdot<-cut(test$p, breaks=p.break,labels=p.break.label,include.lowest = TRUE)
}
if (p.sig.heat=="no"){
test$pdot<-""
}
nstudy<-length(unique(test$study[!is.na(test$study)]))
my.lines<-data.frame(x=(nstudy-0.5), y=0.5, xend=(nstudy-0.5), yend=(length(unique(test$taxa))+0.5))
h<-ggplot2::ggplot(test, ggplot2::aes(pop, plotvar)) +
ggplot2::geom_tile(ggplot2::aes(fill=esticat)) +
ggplot2::geom_text(ggplot2::aes(label = pdot)) +
ggplot2::scale_fill_manual(breaks=levels(test$esticat),
values = levels(test$esticol),
labels = levels(test$esticat),
name = "log(OR)")+
ggplot2::geom_segment(data=my.lines, ggplot2::aes(x,y,xend=xend, yend=yend), size=2, inherit.aes=F)+
ggplot2::ylab("") +ggplot2::xlab("")+
ggplot2::theme(legend.title = ggplot2::element_text(size = 12,face="bold"),
legend.text = ggplot2::element_text(size = leg.text.size,face="bold"),
plot.title = ggplot2::element_text(size=16),
axis.title=ggplot2::element_text(size=14,face="bold"),
legend.position="left",
plot.background = ggplot2::element_blank(),
panel.grid.minor = ggplot2::element_blank(),
panel.grid.major = ggplot2::element_blank(),
panel.background = ggplot2::element_blank(),
panel.border = ggplot2::element_blank(),
axis.ticks.y = ggplot2::element_blank(),
axis.text.y = ggplot2::element_blank(),
axis.title.x = ggplot2::element_blank(),
axis.title.y = ggplot2::element_blank(),
axis.text.x =ggplot2::element_text(size=heat.text.x.size, angle=heat.text.x.angle, hjust = 1,colour="black",face="bold"),
legend.key.size = ggplot2::unit(leg.key.size, "cm"))+
ggplot2::guides(fill=ggplot2::guide_legend(ncol=1))
testf<-metadat$taxsig
testf$taxa<-testf$id
testf$taxa<-gsub("k__bacteria.p__","",testf$taxa)
testf<-testf[testf$taxa %in% unique(test$taxa),]
testf$taxa<-gdata::drop.levels(testf$taxa, reorder=FALSE)
if (sumtype=="taxa"){
if (level=="main"){
testf$taxa2<-paste0(toupper(substr(as.character(testf$taxa), 1, 1)), substr(as.character(testf$taxa), 2, nchar(as.character(testf$taxa))))
testf<-testf[order(testf$taxa,decreasing = FALSE),]
testf$taxa2<-factor(testf$taxa2,unique(testf$taxa2))
testf$taxa<-factor(testf$taxa,unique(testf$taxa))
if (phyla.col=="select"){
testf$colp<-plyr::mapvalues(testf$taxa,from=phyla.select,
to=col.select)
testf$colp<-as.character(testf$colp)
}
if (phyla.col=="rainbow"){
testf$colp<-plyr::mapvalues(testf$taxa,from=levels(testf$taxa),to=grDevices::rainbow(nlevels(testf$taxa)))
testf$colp<-as.character(testf$colp)
}
testf$plotvar<-testf$taxa2
}
if (level=="sub"){
testf$taxas1<-sub(".c__.*f__", " ",as.character(testf$taxa))
testf$taxas2<-sub(".*f__", "",as.character(testf$taxa))
testf$taxas2<-paste0(toupper(substr(as.character(testf$taxas2), 1, 1)), substr(as.character(testf$taxas2), 2, nchar(as.character(testf$taxas2))))
oname<-as.character(testf$taxa[testf$taxas2 %in% c("",".g__")])
testf$taxas2[testf$taxas2 %in% c("",".g__")]<-paste0(toupper(substr(as.character(oname), 1, 1)), substr(as.character(oname), 2, nchar(as.character(oname))))
testf<-testf[order(testf$taxa,decreasing = FALSE),]
testf$taxas<-factor(testf$taxas2,levels=testf$taxas2)
testf$phylum<-sub(".c__.*", "",as.character(testf$taxa))
testf$phylum<-as.factor(testf$phylum)
if (phyla.col=="select"){
testf$colp<-plyr::mapvalues(testf$phylum,from=phyla.select,
to=col.select)
testf$colp<-as.character(testf$colp)
}
if (phyla.col=="rainbow"){
testf$colp<-plyr::mapvalues(testf$phylum,from=levels(testf$phylum),to=grDevices::rainbow(nlevels(testf$phylum)))
testf$colp<-as.character(testf$colp)
}
testf$plotvar<-testf$taxas
}
}
if (sumtype=="path"){
testf<-testf[order(testf$taxa,decreasing = FALSE),]
testf$taxas<-factor(testf$taxa,levels=testf$taxa)
testf$colp=1
testf$plotvar<-testf$taxas
}
testf$pcut<-testf[,p]
testf$p.adjustcut<-testf[,p.adjust]
testf$psig<-cut(testf$pcut, breaks=p.pool.break,labels=p.pool.break.label ,include.lowest = TRUE, right = FALSE)
testf$psigsize<-plyr::mapvalues(testf$psig,from=p.pool.break.label, to=point.ratio)
testf$psigsize2<-plyr::mapvalues(testf$psig,from=p.pool.break.label, to=line.ratio)
testf$psigcol<-plyr::mapvalues(testf$psig,from=p.pool.break.label,to=forest.est.col)
testf$psigcol<-gdata::drop.levels(testf$psigcol,reorder=FALSE)
testf$padjustsig<-cut(testf$p.adjustcut, breaks=padjust.pool.break,labels=padjust.pool.break.label,include.lowest = TRUE, right = FALSE)
testf$estimate<-as.numeric(as.character(testf$estimate))
testf$padjustsign<-plyr::mapvalues(testf$padjustsig,from=padjust.pool.break.label,to=forest.est.shape)
testf$padjustsize<-plyr::mapvalues(testf$padjustsig,from=padjust.pool.break.label,to=point.ratio)
testf$esticat<-cut(testf$estimate, breaks=est.break,
labels=est.break.label)
testf$esticol<-plyr::mapvalues(testf$esticat,from=est.break.label,
to=c(rev(RColorBrewer::brewer.pal(((length(est.break)-1)/2)+1, neg.palette)[-1]),RColorBrewer::brewer.pal(((length(est.break)-1)/2)+1, pos.palette)[-1]))
testf$esticat<-gdata::drop.levels(testf$esticat, reorder=FALSE)
testf$esticol<-gdata::drop.levels(testf$esticol, reorder=FALSE)
testf[,c("estimate","ll","ul")]<-apply(testf[,c("estimate","ll","ul")],2,function(x){x[x>=5]=5;x[x<=-5]=-5;x})
if (forest.col=="by.pvalue"){
f<-ggplot2::ggplot(data=testf,ggplot2::aes(x=estimate,y=plotvar,colour=psigcol))+
ggplot2::geom_point(shape=as.numeric(as.character(testf$padjustsign)),size=as.numeric(as.character(testf$padjustsize)))+
ggplot2::scale_y_discrete(position = "right")+
ggplot2::geom_errorbarh(ggplot2::aes(xmin=ll,xmax=ul,colour=psigcol),height=0.0,size=1)+
ggplot2::geom_vline(xintercept=0,linetype="dashed")+
ggplot2::scale_colour_manual(breaks=testf$psigcol,values = levels(testf$psigcol))+
ggplot2::theme(legend.position="none",
plot.background = ggplot2::element_blank(),
panel.background = ggplot2::element_blank(),
axis.ticks.y= ggplot2::element_blank(),
axis.title = ggplot2::element_blank(),
axis.text.y =ggplot2::element_text(size=forest.axis.text.y, colour = testf$colp,face="bold"),
axis.text.x =ggplot2::element_text(size=forest.axis.text.x,colour="black",face="bold"))
}
if (forest.col=="by.estimate"){
f<-ggplot2::ggplot(data=testf,ggplot2::aes(x=estimate,y=plotvar,colour=esticol))+
ggplot2::geom_point(shape=as.numeric(as.character(testf$padjustsign)),size=as.numeric(as.character(testf$psigsize)))+
ggplot2::scale_y_discrete(position = "right")+
ggplot2::geom_errorbarh(ggplot2::aes(xmin=ll,xmax=ul,colour=esticol),height=0.0, size=as.numeric(as.character(testf$psigsize2)))+
ggplot2::geom_vline(xintercept=0,linetype="dashed")+
ggplot2::scale_colour_manual(breaks=testf$esticol,values = levels(testf$esticol))+
ggplot2::theme(legend.position="none",
plot.background = ggplot2::element_blank(),
panel.background = ggplot2::element_blank(),
axis.ticks.y= ggplot2::element_blank(),
axis.title = ggplot2::element_blank(),
axis.text.y =ggplot2::element_text(size=forest.axis.text.y, colour = testf$colp,face="bold"),
axis.text.x =ggplot2::element_text(size=forest.axis.text.x,colour="black",face="bold"))
}
return(gridExtra::grid.arrange(h,f,nrow=1,widths = heat.forest.width.ratio))
}
|
NULL
forecastservice <- function(config = list()) {
svc <- .forecastservice$operations
svc <- set_config(svc, config)
return(svc)
}
.forecastservice <- list()
.forecastservice$operations <- list()
.forecastservice$metadata <- list(
service_name = "forecastservice",
endpoints = list("*" = list(endpoint = "forecast.{region}.amazonaws.com", global = FALSE), "cn-*" = list(endpoint = "forecast.{region}.amazonaws.com.cn", global = FALSE), "us-iso-*" = list(endpoint = "forecast.{region}.c2s.ic.gov", global = FALSE), "us-isob-*" = list(endpoint = "forecast.{region}.sc2s.sgov.gov", global = FALSE)),
service_id = "forecast",
api_version = "2018-06-26",
signing_name = "forecast",
json_version = "1.1",
target_prefix = "AmazonForecast"
)
.forecastservice$service <- function(config = list()) {
handlers <- new_handlers("jsonrpc", "v4")
new_service(.forecastservice$metadata, handlers, config)
}
|
context("checking that the length of AB-PSSM feature vectorS is equal to 400")
test_that("whether the AB-PSSM gives us the expected output",{
ss<-AB_PSSM(system.file("extdata","C7GRQ3.txt.pssm",package="PSSMCOOL"))
expect_equal(length(ss),400)
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.