code
stringlengths 1
13.8M
|
---|
teamBowlersVsBatsmenOppnAllMatches <- function(matches,main,opposition,plot=1,top=5){
noBalls=wides=team=runs=bowler=wicketKind=wicketPlayerOut=NULL
ggplotly=NULL
team=bowler=ball=wides=noballs=runsConceded=overs=batsman=NULL
a <-filter(matches,team != main)
b <-summarise(group_by(a,bowler,batsman),sum(runs))
names(b) <- c("bowler","batsman","runsConceded")
c <- summarise(group_by(b,bowler),runs=sum(runsConceded))
d <- arrange(c,desc(runs))
d <- head(d,top)
bowlers <- as.character(d$bowler)
e <- NULL
for(i in 1:length(bowlers)){
f <- filter(b,bowler==bowlers[i])
e <- rbind(e,f)
}
names(e) <- c("bowler","batsman","runsConceded")
if(plot == 1){
plot.title = paste("Bowlers vs batsmen -",main," Vs ",opposition,"(all matches)",sep="")
ggplot(data=e,aes(x=batsman,y=runsConceded,fill=factor(batsman))) +
facet_grid(. ~ bowler) + geom_bar(stat="identity") +
xlab("Batsman") + ylab("Runs conceded") +
ggtitle(bquote(atop(.(plot.title),
atop(italic("Data source:http://cricsheet.org/"),"")))) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
} else if(plot == 2){
plot.title = paste("Bowlers vs batsmen -",main," Vs ",opposition,"(all matches)",sep="")
g <- ggplot(data=e,aes(x=batsman,y=runsConceded,fill=factor(batsman))) +
facet_grid(. ~ bowler) + geom_bar(stat="identity") +
xlab("Batsman") + ylab("Runs conceded") +
ggtitle(plot.title) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
ggplotly(g,height=500)
} else{
e
}
} |
lines.predMexhaz <- function(x,which=c("surv","hazard"),conf.int=TRUE,lty.pe="solid",lty.ci="dashed",...){
which <- match.arg(which)
if (x$type=="multiobs"){
stop("The 'lines.predMexhaz' function applies only to predictions realised on a single vector of covariates.")
}
time.pts <- x$results$time.pts
if (which=="hazard"){
lines(time.pts,x$results$hazard,lty=lty.pe,...)
}
else {
lines(c(0,time.pts),c(1,x$results$surv),lty=lty.pe,...)
}
if (conf.int==TRUE & x$ci.method!="none"){
if (which=="hazard"){
lines(time.pts,x$results$hazard.inf,lty=lty.ci,...)
lines(time.pts,x$results$hazard.sup,lty=lty.ci,...)
}
else {
lines(c(0,time.pts),c(1,x$results$surv.inf),lty=lty.ci,...)
lines(c(0,time.pts),c(1,x$results$surv.sup),lty=lty.ci,...)
}
}
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(criticalpath)
sch <- sch_new() %>%
sch_title("Project 1: Cost Information System") %>%
sch_reference("VANHOUCKE, Mario.
Integrated project management and control:
first comes the theory, then the practice.
Gent: Springer, 2014, p. 6") %>%
sch_add_activities(
id = 1:17,
name = paste("a", as.character(1:17), sep=""),
duration = c(1L,2L,2L,4L,3L,3L,3L,2L,1L,1L,2L,1L,1L,1L,1L,2L,1L)
) %>%
sch_add_relations(
from = c(1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 11L, 11L, 12L, 12L, 13L, 13L, 14L, 14L, 15L, 15L),
to = c(2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 11L, 11L,
12L, 13L, 14L, 15L, 16L, 17L, 16L, 17L, 16L, 17L, 16L, 17L, 16L, 17L)
) %>%
sch_plan()
sch_duration(sch)
sch_activities(sch)
sch_relations(sch)
sch <- sch_new() %>%
sch_title("Project 3: Old Carriage House Renovation") %>%
sch_reference(
"VANHOUCKE, Mario. Integrated project management and control:
first comes the theory, then the practice. Gent: Springer, 2014, p. 11") %>%
sch_add_activity( 1L, "a1" , 2L) %>%
sch_add_activity( 2L, "a2" , 2L) %>%
sch_add_activity( 3L, "a3" , 4L) %>%
sch_add_activity( 4L, "a4" , 3L) %>%
sch_add_activity( 5L, "a5" , 4L) %>%
sch_add_activity( 6L, "a6" , 1L) %>%
sch_add_activity( 7L, "a7" , 1L) %>%
sch_add_activity( 8L, "a8" , 1L) %>%
sch_add_activity( 9L, "a9" , 1L) %>%
sch_add_activity(10L, "a10", 1L) %>%
sch_add_activity(11L, "a11", 3L) %>%
sch_add_activity(12L, "a12", 2L) %>%
sch_add_activity(13L, "a13", 1L) %>%
sch_add_activity(14L, "a14", 1L) %>%
sch_add_activity(15L, "a15", 2L) %>%
sch_add_activity(16L, "a16", 1L) %>%
sch_add_activity(17L, "a17", 1L) %>%
sch_add_relation( 1L, 2L) %>%
sch_add_relation( 2L, 3L) %>%
sch_add_relation( 3L, 4L) %>%
sch_add_relation( 4L, 5L) %>%
sch_add_relation( 5L, 6L) %>%
sch_add_relation( 6L, 7L) %>%
sch_add_relation( 6L, 8L) %>%
sch_add_relation( 6L, 9L) %>%
sch_add_relation( 7L, 10L) %>%
sch_add_relation( 8L, 10L) %>%
sch_add_relation( 9L, 10L) %>%
sch_add_relation(10L, 11L) %>%
sch_add_relation(10L, 13L) %>%
sch_add_relation(11L, 12L) %>%
sch_add_relation(12L, 15L) %>%
sch_add_relation(13L, 14L) %>%
sch_add_relation(14L, 15L) %>%
sch_add_relation(15L, 16L) %>%
sch_add_relation(16L, 17L) %>%
sch_plan()
sch_duration(sch)
sch_activities(sch)
sch_relations(sch)
sch <- sch_new() %>%
sch_title("Fictitious Project Example") %>%
sch_reference("VANHOUCKE, Mario. Measuring time:
improving project performance using earned value management.
Gent: Springer, 2009, p. 18") %>%
sch_add_activity( 1L, "a1" , 0L, 2L,3L,4L) %>%
sch_add_activity( 2L, "a2" , 4L, 5L) %>%
sch_add_activity( 3L, "a3" , 9L, 10L) %>%
sch_add_activity( 4L, "a4" , 1L, 6L) %>%
sch_add_activity( 5L, "a5" , 4L, 9L) %>%
sch_add_activity( 6L, "a6" , 5L, 7L) %>%
sch_add_activity( 7L, "a7" , 1L, 8L,11L) %>%
sch_add_activity( 8L, "a8" , 7L, 12L) %>%
sch_add_activity( 9L, "a9" , 8L, 12L) %>%
sch_add_activity(10L, "a10", 3L, 12L) %>%
sch_add_activity(11L, "a11", 3L, 12L) %>%
sch_add_activity(12L, "a12", 0L) %>%
sch_plan()
sch_duration(sch)
sch_activities(sch)
sch_relations(sch)
sch <- sch_new() %>%
sch_add_activity(1L, "Task 1", 5L) %>%
sch_add_activity(2L, "Task 2", 6L) %>%
sch_add_activity(3L, "Task 3", 8L) %>%
sch_add_activity(4L, "Task 4", 6L) %>%
sch_add_activity(5L, "Task 5", 9L) %>%
sch_add_activity(6L, "Task 6", 3L) %>%
sch_add_activity(7L, "Task 7", 4L) %>%
sch_plan()
sch_duration(sch)
sch_activities(sch)
sch <- sch_new() %>%
sch_title("Fictitious Project Example") %>%
sch_reference("VANHOUCKE, Mario. Measuring time:
improving project performance using earned value management.
Gent: Springer, 2009, p. 18") %>%
sch_add_activity( 1L, "a1" , 0L, 2L,3L,4L) %>%
sch_add_activity( 2L, "a2" , 4L, 5L) %>%
sch_add_activity( 3L, "a3" , 9L, 10L) %>%
sch_add_activity( 4L, "a4" , 1L, 6L) %>%
sch_add_activity( 5L, "a5" , 4L, 9L) %>%
sch_add_activity( 6L, "a6" , 5L, 7L) %>%
sch_add_activity( 7L, "a7" , 1L, 8L,11L) %>%
sch_add_activity( 8L, "a8" , 7L, 12L) %>%
sch_add_activity( 9L, "a9" , 8L, 12L) %>%
sch_add_activity( 10L, "a10", 3L, 12L) %>%
sch_add_activity( 11L, "a11", 3L, 12L) %>%
sch_add_activity( 12L, "a12", 0L) %>%
sch_plan()
sch_title(sch)
sch_reference(sch) %>% cat()
sch_duration(sch)
sch <- sch_new() %>%
sch_title("Fictitious Project Example") %>%
sch_reference("VANHOUCKE, Mario. Measuring time:
improving project performance using earned value management.
Gent: Springer, 2009, p. 18")
sch_has_any_activity(sch)
sch_nr_activities(sch)
sch %<>%
sch_add_activity( 1L, "a1" , 0L, 2L,3L,4L) %>%
sch_add_activity( 2L, "a2" , 4L, 5L) %>%
sch_add_activity( 3L, "a3" , 9L, 10L) %>%
sch_add_activity( 4L, "a4" , 1L, 6L) %>%
sch_add_activity( 5L, "a5" , 4L, 9L) %>%
sch_add_activity( 6L, "a6" , 5L, 7L) %>%
sch_add_activity( 7L, "a7" , 1L, 8L,11L) %>%
sch_add_activity( 8L, "a8" , 7L, 12L) %>%
sch_add_activity( 9L, "a9" , 8L, 12L) %>%
sch_add_activity( 10L, "a10", 3L, 12L) %>%
sch_add_activity( 11L, "a11", 3L, 12L) %>%
sch_add_activity( 12L, "a12", 0L) %>%
sch_plan()
sch_has_any_activity(sch)
sch_nr_activities(sch)
sch_get_activity(sch, 10L)
sch_activities(sch)
sch <- sch_new() %>%
sch_title("A project") %>%
sch_reference("From criticalpath") %>%
sch_add_activities(
id = c( 1L, 2L, 3L, 4L ),
name = c("A", "B", "C", "D"),
duration = c( 2L, 3L, 1L, 2L )
) %>%
sch_add_relations(
from = c(1L, 2L, 4L, 4L),
to = c(3L, 3L, 1L, 2L)
) %>%
sch_plan()
gantt <- sch_gantt_matrix(sch)
gantt
colSums(gantt)
rowSums(gantt)
cumsum(colSums(gantt))
plot(cumsum(colSums(gantt)), type="l", lwd=3)
xyw <- sch_xy_gantt_matrix(sch)
xyw
plot(xyw[, 1:2])
sch <- sch_new() %>%
sch_title("Project 2: Patient Transport System") %>%
sch_reference(
"VANHOUCKE, Mario. Integrated project management and control:
first comes the theory, then the practice. Gent: Springer, 2014, p. 9") %>%
sch_add_activities(
id = 1:17,
name = paste("a", as.character(1:17), sep=""),
duration = c(1L,1L,3L,2L, 2L,2L,2L,1L, 4L,5L,3L,3L, 4L,5L,1L,5L,2L)
) %>%
sch_add_relations(
from = c(1L, 2L, 3L, 3L, 4L, 5L, 6L, 7L, 8L, 8L, 8L,
8L, 8L, 9L, 10L, 11L, 12L, 13L, 13L, 14L, 14L, 15L, 15L),
to = c(2L, 3L, 4L, 6L, 5L, 8L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 14L, 14L, 14L, 14L, 15L, 16L, 17L, 16L, 17L)
) %>%
sch_plan()
sch_duration(sch)
sch_activities(sch)$duration
new_durations <- c(1L,2L,5L, 4L,3L, 2L,1L, 5L, 3L,5L,5L,3L,4L, 2L,1L, 2L,4L)
sch %<>%
sch_change_activities_duration(new_durations)
sch_duration(sch)
sch_activities(sch)$duration
n <- sch %>% sch_nr_activities()
set.seed(45678)
i <- sample(n)
another_schedule <- sch_new() %>%
sch_add_activities(
id = sch_activities(sch)$id[i],
name = sch_activities(sch)$name[i],
duration = sch_activities(sch)$duration[i]
) %>%
sch_add_relations(
from = c(1L, 2L, 3L, 3L, 4L, 5L, 6L, 7L, 8L, 8L, 8L,
8L, 8L, 9L, 10L, 11L, 12L, 13L, 13L, 14L, 14L, 15L, 15L),
to = c(2L, 3L, 4L, 6L, 5L, 8L, 7L, 8L, 9L, 10L, 11L,
12L, 13L, 14L, 14L, 14L, 14L, 14L, 15L, 16L, 17L, 16L, 17L)
) %>%
sch_plan()
another_schedule %<>% sch_change_activities_duration(new_durations[i])
sch_duration(another_schedule)
sch_duration(sch)
sch <- sch_new() %>%
sch_title("Fictitious Project Example") %>%
sch_reference("VANHOUCKE, Mario. Measuring time:
improving project performance using earned value management.
Gent: Springer, 2009, p. 18")
sch_has_any_relation(sch)
sch_nr_relations(sch)
sch %<>%
sch_add_activity( 1L, "a1" , 0L, 2L,3L,4L) %>%
sch_add_activity( 2L, "a2" , 4L, 5L) %>%
sch_add_activity( 3L, "a3" , 9L, 10L) %>%
sch_add_activity( 4L, "a4" , 1L, 6L) %>%
sch_add_activity( 5L, "a5" , 4L, 9L) %>%
sch_add_activity( 6L, "a6" , 5L, 7L) %>%
sch_add_activity( 7L, "a7" , 1L, 8L,11L) %>%
sch_add_activity( 8L, "a8" , 7L, 12L) %>%
sch_add_activity( 9L, "a9" , 8L, 12L) %>%
sch_add_activity(10L, "a10", 3L, 12L) %>%
sch_add_activity(11L, "a11", 3L, 12L) %>%
sch_add_activity(12L, "a12", 0L) %>%
sch_plan()
sch_has_any_relation(sch)
sch_nr_relations(sch)
sch_relations(sch)
sch <- sch_new() %>%
sch_title("Fictitious Project Example") %>%
sch_reference("VANHOUCKE, Mario. Measuring time:
improving project performance using earned value management.
Gent: Springer, 2009, p. 18") %>%
sch_add_activity( 2L, "a2" , 4L, 5L, 12L) %>%
sch_add_activity( 3L, "a3" , 9L, 10L) %>%
sch_add_activity( 4L, "a4" , 1L, 6L) %>%
sch_add_activity( 5L, "a5" , 4L, 9L) %>%
sch_add_activity( 6L, "a6" , 5L, 7L) %>%
sch_add_activity( 7L, "a7" , 1L, 8L,11L) %>%
sch_add_activity( 8L, "a8" , 7L, 12L) %>%
sch_add_activity( 9L, "a9" , 8L, 12L) %>%
sch_add_activity(10L, "a10", 3L, 12L) %>%
sch_add_activity(11L, "a11", 3L, 12L) %>%
sch_add_activity(12L, "a12", 0L) %>%
sch_plan()
sch_all_successors(sch, 2)
sch_all_successors(sch, 7)
sch_all_successors(sch, 10)
sch_successors(sch, 2)
sch_successors(sch, 7)
sch_successors(sch, 10)
sch_all_predecessors(sch, 2)
sch_all_predecessors(sch, 7)
sch_all_predecessors(sch, 10)
sch_predecessors(sch, 2)
sch_predecessors(sch, 7)
sch_predecessors(sch, 10)
sch_is_redundant(sch, 2, 5)
sch_is_redundant(sch, 2, 12)
sch <- sch_new() %>%
sch_title("Fictitious Project Example") %>%
sch_reference("VANHOUCKE, Mario. Measuring time:
improving project performance using earned value management.
Gent: Springer, 2009, p. 18") %>%
sch_add_activity( 1L, "a1" , 0L, 2L,3L,4L) %>%
sch_add_activity( 2L, "a2" , 4L, 5L) %>%
sch_add_activity( 3L, "a3" , 9L, 10L) %>%
sch_add_activity( 4L, "a4" , 1L, 6L) %>%
sch_add_activity( 5L, "a5" , 4L, 9L) %>%
sch_add_activity( 6L, "a6" , 5L, 7L) %>%
sch_add_activity( 7L, "a7" , 1L, 8L,11L) %>%
sch_add_activity( 8L, "a8" , 7L, 12L) %>%
sch_add_activity( 9L, "a9" , 8L, 12L) %>%
sch_add_activity(10L, "a10", 3L, 12L) %>%
sch_add_activity(11L, "a11", 3L, 12L) %>%
sch_add_activity(12L, "a12", 0L) %>%
sch_plan()
sch_topoi_sp(sch)
sch_topoi_ad(sch)
sch_topoi_la(sch)
sch_topoi_tf(sch) |
normalizedEdgeComplexity <- function(g,ita=NULL){
if(class(g)[1]!="graphNEL"){
stop("'g' must be a 'graphNEL' object")
}
stopifnot(.validateGraph(g))
if(is.null(ita)){
ita <- totalAdjacency(g)
}
return(ita/(numNodes(g)^2))
} |
set_font <- function(p, family="sans", fontface=NULL, size=NULL, color=NULL) {
if (!is.null(size))
size <- size * .pt
par <- list(fontfamily = family, fontface = fontface, fontsize = size, col = color)
par <- par[!sapply(par, is.null)]
gp <- do.call(gpar, par)
g <- ggplotGrob(p)
ng <- grid.ls(grid.force(g), print=FALSE)$name
txt <- ng[which(grepl("text", ng))]
for (i in seq_along(txt)) {
g <- editGrob(grid.force(g), gPath(txt[i]),
grep = TRUE, gp = gp)
}
grid.draw(g)
invisible(g)
} |
print.site <- function(x, ...){
class(x) <- 'data.frame'
print(format(data.frame(site.name = x$site.name,
long = x$long,
lat = x$lat,
elev = x$elev),
justify='left'), row.names=FALSE)
cat(paste0('A site object containing ',nrow(x),' sites and 8 parameters.\n'))
} |
ks_stat<-function(x,z){
nvar=dim(x)[2]
x1=x[z==1,]
x0=x[z==0,]
ks=numeric(nvar)
where=numeric(nvar)
for (i in 1:nvar){
ks[i]=stats::ks.test(x1[,i],x0[,i])$statistic
}
ks
} |
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
fig.width = 6,
fig.height = 4
)
library('adea')
data(tokyo_libraries)
head(tokyo_libraries)
input <- tokyo_libraries[, 1:4]
output <- tokyo_libraries[, 5:6]
m <- adea(input, output)
summary(m)
mc <- cadea(input, output, load.min = 0.6, load.max = 4)
summary(mc)
plot(m$eff, mc$eff, main ='Initial efficiencies vs constrained model efficiencies') |
plotProbs <- function (result, traits, colors = c("lightblue", "blue"), xlim = NULL, ylim = NULL,
xlab = NULL, ylab = NULL, zlab = "Probability", distance = 0.3, cex.lab = 1.5, box.col = "transparent",
xbase = 0.5, ybase = 0.5,...)
{
res <- result$prob
cols <- function(n) {
(grDevices::colorRampPalette(colors = colors))(20)
}
if (ncol(traits) == "1") {
graphics::barplot(t(res), col = colors[2],
names = rownames(res), ylab = ifelse(is.null(ylab), "Probability", ylab),
xlab = ifelse(is.null(xlab), "Trait X", xlab),...)
}
if (ncol(traits) == "2") {
if (is.null(xlim)) xlim <- c(min(traits[,1]) - 1, max(traits[, 1]) + 1)
if (is.null(ylim)) ylim <- c(min(traits[,2]) - 1, max(traits[, 2]) + 1)
lattice::cloud(res ~ as.vector(t(traits[, 1])) + as.vector(t(traits[,2])), panel.3d.cloud = latticeExtra::panel.3dbars,
xbase = xbase, ybase = ybase, scales = list(arrows = FALSE,col = 1), perspective = TRUE,
distance = distance, xlim = xlim, ylim = ylim,
par.settings = list(axis.line = list(col = box.col)),
xlab = list(ifelse(is.null(xlab), "Trait X", xlab), rot = 50),
ylab = list(ifelse(is.null(ylab), "Trait Y", ylab), rot = -30),
zlab = list(zlab,rot = 90), screen = list(z = 55, x = -55),
col.facet = lattice::level.colors(res, at = lattice::do.breaks(range(res), 20), col.regions = cols, colors = TRUE),...)
}
} |
context("running filtering of matrix")
set.seed(42)
high_var = data.frame(matrix(rnorm(140, mean = 10, sd = 10), nrow = 7))
low_var = data.frame(matrix(rnorm(140, mean = 10, sd = 1), nrow = 7))
low_mean = data.frame(matrix(rnorm(120, mean = 1, sd = 10), nrow = 6))
total_mat = rbind(high_var, low_var, low_mean)
rownames(total_mat) = letters[1:20]
groups = c(rep(c("A", "B", "C"), each = 6), "A")
design = makeDesign(groups)
test_that("filterGenes works", {
library(matrixStats)
filtered_mean = filterGenes(total_mat, filterTypes = c("central"),
keepRows = NULL, filterCentralType = "median", filterCentralPercentile = 0.3)
expect_equal(rownames(filtered_mean), letters[1:14])
filtered_mean = filterGenes(total_mat, filterTypes = c("central"),
keepRows = NULL, filterCentralType = "mean", filterCentralPercentile = 0.3)
expect_equal(rownames(filtered_mean), letters[1:14])
filtered_variance = filterGenes(total_mat, filterTypes = c("dispersion"),
keepRows = NULL, filterDispersionType = "cv", filterDispersionPercentile = 0.35)
expect_equal(rownames(filtered_variance), c(letters[1:7], letters[15:20]))
filtered_variance = filterGenes(total_mat, filterTypes = c("dispersion"),
keepRows = NULL, filterDispersionType = "variance", filterDispersionPercentile = 0.35)
expect_equal(rownames(filtered_variance), c(letters[1:7], letters[15:20]))
filtered_mat = filterGenes(total_mat, filterTypes = c("central", "dispersion"),
keepRows = NULL, filterCentralType = "median",
filterDispersionType = "cv", filterCentralPercentile = 0.3,
filterDispersionPercentile = 0.5, sequential = TRUE)
expect_equal(rownames(filtered_mat), c(letters[1:7]))
filtered_mat = filterGenes(total_mat, filterTypes = c("central", "dispersion"),
keepRows = NULL, filterCentralType = "median",
filterDispersionType = "cv", filterCentralPercentile = 0.3,
filterDispersionPercentile = 0.35, sequential = FALSE)
expect_equal(rownames(filtered_mat), c(letters[1:7]))
filtered_mat = filterGenes(total_mat, filterTypes = c("central", "dispersion"),
keepRows = c(letters[10], letters[20]), filterCentralType = "median",
filterDispersionType = "cv", filterCentralPercentile = 0.3,
filterDispersionPercentile = 0.45, sequential = TRUE)
expect_equal(rownames(filtered_mat), c(letters[1:7], letters[10], letters[20]))
filtered_mat = filterGenes(total_mat, filterTypes = c("central", "dispersion"),
keepRows = c(letters[10], letters[20]), filterCentralType = "median",
filterDispersionType = "cv", filterCentralPercentile = 0.3,
filterDispersionPercentile = 0.35, sequential = FALSE)
expect_equal(rownames(filtered_mat), c(letters[1:7], letters[10], letters[20]))
filtered_mat = filterGenes(total_mat, filterTypes = c("central"), keepRows = NULL, filterCentralType = "mean", filterCentralPercentile = 0.35, allGroups = TRUE, design = design)
expect_equal(rownames(filtered_mat), c("b", "d", "e", "f", "h", "i", "j", "k", "l", "m", "n"))
}) |
examplify_to_r <- function(in_fname, out_fname, verbose=FALSE) {
if(!requireNamespace("xml2", quietly=TRUE) ||
!requireNamespace("rvest", quietly=TRUE) ||
!requireNamespace("formatR", quietly=TRUE)) {
stop("Please install rvest, xml2 and formatR before using this function.")
}
page1 <- xml2::read_html(in_fname)
qns <- rvest::html_nodes(page1, "
stringr::str_replace_all("\r\n", "\n
ans <- rvest::html_nodes(page1, "
as.character
if(verbose){
message("HTML parsed.\n")
}
if(length(qns) != length(ans)){
warning(paste0("Questions and answers do not match up for ", in_fname))
}
full_text <- NULL
for (ii in 1:length(qns)) {
tmp_qn <- formatR::tidy_source(text = qns[ii], output=FALSE)$text.tidy
tmp_ans <- stringr::str_split(ans[ii], "\n")[[1]]
tmp_ans <- stringr::str_replace_all(ans[ii], "<br>", "\n") %>%
xml2::read_xml() %>%
rvest::xml_nodes("p") %>%
rvest::html_text()
full_text <- c(full_text, tmp_qn, "", tmp_ans, "")
}
writeLines(full_text, con=out_fname)
if(verbose){
message(out_fname, "written.\n")
}
} |
context("Babble")
p <- sbo_predictor(twitter_predtable)
test_that("some text is generated with default input argument",{
set.seed(840)
bla <- babble(p)
expect_true(is.character(bla))
expect_length(bla, 1)
})
test_that("some text is generated for input = ''",{
set.seed(840)
bla <- babble(p, input = "")
expect_true(is.character(bla))
expect_length(bla, 1)
})
test_that("some text is generated for input = 'i love'",{
set.seed(840)
bla <- babble(p, input = "")
expect_true(is.character(bla))
expect_length(bla, 1)
})
test_that("informs with output when reaches maximum length",{
set.seed(840)
expect_true(grepl("\\[\\.\\.\\. reached maximum length \\.\\.\\.\\]$",
babble(p, n_max = 1L))
)
})
test_that("throws error on non character or NA_character_ input",{
set.seed(840)
expect_error(babble(p, input = 1))
expect_error(babble(p, input = TRUE))
})
test_that("throws error on length != 1 input",{
set.seed(840)
expect_error(babble(p, input = character()))
expect_error(babble(p, input = c("i love", "you love")))
})
test_that("throws error on length != 1 input",{
set.seed(840)
expect_error(babble(p, input = character()))
expect_error(babble(p, input = c("i love", "you love")))
})
test_that("throws error on non-numeric n_max",{
set.seed(840)
expect_warning(expect_error(babble(p, n_max = "ciao")))
})
test_that("throws error on NA n_max",{
set.seed(840)
expect_error(babble(p, n_max = NA_integer_))
})
test_that("throws error on length != 1 n_max",{
set.seed(840)
expect_error(babble(p, n_max = double()))
expect_error(babble(p, n_max = c(1,2)))
})
test_that("throws error on n_max < 1",{
set.seed(840)
expect_error(babble(p, n_max = 0))
}) |
cache_file <- file.path(tempdir(), "foghorn-n_cran_flavors.rds")
current_cran_flavors <- 14L
test_that("caching for CRAN flavors", {
skip_on_cran()
unlink(cache_file)
expect_false(file.exists(cache_file))
expect_identical(n_cran_flavors(), current_cran_flavors)
expect_true(file.exists(cache_file))
})
test_that("disabling caching for CRAN flavors", {
skip_on_cran()
unlink(cache_file)
expect_false(file.exists(cache_file))
expect_identical(n_cran_flavors(use_cache = FALSE), current_cran_flavors)
expect_false(file.exists(cache_file))
})
test_that("specifying force default for CRAN flavors", {
skip_on_cran()
unlink(cache_file)
expect_false(file.exists(cache_file))
expect_identical(n_cran_flavors(force_default = TRUE, n_flavors = 999L), 999L)
expect_false(file.exists(cache_file))
})
test_that("assertions for n_cran_flavors", {
expect_error(n_cran_flavors(use_cache = 123))
expect_error(n_cran_flavors(use_cache = "123"))
expect_error(n_cran_flavors(use_cache = logical(0)))
expect_error(n_cran_flavors(use_cache = c(TRUE, FALSE)))
expect_error(n_cran_flavors(use_cache = NA))
expect_error(n_cran_flavors(use_cache = NULL))
expect_error(n_cran_flavors(force_default = 123))
expect_error(n_cran_flavors(force_default = "123"))
expect_error(n_cran_flavors(force_default = logical(0)))
expect_error(n_cran_flavors(force_default = c(TRUE, FALSE)))
expect_error(n_cran_flavors(force_default = NA))
expect_error(n_cran_flavors(force_default = NULL))
expect_error(n_cran_flavors(n_flavors = 123))
expect_error(n_cran_flavors(n_flavors = "123"))
expect_error(n_cran_flavors(n_flavors = integer(0)))
expect_error(n_cran_flavors(n_flavors = c(1234L, 5678L)))
expect_error(n_cran_flavors(use_cache = NA_integer_))
expect_error(n_cran_flavors(use_cache = NULL))
}) |
interpret_icc <- function(icc, rules = "koo2016", ...) {
rules <- .match.rules(
rules,
list(
koo2016 = rules(c(0.5, 0.75, 0.9),
c("poor", "moderate", "good", "excellent"),
name = "koo2016", right = FALSE
)
)
)
interpret(icc, rules)
} |
div_profile <- function(count,qvalues,tree,hierarchy,level){
if(missing(count)) stop("The countance data is missing")
if(missing(qvalues)) {qvalues= seq(from = 0, to = 5, by = (0.1))}
if(missing(level)) {level= "NA"}
if(is.null(dim(count)) == TRUE){
profile <- c()
for (o in qvalues){
if(missing(tree)){
div.value <- hill_div(count,o)
}else{
div.value <- hill_div(count,o,tree)
}
profile <- c(profile,div.value)
}
names(profile) <- qvalues
}
if(!missing(tree)){
hill_div_fast <- function(count,qvalue,tree,dist){
if(qvalue==1){qvalue=0.99999}
phylogenetic.Hill.fast <- function(vector,qvalue,tree){
Li <- tree$edge.length
ai <- unlist(lapply(ltips, function(TipVector) sum(vector[TipVector])))
T <- sum(Li * ai)
Li <- Li[ai != 0]
ai <- ai[ai != 0]
sum(Li/T * ai^qvalue)^(1/(1-qvalue))
}
divs <- apply(tss(count), 2, function(x) phylogenetic.Hill.fast(x,qvalue,tree))
return(divs)
}
alpha_div_fast <- function(otutable,qvalue,tree,weight){
if(missing(otutable)) stop("OTU table is missing")
if(is.null(dim(otutable)) == TRUE) stop("The OTU table is not a matrix")
if(dim(otutable)[1] < 2) stop("The OTU table only less than 2 OTUs")
if(dim(otutable)[2] < 2) stop("The OTU table contains less than 2 samples")
if(sum(colSums(otutable)) != ncol(otutable)) {otutable <- tss(otutable)}
if(missing(qvalue)) stop("q value is missing")
if(qvalue < 0) stop("q value needs to be possitive (equal or higher than zero)")
if(identical(sort(rownames(otutable)),sort(tree$tip.label)) == FALSE) stop("OTU names in the OTU table and tree do not match")
if(is.ultrametric(tree) == FALSE) stop("Tree needs to be ultrametric")
if (qvalue==1) {qvalue=0.99999}
if(missing(weight)) { weight= rep(1/ncol(otutable),ncol(otutable))}
otutable <- as.data.frame(otutable)
wj <- weight
N <- ncol(otutable)
Li <- tree$edge.length
aij <- matrix(unlist(lapply(ltips, function(TipVector) colSums(otutable[TipVector,]))), ncol = N, byrow = TRUE)
aij.wj <- sweep(aij, 2, wj, "*")
T <- sum(sweep(aij.wj, 1, Li, "*"))
L <- matrix(rep(Li, N), ncol = N)
wm <- matrix(rep(wj, length(Li)), ncol = N,byrow=TRUE)
i <- which(aij > 0)
phylodiv <- sum(L[i] * (aij[i]*wm[i]/T)^qvalue)^(1/(1 - qvalue))/(N*T)
return(phylodiv)
}
gamma_div_fast <- function(otutable,qvalue,tree,weight){
if(missing(otutable)) stop("OTU table is missing")
if(is.null(dim(otutable)) == TRUE) stop("The OTU table is not a matrix")
if(dim(otutable)[1] < 2) stop("The OTU table only less than 2 OTUs")
if(dim(otutable)[2] < 2) stop("The OTU table contains less than 2 samples")
if(sum(colSums(otutable)) != ncol(otutable)) {otutable <- tss(otutable)}
if(missing(qvalue)) stop("q value is missing")
if(qvalue < 0) stop("q value needs to be possitive (equal or higher than zero)")
if (qvalue==1) {qvalue=0.99999}
if(is.ultrametric(tree) == FALSE) stop("Tree needs to be ultrametric")
if(identical(sort(rownames(otutable)),sort(tree$tip.label)) == FALSE) stop("OTU names in the OTU table and tree do not match")
if(missing(weight)) { weight= rep(1/ncol(otutable),ncol(otutable))}
otutable <- as.data.frame(otutable)
wj <- weight
N <- ncol(otutable)
Li <- tree$edge.length
aij <- matrix(unlist(lapply(ltips, function(TipVector) colSums(otutable[TipVector,]))), ncol = N, byrow = TRUE)
aij.wj <- sweep(aij, 2, wj, "*")
ai <- rowSums(aij.wj)
T <- sum(sweep(aij.wj, 1, Li, "*"))
L <- matrix(rep(Li, N), ncol = N)
Li <- Li[ai != 0]
ai <- ai[ai != 0]
wm <- matrix(rep(wj, length(Li)), ncol = N, byrow=TRUE)
phylodiv <- (sum(Li * (ai/T)^qvalue)^(1/(1 - qvalue)))/T
return(phylodiv)
}
}
if(is.null(dim(count)) == FALSE){
if(dim(count)[1] < 2) stop("The OTU table only less than 2 OTUs")
if(dim(count)[2] < 2) stop("The OTU table contains less than 2 samples")
if(missing(hierarchy)){
profile <- c()
for (o in qvalues){
if(missing(tree)){
if(level == "NA"){div.values <- hill_div(count,o)}
if(level == "gamma"){div.values <- gamma_div(count,o)}
if(level == "alpha"){div.values <- alpha_div(count,o)}
}else{
ltips <- sapply(tree$edge[, 2], function(node) tips(tree, node))
if(level == "NA"){div.values <- hill_div_fast(count,o,tree)}
if(level == "gamma"){div.values <- gamma_div(count,o,tree)}
if(level == "alpha"){div.values <- alpha_div(count,o,tree)}
}
profile <- rbind(profile,div.values)
}
if(level == "NA"){
rownames(profile) <- qvalues
}
if(level == "gamma"){
profile <- c(profile)
names(profile) <- qvalues
}
if(level == "alpha"){
profile <- c(profile)
names(profile) <- qvalues
}
}
if(!missing(hierarchy)){
if(ncol(hierarchy) != 2) stop("The hierarchy table must contain two columns.")
colnames(hierarchy) <- c("Sample","Group")
groups <- as.character(sort(unique(hierarchy$Group)))
profile <- c()
for (g in groups){
samples <- as.character(hierarchy[which(hierarchy$Group == g),1])
count.subset <- count[,samples]
count.subset <- as.data.frame(count.subset[apply(count.subset, 1, function(z) !all(z==0)),])
if(!missing(tree)){
missing.otus <- setdiff(tree$tip.label,rownames(count.subset))
tree.subset <- drop.tip(tree,missing.otus)
}
for (o in qvalues){
if(missing(tree)){
if(level == "NA"){div.value <- gamma_div(count.subset,o)}
if(level == "gamma"){div.value <- gamma_div(count.subset,o)}
if(level == "alpha"){div.value <- alpha_div(count.subset,o)}
}else{
ltips <- sapply(tree.subset$edge[, 2], function(node) tips(tree.subset, node))
if(level == "NA"){div.value <- gamma_div_fast(count.subset,o,tree.subset)}
if(level == "gamma"){div.value <- gamma_div_fast(count.subset,o,tree.subset)}
if(level == "alpha"){div.value <- alpha_div_fast(count.subset,o,tree.subset)}
}
profile <- rbind(profile,as.numeric(div.value))
}
}
profile <- matrix(profile,nrow=length(qvalues))
colnames(profile) <- as.character(groups)
rownames(profile) <- as.character(qvalues)
}
}
return(profile)
} |
knitr::opts_chunk$set(collapse = TRUE, comment = "
library(knitr)
include_graphics('dem.png')
data(landslides)
include_graphics("terrain_variables.png")
include_graphics("lslpred.png") |
data2mat <-
function(data = data)
{
if (!any(colnames(data) == "abundance"))
stop("A column named \"abundance\" must be speciefied.")
if (!any(is.integer(data$abundance)))
stop("Number of individuals must be integer!")
col <- which(colnames(data) == "abundance")
data1 <- data[,-col]
abundance <- as.numeric(data[,col])
result1 <- data.frame(rep(NA, sum(abundance)))
colnames(result1) <- "plots"
for (i in 1:(ncol(data)-1)){
result1[, i] <- rep(as.character(data[, i]), abundance)
}
result <- table(result1)
return(result)
} |
revolution <- c(CRAN = getOption("minicran.mran"))
revolution
pkgs <- c("foreach")
pkgTypes <- c("source", "win.binary")
pdb <- cranJuly2014
\dontrun{
pdb <- pkgAvail(repos = revolution, type = "source")
}
pkgList <- pkgDep(pkgs, availPkgs = pdb, repos = revolution, type = "source", suggests = FALSE)
pkgList
\dontrun{
dir.create(pth <- file.path(tempdir(), "miniCRAN"))
makeRepo(pkgList, path = pth, repos = revolution, type = pkgTypes)
oldVers <- data.frame(package = c("foreach", "codetools", "iterators"),
version = c("1.4.0", "0.2-7", "1.0.5"),
stringsAsFactors = FALSE)
pkgs <- oldVers$package
addOldPackage(pkgs, path = pth, vers = oldVers$version, repos = revolution, type = "source")
pkgVersionsSrc <- checkVersions(pkgs, path = pth, type = "source")
pkgVersionsBin <- checkVersions(pkgs, path = pth, type = "win.binary")
basename(pkgVersionsSrc)
basename(pkgVersionsBin)
file.remove(c(pkgVersionsSrc[1], pkgVersionsBin[1]))
updateRepoIndex(pth, type = pkgTypes, Rversion = R.version)
pkgAvail(pth, type = "source")
addPackage("Matrix", path = pth, repos = revolution, type = pkgTypes)
unlink(pth, recursive = TRUE)
} |
context("Testing reference based continuous outcome imputation")
expit <- function(x) {
exp(x)/(1+exp(x))
}
test_that("Monotone missingness MAR imputation with M=2 runs", {
expect_error({
set.seed(1234)
n <- 500
corr <- matrix(1, nrow=4, ncol=4) + diag(0.5, nrow=4)
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y0 <- data[,1]
y1 <- data[,2]
y2 <- data[,3]
y3 <- data[,4]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<expit(1-y0))
r2 <- 1*(runif(n)<expit(2-(y1-y0)))
r2[r1==0] <- 0
r3 <- 1*(runif(n)<expit(2-(y2-y0)))
r3[r2==0] <- 0
y1[r1==0] <- NA
y2[r2==0] <- NA
y3[r3==0] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", "y0", baselineVisitInt=FALSE, M=2)
}, NA)
})
test_that("Monotone missingness MAR imputation with M=2 and 2 baseline covariates runs", {
expect_error({
set.seed(1234)
n <- 500
corr <- matrix(1, nrow=5, ncol=5) + diag(0.5, nrow=5)
corr
data <- MASS::mvrnorm(n, mu=c(2,0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
v <- data[,1]
y0 <- data[,2]
y1 <- data[,3]
y2 <- data[,4]
y3 <- data[,5]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<expit(1-y0))
r2 <- 1*(runif(n)<expit(2-(y1-y0)))
r2[r1==0] <- 0
r3 <- 1*(runif(n)<expit(2-(y2-y0)))
r3[r2==0] <- 0
y1[r1==0] <- NA
y2[r2==0] <- NA
y3[r3==0] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, v=v, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", c("v", "y0"), baselineVisitInt=FALSE, M=2)
}, NA)
})
test_that("Non-monotone MCAR imputation with no baseline covariates runs", {
expect_error({
set.seed(1234)
n <- 500
corr <- matrix(1, nrow=3, ncol=3) + diag(0.5, nrow=3)
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y1 <- data[,1]
y2 <- data[,2]
y3 <- data[,3]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
y1[1*(runif(n)<0.25)] <- NA
y2[1*(runif(n)<0.25)] <- NA
y3[1*(runif(n)<0.25)] <- NA
wideData <- data.frame(id=1:n, trt=trt, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", baselineVisitInt=FALSE, M=1)
}, NA)
})
test_that("Non-monotone MCAR imputation with no baseline covariates is unbiased at final time point", {
skip_on_cran()
expect_equal({
set.seed(1234)
n <- 50000
corr <- matrix(1, nrow=3, ncol=3) + diag(0.5, nrow=3)
data <- MASS::mvrnorm(n, mu=c(0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y1 <- data[,1]
y2 <- data[,2]
y3 <- data[,3]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
y1[1*(runif(n)<0.25)] <- NA
y2[1*(runif(n)<0.25)] <- NA
y3[1*(runif(n)<0.25)] <- NA
wideData <- data.frame(id=1:n, trt=trt, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", baselineVisitInt=FALSE, M=1)
(abs(mean(imps$y3[imps$trt==1])-1.5)<0.1) & (abs(mean(imps$y3[imps$trt==0])-0)<0.1)
}, TRUE)
})
test_that("Monotone missingness MAR imputation is unbiased at final time point", {
skip_on_cran()
expect_equal({
set.seed(1234)
n <- 50000
corr <- matrix(1, nrow=4, ncol=4) + diag(0.5, nrow=4)
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y0 <- data[,1]
y1 <- data[,2]
y2 <- data[,3]
y3 <- data[,4]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<expit(1-y0))
r2 <- 1*(runif(n)<expit(2-(y1-y0)))
r2[r1==0] <- 0
r3 <- 1*(runif(n)<expit(2-(y2-y0)))
r3[r2==0] <- 0
y1[r1==0] <- NA
y2[r2==0] <- NA
y3[r3==0] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", "y0", baselineVisitInt=FALSE, M=1)
(abs(mean(imps$y3[imps$trt==1])-1.5)<0.1) & (abs(mean(imps$y3[imps$trt==0])-0)<0.1)
}, TRUE)
})
test_that("Monotone missingness MAR imputation with 2 baseline covariates is unbiased at final time point", {
skip_on_cran()
expect_equal({
set.seed(1234)
n <- 50000
corr <- matrix(1, nrow=5, ncol=5) + diag(0.5, nrow=5)
corr
data <- MASS::mvrnorm(n, mu=c(2,0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
v <- data[,1]
y0 <- data[,2]
y1 <- data[,3]
y2 <- data[,4]
y3 <- data[,5]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<expit(1-y0))
r2 <- 1*(runif(n)<expit(2-(y1-y0)))
r2[r1==0] <- 0
r3 <- 1*(runif(n)<expit(2-(y2-y0)))
r3[r2==0] <- 0
y1[r1==0] <- NA
y2[r2==0] <- NA
y3[r3==0] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, v=v, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", c("v", "y0"), baselineVisitInt=FALSE, M=1)
(abs(mean(imps$y3[imps$trt==1])-1.5)<0.1) & (abs(mean(imps$y3[imps$trt==0])-0)<0.1)
}, TRUE)
})
test_that("Imputation with intermediate missingness runs", {
expect_error({
set.seed(1234)
n <- 500
corr <- matrix(1, nrow=4, ncol=4) + diag(0.5, nrow=4)
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y0 <- data[,1]
y1 <- data[,2]
y2 <- data[,3]
y3 <- data[,4]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<0.25)
r2 <- 1*(runif(n)<0.25)
r3 <- 1*(runif(n)<0.25)
y1[(r1==0)] <- NA
y2[(r2==0)] <- NA
y3[(r3==0)] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", "y0", baselineVisitInt=FALSE, M=2)
}, NA)
})
test_that("Imputation with only one intermediate missingness pattern runs", {
expect_error({
set.seed(1234)
n <- 500
corr <- matrix(1, nrow=4, ncol=4) + diag(0.5, nrow=4)
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y0 <- data[,1]
y1 <- data[,2]
y2 <- data[,3]
y3 <- data[,4]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<0.25)
y1[(r1==0)] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", "y0", baselineVisitInt=FALSE, M=2)
}, NA)
})
test_that("Imputation with intermediate missingness is unbiased", {
skip_on_cran()
expect_equal({
set.seed(1234)
n <- 50000
corr <- matrix(1, nrow=4, ncol=4) + diag(0.5, nrow=4)
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y0 <- data[,1]
y1 <- data[,2]
y2 <- data[,3]
y3 <- data[,4]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<0.25)
r2 <- 1*(runif(n)<0.25)
r3 <- 1*(runif(n)<0.25)
y1[(r1==0)] <- NA
y2[(r2==0)] <- NA
y3[(r3==0)] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", "y0", baselineVisitInt=FALSE, M=1)
(abs(mean(imps$y3[imps$trt==1])-1.5)<0.1) & (abs(mean(imps$y3[imps$trt==0])-0)<0.1)
}, TRUE)
})
test_that("Monotone missingness J2R imputation with M=2 runs", {
expect_error({
set.seed(1234)
n <- 500
corr <- matrix(1, nrow=4, ncol=4) + diag(0.5, nrow=4)
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y0 <- data[,1]
y1 <- data[,2]
y2 <- data[,3]
y3 <- data[,4]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<expit(1-y0))
r2 <- 1*(runif(n)<expit(2-(y1-y0)))
r2[r1==0] <- 0
r3 <- 1*(runif(n)<expit(2-(y2-y0)))
r3[r2==0] <- 0
y1[r1==0] <- NA
y2[r2==0] <- NA
y3[r3==0] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(obsData=wideData, outcomeVarStem="y", nVisits=3, trtVar="trt", baselineVars="y0", type="J2R", baselineVisitInt=FALSE, M=2)
}, NA)
})
test_that("J2R imputation Cro et al 2019 simulation study setup", {
skip_on_cran()
expect_equal({
set.seed(1234)
n <- 50000
corr <- matrix(c(0.4, 0.2, 0.2, 0.2, 0.5, 0.2, 0.2, 0.2, 0.6), byrow=TRUE, nrow=3)
corr
data <- MASS::mvrnorm(n, mu=c(2, 1.95, 1.9), Sigma=corr)
trt <- c(rep(0,n/2), rep(1,n/2))
y0 <- data[,1]
y1 <- data[,2]
y2 <- data[,3]
y1 <- y1+trt*(2.21-1.95)
y2 <- y2+trt*(2.9-1.9)
d <- runif(n)
y1[(d<0.25) & (trt==1)] <- NA
y2[(d<0.5) & (trt==1)] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, y1=y1, y2=y2)
imps <- refBasedCts(obsData=wideData, outcomeVarStem="y", nVisits=2, trtVar="trt", baselineVars="y0", type="J2R", baselineVisitInt=FALSE, M=1)
(abs(mean(imps$y2[imps$trt==1])-2.4)<0.05)
}, TRUE)
})
test_that("If you pass a factor as a baseline variable, you get an error", {
expect_error({
set.seed(1234)
n <- 500
corr <- matrix(1, nrow=4, ncol=4) + diag(0.5, nrow=4)
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y0 <- data[,1]
y1 <- data[,2]
y2 <- data[,3]
y3 <- data[,4]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<expit(1-y0))
r2 <- 1*(runif(n)<expit(2-(y1-y0)))
r2[r1==0] <- 0
r3 <- 1*(runif(n)<expit(2-(y2-y0)))
r3[r2==0] <- 0
y1[r1==0] <- NA
y2[r2==0] <- NA
y3[r3==0] <- NA
y0 <- 1*(y0<0)
wideData <- data.frame(id=1:n, trt=trt, y0=factor(y0), y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", "y0", baselineVisitInt=FALSE, M=2)
})
})
test_that("Monotone missingness MAR imputation with baseline time interactions runs", {
expect_error({
set.seed(1234)
n <- 500
corr <- matrix(1, nrow=4, ncol=4) + diag(0.5, nrow=4)
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y0 <- data[,1]
y1 <- data[,2]
y2 <- data[,3]
y3 <- data[,4]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<expit(1-y0))
r2 <- 1*(runif(n)<expit(2-(y1-y0)))
r2[r1==0] <- 0
r3 <- 1*(runif(n)<expit(2-(y2-y0)))
r3[r2==0] <- 0
y1[r1==0] <- NA
y2[r2==0] <- NA
y3[r3==0] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", "y0", baselineVisitInt=TRUE, M=1)
}, NA)
})
test_that("Monotone missingness MAR imputation with baseline time interactions is approximately unbiased", {
skip_on_cran()
expect_equal({
set.seed(1234)
n <- 50000
corr <- matrix(1, nrow=4, ncol=4) + diag(0.5, nrow=4)
corr[,1] <- c(1.5, 1, 0.75, 0.25)
corr[1,] <- corr[,1]
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
y0 <- data[,1]
y1 <- data[,2]
y2 <- data[,3]
y3 <- data[,4]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<expit(1-y0))
r2 <- 1*(runif(n)<expit(2-(y1-y0)))
r2[r1==0] <- 0
r3 <- 1*(runif(n)<expit(2-(y2-y0)))
r3[r2==0] <- 0
y1[r1==0] <- NA
y2[r2==0] <- NA
y3[r3==0] <- NA
wideData <- data.frame(id=1:n, trt=trt, y0=y0, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", "y0", baselineVisitInt=TRUE, M=1)
(abs(mean(imps$y3[imps$trt==1])-1.5)<0.1) & (abs(mean(imps$y3[imps$trt==0])-0)<0.1)
}, TRUE)
})
test_that("Monotone missingness MAR imputation with baseline time interactions two baselines runs", {
expect_error({
set.seed(1234)
n <- 500
corr <- matrix(1, nrow=5, ncol=5) + diag(0.5, nrow=5)
corr[,1] <- c(1.5, 1, 0.75, 0.5, 0.25)
corr[1,] <- corr[,1]
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
v <- data[,1]
y0 <- data[,2]
y1 <- data[,3]
y2 <- data[,4]
y3 <- data[,5]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<expit(1-y0))
r2 <- 1*(runif(n)<expit(2-(y1-y0)))
r2[r1==0] <- 0
r3 <- 1*(runif(n)<expit(2-(y2-y0)))
r3[r2==0] <- 0
y1[r1==0] <- NA
y2[r2==0] <- NA
y3[r3==0] <- NA
wideData <- data.frame(id=1:n, trt=trt, v=v, y0=y0, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", c("v", "y0"), baselineVisitInt=TRUE, M=1)
}, NA)
})
test_that("Monotone missingness MAR imputation with baseline time interactions two baselines is unbiased", {
skip_on_cran()
expect_equal({
set.seed(1234)
n <- 50000
corr <- matrix(1, nrow=5, ncol=5) + diag(0.5, nrow=5)
corr[,1] <- c(1.5, 1, 0.75, 0.5, 0.25)
corr[1,] <- corr[,1]
corr
data <- MASS::mvrnorm(n, mu=c(0,0,0,0,0), Sigma=corr)
trt <- 1*(runif(n)<0.5)
v <- data[,1]
y0 <- data[,2]
y1 <- data[,3]
y2 <- data[,4]
y3 <- data[,5]
y1 <- y1+trt*0.5
y2 <- y2+trt*1
y3 <- y3+trt*1.5
r1 <- 1*(runif(n)<expit(1-y0))
r2 <- 1*(runif(n)<expit(2-(y1-y0)))
r2[r1==0] <- 0
r3 <- 1*(runif(n)<expit(2-(y2-y0)))
r3[r2==0] <- 0
y1[r1==0] <- NA
y2[r2==0] <- NA
y3[r3==0] <- NA
wideData <- data.frame(id=1:n, trt=trt, v=v, y0=y0, y1=y1, y2=y2, y3=y3)
imps <- refBasedCts(wideData, "y", 3, "trt", c("v", "y0"), baselineVisitInt=TRUE, M=1)
(abs(mean(imps$y3[imps$trt==1])-1.5)<0.1) & (abs(mean(imps$y3[imps$trt==0])-0)<0.1)
}, TRUE)
}) |
svb.fit <- function(Y, delta, X, lambda=1, a0=1, b0=ncol(X),
mu.init=NULL, s.init=rep(0.05, ncol(X)), g.init=rep(0.5, ncol(X)),
maxiter=1e3, tol=1e-3, alpha=1, center=TRUE, verbose=TRUE)
{
if (!is.matrix(X)) stop("'X' must be a matrix")
if (!(lambda > 0)) stop("'lambda' must be greater than 0")
p <- ncol(X)
if (is.null(mu.init)) {
y <- survival::Surv(as.matrix(Y), as.matrix(as.numeric(delta)))
g <- glmnet::glmnet(X, y, family="cox", nlambda=10, alpha=alpha,
standardize=FALSE)
mu.init <- g$beta[ , ncol(g$beta)]
}
oY <- order(Y)
Y <- Y[oY]
delta <- delta[oY]
X <- X[oY, ]
if (center) {
X <- scale(X, center=T, scale=F)
}
res <- fit_partial(Y, delta, X, lambda, a0, b0,
mu.init, s.init, g.init, maxiter, tol, verbose)
res$lambda <- lambda
res$a0 <- a0
res$b0 <- b0
res$beta_hat <- res$m * res$g
res$inclusion_prob <- res$g
return(res)
} |
test_that("insert_named.list", {
x = named_list(letters[1:3], 1)
x = insert_named(x, list(d = 1))
expect_list(x, len = 4L)
expect_set_equal(names(x), letters[1:4])
expect_equal(x$d, 1)
x = remove_named(x, c("d", "e"))
expect_list(x, len = 3L)
expect_set_equal(names(x), letters[1:3])
expect_equal(x$d, NULL)
x = insert_named(list(), list(a = 1))
expect_list(x, len = 1L)
expect_equal(x$a, 1)
x = insert_named(c(a = 1), c(b = 2))
expect_numeric(x, len = 2L)
expect_equal(x[["a"]], 1)
expect_equal(x[["b"]], 2)
x = remove_named(x, "a")
expect_numeric(x, len = 1L)
expect_equal(x[["b"]], 2)
})
test_that("insert_named.environment", {
x = list2env(named_list(letters[1:3], 1))
x = insert_named(x, list(d = 1))
expect_environment(x, contains = letters[1:4])
expect_equal(x$d, 1)
x = remove_named(x, c("d", "e"))
expect_environment(x, contains = letters[1:3])
expect_equal(x$d, NULL)
x = insert_named(new.env(), list(a = 1))
expect_environment(x, contains = "a")
expect_equal(x$a, 1)
})
test_that("insert_named.data.frame", {
x = as.data.frame(named_list(letters[1:3], 1))
x = insert_named(x, list(d = 1))
expect_data_frame(x, nrows = 1, ncols = 4)
expect_set_equal(names(x), letters[1:4])
expect_equal(x$d, 1)
x = remove_named(x, c("d", "e"))
expect_data_frame(x, nrows = 1, ncols = 3)
expect_set_equal(names(x), letters[1:3])
expect_equal(x$d, NULL)
x = insert_named(data.frame(), list(a = 1))
expect_data_frame(x, nrows = 1, ncols = 1)
expect_equal(x$a, 1)
})
test_that("insert_named.data.table", {
x = as.data.table(named_list(letters[1:3], 1))
x = insert_named(x, list(d = 1))
expect_data_table(x, nrows = 1, ncols = 4)
expect_set_equal(names(x), letters[1:4])
expect_equal(x$d, 1)
x = remove_named(x, c("d", "e"))
expect_data_table(x, nrows = 1, ncols = 3)
expect_set_equal(names(x), letters[1:3])
expect_equal(x$d, NULL)
x = insert_named(data.table(), list(a = 1))
expect_data_table(x, nrows = 1, ncols = 1)
expect_equal(x$a, 1)
}) |
weights.fixest = function(object, ...){
w = object[["weights"]]
if(is.null(w)) return(NULL)
w = fill_with_na(w, object)
w
}
sigma.fixest = function(object, ...){
sqrt(deviance(object) / (object$nobs - object$nparams))
}
deviance.fixest = function(object, ...){
if(isTRUE(object$lean)){
stop("The method 'deviance.fixest' cannot be applied to 'lean' fixest objects. Please re-estimate with 'lean = FALSE'.")
}
method = object$method
family = object$family
r = object$residuals
w = object[["weights"]]
if(is.null(w)) w = rep(1, length(r))
if(is.null(r) && !method %in% c("fepois", "feglm")){
stop("The method 'deviance.fixest' cannot be applied to a 'lean' summary. Please apply it to the estimation object directly.")
}
if(method %in% c("feols", "feols.fit") || (method %in% c("femlm", "feNmlm") && family == "gaussian")){
res = sum(w * r**2)
} else if(method %in% c("fepois", "feglm")){
res = object$deviance
} else {
mu = object$fitted.values
theta = ifelse(family == "negbin", object$theta, 1)
if(family == "poisson"){
dev.resids = poisson()$dev.resids
} else if(family == "logit"){
dev.resids = binomial()$dev.resids
} else if(family == "negbin"){
dev.resids = function(y, mu, wt) 2 * wt * (y * log(pmax(1, y)/mu) - (y + theta) * log((y + theta)/(mu + theta)))
}
y = r + mu
res = sum(dev.resids(y, mu, w))
}
res
}
hatvalues.fixest = function(model, ...){
if(isTRUE(model$lean)){
stop("The method 'hatvalues.fixest' cannot be applied to 'lean' fixest objects. Please re-estimate with 'lean = FALSE'.")
}
validate_dots()
method = model$method_type
family = model$family
msg = "hatvalues.fixest: 'hatvalues' is not implemented for estimations with fixed-effects."
if(!is.null(model$fixef_id)){
stop(msg)
}
if(method == "feols"){
X = model.matrix(model)
res = cpp_diag_XUtX(X, model$cov.iid / model$sigma2)
} else if(method == "feglm"){
XW = model.matrix(model) * sqrt(model$irls_weights)
res = cpp_diag_XUtX(XW, model$cov.iid)
} else {
stop("'hatvalues' is currently not implemented for function ", method, ".")
}
res
}
estfun.fixest = function(x, ...){
if(isTRUE(x$lean)){
stop("The method 'estfun.fixest' cannot be applied to 'lean' fixest objects. Please re-estimate with 'lean = FALSE'.")
}
x$scores
}
NULL
NULL
NULL
bread.fixest = function(x, ...){
validate_dots()
method = x$method_type
family = x$family
if(method == "feols"){
res = x$cov.iid / x$sigma2 * x$nobs
} else if(method == "feglm"){
res = x$cov.iid * x$nobs
} else {
stop("'bread' is not currently implemented for function ", method, ".")
}
res
} |
PredictionOutput <- R6::R6Class(
classname = "PredictionOutput",
portable = TRUE,
public = list(
initialize = function(predictions, type, target) {
private$predictions <- predictions
private$type <- type
private$target <- target
},
getPredictions = function() { private$predictions },
getType = function() { private$type },
getTarget = function() { private$target }
),
private = list(
predictions = NULL,
type = NULL,
target = NULL
)
) |
forestRK <- function(X = data.frame(), Y.new = c(), min.num.obs.end.node.tree = 5, nbags, samp.size, entropy = TRUE){
if(!(dim(X)[1] > 1) || !(dim(X)[2] >= 1) || is.null(X)){
stop("Invalid dimension for the dataset X")
}
if(!(length(Y.new) > 1) || is.null(Y.new)){
stop("Invalid length for the vector Y.new")
}
if(!(dim(X)[1] == length(Y.new))){
stop("The number of observations in the dataset X and the vector Y.new do not match")
}
if(!(min.num.obs.end.node.tree > 1)){
stop("'min.num.obs.end.node.tree' (minimum number of data points contained in each end node) has to be greater than 1")
}
if(is.null(nbags) || !(nbags > 1)){
stop("'nbags' (number of bags to be generated) needs to be greater than or equal to 2")
}
if(is.null(samp.size) || !(samp.size > 1)){
stop("'samp.size' (sample size for each bag) needs to be greater than or equal to 2")
}
if(!(is.boolean(entropy))){
stop("The parameter 'entropy' has to be either TRUE or FALSE")
}
ent.status <- entropy
n.col.X <- dim(X)[2]
dat <- data.frame(X, Y.new)
forest.rk.tree.list <- list()
bootsamp.list <- bstrap(dat, nbags, samp.size)
for (z in 1:(length(bootsamp.list))){
forest.rk.tree.list[[z]] <- construct.treeRK(bootsamp.list[[z]][, 1:n.col.X], as.vector(bootsamp.list[[z]][ , (n.col.X + 1)]), min.num.obs.end.node.tree, ent.status)
}
results <- list(X, forest.rk.tree.list, bootsamp.list, ent.status)
names(results) <- c("X", "forest.rk.tree.list", "bootsamp.list", "ent.status")
results
} |
plotGradeStat2D <- function(variabl1, variabl2, Xaxis = "", Yaxis = "", cex.text=0.8, addLabels=TRUE) {
tab <- table(factor(variabl1),factor(variabl2))
tabSum <- addmargins(tab, 2)
tabProp<- prop.table(tabSum, 2)
tabCS <- apply(tabProp, 2, cumsum)
kolor <- c("
"
)[1:ncol(tab)]
plot(c(0,1),c(0,1),type="n",pch=19,xlab=Xaxis,ylab=Yaxis)
abline(0,1,col="grey")
abline(h=seq(0,1,0.2),col="grey95",lty=3)
abline(v=seq(0,1,0.2),col="grey95",lty=3)
for (i in 1:ncol(tab)) {
points(c(0,tabCS[,"Sum"]), c(0,tabCS[,i]), type="b", pch=19, col=kolor[i])
}
legend("topleft", colnames(tab), col=kolor, pch=10, lwd=3,bty="n")
par(xpd=NA)
if (addLabels)
text(tabCS[,"Sum"], apply(tabCS,1,min),rownames(tabCS), srt=-45, adj=c(0,0),cex=cex.text, col="black")
par(xpd=F)
}
plotGradeStat2D2 <- function(variabl1, variabl2, Xaxis="", Xaxis1=Xaxis, Xaxis2=Xaxis, Yaxis="", Yaxis1=Yaxis, Yaxis2=Yaxis, ...) {
par(mfrow=c(1,2))
par(xpd=F)
plotGradeStat2D(variabl1, variabl2, Xaxis=Xaxis1, Yaxis=Yaxis1, ...)
plotGradeStat2D(variabl2, variabl1, Xaxis=Xaxis2, Yaxis=Yaxis2, ...)
}
plotGradeStat <- function(variabl1, variabl2, decreasing = TRUE, Xaxis = "", Yaxis = "", skala=c(0.005,0.5), cex.text=0.8, cutoff = 0.01) {
zm1r <- variabl1/sum(variabl1)
zm2r <- variabl2/sum(variabl2)
iloraz <- zm1r/zm2r
if (decreasing) {
zm1r <- zm1r[order(iloraz, decreasing=FALSE), 1, drop=FALSE]
zm2r <- zm2r[order(iloraz, decreasing=FALSE), 1, drop=FALSE]
iloraz <- zm1r/zm2r
}
par(mfrow=c(1,2))
par(xpd=F)
plot(c(0,cumsum(zm1r[,1])),c(0,cumsum(zm2r[,1])),type="b",pch=19,xlab=Xaxis,ylab=Yaxis)
abline(0,1,col="grey")
par(xpd=NA)
odleglosci <- sqrt(diff(c(0,cumsum(zm1r[,1])))^2+diff(c(0,cumsum(zm2r[,1])))^2)
korekta <- numeric(length(odleglosci))
for (i in seq_along(korekta)) {
if (odleglosci[i] < cutoff)
korekta[i] <- cutoff + korekta[i-1]
}
text(cumsum(zm1r[,1])+korekta+2*cutoff,cumsum(zm2r[,1])+korekta-2*cutoff,rownames(zm1r), srt=-45, adj=c(0,0),cex=cex.text)
text(cumsum(zm1r[,1])+korekta-2*cutoff,cumsum(zm2r[,1])+korekta+2*cutoff,paste(round((1/iloraz[,1]-1)*1000)/10," %",sep=""), srt=-45, adj=c(1,1),cex=cex.text)
par(xpd=F)
plot(1,type="n",log="xy",xlim=skala,ylim=skala, las=1, cex.axis=0.8, xlab=Xaxis, ylab=Yaxis)
abline(0,1,col="grey")
abline(h=c(0.0001*c(1,2,5),0.001*c(1,2,5),0.01*c(1,2,5),0.1*c(1,2,5)),col="grey95")
abline(v=c(0.0001*c(1,2,5),0.001*c(1,2,5),0.01*c(1,2,5),0.1*c(1,2,5)),col="grey95")
points(zm1r[,1],zm2r[,1],pch=19)
par(xpd=NA)
text(zm1r[,1],zm2r[,1],rownames(zm1r), srt=-45, adj=c(-0.1,-0.1),cex=cex.text)
par(xpd=F)
} |
"us.twitter.covariates" |
library(corncob)
library(phyloseq)
context("Test differentialTest")
set.seed(1)
data(soil_phylo)
soil <- phyloseq::subset_samples(soil_phylo, DayAmdmt %in% c(11,21))
subsoil <- phyloseq::prune_taxa(x = soil, taxa = rownames(otu_table(soil))[301:325])
subsoil_disc <- phyloseq::prune_taxa(x = soil, taxa = rownames(otu_table(soil))[c(3001:3024, 7027)])
temp <- differentialTest(formula = ~ Plants + DayAmdmt,
phi.formula = ~ Plants + DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "LRT",
inits = rbind(rep(.01, 6)),
inits_null = rbind(rep(0.01, 2)))
temp2 <- differentialTest(formula = ~ Plants + DayAmdmt,
phi.formula = ~ Plants + DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "LRT",
filter_discriminant = FALSE,
inits = rbind(rep(.01, 6)),
inits_null = rbind(rep(0.01, 2)))
temp3 <- differentialTest(formula = ~ Plants + DayAmdmt,
phi.formula = ~ Plants + DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil_disc, boot = FALSE, test = "LRT",
inits = rbind(rep(.01, 6)),
inits_null = rbind(rep(0.01, 2)))
temp_badinits1 <- differentialTest(formula = ~ Plants + DayAmdmt,
phi.formula = ~ Plants + DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "LRT",
inits = rbind(rep(Inf, 6)),
inits_null = rbind(rep(0.01, 2)))
temp_badinits2 <- differentialTest(formula = ~ Plants + DayAmdmt,
phi.formula = ~ Plants + DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "LRT",
inits = rbind(rep(.01, 6)),
inits_null = rbind(rep(Inf, 2)))
temp_noinit_sing <- differentialTest(formula = ~ DayAmdmt,
phi.formula = ~ DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1, boot = FALSE, test = "LRT",
data = subsoil)
temp_noinit <- differentialTest(formula = ~ Plants + DayAmdmt,
phi.formula = ~ Plants + DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1, boot = FALSE, test = "LRT",
data = subsoil)
temp_sing <- differentialTest(formula = ~ DayAmdmt,
phi.formula = ~ DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "LRT",
inits = rbind(rep(.01, 4)))
temp_badinits3 <- differentialTest(formula = ~ DayAmdmt,
phi.formula = ~ DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "LRT",
inits = rbind(rep(Inf, 4)))
mydat <- phyloseq::get_taxa(subsoil)
mysampdat <- phyloseq::get_variable(subsoil)
temp_nonphylo <- differentialTest(formula = ~ DayAmdmt,
phi.formula = ~ DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = mydat, boot = FALSE, test = "LRT",
sample_data = mysampdat,
inits = rbind(rep(.01, 4)))
temp_wald <- differentialTest(formula = ~ Plants + DayAmdmt,
phi.formula = ~ Plants + DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "Wald",
inits = rbind(rep(.01, 6)),
inits_null = rbind(rep(0.01, 2)))
temp_pblrt <- differentialTest(formula = ~ Plants + DayAmdmt,
phi.formula = ~ Plants + DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = TRUE, B = 5, test = "LRT",
inits = rbind(rep(.01, 6)),
inits_null = rbind(rep(0.01, 2)))
temp_pbwald <- differentialTest(formula = ~ Plants + DayAmdmt,
phi.formula = ~ Plants + DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = TRUE, B = 5, test = "Wald",
inits = rbind(rep(.01, 6)),
inits_null = rbind(rep(0.01, 2)))
test_that("differentialTest works", {
expect_is(temp, "differentialTest")
expect_is(temp2, "differentialTest")
expect_is(temp3, "differentialTest")
expect_is(temp_wald, "differentialTest")
expect_is(temp_pbwald, "differentialTest")
expect_is(temp_pblrt, "differentialTest")
expect_is(temp, "differentialTest")
expect_is(temp_sing, "differentialTest")
expect_is(temp_nonphylo, "differentialTest")
expect_is(temp_noinit, "differentialTest")
expect_is(temp_noinit_sing, "differentialTest")
expect_is(temp_badinits1, "differentialTest")
expect_is(temp_badinits2, "differentialTest")
expect_is(temp_badinits3, "differentialTest")
})
test_that("differentialTest S3 methods", {
expect_is(plot(temp), "ggplot")
expect_is(plot(temp, level = c("Order", "Class")), "ggplot")
expect_is(plot(temp, level = "Kingdom"), "ggplot")
expect_output(expect_null(print(temp)))
})
test_that("differentialTest works without phyloseq", {
expect_true(all.equal(temp_sing$p, temp_nonphylo$p))
})
test_that("otu_to_taxonomy works", {
expect_is(otu_to_taxonomy(temp$significant_taxa, soil_phylo), "character")
expect_error(otu_to_taxonomy(temp$significant_taxa, mysampdat))
})
test_that("requires data frame, matrix, or phyloseq", {
expect_error(differentialTest(formula = ~ DayAmdmt,
phi.formula = ~ DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = c(1,2,3), boot = FALSE, test = "LRT",
inits = rbind(rep(.01, 4))))
})
test_that("inits require correct length", {
expect_error(differentialTest(formula = ~ DayAmdmt,
phi.formula = ~ DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "LRT",
inits = rbind(rep(.01, 6))))
expect_error(differentialTest(formula = ~ DayAmdmt,
phi.formula = ~ DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "LRT",
inits_null = rbind(rep(.01, 4))))
})
test_that("try_only works", {
expect_is(differentialTest(formula = ~ DayAmdmt,
phi.formula = ~ DayAmdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "LRT",
try_only = 1:2), "differentialTest")
})
test_that("overspecification error message", {
expect_error(differentialTest(formula = ~ Plants*Day*Amdmt,
phi.formula = ~ Plants*Day*Amdmt,
formula_null = ~ 1,
phi.formula_null = ~ 1,
data = subsoil, boot = FALSE, test = "LRT",
try_only = 1:2))
})
test_that("differentialTest does NAs correctly", {
expect_equal(length(temp$p), 25)
expect_equal(length(temp$p_fdr), 25)
expect_equal(length(temp3$p), 25)
expect_equal(length(temp3$p_fdr), 25)
}) |
func.med.RPD <- function(functions, deriv = c(0,1))
{
depth.RPD(functions, deriv = deriv)$median
} |
NULL
.onLoad <- function(libname, pkgname) {
if (is.null(getOption("libbi_args"))) options(libbi_args = list())
} |
test_rotate <- function(){
plot(-1:1, -1:1, type = "n", xlab = "Re", ylab = "Im")
K <- 16; text(exp(1i * 2 * pi * (1:K) / K), col = 2, srt = 30)
}
test_circle <- function(){
N <- nrow(trees)
with(trees, {
symbols(Height, Volume, circles = Girth/24, inches = FALSE, bg = "blue",
main = "Trees' Girth")
op <- palette(rainbow(N, end = 0.9))
symbols(Height, Volume, circles = Girth/16, inches = FALSE, bg = 1:N,
fg = "gray30", main = "symbols(*, circles = Girth/16, bg = 1:N)")
palette(op)
})
}
test_rect <- function(){
op <- par(bg = "thistle")
plot(c(100, 250), c(300, 450), type = "n", xlab = "", ylab = "",
main = "2 x 11 rectangles; 'rect(100+i,300+i, 150+i,380+i)'")
i <- 4*(0:10)
rect(100+i, 300+i, 150+i, 380+i, col = rainbow(11, start = 0.7, end = 0.1))
rect(240-i, 320+i, 250-i, 410+i, col = heat.colors(11), lwd = i/5)
}
test_path <- function(){dev
plotPath <- function(x, y, col = "grey", rule = "winding") {
plot.new()
plot.window(range(x, na.rm = TRUE), range(y, na.rm = TRUE))
polypath(x, y, col = col, rule = rule)
if (!is.na(col))
mtext(paste("Rule:", rule), side = 1, line = 0)
}
plotRules <- function(x, y, title) {
plotPath(x, y)
plotPath(x, y, rule = "evenodd")
mtext(title, side = 3, line = 0)
plotPath(x, y, col = NA)
}
op <- par(mfrow = c(5, 3), mar = c(2, 1, 1, 1))
plotRules(c(.1, .1, .9, .9, NA, .2, .2, .8, .8),
c(.1, .9, .9, .1, NA, .2, .8, .8, .2),
"Nested rectangles, both clockwise")
}
test_ggplot <- function(){
print(ggplot2::qplot(cars$speed, cars$dist, geom = c("point", "smooth")))
}
test_ggplot2 <- function(){
ggplot(diamonds, aes(cut, price)) +
geom_boxplot() +
coord_flip()
}
unlink("*.png")
png("cairo_small.png", width = 800, height = 600)
par(cex = 96/72)
test_ggplot()
dev.off()
png("cairo_large.png", width = 1600, height = 1200, res = 144)
par(cex = 96/72)
test_ggplot()
dev.off()
dev <- magick::image_graph(800, 600, bg = 'white')
test_ggplot()
dev.off()
image_write(dev, "magick_small.png", format = 'png')
dev <- magick::image_graph(1600, 1200, bg = 'white', res = 144)
test_ggplot()
dev.off()
image_write(dev, "magick_large.png", format = 'png')
img <- image_graph(900, 600, bg = 'white', res = 96)
test_ggplot()
dev.off()
print(img)
test_ggplot() |
Plot.Data.Events <-
function (yy, paciente, inicio, dias, censored, especiales, colevent = "red",
colcensor = "blue")
{ p <- ncol(yy)
N <- nrow(yy)
nn <- length(paciente)
n <- nn
dev.new()
par(bg = "white")
plot(inicio, paciente, xlim = c(-1, (max(dias + inicio) +
1)), ylim = c(-0.5, n), xlab = "Time", ylab = "Unit",
pch = 19, cex = 0.4, col = "dark blue", sub = R.version.string)
title(main = list("Graphical Representation of Recurrent Event Data",
cex = 0.8, font = 2.3, col = "dark blue"))
mtext("Research Group: AVANCE USE R!", cex = 0.7, font = 2,
col = "dark blue", line = 1)
mtext("Software made by: Dr. Carlos Martinez", cex = 0.6, font = 2,
col = "dark red", line = 0)
x1 <- -0.5
y <- 0.5
x2 <- max(dias + inicio)/5 - 1
x3 <- 2 * max(dias + inicio)/5 - 2
legend(x1, y, c("Start"), bty = "n", cex = 0.6, pch = 19,
col = "dark blue")
legend(x2, y, c("Event"), bty = "n", cex = 0.6, pch = 4,
col = colevent)
legend(x3, y, c("Censored"), bty = "n", cex = 0.6, pch = 0,
col = colcensor)
for (i in 1:n) {
temp1 <- censored[i]
if (temp1 == 0)
temp1 <- 0
else temp1 <- 4
segments(inicio[i], paciente[i], dias[i], paciente[i],
col = "black", lty = "dotted")
}
a <- 1
if (a == 1) {
m <- nrow(especiales)
for (j in 1:m) {
temp2 <- especiales[j, 3]
if (temp2 == 1)
temp2 <- 4
else {
if (temp2 == 0)
temp2 <- 0
else temp2 <- 0
}
temp3 <- 0
for (i in 1:n) {
if (especiales[j, 1] <= n)
temp3[especiales[j, 1] == i] <- inicio[i]
}
if (temp2 == 4) {
colorx1 <- colevent
us <- "X"
}
else {
colorx1 <- colcensor
us <- "O"
}
if (especiales[j, 1] <= n)
points((temp3 + especiales[j, 2]), especiales[j,
1], pch = us, col = colorx1, cex = 0.5)
}
}
} |
setMethodS3("getAttributes", "GenericDataFile", function(this, ...) {
attrs <- this$.attributes
if (length(attrs) == 0) {
attrs <- list()
} else {
names <- names(attrs)
if (length(names) > 0) {
o <- order(names)
attrs <- attrs[o]
}
}
attrs
}, protected=TRUE)
setMethodS3("setAttributes", "GenericDataFile", function(this, ...) {
args <- list(...)
names <- names(args)
if (is.null(names)) {
throw("No named arguments specified.")
}
attrs <- this$.attributes
attrs[names] <- args
this$.attributes <- attrs
invisible(args)
}, protected=TRUE)
setMethodS3("getAttribute", "GenericDataFile", function(this, name, defaultValue=NULL, ...) {
attrs <- this$.attributes
if (name %in% names(attrs)) {
value <- attrs[[name]]
} else {
value <- defaultValue
}
value
}, protected=TRUE)
setMethodS3("setAttribute", "GenericDataFile", function(this, name, value, ...) {
attrs <- this$.attributes
attrs[[name]] <- value
this$.attributes <- attrs
invisible(attrs[name])
}, protected=TRUE)
setMethodS3("testAttributes", "GenericDataFile", function(this, select, ...) {
attrs <- getAttributes(this)
expr <- substitute(select)
res <- eval(expr, envir=attrs, enclos=parent.frame())
res
}, protected=TRUE)
setMethodS3("setAttributesBy", "GenericDataFile", function(this, object, ...) {
if (inherits(object, "character")) {
setAttributesByTags(this, object, ...)
} else {
throw("Unknown type on argument 'object': ", class(object)[1])
}
}, protected=TRUE)
setMethodS3("setAttributesByTags", "GenericDataFile", function(this, tags=getTags(this), ...) {
if (length(tags) > 0) {
tags <- unlist(strsplit(tags, split=","), use.names=FALSE)
tags <- trim(tags)
}
newAttrs <- list()
pattern <- "^([abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ]+)=(.*)$"
values <- grep(pattern, tags, value=TRUE)
for (kk in seq_along(values)) {
tag <- values[[kk]]
key <- gsub(pattern, "\\1", tag)
value <- gsub(pattern, "\\2", tag)
suppressWarnings({
value2 <- as.integer(value)
if (!identical(value2 == value, TRUE)) {
value2 <- as.double(value)
if (!identical(value2 == value, TRUE)) {
value2 <- as.character(value)
}
}
value <- value2
})
newAttrs <- c(newAttrs, setAttribute(this, key, value))
}
invisible(newAttrs)
}, protected=TRUE) |
.Rd_get_latex <-
function(x) {
rval <- NULL
file <- textConnection("rval", "w", local = TRUE)
save <- options(useFancyQuotes = FALSE)
sink(file)
tryCatch(Rd2latex(x, fragment=TRUE),
finally = {sink(); options(save); close(file)})
if (is.null(rval)) rval <- character()
else enc2utf8(rval)
}
latex_canonical_encoding <- function(encoding)
{
if (encoding == "") encoding <- utils::localeToCharset()[1L]
encoding <- tolower(encoding)
encoding <- sub("iso_8859-([0-9]+)", "iso-8859-\\1", encoding)
encoding <- sub("iso8859-([0-9]+)", "iso-8859-\\1", encoding)
encoding[encoding == "iso-8859-1"] <- "latin1"
encoding[encoding == "iso-8859-2"] <- "latin2"
encoding[encoding == "iso-8859-3"] <- "latin3"
encoding[encoding == "iso-8859-4"] <- "latin4"
encoding[encoding == "iso-8859-5"] <- "cyrillic"
encoding[encoding == "iso-8859-6"] <- "arabic"
encoding[encoding == "iso-8859-7"] <- "greek"
encoding[encoding == "iso-8859-8"] <- "hebrew"
encoding[encoding == "iso-8859-9"] <- "latin5"
encoding[encoding == "iso-8859-10"] <- "latin6"
encoding[encoding == "iso-8859-14"] <- "latin8"
encoding[encoding %in% c("latin-9", "iso-8859-15")] <- "latin9"
encoding[encoding == "iso-8859-16"] <- "latin10"
encoding[encoding == "utf-8"] <- "utf8"
encoding
}
Rd2latex <- function(Rd, out="", defines=.Platform$OS.type, stages="render",
outputEncoding = "ASCII", fragment = FALSE, ...,
writeEncoding = TRUE)
{
encode_warn <- FALSE
WriteLines <-
if(outputEncoding == "UTF-8" ||
(outputEncoding == "" && l10n_info()[["UTF-8"]])) {
function(x, con, outputEncoding, ...)
writeLines(x, con, useBytes = TRUE, ...)
} else {
function(x, con, outputEncoding, ...) {
x <- iconv(x, "UTF-8", outputEncoding, mark=FALSE)
if (anyNA(x)) {
x <- iconv(x, "UTF-8", outputEncoding,
sub="byte", mark=FALSE)
encode_warn <<- TRUE
}
writeLines(x, con, useBytes = TRUE, ...)
}
}
last_char <- ""
of0 <- function(...) of1(paste0(...))
of1 <- function(text) {
nc <- nchar(text)
last_char <<- substr(text, nc, nc)
WriteLines(text, con, outputEncoding, sep = "")
}
trim <- function(x) {
x <- psub1("^\\s*", "", as.character(x))
psub1("\\s*$", "", x)
}
envTitles <- c("\\description"="Description", "\\usage"="Usage",
"\\arguments"="Arguments",
"\\format"="Format", "\\details"="Details", "\\note"="Note",
"\\section"="", "\\author"="Author",
"\\references"="References", "\\source"="Source",
"\\seealso"="SeeAlso", "\\examples"="Examples",
"\\value"="Value")
sectionExtras <-
c("\\usage"="verbatim",
"\\arguments"="ldescription",
"\\examples"="ExampleCode")
inCodeBlock <- FALSE
inCode <- FALSE
inEqn <- FALSE
inPre <- FALSE
sectionLevel <- 0
hasFigures <- FALSE
startByte <- function(x) {
srcref <- attr(x, "srcref")
if (is.null(srcref)) NA
else srcref[2L]
}
addParaBreaks <- function(x, tag) {
start <- startByte(x)
if (isBlankLineRd(x)) "\n"
else if (identical(start, 1L)) psub("^\\s+", "", x)
else x
}
texify <- function(x, code = inCodeBlock) {
if(inEqn) return(x)
if (!code) {
x <- fsub("\\", "\\bsl", x)
x <- psub("([&$%_
x <- fsub("{", "\\{", x)
x <- fsub("}", "\\}", x)
x <- fsub("^", "\\textasciicircum{}", x)
x <- fsub("~", "\\textasciitilde{}", x)
x <- fsub("\\bsl", "\\bsl{}", x)
} else {
x <- psub("\\\\[l]{0,1}dots", "...", as.character(x))
x <- psub("\\\\([$^&~_
if (inCodeBlock) {
x <- fsub1('"\\{"', '"{"', x)
} else if (inPre) {
BSL = '@BSL@';
x <- fsub("\\", BSL, x)
x <- psub("(?<!\\\\)\\{", "\\\\{", x)
x <- psub("(?<!\\\\)}", "\\\\}", x)
x <- fsub(BSL, "\\bsl{}", x)
x <- psub("\\\\\\\\var\\\\\\{([^\\\\]*)\\\\}", "\\\\var{\\1}", x)
} else {
BSL = '@BSL@';
x <- fsub("\\", BSL, x)
x <- psub("(?<!\\\\)\\{", "\\\\{", x)
x <- psub("(?<!\\\\)}", "\\\\}", x)
x <- psub("(?<!\\\\)([&$%_
x <- fsub("^", "\\textasciicircum{}", x)
x <- fsub("~", "\\textasciitilde{}", x)
x <- fsub(BSL, "\\bsl{}", x)
x <- fsub("<<", "<{}<", x)
x <- fsub(">>", ">{}>", x)
x <- fsub(",,", ",{},", x)
}
}
x
}
wrappers <- list("\\dQuote" =c("``", "''"),
"\\sQuote" =c("`", "'"),
"\\cite" =c("\\Cite{", "}"))
writeWrapped <- function(block, tag) {
wrapper <- wrappers[[tag]]
if (is.null(wrapper))
wrapper <- c(paste0(tag, "{"), "}")
of1(wrapper[1L])
writeContent(block, tag)
of1(wrapper[2L])
}
writeURL <- function(block, tag) {
if (tag == "\\url")
url <- as.character(block)
else {
url <- as.character(block[[1L]])
tag <- "\\Rhref"
}
url <- trimws(gsub("\n", "",
paste(as.character(url), collapse = ""),
fixed = TRUE, useBytes = TRUE))
url <- gsub("%", "\\%", url, fixed = TRUE, useBytes = TRUE)
of0(tag, "{", url, "}")
if (tag == "\\Rhref") {
of1("{")
writeContent(block[[2L]], tag)
of1("}")
}
}
writeLink <- function(tag, block) {
parts <- get_link(block, tag)
of0("\\LinkA{", latex_escape_link(parts$topic), "}{",
latex_link_trans0(parts$dest), "}")
}
writeDR <- function(block, tag) {
if (length(block) > 1L) {
of1('
writeContent(block, tag)
of1('\n
} else {
of1('
writeContent(block, tag)
}
}
ltxstriptitle <- function(x)
{
x <- fsub("\\R", "\\R{}", x)
x <- psub("(?<!\\\\)([&$%_
x <- fsub("^", "\\textasciicircum{}", x)
x <- fsub("~", "\\textasciitilde{}", x)
x
}
latex_escape_name <- function(x)
{
x <- psub("([$
x <- fsub("{", "\\textbraceleft{}", x)
x <- fsub("}", "\\textbraceright{}", x)
x <- fsub("^", "\\textasciicircum{}", x)
x <- fsub("~", "\\textasciitilde{}", x)
x <- fsub("%", "\\Rpercent{}", x)
x <- fsub("\\\\", "\\textbackslash{}", x)
x <- fsub("<<", "<{}<", x)
x <- fsub(">>", ">{}>", x)
x
}
latex_escape_link <- function(x)
{
x <- fsub("\\_", "_", x)
latex_escape_name(x)
}
latex_link_trans0 <- function(x)
{
x <- fsub("\\Rdash", ".Rdash.", x)
x <- fsub("-", ".Rdash.", x)
x <- fsub("\\_", ".Rul.", x)
x <- fsub("\\$", ".Rdol.", x)
x <- fsub("\\^", ".Rcaret.", x)
x <- fsub("^", ".Rcaret.", x)
x <- fsub("_", ".Rul.", x)
x <- fsub("$", ".Rdol.", x)
x <- fsub("\\
x <- fsub("
x <- fsub("\\&", ".Ramp.", x)
x <- fsub("&", ".Ramp.", x)
x <- fsub("\\~", ".Rtilde.", x)
x <- fsub("~", ".Rtilde.", x)
x <- fsub("\\%", ".Rpcent.", x)
x <- fsub("%", ".Rpcent.", x)
x <- fsub("\\\\", ".Rbl.", x)
x <- fsub("{", ".Rlbrace.", x)
x <- fsub("}", ".Rrbrace.", x)
x
}
latex_code_alias <- function(x)
{
x <- fsub("{", "\\{", x)
x <- fsub("}", "\\}", x)
x <- psub("(?<!\\\\)([&$%_
x <- fsub("^", "\\textasciicircum{}", x)
x <- fsub("~", "\\textasciitilde{}", x)
x <- fsub("<-", "<\\Rdash{}", x)
x <- psub("([!|])", '"\\1', x)
x
}
currentAlias <- NA_character_
writeAlias <- function(block, tag) {
alias <- as.character(block)
aa <- "\\aliasA{"
if(grepl("[|{(]", alias)) aa <- "\\aliasB{"
if(is.na(currentAlias)) currentAlias <<- name
if (pmatch(paste0(currentAlias, "."), alias, 0L)) {
aa <- "\\methaliasA{"
} else currentAlias <<- alias
if (alias == name) return()
alias2 <- latex_link_trans0(alias)
of0(aa, latex_code_alias(alias), "}{",
latex_escape_name(name), "}{", alias2, "}\n")
}
writeBlock <- function(block, tag, blocktag) {
switch(tag,
UNKNOWN =,
VERB = of1(texify(block, TRUE)),
RCODE = of1(texify(block, TRUE)),
TEXT = of1(addParaBreaks(texify(block), blocktag)),
USERMACRO =,
"\\newcommand" =,
"\\renewcommand" =,
COMMENT = {},
LIST = writeContent(block, tag),
"\\describe"= {
of1("\\begin{description}\n")
writeContent(block, tag)
of1("\n\\end{description}\n")
},
"\\enumerate"={
of1("\\begin{enumerate}\n")
writeContent(block, tag)
of1("\n\\end{enumerate}\n")
},
"\\itemize"= {
of1("\\begin{itemize}\n")
writeContent(block, tag)
of1("\n\\end{itemize}\n")
},
"\\command"=,
"\\env" =,
"\\kbd"=,
"\\option" =,
"\\samp" = writeWrapped(block, tag),
"\\url"=,
"\\href"= writeURL(block, tag),
"\\code"= {
inCode <<- TRUE
writeWrapped(block, tag)
inCode <<- FALSE
},
"\\acronym" =,
"\\bold"=,
"\\dfn"=,
"\\dQuote"=,
"\\email"=,
"\\emph"=,
"\\file" =,
"\\pkg" =,
"\\sQuote" =,
"\\strong"=,
"\\var" =,
"\\cite" =
if (inCodeBlock) writeContent(block, tag)
else writeWrapped(block, tag),
"\\preformatted"= {
inPre <<- TRUE
of1("\\begin{alltt}")
writeContent(block, tag)
of1("\\end{alltt}\n")
inPre <<- FALSE
},
"\\Sexpr"= { of1("\\begin{verbatim}\n")
of0(as.character.Rd(block, deparse=TRUE))
of1("\n\\end{verbatim}\n")
},
"\\verb"= {
of0("\\AsIs{")
writeContent(block, tag)
of1("}")
},
"\\special"= writeContent(block, tag),
"\\linkS4class" =,
"\\link" = writeLink(tag, block),
"\\cr" = of1("\\\\{}"),
"\\dots" =,
"\\ldots" = of1(if(inCode || inCodeBlock) "..." else tag),
"\\R" = of0(tag, "{}"),
"\\donttest" = writeContent(block, tag),
"\\dontrun"= writeDR(block, tag),
"\\enc" = {
if (outputEncoding == "ASCII")
writeContent(block[[2L]], tag)
else
writeContent(block[[1L]], tag)
} ,
"\\eqn" =,
"\\deqn" = {
of0(tag, "{")
inEqn <<- TRUE
writeContent(block[[1L]], tag)
inEqn <<- FALSE
of0('}{}')
},
"\\figure" = {
of0('\\Figure{')
writeContent(block[[1L]], tag)
of0('}{')
if (length(block) > 1L) {
includeoptions <- .Rd_get_latex(block[[2]])
if (length(includeoptions)
&& startsWith(includeoptions, "options: "))
of0(sub("^options: ", "", includeoptions))
}
of0('}')
hasFigures <<- TRUE
},
"\\dontshow" =,
"\\testonly" = {},
"\\method" =,
"\\S3method" =,
"\\S4method" = {
},
"\\tabular" = writeTabular(block),
"\\subsection" = writeSection(block, tag),
"\\if" =,
"\\ifelse" =
if (testRdConditional("latex", block, Rdfile))
writeContent(block[[2L]], tag)
else if (tag == "\\ifelse")
writeContent(block[[3L]], tag),
"\\out" = for (i in seq_along(block))
of1(block[[i]]),
stopRd(block, Rdfile, "Tag ", tag, " not recognized")
)
}
writeTabular <- function(table) {
format <- table[[1L]]
content <- table[[2L]]
if (length(format) != 1L || RdTags(format) != "TEXT")
stopRd(table, Rdfile, "\\tabular format must be simple text")
tags <- RdTags(content)
of0('\n\\Tabular{', format, '}{')
for (i in seq_along(tags)) {
switch(tags[i],
"\\tab" = of1("&"),
"\\cr" = of1("\\\\{}"),
writeBlock(content[[i]], tags[i], "\\tabular"))
}
of1('}')
}
writeContent <- function(blocks, blocktag) {
inList <- FALSE
itemskip <- FALSE
tags <- RdTags(blocks)
i <- 0
while (i < length(tags)) {
i <- i + 1
block <- blocks[[i]]
tag <- attr(block, "Rd_tag")
if(!is.null(tag))
switch(tag,
"\\method" =,
"\\S3method" =,
"\\S4method" = {
blocks <- transformMethod(i, blocks, Rdfile)
tags <- RdTags(blocks)
i <- i - 1
},
"\\item" = {
if (blocktag == "\\value" && !inList) {
of1("\\begin{ldescription}\n")
inList <- TRUE
}
switch(blocktag,
"\\describe" = {
of1('\\item[')
writeContent(block[[1L]], tag)
of1('] ')
writeContent(block[[2L]], tag)
},
"\\value"=,
"\\arguments"={
of1('\\item[\\code{')
inCode <<- TRUE
writeContent(block[[1L]], tag)
inCode <<- FALSE
of1('}] ')
writeContent(block[[2L]], tag)
},
"\\enumerate" =,
"\\itemize"= {
of1("\\item ")
itemskip <- TRUE
})
itemskip <- TRUE
},
"\\cr" = of1("\\\\{}"),
{
if (inList && !(tag == "TEXT" && isBlankRd(block))) {
of1("\\end{ldescription}\n")
inList <- FALSE
}
if (itemskip) {
itemskip <- FALSE
if (tag == "TEXT") {
txt <- psub("^ ", "", as.character(block))
of1(texify(txt))
} else writeBlock(block, tag, blocktag)
} else writeBlock(block, tag, blocktag)
})
}
if (inList) of1("\\end{ldescription}\n")
}
writeSectionInner <- function(section, tag)
{
if (length(section)) {
nxt <- section[[1L]]
if (!attr(nxt, "Rd_tag") %in% c("TEXT", "RCODE") ||
substr(as.character(nxt), 1L, 1L) != "\n") of1("\n")
writeContent(section, tag)
inCodeBlock <<- FALSE
if (last_char != "\n") of1("\n")
}
}
writeSection <- function(section, tag) {
if (tag %in% c("\\encoding", "\\concept"))
return()
save <- sectionLevel
sectionLevel <<- sectionLevel + 1
if (tag == "\\alias")
writeAlias(section, tag)
else if (tag == "\\keyword") {
key <- trim(section)
of0("\\keyword{", latex_escape_name(key), "}{", ltxname, "}\n")
} else if (tag == "\\section" || tag == "\\subsection") {
macro <- c("Section", "SubSection", "SubSubSection")[min(sectionLevel, 3)]
of0("%\n\\begin{", macro, "}{")
writeContent(section[[1L]], tag)
of1("}")
writeSectionInner(section[[2L]], tag)
of0("\\end{", macro, "}\n")
} else {
title <- envTitles[tag]
of0("%\n\\begin{", title, "}")
if(tag %in% c("\\author", "\\description", "\\details", "\\note",
"\\references", "\\seealso", "\\source"))
of1("\\relax")
extra <- sectionExtras[tag]
if(!is.na(extra)) of0("\n\\begin{", extra, "}")
if(tag %in% c("\\usage", "\\examples")) inCodeBlock <<- TRUE
writeSectionInner(section, tag)
inCodeBlock <<- FALSE
if(!is.na(extra)) of0("\\end{", extra, "}\n")
of0("\\end{", title, "}\n")
}
sectionLevel <<- save
}
Rd <- prepare_Rd(Rd, defines=defines, stages=stages, fragment=fragment, ...)
Rdfile <- attr(Rd, "Rdfile")
sections <- RdTags(Rd)
if (is.character(out)) {
if(out == "") {
con <- stdout()
} else {
con <- file(out, "wt")
on.exit(close(con))
}
} else {
con <- out
out <- summary(con)$description
}
if (outputEncoding != "ASCII") {
latexEncoding <- latex_canonical_encoding(outputEncoding)
if(writeEncoding) of0("\\inputencoding{", latexEncoding, "}\n")
} else latexEncoding <- NA
if (fragment) {
if (sections[1L] %in% names(sectionOrder))
for (i in seq_along(sections))
writeSection(Rd[[i]], sections[i])
else
for (i in seq_along(sections))
writeBlock(Rd[[i]], sections[i], "")
} else {
nm <- character(length(Rd))
isAlias <- sections == "\\alias"
sortorder <- if (any(isAlias)) {
nm[isAlias] <- sapply(Rd[isAlias], as.character)
order(sectionOrder[sections], toupper(nm), nm)
} else order(sectionOrder[sections])
Rd <- Rd[sortorder]
sections <- sections[sortorder]
title <- .Rd_get_latex(.Rd_get_section(Rd, "title"))
title <- paste(title[nzchar(title)], collapse = " ")
name <- Rd[[2L]]
name <- trim(as.character(Rd[[2L]][[1L]]))
ltxname <- latex_escape_name(name)
of0('\\HeaderA{', ltxname, '}{',
ltxstriptitle(title), '}{',
latex_link_trans0(name), '}\n')
for (i in seq_along(sections)[-(1:2)])
writeSection(Rd[[i]], sections[i])
}
if (encode_warn)
warnRd(Rd, Rdfile, "Some input could not be re-encoded to ",
outputEncoding)
invisible(structure(out, latexEncoding = latexEncoding,
hasFigures = hasFigures))
} |
chart_labels <- function( x, title = NULL, xlab = NULL, ylab = NULL){
if( !is.null(title) ) x$labels[["title"]] <- htmlEscape(title)
else x$labels[["title"]] <- NULL
if( !is.null(xlab) ) x$labels[["x"]] <- htmlEscape(xlab)
else x$labels[["x"]] <- NULL
if( !is.null(ylab) ) x$labels[["y"]] <- htmlEscape(ylab)
else x$labels[["y"]] <- NULL
x
} |
setMethod("bigglm",
c("ANY","DBIConnection"),
function(formula, data, family = gaussian(),
tablename, ..., chunksize=5000){
terms<-terms(formula)
modelvars<-all.vars(formula)
dots<-as.list(substitute(list(...)))[-1]
dotvars<-unlist(lapply(dots,all.vars))
vars<-unique(c(modelvars,dotvars))
query<-paste("select ",paste(vars,collapse=", ")," from ",tablename)
result<-dbSendQuery(data, query)
got<-0
on.exit(dbClearResult(result))
chunk<-function(reset=FALSE){
if(reset){
if(got>0){
dbClearResult(result)
result<<-dbSendQuery(data,query)
got<<-0
}
return(TRUE)
}
rval<-fetch(result,n=chunksize)
got<<-got+nrow(rval)
if (nrow(rval)==0)
return(NULL)
return(rval)
}
rval<-bigglm(formula, data=chunk, family=family, ...)
rval$call<-sys.call()
rval$call[[1]]<-as.name("bigglm")
rval
}
)
|
GetLabels <- function(data) {
col.names <- names(data)
if (sum(c("timestamp", "value", "is.anomaly", "is.real.anomaly") %in% col.names) != 4) {
stop("data argument must be a data.frame with timestamp}, value, is.anomaly and is.real.anomaly
columns.")
}
calculate.tp <- function(index) {
start <- data[index, "start.limit"]
end <- data[index, "end.limit"]
anomaly.index <- which(data$is.anomaly == 1)
anomaly.pos <- which(anomaly.index >= start & anomaly.index <= end)
if (length(anomaly.pos) == 0) {
return(-1)
} else {
return(anomaly.index[anomaly.pos])
}
}
real.anomaly.index <- which(data$is.real.anomaly == 1 & data$start.limit != 0)
tp.index <- lapply(real.anomaly.index, calculate.tp)
data$first.tp <- 0
data[real.anomaly.index, "first.tp"] <- sapply(tp.index, function(elem) return(elem[1]))
data$label <- "tn"
tp.index <- unlist(tp.index)
tp.index <- tp.index[tp.index != -1]
data[tp.index, "label"] <- "tp"
tp.index <- which(data$first.tp != -1 & data$first.tp != 0)
data[tp.index, "label"] <- "tp"
tp.index <- which(data$first.tp == -1)
data[tp.index, "label"] <- "fn"
fp.index <- which(data$is.anomaly == 1 & data$label != "tp")
data[fp.index, "label"] <- "fp"
return(data)
} |
summary2 <- function(x, na.rm=FALSE)
{
if(length(x) <= 5)
return(x)
else
return(summary(x, na.rm=na.rm))
}
summary3 <- function(x, na.rm=FALSE)
{
c(quantile(x), mean=mean(x))
} |
rlassoIV <- function(x, ...)
UseMethod("rlassoIV")
rlassoIV.default <- function(x, d, y, z, select.Z = TRUE, select.X = TRUE, post = TRUE,
...) {
d <- as.matrix(d)
z <- as.matrix(z)
if (is.null(colnames(d)))
colnames(d) <- paste("d", 1:ncol(d), sep = "")
if (is.null(colnames(x)) & !is.null(x))
colnames(x) <- paste("x", 1:ncol(x), sep = "")
if (is.null(colnames(z)) & !is.null(z))
colnames(z) <- paste("z", 1:ncol(z), sep = "")
n <- length(y)
if (select.Z == FALSE && select.X == FALSE) {
res <- tsls(x, d, y, z, homoscedastic = FALSE, ...)
return(res)
}
if (select.Z == TRUE && select.X == FALSE) {
res <- rlassoIVselectZ(x, d, y, z, post = post, ...)
return(res)
}
if (select.Z == FALSE && select.X == TRUE) {
res <- rlassoIVselectX(x, d, y, z, post = post, ...)
return(res)
}
if (select.Z == TRUE && select.X == TRUE) {
Z <- cbind(z, x)
lasso.d.zx <- rlasso(Z, d, post = post, ...)
lasso.y.x <- rlasso(x, y, post = post, ...)
lasso.d.x <- rlasso(x, d, post = post, ...)
if (sum(lasso.d.zx$index) == 0) {
message("No variables in the Lasso regression of d on z and x selected")
return(list(alpha = NA, se = NA))
}
ind.dzx <- lasso.d.zx$index
PZ <- as.matrix(predict(lasso.d.zx))
lasso.PZ.x <- rlasso(x, PZ, post = post, ...)
ind.PZx <- lasso.PZ.x$index
if (sum(ind.PZx) == 0) {
Dr <- d - mean(d)
} else {
Dr <- d - predict(lasso.PZ.x)
}
if (sum(lasso.y.x$index) == 0) {
Yr <- y - mean(y)
} else {
Yr <- lasso.y.x$residuals
}
if (sum(lasso.PZ.x$index) == 0) {
Zr <- PZ - mean(x)
} else {
Zr <- lasso.PZ.x$residuals
}
result <- tsls(y = Yr, d = Dr, x = NULL, z = Zr, intercept = FALSE, homoscedastic = FALSE)
coef <- as.vector(result$coefficient)
se <- diag(sqrt(result$vcov))
names(coef) <- names(se) <- colnames(d)
res <- list(coefficients = coef, se = se, vcov = vcov, call = match.call(),
samplesize = n)
class(res) <- "rlassoIV"
return(res)
}
}
rlassoIV.formula <- function(formula, data, select.Z = TRUE, select.X = TRUE, post = TRUE,
...) {
mat <- f.formula(formula, data, all.categories = FALSE)
y <- mat$Y
x <- mat$X
d <- mat$D
z <- mat$Z
res <- rlassoIV(x=x, d=d, y=y, z=z, select.Z = select.Z, select.X = select.X, post = post,
...)
res$call <- match.call()
return(res)
}
print.rlassoIV <- function(x, digits = max(3L, getOption("digits") - 3L),
...) {
cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"),
"\n\n", sep = "")
if (length(coef(x))) {
cat("Coefficients:\n")
print.default(format(coef(x), digits = digits), print.gap = 2L,
quote = FALSE)
} else cat("No coefficients\n")
cat("\n")
invisible(coef(x))
}
summary.rlassoIV <- function(object, digits = max(3L, getOption("digits") -
3L), ...) {
if (length(coef(object))) {
k <- length(object$coefficient)
table <- matrix(NA, ncol = 4, nrow = k)
rownames(table) <- names(object$coefficients)
colnames(table) <- c("coeff.", "se.", "t-value", "p-value")
table[, 1] <- object$coefficients
table[, 2] <- object$se
table[, 3] <- table[, 1]/table[, 2]
table[, 4] <- 2 * pnorm(-abs(table[, 3]))
cat("Estimates and Significance Testing of the effect of target variables in the IV regression model",
"\n")
printCoefmat(table, digits = digits, P.values = TRUE, has.Pvalue = TRUE)
cat("\n")
} else {
cat("No coefficients\n")
}
cat("\n")
invisible(table)
}
confint.rlassoIV <- function(object, parm, level = 0.95, ...) {
n <- object$samplesize
k <- length(object$coefficients)
cf <- coef(object)
pnames <- names(cf)
if (missing(parm))
parm <- pnames else if (is.numeric(parm))
parm <- pnames[parm]
a <- (1 - level)/2
a <- c(a, 1 - a)
fac <- qnorm(a)
pct <- format.perc(a, 3)
ci <- array(NA, dim = c(length(parm), 2L), dimnames = list(parm, pct))
ses <- object$se[parm]
ci[] <- cf[parm] + ses %o% fac
print(ci)
invisible(ci)
}
rlassoIVmult <- function(x, d, y, z, select.Z = TRUE, select.X = TRUE,
...) {
d <- as.matrix(d)
if (is.null(colnames(d)))
colnames(d) <- paste("d", 1:ncol(d), sep = "")
if (is.null(colnames(x)) & !is.null(x))
colnames(x) <- paste("x", 1:ncol(x), sep = "")
if (is.null(colnames(z)) & !is.null(z))
colnames(z) <- paste("z", 1:ncol(z), sep = "")
if (select.Z == FALSE & select.X == FALSE) {
res <- tsls(x=x, d=d, y=y, z=z, homoscedastic = FALSE, ...)
return(res)
}
if (select.Z == TRUE & select.X == FALSE) {
res <- rlassoIVselectZ(x, d, y, z, ...)
return(res)
}
if (select.Z == FALSE & select.X == TRUE) {
res <- rlassoIVselectX(x, d, y, z, ...)
return(res)
}
if (select.Z == TRUE & select.X == TRUE) {
d <- as.matrix(d)
n <- dim(x)[1]
d <- as.matrix(d)
kd <- dim(d)[2]
Z <- cbind(z, x)
if (is.null(colnames(d)))
colnames(d) <- paste("d", 1:kd, sep = "")
lasso.y.x <- rlasso(x, y, ...)
Yr <- lasso.y.x$residuals
Drhat <- NULL
Zrhat <- NULL
for (i in 1:kd) {
lasso.d.x <- rlasso(d[, i] ~ x, ...)
lasso.d.zx <- rlasso(d[, i] ~ Z, ...)
if (sum(lasso.d.zx$index) == 0) {
Drhat <- cbind(Drhat, d[, i] - mean(d[, i]))
Zrhat <- cbind(Zrhat, d[, i] - mean(d[, i]))
next
}
ind.dzx <- lasso.d.zx$index
PZ <- Z[, ind.dzx, drop = FALSE] %*% MASS::ginv(t(Z[, ind.dzx,
drop = FALSE]) %*% Z[, ind.dzx, drop = FALSE]) %*% t(Z[,
ind.dzx, drop = FALSE]) %*% d[, i, drop = FALSE]
lasso.PZ.x <- rlasso(PZ ~ x, ...)
ind.PZx <- lasso.PZ.x$index
Dr <- d[, i] - x[, ind.PZx, drop = FALSE] %*% MASS::ginv(t(x[,
ind.PZx, drop = FALSE]) %*% x[, ind.PZx, drop = FALSE]) %*%
t(x[, ind.PZx, drop = FALSE]) %*% PZ
Zr <- lasso.PZ.x$residuals
Drhat <- cbind(Drhat, Dr)
Zrhat <- cbind(Zrhat, Zr)
}
result <- tsls(y = Yr, d = Drhat, x = NULL, z = Zrhat, homoscedastic = FALSE)
coef <- as.vector(result$coefficient)
se <- sqrt(diag(result$vcov))
names(coef) <- names(se) <- colnames(d)
res <- list(coefficients = coef, se = se, vcov = result$vcov, call = match.call(),
samplesize = n)
class(res) <- "rlassoIV"
return(res)
}
} |
context("SVM and Linear SVM")
library(kernlab)
set.seed(91)
testdata <- generateSlicedCookie(50,expected=TRUE)
extra_testdata <- generateSlicedCookie(100,expected=TRUE)
g1 <- SVM(formula(Class~.), testdata, C=1000,eps=1e-10)
g2 <- LinearSVM(formula(Class~.), testdata, C=10000, method="Dual",eps=1e-10)
g3 <- LinearSVM(formula(Class~.), testdata, C=10000, method="Primal",eps=1e-10)
test_that("Batch Gradient Descent gives a warning", {
expect_warning(g4 <- LinearSVM(formula(Class~.), testdata, C=500, method="BGD",reltol=1e-100, maxit=1000,eps=1e-10))
})
test_that("Same result as kernlab implementation", {
g_nonscaled <- SVM(formula(Class~.), testdata, C=1000,eps=1e-10,scale=FALSE)
g_kernlab <- ksvm(formula(Class~.),data=testdata, C=1000,kernel=vanilladot(),scaled=FALSE)
expect_equal(g_nonscaled@alpha[g_kernlab@alphaindex[[1]]],-g_kernlab@coef[[1]],tolerance=1e-2)
})
test_that("Same result as svmd implementation", {
g_nonscaled <- SVM(formula(Class~.), testdata, C=1,eps=1e-5,scale=FALSE,x_center=FALSE)
g_kernlab <- svmd(formula(Class~.), kernel="linear", testdata,cost=1, scale = FALSE)
expect_equal(g_nonscaled@alpha[g_kernlab$index],
as.numeric(-g_kernlab$coefs),tolerance=10e-4)
})
test_that("Same result for SVM and Linear SVM.", {
expect_equal(decisionvalues(g2,testdata),decisionvalues(g1,testdata),tolerance=1e-5)
})
test_that("Weights equal for Primal and Dual solution", {
expect_equal(g2@w, as.numeric(g3@w),tolerance=10e-2,scale=1)
})
test_that("Predictions the same for SVM and LinearSVM",{
expect_equal(predict(g2,extra_testdata), predict(g1,extra_testdata))
expect_equal(predict(g3,extra_testdata), predict(g1,extra_testdata))
})
test_that("Loss functions return the same value for SVM and LinearSVM",{
expect_equal(loss(g2,extra_testdata), loss(g1,extra_testdata),tolerance=1e-4,scale=1)
l1 <- loss(g1,testdata)
expect_equal(l1,loss(g2,testdata),tolerance=1e-3,scale=1)
})
test_that("Gradient is superficially correct",{
library("numDeriv")
data(testdata)
X <- cbind(1,testdata$X)
y <- as.numeric(testdata$y)*2-3
w <- rnorm(ncol(X))
C <- 500
expect_equal(as.numeric(numDeriv::grad(RSSL:::svm_opt_func,w,X=X,y=y,C=C, method="simple")),as.numeric(RSSL:::svm_opt_grad(w,X=X,y=y,C=C)),tolerance=1e-2)
}) |
library(testthat)
library(parsnip)
library(rlang)
context("nearest neighbor")
source("helpers.R")
test_that('primary arguments', {
basic <- nearest_neighbor(mode = "regression")
basic_kknn <- translate(basic %>% set_engine("kknn"))
expect_equal(
object = basic_kknn$method$fit$args,
expected = list(
formula = expr(missing_arg()),
data = expr(missing_arg()),
ks = expr(min_rows(5, data, 5))
)
)
neighbors <- nearest_neighbor(mode = "classification", neighbors = 2)
neighbors_kknn <- translate(neighbors %>% set_engine("kknn"))
expect_equal(
object = neighbors_kknn$method$fit$args,
expected = list(
formula = expr(missing_arg()),
data = expr(missing_arg()),
ks = expr(min_rows(2, data, 5))
)
)
weight_func <- nearest_neighbor(mode = "classification", weight_func = "triangular")
weight_func_kknn <- translate(weight_func %>% set_engine("kknn"))
expect_equal(
object = weight_func_kknn$method$fit$args,
expected = list(
formula = expr(missing_arg()),
data = expr(missing_arg()),
kernel = new_empty_quosure("triangular"),
ks = expr(min_rows(5, data, 5))
)
)
dist_power <- nearest_neighbor(mode = "classification", dist_power = 2)
dist_power_kknn <- translate(dist_power %>% set_engine("kknn"))
expect_equal(
object = dist_power_kknn$method$fit$args,
expected = list(
formula = expr(missing_arg()),
data = expr(missing_arg()),
distance = new_empty_quosure(2),
ks = expr(min_rows(5, data, 5))
)
)
})
test_that('engine arguments', {
kknn_scale <- nearest_neighbor(mode = "classification") %>% set_engine("kknn", scale = FALSE)
expect_equal(
object = translate(kknn_scale, "kknn")$method$fit$args,
expected = list(
formula = expr(missing_arg()),
data = expr(missing_arg()),
scale = new_empty_quosure(FALSE),
ks = expr(min_rows(5, data, 5))
)
)
})
test_that('updating', {
expr1 <- nearest_neighbor() %>% set_engine("kknn", scale = FALSE)
expr1_exp <- nearest_neighbor(neighbors = 5) %>% set_engine("kknn", scale = FALSE)
expr2 <- nearest_neighbor(neighbors = tune()) %>% set_engine("kknn", scale = tune())
expr2_exp <- nearest_neighbor(neighbors = tune(), weight_func = "triangular") %>% set_engine("kknn", scale = FALSE)
expr3 <- nearest_neighbor(neighbors = 2, weight_func = tuns()) %>% set_engine("kknn", scale = tune())
expr3_exp <- nearest_neighbor(neighbors = 3) %>% set_engine("kknn", scale = FALSE)
expect_equal(update(expr1, neighbors = 5, scale = FALSE), expr1_exp)
expect_equal(update(expr2, weight_func = "triangular", scale = FALSE), expr2_exp)
expect_equal(update(expr3, neighbors = 3, fresh = TRUE, scale = FALSE), expr3_exp)
param_tibb <- tibble::tibble(neighbors = 7, dist_power = 1)
param_list <- as.list(param_tibb)
expr1_updated <- update(expr1, param_tibb)
expect_equal(expr1_updated$args$neighbors, 7)
expect_equal(expr1_updated$args$dist_power, 1)
expect_equal(expr1_updated$eng_args$scale, rlang::quo(FALSE))
expr1_updated_lst <- update(expr1, param_list)
expect_equal(expr1_updated_lst$args$neighbors, 7)
expect_equal(expr1_updated_lst$args$dist_power, 1)
expect_equal(expr1_updated_lst$eng_args$scale, rlang::quo(FALSE))
expr1_updated_mod <- update(expr1, param_list, neighbors = 3)
expect_equal(expr1_updated_mod$args$neighbors, 7)
expect_equal(expr1_updated_mod$args$dist_power, 1)
expect_equal(expr1_updated_mod$eng_args$scale, rlang::quo(FALSE))
param_tibb$scale <- TRUE
expect_error(
update(expr1, param_tibb),
"At least one argument is not a main argument"
)
})
test_that('bad input', {
expect_error(nearest_neighbor(mode = "reallyunknown"))
expect_error(nearest_neighbor() %>% set_engine( NULL))
}) |
require(testthat)
context("Testing remove_runs().")
index <- c(1,2,4,5,6,10,12,13,14,15,18,19,20)
y <- seq_along(index)
result <- y
result[c(1,3,4,7,8,9,11,12)] <- NA
test_that(paste0("test remove_runs() with max last, ordered"), {
expect_identical(remove_runs(y, index),
result)
})
result <- y
result[c(2,4,5,8,9,10,12,13)] <- NA
test_that(paste0("test remove_runs() with min first, ordered"), {
expect_identical(remove_runs(y, index, FALSE),
result)
})
index <- c(1,2,4,5,6,10,12,13,14,15,18,19,20)
y <- -seq_along(index)
result <- y
result[c(2,4,5,8,9,10,12,13)] <- NA
test_that(paste0("test remove_runs() with max first, ordered"), {
expect_identical(remove_runs(y, index),
result)
})
index <- -rev(c(1,2,4,5,6,10,12,13,14,15,18,19,20))
y <- seq_along(index)
result <- y
result[c(1,2,4,5,6,9,10,12)] <- NA
test_that(paste0("test remove_runs(), negative indices, ordered"), {
expect_identical(remove_runs(y, index),
result)
})
index <- c(1,4,5,6,2,12,13,14,15,18,20,19,10)
y <- seq_along(index)
result <- y
result[c(1,2,3,6:8,10:11)] <- NA
test_that(paste0("test remove_runs(), unordered"), {
expect_identical(remove_runs(y, index),
result)
})
index <- 20
y <- seq_along(index)
result <- y
test_that(paste0("test remove_runs(), single value"), {
expect_identical(remove_runs(y, index),
y)
})
index <- c(14,20)
y <- seq_along(index)
result <- y
test_that(paste0("test remove_runs(), no removals"), {
expect_identical(remove_runs(y, index),
y)
})
context("Testing screen_within_block().")
index <- c(1,10,11,15,19,21,45,51,53)
y <- seq_along(index)
result <- y
result[c(1,3,4,8)] <- NA
test_that(paste0("test screen_within_block() with max last, ordered"), {
expect_identical(screen_within_block(y, index),
result)
})
index <- c(1,10,11,15,19,21,45,51,53)
y <- -seq_along(index)
result <- y
result[c(2,4,5,9)] <- NA
test_that(paste0("test screen_within_block() with max first, ordered"), {
expect_identical(screen_within_block(y, index),
result)
})
index <- c(1,10,11,15,19,21,45,51,53)
y <- c(0, 1, 5, 3, 7, 9, 11, 0, 7)
result <- y
result[c(1,3,4,8)] <- NA
test_that(paste0("test screen_within_block() with max last, unordered"), {
expect_identical(screen_within_block(y, index),
result)
})
index <- 20
y <- seq_along(index)
test_that(paste0("test screen_within_block(), single value"), {
expect_equal(screen_within_block(y, index),
y)
})
index <- c(5,20)
y <- seq_along(index)
test_that(paste0("test screen_within_block(), no removals"), {
expect_equal(screen_within_block(y, index),
y)
}) |
library(shiny)
source("helper/bbox-plot.R")
observe({
updateSelectInput(session, 'bbox_select_x', choices = names(filt_data$p))
updateSelectInput(session, 'bbox_select_y', choices = names(filt_data$p))
})
observeEvent(input$finalok, {
num_data <- final_split$train[, sapply(final_split$train, is.numeric)]
f_data <- final_split$train[, sapply(final_split$train, is.factor)]
if (is.null(dim(f_data))) {
k <- final_split$train %>% map(is.factor) %>% unlist()
j <- names(which(k == TRUE))
fdata <- tibble::as_data_frame(f_data)
colnames(fdata) <- j
updateSelectInput(session, inputId = "bbox_select_x",
choices = names(fdata))
} else {
updateSelectInput(session, 'bbox_select_x', choices = names(f_data))
}
if (is.null(dim(num_data))) {
k <- final_split$train %>% map(is.numeric) %>% unlist()
j <- names(which(k == TRUE))
numdata <- tibble::as_data_frame(num_data)
colnames(numdata) <- j
updateSelectInput(session, 'bbox_select_y',
choices = names(numdata), selected = names(numdata))
} else if (ncol(num_data) < 1) {
updateSelectInput(session, 'bbox_select_y',
choices = '', selected = '')
} else {
updateSelectInput(session, 'bbox_select_y', choices = names(num_data))
}
})
observeEvent(input$submit_part_train_per, {
num_data <- final_split$train[, sapply(final_split$train, is.numeric)]
f_data <- final_split$train[, sapply(final_split$train, is.factor)]
if (is.null(dim(f_data))) {
k <- final_split$train %>% map(is.factor) %>% unlist()
j <- names(which(k == TRUE))
fdata <- tibble::as_data_frame(f_data)
colnames(fdata) <- j
updateSelectInput(session, inputId = "bbox_select_x",
choices = names(fdata))
} else {
updateSelectInput(session, 'bbox_select_x', choices = names(f_data))
}
if (is.null(dim(num_data))) {
k <- final_split$train %>% map(is.numeric) %>% unlist()
j <- names(which(k == TRUE))
numdata <- tibble::as_data_frame(num_data)
colnames(numdata) <- j
updateSelectInput(session, 'bbox_select_y',
choices = names(numdata), selected = names(numdata))
} else if (ncol(num_data) < 1) {
updateSelectInput(session, 'bbox_select_y',
choices = '', selected = '')
} else {
updateSelectInput(session, 'bbox_select_y', choices = names(num_data))
}
})
f_split <- reactiveValues(num_data = NULL)
num_data1 <- eventReactive(input$button_split_no, {
numdata <- final_split$train[, sapply(final_split$train, is.factor)]
if (is.factor(numdata)) {
out <- 1
} else {
out <- ncol(numdata)
}
out
})
num_data2 <- eventReactive(input$submit_part_train_per, {
numdata <- final_split$train[, sapply(final_split$train, is.factor)]
if (is.factor(numdata)) {
out <- 1
} else {
out <- ncol(numdata)
}
out
})
observeEvent(input$button_split_no, {
f_split$num_data <- num_data1()
})
observeEvent(input$submit_part_train_per, {
f_split$num_data <- num_data2()
})
bbox_x <- eventReactive(input$box2_create, {
if (f_split$num_data > 0) {
box_data <- final_split$train[, input$bbox_select_x]
} else {
box_data <- NULL
}
box_data
})
bbox_y <- eventReactive(input$box2_create, {
box_data <- final_split$train[, input$bbox_select_y]
})
n_labels <- eventReactive(input$box2_create, {
if (!is.null(bbox_x())) {
k <- nlevels(bbox_x())
}
k
})
observeEvent(input$box2_create, {
if (!is.null(bbox_x())) {
updateNumericInput(session, 'nbox2label', value = n_labels())
}
})
output$ui_ncolbox2 <- renderUI({
ncol <- as.integer(input$ncolbox2)
lapply(1:ncol, function(i) {
textInput(paste("n_box2col_", i), label = paste0("Box Color ", i),
value = 'blue')
})
})
colours_box2 <- reactive({
ncol <- as.integer(input$ncolbox2)
collect <- list(lapply(1:ncol, function(i) {
input[[paste("n_box2col_", i)]]
}))
colors <- unlist(collect)
})
output$ui_nborbox2 <- renderUI({
ncol <- as.integer(input$nborbox2)
lapply(1:ncol, function(i) {
textInput(paste("n_box2bor_", i), label = paste0("Border Color ", i),
value = 'black')
})
})
borders_box2 <- reactive({
ncol <- as.integer(input$nborbox2)
collect <- list(lapply(1:ncol, function(i) {
input[[paste("n_box2bor_", i)]]
}))
colors <- unlist(collect)
})
output$ui_nbox2label <- renderUI({
ncol <- as.integer(input$nbox2label)
if (ncol < 1) {
NULL
} else {
lapply(1:ncol, function(i) {
textInput(paste("n_box2label_", i),
label = paste0("Label ", i))
})
}
})
labels_box2 <- reactive({
ncol <- as.integer(input$nbox2label)
if (ncol < 1) {
colors <- NULL
} else {
collect <- list(lapply(1:ncol, function(i) {
input[[paste("n_box2label_", i)]]
}))
colors <- unlist(collect)
}
colors
})
output$ui_box2_legnames <- renderUI({
ncol <- as.integer(input$box2_legnames)
if (ncol < 1) {
NULL
} else {
lapply(1:ncol, function(i) {
textInput(paste("n_legnamesbox2_", i),
label = paste0("Legend Name ", i))
})
}
})
output$ui_box2_legpoint <- renderUI({
ncol <- as.integer(input$box2_leg_point)
if (ncol < 1) {
NULL
} else {
lapply(1:ncol, function(i) {
numericInput(paste("n_pointbox2_", i),
label = paste0("Legend Point ", i), value = 15)
})
}
})
name_box2 <- reactive({
ncol <- as.integer(input$box2_legnames)
if (ncol < 1) {
colors <- NULL
} else {
collect <- list(lapply(1:ncol, function(i) {
input[[paste("n_legnamesbox2_", i)]]
}))
colors <- unlist(collect)
}
colors
})
point_box2 <- reactive({
ncol <- as.integer(input$box2_leg_point)
if (ncol < 1) {
colors <- NULL
} else {
collect <- list(lapply(1:ncol, function(i) {
input[[paste("n_pointbox2_", i)]]
}))
colors <- unlist(collect)
}
colors
})
output$bbox_plot_1 <- renderPlot({
if (!is.null(bbox_x())) {
box_plotb(bbox_x(), bbox_y(), title = input$bbox_title, subs = input$bbox_subtitle,
xlabel = input$bbox_xlabel, ylabel = input$bbox_ylabel)
}
})
output$bbox_plot_2 <- renderPlot({
box_plotb(bbox_x(), bbox_y(), title = input$bbox_title, subs = input$bbox_subtitle,
xlabel = input$bbox_xlabel, ylabel = input$bbox_ylabel, horiz = as.logical(input$bbox_horiz),
notches = as.logical(input$bbox_notch), ranges = input$bbox_range, outlines = as.logical(input$bbox_outline),
varwidths = as.logical(input$bbox_varwidth))
})
output$bbox_plot_3 <- renderPlot({
box_plotb(bbox_x(), bbox_y(), title = input$bbox_title, subs = input$bbox_subtitle,
xlabel = input$bbox_xlabel, ylabel = input$bbox_ylabel, horiz = as.logical(input$bbox_horiz),
notches = as.logical(input$bbox_notch), ranges = input$bbox_range, outlines = as.logical(input$bbox_outline),
varwidths = as.logical(input$bbox_varwidth), color = colours_box2(), borders = borders_box2(),
labels = labels_box2())
})
output$bbox_plot_5 <- renderPlot({
box_plotb(
bbox_x(), bbox_y(), title = input$bbox_title, subs = input$bbox_subtitle,
xlabel = input$bbox_xlabel, ylabel = input$bbox_ylabel, horiz = as.logical(input$bbox_horiz),
notches = as.logical(input$bbox_notch), ranges = input$bbox_range, outlines = as.logical(input$bbox_outline),
varwidths = as.logical(input$bbox_varwidth), color = colours_box2(), borders = borders_box2(),
text_p = input$bbox_plottext, text_x_loc = input$bbox_text_x_loc,
text_y_loc = input$bbox_text_y_loc, text_col = input$bbox_textcolor, text_font = input$bbox_textfont,
text_size = input$bbox_textsize, m_text = input$bbox_mtextplot, m_side = input$bbox_mtext_side,
m_line = input$bbox_mtext_line, m_adj = input$bbox_mtextadj, m_col = input$bbox_mtextcolor,
m_font = input$bbox_mtextfont, m_cex = input$bbox_mtextsize
)
})
output$bbox_plot_6 <- renderPlot({
box_plotb(
bbox_x(), bbox_y(), title = input$bbox_title, subs = input$bbox_subtitle,
xlabel = input$bbox_xlabel, ylabel = input$bbox_ylabel, horiz = as.logical(input$bbox_horiz),
notches = as.logical(input$bbox_notch), ranges = input$bbox_range, outlines = as.logical(input$bbox_outline),
varwidths = as.logical(input$bbox_varwidth), color = colours_box2(), borders = borders_box2(),
labels = labels_box2(), input$bbox_coltitle, input$bbox_colsub, input$bbox_colaxis,
input$bbox_collabel, fontmain = input$bbox_fontmain, fontsub = input$bbox_fontsub,
fontaxis = input$bbox_fontaxis, fontlab = input$bbox_fontlab, input$bbox_cexmain,
input$bbox_cexsub, input$bbox_cexaxis, input$bbox_cexlab,
text_p = input$bbox_plottext, text_x_loc = input$bbox_text_x_loc,
text_y_loc = input$bbox_text_y_loc, text_col = input$bbox_textcolor, text_font = input$bbox_textfont,
text_size = input$bbox_textsize, m_text = input$bbox_mtextplot, m_side = input$bbox_mtext_side,
m_line = input$bbox_mtext_line, m_adj = input$bbox_mtextadj, m_col = input$bbox_mtextcolor,
m_font = input$bbox_mtextfont, m_cex = input$bbox_mtextsize
)
})
output$bbox_plot_final <- renderPlot({
box_plotb(
bbox_x(), bbox_y(), title = input$bbox_title, subs = input$bbox_subtitle,
xlabel = input$bbox_xlabel, ylabel = input$bbox_ylabel, horiz = as.logical(input$bbox_horiz),
notches = as.logical(input$bbox_notch), ranges = input$bbox_range, outlines = as.logical(input$bbox_outline),
varwidths = as.logical(input$bbox_varwidth), color = colours_box2(), borders = borders_box2(),
labels = labels_box2(), input$bbox_coltitle, input$bbox_colsub, input$bbox_colaxis,
input$bbox_collabel, fontmain = input$bbox_fontmain, fontsub = input$bbox_fontsub,
fontaxis = input$bbox_fontaxis, fontlab = input$bbox_fontlab, input$bbox_cexmain,
input$bbox_cexsub, input$bbox_cexaxis, input$bbox_cexlab,
text_p = input$bbox_plottext, text_x_loc = input$bbox_text_x_loc,
text_y_loc = input$bbox_text_y_loc, text_col = input$bbox_textcolor, text_font = input$bbox_textfont,
text_size = input$bbox_textsize, m_text = input$bbox_mtextplot, m_side = input$bbox_mtext_side,
m_line = input$bbox_mtext_line, m_adj = input$bbox_mtextadj, m_col = input$bbox_mtextcolor,
m_font = input$bbox_mtextfont, m_cex = input$bbox_mtextsize
)
})
|
phenoEstimate <- function(counts, params = newPhenoParams()) {
UseMethod("phenoEstimate")
}
phenoEstimate.SingleCellExperiment <- function(counts,
params = newPhenoParams()) {
counts <- getCounts(counts)
phenoEstimate(counts, params)
}
phenoEstimate.matrix <- function(counts, params = newPhenoParams()) {
checkmate::assertClass(params, "PhenoParams")
nGenes <- nrow(counts)
quarter <- floor(nGenes / 4)
params <- setParams(params, nCells = ncol(counts),
n.de = nGenes - 3 * quarter,
n.pst = quarter, n.pst.beta = quarter,
n.de.pst.beta = quarter)
return(params)
} |
context("fpca_gauss")
test_that("bfpca output is a list with non-null items and class fpca",{
Y = simulate_functional_data()$Y
Y$value = Y$latent_mean
fpca_object = fpca_gauss(Y, npc = 2, print.iter = TRUE)
expect_equal(class(fpca_object), "fpca")
expect_equal(fpca_object$family, "gaussian")
expect_false(any(is.na(fpca_object$mu)))
expect_false(any(is.na(fpca_object$efunctions)))
expect_false(any(is.na(fpca_object$evalues)))
expect_false(any(is.na(fpca_object$scores)))
}) |
create_beast2_run_cmd_from_options <- function(beast2_options) {
cmds <- beastier::create_beast2_continue_cmd_from_options(beast2_options)
cmds[cmds != "-resume"]
} |
MandelPvalue <-
function(hfobj)
{
a <- nlevels(hfobj$tall$rows)
b <- nlevels(hfobj$tall$cols)
ymtx <- matrix(hfobj$tall$y,nrow=a,ncol=b,byrow=T)
coldevs <- apply(ymtx,2,mean)-mean(ymtx)
rowdevs <- apply(ymtx,1,mean)-mean(ymtx)
SSRow <- b*sum(rowdevs^2)
SSCol <- a*sum(coldevs^2)
SSTot <- (a*b-1)*var(hfobj$tall$y)
slopes <- ymtx %*% coldevs/sum(coldevs^2)
SSMandel <- sum((slopes-1)^2) * sum(coldevs^2)
SSE <- SSTot-SSMandel-SSRow-SSCol
dfE <- ((a-1)*(b-2))
MSE <- SSE/dfE
Fratio <- (SSMandel/(a-1))/MSE
pvalue <- 1-pf(Fratio,(a-1),dfE)
SumSq <- c(SSRow=SSRow,SSCol=SSCol,SSMandel=SSMandel,SSE=SSE,SSTot=SSTot)
list(pvalue=pvalue,SumSq=SumSq,Fratio=Fratio,df=c(a-1,dfE))
} |
endpoint <- "https://api.beta.ons.gov.uk/v1"
EMPTY <- ""
set_endpoint <- function(query) {
paste(endpoint, query, sep = "/")
}
build_request <- function(id, edition = NULL, version = NULL) {
edition <- edition %||% ons_latest_edition(id)
version <- version %||% ons_latest_version(id)
build_base_request(datasets = id, editions = edition, versions = version)
}
build_base_request <- function(...) {
query <- build_request_dots(...)
set_endpoint(query)
}
build_request_dots <- function(...) {
params <- list(...)
plen <- length(params)
param_chunks <- vector("character", plen)
for (i in 1:plen) {
pm <- params[[i]][1]
if(is.null(pm)) {
param_chunks[i] <- ""
}else if(pm == EMPTY){
param_chunks[i] <- names(params)[i]
}else{
param_chunks[i] <- paste(names(params)[i], pm, sep = "/")
}
}
is_empty <- param_chunks == EMPTY
paste(param_chunks[!is_empty], collapse = "/")
}
extend_request_dots <- function(pre, ...) {
append <- build_request_dots(...)
paste(pre, append, sep = "/")
}
try_VERB <- function(x, limit, offset, VERB = "GET", ...) {
tryCatch(
RETRY(VERB, url = x, timeout(10), quiet = TRUE,
query = list(limit = limit, offset = offset), ...),
error = function(err) conditionMessage(err),
warning = function(warn) conditionMessage(warn)
)
}
is_response <- function(x) {
class(x) == "response"
}
make_request <- function(query, limit = NULL, offset = NULL, ...) {
if (!curl::has_internet()) {
message("No internet connection.")
return(invisible(NULL))
}
resp <- try_VERB(query, limit = limit, offset = offset, ...)
if (!is_response(resp)) {
message(resp)
return(invisible(NULL))
}
if (httr::http_error(resp)) {
httr::message_for_status(resp)
return(invisible(NULL))
}
resp
}
process_response <- function(res) {
ct <- content(res, as = "text", encoding = "UTF-8")
fromJSON(ct, simplifyVector = TRUE)
} |
tcut <- function (x, breaks, labels, scale=1){
x <- as.numeric(x)
breaks <- as.numeric(breaks)
if(length(breaks) == 1) {
if(breaks < 1)
stop("Must specify at least one interval")
if(missing(labels))
labels <- paste("Range", seq(length = breaks))
else if(length(labels) != breaks)
stop("Number of labels must equal number of intervals")
r <- range(x[!is.na(x)])
r[is.na(r)] <- 1
if((d <- diff(r)) == 0) {
r[2] <- r[1] + 1
d <- 1
}
breaks <- seq(r[1] - 0.01 * d, r[2] + 0.01 * d, length = breaks +1)
}
else {
if(is.na(adb <- all(diff(breaks) >= 0)) || !adb)
stop("breaks must be given in ascending order and contain no NA's")
if(missing(labels))
labels <- paste(format(breaks[ - length(breaks)]),
"+ thru ", format(breaks[-1]), sep = "")
else if(length(labels) != length(breaks) - 1)
stop("Number of labels must be 1 less than number of break points")
}
temp <- structure(x*scale, cutpoints=breaks*scale, labels=labels)
class(temp) <- 'tcut'
temp
}
"[.tcut" <- function(x, ..., drop=FALSE) {
atts <- attributes(x)
x <- unclass(x)[..1]
attributes(x) <- atts
class(x) <- 'tcut'
x
}
levels.tcut <- function(x) attr(x, 'labels') |
gaussian.trees.e.step <- function(X, S) {
v = nrow(S)
m = ncol(X)
n = nrow(X)
latentFirstMoments = S[(m + 1):v, 1:m] %*% solve(S[1:m, 1:m]) %*% t(X)
schurComplement = S[(m + 1):v, (m + 1):v] - S[(m + 1):v, 1:m] %*% solve(S[1:m, 1:m], S[1:m, (m +
1):v])
latentFirstMomentCovarianceSum = latentFirstMoments %*% t(latentFirstMoments)
latentSecondMomentsSum = schurComplement + 1 / n * latentFirstMomentCovarianceSum
return(list(latentFirstMoments, latentSecondMomentsSum))
}
gaussian.trees.m.step <- function(latentFirstMoments, latentSecondMomentsSum, X,
edges, supp) {
if (is.vector(edges)) {
edges = t(matrix(edges, 2, length(edges) / 2))
}
n = dim(X)[1]
m = dim(X)[2]
v = 2 * m - 2
Sigma11 = 1 / n * t(X) %*% X
Sigma12 = 1 / n * t(latentFirstMoments %*% X)
Sigma22 = latentSecondMomentsSum
Sigma = rbind(cbind(Sigma11, Sigma12), cbind(t(Sigma12), Sigma22))
edgeCorrelations = rep(0, length(supp))
if (dim(edges)[1] > 0) {
for (i in 1:(dim(edges)[1])) {
if (supp[i] == 1) {
edgeCorrelations[i] = Sigma[edges[i, 1], edges[i, 2]] / sqrt(Sigma[edges[i, 1], edges[i, 1]] *
Sigma[edges[i, 2], edges[i, 2]])
}
}
}
return(getCovMat(edgeCorrelations, edges, v))
} |
geom_rect_interactive <- function(...)
layer_interactive(geom_rect, ...)
GeomInteractiveRect <- ggproto(
"GeomInteractiveRect",
GeomRect,
default_aes = add_default_interactive_aes(GeomRect),
parameters = interactive_geom_parameters,
draw_key = interactive_geom_draw_key,
draw_panel = function(self, data, panel_params, coord, linejoin = "mitre", .ipar = IPAR_NAMES) {
if (!coord$is_linear()) {
aesthetics <- setdiff(names(data),
c("x", "y", "xmin", "xmax", "ymin", "ymax"))
polys <-
lapply(split(data, seq_len(nrow(data))), function(row) {
poly <- rect_to_poly(row$xmin, row$xmax, row$ymin, row$ymax)
aes <- new_data_frame(row[aesthetics])[rep(1, 5), ]
GeomInteractivePolygon$draw_panel(cbind(poly, aes), panel_params, coord, .ipar = .ipar)
})
ggname("bar", do.call("grobTree", polys))
} else {
coords <- coord$transform(data, panel_params)
gr <- ggname(
"geom_rect_interactive",
rectGrob(
coords$xmin,
coords$ymax,
width = coords$xmax - coords$xmin,
height = coords$ymax - coords$ymin,
default.units = "native",
just = c("left", "top"),
gp = gpar(
col = coords$colour,
fill = alpha(coords$fill, coords$alpha),
lwd = coords$size * .pt,
lty = coords$linetype,
linejoin = linejoin,
lineend = if (identical(linejoin, "round"))
"round"
else
"square"
)
)
)
add_interactive_attrs(gr, coords, ipar = .ipar)
}
}
)
rect_to_poly <- function(xmin, xmax, ymin, ymax) {
new_data_frame(list(
y = c(ymax, ymax, ymin, ymin, ymax),
x = c(xmin, xmax, xmax, xmin, xmin)
))
} |
PhenoTrs <-
function(
x,
approach = c("White", "Trs"),
trs = 0.5,
min.mean = 0.1,
formula=NULL,
uncert=FALSE,
params=NULL,
breaks,
...
) {
if (all(is.na(x))) return(c(sos=NA, eos=NA, los=NA, pop=NA, mgs=NA, rsp=NA, rau=NA, peak=NA, msp=NA, mau=NA))
n <- index(x)[length(x)]
avg <- mean(x, na.rm=TRUE)
x2 <- na.omit(x)
avg2 <- mean(x2[x2 > min.mean], na.rm=TRUE)
peak <- max(x, na.rm=TRUE)
mn <- min(x, na.rm=TRUE)
ampl <- peak - mn
pop <- median(index(x)[which(x == max(x, na.rm=TRUE))])
approach <- approach[1]
if (approach == "White") {
ratio <- (x - mn) / ampl
trs.low <- trs - 0.1
trs.up <- trs + 0.1
}
if (approach == "Trs") {
ratio <- x
a <- diff(range(ratio, na.rm=TRUE)) * 0.1
trs.low <- trs - a
trs.up <- trs + a
}
.Greenup <- function (x, ...)
{
ratio.deriv <- c(NA, diff(x))
greenup <- rep(NA, length(x))
greenup[ratio.deriv > 0] <- TRUE
greenup[ratio.deriv < 0] <- FALSE
return(greenup)
}
greenup <- .Greenup(ratio)
bool <- ratio >= trs.low & ratio <= trs.up
soseos <- index(x)
sos <- round(median(soseos[greenup & bool], na.rm=TRUE))
eos <- round(median(soseos[!greenup & bool], na.rm=TRUE))
los <- eos - sos
los[los < 0] <- n + (eos[los < 0] - sos[los < 0])
mgs <- mean(x[ratio > trs], na.rm=TRUE)
msp <- mau <- NA
if (!is.na(sos)) {
id <- (sos-10):(sos+10)
id <- id[(id > 0) & (id < n)]
msp <- mean(x[which(index(x) %in% id==TRUE)], na.rm=TRUE)
}
if (!is.na(eos)) {
id <- (eos-10):(eos+10)
id <- id[(id > 0) & (id < n)]
mau <- mean(x[which(index(x) %in% id==TRUE)], na.rm=TRUE)
}
metrics <- c(sos=sos, eos=eos, los=los, pop=pop, mgs=mgs, rsp=NA, rau=NA, peak=peak, msp=msp, mau=mau)
return(metrics)
} |
qat_call_plot_lim_rule <-
function(resultlist_part, measurement_vector=NULL, time=NULL, height= NULL, lat=NULL, lon=NULL, measurement_name="", directoryname="", basename="", plotstyle=NULL) {
if (resultlist_part$method == 'lim_static') {
filename<-paste(basename,"_",resultlist_part$element,"_",'lim_static',sep="")
if (is.null(dim(resultlist_part$result$flagvector))) {
qat_plot_lim_rule_static_1d(resultlist_part$result$flagvector, filename, measurement_vector=measurement_vector, min_value=resultlist_part$result$min_value, max_value=resultlist_part$result$max_value, measurement_name=measurement_name, directoryname=directoryname, plotstyle=plotstyle)
}
if (length(dim(resultlist_part$result$flagvector))==2) {
qat_plot_lim_rule_static_2d(resultlist_part$result$flagvector, filename, measurement_vector=measurement_vector, min_value=resultlist_part$result$min_value, max_value=resultlist_part$result$max_value, measurement_name=measurement_name, directoryname=directoryname, plotstyle=plotstyle)
}
}
if (resultlist_part$method == 'lim_sigma') {
filename<-paste(basename,"_",resultlist_part$element,"_",'lim_sigma',sep="")
if (is.null(dim(resultlist_part$result$flagvector))) {
qat_plot_lim_rule_sigma_1d(resultlist_part$result$flagvector, filename, measurement_vector=measurement_vector, sigma_factor=resultlist_part$result$sigma_factor, meanofvector=resultlist_part$result$meanofvector, sdofvector=resultlist_part$result$sdofvector, measurement_name=measurement_name, directoryname=directoryname, plotstyle=plotstyle)
}
if (length(dim(resultlist_part$result$flagvector))==2) {
qat_plot_lim_rule_sigma_2d(resultlist_part$result$flagvector, filename, measurement_vector=measurement_vector, sigma_factor=resultlist_part$result$sigma_factor, meanofvector=resultlist_part$result$meanofvector, sdofvector=resultlist_part$result$sdofvector, measurement_name=measurement_name, directoryname=directoryname, plotstyle=plotstyle)
}
}
if (resultlist_part$method == 'lim_dynamic') {
filename<-paste(basename,"_",resultlist_part$element,"_",'lim_dynamic',sep="")
if (is.null(dim(resultlist_part$result$flagvector))) {
qat_plot_lim_rule_dynamic_1d(resultlist_part$result$flagvector, filename, measurement_vector=measurement_vector, min_vector=resultlist_part$result$min_vector, max_vector=resultlist_part$result$max_vector, min_vector_name=resultlist_part$result$min_vector_name, max_vector_name=resultlist_part$result$max_vector_name, measurement_name=measurement_name, directoryname=directoryname, plotstyle=plotstyle)
}
if (length(dim(resultlist_part$result$flagvector))==2) {
qat_plot_lim_rule_dynamic_1d(resultlist_part$result$flagvector, filename, measurement_vector=measurement_vector, min_vector=resultlist_part$result$min_vector, max_vector=resultlist_part$result$max_vector, min_vector_name=resultlist_part$result$min_vector_name, max_vector_name=resultlist_part$result$max_vector_name, measurement_name=measurement_name, directoryname=directoryname, plotstyle=plotstyle)
}
}
} |
tableby.control <- function(
test=TRUE,total=TRUE, total.pos = c("after", "before"), test.pname=NULL,
numeric.simplify=FALSE, cat.simplify=FALSE, cat.droplevels=FALSE, ordered.simplify=FALSE, date.simplify=FALSE,
numeric.test="anova", cat.test="chisq", ordered.test="trend", surv.test="logrank", date.test="kwt", selectall.test="notest",
test.always = FALSE,
numeric.stats=c("Nmiss","meansd","range"), cat.stats=c("Nmiss","countpct"),
ordered.stats=c("Nmiss", "countpct"), surv.stats=c("Nmiss", "Nevents","medSurv"), date.stats=c("Nmiss", "median","range"),
selectall.stats=c("Nmiss", "countpct"),
stats.labels = list(),
digits = 3L, digits.count = 0L, digits.pct = 1L, digits.p = 3L, format.p = TRUE, digits.n = 0L, conf.level = 0.95,
wilcox.correct = FALSE, wilcox.exact = NULL,
chisq.correct=FALSE, simulate.p.value=FALSE, B=2000, times = 1:5, ...) {
nm <- names(list(...))
if("digits.test" %in% nm) .Deprecated(msg = "Using 'digits.test = ' is deprecated. Use 'digits.p = ' instead.")
if("nsmall" %in% nm) .Deprecated(msg = "Using 'nsmall = ' is deprecated. Use 'digits = ' instead.")
if("nsmall.pct" %in% nm) .Deprecated(msg = "Using 'nsmall.pct = ' is deprecated. Use 'digits.pct = ' instead.")
if(!is.null(digits) && digits < 0L)
{
warning("digits must be >= 0. Set to default.")
digits <- 3L
}
if(!is.null(digits.count) && digits.count < 0L)
{
warning("digits.count must be >= 0. Set to default.")
digits.count <- 0L
}
if(!is.null(digits.pct) && digits.pct < 0L)
{
warning("digits.pct must be >= 0. Set to default.")
digits.pct <- 1L
}
if(!is.null(digits.p) && digits.p < 0L)
{
warning("digits.p must be >= 0. Set to default.")
digits.p <- 3L
}
if(!is.null(digits.n) && !is.na(digits.n) && digits.p < 0L)
{
warning("digits.n must be >= 0 or NA or NULL. Set to default.")
digits.n <- 0L
}
stats.labels <- if(is.null(stats.labels)) NULL else add_tbc_stats_labels(stats.labels)
list(test=test, total=total, total.pos = match.arg(total.pos), test.pname=test.pname,
numeric.simplify=numeric.simplify, cat.simplify=cat.simplify, cat.droplevels = cat.droplevels, ordered.simplify=ordered.simplify, date.simplify=date.simplify,
numeric.test=numeric.test, cat.test=cat.test, ordered.test=ordered.test, surv.test=surv.test, date.test=date.test, selectall.test=selectall.test,
test.always=test.always,
numeric.stats=numeric.stats, cat.stats=cat.stats, ordered.stats=ordered.stats, surv.stats=surv.stats, date.stats=date.stats, selectall.stats=selectall.stats,
stats.labels=stats.labels,
digits=digits, digits.p=digits.p, digits.count = digits.count, digits.pct = digits.pct, format.p = format.p, digits.n = digits.n,
conf.level=conf.level,
wilcox.correct = wilcox.correct, wilcox.exact = wilcox.exact,
chisq.correct=chisq.correct, simulate.p.value=simulate.p.value, B=B, times=times)
}
add_tbc_stats_labels <- function(x) {
start <- list(
Nmiss="N-Miss", Nmiss2="N-Miss", Nmisspct="N-Miss (%)", Nmisspct2="N-Miss (%)",
meansd="Mean (SD)", meanse = "Mean (SE)", meanpmsd="Mean ± SD", meanpmse = "Mean ± SE", medianrange="Median (Range)",
median="Median", medianq1q3="Median (Q1, Q3)", q1q3="Q1, Q3", iqr = "IQR",
mean = "Mean", sd = "SD", var = "Var", max = "Max", min = "Min", meanCI = "Mean (CI)", sum = "Sum",
gmean = "Geom Mean", gsd = "Geom SD", gmeansd = "Geom Mean (Geom SD)", gmeanCI = "Geom Mean (CI)",
range="Range", Npct="N (%)", Nrowpct="N (%)", Nevents="Events", medSurv="Median Survival",
medTime = "Median Follow-Up", medianmad="Median (MAD)", Nsigntest = "N (sign test)",
overall = "Overall", total = "Total", difference = "Difference"
)
nms <- setdiff(names(x), "")
start[nms] <- x[nms]
start
} |
if (require("testthat") && require("sjmisc") && require("dplyr")) {
data(efc)
data(mtcars)
efc$c172code <- as.factor(efc$c172code)
efc$e42dep <- as.factor(efc$e42dep)
test_that("std, vector", {
expect_is(std(efc$c12hour), "numeric")
})
test_that("std, data.frame", {
expect_is(std(efc, c12hour), "data.frame")
})
test_that("std, robust", {
expect_is(std(efc, c12hour, c160age, robust = "2sd"), "data.frame")
})
test_that("std, robust", {
expect_is(std(efc, c12hour, c160age, robust = "gmd", append = FALSE), "data.frame")
})
test_that("std, factors", {
tmp <- std(efc, append = FALSE)
expect_is(tmp$c172code_z, "factor")
tmp <- std(efc, append = FALSE, include.fac = TRUE)
expect_is(tmp$c172code_z, "numeric")
})
test_that("std, factors", {
mtcars %>%
dplyr::group_by(cyl) %>%
std(disp)
})
} |
prm <- c(one=1, two=2, 3=3, 4=4)
prm <- c(one=1, two=2, "3"=3, "4"=4)
prm
maskidx <- c(1)
maskidx <- c("one")
lower <- c(0,0,0,1)
upper <- c(1,1,1,1)
tmask <- which(lower==upper)
tmask
newmask <- maskidx && tmask
newmask <- maskidx & tmask
tmask
str(tmask)
str(maskidx)
pnames <- names(prm)
pnames
masked <- maskidx
masked
maskidx <- which(pnames %in% masked)
maskidx
newmask <- maskidx & tmask
newmask
newmask <- union(tmask, maskidx)
newmask
union(tmask, tmask)
savehistory("tunionmasked.R") |
NULL
configservice_batch_get_aggregate_resource_config <- function(ConfigurationAggregatorName, ResourceIdentifiers) {
op <- new_operation(
name = "BatchGetAggregateResourceConfig",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$batch_get_aggregate_resource_config_input(ConfigurationAggregatorName = ConfigurationAggregatorName, ResourceIdentifiers = ResourceIdentifiers)
output <- .configservice$batch_get_aggregate_resource_config_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$batch_get_aggregate_resource_config <- configservice_batch_get_aggregate_resource_config
configservice_batch_get_resource_config <- function(resourceKeys) {
op <- new_operation(
name = "BatchGetResourceConfig",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$batch_get_resource_config_input(resourceKeys = resourceKeys)
output <- .configservice$batch_get_resource_config_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$batch_get_resource_config <- configservice_batch_get_resource_config
configservice_delete_aggregation_authorization <- function(AuthorizedAccountId, AuthorizedAwsRegion) {
op <- new_operation(
name = "DeleteAggregationAuthorization",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_aggregation_authorization_input(AuthorizedAccountId = AuthorizedAccountId, AuthorizedAwsRegion = AuthorizedAwsRegion)
output <- .configservice$delete_aggregation_authorization_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_aggregation_authorization <- configservice_delete_aggregation_authorization
configservice_delete_config_rule <- function(ConfigRuleName) {
op <- new_operation(
name = "DeleteConfigRule",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_config_rule_input(ConfigRuleName = ConfigRuleName)
output <- .configservice$delete_config_rule_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_config_rule <- configservice_delete_config_rule
configservice_delete_configuration_aggregator <- function(ConfigurationAggregatorName) {
op <- new_operation(
name = "DeleteConfigurationAggregator",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_configuration_aggregator_input(ConfigurationAggregatorName = ConfigurationAggregatorName)
output <- .configservice$delete_configuration_aggregator_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_configuration_aggregator <- configservice_delete_configuration_aggregator
configservice_delete_configuration_recorder <- function(ConfigurationRecorderName) {
op <- new_operation(
name = "DeleteConfigurationRecorder",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_configuration_recorder_input(ConfigurationRecorderName = ConfigurationRecorderName)
output <- .configservice$delete_configuration_recorder_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_configuration_recorder <- configservice_delete_configuration_recorder
configservice_delete_conformance_pack <- function(ConformancePackName) {
op <- new_operation(
name = "DeleteConformancePack",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_conformance_pack_input(ConformancePackName = ConformancePackName)
output <- .configservice$delete_conformance_pack_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_conformance_pack <- configservice_delete_conformance_pack
configservice_delete_delivery_channel <- function(DeliveryChannelName) {
op <- new_operation(
name = "DeleteDeliveryChannel",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_delivery_channel_input(DeliveryChannelName = DeliveryChannelName)
output <- .configservice$delete_delivery_channel_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_delivery_channel <- configservice_delete_delivery_channel
configservice_delete_evaluation_results <- function(ConfigRuleName) {
op <- new_operation(
name = "DeleteEvaluationResults",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_evaluation_results_input(ConfigRuleName = ConfigRuleName)
output <- .configservice$delete_evaluation_results_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_evaluation_results <- configservice_delete_evaluation_results
configservice_delete_organization_config_rule <- function(OrganizationConfigRuleName) {
op <- new_operation(
name = "DeleteOrganizationConfigRule",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_organization_config_rule_input(OrganizationConfigRuleName = OrganizationConfigRuleName)
output <- .configservice$delete_organization_config_rule_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_organization_config_rule <- configservice_delete_organization_config_rule
configservice_delete_organization_conformance_pack <- function(OrganizationConformancePackName) {
op <- new_operation(
name = "DeleteOrganizationConformancePack",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_organization_conformance_pack_input(OrganizationConformancePackName = OrganizationConformancePackName)
output <- .configservice$delete_organization_conformance_pack_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_organization_conformance_pack <- configservice_delete_organization_conformance_pack
configservice_delete_pending_aggregation_request <- function(RequesterAccountId, RequesterAwsRegion) {
op <- new_operation(
name = "DeletePendingAggregationRequest",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_pending_aggregation_request_input(RequesterAccountId = RequesterAccountId, RequesterAwsRegion = RequesterAwsRegion)
output <- .configservice$delete_pending_aggregation_request_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_pending_aggregation_request <- configservice_delete_pending_aggregation_request
configservice_delete_remediation_configuration <- function(ConfigRuleName, ResourceType = NULL) {
op <- new_operation(
name = "DeleteRemediationConfiguration",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_remediation_configuration_input(ConfigRuleName = ConfigRuleName, ResourceType = ResourceType)
output <- .configservice$delete_remediation_configuration_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_remediation_configuration <- configservice_delete_remediation_configuration
configservice_delete_remediation_exceptions <- function(ConfigRuleName, ResourceKeys) {
op <- new_operation(
name = "DeleteRemediationExceptions",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_remediation_exceptions_input(ConfigRuleName = ConfigRuleName, ResourceKeys = ResourceKeys)
output <- .configservice$delete_remediation_exceptions_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_remediation_exceptions <- configservice_delete_remediation_exceptions
configservice_delete_resource_config <- function(ResourceType, ResourceId) {
op <- new_operation(
name = "DeleteResourceConfig",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_resource_config_input(ResourceType = ResourceType, ResourceId = ResourceId)
output <- .configservice$delete_resource_config_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_resource_config <- configservice_delete_resource_config
configservice_delete_retention_configuration <- function(RetentionConfigurationName) {
op <- new_operation(
name = "DeleteRetentionConfiguration",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_retention_configuration_input(RetentionConfigurationName = RetentionConfigurationName)
output <- .configservice$delete_retention_configuration_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_retention_configuration <- configservice_delete_retention_configuration
configservice_delete_stored_query <- function(QueryName) {
op <- new_operation(
name = "DeleteStoredQuery",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$delete_stored_query_input(QueryName = QueryName)
output <- .configservice$delete_stored_query_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$delete_stored_query <- configservice_delete_stored_query
configservice_deliver_config_snapshot <- function(deliveryChannelName) {
op <- new_operation(
name = "DeliverConfigSnapshot",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$deliver_config_snapshot_input(deliveryChannelName = deliveryChannelName)
output <- .configservice$deliver_config_snapshot_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$deliver_config_snapshot <- configservice_deliver_config_snapshot
configservice_describe_aggregate_compliance_by_config_rules <- function(ConfigurationAggregatorName, Filters = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeAggregateComplianceByConfigRules",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_aggregate_compliance_by_config_rules_input(ConfigurationAggregatorName = ConfigurationAggregatorName, Filters = Filters, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_aggregate_compliance_by_config_rules_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_aggregate_compliance_by_config_rules <- configservice_describe_aggregate_compliance_by_config_rules
configservice_describe_aggregation_authorizations <- function(Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeAggregationAuthorizations",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_aggregation_authorizations_input(Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_aggregation_authorizations_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_aggregation_authorizations <- configservice_describe_aggregation_authorizations
configservice_describe_compliance_by_config_rule <- function(ConfigRuleNames = NULL, ComplianceTypes = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeComplianceByConfigRule",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_compliance_by_config_rule_input(ConfigRuleNames = ConfigRuleNames, ComplianceTypes = ComplianceTypes, NextToken = NextToken)
output <- .configservice$describe_compliance_by_config_rule_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_compliance_by_config_rule <- configservice_describe_compliance_by_config_rule
configservice_describe_compliance_by_resource <- function(ResourceType = NULL, ResourceId = NULL, ComplianceTypes = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeComplianceByResource",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_compliance_by_resource_input(ResourceType = ResourceType, ResourceId = ResourceId, ComplianceTypes = ComplianceTypes, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_compliance_by_resource_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_compliance_by_resource <- configservice_describe_compliance_by_resource
configservice_describe_config_rule_evaluation_status <- function(ConfigRuleNames = NULL, NextToken = NULL, Limit = NULL) {
op <- new_operation(
name = "DescribeConfigRuleEvaluationStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_config_rule_evaluation_status_input(ConfigRuleNames = ConfigRuleNames, NextToken = NextToken, Limit = Limit)
output <- .configservice$describe_config_rule_evaluation_status_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_config_rule_evaluation_status <- configservice_describe_config_rule_evaluation_status
configservice_describe_config_rules <- function(ConfigRuleNames = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeConfigRules",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_config_rules_input(ConfigRuleNames = ConfigRuleNames, NextToken = NextToken)
output <- .configservice$describe_config_rules_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_config_rules <- configservice_describe_config_rules
configservice_describe_configuration_aggregator_sources_status <- function(ConfigurationAggregatorName, UpdateStatus = NULL, NextToken = NULL, Limit = NULL) {
op <- new_operation(
name = "DescribeConfigurationAggregatorSourcesStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_configuration_aggregator_sources_status_input(ConfigurationAggregatorName = ConfigurationAggregatorName, UpdateStatus = UpdateStatus, NextToken = NextToken, Limit = Limit)
output <- .configservice$describe_configuration_aggregator_sources_status_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_configuration_aggregator_sources_status <- configservice_describe_configuration_aggregator_sources_status
configservice_describe_configuration_aggregators <- function(ConfigurationAggregatorNames = NULL, NextToken = NULL, Limit = NULL) {
op <- new_operation(
name = "DescribeConfigurationAggregators",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_configuration_aggregators_input(ConfigurationAggregatorNames = ConfigurationAggregatorNames, NextToken = NextToken, Limit = Limit)
output <- .configservice$describe_configuration_aggregators_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_configuration_aggregators <- configservice_describe_configuration_aggregators
configservice_describe_configuration_recorder_status <- function(ConfigurationRecorderNames = NULL) {
op <- new_operation(
name = "DescribeConfigurationRecorderStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_configuration_recorder_status_input(ConfigurationRecorderNames = ConfigurationRecorderNames)
output <- .configservice$describe_configuration_recorder_status_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_configuration_recorder_status <- configservice_describe_configuration_recorder_status
configservice_describe_configuration_recorders <- function(ConfigurationRecorderNames = NULL) {
op <- new_operation(
name = "DescribeConfigurationRecorders",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_configuration_recorders_input(ConfigurationRecorderNames = ConfigurationRecorderNames)
output <- .configservice$describe_configuration_recorders_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_configuration_recorders <- configservice_describe_configuration_recorders
configservice_describe_conformance_pack_compliance <- function(ConformancePackName, Filters = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeConformancePackCompliance",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_conformance_pack_compliance_input(ConformancePackName = ConformancePackName, Filters = Filters, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_conformance_pack_compliance_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_conformance_pack_compliance <- configservice_describe_conformance_pack_compliance
configservice_describe_conformance_pack_status <- function(ConformancePackNames = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeConformancePackStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_conformance_pack_status_input(ConformancePackNames = ConformancePackNames, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_conformance_pack_status_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_conformance_pack_status <- configservice_describe_conformance_pack_status
configservice_describe_conformance_packs <- function(ConformancePackNames = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeConformancePacks",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_conformance_packs_input(ConformancePackNames = ConformancePackNames, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_conformance_packs_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_conformance_packs <- configservice_describe_conformance_packs
configservice_describe_delivery_channel_status <- function(DeliveryChannelNames = NULL) {
op <- new_operation(
name = "DescribeDeliveryChannelStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_delivery_channel_status_input(DeliveryChannelNames = DeliveryChannelNames)
output <- .configservice$describe_delivery_channel_status_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_delivery_channel_status <- configservice_describe_delivery_channel_status
configservice_describe_delivery_channels <- function(DeliveryChannelNames = NULL) {
op <- new_operation(
name = "DescribeDeliveryChannels",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_delivery_channels_input(DeliveryChannelNames = DeliveryChannelNames)
output <- .configservice$describe_delivery_channels_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_delivery_channels <- configservice_describe_delivery_channels
configservice_describe_organization_config_rule_statuses <- function(OrganizationConfigRuleNames = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeOrganizationConfigRuleStatuses",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_organization_config_rule_statuses_input(OrganizationConfigRuleNames = OrganizationConfigRuleNames, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_organization_config_rule_statuses_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_organization_config_rule_statuses <- configservice_describe_organization_config_rule_statuses
configservice_describe_organization_config_rules <- function(OrganizationConfigRuleNames = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeOrganizationConfigRules",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_organization_config_rules_input(OrganizationConfigRuleNames = OrganizationConfigRuleNames, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_organization_config_rules_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_organization_config_rules <- configservice_describe_organization_config_rules
configservice_describe_organization_conformance_pack_statuses <- function(OrganizationConformancePackNames = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeOrganizationConformancePackStatuses",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_organization_conformance_pack_statuses_input(OrganizationConformancePackNames = OrganizationConformancePackNames, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_organization_conformance_pack_statuses_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_organization_conformance_pack_statuses <- configservice_describe_organization_conformance_pack_statuses
configservice_describe_organization_conformance_packs <- function(OrganizationConformancePackNames = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeOrganizationConformancePacks",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_organization_conformance_packs_input(OrganizationConformancePackNames = OrganizationConformancePackNames, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_organization_conformance_packs_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_organization_conformance_packs <- configservice_describe_organization_conformance_packs
configservice_describe_pending_aggregation_requests <- function(Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribePendingAggregationRequests",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_pending_aggregation_requests_input(Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_pending_aggregation_requests_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_pending_aggregation_requests <- configservice_describe_pending_aggregation_requests
configservice_describe_remediation_configurations <- function(ConfigRuleNames) {
op <- new_operation(
name = "DescribeRemediationConfigurations",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_remediation_configurations_input(ConfigRuleNames = ConfigRuleNames)
output <- .configservice$describe_remediation_configurations_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_remediation_configurations <- configservice_describe_remediation_configurations
configservice_describe_remediation_exceptions <- function(ConfigRuleName, ResourceKeys = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeRemediationExceptions",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_remediation_exceptions_input(ConfigRuleName = ConfigRuleName, ResourceKeys = ResourceKeys, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_remediation_exceptions_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_remediation_exceptions <- configservice_describe_remediation_exceptions
configservice_describe_remediation_execution_status <- function(ConfigRuleName, ResourceKeys = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeRemediationExecutionStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_remediation_execution_status_input(ConfigRuleName = ConfigRuleName, ResourceKeys = ResourceKeys, Limit = Limit, NextToken = NextToken)
output <- .configservice$describe_remediation_execution_status_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_remediation_execution_status <- configservice_describe_remediation_execution_status
configservice_describe_retention_configurations <- function(RetentionConfigurationNames = NULL, NextToken = NULL) {
op <- new_operation(
name = "DescribeRetentionConfigurations",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$describe_retention_configurations_input(RetentionConfigurationNames = RetentionConfigurationNames, NextToken = NextToken)
output <- .configservice$describe_retention_configurations_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$describe_retention_configurations <- configservice_describe_retention_configurations
configservice_get_aggregate_compliance_details_by_config_rule <- function(ConfigurationAggregatorName, ConfigRuleName, AccountId, AwsRegion, ComplianceType = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "GetAggregateComplianceDetailsByConfigRule",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_aggregate_compliance_details_by_config_rule_input(ConfigurationAggregatorName = ConfigurationAggregatorName, ConfigRuleName = ConfigRuleName, AccountId = AccountId, AwsRegion = AwsRegion, ComplianceType = ComplianceType, Limit = Limit, NextToken = NextToken)
output <- .configservice$get_aggregate_compliance_details_by_config_rule_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_aggregate_compliance_details_by_config_rule <- configservice_get_aggregate_compliance_details_by_config_rule
configservice_get_aggregate_config_rule_compliance_summary <- function(ConfigurationAggregatorName, Filters = NULL, GroupByKey = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "GetAggregateConfigRuleComplianceSummary",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_aggregate_config_rule_compliance_summary_input(ConfigurationAggregatorName = ConfigurationAggregatorName, Filters = Filters, GroupByKey = GroupByKey, Limit = Limit, NextToken = NextToken)
output <- .configservice$get_aggregate_config_rule_compliance_summary_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_aggregate_config_rule_compliance_summary <- configservice_get_aggregate_config_rule_compliance_summary
configservice_get_aggregate_discovered_resource_counts <- function(ConfigurationAggregatorName, Filters = NULL, GroupByKey = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "GetAggregateDiscoveredResourceCounts",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_aggregate_discovered_resource_counts_input(ConfigurationAggregatorName = ConfigurationAggregatorName, Filters = Filters, GroupByKey = GroupByKey, Limit = Limit, NextToken = NextToken)
output <- .configservice$get_aggregate_discovered_resource_counts_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_aggregate_discovered_resource_counts <- configservice_get_aggregate_discovered_resource_counts
configservice_get_aggregate_resource_config <- function(ConfigurationAggregatorName, ResourceIdentifier) {
op <- new_operation(
name = "GetAggregateResourceConfig",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_aggregate_resource_config_input(ConfigurationAggregatorName = ConfigurationAggregatorName, ResourceIdentifier = ResourceIdentifier)
output <- .configservice$get_aggregate_resource_config_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_aggregate_resource_config <- configservice_get_aggregate_resource_config
configservice_get_compliance_details_by_config_rule <- function(ConfigRuleName, ComplianceTypes = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "GetComplianceDetailsByConfigRule",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_compliance_details_by_config_rule_input(ConfigRuleName = ConfigRuleName, ComplianceTypes = ComplianceTypes, Limit = Limit, NextToken = NextToken)
output <- .configservice$get_compliance_details_by_config_rule_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_compliance_details_by_config_rule <- configservice_get_compliance_details_by_config_rule
configservice_get_compliance_details_by_resource <- function(ResourceType, ResourceId, ComplianceTypes = NULL, NextToken = NULL) {
op <- new_operation(
name = "GetComplianceDetailsByResource",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_compliance_details_by_resource_input(ResourceType = ResourceType, ResourceId = ResourceId, ComplianceTypes = ComplianceTypes, NextToken = NextToken)
output <- .configservice$get_compliance_details_by_resource_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_compliance_details_by_resource <- configservice_get_compliance_details_by_resource
configservice_get_compliance_summary_by_config_rule <- function() {
op <- new_operation(
name = "GetComplianceSummaryByConfigRule",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_compliance_summary_by_config_rule_input()
output <- .configservice$get_compliance_summary_by_config_rule_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_compliance_summary_by_config_rule <- configservice_get_compliance_summary_by_config_rule
configservice_get_compliance_summary_by_resource_type <- function(ResourceTypes = NULL) {
op <- new_operation(
name = "GetComplianceSummaryByResourceType",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_compliance_summary_by_resource_type_input(ResourceTypes = ResourceTypes)
output <- .configservice$get_compliance_summary_by_resource_type_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_compliance_summary_by_resource_type <- configservice_get_compliance_summary_by_resource_type
configservice_get_conformance_pack_compliance_details <- function(ConformancePackName, Filters = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "GetConformancePackComplianceDetails",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_conformance_pack_compliance_details_input(ConformancePackName = ConformancePackName, Filters = Filters, Limit = Limit, NextToken = NextToken)
output <- .configservice$get_conformance_pack_compliance_details_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_conformance_pack_compliance_details <- configservice_get_conformance_pack_compliance_details
configservice_get_conformance_pack_compliance_summary <- function(ConformancePackNames, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "GetConformancePackComplianceSummary",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_conformance_pack_compliance_summary_input(ConformancePackNames = ConformancePackNames, Limit = Limit, NextToken = NextToken)
output <- .configservice$get_conformance_pack_compliance_summary_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_conformance_pack_compliance_summary <- configservice_get_conformance_pack_compliance_summary
configservice_get_discovered_resource_counts <- function(resourceTypes = NULL, limit = NULL, nextToken = NULL) {
op <- new_operation(
name = "GetDiscoveredResourceCounts",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_discovered_resource_counts_input(resourceTypes = resourceTypes, limit = limit, nextToken = nextToken)
output <- .configservice$get_discovered_resource_counts_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_discovered_resource_counts <- configservice_get_discovered_resource_counts
configservice_get_organization_config_rule_detailed_status <- function(OrganizationConfigRuleName, Filters = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "GetOrganizationConfigRuleDetailedStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_organization_config_rule_detailed_status_input(OrganizationConfigRuleName = OrganizationConfigRuleName, Filters = Filters, Limit = Limit, NextToken = NextToken)
output <- .configservice$get_organization_config_rule_detailed_status_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_organization_config_rule_detailed_status <- configservice_get_organization_config_rule_detailed_status
configservice_get_organization_conformance_pack_detailed_status <- function(OrganizationConformancePackName, Filters = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "GetOrganizationConformancePackDetailedStatus",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_organization_conformance_pack_detailed_status_input(OrganizationConformancePackName = OrganizationConformancePackName, Filters = Filters, Limit = Limit, NextToken = NextToken)
output <- .configservice$get_organization_conformance_pack_detailed_status_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_organization_conformance_pack_detailed_status <- configservice_get_organization_conformance_pack_detailed_status
configservice_get_resource_config_history <- function(resourceType, resourceId, laterTime = NULL, earlierTime = NULL, chronologicalOrder = NULL, limit = NULL, nextToken = NULL) {
op <- new_operation(
name = "GetResourceConfigHistory",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_resource_config_history_input(resourceType = resourceType, resourceId = resourceId, laterTime = laterTime, earlierTime = earlierTime, chronologicalOrder = chronologicalOrder, limit = limit, nextToken = nextToken)
output <- .configservice$get_resource_config_history_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_resource_config_history <- configservice_get_resource_config_history
configservice_get_stored_query <- function(QueryName) {
op <- new_operation(
name = "GetStoredQuery",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$get_stored_query_input(QueryName = QueryName)
output <- .configservice$get_stored_query_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$get_stored_query <- configservice_get_stored_query
configservice_list_aggregate_discovered_resources <- function(ConfigurationAggregatorName, ResourceType, Filters = NULL, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "ListAggregateDiscoveredResources",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$list_aggregate_discovered_resources_input(ConfigurationAggregatorName = ConfigurationAggregatorName, ResourceType = ResourceType, Filters = Filters, Limit = Limit, NextToken = NextToken)
output <- .configservice$list_aggregate_discovered_resources_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$list_aggregate_discovered_resources <- configservice_list_aggregate_discovered_resources
configservice_list_discovered_resources <- function(resourceType, resourceIds = NULL, resourceName = NULL, limit = NULL, includeDeletedResources = NULL, nextToken = NULL) {
op <- new_operation(
name = "ListDiscoveredResources",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$list_discovered_resources_input(resourceType = resourceType, resourceIds = resourceIds, resourceName = resourceName, limit = limit, includeDeletedResources = includeDeletedResources, nextToken = nextToken)
output <- .configservice$list_discovered_resources_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$list_discovered_resources <- configservice_list_discovered_resources
configservice_list_stored_queries <- function(NextToken = NULL, MaxResults = NULL) {
op <- new_operation(
name = "ListStoredQueries",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$list_stored_queries_input(NextToken = NextToken, MaxResults = MaxResults)
output <- .configservice$list_stored_queries_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$list_stored_queries <- configservice_list_stored_queries
configservice_list_tags_for_resource <- function(ResourceArn, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "ListTagsForResource",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$list_tags_for_resource_input(ResourceArn = ResourceArn, Limit = Limit, NextToken = NextToken)
output <- .configservice$list_tags_for_resource_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$list_tags_for_resource <- configservice_list_tags_for_resource
configservice_put_aggregation_authorization <- function(AuthorizedAccountId, AuthorizedAwsRegion, Tags = NULL) {
op <- new_operation(
name = "PutAggregationAuthorization",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_aggregation_authorization_input(AuthorizedAccountId = AuthorizedAccountId, AuthorizedAwsRegion = AuthorizedAwsRegion, Tags = Tags)
output <- .configservice$put_aggregation_authorization_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_aggregation_authorization <- configservice_put_aggregation_authorization
configservice_put_config_rule <- function(ConfigRule, Tags = NULL) {
op <- new_operation(
name = "PutConfigRule",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_config_rule_input(ConfigRule = ConfigRule, Tags = Tags)
output <- .configservice$put_config_rule_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_config_rule <- configservice_put_config_rule
configservice_put_configuration_aggregator <- function(ConfigurationAggregatorName, AccountAggregationSources = NULL, OrganizationAggregationSource = NULL, Tags = NULL) {
op <- new_operation(
name = "PutConfigurationAggregator",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_configuration_aggregator_input(ConfigurationAggregatorName = ConfigurationAggregatorName, AccountAggregationSources = AccountAggregationSources, OrganizationAggregationSource = OrganizationAggregationSource, Tags = Tags)
output <- .configservice$put_configuration_aggregator_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_configuration_aggregator <- configservice_put_configuration_aggregator
configservice_put_configuration_recorder <- function(ConfigurationRecorder) {
op <- new_operation(
name = "PutConfigurationRecorder",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_configuration_recorder_input(ConfigurationRecorder = ConfigurationRecorder)
output <- .configservice$put_configuration_recorder_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_configuration_recorder <- configservice_put_configuration_recorder
configservice_put_conformance_pack <- function(ConformancePackName, TemplateS3Uri = NULL, TemplateBody = NULL, DeliveryS3Bucket = NULL, DeliveryS3KeyPrefix = NULL, ConformancePackInputParameters = NULL) {
op <- new_operation(
name = "PutConformancePack",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_conformance_pack_input(ConformancePackName = ConformancePackName, TemplateS3Uri = TemplateS3Uri, TemplateBody = TemplateBody, DeliveryS3Bucket = DeliveryS3Bucket, DeliveryS3KeyPrefix = DeliveryS3KeyPrefix, ConformancePackInputParameters = ConformancePackInputParameters)
output <- .configservice$put_conformance_pack_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_conformance_pack <- configservice_put_conformance_pack
configservice_put_delivery_channel <- function(DeliveryChannel) {
op <- new_operation(
name = "PutDeliveryChannel",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_delivery_channel_input(DeliveryChannel = DeliveryChannel)
output <- .configservice$put_delivery_channel_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_delivery_channel <- configservice_put_delivery_channel
configservice_put_evaluations <- function(Evaluations = NULL, ResultToken, TestMode = NULL) {
op <- new_operation(
name = "PutEvaluations",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_evaluations_input(Evaluations = Evaluations, ResultToken = ResultToken, TestMode = TestMode)
output <- .configservice$put_evaluations_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_evaluations <- configservice_put_evaluations
configservice_put_external_evaluation <- function(ConfigRuleName, ExternalEvaluation) {
op <- new_operation(
name = "PutExternalEvaluation",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_external_evaluation_input(ConfigRuleName = ConfigRuleName, ExternalEvaluation = ExternalEvaluation)
output <- .configservice$put_external_evaluation_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_external_evaluation <- configservice_put_external_evaluation
configservice_put_organization_config_rule <- function(OrganizationConfigRuleName, OrganizationManagedRuleMetadata = NULL, OrganizationCustomRuleMetadata = NULL, ExcludedAccounts = NULL) {
op <- new_operation(
name = "PutOrganizationConfigRule",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_organization_config_rule_input(OrganizationConfigRuleName = OrganizationConfigRuleName, OrganizationManagedRuleMetadata = OrganizationManagedRuleMetadata, OrganizationCustomRuleMetadata = OrganizationCustomRuleMetadata, ExcludedAccounts = ExcludedAccounts)
output <- .configservice$put_organization_config_rule_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_organization_config_rule <- configservice_put_organization_config_rule
configservice_put_organization_conformance_pack <- function(OrganizationConformancePackName, TemplateS3Uri = NULL, TemplateBody = NULL, DeliveryS3Bucket = NULL, DeliveryS3KeyPrefix = NULL, ConformancePackInputParameters = NULL, ExcludedAccounts = NULL) {
op <- new_operation(
name = "PutOrganizationConformancePack",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_organization_conformance_pack_input(OrganizationConformancePackName = OrganizationConformancePackName, TemplateS3Uri = TemplateS3Uri, TemplateBody = TemplateBody, DeliveryS3Bucket = DeliveryS3Bucket, DeliveryS3KeyPrefix = DeliveryS3KeyPrefix, ConformancePackInputParameters = ConformancePackInputParameters, ExcludedAccounts = ExcludedAccounts)
output <- .configservice$put_organization_conformance_pack_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_organization_conformance_pack <- configservice_put_organization_conformance_pack
configservice_put_remediation_configurations <- function(RemediationConfigurations) {
op <- new_operation(
name = "PutRemediationConfigurations",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_remediation_configurations_input(RemediationConfigurations = RemediationConfigurations)
output <- .configservice$put_remediation_configurations_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_remediation_configurations <- configservice_put_remediation_configurations
configservice_put_remediation_exceptions <- function(ConfigRuleName, ResourceKeys, Message = NULL, ExpirationTime = NULL) {
op <- new_operation(
name = "PutRemediationExceptions",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_remediation_exceptions_input(ConfigRuleName = ConfigRuleName, ResourceKeys = ResourceKeys, Message = Message, ExpirationTime = ExpirationTime)
output <- .configservice$put_remediation_exceptions_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_remediation_exceptions <- configservice_put_remediation_exceptions
configservice_put_resource_config <- function(ResourceType, SchemaVersionId, ResourceId, ResourceName = NULL, Configuration, Tags = NULL) {
op <- new_operation(
name = "PutResourceConfig",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_resource_config_input(ResourceType = ResourceType, SchemaVersionId = SchemaVersionId, ResourceId = ResourceId, ResourceName = ResourceName, Configuration = Configuration, Tags = Tags)
output <- .configservice$put_resource_config_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_resource_config <- configservice_put_resource_config
configservice_put_retention_configuration <- function(RetentionPeriodInDays) {
op <- new_operation(
name = "PutRetentionConfiguration",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_retention_configuration_input(RetentionPeriodInDays = RetentionPeriodInDays)
output <- .configservice$put_retention_configuration_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_retention_configuration <- configservice_put_retention_configuration
configservice_put_stored_query <- function(StoredQuery, Tags = NULL) {
op <- new_operation(
name = "PutStoredQuery",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$put_stored_query_input(StoredQuery = StoredQuery, Tags = Tags)
output <- .configservice$put_stored_query_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$put_stored_query <- configservice_put_stored_query
configservice_select_aggregate_resource_config <- function(Expression, ConfigurationAggregatorName, Limit = NULL, MaxResults = NULL, NextToken = NULL) {
op <- new_operation(
name = "SelectAggregateResourceConfig",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$select_aggregate_resource_config_input(Expression = Expression, ConfigurationAggregatorName = ConfigurationAggregatorName, Limit = Limit, MaxResults = MaxResults, NextToken = NextToken)
output <- .configservice$select_aggregate_resource_config_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$select_aggregate_resource_config <- configservice_select_aggregate_resource_config
configservice_select_resource_config <- function(Expression, Limit = NULL, NextToken = NULL) {
op <- new_operation(
name = "SelectResourceConfig",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$select_resource_config_input(Expression = Expression, Limit = Limit, NextToken = NextToken)
output <- .configservice$select_resource_config_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$select_resource_config <- configservice_select_resource_config
configservice_start_config_rules_evaluation <- function(ConfigRuleNames = NULL) {
op <- new_operation(
name = "StartConfigRulesEvaluation",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$start_config_rules_evaluation_input(ConfigRuleNames = ConfigRuleNames)
output <- .configservice$start_config_rules_evaluation_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$start_config_rules_evaluation <- configservice_start_config_rules_evaluation
configservice_start_configuration_recorder <- function(ConfigurationRecorderName) {
op <- new_operation(
name = "StartConfigurationRecorder",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$start_configuration_recorder_input(ConfigurationRecorderName = ConfigurationRecorderName)
output <- .configservice$start_configuration_recorder_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$start_configuration_recorder <- configservice_start_configuration_recorder
configservice_start_remediation_execution <- function(ConfigRuleName, ResourceKeys) {
op <- new_operation(
name = "StartRemediationExecution",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$start_remediation_execution_input(ConfigRuleName = ConfigRuleName, ResourceKeys = ResourceKeys)
output <- .configservice$start_remediation_execution_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$start_remediation_execution <- configservice_start_remediation_execution
configservice_stop_configuration_recorder <- function(ConfigurationRecorderName) {
op <- new_operation(
name = "StopConfigurationRecorder",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$stop_configuration_recorder_input(ConfigurationRecorderName = ConfigurationRecorderName)
output <- .configservice$stop_configuration_recorder_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$stop_configuration_recorder <- configservice_stop_configuration_recorder
configservice_tag_resource <- function(ResourceArn, Tags) {
op <- new_operation(
name = "TagResource",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$tag_resource_input(ResourceArn = ResourceArn, Tags = Tags)
output <- .configservice$tag_resource_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$tag_resource <- configservice_tag_resource
configservice_untag_resource <- function(ResourceArn, TagKeys) {
op <- new_operation(
name = "UntagResource",
http_method = "POST",
http_path = "/",
paginator = list()
)
input <- .configservice$untag_resource_input(ResourceArn = ResourceArn, TagKeys = TagKeys)
output <- .configservice$untag_resource_output()
config <- get_config()
svc <- .configservice$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.configservice$operations$untag_resource <- configservice_untag_resource |
require(bigstatsr)
require(foreach)
require(microbenchmark)
source('R/utils.R')
fill <- function(n, m, block.size = 1e3) {
X <- big.matrix(n, m, type = "double", shared = TRUE)
intervals <- CutBySize(m, block.size)
for (i in 1:nrow(intervals)) {
X[, seq2(intervals[i, ])] <- rnorm(n * intervals[i, "size"])
}
X
}
nl <- c(1e3, 5e3, 20e3)
ml <- c(5e3, 20e3, 100e3)
grid <- expand.grid(n = nl, m = ml)
resSeq <- foreach(i = 1:nrow(grid), .combine = 'rbind') %do% {
n <- grid[i, "n"]
m <- grid[i, "m"]
X <- fill(n, m)
tmp <- microbenchmark(
RandomProjPCA(X, fun.scaling = colmeans_sds),
times = 10
)
rm(X); gc()
c(n, m, tmp[, 2] / 1e9)
}
getMeanSd <- function(x) {
tmp <- x[-(1:2)]
c(time.mean = mean(tmp), time.sd = sd(tmp))
}
test <- apply(resSeq, 1, getMeanSd)
res2 <- cbind(grid, t(test))
mylm <- lm(time.mean ~ n*m, data = res2)
print(summary(mylm))
mylm2 <- lm(time.mean ~ n:m - 1, data = res2)
print(summary(mylm2))
resPar <- foreach(i = 1:nrow(grid), .combine = 'rbind') %do% {
n <- grid[i, "n"]
m <- grid[i, "m"]
X <- fill(n, m)
tmp <- microbenchmark(
ParallelRandomProjPCA(X, fun.scaling = colmeans_sds, ncores = 6),
times = 10
)
rm(X); gc()
c(n, m, tmp[, 2] / 1e9)
}
test2 <- apply(resPar, 1, getMeanSd)
res3 <- cbind(grid, t(test2))
mylm3 <- lm(time.mean ~ n*m, data = res3)
print(summary(mylm3))
mylm4 <- lm(time.mean ~ n:m, data = res3)
print(summary(mylm4)) |
tunemat.fn <-
function(l.forget,l.noforget,d){
tune.mat<-matrix(unlist(unique(combn(rep(c(l.noforget,l.forget),d),d,simplify=FALSE))),(2^d),d,byrow=TRUE)
return(tune.mat)} |
elaborator_draw_curved_line <- function(x1, y1, x2, y2, ...) {
A <- matrix(c(x1, x2, 1, 1), nrow = 2, ncol = 2)
b <- c(-5, 5)
z <- solve(A, b)
x <- seq(x1, x2, 0.05)
y <- (y2 - y1) / 2 * tanh(z[1] * x + z[2]) + (y1 + y2) / 2
graphics::points(x, y, type = "l", ...)
} |
.check_validity_custom <- function(object) {
errors = character()
if(is.na(object@labels[1]))
errors = c(errors, 'type CUSTOM requires labels to be known')
if(is.na(object@levels[1]))
errors = c(errors, 'type CUSTOM requires levels to be known')
if(length(errors) == 0) TRUE else errors
}
setClass(
"variable_custom",
representation(
levels = "integer",
labels = "character"),
contains = "variable",
validity = .check_validity_custom
)
setGeneric("variable_custom",
valueClass = 'variable_custom',
function(name, labels, levels) standardGeneric("variable_custom")
)
setMethod("variable_custom",
signature(
name = "character",
labels = "character",
levels = "numeric"),
function(name, labels, levels)
new(
'variable_custom',
name = name,
type = "ENUM",
width = max(nchar(as.integer(levels))),
labels = labels,
levels = as.integer(levels)
)
)
setMethod("variable_custom",
signature(
name = "character",
labels = "character",
levels = "character"),
function(name, labels, levels)
variable_custom(name, labels = labels, levels = as.integer(levels))
)
setGeneric("variable_from_custom",
valueClass = 'variable_enum',
function(name, custom_type) standardGeneric("variable_from_custom")
)
setMethod("variable_from_custom",
signature(
name = "character",
custom_type = "variable_custom"
),
function(name, custom_type)
variable_enum(
name = name,
labels = as.character(variable_levels(custom_type)),
levels = variable_levels(custom_type)
)
)
setMethod('show', 'variable_custom', function(object){
callNextMethod(object)
cat('\n',
'labels : ', paste(sprintf("(%i:'%s')", variable_levels(object), variable_labels(object)), collapse = '|')
)
})
setMethod("variable_levels", "variable_custom", function(object) object@levels)
setMethod("variable_labels", "variable_custom", function(object) object@labels) |
setMethodS3("updateMeansTogether", "PairedPSCBS", function(fit, idxList, ..., avgTCN=c("mean", "median"), avgDH=c("mean", "median"), verbose=FALSE) {
nbrOfSegments <- nbrOfSegments(fit, splitters=TRUE)
if (!is.list(idxList)) {
idxList <- list(idxList)
}
idxList <- lapply(idxList, FUN=function(idxs) {
idxs <- Arguments$getIndices(idxs, max=nbrOfSegments)
sort(unique(idxs))
})
avgTCN <- match.arg(avgTCN)
avgDH <- match.arg(avgDH)
verbose <- Arguments$getVerbose(verbose)
if (verbose) {
pushState(verbose)
on.exit(popState(verbose))
}
verbose && enter(verbose, "Updating mean level estimates of multiple segments")
verbose && cat(verbose, "Segments:")
verbose && str(verbose, idxList)
avgList <- list(
tcn = get(avgTCN, mode="function"),
dh = get(avgDH, mode="function")
)
data <- getLocusData(fit)
segs <- getSegments(fit, splitters=TRUE)
nbrOfSegments <- nrow(segs)
verbose && cat(verbose, "Total number of segments: ", nbrOfSegments)
for (ss in seq_along(idxList)) {
idxs <- idxList[[ss]]
fitT <- extractSegments(fit, idxs)
verbose && cat(verbose, "Number of segments: ", nbrOfSegments(fitT))
dataT <- getLocusData(fitT)
segsT <- getSegments(fitT)
CT <- dataT$CT
rho <- dataT$rho
verbose && enter(verbose, "Recalculate (TCN,DH,C1,C2) means")
naValue <- NA_real_
mus <- c(tcn=naValue, dh=naValue, c1=naValue, c2=naValue)
for (key in c("tcn", "dh")) {
avgFUN <- avgList[[key]]
if (key == "tcn") {
value <- CT
} else if (key == "dh") {
value <- rho
}
keep <- which(!is.na(value))
gamma <- avgFUN(value[keep])
.stop_if_not(length(gamma) == 0 || !is.na(gamma))
mus[key] <- gamma
}
mus["c1"] <- 1/2*(1-mus["dh"])*mus["tcn"]
mus["c2"] <- mus["tcn"] - mus["c1"]
names(mus) <- sprintf("%sMean", names(mus))
verbose && print(verbose, mus)
verbose && exit(verbose)
for (key in names(mus)) {
segs[idxs,key] <- mus[key]
}
}
res <- fit
res$output <- segs
res <- setMeanEstimators(res, tcn=avgTCN, dh=avgDH)
verbose && exit(verbose)
res
}, private=TRUE) |
set.seed(126)
rpr_data = geoR::grf(25, cov.pars = c(1, 1), nugget = 0.1,
messages = FALSE)
y = rpr_data$data
x = matrix(1, nrow = length(y))
coords = rpr_data$coords
d = ganiso_d(rpr_data$coords, coords2 = rpr_data$coords,
invert = TRUE)
geoR_ml = geoR::likfit(rpr_data, ini = c(1, 1),
cov.model = "matern",
nugget = 0.1, kappa = 1,
psiA = pi/8, psiR = 1.5,
fix.nug = TRUE,
fix.kappa = TRUE,
fix.psiA = TRUE,
fix.psiR = FALSE,
messages = FALSE)
geoR_reml = geoR::likfit(rpr_data, ini = c(1, 1),
cov.model = "matern",
nugget = 0.1, kappa = 1,
psiA = pi/8, psiR = 1.5,
fix.nug = TRUE,
fix.kappa = TRUE,
fix.psiA = TRUE,
fix.psiR = FALSE,
messages = FALSE, lik.method = "REML")
aniso_coords = geoR::coords.aniso(coords, aniso.pars = geoR_reml$aniso.pars)
rpr_data_noaniso = rpr_data
rpr_data_noaniso$coords = aniso_coords
geoR_reml_noaniso = geoR::likfit(rpr_data_noaniso, ini = c(1, 1),
cov.model = "matern", kappa = 1,
nugget = 0.1, fix.nug = TRUE,
fix.kappa = TRUE,
messages = FALSE,
lik.method = "REML")
geoR_ml_loglik = geoR::loglik.GRF(rpr_data, obj.model = geoR_ml)
geoR_reml_loglik = geoR::loglik.GRF(rpr_data, obj.model = geoR_reml)
geoR_reml_noaniso_loglik = geoR::loglik.GRF(rpr_data_noaniso, obj.model = geoR_reml_noaniso)
kc_ml = geoR::krige.control(obj.model = geoR_ml)
geoR_out = geoR::output.control(messages = FALSE)
geoR_ml_beta = geoR::krige.conv(rpr_data, krige = kc_ml,
locations = cbind(1, 1),
output = geoR_out)$beta.est
kc_reml = geoR::krige.control(obj.model = geoR_reml)
geoR_reml_beta = geoR::krige.conv(rpr_data, krige = kc_reml,
locations = cbind(1, 1),
output = geoR_out)$beta.est
fpath = system.file("testdata", package = "gear")
fname = paste(fpath, "/ploglik_cmodStd_r_psill_ratio.rda", sep = "")
save(x, y, d, coords, geoR_ml, geoR_reml, geoR_ml_loglik,
geoR_reml_loglik, geoR_reml_noaniso_loglik,
geoR_ml_beta, geoR_reml_beta,
compress = "bzip2",
file = fname,
version = 2) |
context("test-rbindlist")
setup({
as.disk.frame(disk.frame:::gen_datatable_synthetic(1e3+11), file.path(tempdir(), "tmp_rbindlist1.df"), overwrite=TRUE)
as.disk.frame(disk.frame:::gen_datatable_synthetic(1e3+11), file.path(tempdir(), "tmp_rbindlist2.df"), overwrite=TRUE)
as.disk.frame(disk.frame:::gen_datatable_synthetic(1e3+11), file.path(tempdir(), "tmp_rbindlist4.df"), overwrite=TRUE)
})
test_that("test rbindlist", {
df1 = disk.frame(file.path(tempdir(), "tmp_rbindlist1.df"))
df2 = disk.frame(file.path(tempdir(), "tmp_rbindlist2.df"))
df3 = rbindlist.disk.frame(list(df1, df2), outdir = file.path(tempdir(), "tmp_rbindlist3.df"), overwrite=TRUE)
expect_equal(nrow(df3), 2*(1e3+11))
})
test_that("test rbindlist accepts only list", {
df1 = disk.frame(file.path(tempdir(), "tmp_rbindlist4.df"))
expect_error(rbindlist.disk.frame(df1, outdir = file.path(tempdir(), "tmp_rbindlist5.df")))
})
teardown({
fs::dir_delete(file.path(tempdir(), "tmp_rbindlist1.df"))
fs::dir_delete(file.path(tempdir(), "tmp_rbindlist2.df"))
fs::dir_delete(file.path(tempdir(), "tmp_rbindlist3.df"))
fs::dir_delete(file.path(tempdir(), "tmp_rbindlist4.df"))
fs::dir_delete(file.path(tempdir(), "tmp_rbindlist5.df"))
}) |
quadFuncCalc <- function( xNames, data, coef, shifterNames = NULL,
homWeights = NULL ) {
data <- .micEconVectorToDataFrame( data )
checkNames( c( xNames, shifterNames ), names( data ) )
.quadFuncCheckHomWeights( homWeights, xNames )
.quadFuncCheckCoefNames( names( coef ), nExog = length( xNames ),
shifterNames = shifterNames, data = data )
if( !is.null( homWeights ) ) {
deflator <- 0
for( i in seq( along = homWeights ) ) {
deflator <- deflator +
homWeights[ i ] * data[[ names( homWeights )[ i ] ]]
}
}
result <- rep( coef[ "a_0" ], nrow( data ) )
for( i in seq( along = xNames ) ) {
result <- result + coef[ paste( "a", i, sep = "_" ) ] *
.quadFuncVarHom( data, xNames[ i ], homWeights, deflator )
for( j in seq( along = xNames ) ) {
result <- result + 0.5 *
coef[ paste( "b", min( i, j ), max( i, j ), sep = "_" ) ] *
.quadFuncVarHom( data, xNames[ i ], homWeights, deflator ) *
.quadFuncVarHom( data, xNames[ j ], homWeights, deflator )
}
}
for( i in seq( along = shifterNames ) ) {
if( is.logical( data[[ shifterNames[ i ] ]] ) ) {
result <- result + coef[ paste( "d", i, "TRUE", sep = "_" ) ] *
data[[ shifterNames[ i ] ]]
} else if( is.factor( data[[ shifterNames[ i ] ]] ) ) {
for( j in levels( data[[ shifterNames[ i ] ]] ) ) {
thisCoefName <- paste( "d", i, j, sep = "_" )
if( thisCoefName %in% names( coef ) ) {
result <- result + coef[ thisCoefName ] *
( data[[ shifterNames[ i ] ]] == j )
}
}
} else {
result <- result + coef[ paste( "d", i, sep = "_" ) ] *
data[[ shifterNames[ i ] ]]
}
}
names( result ) <- rownames( data )
return( result )
} |
library(hamcrest)
expected <- structure(list(x = c(-2.23160583526092, -2.19312987258401, -2.1546539099071,
-2.11617794723018, -2.07770198455327, -2.03922602187636, -2.00075005919945,
-1.96227409652253, -1.92379813384562, -1.88532217116871, -1.8468462084918,
-1.80837024581488, -1.76989428313797, -1.73141832046106, -1.69294235778415,
-1.65446639510723, -1.61599043243032, -1.57751446975341, -1.5390385070765,
-1.50056254439958, -1.46208658172267, -1.42361061904576, -1.38513465636885,
-1.34665869369193, -1.30818273101502, -1.26970676833811, -1.2312308056612,
-1.19275484298428, -1.15427888030737, -1.11580291763046, -1.07732695495355,
-1.03885099227664, -1.00037502959972, -0.96189906692281, -0.923423104245898,
-0.884947141568985, -0.846471178892073, -0.807995216215161, -0.769519253538248,
-0.731043290861336, -0.692567328184423, -0.654091365507511, -0.615615402830598,
-0.577139440153686, -0.538663477476774, -0.500187514799861, -0.461711552122949,
-0.423235589446036, -0.384759626769124, -0.346283664092212, -0.307807701415299,
-0.269331738738387, -0.230855776061474, -0.192379813384562, -0.153903850707649,
-0.115427888030737, -0.0769519253538249, -0.0384759626769124,
0, 0.0384759626769124, 0.0769519253538249, 0.115427888030737,
0.15390385070765, 0.192379813384562, 0.230855776061475, 0.269331738738387,
0.3078077014153, 0.346283664092212, 0.384759626769124, 0.423235589446037,
0.461711552122949, 0.500187514799862, 0.538663477476774, 0.577139440153686,
0.615615402830599, 0.654091365507511, 0.692567328184424, 0.731043290861336,
0.769519253538248, 0.807995216215161, 0.846471178892073, 0.884947141568986,
0.923423104245898, 0.961899066922811, 1.00037502959972, 1.03885099227664,
1.07732695495355, 1.11580291763046, 1.15427888030737, 1.19275484298428,
1.2312308056612, 1.26970676833811, 1.30818273101502, 1.34665869369193,
1.38513465636885, 1.42361061904576, 1.46208658172267, 1.50056254439958,
1.5390385070765, 1.57751446975341, 1.61599043243032, 1.65446639510723,
1.69294235778415, 1.73141832046106, 1.76989428313797, 1.80837024581488,
1.8468462084918, 1.88532217116871, 1.92379813384562, 1.96227409652253,
2.00075005919945, 2.03922602187636, 2.07770198455327, 2.11617794723018,
2.1546539099071, 2.19312987258401, 2.23160583526092), y = c(0.791926876519226,
0.776913216182625, 0.761861236648169, 0.746778329119246, 0.731671884799247,
0.716549294891563, 0.701417950599583, 0.686285243126698, 0.671158563676298,
0.656045303451773, 0.640952853656513, 0.625888605493909, 0.610859950167351,
0.595874278880229, 0.580938982835932, 0.566061453237852, 0.551249081289378,
0.536509258193901, 0.521849375154811, 0.507276823375497, 0.492798994059351,
0.478423278409762, 0.464157067630121, 0.450007752923818, 0.435982725494244,
0.422089376544788, 0.408335097278841, 0.394727278899793, 0.381273312611033,
0.367980589615953, 0.354856501117942, 0.341908438320391, 0.329143792426691,
0.316569954640231, 0.304194316164402, 0.292024268202593, 0.280067201958195,
0.268330508634598, 0.256821579435192, 0.245547805563368, 0.234516578222515,
0.223735288616025, 0.213211327947287, 0.202952087419691, 0.192964958236629,
0.183257331601488, 0.173836598717661, 0.164710150788537, 0.155885379017507,
0.147369674607961, 0.139170428763288, 0.13129503268688, 0.123750877582125,
0.116545354652416, 0.109685855101141, 0.103179770131692, 0.0970344909474586,
0.0912574087518302, 0.0858559147481973, 0.0808374001399503, 0.0762092561304796,
0.0719788739231754, 0.0681536447214277, 0.0647409597286268, 0.0617482101481629,
0.0591827871834262, 0.0570520820378072, 0.0553634859146958, 0.0541243900174823,
0.053342185549557, 0.05302426371431, 0.0531780157151316, 0.053810832755412,
0.0549301060385414, 0.0565432267679101, 0.0586575861469083, 0.0612805753789261,
0.0644195856673538, 0.0680820082155816, 0.0722752342269998, 0.0770066549049985,
0.0822836614529681, 0.0881136450742987, 0.0945039969723803, 0.101462108350603,
0.108995370412358, 0.117111174361034, 0.125816911400023, 0.135119972732715,
0.145027749562499, 0.155547633092766, 0.166687014526905, 0.178453285068307,
0.190853835920363, 0.203896058286462, 0.217587343369996, 0.231935082374354,
0.246946666502927, 0.262629486959103, 0.278990934946274, 0.29603840166783,
0.31377927832716, 0.332220956127656, 0.351370826272707, 0.371236279965705,
0.391824708410038, 0.413143502809098, 0.435200054366274, 0.458001754284957,
0.481555993768537, 0.505870164020405, 0.53095165624395, 0.556807861642563,
0.583446171419634, 0.610873976778554, 0.639098668922712, 0.6681276390555
)), .Names = c("x", "y"))
assertThat(stats:::spline(x=c(-0.327103316347528, -0.194028142423926, -0.128901111149042,
0.0643168351238744, -0.779139683672991, 1.07572272256151, 0.615141104595973,
-0.539207639325099, -1.34233568007726, 1.76882503851871, 0.967421566101701,
0.128901111149042, 2.23160583526092, -0.466265261370636, -0.0643168351238744,
0.869423773288886, -1.07572272256151, -0.395725295814487, -0.615141104595974,
0.694801852365364, -1.76882503851871, 0.539207639325099, 1.34233568007726,
-2.23160583526092, 1.19837970230692, 0.25998960123107, 0.395725295814487,
0.779139683672991, 1.52121804642593, 0.327103316347528, -1.19837970230692,
-0.967421566101701, 0.466265261370636, -0.869423773288886, -0.25998960123107,
-1.52121804642593, 0.194028142423926, -0.694801852365364, 0),y=structure(c(0.14324231498137, 0.11684700107643, 0.105417349499038,
0.0776855863727447, 0.259677483053058, 0.116761056334463, 0.0565203054667309,
0.193104274129517, 0.448425619508942, 0.37067448790322, 0.0954676322082211,
0.0705929088404039, 0.6681276390555, 0.174936352005987, 0.0950963958222753,
0.0800884911230014, 0.354313071423935, 0.158369275917781, 0.213083234254889,
0.0614486908032015, 0.610442884419521, 0.053823253810292, 0.189428695910491,
0.791926876519226, 0.146527289603251, 0.0597660033945688, 0.0538545872022444,
0.0690804150504691, 0.255281939100249, 0.0561495290692076, 0.396707200866212,
0.318362682892637, 0.0530177084608072, 0.287174068638674, 0.129432546879759,
0.515088671856927, 0.0646040864336687, 0.235150461233751, 0.0858559147481973
), .Names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21",
"22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
"33", "34", "35", "36", "37", "38", "39")))
, identicalTo( expected, tol = 1e-6 ) ) |
cat_entries <- function(entries, table) {
if (entries == 0) cat(crayon::silver("\n\n No entries found."))
if (entries == 1) cat(crayon::green("\n\n 1 entry found\n"))
if (entries > 1) cat(crayon::green(paste0("\n\n ", entries), "entries found\n"))
if (entries > 0) cat(crayon::silver(paste0(" Fetching data from table '", table, "'\n\n")))
}
check_http <- function(res, table, stop, ...) {
if (...length() > 0) {
args <- ...elt(...length())
if (length(args) > 0) if (!is.list(args[1])) args <- list(...)
} else {
args <- NULL
}
code <- httr::status_code(res)
if (stop) {
if (code >= 400) {
if (!table %in% get_tables()) {
stop (
"The requested table '",
table,
"' does not exist.\nUse get_tables() to check for available tables."
)
}
var_diff <- setdiff(names(args), get_variables(table))
if (length(var_diff) > 0) {
if (length(var_diff) == 1) {
stop (
"Unknow filter variable '",
var_diff,
"'. \nUse get_variables(table = \"",
table,
"\") to check for available filter variables."
)
}
if (length(var_diff) > 1) {
stop (
"Unknow filter variables: '",
paste0(var_diff, collapse = "', '"),
"'. \nUse get_variables(table = \"",
table,
"\") to check for available filter variables."
)
}
}
status <- httr::http_status(res)
stop(status$message)
} else {
return(res)
}
} else {
if (code >= 400) {
return(invisible("suppressed-error"))
} else {
return(res)
}
}
}
check_url_length <- function(table, package_size, ...) {
nchar(get_url_skip(table, package_size, 0, ...))
} |
test_that("huc_12 works", {
rATTAINS_options(cache_downloads = FALSE)
huc12_cache$delete_all()
vcr::use_cassette("huc12_works", {
x_1 <- huc12_summary(huc = "020700100204")
})
testthat::expect_s3_class(x_1$huc_summary, "tbl_df")
testthat::expect_s3_class(x_1$au_summary, "tbl_df")
testthat::expect_s3_class(x_1$ir_summary, "tbl_df")
testthat::expect_s3_class(x_1$use_summary, "tbl_df")
testthat::expect_s3_class(x_1$param_summary, "tbl_df")
testthat::expect_s3_class(x_1$res_plan_summary, "tbl_df")
testthat::expect_s3_class(x_1$vision_plan_summary, "tbl_df")
vcr::use_cassette("huc12_chr_works", {
x_2 <- huc12_summary(huc = "020700100204", tidy = FALSE)
})
testthat::expect_type(x_2, "character")
})
test_that("huc_12 retuns errors", {
expect_error(huc12_summary(huc = 20700100204))
expect_error(huc12_summary(huc = "020700100204", tidy = "Y"))
skip_on_cran()
webmockr::enable()
stub <- webmockr::stub_request("get", "https://attains.epa.gov/attains-public/api/huc12summary?huc=020700100204")
webmockr::to_return(stub, status = 502)
testthat::expect_error(huc12_summary(huc = "020700100204"))
webmockr::disable()
})
test_that("huc12 cache works", {
skip_on_cran()
skip_if_offline()
rATTAINS_options(cache_downloads = TRUE)
Sys.sleep(20)
x <- huc12_summary(huc = "020700100204",
timeout_ms = 20000)
testthat::expect_message(huc12_summary(huc = "020700100204"),
"reading cached file from: ")
y <- huc12_summary(huc = "020700100204")
testthat::expect_equal(x, y)
}) |
parse_packet_set.SENSOR_DATA <- function(
set, log, tz = "UTC", verbose = FALSE,
parameters, schema, ...
) {
if (is.null(schema)) stop(paste(
"Cannot parse IMU packets without",
"a sensor schema.\n Make sure your call to read_gt3x",
" has (minimally) the following:",
"\n `include = c(\"SENSOR_SCHEMA\",",
"\"SENSOR_DATA\", \"PARAMETERS\")`"
))
if (is.null(parameters)) {
warning(paste(
"No `parameters` argument passed to ",
"parse_packet_set.SENSOR_DATA.\n Assuming",
"temperature offset is 21 degrees. Make sure by",
"making a\n read_gt3x call that has (minimally) the following:",
"\n `include = c(\"SENSOR_SCHEMA\", \"SENSOR_DATA\",",
"\"PARAMETERS\")`"
))
temp_offset <- 21
} else {
if (!"IMU_TEMP_OFFSET" %in% names(parameters$Payload)) {
warning(paste(
"PARAMETERS object has no `IMU_TEMP_OFFSET` entry.",
"\n Defaulting to 21 degrees."
))
temp_offset <- 21
} else {
temp_offset <- as.numeric(as.character(
parameters$Payload$IMU_TEMP_OFFSET
))
}
}
init <- get_times(
set$timestamp[1],
set$timestamp[nrow(set)] + 1,
schema$samples
) %>% {data.frame(
Timestamp = lubridate::with_tz(
., tz
)
)}
IMU <- parse_IMU_C(
set, log, schema$sensorColumns,
schema$id, schema$samples, verbose
) %>% {data.frame(
data.table::rbindlist(.)
)}
IMU$Timestamp <- lubridate::with_tz(
IMU$Timestamp, tz
)
if ("Temperature" %in% names(IMU)) {
if (verbose) cat(
"\r Calculating temperature",
" "
)
IMU$Temperature <- IMU$Temperature + temp_offset
}
IMU <- merge(
init, IMU, "Timestamp", all.x = TRUE
) %>% impute_IMU(
., verbose
) %>% {structure(
., class = append(class(.), "IMU", 0)
)}
if (verbose) packet_print("cleanup", class(set)[1])
IMU
} |
cross_validate <- function(container,nfold,algorithm=c("SVM","SLDA","BOOSTING","BAGGING","RF","GLMNET","TREE","NNET"),seed=NA,
method="C-classification", cross=0, cost=100, kernel="radial",
maxitboost=100,
maxitglm=10^5,
size=1,maxitnnet=1000,MaxNWts=10000,rang=0.1,decay=5e-4,
ntree=200,
l1_regularizer=0.0,l2_regularizer=0.0,use_sgd=FALSE,set_heldout=0,verbose=FALSE
) {
options(warn=-1)
if (!is.na(seed))
set.seed(seed)
extract_label_from_prob_names <- function(x) return(rownames(as.matrix(which.max(x))))
alldata <- rbind(container@training_matrix,container@classification_matrix)
allcodes <- as.factor(c(container@training_codes,container@testing_codes))
rand <- sample(nfold,dim(alldata)[1], replace=T)
cv_accuracy <- NULL
for (i in sort(unique(rand))) {
if (algorithm=="SVM") {
model <- svm(x=alldata[rand!=i,], y=allcodes[rand!=i],method=method,cross=cross,cost=cost,kernel=kernel)
pred <- predict(model,alldata[rand==i,])
} else
if (algorithm=="SLDA") {
alldata <- rbind(as.matrix(container@training_matrix),as.matrix(container@classification_matrix))
colnames(alldata) <- container@column_names
data_and_codes <- cbind(as.matrix(alldata),allcodes)
model <- slda(as.factor(allcodes)~.,data=data.frame(data_and_codes[rand!=i,]))
pred <- predict(model,data.frame(alldata[rand==i,]))
pred <- as.numeric(pred$class)
} else
if (algorithm=="RF") {
alldata <- rbind(as.matrix(container@training_matrix),as.matrix(container@classification_matrix))
data_and_codes <-cbind(alldata,allcodes)
model <- randomForest(as.factor(allcodes)~.,data=data_and_codes[rand!=i,], ntree=ntree)
pred <- predict(model,newdata=alldata[rand==i,])
} else
if (algorithm=="GLMNET") {
sparsedata <- as(as.matrix.csc(alldata[rand!=i,]),"dgCMatrix")
model <- glmnet(x=sparsedata, y=as.vector(allcodes[rand!=i]),family="multinomial", maxit=maxitglm)
prob <- predict(model,sparsedata,s=0.01,type="response")
pred <- apply(prob[,,1],1,extract_label_from_prob_names)
pred <- as.numeric(pred)
} else
if (algorithm=="BOOSTING") {
alldata <- rbind(as.matrix(container@training_matrix),as.matrix(container@classification_matrix))
colnames(alldata) <- container@column_names
data_and_codes <- cbind(alldata,allcodes)
model <- LogitBoost(xlearn=alldata[rand!=i,], ylearn=allcodes[rand!=i],maxitboost)
pred <- predict(model,data.frame(alldata[rand==i,]))
} else
if (algorithm=="BAGGING") {
alldata <- rbind(as.matrix(container@training_matrix),as.matrix(container@classification_matrix))
data_and_codes <-cbind(alldata,allcodes)
model <- bagging(as.factor(allcodes)~.,data=data.frame(data_and_codes[rand!=i,]))
pred <- predict(model,newdata=alldata[rand==i,])
} else
if (algorithm=="TREE") {
alldata <- rbind(as.matrix(container@training_matrix),as.matrix(container@classification_matrix))
colnames(alldata) <- container@column_names
data_and_codes <- cbind(alldata,allcodes)
model <- tree(as.factor(allcodes)~ ., data = data.frame(data_and_codes[rand!=i,]))
prob <- predict(model,newdata=data.frame(alldata[rand==i,]), type="vector")
pred <- apply(prob,1,which.max)
} else
if(algorithm=="NNET") {
alldata <- rbind(as.matrix(container@training_matrix),as.matrix(container@classification_matrix))
colnames(alldata) <- container@column_names
data_and_codes <- cbind(alldata,allcodes)
model <- nnet(as.factor(allcodes)~ ., data = data.frame(data_and_codes[rand!=i,]),size=size,maxit=maxitnnet,MaxNWts=MaxNWts,rang=rang,decay=decay,trace=FALSE)
prob <- predict(model,newdata=data.frame(alldata[rand==i,]))
pred <- apply(prob,1,which.max)
}
cv_accuracy[i] <- recall_accuracy(allcodes[rand==i],pred)
cat("Fold ",i," Out of Sample Accuracy"," = ",cv_accuracy[i],"\n",sep="")
}
return(list(cv_accuracy,meanAccuracy=mean(cv_accuracy)))
} |
options(digits=12)
if(!require("BB"))stop("this test requires package BB.")
if(!require("setRNG"))stop("this test requires setRNG.")
test.rng <- list(kind="Wichmann-Hill", normal.kind="Box-Muller", seed=c(979,1479,1542))
old.seed <- setRNG(test.rng)
cat("BB test poissmix.loglik ...\n")
test.rng <- list(kind="Wichmann-Hill", normal.kind="Box-Muller", seed=c(979,1479,1542))
old.seed <- setRNG(test.rng)
poissmix.loglik <- function(p,y) {
i <- 0:(length(y)-1)
loglik <- y*log(p[1]*exp(-p[2])*p[2]^i/exp(lgamma(i+1)) +
(1 - p[1])*exp(-p[3])*p[3]^i/exp(lgamma(i+1)))
return ( -sum(loglik) )
}
poissmix.dat <- data.frame(death=0:9, freq=c(162,267,271,185,111,61,27,8,3,1))
lo <- c(0.001,0,0)
hi <- c(0.999, Inf, Inf)
y <- poissmix.dat$freq
p <- runif(3,c(0.3,1,1),c(0.7,5,8))
system.time(ans.spg <- spg(par=p, fn=poissmix.loglik, y=y,
projectArgs=list(lower=lo, upper=hi),
control=list(maxit=2500, M=20)))[1]
z <- sum(ans.spg$par)
good <- 4.55961554279947
print(z, digits=16)
if(any(abs(good - z) > 1e-4)) stop("BB test poissmix.loglik a FAILED")
|
vcov.mpr <-
function(object, ...){
object$vcov
} |
library(plyr)
library(dplyr)
library(tidyr)
library(arules)
library(arulesViz)
library(plotly)
library(googleAnalyticsR)
data_f <- function(view_id,
date_range = c(Sys.Date() - 2, Sys.Date() - 1),
...){
google_analytics(view_id,
date_range = date_range,
metrics = c("itemQuantity", "itemRevenue"),
dimensions = c("productName", "transactionId"),
order = order_type("itemQuantity", "DESCENDING"),
max = 9999)
}
model_f <- function(df, ...){
if(nrow(df) == 0){
stop("No data found in this GA account")
}
temp <- tempfile(fileext = ".csv")
df1 <- df %>%
dplyr::mutate(
itemCost = itemRevenue / itemQuantity
) %>%
tidyr::uncount (weights = itemQuantity) %>%
plyr::ddply(c('transactionId'),
function(tf1)paste(tf1$productName,
collapse = ',')) %>%
tidyr::separate('V1',
into = paste('item',1:70,sep = "_"),
sep = ',') %>%
write.csv(temp)
a_trans <- arules::read.transactions(temp, format = "basket", sep = ",")
rules <- apriori(a_trans, parameter = list(supp=0.01, conf=0.05))
sort(rules, by='confidence', decreasing = TRUE)
}
output_f <- function(rules,
method = c("graph", "scatterplot", "matrix"),
max_n = 100, ...){
method <- match.arg(method)
if(!require(arulesViz)){
stop("Need library(arulesViz)")
}
plot(rules, method=method, engine = "default", max = max_n)
}
inputS <- shiny::tagList(
shiny::numericInput("max_n","Maximum number of rules",100,5,300, step = 1),
shiny::selectInput("method","Rule plot type",
choices = c("graph", "scatterplot", "matrix"))
)
model <- ga_model_make(
data_f = data_f,
required_columns = c("productName","transactionId","itemQuantity","itemRevenue"),
model_f = model_f,
output_f = output_f,
required_packages = c("plyr","dplyr","tidyr","arules","arulesViz"),
description = "Market Basket Analysis by Jamarius Taylor",
outputShiny = shiny::plotOutput,
renderShiny = shiny::renderPlot,
inputShiny = inputS
)
ga_model_save(model, "inst/models/examples/market-basket.gamr") |
modt.stat = function (X, L)
{
FUN = modt.fun(L=L)
score = FUN(X)
return( score )
}
modt.fun <- function (L)
{
if (missing(L)) stop("Class labels are missing!")
L = factor(L)
cl = levels(L)
if (length(cl) != 2) stop("Class labels must be specified for two groups, not more or less!")
function(X)
{
L = as.integer(L)
d <- cbind(rep(1, length(L)), L)
fit <- limma::lmFit(t(X), design=d)
eb.out <- limma::eBayes(fit)
modt <- -eb.out$t[,2]
return(modt)
}
} |
shinydashboard::tabItem(
tabName = "funnel",
fluidRow(
column(
width = 12,
br(),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("Simple example", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("funnel1"))
)),
tabPanel(
title = "Code",
fluidRow(
h2("Simple example", align="center"),
column(
width = 12,
verbatimTextOutput("code_funnel1"))
)
)
),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("3D", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("funnel2"))
)),
tabPanel(
title = "Code",
fluidRow(
h2("3D", align="center"),
column(
width = 12,
verbatimTextOutput("code_funnel2"))
)
)
),
tabBox(width=12,height=550,
tabPanel(
title = "Graphic",
fluidRow(
h2("Revert, labels position ...", align="center"),
column(
width = 12,
rAmCharts::amChartsOutput("funnel3"))
)),
tabPanel(
title = "Code",
fluidRow(
h2("Revert, labels position ...", align="center"),
column(
width = 12,
verbatimTextOutput("code_funnel3"))
)
)
)
)
)
) |
JRC <- R6::R6Class("JRC",
inherit = CountryDataClass,
public = list(
origin = "European Commission's Joint Research Centre (JRC)",
supported_levels = list("1", "2"),
supported_region_names = list("1" = "country", "2" = "region"),
supported_region_codes = list("1" = "iso_code", "2" = "region_code"),
level_data_urls = list(
"1" = list(
"country" = "https://raw.githubusercontent.com/ec-jrc/COVID-19/master/data-by-country/jrc-covid-19-all-days-by-country.csv"
),
"2" = list(
"region" = "https://raw.githubusercontent.com/ec-jrc/COVID-19/master/data-by-region/jrc-covid-19-all-days-by-regions.csv"
)
),
source_data_cols = c(
"CumulativePositive",
"CuulativeDeceased",
"CumulativeRecovered",
"CurrentlyPositive",
"Hospitalized",
"IntensiveCare"
),
source_text = "European Commission Joint Research Centre (JRC)",
source_url = "https://github.com/ec-jrc/COVID-19",
clean_common = function() {
self$data$clean <- self$data$raw[[names(self$data_urls)]] %>%
mutate(
Date = ymd(.data$Date),
CumulativePositive = as.double(.data$CumulativePositive),
CumulativeDeceased = as.double(.data$CumulativeDeceased),
CumulativeRecovered = as.double(.data$CumulativeRecovered),
CurrentlyPositive = as.double(.data$CurrentlyPositive),
Hospitalized = as.double(.data$Hospitalized)
) %>%
rename(
date = Date,
cases_total = CumulativePositive,
deaths_total = CumulativeDeceased,
recovered_total = CumulativeRecovered,
hosp_total = Hospitalized,
level_1_region = CountryName,
level_1_region_code = iso3
)
},
clean_level_1 = function() {
self$data$clean <- self$data$clean %>%
select(
date,
level_1_region,
level_1_region_code,
cases_total,
deaths_total,
recovered_total,
hosp_total,
everything()
)
},
clean_level_2 = function() {
self$data$clean <- self$data$clean %>%
rename(
level_2_region = Region,
level_2_region_code = NUTS
) %>%
select(
date,
level_1_region,
level_1_region_code,
level_2_region,
level_2_region_code,
cases_total,
deaths_total,
recovered_total,
hosp_total,
everything()
)
}
)
) |
set.seed(129)
n <- 100
p <- 2
X <- matrix(rnorm(n * p), n, p)
y <- rnorm(n)
obj <- .lm.fit (x = cbind(1, X), y = y)
info <- summary_lm(obj) |
set_coef.crch <- function(model, coefs) {
out <- model
out$coefficients["location"]$location <-
coefs[1:length(out$coefficients["location"]$location)]
out$coefficients["scale"]$scale <-
coefs[(length(out$coefficients["location"]$location) + 1):length(coefs)]
return(out)
}
get_vcov.crch <- function(model, ...) {
cn <- names(get_coef(model))
stats::vcov(model)
}
get_predict.crch <- function(model, newdata = NULL, type = "location", ...) {
pred <- stats::predict(model, newdata = newdata, type = type)
sanity_predict_vector(pred = pred, model = model, newdata = newdata, type = type)
sanity_predict_numeric(pred = pred, model = model, newdata = newdata, type = type)
out <- data.frame(
rowid = 1:nrow(newdata),
predicted = pred)
return(out)
}
set_coef.hlxr <- function(model, coefs) {
out <- model
idx_int <- length(model$coefficients$intercept)
idx_loc <- length(model$coefficients$location)
out$coefficients["intercept"]$intercept <- coefs[1:idx_int]
out$coefficients["location"]$location <- coefs[(idx_int + 1):(idx_int + 1 + idx_loc)]
out$coefficients["scale"]$scale <- coefs[(idx_int + idx_loc + 1):length(coefs)]
return(out)
}
get_vcov.hlxr <- get_vcov.crch
get_predict.hlxr <- get_predict.crch |
summary.gSlc <-function(object,colour=TRUE,paletteNumber=1,...)
{
fitObject <- object
if (!any(colour==c(TRUE,FALSE))) stop("colour must be TRUE or FALSE.\n")
if (!any(paletteNumber==c(1,2))) stop("paletteNumber must be 1 or 2.\n")
modelType <- fitObject$modelType
idnumPresent <- FALSE
if (any(modelType==c("linOnlyMix","linAddMix","pureAddMix")))
idnumPresent <- TRUE
if (is.null(fitObject$XlinPreds)) numLinCompons <- 0
if (!is.null(fitObject$XlinPreds)) numLinCompons <- ncol(fitObject$XlinPreds)
if (is.null(fitObject$XsplPreds)) numSplCompons <- 0
if (!is.null(fitObject$XsplPreds)) numSplCompons <- ncol(fitObject$XsplPreds)
ncZspl <- fitObject$ncZspl
linPredNames <- fitObject$linPredNames
splPredNames <- fitObject$splPredNames
nuMCMC <- t(fitObject$nu)
sigsqMCMC <- t(fitObject$sigmaSquared)
if (any(modelType==c("linOnly","linAdd","linOnlyMix","linAddMix")))
betaMCMC <- t(nuMCMC[1:(numLinCompons+1),])
if (idnumPresent)
sigsqRanEffMCMC <- sigsqMCMC[nrow(sigsqMCMC),]
preTransfData <- fitObject$preTransfData
if (preTransfData&any(modelType==c("linOnly","linAdd","linOnlyMix","linAddMix")))
{
XlinPreds <- fitObject$XlinPreds
minVec <- apply(XlinPreds,2,min) ; maxVec <- apply(XlinPreds,2,max)
denVec <- maxVec - minVec
betaStarMCMC <- betaMCMC
for (jLin in 2:(1+numLinCompons))
betaMCMC[,jLin] <- betaMCMC[,jLin]/denVec[jLin-1]
for (jLin in 2:(1+numLinCompons))
betaMCMC[,1] <- betaMCMC[,1] - betaStarMCMC[,jLin]*minVec[jLin-1]/denVec[jLin-1]
}
if (numSplCompons>0)
{
XsplPreds <- fitObject$XsplPreds
Zspl <- fitObject$Zspl
Cspl <- cbind(XsplPreds,Zspl)
etaMCMC <- crossprod(t(Cspl),nuMCMC[1:ncol(Cspl),])
if (fitObject$family=="binomial") wMCMC <- 0.5/(1 + cosh(etaMCMC))
if (fitObject$family=="poisson") wMCMC <- exp(etaMCMC)
nMCMCfinal <- ncol(nuMCMC)
edfMCMC <- rep(NA,nMCMCfinal)
Dmat <- diag(c(rep(0,ncol(XsplPreds)),rep(1,ncol(Zspl))))
diagonalEDFMAT <- matrix(NA,ncol(Cspl),nMCMCfinal)
for (iMCMC in 1:nMCMCfinal)
{
CTWCcurr <- crossprod(Cspl*wMCMC[,iMCMC],Cspl)
diagonalLambda <- rep(0,numSplCompons)
for (jSpl in 1:numSplCompons)
diagonalLambda <- c(diagonalLambda,(1/sigsqMCMC[jSpl,iMCMC])*rep(1,ncZspl[jSpl]))
diagonalEDFMAT[,iMCMC] <- diag(solve(CTWCcurr + diag(diagonalLambda),CTWCcurr))
}
edfMCMC <- vector("list",numSplCompons)
indsZstt <- numSplCompons + 1
for (jSpl in 1:numSplCompons)
{
indsZend <- indsZstt + ncZspl[jSpl] - 1
indsZcurr <- indsZstt:indsZend
indsCcurr <- c(jSpl,indsZcurr)
edfMCMC[[jSpl]] <- colSums(diagonalEDFMAT[indsCcurr,])
indsZstt <- indsZend + 1
}
if (any(modelType==c("pureAdd","pureAddMix"))&(numSplCompons==1))
edfMCMC[[1]] <- edfMCMC[[1]] + 1
}
MCMClistLength <- numLinCompons + numSplCompons + as.numeric(idnumPresent)
beta0included <- any(modelType==c("linOnly","linOnlyMix"))
if (beta0included)
MCMClistLength <- MCMClistLength + 1
parNamesVal <- vector("list",MCMClistLength)
MCMCmat <- NULL
if (any(modelType==c("linOnly","linAdd","linOnlyMix","linAddMix")))
{
if (any(modelType==c("linOnly","linOnlyMix")))
{
MCMCmat <- cbind(MCMCmat,betaMCMC)
parNamesVal[[1]] <- expression(beta[0])
indStt <- 1
}
if (!any(modelType==c("linOnly","linOnlyMix")))
{
MCMCmat <- cbind(MCMCmat,betaMCMC[,-1])
indStt <- 0
}
if (numLinCompons>0)
for (jLin in 1:numLinCompons)
parNamesVal[[indStt+jLin]] <- eval(bquote(expression(beta[.(linPredNames[jLin])])))
}
if (numSplCompons>0)
{
for (jSpl in 1:numSplCompons)
{
MCMCmat <- cbind(MCMCmat,edfMCMC[[jSpl]])
parNamesVal[[numLinCompons+jSpl]] <- eval(bquote(expression(edf[.(splPredNames[jSpl])])))
}
}
if (idnumPresent)
{
MCMCmat <- cbind(MCMCmat,sigsqRanEffMCMC)
parNamesVal[[as.numeric(beta0included)+numLinCompons+numSplCompons+1]] <- expression(sigma^2)
}
summMCMC(list(MCMCmat),colourVersion=colour,paletteNum=paletteNumber,parNames=parNamesVal)
} |
task = TaskGeneratorSimdens$new()$generate(20)
test_that("mlr_measures", {
keys = mlr_measures$keys("^dens")
for (key in keys) {
m = mlr_measures$get(key)
expect_measure(m)
perf = mlr_learners$get("dens.hist")$train(task)$predict(task)$score()
expect_number(perf, na.ok = "na_score" %in% m$properties)
}
}) |
BootAfterBootT.PI <-
function(x,p,h,nboot,prob)
{
n <- nrow(x)
B <- OLS.ART(x,p,h,prob)
BBC <- BootstrapT(x,p,h,200)
BBCB <- BootstrapTB(x,p,h,200)
bb <- BBCB$coef
eb <- sqrt( (n-p) / ( (n-p)-length(bb)))*BBCB$resid
bias <- B$coef - BBC$coef
ef <- sqrt( (n-p) / ( (n-p)-length(bb)))*BBC$resid
fore <- matrix(NA,nrow=nboot,ncol=h)
for(i in 1:nboot)
{
index <- as.integer(runif(n-p, min=1, max=nrow(eb)))
es <- eb[index,1]
xs <- ysbT(x, bb, es)
bs <- LSMT(xs,p)$coef
bsc <- bs-bias
bsc <- adjust(bs,bsc,p)
if(sum(bsc) != sum(bs))
bsc[(p+1):(p+2),] <- RE.LSMT(xs,p,bsc)
fore[i,] <- ART.ForeB(xs,bsc,h,ef,length(bs)-2)
}
Interval <- matrix(NA,nrow=h,ncol=length(prob),dimnames=list(1:h,prob))
for( i in 1:h)
Interval[i,] <- quantile(fore[,i],probs=prob)
return(list(PI=Interval,forecast=BBC$forecast))
} |
pluscode_westneighbour <- function(pluscode) {
code<-c("2","3","4","5","6","7","8","9","C","F","G","H","J","M","P","Q","R","V","W","X")
pluscode<-toupper(gsub(pattern = "\\+",replacement = "",pluscode))
pluscode_length<-nchar(pluscode)
if(pluscode_length %in% c(2,4,8,10)!=TRUE) {
stop(paste0("The pluscode is not a valid length, please enter value with length of 2/4/6/8/10, or 9/11 (with + character)"))
}
for(i in strsplit(pluscode,"")[[1]]){
if(any(grepl(i,code))!=TRUE){
stop(paste0("The character ",i," is not a valid pluscode character"))
}
}
d10<-strsplit(pluscode,"")[[1]][10]
d9<-strsplit(pluscode,"")[[1]][9]
d8<-strsplit(pluscode,"")[[1]][8]
d7<-strsplit(pluscode,"")[[1]][7]
d6<-strsplit(pluscode,"")[[1]][6]
d5<-strsplit(pluscode,"")[[1]][5]
d4<-strsplit(pluscode,"")[[1]][4]
d3<-strsplit(pluscode,"")[[1]][3]
d2<-strsplit(pluscode,"")[[1]][2]
d1<-strsplit(pluscode,"")[[1]][1]
if(d1%in% seq(3,9)!=TRUE){
stop(paste0("The character ",d1," is not a valid pluscode character for the first character"))
}
n10<-if(is.na(d10)==TRUE) {
NA
} else if (grep(d10,code)==1) {
code[20]
} else {
code[grep(d10,code)-1]
}
n8<-if(is.na(d8)==TRUE) {
NA
} else if(any(is.na(d10)==TRUE | grep(d10,code)==1,na.rm = T) & grep(d7,code)==1){
code[20]
} else if (any(is.na(d10)==TRUE | grep(d10,code)==1,na.rm = T)) {
code[grep(d8,code)-1]
} else {
code[grep(d8,code)]
}
n6<-if(is.na(d6)==TRUE) {
NA
} else if(any(is.na(d10)==TRUE | grep(d10,code)==1,na.rm = T) & any(is.na(d8)==TRUE | grep(d8,code)==1,na.rm = T) & grep(d6,code)==1){
code[20]
} else if (any(is.na(d10)==TRUE | grep(d10,code)==1,na.rm = T) & any(is.na(d8)==TRUE | grep(d8,code)==1,na.rm = T)) {
code[grep(d6,code)-1]
} else {
code[grep(d6,code)]
}
n4<-if(is.na(d4)==TRUE) {
NA
} else if(any(is.na(d10)==TRUE | grep(d10,code)==1,na.rm = T) & any(is.na(d8)==TRUE | grep(d8,code)==1,na.rm = T) & any(is.na(d6)==TRUE | grep(d6,code)==1,na.rm = T) & grep(d4,code)==1){
code[20]
} else if (any(is.na(d10)==TRUE | grep(d10,code)==1,na.rm = T) & any(is.na(d8)==TRUE | grep(d7,code)==1,na.rm = T) & any(is.na(d6)==TRUE | grep(d6,code)==1,na.rm = T)) {
code[grep(d4,code)-1]
} else {
code[grep(d4,code)]
}
n2<-if(is.na(d2)==TRUE) {
NA
} else if(any(is.na(d10)==TRUE | grep(d10,code)==1,na.rm = T) & any(is.na(d8)==TRUE | grep(d8,code)==1,na.rm = T) & any(is.na(d6)==TRUE | grep(d6,code)==1,na.rm = T) & any(is.na(d4)==TRUE | grep(d4,code)==1,na.rm = T) & grep(d2,code)==1){
code[20]
} else if(any(is.na(d10)==TRUE | grep(d10,code)==1,na.rm = T) & any(is.na(d8)==TRUE | grep(d8,code)==1,na.rm = T) & any(is.na(d6)==TRUE | grep(d6,code)==1,na.rm = T) & any(is.na(d4)==TRUE | grep(d4,code)==1,na.rm = T)) {
as.numeric(d2)-1
} else {
d2
}
pluscode_neighbour<-if(pluscode_length == 10) {
paste0(d1,n2,d3,n4,d5,n6,d7,n8,"+",d9,n10)
} else if(pluscode_length == 8) {
paste0(d1,n2,d3,n4,d5,n6,d7,n8,"+")
} else if(pluscode_length == 4) {
paste0(d1,n2,d3,n4)
} else if(pluscode_length == 2) {
paste0(d1,n2)
}
return(pluscode_neighbour)
} |
loadFields <- function(fieldnames=c("Liebe","Familie"),
baseurl=paste("https://raw.githubusercontent.com/quadrama/metadata/master",
ensureSuffix(directory,fileSep), sep=fileSep),
directory="fields/",
fileSuffix=".txt",
fileSep = "/") {
r <- list()
for (field in fieldnames) {
url <- paste(baseurl, field, fileSuffix, sep="")
r[[field]] <- as.character((readr::read_csv(url,
col_names = FALSE,
locale = readr::locale(),
col_types = c(readr::col_character())))$X1)
}
r
}
dictionaryStatistics <- function(drama, fields=DramaAnalysis::base_dictionary[fieldnames],
fieldnames=c("Liebe"),
segment=c("Drama","Act","Scene"),
normalizeByCharacter = FALSE,
normalizeByField = FALSE,
byCharacter = TRUE,
column="Token.lemma",
ci = TRUE) {
stopifnot(inherits(drama, "QDDrama"))
.N <- NULL
. <- NULL
corpus <- NULL
Speaker.figure_surface <- NULL
Speaker.figure_id <- NULL
segment <- match.arg(segment)
text <- switch(segment,
Drama=drama$text,
Act=segment(drama$text, drama$segments),
Scene=segment(drama$text, drama$segments))
bylist <- list(text$corpus, text$drama, text$Speaker.figure_id)
r <- aggregate(text, by=bylist, length)[,1:3]
first <- TRUE
singles <- lapply(names(fields),function(x) {
dss <- as.data.table(dictionaryStatisticsSingle(drama, fields[[x]], ci=ci,
segment = segment,
byCharacter = byCharacter,
normalizeByCharacter = normalizeByCharacter,
normalizeByField = normalizeByField,
column=column))
colnames(dss)[ncol(dss)] <- x
if (x == names(fields)[[1]]) {
if (segment=="Scene") {
u <- unique(text[,c("begin.Scene","Number.Act", "Number.Scene")])
dss <- merge(dss, u,
by.x=c("Number.Act", "Number.Scene"),
by.y=c("Number.Act", "Number.Scene"))
dss$begin.Scene <- NULL
data.table::setcolorder(dss, c("corpus","drama","Number.Act","Number.Scene","character",x))
}
dss
} else {
dss[,x,with=FALSE]
}
})
r <- Reduce(cbind,singles)
class(r) <- c("QDDictionaryStatistics", "QDHasCharacter", switch(segment,
Drama = "QDByDrama",
Act = "QDByAct",
Scene ="QDByScene"), "data.frame")
if (byCharacter)
class(r) <- append(class(r), "QDByCharacter")
r
}
dictionaryStatisticsSingle <- function(drama, wordfield=c(),
segment=c("Drama","Act","Scene"),
normalizeByCharacter = FALSE,
normalizeByField = FALSE,
byCharacter = TRUE,
fieldNormalizer = length(wordfield),
column="Token.lemma",
ci=TRUE,
colnames=NULL)
{
stopifnot(inherits(drama, "QDDrama"))
.N <- NULL
. <- NULL
.SD <- NULL
`:=` <- NULL
N <- NULL
value <- NULL
segment <- match.arg(segment)
text <- switch(segment,
Drama=drama$text,
Act=segment(drama$text, drama$segments),
Scene=segment(drama$text, drama$segments))
bycolumns <- c("corpus",
switch(segment,
Drama=c("drama"),
Act=c("drama","Number.Act"),
Scene=c("drama","Number.Act","Number.Scene"))
)
bylist <- paste(bycolumns,collapse=",")
if (ci) {
wordfield <- tolower(wordfield)
casing <- tolower
} else {
casing <- identity
}
if (normalizeByField == FALSE) {
fieldNormalizer <- 1
}
dt <- data.table(text)
dt$match <- casing(dt[[column]]) %in% wordfield
if (byCharacter == TRUE) {
xt <- dt[,melt(xtabs(~ Speaker.figure_id, data=.SD[match])),
keyby=bylist]
} else {
xt <- dt[,.(value=sum(match)), keyby=bylist]
}
if(normalizeByField || normalizeByCharacter) {
xt$value <- as.double(xt$value)
}
if (byCharacter == TRUE) {
xt <- unique(merge(xt, drama$characters,
by.x = c("corpus","drama","Speaker.figure_id"),
by.y = c("corpus","drama","figure_id"))[,names(xt), with=F])
}
if (normalizeByCharacter == TRUE) {
if (byCharacter == TRUE) {
bycolumns <- append(bycolumns,"Speaker.figure_id")
}
bylist <- paste(bycolumns, collapse=",")
xt <- merge(xt, dt[,.N,keyby=bylist],
by.x = bycolumns,
by.y = bycolumns)
xt[,value:=((value/fieldNormalizer)/N), keyby=bylist]
xt <- xt[,-"N"]
} else {
xt$value <- as.double(xt$value) / fieldNormalizer
}
r <- xt
colnames(r)[ncol(r)] <- "x"
if (byCharacter) {
colnames(r)[ncol(r)-1] <- "character"
}
if (! is.null(colnames)) {
colnames(r) <- colnames
}
r[is.nan(r$x)]$x <- 0
class(r) <- c("QDDictionaryStatistics", "QDHasCharacter",
switch(segment,
Drama = "QDByDrama",
Act = "QDByAct",
Scene ="QDByScene"), "data.frame", class(r))
if (byCharacter) {
class(r) <- append(class(r), "QDByCharacter")
r$character <- as.factor(r$character)
}
r
}
filterByDictionary <- function(ft,
fields=DramaAnalysis::base_dictionary[fieldnames],
fieldnames=c("Liebe")) {
as.matrix(ft[,which(colnames(ft) %in% unlist(fields))])
}
as.matrix.QDDictionaryStatistics <- function (x, ...) {
stopifnot(inherits(x, "QDDictionaryStatistics"))
if (inherits(x, "QDByCharacter")) {
byCharacter <- TRUE
} else {
byCharacter <- FALSE
}
if (inherits(x, "QDByDrama")) {
segment <- "Drama"
metaCols <- 1:(3+byCharacter)
} else if (inherits(x, "QDByAct")) {
segment <- "Act"
metaCols <- 1:(4+byCharacter)
} else if (inherits(x, "QDByScene")) {
segment <- "Scene"
metaCols <- 1:(5+byCharacter)
}
as.matrix.data.frame(x[,max(metaCols):ncol(x)])
} |
ne_download <- function(scale = 110,
type = 'countries',
category = c('cultural', 'physical', 'raster'),
destdir = tempdir(),
load = TRUE,
returnclass = c('sp','sf')
)
{
category <- match.arg(category)
returnclass <- match.arg(returnclass)
file_name <- ne_file_name(scale=scale, type=type, category=category, full_url=FALSE)
address <- ne_file_name(scale=scale, type=type, category=category, full_url=TRUE)
download_failed <- tryCatch( utils::download.file(file.path(address), zip_file <- tempfile()),
error = function(e) {
message(paste('download failed'))
check_data_exist( scale = scale, category = category, type = type )
return(TRUE)
})
if (download_failed) return()
utils::unzip(zip_file, exdir=destdir)
if ( load & category == 'raster' )
{
rst <- raster::raster(file.path(destdir, file_name, paste0(file_name, '.tif')))
return(rst)
} else if ( load )
{
sp_object <- rgdal::readOGR(destdir, file_name, encoding='UTF-8', stringsAsFactors=FALSE, use_iconv=TRUE)
sp_object@data[sp_object@data=='-99' | sp_object@data=='-099'] <- NA
return( ne_as_sf(sp_object, returnclass))
} else
{
return(file_name)
}
} |
hlm_resid <- function(object, ...){
UseMethod("hlm_resid", object)
}
hlm_resid.default <- function(object, ...){
stop(paste("there is no hlm_resid() method for objects of class",
paste(class(object), collapse=", ")))
}
hlm_resid.lmerMod <- function(object, level = 1, standardize = FALSE, include.ls = TRUE, data = NULL, ...) {
if(!isNestedModel(object)){
stop("hlm_resid is not currently implemented for non-nested models.")
}
if(!level %in% c(1, names(object@flist))) {
stop("level can only be 1 or the following grouping factors from the fitted model: \n",
stringr::str_c(names(object@flist), collapse = ", "))
}
if(!is.null(standardize) && !standardize %in% c(FALSE, TRUE, "semi")) {
stop("standardize can only be specified to be logical or 'semi'.")
}
if(class(attr(object@frame, "na.action")) == "exclude" && is.null(data) && level == 1){
stop("Please provide the data frame used to fit the model. This is necessary when the na.action is set to na.exclude")
}
if(!is.null(getCall(object)$correlation)){
warning("LS residuals for non-random correlation are not yet implemented")
include.ls <- FALSE
}
if(class(attr(object@frame, "na.action")) == "exclude"){
na.index <- which(!rownames(data) %in% rownames(object@frame))
col.index <- which(colnames(data) %in% colnames(object@frame))
data <- data[col.index]
} else {
data <- object@frame
}
if(level == 1) {
if(include.ls == TRUE) {
ls.resid <- LSresids(object, level = 1, standardize = standardize)
ls.resid <- ls.resid[order(as.numeric(rownames(ls.resid))),]
}
if (standardize == TRUE) {
eb.resid <- data.frame(.std.resid = resid(object, scale = TRUE))
} else {
eb.resid <- data.frame(.resid = resid(object))
}
eb.fitted <- data.frame(.fitted = predict(object))
mr <- object@resp$y - lme4::getME(object, "X") %*% lme4::fixef(object)
if (standardize == TRUE) {
sig0 <- lme4::getME(object, "sigma")
ZDZt <- sig0^2 * crossprod( lme4::getME(object, "A") )
n <- nrow(ZDZt)
R <- Diagonal( n = n, x = sig0^2 )
V <- R + ZDZt
V.chol <- chol( V )
Lt <- solve(t(V.chol))
mar.resid <- data.frame(.chol.mar.resid = (Lt %*% mr)[,1])
} else {
mar.resid <- data.frame(.mar.resid = mr[,1])
}
mar.fitted <- data.frame(.mar.fitted = predict(object, re.form = ~0))
if(class(attr(object@frame, "na.action")) == "exclude"){
if(include.ls == TRUE){
problem_dfs <- cbind(ls.resid, mar.resid)
na.fix <- data.frame(LSR = rep(NA, length(na.index)),
LSF = rep(NA, length(na.index)),
MR = rep(NA, length(na.index)))
rownames(na.fix) <- na.index
names(na.fix) <- c(names(ls.resid), names(mar.resid))
problem_dfs <- rbind(problem_dfs, na.fix)
problem_dfs <- problem_dfs[order(as.numeric(rownames(problem_dfs))),]
} else {
na.fix <- data.frame(MR = rep(NA, length(na.index)))
rownames(na.fix) <- na.index
names(na.fix) <- names(mar.resid)
problem_dfs <- rbind(mar.resid, na.fix)
problem_dfs <- data.frame(MR = problem_dfs[order(as.numeric(rownames(problem_dfs))),])
names(problem_dfs) <- names(mar.resid)
}
} else {
if(include.ls == TRUE){
problem_dfs <- cbind(ls.resid, mar.resid)
} else {
problem_dfs <- mar.resid
}
}
if (include.ls == TRUE) {
return.tbl <- tibble::tibble("id" = as.numeric(rownames(data)),
data,
eb.resid,
eb.fitted,
problem_dfs,
mar.fitted)
} else {
return.tbl <- tibble::tibble("id" = as.numeric(rownames(data)),
data,
eb.resid,
eb.fitted,
problem_dfs,
mar.fitted)
}
return(return.tbl)
}
if (level %in% names(object@flist)) {
eb.resid <- lme4::ranef(object)[[level]]
eb.resid <- janitor::clean_names(eb.resid)
groups <- rownames(eb.resid)
if (standardize == TRUE) {
se.re <- se.ranef(object)[[level]]
eb.resid <- eb.resid/se.re
eb.names <- paste0(".std.ranef.", names(eb.resid))
} else {
eb.names <- paste0(".ranef.", names(eb.resid))
}
if (include.ls == TRUE) {
ls.resid <- LSresids(object, level = level, stand = standardize)
ls.resid <- ls.resid[match(groups, ls.resid$group),]
ls.resid <- janitor::clean_names(ls.resid)
if (standardize == TRUE) {
ls.names <- paste0(".std.ls.", names(ls.resid))
} else {
ls.names <- paste0(".ls.", names(ls.resid))
}
}
fixed <- as.character(lme4::nobars( formula(object)))
data <- object@frame
names(data)[which(names(data) == fixed[2])] <- "y"
fixed[2] <- "y"
n.ranefs <- length(names(object@flist))
ranef_names <- names( lme4::ranef(object)[[level]] )
if(level == names(object@flist)[n.ranefs]){
form <- paste(fixed[2], fixed[1], fixed[3], "|", level)
g.list <- suppressWarnings(lme4::lmList(formula(form), data = data))
g.index <- which(purrr::map_lgl(coef(g.list), ~all(is.na(.x))))
g.names <- names(g.index)
interaction.index <- stringr::str_detect(g.names, ":")
g.names <- g.names[!interaction.index]
g.exp <- stringr::str_c(g.names, collapse = "|")
g.index.frame <- which(
stringr::str_detect(g.exp, names(object@frame)))
g.vars <- object@frame %>%
dplyr::select(all_of(level), all_of(g.index.frame))
g.vars <- unique(g.vars)
if (include.ls == TRUE) {
return.tbl <- suppressMessages(tibble::tibble(
groups, eb.resid, ls.resid[,-1], .name_repair = "universal"))
names(return.tbl) <- c(level, eb.names, ls.names[-1])
if(sum(class(g.vars[level][[1]]) != class(return.tbl[level][[1]])) != 0){
g.vars[level][[1]] <- as.character(g.vars[level][[1]])
return.tbl[level][[1]] <- as.character(return.tbl[level][[1]])
}
return.tbl <- tibble::tibble(
unique(suppressMessages(dplyr::left_join(g.vars, return.tbl))))
} else {
return.tbl <- tibble::tibble(groups, eb.resid)
names(return.tbl) <- c(level, eb.names)
if(sum(class(g.vars[level][[1]]) != class(return.tbl[level][[1]])) != 0){
g.vars[level][[1]] <- as.character(g.vars[level][[1]])
return.tbl[level][[1]] <- as.character(return.tbl[level][[1]])
}
return.tbl <- tibble::tibble(
unique(suppressMessages(dplyr::left_join(g.vars, return.tbl))))
}
return(return.tbl)
} else {
level.var <- stringr::str_split(level, ":")[[1]]
level.var <- level.var[which(!level.var %in% names(object@flist))]
form <- paste(fixed[2], fixed[1], fixed[3], "|", level.var)
g.list <- suppressWarnings(lme4::lmList(formula(form), data = data))
g.index <- which(purrr::map_lgl(coef(g.list), ~all(is.na(.x))))
g.names <- names(g.index)
interaction.index <- stringr::str_detect(g.names, ":")
g.names <- g.names[!interaction.index]
higher.level <- names(object@flist[which(names(object@flist) == level) + 1])
g.exp <- stringr::str_c(g.names, collapse = "|")
g.index.frame <- which(
stringr::str_detect(g.exp, names(object@frame)))
g.vars <- object@frame %>%
dplyr::select(all_of(level.var), all_of(higher.level), all_of(g.index.frame))
g.vars <- unique(g.vars)
g.vars$group <- rep(NA, nrow(g.vars))
for (i in 1:nrow(g.vars)){
g.vars$group[i] <- stringr::str_c(g.vars[level.var][i,],
g.vars[higher.level][i,], sep = ":")
}
g.vars <- g.vars %>%
dplyr::select(ncol(g.vars), 1:(ncol(g.vars)-1))
if (include.ls == TRUE) {
return.tbl <- suppressMessages(tibble::tibble(
groups, eb.resid, ls.resid[,-1], .name_repair = "universal"))
names(return.tbl) <- c("group", eb.names, ls.names[-1])
return.tbl <- tibble::tibble(
unique(suppressMessages(dplyr::left_join(g.vars, return.tbl))))
} else {
return.tbl <- tibble::tibble(groups, eb.resid)
names(return.tbl) <- c("group", eb.names)
return.tbl <- tibble::tibble(
unique(suppressMessages(dplyr::left_join(g.vars, return.tbl))))
}
return(return.tbl)
}
}
}
hlm_resid.lme <- function(object, level = 1, standardize = FALSE, include.ls = TRUE, data = NULL, ...) {
if(!isNestedModel(object)){
stop("hlm_resid is not currently implemented for non-nested models.")
}
if(!level %in% c(1, names(object$groups))) {
stop("level can only be 1 or the following grouping factors from the fitted model: \n",
stringr::str_c(names(object$groups), collapse = ", "))
}
if(!is.null(standardize) && !standardize %in% c(FALSE, TRUE, "semi")) {
stop("standardize can only be specified to be logical or 'semi'.")
}
if(level == 1) {
if(include.ls == TRUE) {
ls.resid <- LSresids(object, level = 1, stand = standardize)
ls.resid <- ls.resid[order(as.numeric(rownames(ls.resid))),]
}
if(standardize == TRUE) {
eb.resid <- data.frame(.std.resid = resid(object, type = "normalized"))
} else {
eb.resid <- data.frame(.resid = resid(object, type = "response"))
}
eb.fitted <- data.frame(.fitted = fitted(object))
mr <- resid(object, type="response", level=0)
if (standardize == TRUE) {
V <- Matrix(extract_design(object)$V)
V.chol <- chol( V )
Lt <- solve(t(V.chol))
mar.resid <- data.frame(.chol.mar.resid = (Lt %*% mr)[,1])
} else {
mar.resid <- data.frame(.mar.resid = mr)
}
mar.fitted <- data.frame(.mar.fitted = fitted(object, level=0))
fixed <- as.character(formula(object))
dataform <- paste(fixed[2], fixed[1], fixed[3], " + ",
paste(names(object$groups), collapse = " + "))
data <- object$data %>%
dplyr::mutate(dplyr::across(where(is.character), ~ as.factor(.x))) %>%
as.data.frame()
model.data <- model.frame(formula(dataform), data)
if(class(object$na.action) == "exclude"){
na.index <- which(!rownames(data) %in% rownames(model.data))
na.fix.data <- data[which(rownames(data) %in% na.index),] %>%
dplyr::select(all_of(names(model.data)))
model.data <- rbind(model.data, na.fix.data)
model.data <- model.data[order(as.numeric(rownames(model.data))),]
if(include.ls == TRUE){
na.fix.ls <- data.frame(LSR = rep(NA, length(na.index)),
LSF = rep(NA, length(na.index)))
rownames(na.fix.ls) <- na.index
names(na.fix.ls) <- c(names(ls.resid))
ls.resid <- rbind(ls.resid, na.fix.ls)
ls.resid <- ls.resid[order(as.numeric(rownames(ls.resid))),]
}
}
if (include.ls == TRUE) {
return.tbl <- tibble::tibble("id" = as.numeric(rownames(model.data)),
model.data,
eb.resid,
eb.fitted,
ls.resid,
mar.resid,
mar.fitted)
} else {
return.tbl <- tibble::tibble("id" = as.numeric(rownames(model.data)),
model.data,
eb.resid,
eb.fitted,
mar.resid,
mar.fitted)
}
return(return.tbl)
}
if (level %in% names(object$groups)) {
if(standardize == "semi") standardize <- FALSE
if (length(object$groups) != 1) {
eb.resid <- nlme::ranef(object, standard = standardize)[[level]]
} else {
eb.resid <- nlme::ranef(object, standard = standardize)
}
eb.resid <- janitor::clean_names(eb.resid)
groups <- rownames(eb.resid)
if (standardize == TRUE) {
eb.names <- paste0(".std.ranef.", names(eb.resid))
} else {
eb.names <- paste0(".ranef.", names(eb.resid))
}
if (include.ls == TRUE) {
ls.resid <- LSresids(object, level = level, stand = standardize)
ls.resid <- ls.resid[match(groups, ls.resid$group),]
ls.resid <- janitor::clean_names(ls.resid)
if (standardize == TRUE) {
ls.names <- paste0(".std.ls.", names(ls.resid))
} else {
ls.names <- paste0(".ls.", names(ls.resid))
}
}
fixed <- as.character(formula(object))
n.ranefs <- length(names(object$groups))
if (n.ranefs == 1){
ranef_names <- names( nlme::ranef(object) )
} else {
ranef_names <- names( nlme::ranef(object)[[level]] )
}
data <- object$data %>%
dplyr::mutate(dplyr::across(where(is.character), ~ as.factor(.x))) %>%
as.data.frame()
form <- paste(fixed[2], fixed[1], fixed[3], "|", level)
g.list <- suppressWarnings(lme4::lmList(formula(form), data = data))
g.index <- which(purrr::map_lgl(coef(g.list), ~all(is.na(.x))))
g.names <- names(g.index)
interaction.index <- stringr::str_detect(g.names, ":")
g.names <- g.names[!interaction.index]
g.exp <- stringr::str_c(g.names, collapse = "|")
g.index.frame <- which(
stringr::str_detect(g.exp, names(data)))
if(level == names(object$groups)[1]){
g.vars <- data %>%
dplyr::select(all_of(level), all_of(g.index.frame))
g.vars <- unique(g.vars)
if (include.ls == TRUE) {
return.tbl <- suppressMessages(tibble::tibble(
groups, eb.resid, ls.resid[,-1], .name_repair = "universal"))
names(return.tbl) <- c(level, eb.names, ls.names[-1])
if(sum(class(g.vars[level][[1]]) != class(return.tbl[level][[1]])) != 0){
g.vars[level][[1]] <- as.character(g.vars[level][[1]])
return.tbl[level][[1]] <- as.character(return.tbl[level][[1]])
}
return.tbl <- tibble::tibble(
unique(suppressMessages(dplyr::left_join(g.vars, return.tbl))))
} else {
return.tbl <- tibble::tibble(groups, eb.resid)
names(return.tbl) <- c(level, eb.names)
if(sum(class(g.vars[level][[1]]) != class(return.tbl[level][[1]])) != 0){
g.vars[level][[1]] <- as.character(g.vars[level][[1]])
return.tbl[level][[1]] <- as.character(return.tbl[level][[1]])
}
return.tbl <- tibble::tibble(
unique(suppressMessages(dplyr::left_join(g.vars, return.tbl))))
}
return(return.tbl)
} else {
higher.level <- names(object$groups[which(names(object$groups) == level) -1])
g.vars <- data %>%
dplyr::select(all_of(higher.level), all_of(level), all_of(g.index.frame))
g.vars <- unique(g.vars)
g.vars$group <- rep(NA, nrow(g.vars))
for (i in 1:nrow(g.vars)){
g.vars$group[i] <- stringr::str_c(g.vars[higher.level][i,],
g.vars[level][i,], sep = "/")
}
g.vars <- g.vars %>%
dplyr::select(ncol(g.vars), 1:(ncol(g.vars)-1))
if (include.ls == TRUE) {
return.tbl <- suppressMessages(tibble::tibble(
groups, eb.resid, ls.resid[,-1], .name_repair = "universal"))
names(return.tbl) <- c("group", eb.names, ls.names[-1])
return.tbl <- tibble::tibble(
unique(suppressMessages(dplyr::left_join(g.vars, return.tbl))))
} else {
return.tbl <- tibble::tibble(groups, eb.resid)
names(return.tbl) <- c("group", eb.names)
return.tbl <- tibble::tibble(
unique(suppressMessages(dplyr::left_join(g.vars, return.tbl))))
}
return(return.tbl)
}
}
} |
"con2df" <- function(con, Traits){
con <- con[setdiff(names(con), c("lb", "ub", "uniform"))]
if(length(con)==0){
return(data.frame(dir=character(0), var=character(0), val=numeric(0), isLin=logical(0)))
}
dir <- str_sub(names(con),1,2)
var <- str_sub(names(con),4,-1)
if(any(duplicated(var))){
stop("Some variables appear in more than one constraint.\n")
}
for(i in seq_along(con)){
if((!is.numeric(con[[i]])) || length(con[[i]])>1 || is.na(con[[i]])){
stop(paste0("Constraint ", names(con)[i], " must be a numeric value.\n"))
}
if((!(var[i] %in% Traits)) && con[[i]]<0){
stop(paste0("Constraint ", names(con)[i], " must be a positive numeric value.\n"))
}
}
condf <- data.frame(
dir = setNames(c("<=", ">=", "=="), c("ub", "lb", "eq"))[dir],
var = var,
val = unlist(con),
isLin = var %in% Traits,
row.names = var,
stringsAsFactors = FALSE)
return(condf)
} |
sugm.tiger.ladm.scr <- function(data, n, d, maxdf, rho, lambda, shrink, prec, max.ite, verbose){
if(verbose==TRUE)
cat("Tuning-Insensitive Graph Estimation and Regression.\n")
Z = data
rm(data)
ZZ = crossprod(Z)
nlambda = length(lambda)
lambda = lambda-shrink*prec
d1 = d-1
num.scr = d1
if(d1>=n){
if(n<=3){
num.scr1 = n
num.scr2 = n
}else{
num.scr1 = ceiling(n/log(n))
num.scr2 = n-1
}
}else{
if(d1<=3){
num.scr1 = d1
num.scr2 = d1
}else{
num.scr1 = ceiling(sqrt(d1))
num.scr2 = ceiling(d1/log(d1))
}
}
ite.int = matrix(0,nrow=d,ncol=nlambda)
ite.int1 = matrix(0,nrow=d,ncol=nlambda)
ite.int2 = matrix(0,nrow=d,ncol=nlambda)
ite.int3 = matrix(0,nrow=d,ncol=nlambda)
ite.int4 = matrix(0,nrow=d,ncol=nlambda)
ite.int5 = matrix(0,nrow=d,ncol=nlambda)
x = rep(0,d*maxdf*nlambda)
col.cnz = rep(0,d+1)
row.idx = rep(0,d*maxdf*nlambda)
icov.list1 = vector("list", nlambda)
for(i in 1:nlambda){
icov.list1[[i]] = matrix(0,d,d)
}
for(j in 1:d){
Z.j = Z[,j]
Z.resj = Z[,-j]
Zy = ZZ[-j,j]
idx.scr0 = order(Zy)
idx.scr1 = idx.scr0[1:num.scr1]
idx.scr2 = idx.scr0[1:num.scr2]
ZZ0 = ZZ[-j,-j]
Z.order = ZZ0[idx.scr0,idx.scr0]
gamma = max(colSums(abs(Z.order)))
icov0 = rep(0,d*nlambda)
ite0.int = rep(0,nlambda)
ite0.int1 = rep(0,nlambda)
ite0.int2 = rep(0,nlambda)
ite0.int3 = rep(0,nlambda)
ite0.int4 = rep(0,nlambda)
ite0.int5 = rep(0,nlambda)
x0 = rep(0,maxdf*nlambda)
col.cnz0 = 0
row.idx0 = rep(0,maxdf*nlambda)
str=.C("sugm_tiger_ladm_scr", as.double(Z.j), as.double(Z.resj),
as.double(Zy),
as.double(Z.order), as.double(icov0), as.double(x0), as.integer(d),
as.integer(n), as.double(gamma), as.double(lambda), as.integer(nlambda),
as.double(rho), as.integer(col.cnz0), as.integer(row.idx0),
as.integer(ite0.int), as.integer(ite0.int1), as.integer(ite0.int2),
as.integer(ite0.int3), as.integer(ite0.int4), as.integer(ite0.int5),
as.integer(num.scr1), as.integer(num.scr2),
as.integer(idx.scr0), as.integer(idx.scr1), as.integer(idx.scr2),
as.integer(max.ite), as.double(prec), as.integer(j), PACKAGE="flare")
icov = matrix(unlist(str[5]), byrow = FALSE, ncol = nlambda)
for(i in 1:nlambda){
icov.list1[[i]][,j] = icov[,i]
}
cnt = unlist(str[13])
col.cnz[j+1] = cnt+col.cnz[j]
if(cnt>0){
x[(col.cnz[j]+1):col.cnz[j+1]] = unlist(str[6])[1:cnt]
row.idx[(col.cnz[j]+1):col.cnz[j+1]] = unlist(str[14])[1:cnt]
}
ite.int[j,] = unlist(str[15])
ite.int1[j,] = unlist(str[16])
ite.int2[j,] = unlist(str[17])
ite.int3[j,] = unlist(str[18])
ite.int4[j,] = unlist(str[19])
ite.int5[j,] = unlist(str[20])
}
icov.list = vector("list", nlambda)
for(i in 1:nlambda){
icov.i = icov.list1[[i]]
}
ite = list()
ite[[1]] = ite.int1
ite[[2]] = ite.int2
ite[[3]] = ite.int
return(list(icov=icov.list, icov1=icov.list1,ite=ite, x=x[1:col.cnz[d+1]], col.cnz=col.cnz, row.idx=row.idx[1:col.cnz[d+1]]))
} |
model_evaluation_optimization = function(x, source_names, algorithm, correct_topology, lr_network, sig_network, gr_network, settings, secondary_targets = FALSE, remove_direct_links = "no",damping_factor = NULL,...){
requireNamespace("dplyr")
if (!is.null(damping_factor) & is.null(x$damping_factor)){
x$damping_factor = damping_factor
}
if (!is.list(x))
stop("x should be a list!")
if (!is.numeric(x$source_weights))
stop("x$source_weights should be a numeric vector")
if (x$lr_sig_hub < 0 | x$lr_sig_hub > 1)
stop("x$lr_sig_hub must be a number between 0 and 1 (0 and 1 included)")
if (x$gr_hub < 0 | x$gr_hub > 1)
stop("x$gr_hub must be a number between 0 and 1 (0 and 1 included)")
if(is.null(x$ltf_cutoff)){
if( (algorithm == "PPR" | algorithm == "SPL") & correct_topology == FALSE)
warning("Did you not forget to give a value to x$ltf_cutoff?")
} else {
if (x$ltf_cutoff < 0 | x$ltf_cutoff > 1)
stop("x$ltf_cutoff must be a number between 0 and 1 (0 and 1 included)")
}
if(algorithm == "PPR"){
if (x$damping_factor < 0 | x$damping_factor >= 1)
stop("x$damping_factor must be a number between 0 and 1 (0 included, 1 not)")
}
if (algorithm != "PPR" & algorithm != "SPL" & algorithm != "direct")
stop("algorithm must be 'PPR' or 'SPL' or 'direct'")
if (correct_topology != TRUE & correct_topology != FALSE)
stop("correct_topology must be TRUE or FALSE")
if (!is.data.frame(lr_network))
stop("lr_network must be a data frame or tibble object")
if (!is.data.frame(sig_network))
stop("sig_network must be a data frame or tibble object")
if (!is.data.frame(gr_network))
stop("gr_network must be a data frame or tibble object")
if (!is.list(settings))
stop("settings should be a list!")
if(!is.character(settings[[1]]$from) | !is.character(settings[[1]]$name))
stop("setting$from and setting$name should be character vectors")
if(!is.logical(settings[[1]]$response) | is.null(names(settings[[1]]$response)))
stop("setting$response should be named logical vector containing class labels of the response that needs to be predicted ")
if (secondary_targets != TRUE & secondary_targets != FALSE)
stop("secondary_targets must be TRUE or FALSE")
if (remove_direct_links != "no" & remove_direct_links != "ligand" & remove_direct_links != "ligand-receptor")
stop("remove_direct_links must be 'no' or 'ligand' or 'ligand-receptor'")
if(!is.character(source_names))
stop("source_names should be a character vector")
if(length(source_names) != length(x$source_weights))
stop("Length of source_names should be the same as length of x$source_weights")
if(correct_topology == TRUE && !is.null(x$ltf_cutoff))
warning("Because PPR-ligand-target matrix will be corrected for topology, the proposed cutoff on the ligand-tf matrix will be ignored (x$ltf_cutoff")
if(correct_topology == TRUE && algorithm != "PPR")
warning("Topology correction is PPR-specific and makes no sense when the algorithm is not PPR")
names(x$source_weights) = source_names
parameters_setting = list(model_name = "query_design", source_weights = x$source_weights)
if (algorithm == "PPR") {
if (correct_topology == TRUE){
parameters_setting = add_hyperparameters_parameter_settings(parameters_setting, lr_sig_hub = x$lr_sig_hub, gr_hub = x$gr_hub, ltf_cutoff = 0, algorithm = algorithm,damping_factor = x$damping_factor,correct_topology = TRUE)
} else {
parameters_setting = add_hyperparameters_parameter_settings(parameters_setting, lr_sig_hub = x$lr_sig_hub, gr_hub = x$gr_hub, ltf_cutoff = x$ltf_cutoff, algorithm = algorithm,damping_factor = x$damping_factor,correct_topology = FALSE)
}
}
if (algorithm == "SPL" | algorithm == "direct"){
parameters_setting = add_hyperparameters_parameter_settings(parameters_setting, lr_sig_hub = x$lr_sig_hub, gr_hub = x$gr_hub, ltf_cutoff = x$ltf_cutoff, algorithm = algorithm,damping_factor = NULL,correct_topology = FALSE)
}
output_evaluation = evaluate_model(parameters_setting, lr_network, sig_network, gr_network, settings,calculate_popularity_bias_target_prediction = FALSE,calculate_popularity_bias_ligand_prediction=FALSE,ncitations = ncitations, secondary_targets = secondary_targets, remove_direct_links = remove_direct_links, n_target_bins = 3, ...)
ligands_evaluation = settings %>% sapply(function(x){x$from}) %>% unlist() %>% unique()
ligand_activity_performance_setting_summary = output_evaluation$performances_ligand_prediction_single %>% select(-setting, -ligand) %>% group_by(importance_measure) %>% summarise_all(mean) %>% group_by(importance_measure) %>% mutate(geom_average = exp(mean(log(c(auroc,aupr_corrected)))))
best_metric = ligand_activity_performance_setting_summary %>% ungroup() %>% filter(geom_average == max(geom_average)) %>% pull(importance_measure) %>% .[1]
performances_ligand_prediction_single_summary = output_evaluation$performances_ligand_prediction_single %>% filter(importance_measure == best_metric)
performances_target_prediction_averaged = ligands_evaluation %>% lapply(function(x){x}) %>%
lapply(wrapper_average_performances, output_evaluation$performances_target_prediction,"median") %>% bind_rows() %>% drop_na()
performances_ligand_prediction_single_summary_averaged = ligands_evaluation %>% lapply(function(x){x}) %>%
lapply(wrapper_average_performances, performances_ligand_prediction_single_summary %>% select(-importance_measure),"median") %>% bind_rows() %>% drop_na()
mean_auroc_target_prediction = performances_target_prediction_averaged$auroc %>% mean(na.rm = TRUE) %>% unique()
mean_aupr_target_prediction = performances_target_prediction_averaged$aupr_corrected %>% mean(na.rm = TRUE) %>% unique()
median_auroc_ligand_prediction = performances_ligand_prediction_single_summary_averaged$auroc %>% median(na.rm = TRUE) %>% unique()
median_aupr_ligand_prediction = performances_ligand_prediction_single_summary_averaged$aupr_corrected %>% median(na.rm = TRUE) %>% unique()
return(c(mean_auroc_target_prediction, mean_aupr_target_prediction, median_auroc_ligand_prediction, median_aupr_ligand_prediction))
}
mlrmbo_optimization = function(run_id,obj_fun,niter,ncores,nstart,additional_arguments){
requireNamespace("mlrMBO")
requireNamespace("parallelMap")
requireNamespace("dplyr")
if (length(run_id) != 1)
stop("run_id should be a vector of length 1")
if(!is.function(obj_fun) | !is.list(attributes(obj_fun)$par.set$pars))
stop("obj_fun should be a function (and generated by mlrMBO::makeMultiObjectiveFunction)")
if(niter <= 0)
stop("niter should be a number higher than 0")
if(ncores <= 0)
stop("ncores should be a number higher than 0")
nparams = attributes(obj_fun)$par.set$pars %>% lapply(function(x){x$len}) %>% unlist() %>% sum()
if(nstart < nparams)
stop("nstart should be equal or larger than the number of parameters")
if (!is.list(additional_arguments))
stop("additional_arguments should be a list!")
ctrl = makeMBOControl(n.objectives = attributes(obj_fun) %>% .$n.objectives, propose.points = ncores)
ctrl = setMBOControlMultiObj(ctrl, method = "dib",dib.indicator = "sms")
ctrl = setMBOControlInfill(ctrl, crit = makeMBOInfillCritDIB())
ctrl = setMBOControlMultiPoint(ctrl, method = "cb")
ctrl = setMBOControlTermination(ctrl, iters = niter)
design = generateDesign(n = nstart, par.set = getParamSet(obj_fun))
configureMlr(on.learner.warning = "quiet", show.learner.output = FALSE)
parallelStartMulticore(cpus = ncores, show.info = TRUE)
surr.rf = makeLearner("regr.km", predict.type = "se")
print(design)
print(ctrl)
res = mbo(obj_fun, design = design, learner = surr.rf ,control = ctrl, show.info = TRUE, more.args = additional_arguments)
parallelStop()
return(res)
}
model_evaluation_hyperparameter_optimization = function(x, source_weights, algorithm, correct_topology, lr_network, sig_network, gr_network, settings, secondary_targets = FALSE, remove_direct_links = "no",damping_factor = NULL,...){
requireNamespace("dplyr")
if (!is.null(damping_factor) & is.null(x$damping_factor)){
x$damping_factor = damping_factor
}
if (!is.list(x))
stop("x should be a list!")
if (x$lr_sig_hub < 0 | x$lr_sig_hub > 1)
stop("x$lr_sig_hub must be a number between 0 and 1 (0 and 1 included)")
if (x$gr_hub < 0 | x$gr_hub > 1)
stop("x$gr_hub must be a number between 0 and 1 (0 and 1 included)")
if(is.null(x$ltf_cutoff)){
if( (algorithm == "PPR" | algorithm == "SPL") & correct_topology == FALSE)
warning("Did you not forget to give a value to x$ltf_cutoff?")
} else {
if (x$ltf_cutoff < 0 | x$ltf_cutoff > 1)
stop("x$ltf_cutoff must be a number between 0 and 1 (0 and 1 included)")
}
if (!is.numeric(source_weights) | is.null(names(source_weights)))
stop("source_weights should be a named numeric vector")
if(algorithm == "PPR"){
if (x$damping_factor < 0 | x$damping_factor >= 1)
stop("x$damping_factor must be a number between 0 and 1 (0 included, 1 not)")
}
if (algorithm != "PPR" & algorithm != "SPL" & algorithm != "direct")
stop("algorithm must be 'PPR' or 'SPL' or 'direct'")
if (correct_topology != TRUE & correct_topology != FALSE)
stop("correct_topology must be TRUE or FALSE")
if (!is.data.frame(lr_network))
stop("lr_network must be a data frame or tibble object")
if (!is.data.frame(sig_network))
stop("sig_network must be a data frame or tibble object")
if (!is.data.frame(gr_network))
stop("gr_network must be a data frame or tibble object")
if (!is.list(settings))
stop("settings should be a list!")
if(!is.character(settings[[1]]$from) | !is.character(settings[[1]]$name))
stop("setting$from and setting$name should be character vectors")
if(!is.logical(settings[[1]]$response) | is.null(names(settings[[1]]$response)))
stop("setting$response should be named logical vector containing class labels of the response that needs to be predicted ")
if (secondary_targets != TRUE & secondary_targets != FALSE)
stop("secondary_targets must be TRUE or FALSE")
if (remove_direct_links != "no" & remove_direct_links != "ligand" & remove_direct_links != "ligand-receptor")
stop("remove_direct_links must be 'no' or 'ligand' or 'ligand-receptor'")
if(correct_topology == TRUE && !is.null(x$ltf_cutoff))
warning("Because PPR-ligand-target matrix will be corrected for topology, the proposed cutoff on the ligand-tf matrix will be ignored (x$ltf_cutoff")
if(correct_topology == TRUE && algorithm != "PPR")
warning("Topology correction is PPR-specific and makes no sense when the algorithm is not PPR")
parameters_setting = list(model_name = "query_design", source_weights = source_weights)
if (algorithm == "PPR") {
if (correct_topology == TRUE){
parameters_setting = add_hyperparameters_parameter_settings(parameters_setting, lr_sig_hub = x$lr_sig_hub, gr_hub = x$gr_hub, ltf_cutoff = 0, algorithm = algorithm,damping_factor = x$damping_factor,correct_topology = TRUE)
} else {
parameters_setting = add_hyperparameters_parameter_settings(parameters_setting, lr_sig_hub = x$lr_sig_hub, gr_hub = x$gr_hub, ltf_cutoff = x$ltf_cutoff, algorithm = algorithm,damping_factor = x$damping_factor,correct_topology = FALSE)
}
}
if (algorithm == "SPL" | algorithm == "direct"){
parameters_setting = add_hyperparameters_parameter_settings(parameters_setting, lr_sig_hub = x$lr_sig_hub, gr_hub = x$gr_hub, ltf_cutoff = x$ltf_cutoff, algorithm = algorithm,damping_factor = NULL,correct_topology = FALSE)
}
output_evaluation = evaluate_model(parameters_setting, lr_network, sig_network, gr_network, settings,calculate_popularity_bias_target_prediction = FALSE,calculate_popularity_bias_ligand_prediction=FALSE,ncitations = ncitations, secondary_targets = secondary_targets, remove_direct_links = remove_direct_links, n_target_bins = 3, ...)
ligands_evaluation = settings %>% sapply(function(x){x$from}) %>% unlist() %>% unique()
ligand_activity_performance_setting_summary = output_evaluation$performances_ligand_prediction_single %>% select(-setting, -ligand) %>% group_by(importance_measure) %>% summarise_all(mean) %>% group_by(importance_measure) %>% mutate(geom_average = exp(mean(log(c(auroc,aupr_corrected)))))
best_metric = ligand_activity_performance_setting_summary %>% ungroup() %>% filter(geom_average == max(geom_average)) %>% pull(importance_measure) %>% .[1]
performances_ligand_prediction_single_summary = output_evaluation$performances_ligand_prediction_single %>% filter(importance_measure == best_metric)
performances_target_prediction_averaged = ligands_evaluation %>% lapply(function(x){x}) %>%
lapply(wrapper_average_performances, output_evaluation$performances_target_prediction,"median") %>% bind_rows() %>% drop_na()
performances_ligand_prediction_single_summary_averaged = ligands_evaluation %>% lapply(function(x){x}) %>%
lapply(wrapper_average_performances, performances_ligand_prediction_single_summary %>% select(-importance_measure),"median") %>% bind_rows() %>% drop_na()
mean_auroc_target_prediction = performances_target_prediction_averaged$auroc %>% mean(na.rm = TRUE) %>% unique()
mean_aupr_target_prediction = performances_target_prediction_averaged$aupr_corrected %>% mean(na.rm = TRUE) %>% unique()
median_auroc_ligand_prediction = performances_ligand_prediction_single_summary_averaged$auroc %>% median(na.rm = TRUE) %>% unique()
median_aupr_ligand_prediction = performances_ligand_prediction_single_summary_averaged$aupr_corrected %>% median(na.rm = TRUE) %>% unique()
return(c(mean_auroc_target_prediction, mean_aupr_target_prediction, median_auroc_ligand_prediction, median_aupr_ligand_prediction))
}
process_mlrmbo_nichenet_optimization = function(optimization_results,source_names,parameter_set_index = NULL){
requireNamespace("dplyr")
requireNamespace("tibble")
if(length(optimization_results) == 1){
optimization_results = optimization_results[[1]]
}
if (!is.list(optimization_results))
stop("optimization_results should be a list!")
if (!is.list(optimization_results$pareto.set))
stop("optimization_results$pareto.set should be a list! Are you sure you provided the output of mlrMBO::mbo (multi-objective)?")
if (!is.matrix(optimization_results$pareto.front))
stop("optimization_results$pareto.front should be a matrix! Are you sure you provided the output of mlrMBO::mbo (multi-objective?")
if (!is.character(source_names))
stop("source_names should be a character vector")
if(!is.numeric(parameter_set_index) & !is.null(parameter_set_index))
stop("parameter_set_index should be a number or NULL")
if(is.null(parameter_set_index)){
parameter_set_index = optimization_results$pareto.front %>% as_tibble() %>% mutate(average = apply(.,1,function(x){exp(mean(log(x)))}), index = seq(nrow(.))) %>% filter(average == max(average)) %>% .$index
}
if(parameter_set_index > nrow(optimization_results$pareto.front))
stop("parameter_set_index may not be a number higher than the total number of proposed solutions")
parameter_set = optimization_results$pareto.set[[parameter_set_index]]
source_weights = parameter_set$source_weights
names(source_weights) = source_names
lr_sig_hub = parameter_set$lr_sig_hub
gr_hub = parameter_set$gr_hub
ltf_cutoff = parameter_set$ltf_cutoff
damping_factor = parameter_set$damping_factor
source_weight_df = tibble(source = names(source_weights), weight = source_weights)
output_optimization = list(source_weight_df = source_weight_df, lr_sig_hub = lr_sig_hub, gr_hub = gr_hub,ltf_cutoff = ltf_cutoff, damping_factor = damping_factor)
return(output_optimization)
}
model_evaluation_optimization_application = function(x, source_names, algorithm, correct_topology, lr_network, sig_network, gr_network, settings, secondary_targets = FALSE, remove_direct_links = "no",classification_algorithm = "lda",damping_factor = NULL,...){
requireNamespace("dplyr")
if (!is.null(damping_factor) & is.null(x$damping_factor)){
x$damping_factor = damping_factor
}
if (!is.list(x))
stop("x should be a list!")
if (!is.numeric(x$source_weights))
stop("x$source_weights should be a numeric vector")
if (x$lr_sig_hub < 0 | x$lr_sig_hub > 1)
stop("x$lr_sig_hub must be a number between 0 and 1 (0 and 1 included)")
if (x$gr_hub < 0 | x$gr_hub > 1)
stop("x$gr_hub must be a number between 0 and 1 (0 and 1 included)")
if(is.null(x$ltf_cutoff)){
if( (algorithm == "PPR" | algorithm == "SPL") & correct_topology == FALSE)
warning("Did you not forget to give a value to x$ltf_cutoff?")
} else {
if (x$ltf_cutoff < 0 | x$ltf_cutoff > 1)
stop("x$ltf_cutoff must be a number between 0 and 1 (0 and 1 included)")
}
if(algorithm == "PPR"){
if (x$damping_factor < 0 | x$damping_factor >= 1)
stop("x$damping_factor must be a number between 0 and 1 (0 included, 1 not)")
}
if (algorithm != "PPR" & algorithm != "SPL" & algorithm != "direct")
stop("algorithm must be 'PPR' or 'SPL' or 'direct'")
if (correct_topology != TRUE & correct_topology != FALSE)
stop("correct_topology must be TRUE or FALSE")
if (!is.data.frame(lr_network))
stop("lr_network must be a data frame or tibble object")
if (!is.data.frame(sig_network))
stop("sig_network must be a data frame or tibble object")
if (!is.data.frame(gr_network))
stop("gr_network must be a data frame or tibble object")
if (!is.list(settings))
stop("settings should be a list!")
if(!is.character(settings[[1]]$from) | !is.character(settings[[1]]$name))
stop("setting$from and setting$name should be character vectors")
if(!is.logical(settings[[1]]$response) | is.null(names(settings[[1]]$response)))
stop("setting$response should be named logical vector containing class labels of the response that needs to be predicted ")
if (secondary_targets != TRUE & secondary_targets != FALSE)
stop("secondary_targets must be TRUE or FALSE")
if (remove_direct_links != "no" & remove_direct_links != "ligand" & remove_direct_links != "ligand-receptor")
stop("remove_direct_links must be 'no' or 'ligand' or 'ligand-receptor'")
if(!is.character(source_names))
stop("source_names should be a character vector")
if(length(source_names) != length(x$source_weights))
stop("Length of source_names should be the same as length of x$source_weights")
if(correct_topology == TRUE && !is.null(x$ltf_cutoff))
warning("Because PPR-ligand-target matrix will be corrected for topology, the proposed cutoff on the ligand-tf matrix will be ignored (x$ltf_cutoff")
if(correct_topology == TRUE && algorithm != "PPR")
warning("Topology correction is PPR-specific and makes no sense when the algorithm is not PPR")
if(!is.character(classification_algorithm))
stop("classification_algorithm should be a character vector of length 1")
names(x$source_weights) = source_names
parameters_setting = list(model_name = "query_design", source_weights = x$source_weights)
if (algorithm == "PPR") {
if (correct_topology == TRUE){
parameters_setting = add_hyperparameters_parameter_settings(parameters_setting, lr_sig_hub = x$lr_sig_hub, gr_hub = x$gr_hub, ltf_cutoff = 0, algorithm = algorithm,damping_factor = x$damping_factor,correct_topology = TRUE)
} else {
parameters_setting = add_hyperparameters_parameter_settings(parameters_setting, lr_sig_hub = x$lr_sig_hub, gr_hub = x$gr_hub, ltf_cutoff = x$ltf_cutoff, algorithm = algorithm,damping_factor = x$damping_factor,correct_topology = FALSE)
}
}
if (algorithm == "SPL" | algorithm == "direct"){
parameters_setting = add_hyperparameters_parameter_settings(parameters_setting, lr_sig_hub = x$lr_sig_hub, gr_hub = x$gr_hub, ltf_cutoff = x$ltf_cutoff, algorithm = algorithm,damping_factor = NULL,correct_topology = FALSE)
}
output_evaluation = evaluate_model_application_multi_ligand(parameters_setting, lr_network, sig_network, gr_network, settings, secondary_targets = secondary_targets, remove_direct_links = remove_direct_links, classification_algorithm = classification_algorithm,...)
mean_auroc_target_prediction = output_evaluation$performances_target_prediction$auroc %>% mean()
mean_aupr_target_prediction = output_evaluation$performances_target_prediction$aupr_corrected %>% mean()
return(c(mean_auroc_target_prediction, mean_aupr_target_prediction))
}
estimate_source_weights_characterization = function(loi_performances,loo_performances,source_weights_df, sources_oi, random_forest =FALSE){
requireNamespace("dplyr")
requireNamespace("tibble")
if(!is.data.frame(loi_performances))
stop("loi_performances should be a data frame")
if(!is.character(loi_performances$model_name))
stop("loi_performances$model_name should be a character vector")
if(!is.data.frame(loo_performances))
stop("loo_performances should be a data frame")
if(!is.character(loo_performances$model_name))
stop("loo_performances$model_name should be a character vector")
if (!is.data.frame(source_weights_df) || sum((source_weights_df$weight > 1)) != 0)
stop("source_weights_df must be a data frame or tibble object and no data source weight may be higher than 1")
if(!is.character(sources_oi))
stop("sources_oi should be a character vector")
if(random_forest != TRUE & random_forest != FALSE)
stop("random_forest should be TRUE or FALSE")
loi_performances_train = loi_performances %>% filter((model_name %in% sources_oi) == FALSE)
loo_performances_train = loo_performances %>% filter((model_name %in% sources_oi) == FALSE)
loi_performances_test = loi_performances %>% filter(model_name == "complete_model" | (model_name %in% sources_oi))
loo_performances_test = loo_performances %>% filter(model_name == "complete_model" | (model_name %in% sources_oi))
output_regression_model = regression_characterization_optimization(loi_performances_train, loo_performances_train, source_weights_df, random_forest = random_forest)
new_source_weight_df = assign_new_weight(loi_performances_test, loo_performances_test,output_regression_model,source_weights_df)
return(list(source_weights_df = new_source_weight_df, model = output_regression_model))
}
evaluate_model_cv = function(parameters_setting, lr_network, sig_network, gr_network, settings,secondary_targets = FALSE, remove_direct_links = "no", ...){
requireNamespace("dplyr")
if (!is.list(parameters_setting))
stop("parameters_setting should be a list!")
if (!is.character(parameters_setting$model_name))
stop("parameters_setting$model_name should be a character vector")
if (!is.numeric(parameters_setting$source_weights) | is.null(names(parameters_setting$source_weights)))
stop("parameters_setting$source_weights should be a named numeric vector")
if (parameters_setting$lr_sig_hub < 0 | parameters_setting$lr_sig_hub > 1)
stop("parameters_setting$lr_sig_hub must be a number between 0 and 1 (0 and 1 included)")
if (parameters_setting$gr_hub < 0 | parameters_setting$gr_hub > 1)
stop("parameters_setting$gr_hub must be a number between 0 and 1 (0 and 1 included)")
if(is.null(parameters_setting$ltf_cutoff)){
if( parameters_setting$algorithm == "PPR" | parameters_setting$algorithm == "SPL" )
warning("Did you not forget to give a value to parameters_setting$ltf_cutoff?")
} else {
if (parameters_setting$ltf_cutoff < 0 | parameters_setting$ltf_cutoff > 1)
stop("parameters_setting$ltf_cutoff must be a number between 0 and 1 (0 and 1 included)")
}
if (parameters_setting$algorithm != "PPR" & parameters_setting$algorithm != "SPL" & parameters_setting$algorithm != "direct")
stop("parameters_setting$algorithm must be 'PPR' or 'SPL' or 'direct'")
if(parameters_setting$algorithm == "PPR"){
if (parameters_setting$damping_factor < 0 | parameters_setting$damping_factor >= 1)
stop("parameters_setting$damping_factor must be a number between 0 and 1 (0 included, 1 not)")
}
if (parameters_setting$correct_topology != TRUE & parameters_setting$correct_topology != FALSE)
stop("parameters_setting$correct_topology must be TRUE or FALSE")
if (!is.data.frame(lr_network))
stop("lr_network must be a data frame or tibble object")
if (!is.data.frame(sig_network))
stop("sig_network must be a data frame or tibble object")
if (!is.data.frame(gr_network))
stop("gr_network must be a data frame or tibble object")
if (!is.list(settings))
stop("settings should be a list!")
if(!is.character(settings[[1]]$from) | !is.character(settings[[1]]$name))
stop("setting$from and setting$name should be character vectors")
if(!is.logical(settings[[1]]$response) | is.null(names(settings[[1]]$response)))
stop("setting$response should be named logical vector containing class labels of the response that needs to be predicted ")
if (secondary_targets != TRUE & secondary_targets != FALSE)
stop("secondary_targets must be TRUE or FALSE")
if (remove_direct_links != "no" & remove_direct_links != "ligand" & remove_direct_links != "ligand-receptor")
stop("remove_direct_links must be 'no' or 'ligand' or 'ligand-receptor'")
ligands = extract_ligands_from_settings(settings)
output_model_construction = construct_model(parameters_setting, lr_network, sig_network, gr_network, ligands, secondary_targets = secondary_targets, remove_direct_links = remove_direct_links)
model_name = output_model_construction$model_name
ligand_target_matrix = output_model_construction$model
ligands_zero = ligand_target_matrix %>% colnames() %>% sapply(function(ligand){sum(ligand_target_matrix[,ligand]) == 0}) %>% .[. == TRUE]
if (length(ligands_zero > 0)){
noisy_target_scores = runif(nrow(ligand_target_matrix), min = 0, max = min(ligand_target_matrix[ligand_target_matrix>0]))
ligand_target_matrix[,names(ligands_zero)] = noisy_target_scores
}
performances_target_prediction = bind_rows(lapply(settings,evaluate_target_prediction, ligand_target_matrix))
all_ligands = unlist(extract_ligands_from_settings(settings, combination = FALSE))
settings_ligand_pred = convert_settings_ligand_prediction(settings, all_ligands, validation = TRUE, single = TRUE)
ligand_importances = bind_rows(lapply(settings_ligand_pred, get_single_ligand_importances, ligand_target_matrix[, all_ligands]))
ligand_importances$pearson[is.na(ligand_importances$pearson)] = 0
ligand_importances$spearman[is.na(ligand_importances$spearman)] = 0
ligand_importances$pearson_log_pval[is.na(ligand_importances$pearson_log_pval)] = 0
ligand_importances$spearman_log_pval[is.na(ligand_importances$spearman_log_pval)] = 0
ligand_importances$mean_rank_GST_log_pval[is.na(ligand_importances$mean_rank_GST_log_pval)] = 0
ligand_importances$pearson_log_pval[is.infinite(ligand_importances$pearson_log_pval)] = 10000
ligand_importances$spearman_log_pval[is.infinite(ligand_importances$spearman_log_pval)] = 10000
ligand_importances$mean_rank_GST_log_pval[is.infinite(ligand_importances$mean_rank_GST_log_pval)] = 10000
all_importances = ligand_importances %>% select_if(.predicate = function(x){sum(is.na(x)) == 0})
performances_ligand_prediction_single = all_importances$setting %>% unique() %>% lapply(function(x){x}) %>%
lapply(wrapper_evaluate_single_importances_ligand_prediction,all_importances) %>%
bind_rows() %>% inner_join(all_importances %>% distinct(setting,ligand))
return(list(performances_target_prediction = performances_target_prediction, importances_ligand_prediction = all_importances, performances_ligand_prediction_single = performances_ligand_prediction_single))
} |
listCaches = function(cacheSubDir="") {
cacheDirFiles = list.files(paste0(getCacheDir(), cacheSubDir))
cacheDirFiles[which(sapply(cacheDirFiles, function(f) endsWith(f, ".RData")))]
} |
script='mqm_listeria1'
library(qtl)
data(listeria)
augmentedcross <- mqmaugment(listeria, minprob=1.0)
result <- mqmscan(augmentedcross)
sink(paste('regression/',script,'.rnew',sep=''))
result
sink()
cat(script,'successful') |
ContinuousProximities<- function(x, y=NULL, ysup=FALSE, transpose=FALSE, coef = "Pythagorean", r = 1) {
distances = c("Pythagorean", "Taxonomic", "City", "Minkowski", "Divergence", "dif_sum", "Camberra", "Bray_Curtis", "Soergel", "Ware_Hedges", "Gower")
if (is.numeric(coef)) coef = distances[coef]
if (!is.null(y)){
if (!(ncol(x)==ncol(y))) stop("Columns don't match")
}
Type="dissimilarity"
if (is.null(y)) {Shape="Squared"}
else{
if (ysup) Shape="Squared"
else Shape="Rectagular"}
result= list()
result$TypeData="Continuous"
result$Type=Type
result$Coefficient=coef
result$Data=x
result$SupData=y
result$r=r
if ((!is.null(y) & (!ysup)))
result$Proximities=ContinuousDistances(x, y, coef = coef, r = r)
else
result$Proximities=SymmetricContinuousDistances(x, coef = coef, r = r)
result$SupProximities=NULL
if (!is.null(y) & (ysup)) result$SupProximities=ContinuousDistances(x, y, coef = coef, r = r)
class(result)="proximities"
return(result)
} |
blrm_exnex <- function(formula,
data,
prior_EX_mu_mean_comp,
prior_EX_mu_sd_comp,
prior_EX_tau_mean_comp,
prior_EX_tau_sd_comp,
prior_EX_corr_eta_comp,
prior_EX_mu_mean_inter,
prior_EX_mu_sd_inter,
prior_EX_tau_mean_inter,
prior_EX_tau_sd_inter,
prior_EX_corr_eta_inter,
prior_is_EXNEX_inter,
prior_is_EXNEX_comp,
prior_EX_prob_comp,
prior_EX_prob_inter,
prior_NEX_mu_mean_comp,
prior_NEX_mu_sd_comp,
prior_NEX_mu_mean_inter,
prior_NEX_mu_sd_inter,
prior_tau_dist,
iter=getOption("OncoBayes2.MC.iter" , 2000),
warmup=getOption("OncoBayes2.MC.warmup", 1000),
save_warmup=getOption("OncoBayes2.MC.save_warmup", TRUE),
thin=getOption("OncoBayes2.MC.thin", 1),
init=getOption("OncoBayes2.MC.init", 0.5),
chains=getOption("OncoBayes2.MC.chains", 4),
cores=getOption("mc.cores", 1L),
control=getOption("OncoBayes2.MC.control", list()),
prior_PD=FALSE,
verbose=FALSE
)
{
call <- match.call()
if (missing(data))
data <- environment(formula)
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data", "na.action"), names(mf), 0)
mf <- mf[c(1, m)]
f <- Formula::Formula(formula)
mf[[1]] <- as.name("model.frame")
mf$formula <- f
mf <- eval(mf, parent.frame())
num_rhs_terms <- length(f)[2]
idx_group_term <- num_rhs_terms
has_inter <- TRUE
idx_inter_term <- num_rhs_terms-1
mt <- attr(mf, "terms")
for (i in seq_len(num_rhs_terms)) {
tc <- terms(f, rhs=i)
nt <- length(tc)-1
if(nt == 2 && attr(tc, "intercept") == 1 )
num_comp <- i
else
break
}
if (num_comp == 1) {
has_inter <- FALSE
idx_inter_term <- 0
}
assert_that(length(f)[1] == 1)
for (i in seq_len(num_comp))
assert_that(attr(terms(f, rhs=i), "intercept") == 1, msg="Intercept must be present for all components.")
if(has_inter)
assert_that(attr(terms(f, rhs=idx_inter_term), "intercept") == 0, msg="No intercept must be present for the interaction model.")
y <- model.response(mf)
assert_matrix(y, ncols=2, any.missing=FALSE)
nr <- array(y[,2])
r <- array(y[,1])
n <- r + nr
num_obs <- length(r)
group_index_term <- model.part(f, data = mf, rhs = idx_group_term)
if(ncol(group_index_term) > 2)
stop("Grouping factor must have at most two terms (study index and optionally a stratum).")
if(ncol(group_index_term) == 0)
stop("Grouping factor must have at least one term (study index).")
if(ncol(group_index_term) == 2) {
idx_group_index <- 2
idx_strata_index <- 1
} else {
idx_group_index <- 1
idx_strata_index <- NA
}
group_fct <- group_index_term[,idx_group_index]
if(!is.factor(group_fct))
group_fct <- factor(group_index)
group_index <- as.integer(unclass(group_fct))
num_groups <- nlevels(group_fct)
assert_that(NROW(group_index) == num_obs)
if(is.na(idx_strata_index)) {
strata_fct <- rep(1, num_obs)
} else {
strata_fct <- group_index_term[,idx_strata_index]
}
if(!is.factor(strata_fct))
strata_fct <- factor(strata_fct)
strata_index <- array(as.integer(unclass(strata_fct)))
num_strata <- nlevels(strata_fct)
assert_that(NROW(strata_index) == num_obs)
.validate_group_stratum_nesting(group_index, strata_index)
group_strata <- data.frame(group_index=seq_len(num_groups)) %>%
left_join(unique(data.frame(group_index=group_index, strata_index=strata_index)), by="group_index")
if(any(is.na(group_strata$strata_index))) {
group_strata_undef <- which(is.na(group_strata$strata_index))
message("Info: The group(s) ", paste(levels(group_fct)[group_strata_undef], collapse=", "), " have undefined strata. Assigning first stratum ", levels(strata_fct)[1], ".")
group_strata$strata_index[is.na(group_strata$strata_index)] <- 1
}
group_index <- array(group_index)
X <- .get_X(f, mf, num_comp, has_inter, idx_inter_term)
X_comp <- X$comp
X_comp_cols <- X$comp_cols
X_inter <- X$inter
num_inter <- ncol(X_inter)
has_inter <- num_inter > 0
assert_matrix(prior_EX_mu_mean_comp, any.missing=FALSE, nrows=num_comp, ncols=2)
assert_matrix(prior_EX_mu_sd_comp, any.missing=FALSE, nrows=num_comp, ncols=2)
if(num_strata == 1) {
if (is.matrix(prior_EX_tau_mean_comp))
prior_EX_tau_mean_comp <- array(prior_EX_tau_mean_comp, c(1, dim(prior_EX_tau_mean_comp)))
if (is.matrix(prior_EX_tau_sd_comp))
prior_EX_tau_sd_comp <- array(prior_EX_tau_sd_comp, c(1, dim(prior_EX_tau_sd_comp)))
}
assert_array(prior_EX_tau_mean_comp, any.missing=FALSE, d=3)
assert_array(prior_EX_tau_sd_comp, any.missing=FALSE, d=3)
assert_that(all(dim(prior_EX_tau_mean_comp) == c(num_strata, num_comp, 2)),
msg="prior_EX_tau_mean_comp must have dimensionality of num_strata x num_comp x 2.\nIn case of only one stratum a matrix of num_comp x 2 is sufficient.")
assert_that(all(dim(prior_EX_tau_sd_comp) == c(num_strata, num_comp, 2)),
msg="prior_EX_tau_sd_comp must have dimensionality of num_strata x num_comp x 2.\nIn case of only one stratum a matrix of num_comp x 2 is sufficient.")
if(missing(prior_EX_corr_eta_comp))
prior_EX_corr_eta_comp <- rep(1.0, times=num_comp)
assert_numeric(prior_EX_corr_eta_comp, lower=0, finite=TRUE, any.missing=FALSE, len=num_comp)
if(!has_inter & missing(prior_EX_mu_mean_inter)) {
prior_EX_mu_mean_inter <- array(0, dim=0)
}
if(!has_inter & missing(prior_EX_mu_sd_inter)) {
prior_EX_mu_sd_inter <- array(0, dim=0)
}
assert_numeric(prior_EX_mu_mean_inter, any.missing=FALSE, len=num_inter)
assert_numeric(prior_EX_mu_sd_inter, any.missing=FALSE, len=num_inter, lower=0)
if(!has_inter & missing(prior_EX_tau_mean_inter)) {
prior_EX_tau_mean_inter <- matrix(1, nrow=num_strata, ncol=num_inter)
}
if(!has_inter & missing(prior_EX_tau_sd_inter)) {
prior_EX_tau_sd_inter <- matrix(1, nrow=num_strata, ncol=num_inter)
}
assert_matrix(prior_EX_tau_mean_inter, any.missing=FALSE, nrows=num_strata, ncols=num_inter)
assert_matrix(prior_EX_tau_sd_inter, any.missing=FALSE, nrows=num_strata, ncols=num_inter)
if(!has_inter & missing(prior_EX_prob_inter)) {
prior_EX_prob_inter <- matrix(1, nrow=num_groups, ncol=num_inter)
}
assert_matrix(prior_EX_prob_comp, any.missing=FALSE, nrows=num_groups, ncols=num_comp)
assert_matrix(prior_EX_prob_inter, any.missing=FALSE, nrows=num_groups, ncols=num_inter)
if(missing(prior_EX_corr_eta_inter))
prior_EX_corr_eta_inter <- 1.0
assert_number(prior_EX_corr_eta_inter, lower=0, finite=TRUE)
if(missing(prior_NEX_mu_mean_comp))
prior_NEX_mu_mean_comp <- prior_EX_mu_mean_comp
if(missing(prior_NEX_mu_sd_comp))
prior_NEX_mu_sd_comp <- prior_EX_mu_sd_comp
assert_matrix(prior_NEX_mu_mean_comp, any.missing=FALSE, nrows=num_comp, ncols=2)
assert_matrix(prior_NEX_mu_sd_comp, any.missing=FALSE, nrows=num_comp, ncols=2)
if(missing(prior_NEX_mu_mean_inter))
prior_NEX_mu_mean_inter <- prior_EX_mu_mean_inter
if(missing(prior_NEX_mu_sd_inter))
prior_NEX_mu_sd_inter <- prior_EX_mu_sd_inter
assert_numeric(prior_NEX_mu_mean_inter, any.missing=FALSE, len=num_inter)
assert_numeric(prior_NEX_mu_sd_inter, any.missing=FALSE, len=num_inter, lower=0)
if(missing(prior_is_EXNEX_comp)) {
prior_is_EXNEX_comp <- apply(prior_EX_prob_comp < 1, 2, any)
} else {
assert_that(
!any(!prior_is_EXNEX_comp & apply(prior_EX_prob_comp < 1, 2, any)),
msg = paste("At least one drug component has",
"prior_is_ENXEX_comp = FALSE, but",
"prior_EX_prob_comp < 1 for one or more group_id's.",
"For these component(s), if an EXNEX prior is desired",
"set prior_is_EXNEX_comp = TRUE. Otherwise, if a",
"fully exchangeable prior is desired, set",
"prior_is_EX_prob_comp = 1.")
)
if(any((prior_is_EXNEX_comp & apply(prior_EX_prob_comp == 1, 2, all)))) {
warning(paste("At least one drug component has",
"prior_is_ENXEX_comp = TRUE, but",
"prior_EX_prob_comp = 1 for every group_id.",
"The sampler will be more efficient if",
"prior_is_EXNEX_comp is set to FALSE for those",
"component(s)."))
}
}
if(missing(prior_is_EXNEX_inter)) {
prior_is_EXNEX_inter <- apply(prior_EX_prob_inter < 1, 2, any)
} else {
assert_that(
!any(!prior_is_EXNEX_inter & apply(prior_EX_prob_inter < 1, 2, any)),
msg=paste("At least one drug component has",
"prior_is_ENXEX_inter = FALSE, but",
"prior_EX_prob_inter < 1 for one or more group_id's.",
"For these interaction(s), if an EXNEX prior is desired",
"set prior_is_EXNEX_inter = TRUE. Otherwise, if a",
"fully exchangeable prior is desired, set",
"prior_is_EX_prob_inter = 1.")
)
if(any((prior_is_EXNEX_inter & apply(prior_EX_prob_inter == 1, 2, all)))) {
warning(paste("At least one interaction prior has",
"prior_is_ENXEX_inter = TRUE, but",
"prior_EX_prob_inter = 1 for every group_id.",
"The sampler will be more efficient if",
"prior_is_EXNEX_inter is set to FALSE for those",
"interaction(s)."))
}
}
assert_logical(prior_is_EXNEX_comp, any.missing=FALSE, len=num_comp)
assert_logical(prior_is_EXNEX_inter, any.missing=FALSE, len=num_inter)
assert_number(prior_tau_dist, lower=0, upper=2)
assert_logical(prior_PD, any.missing=FALSE, len=1)
stan_data <- list(
num_obs=num_obs,
r=r,
nr=nr,
num_comp=num_comp,
num_inter=num_inter,
X_comp=X_comp,
X_inter=X_inter,
num_groups=num_groups,
num_strata=num_strata,
group=group_index,
stratum=strata_index,
group_stratum_cid=array(group_strata$strata_index),
prior_tau_dist = prior_tau_dist,
prior_EX_prob_comp=prior_EX_prob_comp,
prior_EX_prob_inter=prior_EX_prob_inter,
prior_EX_mu_mean_comp=prior_EX_mu_mean_comp,
prior_EX_mu_sd_comp=prior_EX_mu_sd_comp,
prior_EX_tau_mean_comp=prior_EX_tau_mean_comp,
prior_EX_tau_sd_comp=prior_EX_tau_sd_comp,
prior_EX_corr_eta_comp=array(prior_EX_corr_eta_comp, num_comp),
prior_EX_mu_mean_inter=array(prior_EX_mu_mean_inter, num_inter),
prior_EX_mu_sd_inter=array(prior_EX_mu_sd_inter, num_inter),
prior_EX_tau_mean_inter=prior_EX_tau_mean_inter,
prior_EX_tau_sd_inter=prior_EX_tau_sd_inter,
prior_EX_corr_eta_inter=prior_EX_corr_eta_inter,
prior_NEX_mu_mean_comp=prior_NEX_mu_mean_comp,
prior_NEX_mu_sd_comp=prior_NEX_mu_sd_comp,
prior_NEX_mu_mean_inter=array(prior_NEX_mu_mean_inter, num_inter),
prior_NEX_mu_sd_inter=array(prior_NEX_mu_sd_inter, num_inter),
prior_is_EXNEX_comp=array(1*prior_is_EXNEX_comp, num_comp),
prior_is_EXNEX_inter=array(1*prior_is_EXNEX_inter, num_inter),
prior_PD=1*prior_PD
)
control_sampling <- modifyList(list(adapt_delta=0.99, stepsize=0.1), control)
exclude_pars <- ifelse(save_warmup, "", c("log_beta_raw", "eta_raw",
"tau_log_beta_raw", "tau_eta_raw",
"L_corr_log_beta", "L_corr_eta",
"beta", "eta",
"beta_EX_prob", "eta_EX_prob"))
stan_msg <- capture.output(stanfit <- rstan::sampling(stanmodels$blrm_exnex,
data=stan_data,
warmup=warmup,
iter=iter,
chains=chains,
cores=cores,
thin=thin,
init=init,
control=control_sampling,
algorithm = "NUTS",
open_progress=FALSE,
save_warmup=save_warmup,
include=FALSE,
pars=exclude_pars
))
if(verbose) {
cat(paste(c(stan_msg, ""), collapse="\n"))
}
if(attributes(stanfit)$mode != 0)
stop("Stan sampler did not run successfully!")
labels <- list()
labels$param_log_beta <- .make_label_factor(c("intercept", "log_slope"))
labels$param_beta <- .make_label_factor(c("intercept", "slope"))
labels$component <- .make_label_factor(.abbreviate_label(sapply(X_comp_cols, "[", 2)))
stanfit <- .label_index(stanfit, "mu_log_beta", labels$component, labels$param_log_beta)
stanfit <- .label_index(stanfit, "tau_log_beta", strata_fct, labels$component, labels$param_log_beta)
stanfit <- .label_index(stanfit, "rho_log_beta", labels$component)
stanfit <- .label_index(stanfit, "beta_group", group_fct, labels$component, labels$param_beta)
if(save_warmup)
stanfit <- .label_index(stanfit, "beta_EX_prob", group_fct, labels$component)
stanfit <- .label_index(stanfit, "log_lik_group", group_fct)
if(has_inter) {
labels$param_eta <- .make_label_factor(.abbreviate_label(colnames(X_inter)))
stanfit <- .label_index(stanfit, "eta_group", group_fct, labels$param_eta)
if(save_warmup)
stanfit <- .label_index(stanfit, "eta_EX_prob", group_fct, labels$param_eta)
stanfit <- .label_index(stanfit, "mu_eta", labels$param_eta)
stanfit <- .label_index(stanfit, "tau_eta", strata_fct, labels$param_eta)
stanfit <- .label_index(stanfit, "Sigma_corr_eta", labels$param_eta, labels$param_eta)
}
out <- list(
call = call,
group_strata=group_strata,
standata=stan_data,
stanfit=stanfit,
formula = f,
model = mf,
terms = mt,
xlevels = .getXlevels(mt, mf),
data = data,
idx_group_term=idx_group_term,
idx_inter_term=idx_inter_term,
has_inter=has_inter,
group_fct=group_fct,
strata_fct=strata_fct,
labels=labels
)
structure(out, class="blrmfit")
}
.get_X <- function(formula, model_frame, num_comp, has_inter, idx_inter_term) {
X_comp <- list()
X_comp_cols <- list()
for (i in seq_len(num_comp)) {
X_comp <- c(X_comp, list(model.matrix(formula, model_frame, rhs=i)))
X_comp_cols <- c(X_comp_cols, list(colnames( X_comp[[i]] )))
assert_matrix(X_comp[[i]], ncols=2, any.missing=FALSE)
}
X_comp <- do.call(abind, c(X_comp, list(along=0)))
if(has_inter)
X_inter <- model.matrix(formula, model_frame, rhs=idx_inter_term)
else
X_inter <- model.matrix(~0, model_frame)
list(comp=X_comp, inter=X_inter, comp_cols=X_comp_cols)
}
print.blrmfit <- function(x, ..., prob=0.95, digits=2) {
cat("Bayesian Logistic Regression Model with EXchangeability-NonEXchangeability\n\n")
cat("Number of observations:", x$standata$num_obs, "\n")
cat("Number of groups :", x$standata$num_groups, "\n")
cat("Number of strata :", x$standata$num_strata, "\n")
cat("Number of components :", x$standata$num_comp, "\n")
cat("Number of interactions:", x$standata$num_inter, "\n")
cat("EXNEX components :", sum(x$standata$prior_is_EXNEX_comp), "\n")
cat("EXNEX interactions :", sum(x$standata$prior_is_EXNEX_inter), "\n")
assert_number(prob, lower=0, upper=1, finite=TRUE)
probs <- c(0.5-prob/2, 0.5, 0.5+prob/2)
Stratum <- Group <- total <- n_total <- NULL
cat("\nObservations per group:\n")
ds <- as.data.frame(table(x$group_fct))
rownames(ds) <- match(ds$Var1, levels(x$group_fct))
names(ds) <- c("Group", "n")
totals <- data.frame(Stratum=x$strata_fct, Group=x$group_fct, total=x$standata$nr+x$standata$r) %>%
group_by(Stratum, Group) %>%
summarise(n_total=sum(total)) %>%
ungroup()
ds <- left_join(ds, totals, by="Group")
ds$Stratum <- levels(x$strata_fct)[x$group_strata$strata_index]
ds$n_total[is.na(ds$n_total)] <- 0
print(ds)
cat("\nGroups per stratum:\n")
si <- levels(x$strata_fct)[x$group_strata$strata_index]
ds <- as.data.frame(table(si), stringsAsFactors = FALSE)
names(ds) <- c("Stratum", "Groups")
ds$Stratum <- factor(ds$Stratum, levels=levels(x$strata_fct))
ds <- ds[order(ds$Stratum, ds$Groups), ]
totals_stratum <- totals %>%
group_by(Stratum) %>%
summarise(n_total=sum(n_total))
ds <- left_join(ds, totals_stratum, by="Stratum")
print(ds)
comp_idx <- function(labels) {
inter <- grep("intercept\\]$", labels)
slope <- grep("slope\\]$", labels)
list(inter=inter, slope=slope)
}
strip_variable <- function(labels) {
gsub("^([A-Za-z_]+\\[)(.*)\\]$", "\\2", labels)
}
cat("\nComponent posterior:\n")
cat("Population mean posterior mu_log_beta\n")
mu_log_beta <- summary(x$stanfit, pars=c("mu_log_beta"), probs=probs)$summary
rs <- rownames(mu_log_beta)
idx <- comp_idx(rs)
rownames(mu_log_beta) <- gsub("^(.*),intercept|,log_slope$", "\\1", strip_variable(rs))
cat("intercept:\n")
print(mu_log_beta[idx$inter,], digits=digits)
cat("log-slope:\n")
print(mu_log_beta[idx$slope,], digits=digits)
cat("\nPopulation heterogeniety posterior tau_log_beta\n")
tau_log_beta <- summary(x$stanfit, pars=c("tau_log_beta"), probs=probs)$summary
rs <- rownames(tau_log_beta)
idx <- comp_idx(rs)
rownames(tau_log_beta) <- gsub("^(.*),intercept|,log_slope$", "\\1", strip_variable(rs))
cat("intercept:\n")
print(tau_log_beta[idx$inter,], digits=digits)
cat("log-slope:\n")
print(tau_log_beta[idx$slope,], digits=digits)
cat("\nPopulation correlation posterior rho_log_beta\n")
rho_log_beta <- summary(x$stanfit, pars=c("rho_log_beta"), probs=probs)$summary
rownames(rho_log_beta) <- strip_variable(rownames(rho_log_beta))
print(rho_log_beta, digits=digits)
if(x$standata$num_inter > 0) {
cat("\nInteraction model posterior:\n")
cat("Population mean posterior mu_eta\n")
mu_eta <- summary(x$stanfit, pars=c("mu_eta"), probs=probs)$summary
rownames(mu_eta) <- strip_variable(rownames(mu_eta))
print(mu_eta, digits=digits)
cat("\nPopulation heterogeniety posterior tau_eta\n")
tau_eta <- summary(x$stanfit, pars=c("tau_eta"), probs=probs)$summary
rownames(tau_eta) <- strip_variable(rownames(tau_eta))
print(tau_eta, digits=digits)
cat("\nPopulation correlation posterior Sigma_corr_eta\n")
Sigma_corr_eta <- summary(x$stanfit, pars=c("Sigma_corr_eta"), probs=probs)$summary
rownames(Sigma_corr_eta) <- strip_variable(rownames(Sigma_corr_eta))
print(Sigma_corr_eta, digits=digits)
} else {
cat("\nNo interaction model posterior specified.\n")
}
invisible(x)
}
.label_index <- function(stanfit, par, ...) {
idx <- grep(paste0("^", par, "\\["), names(stanfit))
str <- names(stanfit)[idx]
fct <- list(...)
idx_str <- t(sapply(strsplit(gsub("(.*)\\[([0-9,]*)\\]$", "\\2", str), ","), as.numeric))
if (length(fct) == 1) {
idx_str <- matrix(idx_str, ncol=1)
}
ni <- ncol(idx_str)
colnames(idx_str) <- paste0("idx_", seq_len(ni))
idx_str <- as.data.frame(idx_str)
assert_that(ni == length(fct), msg="Insufficient number of indices specified")
for(i in seq_len(ni)) {
f <- fct[[i]]
key <- data.frame(idx=seq_len(nlevels(f)), label=levels(f))
names(key) <- paste0(names(key), "_", i)
idx_str <- left_join(idx_str, key, by=paste0("idx_", i))
}
labs <- paste0("label_", seq_len(ni))
names(stanfit)[idx] <- paste0(par, "[", do.call(paste, c(idx_str[labs], list(sep=","))), "]")
stanfit
}
.abbreviate_label <- function(label) {
minlength <- getOption("OncoBayes2.abbreviate.min", 0)
if(minlength > 0)
return(abbreviate(label, minlength=minlength))
label
}
.make_label_factor <- function(labels) {
factor(seq_along(labels), levels=seq_along(labels), labels=labels)
}
model.matrix.blrmfit <- function(object, ...) {
return(model.matrix.default(object, object$data))
}
.validate_group_stratum_nesting <- function(group_def, strata_def) {
group_id <- strata_id <- NULL
strata_per_group <- data.frame(group_id=group_def, strata_id=strata_def) %>%
group_by(group_id) %>%
summarize(num_strata=length(unique(strata_id)))
assert_that(all(strata_per_group$num_strata == 1), msg="Inconsistent nesting of groups into strata. Any group must belong to a single stratum.")
} |
fdp_resolve_read <- function(this_read, yaml) {
endpoint <- yaml$run_metadata$local_data_registry_url
if ("use" %in% names(this_read)) {
alias <- this_read$use
} else {
alias <- list()
}
if ("version" %in% names(this_read)) {
read_version <- this_read$version
} else if ("version" %in% names(alias)) {
read_version <- alias$version
} else {
if ("data_product" %in% names(alias)) {
read_dataproduct <- alias$data_product
} else {
read_dataproduct <- this_read$data_product
}
if ("namespace" %in% names(alias)) {
read_namespace <- alias$namespace
} else {
read_namespace <- yaml$run_metadata$default_input_namespace
}
read_namespace_url <- new_namespace(name = read_namespace,
endpoint = endpoint)
read_namespace_id <- extract_id(read_namespace_url, endpoint = endpoint)
entries <- get_entry("data_product",
list(name = read_dataproduct,
namespace = read_namespace_id))
if (is.null(entries)) {
usethis::ui_stop("{read_dataproduct} is not in local registry")
} else {
read_version <- lapply(entries, function(x) x$version) %>%
unlist() %>%
max()
}
}
read_version
} |
linters_to_lint <- list(
assignment_linter = lintr::assignment_linter,
line_length_linter = lintr::line_length_linter(80),
trailing_semicolon_linter = trailing_semicolon_linter,
attach_detach_linter = attach_detach_linter,
setwd_linter = setwd_linter,
sapply_linter = sapply_linter,
library_require_linter = library_require_linter,
seq_linter = seq_linter
)
PREPS$lintr <- function(state, path = state$path, quiet) {
path <- normalizePath(path)
suppressMessages(
state$lintr <- try(lint_package(path, linters = linters_to_lint),
silent = TRUE)
)
if(inherits(state$lintr, "try-error")) {
warning("Prep step for linter failed.")
}
state
} |
context("test-path0-sanity")
x <- PATH0(minimal_mesh)
test_that("PATH0 round trip suite works", {
skip_on_cran()
expect_silent({
SC(x)
SC0(x)
plot(SC(x))
plot(SC0(x))
sc_vertex(x)
sc_coord(x)
sc_node(x)
sc_edge(x)
sc_segment(x)
sc_object(x)
sc_path(x)
PATH(x)
PATH0(x)
sc_start(x)
sc_end(x)
})
expect_warning({
ARC(x)
sc_arc(x)
}
)
expect_s3_class(TRI0(x), "TRI0")
expect_s3_class( TRI(x), "TRI")
})
test_that("errors when PATH0 round trip unsupported", {
expect_error(ARC0(x))
}) |
findt2ab <- function(tstart, tmid, tend, ulstart, ulmid, xlstart, xlmid, xfstart, uf, lty, lwd, col) {
tstart <- tstart
tend <- tmid
ustart <- ulstart
uend <- ulmid
xstart <- xlstart
xend <- xlmid
step <- 0.25
ab <- trajectoryab(tstart, tend, ustart, uend, xstart, xend, step)
a <- ab[[1]][1]
b <- ab[[1]][2]
h01 <- function(t, tstart, ulstart, ulmid, xlstart, xlmid, xfstart, uf, a, b)
xab(x0 = xlstart, u0 = ulstart, a, b, t, t0 = tstart) -
xfollow(x0 = xfstart, u = uf, t, t0 = tstart)
h12 <- function(t, tstart, tmid, xlmid, ulmid, xfstart, uf)
xlmid + ulmid * (t - tmid) -
xfollow(x0 = xfstart, u = uf, t, t0 = tstart)
h0 <- h01(t = tstart, tstart, ulstart, ulmid, xlstart, xlmid, xfstart, uf, a, b)
h1 <- h01(t = tmid, tstart, ulstart, ulmid, xlstart, xlmid, xfstart, uf, a, b)
j1 <- h12(t = tstart, tstart, tmid, xlmid, ulmid, xfstart, uf)
j2 <- h12(t = tend, tstart, tmid, xlmid, ulmid, xfstart, uf)
s0 <- sign(h0)
s1 <- sign(h1)
w1 <- sign(j1)
w2 <- sign(j2)
t2 <- NA
if(s0 != s1) {
t2 <- uniroot(h01,
tstart = tstart,
ulstart = ulstart,
ulmid = ulmid,
xlstart = xlstart,
xlmid = xlmid,
xfstart = xfstart,
uf = uf,
a, b,
interval = c(tstart, tmid), tol = 1e-9)$root
xl2 <- xab(xlstart, ulstart, a, b, t2, tstart)
ul2 <- uab(ulstart, a, b, t2, tstart)
ul2 <- min(uf, ulmid)
dest <- abs((ul2 - ulstart)/(t2 - tstart))
answer <- as.matrix(data.frame(dest = dest, t2 = t2, xl2, ul2, test = 4))
return(answer)
}
if(w1 != w2 & is.na(t2)) {
t2 <- uniroot(h12,
tstart = tstart,
tmid = tmid,
xlmid = xlmid,
ulmid = ulmid,
xfstart = xfstart,
uf = uf,
interval = c(tstart, tend), tol = 1e-9)$root
xl2 <- xfollow(xfstart, uf, t2, tstart)
ul2 <- min(uf, ulmid)
dest <- abs((ul2 - ulstart)/(t2 - tstart))
answer <- as.matrix(data.frame(dest = dest, t2 = t2, xl2, ul2, test = 1))
return(answer)
}
if(is.na(t2)) {
t2 <- (xlmid - xfstart + uf * tstart - ulmid * tmid)/(uf - ulmid)
if(t2 > tstart) {
xl2 <- xfstart + uf * (t2 - tstart)
ul2 <- min(uf, ulmid)
dest <- abs((ul2 - ulstart)/(t2 - tstart))
answer <- as.matrix(data.frame(dest = dest, t2 = t2, xl2, ul2, test = 2))
return(answer)
} else {
t2 <- tmid
ul2 <- ulmid
xl2 <- xlstart + ulmid * (t2 - tstart)
answer <- as.matrix(data.frame(dest = NA, t2 = t2, xl2, ul2, test = 2))
}
}
} |
library(tidyverse)
library(ggforce)
library(poissoned)
library(wesanderson)
library(colorspace)
s <- round(runif(1, 0, 1000))
set.seed(s)
pnts1 <- data.frame(
x = rnorm(10, 0, 100),
y = rnorm(10, 0, 100)
) %>%
expand(x, y)
pnts2 <- poisson_disc(ncols = 10, nrows = 20, cell_size = 10, verbose = TRUE)
pnts <- rbind(pnts1, pnts2) %>%
mutate(fill = round((x / y) %% 4))
w <- max(pnts$x) - min(pnts$x)
h <- max(pnts$y) - min(pnts$y)
a <- w/h
pal = wes_palette("Darjeeling1", 5, "discrete")
ggplot(pnts, aes(x, y)) +
geom_voronoi_tile(aes(fill = factor(fill))) +
geom_voronoi_segment(aes(color = factor(fill)), size = 0.4, alpha = 0.9) +
scale_fill_manual(values = pal) +
scale_color_manual(values = lighten(pal, 0.2)) +
theme_void() +
theme(
legend.position = "none",
plot.background = element_rect(fill = "grey90", color = NA),
plot.margin = margin(10, 10, 10, 10)
)
ggsave(here::here("genuary", "2021", "2021-14", paste0("2021-14-", s, ".png")), dpi = 320, width = 7, height = 7 / a) |
varNDWI<-function(green,nir){
ndwi<-(green-nir)/(green+nir)
return(ndwi)
} |
euklid.ewma.arl <- function(gX, gY, kL, kU, mu, y0, r0=0) {
if ( gX <= 0 ) stop("gX must be positive")
if ( gY <= 0 ) stop("gY must be positive")
if ( kL <= 0 ) stop("kL must be positive")
if ( kU <= 0 ) stop("kU must be positive")
if ( kU < kL ) stop("kU must be larger than or equal to kL")
if ( mu <= 0 ) stop("mu must be positive")
if ( y0 <= 0 ) stop("y0 must be positive")
if ( r0 < 0 ) stop("r0 must be non-negative")
arl <- .C("euklid_ewma_arl",
as.integer(gX), as.integer(gY), as.integer(kL), as.integer(kU),
as.double(mu), as.double(y0), as.integer(r0),
ans=double(length=1), PACKAGE="spc")$ans
names(arl) <- "arl"
arl
} |
upliftRF <- function(x, ...) UseMethod("upliftRF")
upliftRF.default <- function(x,
y,
ct,
mtry = floor(sqrt(ncol(x))),
ntree = 100,
split_method = c("ED", "Chisq", "KL", "L1", "Int"),
interaction.depth = NULL,
bag.fraction = 0.5,
minsplit = 20,
minbucket_ct0 = round(minsplit/4),
minbucket_ct1 = round(minsplit/4),
keep.inbag = FALSE,
verbose = FALSE,
...) {
if(!is.data.frame(x))
stop("uplift: x must be data frame. Aborting...")
if(!is.numeric(y))
stop("uplift: y must be a numeric vector. Aborting...")
if(!is.numeric(ct))
stop("uplift: ct must be a numeric vector. Aborting...")
if (any(is.na(as.vector(x))) |
any(is.infinite(as.matrix(x))) |
any(is.na(as.vector(y))) |
any(is.infinite(as.vector(y))) |
any(is.na(as.vector(ct))) |
any(is.infinite(as.vector(ct))))
stop("uplift: training data contains NaNs or Inf values. Please correct and try again. Aborting...")
out.method <- charmatch(tolower(split_method),
c("ed", "chisq", "kl", "l1", "int"))
if (is.na(out.method))
stop("uplift: split_method must be one of 'ED', 'Chisq', 'KL', 'L1' or 'Int'. Aborting...")
if (bag.fraction <= 0 || bag.fraction > 1)
stop("uplift: bag.fraction must be greater than 0 and equal or less than 1. Aborting...")
if (!is.null(interaction.depth) && interaction.depth < 1)
stop("uplift: interaction.depth must be greater than 0. Aborting...")
if (mtry < 1 || mtry > ncol(x))
stop("uplift: invalid mtry: reset to within valid range. Aborting...")
if (length(unique(y)) != 2)
stop("uplift: upliftRF supports only binary response variables. Aborting...")
if (!all(unique(y) %in% c(0,1)))
stop("uplift: y must be coded as 0/1. Aborting...")
if (!all(unique(ct) %in% c(0,1)))
stop("uplift: ct must be coded as 0/1. Aborting...")
if (length(unique(ct)) != 2)
stop("uplift: upliftRF supports only 2 treatments at the moment. Aborting...")
if (length(y) != nrow(x) || nrow(x) != length(ct))
stop("uplift: length of x, y, and ct must be similar. Aborting...")
xlevels <- lapply(x, mylevels)
ncat <- sapply(xlevels, length)
maxcat <- max(ncat)
if (maxcat > 32)
stop("uplift: can not handle categorical predictors with more than 32 categories. Aborting...")
if (minbucket_ct0 < 1 || minbucket_ct1 < 1)
stop("uplift: minbucket_ct0 and minbucket_ct1 must be greater than 0. Aborting...")
if (verbose)
message("uplift: status messages enabled; set \"verbose\" to false to disable")
dframe <- cbind(x, ct, y, obs.index = 1:nrow(x))
nr_samples <- nrow(dframe)
nr_vars <- ncol(x)
dframe_sp <- split(dframe, list(dframe$y, dframe$ct))
split_len <- length(dframe_sp)
if (split_len != 4)
stop("uplift: each level of treatment ct must have positive (y=1) and negative (y=0) responses. Aborting...")
nr_in_samples_sp <- lapply(dframe_sp, function(x) floor(nrow(x) * bag.fraction))
nr_in_samples <- sum(unlist(nr_in_samples_sp))
nr_nodes <- 2 * nr_in_samples + 1
trees <- vector("list", ntree)
b.ind.m <- matrix(nrow = nr_in_samples, ncol = ntree,
dimnames = list(NULL, paste('tree', 1:ntree,sep='')))
if (verbose)
cat("upliftRF: starting.",date(),"\n")
for (i in 1:ntree) {
if (verbose)
if ((i %% 10) == 0 && i < ntree) message( "", i, " out of ", ntree, " trees so far...")
b.ind <- lapply(1:split_len, function(k) sample(1:nrow(dframe_sp[[k]]),
nr_in_samples_sp[[k]], replace = FALSE))
dframe_sp_s <- lapply(1:split_len, function(k) dframe_sp[[k]][b.ind[[k]], ])
b.dframe <- do.call("rbind", dframe_sp_s)
trees[[i]] <- buildTree(b.dframe,
mtry,
split_method,
interaction.depth,
minsplit,
minbucket_ct0,
minbucket_ct1,
nr_vars,
nr_in_samples,
nr_nodes);
if (keep.inbag)
b.ind.m[, i] <- b.dframe$obs.index
}
cl <- match.call()
var.names <- colnames(x)
var.class <- sapply(x, class)
res.trees <- list(call = cl,
trees = trees,
split_method = split_method,
ntree = ntree,
mtry = mtry,
var.names = var.names,
var.class = var.class,
inbag = b.ind.m)
class(res.trees) <- "upliftRF"
return(res.trees)
} |
OrderWR<-function(N,m,ID=FALSE){
b<-c(1:N)
grilla<-function(a){
A<-seq(1:length(a))
unoA <-rep(1,length(A))
B<-seq(1:length(a))
unoB <-rep(1,length(B))
P1<-kronecker(A,unoB)
P2<-kronecker(unoA,B)
grid<-matrix(cbind(P1,P2),ncol=2)
return(grid)
}
if(m==1){
sam<-as.matrix(b)
}
if(m==2){
sam<-grilla(b)
}
if(m>2){
sam<-grilla(b)
for(l in 3:m){
Sam1<-rep(0,l)
for(j in 1:dim(sam)[1]){
for(k in 1:length(b)){
Sam1<-rbind(Sam1,c(sam[j,],b[k]))
} }
sam<-Sam1[-1,]
}
}
if (is.logical(ID) == TRUE){return(sam)}
else{
a<-dim(sam)
val<-matrix(NA,a[1],a[2])
for(ii in 1:(dim(val)[1])){
for(jj in 1:(dim(val)[2])){
val[ii,jj]<-ID[sam[ii,jj]]
}
}
return(val)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.