code
stringlengths 1
13.8M
|
---|
appliquePonder <-
function(var, pond){
res <- var * pond
return (res)
}
|
sampler.hmc.bounded <- function(f, q, fq, w, lower, upper,
control) {
epsilon <- control$epsilon
L <- control$L
m <- control$m
if ( m != 1 )
stop("Varying m not allowed yet.")
if ( any(upper < Inf) )
stop("Probably should not try upper yet.")
q.in <- q
fq.in <- fq
gq <- attr(fq, "gr")
p.in <- p <- rnorm(length(q), 0, 1)
p <- p + epsilon * gq / 2
for (i in seq_len(L)) {
q <- q + epsilon * p
nok <- q < lower
if ( any(nok) ) {
q[nok] <- 2 * lower[nok] - q[nok]
p[nok] <- -p[nok]
}
if ( i != L )
p <- p + epsilon * attr(f(q), "gr")
}
fq.out <- f(q)
p <- p + epsilon * attr(fq.out, "gr") / 2
k.in <- sum(p.in^2) / 2
k.out <- sum(p^2) / 2
alpha <- exp(-fq.in - -fq.out + k.in - k.out)
if ( runif(1) < alpha )
list(q, fq.out)
else
list(q.in, fq.in)
}
|
context("dimCode Test")
x <- maxample("animal")
pop <- maxample("pop")
test_that("dimension codes are correctly extracted", {
expect_equivalent(dimCode(1, x), 1)
expect_equivalent(dimCode(1.5, x), 1.5)
expect_equivalent(dimCode(4.2, x), 0)
expect_equivalent(dimCode(3.5, x, strict = FALSE), 3.5)
expect_equivalent(dimCode(3.5, x, strict = TRUE), 0)
expect_equivalent(dimCode("month", x), 2.2)
expect_equivalent(dimCode("x", x), 1.1)
expect_equivalent(dimCode("country", x), 1.3)
expect_equivalent(dimCode(c("y", "year", "color"), x), c(1.2, 2.1, 3.3))
expect_equivalent(dimCode(NULL, x), NULL)
expect_equivalent(dimCode("t", pop), 2)
expect_equivalent(dimCode("notavail", pop), 0)
})
test_that("illegal dim values are properly detected", {
expect_error(dimCode("a.b", x), "separator must not be used in dimension name")
getSets(pop) <- rep("same", 3)
expect_error(dimCode("same", pop), "found more than once")
getSets(x, fulldim = FALSE)[3] <- "species.species.color"
expect_error(dimCode("species", x), "more than once")
expect_error(dimCode(5, x, missing = "stop"), "illegal dimension")
})
|
plotPost <-
function(paramSampleVec, credMass = 0.95, compVal = NULL, ROPE = NULL,
HDItextPlace = 0.7, showMode = FALSE, showCurve = FALSE, ...) {
dots <- list(...)
if(length(dots) == 1 && class(dots[[1]]) == "list")
dots <- dots[[1]]
defaultArgs <- list(xlab=deparse(substitute(paramSampleVec)),
yaxt="n", ylab="", main="", cex.lab=1.5,
cex=1.4, col="skyblue", border="white", bty="n", lwd=5, freq=FALSE,
xlim=range(compVal, HDInterval::hdi(paramSampleVec, 0.99)))
useArgs <- modifyList(defaultArgs, dots)
breaks <- dots$breaks
if (is.null(breaks)) {
if (all(paramSampleVec == round(paramSampleVec))) {
breaks <- seq(min(paramSampleVec), max(paramSampleVec) + 1) - 0.5
} else {
by <- diff(HDInterval::hdi(paramSampleVec))/18
breaks <- unique(c( seq( from=min(paramSampleVec), to=max(paramSampleVec),
by=by), max(paramSampleVec) ))
}
}
histinfo <- hist(paramSampleVec, breaks=breaks, plot=FALSE)
histinfo$xname <- useArgs$xlab
oldpar <- par(xpd=TRUE) ; on.exit(par(oldpar))
if (showCurve) {
densCurve <- density( paramSampleVec, adjust=2 )
selPlot <- names(useArgs) %in%
c(names(as.list(args(plot.default))), names(par(no.readonly=TRUE)))
plotArgs <- useArgs[selPlot]
plotArgs$x <- densCurve$x
plotArgs$y <- densCurve$y
plotArgs$type <- "l"
plotArgs$xpd <- FALSE
do.call(plot, plotArgs, quote=TRUE)
abline(h=0, col='grey', xpd=FALSE)
if(!is.null(credMass)) {
HDI <- HDInterval::hdi(densCurve, credMass, allowSplit=TRUE)
ht <- attr(HDI, "height")
segments(HDI[, 1], ht, HDI[, 2], ht, lwd=4, lend='butt')
segments(HDI, 0, HDI, ht, lty=2)
text( mean(HDI), ht, bquote(.(100*credMass) * "% HDI" ),
adj=c(.5,-1.7), cex=useArgs$cex )
text( HDI, ht, bquote(.(signif(HDI, 3))),
pos=3, cex=useArgs$cex )
}
} else {
plot.histogram.args.names <- c("freq", "density", "angle", "border",
"main", "sub", "xlab", "ylab", "xlim", "ylim", "axes", "labels",
"add")
selPlot <- names(useArgs) %in%
c(plot.histogram.args.names, names(par(no.readonly=TRUE)))
plotArgs <- useArgs[selPlot]
plotArgs$lwd <- 1
plotArgs$x <- histinfo
do.call(plot, plotArgs, quote=TRUE)
if(!is.null(credMass)) {
HDI <- HDInterval::hdi( paramSampleVec, credMass )
lines(HDI, c(0,0), lwd=4, lend='butt')
text( mean(HDI), 0, bquote(.(100*credMass) * "% HDI" ),
adj=c(.5,-1.7), cex=useArgs$cex )
text( HDI[1], 0, bquote(.(signif(HDI[1],3))),
adj=c(HDItextPlace,-0.5), cex=useArgs$cex )
text( HDI[2], 0, bquote(.(signif(HDI[2],3))),
adj=c(1.0-HDItextPlace,-0.5), cex=useArgs$cex )
}
}
cenTendHt <- 0.9 * max(histinfo$density)
if ( showMode==FALSE ) {
meanParam <- mean( paramSampleVec )
text( meanParam, cenTendHt,
bquote(mean==.(signif(meanParam,3))), adj=c(.5,0), cex=useArgs$cex )
} else {
dres <- density( paramSampleVec )
modeParam <- dres$x[which.max(dres$y)]
text( modeParam, cenTendHt,
bquote(mode==.(signif(modeParam,3))), adj=c(.5,0), cex=useArgs$cex )
}
if ( !is.null( compVal ) ) {
cvHt <- 0.7 * max(histinfo$density)
cvCol <- "darkgreen"
pcgtCompVal <- round( 100 * sum( paramSampleVec > compVal )
/ length( paramSampleVec ) , 1 )
pcltCompVal <- 100 - pcgtCompVal
lines( c(compVal,compVal), c(0.96*cvHt,0),
lty="dotted", lwd=1, col=cvCol )
text( compVal, cvHt,
bquote( .(pcltCompVal)*"% < " *
.(signif(compVal,3)) * " < "*.(pcgtCompVal)*"%" ),
adj=c(pcltCompVal/100,0), cex=0.8*useArgs$cex, col=cvCol )
}
if ( !is.null( ROPE ) ) {
ROPEtextHt <- 0.55 * max(histinfo$density)
ropeCol <- "darkred"
pcInROPE <- ( sum( paramSampleVec > ROPE[1] & paramSampleVec < ROPE[2] )
/ length( paramSampleVec ) )
lines( c(ROPE[1],ROPE[1]), c(0.96*ROPEtextHt,0), lty="dotted", lwd=2,
col=ropeCol )
lines( c(ROPE[2],ROPE[2]), c(0.96*ROPEtextHt,0), lty="dotted", lwd=2,
col=ropeCol)
text( mean(ROPE), ROPEtextHt,
bquote( .(round(100*pcInROPE))*"% in ROPE" ),
adj=c(.5,0), cex=1, col=ropeCol )
}
return(invisible(histinfo))
}
|
vg_check <- function () {
vg <- system2 (command = "R",
args = c ('-d "valgrind --tool=memcheck --leak-check=full"',
'-f valgrind-script.R'),
stdout = TRUE, stderr = TRUE)
lost <- NULL
types <- c ("definitely lost", "indirectly lost", "possibly lost")
for (ty in types) {
lost_type <- which (grepl (ty, vg))
n <- regmatches (vg [lost_type],
gregexpr ("[[:digit:]]+", vg [lost_type]))
lost <- c (lost, as.numeric (n [[1]] [2:3]))
}
if (any (lost > 0))
stop ("valgrind memory leaks detected!")
return (TRUE)
}
if (identical (Sys.getenv ("TRAVIS"), "true")) {
}
|
readWiki <- function(category, subcategories = TRUE,
language = "en", project = "wikipedia"){
stopifnot(
is.character(category), length(category) == 1,
is.logical(subcategories), length(subcategories) == 1,
is.character(language), length(language) == 1,
is.character(project), length(project) == 1)
level1pages <-
WikipediR::pages_in_category(
language = language, project = project, type = "page", limit = 500,
properties = c("id", "title", "timestamp"),
categories = category)$query$categorymembers
subs <- NULL
level2pages <- NULL
if (subcategories){
subs <-
WikipediR::pages_in_category(
language = language, project = project, type = "subcat", limit = 500,
properties = "title", categories = category)$query$categorymembers
subs <- gsub("Category:", "", sapply(subs, function(x) x$title))
level2pages <-
do.call(c,
lapply(subs, function(x)
WikipediR::pages_in_category(
language = language, project = project, type = "page", limit = 500,
properties = c("id", "title", "timestamp"),
categories = x)$query$categorymembers))
}
pages = c(level1pages, level2pages)
message("downloading ", length(pages), " articles in the category \"", category,
"\" and ", length(subs), " subcategories...")
id <- sapply(pages, function(x) x$pageid)
title <- sapply(pages, function(x) x$title)
date <- as.Date(sapply(pages, function(x) x$timestamp))
categoryCall <- category
touched <-
as.Date(
sapply(pages,
function(x) WikipediR::page_info(language = language, project = project,
page = x$title)$query$pages[[1]]$touched))
meta <- data.frame(id = as.character(id), date = date, title = title,
categoryCall = categoryCall, touched = touched, stringsAsFactors = FALSE)
text <- lapply(meta$title,
function(x) WikipediR::page_content(language = language, project = project,
page_name = x)$parse$text$`*`)
names(text) <- meta$id
return(textmeta(meta = meta, text = text))
}
|
spherical.recurrences <- function( n, normalized=FALSE )
{
return( legendre.recurrences( n, normalized ) )
}
|
library("ggplot2")
x <- seq_along(sunspot.year)
y <- as.numeric(sunspot.year)
m <- ggplot(data.frame(x = x, y = y), aes(x = x, y = y)) +
geom_line()
m
ratio <- bank_slopes(x, y)
m + coord_fixed(ratio = ratio)
bank_slopes(x, y, method = "as")
|
addMinicharts <- function(map, lng, lat, chartdata = 1, time = NULL, maxValues = NULL, type = "auto",
fillColor = d3.schemeCategory10[1], colorPalette = d3.schemeCategory10,
width = 30, height = 30, opacity = 1, showLabels = FALSE,
labelText = NULL, labelMinSize = 8, labelMaxSize = 24,
labelStyle = NULL,
transitionTime = 750,
popup = popupArgs(),
layerId = NULL, legend = TRUE, legendPosition = "topright",
timeFormat = NULL, initialTime = NULL, onChange = NULL,
popupOptions = NULL) {
type <- match.arg(type, c("auto", "bar", "pie", "polar-area", "polar-radius"))
if (is.null(layerId)) layerId <- sprintf("_minichart (%s,%s)", lng, lat)
if (is.null(time)) time <- 1
if (is.null(popup$labels)) popup$labels <- colnames(chartdata)
if (showLabels) {
if (!is.null(labelText)) labels <- labelText
else labels <- "auto"
} else {
labels <- "none"
}
options <- .preprocessArgs(
required = list(lng = lng, lat = lat, layerId = layerId, time = time),
optional = list(type = type, width = width, height = height,
opacity = opacity, labels = labels,
labelMinSize = labelMinSize, labelMaxSize = labelMaxSize,
labelStyle = labelStyle,
transitionTime = transitionTime, fillColor = fillColor)
)
args <- .prepareJSArgs(options, chartdata, popup, onChange,
initialTime = initialTime, timeFormat = timeFormat)
if (is.null(maxValues)) maxValues <- args$maxValues
map$dependencies <- c(map$dependencies, minichartDeps())
if(!is.null(maxValues)){
if(!is.null(args$chartdata)){
if(!(length(maxValues) == 1 | length(maxValues) == ncol(args$chartdata[[1]]))){
stop("'maxValues' should be a single number or have same length as 'data'")
}
}
maxValues <- unname(maxValues)
maxValues[maxValues == 0 | is.na(maxValues) | is.infinite(maxValues)] <- 1
}
map <- invokeMethod(map, data = leaflet::getMapData(map), "addMinicharts",
args$options, args$chartdata, maxValues, colorPalette,
args$timeLabels, args$initialTime, args$popupArgs, args$onChange,
popupOptions)
if (legend && length(args$legendLab) > 0 && args$ncol > 1) {
legendCol <- colorPalette[(seq_len(args$ncols)-1) %% args$ncols + 1]
map <- addLegend(map, labels = args$legendLab, colors = legendCol, opacity = 1,
layerId = "minichartsLegend", position = legendPosition)
}
map %>% expandLimits(lat, lng)
}
updateMinicharts <- function(map, layerId, chartdata = NULL, time = NULL, maxValues = NULL, type = NULL,
fillColor = NULL, colorPalette = d3.schemeCategory10,
width = NULL, height = NULL, opacity = NULL, showLabels = NULL,
labelText = NULL, labelMinSize = NULL,
labelMaxSize = NULL, labelStyle = NULL,
transitionTime = NULL, popup = NULL,
legend = TRUE, legendPosition = NULL,
timeFormat = NULL, initialTime = NULL, onChange = NULL,
popupOptions = NULL) {
if (!is.null(type)) {
type <- match.arg(type, c("auto", "bar", "pie", "polar-area", "polar-radius"))
}
if (is.null(time)) time <- 1
if (!is.null(chartdata) & !is.null(popup) & is.null(popup$labels)) popup$labels <- colnames(chartdata)
if (is.null(showLabels)) {
labels <- NULL
} else {
if (showLabels) {
if (!is.null(labelText)) labels <- labelText
else labels <- "auto"
} else {
labels <- "none"
}
}
options <- .preprocessArgs(
required = list(layerId = layerId, time = time),
optional = list(type = type, width = width, height = height,
opacity = opacity, labels = labels,
labelMinSize = labelMinSize, labelMaxSize = labelMaxSize,
labelStyle = labelStyle,
labelText = labelText, transitionTime = transitionTime,
fillColor = fillColor)
)
args <- .prepareJSArgs(options, chartdata, popup, onChange,
initialTime = initialTime, timeFormat = timeFormat)
if(is.null(chartdata)) {
args$timeLabels <- NULL
}
if (!is.null(args$chartdata)) {
if (legend && length(args$legendLab) > 0 && args$ncols > 1) {
legendCol <- colorPalette[(seq_len(args$ncols)-1) %% args$ncols + 1]
map <- addLegend(map, labels = args$legendLab, colors = legendCol, opacity = 1,
layerId = "minichartsLegend", position = legendPosition)
} else {
map <- leaflet::removeControl(map, "minichartsLegend")
}
}
if(!is.null(maxValues)){
if(!is.null(args$chartdata)){
if(!(length(maxValues) == 1 | length(maxValues) == ncol(args$chartdata[[1]]))){
stop("'maxValues' should be a single number or have same length as 'data'")
}
}
maxValues <- unname(maxValues)
maxValues[maxValues == 0 | is.na(maxValues) | is.infinite(maxValues)] <- 1
}
map %>%
invokeMethod(leaflet::getMapData(map), "updateMinicharts",
args$options, args$chartdata, maxValues, colorPalette,
args$timeLabels, args$initialTime, args$popupArgs,
args$legendLab, args$onChange, popupOptions)
}
removeMinicharts <- function(map, layerId) {
invokeMethod(map, leaflet::getMapData(map), "removeMinicharts", layerId)
}
clearMinicharts <- function(map) {
invokeMethod(map, leaflet::getMapData(map), "clearMinicharts") %>%
leaflet::removeControl("minichartsLegend")
}
|
library(ggplot2)
this_base <- "fig03-02_area-and-volume-judgments"
my_data <- data.frame(
val1 = c(0.75, 2, 3, 4, 5, 5, 6, 7, 8),
val2 = c(4, 6, 6, 8, 6, 5, 1, 0.5, 9),
area = c(5, 8, 0.25, 4, 9, 0.5, 6, 1, 12))
p <- ggplot(my_data, aes(x = val1, y = val2, size = area)) +
geom_point(shape = 21, show_guide = FALSE) +
scale_size_area(max_size = 25) +
scale_x_continuous(breaks = seq(2, 8, 2), limit = c(0, 9),
expand = c(0, 0)) +
scale_y_continuous(breaks = seq(0, 10, 2), limit = c(0, 10),
expand = c(0, 0)) +
ggtitle("Fig 3.2 Area and Volume Judgments") +
theme_bw() +
theme(panel.grid.major = element_blank(),
plot.title = element_text(size = rel(1.5), face = "bold", vjust = 1.5),
axis.title = element_blank())
p
ggsave(paste0(this_base, ".png"),
p, width = 6, height = 5)
|
pmclust.internal <- function(X = NULL, K = 2, MU = NULL,
algorithm = .PMC.CT$algorithm.gbd, RndEM.iter = .PMC.CT$RndEM.iter,
CONTROL = .PMC.CT$CONTROL, method.own.X = .PMC.CT$method.own.X,
rank.own.X = .pbd_env$SPMD.CT$rank.source, comm = .pbd_env$SPMD.CT$comm){
if(! (algorithm[1] %in% .PMC.CT$algorithm.gbd)){
comm.stop("The algorithm is not supported")
}
if(! (method.own.X[1] %in% .PMC.CT$method.own.X)){
comm.stop("The method.own.X is not found.")
}
if(comm.all(is.null(X))){
} else{
convert.data(X, method.own.X[1], rank.own.X, comm)
}
PARAM.org <- set.global(K = K, RndEM.iter = RndEM.iter)
if(! comm.all(is.null(CONTROL))){
tmp <- .pmclustEnv$CONTROL[!(names(.pmclustEnv$CONTROL) %in%
names(CONTROL))]
.pmclustEnv$CONTROL <- c(tmp, CONTROL)
}
if(! comm.all(is.null(MU))){
if(algorithm[1] != "kmeans"){
PARAM.org <- initial.em(PARAM.org, MU = MU)
} else{
PARAM.org <- initial.center(PARAM.org, MU = MU)
}
} else{
if(algorithm[1] != "kmeans"){
PARAM.org <- initial.RndEM(PARAM.org)
} else{
PARAM.org <- initial.center(PARAM.org)
}
}
method.step <- switch(algorithm[1],
"em" = em.step,
"aecm" = aecm.step,
"apecm" = apecm.step,
"apecma" = apecma.step,
"kmeans" = kmeans.step,
NULL)
PARAM.new <- method.step(PARAM.org)
if(algorithm[1] == "kmeans"){
kmeans.update.class()
} else{
em.update.class()
}
N.CLASS <- get.N.CLASS(K)
ret <- list(algorithm = algorithm[1],
param = PARAM.new,
class = .pmclustEnv$CLASS.spmd,
n.class = N.CLASS,
check = .pmclustEnv$CHECK)
ret
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(htmltools)
tags$div(
class = "shiny-app-frame",
tags$iframe(
src = "https://andrie-de-vries.shinyapps.io/sortable_rank_list_app/",
width = "100%",
height = 550
)
)
knitr::read_chunk(
system.file("shiny-examples/rank_list/app.R", package = "sortable")
)
library(htmltools)
tags$div(
class = "shiny-app-frame",
tags$iframe(
src = "https://andrie-de-vries.shinyapps.io/sortable_bucket_list_app/",
width = "100%",
height = 800
)
)
knitr::read_chunk(
system.file("shiny-examples/bucket_list/app.R", package = "sortable")
)
|
add_rmd <- function(rmd, path) {
no_rmd <- missing(rmd) || is.null(rmd) || is.na(rmd)
no_path <- missing(path) || is.null(path) || is.na(path)
if( no_rmd && no_path) stop('Either rmd or path must be specified')
if(!no_rmd && !no_path) stop('Only one of app or path should be specified')
if(no_path) {
file <- file.path(getShinyOption('appDir'), rmd)
} else {
Path <- shiny::addResourcePath(basename(dirname(path)), dirname(path))
file <- file.path(path)
}
withMathJax(HTML(markdown::markdownToHTML(knitr::knit(file))))
}
|
get_F_const = function(temp_kelvin, gas_constant) {
if(temp_kelvin == 0) stop("Temperature in Kelvin can not be 0.")
Ea_A = 14000
Ea_B = 17000
Ea_W = 19000
Q7 = (1 / temp_kelvin - 1 / 293) / gas_constant
list(Fta = exp(-Q7 * Ea_A),
Ftb = exp(-Q7 * Ea_B),
Ftw = exp(-Q7 * Ea_W))
}
get_poly_const = function(mol_type, exchange = "HD") {
match.arg(mol_type, c("poly", "oligo"))
match.arg(exchange, c("HD", "DH"))
if (exchange == "HD") {
Ka_exponent = 1.62
Kb_exponent = 10.05
Kw_exponent = -1.5
} else {
Ka_exponent = 1.4
Kb_exponent = 9.87
Kw_exponent = -1.6
}
Ka_poly = (10^(Ka_exponent)) / 60
Kb_poly = (10^(Kb_exponent)) / 60
Kw_poly = (10^(Kw_exponent)) / 60
if (mol_type == "poly") {
list(Ka = Ka_poly,
Kb = Kb_poly,
Kw = Kw_poly)
} else {
Kb_oligo = Kb_poly * 1.35
Ka_oligo = Ka_poly * 2.34
Kw_oligo = Kw_poly * 1.585
list(Ka = Ka_oligo,
Kb = Kb_oligo,
Kw = Kw_oligo)
}
}
get_pkc <- function(temp_kelvin, gas_constant, exchange = "HD") {
if(temp_kelvin == 0) stop("Temperature in Kelvin can not be 0.")
match.arg(exchange, c("HD", "DH"))
if (exchange == "HD") {
Ea_Asp <- 1000
Asp_exponent <- -4.48
Glu_exponent <- -4.93
His_exponent <- -7.42
} else {
Ea_Asp <- 960
Asp_exponent <- -3.87
Glu_exponent <- -4.33
His_exponent <- -7
}
Ea_Glu <- 1083
Ea_His <- 7500
pKc_Asp <- -log10(10^(Asp_exponent)*exp(-1*Ea_Asp*((1/temp_kelvin-1/278)/gas_constant)))
pKc_Glu <- -log10(10^(Glu_exponent)*exp(-1*Ea_Glu*((1/temp_kelvin-1/278)/gas_constant)))
pKc_His <- -log10(10^(His_exponent)*exp(-1*Ea_His*((1/temp_kelvin - 1/278)/gas_constant)))
list(asp = pKc_Asp,
glu = pKc_Glu,
his = pKc_His)
}
get_exchange_constants <- function(pH, pkc_consts, k_consts) {
constants <- matrix(
c(0, 0, 0, 0,
-0.59, -0.32, 0.0767122542818456, 0.22,
0, 0, 0, 0,
-0.90, -0.12, 0.69, 0.60,
-0.58, -0.13, 0.49, 0.32,
-0.54, -0.46, 0.62, 0.55,
-0.74, -0.58, 0.55, 0.46,
-0.22, 0.218176047120386, 0.267251569286023, 0.17,
0, 0, 0, 0,
-0.6, -0.27, 0.24, 0.39,
-0.47, -0.27, 0.06, 0.2,
0, 0, 0, 0,
-0.91, -0.59, -0.73, -0.23,
-0.57, -0.13, -0.576252727721677, -0.21,
-0.56, -0.29, -0.040, 0.12,
-0.64, -0.28, -0.00895484265292644, 0.11,
-0.52, -0.43, -0.235859464059171, 0.0631315866300978,
0, -0.194773472023435, 0, -0.24,
0, -0.854416534276379, 0, 0.6,
-0.437992277698594, -0.388518934646472, 0.37, 0.299550285605933,
-0.79, -0.468073125742265, -0.0662579798400606, 0.20,
-0.40, -0.44, -0.41, -0.11,
-0.41, -0.37, -0.27, 0.050,
-0.739022273362575, -0.30, -0.701934483299758, -0.14,
0, -1.32,0,1.62,
0, 0, -1.8, 0,
0, 0, 0, 0,
0, 0.293, 0, -0.197
), ncol = 4, byrow = TRUE)
constants[3,1] <- log10(10^(-0.9 - pH) / (10^(-pkc_consts[["asp"]]) + 10^(-pH)) + 10^(0.9 - pkc_consts[["asp"]]) / (10^(-pkc_consts[["asp"]]) + 10^(-pH)))
constants[3,2] <- log10(10^(-0.12 - pH) / (10^(-pkc_consts[["asp"]]) + 10^(-pH)) + 10^(0.58 - pkc_consts[["asp"]]) / (10^(-pkc_consts[["asp"]]) + 10^(-pH)))
constants[3,3] <- log10(10^(0.69 - pH) / (10^(-pkc_consts[["asp"]]) + 10^(-pH)) + 10^(-0.3 - pkc_consts[["asp"]]) / (10^(-pkc_consts[["asp"]]) + 10^(-pH)))
constants[3,4] <- log10(10^(0.6 - pH) / (10^(-pkc_consts[["asp"]]) + 10^(-pH)) + 10^(-0.18 - pkc_consts[["asp"]]) / (10^(-pkc_consts[["asp"]]) + 10^(-pH)))
constants[9,1] <- log10(10^(-0.6 - pH) / (10^(-pkc_consts[["glu"]]) + 10^(-pH)) + 10^(-0.9 - pkc_consts[["glu"]]) / (10^(-pkc_consts[["glu"]]) + 10^(-pH)))
constants[9,2] <- log10(10^(-0.27 - pH) / (10^(-pkc_consts[["glu"]]) + 10^(-pH)) + 10^(0.31 - pkc_consts[["glu"]]) / (10^(-pkc_consts[["glu"]]) + 10^(-pH)))
constants[9,3] <- log10(10^(0.24 - pH) / (10^(-pkc_consts[["glu"]]) + 10^(-pH)) + 10^(-0.51 - pkc_consts[["glu"]]) / (10^(-pkc_consts[["glu"]]) + 10^(-pH)))
constants[9,4] <- log10(10^(0.39 - pH) / (10^(-pkc_consts[["glu"]]) + 10^(-pH)) + 10^(-0.15 - pkc_consts[["glu"]]) / (10^(-pkc_consts[["glu"]]) + 10^(-pH)))
constants[12,1] <- log10(10^(-0.8 - pH) / (10^(-pkc_consts[["his"]]) + 10^(-pH)) + 10^(-pkc_consts[["his"]]) / (10^(-pkc_consts[["his"]]) + 10^(-pH)))
constants[12,2] <- log10(10^(-0.51 - pH) / (10^(-pkc_consts[["his"]]) + 10^(-pH)) + 10^(-pkc_consts[["his"]]) / (10^(-pkc_consts[["his"]]) + 10^(-pH)))
constants[12,3] <- log10(10^(0.8 - pH) / (10^(-pkc_consts[["his"]]) + 10^(-pH)) + 10^(-0.1 - pkc_consts[["his"]]) / (10^(-pkc_consts[["his"]]) + 10^(-pH)))
constants[12,4] <- log10(10^(0.83 - pH) / (10^(-pkc_consts[["his"]]) + 10^(-pH)) + 10^(0.14 - pkc_consts[["his"]]) / (10^(-pkc_consts[["his"]]) + 10^(-pH)))
constants[26,1] <- log10(10^(0.05 - pH) / (10^(-pkc_consts[["glu"]]) + 10^(-pH)) + 10^(0.96 - pkc_consts[["glu"]]) / (10^(-pkc_consts[["glu"]]) + 10^(-pH)))
constants[27,1] <- log10(135.5 / (k_consts[["Ka"]] * 60))
constants[27,3] <- log10(2970000000 / (k_consts[["Kb"]] * 60))
constants
}
get_exchange_rates <- function(sequence,
exchange = "HD",
pH = 9,
temperature = 15,
mol_type = "poly",
if_corr = FALSE) {
assert(checkLogical(if_corr))
assert(checkChoice(mol_type, c("poly", "oligo")))
assert(checkChoice(exchange, c("HD", "DH")))
assert(checkFALSE(temperature == -273.15))
if (exchange == "HD") {
pd <- pH + 0.4 * if_corr
D <- 10^(-pd)
OD <- 10^(pd - 15.05)
} else {
D <- 10 ^ (-pH)
OD <- 10 ^ (pH - 14.17)
}
gas_constant <- 1.9858775
temp_kelvin <- temperature + 273.15
F_consts <- get_F_const(temp_kelvin, gas_constant)
poly_consts <- get_poly_const(mol_type, exchange)
pkc_consts <- get_pkc(temp_kelvin, gas_constant, exchange)
AAs <- strsplit('ARDdNCsGEeQHILKMFPpSTWYVncma', "")[[1]]
constants <- get_exchange_constants(pH, pkc_consts, poly_consts)
sequence <- c("n", sequence, "c")
N <- length(sequence)
if (N <= 2) stop("Length of sequence must be greater than 0")
kcDH = rep(0, N)
for (i in 1:N) {
if (i == 1 || sequence[i] == 'P' || sequence[i] == 'p' || sequence[i] == 'a') {
next()
} else {
if (i %in% c(1, 2, N) || sequence[i] %in% c("P", "a", "p")) {
Fa <- 0
Fb <- 0
} else {
j <- which(AAs == sequence[i])
k <- which(AAs == sequence[i - 1])
if (i <= 3 && i + 1 == N && sequence[i - 1] != "a" && sequence[i] != "m") {
Fa <- 10 ^ (constants[j, 1] + constants[k, 2] + constants[25, 2] + constants[26, 1])
Fb <- 10 ^ (constants[j, 3] + constants[k, 4] + constants[25, 4] + constants[26, 3])
} else {
if (i <= 3 && sequence[i - 1] != "a") {
Fa <- 10 ^ (constants[j, 1] + constants[k, 2] + constants[25, 2])
Fb <- 10 ^ (constants[j, 3] + constants[k, 4] + constants[25, 4])
} else {
if (i + 1 == N && sequence[i] != "m") {
Fa <- 10 ^ (constants[j, 1] + constants[k, 2] + constants[26, 1])
Fb <- 10 ^ (constants[j, 3] + constants[k, 4] + constants[26, 3])
} else {
Fa <- 10^(constants[j, 1] + constants[k, 2])
Fb <- 10^(constants[j, 3] + constants[k, 4])
}
}
}
}
kcDH[i] <- Fa * poly_consts[["Ka"]] * D * F_consts[["Fta"]] +
Fb * poly_consts[["Kb"]] * OD * F_consts[["Ftb"]] +
Fb * poly_consts[["Kw"]] * F_consts[["Ftw"]]
}
}
kcDH[2:(N - 1)]
}
|
knitr::opts_chunk$set(tidy = FALSE, comment = "
library(NGLVieweR)
NGLVieweR("7CID") %>%
addRepresentation("cartoon")
benz <- "
702
-OEChem-02271511112D
9 8 0 0 0 0 0 0 0999 V2000
0.5369 0.9749 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0
1.4030 0.4749 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
2.2690 0.9749 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0
1.8015 0.0000 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
1.0044 0.0000 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
1.9590 1.5118 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
2.8059 1.2849 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
2.5790 0.4380 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
0.0000 0.6649 0.0000 H 0 0 0 0 0 0 0 0 0 0 0 0
1 2 1 0 0 0 0
1 9 1 0 0 0 0
2 3 1 0 0 0 0
2 4 1 0 0 0 0
2 5 1 0 0 0 0
3 6 1 0 0 0 0
3 7 1 0 0 0 0
3 8 1 0 0 0 0
M END
> <ID>
00001
> <DESCRIPTION>
Solvent produced by yeast-based fermentation of sugars.
$$$$
"
NGLVieweR(benz, format="sdf") %>%
addRepresentation("ball+stick")
NGLVieweR("7CID") %>%
addRepresentation("cartoon",
param = list(colorScheme = "residueindex")
) %>%
addRepresentation("ball+stick",
param = list(
sele = "233-248",
colorValue = "red",
colorScheme = "element"
)
) %>%
addRepresentation("surface",
param = list(
colorValue = "white",
opacity = 0.1
)
)
NGLVieweR("7CID") %>%
stageParameters(backgroundColor = "white", zoomSpeed = 1) %>%
addRepresentation("cartoon",
param = list(name = "cartoon", colorScheme = "residueindex")
) %>%
setSpin()
NGLVieweR("7CID") %>%
addRepresentation("cartoon") %>%
addRepresentation("ball+stick", param = list(
colorScheme = "element",
colorValue = "yellow",
sele = "20"
)) %>%
addRepresentation("label",
param = list(
sele = "20",
labelType = "format",
labelFormat = "[%(resname)s]%(resno)s",
labelGrouping = "residue",
color = "white",
fontFamiliy = "sans-serif",
xOffset = 1,
yOffset = 0,
zOffset = 0,
fixedSize = TRUE,
radiusType = 1,
radiusSize = 1.5,
showBackground = FALSE
)
)
NGLVieweR("7CID") %>%
addRepresentation("cartoon") %>%
addRepresentation("ball+stick",
param = list(
colorScheme = "element",
colorValue = "yellow",
sele = "20"
)
) %>%
addRepresentation("label",
param = list(
sele = "20",
labelType = "format",
labelFormat = "[%(resname)s]%(resno)s",
labelGrouping = "residue",
color = "white",
xOffset = 1,
fixedSize = TRUE,
radiusType = 1,
radiusSize = 1.5
)
) %>%
zoomMove(
center = "20",
zoom = "20",
duration = 0,
z_offSet = -20
)
NGLVieweR("3RY2") %>%
addRepresentation("cartoon") %>%
addRepresentation("ball+stick",
param = list(
name = "biotin",
colorvalue = "grey",
colorScheme = "element",
sele = "5001"
)
) %>%
addRepresentation("ball+stick",
param = list(
name = "interacting",
colorScheme = "element",
colorValue = "green",
sele = "23 or 27 or 43 or 45 or 128"
)
) %>%
zoomMove(
center = "27:B",
zoom = "27:B",
z_offSet = -20
) %>%
addRepresentation("contact",
param = list(
name = "contact",
sele = "5001 or 23 or 27 or 43 or 45 or 128",
filterSele = list("23 or 27 or 45 or 128", "5001"),
labelVisible = TRUE,
labelFixedSize = FALSE,
labelUnit = "angstrom",
labelSize = 2
)
)
knitr::include_graphics("../man/figures/basic_shiny.PNG")
knitr::include_graphics("../man/figures/API_shiny.PNG")
|
test_that("informative error on old FACTS files", {
skip_paths()
facts_file <- get_facts_file_example("old.facts")
expect_error(
run_flfll(facts_file),
regexp = "version of your FACTS file"
)
})
test_that("run_flfll() does not share most arg names with engines", {
flfll <- names(formals(run_flfll))
x <- intersect(flfll, names(formals(run_engine_contin)))
expect_equal(x, "verbose")
})
test_that("run_flfll() on broken.facts", {
skip_paths()
facts_file <- get_facts_file_example("broken.facts")
expect_error(
run_flfll(facts_file = facts_file, verbose = FALSE),
regexp = "failed with exit code"
)
})
test_that("run_flfll() on contin.facts with default args", {
skip_paths()
facts_file <- get_facts_file_example("contin.facts")
out <- run_flfll(facts_file = facts_file, verbose = FALSE)
param_files <- get_param_files(out)
expect_equal(length(param_files), 4L)
expect_true(all(file.exists(param_files)))
expect_true(all(grepl("nuk1_e\\.param", param_files)))
})
test_that("run_flfll() on contin.facts with more args", {
skip_paths()
out <- run_flfll(
facts_file = get_facts_file_example("contin.facts"),
output_path = tempfile(),
log_path = tempfile(),
n_burn = 4,
n_mcmc = 4,
n_weeks_files = 4,
n_patients_files = 4,
n_mcmc_files = 4,
n_mcmc_thin = 2,
flfll_seed = 1,
flfll_offset = 1,
verbose = FALSE
)
param_files <- get_param_files(out)
expect_equal(length(param_files), 4L)
expect_true(all(file.exists(param_files)))
expect_true(all(grepl("nuk1_e\\.param", param_files)))
})
|
brplus <- function(mdata,
base.algorithm = getOption("utiml.base.algorithm", "SVM"),
..., cores = getOption("utiml.cores", 1),
seed = getOption("utiml.seed", NA)) {
if (!is(mdata, "mldr")) {
stop("First argument must be an mldr object")
}
if (cores < 1) {
stop("Cores must be a positive value")
}
brpmodel <- list(labels = rownames(mdata$labels), call = match.call())
freq <- mdata$labels$freq
names(freq) <- brpmodel$labels
brpmodel$freq <- sort(freq)
brpmodel$initial <- br(mdata, base.algorithm, ..., cores = cores, seed = seed)
labeldata <- as.data.frame(mdata$dataset[mdata$labels$index])
for (i in seq(ncol(labeldata))) {
labeldata[, i] <- factor(labeldata[, i], levels=c(0, 1))
}
labels <- utiml_rename(seq(mdata$measures$num.labels), brpmodel$labels)
brpmodel$models <- utiml_lapply(labels, function(li) {
basedata <- utiml_create_binary_data(mdata, brpmodel$labels[li],
labeldata[-li])
dataset <- utiml_prepare_data(basedata, "mldBRP", mdata$name, "brplus",
base.algorithm)
utiml_create_model(dataset, ...)
}, cores, seed)
class(brpmodel) <- "BRPmodel"
brpmodel
}
predict.BRPmodel <- function(object, newdata,
strategy = c("Dyn", "Stat", "Ord", "NU"),
order = list(),
probability = getOption("utiml.use.probs", TRUE),
..., cores = getOption("utiml.cores", 1),
seed = getOption("utiml.seed", NA)) {
if (!is(object, "BRPmodel")) {
stop("First argument must be an BRPmodel object")
}
strategy <- match.arg(strategy)
labels <- object$labels
if (strategy == "Ord") {
if (!utiml_is_equal_sets(order, labels)) {
stop("Invalid order (all labels must be on the chain)")
}
}
if (cores < 1) {
stop("Cores must be a positive value")
}
if (!anyNA(seed)) {
set.seed(seed)
}
newdata <- utiml_newdata(newdata)
initial.preds <- predict.BRmodel(object$initial, newdata, probability=FALSE,
..., cores=cores, seed=seed)
labeldata <- as.data.frame(as.bipartition(initial.preds))
for (i in seq(ncol(labeldata))) {
labeldata[, i] <- factor(labeldata[, i], levels=c(0, 1))
}
if (strategy == "NU") {
indices <- utiml_rename(seq_along(labels), labels)
predictions <- utiml_lapply(indices, function(li) {
utiml_predict_binary_model(object$models[[li]],
cbind(newdata, labeldata[, -li]), ...)
}, cores, seed)
}
else {
order <- switch (strategy,
Dyn = names(sort(apply(as.probability(initial.preds), 2, mean))),
Stat = names(object$freq),
Ord = order
)
predictions <- list()
for (labelname in order) {
other.labels <- !labels %in% labelname
model <- object$models[[labelname]]
data <- cbind(newdata, labeldata[, other.labels, drop = FALSE])
predictions[[labelname]] <- utiml_predict_binary_model(model, data, ...)
labeldata[, labelname] <- factor(predictions[[labelname]]$bipartition,
levels=c(0, 1))
}
}
utiml_predict(predictions[labels], probability)
}
print.BRPmodel <- function(x, ...) {
cat("Classifier BRplus (also called BR+)\n\nCall:\n")
print(x$call)
cat("\n", length(x$models), "Models (labels):\n")
print(names(x$models))
}
|
pklogit <-
function(y, auc, doses, x, theta, prob = 0.9, options = list(nchains = 4, niter = 4000, nadapt = 0.8),
betapriors = c(10, 10000, 20, 10), thetaL=NULL, p0 = NULL, L = NULL, deltaAUC = NULL, CI = TRUE){
checking1 <- function(x,target,error){
sum(x>(target+error))/length(x)
}
f_logit <- function(v,lambda,parmt){
invlogit(-lambda[1]+lambda[2]*v)*dnorm(v,parmt[1],parmt[2])
}
f2_logit <- function(v, lambda1, lambda2, parmt1, parmt2){
invlogit(-lambda1+lambda2*v)*dnorm(v,parmt1,parmt2)
}
num <- length(x)
dose1 <- cbind(rep(1,num), log(doses[x]))
mu1 <- -log(betapriors[1])
data_s <- list(N=num, auc=log(auc), dose=dose1, mu = mu1, beta0=betapriors[2])
sm_lrauc <- stanmodels$reg_auc
reg1 <- sampling(sm_lrauc, data=data_s, iter=options$niter, chains=options$nchains,
control = list(adapt_delta = options$nadapt))
a1 = get_posterior_mean(reg1)
sampl1 <- extract(reg1)
beta1 <- a1[1:2,options$nchains+1]
nu <- a1[3,options$nchains+1]
auc1 <- log(auc)
data_s <- list(N=num,y=y,dose=auc1, beta2mean = betapriors[3], beta3mean = betapriors[4])
sm_lr <- stanmodels$logit_reg_pklogit
reg2 <- sampling(sm_lr, data=data_s, iter=options$niter, chains=options$nchains, control = list(adapt_delta = options$nadapt))
a2 = get_posterior_mean(reg2)
sampl2 <- extract(reg2)
Beta <- a2[1:2,options$nchains+1]
pstim <- NULL
for (o in 1:length(doses)){
parmt = c(a1[1,options$nchains+1] + a1[2,options$nchains+1]*log(doses[o]),a1[3,options$nchains+1])
pstim <- c(pstim, integrate(f_logit,-Inf,Inf, lambda=a2[1:2,options$nchains+1], parmt=parmt)$value)
}
pstim_sum <- matrix(0, ncol = options$nchains*options$niter/2, nrow = length(doses))
p_sum <- NULL
parmt1 = sampl1$b[,1] + sampl1$b[,2]*log(doses[1])
parmt2 = sampl1$sigma
for (i in 1:ncol(pstim_sum)){
pstim_sum[1,i] <- integrate(f2_logit,-Inf, Inf, lambda1=sampl2$beta2[i], lambda2 = sampl2$beta3[i],
parmt1=parmt1[i], parmt2 = parmt2[i])$value
}
pstop <- checking1(pstim_sum[1,], target=theta, error=0)
stoptox <- (pstop >= prob)
stoptrial <- stoptox
if(CI == "TRUE"){
p_sum <- summary(pstim_sum[1, ])
for (o in 2:length(doses)){
parmt1 = sampl1$b[,1] + sampl1$b[,2]*log(doses[o])
parmt2 = sampl1$sigma
for (i in 1:ncol(pstim_sum)){
pstim_sum[o,i] <- integrate(f2_logit,-Inf, Inf, lambda1=sampl2$beta2[i], lambda2 = sampl2$beta3[i],
parmt1=parmt1[i], parmt2 = parmt2[i])$value
}
p_sum <- rbind(p_sum, summary(pstim_sum[o,]))
}
}else{
p_sum <- NULL
}
if (stoptrial){
newDose = NA
message("The trial stopped based on the stopping rule \n \n")
}else{
newDose <- order((abs(pstim-theta)))[1]
}
parameters <- c(beta1, nu, Beta)
names(parameters) <- c("beta0", "beta1", "nu", "beta2", "beta3")
list(newDose=newDose, pstim = pstim, p_sum=p_sum, parameters = parameters)
}
|
tar_test("tar_make_future() works", {
skip_if_not_installed("future")
tar_script(list(tar_target(x, "x")))
tar_make_future(
callr_arguments = list(show = FALSE),
reporter = "silent"
)
expect_equal(tar_read(x), "x")
})
tar_test("tar_make_future() can use tidyselect", {
skip_if_not_installed("future")
tar_script(
list(
tar_target(y1, 1 + 1),
tar_target(y2, 1 + 1),
tar_target(z, y1 + y2)
)
)
tar_make_future(
names = starts_with("y"),
reporter = "silent",
callr_arguments = list(show = FALSE)
)
out <- sort(list.files(file.path("_targets", "objects")))
expect_equal(out, sort(c("y1", "y2")))
})
tar_test("nontrivial globals with global environment", {
skip_on_cran()
skip_if_not_installed("future")
skip_if_not_installed("future.callr")
tar_script({
future::plan(future.callr::callr)
f <- function(x) {
g(x) + 1L
}
g <- function(x) {
x + 1L
}
list(
tar_target(x, 1),
tar_target(y, f(x))
)
})
tar_make_future(
reporter = "silent",
callr_arguments = list(spinner = FALSE)
)
expect_equal(tar_read(y), 3L)
})
tar_test("nontrivial globals with non-global environment", {
skip_on_cran()
skip_if_not_installed("future")
skip_if_not_installed("future.callr")
tar_script({
future::plan(future.callr::callr)
envir <- new.env(parent = globalenv())
evalq({
f <- function(x) {
g(x) + 1L
}
g <- function(x) {
x + 1L
}
}, envir = envir)
tar_option_set(envir = envir)
list(
tar_target(x, 1),
tar_target(y, f(x))
)
})
tar_make_future(
reporter = "silent",
callr_arguments = list(spinner = FALSE)
)
expect_equal(tar_read(y), 3L)
})
tar_test("custom script and store args", {
skip_on_cran()
skip_if_not_installed("future")
expect_equal(tar_config_get("script"), path_script_default())
expect_equal(tar_config_get("store"), path_store_default())
tar_script(
tar_target(x, TRUE),
script = "example/script.R"
)
tar_make_future(
script = "example/script.R",
store = "example/store",
callr_function = NULL
)
expect_false(file.exists("_targets.yaml"))
expect_equal(tar_config_get("script"), path_script_default())
expect_equal(tar_config_get("store"), path_store_default())
expect_false(file.exists(path_script_default()))
expect_false(file.exists(path_store_default()))
expect_true(file.exists("example/script.R"))
expect_true(file.exists("example/store"))
expect_true(file.exists("example/store/meta/meta"))
expect_true(file.exists("example/store/objects/x"))
expect_equal(readRDS("example/store/objects/x"), TRUE)
tar_config_set(script = "x")
expect_equal(tar_config_get("script"), "x")
expect_true(file.exists("_targets.yaml"))
})
tar_test("custom script and store args with callr function", {
skip_on_cran()
skip_if_not_installed("future")
expect_equal(tar_config_get("script"), path_script_default())
expect_equal(tar_config_get("store"), path_store_default())
tar_script(
tar_target(x, TRUE),
script = "example/script.R"
)
tar_make_future(
script = "example/script.R",
store = "example/store",
reporter = "silent"
)
expect_false(file.exists("_targets.yaml"))
expect_equal(tar_config_get("script"), path_script_default())
expect_equal(tar_config_get("store"), path_store_default())
expect_false(file.exists(path_script_default()))
expect_false(file.exists(path_store_default()))
expect_true(file.exists("example/script.R"))
expect_true(file.exists("example/store"))
expect_true(file.exists("example/store/meta/meta"))
expect_true(file.exists("example/store/objects/x"))
expect_equal(readRDS("example/store/objects/x"), TRUE)
tar_config_set(script = "x")
expect_equal(tar_config_get("script"), "x")
expect_true(file.exists("_targets.yaml"))
})
tar_test("bootstrap builder for shortcut", {
skip_on_cran()
tar_script({
list(
tar_target(w, 1L),
tar_target(x, w),
tar_target(y, 1L),
tar_target(z, x + y)
)
})
tar_make_future(callr_function = NULL)
expect_equal(tar_read(z), 2L)
tar_script({
list(
tar_target(w, 1L),
tar_target(x, w),
tar_target(y, 1L),
tar_target(z, x + y + 1L)
)
})
tar_make_future(names = "z", shortcut = TRUE, callr_function = NULL)
expect_equal(tar_read(z), 3L)
progress <- tar_progress()
expect_equal(nrow(progress), 1L)
expect_equal(progress$name, "z")
expect_equal(progress$progress, "built")
})
|
IFFChunk.IFF.ILBM <- function(x, ...) {
if ("matrix" %in% class(x)) stop(paste("This IFF chunk interpretation is probably based on",
"an ANIM DLTA chunk. It can't be converted back into an IFFChunk object."))
rasterToIFF(x, ...)@chunk.data[[1]]
}
IFFChunk.IFF.CMAP <- function(x, ...) {
result <- colourToAmigaRaw(x, n.bytes = "3", ...)
return(new("IFFChunk", chunk.type = "CMAP", chunk.data = list(result)))
}
IFFChunk.IFF.BMHD <- function(x, ...) {
compr <- which(c("cmpNone", "cmpByteRun1") == x$Compression) - 1
if (length(compr) == 0) compr <- 0
mask <- which(c("mskNone", "mskHasMask", "mskHasTransparentColour", "mskLasso") == x$Masking) - 1
if (length(mask) == 0) mask <- 0
result <- c(.amigaIntToRaw(c(x$w, x$h), 16, F),
.amigaIntToRaw(c(x$x, x$y), 16, T),
.amigaIntToRaw(c(x$nPlanes, mask, compr), 8, F),
as.raw(x$pad)[[1]],
.amigaIntToRaw(x$transparentColour, 16, F),
.amigaIntToRaw(c(x$xAspect, x$yAspect), 8, F),
.amigaIntToRaw(c(x$pageWidth, x$pageHeight), 16, F))
return(new("IFFChunk", chunk.type = "BMHD", chunk.data = list(result)))
}
IFFChunk.IFF.CAMG <- function(x, ...) {
return(.inverseViewPort(x$display.mode, x$monitor))
}
IFFChunk.IFF.CRNG <- function(x, ...) {
flag <- which(c("RNG_OFF", "RNG_ACTIVE", "RNG_REVERSE") == x$flags) - 1
if (length(flag) == 0) flag <- 0
dat <- c(
x$padding,
.amigaIntToRaw(round(x$rate*(2^14)/60), 16, F),
.amigaIntToRaw(flag, 16, F),
.amigaIntToRaw(c(x$low, x$high), 8, F)
)
result <- new("IFFChunk", chunk.type = "CRNG", chunk.data = list(dat))
return(result)
}
IFFChunk.IFF.ANIM <- function(x, ...) {
rasterToIFF(x, ...)@chunk.data[[1]]
}
IFFChunk.IFF.ANHD <- function(x, ...) {
oper <- which(x$operation == c("standard", "XOR", "LongDeltaMode", "ShortDeltaMode", "GeneralDeltamode", "ByteVerticalCompression", "StereoOp5", "ShortLongVerticalDeltaMode")) - 1
if (length(oper) == 0) oper <- 0
result <- c(.amigaIntToRaw(oper, 8, F),
.bitmapToRaw(x$mask, F, F),
.amigaIntToRaw(c(x$w, x$h), 16, F),
.amigaIntToRaw(c(x$x, x$y), 16, T),
.amigaIntToRaw(c(x$abstime, x$reltime), 32, T),
.amigaIntToRaw(x$interleave, 8, F),
x$pad0,
.bitmapToRaw(x$flags, T, T),
x$pad1
)
result <- new("IFFChunk", chunk.type = "ANHD", chunk.data = list(result))
return(result)
}
IFFChunk.IFF.DLTA <- function(x, ...) {
return(new("IFFChunk", chunk.type = "DLTA", chunk.data = list(x)))
}
IFFChunk.IFF.DPAN <- function(x, ...) {
result <- c(.amigaIntToRaw(c(x$version, x$nframes), 16, F),
.bitmapToRaw(x$flags, T, T)
)
result <- new("IFFChunk", chunk.type = "DPAN", chunk.data = list(result))
return(result)
}
as.raster.IFFChunk <- function(x, ...) {
if ([email protected] == "FORM") {
result <- lapply([email protected], function(y){
if ([email protected] == "ILBM") return(as.raster(y))
if ([email protected] == "ANIM") return(interpretIFFChunk(y))
})
if (length(result) == 1) result <- result[[1]]
return (result)
} else if ([email protected] == "ILBM") {
sub.chunks <- unlist(lapply([email protected], function(y) [email protected]))
if (!("BMHD" %in% sub.chunks)) stop("No bitmap header present. Can't interpret bitmap.")
if (!("BODY" %in% sub.chunks)) stop("No BODY chunk present. Can't convert the bitmap into a raster.")
bm.header <- interpretIFFChunk(getIFFChunk(x, "BMHD"))
if (!("CAMG" %in% sub.chunks)) {
bm.vp.mode <- NULL
warning("No Amiga viewport available, interpretation possibly incorrect.")
} else {
bm.vp.mode <- interpretIFFChunk(getIFFChunk(x, "CAMG"))
bm.vp.mode <- .display.properties(bm.vp.mode$display.mode, bm.vp.mode$monitor)
}
bm.palette <- grDevices::gray(round(seq(0, 15, length.out = 2^bm.header$nPlanes))/15)
try(bm.palette <- interpretIFFChunk(getIFFChunk(x, "CMAP")), silent = T)
if (!is.null(bm.vp.mode) && bm.vp.mode$is.halfbright) {
bm.palette <- c(bm.palette,
substr(grDevices::adjustcolor(bm.palette, 1, 0.5, 0.5, 0.5), 1, 7))
}
if (bm.header$Compression == "cmpByteRun1") {
bm <- unPackBitmap(interpretIFFChunk(getIFFChunk(x, "BODY")))
} else if (bm.header$Compression == "cmpNone") {
bm <- interpretIFFChunk(getIFFChunk(x, "BODY"))
} else {
stop("Bitmap data is compressed with unsupported algorithm.")
}
np <- bm.header$nPlanes
if (length(bm.palette) < (2^np)) {
if (bm.vp.mode$is.HAM) np <- ifelse(np == 8, 6, 5)
bm.palette <- c(bm.palette, rep("
}
rm(np)
if (bm.header$Masking == "mskHasTransparentColour") {
transparent <- bm.header$transparentColour + 1
bm.palette[transparent] <- grDevices::adjustcolor(bm.palette[transparent],
alpha.f = 0)
}
attr.palette <- NULL
if ("palette" %in% names(list(...)) && is.null(list(...)$palette)){
attr.palette <- bm.palette
bm.palette <- NULL
}
if (bm.vp.mode$is.HAM) {
result <- bitmapToRaster(bm, bm.header$w, bm.header$h, bm.header$nPlanes, NULL)
if (!is.null(bm.palette)) {
result <- .indexToHAMraster(result, bm.header$nPlanes, bm.palette, bm.header$transparentColour)
}
} else {
result <- bitmapToRaster(bm, bm.header$w, bm.header$h, bm.header$nPlanes, bm.palette)
}
if (bm.vp.mode$is.HAM) {
attributes(result)[["mode"]] <- ifelse(bm.header$nPlanes == 8, "HAM8", "HAM6")
}
attributes(result)[["asp"]] <- bm.vp.mode$aspect.y/bm.vp.mode$aspect.x
if (!is.null(attr.palette)) attributes(result)[["palette"]] <- attr.palette
return(result)
} else if ([email protected] == "ANIM") {
return(interpretIFFChunk(x))
} else {
stop(sprintf("IFF chunk of type %s cannot be converted into a raster.", [email protected]))
}
}
plot.IFF.ILBM <- function(x, y, ...) {
if ("matrix" %in% class(x)) {
pal <- grDevices::gray(seq(0, 1, length.out = max(round(abs(x)))))
asp <- attributes(x)$asp
x <- as.raster(apply(x, 2, function(z) pal[round(abs(z)) + 1]))
attributes(x)$asp <- asp
}
class(x) <- "raster"
if ("asp" %in% names(list(...)))
graphics::plot(x, y, ...) else
graphics::plot(x, y, asp = attributes(x)$asp, ...)
}
plot.IFF.ANIM <- function(x, y, ...) {
invisible(lapply(x, plot.IFF.ILBM, ...))
}
rasterToIFF <- function(x,
display.mode = as.character(AmigaFFH::amiga_display_modes$DISPLAY_MODE),
monitor = as.character(AmigaFFH::amiga_monitors$MONITOR_ID),
anim.options,
...) {
display.mode <- match.arg(display.mode)
monitor <- match.arg(monitor)
pars <- list(...)
if (is.null(pars$depth)) pars$depth <- 3
if (is.null(pars$colour.depth)) pars$colour.depth <- "12 bit"
if (grepl("EHB|EXTRAHALFBRITE", display.mode)) stop("Sorry, 'extra halfbrite' modes is currently not implemented")
special.mode <- "none"
if (pars$depth %in% c("HAM6", "HAM8")) {
if (!grepl("HAM", display.mode)) warning("Display mode should be a HAM mode, when 'depth' is set to 'HAM6' or 'HAM8'. Display mode is corrected to 'HAM_KEY'.")
display.mode <- "HAM_KEY"
}
if (grepl("HAM", display.mode)) {
if (pars$depth %in% c("HAM6", "HAM8")) {
special.mode <- pars$depth
pars$colour.depth <- ifelse(special.mode == "HAM6", "12 bit", "24 bit")
pars$depth <- ifelse(special.mode == "HAM6", 6, 8)
} else {
special.mode <- ifelse(pars$colour.depth == "24 bit", "HAM8", "HAM6")
}
}
if (is.list(x)) {
if (length(x) < 2) stop("When x is a list of rasters, it will be converted to an anim. x should have a length of at least 2.")
if (any(unlist(lapply(x, function(y) !any(c("raster", "matrix") %in% class(y)) || !all(.is.colour(y))))))
stop("All elements of x should be a grDevices raster or a matrix of colours")
if ("indexing" %in% names(list(...))) {
x <- list(...)$indexing(x = x, length.out = ifelse(special.mode %in% c("HAM6", "HAM8"),
special.mode,
2^pars$depth))
} else {
x <- index.colours(x, length.out = ifelse(special.mode %in% c("HAM6", "HAM8"),
special.mode,
2^pars$depth))
}
pal <- attributes(x)$palette
trans <- attributes(x)$transparent
anhd <- lapply(1:(length(x) + 2), function(z) {
anhdz <- list(
operation = "ByteVerticalCompression",
mask = rep(F, 8),
w = dim(x[[1]])[[2]],
h = dim(x[[1]])[[1]],
x = 0,
y = 0,
abstime = z*2,
reltime = 2,
interleave = 0,
pad0 = raw(1),
flags = rep(F, 32),
pad1 = raw(16)
)
class(anhdz) <- "IFF.ANHD"
anhdz <- IFFChunk(anhdz)
anhdz
})
frame1 <- .indexToBitmap(x[[1]], pars$depth, T)
frame1 <- .bitmapToILBM(frame1, dim(x[[1]]), display.mode, monitor, pars$depth, pars$colour.depth, pal, trans)
dpan <- list(version = 4, nframes = length(x), flags = rep(F, 32))
class(dpan) <- "IFF.DPAN"
[email protected] <- c([email protected][1],
anhd[[1]],
[email protected][2],
IFFChunk(dpan),
[email protected][3:4])
frame1 <- new("IFFChunk", chunk.type = "FORM", chunk.data = list(frame1))
x <- .byteVerticalCompression(x, pars$depth)
x[-1] <- lapply(2:length(x), function(y) {
res <- new("IFFChunk", chunk.type = "ILBM", chunk.data = list(anhd[[y]], x[[y]]))
res <- new("IFFChunk", chunk.type = "FORM", chunk.data = list(res))
return(res)
})
x[[1]] <- frame1
x <- new("IFFChunk", chunk.type = "ANIM", chunk.data = x)
x <- new("IFFChunk", chunk.type = "FORM", chunk.data = list(x))
return(x)
}
if (!any(c("raster", "matrix") %in% class(x)) || !all(.is.colour(x))) stop("x should be a raster object or a matrix of colours.")
if ("depth" %in% names(list(...))) {
bm <- rasterToBitmap(x, ...)
} else {
bm <- rasterToBitmap(x, depth = ifelse(special.mode %in% c("HAM6", "HAM8"),
special.mode,
pars$depth), ...)
}
pal <- attributes(bm)$palette
transparent <- attributes(bm)$transparent
ilbm <- .bitmapToILBM(bm, dim(x), display.mode, monitor, pars$depth, pars$colour.depth, pal, transparent)
form <- new("IFFChunk", chunk.type = "FORM", chunk.data = list(ilbm))
return(form)
}
.byteVerticalDecompression <- function(dlta, w, h, interleave, use.xor, previous = NULL) {
interleave[interleave == 0] <- 2
pointers <- .rawToAmigaInt(dlta[1:(16*4)], 32, F)[1:8]
if (all(pointers == 0)) {
if (is.null(previous) || length(previous) == 0) {
result <- matrix(0, h, w)
class(result) <- c("IFF.ILBM", "IFF.ANY", class(result))
return(result)
} else {
prev <- length(previous) - interleave + 1
prev[prev < 1] <- 1
return(previous[[prev]])
}
}
bitmap.layers <- which(pointers > 1)
bitmap.layers <- 1:bitmap.layers[bitmap.layers == max(bitmap.layers)]
bitmap.layers <- pointers[bitmap.layers]
result <- lapply(1:length(bitmap.layers), function(y) {
offs <- bitmap.layers[[y]]
prev <- NULL
if (!is.null(previous)) {
prev <- length(previous) - (interleave - 1)
if (prev < 1) prev <- 1
prev <- previous[[prev]]
prev <- apply(prev, 2, function(z) {
as.logical(floor(z/(2^(y - 1))) %% 2)
})
prev <- cbind(prev, matrix(F, h, w - ncol(prev)))
}
if (offs == 0) {
if (is.null(prev)) {
return (matrix(0, h, w))
} else return(prev)
}
layer <- NULL
for (i in 1:(w/8)) {
op.count <- .rawToAmigaInt(dlta[1 + offs], 8, F)
offs <- offs + 1
row.result <- matrix(F, 0, 8)
if (op.count > 0) {
for (j in 1:op.count) {
op <- .rawToAmigaInt(dlta[1 + offs], 8, F)
offs <- offs + 1
if (op == 0) {
rep.count <- .rawToAmigaInt(dlta[1 + offs], 8, F)
rep.dat <- matrix(rep(
as.logical(.rawToBitmap(dlta[2 + offs], T, F)),
rep.count
),
ncol = 8, byrow = T)
if (use.xor)
rep.dat <- xor(prev[nrow(row.result) + 1:nrow(rep.dat), i*8 + (-7:0)], rep.dat)
row.result <- rbind(row.result, rep.dat)
offs <- offs + 2
} else if (op < 0x80) {
if (is.null(previous) || (is.list(previous) && length(previous) == 0)) {
row.result <- rbind(row.result, matrix(F, nrow = op, ncol = 8))
} else {
nroff <- nrow(row.result) + 1
if (length(nroff) == 0) nroff <- 1
row.result <- rbind(row.result, prev[nroff + 0:(op - 1), i*8 + (-7:0)])
}
} else {
op.cor <- op - 0x80
temp <- as.logical(.rawToBitmap(dlta[(1 + offs):(offs + op.cor)], T, F))
temp <- matrix(temp, ncol = 8, byrow = T)
if (use.xor)
temp <- xor(prev[nrow(row.result) + 1:nrow(temp), i*8 + (-7:0)], temp)
row.result <- rbind(row.result, temp)
offs <- offs + op.cor
}
}
}
if (nrow(row.result) == 0 || op.count == 0) {
if (is.null(previous)) {
row.result <- matrix(F, ncol = 8, nrow = h)
} else {
row.result <- prev[1:h, i*8 + (-7:0)]
}
}
if (is.null(dim(row.result)) || !all(dim(row.result) == c(h, 8))) stop("Could not decode the bitmap correctly. If the bitmap was encoded with the AmigaFFH package, please contact the package author to get this fixed.")
layer <- cbind(layer, row.result)
}
layer <- apply(layer, 2, function(z) (2^(y - 1))*as.numeric(z))
return(layer)
})
result <- Reduce("+", result)
class(result) <- c("IFF.ILBM", "IFF.ANY", class(result))
return(result)
}
.byteVerticalCompression <- function(x, depth) {
x <- c(x, x[1:2])
h <- dim(x[[1]])[[1]]
w <- dim(x[[1]])[[2]]
x <- lapply(x, function(y) cbind(y, matrix(0, nrow = h, ncol = (-w %% 16))))
wbm <- w + (-w %%16)
result <- vector("list", length(x))
for (i in 2:length(x)) {
prev.id <- i - 2
if (prev.id < 1) prev.id <- 1
pointers <- NULL
no.change <- rep(F, 16)
for (j in 1:depth) {
dep.data <- NULL
for (k in 1:(wbm/8)) {
previous.column <- floor((x[[prev.id]][,k*8 + (-7:0)] - 1)/(2^(j - 1))) %% 2
curr.column <- floor((x[[i]][,k*8 + (-7:0)] - 1)/(2^(j - 1))) %% 2
row.similarity <- apply(previous.column == curr.column, 1, all)
run.lengths <- rle(row.similarity)$lengths
run.lengths <- rep(run.lengths, run.lengths)
row.similarity[row.similarity & run.lengths < 3] <- F
cursor <- 1
op.count <- 0
op.data <- NULL
if (!all(row.similarity)) {
while (cursor <= h) {
if (row.similarity[[cursor]]) {
skip <- which(diff(c(row.similarity[cursor:h], F)) != 0)[[1]]
repskip <- floor(skip/127)
op.data <- c(op.data,
.amigaIntToRaw(c(
rep(127, repskip),
skip %% 127), 8, F))
op.count <- op.count + repskip + 1
cursor <- cursor + skip
} else {
dup <- c(T, duplicated(curr.column[cursor:h,, drop = F], fromLast = F)[-1]) & !row.similarity[cursor:h]
dup.run.length <- rle(dup)$lengths
dup.run1 <- dup.run.length[[1]]
dup.run1[dup.run1 > 255] <- 255
dup.run.length <- c(1, dup.run.length[1] - 1, dup.run.length[-1])
dup.run.length <- rep(dup.run.length, dup.run.length)
if (dup.run1 > 3 && length(dup) > 3 && dup[[2]]){
op.data <- c(op.data,
.amigaIntToRaw(c(0, dup.run1), 8, F),
.bitmapToRaw(as.logical(t(curr.column[cursor,, drop = F])),
T, F))
op.count <- op.count + 1
cursor <- cursor + dup.run1
} else {
skip <- which(diff(c(row.similarity[cursor:h] |
c(dup.run.length[-1] > 2 & dup[-1], F), T)) != 0)[[1]]
skip[skip > 127] <- 127
dat <- .bitmapToRaw(as.logical(t(curr.column[cursor:(cursor + skip - 1),, drop = F])),
T, F)
op.data <- c(op.data,
.amigaIntToRaw(skip + 0x80, 8, F),
dat)
cursor <- cursor + skip
op.count <- op.count + 1
}
}
}
}
dep.data <- c(dep.data,
.amigaIntToRaw(op.count, 8, F),
op.data)
}
if (all(dep.data == raw(1))) {
no.change[[j]] <- T
dep.data <- NULL
}
pointers <- c(pointers, length(dep.data))
if (!is.null(dep.data)) result[[i]] <- c(result[[i]], dep.data)
}
pointers <- cumsum(pointers)
ptrs <- rep(0, 16)
ptrs[1:length(pointers)] <- 64 + c(0 , pointers[0:(length(pointers) - 1)])
ptrs[no.change] <- 0
result[[i]] <- c(
.amigaIntToRaw(ptrs, 32, F),
result[[i]]
)
result[[i]] <- new("IFFChunk", chunk.type = "DLTA", chunk.data = list(result[[i]]))
}
return(result)
}
.bitmapToILBM <- function(bm, dim.x, display.mode, monitor, depth, colour.depth, pal, transparent) {
bm <- .bitmapToRaw(bm, T, F)
bm <- matrix(bm, nrow = 2*ceiling(dim.x[[2]]/16), byrow = F)
bm <- c(unlist(apply(bm, 2, packBitmap)))
body <- new("IFFChunk", chunk.type = "BODY", chunk.data = list(bm))
camg <- .inverseViewPort(display.mode, monitor)
disp <- .amigaViewPortModes([email protected][[1]])
disp.prop <- .display.properties(disp$display.mode, disp$monitor)
BMHD <- list(
w = dim.x[2],
h = dim.x[1],
x = 0,
y = 0,
nPlanes = depth,
Masking = ifelse(!is.null(transparent) && !is.na(transparent), "mskHasTransparentColour", "mskNone"),
Compression = "cmpByteRun1",
pad = raw(1),
transparentColour = ifelse(!is.null(transparent) && !is.na(transparent), transparent - 1, 0),
xAspect = disp.prop$aspect.x,
yAspect = disp.prop$aspect.y,
pageWidth = disp.prop$screenwidth,
pageHeight = disp.prop$screenheight
)
class(BMHD) <- "IFF.BMHD"
hdr <- IFFChunk(BMHD)
class(pal) <- "IFF.CMAP"
cmap <- IFFChunk(pal, colour.depth = colour.depth)
ilbm <- new("IFFChunk", chunk.type = "ILBM", chunk.data = list(
hdr, cmap, camg, body
))
return(ilbm)
}
.indexToHAMraster <- function(x, depth, palette, transparentColour) {
control.mask <- bitwShiftL(3, depth - 2)
max_color <- ifelse(depth == 8, 255, 15)
color_divisor <- ifelse(depth == 8, 1, 17)
color_multi <- ifelse(depth == 8, 255/63, 1)
x <- apply(x, 1, function(y) {
control.flags <- 3*bitwAnd(y, control.mask)/control.mask
y.shift <- (y - control.mask*control.flags/3)
z <- rep(NA, length(y))
z[control.flags == 0] <- palette[y.shift[control.flags == 0] + 1]
for (i in 1:length(y)) {
if (is.na(z[i])) {
z0 <- z[i - 1]
if (length(z0) == 0) z0 <- palette[transparentColour + 1]
cl <- grDevices::col2rgb(z0)
z[i] <- grDevices::rgb(
ifelse(control.flags[i] == 2, color_multi*y.shift[i], cl["red",]/color_divisor),
ifelse(control.flags[i] == 3, color_multi*y.shift[i], cl["green",]/color_divisor),
ifelse(control.flags[i] == 1, color_multi*y.shift[i], cl["blue",]/color_divisor),
maxColorValue = max_color
)
}
}
z
})
as.raster(t(x))
}
|
remove_noise_from_matrix <- function(
expression.matrix,
noise.thresholds,
add.threshold=TRUE,
average.threshold=TRUE,
remove.noisy.features=TRUE,
export.csv=NULL,
...
){
if(base::length(noise.thresholds) == 1){
base::message("noise.thresholds only has 1 value, using a fixed threshold...")
noise.thresholds <- base::rep(noise.thresholds, base::ncol(expression.matrix))
}else if(base::length(noise.thresholds) != base::ncol(expression.matrix)){
base::stop("noise.thresholds needs to be length 1 or ncol(expression.matrix)")
}
base::message("Denoising expression matrix...")
expression.matrix.denoised <- expression.matrix
threshold.matrix <- base::matrix(base::rep(noise.thresholds, base::nrow(expression.matrix)),
ncol=base::ncol(expression.matrix), byrow = TRUE)
if(remove.noisy.features){
base::message(" removing noisy genes")
above.noise.threshold <- base::as.vector(
base::rowSums(expression.matrix >= threshold.matrix) > 0)
expression.matrix.denoised <- expression.matrix.denoised[above.noise.threshold,]
threshold.matrix <- threshold.matrix[above.noise.threshold,]
}
if(average.threshold){
noise.thresholds.mean <- base::mean(noise.thresholds)
threshold.matrix[] <- noise.thresholds.mean
}
threshold.matrix <- base::round(threshold.matrix)
base::message(" adjusting matrix")
if(!add.threshold){
expression.matrix.denoised <- base::pmax(expression.matrix.denoised, threshold.matrix)
}else{
expression.matrix.denoised <- expression.matrix.denoised + threshold.matrix
}
if(!base::is.null(export.csv)){
utils::write.csv(expression.matrix.denoised,
file=export.csv)
}
return(expression.matrix.denoised)
}
|
INV <-
function(w) {as.matrix(t(svd(w)$v %*% (t(svd(w)$u)/svd(w)$d)))}
|
is_continuous <- function(x) {
n <- length(x)
checks <- logical(n - 1)
if (n > 1) {
if (n == 2) {
if (abs(x[1] - x[2]) == 1) {
TRUE
} else {
FALSE
}
} else {
if(x[2] - x[1] == 1) {
checks[1] <- TRUE
for (i in 2:(n-1)) {
checks[i] <- ifelse(x[i+1] - x[i] == 1, TRUE, FALSE)
}
all(checks)
} else {
if(x[2] - x[1] == -1) {
checks[1] <- TRUE
for (i in 2:(n-1)) {
checks[i] <- ifelse(x[i+1] - x[i] == -1, TRUE, FALSE)
}
all(checks)
} else {
FALSE
}
}
}
} else {
FALSE
}
}
|
test_that("Discrete axis maps to categorical type", {
g <- ggplot(mpg, aes(class, color = class)) + geom_bar()
p <- ggplotly(g, dynamicTicks = "x")
classes <- getLevels(mpg[["class"]])
axisActual <- with(
p$x$layout$xaxis, list(type, tickmode, categoryorder, categoryarray)
)
axisExpect <- list("category", "auto", "array", classes)
expect_equivalent(axisActual, axisExpect)
expect_equivalent(
sort(sapply(p$x$data, "[[", "x")), classes
)
axisActual <- with(
p$x$layout$yaxis, list(type, tickmode)
)
axisExpect <- list("linear", "array")
expect_equivalent(axisActual, axisExpect)
})
test_that("Categorical axis reflects custom scale mapping", {
lims <- c("2seater", "suv")
g <- ggplot(mpg, aes(class, color = class)) +
geom_bar() +
scale_x_discrete(limits = lims)
expect_warning(p <- ggplotly(g, dynamicTicks = "x"),
regexp = "non-finite values")
axisActual <- with(
p$x$layout$xaxis, list(type, tickmode, categoryorder, categoryarray)
)
axisExpect <- list("category", "auto", "array", lims)
expect_equivalent(axisActual, axisExpect)
expect_equivalent(
sort(sapply(p$x$data, "[[", "x")), sort(lims)
)
labs <- c("small", "large")
g <- ggplot(mpg, aes(class, color = class)) +
geom_bar() +
scale_x_discrete(limits = lims, labels = labs)
expect_warning(p <- ggplotly(g, dynamicTicks = "x"),
regexp = "non-finite values")
axisActual <- with(
p$x$layout$xaxis, list(type, tickmode, categoryorder, categoryarray)
)
axisExpect <- list("category", "auto", "array", labs)
expect_equivalent(axisActual, axisExpect)
expect_equivalent(
sort(sapply(p$x$data, "[[", "x")), sort(labs)
)
})
test_that("Time axis inverse transforms correctly", {
d <- data.frame(
x = seq(Sys.Date(), Sys.Date() + 9, length.out = 10),
y = rnorm(10)
)
l <- ggplotly(ggplot(d, aes(x, y)) + geom_line(), dynamicTicks = TRUE)$x
expect_length(l$data, 1)
expect_equivalent(l$layout$xaxis$type, "date")
expect_equivalent(l$layout$xaxis$tickmode, "auto")
expect_is(l$layout$xaxis$range, "Date")
expect_equivalent(l$data[[1]][["x"]], d$x)
d2 <- data.frame(
x = seq(Sys.time(), Sys.time() + 9000, length.out = 10),
y = rnorm(10)
)
l2 <- ggplotly(ggplot(d2, aes(x, y)) + geom_line(), dynamicTicks = TRUE)$x
expect_length(l2$data, 1)
expect_equivalent(l2$layout$xaxis$type, "date")
expect_equivalent(l2$layout$xaxis$tickmode, "auto")
expect_is(l2$layout$xaxis$range, "POSIXt")
expect_equivalent(l2$data[[1]][["x"]], d2$x)
})
test_that("Inverse maps colorbar data", {
p <- ggplot(mpg, aes(hwy, manufacturer)) +
stat_bin2d(aes(fill = ..density..), binwidth = c(3,1))
l <- ggplotly(p, dynamicTicks = TRUE)$x
expect_length(l$data, 2)
expect_true(l$data[[2]]$y %in% unique(mpg$manufacturer))
})
|
expected <- eval(parse(text="\"/vignettes\""));
test(id=0, code={
argv <- eval(parse(text="list(\"/home/lzhao/hg/r-instrumented/src/library/utils\", \"\", \"/home/lzhao/hg/r-instrumented/src/library/utils/vignettes\", FALSE, FALSE, TRUE, FALSE)"));
.Internal(gsub(argv[[1]], argv[[2]], argv[[3]], argv[[4]], argv[[5]], argv[[6]], argv[[7]]));
}, o=expected);
|
library(joineRML)
library(survival)
library(dplyr)
hvd <- heart.valve %>%
filter(!is.na(log.grad), !is.na(log.lvmi), num <= 50)
mjoint_fit <- mjoint(
formLongFixed = list("grad" = log.grad ~ time + sex + hs),
formLongRandom = list("grad" = ~ 1 | num),
formSurv = survival::Surv(fuyrs, status) ~ age,
data = hvd,
inits = list(
"gamma" = c(0.1, 2.7),
"beta" = c(2.5, 0.0, 0.1, 0.2)
),
timeVar = "time"
)
mjoint_fit2 <- mjoint(
formLongFixed = list(
"grad" = log.grad ~ time + sex + hs,
"lvmi" = log.lvmi ~ time + sex
),
formLongRandom = list(
"grad" = ~ 1 | num,
"lvmi" = ~ time | num
),
formSurv = Surv(fuyrs, status) ~ age,
data = hvd,
inits = list(
"gamma" = c(0.11, 1.51, 0.80),
"beta" = c(2.52, 0.01, 0.03, 0.08, 4.99, 0.03, -0.20)
),
timeVar = "time"
)
mjoint_fit_bs_se <- bootSE(mjoint_fit, nboot = 5, safe.boot = TRUE)
mjoint_fit2_bs_se <- bootSE(mjoint_fit2, nboot = 5, safe.boot = TRUE)
usethis::use_data(
mjoint_fit, mjoint_fit2,
mjoint_fit_bs_se, mjoint_fit2_bs_se,
internal = TRUE, overwrite = TRUE
)
|
calc_RNDmin <- function(bial, populations, outgroup){
if(outgroup[1]==FALSE || length(outgroup[1])==0){
stop("This statistic needs an outgroup ! (set.outgroup)")
}
if(length(populations)!=2){
stop("This statistic requires 2 populations")
}
n1 <- length(populations[[1]])
n2 <- length(outgroup)
diff <- rep(NaN, n1*n2)
zz <- 1
for(xx in 1:n1){
seq1 <- bial[populations[[1]][xx],]
for(yy in 1:n2){
seq2 <- bial[outgroup[yy],]
diff[zz] <- sum(seq1 != seq2, na.rm=TRUE)
zz <- zz + 1
}
}
d1O <- mean(diff, na.rm=TRUE)
n1 <- length(populations[[2]])
n2 <- length(outgroup)
diff <- rep(NaN, n1*n2)
zz <- 1
for(xx in 1:n1){
seq1 <- bial[populations[[2]][xx],]
for(yy in 1:n2){
seq2 <- bial[outgroup[yy],]
diff[zz] <- sum(seq1 != seq2, na.rm=TRUE)
zz <- zz + 1
}
}
d2O <- mean(diff, na.rm=TRUE)
n1 <- length(populations[[1]])
n2 <- length(populations[[2]])
diff <- rep(NaN, n1*n2)
ppp1 <- rep(NaN, n1*n2)
ppp2 <- rep(NaN, n1*n2)
zz <- 1
for(xx in 1:n1){
seq1 <- bial[populations[[1]][xx],]
for(yy in 1:n2){
seq2 <- bial[populations[[2]][yy],]
diff[zz] <- sum(seq1 != seq2, na.rm=TRUE)
ppp1[zz] <- xx
ppp2[zz] <- yy
zz <- zz + 1
}
}
RNDmin <- min(diff, na.rm=TRUE)/((d1O+d2O)/2)
Gmin <- min(diff, na.rm=TRUE)/mean(diff, na.rm=TRUE)
return(list(RNDmin=RNDmin,Gmin=Gmin))
}
|
bcgam.fit <- function(y=y, xmat=xmat, shapes=shapes, zmat=zmat, nums=nums,
ks=ks, sps=sps, nloop=nloop, burnin=burnin, family=family,
xmatnms=xmatnms, znms=znms)
{
n=length(y)
if(is.null(zmat)==F){
XZ=cbind(xmat,zmat)
XZ_one=cbind(rep(1,n),XZ)
X_one=cbind(rep(1,n),xmat)
Z_one=cbind(rep(1,n),zmat)
err_xz=tryCatch(solve(t(XZ)%*%XZ), error=function(e) NULL)
err_xz_one=tryCatch(solve(t(XZ_one)%*%XZ_one), error=function (e) NULL)
err_z_one=tryCatch(solve(t(Z_one)%*%Z_one), error=function (e) NULL)
err_x_one=tryCatch(solve(t(X_one)%*%X_one), error=function (e) NULL)
ind_z_one=1
if(is.null(err_xz)==T){ stop("cols of X and Z are not linearly independent")}
if(is.null(err_xz_one)==T){
if(is.null(err_x_one)==T|is.null(err_z_one)==T){
if(is.null(err_x_one)==T){stop("unitary vector is in the space spanned by cols of X")}else{ind_z_one=0} }
else{stop("unitary vector is in the space spanned by cols of X and Z")}
}
}
else{
X_one=cbind(rep(1,n),xmat)
err_x_one=tryCatch(solve(t(X_one)%*%X_one), error=function (e) NULL)
ind_z_one=1
if(is.null(err_x_one)==T){ stop("unitary vector is in the space spanned by cols of X")}
}
v=1:n*0+1
nz=length(zmat)/n
if(nz!=round(nz)){nz=0}
if(nz==1){zmat=matrix(zmat,ncol=1)}
xs<-NULL
L=length(xmat)/n
tt<-vector("list",L)
center.delta<-vector("list",L)
delta<-NULL
s<-NULL
m<-NULL
vx<-NULL
sumvx<-NULL
incr<-NULL
decr<-NULL
pos_con<-NULL
zmatb<-NULL
znmsb<-NULL
for(i in 1:L){
xs<-unique(sort(xmat[,i]))
n1<-length(xs)
if(length(ks[[i]])>1){
tt[[i]]=cbind(ks[[i]])}
else{ if(nums[i]==0){k=trunc(4+n1^(1/7))} else{ if(nums[i]>0){k=nums[i]} }
if(sps[i]=="Q"){
tt[[i]]<-quantile(xs, probs=seq(0,1,length=k))
}
else{if(sps[i]=="E"){
xs=xmat[,i]
tt[[i]]=cbind(min(xs)+(max(xs)-min(xs))*(0:(k-1))/(k-1))
}}
}
if(shapes[i]==1){ delta.i=monincr(xmat[,i],tt[[i]])
delta=rbind(delta,delta.i$sigma-delta.i$center.vector)
m=c(m,length(delta.i$sigma)/n)
center.delta[[i]]=delta.i$center.vector}
if(shapes[i]==2){ delta.i=mondecr(xmat[,i],tt[[i]])
delta=rbind(delta,delta.i$sigma-delta.i$center.vector)
m=c(m,length(delta.i$sigma)/n)
center.delta[[i]]=delta.i$center.vector}
if(shapes[i]==3){ delta.i=convex(xmat[,i],tt[[i]], pred.new=FALSE)
delta=rbind( delta,delta.i$sigma-t(delta.i$x.mat%*%delta.i$center.vector) )
m=c(m,length(delta.i$sigma)/n)
center.delta[[i]]=delta.i$center.vector}
if(shapes[i]==4){ delta.i=concave(xmat[,i],tt[[i]], pred.new=FALSE)
delta=rbind( delta,delta.i$sigma-t(delta.i$x.mat%*%delta.i$center.vector) )
m=c(m,length(delta.i$sigma)/n)
center.delta[[i]]=delta.i$center.vector}
if(shapes[i]==5){ delta.i=incconvex(xmat[,i],tt[[i]])
delta=rbind(delta,delta.i$sigma-delta.i$center.vector)
m=c(m,length(delta.i$sigma)/n)
center.delta[[i]]=delta.i$center.vector}
if(shapes[i]==7){ delta.i=incconcave(xmat[,i],tt[[i]])
delta=rbind(delta,delta.i$sigma-delta.i$center.vector)
m=c(m,length(delta.i$sigma)/n)
center.delta[[i]]=delta.i$center.vector}
if(shapes[i]==6){ delta.i=decconvex(xmat[,i],tt[[i]])
delta=rbind(delta,delta.i$sigma-delta.i$center.vector)
m=c(m,length(delta.i$sigma)/n)
center.delta[[i]]=delta.i$center.vector}
if(shapes[i]==8){ delta.i=decconcave(xmat[,i],tt[[i]])
delta=rbind(delta,delta.i$sigma-delta.i$center.vector)
m=c(m,length(delta.i$sigma)/n)
center.delta[[i]]=delta.i$center.vector}
if(shapes[i]==1|shapes[i]==5|shapes[i]==7){incr=c(incr,1)}else{incr=c(incr,0)}
if(shapes[i]==2|shapes[i]==6|shapes[i]==8){decr=c(decr,1)}else{decr=c(decr,0)}
vx=cbind(vx,xmat[,i])
if(incr[i]==0 & decr[i]==0){
pos_con=cbind(pos_con,i)
zmatb=cbind(zmatb,vx[,i])
znmsb=c(znmsb, xmatnms[i])
}
}
if(ind_z_one==1){
zmatb=cbind(v,zmat,zmatb)
znmsb=c("(Intercept)",znms, znmsb)}
else{zmatb=cbind(zmat,zmatb)
znmsb=c(znms, znmsb)}
p=length(zmatb)/n
betalpha<-NULL
M<-NULL
P<-NULL
deltaz<-NULL
tau<-NULL
if(family$family=="gaussian"){
gausCode <- nimbleCode({
for (j in 1:n){
y[j] ~ dnorm(eta[j],tau)
eta[j]<-inprod(betalpha[1:(M+P)],deltaz[j,1:(M+P)])
}
tau ~ dgamma(0.1,0.1)
sigma <- 1/sqrt(tau)
for(m in 1:M){
betalpha[m] ~ dgamma(0.01,0.01) }
for(k in (M+1):(M+P)){
betalpha[k] ~ dnorm(0,1.0E-4) }
})
delta.dat=t(delta)
z.dat=zmatb
deltaz.dat=cbind(delta.dat,z.dat)
gausConsts <- list(n=n,M=sum(m), P=p, deltaz=deltaz.dat)
gausData <- list(y=y)
beta.ini=rep(0.1,sum(m))
alpha.ini=rep(1,p)
betalpha.ini=c(beta.ini,alpha.ini)
tau.ini=0.1
gausInits <- list( betalpha=betalpha.ini,tau=tau.ini )
gaus <- nimbleModel(code = gausCode, name = 'gaus', constants = gausConsts,
data = gausData, inits = gausInits)
gausMonitor <- configureMCMC(gaus)
gausMonitor$addMonitors(c('betalpha','sigma','eta'))
gausMCMC <- buildMCMC(gausMonitor)
Cgaus <- compileNimble(gaus)
CgausMCMC <- compileNimble(gausMCMC, project = gaus)
CgausMCMC$run(nloop)
MCMCsamples <- as.matrix(CgausMCMC$mvSamples)
}
else{ if(family$family=="binomial"){
binoCode <- nimbleCode({
for (j in 1:n){
y[j]~dbern(p[j])
p[j] <- expit(eta[j])
eta[j] <- inprod(betalpha[1:(M+P)],deltaz[j,1:(M+P)])
}
for(m in 1:M){
betalpha[m] ~ dgamma(0.01,0.01) }
for(k in (M+1):(M+P)){
betalpha[k] ~ dnorm(0,1.0E-4) }
})
delta.dat=t(delta)
z.dat=zmatb
deltaz.dat=cbind(delta.dat,z.dat)
binoConsts <- list(n=n,M=sum(m), P=p, deltaz=deltaz.dat)
binoData <- list(y=y)
beta.ini=rep(0.1,sum(m))
alpha.ini=rep(1,p)
betalpha.ini=c(beta.ini,alpha.ini)
binoInits <- list( betalpha=betalpha.ini)
bino <- nimbleModel(code = binoCode, name = 'bino', constants = binoConsts,
data = binoData, inits = binoInits)
binoMonitor <- configureMCMC(bino)
binoMonitor$addMonitors(c('betalpha','eta'))
binoMCMC <- buildMCMC(binoMonitor)
Cbino <- compileNimble(bino)
CbinoMCMC <- compileNimble(binoMCMC, project = bino)
CbinoMCMC$run(nloop)
MCMCsamples <- as.matrix(CbinoMCMC$mvSamples)
}
else{ if(family$family=="poisson"){
poisCode <- nimbleCode({
for (j in 1:n){
y[j]~dpois(p[j])
p[j] <- exp(eta[j])
eta[j]<-inprod(betalpha[1:(M+P)],deltaz[j,1:(M+P)])
}
for(m in 1:M){
betalpha[m] ~ dgamma(0.01,0.01) }
for(k in (M+1):(M+P)){
betalpha[k] ~ dnorm(0,1.0E-4) }
})
delta.dat=t(delta)
z.dat=zmatb
deltaz.dat=cbind(delta.dat,z.dat)
poisConsts <- list(n=n,M=sum(m), P=p, deltaz=deltaz.dat)
poisData <- list(y=y)
beta.ini=rep(0.1,sum(m))
alpha.ini=rep(1,p)
betalpha.ini=c(beta.ini,alpha.ini)
poisInits <- list( betalpha=betalpha.ini)
pois <- nimbleModel(code = poisCode, name = 'pois', constants = poisConsts,
data = poisData, inits = poisInits)
poisMonitor <- configureMCMC(pois)
poisMonitor$addMonitors(c('betalpha','eta'))
poisMCMC <- buildMCMC(poisMonitor)
Cpois <- compileNimble(pois)
CpoisMCMC <- compileNimble(poisMCMC, project = pois)
CpoisMCMC$run(nloop)
MCMCsamples <- as.matrix(CpoisMCMC$mvSamples)
}
else{ stop("not valid family") } } }
sims.list=MCMCsamples[(burnin+1):nloop,]
delta.t=t(delta)
zmat.b=zmatb
bigmat <- cbind(zmat.b, delta.t)
alpha.sims <- matrix( sims.list[,(sum(m)+1):(sum(m)+p)], ncol=p )
beta.sims <- matrix( sims.list[,1:sum(m)], ncol=sum(m) )
eta.sims <- matrix( sims.list[,(sum(m)+p+1):(sum(m)+p+n)], ncol=n )
coefs <- apply(sims.list[,c((sum(m)+1):(sum(m)+p), 1:sum(m))],2, mean)
sd.coefs <- apply(sims.list[,c((sum(m)+1):(sum(m)+p), 1:sum(m))],2, sd)
coefs.sims <- cbind(beta.sims, alpha.sims)
etahat <- apply(eta.sims, 2, "mean")
if(family$family=="gaussian"){
sigma.sims <- matrix( sims.list[,sum(m)+p+n+1], ncol=1 )
muhat <- etahat
mu.sims <- eta.sims
}
if(family$family=="binomial"){
muhat <- exp(etahat)/(1+exp(etahat))
mu.sims <- exp(eta.sims)/(1+exp(eta.sims))
}
if(family$family=="poisson"){
muhat <- exp(etahat)
mu.sims <- exp(eta.sims)
}
ans <- list(alpha.sims=alpha.sims, beta.sims=beta.sims, mu.sims=mu.sims, eta.sims=eta.sims,
delta=delta.t, zmat=zmat.b, znms=znmsb, bigmat=bigmat, coefs.sims=coefs.sims, coefs=coefs, sd.coefs=sd.coefs,
muhat=muhat, etahat=etahat, knots=tt, ind_intercept=ind_z_one, center.delta=center.delta)
if(family$family=="gaussian"){
ans$sigma.sims <- sigma.sims}
ans
}
|
geem <- function(formula, id, waves=NULL, data = parent.frame(),
family = gaussian, corstr = "independence", Mv = 1,
weights = NULL, corr.mat = NULL, init.beta=NULL,
init.alpha=NULL, init.phi = 1, scale.fix = FALSE, nodummy = FALSE,
sandwich = TRUE, useP = TRUE, maxit = 20, tol = 0.00001){
call <- match.call()
famret <- getfam(family)
if(inherits(famret, "family")){
LinkFun <- famret$linkfun
InvLink <- famret$linkinv
VarFun <- famret$variance
InvLinkDeriv <- famret$mu.eta
}else{
LinkFun <- famret$LinkFun
VarFun <- famret$VarFun
InvLink <- famret$InvLink
InvLinkDeriv <- famret$InvLinkDeriv
}
if(scale.fix & is.null(init.phi)){
stop("If scale.fix=TRUE, then init.phi must be supplied")
}
useP <- as.numeric(useP)
dat <- model.frame(formula, data, na.action=na.pass)
nn <- dim(dat)[1]
if(typeof(data) == "environment"){
id <- id
weights <- weights
if(is.null(call$weights)) weights <- rep(1, nn)
waves <- waves
}
else{
if(length(call$id) == 1){
subj.col <- which(colnames(data) == call$id)
if(length(subj.col) > 0){
id <- data[,subj.col]
}else{
id <- eval(call$id, envir=parent.frame())
}
}else if(is.null(call$id)){
id <- 1:nn
}
if(length(call$weights) == 1){
weights.col <- which(colnames(data) == call$weights)
if(length(weights.col) > 0){
weights <- data[,weights.col]
}else{
weights <- eval(call$weights, envir=parent.frame())
}
}else if(is.null(call$weights)){
weights <- rep.int(1,nn)
}
if(length(call$waves) == 1){
waves.col <- which(colnames(data) == call$waves)
if(length(waves.col) > 0){
waves <- data[,waves.col]
}else{
waves <- eval(call$waves, envir=parent.frame())
}
}else if(is.null(call$waves)){
waves <- NULL
}
}
dat$id <- id
dat$weights <- weights
dat$waves <- waves
if(!is.numeric(dat$waves) & !is.null(dat$waves)) stop("waves must be either an integer vector or NULL")
na.inds <- NULL
if(any(is.na(dat))){
na.inds <- which(is.na(dat), arr.ind=T)
}
if(!is.null(waves)){
dat <- dat[order(id, waves),]
}else{
dat <- dat[order(id),]
}
cor.vec <- c("independence", "ar1", "exchangeable", "m-dependent", "unstructured", "fixed", "userdefined")
cor.match <- charmatch(corstr, cor.vec)
if(is.na(cor.match)){stop("Unsupported correlation structure")}
if(!is.null(dat$waves)){
wavespl <- split(dat$waves, dat$id)
idspl <- split(dat$id, dat$id)
maxwave <- rep(0, length(wavespl))
incomp <- rep(0, length(wavespl))
for(i in 1:length(wavespl)){
maxwave[i] <- max(wavespl[[i]]) - min(wavespl[[i]]) + 1
if(maxwave[i] != length(wavespl[[i]])){
incomp[i] <- 1
}
}
if( !is.element(cor.match,c(1,3)) & (sum(incomp) > 0) & !nodummy){
dat <- dummyrows(formula, dat, incomp, maxwave, wavespl, idspl)
id <- dat$id
waves <- dat$waves
weights <- dat$weights
}
}
if(!is.null(na.inds)){
weights[unique(na.inds[,1])] <- 0
for(i in unique(na.inds)[,2]){
if(is.factor(dat[,i])){
dat[na.inds[,1], i] <- levels(dat[,i])[1]
}else{
dat[na.inds[,1], i] <- median(dat[,i], na.rm=T)
}
}
}
includedvec <- weights>0
inclsplit <- split(includedvec, id)
dropid <- NULL
allobs <- T
if(any(!includedvec)){
allobs <- F
for(i in 1:length(unique(id))){
if(all(!inclsplit[[i]])){
dropid <- c(dropid, unique(id)[i])
}
}
}
dropind <- c()
if(is.element(cor.match, c(1,3))){
dropind <- which(weights==0)
}else if(length(dropid)>0){
dropind <- which(is.element(id, dropid))
}
if(length(dropind) > 0){
dat <- dat[-dropind,]
includedvec <- includedvec[-dropind]
weights <- weights[-dropind]
id <- id[-dropind]
}
nn <- dim(dat)[1]
K <- length(unique(id))
modterms <- terms(formula)
X <- model.matrix(formula,dat)
Y <- model.response(dat)
offset <- model.offset(dat)
p <- dim(X)[2]
if(is.null(offset)){
off <- rep(0, nn)
}else{
off <- offset
}
interceptcol <- apply(X==1, 2, all)
linkOfMean <- LinkFun(mean(Y[includedvec])) - mean(off)
if( any(is.infinite(linkOfMean) | is.nan(linkOfMean)) ){
stop("Infinite or NaN in the link of the mean of responses. Make sure link function makes sense for these data.")
}
if( any(is.infinite( VarFun(mean(Y))) | is.nan( VarFun(mean(Y)))) ){
stop("Infinite or NaN in the variance of the mean of responses. Make sure variance function makes sense for these data.")
}
if(is.null(init.beta)){
if(any(interceptcol)){
init.beta <- rep(0, dim(X)[2])
init.beta[which(interceptcol)] <- linkOfMean
}else{
stop("Must supply an initial beta if not using an intercept.")
}
}
includedlen <- rep(0, K)
len <- rep(0,K)
uniqueid <- unique(id)
tmpwgt <- as.numeric(includedvec)
idspl <-ifelse(tmpwgt==0, NA, id)
includedlen <- as.numeric(summary(split(Y, idspl, drop=T))[,1])
len <- as.numeric(summary(split(Y, id, drop=T))[,1])
W <- Diagonal(x=weights)
sqrtW <- sqrt(W)
included <- Diagonal(x=(as.numeric(weights>0)))
if(is.null(init.alpha)){
alpha.new <- 0.2
if(cor.match==4){
alpha.new <- 0.2^(1:Mv)
}else if(cor.match==5){
alpha.new <- rep(0.2, sum(1:(max(len)-1)))
}else if(cor.match==7){
alpha.new <- rep(0.2, max(unique(as.vector(corr.mat))))
}
}else{
alpha.new <- init.alpha
}
if(is.null(init.phi)){
phi <- 1
}else{
phi <- init.phi
}
beta <- init.beta
StdErr <- Diagonal(nn)
dInvLinkdEta <- Diagonal(nn)
Resid <- Diagonal(nn)
if(cor.match == 1){
R.alpha.inv <- Diagonal(x = rep.int(1, nn))/phi
BlockDiag <- getBlockDiag(len)$BDiag
}else if(cor.match == 2){
tmp <- buildAlphaInvAR(len)
a1<- tmp$a1
a2 <- tmp$a2
a3 <- tmp$a3
a4 <- tmp$a4
row.vec <- tmp$row.vec
col.vec <- tmp$col.vec
BlockDiag <- getBlockDiag(len)$BDiag
}else if(cor.match == 3){
tmp <- getBlockDiag(len)
BlockDiag <- tmp$BDiag
n.vec <- vector("numeric", nn)
index <- c(cumsum(len) - len, nn)
for(i in 1:K){
n.vec[(index[i]+1) : index[i+1]] <- rep(includedlen[i], len[i])
}
}else if(cor.match == 4){
if(Mv >= max(len)){
stop("Cannot estimate that many parameters: Mv >= max(clustersize)")
}
tmp <- getBlockDiag(len)
BlockDiag <- tmp$BDiag
row.vec <- tmp$row.vec
col.vec <- tmp$col.vec
R.alpha.inv <- NULL
}else if(cor.match == 5){
if( max(len^2 - len)/2 > length(len)){
stop("Cannot estimate that many parameters: not enough subjects for unstructured correlation")
}
tmp <- getBlockDiag(len)
BlockDiag <- tmp$BDiag
row.vec <- tmp$row.vec
col.vec <- tmp$col.vec
}else if(cor.match == 6){
corr.mat <- checkFixedMat(corr.mat, len)
R.alpha.inv <- as(getAlphaInvFixed(corr.mat, len), "symmetricMatrix")/phi
BlockDiag <- getBlockDiag(len)$BDiag
}else if(cor.match == 7){
corr.mat <- checkUserMat(corr.mat, len)
tmp1 <- getUserStructure(corr.mat)
corr.list <- tmp1$corr.list
user.row <- tmp1$row.vec
user.col <- tmp1$col.vec
struct.vec <- tmp1$struct.vec
tmp2 <- getBlockDiag(len)
BlockDiag <- tmp2$BDiag
row.vec <- tmp2$row.vec
col.vec <- tmp2$col.vec
}else if(cor.match == 0){
stop("Ambiguous Correlation Structure Specification")
}else{
stop("Unsupported Correlation Structure")
}
stop <- F
converged <- F
count <- 0
beta.old <- beta
unstable <- F
phi.old <- phi
while(!stop){
count <- count+1
eta <- as.vector(X %*% beta) + off
mu <- InvLink(eta)
diag(StdErr) <- sqrt(1/VarFun(mu))
if(!scale.fix){
phi <- updatePhi(Y, mu, VarFun, p, StdErr, included, includedlen, sqrtW, useP)
}
phi.new <- phi
if(cor.match == 2){
alpha.new <- updateAlphaAR(Y, mu, VarFun, phi, id, len,
StdErr, p, included, includedlen,
includedvec, allobs, sqrtW,
BlockDiag, useP)
R.alpha.inv <- getAlphaInvAR(alpha.new, a1,a2,a3,a4, row.vec, col.vec)/phi
}else if(cor.match == 3){
alpha.new <- updateAlphaEX(Y, mu, VarFun, phi, id, len, StdErr,
Resid, p, BlockDiag, included,
includedlen, sqrtW, useP)
R.alpha.inv <- getAlphaInvEX(alpha.new, n.vec, BlockDiag)/phi
}else if(cor.match == 4){
if(Mv==1){
alpha.new <- updateAlphaAR(Y, mu, VarFun, phi, id, len,
StdErr, p, included, includedlen,
includedvec, allobs,
sqrtW, BlockDiag, useP)
}else{
alpha.new <- updateAlphaMDEP(Y, mu, VarFun, phi, id, len,
StdErr, Resid, p, BlockDiag, Mv,
included, includedlen,
allobs, sqrtW, useP)
if(sum(len>Mv) <= p){
unstable <- T
}
}
if(any(alpha.new >= 1)){
stop <- T
warning("some estimated correlation is greater than 1, stopping.")
}
R.alpha.inv <- getAlphaInvMDEP(alpha.new, len, row.vec, col.vec)/phi
}else if(cor.match == 5){
alpha.new <- updateAlphaUnstruc(Y, mu, VarFun, phi, id, len,
StdErr, Resid, p, BlockDiag,
included, includedlen, allobs,
sqrtW, useP)
if(any(alpha.new >= 1)){
stop <- T
warning("some estimated correlation is greater than 1, stopping.")
}
R.alpha.inv <- getAlphaInvUnstruc(alpha.new, len, row.vec, col.vec)/phi
}else if(cor.match ==6){
R.alpha.inv <- R.alpha.inv*phi.old/phi
}else if(cor.match == 7){
alpha.new <- updateAlphaUser(Y, mu, phi, id, len, StdErr, Resid,
p, BlockDiag, user.row, user.col,
corr.list, included, includedlen,
allobs, sqrtW, useP)
R.alpha.inv <- getAlphaInvUser(alpha.new, len, struct.vec, user.row, user.col, row.vec, col.vec)/phi
}else if(cor.match == 1){
R.alpha.inv <- Diagonal(x = rep.int(1/phi, nn))
alpha.new <- "independent"
}
beta.list <- updateBeta(Y, X, beta, off, InvLinkDeriv, InvLink, VarFun, R.alpha.inv, StdErr, dInvLinkdEta, tol, W, included)
beta <- beta.list$beta
phi.old <- phi
if( max(abs((beta - beta.old)/(beta.old + .Machine$double.eps))) < tol ){converged <- T; stop <- T}
if(count >= maxit){stop <- T}
beta.old <- beta
}
biggest <- which.max(len)[1]
index <- sum(len[1:biggest])-len[biggest]
if(K == 1){
biggest.R.alpha.inv <- R.alpha.inv
if(cor.match == 6) {
biggest.R.alpha <- corr.mat*phi
}else{
biggest.R.alpha <- solve(R.alpha.inv)
}
}else{
biggest.R.alpha.inv <- R.alpha.inv[(index+1):(index+len[biggest]) , (index+1):(index+len[biggest])]
if(cor.match == 6){
biggest.R.alpha <- corr.mat[1:len[biggest] , 1:len[biggest]]*phi
}else{
biggest.R.alpha <- solve(biggest.R.alpha.inv)
}
}
eta <- as.vector(X %*% beta) + off
if(sandwich){
sandvar.list <- getSandwich(Y, X, eta, id, R.alpha.inv, phi, InvLinkDeriv, InvLink, VarFun,
beta.list$hess, StdErr, dInvLinkdEta, BlockDiag, W, included)
}else{
sandvar.list <- list()
sandvar.list$sandvar <- "no sandwich"
}
if(!converged){warning("Did not converge")}
if(unstable){warning("Number of subjects with number of observations >= Mv is very small, some correlations are estimated with very low sample size.")}
dat <- model.frame(formula, data, na.action=na.pass)
X <- model.matrix(formula, dat)
if(is.character(alpha.new)){alpha.new <- 0}
results <- list()
results$beta <- as.vector(beta)
results$phi <- phi
results$alpha <- alpha.new
if(cor.match == 6){
results$alpha <- as.vector(triu(corr.mat, 1)[which(triu(corr.mat,1)!=0)])
}
results$coefnames <- colnames(X)
results$niter <- count
results$converged <- converged
results$naiv.var <- solve(beta.list$hess)
results$var <- sandvar.list$sandvar
results$call <- call
results$corr <- cor.vec[cor.match]
results$clusz <- len
results$FunList <- famret
results$X <- X
results$offset <- off
results$eta <- eta
results$dropped <- dropid
results$weights <- weights
results$terms <- modterms
results$y <- Y
results$biggest.R.alpha <- biggest.R.alpha/phi
results$formula <- formula
class(results) <- "geem"
return(results)
}
updatePhi <- function(YY, mu, VarFun, p, StdErr, included, includedlen, sqrtW, useP){
nn <- sum(includedlen)
resid <- diag(StdErr %*% included %*% sqrtW %*% Diagonal(x = YY - mu))
phi <- (1/(sum(included)- useP * p))*crossprod(resid, resid)
return(as.numeric(phi))
}
updateBeta = function(YY, XX, beta, off, InvLinkDeriv, InvLink,
VarFun, R.alpha.inv, StdErr, dInvLinkdEta, tol, W, included){
beta.new <- beta
conv=F
for(i in 1:10){
eta <- as.vector(XX%*%beta.new) + off
diag(dInvLinkdEta) <- InvLinkDeriv(eta)
mu <- InvLink(eta)
diag(StdErr) <- sqrt(1/VarFun(mu))
hess <- crossprod( StdErr %*% dInvLinkdEta %*%XX, R.alpha.inv %*% W %*% StdErr %*%dInvLinkdEta %*% XX)
esteq <- crossprod( StdErr %*%dInvLinkdEta %*%XX , R.alpha.inv %*% W %*% StdErr %*% as.matrix(YY - mu))
update <- solve(hess, esteq)
beta.new <- beta.new + as.vector(update)
}
return(list(beta = beta.new, hess = hess))
}
getSandwich = function(YY, XX, eta, id, R.alpha.inv, phi, InvLinkDeriv,
InvLink, VarFun, hessMat, StdErr, dInvLinkdEta,
BlockDiag, W, included){
diag(dInvLinkdEta) <- InvLinkDeriv(eta)
mu <- InvLink(eta)
diag(StdErr) <- sqrt(1/VarFun(mu))
scoreDiag <- Diagonal(x= YY - mu)
BlockDiag <- scoreDiag %*% BlockDiag %*% scoreDiag
numsand <- as.matrix(crossprod( StdErr %*% dInvLinkdEta %*% XX, R.alpha.inv %*% W %*% StdErr %*% BlockDiag %*% StdErr %*% W %*% R.alpha.inv %*% StdErr %*% dInvLinkdEta %*% XX))
sandvar <- t(solve(hessMat, numsand))
sandvar <- t(solve(t(hessMat), sandvar))
return(list(sandvar = sandvar, numsand = numsand))
}
|
ChiSquareTail <- function(U,
df,
xlim = c(0, 10),
col = fadeColor("black", "22"),
axes = TRUE,
...) {
x <- c(0, seq(xlim[1], xlim[2] + 3, length.out = 300))
y <- c(0, stats::dchisq(x[-1], df))
graphics::plot(x, y, type = "l", axes = FALSE, xlim = xlim)
graphics::abline(h = 0)
if (axes) {
axis(1)
}
these <- which(x >= U)
X <- x[c(these[1], these, rev(these)[1])]
Y <- c(0, y[these], 0)
graphics::polygon(X, Y, col = col)
}
|
set_window = function(width = 6, height = 4.5, kill = TRUE, noRStudioGD = TRUE) {
if (kill) graphics.off()
dev.new(width = width, height = height, noRStudioGD)
set_panels(1, 1)
}
|
aggregation.misclass <- function (full.data = NULL, response, x, model, cplx = NULL,
type = c("apparent", "noinf"), fullsample.attr = NULL, ...)
{
data <- as.data.frame(x)
data$response <- response
if (class(model)[1] == "penfit") {
probs <- predict(model, data = data, penalized = x, ...)
} else {
if(class(model)[1] == "glm") {
probs <- predict(model, newdata = data, penalized = x, , type = "response", ...)
} else {
probs <- predict(model, data = data, type = "response",
...)
}
}
type <- match.arg(type)
if (type == "apparent") {
mr <- sum(abs(round(probs) - response))/length(response)
}
if (type == "noinf") {
mr <- mean(abs((matrix(response, length(response), length(response),
byrow = TRUE) - round(probs))))
}
mr
}
|
ClusProc0 <- function(signal,signal.mean,Num,threshold,thresMAF,cut,itermax,thres_sil){
seed<- sample(c(1:1000000),1)
set.seed(seed)
pX <- as.matrix(signal)
S <- dim(pX)[1]
clusRes <- rep(NA,S)
del <- list()
mu <- list()
kcl <- kmeans(pX,Num,nstart=10)
KX <- data.frame(X=pX,Kn=kcl$cluster)
for(i in 1:Num){
mu[[i]] <- apply(as.matrix(KX[KX$Kn==i,c(1:cut)]),2,mean)
del[[i]] <- cov(as.matrix(KX[KX$Kn==i,c(1:cut)]))
}
alpha=rep(1/Num,Num)
iter <- 0
logLold <- Inf
pin <- matrix(NA,S,Num)
M=rep(NA,Num)
LDdel=rep(NA,Num)
while(1){
iter=iter+1
for(i in 1:S)
for(n in 1:Num)
pin[i,n] <- 1/(2*pi*det(del[[n]]))*exp(-1/2*(pX[i,]-mu[[n]])%*%solve(del[[n]])%*%as.matrix(pX[i,]-mu[[n]]))*alpha[n]
for(i in 1:S)
clusRes[i] <- which(pin[i,]==max(pin[i,]))
for(i in 1:Num)
alpha[i] <- mean(clusRes==i)
Sdata <- data.frame(pX=pX,clusRes=clusRes)
for(i in 1:Num){
mu[[i]] <- apply(as.matrix(Sdata[Sdata$clusRes==i,c(1:cut)]),2,mean)
del[[i]] <- cov(as.matrix(Sdata[Sdata$clusRes==i,c(1:cut)]))
LDdel[i] <- log(det(del[[i]]))
M[i] <- sum(Sdata$clusRes==i)
}
sum <- 0
for(i in 1:S)
sum <- sum+(pX[i,]-mu[[clusRes[i]]])%*%solve(del[[clusRes[i]]])%*%as.matrix(pX[i,]-mu[[clusRes[i]]])
logL <- -1/2*(sum(M*LDdel)+sum)
if(abs(logL-logLold)<threshold) break
if(iter>itermax) break
logLold <- logL
}
logL <- logL-1/2*S*cut*log(2*pi)
cat("The logliklihood for signal model is ",logL," when clustering number is ",Num,'.\n',sep='')
Sdata$clusRes <- Sdata$clusRes+Num
old.order.mean <- as.matrix(tapply(signal.mean,Sdata$clusRes,mean))
old.order.id <- (Num+1):(2*Num)
mid <- sort(old.order.mean,index.return=TRUE)$ix
for(i in 1:Num)
Sdata[Sdata$clusRes==old.order.id[mid[i]],]$clusRes <- i
rownames(Sdata) <- rownames(signal.mean)
sil <- silWidth(Sdata,thres_sil=thres_sil,thres_MAF=thresMAF)
return(list(logL=logL,sil=sil))
}
ClusProc <- function(signal,N=2:6,varSelection=c('PC1','RAW','PC.9','MEAN'),threshold=1e-05,itermax=8,adjust=TRUE,thresMAF=0.01,scale=FALSE,thresSil=0.01){
varSelection <- match.arg(varSelection)
sX0 <- as.matrix(signal)
if(scale) sX <- scale(sX0) else sX <- sX0
cut <- 1
if(varSelection=='PC.9'){
prop <- 0.9
pca <- princomp(sX)
sds <- pca$sdev
vars <- sds^2
varprop <- vars/sum(vars)
cumvars <- as.vector(cumsum(varprop))
while(cumvars[cut]<prop) cut=cut+1
if(cut>1) cat("The first ",cut,' principal components are used.\n',sep='') else cat("The first principal component is used.\n",sep='')
Invcov <- matrix(0,nrow=cut,ncol=cut)
diag(Invcov) <- 1/vars[1:cut]
comptable <- data.frame(sdev=pca$sdev,vars=vars,cumu=cumvars)
coef <- pca$loadings[,1:cut]
pX <- sX%*%coef
}
if(varSelection=='RAW') {
pX <- sX
cut <- ncol(pX)
cat("The raw intensity measurement is used.\n",sep='')
}
if(varSelection=='MEAN'){
pX <- apply(sX,1,mean)
cat("The mean of the intensity measurement is used.\n",sep='')
}
if(varSelection=='PC1'){
cat("The first principal component is used.\n",sep='')
pX <- prcomp(sX)$x[,1]
}
signal.mean <- as.matrix(apply(sX0,1,mean))
rownames(signal.mean) <- rownames(sX0)
if(1%in%N) stop('The assigned clustering number must be larger than 1.')
res <- list()
for(i in 1:length(N)){
Num <- N[i]
res[[i]] <- ClusProc0(signal=pX,signal.mean=signal.mean,Num=Num,threshold=threshold,thresMAF=thresMAF,cut=cut,itermax=itermax,thres_sil=thresSil)
}
Nlen <- length(N)
silR <- rep(NA,Nlen)
for(i in 1:Nlen)
if(adjust) silR[i] <- res[[i]]$sil$adjusted$silMean.adjust else silR[i] <- res[[i]]$sil$unadjusted$silMean
if(adjust) {
N <- rep(NA,Nlen)
for(i in 1:Nlen)
N[i] <- res[[i]]$sil$adjusted$clusNum.adjust
}
n <- which(silR==max(silR))
clusNum <- N[n]
logL <- res[[n]]$logL
sil <- res[[n]]$sil
resfinal <- list(clusNum=clusNum,silWidth=sil,signal=signal,adjust=adjust)
class(resfinal) <- 'clust'
return(resfinal)
}
print.clust <- function(x, ...) {
adjust <- x$adjust
if(adjust) res <- data.frame(clusNum.adjust=x$silWidth$adjusted$clusNum.adjust,silMean.adjust=round(x$silWidth$adjusted$silMean.adjust,4)) else
res <- data.frame(clusNum=x$silWidth$unadjusted$clusNum,silMean=round(x$silWidth$unadjusted$silMean,4))
print(res,quote=FALSE,row.names=FALSE)
}
|
expected <- eval(parse(text="TRUE"));
test(id=0, code={
argv <- eval(parse(text="list(structure(1, .Tsp = c(1, 1, 1), class = \"ts\"))"));
do.call(`is.finite`, argv);
}, o=expected);
|
graph1_m_DEA <- function(input, output, mseries, B,
RTS = "crs", ORIENTATION = "in",
check = c(1), col = c("black"), print = TRUE) {
input <- as.data.frame(input)
output <- as.data.frame(output)
meff <- matrix(0, nrow = length(mseries), ncol = length(check))
for (m in 1:length(mseries)) {
if (print == TRUE) {
sprintf("The code is now computing the Robust DEA scores for m = %s", mseries[m])
}
DEA <- robust_DEA(input, output, m = mseries[m], B, RTS= RTS, ORIENTATION= ORIENTATION)$eff
for(l in 1:length(check)) {
meff[m,l] <- length(DEA[DEA>check[l]])/nrow(output)
}
}
plot(x=mseries, y=meff[,1], type = "b", lwd = 2,
main = "Percentage of super-efficient units",
xlab = c("m"),
ylab = c("Percentage of super-efficient units"),
ylim=c(0, max(meff[,1])) )
for(l in 2:length(check)) {
graphics::lines(x=mseries, y=meff[,l], type = "b", lwd = 2, col = col[l])
}
legend("topright", legend = check, col = col, lwd = 2)
legend
}
|
context("portable")
test_that("initialization", {
AC <- R6Class("AC",
portable = TRUE,
public = list(
x = 1,
initialize = function(x, y) {
self$x <- self$getx() + x
private$y <- y
},
getx = function() self$x,
gety = function() private$y
),
private = list(
y = 2
)
)
A <- AC$new(2, 3)
expect_identical(A$x, 3)
expect_identical(A$gety(), 3)
AC <- R6Class("AC", portable = TRUE, public = list(x = 1))
expect_error(AC$new(3))
})
test_that("empty members and methods are allowed", {
AC <- R6Class("AC", portable = TRUE)
expect_no_error(AC$new())
})
test_that("Private members are private, and self/private environments", {
AC <- R6Class("AC",
portable = TRUE,
public = list(
x = 1,
gety = function() private$y,
getx = function() self$x,
getx2 = function() private$getx_priv(),
getself = function() self,
getprivate = function() private
),
private = list(
y = 2,
getx_priv = function() self$x
)
)
A <- AC$new()
expect_identical(A$getself(), A)
expect_identical(parent.env(A), emptyenv())
private_bind_env <- A$getprivate()
expect_identical(ls(private_bind_env), c("getx_priv", "y"))
expect_identical(parent.env(private_bind_env), emptyenv())
eval_env <- environment(A$getx)
expect_identical(parent.env(eval_env), environment())
expect_identical(eval_env$self, A)
expect_identical(eval_env$private, A$getprivate())
expect_identical(eval_env, environment(A$getprivate()$getx_priv))
expect_identical(A$x, 1)
expect_null(A$y)
expect_null(A$getx_foo)
expect_identical(A$gety(), 2)
expect_identical(A$getx(), 1)
expect_identical(A$getx2(), 1)
})
test_that("Private methods exist even when no private fields", {
AC <- R6Class("AC",
portable = TRUE,
public = list(
x = 1,
getx = function() self$x,
getx2 = function() private$getx_priv(),
getself = function() self,
getprivate = function() private
),
private = list(
getx_priv = function() self$x
)
)
A <- AC$new()
private_bind_env <- A$getprivate()
expect_identical(ls(private_bind_env), "getx_priv")
expect_identical(parent.env(private_bind_env), emptyenv())
})
test_that("Active bindings work", {
AC <- R6Class("AC",
portable = TRUE,
public = list(
x = 5
),
active = list(
x2 = function(value) {
if (missing(value)) return(self$x * 2)
else self$x <- value/2
},
sqrt_of_x = function(value) {
if (!missing(value))
stop("Sorry this is a read-only variable.")
else {
if (self$x < 0) stop("The requested value is not available.")
else sqrt(self$x)
}
}
)
)
A <- AC$new()
expect_identical(A$x2, 10)
A$x <- 20
expect_identical(A$x2, 40)
A$x2 <- 60
expect_identical(A$x2, 60)
expect_identical(A$x, 30)
A$x <- -2
expect_error(A$sqrt_of_x)
muted_print <- function(x) capture.output(print(x))
expect_no_error(muted_print(A))
})
test_that("Locking works", {
AC <- R6Class("AC",
portable = FALSE,
public = list(x = 1, getx = function() self$x),
private = list(y = 2, gety = function() self$y),
lock_objects = TRUE
)
A <- AC$new()
expect_no_error(A$x <- 5)
expect_identical(A$x, 5)
expect_no_error(A$private$y <- 5)
expect_identical(A$private$y, 5)
expect_error(A$getx <- function() 1)
expect_error(A$gety <- function() 2)
expect_error(A$z <- 1)
expect_error(A$private$z <- 1)
AC <- R6Class("AC",
portable = FALSE,
public = list(x = 1, getx = function() x),
private = list(y = 2, gety = function() y),
lock_objects = FALSE
)
A <- AC$new()
expect_no_error(A$x <- 5)
expect_identical(A$x, 5)
expect_no_error(A$private$y <- 5)
expect_identical(A$private$y, 5)
expect_error(A$getx <- function() 1)
expect_error(A$private$gety <- function() 2)
expect_no_error(A$z <- 1)
expect_identical(A$z, 1)
expect_no_error(A$private$z <- 1)
expect_identical(A$private$z, 1)
})
|
qqextcoeff <- function(fitted, estim = "ST", marge = "emp",
xlab = "Semi-Empirical", ylab = "Model", ...){
if (!any("maxstab" %in% class(fitted)))
stop("This functin is only available for 'maxstab' objects")
data <- fitted$data
coord <- fitted$coord
ext.coeff <- fitted$ext.coeff
if (fitted$iso){
dist <- distance(coord)
exco.mod <- ext.coeff(dist)
}
else {
dist <- distance(coord, vec = TRUE)
exco.mod <- apply(dist, 1, ext.coeff)
}
exco.emp <- fitextcoeff(data, coord, plot = FALSE, estim = estim,
marge = marge)$ext.coeff[,"ext.coeff"]
plot(exco.emp, exco.mod, xlab = xlab, ylab = ylab, ...)
abline(0, 1)
}
qqgev <- function(fitted, xlab, ylab, ...){
data <- fitted$data
n.site <- ncol(data)
gev.param <- t(apply(data, 2, gevmle))
pred <- predict(fitted)
if (missing(xlab))
xlab <- c(expression(mu[MLE]), expression(sigma[MLE]), expression(xi[MLE]))
if (missing(ylab))
ylab <- c(expression(mu[Model]), expression(sigma[Model]), expression(xi[Model]))
op <- par(mfrow=c(1,3))
on.exit(par(op))
if (length(unique(pred[,"loc"])) != 1){
xlim <- ylim <- range(c(gev.param[,"loc"], pred[,"loc"]))
plot(gev.param[,"loc"], pred[,"loc"], xlab = xlab[1], ylab = ylab[1], ...,
xlim = xlim, ylim = ylim)
abline(0, 1)
}
else{
hist(gev.param[,"loc"], xlab = xlab[1], main = "")
axis(3, at = pred[1, "loc"], labels = ylab[1])
}
if (length(unique(pred[,"scale"])) !=1){
xlim <- ylim <- range(c(gev.param[,"scale"], pred[,"scale"]))
plot(gev.param[,"scale"], pred[,"scale"], xlab = xlab[2], ylab = ylab[2],
..., xlim = xlim, ylim = ylim)
abline(0, 1)
}
else{
hist(gev.param[,"scale"], xlab = xlab[2], main = "")
axis(3, at = pred[1, "scale"], labels = ylab[2])
}
if (length(unique(pred[,"shape"])) != 1){
xlim <- ylim <- range(c(gev.param[,"shape"], pred[,"shape"]))
plot(gev.param[,"shape"], pred[,"shape"], xlab = xlab[3], ylab = ylab[3],
..., xlim = xlim, ylim = ylim)
abline(0, 1)
}
else{
hist(gev.param[,"shape"], xlab = xlab[3], main = "")
axis(3, at = pred[1, "shape"], labels = ylab[3])
}
}
plot.copula <- function(x, ..., sites){
n.site <- ncol(x$data)
n.obs <- nrow(x$data)
if (missing(sites))
sites <- sample(1:n.site, 4)
else if (length(sites) != 4)
stop("'sites' must have length 4")
op <- par(no.readonly = TRUE)
layout(matrix(c(1,6,7,9,13,2,8,10,5,5,3,11,5,5,12,4), 4))
par(mar = c(4,4,1,0.5))
on.exit(par(op))
gev.param <- predict(x, std.err = FALSE)[sites, c("loc", "scale", "shape")]
for (i in 1:4){
boot <- matrix(NA, nrow = 1000, ncol = n.obs)
loc <- gev.param[i,1]
scale <- gev.param[i,2]
shape <- gev.param[i,3]
probs <- 1:n.obs / (n.obs + 1)
for (j in 1:1000)
boot[j,] <- sort(rgev(n.obs, loc, scale, shape))
ci <- apply(boot, 2, quantile, c(0.025, 0.975))
matplot(1 / (1 - probs), t(ci), pch ="-", col = 1,
xlab = "Return Period", ylab = "Return level", log = "x")
fun <- function(T) qgev(1 - 1/T, loc, scale, shape)
curve(fun, from = 1.001, to = 100, add = TRUE)
points(1 / (1 - probs), sort(x$data[,sites[i]]))
}
fmadogram(x$data, x$coord, which = "ext", col = "lightgrey")
fmadogram(fitted = x, which = "ext", add = TRUE, n.bins = n.site)
model <- x$model
DoF <- x$par["DoF"]
nugget <- x$par["nugget"]
range <- x$par["range"]
smooth <- x$par["smooth"]
sim.copula <- rcopula(n.obs * 1000, x$coord[sites,], x$copula, x$cov.mod,
nugget = nugget, range = range, smooth = smooth, DoF = DoF)
sim.copula <- array(log(sim.copula), c(n.obs, 1000, 4))
gumb <- log(apply(x$data[,sites], 2, gev2frech, emp = TRUE))
for (i in 1:3){
for (j in (i+1):4){
pair.max <- sort(apply(gumb[,c(i, j)], 1, max))
sim.pair.max <- apply(pmax(sim.copula[,,i], sim.copula[,,j]), 2, sort)
dummy <- rowMeans(sim.pair.max)
ci <- apply(sim.pair.max, 1, quantile, c(0.025, 0.975))
matplot(dummy, t(ci), pch = "-", col = 1, , xlab = "Model",
ylab = "Observed")
points(dummy, pair.max)
abline(0, 1)
h <- distance(x$coord[sites[c(i,j)],])
legend("bottomright", paste("h =", round(h, 2)), bty = "n")
}
}
block.max <- sort(apply(gumb, 1, max))
sim.block.max <- sim.copula[,,1]
for (i in 2:4)
sim.block.max <- pmax(sim.block.max, sim.copula[,,i])
sim.block.max <- apply(sim.block.max, 2, sort)
dummy <- rowMeans(sim.block.max)
ci <- apply(sim.block.max, 1, quantile, c(0.025, 0.975))
matplot(dummy, t(ci), pch = "-", col = 1, xlab = "Model", ylab = "Observed")
points(dummy, block.max)
abline(0, 1)
plot(x$coord, type = "n")
points(x$coord[-sites,])
points(x$coord[sites,], pch = c("1", "2", "3", "4"), col = "blue")
}
plot.maxstab <- function(x, ..., sites){
n.site <- ncol(x$data)
if (missing(sites))
sites <- sample(1:n.site, 4)
else if (length(sites) != 4)
stop("'sites' must have length 4")
op <- par(no.readonly = TRUE)
layout(matrix(c(1,6,7,9,13,2,8,10,5,5,3,11,5,5,12,4), 4))
par(mar = c(4,4,1,0.5))
on.exit(par(op))
gev.param <- predict(x, std.err = FALSE)[sites, c("loc", "scale", "shape")]
for (i in 1:4){
n.obs <- length(na.omit(x$data[,sites[i]]))
boot <- matrix(NA, nrow = 1000, ncol = n.obs)
loc <- gev.param[i,1]
scale <- gev.param[i,2]
shape <- gev.param[i,3]
probs <- 1:n.obs / (n.obs + 1)
boot <- matrix(rgev(n.obs * 1000, loc, scale, shape), nrow = 1000, ncol = n.obs)
boot <- apply(boot, 1, sort)
ci <- apply(boot, 1, quantile, prob = c(0.025, 0.975))
matplot(1 / (1 - probs), t(ci), pch = "-", col = 1,
xlab = "Return Period", ylab = "Return level", log = "x")
fun <- function(T) qgev(1 - 1/T, loc, scale, shape)
curve(fun, from = 1.001, to = 100, add = TRUE)
points(1 / (1 - probs), sort(x$data[,sites[i]]))
}
fmadogram(x$data, x$coord, which = "ext", col = "lightgrey")
fmadogram(fitted = x, which = "ext", add = TRUE, n.bins = n.site)
n.obs <- nrow(x$data[,sites])
model <- x$model
notimplemented <- FALSE
if (model == "Smith"){
cov11 <- x$par["cov11"]
cov12 <- x$par["cov12"]
cov22 <- x$par["cov22"]
sim.maxstab <- rmaxstab(n.obs * 1000, x$coord[sites,], "gauss",
cov11 = cov11, cov12 = cov12, cov22 = cov22)
}
else if (model == "Schlather"){
nugget <- x$par["nugget"]
range <- x$par["range"]
smooth <- x$par["smooth"]
sim.maxstab <- rmaxstab(n.obs * 1000, x$coord[sites,], x$cov.mod,
nugget = nugget, range = range, smooth = smooth)
}
else if (model == "Geometric"){
sigma2 <- x$par["sigma2"]
nugget <- x$par["nugget"]
range <- x$par["range"]
smooth <- x$par["smooth"]
cov.mod <- paste("g", x$cov.mod, sep = "")
sim.maxstab <- rmaxstab(n.obs * 1000, x$coord[sites,], cov.mod,
sigma2 = sigma2, nugget = nugget, range = range,
smooth = smooth)
}
else if (model == "Brown-Resnick"){
range <- x$par["range"]
smooth <- x$par["smooth"]
sim.maxstab <- rmaxstab(n.obs * 1000, x$coord[sites,], "brown",
range = range, smooth = smooth)
}
else if (model == "Extremal-t"){
DoF <- x$par["DoF"]
nugget <- x$par["nugget"]
range <- x$par["range"]
smooth <- x$par["smooth"]
cov.mod <- paste("t", x$cov.mod, sep = "")
sim.maxstab <- rmaxstab(n.obs * 1000, x$coord[sites,], cov.mod,
DoF = DoF, nugget = nugget, range = range,
smooth = smooth)
}
if (notimplemented){
for (i in 1:7){
plot(0, 0, type = "n", bty = "n", axes = FALSE, xlab = "", ylab = "")
text(0, 0, "Not implemented")
}
}
else {
sim.maxstab <- array(log(sim.maxstab), c(n.obs, 1000, 4))
for (i in 1:4){
idx.na <- which(is.na(x$data[,sites[i]]))
sim.maxstab[idx.na,,i] <- NA
}
gumb <- log(apply(x$data[,sites], 2, gev2frech, emp = TRUE))
for (i in 1:3){
for (j in (i+1):4){
pair.max <- sort(apply(gumb[,c(i, j)], 1, max))
sim.pair.max <- apply(pmax(sim.maxstab[,,i], sim.maxstab[,,j]), 2, sort)
dummy <- rowMeans(sim.pair.max)
ci <- apply(sim.pair.max, 1, quantile, c(0.025, 0.975))
matplot(dummy, t(ci), pch = "-", col = 1, , xlab = "Model",
ylab = "Observed")
points(dummy, pair.max)
abline(0, 1)
h <- distance(x$coord[sites[c(i,j)],])
legend("bottomright", paste("h =", round(h, 2)), bty = "n")
}
}
block.max <- sort(apply(gumb, 1, max, na.rm = TRUE))
sim.block.max <- sim.maxstab[,,1]
for (i in 2:4)
sim.block.max <- pmax(sim.block.max, sim.maxstab[,,i], na.rm = TRUE)
sim.block.max <- apply(sim.block.max, 2, sort, na.last = NA)
dummy <- rowMeans(sim.block.max)
ci <- apply(sim.block.max, 1, quantile, c(0.025, 0.975))
matplot(dummy, t(ci), pch = "-", col = 1, xlab = "Model", ylab = "Observed")
points(dummy, block.max)
abline(0, 1)
}
plot(x$coord, type = "n")
points(x$coord[-sites,])
points(x$coord[sites,], pch = c("1", "2", "3", "4"), col = "blue")
}
.qqmaxtupple <- function(fitted, tupple.size = 2, n.plots = 6){
n.obs <- nrow(fitted$data)
n.site <- ncol(fitted$data)
model <- fitted$model
tupples <- apply(replicate(n.plots, sample(n.site, tupple.size)), 2, sort)
sites <- unique(as.numeric(tupples))
coord <- fitted$coord[sites,]
if (model == "Smith"){
cov11 <- fitted$par["cov11"]
cov12 <- fitted$par["cov12"]
cov22 <- fitted$par["cov22"]
sim.maxstab <- rmaxstab(n.obs * 1000, coord, "gauss",
cov11 = cov11, cov12 = cov12, cov22 = cov22)
}
else if (model == "Schlather"){
nugget <- fitted$par["nugget"]
range <- fitted$par["range"]
smooth <- fitted$par["smooth"]
sim.maxstab <- rmaxstab(n.obs * 1000, coord, fitted$cov.mod,
nugget = nugget, range = range, smooth = smooth)
}
else if (model == "Geometric"){
sigma2 <- fitted$par["sigma2"]
nugget <- fitted$par["nugget"]
range <- fitted$par["range"]
smooth <- fitted$par["smooth"]
cov.mod <- paste("g", fitted$cov.mod, sep = "")
sim.maxstab <- rmaxstab(n.obs * 1000, coord, cov.mod,
sigma2 = sigma2, nugget = nugget, range = range,
smooth = smooth)
}
else if (model == "Brown-Resnick"){
range <- fitted$par["range"]
smooth <- fitted$par["smooth"]
sim.maxstab <- rmaxstab(n.obs * 1000, coord, "brown",
range = range, smooth = smooth)
}
else if (model == "Extremal-t"){
DoF <- fitted$par["DoF"]
nugget <- fitted$par["nugget"]
range <- fitted$par["range"]
smooth <- fitted$par["smooth"]
cov.mod <- paste("t", fitted$cov.mod, sep = "")
sim.maxstab <- rmaxstab(n.obs * 1000, coord, cov.mod,
DoF = DoF, nugget = nugget, range = range,
smooth = smooth)
}
sim.maxstab <- array(log(sim.maxstab), c(n.obs, 1000, length(sites)))
for (i in 1:length(sites)){
idx.na <- which(is.na(fitted$data[,sites[i]]))
sim.maxstab[idx.na,,i] <- NA
}
gumb <- log(apply(fitted$data[,sites], 2, gev2frech, emp = TRUE))
for (i in 1:n.plots){
tupple <- tupples[,i]
idx <- order(unique(c(tupple, tupples[,-i])))
tupple.max <- sort(apply(gumb[,idx], 1, max))
sim.tupple.max <- apply(apply(sim.maxstab[,,idx], c(1,2), max), 2, sort)
dummy <- rowMeans(sim.tupple.max)
ci <- apply(sim.tupple.max, 1, quantile, c(0.025, 0.975))
matplot(dummy, t(ci), pch = "-", col = 1, , xlab = "Model", ylab = "Observed")
points(dummy, tupple.max)
abline(0, 1)
legend("bottomright", paste(c("Stations: ", sort(tupple)), collapse = " "), bty = "n")
}
}
|
read_pfile <- function(fname, n_ref_scans = NULL, verbose, extra) {
fbytes <- file.size(fname)
hdr <- read_pfile_header(fname)
if (!is.null(n_ref_scans)) hdr$rhuser19 <- n_ref_scans
con <- file(fname, "rb")
seek(con, hdr$off_data)
endian <- "little"
Npts <- (fbytes - hdr$off_data) / 4
raw_pts <- readBin(con, "int", n = Npts, size = 4, endian = endian)
close(con)
coils <- 0
for (n in seq(1, 8, 2)) {
if ((hdr$rcv[n] != 0) || (hdr$rcv[n + 1] != 0)) {
coils <- coils + 1 + hdr$rcv[n + 1] - hdr$rcv[n]
}
}
if (coils == 0) coils <- 1
expt_pts <- coils * (hdr$nframes * hdr$nechoes + hdr$nechoes) * hdr$frame_size * 2
if (expt_pts != Npts) {
warning("Unexpected number of data points.")
cat(paste("Expecting :", Npts, "points based on file size.\n"))
cat(paste("Expecting :", expt_pts, "points based on header information.\n"))
cat(paste("Coils :", coils, "\n"))
cat(paste("nframes :", hdr$nframes, "\n"))
cat(paste("nechoes :", hdr$nechoes), "\n")
cat(paste("frame_size :", hdr$frame_size), "\n")
cat(paste("w_frames :", hdr$rhuser19), "\n")
cat(paste("Header rev. :", hdr$hdr_rev), "\n")
}
if (verbose) {
cat(paste("Expecting :", Npts, "points based on file size.\n"))
cat(paste("Expecting :", expt_pts, "points based on header information.\n"))
cat(paste("Coils :", coils, "\n"))
cat(paste("nframes :", hdr$nframes, "\n"))
cat(paste("nechoes :", hdr$nechoes), "\n")
cat(paste("frame_size :", hdr$frame_size), "\n")
cat(paste("w_frames :", hdr$rhuser19), "\n")
cat(paste("Header rev. :", hdr$hdr_rev), "\n\n")
}
data <- raw_pts[c(TRUE, FALSE)] + 1i * raw_pts[c(FALSE, TRUE)]
dyns <- hdr$nechoes * hdr$nframes + hdr$nechoes
data <- array(data, dim = c(hdr$frame_size, dyns, coils, 1, 1, 1, 1))
data <- aperm(data, c(7,6,5,4,2,3,1))
rem <- seq(from = 1, to = dyns, by = dyns / hdr$nechoes)
data <- data[,,,,-rem,,,drop = FALSE]
res <- c(NA, NA, NA, NA, 1, NA, 1 / hdr$spec_width)
freq_domain <- rep(FALSE, 7)
ref <- def_ref()
nuc <- def_nuc()
meta <- list(EchoTime = hdr$te)
mrs_data <- mrs_data(data = data, ft = hdr$ps_mps_freq / 10, resolution = res,
ref = ref, nuc = nuc, freq_domain = freq_domain,
affine = NULL, meta = meta, extra = extra)
if (hdr$rhuser19 > 0) {
wref_inds <- rep(FALSE, Ndyns(mrs_data) / hdr$nechoes)
wref_inds[1:hdr$rhuser] <- TRUE
wref_inds <- rep(wref_inds, hdr$nechoes)
ref_mrs <- get_dyns(mrs_data, which(wref_inds))
metab_mrs <- get_dyns(mrs_data, which(!wref_inds))
} else {
ref_mrs <- NA
metab_mrs <- mrs_data
}
list(metab = metab_mrs, ref = ref_mrs)
}
read_pfile_header <- function(fname) {
endian <- "little"
vars <- get_pfile_vars()
con <- file(fname, "rb")
vars$hdr_rev <- readBin(con, "numeric", size = 4, endian = endian)
loc <- get_pfile_dict(vars$hdr_rev, con)
seek(con, loc$off_data)
vars$off_data <- readBin(con, "int", size = 4, endian = endian)
seek(con, loc$nechoes)
vars$nechoes <- readBin(con, "int", size = 2, endian = endian)
seek(con, loc$nframes)
vars$nframes <- readBin(con, "int", size = 2, endian = endian)
seek(con, loc$frame_size)
vars$frame_size <- readBin(con, "int", size = 2, signed = FALSE,
endian = endian)
seek(con, loc$rcv)
vars$rcv <- readBin(con, "int", n = 8, size = 2, endian = endian)
seek(con, loc$rhuser19)
vars$rhuser19 <- readBin(con, "numeric", size = 4, endian = endian)
seek(con, loc$spec_width)
vars$spec_width <- readBin(con, "numeric", size = 4, endian = endian)
seek(con, loc$csi_dims)
vars$csi_dims <- readBin(con, "int", size = 2, endian = endian)
seek(con, loc$xcsi)
vars$xcsi <- readBin(con, "int", size = 2, endian = endian)
seek(con, loc$ycsi)
vars$ycsi <- readBin(con, "int", size = 2, endian = endian)
seek(con, loc$zcsi)
vars$zcsi <- readBin(con, "int", size = 2, endian = endian)
seek(con, loc$ps_mps_freq)
ps_mps_freq_bits <- intToBits(readBin(con, "int", size = 4, endian = endian))
vars$ps_mps_freq <- sum(2^.subset(0:31, as.logical(ps_mps_freq_bits)))
seek(con, loc$te)
vars$te <- readBin(con, "int", size = 4, endian = endian) / 1e6
close(con)
vars
}
get_pfile_vars <- function() {
vars <- vector(mode = "list", length = 14)
names(vars) <- c("hdr_rev", "off_data", "nechoes", "nframes", "frame_size",
"rcv", "rhuser19", "spec_width", "csi_dims", "xcsi", "ycsi",
"zcsi", "ps_mps_freq", "te")
vars
}
get_pfile_dict <- function(hdr_rev, con) {
loc <- get_pfile_vars()
if (floor(hdr_rev) > 25) {
loc$hdr_rev <- 0
loc$off_data <- 4
loc$nechoes <- 146
loc$nframes <- 150
loc$frame_size <- 156
loc$rcv <- 264
loc$rhuser19 <- 356
loc$spec_width <- 432
loc$csi_dims <- 436
loc$xcsi <- 438
loc$ycsi <- 440
loc$zcsi <- 442
loc$ps_mps_freq <- 488
loc$te <- 1148
} else if ((floor(hdr_rev) > 11) && (floor(hdr_rev) < 25)) {
loc$hdr_rev <- 0
loc$off_data <- 1468
loc$nechoes <- 70
loc$nframes <- 74
loc$frame_size <- 80
loc$rcv <- 200
loc$rhuser19 <- 292
loc$spec_width <- 368
loc$csi_dims <- 372
loc$xcsi <- 374
loc$ycsi <- 376
loc$zcsi <- 378
loc$ps_mps_freq <- 424
loc$te <- 1212
} else {
close(con)
stop(paste("Error, pfile version not supported :", hdr_rev))
}
loc
}
|
dataRep <- function(formula, data, subset, na.action)
{
call <- match.call()
nact <- NULL
y <- match.call(expand.dots=FALSE)
if(missing(na.action))
y$na.action <- na.delete
y[[1]] <- as.name("model.frame")
X <- eval(y, sys.parent())
nact <- attr(X,"na.action")
n <- nrow(X)
nam <- names(X)
p <- length(nam)
types <- character(p)
parms <- character(p)
pctl <- vector('list',p)
margfreq <- vector('list',p)
Xu <- vector('list',p)
for(j in 1:p) {
namj <- nam[j]
xj <- X[[j]]
if(is.character(xj))
xj <- as.factor(xj)
if(is.factor(xj)) {
parms[[j]] <- paste(levels(xj),collapse=' ')
types[j] <- 'exact categorical'
} else if(inherits(xj,'roundN')) {
atr <- attributes(xj)
nam[j] <- atr$name
types[j] <- 'round'
parms[j] <- paste('to nearest',format(atr$tolerance))
if(length(w <- atr$clip))
parms[j] <- paste(parms[j],', clipped to [',
paste(format(w),collapse=','),']',sep='')
pctl[[j]] <- atr$percentiles
} else {
types[j] <- 'exact numeric'
parms[j] <- ''
pctl[[j]] <- quantile(xj, seq(0,1,by=.01))
}
margfreq[[j]] <- table(xj)
Xu[[j]] <- sort(unique(xj))
X[[j]] <- xj
}
names(types) <- names(parms) <- names(pctl) <- names(margfreq) <-
names(Xu) <- nam
Xu <- expand.grid(Xu)
m <- nrow(Xu)
count <- integer(m)
for(i in 1:m) {
matches <- rep(TRUE,n)
for(j in 1:p)
matches <- matches & (as.character(X[[j]]) ==
as.character(Xu[[j]][i]))
count[i] <- sum(matches)
}
if(any(count==0)) {
s <- count > 0
Xu <- Xu[s,]
count <- count[s]
m <- sum(s)
}
structure(list(call=call, formula=formula, n=n, names=nam,
types=types, parms=parms, margfreq=margfreq,
percentiles=pctl, X=Xu, count=count, na.action=nact),
class='dataRep')
}
roundN <- function(x, tol=1, clip=NULL)
{
pct <- quantile(x, seq(0,1,by=.01), na.rm=TRUE)
name <- deparse(substitute(x))
lab <- attr(x, 'label')
if(!length(lab))
lab <- name
if(!missing(clip))
x <- pmin(pmax(x,clip[1]),clip[2])
structure(as.single(tol*round(x/tol)), tolerance=tol, clip=clip,
percentiles=pct, name=name, label=lab, class='roundN')
}
as.data.frame.roundN <- as.data.frame.vector
'[.roundN' <- function(x, i, ...)
{
atr <- attributes(x)
x <- unclass(x)[i]
attributes(x) <- atr
x
}
print.dataRep <- function(x, long=FALSE, ...)
{
cat("\n")
cat("Data Representativeness n=",x$n,"\n\n", sep='')
dput(x$call)
cat("\n")
if(length(z <- x$na.action))
naprint(z)
specs <- data.frame(Type=x$types,
Parameters=x$parms,
row.names=x$names)
cat('Specifications for Matching\n\n')
print.data.frame(specs)
X <- x$X
if(long) {
X$Frequency <- x$count
cat('\nUnique Combinations of Descriptor Variables\n\n')
print.data.frame(X)
} else cat('\n',nrow(X),
'unique combinations of variable values were found.\n\n')
invisible()
}
predict.dataRep <- function(object, newdata, ...)
{
n <- object$n
count <- object$count
if(missing(newdata))
return(count)
pctl <- object$percentiles
margfreq <- object$margfreq
p <- length(margfreq)
m <- nrow(newdata)
nam <- object$names
types <- object$types
X <- object$X
Xn <- model.frame(object$formula, newdata, na.action=na.keep)
names(Xn) <- nam
worst.margfreq <- rep(1e8, m)
pct <- matrix(NA, m, p, dimnames=list(row.names(Xn),nam))
for(j in 1:p) {
xj <- Xn[[j]]
freq <- margfreq[[nam[j]]][as.character(xj)]
freq[is.na(freq)] <- 0
pct[,j] <- if(types[j]=='exact categorical')
100*freq/n
else
approx(pctl[[nam[j]]], seq(0,100,by=1),
xout=newdata[[nam[j]]], rule=2)$y
worst.margfreq <- pmin(worst.margfreq, freq)
}
cnt <- integer(m)
for(i in 1:m) {
matches <- rep(TRUE,nrow(X))
for(j in 1:p) {
matches <- matches & (as.character(X[[j]]) == as.character(Xn[[j]][i]))
}
s <- sum(matches)
if(s > 1)
warning('more than one match to original data combinations')
cnt[i] <- if(s)
count[matches]
else
0
}
if(any(cnt > worst.margfreq))
warning('program logic error')
structure(list(count=cnt, percentiles=pct, worst.margfreq=worst.margfreq,
newdata=newdata), class='predict.dataRep')
}
print.predict.dataRep <- function(x, prdata=TRUE, prpct=TRUE, ...)
{
if(prdata) {
dat <- x$newdata
dat$Frequency <- x$count
dat$Marginal.Freq <- x$worst.margfreq
cat('\nDescriptor Variable Values, Estimated Frequency in Original Dataset,\nand Minimum Marginal Frequency for any Variable\n\n')
print.data.frame(dat)
} else {
cat('\nFrequency in Original Dataset\n\n')
print(x$count)
cat('\nMinimum Marginal Frequency for any Variable\n\n')
print(x$worst.margfreq)
}
if(prpct) {
cat('\n\nPercentiles for Continuous Descriptor Variables,\nPercentage in Category for Categorical Variables\n\n')
print(round(x$percentiles))
}
invisible()
}
|
msm.emm.fit <- function(f,
qdata,
intvals,
expnms,
emmvar,
emmvars,
rr=TRUE,
main=TRUE,
degree=1,
id=NULL,
weights,
bayes=FALSE,
MCsize=nrow(qdata), hasintercept=TRUE, ...){
newform <- terms(f, data = qdata)
nobs = nrow(qdata)
thecall <- match.call(expand.dots = FALSE)
names(thecall) <- gsub("qdata", "data", names(thecall))
names(thecall) <- gsub("f", "formula", names(thecall))
m <- match(c("formula", "data", "weights", "offset"), names(thecall), 0L)
hasweights = ifelse("weights" %in% names(thecall), TRUE, FALSE)
thecall <- thecall[c(1L, m)]
thecall$drop.unused.levels <- TRUE
thecall[[1L]] <- quote(stats::model.frame)
thecalle <- eval(thecall, parent.frame())
if(hasweights){
qdata$weights <- as.vector(model.weights(thecalle))
} else qdata$weights = rep(1, nobs)
if(is.null(id)) {
id <- "id__"
qdata$id__ <- seq_len(dim(qdata)[1])
}
nidx = which(!(names(qdata) %in% id))
if(!bayes) fit <- glm(newform, data = qdata,
weights=weights,
...)
if(bayes){
requireNamespace("arm")
fit <- bayesglm(f, data = qdata[,nidx,drop=FALSE],
weights=weights,
...)
}
if(fit$family$family %in% c("gaussian", "poisson")) rr=FALSE
if(is.null(intvals)){
intvals <- (seq_len(length(table(qdata[expnms[1]])))) - 1
}
predit <- function(idx, newdata){
newdata[,expnms] <- idx
suppressWarnings(predict(fit, newdata=newdata, type='response'))
}
if(MCsize==nrow(qdata)){
newdata <- qdata
}else{
newids <- data.frame(temp=sort(sample(unique(qdata[,id, drop=TRUE]), MCsize,
replace = TRUE
)))
names(newids) <- id
newdata <- merge(qdata,newids, by=id, all.x=FALSE, all.y=TRUE)[seq_len(MCsize),]
}
predmat = lapply(intvals, predit, newdata=newdata)
msmdat <- data.frame(
cbind(
Ya = do.call(c,predmat),
psi = rep(intvals, each=MCsize),
weights = rep(newdata$weights, times=length(intvals))
)
)
msmdat[,emmvars] <- newdata[,emmvars]
polydat <- as.data.frame(poly(msmdat$psi, degree=degree, raw=TRUE))
newexpnms <- paste0("psi",1:degree)
names(polydat) <- newexpnms
msmdat <- cbind(msmdat, polydat)
msmf <- paste0("Ya ~ ",
ifelse(hasintercept, "1 +", "-1 +"),
paste0(c(newexpnms, emmvars), collapse = "+"))
msmform <- .intmaker(as.formula(msmf), expnms = newexpnms, emmvars = emmvars)
class(msmform) <- "formula"
newterms <- terms(msmform)
nterms = length(attr(newterms, "term.labels"))
nterms = nterms + attr(newterms, "intercept")
if(bayes){
if(!rr) suppressWarnings(msmfit <- bayesglm(msmform, data=msmdat,
weights=weights, x=TRUE,
...))
if(rr) suppressWarnings(msmfit <- bayesglm(msmform, data=msmdat,
family=binomial(link='log'), start=rep(-0.0001, nterms),
weights=weights, x=TRUE))
}
if(!bayes){
if(!rr) suppressWarnings(msmfit <- glm(msmform, data=msmdat,
weights=weights, x=TRUE,
...))
if(rr) suppressWarnings(msmfit <- glm(msmform, data=msmdat,
family=binomial(link='log'), start=rep(-0.0001, nterms),
weights=weights, x=TRUE))
}
res <- list(fit=fit, msmfit=msmfit)
if(main) {
res$Ya <- msmdat$Ya
res$Yamsm <- as.numeric(predict(msmfit, type='response'))
res$Yamsml <- as.numeric(predict(msmfit, type="link"))
res$A <- msmdat$psi
res[[emmvar]] <- do.call(c, lapply(intvals, function(x) newdata[,emmvar]))
}
newtermlabels <- attr(newterms, "term.labels")
for(emmv in emmvars){
newtermlabels <- gsub(paste0("psi([0-9]):", emmv), paste0(emmv,":","mixture", "^\\1"), newtermlabels)
}
newtermlabels <- gsub("\\^1", "", newtermlabels)
attr(res, "term.labels") <- newtermlabels
res
}
qgcomp.emm.boot <- function(
f,
data,
expnms=NULL,
emmvar="",
q=4,
breaks=NULL,
id=NULL,
weights,
alpha=0.05,
B=200,
rr=TRUE,
degree=1,
seed=NULL,
bayes=FALSE,
MCsize=nrow(data),
parallel=FALSE,
parplan = FALSE,
errcheck=FALSE,
...){
oldq = NULL
if(is.null(seed)) seed = round(runif(1, min=0, max=1e8))
if(errcheck){
if (is.null(expnms)) {
stop("'expnms' must be specified explicitly\n")
}
if (is.null(emmvar)) {
stop("'emmvar' must be specified explicitly\n")
}
}
allemmvals<- unique(data[,emmvar])
emmlev <- length(allemmvals)
zdata = zproc(data[,emmvar], znm = emmvar)
emmvars = names(zdata)
data = cbind(data, zdata)
data = data[,unique(names(data)),drop=FALSE]
if(errcheck){
}
originalform <- terms(f, data = data)
hasintercept = as.logical(attr(originalform, "intercept"))
(f <- .intmaker(f,expnms,emmvars))
newform <- terms(f, data = data)
addedterms <- setdiff(attr(newform, "term.labels"), attr(originalform, "term.labels"))
addedmain <- setdiff(addedterms, grep(":",addedterms, value = TRUE))
addedints <- setdiff(addedterms, addedmain)
addedintsl <- lapply(emmvars, function(x) grep(x, addedints, value = TRUE))
addedintsord = addedints
class(newform) <- "formula"
nobs = nrow(data)
origcall <- thecall <- match.call(expand.dots = FALSE)
names(thecall) <- gsub("f", "formula", names(thecall))
m <- match(c("formula", "data", "weights", "offset"), names(thecall), 0L)
hasweights = ifelse("weights" %in% names(thecall), TRUE, FALSE)
thecall <- thecall[c(1L, m)]
thecall$drop.unused.levels <- TRUE
thecall[[1L]] <- quote(stats::model.frame)
thecalle <- eval(thecall, parent.frame())
if(hasweights){
data$weights <- as.vector(model.weights(thecalle))
} else data$weights = rep(1, nobs)
if (is.null(expnms)) {
expnms <- attr(newform, "term.labels")
message("Including all model terms as exposures of interest\n")
}
lin = .intchecknames(expnms)
if(!lin) stop("Model appears to be non-linear and I'm having trouble parsing it:
please use `expnms` parameter to define the variables making up the exposure")
if (!is.null(q) & !is.null(breaks)){
oldq = q
q <- NULL
}
if (!is.null(q) | !is.null(breaks)){
ql <- qgcomp::quantize(data, expnms, q, breaks)
qdata <- ql$data
br <- ql$breaks
if(is.null(q)){
nvals <- length(br[[1]])-1
} else{
nvals <- q
}
intvals <- (seq_len(nvals))-1
} else {
qdata <- data[unique(names(data)),]
nvals = length(table(unlist(data[,expnms])))
if(nvals < 10){
message("\nNote: using all possible values of exposure as the
intervention values\n")
p = length(expnms)
intvals <- as.numeric(names(table(unlist(data[,expnms]))))
br <- lapply(seq_len(p), function(x) c(-1e16, intvals[2:nvals]-1e-16, 1e16))
}else{
message("\nNote: using quantiles of all exposures combined in order to set
proposed intervention values for overall effect (25th, 50th, 75th %ile)
You can ensure this is valid by scaling all variables in expnms to have similar ranges.")
intvals = as.numeric(quantile(unlist(data[,expnms]), c(.25, .5, .75)))
br <- NULL
}
}
if(is.null(id)) {
id <- "id__"
qdata$id__ <- seq_len(dim(qdata)[1])
}
msmfit <- msm.emm.fit(newform, qdata, intvals, emmvar=emmvar, emmvars=emmvars, expnms=expnms, rr, main=TRUE,degree=degree, id=id,
weights,
bayes,
MCsize=MCsize,
...)
msmcoefnames <- attr(msmfit, "term.labels")
estb <- as.numeric(msmfit$msmfit$coefficients)
nobs <- dim(qdata)[1]
nids <- length(unique(qdata[,id, drop=TRUE]))
starttime = Sys.time()
psi.emm.only <- function(i=1, f=f, qdata=qdata, intvals=intvals, emmvar=emmvar, emmvars=emmvars, expnms=expnms, rr=rr, degree=degree,
nids=nids, id=id,
weights,MCsize=MCsize,
...){
if(i==2 & !parallel){
timeiter = as.numeric(Sys.time() - starttime)
if((timeiter*B/60)>0.5) message(paste0("Expected time to finish: ", round(B*timeiter/60, 2), " minutes \n"))
}
bootids <- data.frame(temp=sort(sample(unique(qdata[,id, drop=TRUE]), nids,
replace = TRUE
)))
names(bootids) <- id
qdata_ <- merge(qdata,bootids, by=id, all.x=FALSE, all.y=TRUE)
ft = msm.emm.fit(f, qdata_, intvals=intvals, expnms=expnms, emmvar=emmvar, emmvars=emmvars, rr, main=FALSE, degree, id, weights=weights, bayes, MCsize=MCsize,
...)
yhatty = data.frame(yhat=predict(ft$msmfit), psi=ft$msmfit$data[,"psi"])
as.numeric(
c(
with(yhatty, tapply(yhat, psi, mean)),
ft$msmfit$coefficients
)
)
}
set.seed(seed)
if(parallel){
if (parplan) {
oplan <- future::plan(strategy = future::multisession)
on.exit(future::plan(oplan), add = TRUE)
}
bootsamps <- future.apply::future_lapply(X=seq_len(B), FUN=psi.emm.only,f=f, qdata=qdata, intvals=intvals,
emmvar=emmvar, emmvars=emmvars, expnms=expnms, rr=rr, degree=degree, nids=nids, id=id,
weights=qdata$weights,MCsize=MCsize,
future.seed=TRUE,
...)
}else{
bootsamps <- lapply(X=seq_len(B), FUN=psi.emm.only,f=f, qdata=qdata, intvals=intvals,
emmvar=emmvar, emmvars=emmvars, expnms=expnms, rr=rr, degree=degree, nids=nids, id=id,
weights=weights, MCsize=MCsize,
...)
}
bootsamps = do.call("cbind", bootsamps)
hatidx = seq_len(length(intvals))
hats = t(bootsamps[hatidx,])
cov.yhat = cov(hats)
bootsamps = bootsamps[-hatidx,]
seb <- apply(bootsamps, 1, sd)
covmat.coef <- cov(t(bootsamps))
colnames(covmat.coef) <- rownames(covmat.coef) <- names(estb) <- c("(Intercept)", msmcoefnames)
tstat <- estb / seb
df <- nobs - length(attr(terms(f, data = data), "term.labels")) - 1 - degree
pval <- 2 - 2 * pt(abs(tstat), df = df)
pvalz <- 2 - 2 * pnorm(abs(tstat))
ci <- cbind(estb + seb * qnorm(alpha / 2), estb + seb * qnorm(1 - alpha / 2))
if (!is.null(oldq)){
q = oldq
}
psidx = 1:(hasintercept+1)
qx <- qdata[, expnms]
res <- .qgcompemm_object(
qx = qx, fit = msmfit$fit, msmfit = msmfit$msmfit,
psi = estb[-1],
var.psi = seb[-1] ^ 2,
covmat.psi=covmat.coef["psi1", "psi1"],
covmat.psiint=covmat.coef[grep("mixture", colnames(covmat.coef)), grep("mixture", colnames(covmat.coef))],
ci = ci[-1,],
coef = estb, var.coef = seb ^ 2, covmat.coef=covmat.coef, ci.coef = ci,
expnms=expnms,
intterms = addedintsord,
q=q, breaks=br, degree=degree,
pos.psi = NULL, neg.psi = NULL,
pos.weights = NULL, neg.weights = NULL, pos.size = NULL,neg.size = NULL, bootstrap=TRUE,
y.expected=msmfit$Ya, y.expectedmsm=msmfit$Yamsm, index=msmfit$A,
emmvar.msm = msmfit[[emmvar]],
bootsamps = bootsamps,
cov.yhat=cov.yhat,
alpha=alpha,
call=origcall,
emmlev = emmlev
)
if(msmfit$fit$family$family=='gaussian'){
res$tstat <- tstat
res$df <- df
res$pval <- pval
}
if(msmfit$fit$family$family %in% c('binomial', 'poisson')){
res$zstat <- tstat
res$pval <- pvalz
}
res
}
|
correlation.limits <-
function(n.P, n.B, n.C, lambda.vec=NULL, prop.vec=NULL, coef.mat=NULL) {
validation.bin(n.B, prop.vec)
if (missing(n.P) == TRUE && !is.null(lambda.vec)) {
stop("Number of Poisson variables is not specified!")
} else
if (n.P > 0 && is.null(lambda.vec)) {
stop("Lambda vector is not specified while n.P > 0!")
} else
if (!is.null(lambda.vec)) {
if(n.P == 0) {
stop("Lambda vector is specified while n.P=0!")
} else
if (n.P > 0 && (length(lambda.vec) != n.P)) {
stop("Length of lambda vector does not match the number of Poisson variables! \n")
} else
errorCount1=0
for (i in 1:length(lambda.vec)){
if(lambda.vec[i] <= 0) {
cat("\n Lambda for Poisson variable",i,"must be greater than '0'!","\n")
errorCount1 = errorCount1 + 1
cat("\n")
}
}
if (errorCount1 > 0) {
stop("Range violation occurred in the lambda vector!")
}
}
if (missing(n.C) == TRUE && !is.null(coef.mat)) {
stop("Number of continuous variables is not specified!")
} else
if (n.C > 0 && is.null(coef.mat)) {
stop("Coefficient matrix is not specified while n.C> 0!")
} else
if (!is.null(coef.mat)) {
if(n.C == 0) {
stop("Coefficient matrix is specified while n.C=0!")
} else
if (n.C > 0 && (ncol(coef.mat) != n.C)) {
stop("Dimension of coefficient matrix does not match the number of continuous variables! \n")
}
}
if(!is.null(lambda.vec)) {
samples=1e+05
xmat1=sapply(1:length(lambda.vec),function(i) rpois(samples,lambda.vec[i]))
sxmat=apply(xmat1,2,sort)
upp.lim.p=cor(sxmat)[col(cor(sxmat)) > row(cor(sxmat))]
rsxmat=apply(sxmat,2,rev)
low.lim.p=cor(sxmat,rsxmat)[col(cor(sxmat,rsxmat)) < row(cor(sxmat,rsxmat))]
sugcormat.p=diag(1,n.P)
sugcormat.p[lower.tri(sugcormat.p)]=low.lim.p
sugcormat.p[upper.tri(sugcormat.p)]=upp.lim.p
}
if(!is.null(prop.vec)) {
q.vec=(1-prop.vec)
a=unlist(sapply(2:n.B , function(i) sapply(1:(i-1), function(j) -sqrt((prop.vec[i]*prop.vec[j])/(q.vec[i]*q.vec[j])) )))
b=unlist(sapply(2:n.B , function(i) sapply(1:(i-1), function(j) -sqrt((q.vec[i]*q.vec[j])/(prop.vec[i]*prop.vec[j])) )))
low.lim.b=apply(cbind(a,b),1,max)
c=unlist(sapply(2:n.B , function(i) sapply(1:(i-1), function(j) sqrt((prop.vec[i]*q.vec[j])/(q.vec[i]*prop.vec[j])) )))
d=unlist(sapply(2:n.B , function(i) sapply(1:(i-1), function(j) sqrt((q.vec[i]*prop.vec[j])/(prop.vec[i]*q.vec[j])) )))
upp.lim.b=apply(cbind(c,d),1,min)
samples = 1e+05
xmat2=sapply(1:length(prop.vec),function(i) rbinom(samples,1,prop.vec[i]))
sugcormat.b=diag(1,n.B)
sugcormat.b[lower.tri(sugcormat.b)]=low.lim.b
sugcormat.b[upper.tri(sugcormat.b)]=upp.lim.b
}
if(!is.null(coef.mat)) {
samples = 1e+05
xmat3=matrix(NA, nrow=samples, ncol=n.C)
for (i in 1:n.C){
x=as.vector(rnorm(samples))
xx=cbind(1,x,x^2,x^3)
xmat3[,i]=xx%*%coef.mat[,i]
}
sxmat=apply(xmat3,2,sort)
upp.lim.n=cor(sxmat)[col(cor(sxmat)) > row(cor(sxmat))]
rsxmat=apply(sxmat,2,rev)
low.lim.n=cor(sxmat,rsxmat)[col(cor(sxmat,rsxmat)) < row(cor(sxmat,rsxmat))]
sugcormat.n=diag(1,n.C)
sugcormat.n[lower.tri(sugcormat.n)]=low.lim.n
sugcormat.n[upper.tri(sugcormat.n)]=upp.lim.n
}
if(!is.null(lambda.vec) && is.null(prop.vec) && is.null(coef.mat) ) {
sugcormat=sugcormat.p
diag(sugcormat)=NA
} else
if(is.null(lambda.vec) && !is.null(prop.vec) && is.null(coef.mat) ) {
sugcormat=sugcormat.b
diag(sugcormat)=NA
} else
if(is.null(lambda.vec) && is.null(prop.vec) && !is.null(coef.mat) ) {
sugcormat=sugcormat.n
diag(sugcormat)=NA
} else
if(!is.null(lambda.vec) && !is.null(prop.vec) && is.null(coef.mat)) {
xmat=cbind(xmat1,xmat2)
sxmat=apply(xmat,2,sort)
upp.lim=cor(sxmat)[col(cor(sxmat)) > row(cor(sxmat))]
rsxmat=apply(sxmat,2,rev)
low.lim=cor(sxmat,rsxmat)[col(cor(sxmat,rsxmat)) < row(cor(sxmat,rsxmat))]
sugcormat=diag(1,(n.P+n.B))
sugcormat[lower.tri(sugcormat)]=low.lim
sugcormat[upper.tri(sugcormat)]=upp.lim
sugcormat[(n.P+1):(n.P+n.B),(n.P+1):(n.P+n.B)]=sugcormat.b
diag(sugcormat)=NA
} else
if(!is.null(lambda.vec) && is.null(prop.vec) && !is.null(coef.mat)) {
xmat=cbind(xmat1,xmat3)
sxmat=apply(xmat,2,sort)
upp.lim=cor(sxmat)[col(cor(sxmat)) > row(cor(sxmat))]
rsxmat=apply(sxmat,2,rev)
low.lim=cor(sxmat,rsxmat)[col(cor(sxmat,rsxmat)) < row(cor(sxmat,rsxmat))]
sugcormat=diag(1,(n.P+n.C))
sugcormat[lower.tri(sugcormat)]=low.lim
sugcormat[upper.tri(sugcormat)]=upp.lim
diag(sugcormat)=NA
} else
if(is.null(lambda.vec) && !is.null(prop.vec) && !is.null(coef.mat)) {
xmat=cbind(xmat2,xmat3)
sxmat=apply(xmat,2,sort)
upp.lim=cor(sxmat)[col(cor(sxmat)) > row(cor(sxmat))]
rsxmat=apply(sxmat,2,rev)
low.lim=cor(sxmat,rsxmat)[col(cor(sxmat,rsxmat)) < row(cor(sxmat,rsxmat))]
sugcormat=diag(1,(n.B+n.C))
sugcormat[lower.tri(sugcormat)]=low.lim
sugcormat[upper.tri(sugcormat)]=upp.lim
sugcormat[1:n.B,1:n.B]=sugcormat.b
diag(sugcormat)=NA
} else
if(!is.null(lambda.vec) && !is.null(prop.vec) && !is.null(coef.mat)) {
xmat=cbind(xmat1,xmat2,xmat3)
sxmat=apply(xmat,2,sort)
upp.lim=cor(sxmat)[col(cor(sxmat)) > row(cor(sxmat))]
rsxmat=apply(sxmat,2,rev)
low.lim=cor(sxmat,rsxmat)[col(cor(sxmat,rsxmat)) < row(cor(sxmat,rsxmat))]
sugcormat=diag(1,(n.P+n.B+n.C))
sugcormat[lower.tri(sugcormat)]=low.lim
sugcormat[upper.tri(sugcormat)]=upp.lim
sugcormat[(n.P+1):(n.P+n.B),(n.P+1):(n.P+n.B)]=sugcormat.b
diag(sugcormat)=NA
}
limits.corr.mat=sugcormat
return(limits.corr.mat)
}
|
gb_classifier <- function(form, distribution, data.train,
n.trees, interaction.depth,
n.minobsinnode, shrinkage,
verbose = c(TRUE, FALSE)) {
if (isTRUE(verbose == TRUE)) {
out <- gbm::gbm(formula = form, distribution = distribution,
data = data.train, n.trees = n.trees,
interaction.depth = interaction.depth,
n.minobsinnode = n.minobsinnode,
shrinkage = shrinkage,
train.fraction = 1, n.cores = 1)
} else {
out <- suppressMessages(suppressWarnings(
gbm::gbm(formula = form, distribution = distribution,
data = data.train, n.trees = n.trees,
interaction.depth = interaction.depth,
n.minobsinnode = n.minobsinnode,
shrinkage = shrinkage,
train.fraction = 1, n.cores = 1)
))
}
return(out)
}
gb_classifier_update <- function(object, n.new.trees,
verbose = c(TRUE, FALSE)) {
if (isTRUE(verbose == TRUE)) {
out <- gbm::gbm.more(object = object,
n.new.trees = n.new.trees)
} else {
out <- suppressMessages(suppressWarnings(
gbm::gbm.more(object = object,
n.new.trees = n.new.trees)
))
}
return(out)
}
|
RejectAssignment <-
RejectAssignments <-
reject <-
function (assignments,
feedback,
verbose = getOption('pyMTurkR.verbose', TRUE)){
GetClient()
if (is.factor(assignments)) {
assignments <- as.character(assignments)
}
if (is.factor(feedback)) {
feedback <- as.character(feedback)
}
for (i in 1:length(feedback)) {
if (!is.null(feedback[i]) && nchar(feedback[i]) > 1024)
stop("Feedback ", i, " is too long (1024 char max)")
}
if (length(feedback) == 1) {
feedback <- rep(feedback[1], length(assignments))
} else if (!length(feedback) == length(assignments)) {
stop("Number of feedback is not 1 nor length(assignments)")
}
Assignments <- emptydf(0, 3, c("AssignmentId", "Feedback", "Valid"))
for (i in 1:length(assignments)){
response <- try(pyMTurkR$Client$reject_assignment(
AssignmentId = assignments[i],
RequesterFeedback = feedback[i]
), silent = !verbose)
if (class(response) == "try-error") {
valid <- FALSE
if (verbose) {
warning(i, ": Invalid request for assignment ",assignments[i])
}
} else {
valid <- TRUE
if (verbose) {
message(i, ": Assignment (", assignments[i], ") Rejected")
}
}
Assignments <- rbind(Assignments, data.frame(AssignmentId = assignments[i],
Feedback = feedback[i],
Valid = valid))
}
message(sum(Assignments$Valid), " Assignments Rejected")
return(Assignments)
}
|
populateCopierVector <- function(fxnPtr, Robject, vecName, dll) {
vecPtr <- eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getModelObjectPtr, fxnPtr, vecName))
copierVectorObject <- Robject[[vecName]]
fromPtr <- eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getModelObjectPtr, fxnPtr, copierVectorObject[[1]]))
toPtr <- eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getModelObjectPtr, fxnPtr, copierVectorObject[[2]]))
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$populateCopierVector, vecPtr, fromPtr, toPtr, as.integer(copierVectorObject[[3]]), as.integer(copierVectorObject[[4]])))
}
populateManyModelVarMapAccess <- function(fxnPtr, Robject, manyAccessName, dll) {
manyAccessPtr = eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getModelObjectPtr, fxnPtr, manyAccessName))
cModel <- Robject[[manyAccessName]][[1]]$CobjectInterface
if(is(cModel, 'uninitializedField'))
stop('Compiled C++ model not available; please include the model in your compilation call (or compile it in advance).', call. = FALSE)
mapInfo <- makeMapInfoFromAccessorVectorFaster(Robject[[manyAccessName]])
if(length(mapInfo[[1]]) > 0) {
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$populateValueMapAccessorsFromNodeNames, manyAccessPtr, mapInfo[[1]], mapInfo[[2]], cModel$.basePtr))
}
}
populateManyModelValuesMapAccess <- function(fxnPtr, Robject, manyAccessName, dll){
manyAccessPtr = eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getModelObjectPtr, fxnPtr, manyAccessName))
cModelValues <- Robject[[manyAccessName]][[1]]$CobjectInterface
mapInfo <- makeMapInfoFromAccessorVectorFaster(Robject[[manyAccessName]])
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$populateValueMapAccessorsFromNodeNames, manyAccessPtr, mapInfo[[1]], mapInfo[[2]], cModelValues$extptr))
}
getNamedObjected <- function(objectPtr, fieldName, dll)
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getModelObjectPtr, objectPtr, fieldName))
populateNodeFxnVecNew <- function(fxnPtr, Robject, fxnVecName, dll){
fxnVecPtr <- getNamedObjected(fxnPtr, fxnVecName, dll = dll)
indexingInfo <- Robject[[fxnVecName]]$indexingInfo
declIDs <- indexingInfo$declIDs
rowIndices <- indexingInfo$unrolledIndicesMatrixRows
if(is.null(Robject[[fxnVecName]]$model$CobjectInterface) || inherits(Robject[[fxnVecName]]$model$CobjectInterface, 'uninitializedField'))
stop("populateNodeFxnVecNew: error in accessing compiled model; perhaps you did not compile the model used by your nimbleFunction along with or before this compilation of the nimbleFunction?")
numberedPtrs <- Robject[[fxnVecName]]$model$CobjectInterface$.nodeFxnPointers_byDeclID$.ptr
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$populateNodeFxnVectorNew_byDeclID, fxnVecPtr, as.integer(declIDs), numberedPtrs, as.integer(rowIndices)))
}
populateIndexedNodeInfoTable <- function(fxnPtr, Robject, indexedNodeInfoTableName, dll) {
iNITptr <- getNamedObjected(fxnPtr, indexedNodeInfoTableName, dll = dll)
iNITcontent <- Robject[[indexedNodeInfoTableName]]$unrolledIndicesMatrix
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$populateIndexedNodeInfoTable, iNITptr, iNITcontent))
}
numberedObjects <- setRefClass('numberedObjects',
fields = c('.ptr' = 'ANY', dll = 'ANY'),
methods = list(
initialize = function(dll){
dll <<- dll
.ptr <<- newNumberedObjects(dll)
},
finalize = function() {
nimbleInternalFunctions$nimbleFinalize(.ptr)
},
getSize = function(){
getSize_NumberedObjects(.ptr, dll)
},
resize = function(size){
resize_NumberedObjects(.ptr, size, dll)
}
)
)
setMethod('[', 'numberedObjects', function(x, i){
getNumberedObject(x$.ptr, i, x$dll)
})
setMethod('[<-', 'numberedObjects', function(x, i, value){
assignNumberedObject(x$.ptr, i, value, x$dll)
return(x)
})
newNumberedObjects <- function(dll){
ans <- eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$newNumberedObjects))
eval(call('.Call',nimbleUserNamespace$sessionSpecificDll$register_numberedObjects_Finalizer, ans, dll[['handle']], "numberedObjects"))
ans
}
getSize_NumberedObjects <- function(numberedObject, dll){
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getSizeNumberedObjects, numberedObject))
}
resize_NumberedObjects <- function(numberedObject, size, dll){
nil <- eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$resizeNumberedObjects, numberedObject, as.integer(size)) )
}
assignNumberedObject <- function(numberedObject, index, val, dll){
if(!is(val, 'externalptr'))
stop('Attempting to assign a val which is not an externalptr to a NumberedObjects')
if(index < 1 || index > getSize_NumberedObjects(numberedObject, dll) )
stop('Invalid index')
nil <- eval(call('.Call', getNativeSymbolInfo('setNumberedObject', nimbleUserNamespace$sessionSpecificDll), numberedObject, as.integer(index), val))
}
getNumberedObject <- function(numberedObject, index, dll){
if(index < 1 || index > getSize_NumberedObjects(numberedObject, dll) )
stop('Invalid index')
eval(call('.Call', nimbleUserNamespace$sessionSpecificDll$getNumberedObject, numberedObject, as.integer(index)))
}
|
context("all_subsets")
test_that("all subsets selection output matches the expected result", {
model <- lm(y ~ x1 + x2 + x3 + x4, data = cement)
k <- ols_step_all_possible(model)
pred_exp <- c(
"x4", "x2", "x1", "x3", "x1 x2",
"x1 x4", "x3 x4", "x2 x3", "x2 x4", "x1 x3",
"x1 x2 x4", "x1 x2 x3", "x1 x3 x4", "x2 x3 x4",
"x1 x2 x3 x4"
)
expect_equal(k$mindex, c(1:15))
expect_equivalent(k$predictors, pred_exp)
})
test_that("output from all subsets regression is as expected", {
x <- cat("Index N Predictors R-Square Adj. R-Square Mallow's Cp
1 1 1 disp 0.7183433 0.7089548 4.443792
2 2 1 hp 0.6024373 0.5891853 17.794906
3 3 2 disp hp 0.7482402 0.7308774 3.000000")
model <- lm(mpg ~ disp + hp, data = mtcars)
expect_output(print(ols_step_all_possible(model)), x)
})
test_that("all possible regression betas are as expected", {
model <- lm(mpg ~ disp + hp + wt, data = mtcars)
k <- ols_step_all_possible_betas(model)
is_dt <- is.data.table(k)
k_class <- class(k)
if(!is_dt) {
k <- data.table(k)
}
actual <- k[, list(beta = mean(beta)), by = predictor]
if(!is_dt) {
class(actual) <- k_class
}
predictor <- c("(Intercept)", "disp", "hp", "wt")
beta <- c(33.85901073, -0.02255579, -0.03899945, -4.09350456)
expected <- data.frame(predictor, beta)
expect_equivalent(actual$predictor, expected$predictor)
expect_equivalent(actual$beta, expected$beta)
})
|
randomRescaledEventMoves <-
function(events,boundaries,countOnly=F){
chrlengths<-boundaries[,"end"]-boundaries[,"start"]+1
chrfrac<-(events[,"end"]-events[,"start"]+1)/
chrlengths[match(events[,"chrom"],boundaries[,"chrom"])]
chrstart<-cumsum(chrlengths)-chrlengths+1
newchrom<-sample(unique(events[,"chrom"]),size=nrow(events),replace=T)
newstart<-chrstart[newchrom]+
floor((1-chrfrac)*runif(nrow(events))*
chrlengths[match(newchrom,boundaries[,"chrom"])])
if(countOnly)return()
newend<-newstart+
pmax(0,round(chrfrac*chrlengths[match(newchrom,boundaries[,"chrom"])])-1)
return(matrix(ncol=3,data=c(newstart,newend,newchrom),dimnames=list(NULL,
c("start","end","chrom"))))
}
|
invErf <- function(x)
{
if ( sum(x >= 1) > 0 | sum(x <= -1) > 0 )
stop("Argument must be between -1 and 1")
return(qnorm((1+x)/2)/sqrt(2));
}
|
test_that("Credentials are accepted and a db is created", {
skip_unless_socket_available()
expect_error(SocketClass$new(host, port = 1984L, "admin", "denied"))
expect_type(SocketClass$new("localhost", port = 1984L, "admin", "admin"), "environment")
Session <- BasexClient$new("localhost", 1984L, username = "admin", password = "admin")
Session$set_intercept(TRUE)$Execute("drop DB TestDB")
Session$Execute("Open TestDB")
Opened <- Session$get_success()
if (!Opened) {
Session$Create("TestDB")
Session$Add("Test.xml", "<Line_1 line='1'>Content 1</Line_1>")
Session$Add("Test.xml", "<Line_2 line='2'>Content 2</Line_2>")
Session$Add("Test.xml", "<Line_3 line='3'>Content 3</Line_3>")
Session$Add("Books", "<book title='XQuery' author='Walmsley'/>")
Add_Book <- "let $book := <book title='Advanced R' author='Wickham'/>
return insert node $book as last into collection('TestDB/Books')"
Query_obj <- Session$Query(Add_Book)
Query_obj$queryObject$ExecuteQuery()
}
Session$Execute("Close")
Session$restore_intercept()
expect_equal(Session$get_intercept(), FALSE)
rm(Session)
})
|
NULL
tf_v2 <- function() {
package_version(tf_version()) >= "1.14"
}
.globals <- new.env(parent = emptyenv())
.globals$tensorboard <- NULL
.onLoad <- function(libname, pkgname) {
tensorflow_python <- Sys.getenv("TENSORFLOW_PYTHON", unset = NA)
if (!is.na(tensorflow_python))
Sys.setenv(RETICULATE_PYTHON = tensorflow_python)
cpp_log_opt <- getOption("tensorflow.core.cpp_min_log_level")
if (!is.null(cpp_log_opt))
Sys.setenv(TF_CPP_MIN_LOG_LEVEL = max(min(cpp_log_opt, 1), 0))
tf <<- import("tensorflow", delay_load = list(
priority = 5,
environment = "r-reticulate",
on_load = function() {
register_suppress_warnings_handler(list(
suppress = function() {
if (tf_v2()) {
tf_logger <- tf$get_logger()
logging <- reticulate::import("logging")
old_verbosity <- tf_logger$level
tf_logger$setLevel(logging$ERROR)
old_verbosity
} else {
old_verbosity <- tf$logging$get_verbosity()
tf$logging$set_verbosity(tf$logging$ERROR)
old_verbosity
}
},
restore = function(context) {
if (tf_v2()) {
tf_logger <- tf$get_logger()
tf_logger$setLevel(context)
} else {
tf$logging$set_verbosity(context)
}
}
))
register_tf_help_handler()
tryCatch(tf$python$util$deprecation$silence()$`__enter__`(),
error = function(e) NULL)
emit <- get("packageStartupMessage")
emit("Loaded Tensorflow version ", tf$version$VERSION)
}
,
on_error = function(e) {
stop(tf_config_error_message(), call. = FALSE)
}
))
reticulate::register_class_filter(function(classes) {
if (any(c("tensorflow.python.ops.variables.Variable",
"tensorflow.python.framework.ops.Tensor",
"tensorflow.python.ops.ragged.ragged_tensor.RaggedTensor")
%in%
classes)) {
c("tensorflow.tensor", classes)
} else {
classes
}
})
}
tf_config <- function() {
have_tensorflow <- py_module_available("tensorflow")
config <- py_config()
if (have_tensorflow) {
if (reticulate::py_has_attr(tf, "version"))
version_raw <- tf$version$VERSION
else
version_raw <- tf$VERSION
tfv <- strsplit(version_raw, ".", fixed = TRUE)[[1]]
version <- package_version(paste(tfv[[1]], tfv[[2]], sep = "."))
structure(class = "tensorflow_config", list(
available = TRUE,
version = version,
version_str = version_raw,
location = config$required_module_path,
python = config$python,
python_version = config$version
))
} else {
structure(class = "tensorflow_config", list(
available = FALSE,
python_versions = config$python_versions,
error_message = tf_config_error_message()
))
}
}
tf_version <- function() {
config <- tf_config()
if (config$available)
config$version
else
NULL
}
print.tensorflow_config <- function(x, ...) {
if (x$available) {
aliased <- function(path) sub(Sys.getenv("HOME"), "~", path)
cat("TensorFlow v", x$version_str, " (", aliased(x$location), ")\n", sep = "")
cat("Python v", x$python_version, " (", aliased(x$python), ")\n", sep = "")
} else {
cat(x$error_message, "\n")
}
}
tf_gpu_configured <- function(verbose=TRUE) {
res <- tryCatch({
tf$test$is_gpu_available()
}, error = function(e) {
warning("Can not determine if GPU is configured.", call. = FALSE);
NA
})
if (!is.na(verbose) && is.logical(verbose) &&verbose) {
tryCatch({
cat(paste("TensorFlow built with CUDA: ", tf$test$is_built_with_cuda()),
"\n");
cat(paste("GPU device name: ", tf$test$gpu_device_name(),
collapse = "\n"))
}, error = function(e) {})
}
res
}
tf_config_error_message <- function() {
message <- "Valid installation of TensorFlow not found."
config <- py_config()
if (!is.null(config)) {
if (length(config$python_versions) > 0) {
message <- paste0(message,
"\n\nPython environments searched for 'tensorflow' package:\n")
python_versions <- paste0(" ", normalizePath(config$python_versions, mustWork = FALSE),
collapse = "\n")
message <- paste0(message, python_versions, sep = "\n")
}
}
python_error <- tryCatch({
import("tensorflow")
list(message = NULL)
},
error = function(e) {
on.exit(py_clear_last_error())
py_last_error()
})
message <- paste0(message,
"\nPython exception encountered:\n ",
python_error$message, "\n")
message <- paste0(message,
"\nYou can install TensorFlow using the install_tensorflow() function.\n")
message
}
|
.plotfun <- function(x, y, type, xlab, ylab, main, plot, add, ... ) {
if (plot & add) {
called <- tryCatch( {par(new = TRUE); TRUE}, warning = function(x) FALSE)
if (!called) {
warning("Both \'plot\' and \'add\' are TRUE, \'add\' is set to FALSE:
the results are plotted in a separate plot.")
add <- FALSE
} else {
warning("Both \'plot\' and \'add\' are TRUE, \'plot\' is set to FALSE:
the results are added to an existing plot.")
plot <- FALSE
}
}
if (plot | add) {
if ( plot ) {
plot(x, y, type = type, xlab = xlab, ylab = ylab, main = main, ...)
} else {
lines(x, y, ...)
}
}
}
.checkInput <- function (data, gamma, scale, DT, pos = TRUE, gammapos = TRUE,
scalepos = TRUE, DTpos = TRUE, r = 1) {
if (!is.numeric(data)) {
stop("data should be a numeric vector.")
}
n <- length(data)
if (n == 1) {
stop("We need at least two data points.")
}
if (pos) {
if (min(data) <= 0) {
stop("data can only contain strictly positive values.")
}
}
if (!missing(gamma)) {
if (!is.numeric(gamma)) {
stop("gamma should be a numeric vector.")
}
if (gammapos & min(gamma, na.rm = TRUE) <= 0) {
stop("gamma can only contain strictly positive values.")
}
if (!(length(gamma) %in% c(n - 2, n - 1, n) + (r - 1) )) {
stop(paste0("gamma should have length ", n - 2, ", ", n - 1,
" or ", n, "."))
}
}
if (!missing(scale)) {
if (!is.numeric(scale)) {
stop("scale should be a numeric vector.")
}
if (scalepos & min(scale, na.rm = TRUE) <= 0) {
stop("scale can only contain strictly positive values.")
}
if (!(length(scale) %in% c(n - 2, n - 1, n))) {
stop(paste("scale should have length", n - 2, ",", n - 1, "or", n))
}
}
if (!missing(gamma) & !missing(scale)) {
if (length(gamma) != length(scale)) {
stop("gamma and scale should have the same length.")
}
}
if (!missing(DT)) {
if (!is.numeric(DT)) {
stop("DT should be a numeric vector.")
}
if (DTpos) {
if (min(DT, na.rm = TRUE) < 0) {
stop("DT can only contain positive values.")
}
}
if (length(DT) != 1 & length(DT) != (n - r)) {
stop(paste("DT should have length 1 or length", n - r))
}
}
}
.checkProb <- function(p, l = 1) {
if (length(p) != l) {
stop(paste0("p should be a numeric of length ", l, "."))
}
if (is.numeric(p)) {
if (p < 0 | p > 1) {
stop("p should be between 0 and 1.")
}
} else {
stop("p should be numeric.")
}
}
.checkCensored <- function(censored, n) {
if (length(censored) != 1) {
if (n != length(censored)) {
stop("data and censored should have the same length.")
}
} else {
censored <- rep(censored, n)
}
if (!is.logical(censored)) {
if (!all(censored == 1 | censored == 0)) {
stop("censored should be a logical vector.")
} else {
censored <- as.logical(censored)
}
}
if (all(censored)) {
stop("Not all data points can be censored.")
}
return(censored)
}
.output <- function(x, plot, add) {
if (plot || add) {
return(invisible(x))
} else {
return(x)
}
}
|
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
)
library(gaussplotR)
data(gaussplot_sample_data)
samp_dat <-
gaussplot_sample_data[,1:3]
gauss_fit_cir_user <-
fit_gaussian_2D(samp_dat,
constrain_amplitude = TRUE,
method = "circular",
user_init = c(25.72529, -2.5, 1.7, 1.3, 1.6),
print_initial_params = TRUE)
gauss_fit_cir_user
gauss_fit_cir <-
fit_gaussian_2D(samp_dat,
method = "circular")
gauss_fit_cir
|
isStrictlyNegativeIntegerOrNanOrInfVectorOrNull <- function(argument, default = NULL, stopIfNot = FALSE, n = NA, message = NULL, argumentName = NULL) {
checkarg(argument, "N", default = default, stopIfNot = stopIfNot, nullAllowed = TRUE, n = NA, zeroAllowed = FALSE, negativeAllowed = TRUE, positiveAllowed = FALSE, nonIntegerAllowed = FALSE, naAllowed = FALSE, nanAllowed = TRUE, infAllowed = TRUE, message = message, argumentName = argumentName)
}
|
add_gml_mids <- function(data, keep, init = "sidea-all-joiners") {
if (init %nin% c("sidea-all-joiners", "sidea-with-joiners", "sidea-orig")) {
stop("init must be one of 'sidea-all-joiners', 'sidea-with-joiners', or 'sidea-orig'. You may have mispelled something. This argument applies only to state-year or leader-year analyses.")
}
if (length(attributes(data)$ps_data_type) > 0 && attributes(data)$ps_data_type == "dyad_year") {
if (!all(i <- c("ccode1", "ccode2") %in% colnames(data))) {
stop("add_gml_mids() merges on two Correlates of War codes (ccode1, ccode2), which your data don't have right now. Make sure to run create_dyadyears() at the top of the pipe. You'll want the default option, which returns Correlates of War codes.")
} else {
if (nrow(data %>% filter(.data$ccode1 > .data$ccode2)) == 0) {
message("Dyadic data are non-directed and initiation variables make no sense in this context.")
if (missing(keep)) {
gml_mid_ddydisps %>% select(everything()) -> dirdisp
} else {
gml_mid_ddydisps %>% select(one_of("ccode1", "ccode2", "year", "gmlmidonset", "gmlmidongoing", keep)) -> dirdisp
}
dirdisp %>%
left_join(data, .) %>%
mutate_at(vars("gmlmidonset", "gmlmidongoing"), ~ifelse(is.na(.) & between(.data$year, 1816, 2010), 0, .)) -> data
} else {
if (init == "sidea-orig") {
gml_mid_ddydisps %>%
mutate(init1 = ifelse(.data$sidea1 == 1 & .data$orig1 == 1, 1, 0),
init2 = ifelse(.data$sidea2 == 1 & .data$orig2 == 1, 1, 0)) -> hold_this
} else if (init == "sidea-with-joiners") {
gml_mid_ddydisps %>%
mutate(init1 = ifelse(.data$sidea1 == 1 | (.data$orig1 == 0 & .data$sidea1 == 1), 1, 0),
init2 = ifelse(.data$sidea2 == 1 | (.data$orig2 == 0 & .data$sidea2 == 1), 1, 0)) -> hold_this
} else if (init == "sidea-all-joiners") {
gml_mid_ddydisps %>%
mutate(init1 = ifelse(.data$sidea1 == 1 | (.data$orig1 == 0), 1, 0),
init2 = ifelse(.data$sidea2 == 1 | (.data$orig2 == 0), 1, 0) ) -> hold_this
}
if (missing(keep)) {
hold_this %>% select(everything()) -> dirdisp
} else {
hold_this %>% select(one_of("ccode1", "ccode2", "year",
"gmlmidonset", "gmlmidongoing",
"init1", "init2",
"sidea1", "sidea2", "orig1", "orig2",
keep)) -> dirdisp
}
dirdisp %>%
left_join(data, .) %>%
mutate_at(vars("gmlmidonset", "gmlmidongoing"), ~ifelse(is.na(.) & between(.data$year, 1816, 2010), 0, .)) -> data
}
message("add_gml_mids() IMPORTANT MESSAGE: By default, this function whittles dispute-year data into dyad-year data by first selecting on unique onsets. Thereafter, where duplicates remain, it whittles dispute-year data into dyad-year data in the following order: 1) retaining highest `fatality`, 2) retaining highest `hostlev`, 3) retaining highest estimated `mindur`, 4) retaining reciprocated over non-reciprocated observations, 5) retaining the observation with the lowest start month, and, where duplicates still remained (and they don't), 6) forcibly dropping all duplicates for observations that are otherwise very similar.\nSee: http://svmiller.com/peacesciencer/articles/coerce-dispute-year-dyad-year.html")
return(data)
}
} else if (length(attributes(data)$ps_data_type) > 0 && attributes(data)$ps_data_type == "state_year") {
if (!all(i <- c("ccode") %in% colnames(data))) {
stop("add_gml_mids() for leader-year data merges on Correlates of War state codes (ccode), which you don't have.")
}
gml_part %>%
filter(.data$allmiss_leader_start == 0 & .data$allmiss_leader_end == 0) %>%
rowwise() %>%
mutate(year = list(seq(.data$styear, .data$endyear)),
gmlmidonset = list(ifelse(.data$year == min(.data$year), 1, 0))) %>%
unnest(c(.data$year, .data$gmlmidonset)) %>%
mutate(gmlmidongoing = 1) -> hold_this
if (init == "sidea-orig") {
hold_this %>%
mutate(gmlmidongoing_init = ifelse(.data$gmlmidongoing == 1 & (.data$sidea == 1 & .data$orig == 1), 1, 0),
gmlmidonset_init = ifelse(.data$gmlmidonset == 1 & .data$gmlmidongoing_init == 1, 1, 0)) %>%
select(.data$dispnum:.data$ccode, .data$year, .data$gmlmidonset:ncol(.)) -> hold_this
} else if (init == "sidea-with-joiners") {
hold_this %>%
mutate(gmlmidongoing_init = ifelse(.data$gmlmidongoing == 1 & (.data$sidea == 1 | ( .data$orig == 0 & .data$sidea == 1)), 1, 0),
gmlmidonset_init = ifelse(.data$gmlmidonset == 1 & .data$gmlmidongoing_init == 1, 1, 0)) %>%
select(.data$dispnum:.data$ccode, .data$year, .data$gmlmidonset:ncol(.)) -> hold_this
} else if (init == "sidea-all-joiners") {
hold_this %>%
mutate(gmlmidongoing_init = ifelse(.data$gmlmidongoing == 1 & (.data$sidea == 1 | ( .data$orig == 0)), 1, 0),
gmlmidonset_init = ifelse(.data$gmlmidonset == 1 & .data$gmlmidongoing_init == 1, 1, 0)) %>%
select(.data$dispnum:.data$ccode, .data$year, .data$gmlmidonset:ncol(.)) -> hold_this
}
hold_this %>%
group_by(.data$ccode, .data$year) %>%
summarize(gmlmidongoing = sum(.data$gmlmidongoing),
gmlmidonset = sum(.data$gmlmidonset),
gmlmidongoing_init = sum(.data$gmlmidongoing_init),
gmlmidonset_init = sum(.data$gmlmidonset_init)) %>%
mutate_at(vars(c(.data$gmlmidongoing, .data$gmlmidonset, .data$gmlmidongoing_init, .data$gmlmidonset_init)), ~ifelse(. >= 1, 1, 0)) %>%
ungroup() -> hold_this
data %>%
left_join(., hold_this) -> data
data %>%
mutate_at(vars(c(.data$gmlmidongoing, .data$gmlmidonset, .data$gmlmidongoing_init, .data$gmlmidonset_init)), ~ifelse(is.na(.), 0, .)) -> data
} else if (length(attributes(data)$ps_data_type) > 0 && attributes(data)$ps_data_type == "leader_year") {
if (!all(i <- c("ccode") %in% colnames(data))) {
stop("add_gml_mids() for leader-year data merges on Correlates of War state codes (ccode), which you don't have.")
}
leaderdays <- create_leaderdays(standardize = "cow")
gml_part %>%
filter(.data$allmiss_leader_start == 0 & .data$allmiss_leader_end == 0) %>%
mutate(stdate = as.Date(paste0(.data$styear,"/", .data$stmon,"/", .data$dummy_stday)),
enddate = as.Date(paste0(.data$endyear,"/", .data$endmon,"/", .data$dummy_endday))) %>%
rowwise() %>%
mutate(date = list(seq(.data$stdate, .data$enddate, by = "1 day")),
gmlmidonset = list(ifelse(date == min(.data$date), 1, 0))) %>%
unnest(c(.data$date, .data$gmlmidonset)) %>%
mutate(gmlmidongoing = 1) %>%
select(.data$dispnum:.data$ccode, .data$obsid_start, .data$sidea, .data$orig, .data$date, .data$gmlmidongoing, .data$gmlmidonset) %>%
left_join(leaderdays, .) -> hold_this
if (init == "sidea-orig") {
hold_this %>%
mutate(gmlmidongoing_init = ifelse(.data$gmlmidongoing == 1 & .data$obsid_start == .data$obsid & (.data$sidea == 1 & .data$orig == 1), 1, 0),
gmlmidonset_init = ifelse(.data$gmlmidonset == 1 & .data$gmlmidongoing_init == 1, 1, 0)) -> hold_this
} else if (init == "sidea-with-joiners") {
hold_this %>%
mutate(gmlmidongoing_init = ifelse(.data$gmlmidongoing == 1 & .data$obsid_start == .data$obsid & (.data$sidea == 1 | ( .data$orig == 0 & .data$sidea == 1 )), 1, 0),
gmlmidonset_init = ifelse(.data$gmlmidonset == 1 & .data$gmlmidongoing_init == 1, 1, 0)) -> hold_this
} else if (init == "sidea-all-joiners") {
hold_this %>%
mutate(gmlmidongoing_init = ifelse(.data$gmlmidongoing == 1 & .data$obsid_start == .data$obsid & (.data$sidea == 1 | (.data$orig == 0)), 1, 0),
gmlmidonset_init = ifelse(.data$gmlmidonset == 1 & .data$gmlmidongoing_init == 1, 1, 0)) -> hold_this
}
hold_this %>%
mutate(year = .pshf_year(.data$date)) %>%
group_by(.data$obsid, .data$year) %>%
summarize(gmlmidongoing = sum(.data$gmlmidongoing, na.rm=T),
gmlmidonset = sum(.data$gmlmidonset, na.rm=T),
gmlmidongoing_init = sum(.data$gmlmidongoing_init, na.rm=T),
gmlmidonset_init = sum(.data$gmlmidonset_init, na.rm=T)) %>%
ungroup() -> hold_this
hold_this %>%
mutate_at(vars("gmlmidongoing", "gmlmidonset", "gmlmidongoing_init", "gmlmidonset_init"), ~ifelse(.data$year >= 2011, NA, .)) %>%
mutate_at(vars("gmlmidongoing", "gmlmidonset", "gmlmidongoing_init", "gmlmidonset_init"), ~ifelse(. >= 1, 1, 0)) -> hold_this
data %>%
left_join(., hold_this) -> data
} else if (length(attributes(data)$ps_data_type) > 0 && attributes(data)$ps_data_type == "leader_dyad_year") {
if (!all(i <- c("ccode1", "ccode2") %in% colnames(data))) {
stop("add_gml_mids() merges on two Correlates of War codes (ccode1, ccode2), which your data don't have right now. Make sure to run create_leaderdyadyears(system='cow') at the top of the pipe.")
}
if (nrow(data %>% filter(.data$ccode1 > .data$ccode2)) == 0) {
message("The leader-dyadic data are non-directed and initiation variables make no sense in this context.")
data %>%
left_join(., gml_mid_ddlydisps) -> hold_this
hold_this %>%
mutate_at(vars("gmlmidonset", "gmlmidongoing"), ~ifelse(is.na(.) & between(.data$year, 1816, 2010), 0, .)) -> data
} else {
data %>%
left_join(., gml_mid_ddlydisps) -> hold_this
if (init == "sidea-orig") {
hold_this %>%
mutate(gmlmidongoing_init = ifelse(.data$gmlmidongoing == 1 & .data$obsid_start1 == .data$obsid1 & (.data$sidea1 == 1 & .data$orig1 == 1), 1, 0),
gmlmidonset_init = ifelse(.data$gmlmidonset == 1 & .data$gmlmidongoing_init == 1, 1, 0)) -> hold_this
} else if (init == "sidea-with-joiners") {
hold_this %>%
mutate(gmlmidongoing_init = ifelse(.data$gmlmidongoing == 1 & .data$obsid_start1 == .data$obsid1 & (.data$sidea1 == 1 | ( .data$orig1 == 0 & .data$sidea1 == 1 )), 1, 0),
gmlmidonset_init = ifelse(.data$gmlmidonset == 1 & .data$gmlmidongoing_init == 1, 1, 0)) -> hold_this
} else if (init == "sidea-all-joiners") {
hold_this %>%
mutate(gmlmidongoing_init = ifelse(.data$gmlmidongoing == 1 & .data$obsid_start1 == .data$obsid1 & (.data$sidea1 == 1 | (.data$orig1 == 0)), 1, 0),
gmlmidonset_init = ifelse(.data$gmlmidonset == 1 & .data$gmlmidongoing_init == 1, 1, 0)) -> hold_this
}
hold_this %>%
mutate_at(vars("gmlmidonset", "gmlmidongoing",
"gmlmidonset_init", "gmlmidongoing_init"), ~ifelse(is.na(.) & !(is.na(obsid1) & is.na(obsid2)) & between(.data$year, 1816, 2010), 0, .)) -> data
}
} else {
stop("add_gml_mids() requires a data/tibble with attributes$ps_data_type of state_year, leader_year, or dyad_year. Try running create_dyadyears(), create_leaderyears(), or create_stateyears() at the start of the pipe.")
}
return(data)
}
|
library(titrationCurves)
wb_sa(eqpt = TRUE, main = "Titration of WB w/ SA")
wb_sa(pka = 7, col = "blue", overlay = TRUE)
wb1 = wb_sa(pka = 8)
wb2 = wb_sa(pka = 6)
head(wb1)
plot(wb1, ylim = c(0, 12), xlim = c(0, 80), type = "l", col = "blue",
lwd = 2, xlab = "volume of titrant in mL")
lines(wb2, col = "green", lwd = 2)
abline(v = 50, col = "red", lty = 2)
legend(x = "topright", legend = c("pKa = 8", "pKa = 6"),
col = c("blue", "green"), lty = 1, lwd = 2)
metal_edta(eqpt = TRUE)
metal_edta(logkf = 6, col = "blue", overlay = TRUE)
redox_titration(eqpt = TRUE)
redox_titration(pot.analyte = 0.5, pot.titrant = 1.5, col = "blue", overlay = TRUE)
ppt_mixture(eqpt = TRUE)
ppt_mixture(pksp1 = 12, pksp2 = 8, col = "blue", overlay = TRUE)
wbd = derivative(wb1)
str(wbd)
plot(wbd$first_deriv, xlim = c(48, 52), col = "blue", type = "l", lwd = 2,
xlab = "volume of titrant in mL", ylab = "first derivative")
abline(v = 50, col = "red", lty = 2)
triwa_sb(conc.acid = 0.0400, conc.base = 0.120, pka1 = 3.128, pka2 = 4.761,
pka3 = 6.396, col = "blue", eqpt = TRUE)
wa_sb(pka = 8, pkw = 20, col = "blue", eqpt = TRUE)
wa_sb(pka = 8, col = "green", overlay = TRUE)
legend(x = "topleft", legend = c("non-aqueous", "aqueous"),
col = c("blue", "green"), lty = 1, lwd = 2)
metal_edta(col = "blue", eqpt = TRUE)
metal_edta(ph = 7, col = "green", overlay = TRUE)
legend(x = "topleft", legend = c("pH = 10", "pH = 7"),
col = c("blue", "green"), lty = 1, lwd =2)
metal_edta(conc.metal = 0.0500, conc.edta = 0.025, vol.metal = 25.0,
alpha.metal = 0.00415, logkf = 18.80, col = "blue", eqpt = TRUE)
metal_edta(conc.metal = 0.0500, conc.edta = 0.0250, vol.metal = 25.0,
alpha.metal = 4.63e-10, logkf = 18.80, col = "green", overlay = TRUE)
legend(x = "topleft",
legend = c(expression(paste("0.0010 M N", H[3])),
expression(paste("0.10 M N", H[3]))),
col = c("blue", "green"), lty = 1, lwd = 2)
redox_titration(pot.analyte = 0.154, elec.analyte = 2, pot.titrant = 1.72,
col = "blue", eqpt = TRUE)
redox_titration(pot.analyte = 0.771, pot.titrant = 1.51, elec.titrant = 5,
col = "black", eqpt = TRUE)
redox_titration(pot.analyte = 0.771, pot.titrant = 1.415, elec.titrant = 5,
col = "blue", overlay =TRUE)
redox_titration(pot.analyte = 0.771, pot.titrant = 1.321, elec.titrant = 5,
col = "green", overlay = TRUE)
legend(x = "topleft", legend = c("pH = 0", "pH = 1", "ph = 2"),
col = c("black", "blue", "green"), lty = 1, lwd = 2)
p.a = ppt_analyte(eqpt = TRUE)
p.t = ppt_titrant(overlay = TRUE)
plot(p.a, col = "blue", type = "l", lwd = 2, xlim = c(0,50), ylim = c(0,15),
xlab = "volume of titrant (mL)", ylab = "pAg or pI")
lines(p.t, col = "green", lwd = 2)
legend(x = "left", legend = c("pAg", "pI"), col = c("blue", "green"),
lty = 1, lwd = 2)
ppt_mixture(col = "blue", eqpt = TRUE)
|
test_that("Archive", {
a = Archive$new(PS_2D, FUN_2D_CODOMAIN)
expect_output(print(a), "Archive")
expect_equal(a$n_evals, 0)
expect_equal(a$cols_x, c("x1", "x2"))
expect_equal(a$cols_y, c("y"))
xdt = data.table(x1 = 0, x2 = 1)
xss_trafoed = list(list(x1 = 0, x2 = 1))
ydt = data.table(y = 1)
a$add_evals(xdt, xss_trafoed, ydt)
expect_equal(a$n_evals, 1)
expect_equal(a$data$x_domain, xss_trafoed)
adt = as.data.table(a)
expect_data_table(adt, nrows = 1)
expect_names(colnames(adt), identical.to = c("x1", "x2", "y", "timestamp", "batch_nr", "x_domain_x1", "x_domain_x2"))
a$clear()
expect_data_table(a$data, nrows = 0)
adt = as.data.table(a)
expect_data_table(adt, nrows = 0)
a$add_evals(xdt, NULL, ydt)
adt = as.data.table(a)
expect_data_table(adt, nrows = 1)
expect_names(colnames(adt), identical.to = c("x1", "x2", "y", "timestamp", "batch_nr"))
})
test_that("Archive best works", {
a = Archive$new(PS_2D, FUN_2D_CODOMAIN)
xdt = data.table(x1 = c(0, 0.5), x2 = c(1, 1))
xss_trafoed = list(list(x1 = c(0, 0.5), x2 = c(1, 1)))
ydt = data.table(y = c(1, 0.25))
a$add_evals(xdt, xss_trafoed, ydt)
expect_equal(a$best()$y, 0.25)
xdt = data.table(x1 = 1, x2 = 1)
xss_trafoed = list(list(x1 = 1, x2 = 1))
ydt = data.table(y = 2)
a$add_evals(xdt, xss_trafoed, ydt)
expect_equal(a$best(batch = 2)$batch_nr, 2L)
a = Archive$new(PS_2D, FUN_2D_2D_CODOMAIN)
xdt = data.table(x1 = c(-1, -1, -1), x2 = c(1, 0, -1))
xss_trafoed = list(list(x1 = -1, x2 = 1), list(x1 = -1, x2 = 0), list(x1 = -1, x2 = 1))
ydt = data.table(y1 = c(1, 1, 1), y2 = c(-1, 0, -1))
a$add_evals(xdt, xss_trafoed, ydt)
expect_equal(a$best()$y2, 0)
})
test_that("Archive on 1D problem works", {
a = Archive$new(PS_1D, FUN_1D_CODOMAIN)
xdt = data.table(x = 1)
xss_trafoed = list(list(x = 1))
ydt = data.table(y = 1)
a$add_evals(xdt, xss_trafoed, ydt)
expect_equal(a$n_evals, 1)
expect_equal(a$data$x_domain, xss_trafoed)
expect_list(a$data$x_domain[[1]])
xdt = data.table(x = 2)
expect_error(a$add_evals(xdt, transpose_list(xdt), ydt), "Element 1 is not")
})
test_that("Unnest columns", {
a = Archive$new(PS_2D, FUN_2D_CODOMAIN)
xdt = data.table(x1 = 0, x2 = 1)
xss_trafoed = list(list(x1 = 1, x2 = 2))
ydt = data.table(y = 1)
a$add_evals(xdt, xss_trafoed, ydt)
adt = as.data.table(a)
expect_names(colnames(adt), identical.to = c("x1", "x2", "y", "timestamp", "batch_nr", "x_domain_x1", "x_domain_x2"))
expect_equal(adt$x_domain_x1, 1)
expect_equal(adt$x_domain_x2, 2)
xdt = data.table(x1 = 0.5, x2 = 2)
expect_error(a$add_evals(xdt, xss_trafoed, ydt), "Element 1 is not")
})
test_that("NAs in ydt throw an error", {
a = Archive$new(PS_1D, FUN_1D_CODOMAIN)
xdt = data.table(x = 1)
xss_trafoed = list(list(x = 1))
ydt = data.table(y = NA)
expect_error(a$add_evals(xdt, xss_trafoed, ydt), "Contains missing values")
})
test_that("start_time is set by Optimizer", {
inst = MAKE_INST()
expect_null(inst$archive$start_time)
optimizer = OptimizerRandomSearch$new()
time = Sys.time()
optimizer$optimize(inst)
expect_equal(inst$archive$start_time, time, tolerance = 0.5)
})
test_that("check_values flag works", {
a = Archive$new(PS_2D, FUN_2D_CODOMAIN, check_values = FALSE)
xdt = data.table(x1 = c(0, 2), x2 = c(1, 1))
xss_trafoed = list(list(x1 = c(0, 0.5), x2 = c(1, 1)))
ydt = data.table(y = c(1, 0.25))
a$add_evals(xdt, xss_trafoed, ydt)
a = Archive$new(PS_2D, FUN_2D_CODOMAIN, check_values = TRUE)
xdt = data.table(x1 = c(0, 2), x2 = c(1, 1))
xss_trafoed = list(list(x1 = c(0, 0.5), x2 = c(1, 1)))
ydt = data.table(y = c(1, 0.25))
expect_error(a$add_evals(xdt, xss_trafoed, ydt), "x1: Element 1 is not <= 1.", fixed = TRUE)
})
test_that("deep clone works", {
a1 = Archive$new(PS_2D, FUN_2D_CODOMAIN)
xdt = data.table(x1 = 0, x2 = 1)
xss_trafoed = list(list(x1 = 0, x2 = 1))
ydt = data.table(y = 1)
a1$add_evals(xdt, xss_trafoed, ydt)
a2 = a1$clone(deep = TRUE)
expect_different_address(a1$data, a2$data)
expect_different_address(a1$search_space, a2$search_space)
expect_different_address(a1$codomain, a2$codomain)
})
|
fitted.ellipsesummarylist <- function(object,...){
g <- object
thenames <- g$Boot.Estimates[,1:(which(colnames(g$Boot.Estimates)=="b.x")-1)]
thelengths <- lapply(g$models, function(x) length(x$pred.x))
rowvec <- mapply(function(x,y) rep(x,each=y),1:length(thelengths),y=thelengths)
thenames <- thenames[rowvec,]
thefittedx<-lapply(g$models,function (x) x$pred.x)
thefittedx <- unlist(thefittedx)
thefittedy<-lapply(g$models,function (x) x$pred.y)
thefittedy <- unlist(thefittedy)
data.frame(thenames,"input"=thefittedx,"output"=thefittedy)
}
|
select_folder_int <- function(self, name, mute, retries) {
check_args(name = name, mute = mute, retries = retries)
retries <- as.integer(retries)
folder <- adjust_folder_name(name)
url <- self$con_params$url
h <- self$con_handle
tryCatch({
curl::handle_setopt(h, customrequest = paste0('SELECT ', folder))
}, error = function(e){
stop("The connection handle is dead. Please, configure a new IMAP connection with configure_imap().")
})
response <- tryCatch({
curl::curl_fetch_memory(url, handle = h)
}, error = function(e){
response_error_handling(e$message[1])
})
if(is.null(response)){
count_retries = 0
while (is.null(response) && count_retries < retries) {
count_retries = count_retries + 1
response <- tryCatch({
curl::curl_fetch_memory(url, handle = h)
}, error = function(e){
response_error_handling(e$message[1])
})
}
if (is.null(response)) {
stop('Request error: the server returned an error.')
} else {
if (!mute) {
if (self$con_params$verbose) {
Sys.sleep(0.01)
}
cat(paste0("\n::mRpostman: ", '"', name, '"', " selected.\n"))
}
}
} else {
if (!mute) {
if (self$con_params$verbose) {
Sys.sleep(0.01)
}
cat(paste0("\n::mRpostman: ", '"', name, '"', " selected.\n"))
}
}
invisible(name)
}
|
plot_ppsurv <- function(data, dist, time = "time", censor = "censor") {
fit <- fit_data(data, dist, time, censor)
data <- data[order(data[[time]], -data[[censor]]),]
n_all <- nrow(data)
data$rank <- as.numeric(rownames(data))
data$rev_rank <- rev(data$rank)
data <- data[data[[censor]] == 1, ]
n <- nrow(data)
adj_rank <- 0
for (i in 1:nrow(data)) {
adj_rank <- (data$rev_rank[i] * adj_rank + (n_all + 1)) / (data$rev_rank[i] + 1)
data$adj_rank[i] <- adj_rank
}
pfunc <- match.fun(paste("p", dist, sep = ""))
z <- c()
Fz <- c()
for (i in 1:length(data[[time]])) {
Fz <- c(Fz, (data$adj_rank[i] - 0.3) / (n_all + 0.4))
args <- c(q = data[[time]][i], fit$estimate)
args <- split(unname(args), names(args))
z <- c(z, do.call(pfunc, args) * 100)
}
line <- seq(0, 100, length.out = length(z))
Fz <- Fz * 100
df <- data.frame(Fz, z, line)
p <- ggplot(df, aes(x = Fz, y = z)) + geom_point() +
geom_line(aes(x = line, y = line)) +
scale_x_continuous(name = "Sample") +
scale_y_continuous(name = "Theoretical") +
expand_limits(x = c(0, 100), y = c(0, 100)) +
ggtitle(paste(dist, "probability plot")) +
theme(axis.text.x = element_text(size = rel(1.5)),
axis.text.y = element_text(size = rel(1.5)),
axis.title.y = element_text(size = rel(1.5)),
axis.title.x = element_text(size = rel(1.5)),
plot.title = element_text(size = rel(2)))
plot(p)
}
|
context("median regression fit: single mediator, no covariates")
library("robmed", quietly = TRUE)
n <- 250
a <- c <- 0.2
b <- 0
seed <- 20190201
set.seed(seed)
X <- rnorm(n)
M <- a * X + rnorm(n)
Y <- b * M + c * X + rnorm(n)
test_data <- data.frame(X, Y, M)
foo <- fit_mediation(test_data, x = "X", y = "Y", m = "M",
method = "regression", robust = "median")
bar <- summary(foo)
test_that("output has correct structure", {
expect_s3_class(foo, "reg_fit_mediation")
expect_s3_class(foo, "fit_mediation")
expect_s3_class(foo$fit_mx, "rq")
expect_s3_class(foo$fit_ymx, "rq")
expect_null(foo$fit_yx)
})
test_that("arguments are correctly passed", {
expect_identical(foo$x, "X")
expect_identical(foo$y, "Y")
expect_identical(foo$m, "M")
expect_identical(foo$covariates, character())
expect_identical(foo$robust, "median")
expect_identical(foo$family, "gaussian")
expect_null(foo$control)
expect_false(foo$contrast)
})
test_that("dimensions are correct", {
expect_length(foo$a, 1L)
expect_length(foo$b, 1L)
expect_length(foo$direct, 1L)
expect_length(foo$total, 1L)
expect_length(foo$ab, 1L)
expect_length(coef(foo$fit_mx), 2L)
expect_length(coef(foo$fit_ymx), 3L)
expect_identical(dim(foo$data), c(as.integer(n), 3L))
})
test_that("values of coefficients are correct", {
expect_equivalent(foo$a, coef(foo$fit_mx)["X"])
expect_equivalent(foo$b, coef(foo$fit_ymx)["M"])
expect_equivalent(foo$direct, coef(foo$fit_ymx)["X"])
expect_equivalent(foo$total, foo$a * foo$b + foo$direct)
expect_equivalent(foo$ab, foo$a * foo$b)
})
test_that("output of coef() method has correct attributes", {
coefficients <- coef(foo)
expect_length(coefficients, 5L)
expect_named(coefficients, c("a", "b", "Direct", "Total", "ab"))
})
test_that("coef() method returns correct values of coefficients", {
expect_equivalent(coef(foo, parm = "a"), foo$a)
expect_equivalent(coef(foo, parm = "b"), foo$b)
expect_equivalent(coef(foo, parm = "Direct"), foo$direct)
expect_equivalent(coef(foo, parm = "Total"), foo$total)
expect_equivalent(coef(foo, parm = "ab"), foo$ab)
})
test_that("summary returns original object", {
expect_identical(foo, bar)
})
test_that("object returned by setup_xxx_plot() has correct structure", {
expect_error(setup_ellipse_plot(foo))
expect_error(setup_weight_plot(foo))
})
fit_f1 <- fit_mediation(Y ~ m(M) + X, data = test_data,
method = "regression", robust = "median")
fit_f2 <- fit_mediation(Y ~ m(M) + X,
method = "regression", robust = "median")
med <- m(M)
fit_f3 <- fit_mediation(Y ~ med + X, data = test_data,
method = "regression", robust = "median")
test_that("formula interface works correctly", {
expect_equal(fit_f1, foo)
expect_equal(fit_f2, foo)
expect_equal(fit_f3, foo)
})
|
.sRGB_to_XYZ <- matrix(
data = c(0.4124564, 0.3575761, 0.1804375,
0.2126729, 0.7151522, 0.0721750,
0.0193339, 0.1191920, 0.9503041),
nrow = 3, ncol = 3, byrow = TRUE
)
.XYZ_to_sRGB <- matrix(
data = c(3.2404542, -1.5371385, -0.4985314,
-0.9692660, 1.8760108, 0.0415560,
0.0556434, -0.2040259, 1.0572252),
nrow = 3, ncol = 3, byrow = TRUE
)
.XYZ_to_LMS <- matrix(
data = c(0.4002, 0.7076, -0.0808,
-0.2263, 1.1653, 0.0457,
0.0000, 0.0000, 0.9182),
nrow = 3, ncol = 3, byrow = TRUE
)
source("./data-raw/schemes_FabioCrameri.R")
source("./data-raw/schemes_PaulTol.R")
source("./data-raw/schemes_OkabeIto.R")
source("./data-raw/schemes_science.R")
.schemes <- c(schemes_crameri2020, schemes_tol2018, schemes_okabe2008,
schemes_science)
usethis::use_data(.schemes, .sRGB_to_XYZ, .XYZ_to_sRGB, .XYZ_to_LMS,
internal = TRUE, overwrite = TRUE)
|
blatentModel <-
R6::R6Class(
classname = "blatentModel",
public = list(
attributeAnalyses = NULL,
chain = NULL,
data = NULL,
dataParameterSummary = NULL,
estimatedLatentVariables = NULL,
informationCriteria = NULL,
logLikelihoods = NULL,
options = NULL,
parameterSummary = NULL,
PPMC = NULL,
specs = NULL,
variables = NULL,
analyzeCategoricalStructuralModel = function(type = c("loglinear", "tetrachoric"), correct = .01){
if (self$specs$nCategoricalLatents != 0){
if (self$options$parallel){
cl = parallel::makeCluster(self$options$nCores, outfile="", setup_strategy = "sequential")
parallel::clusterExport(
cl = cl,
varlist = c("self", "type", "correct"),
envir = environment()
)
self$attributeAnalyses$chain = parallel::parLapply(
cl = cl,
X = 1:length(self$chain),
fun = chainAttributeAnalysis,
model = self,
type = type,
correct = correct
)
parallel::stopCluster(cl = cl)
} else {
self$attributeAnalyses$chain = lapply(
X = 1:length(self$chain),
FUN = chainAttributeAnalysis,
model = self,
type = type,
correct = correct
)
}
self$attributeAnalyses$summary = chainSummary(chain = self$attributeAnalyses$chain,
HDPIntervalValue = self$options$HDPIntervalValue)
self$attributeAnalyses$summary = as.data.frame(self$attributeAnalyses$summary[,1:11])
}
},
calculateLogLikelihoods = function(force = FALSE){
if(!private$likelihoodsCalculated | force){
self$logLikelihoods = list()
self$logLikelihoods$routines = list()
self$logLikelihoods$marginal = matrix(data = NA, nrow = self$options$nSampled*self$options$nChains, ncol = self$specs$nUnits)
self$logLikelihoods$conditional = matrix(data = NA, nrow = self$options$nSampled*self$options$nChains, ncol = self$specs$nUnits)
if (self$specs$nLatentVariables == 0){
self$logLikelihoods$routines$calculateMarginalLogLikelihood = logLikelihoodObservedOnly
self$logLikelihoods$type = ""
} else {
self$logLikelihoods$type = "Marginal "
if (self$specs$nJointVariables == 0){
self$specs$attributeProfile = matrix(data = NA, nrow = 2^self$specs$nLatents, ncol = self$specs$nLatents)
for (profile in 1:2^self$specs$nLatents){
self$specs$attributeProfile[profile, ] = dec2bin(decimal_number = profile-1, nattributes = self$specs$nLatents, basevector = rep(2, self$specs$nLatents))
}
colnames(self$specs$attributeProfile) = self$specs$latentVariables
self$specs$attributeProfile = as.data.frame(self$specs$attributeProfile)
self$logLikelihoods$routines$calculateMarginalLogLikelihood = logLikelihoodMarginalLatentCategoricalUnivariate
} else {
if (self$specs$nJointVariables == 1){
self$specs$attributeProfile = as.data.frame(self$variables[[self$specs$jointVariables[1]]]$attributeProfile)
self$logLikelihoods$routines$calculateMarginalLogLikelihood = logLikelihoodMarginalLatentCategoricalJoint
}
}
}
for (chain in 1:length(self$chain)){
for (iter in 1:nrow(self$chain[[chain]])){
self$movePosteriorToVariableBeta(chain =chain, iteration = iter)
self$logLikelihoods$marginal[(chain-1)*self$options$nSampled+iter,] = self$logLikelihoods$routines$calculateMarginalLogLikelihood(
specs = self$specs, variables = self$variables, data = self$data)
}
}
private$likelihoodsCalculated = TRUE
}
invisible(self)
},
createParameterSummary = function(){
nChains = length(self$chain)
if (class(self$chain) == "list"){
modelChain = lapply(X = self$chain, FUN = function(x) return(x[,self$specs$parameters$paramNames[which(self$specs$parameters$paramTypes == "model")]]))
if (nChains > 1){
stackedModelChain = coda::mcmc(do.call("rbind", lapply(
X = modelChain,
FUN = function(x)
return(as.matrix(x))
)))
modelChain = coda::mcmc.list(lapply(X = modelChain, FUN = coda::mcmc))
} else {
modelChain = self$chain[[1]][,self$specs$parameters$paramNames[which(self$specs$parameters$paramTypes == "model")]]
stackedModelChain = modelChain
modelChain = coda::mcmc(modelChain)
stackedModelChain = coda::mcmc(modelChain)
}
}
chainSummary = summary(modelChain)
chainSummary = cbind(chainSummary$statistics, chainSummary$quantiles)
HPDIval = self$options$HDPIntervalValue
HDPI = coda::HPDinterval(stackedModelChain, prob = HPDIval)
colnames(HDPI) = c(paste0("lowerHDPI", HPDIval), paste0("upperHDPI95", HPDIval))
chainSummary = cbind(chainSummary, HDPI)
if (nChains > 1){
convergenceDiagnostics = coda::gelman.diag(modelChain, multivariate = FALSE)
colnames(convergenceDiagnostics$psrf) = c("PSRF", "PSRF Upper C.I.")
chainSummary = cbind(chainSummary, convergenceDiagnostics$psrf)
} else {
convergenceDiagnostics = coda::heidel.diag(modelChain)
temp = convergenceDiagnostics[, c(3,4)]
colnames(temp) = c("Heidel.Diag p-value", "Heidel.Diag Htest")
chainSummary = cbind(chainSummary, temp)
}
self$parameterSummary = chainSummary
invisible(self)
},
initialize = function(data, specs, options, chain, variables) {
self$data = data
self$specs = specs
self$options = options
self$chain = chain
self$variables = variables
},
movePosteriorMeanToVariableBeta = function(){
if (is.null(self$parameterSummary)) self$createParameterSummary()
self$variables = lapply(
X = self$variables,
FUN = function(x) {
paramVals = self$parameterSummary[which(rownames(self$parameterSummary) %in% x$paramNames), 1]
evalThis = paste0("self$",
self$specs$parameters$paramLocation[which(self$specs$parameters$paramNames %in% x$paramNames)],
"=", paramVals[x$paramNames])
eval(parse(text=evalThis))
return(x)
}
)
invisible(self)
},
movePosteriorToVariableBeta = function(chain, iteration){
if (chain <= length(self$chain) & iteration <= nrow(self$chain[[chain]])){
self$variables = lapply(
X = self$variables,
FUN = function(x, chain, iteration) {
paramVals = self$chain[[chain]][iteration, which(colnames(self$chain[[chain]]) %in% x$paramNames)]
evalThis = paste0("self$",
self$specs$parameters$paramLocation[which(self$specs$parameters$paramNames %in% x$paramNames)],
"=", paramVals[x$paramNames])
eval(parse(text=evalThis))
return(x)
},
chain = chain,
iteration = iteration
)
} else {
stop("self$movePosteriorToVariableBeta: chain or iteration number exceeds values in self.")
}
invisible(self)
},
latentEstimates = function(...){
if (!private$latentEstimatesCalculated){
if (self$specs$nCategoricalLatents > 0){
allCategoricalLVProfiles = matrix(data = NA, nrow = 2^self$specs$nCategoricalLatents,
ncol = self$specs$nCategoricalLatents)
colnames(allCategoricalLVProfiles) = self$specs$latentVariables
for (profile in 1:nrow(allCategoricalLVProfiles)){
allCategoricalLVProfiles[profile,] = dec2bin(decimal_number = profile-1,
nattributes = ncol(allCategoricalLVProfiles),
basevector = rep(2, ncol(allCategoricalLVProfiles)))
}
rownames(allCategoricalLVProfiles) = paste0("profile",
apply(
X = allCategoricalLVProfiles,
MARGIN = 1,
FUN = function(x)
return(paste(x, collapse = ""))
))
temp = lapply(
X = 1:self$specs$nUnits,
FUN = private$getCategoricalLatentEstimates,
profileMatrix = allCategoricalLVProfiles
)
self$estimatedLatentVariables = do.call("rbind", temp)
}
private$latentEstimatesCalculated = TRUE
}
invisible(self)
},
prepareData = function(...){
for (variable in 1:length(self$variables)){
self$data = self$variables[[variable]]$prepareData(data = self$data)
self$specs$underlyingVariables =
c(self$specs$underlyingVariables, self$variables[[variable]]$underlyingVariables)
}
invisible(self)
},
summary = function(numDigits = 3L, ...) {
num.format <-
paste("%", max(8L, numDigits + 5L), ".", numDigits, "f", sep = "")
char.format <-
paste("%", max(8L, numDigits + 5L), "s", sep = "")
headings = paste0(sprintf(char.format, c(" ")), collapse = "")
cat(paste0("\nblatent (version ", packageVersion("blatent"), ") Analysis Summary\n"))
cat(paste0(rep("-", 80), collapse = ""))
cat("\nAnalysis Specs:")
cat("\n")
preamble = paste0(" ", "Algorithm", collapse = "")
paramVals = paste0(sprintf(char.format, self$options$estimator), collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(paramVals)), collapse = "")
cat(paste0(preamble, buffer, paramVals, collapse = ""))
cat("\n")
preamble = paste0(" ", "Number of Model Parameters", collapse = "")
paramVals = paste0(sprintf(char.format, length(which(self$specs$parameters$paramTypes == "model"))), collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(paramVals)), collapse = "")
cat(paste0(preamble, buffer, paramVals, collapse = ""))
cat("\n")
preamble = paste0(" ", "Number of Observations", collapse = "")
paramVals = paste0(sprintf(char.format, length(self$specs$unitList)), collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(paramVals)), collapse = "")
cat(paste0(preamble, buffer, paramVals, collapse = ""))
cat("\n")
cat(paste0(rep("-", 80), collapse = ""))
cat("\n")
cat("Convergence Diagnostics:")
cat("\n")
if (self$options$nChains > 1) {
preamble = paste0(" ", "Maximum Univariate PSRF of Model Parameters:", collapse = "")
paramVals = paste0(sprintf(num.format, max(self$parameterSummary[,"PSRF"])), collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(paramVals)), collapse = "")
cat(paste0(preamble, buffer, paramVals, collapse = ""))
cat("\n")
} else {
preamble = paste0(" ", "Minimum Heidel.Diag p-value of Model Parameters:", collapse = "")
paramVals = paste0(sprintf(num.format, min(self$parameterSummary[,"Heidel.Diag p-value"])), collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(paramVals)), collapse = "")
cat(paste0(preamble, buffer, paramVals, collapse = ""))
cat("\n")
}
cat(paste0(rep("-", 80), collapse = ""))
if (self$options$calculateDIC | self$options$calculateWAIC){
cat("\nInformation Criteria:")
headings = paste0(sprintf(char.format, c(" ")), collapse = "")
if (self$options$calculateDIC & !is.null(self$informationCriteria$DIC)){
cat("\n")
preamble = paste0(" ", "DIC", collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(headings)), collapse = "")
cat(paste0(preamble, buffer, headings))
cat("\n")
preamble = paste0(" ", self$logLikelihoods$type, "DIC", collapse = "")
paramVals = paste0(sprintf(num.format, self$informationCriteria$DIC$DIC), collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(paramVals)), collapse = "")
cat(paste0(preamble, buffer, paramVals, collapse = ""))
cat("\n")
preamble = paste0(" ", self$logLikelihoods$type, "DIC Effective Number of Parameters", collapse = "")
paramVals = paste0(sprintf(num.format, self$informationCriteria$DIC$p_D), collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(paramVals)), collapse = "")
cat(paste0(preamble, buffer, paramVals, collapse = ""))
cat("\n")
}
headings = paste0(sprintf(char.format, c(" ")), collapse = "")
if (self$options$calculateWAIC & !is.null(self$informationCriteria$WAIC)){
preamble = paste0(" ", "WAIC", collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(headings)), collapse = "")
cat(paste0(preamble, buffer, headings))
cat("\n")
preamble = paste0(" ", self$logLikelihoods$type, "WAIC (Deviance metric: -2*WAIC)", collapse = "")
paramVals = paste0(sprintf(num.format, -2*self$informationCriteria$WAIC$WAIC), collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(headings)), collapse = "")
cat(paste0(preamble, buffer, paramVals, collapse = ""))
cat("\n")
preamble = paste0(" ", self$logLikelihoods$type, "WAIC Effective Number of Parameters", collapse = "")
paramVals = paste0(sprintf(num.format, self$informationCriteria$WAIC$p_WAIC), collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(paramVals)), collapse = "")
cat(paste0(preamble, buffer, paramVals, collapse = ""))
cat("\n")
}
cat(paste0(rep("-", 80), collapse = ""))
}
if (self$options$posteriorPredictiveChecks$estimatePPMC & !is.null(self$PPMC)){
cat("\nPosterior Predictive Model Check Summary: \n")
for (ppmc in 1:length(self$PPMC)){
if (!names(self$PPMC)[[ppmc]] %in% c("univariate", "bivariate")) {
cat(self$PPMC[[ppmc]]$summaryMessage)
cat("\n")
}
}
for (ppmc in 1:length(self$PPMC)){
if (names(self$PPMC)[[ppmc]] %in% c("univariate", "bivariate")) {
cat(self$PPMC[[ppmc]]$summaryMessage)
cat("\n")
}
}
cat(paste0(rep("-", 80), collapse = ""))
}
cat("\nParameter Estimates:")
if (self$options$nChains > 1) {
headings = paste0(sprintf(char.format, c(
"Mean", "SD", "LowHPDI", "UpHDPI", "PSRF"
)), collapse = "")
} else if (self$options$nChains == 1) {
headings = paste0(sprintf(char.format, c(
"Mean", "SD", "LowHPDI", "UpHDPI", "HDPV"
)), collapse = "")
}
cat("\n")
for (variable in names(self$variables)) {
cat(paste0(rep("-", 80), collapse = ""))
cat("\n")
preamble = paste0(variable, ":", collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(headings)), collapse = "")
cat(paste0(preamble, buffer, headings))
cat("\n")
for (param in self$variables[[variable]]$paramNames) {
csRow = which(rownames(self$parameterSummary) == param)
preamble = paste0(" ", param, collapse = "")
buffer = paste0(rep(" ", 80 - nchar(preamble) - nchar(headings)), collapse = "")
if (self$options$nChains > 1) {
paramVals = paste0(sprintf(num.format, self$parameterSummary[csRow, c("Mean",
"SD",
"lowerHDPI0.95",
"upperHDPI950.95",
"PSRF")]),
collapse = "")
} else if (self$options$nChains == 1) {
paramVals = paste0(sprintf(num.format, self$parameterSummary[csRow, c("Mean",
"SD",
"lowerHDPI0.95",
"upperHDPI950.95",
"Heidel.Diag p-value")]),
collapse = "")
}
cat(paste0(preamble, buffer, paramVals, collapse = ""))
cat("\n")
}
}
}
),
private = list(
latentEstimatesCalculated = FALSE,
likelihoodsCalculated = FALSE,
getCategoricalLatentEstimates = function(obs, profileMatrix){
lvcols = which(colnames(self$chain[[1]]) %in% paste0(obs, ".",self$specs$latentVariables))
if (length(lvcols) == 0) return(NULL)
temp = lapply(X = self$chain, FUN = function(x) return(x[,lvcols]))
latentData = do.call("rbind", temp)
marginalMeans = apply(X = latentData, MARGIN = 2, FUN = mean)
latentData = cbind(latentData, apply(X = latentData, MARGIN = 1, FUN = bin2dec, nattributes = ncol(latentData),
basevector = rep(2, ncol(latentData)))+1)
colnames(latentData)[ncol(latentData)] = "clvProfile"
nProfiles = 2^self$specs$nCategoricalLatents
eapProfile = table(factor(latentData[,"clvProfile"], levels = 1:nProfiles))/nrow(latentData)
result = cbind(t(marginalMeans), t(eapProfile))
colnames(result) = c(paste0(self$specs$latentVariables, ".EAP.marginal"),
paste0(rownames(profileMatrix), ".EAP.joint"))
rownames(result) = obs
result = cbind(result, t(round(marginalMeans)), t(as.numeric(which.max(eapProfile))))
colnames(result)[(ncol(result)-length(marginalMeans)):ncol(result)] =
c(paste0(self$specs$latentVariables, ".MAP.marginal"),"profileNumber.MAP")
result = cbind(result, t(profileMatrix[which.max(eapProfile),]))
colnames(result)[(ncol(result)-length(marginalMeans)+1):ncol(result)] =
paste0(self$specs$latentVariables, ".MAP.joint")
result = as.data.frame(result)
result = cbind(t(obs), result)
colnames(result)[1] = "observation"
return(result)
}
),
)
|
"BinMatInput_reps"
|
NULL
stat_overlay_normal_density <- function(mapping = NULL, data = NULL, geom = "line",
position = "identity", na.rm = FALSE, show.legend = NA,
inherit.aes = TRUE, ...) {
if(is.null(mapping)){
mapping <- ggplot2::aes(y = NULL)
}else{
mapping["y"] <- list(NULL)
}
layer(
stat = StatOverlayNormalDensity, data = data, mapping = mapping, geom = geom,
position = position, show.legend = show.legend, inherit.aes = inherit.aes,
params = list(na.rm = na.rm, ...)
)
}
StatOverlayNormalDensity<- ggproto("StatOverlayNormalDensity", Stat,
required_aes = c("x"),
compute_group = function(data, scales) {
x <- data$x
.mean <- mean(x, na.rm = TRUE)
.sd <- stats::sd(x, na.rm = TRUE)
probability.points <- stats::ppoints(length(x[!(is.na(x))]))
res.density <- stats::density(stats::qnorm(probability.points, .mean, .sd))
res.density <- data.frame(x = res.density$x, y = res.density$y)
res.density
}
)
|
pl.hsdgg <- function(x,l = 1, bin = 30){
x <- x
varname <- names(x)
n <- length(varname)
..density.. <- NULL
plots <- list()
for(i in 1:n){
plots[[i]] <- ggplot(x, aes_string(x = varname[i])) +
geom_histogram(aes(y = ..density..), binwidth = bin, colour = "black") +
geom_density(alpha = .2) +
ggtitle(paste("Fig.",as.character(i+l-1), "Histogram of", varname[i])) +
theme(plot.title = element_text(hjust = 0.5)) +
labs(y = "Frequency", x = varname[i])
}
marrangeGrob(plots, nrow = 2, ncol = 2)
}
|
stepper <- function(rschedule) {
function(n) {
n <- vec_cast(n, integer(), x_arg = "n")
new_stepper(n = n, rschedule = rschedule)
}
}
`%s+%` <- function(x, y) {
vec_arith("+", x, y)
}
`%s-%` <- function(x, y) {
vec_arith("-", x, y)
}
workdays <- function(n, since = "1900-01-01", until = "2100-01-01") {
rschedule <- weekly(since = since, until = until)
rschedule <- recur_on_weekends(rschedule)
workdays_stepper <- stepper(rschedule)
workdays_stepper(n)
}
new_stepper <- function(n = integer(), rschedule = daily()) {
if (!is_integer(n)) {
abort("`n` must be an integer.")
}
validate_rschedule(rschedule, x_arg = "rschedule")
new_vctr(
.data = n,
rschedule = rschedule,
class = "almanac_stepper",
inherit_base_type = FALSE
)
}
vec_ptype_abbr.almanac_stepper <- function(x, ...) {
"stepper"
}
vec_ptype_full.almanac_stepper <- function(x, ...) {
"stepper"
}
NULL
vec_arith.almanac_stepper <- function(op, x, y, ...) {
UseMethod("vec_arith.almanac_stepper", y)
}
vec_arith.almanac_stepper.default <- function(op, x, y, ...) {
stop_incompatible_op(op, x, y)
}
vec_arith.almanac_stepper.MISSING <- function(op, x, y, ...) {
switch(
op,
`+` = plus_stepper_missing(x),
`-` = minus_stepper_missing(x),
stop_incompatible_op(op, x, y)
)
}
plus_stepper_missing <- function(x) {
x
}
minus_stepper_missing <- function(x) {
rschedule <- stepper_rschedule(x)
x <- unclass(x)
x <- -x
new_stepper(x, rschedule)
}
vec_arith.almanac_stepper.Date <- function(op, x, y, ...) {
switch(
op,
`+` = plus_stepper_date(x, y),
stop_incompatible_op(op, x, y)
)
}
plus_stepper_date <- function(x, y) {
rschedule <- stepper_rschedule(x)
n <- unclass(x)
alma_step(y, n, rschedule)
}
vec_arith.Date.almanac_stepper <- function(op, x, y, ...) {
switch(
op,
`+` = plus_date_stepper(x, y),
`-` = minus_date_stepper(x, y),
stop_incompatible_op(op, x, y)
)
}
plus_date_stepper <- function(x, y) {
rschedule <- stepper_rschedule(y)
n <- unclass(y)
alma_step(x, n, rschedule)
}
minus_date_stepper <- function(x, y) {
rschedule <- stepper_rschedule(y)
n <- unclass(y)
n <- -n
alma_step(x, n, rschedule)
}
vec_ptype2.almanac_stepper.almanac_stepper <- function(x, y, ..., x_arg = "", y_arg = "") {
if (!stepper_identical_rschedules(x, y)) {
details <- "Steppers must have identical rschedules to be coercible."
stop_incompatible_type(x, y, x_arg = x_arg, y_arg = y_arg, details = details)
}
new_stepper(rschedule = stepper_rschedule(x))
}
vec_cast.almanac_stepper.almanac_stepper <- function(x, to, ..., x_arg = "", to_arg = "") {
if (!stepper_identical_rschedules(x, to)) {
details <- "Steppers must have identical rschedules to be coercible."
stop_incompatible_cast(x, to, x_arg = x_arg, to_arg = to_arg, details = details)
}
x
}
stepper_rschedule <- function(x) {
attr(x, "rschedule", exact = TRUE)
}
stepper_identical_rschedules <- function(x, y) {
identical(stepper_rschedule(x), stepper_rschedule(y))
}
|
Initialization <- function(x, y, svr.eps= 1,kernel.function = radial.kernel, param.kernel = 1){
eps <- svr.eps
w0 <- optimize(loss, quantile(y, c(0,1)), y = y, eps = eps)$minimum
Center <- (which(abs(y - w0) < eps))
Right <- (which((y - w0) > eps))
Left <- (which((y - w0) < -eps))
Left.cp <- Left
Right.cp <- Right
Elbow.R <- Elbow.L <- NULL
K <- kernel.function(x, x, param.kernel = param.kernel)
gx <- apply(K[,Right, drop = F], 1, sum) - apply(K[,Left, drop = F], 1, sum)
lambda1 <- (outer(gx[Left], gx[Right], "-")) / (outer(y[Left], y[Right], "-") + 2 * eps)
lambda2 <- (outer(gx[Left], gx[Center], "-")) / (outer(y[Left], y[Center], "-"))
lambda3 <- (outer(gx[Right], gx[Center], "-")) / (outer(y[Right], y[Center], "-"))
lambda4 <- (outer(gx[Center], gx[Center], "-")) / (outer(y[Center], y[Center], "-") + 2 * eps)
max.lambda1 <- lambda1[which.max(lambda1)]
max.lambda2 <- lambda2[which.max(lambda2)]
max.lambda3 <- lambda3[which.max(lambda3)]
max.lambda4 <- lambda4[which.max(lambda4)]
max.lambda <- c(max.lambda1,
max.lambda2,
max.lambda3,
max.lambda4)
sel.case <- which.max(max.lambda)
lambda0 <- max.lambda[sel.case]
if (sel.case == 1) {
temp <- lambda1
} else if (sel.case == 2) {
temp <- lambda2
} else if (sel.case == 3) {
temp <- lambda3
} else if (sel.case == 4) {
temp <- lambda4
} else step()
i1 <- row(matrix(0, nrow(temp), ncol(temp)))[which.max(temp)]
i2 <- col(matrix(0, nrow(temp), ncol(temp)))[which.max(temp)]
if (sel.case == 1) {
Elbow.L <- Left[i1]
Elbow.R <- Right[i2]
Left <- setdiff(Left, Elbow.L)
Right <- setdiff(Right, Elbow.R)
} else if (sel.case == 2) {
Elbow.L <- Left[i1]
Elbow.L <- c(Elbow.L, Center[i2])
Center <- setdiff(Center, Center[i2])
Left <- setdiff(Left, Left[i1])
} else if (sel.case == 3) {
Elbow.R <- Right[i1]
Elbow.R <- c(Elbow.R, Center[i2])
Center <- setdiff(Center, Center[i2])
Right <- setdiff(Right, Right[i1])
} else if (sel.case == 4) {
Elbow.L <- Center[i1]
Elbow.R <- Center[i2]
Center <- setdiff(Center, c(Elbow.L, Elbow.R))
} else step()
if(length(Elbow.R)==0){
Elbow.R <- integer(0)
}else if(length(Elbow.L) == 0){
Elbow.L <- integer(0)
}
theta0 <- c(y[Elbow.L] - gx[Elbow.L]/lambda0 + eps, y[Elbow.R] - gx[Elbow.R]/lambda0 - eps)
theta0 <- mean(theta0)
theta <- rep(0, length(y))
if(sel.case==1) {
theta[c(Right,Elbow.R)] <- 1
theta[c(Left, Elbow.L)] <- -1
}else if(sel.case==2) {
theta[c(Right)] <- 1
theta[c(Left, Left.cp[i1])] <- -1
}else if(sel.case==3) {
theta[c(Right, Right.cp[i1])] <- 1
theta[c(Left)] <- -1
}else if(sel.case==4) {
theta[c(Right)] <- 1
theta[c(Left)] <- -1
}else step()
list(Elbow.L = Elbow.L, Elbow.R=Elbow.R, Center=Center,
Right=Right, Left=Left, lambda0=lambda0,
case.of.lambda = paste("case :",sel.case),
theta0=theta0, theta = theta)
}
|
load(file="sleep_imp.Rdata")
M <- cor(sleep_imp3)
library(corrplot)
col4 <- colorRampPalette(c("
"
corrplot(M, method = "color", col = col4(20), cl.length = 21,
order = "AOE", addCoef.col = "green")
library(car)
vif(lm(Sleep ~ BodyWgt + BrainWgt + Span + Gest + Pred + Exp + Danger,
data = sleep_imp3))
cars <- mtcars[, 1:7]
pairs(cars, panel = panel.smooth)
panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...) {
usr <- par("usr"); on.exit(par(usr))
par(usr = c(0, 1, 0, 1))
r <- abs(cor(x, y, method = "spearman"))
txt <- format(c(r, 0.123456789), digits=digits)[1]
txt <- paste(prefix, txt, sep = "")
if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
text(0.5, 0.5, txt, cex = cex.cor * r)
}
pairs(cars, , panel = panel.smooth, lower.panel = panel.cor)
library(lattice)
splom(cars)
library(GGally)
ggpairs(cars,
upper = list(continuous = "density", combo = "box"),
lower = list(continuous = "points", combo = "dot"))
library(mgcv)
summary(gam(mpg ~ s(hp) + s(qsec), data = cars))
Sparrows <- read.table(file = "SparrowsElphick.txt", header = TRUE)
I1 <- Sparrows$SpeciesCode == 1 & Sparrows$Sex != "0" & Sparrows$wingcrd < 65
Wing1 <- Sparrows$wingcrd[I1]
Wei1 <- Sparrows$wt[I1]
Mon1 <- factor(Sparrows$Month[I1])
Sex1<- factor(Sparrows$Sex[I1])
fMonth1 <- factor(Mon1,levels = c(5, 6, 7, 8, 9),
labels=c("May", "Jun", "Jul", "Aug", "Sep"))
fSex1 <- factor(Sex1, levels = c(4, 5),
labels=c("Male","Female"))
coplot(Wei1 ~ Wing1 | fMonth1 * fSex1, ylab = "Weight (g)",
xlab = "Wing length (mm)",
panel = function(x, y, ...) {
tmp <- lm(y ~ x, na.action = na.omit)
abline(tmp)
points(x, y) })
df <-data.frame(weight = Wei1, length = Wing1, sex = fSex1, month = fMonth1)
df1 <- df[df$month != "May" & df$month != "Sep", ]
M1 <- lm(weight ~ length*month*sex, data = df1)
DT <- anova(M1)
library(stargazer)
stargazer(M1, type = "html", out = "M1.doc")
stargazer(DT, type = "html", out = "DT.doc", summary = FALSE)
Waders <- read.table(file = "wader.txt", header = TRUE)
Time <- seq(1, 25)
par(mfrow = c(2, 2), mar = c(5, 4, 3, 2))
plot(Time, Waders$C.fuscicolis, type = "l",
xlab = "Время (2 недели)", ylab = "C. fuscicollis abundance")
acf(Waders$C.fuscicolis, main = "C. fuscicollis ACF")
plot(Time, Waders$L.dominicanus, type = "l",
xlab = "Время (2 недели)", ylab = "L. dominicanus abundance")
acf(Waders$L.dominicanus, main = "L. dominicanus ACF")
tomato <- data.frame(weight =
c(1.5, 1.9, 1.3, 1.5, 2.4, 1.5,
1.5, 1.2, 1.2, 2.1, 2.9, 1.6,
1.9, 1.6, 0.8, 1.15, 0.9, 1.6),
trt = rep(c("Water", "Nutrient", "Nutrient+24D"),
c(6, 6, 6)))
levels(tomato$trt)
tomato$trt <- relevel(tomato$trt, ref = "Water")
levels(tomato$trt)
M <- lm(weight ~ trt, data = tomato)
summary(M)
tapply(tomato$weight, tomato$trt, mean)
anova(M)
model.matrix(M)
M <- lm(count ~ spray, data = InsectSprays)
summary(M)
str(M)
M.res <- M$residuals
M.fit <- M$fitted.values
plot(M1.fit, M1.res, pch = 19, col = 4,
xlab = "Предсказанные значения", ylab = "Остатки")
cor.test(fitted(M2), InsectSprays$count)
shapiro.test(resid(M))
library(car)
set.seed(202)
dat = data.frame(Group = rep(c("A", "B", "C"), each = 1000),
Value = c(
rnorm(n=1000, mean=5, sd=1.2),
rnorm(n=1000, mean=7, sd=1.5),
rnorm(n=1000, mean=15, sd=2)
))
library(ggplot2)
p1 = ggplot(dat, aes(x = Value, fill = Group)) +
geom_density(alpha = 0.6) +
xlab("Значение") + ylab("Плотность вероятности")
p2 = ggplot(dat, aes(x = Value)) +
geom_density(alpha = 0.6, fill = "blue") +
xlab("Значение") + ylab("Плотность вероятности")
multiplot <- function(..., plotlist=NULL, cols) {
require(grid)
plots <- c(list(...), plotlist)
numPlots = length(plots)
plotCols = cols
plotRows = ceiling(numPlots/plotCols)
grid.newpage()
pushViewport(viewport(layout = grid.layout(plotRows, plotCols)))
vplayout <- function(x, y)
viewport(layout.pos.row = x, layout.pos.col = y)
for (i in 1:numPlots) {
curRow = ceiling(i/plotCols)
curCol = (i-1) %% plotCols + 1
print(plots[[i]], vp = vplayout(curRow, curCol ))
}
}
multiplot(p1, p2, cols = 2)
ggplot(InsectSprays, aes(x = count)) + geom_histogram() +
facet_wrap(~spray) +
xlab("Число насекомых") + ylab("Частота")
ggplot(InsectSprays, aes(sample = count)) + stat_qq() +
facet_wrap(~spray, scales = "free_y") +
xlab("Ожидаемые квантили") + ylab("Наблюдаемые значения")
M <- lm(count ~ spray, data = InsectSprays)
InsectSprays$resids = resid(M)
p3 = ggplot(InsectSprays, aes(x = resids)) +
geom_histogram(aes(y=..density..)) +
geom_density(color = "red") +
xlab("Остатки") + ylab("Плотность вероятности")
p4 = ggplot(InsectSprays, aes(sample = resids)) + stat_qq() +
xlab("Ожидаемые квантили") + ylab("Наблюдаемые значения")
multiplot(p3, p4, cols = 2)
set.seed(202)
ggplot(InsectSprays, aes(x = spray, y = count)) + geom_boxplot() +
geom_jitter(alpha = 0.5) +
xlab("Инсектицид") + ylab("Число выживших насекомых")
InsectSprays$fit = fitted(M)
ggplot(InsectSprays, aes(x = fit, y = resids)) + geom_point() +
xlab("Предсказанные значения") + ylab("Остатки")
leveneTest(InsectSprays$count, InsectSprays$spray)
M.log <- lm(log(count + 1) ~ spray, data = InsectSprays)
shapiro.test(resid(M.log))
leveneTest(log(InsectSprays$count + 1), InsectSprays$spray)
kruskal.test(count ~ spray, data = InsectSprays)
library(HSAUR2)
data(weightgain)
M2 <- lm(weightgain ~ type*source, data = weightgain)
summary(M2)
anova(M2)
M3 <- lm(weightgain ~ source*type, data = weightgain)
anova(M3)
weightgain2 <- weightgain[-c(1:6, 34:40), ]
M4 <- lm(weightgain ~ type*source, data = weightgain2)
summary(M4)
M5 <- lm(weightgain ~ source*type, data = weightgain2)
summary(M5)
anova(M4)
anova(M5)
plot.design(weightgain2)
boxplot(count ~ spray, data = InsectSprays, col = "coral",
xlab = "Инсектицид",
ylab = "Число выживших насекомых")
contrasts(InsectSprays$spray) <- contr.sum(n = 6)
contrasts(InsectSprays$spray)
M3 <- lm(count ~ spray, data = InsectSprays)
summary(M3)
with(InsectSprays, mean(tapply(count, spray, mean)))
contrasts(InsectSprays$spray) <- contr.helmert(n = 6)
contrasts(InsectSprays$spray)
mat <- contrasts(InsectSprays$spray)
sum(mat[, 1]*mat[, 2])
M4 <- lm(count ~ spray, data = InsectSprays)
summary(M4)
con1 <- c(1, 1, 1, -1, -1, -1)
con2 <- c(1, 1, -1, -1, -1, 1)
con.matrix <- cbind(con1, con2)
con.matrix
contrasts(InsectSprays$spray) <- con.matrix
summary(M5, split = list(spray = list("Первые три против остальных" = 1,
"ABF против CDE" = 2)))
p.adjust(c(0.01, 0.02, 0.005), method = "bonferroni")
alpha <- 0.05
p.adjust(c(0.01, 0.02, 0.005), method = "bonferroni") < alpha
p.adjust(c(0.01, 0.02, 0.005), method = "holm")
alpha <- 0.05
p.adjust(c(0.01, 0.02, 0.005), method = "holm") < alpha
pvals <- c(0.0001, 0.0004, 0.0019, 0.0095, 0.0201,
0.0278, 0.0298, 0.0344, 0.0459, 0.3240,
0.4262, 0.5719, 0.6528, 0.7590, 1.000)
p.adjust(pvals, method = "BH")
p.adjust(pvals, "BY")
waterbodies <- data.frame(Water = rep(c("Grayson", "Beaver",
"Angler", "Appletree",
"Rock"), each = 6),
Sr = c(28.2, 33.2, 36.4, 34.6, 29.1, 31.0,
39.6, 40.8, 37.9, 37.1, 43.6, 42.4,
46.3, 42.1, 43.5, 48.8, 43.7, 40.1,
41.0, 44.1, 46.4, 40.2, 38.6, 36.3,
56.3, 54.1, 59.4, 62.7, 60.0, 57.3) )
M <- aov(Sr ~ Water, data = waterbodies)
summary(M)
TukeyHSD(M)
par(mar = c(4.5, 8, 4.5, 4.5))
plot(TukeyHSD(M), las = 1)
M <- lm(Sr ~ Water, data = waterbodies)
summary(M)
coef(M)
vcov(M)
library(multcomp)
glht(M, linfct = mcp(Water = "Tukey"))
glht(M, linfct = mcp(Water = c(
"Rock - Angler = 0",
"Grayson - Appletree = 0",
"Grayson - Beaver = 0"))
)
contr <- rbind("Rock - Angler" = c(-1, 0, 0, 0, 1),
"Grayson - Appletree" = c(0, -1, 0, 1, 0),
"Grayson - Beaver" = c(0, 0, -1, 1, 0) )
contr
glht(M, linfct = mcp(Water = contr))
summary(glht(M, linfct = mcp(Water = "Tukey")))
mult <- glht(M, linfct = mcp(Water = contr))
confint(mult, level = 0.95)
plot(confint(mult, level = 0.95))
|
visualisation_recipe.easycor_test <- function(x,
show_data = "point",
show_text = "subtitle",
smooth = NULL,
point = NULL,
text = NULL,
labs = NULL,
...) {
data <- attributes(x)$data
subtitle <- NULL
title <- NULL
if (!is.null(show_text) && show_text == "subtitle") subtitle <- cor_text(x, ...)
if (!is.null(show_text) && show_text == "title") title <- cor_text(x, ...)
layers <- .see_scatter(data,
cor_results = x,
x = x$Parameter1,
y = x$Parameter2,
show_data = show_data,
show_text = show_text,
smooth = smooth,
point = point,
text = text,
labs = labs,
title = title,
subtitle = subtitle,
...
)
if (!is.null(show_text) && show_text != FALSE && show_text %in% c("text", "label")) {
x$label <- cor_text(x, ...)
x$label_x <- max(data[[x$Parameter1]], na.rm = TRUE)
x$label_y <- max(data[[x$Parameter2]], na.rm = TRUE) + 0.05 * diff(range(data[[x$Parameter2]], na.rm = TRUE))
l <- paste0("l", length(layers) + 1)
layers[[l]] <- list(
geom = show_text,
data = x,
hjust = 1,
aes = list(
label = "label",
x = "label_x",
y = "label_y"
)
)
if (!is.null(text)) layers[[l]] <- utils::modifyList(layers[[l]], text)
}
class(layers) <- c("visualisation_recipe", "see_visualisation_recipe", class(layers))
attr(layers, "data") <- data
layers
}
.see_scatter <- function(data,
cor_results,
x,
y,
show_data = "point",
show_text = "text",
smooth = NULL,
point = NULL,
text = NULL,
labs = NULL,
title = NULL,
subtitle = NULL,
type = show_data,
...) {
layers <- list()
if (!missing(type)) {
show_data <- type
}
l <- 1
layers[[paste0("l", l)]] <- list(
geom = "smooth",
data = data,
method = "lm",
aes = list(
x = x,
y = y
)
)
if (!is.null(smooth)) {
layers[[paste0("l", l)]] <- utils::modifyList(layers[[paste0("l", l)]], smooth)
}
l <- l + 1
layers[[paste0("l", l)]] <- list(
geom = show_data,
data = data,
aes = list(
x = x,
y = y
)
)
if (!is.null(point)) {
layers[[paste0("l", l)]] <- utils::modifyList(layers[[paste0("l", l)]], point)
}
l <- l + 1
layers[[paste0("l", l)]] <- list(geom = "labs", subtitle = subtitle, title = title)
if (!is.null(labs)) {
layers[[paste0("l", l)]] <- utils::modifyList(layers[[paste0("l", l)]], labs)
}
layers
}
|
.dot_internals <- c(".subset", ".subset2", ".getRequiredPackages",
".getRequiredPackages2", ".isMethodsDispatchOn",
".row_names_info", ".set_row_names", ".ArgsEnv",
".genericArgsEnv", ".TAOCP1997init", ".gt",
".gtn", ".primTrace", ".primUntrace",
".POSIXct", ".POSIXlt", ".cache_class",
".Firstlib_as_onload", ".methodsNamespace",
".popath", ".mapply", ".detach", ".maskedMsg")
apropos <- function (what, where = FALSE, ignore.case = TRUE, mode = "any")
{
stopifnot(is.character(what))
x <- character(0L)
check.mode <- mode != "any"
for (i in seq_along(sp <- search())) {
li <-
if(ignore.case)
grep(what, ls(pos = i, all.names = TRUE),
ignore.case = TRUE, value = TRUE)
else ls(pos = i, pattern = what, all.names = TRUE)
li <- grep("^[.](__|C_|F_)", li, invert = TRUE, value = TRUE)
if(sp[i] == "package:base") li <- li[! li %in% .dot_internals]
if(length(li)) {
if(check.mode)
li <- li[sapply(li, exists, where = i,
mode = mode, inherits = FALSE)]
x <- c(x, if(where) structure(li, names = rep.int(i, length(li))) else li)
}
}
sort(x)
}
find <- function(what, mode = "any", numeric = FALSE, simple.words=TRUE)
{
stopifnot(is.character(what))
if(length(what) > 1L) {
warning("elements of 'what' after the first will be ignored")
what <- what[1L]
}
len.s <- length(sp <- search())
ind <- logical(len.s)
check.mode <- mode != "any"
for (i in 1L:len.s) {
if(simple.words) {
found <- what %in% ls(pos = i, all.names = TRUE)
if(found && check.mode)
found <- exists(what, where = i, mode = mode, inherits=FALSE)
ind[i] <- found
} else {
li <- ls(pos = i, pattern = what, all.names = TRUE)
li <- grep("^[.](__|C_|F_)", li, invert = TRUE, value = TRUE)
if(sp[i] == "package:base") li <- li[! li %in% .dot_internals]
ll <- length(li)
if(ll > 0 && check.mode) {
mode.ok <- sapply(li, exists, where = i, mode = mode,
inherits = FALSE)
ll <- sum(mode.ok)
if(ll >= 2)
warning(sprintf(ngettext(ll,
"%d occurrence in %s",
"%d occurrences in %s"), ll, sp[i]),
domain = NA)
}
ind[i] <- ll > 0L
}
}
if(numeric) structure(which(ind), names=sp[ind]) else sp[ind]
}
|
docurl = "https://docs.google.com/spreadsheets/d/"
sheeturl = paste0("1QogGSuEab5SZyZIw1Q8h-0yrBNs1Z_eEBJG7oRESW5k","/edit
sheetname = "560796239"
fullurl = paste0(docurl, sheeturl, sheetname)
fullurl
df = as.data.frame(gsheet::gsheet2tbl(fullurl, skip=2))
summary(df)
str(df)
colcs1 = c('numeric','character', NA,NA,'character', 'character', 'character', 'character' ,'numeric', 'numeric', 'character','factor', 'character', 'numeric','numeric' ,'numeric', 'factor')
length(colcs1)
auctiondata = read.csv('./Data/AuctionsData - set1.csv', skip=2)
dim(auctiondata)
str(auctiondata)
names(ag2b)
gb1 = ggplot(data = ag2b, aes(x = "", y = saleprice, fill = auchouse ))
gb2 = geom_bar(stat = "identity", position = position_fill())
gb3 = geom_text(aes(label = awcat), position = position_fill(vjust = 0.5))
gb4 = coord_polar(theta = "y")
gb5 = facet_wrap(~ auchouse)
gb6 = theme(axis.title.x = element_blank(), axis.title.y = element_blank())
gb7 = theme(legend.position='bottom')
gb8 = guides(fill=guide_legend(nrow=2,byrow=TRUE))
gb1+gb2+gb3 + gb4 + gb5 + gb6 + gb7 + gb8
+ gb4 + ga5
|
cat("\014")
rm(list = ls())
setwd("~/git/of_dollars_and_data")
source(file.path(paste0(getwd(),"/header.R")))
library(dplyr)
library(ggplot2)
library(tidyr)
library(scales)
library(grid)
library(gridExtra)
library(gtable)
library(RColorBrewer)
library(stringr)
library(ggrepel)
library(BenfordTests)
my_palette <- c("
nyse_fundamentals <- readRDS(paste0(localdir, "0018_nyse_fundamentals.Rds"))
vars_to_test <- c("Accounts.Payable", "Accounts.Receivable", "Capital.Expenditures",
"Cash.and.Cash.Equivalents", "Depreciation", "Earnings.Before.Interest.and.Tax",
"Goodwill", "Gross.Profit", "Income.Tax",
"Net.Income", "Operating.Income", "Total.Assets",
"Total.Equity", "Total.Revenue")
vars_shortname <- c("accounts_payable", "accounts_receivable", "capex", "cash", "depreciation", "ebit",
"goodwill", "gross_profit", "income_tax",
"net_income", "operating_income", "tot_assets", "tot_equity", "tot_revenue")
nyse_fundamentals[, "Capital.Expenditures"] <- abs(nyse_fundamentals[, "Capital.Expenditures"])
nyse_fundamentals <- as.data.frame(apply(nyse_fundamentals[, vars_to_test], 2, function(x) {ifelse(x < 0, 0, x)}))
vars_df <- as.data.frame(cbind(vars_to_test, vars_shortname))
benford_digits <- data.frame(leading_digit = as.character(seq(1,9)), stringsAsFactors = FALSE)
create_bedford_counts <- function(df, name_df){
var_string <- paste0(name_df[,1])
temp <- select_(df, var_string)
temp[, var_string] <- as.character(temp[, var_string])
temp["leading_digit"] <- gsub("(\\d).*", "\\1", temp[, var_string])
temp <- temp %>%
inner_join(benford_digits)
temp <- temp %>%
group_by(leading_digit) %>%
summarise(count = n()) %>%
mutate(benford_count = nrow(temp) * log10(1 + 1/(as.numeric(leading_digit))),
n_obs = nrow(temp)) %>%
select(leading_digit, n_obs, count, benford_count)
temp["shortname"] <- name_df[,2]
return(temp)
}
for (i in 1:nrow(vars_df)){
string <- as.character(vars_df[i,1])
print(string)
if (i == 1){
benford_stats <- create_bedford_counts(nyse_fundamentals, vars_df[i, ])
benford_stats[1:9,"p_value"] <- ks.benftest(nyse_fundamentals[, string])$p.value
} else {
new_stats <- create_bedford_counts(nyse_fundamentals, vars_df[i, ])
new_stats[1:9,"p_value"] <- ks.benftest(nyse_fundamentals[, string])$p.value
benford_stats <- bind_rows(benford_stats, new_stats)
}
sname <- vars_df[i,2]
to_plot <- filter(benford_stats, shortname == sname) %>%
mutate(pct = count/n_obs,
benford_pct = benford_count/n_obs)
file_path = paste0(exportdir, "0018_nyse_benford_plots/benford-", sname,".jpeg")
p_value <- round(min(to_plot$p_value)*100, 2)
if (p_value == 0){
p_value <- "less than 0.01"
}
plot <- ggplot(data = to_plot, aes(x = leading_digit, y = pct)) +
geom_bar(stat = "identity", col = "black", fill = "black") +
geom_point(data = to_plot, aes(x = leading_digit, y = benford_pct), col = "red", size = 5) +
geom_text_repel(data = filter(to_plot, leading_digit == "1"),
aes(x = leading_digit,
y = (benford_pct*0.75)),
label = "Actual Percentage",
col = "black",
family = "my_font",
nudge_y = 0.05,
nudge_x = 2.2) +
geom_text_repel(data = filter(to_plot, leading_digit == "5"),
aes(x = leading_digit,
y = benford_pct),
label = "Expected Percentage\nUnder Benford's Law",
col = "red",
family = "my_font",
nudge_y = 0.1,
nudge_x = 1) +
scale_color_manual(values = my_palette, guide = FALSE) +
scale_y_continuous(label = percent) +
of_dollars_and_data_theme +
labs(x = "Leading Digit" , y = "Percentage of Total") +
ggtitle(paste0("Actual Percentages vs. Benford's Law\n", string))
source_string <- "Source: NYSE data from Kaggle, 2010 - 2016 (OfDollarsAndData.com)"
note_string <- paste0("Note: The probability of seeing this result is ", p_value, "%, when running a KS test.")
my_gtable <- ggplot_gtable(ggplot_build(plot))
source_grob <- textGrob(source_string, x = (unit(0.5, "strwidth", source_string) + unit(0.2, "inches")), y = unit(0.1, "inches"),
gp =gpar(fontfamily = "my_font", fontsize = 8))
note_grob <- textGrob(note_string, x = (unit(0.5, "strwidth", note_string) + unit(0.2, "inches")), y = unit(0.15, "inches"),
gp =gpar(fontfamily = "my_font", fontsize = 8))
my_gtable <- arrangeGrob(my_gtable, bottom = source_grob)
my_gtable <- arrangeGrob(my_gtable, bottom = note_grob)
ggsave(file_path, my_gtable, width = 15, height = 12, units = "cm")
}
|
team_stats_per_game <- function(df1){
for(i in 3:ncol(df1)){
if(i==5 || i==8 || i==11 || i==14){
df1[i] <- round(df1[i],3)
}
else{
df1[i] <- round(df1[i] / df1[1],2)
}
}
names(df1) <- c("G","MP","FG","FGA","FG%","3P","3PA","3P%","2P","2PA","2P%","FT","FTA","FT%",
"ORB","DRB","TRB","AST","STL","BLK","TOV","PF","PTS","+/-")
return(df1)
}
|
library(checkargs)
context("isStrictlyNegativeNumberOrInfScalar")
test_that("isStrictlyNegativeNumberOrInfScalar works for all arguments", {
expect_identical(isStrictlyNegativeNumberOrInfScalar(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_error(isStrictlyNegativeNumberOrInfScalar(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(0, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isStrictlyNegativeNumberOrInfScalar(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isStrictlyNegativeNumberOrInfScalar(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isStrictlyNegativeNumberOrInfScalar(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(1, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isStrictlyNegativeNumberOrInfScalar(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isStrictlyNegativeNumberOrInfScalar(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar("", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar("X", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isStrictlyNegativeNumberOrInfScalar(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
})
|
BayesMDei4cov <- function(formula, covariate, total, data, lambda1 = 2,
lambda2 = 4, covariateprior = NULL,
tune.dr = NULL, tune.beta = NULL, tune.gamma
= NULL, tune.delta = NULL,
start.dr = NULL, start.betas = NULL,
start.gamma = NULL, start.delta = NULL,
sample = 1000,
thin = 1, burnin = 1000, verbose = 0, ret.beta =
'r', ret.mcmc = TRUE, usrfun = NULL, ...){
if(thin < 1){stop('thin must be positive integer')}
if(sample < 1){stop('thin must be positive integer')}
if(burnin < 0){stop('burnin must be non-negative integer')}
DD <- model.frame(formula, data)
countParty <- countGroup <- propParty <- propGroup <- FALSE
checkGroups <- round(apply(DD[[2]], 1, sum), 3)
checkParties <- round(apply(DD[[1]], 1, sum), 3)
if(all(DD[[1]] %% 1 == 0) & all(DD[[1]] >= 0)){countParty <- TRUE}
else if(all(0 <= DD[[1]] & DD[[1]] <= 1)){
if(all(checkParties == 1)){propParty <- TRUE}else{
stop("column marginals are proportions that do not
sum to 1 - please respecify data")}}
else stop("column marginals are neither counts nor proportions - please
respecify data")
if(all(DD[[2]] %% 1 == 0) & all(DD[[2]] >= 0)){countGroup <- TRUE}
else if(all(0 <= DD[[2]] & DD[[2]] <= 1)){
if(all(checkGroups == 1)){propGroup <- TRUE}else{
stop("row marginals are proportions that do not sum to 1 - please
respecify data")}}
else stop("row marginals are neither counts nor proportions - please
respecify data")
if((propParty | propGroup) & is.null(total)){
stop("one or both marginals are proportions - 'total' must be
provided")}
if(propParty & !is.null(total)){
DD[[1]] <- DD[[1]] * total
warning("column margnials are proportions - multiplying by unit size")}
if(propGroup & !is.null(total)){
DD[[2]] <- DD[[2]] * total
warning("row margnials are proportions - multiplying by unit size")}
checkGroups <- round(apply(DD[[2]], 1, sum), 1)
checkParties <- round(apply(DD[[1]], 1, sum), 1)
if(identical(checkParties, checkGroups) == FALSE){
stop("row and column totals unequal in some units - please
respecify data")}
Groups <- DD[[2]]
TT <- t(DD[[1]])
XX <- t(Groups/apply(Groups,1,sum))
group.names <- colnames(Groups)
party.names <- rownames(TT)
RR <- t(Groups)
CC <- model.frame(covariate, data)
ZZ <- as.matrix(CC)
NG <- nrow(XX)
NP <- nrow(TT)
Precincts <- nrow(DD)
if(is.null(start.dr)){
start.dr <- matrix(rgamma(NG, lambda1, lambda2), NG)}
if(min(start.dr) <= 0){stop("inadmissable starting values for dr")}
if(is.null(start.betas)){
start.betas <- array(NA, dim= c(NG, NP, Precincts))
for(i in 1:Precincts){
start.betas[,,i] <- rdirichlet(NG, rep(1,NP))}
}
if(identical(round(apply(start.betas, c(1,3), sum),10),matrix(1,NG,
Precincts))!=TRUE){stop("inadmissable
starting values
for beta")}
if(is.null(start.gamma)){
start.gamma <- cbind(matrix(rnorm(NG*(NP-1)), NG, NP-1),0)}
if(identical(start.gamma[,NP], rep(0,NG))!=TRUE){stop("final column
of 'start.gamma' must be zero")}
if(is.null(start.delta)){
start.delta <- cbind(matrix(rnorm(NG*(NP-1)), NG, NP-1),0)}
if(identical(start.delta[,NP], rep(0,NG))!=TRUE){stop("final column
of 'start.delta' must be zero")}
usrenv <- environment(fun = usrfun)
usrlen <- length(as.numeric(usrfun(list(start.dr, start.betas,
start.gamma, start.delta, TT,
RR))))
if(is.null(tune.dr)){
tune.dr <- rep(2,NG)}
if(is.null(tune.beta)){
tune.beta <- array(rep(.05, NG*(NP-1)*Precincts), c(NG, NP-1, Precincts))}
if(is.null(tune.gamma)){
tune.gamma <- matrix(.25, NG, NP-1)}
if(is.null(tune.delta)){
tune.delta <- matrix(.25, NG, NP-1)}
if(identical(length(tune.dr), NG)!=TRUE) {stop("'tune.dr'
has incorrect dimensions")}
if(identical(as.numeric(dim(tune.beta)), c(NG, NP-1, Precincts))!=TRUE)
{stop("'tune.beta'
has incorrect dimensions")}
if(identical(as.numeric(dim(tune.gamma)), c(NG, NP-1))!=TRUE)
{stop("'tune.gamma'
has incorrect dimensions")}
if(identical(as.numeric(dim(tune.delta)), c(NG, NP-1))!=TRUE)
{stop("'tune.delta'
has incorrect dimensions")}
if(is.null(covariateprior)){
covprior <- 0
delmean <- gammean <- rep(0, NG*(NP-1))
delsd <- gamsd <- rep(1, NG*(NP-1))
}else{
covprior <- 1
delmean <- covariateprior[[1]]
delsd <- covariateprior[[2]]
gammean <- covariateprior[[3]]
gamsd <- covariateprior[[4]]
if(identical(as.numeric(dim(delmean)), c(NG, NP-1))!=TRUE)
{stop("matrix of prior means for delta has incorrect dimensions")}
if(identical(as.numeric(dim(delsd)), c(NG, NP-1))!=TRUE)
{stop("matrix of prior sd for delta has incorrect dimensions")}
if(identical(as.numeric(dim(gammean)), c(NG, NP-1))!=TRUE)
{stop("matrix of prior means for gamma has incorrect dimensions")}
if(identical(as.numeric(dim(gamsd)), c(NG, NP-1))!=TRUE)
{stop("matrix of prior sd for gamma has incorrect dimensions")}
if(min(gamsd)<=0)
{stop("prior sd for gamma must be > 0")}
if(min(gamsd)<=0)
{stop("prior sd for delta must be > 0")}
}
beta.names <- paste(paste(paste(group.names,matrix(rep(party.names,
NG),NG,NP, byrow=T)
,sep="."),
matrix(rep(1:Precincts,NG*NP),NG*NP, Precincts,
byrow=TRUE),sep="."), ".txt.gz", sep="")
if(ret.beta == 's'){touch.betas(beta.names)
ret.beta <- 2}
if(ret.beta == 'd'){ret.beta <- 1}
if(ret.beta == 'r'){ret.beta <- 0}
if(is.numeric(ret.beta)==FALSE){stop("incorrect option for
ret.beta")}
output <- .Call("rbycei_fcn4",
as.numeric(start.dr),
as.numeric(start.betas),
as.numeric(start.gamma),
as.numeric(start.delta),
as.numeric(TT),
as.numeric(XX),
as.numeric(ZZ),
as.numeric(tune.dr),
as.numeric(tune.beta),
as.numeric(tune.gamma),
as.numeric(tune.delta),
as.integer(NG),
as.integer(NP),
as.integer(Precincts),
as.numeric(lambda1),
as.numeric(lambda2),
as.integer(covprior),
as.numeric(delmean),
as.numeric(delsd),
as.numeric(gammean),
as.numeric(gamsd),
as.integer(sample),
as.integer(thin),
as.integer(burnin),
as.integer(verbose),
as.integer(ret.beta),
as.numeric(RR),
usrfun,
usrenv,
as.integer(usrlen),
as.character(beta.names)
)
if(ret.beta==0){names(output) <- c("Dr", "Beta","Gamma","Delta",
"dr.acc","beta.acc", "gamma.acc",
"delta.acc","cell.count", "usrfun")}
else{names(output) <- c("Dr","Gamma","Delta",
"dr.acc","beta.acc", "gamma.acc",
"delta.acc","cell.count", "usrfun")}
if(ret.mcmc){
colnames(output$Dr) <- paste("dr", group.names, sep=".")
output$Dr <- coda::mcmc(output$Dr, thin=thin)
colnames(output$cell.count) <- paste("ccount",matrix(rep(group.names,
NP),NG,NP)
,matrix(rep(party.names, NG),NG,NP,
byrow=T) ,sep=".")
output$cell.count <- coda::mcmc(output$cell.count, thin=thin)
colnames(output$Gamma) <- paste("gamma",matrix(rep(group.names,
(NP-1)),NG,NP-1)
,matrix(rep(party.names[1:(NP-1)], NG),NG,NP-1,
byrow=T) ,sep=".")
output$Gamma <- coda::mcmc(output$Gamma, thin=thin)
colnames(output$Delta) <- paste("delta",matrix(rep(group.names,
(NP-1)),NG,NP-1)
,matrix(rep(party.names[1:(NP-1)], NG),NG,NP-1,
byrow=T) ,sep=".")
output$Delta <- coda::mcmc(output$Delta, thin=thin)
if(ret.beta==0){
colnames(output$Beta) <- paste(paste("beta", group.names,matrix(rep(party.names, NG),NG,NP, byrow=T) ,sep="."), matrix(rep(1:Precincts,NG*NP),NG*NP, Precincts, byrow=TRUE),sep=".")
output$Beta <- coda::mcmc(output$Beta, thin=thin)
}
}else{
output$Dr <- t(output$Dr)
dimnames(output$Dr) <- list(paste("dr", group.names, sep="."), 1:sample)
output$cell.count <- array(t(output$cell.count), c(NG, NP, sample))
dimnames(output$cell.count) <- list(group.names, party.names,
1:sample)
output$Gamma <- array(t(output$Gamma), c(NG, NP-1, sample))
dimnames(output$Gamma) <- list(group.names, party.names[1:(NP-1)], 1:sample)
output$Delta <- array(t(output$Delta), c(NG, NP-1,sample))
dimnames(output$Delta) <- list(group.names, party.names[1:(NP-1)], 1:sample)
if(ret.beta==0){
output$Beta <- array(t(output$Beta), c(NG, NP, Precincts, sample))
dimnames(output$Beta) <- list(group.names, party.names, 1:Precincts,
1:sample)
}
}
return(output)
}
|
print.logistf <-
function(x, ...)
{
print(x$call)
cat("Model fitted by", x$method)
cat("\nConfidence intervals and p-values by", paste(unique(x$method.ci), sep="/"), "\n\n")
cat("Coefficients:\n")
out <- x$coefficients
print(out)
LL <- -2 * (x$loglik['null']-x$loglik['full'])
cat("\nLikelihood ratio test=", LL, " on ", x$df, " df, p=", 1 -
pchisq(LL, x$df), ", n=",
x$n, "\n\n", sep = "")
invisible(x)
}
|
interpolateWithinGrid2D <-
function(grid_string, x, y, default_z){
parts = strsplit(grid_string,split=",",fixed=TRUE);
x_values = as.numeric(strsplit(parts[[1]][1],split=" ",fixed=TRUE)[[1]]);
y_values = as.numeric(strsplit(parts[[1]][2],split=" ",fixed=TRUE)[[1]]);
z_values = as.numeric(strsplit(parts[[1]][3],split=" ",fixed=TRUE)[[1]]);
NX = length(x_values);
NY = length(y_values);
NZ = length(z_values);
if(length(z_values)!=NX*NY){
cat(sprintf("ERROR parsing grid string: NX=%d, NY=%d but NZ=%d != NX*NY=%d\n",NX,NY,NZ,NX*NY));
return(0);
}
EPSILON = 1e-5;
if((!isInRange(x_values[1],x_values[NX],x,EPSILON)) || (!isInRange(y_values[1],y_values[NY],y,EPSILON))) return(default_z);
x_du = x + abs(x)*EPSILON;
x_dd = x - abs(x)*EPSILON;
y_du = y + abs(y)*EPSILON;
y_dd = y - abs(y)*EPSILON;
for(xi in 2:NX){
if(x_values[xi-1]<=x_du && x_values[xi]>=x_dd){ xi2 = xi; break; }
}
for(yi in 2:NY){
if(y_values[yi-1]<=y_du && y_values[yi]>=y_dd){ yi2 = yi; break; }
}
x1 = x_values[xi2-1];
x2 = x_values[xi2];
y1 = y_values[yi2-1];
y2 = y_values[yi2];
z11 = z_values[(xi2-2)*NY + (yi2-1)];
z12 = z_values[(xi2-2)*NY + yi2];
z21 = z_values[(xi2-1)*NY + (yi2-1)];
z22 = z_values[(xi2-1)*NY + yi2];
tz1 = z11*(x2-x)/(x2-x1) + z21*(x-x1)/(x2-x1);
tz2 = z12*(x2-x)/(x2-x1) + z22*(x-x1)/(x2-x1);
z = tz1*(y2-y)/(y2-y1) + tz2*(y-y1)/(y2-y1);
return(z);
}
|
rhub::check(".", "ubuntu-rchk", check_args="--no-manual --no-vignettes")
|
grid_positions<-function(n,m){
G1<-expand.grid(n:1,1:m)
G2<-cbind(G1[,2],G1[,1])
G2<-G2-0.5
G2[,1]<-G2[,1]/m
G2[,2]<-G2[,2]/n
return(G2)
}
|
library(sommer)
data(DT_yatesoats)
DT <- DT_yatesoats
DT$row <- as.numeric(as.character(DT$row))
DT$col <- as.numeric(as.character(DT$col))
DT$R <- as.factor(DT$row)
DT$C <- as.factor(DT$col)
m1.sommer <- mmer(Y~1+V+spl2Db(col,row, nsegments = c(14,21), degree = c(3,3), penaltyord = c(2,2), what = "base"),
random = ~R+C+spl2Db(col,row, nsegments = c(14,21), degree = c(3,3), penaltyord = c(2,2), what="bits"),
data=DT, tolpar = 1e-6, verbose = FALSE)
summary(m1.sommer)$varcomp
m2.sommer <- mmer(Y~1+V,
random = ~R+C+spl2Da(col,row, nsegments = c(14,21), degree = c(3,3), penaltyord = c(2,2)),
data=DT, tolpar = 1e-6, verbose = FALSE)
summary(m1.sommer)$varcomp
DT2 <- rbind(DT,DT)
DT2$Y <- DT2$Y + rnorm(length(DT2$Y))
DT2$trial <- c(rep("A",nrow(DT)),rep("B",nrow(DT)))
head(DT2)
m3.sommer <- mmer(Y~1+V,
random = ~vs(ds(trial),R)+vs(ds(trial),C)+
spl2Da(col,row, nsegments = c(14,21), degree = c(3,3), penaltyord = c(2,2), at.var = trial),
rcov = ~vs(ds(trial),units),
data=DT2, tolpar = 1e-6, verbose = FALSE)
summary(m3.sommer)$varcomp
|
gstream = function(distM, L, N0, k, statistics=c("all","o","w","g","m"), n0=0.3*L, n1=0.7*L, ARL=10000,alpha=0.05,skew.corr=TRUE,asymp=FALSE){
r1 = list()
n0 = ceiling(n0)
n1 = floor(n1)
if(n0<2){
cat("Note: Starting index has been set to n0 = 2 as the graph-based statistics are not well-defined for t<2. \n")
n0=2
}
if(n1>(L-2)){
cat("Note: Ending index has been set to n1 =", L-2, " as the graph-based statistics are not well-defined for t>",L-2,". \n")
n1=L-2
}
if(N0<L){
stop("Warning: Please adjust either N0 or L. The number of historical observations (N0) must be at least L. \n")
}
N = dim(distM)[1]
r1$scanZ = getscanZ(distM,N0,L,N,k,n0,n1,statistics)
r1$b = getb(distM,ARL,alpha,N0,n0,n1,L,k,statistics,skew.corr,dif=1e-10, nIterMax=100,asymp)
if (length(which(!is.na(match(c("o","ori","original","all"),statistics))))>0){
r1$tauhat$ori = which(r1$scanZ$ori>r1$b$ori)
}
if (length(which(!is.na(match(c("w","weighted","all"),statistics))))>0){
r1$tauhat$weighted = which(r1$scanZ$weighted>r1$b$weighted)
}
if (length(which(!is.na(match(c("m","max","all"),statistics))))>0){
r1$tauhat$max.type = which(r1$scanZ$max.type>r1$b$max.type)
}
if (length(which(!is.na(match(c("g","generalized","all"),statistics))))>0){
r1$tauhat$generalized = which(r1$scanZ$generalized>r1$b$generalized)
}
return(r1)
}
getZL = function(distM, k = 1){
L = dim(distM)[1]
A = matrix(0,L,k)
for (i in 1:L){
A[i,] = (sort(distM[i,1:L], index.return=T)$ix)[1:k]
}
temp = table(A)
id = as.numeric(row.names(temp))
deg = rep(0,L)
deg[id] = temp
deg.sumsq = sum(deg^2)
cn = sum((deg-k)^2)/L/k
count = 0
for (i in 1:L){
ids = A[i,]
count = count + length(which(A[ids,]==i))
}
vn = count/L/k
ts = 1:(L-1)
q = (L-ts-1)/(L-2)
p = (ts-1)/(L-2)
EX1L = 2*k*(ts)*(ts-1)/(L-1)
EX2L = 2*k*(L-ts)*(L-ts-1)/(L-1)
EX = 4*k*ts*(L-ts)/(L-1)
config1 = (2*k*L + 2*k*L*vn)
config2 = (3*k^2*L + deg.sumsq -2*k*L -2*k*L*vn)
config3 = (4*L^2*k^2 + 4*k*L + 4*k*L*vn - 12*k^2*L - 4*deg.sumsq)
f11 = 2*(ts)*(ts-1)/L/(L-1)
f21 = 4*(ts)*(ts-1)*(ts-2)/L/(L-1)/(L-2)
f31 = (ts)*(ts-1)*(ts-2)*(ts-3)/L/(L-1)/(L-2)/(L-3)
f12 = 2*(L-ts)*(L-ts-1)/L/(L-1)
f22 = 4*(L-ts)*(L-ts-1)*(L-ts-2)/L/(L-1)/(L-2)
f32 = (L-ts)*(L-ts-1)*(L-ts-2)*(L-ts-3)/L/(L-1)/(L-2)/(L-3)
h = 4*(ts-1)*(L-ts-1)/((L-2)*(L-3))
VX = EX*(h*(1+vn-2*k/(L-1))+(1-h)*cn)
var1 = config1*f11 + config2*f21 + config3*f31 - EX1L^2
var2 = config1*f12 + config2*f22 + config3*f32 - EX2L^2
v12 = config3*((ts)*(ts-1)*(L-ts)*(L-ts-1))/(L*(L-1)*(L-2)*(L-3)) - EX1L*EX2L
X = X1 = X2 = rep(0,L-1)
for (t in 1:(L-1)){
X2[t] = 2*(length(which(A[(t+1):L,]>t)))
X1[t] = 2*(length(which(A[1:t,]<=t)))
X[t] = 2*(length(which(A[1:t,]>t))+length(which(A[(t+1):L,]<=t)))
}
Rw = q*X1 + p*X2
ERw = q*EX1L + p*EX2L
varRw = q^2*var1 + p^2*var2 + 2*p*q*v12
Zw = (Rw - ERw)/sqrt(varRw)
Zdiff = ((X1-X2)-(EX1L-EX2L))/sqrt(var1+var2-2*v12)
S = Zw^2 + Zdiff^2
M = apply(cbind(abs(Zdiff),Zw),1,max)
Z = (EX-X)/sqrt(VX)
list(R=X,R1= X1, R2 = X2, Rw = Rw, Z1 = (X1-EX1L)/sqrt(var1) , Z2 = (X2-EX2L)/sqrt(var2), Zdiff = Zdiff, Zw = Zw, S = S, M =M, Z=Z )
}
getscanZ = function(distM,N0,L,N,k,n0,n1,statistics="all"){
maxZ = maxZw = maxS = maxM = rep((N0+1):N)
for (n in (N0+1):N){
tests = getZL(distM[(n-L+1):n,(n-L+1):n],k)
maxZ[n-N0] = max(tests$Z[n0:n1])
maxZw[n-N0] = max(tests$Zw[n0:n1])
maxS[n-N0] = max(tests$S[n0:n1])
maxM[n-N0] = max(tests$M[n0:n1])
}
scanZ = list()
if (length(which(!is.na(match(c("o","ori","original","all"),statistics))))>0){
scanZ$ori = maxZ
}
if (length(which(!is.na(match(c("w","weighted","all"),statistics))))>0){
scanZ$weighted = maxZw
}
if (length(which(!is.na(match(c("m","max","g","generalized","all"),statistics))))>0){
scanZ$max.type = maxM
}
if (length(which(!is.na(match(c("g","generalized","all"),statistics))))>0){
scanZ$generalized = maxS
}
return(scanZ)
}
gb_quantities = function(distM,N0,k){
psum = qsum = psumk = qsumk = psumk1 = qsumk1 = psumk2 = qsumk2 = pLk1 = qLk1 = deg.sum3.n = aaa1.n = aaa2.n = daa.n = dda.n = rep(0,1)
psumk_hao = qsumk_hao = rep(0,1)
n = N0
An = matrix(0,n,k+2)
for (i in 1:n){
An[i,] = (sort(distM[i,1:n], index.return=T)$ix)[1:(k+2)]
}
temp = table(An[,1:k])
id = as.numeric(row.names(temp))
deg = rep(0,n)
deg[id] = temp
deg.sumsq = sum(deg^2)
deg.sum3 = sum(deg^3)
count = daa = dda = aaa1 = aaa2 = 0
for (i in 1:n){
ids = An[i,1:k]
count = count + length(which(An[ids,1:k]==i))
daa = daa + deg[i]*length(which(An[ids,1:k]==i))
dda = dda + deg[i]*sum(deg[ids])
for (j in ids){
u = An[j,1:k]
aaa1 = aaa1 + length(which(An[u,1:k]==i))
aaa2 = aaa2 + length(which(!is.na(match(ids,u))))
}
}
psum = count/n
qsum = deg.sumsq/n-k
deg.sum3.n = deg.sum3
aaa1.n = aaa1
aaa2.n = aaa2
daa.n = daa
dda.n = dda
count1 = count2 = count3 = count4 = count5 = count6 = count7 = count8 = 0
for (i in 1:n){
ids = An[i,k]
count1 = count1 + length(which(An[ids,1:k]==i))
count2 = count2 + length(which(An[-i,1:k]==ids))
ids1 = An[i,k+1]
count3 = count3 + length(which(An[ids1,1:k]==i))
count4 = count4 + length(which(An[-i,1:k]==ids1))
count7 = count7 + length(which(An[ids1,k+1]==i))
count8 = count8 + length(which(An[-i,k+1]==ids1))
ids2 = An[i,k+2]
count5 = count5 + length(which(An[ids2,1:k]==i))
count6 = count6 + length(which(An[-i,1:k]==ids2))
}
psumk = count1/n
qsumk = count2/n
psumk1 = count3/n
qsumk1 = count4/n
psumk2 = count5/n
qsumk2 = count6/n
pLk1 = count7/n
qLk1 = count8/n
list(psum=psum,qsum=qsum, psumk1=psumk1, qsumk1=qsumk1, psumk2=psumk2, qsumk2=qsumk2, pLk1=pLk1, qLk1=qLk1, psumk = psumk, qsumk=qsumk, deg.sumsq = deg.sumsq, deg.sum3.n= deg.sum3.n, aaa1.n=aaa1.n, aaa2.n=aaa2.n, daa.n=daa.n, dda.n=dda.n)
}
Nu = function(x){
y = x/2
(1/y)*(pnorm(y)-0.5)/(y*pnorm(y) + dnorm(y))
}
C1_Z = function(x, L, k, psum,qsum){
((16*(k + 2*psum - psum)*(2*L- 2*x - 1)*(x^2 - x))/(L^3 - 6*L^2 + 11*L - 6) - (16*k^2*x^2*(L- x))/(L - 1)^2 + (16*k^2*x*(L- x)^2)/(L - 1)^2 + (4*x*(3*k^2 + k + 2*qsum - qsum)*(3*L^2 - 10*L*x - 3*L + 8*x^2 + 2*x + 2))/(L^3 - 6*L^2 + 11*L - 6) + (16*L*k^2*x*(3*L*x - L^2 + L - 2*x^2 - 2*x + 1))/((L - 1)*(L - 2)*(L - 3)))/(4*((k^2*(((((-x+ 1)*(4*L - 4*x - 4))/((L - 2)*(L - 3)) + 1)*(k + qsum - k^2))/k + ((-x+ 1)*(4*L - 4*x - 4)*(k + psum - L*k - L*psum + 2*k^2))/(k*(L - 1)*(L - 2)*(L - 3)))^2*x^2*(L- x)^2)/(L - 1)^2)^(1/2)) - (((16*k^2*(((((-x+ 1)*(4*L - 4*x - 4))/((L - 2)*(L - 3)) + 1)*(k - k^2 + qsum))/k + ((-x+ 1)*(4*L - 4*x - 4)*(k + psum - L*k - L*psum + 2*k^2))/(k*(L - 1)*(L - 2)*(L - 3)))^2*x^2*(L- x))/(L - 1)^2 - (16*k^2*(((((-x+ 1)*(4*L - 4*x - 4))/((L - 2)*(L - 3)) + 1)*(k - k^2 + qsum))/k + ((-x+ 1)*(4*L - 4*x - 4)*(k + psum - L*k - L*psum + 2*k^2))/(k*(L - 1)*(L - 2)*(L - 3)))^2*x*(L- x)^2)/(L - 1)^2 + (64*k*(((((-x+ 1)*(4*L - 4*x - 4))/((L - 2)*(L - 3)) + 1)*(k - k^2 + qsum))/k + ((-x+ 1)*(4*L - 4*x - 4)*(k + psum - L*k - L*psum + 2*k^2))/(k*(L - 1)*(L - 2)*(L - 3)))*x^2*(L- 2*x)*(L- x)^2*(psum - qsum - L*psum + L*qsum - L*k^2 + 3*k^2))/((L - 1)^2*(L^3 - 6*L^2 + 11*L - 6)))*(L*((4*x*(L- x))/(L*(L - 1)) - (16*(L- x)*(L - x - 1)*(x^2 - x))/(L*(L - 1)*(L - 2)*(L - 3)))*(3*k^2 + k + 2*qsum - qsum) + (16*(k + 2*psum - psum)*(x^2 - x)*(L^2 - 2*L*x - L + x^2 + x))/(L^3 - 6*L^2 + 11*L - 6) - (16*k^2*x^2*(L- x)^2)/(L - 1)^2 + (16*L*k^2*(L- x)*(L - x - 1)*(x^2 - x))/((L - 1)*(L - 2)*(L - 3))))/(128*((k^2*(((((-x+ 1)*(4*L - 4*x - 4))/((L - 2)*(L - 3)) + 1)*(k + qsum - k^2))/k + ((-x+ 1)*(4*L - 4*x - 4)*(k + psum - L*k - L*psum + 2*k^2))/(k*(L - 1)*(L - 2)*(L - 3)))^2*x^2*(L- x)^2)/(L - 1)^2)^(3/2))
}
C2_Z = function(x, L, k, psum, qsum, psumk, qsumk){
((((4*x*(L - x))/(L*(L - 1)) - (16*(L - x)*(L - x - 1)*(x^2 - x))/(L*(L - 1)*(L - 2)*(L - 3)))*(2*k + 4*qsum - 2*qsum - 7*L*k - 8*L*qsum + 7*L*qsum - 2*L*qsumk - 9*L*k^2 + 3*L^2*k + 2*L^2*qsum - 3*L^2*qsum + 2*L^2*qsumk + 6*k^2 + 3*L^2*k^2))/(L^2 - 3*L + 2) + L*(3*k^2 + k + 2*qsum - qsum)*((4*(L^2 - 2*L*x - 2*L + x^2 + 2*x))/(L*(L - 1)*(L - 2)) - (4*x*(L - x))/(L^2*(L - 1)) + (4*x*(L - x))/(L*(L - 1)^2*(L - 2)) + (16*(-x + 1)*(L^2 - 3*L*x - L + 2*x^2 + x))/(L*(L - 1)*(L - 2)*(L - 3)) - (16*(4*L^2 - 12*L + 6)*(L - x)*(L - x - 1)*(x^2 - x))/(L^2*(L - 1)^2*(L - 2)^2*(L - 3)^2)) + (16*k^2*x^2*(L - x))/(L - 1)^2 - (16*k^2*x*(L - x)^2)/(L - 1)^2 - (16*(k + 2*psum - psum)*(-x + 1)*(L^6 - 3*L^5*x - 7*L^5 + 2*L^4*x^2 + 23*L^4*x + 17*L^4 - 20*L^3*x^2 - 55*L^3*x - 17*L^3 + 4*L^2*x^3 + 50*L^2*x^2 + 47*L^2*x + 6*L^2 - 12*L*x^3 - 36*L*x^2 - 12*L*x + 6*x^3 + 6*x^2))/(L*(11*L - 6*L^2 + L^3 - 6)^2) + (16*(x^2 - x)*(L^2 - 2*L*x - L + x^2 + x)*(2*k + 4*psum - 2*psum - 7*L*k - 10*L*psum + 7*L*psum - 2*L*psumk + 3*L^2*k + 4*L^2*psum - 3*L^2*psum + 2*L^2*psumk))/(L*(L^2 - 3*L + 2)*(L^3 - 6*L^2 + 11*L - 6)) - (16*L*k^2*(-x + 1)*(L^2 - 3*L*x - L + 2*x^2 + x))/((L - 1)*(L - 2)*(L - 3)) + (16*k^2*(4*L^2 - 12*L + 6)*(L - x)*(L - x - 1)*(x^2 - x))/((L - 1)^2*(L - 2)^2*(L - 3)^2))/(4*((k^2*(((((-x + 1)*(4*L - 4*x - 4))/((L - 2)*(L - 3)) + 1)*(k + qsum - k^2))/k + ((-x + 1)*(4*L - 4*x - 4)*(k + psum - L*k - L*psum + 2*k^2))/(k*(L - 1)*(L - 2)*(L - 3)))^2*x^2*(L - x)^2)/(L - 1)^2)^(1/2)) + (((16*k^2*(((((-x + 1)*(4*L - 4*x - 4))/((L - 2)*(L - 3)) + 1)*(k - k^2 + qsum))/k + ((-x + 1)*(4*L - 4*x - 4)*(k + psum - L*k - L*psum + 2*k^2))/(k*(L - 1)*(L - 2)*(L - 3)))^2*x^2*(L - x))/(L - 1)^2 - (16*k^2*(((((-x + 1)*(4*L - 4*x - 4))/((L - 2)*(L - 3)) + 1)*(k - k^2 + qsum))/k + ((-x + 1)*(4*L - 4*x - 4)*(k + psum - L*k - L*psum + 2*k^2))/(k*(L - 1)*(L - 2)*(L - 3)))^2*x*(L - x)^2)/(L - 1)^2 + (64*k*(((((-x + 1)*(4*L - 4*x - 4))/((L - 2)*(L - 3)) + 1)*(k - k^2 + qsum))/k + ((-x + 1)*(4*L - 4*x - 4)*(k + psum - L*k - L*psum + 2*k^2))/(k*(L - 1)*(L - 2)*(L - 3)))*x^2*(L - 2*x)*(L - x)^2*(psum - qsum - L*psum + L*qsum - L*k^2 + 3*k^2))/((L - 1)^2*(L^3 - 6*L^2 + 11*L - 6)))*(L*((4*x*(L - x))/(L*(L - 1)) - (16*(L - x)*(L - x - 1)*(x^2 - x))/(L*(L - 1)*(L - 2)*(L - 3)))*(3*k^2 + k + 2*qsum - qsum) + (16*(k + 2*psum - psum)*(x^2 - x)*(L^2 - 2*L*x - L + x^2 + x))/(L^3 - 6*L^2 + 11*L - 6) - (16*k^2*x^2*(L - x)^2)/(L - 1)^2 + (16*L*k^2*(L - x)*(L - x - 1)*(x^2 - x))/((L - 1)*(L - 2)*(L - 3))))/(128*((k^2*(((((-x + 1)*(4*L - 4*x - 4))/((L - 2)*(L - 3)) + 1)*(k + qsum - k^2))/k + ((-x + 1)*(4*L - 4*x - 4)*(k + psum - L*k - L*psum + 2*k^2))/(k*(L - 1)*(L - 2)*(L - 3)))^2*x^2*(L - x)^2)/(L - 1)^2)^(3/2))
}
C1_w_asy = function(x){
1/(2*x*(1-x))
}
C2_w_asy = function(x,k,psum,psumk1){
(x^2-x+1)/(x*(1-x)) - (2*k*psumk1)/(k+psum)
}
C1_d_asy = function(x){
1/(x*(1-x))
}
C2_d_asy = function(x,k,qsum,qsumk1){
(10*qsum-4*k*qsumk1-(6*k^2-10*k))/(2*(qsum-k^2+k)) - 1/(2*x*(1-x))
}
C1_w = function(x,L,k,psum,qsum){
if(k==1){
result=-(x^2*(x - 1)^2*(2*x^2 - 2*L*x + L)*(L^2 - 2*L*x - L + x^2 + x)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2*(2*psum - 4*L + qsum - 3*L*psum - L*qsum - L*k^2 + L^2*psum + L^2 + 3*k^2 + 3))/(2*(L - 1)^5*(L - 2)^6*(L - 3)^3*((x^2*(x - 1)^2*(L^2 - 2*L*x - L + x^2 + x)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2)/((L - 3)^2*(L^2 - 3*L + 2)^4))^(3/2))
}
if(k==5){
result= -(x^2*(x - 1)^2*(2*x^2 - 2*L*x + L)*(L^2 - 2*L*x - L + x^2 + x)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2*(2*psum - 20*L + qsum - 3*L*psum - L*qsum - L*k^2 + L^2*psum + 5*L^2 + 3*k^2 + 15))/(2*(L - 1)^5*(L - 2)^6*(L - 3)^3*((x^2*(x - 1)^2*(L^2 - 2*L*x - L + x^2 + x)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2)/((L - 3)^2*(L^2 - 3*L + 2)^4))^(3/2))
}
else{
result = -(x^2*(x - 1)^2*(2*x^2 - 2*L*x + L)*(L^2 - 2*L*x - L + x^2 + x)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^3)/(2*(L - 1)^5*(L - 2)^6*(L - 3)^3*((x^2*(x - 1)^2*(L^2 - 2*L*x - L + x^2 + x)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2)/((L - 3)^2*(L^2 - 3*L + 2)^4))^(3/2))
}
return(result)
}
C2_w = function(x,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2){
if(k==1){
num=- ((x - L + 1)*(36*L - 72*x + 72*k^2*x^2 + 72*k^2*x^3 + 24*L*psum + 12*L*qsum + 66*L*x - 48*psum*x - 24*qsum*x + 36*L*k^2 - 74*L^2*psum + 85*L^3*psum - 45*L^4*psum + 11*L^5*psum - L^6*psum - 31*L^2*qsum + 27*L^3*qsum - 9*L^4*qsum + L^5*qsum - 312*L*x^2 + 88*L^2*x - 36*L*x^3 - 169*L^3*x + 96*L^4*x - 23*L^5*x + 2*L^6*x - 72*k^2*x + 88*psum*x^2 + 8*psum*x^3 - 48*psumk1*x^2 + 48*psumk1*x^3 - 16*psumk2*x^2 + 16*psumk2*x^3 + 56*qsum*x^2 - 8*qsum*x^3 - 16*qsumk1*x^2 + 16*qsumk1*x^3 - 4*qsumk2*x^2 + 4*qsumk2*x^3 - 105*L^2 + 112*L^3 - 54*L^4 + 12*L^5 - L^6 - 69*L^2*k^2 + 43*L^3*k^2 - 11*L^4*k^2 + L^5*k^2 + 144*x^2 + 313*L^2*x^2 + 33*L^2*x^3 - 153*L^3*x^2 - 10*L^3*x^3 + 35*L^4*x^2 + L^4*x^3 - 3*L^5*x^2 - 210*L*k^2*x^2 + 52*L^2*k^2*x - 66*L*k^2*x^3 - 64*L^3*k^2*x + 20*L^4*k^2*x - 2*L^5*k^2*x + 245*L^2*psum*x^2 + 33*L^2*psum*x^3 - 133*L^3*psum*x^2 - 10*L^3*psum*x^3 + 33*L^4*psum*x^2 + L^4*psum*x^3 - 3*L^5*psum*x^2 + 30*L^2*psumk1*x^2 + 70*L^2*psumk1*x^3 + 14*L^2*psumk2*x^2 - 50*L^3*psumk1*x^2 + 14*L^2*psumk2*x^3 - 20*L^3*psumk1*x^3 - 12*L^3*psumk2*x^2 + 18*L^4*psumk1*x^2 - 2*L^3*psumk2*x^3 + 2*L^4*psumk1*x^3 + 2*L^4*psumk2*x^2 - 2*L^5*psumk1*x^2 + 68*L^2*qsum*x^2 - 20*L^3*qsum*x^2 + 2*L^4*qsum*x^2 + 14*L^2*qsumk1*x^2 + 14*L^2*qsumk1*x^3 + 4*L^2*qsumk2*x^2 - 12*L^3*qsumk1*x^2 + 2*L^2*qsumk2*x^3 - 2*L^3*qsumk1*x^3 - 2*L^3*qsumk2*x^2 + 2*L^4*qsumk1*x^2 + 60*L*psum*x + 48*L*psumk1*x + 16*L*psumk2*x + 6*L*qsum*x + 16*L*qsumk1*x + 4*L*qsumk2*x + 152*L^2*k^2*x^2 + 20*L^2*k^2*x^3 - 42*L^3*k^2*x^2 - 2*L^3*k^2*x^3 + 4*L^4*k^2*x^2 + 66*L*k^2*x - 218*L*psum*x^2 + 40*L^2*psum*x - 38*L*psum*x^3 - 117*L^3*psum*x + 78*L^4*psum*x - 21*L^5*psum*x + 2*L^6*psum*x + 52*L*psumk1*x^2 - 100*L^2*psumk1*x - 100*L*psumk1*x^3 + 12*L*psumk2*x^2 - 28*L^2*psumk2*x + 70*L^3*psumk1*x - 28*L*psumk2*x^3 + 14*L^3*psumk2*x - 20*L^4*psumk1*x - 2*L^4*psumk2*x + 2*L^5*psumk1*x - 94*L*qsum*x^2 + 48*L^2*qsum*x + 2*L*qsum*x^3 - 52*L^3*qsum*x + 18*L^4*qsum*x - 2*L^5*qsum*x + 12*L*qsumk1*x^2 - 28*L^2*qsumk1*x - 28*L*qsumk1*x^3 + 2*L*qsumk2*x^2 - 6*L^2*qsumk2*x + 14*L^3*qsumk1*x - 6*L*qsumk2*x^3 + 2*L^3*qsumk2*x - 2*L^4*qsumk1*x))/((L - 2)^3*(L - 4)*(L^2 - 4*L + 3)^2*((x^2*(x - 1)^2*(x - L - 2*L*x + L^2 + x^2)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2)/((L - 3)^2*(L^2 - 3*L + 2)^4))^(1/2)) - (x^2*(x - 1)^2*(L^2 - 2*L*x - L + x^2 + x)^2*(2*L^2*x - L^2 - 6*L*x^2 + 2*L*x + L + 4*x^3 - 2*x)*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2*(2*psum - 4*L + qsum - 3*L*psum - L*qsum - L*k^2 + L^2*psum + L^2 + 3*k^2 + 3))/(2*(L - 3)^3*(L^2 - 3*L + 2)^6*((x^2*(x - 1)^2*(x - L - 2*L*x + L^2 + x^2)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2)/((L - 3)^2*(L^2 - 3*L + 2)^4))^(3/2))
den=1
part2=0
}
if(k==5){
num=((x - L + 1)*(75600*L - 151200*x + 30240*k^2*x^2 + 30240*k^2*x^3 + 10080*L*psum + 5040*L*qsum + 196740*L*x - 20160*psum*x - 10080*qsum*x + 15120*L*k^2 - 34956*L^2*psum + 48188*L^3*psum - 34305*L^4*psum + 13857*L^5*psum - 3282*L^6*psum + 450*L^7*psum - 33*L^8*psum + L^9*psum - 14958*L^2*qsum + 16615*L^3*qsum - 8845*L^4*qsum + 2506*L^5*qsum - 388*L^6*qsum + 31*L^7*qsum - L^8*qsum - 771480*L*x^2 + 123450*L^2*x - 75600*L*x^3 - 418250*L^3*x + 347605*L^4*x - 145120*L^5*x + 34290*L^6*x - 4640*L^7*x + 335*L^8*x - 10*L^9*x - 30240*k^2*x + 36960*psum*x^2 + 3360*psum*x^3 - 47040*psumk1*x^2 + 47040*psumk1*x^3 - 14400*psumk2*x^2 + 14400*psumk2*x^3 + 23520*qsum*x^2 - 3360*qsum*x^3 - 6720*qsumk1*x^2 + 6720*qsumk1*x^3 - 1800*qsumk2*x^2 + 1800*qsumk2*x^3 - 249570*L^2 + 324015*L^3 - 215750*L^4 + 81815*L^5 - 18350*L^6 + 2405*L^7 - 170*L^8 + 5*L^9 - 34794*L^2*k^2 + 30009*L^3*k^2 - 13141*L^4*k^2 + 3222*L^5*k^2 - 448*L^6*k^2 + 33*L^7*k^2 - L^8*k^2 + 302400*x^2 + 925350*L^2*x^2 + 98370*L^2*x^3 - 609605*L^3*x^2 - 51675*L^3*x^3 + 233495*L^4*x^2 + 14030*L^4*x^3 - 53130*L^5*x^2 - 2080*L^5*x^3 + 7060*L^6*x^2 + 160*L^6*x^3 - 505*L^7*x^2 - 5*L^7*x^3 + 15*L^8*x^2 - 99828*L*k^2*x^2 + 9570*L^2*k^2*x - 39348*L*k^2*x^3 - 33736*L^3*k^2*x + 19838*L^4*k^2*x - 5548*L^5*k^2*x + 830*L^6*k^2*x - 64*L^7*k^2*x + 2*L^8*k^2*x + 140076*L^2*psum*x^2 + 20176*L^2*psum*x^3 - 100385*L^3*psum*x^2 - 10387*L^3*psum*x^3 + 41021*L^4*psum*x^2 + 2808*L^4*psum*x^3 - 9792*L^5*psum*x^2 - 416*L^5*psum*x^3 + 1348*L^6*psum*x^2 + 32*L^6*psum*x^3 - 99*L^7*psum*x^2 - L^7*psum*x^3 + 3*L^8*psum*x^2 - 8800*L^2*psumk1*x^2 + 137880*L^2*psumk1*x^3 - 600*L^2*psumk2*x^2 - 63210*L^3*psumk1*x^2 + 38880*L^2*psumk2*x^3 - 74670*L^3*psumk1*x^3 - 19470*L^3*psumk2*x^2 + 52530*L^4*psumk1*x^2 - 19410*L^3*psumk2*x^3 + 22140*L^4*psumk1*x^3 + 14400*L^4*psumk2*x^2 - 18540*L^5*psumk1*x^2 + 5010*L^4*psumk2*x^3 - 3600*L^5*psumk1*x^3 - 4380*L^5*psumk2*x^2 + 3300*L^6*psumk1*x^2 - 630*L^5*psumk2*x^3 + 300*L^6*psumk1*x^3 + 600*L^6*psumk2*x^2 - 290*L^7*psumk1*x^2 + 30*L^6*psumk2*x^3 - 10*L^7*psumk1*x^3 - 30*L^7*psumk2*x^2 + 10*L^8*psumk1*x^2 + 44994*L^2*qsum*x^2 - 502*L^2*qsum*x^3 - 21536*L^3*qsum*x^2 + 52*L^3*qsum*x^3 + 5678*L^4*qsum*x^2 - 2*L^4*qsum*x^3 - 834*L^5*qsum*x^2 + 64*L^6*qsum*x^2 - 2*L^7*qsum*x^2 + 280*L^2*qsumk1*x^2 + 17200*L^2*qsumk1*x^3 + 270*L^2*qsumk2*x^2 - 8990*L^3*qsumk1*x^2 + 4290*L^2*qsumk2*x^3 - 8210*L^3*qsumk1*x^3 - 2400*L^3*qsumk2*x^2 + 6220*L^4*qsumk1*x^2 - 1890*L^3*qsumk2*x^3 + 1990*L^4*qsumk1*x^3 + 1500*L^4*qsumk2*x^2 - 1760*L^5*qsumk1*x^2 + 390*L^4*qsumk2*x^3 - 230*L^5*qsumk1*x^3 - 360*L^5*qsumk2*x^2 + 220*L^6*qsumk1*x^2 - 30*L^5*qsumk2*x^3 + 10*L^6*qsumk1*x^3 + 30*L^6*qsumk2*x^2 - 10*L^7*qsumk1*x^2 + 32952*L*psum*x + 47040*L*psumk1*x + 14400*L*psumk2*x + 6396*L*qsum*x + 6720*L*qsumk1*x + 1800*L*qsumk2*x + 99366*L^2*k^2*x^2 + 20670*L^2*k^2*x^3 - 46952*L^3*k^2*x^2 - 5612*L^3*k^2*x^3 + 12056*L^4*k^2*x^2 + 832*L^4*k^2*x^3 - 1728*L^5*k^2*x^2 - 64*L^5*k^2*x^3 + 130*L^6*k^2*x^2 + 2*L^6*k^2*x^3 - 4*L^7*k^2*x^2 + 39348*L*k^2*x - 105772*L*psum*x^2 + 6036*L^2*psum*x - 17252*L*psum*x^3 - 54214*L^3*psum*x + 52495*L^4*psum*x - 24070*L^5*psum*x + 6084*L^6*psum*x - 866*L^7*psum*x + 65*L^8*psum*x - 2*L^9*psum*x + 82040*L*psumk1*x^2 - 129080*L^2*psumk1*x - 129080*L*psumk1*x^3 + 23880*L*psumk2*x^2 - 38280*L^2*psumk2*x + 137880*L^3*psumk1*x - 38280*L*psumk2*x^3 + 38880*L^3*psumk2*x - 74670*L^4*psumk1*x - 19410*L^4*psumk2*x + 22140*L^5*psumk1*x + 5010*L^5*psumk2*x - 3600*L^6*psumk1*x - 630*L^6*psumk2*x + 300*L^7*psumk1*x + 30*L^7*psumk2*x - 10*L^8*psumk1*x - 48524*L*qsum*x^2 + 18654*L^2*qsum*x + 2132*L*qsum*x^3 - 29436*L^3*qsum*x + 17026*L^4*qsum*x - 4954*L^5*qsum*x + 774*L^6*qsum*x - 62*L^7*qsum*x + 2*L^8*qsum*x + 10760*L*qsumk1*x^2 - 17480*L^2*qsumk1*x - 17480*L*qsumk1*x^3 + 2760*L*qsumk2*x^2 - 4560*L^2*qsumk2*x + 17200*L^3*qsumk1*x - 4560*L*qsumk2*x^3 + 4290*L^3*qsumk2*x - 8210*L^4*qsumk1*x - 1890*L^4*qsumk2*x + 1990*L^5*qsumk1*x + 390*L^5*qsumk2*x - 230*L^6*qsumk1*x - 30*L^6*qsumk2*x + 10*L^7*qsumk1*x))
den=((L - 2)^3*(L^2 - 4*L + 3)^2*(L^4 - 26*L^3 + 251*L^2 - 1066*L + 1680)*((x^2*(x - 1)^2*(x - L - 2*L*x + L^2 + x^2)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2)/((L - 3)^2*(L^2 - 3*L + 2)^4))^(1/2))
part2 = (x^2*(x - 1)^2*(L^2 - 2*L*x - L + x^2 + x)^2*(2*L^2*x - L^2 - 6*L*x^2 + 2*L*x + L + 4*x^3 - 2*x)*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2*(2*psum - 20*L + qsum - 3*L*psum - L*qsum - L*k^2 + L^2*psum + 5*L^2 + 3*k^2 + 15))/(2*(L - 3)^3*(L^2 - 3*L + 2)^6*((x^2*(x - 1)^2*(x - L - 2*L*x + L^2 + x^2)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2)/((L - 3)^2*(L^2 - 3*L + 2)^4))^(3/2))
}else{
num = - ((x - L + 1)*(18*k*x - 18*k^2*x^3 - 9*L*k - 6*L*psum - 3*L*qsum - 18*k^2*x^2 + 12*psum*x + 6*qsum*x - 9*L*k^2 + 24*L^2*k - 22*L^3*k + 8*L^4*k - L^5*k + 17*L^2*psum - 17*L^3*psum + 7*L^4*psum - L^5*psum + 7*L^2*qsum - 5*L^3*qsum + L^4*qsum - 36*k*x^2 + 18*k^2*x + 2*psum*x^2 - 26*psum*x^3 - 12*psumk*x^2 + 12*psumk*x^3 + 4*qsum*x^2 - 16*qsum*x^3 - 6*qsumk*x^2 + 6*qsumk*x^3 + 15*L^2*k^2 - 7*L^3*k^2 + L^4*k^2 + 48*L*k^2*x^2 - 61*L^2*k*x^2 - 16*L^2*k^2*x + 12*L*k^2*x^3 - 6*L^2*k*x^3 + 23*L^3*k*x^2 + 12*L^3*k^2*x + L^3*k*x^3 - 3*L^4*k*x^2 - 2*L^4*k^2*x - 67*L^2*psum*x^2 - 20*L^2*psum*x^3 + 33*L^3*psum*x^2 + 3*L^3*psum*x^3 - 5*L^4*psum*x^2 + 10*L^2*psumk*x^2 + 12*L^2*psumk*x^3 - 10*L^3*psumk*x^2 - 2*L^3*psumk*x^3 + 2*L^4*psumk*x^2 - 26*L^2*qsum*x^2 - 4*L^2*qsum*x^3 + 6*L^3*qsum*x^2 + 6*L^2*qsumk*x^2 + 2*L^2*qsumk*x^3 - 2*L^3*qsumk*x^2 - 12*L*k*x - 36*L*psum*x + 12*L*psumk*x - 18*L*qsum*x + 6*L*qsumk*x - 26*L^2*k^2*x^2 - 2*L^2*k^2*x^3 + 4*L^3*k^2*x^2 + 69*L*k*x^2 - 12*L*k^2*x - 25*L^2*k*x + 9*L*k*x^3 + 36*L^3*k*x - 15*L^4*k*x + 2*L^5*k*x + 41*L*psum*x^2 + 19*L^2*psum*x + 41*L*psum*x^3 + 12*L^3*psum*x - 11*L^4*psum*x + 2*L^5*psum*x + 10*L*psumk*x^2 - 22*L^2*psumk*x - 22*L*psumk*x^3 + 12*L^3*psumk*x - 2*L^4*psumk*x + 20*L*qsum*x^2 + 6*L^2*qsum*x + 18*L*qsum*x^3 + 6*L^3*qsum*x - 2*L^4*qsum*x + 2*L*qsumk*x^2 - 8*L^2*qsumk*x - 8*L*qsumk*x^3 + 2*L^3*qsumk*x))
den =((L - 2)^3*(L^2 - 4*L + 3)^2*((x^2*(x - 1)^2*(x - L - 2*L*x + L^2 + x^2)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2)/((L - 3)^2*(L^2 - 3*L + 2)^4))^(1/2))
part2 = (x^2*(x - 1)^2*(L^2 - 2*L*x - L + x^2 + x)^2*(2*L^2*x - L^2 - 6*L*x^2 + 2*L*x + L + 4*x^3 - 2*x)*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^3)/(2*(L - 3)^3*(L^2 - 3*L + 2)^6*((x^2*(x - 1)^2*(x - L - 2*L*x + L^2 + x^2)^2*(3*k + 2*psum + qsum - 4*L*k - 3*L*psum - L*qsum - L*k^2 + L^2*k + L^2*psum + 3*k^2)^2)/((L - 3)^2*(L^2 - 3*L + 2)^4))^(3/2))
}
return(num/den - part2)
}
C1_d = function(x,L,k,qsum){
if(k==1){
result = (L*x^2*(L - x)^2*(- k^2 + k + qsum)^2*(- k^2 + qsum + 1))/(2*(L - 1)^3*((x^2*(L - x)^2*(- k^2 + k + qsum)^2)/(L - 1)^2)^(3/2))
}
if(k==5){
result = (L*x^2*(L - x)^2*(- k^2 + k + qsum)^2*(- k^2 + qsum + 5))/(2*(L - 1)^3*((x^2*(L - x)^2*(- k^2 + k + qsum)^2)/(L - 1)^2)^(3/2))
}
else{
result = (L*x^2*(L - x)^2*(- k^2 + k + qsum)^3)/(2*(L - 1)^3*((x^2*(L - x)^2*(- k^2 + k + qsum)^2)/(L - 1)^2)^(3/2))
}
return(result)
}
C2_d = function(x,L,k,psum,qsum,qsumk,psumk1,qsumk1,psumk2,qsumk2){
if(k==1){
result=-(x^2*(L - x)^2*(- k^2 + k + qsum)^2*(48*k^2*x^2 + 144*L*x - 12*L^2*qsum + 19*L^3*qsum - 8*L^4*qsum + L^5*qsum + 204*L*x^2 - 204*L^2*x + 82*L^3*x - 10*L^4*x - 144*qsum*x^2 + 32*qsumk1*x^2 + 8*qsumk2*x^2 - 12*L^2 + 19*L^3 - 8*L^4 + L^5 + 12*L^2*k^2 - 19*L^3*k^2 + 8*L^4*k^2 - L^5*k^2 - 144*x^2 - 82*L^2*x^2 + 10*L^3*x^2 - 100*L*k^2*x^2 + 100*L^2*k^2*x - 46*L^3*k^2*x + 6*L^4*k^2*x - 82*L^2*qsum*x^2 + 10*L^3*qsum*x^2 + 28*L^2*qsumk1*x^2 + 4*L^2*qsumk2*x^2 - 4*L^3*qsumk1*x^2 + 144*L*qsum*x - 32*L*qsumk1*x - 8*L*qsumk2*x + 46*L^2*k^2*x^2 - 6*L^3*k^2*x^2 - 48*L*k^2*x + 204*L*qsum*x^2 - 204*L^2*qsum*x + 82*L^3*qsum*x - 10*L^4*qsum*x - 56*L*qsumk1*x^2 + 56*L^2*qsumk1*x - 12*L*qsumk2*x^2 + 12*L^2*qsumk2*x - 28*L^3*qsumk1*x - 4*L^3*qsumk2*x + 4*L^4*qsumk1*x))/(2*(L - 1)^4*(L^3 - 9*L^2 + 26*L - 24)*((x^2*(L - x)^2*(- k^2 + k + qsum)^2)/(L - 1)^2)^(3/2))
}
if(k==5){
result=-(x^2*(L - x)^2*(- k^2 + k + qsum)^2*(6720*k^2*x^2 + 100800*L*x - 1680*L^2*qsum + 2746*L^3*qsum - 1317*L^4*qsum + 277*L^5*qsum - 27*L^6*qsum + L^7*qsum + 147960*L*x^2 - 147960*L^2*x + 68360*L^3*x - 14110*L^4*x + 1360*L^5*x - 50*L^6*x - 20160*qsum*x^2 + 4480*qsumk1*x^2 + 1200*qsumk2*x^2 - 8400*L^2 + 13730*L^3 - 6585*L^4 + 1385*L^5 - 135*L^6 + 5*L^7 + 1680*L^2*k^2 - 2746*L^3*k^2 + 1317*L^4*k^2 - 277*L^5*k^2 + 27*L^6*k^2 - L^7*k^2 - 100800*x^2 - 68360*L^2*x^2 + 14110*L^3*x^2 - 1360*L^4*x^2 + 50*L^5*x^2 - 14344*L*k^2*x^2 + 14344*L^2*k^2*x - 7400*L^3*k^2*x + 1610*L^4*k^2*x - 160*L^5*k^2*x + 6*L^6*k^2*x - 13672*L^2*qsum*x^2 + 2822*L^3*qsum*x^2 - 272*L^4*qsum*x^2 + 10*L^5*qsum*x^2 + 8080*L^2*qsumk1*x^2 + 1980*L^2*qsumk2*x^2 - 2780*L^3*qsumk1*x^2 - 600*L^3*qsumk2*x^2 + 400*L^4*qsumk1*x^2 + 60*L^4*qsumk2*x^2 - 20*L^5*qsumk1*x^2 + 20160*L*qsum*x - 4480*L*qsumk1*x - 1200*L*qsumk2*x + 7400*L^2*k^2*x^2 - 1610*L^3*k^2*x^2 + 160*L^4*k^2*x^2 - 6*L^5*k^2*x^2 - 6720*L*k^2*x + 29592*L*qsum*x^2 - 29592*L^2*qsum*x + 13672*L^3*qsum*x - 2822*L^4*qsum*x + 272*L^5*qsum*x - 10*L^6*qsum*x - 10160*L*qsumk1*x^2 + 10160*L^2*qsumk1*x - 2640*L*qsumk2*x^2 + 2640*L^2*qsumk2*x - 8080*L^3*qsumk1*x - 1980*L^3*qsumk2*x + 2780*L^4*qsumk1*x + 600*L^4*qsumk2*x - 400*L^5*qsumk1*x - 60*L^5*qsumk2*x + 20*L^6*qsumk1*x))/(2*(L - 1)^4*((x^2*(L - x)^2*(- k^2 + k + qsum)^2)/(L - 1)^2)^(3/2)*(L^5 - 28*L^4 + 303*L^3 - 1568*L^2 + 3812*L - 3360))
}
else{
result = -(x^2*(L - x)^2*(- k^2 + k + qsum)^2*(4*k^2*x^2 - L^2*k + L^3*k - L^2*qsum + L^3*qsum - 12*k*x^2 - 4*qsumk*x^2 + L^2*k^2 - L^3*k^2 - 6*L*k^2*x^2 + 6*L^2*k^2*x + 12*L*k*x + 4*L*qsumk*x + 10*L*k*x^2 - 4*L*k^2*x - 10*L^2*k*x + 2*L*qsum*x^2 - 2*L^2*qsum*x + 4*L*qsumk*x^2 - 4*L^2*qsumk*x))/(2*(L - 1)^4*(L - 2)*((x^2*(L - x)^2*(- k^2 + k + qsum)^2)/(L - 1)^2)^(3/2))
}
return(result)
}
T3.lambda = function(b, n0, n1, L, k, psum, qsum, psumk, qsumk){
C3 = C1_Z(n0:n1,L,k,psum,qsum)
C4 = C2_Z(n0:n1,L,k,psum,qsum,psumk,qsumk)
dnorm(b)*b^3*sum(C3*C4*Nu(sqrt(2*C3*b^2))*Nu(sqrt(2*C4*b^2)))
}
T3.lambdaZw = function(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp){
if(asymp==TRUE){
C1 = C1_w_asy((n0:n1)/L)
C2 = C2_w_asy((n0:n1)/L,k,psum,psumk1)
C2[C2<0] = 0.00000001
}
if(asymp==FALSE){
C1 = C1_w(n0:n1,L,k,psum,qsum)
C2 = C2_w(n0:n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1, psumk2,qsumk2)
C2[C2<0] = 0.00000001
}
dnorm(b)*b^3*sum(C1*C2*Nu(sqrt(2*C1*b^2))*Nu(sqrt(2*C2*b^2)))
}
T3.lambdaZdiff = function(b,n0,n1,L,k,psum,qsum,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp){
if(asymp==TRUE){
C1 = C1_d_asy((n0:n1)/L)
C2 = C2_d_asy((n0:n1)/L,k,qsum,qsumk1)
C2[C2<0] = 0.00000001
}
if(asymp==FALSE){
C1 =C1_d(n0:n1,L,k,qsum)
C2 =C2_d(n0:n1,L,k,psum,qsum,qsumk,psumk1,qsumk1,psumk2,qsumk2)
C2[C2<0] = 0.00000001
}
nu1 = Nu(sqrt(2*C1*b^2))
nu2 = Nu(sqrt(2*C2*b^2))
nu1[is.na(nu1)]=0
nu2[is.na(nu2)]=0
dnorm(b)*b^3*sum(C1*C2*Nu(sqrt(2*C1*b^2))*Nu(sqrt(2*C2*b^2)))
}
T3.lambdaM = function(D,b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,asymp){
pval_Zd = T3.lambdaZdiff(b,n0,n1,L,k,psum,qsum,qsumk,psumk1,qsumk1,psumk2, qsumk2,asymp)
pval_Zw = T3.lambdaZw(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)
return(1-(1-D*2*pval_Zd)*(1-D*pval_Zw))
}
T3.lambdaS = function(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp){
integrand = function(t,w){
if(asymp==TRUE){
C1w = C1_w_asy(t/L)
C2w = C2_w_asy(t/L,k,psum,psumk1)
C1d =C1_d_asy(t/L)
C2d = C2_d_asy(t/L,k,qsum,qsumk1)
C1d[C1d<0]=0
C2d[C2d<0]=0
C1w[C1w<0]=0
C2w[C2w<0]=0
}
if(asymp==FALSE){
C1w = C1_w(t,L,k,psum,qsum)
C2w = C2_w(t,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2)
C1d =C1_d(t,L,k,qsum)
C2d = C2_d(t,L,k,psum,qsum,qsumk,psumk1,qsumk1, psumk2 ,qsumk2)
C1d[C1d<0]=0
C2d[C2d<0]=0
C1w[C1w<0]=0
C2w[C2w<0]=0
}
nu1 = Nu(sqrt(2*b*(C1d*cos(w)^2+C1w*sin(w)^2)))
nu2 = Nu(sqrt(2*b*(C2d*cos(w)^2+C2w*sin(w)^2)))
(4*(C1d*cos(w)^2+C1w*sin(w)^2)*(C2d*cos(w)^2+C2w*sin(w)^2)*b^2*nu1*nu2)/(2*pi)
}
integrand0 = function(t) {integrate(integrand,0,2*pi,t=t,subdivisions=3000, stop.on.error=FALSE)$value}
result=Vectorize(integrand0)
dchisq(b,2)*integrate(result, n0, n1, subdivisions=3000, stop.on.error=FALSE)$value
}
EX3_new.f = function(t, n, k, psum, deg.sumsq, deg.sum3, daa, dda, aaa1, aaa2){
x1 = 2*k*n+6*k*n*psum/k
x2 = 3*k^2*n+deg.sumsq+2*k*n*psum+2*daa-x1
x3 = 4*k^2*n^2*(1+psum/k)-4*(3*k^2*n+deg.sumsq+2*k^2*n*psum/k+2*daa)+2*(2*k*n+6*k*n*psum/k)
x4 = 4*k^3*n+3*k*deg.sumsq+deg.sum3-3*(3*k^2*n+deg.sumsq+2*k^2*n*psum/k+2*daa)+2*(2*k*n+6*k*n*psum/k)
x5 = 4*k^3*n+2*k*deg.sumsq+2*dda-2*(3*k^2*n+deg.sumsq+2*k^2*n*psum/k+2*daa)+x1-2*aaa1-6*aaa2
x6 = 2*aaa1+6*aaa2
x7 = 2*k*n*(3*k^2*n+deg.sumsq)-4*k^2*n^2*(1+psum/k) - 4*(4*k^3*n+2*k*deg.sumsq+2*dda-(3*k^2*n+deg.sumsq+2*k^2*n*psum/k+2*daa))-2*(4*k^3*n+3*k*deg.sumsq+deg.sum3-(3*k^2*n+deg.sumsq+2*k^2*n*psum/k+2*daa))+ 4*((3*k^2*n+deg.sumsq+2*k^2*n*psum/k+2*daa)-(2*k*n+6*k*n*psum/k))+2*x6
x8 = 8*k^3*n^3-4*x1-24*x2-6*x3-8*x4-24*x5-8*x6-12*x7
p1 = t*(t-1)/n/(n-1)
p2 = t*(t-1)*(t-2)/n/(n-1)/(n-2)
p3 = t*(t-1)*(t-2)*(t-3)/(n*(n-1)*(n-2)*(n-3))
p4 = p5 = t*(t-1)*(t-2)*(t-3)/(n*(n-1)*(n-2)*(n-3))
p6 = p2
p7 = t*(t-1)*(t-2)*(t-3)*(t-4)/(n*(n-1)*(n-2)*(n-3)*(n-4))
p8 = t*(t-1)*(t-2)*(t-3)*(t-4)*(t-5)/(n*(n-1)*(n-2)*(n-3)*(n-4)*(n-5))
q1 = (n-t)*(n-t-1)/n/(n-1)
q2 = (n-t)*(n-t-1)*(n-t-2)/n/(n-1)/(n-2)
q3 = (n-t)*(n-t-1)*(n-t-2)*(n-t-3)/(n*(n-1)*(n-2)*(n-3))
q4 = q5 = q3
q6 = q2
q7 = (n-t)*(n-t-1)*(n-t-2)*(n-t-3)*(n-t-4)/(n*(n-1)*(n-2)*(n-3)*(n-4))
q8 = (n-t)*(n-t-1)*(n-t-2)*(n-t-3)*(n-t-4)*(n-t-5)/(n*(n-1)*(n-2)*(n-3)*(n-4)*(n-5))
A11 = 4*x1*p1 + 24*x2*p2 + 6*x3*p3 + 8*x4*p4 + 24*x5*p5 + 8*x6*p6 + 12*x7*p7 + x8*p8
A12 = 2*x3*t*(t-1)*(n-t)*(n-t-1)/(n*(n-1)*(n-2)*(n-3)) + 4*x7*t*(t-1)*(t-2)*(n-t)*(n-t-1)/(n*(n-1)*(n-2)*(n-3)*(n-4)) + x8*t*(t-1)*(t-2)*(t-3)*(n-t)*(n-t-1)/(n*(n-1)*(n-2)*(n-3)*(n-4)*(n-5))
A21 = 2*x3*t*(t-1)*(n-t)*(n-t-1)/(n*(n-1)*(n-2)*(n-3)) + 4*x7*(n-t)*(n-t-1)*(n-t-2)*(t)*(t-1)/(n*(n-1)*(n-2)*(n-3)*(n-4)) + x8*(n-t)*(n-t-1)*(n-t-2)*(n-t-3)*(t)*(t-1)/(n*(n-1)*(n-2)*(n-3)*(n-4)*(n-5))
A22 = 4*x1*q1 + 24*x2*q2 + 6*x3*q3 + 8*x4*q4 + 24*x5*q5 + 8*x6*q6 + 12*x7*q7 + x8*q8
q = (n-t-1)/(n-2)
p = (t-1)/(n-2)
ERw3 = q^3*A11 + 3*q^2*p*A12 + 3*q*p^2*A21 + p^3*A22
ERd3 = A11 - 3*A12 + 3*A21 - A22
list(A11=A11, A12=A12, A21=A21, A22=A22, ERw3=ERw3, ERd3=ERd3)
}
EX3.f = function(n, t, k, vn, deg.sumsq, deg.sum3, daa, dda, aaa1, aaa2){
x1 = 2*k*n+6*k*n*vn
x2 = 3*k^2*n+deg.sumsq+2*k^2*n*vn+2*daa-x1
x3 = 4*k^2*n^2*(1+vn)-4*(3*k^2*n+deg.sumsq+2*k^2*n*vn+2*daa)+2*(2*k*n+6*k*n*vn)
x4 = 4*k^3*n+3*k*deg.sumsq+deg.sum3-3*(3*k^2*n+deg.sumsq+2*k^2*n*vn+2*daa)+2*(2*k*n+6*k*n*vn)
x5 = 4*k^3*n+2*k*deg.sumsq+2*dda-2*(3*k^2*n+deg.sumsq+2*k^2*n*vn+2*daa)+x1-2*aaa1-6*aaa2
x6 = 2*aaa1+6*aaa2
x7 = 2*k*n*(3*k^2*n+deg.sumsq)-4*k^2*n^2*(1+vn) - 4*(4*k^3*n+2*k*deg.sumsq+2*dda-(3*k^2*n+deg.sumsq+2*k^2*n*vn+2*daa))-2*(4*k^3*n+3*k*deg.sumsq+deg.sum3-(3*k^2*n+deg.sumsq+2*k^2*n*vn+2*daa))+ 4*((3*k^2*n+deg.sumsq+2*k^2*n*vn+2*daa)-(2*k*n+6*k*n*vn))+2*x6
x8 = 8*k^3*n^3-4*x1-24*x2-6*x3-8*x4-24*x5-8*x6-12*x7
p1 = 2*t*(n-t)/n/(n-1)
p2 = p1/2
p3 = 4*t*(t-1)*(n-t)*(n-t-1)/(n*(n-1)*(n-2)*(n-3))
p4 = t*(n-t)*((n-t-1)*(n-t-2)+(t-1)*(t-2))/(n*(n-1)*(n-2)*(n-3))
p5 = p7 = p3/2
p8 = 8*t*(t-1)*(t-2)*(n-t)*(n-t-1)*(n-t-2)/(n*(n-1)*(n-2)*(n-3)*(n-4)*(n-5))
4*x1*p1 + 24*x2*p2 + 6*x3*p3 + 8*x4*p4 + 24*x5*p5 + 12*x7*p7 + x8*p8
}
ERw = function(n,t,k){
q=(n-t-1)/(n-2)
p=(t-1)/(n-2)
ER1 = 2*k*t*(t-1)/(n-1)
ER2 = 2*k*(n-t)*(n-t-1)/(n-1)
result = q*ER1 + p*ER2
return(result)
}
ERd = function(n,t,k){
result = 2*k*t*(t-1)/(n-1)- 2*k*(n-t)*(n-t-1)/(n-1)
return(result)
}
varRw = function(n,t,k,psum,deg.sumsq){
vn= psum/k
config1 = (2*k*n + 2*k*n*vn)
config2 = (3*k^2*n + deg.sumsq -2*k*n -2*k*n*vn)
config3 = (4*n^2*k^2 + 4*k*n + 4*k*n*vn - 12*k^2*n - 4*deg.sumsq)
f11 = 2*(t)*(t-1)/n/(n-1)
f21 = 4*(t)*(t-1)*(t-2)/n/(n-1)/(n-2)
f31 = (t)*(t-1)*(t-2)*(t-3)/n/(n-1)/(n-2)/(n-3)
V1 = config1*f11 + config2*f21 + config3*f31 - (2*k*t*(t-1)/(n-1))^2
f12 = 2*(n-t)*(n-t-1)/n/(n-1)
f22 = 4*(n-t)*(n-t-1)*(n-t-2)/n/(n-1)/(n-2)
f32 = (n-t)*(n-t-1)*(n-t-2)*(n-t-3)/n/(n-1)/(n-2)/(n-3)
V2 = config1*f12 + config2*f22 + config3*f32 - (2*k*(n-t)*(n-t-1)/(n-1))^2
P3 = (t*(t-1)*(n-t)*(n-t-1))/(n*(n-1)*(n-2)*(n-3))
V12 = config3*P3 - (2*k*t*(t-1)/(n-1))*(2*k*(n-t)*(n-t-1)/(n-1))
q=(n-t-1)/(n-2)
p=(t-1)/(n-2)
result = q^2*V1 + p^2*V2 + 2*p*q*V12
return(result)
}
varRd = function(n,t,k,psum,deg.sumsq){
vn= psum/k
config1 = (2*k*n + 2*k*n*vn)
config2 = (3*k^2*n + deg.sumsq -2*k*n -2*k*n*vn)
config3 = (4*n^2*k^2 + 4*k*n + 4*k*n*vn - 12*k^2*n - 4*deg.sumsq)
f11 = 2*(t)*(t-1)/n/(n-1)
f21 = 4*(t)*(t-1)*(t-2)/n/(n-1)/(n-2)
f31 = (t)*(t-1)*(t-2)*(t-3)/n/(n-1)/(n-2)/(n-3)
V1 = config1*f11 + config2*f21 + config3*f31 - (2*k*t*(t-1)/(n-1))^2
f12 = 2*(n-t)*(n-t-1)/n/(n-1)
f22 = 4*(n-t)*(n-t-1)*(n-t-2)/n/(n-1)/(n-2)
f32 = (n-t)*(n-t-1)*(n-t-2)*(n-t-3)/n/(n-1)/(n-2)/(n-3)
V2 = config1*f12 + config2*f22 + config3*f32 - (2*k*(n-t)*(n-t-1)/(n-1))^2
P3 = (t*(t-1)*(n-t)*(n-t-1))/(n*(n-1)*(n-2)*(n-3))
V12 = config3*P3 - (2*k*t*(t-1)/(n-1))*(2*k*(n-t)*(n-t-1)/(n-1))
result = V1 + V2 - 2*V12
return(result)
}
varR = function(n,t,k,psum,qsum){
vn=psum/k
cn=(qsum+k-k^2)/k
h = 4*(t-1)*(n-t-1)/(n-2)/(n-3)
4*k*t*(n-t)/(n-1)*(h*(1+vn-2*k/(n-1))+(1-h)*cn)
}
T3.skewed.lambda = function(b, n0, n1, L, k, psum, qsum, psumk, qsumk, deg.sumsq, deg.sum3, aaa1, aaa2, daa, dda){
C3 = C1_Z(n0:n1,L,k,psum,qsum)
C4 = C2_Z(n0:n1,L,k,psum,qsum,psumk,qsumk)
n = L
ts = 1:(n-1)
vn=psum/k
EX = 4*k*ts*(n-ts)/(n-1)
EX2 = 4*k*(1+vn)*2*ts*(n-ts)/(n-1) + 4*(3*k^2*n+deg.sumsq-2*k*n*(1+vn))*ts*(n-ts)/n/(n-1) + (4*k^2*n^2-4*(3*k^2*n+deg.sumsq)+4*k*n*(1+vn))*4*ts*(ts-1)*(n-ts)*(n-ts-1)/(n*(n-1)*(n-2)*(n-3))
EX3 = EX3.f(n,ts,k,vn, deg.sumsq,deg.sum3,daa,dda,aaa1,aaa2)
VX = EX2-EX^2
gamma = -(EX3-3*EX*VX-EX^3)/(VX^(3/2))
theta = rep(0,n-1)
pos = which(1+2*gamma*b>0)
theta[pos] = (sqrt((1+2*gamma*b)[pos])-1)/gamma[pos]
S = (1+gamma*theta)^(-1/2)*exp((b-theta)^2/2 + gamma*theta^3/6)
nn = n-length(pos)
if (nn>0.75*n){
print("Not enough points for extrapolation!")
return(0)
}
if (nn>=2*n0){
neg = which(1+2*gamma*b<=0)
dif = neg[2:nn]-neg[1:(nn-1)]
id1 = which.max(dif)
if (nn<n){
id2 = id1 + ceiling(0.02*n)
id3 = id2 + ceiling(0.02*n)
inc = (S[id3]-S[id2])/(id3-id2)
S[id2:1] = S[id2+1]-inc*(1:id2)
S[(n-id2):(n-1)] = S[id2:1]
}else{
ymax = S[ceiling(n/2)]
id = id1+0.05*n
a = (ymax-S[id])/(id-n/2)^2
S[1:id] = ymax-a*((1:id)-n/2)^2
S[(n-id):(n-1)] = S[id:1]
}
neg2 = which(S<0)
S[neg2] = 0
}
dnorm(b)*b^3*sum(S[(n-n0):(n-n1)]*C3*C4*Nu(sqrt(2*C3*b^2))*Nu(sqrt(2*C4*b^2)))
}
T3.skewed.lambdaZw = function(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1, psumk2, qsumk2, deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda){
C1 = C1_w(n0:n1,L,k,psum,qsum)
C2 = C2_w(n0:n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1, psumk2,qsumk2 )
n = L
ts = 1:(n-1)
C2[C2<0] = 0.00000001
EX = ERw(L,ts,k)
EX3 = EX3_new.f(ts, L, k, psum, deg.sumsq, deg.sum3, daa, dda, aaa1, aaa2)$ERw3
VX = varRw(L,ts,k,psum,deg.sumsq)
gamma = (EX3-3*EX*VX-EX^3)/(VX^(3/2))
theta = rep(0,n-1)
pos = which(1+2*gamma*b>0)
theta[pos] = (sqrt((1+2*gamma*b)[pos])-1)/gamma[pos]
S = (1+gamma*theta)^(-1/2)*exp((b-theta)^2/2 + gamma*theta^3/6)
nn = n-length(pos)
if (nn>0.75*n){
print("Not enough points for extrapolation!")
return(0)
}
if (nn>=(n0-1)+(n-n0)){
neg = which(1+2*gamma*b<=0)
dif = neg[2:nn]-neg[1:(nn-1)]
id1 = which.max(dif)
id2 = id1 + ceiling(0.03*n)
id3 = id2 + ceiling(0.09*n)
inc = (S[id3]-S[id2])/ceiling(0.09*n)
S[id2:1] = S[id2+1]-inc*(1:id2)
S[(n/2+1):n] = S[(n/2):1]
neg2 = which(S<0)
S[neg2] = 0
}
dnorm(b)*b^3*sum(S[(n-n0):(n-n1)]*C1*C2*Nu(sqrt(2*C1*b^2))*Nu(sqrt(2*C2*b^2)))
}
T3.skewed.lambdaZd = function(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,deg.sumsq,deg.sum3,aaa1,aaa2,daa,dda){
C1 = C1_d(n0:n1,L,k,qsum)
C2 = C2_d(n0:n1,L,k,psum,qsum,qsumk,psumk1,qsumk1,psumk2,qsumk2)
C1[C1<0] = 0.0001
C2[C2<0] = 0.0001
n = L
ts = 1:(n-1)
EX = ERd(L,ts,k)
EX3 = EX3_new.f(ts, L, k, psum, deg.sumsq, deg.sum3, daa, dda, aaa1, aaa2)$ERd3
VX = varRd(L,ts,k,psum,deg.sumsq)
gamma = (EX3-3*EX*VX-EX^3)/(VX^(3/2))
theta = rep(0,n-1)
pos = which(1+2*gamma*b>0)
theta[pos] = (sqrt((1+2*gamma*b)[pos])-1)/gamma[pos]
S = (1+gamma*theta)^(-1/2)*exp((b-theta)^2/2 + gamma*theta^3/6)
S[n/2]=S[n/2-1]
nn = n-length(pos)
nn.l = ceiling(n/2)-length(which(1+2*gamma[1:ceiling(n/2)]*b>0))
nn.r = ceiling(n/2)-length(which(1+2*gamma[ceiling(n/2+1):n]*b>0))
if (nn>0.75*n){
print("Not enough points for extrapolation!")
return(0)
}
if (nn.r>=(n-n1)){
neg = which(1+2*gamma[ceiling(n/2+1):(n-1)]*b<=0)
id1 = neg[1]+ceiling(n/2)-1
id2 = id1 - ceiling(0.06*n)
id3 = id2 - ceiling(0.06*n)
inc = (S[id3]-S[id2])/(id3-id2)
S[id2:n] = S[id2]+inc*((id2:n)-id2)+inc^2*((id2:n)-id2)+inc^3*((id2:n)-id2)
if(n0<=0.15*200){
S[S<0]=0
}
}
dnorm(b)*b^3*sum(S[(n-n0):(n-n1)]*C1*C2*Nu(sqrt(2*C1*b^2))*Nu(sqrt(2*C2*b^2)))
}
T3.skewed.lambdaM = function(D,b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda){
pval_Zd = T3.skewed.lambdaZd(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)
pval_Zw = T3.skewed.lambdaZw(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)
return(1-(1-D*2*pval_Zd)*(1-D*pval_Zw))
}
getbZ = function(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda,bmin=3,bmax=5,skew.corr=FALSE,dif=1e-10, nIterMax=100){
m0=ARL*alpha
if(skew.corr==FALSE){
pm = T3.lambda(bmin,n0,n1,L,k,psum,qsum,psumk,qsumk)*m0
while (pm<alpha){
bmin = bmin-1
pm = T3.lambda(bmin,n0,n1,L,k,psum,qsum,psumk,qsumk)*m0
}
pM = T3.lambda(bmax,n0,n1,L,k,psum,qsum,psumk,qsumk)*m0
while (pM>alpha){
bmax = bmax+1
pM = T3.lambda(bmax,n0,n1,L,k,psum,qsum,psumk,qsumk)*m0
}
b = (bmin+bmax)/2
p = T3.lambda(b,n0,n1,L,k,psum,qsum,psumk,qsumk)*m0
nIter = 1
while (abs(p-alpha)>dif && nIter<nIterMax){
if (p<alpha){
bmax = b
}else{
bmin = b
}
b = (bmin+bmax)/2
p = T3.lambda(b,n0,n1,L,k,psum,qsum,psumk,qsumk)*m0
nIter = nIter + 1
}
return(b)
}else{
pm = T3.skewed.lambda(bmin,n0, n1, L, k, psum, qsum, psumk, qsumk, deg.sumsq, deg.sum3, aaa1,aaa2, daa, dda)*m0
while (pm<alpha){
bmin = bmin-1
pm = T3.skewed.lambda(bmin,n0, n1, L, k, psum, qsum, psumk, qsumk, deg.sumsq, deg.sum3, aaa1, aaa2, daa, dda)*m0
}
pM = T3.skewed.lambda(bmax,n0, n1, L, k, psum, qsum, psumk, qsumk, deg.sumsq, deg.sum3, aaa1,aaa2, daa, dda)*m0
while (pM>alpha){
bmax = bmax+1
pM = T3.skewed.lambda(bmax,n0, n1, L, k, psum, qsum, psumk, qsumk, deg.sumsq, deg.sum3, aaa1,aaa2, daa, dda)*m0
}
b = (bmin+bmax)/2
p = T3.skewed.lambda(b,n0, n1, L, k, psum, qsum, psumk, qsumk, deg.sumsq, deg.sum3, aaa1,aaa2, daa, dda)*m0
nIter = 1
while (abs(p-alpha)>dif && nIter<nIterMax){
if (p<alpha){
bmax = b
}else{
bmin = b
}
b = (bmin+bmax)/2
p = T3.skewed.lambda(b,n0, n1, L, k, psum, qsum, psumk, qsumk, deg.sumsq, deg.sum3, aaa1,aaa2, daa, dda)*m0
nIter = nIter + 1
}
return(b)
}
}
getbZw = function(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda, bmin=3,bmax=5,skew.corr=FALSE,dif=1e-10, nIterMax=100,asymp){
m0=ARL*alpha
if(skew.corr==FALSE){
pm = T3.lambdaZw(bmin,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
while (pm<alpha){
bmin = bmin-1
pm = T3.lambdaZw(bmin,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
}
pM = T3.lambdaZw(bmax,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
while (pM>alpha){
bmax = bmax+1
pM = T3.lambdaZw(bmax,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
}
b = (bmin+bmax)/2
p = T3.lambdaZw(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
nIter = 1
while (abs(p-alpha)>dif && nIter<nIterMax){
if (p<alpha){
bmax = b
}else{
bmin = b
}
b = (bmin+bmax)/2
p = T3.lambdaZw(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
nIter = nIter + 1
}
return(b)
}else{
pm = T3.skewed.lambdaZw(bmin,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1, psumk2, qsumk2, deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)*m0
while (pm<alpha){
bmin = bmin-1
pm = T3.skewed.lambdaZw(bmin,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1, psumk2, qsumk2, deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)*m0
}
pM = T3.skewed.lambdaZw(bmax,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1, psumk2, qsumk2, deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)*m0
while (pM>alpha){
bmax = bmax+1
pM = T3.skewed.lambdaZw(bmax,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1, psumk2, qsumk2, deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)*m0
}
b = (bmin+bmax)/2
p = T3.skewed.lambdaZw(b,n0,n1,L,k,psum,qsum,psumk1,psumk,qsumk,qsumk1, psumk2, qsumk2, deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)*m0
nIter = 1
while (abs(p-alpha)>dif && nIter<nIterMax){
if (p<alpha){
bmax = b
}else{
bmin = b
}
b = (bmin+bmax)/2
p = T3.skewed.lambdaZw(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1, psumk2, qsumk2, deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)*m0
nIter = nIter + 1
}
return(b)
}
}
getbS = function(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda,bmin=3,bmax=5,skew.corr=FALSE,dif=1e-10, nIterMax=100,asymp){
m0=ARL*alpha
pm = T3.lambdaS(bmin,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
while (pm<alpha){
bmin = bmin-1
pm = T3.lambdaS(bmin,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
}
pM = T3.lambdaS(bmax,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
while (pM>alpha){
bmax = bmax+1
pM = T3.lambdaS(bmax,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
}
b = (bmin+bmax)/2
p = T3.lambdaS(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
nIter = 1
while (abs(p-alpha)>dif && nIter<nIterMax){
if (p<alpha){
bmax = b
}else{
bmin = b
}
b = (bmin+bmax)/2
p = T3.lambdaS(b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,asymp)*m0
nIter = nIter + 1
}
b
}
getbM = function(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda,bmin=3,bmax=21,skew.corr=FALSE,dif=1e-10, nIterMax=100,asymp){
m0=ARL*alpha
if(skew.corr==FALSE){
pm = T3.lambdaM(m0,bmin,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,asymp)
while (pm<alpha){
bmin = bmin-1
pm = T3.lambdaM(m0,bmin,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,asymp)
}
pM = T3.lambdaM(m0,bmax,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,asymp)
while (pM>alpha){
bmax = bmax+1
pM = T3.lambdaM(m0,bmax,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,asymp)
}
b = (bmin+bmax)/2
p = T3.lambdaM(m0,b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,asymp)
nIter = 1
while (abs(p-alpha)>dif && nIter<nIterMax){
if (p<alpha){
bmax = b
}else{
bmin = b
}
b = (bmin+bmax)/2
p = T3.lambdaM(m0,b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,asymp)
nIter = nIter + 1
}
return(b)
}else{
pm = T3.skewed.lambdaM(m0,bmin,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)
while (pm<alpha){
bmin = bmin-1
pm = T3.skewed.lambdaM(m0,bmin,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)
}
pM = T3.skewed.lambdaM(m0,bmax,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)
while (pM>alpha){
bmax = bmax+1
pM = T3.skewed.lambdaM(m0,bmax,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)
}
b = (bmin+bmax)/2
p = T3.skewed.lambdaM(m0,b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)
nIter = 1
while (abs(p-alpha)>dif && nIter<nIterMax){
if (p<alpha){
bmax = b
}else{
bmin = b
}
b = (bmin+bmax)/2
p = T3.skewed.lambdaM(m0,b,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2, qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda)
nIter = nIter + 1
}
return(b)
}
}
getb = function(distM,ARL,alpha,N0,n0,n1,L,k,statistics,skew.corr,dif=1e-10, nIterMax=100,asymp){
quantities = gb_quantities(distM,N0,k)
psum = quantities$psum
qsum = quantities$qsum
psumk = quantities$psumk
qsumk = quantities$qsumk
psumk1 = quantities$psumk1
qsumk1 = quantities$qsumk1
psumk2 = quantities$psumk2
qsumk2 = quantities$qsumk2
deg.sumsq = quantities$deg.sumsq
deg.sum3 = quantities$deg.sum3.n
aaa1 = quantities$aaa1.n
aaa2 = quantities$aaa2.n
dda = quantities$dda.n
daa = quantities$daa.n
output=list()
if (skew.corr==FALSE){
if (length(which(!is.na(match(c("o","ori","original","all"), statistics))))>0){
output$ori = getbZ(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda,bmin=3,bmax=5,skew.corr=FALSE,dif=1e-10, nIterMax=100)
}
if (length(which(!is.na(match(c("w","weighted","all"), statistics))))>0){
output$weighted = getbZw(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda, bmin=3,bmax=5,skew.corr=FALSE,dif=1e-10, nIterMax=100,asymp)
}
if (length(which(!is.na(match(c("m","max","all"), statistics))))>0){
output$max.type = getbM(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda,bmin=7,bmax=21,skew.corr=FALSE,dif=1e-10, nIterMax=100,asymp)
}
if (length(which(!is.na(match(c("g","generalized","all"), statistics))))>0){
output$generalized = getbS(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda,bmin=20,bmax=30,skew.corr=FALSE,dif=1e-10, nIterMax=100,asymp)
}
return(output)
}
if (length(which(!is.na(match(c("o","ori","original","all"), statistics))))>0){
output$ori = getbZ(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda,bmin=3,bmax=5,skew.corr=TRUE)
}
if (length(which(!is.na(match(c("w","weighted","all"), statistics))))>0){
output$weighted = getbZw(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda,bmin=3,bmax=5,skew.corr=TRUE,dif=1e-10, nIterMax=100,asymp)
}
if (length(which(!is.na(match(c("m","max","all"), statistics))))>0){
output$max.type = getbM(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda,bmin=8,bmax=20,skew.corr=TRUE,dif=1e-10, nIterMax=100,asymp)
}
if (length(which(!is.na(match(c("g","generalized","all"), statistics))))>0){
output$generalized = getbS(ARL,alpha,n0,n1,L,k,psum,qsum,psumk,qsumk,psumk1,qsumk1,psumk2,qsumk2,deg.sumsq,deg.sum3, aaa1,aaa2,daa,dda,bmin=20,bmax=30,skew.corr=TRUE,dif=1e-10, nIterMax=100,asymp)
}
return(output)
}
|
test_that("Testing multivariate distributions", {
skip_on_cran()
expect_true(all.equal(rowSums(rmnom(5000, 50, c(2/10, 5/10, 3/10))), rep(50, 5000)))
expect_true(all.equal(rowSums(rdirichlet(5000, c(2/10, 5/10, 3/10))), rep(1.0, 5000)))
xx <- expand.grid(0:20, 0:20, 0:20)
expect_equal(sum(ddirmnom(xx[rowSums(xx) == 20,], 20, c(2, 5, 3))), 1)
expect_equal(sum(dmnom(xx[rowSums(xx) == 20,], 20, c(2/10, 5/10, 3/10))), 1)
expect_equal(sum(dmvhyper(xx[rowSums(xx) == 35,], c(20, 20, 20), 35)), 1)
p <- c(4, 5, 1, 6, 2)
expect_equal(prop.table(colSums(rmnom(1e5, 100, p/sum(p)))),
p/sum(p),
tolerance = 1e-2)
expect_equal(as.numeric(prop.table(table(rcat(1e5, p/sum(p))))),
p/sum(p),
tolerance = 1e-2)
expect_equal(prop.table(colSums(rdirichlet(1e5, p))),
p/sum(p),
tolerance = 1e-2)
expect_equal(prop.table(colSums(rdirmnom(1e5, 100, p))),
p/sum(p),
tolerance = 1e-2)
n <- c(11, 24, 43, 7, 56)
expect_equal(prop.table(colSums(rmvhyper(1e5, n, 100))),
n/sum(n),
tolerance = 1e-2)
})
test_that("Evaluate wrong parameters first", {
expect_warning(expect_true(is.nan(dbvpois(-1, -1, -1, 1, 1))))
expect_warning(expect_true(is.nan(ddirichlet(c(2, 2), c(-1, 0.5)))))
expect_warning(expect_true(is.nan(ddirmnom(c(-1, 1, 1), 1.5, c(1, 1, 1)))))
expect_warning(expect_true(is.nan(dmnom(c(-1, 1, 1), 1.5, c(1/3, 1/3, 1/3)))))
expect_warning(expect_true(is.nan(dmvhyper(c(-1, 2, 2), c(2,3,4), -5))))
})
test_that("Check if rmnom and rdirmnom deal with underflow (
skip_on_cran()
expect_false(anyNA(rmnom(5000, 100, c(0.504115095275327, 2.669522645838e-39, 0, 2.58539638831141, 0))))
expect_false(anyNA(rdirmnom(5000, 100, c(1.480592e+00, 1.394943e-03, 4.529932e-06, 3.263573e+00, 4.554952e-06))))
p <- c(0, 0, 1, 0, 2.77053929981958e-18)
expect_false(anyNA(rmnom(5000, 100, p)))
expect_false(anyNA(rdirmnom(5000, 100, p + 1e-5)))
})
|
require(tcltk) || stop("tcltk support is absent")
require(graphics); require(stats)
local({
have_ttk <- as.character(tcl("info", "tclversion")) >= "8.5"
if(have_ttk) {
tkbutton <- ttkbutton
tkframe <- ttkframe
tklabel <- ttklabel
tkradiobutton <- ttkradiobutton
}
y <- NULL
xlim <- NULL
size <- tclVar(50)
dist <- tclVar(1)
kernel<- tclVar("gaussian")
bw <- tclVar(1)
bw.sav <- 1
replot <- function(...) {
if (is.null(y)) return()
bw.sav <<- b <- as.numeric(tclObj(bw))
k <- as.character(tclObj(kernel))
sz <- as.numeric(tclObj(size))
eval(substitute(plot(density(y, bw=b, kernel=k),xlim=xlim)))
points(y,rep(0,sz))
}
replot.maybe <- function(...)
{
if (as.numeric(tclObj(bw)) != bw.sav) replot()
}
regen <- function(...) {
if (tclvalue(dist)=="1") y<<-rnorm(as.numeric(tclObj(size)))
else y<<-rexp(as.numeric(tclObj(size)))
xlim <<- range(y) + c(-2,2)
replot()
}
grDevices::devAskNewPage(FALSE)
tclServiceMode(FALSE)
base <- tktoplevel()
tkwm.title(base, "Density")
spec.frm <- tkframe(base,borderwidth=2)
left.frm <- tkframe(spec.frm)
right.frm <- tkframe(spec.frm)
frame1 <- tkframe(left.frm, relief="groove", borderwidth=2)
tkpack(tklabel(frame1, text="Distribution"))
tkpack(tkradiobutton(frame1, command=regen, text="Normal",
value=1, variable=dist), anchor="w")
tkpack(tkradiobutton(frame1, command=regen, text="Exponential",
value=2, variable=dist), anchor="w")
frame2 <- tkframe(left.frm, relief="groove", borderwidth=2)
tkpack(tklabel(frame2, text="Kernel"))
for ( i in c("gaussian", "epanechnikov", "rectangular",
"triangular", "cosine") ) {
tmp <- tkradiobutton(frame2, command=replot,
text=i, value=i, variable=kernel)
tkpack(tmp, anchor="w")
}
frame3 <-tkframe(right.frm, relief="groove", borderwidth=2)
tkpack(tklabel(frame3, text="Sample size"))
for ( i in c(50,100,200,300) ) {
tmp <- tkradiobutton(frame3, command=regen,
text=i,value=i,variable=size)
tkpack(tmp, anchor="w")
}
frame4 <-tkframe(right.frm, relief="groove", borderwidth=2)
tkpack(tklabel (frame4, text="Bandwidth"))
tkpack(tkscale(frame4, command=replot.maybe, from=0.05, to=2.00,
showvalue=FALSE, variable=bw,
resolution=0.05, orient="horiz"))
tkpack(frame1, frame2, fill="x")
tkpack(frame3, frame4, fill="x")
tkpack(left.frm, right.frm,side="left", anchor="n")
q.but <- tkbutton(base,text="Quit",
command=function() tkdestroy(base))
tkpack(spec.frm, q.but)
tclServiceMode(TRUE)
cat("******************************************************\n",
"The source for this demo can be found in the file:\n",
file.path(system.file(package = "tcltk"), "demo", "tkdensity.R"),
"\n******************************************************\n")
regen()
})
|
NULL
prior_pred <- function(model,
verbose = TRUE,
quiet = FALSE,
refresh = 0,
STREAM = get_stream(),
...) {
check_type(model, "lgpmodel")
if (quiet) verbose <- FALSE
log_progress("Sampling from parameter prior...", verbose)
stan_fit <- sample_param_prior(
model,
verbose = verbose,
quiet = quiet,
refresh = refresh,
...
)
log_progress("Drawing from GP priors conditional on parameters...", verbose)
f_draws <- draw_f_prior(model, stan_fit, verbose, STREAM)
log_progress("Drawing from prior predictive distribution...", verbose)
draw_prior_pred(model, stan_fit, f_draws, verbose)
}
sample_param_prior <- function(model, verbose = TRUE, quiet = FALSE, ...) {
check_type(model, "lgpmodel")
if (quiet) verbose <- FALSE
object <- dollar(stanmodels, "parameter_prior")
data <- model@stan_input
rstan::sampling(
object = object,
data = data,
check_data = TRUE,
...
)
}
draw_prior_pred <- function(model, stan_fit, f_draws, verbose) {
f_sum_draws <- dollar(f_draws, "f_draws")
c_hat <- get_chat(model)
h <- map_f_to_h(model, f_sum_draws, c_hat, reduce = NULL)
pred_draws <- new("Prediction",
f_comp = dollar(f_draws, "f_draws_comp"),
f = f_sum_draws,
h = h,
x = dollar(f_draws, "x"),
extrapolated = FALSE
)
y_draws <- draw_pred.subroutine(model, stan_fit, pred_draws)
list(
y_draws = y_draws,
pred_draws = pred_draws,
param_draws = stan_fit
)
}
draw_f_prior <- function(model, stan_fit, verbose, STREAM) {
kc <- create_kernel_computer(model, stan_fit, NULL, NULL, NULL, FALSE, STREAM)
input <- kc@input
K_input <- kc@K_input
S <- num_paramsets(kc)
P <- num_evalpoints(kc)
J <- num_components(kc)
comp_names <- component_names(kc)
delta <- dollar(input, "delta")
f_draws_comp <- array(0.0, c(S, P, J))
f_draws <- array(0.0, c(S, P))
progbar <- verbose && S > 1
pb <- progbar_setup(L = S)
hdr <- dollar(pb, "header")
idx_print <- dollar(pb, "idx_print")
log_progress(hdr, progbar)
for (idx in seq_len(S)) {
K_prior <- kernel_all(K_input, input, idx, kc@STREAM)
f_i <- draw_gp_components(K_prior, delta)
f_draws_comp[idx, , ] <- f_i
f_draws[idx, ] <- rowSums(f_i)
if (progbar) progbar_print(idx, idx_print)
}
log_progress(" ", progbar)
f_draws_comp <- aperm(f_draws_comp, c(3, 1, 2))
out <- list(
f_draws_comp = arr3_to_list(f_draws_comp, comp_names),
f_draws = f_draws,
x = get_data(model)
)
return(out)
}
draw_gp_components <- function(K, delta) {
N <- nrow(K[[1]])
J <- length(K)
mu0 <- rep(0.0, N)
f_draws <- matrix(0.0, N, J)
for (j in seq_len(J)) {
Sigma <- K[[j]] + delta * diag(N)
f_draws[, j] <- MASS::mvrnorm(n = 1, mu = mu0, Sigma = Sigma)
}
return(f_draws)
}
|
dmjd2ut <-
function(dmjd, tz='UTC') {
jd <- trunc(dmjd) + 2400000.5
ymd <- jd2ymd(jd)
ymd <- as.numeric(unlist(strsplit(as.character(ymd), '[-: ]')))
len <- length(ymd)
yr <- ymd[seq(1, len, by=3)]
mo <- ymd[seq(2, len, by=3)]
dy <- ymd[seq(3, len, by=3)]
dayfrac <- dmjd%%1
hr <- dayfrac*24
min <- (hr%%1)*60
ds <- getOption('digits.secs')
if(is.null(ds)) ds <- 0
sec <- round((min%%1)*60, ds)
out <- ISOdatetime(yr, mo, dy, trunc(hr), trunc(min), sec, 'UTC')
attr(out, 'tzone') <- tz
out
}
|
print.compare_performance <- function(x, digits = 3, ...) {
table_caption <- c("
formatted_table <- format(x = x, digits = digits, format = "text", ...)
if ("Performance_Score" %in% colnames(formatted_table)) {
footer <- c(sprintf("\nModel %s (of class %s) performed best with an overall performance score of %s.", formatted_table$Model[1], formatted_table$Type[1], formatted_table$Performance_Score[1]), "yellow")
} else {
footer <- NULL
}
cat(insight::export_table(x = formatted_table, digits = digits, format = "text", caption = table_caption, footer = footer, ...))
invisible(x)
}
print.performance_model <- function(x, digits = 3, ...) {
formatted_table <- format(x = x, digits = digits, format = "text", ...)
cat(insight::export_table(x = formatted_table, digits = digits, format = "text", caption = c("
invisible(x)
}
print.check_outliers <- function(x, ...) {
outliers <- which(x)
if (length(outliers) >= 1) {
o <- paste0(" (cases ", paste0(outliers, collapse = ", "), ")")
insight::print_color(sprintf("Warning: %i outliers detected%s.\n", length(outliers), o), "red")
} else {
insight::print_color("OK: No outliers detected.\n", "green")
}
invisible(x)
}
print.check_model <- function(x, ...) {
insight::check_if_installed("see", "for model diagnositic plots")
NextMethod()
}
print.check_distribution <- function(x, ...) {
insight::print_color("
x1 <- x[order(x$p_Residuals, decreasing = TRUE)[1:3], c(1, 2)]
x1 <- x1[x1$p_Residuals > 0, ]
x1$p_Residuals <- sprintf("%g%%", round(100 * x1$p_Residuals))
colnames(x1) <- c("Distribution", "Probability")
insight::print_color("Predicted Distribution of Residuals\n\n", "red")
print.data.frame(x1, row.names = FALSE, ...)
x2 <- x[order(x$p_Response, decreasing = TRUE)[1:3], c(1, 3)]
x2 <- x2[x2$p_Response > 0, ]
x2$p_Response <- sprintf("%g%%", round(100 * x2$p_Response))
colnames(x2) <- c("Distribution", "Probability")
insight::print_color("\nPredicted Distribution of Response\n\n", "red")
print.data.frame(x2, row.names = FALSE, ...)
invisible(x)
}
print.check_distribution_numeric <- function(x, ...) {
insight::print_color("
x1 <- x[order(x$p_Vector, decreasing = TRUE)[1:3], c(1, 2)]
x1 <- x1[x1$p_Vector > 0, ]
x1$p_Vector <- sprintf("%g%%", round(100 * x1$p_Vector))
colnames(x1) <- c("Distribution", "Probability")
print.data.frame(x1, row.names = FALSE, ...)
invisible(x)
}
print.performance_roc <- function(x, ...) {
if (length(unique(x$Model)) == 1) {
cat(sprintf("AUC: %.2f%%\n", 100 * bayestestR::area_under_curve(x$Specificity, x$Sensitivity)))
} else {
insight::print_color("
dat <- split(x, f = x$Model)
max_space <- max(nchar(x$Model))
for (i in 1:length(dat)) {
cat(sprintf(
" %*s: %.2f%%\n",
max_space,
names(dat)[i],
100 * bayestestR::area_under_curve(dat[[i]]$Specificity, dat[[i]]$Sensitivity)
))
}
}
invisible(x)
}
print.item_difficulty <- function(x, ...) {
spaces <- max(nchar(x$item))
insight::print_color("
insight::print_color(sprintf(" %*s ideal\n", spaces + 10, "difficulty"), "red")
for (i in 1:length(x$item)) {
cat(sprintf(" %*s %.2f %.2f\n", spaces, x$item[i], x$difficulty[i], x$ideal[i]))
}
invisible(x)
}
print.performance_pcp <- function(x, digits = 2, ...) {
insight::print_color("
cat(sprintf(" Full model: %.2f%% [%.2f%% - %.2f%%]\n", 100 * x$pcp_model, 100 * x$model_ci_low, 100 * x$model_ci_high))
cat(sprintf(" Null model: %.2f%% [%.2f%% - %.2f%%]\n", 100 * x$pcp_m0, 100 * x$null_ci_low, 100 * x$null_ci_high))
insight::print_color("\n
v1 <- sprintf("%.3f", x$lrt_chisq)
v2 <- sprintf("%.3f", x$lrt_df_error)
v3 <- sprintf("%.3f", x$lrt_p)
space <- max(nchar(c(v1, v2)))
cat(sprintf(" Chi-squared: %*s\n", space, v1))
cat(sprintf(" df: %*s\n", space, v2))
cat(sprintf(" p-value: %*s\n\n", space, v3))
invisible(x)
}
print.looic <- function(x, digits = 2, ...) {
insight::print_color("
out <- paste0(c(
sprintf(" LOOIC: %.*f [%.*f]", digits, x$LOOIC, digits, x$LOOIC_SE),
sprintf(" ELPD: %.*f [%.*f]", digits, x$ELPD, digits, x$ELPD_SE)
),
collapse = "\n"
)
cat(out)
cat("\n")
invisible(x)
}
print.r2_generic <- function(x, digits = 3, ...) {
model_type <- attr(x, "model_type")
if (!is.null(model_type)) {
insight::print_color(sprintf("
}
if (all(c("R2_adjusted", "R2_within_adjusted") %in% names(x))) {
out <- paste0(c(
sprintf(" R2: %.*f", digits, x$R2),
sprintf(" adj. R2: %.*f", digits, x$R2_adjusted),
sprintf(" within R2: %.*f", digits, x$R2_within),
sprintf(" adj. within R2: %.*f", digits, x$R2_within_adjusted)
),
collapse = "\n"
)
} else if ("R2_adjusted" %in% names(x)) {
out <- paste0(c(
sprintf(" R2: %.*f", digits, x$R2),
sprintf(" adj. R2: %.*f", digits, x$R2_adjusted)
),
collapse = "\n"
)
} else {
out <- sprintf(" %s: %.*f", names(x$R2), digits, x$R2)
}
cat(out)
cat("\n")
invisible(x)
}
print.r2_pseudo <- function(x, digits = 3, ...) {
model_type <- attr(x, "model_type")
if (!is.null(model_type)) {
insight::print_color(sprintf("
}
cat(sprintf(" %s: %.*f\n", names(x[[1]]), digits, x[[1]]))
invisible(x)
}
print.r2_mlm <- function(x, digits = 3, ...) {
model_type <- attr(x, "model_type")
if (!is.null(model_type)) {
insight::print_color(sprintf("
} else {
insight::print_color("
}
for (i in names(x)) {
insight::print_color(sprintf("
out <- paste0(c(
sprintf(" R2: %.*f", digits, x[[i]]$R2),
sprintf(" adj. R2: %.*f", digits, x[[i]]$R2_adjusted)
),
collapse = "\n"
)
cat(out)
cat("\n\n")
}
invisible(x)
}
print.r2_nakagawa <- function(x, digits = 3, ...) {
model_type <- attr(x, "model_type")
if (is.null(model_type)) {
insight::print_color("
} else {
insight::print_color("
}
out <- paste0(c(
sprintf(" Conditional R2: %.*f", digits, x$R2_conditional),
sprintf(" Marginal R2: %.*f", digits, x$R2_marginal)
),
collapse = "\n"
)
cat(out)
cat("\n")
invisible(x)
}
print.r2_bayes <- function(x, digits = 3, ...) {
insight::print_color("
r2_ci <- insight::format_ci(
attributes(x)$CI$R2_Bayes$CI_low,
attributes(x)$CI$R2_Bayes$CI_high,
ci = attributes(x)$CI$R2_Bayes$CI,
digits = digits
)
out <- sprintf(" Conditional R2: %.*f (%s)", digits, x$R2_Bayes, r2_ci)
if ("R2_Bayes_marginal" %in% names(x)) {
r2_marginal_ci <- insight::format_ci(
attributes(x)$CI$R2_Bayes_marginal$CI_low,
attributes(x)$CI$R2_Bayes_marginal$CI_high,
ci = attributes(x)$CI$R2_Bayes_marginal$CI,
digits = digits
)
out <- paste0(c(out, sprintf(" Marginal R2: %.*f (%s)", digits, x$R2_Bayes_marginal, r2_marginal_ci)), collapse = "\n")
}
cat(out)
cat("\n")
invisible(x)
}
print.r2_loo <- function(x, digits = 3, ...) {
insight::print_color("
r2_ci <- insight::format_ci(
attributes(x)$CI$R2_loo$CI_low,
attributes(x)$CI$R2_loo$CI_high,
ci = attributes(x)$CI$R2_loo$CI,
digits = digits
)
out <- sprintf(" Conditional R2: %.*f (%s)", digits, x$R2_loo, r2_ci)
if ("R2_loo_marginal" %in% names(x)) {
r2_marginal_ci <- insight::format_ci(
attributes(x)$CI$R2_loo_marginal$CI_low,
attributes(x)$CI$R2_loo_marginal$CI_high,
ci = attributes(x)$CI$R2_loo_marginal$CI,
digits = digits
)
out <- paste0(c(out, sprintf(" Marginal R2: %.*f (%s)", digits, x$R2_loo_marginal, r2_marginal_ci)), collapse = "\n")
}
cat(out)
cat("\n")
invisible(x)
}
print.icc <- function(x, digits = 3, ...) {
insight::print_color("
out <- paste0(c(
sprintf(" Adjusted ICC: %.*f", digits, x$ICC_adjusted),
sprintf(" Conditional ICC: %.*f", digits, x$ICC_conditional)
),
collapse = "\n"
)
cat(out)
cat("\n")
invisible(x)
}
print.icc_by_group <- function(x, digits = 3, ...) {
insight::print_color("
cat(insight::export_table(x, digits = digits))
invisible(x)
}
print.r2_nakagawa_by_group <- function(x, digits = 3, ...) {
insight::print_color("
cat(insight::export_table(x, digits = digits))
cat("\n")
invisible(x)
}
print.check_zi <- function(x, ...) {
insight::print_color("
cat(sprintf(" Observed zeros: %i\n", x$observed.zeros))
cat(sprintf(" Predicted zeros: %i\n", x$predicted.zeros))
cat(sprintf(" Ratio: %.2f\n\n", x$ratio))
lower <- 1 - x$tolerance
upper <- 1 + x$tolerance
if (x$ratio < lower) {
message("Model is underfitting zeros (probable zero-inflation).")
} else if (x$ratio > upper) {
message("Model is overfitting zeros.")
} else {
message(insight::format_message("Model seems ok, ratio of observed and predicted zeros is within the tolerance range."))
}
invisible(x)
}
print.check_overdisp <- function(x, digits = 3, ...) {
orig_x <- x
x$dispersion_ratio <- sprintf("%.*f", digits, x$dispersion_ratio)
x$chisq_statistic <- sprintf("%.*f", digits, x$chisq_statistic)
x$p_value <- pval <- round(x$p_value, digits = digits)
if (x$p_value < .001) x$p_value <- "< 0.001"
maxlen <- max(
nchar(x$dispersion_ratio),
nchar(x$chisq_statistic),
nchar(x$p_value)
)
insight::print_color("
cat(sprintf(" dispersion ratio = %s\n", format(x$dispersion_ratio, justify = "right", width = maxlen)))
cat(sprintf(" Pearson's Chi-Squared = %s\n", format(x$chisq_statistic, justify = "right", width = maxlen)))
cat(sprintf(" p-value = %s\n\n", format(x$p_value, justify = "right", width = maxlen)))
if (pval > 0.05) {
message("No overdispersion detected.")
} else {
message("Overdispersion detected.")
}
invisible(orig_x)
}
print.icc_decomposed <- function(x, digits = 2, ...) {
cat("
reform <- attr(x, "re.form", exact = TRUE)
if (is.null(reform)) {
reform <- "all random effects"
} else {
reform <- .safe_deparse(reform)
}
cat(sprintf("Conditioned on: %s\n\n", reform))
prob <- attr(x, "ci", exact = TRUE)
cat(insight::print_color("
icc.val <- sprintf("%.*f", digits, x$ICC_decomposed)
ci.icc.lo <- sprintf("%.*f", digits, x$ICC_CI[1])
ci.icc.hi <- sprintf("%.*f", digits, x$ICC_CI[2])
cat(sprintf(
"Ratio: %s CI %i%%: [%s %s]\n",
icc.val,
as.integer(round(prob * 100)),
ci.icc.lo,
ci.icc.hi
))
cat(insight::print_color("\n
null.model <- sprintf("%.*f", digits, attr(x, "var_rand_intercept", exact = TRUE))
ci.null <- attr(x, "ci.var_rand_intercept", exact = TRUE)
ci.null.lo <- sprintf("%.*f", digits, ci.null$CI_low)
ci.null.hi <- sprintf("%.*f", digits, ci.null$CI_high)
full.model <- sprintf("%.*f", digits, attr(x, "var_total", exact = TRUE))
ci.full <- attr(x, "ci.var_total", exact = TRUE)
ci.full.lo <- sprintf("%.*f", digits, ci.full$CI_low)
ci.full.hi <- sprintf("%.*f", digits, ci.full$CI_high)
ml <- max(nchar(null.model), nchar(full.model))
ml.ci <- max(nchar(ci.full.lo), nchar(ci.null.lo))
mh.ci <- max(nchar(ci.full.hi), nchar(ci.null.hi))
cat(sprintf(
"Conditioned on fixed effects: %*s CI %i%%: [%*s %*s]\n",
ml,
null.model,
as.integer(round(prob * 100)),
ml.ci,
ci.null.lo,
mh.ci,
ci.null.hi
))
cat(sprintf(
"Conditioned on rand. effects: %*s CI %i%%: [%*s %*s]\n",
ml,
full.model,
as.integer(round(prob * 100)),
ml.ci,
ci.full.lo,
mh.ci,
ci.full.hi
))
cat(insight::print_color("\n
res <- sprintf("%.*f", digits, attr(x, "var_residual", exact = TRUE))
ci.res <- attr(x, "ci.var_residual", exact = TRUE)
ci.res.lo <- sprintf("%.*f", digits, ci.res$CI_low)
ci.res.hi <- sprintf("%.*f", digits, ci.res$CI_high)
cat(sprintf(
"Difference: %s CI %i%%: [%s %s]\n",
res,
as.integer(round(prob * 100)),
ci.res.lo,
ci.res.hi
))
invisible(x)
}
print.binned_residuals <- function(x, ...) {
insight::check_if_installed("see", "to plot binned residuals")
NextMethod()
}
print.performance_hosmer <- function(x, ...) {
insight::print_color("
v1 <- sprintf("%.3f", x$chisq)
v2 <- sprintf("%i ", x$df)
v3 <- sprintf("%.3f", x$p.value)
space <- max(nchar(c(v1, v2, v3)))
cat(sprintf(" Chi-squared: %*s\n", space, v1))
cat(sprintf(" df: %*s\n", space, v2))
cat(sprintf(" p-value: %*s\n\n", space, v3))
if (x$p.value >= 0.05) {
message("Summary: model seems to fit well.")
} else {
message("Summary: model does not fit well.")
}
invisible(x)
}
print.performance_accuracy <- function(x, ...) {
insight::print_color("
cat(sprintf("Accuracy: %.2f%%\n", 100 * x$Accuracy))
cat(sprintf(" SE: %.2f%%-points\n", 100 * x$SE))
cat(sprintf(" Method: %s\n", x$Method))
invisible(x)
}
print.performance_score <- function(x, ...) {
insight::print_color("
results <- format(
c(
sprintf("%.4f", x$logarithmic),
sprintf("%.4f", x$quadratic),
sprintf("%.4f", x$spherical)
),
justify = "right"
)
cat(sprintf("logarithmic: %s\n", results[1]))
cat(sprintf(" quadratic: %s\n", results[2]))
cat(sprintf(" spherical: %s\n", results[3]))
invisible(x)
}
print.check_collinearity <- function(x, ...) {
insight::print_color("
if ("Component" %in% colnames(x)) {
comp <- split(x, x$Component)
for (i in 1:length(comp)) {
cat(paste0("\n* ", comp[[i]]$Component[1], " component:\n"))
.print_collinearity(comp[[i]][, 1:3])
}
} else {
.print_collinearity(x)
}
invisible(x)
}
.print_collinearity <- function(x) {
vifs <- x$VIF
x$Tolerance <- 1 / x$VIF
x$VIF <- sprintf("%.2f", x$VIF)
x$SE_factor <- sprintf("%.2f", x$SE_factor)
x$Tolerance <- sprintf("%.2f", x$Tolerance)
colnames(x)[3] <- "Increased SE"
low_corr <- which(vifs < 5)
if (length(low_corr)) {
cat("\n")
insight::print_color("Low Correlation\n\n", "green")
print.data.frame(x[low_corr, ], row.names = FALSE)
}
mid_corr <- which(vifs >= 5 & vifs < 10)
if (length(mid_corr)) {
cat("\n")
insight::print_color("Moderate Correlation\n\n", "yellow")
print.data.frame(x[mid_corr, ], row.names = FALSE)
}
high_corr <- which(vifs >= 10)
if (length(high_corr)) {
cat("\n")
insight::print_color("High Correlation\n\n", "red")
print.data.frame(x[high_corr, ], row.names = FALSE)
}
}
print.test_likelihoodratio <- function(x, digits = 2, ...) {
if ("LogLik" %in% names(x)) {
best <- which.max(x$LogLik)
footer <- c(sprintf("\nModel '%s' seems to have the best model fit.\n", x$Model[best]), "yellow")
} else {
footer <- NULL
}
x$p <- insight::format_p(x$p, name = NULL)
cat(insight::export_table(
x,
digits = digits,
caption = c("
footer = footer
))
invisible(x)
}
print.check_itemscale <- function(x, digits = 2, ...) {
insight::print_color("
cat(insight::export_table(
lapply(1:length(x), function(i) {
out <- x[[i]]
attr(out, "table_caption") <- c(sprintf("\nComponent %i", i), "red")
attr(out, "table_footer") <- c(sprintf(
"\nMean inter-item-correlation = %.3f Cronbach's alpha = %.3f",
attributes(out)$item_intercorrelation,
attributes(out)$cronbachs_alpha
), "yellow")
out
}),
digits = digits,
format = "text",
missing = "<NA>",
zap_small = TRUE
))
}
|
try_with_timeout <- function(test_fn, tlimit = 30, defaultvalue = "TimedOut") {
results <- tryCatch(expr = evalWithTimeout(test_fn, timeout = tlimit),
TimeoutException = function(ex) defaultvalue)
if(is(results, "TimedOut")){
return( defaultvalue )
} else { results }
}
|
context("meteo")
test_that("search for multi-monitor data", {
skip_on_cran()
skip_on_ci()
skip_if_government_down()
monitors <- c("ASN00003003", "ASM00094299")
search_a <- meteo_pull_monitors(monitors)
search_b <- meteo_pull_monitors(monitors, var = "PRCP")
expect_is(search_a, "data.frame")
expect_is(search_a$prcp, "numeric")
})
test_that("determine monitors' data coverage", {
skip_on_cran()
skip_on_ci()
skip_if_government_down()
monitors <- c("ASN00003003", "ASM00094299")
search_a <- meteo_pull_monitors(monitors)
obs_covr <- meteo_coverage(search_a)
expect_is(obs_covr, "list")
expect_is(obs_covr[[1]]$start_date, "Date")
expect_is(obs_covr[[1]]$total_obs, "integer")
expect_is(obs_covr[[1]]$prcp, "numeric")
expect_equal(NROW(obs_covr[[1]]), length(monitors))
expect_is(obs_covr[[2]]$date, "Date")
expect_is(obs_covr[[2]]$id, "character")
expect_is(obs_covr[[2]]$prcp, "numeric")
})
|
tii <- function(object) {
object <- as.annual(object)
return(sum(log(object$precipitation[2:nrow(object)]/object$precipitation[(1:(nrow(object)-1))]))/(nrow(object)-1))
}
|
fit_sbm_geobiased_const = function( trees,
tip_latitudes,
tip_longitudes,
radius,
reference_latitudes = NULL,
reference_longitudes = NULL,
only_basal_tip_pairs = FALSE,
only_distant_tip_pairs = FALSE,
min_MRCA_time = 0,
max_MRCA_age = Inf,
max_phylodistance = Inf,
min_diffusivity = NULL,
max_diffusivity = NULL,
rarefaction = 0.1,
Nsims = 100,
max_iterations = 100,
Nbootstraps = 0,
NQQ = 0,
Nthreads = 1,
include_simulations = FALSE,
SBM_PD_functor = NULL,
verbose = FALSE,
verbose_prefix = ""){
if("phylo" %in% class(trees)){
trees = list(trees)
Ntrees = 1
if(!(("list" %in% class(tip_latitudes)) && (length(tip_latitudes)==1))){
tip_latitudes = list(tip_latitudes)
}
if(!(("list" %in% class(tip_longitudes)) && (length(tip_longitudes)==1))){
tip_longitudes = list(tip_longitudes)
}
}else if("list" %in% class(trees)){
Ntrees = length(trees)
if("list" %in% class(tip_latitudes)){
if(length(tip_latitudes)!=Ntrees) return(list(success=FALSE,error=sprintf("Input list of tip_latitudes has length %d, but should be of length %d (number of trees)",length(tip_latitudes),Ntrees)))
}else if("numeric" %in% class(tip_latitudes)){
if(Ntrees!=1) return(list(success=FALSE,error=sprintf("Input tip_latitudes was given as a single vector, but expected a list of %d vectors (number of trees)",Ntrees)))
if(length(tip_latitudes)!=length(trees[[1]]$tip.label)) return(list(success=FALSE,error=sprintf("Input tip_latitudes was given as a single vector of length %d, but expected length %d (number of tips in the input tree)",length(tip_latitudes),length(trees[[1]]$tip.label))))
tip_latitudes = list(tip_latitudes)
}
if("list" %in% class(tip_longitudes)){
if(length(tip_longitudes)!=Ntrees) return(list(success=FALSE,error=sprintf("Input list of tip_longitudes has length %d, but should be of length %d (number of trees)",length(tip_longitudes),Ntrees)))
}else if("numeric" %in% class(tip_longitudes)){
if(Ntrees!=1) return(list(success=FALSE,error=sprintf("Input tip_longitudes was given as a single vector, but expected a list of %d vectors (number of trees)",Ntrees)))
if(length(tip_longitudes)!=length(trees[[1]]$tip.label)) return(list(success=FALSE,error=sprintf("ERROR: Input tip_longitudes was given as a single vector of length %d, but expected length %d (number of tips in the input tree)",length(tip_longitudes),length(trees[[1]]$tip.label))))
tip_longitudes = list(tip_longitudes)
}
}else{
return(list(success=FALSE,error=sprintf("Unknown data format '%s' for input trees[]: Expected a list of phylo trees or a single phylo tree",class(trees)[1])))
}
Nsims = max(2,Nsims)
max_iterations = max(1,max_iterations)
rarefaction = max(0,min(1,rarefaction))
if(is.null(reference_latitudes) || is.null(reference_longitudes)){
reference_latitudes = unlist(tip_latitudes)
reference_longitudes = unlist(tip_longitudes)
}
if(verbose) cat(sprintf("%sFitting basic birth-death models to %d trees..\n",verbose_prefix,Ntrees))
BD_lambdas = rep(NA,Ntrees)
BD_mus = rep(NA,Ntrees)
BD_rhos = rep(NA,Ntrees)
for(tr in seq_len(Ntrees)){
if(length(trees[[tr]]$tip.label)<=4) next
BDfit = castor::fit_hbd_model_on_grid( tree = trees[[tr]],
const_lambda = TRUE,
const_mu = TRUE,
guess_rho0 = rarefaction,
min_rho0 = 0.0001*rarefaction,
condition = "auto",
Ntrials = 100,
Nthreads = Nthreads)
if(!BDfit$success) next
BD_rhos[tr] = min(rarefaction,(if(BDfit$fitted_lambda<=BDfit$fitted_mu) 1 else BDfit$fitted_rho/(1-BDfit$fitted_mu/BDfit$fitted_lambda)))
BD_lambdas[tr] = max(0,BDfit$fitted_lambda * BDfit$fitted_rho / BD_rhos[tr])
BD_mus[tr] = max(0,BD_lambdas[tr] - (BDfit$fitted_lambda - BDfit$fitted_mu))
}
successfull_BD_fits = which(is.finite(BD_lambdas))
if(length(successfull_BD_fits)==0) return(list(success=FALSE, error=sprintf("BD model fitting failed for all %d trees",Ntrees)))
if(length(successfull_BD_fits)<Ntrees){
if(verbose) cat(sprintf("%s WARNING: Ignoring %d out of %d trees for which BD model fitting failed\n",verbose_prefix,Ntrees-length(successfull_BD_fits),Ntrees))
BD_lambdas = BD_lambdas[successfull_BD_fits]
BD_mus = BD_mus[successfull_BD_fits]
BD_rhos = BD_rhos[successfull_BD_fits]
trees = trees[successfull_BD_fits]
tip_latitudes = tip_latitudes[successfull_BD_fits]
tip_longitudes = tip_longitudes[successfull_BD_fits]
Ntrees = length(successfull_BD_fits)
}
if(verbose) cat(sprintf("%s Note: Congruents of fitted models have mean lambda = %g, mu = %g, r = %g, rho = %g\n",verbose_prefix,mean(BD_lambdas),mean(BD_mus),mean(BD_lambdas-BD_mus),mean(BD_rhos)))
if(verbose) cat(sprintf("%sFitting diffusivity without any correction..\n",verbose_prefix))
fit0 = fit_sbm_const( trees = trees,
tip_latitudes = tip_latitudes,
tip_longitudes = tip_longitudes,
radius = radius,
only_basal_tip_pairs = only_basal_tip_pairs,
only_distant_tip_pairs = only_distant_tip_pairs,
min_MRCA_time = min_MRCA_time,
max_MRCA_age = max_MRCA_age,
max_phylodistance = max_phylodistance,
min_diffusivity = min_diffusivity,
max_diffusivity = max_diffusivity,
Nbootstraps = Nbootstraps,
NQQ = 0,
SBM_PD_functor = SBM_PD_functor)
if(!fit0$success) return(list(success=FALSE, error=sprintf("Could not fit SBM model in first round: %s",fit0$error)))
if(verbose) cat(sprintf("%s Fitted diffusivity: %g\n",verbose_prefix,fit0$diffusivity))
root_ages = sapply(seq_len(Ntrees), FUN=function(tr) get_tree_span(trees[[tr]])$max_distance)
correction_factor = 1
all_correction_factors = rep(NA,min(1000,max_iterations))
all_diffusivity_estimates = rep(NA,min(1000,max_iterations))
Niterations = 0
stopping_criterion = NULL
sims = vector(mode="list", Ntrees)
Nsims_per_tree = numeric(Ntrees)
tile_counts = NULL
tile_latitudes = NULL
tile_longitudes = NULL
converged = FALSE
for(i in seq_len(max_iterations)){
if(verbose) cat(sprintf("%sIteration %d\n",verbose_prefix,i))
if(verbose) cat(sprintf("%s Simulating %d replicate SBM models for each input tree (with D=%g)..\n",verbose_prefix,Nsims,fit0$diffusivity * correction_factor))
for(tr in seq_len(Ntrees)){
sims[[tr]] = simulate_geobiased_sbm(Nsims = Nsims,
Ntips = length(trees[[tr]]$tip.label),
radius = radius,
diffusivity = fit0$diffusivity * correction_factor,
lambda = BD_lambdas[tr],
mu = BD_mus[tr],
rarefaction = BD_rhos[tr],
crown_age = root_ages[tr],
Nthreads = Nthreads,
omit_failed_sims = TRUE,
reference_latitudes = reference_latitudes,
reference_longitudes = reference_longitudes,
tile_counts = tile_counts,
tile_latitudes = tile_latitudes,
tile_longitudes = tile_longitudes)
if(!sims[[tr]]$success) return(list(success=FALSE, error=sprintf("Iteration %d failed for tree
Nsims_per_tree[tr] = length(sims[[tr]]$sims)
if(is.null(tile_counts)){
tile_counts = sims[[tr]]$tile_counts
tile_latitudes = sims[[tr]]$tile_latitudes
tile_longitudes = sims[[tr]]$tile_longitudes
}
if(length(sims[[tr]]$sims)==0){
sims[[tr]]$success = FALSE
next
}
}
trees_with_valid_sims = which(sapply(seq_len(Ntrees), FUN=function(tr) sims[[tr]]$success))
if(length(trees_with_valid_sims)==0) return(list(success=FALSE, error=sprintf("Iteration %d failed: Simulations failed completely for all trees",i)))
aux_fit_SBM_to_simulation = function(r){
sim_trees = lapply(trees_with_valid_sims, FUN=function(tr) sims[[tr]]$sims[[1+(r-1) %% Nsims_per_tree[tr]]]$tree)
sim_latitudes = lapply(trees_with_valid_sims, FUN=function(tr) sims[[tr]]$sims[[1+(r-1) %% Nsims_per_tree[tr]]]$latitudes)
sim_longitudes = lapply(trees_with_valid_sims, FUN=function(tr) sims[[tr]]$sims[[1+(r-1) %% Nsims_per_tree[tr]]]$longitudes)
sim_fit = fit_sbm_const(trees = sim_trees,
tip_latitudes = sim_latitudes,
tip_longitudes = sim_longitudes,
radius = radius,
only_basal_tip_pairs = only_basal_tip_pairs,
only_distant_tip_pairs = only_distant_tip_pairs,
min_MRCA_time = min_MRCA_time,
max_MRCA_age = max_MRCA_age,
max_phylodistance = max_phylodistance,
SBM_PD_functor = SBM_PD_functor)
return(if(sim_fit$success) sim_fit$diffusivity else NA)
}
if((Nsims>1) && (Nthreads>1) && (.Platform$OS.type!="windows")){
if(verbose) cat(sprintf("%s Fitting SBM diffusivity to %d simulations (parallelized)..\n",verbose_prefix,Nsims))
sim_fit_diffusivities = unlist(parallel::mclapply( seq_len(Nsims),
FUN = function(r){ aux_fit_SBM_to_simulation(r) },
mc.cores = min(Nthreads, Nsims),
mc.preschedule = TRUE,
mc.cleanup = TRUE))
}else{
if(verbose) cat(sprintf("%s Fitting SBM diffusivity to %d simulations (sequentially)..\n",verbose_prefix,Nsims))
sim_fit_diffusivities = rep(NA, Nsims)
for(r in seq_len(Nsims)){
sim_fit_diffusivities[r] = aux_fit_SBM_to_simulation(r)
}
}
valid_fits = which(is.finite(sim_fit_diffusivities))
if(length(valid_fits)==0) return(list(success=FALSE, error=sprintf("Iteration %d failed: Could not fit SBM to any of the simulated datasets",i)))
if(length(valid_fits)==1) return(list(success=FALSE, error=sprintf("Iteration %d failed: Could only fit SBM to one of the simulated datasets, but need at least 2 successful sims",i)))
sim_fit_diffusivities = sim_fit_diffusivities[valid_fits]
if(length(sim_fit_diffusivities)>=5) sim_fit_diffusivities = remove_outliers(X=sim_fit_diffusivities, outlier_prob=0.1)
if(length(sim_fit_diffusivities)<2) return(list(success=FALSE, error=sprintf("Iteration %d failed: Nearly all sim-fitted diffusivities were filtered out as 'outliers'.",i)))
mean_sim_fit_diffusivity = exp(mean(log(sim_fit_diffusivities)))
se_sim_fit_log_diffusivity = sd(log(sim_fit_diffusivities))/sqrt(length(sim_fit_diffusivities))
all_correction_factors[i] = correction_factor
all_diffusivity_estimates[i] = mean_sim_fit_diffusivity
Niterations = Niterations + 1
if(verbose) cat(sprintf("%s Geometric-mean diffusivity fitted to sims: %g (standard error of mean log-D %g)\n",verbose_prefix,mean_sim_fit_diffusivity,se_sim_fit_log_diffusivity))
if((abs(log(fit0$diffusivity)-log(mean_sim_fit_diffusivity))<min(se_sim_fit_log_diffusivity,0.1)) && (i>1) && (abs(log(correction_factor/all_correction_factors[i-1]))<0.1)){
if(verbose) cat(sprintf("%s Achieved approximate convergence at iteration %d: true estimated diffusivity = %g\n",verbose_prefix,i,fit0$diffusivity*correction_factor))
stopping_criterion = sprintf("Achieved approximate convergence at iteration %d (relative difference to uncorrected fit: %g)",i,abs(fit0$diffusivity-mean_sim_fit_diffusivity)/fit0$diffusivity)
converged = TRUE
break
}
if(i<=2){
correction_factor = correction_factor * fit0$diffusivity/mean_sim_fit_diffusivity
}else{
aboves = which(all_diffusivity_estimates-fit0$diffusivity>=0)
belows = which(all_diffusivity_estimates-fit0$diffusivity<=0)
if((length(aboves)>0) && (length(belows)>0)){
left = belows[which.min(fit0$diffusivity-all_diffusivity_estimates[belows])]
right = aboves[which.min(all_diffusivity_estimates[aboves]-fit0$diffusivity)]
if((i!=left) && (i!=right)){
if((all_diffusivity_estimates[i]-fit0$diffusivity) * (all_diffusivity_estimates[left]-fit0$diffusivity)<0){
right = i
}else{
left = i
}
}
}else{
left = i-1
right = i
}
correction_factor = exp(log(all_correction_factors[left]) + (log(fit0$diffusivity)-log(all_diffusivity_estimates[left])) * (log(all_correction_factors[right])-log(all_correction_factors[left]))/(log(all_diffusivity_estimates[right])-log(all_diffusivity_estimates[left])))
}
if(verbose) cat(sprintf("%s Estimated correction factor: %g\n",verbose_prefix,correction_factor))
if(!is.finite(correction_factor)) return(list( success = FALSE,
error = sprintf("Sequence diverged (correction factor non-finite)"),
Niterations = Niterations,
uncorrected_fit_diffusivity = fit0$diffusivity,
all_correction_factors = all_correction_factors[seq_len(Niterations)],
all_diffusivity_estimates = all_diffusivity_estimates[seq_len(Niterations)]))
}
if(!converged) return(list(success=FALSE, error="Failed to converge", Nlat = sims[[1]]$Nlat, Nlon = sims[[1]]$Nlon, uncorrected_fit_diffusivity = fit0$diffusivity, Ncontrasts = fit0$Ncontrasts, Ntrees = Ntrees))
true_diffusivity = fit0$diffusivity * correction_factor
if(NQQ>0){
sim_geodistances = numeric(NQQ * fit0$Ncontrasts)
next_g = 1
for(tr in 1:Ntrees){
tip_pairs = fit0$tip_pairs_per_tree[[tr]]
if(length(tip_pairs)>0){
for(q in 1:NQQ){
sim = castor::simulate_sbm(tree = trees[[tr]], radius = radius, diffusivity = true_diffusivity, root_latitude = NULL, root_longitude = NULL)
if(!sim$success) return(list(success=FALSE, error=sprintf("Calculation of QQ failed at simulation %d for tree %d: Could not simulate SBM for the fitted model: %s",q,tr,sim$error), diffusivity=true_diffusivity));
sim_geodistances[next_g + c(1:nrow(tip_pairs))] = radius * geodesic_angles(sim$tip_latitudes[tip_pairs[,1]],sim$tip_longitudes[tip_pairs[,1]],sim$tip_latitudes[tip_pairs[,2]],sim$tip_longitudes[tip_pairs[,2]])
next_g = next_g + nrow(tip_pairs)
}
}
}
probs = seq_len(fit0$Ncontrasts)/fit0$Ncontrasts
QQplot = cbind(quantile(fit0$geodistances, probs=probs, na.rm=TRUE, type=8), quantile(sim_geodistances, probs=probs, na.rm=TRUE, type=8))
}
return(list(success = TRUE,
Nlat = sims[[1]]$Nlat,
Nlon = sims[[1]]$Nlon,
diffusivity = true_diffusivity,
correction_factor = correction_factor,
Niterations = Niterations,
stopping_criterion = stopping_criterion,
uncorrected_fit_diffusivity = fit0$diffusivity,
last_sim_fit_diffusivity = mean_sim_fit_diffusivity,
all_correction_factors = all_correction_factors[seq_len(Niterations)],
all_diffusivity_estimates = all_diffusivity_estimates[seq_len(Niterations)],
Ntrees = Ntrees,
lambda = BD_lambdas,
mu = BD_mus,
rarefaction = rarefaction,
Ncontrasts = fit0$Ncontrasts,
standard_error = fit0$standard_error * correction_factor,
CI50lower = fit0$CI50lower * correction_factor,
CI50upper = fit0$CI50upper * correction_factor,
CI95lower = fit0$CI95lower * correction_factor,
CI95upper = fit0$CI95upper * correction_factor,
QQplot = (if(NQQ>0) QQplot else NULL),
simulations = (if(include_simulations) sims else NULL),
SBM_PD_functor = fit0$SBM_PD_functor))
}
|
"fun.fmkl.mm.min" <-
function(coef, data)
{
L3 <- coef[1]
L4 <- coef[2]
aa <- fun.moments(data)
v1 <- fun.fmklb(L3, L4, 1)
v2 <- fun.fmklb(L3, L4, 2)
v3 <- fun.fmklb(L3, L4, 3)
v4 <- fun.fmklb(L3, L4, 4)
g3 <- (v3 - 3 * v2 * v1 + 2 * v1^3) * (v2 - v1^2)^(-3/2)
g4 <- (v4 - 4 * v1 * v3 + 6 * v1^2 * v2 - 3 * v1^4) * (v2 - v1^2)^(-2)
abs(g3 - aa$a3) + abs(g4 - aa$a4)
}
|
set.seed(123)
n <- 10
cgnp_pair <- sample_correlated_gnp_pair(n = n,
corr = 0.7, p = 0.2)
g1 <- cgnp_pair$graph1
g2 <- cgnp_pair$graph2
lcc1 <- largest_common_cc(g1, g2, min_degree = 1)
lcc3 <- largest_common_cc(g1, g2, min_degree = 3)
test_that("largest cc w. min_degree", {
expect_length(lcc1, 3)
expect_equal(sum(lcc1$keep), 4)
expect_length(lcc1$keep, n)
expect_length(lcc3, 3)
expect_equal(sum(lcc3$keep), 2)
expect_length(lcc3$keep, n)
})
set.seed(123)
g <- igraph::sample_gnp(100, .01)
lcc <- largest_cc(g)
test_that("largest cc", {
expect_length(lcc, 2)
expect_equal(sum(lcc$keep), 46)
expect_length(lcc$keep, 100)
})
|
trans_province <- function(province, lang="zh") {
lang <- match.arg(lang, c("zh", "en"))
prov_cities <- jsonlite::fromJSON(system.file('provinces_and_cities.json', package="nCov2019"))
oversea <- readRDS(system.file('oversea_province_translate.rds', package="nCov2019"))
prov_cities <- rbind(prov_cities[,1:2],oversea)
if (lang == "zh") {
load(system.file("ncovEnv.rda", package="nCov2019"))
ncovEnv <- get("ncovEnv")
setup_province <- get("setup_province", envir = ncovEnv)
province <- setup_province(province)
res <- prov_cities$province_name_en[match(province, prov_cities$province_name_zh)]
} else {
res <- prov_cities$province_name_zh[match(province, prov_cities$province_name_en)]
}
return(res)
}
trans_city <- function(city, lang="zh") {
lang <- match.arg(lang, c("zh", "en"))
prov_cities <- jsonlite::fromJSON(system.file('provinces_and_cities.json', package="nCov2019"))
city_df <- unique(dplyr::bind_rows(prov_cities$cities))
if (lang == "zh") {
load(system.file("ncovEnv.rda", package="nCov2019"))
ncovEnv <- get("ncovEnv")
setup_city <- get("setup_city", envir = ncovEnv)
city <- setup_city(city)
res <- city_df$city_name_en[match(city, city_df$city_name_zh)]
} else {
res <- city_df$city_name_zh[match(city, city_df$city_name_en)]
}
return(res)
}
|
SimEF=function (n, p, vn.int, v.boundaryE, v.boundaryF, nsim, eff.stop) {
vn.an <- c(vn.int, n)
n.an <- length(vn.an)
nposE <- nstopE <- rep(0, n.an)
nstopF <- rep(0, n.an)
n.inconclus <- 0
v.critE <- v.boundaryE[vn.an]
v.critF <- v.boundaryF[vn.an]
vsim.npat <- rep(n, nsim)
for (i in 1:nsim) {
stopF <- stopE <- 0
posE.last <- 0
response <- rbinom(size = 1, prob = p, n = n)
response.cum <- cumsum(response)
for (j in 1:n.an) {
npat <- vn.an[j]
if (response.cum[npat] >= (v.critE[j] - 0.5)) {
nposE[j] <- nposE[j] + 1
if (j == n.an) posE.last <- 1
if (eff.stop == 'y') {
vsim.npat[i] <- npat
stopE <- 1
nstopE[j] <- nstopE[j] + 1
}
}
if (response.cum[npat] <= (v.critF[j] + 0.5)) {
stopF <- 1
vsim.npat[i] <- npat
nstopF[j] <- nstopF[j] + 1
}
if ((j == n.an) && (posE.last + stopF == 0)) n.inconclus <- n.inconclus + 1
if (((stopE == 1) && (eff.stop == 'y')) || (stopF == 1)) break
}
}
prob.eff <- round(nposE/nsim, digits = 4)
prob.effstop <- round(nstopE/nsim, digits = 4)
prob.futilstop <- round(nstopF/nsim, digits = 4)
prob.effstop.cum <- round(cumsum(prob.effstop), digits = 4)
prob.futilstop.cum <- round(cumsum(prob.futilstop), digits = 4)
mean.npat <- round(mean(vsim.npat), digits = 1)
prob.inconclus <- round(n.inconclus/nsim, digits = 4)
if (eff.stop == 'y') {
return(list(prob.effstop, prob.effstop.cum, prob.futilstop, prob.futilstop.cum, mean.npat, prob.inconclus))
}
else {
return(list(prob.eff, prob.futilstop, prob.futilstop.cum, mean.npat, prob.inconclus))
}
}
|
mon_num_below <- function(var, thld = 0, infile, outfile, nc34 = 4, overwrite = FALSE,
verbose = FALSE, nc = NULL) {
mon_num_wrapper(2, var, thld, infile, outfile, nc34, overwrite, verbose, nc = nc)
}
|
random_force <- structure(list(
xmin = NULL,
xmax = NULL,
ymin = NULL,
ymax = NULL
), class = c('random_force', 'force'))
print.random_force <- function(x, ...) {
cat('Random Force:\n')
cat('* A force that modifies the velocity randomly at each step\n')
}
train_force.random_force <- function(force, particles, xmin = -1, xmax = 1, ymin = -1, ymax = 1, ...) {
force <- NextMethod()
force$xmin <- xmin
force$xmax <- xmax
force$ymin <- ymin
force$ymax <- ymax
force
}
retrain_force.random_force <- function(force, particles, ...) {
dots <- quos(...)
particle_hash <- digest(particles)
new_particles <- particle_hash != force$particle_hash
force$particle_hash <- particle_hash
nodes <- as_tibble(particles, active = 'nodes')
force <- update_quo(force, 'include', dots, nodes, new_particles, TRUE)
force <- update_unquo(force, 'xmin', dots)
force <- update_unquo(force, 'xmax', dots)
force <- update_unquo(force, 'ymin', dots)
force <- update_unquo(force, 'ymax', dots)
force
}
apply_force.random_force <- function(force, particles, pos, vel, alpha, ...) {
vel[, 1] <- vel[, 1] + runif(nrow(vel), force$xmin, force$xmax) * alpha
vel[, 2] <- vel[, 2] + runif(nrow(vel), force$ymin, force$ymax) * alpha
list(position = pos, velocity = vel)
}
|
ISODigitalTransferOptions <- R6Class("ISODigitalTransferOptions",
inherit = ISOAbstractObject,
private = list(
xmlElement = "MD_DigitalTransferOptions",
xmlNamespacePrefix = "GMD"
),
public = list(
unitsOfDistribution = NULL,
transferSize = NULL,
onLine = list(),
offLine = list(),
initialize = function(xml = NULL){
super$initialize(xml = xml)
},
setUnitsOfDistribution = function(unit){
self$unitsOfDistribution = unit
},
setTransferSize = function(transferSize){
self$transferSize = as.numeric(transferSize)
},
addOnlineResource = function(onlineResource){
if(!is(onlineResource, "ISOOnlineResource")){
stop("The argument should be a 'ISOOnlineResource' object")
}
return(self$addListElement("onLine", onlineResource))
},
setOnlineResource = function(onlineResource){
self$onLine <- list()
return(self$addOnlineResource(onlineResource))
},
delOnlineResource = function(onlineResource){
if(!is(onlineResource, "ISOOnlineResource")){
stop("The argument should be a 'ISOOnlineResource' object")
}
return(self$delListElement("onLine", onlineResource))
},
addOfflineResource = function(offlineResource){
if(!is(offlineResource, "ISOMedium")){
stop("The argument should be a 'ISOMedium' object")
}
return(self$addListElement("offLine", offlineResource))
},
setOfflineResource = function(offlineResource){
self$offLine <- list()
return(self$addOfflineResource(offlineResource))
},
delOfflineResource = function(offlineResource){
if(!is(offlineResource, "ISOMedium")){
stop("The argument should be a 'ISOMedium' object")
}
return(self$delListElement("offLine", offlineResource))
}
)
)
|
logdmultinom <-
function (x, size, prob)
{
lgamma(size + 1) + sum(x * log(prob) - lgamma(x + 1))
}
|
pxweb_metadata <- function(x){
if(is.null(x$title)) {
x$title <- NA
}
checkmate::assert_names(names(x), must.include = "variables")
for(i in seq_along(x$variables)){
if(all(c("values", "valueTexts") %in% names(x$variables[[i]]))){
checkmate::assert_names(names(x$variables[[i]]), must.include = c("values", "valueTexts"))
x$variables[[i]]$values <- unlist(x$variables[[i]]$values)
x$variables[[i]]$valueTexts <- unlist(x$variables[[i]]$valueTexts)
}
if(is.null(x$variables[[i]]$elimination)) x$variables[[i]]$elimination <- FALSE
if(is.null(x$variables[[i]]$time)) x$variables[[i]]$time <- FALSE
}
class(x) <- c("pxweb_metadata", "list")
assert_pxweb_metadata(x)
x
}
assert_pxweb_metadata <- function(x){
checkmate::assert_class(x, c("pxweb_metadata", "list"))
checkmate::assert_names(names(x), must.include = c("title", "variables"))
checkmate::assert_string(x$title, na.ok = TRUE)
for(i in seq_along(x$variables)){
checkmate::assert_names(names(x$variables[[i]]), must.include = c("code", "text", "elimination", "time"), .var.name = paste0("names(x$variables[[", i, "]])"))
checkmate::assert_string(x$variables[[i]]$code, .var.name = paste0("x$variables[[", i, "]]$code"))
checkmate::assert_string(x$variables[[i]]$text, .var.name = paste0("x$variables[[", i, "]]$text"))
if(!is.null(x$variables[[i]]$values)){
checkmate::assert_character(x$variables[[i]]$values, .var.name = paste0("x$variables[[", i, "]]$values"))
checkmate::assert_character(x$variables[[i]]$valueTexts, len = length(unlist(x$variables[[i]]$values)) , .var.name = paste0("x$variables[[", i, "]]$valueTexts"))
}
checkmate::assert_flag(x$variables[[i]]$time, .var.name = paste0("x$variables[[", i, "]]$time"))
checkmate::assert_flag(x$variables[[i]]$elimination, .var.name = paste0("x$variables[[", i, "]]$elimination"))
}
}
print.pxweb_metadata <- function(x, ...){
cat("PXWEB METADATA\n")
cat(x$title, "\n")
cat("variables:\n")
for(i in seq_along(x$variables)){
cat(" [[", i ,"]] ", x$variables[[i]]$code,": ", x$variables[[i]]$text, "\n", sep = "")
}
}
pxweb_metadata_elimination <- function(pxmd){
checkmate::assert_class(pxmd, "pxweb_metadata")
res <- unlist(lapply(pxmd$variables,function(x) x$elimination))
names(res) <- unlist(lapply(pxmd$variables,function(x) x$code))
res
}
pxweb_metadata_time <- function(pxmd){
checkmate::assert_class(pxmd, "pxweb_metadata")
res <- unlist(lapply(pxmd$variables,function(x) x$time))
names(res) <- unlist(lapply(pxmd$variables,function(x) x$code))
res
}
pxweb_metadata_dim <- function(pxmd){
checkmate::assert_class(pxmd, "pxweb_metadata")
dim_res <- numeric(length(pxmd$variables))
for(i in seq_along(pxmd$variables)){
names(dim_res)[i] <- pxmd$variables[[i]]$code
dim_res[i] <- length(pxmd$variables[[i]]$values)
}
dim_res
}
|
simple_function <- function(a, b) {
x <- b + 1
a + x
}
|
OurConf <- function(samples = 100, n = 30, mu = 0, sigma = 1, conf.level = 0.95) {
alpha <- 1 - conf.level
CL <- conf.level * 100
n <- round(n)
N <- round(samples)
if (N <= 0 || n <= 1) {
stop("Number of random samples and sample size must both be at least 2")
}
if (!missing(conf.level) && (length(conf.level) != 1 || !is.finite(conf.level) ||
conf.level <= 0 || conf.level >= 1)) {
stop("'conf.level' must be a single number between 0 and 1")
}
if (sigma <= 0) {
stop("Variance must be a positive value")
}
junk <- rnorm(N * n, mu, sigma)
jmat <- matrix(junk, N, n)
xbar <- apply(jmat, 1, mean)
ll <- xbar - qnorm(1 - alpha / 2) * sigma / sqrt(n)
ul <- xbar + qnorm(1 - alpha / 2) * sigma / sqrt(n)
notin <- sum((ll > mu) + (ul < mu))
percentage <- round((1 - notin / N) * 100, 2)
data <- data.frame(xbar = xbar, ll = ll, ul = ul)
data$samplenumb <- factor(as.integer(rownames(data)))
data$correct <- "Includes"
data$correct[data$ul < mu] <- "Low"
data$correct[data$ll > mu] <- "High"
bestfit <- function(NN = N) {
list(
scale_y_continuous(limits = c((mu - 2 * sigma), (mu + 2 * sigma))),
if (NN >= 51) {
scale_x_discrete(breaks = seq(0, 500, 10))
}
)
}
p <- ggplot(data, aes(y = xbar, x = samplenumb)) +
geom_point() +
geom_hline(yintercept = mu) +
geom_errorbar(aes(ymin = ll, ymax = ul, color = correct), width = 0.3) +
labs(
title = bquote(.(N) ~ "random samples with" ~ .(CL) * "% confidence intervals where" ~ mu ~ "=" ~ .(mu) ~ "and" ~ sigma ~ "=" ~ .(sigma)),
subtitle = bquote("Note:" ~ .(percentage) * "% of the confidence intervals contain" ~ mu ~ "=" ~ .(mu)),
y = expression("Sample mean" ~ (bar(X))),
x = paste0("Random samples of size = ", n),
caption = ("modified from the CIsim function in package BSDA")
) +
bestfit() +
guides(color = guide_legend(title = NULL)) +
theme_bw()
print(p)
cat(percentage, "% of the confidence intervals contain Mu =", mu, ".", "\n")
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.