code
stringlengths 1
13.8M
|
---|
tolIntNormN <-
function (half.width, sigma.hat = 1, coverage = 0.95, cov.type = "content",
conf.level = 0.95, method = "wald.wolfowitz", round.up = TRUE,
n.max = 5000, tol = 1e-07, maxiter = 1000)
{
cov.type <- match.arg(cov.type, c("content", "expectation"))
method <- match.arg(method, c("exact", "wald.wolfowitz"))
if (method != "wald.wolfowitz")
stop("Currently only method='wald.wolfowitz' is allowed.")
if (!is.vector(half.width, mode = "numeric") || !all(is.finite(half.width)) ||
any(half.width <= .Machine$double.eps))
stop(paste("'half.width' must be a numeric vector", "with all positive elements",
"and no Missing (NA), Infinite(-Inf, Inf),", "or Undefined (Nan) values."))
if (!is.vector(sigma.hat, mode = "numeric") || !all(is.finite(sigma.hat)) ||
any(sigma.hat < .Machine$double.eps))
stop(paste("'sigma.hat' must be a numeric vector", "with all positive elements",
"and no Missing (NA), Infinite(-Inf, Inf),", "or Undefined (Nan) values."))
if (!is.vector(coverage, mode = "numeric") || !all(is.finite(coverage)) ||
any(coverage <= .Machine$double.eps) || any(coverage >=
1 - .Machine$double.eps))
stop(paste("'coverage' must be a numeric vector", "with all elements between 0 and 1",
"and no Missing (NA), Infinite(-Inf, Inf),", "or Undefined (Nan) values."))
if (!is.vector(n.max, mode = "numeric") || length(n.max) !=
1 || !is.finite(n.max) || n.max != trunc(n.max) || n.max <
2)
stop("'n.max' must be a positive integer greater than 1")
if (!is.vector(maxiter, mode = "numeric") || length(maxiter) !=
1 || !is.finite(maxiter) || maxiter != trunc(maxiter) ||
maxiter < 2)
stop("'maxiter' must be a positive integer greater than 1")
if (cov.type == "content") {
if (!is.vector(conf.level, mode = "numeric") || !all(is.finite(conf.level)) ||
any(conf.level <= .Machine$double.eps) || any(conf.level >=
1 - .Machine$double.eps))
stop(paste("'conf.level' must be a numeric vector",
"with all elements between 0 and 1", "and no Missing (NA), Infinite(-Inf, Inf),",
"or Undefined (Nan) values."))
arg.mat <- cbind.no.warn(half.width = as.vector(half.width),
sigma.hat = as.vector(sigma.hat), coverage = as.vector(coverage),
conf.level = as.vector(conf.level))
for (i in c("half.width", "sigma.hat", "coverage", "conf.level")) assign(i,
arg.mat[, i])
N <- length(half.width)
n.vec <- numeric(N)
fcn.for.root <- function(n, hw, sigma.hat, coverage,
conf.level, method) {
hw - tolIntNormHalfWidth(n = n, sigma.hat = sigma.hat,
coverage = coverage, cov.type = "content", conf.level = conf.level,
method = method)
}
hw.2 <- tolIntNormHalfWidth(n = 2, sigma.hat = sigma.hat,
coverage = coverage, cov.type = "content", conf.level = conf.level,
method = method)
hw.n.max <- tolIntNormHalfWidth(n = n.max, sigma.hat = sigma.hat,
coverage = coverage, cov.type = "content", conf.level = conf.level,
method = method)
for (i in 1:N) {
hw.i <- half.width[i]
hw.2.i <- hw.2[i]
hw.n.max.i <- hw.n.max[i]
if (hw.2.i <= hw.i) {
n.vec[i] <- 2
}
else {
if (hw.n.max.i > hw.i) {
n.vec[i] <- NA
warning(paste("Value of 'half.width' is too small",
"for element", i, ". Try increasing the value of 'n.max'.",
sep = ""))
}
else {
sigma.hat.i <- sigma.hat[i]
coverage.i <- coverage[i]
conf.level.i <- conf.level[i]
n.vec[i] <- uniroot(fcn.for.root, lower = 2,
upper = n.max, f.lower = hw.i - hw.2.i, f.upper = hw.i -
hw.n.max.i, hw = hw.i, sigma.hat = sigma.hat.i,
coverage = coverage.i, conf.level = conf.level.i,
method = method, tol = tol, maxiter = maxiter)$root
}
}
}
if (round.up)
n.vec <- ceiling(n.vec)
ret.val <- n.vec
names(ret.val) <- NULL
}
else {
ret.val <- predIntNormN(half.width = half.width, k = 1,
n.mean = 1, sigma.hat = sigma.hat, conf.level = coverage,
round.up = round.up, n.max = n.max, tol = tol, maxiter = maxiter)
}
ret.val
} |
cmaRs.mosek_optimization <- function (i, numBF, sqrtz,
Tm, l, alpha, z, L, t, BasisFunctions, n, D, y)
{
cqo1 <- list(sense = "min")
cqo1$c <- rbind(1, matrix(0, nrow <- 2 * numBF + n + 2, ncol <- 1))
cqo1$A <- Matrix(D, sparse = TRUE)
blc <- c(t(y), matrix(0, nrow <- 1, ncol <- numBF))
buc <- c(t(y), matrix(0, nrow <- 1, ncol <- numBF))
cqo1$bc <- rbind (blc, buc)
ppp <- c(0)
for (j in 2:(2 * numBF + n + 2))
{
ppp <- c(ppp, -Inf)
}
qqq <- c(Inf)
for (j in 2 : (2 * numBF + n + 2))
{
qqq <- c(qqq, Inf)
}
blx <- c(ppp, sqrtz[i])
bux <- c(qqq, sqrtz[i])
cqo1$bx <- rbind (blx, bux)
numcones <- 2
cqo1$cones <- matrix (list (), nrow <- 2, ncol <- numcones)
rownames(cqo1$cones) <- c("type", "sub")
concones1 <- c(1, (numBF+3) : (numBF + n + 2))
cqo1$cones[ ,1] <- list ("QUAD", concones1)
concones2 <- c((2 * numBF + n + 3),
(numBF + n + 3) : (2 * numBF + n + 2))
cqo1$cones [ ,2] <- list ("QUAD", concones2)
r <- mosek(cqo1)
ans <- r$sol$itr$xx
Theta <- ans[2 : (numBF + 2)]
Tm <- rbind(Tm, Theta)
l <- length(which((abs(Theta) > 0.001))) - 1
alpha <- c(alpha, l)
m <- BasisFunctions %*% Theta
z <- c(z, sqrt(t((y - m)) %*% (y - m)))
zz <- t(z)
a <- L %*% Theta
t <- c(t, sqrt(t(a) %*% a))
tt <- t(t)
return(list(Theta = Theta, m = m, t = t,
z = z, BasisFunctions = BasisFunctions))
} |
generateSpFromFun <- function(raster.stack, parameters,
rescale = TRUE, formula = NULL,
species.type = "multiplicative", rescale.each.response = TRUE,
plot = FALSE)
{
message("Generating virtual species environmental suitability...\n")
approach <- "response"
if(!(is(raster.stack, "Raster")))
{
stop("raster.stack must be a raster stack object")
}
if(any(is.na(maxValue(raster.stack))))
{
raster.stack <- setMinMax(raster.stack)
}
n.l <- nlayers(raster.stack)
if(n.l != length(parameters))
{stop("Provide as many layers in raster.stack as functions on parameters")}
if(any(!(names(parameters) %in% names(raster.stack)) |
!(names(raster.stack) %in% names(parameters))))
{stop("Layer names and names of parameters must be identical")}
for (i in 1:length(parameters))
{
if(any(!(c("fun", "args") %in% names(parameters[[i]]))))
{stop("The structure of parameters does not seem correct.
Please provide function and arguments for variable '",
names(parameters)[i], "'. See help(generateSpFromFun) for more details.",
sep = "")}
test <- tryCatch(match.fun(parameters[[i]]$fun), error = function(c) "error")
if(!inherits(test, "function"))
{
stop(paste("The function ", parameters[[i]]$fun, " does not exist, please verify spelling.", sep = ""))
}
if(any(!(names(parameters[[i]]$args) %in% names(formals(fun = test)))))
{
stop(paste("Arguments of variable '", names(parameters)[i], "' (",
paste(names(parameters[[i]]$args), collapse = ", "),
") do not match arguments of the associated function\n
List of possible arguments for this function: ",
paste(names(formals(fun = test)), collapse = ", "), sep = ""))
}
rm(test)
}
if(rescale.each.response)
{
message(" - The response to each variable was rescaled between 0 and 1. To
disable, set argument rescale.each.response = FALSE\n")
}
if(rescale)
{
message(" - The final environmental suitability was rescaled between 0 and 1.
To disable, set argument rescale = FALSE\n")
}
suitab.raster <- stack(sapply(names(raster.stack), FUN = function(y)
{
calc(raster.stack[[y]], fun = function(x)
{
do.call(match.fun(parameters[[y]]$fun), args = c(list(x), parameters[[y]]$args))
}
)
}))
for (var in names(raster.stack))
{
parameters[[var]]$min <- raster.stack[[var]]@data@min
parameters[[var]]$max <- raster.stack[[var]]@data@max
}
if(rescale.each.response)
{
suitab.raster <- stack(sapply(names(suitab.raster), function(y)
{
(suitab.raster[[y]] - suitab.raster[[y]]@data@min) / (suitab.raster[[y]]@data@max - suitab.raster[[y]]@data@min)
}))
}
if(is.null(formula))
{
if(species.type == "multiplicative")
{
formula <- paste(names(suitab.raster), collapse = " * ")
suitab.raster <- raster::overlay(suitab.raster, fun = prod)
} else if (species.type == "additive")
{
formula <- paste(names(suitab.raster), collapse = " + ")
suitab.raster <- raster::overlay(suitab.raster, fun = sum)
} else stop("If you do not provide a formula, please choose either species.type = 'additive' or 'multiplicative'")
} else
{
if(any(!(all.vars(reformulate(formula)) %in% names(suitab.raster))))
{
stop("Please verify that the variable names in your formula are correctly spelled")
} else if(any(!(names(suitab.raster) %in% all.vars(reformulate(formula)))))
{
stop("Please verify that your formula contains all the variables of your input raster stack")
} else
{
custom.fun <- NULL
eval(parse(text = paste("custom.fun <- function(",
paste(names(suitab.raster), collapse = ", "),
") {",
formula,
"}"
)))
suitab.raster <- raster::overlay(suitab.raster, fun = custom.fun)
print(formula)
}
}
if(rescale)
{
suitab.raster <- (suitab.raster - suitab.raster@data@min) / (suitab.raster@data@max - suitab.raster@data@min)
}
results <- list(approach = approach,
details = list(variables = names(parameters),
formula = formula,
rescale.each.response = rescale.each.response,
rescale = rescale,
parameters = parameters),
suitab.raster = suitab.raster
)
if(plot)
{
plot(results$suitab.raster, main = "Environmental suitability of the virtual species")
}
class(results) <- append("virtualspecies", class(results))
return(results)
} |
ui.dispColor <- function() {
tabItem(
tabName = "dispColor",
fluidRow(
box(
title = "Color/Format Options", status = "primary", solidHeader = TRUE, width = 12,
plotOutput("plotDisplay")
),
column(12, actionButton("display_redraw", "Redraw display"))
)
)
}
ui.dispSp <- function() {
tabItem(
tabName = "dispSp",
fluidRow(
box(
title = "Species Information", status = "primary", solidHeader = TRUE, width = 12,
radioButtons("sp_type", "Select species codes to display",
choices = list("Mammals" = 1, "Turtles" = 2, "All" = 3)),
textOutput("sp_message"),
conditionalPanel(condition = "input.sp_type == 1", dataTableOutput("sp1")),
conditionalPanel(condition = "input.sp_type == 2", dataTableOutput("sp2")),
conditionalPanel(condition = "input.sp_type == 3", dataTableOutput("sp3"))
)
)
)
}
ui.dispManual <- function() {
tabItem(
tabName = "dispManual",
tags$h5("The height of the manual window is controlled by the 'Map height' input in the sidebar. ",
"If the manual opens in a separate window, you can click 'Open in Browser' to display manual in-app"),
uiOutput("manual_out")
)
} |
SDMXSchema <- function(xmlObj, namespaces) {
new("SDMXSchema", version = version.SDMXSchema(xmlObj, namespaces));
}
version.SDMXSchema <- function(xmlObj, namespaces){
schemaVersion <- NULL
for(i in 1:nrow(namespaces)){
parsed <- strsplit(namespaces$uri[i],"/")[[1]];
if(tolower(parsed[3]) == "www.sdmx.org"){
schemaVersion <- gsub("_",".",substr(parsed[substr(parsed,0,1)=="v"],2,nchar(parsed,"w")));
break;
}
}
return(schemaVersion);
} |
data(NouraguesHD)
data(KarnatakaForest)
HDmodel <- modelHD(D = NouraguesHD$D, H = NouraguesHD$H, method = "log2")
KarnatakaWD <- suppressMessages(getWoodDensity(KarnatakaForest$genus, KarnatakaForest$species,
stand = KarnatakaForest$plotId
))
filt <- KarnatakaForest$plotId %in% c("BSP20", "BSP14")
resultMC <- AGBmonteCarlo(
D = KarnatakaForest$D[filt], WD = KarnatakaWD$meanWD[filt],
errWD = KarnatakaWD$sdWD[filt], HDmodel = HDmodel
)
plot <- KarnatakaForest$plotId[ filt ]
context("summary by plot")
test_that("summary by plot", {
sum <- summaryByPlot(resultMC$AGB_simu, plot)
expect_equal(sum, summaryByPlot(resultMC, plot))
expect_is(sum, "data.frame")
expect_equal(nrow(sum), length(unique(plot)))
expect_equal(ncol(sum), 4)
expect_equal(colnames(sum), c("plot", "AGB", "Cred_2.5", "Cred_97.5"))
plot[ sample(1:length(plot), 100) ] <- NA
expect_failure(expect_equal(sum, summaryByPlot(resultMC$AGB_simu, plot)))
})
test_that("summary by plot with the vector", {
H <- predictHeight(D = KarnatakaForest$D[filt], model = HDmodel)
resultAGB <- computeAGB(D = KarnatakaForest$D[filt], WD = KarnatakaWD$meanWD[filt], H = H)
sum <- summaryByPlot(resultAGB, plot)
expect_is(sum, "data.frame")
expect_length(unique(plot), nrow(sum))
expect_equal(ncol(sum), 2)
plot[ sample(1:length(plot), 100) ] <- NA
expect_failure(expect_equal(sum, summaryByPlot(resultAGB, plot)))
expect_equal(nrow(summaryByPlot(resultAGB, plot)), length(unique(plot)) - 1)
})
test_that("summary by plot error", {
expect_error(
summaryByPlot(resultMC$AGB_simu, plot[1:10]),
"vector"
)
expect_error(
summaryByPlot(as.data.frame(resultMC$AGB_simu), plot),
"matrix"
)
}) |
survDabrowska = function(X, Y, deltaX, deltaY){
data = data.frame(X = X, Y = Y, deltaX = deltaX, deltaY = deltaY)
if(any(!c("X", "Y", "deltaX", "deltaY") %in% names(data))) stop("data.frame data has to contain the following variables: X, Y, deltaX, deltaY")
if(nrow(data)<2) stop("Not enough data")
X = data[,"X"]
Y = data[,"Y"]
deltaX = data[,"deltaX"]
deltaY = data[,"deltaY"]
if(any(X<=0) | any(Y<=0)) stop("'X' and 'Y' should be positive.")
Sx = myOwnKM(time = X, delta = data[,"deltaX"])
Sy = myOwnKM(time = Y, delta = data[,"deltaY"])
SxUnique = unique(Sx[order(Sx$time), c("time", "KM")])
SyUnique = unique(Sy[order(Sy$time), c("time", "KM")])
nX = nY = length(X)
uniqueTimeX = unique(unlist(X))
uniqueTimeY = unique(unlist(Y))
numXTimes = length(uniqueTimeX)
numYTimes = length(uniqueTimeY)
Lam = matrix(NA, nrow=numXTimes, ncol=numYTimes)
LamX = matrix(NA, nrow=numXTimes, ncol=numYTimes)
LamY = matrix(NA, nrow=numXTimes, ncol=numYTimes)
XEventMatr = matrix(NA, nrow=numXTimes, ncol=nX)
YEventMatr = matrix(NA, nrow=numYTimes, ncol=nY)
XAtRiskMatr = matrix(NA, nrow=numXTimes, ncol=nX)
YAtRiskMatr = matrix(NA, nrow=numYTimes, ncol=nY)
for(i in 1:nX){
XAtRiskMatr[,i] = (X[i] >= uniqueTimeX)
YAtRiskMatr[,i] = (Y[i] >= uniqueTimeY)
XEventMatr[,i] = (X[i] == uniqueTimeX)*deltaX[i]
YEventMatr[,i] = (Y[i] == uniqueTimeY)*deltaY[i]
}
atRiskMatr = XAtRiskMatr %*% t(YAtRiskMatr)
M11 = XEventMatr %*% t(YEventMatr)
M10 = XEventMatr %*% t(YAtRiskMatr)
M01 = XAtRiskMatr %*% t(YEventMatr)
Lam = M11/atRiskMatr
LamX = M10 /atRiskMatr
LamY = M01 /atRiskMatr
bigL = (LamX*LamY - Lam)/((1 - LamX)*(1 - LamY))
indicesX = data.frame(rowNames = uniqueTimeX, rowIndex = 1:length(uniqueTimeX))
indicesY = data.frame(colNames = uniqueTimeY, colIndex = 1:length(uniqueTimeY))
indicesX = indicesX[order(uniqueTimeX), ]
indicesY = indicesY[order(uniqueTimeY), ]
DabrowskaEstNew = matrix(NA, nrow=numXTimes+1, ncol=numYTimes+1)
DabrowskaEstNew[1, 1] = 1
DabrowskaEstNew[2:nrow(DabrowskaEstNew), 1] = SxUnique["KM"][,1]
DabrowskaEstNew[1, 2:ncol(DabrowskaEstNew)] = SyUnique["KM"][,1]
colnames(DabrowskaEstNew) = c("0", indicesY$colNames)
rownames(DabrowskaEstNew) = c("0", indicesX$rowNames)
DabrowskaCDF = 1 - DabrowskaEstNew
subBigLNonMiss = 1 - bigL
subBigLNonMiss[is.na(subBigLNonMiss)] = 1
rowInd = indicesX$rowIndex
colInd = indicesY$colIndex
for (i in 1:numXTimes){
for (j in 1:numYTimes){
DabrowskaEstNew[i+1, j+1] = (DabrowskaEstNew[i, j+1] * DabrowskaEstNew[i+1, j] / DabrowskaEstNew[i, j]) * subBigLNonMiss[rowInd[i], colInd[j]]
}
}
DabrowskaEstNew[is.na(DabrowskaEstNew)] = 0
DabrowskaCDF = 1 + DabrowskaEstNew - matrix(DabrowskaEstNew[1, ], nrow = nrow(DabrowskaEstNew), ncol = ncol(DabrowskaEstNew), byrow = TRUE) -
matrix(DabrowskaEstNew[, 1], nrow = nrow(DabrowskaEstNew), ncol = ncol(DabrowskaEstNew))
DabrowskaCDF[1, ] = 1 - DabrowskaEstNew[1, ]
DabrowskaCDF[ ,1] = 1 - DabrowskaEstNew[ ,1]
list(DabrowskaEst = DabrowskaEstNew, DabrowskaCDF = DabrowskaCDF)
} |
grid_arrange_shared_legend <- function(plots, ncol = length(plots), nrow = 1,
position = c("bottom", "right")) {
position <- match.arg(position)
g <- ggplot2::ggplotGrob(plots[[1]] + ggplot2::theme(legend.position = position))$grobs
gb <- sapply(g, function(x) x$name) == "guide-box"
if (!all(!gb)) {
legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
lheight <- sum(legend$height)
lwidth <- sum(legend$width)
}
gl <- lapply(plots, function(x) x + ggplot2::theme(legend.position="none"))
if (!all(!gb)) gl <- c(gl, ncol = ncol, nrow = nrow)
if (!all(!gb)) {
if (position == "bottom") {
hei <- grid::unit.c(grid::unit(1, "npc") - lheight, lheight)
combined <- gridExtra::arrangeGrob(do.call(gridExtra::arrangeGrob, gl),
legend, ncol = 1,
heights = hei)
} else if (position == "right") {
wid <- grid::unit.c(grid::unit(1, "npc") - lwidth, lwidth)
combined <- gridExtra::arrangeGrob(do.call(gridExtra::arrangeGrob, gl),
legend, ncol = 2,
widths = wid)
}
} else {
if (length(gl) == 2) {
combined <- gridExtra::grid.arrange(gl[[1]], gl[[2]], ncol = 2, nrow = 1)
} else {
combined <- gridExtra::arrangeGrob(do.call(gridExtra::arrangeGrob, gl),
ncol = 1, nrow = 1)
}
}
grid::grid.newpage()
grid::grid.draw(combined)
invisible(combined)
} |
set.seed(1234)
test_that("non-confounder functions work", {
counts <- ipi %>%
metaconfoundr() %>%
count_non_confounders()
expect_length(counts, 2)
expect_named(counts, c("study", "n_non_confounders"))
expect_equal(nrow(counts), dplyr::n_distinct(metaconfoundr(ipi)$study))
p11 <- ipi %>%
metaconfoundr() %>%
plot_non_confounders()
p12 <- ipi %>%
metaconfoundr() %>%
plot_non_confounders(size = 3, geom = ggplot2::geom_point)
vdiffr::expect_doppelganger("Non confounder count: bar", p11)
vdiffr::expect_doppelganger("Non confounder count: point", p12)
}) |
.isMassObjectList <- function(x) {
if (!is.list(x)) {
return(FALSE)
}
length(x) && all(unname(vapply(x, .isMassObject, logical(1L))))
}
.stopIfNotIsMassObjectList <- function(x) {
if (!.isMassObjectList(x)) {
parentCall <- deparse(sys.call(-1L))
stop(parentCall, " : ", sQuote(deparse(substitute(x))),
" is no list of MALDIquant::AbstractMassObject objects!", call.=FALSE)
}
TRUE
}
isMassSpectrumList <- function(x) {
if (!is.list(x)) {
return(FALSE)
}
length(x) && all(unname(vapply(x, isMassSpectrum, logical(1L))))
}
.stopIfNotIsMassSpectrumList <- function(x) {
if (!isMassSpectrumList(x)) {
parentCall <- deparse(sys.call(-1L))
stop(parentCall, " : ", sQuote(deparse(substitute(x))),
" is no list of MALDIquant::MassSpectrum objects!", call.=FALSE)
}
TRUE
}
isMassPeaksList <- function(x) {
if (!is.list(x)) {
return(FALSE)
}
length(x) && all(unname(vapply(x, isMassPeaks, logical(1L))))
}
.stopIfNotIsMassPeaksList <- function(x) {
if (!isMassPeaksList(x)) {
parentCall <- deparse(sys.call(-1L))
stop(parentCall, " : ", sQuote(deparse(substitute(x))),
" is no list of MALDIquant::MassPeaks objects!", call.=FALSE)
}
TRUE
} |
function(x, y, z) {
3 + 1
} |
summary.PA_result <- function(object,...){
cat("\nContaining the estimated attachment function. \n");
cat("Number of bins:", object$g,"\n");
cat("Estimated attachment exponent:", object$alpha, "\n");
if (object$ci[1] == "N") {
cat("No possible confidence interval for the estimated attachment exponent.\n");
} else cat("Attachment exponent ","\u00B1", " 2 s.d.", ": (", object$ci[1], ",",
object$ci[2],")\n",sep = "");
} |
.prepare.fs.interaction <- function(x, data = NULL, label = "",
n = 100, xlab = NULL, ylab = NULL, main = NULL,
ylim = NULL, xlim = NULL, ...) {
if (x$dim > 1){
stop("no method for base smooth dim > 1")
}
raw <- data[x$base$term][[1]]
if (is.null(xlim)){ xlim <- range(raw) }
xx <- seq(xlim[1], xlim[2], length = n)
nf <- length(x$flev)
fac <- rep(x$flev, rep(n, nf))
dat <- data.frame(as.factor(fac), xx)
names(dat) <- c(x$fterm, x$base$term)
X <- PredictMat(x, dat)
xlabel <- if (is.null(xlab)) x$base$term else xlab
ylabel <- if (is.null(ylab)) label else ylab
return(list(
X = X, scale = TRUE, se = FALSE, raw = raw, xlim = xlim, ylim = ylim,
xlab = xlabel, ylab = ylabel, main = main, x = xx, n = n, nf = nf
))
} |
info <- function(...) {
dots <- list(...)
if(length(dots) == 0) {stop ("You need to pass a corpus object or a transcript object to this function.")}
x <- NULL
t <- NULL
if (class(dots[[1]])=="corpus") {
x <- dots[[1]]
} else if (class(dots[[1]])=="transcript" ) {
t <- dots[[1]]
} else {
stop ("You need to pass a corpus object or a transcript object to this function. ")
}
if (!is.null(x)) {
transcripts <- data.frame(
transcript.name =character(),
length.sec =double(),
length.formatted =character(),
tier.count =integer(),
annotations.count =integer(),
words.org.count =integer(),
words.norm.count =integer(),
path =character(),
file.encoding =character(),
import.result =character(),
load.message =character(),
media.path.count =integer(),
modification.systime =character(),
stringsAsFactors =FALSE
)
if (length(x@transcripts)>0) {
for (i in 1:length(x@transcripts)) {
content.org <- x@transcripts[[i]]@annotations$content
words.org.count <- lapply(content.org, FUN=stringr::str_count, pattern=options()$act.wordCountRegEx)
words.org.count <- sum(unlist(words.org.count))
content.norm <- x@transcripts[[i]]@annotations$content.norm
words.norm.count <- lapply(content.norm, FUN=stringr::str_count, pattern=options()$act.wordCountRegEx)
words.norm.count <- sum(unlist(words.norm.count))
myRow <- data.frame(
transcript.name = x@transcripts[[i]]@name,
length.sec = as.double(x@transcripts[[i]]@length.sec),
length.formatted = helper_format_time(x@transcripts[[i]]@length.sec),
tier.count = as.integer(nrow(x@transcripts[[i]]@tiers)),
annotations.count = nrow(x@transcripts[[i]]@annotations),
words.org.count = words.org.count,
words.norm.count = words.norm.count,
path = x@transcripts[[i]]@file.path,
file.encoding = x@transcripts[[i]]@file.encoding,
import.result = x@transcripts[[i]]@import.result,
load.message = x@transcripts[[i]]@load.message,
media.path.count = length(x@transcripts[[i]]@media.path),
modification.systime = as.character(x@transcripts[[i]]@modification.systime),
stringsAsFactors = FALSE
)
transcripts[nrow(transcripts)+1,] <- myRow
}
}
rownames(transcripts) <- transcripts$transcript.name
temp <- act::tiers_all(x)
name.unique <- unique(temp$name)
temp2 <- data.frame(tier.name =character(),
tier.count =integer(),
transcript.count =integer(),
transcript.names =character(),
annotations.count =integer(),
words.org.count =integer(),
words.norm.count =integer(),
interval.tier.count =integer(),
interval.transcript.count =integer(),
interval.transcript.names =character(),
interval.annotations.count =integer(),
interval.words.org.count =integer(),
interval.words.norm.count =integer(),
text.tier.count =integer(),
text.transcript.count =integer(),
text.transcript.names =character(),
text.annotations.count =integer(),
text.tiers.words.org.count =integer(),
text.tiers.words.norm.count =integer(),
stringsAsFactors = FALSE)
if (length(name.unique)>0) {
for (i in 1:length(name.unique)) {
tiers.current <- temp[which(temp$name==name.unique[i]),]
tiers.current.interval <- temp[which(temp$name==name.unique[i] & temp$type=="IntervalTier"),]
tiers.current.text <- temp[which(temp$name==name.unique[i] & temp$type=="TextTier"),]
myRow <- data.frame(
tier.name = name.unique[i],
tier.count = nrow(tiers.current),
transcript.count = length(unique(tiers.current$transcript.name)),
transcript.names = paste(unique(tiers.current$transcript.name), sep="|", collapse="|"),
annotations.count = sum(tiers.current$annotations.count),
words.org.count = sum(tiers.current$words.org.count),
words.norm.count = sum(tiers.current$words.norm.count),
interval.tier.count = nrow(tiers.current.interval),
interval.transcript.count = length(unique(tiers.current.interval$transcript.name)),
interval.transcript.names = paste(unique(tiers.current.interval$transcript.name), sep="|", collapse="|"),
interval.annotations.count = sum(tiers.current.interval$annotations.count),
interval.words.org.count = sum(tiers.current.interval$words.org.count),
interval.words.norm.count = sum(tiers.current.interval$words.norm.count),
text.tier.count = nrow(tiers.current.text),
text.transcript.count = length(unique(tiers.current.text$transcript.name)),
text.transcript.names = paste(unique(tiers.current.text$transcript.name), sep="|", collapse="|"),
text.annotations.count = sum(tiers.current.text$annotations.count),
text.tiers.words.org.count = sum(tiers.current.text$words.org.count),
text.tiers.words.norm.count = sum(tiers.current.text$words.norm.count),
stringsAsFactors = FALSE
)
temp2[nrow(temp2)+1,] <- myRow
}
temp2 <- temp2[order(temp2$tier.name),]
}
rownames(temp2) <- temp2$tier.name
info <- list(transcripts=transcripts,
tiers=temp2)
return(info)
}
if (!is.null(t)) {
tier.names <- t@tiers$name
tier.count <- nrow(t@tiers)
tiers.detailed <- t@tiers
for (i in 1:nrow(tiers.detailed)) {
ids <- which(t@annotations$tier.name==tiers.detailed$name[i])
tiers.detailed$annotations.count[i] <- length(ids)
words.org.count <- lapply(t@annotations$content[ids], FUN=stringr::str_count, pattern=options()$act.wordCountRegEx)
tiers.detailed$words.org.count[i] <- sum(unlist(words.org.count))
words.norm.count <- lapply(t@annotations$content.norm[ids], FUN=stringr::str_count, pattern=options()$act.wordCountRegEx)
tiers.detailed$words.norm.count[i] <- sum(unlist(words.norm.count))
}
annotations.count <- sum(nrow(t@annotations))
words.org.count <- lapply(t@annotations$content, FUN=stringr::str_count, pattern=options()$act.wordCountRegEx)
words.org.count <- sum(unlist(words.org.count))
words.norm.count <- lapply(t@annotations$content.norm, FUN=stringr::str_count, pattern=options()$act.wordCountRegEx)
words.norm.count <- sum(unlist(words.norm.count))
info <- list(length.formatted = helper_format_time([email protected]),
length.sec = [email protected],
words.org.count = words.org.count,
words.norm.count = words.norm.count,
annotations.count = annotations.count,
tier.count = tier.count,
tier.names = tier.names,
tiers.detailed = tiers.detailed
)
return(info)
}
} |
pcrboot <- function(
object,
type = c("boot", "jack"),
B = 100,
njack = 1,
plot = TRUE,
do.eff = TRUE,
conf = 0.95,
verbose = TRUE,
...)
{
type <- match.arg(type)
if (class(object)[1] != "pcrfit") stop("Use only with objects of class 'pcrfit'!")
fetchDATA <- fetchData(object)
DATA <- fetchDATA$data
PRED.pos <- fetchDATA$pred.pos
RESP.pos <- fetchDATA$resp.pos
PRED.name <- fetchDATA$pred.name
fitted1 <- fitted(object)
resid1 <- residuals(object)
modLIST <- vector("list", length = B)
effLIST <- vector("list", length = B)
NR <- nrow(DATA)
noCONV <- 0
for (i in 1:B) {
newDATA <- DATA
if (verbose) {
counter(i)
flush.console()
}
if (type == "boot") newDATA[, RESP.pos] <- fitted1 + sample(scale(resid1, scale = FALSE), replace = TRUE)
else {
sampleVec <- sample(1:NR, njack)
newDATA <- newDATA[-sampleVec, ]
}
newMODEL <- try(pcrfit(data = newDATA, cyc = 1, fluo = 2, model = object$MODEL, verbose = FALSE), silent = TRUE)
if (inherits(newMODEL, "try-error")) {
noCONV <- noCONV + 1
next
}
if (plot) plot(newMODEL, ...)
modLIST[[i]] <- list(coef = coef(newMODEL), sigma = summary(newMODEL)$sigma,
rss = sum(residuals(newMODEL)^2),
dfb = abs(coef(newMODEL) - coef(object))/(summary(object)$parameters[, 2]),
gof = pcrGOF(newMODEL))
if (do.eff) {
EFF <- try(efficiency(newMODEL, plot = FALSE, ...)[c(1, 7:18)], silent = TRUE)
if (inherits(EFF, "try-error")) effLIST[[i]] <- NA else effLIST[[i]] <- EFF
}
}
cat("\n\n")
if (verbose) cat("fitting converged in ", 100 - (noCONV/B), "% of iterations.\n\n", sep = "")
COEF <- t(sapply(modLIST, function(z) z$coef))
RSE <- sapply(modLIST, function(z) z$sigma)
RSS <- sapply(modLIST, function(z) z$rss)
GOF <- t(sapply(modLIST, function(z) unlist(z$gof)))
effDAT <- t(sapply(effLIST, function(z) unlist(z)))
statLIST <- list(coef = COEF, rmse = RSE, rss = RSS, gof = GOF, eff = effDAT)
confLIST <- lapply(statLIST, function(x) t(apply(as.data.frame(x), 2, function(y) quantile(y, c((1 - conf)/2, 1 - (1 - conf)/2), na.rm = TRUE))))
if (plot) {
ndata <- sum(rapply(statLIST, function(x) ncol(x)))
par(mfrow = c(6, 5))
par(mar = c(1, 2, 2, 1))
for (i in 1:length(statLIST)) {
temp <- as.data.frame(statLIST[[i]])
if (is.vector(statLIST[[i]])) colnames(temp) <- names(statLIST)[i]
for (j in 1:ncol(temp)) {
if (all(is.na(temp[, j]))) next
COL <- switch(names(statLIST)[i], coef = 2, gof = 3, eff = 4)
boxplot(temp[, j], main = colnames(temp)[j], col.main = COL, outline = FALSE, ...)
abline(h = confLIST[[i]][j, ], col = 2, ...)
}
}
}
return(list(ITER = statLIST, CONF = confLIST))
} |
if(getRversion() >= "2.15.1") utils::globalVariables(c(".", "X.weights.", "ks_diff", "ks.test"))
interplot.lmerMod <- function(m, var1, var2, plot = TRUE, steps = NULL, ci = .95, adjCI = FALSE,hist = FALSE, var2_dt = NA, predPro = FALSE, var2_vals = NULL, point = FALSE, sims = 5000,xmin = NA, xmax = NA, ercolor = NA, esize = 0.5, ralpha = 0.5, rfill = "grey70", stats_cp = "none", txt_caption = NULL, facet_labs = NULL, ...) {
m.class <- class(m)
if(predPro == TRUE) stop("Predicted probability is estimated only for general linear models.")
m.sims <- arm::sim(m, sims)
factor_v1 <- factor_v2 <- FALSE
if (is.factor(eval(parse(text = paste0("m@frame$", var1)))) & is.factor(eval(parse(text = paste0("m@frame$",
var2)))))
stop("The function does not support interactions between two factors.")
if (is.factor(eval(parse(text = paste0("m@frame$", var1))))) {
var1_bk <- var1
var1 <- paste0(var1, levels(eval(parse(text = paste0("m@frame$",
var1)))))
factor_v1 <- TRUE
ifelse(var1 == var2, var12 <- paste0("I(", var1, "^2)"), var12 <- paste0(var2,
":", var1)[-1])
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
var12[i] <- paste0(var1, ":", var2)[-1][i]
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
stop(paste("Model does not include the interaction of",
var1, "and", var2, "."))
}
} else if (is.factor(eval(parse(text = paste0("m@frame$", var2))))) {
var2_bk <- var2
var2 <- paste0(var2, levels(eval(parse(text = paste0("m@frame$",
var2)))))
factor_v2 <- TRUE
ifelse(var1 == var2, var12 <- paste0("I(", var1, "^2)"), var12 <- paste0(var2,
":", var1)[-1])
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
var12[i] <- paste0(var1, ":", var2)[-1][i]
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
stop(paste("Model does not include the interaction of",
var1, "and", var2, "."))
}
} else {
ifelse(var1 == var2, var12 <- paste0("I(", var1, "^2)"), var12 <- paste0(var2,
":", var1))
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
var12[i] <- paste0(var1, ":", var2)[i]
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
stop(paste("Model does not include the interaction of",
var1, "and", var2, "."))
}
}
if (factor_v2) {
xmin <- 0
xmax <- 1
steps <- 2
} else {
if (is.na(xmin))
xmin <- min(m@frame[var2], na.rm = T)
if (is.na(xmax))
xmax <- max(m@frame[var2], na.rm = T)
if (is.null(steps)) {
steps <- eval(parse(text = paste0("length(unique(na.omit(m@frame$",
var2, ")))")))
}
if (steps > 100)
steps <- 100
}
coef <- data.frame(fake = seq(xmin, xmax, length.out = steps), coef1 = NA,
ub = NA, lb = NA)
coef_df <- data.frame(fake = numeric(0), coef1 = numeric(0), ub = numeric(0),
lb = numeric(0), model = character(0))
if (factor_v1) {
for (j in 1:(length(levels(eval(parse(text = paste0("m@frame$",
var1_bk))))) - 1)) {
for (i in 1:steps) {
coef$coef1[i] <- mean(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <- quantile(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))], (1 - ci) / 2)
coef$lb[i] <- quantile(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))], 1 - (1 - ci) / 2)
}
if (plot == TRUE) {
coef$value <- var1[j + 1]
coef_df <- rbind(coef_df, coef)
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
return(coef)
}
}
if (is.null(facet_labs)) facet_labs <- unique(coef_df$value)
coef_df$value <- factor(coef_df$value, labels = facet_labs)
interplot.plot(m = coef_df, hist = hist, var2_dt = var2_dt, point = point,
ercolor = ercolor, esize = esize, ralpha = ralpha, rfill = rfill, ci_diff = ci_diff, ks_diff = ks_diff, stats_cp = stats_cp, txt_caption = txt_caption,
...) + facet_grid(. ~ value)
} else if (factor_v2) {
for (j in 1:(length(levels(eval(parse(text = paste0("m@frame$",
var2_bk))))) - 1)) {
for (i in 1:steps) {
coef$coef1[i] <- mean(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))],
(1 - ci) / 2)
coef$lb[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))],
1 - (1 - ci) / 2)
}
if (plot == TRUE) {
coef$value <- var2[j + 1]
coef_df <- rbind(coef_df, coef)
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
return(coef)
}
}
if (is.null(facet_labs)) facet_labs <- unique(coef_df$value)
coef_df$value <- factor(coef_df$value, labels = facet_labs)
interplot.plot(m = coef_df, hist = hist, var2_dt = var2_dt, point = point,
ercolor = ercolor, esize = esize, ralpha = ralpha, rfill = rfill, ci_diff = ci_diff, ks_diff = ks_diff, stats_cp = stats_cp, txt_caption = txt_caption,
...) + facet_grid(. ~ value)
} else {
multiplier <- if (var1 == var2)
2 else 1
for (i in 1:steps) {
coef$coef1[i] <- mean(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * coef$fake[i] * m.sims@fixef[, match(var12,
unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * coef$fake[i] * m.sims@fixef[, match(var12,
unlist(dimnames(m@pp$X)[2]))], (1 - ci) / 2)
coef$lb[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * coef$fake[i] * m.sims@fixef[, match(var12,
unlist(dimnames(m@pp$X)[2]))], 1 - (1 - ci) / 2)
}
multiplier <- if (var1 == var2)
2 else 1
min_sim <- m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * xmin * m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))]
max_sim <- m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * xmax * m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))]
diff <- max_sim - min_sim
ci_diff <- c(
quantile(diff, (1 - ci) / 2),
quantile(diff, 1 - (1 - ci) / 2)
)
if (plot == TRUE) {
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
interplot.plot(m = coef, hist = hist, var2_dt = var2_dt, point = point,
ercolor = ercolor, esize = esize, ralpha = ralpha, rfill = rfill, ci_diff = ci_diff, ks_diff = ks_diff, stats_cp = stats_cp, txt_caption = txt_caption, ...)
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
return(coef)
}
}
}
interplot.glmerMod <- function(m, var1, var2, plot = TRUE, steps = NULL, ci = .95, adjCI = FALSE, hist = FALSE, var2_dt = NA, predPro = FALSE, var2_vals = NULL, point = FALSE, sims = 5000, xmin = NA, xmax = NA, ercolor = NA, esize = 0.5, ralpha = 0.5, rfill = "grey70", stats_cp = "none", txt_caption = NULL, facet_labs = NULL, ...) {
m.class <- class(m)
m.sims <- arm::sim(m, sims)
factor_v1 <- factor_v2 <- FALSE
if (is.factor(eval(parse(text = paste0("m@frame$", var1)))) & is.factor(eval(parse(text = paste0("m@frame$",
var2)))))
stop("The function does not support interactions between two factors.")
if (is.factor(eval(parse(text = paste0("m@frame$", var1))))) {
var1_bk <- var1
var1 <- paste0(var1, levels(eval(parse(text = paste0("m@frame$",
var1)))))
factor_v1 <- TRUE
ifelse(var1 == var2, var12 <- paste0("I(", var1, "^2)"), var12 <- paste0(var2,
":", var1)[-1])
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
var12[i] <- paste0(var1, ":", var2)[-1][i]
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
stop(paste("Model does not include the interaction of",
var1, "and", var2, "."))
}
} else if (is.factor(eval(parse(text = paste0("m@frame$", var2))))) {
var2_bk <- var2
var2 <- paste0(var2, levels(eval(parse(text = paste0("m@frame$",
var2)))))
factor_v2 <- TRUE
ifelse(var1 == var2, var12 <- paste0("I(", var1, "^2)"), var12 <- paste0(var2,
":", var1)[-1])
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
var12[i] <- paste0(var1, ":", var2)[-1][i]
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
stop(paste("Model does not include the interaction of",
var1, "and", var2, "."))
}
} else {
ifelse(var1 == var2, var12 <- paste0("I(", var1, "^2)"), var12 <- paste0(var2,
":", var1))
for (i in seq(var12)) {
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
var12[i] <- paste0(var1, ":", var2)[i]
if (!var12[i] %in% unlist(dimnames(m@pp$X)[2]))
stop(paste("Model does not include the interaction of",
var1, "and", var2, "."))
}
}
if (factor_v2) {
xmin <- 0
xmax <- 1
steps <- 2
} else {
if (is.na(xmin))
xmin <- min(m@frame[var2], na.rm = T)
if (is.na(xmax))
xmax <- max(m@frame[var2], na.rm = T)
if (is.null(steps)) {
steps <- eval(parse(text = paste0("length(unique(na.omit(m@frame$",
var2, ")))")))
}
if (steps > 100)
steps <- 100
}
coef <- data.frame(fake = seq(xmin, xmax, length.out = steps), coef1 = NA,
ub = NA, lb = NA)
coef_df <- data.frame(fake = numeric(0), coef1 = numeric(0), ub = numeric(0),
lb = numeric(0), model = character(0))
if (factor_v1) {
if(predPro == TRUE) stop("The current version does not support estimating predicted probabilities for factor base terms.")
for (j in 1:(length(levels(eval(parse(text = paste0("m@frame$",
var1_bk))))) - 1)) {
for (i in 1:steps) {
coef$coef1[i] <- mean(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <- quantile(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))], (1 - ci) / 2)
coef$lb[i] <- quantile(m.sims@fixef[, match(var1[j + 1],
unlist(dimnames(m@pp$X)[2]))] + coef$fake[i] * m.sims@fixef[,
match(var12[j], unlist(dimnames(m@pp$X)[2]))], 1 - (1 - ci) / 2)
}
if (plot == TRUE) {
coef$value <- var1[j + 1]
coef_df <- rbind(coef_df, coef)
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
return(coef)
}
}
if (is.null(facet_labs)) facet_labs <- unique(coef_df$value)
coef_df$value <- factor(coef_df$value, labels = facet_labs)
interplot.plot(m = coef_df, hist = hist, steps = steps, var2_dt = var2_dt, point = point,
ercolor = ercolor, esize = esize, ralpha = ralpha, rfill = rfill, stats_cp = "none", txt_caption = NULL,
...) + facet_grid(. ~ value)
} else if (factor_v2) {
if(predPro == TRUE) stop("The current version does not support estimating predicted probabilities for factor base terms.")
for (j in 1:(length(levels(eval(parse(text = paste0("m@frame$",
var2_bk))))) - 1)) {
for (i in 1:steps) {
coef$coef1[i] <- mean(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))],
(1 - ci) / 2)
coef$lb[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
coef$fake[i] * m.sims@fixef[, match(var12[j], unlist(dimnames(m@pp$X)[2]))],
1 - (1 - ci) / 2)
}
if (plot == TRUE) {
coef$value <- var2[j + 1]
coef_df <- rbind(coef_df, coef)
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
return(coef)
}
}
if (is.null(facet_labs)) facet_labs <- unique(coef_df$value)
coef_df$value <- factor(coef_df$value, labels = facet_labs)
interplot.plot(m = coef_df, steps = steps, hist = hist, var2_dt = var2_dt, point = point,
ercolor = ercolor, esize = esize, ralpha = ralpha, rfill = rfill, stats_cp = "none", txt_caption = NULL,
...) + facet_grid(. ~ value)
} else {
if(predPro == TRUE){
if(is.null(var2_vals)) stop("The predicted probabilities cannot be estimated without defining 'var2_vals'.")
df <- data.frame(m$model)
df[[names(m@flist)]] <- NULL
if(sum(grep("X.weights.", names(df))) != 0) df <- select(df, -X.weights.)
df_temp <- select(df, 1)
df <- df[-1] %>%
map(function(var){
if(is.factor(var)){
model.matrix(~ var - 1)[, -1] %>%
as.data.frame()
}else{
as.numeric(var)
}
})
for(i in seq(df)){
if(!is.data.frame(df[[i]])){
namesUpdate <- c(names(df_temp), names(df)[[i]])
df_temp <- cbind(df_temp, df[[i]])
names(df_temp) <- namesUpdate
}else{
df_temp <- cbind(df_temp, df[[i]])
}
}
df <- df_temp
names(df)[1] <- "(Intercept)"
df$`(Intercept)` <- 1
if(var1 == var2){
names(df) <- sub("I\\.(.*)\\.2\\.", "I\\(\\1\\^2\\)", names(df))
}
iv_medians <- summarize_all(df, funs(median(., na.rm = TRUE)))
fake_data <- iv_medians[rep(1:nrow(iv_medians), each=steps*length(var2_vals)), ]
fake_data[[var1]] <- with(df, rep(seq(min(get(var1)), max(get(var1)), length.out=steps),
steps=length(var2_vals)))
fake_data[[var2]] <- rep(var2_vals, each=steps)
fake_data[[var12]] <- fake_data[[var1]] * fake_data[[var2]]
pp <- rowMeans(plogis(data.matrix(fake_data) %*% t(data.matrix(m.sims@fixef))))
row_quantiles <- function (x, probs) {
naValue <- NA
storage.mode(naValue) <- storage.mode(x)
nrow <- nrow(x)
q <- matrix(naValue, nrow = nrow, ncol = length(probs))
if (nrow > 0L) {
t <- quantile(x[1L, ], probs = probs)
colnames(q) <- names(t)
q[1L, ] <- t
if (nrow >= 2L) {
for (rr in 2:nrow) {
q[rr, ] <- quantile(x[rr, ], probs = probs)
}
}
}
else {
t <- quantile(0, probs = probs)
colnames(q) <- names(t)
}
q <- drop(q)
q
}
pp_bounds <- row_quantiles(plogis(data.matrix(fake_data) %*% t(data.matrix(m.sims@fixef))), prob = c((1 - ci)/2, 1 - (1 - ci)/2))
pp <- cbind(pp, pp_bounds)
pp <- pp*100
colnames(pp) <- c("coef1", "lb", "ub")
pp <- cbind(fake_data[, c(var1, var2)], pp)
pp[,var2] <- as.factor(pp[,var2])
names(pp)[1] <- "fake"
names(pp)[2] <- "value"
coef <- pp
} else {
multiplier <- if (var1 == var2)
2 else 1
for (i in 1:steps) {
coef$coef1[i] <- mean(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * coef$fake[i] * m.sims@fixef[, match(var12,
unlist(dimnames(m@pp$X)[2]))])
coef$ub[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * coef$fake[i] * m.sims@fixef[, match(var12,
unlist(dimnames(m@pp$X)[2]))], (1 - ci) / 2)
coef$lb[i] <- quantile(m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * coef$fake[i] * m.sims@fixef[, match(var12,
unlist(dimnames(m@pp$X)[2]))], 1 - (1 - ci) / 2)
}
}
multiplier <- if (var1 == var2)
2 else 1
min_sim <- m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * xmin * m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))]
max_sim <- m.sims@fixef[, match(var1, unlist(dimnames(m@pp$X)[2]))] +
multiplier * xmax * m.sims@fixef[, match(var12, unlist(dimnames(m@pp$X)[2]))]
diff <- max_sim - min_sim
ci_diff <- c(
quantile(diff, (1 - ci) / 2),
quantile(diff, 1 - (1 - ci) / 2)
)
if (plot == TRUE) {
if (hist == TRUE) {
if (is.na(var2_dt)) {
var2_dt <- eval(parse(text = paste0("m@frame$", var2)))
} else {
var2_dt <- var2_dt
}
}
interplot.plot(m = coef, steps = steps, hist = hist, predPro = predPro, var2_vals = var2_vals, var2_dt = var2_dt, point = point, ercolor = ercolor, esize = esize, ralpha = ralpha, rfill = rfill, stats_cp = "none", txt_caption = NULL, ...)
} else {
if(predPro == TRUE){
names(coef) <- c(var2, paste0("values_in_", var1), "coef", "ub", "lb")
} else {
names(coef) <- c(var2, "coef", "ub", "lb")
}
return(coef)
}
}
} |
get_example_filenames <- function(
folder_name = get_default_pureseqtm_folder()
) {
pureseqtmr::check_pureseqtm_installation(folder_name)
pureseqtm_folder <- file.path(folder_name, "PureseqTM_Package")
testthat::expect_true(dir.exists(pureseqtm_folder))
pureseqtm_examples_folder <- file.path(pureseqtm_folder, "example")
testthat::expect_true(dir.exists(pureseqtm_examples_folder))
list.files(
pureseqtm_examples_folder,
full.names = TRUE
)
} |
verifyFunctionReturnTypesDefinition <- function(object_o_1,
requiresFullInstrumentation_b_1 = TRUE) {
buildReturnValue <- function(validity_b, intent_s, msg_s) {
list(validity = validity_b,
check = ifelse(requiresFullInstrumentation_b_1, 'full instrumentation check',
'partial instrumentation check'),
class = getObjectClassNames(object_o_1)$classname,
intent = intent_s,
message = msg_s)
}
mef <- function(x_s) strBracket(strJoin(x_s))
verifyFormat <- function(sof_l) {
brv <- function(validity_b, msg_s) {
buildReturnValue(validity_b, 'function return types information format', msg_s)
}
if (!sof_l$frt)
return(brv(FALSE, paste('no parameter', frtcn, 'definition in class')))
fn <- sof_l$instrumented_fn
if (!data.table::is.data.table(fn))
return(brv(FALSE, paste('parameter', frtcn, 'wrongly instrumented in class. Must be a data.table')))
expected_column_names <- c('function_name', 'return_value')
if (length(setdiff(expected_column_names, colnames(fn))) != 0)
return(brv(FALSE,
paste('wrong column name, got', mef(colnames(fn)),
'expected were', mef(expected_column_names))))
brv(TRUE, 'verified correct')
}
verifyContent <- function(sof_l) {
brv <- function(validity_b, msg_s) {
buildReturnValue(validity_b, 'function return types information content', msg_s)
}
fn <- sof_l$instrumented_fn
if (length(unique(fn$function_name)) != length(fn$function_name))
return(brv(FALSE, 'unicity issue with declared function names'))
ofn <- getObjectFunctionNames(object_o_1)
sd <- setdiff(fn$function_name, ofn)
if (length(sd) != 0)
return(brv(FALSE, paste('unknown function name:', strJoin(strBracket(sd)))))
sd <- setdiff(ofn, fn$function_name)
if (requiresFullInstrumentation_b_1 && length(sd) != 0)
return(brv(FALSE, paste('missing function declarations:', strJoin(strBracket(sd)))))
rv <- unique(fn$return_value)
cv <- sapply(rv, function(e) {
FunctionParameterName(e)$isSemanticName()
}, simplify = FALSE)
if (any(cv == FALSE)) {
w <- which(cv == FALSE)
return(brv(FALSE, paste('wrong return value declaration', strBracket(rv[w]))))
}
brv(TRUE, 'verified correct')
}
sof <- retrieveSupportedObjectInformation(object_o_1)
frtcn <- strBracket(defineFunctionReturnTypesParameterName())
rv <- verifyFormat(sof)
if (!rv$validity)
return(buildReturnValue(FALSE, paste(frtcn, 'format verification'),
paste('failure', rv$intent, rv$message)))
rv <- verifyContent(sof)
if (!rv$validity)
return(buildReturnValue(FALSE, paste(frtcn, 'content verification'),
paste('failure', rv$intent, rv$message)))
buildReturnValue(TRUE, 'naming and instrumentation format and content seems good', 'success')
} |
library(testthat)
library(mrgsolve)
library(dplyr)
Sys.setenv(R_TESTS="")
options("mrgsolve_mread_quiet"=TRUE)
context("test-mread")
test_that("ETA(n) in $ODE is error", {
code <- '$OMEGA 1\n$ODE double a = ETA(1);'
expect_error(mcode("test-mread-eta", code, compile = FALSE))
})
test_that("Warning with no $CMT or $INIT", {
code <- '$OMEGA 1\n$ODE double a = 2;'
expect_warning(mcode("test-mread-cmt", code,quiet=FALSE,compile=FALSE))
})
test_that("read in rmd file", {
mod <- mread("popex.Rmd", modlib(), compile = FALSE)
expect_is(mod, "mrgmod")
})
test_that("ERROR is alias for TABLE", {
code <- "$ERROR double x=2;"
expect_is(mcode("error-is-table", code), "mrgmod")
}) |
SDMXStructureType <- function(xmlObj, namespaces, resource){
new("SDMXStructureType",
SDMXType(xmlObj),
subtype = type.SDMXStructureType(xmlObj, namespaces, resource));
}
type.SDMXStructureType <- function(xmlObj, namespaces, resource){
sdmxVersion <- version.SDMXSchema(xmlObj, namespaces)
VERSION.21 <- sdmxVersion == "2.1"
messageNsString <- "message"
if(isRegistryInterfaceEnvelope(xmlObj, FALSE)) messageNsString <- "registry"
messageNs <- findNamespace(namespaces, messageNsString)
strNs <- findNamespace(namespaces, "structure")
strType <- NULL
if(VERSION.21){
if(length(strNs)>0){
dsXML <- getNodeSet(xmlObj, "//ns:DataStructures", namespaces = strNs)
ccXML <- getNodeSet(xmlObj, "//ns:Concepts", namespaces = strNs)
clXML <- getNodeSet(xmlObj, "//ns:Codelists", namespaces = strNs)
if(length(dsXML)>0 & any(length(ccXML)>0,length(clXML)>0)){
strType <- "DataStructureDefinitionsType"
}else{
structuresXML <- getNodeSet(xmlObj, "//ns:Structures", namespaces = messageNs)
strType <- paste(xmlName(xmlChildren(structuresXML[[1]])[[1]]), "Type", sep="")
}
}
}else{
if(length(messageNs)>0){
flowXML <- getNodeSet(xmlObj, "//ns:Dataflows", namespaces = messageNs)
dsXML <- getNodeSet(xmlObj, "//ns:KeyFamilies", namespaces = messageNs)
ccXML <- getNodeSet(xmlObj, "//ns:Concepts", namespaces = messageNs)
clXML <- getNodeSet(xmlObj, "//ns:CodeLists", namespaces = messageNs)
if(all(c(length(dsXML)>0, length(ccXML)>0, length(clXML)>0))){
strType <- "DataStructureDefinitionsType"
}else{
if(length(ccXML)>0) return("ConceptsType")
if(length(clXML)>0) return("CodelistsType")
if(length(flowXML)>0) return("DataflowsType")
if(length(dsXML)>0){
if(is.null(resource)){
strType <- "DataStructuresType"
}else{
strType <- switch(resource,
"dataflow" = "DataflowsType",
"datastructure" = "DataStructuresType")
}
}
}
}
}
return(strType)
}
if (!isGeneric("getStructureType"))
setGeneric("getStructureType", function(obj) standardGeneric("getStructureType"));
setMethod(f = "getStructureType", signature = "SDMXStructureType", function(obj){
return(obj@subtype)
}) |
aul<-function (formula, d, data = NULL, na.action, ...)
{
d <- as.matrix(d)
d1 <- d[1L]
aules <- function(formula, d1, data = NULL, na.action) {
cal <- match.call(expand.dots = FALSE)
mat <- match(c("formula", "data", "na.action"), names(cal))
cal <- cal[c(1L, mat)]
cal[[1L]] <- as.name("model.frame")
cal <- eval(cal)
y <- model.response(cal)
md <- attr(cal, "terms")
x <- model.matrix(md, cal, contrasts)
s <- t(x) %*% x
xin <- solve(s)
bb <- xin %*% t(x) %*% y
I <- diag(NCOL(x))
fd <- solve(s + I) %*% (s + d1 * I)
bal <- (I - (1 - d1)^2 * solve(s + I) %*% solve(s + I)) %*%
bb
colnames(bal) <- c("Estimate")
ev <- (t(y) %*% y - t(bb) %*% t(x) %*% y)/(NROW(x) -
NCOL(x))
ev <- diag(ev)
dbd <- ev * (I + (1 - d1) * solve(s + I)) %*% fd %*%
xin %*% fd %*% (I + (1 - d1) * solve(s + I))
Standard_error <- sqrt(diag(abs(dbd)))
dbt <- t(bal)
dbd <- ev * (I + (1 - d1) * solve(s + I)) %*% fd %*%
xin %*% fd %*% (I + (1 - d1) * solve(s + I))
sdbd_inv <- (sqrt(diag(abs(dbd))))^-1
sdbd_inv_mat <- diag(sdbd_inv)
if (NCOL(dbt) == 1L)
tbd <- dbt * sdbd_inv
else tbd <- dbt %*% sdbd_inv_mat
hggh <- t(tbd)
bibet <- -(1 - d1)^2 * solve(s + I) %*% solve(s + I) %*%
bb
bibets <- bibet %*% t(bibet)
mse <- dbd + bibets
mse1 <- sum(diag(mse))
mse1 <- round(mse1, digits = 4L)
names(mse1) <- c("MSE")
tst <- t(2L * pt(-abs(tbd), df <- (NROW(x) - NCOL(x))))
colnames(tst) <- c("p_value")
colnames(hggh) <- c("t_statistic")
ans1 <- cbind(bal, Standard_error, hggh, tst)
ans <- round(ans1, digits = 4L)
anw <- list(`*****Almost Unbiased Liu Estimator*****` = ans,
`*****Mean square error value*****` = mse1)
return(anw)
}
npt <- aules(formula, d1, data, na.action)
plotaul <- function(formula, d, data = NULL, na.action, ...) {
i <- 0
arr <- 0
for (i in 1:NROW(d)) {
if (d[i] < 0L)
d[i] <- 0L
else d[i] <- d[i]
if (d[i] > 1L)
d[i] <- 1L
else d[i] <- d[i]
aulm <- function(formula, d, data, na.action, ...) {
cal <- match.call(expand.dots = FALSE)
mat <- match(c("formula", "data", "na.action"),
names(cal))
cal <- cal[c(1L, mat)]
cal[[1L]] <- as.name("model.frame")
cal <- eval(cal)
y <- model.response(cal)
md <- attr(cal, "terms")
x <- model.matrix(md, cal, contrasts)
s <- t(x) %*% x
xin <- solve(s)
bb <- xin %*% t(x) %*% y
I <- diag(NCOL(x))
fd <- solve(s + I) %*% (s + d * I)
bal <- (I - (1 - d)^2 * solve(s + I) %*% solve(s +
I)) %*% bb
ev <- (t(y) %*% y - t(bb) %*% t(x) %*% y)/(NROW(x) -
NCOL(x))
ev <- diag(ev)
dbd <- ev * (I + (1 - d) * solve(s + I)) %*%
fd %*% xin %*% fd %*% (I + (1 - d) * solve(s +
I))
bibet <- -(1 - d)^2 * solve(s + I) %*% solve(s +
I) %*% bb
bibets <- bibet %*% t(bibet)
mse <- dbd + bibets
mse1 <- sum(diag(mse))
return(mse1)
}
arr[i] <- aulm(formula, d[i], data, na.action)
}
MSE <- arr
parameter <- d
pvl <- cbind(parameter, MSE)
colnames(pvl) <- c("Parameter", "MSE")
sval <- pvl
return(sval)
}
paul <- plotaul(formula, d, data, na.action)
if (nrow(d) > 1L)
val <- paul
else val <- npt
val
} |
expected <- eval(parse(text="c(-1, -0.5, 0, 0.5, 1)"));
test(id=0, code={
argv <- eval(parse(text="list(c(-1, -0.5, 0, 0.5, 1))"));
do.call(`invisible`, argv);
}, o=expected); |
est <-
function (f, est_matrix, n_sample, l1_matrix, l2_matrix, cutp0, cutp1){
if (nrow(l1_matrix) == 1 & nrow(l2_matrix) == 1){
est_samples_cutp0 <- array(0, dim = c(nrow(l2_matrix), n_sample))
est_samples_cutp1 <- array(0, dim = c(nrow(l2_matrix), n_sample))
est_samples <- array(0, dim = c(nrow(l2_matrix), n_sample))
if (sum(cutp0 != cutp1) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, , n_s] %*% t(l2_matrix)
est_samples[, n_s] <- 1 - f(temp)
}
}else if(sum(cutp1 != 0) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, , n_s] %*% t(l2_matrix) - cutp0[n_s]
est_samples[, n_s] <- f(temp)
}
}else{
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, , n_s] %*% t(l2_matrix)
est_samples_cutp0[, n_s] <- temp - cutp0[n_s]
est_samples_cutp1[, n_s] <- temp - cutp1[n_s]
est_samples[, n_s] <- f(est_samples_cutp0[, n_s]) - f(est_samples_cutp1[, n_s])
}
}
}else if (nrow(l1_matrix) == 1 & nrow(l2_matrix) > 1){
est_samples_cutp0 <- array(0, dim = c(nrow(l2_matrix), n_sample))
est_samples_cutp1 <- array(0, dim = c(nrow(l2_matrix), n_sample))
est_samples <- array(0, dim = c(nrow(l2_matrix), n_sample))
if (sum(cutp0 != cutp1) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, colnames(l2_matrix), n_s] %*% t(l2_matrix)
est_samples[, n_s] <- 1 - f(temp)
}
}else if(sum(cutp1 != 0) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, colnames(l2_matrix), n_s] %*% t(l2_matrix) - cutp0[n_s]
est_samples[, n_s] <- f(temp)
}
}else{
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[, colnames(l2_matrix), n_s] %*% t(l2_matrix)
est_samples_cutp0[, n_s] <- temp - cutp0[n_s]
est_samples_cutp1[, n_s] <- temp - cutp1[n_s]
est_samples[, n_s] <- f(est_samples_cutp0[, n_s]) - f(est_samples_cutp1[, n_s])
}
}
}else if (nrow(l2_matrix) == 1 & nrow(l1_matrix) > 1){
est_samples_cutp0 <- array(0, dim = c(nrow(l1_matrix), n_sample))
est_samples_cutp1 <- array(0, dim = c(nrow(l1_matrix), n_sample))
est_samples <- array(0, dim = c(nrow(l1_matrix), n_sample))
if (sum(cutp0 != cutp1) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), , n_s] %*% t(l2_matrix)
est_samples[, n_s] <- 1 - f(temp)
}
}else if(sum(cutp1 != 0) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), , n_s] %*% t(l2_matrix) - cutp0[n_s]
est_samples[, n_s] <- f(temp)
}
}else{
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), , n_s] %*% t(l2_matrix)
est_samples_cutp0[, n_s] <- temp - cutp0[n_s]
est_samples_cutp1[, n_s] <- temp - cutp1[n_s]
est_samples[, n_s] <- f(est_samples_cutp0[, n_s]) - f(est_samples_cutp1[, n_s])
}
}
}else{
est_samples_cutp0 <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
est_samples_cutp1 <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
est_samples <- array(0, dim = c(nrow(l1_matrix), nrow(l2_matrix), n_sample))
if (sum(cutp0 != cutp1) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix)
est_samples[,, n_s] <- 1 - f(temp)
}
}else if(sum(cutp1 != 0) == 0){
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix), n_s] %*% t(l2_matrix) - cutp0[n_s]
est_samples[,, n_s] <- f(temp)
}
}else{
for (n_s in 1:n_sample){
temp <- l1_matrix %*% est_matrix[colnames(l1_matrix), colnames(l2_matrix),n_s] %*% t(l2_matrix)
est_samples_cutp0[,, n_s] <- temp - cutp0[n_s]
est_samples_cutp1[,, n_s] <- temp - cutp1[n_s]
est_samples[,, n_s] <- f(est_samples_cutp0[,, n_s]) - f(est_samples_cutp1[,, n_s])
}
}
}
return(est_samples)
} |
NULL
setClass('lcMethodFlexmix', contains = 'lcMethod')
lcMethodFlexmix = function(
formula,
formula.mb = ~ 1,
time = getOption('latrend.time'),
id = getOption('latrend.id'),
nClusters = 2,
...
) {
mc = match.call.all()
mc$Class = 'lcMethodFlexmix'
do.call(new, as.list(mc))
}
setMethod('getArgumentDefaults', signature('lcMethodFlexmix'), function(object) {
c(
formals(lcMethodFlexmix),
formals(flexmix::flexmix),
callNextMethod()
)
})
setMethod('getArgumentExclusions', signature('lcMethodFlexmix'), function(object) {
union(
callNextMethod(),
c('data', 'concomitant', 'k')
)
})
setMethod('getName', signature('lcMethodFlexmix'), function(object) 'flexmix')
setMethod('getShortName', signature('lcMethodFlexmix'), function(object) 'flx')
setMethod('preFit', signature('lcMethodFlexmix'), function(method, data, envir, verbose, ...) {
e = new.env()
f = formula(method) %>% dropRE()
e$formula = paste(deparse(f), '|', idVariable(method)) %>% as.formula
if (isArgDefined(method, 'model')) {
e$model = method$model
}
cat(verbose, sprintf('\tformula: %s', deparse(e$formula)), level = verboseLevels$finest)
if (hasCovariates(method$formula.mb)) {
e$concomitant = flexmix::FLXPmultinom(formula = method$formula.mb)
} else {
e$concomitant = flexmix::FLXPconstant()
}
return(e)
})
setMethod('fit', signature('lcMethodFlexmix'), function(method, data, envir, verbose, ...) {
args = as.list(method, args = flexmix::flexmix)
args$data = data
args$formula = envir$formula
args$model = envir$model
args$concomitant = envir$formula.mb
args$k = method$nClusters
if (is.null(args$model)) {
args$model = NULL
}
flexmodel = do.call(flexmix::flexmix, args)
if (flexmodel@k < method$nClusters) {
warning('flexmix returned a result with fewer components than was specified for nClusters')
}
new(
'lcModelFlexmix',
method = method,
data = data,
model = flexmodel,
clusterNames = make.clusterNames(flexmodel@k)
)
}) |
pcf.cross.3D<-
function(X,Y,Z,X2,Y2,Z2,psz=25,width=1,intensity=NULL,intensity2=NULL,parallel=FALSE,bw=0.01)
{
actualwidth=width
width=1.1*width
N<-length(X)
N2<-length(X2)
width.psz<-floor(width*psz)+1
x<-round(X*psz,0)+width.psz+1
y<-round(Y*psz,0)+width.psz+1
z<-round(Z*psz,0)+width.psz+1
x2<-round(X2*psz,0)+width.psz+1
y2<-round(Y2*psz,0)+width.psz+1
z2<-round(Z2*psz,0)+width.psz+1
ID<-1:N
ID2<-1:N2
ID.matrix<-ID.matrix2<-array(NA,c(round(max(c(X,X2))*psz,0)+(2*width.psz+1),round(max(c(Y,Y2))*psz,0)+(2*width.psz+1),round(max(c(Z,Z2))*psz,0)+(2*width.psz+1)))
if (!is.null(intensity))
{
intensity.mx<-array(0,dim(ID.matrix))
intensity.mx[width.psz+(1:dim(intensity)[1]),width.psz+(1:dim(intensity)[2]),width.psz+(1:dim(intensity)[3])]<-intensity
intensity<-TRUE
}
if (!is.null(intensity2))
{
intensity.mx2<-array(0,dim(ID.matrix2))
intensity.mx2[width.psz+(1:dim(intensity2)[1]),width.psz+(1:dim(intensity2)[2]),width.psz+(1:dim(intensity2)[3])]<-intensity2
intensity2<-TRUE
}
for (i in 1:N)
{
ID.matrix[x[i],y[i],z[i]]<-ID[i]
}
for (i in 1:N2)
{
ID.matrix2[x2[i],y2[i],z2[i]]<-ID2[i]
}
dist<-0:width.psz
extractneighbour<-function(i)
{
res<-NULL
int<-NULL
neighbours<-ID.matrix2[x[i]+dist,y[i]+dist,z[i]+dist]
neighbours<-as.vector(neighbours)
neighbours<-neighbours[!is.na(neighbours)]
neighbours<-neighbours[neighbours!=i]
for (j in neighbours)
{
res<-c(res,sqrt(sum((c(X[i],Y[i],Z[i])-c(X2[j],Y2[j],Z2[j]))^2)))
if (!is.null(intensity))int<-c(int,intensity.mx[x[i],y[i],z[i]]*intensity.mx2[x2[j],y2[j],z2[j]])
}
return(rbind(res,int))
}
if(parallel)dist<-mclapply(1:N,extractneighbour)
if(!parallel)dist<-lapply(1:N,extractneighbour)
dist<-unlist(dist)
if(!is.null(intensity))
{
weight<-dist[seq(2,length(dist),by=2)]
dist<-dist[seq(1,length(dist),by=2)]
weight<-weight[dist<=width]
dist<-dist[dist<=width]
}
else
{
dist<-dist[dist<=width]
weight<-rep(1,length(dist))
}
breaks=seq(0,width,length=100)
dr<-width/100
counts<-rep(0,99)
for (i in 1:99)
{
single<-1/weight[dist>breaks[i]&dist<=breaks[i+1]]
single[single==Inf]<-0
counts[i]<-sum(single)
}
counts<-counts/N/4/pi/dr/(seq(0,width,length=100)[-100])/(seq(0,width,length=100)[-100])
breaks<-0.5*(breaks[2:100]+breaks[1:99])
dist<-rep(0,99)
for (i in 2:99)
{
dist0<-rep(0,99)
for (j in 2:99)
dist0[j]<-dnorm(breaks[i],breaks[j],bw)
dist<-dist+counts[i]*(dist0/sum(dist0))
}
dist<-dist[breaks<=actualwidth]
breaks<-breaks[breaks<=actualwidth]
return(list("x"=breaks,"y"=dist))
} |
gff2fasta <- function(gff.table, genome){
genome %>%
mutate(Header = word(.data$Header, 1, 1)) %>%
rename(Seqid = .data$Header, Gseq = .data$Sequence) %>%
right_join(gff.table, by = "Seqid") %>%
mutate(Sequence = str_sub(.data$Gseq, .data$Start, .data$End)) %>%
mutate(Sequence = if_else(.data$Strand == "+", .data$Sequence, reverseComplement(.data$Sequence))) %>%
mutate(Header = str_c("Seqid=", .data$Seqid, ";Start=", .data$Start, ";End=", .data$End, ";Strand=", .data$Strand)) %>%
select(.data$Header, .data$Sequence) %>%
return()
}
readGFF <- function(in.file){
fil <- file(normalizePath(in.file), open = "rt")
lines <- readLines(fil)
close(fil)
fasta.idx <- grep("
cn <- c("Seqid", "Source", "Type", "Start", "End", "Score", "Strand", "Phase", "Attributes")
if(length(lines) > 1){
if(length(fasta.idx) > 0){
lns1 <- lines[1:fasta.idx]
M <- str_split(lns1[!grepl("^
if(ncol(M) != 9 ) stop("Table must have 9 tab-separated columns, this one has", ncol(M))
colnames(M) <- cn
as_tibble(M) %>%
mutate_at(c("Start", "End", "Score", "Phase"), as.numeric) -> gff.table
lns2 <- lines[(fasta.idx+1):length(lines)]
idx <- c(grep("^>", lns2), length(lns2) + 1)
fsa <- tibble(Header = gsub("^>", "", lns2[idx[1:(length(idx)-1)]]),
Sequence = sapply(1:(length(idx)-1), function(ii){
str_c(lns2[(idx[ii]+1):(idx[ii+1]-1)], collapse = "")
}))
attr(gff.table, "FASTA") <- fsa
} else {
M <- str_split(lines[!grepl("^
if(ncol(M) != 9 ) stop("Table must have 9 tab-separated columns, this one has", ncol(M))
colnames(M) <- cn
as_tibble(M) %>%
mutate(Score = if_else(.data$Score == ".", NA_character_, .data$Score)) %>%
mutate(Phase = if_else(.data$Phase == ".", NA_character_, .data$Phase)) %>%
mutate_at(c("Start", "End", "Score", "Phase"), as.numeric) -> gff.table
}
} else {
gff.table <- tibble("Seqid" = character(0),
"Source" = character(0),
"Type" = character(0),
"Start" = numeric(0),
"End" = numeric(0),
"Score" = numeric(0),
"Strand" = character(0),
"Phase" = numeric(0),
"Attributes" = character(0))
}
return(gff.table)
}
writeGFF <- function(gff.table, out.file){
line1 <- c("
sapply(1:nrow(gff.table), function(i){str_c(gff.table[i,], collapse = "\t")}) %>%
str_replace_all("\tNA\t", "\t.\t") %>%
str_replace_all("\tNA$", "\t.") -> lines
out.file <- file.path(normalizePath(dirname(out.file)),
basename(out.file))
writeLines(c(line1, lines), con = out.file)
return(NULL)
} |
bigstatsr_is_installed <- function() {
requireNamespace("bigstatsr",
quietly = TRUE,
warn.conflicts = FALSE)
}
bigstatsr_scores <- function(X,
ncol,
center = TRUE,
ret_extra = FALSE,
ncores = 1,
verbose = FALSE) {
res <- bigstatsr::big_randomSVD(
X = bigstatsr::as_FBM(X),
fun.scaling = bigstatsr::big_scale(center = center, scale = FALSE),
k = ncol,
ncores = ncores
)
if (verbose) {
totalvar <- sum(apply(X, 2, stats::var))
lambda <- sum((res$d^2) / (nrow(X) - 1))
varex <- lambda / totalvar
tsmessage(
"PCA: ",
ncol,
" components explained ",
formatC(varex * 100),
"% variance"
)
}
scores <- stats::predict(res)
if (ret_extra) {
list(
scores = scores,
rotation = res$v,
center = res$center
)
} else {
scores
}
} |
GenericClass <- R6Class("GenericClass",
public = list(
object_generator = NULL,
attached = list(),
initialize = function(object_generator = NULL, ...) {
if (!is.null(object_generator)) {
self$object_generator <- object_generator
} else {
self$object_generator <- eval(parse(text = class(self)[1]))
}
},
new_clone = function(...) {
return(self$object_generator$new(object_generator = self$object_generator, ...))
}
),
private = list(
)
) |
.time.timeSeries <-
function(x, ...)
{
if (length(x@positions)>0)
timeDate(x@positions, zone = "GMT",
FinCenter = x@FinCenter)
else
seq.int(NROW(x))
}
setMethod("time", "timeSeries",
function(x, ...) .time.timeSeries(x, ...))
time.timeSeries <- function(x, ...) .time.timeSeries(x, ...)
`time<-` <-
function(x, value)
{
UseMethod("time<-")
}
`time<-.timeSeries` <-
function(x, value)
{
rownames(x) <- value
x
}
getTime <-
function(x)
{
time(x)
}
"setTime<-" <-
function(x, value)
{
time(x) <- value
x
}
seriesPositions <-
function(object)
{
.Deprecated(new = "time", package = "timeSeries")
time(object)
}
"newPositions<-" <-
function(object, value)
{
.Deprecated(new = "time<-", package = "timeSeries")
rownames(object) <- value
object
} |
library("mvtnorm")
set.seed(1234)
n <- 100
p <- 25
beta <- rep.int(c(1, 0), c(5, p-5))
sigma <- 0.5
epsilon <- 0.1
Sigma <- 0.5^t(sapply(1:p, function(i, j) abs(i-j), 1:p))
x <- rmvnorm(n, sigma=Sigma)
e <- rnorm(n)
i <- 1:ceiling(epsilon*n)
e[i] <- e[i] + 5
y <- c(x %*% beta + sigma * e)
x[i,] <- x[i,] + 5
fitRlars <- rlars(x, y, sMax = 10)
head(fortify(fitRlars))
fitSparseLTS <- sparseLTS(x, y, lambda = 0.05, mode = "fraction")
head(fortify(fitSparseLTS))
head(fortify(fitSparseLTS, fit = "both")) |
r0 <- function(p0, lambda, delta, N=NULL, eps=sqrt(.Machine$double.eps)){
q <- p <- p0
j = 0
u = runif(1)
while(u > q){
j = j + 1
p = p * lambda * ((j+1)^delta) / j^(delta+1)
q = q + p
}
return(j)
}
TAU <- function(pars) tau(lambda=pars[1], delta=pars[2], N=NULL, eps=sqrt(.Machine$double.eps) )
R0 <- function(pars) r0(p0=pars[1], lambda=pars[2], delta=pars[3], N=NULL, eps=sqrt(.Machine$double.eps))
rtouch <- function(n, lambda, delta, N=NULL, eps=sqrt(.Machine$double.eps)){
if(length(lambda) == 1 & length(delta) == 1){
stopifnot(lambda >= 0)
p0 <- 1/tau(lambda,delta, N, eps)
x <- replicate(n, r0(p0, lambda, delta, N, eps))
}else{
stopifnot(all(lambda >= 0))
lam <- rep(lambda, length=n)
del <- rep(delta, length=n)
pars <- cbind(lam,del)
p0 <- 1/apply(pars, 1, FUN=TAU)
x <- apply(cbind(p0,pars), 1, FUN=R0)
}
return(x)
} |
pwd_ui <- function(id, tag_img = NULL, status = "primary", lan = NULL) {
ns <- NS(id)
if(is.null(lan)){
lan <- use_language()
}
tagList(
singleton(tags$head(
tags$link(href="shinymanager/styles-auth.css", rel="stylesheet"),
tags$script(src = "shinymanager/bindEnter.js")
)),
tags$div(
id = ns("pwd-mod"), class = "panel-auth",
tags$br(), tags$div(style = "height: 70px;"), tags$br(),
fluidRow(
column(
width = 4, offset = 4,
tags$div(
class = paste0("panel panel-", status),
tags$div(
class = "panel-body",
tags$div(
style = "text-align: center;",
if (!is.null(tag_img)) tag_img,
tags$h3(lan$get("Please change your password"))
),
tags$br(),
passwordInput(
inputId = ns("pwd_one"),
label = lan$get("New password:"),
width = "100%"
),
passwordInput(
inputId = ns("pwd_two"),
label = lan$get("Confirm password:"),
width = "100%"
),
tags$span(
class = "help-block",
icon("info-circle"),
lan$get("Password must contain at least one number, one lowercase, one uppercase and must be at least length 6.")
),
tags$br(),
tags$div(
id = ns("container-btn-update"),
actionButton(
inputId = ns("update_pwd"),
label = lan$get("Update new password"),
width = "100%",
class = paste0("btn-", status)
),
tags$br(), tags$br()
),
tags$script(
sprintf("bindEnter('%s');", ns(""))
),
tags$div(id = ns("result_pwd"))
)
)
)
)
)
)
}
pwd_server <- function(input, output, session, user, update_pwd, validate_pwd = NULL,
use_token = FALSE, lan = NULL) {
if(!is.reactive(lan)){
if(is.null(lan)){
lan <- reactive(use_language())
} else {
lan <- reactive(lan)
}
}
if (is.null(validate_pwd)) {
validate_pwd <- getFromNamespace("validate_pwd", "shinymanager")
}
ns <- session$ns
jns <- function(x) {
paste0("
}
password <- reactiveValues(result = FALSE, user = NULL, relog = NULL)
observeEvent(input$update_pwd, {
password$relog <- NULL
removeUI(selector = jns("msg_pwd"))
if (!identical(input$pwd_one, input$pwd_two)) {
insertUI(
selector = jns("result_pwd"),
ui = tags$div(
id = ns("msg_pwd"), class = "alert alert-danger",
icon("exclamation-triangle"), lan()$get("The two passwords are different")
)
)
} else {
if (!isTRUE(validate_pwd(input$pwd_one))) {
insertUI(
selector = jns("result_pwd"),
ui = tags$div(
id = ns("msg_pwd"), class = "alert alert-danger",
icon("exclamation-triangle"), lan()$get("Password does not respect safety requirements")
)
)
} else {
res_pwd <- update_pwd(user$user, input$pwd_one)
if (isTRUE(res_pwd$result)) {
password$result <- TRUE
password$user <- user$user
removeUI(selector = jns("container-btn-update"))
insertUI(
selector = jns("result_pwd"),
ui = tags$div(
id = ns("msg_pwd"),
tags$div(
class = "alert alert-success",
icon("check"), lan()$get("Password successfully updated! Please re-login")
),
actionButton(
inputId = ns("relog"),
label = lan()$get("Login"),
width = "100%"
)
)
)
} else {
insertUI(
selector = jns("result_pwd"),
ui = tags$div(
id = ns("msg_pwd"), class = "alert alert-danger",
icon("exclamation-triangle"), lan()$get("Failed to update password")
)
)
}
}
}
}, ignoreInit = TRUE)
observeEvent(input$relog, {
if (isTRUE(use_token)) {
token <- getToken(session = session)
.tok$remove(token)
resetQueryString(session = session)
session$reload()
}
password$relog <- input$relog
}, ignoreInit = TRUE)
return(password)
} |
orthonorm <-
function (p)
{
V <- matrix(0, nrow = p, ncol = p - 1)
for (i in 1:(p - 1)) {
V[1:i, i] <- 1/i
V[i + 1, i] <- (-1)
V[, i] <- V[, i] * sqrt(i/(i + 1))
}
return(V = V)
} |
aggregateForBarplot <- function(v) {
outF <- data.frame(table(v))
names(outF) <- c("x", "y")
outF
} |
runoptDirect <- function(expName = "obkpara20201017",
rkiwerte = babsim.hospital::rkidata,
icuwerte = babsim.hospital::icudata,
region = 5374,
TrainFieldStartDate = NULL,
TrainSimStartDate = NULL,
TestFieldStartDate = NULL,
TestSimStartDate = NULL,
Overlap = 7,
verbosity = 0,
seed = 123,
direct = FALSE,
repeats = 1,
funEvals = 35,
funEvalsFactor = 0,
size = 30,
simrepeats = 2,
subset = 32,
parallel = FALSE,
percCores = NULL,
icu = TRUE,
icuWeights = 1,
testRepeats = 3,
resourceNames = c("intensiveBed", "intensiveBedVentilation"),
resourceEval = c("intensiveBed", "intensiveBedVentilation"),
spotEvalsParallel = FALSE,
tryOnTestSet = TRUE) {
messageDateRange("Date range for cases", rkiwerte$Refdatum)
messageDateRange("Date range for resources", icuwerte$daten_stand)
result.df <- data.frame(x = NULL, y = NULL)
reslist <- list()
regionIcuwerte <- getRegionIcu(
data = icuwerte,
region = region
)
fieldData <- getIcuBeds(regionIcuwerte)
fieldData <-
fieldData[which(fieldData$Day >= as.Date(TrainFieldStartDate)), ]
regionRkiwerte <- getRegionRki(
data = rkiwerte,
region = region
)
simData <- getRkiData(regionRkiwerte)
simData <- simData[which(simData$Day >= as.Date(TrainSimStartDate)), ]
TrainSimStartDate <- min(simData$Day)
EndDate <- min(
max(as.Date(simData$Day)),
max(as.Date(fieldData$Day))
)
fieldData <-
fieldData[which(fieldData$Day <= EndDate), ]
simData <-
simData[which(simData$Day <= EndDate), ]
simData$time <- simData$time - min(simData$time)
rownames(fieldData) <- NULL
rownames(simData) <- NULL
if (tryOnTestSet) {
TrainEndDate <- as.Date(TestFieldStartDate) + Overlap
} else {
TrainEndDate <- as.Date(EndDate)
}
TrainSimData <- simData[which(simData$Day <= TrainEndDate), ]
TrainFieldData <- fieldData[which(fieldData$Day <= TrainEndDate), ]
syncedEndTrainDate <- min(max(TrainSimData$Day), max(TrainFieldData$Day))
TrainSimData <- simData[which(simData$Day <= syncedEndTrainDate), ]
TrainFieldData <- fieldData[which(fieldData$Day <= syncedEndTrainDate), ]
trainData <- list(
simData = TrainSimData,
fieldData = TrainFieldData
)
messagef(
"Training: Simulation date range: %s - %s",
min(trainData$simData$Day),
max(trainData$simData$Day)
)
messagef(
"Training: Field date range: %s - %s",
min(trainData$fieldData$Day),
max(trainData$fieldData$Day)
)
SIM_EQ_FIELD_TRAINDATA <-
(min(as.Date(trainData$simData$Day)) == as.Date(TrainSimStartDate))
if (SIM_EQ_FIELD_TRAINDATA == FALSE) {
stop(sprintf(
"babsim.hospital::runoptDirect: Check TrainSimStartDate. Expected %s, got %s.",
TrainSimStartDate, min(trainData$simData$Day)
))
}
SIM_EQ_FIELD_TRAINDATA <-
(min(as.Date(trainData$fieldData$Day)) == as.Date(TrainFieldStartDate))
if (SIM_EQ_FIELD_TRAINDATA == FALSE) {
stop(sprintf(
"babsim.hospital::runoptDirect: Check TrainFieldStartDate. Expected %s, got %s.",
TrainFieldStartDate, min(trainData$fieldData$Day)
))
}
SIM_EQ_FIELD_TRAINDATA <-
(max(as.Date(trainData$simData$Day)) == max(as.Date(trainData$fieldData$Day)))
if (SIM_EQ_FIELD_TRAINDATA == FALSE) {
stop("babsim.hospital::runoptDirect: Check trainData:
sim and field End data do not agree.")
}
FILENAME <- paste0("results/", expName, ".RData")
runSpotRepeat <- function(i) {
if (spotEvalsParallel) {
requireNamespace("babsim.hospital")
requireNamespace("SPOT")
}
messagef("Repeat %i
conf <- babsimToolsConf()
trainConf <- getConfFromData(
simData = trainData$simData,
fieldData = trainData$fieldData,
conf = conf
)
trainConf$verbosity <- verbosity
trainConf$parallel <- parallel
trainConf$simRepeats <- simrepeats
trainConf$ICU <- icu
trainConf$ResourceNames <- resourceNames
trainConf$ResourceEval <- resourceEval
trainConf$percCores <- percCores
trainConf$logLevel <- 0
trainConf$w2 <- icuWeights
trainConf$seed <- seed + i
messagef("trainConfSim: %s - %s", trainConf$simulationDates$StartDate, trainConf$simulationDates$EndDate)
messagef("trainConfField: %s - %s", trainConf$fieldDates$StartDate, trainConf$fieldDates$EndDate)
SIM_EQ_FIELD_TRAINCONF <-
(min(as.Date(trainConf$simulationDates$StartDate)) == as.Date(TrainSimStartDate)) &
(min(as.Date(trainConf$fieldDates$StartDate)) == as.Date(TrainFieldStartDate)) &
(max(as.Date(trainConf$simulationDates$EndDate)) == max(as.Date(trainConf$fieldDates$EndDate)))
if (SIM_EQ_FIELD_TRAINCONF == FALSE) {
stop("babsim.hospital::runoptDirect: Check trainConf.")
}
set.seed(trainConf$seed)
funEvals <- funEvals + (i - 1) * funEvalsFactor
x0 <- getStartParameter(region = region)
if(is.null(nrow(x0))){
x0 <- matrix(x0, nrow = 1)
}
if (nrow(x0) > 20) {
x0 <- x0[1:20, ]
messagef("Warning cutting some x0 parameters as there are too many")
}
bounds <- getBounds()
a <- bounds$lower
b <- bounds$upper
conf <- trainConf
if (conf$verbosity > 1000) {
messagef("conf before spot optimization is started")
printConf(conf)
}
data <- trainData
g <- function(x) {
return(
rbind(
a[1] - x[1],
x[1] - b[1],
a[2] - x[2],
x[2] - b[2],
a[3] - x[3],
x[3] - b[3],
a[4] - x[4],
x[4] - b[4],
a[5] - x[5],
x[5] - b[5],
a[6] - x[6],
x[6] - b[6],
a[7] - x[7],
x[7] - b[7],
a[8] - x[8],
x[8] - b[8],
a[9] - x[9],
x[9] - b[9],
a[10] - x[10],
x[10] - b[10],
a[11] - x[11],
x[11] - b[11],
a[12] - x[12],
x[12] - b[12],
a[13] - x[13],
x[13] - b[13],
a[14] - x[14],
x[14] - b[14],
a[15] - x[15],
x[15] - b[15],
a[16] - x[16],
x[16] - b[16],
a[17] - x[17],
x[17] - b[17],
a[18] - x[18],
x[18] - b[18],
a[19] - x[19],
x[19] - b[19],
a[20] - x[20],
x[20] - b[20],
a[21] - x[21],
x[21] - b[21],
a[22] - x[22],
x[22] - b[22],
a[23] - x[23],
x[23] - b[23],
a[24] - x[24],
x[24] - b[24],
a[25] - x[25],
x[25] - b[25],
a[26] - x[26],
x[26] - b[26],
a[27] - x[27],
x[27] - b[27],
x[15] + x[16] - 1,
x[17] + x[18] + x[19] - 1,
x[20] + x[21] - 1,
x[23] + x[29] - 1
)
)
}
assign(
expName,
spot(
x = as.matrix(x0),
fun = funWrapOptimizeSim,
lower = a,
upper = b,
control = list(
funEvals = funEvals,
noise = TRUE,
direct = direct,
designControl = list(
size = size,
retries = 1000
),
optimizer = optimNLOPTR,
optimizerControl = list(
opts = list(algorithm = "NLOPT_GN_ISRES"),
eval_g_ineq = g
),
model = buildKriging,
plots = FALSE,
progress = TRUE,
subsetSelect = selectN,
subsetControl = list(N = subset)
),
conf,
data
)
)
res <- get(expName)
x <- as.matrix(res$xbest, 1, )
if (tryOnTestSet) {
messagef("Starting test evaluation:")
messagef("
testPara <- mapXToPara(x)
testPara <- checkSimPara(testPara)
testFieldData <-
fieldData[which(fieldData$Day >= as.Date(TestFieldStartDate)), ]
rownames(testFieldData) <- NULL
testSimData <-
simData[which(simData$Day >= as.Date(TestSimStartDate)), ]
TestSimStartDate <- min(testSimData$Day)
testSimData <-
testSimData[as.Date(testSimData$Day) <= max(as.Date(testFieldData$Day)), ]
testFieldData <-
testFieldData[as.Date(testFieldData$Day) <= max(as.Date(testSimData$Day)), ]
syncedEndTestDate <- min(max(testSimData$Day), max(testFieldData$Day))
testSimData <- testSimData[which(testSimData$Day <= syncedEndTestDate), ]
TestFieldData <- fieldData[which(fieldData$Day <= syncedEndTestDate), ]
testSimData$time <- testSimData$time - min(testSimData$time)
rownames(testSimData) <- NULL
testData <- list(
simData = testSimData,
fieldData = testFieldData
)
messagef("testDataSim: %s - %s", min(testData$simData$Day), max(testData$simData$Day))
messagef("testDataField: %s - %s", min(testData$fieldData$Day), max(testData$fieldData$Day))
SIM_EQ_FIELD_TESTDATA <-
(min(as.Date(testData$simData$Day)) == as.Date(TestSimStartDate))
if (SIM_EQ_FIELD_TESTDATA == FALSE) {
print(as.Date(TestSimStartDate))
stop("babsim.hospital::runoptDirect: Check testData:
TestSimStartDate.")
}
SIM_EQ_FIELD_TESTDATA <-
(min(as.Date(testData$fieldData$Day)) == as.Date(TestFieldStartDate))
if (SIM_EQ_FIELD_TESTDATA == FALSE) {
print(as.Date(TestFieldStartDate))
stop("babsim.hospital::runoptDirect: Check testData: TestFieldStartDate.")
}
SIM_EQ_FIELD_TESTDATA <-
(max(as.Date(testData$simData$Day)) == max(as.Date(testData$fieldData$Day)))
if (SIM_EQ_FIELD_TESTDATA == FALSE) {
stop("babsim.hospital::runoptDirect: Check testData:
sim and field data End date differ!")
}
conf <- babsimToolsConf()
testConf <- getConfFromData(
simData = testSimData,
fieldData = testFieldData,
conf = conf
)
testConf$verbosity <- verbosity
testConf$parallel <- parallel
testConf$simRepeats <- simrepeats
testConf$ICU <- icu
testConf$ResourceNames <- resourceNames
testConf$ResourceEval <- resourceEval
testConf$percCores <- percCores
testConf$logLevel <- 0
testConf$w2 <- icuWeights
testConf$seed <- seed + i + 1
set.seed(testConf$seed)
messagef("testConfSim: %s - %s", testConf$simulationDates$StartDate, testConf$simulationDates$EndDate)
messagef("testConfField: %s - %s", testConf$fieldDates$StartDate, testConf$fieldDates$EndDate)
SIM_EQ_FIELD_TESTCONF <- ((testConf$simulationDates$StartDate != testConf$fieldDates$StartDate) &
(testConf$simulationDates$EndDate != testConf$fieldDates$EndDate))
SIM_EQ_FIELD_TESTCONF <-
(min(as.Date(testConf$simulationDates$StartDate)) == as.Date(TestSimStartDate)) &
(min(as.Date(testConf$fieldDates$StartDate)) == as.Date(TestFieldStartDate)) &
(max(as.Date(testConf$simulationDates$EndDate)) == max(as.Date(testConf$fieldDates$EndDate)))
if (SIM_EQ_FIELD_TESTCONF == FALSE) {
stop("babsim.hospital::runoptDirect: Check testConf.")
}
testErr <- 0
for (j in 1:testRepeats) {
testConf$seed <- seed + i + 1 + j
set.seed(testConf$seed)
envs <- modelResultHospital(
para = testPara,
conf = testConf,
data = testData
)
testConf$verbosity <- 101
err <- getError(envs, conf = testConf)
messagef("Single test error: %f", err)
testErr <- testErr + err
}
testErr <- testErr / testRepeats
messagef("testErr: %f", testErr)
messagef("babsim.hospital version: %s", utils::packageVersion("babsim.hospital"))
return(list(
res = res,
best = data.frame(y = testErr, x = x)
))
} else {
return(list(
res = res,
best = data.frame(y = res$ybest, x = res$xbest)
))
}
}
messagef("Starting optimization loop:")
messagef("
if (!spotEvalsParallel) {
for (i in 1:repeats) {
y <- runSpotRepeat(i)
reslist[[length(reslist) + 1]] <- y$res
result.df <- rbind(result.df, y$best)
FILENAMETMP <- paste0("results/", expName, i, ".RData")
message("FILENAMETMP = '%s'", FILENAMETMP)
save(result.df, file = FILENAMETMP)
}
} else {
if (parallel == TRUE) {
results <- parallel::mclapply(X = 1:repeats, FUN = runSpotRepeat, mc.cores = parallel::detectCores() / (percCores * 32))
} else {
results <- parallel::mclapply(X = 1:repeats, FUN = runSpotRepeat, mc.cores = parallel::detectCores())
}
getBest <- function(result.list) {
result.list$best
}
getRes <- function(result.list) {
result.list$res
}
bestResults <- lapply(results, getBest)
reslist <- lapply(results, getRes)
result.df <- dplyr::bind_rows(bestResults)
}
messagef("Saving results to '%s'.", FILENAME)
save(result.df, file = FILENAME)
return(list(
best.df = result.df,
reslist = reslist
))
} |
by_2sd <- function(df, dataset) {
if (!"by_2sd" %in% names(df)) {
sdX2 <- df$term %>%
as.list() %>%
lapply(function(x) {
if(any(grep(":", x)) && !x %in% names(dataset)) {
first <- gsub(":.*", "", x)
second <- gsub(".*:", "", x)
dataset[[paste0(first,":",second)]] <- dataset[[first]]*dataset[[second]]
}
unmatched <- !x %in% names(dataset)
dx <- dataset[[x]]
dich <- (unmatched ||
stats::na.omit(unique(dx)) %>% sort() %>% identical(c(0,1)))
if (dich) 1 else 2*stats::sd(dataset[[x]], na.rm=TRUE)
}) %>%
unlist()
df$estimate <- df$estimate * sdX2
df$std.error <- df$std.error * sdX2
if ("conf.high" %in% names(df)) {
df$conf.high <- df$conf.high * sdX2
df$conf.low <- df$conf.low * sdX2
}
df$by_2sd <- TRUE
}
return(df)
} |
anm.ExpDesign.tck<-function(){
tclRequire("BWidget")
local({
have_ttk <- as.character(tcl("info", "tclversion")) >= "8.5"
if(have_ttk) {
tkbutton <- ttkbutton
tkcheckbutton <- ttkcheckbutton
tkentry <- ttkentry
tkframe <- ttkframe
tklabel <- ttklabel
tkradiobutton <- ttkradiobutton
}
tclServiceMode(FALSE)
dialog.sd <- function(){
tt <- tktoplevel()
tkwm.title(tt,"Experimental designs")
Proc<-tclVar("all")
int.entry <- tkentry(tt, textvariable=Int, width = 10)
iter.entry<-tkentry(tt, textvariable=Iter, width = 10)
done <- tclVar(0)
reset <- function()
{
tclvalue(Int)<-"0.5"
tclvalue(Iter)<-"30"
}
reset.but <- tkbutton(tt, text="Reset", command=reset)
submit.but <- tkbutton(tt, text="Submit",command=function()tclvalue(done)<-1)
build <- function()
{
interval <-tclvalue(Int)
iter <-tclvalue(Iter)
Proc <-tclvalue(Proc)
substitute(anm.ExpDesign(method = Proc, interval=as.numeric(interval),iter=as.numeric(iter)))
}
tkgrid(tklabel(tt,text="Experimental designs"),columnspan=2)
tkgrid(tklabel(tt,text=""))
tkgrid(tklabel(tt, text="Design"),columnspan=2)
proc <- c("all","CRD","factorial2by2","factorial2by2by2","nested","RCBD","RIBD","split","split.split", "SPRB","strip","split.block","strip.split","latin","pairs")
comboBox <- tkwidget(tt,"ComboBox", editable=FALSE, values=proc, textvariable = Proc, width = 15)
tkgrid(comboBox,columnspan=2)
tkgrid(tklabel(tt,text="Anim. int."),int.entry)
tkgrid(tklabel(tt,text="Iterations "), iter.entry)
tkgrid(tklabel(tt,text=""))
tkgrid(submit.but, reset.but, sticky="w")
tkbind(tt, "<Destroy>", function()tclvalue(done)<-2)
tkwait.variable(done)
if(tclvalue(done)=="2") stop("aborted")
tkdestroy(tt)
cmd <- build()
eval.parent(cmd)
invisible(tclServiceMode(TRUE))
}
Iter<-tclVar("30")
Int<-tclVar("0.5")
dialog.sd()
})
} |
maxFreq <- function(trimmed, header, verbose){
if(verbose==1) print("Building consensus sequence...")
maxFreqSequence<- vector("list", length(trimmed[1,]))
for(i in 1:length(trimmed[1,])) {
maxInCol<-names(which(table(trimmed[,i])==max(table(trimmed[,i]))))
if (length(maxInCol)==1){
maxFreqSequence[[i]]<-c(maxFreqSequence[[i]], names(which(table(trimmed[,i])==max(table(trimmed[,i])))))
}
else{
maxFreqSequence[[i]]<-c(maxFreqSequence[[i]], "X")
}
}
maxFreq<-as.data.frame(lapply(maxFreqSequence, suppressBrackets))
names(maxFreq)<-header
options(stringsAsFactors=FALSE)
maxFreq
} |
single.beta <- function(X, y, maxcomp = NULL) {
if (missing(X) | missing(y)) stop("Please specify both x and y")
if (is.null(maxcomp)) maxcomp <- min(nrow(X) - 1L, ncol(X))
plsdf <- as.data.frame(cbind(X, "y" = y))
plsr.cvfit <- pls::plsr(
y ~ X,
data = plsdf, ncomp = maxcomp,
scale = TRUE, method = "simpls", validation = "LOO"
)
opt.cv <- which.min(pls::RMSEP(plsr.cvfit)[["val"]][2L, 1L, -1L])
rmse.cv <- min(pls::RMSEP(plsr.cvfit)[["val"]][2L, 1L, -1L])
plsr.fit <- pls::plsr(
y ~ X,
data = plsdf, ncomp = opt.cv,
scale = TRUE, method = "simpls", validation = "none"
)
beta1 <- matrix(coef(plsr.fit), ncol = 1L)
simplsfit <- simpls.fit(X, y, opt.cv)
beta <- coef(simplsfit, ncomp = opt.cv, intercept = FALSE)
beta.simpls <- matrix(simplsfit$coefficients[, , opt.cv], ncol = 1L)
obj <- list(
"beta" = beta1,
"opt.cv" = opt.cv,
"rmse.cv" = rmse.cv,
"beta.simpls" = beta.simpls
)
obj
} |
setClass("multimap", contains = "unordered_map")
multimap <- function(key.class = c("character", "numeric", "integer")) {
key.class <- match.arg(key.class)
key.class <- match.arg(key.class)
map <- switch(
key.class,
"character" = methods::new(multimap_s),
"numeric" = methods::new(multimap_d),
"integer" = methods::new(multimap_i),
stop("Error defining key class")
)
methods::new("multimap",
.key.class = key.class,
.map = map
)
}
.erase.multimap <- function(obj, key, value) {
.check.key.class(obj, key)
if (length(key) != length(value)) {
stop("dimensions of keys and values do not match")
}
[email protected]$remove_with_value(key, value)
obj
}
setMethod(
"erase",
signature = signature(obj = "multimap", key = "vector", value = "vector"),
function(obj, key, value) {
if (length(key) == 1) {
value <- list(value)
} else if (length(key) == length(value) && is.vector(value)) {
value <- as.list(value)
}
.erase.multimap(obj, key, value)
}
)
setMethod(
"erase",
signature = signature(obj = "multimap", key = "vector", value = "list"),
function(obj, key, value) {
if (length(key) == 1) value <- list(value)
.erase.multimap(obj, key, value)
}
)
setMethod(
"erase",
signature = signature(obj = "multimap", key = "vector", value = "ANY"),
function(obj, key, value) {
.erase.multimap(obj, key, list(value))
}
) |
isSupported <- function(v) {
suppClasses <- c("character", "factor", "labelled", "haven_labelled",
"numeric", "integer",
"logical", "Date")
vClasses <- class(v)
out <- list(problem = FALSE, message = "", problemValues = NULL)
if (any(vClasses %in% suppClasses)) {
return(checkResult(out))
}
out$problem <- TRUE
out$message <- paste("The variable has class", vClasses[1],
"which is not supported by dataMaid.")
checkResult(out)
}
isSupported <- checkFunction(isSupported,
"Check if the variable class is supported by dataMaid.",
allClasses()) |
plot.IP <- plot.IP <- function (x, ..., N = NULL, clutch = 1, result = "data") {
p3p <- list(...)
result <- tolower(result)
if (is.list(x)) {
if (!(identical(x$ML, list())) | !(identical(x$MH, list()))) {
if (!(identical(x$MH, list()))) {
data <- x$MH$parametersMCMC$control$data
pari <- c(as.parameters(x$MH), x$MH$parametersMCMC$control$fixed.parameters)
} else {
data <- x$ML$data
pari <- c(x$ML$par, x$ML$fixed.parameters)
}
meanIP <- log(abs(pari["meanIP"]))
sdIP <- abs(pari["sdIP"])
minIP <- abs(pari["minIP"])
DeltameanIP <- pari["DeltameanIP"]
pAbort <- invlogit(-pari["pAbort"])
meanAbort <- log(abs(pari["meanAbort"]))
sdAbort <- abs(pari["sdAbort"])
pCapture <- invlogit(-pari["pCapture"])
meanECF <- log(abs(pari["meanECF"]))
sdECF <- abs(pari["sdECF"])
ECF <- abs(pari[substr(names(pari), 1, 3) == "ECF"])
Nnull <- is.null(N)
if (Nnull) {
N <- pari["N"]
if (is.na(N))
N <- 1e+06
}
if (!is.na(meanECF)) {
CFx <- floor(rlnorm(N, meanlog = meanECF, sdlog = sdECF)) +
1
CFx <- as.data.frame(table(CFx), stringsAsFactors = FALSE)
CFx[, "CFx"] <- as.numeric(CFx[, "CFx"])
ECF <- data.frame(ECF = 1:max(CFx[, "CFx"]),
Freq = 0)
ECF[CFx[, "CFx"], "Freq"] <- CFx[, "Freq"]/sum(CFx[,
"Freq"])
} else {
ECF["ECF.1"] <- 1
ECF <- ECF[order(as.numeric(gsub("ECF\\.", "",
names(ECF))))]
ECF <- ECF/sum(ECF)
ECF <- data.frame(ECF = 1:length(ECF), Freq = ECF)
}
if ((result == "model") | (result == "data&model") | (result == "reverseecf")) {
if (!is.null(x$model) & (Nnull)) {
model <- x$model
} else {
model <- IPModel(pari)
}
reverseECF <- model$reverseECF
model <- model$cumuld
} else {
model <- NULL
reverseECF <- NULL
}
di <- floor(rlnorm(N, meanlog = log(exp(meanIP) +
(clutch - 1) * ifelse(is.na(DeltameanIP), 0,
DeltameanIP)), sdlog = sdIP))
di <- di[di >= minIP]
di <- as.data.frame(table(di), stringsAsFactors = FALSE)
di[, "di"] <- as.numeric(di[, "di"])
IP <- data.frame(IP = 1:max(di[, "di"]), Freq = 0)
IP[di[, "di"], "Freq"] <- di[, "Freq"]/sum(di[, "Freq"])
di <- floor(rlnorm(N, meanlog = meanAbort, sdlog = sdAbort))
di <- as.data.frame(table(di), stringsAsFactors = FALSE)
di[, "di"] <- as.numeric(di[, "di"])
Abort <- data.frame(Abort = 0:(max(di[, "di"])),
Freq = 0)
Abort[di[, "di"] + 1, "Freq"] <- di[, "Freq"]/sum(di[,
"Freq"])
} else {
data <- x$cumuld
reverseECF <- x$reverseECF
}
} else {
pari <- NULL
data <- x
reverseECF <- NULL
}
if (is.matrix(data)) {
data <- colSums(data)
}
if (result == "data") {
do.call(plot, modifyList(list(x = (1:length(data)) -
1, y = data, type = "h", bty = "n", las = 1, xlab = "Days after first observation",
ylab = "Number of observations"), p3p))
}
if (result == "model") {
do.call(plot, modifyList(list(x = as.numeric(names(model)),
y = model, type = "h", bty = "n", las = 1, xlab = "Days after first observation",
ylab = "Number of observations"), p3p))
}
if (result == "ecf") {
do.call(plot, modifyList(list(x = ECF$ECF, y = ECF$Freq,
type = "h", bty = "n", las = 1, xlab = "Estimated Clutch Frequency",
ylab = "Proportion", xaxt = "n"), p3p))
axis(1, 1:(ScalePreviousPlot()$xlim["end"]), cex.axis = 0.8)
}
if (result == "data&model") {
xl <- max(c(as.numeric(names(model)), length(data) -
1))
if (!is.null(p3p$xlim))
xl <- p3p$xlim[2]
do.call(plot, modifyList(list(x = (1:length(data)) -
1, y = data, type = "h", bty = "n", las = 1, ylim = c(-max(c(data,
model * sum(data))), +max(c(data, model * sum(data)))),
xlim = c(0, xl), xaxt = "n", xlab = "Days after first observation",
ylab = "Number of observations"), p3p))
par(new = TRUE)
do.call(plot, modifyList(list(x = as.numeric(names(model)),
y = -model * sum(data), type = "h", bty = "n", ylim = c(-max(c(data,
model * sum(data))), +max(c(data, model * sum(data)))),
xlim = c(0, xl), axes = FALSE, xlab = "", ylab = "",
xaxt = "n"), p3p))
axis(1, 0:(ScalePreviousPlot()$xlim["end"]), cex.axis = 0.8)
text(xl, max(c(data, model * sum(data)))/2, labels = "Observations",
pos = 2)
text(xl, -max(c(data, model * sum(data)))/2, labels = "Model",
pos = 2)
}
if (result == "ip") {
do.call(plot, modifyList(list(x = IP$IP, y = IP$Freq,
type = "h", bty = "n", las = 1, xlab = "Internesting Period",
ylab = "Proportion", xaxt = "n"), p3p))
axis(1, 1:(ScalePreviousPlot()$xlim["end"]), cex.axis = 0.8)
}
if (result == "abort") {
do.call(plot, modifyList(list(x = Abort$Abort, y = Abort$Freq,
type = "h", bty = "n", las = 1, xlab = "Number of days between two tentatives",
ylab = "Proportion", xaxt = "n"), p3p))
axis(1, 0:(ScalePreviousPlot()$xlim["end"]), cex.axis = 0.8)
}
if ((result == "reverseecf") & (!is.null(reverseECF))) {
cmrev <- reverseECF
maxx <- 1
maxy <- 1
for (col in 1:ncol(cmrev)) {
maxx <- ifelse(test = (sum(cmrev[, col]) != 0), col,
maxx)
maxy <- max(which(cmrev[, col] != 0), maxy)
cmrev[, col] <- cumsum(cmrev[, col])
}
if (is.null(p3p$col)) {
color <- rainbow(maxy)
} else {
color <- p3p$col
if (length(color) != maxy) {
p3p$col <- color[floor(length(color) * (1:maxy)/(maxy))]
}
}
par(mar = c(4, 4, 2, 6) + 0.4)
par(xpd=FALSE)
do.call(plot, modifyList(list(x = 0:(ncol(reverseECF) -
1), y = reverseECF[1, ], bty = "n", ylim = c(0, 1),
xlim = c(0, maxx - 1), las = 1, type = "n", xlab = "Days after first observation",
ylab = "Cumulative proportion"), p3p))
polygon(x = c(0:(ncol(reverseECF) - 1), (ncol(reverseECF) -
1):0), y = c(rep(0, ncol(reverseECF)), rev(cmrev[1,
])), col = color[1], border = NA)
for (i in 2:maxy) {
polygon(x = c(0:(ncol(reverseECF) - 1), (ncol(reverseECF) -
1):0), y = c(cmrev[i - 1, ], rev(cmrev[i, ])),
col = color[i], border = NA)
}
par(xpd = TRUE)
maxx <- ScalePreviousPlot()$xlim[2]
dx <- maxx/10
for (ecf in 1:maxy) {
y <- 0.1 + (ecf - 1) * 0.9/(maxy)
dy <- 0.1 + (ecf - 1 + 0.8) * 0.9/(maxy)
polygon(x = c(maxx + dx, (maxx + dx)*1.05, (maxx + dx)*1.05, maxx + dx), y = c(y, y, dy, dy), col = color[ecf],
border = NA)
text(x = (maxx + dx)*1.07, y = mean(c(y, dy)), labels = (ecf -
1))
}
text((maxx + dx)*1.025, y = 1*1.05,
labels = "Clutch")
}
} |
ksample.gauss <- function(
dat1, dat2, K=5
){
dat1 = t(t(dat1)-apply(dat1,2,mean));
dat2 = t(t(dat2)-apply(dat2,2,mean));
n1 = nrow(dat1);
n2 = nrow(dat2);
N = n1+n2;
cov1= (n1-1)/n1*cov(dat1);
cov2= (n2-1)/n2*cov(dat2);
covP= n1/N*cov1 + n2/N*cov2;
eigP= eigen(covP);
if(K==0){
eig1 = eigen(cov1);
eig2 = eigen(cov2);
pfc_scores = rep(0,min(n1,n2));
for(K in 2:min(n1,n2)){
vec = eigP$vectors[,1:K];
prj1 = ksg_projData( dat1, vec );
prj2 = ksg_projData( dat2, vec );
gof = sum((prj1-dat1)^2) + sum((prj2-dat2)^2);
ip1 = (prj1 %*% eig1$vectors)^2/eig1$values;
ip2 = (prj2 %*% eig2$vectors)^2/eig2$values;
pen = 2*(
sum(eig1$values)*sum(ip1)/n1 +
sum(eig2$values)*sum(ip2)/n2
);
pfc_scores[K] = gof + pen;
}
pfc_scores[1] = max(pfc_scores);
K = which.min(pfc_scores);
}
vec = eigP$vectors[,1:K];
ev1 = t(vec) %*% cov1 %*% vec/n1;
ev2 = t(vec) %*% cov2 %*% vec/n2;
denom = n1*diag( ev1 ) + n2*diag( ev2 );
mat = t((ev1-ev2)^2/denom)/denom;
tstat = (n1*n2*N)/2*sum(mat);
dof = K*(K+1)/2;
return( pchisq(tstat,dof,lower.tail=FALSE) );
}
ksg_projData <- function( dat, vec ){
return( (dat %*% vec) %*% t(vec) );
}
ksample.vstab <- function(
dat1, dat2, K=5
){
dat1 = t(t(dat1)-apply(dat1,2,mean));
dat2 = t(t(dat2)-apply(dat2,2,mean));
n1 = nrow(dat1);
n2 = nrow(dat2);
N = n1+n2;
cov1= (n1-1)/n1*cov(dat1);
cov2= (n2-1)/n2*cov(dat2);
covP= n1/N*cov1 + n2/N*cov2;
eigP= eigen(covP);
if(K==0){
cumEig = cumsum(eigP$values)/sum(eigP$values);
K = which(cumEig>0.9)[1];
}
vec = eigP$vectors[,1:K];
ev1 = t(vec) %*% cov1 %*% vec/n1;
ev2 = t(vec) %*% cov2 %*% vec/n2;
tstat1= sum( (log(diag(ev1))-log(diag(ev2)))^2,na.rm=TRUE )/2
dprod1= sqrt(outer(diag(ev1),diag(ev1)));
dprod2= sqrt(outer(diag(ev2),diag(ev2)));
tstat2= ((
log((dprod1+ev1)/(dprod1-ev1)) -
log((dprod2+ev2)/(dprod2-ev2))
)/2)^2;
tstat2= sum( tstat2*upper.tri(tstat2),na.rm=TRUE );
tstat = n1*n2/N*(tstat1+tstat2);
dof = K*(K+1)/2;
return( pchisq(tstat,dof,lower.tail=FALSE) );
} |
timestamp <- Sys.time()
library(caret)
library(plyr)
library(recipes)
library(dplyr)
model <- "awnb"
set.seed(2)
training <- LPH07_1(100, factors = TRUE, class = TRUE)
testing <- LPH07_1(100, factors = TRUE, class = TRUE)
trainX <- training[, -ncol(training)]
trainY <- training$Class
rec_cls <- recipe(Class ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
cctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all",
classProbs = TRUE,
summaryFunction = twoClassSummary)
cctrl2 <- trainControl(method = "LOOCV",
classProbs = TRUE, summaryFunction = twoClassSummary)
cctrl3 <- trainControl(method = "none",
classProbs = TRUE, summaryFunction = twoClassSummary)
cctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random")
set.seed(849)
test_class_cv_model <- train(trainX, trainY,
method = "awnb",
trControl = cctrl1,
metric = "ROC")
test_class_pred <- predict(test_class_cv_model, testing[, -ncol(testing)])
test_class_prob <- predict(test_class_cv_model, testing[, -ncol(testing)], type = "prob")
set.seed(849)
test_class_rand <- train(trainX, trainY,
method = "awnb",
trControl = cctrlR,
tuneLength = 4)
set.seed(849)
test_class_loo_model <- train(trainX, trainY,
method = "awnb",
trControl = cctrl2,
metric = "ROC")
set.seed(849)
test_class_none_model <- train(trainX, trainY,
method = "awnb",
trControl = cctrl3,
tuneGrid = test_class_cv_model$bestTune,
metric = "ROC")
test_class_none_pred <- predict(test_class_none_model, testing[, -ncol(testing)])
test_class_none_prob <- predict(test_class_none_model, testing[, -ncol(testing)], type = "prob")
test_levels <- levels(test_class_cv_model)
if(!all(levels(trainY) %in% test_levels))
cat("wrong levels")
test_class_predictors1 <- predictors(test_class_cv_model)
test_class_imp <- varImp(test_class_cv_model)
tests <- grep("test_", ls(), fixed = TRUE, value = TRUE)
sInfo <- sessionInfo()
timestamp_end <- Sys.time()
save(list = c(tests, "sInfo", "timestamp", "timestamp_end"),
file = file.path(getwd(), paste(model, ".RData", sep = "")))
if(!interactive())
q("no") |
plot.fanc <- function (x, Window.Height=500, type=NULL, df.method="active", ...){
if(nchar(system.file(package="ellipse")) == 0){
msg <- paste0("The package 'ellipse' is required to plot ",
"the solution path.\n",
"Do you want to install 'ellipse' now? (y/n)")
answer <- readline(msg)
if(answer=="y"){
install.packages("ellipse")
if (nchar(system.file(package="ellipse")) == 0) stop('The package "ellipse" was not able to be installed')
} else {
stop("The plot was terminated.")
}
}
requireNamespace("ellipse", quietly=TRUE)
if(nchar(system.file(package="tcltk")) == 0){
answer <- readline("The package 'tcltk' is required to plot the solution path. \nDo you want to install 'tcltk' now? (y/n)")
if(answer=="y"){
install.packages("tcltk")
if (nchar(system.file(package="tcltk")) == 0) stop('The package "tcltk" was not able to be installed')
}else{
stop("The plot was terminated.")
}
}
requireNamespace("tcltk", quietly=TRUE)
fig.type <- ""
if (identical(type, "path") ||
(is.null(type) && dim(x$loadings[[1]][[1]])[1] < 50)) {
if(dim(x$loadings[[1]][[1]])[1] > 100) {
msg <- paste0("The number of variables must be less than or",
"equal to 100 to plot the solution path.")
stop(msg)
}
if(Window.Height<250 || Window.Height>2000) {
stop("'Window.Height' must be in [250,2000].")
}
fig.type <- "path"
} else if (identical(type, "heatmap") ||
(is.null(type) && dim(x$x)[2] >= 50)) {
fig.type <- "heatmap"
} else {
stop("Only 'path' and 'heatmap' are available for 'type'")
}
L <- x$loadings
lambdas <- x$rho
gammas <- x$gamma
if(df.method=="reparametrization"){
GFIs <- x$GFI
AGFIs <- x$AGFI
CFIs <- x$CFI
RMSEAs <- x$RMSEA
SRMRs <- x$SRMR
AICs <- x$AIC
BICs <- x$BIC
CAICs <- x$CAIC
EBICs <- x$EBIC
}
if(df.method=="active"){
GFIs <- x$GFI
AGFIs <- x$AGFI_dfnonzero
CFIs <- x$CFI_dfnonzero
RMSEAs <- x$RMSEA_dfnonzero
SRMRs <- x$SRMR
AICs <- x$AIC_dfnonzero
BICs <- x$BIC_dfnonzero
CAICs <- x$CAIC_dfnonzero
EBICs <- x$EBIC_dfnonzero
}
info.fanc <- list("Rad.Ellipse"=50, "Len.Rec"=50,
"Window.Height"=Window.Height,
"N.var"=NULL, "N.fac"=NULL, "N.lambda"=NULL,
"L"=NULL, "lambdas"=NULL, "num.lambda"=1,
"num.gamma"=1,"num.GFI"=1)
info.fanc$lambda.current <- lambdas[1,1]
info.fanc$gamma.current <- gammas[1]
info.fanc$GFI.current <- GFIs[1]
info.fanc$AGFI.current <- AGFIs[1]
info.fanc$CFI.current <- CFIs[1]
info.fanc$RMSEA.current <- RMSEAs[1]
info.fanc$SRMR.current <- SRMRs[1]
info.fanc$AIC.current <- AICs[1]
info.fanc$BIC.current <- BICs[1]
info.fanc$CAIC.current <- CAICs[1]
info.fanc$EBIC.current <- EBICs[1]
info.fanc$L <- L
info.fanc$lambdas <- lambdas
info.fanc$gammas <- gammas
info.fanc$num.lambda <- 1
info.fanc$num.gamma <- 1
info.fanc$GFIs <- GFIs
info.fanc$AGFIs <- AGFIs
info.fanc$CFIs <- CFIs
info.fanc$RMSEAs <- RMSEAs
info.fanc$SRMRs <- SRMRs
info.fanc$AICs <- AICs
info.fanc$BICs <- BICs
info.fanc$CAICs <- CAICs
info.fanc$EBICs <- EBICs
info.fanc$N.var <- dim(info.fanc$L[[1]][[1]])[1]
info.fanc$N.fac <- dim(info.fanc$L[[1]][[1]])[2]
info.fanc$N.lambda <- length(info.fanc$L[[1]])
info.fanc$N.gamma <- length(info.fanc$L)
info.fanc$Window.Width <- max(((info.fanc$N.var+1) * info.fanc$Len.Rec + (info.fanc$N.var+2) * info.fanc$Len.Rec / 2), ((info.fanc$N.fac) * 1.5 * info.fanc$Rad.Ellipse),650)
n.col <- 256
col.red <- rgb(red=1, green = (0:n.col)/n.col, blue = (0:n.col)/n.col,
names = paste("red", 0:n.col, sep = "."))
col.black <- rgb(red=(0:n.col)/n.col, green = (0:n.col)/n.col,
blue = (0:n.col)/n.col, names = paste("black", 0:n.col, sep = "."))
col.all <- c(col.red,rev(col.black))
max.col <- 0
for(i in 1:length(x$loadings)){
for(j in 1:length(x$loadings[[1]])){
max.col <- max(max.col,max(abs(x$loadings[[i]][[j]])))
}
}
isPDF <- FALSE
PDFFileName <- ""
pngFileName <- ""
uniqFilename <- function(suffix) {
nlen <- 17
st <- strtoi(charToRaw('a'), 16)
fin <- strtoi(charToRaw('z'), 16)
fname <- ""
while (TRUE) {
xraw <- as.raw(floor(runif(nlen, st, fin+1)))
fname <- paste(rawToChar(xraw), '.',suffix,sep='',collapse='')
if (!file.exists(fname)) {
break
}
}
return(fname)
}
minFontSize <- 10
wscale <- 1.2
win.dpi <- 72
apprFontSize <- function( width, nlen, dpi=win.dpi ) {
width0 <- floor(width * wscale)
pts <- floor( 72*width0/(nlen*dpi) )
len <- nlen
if (pts<minFontSize) {
len <- floor( 72*width0/(minFontSize*dpi) )
pts <- minFontSize
}
return( c(pts, len) )
}
cbExposeLabelLambda <- function () {
text <- sprintf ("rho : %.6f", info.fanc$lambda.current)
tcltk::tkconfigure(fr3.label, text=text, font=fontSmall)
}
cbExposeLabelGFI <- function () {
text <- sprintf("%5s: %5.3f", "GFI", info.fanc$GFI.current)
tcltk::tkconfigure(fr1.gfi, text=text, font=fontSmall)
}
cbExposeLabelAGFI <- function () {
text <- sprintf("%5s: %5.3f", "AGFI", info.fanc$AGFI.current)
tcltk::tkconfigure(fr1.agfi, text=text, font=fontSmall)
}
cbExposeLabelCFI <- function () {
text <- sprintf("%5s: %5.3f", "CFI", info.fanc$CFI.current)
tcltk::tkconfigure(fr1.cfi, text=text, font=fontSmall)
}
cbExposeLabelRMSEA <- function () {
text <- sprintf("%5s: %5.3f", "RMSEA", info.fanc$RMSEA.current)
tcltk::tkconfigure(fr1.rmsea, text=text, font=fontSmall)
}
cbExposeLabelSRMR <- function () {
text <- sprintf("%5s: %5.3f", "SRMR", info.fanc$SRMR.current)
tcltk::tkconfigure(fr1.srmr, text=text, font=fontSmall)
}
cbExposeLabelAIC <- function () {
text <- sprintf("%5s: %.4f", "AIC", info.fanc$AIC.current)
tcltk::tkconfigure(fr2.aic, text=text, font=fontSmall)
}
cbExposeLabelBIC <- function () {
text <- sprintf("%5s: %.4f", "BIC", info.fanc$BIC.current)
tcltk::tkconfigure(fr2.bic, text=text, font=fontSmall)
}
cbExposeLabelCAIC <- function () {
text <- sprintf("%5s: %.4f", "CAIC", info.fanc$CAIC.current)
tcltk::tkconfigure(fr2.caic, text=text, font=fontSmall)
}
cbExposeLabelEBIC <- function () {
text <- sprintf("%5s: %.4f", "EBIC", info.fanc$EBIC.current)
tcltk::tkconfigure(fr2.ebic, text=text, font=fontSmall)
}
cbExposeLabelGamma <- function () {
text <- sprintf ("gam : %f", info.fanc$gamma.current)
tcltk::tkconfigure(fr4.label, text=text, font=fontSmall)
}
onClickLoadings <- function () {
print(info.fanc$L[[info.fanc$num.gamma]][[info.fanc$num.lambda]])
}
onClickPDF <- function() {
filename <- tcltk::tclvalue(tcltk::tkgetSaveFile())
if (nchar(filename)>0) {
isPDF <<- TRUE
PDFFileName <<- filename
cbExposeCanvas()
isPDF <<- FALSE
}
}
onClickOut <- function() {
lambda.current <- info.fanc$lambda.current
gamma.current <- info.fanc$gamma.current
print(out(x, rho=lambda.current, gamma=gamma.current, df.method=df.method))
}
cbExposePath <- function () {
maxStrLen <- 6
orgFontSize <- par("ps")
N.var <- info.fanc$N.var
N.fac <- info.fanc$N.fac
Window.Width <- as.numeric(tcltk::tkwinfo("width", canvas))
Window.Height <- as.numeric(tcltk::tkwinfo("height", canvas))
scale.x <- Window.Width / info.fanc$Window.Width
scale.y <- Window.Height / info.fanc$Window.Height
Rad.Ellipse.x <- info.fanc$Rad.Ellipse * scale.x * 2
Rad.Ellipse.y <- info.fanc$Rad.Ellipse * scale.y
Len.Rec.x <- info.fanc$Len.Rec * scale.x
Len.Rec.y <- info.fanc$Len.Rec * scale.y
Sep.Ellipse <- info.fanc$Rad.Ellipse * scale.x / 2
Step.Ellipse <- Rad.Ellipse.x + Sep.Ellipse
Sep.Rec <- Len.Rec.x/2
Step.Rec <- Len.Rec.x + Sep.Rec
len <- 1 + floor(log10(N.fac))
fontParams1 <- apprFontSize(Rad.Ellipse.x, len)
if (length(colnames(x$x)) == 0 ) {
len <- 1 + floor(log10(N.var)) + 1
fontParams2 <- apprFontSize(Len.Rec.x, len)
} else {
len <- max(nchar(colnames(x$x)))
if ( len > maxStrLen ) {
len <- maxStrLen+2
}
fontParams2 <- apprFontSize(Len.Rec.x, len)
}
fontSize <- min(c(fontParams1[1], fontParams2[1]))
strLen <- fontParams2[2]
if (strLen > maxStrLen) {
strLen <- maxStrLen
}
HN.var <- N.var / 2
HN.fac <- N.fac / 2
par(plt=c(0,1,0,1))
par(mai=c(0, 0, 0, 0))
par(mar=c(0, 0, 0, 0))
par(omd=c(0, 1, 0, 1))
par(oma=c(0, 0, 0, 0))
par(omi=c(0, 0, 0, 0))
par(xpd=NA)
dev.off()
if ( isPDF == TRUE ) {
aspect <- Window.Width / Window.Height
if ( aspect > 1.417 ) {
paper.Width <- 8.5
paper.Height <- 8.5 / aspect
} else {
paper.Height <- 6
paper.Width <- 6 * aspect
}
winWidthInch <- Window.Width / win.dpi
printScale.x <- paper.Width / winWidthInch
printFontSize <- floor(fontSize*printScale.x)
print(sprintf("printFontSize=%d", printFontSize))
pdf(file=PDFFileName, width=paper.Width, height=paper.Height,
family="Courier" )
} else {
pngFileName <- uniqFilename('png')
png(filename=pngFileName, width=Window.Width,
height=Window.Height)
}
plot(NULL, NULL, xlim=c(0,Window.Width), ylim=c(Window.Height,0),
axes=FALSE, ann=FALSE)
Rem.N.fac <- N.fac %% 2
LineWidth <- 2
x0 <- Window.Width / 2
y0 <- 0.1 * Window.Height
y1 <- y0 - Rad.Ellipse.y / 2
y2 <- y0 + Rad.Ellipse.y / 2
offset.num <- 1
Offset.Ellipse <- Sep.Ellipse / 2
NN.fac <- HN.fac
rad <- seq(-pi, pi, length=40)
if (Rem.N.fac != 0) {
offset.num <- 2
Offset.Ellipse <- Rad.Ellipse.x/2 + Sep.Ellipse
NN.fac <- floor(HN.fac)
}
if (Rem.N.fac != 0) {
x1 <- x0 - Rad.Ellipse.x/2
x2 <- x0 + Rad.Ellipse.x/2
lines(cos(rad)*Rad.Ellipse.x/2+x0, sin(rad)*Rad.Ellipse.y/2+y0,
lwd=LineWidth )
if (isPDF == TRUE) {
par(ps=printFontSize)
} else {
par(ps=fontSize)
}
text <- sprintf ("f%d", NN.fac + 1)
x1 <- x0
text(x1, y0, labels=text)
par(ps=orgFontSize)
}
if (NN.fac>0) {
for (i in 1:NN.fac) {
ii <- i - 1
x1 <- x0 + Offset.Ellipse + ii*Step.Ellipse
x2 <- x1 + Rad.Ellipse.x
xc <- (x1+x2)/2
lines(cos(rad)*Rad.Ellipse.x/2+xc, sin(rad)*Rad.Ellipse.y/2+y0,
lwd=LineWidth)
x2 <- x0 - Offset.Ellipse - ii*Step.Ellipse
x1 <- x2 - Rad.Ellipse.x
xc <- (x1+x2)/2
lines(cos(rad)*Rad.Ellipse.x/2+xc, sin(rad)*Rad.Ellipse.y/2+y0,
lwd=LineWidth)
if (isPDF == TRUE) {
par(ps=printFontSize)
} else {
par(ps=fontSize)
}
text <- sprintf ("f%d", NN.fac + offset.num + ii)
x1 <- x0 + (Offset.Ellipse+Rad.Ellipse.x/2) + ii*Step.Ellipse
text(x1, y0, labels=text, ps=fontSize)
text <- sprintf ("f%d", NN.fac - ii)
x1 <- x0 - (Offset.Ellipse+Rad.Ellipse.x/2) - ii*Step.Ellipse
text(x1, y0, labels=text, ps=fontSize)
par(ps=orgFontSize)
}
}
Rem.N.var <- N.var %% 2
LineWidth <- 2
y0 <- 0.9 * Window.Height
y1 <- y0 - Len.Rec.y / 2
y2 <- y0 + Len.Rec.y / 2
Offset.Rec <- Sep.Rec / 2
offset.num <- 1
NN.var <- HN.var
if (Rem.N.var != 0) {
Offset.Rec <- Len.Rec.x/2 + Sep.Rec
offset.num <- 2
NN.var <- floor(HN.var)
}
if (Rem.N.var != 0) {
x1 <- x0 - Len.Rec.x/2
x2 <- x0 + Len.Rec.x/2
rect(x1, y1, x2, y2, lwd=LineWidth)
if ( length(colnames(x$x)) == 0 ) {
text <- sprintf ("x%d", NN.var + 1)
} else {
text <- colnames(x$x)[NN.var + 1]
if (nchar(text) > maxStrLen ) {
text <- paste0(substring(text, 1, strLen), "..")
}
}
if (isPDF == TRUE) {
par(ps=printFontSize)
} else {
par(ps=fontSize)
}
x1 <- x0
text(x1, y0, labels=text)
par(ps=orgFontSize)
}
if (NN.var>0) {
for (i in 1:NN.var) {
ii <- i - 1
x1 <- x0 + Offset.Rec + ii*(3/2*Len.Rec.x)
x2 <- x1 + Len.Rec.x
rect(x1, y1, x2, y2, lwd=LineWidth)
x2 <- x0 - Offset.Rec - ii*(3/2*Len.Rec.x)
x1 <- x2 - Len.Rec.x
rect(x1, y1, x2, y2, lwd=LineWidth)
if ( length(colnames(x$x)) == 0 ) {
text1 <- sprintf ("x%d", NN.var + offset.num + ii)
text2 <- sprintf ("x%d", NN.var - ii)
} else {
text1 <- colnames(x$x)[NN.var + offset.num + ii]
text2 <- colnames(x$x)[NN.var - ii]
if (nchar(text1) > strLen ) {
text1 <- paste0(substring(text1, 1, strLen), "..")
}
if (nchar(text2) > strLen ) {
text2 <- paste0(substring(text2, 1, strLen), "..")
}
}
if (isPDF == TRUE) {
par(ps=printFontSize)
} else {
par(ps=fontSize)
}
x1 <- x0 + (Offset.Rec+Len.Rec.x/2) + ii*(3/2*Len.Rec.x)
text(x1, y0, labels=text1)
x1 <- x0 - (Offset.Rec+Len.Rec.x/2) - ii*(3/2*Len.Rec.x)
text(x1, y0, labels=text2)
par(ps=orgFontSize)
}
}
x0 <- Window.Width / 2
y2 <- 0.1*Window.Height + Rad.Ellipse.y/2
y1 <- 0.9*Window.Height - Len.Rec.y/2
x0.fac <- x0-(Sep.Ellipse+Rad.Ellipse.x)/2-Step.Ellipse*(NN.fac-1)
x0.var <- x0 - (Sep.Rec+Len.Rec.x)/2 - Step.Rec*(NN.var-1)
cur.lambda <- info.fanc$num.lambda
cur.gamma <- info.fanc$num.gamma
if (Rem.N.fac != 0) {
x0.fac <- x0-(Sep.Ellipse+Rad.Ellipse.x)-Step.Ellipse*(NN.fac-1)
}
if (Rem.N.var != 0 ) {
x0.var <- x0 - (Sep.Rec+Len.Rec.x) - Step.Rec*(NN.var-1)
}
for (i in 1:N.var) {
ii <- i - 1
x1 <- x0.var + ii*Step.Rec
for (j in 1:N.fac) {
jj <- j - 1
x2 <- x0.fac + jj*Step.Ellipse
val <- info.fanc$L[[cur.gamma]][[cur.lambda]][i, j]
lw0 <- abs((val * 10))
LineWidth <- 0
if (lw0 > 0.05 && lw0<1.5 ) {
LineWidth <- 1
} else if (lw0 >=1.5) {
LineWidth <- as.integer( lw0 + 0.5 )
}
color <- "black"
if (info.fanc$L[[cur.gamma]][[cur.lambda]][i, j] < 0) {
color <- "red"
}
if (LineWidth > 0) {
lines(c(x1, x2), c(y1, y2), col=color, lwd=LineWidth)
}
}
}
dev.off()
graphics.off()
if ( isPDF == FALSE ) {
image1 <- tcltk::tclVar()
tcltk::tkimage.create("photo", image1, file=pngFileName)
tcltk::tkdelete(canvas, tag="all")
tcltk::tkcreate(canvas, "image",0,0,image=image1,anchor="nw")
file.remove(pngFileName)
}
}
cbExposeHeatmap <- function() {
loadings <-
info.fanc$L[[info.fanc$num.gamma]][[info.fanc$num.lambda]]
loadings <- as.matrix(loadings)
loadings <- t(loadings)
loadings <- fliplr.fanc(loadings)
Window.Width <- as.numeric(tcltk::tkwinfo("width", canvas))
Window.Height <- as.numeric(tcltk::tkwinfo("height", canvas))
if ( isPDF == FALSE ) {
pngFileName <- uniqFilename('png')
png(pngFileName, width=Window.Width, height=Window.Height)
} else {
pdf(file=PDFFileName, width=6, height=6)
}
image(loadings, col=col.all, zlim=c(-max.col, max.col),
xlab="factors", ylab="variables")
dev.off()
if ( isPDF == FALSE ) {
image1 <- tcltk::tclVar()
tcltk::tkimage.create("photo", image1, file=pngFileName)
tcltk::tkdelete(canvas, tag="all")
tcltk::tkcreate(canvas, "image", 0, 0, image=image1,
anchor="nw" )
file.remove(pngFileName)
}
}
cbExposeCanvas <- function() {
if ( fig.type == "path" ) {
cbExposePath()
} else {
cbExposeHeatmap()
}
}
onChangeParam <- function (...) {
value <- as.numeric(tcltk::tclvalue(LambdaValue))
num.lambda <- value + 1
if (num.lambda < 1 ) {
num.lambda <- 1
}
value <- as.numeric(tcltk::tclvalue(GammaValue))
num.gamma <- value + 1
if (num.gamma < 1) {
num.gamma <- 1
}
info.fanc$num.lambda <<- num.lambda
info.fanc$num.gamma <<- num.gamma
info.fanc$lambda.current<<-info.fanc$lambdas[num.lambda, num.gamma]
info.fanc$gamma.current<<-info.fanc$gammas[num.gamma]
info.fanc$GFI.current <<- info.fanc$GFIs[num.lambda, num.gamma]
info.fanc$AGFI.current <<- info.fanc$AGFIs[num.lambda, num.gamma]
info.fanc$CFI.current <<- info.fanc$CFIs[num.lambda, num.gamma]
info.fanc$RMSEA.current <<- info.fanc$RMSEAs[num.lambda, num.gamma]
info.fanc$SRMR.current <<- info.fanc$SRMRs[num.lambda, num.gamma]
info.fanc$AIC.current <<- info.fanc$AICs[num.lambda, num.gamma]
info.fanc$BIC.current <<- info.fanc$BICs[num.lambda, num.gamma]
info.fanc$CAIC.current <<- info.fanc$CAICs[num.lambda, num.gamma]
info.fanc$EBIC.current <<- info.fanc$EBICs[num.lambda, num.gamma]
cbExposeCanvas()
cbExposeLabelLambda()
cbExposeLabelGFI()
cbExposeLabelAGFI()
cbExposeLabelCFI()
cbExposeLabelRMSEA()
cbExposeLabelSRMR()
cbExposeLabelAIC()
cbExposeLabelBIC()
cbExposeLabelCAIC()
cbExposeLabelEBIC()
cbExposeLabelGamma()
}
onClickOverview <- function() {
cbExposeSubPath <- function() {
N.var <- info.fanc$N.var
N.fac <- info.fanc$N.fac
window.width<-as.numeric(tcltk::tkwinfo("width", subCanvas))
window.height<-as.numeric(tcltk::tkwinfo("height",subCanvas))
canvas.height <- window.height/ndiv.lambda
canvas.width <- window.width/ndiv.gamma
scale.x <- canvas.width / info.fanc$Window.Width
scale.y <- canvas.height / info.fanc$Window.Height
Rad.Ellipse.x <- info.fanc$Rad.Ellipse * scale.x * 2
Rad.Ellipse.y <- info.fanc$Rad.Ellipse * scale.y
Len.Rec.x <- info.fanc$Len.Rec * scale.x
Len.Rec.y <- info.fanc$Len.Rec * scale.y
Sep.Ellipse <- info.fanc$Rad.Ellipse * scale.x / 2
Step.Ellipse <- Rad.Ellipse.x + Sep.Ellipse
Sep.Rec <- Len.Rec.x/2
Step.Rec <- Len.Rec.x + Sep.Rec
HN.var <- N.var / 2
HN.fac <- N.fac / 2
tcltk::tkdelete(subCanvas, tag="all")
for (i in 1:(ndiv.lambda-1)) {
yy <- i * canvas.height
tcltk::tkcreate(subCanvas, "line", 0, yy, window.width, yy,
width=2, fill="
}
for (i in 1:(ndiv.gamma-1)) {
xx <- i * canvas.width
tcltk::tkcreate(subCanvas, "line", xx, 0,
xx, window.height, width=2, fill="
}
Rem.N.fac <- N.fac %% 2
Rem.N.var <- N.var %% 2
NN.fac <- HN.fac
if (Rem.N.fac != 0) {
NN.fac <- floor(HN.fac)
}
NN.var <- HN.var
if (Rem.N.var != 0) {
NN.var <- floor(HN.var)
}
LineWidth <- 1
for ( i in 1:ndiv.gamma ) {
x0 <- (i-1)*canvas.width + canvas.width/2
for ( j in 1:ndiv.lambda ) {
y0 <- (j-1)*canvas.height + 0.2 * canvas.height
y1 <- y0 - Rad.Ellipse.y / 2
y2 <- y0 + Rad.Ellipse.y / 2
Offset.Ellipse <- Sep.Ellipse / 2
offset.num <- 1
if (Rem.N.fac != 0) {
offset.num <- 2
Offset.Ellipse <- Rad.Ellipse.x/2 + Sep.Ellipse
}
if (Rem.N.fac != 0) {
x1 <- x0 - Rad.Ellipse.x/2
x2 <- x0 + Rad.Ellipse.x/2
tcltk::tkcreate(subCanvas, "oval", x1, y1, x2, y2,
width=LineWidth)
text <- sprintf ("f%d", NN.fac + 1)
x1 <- x0
tcltk::tkcreate(subCanvas, "text", x1, y0, text=text,
anchor="center", font=fontTiny)
}
if (NN.fac>0) {
for (ii in 1:NN.fac) {
iii <- ii - 1
x1 <- x0 + Offset.Ellipse + iii*Step.Ellipse
x2 <- x1 + Rad.Ellipse.x
tcltk::tkcreate(subCanvas, "oval", x1, y1, x2, y2,
width=LineWidth)
x2 <- x0 - Offset.Ellipse - iii*Step.Ellipse
x1 <- x2 - Rad.Ellipse.x
tcltk::tkcreate(subCanvas, "oval", x1, y1, x2, y2,
width=LineWidth)
text <- sprintf ("f%d", NN.fac + offset.num + iii)
x1 <- x0 + (Offset.Ellipse+Rad.Ellipse.x/2) + iii*Step.Ellipse
tcltk::tkcreate(subCanvas, "text", x1, y0,
text=text, anchor="center", font=fontTiny)
text <- sprintf ("f%d", NN.fac - iii)
x1 <- x0 - (Offset.Ellipse+Rad.Ellipse.x/2) - iii*Step.Ellipse
tcltk::tkcreate(subCanvas, "text", x1, y0,
text=text, anchor="center", font=fontTiny)
}
}
}
}
LineWidth <- 1
for ( i in 1:ndiv.gamma ) {
x0 <- (i-1)*canvas.width + canvas.width/2
for ( j in 1:ndiv.lambda ) {
y0 <- (j-1)*canvas.height + 0.9 * canvas.height
y1 <- y0 - Len.Rec.y / 2
y2 <- y0 + Len.Rec.y / 2
Offset.Rec <- Sep.Rec / 2
offset.num <- 1
if (Rem.N.var != 0) {
Offset.Rec <- Len.Rec.x/2 + Sep.Rec
offset.num <- 2
}
if (Rem.N.var != 0) {
x1 <- x0 - Len.Rec.x/2
x2 <- x0 + Len.Rec.x/2
tcltk::tkcreate(subCanvas, "rectangle", x1, y1,
x2, y2, width=LineWidth)
text <- sprintf ("x%d", NN.var + 1)
x1 <- x0
tcltk::tkcreate(subCanvas, "text", x1, y0, text=text,
anchor="center", font=fontTiny)
}
if (NN.var>0) {
for (ii in 1:NN.var) {
iii <- ii - 1
x1 <- x0 + Offset.Rec + iii*Step.Rec
x2 <- x1 + Len.Rec.x
tcltk::tkcreate(subCanvas, "rectangle", x1, y1,
x2, y2, width=LineWidth)
x2 <- x0 - Offset.Rec - iii*Step.Rec
x1 <- x2 - Len.Rec.x
tcltk::tkcreate(subCanvas, "rectangle", x1, y1,
x2, y2, width=LineWidth)
text <- sprintf ("x%d", NN.var + offset.num + iii)
x1 <- x0 + Offset.Rec+Len.Rec.x/2 + iii*Step.Rec
tcltk::tkcreate(subCanvas, "text", x1, y0,
text=text, anchor="center", font=fontTiny)
text <- sprintf ("x%d", NN.var - iii)
x1 <- x0 - Offset.Rec - iii*Step.Rec - Len.Rec.x/2
tcltk::tkcreate(subCanvas, "text", x1, y0,
text=text, anchor="center", font=fontTiny)
}
}
}
}
for ( i in 1:ndiv.gamma ) {
x0 <- (i-1)*canvas.width + canvas.width/2
for ( j in 1:ndiv.lambda ) {
y2 <- (j-1)*canvas.height + 0.2*canvas.height +
Rad.Ellipse.y/2
y1 <- (j-1)*canvas.height + 0.9*canvas.height -
Len.Rec.y/2
x0.fac <- x0 - Step.Ellipse/2 - Step.Ellipse*(NN.fac-1)
x0.var <- x0 - Step.Rec/2 - Step.Rec*(NN.var-1)
cur.lambda <- lambda.list[j]
cur.gamma <- gamma.list[i]
if (Rem.N.fac != 0) {
x0.fac <- x0 - Step.Ellipse*NN.fac
}
if (Rem.N.var != 0 ) {
x0.var <- x0 - Step.Rec*NN.var
}
for (ii in 1:N.var) {
x1 <- x0.var + (ii-1)*Step.Rec
for (jj in 1:N.fac) {
x2 <- x0.fac + (jj-1)*Step.Ellipse
val<-info.fanc$L[[cur.gamma]][[cur.lambda]][ii, jj]
color <- "black"
if (val < 0) {
color <- "red"
}
LineWidth <- abs(val * 5)
if (LineWidth > 0.025) {
tcltk::tkcreate(subCanvas, "line", x1, y1,
x2, y2, fill=color, width=LineWidth)
}
}
}
}
}
for ( i in 1:ndiv.gamma ) {
x0 <- (i-1)*canvas.width + canvas.width/2
for ( j in 1:ndiv.lambda ) {
y0 <- (j-1)*canvas.height + 0.05*canvas.height
cur.lambda <- lambda.list[j]
cur.gamma <- gamma.list[i]
lambda <- info.fanc$lambdas[cur.lambda, cur.gamma]
gamma <- info.fanc$gammas[cur.gamma]
text <- sprintf("lambda= %.3f gamma= %.3f",
lambda, gamma)
tcltk::tkcreate(subCanvas, "text", x0, y0, text=text,
anchor="center", font=fontTiny )
}
}
}
cbExposeSubHeatmap <- function() {
N.var <- info.fanc$N.var
N.fac <- info.fanc$N.fac
window.width<-as.numeric(tcltk::tkwinfo("width", subCanvas))
window.height<-as.numeric(tcltk::tkwinfo("height",subCanvas))
canvas.height <- window.height/ndiv.lambda
canvas.width <- window.width/ndiv.gamma
tcltk::tkdelete(subCanvas, tag="all")
for (i in 1:ndiv.gamma) {
cur.gamma <- gamma.list[i]
x.pos <- canvas.width * (i-1)
gamma <- info.fanc$gammas[cur.gamma]
for (j in 1:ndiv.lambda) {
cur.lambda <- lambda.list[j]
y.pos <- canvas.height * (j-1)
lambda <- info.fanc$lambdas[cur.lambda, cur.gamma]
loadings <- info.fanc$L[[cur.gamma]][[cur.lambda]]
loadings <- as.matrix(loadings)
loadings <- t(loadings)
loadings <- fliplr.fanc(loadings)
text <- sprintf("lambda= %.3f gamma= %.3f",
lambda, gamma)
tmpFile <- uniqFilename('png')
png(tmpFile, width=canvas.width,
height=canvas.height)
image(loadings, col=col.all, main=text,
zlim=c(-max.col, max.col),
xlab="factors", ylab="variables")
dev.off()
image1 <- tcltk::tclVar()
tcltk::tkimage.create("photo", image1, file=tmpFile)
tcltk::tkcreate(subCanvas, "image", x.pos, y.pos,
image=image1, anchor="nw" )
file.remove(tmpFile)
}
}
}
cbExposeSubCanvas <- function() {
if ( fig.type == "path" ) {
cbExposeSubPath()
} else {
cbExposeSubHeatmap()
}
}
onClickDiv <- function() {
if (ndiv.lambda == 5) {
ndiv.lambda <<- 4
ndiv.gamma <<- 4
tcltk::tkconfigure(subFrm.div, text="5x5")
tcltk::tktitle(subWin) <- "Overview (4x4)"
} else {
ndiv.lambda <<- 5
ndiv.gamma <<- 5
tcltk::tkconfigure(subFrm.div, text="4x4")
tcltk::tktitle(subWin) <- "Overview (5x5)"
}
if (ndiv.lambda > N.lambda) {
ndiv.lambda <<- N.lambda
}
if (ndiv.gamma > N.gamma) {
ndiv.gamma <<- N.gamma
}
cbExposeSubCanvas()
}
N.lambda <- info.fanc$N.lambda
N.gamma <- info.fanc$N.gamma
ndiv.lambda <- 5
ndiv.gamma <- 5
if (N.lambda < ndiv.lambda) {
ndiv.lambda <- N.lambda
}
if (N.gamma < ndiv.gamma) {
ndiv.gamma <- N.gamma
}
lambda.list <- vector(length=ndiv.lambda)
gamma.list <- vector(length=ndiv.gamma)
if (ndiv.lambda == 1) {
lambda.list[1] <- 1
} else {
d.lambda <- (N.lambda-1) / (ndiv.lambda-1)
for (i in 1:ndiv.lambda) {
lambda.list[i] <- 1 + as.integer((i-1)*d.lambda+0.1)
}
}
if (ndiv.gamma == 1) {
gamma.list[1] <- 1
} else {
d.gamma <- (N.gamma-1) / (ndiv.gamma-1)
for (i in 1:ndiv.gamma) {
gamma.list[i] <- 1 + as.integer((i-1)*d.gamma+0.1)
}
}
subWin <- tcltk::tktoplevel()
title <- sprintf("Overview (%dx%d)", ndiv.lambda, ndiv.gamma)
tcltk::tktitle(subWin) <- title
subCanvas <- tcltk::tkcanvas(subWin, background="
tcltk::tkpack(subCanvas, expand=TRUE, fill="both")
tcltk::tkbind(subCanvas, "<Configure>", cbExposeSubCanvas)
subFrm <- tcltk::tkframe(subWin)
subFrm.close <- tcltk::tkbutton(subFrm, text="Close",
width=Text.Width, padx=10,
command=function() tcltk::tkdestroy(subWin))
subFrm.div <- tcltk::tkbutton(subFrm, text="4x4",
width=Text.Width, padx=10, command=onClickDiv)
tcltk::tkpack(subFrm.close, side="right")
tcltk::tkpack(subFrm.div, side="right")
tcltk::tkpack(subFrm, side="right")
tcltk::tkwm.geometry(subWin, "1200x850")
}
lambdas <- info.fanc$lambdas
gammas <- info.fanc$gammas
N.lambda <- info.fanc$N.lambda
N.gamma <- info.fanc$N.gamma
Min.lambda <- 0
Max.lambda <- N.lambda - 1
Step.lambda <- 1
Min.gamma <- 0
Max.gamma <- N.gamma - 1
Step.gamma <- 1
LambdaValue <- tcltk::tclVar(sprintf("f", Min.lambda))
GammaValue <- tcltk::tclVar(sprintf("f", Min.gamma))
Items <- c()
fontNormal <- tcltk::tkfont.create( family="Courier New", size=14)
fontSmall <- tcltk::tkfont.create( family="Courier New", size=10)
fontTiny <- tcltk::tkfont.create( family="Courier New", size=8)
Window.Width <- sprintf("%d", info.fanc$Window.Width)
Window.Height0 <- sprintf("%d", info.fanc$Window.Height + 200)
Text.Width <- "16"
top <- tcltk::tktoplevel(width=Window.Width, height=Window.Height0)
canvas <- tcltk::tkcanvas(top, background="
tcltk::tkpack(canvas, expand=TRUE, fill="both")
tcltk::tkbind(canvas, "<Configure>", cbExposeCanvas)
frmAll <- tcltk::tkframe(top, width=Window.Width)
fr1 <- tcltk::tkframe(frmAll, width=Window.Width)
fr1.gfi <- tcltk::tklabel(fr1, width=Text.Width, anchor="w", text="")
fr1.agfi <- tcltk::tklabel(fr1, width=Text.Width, anchor="w", text="")
fr1.cfi <- tcltk::tklabel(fr1, width=Text.Width, anchor="w", text="")
fr1.rmsea <- tcltk::tklabel(fr1, width=Text.Width, anchor="w", text="")
fr1.srmr <- tcltk::tklabel(fr1, width=Text.Width, anchor="w", text="")
tcltk::tkpack(fr1.gfi, side="left")
tcltk::tkpack(fr1.agfi, side="left")
tcltk::tkpack(fr1.cfi, side="left")
tcltk::tkpack(fr1.rmsea, side="left")
tcltk::tkpack(fr1.srmr, side="left")
tcltk::tkpack(fr1)
fr2 <- tcltk::tkframe(frmAll, width=Window.Width)
fr2.aic <- tcltk::tklabel(fr2, width=Text.Width, anchor="w", text="" )
fr2.bic <- tcltk::tklabel(fr2, width=Text.Width, anchor="w", text="" )
fr2.caic <- tcltk::tklabel(fr2, width=Text.Width, anchor="w", text="" )
fr2.ebic <- tcltk::tklabel(fr2, width=Text.Width, anchor="w", text="" )
fr2.dum <- tcltk::tklabel(fr2, width=Text.Width, anchor="w", text="" )
tcltk::tkpack(fr2.aic, side="left")
tcltk::tkpack(fr2.bic, side="left")
tcltk::tkpack(fr2.caic, side="left")
tcltk::tkpack(fr2.ebic, side="left")
tcltk::tkpack(fr2.dum, side="left")
tcltk::tkpack(fr2)
fr3 <- tcltk::tkframe(frmAll, width=Window.Width)
fr3.label <- tcltk::tklabel(fr3, width=Text.Width, anchor="w", text="")
fr3.scale <- tcltk::tkscale(fr3, length=250, from=Min.lambda,
to=Max.lambda, resolution=Step.lambda, variable=LambdaValue,
orient="horizontal", showvalue=0, command=onChangeParam )
tcltk::tkpack(fr3.label, side="left")
tcltk::tkpack(fr3.scale, side="left")
tcltk::tkpack(fr3)
fr4 <- tcltk::tkframe(frmAll, width=Window.Width)
fr4.label <- tcltk::tklabel(fr4, width=Text.Width, anchor="w", text="")
fr4.scale <- tcltk::tkscale(fr4, length=250, from=Min.gamma,
to=Max.gamma, resolution=Step.gamma, variable=GammaValue,
orient="horizontal", showvalue=0, command=onChangeParam )
tcltk::tkpack(fr4.label, side="left")
tcltk::tkpack(fr4.scale, side="left")
tcltk::tkpack(fr4)
fr5 <- tcltk::tkframe(frmAll, width=Window.Width)
fr5.overview <- tcltk::tkbutton(fr5, text="Overview", width=Text.Width,
padx=10, command=onClickOverview)
fr5.loadings <- tcltk::tkbutton(fr5, text="Output loadings",
width=Text.Width, padx=10, command=onClickLoadings)
fr5.out <- tcltk::tkbutton(fr5, text="Output params", width=Text.Width,
padx=10, command=onClickOut)
fr5.pdf <- tcltk::tkbutton(fr5, text="PDF", width=Text.Width,
padx=20, command=onClickPDF)
tcltk::tkpack(fr5.loadings, side="right")
tcltk::tkpack(fr5.overview, side="right")
tcltk::tkpack(fr5.out, side="right")
tcltk::tkpack(fr5.pdf, side="right")
tcltk::tkpack(fr5, side="right")
tcltk::tkpack(frmAll, fill="x")
tcltk::tkwm.geometry(top, "900x650")
if(x$type == "MC"){
tcltk::tktitle(top) <- "Factor analysis with MC+"
} else if (x$type == "prenet" ) {
tcltk::tktitle(top) <- "Factor analysis with prenet"
}
}
fliplr.fanc <- function(x){
m <- ncol(x)
x[,m:1]
} |
hillshader <- function(
elevation,
shader = "ray_shade",
filename = NULL,
...
) {
dots <- list(...)
mat <- raster_to_matrix(elevation)
shades <- lapply(
shader,
function(shd) {
shader_fun <- switch (
shd,
"ray_shade" = rayshader::ray_shade,
"lamb_shade" = rayshader::lamb_shade,
"ambient_shade" = rayshader::ambient_shade,
stop("Wrong shader option", call. = FALSE)
)
args_shader <- dots
args_shader$heightmap <- mat
args_shader <- .subset_args(fun = shader_fun, args = args_shader)
res_shd <- do.call(shader_fun, args_shader)
res_shd
})
res <- shades[[1]]
if (length(shades) > 1) {
for(i in 2:length(shades)) {
args_shadow <- dots
args_shadow$hillshade <- res
args_shadow$shadowmap <- shades[[i]]
args_shadow <- .subset_args(fun = add_shadow_2d, args = args_shadow)
res <- do.call(
add_shadow_2d,
args_shadow
)
}
}
if (!is.null(filename)) {
args_write_raster <- dots
args_write_raster$hillshade <- res
args_write_raster$elevation <- elevation
args_write_raster$filename <- filename
do.call(write_raster, args_write_raster)
return(invisible(NULL))
} else {
rast <- matrix_to_raster(res, raster = elevation)
return(rast)
}
} |
NULL
NULL
methods::setGeneric(
"add_relative_targets",
signature = methods::signature("x", "targets"),
function(x, targets) standardGeneric("add_relative_targets"))
methods::setMethod(
"add_relative_targets",
methods::signature("ProjectProblem", "numeric"),
function(x, targets) {
assertthat::assert_that(
inherits(x, "ProjectProblem"),
length(targets) %in% c(1, number_of_features(x)),
is.numeric(targets),
assertthat::noNA(targets),
min(targets) >= 0,
max(targets) <= 1)
add_manual_targets(x, tibble::tibble(feature = x$feature_names(),
type = "relative",
sense = ">=",
target = targets))
})
methods::setMethod(
"add_relative_targets",
methods::signature("ProjectProblem", "character"),
function(x, targets) {
assertthat::assert_that(
inherits(x, "ProjectProblem"),
assertthat::is.string(targets),
assertthat::noNA(targets),
assertthat::has_name(x$data$features, targets),
is.numeric(x$data$features[[targets]]),
assertthat::noNA(x$data$features[[targets]]),
min(x$data$features[[targets]]) >= 0,
max(x$data$features[[targets]]) <= 1)
add_relative_targets(x, x$data$features[[targets]])
}) |
rename <- function(x, replace, warn_missing = TRUE, warn_duplicated = TRUE ) {
names(x) <- revalue(names(x), replace, warn_missing = warn_missing)
duplicated_names <- names(x)[duplicated(names(x))]
if (warn_duplicated && (length(duplicated_names) > 0L)) {
duplicated_names_message <- paste0("`", duplicated_names, "`", collapse=", ")
warning("The plyr::rename operation has created duplicates for the ",
"following name(s): (", duplicated_names_message, ")",
call. = FALSE)
}
x
} |
expected <- eval(parse(text="c(2.0943951023932, 2.11184839491314, 2.12930168743308, 2.14675497995302, 2.16420827247297, 2.18166156499291, 2.19911485751286, 2.2165681500328, 2.23402144255274, 2.25147473507268, 2.26892802759263, 2.28638132011257, 2.30383461263251, 2.32128790515246, 2.3387411976724, 2.35619449019234, 2.37364778271229, 2.39110107523223, 2.40855436775217, 2.42600766027212, 2.44346095279206, 2.460914245312, 2.47836753783195, 2.49582083035189, 2.51327412287183, 2.53072741539178, 2.54818070791172, 2.56563400043166, 2.58308729295161, 2.60054058547155, 2.61799387799149)"));
test(id=0, code={
argv <- eval(parse(text="list(from = 2.0943951023932, to = 2.61799387799149, by = 0.0174532925199433)"));
do.call(`seq.int`, argv);
}, o=expected); |
timmaCategoryWeighted1 <- function(profile_data, sens, loo = TRUE, class) {
drug_number <- nrow(as.matrix(profile_data))
target_number <- ncol(as.matrix(profile_data))
profile_data <- matrix(profile_data, nrow = drug_number, ncol = target_number)
prof <- unique(profile_data)
dec_prof <- apply(prof, 1, function(x) strtoi(paste(x, collapse = ""), base = class))
dec <- apply(profile_data, 1, function(x) strtoi(paste(x, collapse = ""), base = class))
col_num <- length(dec_prof)
identical_idx <- sapply(dec, function(x) which(dec_prof == x))
IM_d <- array(NA, dim = c(drug_number, col_num))
IM_subset <- array(Inf, dim = c(drug_number, col_num))
IM_subw <- array(0, dim = c(drug_number, col_num))
IM_superset <- array(-Inf, dim = c(drug_number, col_num))
IM_supw <- array(0, dim = c(drug_number, col_num))
for (i in 1:drug_number) {
IM_d[i, identical_idx[i]] <- 1 * sens[i]
bin_set <- getBinary1(profile_data[i, ], profile_data)
if (length(bin_set$subset) != 0) {
subset_index <- dec_prof %in% dec[bin_set$subset]
IM_subset[i, subset_index] <- sens[i]
for (each in which(subset_index == TRUE)) {
IM_subw[i, each] <- bin_set$subw[which(dec[bin_set$subset] == dec_prof[each])[1]]
}
}
if (length(bin_set$superset) != 0) {
superset_index <- dec_prof %in% dec[bin_set$superset]
IM_superset[i, superset_index] <- sens[i]
for (each in which(superset_index == TRUE)) {
IM_supw[i, each] <- bin_set$supw[which(dec[bin_set$superset] == dec_prof[each])[1]]
}
}
}
M_d <- colMeans(IM_d, na.rm = TRUE)
maxval <- maxcpp1(IM_superset, drug_number, col_num)
minval <- mincpp1(IM_subset, drug_number, col_num)
min_subset <- minval$min
min_index <- minval$min_idx
max_superset <- maxval$max
max_index <- maxval$max_idx
cell <- is.nan(M_d) & is.finite(max_superset)
cell <- which(cell == TRUE)
if (length(cell) != 0) {
for (i in cell) {
drug_sub_cell <- !is.infinite(IM_superset[, i])
index <- max_index[i]
dec_maxsens <- identical_idx[index]
supersets_small <- IM_subset[, dec_maxsens] < max_superset[i]
common_cell <- which(drug_sub_cell & supersets_small)
if (length(common_cell) != 0) {
total <- sum(1/IM_supw[common_cell, i]) + 1/IM_supw[index, i]
max_superset[i] <- 1/IM_supw[index, i]/total * sens[index] + sum(1/IM_supw[common_cell,
i]/total * sens[common_cell])
}
}
}
cell2 <- is.nan(M_d) & is.finite(min_subset)
cell2 <- which(cell2 == TRUE)
if (length(cell2) != 0) {
for (i in cell2) {
drug_sub_cell <- !is.infinite(IM_subset[, i])
index <- min_index[i]
dec_minsens <- identical_idx[index]
subsets_small <- IM_superset[, dec_minsens] > min_subset[i]
if (length(subsets_small) == 0) {
common_cell2 <- vector("numeric")
} else {
common_cell2 <- which(drug_sub_cell & subsets_small)
}
if (length(common_cell2) != 0) {
total <- sum(1/IM_subw[common_cell, i]) + 1/IM_subw[index, i]
min_subset[i] <- 1/IM_subw[index, i]/total * sens[index] + sum(1/IM_subw[common_cell,
i]/total * sens[common_cell])
}
}
}
M <- M_d
M[cell] <- (max_superset[cell] + 1)/2
M[cell2] <- (min_subset[cell2] + 0)/2
average_index <- intersect(cell, cell2)
M[average_index] <- (max_superset[average_index] + min_subset[average_index])/2
error_predict <- rep(NA, drug_number)
pred <- rep(NA, drug_number)
if (loo == FALSE) {
pred <- M[identical_idx]
error_predict <- abs(pred - sens)
} else {
for (i in 1:drug_number) {
dim_IMd <- c(drug_number - 1, col_num)
IM_d_loo <- array(IM_d[-i, ], dim = dim_IMd)
IM_subset_loo <- array(IM_subset[-i, ], dim = dim_IMd)
IM_subw_loo <- array(IM_subw[-i, ], dim = dim_IMd)
IM_superset_loo <- array(IM_superset[-i, ], dim = dim_IMd)
IM_supw_loo <- array(IM_supw[-i, ], dim = dim_IMd)
sens_loo <- sens[-i]
drug_idx_loo <- identical_idx[-i]
M_d_loo <- M_d
M_d_loo[identical_idx[i]] <- mean(IM_d_loo[, identical_idx[i]], na.rm = TRUE)
M_loo <- M_d_loo
maxval <- maxcpp1(IM_superset_loo, drug_number - 1, col_num)
minval <- mincpp1(IM_subset_loo, drug_number - 1, col_num)
min_subset_loo <- minval$min
min_index_loo <- minval$min_idx
max_superset_loo <- maxval$max
max_index_loo <- maxval$max_idx
cell <- is.nan(M_d_loo) & is.finite(max_superset_loo)
cell <- which(cell == TRUE)
cell2 <- is.nan(M_d_loo) & is.finite(min_subset_loo)
cell2 <- which(cell2 == TRUE)
j_max <- which(cell == identical_idx[i])
j_min <- which(cell2 == identical_idx[i])
if (length(j_max) != 0 && length(j_min) == 0) {
cell_index <- cell[j_max]
drug_sub_cell <- !is.infinite(IM_superset_loo[, cell_index])
index <- max_index_loo[cell_index]
dec_maxsens <- drug_idx_loo[index]
supersets_small <- IM_subset_loo[, dec_maxsens] < max_superset_loo[cell_index]
common_cell <- which(drug_sub_cell & supersets_small)
if (length(common_cell) != 0) {
total <- sum(1/IM_supw_loo[common_cell, cell_index]) + 1/IM_supw_loo[index, cell_index]
max_superset_loo[cell_index] <- 1/IM_supw_loo[index, cell_index]/total * sens_loo[index] +
sum(1/IM_supw_loo[common_cell, cell_index]/total * sens_loo[common_cell])
}
pred[i] <- (max_superset_loo[identical_idx[i]] + 1)/2
error_predict[i] <- abs(pred[i] - sens[i])
} else if (length(j_max) == 0 && length(j_min) != 0) {
cell2_index <- cell2[j_min]
drug_sub_cell <- !is.infinite(IM_subset_loo[, cell2_index])
index <- min_index_loo[cell2_index]
dec_minsens <- drug_idx_loo[index]
supersets_small <- IM_superset_loo[, dec_minsens] > min_subset_loo[cell2_index]
common_cell <- which(drug_sub_cell & supersets_small)
if (length(common_cell) != 0) {
total <- sum(1/IM_subw_loo[common_cell, cell2_index]) + 1/IM_subw_loo[index, cell2_index]
min_subset_loo[cell2_index] <- 1/IM_subw_loo[index, cell2_index]/total * sens_loo[index] +
sum(1/IM_subw_loo[common_cell, cell2_index]/total * sens_loo[common_cell])
}
pred[i] <- (min_subset_loo[identical_idx[i]] + 0)/2
error_predict[i] <- abs(pred[i] - sens[i])
} else if (length(j_max) != 0 && length(j_min) != 0) {
cell_index <- cell[j_max]
drug_sub_cell <- !is.infinite(IM_superset_loo[, cell_index])
index <- max_index_loo[cell_index]
dec_maxsens <- drug_idx_loo[index]
supersets_small <- IM_subset_loo[, dec_maxsens] < max_superset_loo[cell_index]
common_cell <- which(drug_sub_cell & supersets_small)
if (length(common_cell) != 0) {
total <- sum(1/IM_supw_loo[common_cell, cell_index]) + 1/IM_supw_loo[index, cell_index]
max_superset_loo[cell_index] <- 1/IM_supw_loo[index, cell_index]/total * sens_loo[index] +
sum(1/IM_supw_loo[common_cell, cell_index]/total * sens_loo[common_cell])
}
cell2_index <- cell2[j_min]
drug_sub_cell <- !is.infinite(IM_subset_loo[, cell2_index])
index <- min_index_loo[cell2_index]
dec_minsens <- drug_idx_loo[index]
supersets_small <- IM_superset_loo[, dec_minsens] > min_subset_loo[cell2_index]
common_cell <- which(drug_sub_cell & supersets_small)
if (length(common_cell) != 0) {
total <- sum(1/IM_subw_loo[common_cell, cell2_index]) + 1/IM_subw_loo[index, cell2_index]
min_subset_loo[cell2_index] <- 1/IM_subw_loo[index, cell2_index]/total * sens_loo[index] +
sum(1/IM_subw_loo[common_cell, cell2_index]/total * sens_loo[common_cell])
}
pred[i] <- (max_superset_loo[identical_idx[i]] + min_subset_loo[identical_idx[i]])/2
error_predict[i] <- abs(pred[i] - sens[i])
} else {
pred[i] <- M_loo[identical_idx[i]]
error_predict[i] <- abs(pred[i] - sens[i])
}
}
}
return(list(dummy = M, error = error_predict, prediction = pred))
}
|
structure(list(url = "http://www.colourlovers.com/api/palettes/new?format=xml&hex=0000FF&numResults=5",
status_code = 200L, headers = structure(list(date = "Tue, 30 Apr 2019 17:10:15 GMT",
server = "Apache/2.2.22 (Ubuntu)", connection = "Close",
vary = "Accept-Encoding", `content-encoding` = "gzip",
`content-length` = "865", `content-type` = "text/xml; charset=utf-8"), class = c("insensitive",
"list")), all_headers = list(list(status = 200L, version = "HTTP/1.1",
headers = structure(list(date = "Tue, 30 Apr 2019 17:10:15 GMT",
server = "Apache/2.2.22 (Ubuntu)", connection = "Close",
vary = "Accept-Encoding", `content-encoding` = "gzip",
`content-length` = "865", `content-type` = "text/xml; charset=utf-8"), class = c("insensitive",
"list")))), cookies = structure(list(domain = logical(0),
flag = logical(0), path = logical(0), secure = logical(0),
expiration = structure(numeric(0), class = c("POSIXct",
"POSIXt")), name = logical(0), value = logical(0)), row.names = integer(0), class = "data.frame"),
content = charToRaw("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<palettes numResults=\"5\" totalResults=\"1000\">\n\t<palette>\n\t\t<id>4630210</id>\n\t\t<title><![CDATA[Space Explorers!]]></title>\n\t\t<userName><![CDATA[MischieffMayhem]]></userName>\n\t\t<numViews>111</numViews>\n\t\t<numVotes>0</numVotes>\n\t\t<numComments>0</numComments>\n\t\t<numHearts>0</numHearts>\n\t\t<rank>0</rank>\n\t\t<dateCreated>2019-02-14 00:51:01</dateCreated>\n\t\t<colors>\n\t\t\t<hex>FBB03B</hex>\n\t\t\t<hex>29ABE2</hex>\n\t\t\t<hex>0000FF</hex>\n\t\t\t<hex>FDE061</hex>\n\t\t\t<hex>FF0000</hex>\n\t\t</colors>\n\t\t<description><![CDATA[]]></description>\n\t\t<url><![CDATA[http://www.colourlovers.com/palette/4630210/Space_Explorers!]]></url>\n\t\t<imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/FBB03B/29ABE2/0000FF/FDE061/FF0000/Space_Explorers!.png]]></imageUrl>\n\t\t<badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/4630/4630210_Space_Explorers!.png]]></badgeUrl>\n\t\t<apiUrl>http://www.colourlovers.com/api/palette/4630210</apiUrl>\n\t</palette>\n\t<palette>\n\t\t<id>4604928</id>\n\t\t<title><![CDATA[NMS]]></title>\n\t\t<userName><![CDATA[AnythingButOrdinary]]></userName>\n\t\t<numViews>76</numViews>\n\t\t<numVotes>1</numVotes>\n\t\t<numComments>0</numComments>\n\t\t<numHearts>0</numHearts>\n\t\t<rank>0</rank>\n\t\t<dateCreated>2018-10-22 13:52:57</dateCreated>\n\t\t<colors>\n\t\t\t<hex>CC99FF</hex>\n\t\t\t<hex>9973FF</hex>\n\t\t\t<hex>664DFF</hex>\n\t\t\t<hex>3326FF</hex>\n\t\t\t<hex>0000FF</hex>\n\t\t</colors>\n\t\t<description><![CDATA[]]></description>\n\t\t<url><![CDATA[http://www.colourlovers.com/palette/4604928/NMS]]></url>\n\t\t<imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/CC99FF/9973FF/664DFF/3326FF/0000FF/NMS.png]]></imageUrl>\n\t\t<badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/4604/4604928_NMS.png]]></badgeUrl>\n\t\t<apiUrl>http://www.colourlovers.com/api/palette/4604928</apiUrl>\n\t</palette>\n\t<palette>\n\t\t<id>4604200</id>\n\t\t<title><![CDATA[Primary Design]]></title>\n\t\t<userName><![CDATA[Bubbletripper]]></userName>\n\t\t<numViews>21</numViews>\n\t\t<numVotes>0</numVotes>\n\t\t<numComments>0</numComments>\n\t\t<numHearts>0</numHearts>\n\t\t<rank>0</rank>\n\t\t<dateCreated>2018-10-19 12:33:16</dateCreated>\n\t\t<colors>\n\t\t\t<hex>8A9B3F</hex>\n\t\t\t<hex>0000FF</hex>\n\t\t\t<hex>FF00FF</hex>\n\t\t\t<hex>01FFFF</hex>\n\t\t\t<hex>A0996F</hex>\n\t\t</colors>\n\t\t<description><![CDATA[]]></description>\n\t\t<url><![CDATA[http://www.colourlovers.com/palette/4604200/Primary_Design]]></url>\n\t\t<imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/8A9B3F/0000FF/FF00FF/01FFFF/A0996F/Primary_Design.png]]></imageUrl>\n\t\t<badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/4604/4604200_Primary_Design.png]]></badgeUrl>\n\t\t<apiUrl>http://www.colourlovers.com/api/palette/4604200</apiUrl>\n\t</palette>\n\t<palette>\n\t\t<id>4604196</id>\n\t\t<title><![CDATA[Primary Mark]]></title>\n\t\t<userName><![CDATA[Bubbletripper]]></userName>\n\t\t<numViews>35</numViews>\n\t\t<numVotes>1</numVotes>\n\t\t<numComments>0</numComments>\n\t\t<numHearts>0</numHearts>\n\t\t<rank>0</rank>\n\t\t<dateCreated>2018-10-19 12:28:01</dateCreated>\n\t\t<colors>\n\t\t\t<hex>0000FF</hex>\n\t\t\t<hex>2D4A05</hex>\n\t\t\t<hex>F1DE92</hex>\n\t\t\t<hex>FFFF01</hex>\n\t\t\t<hex>FBFBFA</hex>\n\t\t</colors>\n\t\t<description><![CDATA[]]></description>\n\t\t<url><![CDATA[http://www.colourlovers.com/palette/4604196/Primary_Mark]]></url>\n\t\t<imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/0000FF/2D4A05/F1DE92/FFFF01/FBFBFA/Primary_Mark.png]]></imageUrl>\n\t\t<badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/4604/4604196_Primary_Mark.png]]></badgeUrl>\n\t\t<apiUrl>http://www.colourlovers.com/api/palette/4604196</apiUrl>\n\t</palette>\n\t<palette>\n\t\t<id>4604191</id>\n\t\t<title><![CDATA[Primary Clarity]]></title>\n\t\t<userName><![CDATA[Bubbletripper]]></userName>\n\t\t<numViews>11</numViews>\n\t\t<numVotes>1</numVotes>\n\t\t<numComments>0</numComments>\n\t\t<numHearts>0</numHearts>\n\t\t<rank>0</rank>\n\t\t<dateCreated>2018-10-19 12:18:39</dateCreated>\n\t\t<colors>\n\t\t\t<hex>8F8664</hex>\n\t\t\t<hex>EBAC75</hex>\n\t\t\t<hex>FFFF01</hex>\n\t\t\t<hex>0000FF</hex>\n\t\t\t<hex>EA17BB</hex>\n\t\t</colors>\n\t\t<description><![CDATA[]]></description>\n\t\t<url><![CDATA[http://www.colourlovers.com/palette/4604191/Primary_Clarity]]></url>\n\t\t<imageUrl><![CDATA[http://www.colourlovers.com/paletteImg/8F8664/EBAC75/FFFF01/0000FF/EA17BB/Primary_Clarity.png]]></imageUrl>\n\t\t<badgeUrl><![CDATA[http://www.colourlovers.com/images/badges/p/4604/4604191_Primary_Clarity.png]]></badgeUrl>\n\t\t<apiUrl>http://www.colourlovers.com/api/palette/4604191</apiUrl>\n\t</palette>\n</palettes>"),
date = structure(1556644215, class = c("POSIXct", "POSIXt"
), tzone = "GMT"), times = c(redirect = 0, namelookup = 0.000035,
connect = 0.12279, pretransfer = 0.122869, starttransfer = 0.261654,
total = 0.261787)), class = "response") |
plot.UPCM <- function(x, sig = 0.05, KIfactor = 0.9, xlim, ylim, ...){
quant <- qnorm(1-sig/2)
if(is.na(x$xi[1])|is.na(x$alpha[1])){
stop("Plotting is only possible if covariates are used (both for
the location and heterogeneity effect (i.e. if argument X is specified)!")
}
xi <- x$xi
xi.KI <- cbind(xi-quant*x$se.xi,xi+quant*x$se.xi)
xi <- xi
alpha <- x$alpha
alpha.KI <- exp(cbind(alpha-quant*x$se.alpha,alpha+quant*x$se.alpha))
alpha <- exp(alpha)
if(missing(ylim)){
ylim <- range(c(1,alpha.KI))
}
if(missing(xlim)){
xlim <- range(c(0,xi.KI))
}
plot(xi,alpha,pch=16,xlim=xlim,ylim=ylim,
xlab=expression(xi),ylab=expression(exp(alpha)),...)
p.X <- length(xi)
label.x <- label.y <- c()
for(i in 1:p.X){
x <- c(xi.KI[i,1],xi.KI[i,1]+(xi[i]-xi.KI[i,1])*(KIfactor),xi[i],xi[i]+(xi[i]-xi.KI[i,1])*(1-KIfactor),
xi.KI[i,2],xi[i]+(xi[i]-xi.KI[i,1])*(1-KIfactor),xi[i],xi.KI[i,1]+(xi[i]-xi.KI[i,1])*(KIfactor),
xi.KI[i,1])
y <- c(alpha[i],alpha.KI[i,1]+(alpha[i]-alpha.KI[i,1])*(KIfactor),alpha.KI[i,1],alpha.KI[i,1]+(alpha[i]-alpha.KI[i,1])*(KIfactor),alpha[i],
alpha[i]+(alpha[i]-alpha.KI[i,1])*(1-KIfactor),alpha.KI[i,2],alpha[i]+(alpha[i]-alpha.KI[i,1])*(1-KIfactor),alpha[i])
polygon(x,y,col=grey(0.9))
label.x <- c(label.x,x[6])
label.y <- c(label.y,y[6])
}
points(xi,alpha,pch=16)
abline(h=1,lty=2,lwd=2,col="gray")
abline(v=0,lty=2,lwd=2,col="gray")
text(label.x,label.y,labels=names(xi),adj=c(-0.1,-0.1))
} |
set_phantoms <- function(partable, ov.names, lv.names, ov.names.x, lv.names.x, ov.cp, lv.cp, lv.x.wish, ngroups) {
partable <- lavMatrixRepresentation(partable, add.attributes = TRUE)
defpar <- which(partable$op == ":=")
if(length(defpar) > 0){
partable$mat[defpar] <- "def"
partable$row[defpar] <- 1:length(defpar)
partable$col[defpar] <- 1
partable$group[defpar] <- 1
}
if(is.na(match("prior", names(partable)))) partable$prior <- rep("", length(partable$id))
if(lv.x.wish){
covpars <- which(partable$op == "~~" &
partable$lhs != partable$rhs &
partable$group == 1 &
!(partable$lhs %in% ov.names.x &
partable$free == 0) &
!(partable$lhs %in% lv.names.x))
} else {
if(lv.cp == "srs"){
covpars <- which(partable$op == "~~" &
partable$lhs != partable$rhs &
partable$group == 1 &
!(partable$lhs %in% ov.names.x &
partable$free == 0))
}
if(lv.cp == "fa"){
covpars <- which(partable$op == "~~" &
partable$lhs != partable$rhs &
partable$group == 1 &
!(partable$lhs %in% ov.names.x &
partable$free == 0) &
!(partable$lhs %in% lv.names &
partable$free == 0))
}
}
blkrow <- rep(NA, length(partable$id))
facovs <- NULL
if(length(covpars) > 0){
nmvcovs <- sum(partable$lhs[covpars] %in% ov.names)
nlvcovs <- length(covpars) - nmvcovs
patts <- attributes(partable)
for(k in 1:ngroups){
if(!("lambda" %in% patts$mmNames[[k]]) & nmvcovs > 0){
lcolstart <- 0
attributes(partable)$mmNames[[k]] <- c(patts$mmNames[[k]],
"lambda")
attributes(partable)$mmRows[[k]] <- c(patts$mmRows[[k]], lambda=length(ov.names))
attributes(partable)$mmCols[[k]] <- c(patts$mmCols[[k]], lambda=nmvcovs)
} else {
lcolstart <- patts$mmCols[[k]]["lambda"]
attributes(partable)$mmCols[[k]]["lambda"] <- patts$mmCols[[k]]["lambda"] + nmvcovs
}
if(!("beta" %in% patts$mmNames[[k]]) & nlvcovs > 0){
bcolstart <- 0
attributes(partable)$mmNames[[k]] <- c(patts$mmNames[[k]], "beta")
attributes(partable)$mmRows[[k]] <- c(patts$mmRows[[k]], beta=
nlvcovs)
attributes(partable)$mmCols[[k]] <- c(patts$mmCols[[k]], beta=nlvcovs)
} else {
bcolstart <- patts$mmCols[[k]]["beta"]
attributes(partable)$mmRows[[k]]["beta"] <- patts$mmRows[[k]]["beta"] + nlvcovs
attributes(partable)$mmCols[[k]]["beta"] <- patts$mmCols[[k]]["beta"] + nlvcovs
}
if(!("psi" %in% patts$mmNames[[k]])){
psicolstart <- 0
attributes(partable)$mmNames[[k]] <- c(patts$mmNames[[k]], "psi")
attributes(partable)$mmRows[[k]] <- c(patts$mmRows[[k]], psi=length(covpars))
attributes(partable)$mmCols[[k]] <- c(patts$mmCols[[k]], psi=length(covpars))
} else {
psicolstart <- patts$mmCols[[k]]["psi"]
attributes(partable)$mmRows[[k]]["psi"] <- patts$mmRows[[k]]["psi"] + length(covpars)
attributes(partable)$mmCols[[k]]["psi"] <- patts$mmCols[[k]]["psi"] + length(covpars)
}
}
cprm <- NULL
ridx <- 1:length(covpars)
for(k in 1:ngroups){
tlcs <- lcolstart
tbcs <- bcolstart
tpcs <- psicolstart
for(i in 1:length(covpars)){
covparg <- which(partable$op == "~~" &
partable$lhs == partable$lhs[covpars[i]] &
partable$rhs == partable$rhs[covpars[i]] &
partable$group == k)
eq.const <- FALSE
grp.idx <- k
eq.idx <- which(partable$op == "==" & partable$rhs == partable$plabel[covparg])
if(length(eq.idx) > 0){
eq.const <- TRUE
full.idx <- which(partable$plabel == partable$lhs[eq.idx])
old.idx <- which(partable$lhs[covpars] == partable$lhs[full.idx[1]] &
partable$rhs[covpars] == partable$rhs[full.idx[1]])
old.ridx <- ridx[old.idx]
grp.idx <- partable$group[full.idx[1]]
}
tmprows <- nrow(partable) + 1:3
phname <- paste(".phant", i, sep="")
partable <- rbind(partable, blkrow, blkrow, blkrow)
partable$group[tmprows] <- partable$block[tmprows] <- k
partable$rhs[tmprows[1]] <- partable$lhs[covpars[i]]
partable$rhs[tmprows[2]] <- partable$rhs[covpars[i]]
if(partable$lhs[covpars[i]] %in% ov.names){
partable$lhs[tmprows[1]] <- phname
partable$op[tmprows[1]] <- "=~"
partable$rhs[tmprows[1]] <- partable$lhs[covpars[i]]
partable$mat[tmprows[1]] <- "lambda"
partable$row[tmprows[1]] <- match(partable$lhs[covpars[i]],
patts$mmDimNames[[k]]$lambda[[1]])
tlcs <- tlcs + 1
partable$col[tmprows[1]] <- tlcs
v1var <- which(partable$lhs == partable$lhs[covpars[i]] &
partable$rhs == partable$lhs[covpars[i]] &
partable$group == k &
partable$op == "~~")
tmpv1 <- paste(partable$mat[v1var], "[", partable$row[v1var], ",", partable$col[v1var], ",", k,
"]", sep="")
if(eq.const){
oldr <- match(partable$lhs[full.idx], patts$mmDimNames[[k]]$lambda[[1]])
oldv1 <- paste(partable$mat[v1var], "[", oldr , ",", oldr, ",", grp.idx, "]", sep="")
}
ctype <- "ov"
} else {
partable$lhs[tmprows[1]] <- partable$lhs[covpars[i]]
partable$op[tmprows[1]] <- "~"
partable$rhs[tmprows[1]] <- phname
partable$mat[tmprows[1]] <- "beta"
tbcs <- tbcs + 1
partable$row[tmprows[1]] <- tbcs
partable$col[tmprows[1]] <- match(partable$lhs[covpars[i]],
patts$mmDimNames[[k]]$psi[[1]])
tmpv1 <- paste("psi[", partable$col[tmprows[1]], ",", partable$col[tmprows[1]],
",", k, "]", sep="")
if(eq.const){
oldr <- match(partable$lhs[full.idx], patts$mmDimNames[[k]]$psi[[1]])
oldv1 <- paste("psi[", oldr, ",", oldr, ",", grp.idx, "]", sep="")
}
ctype <- "lv"
}
if(partable$rhs[covpars[i]] %in% ov.names){
partable$lhs[tmprows[2]] <- phname
partable$op[tmprows[2]] <- "=~"
partable$rhs[tmprows[2]] <- partable$rhs[covpars[i]]
partable$mat[tmprows[2]] <- "lambda"
partable$row[tmprows[2]] <- match(partable$rhs[covpars[i]],
patts$mmDimNames[[k]]$lambda[[1]])
tlcs <- tlcs + 1
partable$col[tmprows[2]] <- tlcs
v2var <- which(partable$lhs == partable$rhs[covpars[i]] &
partable$rhs == partable$rhs[covpars[i]] &
partable$group == k &
partable$op == "~~")
tmpv2 <- paste(partable$mat[v2var], "[", partable$row[v2var], ",", partable$col[v2var], ",", k, "]", sep="")
if(eq.const){
oldr <- match(partable$rhs[full.idx], patts$mmDimNames[[k]]$lambda[[1]])
oldv2 <- paste(partable$mat[v2var], "[", oldr, ",", oldr, ",", grp.idx, "]", sep="")
}
} else {
partable$lhs[tmprows[2]] <- partable$rhs[covpars[i]]
partable$op[tmprows[2]] <- "~"
partable$rhs[tmprows[2]] <- phname
partable$mat[tmprows[2]] <- "beta"
tbcs <- tbcs + 1
partable$row[tmprows[2]] <- tbcs
partable$col[tmprows[2]] <- match(partable$rhs[covpars[i]],
patts$mmDimNames[[k]]$psi[[1]])
tmpv2 <- paste("psi[", partable$col[tmprows[2]], ",", partable$col[tmprows[2]],
",", k, "]", sep="")
if(eq.const){
oldr <- match(partable$lhs[full.idx], patts$mmDimNames[[k]]$psi[[1]])
oldv2 <- paste("psi[", oldr, ",", oldr, ",", grp.idx, "]", sep="")
}
}
partable$prior[tmprows[1:3]] <- ""
tpcs <- tpcs + 1
if((ctype == "ov" & ov.cp == "srs") | (ctype == "lv" & lv.cp == "srs")){
rhomat <- "rho"
if(partable$mat[covpars[i]] == "psi") rhomat <- "lvrho"
rhoind <- paste(partable$row[covpars[i]], ",", partable$col[covpars[i]], sep="")
partable$free[tmprows[1:3]] <- 0L
partable$exo[tmprows[1:3]] <- 0L
partable$ustart[tmprows[1]] <- paste("sqrt(abs(", rhomat, "[", rhoind, ",", k, "])*", tmpv1, ")", sep="")
partable$ustart[tmprows[2]] <- paste("(-1 + 2*step(", rhomat, "[", rhoind, ",", k,
"]))*sqrt(abs(", rhomat, "[", rhoind, ",", k, "])*", tmpv2, ")", sep="")
partable$ustart[tmprows[3]] <- 1
partable$mat[tmprows[3]] <- "psi"
partable$row[tmprows[3]] <- partable$col[tmprows[3]] <- tpcs
partable$id[covparg] <- paste(rhomat, "[", rhoind, ",", k, "]", sep="")
partable$plabel[tmprows] <- paste(".p", tmprows,
".", sep="")
partable$lhs[tmprows[3]] <- partable$rhs[tmprows[3]] <- phname
partable$op[tmprows[3]] <- "~~"
} else {
partable$mat[tmprows[3]] <- "psi"
partable$row[tmprows[3]] <- partable$col[tmprows[3]] <- tpcs
if(partable$free[covparg] == 0){
if(partable$ustart[covparg] != 0) stop("blavaan ERROR: Cannot fix covariances to nonzero values under fa priors.\n")
partable$free[tmprows[1:3]] <- 0
partable$ustart[tmprows[3]] <- 1
partable$ustart[tmprows[1:2]] <- 0
partable$exo[tmprows[1:3]] <- 0
} else {
partable$plabel[tmprows[3]] <- partable$plabel[covparg]
partable$free[tmprows[3]] <- partable$free[covparg]
partable$exo[tmprows[1:3]] <- 0
partable$plabel[tmprows[1:2]] <- paste(".p", tmprows[1:2], ".", sep="")
partable$free[tmprows[1:2]] <- tmprows[1:2]
}
cprm <- c(cprm, covparg)
partable$lhs[tmprows[3]] <- partable$rhs[tmprows[3]] <- phname
partable$op[tmprows[3]] <- "~~"
}
if(eq.const){
partable$free[tmprows[1:2]] <- tmprows[1:2]
old.labels <- which(partable$op %in% c("=~", "~") &
partable$group == grp.idx &
(grepl(paste(".phant", old.ridx, sep=""),
partable$lhs) |
grepl(paste(".phant", old.ridx, sep=""),
partable$rhs)))
partable <- rbind(partable, blkrow, blkrow)
nr <- nrow(partable)
partable$lhs[(nr-1):nr] <- partable$plabel[old.labels[1:2]]
partable$op[(nr-1):nr] <- "=="
partable$rhs[(nr-1):nr] <- partable$plabel[tmprows[1:2]]
partable$mat[(nr-1):nr] <- ""
partable$user[(nr-1):nr] <- 2
partable$free[(nr-1):nr] <- 0
partable$group[(nr-1):nr] <- 0
partable$exo[(nr-1):nr] <- 0
if((ctype == "ov" & ov.cp == "fa") | (ctype == "lv" & lv.cp == "fa")){
old.label <- which(partable$op == "~~" &
partable$group == grp.idx &
grepl(paste(".phant", old.ridx, sep=""), partable$lhs))
partable <- rbind(partable, blkrow)
nr <- nrow(partable)
partable$lhs[nr] <- partable$plabel[old.label]
partable$op[nr] <- "=="
partable$rhs[nr] <- partable$plabel[tmprows[3]]
partable$mat[(nr-1):nr] <- ""
partable$user[nr] <- 2
partable$free[nr] <- 0
partable$group[nr] <- 0
partable$exo[nr] <- 0
}
}
}
}
if(!is.null(cprm)){
facovs <- partable[cprm,]
partable <- partable[-cprm,]
}
}
covpars <- which(partable$op == "~~" &
partable$lhs != partable$rhs &
partable$group == 1 &
partable$lhs %in% ov.names.x &
partable$free == 0)
if(length(covpars) > 0) partable <- partable[-covpars,]
if(any(is.na(partable$exo))) partable$exo[is.na(partable$exo)] <- 0
parnums <- rep(NA, nrow(partable))
parrows <- which(!(partable$op == "=="))
parnums[parrows] <- 1:length(parrows)
partable$parnums <- parnums
list(partable = partable, facovs = facovs)
}
set_mv0 <- function(partable, ov.names, ngroups) {
mv0 <- which(partable$op == "~~" &
partable$lhs %in% ov.names &
partable$rhs == partable$lhs &
partable$group == 1 &
partable$free == 0 &
partable$ustart == 0)
if(length(mv0) > 0){
ovn <- partable$lhs[mv0]
for(i in 1:length(ovn)){
for(j in 1:ngroups){
mvloc <- which(partable$op == "~~" &
partable$lhs == ovn[i] &
partable$rhs == partable$lhs &
partable$group == j &
partable$free == 0 &
partable$ustart == 0)
lvloc <- which(partable$op == "=~" &
partable$rhs == ovn[i] &
partable$group == j)
lvreg <- which(partable$op == "~" &
partable$lhs == ovn[i] &
partable$group == j)
lvcov <- which(partable$op == "~~" &
(partable$lhs %in% partable$lhs[lvloc] |
partable$rhs %in% partable$lhs[lvloc]) &
partable$lhs != partable$rhs)
if(length(lvloc) + length(lvreg) + length(lvcov) > 1){
if(length(mvloc) > 1){
stop("blavaan ERROR: Problem with ov variances fixed to 0.")
}
partable$ustart[mvloc] <- .001
message(paste("blavaan NOTE: The variance of variable", ovn[i],
"in group", j, "has been fixed to .001 instead of 0 (necessary for conditional model specification).\n"))
} else {
lvname <- partable$lhs[lvloc]
lvvar <- which(partable$lhs == lvname &
partable$rhs == lvname &
partable$op == "~~" &
partable$group == j)
tmpfree <- partable$free[lvvar]
tmpustart <- partable$ustart[lvvar]
tmpplabel <- partable$plabel[lvvar]
tmpstart <- partable$start[lvvar]
partable$free[lvvar] <- partable$free[mvloc]
partable$ustart[lvvar] <- partable$ustart[mvloc]
partable$plabel[lvvar] <- partable$plabel[mvloc]
partable$start[lvvar] <- partable$start[mvloc]
partable$free[mvloc] <- tmpfree
partable$ustart[mvloc] <- tmpustart
partable$plabel[mvloc] <- tmpplabel
partable$start[mvloc] <- tmpstart
}
}
}
}
partable
}
set_phanvars <- function(partable, ov.names, lv.names, ov.cp, lv.cp, ngroups){
vnames <- c(ov.names, lv.names)
for(i in 1:length(vnames)){
for(k in 1:ngroups){
if(vnames[i] %in% ov.names){
phanlvs <- which(partable$rhs == vnames[i] &
grepl(".phant", partable$lhs) &
partable$op == "=~" &
partable$group == k)
} else {
phanlvs <- which(partable$lhs == vnames[i] &
grepl(".phant", partable$rhs) &
partable$op == "~" &
partable$group == k)
}
if(length(phanlvs) > 0){
vvar <- which(partable$lhs == vnames[i] &
partable$lhs == partable$rhs &
partable$op == "~~" &
partable$group == k)
if(ov.cp == "srs"){
eqconst <- paste(partable$mat[vvar], "[", partable$row[vvar],
",", partable$col[vvar], ",", k, "]", sep="")
for(j in 1:length(phanlvs)){
eqconst <- paste(eqconst, " - (", partable$ustart[phanlvs[j]],
")^2", sep="")
}
partable <- rbind(partable, partable[vvar,])
partable$parnums[nrow(partable)] <- max(partable$parnums, na.rm=TRUE) + 1
partable$mat[vvar] <- paste(partable$mat[vvar], "star", sep="")
} else {
eqconst <- paste(partable$mat[vvar], "star[", partable$row[vvar],
",", partable$col[vvar], ",", k, "]", sep="")
for(j in 1:length(phanlvs)){
if(vnames[i] %in% ov.names){
phname <- partable$lhs[phanlvs[j]]
} else {
phname <- partable$rhs[phanlvs[j]]
}
phanvar <- which(partable$lhs == phname &
partable$lhs == partable$rhs &
partable$op == "~~" &
partable$group == k)
eqconst <- paste(eqconst, " + (", partable$mat[phanlvs[j]], "[",
partable$row[phanlvs[j]], ",",
partable$col[phanlvs[j]], ",", k, "]^2*",
partable$mat[phanvar], "[",
partable$row[phanvar], ",", partable$col[phanvar],
",", k, "])", sep="")
}
partable <- rbind(partable, partable[vvar,])
partable$mat[nrow(partable)] <- paste(partable$mat[vvar], "star",
sep="")
partable$parnums[nrow(partable)] <- max(partable$parnums, na.rm=TRUE) + 1
}
partable$free[vvar] <- 0
partable$label[vvar] <- ""
partable$ustart[vvar] <- eqconst
}
}
}
partable
} |
pgfDneymantypec <-
function(s,params) {
require(hypergeo)
k<-s[abs(s)>1]
if (length(k)>0)
warning("At least one element of the vector s are out of interval [-1,1]")
if (length(params)<2) stop("At least one value in params is missing")
if (length(params)>2) stop("The length of params is 2")
theta<-params[1]
lambda<-params[2]
if (theta<=0)
stop ("Parameter theta must be positive")
if (lambda<=0)
stop ("Parameter lambda must be positive")
theta*lambda/3*genhypergeo(2,4,theta*(s-1))*pgfneymantypec(s,params)
} |
library(hamcrest)
expected <- c(0x1.91013f1343ccap+8 + 0x0p+0i, 0x1.16d6ca178b7c2p+6 + 0x1.36a739f0aa691p+6i,
0x1.514dd0ba2f76ap+7 + -0x1.9db2b19e2b2cp+1i, 0x1.6632b2287fc46p+8 + -0x1.04c7f85576aa8p+7i,
-0x1.39953dda298ap+5 + 0x1.b92d15d6ae60fp+4i, 0x1.f2f6e60cf04a3p+7 + 0x1.67d18306ae31dp+7i,
0x1.207e4ae677667p+7 + -0x1.07d9d33a8b352p+3i, 0x1.267b111085d4p+7 + 0x1.3239ad99106edp+6i,
0x1.600a2a745e36cp+3 + 0x1.9b0ffeeb363e1p+5i, 0x1.5e883d75cbd5p+7 + -0x1.c679f290e2c93p+5i,
0x1.04ca7736d495ap+5 + 0x1.7bbbfec2d0cc3p+6i, 0x1.e03335739dcd3p+7 + -0x1.0315e4a239b81p+7i,
0x1.04aca4fa15343p+8 + 0x1.2af391aace15bp+2i, 0x1.72a9281ee5abap+4 + 0x1.f94509927a30cp+6i,
0x1.30a970ad68fc2p+6 + -0x1.0e7a3519d97fep+6i, 0x1.fa2913f6f971ep+6 + 0x1.d1e41cdabc4bbp+6i,
-0x1.71c6081a1d6d6p+7 + -0x1.d50d80c69f0dp+6i, 0x1.3b3261e276d37p+7 + -0x1.5d0f93dea3366p+7i,
0x1.05dc785581b9fp+7 + -0x1.afbc2947a230cp+4i, 0x1.ae6c983f98445p+7 + 0x1.4d41908b6d158p+5i,
-0x1.d2fa1428fa922p+7 + -0x1.1e92b80e99ecap+7i, 0x1.c9c4cacc6decdp+5 + 0x1.7f0b382c463dp+3i,
-0x1.f37cc2637d4b8p+4 + 0x1.7e206930f9507p+6i, -0x1.16c5b9301eb2ep+6 + -0x1.876a3d71ff5c6p+5i,
-0x1.cd467328a272ap+4 + -0x1.19814f4af7c36p+7i, 0x1.94a41e018252ep+7 + -0x1.bcc98bc3e2522p+5i,
0x1.033d865ecc562p+7 + 0x1.27c73cb6db575p+6i, -0x1.654aa9ca0e43p+5 + 0x1.3bbaf02e71b3ep+7i,
0x1.41aa19c7e14a3p+6 + -0x1.46aa1ff3dfc8p+7i, -0x1.949581eaadcdfp+6 + 0x1.659810984138ep+5i,
-0x1.91365a760c7e8p+3 + 0x1.eb0a7d20ea5f7p+5i, 0x1.083c8861cdd56p+7 + 0x1.2d0ae50f6bac2p+7i,
-0x1.f66afec592aap+0 + 0x1.702afc1381327p+5i, 0x1.5c0480775b583p+4 + 0x1.a0f88c5e1cd7ap+6i,
0x1.60e8fa1d6298p-2 + 0x1.0ac74e101b8f2p+7i, 0x1.7fce232ccfb02p+4 + 0x1.424bb70e489cfp+6i,
-0x1.315b75f4340ap+3 + 0x1.08ad4b7623c6p+7i, 0x1.03a0ada7ae33p+4 + 0x1.41e2634374806p+5i,
-0x1.8bc643cbda5p+3 + 0x1.6d30328cc768ep+6i, -0x1.d26a0be7ec7f1p+6 + -0x1.0ed1bb406897p+2i,
0x1.5643f6696503dp+5 + 0x1.906b20227ca7bp+6i, -0x1.a3c981f88d685p+6 + -0x1.e1efa99f810f4p+3i,
-0x1.0d2df4c7afd3fp+2 + 0x1.18970ec351344p+5i, -0x1.3822469996b72p+5 + -0x1.5f5b720a93716p+6i,
-0x1.80d2fae0e5c5ap+6 + 0x1.2ac10f51a0c77p+6i, -0x1.06f9d12c36902p+5 + 0x1.6fc1522bfe6afp+6i,
-0x1.098cba9da73c4p+6 + -0x1.3ae20aa44d434p+6i, 0x1.724b4dee89a0cp+3 + -0x1.d1be076c0c984p+2i,
-0x1.8681738191a6cp+5 + 0x1.7aa92d9018c69p+6i, -0x1.ecb09741b1a2p-1 + 0x1.221ca9b7d6467p+6i,
0x1.8ee45253f9904p+2 + -0x1.4f5ab42cba312p+6i, 0x1.13e6a70bee486p+4 + 0x1.6d95c844d2794p+5i,
-0x1.ebb89bdd0757ap+3 + 0x1.3192dfbbdfc27p+6i, -0x1.a7701ab0ca8acp+4 + -0x1.14403d502a51ap+3i,
-0x1.139ec16eab422p+5 + 0x1.2e129245f45fap+7i, -0x1.a2f4eb92719cp+5 + 0x1.3cbb3a790981ep+3i,
0x1.cb609c88c112ap+5 + -0x1.33e2c11988961p+6i, 0x1.8ce48aec82414p+3 + 0x1.5d770b22f430dp+5i,
-0x1.c98eab73f6a41p+4 + 0x1.554bca55bef7p+6i, 0x1.2f3c932f29a98p+1 + -0x1.6cc6df5d3c69p+3i,
0x1.88ae0c5a2d50cp+5 + 0x1.2ca1dbab6d3abp+5i, 0x1.00341129108cdp+6 + 0x1.f84782be2b1ddp+5i,
-0x1.2e193da55708bp+6 + 0x1.c2ba2f046f78p-2i, 0x1.6ece586ce1a4p+4 + -0x1.3ab7e34a3bbaep+6i,
0x1.a987723d5366dp+5 + 0x1.1083edce2bc9cp+3i, 0x1.a20dff0259023p+5 + 0x1.d31f8c938601fp+5i,
0x1.131140f3ac2aep+5 + -0x1.4c954a87225b4p+2i, 0x1.74dec1e036565p+4 + -0x1.bf542aebab1ecp+4i,
-0x1.d4ff320026c33p+5 + 0x1.71539d7de33b4p+3i, -0x1.e143abac97944p+5 + -0x1.9a9e9f7e99d6cp+4i,
0x1.7825328636fp+0 + 0x1.82fbb06ab11d6p+5i, 0x1.821c96841b705p+2 + -0x1.cd174812298dep+5i,
-0x1.c47572dd8312fp+5 + 0x1.222f73959f7c7p+4i, 0x1.457daa36a2727p+4 + 0x1.ce0abe2a563cp+2i,
-0x1.3df07d3d83edbp+6 + 0x1.d918ec921bb8bp+5i, 0x1.f28fb881edffdp+4 + -0x1.6f8b330119ebp+4i,
0x1.eca243efedccp+3 + -0x1.6a32e166edc28p+4i, -0x1.571fedf70cfe4p+3 + 0x1.f302a8dd82ed5p+4i,
0x1.56f323a55f2cp+2 + -0x1.581eb5da6a292p+4i, 0x1.20e2a4c336c92p+5 + 0x1.44c32570db58cp+4i,
0x1.1b7bc980667ap+5 + 0x1.be5240d3b1926p+3i, -0x1.91904e3207bf8p+2 + 0x1.774356cf742eep+3i,
0x1.851d90b61ef3cp+2 + 0x1.0e79f2076ff5cp+6i, -0x1.8d896e0867834p+3 + 0x1.0fec5341655aap+5i,
-0x1.00441c7031095p+5 + 0x1.7044357d816d8p-1i, -0x1.2f6124e51f37p+4 + 0x1.6a80e5e771ec4p+5i,
-0x1.d6fbf6e5e3684p+4 + -0x1.73ac0dabe9fbcp+5i, -0x1.500c69d597e4cp+5 + 0x1.0ab91cbc95ffbp+4i,
0x1.39700fae27b1p+6 + -0x1.0633ba2df2facp+2i, -0x1.5bd34583008d6p+5 + 0x1.4f5a39357a17ap+4i,
0x1.77688be34b48p+2 + -0x1.498b6f315247p+1i, 0x1.16c4f4ebb936ep+4 + 0x1.69f2e75a74358p+4i,
0x1.6d6033c425281p+6 + -0x1.08bb43ea0816p+1i, -0x1.06e0fb2227a51p+6 + -0x1.64401c2ba13ep+4i,
-0x1.ae9d5792de6p+1 + -0x1.a7f14ea1c8b32p+6i, 0x1.4857b8fecec1cp+4 + 0x1.5533bb012bf26p+4i,
0x1.525c9a249f3fp+5 + 0x1.3e123726609c7p+5i, -0x1.3fade4635dea1p+5 + 0x1.1773f612be4d3p+6i,
0x1.5521934a78d5p+4 + 0x1.e6c9957439facp+2i, -0x1.58477f325072cp+1 + 0x1.ae9cb5ede056bp+3i,
0x1.8cbc1931b2456p+5 + 0x1.99e09760ae0cdp+5i, 0x1.d438a032e3b9p+0 + -0x1.3944353a9f4d3p+6i,
0x1.c7e2790d4586p+1 + -0x1.b592146e8eac4p+5i, -0x1.d197f0e03055ep+5 + -0x1.ac384dbcffe0cp+3i,
0x1.f62b64e352313p+5 + 0x1.dc3650101f6b6p+2i, -0x1.c722aa3e7b193p+5 + 0x1.520f74936f0dcp+4i,
-0x1.912a5b56fd698p+1 + -0x1.3c6c9ef99e20dp+4i, -0x1.cffe52554c9d4p+4 + -0x1.b7d2c69661fd4p+5i,
0x1.5d769e27ef727p+5 + 0x1.b468744526036p+4i, 0x1.14892f43e0185p+5 + 0x1.9c0aca26c67e8p+0i,
0x1.1de4b2aa6962cp+3 + -0x1.64630d8abaa4p-1i, -0x1.df19dbfa53713p+4 + -0x1.b8651f7d05382p+5i,
0x1.34001f9b02f9cp+5 + 0x1.af40c8691f20ap+4i, -0x1.855d398de0224p+4 + 0x1.d52878b094358p+4i,
0x1.00195111a4aa7p+5 + 0x1.690fa1e34527cp+2i, -0x1.22533d8312128p+4 + -0x1.b37be758cabp+2i,
0x1.1ff3b519495a1p+6 + 0x1.68f5a66142ca6p+5i, 0x1.30e4e3ff4429ap+5 + 0x1.35087e3be844fp+4i,
0x1.ba71eaa70c72ep+5 + 0x1.a338e086aafb2p+5i, 0x1.1ccc9bb762d79p+6 + 0x1.18f2289060894p+6i,
0x1.4a4b10cd83b92p+4 + -0x1.61052796ef845p+5i, 0x1.7e2b9a72bd4b5p+5 + 0x1.022dd3abf3616p+6i,
0x1.c9567405c9cacp+5 + 0x1.6658eb6d9fe1ep+6i, -0x1.55db4fdeb01f9p+6 + -0x1.164b21965d7d2p+5i,
0x1.0bd87ea392732p+4 + -0x1.22859c16c81a4p+2i, 0x1.c03f2dd7ccc28p+5 + 0x1.15f399de90418p+5i,
-0x1.b900819d58255p+5 + -0x1.9b3838bdb9a4p+2i, -0x1.2b25808249b4p+0 + 0x1.f576ecaa2c178p+5i,
-0x1.400c9e6220efdp+4 + -0x1.b08faae4290f8p+4i, 0x1.043ca3c271f62p+5 + -0x1.5661291f41adp+4i,
0x1.673f1278ab395p+6 + 0x1.8fc2aa52efc78p+6i, 0x1.381ba8c23d936p+6 + 0x1.a5afe11ca2356p+5i,
-0x1.4be20b7339bc9p+5 + -0x1.5b1737107011ap+7i, 0x1.2b2b633982cb1p+7 + -0x1.b9140d8584185p+6i,
0x1.1e98defdca44ap+5 + 0x1.f27bb7a9333a9p+5i, -0x1.466e231c94022p+6 + 0x1.bc37929312448p+4i,
0x1.099fe6e43bc3ap+5 + -0x1.292124aac7ca4p+7i, 0x1.9278291d40fa8p+4 + 0x1.27f71ed126ee6p+4i,
-0x1.3b0e9a75142a8p+2 + 0x1.352dfedff2e64p+6i, 0x1.d57678cb93e58p+1 + 0x1.248f71d92d55cp+6i,
0x1.a525a535c9f6fp+6 + -0x1.2c0164eb8bd49p+7i, 0x1.2f1384ff3a716p+3 + 0x1.a8eca8670a0a4p+2i,
-0x1.d89ccb7531d13p+6 + -0x1.6e45ddf348806p+6i, -0x1.b926736c77d04p+3 + 0x1.9e2450b4ad6acp+5i,
0x1.154a311ef519p+5 + 0x1.ee29250e6eaf4p+5i, -0x1.fb41d0f6e8969p+4 + -0x1.34d0e7f2c9b6p+4i,
-0x1.94fabe84e87d7p+6 + -0x1.52d798f4432f8p+6i, 0x1.904763f8f2b3ep+3 + 0x1.836b113e400bp+5i,
0x1.5d7853336319ep+6 + 0x1.a5a495343124cp+4i, -0x1.9d90fb72d14a8p+4 + 0x1.54049024c34bep+5i,
-0x1.e036b1c1c0222p+3 + -0x1.354b9350696eep+6i, -0x1.d31b177a31cep+2 + 0x1.ac5e436b91d0bp+6i,
-0x1.841b31002dc98p+2 + 0x1.0cab5c8c7d4c1p+5i, 0x1.063687f2e523cp+5 + 0x1.cf1c90ff3d58cp+6i,
-0x1.6ae967a6567fep+4 + 0x1.d73b2aec80228p+3i, -0x1.2dd3fc52d2e8cp+6 + 0x1.0805d3d63d55cp+7i,
0x1.0cbde255bb91p+5 + 0x1.9eafd2ff4c9fdp+4i, -0x1.2241c7d2ed9acp+5 + 0x1.2e5be5df653ep+7i,
-0x1.7c1e22843ebfcp+3 + 0x1.02ef441f6dde4p+7i, -0x1.01ad62051ff43p+5 + 0x1.e3b8080acf964p+3i,
-0x1.1975f22ef2ccap+6 + 0x1.41f3d602b92c1p+6i, -0x1.4835cfba4d8cap+4 + 0x1.127c6f146c2b1p+8i,
-0x1.ff081baa8f008p+6 + 0x1.0810c35d761cdp+4i, 0x1.3d71f62bb62bbp+4 + 0x1.6abdfc4792ad9p+6i,
-0x1.b98340b6910eap+5 + 0x1.3299800114babp+6i, -0x1.2e40d0357a9cbp+6 + 0x1.292a7cdfc78cp-1i,
-0x1.2211981a873e6p+7 + 0x1.216ab12e86221p+8i, -0x1.ea878f9b8aa4ep+6 + -0x1.b5811a660a5a5p+7i,
0x1.06905332d8718p+7 + 0x1.936307e4bbd4fp+5i, 0x1.093340cbc9fbdp+7 + 0x1.9c4ab16e33439p+7i,
-0x1.51545051d6b3p+4 + 0x1.bb755943cb9d4p+7i, -0x1.673d83ed43078p+5 + -0x1.2639c7c28e6f1p+7i,
0x1.1425a3ba473bp+8 + 0x1.068b75fc7d8f8p+6i, -0x1.b900f50803dfcp+6 + 0x1.16f943bded84fp+8i,
-0x1.3b8d5f552ab4ep+7 + -0x1.d7aaee9900e32p+5i, 0x1.58020a1963778p+8 + -0x1.a8d8b9e0a0227p+7i,
0x1.1d4bcaf1e33b5p+7 + 0x1.0aae93147cff4p+8i, 0x1.82224ce493a9cp+3 + 0x1.245376145c93ap+8i,
-0x1.65b3eba8bee0ap+7 + 0x1.d4d0d74a6bcebp+6i, 0x1.bb5ad52552facp+7 + -0x1.502b36696878p+7i,
0x1.1b79a583b387ep+6 + 0x1.e2a2d8e7f3db6p+7i, -0x1.36e962d6aa901p+7 + -0x1.cff001cf3c099p+6i,
0x1.b12eb23e6e99ep+5 + 0x1.891ff6c8088fcp+3i, 0x1.22e667ac490dp+8 + -0x1.71a5b51efd0bap+3i,
0x1.37e51cedeff0dp+3 + 0x1.7d8660aead164p+4i, -0x1.92505c920459cp+6 + -0x1.4e8f52614d024p+5i,
-0x1.183f6d6265869p+7 + -0x1.a334d9f340006p+3i, 0x1.23bef971cbeeap+7 + -0x1.83a0840432e48p+4i,
-0x1.b42a0cfd66413p+4 + -0x1.25edce810ad76p+6i, 0x1.52e7f5f7500d8p+6 + 0x1.3e947be939ab2p+3i,
-0x1.0cabfb06c2078p+7 + -0x1.ababb3e989cd8p+4i, 0x1.1c855252b05ccp+7 + 0x1.bdee7ffffe724p+3i,
-0x1.7e12ed8e261a2p+5 + 0x1.56bd17543030cp+3i, 0x1.3e08ceff60b99p+5 + -0x1.4808e592422c5p+6i,
-0x1.c76aa047fc7f9p+5 + 0x1.6989c8cb8fb82p+3i, -0x1.14961daf39c88p+4 + -0x1.ea6bf5b39cc24p+6i,
-0x1.195025998ecd8p+2 + 0x1.9ce00d2768746p+4i, -0x1.384a3576cb2b4p+6 + -0x1.558a4603be24p+7i,
-0x1.9e05c03e2b87cp+3 + 0x1.b29284ef7a48ap+4i, -0x1.a1988353dfe1dp+5 + -0x1.2c34f8cae02fap+7i,
-0x1.dd2c3373e22a6p+5 + 0x1.634b16be5dd8ap+5i, 0x1.b035651169d7ap+6 + -0x1.5eee55cec4934p+2i,
-0x1.9fd0d799df5c2p+6 + -0x1.1cd3f7e3c8244p+5i, 0x1.3c62e04a4734cp+5 + -0x1.701e644d2f30cp+4i,
0x1.c01e2ff61229p+1 + 0x1.b8c3660440c6ep+5i, 0x1.366c409640bf4p+6 + -0x1.4e4a75a1d324p+7i,
-0x1.88a9206755ce8p+6 + 0x1.f4ad656b1cfc4p+6i, 0x1.0f5424c8a7d94p+7 + -0x1.a3841c9346f5ap+6i,
-0x1.141f525d2b5d2p+5 + -0x1.9292cfe323bep+5i, -0x1.45552d839c0d2p+6 + -0x1.6fbdc8cce34f9p+6i,
-0x1.de9329f28e7cfp+6 + 0x1.5e954ecb6af71p+5i, 0x1.938b2357b30fep+4 + 0x1.cb2bb791c6188p+3i,
0x1.1b6b2284c403cp+2 + 0x1.b56f4aa8f0e7ep+5i, 0x1.82b0afa08cdbfp+1 + -0x1.2a55c62ede713p+6i,
-0x1.cb20eedb2e19ep+5 + -0x1.96cf249f9983ep+6i, 0x1.11f5a59b8ee58p+6 + 0x1.9cd43d9f4461p+1i,
-0x1.21e4eae9aaefdp+7 + 0x1.de4cd9362ebb7p+5i, 0x1.6de27e138d8d5p+5 + -0x1.ef98d8ae21f26p+6i,
-0x1.a8d83a0aefaf2p+6 + -0x1.073fa0cd7c9cep+4i, -0x1.bc61c70723566p+6 + 0x1.61a13aee40acbp+5i,
-0x1.13a4c5eb0a3dap+6 + 0x1.ce19cfb30e6d6p+6i, 0x1.daa1e10ae114fp+6 + -0x1.627d314e939e7p+6i,
-0x1.e4f07b3ce25fcp+6 + -0x1.8651920b661bap+5i, -0x1.2495288b58c44p+4 + 0x1.e88deff6308a6p+5i,
-0x1.e2537f08283cap+5 + -0x1.48ccb8c668788p+4i, -0x1.925af3323d707p+4 + -0x1.05b9ad3a75a5ep+6i,
-0x1.353e33c1f009ap+6 + 0x1.1977c4aedd1fap+3i, 0x1.0e532361f3d3ap+5 + -0x1.08b071f26b455p+6i,
-0x1.6c16a6f1ca34fp+5 + -0x1.0d394c82ac99p+5i, 0x1.f2923972d8f45p+5 + -0x1.eec324803f57ep+2i,
0x1.a25cc09a6b0c8p+5 + -0x1.7b68ab2d84159p+5i, 0x1.dfeab9ea587aep+6 + 0x1.f968ab4b10a94p+4i,
0x1.8fb06ace800dep+6 + -0x1.f3f7e69cf9e3dp+5i, 0x1.da886331d09ep+5 + -0x1.697aa76e6588fp+2i,
0x1.56a154050acccp+7 + -0x1p-48i, 0x1.da886331d09d6p+5 + 0x1.697aa76e658f6p+2i,
0x1.8fb06ace800d9p+6 + 0x1.f3f7e69cf9e42p+5i, 0x1.dfeab9ea587a8p+6 + -0x1.f968ab4b10a86p+4i,
0x1.a25cc09a6b0bap+5 + 0x1.7b68ab2d84158p+5i, 0x1.f2923972d8f38p+5 + 0x1.eec324803f61ap+2i,
-0x1.6c16a6f1ca351p+5 + 0x1.0d394c82ac99p+5i, 0x1.0e532361f3d34p+5 + 0x1.08b071f26b459p+6i,
-0x1.353e33c1f009cp+6 + -0x1.1977c4aedd1bcp+3i, -0x1.925af3323d6fap+4 + 0x1.05b9ad3a75a5cp+6i,
-0x1.e2537f08283d2p+5 + 0x1.48ccb8c6687cp+4i, -0x1.2495288b58c4ep+4 + -0x1.e88deff6308aap+5i,
-0x1.e4f07b3ce25f4p+6 + 0x1.8651920b661c2p+5i, 0x1.daa1e10ae114ep+6 + 0x1.627d314e939eap+6i,
-0x1.13a4c5eb0a3dep+6 + -0x1.ce19cfb30e6c8p+6i, -0x1.bc61c70723564p+6 + -0x1.61a13aee40adp+5i,
-0x1.a8d83a0aefaep+6 + 0x1.073fa0cd7c9e4p+4i, 0x1.6de27e138d8cbp+5 + 0x1.ef98d8ae21f29p+6i,
-0x1.21e4eae9aaefdp+7 + -0x1.de4cd9362ebb2p+5i, 0x1.11f5a59b8ee62p+6 + -0x1.9cd43d9f44616p+1i,
-0x1.cb20eedb2e192p+5 + 0x1.96cf249f99841p+6i, 0x1.82b0afa08cda4p+1 + 0x1.2a55c62ede714p+6i,
0x1.1b6b2284c3fbcp+2 + -0x1.b56f4aa8f0e76p+5i, 0x1.938b2357b3104p+4 + -0x1.cb2bb791c61a7p+3i,
-0x1.de9329f28e7cap+6 + -0x1.5e954ecb6af62p+5i, -0x1.45552d839c0cep+6 + 0x1.6fbdc8cce34fdp+6i,
-0x1.141f525d2b5cdp+5 + 0x1.9292cfe323be7p+5i, 0x1.0f5424c8a7d94p+7 + 0x1.a3841c9346f5bp+6i,
-0x1.88a9206755ce5p+6 + -0x1.f4ad656b1cfc2p+6i, 0x1.366c409640bf8p+6 + 0x1.4e4a75a1d323cp+7i,
0x1.c01e2ff61223p+1 + -0x1.b8c3660440c6cp+5i, 0x1.3c62e04a4734ep+5 + 0x1.701e644d2f318p+4i,
-0x1.9fd0d799df5c1p+6 + 0x1.1cd3f7e3c823ep+5i, 0x1.b035651169d7ap+6 + 0x1.5eee55cec48ep+2i,
-0x1.dd2c3373e22b2p+5 + -0x1.634b16be5dd8ap+5i, -0x1.a1988353dfe16p+5 + 0x1.2c34f8cae02fap+7i,
-0x1.9e05c03e2b896p+3 + -0x1.b29284ef7a489p+4i, -0x1.384a3576cb2b1p+6 + 0x1.558a4603be24p+7i,
-0x1.195025998ed1p+2 + -0x1.9ce00d276872ep+4i, -0x1.14961daf39c7ep+4 + 0x1.ea6bf5b39cc24p+6i,
-0x1.c76aa047fc807p+5 + -0x1.6989c8cb8fb58p+3i, 0x1.3e08ceff60b96p+5 + 0x1.4808e592422c1p+6i,
-0x1.7e12ed8e261a4p+5 + -0x1.56bd1754303p+3i, 0x1.1c855252b05cep+7 + -0x1.bdee7ffffe718p+3i,
-0x1.0cabfb06c207ap+7 + 0x1.ababb3e989cfp+4i, 0x1.52e7f5f7500dap+6 + -0x1.3e947be939acp+3i,
-0x1.b42a0cfd66402p+4 + 0x1.25edce810ad76p+6i, 0x1.23bef971cbee8p+7 + 0x1.83a0840432e4p+4i,
-0x1.183f6d626586bp+7 + 0x1.a334d9f34002p+3i, -0x1.92505c92045a1p+6 + 0x1.4e8f52614d02ap+5i,
0x1.37e51cedeff4p+3 + -0x1.7d8660aead174p+4i, 0x1.22e667ac490d1p+8 + 0x1.71a5b51efd0b8p+3i,
0x1.b12eb23e6e998p+5 + -0x1.891ff6c80892p+3i, -0x1.36e962d6aa901p+7 + 0x1.cff001cf3c09ap+6i,
0x1.1b79a583b387ap+6 + -0x1.e2a2d8e7f3dbap+7i, 0x1.bb5ad52552fb1p+7 + 0x1.502b366968781p+7i,
-0x1.65b3eba8bee0ep+7 + -0x1.d4d0d74a6bce3p+6i, 0x1.82224ce493a9p+3 + -0x1.245376145c93cp+8i,
0x1.1d4bcaf1e33b6p+7 + -0x1.0aae93147cff8p+8i, 0x1.58020a196377ap+8 + 0x1.a8d8b9e0a0226p+7i,
-0x1.3b8d5f552ab51p+7 + 0x1.d7aaee9900e3dp+5i, -0x1.b900f50803e09p+6 + -0x1.16f943bded85p+8i,
0x1.1425a3ba473b4p+8 + -0x1.068b75fc7d901p+6i, -0x1.673d83ed4306ep+5 + 0x1.2639c7c28e6f2p+7i,
-0x1.51545051d6b5p+4 + -0x1.bb755943cb9d8p+7i, 0x1.093340cbc9fbep+7 + -0x1.9c4ab16e3343dp+7i,
0x1.06905332d871ap+7 + -0x1.936307e4bbd4fp+5i, -0x1.ea878f9b8aa54p+6 + 0x1.b5811a660a5abp+7i,
-0x1.2211981a873e8p+7 + -0x1.216ab12e86224p+8i, -0x1.2e40d0357a9cbp+6 + -0x1.292a7cdfc75p-1i,
-0x1.b98340b6910efp+5 + -0x1.3299800114baap+6i, 0x1.3d71f62bb62a6p+4 + -0x1.6abdfc4792ae3p+6i,
-0x1.ff081baa8f00fp+6 + -0x1.0810c35d761d1p+4i, -0x1.4835cfba4d8ep+4 + -0x1.127c6f146c2b4p+8i,
-0x1.1975f22ef2cccp+6 + -0x1.41f3d602b92c2p+6i, -0x1.01ad62051ff5p+5 + -0x1.e3b8080acf97p+3i,
-0x1.7c1e22843ec18p+3 + -0x1.02ef441f6dde8p+7i, -0x1.2241c7d2ed9bcp+5 + -0x1.2e5be5df653e3p+7i,
0x1.0cbde255bb91p+5 + -0x1.9eafd2ff4c9fdp+4i, -0x1.2dd3fc52d2e84p+6 + -0x1.0805d3d63d556p+7i,
-0x1.6ae967a6567eap+4 + -0x1.d73b2aec801fp+3i, 0x1.063687f2e5237p+5 + -0x1.cf1c90ff3d588p+6i,
-0x1.841b31002dcc8p+2 + -0x1.0cab5c8c7d4b4p+5i, -0x1.d31b177a31cf7p+2 + -0x1.ac5e436b91d01p+6i,
-0x1.e036b1c1c024p+3 + 0x1.354b9350696ebp+6i, -0x1.9d90fb72d14a3p+4 + -0x1.54049024c34b2p+5i,
0x1.5d78533363199p+6 + -0x1.a5a495343125fp+4i, 0x1.904763f8f2b08p+3 + -0x1.836b113e400bp+5i,
-0x1.94fabe84e87d4p+6 + 0x1.52d798f4432f8p+6i, -0x1.fb41d0f6e8968p+4 + 0x1.34d0e7f2c9b58p+4i,
0x1.154a311ef5184p+5 + -0x1.ee29250e6eaefp+5i, -0x1.b926736c77cfp+3 + -0x1.9e2450b4ad6a4p+5i,
-0x1.d89ccb7531d1p+6 + 0x1.6e45ddf348808p+6i, 0x1.2f1384ff3a6e6p+3 + -0x1.a8eca8670a1p+2i,
0x1.a525a535c9f6ep+6 + 0x1.2c0164eb8bd46p+7i, 0x1.d57678cb93e1p+1 + -0x1.248f71d92d555p+6i,
-0x1.3b0e9a751433p+2 + -0x1.352dfedff2e63p+6i, 0x1.9278291d40fap+4 + -0x1.27f71ed126efp+4i,
0x1.099fe6e43bc44p+5 + 0x1.292124aac7ca7p+7i, -0x1.466e231c94024p+6 + -0x1.bc3792931244p+4i,
0x1.1e98defdca44p+5 + -0x1.f27bb7a9333a2p+5i, 0x1.2b2b633982cb4p+7 + 0x1.b9140d8584184p+6i,
-0x1.4be20b7339bc5p+5 + 0x1.5b1737107011ap+7i, 0x1.381ba8c23d93p+6 + -0x1.a5afe11ca235ep+5i,
0x1.673f1278ab391p+6 + -0x1.8fc2aa52efc7ap+6i, 0x1.043ca3c271f6cp+5 + 0x1.5661291f41acdp+4i,
-0x1.400c9e6220f02p+4 + 0x1.b08faae4290e8p+4i, -0x1.2b25808249aap+0 + -0x1.f576ecaa2c174p+5i,
-0x1.b900819d58255p+5 + 0x1.9b3838bdb9a4cp+2i, 0x1.c03f2dd7ccc2dp+5 + -0x1.15f399de9041ep+5i,
0x1.0bd87ea392731p+4 + 0x1.22859c16c8178p+2i, -0x1.55db4fdeb01f6p+6 + 0x1.164b21965d7d4p+5i,
0x1.c9567405c9ca4p+5 + -0x1.6658eb6d9fe2p+6i, 0x1.7e2b9a72bd4b5p+5 + -0x1.022dd3abf3616p+6i,
0x1.4a4b10cd83b9p+4 + 0x1.61052796ef843p+5i, 0x1.1ccc9bb762d78p+6 + -0x1.18f2289060893p+6i,
0x1.ba71eaa70c72dp+5 + -0x1.a338e086aafacp+5i, 0x1.30e4e3ff44298p+5 + -0x1.35087e3be845p+4i,
0x1.1ff3b519495a2p+6 + -0x1.68f5a66142cafp+5i, -0x1.22533d8312122p+4 + 0x1.b37be758cab5p+2i,
0x1.00195111a4aa6p+5 + -0x1.690fa1e34526p+2i, -0x1.855d398de0236p+4 + -0x1.d52878b094348p+4i,
0x1.34001f9b02f98p+5 + -0x1.af40c8691f1f9p+4i, -0x1.df19dbfa53708p+4 + 0x1.b8651f7d05384p+5i,
0x1.1de4b2aa6963p+3 + 0x1.64630d8abaaep-1i, 0x1.14892f43e0184p+5 + -0x1.9c0aca26c6758p+0i,
0x1.5d769e27ef727p+5 + -0x1.b46874452603cp+4i, -0x1.cffe52554c9e2p+4 + 0x1.b7d2c69661fd2p+5i,
-0x1.912a5b56fd6dp+1 + 0x1.3c6c9ef99e20ap+4i, -0x1.c722aa3e7b186p+5 + -0x1.520f74936f0d6p+4i,
0x1.f62b64e35231p+5 + -0x1.dc3650101f6cp+2i, -0x1.d197f0e030569p+5 + 0x1.ac384dbcffe18p+3i,
0x1.c7e2790d4586p+1 + 0x1.b592146e8eabbp+5i, 0x1.d438a032e3cd8p+0 + 0x1.3944353a9f4d4p+6i,
0x1.8cbc1931b2454p+5 + -0x1.99e09760ae0ccp+5i, -0x1.58477f32507bbp+1 + -0x1.ae9cb5ede05ap+3i,
0x1.5521934a78d65p+4 + -0x1.e6c9957439ffp+2i, -0x1.3fade4635dea9p+5 + -0x1.1773f612be4d2p+6i,
0x1.525c9a249f3e4p+5 + -0x1.3e123726609c9p+5i, 0x1.4857b8fecebf6p+4 + -0x1.5533bb012bf4p+4i,
-0x1.ae9d5792de54p+1 + 0x1.a7f14ea1c8b2ep+6i, -0x1.06e0fb2227a56p+6 + 0x1.64401c2ba13f2p+4i,
0x1.6d6033c42528p+6 + 0x1.08bb43ea0813p+1i, 0x1.16c4f4ebb936cp+4 + -0x1.69f2e75a74344p+4i,
0x1.77688be34b3d8p+2 + 0x1.498b6f3152478p+1i, -0x1.5bd34583008e7p+5 + -0x1.4f5a39357a18bp+4i,
0x1.39700fae27b13p+6 + 0x1.0633ba2df301ap+2i, -0x1.500c69d597e5ap+5 + -0x1.0ab91cbc95ffap+4i,
-0x1.d6fbf6e5e3693p+4 + 0x1.73ac0dabe9fc6p+5i, -0x1.2f6124e51f377p+4 + -0x1.6a80e5e771ec1p+5i,
-0x1.00441c703109dp+5 + -0x1.7044357d8158p-1i, -0x1.8d896e0867874p+3 + -0x1.0fec53416559ep+5i,
0x1.851d90b61ef6p+2 + -0x1.0e79f2076ff6p+6i, -0x1.91904e3207cdp+2 + -0x1.774356cf742e8p+3i,
0x1.1b7bc98066797p+5 + -0x1.be5240d3b192cp+3i, 0x1.20e2a4c336c94p+5 + -0x1.44c32570db58cp+4i,
0x1.56f323a55f2ep+2 + 0x1.581eb5da6a293p+4i, -0x1.571fedf70cfdap+3 + -0x1.f302a8dd82eep+4i,
0x1.eca243efedccp+3 + 0x1.6a32e166edc29p+4i, 0x1.f28fb881ee006p+4 + 0x1.6f8b330119e88p+4i,
-0x1.3df07d3d83ed5p+6 + -0x1.d918ec921bb84p+5i, 0x1.457daa36a2721p+4 + -0x1.ce0abe2a563b6p+2i,
-0x1.c47572dd8312fp+5 + -0x1.222f73959f7c4p+4i, 0x1.821c96841b72ap+2 + 0x1.cd174812298d5p+5i,
0x1.7825328636f2p+0 + -0x1.82fbb06ab11d3p+5i, -0x1.e143abac9793bp+5 + 0x1.9a9e9f7e99d5ep+4i,
-0x1.d4ff320026c3cp+5 + -0x1.71539d7de3383p+3i, 0x1.74dec1e036566p+4 + 0x1.bf542aebab1cfp+4i,
0x1.131140f3ac2acp+5 + 0x1.4c954a8722594p+2i, 0x1.a20dff0259025p+5 + -0x1.d31f8c938601bp+5i,
0x1.a987723d5365dp+5 + -0x1.1083edce2bc9cp+3i, 0x1.6ece586ce1a46p+4 + 0x1.3ab7e34a3bbabp+6i,
-0x1.2e193da55708ep+6 + -0x1.c2ba2f046ef6p-2i, 0x1.00341129108c8p+6 + -0x1.f84782be2b1dep+5i,
0x1.88ae0c5a2d504p+5 + -0x1.2ca1dbab6d3b4p+5i, 0x1.2f3c932f29b7p+1 + 0x1.6cc6df5d3c676p+3i,
-0x1.c98eab73f6a4p+4 + -0x1.554bca55bef63p+6i, 0x1.8ce48aec82415p+3 + -0x1.5d770b22f4309p+5i,
0x1.cb609c88c112p+5 + 0x1.33e2c11988957p+6i, -0x1.a2f4eb92719b2p+5 + -0x1.3cbb3a79097f1p+3i,
-0x1.139ec16eab42fp+5 + -0x1.2e129245f45f6p+7i, -0x1.a7701ab0ca8a9p+4 + 0x1.14403d502a52p+3i,
-0x1.ebb89bdd07584p+3 + -0x1.3192dfbbdfc26p+6i, 0x1.13e6a70bee49p+4 + -0x1.6d95c844d2792p+5i,
0x1.8ee45253f98ep+2 + 0x1.4f5ab42cba30cp+6i, -0x1.ecb09741b1c4p-1 + -0x1.221ca9b7d6469p+6i,
-0x1.8681738191a6fp+5 + -0x1.7aa92d9018c6ap+6i, 0x1.724b4dee89a12p+3 + 0x1.d1be076c0c95bp+2i,
-0x1.098cba9da73bfp+6 + 0x1.3ae20aa44d435p+6i, -0x1.06f9d12c36904p+5 + -0x1.6fc1522bfe6aep+6i,
-0x1.80d2fae0e5c59p+6 + -0x1.2ac10f51a0c79p+6i, -0x1.3822469996b64p+5 + 0x1.5f5b720a93718p+6i,
-0x1.0d2df4c7afd4cp+2 + -0x1.18970ec351348p+5i, -0x1.a3c981f88d683p+6 + 0x1.e1efa99f810f8p+3i,
0x1.5643f66965034p+5 + -0x1.906b20227ca7cp+6i, -0x1.d26a0be7ec7eep+6 + 0x1.0ed1bb4068968p+2i,
-0x1.8bc643cbda524p+3 + -0x1.6d30328cc7693p+6i, 0x1.03a0ada7ae334p+4 + -0x1.41e2634374802p+5i,
-0x1.315b75f4340b6p+3 + -0x1.08ad4b7623c61p+7i, 0x1.7fce232ccfb12p+4 + -0x1.424bb70e489d2p+6i,
0x1.60e8fa1d627p-2 + -0x1.0ac74e101b8f2p+7i, 0x1.5c0480775b58ap+4 + -0x1.a0f88c5e1cd79p+6i,
-0x1.f66afec5929e8p+0 + -0x1.702afc1381324p+5i, 0x1.083c8861cdd54p+7 + -0x1.2d0ae50f6bac2p+7i,
-0x1.91365a760c7f4p+3 + -0x1.eb0a7d20ea5fcp+5i, -0x1.949581eaadce3p+6 + -0x1.659810984138p+5i,
0x1.41aa19c7e14aap+6 + 0x1.46aa1ff3dfc82p+7i, -0x1.654aa9ca0e42ap+5 + -0x1.3bbaf02e71b4p+7i,
0x1.033d865ecc564p+7 + -0x1.27c73cb6db57bp+6i, 0x1.94a41e0182531p+7 + 0x1.bcc98bc3e251bp+5i,
-0x1.cd467328a272p+4 + 0x1.19814f4af7c36p+7i, -0x1.16c5b9301eb2ep+6 + 0x1.876a3d71ff5d1p+5i,
-0x1.f37cc2637d4c4p+4 + -0x1.7e206930f9509p+6i, 0x1.c9c4cacc6decep+5 + -0x1.7f0b382c4641p+3i,
-0x1.d2fa1428fa922p+7 + 0x1.1e92b80e99ecbp+7i, 0x1.ae6c983f98448p+7 + -0x1.4d41908b6d158p+5i,
0x1.05dc785581b9fp+7 + 0x1.afbc2947a22fep+4i, 0x1.3b3261e276d37p+7 + 0x1.5d0f93dea3366p+7i,
-0x1.71c6081a1d6d4p+7 + 0x1.d50d80c69f0dbp+6i, 0x1.fa2913f6f971fp+6 + -0x1.d1e41cdabc4bfp+6i,
0x1.30a970ad68fc1p+6 + 0x1.0e7a3519d97fbp+6i, 0x1.72a9281ee5aacp+4 + -0x1.f94509927a30ep+6i,
0x1.04aca4fa15345p+8 + -0x1.2af391aace1ap+2i, 0x1.e03335739dcdap+7 + 0x1.0315e4a239b85p+7i,
0x1.04ca7736d495bp+5 + -0x1.7bbbfec2d0cc8p+6i, 0x1.5e883d75cbd56p+7 + 0x1.c679f290e2c9p+5i,
0x1.600a2a745e36cp+3 + -0x1.9b0ffeeb363e7p+5i, 0x1.267b111085d42p+7 + -0x1.3239ad99106efp+6i,
0x1.207e4ae67766ap+7 + 0x1.07d9d33a8b352p+3i, 0x1.f2f6e60cf04a8p+7 + -0x1.67d18306ae325p+7i,
-0x1.39953dda29897p+5 + -0x1.b92d15d6ae612p+4i, 0x1.6632b2287fc4ap+8 + 0x1.04c7f85576aa9p+7i,
0x1.514dd0ba2f77p+7 + 0x1.9db2b19e2b2ap+1i, 0x1.16d6ca178b7c2p+6 + -0x1.36a739f0aa698p+6i
)
assertThat(stats:::fft(z=c(11.5322877347435, -0.0536614882909153, 8.10388429405067, 7.12388541217765,
0.634648654879482, 20.6833254842938, -0.209293452834741, 8.1834025852561,
21.7096048994268, -8.66744108958155, 11.3413447309357, 6.25957684569318,
-4.04847768085968, 0.00669891179891191, 3.69273001961162, -0.324271630661781,
3.53811102919027, -7.99149334008458, -0.0102746159410632, -7.9084025084199,
-4.53227802531144, -3.1695145523155, -0.864185075878322, -0.398000959481147,
3.03058780827192, 0.147094061760344, -1.29472877344459, 0.174294262007368,
1.50616668651532, 1.03254251754203, -0.373638003965538, 0.0266208434309929,
2.48043908368853, -2.50526412432748, 0.30690547474626, 0.349642739530974,
6.72975734560601, 2.8890842505495, 1.67781475634695, 5.02189702333893,
-1.66055109785237, 1.16228724804414, 0.230913971772941, 0.0835513315335332,
3.02573807301983, -9.61285442877846, 3.42426082420763, 1.66855831536857,
-1.05259726864905, -2.8587199950412, 2.27652604048087, 3.37370877425695,
0.626715969904431, 2.02680689688908, -0.106173931047774, 4.05964071110835,
-0.429723534569165, 9.9623455881932, -1.04430990664505, -2.05892006945102,
0.932154475075483, 4.04395653845625, -4.97944044996944, -2.41748837370433,
-0.44895603075282, -4.02834963633426, 0.620322975096342, -1.15058491287586,
0.826950398158126, -2.50567395281835, 0.699821800321542, 2.11211178878044,
2.04735307386135, -2.92785006289004, 2.10292525623853, 3.45883850396476,
-0.671545458899436, 5.84239075792953, 0.563010253568881, 1.50358413790881,
0.00602773681692171, 0.408266963803238, -1.25956219870405, -0.732088282589892,
1.81543586186064, 0.724049036972522, 3.1735719491931, 1.45844201665592,
-2.20565622153703, -0.611422913809857, -1.92370917377262, 1.09614589550477,
-0.00457882050876997, 1.58603052554574, -0.771296666845567, 1.10790473433538,
-13.4072858820316, 2.62229137656914, -4.92504625020915, -4.11482057721809,
4.78439406922046, 0.604538269265267, 4.75259203132082, -2.26347513843737,
7.38556723168493, -4.5031573891696, -3.34030944887638, 6.36007798002467,
-2.20637032158137, -18.197837172008, 3.27253991179982, -8.32283891053862,
-3.09246137527566, -0.857308361913176, -8.59847976133741, 0.193193723881243,
-10.6078310513925, 2.73605756847678, -3.4690116511855, -4.0922938043148,
0.835042235655886, 4.58113606623019, -3.48612959994298, 3.88319495087222,
0.694612040388423, 0.80151350556459, 1.21608936226856, -0.146830520602753,
-1.97523798214778, -3.8032912376745, -1.32066476942786, -3.1469052447554,
0.330968529506233, 2.50219654284036, -0.00534679693188097, 2.06770977641846,
1.2770416282903, -4.56652819369173, 1.18070542411989, -8.45910028112526,
0.500313327202124, -9.890134984691, 3.80427381285811, -3.28410753671459,
-0.0928863710767388, -1.13586531490098, 0.00142177069221664,
-1.6368331330302, -1.27560914922195, 4.5942060362111, -0.136144647655544,
6.64978435728382, 0.620741030357076, 11.1940268663154, 6.38863824971662,
-0.0968271769604799, -1.75142016892662, -2.12272925858779, 0.808778833106189,
-3.27410938305493, -1.87926977392442, 3.90793437249278, -0.129364676797616,
6.67327962079714, -1.23241389955717, 10.3340692183342, 4.49995204228895,
-0.0175684929204964, 10.0198421874161, 8.9142567170814, 0.965828250129739,
4.47214627709161, 11.3760856208011, -3.83374614632753, 9.39467171249471,
-0.211894601421547, 5.6260991382355, 7.39370308616533, -2.19703219902215,
0.477785795263814, 6.69342208489987, 0.271087280818287, -0.08866407563,
-0.892298925717517, -0.0655739925678449, 1.70824976848388, 9.74434779116223,
0.047059087305297, 6.66327852556352, -0.733242516998134, -0.862763720321917,
0.532230208135849, 1.81853492867694, 0.073173918632501, -0.0120313235998422,
-0.709822172742577, -0.0365218393879865, 2.20173709326303, 7.15838705301316,
1.71593352824277, 6.80902593716949, 0.631154474802138, -2.30222003886426,
-0.131440818992655, -1.81093283688568, 0.816657557136837, 0.315036696486329,
1.49153540674174, 4.77648470027498, -5.35524597943366, 3.69216544938606,
-4.70986387995559, -0.0298074745418237, -3.42418611047606, -2.07909868468986,
0.86132764239749, -3.45611867803019, 4.08717401387356, 5.13942988746377,
2.71707924098775, 11.7389555330178, -3.52763050590055, 6.70057260091543,
-1.21245743036517, -0.0471250902662232, 7.31049337751672, -2.92928208577723,
-15.7076983395274, 0.63733823895768, -3.06253651103384, -9.95912511629547,
6.82287854428249, -19.4024635601163, 6.95878639659263, -13.8216141163645,
2.7120340145206, -7.77407462095592, -13.513178075734, 10.2223216488225,
-4.22180518657962, -0.616630024282006, 0.0969658155583185, 0.739868492840877,
-0.736455002272661, 4.02197590170101, 3.20195481765355, -0.21625823668785,
3.23374230114808, -1.82251152690908, -4.55969152782826, 5.46420594309378,
-1.72396052139612, 0.248221910480828, 0.290997787609224, 0.160378112098767,
1.30565173508994, 2.11405227228869, -1.25371061658579, -0.322274215846882,
0.771284123778419, -5.82916249789895, -4.7688594054108, 1.09757683227523,
-10.7753363770895, 0.679683351531881, 8.71092738239496, -4.24896710613194,
16.9944227083797, 3.49396472360447, 7.38168846440029, 16.0501687217935,
-2.82853241537599, 13.7623602185726, -1.13934151045584, -0.33303108290957,
10.6095112893565, 1.21280563244208, -3.26703517084193, 5.42566343048067,
1.90615443758752, -3.76929098760009, 4.7571522247348, -4.56749632060659,
3.48505186522957, 2.38634564614694, 0.720134853083301, 0.0173349424500548,
-2.46683586012268, -0.264854638050591, -1.68672652680576, -3.62579119964558,
0.191410234483265, -3.33100322243884, -1.23832654965653, -1.51271513527201,
-3.21004788668115, -0.677638617308621, -6.76458871937203, -0.0595937932771723,
0.905273755826399, -0.665348283295009, 4.26156394787796, 8.13053719457733,
0.706617892077626, 5.34922822655341, 0.390024021340803, 4.10094350953699,
8.54431214167078, -0.428658532924323, 5.80977874906543, 7.95416262868259,
3.96409184859711, 1.0270509303756, 11.4978449522953, 5.69071149278792,
1.71245082553867, 5.33664978404515, -0.232282926333662, 7.77512020618274,
5.97247960628241, 0.671851241883722, 11.2576322982288, -0.493627408568823,
-19.8105786010346, 6.19139526090894, -9.67081923341575, -7.31550578449565,
2.4158941512503, -4.20661615110722, 3.25330587170611, -0.48893765610774,
-5.33816556417316, 4.89329913232602, -11.0745355673873, 0.745658812763246,
21.4225369306003, -11.5373050729955, 17.3690479458296, 13.5338453597935,
-5.80352036607883, 16.9292340489376, 0.687513189357384, 1.05372199155113,
8.89073380712435, -11.7747491177948, 11.1662011727824, 2.36590450521909,
-24.6147805310095, 13.4682057889952, -10.8297221948164, -6.74435215918939,
14.2990024988825, -7.80399898169954, -0.930435016741878, 0.321488406672147,
-6.857038098823, 13.2451606534375, -2.66148710976401, -1.23417272603375,
16.3591694745706, 7.08590128328528, 1.33646705573818, -0.56311276188225,
2.54820325921967, -1.96480359504391, -4.25723853098776, -0.0776726504030251,
-0.64344874994151, -2.35581150968545, 0.299289630671684, 1.35468917177273,
-2.56823906954974, -2.81906400531936, 0.109353810080396, 0.579503978626958,
-0.707899159556581, 2.64445110496137, 2.13806939588322, -1.224278628552,
0.805978534861034, 0.376984163413155, -1.91911667244579, -1.38425250749227,
-0.809550458408014, -5.64389046017235, -0.350469584338703, 1.59190247258925,
-3.23875262389022, 7.47336910432749, 2.02559416181311, 4.28660730624579,
8.26458185653524, -1.24119303458942, 7.25599872181589, 7.73800445477148,
2.14204589483061, 10.6125479452692, -3.11047296991716, -1.29762985706114,
2.53438555626821, -9.81060993607349, -2.38711547928007, -4.51756875842113,
-8.15520205797756, 1.87215005977658, -7.00271473838324, -9.66316630274651,
-4.98723055840333, -10.3346181113708, 3.21058150666009, -1.67116244708664,
-2.59609868860278, 2.817272347566, -1.80390285834556, 0.189320448742696,
2.53318240441112, -1.10418529151376, 0.475894571767647, 0.121382902515877,
-0.150468000171074, 1.26655888970022, 2.36460134108056, -1.08876139639527,
-1.05586258793118, 1.4416293351108, -0.0746955861959464, 0.437292873611172,
0.966824603061367, 1.19967406239761, 0.27987994117392, 0.0727495646706561,
0.0547790151715594, 1.88603632419523, 3.81703430837322, -1.22688536881049,
-1.95158226953404, 2.67542807961795, -0.485318359658868, 8.73316813799053,
-1.2626836337253, 4.38927324061488, -0.635253885794933, -6.50838946636762,
-0.798736937734671, 4.42660261545315, -10.5105661136931, 0.956252645260474,
-0.375614736453113, 2.32387372105472, 3.78487569254801, 8.39347536421347,
0.429269311717134, 16.6988816716912, -1.0277607447264, 4.97280286849382,
3.15259355009544, 3.40220551135325, -5.79235899059601, 0.890912184254578,
-0.316440269791223, 2.07638491989382, 3.40063013920156, 11.7890976851689,
0.65194608903028, 22.6051490917594, 14.548240757248, 6.7024158797134,
19.992901935073))
, identicalTo( expected, tol = 1e-6 ) ) |
setClass("cgOneFactorFit",
representation(olsfit="olsfit",
rrfit="rrfit",
aftfit="aftfit",
uvfit="uvfit",
settings="list"))
setMethod("fit", "cgOneFactorData",
fit.cgOneFactorData <-
function(data, type="rr", ...) {
dots <- list(...)
validDotsArgs(dots, names=c("maxIter","sandaft"))
rr <- aft <- uv <- FALSE
aftfit <- rrfit <- uvfit <- "No fit was requested."
if([email protected]) { type <- "aft" }
else if(missing(type)) { type <- "rr" }
type <- validFitType(type)
maxIter <- if(is.null(dots$maxIter)) 100 else dots$maxIter
validNumeric(maxIter, positive=TRUE, integer=TRUE)
if(type=="rr") { rr <- TRUE }
else if(type=="aft") { aft <- TRUE }
else if(type=="uv") { uv <- TRUE }
dfru <- data@dfru
settings <- data@settings
endptscale <- settings$endptscale
grpnames <- settings$grpnames
oldop <- options(contrasts=c("contr.treatment", "contr.poly"))
on.exit(oldop, add=TRUE)
validAft(type, dfru)
olsfit <- if(endptscale=="log") {
lm(log(endpt) ~ -1 + grpf, data=dfru)
}
else {
lm(endpt ~ -1 + grpf, data=dfru)
}
olsfit$dfru <- dfru
names(olsfit$coef) <- grpnames
if(rr) {
rrfit <-
if(endptscale=="log") {
try(rlm(log(endpt) ~ -1 + grpf, data=dfru, method="MM",
maxit=maxIter, ...))
}
else {
try(rlm(endpt ~ -1 + grpf, data=dfru, method="MM",
maxit=maxIter, ...))
}
if(class(rrfit)[1]!="try-error") {
rrfit$dfru <- dfru
names(rrfit$coef) <- grpnames
class(rrfit) <- "rlm"
}
else {
warning(cgMessage("The Resistant & Robust (rr) fit did not",
"converge in the specified number of",
"iterations. You may want to try again with an",
"increased value for the maxIter argument.",
warning=TRUE))
rrfit <- "The fit did not converge in the specified number of iterations."
}
}
else if(aft) {
if(!is.null(sandaft <- dots$sandaft)) {
validBoolean(sandaft)
}
else {
sandaft <- TRUE
}
thesurvobject <- with(dfru,
if(endptscale=="log") {
survival::Surv(time=log(endpt1), time2=log(endpt2),
event=status, type="interval")
}
else {
survival::Surv(time=endpt1, time2=endpt2,
event=status, type="interval")
})
aftfit <- try(survreg(thesurvobject ~ -1 + grpf,
data=dfru, dist="gaussian", maxiter=maxIter))
if(class(aftfit)[1]!="try-error") {
aftfit$dfru <- dfru
aftfit$Surv <- thesurvobject
aftfit$maxIter <- maxIter
names(aftfit$coef) <- grpnames
aftfit$sandaft <- sandaft
if(sandaft) {
aftfit$naive.var <- aftfit$var
aftfit$var <- crossprod(resid(aftfit, "dfbeta"))
}
}
else {
warning(cgMessage("The Accelerated Failure Time (aft) fit did not",
"converge in the specified number of",
"iterations. You may want to try again with an",
"increased value for the maxIter argument.",
warning=TRUE))
aftfit <- paste("The AFT fit did not converge in the specified",
"number of iterations.")
}
}
else if(uv) {
uvfit <- if(endptscale=="log") {
gls(log(endpt) ~ -1 + grpf, data=dfru,
weights=varIdent(form = ~ 1 | grpf))
}
else {
gls(endpt ~ -1 + grpf, data=dfru,
weights=varIdent(form = ~ 1 | grpf))
}
uvfit$dfru <- dfru
names(uvfit$coef) <- grpnames
}
returnObj <- new("cgOneFactorFit",
olsfit=olsfit,
rrfit=rrfit,
aftfit=aftfit,
uvfit=uvfit,
settings=settings)
returnObj
})
setMethod("print", "cgOneFactorFit",
print.cgOneFactorFit <-
function(x, title=NULL, endptname=NULL,...) {
dots <- list(...)
validDotsArgs(dots, names="model")
modelarg <- getDotsArgName(dots, "model")
if(!is.na(modelarg)) {
model <- eval(parse(text=paste("dots$", modelarg, sep="")))
model <- validArgMatch(model, choices=c("both", "olsonly","rronly"))
}
else {
model <- "both"
}
olsfit <- x@olsfit
rrfit <- x@rrfit
aftfit <- x@aftfit
uvfit <- x@uvfit
settings <- x@settings
ols <- rr <- uv <- aft <- FALSE
if(class(aftfit)[1]=="survreg") {
aft <- TRUE
validArgModel(...)
}
else if(class(uvfit)[1]=="gls") {
uv <- TRUE
validArgModel(...)
}
if(class(rrfit)[1]=="rlm" && model!="olsonly" && !aft && !uv) {
rr <- TRUE
}
if(class(olsfit)[1]=="lm" && (model!="rronly") && !aft && !uv) {
ols <- TRUE
if(!rr) model <- "olsonly"
}
if(is.null(title)) {
title <- paste("Fitted Models of", settings$analysisname)
}
else {
validCharacter(title)
}
if(is.null(endptname)) {
endptname <- settings$endptname
if(!is.character(endptname)) {
endptname <- ""
}
}
else {
validCharacter(endptname)
}
cat(title,"\n")
if(endptname!="") { cat(paste("Endpoint:", endptname, "\n")) }
if(ols) {
cat("\nClassical Least Squares Model Fit\n")
print(olsfit, ...)
}
if(rr) {
cat("\nResistant & Robust Model Fit\n\n")
print(rrfit, ...)
cat("\nEstimated Standard Deviation from rlm is",
signif(summary(rrfit)$stddev, 4), "\n\n")
}
if(aft) {
cat("\nAccelerated Failure Time Model Fit\n")
print(aftfit, ...)
}
if(uv) {
cat("\nUnequal Variances Model Fit\n")
print(uvfit, ...)
}
invisible()
}
)
setMethod("show", "cgOneFactorFit", function(object) print(object))
setMethod("showObj", "cgOneFactorFit",
showObj.cgOneFactorFit <- function(object) showDefault(object))
setMethod("summary", "cgOneFactorFit",
summary.cgOneFactorFit <-
function(object, title=NULL, endptname=NULL, ...) {
dots <- list(...)
validDotsArgs(dots, names="model")
modelarg <- getDotsArgName(dots, "model")
if(!is.na(modelarg)) {
model <- eval(parse(text=paste("dots$", modelarg, sep="")))
model <- validArgMatch(model, choices=c("both", "olsonly","rronly"))
}
else {
model <- "both"
}
olsfit <- object@olsfit
rrfit <- object@rrfit
aftfit <- object@aftfit
uvfit <- object@uvfit
settings <- object@settings
ols <- rr <- uv <- aft <- FALSE
if(class(aftfit)[1]=="survreg") {
aft <- TRUE
validArgModel(...)
}
else if(class(uvfit)[1]=="gls") {
uv <- TRUE
validArgModel(...)
}
if(class(rrfit)[1]=="rlm" && model!="olsonly" && !aft && !uv) {
rr <- TRUE
}
if(class(olsfit)[1]=="lm" && (model!="rronly") && !aft && !uv) {
ols <- TRUE
if(!rr) model <- "olsonly"
}
if(is.null(title)) {
title <- paste("Fitted Model Summaries of", settings$analysisname)
}
else {
validCharacter(title)
}
if(is.null(endptname)) {
endptname <- settings$endptname
if(!is.character(endptname)) {
endptname <- ""
}
}
else {
validCharacter(endptname)
}
cat(title,"\n")
if(endptname!="") { cat(paste("Endpoint:", endptname, "\n")) }
if(ols) {
cat("\nClassical Least Squares Model Fit Summary\n")
print(summary(olsfit, ...))
}
if(rr) {
cat("\nResistant & Robust Model Fit Summary\n")
print(summary(rrfit, ...))
cat("\nEstimated Standard Deviation from rlm is",
signif(summary(rrfit)$stddev, 4), "\n\n")
}
if(aft) {
cat("\nAccelerated Failure Time Model Fit Summary\n")
print(summary(aftfit, ...))
}
if(uv) {
cat("\nUnequal Variances Model Fit Summary\n")
print(summary(uvfit, ...))
}
invisible()
}
)
validAft <- function(type, dfru) {
if(type=="aft" && ncol(dfru)!=5) {
stop(cgMessage("An accelerated failure time (AFT) model",
"cannot be fit as requested (type=\"aft\")",
"since the data frame does not seem to have",
"a censored status column or the required format.",
seeHelpFile("CGOneFactorFit")))
}
return(TRUE)
}
validFitType <- function(type) {
x <- try(match.arg(type, c("ols","rr","aft","uv")))
if(class(x)=="try-error") {
stop(cgMessage("The type argument needs to evaluate to one",
"of: \"ols\", \"rr\", \"aft\", \"uv\".",
seeHelpFile("CGOneFactorFit")))
}
else return(x)
} |
jc.probs <- function(x, y1, y2, y3 = NULL, newdata, type = "joint", cond = 0, intervals = FALSE, n.sim = 100, prob.lev = 0.05,
min.pr = 1e-323, max.pr = 1, cumul = "no"){
if(x$VC$Model == "ROY") stop("This function is not designed for the type of model chosen for modelling. Get in touch for more info.")
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol
cont1par <- x$VC$m1d
cont2par <- c(x$VC$m2,x$VC$m2d)
cont3par <- x$VC$m3
bin.link <- x$VC$bl
if(x$VC$Cont == "YES" && x$surv == TRUE && x$margins[1] %in% c(cont2par,cont3par) && x$margins[2] %in% c(cont2par,cont3par)) stop("This function is currently not suitable for survival models with\nparametric margins. Consider using semiparametric margins instead. ")
if(x$VC$Cont == "YES" && x$surv == TRUE && x$margins[1] %in% bin.link && x$margins[2] %in% bin.link) y1 <- y2 <- 1
if(x$VC$Cont == "YES" && x$surv == TRUE && x$margins[1] %in% c(cont2par,cont3par) && x$margins[2] %in% bin.link ) y2 <- 1
if(x$univar.gamlss == TRUE) stop("This function is not suitable for univariate models.")
if(missing(y1)) stop("You must provide a value for y1.")
if(missing(y2)) stop("You must provide a value for y2.")
if(x$triv == TRUE && missing(y3)) stop("You must provide a binary value for y3.")
if(!(type %in% c("joint","independence"))) stop("Error in parameter type value. It should be one of: joint, independence.")
if(!(cond %in% c(0,1,2, 3))) stop("Error in parameter cond value. It should be one of: 0, 1, 2 or 3 (for the trivariate model).")
if( type %in% c("independence") && x$VC$gamlssfit == FALSE && is.null(x$VC$K1)) stop("You need to re-fit the model and set gamlssfit = TRUE to obtain probabilities under independence.")
if(x$margins[1] %in% c(x$VC$m1d, x$VC$m2d) && (!is.wholenumber(y1) || y1 < 0)) stop("The value for y1 must be discrete and positive.")
if(x$margins[2] %in% c(x$VC$m1d, x$VC$m2d) && (!is.wholenumber(y2) || y2 < 0)) stop("The value for y2 must be discrete and positive.")
if( x$VC$Cont == "NO" && !(x$margins[2] %in% bin.link) && !(y1 %in% c(0,1)) && is.null(x$VC$K1) ) stop("The value for y1 must be either 0 or 1.")
if( x$VC$Cont == "NO" && !(x$margins[2] %in% bin.link) && !is.null(x$VC$K1) && !(y1 %in% seq.int(1, x$VC$K1))) stop(paste(paste("The value for y1 must be an integer between 1 and", x$VC$K1, "")), ".")
if( x$VC$Cont == "NO" && x$margins[2] %in% bin.link){ if( !(y1 %in% c(0,1)) || !(y2 %in% c(0,1)) ) stop("The value for y1 and/or y2 must be either 0 or 1.") }
if(x$triv == FALSE) {if(!missing(newdata) && x$BivD %in% x$BivD2) stop("Prediction for models based on mixed copulae and a new dataset is not feasible.")}
if(x$triv == TRUE){
if( !(y1 %in% c(0,1)) ) stop("The value for y1 must be either 0 or 1.")
if( !(y2 %in% c(0,1)) ) stop("The value for y2 must be either 0 or 1.")
if( !(y3 %in% c(0,1)) ) stop("The value for y3 must be either 0 or 1.")
}
if(x$triv == FALSE){
if(x$VC$Cont == "YES" && x$surv == FALSE ) rr <- jc.probs1(x, y1, y2, newdata, type, cond, intervals, n.sim, prob.lev, cont1par, cont2par, cont3par, bin.link, min.pr, max.pr, cumul)
if(x$VC$Cont == "NO" && !(x$margins[2] %in% bin.link) ){
if( is.null(x$VC$K1)) rr <- jc.probs2(x, y1, y2, newdata, type, cond, intervals, n.sim, prob.lev, cont1par, cont2par, cont3par, bin.link, min.pr, max.pr)
if(!is.null(x$VC$K1)) {
if( type %in% c("joint") && x$VC$ind.ord == "TRUE") stop("You need to provide the fitted joint model as input to obtain predictive probabilities.")
if( type %in% c("independence") && x$VC$ind.ord != "TRUE") stop("You need to provide the fitted independence model as input to obtain probabilities under independence.")
rr <- jc.probs7(x, y1, y2, newdata, type, cond, intervals, n.sim, prob.lev, cont1par, cont2par, cont3par, bin.link, min.pr, max.pr)
}
}
if(x$VC$Cont == "NO" && x$margins[2] %in% bin.link) rr <- jc.probs3(x, y1, y2, newdata, type, cond, intervals, n.sim, prob.lev, cont1par, cont2par, cont3par, bin.link, min.pr, max.pr)
if(x$VC$Cont == "YES" && x$surv == TRUE && x$margins[1] %in% bin.link && x$margins[2] %in% bin.link ) rr <- jc.probs4(x, y1, y2, newdata, type, cond, intervals, n.sim, prob.lev, cont1par, cont2par, cont3par, bin.link, min.pr, max.pr)
if(x$VC$Cont == "YES" && x$surv == TRUE && x$margins[1] %in% c(cont2par,cont3par) && x$margins[2] %in% bin.link ) rr <- jc.probs5(x, y1, y2, newdata, type, cond, intervals, n.sim, prob.lev, cont1par, cont2par, cont3par, bin.link, min.pr, max.pr)
}
if(x$triv == TRUE) rr <- jc.probs6(x, y1, y2, y3, newdata, type, cond, intervals, n.sim, prob.lev, cont1par, cont2par, cont3par, bin.link, min.pr, max.pr)
p12s <- rr$p12s
p12 <- rr$p12
p1 <- rr$p1
p2 <- rr$p2
if(x$triv == TRUE){
p3 <- rr$p3
theta12 <- rr$theta12
theta13 <- rr$theta13
theta23 <- rr$theta23
theta12s <- rr$theta12s
theta13s <- rr$theta13s
theta23s <- rr$theta23s
}
if(intervals == TRUE){
CIp12 <- rowQuantiles(p12s, probs = c(prob.lev/2,1-prob.lev/2), na.rm = TRUE)
if(x$triv == TRUE){
if(type == "joint"){
CItheta12 <- rowQuantiles(theta12s, probs = c(prob.lev/2,1-prob.lev/2), na.rm = TRUE)
CItheta13 <- rowQuantiles(theta13s, probs = c(prob.lev/2,1-prob.lev/2), na.rm = TRUE)
CItheta23 <- rowQuantiles(theta23s, probs = c(prob.lev/2,1-prob.lev/2), na.rm = TRUE)
}else{
CItheta12 <- CItheta13 <- CItheta23 <- cbind(0, 0)
}
}
if(x$triv == FALSE){
if(length(p12) > 1) {res <- data.frame(p12, CIp12, p1, p2); names(res)[2:3] <- names(quantile(c(1,1), probs = c(prob.lev/2,1-prob.lev/2)))}
if(length(p12) == 1) {res <- data.frame(t(c(p12, CIp12, p1, p2))); names(res) <- c("p12",names(quantile(c(1,1), probs = c(prob.lev/2,1-prob.lev/2))),"p1","p2")}
}
if(x$triv == TRUE){
if(length(p12) > 1){ p123 <- p12
CIp123 <- CIp12
res <- data.frame(p123, CIp123, p1, p2, p3, theta12, theta13, theta23, CItheta12, CItheta13, CItheta23 )
names(res)[c(2:3, 10:15)] <- c(rep(names(quantile(c(1,1), probs = c(prob.lev/2,1-prob.lev/2))),4))
}
if(length(p12) == 1) {res <- data.frame(t(c(p12, CIp12, p1, p2, p3, theta12, theta13, theta23, CItheta12, CItheta13, CItheta23)))
names(res) <- c("p123",names(quantile(c(1,1), probs = c(prob.lev/2,1-prob.lev/2))),"p1","p2","p3",
"theta12", "theta13", "theta23", c(rep(names(quantile(c(1,1), probs = c(prob.lev/2,1-prob.lev/2))),3)) )
}
rm(p12, CIp12)
}
}else{
if(x$triv == FALSE) res <- data.frame(p12, p1, p2)
if(x$triv == TRUE) {p123 <- p12; res <- data.frame(p123, p1, p2, p3, theta12, theta13, theta23)}
}
res.n <- names(res)
if(x$triv == FALSE && !is.null(rr$tau) && !is.null(rr$CIkt)){
if(is.null(dim(rr$CIkt))) {CItauLB <- rr$CIkt[1]; CItauUB <- rr$CIkt[2]}
if(!is.null(dim(rr$CIkt))) {CItauLB <- rr$CIkt[,1]; CItauUB <- rr$CIkt[,2]}
res <- data.frame(res, tau = rr$tau, CItauLB = CItauLB, CItauUB = CItauUB )
names(res)[1 : length(res.n)] <- res.n
}
if(x$triv == FALSE && !is.null(rr$tau) && is.null(rr$CIkt)) res <- data.frame(res, tau = rr$tau )
return(res)
} |
getbetterint <- function (int) {
int = as.factor(int)
ilocate_comma = stringr::str_locate(levels(int), ",")
start <- as.numeric( substr( levels(int), 2,ilocate_comma - 1 ) )
end <- as.numeric( substr( levels(int), ilocate_comma + 1, nchar( levels(int) ) - 1 ) )
levels(int) <- paste0(
formatC( start, big.mark = ",", format = "f", drop0trailing = TRUE )
, "-",
formatC( end, big.mark = ",", format = "f", drop0trailing = TRUE )
)
return(int)
} |
NULL
createTD <- function(data,
genotype = NULL,
trial = NULL,
loc = NULL,
year = NULL,
repId = NULL,
subBlock = NULL,
plotId = NULL,
rowCoord = NULL,
colCoord = NULL,
rowId = rowCoord,
colId = colCoord,
checkId = NULL,
trLocation = NULL,
trDate = NULL,
trDesign = NULL,
trLat = NULL,
trLong = NULL,
trPlWidth = NULL,
trPlLength = NULL) {
dataName <- deparse(substitute(data))
if (length(dataName) > 1) {
dataName <- "dat"
}
if (missing(data) || !is.data.frame(data)) {
stop("data has to be a data.frame.\n")
}
data <- as.data.frame(data)
cols <- colnames(data)
for (param in c(genotype, trial, loc, year, repId, subBlock, plotId,
rowId, colId, rowCoord, colCoord, checkId)) {
if (!is.null(param) && (!is.character(param) || length(param) > 1 ||
!hasName(data, param))) {
stop(deparse(param), " has to be NULL or a column in data.\n")
}
}
checkTDMeta(trPlWidth = trPlWidth, trPlLength = trPlLength)
renameCols <- c("genotype", "trial", "loc", "year", "repId", "plotId",
"subBlock", "rowId", "colId", "rowCoord", "colCoord",
"checkId")
renameFrom <- as.character(sapply(X = renameCols, FUN = function(x) {
get(x)
}))
renamed <- data.frame(orig = renameFrom[renameFrom != "NULL"],
new = renameCols[renameFrom != "NULL"],
stringsAsFactors = FALSE)
dupCols <- which(duplicated(renameFrom) & renameFrom != "NULL")
for (dupCol in dupCols) {
tempName <- paste0(".temp", dupCol)
data[tempName] <- data[, colnames(data) == renameFrom[dupCol]]
cols[length(cols) + 1] <- tempName
renameFrom[dupCol] <- tempName
}
for (i in 1:length(renameCols)) {
cols[cols == renameFrom[i]] <- renameCols[i]
}
dupCols <- cols[duplicated(cols)]
if (length(dupCols) > 0) {
stop("The following columns already exist in the input data:\n",
paste(dupCols, collapse = ","), "\n",
"Renaming another column to one of these is impossible.\n")
}
colnames(data) <- cols
factorCols <- c("genotype", "trial", "loc", "year", "repId", "subBlock",
"plotId", "rowId", "colId", "checkId")
for (factorCol in factorCols) {
if (hasName(data, factorCol) && !is.factor(data[[factorCol]])) {
data[cols == factorCol] <- as.factor(data[, cols == factorCol])
}
}
if (all(hasName(data, c("trial", "plotId")))) {
data$plotId <- interaction(data$trial, data$plotId, sep = "_")
}
numCols <- c("rowCoord", "colCoord")
for (numCol in numCols) {
if (hasName(data, numCol) && !is.numeric(data[cols == numCol])) {
data[cols == numCol] <- as.numeric(data[, cols == numCol])
}
}
if (all(hasName(data, c("rowCoord", "colCoord")))) {
data <- data[order(data[["rowCoord"]], data[["colCoord"]]), ]
if (hasName(data, "trial")) {
rowColTab <- table(data[["trial"]], data[["rowCoord"]],
data[["colCoord"]])
if (any(rowColTab > 1)) {
warning("Combinations of row and column coordinates should be unique ",
"within trials.\n")
}
} else {
rowColTab <- table(data[["rowCoord"]], data[["colCoord"]])
if (any(rowColTab > 1)) {
warning("Combinations of row and column coordinates should be unique.\n")
}
}
}
if (hasName(data, "trial")) {
listData <- split(x = data, f = data[["trial"]], drop = TRUE)
} else {
listData <- setNames(list(data), dataName)
}
meta <- c("trLocation", "trPlWidth", "trPlLength")
metaVals <- sapply(X = meta, FUN = function(m) {
if (!is.null(get(m))) {
metaVal <- rep(x = get(m), length.out = length(listData))
if (is.null(names(metaVal)) || !all(hasName(listData, names(metaVal)))) {
names(metaVal) <- names(listData)
}
return(metaVal)
} else {
NULL
}
}, simplify = FALSE)
for (tr in names(listData)) {
for (m in meta) {
attr(x = listData[[tr]], which = m) <- unname(metaVals[[m]][tr])
}
if (is.null(trLocation)) {
if (hasName(x = listData[[tr]], name = "loc") &&
length(unique(listData[[tr]][["loc"]])) == 1) {
attr(x = listData[[tr]],
which = "trLocation") <- as.character(listData[[tr]][["loc"]][1])
} else {
attr(x = listData[[tr]], which = "trLocation") <- tr
}
}
trLatDat <- trLat
if (!is.null(trLat) && hasName(x = listData[[tr]], name = trLat)) {
trLatDat <- unique(listData[[tr]][[trLat]])
if (!length(trLatDat) == 1) {
stop("trLat not unique for ", tr, ".\n")
}
}
trLongDat <- trLong
if (!is.null(trLong) && hasName(x = listData[[tr]], name = trLong)) {
trLongDat <- unique(listData[[tr]][[trLong]])
if (!length(trLongDat) == 1) {
stop("trLong not unique for ", tr, ".\n")
}
}
chkLatLong(trLatDat, trLongDat)
attr(x = listData[[tr]], which = "trLat") <- trLatDat
attr(x = listData[[tr]], which = "trLong") <- trLongDat
trDateDat <- trDate
if (!is.null(trDate) && hasName(x = listData[[tr]], name = trDate)) {
trDateDat <- unique(listData[[tr]][[trDate]])
if (!length(trDateDat) == 1) {
stop("trDate not unique for ", tr, ".\n")
}
}
attr(x = listData[[tr]], which = "trDate") <- trDateDat
trDesignDat <- trDesign
if (!is.null(trDesign) && hasName(x = listData[[tr]], name = trDesign)) {
trDesignDat <- unique(listData[[tr]][[trDesign]])
if (!length(trDesignDat) == 1) {
stop("trDesign not unique for ", tr, ".\n")
}
}
chkDesign(trDesignDat)
attr(x = listData[[tr]], which = "trDesign") <- trDesignDat
attr(x = listData[[tr]], which = "renamedCols") <-
if (nrow(renamed) > 0) renamed else NULL
}
TD <- structure(listData,
class = c("TD", "list"))
return(TD)
}
addTD <- function(TD,
data,
genotype = NULL,
trial = NULL,
loc = NULL,
year = NULL,
repId = NULL,
subBlock = NULL,
plotId = NULL,
rowCoord = NULL,
colCoord = NULL,
rowId = rowCoord,
colId = colCoord,
checkId = NULL,
trLocation = NULL,
trDate = NULL,
trDesign = NULL,
trLat = NULL,
trLong = NULL,
trPlWidth = NULL,
trPlLength = NULL) {
TDNw <- createTD(data = data, genotype = genotype, trial = trial,
loc = loc, year = year, repId = repId,
subBlock = subBlock, plotId = plotId, rowCoord = rowCoord,
colCoord = colCoord, rowId = rowId, colId = colId,
checkId = checkId, trLocation = trLocation, trDate = trDate,
trDesign = trDesign, trLat = trLat, trLong = trLong,
trPlWidth = trPlWidth, trPlLength = trPlLength)
dupTrials <- names(TDNw)[names(TDNw) %in% names(TD)]
if (length(dupTrials) > 0) {
warning("The following trials already existed in TD and will be added ",
"again: ", paste(dupTrials, collapse = ", "), ".\n", call. = FALSE)
}
TDTot <- c(TD, TDNw)
class(TDTot) <- c("TD", "list")
return(TDTot)
}
dropTD <- function(TD,
rmTrials) {
naTrials <- rmTrials[!rmTrials %in% names(TD)]
if (length(naTrials) > 0) {
warning("The following trials are not in TD: ",
paste(naTrials, collapse = ", "), ".\n", call. = FALSE)
}
leftTrials <- names(TD)[!names(TD) %in% rmTrials]
if (length(leftTrials) == 0) {
warning("All trials have been removed from TD.\n", call. = FALSE)
}
return(TD[!names(TD) %in% rmTrials])
}
summary.TD <- function(object,
...,
trial = names(object),
traits,
groupBy = NULL,
what = if (!is.null(groupBy)) {
c("nObs", "mean", "sd")
} else {
c("nObs", "nMiss", "mean", "median", "min", "max",
"firstQ", "thirdQ", "var")
}) {
allStat <- data.frame(stat = c("nVals", "nObs", "nMiss", "mean", "median",
"min","max", "range", "firstQ", "thirdQ", "sd",
"seMean", "var", "seVar", "CV", "sum", "sumSq",
"uncorSumSq", "skew", "seSkew", "kurt",
"seKurt"),
name = c("Number of values", "Number of observations",
"Number of missing values", "Mean", "Median",
"Min", "Max", "Range", "First quantile",
"Third quantile", "Standard deviation",
"Standard error of mean", "Variance",
"Standard error of variance",
"Coefficient of variation", "Sum of values",
"Sum of squares", "Uncorrected sum of squares",
"Skewness", "Standard Error of Skewness",
"Kurtosis", "Standard Error of Kurtosis"),
stringsAsFactors = FALSE)
if (!is.character(trial) || length(trial) > 1 ||
!hasName(x = object, name = trial)) {
stop("trial should be a single character string in ",
deparse(substitute(object)), ".\n")
}
trDat <- object[[trial]]
if (!is.character(traits) || !all(hasName(x = trDat, name = traits))) {
stop("All traits should be columns in trial.\n")
}
if (!is.null(groupBy) && (!is.character(groupBy) || length(groupBy) > 1 ||
!hasName(x = trDat, name = groupBy))) {
stop("groupBy should be a single character string indicating ",
"a column in trial")
}
if (what[[1]] == "all") {
what <- allStat[["stat"]]
}
if (!is.character(what) || all(!what %in% allStat[["stat"]])) {
stop("At least one statistic should be chosen.\n")
}
whichStat <- which(allStat[["stat"]] %in% what)
what <- allStat[whichStat, "stat"]
if (!is.null(groupBy)) {
groups <- unique(trDat[[groupBy]])
} else {
trDat[[".tot"]] <- 1
groupBy <- ".tot"
groups <- 1
}
stats <- array(dim = c(length(what), length(traits), length(groups)),
dimnames = list(what, traits, groups))
for (i in seq_along(traits)) {
for (j in seq_along(groups)) {
trDatGr <- trDat[trDat[[groupBy]] == groups[j], traits[i]]
if ("nVals" %in% what) {
stats["nVals", i, j] <- length(trDatGr)
}
if ("nObs" %in% what) {
stats["nObs", i, j] <- length(na.omit(trDatGr))
}
if ("nMiss" %in% what) {
stats["nMiss", i, j] <- sum(is.na(trDatGr))
}
if ("mean" %in% what) {
stats["mean", i, j] <- mean(trDatGr, na.rm = TRUE)
}
if ("median" %in% what) {
stats["median", i, j] <- median(trDatGr, na.rm = TRUE)
}
if ("min" %in% what) {
stats["min", i, j] <- min(trDatGr, na.rm = TRUE)
}
if ("max" %in% what) {
stats["max", i, j] <- max(trDatGr, na.rm = TRUE)
}
if ("range" %in% what) {
stats["range", i, j] <- diff(range(trDatGr, na.rm = TRUE))
}
if ("firstQ" %in% what) {
stats["firstQ", i, j] <- quantile(trDatGr, prob = .25, na.rm = TRUE)
}
if ("thirdQ" %in% what) {
stats["thirdQ", i, j] <- quantile(trDatGr, prob = .75, na.rm = TRUE)
}
if ("sd" %in% what) {
stats["sd", i, j] <- sd(trDatGr, na.rm = TRUE)
}
if ("seMean" %in% what) {
stats["seMean", i, j] <- sd(trDatGr, na.rm = TRUE) /
sqrt(length(na.omit(trDatGr)))
}
if ("var" %in% what) {
stats["var", i, j] <- var(trDatGr, na.rm = TRUE)
}
if ("seVar" %in% what) {
stats["seVar", i, j] <- seVar(trDatGr, na.rm = TRUE)
}
if ("CV" %in% what) {
stats["CV", i, j] <- 100 * sd(trDatGr, na.rm = TRUE) /
mean(trDatGr, na.rm = TRUE)
}
if ("sum" %in% what) {
stats["sum", i, j] <- sum(trDatGr, na.rm = TRUE)
}
if ("sumSq" %in% what) {
stats["sumSq", i, j] <- sum((na.omit(trDatGr) -
mean(trDatGr, na.rm = TRUE)) ^ 2)
}
if ("uncorSumSq" %in% what) {
stats["uncorSumSq", i, j] <- sum(trDatGr ^ 2, na.rm = TRUE)
}
if ("skew" %in% what) {
stats["skew", i, j] <- skewness(trDatGr, na.rm = TRUE)
}
if ("seSkew" %in% what) {
stats["seSkew", i, j] <- seSkewness(length(na.omit(trDatGr)))
}
if ("kurt" %in% what) {
stats["kurt", i, j] <- kurtosis(trDatGr, na.rm = TRUE)
}
if ("seKurt" %in% what) {
stats["seKurt", i, j] <- seKurtosis(length(na.omit(trDatGr)))
}
}
}
rownames(stats) <- allStat[whichStat, "name"]
attr(x = stats, which = "whichStat") <- whichStat
return(structure(stats,
class = c("summary.TD", "array"),
trial = trial,
group = if (groupBy != ".tot") groupBy else NULL))
}
print.summary.TD <- function(x,
...) {
whichStat <- attr(x, "whichStat")
groupBy <- attr(x, "group")
decimals <- c(rep(x = 1, times = 3), rep(x = 2, times = 7),
rep(x = 3, times = 5), rep(x = 2, times = 3),
rep(x = 3, times = 4))[whichStat]
xPrint <- x
for (i in seq_along(decimals)) {
xPrint[i, , ] <- format(x[i, , ], digits = decimals[i],
nsmall = decimals[i])
}
for (i in 1:ncol(xPrint)) {
trait <- colnames(xPrint)[i]
cat(paste("\nSummary statistics for", trait, "in", attr(x, "trial"),
if (!is.null(groupBy)) paste("grouped by", groupBy), "\n\n"))
if (dim(xPrint)[3] > 1) {
xPrintM <- matrix(nrow = nrow(xPrint), ncol = dim(xPrint)[3])
for (j in 1:nrow(xPrint)) {
xPrintM[j, ] <- xPrint[j, i, ]
}
dimnames(xPrintM) <- list(rownames(xPrint), dimnames(xPrint)[[3]])
print(xPrintM, quote = FALSE, right = TRUE)
} else {
xPrintM <- as.matrix(xPrint[, i , 1])
dimnames(xPrintM) <- list(rownames(xPrint), trait)
print(xPrintM, quote = FALSE, right = TRUE)
}
}
cat("\n")
}
plot.TD <- function(x,
...,
plotType = c("layout", "map", "box", "cor", "scatter"),
trials = names(x),
traits = NULL,
title = NULL,
output = TRUE) {
trials <- chkTrials(trials, x)
plotType <- match.arg(plotType)
chkChar(title, len = 1)
dotArgs <- list(...)
x <- dropTD(x, names(x)[!names(x) %in% trials])
if (plotType == "layout") {
p <- layoutPlot(x = x, trials = trials, traits = traits, title = title,
output = output, ...)
} else if (plotType == "map") {
p <- mapPlot(x = x, title = title, output = output, ...)
} else if (plotType == "box") {
p <- boxPlot(x = x, trials = trials, traits = traits, title = title,
output = output, ...)
} else if (plotType == "cor") {
p <- corPlot(x = x, trials = trials, traits = traits, title = title,
output = output, ...)
} else if (plotType == "scatter") {
p <- scatterPlot(x = x, trials = trials, traits = traits, title = title,
output = output, ...)
}
invisible(p)
}
getMeta <- function(TD) {
if (missing(TD) || !inherits(TD, "TD")) {
stop("TD should be an object of class TD.\n")
}
metaVars <- c("trLocation", "trDate", "trDesign", "trLat", "trLong",
"trPlWidth", "trPlLength")
meta <- as.data.frame(matrix(nrow = length(TD), ncol = length(metaVars),
dimnames = list(names(TD), metaVars)))
for (mv in metaVars) {
meta[mv] <- sapply(X = TD, FUN = function(tr) {
mvTr <- attr(tr, which = mv)
if (!is.null(mvTr)) {
return(mvTr)
} else {
return(NA)
}
})
}
class(meta$trDate) <- "Date"
return(meta)
}
setMeta <- function(TD,
meta) {
if (missing(TD) || !inherits(TD, "TD")) {
stop("TD should be an object of class TD.\n")
}
if (missing(meta) || !inherits(meta, "data.frame")) {
stop("meta should be a data.frame.\n")
}
naTr <- rownames(meta)[!rownames(meta) %in% names(TD)]
if (length(naTr) > 0) {
warning("The following trials in meta are not in TD: ",
paste(naTr, collapse = ", "), ".\n", call. = FALSE)
}
metaVars <- c("trLocation", "trDate", "trDesign", "trLat", "trLong",
"trPlWidth", "trPlLength")
for (tr in rownames(meta)[rownames(meta) %in% names(TD)]) {
for (mv in metaVars) {
mvTr <- meta[tr, mv]
if (!is.na(mvTr)) {
chk <- try(do.call(what = checkTDMeta, args = setNames(list(mvTr), mv)),
silent = TRUE)
if (inherits(chk, "try-error")) {
stop("\nError for ", tr, ":\n", substring(text = chk, first = 9))
}
attr(TD[[tr]], which = mv) <- mvTr
}
}
}
return(TD)
}
`[.TD` <- function(x, i, ...) {
r <- NextMethod("[")
attr(r, "class") <- attr(x, "class")
return(r)
}
c.TD <- function(...) {
args <- list(...)
args <- lapply(X = args, FUN = unclass)
argNames <- unique(unlist(lapply(X = args, FUN = names)))
r <- do.call("c", args)
r <- lapply(X = r, FUN = function(trial) {
trial[["trial"]] <- factor(trial[["trial"]], levels = argNames)
return(trial)
})
class(r) <- c("TD", "list")
return(r)
}
checkTDMeta <- function(trLocation = NULL,
trDate = NULL,
trDesign = NULL,
trLat = NULL,
trLong = NULL,
trPlWidth = NULL,
trPlLength = NULL) {
chkDesign(trDesign)
chkLatLong(trLat, trLong)
if (!is.null(trPlWidth) && (!is.numeric(trPlWidth) || any(trPlWidth < 0))) {
stop("trPlWidth should be a positive numerical vector.\n", call. = FALSE)
}
if (!is.null(trPlLength) && (!is.numeric(trPlLength) || any(trPlLength < 0))) {
stop("trPlLength should be a positive numerical vector.\n", call. = FALSE)
}
}
chkDesign <- function(design) {
match.arg(design, choices = c("none", "ibd", "res.ibd", "rcbd", "rowcol",
"res.rowcol"),
several.ok = TRUE)
}
chkLatLong <- function(lat,
long) {
if (!is.null(lat) && !is.na(lat) &&
(!is.numeric(lat) || any(abs(lat) > 90))) {
stop("lat should be a numerical vector with values between -90 and 90.\n",
call. = FALSE)
}
if (!is.null(long) && !is.na(long) &&
(!is.numeric(long) || any(abs(long) > 180))) {
stop("long should be a numerical vector with values between -180 and 180.\n",
call. = FALSE)
}
if (!is.null(lat) && !is.na(lat) && !is.null(long) && !is.na(long)) {
locLen <- max(length(lat), length(long))
loc <- maps::map.where(x = rep(x = long, length.out = locLen),
y = rep(x = lat, length.out = locLen))
if (length(loc) > 0 && anyNA(loc)) {
warning("Values for latitude and longitude should all match a known ",
"land location.\n", call. = FALSE)
}
}
} |
Inf.Array.calc1 <- function(p, Se, Sp, group.sz, alpha = 2, a,
trace = TRUE, print.time = TRUE, ...) {
start.time <- proc.time()
I <- group.sz
N <- I^2
if (length(p) == 1) {
p.vec <- expectOrderBeta(p = p, alpha = alpha, size = N, ...)
} else if (length(p) > 1) {
p.vec <- sort(p)
alpha <- NA
}
p.ga <- informativeArrayProb(prob.vec = p.vec, nr = I, nc = I,
method = "gd")
save.info <- Array.Measures(p = p.ga, se = Se, sp = Sp)
ET <- save.info$ET
all.ind.testerror <- data.frame("p" = as.numeric(t(p.ga)),
"pse.vec" = as.numeric(t(save.info$PSe)),
"psp.vec" = as.numeric(t(save.info$PSp)),
"pppv.vec" = as.numeric(t(save.info$PPV)),
"pnpv.vec" = as.numeric(t(save.info$NPV)))
ind.testerror <- get.unique.index(all.ind.testerror[a,],
which(colnames(all.ind.testerror) == "psp.vec"),
rowlabel = a)[,-1]
colnames(ind.testerror) <- c("PSe", "PSP", "PPPV", "PNPV", "individuals")
PSe.mat <- save.info$PSe
PSp.mat <- save.info$PSp
PSe <- sum(p.ga * PSe.mat) / sum(p.ga)
PSp <- sum((1 - p.ga) * (PSp.mat)) / sum(1 - p.ga)
PPPV <- sum(p.ga * PSe.mat) / sum(p.ga * PSe.mat +
(1 - p.ga) * (1 - PSp.mat))
PNPV <- sum((1 - p.ga) * PSp.mat) / sum((1 - p.ga) * PSp.mat +
p.ga * (1 - PSe.mat))
save.it <- c(alpha, I, N, ET, ET/N, PSe, PSp, PPPV, PNPV)
acc.ET <- matrix(data = save.it[6:9], nrow = 1, ncol = 4,
dimnames = list(NULL, c("PSe", "PSp", "PPPV", "PNPV")))
Se.display <- matrix(data = Se, nrow = 1, ncol = 2,
dimnames = list(NULL, "Test" = c("Row/Column",
"Individual")))
Sp.display <- matrix(data = Sp, nrow = 1, ncol = 2,
dimnames = list(NULL, "Test" = c("Row/Column",
"Individual")))
if (print.time) {
time.it(start.time)
}
list("algorithm" = "Informative array testing without master pooling",
"prob" = list(p), "alpha" = alpha, "Se" = Se.display, "Sp" = Sp.display,
"Config" = list("Array.dim" = save.it[2], "Array.sz" = save.it[3]),
"p.mat" = p.ga, "ET" = save.it[4], "value" = save.it[5],
"Accuracy" = list("Individual" = ind.testerror, "Overall" = acc.ET))
} |
design_ccd <- function(j, k) {
MinStarPoints <- matrix(NA, nrow = 1, ncol = k)
MaxStarPoints <- matrix(NA, nrow = 1, ncol = k)
CentrePoints <- matrix(NA, nrow = 1, ncol = k)
AlphaPoints <- matrix(NA, nrow = 1, ncol = k)
MinusLambdaPoints <- matrix(NA, nrow = 1, ncol = k)
PlusLambdaPoints <- matrix(NA, nrow = 1, ncol = k)
for (i in 1:k) {
prompt1 <- paste("What is the smallest value of factor ", i, "? ", sep = "")
prompt2 <- paste("What is the greatest value of factor ", i, "? ", sep = "")
minval <- readline(prompt1)
maxval <- readline(prompt2)
MinStarPoints[1, i] <- as.numeric(minval)
MaxStarPoints[1, i] <- as.numeric(maxval)
CentrePoints[1, i] <- (MinStarPoints[1, i] + MaxStarPoints[1, i]) / 2
AlphaPoints[1, i] <- abs(MaxStarPoints[1, i] - MinStarPoints[1, i]) / (2 * 2^(k / 4))
PlusLambdaPoints[1, i] <- CentrePoints[1, i] + AlphaPoints[1, i]
MinusLambdaPoints[1, i] <- CentrePoints[1, i] - AlphaPoints[1, i]
}
FactorialDesign <- MinusLambdaPoints
for (i in 1:k) {
FactorialDesign2 <- FactorialDesign
FactorialDesign <- rbind(FactorialDesign, FactorialDesign2)
FactorialDesign[(2^(i - 1) + 1): 2^i, i] <- PlusLambdaPoints[1, i]
}
headings <- c("Replication")
for (i in 1: k) {
headings <- c(headings, paste("Factor", i, sep = ""))
}
ones <- matrix(1, nrow = 2^k, ncol = 1)
ones <- as.data.frame(ones)
FactorialDesign <- cbind(ones, FactorialDesign)
colnames(FactorialDesign) <- headings
AxialDesign <- matrix(NA, nrow = (2 * k), ncol = k)
for (i in 1:k) {
AxialDesign1 <- CentrePoints
AxialDesign1[1, i] <- MinStarPoints[1, i]
AxialDesign2 <- CentrePoints
AxialDesign2[1, i] <- MaxStarPoints[1, i]
AxialDesign[(2 * i - 1), 1: k] <- AxialDesign1
AxialDesign[(2 * i), 1: k] <- AxialDesign2
}
AxialOnes <- matrix(1, ncol = 1, nrow = 2*k)
AxialOnes <- as.data.frame(AxialOnes)
AxialDesign <- cbind(AxialOnes, AxialDesign)
colnames(AxialDesign) <- headings
CentreDesign <- as.data.frame(cbind(j, CentrePoints))
colnames(CentreDesign) <- headings
CentreRows <- CentrePoints
for (i in 1:j) {
row2 <- CentrePoints
CentreRows <- rbind(CentreRows, row2)
}
CentreRows <- CentreRows[-nrow(CentreRows),]
CentreRows<- as.data.frame(cbind(1, CentreRows))
colnames(CentreRows) <- headings
X <- as.matrix(rbind(FactorialDesign[1:nrow(FactorialDesign), 1:3], AxialDesign[1:nrow(AxialDesign), 1:3], CentreRows[1:nrow(CentreRows), 1:3]))
X <- cbind(X, matrix(NA, nrow(X), 3))
for (i in 1:nrow(X)) {
X[i, 4] <- X[i, 2]^2
X[i, 5] <- X[i, 3]^2
X[i, 6] <- X[i, 2] * X[i, 3]
}
BIGX <- matrix(NA, 1, 6)
for (i in seq(min(X[1:nrow(X), 2]), max(X[1:nrow(X), 2]), 0.1)) {
newrow <- matrix(NA, 1, 6)
for (o in seq(min(X[1:nrow(X), 3]), max(X[1:nrow(X), 3]), 0.1)) {
newrow[1, 1] <- 1
newrow[1, 2] <- i
newrow[1, 3] <- o
newrow[1, 4] <- i * i
newrow[1, 5] <- o * o
newrow[1, 6] <- i * o
BIGX <- rbind(BIGX, newrow)
}
}
BIGX <- BIGX[2:nrow(BIGX), 1:6]
Factor1 <- BIGX[1:nrow(BIGX), 2]
Factor2 <- BIGX[1:nrow(BIGX), 3]
A <- solve(crossprod(X))
Predicted_Variance <- matrix(NA, nrow(BIGX), 1)
for (i in 1:nrow(BIGX)) {
b <- BIGX[i, 1:6]
Predicted_Variance[i, 1] <- t(b) %*% A %*% b
}
if (k == '2') {
ForPlot <- as.data.frame(cbind(Factor1, Factor2, Predicted_Variance))
colnames(ForPlot) <- c("Factor1", "Factor2", "Predicted_Variance")
p <- plotly::plot_ly(ForPlot,
x = ~Factor1,
y = ~Factor2,
z = ~Predicted_Variance,
type = "contour",
colorscale = "Portland",
contours = list(
showlabels = TRUE),
line = list(smoothing = 0)
)
print(p)
}
list(Factorial.Points = FactorialDesign,
Axial.Points = AxialDesign,
Central.Point = CentreDesign)
} |
do.anmm <- function(X, label, ndim=2, preprocess=c("null","center","scale","cscale","decorrelate","whiten"),
No=ceiling(nrow(X)/10), Ne=ceiling(nrow(X)/10)){
aux.typecheck(X)
n = nrow(X)
p = ncol(X)
label = check_label(label, n)
ulabel = unique(label)
for (i in 1:length(ulabel)){
if (sum(label==ulabel[i])==1){
stop("* do.anmm : no degerate class of size 1 is allowed.")
}
}
if (any(is.na(label))||(any(is.infinite(label)))){
stop("* Supervised Learning : any element of 'label' as NA or Inf will simply be considered as a class, not missing entries.")
}
ndim = as.integer(ndim)
if (!check_ndim(ndim,p)){
stop("* do.anmm : 'ndim' is a positive integer in [1,
}
algpreprocess = match.arg(preprocess)
vecNo = anmm_nbdstructure(No, n, 1)
vecNe = anmm_nbdstructure(Ne, n, 2)
tmplist = aux.preprocess.hidden(X,type=algpreprocess,algtype="linear")
trfinfo = tmplist$info
pX = tmplist$pX
D = as.matrix(dist(pX, method="euclidean"))
listNo = anmm_find_No(D, label, vecNo)
listNe = anmm_find_Ne(D, label, vecNe)
S = anmm_computeSC(pX, listNe)
C = anmm_computeSC(pX, listNo)
eigSC = RSpectra::eigs_sym(S-C, ndim, which="LA")
projection = matrix(eigSC$vectors, nrow=p)
projection = aux.adjprojection(projection)
result = list()
result$Y = pX%*%projection
result$trfinfo = trfinfo
result$projection = projection
return(result)
}
anmm_nbdstructure <- function(sizevec, n, Ntype){
tmp = as.vector(round(sizevec))
if (length(tmp)==1){
nbdvec = rep(tmp, n)
} else if (length(tmp)==n){
nbdvec = tmp
} else {
if (Ntype==1){
stop("* do.anmm : homogeneous neighborhood input is invalid.")
} else {
stop("* do.anmm : heterogeneous neighborhood input is invalid.")
}
}
if ((any(nbdvec<1))||(any(nbdvec>n))){
if (Ntype==1){
stop("* do.anmm : range of values from No is invalid.")
} else {
stop("* do.anmm : range of values from Ne is invalid.")
}
}
return(nbdvec)
}
anmm_find_No <- function(matD, label, vecNo){
n = length(label)
if (nrow(matD)!=n){stop("* do.anmm : I don't know why it stopped 1.")}
output = list()
numNo = rep(0,n)
for (i in 1:n){
clabel = which(label==label[i])
nclabel = sum(label==label[i])
nselect = round(min(nclabel, vecNo[i]))
numNo[i]= nselect
tgtdist = matD[i,clabel]
smindex = which(order(tgtdist)<=(nselect+1))
tgtlabel = setdiff(clabel[smindex], round(i))
output[[i]] = tgtlabel
}
return(output)
}
anmm_find_Ne <- function(matD, label, vecNe){
n = length(label)
if (nrow(matD)!=n){stop("* do.anmm : I don't know why it stopped 2.")}
output = list()
numNe = rep(0,n)
for (i in 1:n){
clabel = which(label!=label[i])
nclabel = length(clabel)
nselect = round(min(nclabel, vecNe[i]))
numNe[i]= nselect
tgtdist = matD[i,clabel]
smindex = which(order(tgtdist)<=(nselect+1))
tgtlabel= setdiff(clabel[smindex], round(i))
output[[i]] = tgtlabel
}
return(output)
}
anmm_computeSC <- function(X, memlist){
n = nrow(X)
p = ncol(X)
S = array(0, c(p,p))
for (i in 1:n){
xi = as.vector(X[i,])
tgtvecs = memlist[[i]]
tgtsize = length(tgtvecs)
Stmp = array(0,c(p,p))
for (k in 1:tgtsize){
xk = as.vector(X[tgtvecs[k],])
xdiff= xi-xk
Stmp = Stmp + outer(xdiff,xdiff)
}
Stmp = Stmp/tgtsize
S = S + Stmp
}
return(S)
} |
ubSMOTE <-
function(X,Y,perc.over=200,k=5,perc.under=200,verbose=TRUE){
if(!is.factor(Y))
stop("Y has to be a factor")
if(is.vector(X))
stop("X cannot be a vector")
data<-cbind(X,Y)
id.1 <- which(Y == 1)
time<-system.time({
newExs <- ubSmoteExs(data[id.1,],"Y",perc.over,k)
})
row.has.na<-function(X)
return(apply(X,1,function(x){any(is.na(x))}))
row.is.na<-row.has.na(newExs)
if(any(row.is.na)) {
newExs<-newExs[!row.is.na, ]
colnames(newExs)<-colnames(data)
cat("WARNING: NAs generated by SMOTE removed \n")
}
selMaj <- sample((1:NROW(data))[-id.1],
as.integer((perc.under/100)*nrow(newExs)),
replace=T)
newdataset <- rbind(data[selMaj,],data[id.1,],newExs)
newdataset<-newdataset[sample(1:NROW(newdataset)), ]
X<-newdataset[ ,-ncol(newdataset)]
Y<-newdataset[ ,ncol(newdataset)]
return(list(X=X,Y=Y))
} |
check_family <-
function(family, ...){
if (is.character(family))
family <- get(family, mode = "function", envir = parent.frame())
if (is.function(family))
family <- family()
if (is.null(family$family)) {
print(family)
stop("'family' not recognized")
}
if(family$family == "gaussian"){
family$logLik <- function(y, n, mu, wt, dev){
nobs <- length(y)
0.5 * (sum(log(wt)) - nobs * (log(dev/nobs * 2 * pi) + 1))
}
family$canpar <- function(mu){
mu
}
family$cumulant <- function(mu){
mu^2/2
}
} else if(family$family == "binomial"){
family$logLik <- function(y, n, mu, wt, dev){
m <- if (any(n > 1))
n
else wt
ifelse(m > 0, (wt/m), 0) * dbinom(round(m * y), round(m), mu, log = TRUE)
}
family$canpar <- function(mu){
log(mu / (1 - mu))
}
family$cumulant <- function(mu){
-log(1 - mu)
}
} else if(family$family == "poisson"){
family$logLik <- function(y, n, mu, wt, dev){
dpois(y, mu, log = TRUE) * wt
}
family$canpar <- function(mu){
log(mu)
}
family$cumulant <- function(mu){
mu
}
} else if(family$family == "Gamma"){
family$logLik <- function(y, n, mu, wt, dev){
disp <- dev / sum(wt)
dgamma(y, 1/disp, scale = mu * disp, log = TRUE) * wt
}
family$canpar <- function(mu){
-1/mu
}
family$cumulant <- function(mu){
log(mu)
}
} else if(family$family == "inverse.gaussian"){
family$logLik <- function(y, n, mu, wt, dev){
disp <- dev / sum(wt)
-(1/2) * wt * (log(disp * 2 * pi) + 1 + 3 * log(y))
}
family$canpar <- function(mu){
-1/mu^2
}
family$cumulant <- function(mu){
-2/mu
}
} else if(!family$family == "NegBin"){
stop("'family' not recognized")
}
family
} |
context("Targets")
test_that("Targets return their output on build", {
cleanup()
m <- remake("remake.yml")
store <- m$store
t <- m$targets[["data.csv"]]
expect_equal(target_build(t, store), "data.csv")
remake_remove_target(m, "data.csv")
expect_equal(remake_update(m, "data.csv"), "data.csv")
expect_equal(remake_update(m, "data.csv"), "data.csv")
remake_remove_target(m, "data.csv")
expect_equal(remake_make(m, "data.csv"), "data.csv")
expect_equal(remake_make(m, "data.csv"), "data.csv")
t <- m$targets[["processed"]]
expect_is(target_build(t, store), "data.frame")
remake_remove_target(m, "processed")
expect_is(remake_update(m, "processed"), "data.frame")
expect_is(remake_update(m, "processed"), "data.frame")
remake_remove_target(m, "processed")
expect_is(remake_make(m, "processed"), "data.frame")
expect_is(remake_make(m, "processed"), "data.frame")
t <- m$targets[["all"]]
expect_null(target_build(t, store))
expect_error(remake_remove_target(m, "all"),
"Not something that can be deleted")
expect_null(remake_update(m, "all"))
expect_null(remake_update(m, "all"))
expect_error(remake_remove_target(m, "all"),
"Not something that can be deleted")
expect_null(remake_make(m, "all"))
expect_null(remake_make(m, "all"))
}) |
library(GEOquery)
library(illuminaHumanv3.db)
library(stringr)
library(biomaRt)
library(MatrixEQTL)
library(org.Hs.eg.db)
library(clusterProfiler)
library("BSgenome.Hsapiens.UCSC.hg19")
library(fssemR)
library(igraph)
library(limma)
library(synbreed)
library(gage)
library(httr)
library(XML)
gse1 =
GEOquery:::parseGSEMatrix(
"/media/xinchou/Storage/SMLfl/exp/GSE29999-GPL6947_series_matrix.txt.gz",
destdir = "exp",
AnnotGPL = FALSE,
getGPL = F
)
gse2 =
GEOquery:::parseGSEMatrix(
"/media/xinchou/Storage/SMLfl/exp/GSE29999-GPL6801_series_matrix.txt.gz",
destdir = "exp",
AnnotGPL = FALSE,
getGPL = F
)
Exprdat = read.ilmn(files = "/media/xinchou/Storage/SMLfl/exp/GSE29998_non-normalized.txt", probeid = "ID_REF",
expr = "AVG_Signal")
title2GSM = as.character(gse1$eset@phenoData@data$geo_accession)
names(title2GSM) = as.character(gse1$eset@phenoData@data$title)
colnames(Exprdat) = title2GSM[colnames(Exprdat)]
ExprNorm = neqc(Exprdat)
addrIllumina = toTable(illuminaHumanv3ARRAYADDRESS)[, c("ArrayAddress", "IlluminaID")]
colnames(addrIllumina) = c("ArrayAddrID", "IlluminaID_1")
illuminaToSymbol = toTable(illuminaHumanv3ENTREZREANNOTATED)
addrToSymbol = merge(addrIllumina, illuminaToSymbol, by.x="IlluminaID_1", by.y="IlluminaID")
addrToLocation = toTable(illuminaHumanv3ENSEMBLREANNOTATED)
addrToLocation = merge(addrIllumina, addrToLocation, by.x="IlluminaID_1", by.y="IlluminaID")
rownames(addrToLocation) = addrToLocation$IlluminaID_1
expressedProbe = rowSums(ExprNorm$other$Detection < 0.05) > 2
Exprvarmat = ExprNorm$E[expressedProbe,]
exprIllumina = intersect(rownames(Exprvarmat), rownames(addrToLocation))
Exprvarmat = Exprvarmat[exprIllumina,]
rownames(Exprvarmat) = addrToLocation[rownames(Exprvarmat), 3]
SNPlib = read.csv(
"/media/xinchou/Storage/SMLfl/exp/GenomeWideSNP_6.na29.annot.csv",
comment.char = "
sep = ",",
stringsAsFactors = F
)
SNPlib = SNPlib[SNPlib[,3] != "---" & SNPlib[,4] != "---",]
SNPmap = SNPlib[, c(2, 3, 4)]
SNPmap = unique(SNPmap)
rownames(SNPmap) = SNPmap[,1]
SNPhash = SNPlib[, 2]
names(SNPhash) = SNPlib[, 1]
SNPhash = SNPhash[!duplicated(SNPhash)]
SNPvarmat = gse2$eset@assayData$exprs
SNPID = rownames(SNPvarmat)
FilterSNP = intersect(SNPID, names(SNPhash))
SNPvarmat = SNPvarmat[FilterSNP, , drop = F]
snpnames = SNPhash[rownames(SNPvarmat)]
names(snpnames) = NULL
rownames(SNPvarmat) = snpnames
SNPvarmat[SNPvarmat == "NoCall" | SNPvarmat == "NC"] = NA
SNPvarmat = t(SNPvarmat)
SNPmap = SNPmap[colnames(SNPvarmat),c(2,3)]
colnames(SNPmap) = c("chr", "pos")
SNPmap[,2] = as.numeric(SNPmap[,2])
PData2 = phenoData(gse2$eset)
SNPPheno = PData2@data[rownames(SNPvarmat), 10, drop = F]
SNPPheno[,1] = as.numeric(SNPPheno[,1]) - 1
colnames(SNPPheno) = c("Status")
SNPData = create.gpData(pheno = SNPPheno, geno = SNPvarmat, map = SNPmap, map.unit = "bp")
SNPImputed = readRDS("./data2/ImputedSNP.rds")
ImputeData = SNPImputed$geno
RawData = SNPData$geno[,colnames(ImputeData)]
RawData[RawData == "AA"] = "0"
RawData[RawData == "AB"] = "1"
RawData[RawData == "BB"] = "2"
mode(ImputeData) = "character"
for (i in 1:ncol(RawData)) {
genomap = na.omit(unique(cbind(ImputeData[,i], RawData[,i])))
t = genomap[,2]
names(t) = genomap[,1]
ImputeData[,i] = t[ImputeData[,i]]
}
mode(ImputeData) = "numeric"
SNPvarmat = t(ImputeData)
PData1 = phenoData(gse1$eset)
PData2 = phenoData(gse2$eset)
sampidGE = as.character(PData1@data$source_name_ch1)
sampidSNP = as.character(PData2@data$source_name_ch1)
sampleID = setdiff(intersect(sampidGE, sampidSNP), "08259T2")
GEix = sapply(sampleID, function(id) {
which(sampidGE == id)
})
SNPix = sapply(sampleID, function(id) {
which(sampidSNP == id)
})
Exprvarmat = Exprvarmat[, GEix, drop = F]
SNPvarmat = SNPvarmat[, SNPix, drop = F]
Libensembl = useDataset("hsapiens_gene_ensembl", mart = useMart("ensembl"))
GeneLocation = getBM(
attributes = c(
"ensembl_gene_id",
"chromosome_name",
"start_position",
"end_position"
),
mart = Libensembl
)
Libid = bitr(
rownames(Exprvarmat),
fromType = "ENSEMBL",
toType = "SYMBOL",
OrgDb = "org.Hs.eg.db"
)
ensembl2id = Libid$SYMBOL
names(ensembl2id) = Libid$ENSEMBL
GeneLocation = GeneLocation[GeneLocation$ensembl_gene_id %in% names(ensembl2id), , drop = F]
GeneLocation = GeneLocation[complete.cases(GeneLocation), , drop = F]
GeneLocation = unique(GeneLocation)
geneExprData1 = Exprvarmat[as.character(unique(GeneLocation$ensembl_gene_id)), , drop = F]
Exprmat = SlicedData$new()
colnames(geneExprData1) = NULL
Exprmat$initialize(geneExprData1)
SNPmat = SlicedData$new()
SNPvarmat1 = SNPvarmat
colnames(SNPvarmat1) = NULL
SNPmat$initialize(SNPvarmat1)
GeneLoc = GeneLocation[as.character(GeneLocation$ensembl_gene_id) %in% rownames(geneExprData1), ]
GeneLoc = GeneLoc[, c(1, 2, 3, 4)]
colnames(GeneLoc) = c("geneid", "chr", "left", "right")
rownames(GeneLoc) = NULL
SNPLoc = data.frame(SNPlib[,c(2, 3, 4)])
SNPLoc[,3] = as.numeric(SNPLoc[,3])
SNPLoc = SNPLoc[complete.cases(SNPLoc), , drop = F]
SNPLoc = unique(SNPLoc)
colnames(SNPLoc) = c("snpid", "chr", "pos")
SNPLoc = SNPLoc[SNPLoc$snpid %in% rownames(SNPmat),]
Covariates = NULL
PData = PData1@data[colnames(Exprvarmat), ]
Status = as.character(PData$characteristics_ch1)
Status[Status == "tissue: Tumor"] = "tumor"
Status[Status != "tumor"] = "normal"
Covariates = rbind(Covariates,
status = ifelse(Status == "normal", 0, 1))
Covmat = SlicedData$new()
Covmat$initialize(Covariates)
SNPInfo = SNPvarmat1[SNPLoc$snpid[SNPLoc$chr %in% c(as.character(seq(1,22)), "X", "Y", "MT")], ]
SNPS = data.frame(id = rownames(SNPInfo), SNPInfo)
colnames(SNPS) = c("id", paste("Sample_", seq(1, ncol(SNPInfo)), sep=""))
write.table(SNPS, "./data2/SNP.txt", quote = F, row.names = F, col.names = TRUE, sep = "\t")
GE = data.frame(id = rownames(geneExprData1), geneExprData1)
colnames(GE) = c("id", paste("Sample_", seq(1, ncol(Exprvarmat)), sep=""))
write.table(GE, "./data2/GE.txt", quote = F, row.names = F, col.names = TRUE, sep = "\t")
COV = data.frame(id = rownames(Covariates), Covariates)
colnames(COV) = c("id", paste("Sample_", seq(1, ncol(Covariates)), sep=""))
write.table(COV, "./data2/Covariates.txt", quote = F, row.names = F, col.names = TRUE, sep = "\t")
saveRDS(SNPLoc, "./data2/SNP.rds")
saveRDS(GeneLoc, "./data2/GE.rds")
cis_eQTL = read.csv("./data2/cis_eQTL_results_R.txt", sep = "\t", stringsAsFactors = F)
Normal = which(Status == "normal")
Tumor = which(Status == "tumor")
FilterByMAF = apply(SNPvarmat, 1, function(x) {
MAF_N = min(c(sum(x[Normal] == 0), sum(x[Normal] == 1), sum(x[Normal] == 2))) / length(Normal)
MAF_T = min(c(sum(x[Tumor] == 0), sum(x[Tumor] == 1), sum(x[Tumor] == 2))) / length(Tumor)
(MAF_N > 0.05 & MAF_T > 0.05)
})
SNPFilterByMAF = names(which(FilterByMAF))
Significant_eQTLs = cis_eQTL[(cis_eQTL$FDR < 0.01 & cis_eQTL$SNP %in% SNPFilterByMAF), , drop = F]
Gene2eQTL = split(Significant_eQTLs$SNP, Significant_eQTLs$gene)
center = function(X) {
apply(X, 1, function(x) {
x - mean(x)
})
}
eQTLRank = lapply(Gene2eQTL, function(g) {
t = unique(SNPvarmat[g, Tumor, drop = F])
n = unique(SNPvarmat[g, Normal, drop = F])
min(qr(crossprod(center(t)))$rank, qr(crossprod(center(n)))$rank)
})
Gene2eQTL2 = Gene2eQTL
for (i in 1:length(Gene2eQTL)) {
FDR = NULL
g = as.numeric(names(Gene2eQTL[i]))
for (s in Gene2eQTL[[i]]) {
FDR = c(FDR, Significant_eQTLs[Significant_eQTLs$SNP == s & Significant_eQTLs$gene == g, 6])
}
if (eQTLRank[[i]] != 0) {
Gene2eQTL[[i]] = Gene2eQTL[[i]][which.min(FDR)]
} else {
Gene2eQTL[[i]] = NA
}
}
for(i in 1:length(Gene2eQTL)) {
if (eQTLRank[[i]] == length(Gene2eQTL[[i]])) {
Gene2eQTL[[i]] = Gene2eQTL[[i]]
} else if (eQTLRank[[i]] == 1 & length(Gene2eQTL[[i]]) > 1) {
FDR = NULL
g = as.numeric(names(Gene2eQTL[i]))
for (s in Gene2eQTL[[i]]) {
FDR = c(FDR, Significant_eQTLs[Significant_eQTLs$SNP == s & Significant_eQTLs$gene == g, 6])
}
Gene2eQTL[[i]] = Gene2eQTL[[i]][which.min(FDR)]
} else if (eQTLRank[[i]] > 1 & length(Gene2eQTL[[i]]) > 1) {
FDR = NULL
g = as.numeric(names(Gene2eQTL[i]))
for (s in Gene2eQTL[[i]]) {
FDR = c(FDR, Significant_eQTLs[Significant_eQTLs$SNP == s & Significant_eQTLs$gene == g, 6])
}
index = sort.int(FDR, decreasing = F, index.return = T)$ix
n = 0
j = 1
s = c(Gene2eQTL[[i]][index[j]])
j = j + 1
n = 1
while (n < eQTLRank[[i]] & j < length(index)) {
tmr = SNPvarmat[c(s, Gene2eQTL[[i]][index[j]]), Tumor, drop = F]
nml = SNPvarmat[c(s, Gene2eQTL[[i]][index[j]]), Normal, drop = F]
if (qr(crossprod(center(tmr)))$rank == n + 1 && qr(crossprod(center(nml)))$rank == n + 1) {
s = c(s, Gene2eQTL[[i]][index[j]])
n = n + 1
}
j = j + 1
}
Gene2eQTL[[i]] = s
} else {
Gene2eQTL[[i]] = NA
}
}
Gene2eQTL = Gene2eQTL[!is.na(Gene2eQTL)]
annotation2Entrez = read.table(
"./data/geneAnnotation.txt",
sep = "\t",
quote = "\"",
na.strings = "-",
fill = TRUE,
col.names = c("GeneID", "Symbol", "TypeOfGene"), stringsAsFactors = FALSE
)
ensembl2entrez = bitr(
names(Gene2eQTL),
fromType = "ENSEMBL",
toType = "ENTREZID",
OrgDb = "org.Hs.eg.db"
)
gene4mRNA = annotation2Entrez$GeneID[annotation2Entrez$TypeOfGene == "protein-coding"]
gene4mRNA = intersect(ensembl2entrez$ENTREZID, gene4mRNA)
ensembl2entrez = ensembl2entrez[ensembl2entrez$ENTREZID %in% gene4mRNA, ]
Gene2eQTL = Gene2eQTL[unique(ensembl2entrez$ENSEMBL)]
Gene2eQTL = Gene2eQTL[sapply(Gene2eQTL, length) != 0]
seed = as.numeric(Sys.time())
N = sum(Status == "normal")
Ng = length(Gene2eQTL)
Nk = sum(sapply(Gene2eQTL, length))
set.seed(seed)
Sk = list()
index = 0
CandidateEQTLs = NULL
for (i in 1:length(Gene2eQTL)) {
Sk[[i]] = index + seq(1:length(Gene2eQTL[[i]]))
index = max(Sk[[i]])
CandidateEQTLs = c(CandidateEQTLs, Gene2eQTL[[i]])
}
CandidateGenes = names(Gene2eQTL)
Y = vector("list", 2)
Y[[1]] = Exprvarmat[CandidateGenes, Status == "normal"]
Y[[2]] = Exprvarmat[CandidateGenes, Status == "tumor"]
rownames(Y[[1]]) = rownames(Y[[2]]) = NULL
X = vector("list", 2)
X[[1]] = SNPvarmat[CandidateEQTLs, Status == "normal"]
X[[2]] = SNPvarmat[CandidateEQTLs, Status == "tumor"]
rownames(X[[1]]) = rownames(X[[2]]) = NULL
data = list(
Data = list(
X = X, Y = Y, Sk = Sk
),
Vars = list(
Genes = CandidateGenes, eQTLs = CandidateEQTLs,
n = N, p = Ng, k = Nk
)
)
saveRDS(data, "./data2/gastric0.01.rds")
seed = as.numeric(Sys.time())
set.seed(seed)
data = readRDS("./script/data2/gastric0.01.rds")
L2lamax(data$Data$X, data$Data$Y, data$Data$Sk, data$Vars$n, data$Vars$p, data$Vars$k)
gamma = cv.multiRegression(data$Data$X, data$Data$Y, data$Data$Sk, ngamma = 20, nfold = 5, data$Vars$n, data$Vars$p, data$Vars$k)
ifit = multiRegression(data$Data$X, data$Data$Y, data$Data$Sk, gamma, data$Vars$n, data$Vars$p, data$Vars$k, trans = FALSE)
Xs = data$Data$X
colnames(Xs[[1]]) = colnames(Xs[[2]]) = NULL
Ys = data$Data$Y
colnames(Ys[[1]]) = colnames(Ys[[2]]) = NULL
Sk = data$Data$Sk
cvfit = opt.multiFSSEMiPALM2(Xs = Xs, Ys = Ys, Bs = ifit$Bs, Fs = ifit$Fs, Sk = Sk,
sigma2 = ifit$sigma2, nlambda = 20, nrho = 20,
p = data$Vars$p, q = data$Vars$k, wt = T)
fit = multiFSSEMiPALM2(Xs = Xs, Ys = Ys, Bs = ifit$Bs, Fs = ifit$Fs, Sk = Sk,
sigma2 = ifit$sigma2, lambda = cvfit$lambda, rho = cvfit$rho,
Wl = inverseB(ifit$Bs), Wf = flinvB(ifit$Bs),
p = data$Vars$p, maxit = 1000, threshold = 1e-5, sparse = T,
verbose = T, trans = T, strict = T)
saveRDS(fit, "./data2/gastricfitFSSEM0.01.rds")
fit = readRDS("./script/data2/gastricfitFSSEM0.01.rds")
data = readRDS("./script/data2/gastric0.01.rds")
filterDiffNet = function(fit, data, cutoff = 0.01) {
Ci1 = rowMeans(qnorm(1 - cutoff, mean = 0, sd = sqrt(fit$sigma2)) / data$Data$Y[[1]])
Ci2 = rowMeans(qnorm(1 - cutoff, mean = 0, sd = sqrt(fit$sigma2)) / data$Data$Y[[2]])
BThreshold = quantile(c(abs(fit$Bs[[1]])[fit$Bs[[1]] != 0], abs(fit$Bs[[2]])[fit$Bs[[2]] != 0]), seq(0, 1, by = 0.1))[2 + 1]
B1 = fit$Bs[[1]]
B2 = fit$Bs[[2]]
for(i in 1:data$Vars$p) {
B1[,i] = B1[,i] * (abs(B1[,i]) >= max(BThreshold, Ci1[i]))
B2[,i] = B2[,i] * (abs(B2[,i]) >= max(BThreshold, Ci2[i]))
}
DiffB = B2 - B1
for(i in 1:data$Vars$p) {
DiffB[,i] = DiffB[,i] * ((abs(DiffB[,i]) >= max(BThreshold, Ci1[i], Ci2[i])) & abs(DiffB[,i]) >= pmin(abs(B1[,i]), abs(B2[,i])))
}
list(B1 = B1, B2 = B2, DiffB = DiffB)
}
FilteredB = filterDiffNet(fit, data, cutoff = 0.01)
B1 = FilteredB$B1
B2 = FilteredB$B2
DiffB = FilteredB$DiffB
adjNormalGRN = as.matrix(B1 != 0)
adjTumorGRN = as.matrix(B2 != 0)
adjDifferentialGRN = as.matrix(DiffB != 0)
NormalGRN = graph_from_adjacency_matrix(t(adjNormalGRN)) %>% set_vertex_attr("name", value = data$Vars$Genes)
TumorGRN = graph_from_adjacency_matrix(t(adjTumorGRN)) %>% set_vertex_attr("name", value = data$Vars$Genes)
DifferentialGRN = graph_from_adjacency_matrix(t(adjDifferentialGRN)) %>% set_vertex_attr("name", value = data$Vars$Genes)
NormalGRN = delete.vertices(igraph::simplify(NormalGRN), degree(NormalGRN) == 0)
TumorGRN = delete.vertices(igraph::simplify(TumorGRN), degree(TumorGRN) == 0)
DifferentialGRN = delete.vertices(igraph::simplify(DifferentialGRN), degree(DifferentialGRN) == 0)
DiffGene = bitr(
names(V(DifferentialGRN)),
fromType = "ENSEMBL",
toType = "ENTREZID",
OrgDb = "org.Hs.eg.db"
)
DiffGname = bitr(
names(V(DifferentialGRN)),
fromType = "ENSEMBL",
toType = "SYMBOL",
OrgDb = "org.Hs.eg.db"
)
mRNAgenes = annotation2Entrez[annotation2Entrez$TypeOfGene == "protein-coding", 2]
DiffGname = DiffGname[DiffGname$SYMBOL %in% mRNAgenes,]
rownames(DiffGname) = DiffGname[,1]
UniGene = bitr(
data$Vars$Genes,
fromType = "ENSEMBL",
toType = "ENTREZID",
OrgDb = "org.Hs.eg.db"
)
UniGname = bitr(
data$Vars$Genes,
fromType = "ENSEMBL",
toType = "SYMBOL",
OrgDb = "org.Hs.eg.db"
)
UniGname = UniGname[UniGname$SYMBOL %in% mRNAgenes,]
UniGene = UniGene[UniGene$ENSEMBL %in% UniGname$ENSEMBL,]
GRNLayout = function(G = NULL) {
qcut = sort(degree(G), decreasing = T)[10]
V(G)$color = "blue"
V(G)$frame.color = "blue"
V(G)$color[which(degree(G) >= qcut)] = "red"
V(G)$frame.color[which(degree(G) >= qcut)] = "darkred"
V(G)$size = sqrt(degree(G)) * 1.5 + 0.1
E(G)$color = rgb(0, 0, 0, alpha = .1)
Vnames = rep(NA, length(V(G)))
Vnames[which(degree(G) >= qcut)] = DiffGname[names(which(degree(G) >= qcut)), 2]
plot(
G,
vertex.label = Vnames,
layout = layout.fruchterman.reingold,
edge.arrow.size = 0.1,
edge.curve = 0.1,
vertex.label.font = 1,
vertex.label.cex = 0.5,
vertex.label.dist = 1,
vertex.label.color = "black"
)
}
GRNLayout(NormalGRN)
GRNLayout(TumorGRN)
GRNLayout(DifferentialGRN)
getGSEAdb = function(db = NULL) {
f = readLines(db)
lst = sapply(f, function(x)
unlist(strsplit(x, "\t", fixed = TRUE)))
names(lst) = sapply(lst, function(x)
x[1])
lst1 = lapply(lst, function(x)
x[-(1:2)])
lst2 = lapply(lst, function(x)
x[2])
list(gsea = lst1, url = lst2)
}
GSEAC2 = getGSEAdb("./script/data2/c2.all.v6.2.entrez.gmt")
EntrezGenes = unique(unlist(GSEAC2$gsea))
names(EntrezGenes) = NULL
testGSEA = function(geneset, diffgene, universe) {
bgset = setdiff(universe, diffgene)
pvalue = lapply(geneset, function(x) {
x1 = length(intersect(diffgene, x))
x2 = length(setdiff(diffgene, x))
y1 = length(intersect(bgset, x))
y2 = length(setdiff(bgset, x))
c(fisher.test(matrix(c(x1, x2, y1, y2), nrow = 2), alternative = "two.sided")$p.value,
ifelse(x1/x2 >= y1/y2, "+", "-"))
})
pvalue
}
GAST_related = lapply(GSEAC2$url, function(url) {
url = as.character(url)
mdb = GET(url)
mdb = readHTMLTable(rawToChar(mdb$content), stringsAsFactors = F)
i = which(mdb[[1]][,1] == "Full description or abstract")
description = mdb[[1]][i, 2]
pattern1 = str_detect(description, "gastric relapse | gastric cancer | gastric tumor | gastric adenocarcinoma")
pattern2 = all(str_detect(description, c("gastric", "cancer | tumor | adenocarcinoma | carcinoma")))
pattern1 | pattern2
})
GSEA4GAST = GSEAC2$gsea[unlist(GAST_related)]
GSEA4GAST = GSEA4GAST[sapply(GSEA4GAST, function(x){length(intersect(x, unique(UniGene[,2]))) != 0})]
result = testGSEA(GSEA4GAST, unique(DiffGene[DiffGene$ENSEMBL %in% names(which(degree(DifferentialGRN, mode = "all") >= 1)), 2]),
unique(UniGene[,2]))
pvalue_gsea = as.numeric(sapply(result, `[`, 1))
enrich_gsea = sapply(result, `[`, 2)
enrich_idx = which(pvalue_gsea < 0.05 & enrich_gsea == "+")
enrichedGS = data.frame(gs = names(result)[enrich_idx],
description = unlist(GSEAC2$url[names(result)[enrich_idx]]),
pval = pvalue_gsea[enrich_idx])
rownames(enrichedGS) = NULL
enrichedGS
DiffGname[names(sort(degree(DifferentialGRN, mode = "all"), decreasing = T))[1:10], 2]
for(n in 1:nrow(enrichedGS)) {
cat(as.character(enrichedGS[n,1]), " & ", toupper(format(signif(enrichedGS[n,3], 2), scientific = T)), " \\\\ \n")
cat("\\hline \n")
} |
initQ <- function(ae_data) {
if (ncol(ae_data) == 5) {
Q <- data.frame(trtem = rep(TRUE, nrow(ae_data)))
}
if (ncol(ae_data) == 6) {
Q <- as.data.frame(as.logical(ae_data[,-c(1:5)]))
colnames(Q) <- colnames(ae_data)[-c(1:5)]
}
if (ncol(ae_data) > 6) {
Q <- apply(ae_data[,-c(1:5)], 2, as.logical)
}
return(Q)
} |
maturation_in <- function (data) {
final_table <- data %>%
dplyr::mutate(Age = round((lubridate::time_length(difftime(as.Date(`Testing Date`), as.Date(`Date of Birth`)), "years")/0.5)) * 0.5) %>%
dplyr::mutate(`Testing Date` = as.Date(`Testing Date`)) %>%
dplyr::mutate(`Date of Birth` = as.Date(`Date of Birth`)) %>%
dplyr::mutate(`Birth Year` = lubridate::year(`Date of Birth`)) %>%
dplyr::mutate(Quarter = paste("Q", lubridate::quarter(`Date of Birth`), sep = "")) %>%
dplyr::mutate(`Weight (KG)` = round((`Weight1 (KG)` + `Weight2 (KG)`) / 2, 1),
`Weight (LB)` = round(`Weight (KG)` * 2.20462),
`Height (CM)` = round((`Height1 (CM)` + `Height2 (CM)`) / 2, 1),
`Height (IN)` = round(`Height (CM)` * 0.393701,1),
`Sitting Height (CM)` = ((`Sitting Height1 (CM)` + `Sitting Height2 (CM)`) / 2) - `Bench Height (CM)`,
`Leg Length (CM)` = `Height (CM)` - `Sitting Height (CM)`) %>%
dplyr::mutate(`H-W Ratio` = round(`Height (CM)` / (`Weight (KG)`^ 0.33333),1),
`W-H Ratio` = round((`Weight (KG)` / `Height (CM)`) * 100,1),
BMI = round((`Weight (KG)` / (`Height (CM)`/100) ^ 2),1),
`Sitting/Stand Height` = round(`Sitting Height (CM)` / `Height (CM)`,1),
`Leg Length * Sitting Height` = round(`Leg Length (CM)` * `Sitting Height (CM)`,1),
`Age * Leg Length` = `Leg Length (CM)` * Age,
`Age * Sitting Height` = `Sitting Height (CM)` * Age,
`Age * Weight` = `Weight (KG)` * Age) %>%
dplyr::mutate(`Parent Mid Height (CM)` = round((`Mothers Height (CM)` + `Fathers Height (CM)`) / 2, 1)) %>%
dplyr::mutate(`Parent Mid Height (IN)` = `Parent Mid Height (CM)` * 0.393701) %>%
dplyr::full_join(matuR::table, by = c("Age" = "Age"), copy = T) %>%
na.omit() %>%
dplyr::mutate(`Estimated Adult Height (IN)` = ifelse(Gender == "Male", round(`B1` + (`Height (IN)` * `M-Height`) + (`Weight (LB)` * `M-Weight`) + (`Parent Mid Height (IN)` * `M-Midparent Stature`),1), round(`B2` + (`Height (IN)` * `F-Height`) + (`Weight (LB)` * `F-Weight`) + (`Parent Mid Height (IN)` * `F-Midparent Stature`),1))) %>%
dplyr::mutate(`Estimated Adult Height (CM)` = round(`Estimated Adult Height (IN)` * 2.54,1)) %>%
dplyr::mutate(`% Adult Height` = round((`Height (CM)` / `Estimated Adult Height (CM)`) * 100,1)) %>%
dplyr::mutate(`Remaining Growth (CM)` = round((`Estimated Adult Height (CM)` - `Height (CM)`),1)) %>%
dplyr::mutate(`Remaining Growth (IN)` = round(`Remaining Growth (CM)` * 0.393701,1)) %>%
dplyr::mutate(`Maturity Offset (years)` = ifelse(Gender == "Male", round(-9.236 + (0.0002728 * (`Leg Length * Sitting Height`)) + (-0.001663 * `Age * Leg Length`) + (0.007216 * `Age * Sitting Height`) + (0.02292 * `W-H Ratio`),1), round(-9.376 + (0.0001882 * (`Leg Length * Sitting Height`)) + (0.0022 * `Age * Leg Length`) + (0.005841 * `Age * Sitting Height`) + (-0.002658 * `Age * Weight`) + (0.07693 * `W-H Ratio`),1))) %>%
dplyr::mutate(`Age @ PHV` = Age - `Maturity Offset (years)`) %>%
dplyr::select(Athlete, Gender, `Testing Date`, `Birth Year`, Quarter, Age, `Height (IN)`, `Estimated Adult Height (IN)`, `% Adult Height`, `Remaining Growth (IN)`, `Maturity Offset (years)`, `Age @ PHV`) %>%
dplyr::mutate(`Maturity Category` = ifelse(`% Adult Height` < 85, "Pre-Pubertal",
ifelse(`% Adult Height` >= 85 & `% Adult Height` < 90, "Early Pubertal",
ifelse(`% Adult Height` >= 90 & `% Adult Height` < 95, "Mid-Pubertal", "Late Pubertal"))))
return(final_table)
} |
define_searchrequest_within <- function(operation, seconds, negate, use_uid, flag,
esearch, handle) {
if (isTRUE(esearch)) {
esearch_string = "RETURN () "
} else {
esearch_string = NULL
}
if (!is.null(flag)) {
flag_string <- paste(flag, collapse = " ")
flag_string = paste0(flag_string, " ")
} else {
flag_string = NULL
}
if (isTRUE(use_uid)) {
use_uid_string = "UID "
} else {
use_uid_string = NULL
}
if (isTRUE(negate)) {
negate_string = "NOT "
} else {
negate_string = NULL
}
customrequest <- paste0(use_uid_string, "SEARCH ", esearch_string, flag_string,
negate_string, operation, ' ', seconds)
tryCatch({
curl::handle_setopt(
handle = handle,
customrequest = customrequest)
}, error = function(e){
stop("The connection handle is dead. Please, configure a new IMAP connection with ImapCon$new().")
})
return(c(handle = handle, customrequest = customrequest))
} |
acontext("PredictedPeaks data set")
require(httr)
PredictedPeaks.RData <- file.path(tempdir(), "PredictedPeaks.RData")
request <- GET("http://github.com/tdhock/animint-examples/blob/master/data/PredictedPeaks.RData?raw=true")
stop_for_status(request)
writeBin(content(request), PredictedPeaks.RData)
load(PredictedPeaks.RData, .GlobalEnv)
hover.dots <- subset(PredictedPeaks$chromCounts, nonInputType==type)
viz <- list(
oneChrom=ggplot()+
ggtitle("PeakSegJoint detections on selected chromosome")+
theme_bw()+
coord_cartesian(xlim=c(0, 1))+
theme_animint(width=1500, height=100)+
theme(axis.line.x=element_blank(), axis.text.x=element_blank(),
axis.ticks.x=element_blank(), axis.title.x=element_blank())+
geom_text(aes(relative.middle, type.fac, label=samples.up,
href=paste0(
"http://genome.ucsc.edu/cgi-bin/hgTracks?db=hg19&position=",
chrom, ":", zoomStart, "-", zoomEnd),
showSelected2=chrom,
showSelected=dotID),
size=11,
data=PredictedPeaks$chromCounts)+
scale_y_discrete("cell type", drop=FALSE),
chroms=ggplot()+
theme_bw()+
theme_animint(width=1500, height=330)+
scale_y_discrete("chromosome", drop=FALSE)+
scale_x_continuous("position on chromosome (mega bases)")+
geom_text(aes(0, chrom, label=paste0(peaks, "_"),
clickSelects=chrom,
showSelected=dotID),
hjust=1,
size=11,
data=PredictedPeaks$countsByChrom)+
geom_segment(aes(chromStart/1e6, chrom,
clickSelects=chrom,
xend=chromEnd/1e6, yend=chrom),
size=9,
data=PredictedPeaks$chrom.ranges)+
geom_point(aes(chromEnd/1e6, chrom,
id=chrom,
clickSelects=chrom),
size=5,
data=PredictedPeaks$chrom.ranges)+
geom_text(aes(max(PredictedPeaks$chrom.ranges$chromEnd)/2e6, chrom,
showSelected=dotID,
label=totals),
data=PredictedPeaks$scatter.text),
scatter=ggplot()+
geom_hline(aes(yintercept=N),
color="grey",
data=PredictedPeaks$counts.Input)+
scale_x_continuous("number of samples with a peak")+
facet_grid(nonInputType ~ .)+
theme_bw()+
scale_fill_gradient(low="grey", high="red")+
theme_animint(width=1500)+
theme(panel.margin=grid::unit(0, "cm"))+
geom_vline(aes(xintercept=N),
color="grey",
data=PredictedPeaks$counts.not.Input)+
geom_rect(aes(xmin=up-size, xmax=up+size,
ymin=Input-size, ymax=Input+size,
tooltip=totals,
clickSelects=dotID,
showSelected=chrom,
fill=log10(count)),
color="transparent",
data=PredictedPeaks$bg.rect),
first=list(dotID="38 neutro samples, 1 Input samples", chrom="chr16"))
info <- animint2HTML(viz)
test_that("without selectize option, only render chrom widget", {
widget.vec <- getSelectorWidgets(info$html)
expect_identical(widget.vec, "chrom")
})
getSorted <- function(){
text.list <- getNodeSet(getHTML(), '//g[@class="geom1_text_oneChrom"]//text')
value.vec <- sapply(text.list, xmlValue)
sort(as.numeric(value.vec))
}
test_that("initially 2 text elements rendered", {
num.vec <- getSorted()
expect_equal(num.vec, c(1, 38))
})
clickID("chrM")
Sys.sleep(1)
exp.vec <- c(1, 14, 38)
test_that("3 elements rendered (first time)", {
num.vec <- getSorted()
expect_equal(num.vec, exp.vec)
})
clickID("chrY")
Sys.sleep(1)
clickID("chrM")
Sys.sleep(1)
test_that("3 elements rendered (second time)", {
num.vec <- getSorted()
expect_equal(num.vec, exp.vec)
})
thresh.df <- data.frame(max.input.samples=9, thresh.type="specific")
PredictedPeaks$counts.not.Input$thresh.type <- "max samples"
PredictedPeaks$counts.Input$thresh.type <- "max samples"
viz <- list(
oneChrom=ggplot()+
ggtitle("PeakSegJoint detections on selected chromosome")+
theme_bw()+
coord_cartesian(xlim=c(0, 1))+
theme_animint(width=1500, height=100)+
theme(axis.line.x=element_blank(), axis.text.x=element_blank(),
axis.ticks.x=element_blank(), axis.title.x=element_blank())+
geom_text(aes(relative.middle, type.fac, label=samples.up,
clickSelects=peak.name,
showSelected2=chrom,
showSelected=dotID),
size=11,
data=PredictedPeaks$chromCounts)+
scale_y_discrete("cell type", drop=FALSE),
chroms=ggplot()+
theme_bw()+
theme_animint(width=1500, height=330)+
scale_y_discrete("chromosome", drop=FALSE)+
scale_x_continuous("position on chromosome (mega bases)")+
geom_text(aes(0, chrom, label=paste0(peaks, "_"),
clickSelects=chrom,
showSelected=dotID),
hjust=1,
size=11,
data=PredictedPeaks$countsByChrom)+
geom_segment(aes(chromStart/1e6, chrom,
clickSelects=chrom,
xend=chromEnd/1e6, yend=chrom),
size=9,
data=PredictedPeaks$chrom.ranges)+
geom_point(aes(chromEnd/1e6, chrom,
id=chrom,
clickSelects=chrom),
size=5,
data=PredictedPeaks$chrom.ranges)+
geom_text(aes(max(PredictedPeaks$chrom.ranges$chromEnd)/2e6, chrom,
showSelected=dotID,
label=totals),
data=PredictedPeaks$scatter.text),
scatter=ggplot()+
geom_vline(aes(xintercept=N, color=thresh.type),
data=PredictedPeaks$counts.not.Input)+
scale_color_manual("threshold", values=c(
"max samples"="grey",
specific="grey30"))+
geom_hline(aes(yintercept=max.input.samples+0.5, color=thresh.type),
show.legend=TRUE,
data=thresh.df)+
geom_hline(aes(yintercept=N, color=thresh.type),
show.legend=TRUE,
data=PredictedPeaks$counts.Input)+
scale_x_continuous("number of samples with a peak")+
facet_grid(nonInputType ~ .)+
theme_bw()+
scale_fill_gradient(low="grey", high="red")+
theme_animint(width=1500)+
theme(panel.margin=grid::unit(0, "cm"))+
geom_rect(aes(xmin=up-size, xmax=up+size,
ymin=Input-size, ymax=Input+size,
tooltip=totals,
clickSelects=dotID,
showSelected=chrom,
fill=log10(count)),
color="transparent",
data=PredictedPeaks$bg.rect)+
geom_point(aes(up, Input,
showSelected=peak.name),
data=hover.dots),
selectize=list(dotID=TRUE, chrom=FALSE),
first=list(dotID="38 neutro samples, 1 Input samples", chrom="chr16"))
info <- animint2HTML(viz)
test_that("selectize option respected", {
widget.vec <- getSelectorWidgets(info$html)
expected.widgets <- c("dotID", "thresh.type")
expect_identical(sort(widget.vec), sort(expected.widgets))
})
test_that("rects rendered in fill legend", {
rect.list <- getNodeSet(
info$html, '//tr[@class="log10(count)_variable"]//rect')
expect_equal(length(rect.list), 5)
})
test_that("no lines rendered in fill legend", {
line.list <- getNodeSet(
info$html, '//tr[@class="log10(count)_variable"]//line')
expect_equal(length(line.list), 0)
})
test_that("lines in color legend", {
line.list <- getNodeSet(
info$html, '//tr[@class="thresh_type_variable"]//line')
expect_equal(length(line.list), 2)
})
specific_hlines <- function(html=getHTML()){
getNodeSet(html, '//g[@class="geom7_hline_scatter"]//line')
}
specific.id <- "plot_scatter_thresh_type_variable_specific"
xpath <- sprintf('//td[@id="%s_label"]', specific.id)
specific_opacity <- function(html=getHTML()){
as.numeric(getStyleValue(html, xpath, "opacity"))
}
test_that("initially rendered hlines", {
line.list <- specific_hlines(info$html)
expect_equal(length(line.list), 2)
computed.opacity <- specific_opacity(info$html)
expect_equal(computed.opacity, 1)
})
test_that("hlines after clicking specific", {
html <- clickHTML(id=specific.id)
line.list <- specific_hlines(html)
expect_equal(length(line.list), 0)
computed.opacity <- specific_opacity(html)
expect_equal(computed.opacity, 0.5)
})
test_that("hlines after clicking specific again", {
html <- clickHTML(id=specific.id)
line.list <- specific_hlines(html)
expect_equal(length(line.list), 2)
computed.opacity <- specific_opacity(html)
expect_equal(computed.opacity, 1)
}) |
dynamic_model <- function(x,total=TRUE){
e0 <- 4153.5
e1 <- 12888.8
a0 <- 139500
a1 <- 2.567e+18
slp <- 1.6
tetmlt <- 277
aa <- a0/a1
ee <- e1 - e0
TK <- x + 273
ftmprt <- slp * tetmlt * (TK - tetmlt)/TK
sr <- exp(ftmprt)
xi <- sr/(1 + sr)
xs <- aa * exp(ee/TK)
ak1 <- a1 * exp(-e1/TK)
interE <- 0
memo <- new.env(hash = TRUE)
posi <- 1
assign(x = paste(1), value = 0, envir = memo)
E = 0
S <- ak1
S[1] <- 0
E <- S
options(scipen = 30)
for (l in 2:length(x)) {
if (E[l - 1] < 1) {
S[l] <- E[l - 1]
E[l] <- xs[l] - (xs[l] - S[l]) * exp(-ak1[l])
}
else {
S[l] <- E[l - 1] - E[l - 1] * xi[l - 1]
E[l] <- xs[l] - (xs[l] - S[l]) * exp(-ak1[l])
}
}
interE <- E
y <- rep(0, length(x))
y[which(interE >= 1)] <- interE[which(interE >= 1)] *
xi[which(interE >= 1)]
if (total == TRUE)
return(tail(cumsum(y),n=1))
else return(y)
} |
include.others <- function(selected, center, stats, best=FALSE){
above <- sign(stats[3,selected] - center) == 1
if(best){
if(above){
other <- stats[3,] > center &
stats[3,] <
stats[4,selected]
} else {
other <- stats[3,] < center &
stats[3,] >
stats[2,selected]
}
} else {
if(above){
other <- stats[3,] >
stats[2,selected] &
stats[2,] > center
} else {
other <- stats[3,] <
stats[4,selected] &
stats[4,] < center
}
}
other <- which(other)
return(other)
} |
plsRglmmodel.formula <- function(formula,data=NULL,nt=2,limQ2set=.0975,dataPredictY,modele="pls",family=NULL,typeVC="none",EstimXNA=FALSE,scaleX=TRUE,scaleY=NULL,pvals.expli=FALSE,alpha.pvals.expli=.05,MClassed=FALSE,tol_Xi=10^(-12),weights,subset,start=NULL,etastart,mustart,offset,method="glm.fit",control= list(),contrasts=NULL,sparse=FALSE,sparseStop=TRUE,naive=FALSE,verbose=TRUE)
{
if(missing(modele)){modele="pls"}
if (typeVC!="none") {stop("Use plsRglm_kfoldcv for applying kfold cross validation to glms")}
if (missing(data)) {data <- environment(formula)}
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula","data","nt","limQ2set","dataPredictY","modele","family","typeVC","EstimXNA","scaleX","scaleY","pvals.expli","alpha.pvals.expli","MClassed","tol_Xi","weights","subset","start","etastart","mustart","offset","method","control","contrasts","sparse","sparseStop","naive","verbose"), names(mf), 0L)
if(is.null(mf$modele)){mf$modele<-"pls"}
mf <- mf[c(1L, m)]
mf[[1L]] <- as.name("PLS_glm_formula")
estmodel <- eval(mf, parent.frame())
class(estmodel) <- "plsRglmmodel"
estmodel$call <- match.call()
estmodel
} |
dgig <- function(x, chi = 1, psi = 1, lambda = 1,
param = c(chi, psi, lambda), KOmega = NULL) {
parResult <- gigCheckPars(param)
case <- parResult$case
errMessage <- parResult$errMessage
if (case == "error")
stop(errMessage)
param <- as.numeric(param)
chi <- param[1]
psi <- param[2]
lambda <- param[3]
omega <- sqrt(chi*psi)
if (omega > 700){
KOmega <- besselK(omega, nu = lambda, expon.scaled = TRUE)
logDensity <- ifelse(x > 0,
(lambda/2)*log(psi/chi) -
log(2) - log(KOmega) + omega +
(lambda - 1)*log(x) -
(1/2)*(chi*x^(-1) + psi*x),
-Inf)
gigDensity <- exp(logDensity)
} else {
if (is.null(KOmega)){
KOmega <- besselK(omega, nu = lambda)
}
gigDensity <- ifelse(x > 0, (psi/chi)^(lambda/2) /
(2*KOmega)*x^(lambda - 1) *
exp(-(1/2)*(chi*x^(-1) + psi*x)), 0)
}
gigDensity
}
pgig <- function(q, chi = 1, psi = 1, lambda = 1,
param = c(chi,psi,lambda), lower.tail = TRUE,
ibfTol = .Machine$double.eps^(0.85),
nmax = 200) {
parResult <- gigCheckPars(param)
case <- parResult$case
errMessage <- parResult$errMessage
if (case == "error")
stop(errMessage)
param <- as.numeric(param)
chi <- param[1]
psi <- param[2]
lambda <- param[3]
qCalculate <- which((q > 0) & (is.finite(q)))
prob <- rep(NA, length(q))
prob[q <= 0] <- 1
prob[q == Inf] <- 0
omega <- sqrt(chi*psi)
KOmega <- besselK(omega, nu = lambda)
x <- psi*q/2
y <- chi/(2*q)
const <- (psi/chi)^(lambda/2)/(2*KOmega)
for (i in qCalculate){
prob[i] <- q[i]^lambda*incompleteBesselK(x[i], y[i], -lambda,
tol = ibfTol, nmax = nmax)
}
prob[qCalculate] <- const*prob[qCalculate]
if (lower.tail) prob <- 1 - prob
return(prob)
}
qgig <- function(p, chi = 1, psi = 1, lambda = 1,
param = c(chi, psi, lambda),
lower.tail = TRUE, method = c("spline", "integrate"),
nInterpol = 501, uniTol = 10^(-7),
ibfTol = .Machine$double.eps^(0.85), nmax =200, ...){
parResult <- gigCheckPars(param)
case <- parResult$case
errMessage <- parResult$errMessage
if (case == "error")
stop(errMessage)
if(!lower.tail){
p <- 1 - p
lower.tail == TRUE
}
method <- match.arg(method)
param <- as.numeric(param)
chi <- param[1]
psi <- param[2]
lambda <- param[3]
modeDist <- gigMode(param = param)
pModeDist<- pgig(modeDist, param = param, ibfTol = ibfTol)
xRange <- gigCalcRange(param = param, tol = 10^(-7))
quant <- rep(NA, length(p))
invalid <- which((p < 0) | (p > 1))
pFinite <- which((p > 0) & (p < 1))
if (method == "integrate")
{
less <- which((p <= pModeDist) & (p > .Machine$double.eps^5))
quant <- ifelse(p <= .Machine$double.eps^5, 0, quant)
if (length(less) > 0){
xLow <- 0
xRange <- c(xLow, modeDist)
zeroFnLess <- function(x, param, p)
{
return(pgig(x, param = param, ibfTol = ibfTol) - p)
}
for (i in less){
quant[i] <- uniroot(zeroFnLess, param = param, p = p[i],
interval = xRange, tol = uniTol)$root
}
}
greater <- which ((p > pModeDist) & (p < (1 - .Machine$double.eps^5)))
p[greater] <- 1 - p[greater]
quant <- ifelse(p >= (1 - .Machine$double.eps), Inf, quant)
if (length(greater) > 0){
pHigh <- min(p[greater])
xHigh <- modeDist + sqrt(gigVar(param = param))
while (pgig(xHigh, param = param, lower.tail = FALSE) >= pHigh){
xHigh <- xHigh + sqrt(gigVar(param = param))
}
xRange <- c(modeDist,xHigh)
zeroFnGreater <- function(x, param, p)
{
return(pgig(x, param = param, lower.tail = FALSE,
ibfTol = ibfTol) - p)
}
for (i in greater){
quant[i] <- uniroot(zeroFnGreater, param = param, p = p[i],
interval = xRange, tol = uniTol)$root
}
}
} else if (method == "spline") {
inRange <- which((p > pgig(xRange[1], param = param)) &
(p < pgig(xRange[2], param = param)))
small <- which((p <= pgig(xRange[1], param = param)) & (p >= 0))
large <- which((p >= pgig(xRange[2], param = param)) & (p <= 1))
extreme <- c(small, large)
xVals <- seq(xRange[1], xRange[2], length.out = nInterpol)
yVals <- pgig(xVals, param = param,
ibfTol = max(ibfTol, .Machine$double.eps^0.25) )
splineFit <- splinefun(xVals, yVals)
zeroFn <- function(x, p){
return(splineFit(x) - p)
}
for (i in inRange){
quant[i] <- uniroot(zeroFn, p = p[i],
interval = xRange, tol = uniTol)$root
}
if (length(extreme) > 0){
quant[extreme] <- qgig(p[extreme], param = param,
lower.tail = lower.tail, method = "integrate",
nInterpol = nInterpol, uniTol = uniTol,
ibfTol = ibfTol, ...)
}
}
return(quant)
}
rgig1 <- function(n, chi = 1, psi = 1, param = c(chi, psi)) {
if (length(param) == 2)
param <- c(param, 1)
parResult <- gigCheckPars(param)
case <- parResult$case
errMessage <- parResult$errMessage
if (case == "error")
stop(errMessage)
chi <- param[1]
psi <- param[2]
lambda <- 1
alpha <- sqrt(psi/chi)
beta <- sqrt(psi*chi)
m <- abs(beta)/beta
g <- function(y) {
0.5*beta*y^3 - y^2*(0.5*beta*m + lambda + 1) +
y*(-0.5*beta) + 0.5*beta*m
}
upper <- m
while (g(upper) <= 0)
upper <- 2*upper
yM <- uniroot(g, interval = c(0, m))$root
yP <- uniroot(g, interval = c(m, upper))$root
a <- (yP - m)*exp(-0.25*beta*(yP + 1/yP - m - 1/m))
b <- (yM - m)*exp(-0.25*beta*(yM + 1/yM - m - 1/m))
c <- -0.25*beta*(m + 1/m)
output <- numeric(n)
for (i in 1:n) {
needValue <- TRUE
while (needValue) {
R1 <- runif(1)
R2 <- runif(1)
Y <- m + a*R2/R1 + b*(1 - R2)/R1
if (Y > 0) {
if (-log(R1) >= 0.25*beta*(Y + 1/Y) + c) {
needValue <- FALSE
}
}
}
output[i] <- Y
}
output/alpha
}
rgig <- function(n, chi = 1, psi = 1, lambda = 1,
param = c(chi, psi, lambda)) {
parResult <- gigCheckPars(param)
case <- parResult$case
errMessage <- parResult$errMessage
if (case == "error")
stop(errMessage)
chi <- param[1]
psi <- param[2]
lambda <- param[3]
if (lambda == 1)
stop(return(rgig1(n, param = c(chi, psi))))
alpha <- sqrt(psi/chi)
beta <- sqrt(psi*chi)
m <- (lambda - 1 + sqrt((lambda - 1)^2 + beta^2))/beta
g <- function(y) {
0.5*beta*y^3 - y^2*(0.5*beta*m + lambda + 1) +
y*((lambda - 1)*m - 0.5*beta) + 0.5*beta*m
}
upper <- m
while (g(upper) <= 0)
upper <- 2*upper
yM <- uniroot(g, interval = c(0, m),
tol = min(.Machine$double.eps^0.25,
(.Machine$double.eps + g(0)/10)))$root
yP <- uniroot(g, interval = c(m, upper))$root
a <- (yP - m)*(yP/m)^(0.5*(lambda - 1)) *
exp(-0.25*beta*(yP + 1/yP - m - 1/m))
b <- (yM - m)*(yM/m)^(0.5*(lambda - 1)) *
exp(-0.25*beta*(yM + 1/yM - m - 1/m))
c <- -0.25*beta*(m + 1/m) + 0.5*(lambda - 1)*log(m)
output <- numeric(n)
for (i in 1:n) {
needValue <- TRUE
while (needValue) {
R1 <- runif(1)
R2 <- runif(1)
Y <- m + a*R2/R1 + b*(1 - R2)/R1
if (Y > 0) {
if (-log(R1) >= -0.5*(lambda - 1)*log(Y) +
0.25*beta*(Y + 1/Y) + c) {
needValue <- FALSE
}
}
}
output[i] <- Y
}
output/alpha
}
ddgig <- function(x, chi = 1, psi = 1, lambda = 1,
param = c(chi, psi, lambda), KOmega = NULL) {
parResult <- gigCheckPars(param)
case <- parResult$case
errMessage <- parResult$errMessage
if (case == "error")
stop(errMessage)
param <- as.numeric(param)
chi <- param[1]
psi <- param[2]
lambda <- param[3]
omega <- sqrt(chi*psi)
if (is.null(KOmega))
KOmega <- besselK(x = omega, nu = lambda)
ddgig <- ifelse(x > 0,
dgig(x, param = param, KOmega)*
(chi/x^2 + 2*(lambda - 1)/x - psi)/2,
0)
ddgig
} |
Profile.multinorm <- function(fn,data,times,pars,coefs=NULL,basisvals=NULL,var=c(1,0.01),
fd.obj=NULL,more=NULL,quadrature=NULL,
in.meth='nlminb',out.meth='optim',
control.in=list(),control.out=list(),eps=1e-6,
active=NULL,posproc=FALSE,poslik=FALSE,discrete=FALSE,names=NULL,sparse=FALSE)
{
dims = dim(data)
if(is.null(active)){ active = 1:length(pars) }
profile.obj = multinorm.setup(pars,coefs,fn,basisvals,var,fd.obj,more,
data,times,quadrature,eps=1e-6,posproc=posproc,poslik=poslik,
discrete=discrete,names=names,sparse=sparse)
lik = profile.obj$lik
proc = profile.obj$proc
coefs = profile.obj$coefs
data = profile.obj$data
times = profile.obj$times
Ires = inneropt(data,times,pars,coefs,lik,proc,in.meth,control.in)
apars = pars[active]
aparamnames = names(apars)
res = outeropt(data,times,pars,Ires$coefs,lik,proc,in.meth,out.meth,control.in,control.out,active)
apars = res$pars[active]
names(apars) = aparamnames
ncoefs = as.matrix(res$coefs)
pars[active] = apars
if(!is.null(fd.obj)){
if(length(dims)>2){
ncoefs = array(ncoefs,c(length(ncoefs)/(dims[2]*dims[3]),dims[2],dims[3]))
} else{
ncoefs = array(ncoefs,c(length(ncoefs)/dims[2],dims[2]))
}
fd.obj = fd(ncoefs,fd.obj$basis)
return( list(pars=pars,fd=fd.obj,lik=lik,proc=proc,outer.result=res$outer.result,data=data,times=times) )
}
else{
return( list(pars=pars,coefs=ncoefs,lik=lik,proc=proc,outer.result=res$outer.result,data=data,times=times) )
}
}
Smooth.multinorm <- function(fn,data,times,pars,coefs=NULL,basisvals=NULL,var=c(1,0.01),
fd.obj=NULL,more=NULL,quadrature=NULL,
in.meth='nlminb',control.in=list(),
eps=1e-6,posproc=FALSE,poslik=FALSE,discrete=FALSE,names=NULL,sparse=FALSE)
{
dims = dim(data)
profile.obj = multinorm.setup(pars,coefs,fn,basisvals,var,fd.obj,more,
data,times,quadrature,eps=1e-6,posproc=posproc,poslik=poslik,
discrete=discrete,names=names,sparse=sparse)
lik = profile.obj$lik
proc = profile.obj$proc
coefs = profile.obj$coefs
data = profile.obj$data
times = profile.obj$times
dims = dim(data)
Ires = inneropt(data,times,pars,coefs,lik,proc,in.meth,control.in)
ncoefs = Ires$coefs
Ires = Ires$res
ncoefs = array(ncoefs,dims)
if(!is.null(fd.obj)){
ncoefs = array(ncoefs,c(nrow(ncoefs)/dims[2],dims[2],dims[3]))
fd.obj = fd(ncoefs,fd.obj$basis)
return( list(fd=fd.obj,lik=lik,proc=proc,res=Ires) )
}
else{
return( list(coefs=ncoefs,lik=lik,proc=proc,inner.result=Ires,data=data,times=times) )
}
}
multinorm.setup = function(pars,coefs=NULL,fn,basisvals=NULL,var=c(1,0.01),fd.obj=NULL,
more=NULL,data=NULL,times=NULL,quadrature=NULL,eps=1e-6,posproc=FALSE,poslik=FALSE,
discrete=FALSE,names=NULL,sparse=FALSE)
{
if(!is.null(data) & length(dim(data))>2){
data = matrix(data,dim(data)[1]*dim(data)[2],dim(data)[3])
}
colnames = names
if(!is.null(fd.obj)){
basisvals = fd.obj$basis
if(!is.null(fd.obj$coefs)){
coefs = fd.obj$coefs
}
if(!is.null(fd.obj$fdnames) & is.null(colnames)){
colnames = fd.obj$fdnames[[length(fd.obj$fdnames)]]
}
}
lik = make.multinorm()
if(!poslik){ lik$more = c(make.id(),make.cvar())}
else { lik$more = c(make.exp(),make.cvar())}
lik$more$f.more = NULL
lik$more$v.more= list(mat=var[1]*diag(rep(1,2)),sub=matrix(0,0,3))
if(length(dim(coefs))>2){
if(is.null(colnames)){
colnames = dimnames(coefs)[[3]]
}
nrep = dim(coefs)[2]
coefs = matrix(coefs,dim(coefs)[1]*dim(coefs)[2],dim(coefs)[3])
}
else{
nrep = 1
colnames = colnames(coefs)
}
if(!posproc){
if(!discrete) proc = make.Cproc()
else
proc = make.Dproc()
}
else{
if(!discrete) proc = make.exp.Cproc()
else
proc = make.exp.Dproc()
}
proc$more = make.multinorm()
if(is.list(fn)){
proc$more$more = c(fn,make.cvar())
proc$more$more$f.more = NULL
proc$more$more$v.more = list(mat=var[2]*diag(rep(1,2)),sub=matrix(0,0,3))
proc$more$more$more = more
}
else if(is.function(fn)){
proc$more$more = c(make.findif.ode(),make.cvar())
proc$more$more$f.more$eps = eps
proc$more$more$f.more$fn = fn
proc$more$more$more = more
}
else if(inherits(fn,'pomp')){
proc$more$more = c(make.findif.ode(),make.cvar())
proc$more$more$f.more$fn = pomp.skeleton
proc$more$more$f.more$eps = eps
proc$more$more$f.more$more = list(pomp.obj = fn)
}
else{
stop('fn must be either a list of functions or a function')
}
proc$more$names = colnames
proc$more$parnames = names(pars)
if(is.basis(basisvals)){
if(is.null(times)){
stop('if basisvals is is a basis object, you must specify the observation times')
}
if(sparse){
lik$bvals = spam(diag(rep(1,nrep)) %x%
eval.basis(times,basisvals))
} else{
lik$bvals = diag(rep(1,nrep)) %x% eval.basis(times,basisvals)
}
if(is.null(quadrature) | is.null(quadrature$qpts)){
knots = c(basisvals$rangeval[1],basisvals$params,basisvals$rangeval[2])
qpts = c(knots[1],knots[-length(knots)] + diff(knots)/2,knots[length(knots)])
weights = rep(1,length(qpts))
}
else{
qpts = quadrature$qpts
weights = quadrature$weights
if(is.null(weights)){ weights = rep(1,length(qpts)) }
}
proc$bvals = list()
if(!discrete){
if(sparse){
proc$bvals$bvals = spam(diag(rep(1,nrep)) %x%
eval.basis(qpts,basisvals,0))
proc$bvals$dbvals = spam(diag(rep(1,nrep)) %x%
eval.basis(qpts,basisvals,1))
}else{
proc$bvals$bvals = diag(rep(1,nrep)) %x% eval.basis(qpts,basisvals,0)
proc$bvals$dbvals = diag(rep(1,nrep)) %x% eval.basis(qpts,basisvals,1)
}
proc$more$qpts = rep(qpts,nrep)
proc$mroe$weights = rep(weights,nrep)
}
else{
len = length(times)
if(sparse){
proc$bvals = list(bvals = spam(basisvals[1:(len-1),]),
dbvals= spam(basisvals[2:len,]))
} else{
proc$bvals = list(bvals = basisvals[1:(len-1),],
dbvals= basisvals[2:len,])
}
proc$more$qpts = rep(times[1:(len-1)],nrep)
}
}
else{
if(discrete & (is.matrix(basisvals) | is.null(basisvals))){
if(is.null(basisvals)){ basisvals = Diagonal(nrow(coefs)) }
if(sparse){
lik$bvals = spam(diag(rep(1,nrep))%x%basisvals)
proc$bvals = spam(diag(rep(1,nrep))%x%basisvals)
}else{
lik$bvals = diag(rep(1,nrep))%x%basisvals
proc$bvals = diag(rep(1,nrep))%x%basisvals
}
proc$more$qpts = rep(times[1:(length(times)-1)],nrep)
}
else{
if(sparse){
lik$bvals = spam(diag(rep(1,nrep))%x%basisvals$bvals.obs)
proc$bvals = list(bvals=spam(diag(rep(1,nrep)) %x%
basisvals$bvals),
dbvals=spam(diag(rep(1,nrep)) %x%
basisvals$dbvals))
} else{
lik$bvals = diag(rep(1,nrep))%x%basisvals$bvals.obs
proc$bvals = list(bvals=diag(rep(1,nrep)) %x% basisvals$bvals,
dbvals= diag(rep(1,nrep)) %x%basisvals$dbvals)
}
proc$more$qpts = rep(basisvals$qpts,nrep)
proc$more$weights = rep(basisvals$weights,nrep)
}
}
if(is.null(proc$more$weights)){ proc$more$weights = rep(1,length(proc$more$qpts)) }
if(!is.null(data)){
if(length(dim(data))==2){
if(nrep>1){stop('data dimensions must match coefficient dimensions')}
if(dim(data)[1] != length(times) | dim(data)[2]!= dim(coefs)[2]){stop('data dimensions, times and coefficient dimensions do not match')}
}
if(length(dim(data))==3){
if(dim(data)[2] != nrep | dim(data)[3]!=dim(coefs)[2] | dim(data)[1]!=length(times)){
stop('data dimensions, times and coefficient dimensions do not match')}
data = matrix(data,dim(data)[1]*dim(data)[2],dim(data)[3])
times = rep(times,nrep)
}
}
return( list(lik=lik,proc=proc,coefs=coefs,data=data,times=times) )
} |
crwPostIS = function(object.sim, fullPost=TRUE, df=Inf, scale=1, thetaSamp=NULL)
{
if(!inherits(object.sim, 'crwSimulator')) stop("Argument needs to be of class 'crwSimulator'\nUse 'crwSimulator( )' to create")
fixPar <- object.sim$fixPar
Cmat <- object.sim$Cmat[is.na(fixPar),is.na(fixPar)]
se <- sqrt(diag(Cmat))
err.mfX <- object.sim$err.mfX
err.mfY <- object.sim$err.mfY
par <- object.sim$par
n2ll.mode <- -2*object.sim$loglik
activity <- object.sim$activity
driftMod <- object.sim$driftMod
mov.mf <- object.sim$mov.mf
y <- object.sim$y
noObs = object.sim$noObs
delta <- object.sim$delta
n.errX <- object.sim$n.errX
n.errY <- object.sim$n.errY
rho = object.sim$rho
n.mov <- object.sim$n.mov
N <- object.sim$N
lower <- object.sim$lower
upper <- object.sim$upper
prior <- object.sim$prior
eInd <- is.na(fixPar)
if(fullPost){
if(is.null(object.sim$thetaSampList)){
eps <- rmvtt(mu=rep(0,sum(eInd)), Sigma=scale*Cmat, df=df, lower-par[eInd], upper-par[eInd])
par[eInd] <- par[eInd] + eps
if(df==Inf) dens <- dmvnorm(eps, sigma=scale*Cmat, log=TRUE) - dmvnorm(0.0*eps, sigma=scale*Cmat, log=TRUE)
else dens <- dmvt(eps, sigma=scale*Cmat, df=df, log=TRUE) - dmvt(0.0*eps, sigma=scale*Cmat, df=df, log=TRUE)
} else{
if(is.null(thetaSamp)) thetaSamp <- length(object.sim$thetaSampList)
parRow <- sample(1:nrow(object.sim$thetaSampList[[thetaSamp]]), 1, prob=object.sim$thetaSampList[[thetaSamp]][,1])
par <- as.vector(object.sim$thetaSampList[[thetaSamp]][parRow,-c(1:3)])
}
}
theta = object.sim$par[is.na(object.sim$fixPar)]
argslist = par2arglist(theta, fixPar, y, noObs, delta,
mov.mf, err.mfX, err.mfY, rho, activity,
n.errX, n.errY, n.mov, driftMod)
if (driftMod) {
out=CTCRWSAMPLE_DRIFT(y, argslist$Hmat, argslist$b, argslist$b.drift, argslist$sig2,
argslist$sig2.drift, delta, noObs, argslist$active, argslist$a, argslist$P)
} else {
out=CTCRWSAMPLE(y, argslist$Hmat, argslist$b, argslist$sig2, delta, noObs, argslist$active, argslist$a, argslist$P)
}
if(driftMod){
colnames(out$sim) <- apply(expand.grid(c("mu","theta","gamma"), c("x","y")), 1, paste, collapse=".")
} else {
colnames(out$sim) <- apply(expand.grid(c("mu","nu"), c("x","y")), 1, paste, collapse=".")
}
ln.prior = ifelse(!is.null(object.sim$prior), object.sim$prior(par[eInd]), 0)
isw <- ifelse(is.null(object.sim$thetaSampList) & fullPost==TRUE, out$ll - object.sim$loglik - dens, 0) + ln.prior
samp <- list(alpha.sim=out$sim,
locType=object.sim$locType, TimeNum=object.sim$TimeNum,
loglik=out$lly+out$llx, par=par, log.isw = isw)
samp[[object.sim$Time.name]] = object.sim$TimeNum
if(object.sim$return_posix) samp[[object.sim$Time.name]] = lubridate::as_datetime(samp[[object.sim$Time.name]])
class(samp) <- c("crwIS","list")
attr(samp, "Time.name") = object.sim$Time.name
attr(samp,"coord") <- object.sim$coord
attr(samp,"random.drift") <- object.sim$driftMod
attr(samp,"activity.model") <- !is.null(object.sim$activity)
attr(samp,"epsg") <- attr(object.sim,"epsg")
attr(samp,"proj4") <- attr(object.sim,"proj4")
return(samp)
} |
setMethodS3("plotDensity", "AffymetrixCelFile", function(this, subset=NULL, types=NULL, ..., xlim=c(0,16), xlab=NULL, ylab="density (integrates to one)", log=TRUE, annotate=TRUE, verbose=FALSE) {
requireNamespace("aroma.light") || throw("Package aroma.light not loaded.")
if (is.null(xlab)) {
if (log) {
xlab <- expression(log[2](y))
} else {
xlab <- expression(y)
}
}
verbose <- Arguments$getVerbose(verbose)
cdf <- getCdf(this)
verbose && enter(verbose, "Identifying subset of probes")
suppressWarnings({
subset <- identifyCells(cdf, indices=subset, types=types,
verbose=less(verbose))
})
verbose && exit(verbose)
verbose && enter(verbose, "Plotting the density")
verbose && cat(verbose, "Array: ", getName(this))
suppressWarnings({
verbose && enter(verbose, "Loading probe intensities")
y <- getData(this, indices=subset, fields="intensities")
y <- y$intensities
verbose && exit(verbose)
if (log) {
verbose && cat(verbose, "Taking the logarithm (base 2)")
y <- log(y, base=2)
}
verbose && cat(verbose, "Plotting")
plotDensity(y, xlim=xlim, xlab=xlab, ylab=ylab, ...)
})
if (annotate) {
stextChipType(getChipType(this))
stextLabels(this)
stextSize(this, size=length(y))
}
verbose && exit(verbose)
})
setMethodS3("getAm", "AffymetrixCelFile", function(this, reference, indices=NULL, ..., zeros=FALSE) {
reference <- Arguments$getInstanceOf(reference, "AffymetrixCelFile")
nbrOfCells <- nbrOfCells(this)
if (is.null(indices)) {
} else {
indices <- Arguments$getIndices(indices, max=nbrOfCells)
}
if (nbrOfCells != nbrOfCells(reference)) {
throw("This and the 'reference' CEL file have different number of cells: ",
nbrOfCells, " != ", nbrOfCells(reference))
}
y1 <- getData(this, indices=indices, fields="intensities")[,1]
offset <- this$offset
if (is.null(offset))
offset <- 0
if (offset != 0)
cat("Offset: ", offset, "\n", sep="")
if (!zeros) {
keep <- which(y1 != 0)
y1 <- y1[keep]
} else {
keep <- seq_along(y1)
}
y1 <- y1 + offset
y1 <- log(y1, base=2)
if (length(y1) == 0) {
y2 <- y1
} else {
if (is.null(indices)) {
indices <- keep
} else {
indices <- indices[keep]
}
y2 <- getData(reference, indices=indices, fields="intensities")[,1]
y2 <- y2 + offset
y2 <- log(y2, base=2)
}
am <- matrix(c((y1+y2)/2, y1-y2), ncol=2)
colnames(am) <- c("A", "M")
am
})
setMethodS3("annotateMvsA", "AffymetrixCelFile", function(this, reference, ..., what="M") {
if (identical(what, "M")) {
abline(h=0, lty=1, col="blue")
}
stextChipType(getChipType(this))
stextLabels(this, others=reference)
}, private=TRUE)
setMethodS3("plotMvsA", "AffymetrixCelFile", function(this, reference, indices=NULL, pch=176, xlim=c(0,16), ylim=c(-1,1)*diff(xlim), xlab=expression(A==1/2%*%log[2](y[1]*y[2])), ylab=expression(M==log[2](y[1]/y[2])), ..., annotate=TRUE) {
ma <- getAm(this, reference, indices=indices)
plot(ma, pch=pch, xlab=xlab, ylab=ylab, xlim=xlim, ylim=ylim, ...)
if (annotate) {
annotateMvsA(this, reference)
stextSize(this, size=nrow(ma))
}
this$lastPlotData <- ma
invisible(ma)
})
setMethodS3("smoothScatterMvsA", "AffymetrixCelFile", function(this, reference, indices=NULL, pch=176, xlim=c(0,16), ylim=c(-1,1)*diff(xlim), xlab=expression(A==1/2%*%log[2](y[1]*y[2])), ylab=expression(M==log[2](y[1]/y[2])), ..., annotate=TRUE) {
ma <- getAm(this, reference, indices=indices)
smoothScatter(ma, pch=pch, xlab=xlab, ylab=ylab, xlim=xlim, ylim=ylim, ...)
if (annotate) {
annotateMvsA(this, reference)
stextSize(this, size=nrow(ma))
}
this$lastPlotData <- ma
invisible(ma)
})
setMethodS3("plotMvsX", "AffymetrixCelFile", function(this, reference, x, indices=NULL, pch=176, ylim=c(-1,1)*2, ylab=NULL, ..., what=c("M", "A"), add=FALSE, annotate=!add) {
what <- match.arg(what)
ma <- getAm(this, reference, indices=indices, zeros=TRUE)
nobs <- nrow(ma)
if (nobs == 0)
throw("Cannot plot M vs X because there is not non-zero data.")
if (nobs != length(x)) {
throw("The number of log-ratios does not match the number of elements in argument 'x': ", length(nobs), " != ", length(x))
}
if (what == "M") {
ylab <- expression(M==log[2](y1/y2))
} else {
ma <- ma[,2:1]
ylab <- expression(A==1/2%*%log[2](y1*y2))
}
if (add) {
points(x, ma[,1], pch=pch, ...)
} else {
plot(x, ma[,1], pch=pch, ylim=ylim, ylab=ylab, ...)
if (annotate) {
annotateMvsA(this, reference, what=what)
stextSize(this, size=length(x))
}
}
ma <- cbind(x=x, ma)
this$lastPlotData <- ma
invisible(ma)
})
setMethodS3("highlight", "AffymetrixCelFile", function(this, indices=NULL, ...) {
data <- this$lastPlotData
if (!is.null(indices))
data <- data[indices,,drop=FALSE]
points(data[,1:2], ...)
invisible(data)
}, protected=TRUE)
setMethodS3("image270", "AffymetrixCelFile", function(this, xrange=c(0,Inf), yrange=c(0,Inf), takeLog=TRUE, interleaved=FALSE, ..., field=c("intensities", "stdvs", "pixels"), col=gray.colors(256), main=getName(this)) {
rotate270 <- function(x, ...) {
x <- t(x)
nc <- ncol(x)
if (nc < 2) return(x)
x[,nc:1,drop=FALSE]
}
field <- match.arg(field)
suppressWarnings({
y <- readRawDataRectangle(this, xrange=xrange, yrange=yrange,
fields=field, ..., drop=TRUE)
})
nr <- nrow(y)
if (interleaved) {
idxEven <- which((1:nr) %% 2 == 0)
y[idxEven-1,] <- y[idxEven,]
}
suppressWarnings({
if (takeLog) {
image(log2(rotate270(y)), col=col, ..., axes=FALSE, main=main)
} else {
image(rotate270(y), col=col, ..., axes=FALSE, main=main)
}
})
if (is.null(xrange) || xrange[2] == Inf)
xrange <- c(0,ncol(y)-1)
if (is.null(yrange) || yrange[2] == Inf)
yrange <- c(0,nrow(y)-1)
cdf <- getCdf(this)
dim <- paste(getDimension(cdf), collapse="x")
label <- sprintf("Chip type: %s [%s]", getChipType(this), dim)
text(x=0, y=0, labels=label, adj=c(0,1.2), cex=0.8, xpd=TRUE)
label <- sprintf("(%d,%d)", as.integer(xrange[1]), as.integer(yrange[1]))
text(x=0, y=1, labels=label, adj=c(0,-0.7), cex=0.8, xpd=TRUE)
label <- sprintf("(%d,%d)", as.integer(xrange[2]), as.integer(yrange[2]))
text(x=1, y=0, labels=label, adj=c(1,1.2), cex=0.8, xpd=TRUE)
invisible(y)
})
setMethodS3("getImage", "AffymetrixCelFile", function(this, other=NULL, transforms=list(sqrt), xrange=c(0,Inf), yrange=xrange, zrange=c(0,sqrt(2^16)), field=c("intensities", "stdvs", "pixels"), zoom=1, ..., readRectFcn=NULL, verbose=FALSE) {
readRectangleByField <- function(this, other=NULL, xrange, yrange, ...) {
suppressWarnings({
y <- readRawDataRectangle(this, xrange=xrange, yrange=yrange,
fields=field, ..., drop=TRUE)
})
if (is.null(other)) {
} else {
if (inherits(other, "AffymetrixCelFile")) {
suppressWarnings({
yR <- readRawDataRectangle(other, xrange=xrange, yrange=yrange,
fields=field, ..., drop=TRUE)
})
} else {
yR <- other
}
y <- y/yR
}
y
}
if (!is.null(other)) {
if (inherits(other, "AffymetrixCelFile")) {
hdr1 <- getHeader(this)
hdr2 <- getHeader(other)
fields <- c("rows", "cols")
if (!identical(hdr1[fields], hdr2[fields])) {
throw("Argument 'other' contains an ", class(other)[1], " with a dimension not compatible with the main ", class(this)[1], "")
}
} else {
throw("Argument 'other' is of an unknown class: ", other)
}
}
field <- match.arg(field)
zoom <- Arguments$getDouble(zoom, range=c(0,Inf))
if (is.null(readRectFcn)) {
readRectFcn <- readRectangleByField
} else if (!is.function(readRectFcn)) {
throw("Argument 'readRectFcn' is not a function: ", readRectFcn)
}
verbose <- Arguments$getVerbose(verbose)
verbose && enter(verbose, "Getting CEL image")
verbose && enter(verbose, "Reading CEL image")
y <- readRectFcn(this, other=other, xrange=xrange, yrange=yrange, ...)
verbose && str(verbose, y)
verbose && summary(verbose, as.vector(y[is.finite(y) & (y != 0)]))
verbose && printf(verbose, "RAM: %s\n", hsize(object.size(y), digits = 2L, standard = "IEC"))
verbose && exit(verbose)
verbose && enter(verbose, "Creating Image")
img <- getImage(y, transforms=transforms, scale=zoom, lim=zrange, ...,
verbose=less(verbose, 1))
verbose && print(verbose, img)
verbose && exit(verbose)
verbose && exit(verbose)
attr(img, "field") <- field
img
})
setMethodS3("plotImage", "AffymetrixCelFile", function(this, ...) {
img <- getImage(this, ...)
display(img);
invisible(img)
})
setMethodS3("writeImage", "AffymetrixCelFile", function(this, filename=NULL, fullname=NULL, tags=c("*", "sqrt", "gray"), imgFormat="png", path=NULL, field=c("intensities", "stdvs", "pixels"), ..., skip=TRUE, verbose=FALSE) {
if (is.null(path)) {
rootPath <- "reports"
path <- getPath(this)
parent <- getParent(path);
parent <- getParent(path);
parts <- unlist(strsplit(basename(parent), split=","))
dataSet <- parts[1]
dataSetTags <- parts[-1]
if (length(dataSetTags) == 0) {
dataSetTags <- "raw"
} else {
dataSetTags <- paste(dataSetTags, collapse=",")
}
chipType <- getChipType(this, fullname=FALSE)
set <- "spatial"
path <- filePath(rootPath, dataSet, dataSetTags, chipType, set)
}
path <- Arguments$getWritablePath(path)
tags <- Arguments$getCharacters(tags)
verbose <- Arguments$getVerbose(verbose)
if ("*" %in% tags) {
idx <- match("*", tags)
tags[idx] <- field
tags <- locallyUnique(tags)
}
verbose && enter(verbose, "Writing CEL image to file")
if (is.null(fullname)) {
fullname <- getFullName(this)
}
fullname <- paste(c(fullname, tags), collapse=",")
if (is.null(filename)) {
filename <- sprintf("%s.%s", fullname, imgFormat)
}
pathname <- Arguments$getWritablePathname(filename, path=path)
verbose && cat(verbose, "Pathname: ", pathname)
if (!skip || !isFile(pathname)) {
verbose && enter(verbose, "Getting image")
img <- getImage(this, ..., verbose=less(verbose))
verbose && cat(verbose, "Image object:")
verbose && print(verbose, img)
verbose && exit(verbose)
verbose && enter(verbose, "Writing image")
writeImage(img, file=pathname)
verbose && exit(verbose)
}
verbose && exit(verbose)
pathname
}) |
library(fansi)
old_max <- fansi:::set_int_max(15)
unitizer_sect('tabs', {
tabs_as_spaces("\t1234567")
tryCatch(tabs_as_spaces("\t12345678"), error=conditionMessage)
invisible(fansi:::set_int_max(12))
tabs_as_spaces(c("\t", "\t123"))
})
unitizer_sect('wrap', {
invisible(fansi:::set_int_max(15))
string <- '0123456789'
strwrap_ctl(string, 16)
strwrap2_ctl(string, 16, pad.end=' ')
tce(strwrap2_ctl(string, 17, pad.end=' '))
strwrap_ctl(string, 16, prefix='-----')
tce(strwrap_ctl(string, 16, prefix='------'))
strwrap_ctl(string, 16, indent=5)
tce(strwrap_ctl(string, 16, indent=6))
strwrap_ctl(string, 16, indent=2, prefix='---')
tce(strwrap_ctl(string, 16, indent=3, prefix='---'))
string2 <- '012345678901234'
string3 <- '0123456789012345'
strwrap_ctl(string2, 16)
tce(strwrap_ctl(string3, 16))
string4 <- '\033[31m0123456789'
tce(strwrap_ctl(string4, 16))
invisible(fansi:::set_int_max(9))
tce(strwrap_ctl("A\033[31m a", 5))
})
unitizer_sect('html', {
invisible(fansi:::set_int_max(38))
sgr_to_html("\033[31ma")
tce(sgr_to_html("\033[31mab"))
tce(sgr_to_html("\033[31m\033[42mhello"))
invisible(fansi:::set_int_max(57))
tce(sgr_to_html("\033[31m\033[42mhello", classes=TRUE))
invisible(fansi:::set_int_max(58))
(x <- sgr_to_html("\033[31m\033[42mhello", classes=TRUE))
nchar(x)
invisible(fansi:::set_int_max(4))
tce(sgr_to_html("hello"));
tce(html_esc("hello"));
tce(html_esc("<"));
tce(html_esc("<!"));
tce(html_esc("&"));
tce(html_esc("'"));
})
unitizer_sect('unhandled', {
invisible(fansi:::set_int_max(10))
string <- paste0(rep("\a", 10), collapse="")
unhandled_ctl(string)
tcw(unhandled_ctl(c('\a', string)))
suppressWarnings(unhandled_ctl(c('\a', string)))
})
unitizer_sect('size buffer', {
invisible(fansi:::set_int_max(old_max))
fansi:::size_buff(c(0L, 127L, 128L, 64L, 200L, 1024L))
fansi:::size_buff(c(0L, 127L, -128L))
invisible(fansi:::set_int_max(130))
fansi:::size_buff(c(0L, 127L, 128L, 64L, 200L, 1024L))
invisible(fansi:::set_int_max(64))
fansi:::size_buff(c(0L, 32L, 63L, 64L))
fansi:::size_buff(c(0L, 32L, 63L, 65L))
invisible(fansi:::set_int_max(old_max))
dat <- fansi:::size_buff_prot_test()
dat['first', 'self'] == dat['smaller 1.0', 'self']
dat['new buff', 'prev'] == dat['grow 1.0', 'self']
dat['new buff', 'prev'] != dat['new buff', 'self']
dat['smaller 1.1', 'self'] == dat['grow 1.0', 'self']
dat['smaller 2.0', 'self'] == dat['new buff', 'self']
dat['smaller 2.0', 'prev'] == dat['new buff', 'prev']
dat['smaller 2.0', 'prev'] == dat['grow 2.0', 'prev']
dat['grow 1.1', 'prev'] == dat['grow 2.0', 'self']
dat['grow 2.1', 'prev'] == dat['grow 1.1', 'self']
})
unitizer_sect('misc', {
invisible(fansi:::set_int_max(5))
substr_ctl("\033[43mA B", 5, 5)
substr_ctl("12345", 1, 5)
substr_ctl("123456", 1, 6)
})
fansi:::reset_limits()
unitizer_sect('R_len_t', {
old_rlent <- fansi:::set_rlent_max(5)
tabs_as_spaces("A\tB")
new_rlent <- fansi:::set_rlent_max(old_rlent)
})
fansi:::reset_limits()
unitizer_sect('internal', {
tce(.Call(fansi:::FANSI_buff_test_reset))
tce(.Call(fansi:::FANSI_buff_test_copy_overflow))
tce(.Call(fansi:::FANSI_buff_test_mcopy_overflow))
tce(.Call(fansi:::FANSI_buff_test_fill_overflow))
}) |
"posterior.mode"<-function(x, adjust=0.1, ...){
if(is.mcmc(x)==FALSE){
warning("posterior.mode expecting mcmc object")
}
find.mode<-function(x,adjust,...){
dx<-density(x, adjust=adjust, ...)
dx$x[which.max(dx$y)]
}
apply(as.matrix(x), 2, find.mode, adjust=adjust, ...)
} |
setMethodS3("getAlleleProbePairs", "AffymetrixCdfFile", function(this, units=NULL, ignoreOrder=TRUE, force=FALSE, verbose=FALSE, ...) {
verbose <- Arguments$getVerbose(verbose)
if (verbose) {
pushState(verbose)
on.exit(popState(verbose))
}
verbose && enter(verbose, "Identifying the probes stratified by allele basepairs")
on.exit(verbose && exit(verbose))
chipType <- getChipType(this)
key <- list(method="getAlleleProbePairs", class=class(this)[1], version="2008-02-27", chipType=chipType, units=units, ignoreOrder=ignoreOrder)
if (getOption(aromaSettings, "devel/useCacheKeyInterface", FALSE)) {
key <- getCacheKey(this, method="getAlleleProbePairs", chipType=chipType, units=units, ignoreOrder=ignoreOrder)
}
dirs <- c("aroma.affymetrix", chipType)
if (!force) {
probeSets <- loadCache(key=key, dirs=dirs)
if (!is.null(probeSets)) {
verbose && cat(verbose, "Loaded from file cache")
gc <- gc()
verbose && print(verbose, gc)
return(probeSets)
}
}
cdfFile <- getPathname(this)
verbose && enter(verbose, "Loading all possible allele basepairs")
verbose && enter(verbose, "Identifying compatible SNP units")
types <- getUnitTypes(this, verbose=less(verbose, 1))
unitsAll <- which(types == 2)
verbose && cat(verbose, "Number of SNP units: ", length(unitsAll))
unitSizes <- nbrOfGroupsPerUnit(this, units=unitsAll)
verbose && cat(verbose, "Detected unit sizes:")
verbose && print(verbose, table(unitSizes))
unitsAll <- unitsAll[unitSizes %in% c(2,4)]
unitSizes <- NULL
verbose && cat(verbose, "Number of SNP units with 2 or 4 groups: ",
length(unitsAll))
verbose && exit(verbose)
gc <- gc()
if (!is.null(units)) {
unitsAll <- intersect(unitsAll, units)
}
units <- unitsAll
unitsAll <- NULL
nunits <- length(units)
verbose && cat(verbose, "Number of SNP units to query: ", nunits)
if (nunits == 0)
return(NULL)
verbose && enter(verbose, "Retrieving group names")
groupNames <- .readCdfGroupNames(cdfFile, units=units)
names(groupNames) <- NULL
levels <- as.integer(1:4)
names(levels) <- c("A", "C", "G", "T")
groupNames <- lapply(groupNames, FUN=function(s) {
s <- levels[s]
names(s) <- NULL
s
})
uGroupNames <- unique(groupNames)
o <- order(as.integer(sapply(uGroupNames, FUN=paste, collapse="")))
uGroupNames <- uGroupNames[o]
o <- NULL
gc <- gc()
verbose && print(verbose, gc)
verbose && cat(verbose, "Unique group names:")
verbose && str(verbose, lapply(uGroupNames, FUN=function(x) names(levels[x])), vec.len=8)
verbose && exit(verbose)
verbose && exit(verbose)
verbose && enter(verbose, "Loading cell indices for probepairs for requested units")
nbrOfUnitsPerChunk <- 100e3
nunits <- length(units)
nbrOfChunks <- ceiling(nunits / nbrOfUnitsPerChunk)
uu <- 1:nbrOfUnitsPerChunk
unitsTodo <- units
count <- 1
cells0 <- list()
cdfAll <- list()
while (length(unitsTodo) > 0) {
verbose && enter(verbose, sprintf("Chunk
if (length(unitsTodo) <= nbrOfUnitsPerChunk)
uu <- 1:length(unitsTodo)
verbose && cat(verbose, "Units: ")
verbose && str(verbose, unitsTodo[uu])
cdfAll0 <- .readCdfCellIndices(cdfFile, units=unitsTodo[uu], stratifyBy="pm")
unitsTodo <- unitsTodo[-uu]
names(cdfAll0) <- NULL
cells0[[count]] <- unlist(cdfAll0, use.names=FALSE)
cdfAll0 <- lapply(cdfAll0, FUN=function(unit) {
groups <- .subset2(unit, 1)
names(groups) <- NULL
lapply(groups, FUN=.subset2, 1)
})
gc <- gc()
cdfAll <- c(cdfAll, cdfAll0)
cdfAll0 <- NULL
gc <- gc()
verbose && print(verbose, gc)
count <- count + 1
verbose && exit(verbose)
}
units <- unitsTodo <- uu <- NULL
gc <- gc()
verbose && print(verbose, gc)
cells0 <- unlist(cells0, use.names=FALSE)
gc <- gc()
cells0 <- sort(cells0)
gc <- gc()
nbrOfCells <- length(cells0)
verbose && printf(verbose, "Identified %d (PM_A,PM_B) pairs in %d units, i.e. on average %.2g probe pairs/units\n", round(nbrOfCells/2), nunits, (nbrOfCells/2)/nunits)
if (length(cdfAll) != nunits) {
throw("Internal error: Expected ", nunits, " units, but got ", length(cdfAll))
}
verbose && exit(verbose)
verbose && enter(verbose, "Stratifying by unique allele basepairs")
probeSets <- vector("list", length(uGroupNames))
for (kk in 1:length(uGroupNames)) {
name <- uGroupNames[[kk]]
basepair <- paste(names(levels)[name[1:2]], collapse="")
verbose && enter(verbose, sprintf("Allele basepair %s (%d of %d)", basepair, kk, length(uGroupNames)))
idx <- sapply(groupNames, FUN=identical, name)
idx <- which(idx)
if (verbose) {
bpNames <- matrix(names(levels)[name], nrow=2)
bpNames <- paste(bpNames[1,], bpNames[2,], sep="")
verbose && cat(verbose, "Allele pairs: ", paste(bpNames, collapse=","))
bpNames <- NULL
verbose && cat(verbose, "Number of units: ", length(idx))
}
cdf <- cdfAll[idx]
cdfAll[idx] <- NA;
idx <- NULL
cdf0 <- vector("list", length=length(name))
for (gg in 1:length(name)) {
cdf0[[gg]] <- unlist(lapply(cdf, FUN=.subset2, gg), use.names=FALSE)
}
cdf <- NULL
probeSets[[kk]] <- cdf0
cdf0 <- NULL
names(probeSets)[kk] <- basepair
verbose && exit(verbose)
}
cdfAll <- NULL
gc <- gc()
verbose && print(verbose, gc)
verbose && exit(verbose)
verbose && enter(verbose, "Asserting correctness part I", level=-20)
nbrOfCells2 <- length(unlist(probeSets, use.names=FALSE))
if (nbrOfCells2 != nbrOfCells) {
throw("Internal error: Excepted ", nbrOfCells, " indices: ", nbrOfCells2)
}
if (!identical(sort(unlist(probeSets, use.names=FALSE)), cells0)) {
throw("Internal error: Mismatching probes.")
}
verbose && exit(verbose)
verbose && enter(verbose, "Putting equivalent groups together")
probeSets2 <- list()
for (kk in 1:length(probeSets)) {
bp <- names(probeSets)[kk]
value <- probeSets[[kk]]
nbrOfPairs <- length(value)/2
for (ll in seq_len(nbrOfPairs)) {
value2 <- probeSets2[[bp]]
if (is.null(value2))
value2 <- vector("list", length=2)
value2[[1]] <- c(value2[[1]], value[[1]])
value2[[2]] <- c(value2[[2]], value[[2]])
probeSets2[[bp]] <- value2
value2 <- NULL
bp <- strsplit(bp, split="")[[1]]
bp <- c(A="T", C="G", G="C", T="A")[bp]
bp <- paste(bp, collapse="")
value <- value[-(1:2)]
}
}
verbose && cat(verbose, "Probe pairs: ",
paste(sort(names(probeSets2)), collapse=", "))
verbose && exit(verbose)
verbose && enter(verbose, "Asserting correctness part II", level=-20)
nbrOfCells2 <- length(unlist(probeSets, use.names=FALSE))
if (nbrOfCells2 != nbrOfCells) {
throw("Internal error: Excepted ", nbrOfCells, " indices: ", nbrOfCells2)
}
if (!identical(sort(unlist(probeSets, use.names=FALSE)), cells0)) {
throw("Internal error: Mismatching probes.")
}
verbose && exit(verbose)
if (ignoreOrder) {
verbose && enter(verbose, "Putting AB and BA groups together")
probeSets <- NULL
gc <- gc()
pairs <- strsplit(names(probeSets2), split="")
pairs <- lapply(pairs, FUN=function(x) paste(sort(x), collapse=""))
pairs <- unlist(pairs)
uPairs <- sort(unique(pairs))
verbose && cat(verbose, "Probe pairs (ignoring order): ",
paste(uPairs, collapse=", "))
probeSets <- list()
for (pair in uPairs) {
idx <- which(pairs == pair)
basepairs <- sort(names(probeSets2)[idx])
probeSets[[pair]] <- probeSets2[basepairs]
}
probeSets2 <- NULL
verbose && exit(verbose)
verbose && enter(verbose, "Combining AB and BA groups")
for (kk in 1:length(probeSets)) {
values <- probeSets[[kk]]
if (length(values) == 1) {
values <- values[[1]]
} else {
values[[1]][[1]] <- c(values[[1]][[1]], values[[2]][[2]])
values[[1]][[2]] <- c(values[[1]][[2]], values[[2]][[1]])
values <- values[[1]]
}
probeSets[[kk]] <- values
}
values <- NULL
verbose && exit(verbose)
} else {
probeSets <- probeSets2
probeSets2 <- NULL
}
verbose && enter(verbose, "Asserting correctness part III", level=-20)
nbrOfCells2 <- length(unlist(probeSets, use.names=FALSE))
if (nbrOfCells2 != nbrOfCells) {
throw("Internal error: Excepted ", nbrOfCells, " indices: ", nbrOfCells2)
}
if (!identical(sort(unlist(probeSets, use.names=FALSE)), cells0)) {
throw("Internal error: Mismatching probes.")
}
gc <- gc()
verbose && exit(verbose)
verbose && enter(verbose, "Reformatting to matrices")
for (kk in 1:length(probeSets)) {
verbose && enter(verbose, sprintf("Group
values <- probeSets[[kk]]
values <- matrix(c(values[[1]], values[[2]]), ncol=2)
colnames(values) <- strsplit(names(probeSets)[kk], split="")[[1]]
o <- order(values[,1])
values <- values[o,]
probeSets[[kk]] <- values
verbose && exit(verbose)
}
values <- o <- NULL
gc <- gc()
if (isVisible(verbose, level=-20))
verbose && str(verbose, probeSets, level=-20)
verbose && exit(verbose)
verbose && enter(verbose, "Asserting correctness part IV", level=-20)
nbrOfCells2 <- length(unlist(probeSets, use.names=FALSE))
if (nbrOfCells2 != nbrOfCells) {
throw("Internal error4: Excepted ", nbrOfCells, " indices: ", nbrOfCells2)
}
if (!identical(sort(unlist(probeSets, use.names=FALSE)), cells0)) {
throw("Internal error: The identified set of indices for various allele probe pairs does not match the original set of cell indices.")
}
verbose && exit(verbose)
verbose && enter(verbose, "Identifying indices for all non-SNP PM cells")
unitTypes <- getUnitTypes(this, verbose=less(verbose,1));
verbose && cat(verbose, "Table of identified unit types:")
verbose && print(verbose, table(unitTypes))
nonSnpUnits <- which(unitTypes != 2);
if (length(nonSnpUnits) > 0) {
cells <- getCellIndices(this, units=nonSnpUnits,
useNames=FALSE, unlist=TRUE, verbose=less(verbose,1))
} else {
cells <- NULL
}
verbose && cat(verbose, "Identified non-SNP units:")
verbose && str(verbose, cells)
probeSets$nonSNPs <- cells
cells <- NULL
verbose && exit(verbose)
comment <- key[c("method", "class", "chipType")]
comment <- paste(names(comment), comment, sep="=")
comment <- paste(comment, collapse=", ")
saveCache(probeSets, key=key, comment=comment, dirs=dirs)
probeSets
}, private=TRUE) |
discretize <- function(x, method = "frequency", breaks = 3,
labels = NULL, include.lowest = TRUE, right = FALSE, dig.lab = 3,
ordered_result = FALSE, infinity = FALSE, onlycuts = FALSE, categories = NULL, ...) {
if(!is.null(categories)) {
warning("Parameter categories is deprecated. Use breaks instead! Also, the default method is now frequency!")
breaks <- categories
}
methods <- c("interval", "frequency", "cluster", "fixed")
method <- methods[pmatch(tolower(method), methods)]
if(is.na(method)) stop("Unknown method!")
if(method == "fixed" && length(breaks) < 2)
stop("fixed needs at least two values for breaks.")
if(method != "fixed" && (length(breaks) != 1 || breaks < 1))
stop("breaks needs to be a single positive integer for this method.")
breaks <- switch(method,
interval = seq(from=min(x, na.rm=TRUE), to=max(x, na.rm=TRUE),
length.out=breaks+1),
frequency = stats::quantile(x, probs = seq(0,1, length.out = breaks+1),
na.rm = TRUE),
cluster = {
cl <- stats::kmeans(stats::na.omit(x), breaks, ...)
centers <- sort(cl$centers[,1])
as.numeric(c(min(x, na.rm=TRUE), head(centers,
length(centers)-1) + diff(centers)/2, max(x, na.rm=TRUE)))
},
fixed = breaks
)
if(any(duplicated(breaks))){
warning("The calculated breaks are: ", paste(breaks, collapse = ", "), "\n Only unique breaks are used reducing the number of intervals. Look at ? discretize for details.")
breaks <- unique(breaks)
if(length(breaks) < 2) stop("Less than 2 uniques breaks left. Maybe the variable has only one value!")
}
if(infinity) {
breaks[1] <- -Inf
breaks[length(breaks)] <- Inf
}
if(onlycuts) return(as.vector(breaks))
structure(
cut(x, breaks = breaks, labels = labels,
include.lowest = include.lowest, right = right,
ordered_result = ordered_result),
"discretized:breaks" = as.vector(breaks),
"discretized:method" = method
)
}
discretizeDF <- function(df, methods = NULL, default = NULL) {
if(is.data.frame(methods)) return(.rediscretizeDF(methods, df))
for(i in colnames(df)) {
if(!is.numeric(df[[i]])) next
args <- if(is.null(methods[[i]])) default else methods[[i]]
if(!is.null(args) && (is.null(args$method) || args$method == "none")) next
if(is(err <- try(
df[[i]] <- do.call("discretize", c(list(x = df[[i]]), args)),
silent = TRUE), "try-error")) stop("Problem with column ", i, "\n", err)
}
df
}
.rediscretizeDF <- function(data, newdata) {
if(!all(colnames(data) == colnames(newdata))) stop("column names in the new data are not the same as in the discretized data.")
cps <- lapply(data, FUN = function(x) {
breaks <- attr(x, "discretized:breaks")
if(is.null(breaks)) NULL
else list(breaks = breaks, method = "fixed", labels = levels(x))
})
discretizeDF(newdata, methods = cps, default = list(method = "none"))
} |
"copy.gp" <-
function(object,object2=NULL,...){
nullFlag=FALSE
if(is.null(object2)){
object2=new.env(parent=globalenv())
class(object2)=class(object)
nullFlag=TRUE
}
elements=names(object)
for(index in 1:length(elements)){
assign(elements[index],get(elements[index],envir=object,inherits=FALSE),envir=object2)
}
if(nullFlag){
return(object2)
} else{
return(NULL)
}
} |
zones_to_raster = function(v, resolution, variables, ...){
v_extent = raster::extent(v)
v_crs = sf::st_crs(v)$proj4string
template_raster = raster::raster(v_extent,
crs = v_crs,
resolution = resolution)
v$id = seq_len(nrow(v))
r_id = fasterize::fasterize(v, template_raster, field = "id", ...)
out = if (requireNamespace("pbapply", quietly = TRUE)){
raster::stack(pbapply::pblapply(variables, zone_to_raster,
v = v, resolution = resolution,
id_raster = r_id, ...))
} else {
raster::stack(lapply(variables, zone_to_raster,
v = v, resolution = resolution,
id_raster = r_id, ...))
}
}
zone_to_raster = function(variable, v, resolution, id_raster, ...){
freq_df = as.data.frame(raster::freq(id_raster))
vals_df = sf::st_drop_geometry(v[c(variable, "id")])
names(vals_df) = c("pop", "value")
df = merge(freq_df, vals_df, by = "value", all.x = TRUE)
df$density = df$pop / df$count
rc_mat = df[c("value", "density")]
r = raster::reclassify(id_raster, rc_mat)
names(r) = variable
r
} |
context("Test: rhScore() ")
data(PhyloExpressionSetExample)
data(DivergenceExpressionSetExample)
data(PhyloExpressionSetExample)
data(DivergenceExpressionSetExample)
tai.vals <- TAI(PhyloExpressionSetExample)
tdi.vals <- TDI(DivergenceExpressionSetExample)
test_that("rhScore computes correct reductive hourglass scores...",{
expect_equal(rhScore(tai.vals,
early = 1:2, mid = 3:5, late = 6:7,method = "min", scoringMethod = "mean-mean"),min(c(mean(tai.vals[1:2] - mean(tai.vals[3:5])), mean(tai.vals[6:7] - mean(tai.vals[3:5])))))
expect_equal(rhScore(tdi.vals,
early = 1:2, mid = 3:5, late = 6:7,method = "min", scoringMethod = "mean-mean"),min(c(mean(tdi.vals[1:2] - mean(tdi.vals[3:5])), mean(tdi.vals[6:7] - mean(tdi.vals[3:5])))))
}) |
setMethod("merge", signature(x = "Speclib", y = "Speclib"),
function(x, y, ...)
{
if (dim(x)[2] != dim(y)[2])
stop("Dimensions of Speclibs do not fit")
wl <- wavelength(x)
if (any(wl!=wavelength(y)))
stop("Wavelengths differ")
if (nrow(y@SI) == dim(y)[1])
{
if (nrow(x@SI) == dim(x)[1])
{
SI(x) <- rbind(SI(x),SI(y))
} else {
warning("x does not have proper SI definition. SI information will be lost")
}
} else {
warning("y does not have proper SI definition. SI information will be lost")
}
ids <- c(idSpeclib(x), idSpeclib(y))
spectra(x) <- as.matrix(rbind(spectra(x),spectra(y)))
idSpeclib(x) <- as.character(ids)
dots <- list(...)
if (length(dots) > 0)
{
oldhist <- usagehistory(x)
for (i in 1:length(dots))
{
stopifnot(is.speclib(dots[[i]]))
x <- merge(x, dots[[i]])
}
usagehistory(x) <- NULL
usagehistory(x) <- oldhist
}
uh <- as.character(.get_args(-1))
usagehistory(x) <- paste0("Speclibs '", paste(uh[-1], collapse = "', '"), "' merged")
return(x)
}
) |
setClass(Class="NpdeObject",
representation=representation(
data="NpdeData",
results="NpdeRes",
sim.data="NpdeSimData",
options="list",
prefs="list"
),
validity=function(object){
validObject(object@data)
validObject([email protected])
return(TRUE)
}
)
setMethod(
f="initialize",
signature="NpdeObject",
definition= function (.Object,data,sim.data,options=list(),prefs=list()){
.Object@data<-data
[email protected]<-sim.data
.Object@results<-new(Class="NpdeRes")
.Object@results["ntot.obs"]<-data["ntot.obs"]
.Object@results["not.miss"]<-data["not.miss"]
.Object@results["icens"]<-data["icens"]
opt<-npdeControl()
if(length(options)>0) {
for(i in names(options)) {
if(length(grep(i,names(opt)))==0) message(paste("Option",i, "not found, check spelling")) else
opt[i]<-options[i]
}
i1<-grep("namsav",names(options))
if(length(i1)!=0 && !is.na(i1)) {
opt$namres<-paste(options[i1],".npde",sep="")
opt$namgr<-paste(options[i1],".",opt$type.graph,sep="")
}
}
opt<-check.control.options(opt)
.Object@options<-opt
graph.opt<-set.plotoptions(.Object)
if(length(prefs)>0) {
for(i in names(prefs)) {
if(length(grep(i,names(graph.opt)))==0) message(paste("Graphical option",i, "not found, check spelling")) else graph.opt[i]<-prefs[i]
}
}
.Object@prefs<-graph.opt
validObject(.Object)
return (.Object )
}
)
setMethod(
f ="[",
signature = "NpdeObject" ,
definition = function (x,i,j,drop ){
switch (EXPR=i,
"data"={return(x@data)},
"sim.data"={return([email protected])},
"results"={return(x@results)},
"options"={return(x@options)},
"prefs"={return(x@prefs)},
stop("No such attribute\n")
)
}
)
setReplaceMethod(
f ="[",
signature = "NpdeObject" ,
definition = function (x,i,j,value){
switch (EXPR=i,
"data"={x@data<-value},
"sim.data"={[email protected]<-value},
"results"={x@results<-value},
"options"={x@options<-value},
"prefs"={x@prefs<-value},
stop("No such attribute\n")
)
validObject(x)
return(x)
}
) |
mipplot_interactive_line <- function(D, language = "en") {
model <- period <- NULL
name_of_input_df = as.character(substitute(D))
D <- correct_format_of_iamc_dataframe(D)
region_list <- levels(D$region)
var_list <- levels(D$variable)
model_list <- levels(D$model)
scenario_list <- levels(D$scenario)
period_list <- levels(as.factor(D$period))
ui <- fluidPage(
shinyalert::useShinyalert(),
titlePanel("mipplot"),
sidebarLayout(
sidebarPanel(
selectInput("region", "region:",
choices = c("Choose region" = "", region_list)
),
selectInput("variable", "variable:",
choices = c("Choose variable" = "", var_list)
),
shinyWidgets::pickerInput("model",
label = "model:",
choices = get_model_name_list(D),
multiple = TRUE,
options = list(
`actions-box` = TRUE,
`title` = "Choose model"
)),
shinyWidgets::pickerInput("scenario",
label = "scenario:",
choices = get_scenario_name_list(D),
multiple = TRUE,
options = list(
`actions-box` = TRUE,
`title` = "Choose scenario"
)),
shinyWidgets::sliderTextInput(
inputId = "period",
label = "period:",
choices = period_list,
selected = c(head(period_list, n = 1),
tail(period_list, n = 1))
),
shiny::checkboxInput(
inputId = "showLegend",
label = "show legend",
value = TRUE
),
shiny::checkboxInput(
inputId = "printCredit",
label = "print credit",
value = TRUE
),
checkboxInput(
inputId = "rotateYearLabel45Degrees",
label = "roate year label 45 degrees",
value = FALSE),
selectInput("language", "language:",
choices = c(
"Chinese(Simplified)" = "zh-cn",
"Chinese(Traditional)" = "zh-tw",
"English" = "en",
"Japanese" = "jp",
"Spanish" = "es"),
selected = language),
shiny::div(
class = "form-group shiny-input-container",
submitButton(text = "Apply Changes", icon = NULL, width = NULL)
),
shiny::div(
class = "form-group shiny-input-container",
style = "color:red;",
shiny::textOutput("warning_message_label")
),
shiny::div(
class = "form-group shiny-input-container",
shiny::tags$label(class="control-label", "code:"),
shiny::tags$pre(
style = "overflow: scroll; max-height: 10em; white-space: pre-line;",
shiny::textOutput(
"code_to_reproduce_plot", inline = TRUE)
)
)
),
mainPanel(
plotOutput("line_plot")
)
)
)
server <- function(input, output) {
output$code_to_reproduce_plot <- shiny::reactive({
generate_code_to_plot_line(input, name_of_input_df)
})
output$line_plot <- renderPlot({
output$warning_message_label <- shiny::reactive("")
D_subset = D %>%
dplyr::filter( model %in% input$model ) %>%
dplyr::filter(input$period[1] <= period) %>%
dplyr::filter(period <= input$period[2])
withCallingHandlers({
subset_plot <- mipplot_line(D_subset,
variable = input$variable,
scenario = input$scenario,
region = input$region,
legend = input$showLegend,
axis_year_text_angle = ifelse(input$rotateYearLabel45Degrees, 45, 0),
language = input$language)
}, warning = function(e) {
if(grepl("too many scenarios", e$message, fixed=TRUE)) {
shinyalert::shinyalert(
title = "Info",
text = e$message,
closeOnEsc = TRUE,
closeOnClickOutside = TRUE,
html = FALSE,
type = "info",
showConfirmButton = FALSE,
showCancelButton = FALSE,
timer = 2000,
imageUrl = "",
animation = TRUE
)
output$warning_message_label <- shiny::reactive({
e$message
})
}
})
if (input$printCredit) {
subset_plot <- add_credit_to_list_of_plot(subset_plot)
}
validate(
need(
length(input$variable) > 0 && input$variable != "" &&
length(input$region) > 0 && input$region != "" &&
length(input$model) > 0 && input$model != "" &&
length(input$scenario) > 0 && input$scenario != "",
"Please specify plotting options.")
)
validate(
need(length(subset_plot) > 0, "can't find any data in this condition")
)
subset_plot
},
height = 400, width = 600
)
}
shinyApp(ui, server);
}
get_model_name_list <- function(D) {
return (D %>% dplyr::pull(.data$model) %>% unique() %>% levels())
}
get_scenario_name_list <- function(D) {
return (D %>% dplyr::pull(.data$scenario) %>% unique() %>% levels())
}
generate_code_to_plot_line <- function(input, name_of_iamc_data_variable = "D") {
return(stringr::str_interp(
"data_subset <- ${name_of_iamc_data_variable} %>%
filter( model %in% ${get_string_expression_of_vector_of_strings(input$model)} ) %>%
filter(${input$period[1]} <= period) %>%
filter(period <= ${input$period[2]})
mipplot_line(
data_subset,
variable = ${get_string_expression_of_vector_of_strings(input$variable)},
scenario = ${get_string_expression_of_vector_of_strings(input$scenario)},
region = ${get_string_expression_of_vector_of_strings(input$region)},
legend = ${as.character(input$showLegend)},
axis_year_text_angle = ${ifelse(input$rotateYearLabel45Degrees, 45, 0)},
language = '${input$language}')
"))
} |
"sc.gaussian" <-
function(params){
sigma <- params[p]
mu <- c(X %*% params[-p])
fnb <- dnorm(qb, mu, sigma)
fna <- dnorm(qa, mu, sigma)
dF <- pnorm(qb, mu, sigma) - pnorm(qa, mu, sigma)
sbeta <- colSums(X * (fnb - fna) / dF)
ssigma <- sum((fnb * (qb. - mu) - fna * (qa. - mu)) / (sigma * dF))
c(sbeta, ssigma)
} |
setMethod("show", "pixmap",
function(object){
cat("Pixmap image\n")
cat(" Type :", class(object), "\n")
cat(" Size :", paste(object@size, collapse="x"), "\n")
cat(" Resolution :", paste(object@cellres, collapse="x"), "\n")
cat(" Bounding box :", object@bbox, "\n")
if(is(object, "pixmapIndexed"))
cat(" Nr. of colors :",
length(unique(as(object@index, "vector"))), "of",
length(object@col), "\n")
cat("\n")
})
setMethod("plot", "pixmap",
function(x, y, xlab="", ylab="", axes=FALSE, asp=1, ...){
x = as(x, "pixmapIndexed")
X <- seq(x@bbox[1], x@bbox[3], by=x@cellres[1])
Y <- seq(x@bbox[2], x@bbox[4], by=x@cellres[2])
image(x=X, y=Y, z=t(x@index[nrow(x@index):1,,drop=FALSE]), col=x@col,
xlab=xlab, ylab=ylab, axes=axes, asp=asp, ...)
})
pixmap <- function(data=NULL, nrow=dim(data)[1],
ncol=dim(data)[2],
bbox=NULL, bbcent=FALSE, cellres=NULL)
{
cellres <- rep(cellres, length=2)
if(is.null(bbox)){
if(is.null(cellres))
cellres <- c(1,1)
if(is.null(nrow)){
if(!is.null(ncol))
nrow <- ceiling(length(data)/ncol)
else
stop("Too few dimension attributes (nrow, ncol, bbox)\n")
}
else if(is.null(ncol))
ncol <- ceiling(length(data)/nrow)
if(bbcent)
bbox <- c(1,1,cellres[1]*ncol, cellres[2]*nrow)
else
bbox <- c(0,0,cellres[1]*ncol, cellres[2]*nrow)
}
else{
if(is.null(cellres)){
if(is.null(nrow)){
if(!is.null(ncol))
nrow <- ceiling(length(data)/ncol)
else
stop("Too few dimension attributes (nrow, ncol, bbox)\n")
}
else if(is.null(ncol))
ncol <- ceiling(length(data)/nrow)
cellres = .getCellres(bbox, bbcent, c(nrow, ncol))
}
else{
if(bbcent){
ncol <- (bbox[3]-bbox[1])/cellres[1]+1
nrow <- (bbox[4]-bbox[2])/cellres[2]+1
}
else{
ncol <- (bbox[3]-bbox[1])/cellres[1]
nrow <- (bbox[4]-bbox[2])/cellres[2]
}
}
}
new("pixmap", size=as(c(nrow, ncol),"integer"),
cellres=cellres, bbox=bbox, bbcent=bbcent)
}
pixmapGrey = function(data, ...)
{
z = new("pixmapGrey", pixmap(data, ...))
datamax <- max(data)
datamin <- min(data)
data <- as.numeric(data)
if(datamax>1 || datamin<0)
data <- (data - datamin)/(datamax-datamin)
z@grey = matrix(data, nrow=z@size[1], ncol=z@size[2])
z
}
pixmapRGB = function(data, ...)
{
z = new("pixmapRGB", pixmap(data, ...))
datamax <- max(data)
datamin <- min(data)
data <- as.numeric(data)
if(datamax>1 || datamin<0)
data <- (data - datamin)/(datamax-datamin)
data = array(data, dim=c(z@size[1], z@size[2], 3))
z@red = matrix(data[,,1], nrow=z@size[1], ncol=z@size[2])
z@green = matrix(data[,,2], nrow=z@size[1], ncol=z@size[2])
z@blue = matrix(data[,,3], nrow=z@size[1], ncol=z@size[2])
z
}
pixmapIndexed = function(data, col=NULL, ...)
{
z = new("pixmapIndexed", pixmap(data, ...))
data <- as(data, "integer")
datamin <- min(data)
if(datamin<=0)
data <- data - datamin + 1
datamax <- max(data)
z@index = matrix(data, nrow=z@size[1], ncol=z@size[2])
if(is.null(col))
col <- heat.colors(datamax)
else{
if(is(col,"function"))
col <- col(datamax)
else {
if(length(col) < datamax){
warning("number of of colors smaller than number of data values, recycling\n")
col <- rep(col, length=datamax)
}
}
}
z@col = col
z
}
setAs("pixmapGrey", "pixmapRGB",
function(from, to){
z = new(to, as(from, "pixmap"))
z@red = from@grey
z@green = from@grey
z@blue = from@grey
z@channels = c("red", "green", "blue")
z
})
setAs("pixmapRGB", "pixmapGrey",
function(from, to){
addChannels(from)
})
setAs("pixmapRGB", "pixmapIndexed",
function(from, to){
z = new(to, as(from, "pixmap"))
x = rgb(from@red,from@green,from@blue)
col <- unique(x)
x <- match(x, col)
z@index <- matrix(x, nrow=z@size[1], ncol=z@size[2])
z@col = col
z
})
setAs("pixmapGrey", "pixmapIndexed",
function(from, to){
z = new(to, as(from, "pixmap"))
x = grey(from@grey)
col <- unique(x)
x <- match(x, col)
z@index <- matrix(x, nrow=z@size[1], ncol=z@size[2])
z@col = col
z
})
setAs("pixmapIndexed", "pixmapRGB",
function(from, to){
z = new(to, as(from, "pixmap"))
x <- col2rgb(from@col[from@index])/255
z@red <- matrix(x["red",], nrow=z@size[1], ncol=z@size[2])
z@green <- matrix(x["green",], nrow=z@size[1], ncol=z@size[2])
z@blue <- matrix(x["blue",], nrow=z@size[1], ncol=z@size[2])
z@channels = c("red", "green", "blue")
z
})
setAs("ANY", "pixmapGrey",
function(from, to){
as(as(from, "pixmapRGB"), to)
})
setAs("ANY", "pixmapIndexed",
function(from, to){
as(as(from, "pixmapRGB"), to)
})
setGeneric("addChannels",
function(object, coef=NULL) standardGeneric("addChannels"))
setMethod("addChannels", "pixmapRGB",
function(object, coef=NULL){
if(is.null(coef)) coef = c(0.30, 0.59, 0.11)
z = new("pixmapGrey", object)
z@grey = coef[1] * object@red + coef[2] * object@green +
coef[3] * object@blue
z@channels = "grey"
z
})
setGeneric("getChannels",
function(object, colors="all") standardGeneric("getChannels"))
setMethod("getChannels", "pixmapChannels",
function(object, colors="all"){
for(k in 1:length(colors))
colors[k] = match.arg(colors[k], c("all", object@channels))
if(any(colors=="all")) colors = object@channels
colors = unique(colors)
if(length(colors)>1){
z = array(0, dim=c(object@size, length(colors)))
dimnames(z) = list(NULL, NULL, colors)
for(k in colors){
z[,,k] = slot(object, k)
}
}
else{
z = slot(object, colors)
}
z
})
setMethod("[", "pixmap",
function(x, i, j, ..., drop=FALSE){
if(missing(j))
j = TRUE
if(missing(i))
i = TRUE
osize = x@size
if(is(x, "pixmapIndexed")){
x@index = x@index[i,j,drop=FALSE]
x@size = dim(x@index)
}
else if(is(x, "pixmapChannels")){
for(k in x@channels)
slot(x, k) = slot(x, k)[i,j,drop=FALSE]
x@size = dim(slot(x, k))
}
else
stop(paste("Cannot subset objects of class", class(x)))
bbox = numeric(4)
if(x@bbcent){
b = seq(x@bbox[1], x@bbox[3], length=osize[2])
bbox[c(1,3)] = range(b[j])
b = seq(x@bbox[2], x@bbox[4], length=osize[1])
bbox[c(2,4)] = range(b[i])
}
else{
b = seq(x@bbox[1], x@bbox[3]-x@cellres[1], length=osize[2])
bbox[1] = min(b[j])
bbox[3] = max(b[j]) + x@cellres[1]
b = seq(x@bbox[2], x@bbox[4]-x@cellres[2], length=osize[1])
bbox[2] = min(b[i])
bbox[4] = max(b[i]) + x@cellres[2]
}
x@bbox = bbox
x@cellres <- .getCellres(bbox, x@bbcent, x@size)
x
})
.getCellres = function(bbox, bbcent, size)
{
if(bbcent)
cellres = c((bbox[3]-bbox[1])/(size[2]-1),
(bbox[4]-bbox[2])/(size[1]-1))
else
cellres = c((bbox[3]-bbox[1])/size[2],
(bbox[4]-bbox[2])/size[1])
cellres
}
|
bprecess = function(
ra,
dec,
mu_radec,
parallax = numeric(length(ra)),
rad_vel = numeric(length(ra)),
epoch = 2000) {
n = length( ra )
if(length(rad_vel)!=n )
stop(paste('rad_vel keyword vector must contain ',
n,' values'))
if(!missing(mu_radec) && (length(mu_radec)!=2*n ))
stop('mu_radec keyword (proper motion) be dimensioned (2,' +
n, ')')
radeg = 180/pi
sec_to_radian = 1/radeg/3600
m = cbind( c(+0.9999256795, -0.0111814828, -0.0048590040,
-0.000551, -0.238560, +0.435730) ,
c(+0.0111814828, +0.9999374849, -0.0000271557,
+0.238509, -0.002667, -0.008541) ,
c(+0.0048590039, -0.0000271771, +0.9999881946 ,
-0.435614, +0.012254, +0.002117) ,
c(-0.00000242389840, +0.00000002710544, +0.00000001177742,
+0.99990432, -0.01118145, -0.00485852) ,
c(-0.00000002710544, -0.00000242392702, +0.00000000006585,
+0.01118145, +0.99991613, -0.00002716) ,
c(-0.00000001177742, +0.00000000006585,-0.00000242404995,
+0.00485852, -0.00002717, +0.99996684))
a_dot = 1e-3*c(1.244, -1.579, -0.660 )
ra_rad = ra/radeg
dec_rad = dec/radeg
cosra = cos( ra_rad )
sinra = sin( ra_rad )
cosdec = cos( dec_rad )
sindec = sin( dec_rad )
dec_1950 = dec*0.
ra_1950 = ra*0.
for(i in 1:n) {
a = 1e-6*c( -1.62557, -0.31919, -0.13843)
r0 = c( cosra[i]*cosdec[i], sinra[i]*cosdec[i], sindec[i] )
if(!missing(mu_radec) ){
mu_a = mu_radec[ (2*n-1) ]
mu_d = mu_radec[ 2*n ]
r0_dot = c( -mu_a*sinra[i]*cosdec[i] -
mu_d*cosra[i]*sindec[i] ,
mu_a*cosra[i]*cosdec[i] -
mu_d*sinra[i]*sindec[i] ,
mu_d*cosdec[i] ) +
21.095 * rad_vel[i] * parallax[i] * r0
}
else {
r0_dot = c(0.0, 0.0, 0.0)
}
r_0 = c(r0, r0_dot)
r_1 = r_0 %*% t(m)
r1 = r_1[1:3]
r1_dot = r_1[4:6]
if(!missing(mu_radec) ){
r1 = r1 + sec_to_radian * r1_dot * (epoch - 1950.0)/100.
a = a + sec_to_radian * a_dot * (epoch - 1950.0)/100.
}
x1 = r_1[1]
y1 = r_1[2]
z1 = r_1[3]
rmag = sqrt( x1^2 + y1^2 + z1^2 )
s1 = r1/rmag
s1_dot = r1_dot/rmag
s = s1
for(j in 1:3) {
r = s1 + a - (sum(s * a))*s
s = r/rmag
}
x = r[1]
y = r[2]
z = r[3]
r2 = x^2 + y^2 + z^2
rmag = sqrt( r2 )
if(!missing(mu_radec) ){
r_dot = s1_dot + a_dot - ( sum( s * a_dot))*s
x_dot = r_dot[1] ; y_dot= r_dot[2] ; z_dot = r_dot[3]
mu_radec[(2*n-1)] = ( x*y_dot - y*x_dot) / ( x^2 + y^2)
mu_radec[2*n] = ( z_dot* (x^2 + y^2) - z*(x*x_dot + y*y_dot) ) /
( r2*sqrt( x^2 + y^2) )
}
dec_1950[i] = asin( z / rmag)
ra_1950[i] = atan2( y, x)
if(parallax[i]>0 ){
rad_vel[i] = ( x*x_dot + y*y_dot + z*z_dot )/ (21.095*parallax[i]*rmag)
parallax[i] = parallax[i] / rmag
}
}
neg = (ra_1950<0)
ra_1950[neg] = ra_1950[neg] + 2.*pi
ra_1950 = ra_1950*radeg
dec_1950 = dec_1950*radeg
return(list(ra_1950 = ra_1950, dec_1950=dec_1950))
} |
test_that("can get fx prices", {
skip_if_no_token()
x <- riingo_fx_prices(c("audusd", "eurusd"))
expect_identical(unique(x$ticker), c("audusd", "eurusd"))
expect_s3_class(x$date, "POSIXct")
})
test_that("can get fx prices with partial failures", {
skip_if_no_token()
expect_warning(
x <- riingo_fx_prices(c("audusd", "foobar")),
"No error was thrown"
)
expect_identical(unique(x$ticker), "audusd")
})
test_that("can get 1 minute resolution prices", {
skip_if_no_token()
start <- Sys.Date() - 10
end <- Sys.Date()
x <- riingo_fx_prices(
"eurusd",
start_date = start,
end_date = end,
resample_frequency = "1min"
)
min_diff <- min(diff(as.numeric(x$date)))
expect_identical(min_diff, 60)
}) |
expand.dtplyr_step <- function(data, ..., .name_repair = "check_unique") {
dots <- capture_dots(data, ..., .j = FALSE)
dots <- dots[!vapply(dots, is_null, logical(1))]
if (length(dots) == 0) {
return(data)
}
named_dots <- have_name(dots)
if (any(!named_dots)) {
symbol_dots <- vapply(dots, is_symbol, logical(1))
needs_v_name <- !symbol_dots & !named_dots
v_names <- paste0("V", 1:length(dots))
names(dots)[needs_v_name] <- v_names[needs_v_name]
names(dots)[symbol_dots] <- lapply(dots[symbol_dots], as_name)
}
names(dots) <- vctrs::vec_as_names(names(dots), repair = .name_repair)
dots_names <- names(dots)
out <- step_subset_j(
data,
vars = union(data$groups, dots_names),
j = expr(CJ(!!!dots, unique = TRUE))
)
if (any(dots_names %in% out$groups)) {
group_vars <- out$groups
expanded_group_vars <- dots_names[dots_names %in% group_vars]
out <- step_subset(
out, groups = character(), j = expr(!!expanded_group_vars := NULL)
)
out <- group_by(out, !!!syms(group_vars))
}
out
}
expand.data.table <- function(data, ..., .name_repair = "check_unique") {
data <- lazy_dt(data)
tidyr::expand(data, ..., .name_repair = .name_repair)
} |
hyperlink <- function(text, url) {
if (has_hyperlink()) {
paste0("\u001B]8;;", url, "\u0007", text, "\u001B]8;;\u0007")
} else {
text
}
}
has_hyperlink <- function() {
enabled <- getOption("crayon.hyperlink")
if (!is.null(enabled)) { return(isTRUE(enabled)) }
if (!isatty(stdout())) { return(FALSE) }
if (os_type() == "windows") { return(TRUE) }
if (nzchar(Sys.getenv("CI")) ||
nzchar(Sys.getenv("TEAMCITY_VERSION"))) { return(FALSE) }
if (nzchar(TERM_PROGRAM <- Sys.getenv("TERM_PROGRAM"))) {
version <- package_version(
Sys.getenv("TERM_PROGRAM_VERSION"),
strict = FALSE)
if (TERM_PROGRAM == "iTerm.app") {
if (!is.na(version) && version >= "3.1") return(TRUE)
}
}
if (nzchar(VTE_VERSION <- Sys.getenv("VTE_VERSION"))) {
if (package_version(VTE_VERSION) >= "0.50.1") return(TRUE)
}
FALSE
} |
"print.sreg" <- function(x, ...) {
if (length(x$lambda) > 1) {
c1 <- "Number of Observations:"
c2 <- (x$N)
c1 <- c(c1, "Number of values of lambda in grid:")
c2 <- c(c2, length(x$lambda))
sum <- cbind(c1, c2)
}
else {
digits <- 4
N <- x$N
c1 <- "Number of Observations:"
c2 <- (x$N)
c1 <- c(c1, "Unique Observations:")
c2 <- c(c2, length(x$xM))
c1 <- c(c1, "Effective degrees of freedom:")
c2 <- c(c2, format(round(x$trace, 1)))
c1 <- c(c1, "Residual degrees of freedom:")
c2 <- c(c2, format(round(x$N - x$trace, 1)))
c1 <- c(c1, "Residual root mean square:")
c2 <- c(c2, format(signif(sqrt(sum(x$residuals^2)/N),
4)))
c1 <- c(c1, "Lambda ( smoothing parameter)")
c2 <- c(c2, format(signif((x$lambda), 4)))
sum <- cbind(c1, c2)
}
dimnames(sum) <- list(rep("", dim(sum)[1]), rep("", dim(sum)[2]))
cat("Call:\n")
dput(x$call)
print(sum, quote = FALSE)
invisible(x)
} |
test_that("Mplus User Guide 5.1 - CFA with continuous indicators results can be read in", {
m <- readModels(target = htmlout("https://statmodel.com/usersguide/chap5/ex5.1.html"))
b <- coef(m, params = "loading")
expect_equal(b$est[1], 1.000)
expect_equal(b$se[1], 0.000)
expect_equal(m$summaries$BIC, 9931.295)
})
test_that("Mplus User Guide 5.2 - CFA with categorical indicators results can be read in", {
m <- readModels(target = htmlout("https://statmodel.com/usersguide/chap5/ex5.2.html"))
b <- coef(m, params = "loading")
expect_equal(b$est[1], 1.000)
expect_equal(b$se[1], 0.000)
expect_equal(m$summaries$WRMR, 0.342)
})
test_that("Mplus User Guide 5.5 part 4 - 4PL IRT results can be read in", {
m <- readModels(target = htmlout("https://statmodel.com/usersguide/chap5/ex5.5part4.html"))
b <- coef(m, params = "loading")
expect_equal(b$est[1], 0.918)
expect_equal(b$se[1], 0.155)
expect_equal(m$summaries$BIC, 269933.988)
})
test_that("Mplus User Guide 5.12 - SEM results can be read in", {
m <- readModels(target = htmlout("https://statmodel.com/usersguide/chap5/ex5.12.html"))
b <- coef(m, params = "loading")
expect_equal(b$est[1], 1.000)
expect_equal(b$se[1], 0.000)
b <- coef(m, params = "regression")
expect_equal(b$est[1], 0.473)
expect_equal(b$se[1], 0.057)
expect_equal(m$summaries$BIC, 19542.505)
})
test_that("Mplus User Guide 5.33 - Bayesian SEM multiple group results can be read in", {
m <- readModels(target = htmlout("https://statmodel.com/usersguide/chap5/ex5.33.html"))
b <- coef(m, params = "loading")
expect_equal(b$est[1], 0.848)
expect_equal(b$se[1], 0.061)
expect_equal(m$summaries$DIC, 35277.206)
}) |
gqq <- setRefClass(
Class = "gqq",
fields = c("vbbox1", "vbbox2", "lbbox1", "lbbox2", "rbbox1", "tbbox1"),
contains = c("plot_base"),
methods = list(
setFront = function() {
vbbox1 <<- variableboxes$new()
vbbox1$front(
top = top,
types = list(nonFactors()),
titles = list(
gettextKmg2("Y variable (pick one)")
),
initialSelection = list(0)
)
lbbox1 <<- textfields$new()
lbbox1$front(
top = top,
initValues = list("<auto>", "<auto>", "<auto>"),
titles = list(
gettextKmg2("Horizontal axis label"),
gettextKmg2("Vertical axis label"),
gettextKmg2("Title")
)
)
rbbox1 <<- radioboxes$new()
rbbox1$front(
top = alternateFrame,
labels = list(
gettextKmg2("Normal distribution"),
gettextKmg2("Log-normal distribution"),
gettextKmg2("Beta distribution"),
gettextKmg2("Exponential distribution"),
gettextKmg2("Gamma distribution"),
gettextKmg2("Weibull distribution"),
gettextKmg2("Other distribution")
),
title = gettextKmg2("Distribution")
)
lbbox2 <<- textfields$new()
lbbox2$front(
top = alternateFrame,
initValues = list(
"distribution = qnorm, dparams = list(mean = 0, sd = 1)"
),
titles = list(
gettextKmg2("Parameters for other distribution")
)
)
tbbox1 <<- toolbox$new()
tbbox1$front(top, showcolourbox = FALSE)
},
setBack = function() {
vbbox1$back()
lbbox1$back()
boxlist <- c(
list(rbbox1$frame),
list(labelRcmdr(alternateFrame, text=" ")),
list(lbbox2$frame)
)
do.call(tkgrid, c(lbbox2$back_list, list(sticky="nw")))
do.call(tkgrid, c(boxlist, list(sticky="nw")))
tkgrid(alternateFrame, stick="nw")
tkgrid(labelRcmdr(alternateFrame, text=" "), stick="nw")
tbbox1$back(4)
},
getWindowTitle = function() {
gettextKmg2("Q-Q plot")
},
getHelp = function() {
"Distributions"
},
getParms = function() {
x <- character(0)
y <- getSelection(vbbox1$variable[[1]])
z <- character(0)
s <- character(0)
t <- character(0)
y <- checkVariable(y)
xlab <- tclvalue(lbbox1$fields[[1]]$value)
xauto <- "Theoretical quantile"
ylab <- tclvalue(lbbox1$fields[[2]]$value)
yauto <- "Sample quantile"
zlab <- character(0)
main <- tclvalue(lbbox1$fields[[3]]$value)
size <- tclvalue(tbbox1$size$value)
family <- getSelection(tbbox1$family)
colour <- character(0)
save <- tclvalue(tbbox1$goption$value[[1]])
theme <- checkTheme(getSelection(tbbox1$theme))
options(
kmg2FontSize = tclvalue(tbbox1$size$value),
kmg2FontFamily = seq_along(tbbox1$family$varlist)[tbbox1$family$varlist == getSelection(tbbox1$family)] - 1,
kmg2SaveGraph = tclvalue(tbbox1$goption$value[[1]]),
kmg2Theme = seq_along(tbbox1$theme$varlist)[tbbox1$theme$varlist == getSelection(tbbox1$theme)] - 1
)
distType <- tclvalue(rbbox1$value)
distParms <- tclvalue(lbbox2$fields[[1]]$value)
list(
x = x, y = y, z = z, s = s, t = t,
xlab = xlab, xauto = xauto, ylab = ylab, yauto = yauto, zlab = zlab, main = main,
size = size, family = family, colour = colour, save = save, theme = theme,
distType = distType, distParms = distParms
)
},
checkError = function(parms) {
if (length(parms$y) == 0) {
errorCondition(
recall = windowQQ,
message = gettextKmg2("Y variable is not selected")
)
errorCode <- TRUE
} else {
if (mode == 1) {
commandDoIt("require(\"ggplot2\")", log = TRUE)
}
setDataframe(parms)
if (parms$distType == "2" && any(.df$y <= 0)) {
response <- tclvalue(RcmdrTkmessageBox(
message = gettextKmg2("The log-normal distribution defined on the interval (0, +Inf)."),
title = gettextKmg2("Error"),
icon = "error",
type = "ok",
default = "ok")
)
if (response == "ok") {
return(TRUE)
}
} else if (parms$distType == "3" && any(.df$y > 1 | .df$y < 0)) {
response <- tclvalue(RcmdrTkmessageBox(
message = gettextKmg2("The beta distribution defined on the interval [0, 1]."),
title = gettextKmg2("Error"),
icon = "error",
type = "ok",
default = "ok")
)
if (response == "ok") {
return(TRUE)
}
} else if (parms$distType == "4" && any(.df$y < 0)) {
response <- tclvalue(RcmdrTkmessageBox(
message = gettextKmg2("The exponential distribution defined on the interval [0, +Inf)."),
title = gettextKmg2("Error"),
icon = "error",
type = "ok",
default = "ok")
)
if (response == "ok") {
return(TRUE)
}
} else if (parms$distType == "5" && any(.df$y < 0)) {
response <- tclvalue(RcmdrTkmessageBox(
message = gettextKmg2("The gamma distribution defined on the interval [0, +Inf)."),
title = gettextKmg2("Error"),
icon = "error",
type = "ok",
default = "ok")
)
if (response == "ok") {
return(TRUE)
}
} else if (parms$distType == "6" && any(.df$y < 0)) {
response <- tclvalue(RcmdrTkmessageBox(
message = gettextKmg2("The weibull distribution defined on the interval [0, +Inf)."),
title = gettextKmg2("Error"),
icon = "error",
type = "ok",
default = "ok")
)
if (response == "ok") {
return(TRUE)
}
} else {
if (parms$distType == "1") {
command <- paste0(
"
".est <- c(mean(.df$y), sd(.df$y))"
)
} else if (parms$distType == "2") {
command <- paste0(
"
".est <- c(mean(log(.df$y)), sd(log(.df$y)))"
)
} else if (parms$distType == "3") {
command <- paste0(
"
".est <- c(mean(.df$y)*(mean(.df$y)*(1 - mean(.df$y))/var(.df$y) - 1), (1 - mean(.df$y))*(mean(.df$y)*(1 - mean(.df$y))/var(.df$y) - 1))"
)
} else if (parms$distType == "4") {
command <- paste0(
"
".est <- 1 / mean(.df$y)"
)
} else if (parms$distType == "5") {
command <- paste0(
"
".objf <- function(p, y) {",
"-sum(dgamma(y, shape = p[1], scale = p[2], log = TRUE))",
"}\n",
".est <- optim(c(1, 1), .objf, y = .df$y)"
)
} else if (parms$distType == "6") {
command <- paste0(
"
".objf <- function(p, y) {",
"-sum(dweibull(y, shape = p[1], scale = p[2], log = TRUE))",
"}\n",
".est <- optim(c(1, 1), .objf, y = .df$y)"
)
}
if (any(parms$distType == c("5", "6"))) {
commandDoIt(command)
registRmlist(.objf)
registRmlist(.est)
} else if (any(parms$distType == c("1", "2", "3", "4"))) {
commandDoIt(command)
registRmlist(.est)
}
if (any(parms$distType == c("5", "6")) && (is.na(match(".est", ls(envir = .GlobalEnv, all.names = TRUE))) || .est$convergence != 0)) {
response <- tclvalue(RcmdrTkmessageBox(
message = gettextKmg2("Parameter estimation failed."),
title = gettextKmg2("Error"),
icon = "error",
type = "ok",
default = "ok"
))
if (response == "ok") {
errorCode <- TRUE
}
} else {
.plot <- getPlot(parms)
commandDoIt("print(.plot)")
if (mode == 1 && parms$save == "1") .self$savePlot(.plot)
pos <- 1
assign(".lastcom", paste0(codes, "\n"), envir = as.environment(pos))
errorCode <- 2
}
}
}
errorCode
},
getGgplot = function(parms) {
"ggplot(data = .df, aes(sample = y)) + \n "
},
getGeom = function(parms) {
if (parms$distType == "1") {
distParms <- "distribution = qnorm, dparams = list(mean = .est[1], sd = .est[2])"
} else if (parms$distType == "2") {
distParms <- "distribution = qlnorm, dparams = list(meanlog = .est[1], sdlog = .est[2])"
} else if (parms$distType == "3") {
distParms <- "distribution = qbeta, dparams = list(shape1 = .est[1], shape2 = .est[2])"
} else if (parms$distType == "4") {
distParms <- "distribution = qexp, dparams = list(rate = .est)"
} else if (parms$distType == "5") {
distParms <- "distribution = qgamma, dparams = list(shape = .est$par[1], scale = .est$par[2])"
} else if (parms$distType == "6") {
distParms <- "distribution = qweibull, dparams = list(shape = .est$par[1], scale = .est$par[2])"
} else {
distParms <- parms$distParms
}
paste0("stat_qq(", distParms, ") + \n ")
},
getMain = function(parms) {
if (nchar(parms$main) == 0) {
main <- ""
} else if (parms$main == "<auto>") {
if (parms$distType == "1") {
main <- paste0(
"Theoretical: qnorm(mean = ", round(.est[1], 1),
", sd = ", round(.est[2], 1), ")"
)
} else if (parms$distType == "2") {
main <- paste0(
"Theoretical: qlnorm(meanlog = ", round(.est[1], 1),
", sdlog = ", round(.est[2], 1), ")"
)
} else if (parms$distType == "3") {
main <- paste0(
"Theoretical: qbeta(shape1 = ", round(.est[1], 1),
", shape2 = ", round(.est[2], 1), ")"
)
} else if (parms$distType == "4") {
main <- paste0("Theoretical: qexp(rate = ", round(.est, 1), ")")
} else if (parms$distType == "5") {
main <- paste0(
"Theoretical: qgamma(shape = ", round(.est$par[1], 1),
", scale = ", round(.est$par[2], 1), ")"
)
} else if (parms$distType == "6") {
main <- paste0(
"Theoretical: qweibull(shape = ", round(.est$par[1], 1),
", scale = ", round(.est$par[2], 1), ")"
)
} else {
main <- paste0("Theoretical: ", parms$distParms)
}
main <- paste0("labs(title = \"", main, "\") + \n ")
} else {
main <- paste0("labs(title = \"", parms$main, "\") + \n ")
}
main
}
)
)
windowQQ <- function() {
QQ <- RcmdrPlugin.KMggplot2::gqq$new()
QQ$plotWindow()
} |
cyclocomp_package_dir <- function(path = ".") {
tmp <- tempfile()
dir.create(tmp)
on.exit(unlink(tmp, recursive = TRUE), add = TRUE)
pkgname <- desc_get("Package", file = file.path(path, "DESCRIPTION"))
targz <- build_package(path)
install_local(targz, lib = tmp)
r(libpath = c(tmp, .libPaths()),
function(pkg) {
loadNamespace(pkg)
cyclocomp::cyclocomp_package(pkg)
},
args = list(pkgname)
)
}
build_package <- function(path) {
path <- normalizePath(path)
tmpdir <- tempfile()
dir.create(tmpdir)
on.exit(unlink(tmpdir, recursive = TRUE))
file.copy(path, tmpdir, recursive = TRUE)
if (file.info(path)$isdir) {
build_status <- with_dir(
tmpdir,
rcmd_safe("build", basename(path))
)
unlink(file.path(tmpdir, basename(path)), recursive = TRUE)
}
report_system_error("Build failed", build_status)
on.exit(NULL)
file.path(
tmpdir,
list.files(tmpdir, pattern = "\\.tar\\.gz$")
)
}
report_system_error <- function(msg, status) {
if (status$status == 0) return()
if (status$stderr == "") {
stop(
msg, ", unknown error, standard output:\n",
yellow(status$stdout),
call. = FALSE
)
} else {
stop(
underline(yellow(paste0("\n", msg, ", standard output:\n\n"))),
yellow(status$stdout), "\n",
underline(red("Standard error:\n\n")), red(status$stderr),
call. = FALSE
)
}
} |
useToastr <- function() {
addResourcePath("toastr", system.file("toastr", package = "shinytoastr"))
tags$head(
tags$link(
rel = "stylesheet",
type = "text/css",
href = "toastr/toastr.min.css"
),
tags$script(
src = "toastr/toastr.min.js"
),
tags$script(
src = "toastr/shinytoastr.js"
)
)
}
toastr_fun <- function(toast_type) {
function(
message,
title = "",
closeButton = FALSE,
newestOnTop = FALSE,
progressBar = FALSE,
position = c("top-right", "top-center", "top-left", "top-full-width",
"bottom-right", "bottom-center", "bottom-left", "bottom-full-width"),
preventDuplicates = FALSE,
showDuration = 300,
hideDuration = 1000,
timeOut = 5000,
extendedTimeOut = 1000,
showEasing = c("swing", "linear"),
hideEasing = c("swing", "linear"),
showMethod = c("fadeIn", "slideDown", "show"),
hideMethod = c("fadeOut", "hide")
) {
options <- list(
closeButton = isTRUE(closeButton),
newestonTop = isTRUE(newestOnTop),
progressBar = isTRUE(progressBar),
positionClass = paste0("toast-", match.arg(position)),
preventDuplicates = isTRUE(preventDuplicates),
showDuration = as_count(showDuration),
hideDuration = as_count(hideDuration),
timeOut = as_count(timeOut),
extendedTimeOut = as_count(extendedTimeOut),
showEasing = match.arg(showEasing),
hideEasing = match.arg(hideEasing),
showMethod = match.arg(showMethod),
hideMethod = match.arg(hideMethod)
)
session <- getSession()
session$sendCustomMessage(
type = 'toastr',
message = list(
type = toast_type,
message = message,
title = title,
options = options
)
)
}
}
toastr_success <- toastr_fun("success")
toastr_info <- toastr_fun("info")
toastr_warning <- toastr_fun("warning")
toastr_error <- toastr_fun("error")
getSession <- function() {
session <- getDefaultReactiveDomain()
if (is.null(session)) {
stop("could not find the Shiny session object. This usually happens ",
"when toastr is called from a context that wasn't set up by a ",
"Shiny session.")
}
session
}
as_count <- function(x) {
x <- as.integer(x)
stopifnot(length(x) == 1, ! is.na(x))
x
} |
wilcoxonOR =
function(formula=NULL, data=NULL, x=NULL, y=NULL,
ci=FALSE, conf=0.95, type="perc", R=1000, histogram=FALSE, digits=3,
reportIncomplete=FALSE, verbose=FALSE,
...){
if(!is.null(formula)){
x = eval(parse(text=paste0("data","$",all.vars(formula[[2]])[1])))
g = factor(eval(parse(text=paste0("data","$",all.vars(formula[[3]])[1]))))
A = x[g==levels(g)[1]]
B = x[g==levels(g)[2]]
}
if(is.null(formula)){
A = x
B = y
x = c(A, B)
g = factor(c(rep("A", length(A)), rep("B", length(B))))
}
Matrix = outer(A,B,FUN="-")
Diff1 = Matrix>0
Diff2 = Matrix<0
OR = signif(mean(Diff1) / mean(Diff2), digits=digits)
if(verbose){
Out = data.frame(
Statistic = c("Proportion Ya > Yb","Proportion Ya < Yb",
"Proportion ties"),
Value = c(signif(mean(Matrix>0), digits=3),
signif(mean(Matrix<0), digits=3),
signif(mean(Matrix==0), digits=3))
)
cat("\n")
print(Out)
cat("\n")
}
if(ci==TRUE){
Data = data.frame(x,g)
Function = function(input, index){
Input = input[index,]
if(length(unique(droplevels(Input$g)))==1){
FLAG=1
return(c(NA,FLAG))}
if(length(unique(droplevels(Input$g)))>1){
Matrix = outer(Input$x[Input$g==levels(Input$g)[1]],
Input$x[Input$g==levels(Input$g)[2]],
FUN="-")
Diff1 = Matrix>0
Diff2 = Matrix<0
p = signif(mean(Diff1) / mean(Diff2), digits=digits)
FLAG=0
return(c(p, FLAG))}}
Boot = boot(Data, Function, R=R)
BCI = boot.ci(Boot, conf=conf, type=type)
if(type=="norm") {CI1=BCI$normal[2]; CI2=BCI$normal[3];}
if(type=="basic"){CI1=BCI$basic[4]; CI2=BCI$basic[5];}
if(type=="perc") {CI1=BCI$percent[4]; CI2=BCI$percent[5];}
if(type=="bca") {CI1=BCI$bca[4]; CI2=BCI$bca[5];}
if(sum(Boot$t[,2])>0 & reportIncomplete==FALSE) {CI1=NA; CI2=NA}
CI1=signif(CI1, digits=digits)
CI2=signif(CI2, digits=digits)
if(histogram==TRUE){hist(Boot$t[,1], col = "darkgray",
main="", xlab="PS")}
}
if(ci==FALSE){names(OR)="OR"; return(OR)}
if(ci==TRUE){names(OR) = ""
return(data.frame(OR=OR, lower.ci=CI1, upper.ci=CI2))}
} |
profilelike.gls <-
function(formula, data, correlation=NULL, subject, profile.theta, method="ML", lo.theta, hi.theta, length=300, round=2, subset=NULL, weights=NULL, ...){
if(!is.null(subset)){
stop("Warning message: 'subset' should not be provided")
}
if(!is.null(weights)){
stop("Warning message: 'weights' should not be provided")
}
m <- model.frame(formula, data)
X <- model.matrix(formula, m)
y <- model.response(m)
theta.off <- data[,names(data)==profile.theta]
id <- data[,names(data)==subject]
if(!is.numeric(theta.off)){
stop("Warning message: 'profile.theta' must be a numeric variable")
}
if( ( length(theta.off)!= length(y) | length(theta.off)!= length(X[,1]) | length(y)!= length(X[,1]) ) ){
cat("Warning message: remove missing data \n")
}
if( ( is.null(lo.theta) | is.null(hi.theta) )){
cat("Warning message: provide lo.theta and hi.theta \n")
fit <- lm(y ~ -1 + X + theta.off, na.action=na.fail)
mle <- summary(fit)$coefficient["theta.off",1]
se <- summary(fit)$coefficient["theta.off",2]
lo.theta <- round(mle - 4*se, round)
hi.theta <- round(mle + 4*se, round)
}
theta <- seq(from =lo.theta, to=hi.theta, length=length)
log.lik <- rep(NA, length)
for(i in 1:length){
pi <- theta[i]
y.off <- y - pi*theta.off
fit <- gls(y.off ~ -1 + X, correlation = correlation, method="ML", na.action=na.fail)
log.lik[i] <- logLik(fit)
}
theta <- theta[is.na(log.lik)!=1]
log.lik <- log.lik[is.na(log.lik)!=1]
profile.lik <- exp(log.lik)
mm <- max(log.lik, na.rm=TRUE)
log.norm.lik <- log.lik - mm
profile.lik.norm <- exp(log.norm.lik)
return(list(theta=theta, profile.lik=profile.lik, profile.lik.norm=profile.lik.norm))
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.