code
stringlengths 1
13.8M
|
---|
tar_test("tar_make_clustermq() works", {
skip_on_os("windows")
skip_on_os("solaris")
skip_if_not_installed("clustermq")
skip_on_covr()
tar_script({
options(clustermq.scheduler = "multiprocess")
list(tar_target(x, "x"))
})
tar_make_clustermq(
callr_arguments = list(show = FALSE),
reporter = "silent"
)
expect_equal(tar_read(x), "x")
})
tar_test("tar_make_clustermq() can use tidyselect", {
skip_on_os("windows")
skip_on_os("solaris")
skip_if_not_installed("clustermq")
skip_on_covr()
tar_script({
options(clustermq.scheduler = "multiprocess")
list(
tar_target(y1, 1 + 1),
tar_target(y2, 1 + 1),
tar_target(z, y1 + y2)
)
})
suppressWarnings(
tar_make_clustermq(
names = starts_with("y"),
reporter = "silent",
callr_arguments = list(show = FALSE)
)
)
out <- sort(list.files(file.path("_targets", "objects")))
expect_equal(out, sort(c("y1", "y2")))
})
tar_test("custom script and store args", {
skip_on_cran()
skip_if_not_installed("clustermq")
skip_on_covr()
skip_on_os("windows")
expect_equal(tar_config_get("script"), path_script_default())
expect_equal(tar_config_get("store"), path_store_default())
old_option <- getOption("clustermq.scheduler")
on.exit(options(clustermq.scheduler = old_option))
tar_script({
tar_option_set(packages = character(0))
options(clustermq.scheduler = "multiprocess")
tar_target(x, TRUE)
}, script = "example/script.R")
tar_make_clustermq(
script = "example/script.R",
store = "example/store",
callr_arguments = list(show = FALSE),
reporter = "silent"
)
expect_false(file.exists("_targets.yaml"))
expect_equal(tar_config_get("script"), path_script_default())
expect_equal(tar_config_get("store"), path_store_default())
expect_false(file.exists(path_script_default()))
expect_false(file.exists(path_store_default()))
expect_true(file.exists("example/script.R"))
expect_true(file.exists("example/store"))
expect_true(file.exists("example/store/meta/meta"))
expect_true(file.exists("example/store/objects/x"))
expect_equal(readRDS("example/store/objects/x"), TRUE)
tar_config_set(script = "x")
expect_equal(tar_config_get("script"), "x")
expect_true(file.exists("_targets.yaml"))
})
tar_test("custom script and store args with callr function", {
skip_on_cran()
skip_if_not_installed("clustermq")
skip_on_covr()
skip_on_os("windows")
expect_equal(tar_config_get("script"), path_script_default())
expect_equal(tar_config_get("store"), path_store_default())
tar_script({
options(clustermq.scheduler = "multiprocess")
tar_target(x, TRUE)
}, script = "example/script.R")
tmp <- utils::capture.output(
suppressMessages(
tar_make_clustermq(
script = "example/script.R",
store = "example/store",
reporter = "silent"
)
)
)
expect_false(file.exists("_targets.yaml"))
expect_equal(tar_config_get("script"), path_script_default())
expect_equal(tar_config_get("store"), path_store_default())
expect_false(file.exists(path_script_default()))
expect_false(file.exists(path_store_default()))
expect_true(file.exists("example/script.R"))
expect_true(file.exists("example/store"))
expect_true(file.exists("example/store/meta/meta"))
expect_true(file.exists("example/store/objects/x"))
expect_equal(readRDS("example/store/objects/x"), TRUE)
tar_config_set(script = "x")
expect_equal(tar_config_get("script"), "x")
expect_true(file.exists("_targets.yaml"))
})
tar_test("bootstrap builder for shortcut", {
skip_on_cran()
skip_on_os("windows")
skip_if_not_installed("clustermq")
skip_on_covr()
tar_script({
options(clustermq.scheduler = "multiprocess")
list(
tar_target(w, 1L),
tar_target(x, w),
tar_target(y, 1L),
tar_target(z, x + y)
)
})
suppressWarnings(
tar_make_clustermq(callr_function = NULL)
)
expect_equal(tar_read(z), 2L)
tar_script({
options(clustermq.scheduler = "multiprocess")
list(
tar_target(w, 1L),
tar_target(x, w),
tar_target(y, 1L),
tar_target(z, x + y + 1L)
)
})
suppressWarnings(
tar_make_clustermq(names = "z", shortcut = TRUE, callr_function = NULL)
)
expect_equal(tar_read(z), 3L)
progress <- tar_progress()
expect_equal(nrow(progress), 1L)
expect_equal(progress$name, "z")
expect_equal(progress$progress, "built")
}) |
hero.prepared_starray = function(x, ...) {
lambda = exp(x$loglambda)
parts = lapply(seq_along(lambda), function(i) {
x$Q[[i]] %*% x$U[[i]] %*% diag(1/(1 + lambda[i]*x$s[[i]]))
})
coeffs = rh.seq(parts, x$Ytilde)
fitted = as.matrix(x$B[[1]] %*% Matrix::tcrossprod(coeffs, x$B[[2]]))
out = list(fitted = fitted, coefficients = coeffs, x = x$x)
class(out) = c("hero_starray", "hero")
return(out)
} |
rcbsubset <-
function(distance.structure, near.exact = NULL, fb.list = NULL,
treated.info = NULL, control.info = NULL, exclude.penalty = NULL,
penalty = 2, tol = 1e-3){
exclude.treated = TRUE
target.group <- NULL
k = 1
if(is.null(exclude.penalty)){
return(rcbalance::rcbalance(distance.structure, near.exact, fb.list,
treated.info, control.info, exclude.treated,
target.group, k, penalty, tol))
}
if(!(penalty > 1)){
stop("penalty argument must be greater than 1")
}
if(!is.null(near.exact)){
if(!(!is.null(treated.info) && !is.null(control.info))){
stop('treated.info and control.info must both be specified when near.exact is used')
}
if(ncol(treated.info) != ncol(control.info)){
stop('treated.info and control.info must have the same number of columns')
}
if(!all(colnames(treated.info) == colnames(control.info))){
stop('treated.info and control.info must have identical column names')
}
treated.control.info <- rbind(treated.info, control.info)
if(class(distance.structure) %in% c('matrix', 'InfinitySparseMatrix', 'BlockedInfinitySparseMatrix')){
if(nrow(treated.info) != nrow(distance.structure)){
stop('Dimensions of treated.info and distance.structure do not agree')
}
if(nrow(control.info) != ncol(distance.structure)){
stop('Dimensions of control.info and distance.structure do not agree')
}
}else{
if(nrow(treated.info) != length(distance.structure)){
stop('treated.info and distance.structure specify different numbers of treated units')
}
if(nrow(control.info) < max(laply(distance.structure, function(x) max(c(as.numeric(names(x)),0))))){
stop('Not all control units in distance.structure have information in control.info')
}
}
if(!(all(near.exact %in% colnames(treated.info)))){
stop('near.exact contains variable names not present in colnames(treated.info)')
}
}
if(!is.null(fb.list)){
if(is.null(target.group) && !is.null(near.exact)){
target.group <- treated.info
target.control.info <- treated.control.info
}else{
if(is.null(target.group)){
target.group <- treated.info
}
if(!(!is.null(treated.info) && !is.null(control.info))){
stop('treated.info and control.info must both be specified when fb.list is used')
}
if(ncol(treated.info) != ncol(control.info)){
stop('treated.info and control.info must have the same number of columns')
}
if(!all(colnames(treated.info) == colnames(control.info))){
stop('treated.info and control.info must have identical column names')
}
target.control.info <- rbind(target.group, control.info)
if(class(distance.structure) %in% c('matrix', 'InfinitySparseMatrix', 'BlockedInfinitySparseMatrix')){
if(nrow(target.group) != nrow(distance.structure)){
stop('target.group and distance.structure dimensions do not agree')
}
if(nrow(control.info) != ncol(distance.structure)){
stop('control.info and distance.structure dimensions do not agree')
}
}else{
if(nrow(target.group) != length(distance.structure)){
stop('target.group and distance.structure specify different numbers of treated units')
}
if(nrow(control.info) < max(laply(distance.structure, function(x) max(c(as.numeric(names(x)),0))))){
stop('Not all control units in distance.structure have information in control.info')
}
}
if(!all(unlist(fb.list) %in% colnames(target.group))){
stop('fb.list contains variable names not given in column names of other arguments')
}
if(length(fb.list) > 1){
for(i in c(1:(length(fb.list)-1))) if(!all(fb.list[[i]] %in% fb.list[[i+1]])){
stop('Elements of fb.list must contain all variables listed in previous elements')
}
}
}
}
if (inherits(distance.structure, c('matrix', 'InfinitySparseMatrix'))) {
match.network <- dist2net.matrix(distance.structure,k,
exclude.treated = exclude.treated,
exclude.penalty, tol)
} else if (!is.null(fb.list)){
match.network <- dist2net(distance.structure,k, exclude.treated = exclude.treated, exclude.penalty, ncontrol = nrow(control.info), tol)
}else{
match.network <- dist2net(distance.structure,k, exclude.treated = exclude.treated, exclude.penalty)
}
if(!is.null(fb.list)){
for(my.layer in fb.list){
interact.factor <- apply(target.control.info[,match(my.layer, colnames(target.control.info)), drop = FALSE],1, function(x) paste(x, collapse ='.'))
match.network <- add.layer(match.network, interact.factor)
}
}
if(!is.null(near.exact)){
interact.factor <- apply(treated.control.info[,match(near.exact, colnames(treated.control.info)), drop = FALSE],1, function(x) paste(x, collapse ='.'))
match.network <- penalize.near.exact(match.network, interact.factor)
}
cost <- match.network$cost
if(any(cost != round(cost))){
intcost <- round(cost/tol)
searchtol <- 10^(-c(1:floor(log10(.Machine$integer.max))))
searchtol <- searchtol[searchtol > tol]
for (newtol in searchtol){
new.intcost <- round(intcost*tol/newtol)
if (any(new.intcost != intcost*tol/newtol)) break
tol <- newtol
intcost <- new.intcost
}
cost <- intcost
}
if(any(is.na(as.integer(cost)))){
stop('Integer overflow in penalties! Run with a higher tolerance or fewer balance and near-exact constraints.')
}
match.network$cost <- cost
o <- callrelax(match.network)
if(o$feasible == 0 || o$crash == 1){
stub.message <- 'Match is infeasible or penalties are too large for RELAX to process! Consider raising tolerance or using fewer balance and near-exact constraints'
if(k > 1){
stop(paste(stub.message, 'or reducing k.'))
}
if(!exclude.treated){
stop('Match is infeasible or penalties are too large for RELAX to process! Try setting exclude.treated=TRUE, or raising tolerance or using fewer balance and near-exact constraints')
}
stop(paste(stub.message, '.', sep =''))
}
if('no.optmatch' %in% names(o)){
return(NULL)
}
x <- o$x[1:match.network$tcarcs]
if(all(x == 0)) warning('No matched pairs formed. Try using a higher exclusion penalty?')
match.df <- data.frame('treat' = as.factor(match.network$startn[1:match.network$tcarcs]), 'x' = x, 'control' = match.network$endn[1:match.network$tcarcs])
matched.or.not <- daply(match.df, .(match.df$treat), function(treat.edges) c(as.numeric(as.character(treat.edges$treat[1])), sum(treat.edges$x)), .drop_o = FALSE)
if(any(matched.or.not[,2] == 0)){
match.df <- match.df[-which(match.df$treat %in% matched.or.not[which(matched.or.not[,2] == 0),1]),]
}
match.df$treat <- as.factor(as.character(match.df$treat))
matches <- daply(match.df, .(match.df$treat), function(treat.edges) treat.edges$control[treat.edges$x == 1], .drop_o = FALSE)
if(is.null(fb.list)){
fb.tables <- NULL
}else{
matched.info <- rbind(treated.info[as.numeric(rownames(matches)),,drop = FALSE], control.info[as.vector(matches) - sum(match.network$z),,drop = FALSE])
treatment.status <- c(rep(1, nrow(as.matrix(matches))), rep(0, k*nrow(as.matrix(matches))))
interact.factors.matched = llply(fb.list, function(my.layer) as.factor(apply(matched.info[,match(my.layer, colnames(matched.info)), drop = FALSE],1, function(x) paste(x, collapse ='.'))))
fb.tables <- llply(interact.factors.matched, function(inter.fact) table('balance.variable' = inter.fact, treatment.status))
}
final.matches <- matrix(matches - sum(match.network$z), ncol =k, dimnames = list(rownames(matches),1:k))
final.matches <- final.matches[order(as.numeric(rownames(final.matches))), , drop=FALSE]
return(list('matches' = final.matches, 'fb.tables' = fb.tables))
} |
library(act)
mysearch <- act::search_new(x=examplecorpus, pattern= "yo", runSearch=FALSE)
df <- act::search_transcript_content(t=examplecorpus@transcripts[[3]],
s=mysearch)
nrow(df) |
string.help <- function(string, star = " ") {
str.len <- nchar(star)
str.loc <- NULL
for (i in 1:nchar(string)) {
if (substring(string,i,(i+str.len-1)) == star) {
str.loc <- c(str.loc, i)
}
}
no <- length(str.loc)+1
output <- rep(0,no)
if(no == 1)
output[1] <- string
else {
output[1] <- substring(string,1,(str.loc[1] - 1))
if (no > 2) {
for(i in 2:(no-1)) {
output[i] <- substring(string,(str.loc[i-1]+str.len), (str.loc[i]-1))
}
}
output[no] <- substring(string, (str.loc[no - 1] +str.len), nchar(string))
}
return(output)
} |
setMethod("contaminate",
signature(x = "data.frame", control = "ContControl"),
function(x, control, i = 1) {
epsilon <- getEpsilon(control)[i]
if(epsilon == 0 || nrow(x) == 0) {
x$.contaminated <- rep.int(FALSE, nrow(x))
return(x)
} else if(ncol(x) == 0) return(x)
target <- getTarget(control)
if(is.null(target)) target <- getNames(x)
grouping <- getGrouping(control)
if(length(grouping) > 1) {
stop("'grouping' must not specify more than one variable")
}
aux <- getAux(control)
if(length(aux) > 1) {
stop("'aux' must not specify more than one variable")
}
useGroup <- as.logical(length(grouping))
useAux <- as.logical(length(aux))
if(useGroup) {
groups <- x[, grouping]
if(useAux) {
Ntotal <- nrow(x)
split <- split(1:Ntotal, getFactor(groups))
N <- length(split)
} else {
uniqueGroups <- unique(groups)
N <- length(uniqueGroups)
}
} else N <- nrow(x)
n <- ceiling(epsilon * N)
if(useAux) {
aux <- x[, aux]
if(useGroup) {
aux <- sapply(split, function(i) mean(aux[i]))
}
ind <- ups(N, n, prob=aux)
} else ind <- srs(N, n)
if(useGroup) {
if(useAux) ind <- unlist(split[ind])
else ind <- which(groups %in% uniqueGroups[ind])
}
if(is(control, "DCARContControl")) {
values <- do.call(getDistribution(control), c(n, getDots(control)))
if(useGroup) {
rep <- unsplit(1:n, getFactor(groups[ind]))
values <- if(is.null(dim(values))) values[rep] else values[rep,]
}
} else if(is(control, "DARContControl")) {
dots <- c(list(x[ind, target]), getDots(control))
values <- do.call(getFun(control), dots)
} else {
stop("for user defined contamination control classes, a ",
"method 'contaminate(x, control, i)' needs to be defined")
}
values <- as.data.frame(values)
x[ind, target] <- values
if(is.null(x$.contaminated)) {
contaminated <- logical(nrow(x))
contaminated[ind] <- TRUE
x$.contaminated <- contaminated
} else x[ind, ".contaminated"] <- TRUE
x
})
setMethod("contaminate",
signature(x = "data.frame", control = "character"),
function(x, control, ...) {
if(length(control) != 1) {
stop("'control' must specify exactly one ",
"class extending \"VirtualContControl\"")
}
if(!extends(control, "VirtualContControl")) {
stop(gettextf("\"%s\" does not extend \"VirtualContControl\"",
control))
}
contaminate(x, new(control, ...))
})
setMethod("contaminate",
signature(x = "data.frame", control = "missing"),
function(x, control, ...) {
contaminate(x, DCARContControl(...))
}) |
NULL
meanWt <- function(x, ...) UseMethod("meanWt")
meanWt.default <- function(x, weights, na.rm=TRUE, ...) {
na.rm <- isTRUE(na.rm)
if(missing(weights)) mean(x, na.rm=na.rm)
else weighted.mean(x, w=weights, na.rm=na.rm)
}
meanWt.dataObj <- function(x, vars, na.rm=TRUE, ...) {
dat <- x@data
if ( is.null(dat) ) {
return(NULL)
} else {
if ( length(vars) > 1 ) {
stop("only one variable can be specified!\n")
}
ii <- match(vars, colnames(dat))
if ( any(is.na(ii)) ) {
stop("please provide valid variables that exist in the input object!\n")
}
tmpdat <- dat[[vars]]
if ( !is.null(x@weight) ) {
return(meanWt.default(tmpdat, weights=dat[[x@weight]], na.rm=na.rm))
} else {
return(meanWt.default(tmpdat, na.rm=na.rm))
}
}
}
varWt <- function(x, ...) UseMethod("varWt")
varWt.default <- function(x, weights, na.rm=TRUE, ...) {
na.rm <- isTRUE(na.rm)
if(missing(weights)) var(x, na.rm=na.rm)
else {
x <- as.numeric(x)
weights <- as.numeric(weights)
if(length(weights) != length(x)) {
stop("'weights' must have the same length as 'x'")
}
if(na.rm) {
select <- !is.na(x)
x <- x[select]
weights <- weights[select]
}
if(length(x) <= 1 || sum(weights > 0) <= 1) NA
else sum((x - meanWt(x, weights))^2 * weights) / (sum(weights) - 1)
}
}
varWt.dataObj <- function(x, vars, na.rm=TRUE, ...) {
dat <- x@data
if ( is.null(dat) ) {
return(NULL)
} else {
if ( length(vars) > 1 ) {
stop("only one variable can be specified!\n")
}
ii <- match(vars, colnames(dat))
if ( any(is.na(ii)) ) {
stop("please provide valid variables that exist in the input object!\n")
}
tmpdat <- dat[[vars]]
if ( !is.null(x@weight) ) {
return(varWt.default(tmpdat, weights=dat[[x@weight]], na.rm=na.rm))
} else {
return(varWt.default(tmpdat, na.rm=na.rm))
}
}
}
covWt <- function(x, ...) UseMethod("covWt")
covWt.default <- function(x, y, weights, ...) {
if(missing(y)) y <- x
else if(length(x) != length(y)) {
stop("'x' and 'y' must have the same length")
}
if(missing(weights)) cov(x, y, use = "complete.obs")
else {
if(length(weights) != length(x)) {
stop("'weights' must have the same length as 'x' and 'y'")
}
select <- !is.na(x) & !is.na(y)
x <- x[select]
y <- y[select]
weights <- weights[select]
sum((x-meanWt(x, weights)) * (y-meanWt(y, weights)) * weights) /
(sum(weights)-1)
}
}
covWt.matrix <- function(x, weights, ...) {
if(missing(weights)) cov(x, use = "pairwise.complete.obs")
else {
if(length(weights) != nrow(x)) {
stop("length of 'weights' must equal the number of rows in 'x'")
}
center <- apply(x, 2, meanWt, weights=weights)
x <- sweep(x, 2, center, check.margin = FALSE)
crossprodWt(x, weights)
}
}
covWt.data.frame <- function(x, weights, ...) covWt(as.matrix(x), weights)
covWt.dataObj <- function(x, vars, ...) {
dat <- x@data
if ( is.null(dat) ) {
return(NULL)
} else {
ii <- match(vars, colnames(dat))
if ( any(is.na(ii)) ) {
stop("please provide valid variables that exist in the input object!\n")
}
tmpdat <- dat[,vars,with=F]
if ( !is.null(x@weight) ) {
return(covWt.matrix(as.matrix(tmpdat), weights=dat[[x@weight]]))
} else {
return(covWt.matrix(as.matrix(tmpdat)))
}
}
}
corWt <- function(x, ...) UseMethod("corWt")
corWt.default <- function(x, y, weights, ...) {
if(missing(y)) y <- x
else if(length(x) != length(y)) {
stop("'x' and 'y' must have the same length")
}
if(missing(weights)) cor(x, y, use = "complete.obs")
else covWt(x, y, weights) / sqrt(varWt(x, weights) * varWt(y, weights))
}
corWt.matrix <- function(x, weights, ...) {
if(missing(weights)) cor(x, use = "pairwise.complete.obs")
else {
if(length(weights) != nrow(x)) {
stop("length of 'weights' must equal the number of rows in 'x'")
}
cen <- apply(x, 2, meanWt, weights=weights)
sc <- sqrt(apply(x, 2, varWt, weights=weights))
x <- scale(x, center=cen, scale=sc)
crossprodWt(x, weights)
}
}
corWt.data.frame <- function(x, weights, ...) corWt(as.matrix(x), weights)
corWt.dataObj <- function(x, vars, ...) {
dat <- x@data
if ( is.null(dat) ) {
return(NULL)
} else {
ii <- match(vars, colnames(dat))
if ( any(is.na(ii)) ) {
stop("please provide valid variables that exist in the input object!\n")
}
tmpdat <- dat[,vars,with=F]
if ( !is.null(x@weight) ) {
return(corWt.matrix(as.matrix(tmpdat), weights=dat[[x@weight]]))
} else {
return(corWt.matrix(as.matrix(tmpdat)))
}
}
}
crossprodWt <- function(x, weights) {
ci <- 1:ncol(x)
sapply(ci, function(j) sapply(ci, function(i) {
select <- !is.na(x[, i]) & !is.na(x[, j])
xi <- x[select, i]
xj <- x[select, j]
w <- weights[select]
sum(xi*xj*w) / (sum(w)-1)
}))
} |
glossaryCaPO4Ui <- function(id) {
ns <- NS(id)
shinydashboardPlus::box(
id = ns("boxGlossary"),
solidHeader = TRUE,
width = 12,
height = "50%",
style = "overflow-x: scroll;",
DT::dataTableOutput(ns("glossary"))
)
}
glossaryCaPO4 <- function(input, output, session) {
glossary <- data.frame(
"abreviation" = c("Ca", "Pi", "PTH", "D3", "FGF23",
"PTHg", "CaSR", "VDR", "PHP1"),
"full name" = c(
"Ionized plasma calcium concentration",
"Total plasma phosphate concentration",
"Parathyroid hormone",
"1,25 dihydroxy vitamin D3 (calcitriol)",
"Fibroblast growth factor 23",
"Parathyroid glands",
"Calcium sensing receptor",
"Vitamin D receptor",
"Primary hyperparathyroidism"),
"units" = c("mM (mmol/l)", "mM", "ng/l", rep("", 6))
)
glossary <- DT::datatable(
glossary,
escape = c(rep(FALSE, 3), TRUE),
options = list(dom = 't')
) %>%
DT::formatStyle(
'full.name',
color = 'black',
backgroundColor = 'orange',
fontWeight = 'bold'
)
output$glossary <- DT::renderDataTable(glossary)
} |
plot.hhsmmdata <- function (x, ...)
{
opar <- par(mfrow=c(1,1),no.readonly = TRUE)
N = x$N
Ns = c(0,cumsum(N))
xx = as.matrix(x$x)
d = ncol(xx)
if(anyNA(xx) | any(is.nan(xx))){
allmiss = which(apply(xx,1,function(t) all(is.na(t)|is.nan(t))))
notallmiss = which(!apply(xx,1,function(t) all(is.na(t)|is.nan(t))))
for(ii in allmiss){
neigh = notallmiss[order(abs(ii-notallmiss))[1:2]]
xx[ii,] = (xx[neigh[1],]+xx[neigh[2],])/2
}
if(ncol(xx)>1) xx = complete(mice(xx,printFlag=FALSE))
}
for(j in 1:d){
for(i in 1:length(N)){
if(d * length(N) <= 9){
q1 = trunc(sqrt(d * length(N)))
tmp = d * length(N) / q1
q2 = trunc(tmp)
if(tmp > q2) q2 = q2 + 1
if(i ==1 & j==1){
dev.new(width = 70*q2, height = 35*q1, unit = "px")
par(mfrow = c(q1,q2))
on.exit(par(opar))
}
} else{
dev.new(width=10, height=5, unit="in")
}
xxx = xx[(Ns[i]+1):Ns[i+1],j]
sc = 1
if(!is.null(x$s)) sc = 1.2
plot(ts(xxx), xlab = "Time",
ylab = "Observations",
main = paste("Sequence ", i," variable ",j),
ylim = c(min(xxx)/sc , max(xxx)), ...)
if (!is.null(x$s))
.add.states(x$s[(Ns[i]+1):Ns[i+1]], ht = axTicks(2)[1], time.scale = 1)
}
}
} |
`qq_plot` <- function(model, ...) {
UseMethod("qq_plot")
}
`qq_plot.default` <- function(model, ...) {
stop("Unable to produce a Q-Q plot for <",
class(model)[[1L]], ">",
call. = FALSE)
}
`qq_plot.gam` <- function(model,
method = c("uniform", "simulate", "normal", "direct"),
type = c("deviance", "response", "pearson"),
n_uniform = 10, n_simulate = 50,
level = 0.9,
ylab = NULL, xlab = NULL,
title = NULL, subtitle = NULL, caption = NULL,
ci_col = "black",
ci_alpha = 0.2,
point_col = "black",
point_alpha = 1,
line_col = "red", ...) {
method <- match.arg(method)
if (identical(method, "direct")) {
message("`method = \"direct\"` is deprecated, use `\"uniform\"`")
method <- "uniform"
}
if (identical(method, "uniform") &&
is.null(fix.family.qf(family(model))[["qf"]])) {
method <- "simulate"
}
if (identical(method, "simulate") &&
is.null(fix.family.rd(family(model))[["rd"]])) {
method <- "normal"
}
if (level <= 0 || level >= 1) {
stop("Level must be 0 < level < 1. Supplied level <", level, ">",
call. = FALSE)
}
type <- match.arg(type)
df <- switch(method,
uniform = qq_uniform(model, n = n_uniform, type = type),
simulate = qq_simulate(model, n = n_simulate, type = type,
level = level),
normal = qq_normal(model, type = type, level = level))
df <- as_tibble(df)
if (is.null(ylab)) {
ylab <- paste(toTitleCase(type), "residuals")
}
if (is.null(xlab)) {
xlab <- "Theoretical quantiles"
}
if (is.null(title)) {
title <- "QQ plot of residuals"
}
if (is.null(subtitle)) {
subtitle <- paste("Method:", method)
}
plt <- ggplot(df, aes_string(x = "theoretical", y = "residuals"))
qq_intercept <- 0
qq_slope <- 1
if (method == "normal") {
qq_intercept <- median(df[["residuals"]])
qq_slope <- IQR(df[["residuals"]]) / 1.349
}
plt <- plt + geom_abline(slope = qq_slope, intercept = qq_intercept,
col = line_col)
if (isTRUE(method %in% c("simulate", "normal"))) {
plt <- plt + geom_ribbon(aes_string(ymin = "lower", ymax = "upper",
x = "theoretical"),
inherit.aes = FALSE,
alpha = ci_alpha, fill = ci_col)
}
plt <- plt + geom_point(colour = point_col, alpha = point_alpha)
plt <- plt + labs(title = title, subtitle = subtitle, caption = caption,
y = ylab, x = xlab)
plt
}
`qq_plot.glm` <- function(model, ...) {
if (is.null(model[["sig2"]])) {
model[["sig2"]] <- summary(model)$dispersion
}
qq_plot.gam(model, ...)
}
`qq_plot.lm` <- function(model, ...) {
r <- residuals(model)
r.df <- df.residual(model)
model[["sig2"]] <- sum((r- mean(r))^2) / r.df
if (is.null(weights(model))) {
model$prior.weights <- rep(1, nrow(model.frame(model)))
}
if (is.null(model[["linear.predictors"]])) {
model[["linear.predictors"]] <- model[["fitted.values"]]
}
qq_plot.gam(model, ...)
}
`qq_simulate` <- function(model, n = 50, type = c("deviance","response","pearson"),
level = 0.9, detrend = FALSE) {
type <- match.arg(type)
family <- family(model)
family <- fix.family.rd(family)
rd_fun <- family[["rd"]]
alpha <- (1 - level) / 2
if (is.null(rd_fun)) {
stop("Random deviate function for family <", family[["family"]],
"> not available.")
}
dev_resid_fun <- family[["dev.resids"]]
if (is.null(dev_resid_fun)) {
dev_resid_fun <- family$residuals
if (is.null(dev_resid_fun)) {
stop("Deviance residual function for family <", family[["family"]],
"> not available.")
}
}
var_fun <- family[["variance"]]
fit <- fitted(model)
prior_w <- weights(model, type = "prior")
sigma2 <- model[["sig2"]]
na_action <- na.action(model)
sims <- replicate(n = n,
qq_simulate_data(rd_fun, fit = fit, weights = prior_w,
sigma2 = sigma2, dev_resid_fun = dev_resid_fun,
var_fun = var_fun, type = type,
na_action = na_action))
n_obs <- NROW(fit)
out <- quantile(sims, probs = (seq_len(n_obs) - 0.5) / n_obs)
int <- apply(sims, 1L, quantile, probs = c(alpha, 1 - alpha))
r <- sort(residuals(model, type = type))
if (isTRUE(detrend)) {
r <- r - out
int[1L, ] <- int[1L, ] - out
int[2L, ] <- int[2L, ] - out
}
out <- tibble(theoretical = out,
residuals = r,
lower = int[1L, ],
upper = int[2L, ])
out
}
`qq_simulate_data` <- function(rd_fun, fit, weights, sigma2, dev_resid_fun,
var_fun, type, na_action) {
ysim <- rd_fun(fit, weights, sigma2)
r <- compute_residuals(ysim, fit = fit, weights = weights, type = type,
dev_resid_fun = dev_resid_fun, var_fun = var_fun,
na_action = na_action)
sort(r)
}
`qq_normal` <- function(model, type = c("deviance", "response", "pearson"),
level = 0.9, detrend = FALSE) {
se_zscore <- function(z) {
n <- length(z)
pnorm_z <- pnorm(z)
sqrt(pnorm_z * (1 - pnorm_z) / n) / dnorm(z)
}
type <- match.arg(type)
r <- residuals(model, type = type)
nr <- length(r)
ord <- order(order(r))
sd <- IQR(r) / 1.349
theoretical <- qnorm(ppoints(nr))
med <- median(r) + theoretical * sd
se <- sd * se_zscore(theoretical)
crit <- coverage_normal(level)
crit_se <- crit * se
r <- sort(r)
if (isTRUE(detrend)) {
r <- r - med
med <- med * 0
}
out <- tibble(theoretical = theoretical,
residuals = r,
lower = med - crit_se,
upper = med + crit_se)
out
}
`qq_uniform` <- function(model, n = 10, type = c("deviance","response","pearson"),
level = 0.9, detrend = FALSE) {
type <- match.arg(type)
family <- family(model)
family <- fix.family.qf(family)
dev_resid_fun <- family[["dev.resids"]]
var_fun <- family[["variance"]]
q_fun <- family[["qf"]]
if (is.null(q_fun)) {
stop("Quantile function for family <", family[["family"]], "> not available.")
}
r <- residuals(model, type = type)
fit <- fitted(model)
weights <- weights(model, type = "prior")
sigma2 <- model[["sig2"]]
na_action <- na.action(model)
nr <- length(r)
unif <- (seq_len(nr) - 0.5) / nr
sims <- matrix(0, ncol = n, nrow = nr)
for (i in seq_len(n)) {
unif <- sample(unif, nr)
sims[, i] <- qq_uniform_quantiles(unif, q_fun,
fit = fit,
weights = weights,
sigma2 = sigma2,
dev_resid_fun = dev_resid_fun,
var_fun = var_fun,
type = type,
na_action = na_action)
}
out <- rowMeans(sims)
r <- sort(r)
if (isTRUE(detrend)) {
r <- r - out
}
out <- tibble(theoretical = out,
residuals = r)
out
}
`qq_uniform_quantiles` <- function(qs, q_fun, fit, weights, sigma2, dev_resid_fun,
var_fun, type, na_action) {
qq <- q_fun(qs, fit, weights, sigma2)
r <- compute_residuals(qq, fit = fit, weights = weights, type = type,
dev_resid_fun = dev_resid_fun, var_fun = var_fun,
na_action = na_action)
sort(r)
}
`compute_residuals` <- function(y, fit, weights,
type = c("deviance","response","pearson"),
dev_resid_fun, var_fun, na_action) {
type <- match.arg(type)
r <- switch(type,
deviance = deviance_residuals(y, fit, weights, dev_resid_fun),
response = response_residuals(y, fit),
pearson = pearson_residuals(y, fit, weights, var_fun)
)
naresid(na_action, r)
}
`response_residuals` <- function(y, fit) {
y - fit
}
`deviance_residuals` <- function(y, fit, weights, dev_resid_fun) {
if ("object" %in% names(formals(dev_resid_fun))) {
r <- dev_resid_fun(list(y = y, fitted.values = fit,
prior.weights = weights),
type = "deviance")
} else {
r <- dev_resid_fun(y, fit, weights)
posneg <- attr(r, "sign")
if (is.null(posneg)) {
posneg <- sign(y - fit)
}
r <- sqrt(pmax(r, 0)) * posneg
}
r
}
`pearson_residuals` <- function(y, fit, weights, var_fun) {
if (is.null(var_fun)) {
stop("Pearson residuals are not available for this family.")
}
(y - fit) * sqrt(weights) / sqrt(var_fun(fit))
}
`residuals_linpred_plot` <- function(model,
type = c("deviance", "pearson","response"),
ylab = NULL, xlab = NULL, title = NULL,
subtitle = NULL, caption = NULL,
point_col = "black", point_alpha = 1,
line_col = "red") {
type <- match.arg(type)
r <- residuals(model, type = type)
eta <- model[["linear.predictors"]]
na_action <- na.action(model)
if (is.matrix(eta) && !is.matrix(r)) {
eta <- eta[, 1]
}
eta <- napredict(na_action, eta)
df <- data.frame(eta = eta, residuals = r)
plt <- ggplot(df, aes_string(x = "eta", y = "residuals")) +
geom_hline(yintercept = 0, col = line_col)
plt <- plt + geom_point(colour = point_col, alpha = point_alpha)
if (is.null(xlab)) {
xlab <- "Linear predictor"
}
if (is.null(ylab)) {
ylab <- paste(toTitleCase(type), "residuals")
}
if (missing(title)) {
title <- "Residuals vs linear predictor"
}
if (missing(subtitle)) {
subtitle <- paste("Family:", family(model)[["family"]])
}
plt <- plt + labs(x = xlab, y = ylab, title = title, subtitle = subtitle,
caption = caption)
plt
}
`observed_fitted_plot` <- function(model,
ylab = NULL, xlab = NULL, title = NULL,
subtitle = NULL, caption = NULL,
point_col = "black", point_alpha = 1) {
fit <- fitted(model)
if (NCOL(fit) > 1L) {
fit <- fit[, 1]
}
obs <- model[["y"]]
df <- data.frame(observed = obs, fitted = fit)
plt <- ggplot(df, aes_string(x = "fitted", y = "observed"))
plt <- plt + geom_point(colour = point_col, alpha = point_alpha)
if (is.null(xlab)) {
xlab <- "Fitted values"
}
if (is.null(ylab)) {
ylab <- "Response"
}
if (missing(title)) {
title <- "Observed vs fitted values"
}
if (missing(subtitle)) {
subtitle <- paste("Family:", family(model)[["family"]])
}
plt <- plt + labs(x = xlab, y = ylab, title = title, subtitle = subtitle,
caption = caption)
plt
}
`residuals_hist_plot` <- function(model,
type = c("deviance", "pearson", "response"),
n_bins = c("sturges", "scott", "fd"),
ylab = NULL, xlab = NULL, title = NULL,
subtitle = NULL, caption = NULL) {
type <- match.arg(type)
df <- data.frame(residuals = residuals(model, type = type))
if (is.character(n_bins)) {
n_bins <- match.arg(n_bins)
n_bins <- switch(n_bins,
sturges = nclass.Sturges(df[["residuals"]]),
scott = nclass.scott(df[["residuals"]]),
fd = nclass.FD(df[["residuals"]]))
n_bins <- n_bins + 2
}
if (!is.numeric(n_bins)) {
stop("'n_bins' should be a number or one of: ",
paste(dQuote(c("sturges", "scott", "fd")),
collapse = ", "))
}
plt <- ggplot(df, aes_string(x = "residuals"))
plt <- plt + geom_histogram(bins = n_bins, colour = "black", fill = "grey80")
if (is.null(xlab)) {
xlab <- paste(toTitleCase(type), "residuals")
}
if (is.null(ylab)) {
ylab <- "Frequency"
}
if (missing(title)) {
title <- "Histogram of residuals"
}
if (missing(subtitle)) {
subtitle <- paste("Family:", family(model)[["family"]])
}
plt <- plt + labs(x = xlab, y = ylab, title = title, subtitle = subtitle,
caption = caption)
plt
}
`appraise` <- function(model, ...) {
UseMethod("appraise")
}
`appraise.gam` <- function(model,
method = c("uniform", "simulate", "normal", "direct"),
n_uniform = 10, n_simulate = 50,
type = c("deviance", "pearson", "response"),
n_bins = c("sturges", "scott", "fd"),
ncol = NULL, nrow = NULL,
guides = "keep",
level = 0.9,
ci_col = "black", ci_alpha = 0.2,
point_col = "black", point_alpha = 1,
line_col = "red",
...) {
method <- match.arg(method)
if (identical(method, "direct")) {
message("`method = \"direct\"` is deprecated, use `\"uniform\"`")
method <- "uniform"
}
type <- match.arg(type)
if (is.character(n_bins)) {
n_bins <- match.arg(n_bins)
}
if (!is.character(n_bins) && !is.numeric(n_bins)) {
stop("'n_bins' should be a number or one of: ",
paste(dQuote(c("sturges", "scott", "fd")), collapse = ", "))
}
plt1 <- qq_plot(model, method = method, type = type, n_uniform = n_uniform,
n_simulate = n_simulate, level = level, ci_alpha = ci_alpha,
point_col = point_col, point_alpha = point_alpha,
line_col = line_col)
plt2 <- residuals_linpred_plot(model, type = type, point_col = point_col,
point_alpha = point_alpha,
line_col = line_col)
plt3 <- residuals_hist_plot(model, type = type, n_bins = n_bins,
subtitle = NULL)
plt4 <- observed_fitted_plot(model, subtitle = NULL, point_col = point_col,
point_alpha = point_alpha)
n_plots <- 4
if (is.null(ncol) && is.null(nrow)) {
ncol <- ceiling(sqrt(n_plots))
nrow <- ceiling(n_plots / ncol)
}
wrap_plots(plt1, plt2, plt3, plt4,
byrow = TRUE, ncol = ncol, nrow = nrow, guides = guides,
...)
}
`appraise.lm` <- function(model, ...) {
r <- residuals(model)
r.df <- df.residual(model)
model[["sig2"]] <- sum((r- mean(r))^2) / r.df
if (is.null(weights(model))) {
model$prior.weights <- rep(1, nrow(model.frame(model)))
}
if (is.null(model[["linear.predictors"]])) {
model[["linear.predictors"]] <- model[["fitted.values"]]
}
if (is.null(model[["y"]])) {
model[["y"]] <- model.response(model.frame(model))
}
appraise.gam(model, ...)
}
`worm_plot` <- function(model, ...) {
UseMethod("worm_plot")
}
`worm_plot.default` <- function(model, ...) {
stop("Unable to produce a worm plot for <",
class(model)[[1L]], ">",
call. = FALSE)
}
`worm_plot.gam` <- function(model,
method = c("uniform", "simulate", "normal", "direct"),
type = c("deviance", "response", "pearson"),
n_uniform = 10, n_simulate = 50,
level = 0.9,
ylab = NULL, xlab = NULL,
title = NULL, subtitle = NULL, caption = NULL,
ci_col = "black",
ci_alpha = 0.2,
point_col = "black",
point_alpha = 1,
line_col = "red", ...) {
method <- match.arg(method)
if (identical(method, "direct")) {
message("`method = \"direct\"` is deprecated, use `\"uniform\"`")
method <- "uniform"
}
if (identical(method, "uniform") &&
is.null(fix.family.qf(family(model))[["qf"]])) {
method <- "simulate"
}
if (identical(method, "simulate") &&
is.null(fix.family.rd(family(model))[["rd"]])) {
method <- "normal"
}
if (level <= 0 || level >= 1) {
stop("Level must be 0 < level < 1. Supplied level <", level, ">",
call. = FALSE)
}
type <- match.arg(type)
df <- switch(method,
uniform = qq_uniform(model, n = n_uniform, type = type,
level = level, detrend = TRUE),
simulate = qq_simulate(model, n = n_simulate, type = type,
level = level, detrend = TRUE),
normal = qq_normal(model, type = type, level = level,
detrend = TRUE))
df <- as_tibble(df)
if (is.null(ylab)) {
ylab <- paste(toTitleCase(type), "residuals (Deviation)")
}
if (is.null(xlab)) {
xlab <- "Theoretical quantiles"
}
if (is.null(title)) {
title <- "Worm plot of residuals"
}
if (is.null(subtitle)) {
subtitle <- paste("Method:", method)
}
plt <- ggplot(df, aes_string(x = "theoretical", y = "residuals"))
plt <- plt + geom_hline(yintercept = 0, col = line_col)
if (isTRUE(method %in% c("simulate", "normal"))) {
plt <- plt + geom_ribbon(aes_string(ymin = "lower", ymax = "upper",
x = "theoretical"),
inherit.aes = FALSE,
alpha = ci_alpha, fill = ci_col)
}
plt <- plt + geom_point(colour = point_col, alpha = point_alpha)
plt <- plt + labs(title = title, subtitle = subtitle, caption = caption,
y = ylab, x = xlab)
plt
}
`worm_plot.glm` <- function(model, ...) {
if (is.null(model[["sig2"]])) {
model[["sig2"]] <- summary(model)$dispersion
}
worm_plot.gam(model, ...)
}
`worm_plot.lm` <- function(model, ...) {
r <- residuals(model)
r.df <- df.residual(model)
model[["sig2"]] <- sum((r- mean(r))^2) / r.df
if (is.null(weights(model))) {
model$prior.weights <- rep(1, nrow(model.frame(model)))
}
if (is.null(model[["linear.predictors"]])) {
model[["linear.predictors"]] <- model[["fitted.values"]]
}
worm_plot.gam(model, ...)
}
`weights.lm` <- function(object, type = c("prior", "working"), ...) {
type <- match.arg(type)
wts <- if (type == "prior") {
object$prior.weights
} else {
object$weights
}
if (is.null(object$na.action)) {
wts
} else {
naresid(object$na.action, wts)
}
} |
NULL
Person <- R6::R6Class("Person",
public = list(
fitbit_daily = NULL,
fitbit_intraday = NULL,
util = NULL,
target_steps = NULL,
start_date = NA,
end_date = NA,
user_info = NULL,
groupings = NULL,
apple = NULL,
addl_data = NULL,
addl_data2 = NULL,
initialize = function(fitbit_user_email = NA, fitbit_user_pw = NA,
user_info = NA,
apple_data_file = NA,
target_steps = 10000,
addl_data = NA, addl_data2 = NA,
group_assignments = NA,
start_date = NA, end_date = NA) {
self$addl_data <- addl_data
self$addl_data2 <- addl_data2
if (is.na(start_date)) {
start_date = "1990-01-01"
}
if (is.na(end_date)) {
end_date = Sys.Date()
}
self$start_date <- as.Date(strptime(start_date, format="%Y-%m-%d"))
self$end_date <- as.Date(strptime(end_date, format="%Y-%m-%d"))
self$target_steps <- target_steps
self$user_info <- user_info
self$util <- private$create_util_data(self$start_date, self$end_date)
if (!is.na(apple_data_file)){
self$apple <- private$load_apple_data(apple_data_file)
}
if (!is.na(fitbit_user_email) && !is.na(fitbit_user_pw)){
self$fitbit_intraday <- private$get_fitbit_intraday(fitbit_user_email,
fitbit_user_pw)
self$fitbit_daily <- private$get_fitbit_daily(fitbit_user_email,
fitbit_user_pw)
}
else {
self$fitbit_intraday <- NA
self$fitbit_daily <- NA
}
self$groupings <- group_assignments
}),
private = list(
load_apple_data = function(apple_data_file) {
raw_df <- readr::read_csv(apple_data_file)
cleaned <- tibble::as_tibble(raw_df)
if(!is.null(cleaned$Finish)) {
cleaned$Finish <- NULL
}
if("Start" %in% names(cleaned)) {
cleaned <- dplyr::rename(cleaned, datetime = Start)
}
if("Steps (count)" %in% names(cleaned)) {
cleaned <- dplyr::rename(cleaned, steps = `Steps (count)`)
cleaned <- dplyr::mutate(cleaned,
steps = steps / 4)
}
if("Flights Climbed (count)" %in% names(cleaned)) {
cleaned <- dplyr::rename(cleaned, floors = `Flights Climbed (count)`)
cleaned <- dplyr::mutate(cleaned, floors = floors / 4)
}
if("Heart Rate (count/min)" %in% names(cleaned)) {
cleaned <- dplyr::rename(cleaned, bpm = `Heart Rate (count/min)`)
}
if("Distance (mi)" %in% names(cleaned)) {
cleaned <- dplyr::rename(cleaned, distance = `Distance (mi)`)
cleaned <- dplyr::mutate(cleaned,
distance = distance / 4,
distanceKm = distance * MI_TO_KM)
}
if("Respiratory Rate (count/min)" %in% names(cleaned)) {
cleaned <- dplyr::rename(cleaned,
resp_rate = `Respiratory Rate (count/min)`)
}
if("Active Calories (kcal)" %in% names(cleaned)) {
cleaned <- dplyr::rename(cleaned, active_cal = `Active Calories (kcal)`)
}
cleaned$datetime <- lubridate::dmy_hm(cleaned$datetime,
tz = Sys.timezone())
return(cleaned)
},
create_util_data = function(start_date, end_date) {
df <- tibble::data_frame(date = lubridate::ymd(as.Date(as.POSIXct(
seq(from = start_date, to = end_date, by = 1)))))
df$datetime <- lubridate::make_datetime(year = lubridate::year(df$date),
month = lubridate::month(df$date),
day = lubridate::day(df$date),
hour = 0L,
min = 0L,
sec = 0,
tz = Sys.timezone())
df$day_of_week <- lubridate::wday(df$date, label = TRUE)
weekend <- c('Sat', 'Sun')
df$day_type <- factor((df$day_of_week %in% weekend),
levels = c(FALSE, TRUE),
labels = c('weekday', 'weekend'))
df$month <- lubridate::month(df$date, label = TRUE)
return(tibble::as_data_frame(df))
},
get_fitbit_intraday = function(fitbit_user_email, fitbit_user_pw) {
cookie <- fitbitScraper::login(email = fitbit_user_email,
password = fitbit_user_pw)
start <- self$start_date
end <- self$end_date
char_start <- as.character(start)
char_end <- as.character(end)
intraday <- list()
intraday$isteps <- NULL
intraday$idist <- NULL
intraday$ifloors <- NULL
intraday$iactive_min <- NULL
intraday$ical_burn <- NULL
intraday$ihr <- NULL
for (indiv_date in format(seq.Date(from = as.Date(start),
to = as.Date(end), by = "day"),
format = "%Y-%m-%d")){
char_date <- as.character(indiv_date)
intraday$isteps <- rbind(intraday$isteps,
fitbitScraper::get_intraday_data(
cookie, what = "steps", date = char_date))
intraday$idist <- rbind(intraday$idist,
fitbitScraper::get_intraday_data(
cookie, what = "distance", date = char_date))
intraday$ifloors <- rbind(intraday$ifloors,
fitbitScraper::get_intraday_data(
cookie, what = "floors", date = char_date))
intraday$iactive_min <- rbind(intraday$iactive_min,
fitbitScraper::get_intraday_data(
cookie, what = "active-minutes",
date = char_date))
intraday$ical_burn <- rbind(intraday$ical_burn,
fitbitScraper::get_intraday_data(
cookie, what = "calories-burned",
date = char_date))
intraday$ihr <- rbind(intraday$ihr,
fitbitScraper::get_intraday_data(
cookie, what = "heart-rate", date = char_date))
}
intraday$weight <- fitbitScraper::get_weight_data(cookie,
start_date = char_start,
end_date = char_end)
joined <- tibble::as_data_frame(Reduce(function(x, y) merge(x, y,
all = TRUE,
by = "time"),
intraday)
)
joined <- dplyr::select(joined, -dateTime)
joined$datetime <- lubridate::ymd_hms(joined$time, tz = Sys.timezone())
joined$date <- lubridate::ymd(as.Date(as.POSIXct(joined$datetime,
Sys.timezone())))
joined$time <-
lubridate::make_datetime(year = "1970", month = "01",
day = "01",
hour = lubridate::hour(joined$datetime),
min = lubridate::minute(joined$datetime),
sec = lubridate::second(joined$datetime))
joined <- plyr::rename(joined,
replace = c("active-minutes" = "activeMin"))
joined <- dplyr::mutate(joined,
distanceKm = distance * MI_TO_KM,
weightKg = weight * MI_TO_KM)
joined$`calories-burned` <- NULL
joined <- dplyr::select(joined,
date,
time,
datetime,
steps, distance, distanceKm, floors, activeMin,
activityLevel, bpm, confidence, caloriesBurned,
defaultZone, customZone, weight, weightKg,
dplyr::everything())
return(joined)
},
get_fitbit_daily = function(fitbit_user_email, fitbit_user_pw) {
cookie <- fitbitScraper::login(email = fitbit_user_email,
password = fitbit_user_pw)
start <- self$start_date
end <- self$end_date
char_start <- as.character(start)
char_end <- as.character(end)
daily <- list()
daily$steps <- fitbitScraper::get_daily_data(cookie, what = "steps",
start_date = char_start,
end_date = char_end)
daily$distance <- fitbitScraper::get_daily_data(cookie,
what = "distance",
start_date = char_start,
end_date = char_end)
daily$floors <- fitbitScraper::get_daily_data(cookie, what = "floors",
start_date = char_start,
end_date = char_end)
daily$minsVery <- fitbitScraper::get_daily_data(cookie,
what = "minutesVery",
start_date = char_start,
end_date = char_end)
daily$cal_ratio <- fitbitScraper::get_daily_data(cookie,
what = "caloriesBurnedVsIntake",
start_date = char_start,
end_date = char_end)
daily$rest_hr <- fitbitScraper::get_daily_data(cookie,
what = "getRestingHeartRateData",
start_date = as.character(start),
end_date = as.character(end))
daily$sleep <- fitbitScraper::get_sleep_data(cookie,
start_date = char_start,
end_date = char_end)[[2]]
daily$sleep$time <- as.POSIXct(daily$sleep$date)
joined <- tibble::as_data_frame(Reduce(function(x, y) merge(x, y,
all = TRUE,
by = "time"),
daily))
joined$date <- lubridate::ymd(as.Date(as.POSIXct(joined$time,
tz = Sys.timezone())))
joined <- dplyr::select(joined, -time)
joined$datetime <-
lubridate::make_datetime(year = lubridate::year(joined$date),
month = lubridate::month(joined$date),
day = lubridate::day(joined$date),
hour = 0L,
min = 0L,
sec = 0,
tz = Sys.timezone())
joined <- dplyr::mutate(joined,
minRestlessAwake = joined$sleepDuration - joined$minAsleep,
sleepDurationHrs = sleepDuration / 60,
minAsleepHrs = minAsleep / 60,
restlessProp = (sleepDurationHrs - minAsleepHrs) /
sleepDurationHrs * 100,
distanceKm = distance * MI_TO_KM)
joined <- dplyr::select(joined,
date,
datetime,
dateInForJavascriptLocalFormatting,
steps, distance, distanceKm, floors,
minutesVery, caloriesBurned, caloriesIntake,
restingHeartRate,
startTime, endTime,
startDateTime, endDateTime,
sleepDuration, sleepDurationHrs,
minAsleep, minAsleepHrs,
minRestlessAwake,
awakeCount,
restlessCount,
awakeDuration,
restlessDuration,
restlessProp,
dplyr::starts_with("sleepQuality"),
dplyr::starts_with("sleepBucket"),
clusters,
breaks,
dplyr::everything())
return(joined)
}
)) |
REandar<-function(custo,nand){
resultado = custo/nand
return(data.frame(andar=1:nand,custo=resultado))
} |
data(sample_matrix)
sample.matrix <- sample_matrix
sample.xts <- as.xts(sample.matrix)
test.convert_matrix_to_xts <- function() {
checkIdentical(sample.xts,as.xts(sample.matrix))
}
test.convert_matrix_to_xts_j1 <- function() {
checkIdentical(sample.xts[,1],as.xts(sample.matrix)[,1])
}
test.convert_matrix_to_xts_i1 <- function() {
checkIdentical(sample.xts[1,],as.xts(sample.matrix)[1,])
}
test.convert_matrix_to_xts_i1j1 <- function() {
checkIdentical(sample.xts[1,1],as.xts(sample.matrix)[1,1])
}
test.matrix_reclass <- function() {
checkIdentical(sample.matrix,reclass(try.xts(sample.matrix)))
}
test.matrix_reclass_subset_reclass_j1 <- function() {
checkIdentical(sample.matrix[,1],reclass(try.xts(sample.matrix))[,1])
}
test.matrix_reclass_subset_as.xts_j1 <- function() {
checkIdentical(sample.matrix[,1,drop=FALSE],reclass(try.xts(sample.matrix)[,1]))
checkIdentical(sample.matrix[,1],reclass(try.xts(sample.matrix))[,1])
}
test.matrix_reclass_subset_matrix_j1 <- function() {
checkIdentical(sample.matrix[,1,drop=FALSE],reclass(try.xts(sample.matrix[,1,drop=FALSE])))
}
test.zero_width_xts_to_matrix <- function() {
x <- .xts(,1)
xm <- as.matrix(x)
zm <- as.matrix(as.zoo(x))
checkIdentical(xm, zm)
}
test.dimless_xts_to_matrix <- function() {
ix <- structure(1:3, tclass = c("POSIXct", "POSIXt"), tzone = "")
x <- structure(1:3, index = ix, class = c("xts", "zoo"))
m <- matrix(1:3, 3, 1, dimnames = list(format(.POSIXct(1:3)), "x"))
checkIdentical(as.matrix(x), m)
} |
mainNetFunction <-
function(counts, adjMat, nchips, plotPath = "", tfList = NULL){
message("Evaluating Mutual Estimate Methods")
miMLTime <- system.time(miML <- parMIEstimate(counts, method = "ML", unit = "nat", nchips = nchips, tfList = tfList))
print(paste("ML Estimate Time:", round(miMLTime["elapsed"], 2)))
miMMTime <- system.time(miMM <- parMIEstimate(counts, method = "MM", unit = "nat", nchips = nchips, tfList = tfList))
print(paste("MM Estimate Time:", round(miMMTime["elapsed"], 2)))
miBJTime <- system.time(miBJ <- parMIEstimate(counts, method = "Bayes", unit = "nat", nchips = nchips, priorHyperParam = "Jeffreys", tfList = tfList))
print(paste("BJ Estimate Time:", round(miBJTime["elapsed"], 2)))
miBBTime <- system.time(miBB <- parMIEstimate(counts, method = "Bayes", unit = "nat", nchips = nchips, priorHyperParam = "BLUnif", tfList = tfList))
print(paste("BB Estimate Time:", round(miBBTime["elapsed"], 2)))
miBPTime <- system.time(miBP <- parMIEstimate(counts, method = "Bayes", unit = "nat", nchips = nchips, priorHyperParam = "Perks", tfList = tfList))
print(paste("BP Estimate Time:", round(miBPTime["elapsed"], 2)))
miBMTime <- system.time(miBM <- parMIEstimate(counts, method = "Bayes", unit = "nat", nchips = nchips, priorHyperParam = "MiniMax", tfList = tfList))
print(paste("BM Estimate Time:", round(miBMTime["elapsed"], 2)))
miCSTime <- system.time(miCS <- parMIEstimate(counts, method = "CS", unit = "nat", nchips = nchips, tfList = tfList))
print(paste("CS Estimate Time:", round(miCSTime["elapsed"], 2)))
miSHTime <- system.time(miSH <- parMIEstimate(counts, method = "Shrink", unit = "nat", nchips = nchips, tfList = tfList))
print(paste("SH Estimate Time:", round(miSHTime["elapsed"], 2)))
miKDTime <- system.time(miKD <- parMIEstimate(counts, method = "KD", nchips = nchips, tfList = tfList))
print(paste("KD Estimate Time:", round(miKDTime["elapsed"], 2)))
miKNNTime <- system.time(miKNN <- parMIEstimate(counts, method = "KNN", unit = "nat", k = 3, nchips = nchips, tfList = tfList))
print(paste("KNN Estimate Time:", round(miKNNTime["elapsed"], 2)))
miEst <- list(miML = miML, miMM = miMM, miBJ = miBJ, miBB = miBB, miBP = miBP, miBM = miBM, miCS = miCS, miSH = miSH, miKD = miKD, miKNN = miKNN)
message("Calculating Performance Indexes")
valML <- performanceIndex(miML, adjMat)
valMM <- performanceIndex(miMM, adjMat)
valBJ <- performanceIndex(miBJ, adjMat)
valBB <- performanceIndex(miBB, adjMat)
valBP <- performanceIndex(miBP, adjMat)
valBM <- performanceIndex(miBM, adjMat)
valCS <- performanceIndex(miCS, adjMat)
valSH <- performanceIndex(miSH, adjMat)
valKD <- performanceIndex(miKD, adjMat)
valKNN <- performanceIndex(miKNN, adjMat)
valMet <- list(valML = valML, valMM = valMM, valBJ = valBJ, valBB = valBB, valBP = valBP, valBM = valBM, valCS = valCS, valSH = valSH, valKD = valKD, valKNN = valKNN)
message("Generating ROC and PR Curves")
png(paste(plotPath, "allROC.png", sep = ""), width = 855, height = 543)
ccol <- c("red", "blue", "green", "black", "gray", "yellow", "aquamarine3", "darkmagenta", "burlywood4", "orange")
plot(c(0, valML[, "FPR"], 1), c(0, valML[, "Recall"], 1), type = "l", col = ccol[1], xlab = "FP rate", ylab = "TP rate", main = "ROC Curve", xlim = 0:1, ylim = 0:1)
lines(c(0, valMM[, "FPR"], 1), c(0, valMM[, "Recall"], 1), type = "l", col = ccol[2])
lines(c(0, valBJ[, "FPR"], 1), c(0, valBJ[, "Recall"], 1), type = "l", col = ccol[3])
lines(c(0, valBB[, "FPR"], 1), c(0, valBB[, "Recall"], 1), type = "l", col = ccol[4])
lines(c(0, valBP[, "FPR"], 1), c(0, valBP[, "Recall"], 1), type = "l", col = ccol[5])
lines(c(0, valBM[, "FPR"], 1), c(0, valBM[, "Recall"], 1), type = "l", col = ccol[6])
lines(c(0, valCS[, "FPR"], 1), c(0, valCS[, "Recall"], 1), type = "l", col = ccol[7])
lines(c(0, valSH[, "FPR"], 1), c(0, valSH[, "Recall"], 1), type = "l", col = ccol[8])
lines(c(0, valKD[, "FPR"], 1), c(0, valKD[, "Recall"], 1), type = "l", col = ccol[9])
lines(c(0, valKNN[, "FPR"], 1), c(0, valKNN[, "Recall"], 1), type = "l", col = ccol[10])
lines(0:1, 0:1, col = "black")
legend("bottomright", inset = .05, legend = c("ML", "MM", "BJ", "BB", "BP", "BM", "CS", "SH", "KD", "KNN"), title = "MI Estimators:", fill = ccol)
dev.off()
png(paste(plotPath, "allPR.png", sep = ""), width = 855, height = 543)
ccol <- c("red", "blue", "green", "black", "gray", "yellow", "aquamarine3", "darkmagenta", "burlywood4", "orange")
plot(c(0, valML[, "Recall"]), c(0, valML[, "Precision"]), type = "l", col = ccol[1], xlab = "recall", ylab = "precision", main = "PR Curve", xlim = 0:1, ylim = 0:1)
lines(c(0, valMM[, "Recall"]), c(0, valMM[, "Precision"]), type = "l", col = ccol[2])
lines(c(0, valBJ[, "Recall"]), c(0, valBJ[, "Precision"]), type = "l", col = ccol[3])
lines(c(0, valBB[, "Recall"]), c(0, valBB[, "Precision"]), type = "l", col = ccol[4])
lines(c(0, valBP[, "Recall"]), c(0, valBP[, "Precision"]), type = "l", col = ccol[5])
lines(c(0, valBM[, "Recall"]), c(0, valBM[, "Precision"]), type = "l", col = ccol[6])
lines(c(0, valCS[, "Recall"]), c(0, valCS[, "Precision"]), type = "l", col = ccol[7])
lines(c(0, valSH[, "Recall"]), c(0, valSH[, "Precision"]), type = "l", col = ccol[8])
lines(c(0, valKD[, "Recall"]), c(0, valKD[, "Precision"]), type = "l", col = ccol[9])
lines(c(0, valKNN[, "Recall"]), c(0, valKNN[, "Precision"]), type = "l", col = ccol[10])
legend("topright", inset = .05, legend = c("ML", "MM", "BJ", "BB", "BP", "BM", "CS", "SH", "KD", "KNN"), title = "MI Estimators:", fill = ccol)
dev.off()
message("Creating Result Table")
resTable <- rbind(valML[which(valML$Fscore == max(valML$Fscore))[1], ],
valMM[which(valMM$Fscore == max(valMM$Fscore))[1], ],
valBJ[which(valBJ$Fscore == max(valBJ$Fscore))[1], ],
valBB[which(valBB$Fscore == max(valBB$Fscore))[1], ],
valBP[which(valBP$Fscore == max(valBP$Fscore))[1], ],
valBM[which(valBM$Fscore == max(valBM$Fscore))[1], ],
valCS[which(valCS$Fscore == max(valCS$Fscore))[1], ],
valSH[which(valSH$Fscore == max(valSH$Fscore))[1], ],
valKNN[which(valKD$Fscore == max(valKD$Fscore))[1], ],
valKNN[which(valKNN$Fscore == max(valKNN$Fscore))[1], ])
rownames(resTable) <- c("ML", "MM", "BJ", "BB", "BP", "BM", "CS", "SH", "KD", "KNN")
AUROC <- c(aucDisc(valML[, "FPR"], valML[, "Recall"]),
aucDisc(valMM[, "FPR"], valMM[, "Recall"]),
aucDisc(valBJ[, "FPR"], valBJ[, "Recall"]),
aucDisc(valBB[, "FPR"], valBB[, "Recall"]),
aucDisc(valBP[, "FPR"], valBP[, "Recall"]),
aucDisc(valBM[, "FPR"], valBM[, "Recall"]),
aucDisc(valCS[, "FPR"], valCS[, "Recall"]),
aucDisc(valSH[, "FPR"], valSH[, "Recall"]),
aucDisc(valKD[, "FPR"], valKD[, "Recall"]),
aucDisc(valKNN[, "FPR"], valKNN[, "Recall"]))
AUPR <- c(aucDisc(valML[, "Recall"], valML[, "Precision"]),
aucDisc(valMM[, "Recall"], valMM[, "Precision"]),
aucDisc(valBJ[, "Recall"], valBJ[, "Precision"]),
aucDisc(valBB[, "Recall"], valBB[, "Precision"]),
aucDisc(valBP[, "Recall"], valBP[, "Precision"]),
aucDisc(valBM[, "Recall"], valBM[, "Precision"]),
aucDisc(valCS[, "Recall"], valCS[, "Precision"]),
aucDisc(valSH[, "Recall"], valSH[, "Precision"]),
aucDisc(valKD[, "Recall"], valKD[, "Precision"]),
aucDisc(valKNN[, "Recall"], valKNN[, "Precision"]))
resTable <- cbind(resTable, AUROC, AUPR)
ans <- list(miEst = miEst, valMet = valMet, resTable = resTable)
return(ans)
} |
print.QmethodRes <- function(x, length=10, digits=2, ...) {
old.dig <- getOption("digits")
options(digits=digits)
nn <- c("Summary", "Original data", "Q-sort factor loadings", "Flagged Q-sorts", "Statement z-scores", "Statement factor scores", "Factor characteristics", "Distinguishing and consensus statements")
names(nn) <- c("brief", "dataset", "loa", "flagged", "zsc", "zsc_n", "f_char", "qdc")
ll <- length(x)
nl <- nn[1:ll]
dimsorts <- min(length, x$brief$nqsorts)
dimstats <- min(length, x$brief$nstat)
cat(x$brief$info, sep="\n")
cat("\n")
cat(nl[2], ":\n")
print(x$dataset[1:dimstats, 1:dimsorts])
if (dimstats < x$brief$nstat) cat(" (...) See item '...$dataset' for the full data.\n")
nxt <- c("loa", "flagged")
for (i in nxt) {
cat("\n")
cat(nl[i], ":\n")
print(x[[i]][1:dimsorts, ])
if (dimsorts < x$brief$nqsorts) cat(" (...) See item '...$", i, "' for the full data.\n", sep="")
}
cat("\n")
cat(nl["zsc"], ":\n")
print(round(x[["zsc"]][1:dimstats, ], digits=2))
if (dimstats < x$brief$nstat) cat(" (...) See item '...$", "zsc", "' for the full data.\n", sep="")
cat("\n")
cat(nl["zsc_n"], ":\n")
print(x[["zsc_n"]][1:dimstats, ])
if (dimstats < x$brief$nstat) cat(" (...) See item '...$", "zsc_n", "' for the full data.\n", sep="")
cat("\n", nl[7], ":\n", sep="")
fcl <- c(" General factor characteristics:", " Correlation between factor z-scores:", " Standard error of differences between factors:")
for (i in 1:length(x$f_char)) {
cat(fcl[[i]], "\n")
print(round(x$f_char[[i]], digits=2))
cat("\n")
}
if (ll == 8) {
cat(nl[8], ":\n")
print(x$qdc[1:dimstats, ])
if (dimstats < x$brief$nstat) cat(" (...) See item '...$qdc' for the full data.\n")
}
options(digits=old.dig)
invisible(x)
} |
neighbors.vertex <- function(vertex, Matrix, num.neig) {
dist <- dist.vect.matrix(t(vertex), Matrix)
index <- order(dist, decreasing = FALSE)
neighbors <- Matrix[index[1:num.neig], ]
return(list(neighbors = neighbors, order = index, distance = dist))
} |
timetaken = function(started.at)
{
if (!inherits(started.at,"proc_time")) stop("Use started.at=proc.time() not Sys.time() (POSIXt and slow)")
format = function(secs) {
if (secs > 60.0) {
secs = as.integer(secs)
sprintf("%02d:%02d:%02d", secs%/%3600L, (secs%/%60L)%%60L, secs%%60L)
} else {
sprintf(if (secs >= 10.0) "%.1fs" else "%.3fs", secs)
}
}
tt = proc.time()-started.at
paste0(format(tt[3L])," elapsed (", format(tt[1L]), " cpu)")
} |
get_advanced_match_stats <- function(match_url, stat_type, team_or_player) {
main_url <- "https://fbref.com"
get_each_match_statistic <- function(match_url) {
pb$tick()
match_page <- tryCatch(xml2::read_html(match_url), error = function(e) NA)
if(!is.na(match_page)) {
match_report <- .get_match_report_page(match_page = match_page)
league_url <- match_page %>%
rvest::html_nodes("
rvest::html_node("a") %>%
rvest::html_attr("href") %>% paste0(main_url, .)
all_tables <- match_page %>%
rvest::html_nodes(".table_container")
if(stat_type == "summary") {
stat_df <- all_tables[which(stringr::str_detect(all_tables %>% rvest::html_attr("id"), "summary$"))] %>%
rvest::html_nodes("table")
} else if(stat_type == "passing") {
stat_df <- all_tables[which(stringr::str_detect(all_tables %>% rvest::html_attr("id"), "passing$"))] %>%
rvest::html_nodes("table")
} else if(stat_type == "passing_types") {
stat_df <- all_tables[which(stringr::str_detect(all_tables %>% rvest::html_attr("id"), "passing_types"))] %>%
rvest::html_nodes("table")
} else if(stat_type == "defense") {
stat_df <- all_tables[which(stringr::str_detect(all_tables %>% rvest::html_attr("id"), "defense$"))] %>%
rvest::html_nodes("table")
} else if(stat_type == "possession") {
stat_df <- all_tables[which(stringr::str_detect(all_tables %>% rvest::html_attr("id"), "possession$"))] %>%
rvest::html_nodes("table")
} else if(stat_type == "misc") {
stat_df <- all_tables[which(stringr::str_detect(all_tables %>% rvest::html_attr("id"), "misc$"))] %>%
rvest::html_nodes("table")
} else if(stat_type == "keeper") {
stat_df <- all_tables[which(stringr::str_detect(all_tables %>% rvest::html_attr("id"), "keeper_stats"))] %>%
rvest::html_nodes("table")
}
if(length(stat_df) != 0) {
if(!stat_type %in% c("shots")) {
Team <- match_page %>%
rvest::html_nodes("div:nth-child(1) div strong a") %>%
rvest::html_text() %>% .[1]
home_stat <- stat_df[1] %>%
rvest::html_table() %>% data.frame() %>%
.clean_match_advanced_stats_data()
Home_Away <- "Home"
home_stat <- cbind(Team, Home_Away, home_stat)
Team <- match_page %>%
rvest::html_nodes("div:nth-child(1) div strong a") %>%
rvest::html_text() %>% .[2]
away_stat <- stat_df[2] %>%
rvest::html_table() %>% data.frame() %>%
.clean_match_advanced_stats_data()
Home_Away <- "Away"
away_stat <- cbind(Team, Home_Away, away_stat)
stat_df_output <- dplyr::bind_rows(home_stat, away_stat)
if(any(grepl("Nation", colnames(stat_df_output)))) {
if(!stat_type %in% c("keeper", "shots")) {
if(team_or_player == "team") {
stat_df_output <- stat_df_output %>%
dplyr::filter(stringr::str_detect(.data$Player, " Players")) %>%
dplyr::select(-.data$Player, -.data$Player_Num, -.data$Nation, -.data$Pos, -.data$Age)
} else {
stat_df_output <- stat_df_output %>%
dplyr::filter(!stringr::str_detect(.data$Player, " Players"))
}
}
} else {
if(!stat_type %in% c("keeper", "shots")) {
if(team_or_player == "team") {
stat_df_output <- stat_df_output %>%
dplyr::filter(stringr::str_detect(.data$Player, " Players")) %>%
dplyr::select(-.data$Player, -.data$Player_Num, -.data$Pos, -.data$Age)
} else {
stat_df_output <- stat_df_output %>%
dplyr::filter(!stringr::str_detect(.data$Player, " Players"))
}
}
}
stat_df_output <- cbind(match_report, stat_df_output)
} else if(stat_type == "shots") {
}
} else {
print(glue::glue("NOTE: Stat Type '{stat_type}' is not found for this match. Check {match_url} to see if it exists."))
stat_df_output <- data.frame()
}
} else {
print(glue::glue("Stats data not available for {match_url}"))
stat_df_output <- data.frame()
}
return(stat_df_output)
}
pb <- progress::progress_bar$new(total = length(match_url))
suppressWarnings(
final_df <- match_url %>%
purrr::map_df(get_each_match_statistic) )
seasons <- read.csv("https://raw.githubusercontent.com/JaseZiv/worldfootballR_data/master/raw-data/all_leages_and_cups/all_competitions.csv", stringsAsFactors = F)
seasons <- seasons %>%
dplyr::filter(.data$seasons_urls %in% final_df$League_URL) %>%
dplyr::select(League=.data$competition_name, Gender=.data$gender, Country=.data$country, Season=.data$seasons, League_URL=.data$seasons_urls)
final_df <- seasons %>%
dplyr::left_join(final_df, by = "League_URL") %>%
dplyr::select(-.data$League_URL) %>% dplyr::distinct(.keep_all = T)
return(final_df)
} |
print.orcutt <-
function (x, ...){
cat("Cochrane-orcutt estimation for first order autocorrelation \n \n")
cat("Call:\n")
print(x$call)
cat("\n number of interaction:" , x$number.interaction)
cat("\n rho" , round(x$rho,6))
cat("\n\nDurbin-Watson statistic \n(original): ", format(round(x$DW[1],5), nsmall=5),", p-value:", format(x$DW[2], scientific=TRUE, digits = 4))
cat("\n(transformed):", format(round(x$DW[3],5), nsmall=5),", p-value:", format(x$DW[4], scientific=TRUE, digits = 4))
cat("\n \n coefficients: \n" )
print(round(x$coefficients,6))
} |
pbgtest <- function (x, ...) {
UseMethod("pbgtest")
}
pbgtest.panelmodel <- function(x, order = NULL, type = c("Chisq", "F"), ...) {
model <- describe(x, "model")
effect <- describe(x, "effect")
theta <- x$ercomp$theta
demX <- model.matrix(x, model = model, effect = effect, theta = theta, cstcovar.rm = "all")
demy <- pmodel.response(model.frame(x), model = model, effect = effect, theta = theta)
Ti <- pdim(x)$Tint$Ti
if(is.null(order)) order <- min(Ti)
auxformula <- demy ~ demX - 1
lm.mod <- lm(auxformula)
bgtest <- bgtest(lm.mod, order = order, type = type, ...)
bgtest$method <- "Breusch-Godfrey/Wooldridge test for serial correlation in panel models"
bgtest$alternative <- "serial correlation in idiosyncratic errors"
bgtest$data.name <- data.name(x)
names(bgtest$statistic) <- if(length(bgtest$parameter) == 1) "chisq" else "F"
return(bgtest)
}
pbgtest.formula <- function(x, order = NULL, type = c("Chisq", "F"), data, model=c("pooling", "random", "within"), ...) {
cl <- match.call(expand.dots = TRUE)
if (names(cl)[3L] == "") names(cl)[3L] <- "data"
if (is.null(cl$model)) cl$model <- "pooling"
names(cl)[2L] <- "formula"
m <- match(plm.arg, names(cl), 0)
cl <- cl[c(1L, m)]
cl[[1L]] <- quote(plm)
plm.model <- eval(cl,parent.frame())
pbgtest(plm.model, order = order, type = type, data = data, ...)
}
pwtest <- function(x, ...){
UseMethod("pwtest")
}
pwtest.formula <- function(x, data, effect = c("individual", "time"), ...) {
effect <- match.arg(effect, choices = c("individual", "time"))
cl <- match.call(expand.dots = TRUE)
if (names(cl)[3] == "") names(cl)[3] <- "data"
if (is.null(cl$model)) cl$model <- "pooling"
if (cl$model != "pooling") stop("pwtest only relevant for pooling models")
names(cl)[2] <- "formula"
m <- match(plm.arg, names(cl), 0)
cl <- cl[c(1L, m)]
cl[[1L]] <- quote(plm)
plm.model <- eval(cl,parent.frame())
pwtest.panelmodel(plm.model, effect = effect, ...)
}
pwtest.panelmodel <- function(x, effect = c("individual", "time"), ...) {
if (describe(x, "model") != "pooling") stop("pwtest only relevant for pooling models")
effect <- match.arg(effect, choices = c("individual", "time"))
data <- model.frame(x)
xindex <- unclass(attr(data, "index"))
if (effect == "individual"){
index <- xindex[[1L]]
tindex <- xindex[[2L]]
}
else{
index <- xindex[[2L]]
tindex <- xindex[[1L]]
}
n <- length(unique(index))
X <- model.matrix(x)
k <- ncol(X)
nT <- nrow(X)
t <- max(tapply(X[ , 1L], index, length))
u <- x$residuals
tres <- vector("list", n)
unind <- unique(index)
for(i in 1:n) {
ut <- u[index == unind[i]]
tres[[i]] <- ut %o% ut
}
sum.uptri <- vapply(tres, function(x) sum(x[upper.tri(x, diag = FALSE)]), FUN.VALUE = 0.0, USE.NAMES = FALSE)
W <- sum(sum.uptri)
seW <- sqrt(as.numeric(crossprod(sum.uptri)))
Wstat <- W/seW
names(Wstat) <- "z"
pW <- 2*pnorm(abs(Wstat), lower.tail = FALSE)
RVAL <- list(statistic = Wstat,
parameter = NULL,
method = paste("Wooldridge's test for unobserved",
effect, "effects"),
alternative = "unobserved effect",
p.value = pW,
data.name = paste(deparse(substitute(formula))))
class(RVAL) <- "htest"
return(RVAL)
}
pwartest <- function(x, ...) {
UseMethod("pwartest")
}
pwartest.formula <- function(x, data, ...) {
cl <- match.call(expand.dots = TRUE)
if (is.null(cl$model)) cl$model <- "within"
if (cl$model != "within") stop("pwartest only relevant for within models")
if (names(cl)[3L] == "") names(cl)[3L] <- "data"
names(cl)[2L] <- "formula"
m <- match(plm.arg, names(cl), 0)
cl <- cl[c(1L, m)]
cl[[1L]] <- quote(plm)
plm.model <- eval(cl, parent.frame())
pwartest(plm.model, ...)
}
pwartest.panelmodel <- function(x, ...) {
if (describe(x, "model") != "within") stop("pwartest only relevant for within models")
FEres <- x$residuals
data <- model.frame(x)
attr(FEres, "data") <- NULL
N <- length(FEres)
FEres.1 <- c(NA, FEres[1:(N-1)])
xindex <- unclass(attr(data, "index"))
id <- xindex[[1L]]
time <- xindex[[2L]]
lagid <- as.numeric(id) - c(NA, as.numeric(id)[1:(N-1)])
FEres.1[lagid != 0] <- NA
data <- data.frame(id, time, FEres = unclass(FEres), FEres.1 = unclass(FEres.1))
names(data)[c(1L, 2L)] <- c("id", "time")
data <- na.omit(data)
auxmod <- plm(FEres ~ FEres.1, data = data, model = "pooling", index = c("id", "time"))
t. <- pdim(x)$nT$T
rho.H0 <- -1/(t.-1)
myH0 <- paste("FEres.1 = ", as.character(rho.H0), sep="")
myvcov <- function(x) vcovHC(x, method = "arellano", ...)
FEARstat <- ((coef(auxmod)["FEres.1"] - rho.H0)/sqrt(myvcov(auxmod)["FEres.1", "FEres.1"]))^2
names(FEARstat) <- "F"
df1 <- c("df1" = 1)
df2 <- c("df2" = df.residual(auxmod))
pFEARstat <- pf(FEARstat, df1 = df1, df2 = df2, lower.tail = FALSE)
RVAL <- list(statistic = FEARstat,
parameter = c(df1, df2),
p.value = pFEARstat,
method = "Wooldridge's test for serial correlation in FE panels",
alternative = "serial correlation",
data.name = paste(deparse(substitute(x))))
class(RVAL) <- "htest"
return(RVAL)
}
pbsytest <- function (x, ...) {
UseMethod("pbsytest")
}
pbsytest.formula <- function(x, data, ..., test = c("ar", "re", "j"), re.normal = if (test == "re") TRUE else NULL) {
if (length(test) == 1L) test <- tolower(test)
test <- match.arg(test)
cl <- match.call(expand.dots = TRUE)
if (is.null(cl$model)) cl$model <- "pooling"
if (cl$model != "pooling") stop("pbsytest only relevant for pooling models")
names(cl)[2L] <- "formula"
if (names(cl)[3L] == "") names(cl)[3L] <- "data"
m <- match(plm.arg, names(cl), 0)
cl <- cl[c(1, m)]
cl[[1L]] <- as.name("plm")
plm.model <- eval(cl, parent.frame())
pbsytest(plm.model, test = test, re.normal = re.normal, ...)
}
pbsytest.panelmodel <- function(x, test = c("ar", "re", "j"), re.normal = if (test == "re") TRUE else NULL, ...) {
test <- match.arg(test)
if (describe(x, "model") != "pooling") stop("pbsytest only relevant for pooling models")
if (test != "re" && !is.null(re.normal)) {
stop("argument 're.normal' only relevant for test = \"re\", set re.normal = NULL for other tests")}
poolres <- x$residuals
data <- model.frame(x)
index <- attr(data, "index")
iindex <- index[[1L]]
tindex <- index[[2L]]
oo <- order(iindex,tindex)
ind <- iindex[oo]
tind <- tindex[oo]
poolres <- poolres[oo]
pdim <- pdim(x)
n <- max(pdim$Tint$n)
T_i <- pdim$Tint$Ti
N_t <- pdim$Tint$nt
t <- max(T_i)
N_obs <- pdim$nT$N
S1 <- as.numeric(crossprod(tapply(poolres,ind,sum)))
S2 <- as.numeric(crossprod(poolres))
A <- 1 - S1/S2
unind <- unique(ind)
uu <- rep(NA, length(unind))
uu1 <- rep(NA, length(unind))
for(i in 1:length(unind)) {
u.t <- poolres[ind == unind[i]]
u.t.1 <- u.t[-length(u.t)]
u.t <- u.t[-1L]
uu[i] <- crossprod(u.t)
uu1[i] <- crossprod(u.t, u.t.1)
}
B <- sum(uu1)/sum(uu)
a <- as.numeric(crossprod(T_i))
switch(test,
"ar" = {
stat <- (B + (((N_obs - n)/(a - N_obs)) * A))^2 * (((a - N_obs)*N_obs^2) / ((N_obs - n)*(a - 3*N_obs + 2*n)))
df <- c(df = 1)
names(stat) <- "chisq"
pstat <- pchisq(stat, df = df, lower.tail = FALSE)
tname <- "Bera, Sosa-Escudero and Yoon locally robust test"
myH0_alt <- "AR(1) errors sub random effects"
},
"re" = {
if(re.normal) {
stat <- -sqrt( (N_obs^2) / (2*(a - 3*N_obs + 2*n))) * (A + 2*B)
names(stat) <- "z"
df <- NULL
pstat <- pnorm(stat, lower.tail = FALSE)
tname <- "Bera, Sosa-Escudero and Yoon locally robust test (one-sided)"
myH0_alt <- "random effects sub AR(1) errors"
} else {
stat <- ((N_obs^2) * (A + 2*B)^2) / (2*(a - 3*N_obs + 2*n))
names(stat) <- "chisq"
df <- c(df = 1)
pstat <- pchisq(stat, df = df, lower.tail = FALSE)
tname <- "Bera, Sosa-Escudero and Yoon locally robust test (two-sided)"
myH0_alt <- "random effects sub AR(1) errors"
}
},
"j" = {
stat <- N_obs^2 * ( ((A^2 + 4*A*B + 4*B^2) / (2*(a - 3*N_obs + 2*n))) + (B^2/(N_obs - n)))
df <- c(df = 2)
names(stat) <- "chisq"
pstat <- pchisq(stat, df = df, lower.tail = FALSE)
tname <- "Baltagi and Li AR-RE joint test"
myH0_alt <- "AR(1) errors or random effects"
}
)
dname <- paste(deparse(substitute(formula)))
balanced.type <- if(pdim$balanced) "balanced" else "unbalanced"
tname <- paste(tname, "-", balanced.type, "panel", collapse = " ")
RVAL <- list(statistic = stat,
parameter = df,
method = tname,
alternative = myH0_alt,
p.value = pstat,
data.name = dname)
class(RVAL) <- "htest"
return(RVAL)
}
pdwtest <- function (x, ...) {
UseMethod("pdwtest")
}
pdwtest.panelmodel <- function(x, ...) {
model <- describe(x, "model")
effect <- describe(x, "effect")
theta <- x$ercomp$theta
demX <- model.matrix(x, model = model, effect = effect, theta = theta, cstcovar.rm = "all")
demy <- pmodel.response(model.frame(x), model = model, effect = effect, theta = theta)
dots <- list(...)
order.by <- if(is.null(dots$order.by)) NULL else dots$order.by
alternative <- if(is.null(dots$alternative)) "greater" else dots$alternative
iterations <- if(is.null(dots$iterations)) 15 else dots$iterations
exact <- if(is.null(dots$exact)) NULL else dots$exact
tol <- if(is.null(dots$tol)) 1e-10 else dots$tol
demy <- remove_pseries_features(demy)
auxformula <- demy ~ demX - 1
lm.mod <- lm(auxformula)
ARtest <- dwtest(lm.mod, order.by = order.by,
alternative = alternative,
iterations = iterations, exact = exact, tol = tol)
ARtest$method <- "Durbin-Watson test for serial correlation in panel models"
ARtest$alternative <- "serial correlation in idiosyncratic errors"
ARtest$data.name <- data.name(x)
return(ARtest)
}
pdwtest.formula <- function(x, data, ...) {
cl <- match.call(expand.dots = TRUE)
if (is.null(cl$model)) cl$model <- "pooling"
names(cl)[2L] <- "formula"
if (names(cl)[3L] == "") names(cl)[3L] <- "data"
m <- match(plm.arg, names(cl), 0)
cl <- cl[c(1L, m)]
cl[[1L]] <- quote(plm)
plm.model <- eval(cl, parent.frame())
pdwtest(plm.model, ...)
}
pbnftest <- function (x, ...) {
UseMethod("pbnftest")
}
pbnftest.panelmodel <- function(x, test = c("bnf", "lbi"), ...) {
test <- match.arg(test)
model <- describe(x, "model")
if (model == "random") x <- update(x, model = "within")
consec <- all(is.pconsecutive(x))
balanced <- is.pbalanced(x)
if (!inherits(residuals(x), "pseries")) stop("pdwtest internal error: residuals are not of class \"pseries\"")
ind <- unclass(index(x))[[1L]]
obs1 <- !duplicated(ind)
obsn <- !duplicated(ind, fromLast = TRUE)
res_crossprod <- as.numeric(crossprod(residuals(x)))
res_diff <- diff(residuals(x), shift = "time")
d1.1 <- sum(res_diff^2, na.rm = T) / res_crossprod
d1.2_contrib <- as.logical(is.na(res_diff) - obs1)
d1.2 <- as.numeric(crossprod(residuals(x)[d1.2_contrib])) / res_crossprod
d1 <- d1.1 + d1.2
if (test == "bnf") {
stat <- d1
names(stat) <- "DW"
method <- "Bhargava/Franzini/Narendranathan Panel Durbin-Watson Test"
if (!consec || !balanced) method <- paste0("modified ", method)
}
if (test == "lbi") {
d2_contrib <- as.logical(is.na(lead(residuals(x), shift = "time")) - obsn)
d2 <- as.numeric(crossprod(residuals(x)[d2_contrib])) / res_crossprod
d3 <- as.numeric(crossprod(residuals(x)[obs1])) / res_crossprod
d4 <- as.numeric(crossprod(residuals(x)[obsn])) / res_crossprod
stat <- d1 + d2 + d3 + d4
names(stat) <- "LBI"
method <- "Baltagi/Wu LBI Test for Serial Correlation in Panel Models"
}
result <- list(statistic = stat,
method = method,
alternative = "serial correlation in idiosyncratic errors",
data.name = data.name(x))
class(result) <- "htest"
return(result)
}
pbnftest.formula <- function(x, data, test = c("bnf", "lbi"), model = c("pooling", "within", "random"), ...) {
test <- match.arg(test)
model <- match.arg(model)
cl <- match.call(expand.dots = TRUE)
if (is.null(model)) model <- "pooling"
names(cl)[2L] <- "formula"
if (names(cl)[3L] == "") names(cl)[3L] <- "data"
m <- match(plm.arg, names(cl), 0)
cl <- cl[c(1L, m)]
cl[[1L]] <- quote(plm)
plm.model <- eval(cl, parent.frame())
pbnftest(plm.model, test = test)
}
pbltest <- function (x, ...)
{
UseMethod("pbltest")
}
pbltest.formula <- function(x, data, alternative = c("twosided", "onesided"), index = NULL, ...) {
X <- model.matrix(x, data = data)
data <- data[which(row.names(data) %in% row.names(X)), ]
if (! inherits(data, "pdata.frame"))
data <- pdata.frame(data, index = index)
gindex <- dimnames(attr(data, "index"))[[2L]][1L]
rformula <- NULL
eval(parse(text = paste("rformula <- ~1|", gindex, sep = "")))
mymod <- lme(x, data = data, random = rformula, method = "ML")
nt. <- mymod$dims$N
n. <- as.numeric(mymod$dims$ngrps[1])
t. <- nt./n.
Jt <- matrix(1, ncol = t., nrow = t.)/t.
Et <- diag(1, t.) - Jt
G <- matrix(0, ncol = t., nrow = t.)
for(i in 2:t.) {
G[i-1, i] <- 1
G[i, i-1] <- 1
}
uhat <- residuals(mymod, level = 0)
uhat.i <- vector("list", n.)
for(i in 1:n.) {
uhat.i[[i]] <- uhat[t.*(i-1)+1:t.]
}
s2e <- rep(NA, n.)
s21 <- rep(NA, n.)
for(i in 1:n.) {
u.i <- uhat.i[[i]]
s2e[i] <- as.numeric(crossprod(u.i, Et) %*% u.i)
s21[i] <- as.numeric(crossprod(u.i, Jt) %*% u.i)
}
sigma2.e <- sum(s2e) / (n.*(t.-1))
sigma2.1 <- sum(s21) / n.
star1 <- (Jt/sigma2.1 + Et/sigma2.e) %*% G %*% (Jt/sigma2.1 + Et/sigma2.e)
star2 <- rep(NA, n.)
for(i in 1:n.) {
star2[i] <- as.numeric(crossprod(uhat.i[[i]], star1) %*% uhat.i[[i]])
}
star2 <- sum(star2)
Drho <- (n.*(t.-1)/t.) * (sigma2.1-sigma2.e)/sigma2.1 + sigma2.e/2 * star2
a <- (sigma2.e - sigma2.1)/(t.*sigma2.1)
j.rr <- n. * (2 * a^2 * (t.-1)^2 + 2*a*(2*t.-3) + (t.-1))
j.12 <- n.*(t.-1)*sigma2.e / sigma2.1^2
j.13 <- n.*(t.-1)/t. * sigma2.e * (1/sigma2.1^2 - 1/sigma2.e^2)
j.22 <- (n. * t.^2) / (2 * sigma2.1^2)
j.23 <- (n. * t.) / (2 * sigma2.1^2)
j.33 <- (n./2) * (1/sigma2.1^2 + (t.-1)/sigma2.e^2)
Jmat <- matrix(nrow = 3L, ncol = 3L)
Jmat[1L, ] <- c(j.rr, j.12, j.13)
Jmat[2L, ] <- c(j.12, j.22, j.23)
Jmat[3L, ] <- c(j.13, j.23, j.33)
J11 <- n.^2 * t.^2 * (t.-1) / (det(Jmat) * 4*sigma2.1^2 * sigma2.e^2)
switch(match.arg(alternative),
"onesided" = {
LMr.m <- Drho * sqrt(J11)
pval <- pnorm(LMr.m, lower.tail = FALSE)
names(LMr.m) <- "z"
method1 <- "one-sided"
method2 <- "H0: rho = 0, HA: rho > 0"
parameter <- NULL
},
"twosided" = {
LMr.m <- Drho^2 * J11
pval <- pchisq(LMr.m, df = 1, lower.tail = FALSE)
names(LMr.m) <- "chisq"
parameter <- c(df = 1)
method1 <- "two-sided"
method2 <- "H0: rho = 0, HA: rho != 0"
}
)
dname <- paste(deparse(substitute(x)))
method <- paste("Baltagi and Li", method1, "LM test")
alternative <- "AR(1)/MA(1) errors in RE panel model"
res <- list(statistic = LMr.m,
p.value = pval,
method = method,
alternative = alternative,
parameter = parameter,
data.name = dname)
class(res) <- "htest"
res
}
pbltest.plm <- function(x, alternative = c("twosided", "onesided"), ...) {
if (describe(x, "model") != "random") stop("Test is only for random effects models.")
pbltest.formula(formula(x$formula), data=cbind(index(x), x$model),
index=names(index(x)), alternative = alternative, ...)
}
pwfdtest <- function(x, ...) {
UseMethod("pwfdtest")
}
pwfdtest.formula <- function(x, data, ..., h0 = c("fd", "fe")) {
cl <- match.call(expand.dots = TRUE)
if (is.null(cl$model)) cl$model <- "fd"
names(cl)[2L] <- "formula"
if (names(cl)[3L] == "") names(cl)[3L] <- "data"
m <- match(plm.arg, names(cl), 0)
cl <- cl[c(1L, m)]
cl[[1L]] <- quote(plm)
plm.model <- eval(cl, parent.frame())
pwfdtest(plm.model, ..., h0 = h0)
}
pwfdtest.panelmodel <- function(x, ..., h0 = c("fd", "fe")) {
model <- describe(x, "model")
if (model != "fd") stop(paste0("input 'x' needs to be a \"fd\" model (first-differenced model), but is \"", model, "\""))
FDres <- x$residuals
xindex <- unclass(attr(model.frame(x), "index"))
time <- as.numeric(xindex[[2L]])
id <- as.numeric(xindex[[1L]])
pdim <- pdim(x)
n <- pdim$nT$n
Ti_minus_one <- pdim$Tint$Ti-1
red_id <- integer()
for(i in 1:n) {
red_id <- c(red_id, rep(i, Ti_minus_one[i]))
}
if(length(red_id) == 0L)
stop("only individuals with one observation in original data: test not feasible")
auxdata <- pdata.frame(as.data.frame(cbind(red_id, FDres)), index = "red_id")
auxdata[["FDres.1"]] <- lag(auxdata[["FDres"]], shift = "row")
auxmod <- plm(FDres ~ FDres.1, data = auxdata, model = "pooling")
switch(match.arg(h0),
"fd" = {h0des <- "differenced"
rho.H0 <- 0},
"fe" = {h0des <- "original"
rho.H0 <- -0.5})
myH0 <- paste("FDres.1 = ", as.character(rho.H0), sep="")
myvcov <- function(x) vcovHC(x, method = "arellano", ...)
FDARstat <- ((coef(auxmod)["FDres.1"] - rho.H0)/sqrt(myvcov(auxmod)["FDres.1", "FDres.1"]))^2
names(FDARstat) <- "F"
df1 <- c(df1 = 1)
df2 <- c(df2 = df.residual(auxmod))
pFDARstat <- pf(FDARstat, df1 = df1, df2 = df2, lower.tail = FALSE)
RVAL <- list(statistic = FDARstat,
parameter = c(df1, df2),
p.value = pFDARstat,
method = "Wooldridge's first-difference test for serial correlation in panels",
alternative = paste("serial correlation in", h0des, "errors"),
data.name = paste(deparse(substitute(x))))
class(RVAL) <- "htest"
return(RVAL)
} |
pocket_tag <- function(action_name = c("tags_replace", "tags_remove", "tags_add", "tags_clear", "tag_rename", "tag_delete"), item_ids = NULL, tags = NULL, consumer_key = Sys.getenv("POCKET_CONSUMER_KEY"),
access_token = Sys.getenv("POCKET_ACCESS_TOKEN")) {
if (consumer_key == "") usethis::ui_stop(error_message_consumer_key())
if (access_token == "") usethis::ui_stop(error_message_access_token())
stop_for_invalid_tag_action_(item_ids = item_ids, action_name = action_name, tags = tags)
tags <- paste(tags, collapse = ",")
if (action_name %in% c("tags_replace", "tags_remove", "tags_add")) {
action_results <- pocket_modify_bulk_(item_ids, action_name, consumer_key, access_token, tags = tags)
return(invisible(action_results))
}
if (action_name == "tags_clear") {
action_results <- pocket_modify_bulk_(item_ids, action_name, consumer_key, access_token)
return(invisible(action_results))
}
if (action_name == "tag_rename") {
action_list <- action_name %>% purrr::map(
old_tag = tags[1],
new_tag = tags[2],
.f = gen_tag_action_
)
actions_json <- jsonlite::toJSON(action_list, auto_unbox = TRUE)
res <- pocket_post_("send",
consumer_key,
access_token,
actions = actions_json
)
pocket_stop_for_status_(res)
usethis::ui_done(glue::glue("Successfully renamed tag '{tags[1]}' for '{tags[2]}'."))
}
if (action_name == "tag_delete") {
action_list <- action_name %>% purrr::map(
tag = tags,
.f = gen_tag_action_
)
action_list <- action_name %>% purrr::map(
tag = tags,
.f = gen_tag_action_
)
actions_json <- jsonlite::toJSON(action_list, auto_unbox = TRUE)
res <- pocket_post_("send",
consumer_key,
access_token,
actions = actions_json
)
pocket_stop_for_status_(res)
usethis::ui_done(glue::glue("Successfully removed tag '{tags}'."))
}
}
gen_tag_action_ <- function(action_name, ...) {
return(list(
action = action_name,
time = as.POSIXct(Sys.time()),
...
))
}
stop_for_invalid_tag_action_ <- function(item_ids, action_name, tags) {
actions <- c("tags_add", "tags_remove", "tags_replace", "tags_clear", "tag_rename", "tag_delete")
if (!action_name %in% actions) {
usethis::ui_stop("Tag actions can be only be: 'tags_add', 'tags_remove', 'tags_replace', 'tags_clear', 'tag_rename', or 'tag_delete'.")
}
if (is.null(item_ids) & !action_name %in% c("tag_delete", "tag_rename")) {
usethis::ui_stop("If your action_name is not 'tag_delete' or 'tag_rename', you need to provide at least one item_id.")
}
if (action_name == "tag_delete") {
if (length(tags) > 1) {
usethis::ui_stop("For 'tag_delete', you can only specify an atomic vector of one tag.")
}
if (is.null(tags)) {
usethis::ui_stop("For 'tag_delete', you need to specify an atomic vector of one tag.")
}
}
if (action_name == "tag_rename" & length(tags) != 2) {
usethis::ui_stop("If your action is 'tag_rename', your tags vector must be of length 2, format: c('old tag', 'new tag').")
}
if (action_name == "tags_clear" & !is.null(tags)) {
usethis::ui_stop("If your action is 'tags_clear', you must not provide tags.")
}
if (action_name == "tags_replace" & is.null(tags)) {
usethis::ui_stop("For 'tags_replace', you need to specify the tags argument.")
}
} |
github_api_branch_get_ref = function(repo, branch) {
ghclass_api_v3_req(
endpoint = "GET /repos/:owner/:repo/commits/:ref",
owner = get_repo_owner(repo),
repo = get_repo_name(repo),
ref = paste0("heads/", branch)
)
}
get_branch_ref = function(repo, branch) {
arg_is_chr_scalar(repo, branch)
res = purrr::safely(github_api_branch_get_ref)(repo, branch)
repo_txt = format_repo(repo, branch)
if (failed(res))
cli_stop("Unable to locate branch {.val {repo_txt}}.")
result(res)
}
github_api_branch_create = function(repo, branch, new_branch) {
head = get_branch_ref(repo, branch)
ghclass_api_v3_req(
"POST /repos/:owner/:repo/git/refs",
owner = get_repo_owner(repo),
repo = get_repo_name(repo),
ref = paste0("refs/heads/", new_branch),
sha = head[["sha"]]
)
}
branch_create = function(repo, branch, new_branch) {
arg_is_chr(repo, branch, new_branch)
invisible( purrr::pmap(
list(repo, branch, new_branch),
function(repo, branch, new_branch) {
cur_repo = format_repo(repo, branch)
new_repo = format_repo(repo, new_branch)
branches = repo_branches(repo)
if (!branch %in% branches) {
cli::cli_alert_danger("Failed to create branch, {.val {cur_repo}} does not exist.")
return()
}
if (new_branch %in% branches) {
cli::cli_alert_danger("Skipping creation of branch {.val {new_repo}}, it already exists.")
return()
}
res = purrr::safely(github_api_branch_create)(repo, branch, new_branch)
status_msg(
res,
"Created branch {.val {new_branch}} in repo {.val {repo}}.",
"Failed to create branch {.val {new_branch}} in repo {.val {repo}}."
)
res
}
) )
} |
get_desc <- function (sourcevar,
origin) {
if (length(sourcevar) == 0) {return(character(0))}
origin <- toupper(origin)
if (origin == "NAICS2017") {
desc.df <- concordance::naics2017_desc
} else if (origin == "NAICS2012"){
desc.df <- concordance::naics2012_desc
} else if (origin == "NAICS2007"){
desc.df <- concordance::naics2007_desc
} else if (origin == "NAICS2002"){
desc.df <- concordance::naics2002_desc
} else if (origin == "HS"){
desc.df <- concordance::hs_desc
} else if (origin == "HS0"){
desc.df <- concordance::hs0_desc
} else if (origin == "HS1"){
desc.df <- concordance::hs1_desc
} else if (origin == "HS2"){
desc.df <- concordance::hs2_desc
} else if (origin == "HS3"){
desc.df <- concordance::hs3_desc
} else if (origin == "HS4"){
desc.df <- concordance::hs4_desc
} else if (origin == "HS5"){
desc.df <- concordance::hs5_desc
} else if (origin == "ISIC2"){
desc.df <- concordance::isic2_desc
} else if (origin == "ISIC3"){
desc.df <- concordance::isic3_desc
} else if (origin == "ISIC4"){
desc.df <- concordance::isic4_desc
} else if (origin == "SITC1"){
desc.df <- concordance::sitc1_desc
} else if (origin == "SITC2"){
desc.df <- concordance::sitc2_desc
} else if (origin == "SITC3"){
desc.df <- concordance::sitc3_desc
} else if (origin == "SITC4"){
desc.df <- concordance::sitc4_desc
} else if (origin == "BEC"){
desc.df <- concordance::bec_desc
} else {
stop("Conversion dictionary not available.")
}
digits <- unique(nchar(sourcevar))
if (length(digits) > 1) {stop("'sourcevar' has codes with different number of digits. Please ensure that input codes are at the same length.")}
if (origin == "HS" | origin == "HS0" | origin == "HS1" | origin == "HS2" | origin == "HS3" | origin == "HS4" | origin == "HS5"){
origin.digits <- c(2, 4, 6)
if (!(digits %in% origin.digits)) {stop("'sourcevar' only accepts 2, 4, 6-digit inputs for HS codes.")}
} else if (origin == "NAICS2002" | origin == "NAICS2007" | origin == "NAICS2012" | origin == "NAICS2017") {
origin.digits <- c(2, 3, 4, 5, 6)
if (!(digits %in% origin.digits)) {stop("'sourcevar' only accepts 2, 3, 4, 5, 6-digit inputs for NAICS codes.")}
} else if (origin == "SITC1" | origin == "SITC2" | origin == "SITC3" | origin == "SITC4") {
origin.digits <- c(1, 2, 3, 4, 5)
if (!(digits %in% origin.digits)) {stop("'sourcevar' only accepts 1, 2, 3, 4, 5-digit inputs for SITC codes.")}
} else if (origin == "BEC") {
origin.digits <- c(1, 2, 3)
if (!(digits %in% origin.digits)) {stop("'sourcevar' only accepts 1, 2, 3-digit inputs for BEC codes.")}
} else if (origin == "ISIC2" | origin == "ISIC3" | origin == "ISIC4") {
origin.digits <- c(1, 2, 3, 4)
if (!(digits %in% origin.digits)) {stop("'sourcevar' only accepts 1, 2, 3, 4-digit inputs for ISIC codes.")}
} else {
stop("Concordance not supported.")
}
all.origin.codes <- desc.df$code
if (!all(sourcevar %in% all.origin.codes)){
no.code <- sourcevar[!sourcevar %in% all.origin.codes]
no.code <- paste0(no.code, collapse = ", ")
warning(paste(str_extract(origin, "[^_]+"), " code(s): ", no.code, " not found and returned NA. Please double check input code and classification.\n", sep = ""))
}
matches <- which(all.origin.codes %in% sourcevar)
dest.var <- desc.df[matches, c("code", "desc")]
out <- dest.var[match(sourcevar, dest.var$code),] %>%
pull(desc)
return(out)
} |
spmd.hostinfo <- function(comm = .pbd_env$SPMD.CT$comm){
if(spmd.comm.size(comm) == 0){
stop(paste("It seems no members running on comm", comm))
}
HOST.NAME <- spmd.get.processor.name()
COMM.RANK <- spmd.comm.rank(comm)
COMM.SIZE <- spmd.comm.size(comm)
cat("\tHost:", HOST.NAME, "\tRank(ID):", COMM.RANK, "\tof Size:", COMM.SIZE,
"on comm", comm, "\n")
invisible()
}
spmd.comm.print <- function(x, all.rank = .pbd_env$SPMD.CT$print.all.rank,
rank.print = .pbd_env$SPMD.CT$rank.source, comm = .pbd_env$SPMD.CT$comm,
quiet = .pbd_env$SPMD.CT$print.quiet,
flush = .pbd_env$SPMD.CT$msg.flush,
barrier = .pbd_env$SPMD.CT$msg.barrier, con = stdout(), ...){
COMM.RANK <- spmd.comm.rank(comm)
if (!exists(deparse(substitute(x))))
quiet <- TRUE
if(barrier){
spmd.barrier(comm)
}
if(all.rank){
for(i.rank in 0:(spmd.comm.size(comm) - 1)){
if(i.rank == COMM.RANK){
if(! quiet){
cat("COMM.RANK = ", COMM.RANK, "\n", sep = "")
if(flush){
flush(con)
}
}
print(x, ...)
if(flush){
flush(con)
}
}
if(barrier){
spmd.barrier(comm)
}
}
} else{
for(i.rank in rank.print){
if(i.rank == COMM.RANK){
if(! quiet){
cat("COMM.RANK = ", COMM.RANK, "\n", sep = "")
if(flush){
flush(con)
}
}
print(x, ...)
if(flush){
flush(con)
}
}
if(barrier){
spmd.barrier(comm)
}
}
}
invisible()
}
comm.print <- spmd.comm.print
spmd.comm.cat <- function(..., all.rank = .pbd_env$SPMD.CT$print.all.rank,
rank.print = .pbd_env$SPMD.CT$rank.source, comm = .pbd_env$SPMD.CT$comm,
quiet = .pbd_env$SPMD.CT$print.quiet, sep = " ", fill = FALSE,
labels = NULL, append = FALSE, flush = .pbd_env$SPMD.CT$msg.flush,
barrier = .pbd_env$SPMD.CT$msg.barrier, con = stdout()){
COMM.RANK <- spmd.comm.rank(comm)
if(barrier){
spmd.barrier(comm)
}
if(all.rank){
for(i.rank in 0:(spmd.comm.size(comm) - 1)){
if(i.rank == COMM.RANK){
if(! quiet){
cat("COMM.RANK = ", COMM.RANK, "\n", sep = "")
if(flush){
flush(con)
}
}
cat(..., sep = sep, fill = fill, labels = labels, append = append)
if(flush){
flush(con)
}
}
if(barrier){
spmd.barrier(comm)
}
}
} else{
for(i.rank in rank.print){
if(i.rank == COMM.RANK){
if(! quiet){
cat("COMM.RANK = ", COMM.RANK, "\n", sep = "")
if(flush){
flush(con)
}
}
cat(..., sep = sep, fill = fill, labels = labels, append = append)
if(flush){
flush(con)
}
}
if(barrier){
spmd.barrier(comm)
}
}
}
invisible()
}
comm.cat <- spmd.comm.cat |
changes <- function(offset = 0, limit = 31,url = get_default_url(),
key = get_default_key(), as ='list', ...) {
args <- cc(list(offset = offset, limit = limit))
res <- ckan_GET(url, 'recently_changed_packages_activity_list', args,
key = key, opts = list(...))
switch(as, json = res, list = jsl(res), table = jsd(res))
} |
library(metaBMA)
library(testthat)
set.seed(123)
params <- list(
"norm" = c(mean = 0, sd = .3),
"t" = c(location = 0, scale = .3, nu = 1),
"beta" = c(1, 2),
"invgamma" = c(shape = 1, scale = 1),
"gamma" = c(shape = 1, rate = 1),
"cauchy" = c(location = 0, scale = 0.707)
)
priors <- names(params)
test_that("prior returns vectorized function", {
for (i in seq_along(priors)) {
for (lower in c(-Inf, 0)) {
for (upper in c(1, Inf)) {
if (!(priors[i] == "beta" & (lower == -Inf || upper == Inf))) {
suppressWarnings(pp <- prior(priors[i], params[[i]], lower = lower, upper = upper))
plot(pp)
plot(pp, from = -1, to = 1.5)
expect_s3_class(pp, "prior")
expect_true(is.function(pp))
expect_length(pp(1:10), 10)
expect_equal(pp(1:3, log = TRUE), log(pp(1:3)))
aa <- attributes(pp)
expect_true(all(c(
"family", "param", "label",
"lower", "upper"
) %in% names(aa)))
expect_is(aa$lower, "numeric")
expect_is(aa$upper, "numeric")
expect_lt(aa$lower, aa$upper)
expect_silent(x <- metaBMA:::rprior(3, pp))
expect_length(x, 3)
}
}
}
}
})
test_that("prior crashes for non-vectorized/negative functions", {
expect_error(prior("norm", c(0), "xx"))
expect_error(prior("cauchy", NULL, "xx"))
expect_error(prior("custom", 1, "xx"))
expect_error(prior("custom", function(x) x, "xx"))
expect_error(prior("custom", function(x) -dunif(x), "xx"))
})
test_that("expected value in truncnorm_mean() is correct", {
x <- metaBMA:::rtrunc(5e5, "norm", 0, Inf, mean = .14, sd = .5)
expect_silent(avg <- metaBMA:::truncnorm_mean(.14, .5, 0, Inf))
expect_equal(mean(x), avg, tolerance = .001)
expect_length(metaBMA:::truncnorm_mean(0:1, c(.3, .4), 0, 4), 2)
})
test_that("log_diff_exp() correctly implemented", {
x <- c(-3.2, -4.5)
expect_silent(lde <- metaBMA:::log_diff_exp(x[1], x[2]))
expect_equal(lde, log(exp(x)[1] - exp(x)[2]))
}) |
library(testthat)
library(recipes)
library(dplyr)
set.seed(1234)
context("ROSE")
test_that("minority_prop value", {
rec <- recipe(~., data = circle_example)
rec21 <- rec %>%
step_rose(class, minority_prop = 0.1)
rec22 <- rec %>%
step_rose(class, minority_prop = 0.2)
rec21_p <- prep(rec21, training = circle_example)
rec22_p <- prep(rec22, training = circle_example)
tr_xtab1 <- table(bake(rec21_p, new_data = NULL)$class, useNA = "no")
tr_xtab2 <- table(bake(rec22_p, new_data = NULL)$class, useNA = "no")
expect_equal(sum(tr_xtab1), sum(tr_xtab2))
expect_lt(tr_xtab1[["Circle"]], tr_xtab2[["Circle"]])
})
test_that("tunable", {
rec <-
recipe(~., data = iris) %>%
step_rose(all_predictors(), under_ratio = 1)
rec_param <- tunable.step_rose(rec$steps[[1]])
expect_equal(rec_param$name, c("over_ratio"))
expect_true(all(rec_param$source == "recipe"))
expect_true(is.list(rec_param$call_info))
expect_equal(nrow(rec_param), 1)
expect_equal(
names(rec_param),
c("name", "call_info", "source", "component", "component_id")
)
})
test_that("row matching works correctly
expect_error(
recipe(class ~ ., data = circle_example) %>%
step_rose(class, over_ratio = 1.2) %>%
prep(),
NA
)
expect_error(
recipe(class ~ ., data = circle_example) %>%
step_rose(class, over_ratio = 0.8) %>%
prep(),
NA
)
expect_error(
recipe(class ~ ., data = circle_example) %>%
step_rose(class, over_ratio = 1.7) %>%
prep(),
NA
)
})
test_basic_usage(step_rose)
test_printing(step_rose)
test_bad_data(step_rose)
test_no_skipping(step_rose)
test_character_error(step_rose)
test_na_response(step_rose)
test_seed(step_rose)
test_tidy(step_rose)
test_2_class_only(step_rose)
test_factor_level_memory(step_rose)
test_id_variables_are_ignores(step_rose) |
CalculateContributions <- function(X, A, B){
I=dim(X)[1]
J=dim(X)[2]
I1=dim(A)[1]
S=dim(A)[2]
J1=dim(B)[1]
S1=dim(B)[2]
if (!I==I1) stop("Number of rows of the data and coordinates must be the same")
if (!J==J1) stop("Number of columns of the data and coordinates must be the same")
if (!S==S1) stop("Number of columns of both coordinate matrices must be the same")
CumRowContributions=matrix(0,I,S)
CumColContributions=matrix(0,J,S)
CumFit=matrix(0,S,1)
for (i in 1:S){
Xesp= A[,1:i] %*% t(B[,1:i])
CumFit[i]=sum(Xesp^2)/sum(X^2)
CumRowContributions[,i] = apply(Xesp^2,1,sum)/apply(X^2,1,sum)
CumColContributions[,i] = apply(Xesp^2,2,sum)/apply(X^2,2,sum)
}
RowContributions=CumRowContributions
ColContributions=CumColContributions
Fit=CumFit
for (i in 2:S){
Fit[i]=CumFit[i]-CumFit[i-1]
RowContributions[,i] = CumRowContributions[,i] - CumRowContributions[,(i-1)]
ColContributions[,i] = CumColContributions[,i] - CumColContributions[,(i-1)]
}
RowContributions[which(RowContributions<0)]=0
ColContributions[which(RowContributions<0)]=0
RowContributions=round(RowContributions,digits=4)*100
ColContributions=round(ColContributions,digits=4)*100
rownames(RowContributions)=rownames(X)
colnames(RowContributions)=colnames(A)
rownames(ColContributions)=colnames(X)
colnames(ColContributions)=colnames(A)
colnames(Fit)="Percentage"
rownames(Fit)=colnames(A)
Structure=round(cor(X,A),digits=4)
result=list(Fit=Fit, RowContributions=RowContributions, ColContributions=ColContributions, Structure=Structure)
return(result)
} |
NULL
.onLoad <- function(libname, pkgname) {
if (is.null(getOption("gu.API.key"))) {
key <- Sys.getenv("GU_API_KEY")
if (key != "") options("gu.API.key" = key)
}
invisible()
} |
re2p <- re2_regexp("hello world")
stopifnot(mode(re2p) == "externalptr")
x <- "fa\xE7ile"
Encoding(x) <- "latin1"
re2_detect(x, re2_regexp("fa\xE7", encoding = "Latin1"))
re2_detect("fOobar ", re2_regexp("Foo", case_sensitive = FALSE))
re2_detect("foo\\$bar", re2_regexp("foo\\$b", literal = TRUE))
re2_detect("foo\\$bar", re2_regexp("foo\\$b", literal = FALSE))
re <- re2_regexp("(abc(.|\n)*def)", never_nl = FALSE)
re2_match("abc\ndef\n", re)
re <- re2_regexp("(abc(.|\n)*def)", never_nl = TRUE)
re2_match("abc\ndef\n", re) |
cat("test_diff.R:\n")
locinfile <- genepopExample('sample.txt')
outfile <- test_diff(locinfile,outputFile="sample.txt.GE")
testthat::expect_equal(readLines(outfile)[116],"mtDNA 0.2106 ")
outfile <- test_diff(locinfile,pairs=TRUE,outputFile="sample.txt.GE2")
testthat::expect_equal(readLines(outfile)[157],"Tertre Rotebo & last pop 14.52354 12 0.268532")
testthat::expect_equal(readLines(outfile)[158],"Bonneau 05 & last pop 48.07912 12 3.03e-006")
outfile <- test_diff(locinfile,genic=FALSE,outputFile="sample.txt.G")
nums <- as.numeric(unlist(strsplit(readLines(outfile)[112], "[^0-9e.-]+"))[c(3,4,7)])
testthat::expect_equal(nums,c(81.0679,10,3.09949e-013))
outfile <- test_diff(locinfile,genic=FALSE,pairs=TRUE,outputFile="sample.txt.2G2")
testthat::expect_equal(readLines(outfile)[146],"Bonneau 05 & last pop 32.50364 10 0.000330") |
PhasesGap <- function(Phase1Max_chain, Phase2Min_chain, level=0.95){
if(length(Phase1Max_chain) != length(Phase2Min_chain)) { stop('Error : the parameters do not have the same length')}
else{
if( sum(ifelse(Phase1Max_chain <=Phase2Min_chain, 1, 0)) != length(Phase2Min_chain) ) {
stop('Error : Phase1Max_chain should be older than Phase2Min_chain')
} else {
interval <- function(epsilon, P1Max, P2Min, level)
{
q1 = quantile(P1Max ,probs = 1-epsilon) ;
indz = (P1Max < q1)
q2 = quantile(P2Min[indz],probs= (1-level-epsilon)/(1-epsilon))
c(q1,q2)
}
hia = Vectorize(interval,"epsilon")
epsilon = seq(0,1-level,.001)
p = hia(epsilon, Phase1Max_chain, Phase2Min_chain, level)
rownames(p)<- c("HiatusIntervalInf", "HiatusIntervalSup")
D<- p[2,]-p[1,]
DD = D[D>0]
if (length(DD) > 0){
I = which(D==max(DD))
interval2 = round( p[,I], 0)
if (p[2,I] != p[1,I]) {
c(level=level, interval2[1], interval2[2])
} else {
c(level=level, HiatusIntervalInf='NA',HiatusIntervalSup='NA')
}
} else {
c(level=level, HiatusIntervalInf='NA',HiatusIntervalSup='NA')
}
}
}
}
phases_gap <- function(a_chain, b_chain, level = 0.95) {
chain_len <- length(a_chain)
if (chain_len != length(b_chain))
stop('Chains are not the same length')
if (sum(a_chain <= b_chain) != chain_len)
stop("One chain should be strictly older than the other")
no_hiatus <- list(hiatus = c(inf = 'NA', sup = 'NA'),
duration = 'NA',
level = level)
interval <- function(epsilon, p1, p2, level) {
prob <- 1 - epsilon
q1 <- quantile(p1, probs = prob)
ind <- (p1 < q1)
q2 <- quantile(p2[ind], probs = (prob - level) / prob)
c(q1, q2)
}
hia = Vectorize(interval, "epsilon")
epsilon = seq(0, 1 - level, .001)
p = hia(epsilon, a_chain, b_chain, level)
d <- p[2, ] - p[1, ]
dd <- d[d > 0]
if (length(dd) < 1) return(no_hiatus)
i <- which(d == max(dd))
i2 = round(p[, i], 0)
if (p[2, i] == p[1, i]) return(no_hiatus)
inf <- unname(i2[1])
sup <- unname(i2[2])
list(hiatus = c(inf = inf, sup = sup),
level = level,
call = match.call())
} |
rmultinomial<-function(n=5, pr=c(0.5,0.5), long=FALSE) {
k<-length(pr)
if (abs(1-sum(pr))>0.000001)
stop("(rmultinomial): parameter pr must be the k probabilities (summing to 1)")
if(long) {
y<-runif(n, 0, 1)
p<-cumsum(pr)
Seq<-1:n
x<-sapply(y, function(y, Seq, p) {Seq[y <= p][1]}, Seq=Seq, p=p)
} else {
x<-rep(NA,k)
p<-pr/c(1,(1-cumsum(pr[1:(k-1)])))
for (i in 1:(k-1)) {
if (n==0) {
x[i]<-0
if (i==k-1) x[k]<-0
next
}
y<-rbinom(1,n,p[i])
x[i]<-y
if (i==k-1) x[k]<-n-y
n<-n-y
}
}
return(x)
}
rdirich<-function(n,alphavec) {
k<-length(alphavec)
p<-matrix(rgamma(n*k,alphavec),n,k,byrow=T)
sm<-matrix(apply(p,1,sum),n,k)
return(p/sm)
} |
kp_trends <- function(){
tryCatch(
expr = {
if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination, set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE)
browser <- login()
url <- "https://kenpom.com/trends.php"
page <- rvest::session_jump_to(browser, url)
header_cols <- c("Season","Efficiency","Tempo","eFG.Pct","TO.Pct",
"OR.Pct","FTRate","FG_2.Pct","FG_3.Pct","FG_3A.Pct",'FT.Pct',
"A.Pct","Blk.Pct","Stl.Pct","NonStl.Pct","Avg.Hgt",
"Continuity","HomeWin.Pct","PPG")
x <- (page %>%
xml2::read_html() %>%
rvest::html_elements("table"))[[1]] %>%
rvest::html_table() %>%
as.data.frame()
colnames(x) <- header_cols
suppressWarnings(
x <- x %>%
dplyr::filter(!is.na(as.numeric(.data$eFG.Pct)))
)
kenpom <- x %>%
dplyr::mutate_at(c("Season","Efficiency","Tempo","eFG.Pct","TO.Pct",
"OR.Pct","FTRate","FG_2.Pct","FG_3.Pct","FG_3A.Pct",'FT.Pct',
"A.Pct","Blk.Pct","Stl.Pct","NonStl.Pct","Avg.Hgt",
"Continuity","HomeWin.Pct","PPG"), as.numeric) %>%
janitor::clean_names()
},
error = function(e) {
message(glue::glue("{Sys.time()}: Invalid arguments or no trends data available!"))
},
warning = function(w) {
},
finally = {
}
)
return(kenpom)
}
kp_officials <- function(year = most_recent_mbb_season()){
tryCatch(
expr = {
if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination, set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE)
browser <- login()
if(!(is.numeric(year) && nchar(year) == 4 && year>=2016)) {
cli::cli_abort("Enter valid year as a number (YYYY), data only goes back to 2016")
}
url <- paste0("https://kenpom.com/officials.php?y=",year)
page <- rvest::session_jump_to(browser, url)
header_cols <- c("Rk","OfficialName","RefRating","Gms","Last.Game",
"Last.Game.1","Last.Game.2")
x <- (page %>%
xml2::read_html() %>%
rvest::html_elements("table"))[[1]] %>%
rvest::html_table() %>%
as.data.frame()
colnames(x) <- header_cols
x <- x %>%
dplyr::select(-.data$Last.Game.2) %>%
suppressWarnings(
x <- x %>%
dplyr::filter(!is.na(as.numeric(.data$RefRating)))
)
x <- dplyr::mutate(x,
"Year" = year)
suppressWarnings(
x <- x %>%
dplyr::mutate_at(c("Year","RefRating","Gms"), as.numeric) %>%
as.data.frame()
)
kenpom <- x %>%
janitor::clean_names()
},
error = function(e) {
message(glue::glue("{Sys.time()}: Invalid arguments or no officials data for {year} available!"))
},
warning = function(w) {
},
finally = {
}
)
return(kenpom)
}
kp_referee <- function(referee, year){
tryCatch(
expr = {
if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination, set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE)
browser <- login()
if(!(is.numeric(year) && nchar(year) == 4 && year>=2016)) {
cli::cli_abort("Enter valid year as a number (YYYY), data only goes back to 2016")
}
url <- paste0("https://kenpom.com/referee.php?",
"r=",referee,
"&y=",year)
page <- rvest::session_jump_to(browser, url)
header_cols <- c("GameNumber","Date","Time (ET)","Game","Location",
"Venue","Conference", "ThrillScore")
x <- (page %>%
xml2::read_html() %>%
rvest::html_elements("table"))[[1]] %>%
rvest::html_table() %>%
as.data.frame()
colnames(x) <- header_cols
rk <- page %>%
xml2::read_html() %>%
rvest::html_element(".rank") %>%
rvest::html_text()
name <- page %>%
xml2::read_html() %>%
rvest::html_element("h5") %>%
rvest::html_text()
x$RefereeName <- stringr::str_remove(name,"\\d+ ")
x$RefRank <- as.numeric(rk)
x <- dplyr::mutate(x,
"Year" = year)
kenpom <- x %>%
janitor::clean_names()
},
error = function(e) {
message(glue::glue("{Sys.time()}: Invalid arguments or no referee data for {referee} in {year} available!"))
},
warning = function(w) {
},
finally = {
}
)
return(kenpom)
}
kp_hca <- function(){
tryCatch(
expr = {
if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination, set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE)
browser <- login()
url <- paste0("https://kenpom.com/hca.php")
page <- rvest::session_jump_to(browser, url)
header_cols <- c("Team", "Conf", "HCA","HCA.Rk", "PF","PF.Rk", "Pts","Pts.Rk", "NST","NST.Rk",
"Blk","Blk.Rk", "Elev","Elev.Rk")
x <- (page %>%
xml2::read_html() %>%
rvest::html_elements("table"))[[1]] %>%
rvest::html_table() %>%
as.data.frame()
colnames(x) <- header_cols
suppressWarnings(
x <- x %>%
dplyr::filter(!is.na(as.numeric(.data$HCA)))
)
kenpom <- x %>%
dplyr::mutate_at(c("HCA","HCA.Rk", "PF","PF.Rk", "Pts","Pts.Rk",
"NST","NST.Rk", "Blk","Blk.Rk", "Elev","Elev.Rk"),
as.numeric) %>%
janitor::clean_names()
},
error = function(e) {
message(glue::glue("{Sys.time()}: Invalid arguments or no home court advantage data available!"))
},
warning = function(w) {
},
finally = {
}
)
return(kenpom)
}
kp_arenas <- function(year=most_recent_mbb_season()){
tryCatch(
expr = {
if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination, set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE)
browser <- login()
if(!(is.numeric(year) && nchar(year) == 4 && year>=2010)) {
cli::cli_abort("Enter valid year as a number (YYYY), data only goes back to 2010")
}
url <- paste0("https://kenpom.com/arenas.php?y=",year)
page <- rvest::session_jump_to(browser, url)
header_cols <- c("Rk","Team", "Conf", "Arena",
"Alternate")
x <- (page %>%
xml2::read_html() %>%
rvest::html_elements("table"))[[1]] %>%
rvest::html_table() %>%
as.data.frame()
colnames(x) <- header_cols
x <- dplyr::mutate(x,
"Rk" = as.numeric(.data$Rk),
"Year" = as.numeric(year))
kenpom <- x %>%
janitor::clean_names()
},
error = function(e) {
message(glue::glue("{Sys.time()}: Invalid arguments or no arenas data available!"))
},
warning = function(w) {
},
finally = {
}
)
return(kenpom)
}
kp_game_attrs <- function(year=most_recent_mbb_season(), attr = "Excitement"){
tryCatch(
expr = {
if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination, set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE)
browser <- login()
if(!(is.numeric(year) && nchar(year) == 4 && year>=2010)) {
cli::cli_abort("Enter valid year as a number (YYYY), data only goes back to 2010")
}
url <- paste0("https://kenpom.com/game_attrs.php?",
"y=", year,
"&s=", attr)
page <- rvest::session_jump_to(browser, url)
header_cols <- c("Rk","Data","Game",
"col","Location","Conf",
attr)
x <- (page %>%
xml2::read_html() %>%
rvest::html_elements("table"))[[1]] %>%
rvest::html_table()
colnames(x) <- header_cols
x <- dplyr::mutate(x,
"Year" = year)%>%
as.data.frame()
kenpom <- x %>% dplyr::select(-.data$col) %>%
janitor::clean_names()
},
error = function(e) {
message(glue::glue("{Sys.time()}: Invalid arguments or no game attributes data for {attr} available!"))
},
warning = function(w) {
},
finally = {
}
)
return(kenpom)
}
kp_fanmatch <- function(date="2020-02-12"){
tryCatch(
expr = {
if (!has_kp_user_and_pw()) stop("This function requires a KenPom subscription e-mail and password combination, set as the system environment variables KP_USER and KP_PW.", "\n See ?kp_user_pw for details.", call. = FALSE)
browser <- login()
url <- paste0("https://kenpom.com/fanmatch.php?",
"d=", date)
page <- rvest::session_jump_to(browser, url)
header_cols <- c("Game","Prediction","Time(ET)",
"Location","ThrillScore","Comeback","Excitement")
x <- (page %>%
xml2::read_html() %>%
rvest::html_elements("
rvest::html_table()
colnames(x) <- header_cols
suppressWarnings(
x <- x %>%
tidyr::separate(.data$Game,
into = c("Winner","col"),
sep = ",",
extra = "merge"))
x <- x %>%
dplyr::mutate(
WinRk = stringr::str_extract(
stringr::str_extract(.data$Winner,"[\\w]+"),"\\d{1,3}+"),
WinTeam = stringr::str_extract(
stringr::str_extract(.data$Winner,'[^\\d]+'),".+"),
WinScore = stringr::str_extract(
stringi::stri_extract_last_regex(.data$Winner,'[\\d]+'),"\\d{1,3}+"),
Loser = stringr::str_extract(
stringr::str_extract(.data$col,'[^\\[]+'),".+"),
LossRk = stringr::str_extract(
stringr::str_extract(.data$Loser,"[\\w]+"),"\\d{1,3}+"),
LossTeam =
stringr::str_match(.data$Loser,'\\d{1,3}\\s(.*?)\\s\\d{1,3}')[,2],
LossScore = stringr::str_extract(
stringi::stri_extract_last_regex(.data$Loser,'[\\d]+'),"\\d{1,3}+"),
Poss = stringr::str_match(.data$col,'\\[(.*?)\\]')[,2],
MVP = stringr::str_match(.data$col,'MVP\\:(.*)')[,2],
Event = stringr::str_match(.data$col,'\\](.*)')[,2]
)
x <- dplyr::mutate(x,
"Date" = date)
suppressWarnings(
x <- x %>%
dplyr::filter(!is.na(as.numeric(.data$Poss)))
)
x <- x %>%
dplyr::select(-.data$col,-.data$Winner,-.data$Loser,
.data$WinRk, .data$WinTeam, .data$WinScore,
.data$LossRk, .data$LossTeam, .data$LossScore,
.data$Poss, .data$Prediction, .data$ThrillScore,
.data$Comeback, .data$Excitement, .data$MVP,
.data$Location, "Time(ET)", .data$Event, .data$Date)
suppressWarnings(
kenpom <- x %>%
dplyr::mutate_at(c("WinScore","LossScore","Poss","ThrillScore","Comeback",
"Excitement"), as.numeric) %>%
janitor::clean_names()
)
},
error = function(e) {
message(glue::glue("{Sys.time()}: Invalid arguments or no Fan Match data for {date} available!"))
},
warning = function(w) {
},
finally = {
}
)
return(kenpom)
} |
plot_trends <- function(rotated_modelfit,
years = NULL,
highlight_outliers = FALSE,
threshold = 0.01) {
rotated <- rotated_modelfit
df <- dfa_trends(rotated, years = years)
p1 <- ggplot(df, aes_string(x = "time", y = "estimate")) +
geom_ribbon(aes_string(ymin = "lower", ymax = "upper"), alpha = 0.4) +
geom_line() +
facet_wrap("trend_number") +
xlab("Time") +
ylab("")
if (highlight_outliers) {
swans <- find_swans(rotated, threshold = threshold)
df$outliers <- swans$below_threshold
p1 <- p1 + geom_point(data = df[which(df$outliers), ], color = "red")
}
p1
} |
HTstrata<-function (y, pik, strata, description=FALSE)
{
str <- function(st, h, n) .C("str", as.double(st), as.integer(h),
as.integer(n), s = double(n), PACKAGE = "sampling")$s
if(any(is.na(pik))) stop("there are missing values in pik")
if(any(is.na(y))) stop("there are missing values in y")
if(length(y)!=length(pik)) stop("y and pik have different sizes")
if (is.matrix(y))
sample.size <- nrow(y) else sample.size <- length(y)
h <- unique(strata)
s1 <- 0
for (i in 1:length(h)) {
s <- str(strata, h[i], sample.size)
est<-HTestimator(y[s == 1], pik[s == 1])
s1 <- s1 + est
if(description)
cat("For stratum",i,",the Horvitz-Thompson estimator is:",est,"\n")
}
if(description)
cat("The Horvitz-Thompson estimator is:\n")
s1
} |
form_form <-
function(object, control, env, ...) {
check_outcome(eval_tidy(env$formula[[2]], env$data), object)
y_levels <- levels_from_formula(env$formula, env$data)
object <- check_mode(object, y_levels)
if (requires_descrs(object)) {
data_stats <- get_descr_form(env$formula, env$data)
scoped_descrs(data_stats)
}
object <- check_args(object)
object <- translate(object, engine = object$engine)
fit_call <- make_form_call(object, env = env)
res <- list(
lvl = y_levels,
spec = object
)
if (control$verbosity > 1L) {
elapsed <- system.time(
res$fit <- eval_mod(
fit_call,
capture = control$verbosity == 0,
catch = control$catch,
env = env,
...
),
gcFirst = FALSE
)
} else {
res$fit <- eval_mod(
fit_call,
capture = control$verbosity == 0,
catch = control$catch,
env = env,
...
)
elapsed <- list(elapsed = NA_real_)
}
res$preproc <- list(y_var = all.vars(env$formula[[2]]))
res$elapsed <- elapsed
res
}
xy_xy <- function(object, env, control, target = "none", ...) {
if (inherits(env$x, "tbl_spark") | inherits(env$y, "tbl_spark"))
rlang::abort("spark objects can only be used with the formula interface to `fit()`")
object <- check_mode(object, levels(env$y))
check_outcome(env$y, object)
encoding_info <-
get_encoding(class(object)[1]) %>%
dplyr::filter(mode == object$mode, engine == object$engine)
remove_intercept <- encoding_info %>% dplyr::pull(remove_intercept)
if (remove_intercept) {
env$x <- env$x[, colnames(env$x) != "(Intercept)", drop = FALSE]
}
if (requires_descrs(object)) {
data_stats <- get_descr_xy(env$x, env$y)
scoped_descrs(data_stats)
}
object <- check_args(object)
object <- translate(object, engine = object$engine)
fit_call <- make_xy_call(object, target)
res <- list(lvl = levels(env$y), spec = object)
if (control$verbosity > 1L) {
elapsed <- system.time(
res$fit <- eval_mod(
fit_call,
capture = control$verbosity == 0,
catch = control$catch,
env = env,
...
),
gcFirst = FALSE
)
} else {
res$fit <- eval_mod(
fit_call,
capture = control$verbosity == 0,
catch = control$catch,
env = env,
...
)
elapsed <- list(elapsed = NA_real_)
}
if (is.vector(env$y)) {
y_name <- character(0)
} else {
y_name <- colnames(env$y)
}
res$preproc <- list(y_var = y_name)
res$elapsed <- elapsed
res
}
form_xy <- function(object, control, env,
target = "none", ...) {
encoding_info <-
get_encoding(class(object)[1]) %>%
dplyr::filter(mode == object$mode, engine == object$engine)
indicators <- encoding_info %>% dplyr::pull(predictor_indicators)
remove_intercept <- encoding_info %>% dplyr::pull(remove_intercept)
data_obj <- .convert_form_to_xy_fit(
formula = env$formula,
data = env$data,
...,
composition = target,
indicators = indicators,
remove_intercept = remove_intercept
)
env$x <- data_obj$x
env$y <- data_obj$y
check_outcome(env$y, object)
res <- xy_xy(
object = object,
env = env,
control = control,
target = target
)
data_obj$y_var <- all.vars(env$formula[[2]])
data_obj$x <- NULL
data_obj$y <- NULL
data_obj$weights <- NULL
data_obj$offset <- NULL
res$preproc <- data_obj
res
}
xy_form <- function(object, env, control, ...) {
check_outcome(env$y, object)
encoding_info <-
get_encoding(class(object)[1]) %>%
dplyr::filter(mode == object$mode, engine == object$engine)
remove_intercept <- encoding_info %>% dplyr::pull(remove_intercept)
data_obj <-
.convert_xy_to_form_fit(
x = env$x,
y = env$y,
weights = NULL,
y_name = "..y",
remove_intercept = remove_intercept
)
env$formula <- data_obj$formula
env$data <- data_obj$data
res <- form_form(
object = object,
env = env,
control = control,
...
)
if (is.vector(env$y)) {
data_obj$y_var <- character(0)
} else {
data_obj$y_var <- colnames(env$y)
}
res$preproc <- data_obj[c("x_var", "y_var")]
res
} |
SRM_PARTABLE_EXTEND <- function(parm.table, var_positive, optimizer, method="ml")
{
symm_matrices <- c("PHI_U", "PSI_U", "PHI_D", "PSI_D")
npar <- attr(parm.table, "npar")
parm.table$est <- parm.table$starts
parm.table$est[ is.na(parm.table$starts) ] <- parm.table$fixed[ is.na(parm.table$starts) ]
parm.table$starts[ ! is.na(parm.table$fixed) ] <- parm.table$fixed[ ! is.na(parm.table$fixed) ]
parm.table$est[ ! is.na(parm.table$fixed) ] <- parm.table$fixed[ ! is.na(parm.table$fixed) ]
parm.table$lower <- -Inf
if (var_positive>=0){
ind1 <- union( grep("PHI", parm.table$mat), grep("PSI", parm.table$mat) )
ind2 <- which(parm.table$row == parm.table$col)
parm.table$lower[ intersect(ind1,ind2)] <- var_positive
if (optimizer=="srm"){
optimizer <- "nlminb"
}
}
parm_table_free <- parm.table[ ! is.na(parm.table$index), ]
parm_table_free <- parm_table_free[ order(parm_table_free$index), ]
lower <- parm_table_free[ parm_table_free$unid > 0, 'lower']
NOP <- nrow(parm_table_free)
optim_avai <- c("srm", "nlminb", "spg")
if (! (optimizer %in% optim_avai) ){
stop(paste0("Choose among following optimizers:\n",
paste0(optim_avai, collapse=" "), "\n" ))
}
if (method=="uls"){
optimizer <- "nlminb"
}
res <- list(parm.table=parm.table, parm_table_free=parm_table_free,
lower=lower, upper=NULL, NOP=NOP, npar=npar, symm_matrices=symm_matrices,
optimizer=optimizer)
return(res)
} |
f7Timeline <- function(..., sides = FALSE, horizontal = FALSE, calendar = FALSE,
year = NULL, month = NULL) {
if (sides & horizontal) {
stop("Choose either sides or horizontal. Not compatible together.")
}
timelineCl <- "timeline"
if (sides) timelineCl <- paste0(timelineCl, " timeline-sides")
if (horizontal) timelineCl <- paste0(timelineCl, " timeline-horizontal col-50 tablet-20")
if (calendar) timelineCl <- paste0(timelineCl, " timeline-horizontal col-33 tablet-15")
timelineTag <- shiny::tags$div(
class = timelineCl,
...
)
timelineWrapper <- if (calendar) {
shiny::tags$div(
class = "timeline-year",
shiny::tags$div(
class = "timeline-year-title",
shiny::span(year)
),
shiny::tags$div(
class = "timeline-month",
shiny::tags$div(
class = "timeline-month-title",
shiny::span(month)
),
timelineTag
)
)
} else {
timelineTag
}
timelineWrapper
}
f7TimelineItem <- function(..., date = NULL, card = FALSE, time = NULL,
title = NULL, subtitle = NULL, side = NULL) {
itemCl <- "timeline-item"
if (!is.null(side)) itemCl <- paste0(itemCl, " timeline-item-", side)
shiny::tags$div(
class = itemCl,
if (!is.null(date)) shiny::tags$div(class = "timeline-item-date", date),
shiny::tags$div(class = "timeline-item-divider"),
shiny::tags$div(
class = "timeline-item-content",
if (card) {
shiny::tags$div(
class = "timeline-item-inner",
if (!is.null(time)) shiny::tags$div(class = "timeline-item-time", time),
if (!is.null(title)) shiny::tags$div(class = "timeline-item-title", title),
if (!is.null(subtitle)) shiny::tags$div(class = "timeline-item-subtitle", subtitle),
if (!is.null(...)) shiny::tags$div(class = "timeline-item-text", ...)
)
} else {
shiny::tagList(
if (!is.null(time)) shiny::tags$div(class = "timeline-item-time", time),
if (!is.null(title)) shiny::tags$div(class = "timeline-item-title", title),
if (!is.null(subtitle)) shiny::tags$div(class = "timeline-item-subtitle", subtitle),
if (!is.null(...)) shiny::tags$div(class = "timeline-item-text", ...)
)
}
)
)
} |
bsubset <- function(file = NULL,
head = NULL, tail = NULL,
first_row = NULL, last_row = NULL,
...){
args = list(...)
if(.Platform$OS.type == "windows"){
qfile <- shQuote(file, type = "cmd2")
} else if(.Platform$OS.type == "unix"){
qfile <- shQuote(file)
}
meta_output <- list()
meta_output$colnames <- bcolnames(file, ...)
unixCmdStr <- bsubsetStr(file = file, head = head, tail = tail,
first_row = first_row, last_row = last_row,
...) %>%
paste(qfile)
args <- c(cmd = unixCmdStr, args)
df <- do.call(data.table::fread, args)
colnames(df) <- meta_output$colnames
return(df)
} |
library(shiny)
library(shinydashboard)
library(shinyBS)
library(shinyjs)
library(DT)
library(ggplot2)
library(shinycssloaders)
ui <- dashboardPage(
dashboardHeader(title = "Diamonds Explorer - Modal demo using shinyBS package" , titleWidth = 600),
dashboardSidebar(
sidebarMenu(
menuItem("Data", tabName = "tab1", icon = icon("th"))
)
),
dashboardBody(
shinyjs::useShinyjs(),
tabItems(
tabItem(
tabName = "tab1",
box(
width = 5,
title = "Input Data", status = "primary", solidHeader = TRUE,
fileInput("file", "Upload Data"),
shinyjs::hidden(
div(id = "data_b",style="display:inline-block",
actionButton("data", "View Data", icon=icon('table'))
)),
shinyjs::hidden(
div(id = "plot_b", style="display:inline-block",
actionButton("plot", "View Plot", icon=icon("bar-chart"))
))
))),
bsModal(id="dataset", title = "Diamonds Dataset", trigger = "data", size="large",
withSpinner(dataTableOutput("data_set"))),
bsModal(id= "Plot", title = "Plot", trigger = "plot", size="large",
sliderInput(inputId = "b", label = "Select the bin width value" , min = 50 , max = 500, value = 100),
br(),
withSpinner(plotOutput("plot_gg"))
)))
server <- function(input, output) {
observeEvent(input$file,
shinyjs::show("data_b"))
observeEvent(input$file,
shinyjs::show("plot_b"))
data_uploaded <- reactive({
file1 <- input$file
if(is.null(file1)){return()}
read.table(file=file1$datapath, sep=",", header = T, stringsAsFactors = T)
})
output$data_set <- renderDataTable(
data_uploaded(),options=list(scrollX = TRUE))
output$plot_gg <- renderPlot(
ggplot(data=data_uploaded()) +
geom_histogram(binwidth=input$b, aes(x=price)) +
ggtitle("Diamond Price Distribution") +
xlab(paste("Diamond Price & binwidth as ", input$b)) +
ylab("Frequency") +
theme_minimal() + xlim(0,2500)
)
}
shinyApp(ui=ui, server = server) |
reflect <- function(rf, wv) {
return((colSums(rf) / nrow(rf)) + ((colSums(rf) / nrow(rf)) - wv))
}
expandV <- function(rf, wv) {
return((colSums(rf) / nrow(rf)) + 2 * ((colSums(rf) / nrow(rf)) - wv))
}
contrRS <- function(rf, wv) {
return((colSums(rf) / nrow(rf)) + 0.5 * ((colSums(rf) / nrow(rf)) - wv))
}
contrWS <- function(rf, wv) {
return((colSums(rf) / nrow(rf)) - 0.5 * ((colSums(rf) / nrow(rf)) - wv))
}
checkMain <- function(simplex) {
if (class(simplex) != 'smplx') {
stop("Argument simplex is expected to be 'smplx' class. Provided: ",
class(simplex), ". ", "Use labsimplex() to generate a 'smplx'",
"class object")
}
}
checkCrit <- function(crit, lastQF, transf = FALSE) {
if (class(crit) == "character") {
if (crit == "max") {
pos <- order(lastQF)
qft <- lastQF
} else {
if (crit == "min") {
pos <- order(lastQF ^ 2, decreasing = TRUE)
qft <- 1 / (lastQF ^ 2)
} else {
stop("If criteria is not numeric, only 'max' or min' are accepted")
}
}
}
if (class(crit) == "numeric") {
pos <- order((lastQF - crit) ^ 2, decreasing = TRUE)
qft <- 1 / ((lastQF - crit) ^ 2)
}
if (transf) return(qft) else return(pos)
}
shape <- function(x, simplex){
if (is.null(x)) x <- NA
if (length(x) < nrow(simplex$coords)){
x <- c(x, rep(NA, nrow(simplex$coords) - length(x)))
}
return(x)
}
AssignQF <- function(simplex, qflv){
if (class(qflv) != "numeric") stop("Argument qflv must be numeric")
simplex$qual.fun <- c(simplex$qual.fun, qflv)
if (length(simplex$qual.fun) > nrow(simplex$coords)) {
stop("The amount of vertices can not be smaller than the size of",
" response vector.")
}
return(simplex)
}
redundant <- function(simplex, NV, counter) {
} |
library(PerformanceAnalytics)
Rdec <- R / 100
Pret <- apply(W, 2, function(x) Rdec %*% x / 100)
SD <- apply(Pret, 2, sd) * 100
ES95 <- apply(Pret, 2, function(x)
abs(ES(R = x, method = "modified") * 100))
DR <- apply(W, 2, dr, Sigma = V)
CR <- apply(W, 2, cr, Sigma = V)
Res <- rbind(SD, ES95, DR, CR) |
surv_c30 <- function(x){
covariates <- c('QL','PF','RF','EF','CF','SF','FA','NV','PA','DY','SL','AP','CO','DI','FI')
arm1_qol <- qol(x[x$arm==1,])
arm2_qol <- qol(x[x$arm==2,])
univ_formulas <- sapply(covariates,function(y) as.formula(paste('Surv(time, event)~', y)))
univ_arm1 <- lapply(univ_formulas,function(y){coxph(y, data = arm1_qol)})
univ_arm2 <- lapply(univ_formulas,function(y){coxph(y, data = arm2_qol)})
univ_results <- mapply(function(x1,x2){
x1 <- summary(x1)
x2 <- summary(x2)
HR <- signif(x2$coef[2]/x1$coef[2], digits=3);
HR.confint.lower <- signif(x2$conf.int[,"lower .95"]/x1$conf.int[,"lower .95"], 3)
HR.confint.upper <- signif(x2$conf.int[,"upper .95"]/x1$conf.int[,"upper .95"],3)
res<-c(HR,HR.confint.lower,HR.confint.upper)
names(res) <- c('HR','Lower 95% CI','Upper 95% CI')
return(res)},
univ_arm1,univ_arm2)
relative.HR <- t(as.data.frame(univ_results, check.names = FALSE))
return(relative.HR)
} |
scale_color_grafify <- function(palette = "all_grafify", reverse = FALSE, ...){
pal <- graf_col_palette(palette = palette, reverse = reverse)
discrete_scale("colour", paste0("graf_", palette), palette = pal, ...)
} |
context("PCRE to Java regex")
sc <- testthat_spark_connection()
as_utf8 <- function(ascii) {
invoke_static(
sc,
"org.apache.spark.unsafe.types.UTF8String",
"fromString",
ascii
)
}
to_string <- function(utf8) {
invoke(utf8, "toString")
}
expect_split <- function(x, sep, expected) {
sep <- sep %>%
pcre_to_java() %>%
as_utf8()
actual <- x %>%
as_utf8() %>%
invoke("split", sep, -1L) %>%
lapply(to_string)
expect_equal(actual, expected)
}
test_that("pcre_to_java converts [:alnum:] correctly", {
test_requires_version("2.0.0")
for (delim in c(letters, LETTERS, as.character(seq(0, 9)))) {
expect_split(sprintf("^%s$", delim), "[[:alnum:]]", list("^", "$"))
expect_split(sprintf("^%s@|$", delim), "[|[:alnum:]]", list("^", "@", "$"))
}
})
test_that("pcre_to_java converts [:alpha:] correctly", {
test_requires_version("2.0.0")
for (delim in c(letters, LETTERS)) {
expect_split(sprintf("1%s2", delim), "[[:alpha:]]", list("1", "2"))
expect_split(sprintf("1%s2|3", delim), "[|[:alpha:]]", list("1", "2", "3"))
}
})
test_that("pcre_to_java converts [:ascii:] correctly", {
test_requires_version("2.0.0")
for (x in c("\u00A9", "\u00B1")) {
for (delim in c("~", " ", "\033", "a", "Z", "$")) {
expect_split(sprintf("%s%s%s", x, delim, x), "[[:ascii:]]", list(x, x))
}
}
})
test_that("pcre_to_java converts [:blank:] correctly", {
test_requires_version("2.0.0")
for (delim in c(" ", "\t")) {
expect_split(sprintf("^%s$", delim), "[[:blank:]]", list("^", "$"))
expect_split(sprintf("^%s@|$", delim), "[|[:blank:]]", list("^", "@", "$"))
}
})
test_that("pcre_to_java converts [:cntrl:] correctly", {
test_requires_version("2.0.0")
for (delim in c("\x01", "\x1F", "\x7F")) {
expect_split(sprintf("^%s$", delim), "[[:cntrl:]]", list("^", "$"))
expect_split(sprintf("^%s@|$", delim), "[|[:cntrl:]]", list("^", "@", "$"))
}
})
test_that("pcre_to_java converts [:digit:] correctly", {
test_requires_version("2.0.0")
for (delim in as.character(seq(0, 9))) {
expect_split(sprintf("^%s$", delim), "[[:digit:]]", list("^", "$"))
expect_split(sprintf("^%s@|$", delim), "[|[:digit:]]", list("^", "@", "$"))
}
})
test_that("pcre_to_java converts [:graph:] correctly", {
test_requires_version("2.0.0")
for (delim in c("A", "Z", "a", "z", "0", "9", "\"", "&", "@", "[", "]", "^", "~")) {
expect_split(
sprintf("\x02%s\x03%s ", delim, delim), "[[:graph:]]", list("\x02", "\x03", " ")
)
expect_split(
sprintf("\x02%s\x03\x01\x04%s ", delim, delim),
"[\x01[:graph:]]",
list("\x02", "\x03", "\x04", " ")
)
}
})
test_that("pcre_to_java converts [:lower:] correctly", {
test_requires_version("2.0.0")
for (delim in letters) {
expect_split(sprintf("A%sB", delim), "[[:lower:]]", list("A", "B"))
expect_split(sprintf("A%sB|C", delim), "[|[:lower:]]", list("A", "B", "C"))
}
})
test_that("pcre_to_java converts [:print:] correctly", {
test_requires_version("2.0.0")
for (delim in c("A", "Z", "a", "z", "0", "9", "\"", "&", "@", "[", "]", "^", "~")) {
expect_split(
sprintf("\x01%s\x19%s\x7F", delim, delim), "[[:print:]]", list("\x01", "\x19", "\x7F")
)
expect_split(
sprintf("\x02%s\x19\x01\x7F%s\x10", delim, delim),
"[\x01[:print:]]",
list("\x02", "\x19", "\x7F", "\x10")
)
}
})
test_that("pcre_to_java converts [:punct:] correctly", {
test_requires_version("2.0.0")
for (delim in c(
"!", "\"", "
")", "*", "+", ",", "-", ".", "/", ":",
";", "<", "=", ">", "?", "@", "[", "\\",
"]", "^", "_", "'", "{", "|", "}", "~"
)
) {
expect_split(
sprintf("a%sb%sc", delim, delim), "[[:punct:]]", list("a", "b", "c")
)
expect_split(
sprintf("a%sb%scAd", delim, delim), "[A[:punct:]]", list("a", "b", "c", "d")
)
}
})
test_that("pcre_to_java converts [:space:] correctly", {
test_requires_version("2.0.0")
for (delim in c(" ", "\t", "\r", "\n", "\v", "\f")) {
expect_split(
sprintf("a%sb%sc", delim, delim), "[[:space:]]", list("a", "b", "c")
)
expect_split(
sprintf("a%sb%sc&d", delim, delim), "[&[:space:]]", list("a", "b", "c", "d")
)
}
})
test_that("pcre_to_java converts [:upper:] correctly", {
test_requires_version("2.0.0")
for (delim in LETTERS) {
expect_split(sprintf("a%sb", delim), "[[:upper:]]", list("a", "b"))
expect_split(sprintf("a%sb|c", delim), "[|[:upper:]]", list("a", "b", "c"))
}
})
test_that("pcre_to_java converts [:word:] correctly", {
test_requires_version("2.0.0")
for (delim in c(letters, LETTERS, "_")) {
expect_split(sprintf("^%s$", delim), "[[:word:]]", list("^", "$"))
expect_split(sprintf("^%s@|$", delim), "[|[:word:]]", list("^", "@", "$"))
}
})
test_that("pcre_to_java converts [:xdigits:] correctly", {
test_requires_version("2.0.0")
for (delim in c(
as.character(seq(0, 9)),
"a", "b", "c", "d", "e", "f",
"A", "B", "C", "D", "E", "F"
)
) {
expect_split(sprintf("g%sh", delim), "[[:xdigit:]]", list("g", "h"))
expect_split(sprintf("G%sH|I", delim), "[|[:xdigit:]]", list("G", "H", "I"))
}
}) |
"volatility" <-
function(OHLC, n=10, calc="close", N=260, mean0=FALSE, ...) {
OHLC <- try.xts(OHLC, error=as.matrix)
calc <- match.arg(calc,
c("close","garman.klass","parkinson",
"rogers.satchell","gk.yz","yang.zhang"))
if( calc=="close" ) {
if( NCOL(OHLC) == 1 ) {
r <- ROC(OHLC[, 1], 1, ...)
} else {
r <- ROC(OHLC[, 4], 1, ...)
}
if( isTRUE(mean0) ) {
s <- sqrt(N) * sqrt(runSum(r^2, n-1) / (n-2))
} else {
s <- sqrt(N) * runSD(r, n-1)
}
}
if( calc=="garman.klass" ) {
s <- sqrt( N/n * runSum( .5 * log(OHLC[,2]/OHLC[,3])^2 -
(2*log(2)-1) * log(OHLC[,4]/OHLC[,1])^2 , n ) )
}
if( calc=="parkinson" ) {
s <- sqrt( N/(4*n*log(2)) * runSum( log(OHLC[,2]/OHLC[,3])^2, n ) )
}
if( calc=="rogers.satchell" ) {
s <- sqrt( N/n * runSum(
log(OHLC[,2]/OHLC[,4]) * log(OHLC[,2]/OHLC[,1]) +
log(OHLC[,3]/OHLC[,4]) * log(OHLC[,3]/OHLC[,1]), n ) )
}
if( calc=="gk.yz" ) {
if(is.xts(OHLC)) {
Cl1 <- lag.xts(OHLC[,4])
} else {
Cl1 <- c( NA, OHLC[-NROW(OHLC),4] )
}
s <- sqrt( N/n * runSum(
log(OHLC[,1]/Cl1)^2 +
.5 * log(OHLC[,2]/OHLC[,3])^2 -
(2*log(2)-1) * log(OHLC[,4]/OHLC[,1])^2 , n) )
}
if( calc=="yang.zhang" ) {
if(is.xts(OHLC)) {
Cl1 <- lag.xts(OHLC[,4])
} else {
Cl1 <- c( NA, OHLC[-NROW(OHLC),4] )
}
dots <- list(...)
if(is.null(dots$alpha)) {
alpha <- 1.34
}
if(is.null(dots$k)) {
k <- (alpha-1) / ( alpha + (n+1)/(n-1) )
}
s2o <- N * runVar(log(OHLC[,1] / Cl1), n=n)
s2c <- N * runVar(log(OHLC[,4] / OHLC[,1]), n=n)
s2rs <- volatility(OHLC=OHLC, n=n, calc="rogers.satchell", N=N, ...)
s <- sqrt(s2o + k*s2c + (1-k)*(s2rs^2))
}
reclass(s,OHLC)
} |
"print.variogramModel" =
function (x, ...)
{
df = data.frame(x)
shape.models = c("Mat", "Exc", "Cau", "Ste")
if (!any(match(df[, "model"], shape.models, nomatch=0)))
df$kappa = NULL
if (!any(df[, "anis2"] != 1)) {
df$anis2 = NULL
df$ang2 = NULL
df$ang3 = NULL
if (!any(df[, "anis1"] != 1)) {
df$anis1 = NULL
df$ang1 = NULL
}
}
if (any(match(df[, "model"], "Tab", nomatch=0))) {
df$maxdist = df$range
df$range = NULL
print(df, ...)
cat("covariance table:\n")
tab = attr(x, "table")
idx = round(seq(1, length(tab), length=6))
print(tab[idx])
} else
print(df, ...)
invisible(x)
} |
setGeneric(
"decrease_key",
function(obj, from, to, handle) {
standardGeneric("decrease_key")
},
package = "datastructures"
) |
trendline_summary <- function(x,y,model="line2P", Pvalue.corrected=TRUE, summary=TRUE, eDigit=5)
{
model=model
OK <- complete.cases(x, y)
x <- x[OK]
y <- y[OK]
z<-data.frame(x,y)
z<-na.omit(z)
nrow = nrow(z)
if (model== c("line2P"))
{
Pvalue.corrected=TRUE
formula = 'y = a*x + b'
fit<- lm(y~x)
sum.line2P <- summary(fit)
ss.res<-sum((residuals(fit))^2)
if (summary==TRUE){
print(sum.line2P,digits=eDigit)
}else{}
coeff<-sum.line2P$coefficients
a<-coeff[2,1]
b<-coeff[1,1]
n<-length(x)
pval <- coeff[2,4]
pval<-unname(pval)
r2 <- sum.line2P$r.squared
adjr2<- sum.line2P$adj.r.squared
a = format(a, digits = eDigit)
b = format(b, digits = eDigit)
r2 = format(r2, digits = eDigit)
adjr2 = format(adjr2, digits = eDigit)
pval = format(pval, digits = eDigit)
a=as.numeric(a)
b=as.numeric(b)
param.out<- c(list("a"=a,"b"=b))
}
if (model== c("line3P"))
{
Pvalue.corrected=TRUE
formula = 'y = a*x^2 + b*x + c'
fit<-lm(y~I(x^2)+x)
sum.line3P <- summary(fit)
ss.res<-sum((residuals(fit))^2)
if (summary==TRUE){
print(sum.line3P,digits=eDigit)
}else{}
coeff<-coef(sum.line3P)
a<-coeff[2,1]
b<-coeff[3,1]
c<-coeff[1,1]
n<-length(x)
r2<-sum.line3P$r.squared
adjr2 <- sum.line3P$adj.r.squared
fstat<-sum.line3P$fstatistic
pval<-pf(fstat[1], fstat[2], fstat[3], lower.tail=FALSE)
pval<-unname(pval)
a = format(a, digits = eDigit)
b = format(b, digits = eDigit)
c = format(c, digits = eDigit)
r2 = format(r2, digits = eDigit)
adjr2 = format(adjr2, digits = eDigit)
pval = format(pval, digits = eDigit)
a=as.numeric(a)
b=as.numeric(b)
c=as.numeric(c)
param.out<- c(list("a"=a,"b"=b,"c"=c))
}
if (model== c("log2P"))
{
Pvalue.corrected=TRUE
formula = 'y = a*ln(x) + b'
yadj<-y-min(y)
if (min(x)>0)
{
if (summary==TRUE){
fit0<-lm(y~log(x))
sum.log0<-summary(fit0)
ss.res<-sum((residuals(fit0))^2)
print(sum.log0, digits = eDigit)
}else{}
fit<-lm(yadj~log(x))
sum.log<-summary(fit)
ss.res<-sum((residuals(fit))^2)
a<-sum.log$coefficients[2,1]
b<-sum.log$coefficients[1,1]
b=b+min(y)
fstat<-sum.log$fstatistic
pval<-pf(fstat[1], fstat[2], fstat[3], lower.tail=FALSE)
pval<-unname(pval)
n<-length(x)
r2<-sum.log$r.squared
adjr2 <- sum.log$adj.r.squared
a = format(a, digits = eDigit)
b = format(b, digits = eDigit)
r2 = format(r2, digits = eDigit)
adjr2 = format(adjr2, digits = eDigit)
pval= format(pval, digits = eDigit)
a=as.numeric(a)
b=as.numeric(b)
param.out<- c(list("a"=a,"b"=b))
}else{
stop("
'log2P' model need ALL x values greater than 0. Try other models.")
}
}
if (model== c("exp2P"))
{
formula = 'y = a*exp(b*x)'
n=length(x)
k = 2
fit<-nls(y~SSexp2P(x,a,b),data=z)
sum.exp2P <- summary(fit)
ss.res<-sum((residuals(fit))^2)
ss.total.uncor<-sum(y^2)
ss.total.cor<-sum((y-mean(y))^2)
if (Pvalue.corrected==TRUE){
ss.reg <- ss.total.cor - ss.res
dfR= k-1
}else{
ss.reg <- ss.total.uncor - ss.res
dfR= k
}
dfE= n-k
Fval=(ss.reg/dfR)/(ss.res/dfE)
pval=pf(Fval,dfR,dfE,lower.tail = F)
pval<-unname(pval)
RSE<-sum.exp2P$sigma
SSE<-(RSE^2)*(n-1)
adjr2 <- 1-SSE/((var(y))*(n-1))
r2<-1-(1-adjr2)*((n-k)/(n-1))
if (summary==TRUE){
coeff = coef(sum.exp2P)
cat("\nNonlinear regression model\n")
cat("\nFormula: y = a*exp(b*x)","\n")
df <- sum.exp2P$df
rdf <- df[2L]
cat("\nParameters:\n")
printCoefmat(coeff, digits = eDigit)
cat("\nResidual standard error:",
format(sum.exp2P$sigma, digits = eDigit), "on", rdf, "degrees of freedom","\n")
convInfo = fit$convInfo
iterations<-convInfo$finIter
tolerance<-convInfo$finTol
cat("\nNumber of iterations to convergence:",
format(iterations, digits = eDigit))
cat("\nAchieved convergence tolerance:",format(tolerance, digits = eDigit),"\n")
cat("\nMultiple R-squared:",
format(r2, digits = eDigit), ", Adjusted R-squared: ",
format(adjr2, digits = eDigit))
cat("\nF-statistic:",
format(Fval, digits = eDigit), "on", dfR, "and", dfE, "DF, ", "p-value:", format(pval, digits = eDigit), "\n")
}else{}
coeffs<-sum.exp2P$coefficients
a<-coeffs[1,1]
b<-coeffs[2,1]
a = format(a, digits = eDigit)
b = format(b, digits = eDigit)
r2 = format(r2, digits = eDigit)
adjr2 = format(adjr2, digits = eDigit)
pval= format(pval, digits = eDigit)
a=as.numeric(a)
b=as.numeric(b)
param.out<- c(list("a"=a,"b"=b))
}
if (model== c("exp3P"))
{
formula = 'y = a*exp(b*x) + c'
yadj<-y-min(y)+1
zzz<-data.frame(x,yadj)
n=length(x)
k = 3
fit<-nls(yadj~SSexp3P(x,a,b,c),data=zzz)
sum.exp3P <- summary(fit)
ss.res<-sum((residuals(fit))^2)
ss.total.uncor<-sum(y^2)
ss.total.cor<-sum((y-mean(y))^2)
if (Pvalue.corrected==TRUE){
ss.reg <- ss.total.cor - ss.res
dfR= k-1
}else{
ss.reg <- ss.total.uncor - ss.res
dfR= k
}
dfE= n-k
Fval=(ss.reg/dfR)/(ss.res/dfE)
pval=pf(Fval,dfR,dfE,lower.tail = F)
pval<-unname(pval)
RSE<-sum.exp3P$sigma
SSE<-(RSE^2)*(n-1)
adjr2 <- 1-SSE/((var(y))*(n-1))
r2<-1-(1-adjr2)*((n-k)/(n-1))
if (summary==TRUE){
coeffadj = coef(sum.exp3P)
ab.param<-coeffadj[1:2,]
c.param<-coeffadj[3,]
c.p1<-c.param[1]
c.p1 = c.p1 + min(y)-1
c.se<-c.param[2]
c.tval<-c.p1/c.se
c.pval<-2 * pt(abs(c.tval), n-k, lower.tail = FALSE)
c<-c(c.p1,c.se,c.tval,c.pval)
coeff.re.adj<- rbind(ab.param,c)
cat("\nNonlinear regression model\n")
cat("\nFormula: y = a*exp(b*x) + c","\n")
df <- sum.exp3P$df
rdf <- df[2L]
cat("\nParameters:\n")
printCoefmat(coeff.re.adj, digits = eDigit)
cat("\nResidual standard error:",
format(sum.exp3P$sigma, digits = eDigit), "on", rdf, "degrees of freedom","\n")
convInfo = fit$convInfo
iterations<-convInfo$finIter
tolerance<-convInfo$finTol
cat("\nNumber of iterations to convergence:",
format(iterations, digits = eDigit))
cat("\nAchieved convergence tolerance:",format(tolerance, digits = eDigit),"\n")
cat("\nMultiple R-squared:",
format(r2, digits = eDigit), ", Adjusted R-squared: ",
format(adjr2, digits = eDigit))
cat("\nF-statistic:",
format(Fval, digits = eDigit), "on", dfR, "and", dfE, "DF, ", "p-value:", format(pval, digits = eDigit), "\n")
}else{}
coeff<-sum.exp3P$coefficients
a<-coeff[1,1]
b<-coeff[2,1]
c<-coeff[3,1]+min(y)-1
a = format(a, digits = eDigit)
b = format(b, digits = eDigit)
c = format(c, digits = eDigit)
r2 = format(r2, digits = eDigit)
adjr2 = format(adjr2, digits = eDigit)
pval= format(pval, digits = eDigit)
a=as.numeric(a)
b=as.numeric(b)
c=as.numeric(c)
param.out<- c(list("a"=a,"b"=b,"c"=c))
}
if (model== c("power2P"))
{
formula = 'y = a*x^b'
n<-length(x)
k = 2
if (min(x)>0){
fit<-nls(y ~ SSpower2P(x,a,b),data=z)
sum.power2P <- summary(fit)
ss.res<-sum((residuals(fit))^2)
ss.total.uncor<-sum(y^2)
ss.total.cor<-sum((y-mean(y))^2)
if (Pvalue.corrected==TRUE){
ss.reg <- ss.total.cor - ss.res
dfR= k-1
}else{
ss.reg <- ss.total.uncor - ss.res
dfR= k
}
dfE = n-k
Fval = (ss.reg/dfR)/(ss.res/dfE)
pval = pf(Fval,dfR,dfE,lower.tail = F)
pval <- unname(pval)
RSE<-sum.power2P$sigma
SSE<-(RSE^2)*(n-1)
adjr2 <- 1-SSE/((var(y))*(n-1))
r2 <- 1-(1-adjr2)*((n-k)/(n-1))
if (summary==TRUE){
coeff = coef(sum.power2P)
ab.param<-coeff[1:2,]
cat("\nNonlinear regression model\n")
cat("\nFormula: y = a*x^b","\n")
df <- sum.power2P$df
rdf <- df[2L]
cat("\nParameters:\n")
printCoefmat(coeff, digits = eDigit)
cat("\nResidual standard error:",
format(sum.power2P$sigma, digits = eDigit), "on", rdf, "degrees of freedom","\n")
convInfo = fit$convInfo
iterations<-convInfo$finIter
tolerance<-convInfo$finTol
cat("\nNumber of iterations to convergence:",
format(iterations, digits = eDigit))
cat("\nAchieved convergence tolerance:",format(tolerance, digits = eDigit),"\n")
cat("\nMultiple R-squared:",
format(r2, digits = eDigit), ", Adjusted R-squared: ",
format(adjr2, digits = eDigit))
cat("\nF-statistic:",
format(Fval, digits = eDigit), "on", dfR, "and", dfE, "DF, ", "p-value:", format(pval, digits = eDigit), "\n")
}else{}
coeffs<-sum.power2P$coefficients
a<-coeffs[1,1]
b<-coeffs[2,1]
a = format(a, digits = eDigit)
b = format(b, digits = eDigit)
r2 = format(r2, digits = eDigit)
adjr2 = format(adjr2, digits = eDigit)
pval = format(pval, digits = eDigit)
a=as.numeric(a)
b=as.numeric(b)
param.out<- c(list("a"=a,"b"=b))
}else{
stop("
'power2P' model need ALL x values greater than 0. Try other models.")
}
}
if (model== c("power3P"))
{
formula = 'y = a*x^b + c'
yadj<-y-min(y)+1
zzz<-data.frame(x,yadj)
n<-length(x)
k = 3
if (min(x)>0){
fit<-nls(yadj~SSpower3P(x,a,b,c),data=zzz)
sum.power3P <- summary(fit)
ss.res<-sum((residuals(fit))^2)
ss.total.uncor<-sum(y^2)
ss.total.cor<-sum((y-mean(y))^2)
if (Pvalue.corrected==TRUE){
ss.reg <- ss.total.cor - ss.res
dfR= k-1
}else{
ss.reg <- ss.total.uncor - ss.res
dfR= k
}
dfE= n-k
Fval=(ss.reg/dfR)/(ss.res/dfE)
pval=pf(Fval,dfR,dfE,lower.tail = F)
pval<-unname(pval)
RSE<-sum.power3P$sigma
SSE<-(RSE^2)*(n-1)
adjr2 <- 1-SSE/((var(y))*(n-1))
r2<-1-(1-adjr2)*((n-k)/(n-1))
if (summary==TRUE){
coeffadj = coef(sum.power3P)
ab.param<-coeffadj[1:2,]
c.param<-coeffadj[3,]
c.p1<-c.param[1]
c.p1 = c.p1 + min(y)-1
c.se<-c.param[2]
c.tval<-c.p1/c.se
c.pval<-2 * pt(abs(c.tval), n-k, lower.tail = FALSE)
c<-c(c.p1,c.se,c.tval,c.pval)
coeff.re.adj<- rbind(ab.param,c)
cat("\nNonlinear regression model\n")
cat("\nFormula: y = a*x^b + c","\n")
df <- sum.power3P$df
rdf <- df[2L]
cat("\nParameters:\n")
printCoefmat(coeff.re.adj, digits = eDigit)
cat("\nResidual standard error:",
format(sum.power3P$sigma, digits = eDigit), "on", rdf, "degrees of freedom","\n")
convInfo = fit$convInfo
iterations<-convInfo$finIter
tolerance<-convInfo$finTol
cat("\nNumber of iterations to convergence:",
format(iterations, digits = eDigit))
cat("\nAchieved convergence tolerance:",format(tolerance, digits = eDigit),"\n")
cat("\nMultiple R-squared:",
format(r2, digits = eDigit), ", Adjusted R-squared: ",
format(adjr2, digits = eDigit))
cat("\nF-statistic:",
format(Fval, digits = eDigit), "on", dfR, "and", dfE, "DF, ", "p-value:", format(pval, digits = eDigit), "\n")
}else{}
coeff<-sum.power3P$coefficients
a<-coeff[1,1]
b<-coeff[2,1]
c<-coeff[3,1]
c<-c+min(y)-1
a = format(a, digits = eDigit)
b = format(b, digits = eDigit)
c = format(c, digits = eDigit)
r2 = format(r2, digits = eDigit)
adjr2 = format(adjr2, digits = eDigit)
pval = format(pval, digits = eDigit)
a=as.numeric(a)
b=as.numeric(b)
c=as.numeric(c)
param.out<- c(list("a"=a,"b"=b,"c"=c))
}else{
stop("
'power3P' model need ALL x values greater than 0. Try other models.")
}
}else{
Check<-c("line2P","line3P","log2P","exp2P","exp3P","power2P","power3P")
if (!model %in% Check)
stop("
\"model\" should be one of c(\"lin2P\",\"line3P\",\"log2P\",\"exp2P\",\"exp3P\",\"power2P\",\"power3P\".")
}
nrow = as.numeric(nrow)
r2=as.numeric(r2)
adjr2=as.numeric(adjr2)
pval=as.numeric(pval)
AIC = as.numeric(format(AIC(fit), digits = eDigit))
BIC = as.numeric(format(BIC(fit), digits = eDigit))
ss.res=as.numeric(format(ss.res, digits = eDigit))
if (summary==TRUE){
cat("\nN:", nrow, ", AIC:", AIC, ", BIC: ", BIC, "\nResidual Sum of Squares: ", ss.res,"\n")
}else{}
invisible(list(formula=formula, parameter=param.out, R.squared=r2, adj.R.squared=adjr2, p.value = pval,
N = nrow, AIC=AIC, BIC=BIC, RSS=ss.res))
} |
format_data <- function(data, y, X, time,
lon = "lon", lat = "lat",
station = NULL, nknots = 25L,
covariance = c("squared-exponential",
"exponential", "matern"),
fixed_intercept = FALSE,
cluster = c("pam", "kmeans")) {
data <- as.data.frame(data)
cluster <- match.arg(cluster)
covariance <- match.arg(covariance)
if (is.null(time)) {
data$time <- 1
time <- "time"
}
yearID <- as.numeric(data[, time, drop = TRUE])
yearID <- yearID - min(yearID) + 1
if (is.null(station)) {
stationID <- seq_len(nrow(data))
} else {
stationID <- as.numeric(forcats::as_factor(data[, station, drop = TRUE]))
}
data$stationID <- stationID
if (length(unique(stationID)) < length(stationID)) {
first_instance <- which(!duplicated(stationID))
if (cluster == "pam") {
knots <- cluster::pam(data[first_instance, c(lon, lat), drop = FALSE], nknots)$medoids
} else {
if (cluster == "kmeans") {
knots <- stats::kmeans(data[first_instance, c(lon, lat), drop = FALSE], nknots)$centers
} else {
knots <- data[first_instance, c(lon, lat)]
}
}
distKnots <- as.matrix(dist(knots))
ix <- sort(data[first_instance, "stationID"], index.return = TRUE)$ix
distAll <- as.matrix(stats::dist(rbind(data[first_instance, c(lon, lat)][ix, ], knots)))
nLocs <- length(first_instance)
} else {
if (cluster == "pam") {
knots <- cluster::pam(data[, c(lon, lat), drop = FALSE], nknots)$medoids
} else {
if (cluster == "kmeans") {
knots <- stats::kmeans(data[, c(lon, lat), drop = FALSE], nknots)$centers
} else {
knots <- data[, c(lon, lat), drop = FALSE]
}
}
distKnots <- as.matrix(dist(knots))
distAll <- as.matrix(stats::dist(rbind(data[, c(lon, lat), drop = FALSE], knots)))
nLocs <- nrow(data)
}
if (covariance == "squared-exponential") {
distKnots <- distKnots^2
distAll <- distAll^2
}
distKnots21 <- t(distAll[-seq_len(nLocs), -seq(nLocs + 1, ncol(distAll))])
spatglm_data <- list(
nKnots = nknots,
nLocs = nLocs,
nT = max(yearID),
N = length(y),
stationID = stationID,
yearID = yearID,
y = y,
distKnots = distKnots,
distKnots21 = distKnots21,
X = X,
nCov = if(fixed_intercept) 0 else ncol(X)
)
list(spatglm_data = spatglm_data, knots = knots)
} |
source("utils.R")
wml_is_italic <- function(doc_){
!inherits(xml_find_first(doc_, "/w:document/w:rPr/w:i"), "xml_missing")
}
wml_is_bold <- function(doc_){
!inherits(xml_find_first(doc_, "/w:document/w:rPr/w:b"), "xml_missing")
}
wml_is_underline <- function(doc_){
!inherits(xml_find_first(doc_, "/w:document/w:rPr/w:u"), "xml_missing")
}
test_that("wml - font size", {
fp <- fp_text(font.size = 10)
xml_ <- format(fp, type = "wml")
doc <- read_xml( wml_str(xml_) )
sz <- xml_find_first(doc, "/w:document/w:rPr/w:sz")
szCs <- xml_find_first(doc, "/w:document/w:rPr/w:szCs")
expect_false(inherits( szCs, "xml_missing") )
expect_false(inherits( sz, "xml_missing") )
expect_equal(xml_attr(sz, "val"), xml_attr(szCs, "val"))
expect_equal(xml_attr(sz, "val"), expected = "20")
})
test_that("wml - bold italic underlined", {
fp_bold <- fp_text(bold = TRUE)
fp_italic <- update(fp_bold, bold = FALSE, italic = TRUE)
fp_bold_italic <- update(fp_bold, italic = TRUE)
fp_underline <- fp_text(underlined = TRUE )
xml_bold_ <- format(fp_bold, type = "wml")
xml_italic_ <- format(fp_italic, type = "wml")
xml_bolditalic_ <- format(fp_bold_italic, type = "wml")
xml_underline_ <- format(fp_underline, type = "wml")
doc_bold_ <- read_xml( wml_str(xml_bold_) )
doc_italic_ <- read_xml( wml_str(xml_italic_) )
doc_bolditalic_ <- read_xml( wml_str(xml_bolditalic_) )
doc_underline_ <- read_xml( wml_str(xml_underline_) )
expect_equal(wml_is_bold(doc_bold_), TRUE)
expect_equal(
xml_attr(xml_find_first(doc_bold_, "/w:document/w:rPr/w:i"), "val"),
"false")
expect_equal(
xml_attr(xml_find_first(doc_italic_, "/w:document/w:rPr/w:b"), "val"),
"false")
expect_equal(
xml_attr(xml_find_first(doc_italic_, "/w:document/w:rPr/w:i"), "val"),
"true")
expect_equal(
xml_attr(xml_find_first(doc_italic_, "/w:document/w:rPr/w:b"), "val"),
"false")
expect_equal(
xml_attr(xml_find_first(doc_italic_, "/w:document/w:rPr/w:i"), "val"),
"true")
expect_equal(wml_is_bold(doc_bolditalic_), TRUE)
expect_equal(wml_is_italic(doc_bolditalic_), TRUE)
expect_equal(
xml_attr(xml_find_first(doc_bold_, "/w:document/w:rPr/w:u"), "val"),
"none")
expect_equal(
xml_attr(xml_find_first(doc_underline_, "/w:document/w:rPr/w:u"), "val"),
"single")
})
test_that("wml - font name", {
fontname = "Arial"
fp_ <- fp_text(font.family = fontname)
xml_ <- format(fp_, type = "wml")
doc_ <- read_xml( wml_str(xml_) )
node <- xml_find_first(doc_, "/w:document/w:rPr/w:rFonts")
expect_false(inherits(node, "xml_missing"))
expect_equal( xml_attr(node, "ascii"), fontname )
expect_equal( xml_attr(node, "hAnsi"), fontname )
expect_equal( xml_attr(node, "cs"), fontname )
})
test_that("wml - font color", {
fp_ <- fp_text(color = grDevices::rgb(.8, .2, .1, .6))
xml_ <- format(fp_, type = "wml")
doc_ <- read_xml( wml_str(xml_) )
node <- xml_find_first(doc_, "/w:document/w:rPr/w:color")
expect_false(inherits(node, "xml_missing"))
expect_equal( xml_attr(node, "val"), "CC331A" )
node <- xml_find_first(doc_, "/w:document/w:rPr/w14:textFill")
expect_false(inherits(node, "xml_missing"))
expect_equal( xml_attr(xml_child(node, "w14:solidFill/w14:srgbClr"), "val"), "CC331A" )
expect_equal( xml_attr(xml_child(node, "w14:solidFill/w14:srgbClr/w14:alpha"), "val"), "60000" )
})
test_that("wml - shading color", {
fp_ <- fp_text(shading.color = rgb(1,0,1))
xml_ <- format(fp_, type = "wml")
doc_ <- read_xml( wml_str(xml_) )
node <- xml_find_first(doc_, "/w:document/w:rPr/w:shd")
expect_false(inherits(node, "xml_missing"))
expect_equal( xml_attr(node, "fill"), "FF00FF" )
})
pml_has_true_attr <- function(doc_, what = "b"){
rpr <- xml_find_first(doc_, "/a:document/a:rPr")
val <- xml_attr(rpr, what)
!is.na( val ) && val == "1"
}
pml_attr <- function(doc_, what = "u"){
rpr <- xml_find_first(doc_, "/a:document/a:rPr")
xml_attr(rpr, what)
}
test_that("pml - font size", {
fp <- fp_text(font.size = 10)
xml_ <- format(fp, type = "pml")
doc_ <- read_xml( pml_str(xml_) )
rpr <- xml_find_first(doc_, "/a:document/a:rPr")
expect_equal(xml_attr(rpr, "sz"), "1000")
})
test_that("pml - bold italic underlined", {
fp_bold <- fp_text(bold = TRUE)
fp_italic <- update(fp_bold, bold = FALSE, italic = TRUE)
fp_bold_italic <- update(fp_bold, italic = TRUE)
fp_underline <- fp_text(underlined = TRUE )
xml_bold_ <- format(fp_bold, type = "pml")
xml_italic_ <- format(fp_italic, type = "pml")
xml_bolditalic_ <- format(fp_bold_italic, type = "pml")
xml_underline_ <- format(fp_underline, type = "pml")
doc_bold_ <- read_xml( pml_str(xml_bold_) )
doc_italic_ <- read_xml( pml_str(xml_italic_) )
doc_bolditalic_ <- read_xml( pml_str(xml_bolditalic_) )
doc_underline_ <- read_xml( pml_str(xml_underline_) )
expect_equal(pml_has_true_attr(doc_bold_, "b"), TRUE)
expect_equal(pml_has_true_attr(doc_bold_, "i"), FALSE)
expect_equal(pml_has_true_attr(doc_bold_, "u"), FALSE)
expect_equal(pml_has_true_attr(doc_italic_, "b"), FALSE)
expect_equal(pml_has_true_attr(doc_italic_, "i"), TRUE)
expect_equal(pml_has_true_attr(doc_italic_, "u"), FALSE)
expect_equal(pml_has_true_attr(doc_bolditalic_, "b"), TRUE)
expect_equal(pml_has_true_attr(doc_bolditalic_, "i"), TRUE)
expect_equal(pml_has_true_attr(doc_bolditalic_, "u"), FALSE)
expect_equal(pml_has_true_attr(doc_underline_, "b"), FALSE)
expect_equal(pml_has_true_attr(doc_underline_, "i"), FALSE)
expect_equal(pml_attr(doc_underline_, "u"), "sng")
})
test_that("pml - font name", {
fontname = "Arial"
fp_ <- fp_text(font.family = fontname)
xml_ <- format(fp_, type = "pml")
doc_ <- read_xml( pml_str(xml_) )
node <- xml_find_first(doc_, "/a:document/a:rPr/a:latin")
expect_false(inherits(node, "xml_missing"))
expect_equal( xml_attr(node, "typeface"), fontname )
node <- xml_find_first(doc_, "/a:document/a:rPr/a:cs")
expect_false(inherits(node, "xml_missing"))
expect_equal( xml_attr(node, "typeface"), fontname )
})
test_that("pml - font color", {
fp_ <- fp_text(color= rgb(1, 0, 0, .5 ))
xml_ <- format(fp_, type = "pml")
doc_ <- read_xml( pml_str(xml_) )
node <- xml_find_first(doc_, "/a:document/a:rPr/a:solidFill/a:srgbClr")
expect_false(inherits(node, "xml_missing"))
expect_equal( xml_attr(node, "val"), "FF0000" )
node <- xml_find_first(doc_, "/a:document/a:rPr/a:solidFill/a:srgbClr/a:alpha")
expect_equal( xml_attr(node, "val"), "50196" )
})
test_that("css", {
fp <- fp_text(font.size = 10, color = "
expect_true(has_css_color(fp, "color", "rgba\\(0,255,255,0.20\\)"))
expect_true(has_css_attr(fp, "font-family", "'Arial'"))
expect_true(has_css_attr(fp, "font-size", "10.0pt"))
expect_true(has_css_attr(fp, "font-style", "normal"))
expect_true(has_css_attr(fp, "font-weight", "normal"))
expect_true(has_css_attr(fp, "text-decoration", "none"))
expect_true(has_css_color(fp, "background-color", "rgba\\(0,255,255,0.80\\)"))
fp <- fp_text(bold = TRUE, italic = TRUE, underlined = TRUE)
expect_true(has_css_attr(fp, "font-style", "italic"))
expect_true(has_css_attr(fp, "font-weight", "bold"))
expect_true(has_css_attr(fp, "text-decoration", "underline"))
}) |
cdf.ensembleBMAgamma <-
function(fit, ensembleData, values, dates = NULL, ...)
{
powfun <- function(x,power) x^power
powinv <- function(x,power) x^(1/power)
weps <- 1.e-4
matchITandFH(fit,ensembleData)
ensembleData <- ensembleData[,matchEnsembleMembers(fit,ensembleData)]
M <- !dataNA(ensembleData,observations=FALSE)
if (!all(M)) ensembleData <- ensembleData[M,]
fitDates <- modelDates(fit)
M <- matchDates( fitDates, ensembleValidDates(ensembleData), dates=dates)
if (!all(M$ens)) ensembleData <- ensembleData[M$ens,]
if (!all(M$fit)) fit <- fit[fitDates[M$fit]]
if (is.null(dates)) dates <- modelDates(fit)
nObs <- nrow(ensembleData)
if (!nObs) stop("no data")
Dates <- ensembleValidDates(ensembleData)
nForecasts <- ensembleSize(ensembleData)
CDF <- matrix( NA, nrow = nObs, ncol = length(values))
dimnames(CDF) <- list(dataObsLabels(ensembleData), as.character(values))
ensembleData <- ensembleForecasts(ensembleData)
l <- 0
for (d in dates) {
l <- l + 1
WEIGHTS <- fit$weights[,d]
if (all(Wmiss <- is.na(WEIGHTS))) next
I <- which(as.logical(match(Dates, d, nomatch = 0)))
for (i in I) {
f <- ensembleData[i,]
M <- is.na(f) | Wmiss
VAR <- (fit$varCoefs[1,d] + fit$varCoefs[2,d]*f)^2
fTrans <- sapply(f, powfun, power = fit$power)
MEAN <- apply(rbind(1, fTrans) * fit$biasCoefs[,d], 2, sum)
W <- WEIGHTS
if (any(M)) {
W <- W + weps
W <- W[!M]/sum(W[!M])
}
CDF[i,] <- sapply( sapply( values, powfun, power = fit$power),
cdfBMAgamma, WEIGHTS = W, MEAN = MEAN[!M], VAR = VAR[!M])
}
}
CDF
} |
source("tinytest-settings.R")
using("ttdo")
expect_identical_xl(
faviconDuckDuckGo("address.domain"),
"https://icons.duckduckgo.com/ip3/address.domain.ico"
)
expect_identical_xl(
faviconPlease("https://address.domain/path", functions = NULL),
"https://icons.duckduckgo.com/ip3/address.domain.ico"
) |
survDataCheck <- function(data, diagnosis.plot = FALSE) {
if (!("data.frame" %in% class(data))) {
return(msgTableSingleton("dataframeExpected",
"A dataframe is expected."))
}
ref.names <- c("replicate","conc","time","Nsurv")
missing.names <- ref.names[which(is.na(match(ref.names, names(data))))]
if (length(missing.names) != 0) {
msg <- paste("The column ", missing.names,
" is missing.", sep = "")
return(msgTableSingleton("missingColumn",msg))
}
errors <- msgTableCreate()
subdata <- split(data, list(data$replicate), drop = TRUE)
if (any(unlist(lapply(subdata, function(x) x$time[1] != 0)))) {
msg <- "Data are required at time 0 for each replicate."
errors <- msgTableAdd(errors, "firstTime0", msg)
}
if (!is.double(data$conc) && !is.integer(data$conc)) {
msg <- "Column 'conc' must contain only numerical values."
errors <- msgTableAdd(errors, "concNumeric", msg)
}
if (!is.numeric(data$time)) {
msg <- "Column 'time' must contain only numerical values."
errors <- msgTableAdd(errors, "timeNumeric", msg)
}
if (!is.integer(data$Nsurv)) {
msg <- "Column 'Nsurv' must contain only integer values."
errors <- msgTableAdd(errors, "NsurvInteger", msg)
}
table <- subset(data, select = -c(replicate))
if (any(table < 0.0, na.rm = TRUE)) {
msg <- "Data must contain only positive values."
errors <- msgTableAdd(errors, "tablePositive", msg)
}
datatime0 <- data[data$time == 0, ]
if (any(datatime0$Nsurv == 0)) {
msg <- "Nsurv should be different to 0 at time 0 for each concentration and each replicate."
errors <- msgTableAdd(errors, "Nsurv0T0", msg)
}
ID <- idCreate(data)
if (any(duplicated(ID))) {
msg <- paste("The (replicate, time) pair ",
ID[duplicated(ID)],
" is duplicated.", sep = "")
errors <- msgTableAdd(errors, "duplicatedID", msg)
}
df_variation <- data %>%
filter(!is.na(Nsurv)) %>%
group_by(replicate) %>%
arrange(time) %>%
mutate(Nprec = ifelse(time == min(time), Nsurv, lag(Nsurv))) %>%
mutate(decrease = Nsurv <= Nprec) %>%
summarise(decreasing = all(decrease))
if (! all(df_variation$decreasing)) {
replicates <- df_variation$replicate[! df_variation$decreasing]
msg <- paste(
"'Nsurv' increases at some time points in replicate(s) ",
paste(replicates, collapse=", "),
".",
sep = "")
errors <- msgTableAdd(errors, "NsurvIncrease", msg)
}
df_checkMaxTimeSurv <- data %>%
filter(!is.na(Nsurv)) %>%
group_by(replicate) %>%
filter(time == max(time))
df_checkMaxTimeConc <- data %>%
filter(!is.na(conc)) %>%
group_by(replicate) %>%
filter(time == max(time))
if(!all(df_checkMaxTimeConc$time >= df_checkMaxTimeSurv$time) ){
msg <- "In each 'replicate', maximum time for concentration record should
be greater or equal to maximum time in survival data observation."
errors <- msgTableAdd(errors, "maxTimeDiffer", msg)
}
if (diagnosis.plot && "NsurvIncrease" %in% errors$id) {
survDataPlotFull(data, ylab = "Number of surviving individuals")
}
return(errors)
} |
skip_if_no_token <- function() {
if (identical(Sys.getenv("TOKEN_PATH"), "")) {
skip("No authentication available")
} else {
tokens <- readRDS(Sys.getenv("TOKEN_PATH"))
tokens[[length(tokens)]]
}
}
token <- skip_if_no_token()
testthat::test_that("create, update, upload file, delete", {
skip_if_no_token()
board <- trelloR::add_board(
name = paste0("trelloR testing: ", Sys.Date()),
body = list(defaultLists = TRUE, desc = "Test trelloR with testthat"),
token = token
)
testthat::expect_is(board, "list")
testthat::expect_equal(board$desc, "Test trelloR with testthat")
updated <- trelloR::update_resource(
"board",
id = board$id,
body = list(desc = "Updated description"),
token = token
)
testthat::expect_is(updated, "list")
testthat::expect_equal(updated$desc, "Updated description")
list_ <- trelloR::add_list(
board$id,
name = "Testing",
pos = 1L,
token = token
)
testthat::expect_is(list_, "list")
testthat::expect_equal(list_$name, "Testing")
card <- trelloR::add_card(
list_$id,
body = list(
name = "Testing",
desc = "A testing card."
),
token = token
)
testthat::expect_is(card, "list")
testthat::expect_equal(card$desc, "A testing card.")
attachment <- trelloR::create_resource(
resource = "card",
path = "attachments",
id = card$id,
body = list(
name = "A dog in yellow tuque",
file = httr::upload_file("attachment.jpg"),
setCover = TRUE
),
token = token
)
cover <- get_resource("card", id = card$id, token = token)
testthat::expect_is(attachment, "list")
testthat::expect_equal(cover$idAttachmentCover, attachment$id)
deleted <- trelloR::delete_resource("board", board$id, token = token)
testthat::expect_is(deleted, "list")
testthat::expect_null(deleted[["_value"]])
}) |
gaussianKernel <- function(size,sig){
x = seq(-(size-1)/2, (size-1)/2, length=size)
x = matrix(x, size, size)
z = exp(- (x^2 + t(x)^2) / (2*sig^2))
z = z / sum(z)
return(z)
}
utils::globalVariables(".")
gaussianFilter <- function(surfaceMat,
res,
wavelength,
filtertype = "bp",
filterSize = NULL){
if(filtertype %in% c("lp","hp")){
sig <- (wavelength/res)/(2*pi)
if(is.null(filterSize)){
filterSize <- {2*ceiling(2.6*sig) + 1} %>%
magrittr::add(. %% 2)
}
kern <- gaussianKernel(size = filterSize,
sig = sig)
surfaceMatP <- surfaceMat
if((filterSize - dim(surfaceMat)[1]) %% 2 == 1){
surfaceMatP <- surfaceMatP %>%
rbind(rep(0,times = ncol(.)))
}
if((filterSize - dim(surfaceMat)[2]) %% 2 == 1){
surfaceMatP <- surfaceMatP %>%
cbind(rep(0,times = nrow(.)))
}
dimPadded <- dim(surfaceMatP) + filterSize
imPadded <- surfaceMatP %>%
imager::as.cimg() %>%
imager::pad(nPix = dimPadded[1] - dim(surfaceMatP)[1],
axes = "y",
pos = 0) %>%
imager::pad(nPix = dimPadded[2] - dim(surfaceMatP)[2],
axes = "x",
pos = 0) %>%
as.matrix()
kernPadded <- kern %>%
imager::as.cimg() %>%
imager::pad(nPix = {dimPadded[1] - filterSize} %>%
magrittr::add(. %% 2),
axes = "x",
pos = 0) %>%
imager::pad(nPix = {dimPadded[2] - filterSize} %>%
magrittr::add(. %% 2),
axes = "y",
pos = 0) %>%
as.matrix()
}
if(filtertype == "lp"){
imFiltered <- imPadded %>%
fft() %>%
magrittr::multiply_by(fft(kernPadded)) %>%
fft(inverse = TRUE) %>%
magrittr::divide_by(prod(dimPadded)) %>%
fftshift()
imFiltered <- Re(imFiltered) %>%
imager::as.cimg() %>%
imager::crop.borders(nx = {dimPadded[1] - dim(surfaceMatP)[1]} %>%
magrittr::add(-1*(. %% 2)) %>%
magrittr::divide_by(2),
ny = {dimPadded[2] - dim(surfaceMatP)[2]} %>%
magrittr::add(-1*(. %% 2)) %>%
magrittr::divide_by(2)) %>%
as.matrix()
}
else if(filtertype == "hp"){
imFilteredLP <- imPadded %>%
fft() %>%
magrittr::multiply_by(fft(kernPadded)) %>%
fft(inverse = TRUE) %>%
magrittr::divide_by(prod(dimPadded)) %>%
fftshift()
imFiltered <- imPadded - imFilteredLP
imFiltered <- Re(imFiltered) %>%
imager::as.cimg() %>%
imager::crop.borders(nx = {dimPadded[1] - dim(surfaceMatP)[1]} %>%
magrittr::add(-1*(. %% 2)) %>%
magrittr::divide_by(2),
ny = {dimPadded[2] - dim(surfaceMatP)[2]} %>%
magrittr::add(-1*(. %% 2)) %>%
magrittr::divide_by(2)) %>%
as.matrix()
}
else if(filtertype == "bp"){
imFiltered <- gaussianFilter(surfaceMat = surfaceMat %>%
gaussianFilter(res = res,
wavelength = max(wavelength),
filtertype = "hp"),
res = res,
wavelength = min(wavelength),
filtertype = "lp")
}
if((dim(imFiltered)[1] - dim(surfaceMat)[1]) %% 2 == 1){
imFiltered <- imFiltered[1:(nrow(imFiltered) - 1),1:ncol(imFiltered)]
}
if((dim(imFiltered)[2] - dim(surfaceMat)[2]) %% 2 == 1){
imFiltered <- imFiltered[1:nrow(imFiltered),1:(ncol(imFiltered) - 1)]
}
return(imFiltered)
} |
findRmd <- function(path = ".",
pattern = "Hello World",
case.sensitive = TRUE,
show.results = TRUE,
copy = FALSE,
folder = "findRmd",
overwrite = TRUE) {
fls <- list.files(path, pattern = "\\.rmd$", full.names = T, recursive = T, ignore.case = T)
if (length(fls) > 0) {
hits <- NULL
for (i in 1:length(fls)) {
if (case.sensitive == FALSE) {
pattern <- tolower(pattern)
a <- tolower(readLines(fls[i], warn = F))
} else {
a <- readLines(fls[i], warn = F)
}
if (length(grep(pattern, a)) > 0) {
path_to_file <- fls[i]
line <- which(grepl(pattern, a))
hit <- cbind.data.frame(path_to_file, line)
hits <- rbind.data.frame(hits, hit)
rm(hit)
}
}
if (copy == TRUE) {
dir.create(folder)
if (!is.null(hits)) {
for (i in 1:nrow(hits)) {
file.copy(hits$path_to_file[i], folder, overwrite = overwrite)
}
}
}
message(paste0("Number of R markdown files scanned: ", length(fls)))
if (!is.null(hits)) {
message(paste0("Number of R markdown files with matching content: ", length(unique(hits$path_to_file))))
message(paste0("Total number of matches: ", nrow(hits)))
if (show.results == TRUE) hits
} else {
message("Number of R markdown files with matching content: 0")
message("Total number of matches: 0")
}
} else {
message(paste0("No R markdown files found!"))
}
} |
context("dplyr do")
skip_databricks_connect()
sc <- testthat_spark_connection()
test_requires("ggplot2")
diamonds_tbl <- testthat_tbl("diamonds")
test_that("the (serial) implementation of 'do' functions as expected", {
test_requires("dplyr")
R <- diamonds %>%
filter(color == "E" | color == "I", clarity == "SI1") %>%
group_by(color, clarity) %>%
do(model = lm(price ~ x + y + z, data = .))
S <- diamonds_tbl %>%
filter(color == "E" | color == "I", clarity == "SI1") %>%
group_by(color, clarity) %>%
do(model = ml_linear_regression(., price ~ x + y + z))
R <- arrange(R, as.character(color), as.character(clarity))
S <- arrange(S, as.character(color), as.character(clarity))
expect_identical(nrow(R), nrow(S))
for (i in seq_len(nrow(R))) {
lhs <- R$model[[i]]
rhs <- S$model[[i]]
expect_equal(lhs$coefficients, rhs$coefficients)
}
}) |
require(OneStep)
require(actuar)
n <- 1e3
x <- rexp(n)
try( benchonestep(x, "exp", "jaimeleraisindetable") )
try( benchonestep(x, "exp") )
try( benchonestep(x, "exp2", "mle") )
try( benchonestep(matrix(x, 2, n/2), "exp2", "mle") ) |
poped.choose(2,5)
poped.choose("foo",66)
poped.choose(NULL,"hello") |
rp.tkrplot <- function(panel, name, plotfun, action = NA, mousedrag = NA, mouseup = NA,
hscale = 1, vscale = 1, pos = NULL, foreground = NULL, background = NULL,
margins=c(0, 0, 0, 0), parentname = deparse(substitute(panel)),
mar = par()$mar, ...) {
if (!requireNamespace("tkrplot", quietly = TRUE)) stop("the tkrplot package is not available.")
panelname <- panel$panelname
name <- deparse(substitute(name))
if (is.null(pos) && length(list(...)) > 0) pos <- list(...)
pf <- function() {
panel <- rp.control.get(panelname)
panel <- plotfun(panel)
rp.control.put(panelname, panel)
}
if (is.function(action))
fa <- function(x, y) {
panel <- rp.control.get(panelname)
panel <- action(panel, x ,y)
rp.control.put(panelname, panel)
}
else
fa <- NA
if (is.function(mousedrag))
fd <- function(x, y) {
panel <- rp.control.get(panelname)
panel <- mousedrag(panel, x, y)
rp.control.put(panelname, panel)
}
else
fd <- NA
if (is.function(mouseup))
fu <- function(x, y) {
panel <- rp.control.get(panelname);
panel <- mouseup(panel, x ,y)
rp.control.put(panelname, panel)
}
else
fu <- NA
if (rp.widget.exists(panelname, parentname))
parent <- rp.widget.get(panelname, parentname)
else
parent <- panel
if (is.list(pos) && !is.null(pos$grid))
parent <- rp.widget.get(panelname, pos$grid)
widget <- w.tkrplot(parent, plotfun = pf, action = fa, mousedrag = fd, mouseup = fu,
hscale, vscale, pos, foreground, background, margins, name, mar)
rp.widget.put(panelname, name, widget)
if (.rpenv$savepanel) rp.control.put(panelname, panel)
invisible(panelname)
}
.w.tkrplot <- function (parent, fun, hscale = 1, vscale = 1, foreground = NULL, background = NULL,
margins=c(0, 0, 0, 0)) {
image <- paste("Rplot", .make.tkindex(), sep = "")
handshakereverse(.my.tkdev, hscale, vscale)
foreground <- handshake(tkimage.create, 'photo', file = foreground)
w <- as.numeric(handshake(tcl, "image","width", foreground))
h <- as.numeric(handshake(tcl, "image","height", foreground))
pw <- par("pin")[1]; par(pin=c(pw,(h/w)*pw))
try(fun())
handshake(.Tcl, paste("image create Rplot", image))
lab <- handshake(tkcanvas, parent, width=w+margins[1]+margins[3], height=h+margins[2]+margins[4])
handshake(tkcreate, lab, 'image', margins[1], margins[2], image=foreground, anchor="nw")
lab$margins <- margins
w.setbackground(lab, background)
handshake(tkbind, lab, "<Destroy>", function() handshake(.Tcl, paste("image delete", image)))
lab$image <- image; lab$fun <- fun; lab$hscale <- hscale; lab$vscale <- vscale
lab$foreground <- foreground; lab$w <- w; lab$h <- h
lab
}
.w.coords <- function(plot, x, y, parplt, parusr) {
xClick <- x
yClick <- y
width <- as.numeric(handshake(tclvalue, handshake(tkwinfo, "reqwidth",plot)))
height <- as.numeric(handshake(tclvalue, handshake(tkwinfo, "reqheight",plot)))
xMin <- parplt[1] * width; xMax <- parplt[2] * width
yMin <- parplt[3] * height; yMax <- parplt[4] * height
rangeX <- parusr[2] - parusr[1]
rangeY <- parusr[4] - parusr[3]
xClick <- as.numeric(xClick)+0.5
yClick <- as.numeric(yClick)+0.5
yClick <- height - yClick
xPlotCoord <- parusr[1]+(xClick-xMin)*rangeX/(xMax-xMin)
yPlotCoord <- parusr[3]+(yClick-yMin)*rangeY/(yMax-yMin)
c(xPlotCoord, yPlotCoord, width, height, xClick, yClick)
}
w.tkrplot <- function(parent, plotfun, action = NA, mousedrag = NA, mouseup = NA,
hscale = 1, vscale = 1, pos = NULL, foreground = NULL, background = NULL,
margins=c(0, 0, 0, 0), name = paste("plot", .nc(), sep = ""), mar) {
if (requireNamespace("tkrplot", quietly = TRUE)) {
widget <- w.createwidget(parent, pos, NULL, tkrplottype = TRUE)
widget$.type <- "tkrplot"
plotter <- function() {
par(mar = mar)
plotfun()
assign(paste(name, ".plt", sep = ""), par('plt'), envir = .rpenv)
assign(paste(name, ".usr", sep = ""), par('usr'), envir = .rpenv)
}
if (is.null(foreground)) {
widget$.widget <- handshake(tkrplot::tkrplot, parent$.handle, plotter,
hscale = hscale, vscale = vscale)
w.setbackground(widget$.widget, background)
}
else {
widget$.widget <- .w.tkrplot(parent$.handle, plotter, hscale = hscale, vscale = vscale,
foreground = foreground, background = background,
margins = c(deparse(margins[1]), deparse(margins[2]),
deparse(margins[3]),deparse(margins[4])))
}
fdown <- function(x, y) {
coords <- .w.coords(widget$.widget, x, y,
eval(parse(text = paste(name, ".plt", sep = "")), envir=.rpenv),
eval(parse(text = paste(name, ".usr", sep = "")), envir=.rpenv))
action(coords[1], coords[2])
}
fdrag <- function(x, y) {
coords <- .w.coords(widget$.widget, x, y,
eval(parse(text = paste(name, ".plt", sep = "")), envir = .rpenv),
eval(parse(text = paste(name, ".usr", sep = "")), envir = .rpenv))
mousedrag(coords[1], coords[2])
}
fup <- function(x, y) {
coords <- .w.coords(widget$.widget, x, y,
eval(parse(text = paste(name, ".plt", sep = "")), envir = .rpenv),
eval(parse(text = paste(name, ".usr", sep = "")), envir = .rpenv))
mouseup(coords[1], coords[2])
}
if (is.function(action)) handshake(tkbind, widget$.widget, "<Button-1>", fdown)
if (is.function(mousedrag)) handshake(tkbind, widget$.widget, "<B1-Motion>", fdrag)
if (is.function(mouseup)) handshake(tkbind, widget$.widget, "<ButtonRelease-1>", fup)
handshake(tkconfigure, widget$.widget, cursor = "hand2")
w.appearancewidget(widget, NULL, NULL, NULL)
}
else
widget <- warning("Package TkRplot is not installed.")
widget
}
rp.tkrreplot <- function(panel, name) {
if (!exists(panel$panelname, .rpenv, inherits = FALSE))
panelname <- deparse(substitute(panel))
else
panelname <- panel$panelname
name <- deparse(substitute(name))
img <- rp.widget.get(panelname, name)
handshake(tkrplot::tkrreplot, img$.widget)
invisible(panelname)
}
w.tkrreplot <- function(img) {
handshake(tkrplot::tkrreplot, img$.widget)
} |
expected <- eval(parse(text="c(3L, 3L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L)"));
test(id=0, code={
argv <- eval(parse(text="list(c(\"\\\"a\\\"\", \"\\\"b\\\"\", NA, NA, NA, \"\\\"f\\\"\", \"\\\"g\\\"\", \"\\\"h\\\"\", \"\\\"i\\\"\", \"\\\"j\\\"\", \"\\\"k\\\"\", \"\\\"l\\\"\"), \"w\", FALSE)"));
(nchar(argv[[1]], argv[[2]], argv[[3]]));
}, o=expected); |
apollo_cnl <- function(cnl_settings, functionality){
modelType = "CNL"
if(is.null(cnl_settings[["componentName"]])){
cnl_settings[["componentName"]] = ifelse(!is.null(cnl_settings[['componentName2']]),
cnl_settings[['componentName2']], modelType)
test <- functionality=="validate" && cnl_settings[["componentName"]]!='model' && !apollo_inputs$silent
if(test) apollo_print(paste0('Apollo found a model component of type ', modelType,
' without a componentName. The name was set to "',
cnl_settings[["componentName"]],'" by default.'))
}
if(functionality=="validate"){
apollo_modelList <- tryCatch(get("apollo_modelList", envir=parent.frame(), inherits=FALSE), error=function(e) c())
apollo_modelList <- c(apollo_modelList, cnl_settings$componentName)
if(anyDuplicated(apollo_modelList)) stop("Duplicated componentName found (", cnl_settings$componentName,
"). Names must be different for each component.")
assign("apollo_modelList", apollo_modelList, envir=parent.frame())
}
if(!is.null(cnl_settings[["utilities"]])) names(cnl_settings)[which(names(cnl_settings)=="utilities")]="V"
apollo_inputs = tryCatch(get("apollo_inputs", parent.frame(), inherits=FALSE),
error=function(e) return( list(apollo_control=list(cpp=FALSE)) ))
if( !is.null(apollo_inputs[[paste0(cnl_settings$componentName, "_settings")]]) && (functionality!="preprocess") ){
tmp <- apollo_inputs[[paste0(cnl_settings$componentName, "_settings")]]
if(is.null(tmp$V) ) tmp$V <- cnl_settings$V
if(is.null(tmp$cnlNests) ) tmp$cnlNests <- cnl_settings$cnlNests
if(is.null(tmp$cnlStructure)) tmp$cnlStructure <- cnl_settings$cnlStructure
cnl_settings <- tmp
rm(tmp)
} else {
cnl_settings <- apollo_preprocess(inputs = cnl_settings, modelType,
functionality, apollo_inputs)
if(apollo_inputs$apollo_control$cpp) if(!apollo_inputs$silent) apollo_print("No C++ optimisation available for CNL")
cnl_settings$probs_CNL <- function(cnl_settings, all=FALSE){
cnl_settings$choiceNA = FALSE
if(all(is.na(cnl_settings$choiceVar))){
cnl_settings$choiceVar = cnl_settings$alternatives[1]
cnl_settings$choiceNA = TRUE
}
cnl_settings$V <- mapply(function(v,a) apollo_setRows(v, !a, 0),
cnl_settings$V, cnl_settings$avail, SIMPLIFY=FALSE)
if(!all) VSubs <- Reduce('+', mapply("*", cnl_settings$Y, cnl_settings$V, SIMPLIFY=FALSE)) else VSubs <- do.call(pmax, cnl_settings$V)
cnl_settings$V <- lapply(cnl_settings$V, "-", VSubs)
rm(VSubs)
cnl_settings$V <- mapply('*', cnl_settings$V, cnl_settings$avail, SIMPLIFY = FALSE)
cnl_settings$V = lapply(X=cnl_settings$V, FUN=exp)
cnl_settings$V <- mapply('*', cnl_settings$V, cnl_settings$avail, SIMPLIFY = FALSE)
denom_within = list()
nests = nrow(cnl_settings$cnlStructure)
for(t in 1:nests){
denom_within[[t]]=0
for(j in 1:cnl_settings$nAlt){
denom_within[[t]] = denom_within[[t]] +
(cnl_settings$cnlStructure[t,j]*cnl_settings$V[[cnl_settings$altnames[j]]])^(1/cnl_settings$cnlNests[[t]])
}
}
Pwithin = list()
for(j in 1:cnl_settings$nAlt){
Pwithin[[j]] = list()
for(t in 1:nests){
Pwithin[[j]][[t]] = (cnl_settings$cnlStructure[t,j]*cnl_settings$V[[cnl_settings$altnames[j]]])^(1/cnl_settings$cnlNests[[t]])/(denom_within[[t]]+(denom_within[[t]]==0))
}
}
Pnest = list()
denom_nest = 0
for(t in 1:nests) denom_nest = denom_nest + denom_within[[t]]^cnl_settings$cnlNests[[t]]
for(t in 1:nests) Pnest[[t]] = (denom_within[[t]]^cnl_settings$cnlNests[[t]])/denom_nest
Palts = list()
for(j in 1:cnl_settings$nAlt){
Palts[[j]]=0
for(t in 1:nests) Palts[[j]] = Palts[[j]] + Pnest[[t]]*Pwithin[[j]][[t]]
}
names(Palts) <- names(cnl_settings$V)
if(!(all && cnl_settings$choiceNA)) Palts[["chosen"]] <- Reduce('+', mapply('*', cnl_settings$Y, Palts, SIMPLIFY=FALSE))
if(!all) Palts <- Palts[["chosen"]]
return(Palts)
}
apollo_beta <- tryCatch(get("apollo_beta", envir=parent.frame(), inherits=TRUE),
error=function(e) return(NULL))
test <- !is.null(apollo_beta) && functionality %in% c("preprocess", "gradient")
test <- test && all(sapply(cnl_settings$V, is.function))
test <- test && apollo_inputs$apollo_control$analyticGrad
cnl_settings$gradient <- FALSE
if(test){
cnl_settings$dV <- apollo_dVdB(apollo_beta, apollo_inputs, cnl_settings$V)
cnl_settings$gradient <- !is.null(cnl_settings$dV)
}; rm(test)
if(functionality=="preprocess"){
cnl_settings$V <- NULL
cnl_settings$cnlNests <- NULL
cnl_settings$cnlStructure <- NULL
return(cnl_settings)
}
}
if(any(sapply(cnl_settings$V, is.function))){
cnl_settings$V = lapply(cnl_settings$V, function(f) if(is.function(f)) f() else f )
}
if(any(sapply(cnl_settings$cnlNests, is.function))){
cnl_settings$cnlNests = lapply(cnl_settings$cnlNests, function(f) if(is.function(f)) f() else f )
}
if(is.function(cnl_settings$cnlStructure)) cnl_settings$cnlStructure <- cnl_settings$cnlStructure()
cnl_settings$V <- lapply(cnl_settings$V, function(v) if(is.matrix(v) && ncol(v)==1) as.vector(v) else v)
cnl_settings$V <- cnl_settings$V[cnl_settings$altnames]
if(!all(cnl_settings$rows)){
cnl_settings$V <- lapply(cnl_settings$V, apollo_keepRows, r=cnl_settings$rows)
}
if(functionality=="validate"){
if(!apollo_inputs$apollo_control$noValidation) apollo_validate(cnl_settings, modelType,
functionality, apollo_inputs)
if(!apollo_inputs$apollo_control$noDiagnostics) apollo_diagnostics(cnl_settings, modelType, apollo_inputs)
testL <- cnl_settings$probs_CNL(cnl_settings)
if(any(!cnl_settings$rows)) testL <- apollo_insertRows(testL, cnl_settings$rows, 1)
if(all(testL==0)) stop('All observations have zero probability at starting value for model component "', cnl_settings$componentName,'"')
if(any(testL==0) && !apollo_inputs$silent && apollo_inputs$apollo_control$debug) apollo_print(paste0('Some observations have zero probability at starting value for model component "', cnl_settings$componentName,'"'))
return(invisible(testL))
}
if(functionality=="zero_LL"){
for(i in 1:cnl_settings$nAlt) if(length(cnl_settings$avail[[i]])==1) cnl_settings$avail[[i]] <- rep(cnl_settings$avail[[i]], cnl_settings$nObs)
nAvAlt <- rowSums(matrix(unlist(cnl_settings$avail), ncol=cnl_settings$nAlt))
P = 1/nAvAlt
if(any(!cnl_settings$rows)) P <- apollo_insertRows(P, cnl_settings$rows, 1)
return(P)
}
if(functionality=="shares_LL"){
for(i in 1:length(cnl_settings$avail)) if(length(cnl_settings$avail[[i]])==1) cnl_settings$avail[[i]] <- rep(cnl_settings$avail[[i]], cnl_settings$nObs)
nAvAlt <- rowSums(do.call(cbind, cnl_settings$avail))
Y = do.call(cbind,cnl_settings$Y)
if(var(nAvAlt)==0){
Yshares = colSums(Y)/nrow(Y)
P = as.vector(Y%*%Yshares)
} else {
mnl_ll = function(b, A, Y) as.vector(Y%*%c(b,0) - log(rowSums( A%*%exp(c(b,0)) )))
A = do.call(cbind, cnl_settings$avail)
b = maxLik::maxLik(mnl_ll, start=rep(0, cnl_settings$nAlt - 1),
method='BFGS', finalHessian=FALSE, A=A, Y=Y)$estimate
P = exp(mnl_ll(b, A, Y))
}
if(any(!cnl_settings$rows)) P <- apollo_insertRows(P, cnl_settings$rows, 1)
return(P)
}
if(functionality %in% c("estimate","conditionals", "output", "components")){
P <- cnl_settings$probs_CNL(cnl_settings, all=FALSE)
if(any(!cnl_settings$rows)) P <- apollo_insertRows(P, cnl_settings$rows, 1)
return(P)
}
if(functionality %in% c("prediction","raw")){
P <- cnl_settings$probs_CNL(cnl_settings, all=TRUE)
if(any(!cnl_settings$rows)) P <- lapply(P, apollo_insertRows, r=cnl_settings$rows, val=NA)
return(P)
}
if(functionality=='report'){
P <- list()
apollo_inputs$silent <- FALSE
P$data <- utils::capture.output(apollo_diagnostics(cnl_settings, modelType, apollo_inputs, param=FALSE))
P$param <- utils::capture.output(apollo_diagnostics(cnl_settings, modelType, apollo_inputs, data =FALSE))
return(P)
}
} |
tar_test("aws_fst_tbl packages", {
target <- tar_target(x, "x_value", format = "aws_fst_tbl")
out <- sort(store_get_packages(target$store))
exp <- sort(c("paws", "fst", "tibble"))
expect_equal(out, exp)
})
tar_test("inherits from tar_external", {
store <- tar_target(x, "x_value", format = "aws_fst_tbl")$store
expect_true(inherits(store, "tar_external"))
})
tar_test("store_row_path()", {
store <- tar_target(x, "x_value", format = "aws_fst_tbl")$store
store$file$path <- "path"
expect_equal(store_row_path(store), "path")
})
tar_test("store_path_from_record()", {
store <- tar_target(x, "x_value", format = "aws_fst_tbl")$store
record <- record_init(path = "path", format = "aws_fst_tbl")
expect_equal(store_path_from_record(store, record), "path")
})
tar_test("validate aws_fst_tbl", {
skip_if_not_installed("paws")
skip_if_not_installed("fst")
skip_if_not_installed("tibble")
tar_script(list(tar_target(x, "x_value", format = "aws_fst_tbl")))
expect_silent(tar_validate(callr_function = NULL))
}) |
plot.mixdata <- function(x, mixpar = NULL, dist = "norm", root = FALSE,
ytop = NULL, clwd = 1, main, sub, xlab, ylab, bty, ...)
{
mixdataobj<-x
plot.mix(mixdataobj, mixpar, dist, root, ytop, clwd, main,
sub, xlab, ylab, bty, ...)
invisible()
} |
create_tool_overrides <- function(tool_name, params) {
if (tool_name == "export_geotiff" | tool_name == "export_raster") {
params$file$io <- "Output"
} else if (tool_name == "export_shapes" |
tool_name == "export_shapes_to_kml") {
params$file$io <- "Output"
} else if (tool_name == "clip_grid_with_rectangle") {
params$output$feature <- "Grid"
} else if (tool_name == "tiling") {
params$tiles_path$io <- "Output"
} else if (tool_name == "tpi_based_landform_classification") {
if (!"radius_a_min" %in% names(params)) {
names(params)[names(params) == "radius_a"] <- "radius_a_min"
params$radius_a_min$alias <- "radius_a_min"
params$radius_a_min$identifier <- "RADIUS_A_MIN"
params$radius_a_min$default <- 0
names(params)[names(params) == "radius_b"] <- "radius_b_min"
params$radius_b_min$alias <- "radius_b_min"
params$radius_b_min$identifier <- "RADIUS_B_MIN"
params$radius_b_min$default <- 0
params$radius_a_max <- params$radius_a_min
params$radius_a_max$alias <- "radius_a_max"
params$radius_a_max$identifier <- "RADIUS_A_MAX"
params$radius_a_max$default <- 100
params$radius_b_max <- params$radius_b_min
params$radius_b_max$name <- "Large Scale"
params$radius_b_max$alias <- "radius_b_max"
params$radius_b_max$identifier <- "RADIUS_B_MAX"
params$radius_b_max$default <- 1000
}
} else if (tool_name == "topographic_position_index_tpi") {
if (!"radius_min" %in% names(params)) {
names(params)[names(params) == "radius"] <- "radius_min"
params$radius_min$alias <- "radius_min"
params$radius_min$identifier <- "RADIUS_MIN"
params$radius_min$default <- 0
params$radius_max <- params$radius_min
params$radius_max$alias <- "radius_max"
params$radius_max$identifier <- "RADIUS_MAX"
params$radius_max$default <- 100
}
}
params
} |
Compute_log_likelihood_given_params <- function(fit_, it_retained, parallel, ncores) {
if (is_censored(fit_$data)) {
censor_code <- censor_code_rl(fit_$data$left, fit_$data$right)
censor_code_filters <- lapply(0:3, FUN = function(x) censor_code == x)
names(censor_code_filters) <- 0:3
dpred <- function(iter) {
log(dmixcens(
xlefts = fit_$data$left,
xrights = fit_$data$right,
c_code_filters = censor_code_filters,
locations = fit_$means[[iter]],
scales = fit_$sigmas[[iter]],
weights = fit_$weights[[iter]],
distr.k = fit_$distr.k
))
}
}
else {
dpred <- function(iter) {
log(dmix(fit_$data,
locations = fit_$means[[iter]],
scales = fit_$sigmas[[iter]],
weights = fit_$weights[[iter]],
distr.k = fit_$distr.k
))
}
}
unlist(parallel::mclapply(
X = it_retained,
FUN = function(it) sum(dpred(it)),
mc.cores = ifelse(test = parallel, yes = ncores, no = 1)
))
}
Convert_to_matrix_list <- function(fitlist, thinning_to = 1000, parallel = TRUE, ncores = parallel::detectCores()) {
if (Sys.info()[["sysname"]] == "Windows") parallel <- FALSE
if (is_semiparametric(fitlist[[1]])) {
fitlist <- lapply(fitlist, function(fit) {
fit$sigmas <- fill_sigmas(fit)
fit
})
}
Nit <- length(fitlist[[1]]$means)
it_retained <- compute_thinning_grid(Nit, thinning_to = thinning_to)
if (is_semiparametric(fitlist[[1]])) {
lapply(X = fitlist, function(fit_i) {
cbind(
ncomp = fit_i$R[it_retained],
Sigma = fit_i$S[it_retained],
Latent_variable = fit_i$U[it_retained],
log_likelihood = Compute_log_likelihood_given_params(fit_i, it_retained, parallel, ncores)
)
})
}
else {
lapply(X = fitlist, function(fit_i) {
cbind(
ncomp = fit_i$R[it_retained],
Latent_variable = fit_i$U[it_retained],
log_likelihood = Compute_log_likelihood_given_params(fit_i, it_retained, parallel, ncores)
)
})
}
}
convert_to_mcmc <- function(fitlist, thinning_to = 1000, ncores = parallel::detectCores()) {
coda::as.mcmc.list(coda::as.mcmc(lapply(Convert_to_matrix_list(fitlist, thinning_to = thinning_to, ncores = ncores), coda::mcmc)))
} |
Agg.Sim = function(x,min,max,s,w,b){
PMax = x
A = x
B = x
for (j in 1:ncol(x))
{
for (i in 1:nrow(x))
{
PMax[i,j] = (integrate(Vectorize(function(x) {prod(ppert(x,min[j],A[,j][-i],max[j],s))*dpert(x,min[j],B[,j][[i]],max[j],s)}),min[j],max[j])) $value
}}
PMax = PMax[,]
PMin = x
max = apply(x,2,max)
min = apply(x,2,min)
for (j in 1:ncol(x))
{
for (i in 1:nrow(x))
{
PMin[i,j] = (integrate(Vectorize(function(x) {prod(1-ppert(x,min[j],A[,j][-i],max[j],s))*dpert(x,min[j],B[,j][[i]],max[j],s)}),min[j],max[j])) $value
}}
PMin = PMin[,]
NrEsp = nrow(x)
A = x
B = x
PMax = vector("list", ncol(x))
PMin = vector("list", ncol(x))
for (k in 1:(ncol(x)))
{
PMax[[k]] = matrix(0,nrow=NrEsp,ncol=NrEsp)
PMin[[k]] = matrix(0,nrow=NrEsp,ncol=NrEsp)
for (j in 1:(NrEsp))
{
for (i in 1:(NrEsp))
{
PMax[[k]][i,j] = (integrate(Vectorize(function(x) {(ppert(x,min[k],A[i,k],max[k],s))*dpert(x,min[k],B[j,k],max[k],s)}),min[k],max[k]))$value
PMin[[k]][i,j] = (integrate(Vectorize(function(x) {(1-ppert(x,min[k],A[i,k],max[k],s))*dpert(x,min[k],B[j,k],max[k],s)}),min[k],max[k]))$value
}}}
S = vector("list", ncol(x))
for (k in 1:(ncol(x)))
{
S[[k]] = PMax[[k]]/PMin[[k]]
S[[k]] = ifelse(S[[k]]>1,1/S[[k]],S[[k]])
S[[k]] = ifelse(S[[k]]>0.999,1,S[[k]])
rownames(S[[k]]) = paste0("Exp",1:NrEsp)
colnames(S[[k]]) = paste0("Exp",1:NrEsp)
}
names(S) = paste0("Crit",1:ncol(x))
AE = vector("list", ncol(x))
for (k in 1:(ncol(x)))
{
AE[[k]] = apply(S[[k]],1,sum)
AE[[k]] = (AE[[k]]-1)/(NrEsp-1)
}
names(AE) = paste0("Crit",1:ncol(x))
Soma = vector("list", ncol(x))
RAD = vector("list", ncol(x))
CDC = vector("list", ncol(x))
for (k in 1:(ncol(x)))
{
Soma[[k]] = sum(AE[[k]])
RAD[[k]] = AE[[k]]/Soma[[k]]
CDC[[k]] = b*w+(1-b)*RAD[[k]]
}
names(CDC) = paste0("Crit",1:ncol(x))
CDC = t(matrix(unlist(CDC),ncol(x),NrEsp))
rownames(CDC) = paste0("Exp",1:NrEsp)
colnames(CDC) = paste0("Crit",1:ncol(x))
A.mode = vector("list", ncol(x))
for (k in 1:(ncol(x)))
{
A.mode[[k]] = sum(CDC[[k]]*A[,k])
}
names(A.mode) = paste0("Crit",1:ncol(x))
A.mode = unlist(A.mode)
Result = list(SM = S, CDC = CDC, Agg.value = A.mode)
Result
} |
plotweights <- function(dataset, cw1 = 0.95, cw2 = 0.5, cw3 = 0.25, arrow = FALSE, plotall = FALSE, plotallenv, ThreeD = FALSE){
a <- c(cw1, cw2, cw3)
b <- a[order (-a)]
cw <- cw1
cw1 <- b[1]
cw2 <- b[2]
cw3 <- b[3]
WeightDist <- ceiling(100*mean(as.numeric(cumsum(dataset$ModWeight) <= cw1)))
ConfidenceSet <- dataset[which(cumsum(dataset$ModWeight) <= cw1), ]
if(nrow(ConfidenceSet) == 0){
ConfidenceSet <- dataset[1, ]
}
dataset <- dataset[order(-dataset$ModWeight), ]
dataset$cw1 <- as.numeric(cumsum(dataset$ModWeight) <= cw1)
dataset$cw2 <- as.numeric(cumsum(dataset$ModWeight) <= cw2)
dataset$cw3 <- as.numeric(cumsum(dataset$ModWeight) <= cw3)
if(all(dataset$cw3 == 0)){
dataset$cw3[1] <- 1
}
if(all(dataset$cw2 == 0)){
dataset$cw2[1] <- 1
}
if(all(dataset$cw1 == 0)){
dataset$cw1[1] <- 1
}
dataset$cw.full <- dataset$cw1 + dataset$cw2 + dataset$cw3
if(ThreeD == TRUE){
stop("3D plotting temporarily disabled due to issues with the rgl package.")
} else {
dataset$cw.full[which(dataset$cw.full == 3)] <- cw3
dataset$cw.full[which(dataset$cw.full == 2)] <- cw2
dataset$cw.full[which(dataset$cw.full == 1)] <- cw1
dataset$cw.full[which(dataset$cw.full == 0)] <- 1
with(dataset, {
if(arrow == FALSE){
ARR <- ggplot(dataset, aes(x = WindowClose, y = WindowOpen, z = cw.full))+
geom_tile(aes(fill = cw.full))+
scale_fill_gradientn(colours = c("black", "white"), breaks=c(b[1], b[2], b[3]), limits = c(0, 1), name = "")+
theme_climwin()+
theme(legend.position = c(0.75, 0.3))+
ggtitle(paste(WeightDist, "% of models fall within the \n", 100*cw, "% confidence set", sep = ""))+
ylab("Window open")+
xlab("Window close")
if(plotall == TRUE){
plotallenv$cw <- ARR
} else {
ARR
}
} else if(arrow == TRUE){
CIRC <- circle(centre = c(dataset$WindowClose[1], dataset$WindowOpen[1]), diameter = 5, npoints = 100)
colnames(CIRC) <- c("WindowClose", "WindowOpen")
CIRC$cw.full <- 0
ARR <- ggplot(dataset, aes(x = WindowClose, y = WindowOpen, z = cw.full))+
geom_tile(aes(fill = cw.full))+
scale_fill_gradientn(colours = c("black", "white"), breaks=c(b[1], b[2], b[3]), limits = c(0, 1), name = "")+
theme_climwin()+
theme(legend.position = c(0.75, 0.3))+
ggtitle(paste(WeightDist, "% of models fall within the \n", 100*cw, "% confidence set", sep = ""))+
ylab("Window open")+
xlab("Window close")+
geom_path(data = CIRC, aes(x = WindowClose, y = WindowOpen), size = 1.2, colour = "black")+
geom_segment(aes(x = WindowClose[1], y = 0, xend = WindowClose[1], yend = (WindowOpen[1] - 2.5)),
size = 1, linetype = "dashed") +
geom_segment(aes(x = 0, y = WindowOpen[1], xend = (WindowClose[1] - 2.5), yend = WindowOpen[1]),
size = 1, linetype = "dashed")
if(plotall == TRUE){
plotallenv$cw <- ARR
} else {
ARR
}
}
}
)
}
} |
test_that("FSelectorGeneticSearch", {
test_fselector("genetic_search", term_evals = 10, real_evals = 10)
}) |
skip_if_not(exists("token"))
if (!exists("verifyFields", mode = "function")) source("global.R")
context("01. Locations Discovery Service")
expectedFields = list(
locationCode = "character",
locationName = "character",
description = "character",
deployments = "integer",
hasDeviceData = "logical",
hasPropertyData = "logical",
bbox = "list",
lon = "double",
lat = "double",
depth = "double",
dataSearchURL = "character"
)
expectedTreeFields = list(
locationCode = "character",
locationName = "character",
description = "character",
hasDeviceData = "logical",
hasPropertyData = "logical",
children = "list"
)
test_that("01. Get all locations", {
result = onc$getLocations()
expect_true(verifyFields(result[[1]], expectedFields))
expect_gt(length(result), 500)
})
test_that("02. Get locations hierarchy", {
result = onc$getLocationHierarchy(list(locationCode = "SAAN"))
row1 = result[[1]]
expect_true(verifyFields(row1, expectedTreeFields))
expect_equal(length(result), 1)
expect_true("children" %in% names(row1))
expect_gt(length(row1$children), 2)
})
test_that("03. Filter locationCode", {
result = onc$getLocations(list(locationCode = "CQSBG"))
expect_true(verifyFields(result[[1]], expectedFields))
expect_equal(length(result), 1)
expect_equal(result[[1]]$locationName, "Bubbly Gulch")
})
test_that("04. Filter locationName", {
result = onc$getLocations(list(locationName = "Bubbly Gulch"))
expect_true(verifyFields(result[[1]], expectedFields))
expect_equal(length(result), 1)
expect_equal(result[[1]]$locationCode, "CQSBG")
})
test_that("05. Filter deviceCategoryCode", {
result = onc$getLocations(list(deviceCategoryCode = "CTD"))
expect_true(verifyFields(result[[1]], expectedFields))
expect_gt(length(result), 50)
})
test_that("06. Filter deviceCode", {
result = onc$getLocations(list(deviceCode = "NORTEKADCP9917"))
expect_true(verifyFields(result[[1]], expectedFields))
expect_gte(length(result), 1)
})
test_that("07. Filter propertyCode", {
result = onc$getLocations(list(propertyCode = "co2concentration"))
expect_true(verifyFields(result[[1]], expectedFields))
expect_gte(length(result), 1)
})
test_that("08. Filter dataProductCode", {
result = onc$getLocations(list(dataProductCode = "MP4V"))
expect_true(verifyFields(result[[1]], expectedFields))
expect_gte(length(result), 20)
})
test_that("09. Filter includeChildren", {
result = onc$getLocations(list(includeChildren = "true", locationCode = "SAAN"))
expect_true(verifyFields(result[[1]], expectedFields))
expect_gte(length(result), 30)
})
test_that("10. ISO Date Range", {
result = onc$getLocations(list(dateFrom = "2014-02-24T00:00:01.000Z", dateTo = "2014-03-24T00:00:01.000Z"))
expect_true(verifyFields(result[[1]], expectedFields))
expect_gte(length(result), 100)
})
test_that("11. Wrong locationCode", {
result = onc$getLocations(list(locationCode = "CQS34543BG"))
expect_equal(length(result$errors), 1)
expect_true(isErrorResponse(result))
})
test_that("12. No locations found", {
result = onc$getLocations(list(locationCode = "SAAN", dateTo = "1995-03-24T00:00:01.000Z"))
expect_equal(typeof(result), "list")
expect_equal(length(result), 0)
}) |
gni_search <- function(sci, per_page = NULL, page = NULL,
justtotal = FALSE, parse_names = FALSE, search_term = NULL, ...) {
pchk(search_term, "sci")
query <- tc(list(search_term = sci, per_page = per_page,
page = page))
cli <- crul::HttpClient$new(paste0(gni_base(), "name_strings.json"),
headers = tx_ual, opts = list(...))
tt <- cli$get(query = argsnull(query))
tt$raise_for_status()
out <- jsonlite::fromJSON(tt$parse("UTF-8"), FALSE)
if (justtotal) {
out$name_strings_total
} else {
df <- dt2df(lapply(out$name_strings, function(x)
data.frame(t(data.frame(c( checknull(x[["name"]]), checknull(x[["id"]]),
checknull(x[["lsid"]]), checknull(x[["uuid_hex"]]),
checknull(x[["resource_url"]]) ))))), idcol = FALSE)
df <- colClasses(df, "character")
if (NROW(df) != 0) {
names(df) <- c("name","id","lsid","uuid_hex","resource_url")
}
if (parse_names) {
data.frame(df, gni_parse(as.character(df$name)),
stringsAsFactors = FALSE)
} else {
df
}
}
} |
library(difR)
library(ltm)
data(GMAT, package = "difNLR")
data <- GMAT[, 1:20]
group <- GMAT[, "group"]
(fit1PL <- difLord(
Data = data, group = group, focal.name = 1, model = "1PL",
p.adjust.method = "none", purify = FALSE
))
(fit2PL <- difLord(
Data = data, group = group, focal.name = 1, model = "2PL",
p.adjust.method = "none", purify = FALSE
))
guess <- itemParEst(data, model = "3PL")[, 3]
(fit3PL <- difLord(
Data = data, group = group, focal.name = 1, model = "3PL",
c = guess, p.adjust.method = "none", purify = FALSE
)) |
Opt1=function(X,Y,alpha,K,nk){
n=nrow(X)
p=ncol(X)
nk=n/K
L1=c(1:K)
Rm=matrix(rep(0, nk*K),ncol=K)
mr=matrix(rep(0,K*nk), ncol=nk)
for(i in 1:K ) {
mr[i, ]=sample(1:n,nk,replace=T)
r=matrix(c(1:nk,mr[i, ]),ncol=nk,byrow=T)
Rm[,i]=r[2,]
R=matrix(rep(0, nk*n),ncol=n)
R[t(r)]=1
X1=R%*%X
Y1=R%*%Y
Hr=X1%*%solve(crossprod(X1))%*%t(X1)
I1=diag(rep(1,nk))
SX=(t(Y1)%*%(I1-Hr)%*%Y1)/(nk-p)
SY=sqrt(t(Y1)%*%(I1-Hr)%*%Y1)/(nk-p)
C1=sum(diag(X1%*%solve(crossprod(X1))%*%t(X1)))/nk
L1[i]=2*SY*C1*qt(1-alpha/2,nk-p)
}
opt1=Rm[,which.min(L1)]
Yopt1=Y[opt1]
Xopt1=X[opt1,]
Bopt1=solve(crossprod(Xopt1))%*%t(Xopt1)%*%Yopt1
MUopt1=Xopt1%*%Bopt1
Nopt1=length(Yopt1)
E3=(t(Yopt1-MUopt1)%*%(Yopt1-MUopt1))/Nopt1
A3=sum(abs(Yopt1-MUopt1))/Nopt1
return(list(MUopt1=MUopt1,Bopt1=Bopt1,MAEMUopt1=A3,MSEMUopt1=E3,opt1=opt1,Yopt1=Yopt1))
} |
test_that("as_factor", {
x = as_factor(c("a", "b"), c("a", "b"))
y = as_factor(c("a", "b"), c("b", "a"))
expect_factor(x, levels = c("a", "b"))
expect_factor(y, levels = c("b", "a"))
expect_equal(levels(x), c("a", "b"))
expect_equal(levels(y), c("b", "a"))
z = as_factor(x, levels(y))
expect_factor(z, levels = c("a", "b"))
expect_equal(levels(z), levels(y))
}) |
biomasse <- function(input , climdata, annee=3)
{
if(class(input)=="numeric"){input <- as.data.frame(as.list(input))}
Eb <- input[1,1]
Eimax <- input[1,2]
K <- input[1,3]
Lmax <- input[1,4]
A <- input[1,5]
B <- input[1,6]
TI <- input[1,7]
if (is.null(annee)){
annee <- input[1,8]
}
PAR<-0.5*0.01*climdata$RG[climdata$ANNEE==annee]
Tmoy<-(climdata$Tmin[climdata$ANNEE==annee]+
climdata$Tmax[climdata$ANNEE==annee])/2
Tmoy[Tmoy<0]<-0
ST<-Tmoy
for (i in (2:length(Tmoy)))
{
ST[i]<-ST[i-1]+Tmoy[i]
}
Tr<-(1/B)*log(1+exp(A*TI))
LAI<-Lmax*((1/(1+exp(-A*(ST-TI))))-exp(B*(ST-(Tr))))
LAI[LAI<0]<-0
U<-Eb*Eimax*(1-exp(-K*LAI))*PAR
BIOMASSE<-sum(U)
U <- cumsum(U)
U
} |
get_ned <- function(template,
label,
res = "1",
raw.dir = "./RAW/NED",
extraction.dir = paste0("./EXTRACTIONS/", label, "/NED"),
raster.options = c("COMPRESS=DEFLATE",
"ZLEVEL=9",
"INTERLEAVE=BAND"),
force.redo = F) {
raw.dir <- normalizePath(paste0(raw.dir,"/."), mustWork = FALSE)
extraction.dir <- normalizePath(paste0(extraction.dir,"/."), mustWork = FALSE)
dir.create(raw.dir, showWarnings = FALSE, recursive = TRUE)
dir.create(extraction.dir, showWarnings = FALSE, recursive = TRUE)
template <- sp::spTransform(polygon_from_extent(template), sp::CRS("+proj=longlat +ellps=WGS84"))
extent.latlon <- raster::extent(template)
if (file.exists(paste0(extraction.dir, "/", label, "_NED_", res, ".tif")) & !force.redo) {
extracted.DEM <- raster::raster(paste0(extraction.dir, "/", label, "_NED_", res, ".tif"))
return(extracted.DEM)
}
wests <- seq(ceiling(abs(extent.latlon@xmax)), ceiling(abs(extent.latlon@xmin)))
norths <- seq(ceiling(abs(extent.latlon@ymin)), ceiling(abs(extent.latlon@ymax)))
tilesLocations <- as.matrix(expand.grid(norths, wests, stringsAsFactors = FALSE))
message("Area of interest includes ", nrow(tilesLocations), " NED tiles.")
loc = NULL
tiles <- foreach::foreach(loc = 1:nrow(tilesLocations)) %do% {
return(tryCatch(get_ned_tile(template = template,
res = res,
tileNorthing = tilesLocations[loc,1],
tileWesting = tilesLocations[loc,2],
raw.dir = raw.dir),
error = function(e) {
message("WARNING: ",e$message)
return(NULL)},
warning = function(w) NULL))
}
if(all(sapply(tiles, is.null))){
stop("No NED tiles are available for your study area. Please check your input data and internet connection.")
}
tiles <- tiles[which(!sapply(tiles, is.null))]
if (length(tiles) > 1) {
message("Mosaicking NED tiles.")
utils::flush.console()
tiles$fun <- mean
names(tiles)[1:2] <- c("x", "y")
tiles <- do.call(raster::mosaic, tiles)
gc()
} else {
tiles <- tiles[[1]]
}
tiles <- tryCatch(tiles %>% raster::crop(y = template %>% sp::spTransform(CRSobj = tiles %>% raster::projection()), snap = "out"),
error = function(e) {
tiles %>% raster::crop(y = template %>% sp::spTransform(CRSobj = tiles %>% raster::projection()))
})
raster::writeRaster(tiles,
paste(extraction.dir, "/", label, "_NED_", res, ".tif", sep = ""),
datatype = "FLT4S",
options = raster.options,
overwrite = T,
setStatistics = FALSE)
return(tiles)
}
download_ned_tile <- function(res = "1", tileNorthing, tileWesting, raw.dir) {
destdir <- paste(raw.dir, "/", res, "/", sep = "")
dir.create(destdir, showWarnings = FALSE, recursive = TRUE)
tileWesting <- formatC(tileWesting, width = 3, format = "d", flag = "0")
tileNorthing <- formatC(tileNorthing, width = 2, format = "d", flag = "0")
url <- paste0("https://prd-tnm.s3.amazonaws.com/StagedProducts/Elevation/", res, "/ArcGrid/USGS_NED_",res,"_n", tileNorthing, "w", tileWesting,
"_ArcGrid.zip")
if(httr::http_error(url))
url <- paste0("https://prd-tnm.s3.amazonaws.com/StagedProducts/Elevation/", res, "/ArcGrid/n", tileNorthing, "w", tileWesting,
".zip")
download_data(url = url, destdir = destdir)
return(normalizePath(paste0(destdir, basename(url))))
}
get_ned_tile <- function(template = NULL, res = "1", tileNorthing, tileWesting, raw.dir) {
tmpdir <- tempfile()
if (!dir.create(tmpdir))
stop("failed to create my temporary directory")
message("(Down)Loading NED tile for ", tileNorthing, "N and ", tileWesting, "W.")
file <- download_ned_tile(res = res, tileNorthing = tileNorthing, tileWesting = tileWesting, raw.dir = raw.dir)
tryCatch(utils::unzip(file, exdir = tmpdir),
warning = function(w){
if(grepl("extracting from zip file",w$message)){
stop("NED file ",file," corrupt or incomplete. Please delete the file and try again.")
}
})
dirs <- list.dirs(tmpdir, full.names = TRUE, recursive = F)
dirs <- dirs[grepl("grdn", dirs)]
tile <- raster::raster(dirs)
if (!is.null(template)) {
tile <- tryCatch(tile %>% raster::crop(y = template %>% sp::spTransform(CRSobj = tile %>% raster::projection()), snap = "out"),
error = function(e) {
tile %>% raster::crop(y = template %>% sp::spTransform(CRSobj = tile %>% raster::projection()))
})
}
tile <- tile * 1
unlink(tmpdir, recursive = TRUE)
return(tile)
} |
rlnormMix <-
function (n, meanlog1 = 0, sdlog1 = 1, meanlog2 = 0, sdlog2 = 1,
p.mix = 0.5)
{
ln <- length(n)
if (ln == 0)
stop("'n' must be a non-empty scalar or vector.")
if (ln > 1)
n <- ln
else {
if (is.na(n) || n <= 0 || n != trunc(n))
stop("'n' must be a positive integer or a vector.")
}
if (length(p.mix) != 1 || is.na(p.mix) || p.mix < 0 || p.mix >
1)
stop("'p.mix' must be a single number between 0 and 1.")
arg.mat <- cbind.no.warn(dum = rep(1, n), meanlog1 = as.vector(meanlog1),
sdlog1 = as.vector(sdlog1), meanlog2 = as.vector(meanlog2),
sdlog2 = as.vector(sdlog2))[, -1, drop = FALSE]
if (n < nrow(arg.mat))
arg.mat <- arg.mat[1:n, , drop = FALSE]
na.index <- is.na.matrix(arg.mat)
if (all(na.index))
return(rep(NA, n))
else {
r <- numeric(n)
r[na.index] <- NA
r.no.na <- r[!na.index]
for (i in c("meanlog1", "sdlog1", "meanlog2", "sdlog2")) assign(i,
arg.mat[!na.index, i])
if (any(c(sdlog1, sdlog2) < .Machine$double.eps))
stop("All non-missing values of 'sdlog1' and 'sdlog2' must be positive.")
n.no.na <- sum(!na.index)
index <- rbinom(n.no.na, 1, 1 - p.mix)
n1 <- sum(index)
n2 <- n.no.na - n1
if (n1 > 0)
r.no.na[index == 1] <- rlnorm(n1, meanlog1, sdlog1)
if (n2 > 0)
r.no.na[index == 0] <- rlnorm(n2, meanlog2, sdlog2)
r[!na.index] <- r.no.na
return(r)
}
} |
NULL
normalizeGaussian_severalstations <-
function(x,
data=x,
cpf=NULL,mean=0,
sd=1,
inverse=FALSE,
step=NULL,
prec=10^-4,
type=3,
extremes=TRUE,
sample=NULL,
origin_x=NULL,
origin_data=NULL
) {
out <- x*NA
if (is.null(sample)) {
for (i in 1:ncol(x)) {
out[,i] <- normalizeGaussian(x=x[,i],data=data[,i],cpf=cpf,mean=mean,sd=sd,inverse=inverse,step=step,prec=prec,type=type,extremes=extremes,sample=sample)
}
} else if (sample=="monthly") {
months <- months_f((0.5:11.5)*365/12,abbreviate=TRUE)
for (m in 1:length(months)) {
i_months_x <- extractmonths(data=1:nrow(x),when=months[m],origin=origin_x)
i_months_data <- extractmonths(data=1:nrow(data),when=months[m],origin=origin_data)
for (i in 1:ncol(x)) {
out[i_months_x,i] <- normalizeGaussian(x=x[i_months_x,i],data=data[i_months_data,i],cpf=cpf,mean=mean,sd=sd,inverse=inverse,step=step,prec=prec,type=type,extremes=extremes,sample=NULL)
}
}
} else if (sample=="monthly_year"){
} else {
print("Error in normalizaGaussian_sevaralStation: sample option not yet implemented!!")
}
names(out) <- names(x)
return(out)
} |
QI <- function(map1=map1,map2=map2){
R <- length(map1)
levels(map1) <- as.character(1:length(levels(map1)))
map1 <- as.numeric(map1)
levels(map2) <- as.character(1:length(levels(map2)))
map2 <- as.numeric(map2)
k=max(map1)
map12=10*map1+map2
symb <- numeric()
h <- 0
for (i in 1:k){
for (j in 1:k){
if (i!=j){
h <- h+1
symb[h] <- 10*i+j}
}
}
nusi=length(symb)
nsk <- numeric()
for (s in 1:nusi){
nsk[s] <- sum(map12==symb[s])
}
nsx <- table(map1)
nsy <- table(map2)
lns <- log((nsk>0)*nsk)
lnsX <- log((nsx>0)*nsx)
lnsY <- log((nsy>0)*nsy)
hXY <- -sum((nsk/R)*lns)
hX <- -sum((nsx/R)*lnsX)
hY <- -sum((nsy/R)*lnsY)
QI <- hXY-hX-hY
} |
return_codeLPSOLVE <- function(code) {
if (code == 0) { return( "optimal solution found" ) }
else if (code == 1) { return( "the model is sub-optimal" ) }
else if (code == 2) { return( "the model is infeasible" ) }
else if (code == 3) { return( "the model is unbounded" ) }
else if (code == 4) { return( "the model is degenerate" ) }
else if (code == 5) { return( "numerical failure encountered" ) }
else if (code == 6) { return( "process aborted" ) }
else if (code == 7) { return( "timeout" ) }
else if (code == 9) { return( "the model was solved by presolve" ) }
else if (code == 10) { return( "the branch and bound routine failed" ) }
else if (code == 11) { return( paste("the branch and bound was stopped",
"because of a break-at-first",
"or break-at-value"
)
)
}
else if (code == 12) { return( paste("a feasible branch and bound",
"solution was found"
)
)
}
else if (code == 13) { return( paste("no feasible branch and bound",
"solution was found"
)
)
}
else { return(paste("Failed to obtain solution",
"unknown error code:", code
)
)
}
}
loadMatrixPerColumnLPSOLVE <- function(lpmod, constMat) {
stopifnot(is(constMat, "Matrix"))
x <- constMat@x
p <- constMat@p + 1
i <- constMat@i + 1
k <- 1
while (k <= ncol(constMat)) {
lpSolveAPI::set.column(lpmod,
column = k,
x = x[(p[k]):(p[k+1]-1)],
indices = i[(p[k]):(p[k+1]-1)])
k <- k + 1
}
} |
context("Monotherapy fitting")
test_that('marginals', {
dataM <- data[data$d1 < 1e-12 | data$d2 < 1e-12,]
fit1 <- fitMarginals(data, method = "nls")
fit2 <- fitMarginals(data, method = "nlslm")
fit3 <- fitMarginals(data, method = "optim")
expect_true(inherits(fit1, "MarginalFit"))
expect_true(inherits(fit2, "MarginalFit"))
expect_true(inherits(fit3, "MarginalFit"))
expect_equal(coef(fit1), coef(fit2))
expect_equal(fitted(fit1), fitted(fit2))
expect_equal(residuals(fit1), residuals(fit2), tolerance = 1e-1)
expect_equal(fitted(fit1), predict(fit1, newdata = dataM))
expect_equal(fitted(fit2), predict(fit2, newdata = dataM))
expect_true(all(abs(vcov(fit1) - vcov(fit2)) < 1e-1))
expect_equal(df.residual(fit1), df.residual(fit2))
expect_equal(df.residual(fit1), df.residual(fit3))
expect_equal(dataM[["effect"]], fitted(fit1) + residuals(fit1))
expect_equal(dataM[["effect"]], fitted(fit2) + residuals(fit2))
expect_equal(dataM[["effect"]], fitted(fit3) + residuals(fit3))
expect_equal(fitMarginals(data, start = initPars, method = "nls")$coef,
fitMarginals(data, start = initPars, method = "nlslm")$coef)
})
test_that('marginals-constraints', {
constraintsA <- list("matrix" = c(0, 0, 0, 1, -1, 0, 0),
"vector" = 0)
constraintsB <- list("matrix" = c(0, 0, 1, 0, 0, 0, 0),
"vector" = 13000)
constraints2 <- list(
"matrix" = rbind(c(0, 0, 1, 0, 0, 0, 0),
c(0, 0, 0, 1, -1, 0, 0)),
"vector" = c(13000, 0)
)
constraints <- list(
"matrix" = rbind(c(2, -2, 0, 0, 0, 0, 0),
c(0, 0, 0, 1, -1, 0, 0),
c(0, 0, 0, 0, 0, pi, -pi)),
"vector" = rep(0, 3)
)
fit1 <- fitMarginals(data, method = "nls", fixed = c("b" = 13000, "h2" = 2))
fit2 <- fitMarginals(data, method = "nlslm", fixed = c("h2" = 2, "b" = 13000))
fit3 <- fitMarginals(data, method = "optim", fixed = c("b" = 13000, "h2" = 2))
expect_equal(fit1$coef[["b"]], 13000)
expect_equal(fit2$coef[["b"]], 13000)
expect_equal(fit3$coef[["b"]], 13000)
expect_equal(fit1$coef[["h2"]], 2)
expect_equal(fit2$coef[["h2"]], 2)
expect_equal(fit3$coef[["h2"]], 2)
expect_error(fitMarginals(data, method = "optim", fixed = c("ABC" = 1)))
expect_error(fitMarginals(data, method = "optim", fixed = c("b" = 13000, "ABC" = 1)))
expect_warning(fit1 <- fitMarginals(data, method = "nlslm",
fixed = c("b" = 12000, "h2" = 1.5),
constraints = constraints2))
expect_equal(fit1$coef[["b"]], 12000)
expect_equal(fit1$coef[["h2"]], 1.5)
fit1 <- fitMarginals(data, method = "nls", constraints = constraintsB)
fit2 <- fitMarginals(data, method = "nlslm", constraints = constraintsB)
fit3 <- fitMarginals(data, method = "optim", constraints = constraintsB)
expect_equal(fit1$coef[["b"]], 13000)
expect_equal(fit2$coef[["b"]], 13000)
expect_equal(fit3$coef[["b"]], 13000)
expect_equal(length(coef(fit1)), 7)
expect_equal(length(coef(fit2)), 7)
expect_equal(length(coef(fit3)), 7)
expect_true(all(abs(fit1$coef - fit2$coef) < 1e-1))
fit1 <- fitMarginals(data, method = "nls", constraints = constraintsA)
fit2 <- fitMarginals(data, method = "nlslm", constraints = constraintsA)
fit3 <- fitMarginals(data, method = "optim", constraints = constraintsA)
expect_equal(fit1$coef[["m1"]], fit1$coef[["m2"]])
expect_equal(fit2$coef[["m1"]], fit2$coef[["m2"]])
expect_equal(fit3$coef[["m1"]], fit3$coef[["m2"]])
expect_equal(length(coef(fit1)), 7)
expect_equal(length(coef(fit2)), 7)
expect_equal(length(coef(fit3)), 7)
expect_true(all(abs(fit1$coef - fit2$coef) < 1e-4))
fit1 <- fitMarginals(data, method = "nls", constraints = constraints2)
fit2 <- fitMarginals(data, method = "nlslm", constraints = constraints2)
fit3 <- fitMarginals(data, method = "optim", constraints = constraints2)
expect_equal(fit1$coef[["m1"]], fit1$coef[["m2"]])
expect_equal(fit2$coef[["m1"]], fit2$coef[["m2"]])
expect_equal(fit3$coef[["m1"]], fit3$coef[["m2"]])
expect_equal(fit1$coef[["b"]], 13000)
expect_equal(fit2$coef[["b"]], 13000)
expect_equal(fit3$coef[["b"]], 13000)
expect_equal(length(coef(fit1)), 7)
expect_equal(length(coef(fit2)), 7)
expect_equal(length(coef(fit3)), 7)
expect_true(all(abs(fit1$coef - fit2$coef) < 1e-4))
fit1 <- fitMarginals(data, method = "nls", constraints = constraints)
fit2 <- fitMarginals(data, method = "nlslm", constraints = constraints)
fit3 <- fitMarginals(data, method = "optim", constraints = constraints)
expect_equal(length(coef(fit1)), 7)
expect_equal(length(coef(fit2)), 7)
expect_equal(length(coef(fit3)), 7)
expect_equal(fit1$coef[["h1"]], fit1$coef[["h2"]])
expect_equal(fit2$coef[["h1"]], fit2$coef[["h2"]])
expect_equal(fit3$coef[["h1"]], fit3$coef[["h2"]])
expect_equal(fit1$coef[["m1"]], fit1$coef[["m2"]])
expect_equal(fit2$coef[["m1"]], fit2$coef[["m2"]])
expect_equal(fit3$coef[["m1"]], fit3$coef[["m2"]])
expect_equal(fit1$coef[["e1"]], fit1$coef[["e2"]])
expect_equal(fit2$coef[["e1"]], fit2$coef[["e2"]])
expect_equal(fit3$coef[["e1"]], fit3$coef[["e2"]])
})
test_that('marginals-transforms', {
dataM <- data[data$d1 < 1e-12 | data$d2 < 1e-12,]
fit1 <- fitMarginals(data, transforms = transforms, method = "nls")
fit2 <- fitMarginals(data, transforms = transforms, method = "nlslm")
fit3 <- fitMarginals(data, transforms = transforms, method = "optim")
expect_equal(length(coef(fit1)), 7)
expect_equal(length(coef(fit2)), 7)
expect_equal(length(coef(fit3)), 7)
expect_true(all(abs(fit1$coef - fit2$coef) < 1e-4))
expect_true(all(abs(fitted(fit1) - fitted(fit2)) < 1e-4))
expect_true(all(abs(residuals(fit1) - residuals(fit2)) < 1e-4))
expect_equal(fitted(fit1), predict(fit1, newdata = dataM))
expect_equal(fitted(fit2), predict(fit2, newdata = dataM))
expect_true(all(abs(vcov(fit1) - vcov(fit2)) < 3e-2))
expect_equal(df.residual(fit1), df.residual(fit2))
expect_equal(df.residual(fit1), df.residual(fit3))
expect_equal(transforms$PowerT(dataM[["effect"]], transforms$compositeArgs),
fitted(fit1) + residuals(fit1))
expect_equal(transforms$PowerT(dataM[["effect"]], transforms$compositeArgs),
fitted(fit2) + residuals(fit2))
expect_equal(transforms$PowerT(dataM[["effect"]], transforms$compositeArgs),
fitted(fit3) + residuals(fit3))
fit1 <- fitMarginals(data, start = initParsT,
transforms = transforms, method = "nls")
fit2 <- fitMarginals(data, start = initParsT,
transforms = transforms, method = "nlslm")
expect_true(all(abs(fit1$coef - fit2$coef) < 1e-4))
constraints <- list(
"matrix" = rbind(c(2, -2, 0, 0, 0, 0, 0),
c(0, 0, 0, 1, -1, 0, 0),
c(0, 0, 0, 0, 0, pi, -pi)),
"vector" = rep(0, 3)
)
fit1 <- fitMarginals(data, method = "nls", constraints = constraints,
transforms = transforms)
fit2 <- fitMarginals(data, method = "nlslm", constraints = constraints,
transforms = transforms)
fit3 <- fitMarginals(data, method = "optim", constraints = constraints,
transforms = transforms)
expect_equal(length(coef(fit1)), 7)
expect_equal(length(coef(fit2)), 7)
expect_equal(length(coef(fit3)), 7)
expect_equal(fit1$coef[["h1"]], fit1$coef[["h2"]])
expect_equal(fit2$coef[["h1"]], fit2$coef[["h2"]])
expect_equal(fit3$coef[["h1"]], fit3$coef[["h2"]])
expect_equal(fit1$coef[["m1"]], fit1$coef[["m2"]])
expect_equal(fit2$coef[["m1"]], fit2$coef[["m2"]])
expect_equal(fit3$coef[["m1"]], fit3$coef[["m2"]])
expect_equal(fit1$coef[["e1"]], fit1$coef[["e2"]])
expect_equal(fit2$coef[["e1"]], fit2$coef[["e2"]])
expect_equal(fit3$coef[["e1"]], fit3$coef[["e2"]])
})
test_that('marginals-extraArgs', {
lowerBounds <- rep(0, 7)
upperBounds <- c(1, rep(Inf, 6))
fit1 <- fitMarginals(data, method = "nls", algorithm = "port",
lower = lowerBounds, upper = upperBounds)
fit2 <- fitMarginals(data, method = "nlslm",
lower = lowerBounds, upper = upperBounds)
expect_true(all(coef(fit1) >= 0))
expect_true(all(coef(fit2) >= 0))
expect_equal(coef(fit1)[[1]], 1)
expect_equal(coef(fit2)[[1]], 1)
})
test_that('marginals-plots', {
fit <- fitMarginals(data)
fitT <- fitMarginals(data, transforms = transforms)
expect_silent(plot(fit))
expect_silent(plot(fit, smooth = FALSE))
expect_silent(plot(fitT))
expect_silent(plot(fitT, smooth = FALSE))
expect_silent(plot(fitT, dataScale = TRUE))
}) |
modpower <- function(n, k, m) {
stopifnot(is.numeric(n), floor(n) == ceiling(n), n >= 0,
is.numeric(k), floor(k) == ceiling(k), k >= 0,
is.numeric(m), floor(m) == ceiling(m), m >= 0)
if (m^2 > 2^53-1)
stop("Modulus 'm' too big for integer arithmetic in R.")
if (k == 0) return(1)
if (n == 0) return(0)
b <- n %% m
r <- 1
while (k != 0) {
if (k %% 2 == 1) {
r <- (b * r) %% m
k <- k - 1
}
k <- k / 2
b <- (b * b) %% m
}
return(r)
}
modorder <- function(n, m) {
stopifnot(is.numeric(n), floor(n) == ceiling(n), n >= 0,
is.numeric(m), floor(m) == ceiling(m), m >= 0)
if (!coprime(n, m)) return(0)
r <- n %% m; k <- 1
if (r == 0) return(NA)
while (r != 1) {
r <- (n*r) %% m; k <- k + 1
}
return(k)
}
primroot <- function (m, all = FALSE) {
stopifnot(is.numeric(m), floor(m) == ceiling(m), m >= 0)
if (!isPrime(m)) return(NA)
if (m == 2) return(1)
if (all) {
res <- c()
for (r in 2:(m-1)) {
k <- modorder(r, m)
if (k == m-1) res <- c(res, r)
}
} else {
for (r in 2:(m-1)) {
k <- modorder(r, m)
if (k == m - 1) break
}
res <- r
}
return(res)
} |
context("translator")
test_that("test Translator csv", {
i18n <- Translator$new(translation_csvs_path = "data")
expect_equal(i18n$t("Hello Shiny!"), "Hello Shiny!")
i18n$set_translation_language("pl")
expect_equal(i18n$t("Hello Shiny!"), "Witaj Shiny!")
i18n$set_translation_language("it")
expect_equal(i18n$t("Hello Shiny!"), "Ciao Shiny!")
i18n$set_translation_language("en")
expect_equal(i18n$t("Hello Shiny!"), "Hello Shiny!")
expect_error(i18n$set_translation_language("es"), "'es' not in Translator")
})
test_that("test Translator json", {
i18n <- Translator$new(translation_json_path = "data/translation.json")
expect_equal(i18n$t("Hello Shiny!"), "Hello Shiny!")
i18n$set_translation_language("pl")
expect_equal(i18n$t("Hello Shiny!"), "Witaj Shiny!")
i18n$set_translation_language("en")
expect_equal(i18n$t("Hello Shiny!"), "Hello Shiny!")
expect_error(i18n$set_translation_language("it"), "'it' not in Translator")
})
test_that("test Translator general", {
expect_error(Translator$new())
expect_error(Translator$new(translation_json_path = "data/translation.json",
translation_csvs_path = "data"),
"mutually exclusive")
})
test_that("test vector translations", {
i18n <- Translator$new(translation_json_path = "data/translation.json")
expect_equal(i18n$t(c("Hello Shiny!")), "Hello Shiny!")
i18n$set_translation_language("pl")
expect_equal(i18n$t(c("Hello Shiny!")), "Witaj Shiny!")
expect_warning(i18n$t(c("Hello Shiny!", "Text")))
expect_equal(i18n$t(c("Hello Shiny!", "Text")), c("Witaj Shiny!", "Text"))
expect_equal(i18n$t(c("Hello Shiny!", "Text", "Frequency")),
c("Witaj Shiny!", "Text", "Częstotliwość"))
expect_warning(i18n$t(c("Hello Shiny!", "X")),
regexp = "'X' translation does not exist.")
}) |
plot.HPWmapSphere <- function(x, lon, lat, plotWhich = "Both",
color = c("firebrick1", "gainsboro", "dodgerblue3"),
turnOut = FALSE, title, ...) {
if (length(color) != 3) {
stop("'color' must be a vector containing exactly three colors!")
}
if (length(lon) * length(lat) != dim(x[[1]]$pw)[1] * dim(x[[1]]$pw)[2]) {
stop("Longitude and latitude are non-comformable to the dimension of x")
}
if (methods::hasArg(title) == TRUE && length(title) != length(x)) {
stop("Number of titles must be equal to the number of plots")
}
if (methods::hasArg(title) == FALSE) {
namesVec <- names(x)
namesVec <- sapply(strsplit(namesVec, "_"), "[", 1)
namesVec <- gsub("NA", "infinity", namesVec)
}
if(plotWhich == "HPW") {
graphics::par(mfrow = c(ceiling(length(x) / 2), 2))
graphics::par(mar = c(2, 2, 2, 2), oma = c(2, 2, 2, 2))
for(i in 1:length(x)){
if (methods::hasArg(title) == FALSE) {
if (i < length(x)) {
mainTxt <- as.expression(
substitute(
paste("HPW-Map for ", z[y], " with ", lambda, "-range = [", x, " - ", w, "]"),
list(x = as.name(namesVec[i]), y = i, w = as.name(namesVec[i + 1]))
)
)
} else {
mainTxt <- as.expression(
substitute(
paste("HPW-Map for ", z[y], " with ", lambda, "-range = [", x, "]"),
list(x = as.name(namesVec[i]), y = i)
)
)
}
} else {
mainTxt <- title[i]
}
if(turnOut) {
tmp <- turnmat(x[[i]]$hpw)
lon.tmp <- lat
lat.tmp <- lon
} else {
tmp <- x[[i]]$hpw
lon.tmp <- lon
lat.tmp <- lat
}
graphics::image(lon.tmp, lat.tmp, tmp, col = color, main = mainTxt,
xaxt = "n", yaxt = "n", cex.main = 1, bty = "n", ...)
maps::map("world", add = TRUE)
}
}
if(plotWhich == "PW") {
graphics::par(mfrow = c(ceiling(length(x) / 2), 2))
graphics::par(mar = c(2, 2, 2, 2), oma = c(2, 2, 2, 2))
for(i in 1:length(x)){
if (methods::hasArg(title) == FALSE) {
if (i < length(x)) {
mainTxt <- as.expression(
substitute(
paste("PW-Map for ", z[y], " with ", lambda, "-range = [", x, " - ", w, "]"),
list(x = as.name(namesVec[i]), y = i, w = as.name(namesVec[i + 1]))
)
)
} else {
mainTxt <- as.expression(
substitute(
paste("PW-Map for ", z[y], " with ", lambda, "-range = [", x, "]"),
list(x = as.name(namesVec[i]), y = i)
)
)
}
} else {
mainTxt <- title[i]
}
if(turnOut) {
tmp <- turnmat(x[[i]]$pw)
lon.tmp <- lat
lat.tmp <- lon
} else {
tmp <- x[[i]]$pw
lon.tmp <- lon
lat.tmp <- lat
}
graphics::image(lon.tmp, lat.tmp, tmp, col = color, main = mainTxt,
xaxt = "n", yaxt = "n", cex.main = 1, bty = "n", ...)
maps::map("world", add = TRUE)
}
}
if(plotWhich == "Both") {
graphics::par(mfrow = c(ceiling(length(x) / 2), 2))
graphics::par(mar = c(2, 2, 2, 2), oma = c(2, 2, 2, 2))
for(i in 1:length(x)){
if (methods::hasArg(title) == FALSE) {
if (i < length(x)) {
mainTxt <- as.expression(
substitute(
paste("HPW-Map for ", z[y], " with ", lambda, "-range = [", x, " - ", w, "]"),
list(x = as.name(namesVec[i]), y = i, w = as.name(namesVec[i + 1]))
)
)
} else {
mainTxt <- as.expression(
substitute(
paste("HPW-Map for ", z[y], " with ", lambda, "-range = [", x, "]"),
list(x = as.name(namesVec[i]), y = i)
)
)
}
} else {
mainTxt <- title[i]
}
if(turnOut) {
tmp <- turnmat(x[[i]]$hpw)
lon.tmp <- lat
lat.tmp <- lon
} else {
tmp <- x[[i]]$hpw
lon.tmp <- lon
lat.tmp <- lat
}
graphics::image(lon.tmp, lat.tmp, tmp, col = color, main = mainTxt,
xaxt = "n", yaxt = "n", cex.main = 1, bty = "n", ...)
maps::map("world", add = TRUE)
}
readline(prompt = "Press [enter] for the PW maps!")
graphics::par(mfrow = c(ceiling(length(x) / 2), 2))
graphics::par(mar = c(2, 2, 2, 2), oma = c(2, 2, 2, 2))
for(i in 1:length(x)){
if (methods::hasArg(title) == FALSE) {
if (i < length(x)) {
mainTxt <- as.expression(
substitute(
paste("PW-Map for ", z[y], " with ", lambda, "-range = [", x, " - ", w, "]"),
list(x = as.name(namesVec[i]), y = i, w = as.name(namesVec[i + 1]))
)
)
} else {
mainTxt <- as.expression(
substitute(
paste("PW-Map for ", z[y], " with ", lambda, "-range = [", x, "]"),
list(x = as.name(namesVec[i]), y = i)
)
)
}
} else {
mainTxt <- title[i]
}
if(turnOut) {
tmp <- turnmat(x[[i]]$pw)
lon.tmp <- lat
lat.tmp <- lon
} else {
tmp <- x[[i]]$pw
lon.tmp <- lon
lat.tmp <- lat
}
graphics::image(lon.tmp, lat.tmp, tmp, col = color, main = mainTxt,
xaxt = "n", yaxt = "n", cex.main = 1, bty = "n", ...)
maps::map("world", add = TRUE)
}
}
} |
"clothing" |
par(mai=c(0.1,0.1,0.1,0.1))
plot.new()
rect(0,0.6,1/3,0.867, col="indianred1")
rect(1/3,0.6,2/3,0.867, col="steelblue2")
rect(2/3,0.6,3/3,0.867, col="springgreen3")
text(0.5,0.9, "Metabolomics Data Processing", cex=1.5)
text(1/6,0.85, "Raw Signal Filtering\nand Peak Calling\n(ChromaTOF)", pos=1,cex=0.8)
text(3/6,0.85, "Multi-sample Peak\nAlignment and\nMetabolite Identification\n(R2DGC)", cex=0.8, pos=1)
text(5/6,0.85, "Data Normalization\nand Statistical\nInference\n(Metaboanalyst)", pos=1,cex=0.8)
arrows(0.17,0.63,0.85,0.63,length = 0.1 ,lwd=3)
points(seq(0,0.2,(0.2-0)/8),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)*0.5)+0.45,type="l", lwd=3)
points(seq(0.1,0.3,(0.3-0.1)/8),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)*0.5)+0.45,type="l", lwd=3)
points(seq(0,0.15,(0.15-0)/8),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)*0.5)+0.22,type="l", lwd=3)
points(seq(0.16,0.3,(0.3-0.16)/8),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)*0.5)+0.22,type="l", lwd=3)
points(seq(0,0.13,(0.13-0)/8)+(0.36),(c(0.0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.26,type="l", lwd=3)
points(seq(0.17,0.3,(0.3-0.17)/8)+(0.34),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.26,type="l", lwd=3)
points(seq(0,0.13,(0.13-0)/8)+(0.36),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.32,type="l", lwd=3)
points(seq(0.17,0.3,(0.3-0.17)/8)+(0.34),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.32,type="l", lwd=3)
points(seq(0,0.13,(0.13-0)/8)+(0.36),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.38,type="l", lwd=3)
points(seq(0.17,0.3,(0.3-0.17)/8)+(0.34),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.38,type="l", lwd=3)
points(seq(0,0.13,(0.13-0)/8)+(0.36),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.44,type="l", lwd=3)
points(seq(0.17,0.3,(0.3-0.17)/8)+(0.34),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.44,type="l", lwd=3)
points(seq(0,0.13,(0.13-0)/8)+(0.7),(c(0.0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.2,type="l", lwd=3)
points(seq(0.17,0.3,(0.3-0.17)/8)+(0.69),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.2,type="l", lwd=3)
points(seq(0,0.13,(0.13-0)/8)+(0.7),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.26,type="l", lwd=3)
points(seq(0.17,0.3,(0.3-0.17)/8)+(0.69),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.26,type="l", lwd=3)
points(seq(0,0.13,(0.13-0)/8)+(0.7),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.42,type="l", lwd=3)
points(seq(0.17,0.3,(0.3-0.17)/8)+(0.69),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.42,type="l", lwd=3)
points(seq(0,0.13,(0.13-0)/8)+(0.7),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.48,type="l", lwd=3)
points(seq(0.17,0.3,(0.3-0.17)/8)+(0.69),(c(0,0.08,0.12,0.15,0.16,0.15,0.13,0.09,0)/3)+0.48,type="l", lwd=3)
rect(xleft = 0.69,ybottom = 0.19,xright = 1,0.325, lwd = 3)
rect(xleft = 0.69,ybottom = 0.41,xright = 1,0.546, lwd = 3)
text(0.85, 0.57, "Group A")
text(0.85, 0.35, "Group B")
arrows(1/3,0.2,1/3,0.6,code = 0,lty=2)
arrows(2/3,0.2,2/3,0.6,code = 0,lty=2)
arrows(1/6.5,0.28,1/6.5,0.45,code = 1, length=0.1,lwd=2)
par(mai=c(0.1,0.1,0,0.1))
plot.new()
text(0.5,1,"Input Sample\nChromatof File Paths", cex=0.8)
arrows(0.5,0.96,0.5,0.905,length=0.1, lwd=2)
rect(0.3,0.75,0.7,0.9, col="springgreen3")
text(0.5,0.83,"Optional: Ion Filtering\n(FindProblemIons)", cex=0.8)
arrows(0.5,0.745,0.5,0.705,length=0.1, lwd=2)
rect(0.3,0.55,0.7,0.7, col="steelblue2")
text(0.5,0.63,"Optional: Intra-Sample\nPeak Compression\n(PrecompressFiles)", cex=0.8)
arrows(0.5,0.545,0.5,0.505,length=0.1, lwd=2)
rect(0.3,0.3,0.7,0.5, col="indianred1")
text(0.5,0.4,"Multi-Sample Peak\nAlignment and\nMetabolite Identification\n(ConsensusAlign)", cex=0.8)
rect(0.8,0.5,1,0.65, col="plum3")
text(0.9,0.58,"Standard Library\nCreation\n(MakeReference)", cex=0.69)
text(0.9,0.77,"Input Metabolite\nStandard\nChromatof File Paths", cex=0.8)
arrows(0.9,0.71,0.9,0.655,length=0.1, lwd=2)
arrows(0.9,0.495,0.705,0.4,length=0.1, lwd=2)
arrows(0.5,0.295,0.5,0.255,length=0.1, lwd=2)
rect(-0.02,0.03,1.02,0.25,col="snow2")
text(0.5,0.225,"Output List")
rect(0,0.05,0.3,0.2, col="wheat1")
text(0.15,0.13,"Peak Alignment Table", cex=0.8)
rect(0.35,0.05,0.65,0.2, col="khaki2")
text(0.5,0.13,"Peak Info Table", cex=0.8)
rect(0.7,0.05,1,0.2, col="lightgoldenrod")
text(0.85,0.13,"Incongruent Quant\nMass List", cex=0.8)
library(R2DGC)
ProblemIons<-FindProblemIons(inputFile=system.file("extdata", "SampleA.txt",
package="R2DGC"))
head(ProblemIons)
library(parallel)
detectCores()
SampleC<-system.file("extdata", "SampleC.txt", package="R2DGC")
CompressionInfo<-PrecompressFiles(inputFileList=SampleC)
CompressionInfo<-PrecompressFiles(inputFileList=SampleC, commonIons = ProblemIons[,1])
Standard1<-system.file("extdata", "Alanine_150226_1.txt", package="R2DGC")
Standard2<-system.file("extdata", "Serine_022715_1.txt", package="R2DGC")
StandardLibrary<-MakeReference(inputFileList = c(Standard1, Standard2),
RT1_Standards=paste0("FAME_", seq(8,24,2)))
plot.new()
points(c(.1,.35,.5,.8),rep(0.8,4), pch=16, col=c("black","red","black","black"))
text(c(.1,.35,.5,.8),rep(0.85,5), labels = c("Std1","Analyte","Std2","Std3"))
arrows(x0 = 0, y0 = 0.7,x1 = 1,y1 = 0.7, code=0, lwd=3)
arrows(x0 = c(0,0.2,0.4,0.6,0.8,1), y0 = rep(0.7,6),x1 = c(0,0.2,0.4,0.6,0.8,1),y1 = rep(0.65,6), code=0, lwd=3)
text(c(0,0.2,0.4,0.6,0.8,1),rep(0.62,6), labels = c(seq(0,10,2)))
text(0.5,0.73, labels = "Retention Time",cex=0.75)
arrows(x0 = .1, y0 = 0.5,x1 = .8,y1 = 0.5, code=0, lwd=2)
text(0.45,0.52, labels = substitute(paste(italic("L"),"=7")))
arrows(x0 = c(.1,.8), y0 = rep(0.49,2),x1 = c(.1,.8),y1 = rep(0.51,2), code=0, lwd=2)
arrows(x0 = .1, y0 = 0.4,x1 = .35,y1 = 0.4, code=0, lwd=2)
text(.225,0.43, labels = expression(italic("d"[1])*"= -2.5"))
arrows(x0 = c(.1,.35), y0 = rep(0.39,2),x1 = c(.1,.35),y1 = rep(0.41,2), code=0, lwd=2)
arrows(x0 = .5, y0 = 0.3,x1 = .35,y1 = 0.3, code=0, lwd=2)
text(.425,0.33, labels = expression(italic("d"[2])*"= 1.5"))
arrows(x0 = c(.5,.35), y0 = rep(0.29,2),x1 = c(.5,.35),y1 = rep(0.31,2), code=0, lwd=2)
arrows(x0 = .8, y0 = 0.2,x1 = .35,y1 = 0.2, code=0, lwd=2)
text(.575,0.23, labels = expression(italic("d"[3])*"= 4.5"))
arrows(x0 = c(.8,.35), y0 = rep(0.19,2),x1 = c(.8,.35),y1 = rep(0.21,2), code=0, lwd=2)
par(mai=rep(0.1,4))
plot.new()
rect(xleft = 0.25,ybottom = 0.9,xright = 0.75,ytop = 1, col="springgreen3")
text(0.5,0.95,"Read in sample files", cex=0.75)
arrows(x0 = 0.5,y0 = 0.9,x1 = 0.5,y1 = 0.875,length=0.05, lwd=2)
rect(0.25,0.775,0.75,0.875, col="wheat1")
text(0.5,0.825,"Optional: Compute retention indices", cex=0.75)
arrows(x0 = 0.5,y0 = 0.775,x1 = 0.5,y1 = 0.75,length=0.05, lwd=2)
rect(0.25,0.65,0.75,.75, col="indianred1")
text(0.5,0.7,"Compute pairwise sample-seed\npeak similarity scores", cex=0.75)
arrows(x0 = 0.5,y0 = 0.65,x1 = 0.5,y1 = 0.625,length=0.05, lwd=2)
rect(0.25,0.525,0.75,.625, col="khaki2")
text(0.5,0.575,"Optional: compute optimal\npeak similarity threshold", cex=0.75)
arrows(x0 = 0.5,y0 = 0.525,x1 = 0.5,y1 = 0.5,length=0.05, lwd=2)
rect(0.25,0.4,0.75,.5, col="steelblue2")
text(0.5,0.45,"Find best peak pairs above\npeak similarity threshold", cex=0.75)
arrows(x0 = 0.5,y0 = 0.4,x1 = 0.5,y1 = 0.375,length=0.05, lwd=2)
rect(0.25,0.275,0.75,.375, col="plum3")
text(0.5,0.325,"Optional: Relaxed threshold search\nfor high likelihood missing peaks", cex=0.75)
arrows(x0 = 0.5,y0 = 0.275,x1 = 0.5,y1 = 0.25,length=0.05, lwd=2)
rect(0.25,0.15,0.75,.25, col="lightgoldenrod")
text(0.5,0.2,"Optional: Identify aligned\npeaks with reference library", cex=0.75)
arrows(x0 = 0.5,y0 = 0.15,x1 = 0.5,y1 = 0.125,length=0.05, lwd=2)
arrows(x0 = 0.1,y0 = 0.325,x1 = 0.1,y1 = 0.7, lwd=2, code=0)
arrows(x0 = 0.25,y0 = 0.325,x1 = 0.1,y1 = 0.325, lwd=2, code=0)
arrows(x0 = 0.25,y0 = 0.7,x1 = 0.1,y1 = 0.7, lwd=2, length=0.05, code=1)
rect(0,0.45,0.2,0.575, col="coral")
text(0.1,0.515, "Optional: repeat\nalignment with\nmultiple seeds", cex=0.7)
rect(0,0,0.3,0.09, col="cadetblue2")
text(0.15,0.045,"Peak Alignment Table", cex=0.8)
rect(0.35,0.0,0.65,0.09, col="navajowhite")
text(0.5,0.045,"Peak Info Table", cex=0.8)
rect(0.7,0.0,1,0.09, col="pink2")
text(0.85,0.045,"Incongruent Quant\nMass List", cex=0.8)
text(0.5,.105, "Outputs", cex=0.8)
rect(0,0,1,0.09)
SampleA<-system.file("extdata", "SampleA.txt", package="R2DGC")
SampleB<-system.file("extdata", "SampleB.txt", package="R2DGC")
Alignment<-ConsensusAlign(c(SampleA,SampleB), standardLibrary = StandardLibrary,
commonIons = ProblemIons)
colnames(Alignment$Alignment_Matrix)<-gsub("^.+/","",colnames(Alignment$Alignment_Matrix))
head(Alignment$Alignment_Matrix, n=3)
Alignment$Unmatched_Quant_Masses |
newtool_template <- function(toolname="",methodname="",toolhelp="",grid.config=grid.config,grid.rows=grid.rows,new.frames){
method_result <- gsub(" ","",methodname,fixed=TRUE)
method_result <- gsub("-","",method_result,fixed=TRUE)
window.temp <- paste0(toolname,method_result)
.update.biclustering.object(window.temp,where="envir",ENVIR=environment())
method_result <- gsub(" ","",methodname,fixed=TRUE)
method_result <- gsub("-","",method_result,fixed=TRUE)
initializeDialog(title = gettextRcmdr(paste(toolname," - ",methodname,sep="")), use.tabs=FALSE)
plotdiagFrame <- tkframe(top)
Tab <- 2
if(length(new.frames[[Tab]])!=0){
if(length(grid.rows[[Tab]])!=0){
for(i in 1:length(grid.rows[[Tab]])){
if(Tab==2){
row.command <- paste("plotdiagFrame_row",i," <- .make.correct.frame(grid.rows[[2]][[",i,"]]$title,grid.rows[[2]][[",i,"]]$border,plotdiagFrame)",sep="")
.eval.command(row.command)
if(grid.rows[[2]][[i]]$title!="" & grid.rows[[2]][[i]]$border==FALSE){
temp.command <- paste("tkgrid(labelRcmdr(plotdiagFrame_row",i ,",fg=getRcmdr('title.color'),font='RcmdrTitleFont',text=gettextRcmdr(grid.rows[[2]][[",i,"]]$title)),sticky='nw')" ,sep="")
.eval.command(temp.command)
}
}
}
}
for(ii in 1:length(new.frames[[Tab]])){
current.frame <- new.frames[[Tab]][[ii]]
frame.name <- current.frame$frame.name
if(length(grid.rows[[Tab]])!=0){
temp.names <- lapply(grid.rows[[Tab]],FUN=function(x){return(x$name.frames)})
boolean <- sapply(temp.names,FUN=function(x){return( frame.name %in% x )})
if(sum(boolean)==1){
if(Tab==2){
window <- paste("plotdiagFrame_row",which(boolean==TRUE),sep="")
}
}
else{
if(Tab==2){
window <- "plotdiagFrame"
}
}
}else {
if(Tab==2){
window <- "plotdiagFrame"
}
}
frame.command <- paste("current.frame$frame <- .make.correct.frame(current.frame$title,current.frame$border,",window,")")
.eval.command(frame.command)
if(current.frame$type=="entryfields"){
number.entries <- length(current.frame$arguments)
arguments <- current.frame$arguments
argument.names <- current.frame$argument.names
initial.values <- current.frame$initial.values
current.frame$entry.frames <- list()
current.frame$entry.vars <- list()
current.frame$entry.fields <- list()
if(current.frame$title!="" & current.frame$border==FALSE){
tkgrid(labelRcmdr( current.frame$frame,fg=getRcmdr("title.color"),font="RcmdrTitleFont" ,text=gettextRcmdr(current.frame$title)),sticky="nw")
}
for(j in 1:number.entries){
current.frame$entry.frames[[j]] <- tkframe(current.frame$frame)
current.frame$entry.vars[[j]] <- tclVar(paste(initial.values[j]))
current.frame$entry.fields[[j]] <- ttkentry(current.frame$entry.frames[[j]],width=current.frame$entry.width[j],textvariable=current.frame$entry.vars[[j]])
tkgrid(labelRcmdr(current.frame$entry.frames[[j]],text=gettextRcmdr(paste(argument.names[j],": ",sep=""))),current.frame$entry.fields[[j]],sticky="nw")
tkgrid(current.frame$entry.frames[[j]],sticky="ne")
}
new.frames[[Tab]][[ii]] <- current.frame
}
if(current.frame$type=="radiobuttons"){
current.frame$argument.values <- sapply(current.frame$argument.values,FUN=function(x){return(paste("BUTTONSTART",x,sep=""))})
current.frame$initial.values <- paste("BUTTONSTART",current.frame$initial.values,sep="")
radioButtons(current.frame$frame,name=frame.name,buttons=current.frame$argument.values,values=current.frame$argument.values,labels=gettextRcmdr(current.frame$argument.names),initialValue=current.frame$initial.values,title="")
if(current.frame$title!="" & current.frame$border==FALSE){
tkgrid(labelRcmdr( current.frame$frame,fg=getRcmdr("title.color"),font="RcmdrTitleFont" ,text=gettextRcmdr(current.frame$title)),sticky="nw")
}
eval(parse(text=paste("current.frame$radioVar <-",frame.name,"Variable",sep="" )))
radio.command <- paste("tkgrid(",frame.name,"Frame,sticky='nw')",sep="")
.eval.command(radio.command)
new.frames[[Tab]][[ii]] <- current.frame
}
if(current.frame$type=="checkboxes"){
checkBoxes(current.frame$frame,frame=frame.name,boxes=paste(current.frame$arguments),initialValues=current.frame$initial.values,labels=sapply(current.frame$argument.names,FUN=gettextRcmdr))
if(current.frame$title!="" & current.frame$border==FALSE){
tkgrid(labelRcmdr( current.frame$frame,fg=getRcmdr("title.color"),font="RcmdrTitleFont" ,text=gettextRcmdr(current.frame$title)),sticky="nw")
}
current.frame$checkVar <- list()
arguments <- current.frame$arguments
for(j in 1:length(arguments)){
temp.arg <- arguments[j]
eval(parse(text=paste("current.frame$checkVar[[",j,"]] <- ",temp.arg,"Variable" ,sep="")))
}
check.command <- paste("tkgrid(",frame.name,",sticky='nw')",sep="")
.eval.command(check.command)
new.frames[[Tab]][[ii]] <- current.frame
}
if(current.frame$type=="valuesliders"){
number.sliders <- length(current.frame$arguments)
arguments <- current.frame$arguments
argument.names <- current.frame$argument.names
initial.values <- current.frame$initial.values
current.frame$slider.frames <- list()
current.frame$slider.vars <- list()
current.frame$slider <- list()
if(current.frame$title!="" & current.frame$border==FALSE){
tkgrid(labelRcmdr( current.frame$frame,fg=getRcmdr("title.color"),font="RcmdrTitleFont" ,text=gettextRcmdr(current.frame$title)),sticky="nw")
}
for( j in 1:number.sliders){
current.frame$slider.frames[[j]] <- tkframe(current.frame$frame)
current.frame$slider.vars[[j]] <- tclVar(as.character(initial.values[j]))
current.frame$slider[[j]] <- tkscale(current.frame$slider.frames[[j]],variable=current.frame$slider.vars[[j]],showvalue=TRUE,from=current.frame$from[j],to=current.frame$to[j],length=current.frame$length[j],resolution=current.frame$by[j],orient="horizontal")
tkgrid(labelRcmdr(current.frame$slider.frames[[j]],text=gettextRcmdr(current.frame$argument.names[j])), current.frame$slider[[j]] ,sticky="sw")
tkgrid(current.frame$slider.frames[[j]],sticky="nw")
}
new.frames[[Tab]][[ii]] <- current.frame
}
if(current.frame$type=="spinboxes"){
number.spins <- length(current.frame$arguments)
arguments <- current.frame$arguments
argument.names <- current.frame$argument.names
initial.values <- current.frame$initial.values
current.frame$spin.frames <- list()
current.frame$spin.vars <- list()
current.frame$spin <- list()
if(current.frame$title!="" & current.frame$border==FALSE){
tkgrid(labelRcmdr( current.frame$frame,fg=getRcmdr("title.color"),font="RcmdrTitleFont" ,text=gettextRcmdr(current.frame$title)),sticky="nw")
}
for(j in 1:number.spins){
current.frame$spin.frames[[j]] <- tkframe(current.frame$frame)
current.frame$spin.vars[[j]] <- tclVar(as.character(initial.values[j]))
current.frame$spin[[j]] <- tkspinbox(current.frame$spin.frames[[j]],from=current.frame$from[j],to=current.frame$to[j],width=current.frame$entry.width,textvariable=current.frame$spin.vars[[j]] ,state="readonly",increment=current.frame$by[j])
tkgrid(labelRcmdr(current.frame$spin.frames[[j]],text=gettextRcmdr(current.frame$argument.names[j])),current.frame$spin[[j]],sticky='nw')
tkgrid(current.frame$spin.frames[[j]],sticky='nw')
}
new.frames[[Tab]][[ii]] <- current.frame
}
if(current.frame$type=="buttons"){
method_result <- gsub(" ","",methodname,fixed=TRUE)
method_result <- gsub("-","",method_result,fixed=TRUE)
button_result <- gsub(" ","",current.frame$button.name,fixed=TRUE)
button_result <- gsub("&","",button_result,fixed=TRUE)
function.command <- paste(current.frame$button.function,"(",sep="")
first.arg=TRUE
if(current.frame$button.data!=""){
input.data <- ActiveDataSet()
if(current.frame$button.data.transf=="matrix"){input.data <- paste("as.matrix(",input.data,")",sep="")}
if(current.frame$button.data.transf=="ExprSet"){input.data <- paste0("as.ExprSet(",input.data,")")}
function.command <- paste(function.command,current.frame$button.data,"=",input.data ,sep="")
first.arg=FALSE
}
if(current.frame$button.biclust!=""){
if(first.arg==TRUE){
function.command <- paste(function.command,current.frame$button.biclust,"=",method_result,sep="")
}
else{
function.command <- paste(function.command,",",current.frame$button.biclust,"=",method_result,sep="")
}
}
if(current.frame$button.data=="" & current.frame$button.biclust=="" & current.frame$button.otherarg==""){
function.command <- paste(function.command,"...",sep="")
}
if(current.frame$button.otherarg!=""){
function.command <- paste(function.command,current.frame$button.otherarg,sep="")
}
arg.names <- .transform.vector2text(current.frame$arg.frames)
save <- current.frame$save
show <- current.frame$show
temp.command <- paste("function(){
biclustering.objects <- .GetEnvBiclustGUI(\"biclustering.objects\")
if(is.null(biclustering.objects)){
.rcmdr.warning('Apply Show Results first')
}
else{
if(!('",method_result,"' %in% biclustering.objects$all)){
.rcmdr.warning('Apply Show Results first')
}
if('",method_result,"' %in% biclustering.objects$all){
function.command <- .build.button.function(\"",function.command,"\",",arg.names,",\"",button_result,"\",new.frames,",save,")
if(",show,"==TRUE){
doItAndPrint(function.command)
}
if(",show,"!=TRUE){
justDoIt(function.command)
}
if(",save,"==TRUE){
doItAndPrint('",button_result,"')
}
.checkplotgridpref()
}
}
}",sep="")
eval(parse(text=paste("button.command <- ",temp.command,sep="")))
current.frame$button.command <- button.command
current.frame$buttonRcmdr <- buttonRcmdr(current.frame$frame,command=current.frame$button.command,text=gettextRcmdr(current.frame$button.name),foreground="darkgreen",default="active",width=current.frame$button.width,borderwidth=3)
tkgrid(current.frame$buttonRcmdr,sticky="s")
new.frames[[Tab]][[ii]] <- current.frame
}
}
if(length(grid.rows[[Tab]])!=0){ special.rows <- lapply(grid.rows[[Tab]],FUN=function(x){return(x$rows)})
special.rows.vector <- sort(unlist(special.rows))} else {special.rows.vector <- c()}
row.index <- 1
while(row.index <= dim(grid.config[[Tab]])[1]){
if((length(grid.rows[[Tab]])!=0) & (row.index %in% special.rows.vector) ){
rowframe.index <- which(lapply(special.rows,FUN=function(x){return(row.index %in% x)}) ==TRUE)
for(i in special.rows[[rowframe.index]]){
grid.command <- paste("tkgrid(")
for(column.index in 1:dim(grid.config[[Tab]])[2]){
if(is.na(grid.config[[Tab]][i,column.index])){} else {grid.command <- paste(grid.command,"new.frames[[",Tab,"]][[",.find.frame(new.frames[[Tab]],grid.config[[Tab]][i,column.index]) ,"]]$frame,",sep="")}
}
grid.command <- paste(grid.command,"sticky='nw',padx=6,pady=6)")
.eval.command(grid.command)
}
if(Tab==2){
grid.command <- paste("tkgrid(plotdiagFrame_row",rowframe.index,",sticky='nw')",sep="")
}
.eval.command(grid.command)
row.index <- i+1
}
else{
grid.command <- "tkgrid("
for(column.index in 1:dim(grid.config[[Tab]])[2]){
if(is.na(grid.config[[Tab]][row.index,column.index])){} else {grid.command <- paste(grid.command,"new.frames[[",Tab,"]][[",.find.frame(new.frames[[Tab]],grid.config[[Tab]][row.index,column.index]) ,"]]$frame,",sep="")}
}
grid.command <- paste(grid.command,"sticky='nw',padx=6,pady=6)",sep="")
.eval.command(grid.command)
row.index <- row.index + 1
}
}
}
onOK <- function(){}
onCancel <- function() {
if (GrabFocus())
tkgrab.release(top)
tkdestroy(top)
tkfocus(CommanderWindow())
}
onHelp <- function() {
tkgrab.release(window)
print(help(toolhelp))
}
exithelpFrame <- tkframe(top)
exitButton2 <- buttonRcmdr(exithelpFrame, text = gettextRcmdr("Exit"), foreground = "red", width = "12", command = onCancel, borderwidth = 3)
helpButton2 <- buttonRcmdr(exithelpFrame, text=gettextRcmdr("Help"),foreground="red",width="12",command=onHelp,borderwidth=3)
tkgrid(exitButton2,helpButton2)
tkgrid(plotdiagFrame,padx=5,pady=5,sticky="nw")
tkgrid(exithelpFrame,sticky="e",padx=5,pady=6)
dialogSuffix(use.tabs=FALSE,onOK=onOK,preventGrabFocus=TRUE)
} |
context("OpenAPI")
test_that("plumberToApiType works", {
expect_equal(plumberToApiType("bool"), "boolean")
expect_equal(plumberToApiType("logical"), "boolean")
expect_equal(plumberToApiType("double"), "number")
expect_equal(plumberToApiType("numeric"), "number")
expect_equal(plumberToApiType("int"), "integer")
expect_equal(plumberToApiType("character"), "string")
expect_equal(plumberToApiType("df"), "object")
expect_equal(plumberToApiType("list"), "object")
expect_equal(plumberToApiType("data.frame"), "object")
expect_warning({
expect_equal(plumberToApiType("flargdarg"), defaultApiType)
}, "Unrecognized type:")
})
test_that("response attributes are parsed", {
lines <- c(
"
"
"
"
"
b <- plumbBlock(length(lines), lines)
expect_length(b$responses, 4)
expect_equal(b$responses$`201`, list(description="This is response 201"))
expect_equal(b$responses$`202`, list(description="Here's second"))
expect_equal(b$responses$`203`, list(description="Here's third"))
expect_equal(b$responses$default, list(description="And default"))
b <- plumbBlock(1, "")
expect_null(b$responses)
})
test_that("params are parsed", {
lines <- c(
"
"
"
"
"
b <- plumbBlock(length(lines), lines)
expect_length(b$params, 4)
expect_equal(b$params$another, list(desc="Another docs", type="integer", required=FALSE, isArray = FALSE))
expect_equal(b$params$test, list(desc="Test docs", type=defaultApiType, required=FALSE, isArray = FALSE))
expect_equal(b$params$required, list(desc="Required param", type="string", required=TRUE, isArray = FALSE))
expect_equal(b$params$multi, list(desc="Required array param", type="integer", required=TRUE, isArray = TRUE))
b <- plumbBlock(1, "")
expect_null(b$params)
})
test_that("getApiSpec works with mounted routers", {
pr1 <- pr()
pr1$handle("GET", "/nested/:path/here", function(){})
pr1$handle("POST", "/nested/:path/here", function(){})
stat <- PlumberStatic$new(".")
pr2 <- pr()
pr2$handle("GET", "/something", function(){})
pr2$handle("POST", "/something", function(){})
pr2$handle("GET", "/", function(){})
pr3 <- pr()
pr3$filter("filter1", function(){})
pr3$handle("POST", "/else", function(){}, "filter1")
pr3$handle("PUT", "/else", function(){})
pr3$handle("GET", "/", function(){})
pr4 <- pr()
pr4$handle("GET", "/completely", function(){})
pr5 <- pr()
pr5$handle("GET", "/trailing_slash/", function(){})
pr1$mount("/static", stat)
pr2$mount("/sub3", pr3)
pr1$mount("/sub2", pr2)
pr1$mount("/sub4", pr4)
pr4$mount("/", pr5)
paths <- names(pr1$getApiSpec()$paths)
expect_length(paths, 7)
expect_equal(paths, c("/nested/:path/here", "/sub2/something",
"/sub2/", "/sub2/sub3/else", "/sub2/sub3/", "/sub4/completely",
"/sub4/trailing_slash/"
))
})
test_that("responsesSpecification works", {
r <- responsesSpecification(NULL)
expect_equal(r, defaultResponse)
r <- responsesSpecification(NA)
expect_equal(r, defaultResponse)
customResps <- list("400" = list())
endpts <- plumber::PlumberEndpoint$new(
path = "/a",
responses = customResps,
verbs = "GET",
expr = function() {},
envir = new.env(parent = globalenv()))
r <- responsesSpecification(endpts)
expect_length(r, 4)
expect_equal(r$default, defaultResponse$default)
expect_equal(r$`400`, customResps$`400`)
})
test_that("parametersSpecification works", {
ep <- list(id=list(desc="Description", type="integer", required=FALSE),
id2=list(desc="Description2", required=FALSE),
make=list(desc="Make description", type="string", required=FALSE),
prices=list(desc="Historic sell prices", type="numeric", required = FALSE, isArray = TRUE),
claims=list(desc="Insurance claims", type="object", required = FALSE))
pp <- data.frame(name=c("id", "id2", "owners"), type=c("int", "int", "chr"), isArray = c(FALSE, FALSE, TRUE), stringsAsFactors = FALSE)
params <- parametersSpecification(ep, pp)
expect_equal(params$parameters[[1]],
list(name="id",
description="Description",
`in`="path",
required=TRUE,
schema = list(
type="integer",
format="int64",
default=NULL)))
expect_equal(params$parameters[[2]],
list(name="id2",
description="Description2",
`in`="path",
required=TRUE,
schema = list(
type="integer",
format="int64",
default=NULL)))
expect_equal(params$parameters[[3]],
list(name="make",
description="Make description",
`in`="query",
required=FALSE,
schema = list(
type="string",
format=NULL,
default=NULL)))
expect_equal(params$parameters[[4]],
list(name="prices",
description="Historic sell prices",
`in`="query",
required=FALSE,
schema = list(
type="array",
items= list(
type="number",
format="double"),
default = NULL),
style="form",
explode=TRUE))
expect_equal(params$parameters[[5]],
list(name="owners",
description=NULL,
`in`="path",
required=TRUE,
schema = list(
type="array",
items= list(
type="string",
format=NULL),
default = NULL),
style="simple",
explode=FALSE))
expect_equal(params$requestBody,
list(content = list(
`application/json` = list(
schema = list(
type = "object",
properties = list(
claims = list(
type = "object",
format = NULL,
example = NULL,
description = "Insurance claims")))))))
params <- parametersSpecification(ep, NULL)
idParam <- params$parameters[[which(vapply(params$parameters, `[[`, character(1), "name") == "id")]]
expect_equal(idParam$required, FALSE)
expect_equal(idParam$schema$type, "integer")
for (param in params$parameters) {
if (param$schema$type != "array") {
expect_equal(length(param), 5)
} else {
expect_equal(length(param), 7)
}
}
params <- parametersSpecification(NULL, pp[3,])
expect_equal(params$parameters[[1]],
list(name="owners",
description=NULL,
`in`="path",
required=TRUE,
schema = list(
type="array",
items= list(
type="string",
format=NULL),
default=NULL),
style="simple",
explode=FALSE))
params <- parametersSpecification(NULL, NULL)
expect_equal(sum(sapply(params, length)), 0)
})
test_that("api kitchen sink", {
skip_on_cran()
skip_on_bioc()
skip_on_os(setdiff(c("windows", "mac", "linux", "solaris"), c("mac", "linux")))
skip_if_not(nzchar(Sys.which("node")), "node not installed")
skip_if_not(nzchar(Sys.which("npm")), "`npm` system dep not installed")
for_each_plumber_api(validate_api_spec, verbose = FALSE)
})
test_that("multiple variations in function extract correct metadata", {
dummy <- function(var0 = 420.69,
var1,
var2 = c(1L, 2L),
var3 = rnorm,
var4 = NULL,
var5 = FALSE,
var6 = list(name = c("luke", "bob"), lastname = c("skywalker", "ross")),
var7 = new.env(parent = .GlobalEnv),
var8 = list(a = 2, b = mean, c = new.env(parent = .GlobalEnv))) {}
funcParams <- getArgsMetadata(dummy)
expect_identical(sapply(funcParams, `[[`, "required"),
c(var0 = FALSE, var1 = TRUE, var2 = FALSE, var3 = FALSE, var4 = FALSE,
var5 = FALSE, var6 = FALSE, var7 = FALSE, var8 = FALSE))
expect_identical(lapply(funcParams, `[[`, "default"),
list(var0 = 420.69, var1 = NA, var2 = 1L:2L, var3 = NA, var4 = NA, var5 = FALSE,
var6 = list(name = c("luke", "bob"), lastname = c("skywalker", "ross")), var7 = NA, var8 = NA))
expect_identical(lapply(funcParams, `[[`, "example"),
list(var0 = 420.69, var1 = NA, var2 = 1L:2L, var3 = NA, var4 = NA, var5 = FALSE,
var6 = list(name = c("luke", "bob"), lastname = c("skywalker", "ross")), var7 = NA, var8 = NA))
expect_identical(lapply(funcParams, `[[`, "isArray"),
list(var0 = defaultIsArray, var1 = defaultIsArray, var2 = TRUE,
var3 = defaultIsArray, var4 = defaultIsArray,
var5 = defaultIsArray, var6 = TRUE,
var7 = defaultIsArray, var8 = defaultIsArray))
expect_identical(lapply(funcParams, `[[`, "type"),
list(var0 = "number", var1 = defaultApiType, var2 = "integer", var3 = defaultApiType, var4 = defaultApiType,
var5 = "boolean", var6 = "object", var7 = defaultApiType, var8 = defaultApiType))
})
test_that("priorize works as expected", {
expect_identical("abc", priorizeProperty(structure("zzz", default = TRUE), NULL, "abc"))
expect_identical(NULL, priorizeProperty(NULL, NULL, NULL))
expect_identical(structure("zzz", default = TRUE), priorizeProperty(structure("zzz", default = TRUE), NULL, NA))
expect_identical(NULL, priorizeProperty())
})
test_that("custom spec works", {
pr <- pr()
pr$handle("POST", "/func1", function(){})
pr$handle("GET", "/func2", function(){})
pr$handle("GET", "/func3", function(){})
customSpec <- function(spec) {
custom <- list(info = list(description = "My Custom Spec", title = "This is only a test"))
return(utils::modifyList(spec, custom))
}
pr$setApiSpec(customSpec)
spec <- pr$getApiSpec()
expect_equal(spec$info$description, "My Custom Spec")
expect_equal(spec$info$title, "This is only a test")
expect_equal(class(spec$openapi), "character")
})
test_that("no params plumber router still produces spec when there is a func params", {
pr <- pr()
handler <- function(num) { sum(as.integer(num)) }
pr$handle("GET", "/sum", handler, serializer = serializer_json())
spec <- pr$getApiSpec()
expect_equal(spec$paths$`/sum`$get$parameters[[1]]$name, "num")
})
test_that("Response content type set with serializer", {
a <- pr()
pr_get(a, "/json", function() {"OK"}, serializer = serializer_json)
pr_get(a, "/csv", function() {"OK"}, serializer = serializer_csv())
spec <- a$getApiSpec()
expect_equal(spec$paths$`/json`$get$responses$`200`$content, list("application/json" = list(schema = list(type = "object"))))
expect_equal(spec$paths$`/csv`$get$responses$`200`$content, list("text/csv" = list(schema = list(type = "string"))))
})
test_that("Api spec can be set using a file path", {
pr <- pr() %>% pr_set_api_spec(test_path("files/openapi.yaml"))
expect_equal(pr$getApiSpec()$paths$`/health-check`$get$summary, " Determine if the API is running and listening as expected")
}) |
wrcc_createMetaDataframe <- function(
tbl,
unitID = as.character(NA),
pwfslDataIngestSource = 'WRCC',
existingMeta = NULL,
addGoogleMeta = FALSE,
addEsriMeta = FALSE
) {
logger.debug(" ----- wrcc_createMetaDataframe() ----- ")
if ( !'monitorType' %in% names(tbl) ) {
logger.error("No 'monitorType' column found in 'tbl' tibble with columns: %s", paste0(names(tbl), collapse=", "))
stop(paste0("No 'monitorType' column found in 'tbl' tibble."))
}
monitorType <- unique(tbl$monitorType)
if ( length(monitorType) > 1 ) {
logger.error("Multilpe monitor types found in 'tbl' tibble: %s", paste0(monitorType, collapse=", "))
stop(paste0("Multiple monitor types found in 'tbl' tibble."))
}
monitorType <- monitorType[1]
if ( !'deploymentID' %in% names(tbl) ) {
logger.error("No 'deploymentID' column found in 'tbl' tibble with columns: %s", paste0(names(tbl), collapse=", "))
stop(paste0("No 'deploymentID' column found in 'tbl' tibble. Have you run addClustering()?"))
}
tbl <- tbl[!duplicated(tbl$deploymentID),]
logger.trace("Tibble contains %d unique deployment(s)", nrow(tbl))
meta <- createEmptyMetaDataframe(nrow(tbl))
meta$longitude <- as.numeric(tbl$medoidLon)
meta$latitude <- as.numeric(tbl$medoidLat)
meta$elevation <- as.numeric(NA)
meta$timezone <- as.character(NA)
meta$countryCode <- as.character(NA)
meta$stateCode <- as.character(NA)
meta$siteName <- as.character(NA)
meta$countyName <- as.character(NA)
meta$msaName <- as.character(NA)
meta$agencyName <- as.character(NA)
meta$monitorType <- as.character(tbl$monitorType)
meta$siteID <- as.character(tbl$deploymentID)
meta$instrumentID <- paste0('wrcc.',unitID)
meta$aqsID <- as.character(NA)
meta$pwfslID <- as.character(tbl$deploymentID)
meta$pwfslDataIngestSource <- as.character(pwfslDataIngestSource)
meta$telemetryAggregator <- paste0('wrcc')
meta$telemetryUnitID <- as.character(unitID)
meta$monitorID <- paste(meta$siteID, meta$instrumentID, sep='_')
meta <- addMazamaMetadata(meta, existingMeta=existingMeta)
NPSMask <- stringr::str_detect(tbl$monitorName,'^Smoke NPS')
USFSMask <- stringr::str_detect(tbl$monitorName,'^Smoke USFS')
meta$agencyName[NPSMask] <- 'National Park Servsice'
meta$agencyName[USFSMask] <- 'United States Forest Service'
if ( addGoogleMeta ) {
result <- try( meta <- addGoogleElevation(meta, existingMeta=existingMeta),
silent=TRUE )
if ( "try-error" %in% class(result) ) {
logger.warn("Unable to add Google elevations: %s", geterrmessage())
}
}
if ( addEsriMeta ) {
result <- try( meta <- addEsriAddress(meta, existingMeta=existingMeta),
silent=TRUE )
if ( "try-error" %in% class(result) ) {
logger.warn("Unable to add ESRI addresses: %s", geterrmessage())
}
}
rownames(meta) <- meta$monitorID
logger.trace("Created 'meta' dataframe with %d rows and %d columns", nrow(meta), ncol(meta))
return(meta)
} |
nobs.kspm <- function(object, ...)
{
return(object$n)
} |
download_files <- function(dllist, overwrite = FALSE) {
assert_that(is_list_of_df(dllist))
assert_that(is_logical(overwrite))
dl_files <- function(dir, file, url) {
if (!dir.exists(dir)) {
pretty_message(paste0("Creating directory: ", dir))
chk <- dir.create(dir, recursive = TRUE)
stopifnot(chk)
}
pretty_message(paste0("Downloading binary: ", url), "\n")
wd <- httr::write_disk(file.path(dir, file), overwrite = TRUE)
res <- httr::GET(url, wd)
httr::stop_for_status(res)
res
}
dlfiles <- lapply(names(dllist), function(platform) {
platformDF <- dllist[[platform]]
if (!overwrite) {
platformDF <- platformDF[!platformDF[["exists"]], ]
}
if (identical(nrow(platformDF), 0L)) {
return(data.frame(
platform = character(), file = character(),
processed = logical(), stringsAsFactors = FALSE
))
}
res <- Map(dl_files,
dir = platformDF[["dir"]],
file = platformDF[["file"]],
url = platformDF[["url"]], USE.NAMES = FALSE
)
res <- vapply(res, class, character(1)) == "response"
data.frame(
platform = platform,
file = file.path(
platformDF[["dir"]],
platformDF[["file"]]
),
processed = res,
stringsAsFactors = FALSE
)
})
invisible(do.call(rbind.data.frame, dlfiles))
} |
context('stored data')
test_that('storedData',{
data(leroy)
expect_true(validObject(leroy))
data(fishers)
expect_true(validObject(fishers))
data(dbbmmstack)
expect_true(validObject(dbbmmstack))
data(leroydbbmm)
expect_true(validObject(leroydbbmm))
}) |
NULL
NULL
CoefQuartVarCI <- R6::R6Class(
classname = "CoefQuartVarCI",
inherit = CoefQuartVar,
public = list(
x = NA,
na.rm = FALSE,
digits = 1,
R = 1000,
alpha = 0.05,
zzz = NA,
f1square = NA,
f3square = NA,
D = NA,
S = NA,
v = NA,
ccc = NA,
bootcqv = NA,
initialize = function(
x = NA,
na.rm = FALSE,
digits = 1,
R = 1000,
alpha = 0.05,
...
) {
if (missing(x) || is.null(x)) {
stop("object 'x' not found")
} else if (!missing(x)) {
self$x <- x
}
if (!missing(na.rm)) {
self$na.rm <- na.rm
}
if (self$na.rm == TRUE) {
self$x <- x[!is.na(x)]
} else if (anyNA(x) & self$na.rm == FALSE) {
stop(
"missing values and NaN's not allowed if 'na.rm' is FALSE"
)
}
if (!is.numeric(x)) {
stop("argument is not a numeric vector")
}
if (!missing(digits)) {
self$digits <- digits
}
if (!missing(R)) {
self$R <- R
}
if (!missing(alpha)) {
self$alpha <- alpha
}
self$zzz = function(...) {
qnorm((1 - ((1 - super$alphastar())/2)))
}
self$f1square = function(...) {
(3 * (self$zzz())^2)/(
4 * length(self$x) * ((super$Yb() - super$Ya())^2))
}
self$f3square = function(...) {
(3 * (self$zzz())^2)/(
4 * length(self$x) * ((super$Yd() - super$Yc())^2))
}
self$D = function(...) {
super$super_$super_$initialize(
x = self$x,
na.rm = self$na.rm,
probs = 0.75,
names = FALSE
) - super$super_$super_$initialize(
x = self$x,
na.rm = self$na.rm,
probs = 0.25,
names = FALSE
)
}
self$S = function(...) {
super$super_$super_$initialize(
x = self$x,
na.rm = self$na.rm,
probs = 0.75,
names = FALSE
) + super$super_$super_$initialize(
x = self$x,
na.rm = self$na.rm,
probs = 0.25,
names = FALSE
)
}
self$v = function(...) {
(
(1/(16 * length(self$x))) * (
(((3/self$f1square()) + (3/self$f3square()) - (
2/sqrt(self$f1square() * self$f3square()))) /
self$D()^2) +
(((3/self$f1square()) + (3/self$f3square()) +
(2/sqrt(self$f1square() * self$f3square()))) /
self$S()^2) -
((2 * ((3/self$f3square()) - (3/self$f1square()))) /
(self$D()*self$S()))
)
)
}
self$ccc = function(...) {length(self$x)/(length(self$x) - 1)}
self$bootcqv = function(...) {
return(
super$super_$initialize(
x = self$x,
na.rm = self$na.rm,
R = self$R,
alpha = self$alpha
))
}
self$bootcqv()
},
bonett_ci = function(...) {
return(
list(
method = "cqv with Bonett CI",
statistics = data.frame(
est = round(super$est(), digits = self$digits),
lower = (
round(
(100 * exp(
((SciViews::ln((self$D()/self$S())) *
self$ccc())) -
(self$zzz() * (self$v()^(0.5)))
)), digits = self$digits
)
),
upper = (
round(
(100 * exp(
((SciViews::ln((self$D()/self$S())) *
self$ccc())) +
(self$zzz() * (self$v()^(0.5)))
)), digits = self$digits
)
),
row.names = c(" ")
)
)
)
},
norm_ci = function(...) {
return(
list(
method = "cqv with normal approximation bootstrap CI",
statistics = data.frame(
est = round(super$est(), digits = self$digits),
lower = round(
self$boot_norm_ci()$normal[2],
digits = self$digits),
upper = round(
self$boot_norm_ci()$normal[3],
digits = self$digits),
row.names = c(" ")
)
)
)
},
basic_ci = function(...) {
return(
list(
method = "cqv with basic bootstrap CI",
statistics = data.frame(
est = round(super$est(), digits = self$digits),
lower = round(
self$boot_basic_ci()$basic[4],
digits = self$digits),
upper = round(
self$boot_basic_ci()$basic[5],
digits = self$digits),
row.names = c(" ")
)
)
)
},
perc_ci = function(...) {
return(
list(
method = "cqv with bootstrap percentile CI",
statistics = data.frame(
est = round(super$est(), digits = self$digits),
lower = round(
self$boot_perc_ci()$percent[4],
digits = self$digits),
upper = round(
self$boot_perc_ci()$percent[5],
digits = self$digits),
row.names = c(" ")
)
)
)
},
bca_ci = function(...) {
return(
list(
method = "cqv with adjusted bootstrap percentile (BCa) CI",
statistics = data.frame(
est = round(super$est(), digits = self$digits),
lower = round(
self$boot_bca_ci()$bca[4],
digits = self$digits),
upper = round(
self$boot_bca_ci()$bca[5],
digits = self$digits),
row.names = c(" ")
)
)
)
},
all_ci = function(...) {
return(
list(
method = "All methods",
statistics = data.frame(
row.names = c(
"bonett",
"norm",
"basic",
"percent",
"bca"
),
est = c(
round(super$est(), digits = self$digits),
round(super$est(), digits = self$digits),
round(super$est(), digits = self$digits),
round(super$est(), digits = self$digits),
round(super$est(), digits = self$digits)
),
lower = c(
round(
(100 * exp(
((SciViews::ln((self$D()/self$S())) *
self$ccc())) -
(self$zzz() * (self$v()^(0.5)))
)), digits = self$digits
),
round(
self$boot_norm_ci()$normal[2],
digits = self$digits),
round(
self$boot_basic_ci()$basic[4],
digits = self$digits),
round(
self$boot_perc_ci()$percent[4],
digits = self$digits),
round(
self$boot_bca_ci()$bca[4],
digits = self$digits)
),
upper = c(
round(
(100 * exp(
((SciViews::ln((self$D()/self$S())) *
self$ccc())) +
(self$zzz() * (self$v()^(0.5)))
)), digits = self$digits
),
round(
self$boot_norm_ci()$normal[3],
digits = self$digits),
round(
self$boot_basic_ci()$basic[5],
digits = self$digits),
round(
self$boot_perc_ci()$percent[5],
digits = self$digits),
round(
self$boot_bca_ci()$bca[5],
digits = self$digits)
),
description = c(
"cqv with Bonett CI",
"cqv with normal approximation CI",
"cqv with basic bootstrap CI",
"cqv with bootstrap percentile CI",
"cqv with adjusted bootstrap percentile (BCa) CI"
)
)
)
)
}
)
) |
thetafun <- function(theta, WfdList, U,
itermax = 20, crit = 1e-3, itdisp=FALSE) {
if (!inherits(WfdList,"list"))
stop("Arguments WfdList is not list object.")
N <- nrow(U)
n <- ncol(U)
if (length(theta) != N)
{
stop("Length of theta not equal to nrow(U).")
}
if (any(theta < 0) || any(theta > 100))
stop('Values of theta out of bounds.')
if (length(WfdList) != n)
stop("Length of WfdList not equal to ncol(U).")
Hval <- Hfun(theta, WfdList, U)
DHList <- DHfun(theta, WfdList, U)
DHval <- DHList$DH
D2Hval <- DHList$D2H
ngrid <- 26
jneg <- which(D2Hval <= 0)
if (length(jneg) > 0)
{
if (itdisp) {
print(paste("Number of nonpositive D2H =",length(jneg)))
}
thetatry <- seq(0,100,length.out=ngrid)
for (j in 1:length(jneg))
{
jind <- jneg[j]
Uj <- matrix(U[jind,], 1)[rep(1,ngrid), ]
Htry <- Hfun(thetatry, WfdList, Uj)
Hmin <- min(Htry)
kmin <- which(Htry == Hmin)
theta[jind] <- thetatry[kmin[1]]
}
Hvalnonpos <- Hfun(theta[jneg], WfdList, U[jneg,])
result <- DHfun(theta[jneg], WfdList, U[jneg,])
DHvalnonpos <- result$DH
D2Hvalnonpos <- result$D2H
Hval[jneg] <- Hvalnonpos
DHval[jneg] <- DHvalnonpos
D2Hval[jneg] <- D2Hvalnonpos
}
if (itdisp) {
print(paste("mean adjusted values =",round(mean(theta[jneg]),2)))
}
if (itermax == 0)
{
theta_out <- theta
return(theta_out)
}
active <- ActiveTestFn(theta, DHval, D2Hval, crit)
nactive <- sum(active)
thetaa <- theta[active]
Ha <- Hval[active]
DHa <- DHval[active]
D2Ha <- D2Hval[active]
iter <- 0
while(nactive > 0 && iter < itermax)
{
iter <- iter + 1
if (itdisp) {
print(paste("iter",iter,", nactive = ",nactive))
}
step <- DHa/D2Ha
step[step < -10] <- -10
step[step > 10] <- 10
stepind0 <- which(thetaa - step <= 0)
stepindn <- which(thetaa - step >= 100)
if (length(stepind0) > 0)
{
step[stepind0] <- (thetaa[stepind0] - 0)
}
if (length(stepindn) > 0)
{
step[stepindn] <- -(100 - thetaa[stepindn])
}
thetaanew <- theta[active]
Uanew <- as.matrix(U[active,])
Hanew <- Hval[active]
fac <- 1
stepiter <- 0
failindex <- 1:nactive
while(length(failindex) > 0 && stepiter < 10)
{
stepiter <- stepiter + 1
stepnew <- fac * step[failindex]
thetaanew[failindex] <- thetaa[failindex] - stepnew
if (nactive == 1)
{
Uanewfail <- Uanew
} else
{
Uanewfail <- as.matrix(Uanew[failindex,])
}
Hanew[failindex] <- Hfun(thetaanew[failindex], WfdList, Uanewfail)
failindex <- which((Hval[active] - Hanew) < -crit)
fac <- fac/2
}
theta[active] <- thetaanew
Ha <- Hanew
DHLista <- DHfun(theta[active], WfdList, as.matrix(U[active,]))
DHa <- DHLista$DH
D2Ha <- DHLista$D2H
jneg <- which(D2Ha <= 0)
Hval[active] <- Ha
DHval[active] <- DHa
D2Hval[active] <- D2Ha
active <- ActiveTestFn(thetaanew, DHa, D2Ha, crit, active)
nactive <- length(which(active == TRUE))
if (nactive > 0)
{
thetaa <- theta[active]
DHa <- DHval[active]
D2Ha <- D2Hval[active]
}
}
theta_out <- theta
return(list(theta_out=theta_out, Hval=Hval, DHval=DHval, D2Hval=D2Hval, iter=iter))
}
ActiveTestFn <- function(theta, DHval, D2Hval, crit = 1e-3, activeold = NULL) {
if (is.null(activeold)) {
N <- length(theta)
activenew <- rep(FALSE, N)
for (j in 1:N) {
thetaj <- theta[j]
test <- (thetaj > 0 && thetaj < 100) |
(thetaj == 0 && DHval[j] < 0) |
(thetaj == 100 && DHval[j] > 0)
if (test) activenew[j] <- TRUE
}
} else {
nactive <- length(theta)
N <- length(activeold)
activenew <- rep(FALSE,N)
activeind <- which(activeold)
for (j in 1:nactive) {
thetaj <- theta[j]
DHaj <- DHval[j]
D2Haj <- D2Hval[j]
test1 <- thetaj > 10 && abs(DHaj) > 10 * crit && D2Haj > 0 &&
thetaj > 0 && thetaj < 100
test2 = thetaj <= 10 && abs(DHaj) > 50 * crit && D2Haj > 0 &&
thetaj > 0 && thetaj < 100
test3 <- thetaj == 0 && DHaj < 0
test4 <- thetaj == 100 && DHaj > 0
if (test1 || test2 || test3 || test4)
activenew[activeind[j]] <- TRUE
}
}
return(activenew)
} |
expected <- eval(parse(text="structure(list(c(\"1\", \"2\", NA)), .Names = \"\")"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(1L, 2L, 1L), .Dim = 3L, .Dimnames = structure(list(c(\"1\", \"2\", NA)), .Names = \"\"), class = \"table\"))"));
do.call(`dimnames`, argv);
}, o=expected); |
mathmlPlot <-
function(node)
{
UseMethod("mathmlPlot",node)
}
mathmlPlot.XMLDocument <-
function(doc)
{
return(mathmlPlot(doc$doc$children))
}
mathmlPlot.default <-
function(children)
{
expr <- expression()
i <- 1
ok <- (i <= length(children))
while(ok) {
child <- children[[i]]
if(is.null(child)) {
i <- i+1
ok <- (i <= length(children))
next
}
if(!is.null(class(child)) && class(child) == "XMLComment") {
i <- i+1
ok <- (i <= length(children))
next
}
if(xmlName(child) == "mo") {
op <- child$children[[1]]$value
if(op == "sum") {
tmp <- c(as.name(op), quote(x[i]),mathmlPlot(children[[i+1]]), mathmlPlot(children[[i+2]]))
expr <- c(expr, tmp)
i <- i+2
} else {
expr <- c(mathmlPlot(child), expr , mathmlPlot(children[[i+1]]))
}
mode(expr) <- "call"
i <- i+1
} else {
expr <- c(expr, mathmlPlot(child))
}
i <- i+1
ok <- (i <= length(children))
}
return(expr)
}
mathmlPlot.XMLEntityRef <-
function(node)
{
nm <- xmlName(node)
val <- switch(nm,
PlusMinus=as.name("%+-%"),
InvisibleTimes=as.name("*"),
int=as.name("integral"),
infty = as.name("infinity"),
NULL
)
if(is.null(val)) {
val <- as.name(nm)
}
return(val)
}
mathmlPlot.XMLNode <-
function(node)
{
nm <- name(node)
if(nm == "mi" || nm == "ci") {
val <- c(as.name("italic"),mathmlPlot(node$children))
mode(val) <- "call"
} else if(nm == "msqrt") {
val <- c(as.name("sqrt"), mathmlPlot(node$children))
mode(val) <- "call"
} else if(nm == "msubsup") {
tmp <- c(as.name("^"), mathmlPlot(node$children[[1]]),mathmlPlot(node$children[[2]]))
mode(tmp) <- "call"
val <- c(as.name("["), tmp, mathmlPlot(node$children[[3]]))
mode(val) <- "call"
} else if(nm == "mrow") {
val <- mathmlPlot(node$children)
} else if(nm == "text") {
val <- node$value
} else if(nm == "mo") {
if(inherits(node$children[[1]],"XMLEntityRef"))
val <- mathmlPlot(node$children[[1]])
else {
op <- node$children[[1]]$value
tmp <- switch(op,
"=" = "==",
op)
val <- as.name(tmp)
}
} else if(nm == "mfrac") {
val <- list(as.name("frac"), mathmlPlot(node$children[[1]]), mathmlPlot(node$children[[2]]))
mode(val) <- "call"
} else if(nm == "msup" || nm == "msub") {
op <- switch(nm, "msup" = "^", "msub"="[")
val <- c(as.name(op), mathmlPlot(node$children[[1]]), mathmlPlot(node$children[[2]]))
mode(val) <- "call"
} else if(nm == "mn" || nm == "cn") {
val <- as.numeric(node$children[[1]]$value)
} else if(nm == "mstyle") {
val <- mathmlPlot(node$children)
} else if(nm == "munderover") {
val <- mathmlPlot(node$children)
} else if(nm == "mroot") {
val <- c(as.name("sqrt"), mathmlPlot(node$children[[1]]), mathmlPlot(node$children[[2]]))
mode(val) <- "call"
} else if(nm == "reln") {
val <- mathmlPlot(node$children)
mode(val) <- "call"
} else if(nm == "eq") {
val <- as.name("==")
} else if(nm == "geq") {
val <- as.name(">=")
} else if(nm == "set") {
n <- min( (1:length(node$children))[sapply(node$children, xmlName) == "condition"])
cat("Condition @",n,"\n")
args <- c(mathmlPlot(node$children[1:(n-1)]), "|", mathmlPlot(node$children[n:length(node$children)]))
args <- c(as.name("paste"), args)
mode(args) <- "call"
val <- list(as.name("group"),"{", args,"}")
mode(val) <- "call"
} else if(nm == "bvar") {
val <- mathmlPlot(node$children)
} else if(nm == "condition") {
val <- mathmlPlot(node$children)
} else if(nm == "interval") {
sep <- xmlAttrs(node)[["closure"]]
sep <- switch(sep,
open=c("(",")"),
closed=c("[","]"),
"closed-open"=c("[",")"),
"open-closed"=c("(","]"),
)
els <- mathmlPlot(node$children)
els <- c(as.name("paste"), els[[1]],",",els[[2]])
mode(els) <- "call"
val <- list(as.name("group"),sep[1], els ,sep[2])
mode(val) <- "call"
} else if(nm == "power") {
val <- c(as.name("^"), mathmlPlot(node$children[[1]]), mathmlPlot(node$children[[2]]))
} else if(nm == "plus") {
val <- as.name("+")
} else if(nm == "apply") {
val <- mathmlPlot.apply(node)
}
return(val)
}
mathmlPlot.apply <-
function(node)
{
sub <- mathmlPlot(node$children)
nm <- xmlName(node$children[[1]])
print(node$children[[1]])
if(nm == "plus" || nm == "minus" || nm == "times" || nm == "div" ) {
print(sub[[1]])
val <- c(mathmlPlot(node$children[[1]]), sub[[2]], sub[[3]])
mode(val) <- "call"
for(i in 4:length(sub)) {
tmp <- c(mathmlPlot(node$children[[1]]), val, sub[[i]])
mode(tmp) <- "call"
val <- tmp
}
} else {
val <- sub
mode(val) <- "call"
}
return(val)
} |
DCCSWA <- function(Data, Group, ncomp=NULL, Scale=FALSE, graph=FALSE){
check(Data, Group)
if (is.data.frame(Data) == TRUE) {
Data=as.matrix(Data)
}
if(is.null(ncomp)) {ncomp=2}
if(is.null(colnames(Data))) {
colnames(Data) = paste('V', 1:ncol(Data), sep='')
}
Group = as.factor(Group)
rownames(Data)=Group
M=length(levels(Group))
P=dim(Data)[2]
n=as.vector(table(Group))
N=sum(n)
split.Data=split(Data,Group)
for(m in 1:M){
split.Data[[m]]=matrix(split.Data[[m]],nrow=n[m])
split.Data[[m]]<-scale(split.Data[[m]],center=TRUE,scale=Scale)
}
Con.Data = split.Data[[1]]
for(m in 2:M) {
Con.Data = rbind(Con.Data, split.Data[[m]])
}
rownames(Con.Data) = Group
colnames(Con.Data) = colnames(Data)
cov.Group=vector("list", M)
for(m in 1:M){
cov.Group[[m]] = t(split.Data[[m]]) %*% split.Data[[m]] / n[m]
}
Itot = 0
for (m in 1:M) {
Itot = Itot + sum(cov.Group[[m]]^2)
}
saliences = matrix(0,M,ncomp)
A = matrix(0,nrow=P,ncol=ncomp)
explained = matrix(0,ncomp)
res <- list(
Data = Data,
Con.Data = Con.Data,
split.Data = split.Data,
Group=Group)
for (h in 1:ncomp) {
salience= c(rep(1,M))
threshold = 1e-10
deltafit = 1000000;
previousfit = Itot;
while(deltafit > threshold){
Vc = 0
for(m in 1:M){
Vc = salience[m] * cov.Group[[m]] + Vc
}
a = eigen(Vc)$vectors[,1]
for(m in 1:M){
salience[m] = t(a) %*% cov.Group[[m]] %*% a
}
def=0
for(m in 1:M){
def = sum(cov.Group[[m]] - salience[m] * as.matrix(a) %*% t(as.matrix(a)))^2 + def
}
deltafit = previousfit-def
previousfit = def
}
explained[h,1] = 100 * sum(salience ^2) / Itot
saliences[,h] = salience;
A[,h] = a;
aux = diag(1,P)- matrix(a,ncol=1) %*% matrix(a,nrow=1);
for (m in 1:M) {
split.Data[[m]] = split.Data[[m]] %*% aux
cov.Group[[m]] = t(split.Data[[m]]) %*% split.Data[[m]]
}
}
res$loadings.common=A
rownames(res$loadings.common)=colnames(Data)
colnames(res$loadings.common)=paste("Dim", 1:ncomp, sep="")
res$saliences= saliences
rownames(res$saliences) = levels(Group)
colnames(res$saliences) = paste("Dim", 1:ncomp, sep="")
expl = matrix(0, nrow=ncomp, ncol=2)
expl[,1] = c(explained)
expl[,2] = cumsum(expl[,1])
res$exp.variance = expl
rownames(res$exp.variance) = paste("Dim", 1:ncomp, sep="")
colnames(res$exp.variance) = c("%Total Var expl", "Cumul % total Var")
Y<-scale(Data,center=TRUE,scale=FALSE)
Datam=split(Y, Group)
for(m in 1:M){
Datam[[m]] = matrix(Datam[[m]], nrow=n[m])
Datam[[m]] = scale(Datam[[m]], center=TRUE, scale=FALSE)
}
for(m in 1:M) {
cov.Group[[m]] = t(Datam[[m]]) %*% Datam[[m]] / n[m]
}
lambda = matrix(0, nrow=M, ncol=ncomp)
for(m in 1:M){
lambda[m,]=round(diag(t(A) %*% (cov.Group[[m]]) %*% A),3)
}
res$lambda = lambda
rownames(res$lambda) = levels(Group)
colnames(res$lambda) = paste("Dim", 1:ncomp, sep="")
exp.var = matrix(0,M,ncomp)
for(m in 1:M){
exp.var[m,] = 100 * lambda[m,]/ sum(diag(cov.Group[[m]]))
}
res$exp.var = exp.var
rownames(res$exp.var) = levels(Group)
colnames(res$exp.var) = paste("Dim", 1:ncomp, sep="")
if(graph) {plot.mg(res)}
class(res) = c("DCCSWA", "mg")
return(res)
}
print.DCCSWA <- function(x, ...)
{
cat("\nDual Common Component and Specific Weights Analysis\n")
cat(rep("-",43), sep="")
cat("\n$loadings.common ", "common loadings")
cat("\n$Data ", "Data set")
cat("\n")
invisible(x)
} |
library(testthat)
source("../helpers.R")
library(datasets)
data("iris")
test_that("it fails for invalid arguments", {
expect_does_throw({
mmb::bayesRegress(df = data.frame(), features = data.frame(), targetCol = "foo", numBuckets = 1)
})
m <- mmb::getMessages()
mmb::setMessages(TRUE)
w <- mmb::getWarnings()
mmb::setWarnings(FALSE)
expect_message({
mmb::bayesRegress(
df = iris[1:100, ],
features = mmb::sampleToBayesFeatures(iris[101, ], "Sepal.Length"),
targetCol = "Sepal.Length", numBuckets = 2)
}, "No explicit feature selection")
mmb::setWarnings(w)
mmb::setMessages(m)
})
test_that("we can also sample from the most likely range only", {
w <- mmb::getWarnings()
mmb::setWarnings(TRUE)
res <- expect_warning({
mmb::bayesRegress(
df = iris[1:100, ],
features = mmb::sampleToBayesFeatures(iris[101, ], "Petal.Width"),
targetCol = "Petal.Width", selectedFeatureNames = c("Species", "Sepal.Length"),
sampleFromAllBuckets = FALSE, numBuckets = NA)
}, "Segmenting stopped prematurely")
expect_false(is.nan(res))
expect_gt(res, 0)
})
test_that("custom regressor errors are handled properly", {
w <- mmb::getWarnings()
mmb::setWarnings(TRUE)
res <- expect_warning({
mmb::bayesRegress(
df = iris[1:5, ],
features = mmb::sampleToBayesFeatures(iris[101, ], "Petal.Width"),
targetCol = "Petal.Width", selectedFeatureNames = c("Species", "Sepal.Length"),
sampleFromAllBuckets = FALSE)
}, "Regressor returned NaN")
expect_true(is.nan(res))
res <- expect_warning({
mmb::bayesRegress(
df = iris[1:100, ],
features = mmb::sampleToBayesFeatures(iris[101, ], "Petal.Width"),
targetCol = "Petal.Width", selectedFeatureNames = c("Species", "Sepal.Length"),
sampleFromAllBuckets = FALSE, regressor = function(vec) stop("--42--"))
}, "--42--")
expect_true(is.nan(res))
rd <- mmb::getDefaultRegressor()
mmb::setDefaultRegressor(function(data) paste(ceiling(data), collapse = "-"))
res <- expect_warning({
mmb::bayesRegress(
df = iris[1:100, ],
features = mmb::sampleToBayesFeatures(iris[101, ], "Petal.Width"),
targetCol = "Petal.Width", selectedFeatureNames = c("Species", "Sepal.Length"),
sampleFromAllBuckets = FALSE)
}, "Segmenting stopped")
expect_equal(grep("^\\d+?(\\-\\d+?)*?$", res), 1)
mmb::setDefaultRegressor(rd)
mmb::setWarnings(w)
})
test_that("we can do regression for multiple values", {
w <- mmb::getWarnings()
mmb::setWarnings(FALSE)
df <- iris[, ]
set.seed(84735)
rn <- base::sample(rownames(df), 150)
dfTrain <- df[1:120, ]
dfValid <- df[121:150, ]
res <- mmb::bayesRegressAssign(
dfTrain, dfValid[, !(colnames(dfValid) %in% "Sepal.Length")],
"Sepal.Length", sampleFromAllBuckets = TRUE, doEcdf = TRUE)
c <- cov(res, iris[121:150,]$Sepal.Length)^2
expect_true(all(c >= 0) && all(c <= 1))
mmb::setWarnings(w)
})
test_that("regression for multiple values works in simple and online, too", {
w <- mmb::getWarnings()
mmb::setWarnings(FALSE)
df <- iris[, ]
set.seed(84735)
rn <- base::sample(rownames(df), 150)
dfTrain <- df[1:120, ]
dfValid <- df[121:150, ]
res <- mmb::bayesRegressAssign(
dfTrain, dfValid[, !(colnames(dfValid) %in% "Sepal.Length")],
"Sepal.Length", sampleFromAllBuckets = FALSE, doEcdf = FALSE, online = 100, numBuckets = NA)
c <- cov(res, iris[121:150,]$Sepal.Length)^2
expect_true(all(c >= 0) && all(c <= 1))
res <- mmb::bayesRegressAssign(
dfTrain, dfValid[, ],
"Sepal.Length", sampleFromAllBuckets = TRUE, doEcdf = FALSE, simple = TRUE)
c <- cov(res, iris[121:150,]$Sepal.Length)^2
expect_true(all(c >= 0) && all(c <= 1))
mmb::setWarnings(w)
}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.