code
stringlengths 1
13.8M
|
---|
context("IData indexing operations")
test_that("row-only indexing works correctly for Idata objects", {
Xbnds <- data.frame(XLB=c(1,2,4),XUB=c(9,7,6),row.names=paste("Unit",1:3))
Ybnds <- data.frame(YLB=c(10,3,5),YUB=c(15,8,6),row.names=paste("Unit",1:3))
Allbnds <- cbind(Xbnds,Ybnds)
Idt <- IData(Allbnds,VarNames = c("X","Y"))
Idt2 <- IData(Allbnds[2,],VarNames = c("X","Y"))
Idt13 <- IData(Allbnds[c(1,3),],VarNames = c("X","Y"))
Idt31 <- IData(Allbnds[c(3,1),],VarNames = c("X","Y"))
Idt23 <- IData(Allbnds[2:3,],VarNames = c("X","Y"))
Idt32 <- IData(Allbnds[3:2,],VarNames = c("X","Y"))
expect_identical(Idt[2,],Idt2)
expect_identical(Idt[-c(1,3),],Idt2)
expect_identical(Idt[c(1,3),],Idt13)
expect_identical(Idt[-2,],Idt13)
expect_identical(Idt[c(3,1),],Idt31)
expect_identical(Idt[2:3,],Idt23)
expect_identical(Idt[-1,],Idt23)
expect_identical(Idt[3:2,],Idt32)
} )
test_that("column-only indexing works correctly for Idata objects", {
Lbnds <- data.frame(XLB=c(1,2,4),YLB=c(10,3,5),ZLB=c(8,5,4),row.names=paste("Unit",1:3))
Ubnds <- data.frame(XUB=c(9,7,6),YUB=c(15,8,6),ZUB=c(12,9,7),row.names=paste("Unit",1:3))
Idt <- IData(cbind(Lbnds,Ubnds),Seq="AllLb_AllUb",VarNames = c("X","Y","Z"))
Idt2 <- IData(cbind(Lbnds[,2,drop=FALSE],Ubnds[,2,drop=FALSE]),Seq="AllLb_AllUb",VarNames = "Y")
Idt13 <- IData(cbind(Lbnds[,c(1,3)],Ubnds[,c(1,3)]),Seq="AllLb_AllUb",VarNames = c("X","Z"))
Idt31 <- IData(cbind(Lbnds[,c(3,1)],Ubnds[,c(3,1)]),Seq="AllLb_AllUb",VarNames = c("Z","X"))
Idt23 <- IData(cbind(Lbnds[,2:3],Ubnds[,2:3]),Seq="AllLb_AllUb",VarNames = c("Y","Z"))
Idt32 <- IData(cbind(Lbnds[,3:2],Ubnds[,3:2]),Seq="AllLb_AllUb",VarNames = c("Z","Y"))
expect_identical(Idt[,2],Idt2)
expect_identical(Idt[,-c(1,3)],Idt2)
expect_identical(Idt[,c(1,3)],Idt13)
expect_identical(Idt[,-2],Idt13)
expect_identical(Idt[,c(3,1)],Idt31)
expect_identical(Idt[,2:3],Idt23)
expect_identical(Idt[,-1],Idt23)
expect_identical(Idt[,3:2],Idt32)
} )
test_that("indexing by both rows and columns works correctly for Idata objects", {
Lbnds <- data.frame(XLB=c(1,2,4),YLB=c(10,3,5),ZLB=c(8,5,4),row.names=paste("Unit",1:3))
Ubnds <- data.frame(XUB=c(9,7,6),YUB=c(15,8,6),ZUB=c(12,9,7),row.names=paste("Unit",1:3))
Idt <- IData(cbind(Lbnds,Ubnds),Seq="AllLb_AllUb",VarNames = c("X","Y","Z"))
Idtr2c3 <- IData(cbind(Lbnds[2,3,drop=FALSE],Ubnds[2,3,drop=FALSE]),Seq="AllLb_AllUb",VarNames = "Z")
Idtr2c13 <- IData(cbind(Lbnds[2,c(1,3),drop=FALSE],Ubnds[2,c(1,3)]),Seq="AllLb_AllUb",VarNames = c("X","Z"))
Idtr13c2 <- IData(cbind(Lbnds[c(1,3),2,drop=FALSE],Ubnds[c(1,3),2]),Seq="AllLb_AllUb",VarNames = "Y")
Idtr13c21 <- IData(cbind(Lbnds[c(1,3),2:1],Ubnds[c(1,3),2:1]),Seq="AllLb_AllUb",VarNames = c("Y","X"))
Idtr32c12 <- IData(cbind(Lbnds[3:2,1:2],Ubnds[3:2,1:2]),Seq="AllLb_AllUb",VarNames = c("X","Y"))
expect_identical(Idt[2,3],Idtr2c3)
expect_identical(Idt[-c(1,3),3],Idtr2c3)
expect_identical(Idt[2,-(1:2)],Idtr2c3)
expect_identical(Idt[-c(1,3),-c(1,2)],Idtr2c3)
expect_identical(Idt[2,c(1,3)],Idtr2c13)
expect_identical(Idt[-c(1,3),c(1,3)],Idtr2c13)
expect_identical(Idt[2,-2],Idtr2c13)
expect_identical(Idt[-c(1,3),-2],Idtr2c13)
expect_identical(Idt[c(1,3),2],Idtr13c2)
expect_identical(Idt[-2,2],Idtr13c2)
expect_identical(Idt[c(1,3),-c(1,3)],Idtr13c2)
expect_identical(Idt[-2,-c(1,3)],Idtr13c2)
expect_identical(Idt[c(1,3),2:1],Idtr13c21)
expect_identical(Idt[-2,2:1],Idtr13c21)
expect_identical(Idt[3:2,1:2],Idtr32c12)
expect_identical(Idt[3:2,-3],Idtr32c12)
} )
|
rostdeviance <- function(object)
{
X <- object$X
N <- dim(X)[1]
K <- dim(X)[2]
x.ch <- apply(X,1,toString)
nx <- as.vector(table(x.ch))
lsat <- sum(nx*(log(nx/N)))
npar.sat <- prod(apply(X, 2, max) + 1) - 1
rv <- rowSums(X, na.rm = TRUE)
lmml <- sum(table(rv)*log(table(rv)/N))+object$loglik.cml
npar.mml <- dim(object$W)[2]
dev <- -2*(lmml - lsat)
df.chi <- npar.sat - npar.mml
p.value <- 1-pchisq(dev,df.chi)
result <- list(value = dev, df = df.chi, p.value = p.value)
return(result)
}
|
dv_vs_idv <- function(xpdb,
mapping = NULL,
group = 'ID',
type = 'pls',
title = '@y vs. @x | @run',
subtitle = 'Ofv: @ofv',
caption = '@dir',
tag = NULL,
log = NULL,
facets,
.problem,
quiet,
...) {
check_xpdb(xpdb, check = 'data')
if (missing(.problem)) .problem <- default_plot_problem(xpdb)
check_problem(.problem, .subprob = NULL, .method = NULL)
if (missing(quiet)) quiet <- xpdb$options$quiet
if (missing(facets)) facets <- xpdb$xp_theme$facets
xplot_scatter(xpdb = xpdb, group = group, quiet = quiet,
opt = data_opt(.problem = .problem,
filter = only_obs(xpdb, .problem, quiet)),
mapping = aes_c(aes_string(x = xp_var(xpdb, .problem, type = 'idv')$col,
y = xp_var(xpdb, .problem, type = 'dv')$col), mapping),
type = type, facets = facets,
xscale = check_scales('x', log),
yscale = check_scales('y', log),
title = title, subtitle = subtitle, caption = caption,
tag = tag, plot_name = as.character(match.call()[[1]]), ...)
}
ipred_vs_idv <- function(xpdb,
mapping = NULL,
group = 'ID',
type = 'pls',
facets,
title = '@y vs. @x | @run',
subtitle = 'Ofv: @ofv, Eps shrink: @epsshk',
caption = '@dir',
tag = NULL,
log = NULL,
.problem,
quiet,
...) {
check_xpdb(xpdb, check = 'data')
if (missing(.problem)) .problem <- default_plot_problem(xpdb)
check_problem(.problem, .subprob = NULL, .method = NULL)
if (missing(quiet)) quiet <- xpdb$options$quiet
if (missing(facets)) facets <- xpdb$xp_theme$facets
xplot_scatter(xpdb = xpdb, group = group, quiet = quiet,
opt = data_opt(.problem = .problem,
filter = only_obs(xpdb, .problem, quiet)),
mapping = aes_c(aes_string(x = xp_var(xpdb, .problem, type = 'idv')$col,
y = xp_var(xpdb, .problem, type = 'ipred')$col), mapping),
type = type, facets = facets,
xscale = check_scales('x', log),
yscale = check_scales('y', log),
title = title, subtitle = subtitle, caption = caption,
tag = tag, plot_name = as.character(match.call()[[1]]), ...)
}
pred_vs_idv <- function(xpdb,
mapping = NULL,
group = 'ID',
type = 'pls',
facets,
title = '@y vs. @x | @run',
subtitle = 'Ofv: @ofv',
caption = '@dir',
tag = NULL,
log = NULL,
.problem,
quiet,
...) {
check_xpdb(xpdb, check = 'data')
if (missing(.problem)) .problem <- default_plot_problem(xpdb)
check_problem(.problem, .subprob = NULL, .method = NULL)
if (missing(quiet)) quiet <- xpdb$options$quiet
if (missing(facets)) facets <- xpdb$xp_theme$facets
xplot_scatter(xpdb = xpdb, group = group, quiet = quiet,
opt = data_opt(.problem = .problem,
filter = only_obs(xpdb, .problem, quiet)),
mapping = aes_c(aes_string(x = xp_var(xpdb, .problem, type = 'idv')$col,
y = xp_var(xpdb, .problem, type = 'pred')$col), mapping),
type = type, facets = facets,
xscale = check_scales('x', log),
yscale = check_scales('y', log),
title = title, subtitle = subtitle, caption = caption,
tag = tag, plot_name = as.character(match.call()[[1]]), ...)
}
dv_preds_vs_idv <- function(xpdb,
mapping = NULL,
group = 'ID',
type = 'pls',
facets,
title = 'Observations, Individual and Population Predictions vs. @x | @run',
subtitle = 'Ofv: @ofv, Eps shrink: @epsshk',
caption = '@dir',
tag = NULL,
log = NULL,
.problem,
quiet,
...) {
check_xpdb(xpdb, check = 'data')
if (missing(.problem)) .problem <- default_plot_problem(xpdb)
check_problem(.problem, .subprob = NULL, .method = NULL)
if (missing(quiet)) quiet <- xpdb$options$quiet
if (missing(facets)) facets <- add_facet_var(facets = xpdb$xp_theme$facets,
variable = 'variable')
xplot_scatter(xpdb = xpdb, group = group, quiet = quiet,
opt = data_opt(.problem = .problem, tidy = TRUE,
filter = only_obs(xpdb, .problem, quiet),
value_col = xp_var(xpdb, .problem,
type = c('dv', 'pred', 'ipred'))$col),
mapping = aes_c(aes_string(x = xp_var(xpdb, .problem, type = 'idv')$col,
y = 'value'), mapping),
type = type, guide = FALSE, facets = facets,
xscale = check_scales('x', log),
yscale = check_scales('y', log),
title = title, subtitle = subtitle, caption = caption,
tag = tag, plot_name = as.character(match.call()[[1]]), ...)
}
|
prepareFiles <- function(listOfFiles) {
listOfFiles = gsub("^file://","", listOfFiles)
listOfFiles = normalizePath(path.expand(listOfFiles))
return(listOfFiles)
}
|
DNbuilder.core <- function(model, data, clevel, m.summary, covariate, DNtitle, DNxlab, DNylab, DNlimits) {
mclass <- getclass.DN(model)$model.class
mfamily <- getclass.DN(model)$model.family
if (mclass %in% c("lm", "ols")){
mlinkF <- function(eta) eta
} else{
mlinkF <- ifelse(mclass == "lrm", function(mu) plogis(mu), model$family$linkinv)
}
input.data <- NULL
old.d <- NULL
if (mclass %in% c("ols", "Glm", "lrm")){
model <- update(model, x=T, y=T)
}
allvars <- all.vars(model$terms)
if (mclass %in% c("ols", "lrm", "Glm")){
terms <- model$Design$assume[model$Design$assume!="interaction"]
names(terms) = model$Design$name[model$Design$assume!="interaction"]
if (mclass %in% c("Glm")){
terms <- c(attr(attr(model$model, "terms"), "dataClasses")[1], terms)
} else{
terms <- c(attr(model$terms,"dataClasses")[1], terms)
}
}
if (mclass %in% c("lm", "glm", "gam", "Gam")){
if(length(attr(model$terms, "dataClasses")) == length(allvars)){
terms <- attr(model$terms, "dataClasses")
names(terms) = allvars
} else{
terms <- attr(model$terms, "dataClasses")[which(names(attr(model$terms, "dataClasses")) %in% allvars)]
}
}
if (terms[[1]] == "logical")
stop("Error in model syntax: logical form for response not supported")
terms[terms %in% c("numeric", "asis", "polynomial", "integer", "double", "matrx") |
grepl("nmatrix", terms, fixed = T) | grepl("spline", terms, fixed = T)] = "numeric"
terms[terms %in% c("factor", "ordered", "logical", "category", "scored")] = "factor"
resp <- terms[1]
names(resp) <- allvars[1]
if ("(weights)" %in% names(terms)){
preds <- as.list(terms[-c(1, length(terms))])
} else{
preds <- as.list(terms[-1])
}
names(preds) <- allvars[-1]
for (i in 1:length(preds)){
if (preds[[i]] == "numeric"){
i.dat <- which(names(preds[i]) == names(data))
preds[[i]] <- list(v.min = floor(min(na.omit(data[, as.numeric(i.dat)]))),
v.max = ceiling(max(na.omit(data[, as.numeric(i.dat)]))),
v.mean = zapsmall(mean(data[, as.numeric(i.dat)], na.rm=T), digits = 4)
)
next
}
if (preds[[i]] == "factor"){
i.dat <- which(names(preds[i]) == names(data))
if (mclass %in% c("ols", "Glm", "lrm", "cph")){
preds[[i]] <- list(v.levels = model$Design$parms[[which(names(preds[i]) == names(model$Design$parms))]])
} else{
preds[[i]] <- list(v.levels = model$xlevels[[which(names(preds[i]) == names(model$xlevels))]])
}
}
}
if (!is.null(DNlimits) & !length(DNlimits)==2)
stop("A vector of 2 is required as 'DNlimits'")
if (is.null(DNlimits)){
if ((mclass %in% c("glm") & mfamily %in% c("binomial", "quasibinomial")) | mclass == "lrm"){
limits0 <- c(0, 1)
} else{
if (mclass %in% c("lm", "glm", "gam", "Gam")) {
limits0 <- c(mean(model$model[,names(resp)]) - 3 * sd(model$model[,names(resp)]),
mean(model$model[,names(resp)]) + 3 * sd(model$model[,names(resp)]))
}
if (mclass %in% c("ols", "lrm", "Glm")) {
limits0 <- c(mean(model$y) - 3 * sd(model$y), mean(model$y) + 3 * sd(model$y))
}
}
if (mclass %in% c("glm", "Glm") & mfamily %in% c("poisson", "quasipoisson", "Gamma")){
limits0[1] <- 0
}
} else{
limits0 <- DNlimits
}
neededVar <- c(names(resp), names(preds))
data <- data[, neededVar]
input.data <- data[0, ]
model <- update(model, data=data)
wdir <- getwd()
app.dir <- paste(wdir, "DynNomapp", sep="/")
message(paste("creating new directory: ", app.dir, sep=""))
dir.create(app.dir)
setwd(app.dir)
message(paste("Export dataset: ", app.dir, "/dataset.RData", sep=""))
save(data, model, preds, resp, mlinkF, getpred.DN, getclass.DN,
DNtitle, DNxlab, DNylab, DNlimits, limits0, terms, input.data, file = "data.RData")
message(paste("Export functions: ", app.dir, "/functions.R", sep=""))
dump(c("getpred.DN", "getclass.DN"), file="functions.R")
if (!is.null(DNlimits)) {
limits.bl <- paste("limits <- reactive({ DNlimits })")
} else{
limits.bl <- paste("limits <- reactive({ if (input$limits) { limits <- c(input$lxlim, input$uxlim) } else {
limits <- limits0 } })")
}
noSE.bl <- paste("by '", mclass, "'", sep="")
p1title.bl <- paste(clevel * 100, "% ", "Confidence Interval for Response", sep = "")
p1msg.bl <- paste("Confidence interval is not available as there is no standard errors available by '", mclass, "' ", sep="")
if (m.summary == "formatted"){
if (mclass == "lm"){
sumtitle.bl <- paste("Linear Regression:", model$call[2], sep = " ")
}
if (mclass %in% c("glm")){
sumtitle.bl <- paste(mfamily, " regression (", model$family$link, "): ", model$formula[2],
" ", model$formula[1], " ", model$formula[3], sep = "")
}
if (mclass %in% c("ols", "lrm", "Glm")){
sumtitle.bl <- paste("Linear Regression:", model$call[2], sep = " ")
}
} else{
sumtitle.bl = NULL
}
if (m.summary == "formatted"){
if (mclass %in% c("lm", "glm", "ols", "lrm", "Glm")){
sum.bi <- paste("stargazer(model, type = 'text', omit.stat = c('LL', 'ser', 'f'), ci = TRUE, ci.level = clevel, single.row = TRUE, title = '",
sumtitle.bl,"')", sep="")
}
if (mclass == "gam"){
sum.bi <- paste("Msum <- list(summary(model)$formula, summary(model)$p.table, summary(model)$s.table)
invisible(lapply(1:3, function(i){ cat(sep='', names(Msum)[i], '\n') ; print(Msum[[i]])}))")
}
if (mclass == "Gam"){
sum.bi <- paste("Msum <- list(model$formula, summary(model)$parametric.anova, summary(model)$anova)
invisible(lapply(1:3, function(i){ cat(sep='', names(Msum)[i], '\n')) ; print(Msum[[i]])}))")
}}
if (m.summary == "raw"){
if (mclass %in% c("ols", "Glm", "lrm")){
sum.bi <- paste("print(model)")
} else{
sum.bi <- paste("summary(model)")
}}
if (mclass %in% c("ols", "Glm", "lrm")){
datadist.bl <- paste("t.dist <- datadist(data)
options(datadist = 't.dist')", sep="")
} else{
datadist.bl <- ""
}
if (mclass %in% c("lm", "glm")){
library.bl <- ""
} else{
if (mclass %in% c("ols", "Glm", "lrm")){
library.bl <- paste("library(rms)")
}
if (mclass %in% c("Gam")){
library.bl <- paste("library(gam)")
}
if (mclass %in% c("gam")){
library.bl <- paste("library(mgcv)")
}
}
GLOBAL=paste("library(ggplot2)
library(shiny)
library(plotly)
library(stargazer)
library(compare)
library(prediction)
", library.bl ,"
load('data.RData')
source('functions.R')
", datadist.bl,"
m.summary <- '",m.summary,"'
covariate <- '", covariate,"'
clevel <- ", clevel,"
", sep="")
UI=paste("ui = bootstrapPage(fluidPage(
titlePanel('", DNtitle,"'),
sidebarLayout(sidebarPanel(uiOutput('manySliders'),
uiOutput('setlimits'),
actionButton('add', 'Predict'),
br(), br(),
helpText('Press Quit to exit the application'),
actionButton('quit', 'Quit')
),
mainPanel(tabsetPanel(id = 'tabs',
tabPanel('Graphical Summary', plotlyOutput('plot')),
tabPanel('Numerical Summary', verbatimTextOutput('data.pred')),
tabPanel('Model Summary', verbatimTextOutput('summary'))
)
)
)))", sep = "")
SERVER=paste('server = function(input, output){
observe({if (input$quit == 1)
stopApp()})
', limits.bl, '
output$manySliders <- renderUI({
slide.bars <- list()
for (j in 1:length(preds)){
if (terms[j+1] == "factor"){
slide.bars[[j]] <- list(selectInput(paste("pred", j, sep = ""), names(preds)[j], preds[[j]]$v.levels, multiple = FALSE))
}
if (terms[j+1] == "numeric"){
if (covariate == "slider") {
slide.bars[[j]] <- list(sliderInput(paste("pred", j, sep = ""), names(preds)[j],
min = preds[[j]]$v.min, max = preds[[j]]$v.max, value = preds[[j]]$v.mean))
}
if (covariate == "numeric") {
slide.bars[[j]] <- list(numericInput(paste("pred", j, sep = ""), names(preds)[j], value = zapsmall(preds[[j]]$v.mean, digits = 4)))
}}}
do.call(tagList, slide.bars)
})
output$setlimits <- renderUI({
if (is.null(DNlimits)){
setlim <- list(checkboxInput("limits", "Set x-axis ranges"),
conditionalPanel(condition = "input.limits == true",
numericInput("uxlim", "x-axis upper", zapsmall(limits0[2], digits = 2)),
numericInput("lxlim", "x-axis lower", zapsmall(limits0[1], digits = 2))))
} else{ setlim <- NULL }
setlim
})
a <- 0
new.d <- reactive({
input$add
input.v <- vector("list", length(preds))
for (i in 1:length(preds)) {
input.v[[i]] <- isolate({
input[[paste("pred", i, sep = "")]]
})
names(input.v)[i] <- names(preds)[i]
}
out <- data.frame(lapply(input.v, cbind))
if (a == 0) {
input.data <<- rbind(input.data, out)
}
if (a > 0) {
if (!isTRUE(compare(old.d, out))) {
input.data <<- rbind(input.data, out)
}}
a <<- a + 1
out
})
p1 <- NULL
old.d <- NULL
data2 <- reactive({
if (input$add == 0)
return(NULL)
if (input$add > 0) {
if (!isTRUE(compare(old.d, new.d()))) {
isolate({
mpred <- getpred.DN(model, new.d(), set.rms=T)$pred
se.pred <- getpred.DN(model, new.d(), set.rms=T)$SEpred
if (is.na(se.pred)) {
lwb <- "No standard errors"
upb <- "', noSE.bl,'"
pred <- mlinkF(mpred)
d.p <- data.frame(Prediction = zapsmall(pred, digits = 3),
Lower.bound = lwb, Upper.bound = upb)
} else {
lwb <- sort(mlinkF(mpred + cbind(1, -1) * (qnorm(1 - (1 - clevel)/2) * se.pred)))[1]
upb <- sort(mlinkF(mpred + cbind(1, -1) * (qnorm(1 - (1 - clevel)/2) * se.pred)))[2]
pred <- mlinkF(mpred)
d.p <- data.frame(Prediction = zapsmall(pred, digits = 3),
Lower.bound = zapsmall(lwb, digits = 3),
Upper.bound = zapsmall(upb, digits = 3))
}
old.d <<- new.d()
data.p <- cbind(d.p, counter = 1, count=0)
p1 <<- rbind(p1, data.p)
p1$counter <- seq(1, dim(p1)[1])
p1$count <- 0:(dim(p1)[1]-1) %% 11 + 1
p1
})
} else {
p1$count <- seq(1, dim(p1)[1])
}}
rownames(p1) <- c()
p1
})
output$plot <- renderPlotly({
if (input$add == 0)
return(NULL)
if (is.null(new.d()))
return(NULL)
coll=c("
"
lim <- limits()
yli <- c(0 - 0.5, 10 + 0.5)
dat2 <- data2()
if (dim(data2())[1] > 11){
input.data = input.data[-c(1:(dim(input.data)[1]-11)),]
dat2 <- data2()[-c(1:(dim(data2())[1]-11)),]
yli <- c(dim(data2())[1] - 11.5, dim(data2())[1] - 0.5)
}
in.d <- input.data
xx <- matrix(paste(names(in.d), ": ", t(in.d), sep = ""), ncol = dim(in.d)[1])
Covariates <- apply(xx, 2, paste, collapse = "<br />")
p <- ggplot(data = dat2, aes(x = Prediction, y = counter - 1, text = Covariates,
label = Prediction, label2 = Lower.bound, label3=Upper.bound)) +
geom_point(size = 2, colour = coll[dat2$count], shape = 15) +
ylim(yli[1], yli[2]) + coord_cartesian(xlim = lim) +
labs(title = "', p1title.bl,'",
x = "', DNxlab,'", y = "', DNylab,'") + theme_bw() +
theme(axis.text.y = element_blank(), text = element_text(face = "bold", size = 10))
if (is.numeric(dat2$Upper.bound)){
p <- p + geom_errorbarh(xmax = dat2$Upper.bound, xmin = dat2$Lower.bound,
size = 1.45, height = 0.4, colour = coll[dat2$count])
} else{
message("', p1msg.bl,'")
}
gp <- ggplotly(p, tooltip = c("text", "label", "label2", "label3"))
gp$elementId <- NULL
gp
})
output$data.pred <- renderPrint({
if (input$add > 0) {
if (nrow(data2()) > 0) {
if (dim(input.data)[2] == 1) {
in.d <- data.frame(input.data)
names(in.d) <- names(terms)[2]
data.p <- cbind(in.d, data2()[1:3])
}
if (dim(input.data)[2] > 1) {
data.p <- cbind(input.data, data2()[1:3])
}}
stargazer(data.p, summary = FALSE, type = "text")
}
})
output$summary <- renderPrint({
', sum.bi,'
})
}', sep = "")
output=list(ui=UI, server=SERVER, global=GLOBAL)
text <- paste("This guide will describe how to deploy a shiny application using scripts generated by DNbuilder:
1. Run the shiny app by setting your working directory to the DynNomapp folder, and then run: shiny::runApp() If you are using the RStudio IDE, you can also run it by clicking the Run App button in the editor toolbar after open one of the R scripts.
2. You could modify codes to apply all the necessary changes. Run again to confirm that your application works perfectly.
3. Deploy the application by either clicking on the Publish button in the top right corner of the running app, or use the generated files and deploy it on your server if you host any.
You can find a full guide of how to deploy an application on shinyapp.io server here:
http://docs.rstudio.com/shinyapps.io/getting-started.html
Please cite the package if using in publication.", sep="")
message(paste("writing file: ", app.dir, "/README.txt", sep=""))
writeLines(text, "README.txt")
message(paste("writing file: ", app.dir, "/ui.R", sep=""))
writeLines(output$ui, "ui.R")
message(paste("writing file: ", app.dir, "/server.R", sep=""))
writeLines(output$server, "server.R")
message(paste("writing file: ", app.dir, "/global.R", sep=""))
writeLines(output$global, "global.R")
setwd(wdir)
}
|
context("Exchange method updating objective")
library("anticlust")
test_that("computing distance objectives in specialized exchange method is equal to generic method", {
for (M in 1:4) {
for (K in 2:5) {
for (i in 3:8) {
N <- K * i
features <- matrix(rnorm(N * M), ncol = M)
distances <- as.matrix(dist(features))
clusters <- sample(rep(1:K, N/K))
objective <- diversity_objective_(clusters, distances)
objective2 <- diversity_objective_(clusters, features)
expect_equal(objective, objective2)
to_swap <- sample(1:K, size = 2)
swap1 <- which(clusters == to_swap[1])[1]
swap2 <- which(clusters == to_swap[2])[1]
selected <- selection_matrix_from_clusters(clusters)
obj1 <- update_objective_distance(distances, selected, swap1, swap2, objective)
obj2 <- update_objective_generic(distances, clusters, swap1, swap2, diversity_objective)
expect_equal(obj1, obj2)
}
}
}
})
|
crop_row_finder <- function(picture_list, ratio, final_ratio, intensity) {
best_image <- best_rotation(picture_list, ratio, intensity)
crop_rows <- crop_lines(picture_list, final_ratio, best_image, intensity)
return(crop_rows)
}
|
context("allocationTable.R")
if (file.exists("local-token.Rdata")){
load("local-token.Rdata")
} else {
url <- "https://redcap.notaplace.net/redcap/api/"
token_case_01 <- "NOTaREALtoken1234567890123456789"
token_case_20 <- token_case_01
}
rcon <- redcapConnection(url, token_case_20)
test_that(
"Allocation Table can be generated",
{
expect_silent(
allocationTable(rcon,
random = "treatment",
replicates = 8,
block.size = 8,
seed.dev = 10,
seed.prod = 20,
weights = c(Control = 1, Treatment = 1))
)
}
)
test_that(
"Allocation Table in offline style",
{
meta_data20 <- exportMetaData(rcon)
write.csv(meta_data20, "MetaDataForAllocation.csv", na = "", row.names = FALSE)
on.exit(file.remove("MetaDataForAllocation.csv"))
expect_silent(
allocationTable_offline("MetaDataForAllocation.csv",
random = "treatment",
replicates = 8,
block.size = 8,
seed.dev = 10,
seed.prod = 20,
weights = c(Control = 1, Treatment = 1))
)
}
)
|
"volcano_arr"
|
organize_caes <- function(base){
if ('PP04B_CAES' %in% names(base)) {
warning("Creando nueva variable PP04B_COD como copia de PP04B_CAES por compatibilidad.")
base <- base %>%
dplyr::mutate(PP04B_COD = dplyr::case_when(ANO4 %in% 2011:2015 ~ PP04B_CAES,
TRUE~ PP04B_COD))
}
warning("Convirtiendo PP04B_COD a character")
base <- base %>%
dplyr::mutate(PP04B_COD = as.character(PP04B_COD),
PP04B_COD = dplyr::case_when(nchar(PP04B_COD) == 1 ~ paste0("0", PP04B_COD),
nchar(PP04B_COD) == 2 ~ PP04B_COD,
nchar(PP04B_COD) == 3 ~ paste0("0", PP04B_COD),
nchar(PP04B_COD) == 4 ~ PP04B_COD),
caes_version = dplyr::case_when(ANO4 >= 2011 ~ "1.0",
ANO4 < 2011 ~ "0"))
base <- base %>%
dplyr::left_join(caes, by = c("PP04B_COD","caes_version"))
if(any(base$ANO4 < 2011) & any(base$ANO4 >= 2011)){
warning("Para los datos anteriores a 2011 se aplico la clasificacion CAES v.0 y para los de 2011 en adelante la clasificacion CAES v.1.0")
}
return(base)
}
|
predict_grp <- function(E_ini_fun,beta_fun,A_fun,correl_fun, tol=0.00000001) {
n_fun <- length(A_fun)
E_ini_fun <- as.matrix(E_ini_fun)
if (correl_fun=="Comp"|correl_fun=="SC") {
beta_fun <- diag(1,n_fun)
}
B_fun <- compute.B.from.beta(beta_fun)
L_Phi_fun <- class_group(beta_fun)
p_fun <- length(L_Phi_fun)
grp_typ <- group_types(beta_fun)
is.correl.authorized(correl_fun)
is.beta.accurate(beta_fun,n_fun,correl_fun)
if (length(E_ini_fun)!=n_fun) {
stop("An enzyme are missing. A_fun and E_ini_fun have not the same length.")
}
eq_ingrp <- rep(NA,n_fun)
eq_btwgrp <- rep(NA,p_fun)
eq_total <- rep(NA,n_fun)
eq_tau <- rep(NA,p_fun)
Eq_btwgrp <- rep(NA,p_fun)
E_fun <- rep(NA,n_fun)
if (any(correl_fun==c("SC","RegPos","RegNeg"))) {
for (q in 1:p_fun) {
phi_q <- L_Phi_fun[[q]]
which.typ.q <- search_group(q,grp_typ)
if(names(which.typ.q)=="grp_pos") {
eq_ingrp[phi_q] <- predict_th(A_fun[phi_q],"RegPos",B_fun[phi_q])$pred_e
eq_tau[q] <- 1
E_fun[phi_q] <- Inf
}
if(names(which.typ.q)=="grp_single") {
eq_ingrp[phi_q] <- 1
E_fun[phi_q] <- Inf
}
if(names(which.typ.q)=="grp_neg") {
eq_values <- predict_eff(E_ini_fun[phi_q],B_fun[phi_q],A_fun[phi_q],"RegNeg")
eq_ingrp[phi_q] <- eq_values$pred_e
eq_tau[q] <- eq_values$pred_tau
E_fun[phi_q] <- eq_values$pred_E
}
Eq_btwgrp[q] <- sum(E_fun[phi_q])
}
A_app <- unlist(lapply(L_Phi_fun,apparent.activities.Aq,A_fun,B_fun,correl_fun))
if (length(grp_typ$grp_neg)==0) {
eq_btwgrp <- predict_th(A_app,"SC")$pred_e
}
if (length(grp_typ$grp_neg)==p_fun) {
eq_btwgrp <- Eq_btwgrp/sum(Eq_btwgrp)
}
if (length(grp_typ$grp_neg)>0 & length(grp_typ$grp_neg)<p_fun) {
for (q in 1:p_fun) {
which.typ.q <- search_group(q,grp_typ)
if(names(which.typ.q)=="grp_neg") {
eq_btwgrp[q] <- 0
} else {
grp_pos_sgl <- c(grp_typ$grp_pos,grp_typ$grp_single)
eq_btwgrp[grp_pos_sgl] <- predict_th(A_app[grp_pos_sgl],"SC")$pred_e
}
}
}
Etot_fun <- sum(E_fun)
}
if (any(correl_fun==c("Comp","CRPos","CRNeg"))) {
for (q in 1:p_fun) {
phi_q <- unlist(L_Phi_fun[[q]])
if (correl_fun=="Comp"|length(phi_q)==1) {
eq_ingrp[phi_q] <- 1
} else {
nb_not_single <- sum(length(grp_typ$grp_pos),length(grp_typ$grp_neg))
if (nb_not_single==1) {
eq_values <- predict_eff(E_ini_fun[phi_q],B_fun[phi_q],A_fun[phi_q],correl_fun)
eq_ingrp[phi_q] <- eq_values$pred_e
eq_tau <- eq_values$pred_tau
}
}
}
A_app <- unlist(lapply(L_Phi_fun,apparent.activities.Aq,A_fun,B_fun,correl_fun,eiq_eff=eq_ingrp))
eq_btwgrp <- predict_th(A_app,"Comp")$pred_e
}
for (j in 1:n_fun){
eq_total[j] <- eq_ingrp[j]*eq_btwgrp[search_group(j,L_Phi_fun)]
}
if (any(correl_fun==c("Comp","CRPos","CRNeg"))) {
Etot_fun <- sum(E_ini_fun)
Eq_btwgrp <- eq_btwgrp*Etot_fun
E_fun <- eq_total*Etot_fun
}
return(list(pred_eiq=eq_ingrp, pred_eq=eq_btwgrp, pred_ei=eq_total, pred_tau=eq_tau, pred_Ei=E_fun, pred_Eq=Eq_btwgrp, pred_Etot=Etot_fun))
}
|
"tgp.choose.as" <-
function(out, as)
{
if(is.null(as) || as == "s2" || as == "ks2") {
X <- out$XX
if(is.null(as)) {
criteria <- c(out$Zp.q, out$ZZ.q)
name <- "quantile diff (error)"
if(!is.null(out$Zp.q)) X <- rbind(out$X, X)
} else if(as == "ks2") {
criteria = c(out$Zp.ks2, out$ZZ.ks2)
name <- "kriging var"
if(!is.null(out$Zp.ks2)) X <- rbind(out$X, X)
} else {
if(is.matrix(out$Zp.s2)) criteria <- c(diag(out$Zp.s2), diag(out$ZZ.s2))
else criteria <- c(out$Zp.s2, out$ZZ.s2)
name <- "pred var"
if(!is.null(out$Zp.s2)) X <- rbind(out$X, X)
}
} else {
X <- out$XX
criteria <- out$ZZ.q
name <- "ALM stats"
if(as == "alc") {
if(is.null(out$Ds2x)) cat("NOTICE: out$Ds2x is NULL, using ALM\n")
else { criteria <- out$Ds2x; name <- "ALC stats" }
} else if(as == "improv") {
if(is.null(out$improv)) cat("NOTICE: out$improv is NULL, using ALM\n")
else {
criteria <- out$improv[,1];
name <- paste("Improv stats (g=", out$g[1], ")", sep="")
}
} else if(as != "alm")
warning(paste("as criteria \"", as, "\" not recognized; defaulting to \"alm\"",
sep=""))
}
if(is.null(criteria)) stop("no predictive data, so nothing to plot")
return(list(X=X, criteria=criteria, name=name))
}
"tgp.choose.center" <-
function(out, center)
{
X <- out$XX
if(center != "mean" && center != "med" && center != "km") {
warning(paste("center = \"", center, "\" invalid, defaulting to \"mean\"\n",
sep=""))
center <- "mean"
}
if(center == "med") {
name <- "median";
Z <- c(out$Zp.med, out$ZZ.med)
if(!is.null(out$Zp.med)) X <- rbind(out$X, X)
} else if(center == "km") {
name <- "kriging mean";
Z <- c(out$Zp.km, out$ZZ.km)
if(!is.null(out$Zp.km)) X <- rbind(out$X, X)
} else {
name <- "mean";
Z <- c(out$Zp.mean, out$ZZ.mean)
if(!is.null(out$Zp.mean)) X <- rbind(out$X, X)
}
if(is.null(Z)) stop("no predictive data, so nothing to plot")
return(list(X=X, Z=Z, name=name))
}
|
get.series.bacen<- function(x, from = "", to = ""){
if (missing(x)){
stop("Need to specify at least one serie.")
}
if (! is.numeric(x)){
stop("Argument x must be numeric.")
}
if (from == ""){
data_init = "01/01/1980"
} else {data_init = from}
if (to == ""){
data_end = format(Sys.Date(), "%d/%m/%Y")
} else {data_end = to}
inputs = as.character(x)
len = seq_along(inputs)
serie = mapply(paste0, "serie_", inputs, USE.NAMES = FALSE)
for (i in len){
result = tryCatch({
RCurl::getURL(paste0('http://api.bcb.gov.br/dados/serie/bcdata.sgs.',
inputs[i],
'/dados?formato=csv&dataInicial=', data_init, '&dataFinal=',
data_end),
ssl.verifyhost=FALSE, ssl.verifypeer=FALSE, .opts = list(timeout = 1, maxredirs = 2))
},
error = function(e) {
return(RCurl::getURL(paste0('http://api.bcb.gov.br/dados/serie/bcdata.sgs.',
inputs[i],
'/dados?formato=csv&dataInicial=', data_init,
'&dataFinal=',
data_end),
ssl.verifyhost=FALSE, ssl.verifypeer=FALSE))
})
assign(serie[i], result)
}
sinal = tryCatch({
for (i in len){
texto = utils::read.csv2(textConnection(eval(as.symbol(
serie[i]))), header=T)
texto$data = gsub(' .*$','', eval(texto$data))
assign(serie[i], texto)
}},
error = function(e){
return("error")
})
if(sinal == "error"){
for(i in len){
texto=tryCatch({
k = paste0('http://api.bcb.gov.br/dados/serie/bcdata.sgs.',
inputs[i],
'/dados?formato=csv&dataInicial=', data_init, '&dataFinal=',
data_end)
dados = httr::GET(k)
aux = content(dados,'raw')
aux2=rawToChar(aux)
DF <- data.frame(do.call(cbind, strsplit(aux2, "\r\n", fixed=TRUE)))
names(DF) <-"mist"
DF$mist <- as.character(DF$mist)
DF$mist<- gsub(x = DF$mist,pattern = '"',replacement = "")
DF$data <- gsub(x = DF$mist,pattern = ";.*",replacement = "")
DF$valor <- gsub(x = DF$mist,pattern = ".*;",replacement = "")
DF$valor <- gsub(x = DF$valor,pattern = ",",replacement = ".")
DF <- DF[-1,-1]
})}
assign(serie[i], result)
}
if(sinal == "error"){
for (i in len){
texto$data = gsub(' .*$','', eval(texto$data))
assign(serie[i], texto)
}
}
if(ncol(texto) == 1){
for (i in len){
texto = utils::read.csv(textConnection(eval(as.symbol(
serie[i]))), header=T)
texto$data = gsub(' .*$','', eval(texto$data))
assign(serie[i], texto)
}
}
rm(texto)
lista = list()
ls_df = ls()[grepl('data.frame', sapply(ls(), function(x) class(get(x))))]
for ( obj in ls_df ) { lista[obj]=list(get(obj)) }
return(lista)
}
|
multistageoptimum.search<-function (maseff=0.4, VGCAandE,
VSCA=c(0,0,0,0), CostProd = c(0.5,1,1), CostTest = c(0.5,1,1),
Nf = 10, Budget = 10021, N2grid = c(11, 1211, 30),
N3grid = c(11, 211, 5), L2grid=c(1,3,1), L3grid=c(6,8,1),
T2grid=c(1,1,1), T3grid=c(1,1,1),R2=1,R3=1, alg = Miwa(),detail=FALSE,fig=FALSE,
alpha.nursery=1,cost.nursery=c(0,0)
,t2free= FALSE,
parallel.search=FALSE
)
{
if (parallel.search)
{
no_cores <- detectCores() - 1
cl <- makeCluster(no_cores);
clusterEvalQ(cl,{library(selectiongain);source("multistageoptimum.grid.R")})
}
Vgca=VGCAandE
Vsca=VSCA
L2limit=L2grid
L3limit=L3grid
T2limit=T2grid
T3limit=T3grid
alpha.nur=alpha.nursery
Cost.nur=cost.nursery
dim=(T3limit[2]-T3limit[1]+1)/T3limit[3]*(T2limit[2]-T2limit[1]+1)/T2limit[3]*(L3limit[2]-L3limit[1]+1)/L3limit[3]*(L2limit[2]-L2limit[1]+1)/L2limit[3]
gainmatrix=array(0,c(1,18))
colnames(gainmatrix)<-c("Nf","Nini","alpha.nur","N1","N2","N3","L2","L3","T2","T3","R2","R3","Bini","B1","B2","B3","Budget","Gain")
if (alpha.nur == 1 )
{
CostProdMod1<-CostProd[1]+Cost.nur[1]
warning("No nursery is used as alpha.nursery is set to 1. Then cost of production in Nursery added to CostProd[1]")
}
else
{
CostProdMod1<-CostProd[1]
}
if (Budget< c(N2grid[1]*L2grid[1]*T2grid[1]+N3grid[1]*L3grid[1]*T3grid[1]))
{
warning("budget too small, try value => c(N2grid[1]*L2grid[1]*T2grid[1]+N3grid[1]*L3grid[1]*T3grid[1])")
}
if (Budget> c(N2grid[2]*L2grid[2]*T2grid[2]+N3grid[2]*L3grid[2]*T3grid[2]))
{
warning("budget too great, try value => c(N2grid[2]*L2grid[2]*T2grid[2]+N3grid[2]*L3grid[2]*T3grid[2])")
}
if (length(CostTest)!= 3)
{
stop( "dimension of CostTest has to be 3")
}
if (length(CostProd)!= 3)
{
stop( "dimension of CostProd has to be 3")
}
for (T3 in seq.int(T3limit[1],T3limit[2],T3limit[3]))
{
for (T2 in seq.int(T2limit[1],T2limit[2],T2limit[3]))
{
for (L3 in L3limit[1]:L3limit[2])
{
for (L2 in L2limit[1]:L2limit[2])
{
allocation = c(Nf,0,alpha.nur,0,0,0,L2,L3,T2,T3,R2,R3,0,0,0,0,0,0)
gainmatrix=rbind(gainmatrix,allocation)
}
}
}
}
theloop<-function(j,gainmatrix, N2grid= N2grid, N3grid= N3grid,maseff,t2free,CostTest=CostTest,CostProd=CostProd,Budget=Budget,Nf=Nf,alg=alg,cost.nursery=c(0,0) )
{
i=j+1
Cost.nur=cost.nursery
alpha.nur=gainmatrix[i,"alpha.nur"]
L3=gainmatrix[i,"L3"]
L2=gainmatrix[i,"L2"]
T3=gainmatrix[i,"T3"]
T2=gainmatrix[i,"T2"]
R3=gainmatrix[i,"R3"]
R2=gainmatrix[i,"R2"]
N.fs=gainmatrix[i,"Nf"]
L1=1
T1=1
R1=1
if (!is.na(maseff))
{
corr.longin.mas.index = multistagecor(VGCAandE=Vgca,VSCA=Vsca,L=c(L1,L2,L3),Rep=c(R1,R2,R3),T=c(T1,T2,T3),index=FALSE,maseff=maseff)
corr.matrix=corr.longin.mas.index
CostTestloop=c(CostTest[1],CostTest[2]*L2*T2*R2,CostTest[3]*L3*T3*R3)
if(t2free)
{
CostProdloop=c(CostProd[1],CostProd[2]*T2,CostProd[3]*(T3-T2))
}else
{
CostProdloop=c(CostProd[1],CostProd[2]*T2,CostProd[3]*T3)
}
result=multistageoptimum.grid(N.upper = c(100000,N2grid[2],N3grid[2]), N.lower = c(1,N2grid[1],N3grid[1]),
Vg=Vgca[1],corr = corr.matrix, width = c(1,N2grid[3],N3grid[3]),
Budget = Budget, CostProd =CostProdloop, CostTest = CostTestloop, Nf = Nf,
detail = FALSE, alg = Miwa(),fig=FALSE
,alpha.nursery = alpha.nur,cost.nursery = Cost.nur
)
gainmatrix[i,"Budget"]=Budget
gainmatrix[i,"Nini"]= result[1]
gainmatrix[i,"Bini"]= result[1]*(Cost.nur[1]+Cost.nur[2])
gainmatrix[i,"N1"]= result[2]
gainmatrix[i,"B1"]= result[2]*(CostTest[1]+CostProdMod1)
gainmatrix[i,"N2"]= result[3]
gainmatrix[i,"N3"]= result[4]
gainmatrix[i,"B2"]= result[3]*( (L2*T2*R2*CostTest[2])+(CostProd[2]*T2))
if(t2free)
{
gainmatrix[i,"B3"]= result[4]*( (L3*T3*R3*CostTest[3])+(CostProd[3]*(T3-T2)))
}else
{
gainmatrix[i,"B3"]= result[4]*( (L3*T3*R3*CostTest[3])+(CostProd[3]*T3))
}
gainmatrix[i,"Gain"]= result[5]
}else
{
corr.longin.mas.index = multistagecor(VGCAandE=Vgca,VSCA=Vsca,L=c(L2,L3),Rep=c(R2,R3),T=c(T2,T3),index=FALSE,maseff=maseff)
corr.matrix=corr.longin.mas.index
CostTestloop=c(CostTest[2]*L2*T2*R2,CostTest[3]*L3*T3*R3)
if(t2free)
{
CostProdloop=c(CostProd[1]+(CostProd[2]*T2),CostProd[3]*(T3-T2))
}else
{
CostProdloop=c(CostProd[1]+(CostProd[2]*T2),CostProd[3]*T3)
}
result=multistageoptimum.grid( N.upper = c(N2grid[2],N3grid[2]), N.lower = c(N2grid[1],N3grid[1]),
Vg=Vgca[1],corr = corr.matrix, width = c(N2grid[3],N3grid[3]),
Budget = Budget, CostProd =CostProdloop, CostTest = CostTestloop,
Nf = Nf, detail = FALSE, alg = Miwa(),fig=FALSE
,alpha.nursery = alpha.nur,cost.nursery = Cost.nur
)
gainmatrix[i,"Budget"]=Budget
gainmatrix[i,"Nini"]= result[1]
gainmatrix[i,"Bini"]= result[1]*(Cost.nur[1]+Cost.nur[2])
gainmatrix[i,"N2"]= result[2]
gainmatrix[i,"N3"]= result[3]
gainmatrix[i,"B2"]= result[2]*( (L2*T2*R2*CostTest[2])+(CostProdMod1+(CostProd[2]*T2)))
if(t2free)
{
gainmatrix[i,"B3"]= result[3]*( (L3*T3*R3*CostTest[3])+(CostProd[3]*(T3-T2)))
}else
{
gainmatrix[i,"B3"]= result[3]*( (L3*T3*R3*CostTest[3])+(CostProd[3]*T3))
}
gainmatrix[i,"Gain"]= result[4]
}
gainmatrix[i,]
}
if (!parallel.search)
{
for (j in 1:dim )
{
gainmatrix[j+1,]= theloop(j=j,gainmatrix,N2grid= N2grid, N3grid= N3grid,maseff,t2free,CostTest=CostTest,CostProd=CostProd,Budget=Budget,Nf=Nf,alg=alg,cost.nursery=cost.nursery)
}
}else if(parallel.search)
{
resulta<- parSapply(cl=cl, 1:dim, FUN=theloop,gainmatrix,N2grid= N2grid, N3grid= N3grid,maseff=maseff,t2free=t2free,CostTest=CostTest,CostProd=CostProd,Budget=Budget,Nf=Nf,alg=alg,cost.nursery=cost.nursery)
gainmatrix[1:dim+1,]<-t(resulta)
}
Output=round( gainmatrix,digits=1)
Output[,"Gain"]=round( gainmatrix[,"Gain"],digits=3)
output=Output[2:c(dim+1),c("Nf", "Nini","N1", "N2", "N3","L2","L3","T2","T3","R2","R3","Bini","B1","B2","B3","Budget","Gain")]
gainmax=max(output[,"Gain"])
gainlocation = which(output[,"Gain"]==gainmax,arr.ind =TRUE)
if (fig==TRUE)
{
i=gainlocation[1]
L3=gainmatrix[i,"L3"]
L2=gainmatrix[i,"L2"]
T3=gainmatrix[i,"T3"]
T2=gainmatrix[i,"T2"]
R3=gainmatrix[i,"R3"]
R2=gainmatrix[i,"R2"]
N.fs=gainmatrix[i,"Nf"]
L1=1
T1=1
R1=1
corr.longin.mas.index = multistagecor(VGCAandE=Vgca,VSCA=Vsca,L=c(L1,L2,L3),Rep=c(R1,R2,R3),T=c(T1,T2,T3),index=FALSE,maseff=maseff)
corr.matrix=corr.longin.mas.index
CostTestloop=c(CostTest[1],CostTest[2]*L2*T2*R2,CostTest[3]*L3*T3*R3)
if(t2free)
{
CostProdloop=c(CostProd[1],CostProd[2]*T2,CostProd[3]*(T3-T2))
}else
{
CostProdloop=c(CostProd[1],CostProd[2]*T2,CostProd[3]*T3)
}
result=multistageoptimum.grid( N.upper = c(100000,N2grid[2],N3grid[2]), N.lower = c(1,N2grid[1],N3grid[1]),
Vg=Vgca[1],corr = corr.matrix, width = c(1,N2grid[3],N3grid[3]),
Budget = Budget, CostProd =CostProdloop, CostTest = CostTestloop, Nf = Nf,
detail = detail, alg = Miwa(),fig=TRUE
,alpha.nursery=alpha.nursery,cost.nursery=cost.nursery)
}
if (detail==TRUE)
{
output
}else if (detail!=TRUE )
{
output[gainlocation[1],]
}
}
|
test_that("Glassdoor PAT", {
if (!have_gd_pat()) {
expect_error(gd_pat(error = TRUE))
} else {
expect_silent(gd_pat(error = TRUE))
}
expect_error(gd_pat(token = "", error = TRUE))
})
test_that("Glassdoor PID", {
if (!have_gd_pid()) {
expect_error(gd_pid(error = TRUE))
} else {
expect_silent(gd_pid(error = TRUE))
}
expect_error(gd_pid(token = "", error = TRUE))
})
|
staticmap_plotRasterBrick <- function(
rasterBrick = NULL,
grayscale = FALSE,
...
) {
if ( is.null(rasterBrick) )
stop("Required parameter 'rasterBrick' is missing")
argsList <- list(...)
if ( is.null(argsList$interpolate) )
argsList$interpolate <- TRUE
if ( !grayscale ) {
argsList$x <- rasterBrick
do.call(raster::plotRGB, argsList)
} else {
singleLayerMap <- raster::raster(rasterBrick, layer = 1)
grayImageArray <- round(apply(raster::values(rasterBrick), 1, sum)/3)
raster::setValues(singleLayerMap, grayImageArray)
argsList$x <- singleLayerMap
if ( is.null(argsList$col) ) {
argsList$col <- grDevices::gray.colors(255, gamma = 1)
}
do.call(raster::plot, argsList)
}
}
|
carrierprobpheno <- function(method="data", fit=NULL, data, mode="dominant", q=0.02)
{
if(sum(is.na(data$mgene))==0) stop("Mutatioin carrier statuses are all known")
if(method=="data"){
carrp <- data$mgene
cfam.id <- data$famID[data$proband==1 & data$mgene==1]
nfam.id <- data$famID[data$proband==1 & data$mgene==0]
i.cfam <- is.element(data$famID,cfam.id)
i.nfam <- is.element(data$famID,nfam.id)
for(g in unique(data$relation)){
for(s in c(0,1)){
for(d in c(0,1)){
carrp[i.cfam & is.na(data$mgene) & data$relation==g & data$gender==s &
data$status==d] <- mean(data$mgene[i.cfam & !is.na(data$mgene) & data$relation==g & data$gender==s & data$status==d])
carrp[i.nfam & is.na(data$mgene) & data$relation==g & data$gender==s &
data$status==d] <- mean(data$mgene[i.nfam & !is.na(data$mgene) & data$relation==g & data$gender==s & data$status==d])
}
}
}
}
else if(method=="model"){
if(is.null(fit)) stop("fit should be specified.")
theta <- fit$estimates
base.dist <- attr(fit, "base.dist")
agemin <- attr(fit, "agemin")
nbase <- attr(fit, "nbase")
cuts <- attr(fit, "cuts")
formula <- attr(fit, "formula")
gvar <- attr(fit, "gvar")
Y <- attr(fit, "Y")
X <- attr(fit, "X")
var.names <- colnames(X)
X0 <- X1 <- X
X0[, gvar] <- 0
X1[, gvar] <- 1
xbeta <- c(X%*%theta[-c(1:nbase)])
xbeta0 <- c(X0%*%theta[-c(1:nbase)])
xbeta1 <- c(X1%*%theta[-c(1:nbase)])
time0 <- Y[,1] - agemin
cuts0 <- cuts - agemin
status <- Y[,2]
parms <- exp(theta[1:nbase])
if(base.dist=="lognormal") parms[1] <- theta[1]
p.geno <- data$carrp.geno
if(is.null(p.geno)) {
p.geno <- carrierprobgeno(data=data, method="mendelian", mode=mode, q=q)$carrp.geno
data$carrp.geno <- p.geno
}
p1 <- cprob(theta, X1, time0, status, p=p.geno, base.dist=base.dist, cuts=cuts0, nbase=nbase)
p0 <- cprob(theta, X0, time0, status, p=1-p.geno, base.dist=base.dist, cuts=cuts0, nbase=nbase)
carrp <- p1/(p1+p0)
carrp[!is.na(data$mgene)] <- data$mgene[!is.na(data$mgene)]
}
carrp[is.na(carrp)] <- 0
data$carrp.pheno <- carrp
return(data)
}
|
"bonapersona"
|
knitr::opts_chunk$set(
comment = "
collapse = TRUE
)
library(cowsay)
sort(names(animals))
cow <- animals[['cow']]
cat(cow)
say("why did the chicken cross the road", "chicken")
say("boo!", "ghost")
say("nope, don't do that", type = "warning")
say('time')
say("hello world", by = "cow")
say("hello world", by = "cow", type = "warning")
say("hello world", by = "cow", type = "string")
library(jsonlite)
library(multicolor)
say(what = "fortune",
by = "rabbit",
what_color = "
by_color = "red")
not_on_windows <- c('shortcat','longcat','fish','signbunny','stretchycat',
'anxiouscat','longtailcat','grumpycat','mushroom')
names_safe <- names(animals)[!names(animals) %in% not_on_windows]
say(what = "fortune",
by = sample(names_safe, 1),
what_color = rgb(.1, .2, .3),
by_color = sample(colors(), 5),
type = "message")
say(what = "fortune",
by = sample(names_safe, 1),
what_color = rgb(.1, .2, .3),
by_color = sample(colors(), 5),
type = "message")
say(what = "foobar",
by = "shark",
what_color = "rainbow",
by_color = c("rainbow", "rainbow", "rainbow"))
library(crayon)
say(what = "fortune",
by = "egret",
what_color = bgBlue$white$italic,
by_color = bold$green)
|
GGMPF <- function(lambda, data, K, initial.selection="K-means",
initialize, average=FALSE, asymmetric=TRUE, eps = 5e-2, maxiter=10, maxiter.AMA=5,
local_appro=TRUE, trace = FALSE, penalty = "MCP", theta.fusion=TRUE){
lambda1 = lambda$lambda1
lambda2 = lambda$lambda2
lambda3 = lambda$lambda3
L1 = length(lambda1)
L2 = length(lambda2)
L3 = length(lambda3)
L = L1+L2+L3
aBIC = rep(0,L)
n_all = dim(data)[1]
if(initial.selection=="K-means"){
out.initial = initialize_fuc(data,K)
memb = out.initial$memb
L.mat = matrix(0,n_all,K)
for(jj in 1:n_all) L.mat[jj, memb[jj]]=1
out.initial$L.mat = L.mat
} else if(initial.selection=="dbscan"){
out.initial = initialize_fuc.dbscan(data,K)
memb = out.initial$memb
L.mat = matrix(0,n_all,K)
for(jj in 1:n_all) L.mat[jj, memb[jj]]=1
out.initial$L.mat = L.mat
}
else {out.initial = initialize}
if(L == 3){
l=1
aBIC = rep(0,l)
Mu_hat.list = list()
Theta_hat.list = list()
prob.list = list()
L.mat.list = list()
member.list = list()
lam1 = lambda1;lam2 = lambda2;lam3 = lambda3;
PP = FGGM.refit(data, K, lam1, lam2, lam3, initialization=FALSE, initialize=out.initial, average=average,
asymmetric=asymmetric, local_appro=local_appro, penalty = penalty, theta.fusion=theta.fusion)
mu_hat=PP$mu;Theta_hat=PP$Xi;L.mat = PP$L.mat0;group = PP$group;prob = PP$prob0;aBIC[l] = PP$bic; member = PP$member
Mu_hat.list[[l]]=mu_hat; Theta_hat.list[[l]]=Theta_hat; prob.list[[l]]=prob; L.mat.list[[l]] = L.mat; member.list[[l]]=member
} else {
Mu_hat.list = list()
Theta_hat.list = list()
prob.list = list()
L.mat.list = list()
member.list = list()
lam1 = median(lambda1);lam2 = median(lambda2)
for (l in 1:L3) {
lam3 = lambda3[l]
PP = FGGM.refit(data, K, lam1, lam2, lam3, initialization=FALSE, initialize=out.initial, average=average,
asymmetric=asymmetric, local_appro=local_appro, penalty = penalty, theta.fusion=theta.fusion)
mu_hat=PP$mu;Theta_hat=PP$Xi;L.mat = PP$L.mat0;group = PP$group;prob = PP$prob0;aBIC[l] = PP$bic; member = PP$member
Mu_hat.list[[l]]=mu_hat; Theta_hat.list[[l]]=Theta_hat; prob.list[[l]]=prob; L.mat.list[[l]] = L.mat; member.list[[l]]=member
if(trace){
print(c(cat(paste(l,"lam1 lam2 lam3 ="),c(round(lam1,2),round(lam2,2),round(lam3,2)),":"),paste("K =",as.numeric(dim(Theta_hat)[3]))))
}
}
aBIC[is.na(aBIC)] = 10^10
aBIC[aBIC==0] = abs(aBIC[aBIC!=0][1])*10
n_lam3 = which(aBIC[1:L3] == min(aBIC[1:L3]))[1];lam3 = lambda3[n_lam3]
for (l2 in 1:L2) {
lam2 = lambda2[l2];l = L3+l2
PP = FGGM.refit(data, K, lam1, lam2, lam3, initialization=FALSE, initialize=out.initial, average=average,
asymmetric=asymmetric, local_appro=local_appro, penalty = penalty, theta.fusion=theta.fusion)
mu_hat=PP$mu;Theta_hat=PP$Xi;L.mat = PP$L.mat0;group = PP$group;prob = PP$prob0;aBIC[l] = PP$bic; member = PP$member
Mu_hat.list[[l]]=mu_hat; Theta_hat.list[[l]]=Theta_hat; prob.list[[l]]=prob; L.mat.list[[l]] = L.mat; member.list[[l]]=member
if(trace){
print(c(cat(paste(l,"lam1 lam2 lam3 ="),c(round(lam1,2),round(lam2,2),round(lam3,2)),":"),paste("K =",as.numeric(dim(Theta_hat)[3]))))
}
}
aBIC[is.na(aBIC)] = 10^10
n_lam2 = which(aBIC[(L3+1):(L3+L2)] == min(aBIC[(L3+1):(L3+L2)]))[1];lam2 = lambda2[n_lam2]
for (l1 in 1:L1) {
lam1 = lambda1[l1];l = L3+L2+l1
PP = FGGM.refit(data, K, lam1, lam2, lam3, initialization=F, initialize=out.initial, average=average,
asymmetric=asymmetric, local_appro=local_appro, penalty = penalty, theta.fusion=theta.fusion)
mu_hat=PP$mu;Theta_hat=PP$Xi;L.mat = PP$L.mat0;group = PP$group;prob = PP$prob0;aBIC[l] = PP$bic; member = PP$member
Mu_hat.list[[l]]=mu_hat; Theta_hat.list[[l]]=Theta_hat; prob.list[[l]]=prob; L.mat.list[[l]] = L.mat; member.list[[l]]=member
if(trace){
print(c(cat(paste(l,"lam1 lam2 lam3 ="),c(round(lam1,2),round(lam2,2),round(lam3,2)),":"),paste("K =",as.numeric(dim(Theta_hat)[3]))))
}
}
aBIC[is.na(aBIC)] = 10^10
aBIC[aBIC==0] = abs(aBIC[aBIC!=0][1])*10
n_lam1 = which(aBIC[(L3+L2+1):(L3+L2+L1)] == min(aBIC[(L3+L2+1):(L3+L2+L1)]))[1];lam1 = lambda1[n_lam1]
}
K.list <- rep(1,length(Theta_hat.list))
for (l in 1:length(Theta_hat.list)) {
K.list[l] <- as.numeric(dim(Theta_hat.list[[l]])[3])
}
aBIC[which(K.list == 1)] <- 10^10
n_lam = which(aBIC == min(aBIC))[1]
Opt_aBIC = min(aBIC)
Opt_lambda = c(lam1,lam2,lam3)
result = list(Opt_lambda=Opt_lambda,Mu_hat.list=Mu_hat.list,Theta_hat.list=Theta_hat.list,prob.list=prob.list,member.list=member.list,L.mat.list=L.mat.list,Opt_aBIC=Opt_aBIC,BIC=aBIC,Opt_num=n_lam)
return(result)
}
|
get_var_corr_<-function(df,subset_cols=NULL,
drop_columns = c("character","factor"),
...){
UseMethod("get_var_corr_")
}
get_var_corr_.data.frame<-function(df,subset_cols=NULL,
drop_columns = c("character","factor"),
...){
if(any(sapply(df,class) %in% drop_columns)){
df<- Filter(function(x) ! class(x) %in% drop_columns,df)
warning("Columns with classes in drop_columns were dropped.")
}
to_use <- as.data.frame(t(combn(names(df),2)),stringsAsFactors= FALSE)
compare_with<-to_use[[1]]
other <- to_use[[2]]
final_res <- Map(function(x,y)
manymodelr::get_var_corr(df,
comparison_var = x,
other_vars = y,
...),compare_with,other)
final_result<-do.call(rbind,final_res)
final_result<-structure(final_result,row.names=1:nrow(final_result))
if(!is.null(subset_cols)){
final_result<-final_result[final_result$comparison_var %in% subset_cols[[1]] &
final_result$other_var %in% subset_cols[[2]],]
}
final_result
}
|
list_pop <- function() {
avail_pop <- data.frame("pop_code" = c("ALL", "AFR", "YRI", "LWK",
"GWD", "MSL", "ESN", "ASW",
"ACB", "AMR", "MXL", "PUR",
"CLM", "PEL", "EAS", "CHB",
"JPT", "CHS", "CDX", "KHV",
"EUR", "CEU", "TSI", "FIN",
"GBR", "IBS", "SAS", "GIH",
"PJL", "BEB", "STU", "ITU"),
"super_pop_code" = c("ALL", rep("AFR", 8), rep("AMR", 5),
rep("EAS", 6), rep("EUR", 6),
rep("SAS", 6)),
"pop_name" = c("ALL POPULATIONS",
"AFRICAN",
"Yoruba in Ibadan, Nigera",
"Luhya in Webuye, Kenya",
"Gambian in Western Gambia",
"Mende in Sierra Leone",
"Esan in Nigera",
"Americans of African Ancestry in SW USA",
"African Carribbeans in Barbados",
"AD MIXED AMERICAN",
"Mexican Ancestry from Los Angeles, USA",
"Puerto Ricans from Puerto Rico",
"Colombians from Medellin, Colombia",
"Peruvians from Lima, Peru",
"EAST ASIAN",
"Han Chinese in Bejing, China",
"Japanese in Tokyo, Japan",
"Southern Han Chinese",
"Chinese Dai in Xishuangbanna, China",
"Kinh in Ho Chi Minh City, Vietnam",
"EUROPEAN",
"Utah Residents from North and West Europe",
"Toscani in Italia",
"Finnish in Finland",
"British in England and Scotland",
"Iberian population in Spain",
"SOUTH ASIAN",
"Gujarati Indian from Houston, Texas, USA",
"Punjabi from Lahore, Pakistan",
"Bengali from Bangladesh",
"Sri Lankan Tamil from the UK",
"Indian Telugu from the UK")
)
return(avail_pop)
}
|
library(qte)
data(lalonde)
dd1 <- ddid2(re ~ treat, t=1978, tmin1=1975, tname="year",
data=lalonde.psid.panel, idname="id", se=FALSE,
probs=seq(0.05, 0.95, 0.05))
summary(dd1)
|
cross.table<-
function ( ..., null.tokens = TRUE, out.format = c('rdata','excel'), file.align = 'alignment')
{
out.format = match.arg(out.format)
p1 = prepare.data (..., word.align = FALSE)
len = p1 $ used
p1 = unlist (p1, recursive = FALSE)
if (null.tokens) {
p1 = sapply(3 : length(p1), function(x) c('null', p1[[x]])); fg1 = "null"
} else {
p1 = sapply(3 : length(p1), function(x) p1[[x]]); fg1 = "nolink"
}
if (out.format == 'rdata')
{
readline(paste("If you want to build a gold standard, please enter '1|2' for Sure|Possible alignments. \nIf you want to construct an alignment matrix which is computed by another software, please enter '1' for alignments.\nNow, press 'Enter' to continue.",sep=''))
mm = sapply (1 : len, function (x) {m = matrix (0, length (p1 [[x]]) + 1, length (p1 [[x + len]]) + 1);
m [2 : nrow (m), 1] = p1 [[x]]; m [1, 2 : ncol(m)] = p1 [[x+len]]; m [1, 1] = ''; m})
fg = c()
for(sn in 1 : len)
{
fg2 = mm [[sn]]
fg2 = fix (fg2)
fg[[sn]] = fg2
}
save(fg, fg1, file = paste(file.align,'RData',sep='.'))
print(paste(getwd(), '/', file.align,'.RData',' created',sep=''))
}
if (out.format == 'excel')
{
file_align = paste(file.align,'xlsx',sep='.')
wb1 <- createWorkbook ("data")
for (j in 1 : len)
{
m1 = matrix (0, length (p1 [[j]]) + 1, length (p1 [[j + len]]) + 1)
m1 [2 : nrow (m1), 1] = p1 [[j]]; m1 [1, 2 : ncol (m1)] = p1 [[j + len]]; m1 [1, 1] = ''
addWorksheet (wb1, as.character(j))
writeData (wb1, sheet =j, m1)
saveWorkbook (wb1, file_align, overwrite = TRUE)
}
cat (paste("Now, please edit ","'", file.align,"'",".", "\nIf you want to build a gold standard, please enter 1|2 for Sure|Possible alignments.\nIf you want to construct an alignment matrix which is computed by another software, please enter '1' for alignments.\nImportant: In order to use the created excel file for evaluation function,\ndon't forget to use excel2rdata function to convert the excel file into required R format.\n(evaluation and excel2rdata are functions in the current package.)\n ",sep=''))
print(paste(getwd(), '/', file.align,' created',sep=''))
}
}
|
test_that("add_stage", {
pipeline <- add_stage("$match", list(flight=1545))
expect_s3_class(pipeline, "mongopipe")
expect_equal(as.character(pipeline), "[{\"$match\":{\"flight\":1545}}]")
})
test_that("match", {
pipe_match <- match(mongopipe(), dest="ABQ")
expect_snapshot_output(cat(pipe_match))
})
test_that("pipe", {
pipe <- mongopipe() %>%
match(faa="ABQ") %>%
lookup(from = "test_flights",
local_field = "faa",
foreign_field = "dest") %>%
unwind(field = "test_flights")
expect_snapshot_output(cat(pipe))
pipe2 <- mongopipe() %>%
match(tzone="America/New_York") %>%
lookup(from = "test_flights",
local_field = "faa",
foreign_field = "dest") %>%
field(min_distance = list("$min"="$test_flights.distance")) %>%
match(min_distance=list("$ne"=NA)) %>%
project("min_distance"=1, "faa"=1) %>%
limit(3)
expect_snapshot_output(cat(pipe2))
})
|
weight <- function(cons, inds, vars = NULL, iterations = 10) {
if (!is.data.frame(cons)) {
stop("cons is not a data frame")
}
if (!is.data.frame(inds)) {
stop("inds is not a data frame")
}
if (!(is.atomic(vars) || is.list(vars))) {
stop("vars is not a vector")
}
zones <- as.vector(unlist(cons[, 1]))
cons <- cons[, -1]
cons <- as.matrix(cons)
cons[] <- as.numeric(cons[])
ids <- as.vector(unlist(inds[, 1]))
inds <- inds[, 2:ncol(inds)]
inds <- lapply(as.list(vars), function(x) {
stats::model.matrix( ~ inds[[x]] - 1)
})
for (i in seq_along(vars)) {
colnames(inds[[i]]) <- gsub("inds\\[\\[x\\]\\]", "", colnames(inds[[i]]))
}
rm(i)
ind_cat <- do.call(cbind, inds)
stopifnot(all.equal(colnames(cons), colnames(ind_cat)))
colnames(ind_cat) <- paste0(seq_along(colnames(ind_cat)),
"_",
colnames(ind_cat))
colnames(cons) <- colnames(ind_cat)
if (!isTRUE(all.equal(colnames(ind_cat), colnames(cons)))) {
stop("Column names don't match.\n
Are the first columns in cons and inds a zone code/unique ID?
Check the unique levels in inds and colnames in cons match EXACTLY.
Unique levels identified by weight():\n\n",
vapply(seq_along(colnames(ind_cat)), function(x)
paste0(colnames(ind_cat)[x], " "), "")
)
}
weights <- apply(cons, 1, function(x) {
ipfp::ipfp(x, t(ind_cat), x0 = rep(1, nrow(ind_cat)),
maxit = iterations)
})
if (!isTRUE(all.equal(sum(weights), (sum(cons) / length(vars))))) {
stop("Weight populations don't match constraint populations.
Usually this means the populations for each of your constraints
are slightly different\n",
"Sum of simulated population: ", sum(weights), "\n",
"Sum of constraint population: ", (sum(cons) / length(vars)))
}
if (!isTRUE(colSums(weights) - (rowSums(cons) / length(vars))) < 1L) {
stop("Simulated weights by zone differ from constraint weights by zone\n",
"Sum of the differences between zones (should be <1): ",
sum(colSums(weights) - (rowSums(cons) / length(vars)))
)
}
rownames(weights) <- ids
colnames(weights) <- zones
weights <- as.data.frame(weights)
weights
}
extract <- function(weights, inds, id) {
variables <- colnames(inds)
variables <- variables[-grep(id, variables)]
lapply(inds[, variables], function(x) {
if (class(x) == "numeric" | class(x) == "integer") {
stop("rakeR::extract() cannot work with numeric (i.e. integer or double)
variables because by design it creates a new variable for each
unique level in each variable\n
Consider cut()ing your numeric data, extract() without your
numeric data, or integerise() instead.")
}
})
levels <- lapply(as.list(variables), function(x) {
sort(unique(as.character(inds[[x]])))
})
result <- lapply(variables, function(y) {
lapply(as.list(sort(unique(as.character(inds[[y]])))), function(x) {
match_id <- inds[[id]][inds[[y]] == x]
matched_weights <- weights[row.names(weights) %in% match_id, ]
matched_weights <- colSums(matched_weights)
matched_weights
})
})
result <- as.data.frame(result)
colnames(result) <- unlist(levels)
df <- data.frame(
code = colnames(weights),
total = colSums(weights),
row.names = NULL, stringsAsFactors = FALSE
)
stopifnot(
all.equal(df[["code"]], row.names(result))
)
df <- cbind(df, result)
row.names(df) <- NULL
stopifnot(
all.equal(
sum(df[["total"]]),
(sum(df[, 3:ncol(df)]) / length(variables)))
)
df
}
extract_weights <- function(weights, inds, id) {
.Deprecated("extract")
variables <- colnames(inds)
variables <- variables[-grep(id, variables)]
lapply(inds[, variables], function(x) {
if (class(x) == "numeric" | class(x) == "integer") {
stop("rakeR::extract() cannot work with numeric (i.e. integer or double)
variables because by design it creates a new variable for each
unique level in each variable\n
Consider cut()ing your numeric data, extract() without your
numeric data, or integerise() instead.")
}
})
levels <- lapply(as.list(variables), function(x) {
sort(unique(as.character(inds[[x]])))
})
result <- lapply(variables, function(y) {
lapply(as.list(sort(unique(as.character(inds[[y]])))), function(x) {
match_id <- inds[[id]][inds[[y]] == x]
matched_weights <- weights[row.names(weights) %in% match_id, ]
matched_weights <- colSums(matched_weights)
matched_weights
})
})
result <- as.data.frame(result)
colnames(result) <- unlist(levels)
df <- data.frame(
code = colnames(weights),
total = colSums(weights),
row.names = NULL, stringsAsFactors = FALSE
)
stopifnot(
all.equal(df[["code"]], row.names(result))
)
df <- cbind(df, result)
row.names(df) <- NULL
stopifnot(
all.equal(
sum(df[["total"]]),
(sum(df[, 3:ncol(df)]) / length(variables)))
)
message("extract_weights() is deprecated. Please use extract()")
df
}
integerise <- function(weights, inds, method = "trs", seed = 42) {
set.seed(seed)
if (!all.equal(nrow(weights), nrow(inds))) {
stop("Number of observations in weights does not match inds")
}
if (!is.data.frame(inds)) {
stop("inds is not a data frame")
}
if (!method == "trs") {
stop("Currently this function only supports the truncate, replicate,
sample method.
Proportional probabilities may be added at a later date.
For now use the default method (trs).")
}
weights <- as.matrix(weights)
weights_vec <- as.vector(weights)
weights_int <- floor(weights_vec)
weights_dec <- weights_vec - weights_int
deficit <- round(sum(weights_dec))
if (!sum(weights_dec %% 1) > 0) {
message("weights already integers. Returning unmodified")
return(weights)
}
topup <- wrswoR::sample_int_crank(n = length(weights),
size = deficit,
prob = weights_dec)
weights_int[topup] <- weights_int[topup] + 1
dim(weights_int) <- dim(weights)
dimnames(weights_int) <- dimnames(weights)
weights_int <- apply(weights_int, 2, as.integer)
weights_int <- as.data.frame(weights_int)
weights_int <- as.matrix(weights_int)
indices <- apply(weights_int, 2, function(x) {
rep.int(seq_along(x), x)
})
indices <- as.numeric(unlist(indices))
zone <- rep(colnames(weights), times = colSums(weights_int))
sim_df <- inds[indices, ]
sim_df$zone <- zone
if (!all.equal(sum(weights), nrow(sim_df))) {
stop("Number of simulated observations does not match sum of weights.")
}
sim_df
}
rake <- function(cons, inds, vars,
output = "fraction",
iterations = 10, ...) {
arguments <- list(...)
out <- weight(cons, inds, vars, iterations)
if (output == "fraction") {
frac_out <- extract(weights = out, inds = inds,
id = arguments[["id"]])
return(frac_out)
} else if (output == "integer") {
int_out <- integerise(out, inds,
method = arguments[["method"]],
seed = arguments[["seed"]])
return(int_out)
}
}
simulate <- function(...) {
.Deprecated(msg = "rakeR::simulate() is deprecated. Just use
weight() %>% integerise() (or rake(output = \"integer\"))")
}
|
ls7Search<-function(AppRoot,verbose=FALSE,precise=FALSE,...){
warning("Obsolete function, use lsSearch.")
arg<-list(...)
if((!"dates"%in%names(arg))&
((!"startDate"%in%names(arg)|(!"endDate"%in%names(arg))))
)stop("startDate and endDate, or dates argument need to be defined!")
if("dates"%in%names(arg)){
stopifnot(class(arg$dates)=="Date")
startDate<-min(arg$dates)
endDate<-max(arg$dates)
}else{
startDate<-arg$startDate
endDate<-arg$endDate
}
stopifnot(class(startDate)=="Date")
stopifnot(class(endDate)=="Date")
AppRoot<-pathWinLx(AppRoot)
if(!ls7IsMetaData()){
message("MetaData not loaded! loading...")
ls7LoadMetadata(AppRoot=AppRoot,update=FALSE,...)
}
LS7MD<-getRGISToolsOpt("LS7METADATA")
LS7MD<-LS7MD[as.Date(LS7MD$acquisitionDate)>=startDate&
as.Date(LS7MD$acquisitionDate)<=endDate,]
if("pathrow"%in%names(arg)){
stopifnot(class(arg$pathrow)=="list")
LS7MD<-do.call(rbind,lapply(arg$pathrow,function(rp,LS7MD,verbose)return(genFilterDF(LS7MD,row=rp[2],path=rp[1],verbose=verbose)),
LS7MD,
verbose=verbose))
}else if("extent"%in%names(arg)){
stopifnot(class(extent(arg$extent))=="Extent")
if(precise){
tiles<-unlist(apply(LS7MD[grepl("Corner",names(LS7MD))],1,tileIn,ext=extent(arg$extent)))
LS7MD<-LS7MD[tiles,]
}else{
pathrow<-names(ls7pr)[unlist(lapply(ls7pr,tileInExt,ext2=extent(arg$extent)))]
pathrow<-as.data.frame(cbind(as.integer(substr(pathrow,1,3)),as.integer(substr(pathrow,4,6))))
pathrow = lapply(as.list(1:dim(pathrow)[1]), function(x) unname(pathrow[x[1],]))
LS7MD<-do.call(rbind,lapply(pathrow,
function(pr,LS7MD,verbose){pr=unlist(pr);return(genFilterDF(LS7MD,row=pr[2],path=pr[1],verbose=verbose))},
LS7MD=LS7MD,
verbose=verbose))
}
}else if("lonlat"%in%names(arg)){
stopifnot(class(arg$lonlat)=="numeric")
stopifnot(length(arg$lonlat)==2)
dat_sim <- data.frame(lat = arg$lonlat[2],long = arg$lonlat[1])
dat_sf <- st_transform(st_as_sf(dat_sim, coords = c("long", "lat"), crs = 4326), 3035)
circle <- st_buffer(dat_sf, dist = 1)
circle <- st_transform(circle, 4326)
if(precise){
tiles<-unlist(apply(LS7MD[grepl("Corner",names(LS7MD))],1,tileIn,ext=extent(circle)))
LS7MD<-LS7MD[tiles,]
}else{
pathrow<-names(ls7pr)[unlist(lapply(ls7pr,tileInExt,ext2=extent(circle)))]
pathrow<-as.data.frame(cbind(as.integer(substr(pathrow,1,3)),as.integer(substr(pathrow,4,6))))
pathrow = lapply(as.list(1:dim(pathrow)[1]), function(x) unname(pathrow[x[1],]))
LS7MD<-do.call(rbind,lapply(pathrow,
function(pr,LS7MD,verbose){pr=unlist(pr);return(genFilterDF(LS7MD,row=pr[2],path=pr[1],verbose=verbose))},
LS7MD=LS7MD,
verbose=verbose))
}
}else if("region"%in%names(arg)){
arg$region<-transform_multiple_proj(arg$region, proj4=st_crs(4326))
if(precise){
tiles<-unlist(apply(LS7MD[grepl("Corner",names(LS7MD))],1,tileIn,ext=extent(arg$region)))
LS7MD<-LS7MD[tiles,]
}else{
pathrow<-names(ls7pr)[unlist(lapply(ls7pr,tileInExt,ext2=extent(arg$region)))]
pathrow<-as.data.frame(cbind(as.integer(substr(pathrow,1,3)),as.integer(substr(pathrow,4,6))))
pathrow = lapply(as.list(1:dim(pathrow)[1]), function(x) unname(pathrow[x[1],]))
LS7MD<-do.call(rbind,lapply(pathrow,
function(pr,LS7MD,verbose){pr=unlist(pr);return(genFilterDF(LS7MD,row=pr[2],path=pr[1],verbose=verbose))},
LS7MD=LS7MD,
verbose=verbose))
}
}else{
warning("Location not defined!")
}
if("cloudCover"%in%names(arg)){
LS7MD<-LS7MD[LS7MD$cloudCover>min(arg$cloudCover)&LS7MD$cloudCover<max(arg$cloudCover),]
}
arg<-arg[names(arg)[which(!names(arg)%in%c("pathrow","region","cloudCover"))]]
if(length(arg)>0){
arg$df<-LS7MD
LS7MD<-do.call(genFilterDF,arg)
}
LS7MD<-LS7MD[!duplicated(LS7MD[,c('sceneID')]),]
if("dates"%in%names(arg)){
LS7MD<-LS7MD[as.Date(LS7MD$acquisitionDate)%in%arg$dates,]
}
class(LS7MD)<-"ls7res"
return(LS7MD)
}
|
context("public API")
test_that("styler can style package", {
capture_output(expect_false({
styled <- style_pkg(testthat_file("public-api", "xyzpackage"))
any(styled$changed)
}))
})
test_that("styler can style package and exclude some directories", {
capture_output(
styled <- style_pkg(testthat_file("public-api", "xyzpackage"),
exclude_dirs = "tests"
)
)
expect_true(nrow(styled) == 1)
expect_false(any(grepl("tests/testthat/test-package-xyz.R", styled$file)))
})
test_that("styler can style package and exclude some sub-directories", {
capture_output(
styled <- style_pkg(testthat_file("public-api", "xyzpackage"),
exclude_dirs = "tests/testthat"
)
)
expect_true(nrow(styled) == 2)
expect_true(any(grepl("tests/testthat.R", styled$file)))
expect_false(any(grepl("tests/testthat/test-package-xyz.R", styled$file)))
})
test_that("styler can style package and exclude some directories and files", {
capture_output(expect_true({
styled <- style_pkg(testthat_file("public-api", "xyzpackage"),
exclude_dirs = "tests",
exclude_files = ".Rprofile"
)
nrow(styled) == 1
}))
capture_output(expect_true({
styled <- style_pkg(testthat_file("public-api", "xyzpackage"),
exclude_dirs = "tests",
exclude_files = "./.Rprofile"
)
nrow(styled) == 1
}))
})
test_that("styler can style directory", {
capture_output(expect_false({
styled <- style_dir(testthat_file("public-api", "xyzdir"))
any(styled$changed)
}))
})
test_that("styler can style directories and exclude", {
capture_output(expect_true({
styled <- style_dir(
testthat_file("public-api", "renvpkg"),
exclude_dirs = "renv"
)
nrow(styled) == 2
}))
capture_output(expect_true({
styled <- style_dir(
testthat_file("public-api", "renvpkg"),
exclude_dirs = c("renv", "tests/testthat")
)
nrow(styled) == 1
}))
capture_output(expect_true({
styled <- style_dir(
testthat_file("public-api", "renvpkg"),
exclude_dirs = "./renv"
)
nrow(styled) == 2
}))
capture_output(expect_true({
styled <- style_dir(
testthat_file("public-api", "renvpkg"),
exclude_dirs = "./renv", recursive = FALSE
)
nrow(styled) == 0
}))
capture_output(expect_true({
styled <- style_dir(
testthat_file("public-api", "renvpkg"),
recursive = FALSE
)
nrow(styled) == 0
}))
})
test_that("styler can style files", {
capture_output(expect_equivalent(
{
out <- style_file(c(
testthat_file("public-api", "xyzfile", "random-script.R")
), strict = FALSE)
out$changed
},
rep(FALSE, 1)
))
capture_output(expect_equivalent(
{
out <- style_file(c(
testthat_file("public-api", "xyzfile", "random-script.R"),
testthat_file("public-api", "xyzfile", "subfolder", "random-script.R")
), strict = FALSE)
out$changed
},
rep(FALSE, 2)
))
})
test_that("styler does not return error when there is no file to style", {
capture_output(expect_error(style_dir(
testthat_file("public-api", "xyzemptydir"),
strict = FALSE
), NA))
})
context("public API - Rmd in style_file()")
test_that("styler can style Rmd file", {
capture_output(expect_false({
out <- style_file(
testthat_file("public-api", "xyzfile_rmd", "random.Rmd"),
strict = FALSE
)
out$changed
}))
capture_output(expect_warning(
styled <- style_file(testthat_file("public-api", "xyzfile_rmd", "random2.Rmd"), strict = FALSE)
))
expect_false(styled$changed)
})
test_that("styler can style Rmarkdown file", {
capture_output(expect_false({
out <- style_file(
testthat_file("public-api", "xyzfile_rmd", "random.Rmarkdown"),
strict = FALSE
)
out$changed
}))
capture_output(expect_warning(
styled <- style_file(testthat_file("public-api", "xyzfile_rmd", "random2.Rmarkdown"), strict = FALSE)
))
expect_false(styled$changed)
})
test_that("styler handles malformed Rmd file and invalid R code in chunk", {
capture_output(expect_warning(
style_file(testthat_file("public-api", "xyzfile_rmd", "random4.Rmd"), strict = FALSE),
"3: "
))
capture_output(expect_warning(
style_file(testthat_file("public-api", "xyzfile_rmd", "random7.Rmd"), strict = FALSE),
"Malformed file"
))
})
context("messages are correct")
test_that("messages (via cat()) of style_file are correct", {
for (encoding in ls_testable_encodings()) {
withr::with_options(
list(cli.unicode = encoding == "utf8"),
{
output <- catch_style_file_output(file.path(
"public-api",
"xyzdir-dirty",
"dirty-sample-with-scope-tokens.R"
))
expect_known_value(
output,
testthat_file(paste0(
"public-api/xyzdir-dirty/dirty-reference-with-scope-tokens-",
encoding
)),
update = getOption("styler.test_dir_writable", TRUE)
)
output <- catch_style_file_output(file.path(
"public-api", "xyzdir-dirty", "clean-sample-with-scope-tokens.R"
))
expect_known_value(
output,
testthat_file(paste0(
"public-api/xyzdir-dirty/clean-reference-with-scope-tokens-",
encoding
)),
update = getOption("styler.test_dir_writable", TRUE)
)
output <- catch_style_file_output(file.path(
"public-api", "xyzdir-dirty", "dirty-sample-with-scope-spaces.R"
))
expect_known_value(
output,
testthat_file(paste0(
"public-api/xyzdir-dirty/dirty-reference-with-scope-spaces-",
encoding
)),
update = getOption("styler.test_dir_writable", TRUE)
)
}
)
}
})
test_that("Messages can be suppressed", {
withr::with_options(
list(styler.quiet = TRUE),
{
output <- catch_style_file_output(file.path(
"public-api", "xyzdir-dirty", "dirty-sample-with-scope-spaces.R"
))
expect_equal(output, character(0))
}
)
})
context("public API - Rmd in style_dir()")
test_that("styler can style R, Rmd and Rmarkdown files via style_dir()", {
msg <- capture_output(
style_dir(testthat_file("public-api", "xyz-r-and-rmd-dir"),
filetype = c("R", "Rmd", "Rmarkdown")
)
)
expect_true(any(grepl("random-script-in-sub-dir.R", msg, fixed = TRUE)))
expect_true(any(grepl("random-rmd-script.Rmd", msg, fixed = TRUE)))
expect_true(any(grepl("random-rmd-script.Rmarkdown", msg, fixed = TRUE)))
})
test_that("styler can style Rmd files only via style_dir()", {
msg <- capture_output(
style_dir(testthat_file("public-api", "xyz-r-and-rmd-dir"),
filetype = "Rmd"
)
)
expect_true(any(grepl("random-rmd-script.Rmd", msg, fixed = TRUE)))
expect_false(any(grepl("random-script-in-sub-dir.R", msg, fixed = TRUE)))
expect_false(any(grepl("random-rmd-script.Rmarkdown", msg, fixed = TRUE)))
})
test_that("styler can style .r and .rmd files only via style_dir()", {
msg <- capture_output(
style_dir(testthat_file("public-api", "xyz-r-and-rmd-dir"),
filetype = c(".r", ".rmd")
)
)
expect_true(any(grepl("random-script-in-sub-dir.R", msg, fixed = TRUE)))
expect_true(any(grepl("random-rmd-script.Rmd", msg, fixed = TRUE)))
expect_false(any(grepl("random-rmd-script.Rmarkdown", msg, fixed = TRUE)))
})
context("public API - Rmd in style_pkg()")
test_that("styler can style R and Rmd files via style_pkg()", {
msg <- capture_output(
style_pkg(testthat_file("public-api", "xyzpackage-rmd"),
filetype = c("R", "Rmd", "Rmarkdown")
)
)
expect_true(any(grepl("hello-world.R", msg, fixed = TRUE)))
expect_true(any(grepl("test-package-xyz.R", msg, fixed = TRUE)))
expect_true(any(grepl("random.Rmd", msg, fixed = TRUE)))
expect_true(any(grepl("random.Rmarkdown", msg, fixed = TRUE)))
expect_true(any(grepl("README.Rmd", msg, fixed = TRUE)))
expect_false(any(grepl("RcppExports.R", msg, fixed = TRUE)))
})
test_that("styler can style Rmd files only via style_pkg()", {
msg <- capture_output(
style_pkg(testthat_file("public-api", "xyzpackage-rmd"),
filetype = "Rmd"
)
)
expect_false(any(grepl("hello-world.R", msg, fixed = TRUE)))
expect_false(any(grepl("test-package-xyz.R", msg, fixed = TRUE)))
expect_true(any(grepl("random.Rmd", msg, fixed = TRUE)))
expect_false(any(grepl("random.Rmarkdown", msg, fixed = TRUE)))
expect_true(any(grepl("README.Rmd", msg, fixed = TRUE)))
expect_false(any(grepl("RcppExports.R", msg, fixed = TRUE)))
})
test_that("styler can style Rmarkdown files only via style_pkg()", {
msg <- capture_output(
style_pkg(testthat_file("public-api", "xyzpackage-rmd"),
filetype = "Rmarkdown"
)
)
expect_false(any(grepl("hello-world.R", msg, fixed = TRUE)))
expect_false(any(grepl("test-package-xyz.R", msg, fixed = TRUE)))
expect_false(any(grepl("random.Rmd", msg, fixed = TRUE)))
expect_true(any(grepl("random.Rmarkdown", msg, fixed = TRUE)))
expect_false(any(grepl("README.Rmd", msg, fixed = TRUE)))
expect_false(any(grepl("RcppExports.R", msg, fixed = TRUE)))
})
test_that("insufficient R version returns error", {
expect_error(stop_insufficient_r_version())
})
context("public API - Rnw in style_file()")
test_that("styler can style Rnw file", {
capture_output(expect_false({
out <- style_file(
testthat_file("public-api", "xyzfile-rnw", "random.Rnw"),
strict = FALSE
)
out$changed
}))
capture_output(expect_warning(
styled <- style_file(testthat_file("public-api", "xyzfile-rnw", "random2.Rnw"), strict = FALSE)
))
expect_false(styled$changed)
})
test_that("styler handles malformed Rnw file and invalid R code in chunk", {
capture_output(expect_warning(
style_file(testthat_file("public-api", "xyzfile-rnw", "random3.Rnw"), strict = FALSE)
))
capture_output(expect_warning(
style_file(testthat_file("public-api", "xyzfile-rnw", "random4.Rnw"), strict = FALSE)
))
})
context("public API - Rnw in style_pkg()")
test_that("styler can style R, Rmd and Rnw files via style_pkg()", {
msg <- capture_output(
style_pkg(testthat_file("public-api", "xyzpackage-rnw"),
filetype = c("R", "Rmd", "Rnw")
)
)
expect_true(any(grepl("hello-world.R", msg, fixed = TRUE)))
expect_true(any(grepl("test-package-xyz.R", msg, fixed = TRUE)))
expect_true(any(grepl("random.Rmd", msg, fixed = TRUE)))
expect_true(any(grepl("random.Rnw", msg, fixed = TRUE)))
expect_false(any(grepl("RcppExports.R", msg, fixed = TRUE)))
})
test_that("styler can style Rnw files only via style_pkg()", {
msg <- capture_output(
style_pkg(testthat_file("public-api", "xyzpackage-rnw"),
filetype = "Rnw"
)
)
expect_false(any(grepl("hello-world.R", msg, fixed = TRUE)))
expect_false(any(grepl("test-package-xyz.R", msg, fixed = TRUE)))
expect_false(any(grepl("random.Rmd", msg, fixed = TRUE)))
expect_true(any(grepl("random.Rnw", msg, fixed = TRUE)))
expect_false(any(grepl("RcppExports.R", msg, fixed = TRUE)))
})
test_that("dry run options work:", {
local_test_setup()
path <- test_path("public-api/dry/unstyled.R")
expect_error(test_dry(path, style_file, styled = TRUE))
test_dry(path, style_file)
path <- test_path("public-api/dry/styled.R")
test_dry(path, style_file, styled = TRUE)
test_dry(test_path("public-api/dry/unstyled.Rmd"), style_file, styled = FALSE)
test_dry(test_path("public-api/dry/styled.Rmd"), style_file, styled = TRUE)
test_dry(test_path("public-api/dry/unstyled.Rnw"), style_file, styled = FALSE)
test_dry(test_path("public-api/dry/styled.Rnw"), style_file, styled = TRUE)
})
test_that("base indention works", {
n_spaces <- 5
text_in <- "x<- function() NULL"
expect_equal(
style_text(text_in, base_indention = n_spaces),
construct_vertical(paste0(add_spaces(n_spaces), style_text(text_in)))
)
text_in <- c(
"x<- function()",
'"here\nis"',
"NULL",
"1+ 1"
)
text_out <- c(
" x <- function() {",
' "here',
'is"',
" }",
" NULL",
" 1 + 1"
)
expect_equal(
as.character(style_text(text_in, base_indention = n_spaces)),
text_out
)
})
test_that("scope can be specified as is", {
capture_output(expect_false({
styled <- style_pkg(testthat_file("public-api", "xyzpackage"), scope = I("spaces"))
any(styled$changed)
}))
file <- testthat_file("public-api", "xyzpackage", "R", "hello-world.R")
capture_output(expect_false({
styled <- style_file(file, scope = I("line_breaks"))
any(styled$changed)
}))
expect_equal(
style_text(c("1+14;x=2"), scope = I(c("line_breaks", "tokens"))),
construct_vertical(c("1+14", "x<-2"))
)
})
test_that("Can properly determine style_after_saving", {
withr::with_envvar(list(save_after_styling = TRUE), {
expect_warning(op <- save_after_styling_is_active(), "is depreciated")
expect_equal(op, TRUE)
})
withr::with_envvar(list(save_after_styling = FALSE), {
expect_warning(op <- save_after_styling_is_active(), "is depreciated")
expect_equal(op, FALSE)
})
withr::with_options(list(styler.save_after_styling = TRUE), {
expect_silent(op <- save_after_styling_is_active())
expect_equal(op, TRUE)
})
withr::with_options(list(styler.save_after_styling = TRUE), {
withr::with_envvar(list(save_after_styling = FALSE), {
expect_warning(op <- save_after_styling_is_active(), "is depreciated")
expect_equal(op, TRUE)
})
})
withr::with_options(list(styler.save_after_styling = FALSE), {
expect_silent(op <- save_after_styling_is_active())
expect_equal(op, FALSE)
})
})
|
listShp <- function(printed = TRUE, admin_level = c("admin0", "admin1")){
admn_level <- NULL
admin_level_numeric <- as.numeric(gsub('admin', '', admin_level))
if(exists('available_admin_stored', envir = .malariaAtlasHidden)){
available_admin <- .malariaAtlasHidden$available_admin_stored
} else {
available_admin <- NULL
}
if(!all(admin_level_numeric %in% available_admin$admn_level)){
URL_list <- c("admin0" = utils::URLencode("https://malariaatlas.org/geoserver/Explorer/ows?service=wfs&version=2.0.0&request=GetFeature&outputFormat=csv&TypeName=mapadmin_0_2018&PROPERTYNAME=iso,admn_level,name_0,id_0,type_0,source"),
"admin1" = utils::URLencode("https://malariaatlas.org/geoserver/Explorer/ows?service=wfs&version=2.0.0&request=GetFeature&outputFormat=csv&TypeName=mapadmin_1_2018&PROPERTYNAME=iso,admn_level,name_0,id_0,type_0,name_1,id_1,type_1,source"),
"admin2" = utils::URLencode("https://malariaatlas.org/geoserver/Explorer/ows?service=wfs&version=2.0.0&request=GetFeature&outputFormat=csv&TypeName=mapadmin_2_2018&PROPERTYNAME=iso,admn_level,name_0,id_0,type_0,name_1,id_1,type_1,name_2,id_2,type_2,source" ),
"admin3" = utils::URLencode("https://malariaatlas.org/geoserver/Explorer/ows?service=wfs&version=2.0.0&request=GetFeature&outputFormat=csv&TypeName=mapadmin_3_2018&PROPERTYNAME=iso,admn_level,name_0,id_0,type_0,name_1,id_1,type_1,name_2,id_2,type_2,name_3,id_3,type_3,source"))
use_URL_list <- URL_list[names(URL_list) %in% admin_level & !(0:3) %in% available_admin$admn_level]
available_admin_new <- try(lapply(X = use_URL_list, FUN = utils::read.csv, encoding = "UTF-8"))
if(inherits(available_admin_new, 'try-error')){
message(available_admin_new[1])
return(available_admin_new)
}
if(is.null(available_admin)){
available_admin <- suppressWarnings(dplyr::bind_rows(available_admin_new))
} else {
available_admin <- suppressWarnings(dplyr::bind_rows(available_admin_new, available_admin))
}
available_admin <- dplyr::select(available_admin, names(available_admin)[names(available_admin) %in% c("iso","admn_level","name_0","id_0",
"type_0","name_1","id_1","type_1","name_2","id_2","type_2",
"name_3","id_3","type_3","source")])
.malariaAtlasHidden$available_admin_stored <- available_admin
}
if(printed == TRUE){
message("Shapefiles Available to Download for: \n ",paste(sort(unique(available_admin$name_0[available_admin$admn_level==0])), collapse = " \n "))
}
available_admin <- available_admin[,!names(available_admin)%in%c("FID","gid")]
available_admin <- dplyr::filter(available_admin, admn_level %in% admin_level_numeric)
return(invisible(available_admin))
}
|
get_result <- function(result, pvalueCutoff = 0.05){
result <- result@ScoreResult
result <- result[result$p_value < pvalueCutoff,]
return(result)
}
|
prereg_knit_item_content <- function(x,
section = NULL,
headingLevel = 2) {
rmdpartials::partial(
input =
system.file("partials",
"_preregr_spec_full_partial.Rmd",
package = "preregr")
);
}
|
`symmsign.shape` <- function(X, init=NULL, steps=Inf, eps=1e-6, maxiter=100, na.action=na.fail)
{
X<-na.action(X)
X<-as.matrix(X)
n<-dim(X)[1]
p<-dim(X)[2]
if(p==1) return(diag(1))
if (is.null(init)) init<-covshape(X)
else init<-to.shape(init)
if(is.finite(steps)) maxiter<-Inf
iter<-0
V<-init
while(TRUE)
{
if(iter>=steps) return(V)
if(iter>=maxiter) warning("maxiter reached")
iter<-iter+1
sqrtV<-mat.sqrt(V)
V.new<-sqrtV%*%SSCov(X%*%solve(sqrtV))%*%sqrtV
V.new<-to.shape(V.new)
if(all(is.infinite(steps),mat.norm(V.new-V)<eps)) return(V.new)
V<-V.new
}
}
|
topSRBatsmenAcrossOversAllOppnAllMatches <- function(matches,t1) {
team=ball=totalRuns=total=SRinPowerpPlay=SRinMiddleOvers=SRinDeathOvers=batsman=str_extract=runs=count=NULL
ggplotly=NULL
a <-filter(matches,team==t1)
a1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 0.1, 5.9))
a2 <- select(a1,ball,totalRuns,batsman,date)
a3 <- a2 %>% group_by(batsman) %>% summarise(runs=sum(totalRuns),count=n(), SRinPowerpPlay=runs/count*100) %>% arrange(desc(SRinPowerpPlay)) %>%
select(batsman,SRinPowerpPlay)
b1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 6.1, 15.9))
b2 <- select(b1,ball,totalRuns,batsman,date)
b3 <- b2 %>% group_by(batsman) %>% summarise(runs=sum(totalRuns),count=n(), SRinMiddleOvers=runs/count*100) %>% arrange(desc(SRinMiddleOvers)) %>%
select(batsman,SRinMiddleOvers)
c1 <- a %>% filter(between(as.numeric(str_extract(ball, "\\d+(\\.\\d+)?$")), 16.1, 20.0))
c2 <- select(c1,ball,totalRuns,batsman,date)
c3 <- c2 %>% group_by(batsman) %>% summarise(runs=sum(totalRuns),count=n(), SRinDeathOvers=runs/count*100) %>% arrange(desc(SRinDeathOvers)) %>%
select(batsman,SRinDeathOvers)
val=min(dim(a3)[1],dim(b3)[1],dim(c3)[1])
m=cbind(a3[1:val,],b3[1:val,],c3[1:val,])
m
}
|
tokens_select <- function(x, pattern, selection = c("keep", "remove"),
valuetype = c("glob", "regex", "fixed"),
case_insensitive = TRUE, padding = FALSE, window = 0,
min_nchar = NULL, max_nchar = NULL,
startpos = 1L, endpos = -1L,
verbose = quanteda_options("verbose")) {
UseMethod("tokens_select")
}
tokens_select.default <- function(x, pattern = NULL,
selection = c("keep", "remove"),
valuetype = c("glob", "regex", "fixed"),
case_insensitive = TRUE, padding = FALSE, window = 0,
min_nchar = NULL, max_nchar = NULL,
startpos = 1L, endpos = -1L,
verbose = quanteda_options("verbose")) {
check_class(class(x), "tokens_select")
}
tokens_select.tokens <- function(x, pattern = NULL,
selection = c("keep", "remove"),
valuetype = c("glob", "regex", "fixed"),
case_insensitive = TRUE, padding = FALSE, window = 0,
min_nchar = NULL, max_nchar = NULL,
startpos = 1L, endpos = -1L,
verbose = quanteda_options("verbose")) {
x <- as.tokens(x)
selection <- match.arg(selection)
valuetype <- match.arg(valuetype)
padding <- check_logical(padding)
window <- check_integer(window, min_len = 1, max_len = 2, min = 0)
startpos <- check_integer(startpos, max_len = Inf)
endpos <- check_integer(endpos, max_len = Inf)
verbose <- check_logical(verbose)
attrs <- attributes(x)
type <- types(x)
if (is.null(pattern)) {
if (selection == "keep") {
ids <- as.list(seq_along(type))
} else {
ids <- list()
}
} else {
ids <- object2id(pattern, type, valuetype, case_insensitive,
field_object(attrs, "concatenator"))
}
if (!is.null(min_nchar) | !is.null(max_nchar)) {
len <- stri_length(type)
is_short <- is_long <- rep(FALSE, length(len))
if (!is.null(min_nchar)) {
min_nchar <- check_integer(min_nchar, min = 0)
is_short <- len < min_nchar
}
if (!is.null(max_nchar)) {
max_nchar <- check_integer(max_nchar, min = 0)
is_long <- max_nchar < len
}
id_out <- which(is_short | is_long)
if (length(id_out)) {
if (selection == "keep") {
if (all(lengths(ids) == 1)) {
ids <- setdiff(ids, as.list(id_out))
} else {
has_out <- unlist_integer(lapply(ids, function(x, y) length(intersect(x, y)) > 0, id_out))
ids <- ids[!has_out]
}
} else {
ids <- union(ids, as.list(id_out))
}
}
}
if (verbose) message_select(selection, length(ids), 0)
if (length(window) == 1) window <- rep(window, 2)
if (selection == "keep") {
result <- qatd_cpp_tokens_select(x, type, ids, 1, padding, window[1], window[2], startpos, endpos)
} else {
result <- qatd_cpp_tokens_select(x, type, ids, 2, padding, window[1], window[2], startpos, endpos)
}
rebuild_tokens(result, attrs)
}
tokens_remove <- function(x, ...) {
if ("selection" %in% names(list(...))) {
stop("tokens_remove cannot include selection argument")
}
tokens_select(x, ..., selection = "remove")
}
tokens_keep <- function(x, ...) {
if ("selection" %in% names(list(...))) {
stop("tokens_keep cannot include selection argument")
}
tokens_select(x, ..., selection = "keep")
}
|
conditionalReordering <- function(n,
list.correlation.matrix,
name,
scenario.probability = NULL,
region.boundaries = NULL,
region.probability = NULL,
keep.realized.scenario = F) {
if (!is.character(name) || duplicated(name) || (length(name) < 2) ||
!all(name %in% c("market", "life", "health", "nonlife"))) {
stop("Invalid name, see ?conditionalReordering.")
}
if (!is.list(list.correlation.matrix)) {
stop("Invalid types, see ?conditionalReordering.")
}
if (length(list.correlation.matrix) < 1) {
stop("Void list of correlation matrices, see ?conditionalReordering.")
}
if (!all(sapply(list.correlation.matrix, is.matrix))) {
stop("Invalid types, see ?conditionalReordering.")
}
if (!all(sapply(list.correlation.matrix, function(corr) identical(nrow(corr), ncol(corr))))) {
stop("Correlation matrix is not square, see ?conditionalReordering.")
}
if (!all(sapply(list.correlation.matrix, function(corr) nrow(corr) > 2))) {
stop("Correlation matrix should be at least of dimension 2, see ?conditionalReordering.")
}
if (length(unique(sapply(list.correlation.matrix, function(corr) nrow(corr)))) != 1) {
stop("Not all correlation matrices have the same dimensions, see ?conditionalReordering.")
}
if (any(sapply(list.correlation.matrix, function(corr) is.null(rownames(corr)) || is.null(colnames(corr))))) {
stop("Correlation matrix has missing rownames or colnames, see ?conditionalReordering.")
}
if (any(sapply(list.correlation.matrix, function(corr) !identical(rownames(corr), colnames(corr))))) {
stop("Correlation matrix has different rownames and colnames, see ?conditionalReordering.")
}
if (any(sapply(list.correlation.matrix, function(corr) duplicated(rownames(corr)) || duplicated(colnames(corr))))) {
stop("Correlation matrix has different duplicated colnames or rownames, see ?conditionalReordering.")
}
if (any(sapply(list.correlation.matrix, function(corr) !all(colnames(corr) %in% c("market", "life", "health", "nonlife")) ||
!all(c("market", "life", "health", "nonlife") %in% colnames(corr))))) {
stop("Correlation matrix has invalid names, see ?conditionalReordering.")
}
if (!all(sapply(list.correlation.matrix, function(corr) { identical(t(corr), corr)}))) {
stop("all correlation matrix should be symmetric, see ?conditionalReordering.")
}
if (!all(sapply(list.correlation.matrix, function(corr) { all(eigen(removePerfectCorr(corr), symmetric = T, only.values = T)$values >= 0)}))) {
stop("all correlation matrix should be positive semi-definite, see ?conditionalReordering.")
}
if (length(list.correlation.matrix) > 1) {
if (is.null(region.probability) || is.null(scenario.probability) || is.null(region.boundaries)) {
stop("Invalid types, see ?conditionalReordering.")
}
if (!is.numeric(region.probability) || !is.numeric(scenario.probability) ||
!is.matrix(region.boundaries) || !is.numeric(region.boundaries)) {
stop("Invalid types, see ?conditionalReordering")
}
if (any(!is.finite(region.probability)) || any(!is.finite(scenario.probability)) || any(!is.finite(region.boundaries))) {
stop("Non-finite values, see ?conditionalReordering.")
}
if (is.null(names(list.correlation.matrix)) ||
is.null(rownames(region.boundaries)) ||
is.null(colnames(region.boundaries))) {
stop("Missing names, see ?conditionalReordering.")
}
if (!all(setdiff(names(list.correlation.matrix), "base") %in% rownames(region.boundaries)) ||
!all(rownames(region.boundaries) %in% setdiff(names(list.correlation.matrix), "base"))) {
stop("Incompatible scenario names, see ?conditionalReordering.")
}
if (ncol(region.boundaries) != ncol(list.correlation.matrix[[1]])) {
stop("Incompatible dimensions, see ?conditionalReordering.")
}
if (length(list.correlation.matrix) != (1+length(scenario.probability))) {
stop("Incompatible dimensions, see ?conditionalReordering.")
}
if (length(list.correlation.matrix) != (1+length(region.probability))) {
stop("Incompatible dimensions, see ?conditionalReordering.")
}
if (length(list.correlation.matrix) != (1+nrow(region.boundaries))) {
stop("Incompatible dimensions, see ?conditionalReordering.")
}
if (any(scenario.probability <= 0 | scenario.probability >= 1)) {
stop("scenario.probability should be in (0,1), see ?conditionalReordering.")
}
if (any(region.probability <= 0 | region.probability >= 1)) {
stop("region.probability should be in (0,1), see ?conditionalReordering.")
}
if (sum(scenario.probability / region.probability) > 1) {
stop("Invalid scenario.probability and/or region.probability, see ?conditionalReordering.")
}
if (any(region.boundaries < 0 | region.boundaries > 1)) {
stop("region.boundaries should be in [0,1], see ?conditionalReordering.")
}
}
index.name <- sapply(name, function(n)
which(n == colnames(list.correlation.matrix[[1]])))
list.correlation.matrix <- lapply(list.correlation.matrix, function(corr) {
return(corr[name ,name])
})
if (length(list.correlation.matrix) != 1) {
if (nrow(region.boundaries) == 1) {
region.col.names <- colnames(region.boundaries)
region.row.names <- rownames(region.boundaries)
region.boundaries <- region.boundaries[,index.name]
region.boundaries <- matrix(region.boundaries, nrow = 1)
colnames(region.boundaries) <- region.col.names
rownames(region.boundaries) <- region.row.names
} else {
region.boundaries <- region.boundaries[,index.name]
}
}
u <- data.table::data.table(MASS::mvrnorm(n = n,
mu = rep(0, length(name)),
Sigma = list.correlation.matrix$base))
names(u) <- colnames(list.correlation.matrix[[1]])
u[,names(u) :=lapply(.SD, function(x) stats::pnorm(x))]
if (length(list.correlation.matrix) != 1) {
normalized.probability <- scenario.probability / region.probability
scenario.indicator <- u[, eval(parse(text = paste("list(as.numeric(",
paste(sapply(1:nrow(region.boundaries),
function(i) {
paste(colnames(region.boundaries),
region.boundaries[i,],
sep = " <= ",
collapse = " & ")
}),
collapse = "), as.numeric( "),
"))",
sep = "")), envir = .SD)]
names(scenario.indicator) <- rownames(region.boundaries)
names.regions <- rownames(region.boundaries)
scenario.indicator[, eval(parse(text = paste("ind := ",
paste(names.regions,
2^{0:(nrow(region.boundaries)-1)},
sep = "*",
collapse = " + "),
sep = "")), envir = .SD)]
scenario.indicator[, eval(parse(text = paste("c('",
paste("prob_",
names.regions,
sep = "",
collapse = "', '"),
"') := list(",
paste(names.regions,
"*normalized.probability[",
1:nrow(region.boundaries),
"]",
sep="",
collapse = ", " ),
")", sep ="")), envir = .SD)]
scenario.indicator[, eval(parse(text = paste("prob_base := 1-",
paste("prob_",
names.regions,
sep = "",
collapse = "-"),
sep="")))]
scenario.indicator[, eval(parse(text = paste("scenario.indicator[, scenario := sample(0:",
nrow(region.boundaries),
", size = .N, replace = T, prob = c(",
paste("prob_",
c("base", names.regions),
"[1]",
sep ="",
collapse = ", "),
")), by = 'ind']",
sep = "")))]
u[, scenario := scenario.indicator[,'scenario']]
rm(scenario.indicator)
gc()
u[, eval(parse(text = paste("u[,c('",
paste("c_",
colnames(region.boundaries),
sep = "",
collapse = "', '"),
paste("') := lapply(as.list(data.frame(matrix(MASS::mvrnorm(n = .N, mu = ",
"rep(0,ncol(region.boundaries)), Sigma = list.correlation.matrix[[scenario[1] + 1]]), ",
"ncol = ncol(region.boundaries)))), data.table::frank), by='scenario']",
sep = ""),
sep = "")), envir = .SD)]
u[,eval(parse(text = paste("u[,c('",
paste("ranks_",
colnames(region.boundaries),
sep = "",
collapse = "', '"),
"')",
paste(" := if (scenario[1] == 0) {list(",
paste(colnames(region.boundaries),
collapse = ", "),
")} else { list(sort(",
paste(colnames(region.boundaries),
")[c_",
colnames(region.boundaries),
"]",
collapse = ", sort(",
sep =""),
")}, by = 'scenario']",
sep = ""),
sep = "")), envir = .SD)]
} else if (length(list.correlation.matrix) == 1) {
names(u) <- paste("ranks_", names(u), sep = "")
}
if (!keep.realized.scenario) {
return(u[, eval(parse(text = paste("c('",
paste("ranks_",
colnames(list.correlation.matrix[[1]]),
sep = "",
collapse = "', '"),
"')",
sep ="")), envir = .SD), with = F])
} else {
return(u[, eval(parse(text = paste("c('",
paste("ranks_",
colnames(list.correlation.matrix[[1]]),
sep = "",
collapse = "', '"),
"', 'scenario",
"')",
sep ="")), envir = .SD), with = F])
}
}
|
ts.diag <- function(x, lag = 10, band = qnorm(0.975) / sqrt(length(x))) {
Z <- (x - mean(x, na.rm = TRUE)) / sd(x, na.rm = TRUE)
x_acf <- acf(x, plot = FALSE, lag.max = lag, na.action = na.pass)
x_acf <- with(x_acf, data.frame(lag, acf))
g1 <- ggplot() +
geom_col(data = data.frame(x = as.numeric(time(Z)), y = as.numeric(Z)), aes(x = x, y = y)) +
geom_hline(yintercept = 0, linetype = "solid", color = "blue") +
geom_hline(yintercept = c(-2, 2), linetype = "dashed", color = "blue") +
geom_hline(yintercept = c(-3, 3), linetype = "dotted", color = "blue") +
labs(x = "time(Z)", y = "Z", title = "Standardized Residuals") +
theme_minimal()
g2 <- ggplot(data = x_acf, mapping = aes(x = lag, y = acf)) +
geom_segment(mapping = aes(xend = lag, yend = 0)) +
geom_hline(yintercept = 0, linetype = "solid", color = "blue") +
geom_hline(yintercept = c(-1 * band, band), linetype = "dashed", color = "blue") +
scale_x_continuous(limits = c(0, lag), breaks = 0:lag) +
labs(x = "Lag", y = "ACF", title = "ACF of Residuals") +
theme_minimal()
g3 <- Box.Ljung.Test(x, lag = lag)
g <- g1 + g2 + g3 + plot_layout(nrow = 3, byrow = FALSE)
return(g)
}
|
sessionInfo()
install.packages(c("tidyverse", "lme4", "nlme", "manipulate", "rstanarm",
"simr", "TMB", "gapminder", "aods3", "emdbook", "AER", "arm", "rmarkdown",
"ggeffects", "sjPlot", "bbmle", "MuMIn", "broom", "broom.mixed", "glmmTMB"),
dependencies = TRUE)
|
as.objlist <- function(p) {
objlist(value = 0,
gradient = structure(rep(0, length(p)), names = names(p)),
hessian = matrix(0, length(p), length(p), dimnames = list(names(p), names(p))))
}
constraintExp2 <- function(p, mu, sigma = 1, k = 0.05, fixed=NULL) {
kmin <- 1e-5
if(length(sigma) == 1)
sigma <- structure(rep(sigma, length(mu)), names = names(mu))
if(length(k) == 1)
k <- structure(rep(k, length(mu)), names = names(mu))
k <- sapply(k, function(ki){
if(ki < kmin){
kmin
} else ki
})
par.fixed <- intersect(names(mu), names(fixed))
sumOfFixed <- 0
if(!is.null(par.fixed)) sumOfFixed <- sum(0.5*(exp(k[par.fixed]*((fixed[par.fixed] - mu[par.fixed])/sigma[par.fixed])^2)-1)/(exp(k[par.fixed])-1))
par <- intersect(names(mu), names(p))
t <- p[par]
mu <- mu[par]
s <- sigma[par]
k <- k[par]
gr <- rep(0, length(t)); names(gr) <- names(t)
hs <- matrix(0, length(t), length(t), dimnames = list(names(t), names(t)))
val <- sum(0.5*(exp(k*((t-mu)/s)^2)-1)/(exp(k)-1)) + sumOfFixed
gr <- (k*(t-mu)/(s^2)*exp(k*((t-mu)/s)^2)/(exp(k)-1))
diag(hs)[par] <- k/(s*s)*exp(k*((t-mu)/s)^2)/(exp(k)-1)*(1+2*k*(t-mu)/(s^2))
dP <- attr(p, "deriv")
if(!is.null(dP)) {
gr <- as.vector(gr%*%dP); names(gr) <- colnames(dP)
hs <- t(dP)%*%hs%*%dP; colnames(hs) <- colnames(dP); rownames(hs) <- colnames(dP)
}
objlist(value=val,gradient=gr,hessian=hs)
}
normL2 <- function(data, x, errmodel = NULL, times = NULL, attr.name = "data") {
timesD <- sort(unique(c(0, do.call(c, lapply(data, function(d) d$time)))))
if (!is.null(times)) timesD <- sort(union(times, timesD))
x.conditions <- names(attr(x, "mappings"))
data.conditions <- names(data)
if (!all(data.conditions %in% x.conditions))
stop("The prediction function does not provide predictions for all conditions in the data.")
e.conditions <- names(attr(errmodel, "mappings"))
controls <- list(times = timesD, attr.name = attr.name, conditions = x.conditions)
force(errmodel)
myfn <- function(..., fixed = NULL, deriv=TRUE, conditions = controls$conditions, env = NULL) {
arglist <- list(...)
arglist <- arglist[match.fnargs(arglist, "pars")]
pouter <- arglist[[1]]
pars_out <- colnames(getDerivs(as.parvec(pouter)))
template <- objlist(
value = 0,
gradient = structure(rep(0, length(pars_out)), names = pars_out),
hessian = matrix(0, nrow = length(pars_out), ncol = length(pars_out), dimnames = list(pars_out, pars_out))
)
timesD <- controls$times
attr.name <- controls$attr.name
if (is.null(env)) env <- new.env()
prediction <- x(times = timesD, pars = pouter, fixed = fixed, deriv = deriv, conditions = conditions)
out.data <- lapply(conditions, function(cn) {
err <- NULL
if ((!is.null(errmodel) & is.null(e.conditions)) | (!is.null(e.conditions) && (cn %in% e.conditions))) {
err <- errmodel(out = prediction[[cn]], pars = getParameters(prediction[[cn]]), conditions = cn)
mywrss <- nll(res(data[[cn]], prediction[[cn]], err[[cn]]))
} else {
mywrss <- wrss(res(data[[cn]], prediction[[cn]]))
}
available <- intersect(pars_out, names(mywrss$gradient))
result <- template
result$value <- mywrss$value
if (deriv) {
result$gradient[available] <- mywrss$gradient[available]
result$hessian[available, available] <- mywrss$hessian[available, available]
} else {
result$gradient <- result$hessian <- NULL
}
return(result)
})
out.data <- Reduce("+", out.data)
out <- out.data
attr(out, controls$attr.name) <- out.data$value
if (!is.null(env)) {
assign("prediction", prediction, envir = env)
}
attr(out, "env") <- env
return(out)
}
class(myfn) <- c("objfn", "fn")
attr(myfn, "conditions") <- data.conditions
attr(myfn, "parameters") <- attr(x, "parameters")
attr(myfn, "modelname") <- modelname(x, errmodel)
return(myfn)
}
constraintL2 <- function(mu, sigma = 1, attr.name = "prior", condition = NULL) {
estimateSigma <- ifelse(is.character(sigma), TRUE, FALSE)
if (length(sigma) > 1 & length(sigma) < length(mu))
stop("sigma must either have length 1 or at least length equal to length of mu.")
if (length(sigma) == 1)
sigma <- structure(rep(sigma, length(mu)), names = names(mu))
if (is.null(names(sigma)))
names(sigma) <- names(mu)
if (!is.null(names(sigma)) & !all(names(mu) %in% names(sigma)))
stop("Names of sigma and names of mu do not match.")
sigma <- sigma[names(mu)]
controls <- list(mu = mu, sigma = sigma, attr.name = attr.name)
myfn <- function(..., fixed = NULL, deriv = TRUE, conditions = condition, env = NULL) {
arglist <- list(...)
arglist <- arglist[match.fnargs(arglist, "pars")]
pouter <- arglist[[1]]
mu <- controls$mu
sigma <- controls$sigma
attr.name <- controls$attr.name
nmu <- length(mu)
if (is.list(pouter) && !is.null(conditions)) {
available <- intersect(names(pouter), conditions)
defined <- ifelse(is.null(condition), TRUE, condition %in% conditions)
if (length(available) == 0 | !defined) return()
pouter <- pouter[intersect(available, condition)]
}
if (!is.list(pouter)) pouter <- list(pouter)
outlist <- lapply(pouter, function(p) {
pars <- c(p, fixed)[names(mu)]
p1 <- setdiff(intersect(names(mu), names(p)), names(fixed))
if (estimateSigma) {
sigmapars <- sigma
sigma <- exp(c(p, fixed)[sigma])
names(sigma) <- names(mu)
Jsigma <- do.call(cbind, lapply(unique(sigmapars), function(s) {
(sigmapars == s)*sigma
}))
colnames(Jsigma) <- unique(sigmapars)
rownames(Jsigma) <- names(sigma)
p2 <- setdiff(intersect(unique(sigmapars), names(p)), names(fixed))
}
val <- sum((pars - mu)^2/sigma^2) + estimateSigma * sum(log(sigma^2))
val.p <- 2*(pars - mu)/sigma^2
val.sigma <- -2*(pars-mu)^2/sigma^3 + 2/sigma
val.p.p <- diag(2/sigma^2, nmu, nmu); colnames(val.p.p) <- rownames(val.p.p) <- names(mu)
val.p.sigma <- diag(-4*(pars-mu)/sigma^3, nmu, nmu); colnames(val.p.sigma) <- rownames(val.p.sigma) <- names(mu)
val.sigma.sigma <- diag(6*(pars-mu)^2/sigma^4 - 2/sigma^2, nmu, nmu); colnames(val.sigma.sigma) <- rownames(val.sigma.sigma) <- names(mu)
if (estimateSigma) {
val.sigma.sigma <- t(Jsigma) %*% val.sigma.sigma %*% Jsigma + diag((t(val.sigma) %*% Jsigma)[1,], ncol(Jsigma), ncol(Jsigma))
val.sigma <- (val.sigma %*% Jsigma)[1,]
val.p.sigma <- (val.p.sigma %*% Jsigma)
}
gr <- hs <- NULL
if (deriv) {
gr <- rep(0, length(p)); names(gr) <- names(p)
hs <- matrix(0, length(p), length(p), dimnames = list(names(p), names(p)))
gr[p1] <- val.p[p1]
hs[p1, p1] <- val.p.p[p1, p1]
if (estimateSigma) {
gr[p2] <- val.sigma[p2]
hs[p1, p2] <- val.p.sigma[p1, p2]
hs[p2, p1] <- t(val.p.sigma)[p2, p1]
hs[p2, p2] <- val.sigma.sigma[p2, p2]
}
dP <- attr(p, "deriv")
if (!is.null(dP)) {
gr <- as.vector(gr %*% dP); names(gr) <- colnames(dP)
hs <- t(dP) %*% hs %*% dP; colnames(hs) <- colnames(dP); rownames(hs) <- colnames(dP)
}
}
objlist(value = val, gradient = gr, hessian = hs)
})
out <- Reduce("+", outlist)
attr(out, controls$attr.name) <- out$value
attr(out, "env") <- env
return(out)
}
class(myfn) <- c("objfn", "fn")
attr(myfn, "conditions") <- condition
attr(myfn, "parameters") <- names(mu)
return(myfn)
}
datapointL2 <- function(name, time, value, sigma = 1, attr.name = "validation", condition) {
controls <- list(
mu = structure(name, names = value)[1],
time = time[1],
sigma = sigma[1],
attr.name = attr.name
)
myfn <- function(..., fixed = NULL, deriv=TRUE, conditions = NULL, env = NULL) {
mu <- controls$mu
time <- controls$time
sigma <- controls$sigma
attr.name <- controls$attr.name
arglist <- list(...)
arglist <- arglist[match.fnargs(arglist, "pars")]
pouter <- arglist[[1]]
if (!is.null(env)) {
prediction <- as.list(env)$prediction
} else {
stop("No prediction available. Use the argument env to pass an environment that contains the prediction.")
}
if (!is.null(conditions) && !condition %in% conditions)
return()
if (is.null(conditions) && !condition %in% names(prediction))
stop("datapointL2 requests unavailable condition. Call the objective function explicitly stating the conditions argument.")
datapar <- setdiff(names(mu), names(fixed))
parapar <- setdiff(names(pouter), c(datapar, names(fixed)))
time.index <- which(prediction[[condition]][,"time"] == time)
if (length(time.index) == 0)
stop("datapointL2() requests time point for which no prediction is available. Please add missing time point by the times argument in normL2()")
withDeriv <- !is.null(attr(prediction[[condition]], "deriv"))
pred <- prediction[[condition]][time.index, ]
deriv <- NULL
if (withDeriv)
deriv <- attr(prediction[[condition]], "deriv")[time.index, ]
pred <- pred[mu]
if (withDeriv) {
mu.para <- intersect(paste(mu, parapar, sep = "."), names(deriv))
deriv <- deriv[mu.para]
}
res <- as.numeric(pred - c(fixed, pouter)[names(mu)])
val <- as.numeric((res/sigma) ^ 2)
gr <- NULL
hs <- NULL
if (withDeriv) {
dres.dp <- structure(rep(0, length(pouter)), names = names(pouter))
if (length(parapar) > 0) dres.dp[parapar] <- as.numeric(deriv)
if (length(datapar) > 0) dres.dp[datapar] <- -1
gr <- 2*res*dres.dp/sigma ^ 2
hs <- 2*outer(dres.dp, dres.dp, "*")/sigma ^ 2; colnames(hs) <- rownames(hs) <- names(pouter)
}
out <- objlist(value = val, gradient = gr, hessian = hs)
attr(out, controls$attr.name) <- out$value
attr(out, "prediction") <- pred
attr(out, "env") <- env
return(out)
}
class(myfn) <- c("objfn", "fn")
attr(myfn, "conditions") <- condition
attr(myfn, "parameters") <- value[1]
return(myfn)
}
priorL2 <- function(mu, lambda = "lambda", attr.name = "prior", condition = NULL) {
controls <- list(mu = mu, lambda = lambda, attr.name = attr.name)
myfn <- function(..., fixed = NULL, deriv=TRUE, conditions = condition, env = NULL) {
arglist <- list(...)
arglist <- arglist[match.fnargs(arglist, "pars")]
pouter <- arglist[[1]]
mu <- controls$mu
lambda <- controls$lambda
attr.name <- controls$attr.name
if (is.list(pouter) && !is.null(conditions)) {
available <- intersect(names(pouter), conditions)
defined <- ifelse(is.null(condition), TRUE, condition %in% conditions)
if (length(available) == 0 | !defined) return()
pouter <- pouter[intersect(available, condition)]
}
if (!is.list(pouter)) pouter <- list(pouter)
outlist <- lapply(pouter, function(p) {
par.fixed <- intersect(names(mu), names(fixed))
sumOfFixed <- 0
if (!is.null(par.fixed)) sumOfFixed <- sum(exp(c(fixed, p)[lambda])*(fixed[par.fixed] - mu[par.fixed]) ^ 2)
par <- intersect(names(mu), names(p))
par0 <- setdiff(par, lambda)
val <- sum(exp(c(fixed, p)[lambda]) * (p[par] - mu[par]) ^ 2) + sumOfFixed
gr <- hs <- NULL
if (deriv) {
gr <- rep(0, length(p)); names(gr) <- names(p)
gr[par] <- 2*exp(c(fixed, p)[lambda])*(p[par] - mu[par])
if (lambda %in% names(p)) {
gr[lambda] <- sum(exp(c(fixed, p)[lambda]) * (p[par0] - mu[par0]) ^ 2) +
sum(exp(c(fixed, p)[lambda]) * (fixed[par.fixed] - mu[par.fixed]) ^ 2)
}
hs <- matrix(0, length(p), length(p), dimnames = list(names(p), names(p)))
diag(hs)[par] <- 2*exp(c(fixed, p)[lambda])
if (lambda %in% names(p)) {
hs[lambda, lambda] <- gr[lambda]
hs[lambda, par0] <- hs[par0, lambda] <- gr[par0]
}
dP <- attr(p, "deriv")
if (!is.null(dP)) {
gr <- as.vector(gr %*% dP); names(gr) <- colnames(dP)
hs <- t(dP) %*% hs %*% dP; colnames(hs) <- colnames(dP); rownames(hs) <- colnames(dP)
}
}
objlist(value = val, gradient = gr, hessian = hs)
})
out <- Reduce("+", outlist)
attr(out, controls$attr.name) <- out$value
attr(out, "env") <- env
return(out)
}
class(myfn) <- c("objfn", "fn")
attr(myfn, "conditions") <- condition
attr(myfn, "parameters") <- names(mu)
return(myfn)
}
wrss <- function(nout) {
is.bloq <- nout$bloq
nout.bloq <- nout[is.bloq, , drop = FALSE]
nout <- nout[!is.bloq, , drop = FALSE]
obj <- sum(nout$weighted.residual^2)
grad <- NULL
hessian <- NULL
derivs <- attr(nout, "deriv")
if (!is.null(derivs)) {
derivs.bloq <- derivs[is.bloq, , drop = FALSE]
derivs <- derivs[!is.bloq, , drop = FALSE]
if (nrow(derivs) > 0) {
nout$sigma[is.na(nout$sigma)] <- 1
sens <- as.matrix(derivs[, -(1:2), drop = FALSE])
res <- nout$residual
sigma <- nout$sigma
grad <- as.vector(2*matrix(res/sigma^2, nrow = 1) %*% sens)
names(grad) <- colnames(sens)
hessian <- 2*t(sens/sigma) %*% (sens/sigma)
}
if (nrow(derivs.bloq) > 0) {
objvals.bloq <- -2*pnorm(-nout.bloq$weighted.residual, log.p = TRUE)
obj.bloq <- sum(objvals.bloq)
nout.bloq[is.na(nout.bloq$sigma)] <- 1
sens.bloq <- as.matrix(derivs.bloq[, -(1:2), drop = FALSE])
res <- nout.bloq$residual
sigma <- nout.bloq$sigma
LPhi <- pnorm(-nout.bloq$weighted.residual, log.p = TRUE)
LG <- dnorm(-nout.bloq$weighted.residual, log = TRUE)
G_divided_by_Phi <- exp(LG-LPhi)
grad.bloq <- as.vector(matrix(2 * G_divided_by_Phi/(sigma), nrow = 1) %*% sens.bloq)
names(grad.bloq) <- colnames(sens.bloq)
X1 <- sens.bloq*(G_divided_by_Phi/(sigma))^2
X2 <- sens.bloq*(res*G_divided_by_Phi/(sigma^3))
hessian.bloq <- 2 * t(X1) %*% sens.bloq - 2 * t(X2) %*% sens.bloq
obj <- obj + obj.bloq
if (is.null(grad) & is.null(hessian)) {
grad <- grad.bloq
hessian <- hessian.bloq
} else {
grad <- grad + grad.bloq
hessian <- hessian + hessian.bloq
}
}
}
objlist(value = obj, gradient = grad, hessian = hessian)
}
nll <- function(nout) {
is.bloq <- nout$bloq
nout.bloq <- nout[is.bloq, , drop = FALSE]
nout <- nout[!is.bloq, , drop = FALSE]
obj <- sum(nout$weighted.residual^2) + sum(log(2*pi*nout$sigma^2))
grad <- NULL
hessian <- NULL
derivs <- attr(nout, "deriv")
derivs.err <- attr(nout, "deriv.err")
if (!is.null(derivs) & !is.null(derivs.err)) {
derivs.bloq <- derivs[is.bloq, , drop = FALSE]
derivs.err.bloq <- derivs.err[is.bloq, , drop = FALSE]
derivs <- derivs[!is.bloq, , drop = FALSE]
derivs.err <- derivs.err[!is.bloq, , drop = FALSE]
if (nrow(derivs) > 0 & nrow(derivs.err) > 0) {
sens <- as.matrix(derivs[, -(1:2), drop = FALSE])
sens.err <- as.matrix(derivs.err[, -(1:2), drop = FALSE])
res <- nout$residual
sigma <- nout$sigma
grad <- as.vector(2*matrix(res/sigma^2, nrow = 1) %*% sens -
2*matrix(res^2/sigma^3, nrow = 1) %*% sens.err +
2*matrix(1/sigma, nrow = 1) %*% sens.err)
names(grad) <- colnames(sens)
X1 <- (1/sigma)*sens - (res/sigma^2)*sens.err
X2 <- (res/sigma^2)*sens.err
X3 <- (1/sigma)*sens.err
hessian <- 2 * t(X1) %*% X1
}
if (nrow(derivs.bloq) > 0 & nrow(derivs.err.bloq) > 0) {
objvals.bloq <- -2*pnorm(-nout.bloq$weighted.residual, log.p = TRUE)
obj.bloq <- sum(objvals.bloq)
sens.bloq <- as.matrix(derivs.bloq[, -(1:2), drop = FALSE])
sens.err.bloq <- as.matrix(derivs.err.bloq[, -(1:2), drop = FALSE])
res <- nout.bloq$residual
sigma <- nout.bloq$sigma
LPhi <- pnorm(-nout.bloq$weighted.residual, log.p = TRUE)
LG <- dnorm(-nout.bloq$weighted.residual, log = TRUE)
G_divided_by_Phi <- exp(LG-LPhi)
grad.bloq <- as.vector(matrix(2*G_divided_by_Phi/sigma, nrow = 1) %*% sens.bloq) -
as.vector(matrix(2*G_divided_by_Phi*res/(sigma^2), nrow = 1) %*% sens.err.bloq)
names(grad.bloq) <- colnames(sens.bloq)
X <- -(1/sigma)*sens.bloq + (res/sigma^2)*sens.err.bloq
X1 <- (2*G_divided_by_Phi^2)*X
X2 <- (2*G_divided_by_Phi*res/(sigma))*X
hessian.bloq <- t(X1) %*% X - t(X2) %*% X
obj <- obj + obj.bloq
if (is.null(grad) & is.null(hessian)) {
grad <- grad.bloq
hessian <- hessian.bloq
} else {
grad <- grad + grad.bloq
hessian <- hessian + hessian.bloq
}
}
}
objlist(value = obj, gradient = grad, hessian = hessian)
}
"+.objlist" <- function(out1, out2) {
if (is.null(out1)) return(out2)
if (is.null(out2)) return(out1)
allnames <- c(names(out1), names(out2))
what <- allnames[duplicated(allnames)]
what.names <- what
if (is.null(what)) {
what <- 1:min(c(length(out1), length(out2)))
what.names <- NULL
}
out12 <- lapply(what, function(w) {
sub1 <- out1[[w]]
sub2 <- out2[[w]]
n <- names(sub1)
dn <- dimnames(sub1)
if (!is.null(n) && !is.null(sub1) %% !is.null(sub2)) {
sub1[n] + sub2[n]
} else if (!is.null(dn) && !is.null(sub1) && !is.null(sub2)) {
matrix(sub1[dn[[1]], dn[[2]]] + sub2[dn[[1]], dn[[2]]],
length(dn[[1]]), length(dn[[2]]), dimnames = list(dn[[1]], dn[[2]]))
} else if (!is.null(sub1) && !is.null(sub2)) {
sub1 + sub2
} else {
NULL
}
})
names(out12) <- what.names
out1.attributes <- attributes(out1)[sapply(attributes(out1), is.numeric)]
out2.attributes <- attributes(out2)[sapply(attributes(out2), is.numeric)]
attr.names <- union(names(out1.attributes), names(out2.attributes))
out12.attributes <- lapply(attr.names, function(n) {
x1 <- ifelse(is.null(out1.attributes[[n]]), 0, out1.attributes[[n]])
x2 <- ifelse(is.null(out2.attributes[[n]]), 0, out2.attributes[[n]])
x1 + x2
})
attributes(out12)[attr.names] <- out12.attributes
class(out12) <- "objlist"
return(out12)
}
print.objfn <- function(x, ...) {
parameters <- attr(x, "parameters")
cat("Objective function:\n")
str(args(x))
cat("\n")
cat("... parameters:", paste0(parameters, collapse = ", "), "\n")
}
|
local_disable_cache()
test_that("nesting works", {
expected <- read_utf8("test-nesting-expected.css")
class(expected) <- c("css", "html", "character")
attr(expected, "html") <- TRUE
css <- sass(sass_file("test-nesting-input.scss"))
expect_equal(css, expected)
})
|
context ("Scenario of un wanted inputs")
test_that("NA values are avoided",{
expect_that(NegLLCOMPBin(NA,4,0.1,.3),
throws_error("NA or Infinite or NAN values in the Input"))
})
test_that("Infinite values are avoided",{
expect_that(NegLLCOMPBin(Inf,4,0.1,.3),
throws_error("NA or Infinite or NAN values in the Input"))
})
test_that("NAN values are avoided",{
expect_that(NegLLCOMPBin(NaN,4,0.1,.3),
throws_error("NA or Infinite or NAN values in the Input"))
})
context("Binomial Random variable or frequency issues")
test_that("Negativity Binomial random variable",{
expect_that(NegLLCOMPBin(-3,4,0.2,0.4),
throws_error("Binomial random variable or frequency values cannot be negative"))
})
test_that("Negativity frequency values",{
expect_that(NegLLCOMPBin(-13,4,0.2,0.4),
throws_error("Binomial random variable or frequency values cannot be negative"))
})
context("Probability value issues")
test_that("Probability issues",{
expect_that(NegLLCOMPBin(3,5,3,0.4),
throws_error("Probability value doesnot satisfy conditions"))
})
test_that("Probability issues",{
expect_that(NegLLCOMPBin(3,5,-3,0.4),
throws_error("Probability value doesnot satisfy conditions"))
})
context("Checking outputs")
test_that("Output value expected",{
expect_identical(round(NegLLCOMPBin(Chromosome_data$No.of.Asso,Chromosome_data$fre,0.7,1),4),
472.6649)
})
test_that("Checking class of output",{
expect_that(NegLLCOMPBin(Chromosome_data$No.of.Asso,Chromosome_data$fre,0.7,1),
is_a("numeric"))
})
|
okcurobs <- function(SI=TRUE, localtime=TRUE) {
path <- paste("http://www.mesonet.org/data/public/mesonet/current/",
"current.csv.txt", sep="")
curobs <- read.csv(file=path,
colClasses=c("character", "character", "character",
"numeric", "numeric", "integer", "integer",
"integer", "integer", "integer",
"integer", "integer", "integer", "integer",
"integer", "character", "integer", "integer",
"numeric", "integer", "integer", "numeric"))
time.stitched <- paste(curobs$YR, sprintf("%02d", curobs$MO),
sprintf("%02d", curobs$DA),
sprintf("%02d", curobs$HR),
sprintf("%02d", curobs$MI), "-0600", sep="")
curobs$TIME <- as.POSIXct(time.stitched, format="%Y%m%d%H%M%z")
if (localtime==TRUE) {
curobs$TIME <- as.POSIXct(format(curobs$TIME, tz="America/Chicago"),
tz="America/Chicago")
} else {
curobs$TIME <- as.POSIXct(format(curobs$TIME, tz="GMT"), tz="GMT")
}
if(SI==T) {
curobs$TAIR <- round((5/9) * (curobs$TAIR - 32), 1)
curobs$TDEW <- round((5/9) * (curobs$TDEW - 32), 1)
curobs$CHIL <- round((5/9) * (curobs$CHIL - 32), 1)
curobs$HEAT <- round((5/9) * (curobs$HEAT - 32), 1)
curobs$TMAX <- round((5/9) * (curobs$TMAX - 32), 1)
curobs$TMIN <- round((5/9) * (curobs$TMIN - 32), 1)
curobs$WSPD <- round(curobs$WSPD * 0.44704, 1)
curobs$WMAX <- round(curobs$WMAX * 0.44704, 1)
curobs$RAIN <- round(curobs$RAIN * 25.4, 1)
}
return(curobs)
}
|
to_hv_list <- function(path) {
hvs = new("HypervolumeList")
hvs@HVList = foreach(file = list.files(path), .combine = c) %do% {
readRDS(file.path(path, file))
}
return(hvs)
}
|
postscript("normals.eps", paper = "letter", horizontal = FALSE)
xVals <- seq(-5, 5, length = 1000)
plot(xVals, dnorm(xVals), type = "l", lwd = 2)
lines(xVals, dnorm(xVals, sd = 1.5), lwd = 2, lty = 2)
lines(xVals, dnorm(xVals, sd = 2), lwd = 2, lty = 3)
lines(xVals, dnorm(xVals, sd = 2.5), lwd = 2, lty = 4)
legend(-4, .4, c("1", "1.5", "2", "2.5"), lty = 1 : 4, lwd = 2)
dev.off()
|
ggplot_waterfall <- function(dtData,
cXColumnName,
cYColumnName,
nArrowSize = 0.25,
vcGroupingColumnNames = NULL) {
NextY <- ""
tail <- ""
Change <- ""
dtData <- copy(data.table(dtData))
dtData[
,
NextY := c(tail(get(cYColumnName), -1), NA),
unique(vcGroupingColumnNames)
]
dtData[, Change := "+"]
dtData[NextY > get(cYColumnName), Change := "-"]
dtData[NextY == get(cYColumnName), Change := ""]
ggplotWaterfall <- ggplot() +
geom_segment(
data = dtData[get(cYColumnName) != NextY],
aes_string(
x = cXColumnName,
y = cYColumnName,
xend = cXColumnName,
yend = "NextY",
color = "Change"
),
arrow = arrow(length = unit(nArrowSize, "cm"))
) +
geom_point(
data = dtData[get(cYColumnName) == NextY],
aes_string(
x = cXColumnName,
y = cYColumnName,
color = "Change"
)
) +
scale_color_manual(
breaks = c("+", "-", ""),
values = c("green", "red", "black")
)
ggplotWaterfall
}
|
ISOImageryMetadata <- R6Class("ISOImageryMetadata",
inherit = ISOMetadata,
private = list(
document = TRUE,
xmlElement = "MI_Metadata",
xmlNamespacePrefix = "GMI"
),
public = list(
acquisitionInformation = list(),
initialize = function(xml = NULL){
super$initialize(xml = xml)
},
addAcquisitionInfo = function(acquisitionInfo){
if(!is(acquisitionInfo, "ISOImageryAcquisitionInformation")){
stop("The argument should be an object of class 'ISOImageryAcquisitionInformation")
}
return(self$addListElement("acquisitionInformation", acquisitionInfo))
},
delAcquisitionInfo = function(acquisitionInfo){
if(!is(acquisitionInfo, "ISOImageryAcquisitionInformation")){
stop("The argument should be an object of class 'ISOImageryAcquisitionInformation")
}
return(self$delListElement("acquisitionInformation", acquisitionInfo))
}
)
)
|
library(vcfR)
context("summary_tables functions")
test_that("write.var.info works",{
data("chromR_example")
setwd(tempdir())
write.var.info(chrom, file = "test_var_info.csv")
expect_true(file.exists("test_var_info.csv"))
unlink("test_var_info.csv")
})
test_that("write.var.info works, mask == TRUE",{
data("chromR_example")
setwd(tempdir())
write.var.info(chrom, file = "test_var_info.csv", mask = TRUE)
expect_true(file.exists("test_var_info.csv"))
unlink("test_var_info.csv")
})
test_that("write.win.info works",{
data("chromR_example")
myChrom <- proc.chromR(chrom, verbose = FALSE)
setwd(tempdir())
write.win.info(myChrom, file = "test_win_info.csv")
expect_true(file.exists("test_win_info.csv"))
unlink("test_win_info.csv")
})
|
model2grfun <- function(modelformula, pvec, funname = "mygr",
filename = NULL) {
pnames <- names(pvec)
if (is.null(pnames))
stop("MUST have named parameters in pvec")
if (is.character(modelformula)) {
es <- modelformula
} else {
tstr <- as.character(modelformula)
es <- paste(tstr[[2]], "~", tstr[[3]], "")
}
xx <- all.vars(parse(text = es))
rp <- match(pnames, xx)
xx2 <- c(xx[rp], xx[-rp])
xxparm <- xx[rp]
pstr <- "c("
npar <- length(xxparm)
if (npar > 0) {
for (i in 1:npar) {
pstr <- paste(pstr, "\"", xxparm[i], "\"", sep = "")
if (i < npar)
pstr <- paste(pstr, ", ", sep = "")
}
}
pstr <- paste(pstr, ")", sep = "")
xxvars <- xx[-rp]
nvar <- length(xxvars)
vstr <- ""
if (nvar > 0) {
for (i in 1:nvar) {
vstr <- paste(vstr, xxvars[i], " = NULL", sep = "")
if (i < nvar)
vstr <- paste(vstr, ", ", sep = "")
}
}
ff <- vector("list", length(xx2))
names(ff) <- xx2
parts <- strsplit(as.character(es), "~")[[1]]
if (length(parts) != 2)
stop("Model expression is incorrect!")
lhs <- parts[1]
rhs <- parts[2]
resexp <- paste(rhs, "-", lhs, collapse = " ")
resval <- paste("resids<-as.numeric(eval(", resexp, "))",
sep = "")
resexp <- paste(rhs, "-", lhs, collapse = " ")
jacexp <- deriv(parse(text = resexp), pnames)
dvstr <- ""
if (nvar > 0) {
for (i in 1:nvar) {
dvstr <- paste(dvstr, xxvars[i], sep = "")
if (i < nvar)
dvstr <- paste(dvstr, ", ", sep = "")
}
}
jfstr <- paste("localdf<-data.frame(", dvstr, ");\n", sep = "")
jfstr <- paste(jfstr, "jstruc<-with(localdf,eval(", jacexp,
"))", sep = "")
pparse <- ""
for (i in 1:npar) {
pparse <- paste(pparse, " ", pnames[[i]], "<-prm[[",
i, "]]\n", sep = "")
}
mygstr <- paste(funname, "<-function(prm, ", vstr, ") {\n",
pparse, "\n ", jfstr, " \n", "jacmat<-attr(jstruc,'gradient')\n ",
resval, "\n", "grj<-as.vector(2.0*crossprod(jacmat, resids)) \n",
"}", sep = "")
if (!is.null(filename))
write(mygstr, file = filename)
tparse <- try(parse(text = mygstr))
if (class(tparse) == "try-error")
stop("Error in residual code string")
eval(tparse)
}
|
backval <- function(y, t, w, Tn, minT = 5, nptperyear, ...){
getBack <- function(y, index){
yi <- y[index]
n <- length(yi)
i_end <- ifelse(n <= 5, n, 5)
return( median(sort(yi)[1:i_end]) )
}
n <- length(y)
i_lowT <- (Tn < minT)
n_lowT <- length(which(i_lowT))
i_good <- w >= 1
i_margin <- w >= 0.5
if (n_lowT == 0){
back <- getBack(y, i_good)
} else if (n - n_lowT < max(5, nptperyear/12*2)){
month <- month(t)
i_summer <- month %in% c(6, 7, 8)
I <- i_summer & i_good
if (sum(I) < 5) I <- i_summer & i_margin
back <- getBack(y, I)
} else {
i_goodT <- i_good & (!i_lowT)
if (sum(i_goodT) < 5) {
i_marginT <- i_margin & (!i_lowT)
i_goodT <- i_marginT
}
back <- getBack(y, i_goodT)
}
return(back)
}
|
sraMakeObject <-
function (sradata, model, start, fixed, FUNtimeseries)
{
ans <- list()
ans$data <- sradata
ans$model <- model
ans$start <- start
ans$coefficients <- stats4::coef(model)[names(start)]
sumcoef <- stats4::coef(stats4::summary(model))
ans$confint <- cbind(sumcoef[,1]-2*sumcoef[,2], sumcoef[,1]+2*sumcoef[,2])
ans$pred <- list()
ans$residuals <- list()
ans$vresiduals <- list()
for (pop in split(ans$data, ans$data$rep)) {
range <- 1:(nrow(pop) - 1)
cc <- c(list(beta = (pop$sel[range] - pop$mean[range])/(pop$var[range]),
delta = (pop$vsel[range] - pop$var[range])/pop$var[range]))
cc <- c(cc, ans$coefficients, unlist(fixed))
cc$logvarME <- NULL
ts <- do.call(what = FUNtimeseries, args = cc)
r <- pop$rep[1]
ans$pred[[as.character(r)]] <- list()
ans$pred[[as.character(r)]]$Gen <- names(ts$mean)
ans$pred[[as.character(r)]]$phen <- ts$mean
ans$pred[[as.character(r)]]$var <- ts$varP
ans$pred[[as.character(r)]]$varA <- ts$varA
ans$residuals[[as.character(r)]] <- ans$data[ans$data[,
"rep"] == as.character(r), "mean"] - ts$mean
ans$vresiduals[[as.character(r)]] <- ans$data[ans$data[,
"rep"] == as.character(r), "var"] - ts$varP
}
class(ans) <- c("srafit", "list")
return(ans)
}
|
run_ora <- function(
object,
categories,
extra_annotations,
overwrite,
stringent_or_default,
stringent_logfc_threshold,
verbose,
class_signature,
global
) {
if (global == TRUE) {
stop(
paste0(
"Global ORA analyis is not supported anymore.",
" Use 'global == FALSE'"
)
)
}
if (stringent_or_default == "stringent") {
stop(
paste0(
"Stringent ORA analysis is not supported anymore.",
" Use 'stringent_or_default == 'default''"
)
)
}
regulation <- c("UP", "DOWN", "FLAT", "DIFF")
categories_acceptable <- c(
"LRI",
"LIGAND_COMPLEX",
"RECEPTOR_COMPLEX",
"ER_CELLTYPES",
"EMITTER_CELLTYPE",
"RECEIVER_CELLTYPE",
"GO_TERMS",
"KEGG_PWS"
)
if (!all(categories %in% categories_acceptable)) {
stop(
paste0(
"Accepted 'categories' for ORA are ",
paste0(
categories_acceptable,
collapse = ", "
)
)
)
}
if (!is.null(extra_annotations)) {
err_mess <- paste0(
"'extra_annotations' must be a list of data.tables or data.frames ",
"with exactly two columns each"
)
if (!is.list(extra_annotations)) {
stop(err_mess)
} else if (
any(
sapply(
extra_annotations,
function(i) {
!(methods::is(i, "data.table") | methods::is(i, "data.frame")) ||
length(colnames(i)) != 2
}
)
)
) {
stop(err_mess)
} else {
extra_annotations <- lapply(
extra_annotations,
setDT
)
extra_base_categories <- sapply(
extra_annotations,
function(i) colnames(i)[[1]]
)
extra_new_categories <- sapply(
extra_annotations,
function(i) colnames(i)[[2]]
)
if (!all(extra_base_categories %in% categories_acceptable)) {
stop(
paste0(
"Name of the first colum of each table in 'extra_annotations' ",
"must be a standard ORA category."
)
)
} else if (any(extra_new_categories %in% categories_acceptable)) {
stop(
paste0(
"Name of the second colum of each table in 'extra_annotations' ",
"must be different from standard ORA categories."
)
)
} else {
categories <- c(categories, extra_new_categories)
names(extra_annotations) <- extra_new_categories
}
}
}
temp_param <- object@parameters
condition_inputs <- list(
is_cond = temp_param$conditional_analysis,
cond1 = temp_param$seurat_condition_id$cond1_name,
cond2 = temp_param$seurat_condition_id$cond2_name
)
if (class_signature == "scDiffCom") {
temp_by <- NULL
}
if (class_signature == "scDiffComCombined") {
if (global) {
temp_by <- NULL
} else {
temp_by <- "ID"
}
}
if (temp_param$permutation_analysis &
condition_inputs$is_cond) {
logfc_threshold <- temp_param$threshold_logfc
if (stringent_or_default == "default") {
if (!global) {
temp_ora <- object@ora_table
} else {
temp_ora <- object@ora_combined_default
}
categories_old <- names(temp_ora)
if (is.null(categories_old)) {
mes <- paste0(
"Performing over-representation analysis on the categories: ",
paste0(categories, collapse = ", "),
"."
)
if (verbose) message(mes)
categories_to_run <- categories
} else {
if (overwrite) {
mes <- paste0(
"Performing over-representation analysis on the categories: ",
paste0(categories, collapse = ", "),
".\n",
"Erasing all previous ORA results: ",
paste0(categories_old, collapse = ", "),
"."
)
if (verbose) message(mes)
categories_to_run <- categories
} else {
categories_to_run <- setdiff(categories, categories_old)
mes <- paste0(
"Performing over-representation analysis on the categories: ",
paste0(categories_to_run, collapse = ", "),
".\n",
"Keeping previous ORA results: ",
paste0(setdiff(categories_old, categories_to_run), collapse = ", "),
"."
)
if (verbose) message(mes)
}
}
ora_default <- sapply(
categories_to_run,
function(category) {
temp_dt <- object@cci_table_detected
if (!(category %in% categories_acceptable)) {
extra_annotation <- extra_annotations[[category]]
} else {
extra_annotation <- NULL
}
res <- temp_dt[
,
build_ora_dt(
cci_table_detected = .SD,
logfc_threshold = logfc_threshold,
regulation = regulation,
category = category,
extra_annotation = extra_annotation,
species = temp_param$LRI_species,
global = global
),
by = temp_by
]
},
USE.NAMES = TRUE,
simplify = FALSE
)
if (is.null(categories_old)) {
res_ora <- ora_default
} else {
if (overwrite) {
res_ora <- ora_default
} else {
res_ora <- c(temp_ora, ora_default)
}
}
if (global) {
if (class_signature == "scDiffComCombined") {
object@ora_combined_default <- res_ora
} else {
stop(
paste0(
"No ORA global analysis allowed for object",
" of class 'scDiffComCombined'"
)
)
}
} else {
object@ora_table <- res_ora
}
} else if (stringent_or_default == "stringent") {
if (is.null(stringent_logfc_threshold)) {
if (verbose) {
message(
paste0(
"Choose a non-NULL 'stringent_logfc_threshold' to",
" perform stringent over-representation analysis."
)
)
}
} else {
if(stringent_logfc_threshold > logfc_threshold) {
if (!global) {
temp_ora_stringent <- object@ora_stringent
} else {
temp_ora_stringent <- object@ora_combined_stringent
}
categories_old_stringent <- names(temp_ora_stringent)
if (is.null(categories_old_stringent)) {
mes <- paste0(
"Performing stringent over-representation analysis ",
"on the specified categories: ",
paste0(categories, collapse = ", "),
"."
)
if (verbose) message(mes)
categories_stringent_to_run <- categories
} else {
if (overwrite) {
mes <- paste0(
"Performing stringent over-representation analysis ",
"on the specified categories: ",
paste0(categories, collapse = ", "),
".\n",
"Erasing all previous ORA results: ",
paste0(categories_old_stringent, collapse = ", "),
"."
)
if (verbose) message(mes)
categories_stringent_to_run <- categories
} else {
categories_stringent_to_run <- setdiff(
categories,
categories_old_stringent
)
mes <- paste0(
"Performing stringent over-representation analysis ",
"on the specified categories: ",
paste0(categories_stringent_to_run, collapse = ", "),
".\n",
"Keeping previous ORA results: ",
paste0(
setdiff(
categories_old_stringent,
categories_stringent_to_run
),
collapse = ", "
),
"."
)
if (verbose) message(mes)
}
}
ora_stringent <- sapply(
categories_stringent_to_run,
function(category) {
temp_dt <- object@cci_table_detected
if (!(category %in% categories_acceptable)) {
extra_annotation <- extra_annotation[[category]]
} else {
extra_annotation <- NULL
}
res <- temp_dt[
,
build_ora_dt(
cci_table_detected = .SD,
logfc_threshold = stringent_logfc_threshold,
regulation = regulation,
category = category,
extra_annotation = extra_annotation,
species = temp_param$LRI_species,
global = global
),
by = temp_by
]
},
USE.NAMES = TRUE,
simplify = FALSE
)
if (is.null(categories_old_stringent)) {
res_ora_stringent <- ora_stringent
} else {
if (overwrite) {
res_ora_stringent <- ora_stringent
} else {
res_ora_stringent <- c(temp_ora_stringent, ora_stringent)
}
}
if (global == TRUE) {
if (class_signature == "scDiffComCombined") {
object@ora_combined_stringent <- res_ora_stringent
} else {
stop(
paste0(
"No ORA global analysis allowed for object of ",
"class 'scDiffComCombined'"
)
)
}
} else {
object@ora_stringent <- res_ora_stringent
}
} else {
if (verbose) {
message(
paste0(
"The supposedly 'stringent' logfc is actually less ",
"'stringent' than the default parameter. Choose a higher value."
)
)
}
}
}
} else {
stop("Can't recognize parameter 'stringent_or_default")
}
} else {
if (verbose) {
message(
"No over-representation analysis available for the selected parameters."
)
}
}
return(object)
}
build_ora_dt <- function(
cci_table_detected,
logfc_threshold,
regulation,
category,
extra_annotation,
species,
global
) {
ER_CELLTYPES <- LIGAND_COMPLEX <-
RECEPTOR_COMPLEX <- ID <- LRI <- NULL
cci_dt <- copy(
cci_table_detected
)
if (global & (category == "ER_CELLTYPES")) {
cci_dt[, ER_CELLTYPES := paste(ID, ER_CELLTYPES, sep = "_")]
}
if (category == "LIGAND_COMPLEX") {
cci_dt[, LIGAND_COMPLEX := gsub(":.*", "", LRI)]
}
if (category == "RECEPTOR_COMPLEX") {
cci_dt[, RECEPTOR_COMPLEX := gsub(".*:", "", LRI)]
}
ora_tables <- lapply(
X = regulation,
FUN = function(reg) {
if (category %in% c("GO_TERMS", "KEGG_PWS") |
!is.null(extra_annotation)) {
if (category == "GO_TERMS") {
if (species == "mouse") {
new_intersection_dt <- scDiffCom::LRI_mouse$LRI_curated_GO[
,
c("LRI", "GO_ID", "GO_NAME")
]
}
if (species == "human") {
new_intersection_dt <- scDiffCom::LRI_human$LRI_curated_GO[
,
c("LRI", "GO_ID", "GO_NAME")
]
}
base_category <- "LRI"
new_id <- "GO_ID"
new_name <- "GO_NAME"
new_category <- "GO_TERMS"
}
if (category == "KEGG_PWS") {
if (species == "mouse") {
new_intersection_dt <- scDiffCom::LRI_mouse$LRI_curated_KEGG
}
if (species == "human") {
new_intersection_dt <- scDiffCom::LRI_human$LRI_curated_KEGG
}
base_category <- "LRI"
new_id <- "KEGG_ID"
new_name <- "KEGG_NAME"
new_category <- "KEGG_PWS"
}
if (!is.null(extra_annotation)) {
new_intersection_dt <- extra_annotation
base_category <- colnames(extra_annotation)[[1]]
new_id <- NULL
new_name <- colnames(extra_annotation)[[2]]
new_category <- colnames(extra_annotation)[[2]]
}
counts_dt <- extract_category_counts(
cci_table_detected = cci_dt,
category = base_category,
reg = reg,
logfc_threshold = logfc_threshold
)
counts_dt <- extract_additional_category_counts(
counts_dt = counts_dt,
new_intersection_dt = new_intersection_dt,
base_category = base_category,
new_category = new_category,
new_id = new_id,
new_name = new_name
)
} else {
counts_dt <- extract_category_counts(
cci_table_detected = cci_dt,
category = category,
reg = reg,
logfc_threshold = logfc_threshold
)
}
counts_dt <- perform_ora_from_counts(
counts_dt = counts_dt
)
cols_to_rename <- colnames(counts_dt)
cols_to_rename <- cols_to_rename[
!(cols_to_rename %in%
c("VALUE", "VALUE_BIS", "CATEGORY"))
]
setnames(
x = counts_dt,
old = cols_to_rename,
new = paste0(cols_to_rename, "_", reg)
)
return(counts_dt)
}
)
ora_full <- Reduce(merge, ora_tables)
if (category == "GO_TERMS") {
if (species == "mouse") {
go_info <- scDiffCom::LRI_mouse$LRI_curated_GO
}
if (species == "human") {
go_info <- scDiffCom::LRI_human$LRI_curated_GO
}
ora_full[
unique(go_info[, c("GO_ID", "LEVEL", "ASPECT")]),
on = "VALUE_BIS==GO_ID",
c("LEVEL", "ASPECT") := mget(c("i.LEVEL", "i.ASPECT"))
]
}
return(ora_full)
}
extract_category_counts <- function(
cci_table_detected,
category,
reg,
logfc_threshold
) {
REGULATION <- COUNTS_VALUE_REGULATED <-
COUNTS_VALUE_NOTREGULATED <- LOGFC <- NULL
if (reg == "UP") {
dt_regulated <- cci_table_detected[
REGULATION == "UP" & LOGFC >= logfc_threshold
]
dt_notregulated <- cci_table_detected[
!(REGULATION == "UP" & LOGFC >= logfc_threshold)
]
} else if (reg == "DOWN") {
dt_regulated <- cci_table_detected[
REGULATION == "DOWN" & LOGFC <= -logfc_threshold
]
dt_notregulated <- cci_table_detected[
!(REGULATION == "DOWN" & LOGFC <= -logfc_threshold)
]
} else if (reg == "DIFF") {
dt_regulated <- cci_table_detected[
REGULATION %in% c("UP", "DOWN") & abs(LOGFC) >= logfc_threshold
]
dt_notregulated <- cci_table_detected[
!(REGULATION %in% c("UP", "DOWN") & abs(LOGFC) >= logfc_threshold)
]
} else if (reg == "FLAT") {
dt_regulated <- cci_table_detected[REGULATION == "FLAT"]
dt_notregulated <- cci_table_detected[REGULATION != "FLAT"]
} else {
stop("Type of ORA not supported.")
}
dt_counts <- rbindlist(
l = lapply(
X = category,
FUN = function(categ) {
merge.data.table(
x = dt_regulated[
,
list(
CATEGORY = categ,
COUNTS_VALUE_REGULATED = .N
),
by = list(VALUE = get(categ))],
y = dt_notregulated[
,
list(
CATEGORY = categ,
COUNTS_VALUE_NOTREGULATED = .N
),
by = list(VALUE = get(categ))],
by = c("VALUE", "CATEGORY"),
all = TRUE
)
}
),
use.names = TRUE
)
setnafill(
x = dt_counts,
type = "const",
fill = 0,
cols = c("COUNTS_VALUE_REGULATED", "COUNTS_VALUE_NOTREGULATED")
)
COUNTS_REGULATED <- dt_regulated[, .N]
COUNTS_NOTREGULATED <- dt_notregulated[, .N]
dt_counts <- dt_counts[
,
c(
"COUNTS_NOTVALUE_REGULATED",
"COUNTS_NOTVALUE_NOTREGULATED"
) :=
list(
COUNTS_REGULATED - COUNTS_VALUE_REGULATED,
COUNTS_NOTREGULATED - COUNTS_VALUE_NOTREGULATED
)
]
return(dt_counts)
}
extract_additional_category_counts <- function(
counts_dt,
new_intersection_dt,
base_category,
new_category,
new_id,
new_name
) {
CATEGORY <- COUNTS_VALUE_REGULATED <- COUNTS_NOTVALUE_REGULATED <-
COUNTS_NOTVALUE_NOTREGULATED <- COUNTS_VALUE_NOTREGULATED <-
COUNTS_VALUE_REGULATED_temp <- COUNTS_VALUE_NOTREGULATED_temp <- NULL
if (!identical(
class(counts_dt[["VALUE"]]),
class(new_intersection_dt[[base_category]])
)) {
stop(
paste0(
"First column of ",
new_category,
" (in 'extra_annotations') must be of the same type as column '",
base_category,
"'"
)
)
}
if (length(
intersect(
new_intersection_dt[[base_category]],
counts_dt[["VALUE"]]
)
) == 0) {
stop(
"Can't find any matching term between first column of ",
new_category,
" and column '",
base_category,
"'"
)
}
counts_intersection_dt <- merge.data.table(
new_intersection_dt,
counts_dt,
by.x = base_category,
by.y = "VALUE"
)
counts_intersection_dt[
,
c(
"COUNTS_VALUE_REGULATED_temp",
"COUNTS_VALUE_NOTREGULATED_temp"
) :=
list(
sum(COUNTS_VALUE_REGULATED),
sum(COUNTS_VALUE_NOTREGULATED)
),
by = new_name
]
counts_intersection_dt[
,
c(
"COUNTS_NOTVALUE_REGULATED_temp",
"COUNTS_NOTVALUE_NOTREGULATED_temp"
) := list(
COUNTS_NOTVALUE_REGULATED +
COUNTS_VALUE_REGULATED -
COUNTS_VALUE_REGULATED_temp,
COUNTS_NOTVALUE_NOTREGULATED +
COUNTS_VALUE_NOTREGULATED -
COUNTS_VALUE_NOTREGULATED_temp
)]
counts_intersection_dt[, CATEGORY := new_category]
counts_intersection_dt[, c(
"COUNTS_VALUE_REGULATED", "COUNTS_VALUE_NOTREGULATED",
"COUNTS_NOTVALUE_REGULATED", "COUNTS_NOTVALUE_NOTREGULATED",
base_category
) := NULL]
counts_intersection_dt <- unique(counts_intersection_dt)
if (is.null(new_id)) {
col_new_id <- NULL
} else {
col_new_id <- "VALUE_BIS"
}
setnames(
counts_intersection_dt,
old = c(
new_name, new_id,
"COUNTS_VALUE_REGULATED_temp",
"COUNTS_VALUE_NOTREGULATED_temp",
"COUNTS_NOTVALUE_REGULATED_temp",
"COUNTS_NOTVALUE_NOTREGULATED_temp"
),
new = c(
"VALUE", col_new_id,
"COUNTS_VALUE_REGULATED", "COUNTS_VALUE_NOTREGULATED",
"COUNTS_NOTVALUE_REGULATED", "COUNTS_NOTVALUE_NOTREGULATED"
)
)
counts_intersection_dt
}
perform_ora_from_counts <- function(
counts_dt
) {
P_VALUE <- BH_P_VALUE <- OR <- COUNTS_VALUE_REGULATED <-
COUNTS_VALUE_NOTREGULATED <-COUNTS_NOTVALUE_REGULATED <-
COUNTS_NOTVALUE_NOTREGULATED <- ORA_SCORE <- i.BH_P_VALUE <- NULL
counts_dt[, c("OR", "P_VALUE") :=
vfisher_2sided(
COUNTS_VALUE_REGULATED,
COUNTS_VALUE_NOTREGULATED,
COUNTS_NOTVALUE_REGULATED,
COUNTS_NOTVALUE_NOTREGULATED
)]
counts_dt[, c("KULC_DISTANCE", "IMBALANCE_RATIO") := list(
kulc(
COUNTS_VALUE_REGULATED,
COUNTS_VALUE_NOTREGULATED,
COUNTS_NOTVALUE_REGULATED,
COUNTS_NOTVALUE_NOTREGULATED
),
imbalance_ratio(
COUNTS_VALUE_REGULATED,
COUNTS_VALUE_NOTREGULATED,
COUNTS_NOTVALUE_REGULATED,
COUNTS_NOTVALUE_NOTREGULATED
)
)]
temp_bh_dt <- counts_dt[COUNTS_VALUE_REGULATED > 0]
temp_bh_dt[, "BH_P_VALUE" := list(stats::p.adjust(P_VALUE, method = "BH"))]
counts_dt[temp_bh_dt, on = "VALUE", "BH_P_VALUE" := i.BH_P_VALUE]
counts_dt[, ORA_SCORE := ifelse(
OR <= 1 | BH_P_VALUE >= 0.05,
0,
ifelse(
is.infinite(OR),
Inf,
-log10(BH_P_VALUE) * log2(OR)
)
)]
return(counts_dt)
}
clip_infinite_OR <- function(
ORA_dt
) {
OR <- COUNTS_VALUE_REGULATED <- COUNTS_NOTVALUE_NOTREGULATED <-
COUNTS_VALUE_NOTREGULATED <- COUNTS_NOTVALUE_REGULATED <- NULL
ORA_dt[, OR := ifelse(
is.infinite(OR),
(COUNTS_VALUE_REGULATED + 1) *
(COUNTS_NOTVALUE_NOTREGULATED + 1) /
((COUNTS_VALUE_NOTREGULATED + 1) *
(COUNTS_NOTVALUE_REGULATED + 1)),
OR
)]
return(ORA_dt)
}
fisher_2sided <- function(
COUNTS_VALUE_REGULATED,
COUNTS_VALUE_NOTREGULATED,
COUNTS_NOTVALUE_REGULATED,
COUNTS_NOTVALUE_NOTREGULATED
) {
m <- matrix(
data = c(
COUNTS_VALUE_REGULATED, COUNTS_VALUE_NOTREGULATED,
COUNTS_NOTVALUE_REGULATED, COUNTS_NOTVALUE_NOTREGULATED
),
nrow = 2,
ncol = 2,
byrow = TRUE
)
test <- stats::fisher.test(
x = m,
alternative = "two.sided"
)
res <- c(test$estimate, test$p.value)
return(res)
}
vfisher_2sided <- function(
COUNTS_VALUE_REGULATED,
COUNTS_VALUE_NOTREGULATED,
COUNTS_NOTVALUE_REGULATED,
COUNTS_NOTVALUE_NOTREGULATED
) {
v <- mapply(
FUN = fisher_2sided,
COUNTS_VALUE_REGULATED,
COUNTS_VALUE_NOTREGULATED,
COUNTS_NOTVALUE_REGULATED,
COUNTS_NOTVALUE_NOTREGULATED
)
l <- list(OR = v[1, ], P_VALUE = v[2, ])
return(l)
}
kulc <- function(
COUNTS_VALUE_REGULATED,
COUNTS_VALUE_NOTREGULATED,
COUNTS_NOTVALUE_REGULATED,
COUNTS_NOTVALUE_NOTREGULATED
) {
P_AB <- COUNTS_VALUE_REGULATED /
(COUNTS_VALUE_REGULATED + COUNTS_NOTVALUE_REGULATED)
P_BA <- COUNTS_VALUE_REGULATED /
(COUNTS_VALUE_REGULATED + COUNTS_VALUE_NOTREGULATED)
avg <- (P_AB + P_BA) / 2
return(avg)
}
imbalance_ratio <- function(
COUNTS_VALUE_REGULATED,
COUNTS_VALUE_NOTREGULATED,
COUNTS_NOTVALUE_REGULATED,
COUNTS_NOTVALUE_NOTREGULATED
) {
numerator <- abs(COUNTS_VALUE_NOTREGULATED - COUNTS_NOTVALUE_REGULATED)
denominator <- (COUNTS_VALUE_REGULATED
+ COUNTS_VALUE_NOTREGULATED
+ COUNTS_NOTVALUE_REGULATED)
return(numerator / denominator)
}
get_tables_ora <- function(
object,
categories,
simplified,
class_signature
) {
if (!is.character(categories)) {
stop("'categories' must be a character vector")
}
tables <- copy(object@ora_table)
if (identical(tables, list())) {
warning("The object does not contain ORA tables. Returning 'NULL'")
return(NULL)
}
categories_in <- names(tables)
if (identical(categories, "all")) {
categories <- categories_in
}
if (!all(categories %in% categories_in)) {
stop("All 'categories' must be present in the object.")
}
tables <- tables[categories]
if (simplified) {
if (class_signature == "scDiffComCombined") {
first_col <- "ID"
} else {
first_col <- NULL
}
cols_to_keep <- c(
first_col,
"VALUE",
"VALUE_BIS",
"LEVEL",
"ASPECT",
as.vector(outer(
c("OR_", "P_VALUE_", "BH_P_VALUE_", "ORA_SCORE_"),
c("UP", "DOWN", "FLAT", "DIFF"),
FUN = "paste0"
))
)
tables <- lapply(
tables,
function(table) {
cols_temp <- intersect(cols_to_keep, colnames(table))
res <- table[, cols_temp, with = FALSE]
}
)
}
tables
}
plot_ora <- function(
ora_dt,
category,
regulation,
max_terms_show,
GO_aspect,
OR_threshold,
bh_p_value_threshold
) {
VALUE <- ASPECT <- LEVEL <-
OR <- OR_UP <- OR_DOWN <- OR_FLAT <-
BH_PVAL <- BH_P_VALUE_UP <- BH_P_VALUE_DOWN <- BH_P_VALUE_FLAT <-
ORA_SCORE <- ORA_SCORE_UP <- ORA_SCORE_DOWN <- ORA_SCORE_FLAT <- NULL
if (!requireNamespace("ggplot2", quietly = TRUE)) {
stop(
paste0(
"Package \"ggplot2\" needed for this function to work.",
"Please install it."
),
call. = FALSE
)
}
if (OR_threshold < 1) {
stop(
"'OR_thtreshold' muste be bigger than 1"
)
}
if (bh_p_value_threshold > 0.05) {
stop(
"'bh_p_value_threshold' must be smaller than 0.05"
)
}
dt <- copy(ora_dt)
if(regulation == "UP") {
dt[, OR := OR_UP]
dt[, BH_PVAL := BH_P_VALUE_UP]
dt[, ORA_SCORE := ORA_SCORE_UP ]
} else if(regulation == "DOWN") {
dt[, OR := OR_DOWN]
dt[, BH_PVAL := BH_P_VALUE_DOWN]
dt[, ORA_SCORE := ORA_SCORE_DOWN ]
} else if(regulation == "FLAT") {
dt[, OR := OR_FLAT]
dt[, BH_PVAL := BH_P_VALUE_FLAT]
dt[, ORA_SCORE := ORA_SCORE_FLAT ]
} else {
stop("Can't find 'regulation' type")
}
if (category == "GO_TERMS") {
dt <- dt[
ASPECT == GO_aspect
]
dt[, VALUE := paste0(
"(L",
LEVEL,
") ",
VALUE
)]
}
dt <- dt[
OR > 1 &
BH_PVAL <= 0.05
]
if (any(is.infinite(dt$OR))) {
extra_label_annotation <- " (* : infinite odds ratios are normalized)"
dt[
,
VALUE := ifelse(
is.infinite(OR),
paste0("* ", VALUE),
VALUE
)
]
dt_finite <- dt[is.finite(OR)]
if (nrow(dt_finite) > 0) {
dt[
,
OR := ifelse(
is.infinite(OR),
1 + max(dt_finite$OR),
OR
)
]
} else {
dt[, OR := 100]
}
dt[
,
ORA_SCORE := -log10(BH_PVAL) * log2(OR)
]
} else {
extra_label_annotation <- NULL
}
dt <- dt[
OR > OR_threshold &
BH_PVAL <= bh_p_value_threshold
][order(-ORA_SCORE)]
n_row_tokeep <- min(max_terms_show, nrow(dt))
dt <- dt[1:n_row_tokeep]
dt$VALUE <- sapply(
dt$VALUE,
function(i) {
words <- strsplit(i, " ")[[1]]
n_words <- length(words)
if (n_words >= 5) {
if (n_words%%2 == 0) {
mid <- n_words/2
} else {
mid <- (n_words+1)/2
}
res <- paste0(
paste0(words[1:mid], collapse = " "),
"\n",
paste0(words[(mid+1):length(words)], collapse = " ")
)
} else {
res <- i
}
res
}
)
category_label <- ifelse(
category == "LRI",
"Ligand-Receptor Interactions",
ifelse(
category == "LIGAND_COMPLEX",
"Ligand Genes",
ifelse(
category == "RECEPTOR_COMPLEX",
"Receptor Genes",
ifelse(
category == "ER_CELLTYPES",
"Emitter-Receiver Cell Types",
ifelse(
category == "EMITTER_CELLTYPE",
"Emitter Cell Types",
ifelse(
category == "RECEIVER_CELLTYPE",
"Receiver Cell Types",
ifelse(
category == "GO_TERMS",
ifelse(
GO_aspect == "biological_process",
"GO Biological Processes",
ifelse(
GO_aspect == "molecular_function",
"GO Molecular Functions",
"GO Cellular Components"
)
),
ifelse(
category == "KEGG_PWS",
"KEGG Pathways",
category
)
)
)
)
)
)
)
)
ggplot2::ggplot(
dt,
ggplot2::aes(
ORA_SCORE,
stats::reorder(VALUE, ORA_SCORE)
)
) +
ggplot2::geom_point(
ggplot2::aes(
size = -log10(BH_PVAL),
color = log2(OR)
)
) +
ggplot2::scale_color_gradient(low = "orange", high = "red") +
ggplot2::xlab(paste0("ORA score ", regulation)) +
ggplot2::ylab("") +
ggplot2::labs(
size = "-log10(Adj. P-Value)",
color = "log2(Odds Ratio)",
caption = extra_label_annotation
) +
ggplot2::theme(text = ggplot2::element_text(size = 14)) +
ggplot2::theme(legend.position = c(0.8, 0.3)) +
ggplot2::theme(legend.title = ggplot2::element_text(size = 12)) +
ggplot2::theme(legend.text = ggplot2::element_text(size = 12)) +
ggplot2::theme(plot.title.position = "plot") +
ggplot2::ggtitle(
paste0(
"Top ",
n_row_tokeep,
" ",
regulation,
" ",
category_label
)
)
}
|
annoSegments <- function(x0, y0, x1, y1, plot, default.units = "native",
linecolor = "black", lwd = 1, lty = 1,
lineend = "butt", linejoin = "mitre",
arrow = NULL, params = NULL, ...) {
segmentsInternal <- parseParams(
params = params,
defaultArgs = formals(eval(match.call()[[1]])),
declaredArgs = lapply(match.call()[-1], eval.parent, n = 2),
class = "segmentsInternal"
)
segmentsInternal$gp <- gpar(
col = segmentsInternal$linecolor,
lwd = segmentsInternal$lwd,
lty = segmentsInternal$lty,
lineend = segmentsInternal$lineend,
linejoin = segmentsInternal$linejoin
)
segmentsInternal$gp <- setGP(
gpList = segmentsInternal$gp,
params = segmentsInternal, ...
)
segments <- structure(list(
x0 = segmentsInternal$x0,
y0 = segmentsInternal$y0,
x1 = segmentsInternal$x1,
y1 = segmentsInternal$y1,
arrow = segmentsInternal$arrow,
grobs = NULL,
gp = segmentsInternal$gp
),
class = "segmentsInternal"
)
check_page(error = "Cannot annotate segment without a `plotgardener` page.")
if (is.null(segmentsInternal$plot)) {
stop("argument \"plot\" is missing, with no default.",
call. = FALSE
)
}
if (is.null(segments$x0)) stop("argument \"x0\" is missing, ",
"with no default.", call. = FALSE)
if (is.null(segments$y0)) stop("argument \"y0\" is missing, ",
"with no default.", call. = FALSE)
if (is.null(segments$x1)) stop("argument \"x1\" is missing, ",
"with no default.", call. = FALSE)
if (is.null(segments$y1)) stop("argument \"y1\" is missing, ",
"with no default.", call. = FALSE)
page_height <- get("page_height", envir = pgEnv)
page_units <- get("page_units", envir = pgEnv)
segments$x0 <- misc_defaultUnits(value = segments$x0,
name = "x0",
default.units =
segmentsInternal$default.units)
segments$y0 <- misc_defaultUnits(value = segments$y0,
name = "y0",
default.units =
segmentsInternal$default.units,
funName = "annoSegments",
yBelow = FALSE)
segments$x1 <- misc_defaultUnits(value = segments$x1,
name = "x1",
default.units =
segmentsInternal$default.units)
segments$y1 <- misc_defaultUnits(value = segments$y1,
name = "y1",
default.units =
segmentsInternal$default.units,
funName = "annoSegments",
yBelow = FALSE)
plotVP <- getAnnoViewport(plot = segmentsInternal$plot)
plotVP_bottomLeft <- vp_bottomLeft(viewport = plotVP)
seekViewport(plotVP$name)
new_x0 <- convertX(segments$x0, unitTo = page_units, valueOnly = TRUE)
new_x1 <- convertX(segments$x1, unitTo = page_units, valueOnly = TRUE)
new_y0 <- convertY(segments$y0, unitTo = page_units, valueOnly = TRUE)
new_y1 <- convertY(segments$y1, unitTo = page_units, valueOnly = TRUE)
seekViewport(name = "page")
new_x0 <- as.numeric(plotVP_bottomLeft[[1]]) + new_x0
new_x1 <- as.numeric(plotVP_bottomLeft[[1]]) + new_x1
new_y0 <- as.numeric(plotVP_bottomLeft[[2]]) + new_y0
new_y1 <- as.numeric(plotVP_bottomLeft[[2]]) + new_y1
name <- paste0(
"segments",
length(grep(
pattern = "segments",
x = grid.ls(
print = FALSE,
recursive = FALSE
)
)) + 1
)
segments <- grid.segments(
x0 = unit(new_x0, page_units),
y0 = unit(new_y0, page_units),
x1 = unit(new_x1, page_units),
y1 = unit(new_y1, page_units),
arrow = segments$arrow, gp = segments$gp,
name = name
)
segments$grobs <- segments
message("segments[", segments$name, "]")
invisible(segments)
}
|
LKrigUnrollZGrid<- function( grid.list, ZGrid=NULL){
if( is.null(ZGrid)){
return(ZGrid)
}
if( is.list( ZGrid) ){
if( any(grid.list[[1]] != ZGrid[[1]]) |any(grid.list[[2]] != ZGrid[[2]]) ){
stop("grid list does not match grid for covariates")
}
ZGrid<- ZGrid$z
}
Zdim<- dim( ZGrid)
nx<- length( grid.list[[1]])
ny<- length( grid.list[[2]])
if( (Zdim[1] != nx) | (Zdim[2] != ny) ){
stop( "Dimension of ZGrid does not match dimensions of location grid list.")
}
return( matrix( c(ZGrid), nrow= Zdim[1]*Zdim[2] ))
}
|
plot.sum.intsearch <-function(x,type="summary",startN=21,...){
if(type=="summary"){
summary.int <- x
summary.int$info$log_lambda <- log(summary.int$info$lambda)
breaks <- do.breaks(range(summary.int$info$deviance), 20)
n_init <- 21
summary.int$info$cols <- level.colors(summary.int$info$deviance,at=breaks, col.regions = gray.colors)
n.features <- summary.int$info$n.features
print(my.plot <- xyplot(log_lambda ~ alpha,
data = summary.int$info,
groups = summary.int$info$cols,
cex = 1, cex.axis=1.5,
col = "black",
jitter.y=T, amount=0.01,
ylab=list(expression(paste("log ",lambda)),cex=1.5),
xlab=list(expression(alpha),cex=1.5),
panel = function(x, y, groups, ..., subscripts) {
fill <- groups[subscripts]
panel.grid(h = -1, v = -1)
panel.abline(h = log(summary.int$opt.lambda),
v = summary.int$opt.alpha,
col="red", lty = 1, lwd=2 )
panel.xyplot(x, y, pch = rep(c(22,21),c(n_init,nrow(summary.int$info)-n_init)),
fill = fill, ...) ;
ltext(x=x, y=y, labels=n.features, pos=ifelse(y<0.1,3,4), offset=1.5, cex=1,col=1)
},
legend = list(top = list(fun = draw.colorkey,
args = list(key = list(space = "top",
col = gray.colors,
at = breaks),
draw = FALSE))),
main="Cross-validated partial log likelihood deviance",
scales=list(cex=1)
))
}
if(type=="points"){
summary.int <- x
niter<- nrow(summary.int$info) - startN
iter<-c(rep(0,startN), c(1:niter))
plot(summary.int$info$alpha, iter, xlab=expression(alpha), ylab="Iteration", pch=20,cex=1.5,cex.axis=1.5)
grid(NA, niter+1, lwd=2)
abline(v=summary.int$opt.alpha, col="red")
}
}
|
setClass("OCvar",
slots=c(n="numeric",
k="numeric",
type="character",
paccept="numeric"),
contains="VIRTUAL",
validity=function(object){
if(any(is.na(object@n)) | any(is.na(object@k)) )
return("Missing values in 'n' or 'k'")
if (length(object@n) != 1 | length(object@k) != 1)
return("n and k must be of length 1.")
if (any(object@n <= 0))
return("Sample size 'n' must be greater than 0.")
if (any(object@k <= 0))
return("Cut-off 'k' must be greater than 0.")
return(TRUE)
})
setClass("OCnormal",
slots=c(pd="numeric", s.type="character"),
contains="OCvar",
prototype=prototype("OCvar",type="normal",pd=seq(0,1,by=0.01),s.type="known"),
validity=function(object){
if ([email protected] != "known" & [email protected] != "unknown")
return("s.type must be either 'known' or 'unknown'.")
if (any(is.na(object@pd)))
return("Missing values in 'pd' not allowed")
if (any(object@pd < 0.) | any(object@pd > 1.) )
return("Proportion defectives must be in the range [0,1]")
})
OCvar <- function(n, k, type=c("normal"), ...){
type <- match.arg(type)
OCtype <- paste("OC",type,sep="")
obj <- new(OCtype, n=n, k=k, type=type, ...)
OCtype <- getFromNamespace(paste("calc.",OCtype,sep=""),
ns="AcceptanceSampling")
if (type =="normal")
obj@paccept <- OCtype(n=obj@n, k=obj@k, pd=obj@pd,
[email protected])
obj
}
calc.OCnormal <- function(n,k,pd,s.type)
{
if (s.type=="known"){
pa <- 1-pnorm( (k+qnorm(pd))*sqrt(n))
}
if (s.type=="unknown"){
pa <- 1- pt(k*sqrt(n), df=n-1, ncp=-qnorm(pd)*sqrt(n))
}
return(pa)
}
OCvar.show.default <-
function(object){
if(length(object@n)==0){
x <- matrix(rep(NA,3), ncol=1)
}
else
x <- rbind(object@n, object@k)
dimnames(x) <- list(c("Sample size",
"Constant k"),
paste("Sample", 1:ncol(x)))
show(x)
}
OCvar.show.prob <-
function(object) {
if (object@type=="normal") {
x <- cbind(object@pd, object@paccept)
colnames(x) <- c("Prop. defective","P(accept)")
}
else
stop("No full print method defined for this type")
rownames(x) <- rep("", length(object@paccept))
show(x)
}
setMethod("show", "OCvar",
function(object){
cat(paste("Acceptance Sampling Plan (",object@type,")\n",sep=""))
cat(paste("Standard deviation assumed to be ",[email protected],"\n\n",sep=""))
OCvar.show.default(object)
})
setMethod("summary", "OCvar",
function(object, full=FALSE){
show(object)
if (full){
cat("\nDetailed acceptance probabilities:\n\n")
OCvar.show.prob(object)
}
})
setMethod("plot", signature(x="OCnormal", y="missing"),
function(x, y, type="o", ylim=c(0,1),...){
plot(x@pd, x@paccept, type=type,
xlab="Proportion defective", ylab="P(accept)",
ylim=ylim, ...)
})
setMethod("plot", signature(x="numeric", y="OCnormal"),
function(x, y, type="o", ylim=c(0,1),...){
plot(x, y@paccept, type=type,
ylab="P(accept)", ylim=ylim, ...)
})
assess.OCvar <-
function(object, PRP, CRP){
planOK <- TRUE
if (missing(PRP))
PRP <- rep(NA,3)
else if (!missing(PRP)){
if( !check.quality(PRP[1], type=object@type) |
!check.paccept(PRP[2]) )
stop("Quality and/or desired P(accept) out of bounds")
calc.pa <- getFromNamespace(paste("calc.OC",object@type,sep=""),
ns="AcceptanceSampling")
pa <- switch(object@type,
normal=calc.pa(n=object@n, k=object@k, [email protected],
pd=PRP[1]))
PRP <- c(PRP, pa)
if (pa >= PRP[2])
planOK <- TRUE
else
planOK <- FALSE
}
if (missing(CRP))
CRP <- rep(NA,3)
else if (!missing(CRP)){
if( !check.quality(CRP[1], type=object@type) |
!check.paccept(CRP[2]) )
stop("Quality and/or desired P(accept) out of bound")
calc.pa <- getFromNamespace(paste("calc.OC",object@type,sep=""),
ns="AcceptanceSampling")
pa <- switch(object@type,
normal=calc.pa(n=object@n, k=object@k, [email protected],
pd=CRP[1]))
CRP <- c(CRP, pa)
if (pa <= CRP[2])
planOK <- planOK & TRUE
else
planOK <- planOK & FALSE
}
return(list(OK=planOK, PRP=PRP, CRP=CRP))
}
setMethod("assess", signature(object="OCvar"),
function(object, PRP, CRP, print)
{
if(!hasArg(PRP) & !hasArg(CRP))
stop("At least one risk point, PRP or CRP, must be specified")
else if(CRP[1] <= PRP[1])
stop("Consumer Risk Point quality must be greater than Producer Risk Point quality")
plan <- assess.OCvar(object, PRP, CRP)
if (print) {
show(object)
cat(paste("\nPlan", ifelse(plan$OK, "CAN","CANNOT"),
"meet desired risk point(s):\n\n"))
if(hasArg(PRP) & hasArg(CRP))
RP <- cbind(PRP=plan$PRP, CRP=plan$CRP)
else if (hasArg(PRP))
RP <- cbind(PRP=plan$PRP)
else if (hasArg(CRP))
RP <- cbind(CRP=plan$CRP)
rownames(RP) <- c(" Quality", " RP P(accept)", "Plan P(accept)")
show(t(RP))
}
return(invisible(c(list(n=object@n, k=object@k, [email protected]), plan)))
})
|
NULL
set_palette <- function(p, palette){
p + .ggcolor(palette)+
.ggfill(palette)
}
change_palette <- function(p, palette){
set_palette(p, palette)
}
color_palette <- function(palette = NULL, ...) {
brewerpal <- .brewerpal()
ggscipal <- .ggscipal()
res <- NULL
if (is.null(palette))
palette <- ""
if (length(palette) == 1) {
if (palette %in% brewerpal)
ggplot2::scale_color_brewer(..., palette = palette)
else if (palette %in% ggscipal)
.scale_color_ggsci(palette = palette)
else if (palette == "grey")
ggplot2::scale_color_grey(..., start = 0.8, end = 0.2)
else if (palette == "hue")
ggplot2::scale_color_hue(...)
else if(.is_color(palette))
ggplot2::scale_color_manual(..., values = palette)
}
else if (palette[1] != "")
ggplot2::scale_color_manual(..., values = palette)
}
fill_palette <- function(palette = NULL, ...){
brewerpal <- .brewerpal()
ggscipal <- .ggscipal()
res <- NULL
if (is.null(palette))
palette <- ""
if (length(palette) == 1) {
if (palette %in% brewerpal)
ggplot2::scale_fill_brewer(..., palette = palette)
else if (palette %in% ggscipal)
.scale_fill_ggsci(palette = palette)
else if (palette == "grey")
ggplot2::scale_fill_grey(..., start = 0.8, end = 0.2)
else if (palette == "hue")
ggplot2::scale_fill_hue(...)
else if(.is_color(palette))
ggplot2::scale_fill_manual(..., values = palette)
}
else if (palette[1] != "")
ggplot2::scale_fill_manual(..., values = palette)
}
|
svg.box <- function(x = NULL, ranges = NULL, sides = 1:6, grid.lwd = 1, tick.axes = c(2,3,2),
tick.labels = c(2,3,2), tick.lwd = 1, tick.num = 10, tick.label.size = 'auto',
tick.label.opacity = 1, axis.label = c('x', 'y', 'z'), axis.label.opacity = 1,
axis.label.size = 'auto', grid.opacity = 0.1,
axis.col = rgb(0.5,0.5,0.5), grid.col = rgb(0.8,0.8,0.8), text.col = 'black', z.index=0,
lim.exact=FALSE, name = NULL, file=NULL){
if('svg' == getOption("svgviewr_glo_type")){
if(is.null(file)){
if(is.null(getOption("svg_glo_con"))) stop("svg.new has not been called yet.")
file <- getOption("svg_glo_con")
}
}
if(is.null(ranges)) ranges <- svg_ranges(x)
ranges_list <- svg_box_lim(ranges, tick.num, lim.exact=lim.exact)
xlim <- ranges_list$xlim
ylim <- ranges_list$ylim
zlim <- ranges_list$zlim
lim <- ranges_list$lim
max_diff <- ranges_list$max_diff
med_diff <- ranges_list$med_diff
grid_by <- ranges_list$grid_by
polygons <- svg_axis_polygons(xlim, ylim, zlim, sides)
if(grid.lwd > 0){
svg_grids <- svg_axis_grids(polygons, grid_by)
grids <- svg_grids$grid
grids_type <- svg_grids$type
}
if('svg' == getOption("svgviewr_glo_type")){
if(tick.label.size == 'auto') tick.label.size <- 0.13
if(axis.label.size == 'auto') axis.label.size <- 0.14
}else{
if(tick.label.size == 'auto') tick.label.size <- 0.02
if(axis.label.size == 'auto') axis.label.size <- 0.02
}
tick_len <- max_diff*0.03
ticks <- svg_axis_ticks(xlim, ylim, zlim, grid_by, tick.label.size, tick_len, tick.axes,
tick.labels)
ticks$axislabels <- as.list(axis.label)
if(getOption("svgviewr_glo_type") == 'svg'){
for(i in 1:length(polygons)){
svg.lines(file=file, x=polygons[[i]], col='black', opacity=0.4, layer='Grid border', z.index=z.index)
}
if(grid.lwd > 0) for(grid in grids) svg.lines(file=file, x=grid, col='black',
lwd=grid.lwd, opacity=grid.opacity, layer='Grid', z.index=z.index)
if(tick.lwd > 0){
for(i in 1:length(ticks$ticks)){
svg.lines(file=file, x=ticks$ticks[[i]], col='black', opacity=0.5, layer='Ticks', z.index=z.index)
}
}
if(tick.label.size > 0){
for(i in 1:length(ticks$ticklabels)){
svg.text(file=file, x=ticks$ticklabelspos[[i]], labels=ticks$ticklabels[[i]], col=text.col,
opacity=tick.label.opacity, font.size=max_diff*tick.label.size, layer='Tick labels', z.index=z.index)
}
}
if(axis.label.size > 0){
for(i in 1:length(ticks$axislabels)){
svg.text(file=file, x=ticks$axislabelspos[[i]], labels=ticks$axislabels[[i]], col=text.col,
opacity=axis.label.opacity, font.size=max_diff*axis.label.size, layer='Axis labels', z.index=z.index)
}
}
}else{
env <- as.environment(getOption("svgviewr_glo_env"))
if(is.null(name)){ shape_name <- 'frame.panel' }else{ shape_name <- name }
for(i in 1:length(polygons)){
svgviewr_env$svg$line[[length(svgviewr_env$svg$line)+1]] <- list('type'='line',
'name'=shape_name, 'x'=t(polygons[[i]]), col=setNames(webColor(axis.col), NULL), lwd=grid.lwd,
'depthTest'=TRUE)
}
if(is.null(name)){ shape_name <- 'frame.grid' }else{ shape_name <- name }
if(grid.lwd > 0){
grids_in <- grids[grids_type == 'in']
for(grid in grids_in) svgviewr_env$svg$line[[length(svgviewr_env$svg$line)+1]] <-
list('type'='line', 'name'=shape_name, 'x'=t(grid), 'col'=setNames(webColor(grid.col), NULL),
'lwd'=grid.lwd, 'depthTest'=TRUE)
}
if(is.null(name)){ shape_name <- 'frame.tick' }else{ shape_name <- name }
if(tick.lwd > 0){
for(i in 1:length(ticks$ticks)){
svgviewr_env$svg$line[[length(svgviewr_env$svg$line)+1]] <- list('type'='line',
'name'=shape_name, 'x'=t(ticks$ticks[[i]]), 'col'=setNames(webColor(axis.col), NULL),
'lwd'=grid.lwd, 'depthTest'=TRUE)
}
}
if(is.null(name)){ shape_name <- 'frame.ticklabel' }else{ shape_name <- name }
if(tick.label.size > 0){
for(i in 1:length(ticks$ticklabels)){
svg.text(labels=ticks$ticklabels[[i]], name=shape_name, x=ticks$ticklabelspos[[i]],
col=setNames(webColor(text.col), NULL), size=max_diff*tick.label.size)
}
}
if(is.null(name)){ shape_name <- 'frame.axislabel' }else{ shape_name <- name }
if(axis.label.size > 0){
for(i in 1:length(ticks$axislabels)){
svg.text(labels=ticks$axislabels[[i]], name=shape_name, x=ticks$axislabelspos[[i]],
col=setNames(webColor(text.col), NULL), size=max_diff*axis.label.size)
}
}
}
list('lim'=lim)
}
|
card_corners <- function(layout, footer = NULL, header = NULL, border_radius) {
no_footer <- is_na(footer)
no_header <- is_na(header)
css_corners <- css_corner_function(border_radius)
if(layout == "image-only") {
body_corners <- c(
image = css_corners(tl = no_header, tr = no_header, bl = no_footer, br = no_footer),
label = css_corners()
)
}
if(layout == "label-only") {
body_corners <- c(
image = css_corners(),
label = css_corners(tl = no_header, tr = no_header, bl = no_footer, br = no_footer)
)
}
if(layout == "label-below") {
body_corners <- c(
image = css_corners(tl = no_header, tr = no_header),
label = css_corners(bl = no_footer, br = no_footer)
)
}
if(layout == "label-above") {
body_corners <- c(
image = css_corners(bl = no_footer, br = no_footer),
label = css_corners(tl = no_header, tr = no_header)
)
}
if(layout == "label-left") {
body_corners <- c(
image = css_corners(tr = no_header, br = no_footer),
label = css_corners(tl = no_header, bl = no_footer)
)
}
if(layout == "label-right") {
body_corners <- c(
image = css_corners(tl = no_header, bl = no_footer),
label = css_corners(tr = no_header, br = no_footer)
)
}
if(layout == "inset-top") {
body_corners <- c(
image = css_corners(tl = no_header, tr = no_header, bl = no_footer, br = no_footer),
label = css_corners(tl = no_header, tr = no_header)
)
}
if(layout == "inset-bottom") {
body_corners <- c(
image = css_corners(tl = no_header, tr = no_header, bl = no_footer, br = no_footer),
label = css_corners(bl = no_footer, br = no_footer)
)
}
corners <- c(body_corners,
footer = css_corners(bl = TRUE, br = TRUE),
header = css_corners(tl = TRUE, tr = TRUE),
card = css_corners(tl = TRUE, tr = TRUE, bl = TRUE, br = TRUE),
core = css_corners(tl = no_header, tr = no_header, bl = no_footer, br = no_footer)
)
return(corners)
}
css_corner_function <- function(border_radius) {
function(tl = FALSE, tr = FALSE, bl = FALSE, br = FALSE, size = border_radius) {
cnr <- function(exists, sz) ifelse(exists, sz, "0")
paste(
"border-radius:",
cnr(tl, size),
cnr(tr, size),
cnr(br, size),
cnr(bl, size),
";"
)
}
}
|
hedrick <- function(x){
somme <- colSums(x)
M <- matrix(data=0,nrow=length(somme),ncol=length(somme))
rownames(M) <- dimnames(x)[[2]]
colnames(M) <- dimnames(x)[[2]]
for(i in 1:length(somme)){
for(j in 1:length(somme)){
M[i,j] <- (sum((x[,i]/somme[i])*(x[,j]/somme[j])))/
(0.5*(sum((x[,i]/somme[i])^2+(x[,j]/somme[j])^2)))
}
}
M
}
|
rmdzero<-function(x,est=onestep,grp=NA,nboot=500,...){
if(!is.list(x) && !is.matrix(x))stop("Data must be stored in a matrix or in list mode.")
if(is.list(x)){
mat<-matrix(0,length(x[[1]]),length(x))
for (j in 1:length(x))mat[,j]<-x[[j]]
}
if(is.matrix(x))mat<-x
if(!is.na(grp[1])){
mat<-mat[,grp]
}
mat<-elimna(mat)
J<-ncol(mat)
jp<-0
Jall<-(J^2-J)/2
dif<-matrix(NA,nrow=nrow(mat),ncol=Jall)
ic<-0
for(j in 1:J){
for(k in 1:J){
if(j<k){
ic<-ic+1
dif[,ic]<-mat[,j]-mat[,k]
}}}
dif<-as.matrix(dif)
data <- matrix(sample(nrow(mat), size = nrow(mat) * nboot, replace = T), nrow = nboot)
bvec <- matrix(NA, ncol = ncol(dif), nrow = nboot)
for(j in 1:ncol(dif)) {
temp <- dif[, j]
bvec[, j] <- apply(data, 1, rmanogsub, temp, est)
}
center<-apply(dif,2,est,...)
bcen<-apply(bvec,2,mean)
cmat<-var(bvec-bcen+center)
zvec<-rep(0,Jall)
m1<-rbind(bvec,zvec)
bplus<-nboot+1
discen<-mahalanobis(m1,center,cmat)
sig.level<-sum(discen[bplus]<=discen[1:nboot])/nboot
list(discen = discen, p.value=sig.level,center=center)
}
|
test_that("size of each `.f` result must be 1", {
expect_error(
slide_vec(1:2, ~c(.x, 1)),
"In iteration 1, the result of `.f` had size 2, not 1"
)
})
test_that("size of each `.f` result must be 1", {
expect_error(
slide_dbl(1:2, ~c(.x, 1)),
"In iteration 1, the result of `.f` had size 2, not 1"
)
})
test_that("inner type is allowed to be different", {
expect_equal(
slide_vec(1:2, ~if (.x == 1L) {list(1)} else {list("hi")}, .ptype = list()),
list(1, "hi")
)
})
test_that("inner type can be restricted with list_of", {
expect_error(
slide_vec(1:2, ~if (.x == 1L) {list_of(1)} else {list_of("hi")}, .ptype = list_of(.ptype = double())),
class = "vctrs_error_incompatible_type"
)
})
test_that("inner type can be restricted", {
expect_error(
slide_dbl(1:2, ~if (.x == 1L) {1} else {"x"}),
class = "vctrs_error_incompatible_type"
)
})
test_that(".ptype is respected", {
expect_equal(slide_vec(1, ~.x), 1)
expect_equal(slide_vec(1, ~.x, .ptype = int()), 1L)
expect_error(slide_vec(1, ~.x + .5, .ptype = integer()), class = "vctrs_error_cast_lossy")
})
test_that("`.ptype = NULL` results in 'guessed' .ptype", {
expect_equal(
slide_vec(1, ~.x, .ptype = NULL),
slide_vec(1, ~.x, .ptype = dbl())
)
})
test_that("`.ptype = NULL` fails if no common type is found", {
expect_error(
slide_vec(1:2, ~ifelse(.x == 1L, "hello", 1), .ptype = NULL),
class = "vctrs_error_incompatible_type"
)
})
test_that("`.ptype = NULL` validates that element lengths are 1", {
expect_error(
slide_vec(1:2, ~if(.x == 1L) {1:2} else {1}, .ptype = NULL),
"In iteration 1, the result of `.f` had size 2, not 1."
)
})
test_that("`.ptype = NULL` returns `NULL` with size 0 `.x`", {
expect_equal(slide_vec(integer(), ~.x, .ptype = NULL), NULL)
})
test_that("`.ptype = NULL` is size stable (
expect_length(slide_vec(1:4, ~.x, .step = 2), 4)
expect_length(slide_vec(1:4, ~1, .before = 1, .complete = TRUE), 4)
})
test_that(".ptypes with a vec_proxy() are restored to original type", {
expect_s3_class(
slide_vec(Sys.Date() + 1:5, ~.x, .ptype = as.POSIXlt(Sys.Date())),
"POSIXlt"
)
})
test_that("can return a matrix and rowwise bind the results together", {
mat <- matrix(1, ncol = 2)
expect_equal(
slide_vec(1:5, ~mat, .ptype = mat),
rbind(mat, mat, mat, mat, mat)
)
})
test_that("`slide_vec()` falls back to `c()` method as required", {
local_c_foobar()
expect_identical(slide_vec(1:3, ~foobar(.x), .ptype = foobar(integer())), foobar(1:3))
expect_condition(slide_vec(1:3, ~foobar(.x), .ptype = foobar(integer())), class = "slider_c_foobar")
expect_identical(slide_vec(1:3, ~foobar(.x)), foobar(1:3))
expect_condition(slide_vec(1:3, ~foobar(.x)), class = "slider_c_foobar")
})
test_that(".step produces typed `NA` values", {
expect_identical(slide_int(1:3, identity, .step = 2), c(1L, NA, 3L))
expect_identical(slide_dbl(1:3, identity, .step = 2), c(1, NA, 3))
expect_identical(slide_chr(c("a", "b", "c"), identity, .step = 2), c("a", NA, "c"))
expect_identical(slide_vec(1:3, identity, .step = 2), c(1L, NA, 3L))
expect_identical(slide_vec(1:3, identity, .step = 2, .ptype = integer()), c(1L, NA, 3L))
})
test_that(".complete produces typed `NA` values", {
expect_identical(slide_int(1:3, ~1L, .before = 1, .complete = TRUE), c(NA, 1L, 1L))
expect_identical(slide_dbl(1:3, ~1, .before = 1, .complete = TRUE), c(NA, 1, 1))
expect_identical(slide_chr(1:3, ~"1", .before = 1, .complete = TRUE), c(NA, "1", "1"))
expect_identical(slide_vec(1:3, ~1, .before = 1, .complete = TRUE), c(NA, 1, 1))
expect_identical(slide_vec(1:3, ~1, .before = 1, .complete = TRUE, .ptype = integer()), c(NA, 1L, 1L))
})
test_that("names exist on inner sliced elements", {
names <- letters[1:5]
x <- set_names(1:5, names)
exp <- set_names(as.list(names), names)
expect_equal(slide_vec(x, ~list(names(.x))), exp)
})
test_that("names can be placed on atomics", {
names <- letters[1:5]
x <- set_names(1:5, names)
expect_equal(names(slide_vec(x, ~.x)), names)
expect_equal(names(slide_vec(x, ~.x, .ptype = int())), names)
expect_equal(names(slide_vec(x, ~.x, .ptype = dbl())), names)
expect_equal(names(slide_int(x, ~.x)), names)
expect_equal(names(slide_dbl(x, ~.x)), names)
})
test_that("names from `.x` are kept, and new names from `.f` results are dropped", {
x <- set_names(1, "x")
expect_identical(slide_vec(x, ~c(y = 2), .ptype = NULL), c(x = 2))
expect_identical(slide_vec(1, ~c(y = 2), .ptype = NULL), 2)
expect_identical(slide_dbl(x, ~c(y = 2)), c(x = 2))
expect_identical(slide_dbl(1, ~c(y = 2)), 2)
})
test_that("names can be placed on data frames", {
names <- letters[1:2]
x <- set_names(1:2, names)
out <- slide_vec(x, ~data.frame(x = .x))
expect_equal(rownames(out), names)
out <- slide_vec(x, ~data.frame(x = .x), .ptype = data.frame(x = int()))
expect_equal(rownames(out), names)
})
test_that("names can be placed on arrays", {
names <- letters[1:2]
x <- set_names(1:2, names)
out <- slide_vec(x, ~array(.x, c(1, 1)), .ptype = array(int(), dim = c(0, 1)))
expect_equal(rownames(out), names)
})
test_that("names can be placed correctly on proxied objects", {
names <- letters[1:2]
x <- set_names(1:2, names)
datetime_lt <- as.POSIXlt(new_datetime(0))
out <- slide_vec(x, ~datetime_lt, .ptype = datetime_lt)
expect_equal(names(out), names)
})
test_that("slide_int() works", {
expect_equal(slide_int(1L, ~.x), 1L)
})
test_that("slide_int() can coerce", {
expect_equal(slide_int(1, ~.x), 1L)
})
test_that("slide_dbl() works", {
expect_equal(slide_dbl(1, ~.x), 1)
})
test_that("slide_dbl() can coerce", {
expect_equal(slide_dbl(1L, ~.x), 1)
})
test_that("slide_chr() works", {
expect_equal(slide_chr("x", ~.x), "x")
})
test_that("slide_chr() cannot coerce", {
expect_error(slide_chr(1, ~.x), class = "vctrs_error_incompatible_type")
})
test_that("slide_lgl() works", {
expect_equal(slide_lgl(TRUE, ~.x), TRUE)
})
test_that("slide_lgl() can coerce", {
expect_equal(slide_lgl(1, ~.x), TRUE)
})
test_that("slide_dfr() works", {
expect_identical(
slide_dfr(
1:2,
~new_data_frame(list(x = list(.x))),
.before = 1
),
data_frame(
x = list(1L, 1:2)
)
)
})
test_that("slide_dfc() works", {
x <- 1:2
fn <- function(x) {
if (length(x) == 1) {
data.frame(x1 = x)
} else {
data.frame(x2 = x)
}
}
expect_identical(
slide_dfc(1:2, fn, .before = 1),
data.frame(
x1 = c(1L, 1L),
x2 = 1:2
)
)
})
|
hist.CTLobject <- function(x, phenocol = 1, ...) {
if(missing(x)) stop("argument 'x' which expects a 'CTLobject' object is missing, with no default")
namez <- NULL
plot(c(0, 1.0), c(0, length(unlist(x[[phenocol[1]]]$perms))/5), type='n', main = "CTL scores permutations", ylab = "Frequency", xlab = "Difference in correlation^2")
for(pheno in phenocol) {
if(is.null(x[[pheno]]$perms)) stop(paste("Permutations not found for phenocol=", pheno))
sorted <- sort(unlist(x[[pheno]]$perms))
hist(sorted, breaks = seq(0,1.0,0.01), add = TRUE, col = pheno, ...)
namez <- c(namez,ctl.name(x[[pheno]]))
}
legend("topright", legend = namez, col = phenocol, lwd = 6)
}
|
setGeneric("as.matrix", package = "base")
as.matrix.crossdist <- function(x, ...) {
x <- cbind(x)
class(x) <- c("matrix", "array")
x
}
as.matrix.pairdist <- function(x, ...) {
x <- cbind(x)
class(x) <- c("matrix", "array")
x
}
as.data.frame.crossdist <- function(x, ...) {
as.data.frame(as.matrix(x, ...), ...)
}
as.data.frame.pairdist <- function(x, ...) {
as.data.frame(as.matrix(x, ...), ...)
}
|
.addNode <-
function(ID,parentID,data=NULL,ccstat=NULL){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
ind <- length(tempenv$private$IDs) + 1
parent <- match(parentID,tempenv$private$IDs)
if (is.na(parent)){
stop("Error: parent not found")
}
tempenv$private$IDs[ind] <- ID
tempenv$private$ps[ind] <- parent
tempenv$private$os[[parent]] <- c(tempenv$private$os[[parent]],ind)
tempenv$private$os[[ind]] <- vector("numeric",length=0)
tempenv$private$data[[ind]] <- data
if (!is.null(ccstat)) tempenv$private$Naff <- tempenv$private$Naff + ccstat
}
.addPed <-
function(ped,ORs){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
tempenv$private$Naff <- sum(ped[,6] == 2)
SNPnames <- paste(rep(ORs[,1],rep(2,length(ORs[,1]))),rep(c(".1",".2"),length(ORs[,1])),sep="")
RiskAlleles <- rep(ORs[,2],rep(2,length(ORs[,2])))
temp <- t(apply(ped[,SNPnames],1,function(x) x == RiskAlleles))
temp[ped[,SNPnames] == 0] <- NA
RAcounts <- sapply(ORs[,1],function(x) temp[,paste(x,".1",sep="")] + temp[,paste(x,".2",sep="")])
seen_founders <- ped[ped[,3] == 0 & ped[,4] == 0,2]
couples <- unique(ped[!ped[,2] %in% seen_founders,3:4],MARGIN=1)
coup_f1 <- couples[,1] %in% seen_founders
coup_f2 <- couples[,2] %in% seen_founders
leaves <- ped[,2][!(ped[,2] %in% c(couples[,1],couples[,2]))]
if (any(!coup_f1 & !coup_f2)) stop("Error: Cannot handle non-founder non-founder matings")
if (sum(coup_f1 & coup_f2) > 1) stop("Error: Cannot handle multiple founder-founder matings")
if (sum(coup_f1 & coup_f2) > 1) stop("Error: Cannot handle multiple founder-founder matings")
if (any(duplicated(couples[,1])) | any(duplicated(couples[,2]))) stop("Error: cannot handle half-siblings")
coup_founders <- sapply(1:length(coup_f1),function(i )paste(couples[i,2 - coup_f1[i]]))
coup_nonfounders <- sapply(1:length(coup_f1),function(i )paste(couples[i,2 - !coup_f1[i]]))
coup_ids <- paste(coup_nonfounders,coup_founders,sep="-")
parentage <- apply(ped,1,function(x) coup_ids[x[3] == couples[,1] & x[4] == couples[,2]])
parentage <- sapply(parentage,function(x) ifelse(length(x) == 0,NA,x))
coup_parentage <- parentage[coup_nonfounders]
tempenv$public$addRoot(coup_ids[coup_f1 & coup_f2],RAcounts[as.character(couples[coup_f1 & coup_f2,]),])
toAdd <- which(coup_parentage %in% tempenv$private$IDs & !(coup_ids %in% tempenv$private$IDs))
while (length(toAdd) > 0){
sapply(toAdd,function(i) tempenv$public$addNode(coup_ids[i],coup_parentage[i], RAcounts[c(coup_nonfounders[i] ,coup_founders[i]),]))
toAdd <- which(coup_parentage %in% tempenv$private$IDs & !(coup_ids %in% tempenv$private$IDs))
}
toAdd <- which(parentage %in% tempenv$private$IDs & !(names(parentage) %in% tempenv$private$IDs) & !(names(parentage) %in% c(couples[,1],couples[,2])))
while (length(toAdd) > 0){
sapply(toAdd,function(i) tempenv$public$addNode(names(parentage)[i],parentage[i],RAcounts[i,]))
toAdd <- which(parentage %in% tempenv$private$IDs & !(names(parentage) %in% tempenv$private$IDs) & !(names(parentage) %in% c(couples[,1],couples[,2])))
}
}
.addRoot <-
function(ID,data=NULL,ccstat=NULL){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
ind <- length(tempenv$private$IDs) + 1
tempenv$private$ps[ind] <- NA
tempenv$private$IDs[ind] <- ID
tempenv$private$os[[ind]] <- vector("numeric",length=0)
tempenv$private$data[[ind]] <- data
if (!is.null(ccstat)) tempenv$private$Naff <- tempenv$private$Naff + ccstat
}
.calcAlpha <-
function(ORs,i=1,progress=FALSE){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
if (progress & i %% floor(length(tempenv$private$IDs)/5) == 0){
cat('.')
}
freqs <- ORs[,5]
if (length(tempenv$private$os[[i]]) == 0){
tempenv$private$alpha[[i]] <- tempenv$private$Ls[[i]]
} else {
for (j in tempenv$private$os[[i]]) tempenv$public$calcAlpha(ORs,j, progress=progress)
tempalpha <- tempenv$private$Ls[[i]]
hw_freqs <- cbind((1 - freqs)^2,2*freqs*(1 - freqs),freqs^2)
for (a in 0:2){
for (b in 0:2){
Mtrans <- sapply(0:2,function(c) .getTrans(c(a,b),c))
for (child in tempenv$private$os[[i]]){
if (length(tempenv$private$os[[child]]) == 0){
temp <- apply(Mtrans* tempenv$private$alpha[[child]],2,sum)
tempalpha[a+1,b+1,] <- tempalpha[a+1,b+1,] * temp
} else {
temp <- sapply(1:length(hw_freqs[,1]),function(k) sum(Mtrans %*% t(hw_freqs[k,]) * tempenv$private$alpha[[child]][,,k]))
tempalpha[a+1,b+1,] <- tempalpha[a+1,b+1,] * temp
}
}
}
}
tempenv$private$alpha[[i]] <- tempalpha
}
}
.calcBeta <-
function(ORs,i=1,progress=FALSE){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
if (progress & i %% floor(length(tempenv$private$IDs)/5) == 0){
cat('.')
}
freqs <- ORs[,5]
tempbeta <- tempenv$private$Ls[[i]]*0
hw_freqs <- cbind((1 - freqs)^2,2*freqs*(1 - freqs),freqs^2)
parent <- tempenv$private$ps[i]
if (i == 1){
for (a in 0:2){
for (b in 0:2){
tempbeta[a+1,b+1,] <- hw_freqs[,a+1]*hw_freqs[,b+1]
}
}
} else if (length(tempenv$private$os[[i]]) > 0){
tempenv$private$betap[[i]] <- array(dim=c(3,3,3,3,length(hw_freqs[,1])))
for (a in 0:2){
for (b in 0:2){
tempbeta_ab <- 0
for (c in 0:2){
for (d in 0:2){
tempbeta_abcd <- tempenv$private$beta[[parent]][c+1,d+1,]*tempenv$private$Ls[[parent]][c+1,d+1,]*.getTrans(c(c,d),a) * hw_freqs[,b+1]
Mtrans <- sapply(0:2,function(e) .getTrans(c(c,d),e))
for (sib in setdiff(tempenv$private$os[[parent]],i)){
if (length(tempenv$private$os[[sib]]) == 0){
temp <- apply(Mtrans*tempenv$private$alpha[[sib]],2,sum)
tempbeta_abcd <- tempbeta_abcd * temp
} else {
temp <- sapply(1:length(hw_freqs[,1]),function(k) sum(Mtrans %*% t(hw_freqs[k,]) * tempenv$private$alpha[[sib]][,,k]))
tempbeta_abcd <- tempbeta_abcd * temp
}
}
tempenv$private$betap[[i]][a+1,b+1,c+1,d+1,] <- tempbeta_abcd
tempbeta_ab <- tempbeta_ab + tempbeta_abcd
}
}
tempbeta[a+1,b+1,] <- tempbeta_ab
}
}
} else {
tempenv$private$betap[[i]] <- array(dim=c(3,3,3,length(hw_freqs[,1])))
for (a in 0:2){
tempbeta_ab <- 0
for (c in 0:2){
for (d in 0:2){
tempbeta_abcd <- tempenv$private$beta[[parent]][c+1,d+1,]*tempenv$private$Ls[[parent]][c+1,d+1,]*.getTrans(c(c,d),a)
Mtrans <- sapply(0:2,function(e) .getTrans(c(c,d),e))
for (sib in setdiff(tempenv$private$os[[parent]],i)){
if (length(tempenv$private$os[[sib]]) == 0){
temp <- apply(Mtrans*tempenv$private$alpha[[sib]],2,sum)
tempbeta_abcd <- tempbeta_abcd * temp
} else {
temp <- sapply(1:length(hw_freqs[,1]),function(k) sum(Mtrans %*% t(hw_freqs[k,]) * tempenv$private$alpha[[sib]][,,k]))
tempbeta_abcd <- tempbeta_abcd * temp
}
}
tempenv$private$betap[[i]][a+1,c+1,d+1,] <- tempbeta_abcd
tempbeta_ab <- tempbeta_ab + tempbeta_abcd
}
}
tempbeta[a+1,] <- tempbeta_ab
}
}
tempenv$private$beta[[i]] <- tempbeta
if (length(tempenv$private$os[[i]]) > 0){
for (i in tempenv$private$os[[i]]){
tempenv$public$calcBeta(ORs,i,progress)
}
}
}
.calcLikelihoods <-
function(data){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
tempenv$private$Ls <- lapply(tempenv$private$data,.getLikelihood)
}
.calcParams <-
function(ORs,progress=TRUE){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
cat("Running Inside-Outside Algorithm\n")
cat("Calculating likelihoods.....")
tempenv$public$calcLikelihoods()
cat("done\nCalculating inside parameters")
tempenv$public$calcAlpha(ORs,progress=progress)
cat("done\nCalculating outside parameters")
tempenv$public$calcBeta(ORs,progress=progress)
cat("done\nCalculating posteriors.....")
tempenv$public$calcPost()
cat("done\n")
}
.calcPost <-
function(i=1){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
if (i == 1){
unnorm <- tempenv$private$beta[[i]]*tempenv$private$alpha[[i]]
Pds <- apply(unnorm,3,sum)
tempenv$private$post[[i]] <- unnorm/rep(Pds,rep(9,length(Pds)))
} else {
tempenv$private$condpost[[i]] <- tempenv$private$betap[[i]]*0
if (length(tempenv$private$os[[i]]) == 0){
unnorm <- tempenv$private$beta[[i]]*tempenv$private$alpha[[i]]
Pds <- apply(unnorm,2,sum)
tempenv$private$post[[i]] <- unnorm/rep(Pds,rep(3,length(Pds)))
for (c in 0:2){
for (d in 0:2){
unnorm <- tempenv$private$betap[[i]][,c+1,d+1,]*tempenv$private$alpha[[i]]
Pds <- apply(unnorm,2,sum)
tempenv$private$condpost[[i]][,c+1,d+1,] <- unnorm/rep(Pds,rep(3,length(Pds)))
}
}
} else {
unnorm <- tempenv$private$beta[[i]]*tempenv$private$alpha[[i]]
Pds <- apply(unnorm,3,sum)
tempenv$private$post[[i]] <- unnorm/rep(Pds,rep(9,length(Pds)))
for (c in 0:2){
for (d in 0:2){
unnorm <- tempenv$private$betap[[i]][,,c+1,d+1,]* tempenv$private$alpha[[i]]
Pds <- apply(unnorm,3,sum)
tempenv$private$condpost[[i]][,,c+1,d+1,] <- unnorm/rep(Pds,rep(9,length(Pds)))
}
}
}
}
for (child in tempenv$private$os[[i]]) tempenv$public$calcPost(child)
}
.getCoupleLikelihood <-
function(a){
out <- array(dim=c(3,3,length(a[1,])))
L0_nf <- (a[1,] == 0)
L0_nf[is.na(a[1,])] <- 1
L1_nf <- (a[1,] == 1)
L1_nf[is.na(a[1,])] <- 1
L2_nf <- (a[1,] == 2)
L2_nf[is.na(a[1,])] <- 1
L0_f <- (a[2,] == 0)
L0_f[is.na(a[2,])] <- 1
L1_f <- (a[2,] == 1)
L1_f[is.na(a[2,])] <- 1
L2_f <- (a[2,] == 2)
L2_f[is.na(a[2,])] <- 1
out[1,1,] <- L0_nf * L0_f
out[1,2,] <- L0_nf * L1_f
out[1,3,] <- L0_nf * L2_f
out[2,1,] <- L1_nf * L0_f
out[2,2,] <- L1_nf * L1_f
out[2,3,] <- L1_nf * L2_f
out[3,1,] <- L2_nf * L0_f
out[3,2,] <- L2_nf * L1_f
out[3,3,] <- L2_nf * L2_f
return(out)
}
.getData <-
function(){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
return(tempenv$private)
}
.getLikelihood <-
function(a){
if (is.array(a)){
return(.getCoupleLikelihood(a))
} else {
return(.getSingleLikelihood(a))
}
}
.getMaxDepth <-
function(ID=NULL,depth=0){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
temp <- depth
if (tempenv$public$getNNodes() == 0) return(0)
if (is.null(ID)){
for (x in tempenv$public$getRoot()){
temp <- c(temp,tempenv$public$getMaxDepth(x,depth=depth+1))
}
} else {
for (x in tempenv$public$getOffspring(ID)){
temp <- c(temp,tempenv$public$getMaxDepth(x,depth=depth+1))
}
}
return(max(temp))
}
.getNinds <-
function(){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
return(sum(sapply(tempenv$private$os,length) != 0)*2 + sum(sapply(tempenv$private$os,length) == 0))
}
.getNNodes <-
function(){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
return(length(tempenv$private$IDs))
}
.getOffspring <-
function(ID){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
tempenv$private$IDs[tempenv$private$os[[which(tempenv$private$IDs == ID)]]]
}
.getPrevs <-
function(ORs = NULL,K = NULL,overwrite=FALSE,iter=1000){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
progress=TRUE
if (tempenv$public$getNNodes() < 5) progress=FALSE
if (tempenv$public$getNNodes() == 0) stop("Error: Cannot perform sampling on an empty tree")
if (!is.null(K)) tempenv$private$K <- K
if (overwrite | length(tempenv$private$Ls) == 0 | length(tempenv$private$alpha) == 0 | length(tempenv$private$beta) == 0 | length(tempenv$private$betap) == 0){
if (is.null(ORs)) stop('Error: Need to provide OR object to fit model parameters')
tempenv$public$calcParams(ORs,progress)
}
if (overwrite | length(tempenv$private$simVars) == 0){
cat("Sampling variants from posterior")
tempenv$public$sampleVariants(iter= iter,report=T)
cat('done\n')
}
if (overwrite | length(tempenv$private$simCases) == 0){
if (is.null(ORs)) stop('Error: Need to provide odds ratio object ORs to sample cases')
if (is.null(K)) stop('Error: Need to provide prevalence value K to sample cases')
cat('Sampling cases given sampled variants')
tempenv$public$sampleCases(ORs,K,report=T,iter=iter)
cat('done\n')
}
output <- list()
output$samples <- tempenv$private$simCases
output$K <- tempenv$private$K
output$Ncases <- tempenv$private$Naff
output$N <- tempenv$public$getNinds()
class(output) <- "MangroveSample"
return(output)
}
.getRoot <-
function(){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
tempenv$private$IDs[which(is.na(tempenv$private$ps))]
}
.getSingleLikelihood <-
function(a){
L0 <- (a == 0)
L0[is.na(a)] <- 1
L1 <- (a == 1)
L1[is.na(a)] <- 1
L2 <- (a == 2)
L2[is.na(a)] <- 1
return(rbind(L0,L1,L2))
}
.getTrans <-
function(a,b,f=NULL){
mendT <- array(NA,c(3,3,3))
mendT[c(3,6,7,8,9,10,18,19,20,21,22,25)] <- 0
mendT[c(5,23)] <- 0.25
mendT[c(2,4,11,13,14,15,17,24,26)] <- 0.5
mendT[c(1,12,16,27)] <- 1
if (length(b) > 1 & is.null(f)) stop("Error: Need to supply f for couple->couple trans")
if (length(b) == 1 & !is.null(f)) stop("Error: f supplied but only one b state given")
if (length(b) == 1) return(mendT[a[1]+1,a[2]+1,b+1])
else return(mendT[a[1]+1,a[2]+1,b[1]+1]*dbinom(b[2],2,f))
}
.getVarExp_loci <-
function(K,OR1,OR2,f){
meanor <- (1-f)^2 + 2*f*(1-f)*OR1 + f^2*OR2
P_aa <- applyORs(1/meanor,K)
P_Aa <- applyORs(OR1/meanor,K)
P_AA <- applyORs(OR2/meanor,K)
T <- qnorm(1 - K)
mu_aa <- T - qnorm(1 - P_aa)
mu_Aa <- T - qnorm(1 - P_Aa)
mu_AA <- T - qnorm(1 - P_AA)
Vstar <- mu_aa^2*(1-f)^2 + mu_Aa^2*2*f*(1-f) + mu_AA^2*f^2
return(Vstar)
}
.onLoad <-
function (libname, pkgname)
{
op <- options()
op.utils <- list(help.try.all.packages = FALSE, internet.info = 2,
pkgType = .Platform$pkgType, str = list(strict.width = "no",
digits.d = 3, vec.len = 4), demo.ask = "default",
example.ask = "default", menu.graphics = TRUE, mailer = "mailto")
extra <- if (.Platform$OS.type == "windows") {
list(unzip = "internal", editor = if (length(grep("Rgui",
commandArgs(), TRUE))) "internal" else "notepad",
repos = c(CRAN = "@CRAN@", CRANextra = "http://www.stats.ox.ac.uk/pub/RWin"))
}
else list(unzip = Sys.getenv("R_UNZIPCMD"), editor = Sys.getenv("EDITOR"),
repos = c(CRAN = "@CRAN@"))
op.utils <- c(op.utils, extra)
toset <- !(names(op.utils) %in% names(op))
if (any(toset))
options(op.utils[toset])
}
.printSummary <-
function(){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
cat("A mangrove tree\n")
cat("Number of nodes: ")
cat(tempenv$public$getNNodes())
cat("\n")
cat("Max depth: ")
cat(tempenv$public$getMaxDepth())
cat("\n")
if (length(tempenv$private$data) > 0){
cat("Genotype data: loaded\n")
} else {
cat("Genotype data: Not loaded\n")
}
if (length(tempenv$private$Ls) > 0 & length(tempenv$private$alpha) > 0 & length(tempenv$private$beta) > 0 & length(tempenv$private$betap)){
cat("Model parameters: calculated\n")
} else {
cat("Model parameters: not calculated\n")
}
if (length(tempenv$private$simVars) > 0 | length(tempenv$private$simCases)){
cat("Sampling: performed\n")
} else {
cat("Sampling: not performed\n")
}
}
.printTree <-
function(ID=NULL,depth=0){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
if (tempenv$public$getNNodes() == 0){
cat("The tree is empty\n")
return(0)
}
if (is.null(ID)){
tempenv$public$printTree(tempenv$public$getRoot(),depth=depth+1)
} else {
cat(paste(rep("-",depth),collapse=""))
cat(paste(ID,"\n",sep=""))
for (x in tempenv$public$getOffspring(ID)){
tempenv$public$printTree(x,depth=depth+1)
}
}
}
.sampleCases <-
function(ORs,K,report=FALSE,iter=1000){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
mix2founder <- c(1,2,3,1,2,3,1,2,3)
mix2nfounder <- c(1,1,1,2,2,2,3,3,3)
N <- sum(sapply(tempenv$private$Ls,function(x) length(dim(x))-1))
iters <- iter
out <- matrix(NA,ncol=N,nrow=iters)
pos <- 1
meanOR <- prod(ORs[,6])
for (node in 1:length(tempenv$private$IDs)){
if (report & (node %% floor(N/5)) == 0) cat(".")
if (length(dim(tempenv$private$Ls[[node]])) == 3){
k1 <- apply(tempenv$private$simVars[,node,],1,function(i) prod((mix2founder[i] == 1) + (mix2founder[i] == 2)*ORs[,3] + (mix2founder[i] == 3)*ORs[,4]))
k2 <- apply(tempenv$private$simVars[,node,],1,function(i) prod((mix2nfounder[i] == 1) + (mix2nfounder[i] == 2)*ORs[,3] + (mix2nfounder[i] == 3)*ORs[,4]))
out[,pos] <- k1
out[,pos + 1] <- k2
pos <- pos + 2
} else {
k <- apply(tempenv$private$simVars[,node,],1,function(i) prod((i == 1) + (i == 2)*ORs[,3] + (i == 3)*ORs[,4]))
out[,pos] <- k
pos <- pos + 1
}
}
preodds <- K/(1 - K)
postodds <- preodds*out/meanOR
post <- postodds/(1 + postodds)
tempenv$private$simCases <- apply(post > runif(post),1,sum)
}
.sampleVariant <-
function(variant,i=1,p=NULL,parentsamples=NULL,iter=1000){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
transM <- cbind(rep(0:2,3),rep(0:2,c(3,3,3)))
parents_nz <- (1:9)[parentsamples != 0]
parent_counts <- parentsamples[parentsamples != 0]
if (i == 1) {
if (all(is.na(as.vector(tempenv$private$post[[1]][,,variant])))){
stop(paste("Impossible genetic structure for variant number ",variant,". Likely a Mendelian error.",sep=""))
}
outtemp <- rmultinom(1,iter,as.vector(tempenv$private$post[[1]][,,variant]))
tempenv$private$simVars[,1,variant] <- rep(1:9, outtemp)
} else if (length(tempenv$private$os[[i]]) == 0){
for (x in 1:length(parents_nz)){
if (all(is.na(as.vector(tempenv$private$post[[1]][,,variant])))){
stop(paste("Impossible genetic structure for variant number ",variant," . Likely a Mendelian error.",sep=""))
}
temp_sample <- rmultinom(1,parent_counts[x], tempenv$private$condpost[[i]][,transM[parents_nz[x],1]+1,transM[parents_nz[x],2]+1,variant])
temp_sample_data <- rep(1:3,temp_sample)
if (length(temp_sample_data) > 1) tempenv$private$simVars[tempenv$private$simVars[,p,variant] == parents_nz[x],i,variant] <- sample(temp_sample_data)
else tempenv$private$simVars[tempenv$private$simVars[,p,variant] == parents_nz[x],i,variant] <- temp_sample_data
}
} else {
outtemp <- parentsamples*0
for (x in 1:length(parents_nz)){
temp_sample <- rmultinom(1:9,parent_counts[x],tempenv$private$condpost[[i]][,,transM[parents_nz[x],1]+1,transM[parents_nz[x],2]+1,variant])
temp_sample_data <- rep(1:9,temp_sample)
if (length(temp_sample_data) > 1) tempenv$private$simVars[tempenv$private$simVars[,p,variant] == parents_nz[x],i,variant] <- sample(temp_sample_data)
else tempenv$private$simVars[tempenv$private$simVars[,p,variant] == parents_nz[x],i,variant] <- temp_sample_data
outtemp <- outtemp + temp_sample
}
}
for (child in tempenv$private$os[[i]]) tempenv$public$sampleVariant(variant,child,i,outtemp,iter)
}
.sampleVariants <-
function(iter=1000,report=FALSE){
tempenv <- parent.env(environment())
if (identical(globalenv(), tempenv)) stop("Error: Attempted to write to global environment")
tempenv$private$simVars <- array(dim=c(iter,length(tempenv$private$IDs),length(tempenv$private$Ls[[1]][1,1,])))
for (i in 1:length(tempenv$private$Ls[[1]][1,1,])){
if (report & i %% (max(floor(length(tempenv$private$Ls[[1]][1,1,])/5),1)) == 0) cat('.')
tempenv$public$sampleVariant(i,iter=iter)
}
}
|
get_distance <- function(target, out, overwrite = FALSE){
if(!check_running()) stop("There is no valid GRASS session. Program halted.")
flags <- "quiet"
if(overwrite) flags <- c(flags, "overwrite")
execGRASS(
"r.grow.distance",
flags = flags,
parameters = list(
input = target,
distance = basename(out),
metric = "euclidean"
)
)
invisible()
}
|
call(
x = 1, kdd = 2,
xy = 2, n = 33,
)
call(
x = 1, kdd = 2,
xy = 2, n = 33
)
call(
x = 1, kdd = 2,
xy = 2, n = 33,
)
call(
x = 1, kdd = 2,
xy = 2, n = 33,
)
call(
x = 1, kdd = 2,
xy = 2, n = 33,
)
call(
x = 1, kdd = 2,
xy = 2, n = 33,
)
call(
x = 1, kdd = 2,
xy = 22, n = 33,
)
call(
x = 1, d = 2,
xy = 22, n = 33,
)
call(
x = 1, kdd = 2, k = "abc",
xy = 2, n = 33, z = "333"
)
call(
x = 1,
xy = 2, n = 33, z = "333"
)
call(
x = 1, n = 33, z = "333",
xy = 2,
)
call(
k = ff("pk"), k = 3,
b = f(-g), 22 + 1,
44, 323
)
call(
k = ff("pk"), k = 3,
b = f(-g), 22 + 1,
44, 323,
)
call(
k = ff("pk"), k = 3,
b = f(-g), 22 + 1,
44
)
call(
44,
k = ff("pk"), k = 3,
b = f(-g), 22 + 1,
)
call(
k = ff("pk"), k = 3,
44,
b = f(-g), 22 + 1,
)
fell(
x = 1,
y = 23,
zz = NULL
)
fell(
x = 1,
y = 23,
zz = NULL
)
call(
a = 2,
bb = 3,
)
call(
a = 2, x = 111,
bb = 3,
)
call(
a = 2, x = 111,
bb = 3,
)
call(
a = 2, x = 111,
bb = 3,
)
call(
a = 2, x = 111,
bb = 3
)
call(
a = 2, x = 111,
bb = 3,
)
call(
a = 2, x = 111,
bb = 3,
)
call(
x = 95232,
y = f(),
)
ca(
x = 23200,
y2 = "hi",
m = c(rm.na = 7)
)
ca(
x = 23200,
y2 = "hi",
m = c(rm.na = 7)
)
fell(
x = 8, annoying = 3,
y = 23,
zz = NULL, finally = "stuff"
)
gell(
p = 2, g = gg(x), n = 3 * 3,
31, fds = -1, gz = f / 3 + 1,
)
xgle(
1212, 232, f(n = 2),
1, 2, "kFlya"
)
call(
x = 2, y = "another",
y = "hhjkjkbew", x = 3
)
call(
k = ff("pk"), k = 3,
b = f(-g), 22 + 1,
44, 323
)
|
ARestimate <- function (pd.cond, portf.uncond, rating.type = 'RATING') {
if (class(pd.cond) == 'function') {
pd.cond <- pd.cond(portf.uncond)
} else {
pd.cond <- pd.cond
}
portf.size <- ifelse(rating.type == 'RATING', sum(portf.uncond), length(portf.uncond));
portf.grades <- length(portf.uncond)
if (rating.type == 'RATING') {
portf.uncondP <- portf.uncond / portf.size
} else {
portf.uncondP <- rep(1 / portf.size, portf.size)
}
pd.uncond <- sum(pd.cond * portf.uncondP)
ar.1int <- c(0, cumsum(pd.cond * portf.uncondP)[- portf.grades])
ar.1 <- 2 * sum((1 - pd.cond) * portf.uncondP * ar.1int)
ar.2 <- sum(pd.cond * (1 - pd.cond) * portf.uncondP * portf.uncondP)
ar.total <- (1 / (pd.uncond * (1 - pd.uncond))) * (ar.1 + ar.2) - 1
return(list('AR' = ar.total, 'CT' = pd.uncond))
}
ARConfIntEst <- function(pd.cond, portf.uncond, rating.type = 'RATING', iter = 1000) {
portf.rating.num <- length(portf.uncond)
BootAR <- function() {
if (rating.type == 'RATING') {
subsample <- sample.int(portf.rating.num, size = sum(portf.uncond), replace = TRUE)
portf.uncond.new <- tabulate(subsample, nbins = portf.rating.num)
pd.cond.new <- pd.cond
} else {
subsample <- sample.int(portf.rating.num, size = portf.rating.num, replace = TRUE)
portf.uncond.new <- portf.uncond[subsample]
pd.cond.new <- pd.cond[subsample]
}
return(ARestimate(pd.cond.new, portf.uncond.new, rating.type)$AR)
}
ar.dist <- replicate(iter, BootAR())
return(sd(ar.dist))
}
QMMPDlinkFunc <- function(x, alpha, betta, calib.curve) {
if (calib.curve == 'logit') {
rez <- 1 / (1 + exp(-alpha - betta * x))
} else {
rez <- 1 / (1 + exp(-alpha - betta * qnorm(x)))
}
return(rez)
}
QMMGetRLogitPD <- function (alpha, betta, portf.uncond, portf.condND = NULL, rating.type = 'RATING', calib.curve) {
if (is.null(portf.condND)) {
portf.condND <- portf.uncond
}
if (rating.type == 'RATING') {
portf.cum <- cumsum(portf.condND)
portf.condNDist <- (portf.cum + c(0, portf.cum[-length(portf.cum)])) / (2 * sum(portf.condND))
} else {
portf.condNDist <- ecdf(portf.condND)(portf.condND)
portf.condNDist[length(portf.condNDist)] <- (1 + portf.condNDist[length(portf.condNDist) - 1]) / 2
}
rez <- list()
if (calib.curve == 'logit') {
rez$PD <- QMMPDlinkFunc(portf.condND, alpha, betta, calib.curve)
} else {
rez$PD <- QMMPDlinkFunc(portf.condNDist, alpha, betta, calib.curve)
}
rez$condNDist <- portf.condNDist
return(rez)
}
QMMakeTargetFunc <- function(pd.uncond.new, pd.cond.old, portf.uncond, portf.condND = NULL, AR.target = NULL, rating.type = 'RATING', calib.curve) {
if (is.null(AR.target)) {
AR.target <- ARestimate(pd.cond.old, portf.uncond, rating.type)$AR
}
CT.target <- pd.uncond.new
f <- function(x) {
y <- numeric(2)
pd.cond.cur <- QMMGetRLogitPD(x[1], x[2], portf.uncond, portf.condND, rating.type, calib.curve)$PD
cur <- ARestimate(pd.cond.cur, portf.uncond, rating.type)
y[1] <- cur$AR - AR.target
y[2] <- cur$CT - CT.target
return(y)
}
}
QMMRecalibrate <- function(pd.uncond.new, pd.cond.old, portf.uncond, portf.condND = NULL, AR.target = NULL, rating.type = 'RATING', calib.curve = 'robust.logit') {
if (rating.type == 'RATING' & calib.curve =='logit') {
stop("Simple logit calibration curve is applicable only for rating.type = \'SCORE\'")
}
optimfun <- QMMakeTargetFunc(pd.uncond.new, pd.cond.old, portf.uncond, portf.condND, AR.target, rating.type, calib.curve)
params <- nleqslv::nleqslv(c(0,0), optimfun)
calib.new <- QMMGetRLogitPD(params$x[1], params$x[2], portf.uncond, portf.condND, rating.type, calib.curve)
ar.sdev <- ARConfIntEst(pd.cond.old, portf.uncond, rating.type)
AR.bc <- ARestimate(pd.cond.old, portf.uncond, rating.type)
AR.ac <- ARestimate(calib.new$PD, portf.uncond, rating.type)
optimfun.sd.minus <- QMMakeTargetFunc(pd.uncond.new, pd.cond.old, portf.uncond, portf.condND, AR.ac$AR - ar.sdev, rating.type, calib.curve)
optimfun.sd.plus <- QMMakeTargetFunc(pd.uncond.new, pd.cond.old, portf.uncond, portf.condND, AR.ac$AR + ar.sdev, rating.type, calib.curve)
params.sd.minus <- nleqslv::nleqslv(c(0,0), optimfun.sd.minus)
params.sd.plus <- nleqslv::nleqslv(c(0,0), optimfun.sd.plus)
calib.sd.minus <- QMMGetRLogitPD(params.sd.minus$x[1], params.sd.minus$x[2], portf.uncond, portf.condND, rating.type, calib.curve)
calib.sd.plus <- QMMGetRLogitPD(params.sd.plus$x[1], params.sd.plus$x[2], portf.uncond, portf.condND, rating.type, calib.curve)
rez <- list()
rez$alpha <- params$x[1]
rez$beta <- params$x[2]
rez$CT.ac <- AR.ac$CT
rez$AR.ac <- AR.ac$AR
rez$CT.bc <- AR.bc$CT
rez$AR.bc <- AR.bc$AR
rez$AR.sdev <- ar.sdev
rez$condPD.ac <- calib.new$PD
rez$condPD.bc <- pd.cond.old
rez$condPD.ac.upper <- calib.sd.plus$PD
rez$condPD.ac.lower <- calib.sd.minus$PD
rez$portf.cumdist <- calib.new$condNDist
rez$portf.uncond <- portf.uncond
rez$rating.type <- rating.type
return(rez)
}
QMMPlot <- function(x) {
if (x$rating.type == 'RATING') {
portf <- x$portf.cumdist
} else {
portf <- x$portf.uncond
}
plot(x = portf,
y = x$condPD.ac,
main = "PD New vs Old",
xlab = "Score (Rating)",
ylab = "PD",
type = "l",
lwd = 3,
col = "red")
lines(x = portf,
y = x$condPD.bc,
lwd = 2,
col = "black")
lines(x = portf,
y = x$condPD.ac.upper,
lwd = 2,
lty = "dashed",
col = "blue")
lines(x = portf,
y = x$condPD.ac.lower,
lwd = 2,
lty = "dashed",
col = "green")
legend(x = "topright",
legend = c("PD after Calibration", "PD before Calibration", "PD Upper Bound", "PD Lower Bound"),
pch = c(16, 16, 16, 16),
col = c("red", "black", "blue", "green"))
}
|
test_that("Studentized Range distribution", {
dist <- dist_studentized_range(6, 5, 1)
expect_equal(format(dist), "StudentizedRange(6, 5, 1)")
expect_equal(quantile(dist, 0.1), stats::qtukey(0.1, 6, 5, 1))
expect_equal(quantile(dist, 0.5), stats::qtukey(0.5, 6, 5, 1))
expect_equal(cdf(dist, 0), stats::ptukey(0, 6, 5, 1))
expect_equal(cdf(dist, 3), stats::ptukey(3, 6, 5, 1))
expect_equal(cdf(dist, quantile(dist, 0.4246)), 0.4246, tolerance = 1e-3)
})
|
summary.cmfitlist = function(object, ..., coefs = TRUE) {
if (coefs) {
estimates = ldply(object, function(l) cbind(l$n.seasons,
rbind(ldply(l$estimates))))
names(estimates)[1] = "n.seasons"
estimates$parameter[is.na(estimates$parameter)] = "meanhazard"
values = ldply(object, function(x) x$AIC) %>% rename(c(V1 = "AIC"))
return(list(estimates = estimates, AICtable = values))
}
summarize_listOfFits(object, lrt = TRUE, print = FALSE)
}
print.cmfitlist = function(x, ...) {
print(summary(x, ...))
}
|
square_root <- function(vec, parallel = FALSE) {
n_cores <- translate_parallel(parallel)
RcppParallel::setThreadOptions(n_cores)
on.exit(RcppParallel::setThreadOptions(RcppParallel::defaultNumThreads()))
square_root_(vec)
}
|
test_that("get_centroid works correctly for coord pairs", {
expect_equal(
get_centroid(
lat = c(42.35375, 42.36645),
lng = c(-71.06750, -71.05030)
),
c(
"lat" = 42.3601,
"lng" = -71.0589
)
)
expect_equal(
get_centroid(
lat = c(42.35375, 42.36645),
lng = c(-71.06750, -71.05030)
),
rad_to_deg(get_centroid(
lat = deg_to_rad(c(42.35375, 42.36645)),
lng = deg_to_rad(c(-71.06750, -71.05030)),
coord.unit = "radians"
))
)
})
test_that("get_centroid returns early for single coordinates", {
expect_equal(
get_centroid(lat = 42, lng = -71),
c("lat" = 42, "lng" = -71)
)
})
test_that("get_centroid requires full coord pairs", {
expect_error(get_centroid(
lat = c(42.35375),
lng = c(-71.06750, -71.05030)
))
})
|
ne_coastline <- function(scale = 110,
returnclass = c('sp','sf')) {
returnclass <- match.arg(returnclass)
if ( scale == 10 )
{
check_rnaturalearthhires()
} else
{
check_rnaturalearthdata()
}
scale <- check_scale(scale)
sldf <- NULL
if ( scale==110 ) {
sldf <- rnaturalearthdata::coastline110
} else if ( scale==50 ) {
sldf <- rnaturalearthdata::coastline50
} else if ( scale==10 ) {
sldf <- rnaturalearthhires::coastline10
}
ne_as_sf(sldf, returnclass)
}
|
fa <- function(...){
msg(glue(crayon::red(cli::symbol$warning), " A rewrite of the icons package has introduced breaking changes."))
msg(glue(crayon::blue(cli::symbol$info), " Refer to the NEWS (https://pkg.mitchelloharawild.com/icons/news/) to read the changes."))
abort("Update to the new interface for the icons package.")
}
ii <- fa
ai <- fa
|
District.getByZip <-
function (zip5, zip4=NULL) {
if (length(zip4)==0) {
District.getByZip.basic1 <- function (.zip5) {
request <- "District.getByZip?"
inputs <- paste("&zip5=",.zip5,sep="")
pvs.url <- paste("http://api.votesmart.org/",request,"key=",get('pvs.key',envir=.GlobalEnv),inputs,sep="")
output.base <- xmlRoot(xmlTreeParse(pvs.url, useInternalNodes=TRUE))
districts <- removeChildren(output.base, kids=list(1,2))
electionDistricts <- districts[["electionDistricts"]]
districts <- removeChildren(districts, kids=list("electionDistricts"))
output.districts <- data.frame(t(xmlSApply(districts, function(x) xmlSApply(x, xmlValue))), row.names=NULL)
output.districts$Type <- "district"
output.electionDistricts <- data.frame(t(xmlSApply(electionDistricts, function(x) xmlSApply(x, xmlValue))), row.names=NULL)
output.electionDistricts$Type <- "electionDistrict"
output <- rbind(output.districts, output.electionDistricts)
output$zip5 <- .zip5
output
}
output.list <- lapply(zip5, FUN= function (s) {
District.getByZip.basic1(.zip5=s)
}
)
output.list <- redlist(output.list)
output <- dfList(output.list)
} else {
District.getByZip.basic2 <- function (.zip5, .zip4) {
pvs.url <- paste("http://api.votesmart.org/",request,"key=",get('pvs.key',envir=.GlobalEnv),inputs,sep="")
request <- "District.getByZip?"
inputs <- paste("&zip5=",.zip5, "&zip4=", .zip4, sep="")
output.base <- xmlRoot(xmlTreeParse(pvs.url, useInternalNodes=TRUE))
districts <- removeChildren(output.base, kids=list(1,2))
electionDistricts <- districts[["electionDistricts"]]
districts <- removeChildren(districts, kids=list("electionDistricts"))
output.districts <- data.frame(t(xmlSApply(districts, function(x) xmlSApply(x, xmlValue))), row.names=NULL)
output.districts$Type <- "district"
output.electionDistricts <- data.frame(t(xmlSApply(electionDistricts, function(x) xmlSApply(x, xmlValue))), row.names=NULL)
output.electionDistricts$Type <- "electionDistrict"
output <- rbind(output.districts, output.electionDistricts)
output$zip5 <- .zip5
output$zip4. <- .zip4
output
}
output.list <- lapply(zip5, FUN= function (s) {
lapply(zip4, FUN= function (c) {
District.getByZip.basic2( .zip5=s, .zip4=c)
}
)
}
)
output.list <- redlist(output.list)
output <- dfList(output.list)
}
output
}
|
context("mass-rlm")
skip_on_cran()
skip_if_not_installed("modeltests")
library(modeltests)
skip_if_not_installed("MASS")
library(MASS)
fit <- rlm(stack.loss ~ ., stackloss)
test_that("MASS::rlm tidier arguments", {
check_arguments(tidy.rlm)
check_arguments(glance.rlm)
check_arguments(augment.rlm)
})
test_that("tidy.rlm", {
td2 <- tidy(fit, conf.int = TRUE)
check_tidy_output(td2)
expect_false(NA %in% td2$conf.low)
expect_false(NA %in% td2$conf.high)
})
test_that("glance.rlm", {
gl <- glance(fit)
check_glance_outputs(gl)
check_dims(gl, 1, 7)
})
test_that("augment.rlm", {
skip_on_os("linux")
check_augment_function(
aug = augment.rlm,
model = fit,
data = stackloss,
newdata = stackloss
)
})
|
context("stat_density_2d")
test_that("uses scale limits, not data limits", {
base <- ggplot(mtcars, aes(wt, mpg)) +
stat_density_2d() +
scale_x_continuous(limits = c(1, 6)) +
scale_y_continuous(limits = c(5, 40))
ret <- layer_data(base)
expect_true(min(ret$x) < 1.2)
expect_true(max(ret$x) > 5.8)
expect_true(min(ret$y) < 8)
expect_true(max(ret$y) > 35)
})
|
setMethod('writeRaster', signature(x='RasterLayer', filename='character'),
function(x, filename, format, ...) {
if (!hasValues(x)) {
warning('all cell values are NA')
}
filename <- trim(filename)
if (filename == '') {
stop('provide a filename')
}
filename <- .fullFilename(filename, expand=TRUE)
if (!file.exists(dirname(filename))) {
stop("Attempting to write a file to a path that does not exist:\n ", dirname(filename))
}
filetype <- .filetype(format=format, filename=filename)
filename <- .getExtension(filename, filetype)
if (filetype == 'KML') {
KML(x, filename, ...)
return(invisible(x))
}
verylarge <- ncell(x) > 1000000000
if (! inMemory(x) | verylarge ) {
if ( toupper(x@file@name) == toupper(filename) ) {
stop('filenames of source and target should be different')
}
tr <- blockSize(x)
pb <- pbCreate(tr$n, ...)
r <- writeStart(x, filename=filename, format=filetype, ...)
for (i in 1:tr$n) {
v <- getValues(x, row=tr$row[i], nrows=tr$nrows[i])
r <- writeValues(r, v, tr$row[i])
pbStep(pb, i)
}
if (isTRUE(any(is.factor(x)))) {
levels(r) <- levels(x)
}
r <- writeStop(r)
pbClose(pb)
return(invisible(r))
}
if (.isNativeDriver(filetype)) {
out <- raster(x)
names(out) <- names(x)
try( out@history <- x@history, silent=TRUE)
levels(out) <- levels(x)
out@legend@colortable <- colortable(x)
dots <- list(...)
if (is.integer(x[1]) & is.null(dots$dataype)) {
out <- .startRasterWriting(out, filename, format=filetype, dataytpe="INT4S", ...)
} else {
out <- .startRasterWriting(out, filename, format=filetype, ...)
}
out <- writeValues(out, x@data@values, 1)
return( .stopRasterWriting(out) )
} else if (filetype=='ascii') {
x <- .writeAscii(x, filename=filename,...)
} else if (filetype=='CDF') {
x <- .startWriteCDF(x, filename=filename, ...)
x <- .writeValuesCDF(x, x@data@values)
return( .stopWriteCDF(x) )
} else {
x <- .writeGDALall(x, filename=filename, format=filetype, ...)
}
return(invisible(x))
}
)
setMethod('writeRaster', signature(x='RasterStackBrick', filename='character'),
function(x, filename, format, bylayer=FALSE, suffix='numbers', ...) {
if (!hasValues(x)) {
warning('all cell values are NA')
}
filename <- trim(filename)
if (bylayer) {
nl <- nlayers(x)
if (length(filename) > 1) {
if (length(filename) != nlayers(x) ) {
stop('the number of filenames is > 1 but not equal to the number of layers')
}
filename <- .fullFilename(filename, expand=TRUE)
filetype <- .filetype(format, filename=filename[1])
filename <- .getExtension(filename, filetype)
} else {
if (filename == '') {
stop('provide a filename')
}
filename <- .fullFilename(filename, expand=TRUE)
filetype <- .filetype(format, filename=filename)
filename <- .getExtension(filename, filetype)
ext <- extension(filename)
filename <- extension(filename, '')
if (suffix[1] == 'numbers') {
filename <- paste(filename, '_', 1:nl, ext, sep='')
} else if (suffix[1] == 'names') {
filename <- paste(filename, '_', names(x), ext, sep='')
} else if (length(suffix) == nl) {
filename <- paste(filename, '_', suffix, ext, sep='')
} else {
stop('invalid "suffix" argument')
}
}
if (filetype == 'KML') {
layers <- lapply(1:nl, function(i) KML(x[[i]], filename=filename[i], ...))
return(invisible(x))
}
if (inherits(x, 'RasterBrick')) {
x <- stack(x)
}
layers <- lapply(1:nl, function(i) writeRaster(x[[i]], filename=filename[i], format=filetype, ...))
return(invisible(stack(layers)))
}
if (filename == '') {
stop('provide a filename')
}
filename <- .fullFilename(filename, expand=TRUE)
filetype <- .filetype(format, filename=filename)
filename <- .getExtension(filename, filetype)
if (filetype == "ascii") {
stop('this file format does not support multi-layer files')
}
if (filetype == 'KML') {
KML(x, filename, ...)
return(invisible(x))
}
verylarge <- (ncell(x) * nlayers(x)) > 1000000000
if (.isNativeDriver(filetype)) {
if (! filetype %in% c("raster", "BIL", "BSQ", "BIP") ) {
stop('this file format does not support multi-band files')
}
out <- brick(x, values=FALSE)
names(out) <- names(x)
z <- getZ(x)
if (!is.null(z)) {
out <- setZ(out, z)
}
out <- writeStart(out, filename, format=filetype, ...)
if (inMemory(x) & (!verylarge)) {
out <- writeValues(out, values(x), 1)
} else {
tr <- blockSize(x)
pb <- pbCreate(tr$n, ...)
for (i in 1:tr$n) {
out <- writeValues(out, getValues(x, tr$row[i], tr$nrows[i]), tr$row[i])
pbStep(pb, i)
}
pbClose(pb)
}
out <- .stopRasterWriting(out)
return( invisible(out) )
}
if ( inMemory(x) & (!verylarge)) {
if (filetype=='CDF') {
b <- brick(x, values=FALSE)
b@z <- x@z
b <- .startWriteCDF(b, filename=filename, ...)
b <- .writeValuesBrickCDF(b, values(x))
x <- .stopWriteCDF(b)
} else {
x <- .writeGDALall(x, filename=filename, format=filetype, ...)
}
return(invisible(x))
} else {
if ( toupper(filename(x)) == toupper(filename) ) {
stop('filenames of source and destination should be different')
}
b <- brick(x, values=FALSE)
if (filetype=='CDF') {
b@z <- x@z
}
tr <- blockSize(b)
pb <- pbCreate(tr$n, ...)
x <- readStart(x, ...)
b <- writeStart(b, filename=filename, format=filetype, ...)
for (i in 1:tr$n) {
v <- getValues(x, row=tr$row[i], nrows=tr$nrows[i])
b <- writeValues(b, v, tr$row[i])
pbStep(pb, i)
}
b <- writeStop(b)
x <- readStop(x)
pbClose(pb)
return(invisible(b))
}
}
)
|
OneComp_Volume_Clearance_HalfLife<-function(Cl1,t_alpha,
Cl1.sd=NA,t_alpha.sd=NA,covar=c(Cl1talpha=NA),...){
if(is.na(covar[1])) covar<-0
Cl1.var = (Cl1.sd)^2
t_alpha.var = (t_alpha.sd)^2
V1<-(Cl1*t_alpha)/log(2)
Vdss<-V1
sigma2<-matrix(as.numeric(c(Cl1.var,covar[1],covar[1],t_alpha.var)),
2,2,byrow=T)
V1_deriv<-as.matrix(attr(eval(stats::deriv(~(Cl1*t_alpha)/log(2),
c("Cl1","t_alpha"))),"gradient"))
V1.sd<-sqrt(V1_deriv %*% sigma2 %*% t(V1_deriv))
Vdss.sd<-V1.sd
k10<-log(2)/t_alpha
k10_deriv<-as.matrix(attr(eval(stats::deriv(~log(2)/t_alpha,"t_alpha")),
"gradient"))
k10.sd<-sqrt(k10_deriv * t_alpha.var *k10_deriv)
true_A<-log(2)/(Cl1*t_alpha)
true_A_deriv<-as.matrix(attr(eval(stats::deriv(~log(2)/(Cl1*t_alpha),
c("Cl1","t_alpha"))),"gradient"))
true_A.sd<-sqrt(true_A_deriv %*% sigma2 %*% t(true_A_deriv))
frac_A<-1
frac_A.sd<-ifelse(is.na(Cl1.sd),NA,0)
alpha<-k10
alpha.sd<-k10.sd
if(is.na(t_alpha[1])){
param=rep(NA,8)
sd=rep(NA,8)
} else{
param = c(Cl1,t_alpha,V1,k10,Vdss,true_A,frac_A,alpha)
sd = c(Cl1.sd,t_alpha.sd,V1.sd,k10.sd,Vdss.sd,true_A.sd,frac_A.sd,alpha.sd)
}
result = data.frame(Parameter=c("Cl1","t_alpha","V1","k10","Vdss",
"True_A","Frac_A","alpha"),
Estimate=param, Std.err=sd)
row.names(result) <- c("Cl1","t_alpha","V1","k10","Vdss",
"True_A","Frac_A","alpha")
result<-result[c("Vdss","V1","Cl1","k10","alpha",
"t_alpha","True_A","Frac_A"),]
return(result)
}
|
test_that("predicates match definitions", {
expect_true(is_character(letters, 26))
expect_false(is_character(letters, 1))
expect_false(is_list(letters, 26))
expect_true(is_list(mtcars, 11))
expect_false(is_list(mtcars, 0))
expect_false(is_double(mtcars, 11))
expect_true(is_complex(cpl(1, 2), n = 2))
expect_false(is_complex(cpl(1, 2), n = 3))
expect_false(is_scalar_complex(cpl(1, 2)))
expect_false(is_bare_complex(structure(cpl(1, 2), class = "foo")))
})
test_that("can bypass string serialisation", {
bar <- chr(list("cafe", string(c(0x63, 0x61, 0x66, 0xE9))))
Encoding(bar) <- "latin1"
bytes <- list(bytes(c(0x63, 0x61, 0x66, 0x65)), bytes(c(0x63, 0x61, 0x66, 0xE9)))
expect_identical(map(bar, charToRaw), bytes)
expect_identical(Encoding(bar[[2]]), "latin1")
})
test_that("is_integerish() heeds type requirement", {
for (n in 0:2) {
expect_true(is_integerish(integer(n)))
expect_true(is_integerish(double(n)))
expect_false(is_integerish(double(n + 1) + .000001))
}
types <- c("logical", "complex", "character", "expression", "list", "raw")
for (type in types) {
expect_false(is_integerish(vector(type)))
}
})
test_that("is_integerish() heeds length requirement", {
for (n in 0:2) {
expect_true(is_integerish(double(n), n = n))
expect_false(is_integerish(double(n), n = n + 1))
}
})
test_that("non finite double values are integerish", {
expect_true(is_integerish(dbl(1, Inf, -Inf, NaN), finite = NULL))
expect_true(is_integerish(dbl(1, NA)))
expect_true(is_integerish(int(1, NA)))
})
test_that("is_finite handles numeric types", {
expect_true(is_finite(1L))
expect_false(is_finite(na_int))
expect_true(is_finite(1))
expect_false(is_finite(na_dbl))
expect_false(is_finite(Inf))
expect_false(is_finite(-Inf))
expect_false(is_finite(NaN))
expect_false(is_finite(c(1, 2, NaN)))
expect_error(expect_false(is_finite(NA)), "expected a numeric vector")
expect_true(is_finite(0i))
expect_false(is_finite(complex(real = NA)))
expect_false(is_finite(complex(imaginary = Inf)))
})
test_that("check finiteness", {
expect_true( is_double(dbl(1, 2), finite = TRUE))
expect_true( is_complex(cpl(1, 2), finite = TRUE))
expect_true(is_integerish(dbl(1, 2), finite = TRUE))
expect_false( is_double(dbl(1, 2), finite = FALSE))
expect_false( is_complex(cpl(1, 2), finite = FALSE))
expect_false(is_integerish(dbl(1, 2), finite = FALSE))
expect_false( is_double(dbl(1, Inf), finite = TRUE))
expect_false( is_complex(cpl(1, Inf), finite = TRUE))
expect_false(is_integerish(dbl(1, Inf), finite = TRUE))
expect_true( is_double(dbl(1, Inf), finite = FALSE))
expect_true( is_complex(cpl(1, Inf), finite = FALSE))
expect_true(is_integerish(dbl(1, Inf), finite = FALSE))
expect_true( is_double(dbl(-Inf, Inf), finite = FALSE))
expect_true( is_complex(cpl(-Inf, Inf), finite = FALSE))
expect_true(is_integerish(dbl(-Inf, Inf), finite = FALSE))
})
test_that("scalar predicates heed type and length", {
expect_true_false <- function(pred, pass, fail_len, fail_type) {
expect_true(pred(pass))
expect_false(pred(fail_len))
expect_false(pred(fail_type))
}
expect_true_false(is_scalar_list, list(1), list(1, 2), logical(1))
expect_true_false(is_scalar_atomic, logical(1), logical(2), list(1))
expect_true_false(is_scalar_vector, list(1), list(1, 2), quote(x))
expect_true_false(is_scalar_vector, logical(1), logical(2), function() {})
expect_true_false(is_scalar_integer, integer(1), integer(2), double(1))
expect_true_false(is_scalar_double, double(1), double(2), integer(1))
expect_true_false(is_scalar_character, character(1), character(2), logical(1))
expect_true_false(is_string, character(1), character(2), logical(1))
expect_true_false(is_scalar_logical, logical(1), logical(2), character(1))
expect_true_false(is_scalar_raw, raw(1), raw(2), NULL)
expect_true_false(is_scalar_bytes, raw(1), raw(2), NULL)
})
test_that("is_integerish() supports large numbers (
expect_true(is_integerish(1e10))
expect_true(is_integerish(2^52))
expect_false(is_integerish(2^52 + 1))
expect_false(is_integerish(2^50 - 0.1))
expect_false(is_integerish(2^49 - 0.05))
expect_false(is_integerish(2^40 - 0.0001))
})
test_that("is_string() matches on string", {
expect_true(is_string("foo"))
expect_true(is_string("foo", "foo"))
expect_false(is_string("foo", "bar"))
expect_false(is_string(NA, NA))
expect_true(is_string("foo", c("foo", "bar")))
expect_true(is_string("foo", c("bar", "foo")))
expect_false(is_string("foo", c("bar", "baz")))
})
test_that("is_string2() matches on `empty`", {
expect_snapshot({
(expect_error(is_string2("foo", empty = 1)))
(expect_error(is_string2("foo", empty = NA)))
(expect_error(is_string2("foo", "foo", empty = TRUE)))
})
expect_true(is_string2("foo", empty = NULL))
expect_true(is_string2("foo", empty = FALSE))
expect_false(is_string2("foo", empty = TRUE))
expect_true(is_string2("", empty = NULL))
expect_true(is_string2("", empty = TRUE))
expect_false(is_string2("", empty = FALSE))
})
test_that("is_bool() checks for single `TRUE` or `FALSE`", {
expect_true(is_bool(TRUE))
expect_true(is_bool(FALSE))
expect_false(is_bool(NA))
expect_false(is_bool(c(TRUE, FALSE)))
})
test_that("is_character2() matches empty and missing values", {
expect_true(is_character2("", empty = TRUE, missing = TRUE))
expect_true(is_character2(na_chr, empty = TRUE, missing = TRUE))
expect_false(is_character2(c("foo", ""), empty = FALSE))
expect_true(is_character2(c("foo", ""), empty = TRUE))
expect_true(is_character2(c("", ""), empty = TRUE))
expect_true(is_character2(c("foo", "foo"), empty = FALSE))
expect_false(is_character2(c("foo", NA), missing = FALSE))
expect_true(is_character2(c("foo", NA), missing = TRUE))
expect_true(is_character2(chr(NA, NA), missing = TRUE))
expect_true(is_character2(c("foo", "foo"), missing = FALSE))
expect_true(is_character2(c("foo", "foo"), empty = FALSE, missing = FALSE))
expect_true(is_character2(c("foo", "foo"), empty = FALSE, missing = TRUE))
expect_true(is_character2(chr(NA, NA), empty = FALSE, missing = TRUE))
expect_true(is_character2(c("foo", "foo"), empty = TRUE, missing = FALSE))
expect_true(is_character2(c("", ""), empty = TRUE, missing = FALSE))
})
|
MatrixPaste = function(x, sep="_", forceCharacter=FALSE, stringEmpty = " "){
if(is.null(x)) return(stringEmpty)
if(NCOL(x)==0) return(rep(stringEmpty,NROW(x)))
if(NCOL(x)<=1){
if(forceCharacter)
return(as.character(as.vector(x)))
return(as.vector(x))
}
apply(x , 1 , paste , collapse = sep )
}
MatrixPaste1 = function(x,stringEmpty = "1") MatrixPaste(x,stringEmpty = stringEmpty)
|
reSurv <- function(time1, time2, id, event, status, origin = 0) {
warning("'reSurv()' is being deprecated in Version 1.1.7. Output is prepared by 'Recur()'.\n See '?Recur()' for details.\n")
nArg <- length(match.call()) - 1
if (nArg >= 5) return(Recur(time1 %2% time2, id, event, status))
if (nArg < 5) return(Recur(time1, time2, id, event, origin = origin))
}
is.reReg <- function(x) inherits(x, "reReg")
|
NULL
setClass(
Class = "RLum.Results",
slots = list(data = "list"),
contains = "RLum",
prototype = list (data = list())
)
setAs("list", "RLum.Results",
function(from,to){
new(to,
originator = "coercion",
data = from)
})
setAs("RLum.Results", "list",
function(from){
from@data
})
setMethod("show",
signature(object = "RLum.Results"),
function(object) {
temp.names <- names(object@data)
if (length(object) > 0) {
temp.type <- sapply(1:length(object@data),
function(x) {
paste("\t .. $", temp.names[x],
" : ",
is(object@data[[x]])[1],
sep = "")
})
} else{
temp.type <- paste0("\t .. $", temp.names, " : ", is(object@data)[1])
}
temp.type <- paste(temp.type, collapse = "\n")
cat("\n [RLum.Results-class]")
cat("\n\t originator: ", object@originator, "()", sep = "")
cat("\n\t data:", length(object@data))
cat("\n", temp.type)
cat("\n\t additional info elements: ", length(object@info),"\n")
})
setMethod("set_RLum",
signature = signature("RLum.Results"),
function(class,
originator,
.uid,
.pid,
data = list(),
info = list()) {
newRLumReuslts <- new("RLum.Results")
newRLumReuslts@originator <- originator
newRLumReuslts@data <- data
newRLumReuslts@info <- info
[email protected] <- .uid
[email protected] <- .pid
return(newRLumReuslts)
})
setMethod(
"get_RLum",
signature = signature("RLum.Results"),
definition = function(object, data.object, info.object = NULL, drop = TRUE) {
if (!is.null(info.object)) {
if (info.object %in% names(object@info)) {
unlist(object@info[info.object])
} else {
if (length(object@info) == 0) {
warning("[get_RLum] This RLum.Results object has no info objects! NULL returned!)", call. = FALSE)
} else {
warning(paste0(
"[get_RLum] Invalid info.object name. Valid names are: ",
paste(names(object@info), collapse = ", ")
),
call. = FALSE)
}
return(NULL)
}
} else{
if (!missing(data.object)) {
if (is(data.object, "character")) {
if (all(data.object %in% names(object@data))) {
if (length(data.object) > 1) {
temp.return <- sapply(data.object, function(x) {
object@data[[x]]
})
} else{
temp.return <- list(data.object = object@data[[data.object]])
}
} else {
stop(paste0("[get_RLum()] data.object(s) unknown, valid names are: ",
paste(names(object@data), collapse = ", ")), call. = FALSE)
}
}
else if (is(data.object, "numeric")) {
if (max(data.object) > length(object@data)) {
stop("[get_RLum] 'data.object' index out of bounds!")
} else if (length(data.object) > 1) {
temp.return <- lapply(data.object, function(x) {
object@data[[x]]
})
} else {
temp.return <- list(object@data[[data.object]])
}
names(temp.return) <-
names(object@data)[data.object]
}
else{
stop("[get_RLum] 'data.object' has to be of type character or numeric!", call. = FALSE)
}
} else{
temp.return <- object@data[1]
}
if (drop) {
return(temp.return[[1]])
} else{
return(set_RLum(
"RLum.Results",
originator = object@originator,
data = temp.return
))
}
}
}
)
setMethod("length_RLum",
"RLum.Results",
function(object){
length(object@data)
})
setMethod("names_RLum",
"RLum.Results",
function(object){
names(object@data)
})
|
check_dbplyr <- function() {
check_pkg("dbplyr", "communicate with database backends", install = FALSE)
}
wrap_dbplyr_obj <- function(obj_name) {
`UQ<-` <- NULL
obj <- getExportedValue("dbplyr", obj_name)
obj_sym <- sym(obj_name)
dbplyr_sym <- call("::", quote(dbplyr), obj_sym)
dplyr_sym <- call("::", quote(dplyr), obj_sym)
if (is.function(obj)) {
args <- formals()
pass_on <- map(set_names(names(args)), sym)
dbplyr_call <- expr((!!dbplyr_sym)(!!!pass_on))
dplyr_call <- expr((!!dplyr_sym)(!!!pass_on))
} else {
args <- list()
dbplyr_call <- dbplyr_sym
dplyr_call <- dplyr_sym
}
body <- expr({
if (utils::packageVersion("dplyr") > "0.5.0") {
dplyr::check_dbplyr()
!!dbplyr_call
} else {
!!dplyr_call
}
})
wrapper <- new_function(args, body, caller_env())
expr(!!obj_sym <- !!get_expr(wrapper))
}
utils::globalVariables("!<-")
sql <- function(...) {
check_dbplyr()
dbplyr::sql(...)
}
ident <- function(...) {
check_dbplyr()
dbplyr::ident(...)
}
|
flip_img <- function(img, x = FALSE, y = FALSE, z = FALSE, ...){
img = check_nifti(img, ...)
d = dim(img)
ndim = length(d)
if (ndim == 2) {
if (z) {
stop("Cannot flip z- 2D Image!")
}
if (x) {
img = copyNIfTIHeader(img = img, img[nrow(img):1,])
}
if (y) {
img = copyNIfTIHeader(img = img, img[,ncol(img):1])
}
}
if (ndim == 3) {
if (x){
for (i in seq(d[3])){
x = img[,,i]
x = x[nrow(x):1,]
[email protected][,,i] = x
}
}
if (y){
for (i in seq(d[3])){
x = img[,,i]
x = x[,ncol(x):1]
[email protected][,,i] = x
}
}
if (z){
for (i in seq(d[1])){
x = img[i,,]
x = x[,ncol(x):1]
[email protected][i,,] = x
}
}
}
return(img)
}
|
quickmatch <- function(distances,
treatments,
treatment_constraints = NULL,
size_constraint = NULL,
target = NULL,
caliper = NULL,
...) {
dots <- eval(substitute(alist(...)))
if (!distances::is.distances(distances)) {
dist_call <- dots[names(dots) %in% names(formals(distances::distances))]
dist_call$data <- distances
distances <- do.call(distances::distances, dist_call)
}
ensure_distances(distances)
num_observations <- length(distances)
treatments <- coerce_treatments(treatments, num_observations, FALSE)
if (is.null(treatment_constraints)) {
treatment_constraints <- rep(1L, nlevels(treatments))
names(treatment_constraints) <- levels(treatments)
}
treatment_constraints <- coerce_treatment_constraints(treatment_constraints,
levels(treatments))
size_constraint <- coerce_size_constraint(size_constraint,
sum(treatment_constraints),
num_observations)
target <- coerce_target(target, treatments, FALSE)
ensure_caliper(caliper)
sc_call <- dots[names(dots) %in% names(formals(scclust::sc_clustering))]
if (!is.null(sc_call$type_labels)) {
stop("`type_labels` is ignored, please use the `treatments` parameter instead.")
}
if (!is.null(sc_call$type_constraints)) {
stop("`type_constraints` is ignored, please use the `treatment_constraints` parameter instead.")
}
if (!is.null(sc_call$primary_data_points)) {
stop("`primary_data_points` is ignored, please use the `target` parameter instead.")
}
if (is.null(sc_call$seed_method)) {
sc_call$seed_method <- "inwards_updating"
}
if (is.null(sc_call$primary_unassigned_method)) {
sc_call$primary_unassigned_method <- "closest_seed"
}
if (is.null(sc_call$secondary_unassigned_method)) {
secondary_unassigned_method_default <- TRUE
sc_call$secondary_unassigned_method <- "closest_seed"
} else {
secondary_unassigned_method_default <- FALSE
}
if (is.null(sc_call$primary_radius)) {
sc_call$primary_radius <- "seed_radius"
}
if (is.null(sc_call$secondary_radius)) {
if (is.null(caliper)) {
sc_call$secondary_radius <- "estimated_radius"
} else {
sc_call$secondary_radius <- "seed_radius"
}
}
if (is.null(sc_call$seed_radius) && !is.null(caliper)) {
if (sc_call$primary_unassigned_method %in% c("ignore", "closest_seed")) {
sc_call$seed_radius <- as.numeric(caliper) / 2.0
if (sc_call$secondary_unassigned_method == "closest_assigned") {
warning("Caliper is not properly enforced when `secondary_unassigned_method`==\"closest_assigned\".")
}
} else if (sc_call$primary_unassigned_method %in% c("any_neighbor", "closest_assigned")) {
sc_call$seed_radius <- as.numeric(caliper) / 4.0
warning("Caliper might perform poorly unless `primary_unassigned_method`==\"closest_seed\".")
}
if (sc_call$primary_radius != "seed_radius") {
warning("Caliper is not properly enforced unless `primary_radius`==\"seed_radius\".")
}
if (sc_call$secondary_radius != "seed_radius") {
warning("Caliper is not properly enforced unless `secondary_radius`==\"seed_radius\".")
}
} else if (!is.null(sc_call$seed_radius) && !is.null(caliper)) {
warning("`caliper` is ignored when `seed_radius` is specified.")
}
sc_call$distances <- distances
sc_call$size_constraint <- size_constraint
sc_call$type_labels <- treatments
sc_call$type_constraints <- treatment_constraints
sc_call$primary_data_points <- target
out_matching <- tryCatch({
do.call(scclust::sc_clustering, sc_call)
},
error = function(x) {
if (grepl("\\(scclust:src/nng_clustering.c:[0-9]+\\) Infeasible radius constraint.", x$message)) {
if (secondary_unassigned_method_default) {
new_warning("Most seeds are at zero distance to their neighbors in the clustering NNG. This typically happens with discrete low-dimensional covariates. Consider using exact matching with such data. Running with `secondary_unassigned_method == \"ignore\"`.", level = -5)
sc_call$secondary_unassigned_method <- "ignore"
do.call(scclust::sc_clustering, sc_call)
} else {
new_error("** Error in scclust: ", x$message, "\n ** Explanation of error: Most seeds are at zero distance to their neighbors in the clustering NNG. This typically happens with discrete low-dimensional covariates. Consider using exact matching with such data.", level = -5)
}
} else {
new_error("** Error in scclust: ", x$message, level = -5)
}
})
class(out_matching) <- c("qm_matching", class(out_matching))
out_matching
}
|
swe.gu19 <- function(data, region.gu19, n0=NA ,n1=NA, n2=NA){
if(!inherits(data,"data.frame"))
stop("swe.gu19: data must be given as data.frame")
if(!any((is.element(colnames(data), c("hs","date")))))
stop("swe.gu19: data must contain at least two columns named 'hs' and 'date'")
Hobs <- data$hs
if(any(is.na(Hobs)))
stop("swe.gu19: snow depth data must not be NA")
if(!all(Hobs >= 0))
stop("swe.gu19: snow depth data must not be negative")
if(!is.numeric(Hobs))
stop("swe.gu19: snow depth data must be numeric")
if(!inherits(data$date,"character"))
stop("swe.gu19: date column must be of class character")
if(missing(region.gu19))
stop("swe.gu19: region.gu19 must be given")
if (!is.element(region.gu19,c("italy","southwest","central","southeast","myregion")))
stop("swe.gu19: region.gu19 must be one of 'italy','southwest','central','southeast','myregion'")
guyennet.coeff <- list("italy" = c(n0=294, n1=-8.3e-1, n2=7.7e-3),
"southwest" = c(n0=285.9, n1=1.3e-1, n2=-0.1e-3),
"central" = c(n0=288.9, n1=-9.3e-1, n2=8.2e-3),
"southeast" = c(n0=332.5, n1=-16.8e-1, n2=13.5e-3),
"myregion" = c(n0=n0, n1=n1, n2=n2))
month <- as.numeric( format(as.POSIXct(data$date), "%m"))
yday <- as.POSIXlt(data$date, format="%Y-%m-%d")$yday + 1
dos <- ifelse( month>8 & month<=12, yday-243, yday+122 )
doy <- dos - 122
d <- data$date
doys <- c()
for(i in 1:nrow(data)){
m <- as.numeric( format(as.POSIXct(d[i]), "%m"))
yd <- as.POSIXlt(d[i], format="%Y-%m-%d")$yday + 1
if(m %in% c(10,11,12)){
doy <- yd-366
} else if (m>=7 & m<=9) {
doy <- NA
} else {
doy <- yd
}
doys <- c(doys,doy)
}
if(region.gu19 == "myregion" & any(is.na(c(n0,n1,n2)))){
stop("swe.gu19: at least one of the coefficients n0, n1, n2 is NULL")
}
n0 <- guyennet.coeff[[region.gu19]][1]
n1 <- guyennet.coeff[[region.gu19]][2]
n2 <- guyennet.coeff[[region.gu19]][3]
rho <- n0 + n1*(doys + 61) + n2*(doys + 61)^2
swe <- rho*data$hs
return(swe)
}
|
ARI.F <- function(VC,U, t_norm = c("minimum","product"))
{
if (missing(VC))
stop("The hard partitions VC must be given")
if (missing(U))
stop("The fuzzy partitions U must be given")
if (is.null(VC))
stop("The hard partitions VC is empty")
if (is.null(U))
stop("The fuzzy partitions U is empty")
VC <- as.numeric(VC)
U <- as.matrix(U)
partHard=matrix(0,nrow=length(VC),ncol=length(unique(VC)))
for (i in 1:length(VC))
{
partHard[i, VC[i]]=1
}
U = as.matrix(U)
t_norm <- match.arg(t_norm, choices = eval(formals(ARI.F)$t_norm))
out = partition_comp(HardClust = partHard,Fuzzy = U, t_norm = t_norm)
return(out$adjRand.F)
}
|
context("CSVY imports/exports")
require("datasets")
tmp <- tempfile(fileext = ".csvy")
test_that("Export to CSVY", {
suppressWarnings(expect_true(file.exists(export(iris, tmp))))
})
test_that("Import from CSVY", {
suppressWarnings(d <- import(tmp))
expect_true(inherits(d, "data.frame"))
})
unlink(tmp)
|
soboljansen <- function(model = NULL, X1, X2, nboot = 0, conf = 0.95, ...) {
if ((ncol(X1) != ncol(X2)) | (nrow(X1) != nrow(X2)))
stop("The samples X1 and X2 must have the same dimensions")
p <- ncol(X1)
X <- rbind(X1, X2)
for (i in 1:p) {
Xb <- X1
Xb[,i] <- X2[,i]
X <- rbind(X, Xb)
}
x <- list(model = model, X1 = X1, X2 = X2, nboot = nboot, conf = conf, X = X,
call = match.call())
class(x) <- "soboljansen"
if (!is.null(x$model)) {
response(x, other_types_allowed = TRUE, ...)
tell(x)
}
return(x)
}
estim.soboljansen <- function(data, i = NULL) {
if(is(data,"matrix")){
if(is.null(i)) i <- 1:nrow(data)
d <- as.matrix(data[i, ])
n <- nrow(d)
V <- var(d[, 1])
VCE <- V - (colSums((d[,2] - d[, - c(1, 2)])^2) / (2 * n - 1))
VCE.compl <- (colSums((d[,1] - d[, - c(1, 2)])^2) / (2 * n - 1))
return(c(V, VCE, VCE.compl))
} else if(is(data,"array")){
if(is.null(i)) i <- 1:dim(data)[1]
n <- length(i)
p <- dim(data)[2] - 2
one_dim3 <- function(d_array){
V <- apply(d_array, 3, function(d_matrix){
var(d_matrix[, 1])
})
SumSq <- apply(d_array, 3, function(d_matrix){
matrix(c(
colSums((d_matrix[, 2] - d_matrix[, -c(1, 2), drop = FALSE])^2) /
(2 * n - 1),
colSums((d_matrix[, 1] - d_matrix[, -c(1, 2), drop = FALSE])^2) /
(2 * n - 1)),
ncol = 2)
})
V_rep <- matrix(rep(V, each = p), ncol = dim(d_array)[3],
dimnames = list(NULL, dimnames(d_array)[[3]]))
VCE <- V_rep - SumSq[1:p, , drop = FALSE]
VCE.compl <- SumSq[(p + 1):(2 * p), , drop = FALSE]
return(rbind(V, VCE, VCE.compl, deparse.level = 0))
}
if(length(dim(data)) == 3){
d <- data[i, , , drop = FALSE]
return(one_dim3(d))
} else if(length(dim(data)) == 4){
d <- data[i, , , , drop = FALSE]
all_dim3 <- sapply(1:dim(data)[4], function(i){
one_dim3(array(data[ , , , i],
dim = dim(data)[1:3],
dimnames = dimnames(data)[1:3]))
}, simplify = "array")
dimnames(all_dim3)[[3]] <- dimnames(data)[[4]]
return(all_dim3)
}
}
}
tell.soboljansen <- function(x, y = NULL, return.var = NULL, ...) {
id <- deparse(substitute(x))
if (! is.null(y)) {
x$y <- y
} else if (is.null(x$y)) {
stop("y not found")
}
p <- ncol(x$X1)
n <- nrow(x$X1)
if(is(x$y,"numeric")){
data <- matrix(x$y, nrow = n)
if (x$nboot == 0){
V <- data.frame(original = estim.soboljansen(data))
} else{
V.boot <- boot(data, estim.soboljansen, R = x$nboot)
V <- bootstats(V.boot, x$conf, "basic")
}
rownames(V) <- c("global",
colnames(x$X1),
paste("-", colnames(x$X1), sep = ""))
if (x$nboot == 0) {
S <- V[2:(p + 1), 1, drop = FALSE] / V[1,1]
T <- V[(p + 2):(2 * p + 1), 1, drop = FALSE] / V[1,1]
rownames(T) <- colnames(x$X1)
} else {
S.boot <- V.boot
S.boot$t0 <- V.boot$t0[2:(p + 1)] / V.boot$t0[1]
S.boot$t <- V.boot$t[,2:(p + 1)] / V.boot$t[,1]
S <- bootstats(S.boot, x$conf, "basic")
T.boot <- V.boot
T.boot$t0 <- V.boot$t0[(p + 2):(2 * p + 1)] / V.boot$t0[1]
T.boot$t <- V.boot$t[,(p + 2):(2 * p + 1)] / V.boot$t[,1]
T <- bootstats(T.boot, x$conf, "basic")
rownames(S) <- colnames(x$X1)
rownames(T) <- colnames(x$X1)
}
} else if(is(x$y,"matrix")){
data <- array(x$y, dim = c(n, nrow(x$y) / n, ncol(x$y)),
dimnames = list(NULL, NULL, colnames(x$y)))
if(x$nboot == 0){
V <- estim.soboljansen(data)
rownames(V) <- c("global",
colnames(x$X1),
paste("-", colnames(x$X1), sep = ""))
V_global <- matrix(rep(V[1, ], p), nrow = p, byrow = TRUE)
S <- V[2:(p + 1), , drop = FALSE] / V_global
T <- V[(p + 2):(2 * p + 1), , drop = FALSE] / V_global
rownames(T) <- colnames(x$X1)
} else{
V.boot <- lapply(1:ncol(x$y), function(col_idx){
boot(as.matrix(data[, , col_idx]), estim.soboljansen, R = x$nboot)
})
V <- sapply(1:length(V.boot), function(col_idx){
as.matrix(bootstats(V.boot[[col_idx]], x$conf, "basic"))
}, simplify = "array")
dimnames(V) <- list(
c("global", colnames(x$X1), paste("-", colnames(x$X1), sep = "")),
dimnames(V)[[2]],
colnames(x$y))
S <- sapply(1:length(V.boot), function(col_idx){
S.boot_col <- V.boot[[col_idx]]
S.boot_col$t0 <- V.boot[[col_idx]]$t0[2:(p + 1)] / V.boot[[col_idx]]$t0[1]
S.boot_col$t <- V.boot[[col_idx]]$t[, 2:(p + 1)] / V.boot[[col_idx]]$t[, 1]
as.matrix(bootstats(S.boot_col, x$conf, "basic"))
}, simplify = "array")
T <- sapply(1:length(V.boot), function(col_idx){
T.boot_col <- V.boot[[col_idx]]
T.boot_col$t0 <- V.boot[[col_idx]]$t0[(p + 2):(2 * p + 1)] / V.boot[[col_idx]]$t0[1]
T.boot_col$t <- V.boot[[col_idx]]$t[, (p + 2):(2 * p + 1)] / V.boot[[col_idx]]$t[, 1]
as.matrix(bootstats(T.boot_col, x$conf, "basic"))
}, simplify = "array")
dimnames(S) <- dimnames(T) <- list(colnames(x$X1),
dimnames(V)[[2]],
colnames(x$y))
}
} else if(is(x$y,"array")){
data <- array(x$y, dim = c(n, dim(x$y)[1] / n, dim(x$y)[2:3]),
dimnames = list(NULL, NULL,
dimnames(x$y)[[2]], dimnames(x$y)[[3]]))
if(x$nboot == 0){
V <- estim.soboljansen(data)
dimnames(V)[[1]] <- c("global",
colnames(x$X1),
paste("-", colnames(x$X1), sep = ""))
V_global <- array(rep(V[1, , ], each = p), dim = c(p, dim(x$y)[2:3]))
S <- V[2:(p + 1), , , drop = FALSE] / V_global
T <- V[(p + 2):(2 * p + 1), , , drop = FALSE] / V_global
dimnames(T)[[1]] <- colnames(x$X1)
} else{
V.boot <- lapply(1:dim(x$y)[[3]], function(dim3_idx){
lapply(1:dim(x$y)[[2]], function(dim2_idx){
boot(as.matrix(data[, , dim2_idx, dim3_idx]), estim.soboljansen, R = x$nboot)
})
})
V <- sapply(1:dim(x$y)[[3]], function(dim3_idx){
sapply(1:dim(x$y)[[2]], function(dim2_idx){
as.matrix(bootstats(V.boot[[dim3_idx]][[dim2_idx]], x$conf, "basic"))
}, simplify = "array")
}, simplify = "array")
dimnames(V) <- list(c("global",
colnames(x$X1),
paste("-", colnames(x$X1), sep = "")),
dimnames(V)[[2]],
dimnames(x$y)[[2]],
dimnames(x$y)[[3]])
S <- sapply(1:dim(x$y)[[3]], function(dim3_idx){
sapply(1:dim(x$y)[[2]], function(dim2_idx){
S.boot_dim2 <- V.boot[[dim3_idx]][[dim2_idx]]
S.boot_dim2$t0 <-
V.boot[[dim3_idx]][[dim2_idx]]$t0[2:(p + 1)] /
V.boot[[dim3_idx]][[dim2_idx]]$t0[1]
S.boot_dim2$t <-
V.boot[[dim3_idx]][[dim2_idx]]$t[, 2:(p + 1)] /
V.boot[[dim3_idx]][[dim2_idx]]$t[, 1]
as.matrix(bootstats(S.boot_dim2, x$conf, "basic"))
}, simplify = "array")
}, simplify = "array")
T <- sapply(1:dim(x$y)[[3]], function(dim3_idx){
sapply(1:dim(x$y)[[2]], function(dim2_idx){
T.boot_dim2 <- V.boot[[dim3_idx]][[dim2_idx]]
T.boot_dim2$t0 <-
V.boot[[dim3_idx]][[dim2_idx]]$t0[(p + 2):(2 * p + 1)] /
V.boot[[dim3_idx]][[dim2_idx]]$t0[1]
T.boot_dim2$t <-
V.boot[[dim3_idx]][[dim2_idx]]$t[, (p + 2):(2 * p + 1)] /
V.boot[[dim3_idx]][[dim2_idx]]$t[, 1]
as.matrix(bootstats(T.boot_dim2, x$conf, "basic"))
}, simplify = "array")
}, simplify = "array")
dimnames(S) <- dimnames(T) <- list(colnames(x$X1),
dimnames(V)[[2]],
dimnames(x$y)[[2]],
dimnames(x$y)[[3]])
}
}
x$V <- V
x$S <- S
x$T <- T
for (i in return.var) {
x[[i]] <- get(i)
}
assign(id, x, parent.frame())
}
print.soboljansen <- function(x, ...) {
cat("\nCall:\n", deparse(x$call), "\n", sep = "")
if (!is.null(x$y)) {
if (is(x$y,"numeric")) {
cat("\nModel runs:", length(x$y), "\n")
} else if (is(x$y,"matrix")) {
cat("\nModel runs:", nrow(x$y), "\n")
} else if (is(x$y,"array")) {
cat("\nModel runs:", dim(x$y)[1], "\n")
}
cat("\nFirst order indices:\n")
print(x$S)
cat("\nTotal indices:\n")
print(x$T)
} else {
cat("\n(empty)\n")
}
}
plot.soboljansen <- function(x, ylim = c(0, 1),
y_col = NULL, y_dim3 = NULL, ...) {
if (!is.null(x$y)) {
p <- ncol(x$X1)
pch = c(21, 24)
if(is(x$y,"numeric")){
nodeplot(x$S, xlim = c(1, p + 1), ylim = ylim, pch = pch[1])
nodeplot(x$T, xlim = c(1, p + 1), ylim = ylim, labels = FALSE,
pch = pch[2], at = (1:p)+.3, add = TRUE)
} else if(is(x$y,"matrix") | is(x$y,"array")){
if(is.null(y_col)) y_col <- 1
if(is(x$y,"matrix") && !is.null(y_dim3)){
y_dim3 <- NULL
warning("Argument \"y_dim3\" is ignored since the model output is ",
"a matrix")
}
if(is(x$y,"array") && !is(x$y,"matrix") && is.null(y_dim3)) y_dim3 <- 1
nodeplot(x$S, xlim = c(1, p + 1), ylim = ylim, pch = pch[1],
y_col = y_col, y_dim3 = y_dim3)
nodeplot(x$T, xlim = c(1, p + 1), ylim = ylim, labels = FALSE,
pch = pch[2], at = (1:p)+.3, add = TRUE,
y_col = y_col, y_dim3 = y_dim3)
}
legend(x = "topright", legend = c("main effect", "total effect"), pch = pch)
}
}
ggplot.soboljansen <- function(x, ylim = c(0, 1),
y_col = NULL, y_dim3 = NULL, ...) {
if (!is.null(x$y)) {
p <- ncol(x$X1)
pch = c(21, 24)
if(is(x$y,"numeric")){
nodeggplot(listx = list(x$S,x$T), xname = c("Main effet","Total effect"), ylim = ylim, pch = pch)
} else if(is(x$y,"matrix") | is(x$y,"array")){
if(is.null(y_col)) y_col <- 1
if(is(x$y,"matrix") && !is.null(y_dim3)){
y_dim3 <- NULL
warning("Argument \"y_dim3\" is ignored since the model output is ",
"a matrix")
}
if(is(x$y,"array") && !is(x$y,"matrix") && is.null(y_dim3)) y_dim3 <- 1
nodeggplot(listx = list(x$S, x$T), xname = c("Main effet", "Total effect"), ylim = ylim, pch = pch, y_col = y_col, y_dim3 = y_dim3)
}
}
}
plotMultOut.soboljansen <- function(x, ylim = c(0, 1), ...) {
if (!is.null(x$y)) {
p <- ncol(x$X1)
if (!x$ubiquitous){
stop("Cannot plot functional indices since ubiquitous option was not activated")
}else{
if (x$Tot == T) par(mfrow=c(2,1))
plot(0,ylim=ylim,xlim=c(1,x$q),main="First order Sobol indices",ylab="",xlab="",type="n")
for (i in 1:p) lines(x$Sfct[,i],col=i)
legend(x = "topright", legend = dimnames(x$X1)[[2]], lty=1, col=1:p, cex=0.6)
if (x$Tot == T){
plot(0,ylim=ylim,xlim=c(1,x$q),main="Total Sobol indices",ylab="",xlab="",type="n")
for (i in 1:p) lines(x$Tfct[,i],col=i)
legend(x = "topright", legend = dimnames(x$X1)[[2]], lty=1, col=1:p, cex=0.6)
}
}
}
}
|
getCoords <- function(image) {
.plotImage <- function(image, ...) {
ncols <- ncol(image)
nrows <- nrow(image)
suppressWarnings(plot(0, type='n', xlim=c(0, ncols), ylim=c(0, nrows), ...))
suppressWarnings(rasterImage(image, xleft=0, ybottom=0, xright=ncols, ytop=nrows, ...))
}
.binaryConvert <- function(img) {
grey.image <- 0.2126*img[,,1] + 0.7152*img[,,2] + 0.0722*img[,,3]
binary <- round(grey.image, 0)
rev.binary <- ifelse(binary==1, 0, 1)
return(rev.binary)
}
image.target <- readJPEG(image)
image.target <- .binaryConvert(image.target)
image.width <- dim(image.target)[2]
image.height <- dim(image.target)[1]
.plotImage(image.target, main='Click the bottomright margin of the rectangle you want to crop')
vertices <- locator()
x.cuts <- c(0,round(vertices$x))
y.cuts <- c(0, image.height-round(vertices$y))
cropped <- image.target[y.cuts[1]:y.cuts[2], x.cuts[1]:x.cuts[2]]
cropped.binary <- round(cropped)
cropped.height <- dim(cropped.binary)[1]
.plotImage(cropped.binary, interpolate=FALSE)
vertices <- locator()
col.cut <- sort(round(c(vertices$x[1],vertices$x[2])))
row.cut <- sort(cropped.height - round(c(vertices$y[1], vertices$y[2])))
neg.pos.col <- which(col.cut<0)
if (length(neg.pos.col)!=0) col.cut[neg.pos.col] <- 0
neg.pos.row <- which(row.cut<0)
if (length(neg.pos.row)!=0) row.cut[neg.pos.row] <- 0
coords <- c(col.cut, row.cut)
names(coords) <- c('x1', 'x2', 'y1', 'y2')
final.crop <- cropped.binary[coords['y1']:coords['y2'], coords['x1']:coords['x2']]
.plotImage(final.crop, interpolate=FALSE,
main='Make sure you have enough space on the right of the number for 4 digits \n and also enough space on the left for string shift \n which only occurs if Exposure is not close to the left margin!')
abline(v=seq(0, 300, 10), col='blue')
abline(h=0:100, col='blue')
return(coords)
}
|
status_check <- function(req, as = "parsed", ...) {
if (status_code(req) %in% c("200", "201", "202", "204")) {
res <- content(req, as = as, ...)
if (!is.null(res)) {
attr(res, "response") <- req
}
return(res)
} else if (status_code(req) %in% c("401", "403", "404", "503")) {
msg <- content(req, as = as, ...)$message
stop(paste0("HTTP Status ", status_code(req), ": ", msg), call. = FALSE)
} else {
if ("message" %in% names(content(req, as = as, ...))) {
msg <- content(req, as = as, ...)$message
} else {
msg <- NULL
}
if (is.null(msg)) {
if (status_code(req) %in% names(.sb_api_status_code)) {
msg <- .sb_api_status_code[[status_code(req)]]
}
if (is.null(msg)) {
print(content(req, as = as, ...))
stop(paste("Error of unknown type occured", status_code(req)))
} else {
stop(paste0("HTTP Status ", status_code(req), ": ", msg), call. = FALSE)
}
} else {
stop(paste0("HTTP Status ", status_code(req), ": ", msg), call. = FALSE)
}
}
}
handle_url2 <- function(handle = NULL, url = NULL, ...) {
if (is.null(url) && is.null(handle)) {
stop("Must specify at least one of url or handle")
}
if (is.null(handle)) handle <- handle_find(url)
if (is.null(url)) url <- handle$url
new <- eval(parse(text = "httr:::named(list(...))"))
if (length(new) > 0 || eval(parse(text = "httr:::is.url(url)"))) {
old <- httr::parse_url(url)
url <- build_url2(modifyList(old, new))
}
list(handle = handle, url = url)
}
build_url2 <- function(url) {
stopifnot(eval(parse(text = "httr:::is.url(url)")))
scheme <- url$scheme
hostname <- url$hostname
if (!is.null(url$port)) {
port <- paste0(":", url$port)
}
else {
port <- NULL
}
path <- url$path
if (!is.null(url$params)) {
params <- paste0(";", url$params)
} else {
params <- NULL
}
if (is.list(url$query)) {
url$query <- eval(parse(text = "httr:::compact(url$query)"))
names <- curl_escape(names(url$query))
values <- as.character(url$query)
query <- paste0(names, "=", values, collapse = "&")
} else {
query <- url$query
}
if (!is.null(query)) {
stopifnot(is.character(query), length(query) == 1)
query <- paste0("?", query)
}
if (is.null(url$username) && !is.null(url$password)) {
stop("Cannot set password without username")
}
paste0(scheme, "://", url$username, if (!is.null(url$password)) {
":"
}, url$password, if (!is.null(url$username)) {
"@"
}, hostname, port, "/", path, params, query, if (!is.null(url$fragment)) {
"
}, url$fragment)
}
GET2 <- function(url = NULL, config = list(), ..., handle = NULL) {
hu <- handle_url2(handle, url, ...)
req <- eval(parse(text = 'httr:::request_build("GET", hu$url, config, ...)'))
return(eval(parse(text = "httr:::request_perform(req, hu$handle$handle)")))
}
POST2 <- function(url = NULL, config = list(), ...,
body = NULL, encode = c("json", "form", "multipart"),
multipart = TRUE, handle = NULL) {
if (!missing(multipart)) {
warning("multipart is deprecated, please use encode argument instead",
call. = FALSE
)
encode <- ifelse(multipart, "multipart", "form")
}
encode <- match.arg(encode)
hu <- handle_url2(handle, url, ...)
req <- eval(parse(text = 'httr:::request_build("POST", hu$url, httr:::body_config(body, encode), config, ...)'))
return(eval(parse(text = "httr:::request_perform(req, hu$handle$handle)")))
}
|
context("Climate data")
test_that("data.frame input of climate data is processed correctly", {
df <- data.frame(
year = rep(1950:2009, each = 12),
month = rep(1:12, 60),
temp = rep(-10 * cos(seq(0, 2*pi, length.out = 12)), 60),
prec = rep(seq(100, 220, length.out = 12), 60)
)
dfw <- rbind(df, data.frame(
year = 2010,
month = 1,
temp = -10,
prec = 100
))
dfp1 <- data.frame(cbind(1950:2009, matrix(df$prec, ncol = 12, byrow
= TRUE)))
dfp2 <- data.frame(cbind(1950:2009, matrix(df$temp, ncol = 12, byrow
= TRUE)))
dfpw <- rbind(dfp2, c(2008, rep(1, 12)))
expect_that(as_tcclimate(df), is_a("data.frame"))
expect_that(as_tcclimate(df)$temp,
equals(rep(-10 * cos(seq(0, 2*pi, length.out = 12)),
60)))
expect_that(as_tcclimate(dfw), throws_error())
expect_that(as_tcclimate(dfp1), is_a("data.frame"))
expect_that(as_tcclimate(dfp2)[,3],
equals(rep(-10 * cos(seq(0, 2*pi, length.out = 12)),
60)))
expect_that(as_tcclimate(list(dfp1, dfp2)), is_a("data.frame"))
expect_that(as_tcclimate(dfpw), throws_error())
expect_that(as_tcclimate(list(dfp1, dfpw)), throws_error())
})
|
context("calcFE")
library(testthat)
ped <- data.frame(
id = c("A", "B", "C", "D", "E", "F", "G"),
sire = c(NA, NA, "A", "A", NA, "D", "D"),
dam = c(NA, NA, "B", "B", NA, "E", "E"),
stringsAsFactors = FALSE
)
ped["gen"] <- findGeneration(ped$id, ped$sire, ped$dam)
ped$population <- getGVPopulation(ped, NULL)
pedFactors <- data.frame(
id = c("A", "B", "C", "D", "E", "F", "G"),
sire = c(NA, NA, "A", "A", NA, "D", "D"),
dam = c(NA, NA, "B", "B", NA, "E", "E"),
stringsAsFactors = TRUE
)
pedFactors["gen"] <- findGeneration(pedFactors$id, pedFactors$sire,
pedFactors$dam)
pedFactors$population <- getGVPopulation(pedFactors, NULL)
fe <- calcFE(ped)
feFactors <- calcFE(pedFactors)
test_that("calcFE correctly calculates the number of founder equivalents in
the pedigree", {
expect_equal(fe, feFactors)
expect_equal(fe, 2.9090909091)
})
|
summarize_ads <- function(ma_obj){
ma_metric <- attributes(ma_obj)$ma_metric
ma_methods <- attributes(ma_obj)$ma_methods
is_r <- any(ma_metric %in% c("r_as_r", "d_as_r"))
is_d <- any(ma_metric %in% c("r_as_d", "d_as_d"))
if((is_r | is_d) & (any(ma_methods == "ic") | any(ma_methods == "ad"))){
pairwise_ads <- attributes(ma_obj)$inputs$pairwise_ads[1]
if(any(ma_methods == "ad")){
ad_x <- lapply(ma_obj$ad, function(x) attributes(x$ad$ad_x)[["summary"]])
ad_y <- lapply(ma_obj$ad, function(x) attributes(x$ad$ad_y)[["summary"]])
}else{
ad_x <- lapply(ma_obj$ad, function(x) attributes(x$ic$ad_x_tsa)[["summary"]])
ad_y <- lapply(ma_obj$ad, function(x) attributes(x$ic$ad_y_tsa)[["summary"]])
}
if("pair_id" %in% colnames(ma_obj)){
pair_id <- ma_obj$pair_id
}else{
pair_id <- NULL
}
if("construct_x" %in% colnames(ma_obj)){
construct_x <- ma_obj$construct_x
}else{
construct_x <- NULL
}
if("construct_y" %in% colnames(ma_obj)){
construct_y <- ma_obj$construct_y
}else if("group_contrast" %in% colnames(ma_obj)){
construct_y <- ma_obj$construct_y
}else{
construct_y <- NULL
}
names(ad_x) <- construct_x
names(ad_y) <- construct_y
ad_list <- append(ad_x, ad_y)
if(pairwise_ads){
pair_names <- paste0("Pair ID = ", pair_id)
construct_vec <- c(paste0("X = ", construct_x),
paste0("Y = ", construct_y))
names(ad_list) <- paste0(c(pair_names, pair_names), ": ", construct_vec)
construct_pair <- paste0(paste0("X = ", c(construct_x, construct_x),
"; Y = ", c(construct_y, construct_y)))
var_names <- c(construct_x, construct_y)
}else{
construct_vec <- c(construct_x, construct_y)
dups <- duplicated(construct_vec)
ad_list[dups] <- NULL
names(ad_list) <- construct_vec[!dups]
construct_pair <- NULL
var_names <- names(ad_list)
}
ad_mat <- NULL
if(pairwise_ads) .construct_pair <- paste0(c(pair_names, pair_names), ": ", construct_pair)
for(i in 1:length(ad_list)){
ad_list[[i]] <- ad_list[[i]][,c("k_total", "N_total", "mean", "sd", "sd_res")]
ad_list[[i]] <- data.frame(Variable = var_names[i], Artifact = rownames(ad_list[[i]]), ad_list[[i]], stringsAsFactors = FALSE)
if(pairwise_ads) ad_list[[i]] <- data.frame(Construct_Pair = .construct_pair[i], ad_list[[i]], stringsAsFactors = FALSE)
ad_mat <- rbind(ad_mat, ad_list[[i]])
}
rownames(ad_mat) <- 1:nrow(ad_mat)
ad_mat <- add_column(ad_mat, Artifact_Description = recode(ad_mat$Artifact,
`qxa_irr` = "Unrestricted reliability index (indirect RR)",
`qxa_drr` = "Unrestricted reliability index (direct RR)",
`qxi_irr` = "Restricted reliability index (indirect RR)",
`qxi_drr` = "Restricted reliability index (direct RR)",
`rxxa_irr` = "Unrestricted reliability coefficient (indirect RR)",
`rxxa_drr` = "Unrestricted reliability coefficient (direct RR)",
`rxxi_irr` = "Restricted reliability coefficient (indirect RR)",
`rxxi_drr` = "Restricted reliability coefficient (direct RR)",
`ux` = "Observed-score u ratio",
`ut` = "True-score u ratio"), .after = "Artifact")
ad_mat[ad_mat$mean != 1 & ad_mat$sd != 0,]
}else{
NULL
}
}
|
pvalue.systematic <-
function(
design,
statistic,
save="no",
limit,
data=read.table(file.choose(new=FALSE)),
starts=file.choose(new=FALSE),
assignments=file.choose(new=FALSE)
){
statAB<-function(A,B)
{
return(mean(A,na.rm=TRUE)-mean(B,na.rm=TRUE))
}
statBA<-function(A,B)
{
return(mean(B,na.rm=TRUE)-mean(A,na.rm=TRUE))
}
statabsAB<-function(A,B)
{
return(abs(mean(A,na.rm=TRUE)-mean(B,na.rm=TRUE)))
}
statPAPB<-function(A1,B1,A2,B2)
{
return(mean(c(mean(A1,na.rm=TRUE),mean(A2,na.rm=TRUE)),na.rm=TRUE)-mean(c(mean(B1,na.rm=TRUE),mean(B2,na.rm=TRUE)),na.rm=TRUE))
}
statPBPA<-function(A1,B1,A2,B2)
{
return(mean(c(mean(B1,na.rm=TRUE),mean(B2,na.rm=TRUE)),na.rm=TRUE)-mean(c(mean(A1,na.rm=TRUE),mean(A2,na.rm=TRUE)),na.rm=TRUE))
}
statabsPAPB<-function(A1,B1,A2,B2)
{
return(abs(mean(c(mean(A1,na.rm=TRUE),mean(A2,na.rm=TRUE)),na.rm=TRUE)-mean(c(mean(B1,na.rm=TRUE),mean(B2,na.rm=TRUE)),na.rm=TRUE)))
}
if(design=="CRD"){
observed.a<-data[,2][data[,1]=="A"]
observed.b<-data[,2][data[,1]=="B"]
MT<-nrow(data)
quantity<-choose(MT,MT/2)
if(MT<=22){
if(save=="yes"){
file<-file.choose(new=FALSE)
}
observed<-data[,2]
scores.a<-combn(observed,MT/2)
distribution<-numeric(ncol(scores.a))
if(statistic %in% c("A-B","B-A","|A-B|")){
mean.a<-numeric(ncol(scores.a))
for(it in 1:ncol(scores.a)){
mean.a[it]<-mean(scores.a[,it],na.rm=TRUE)
}
mean.b<-rev(mean.a)
if(statistic=="A-B"){
for(it in 1:length(mean.a)){
distribution[it]<-mean.a[it]-mean.b[it]
}
observed.statistic<-statAB(observed.a,observed.b)
}
else if(statistic=="B-A"){
for(it in 1:length(mean.a)){
distribution[it]<-mean.b[it]-mean.a[it]
}
observed.statistic<-statBA(observed.a,observed.b)
}
else if(statistic=="|A-B|"){
for(it in 1:length(mean.a)){
distribution[it]<-abs(mean.a[it]-mean.b[it])
}
observed.statistic<-statabsAB(observed.a,observed.b)
}
}
else{
scores.b<-rev(scores.a)
dim(scores.b)<-c(MT/2,ncol(scores.a))
for(it in 1:ncol(scores.a)){
A<-scores.a[,it]
B<-scores.b[,it]
distribution[it]<-eval(parse(text=statistic))
}
A<-observed.a
B<-observed.b
observed.statistic<-eval(parse(text=statistic))
}
if(is.na(observed.statistic))
stop("Test statistic cannot be calculated. Please check the data.")
distribution<-sort(distribution)
test<-is.na(distribution)|(distribution>=observed.statistic)
p.value<-sum(test)/quantity
if(save=="yes"|save=="check"){
write.table(distribution,file=file,col.names=FALSE,row.names=FALSE)
}
return(p.value)
}
if(MT>22){
fileCRD<-tempfile(pattern="CRDassignments",tmpdir=tempdir())
file.a<-tempfile(pattern="ascores",tmpdir=tempdir())
file.b<-tempfile(pattern="bscores",tmpdir=tempdir())
if(save=="yes"){
file<-file.choose(new=FALSE)
}
N<-c(rep("A",MT/2),rep("B",MT/2))
assignment<-matrix(0,ncol=MT)
assignment<-rbind(sample(N,MT,replace=FALSE))
write.table(assignment,file=fileCRD,append=TRUE,col.names=FALSE,row.names=FALSE)
assignments<-read.table(fileCRD)
assignment<-as.vector(assignment)
score.a<-data[,2][assignment=="A"]
score.a<-t(as.matrix(score.a))
write.table(score.a,file=file.a,append=TRUE,col.names=FALSE,row.names=FALSE)
scores.a<-read.table(file.a)
score.b<-data[,2][assignment=="B"]
score.b<-t(as.matrix(score.b))
write.table(score.b,file=file.b,append=TRUE,col.names=FALSE,row.names=FALSE)
scores.b<-read.table(file.b)
repeat{
assignment<-matrix(0,ncol=MT)
assignment<-rbind(sample(N,MT,replace=FALSE))
copy<-numeric()
for(itr in 1:nrow(assignments)){
copy2<-numeric(MT)
for(it in 1:MT){
copy2[it]<-assignment[1,it]==assignments[itr,it]
}
copy<-c(copy,prod(copy2))
}
if(sum(copy)==0){
write.table(assignment,file=fileCRD,append=TRUE,col.names=FALSE,row.names=FALSE)
assignments<-read.table(fileCRD)
assignment<-as.vector(assignment)
score.a<-data[,2][assignment=="A"]
score.a<-t(as.matrix(score.a))
write.table(score.a,file=file.a,append=TRUE,col.names=FALSE,row.names=FALSE)
scores.a<-read.table(file.a)
score.b<-data[,2][assignment=="B"]
score.b<-t(as.matrix(score.b))
write.table(score.b,file=file.b,append=TRUE,col.names=FALSE,row.names=FALSE)
scores.b<-read.table(file.b)
}
if(nrow(assignments)==quantity)break
}
scores.a<-as.matrix(scores.a)
scores.b<-as.matrix(scores.b)
distribution<-numeric(quantity)
if(statistic=="A-B"){
for(it in 1:quantity){
distribution[it]<-statAB(scores.a[it,],scores.b[it,])
}
observed.statistic<-statAB(observed.a,observed.b)
}
else if(statistic=="B-A"){
for(it in 1:quantity){
distribution[it]<-statBA(scores.a[it,],scores.b[it,])
}
observed.statistic<-statBA(observed.a,observed.b)
}
else if(statistic=="|A-B|"){
for(it in 1:quantity){
distribution[it]<-statabsAB(scores.a[it,],scores.b[it,])
}
observed.statistic<-statabsAB(observed.a,observed.b)
}
else{
for(it in 1:quantity){
A<-scores.a[it,]
B<-scores.b[it,]
distribution[it]<-eval(parse(text=statistic))
}
A<-observed.a
B<-observed.b
observed.statistic<-eval(parse(text=statistic))
}
unlink(fileCRD,recursive=FALSE)
unlink(file.a,recursive=FALSE)
unlink(file.b,recursive=FALSE)
if(is.na(observed.statistic))
stop("Test statistic cannot be calculated. Please check the data.")
distribution<-sort(distribution)
test<-is.na(distribution)|(distribution>=observed.statistic)
p.value<-sum(test)/quantity
if(save=="yes"|save=="check"){
write.table(distribution,file=file,col.names=FALSE,row.names=FALSE)
}
return(p.value)
}
}
if(design=="RBD"){
observed.a<-data[,2][data[,1]=="A"]
observed.b<-data[,2][data[,1]=="B"]
MT<-nrow(data)
quantity<-2^(MT/2)
if(save=="yes"){
file<-file.choose(new=FALSE)
}
observed1<-rbind(observed.a,observed.b)
observed2<-rbind(observed.b,observed.a)
scores.a<-numeric()
for(it in 1:(MT/2)){
scores.a<-cbind(scores.a,cbind(rep(cbind(rep(observed1[,it],rep(2^it/2,2))),2^(MT/2)/2^it)))
}
scores.b<-numeric()
for(it in 1:(MT/2)){
scores.b<-cbind(scores.b,cbind(rep(cbind(rep(observed2[,it],rep(2^it/2,2))),2^(MT/2)/2^it)))
}
distribution<-numeric(quantity)
if(statistic=="A-B"){
for(it in 1:quantity){
distribution[it]<-statAB(scores.a[it,],scores.b[it,])
}
observed.statistic<-statAB(observed.a,observed.b)
}
else if(statistic=="B-A"){
for(it in 1:quantity){
distribution[it]<-statBA(scores.a[it,],scores.b[it,])
}
observed.statistic<-statBA(observed.a,observed.b)
}
else if(statistic=="|A-B|"){
for(it in 1:quantity){
distribution[it]<-statabsAB(scores.a[it,],scores.b[it,])
}
observed.statistic<-statabsAB(observed.a,observed.b)
}
else{
for(it in 1:quantity){
A<-scores.a[it,]
B<-scores.b[it,]
distribution[it]<-eval(parse(text=statistic))
}
A<-observed.a
B<-observed.b
observed.statistic<-eval(parse(text=statistic))
}
if(is.na(observed.statistic))
stop("Test statistic cannot be calculated. Please check the data.")
distribution<-sort(distribution)
test<-is.na(distribution)|(distribution>=observed.statistic)
p.value<-sum(test)/quantity
if(save=="yes"|save=="check"){
write.table(distribution,file=file,col.names=FALSE,row.names=FALSE)
}
return(p.value)
}
if(design=="ATD"){
observed.a<-data[,2][data[,1]=="A"]
observed.b<-data[,2][data[,1]=="B"]
MT<-nrow(data)
quantityCRD<-choose(MT,MT/2)
if(MT<=20){
if(save=="yes"){
file<-file.choose(new=FALSE)
}
index<-1:MT
index.a<-matrix(combn(index,(MT/2)),ncol=quantityCRD)
index.b<-matrix(index.a[,ncol(index.a):1],ncol=quantityCRD)
if(MT/2<=limit){
stop<-1:ncol(index.a)
}
if(MT/2>limit){
dist.a<-numeric()
for(it in 2:nrow(index.a)){
dist.a<-rbind(dist.a,index.a[it,]-index.a[it-1,])
}
dist.b<-numeric()
for(it in 2:nrow(index.b)){
dist.b<-rbind(dist.b,index.b[it,]-index.b[it-1,])
}
dist.check.a<-dist.a==1
dist.check.b<-dist.b==1
sum.a<-numeric()
for(itr in limit:nrow(dist.check.a)){
sum.a2<-0
for(itr2 in 1:limit){
sum.a2<-sum.a2+dist.check.a[itr-itr2+1,]
}
sum.a<-rbind(sum.a,sum.a2)
}
sum.b<-numeric()
for(itr in limit:nrow(dist.check.b)){
sum.b2<-0
for(itr2 in 1:limit){
sum.b2<-sum.b2 + dist.check.b[itr-itr2+1,]
}
sum.b<-rbind(sum.b,sum.b2)
}
sum.a.check<-sum.a==limit
sum.b.check<-sum.b==limit
sum.rows.a<-numeric(ncol(sum.a.check))
for(it in 1:ncol(sum.a.check)){
sum.rows.a[it]<-sum(sum.a.check[,it])
}
sum.rows.b<-numeric(ncol(sum.b.check))
for(it in 1:ncol(sum.b.check)){
sum.rows.b[it]<-sum(sum.b.check[,it])
}
check.stop<-sum.rows.a+sum.rows.b!=0
stop<-order(check.stop)[1:sum(check.stop==F)]
}
indexes.a<-numeric()
for(it in 1:length(stop)){
indexes.a<-rbind(indexes.a,index.a[,stop[it]])
}
indexes.b<-numeric()
for(it in 1:length(stop)){
indexes.b<-rbind(indexes.b,index.b[,stop[it]])
}
scores.a<-numeric()
for(it in 1:ncol(indexes.a)){
scores.a<-cbind(scores.a,data[,2][indexes.a[,it]])
}
scores.b<-numeric()
for(it in 1:ncol(indexes.b)){
scores.b<-cbind(scores.b,data[,2][indexes.b[,it]])
}
quantity<-nrow(scores.a)
distribution<-numeric(quantity)
if(statistic=="A-B"){
for(it in 1:quantity){
distribution[it]<-statAB(scores.a[it,],scores.b[it,])
}
observed.statistic<-statAB(observed.a,observed.b)
}
else if(statistic=="B-A"){
for(it in 1:quantity){
distribution[it]<-statBA(scores.a[it,],scores.b[it,])
}
observed.statistic<-statBA(observed.a,observed.b)
}
else if(statistic=="|A-B|"){
for(it in 1:quantity){
distribution[it]<-statabsAB(scores.a[it,],scores.b[it,])
}
observed.statistic<-statabsAB(observed.a,observed.b)
}
else{
for(it in 1:quantity){
A<-scores.a[it,]
B<-scores.b[it,]
distribution[it]<-eval(parse(text=statistic))
}
A<-observed.a
B<-observed.b
observed.statistic<-eval(parse(text=statistic))
}
if(is.na(observed.statistic))
stop("Test statistic cannot be calculated. Please check the data.")
distribution<-sort(distribution)
test<-is.na(distribution)|(distribution>=observed.statistic)
p.value<-sum(test)/quantity
if(save=="yes"|save=="check"){
write.table(distribution,file=file,row.names=FALSE,col.names=FALSE)
}
return(p.value)
}
if(MT>20){
fileCRD<-tempfile(pattern="CRDassignments",tmpdir=tempdir())
file.a<-tempfile(pattern="ascores",tmpdir=tempdir())
file.b<-tempfile(pattern="bscores",tmpdir=tempdir())
if(save=="yes"){
file<-file.choose(new=FALSE)
}
N<-c(rep(0,MT/2),rep(1,MT/2))
assignment<-matrix(0,ncol=MT)
assignment<-rbind(rep(c(0,1),MT/2))
write.table(assignment,file=fileCRD,append=TRUE,col.names=FALSE,row.names=FALSE)
CRD<-read.table(fileCRD)
for(it in 1:(length(assignment))){
if(assignment[,it]==0){
assignment[,it]<-"A"
}
else{
assignment[,it]<-"B"
}
}
assignment<-as.vector(assignment)
score.a<-data[,2][assignment=="A"]
score.a<-t(as.matrix(score.a))
write.table(score.a,file=file.a,append=TRUE,col.names=FALSE,row.names=FALSE)
scores.a<-read.table(file.a)
score.b<-data[,2][assignment=="B"]
score.b<-t(as.matrix(score.b))
write.table(score.b,file=file.b,append=TRUE,col.names=FALSE,row.names=FALSE)
scores.b<-read.table(file.b)
repeat{
assignment<-matrix(0,ncol=MT)
assignment<-rbind(sample(N,MT,replace=FALSE))
copy<-numeric()
for(itr in 1:nrow(CRD)){
copy2<-numeric(MT)
for(it in 1:MT){
copy2[it]<-assignment[1,it]==CRD[itr,it]
}
copy<-c(copy,prod(copy2))
}
if(sum(copy)==0){
write.table(assignment,file=fileCRD,append=TRUE,col.names=FALSE,row.names=FALSE)
CRD<-read.table(fileCRD)
check<-numeric()
for(itr in 1:(MT-limit)){
check2<-0
for(it in itr:(itr+limit)){
check2<-check2+assignment[,it]
}
check<-cbind(check,check2)
}
if(sum(check==(limit+1)|check==0)==0){
for(it in 1:(length(assignment))){
if(assignment[,it]==0){
assignment[,it]<-"A"
}
else{
assignment[,it]<-"B"
}
}
assignment<-as.vector(assignment)
score.a<-data[,2][assignment=="A"]
score.a<-t(as.matrix(score.a))
write.table(score.a,file=file.a,append=TRUE,col.names=FALSE,row.names=FALSE)
scores.a<-read.table(file.a)
score.b<-data[,2][assignment=="B"]
score.b<-t(as.matrix(score.b))
write.table(score.b,file=file.b,append=TRUE,col.names=FALSE,row.names=FALSE)
scores.b<-read.table(file.b)
}
}
if(nrow(CRD)==quantityCRD)break
}
unlink(fileCRD,recursive=FALSE)
unlink(file.a,recursive=FALSE)
unlink(file.b,recursive=FALSE)
scores.a<-as.matrix(scores.a)
scores.b<-as.matrix(scores.b)
quantity<-nrow(scores.a)
distribution<-numeric(quantity)
if(statistic=="A-B"){
for(it in 1:quantity){
distribution[it]<-statAB(scores.a[it,],scores.b[it,])
}
observed.statistic<-statAB(observed.a,observed.b)
}
else if(statistic=="B-A"){
for(it in 1:quantity){
distribution[it]<-statBA(scores.a[it,],scores.b[it,])
}
observed.statistic<-statBA(observed.a,observed.b)
}
else if(statistic=="|A-B|"){
for(it in 1:quantity){
distribution[it]<-statabsAB(scores.a[it,],scores.b[it,])
}
observed.statistic<-statabsAB(observed.a,observed.b)
}
else{
for(it in 1:quantity){
A<-scores.a[it,]
B<-scores.b[it,]
distribution[it]<-eval(parse(text=statistic))
}
A<-observed.a
B<-observed.b
observed.statistic<-eval(parse(text=statistic))
}
if(is.na(observed.statistic))
stop("Test statistic cannot be calculated. Please check the data.")
distribution<-sort(distribution)
test<-is.na(distribution)|(distribution>=observed.statistic)
p.value<-sum(test)/quantity
if(save=="yes"|save=="check"){
write.table(distribution,file=file,col.names=FALSE,row.names=FALSE)
}
return(p.value)
}
}
if(design=="AB"){
observed.a<-data[,2][data[,1]=="A"]
observed.b<-data[,2][data[,1]=="B"]
observed<-data[,2]
MT<-nrow(data)
quantity<-choose(MT-2*limit+1,1)
if(save=="yes"){
file<-file.choose(new=FALSE)
}
index.a<-limit:(MT-limit)
scores.a<-list()
for(it in 1:quantity){
scores.a[[it]]<-c(observed[1:index.a[it]])
}
scores.b<-list()
for(it in 1:quantity){
scores.b[[it]]<-c(observed[(index.a[it]+1):MT])
}
distribution<-numeric(quantity)
if(statistic=="A-B"){
for(it in 1:quantity){
distribution[it]<-statAB(scores.a[[it]],scores.b[[it]])
}
observed.statistic<-statAB(observed.a,observed.b)
}
else if(statistic=="B-A"){
for(it in 1:quantity){
distribution[it]<-statBA(scores.a[[it]],scores.b[[it]])
}
observed.statistic<-statBA(observed.a,observed.b)
}
else if(statistic=="|A-B|"){
for(it in 1:quantity){
distribution[it]<-statabsAB(scores.a[[it]],scores.b[[it]])
}
observed.statistic<-statabsAB(observed.a,observed.b)
}
else{
for(it in 1:quantity){
A<-scores.a[[it]]
B<-scores.b[[it]]
distribution[it]<-eval(parse(text=statistic))
}
A<-observed.a
B<-observed.b
observed.statistic<-eval(parse(text=statistic))
}
if(is.na(observed.statistic))
stop("Test statistic cannot be calculated. Please check the data.")
distribution<-sort(distribution)
test<-is.na(distribution)|(distribution>=observed.statistic)
p.value<-sum(test)/quantity
if(save=="yes"|save=="check"){
write.table(distribution,file=file,col.names=FALSE,row.names=FALSE,append=FALSE)
}
return(p.value)
}
if(design=="ABA"){
observed.a1<-data[,2][data[,1]=="A1"]
observed.b1<-data[,2][data[,1]=="B1"]
observed.a2<-data[,2][data[,1]=="A2"]
observed.a<-c(observed.a1,observed.a2)
observed<-data[,2]
MT<-nrow(data)
quantity<-choose(MT-3*limit+2,2)
if(save=="yes"){
file<-file.choose(new=FALSE)
}
index1<-1:(MT-3*limit+1)
index2<-rev(index1)
index.a<-numeric()
for(it in 1:length(index1)){
index.a<-c(index.a,(rep((limit-1+index1[it]),index2[it])))
}
scores.a1<-list()
for(it in 1:quantity){
scores.a1[[it]]<-c(observed[1:(index.a[it])])
}
index.b<-numeric()
for(itr in index1){
for(it in itr:(MT-3*limit+1)){
index.b<-c(index.b,2*limit-1+it)
}
}
scores.b1<-list()
for(it in 1:quantity){
scores.b1[[it]]<-c(observed[(index.a[it]+1):(index.b[it])])
}
scores.a2<-list()
for(it in 1:quantity){
scores.a2[[it]]<-c(observed[(index.b[it]+1):(MT)])
}
scores.a<-list()
for(it in 1:quantity){
scores.a[[it]]<-c(scores.a1[[it]],scores.a2[[it]])
}
distribution<-numeric(quantity)
if(statistic=="A-B"){
for(it in 1:quantity){
distribution[it]<-statAB(scores.a[[it]],scores.b1[[it]])
}
observed.statistic<-statAB(observed.a,observed.b1)
}
else if(statistic=="B-A"){
for(it in 1:quantity){
distribution[it]<-statBA(scores.a[[it]],scores.b1[[it]])
}
observed.statistic<-statBA(observed.a,observed.b1)
}
else if(statistic=="|A-B|"){
for(it in 1:quantity){
distribution[it]<-statabsAB(scores.a[[it]],scores.b1[[it]])
}
observed.statistic<-statabsAB(observed.a,observed.b1)
}
else if(statistic=="PA-PB"){
for(it in 1:quantity){
distribution[it]<-statPAPB(scores.a1[[it]],scores.b1[[it]],scores.a2[[it]],NA)
}
observed.statistic<-statPAPB(observed.a1,observed.b1,observed.a2,NA)
}
else if(statistic=="PB-PA"){
for(it in 1:quantity){
distribution[it]<-statPBPA(scores.a1[[it]],scores.b1[[it]],scores.a2[[it]],NA)
}
observed.statistic<-statPBPA(observed.a1,observed.b1,observed.a2,NA)
}
else if(statistic=="|PA-PB|"){
for(it in 1:quantity){
distribution[it]<-statabsPAPB(scores.a1[[it]],scores.b1[[it]],scores.a2[[it]],NA)
}
observed.statistic<-statabsPAPB(observed.a1,observed.b1,observed.a2,NA)
}
else{
for(it in 1:quantity){
A1<-scores.a1[[it]]
B1<-scores.b1[[it]]
A2<-scores.a2[[it]]
A<-scores.a[[it]]
B<-scores.b1[[it]]
distribution[it]<-eval(parse(text=statistic))
}
A1<-observed.a1
B1<-observed.b1
A2<-observed.a2
A<-observed.a
B<-observed.b1
observed.statistic<-eval(parse(text=statistic))
}
if(is.na(observed.statistic))
stop("Test statistic cannot be calculated. Please check the data.")
distribution<-sort(distribution)
test<-is.na(distribution)|(distribution>=observed.statistic)
p.value<-sum(test)/quantity
if(save=="yes"|save=="check"){
write.table(distribution,file=file,col.names=FALSE,row.names=FALSE,append=FALSE)
}
return(p.value)
}
if(design=="ABAB"){
observed.a1<-data[,2][data[,1]=="A1"]
observed.b1<-data[,2][data[,1]=="B1"]
observed.a2<-data[,2][data[,1]=="A2"]
observed.b2<-data[,2][data[,1]=="B2"]
observed.a<-c(observed.a1,observed.a2)
observed.b<-c(observed.b1,observed.b2)
observed<-data[,2]
MT<-nrow(data)
quantity<-choose(MT-4*limit+3,3)
if(save=="yes"){
file<-file.choose(new=FALSE)
}
index1<-1:(MT-4*limit+1)
index2<-rev(cumsum(index1))
index.a1<-numeric()
for(it in 1:length(index1)){
index.a1<-c(index.a1,(rep((limit+index1[it]-1),index2[it])))
}
scores.a1<-list()
for(it in 1:quantity){
scores.a1[[it]]<-c(observed[1:(index.a1[it])])
}
index.b1<-numeric()
for(itr in index1){
for(it in (itr-1):(MT-4*limit)){
index.b1<-c(index.b1,rep((2*limit+it),(MT-4*limit+1-it)))
}
}
scores.b1<-list()
for(it in 1:quantity){
scores.b1[[it]]<-c(observed[(1+index.a1[it]):index.b1[it]])
}
indexa2<-numeric()
for(it in 1:length(index1)){
indexa2<-c(indexa2,(index1[it]:length(index1)))
}
index.a2<-numeric()
for(it in 1:length(indexa2)){
index.a2<-c(index.a2,(4*limit-limit-1+(indexa2[it]:length(index1))))
}
scores.a2<-list()
for(it in 1:quantity){
scores.a2[[it]]<-c(observed[(1+index.b1[it]):index.a2[it]])
}
scores.b2<-list()
for(it in 1:quantity){
scores.b2[[it]]<-c(observed[(1+index.a2[it]):MT])
}
scores.a<-list()
for(it in 1:quantity){
scores.a[[it]]<-c(scores.a1[[it]],scores.a2[[it]])
}
scores.b<-list()
for(it in 1:quantity){
scores.b[[it]]<-c(scores.b1[[it]],scores.b2[[it]])
}
distribution<-numeric(quantity)
if(statistic=="A-B"){
for(it in 1:quantity){
distribution[it]<-statAB(scores.a[[it]],scores.b[[it]])
}
observed.statistic<-statAB(observed.a,observed.b)
}
else if(statistic=="B-A"){
for(it in 1:quantity){
distribution[it]<-statBA(scores.a[[it]],scores.b[[it]])
}
observed.statistic<-statBA(observed.a,observed.b)
}
else if(statistic=="|A-B|"){
for(it in 1:quantity){
distribution[it]<-statabsAB(scores.a[[it]],scores.b[[it]])
}
observed.statistic<-statabsAB(observed.a,observed.b)
}
else if(statistic=="PA-PB"){
for(it in 1:quantity){
distribution[it]<-statPAPB(scores.a1[[it]],scores.b1[[it]],scores.a2[[it]],scores.b2[[it]])
}
observed.statistic<-statPAPB(observed.a1,observed.b1,observed.a2,observed.b2)
}
else if(statistic=="PB-PA"){
for(it in 1:quantity){
distribution[it]<-statPBPA(scores.a1[[it]],scores.b1[[it]],scores.a2[[it]],scores.b2[[it]])
}
observed.statistic<-statPBPA(observed.a1,observed.b1,observed.a2,observed.b2)
}
else if(statistic=="|PA-PB|"){
for(it in 1:quantity){
distribution[it]<-statabsPAPB(scores.a1[[it]],scores.b1[[it]],scores.a2[[it]],scores.b2[[it]])
}
observed.statistic<-statabsPAPB(observed.a1,observed.b1,observed.a2,observed.b2)
}
else{
for(it in 1:quantity){
A1<-scores.a1[[it]]
B1<-scores.b1[[it]]
A2<-scores.a2[[it]]
B2<-scores.b2[[it]]
A<-scores.a[[it]]
B<-scores.b[[it]]
distribution[it]<-eval(parse(text=statistic))
}
A1<-observed.a1
B1<-observed.b1
A2<-observed.a2
B2<-observed.b2
A<-observed.a
B<-observed.b
observed.statistic<-eval(parse(text=statistic))
}
if(is.na(observed.statistic))
stop("Test statistic cannot be calculated. Please check the data.")
distribution<-sort(distribution)
test<-is.na(distribution)|(distribution>=observed.statistic)
p.value<-sum(test)/quantity
if(save=="yes"|save=="check"){
write.table(distribution,file=file,col.names=FALSE,row.names=FALSE,append=FALSE)
}
return(p.value)
}
if(design=="MBD"){
N<-ncol(data)/2
MT<-nrow(data)
readLines(con=starts,n=N)->startpoints
limits<-strsplit(startpoints,"\\s")
limits<-lapply(limits,function(x){x[x!=""]})
number<-numeric(N)
for(it in 1:N){
number[it]<-length(limits[[it]])
}
coord<-list()
for(itr in 1:length(number)){
cor<-numeric()
for(it in 1:number[itr]){
cor<-c(cor,paste(itr,it,sep=""))
}
coord[[itr]]<-cor
}
startpt<-numeric(N)
for(it in 1:N){
if(number[it]!=1){
startpt[it]<-sample(coord[[it]],1)
}
else{
startpt[it]<-coord[[it]]
}
}
fileSTARTPTS<-tempfile(pattern="startpoints",tmpdir=tempdir())
startpt1<-rbind(startpt)
write.table(startpt1,file=fileSTARTPTS,append=TRUE,col.names=FALSE,row.names=FALSE)
startpts<-read.table(fileSTARTPTS)
repeat{
startpt<-numeric(N)
for(it in 1:N){
if(number[it]!=1){
startpt[it]<-sample(coord[[it]],1)
}
else{
startpt[it]<-coord[[it]]
}
}
copy<-numeric()
for(itr in 1:nrow(startpts)){
copy2<-numeric(N)
for(it in 1:N){
copy2[it]<-startpt[it]==startpts[itr,it]
}
copy<-c(copy,prod(copy2))
}
if(sum(copy)==0){
startpt1<-rbind(startpt)
write.table(startpt1,file=fileSTARTPTS,append=TRUE,col.names=FALSE,row.names=FALSE)
startpts<-read.table(fileSTARTPTS)
}
if(nrow(startpts)==prod(number))break
}
fileCOMBSTARTPOINTS<-tempfile(pattern="combstartpoints",tmpdir=tempdir())
combstartpts1<-sample(startpts[1,],replace=FALSE)
write.table(combstartpts1,file=fileCOMBSTARTPOINTS,append=TRUE,col.names=FALSE,row.names=FALSE)
combstartpts<-read.table(fileCOMBSTARTPOINTS)
for(iter in 1:nrow(startpts)){
repeat{
combstartpts1<-sample(startpts[iter,],replace=FALSE)
copy<-numeric()
for(itr in 1:nrow(combstartpts)){
copy2<-numeric(N)
for(it in 1:N){
copy2[it]<-combstartpts1[it]==combstartpts[itr,it]
}
copy<-c(copy,prod(copy2))
}
if(sum(copy)==0){
write.table(combstartpts1,file=fileCOMBSTARTPOINTS,append=TRUE,col.names=FALSE,row.names=FALSE)
combstartpts<-read.table(fileCOMBSTARTPOINTS)
}
if(nrow(combstartpts)==iter*factorial(N))break
}
}
for(itrow in 1:nrow(combstartpts)){
for(itcol in 1:ncol(combstartpts)){
for(it in 1:N){
for(itr in 1:number[it]){
if(combstartpts[itrow,itcol]==coord[[it]][itr]){combstartpts[itrow,itcol]<-limits[[it]][itr]}
}
}
}
}
fileASSIGNMENTS<-tempfile(pattern="assignments",tmpdir=tempdir())
write.table(combstartpts,file=fileASSIGNMENTS,col.names=FALSE,row.names=FALSE)
assignments<-read.table(fileASSIGNMENTS)
unlink(fileSTARTPTS,recursive=FALSE)
unlink(fileCOMBSTARTPOINTS,recursive=FALSE)
unlink(fileASSIGNMENTS,recursive=FALSE)
observed.a<-list()
for(it in 1:N){
observed.a[[it]]<-data[,it*2][data[,(it*2)-1]=="A"]
}
observed.b<-list()
for(it in 1:N){
observed.b[[it]]<-data[,it*2][data[,(it*2)-1]=="B"]
}
differences<-numeric(N)
if(statistic=="A-B"){
for(it in 1:N){
differences[it]<-statAB(observed.a[[it]],observed.b[[it]])
}
}
else if(statistic=="B-A"){
for(it in 1:N){
differences[it]<-statBA(observed.a[[it]],observed.b[[it]])
}
}
else if(statistic=="|A-B|"){
for(it in 1:N){
differences[it]<-statabsAB(observed.a[[it]],observed.b[[it]])
}
}
else{
for(it in 1:N){
A<-observed.a[[it]]
B<-observed.b[[it]]
differences[it]<-eval(parse(text=statistic))
}
}
observed.statistic<-mean(differences,na.rm=TRUE)
scores.a<-list()
for(iter in 1:nrow(assignments)){
ascores<-list()
for(it in 1:N){
ascores[[it]]<-data[1:(assignments[iter,it]-1),it*2]
}
scores.a[[iter]]<-ascores
}
scores.b<-list()
for(iter in 1:nrow(assignments)){
bscores<-list()
for(it in 1:N){
bscores[[it]]<-data[assignments[iter,it]:MT,it*2]
}
scores.b[[iter]]<-bscores
}
differs<-list()
if(statistic=="A-B"){
for(iter in 1:nrow(assignments)){
differ<-numeric(N)
for(it in 1:N){
differ[it]<-statAB(scores.a[[iter]][[it]],scores.b[[iter]][[it]])
}
differs[[iter]]<-differ
}
}
else if(statistic=="B-A"){
for(iter in 1:nrow(assignments)){
differ<-numeric(N)
for(it in 1:N){
differ[it]<-statBA(scores.a[[iter]][[it]],scores.b[[iter]][[it]])
}
differs[[iter]]<-differ
}
}
else if(statistic=="|A-B|"){
for(iter in 1:nrow(assignments)){
differ<-numeric(N)
for(it in 1:N){
differ[it]<-statabsAB(scores.a[[iter]][[it]],scores.b[[iter]][[it]])
}
differs[[iter]]<-differ
}
}
else{
for(iter in 1:nrow(assignments)){
differ<-numeric(N)
for(it in 1:N){
A<-scores.a[[iter]][[it]]
B<-scores.b[[iter]][[it]]
differ[it]<-eval(parse(text=statistic))
}
differs[[iter]]<-differ
}
}
distribution<-numeric(nrow(assignments))
for(it in 1:nrow(assignments)){
distribution[it]<-mean(differs[[it]],na.rm=TRUE)
}
if(is.na(observed.statistic))
stop("Test statistic cannot be calculated. Please check the data.")
distribution<-sort(distribution)
test<-is.na(distribution)|(distribution>=observed.statistic)
p.value<-sum(test)/nrow(assignments)
if(save=="yes"){
fileSAVE<-file.choose(new=FALSE)
}
if(save=="yes"|save=="check"){
write.table(distribution,file=fileSAVE,col.names=FALSE,row.names=FALSE,append=FALSE)
}
return(p.value)
}
if(design=="Custom"){
if(save=="yes"){
file<-file.choose(new=FALSE)
}
observed<-data[,2]
observed.a<-data[,2][data[,1]=="A"]
observed.b<-data[,2][data[,1]=="B"]
assignments<-read.table(assignments)
quantity<-nrow(assignments)
scores.a<-list()
for(it in 1:quantity)
scores.a[[it]]<-c(observed[assignments[it,]=="A"])
scores.b<-list()
for(it in 1:quantity)
scores.b[[it]]<-c(observed[assignments[it,]=="B"])
distribution<-numeric(quantity)
if(statistic=="A-B"){
for(it in 1:quantity)
distribution[it]<-statAB(scores.a[[it]],scores.b[[it]])
observed.statistic<-statAB(observed.a,observed.b)
}
else if(statistic=="B-A"){
for(it in 1:quantity)
distribution[it]<-statBA(scores.a[[it]],scores.b[[it]])
observed.statistic<-statBA(observed.a,observed.b)
}
else if(statistic=="|A-B|"){
for(it in 1:quantity)
distribution[it]<-statabsAB(scores.a[[it]],scores.b[[it]])
observed.statistic<-statabsAB(observed.a,observed.b)
}
else{
for(it in 1:quantity){
A<-scores.a[[it]]
B<-scores.b[[it]]
distribution[it]<-eval(parse(text=statistic))
}
A<-observed.a
B<-observed.b
observed.statistic<-eval(parse(text=statistic))
}
if(is.na(observed.statistic))
stop("Test statistic cannot be calculated. Please check the data.")
distribution<-sort(distribution)
test<-is.na(distribution)|(distribution>=observed.statistic)
p.value<-sum(test)/quantity
if(save=="yes")
write.table(distribution,file=file,col.names=FALSE,row.names=FALSE,append=FALSE)
return(p.value)
}
}
|
independence_table <- function(x, frequency = c("absolute", "relative")) {
if (!is.array(x))
stop("Need array of absolute frequencies!")
frequency <- match.arg(frequency)
n <- sum(x)
x <- x / n
d <- dim(x)
margins <- lapply(1:length(d), function(i) apply(x, i, sum))
tab <- array(apply(expand.grid(margins), 1, prod), d, dimnames = dimnames(x))
if (frequency == "relative") tab else tab * n
}
mar_table <- function(x) {
if(!is.matrix(x))
stop("Function only defined for 2-way tables.")
tab <- rbind(cbind(x, TOTAL = rowSums(x)), TOTAL = c(colSums(x), sum(x)))
names(dimnames(tab)) <- names(dimnames(x))
tab
}
table2d_summary <- function(object,
margins = TRUE,
percentages = FALSE,
conditionals = c("none", "row", "column"),
chisq.test = TRUE,
...
)
{
ret <- list()
if (chisq.test)
ret$chisq <- summary.table(object, ...)
if(is.matrix(object)) {
conditionals <- match.arg(conditionals)
tab <- array(0, c(dim(object) + margins, 1 + percentages + (conditionals != "none")))
tab[,,1] <- if(margins) mar_table(object) else object
if(percentages) {
tmp <- prop.table(object)
tab[,,2] <- 100 * if(margins) mar_table(tmp) else tmp
}
if(conditionals != "none") {
tmp <- prop.table(object, margin = 1 + (conditionals == "column"))
tab[,,2 + percentages] <- 100 * if(margins) mar_table(tmp) else tmp
}
dimnames(tab) <- c(dimnames(if(margins) mar_table(object) else object),
list(c("freq",
if(percentages) "%",
switch(conditionals, row = "row%", column = "col%")
)
)
)
if(conditionals == "row")
tab[dim(tab)[1],,2 + percentages] <- NA
if(conditionals == "column")
tab[,dim(tab)[2],2 + percentages] <- NA
ret$table <- tab
}
class(ret) <- "table2d_summary"
ret
}
print.table2d_summary <-
function (x, digits = max(1, getOption("digits") - 3), ...)
{
if (!is.null(x$table))
if(dim(x$table)[3] == 1)
print(x$table[,,1], digits = digits, ...)
else
print(ftable(aperm(x$table, c(1,3,2))), 2, digits = digits, ...)
cat("\n")
if (!is.null(x$chisq))
print.summary.table(x$chisq, digits, ...)
invisible(x)
}
|
FRCSnumStarts<-function(p,gamma=0.99,eps=0.5){
if(p>25) stop("p too large.")
if(gamma>=1) stop("gamma should be smaller than 1.")
if(gamma<=0) stop("gamma should be larger than 0.")
if(eps>0.5) stop("eps should be smaller than 1/2.")
if(eps<=0) stop("eps should be larger than 0.")
ns0<-ceiling(log(1-gamma)/log(1-(1-(eps))^(p+1)))
ord<-10^floor(log10(ns0))
max(100,ceiling(ns0/ord)*ord)
}
FastRCS<-function(x,y,nSamp=NULL,alpha=0.5,seed=1,intercept=1){
k1<-25;k0<-25;J<-3;
m1<-"seed should be an integer in [0,2**31]."
if(!is.null(seed)){
if(!is.finite(seed)) stop(m1)
if(!is.numeric(seed)) stop(m1)
if(seed<0) stop(m1)
if(is.na(as.integer(seed))) stop(m1)
}
seed<-as.integer(seed)+1
x<-data.matrix(x)
y<-data.matrix(y)
na.x<-complete.cases(cbind(x,y))
if(!is.numeric(alpha)) stop("alpha should be numeric")
if(alpha<0.5 | alpha>=1)stop("alpha should be in (0.5,1(.")
if(sum(na.x)!=nrow(x)) stop("Your data contains NA.")
if(nrow(x)<(5*ncol(x))) stop("n<5p. You need more observations")
if(intercept){
cx<-cbind(1,x)
} else {
cx<-x
}
n<-nrow(cx)
if(nrow(unique(cbind(x,y)))<n) stop("Your dataset contains duplicated rows. Please remove them.")
p<-ncol(cx)
if(p<2) stop("Univariate RCS is not implemented.")
if(p>25) stop("FastRCS only works for dimensions <=25.")
if(is.null(nSamp)) nSamp<-FRCSnumStarts(p,eps=(1-alpha))
h1<-min(n-1,quanf(n=n,p=p,alpha=alpha))
h0<-quanf(n=n,p=p,alpha=0.5);
Dp<-rep(1.00,n);
k0<-max(k0,p+2);
k1<-max(k1,p+2);
objfunC<-1e3;
n1<-rep(0,h0);
n2<-rep(0,h1)
icandid<-1:n-1
ni<-length(icandid)
fitd<-.C("fastrcs",
as.integer(nrow(cx)),
as.integer(ncol(cx)),
as.integer(k0),
as.single(cx),
as.single(y),
as.integer(k1),
as.single(Dp),
as.integer(nSamp),
as.integer(J),
as.single(objfunC),
as.integer(seed),
as.integer(icandid),
as.integer(ni),
as.integer(n1),
as.integer(n2),
as.integer(h0),
as.integer(h1),
PACKAGE="FastRCS")
outd<-as.numeric(fitd[[7]])
if(is.nan(outd)[1]) stop("too many singular subsets encoutered!")
best<-fitd[[15]]
weit<-as.numeric((1:n)%in%best)
rawC<-lm(y~x,weights=weit)
weit<-as.numeric(abs(rawC$resid)/quantile(abs(rawC$resid),h1/n)/qnorm(1-alpha/2)<=sqrt(qchisq(0.975,df=1)))
FinalFit<-lm(y~x,weights=weit);
FinalFit$scale<-sqrt(sum(FinalFit$resid[weit==1]**2)/FinalFit$df)
A1<-list(alpha=alpha,nSamp=nSamp,obj=as.numeric(fitd[[10]]),rawBest=fitd[[14]],rawDist=fitd[[7]],
best=which(weit==1),coefficients=FinalFit$coef,fitted.values=FinalFit$fitted.values,residuals=FinalFit$residuals, rank=FinalFit$rank,weights=FinalFit$weights,df.residual=FinalFit$df.residual,scale=FinalFit$scale)
class(A1) <-"FastRCS"
return(A1)
}
quanf<-function(n,p,alpha) return(floor(2*floor((n+p+1)/2)-n+2*(n-floor((n+p+1)/2))*alpha))
plot.FastRCS<-function(x,col="black",pch=16,...){
plot(abs(x$resid)/x$scale,col=col,pch=pch,ylab="Robust standardized residuals",xlab="Index")
abline(h=sqrt(qchisq(0.975,df=1)),col="red",lty=2)
}
|
plot.dccm <-function(x, resno=NULL, sse=NULL, colorkey=TRUE,
at=c(-1, -0.75, -0.5, -0.25, 0.25, 0.5, 0.75, 1),
main="Residue Cross Correlation",
helix.col = "gray20", sheet.col = "gray80",
inner.box=TRUE, outer.box=FALSE,
xlab="Residue No.", ylab="Residue No.",
margin.segments=NULL, segment.col=vmd_colors(),
segment.min=1, ...) {
requireNamespace("lattice", quietly = TRUE)
colnames(x) = NULL; rownames(x)=NULL
if(!is.null(resno)) {
if(is.pdb(resno)) {
ca.inds <- atom.select(resno, "calpha", verbose = FALSE)
resno <- resno$atom$resno[ca.inds$atom]
}
if(length(resno) != nrow(x)) {
warning("Length of input 'resno' does not equal the length of input 'x'; Ignoring 'resno'")
resno=NULL
}
}
scales <- NULL
dots <- list(...)
if('scales' %in% names(dots)) {
scales <- dots$scales
}
if(!"at" %in% names(scales)) {
xy.at <- pretty(1:ncol(x))
xy.at <- xy.at[xy.at <= ncol(x)]
xy.at[1] <- 1
if(is.null(resno)) {
scales$at <- xy.at
scales$labels <- xy.at
} else {
labs <- resno[xy.at]
labs[is.na(labs)] <- ""
scales$at <- xy.at
scales$labels <- labs
}
}
dots$scales <- scales
draw.segment <- function(start, length, xymin, xymax, fill.col="gray", side=1) {
if(side==1) {
grid.rect(x=unit(start-0.5, "native"),
y=0,
gp = gpar(fill=fill.col, col=NA),
just=c("left","bottom"),
width=unit(length-0.5, "native"),
height=xymin,
vp=vpPath("plot_01.toplevel.vp","plot_01.panel.1.1.vp"))
}
if(side==2) {
grid.rect(x=0,
y=unit(start-0.5, "native"),
gp = gpar(fill=fill.col, col=NA),
just=c("left","bottom"),
width=xymin,
height=unit(length-0.5, "native"),
vp=vpPath("plot_01.toplevel.vp","plot_01.panel.1.1.vp"))
}
if(side==3) {
grid.rect(x=unit(start-0.5, "native"),
y=xymax,
gp = gpar(fill=fill.col,col=NA),
just=c("left","bottom"),
width=unit(length-0.5, "native"),
height=unit(1, "npc"),
vp=vpPath("plot_01.toplevel.vp","plot_01.panel.1.1.vp"))
}
if(side==4) {
grid.rect(x=xymax,
y=unit(start-0.5, "native"),
gp = gpar(fill=fill.col,col=NA),
just=c("left","bottom"),
width=unit(1, "npc"),
height=unit(length-0.5, "native"),
vp=vpPath("plot_01.toplevel.vp","plot_01.panel.1.1.vp"))
}
}
p1 <- do.call(lattice::contourplot, c(list(x, region = TRUE, labels=FALSE, col="gray40",
at=at, xlab=xlab, ylab=ylab,
colorkey=colorkey, main=main), dots))
if(is.pdb(sse)) {
sse <- pdb2sse(sse)
sse <- bounds.sse(unname(sse))
}
if(length(sse$helix$start)==0 &&
length(sse$sheet$start)==0)
sse <- NULL
xymin=0; xymax=1
if (is.null(sse) && is.null(margin.segments)) {
print(p1)
} else {
xlim <- p1$x.limits
ylim <- p1$y.limits
uni <- 1/(max(xlim)-min(xlim))
pad=0.02
padref <- pad/uni
if(!is.null(sse)) {
xymax <- 1-(pad)
p1$x.limits[2]=xlim[2]+padref
p1$y.limits[2]=ylim[2]+padref
}
if(!is.null(margin.segments)) {
xymin = pad
p1$x.limits[1]=xlim[1]-padref
p1$y.limits[1]=ylim[1]-padref
grps <- table(margin.segments)
grps = names( grps[grps > segment.min] )
store.grps <- NULL;
for(i in 1:length(grps)) {
store.grps <- rbind(store.grps,
cbind( bounds(which(margin.segments == grps[i])),
"grp"=as.numeric(grps[i])) )
}
if(is.null(segment.col)) {
segment.col <- (store.grps[,"grp"])
} else {
segment.col <- segment.col[(store.grps[,"grp"])]
}
}
print(p1)
if(!is.null(sse)) {
if(length(sse$helix$start) > 0) {
if( is.null(sse$helix$length) ) {
sse$helix$length <- (sse$helix$end+1)-sse$helix$start
}
draw.segment(sse$helix$start, sse$helix$length,
xymin=xymin, xymax=xymax, fill.col=helix.col, side=3)
draw.segment(sse$helix$start, sse$helix$length,
xymin=xymin, xymax=xymax, fill.col=helix.col, side=4)
}
if(length(sse$sheet$start) > 0) {
if( is.null(sse$sheet$length) ) {
sse$sheet$length <- (sse$sheet$end+1)-sse$sheet$start
}
draw.segment(sse$sheet$start, sse$sheet$length,
xymin=xymin, xymax=xymax, fill.col=sheet.col, side=3)
draw.segment(sse$sheet$start, sse$sheet$length,
xymin=xymin, xymax=xymax, fill.col=sheet.col, side=4)
}
}
if(!is.null(margin.segments)) {
draw.segment(store.grps[,"start"], store.grps[,"length"],
xymin=xymin, xymax=xymax, fill.col=segment.col, side=1)
draw.segment(store.grps[,"start"], store.grps[,"length"],
xymin=xymin, xymax=xymax, fill.col=segment.col, side=2)
}
if(!outer.box) {
grid.rect(x=0, y=0,
gp = gpar(fill=NA,col="white"),
just=c("left","bottom"),
width=1,height=1,
vp=vpPath("plot_01.toplevel.vp","plot_01.panel.1.1.vp"))
}
if(inner.box) {
grid.rect(x=xymin, y=xymin,
gp = gpar(fill=NA,col="black"),
just=c("left","bottom"),
width=xymax, height=xymax,
vp=vpPath("plot_01.toplevel.vp","plot_01.panel.1.1.vp"))
}
}
}
|
memesSujets <-
function(matDon,matPond){
nbPond <- nrow(matPond)
i <- 1
nbSujets <- nrow(matDon)
nbVar <- ncol(matDon) - 2
somme <- rep(0, nbSujets)
while (i <= nbPond){
matDonMemes <- t(apply(matDon, MARGIN=1, FUN=appliquePonder, c(1, 1, matPond[i, 1:nbVar])))
matDonMemes <- cbind(matDonMemes[,1:2], score=round(apply(matDonMemes[,3:ncol(matDonMemes)], MARGIN=1, FUN=sum), 7))
matDonMemes <- repereRisque(matDonMemes, matPond[i, "seuil"])
somme <- somme + matDonMemes[,"risque"]
i <- i + 1
}
Memes <- length(which(somme!=0 && somme!=nbPond)) == 0
return(Memes)
}
|
plot.Brq <-
function (x, plottype = c("hist", "trace", "ACF", "traceACF",
"histACF", "tracehist", "traceACFhist"), Coefficients = 1, breaks = 30,
lwd = 1, col1 = 0, col2 = 1, col3 = 1, col4 = 1, ...)
{
call <- match.call()
mf <- match.call(expand.dots = FALSE)
mf$drop.unused.levels <- FALSE
Betas=as.matrix(x$beta[, Coefficients])
k = ncol(as.matrix( Betas))
if (k == 2)
par(mfrow = c(1, 2))
if (k == 3)
par(mfrow = c(1, 3))
if (k == 4)
par(mfrow = c(2, 2))
if (k > 4 & k <= 12)
par(mfrow = c(ceiling(k/3), 3))
if (k > 12)
par(mfrow = c(ceiling(k/3), 3))
plottype <- match.arg(plottype)
switch(plottype, trace = for (i in 1:k) {
ts.plot(Betas[, i], xlab = "iterations", ylab = "",
main = noquote(names(coef(x)))[i], col = col4)
}, ACF = for (i in 1:k) {
acf(Betas[, i], main = noquote(names(coef(x)))[i], col = col3)
}, traceACF = {
par(mfrow = c(k, 2))
for (i in 1:k) {
ts.plot(Betas[, i], xlab = "iterations", ylab = "",
main = noquote(names(coef(x)))[i], col = col4)
acf(Betas[, i], main = noquote(names(coef(x)))[i],
col = col3)
}
}, histACF = {
par(mfrow = c(k, 2))
for (i in 1:k) {
hist(Betas[, i], breaks = breaks, prob = TRUE, main = "",
xlab = noquote(names(coef(x)))[i], col = col1)
lines(density(Betas[, i], adjust = 2), lty = "dotted",
col = col2, lwd = lwd)
acf(Betas[, i], main = noquote(names(coef(x)))[i],
col = col3)
}
}, tracehist = {
par(mfrow = c(k, 2))
for (i in 1:k) {
ts.plot(Betas[, i], xlab = "iterations", ylab = "",
main = noquote(names(coef(x)))[i], col = col4)
hist(Betas[, i], breaks = breaks, prob = TRUE, main = "",
xlab = noquote(names(coef(x)))[i], col = col1)
lines(density(Betas[, i], adjust = 2), lty = "dotted",
col = col2, lwd = lwd)
}
}, traceACFhist = {
par(mfrow = c(k, 3))
for (i in 1:k) {
ts.plot(Betas[, i], xlab = "iterations", ylab = "",
main = noquote(names(coef(x)))[i], col = col4)
hist(Betas[, i], breaks = breaks, prob = TRUE, main = "",
xlab = noquote(names(coef(x)))[i], col = col1)
lines(density(Betas[, i], adjust = 2), lty = "dotted",
col = col2, lwd = lwd)
acf(Betas[, i], main = noquote(names(coef(x)))[i],
col = col3)
}
}, hist = for (i in 1:k) {
hist(Betas[, i], breaks = breaks, prob = TRUE, main = "",
xlab = noquote(names(coef(x)))[i], col = col1)
lines(density(Betas[, i], adjust = 2), lty = "dotted",
col = col2, lwd = lwd)
})
}
|
morans.w <- function(pop1, pop2, allele.column, ref.pop=NA)
{
pop <- rbind(pop1,pop2)
ri <- .subset2(pop1,allele.column*2+1)
rj <- .subset2(pop2,allele.column*2+2)
var.p <- sapply(seq(1:length(ref.pop)),function(x){rowMeans(names(ref.pop[x])==data.frame(ri,rj))})
var.p <-rowMeans((t(var.p)-colMeans(var.p))^2)
return(sum(var.p))
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.