code
stringlengths 1
13.8M
|
---|
mKrig.trace <- function(object, iseed, NtrA) {
if (exists(".Random.seed", .GlobalEnv)){
oldseed <- .GlobalEnv$.Random.seed
}
else{
oldseed <- NULL
}
if( !is.na(iseed)){
set.seed(iseed)
}
np<- object$np
if (NtrA >= object$np) {
Ey <- diag(1, np)
NtrA <- np
hold <- diag(predict.mKrig(object, ynew = Ey, collapseFixedEffect=FALSE))
trA.info<- NA
trA.est <- sum(hold)
}
else {
Ey <- matrix(rnorm(np * NtrA), nrow = np,
ncol = NtrA)
trA.info <- colSums(Ey * (predict.mKrig(object, ynew = Ey,
collapseFixedEffect=FALSE)))
trA.est <- mean(trA.info)
}
if (NtrA < np) {
MSE<-(sum(object$residuals^2)/np)
GCV <- MSE/(1 - trA.est /np)^2
GCV.info <- MSE/( 1 - trA.info/np)^2
}
else{
GCV<- NA
GCV.info <- NA
}
if (!is.null(oldseed)){
.GlobalEnv$.Random.seed <- oldseed
}
else{
if( exists(".Random.seed", .GlobalEnv)){
rm(".Random.seed", envir = .GlobalEnv)
}
}
return(
list(trA.info = trA.info, eff.df = trA.est,
GCV= GCV, GCV.info=GCV.info)
)
}
mKrig.coef <- function(object, y, collapseFixedEffect=TRUE) {
if( any(is.na(y))){
stop("mKrig can not omit missing values in observation vecotor")
}
if( object$nt>0){
beta <- as.matrix(qr.coef(object$qr.VT, forwardsolve(object$Mc,
transpose = TRUE, y, upper.tri = TRUE)))
betaMeans<- rowMeans( beta)
if( collapseFixedEffect){
beta<- matrix( betaMeans, ncol=ncol(beta), nrow= nrow( beta))
}
resid <- y - object$Tmatrix %*% beta
}
else{
beta<- NULL
resid <- y
}
c.coef <- forwardsolve(object$Mc, transpose = TRUE, resid,
upper.tri = TRUE)
c.coef <- as.matrix(backsolve(object$Mc, c.coef))
out <- list( beta = (beta), c.coef = c.coef )
return(out)
} |
print.dust <- function(x, ..., asis = TRUE, linebreak_at_end = 2)
{
print_method <- x$print_method
if (print_method == "latex" & x$hhline)
print_method <- "latex_hhline"
switch(print_method,
"console" = print_dust_console(x, ..., asis = asis),
"docx" = print_dust_markdown(x, ..., asis = asis),
"markdown" = print_dust_markdown(x, ..., asis = asis),
"html" = print_dust_html(x, ..., asis = asis, linebreak_at_end = linebreak_at_end),
"latex" = print_dust_latex(x, ..., asis = asis),
"latex_hhline" = print_dust_latex_hhline(x, ..., asis = asis),
"slidy" = print_dust_html(x, ..., asis = asis, linebreak_at_end = linebreak_at_end),
stop(sprintf("'%s' is not an valid print method",
x[["print_method"]])))
}
print.dust_list <- function(x, ..., asis = TRUE)
{
lapply(X = x,
FUN = print.dust,
asis = asis,
...)
} |
NULL
globalVariables(
c(".", "active", "cumdist", "dist_scaled", "dist_to_prev", "distance",
"duration", "ele", "end_time", "lat", "lon", "radius", "start_time",
"time_diff_to_prev", "wday", "x", "y", "year")
) |
getLinks <- function(areas = NULL, exclude = NULL, opts = simOptions(),
internalOnly=FALSE, namesOnly = TRUE,
withDirection = FALSE) {
if (is.null(areas)) areas <- getAreas(opts = opts)
if (is.null(opts$linksDef$from)) {
return(NULL)
}
if (internalOnly) links <- opts$linksDef[from %in% areas & to %in% areas]
else links <- opts$linksDef[from %in% areas | to %in% areas]
links <- links[!from %in% exclude & !to %in% exclude]
if (namesOnly) return(links$link)
if (!withDirection) return(links)
outward_links <- links[, .(area = from, link, to = to)]
outward_links[, direction := 1]
inward_links <- links[, .(area = to, link, to = from)]
inward_links[, direction := -1]
links <- rbind(outward_links, inward_links)
links[area %in% areas]
} |
geo_median <- function(P, tol = 1e-07, maxiter = 200) {
stopifnot(is.numeric(P))
if (!is.matrix(P))
stop("Argument 'P' must be a matrix (of points in R^n).")
m <- nrow(P); n <- ncol(P)
if (n == 1)
return(list(p = median(P), d = sum(abs(P - median(P))),
reltol = 0, niter = 0))
p0 <- apply(P, 2, mean)
p1 <- p0 + 1
iter <- 1
while(max(abs(p0 - p1)) > tol && iter < maxiter) {
iter <- iter + 1
p0 <- p1
s1 <- s2 <- 0
for (j in 1:m) {
d <- Norm(P[j, ] - p0)
s1 <- s1 + P[j, ]/d
s2 <- s2 + 1/d
}
p1 <- s1 / s2
}
if (iter >= maxiter)
warning("Maximum number of iterations reached; may not converge.")
d <- 0
for (j in 1:m)
d <- d + Norm(P[j, ] - p1)
return( list(p = p1, d = d, reltol = max(abs(p0 - p1)), niter = iter) )
} |
library("testthat")
context("ParamChecks")
test_that("checkBoolean", {
testthat::expect_error(checkBoolean(1))
testthat::expect_error(checkBoolean('tertet'))
testthat::expect_equal(checkBoolean(T), T)
testthat::expect_equal(checkBoolean(F), T)
})
test_that("checkHigherEqual", {
testthat::expect_error(checkHigherEqual(1,2))
testthat::expect_error(checkHigherEqual('tertet',1))
testthat::expect_equal(checkHigherEqual(1,0), T)
testthat::expect_equal(checkHigherEqual(0,0), T)
})
test_that("checkLowerEqual", {
testthat::expect_error(checkLowerEqual(2,1))
testthat::expect_error(checkLowerEqual('tertet',1))
testthat::expect_equal(checkLowerEqual(0,1), T)
testthat::expect_equal(checkLowerEqual(0,0), T)
})
test_that("checkHigher", {
testthat::expect_error(checkHigher(1,2))
testthat::expect_error(checkHigher(0,0))
testthat::expect_error(checkHigher('tertet',1))
testthat::expect_equal(checkHigher(1,0), T)
})
test_that("checkLower", {
testthat::expect_error(checkLower(2,1))
testthat::expect_error(checkLower(0,0))
testthat::expect_error(checkLower('tertet',1))
testthat::expect_equal(checkLower(0,1), T)
})
test_that("checkNotNull", {
testthat::expect_error(checkNotNull(NULL))
testthat::expect_equal(checkNotNull(0), T)
testthat::expect_equal(checkNotNull(T), T)
testthat::expect_equal(checkNotNull('yeryey'), T)
})
test_that("checkIsClass", {
testthat::expect_error(checkIsClass('dsdsds', 'double'))
testthat::expect_equal(checkIsClass('dsdsds', "character"), T)
})
test_that("checkInStringVector", {
testthat::expect_error(checkInStringVector('dsdsds', c('dsds','double')))
testthat::expect_equal(checkInStringVector('dsdsds', c('dsdsds','double')), T)
}) |
print.packageSum <- function(x, where, title,
openBrowser = TRUE, template, ...) {
cl <- deparse(substitute(x))
if(length(grep('\\(', cl))>0)cl <- 'x'
if (nrow(x) < 1) {
cat("x has zero rows; ",
"nothing to display.\n")
if (missing(where))
where <- ""
return(invisible(where))
}
if (missing(where))
where <- "HTML"
if (length(where) == 1 &&
where == "console")
where <- c("Package", "Count", 'MaxScore',
'TotalScore', 'Date', "Title", 'Version',
'Author')
if (all(where %in% names(x))) {
print.data.frame(x[, where])
return(invisible(""))
}
if (length(where)>1)
stop("if length(where)>1, ",
"where must be names of columns of",
" x; they are not. where = ",
paste(where, collapse=", "))
if (toupper(where) == "HTML") {
f0 <- tempfile()
for(i in 1:111) {
File <- paste0(f0, ".html")
fInf <- file.info(File)
if(all(is.na(fInf)))
break
f0 <- paste(f0, "1", sep="")
}
} else {
File <- where
}
Ocall <- attr(x, "call")
Oc0 <- deparse(Ocall)
Oc. <- gsub('\"', "'", Oc0)
Oc1 <- paste(cl, "<-", paste(Oc., collapse=''))
iPx <- paste0('installPackages(', cl, ',...)')
w2xls <- paste0('writeFindFn2xls(', cl, ')')
string <- attr(x, "string")
if (missing(title)) {
title <- paste('packageSum for', string)
}
Dir <- dirname(File)
if (Dir == ".") {
Dir <- getwd()
File <- file.path(Dir, File)
} else {
dc0 <- dir.create(Dir, FALSE, TRUE)
}
js <- system.file("js", "sorttable.js",
package = "sos")
if (!file.exists(js)) {
warning("Unable to locate 'sorttable.js' file")
} else {
file.copy(js, Dir)
}
xin <- x
Desc <- x$Title
if(is.null(Desc))Desc <- ''
x$Title <- gsub("(^[ ]+)|([ ]+$)",
"", as.character(Desc), useBytes = TRUE)
x[] <- lapply(x, as.character)
hasTemplate <- !missing(template)
if (!hasTemplate) {
templateFile <- system.file("brew",
"default", "pkgSum.brew.html",
package = "sos")
template <- file(templateFile,
encoding = "utf-8", open = "r" )
}
xenv <- new.env()
assign("Oc1", Oc1, envir = xenv)
assign('iPx', iPx, envir=xenv)
assign('w2xls', w2xls, envir=xenv)
assign("x", x, envir = xenv)
brew::brew(template, File, envir = xenv)
if (!hasTemplate) {
close(template)
}
FileInfo <- file.info(File)
if (is.na(FileInfo$size) || FileInfo$size <= 0) {
if (is.na(FileInfo$size)) {
warning("Brew did not create file ", File)
} else {
warning("Brew created a file of size 0")
}
cat("Ignoring template.\n")
con <- file(File, "wt")
on.exit(close(con))
.cat <- function(...)
cat(..., "\n", sep = "", file = con,
append = TRUE)
cat("<html>", file = con)
.cat("<head>")
.cat("<title>", title, "</title>")
.cat("<script src=sorttable.js type='text/javascript'></script>")
.cat("<style>\n",
"table.sortable thead {\n",
"font: normal 10pt Tahoma, Verdana, Arial;\n",
"background:
"color:
"font-weight: bold;\n",
"cursor: hand;\n",
"}\n",
"table.sortable th {\n",
"width: 75px;\n",
"color:
"border: 1px solid black;\n",
"}\n",
"table.sortable th:hover {\n",
"background:
"}\n",
"table.sortable td {\n",
"font: normal 10pt Tahoma, Verdana, Arial;\n",
"text-align: center;\n",
"border: 1px solid blue;\n",
"}\n",
".link {\n",
"padding: 2px;\n",
"width: 600px;\n",
"}\n",
".link:hover {\n",
"background:
"}\n",
"a {\n",
"color: darkblue;\n",
"text-decoration: none;\n",
"border-bottom: 1px dashed darkblue;\n",
"}\n",
"a:visited {\n",
"color: black;\n",
"}\n",
"a:hover {\n",
"border-bottom: none;\n",
"}\n",
"h1 {\n",
"font: normal bold 20pt Tahoma, Verdana, Arial;\n",
"color:
"text-decoration: underline;\n",
"}\n",
"h2 {\n",
"font: normal bold 12pt Tahoma, Verdana, Arial;\n",
"color:
"}\n",
"table.sortable .empty {\n",
"background: white;\n",
"border: 1px solid white;\n",
"cursor: default;\n",
"}\n",
"</style>\n",
"</head>")
.cat("<h1>", title, "</h1>")
.cat("<h2>call: <font color='
paste(Oc1, collapse = ""), "</font></h2>\n")
.cat("<h2>Title, etc., are available on ",
"installed packages. To get more, use",
" <font color='
" </font></h2>")
.cat("<h2>See also: <font color='
w2xls, "</font></h2>")
.cat("<table class='sortable'>\n<thead>")
link <- as.character(x$pkgLink)
desc <- gsub("(^[ ]+)|([ ]+$)", "",
as.character(x$Title), useBytes = TRUE)
x$pkgLink <- sprintf("<a href='%s' target='_blank'>%s</a>",
link, desc)
x$Title <- NULL
ilk <- which(names(x) == "pkgLink")
names(x)[ilk] <- "Title and Link"
.cat("<tr>\n <th style='width:40px'>Id</th>")
.cat(sprintf(" <th>%s</th>\n</tr>",
paste(names(x), collapse = "</th>\n <th>")))
.cat("</thead>\n<tbody>")
paste.list <- c(list(row.names(x)),
lapply(x, as.character),
sep = "</td>\n <td>")
tbody.list <- do.call("paste", paste.list)
tbody <- sprintf("<tr>\n <td>%s</td>\n</tr>",
tbody.list)
tbody <- sub("<td><a", "<td class=link><a",
tbody, useBytes = TRUE)
.cat(tbody)
.cat("</tbody></table></body></html>")
}
if (openBrowser) {
FileInf2 <- file.info(File)
if (is.na(FileInf2$size)) {
warning("Did not create file ", File,
"; nothing to give to a browser.")
} else {
if (FileInf2$size <= 0) {
warning("0 bytes in file ", File, "; nothing to give to a browser.")
} else {
utils::browseURL(File)
}
}
}
invisible(File)
} |
imputeMissingValue <- function(inc_mat,
method = c("svd", "median", "als", "CA")) {
if (TRUE %in% rowSums(is.na(inc_mat)) == ncol(inc_mat)) {
warning("Some observation row(s) are all Na, removed")
inc_mat <- inc_mat[rowSums(is.na(inc_mat)) != ncol(inc_mat), ]
}
x <- inc_mat
col_name <- colnames(x)
row_name <- rownames(x)
colnames(x) <- paste0("col", 1:ncol(x))
names(col_name) <- paste0("col", 1:ncol(x))
rownames(x) <- paste0("row", 1:nrow(x))
names(row_name) <- paste0("row", 1:nrow(x))
result <- list()
if ("knn" %in% method) {
method <- method[method != "knn"]
knn_imputation <- bnstruct::knn.impute(x)
colnames(knn_imputation) <- col_name[colnames(knn_imputation)]
rownames(knn_imputation) <- row_name[rownames(knn_imputation)]
result$knn <- base::as.matrix(knn_imputation)
}
if ("median" %in% method) {
method <- method[method != "median"]
median_imputation <- t(apply(x, 1, FUN = function(x) {
x[is.na(x)] <- stats::median(x, na.rm = T)
x
}))
colnames(median_imputation) <- col_name[colnames(median_imputation)]
rownames(median_imputation) <- row_name[rownames(median_imputation)]
result$median <- base::as.matrix(median_imputation)
}
if ("svd" %in% method) {
method <- method[method != "svd"]
fits_svd <- softImpute::softImpute(x, type = "svd", trace.it = F)
svd_imputation <- softImpute::complete(x, fits_svd)
colnames(svd_imputation) <- col_name[colnames(svd_imputation)]
rownames(svd_imputation) <- row_name[rownames(svd_imputation)]
result$svd <- base::as.matrix(svd_imputation)
}
if ("als" %in% method) {
method <- method[method != "als"]
fits_als <- softImpute::softImpute(x, type = "als", trace.it = F)
als_imputation <- softImpute::complete(x, fits_als)
colnames(als_imputation) <- col_name[colnames(als_imputation)]
rownames(als_imputation) <- row_name[rownames(als_imputation)]
result$als <- base::as.matrix(als_imputation)
}
if ("CA" %in% method) {
method <- method[method != "CA"]
CA_imputation <- missMDA::imputeCA(x)
colnames(CA_imputation) <- col_name[colnames(CA_imputation)]
rownames(CA_imputation) <- row_name[rownames(CA_imputation)]
result$CA <- base::as.matrix(CA_imputation)
}
if ("FAMD" %in% method) {
method <- method[method != "FAMD"]
FAMD_imputation <- missMDA::imputeFAMD(x)$completeObs
colnames(FAMD_imputation) <- col_name[colnames(FAMD_imputation)]
rownames(FAMD_imputation) <- row_name[rownames(FAMD_imputation)]
result$FAMD <- base::as.matrix(FAMD_imputation)
}
if ("PCA" %in% method) {
method <- method[method != "PCA"]
PCA_imputation <- missMDA::imputePCA(x)$completeObs
colnames(PCA_imputation) <- col_name[colnames(PCA_imputation)]
rownames(PCA_imputation) <- row_name[rownames(PCA_imputation)]
result$PCA <- base::as.matrix(PCA_imputation)
}
if (!is.null(method)) {
for (mice_method in method) {
imp <- mice::mice(x, method = mice_method, m = 1, maxit = 1, printFlag = F)
inc_mat_imp <- mice::complete(imp)
colnames(inc_mat_imp) <- col_name[colnames(inc_mat_imp)]
rownames(inc_mat_imp) <- row_name[rownames(inc_mat_imp)]
result[[mice_method]] <- base::as.matrix(inc_mat_imp)
}
}
return(result)
} |
boot2 <-
function(y,xcopy,phi1,beta,nbs,method,scores=scores){
arp <- length(phi1)
phi <- phi1
p <- length(beta)
n <- length(y)
zn1 <- n-p-arp
zn2 <- n-2*p-arp
if(zn1 < 0){zn1 <- 1}
if(zn2 < 0){zn2 <- 1}
adj <- zn1/zn2
icent <- 1
n1 <- n - arp
ones <- rep(1,n)
proj1 <- ones%*%t(ones)/n
x2 <- as.matrix(xcopy[,2:p])
xbar <- apply(x2,2,mean)
xc <- xcopy[,2:p] - proj1%*%xcopy[,2:p]
x <- xc
p <- p - 1
ehat <- rep(0,n1)
for(i in (arp+1):n){
ypart <- y[i]
for(k in 1:arp){ypart <- ypart - phi[k]*y[i-k]}
xpart <- 0
for(j in 1:(p+icent)){
for(k in 1:arp){
if(k == 1){
xpart <- xpart + beta[j]*(xcopy[i,j] - phi[k]*xcopy[i-k,j])
} else {
xpart <- xpart - beta[j]*phi[k]*xcopy[i-k,j]
}
}
}
ehat[i-arp] <- ypart - xpart
}
ehat <- (ehat - mean(ehat))*sqrt(adj)
sigehat <- sd(ehat)*sqrt((n-arp)/(n-arp-1))
oldb <- beta
pp1 <- p + icent
bsbeta <- matrix(rep(0,pp1^2),ncol=pp1)
ind <- 1:n1
ii <- sample(ind,1,replace=TRUE)
allbeta <- c()
rhostar <- c()
MSEstar <- c()
for(nbk in 1:nbs){
ind2 <- sample(ind,n1,replace=TRUE)
ystar <- y[ii:(ii+arp-1)]
estar <- ehat[ind2]
for(i in (arp+1):n){
ypart <- 0
for(k in 1:arp){ypart <- ypart + phi[k]*ystar[i-k]}
xpart <- 0
for(j in 1:pp1){
for(k in 1:arp){
if(k == 1){
xpart <- xpart + beta[j]*(xcopy[i,j]-phi[k]*xcopy[i-k,j])
} else {
xpart <- xpart - beta[j]*phi[k]*xcopy[i-k,j]
}
}
}
ystar[i] <- ypart + xpart + estar[i-arp]
}
avey <- mean(ystar)
sigestar <- sd(estar*(n/(n-1)))
MSEstar <- c(MSEstar, sigestar ^ 2)
ystar <- ystar - avey
d2fit <- durbin2fit(ystar,x,phi,method=method,scores=scores)
dum3 <- d2fit$beta
d1 <- avey - t(xbar)%*%dum3
dum3 <- c(d1,dum3)
uhat <- y - xcopy %*% dum3
dum4 = lagmat(uhat, arp)
u.y <- dum4[,1]
u.x <- dum4[,-1]
ufit <- lm(u.y ~ u.x)
rhotmp <- ufit$coef[-1]
rhostar <- rbind(rhostar, rhotmp)
allbeta <- rbind(allbeta, dum3)
for(i in 1:pp1){
for(j in 1:pp1){
bsbeta[i,j] <- bsbeta[i,j]+(dum3[i]-oldb[i])*(dum3[j]-oldb[j])/sigestar^2
}
}
}
bsbeta <- bsbeta / nbs
list(betacov = bsbeta, allbeta = allbeta, rhostar = rhostar, MSEstar = MSEstar)
} |
boxplotPOFD <- function(data, centralRegion = 0.5, fmag = 1.5, fdom = 0)
{
N <- dim(data)[2]
P <- dim(data)[1]
w <- (N-rowSums(is.na(data)))/(N)
if(is.null(rownames(data))){rownames(data) <- x <- c(1:P)}else{x <- as.numeric(rownames(data))}
if(is.null(colnames(data))){colnames(data) <- ids <- c(1:N)}else{ids <- colnames(data)}
mbd.ordered <- POIFD(data, type = "MBD")
mbd.ids <- mbd.ordered[ids]
median <- names(mbd.ordered)[1]
idCR <- names(mbd.ordered[1:ceiling(N*centralRegion)])
center <- data[,idCR]
propCR <- rowMeans(!is.na(center))
infCR <- apply(center, 1,function(x) suppressWarnings(min(x, na.rm=TRUE))); infCR[infCR == Inf | infCR == -Inf] = NA
supCR <- apply(center, 1,function(x) suppressWarnings(max(x, na.rm=TRUE))); supCR[supCR == Inf | supCR == -Inf] = NA
upperWhisker <- supCR + fmag*(supCR-infCR)
lowerWhisker <- infCR - fmag*(supCR-infCR)
if(fdom < 1){
dom.out <- which(colSums(data <= lowerWhisker & propCR <= fdom |
data >= upperWhisker & propCR <= fdom, na.rm = TRUE) != 0)
}else{
dom.out <- which(colSums(data <= lowerWhisker & propCR < fdom |
data >= upperWhisker & propCR < fdom, na.rm = TRUE) != 0)
}
mag.out <- which(colSums( data <= lowerWhisker | data >= upperWhisker , na.rm = TRUE) != 0)
fdata <- data.frame(id = rep(ids, each = P),
x = rep(x, N),
y = c(data)
)
fdataMag <- data.frame(id = rep(mag.out, each = P),
x = rep(x, length(mag.out)),
y = c(data[,mag.out])
)
fdataDom <- data.frame(id = rep(dom.out, each = P),
x = rep(x, length(dom.out)),
y = c(data[,dom.out])
)
dataWinkler <- data.frame(id = c(rep(1, P), rep(2, P)),
x = c(x, rev(x)),
y = c(upperWhisker, rev(lowerWhisker)),
wcol = c(w, rev(w)))
dataWinklerBars <- data.frame(
colBar = c(w[ceiling(P/2)], w[ceiling(P/2)]),
x1 = c(x[ceiling(P/2)], x[ceiling(P/2)]),
x2 = c(x[ceiling(P/2)], x[ceiling(P/2)]),
y1 = c(supCR[ceiling(P/2)], infCR[ceiling(P/2)]),
y2 = c(upperWhisker[ceiling(P/2)], lowerWhisker[ceiling(P/2)])
)
auxPolygonX <- c(matrix(rep(c(1,2,2,1), P-1), nrow = 4) + matrix(rep(seq(0:c(P-2))-1, each = 4), nrow = 4))
auxPolygonLowHigh <- c(matrix(rep(c(1,2,P+2,P+1), P-1), nrow = 4) + matrix(rep(seq(0:c(P-2))-1, each = 4), nrow = 4))
dataBand <- data.frame(
id = rep(factor(1:c(P-1)), each = 4),
x = x[auxPolygonX],
y = c(infCR, supCR)[auxPolygonLowHigh],
wcol = rep(w[2:P], each = 4)
)
ggplot2::ggplot() +
ggplot2::geom_polygon(data = dataBand, aes(x = .data$x, y = .data$y, group = .data$id, fill = .data$wcol, color = .data$wcol)) +
ggplot2::geom_line(data = fdata[fdata$id == median,], aes(x = .data$x, y = .data$y), color = 'yellow', cex = 0.75) +
ggplot2::geom_line(data = dataWinkler, aes(x = .data$x, y = .data$y, group = .data$id, color = .data$wcol), cex = 1) +
ggplot2::geom_segment(data = dataWinklerBars, aes(x = .data$x1, y = .data$y1, xend = .data$x2, yend = .data$y2, color =.data$colBar), size = 0.75) +
ggplot2::geom_line(data = fdataMag, aes(x = .data$x, y = .data$y, group = .data$id), color='blue', cex = 0.75)+
ggplot2::geom_line(data = fdataDom, aes(x = .data$x, y = .data$y, group = .data$id), color='red', linetype = "dashed", cex = 0.75)+
ggplot2::scale_fill_gradient(low = "white", high = "black", limits=c(0, 1) , aesthetics = c('fill', "color")) +
ggplot2::labs(x = "", y ="")+
ggplot2::theme(legend.position = "none",
legend.key.size = unit(0.75, "cm"),
legend.title = element_blank(),
panel.background = element_blank(),
plot.title = element_text(hjust = 0.5),
axis.line = element_line(colour = "black",
size = rel(1))
) -> boxplotPartially
return(list(fboxplot = boxplotPartially, all.out = unique(c(mag.out, dom.out)), magnitude = mag.out, domain = dom.out))
} |
geom_contour <- function(mapping = NULL, data = NULL,
stat = "contour", position = "identity",
...,
lineend = "butt",
linejoin = "round",
linemitre = 1,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomContour,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
lineend = lineend,
linejoin = linejoin,
linemitre = linemitre,
na.rm = na.rm,
...
)
)
}
GeomContour <- gganimintproto("GeomContour", GeomPath,
default_aes = aes(weight = 1, colour = "
pre_process = function(g, g.data, ...) {
g$aes[["group"]] <- "piece"
g$geom <- "path"
return(list(g = g, g.data = g.data))
}
) |
NULL
if (!methods::isClass("ArrayParameter")) methods::setOldClass("ArrayParameter")
NULL
NULL
ArrayParameter <- pproto(
"ArrayParameter",
Parameter,
label = character(0),
upper_limit = numeric(0),
lower_limit = numeric(0),
length = 0,
repr = function(self) {
paste0(self$name, " (min: ", min(self$value), ", max: ",
max(self$value), ")")
},
validate = function(self, x) {
assertthat::assert_that(inherits(x, "data.frame"))
invisible(assertthat::see_if(
identical(names(x), "value"),
all(is.finite(x[[1]])),
ncol(x) == 1,
nrow(x) == self$length,
inherits(x[[1]], self$class),
setequal(self$label, rownames(x)),
sum(!is.finite(x[[1]])) == 0,
isTRUE(all(x[[1]] >= self$lower_limit)),
isTRUE(all(x[[1]] <= self$upper_limit))))
},
set = function(self, x) {
check_that(self$validate(x))
self$value <- x[[1]][match(rownames(x), self$label)]
},
get = function(self) {
structure(list(value = self$value),
.Names = "value",
row.names = self$label,
class = "data.frame")
},
render = function(self, ...) {
pkg <- strsplit(self$widget, "::")[[1]][[1]]
if (!requireNamespace(pkg, quietly = TRUE))
stop(paste0("the \"", pkg, "\" R package must be installed to render",
" this parameter."))
f <- do.call(utils::getFromNamespace,
as.list(rev(strsplit(self$widget, "::")[[1]])))
do.call(f, list(outputId = self$id))
}) |
doQmapPTF <- function(x,fobj,...){
if(!any(class(fobj)=="fitQmapPTF"))
stop("class(fobj) should be fitQmapPTF")
UseMethod("doQmapPTF")
}
doQmapPTF.default <- function(x,fobj,...){
ffun <- fobj$tfun
funpar <- fobj$par
wett <- if(!is.null(fobj$wet.day)){
x>=fobj$wet.day
} else {
rep(TRUE,length(x))
}
x[wett] <- do.call(ffun,c(list(x[wett]),as.list(funpar)))
x[!wett] <- 0
if(!is.null(fobj$wet.day))
x[x<0] <- 0
return(x)
}
doQmapPTF.matrix <- function (x, fobj, ...) {
if (ncol(x) != nrow(fobj$par))
stop("'ncol(x)' and 'nrow(fobj$par)' should be eaqual\n")
NN <- ncol(x)
hind <- 1:NN
names(hind) <- colnames(x)
tfun <- fobj$tfun
funpar <- fobj$par
xx <- sapply(hind, function(i) {
tr <- try({
xh <- x[, i]
wett <- if (!is.null(fobj$wet.day)) {
xh >= fobj$wet.day[i]
} else {
rep(TRUE, length(xh))
}
xh[wett] <- do.call(tfun, c(list(xh[wett]), as.list(funpar[i,
])))
xh[!wett] <- 0
if (!is.null(fobj$wet.day))
xh[xh < 0] <- 0
xh
}, silent = TRUE)
if (class(tr) == "try-error") {
warning("Quantile mapping for ", names(hind)[i],
" failed NA's produced.")
tr <- rep(NA, nrow(x))
}
return(tr)
})
rownames(xx) <- rownames(x)
return(xx)
}
doQmapPTF.data.frame <- function(x,fobj,...){
x <- as.matrix(x)
x <- doQmapPTF.matrix(x,fobj,...)
x <- as.data.frame(x)
return(x)
} |
context('get_cw_file')
test_that('Failed to read crosswalk file of type: delimited (pipe)', {
cw <- get_cw_file('./testdata/cw.txt', delimiter = '|')
expect_is(cw, 'data.frame')
expect_identical(names(cw), c('a','b'))
expect_identical(unlist(cw[1,], use.names = FALSE), c('1','2'))
})
test_that('Failed to read crosswalk file of type: delimited (CSV)', {
cw <- get_cw_file('./testdata/cw.csv')
expect_is(cw, 'data.frame')
expect_identical(names(cw), c('a','b'))
expect_identical(unlist(cw[1,], use.names = FALSE), c('1','2'))
})
test_that('Failed to read crosswalk file of type: delimited (TSV)', {
cw <- get_cw_file('./testdata/cw.tsv')
expect_is(cw, 'data.frame')
expect_identical(names(cw), c('a','b'))
expect_identical(unlist(cw[1,], use.names = FALSE), c('1','2'))
})
test_that('Failed to read crosswalk file of type: Excel (XLS)', {
cw <- get_cw_file('./testdata/cw.xls')
expect_is(cw, 'data.frame')
expect_identical(names(cw), c('a','b'))
expect_identical(unlist(cw[1,], use.names = FALSE), c('1','2'))
})
test_that('Failed to read crosswalk file of type: Excel (XLSX)', {
cw <- get_cw_file('./testdata/cw.xlsx')
expect_is(cw, 'data.frame')
expect_identical(names(cw), c('a','b'))
expect_identical(unlist(cw[1,], use.names = FALSE), c('1','2'))
})
test_that('Failed to read crosswalk file of type: Stata (DTA)', {
cw <- get_cw_file('./testdata/cw.dta')
expect_is(cw, 'data.frame')
expect_identical(names(cw), c('a','b'))
expect_identical(unlist(cw[1,], use.names = FALSE), c('1','2'))
}) |
zotero_download_and_export_items <- function(group,
file,
format = "bibtex",
showKeys = TRUE) {
bibliography <-
zotero_get_all_items(group = group,
format = format);
if (dir.exists(dirname(file))) {
writeLines(bibliography, file);
} else {
warning(
paste0(
"You specified filename `",
file,
"` to write to, but the directory in that path does not exist."
)
)
}
if (showKeys) {
print(gsub("^@[a-zA-Z0-9]+\\{(.*),",
"\\1",
bibliography)[grep("^@[a-zA-Z0-9]+\\{(.*),", bibliography)]);
}
return(invisible(bibliography));
} |
library(knitr)
knitr::opts_chunk$set(fig.height=4, fig.width=6,
cache=TRUE, autodep = TRUE, cache.path = 'show_lemonade/')
library(ggplot2)
library(gtable)
library(grid)
dat1 <- data.frame(
gp = factor(rep(letters[1:3], each = 10)),
y = rnorm(30),
cl = sample.int(3, 30, replace=TRUE),
cl2 = sample(c('a','b','c'), 30, replace=TRUE)
)
my.theme <- theme_light()
(
p <- ggplot(dat1, aes(gp, y)) + geom_point() + my.theme
)
g <- ggplotGrob(p)
for (i in 1:nrow(g$layout)) {
if (g$layout$name[i] == 'lemon') next
h <- g$heights[[g$layout$t[i]]]
rot <- if (as.character(h) == "1null") 90 else 0
w <- g$widths[[g$layout$l[i]]]
rot <- if (rot == 90 && as.character(w) == "1null") 0 else rot
r <- rectGrob(gp=gpar(col='black', fill='white', alpha=1/4))
t <- textGrob(g$layout$name[i], rot = rot)
g$grobs[[i]] <- grobTree(r, t)
}
grid.newpage()
grid.draw(g)
is.small <- function(x) {
if (!is.unit(x)) stop('`h` is not a unit.')
if (is.null(attr(x, 'unit'))) return(FALSE)
if (as.numeric(x) == 1 & attr(x, 'unit') == 'null') return(FALSE)
if (as.numeric(x) == 0) return(TRUE)
n <- as.numeric(x)
r <- switch(attr(x, 'unit'),
'null'= FALSE,
'line'= n < 1,
'pt'= n < 10,
'cm' = n < 1,
'grobheight' = FALSE,
'grobwidth' = FALSE,
NA)
return(r)
}
g <- ggplotGrob(p)
gp.gutter <- gpar(colour='grey', lty='dashed')
g <- gtable_add_cols(g, unit(2, 'line'), 0)
for (i in 2:nrow(g)) {
g <- gtable_add_grob(g, t=i, l=1, clip='off', grobs=grobTree(
textGrob(sprintf('(%d, )', i-1)),
linesGrob(x=unit(c(-100,100), 'npc'), y=1, gp=gp.gutter)
), name='lemon')
if (is.small(g$heights[[i]])) g$heights[[i]] <- unit(1, 'line')
}
g <- gtable_add_rows(g, unit(1, 'line'), 0)
for (i in 2:ncol(g)) {
g <- gtable_add_grob(g, t=1, l=i, clip='off', grobs=grobTree(
textGrob(sprintf('( ,%d)', i-1)),
linesGrob(x=1, unit(c(-100, 100), 'npc'), gp=gp.gutter)
), name='lemon')
if (is.small(g$widths[[i]])) g$widths[[i]] <- unit(2, 'line')
}
grid.newpage()
grid.draw(g)
gtable_show_grill <- function(x, plot=TRUE) {
if (is.ggplot(x)) x <- ggplotGrob(x)
gp.gutter <- gpar(colour='grey', lty='dashed')
if (is.null(x$vp)) {
x$vp <- viewport(clip = 'on')
}
x <- gtable_add_cols(x, unit(2, 'line'), 0)
for (i in 2:nrow(x)) {
x <- gtable_add_grob(x, t=i, l=1, clip='off', grobs=grobTree(
textGrob(sprintf('[%d, ]', i-1)),
linesGrob(x=unit(c(-100,100), 'npc'), y=1, gp=gp.gutter)
), name='lemon')
if (is.small(x$heights[[i]])) x$heights[[i]] <- unit(1, 'line')
}
x <- gtable_add_rows(x, unit(1, 'line'), 0)
for (i in 2:ncol(x)) {
x <- gtable_add_grob(x, t=1, l=i, clip='off', grobs=grobTree(
textGrob(sprintf('[ ,%d]', i-1)),
linesGrob(x=1, unit(c(-100, 100), 'npc'), gp=gp.gutter)
), name='lemon')
if (is.small(x$widths[[i]])) x$widths[[i]] <- unit(2, 'line')
}
if (plot) {
grid.newpage()
grid.draw(x)
}
invisible(x)
}
gtable_show_grill(p)
gtable_show_names <- function(x, plot=TRUE) {
if (is.ggplot(x)) x <- ggplotGrob(x)
for (i in 1:nrow(x$layout)) {
if (x$layout$name[i] == 'lemon') next
if (grepl('ylab', x$layout$name[i])) {
rot <- 90
} else if (grepl('-l', x$layout$name[i])) {
rot <- 90
} else if (grepl('-r', x$layout$name[i])) {
rot <- 90
} else {
rot <- 0
}
r <- rectGrob(gp=gpar(col='black', fill='white', alpha=1/4))
t <- textGrob(x$layout$name[i], rot = rot)
x$grobs[[i]] <- grobTree(r, t)
}
if (plot) {
grid.newpage()
grid.draw(x)
}
invisible(x)
}
gtable_show_names(p)
gtable_show_names(gtable_show_grill(p, plot=FALSE))
try(rm(list=c('gtable_show_names','gtable_show_grill')), silent=TRUE)
library(lemon)
print(p)
grid.draw(gtable_show_names(p, plot=FALSE))
gp <- ggplotGrob(p)
gp <- gtable_add_rows(gp, g$heights[1], 0)
gp <- gtable_add_cols(gp, unit(1.5, 'line'))
gp <- gtable_add_grob(gp, linesGrob(x=0.5, gp=gpar(colour='grey', lwd=1.2)), t=1, b=nrow(gp), l=ncol(gp))
g <- gtable_show_names(gtable_show_grill(p, plot=FALSE), plot=FALSE)
g <- cbind(gp, g)
grid.newpage()
grid.draw(g) |
marginalRelevance <- function (x, y)
{
e1 <- new.env()
if (!is.factor(y))
stop("error: y is not a factor")
NF <- dim(x)[2]
NK <- length(unique(y))
u <- matrix(0, 1, NF)
l <- matrix(0, 1, NF)
xOrdered <- matrix(0, dim(x)[1], NF)
bestVars <- matrix(0, 1, NF)
x_dot_f <- apply(x, 2, mean)
for (k in 1:NK) {
u <- u + sum(y == levels(y)[k]) * ((apply(x[y == levels(y)[k],
], 2, mean) - x_dot_f)^2)
l <- l + apply((x[y == levels(y)[k], ] - kronecker(matrix(1,
sum(y == levels(y)[k]), 1), t(as.matrix(apply(x[y ==
levels(y)[k], ], 2, mean)))))^2, 2, sum)
}
e1$score <- u/l
e1$rank <- rank(-e1$score, ties.method = "random")
for (i in 1:NF) {
bestVars[i] <- which(e1$rank == i)
xOrdered[, i] <- x[, which(e1$rank == i)]
}
e1$bestVars <- bestVars
e1$orderedData <- xOrdered
e1 <- as.list(e1)
class(e1) = "marginalRelevance"
return(e1)
} |
if(interactive()) {
library(parcoords)
library(shiny)
ui <- tagList(
textOutput("filteredstate", container=h3),
parcoordsOutput("pc")
)
server <- function(input, output, session) {
rv <- reactiveValues(filtered = FALSE)
output$pc <- renderParcoords({
parcoords(mtcars)
})
observe({
invalidateLater(2500)
rv$filtered <- !isolate(rv$filtered)
})
observeEvent(rv$filtered, {
pcp <- parcoordsProxy("pc")
if(rv$filtered) {
pcFilter(
pcp,
list(
cyl = c(6,8),
hp = list(gt = 200)
)
)
} else {
pcFilter(pcp, list())
}
})
output$filteredstate <- renderText({
paste0("Filtered: ", rv$filtered)
})
}
shinyApp(ui = ui, server = server)
library(shiny)
library(parcoords)
ui <- tags$div(
parcoordsOutput("pc", width = 2500),
style="width: 2500px;"
)
server <- function(input, output, session) {
pcp <- parcoordsProxy("pc")
output$pc <- renderParcoords({
parcoords(mtcars)
})
pcCenter(pcp, 'drat')
}
shinyApp(ui=ui, server=server)
library(parcoords)
library(shiny)
ui <- tagList(
selectizeInput(
inputId = "columns",
label = "Columns to Hide",
choices = c("names",colnames(mtcars)),
selected = "names",
multiple = TRUE
),
parcoordsOutput("pc"),
checkboxInput("hidenames", label="Hide Row Names", value=TRUE),
parcoordsOutput("pc2")
)
server <- function(input, output, session) {
output$pc <- renderParcoords({
parcoords(mtcars, rownames = FALSE, brushMode = "1d")
})
output$pc2 <- renderParcoords({
parcoords(mtcars, rownames = FALSE)
})
pcUnhide
observeEvent(input$columns, {
pcp <- parcoordsProxy("pc")
pcHide(pcp, input$columns)
}, ignoreInit = TRUE, ignoreNULL = FALSE)
observeEvent(input$hidenames, {
pcp2 <- parcoordsProxy("pc2")
if(input$hidenames) {
pcHide(pcp2, "names")
} else {
pcUnhide(pcp2, "names")
}
})
}
shinyApp(ui = ui, server = server)
library(shiny)
library(parcoords)
ui <- tags$div(
actionButton(inputId = "snapBtn", label = "snapshot"),
parcoordsOutput("pc", height=400)
)
server <- function(input, output, session) {
pcp <- parcoordsProxy("pc")
output$pc <- renderParcoords({
parcoords(mtcars)
})
observeEvent(input$snapBtn, {
pcp <- parcoordsProxy("pc")
pcSnapshot(pcp)
})
}
shinyApp(ui=ui, server=server)
} |
gridfs <- function(db = "test", url = "mongodb://localhost", prefix = "fs", options = ssl_options()){
client <- new_client(c(list(uri = url), options))
if(missing(db) || is.null(db)){
url_db <- mongo_get_default_database(client)
if(length(url_db) && nchar(url_db))
db <- url_db
}
fs <- mongo_gridfs_new(client, prefix, db)
orig <- list(
prefix = prefix,
db = db,
url = url,
options = options
)
if(length(options$pem_file) && file.exists(options$pem_file))
attr(orig, "pemdata") <- readLines(options$pem_file)
rm(client)
fs_object(fs, orig)
}
fs_object <- function(fs, orig){
check_fs <- function(){
if(null_ptr(fs)){
message("Connection lost. Trying to reconnect with mongo...")
fs <<- gridfs_reset(orig)
}
}
self <- local({
drop <- function(){
check_fs()
mongo_gridfs_drop(fs)
}
find <- function(filter = '{}', options = '{}'){
check_fs()
mongo_gridfs_find(fs, filter, options)
}
upload <- function(path, name = basename(path), content_type = NULL, metadata = NULL){
check_fs()
mongo_gridfs_upload(fs, name, path, content_type, metadata)
}
download <- function(name, path = "."){
check_fs()
mongo_gridfs_download(fs, name, path)
}
read <- function(name, con = NULL, progress = TRUE){
check_fs()
mongo_gridfs_read_stream(fs, name, con, progress)
}
write <- function(con, name, content_type = NULL, metadata = NULL, progress = TRUE){
check_fs()
mongo_gridfs_write_stream(fs, name, con, content_type, metadata, progress)
}
remove <- function(name){
check_fs()
mongo_gridfs_remove(fs, name)
}
disconnect <- function(gc = TRUE){
mongo_gridfs_disconnect(fs)
if(isTRUE(gc))
base::gc()
invisible()
}
environment()
})
lockEnvironment(self, TRUE)
structure(self, class=c("gridfs", "jeroen", class(self)))
}
gridfs_reset <- function(orig){
if(length(orig$options$pem_file) && !file.exists(orig$options$pem_file)){
orig$options$pem_file <- tempfile()
writeLines(attr(orig, "pemdata"), orig$options$pem_file)
}
client <- new_client(c(list(uri = orig$url), orig$options))
mongo_gridfs_new(client, prefix = orig$prefix, db = orig$db)
}
mongo_gridfs_new <- function(client, prefix, db){
.Call(R_mongo_gridfs_new, client, prefix, db)
}
mongo_gridfs_drop <- function(fs){
.Call(R_mongo_gridfs_drop, fs)
}
mongo_gridfs_find <- function(fs, filter, opts){
out <- .Call(R_mongo_gridfs_find, fs, bson_or_json(filter), bson_or_json(opts))
list_to_df(out)
}
mongo_gridfs_disconnect <- function(fs){
stopifnot(inherits(fs, "mongo_gridfs"))
.Call(R_mongo_gridfs_disconnect, fs)
}
mongo_gridfs_upload <- function(fs, name, path, type, metadata){
stopifnot(is.character(name))
path <- normalizePath(path, mustWork = TRUE)
is_dir <- file.info(path)$isdir
if(any(is_dir))
stop(sprintf("Upload contains directories, you can only upload files (%s)", paste(path[is_dir], collapse = ", ")))
stopifnot(length(name) == length(path))
id <- rep(NA, length(name))
if(is.null(type))
type <- mime::guess_type(name, unknown = NA, empty = NA)
type <- as.character(rep_len(type, length(name)))
metadata <- if(length(metadata))
bson_or_json(metadata)
out <- vector("list", length(name))
for(i in seq_along(name)){
out[[i]] <- .Call(R_mongo_gridfs_upload, fs, name[i], path[i], type[i], metadata)
}
df <- list_to_df(out)
df$path = path
df
}
mongo_gridfs_download <- function(fs, name, path){
if(length(path) == 1 && isTRUE(file.info(path)$isdir)){
path <- normalizePath(file.path(path, name), mustWork = FALSE)
} else if(length(name) != length(path)){
stop("Argument 'path' must be an existing dir or vector of filenames equal length as 'name'")
}
path <- normalizePath(path, mustWork = FALSE)
lapply(path, function(x){ dir.create(dirname(x), showWarnings = FALSE, recursive = TRUE)})
stopifnot(length(name) == length(path))
out <- vector("list", length(name))
for(i in seq_along(name)){
out[[i]] <- .Call(R_mongo_gridfs_download, fs, name_or_query(name[i]), path[i])
}
df <- list_to_df(out)
df$path = path
df
}
mongo_gridfs_remove <- function(fs, name){
out <- lapply(name, function(x){
.Call(R_mongo_gridfs_remove, fs, name_or_query(x))
})
list_to_df(out)
}
mongo_gridfs_read_stream <- function(fs, name, con, progress = TRUE){
name <- name_or_query(name)
stream <- .Call(R_new_read_stream, fs, name)
size <- attr(stream, 'size')
if(length(con) && is.character(con))
con <- file(con, raw = TRUE)
if(!length(con)){
con <- rawConnection(raw(size), 'wb')
on.exit(close(con))
}
stopifnot(inherits(con, "connection"))
if(!isOpen(con)){
open(con, 'wb')
on.exit(close(con))
}
remaining <- size
bufsize <- 1024 * 1024
while(remaining > 0){
buf <- .Call(R_stream_read_chunk, stream, bufsize)
remaining <- remaining - length(buf)
if(length(buf) < bufsize && remaining > 0)
stop("Stream read incomplete: ", remaining, " remaining")
writeBin(buf, con)
if(isTRUE(progress))
cat(sprintf("\r[%s]: read %s (%d%%) ", name, as_size(size - remaining), as.integer(100 * (size - remaining) / size)))
}
if(isTRUE(progress))
cat(sprintf("\r[%s]: read %s (done)\n", name, as_size(size - remaining)))
out <- .Call(R_stream_close, stream)
if(inherits(con, 'rawConnection'))
out$data <- rawConnectionValue(con)
structure(out, class = "miniprint")
}
mongo_gridfs_write_stream <- function(fs, name, con, type, metadata, progress = TRUE){
stopifnot(is.character(name))
type <- as.character(type)
metadata <- if(length(metadata))
bson_or_json(metadata)
stream <- .Call(R_new_write_stream, fs, name, type, metadata)
if(length(con) && is.character(con)){
con <- if(grepl("^https?://", con)){
url(con)
} else {
file(con, raw = TRUE)
}
}
if(is.raw(con)){
con <- rawConnection(con, 'rb')
on.exit(close(con))
}
stopifnot(inherits(con, "connection"))
if(!isOpen(con)){
open(con, 'rb')
on.exit(close(con))
}
total <- 0
bufsize <- 1024 * 1024
repeat {
buf <- readBin(con, raw(), bufsize)
total <- total + .Call(R_stream_write_chunk, stream, buf)
if(!length(buf))
break
if(isTRUE(progress))
cat(sprintf("\r[%s]: written %s ", name, as_size(total)))
}
if(isTRUE(progress))
cat(sprintf("\r[%s]: written %s (done)\n", name, as_size(total)))
out <- .Call(R_stream_close, stream)
structure(out, class = "miniprint")
}
as_size <- function(n) {
format(structure(n, class="object_size"), units="auto", standard = "SI", digits = 2L)
}
list_to_df <- function(list, cols = c("id", "name", "size", "date", "type", "metadata")){
out <- lapply(cols, function(col){
sapply(list, `[[`, col)
})
df <- structure(out, class="data.frame", names = cols, row.names = seq_along(list))
class(df$date) = c("POSIXct", "POSIXt")
df
}
name_or_query <- function(x){
if(!is.character(x)){
stop("Parameter 'name' must be a json query or filename (without spaces)")
}
if(grepl("^id:", x)){
x <- sprintf('{"_id": {"$oid":"%s"}}', sub("^id:", "", x))
}
if(jsonlite::validate(x)){
return(bson_or_json(x))
} else {
if(grepl("[\t {]", x)){
stop("Parameter 'name' does not contain valid json or filename (no spaces)")
}
return(x)
}
} |
NULL
get_hsy <- function(which.data=NULL, which.year=2013, data.dir=tempdir(), verbose=TRUE) {
if (which.data=="Vaestotietoruudukko") {
.Deprecated(new = "get_vaestotietoruudukko", package = "helsinki")
message("get_hsy() has been deprecated, use get_vaestotietoruudukko() instead")
return(NULL)
} else if (which.data=="Rakennustietoruudukko") {
.Deprecated(new = "get_rakennustietoruudukko", package = "helsinki")
message("get_hsy() has been deprecated, use get_vaestotietoruudukko() instead")
return(NULL)
} else if (is.null(which.data)) {
.Deprecated("get_feature")
message("get_hsy() has been deprecated, use get_feature_list() to browse for available HSY features and get_feature() to download them")
return(NULL)
} else {
.Deprecated("get_feature")
message("get_hsy() has been deprecated, use get_feature_list() to browse for available HSY features and get_feature() to download them")
return(NULL)
}
}
get_vaestotietoruudukko <- function(year = NULL) {
namespace_title <- "asuminen_ja_maankaytto:Vaestotietoruudukko"
base_url <- "https://kartta.hsy.fi/geoserver/wfs"
valid_years <- 2015:2020
if (is.null(year)) {
message(paste0("year = NULL! Retrieving feature from year ", max(valid_years)))
year <- max(valid_years)
}
if (!(year %in% valid_years)) {
message(paste0("It is strongly suggested to use a valid year from range: 2015-2019.
Using other years may result in an error."))
}
selection <- paste(namespace_title, year, sep = "_")
feature <- get_feature(base.url = base_url, typename = selection)
feature
}
get_rakennustietoruudukko <- function(year = NULL) {
namespace_title <- "asuminen_ja_maankaytto:Rakennustietoruudukko"
base_url <- "https://kartta.hsy.fi/geoserver/wfs"
valid_years <- 2015:2020
if (is.null(year)) {
message(paste0("year = NULL! Retrieving feature from year ", max(valid_years)))
year <- max(valid_years)
}
if (!(year %in% valid_years)) {
message(paste0("It is strongly suggested to use a valid year from range: 2015-2019.
Using other years may result in an error."))
}
selection <- paste(namespace_title, year, sep = "_")
feature <- get_feature(base.url = base_url, typename = selection)
feature
} |
get_models <- function(fixed, random = NULL, data, auxvars = NULL,
timevar = NULL, no_model = NULL, models = NULL,
analysis_type = NULL, warn = TRUE) {
if (missing(fixed))
errormsg("No formula specified.")
if (missing(data))
errormsg("No dataset given.")
if (!is.null(auxvars) & class(auxvars) != 'formula')
errormsg("The argument %s should be a formula.", dQuote("auxvars"))
models_user <- models
if (is.null(attr(fixed[[1]], 'type')))
fixed <- extract_outcome_data(fixed, random = random, data = data,
analysis_type = analysis_type,
warn = FALSE)$fixed
if (!is.null(timevar)) {
no_model <- c(no_model, timevar)
}
allvars <- unique(c(all_vars(c(fixed, random, auxvars)), timevar))
if (any(!names(models) %in% names(data))) {
errormsg("Variable(s) %s were not found in the data." ,
paste_and(dQuote(names(models)[!names(models) %in% names(data)])))
}
if (!is.null(no_model) &&
any(colSums(is.na(data[, no_model, drop = FALSE])) > 0)) {
errormsg("Variable(s) %s have missing values and imputation models are
needed for these variables." ,
paste(dQuote(no_model[colSums(is.na(data[, no_model,
drop = FALSE])) > 0]),
collapse = ", "))
}
if (any(!names(models_user) %in% allvars)) {
errormsg("You have specified covariate model types for the variable(s) %s
which are not part of the model.",
paste_and(dQuote(names(models_user)[
!names(models_user) %in% allvars])))
}
idvar <- extract_id(random, warn = warn)
groups <- get_groups(idvar, data)
random2 <- remove_grouping(random)
allvars <- unique(c(names(fixed),
all_vars(c(remove_lhs(fixed), random2, auxvars)),
names(models), timevar))
group_lvls <- colSums(!identify_level_relations(groups))
max_lvl <- max(group_lvls)
if (length(allvars) > 0) {
varinfo <- sapply(allvars, function(k) {
x <- eval(parse(text = k), envir = data)
out <- k %in% names(fixed)
lvl <- group_lvls[
check_varlevel(x, groups, group_lvls = identify_level_relations(groups))]
nmis <- sum(is.na(x[match(unique(groups[[names(lvl)]]),
groups[[names(lvl)]])]))
nlev <- length(levels(x))
ordered <- is.ordered(x)
data.frame(out = out, lvl = lvl, nmis = nmis, nlev = nlev,
ordered = ordered, type = NA)
}, simplify = FALSE)
varinfo <- melt_data.frame_list(varinfo, id.vars = colnames(varinfo[[1]]))
varinfo$type[!varinfo$lvl %in% max_lvl & varinfo$nlev > 2 &
varinfo$ordered] <- "clmm"
varinfo$type[varinfo$lvl %in% max_lvl & varinfo$nlev > 2 &
varinfo$ordered] <- "clm"
varinfo$type[!varinfo$lvl %in% max_lvl & varinfo$nlev > 2 &
!varinfo$ordered] <- "mlogitmm"
varinfo$type[varinfo$lvl %in% max_lvl & varinfo$nlev > 2 &
!varinfo$ordered] <- "mlogit"
varinfo$type[!varinfo$lvl %in% max_lvl & varinfo$nlev == 2] <-
"glmm_binomial_logit"
varinfo$type[varinfo$lvl %in% max_lvl & varinfo$nlev == 2] <-
"glm_binomial_logit"
varinfo$type[!varinfo$lvl %in% max_lvl & varinfo$nlev == 0] <- "lmm"
varinfo$type[varinfo$lvl %in% max_lvl & varinfo$nlev == 0] <- "lm"
survmods <- sapply(fixed, 'attr', 'type') %in% c('coxph', 'survreg', 'JM')
if (any(survmods)) {
varinfo$type[varinfo$L1 %in% names(fixed[survmods])] <-
sapply(fixed[survmods], 'attr', 'type')
}
if (!is.null(attr(fixed[[1]], 'type')))
varinfo$type[varinfo$L1 %in% names(fixed)[1]] <- attr(fixed[[1]], 'type')
varinfo <- varinfo[which(!varinfo$L1 %in% no_model), , drop = FALSE]
types <- split(varinfo,
ifelse(varinfo$out, 'outcome',
ifelse(varinfo$nmis > 0,
paste0('incomplete_lvl', varinfo$lvl),
paste0('complete_lvl', varinfo$lvl)
)))
types[which(names(types) != 'outcome')] <-
lapply(types[which(names(types) != 'outcome')], function(x)
x[order(-x$lvl, x$nmis, decreasing = TRUE), , drop = FALSE]
)
NA_lvls <- unique(varinfo$lvl[varinfo$nmis > 0])
models <- do.call(rbind,
c(types['outcome'],
if (any(!varinfo$out) & length(NA_lvls) > 0)
lapply(1:max(NA_lvls), function(k) {
set <- if (k == max(NA_lvls)) {
c('incomplete_lvl')
} else {
c('incomplete_lvl', 'complete_lvl')
}
do.call(rbind, types[paste0(set, k)])
})
))
models <- unlist(setNames(models$type, models$L1))
models[names(models_user)] <- models_user
} else {
models <- NULL
}
models
} |
read_sbatch <- function(x) {
dat <- if (length(x) == 1 && file.exists(x))
unlist(strsplit(readLines(x), split = "\n"))
else x
dat <- dat[grepl("^(
opts_ids <- which(grepl("^
if (!length(opts_ids))
return(character(0))
opts <- dat[opts_ids]
opts <- gsub("^
opts_names <- gsub("=.+", "", opts)
opts_names <- gsub("^[-]{2}", "", opts_names)
opts <- gsub(".+=", "", opts)
structure(
opts, names = opts_names
)
} |
NULL
drdid_rc1 <-function(y, post, D, covariates, i.weights = NULL,
boot = FALSE, boot.type = "weighted", nboot = NULL,
inffunc = FALSE){
D <- as.vector(D)
n <- length(D)
y <- as.vector(y)
post <- as.vector(post)
int.cov <- as.matrix(rep(1,n))
if (!is.null(covariates)){
if(all(as.matrix(covariates)[,1]==rep(1,n))){
int.cov <- as.matrix(covariates)
} else {
int.cov <- as.matrix(cbind(1, covariates))
}
}
if(is.null(i.weights)) {
i.weights <- as.vector(rep(1, n))
} else if(min(i.weights) < 0) stop("i.weights must be non-negative")
pscore.tr <- stats::glm(D ~ -1 + int.cov, family = "binomial", weights = i.weights)
if(pscore.tr$converged == FALSE){
warning(" glm algorithm did not converge")
}
if(anyNA(pscore.tr$coefficients)){
stop("Propensity score model coefficients have NA components. \n Multicollinearity (or lack of variation) of covariates is a likely reason.")
}
ps.fit <- as.vector(pscore.tr$fitted.values)
ps.fit <- pmin(ps.fit, 1 - 1e-16)
reg.coeff.pre <- stats::coef(stats::lm(y ~ -1 + int.cov,
subset = ((D==0) & (post==0)),
weights = i.weights))
if(anyNA(reg.coeff.pre)){
stop("Outcome regression model coefficients have NA components. \n Multicollinearity (or lack of variation) of covariates is a likely reason.")
}
out.y.pre <- as.vector(tcrossprod(reg.coeff.pre, int.cov))
reg.coeff.post <- stats::coef(stats::lm(y ~ -1 + int.cov,
subset = ((D==0) & (post==1)),
weights = i.weights))
if(anyNA(reg.coeff.post)){
stop("Outcome regression model coefficients have NA components. \n Multicollinearity (or lack of variation) of covariates is a likely reason.")
}
out.y.post <- as.vector(tcrossprod(reg.coeff.post, int.cov))
out.y <- post * out.y.post + (1 - post) * out.y.pre
w.treat.pre <- i.weights * D * (1 - post)
w.treat.post <- i.weights * D * post
w.cont.pre <- i.weights * ps.fit * (1 - D) * (1 - post)/(1 - ps.fit)
w.cont.post <- i.weights * ps.fit * (1 - D) * post/(1 - ps.fit)
eta.treat.pre <- w.treat.pre * (y - out.y) / mean(w.treat.pre)
eta.treat.post <- w.treat.post * (y - out.y)/ mean(w.treat.post)
eta.cont.pre <- w.cont.pre * (y - out.y) / mean(w.cont.pre)
eta.cont.post <- w.cont.post * (y - out.y) / mean(w.cont.post)
att.treat.pre <- mean(eta.treat.pre)
att.treat.post <- mean(eta.treat.post)
att.cont.pre <- mean(eta.cont.pre)
att.cont.post <- mean(eta.cont.post)
dr.att <- (att.treat.post - att.treat.pre) - (att.cont.post - att.cont.pre)
weights.ols.pre <- i.weights * (1 - D) * (1 - post)
wols.x.pre <- weights.ols.pre * int.cov
wols.eX.pre <- weights.ols.pre * (y - out.y.pre) * int.cov
XpX.inv.pre <- solve(crossprod(wols.x.pre, int.cov)/n)
asy.lin.rep.ols.pre <- wols.eX.pre %*% XpX.inv.pre
weights.ols.post <- i.weights * (1 - D) * post
wols.x.post <- weights.ols.post * int.cov
wols.eX.post <- weights.ols.post * (y - out.y.post) * int.cov
XpX.inv.post <- solve(crossprod(wols.x.post, int.cov)/n)
asy.lin.rep.ols.post <- wols.eX.post %*% XpX.inv.post
score.ps <- i.weights * (D - ps.fit) * int.cov
Hessian.ps <- stats::vcov(pscore.tr) * n
asy.lin.rep.ps <- score.ps %*% Hessian.ps
inf.treat.pre <- eta.treat.pre - w.treat.pre * att.treat.pre/mean(w.treat.pre)
inf.treat.post <- eta.treat.post - w.treat.post * att.treat.post/mean(w.treat.post)
M1.post <- - base::colMeans(w.treat.post * post * int.cov)/mean(w.treat.post)
M1.pre <- - base::colMeans(w.treat.pre * (1 - post) * int.cov)/mean(w.treat.pre)
inf.treat.or.post <- asy.lin.rep.ols.post %*% M1.post
inf.treat.or.pre <- asy.lin.rep.ols.pre %*% M1.pre
inf.treat.or <- inf.treat.or.post + inf.treat.or.pre
inf.treat <- inf.treat.post - inf.treat.pre + inf.treat.or
inf.cont.pre <- eta.cont.pre - w.cont.pre * att.cont.pre/mean(w.cont.pre)
inf.cont.post <- eta.cont.post - w.cont.post * att.cont.post/mean(w.cont.post)
M2.pre <- base::colMeans(w.cont.pre *(y - out.y - att.cont.pre) * int.cov)/mean(w.cont.pre)
M2.post <- base::colMeans(w.cont.post *(y - out.y - att.cont.post) * int.cov)/mean(w.cont.post)
inf.cont.ps <- asy.lin.rep.ps %*% (M2.post - M2.pre)
M3.post <- - base::colMeans(w.cont.post * post * int.cov) / mean(w.cont.post)
M3.pre <- - base::colMeans(w.cont.pre * (1 - post) * int.cov) / mean(w.cont.pre)
inf.cont.or.post <- asy.lin.rep.ols.post %*% M3.post
inf.cont.or.pre <- asy.lin.rep.ols.pre %*% M3.pre
inf.cont.or <- inf.cont.or.post + inf.cont.or.pre
inf.cont <- inf.cont.post - inf.cont.pre + inf.cont.ps + inf.cont.or
dr.att.inf.func <- inf.treat - inf.cont
if (boot == FALSE) {
se.dr.att <- stats::sd(dr.att.inf.func)/sqrt(n)
uci <- dr.att + 1.96 * se.dr.att
lci <- dr.att - 1.96 * se.dr.att
dr.boot <- NULL
}
if (boot == TRUE) {
if (is.null(nboot) == TRUE) nboot = 999
if(boot.type == "multiplier"){
dr.boot <- mboot.did(dr.att.inf.func, nboot)
se.dr.att <- stats::IQR(dr.boot) / (stats::qnorm(0.75) - stats::qnorm(0.25))
cv <- stats::quantile(abs(dr.boot/se.dr.att), probs = 0.95)
uci <- dr.att + cv * se.dr.att
lci <- dr.att - cv * se.dr.att
} else {
dr.boot <- unlist(lapply(1:nboot, wboot_drdid_rc1,
n = n, y = y, post = post,
D = D, int.cov = int.cov, i.weights = i.weights))
se.dr.att <- stats::IQR((dr.boot - dr.att)) / (stats::qnorm(0.75) - stats::qnorm(0.25))
cv <- stats::quantile(abs((dr.boot - dr.att)/se.dr.att), probs = 0.95)
uci <- dr.att + cv * se.dr.att
lci <- dr.att - cv * se.dr.att
}
}
if(inffunc == FALSE) dr.att.inf.func <- NULL
call.param <- match.call()
argu <- mget(names(formals()), sys.frame(sys.nframe()))
boot.type <- ifelse(argu$boot.type=="multiplier", "multiplier", "weighted")
boot <- ifelse(argu$boot == TRUE, TRUE, FALSE)
argu <- list(
panel = FALSE,
estMethod = "trad2",
boot = boot,
boot.type = boot.type,
nboot = nboot,
type = "dr"
)
ret <- (list(ATT = dr.att,
se = se.dr.att,
uci = uci,
lci = lci,
boots = dr.boot,
att.inf.func = dr.att.inf.func,
call.param = call.param,
argu = argu))
class(ret) <- "drdid"
return(ret)
} |
NULL
ubuntu_add_swap <- function(droplet,
user = "root",
keyfile = NULL,
ssh_passwd = NULL,
verbose = FALSE
) {
droplet_ssh(droplet,
"fallocate -l 4G /swapfile",
"chmod 600 /swapfile",
"mkswap /swapfile",
"sudo swapon /swapfile",
"sudo echo \"/swapfile none swap sw 0 0\" >> /etc/fstab",
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
ubuntu_install_r <- function(droplet,
user = "root",
keyfile = NULL,
ssh_passwd = NULL,
verbose = FALSE,
rprofile = "options(repos=c('CRAN'='https://cloud.r-project.org/'))"
) {
droplet %>%
ubuntu_apt_get_cran(user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
) %>%
ubuntu_apt_get_update(user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
) %>%
ubuntu_apt_get_install("r-base", "r-base-dev",
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
) %>%
droplet_ssh(paste("echo", shQuote(rprofile), "> .Rprofile"),
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
ubuntu_install_rstudio <- function(droplet, user = "rstudio", password = "server",
version = "0.99.484",
keyfile = NULL,
ssh_passwd = NULL,
verbose = FALSE
) {
droplet %>%
ubuntu_apt_get_install("gdebi-core", "libapparmor1",
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
) %>%
droplet_ssh(
sprintf('wget http://download2.rstudio.org/rstudio-server-%s-amd64.deb', version),
sprintf("sudo gdebi rstudio-server-%s-amd64.deb --non-interactive", version),
sprintf('adduser %s --disabled-password --gecos ""', user),
sprintf('echo "%s:%s" | chpasswd', user, password),
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
ubuntu_install_shiny <- function(droplet, version = "1.4.0.756",
user = "root",
keyfile = NULL,
ssh_passwd = NULL,
verbose = FALSE,
rprofile = "options(repos=c('CRAN'='https://cloud.r-project.org/'))"
) {
droplet %>%
ubuntu_install_r(
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose,
rprofile = rprofile
) %>%
install_r_package("shiny",
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
) %>%
install_r_package("rmarkdown",
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
) %>%
ubuntu_apt_get_install("gdebi-core",
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
) %>%
droplet_ssh(
sprintf("wget http://download3.rstudio.org/ubuntu-12.04/x86_64/shiny-server-%s-amd64.deb", version),
sprintf("sudo gdebi shiny-server-%s-amd64.deb --non-interactive", version),
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
ubuntu_install_opencpu <- function(droplet, version = "1.5",
user = "root",
keyfile = NULL,
ssh_passwd = NULL,
verbose = FALSE
) {
droplet %>%
droplet_ssh(
paste0("sudo add-apt-repository ppa:opencpu/opencpu-", version),
"sudo apt-get update",
"sudo apt-get -q -y install opencpu",
"sudo service opencpu start",
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
ubuntu_apt_get_cran <- function(droplet,
user = "root",
keyfile = NULL,
ssh_passwd = NULL,
verbose = FALSE) {
version <- droplet$image$name
cran_key <- if(any(version %in% c("20.04 (LTS) x64", "18.04 (LTS) x64"))) {
"E298A3A825C0D65DFD57CBB651716619E084DAB9"
}
if (is.null(cran_key)) {
message("The CRAN setup requires to use the ubuntu-20-04-x64 or ubuntu-18-04-x64 images.")
stop()
}
cran_url <- "https://cran.pacha.dev/bin/linux/ubuntu/"
cran_apt <- switch(
version,
"20.04 (LTS) x64" = "focal-cran40",
"18.04 (LTS) x64" = "bionic-cran35"
)
droplet_ssh(droplet,
sprintf(
"apt-key adv --keyserver keyserver.ubuntu.com --recv-keys %s", cran_key
),
sprintf(
"printf '\n
),
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
ubuntu_apt_get_update <- function(droplet,
user = "root",
keyfile = NULL,
ssh_passwd = NULL,
verbose = FALSE) {
droplet_ssh(droplet,
"sudo apt-get update -qq",
"sudo apt-get upgrade -y",
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
ubuntu_apt_get_install <- function(droplet, ...,
user = "root",
keyfile = NULL,
ssh_passwd = NULL,
verbose = FALSE) {
droplet_ssh(droplet,
paste0("sudo apt-get install -y --force-yes ", paste(..., collapse = " ")),
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
install_r_package <- function(droplet, package, repo = "https://cloud.r-project.org/",
user = "root",
keyfile = NULL,
ssh_passwd = NULL,
verbose = FALSE
) {
droplet_ssh(droplet,
sprintf("Rscript -e \"install.packages(\'%s\', repos=\'%s/\')\"",
package, repo),
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
install_github_r_package <- function(droplet, package,
repo = "https://cloud.r-project.org/",
user = "root",
keyfile = NULL,
ssh_passwd = NULL,
verbose = FALSE
) {
tf <- tempdir()
randName <- paste(sample(c(letters, LETTERS), size = 10,
replace = TRUE), collapse = "")
tff <- file.path(tf, randName)
on.exit({
if (file.exists(tff)) {
file.remove(tff)
}
})
command = "Rscript -e \"cat(requireNamespace('remotes', quietly = TRUE))\""
droplet_ssh(droplet,
paste0(command,
" > /tmp/",
randName),
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
droplet_download(droplet,
paste0("/tmp/", randName),
tf,
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose)
droplet_ssh(droplet, paste0("rm /tmp/", randName),
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose)
have_remotes <- readLines(tff, warn = FALSE)
if (length(have_remotes) == 1) {
if (have_remotes %in% c("TRUE", "FALSE")) {
have_remotes = as.logical(have_remotes)
} else {
have_remotes = FALSE
}
} else {
have_remotes = FALSE
}
if (!have_remotes) {
install_r_package(droplet, "remotes", repo = repo,
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
droplet_ssh(
droplet,
sprintf("Rscript -e \"remotes::install_github('%s')\"",
package),
user = user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
}
create_password <- function(n = 8) {
stopifnot(n >= 8 & n <= 15)
stopifnot(length(n) == 1 & is.numeric(n))
sam <- list()
sam[[1]] <- 0:9
sam[[2]] <- letters
sam[[3]] <- LETTERS
p <- mapply(sample, sam, 10)
return(paste(sample(p, n), collapse = ""))
}
ubuntu_create_user <- function(droplet, user, password ,
ssh_user = "root", keyfile = NULL,
ssh_passwd = NULL, verbose = FALSE) {
check_for_a_pkg("ssh")
if (missing(user)) stop("'user' is required")
if (missing(password)) {
password <- create_password(10)
warning(sprintf("no 'password' suplied for '%s', using '%s'", user, password))
}
if (password == "rstudio") stop("supply a 'password' other than 'rstudio'")
droplet <- as.droplet(droplet)
droplet_ssh(droplet,
sprintf(
"useradd -m -p $(openssl passwd -1 %s) %s", password, user
),
user = ssh_user,
keyfile = keyfile,
ssh_passwd = ssh_passwd,
verbose = verbose
)
} |
expected <- eval(parse(text="c(1, 0, 1)"));
test(id=0, code={
argv <- eval(parse(text="list(c(TRUE, FALSE, TRUE))"));
do.call(`as.double`, argv);
}, o=expected); |
Id <- "$Id: bhpm.cluster.BB.hier3.lev2.summary.stats.R,v 1.13 2020/03/31 12:42:23 clb13102 Exp clb13102 $"
bhpm.cluster.BB.dep.lev2.summary.stats <- function(raw, prob = 0.95)
{
s_base = bhpm.cluster.1a.dep.lev2.summary.stats(raw, prob)
if (is.null(s_base)) {
return(NULL)
}
monitor = raw$monitor
theta_mon = monitor[monitor$variable == "theta",]$monitor
gamma_mon = monitor[monitor$variable == "gamma",]$monitor
mu.theta_mon = monitor[monitor$variable == "mu.theta",]$monitor
mu.gamma_mon = monitor[monitor$variable == "mu.gamma",]$monitor
sigma2.theta_mon = monitor[monitor$variable == "sigma2.theta",]$monitor
sigma2.gamma_mon = monitor[monitor$variable == "sigma2.gamma",]$monitor
mu.theta.0_mon = monitor[monitor$variable == "mu.theta.0",]$monitor
mu.gamma.0_mon = monitor[monitor$variable == "mu.gamma.0",]$monitor
tau2.theta.0_mon = monitor[monitor$variable == "tau2.theta.0",]$monitor
tau2.gamma.0_mon = monitor[monitor$variable == "tau2.gamma.0",]$monitor
pi_mon = monitor[monitor$variable == "pi",]$monitor
alpha_pi_mon = monitor[monitor$variable == "alpha.pi",]$monitor
beta_pi_mon = monitor[monitor$variable == "beta.pi",]$monitor
theta.trt.grps <- raw$Trt.Grps[ raw$Trt.Grps$param == "theta", ]$Trt.Grp
if (pi_mon == 1 && !("pi" %in% names(raw))) {
message("Missing pi data");
return(NULL)
}
if (alpha_pi_mon == 1 && !("alpha.pi" %in% names(raw))) {
message("Missing alpha.pi data");
return(NULL)
}
if (beta_pi_mon == 1 && !("beta.pi" %in% names(raw))) {
message("Missing beta.pi data");
return(NULL)
}
nchains = raw$chains
pi_summ = data.frame(Trt.Grp = integer(0), Cluster = character(0), Outcome.Grp = character(0), mean = numeric(0),
median = numeric(0), hpi_lower = numeric(0), hpi_upper = numeric(0),
SD = numeric(0), SE = numeric(0))
alpha.pi_summ = data.frame(Trt.Grp = integer(0), mean = numeric(0), median = numeric(0),
hpi_lower = numeric(0), hpi_upper = numeric(0),
SD = numeric(0), SE = numeric(0))
beta.pi_summ = data.frame(Trt.Grp = integer(0), mean = numeric(0), median = numeric(0),
hpi_lower = numeric(0), hpi_upper = numeric(0),
SD = numeric(0), SE = numeric(0))
samples_combined <- rep(NA, (raw$iter - raw$burnin)*nchains)
if (pi_mon == 1) {
for (i in 1:raw$nClusters) {
for (b in 1:raw$nOutcome.Grp[i]) {
for (t in 1:(raw$nTreatments - 1)) {
s = M_global$summaryStats(raw$pi[, t, i, b, ], nchains, prob)
row <- data.frame(Trt.Grp = theta.trt.grps[t], Cluster = raw$Clusters[i], Outcome.Grp = raw$Outcome.Grp[i, b], mean = s[1],
median = s[2], hpi_lower = s[3], hpi_upper = s[4], SD = s[5], SE = s[6])
pi_summ = rbind(pi_summ, row)
}
}
}
}
if (alpha_pi_mon == 1) {
for (t in 1:(raw$nTreatments - 1)) {
s = M_global$summaryStats(raw$alpha.pi[,t,], nchains, prob)
row <- data.frame(Trt.Grp = theta.trt.grps[t], mean = s[1], median = s[2], hpi_lower = s[3], hpi_upper = s[4],
SD = s[5], SE = s[6])
alpha.pi_summ = rbind(alpha.pi_summ, row)
}
}
if (beta_pi_mon == 1) {
for (t in 1:(raw$nTreatments - 1)) {
s = M_global$summaryStats(raw$beta.pi[,t,], nchains, prob)
row <- data.frame(Trt.Grp = theta.trt.grps[t], mean = s[1], median = s[2], hpi_lower = s[3], hpi_upper = s[4],
SD = s[5], SE = s[6])
beta.pi_summ = rbind(beta.pi_summ, row)
}
}
rownames(pi_summ) <- NULL
rownames(alpha.pi_summ) <- NULL
rownames(alpha.pi_summ) <- NULL
s_BB = list(pi.summary = pi_summ, alpha.pi.summary = alpha.pi_summ, beta.pi.summary = beta.pi_summ)
summary.stats= c(s_base, s_BB)
attr(summary.stats, "model") = attr(raw, "model")
return(summary.stats)
}
bhpm.cluster.BB.dep.lev2.print.summary.stats <- function(summ)
{
if (is.null(summ)) {
message("NULL summary data");
return(NULL)
}
monitor = summ$monitor
theta_mon = monitor[monitor$variable == "theta",]$monitor
gamma_mon = monitor[monitor$variable == "gamma",]$monitor
mu.theta_mon = monitor[monitor$variable == "mu.theta",]$monitor
mu.gamma_mon = monitor[monitor$variable == "mu.gamma",]$monitor
sigma2.theta_mon = monitor[monitor$variable == "sigma2.theta",]$monitor
sigma2.gamma_mon = monitor[monitor$variable == "sigma2.gamma",]$monitor
mu.theta.0_mon = monitor[monitor$variable == "mu.theta.0",]$monitor
mu.gamma.0_mon = monitor[monitor$variable == "mu.gamma.0",]$monitor
tau2.theta.0_mon = monitor[monitor$variable == "tau2.theta.0",]$monitor
tau2.gamma.0_mon = monitor[monitor$variable == "tau2.gamma.0",]$monitor
pi_mon = monitor[monitor$variable == "pi",]$monitor
alpha_pi_mon = monitor[monitor$variable == "alpha.pi",]$monitor
beta_pi_mon = monitor[monitor$variable == "beta.pi",]$monitor
model = attr(summ, "model")
if (is.null(model)) {
message("Missing model attribute");
return(NULL)
}
if (theta_mon == 1 && !("theta.summary" %in% names(summ))) {
message("Missing theta.summary data");
return(NULL)
}
if (gamma_mon == 1 && !("gamma.summary" %in% names(summ))) {
message("Missing gamma.summary data");
return(NULL)
}
if (mu.gamma_mon == 1 && !("mu.gamma.summary" %in% names(summ))) {
message("Missing mu.gamma.summary data");
return(NULL)
}
if (mu.theta_mon == 1 && !("mu.theta.summary" %in% names(summ))) {
message("Missing mu.theta.summary data");
return(NULL)
}
if (sigma2.gamma_mon == 1 && !("sigma2.gamma.summary" %in% names(summ))) {
message("Missing sigma2.gamma.summary data");
return(NULL)
}
if (sigma2.theta_mon == 1 && !("sigma2.theta.summary" %in% names(summ))) {
message("Missing sigma2.theta.summary data");
return(NULL)
}
if (mu.gamma.0_mon == 1 && !("mu.gamma.0.summary" %in% names(summ))) {
message("Missing mu.gamma.0.summary data");
return(NULL)
}
if (mu.theta.0_mon == 1 && !("mu.theta.0.summary" %in% names(summ))) {
message("Missing mu.theta.0.summary data");
return(NULL)
}
if (tau2.theta.0_mon == 1 && !("tau2.theta.0.summary" %in% names(summ))) {
message("Missing tau2.theta.0.summary data");
return(NULL)
}
if (tau2.gamma.0_mon == 1 && !("tau2.gamma.0.summary" %in% names(summ))) {
message("Missing tau2.gamma.0.summary data");
return(NULL)
}
if (pi_mon == 1 && !("pi.summary" %in% names(summ))) {
message("Missing pi.summary data");
return(NULL)
}
if (alpha_pi_mon == 1 && !("alpha.pi.summary" %in% names(summ))) {
message("Missing alpha.pi.summary data");
return(NULL)
}
if (beta_pi_mon == 1 && !("beta.pi.summary" %in% names(summ))) {
message("Missing beta.pi.summary data");
return(NULL)
}
cat(sprintf("Variable Mean (HPI) SD SE\n"))
cat(sprintf("=============================================================\n"))
if (gamma_mon == 1)
for (i in 1:nrow(summ$gamma.summary)) {
row = summ$gamma.summary[i, ]
cat(sprintf("gamma[%s, %s, %s]: %0.6f (%0.6f %0.6f) %0.6f %0.6f\n", row$Cluster,
row$Outcome.Grp, row$Outcome, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (theta_mon == 1)
for (i in 1:nrow(summ$theta.summary)) {
row = summ$theta.summary[i, ]
cat(sprintf("theta[%d %s, %s, %s]: %0.6f (%0.6f %0.6f) %0.6f %0.6f\n", row$Trt.Grp, row$Cluster,
row$Outcome.Grp, row$Outcome, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (mu.gamma_mon == 1)
for (i in 1:nrow(summ$mu.gamma.summary)) {
row = summ$mu.gamma.summary[i, ]
cat(sprintf("mu.gamma[%s, %s]: %0.6f (%0.6f %0.6f) %0.6f %0.6f\n", row$Cluster,
row$Outcome.Grp, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (mu.theta_mon == 1)
for (i in 1:nrow(summ$mu.theta.summary)) {
row = summ$mu.theta.summary[i, ]
cat(sprintf("mu.theta[%d %s, %s]: %0.6f (%0.6f %0.6f) %0.6f %0.6f\n", row$Trt.Grp, row$Cluster,
row$Outcome.Grp, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (sigma2.gamma_mon == 1)
for (i in 1:nrow(summ$sigma2.gamma.summary)) {
row = summ$sigma2.gamma.summary[i, ]
cat(sprintf("sigma2.gamma[%s, %s]: %0.6f (%0.6f %0.6f) %0.6f %0.6f\n", row$Cluster,
row$Outcome.Grp, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (sigma2.theta_mon == 1)
for (i in 1:nrow(summ$sigma2.theta.summary)) {
row = summ$sigma2.theta.summary[i, ]
cat(sprintf("sigma2.theta[%d %s, %s]: %0.6f (%0.6f %0.6f) %0.6f %0.6f\n", row$Trt.Grp, row$Cluster,
row$Outcome.Grp, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (pi_mon == 1)
for (i in 1:nrow(summ$pi.summary)) {
row = summ$pi.summary[i, ]
cat(sprintf("pi[%d %s, %s]: %0.6f (%0.6f %0.6f) %0.6f %0.6f\n", row$Trt.Grp, row$Cluster,
row$Outcome.Grp, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (mu.gamma.0_mon == 1)
for (i in 1:nrow(summ$mu.gamma.0.summary)) {
row = summ$mu.gamma.0.summary[i, ]
cat(sprintf("mu.gamma.0: %0.6f (%0.6f %0.6f) %0.6f %0.6f\n",
row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (mu.theta.0_mon == 1)
for (i in 1:nrow(summ$mu.theta.0.summary)) {
row = summ$mu.theta.0.summary[i, ]
cat(sprintf("mu.theta.0: %d %0.6f (%0.6f %0.6f) %0.6f %0.6f\n",
row$Trt.Grp, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (tau2.gamma.0_mon == 1)
for (i in 1:nrow(summ$tau2.gamma.0.summary)) {
row = summ$tau2.gamma.0.summary[i, ]
cat(sprintf("tau2.gamma.0: %0.6f (%0.6f %0.6f) %0.6f %0.6f\n",
row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (tau2.theta.0_mon == 1)
for (i in 1:nrow(summ$tau2.theta.0.summary)) {
row = summ$tau2.theta.0.summary[i, ]
cat(sprintf("tau2.theta.0: %d %0.6f (%0.6f %0.6f) %0.6f %0.6f\n",
row$Trt.Grp, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (alpha_pi_mon == 1)
for (i in 1:nrow(summ$alpha.pi.summary)) {
row = summ$alpha.pi.summary[i, ]
cat(sprintf("alpha.pi: %d %0.6f (%0.6f %0.6f) %0.6f %0.6f\n",
row$Trt.Grp, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
if (beta_pi_mon == 1)
for (i in 1:nrow(summ$beta.pi.summary)) {
row = summ$beta.pi.summary[i, ]
cat(sprintf("beta.pi: %d %0.6f (%0.6f %0.6f) %0.6f %0.6f\n",
row$Trt.Grp, row$mean, row$hpi_lower, row$hpi_upper, row$SD, row$SE))
}
} |
context("Check describe() functions")
test_that("describe cluster_profiles",{
library("DALEX")
library("ranger")
titanic_small <- titanic_imputed[1:500,]
rf_model <- ranger(survived ~., data = titanic_small, probability = TRUE)
explainer_rf <- explain(rf_model, data = titanic_small,
y = titanic_small$survived, label = "RF",
verbose = FALSE)
selected_passangers <- select_sample(titanic_small, n = 1)
cp_rf <- ceteris_paribus(explainer_rf, selected_passangers)
desc_cp_rf <- describe(cp_rf, variables = "age")
expect_true("ceteris_paribus_description" %in% class(desc_cp_rf))
}) |
calc_regres_coef_a <- function(y)
{
time_count <- seq_along(y)
ones <- seq(1,1,length=length(y))
content.matrix <- c(ones, time_count)
X <- matrix(content.matrix, byrow = FALSE, ncol = 2)
suppressWarnings({
fm <- stats::lsfit(x = X, y = y)
data.a <- fm$coef[[1]]
})
return(data.a)
} |
report_side_effects()
expect_equal(1+1, 2)
Sys.setenv(hihi="lol")
expect_equal(1+1, 3)
Sys.setenv(hihi="lulz ftw") |
is.XiMpLe.node <- function(x){
inherits(x, "XiMpLe.node")
}
is.XiMpLe.doc <- function(x){
inherits(x, "XiMpLe.doc")
}
is.XiMpLe.validity <- function(x){
inherits(x, "XiMpLe.validity")
}
setGeneric("XMLName", function(obj){standardGeneric("XMLName")})
setMethod("XMLName",
signature=signature(obj="XiMpLe.node"),
function(obj){
return(obj@name)
}
)
setGeneric("XMLName<-", function(obj, value){standardGeneric("XMLName<-")})
setMethod("XMLName<-",
signature=signature(obj="XiMpLe.node"),
function(obj, value){
obj@name <- value
return(obj)
}
)
setGeneric("XMLAttrs", function(obj){standardGeneric("XMLAttrs")})
setMethod("XMLAttrs",
signature=signature(obj="XiMpLe.node"),
function(obj){
return(obj@attributes)
}
)
setGeneric("XMLAttrs<-", function(obj, value){standardGeneric("XMLAttrs<-")})
setMethod("XMLAttrs<-",
signature=signature(obj="XiMpLe.node"),
function(obj, value){
obj@attributes <- value
return(obj)
}
)
setGeneric("XMLChildren", function(obj){standardGeneric("XMLChildren")})
setMethod("XMLChildren",
signature=signature(obj="XiMpLe.node"),
function(obj){
return(obj@children)
}
)
setMethod("XMLChildren",
signature=signature(obj="XiMpLe.doc"),
function(obj){
return(obj@children)
}
)
setGeneric("XMLChildren<-", function(obj, value){standardGeneric("XMLChildren<-")})
setMethod("XMLChildren<-",
signature=signature(obj="XiMpLe.node"),
function(obj, value){
obj@children <- child.list(value)
return(obj)
}
)
setMethod("XMLChildren<-",
signature=signature(obj="XiMpLe.doc"),
function(obj, value){
obj@children <- child.list(value)
return(obj)
}
)
setGeneric("XMLValue", function(obj){standardGeneric("XMLValue")})
setMethod("XMLValue",
signature=signature(obj="XiMpLe.node"),
function(obj){
directValue <- slot(obj, "value")
children <- XMLChildren(obj)
if("!value!" %in% names(children)){
indirectValue <- sapply(
children[names(children) %in% "!value!"],
XMLValue,
USE.NAMES=FALSE
)
} else {
indirectValue <- NULL
}
if(identical(directValue, "")){
if(!is.null(indirectValue)){
return(indirectValue)
} else {
return(directValue)
}
} else {
return(directValue)
}
}
)
setGeneric("XMLValue<-", function(obj, value){standardGeneric("XMLValue<-")})
setMethod("XMLValue<-",
signature=signature(obj="XiMpLe.node"),
function(obj, value){
obj@value <- value
return(obj)
}
)
setGeneric("XMLFile", function(obj){standardGeneric("XMLFile")})
setMethod("XMLFile",
signature=signature(obj="XiMpLe.doc"),
function(obj){
return(obj@file)
}
)
setGeneric("XMLFile<-", function(obj, value){standardGeneric("XMLFile<-")})
setMethod("XMLFile<-",
signature=signature(obj="XiMpLe.doc"),
function(obj, value){
obj@file <- value
return(obj)
}
)
setGeneric("XMLDecl", function(obj){standardGeneric("XMLDecl")})
setMethod("XMLDecl",
signature=signature(obj="XiMpLe.doc"),
function(obj){
return(obj@xml)
}
)
setGeneric("XMLDecl<-", function(obj, value){standardGeneric("XMLDecl<-")})
setMethod("XMLDecl<-",
signature=signature(obj="XiMpLe.doc"),
function(obj, value){
obj@xml <- value
return(obj)
}
)
setGeneric("XMLDTD", function(obj){standardGeneric("XMLDTD")})
setMethod("XMLDTD",
signature=signature(obj="XiMpLe.doc"),
function(obj){
return(obj@dtd)
}
)
setGeneric("XMLDTD<-", function(obj, value){standardGeneric("XMLDTD<-")})
setMethod("XMLDTD<-",
signature=signature(obj="XiMpLe.doc"),
function(obj, value){
obj@dtd <- value
return(obj)
}
)
setGeneric("XMLScan", function(obj, name, as.list=FALSE){standardGeneric("XMLScan")})
find.nodes <- function(nodes, nName){
res <- list()
for (thisNode in nodes){
if(identical(XMLName(thisNode), nName)){
res <- append(res, thisNode)
} else if(length(XMLChildren(thisNode)) > 0){
res <- append(res, find.nodes(XMLChildren(thisNode), nName=nName))
} else {}
}
return(res)
}
setMethod("XMLScan",
signature=signature(obj="XiMpLe.node"),
function(obj, name, as.list=FALSE){
node.list <- find.nodes(
nodes=child.list(obj),
nName=name)
if(identical(node.list, list())){
return(NULL)
} else if(length(node.list) == 1 && !isTRUE(as.list)){
return(node.list[[1]])
} else {
return(node.list)
}
}
)
setMethod("XMLScan",
signature=signature(obj="XiMpLe.doc"),
function(obj, name, as.list=FALSE){
node.list <- find.nodes(
nodes=XMLChildren(obj),
nName=name)
if(identical(node.list, list())){
return(NULL)
} else if(length(node.list) == 1 && !isTRUE(as.list)){
return(node.list[[1]])
} else {
return(node.list)
}
}
)
setGeneric("XMLScan<-", function(obj, name, value){standardGeneric("XMLScan<-")})
replace.nodes <- function(nodes, nName, replacement){
nodes <- sapply(nodes, function(thisNode){
if(identical(XMLName(thisNode), nName)){
return(replacement)
} else if(length(XMLChildren(thisNode)) > 0){
XMLChildren(thisNode) <- replace.nodes(
XMLChildren(thisNode),
nName=nName,
replacement=replacement)
return(thisNode)
} else {
return(thisNode)
}
})
nodes <- Filter(Negate(is.null), nodes)
return(nodes)
}
setMethod("XMLScan<-",
signature=signature(obj="XiMpLe.node"),
function(obj, name, value){
stopifnot(is.XiMpLe.node(value) || is.null(value))
obj <- replace.nodes(
nodes=child.list(obj),
nName=name,
replacement=value)
stopifnot(validObject(object=obj, test=TRUE, complete=TRUE))
if(identical(obj, as.list(value))){
return(value)
} else {
return(obj[[1]])
}
}
)
setMethod("XMLScan<-",
signature=signature(obj="XiMpLe.doc"),
function(obj, name, value){
stopifnot(is.XiMpLe.node(value) || is.null(value))
XMLChildren(obj) <- replace.nodes(
nodes=XMLChildren(obj),
nName=name,
replacement=value)[[1]]
stopifnot(validObject(object=obj, test=TRUE, complete=TRUE))
return(obj)
}
)
setGeneric("XMLScanDeep", function(obj, find=NULL, search="attributes"){standardGeneric("XMLScanDeep")})
recursiveScan <- function(robj, rfind, rsearch, recResult=list(), result, envID="all"){
if(is.XiMpLe.doc(robj)){
recResult <- append(recResult, lapply(robj@children, function(this.child){
recursiveScan(robj=this.child, rfind=rfind, rsearch=rsearch, recResult=recResult, result=result, envID=envID)
}))
} else if(is.XiMpLe.node(robj)){
foundThis <- NULL
if(identical(rsearch, "attributes")){
foundThis <- XMLAttrs(robj)[[rfind]]
} else if(identical(rsearch, "name")){
objName <- XMLName(robj)
if(identical(objName, rfind)){
foundThis <- objName
} else {}
} else if(identical(rsearch, "value")){
objValue <- XMLValue(robj)
if(identical(objValue, rfind)){
foundThis <- objValue
} else {}
} else {
stop(simpleError("Only \"attributes\", \"name\" or \"value\" are valid for search!"))
}
if(!is.null(foundThis)){
thisResult <- as.list(result)
nodeName <- XMLName(robj)
thisResult[[envID]] <- append(thisResult[[envID]], foundThis)
names(thisResult[[envID]])[length(thisResult[[envID]])] <- nodeName
list2env(thisResult, envir=result)
} else {}
recResult <- append(recResult, lapply(robj@children, function(this.child){
recursiveScan(robj=this.child, rfind=rfind, rsearch=rsearch, recResult=recResult, result=result, envID=envID)
}))
}
return(recResult)
}
setMethod("XMLScanDeep",
signature=signature(obj="XiMpLe.node"),
function(obj, find, search){
result <- new.env()
assign(find, c(), envir=result)
recursiveScan(robj=obj, rfind=find, rsearch=search, recResult=list(), result=result, envID=find)
return(get(find, envir=result))
}
)
setMethod("XMLScanDeep",
signature=signature(obj="XiMpLe.doc"),
function(obj, find, search){
result <- new.env()
assign(find, c(), envir=result)
recursiveScan(robj=obj, rfind=find, rsearch=search, recResult=list(), result=result, envID=find)
return(get(find, envir=result))
}
) |
mod_estimation_fit_curve_hot_server <- function(input, output, session, stringsAsFactors) {
table_reset <- reactiveValues(value = 0)
table_var_reset <- reactiveValues(value = 0)
observeEvent(input$button_gen_table, {
table_reset$value <- 1
table_var_reset$value <- 1
})
previous_coeffs <- reactive({
input$button_gen_table
isolate({
formula_select <- input$formula_select
})
if (formula_select == "lin-quad") {
fit_coeffs_names <- c("coeff_C", "coeff_alpha", "coeff_beta")
} else if (formula_select == "lin-quad-no-int") {
fit_coeffs_names <- c("coeff_alpha", "coeff_beta")
} else if (formula_select == "lin") {
fit_coeffs_names <- c("coeff_C", "coeff_alpha")
} else if (formula_select == "lin-no-int") {
fit_coeffs_names <- c("coeff_alpha")
}
full_data <- data.frame(
matrix(
0.0,
nrow = length(fit_coeffs_names),
ncol = 2
)
) %>%
`row.names<-`(fit_coeffs_names) %>%
`colnames<-`(c("estimate", "std.error"))
return(full_data)
})
previous_var <- reactive({
input$button_gen_table
isolate({
model_formula <- input$formula_select
})
fit_coeffs_names <- names_from_model_formula(model_formula)
full_data <- matrix(
0.0,
nrow = length(fit_coeffs_names),
ncol = length(fit_coeffs_names)
) %>%
`row.names<-`(fit_coeffs_names) %>%
`colnames<-`(fit_coeffs_names) %>%
as.data.frame()
return(full_data)
})
changed_coeffs_data <- reactive({
input$button_gen_table
if (is.null(input$fit_coeffs_hot) | isolate(table_reset$value == 1)) {
table_reset$value <- 0
return(previous_coeffs())
} else if (!identical(previous_coeffs(), input$fit_coeffs_hot)) {
fit_coeffs_names <- row.names(hot_to_r(input$fit_coeffs_hot))
mytable <- as.data.frame(hot_to_r(input$fit_coeffs_hot)) %>%
dplyr::mutate_all(as.numeric) %>%
`row.names<-`(fit_coeffs_names)
return(mytable)
}
})
changed_var_data <- reactive({
input$button_gen_table
if (is.null(input$fit_var_cov_mat_hot) | isolate(table_var_reset$value == 1)) {
table_var_reset$value <- 0
return(previous_var())
} else if (!identical(previous_var(), input$fit_var_cov_mat_hot)) {
fit_coeffs_names <- row.names(hot_to_r(input$fit_var_cov_mat_hot))
mytable <- as.data.frame(hot_to_r(input$fit_var_cov_mat_hot)) %>%
dplyr::mutate_all(as.numeric) %>%
`row.names<-`(fit_coeffs_names)
return(mytable)
}
})
output$fit_coeffs_hot <- renderRHandsontable({
num_cols <- ncol(changed_coeffs_data())
hot <- changed_coeffs_data() %>%
fix_coeff_names(type = "rows", output = "rhot") %>%
rhandsontable(
width = (50 + num_cols * 100),
height = "100%"
) %>%
hot_cols(colWidths = 100) %>%
hot_cols(format = "0.000000")
hot$x$contextMenu <- list(items = c("remove_row", "---------", "undo", "redo"))
return(hot)
})
output$fit_var_cov_mat_hot <- renderRHandsontable({
num_cols <- ncol(changed_var_data())
hot <- changed_var_data() %>%
fix_coeff_names(type = "rows", output = "rhot") %>%
fix_coeff_names(type = "cols", output = "rhot") %>%
rhandsontable(
width = (50 + num_cols * 100),
height = "100%"
) %>%
hot_cols(colWidths = 100) %>%
hot_cols(format = "0.00000000")
hot$x$contextMenu <- list(items = c("remove_row", "---------", "undo", "redo"))
return(hot)
})
}
mod_estimation_fit_curve_server <- function(input, output, session, stringsAsFactors, aberr_module) {
data <- reactive({
input$button_view_fit_data
isolate({
load_fit_data <- input$load_fit_data_check
fit_data <- input$load_fit_data
})
input$button_view_fit_data
isolate({
if (load_fit_data) {
fit_results_list <- readRDS(fit_data$datapath)
if (aberr_module == "translocations") {
fit_genome_factor <- fit_results_list[["genome_factor"]]
if (fit_results_list[["frequency_select"]] == "measured_freq") {
trans_frequency_message <- paste0("The provided observed fitting curve has been converted to full genome, with a genomic conversion factor of ", round(fit_genome_factor, 3), ".")
} else {
trans_frequency_message <- "The provided fitting curve is already full genome."
}
fit_results_list[["fit_trans_frequency_message"]] <- trans_frequency_message
if (fit_results_list[["frequency_select"]] == "measured_freq") {
fit_results_list[["fit_coeffs"]][, "estimate"] <- fit_results_list[["fit_coeffs"]][, "estimate"] / fit_genome_factor
fit_results_list[["fit_coeffs"]][, "std.error"] <- fit_results_list[["fit_coeffs"]][, "std.error"] / fit_genome_factor
fit_results_list[["fit_var_cov_mat"]] <- fit_results_list[["fit_var_cov_mat"]] / fit_genome_factor^2
fit_results_list[["fit_model_statistics"]] <- calculate_model_stats(
model_data = fit_results_list[["fit_raw_data"]],
fit_coeffs_vec = fit_results_list[["fit_coeffs"]][, "estimate"],
response = "yield", link = "identity", type = "theory",
genome_factor = fit_genome_factor,
calc_type = "estimation"
)
}
}
} else {
model_formula <- input$formula_select
fit_formula_tex <- parse_model_formula(model_formula)$fit_formula_tex
fit_coeffs_raw <- hot_to_r(input$fit_coeffs_hot)
fit_coeffs <- fit_coeffs_raw %>%
as.matrix()
if (input$use_var_cov_matrix) {
fit_var_cov_mat <- hot_to_r(input$fit_var_cov_mat_hot) %>%
as.matrix()
} else {
fit_var_cov_mat <- matrix(
0,
nrow = nrow(fit_coeffs),
ncol = nrow(fit_coeffs)
) %>%
`colnames<-`(rownames(fit_coeffs)) %>%
`rownames<-`(rownames(fit_coeffs))
for (x_var in rownames(fit_var_cov_mat)) {
fit_var_cov_mat[[x_var, x_var]] <- fit_coeffs[x_var, "std.error"] * fit_coeffs[x_var, "std.error"]
}
}
fit_cor_mat <- fit_var_cov_mat
for (x_var in rownames(fit_var_cov_mat)) {
for (y_var in colnames(fit_var_cov_mat)) {
fit_cor_mat[x_var, y_var] <- fit_var_cov_mat[x_var, y_var] /
(fit_coeffs[x_var, "std.error"] * fit_coeffs[y_var, "std.error"])
}
}
if (aberr_module == "translocations") {
if (input$frequency_select == "measured_freq") {
fit_genome_factor <- input$fit_genome_factor
fit_coeffs[, "estimate"] <- fit_coeffs[, "estimate"] / fit_genome_factor
fit_coeffs[, "std.error"] <- fit_coeffs[, "std.error"] / fit_genome_factor
fit_var_cov_mat <- fit_var_cov_mat / fit_genome_factor^2
}
}
fit_results_list <- list(
fit_formula_tex = fit_formula_tex,
fit_coeffs = fit_coeffs,
fit_var_cov_mat = fit_var_cov_mat,
fit_cor_mat = fit_cor_mat
)
if (aberr_module == "translocations") {
if (input$frequency_select == "measured_freq") {
trans_frequency_message <- paste0("The provided observed fitting curve has been converted to full genome, with a genomic conversion factor of ", input$fit_genome_factor, ".")
} else {
trans_frequency_message <- "The provided fitting curve is already full genome."
}
fit_results_list[["fit_trans_frequency_message"]] <- trans_frequency_message
}
}
})
return(fit_results_list)
})
output$fit_formula_tex <- renderUI({
if (input$button_view_fit_data <= 0) {
return(NULL)
}
withMathJax(paste0("$$", data()[["fit_formula_tex"]], "$$"))
})
output$fit_trans_frequency_message <- renderUI({
if (input$button_view_fit_data <= 0 | aberr_module != "translocations") {
return(NULL)
}
data()[["fit_trans_frequency_message"]]
})
output$fit_model_statistics <- renderRHandsontable({
if (input$button_view_fit_data <= 0) {
return(NULL)
}
num_cols <- as.numeric(ncol(data()[["fit_model_statistics"]]))
data()[["fit_model_statistics"]] %>%
rhandsontable(
width = (num_cols * 70),
height = "100%"
) %>%
hot_cols(colWidths = 70)
})
output$fit_coeffs <- renderRHandsontable({
if (input$button_view_fit_data <= 0) {
return(NULL)
}
num_cols <- as.numeric(ncol(data()[["fit_coeffs"]]))
data()[["fit_coeffs"]] %>%
formatC(format = "e", digits = 3) %>%
fix_coeff_names(type = "rows", output = "rhot") %>%
rhandsontable(
width = (50 + num_cols * 100),
height = "100%"
) %>%
hot_cols(colWidths = 100) %>%
hot_cols(halign = "htRight")
})
output$fit_var_cov_mat <- renderRHandsontable({
if (input$button_view_fit_data <= 0) {
return(NULL)
}
num_cols <- as.numeric(ncol(data()[["fit_var_cov_mat"]]))
data()[["fit_var_cov_mat"]] %>%
formatC(format = "e", digits = 3) %>%
fix_coeff_names(type = "rows", output = "rhot") %>%
fix_coeff_names(type = "cols", output = "rhot") %>%
rhandsontable(
width = (50 + num_cols * 100),
height = "100%"
) %>%
hot_cols(colWidths = 100) %>%
hot_cols(halign = "htRight")
})
output$fit_cor_mat <- renderRHandsontable({
if (input$button_view_fit_data <= 0) {
return(NULL)
}
num_cols <- as.numeric(ncol(data()[["fit_cor_mat"]]))
data()[["fit_cor_mat"]] %>%
fix_coeff_names(type = "rows", output = "rhot") %>%
fix_coeff_names(type = "cols", output = "rhot") %>%
rhandsontable(
width = (50 + num_cols * 100),
height = "100%"
) %>%
hot_cols(colWidths = 100) %>%
hot_cols(format = "0.000")
})
}
mod_estimation_case_hot_server <- function(input, output, session, stringsAsFactors, aberr_module, genome_factor = NULL) {
table_reset <- reactiveValues(value = 0)
observeEvent(input$button_upd_table, {
table_reset$value <- 1
})
previous <- reactive({
input$button_upd_table
isolate({
load_case_data <- input$load_case_data_check
case_data <- input$load_case_data
num_cases <- 1
num_aberrs <- as.numeric(input$num_aberrs) + 1
})
if (!load_case_data) {
full_data <- data.frame(
matrix(
0,
nrow = num_cases,
ncol = num_aberrs
)
) %>%
`colnames<-`(paste0("C", seq(0, num_aberrs - 1, 1)))
} else {
full_data <- utils::read.csv(case_data$datapath, header = TRUE) %>%
dplyr::rename_with(
.fn = toupper,
.cols = dplyr::everything()
) %>%
dplyr::mutate(
dplyr::across(
.cols = dplyr::starts_with("C"),
.fns = as.integer
)
) %>%
dplyr::select(
dplyr::starts_with("C")
)
}
return(full_data)
})
changed_data <- reactive({
input$button_upd_table
input$button_upd_params
isolate({
if (is.null(input$case_data_hot) | isolate(table_reset$value == 1)) {
table_reset$value <- 0
mytable <- previous()
mytable <- init_aberr_table(
data = mytable,
type = "case",
aberr_module
)
} else if (!identical(previous(), input$case_data_hot)) {
mytable <- as.data.frame(hot_to_r(input$case_data_hot))
mytable <- calculate_aberr_table(
data = mytable,
type = "case",
assessment_u = 1
)
if (aberr_module == "dicentrics" | aberr_module == "micronuclei") {
mytable <- mytable %>%
dplyr::mutate(
y = .data$mean,
y_err = .data$std_err
) %>%
dplyr::select(-.data$mean, -.data$std_err)
} else if (aberr_module == "translocations") {
genome_factor <- genome_factor$genome_factor()
mytable <- mytable %>%
dplyr::mutate(
Fp = .data$mean,
Fp_err = .data$std_err
) %>%
dplyr::select(-.data$mean, -.data$std_err) %>%
dplyr::mutate(
Xc = dplyr::case_when(
input$trans_confounders & input$trans_confounders_type == "sigurdson" ~
calculate_trans_rate_sigurdson(
.data$N, genome_factor,
age_value = input$trans_confounder_age,
sex_bool = input$trans_confounder_sex,
sex_value = input$trans_sex,
smoker_bool = input$trans_confounder_smoke,
ethnicity_value = input$trans_confounder_ethnicity,
region_value = input$trans_confounder_region
),
input$trans_confounders & input$trans_confounders_type == "manual" ~
calculate_trans_rate_manual(.data$N, genome_factor, input$trans_expected_aberr_value),
TRUE ~ 0
),
Fg = correct_negative_vals(.data$X - .data$Xc) / (.data$N * genome_factor),
Fg_err = .data$Fp_err / sqrt(genome_factor)
)
}
return(mytable)
}
})
})
output$case_data_hot <- renderRHandsontable({
num_cols <- as.numeric(ncol(changed_data()))
hot <- changed_data() %>%
rhandsontable(
width = (50 + num_cols * 50),
height = "100%"
) %>%
hot_cols(colWidths = 50)
if (aberr_module == "dicentrics" | aberr_module == "micronuclei") {
hot <- hot %>%
hot_col(c(1, 2, seq(num_cols - 3, num_cols, 1)), readOnly = TRUE) %>%
hot_col(num_cols, renderer = "
function (instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.NumericRenderer.apply(this, arguments);
if (value > 1.96) {
td.style.background = 'pink';
}
}")
} else if (aberr_module == "translocations") {
hot <- hot %>%
hot_col(c(1, 2, seq(num_cols - 6, num_cols, 1)), readOnly = TRUE) %>%
hot_col(num_cols - 3, renderer = "
function (instance, td, row, col, prop, value, cellProperties) {
Handsontable.renderers.NumericRenderer.apply(this, arguments);
if (value > 1.96) {
td.style.background = 'pink';
}
}")
}
hot$x$contextMenu <- list(items = c("remove_row", "---------", "undo", "redo"))
return(hot)
})
}
mod_estimation_results_server <- function(input, output, session, stringsAsFactors, aberr_module, genome_factor = NULL) {
data <- reactive({
input$button_estimate
cli::cli_h1("Dose estimation calculations")
progress <- shiny::Progress$new()
on.exit(progress$close())
progress$set(message = "Performing dose estimation", value = 0)
isolate({
load_fit_data <- input$load_fit_data_check
fit_data <- input$load_fit_data
exposure <- input$exposure_select
assessment <- input$assessment_select
case_data <- hot_to_r(input$case_data_hot)
fraction_coeff <- input$fraction_coeff_select
})
error_method <- input$error_method_whole_select
cli::cli_alert_info("Parsing dose-effect curve...")
progress$set(detail = "Parsing dose-effect curve", value = 1 / 6)
if (load_fit_data) {
fit_results_list <- readRDS(fit_data$datapath)
if (aberr_module == "translocations") {
fit_genome_factor <- fit_results_list[["genome_factor"]]
if (fit_results_list[["frequency_select"]] == "measured_freq") {
fit_results_list[["fit_coeffs"]][, "estimate"] <- fit_results_list[["fit_coeffs"]][, "estimate"] / fit_genome_factor
fit_results_list[["fit_coeffs"]][, "std.error"] <- fit_results_list[["fit_coeffs"]][, "std.error"] / fit_genome_factor
fit_results_list[["fit_var_cov_mat"]] <- fit_results_list[["fit_var_cov_mat"]] / fit_genome_factor^2
}
}
} else {
model_formula <- input$formula_select
fit_formula_tex <- parse_model_formula(model_formula)$fit_formula_tex
fit_coeffs_raw <- hot_to_r(input$fit_coeffs_hot)
fit_coeffs <- fit_coeffs_raw %>%
cbind(statistic = c(rep(0, nrow(fit_coeffs_raw)))) %>%
as.matrix() %>%
`rownames<-`(names_from_model_formula(model_formula))
if (input$use_var_cov_matrix) {
fit_var_cov_mat <- hot_to_r(input$fit_var_cov_mat_hot) %>%
as.matrix() %>%
`colnames<-`(rownames(fit_coeffs)) %>%
`rownames<-`(rownames(fit_coeffs))
} else {
fit_var_cov_mat <- matrix(
0,
nrow = nrow(fit_coeffs),
ncol = nrow(fit_coeffs)
) %>%
`colnames<-`(rownames(fit_coeffs)) %>%
`rownames<-`(rownames(fit_coeffs))
for (x_var in rownames(fit_var_cov_mat)) {
fit_var_cov_mat[[x_var, x_var]] <- fit_coeffs[x_var, "std.error"] * fit_coeffs[x_var, "std.error"]
}
}
if (aberr_module == "translocations") {
if (input$frequency_select == "measured_freq") {
fit_genome_factor <- input$fit_genome_factor
fit_coeffs[, "estimate"] <- fit_coeffs[, "estimate"] / fit_genome_factor
fit_coeffs[, "std.error"] <- fit_coeffs[, "std.error"] / fit_genome_factor
fit_var_cov_mat <- fit_var_cov_mat / fit_genome_factor^2
}
}
fit_results_list <- list(
fit_formula_tex = fit_formula_tex,
fit_coeffs = fit_coeffs,
fit_var_cov_mat = fit_var_cov_mat
)
}
fit_coeffs <- fit_results_list[["fit_coeffs"]]
fit_var_cov_mat <- fit_results_list[["fit_var_cov_mat"]]
fit_formula_tex <- fit_results_list[["fit_formula_tex"]]
if (exposure == "protracted") {
protracted_time <- input$protracted_time
protracted_life_time <- input$protracted_life_time
protracted_g_value <- protracted_g_function(protracted_time, protracted_life_time)
} else if (exposure == "protracted_high") {
protracted_g_value <- 0
protracted_time <- NA
protracted_life_time <- NA
} else {
protracted_g_value <- 1
protracted_time <- NA
protracted_life_time <- NA
}
if (grepl("merkle", error_method, fixed = TRUE)) {
conf_int_curve <- as.numeric(paste0("0.", gsub("\\D", "", error_method)))
conf_int_yield <- conf_int_curve
} else if (error_method == "delta") {
conf_int_curve <- 0.83
conf_int_delta <- 0.95
}
if (aberr_module == "translocations") {
parsed_genome_factor <- genome_factor$genome_factor()
} else {
parsed_genome_factor <- 1
}
if (grepl("merkle", error_method, fixed = TRUE)) {
cli::cli_alert_info("Performing whole-body dose estimation (Merkle's method)...")
progress$set(detail = "Performing whole-body dose estimation", value = 2 / 6)
results_whole <- estimate_whole_body_merkle(
case_data,
fit_coeffs,
fit_var_cov_mat,
conf_int_yield,
conf_int_curve,
protracted_g_value,
parsed_genome_factor,
aberr_module
)
} else if (error_method == "delta") {
cli::cli_alert_info("Performing whole-body dose estimation (delta method)...")
progress$set(detail = "Performing whole-body dose estimation", value = 2 / 6)
results_whole <- estimate_whole_body_delta(
case_data,
fit_coeffs,
fit_var_cov_mat,
conf_int_delta,
protracted_g_value,
aberr_module
)
}
est_doses_whole <- results_whole[["est_doses"]]
AIC_whole <- results_whole[["AIC"]]
if (assessment == "partial-body") {
if (fraction_coeff == "gamma") {
gamma <- input$gamma_coeff
} else if (fraction_coeff == "d0") {
gamma <- 1 / input$d0_coeff
}
cli::cli_alert_info("Performing partial-body dose estimation (Dolphin's method)...")
progress$set(detail = "Performing partial-body dose estimation", value = 3 / 6)
results_partial <- estimate_partial_body_dolphin(
case_data,
fit_coeffs,
fit_var_cov_mat,
conf_int = 0.95,
protracted_g_value,
parsed_genome_factor,
gamma,
aberr_module
)
est_doses_partial <- results_partial[["est_doses"]]
est_frac_partial <- results_partial[["est_frac"]]
AIC_partial <- results_partial[["AIC"]]
} else if (assessment == "hetero") {
if (fraction_coeff == "gamma") {
gamma <- input$gamma_coeff
gamma_error <- input$gamma_error
} else if (fraction_coeff == "d0") {
gamma <- 1 / input$d0_coeff
gamma_error <- 0
}
cli::cli_alert_info("Performing heterogeneous dose estimation (mixed Poisson model)...")
progress$set(detail = "Performing heterogeneous dose estimation", value = 3 / 6)
for (i in 1:5) {
try({
results_hetero <- estimate_hetero_mixed_poisson(
case_data,
fit_coeffs,
fit_var_cov_mat,
conf_int = 0.95,
protracted_g_value,
gamma = gamma,
gamma_error = gamma_error
)
break
})
}
if (!exists("results_hetero")) {
cli::cli_alert_danger("The algorithm did not converge!")
showNotification(
ui = "The algorithm did not converge!\nPlease try again.",
type = "error"
)
}
est_mixing_prop_hetero <- results_hetero[["est_mixing_prop"]]
est_yields_hetero <- results_hetero[["est_yields"]]
est_doses_hetero <- results_hetero[["est_doses"]]
est_frac_hetero <- results_hetero[["est_frac"]]
AIC_hetero <- results_hetero[["AIC"]]
}
cli::cli_alert_info("Plotting dose estimation results...")
progress$set(detail = "Plotting dose estimation results", value = 4 / 6)
if (assessment == "whole-body") {
est_doses <- list(whole = results_whole)
} else if (assessment == "partial-body") {
est_doses <- list(whole = results_whole, partial = results_partial)
} else if (assessment == "hetero") {
est_doses <- list(whole = results_whole, hetero = results_hetero)
}
aberr_name <- to_title(aberr_module)
if (aberr_module == "translocations") {
if (nchar(input$trans_name) > 0) {
aberr_name <- input$trans_name
}
}
gg_curve <- plot_estimated_dose_curve(
est_doses,
fit_coeffs,
fit_var_cov_mat,
protracted_g_value,
conf_int_curve = conf_int_curve,
aberr_name
)
cli::cli_alert_info("Processing results")
progress$set(detail = "Processing results", value = 5 / 6)
est_results_list <- list(
assessment = assessment,
est_doses_whole = est_doses_whole,
est_doses_partial = NA,
est_frac_partial = NA,
est_mixing_prop_hetero = NA,
est_yields_hetero = NA,
est_doses_hetero = NA,
est_frac_hetero = NA,
AIC_whole = AIC_whole,
AIC_partial = NA,
AIC_hetero = NA,
gg_curve = gg_curve,
fit_coeffs = fit_coeffs,
protraction = c(0, 0, 0),
fit_formula_tex = fit_formula_tex,
case_data = case_data,
case_description = input$case_description,
results_comments = input$results_comments
)
if (assessment == "partial-body") {
est_results_list[["est_doses_partial"]] <- est_doses_partial
est_results_list[["est_frac_partial"]] <- est_frac_partial
est_results_list[["est_mixing_prop_hetero"]] <- NA
est_results_list[["est_yields_hetero"]] <- NA
est_results_list[["est_doses_hetero"]] <- NA
est_results_list[["est_frac_hetero"]] <- NA
est_results_list[["AIC_partial"]] <- AIC_partial
est_results_list[["AIC_hetero"]] <- NA
} else if (assessment == "hetero") {
est_results_list[["est_mixing_prop_hetero"]] <- est_mixing_prop_hetero
est_results_list[["est_yields_hetero"]] <- est_yields_hetero
est_results_list[["est_doses_hetero"]] <- est_doses_hetero
est_results_list[["est_frac_hetero"]] <- est_frac_hetero
est_results_list[["est_doses_partial"]] <- NA
est_results_list[["est_frac_partial"]] <- NA
est_results_list[["AIC_partial"]] <- NA
est_results_list[["AIC_hetero"]] <- AIC_hetero
}
if (exposure == "protracted" & any(grep("beta", fit_formula_tex))) {
est_results_list[["protraction"]] <- c(1, protracted_time, protracted_life_time)
}
if (aberr_module == "translocations") {
est_results_list[["genome_factor"]] <- genome_factor$genome_factor()
est_results_list[["chromosome_table"]] <- hot_to_r(input$chromosome_table)
est_results_list[["trans_sex"]] <- input$trans_sex
if (!input$trans_confounders) {
est_results_list[["confounders"]] <- NULL
} else if (input$trans_confounders & input$trans_confounders_type == "sigurdson") {
est_results_list[["confounders"]] <- c(
age_value = input$trans_confounder_age,
sex_bool = input$trans_confounder_sex,
smoker_bool = input$trans_confounder_smoke,
ethnicity_value = input$trans_confounder_ethnicity,
region_value = input$trans_confounder_region
)
} else if (input$trans_confounders & input$trans_confounders_type == "manual") {
est_results_list[["confounders"]] <- input$trans_expected_aberr_value
}
}
cli::cli_alert_success("Dose estimation performed successfully")
progress$set(detail = "Done", value = 1)
showNotification(
ui = "Dose estimation performed successfully"
)
return(est_results_list)
})
output$estimation_results_ui <- renderUI({
assessment <- input$assessment_select
hetero_modal <- bsplus::bs_modal(
id = session$ns("help_dose_mixed_yields_modal"),
title = "Help: Heterogeneous exposures",
size = "large",
body = tagList(
include_help("estimation/dose_mixed_yields.md")
)
)
if (assessment == "whole-body") {
return_tabbox <- tabBox(
id = "estimation_results_tabs",
width = 12,
side = "left",
title = help_modal_button(
container = "tabbox",
session$ns("help_dose_mixed_yields"),
session$ns("help_dose_mixed_yields_modal")
),
tabPanel(
title = "Whole-body",
h5("Whole-body exposure estimation"),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_yields_whole"))
),
br(),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_doses_whole"))
)
)
)
} else if (assessment == "partial-body") {
return_tabbox <- tabBox(
id = "estimation_results_tabs",
width = 12,
side = "left",
title = help_modal_button(
container = "tabbox",
session$ns("help_dose_mixed_yields"),
session$ns("help_dose_mixed_yields_modal")
),
tabPanel(
title = "Whole-body",
h5("Whole-body exposure estimation"),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_yields_whole"))
),
br(),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_doses_whole"))
)
),
tabPanel(
title = "Partial-body",
h5("Partial-body exposure estimation"),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_yields_partial"))
),
br(),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_doses_partial"))
),
br(),
h5("Initial fraction of irradiated cells"),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_frac_partial"))
)
)
)
} else if (assessment == "hetero") {
return_tabbox <- tabBox(
id = "estimation_results_tabs",
width = 12,
side = "left",
title = help_modal_button(
container = "tabbox",
session$ns("help_dose_mixed_yields"),
session$ns("help_dose_mixed_yields_modal")
),
tabPanel(
title = "Whole-body",
h5("Whole-body exposure estimation"),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_yields_whole"))
),
br(),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_doses_whole"))
)
),
tabPanel(
title = "Heterogeneous",
h5("Observed fraction of irradiated cells and its yield"),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_mixing_prop_hetero"))
),
br(),
h5("Heterogeneous exposure estimation"),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_yields_hetero"))
),
br(),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_doses_hetero"))
),
br(),
h5("Initial fraction of irradiated cells"),
div(
class = "hot-improved",
rHandsontableOutput(session$ns("est_frac_hetero"))
)
)
)
} else {
return(NULL)
}
return(tagList(return_tabbox, hetero_modal))
})
output$est_yields_whole <- renderRHandsontable({
if (input$button_estimate <= 0) {
return(NULL)
}
data()[["est_doses_whole"]] %>%
dplyr::select(.data$yield) %>%
t() %>%
as.data.frame() %>%
rhandsontable(
width = 320,
height = "100%",
rowHeaderWidth = 80
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$est_doses_whole <- renderRHandsontable({
if (input$button_estimate <= 0) {
return(NULL)
}
data()[["est_doses_whole"]] %>%
dplyr::select(.data$dose) %>%
t() %>%
as.data.frame() %>%
rhandsontable(
width = 320,
height = "100%",
rowHeaders = "dose (Gy)",
rowHeaderWidth = 80
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$est_yields_partial <- renderRHandsontable({
if (input$button_estimate <= 0 | data()[["assessment"]] != "partial-body") {
return(NULL)
}
data()[["est_doses_partial"]] %>%
dplyr::select(.data$yield) %>%
t() %>%
as.data.frame() %>%
dplyr::mutate(dplyr::across(where(is.logical), as.double)) %>%
`colnames<-`(c("lower", "estimate", "upper")) %>%
`row.names<-`("yield") %>%
rhandsontable(
width = 320,
height = "100%",
rowHeaderWidth = 80
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$est_doses_partial <- renderRHandsontable({
if (input$button_estimate <= 0 | data()[["assessment"]] != "partial-body") {
return(NULL)
}
data()[["est_doses_partial"]] %>%
dplyr::select(.data$dose) %>%
t() %>%
as.data.frame() %>%
dplyr::mutate(dplyr::across(where(is.logical), as.double)) %>%
`colnames<-`(c("lower", "estimate", "upper")) %>%
`row.names<-`("dose (Gy)") %>%
rhandsontable(
width = 320,
height = "100%",
rowHeaderWidth = 80
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$est_frac_partial <- renderRHandsontable({
if (input$button_estimate <= 0 | data()[["assessment"]] != "partial-body") {
return(NULL)
}
data()[["est_frac_partial"]] %>%
t() %>%
as.data.frame() %>%
dplyr::mutate(dplyr::across(where(is.logical), as.double)) %>%
`colnames<-`(c("lower", "estimate", "upper")) %>%
`row.names<-`("fraction") %>%
rhandsontable(
width = 320,
height = "100%",
rowHeaderWidth = 80
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$est_mixing_prop_hetero <- renderRHandsontable({
if (input$button_estimate <= 0 | data()[["assessment"]] != "hetero") {
return(NULL)
}
data()[["est_mixing_prop_hetero"]] %>%
dplyr::mutate(dplyr::across(where(is.logical), as.double)) %>%
`colnames<-`(c("yield", "yield.err", "frac", "frac.err")) %>%
`row.names<-`(c("dose1", "dose2")) %>%
rhandsontable(
width = 405,
height = "100%",
rowHeaderWidth = 85
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$est_yields_hetero <- renderRHandsontable({
if (input$button_estimate <= 0 | data()[["assessment"]] != "hetero") {
return(NULL)
}
data()[["est_yields_hetero"]] %>%
t() %>%
as.data.frame() %>%
dplyr::mutate(dplyr::across(where(is.logical), as.double)) %>%
`colnames<-`(c("lower", "estimate", "upper")) %>%
`row.names<-`(c("yield1", "yield2")) %>%
rhandsontable(
width = 325,
height = "100%",
rowHeaderWidth = 85
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$est_doses_hetero <- renderRHandsontable({
if (input$button_estimate <= 0 | data()[["assessment"]] != "hetero") {
return(NULL)
}
data()[["est_doses_hetero"]] %>%
t() %>%
as.data.frame() %>%
dplyr::mutate(dplyr::across(where(is.logical), as.double)) %>%
`colnames<-`(c("lower", "estimate", "upper")) %>%
`row.names<-`(c("dose1 (Gy)", "dose2 (Gy)")) %>%
rhandsontable(
width = 325,
height = "100%",
rowHeaderWidth = 85
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$est_frac_hetero <- renderRHandsontable({
if (input$button_estimate <= 0 | data()[["assessment"]] != "hetero") {
return(NULL)
}
data()[["est_frac_hetero"]] %>%
dplyr::mutate(dplyr::across(where(is.logical), as.double)) %>%
`colnames<-`(c("estimate", "std.err")) %>%
`row.names<-`(c("dose1", "dose2")) %>%
rhandsontable(
width = 245,
height = "100%",
rowHeaderWidth = 85
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$AIC_whole <- renderRHandsontable({
if (input$button_estimate <= 0) {
return(NULL)
}
data()[["AIC_whole"]] %>%
matrix() %>%
`colnames<-`(c("AIC")) %>%
rhandsontable(
width = 80,
height = "100%"
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$AIC_partial <- renderRHandsontable({
if (input$button_estimate <= 0 | data()[["assessment"]] != "partial-body") {
return(NULL)
}
data()[["AIC_partial"]] %>%
matrix() %>%
`colnames<-`(c("AIC")) %>%
rhandsontable(
width = 80,
height = "100%"
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$AIC_hetero <- renderRHandsontable({
if (input$button_estimate <= 0 | data()[["assessment"]] != "hetero") {
return(NULL)
}
data()[["AIC_hetero"]] %>%
matrix() %>%
`colnames<-`(c("AIC")) %>%
rhandsontable(
width = 80,
height = "100%"
) %>%
hot_cols(colWidths = 80) %>%
hot_cols(format = "0.000")
})
output$plot <- renderPlot(
res = 120,
{
if (input$button_estimate <= 0) {
return(NULL)
}
data()[["gg_curve"]]
}
)
output$save_plot <- downloadHandler(
filename = function() {
paste("estimation-curve-", Sys.Date(), input$save_plot_format, sep = "")
},
content = function(file) {
ggplot2::ggsave(
plot = data()[["gg_curve"]], filename = file,
width = 6, height = 4.5, dpi = 96,
device = gsub("\\.", "", input$save_plot_format)
)
}
)
output$save_report <- downloadHandler(
filename = function() {
paste0(aberr_module, "-estimation-report-", Sys.Date(), input$save_report_format)
},
content = function(file) {
temp_report <- file.path(tempdir(), "report.Rmd")
local_report <- load_rmd_report(
paste0(
"estimation-report-",
gsub("^\\.", "", input$save_report_format),
".Rmd"
)
)
file.copy(local_report, temp_report, overwrite = TRUE)
params <- list(
est_results_list = data(),
aberr_module = aberr_module
)
rmarkdown::render(
input = temp_report,
output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
} |
scan_neighbor = function(genoprobs, pheno, smap, scale, addcovar=NULL, addQTL=NULL, grouping=rep(1,nrow(smap)), response=c("quantitative","binary"), contrasts=NULL) {
response <- match.arg(response)
switch(response,
"quantitative" = glm_family <- stats::gaussian(),
"binary" = glm_family <- stats::binomial()
)
p <- dim(genoprobs$geno[[1]]$prob)[1]
geno <- decompose_genoprobs(genoprobs=genoprobs,contrasts=contrasts)
contrasts <- attr(geno, "contrasts")
scan_effect <- eff_neighbor(genoprobs=genoprobs, pheno=pheno, contrasts=contrasts, smap=smap, scale=scale, addcovar=addcovar, addQTL=addQTL, grouping=grouping, response=response, fig=FALSE)
q <- nrow(scan_effect)
p <- dim(genoprobs$geno[[1]]$prob)[1]
y_self_hat <- genoprobs2selfprobs(geno, a1=scan_effect$a1, d1=scan_effect$d1)
y_nei_hat <- calc_neiprob(geno, a2=scan_effect$a2, d2=scan_effect$d2, smap=smap, scale=scale, grouping=grouping)
X <- c()
if(is.null(addcovar)==FALSE) {
X <- cbind(X, addcovar)
}
if(is.null(addQTL)==FALSE) {
X <- cbind(X, y_self_hat[,match(addQTL, rownames(scan_effect))], y_nei_hat[,match(addQTL, rownames(scan_effect))])
}
if(is.null(addcovar)&is.null(addQTL)) {
LOD_self <- c(); LOD_nei <- c()
LL_null <- logLik_glm.fit(rep(1,length(pheno)),pheno,family=glm_family)
for(k in 1:q) {
LL_self <- logLik_glm.fit(cbind(1,y_self_hat[,k]),pheno,family=glm_family)
LL_nei <- logLik_glm.fit(cbind(1,y_self_hat[,k],y_nei_hat[,k]),pheno,family=glm_family)
LOD_self <- c(LOD_self, log10(exp(LL_self-LL_null)))
LOD_nei <- c(LOD_nei, log10(exp(LL_nei-LL_self)))
}
} else if(is.null(addQTL)==TRUE) {
LOD_self <- c(); LOD_nei <- c()
LL_null <- logLik_glm.fit(cbind(1,X),pheno,family=glm_family)
for(k in 1:q) {
LL_self <- logLik_glm.fit(cbind(1,X,y_self_hat[,k]),pheno,family=glm_family)
LL_nei <- logLik_glm.fit(cbind(1,X,y_self_hat[,k],y_nei_hat[,k]),pheno,family=glm_family)
LOD_self <- c(LOD_self, log10(exp(LL_self-LL_null)))
LOD_nei <- c(LOD_nei, log10(exp(LL_nei-LL_self)))
}
} else {
X <- cbind(y_self_hat[,match(addQTL, rownames(scan_effect))], y_nei_hat[,match(addQTL, rownames(scan_effect))])
LOD_self <- c(); LOD_nei <- c()
LL_null <- logLik_glm.fit(cbind(1,X),pheno,family=glm_family)
for(k in 1:q) {
LL_self <- logLik_glm.fit(cbind(1,X,y_self_hat[,k]),pheno,family=glm_family)
LL_nei <- logLik_glm.fit(cbind(1,X,y_self_hat[,k],y_nei_hat[,k]),pheno,family=glm_family)
LOD_self <- c(LOD_self, log10(exp(LL_self-LL_null)))
LOD_nei <- c(LOD_nei, log10(exp(LL_nei-LL_self)))
}
}
marker_info <- get_markers(genoprobs=genoprobs)
LODlist <- data.frame(marker_info, LOD_self, LOD_nei)
colnames(LODlist) <- c("chr","pos","LOD_self","LOD_nei")
return(LODlist)
} |
filter_throughput_time <- function(eventlog, interval, percentage, reverse, units, ...) {
UseMethod("filter_throughput_time")
}
filter_throughput_time.eventlog <- function(eventlog,
interval = NULL,
percentage = NULL,
reverse = FALSE,
units = c("days","hours","mins","secs","weeks"),
...) {
units <- match.arg(units)
percentage <- deprecated_perc(percentage, ...)
interval[1] <- deprecated_lower_thr(interval[1], ...)
interval[2] <- deprecated_upper_thr(interval[2], ...)
if(!is.null(interval) && (length(interval) != 2 || !is.numeric(interval) || any(interval < 0, na.rm = TRUE) || all(is.na(interval)) )) {
stop("Interval should be a positive numeric vector of length 2. One of the elements can be NA to create open intervals.")
}
if(!is.null(percentage) && (!is.numeric(percentage) || !between(percentage,0,1) )) {
stop("Percentage should be a numeric value between 0 and 1.")
}
if(is.null(interval) & is.null(percentage))
stop("At least an interval or a percentage must be provided.")
else if((!is.null(interval)) & !is.null(percentage))
stop("Cannot filter on both interval and percentage simultaneously.")
else if(!is.null(percentage))
filter_throughput_time_percentile(eventlog,
percentage = percentage,
reverse = reverse)
else
filter_throughput_time_threshold(eventlog,
lower_threshold = interval[1],
upper_threshold = interval[2],
reverse = reverse,
units = units)
}
filter_throughput_time.grouped_eventlog <- function(eventlog,
interval = NULL,
percentage = NULL,
reverse = FALSE,
units = c("days","hours","mins","secs","week"),
...) {
grouped_filter(eventlog, filter_throughput_time, interval, percentage, reverse, units, ...)
}
ifilter_throughput_time <- function(eventlog) {
ui <- miniPage(
gadgetTitleBar("Filter Througput Time"),
miniContentPanel(
fillCol(
fillRow(
radioButtons("filter_type", "Filter type:", choices = c("Interval" = "int", "Use percentile cutoff" = "percentile")),
radioButtons("units", "Time units: ", choices = c("weeks","days","hours","mins"), selected = "hours"),
radioButtons("reverse", "Reverse filter: ", choices = c("Yes","No"), selected = "No")
),
uiOutput("filter_ui")
)
)
)
server <- function(input, output, session){
output$filter_ui <- renderUI({
if(input$filter_type == "int") {
sliderInput("interval_slider", "Throguhput time interval",
min = 0, max = max(eventlog %>% throughput_time("case", units = input$units) %>% pull(throughput_time)), value = c(0,1))
}
else if(input$filter_type == "percentile") {
sliderInput("percentile_slider", "Percentile cut off:", min = 0, max = 100, value = 80)
}
})
observeEvent(input$done, {
if(input$filter_type == "int")
filtered_log <- filter_throughput_time(eventlog,
interval = input$interval_slider,
reverse = ifelse(input$reverse == "Yes", TRUE, FALSE),
units = input$units)
else if(input$filter_type == "percentile") {
filtered_log <- filter_throughput_time(eventlog,
percentage = input$percentile_slider/100,
reverse = ifelse(input$reverse == "Yes", TRUE, FALSE),
units = input$units)
}
stopApp(filtered_log)
})
}
runGadget(ui, server, viewer = dialogViewer("Filter Througput Time", height = 400))
} |
NULL
stopifnot(require(methods), require(utils), require(MortalityTables), require(tidyverse), require(reshape2))
VUBestandstafel.Detail.load = function() {
basedata = utils::read.csv(
system.file("extdata", "VU_Gesamtbestand_Austria_Detail_2012-16.csv", package = "MortalityTables"),
encoding = "UTF-8",
header = TRUE
)
basedata.array = basedata %>% as_tibble %>%
gather(Variable, Value, smooth, raw, Exposure) %>%
acast(tariff ~ sex ~ premium ~ probability ~ age ~ Variable, value.var = "Value")
VU.Gesamtbestand.Detail = array(
data = c(mortalityTable.NA),
dim = c(dim(basedata.array)[1:4], 2),
dimnames = c(`names<-`(dimnames(basedata.array)[1:4], c("Tarif", "Geschlecht", "Prämie", "Wahrscheinlichkeit")), list(Typ = c("raw", "smooth"))))
dmn = dimnames(basedata.array)[1:4]
q = "qx"
ages = 0:99
ages.ch = as.character(ages)
for (t in dmn[[1]]) {
for (s in dmn[[2]]) {
for (p in dmn[[3]]) {
VU.Gesamtbestand.Detail[[t, s, p, q, "smooth"]] = mortalityTable.period(
name = sprintf("VU Gesamtbestand AT, %s, %s, %s, %s, geglättet", t, s, p, q),
ages = ages,
deathProbs = basedata.array[t, s, p, q, ages.ch, "smooth"],
exposures = basedata.array[t, s, p, q, ages.ch, "Exposure"],
data = list(
raw = basedata.array[t, s, p, q, ages.ch, "raw"],
dim = list(
sex = s,
year = "(all)",
data = "smooth",
tarif = t,
table = "VU Gesamtbestand AT",
zahlart = p,
probability = q
))
)
VU.Gesamtbestand.Detail[[t, s, p, q, "raw"]] = mortalityTable.period(
name = sprintf("VU Gesamtbestand AT, %s, %s, %s, %s, roh", t, s, p, q),
ages = ages,
deathProbs = basedata.array[t, s, p, q, ages.ch, "raw"],
exposures = basedata.array[t, s, p, q, ages.ch, "Exposure"],
data = list(dim = list(
sex = s,
year = "(all)",
data = "raw",
tarif = t,
table = "VU Gesamtbestand AT",
zahlart = p,
probability = q
))
)
}
}
}
q = "sx"
ages = 0:40
ages.ch = as.character(ages)
for (t in dmn[[1]]) {
for (s in dmn[[2]]) {
for (p in dmn[[3]]) {
VU.Gesamtbestand.Detail[[t, s, p, q, "raw"]] = mortalityTable.period(
name = sprintf("VU Gesamtbestand AT, %s, %s, %s, %s, roh", t, s, p, q),
ages = ages,
deathProbs = basedata.array[t, s, p, q, ages.ch, "raw"],
exposures = basedata.array[t, s, p, q, ages.ch, "Exposure"],
data = list(dim = list(
sex = s,
year = "(all)",
data = "raw",
tarif = t,
table = "VU Gesamtbestand AT",
zahlart = p,
probability = q
))
)
}
}
}
VU.Gesamtbestand.Detail
}
VUBestandstafel.qx.load = function() {
basedata = utils::read.csv(
system.file("extdata", "VU_Gesamtbestand_Austria_qx_2012-16.csv", package = "MortalityTables"),
encoding = "UTF-8",
header = TRUE
)
sex = c("m", "f", "u")
VU.Gesamtbestand = array(
data = c(mortalityTable.NA),
dim = c(3),
dimnames = list(sex = sex)
)
for (s in sex) {
data = filter(basedata, sex == s)
data = data[order(data$age),]
VU.Gesamtbestand[[s]] = mortalityTable.period(
name = paste0("VU-Gesamtbestand 2012-2016, ", recode(s, "m" = "Männer", "f" = "Frauen", "u" = "Unisex")),
ages = data$age,
deathProbs = data$smooth,
baseYear = 2014,
exposures = data$exposure,
data = list(
raw = data$raw,
dim = list(
sex = s,
year = "2014",
data = "smooth",
tarif = "(all)",
table = "VU Gesamtbestand AT",
probability = "qx",
population = "Lebensversicherte",
country = "AT",
period = "2012-2016"
)
)
)
}
VU.Gesamtbestand
}
VUBestandstafel.Storno.load = function() {
basedata = utils::read.csv(
system.file("extdata", "VU_Gesamtbestand_Austria_Storno_2012-16.csv", package = "MortalityTables"),
encoding = "UTF-8",
header = TRUE
)
tarif = c("KLV", "FLV", "Sonstige")
VU.Gesamtbestand = array(
data = c(mortalityTable.NA),
dim = c(3),
dimnames = list(tarif = tarif)
)
for (t in tarif) {
data = filter(basedata, tarif == t)
data = data[order(data$age),]
VU.Gesamtbestand[[t]] = mortalityTable.period(
name = paste0("VU-Gesamtbestand 2012-2016, Storno ", t),
ages = data$age,
deathProbs = data$sx,
baseYear = 2014,
exposures = data$exposure,
data = list(
dim = list(
sex = "u",
year = "2014",
data = "raw",
tarif = t,
table = "VU Gesamtbestand AT",
probability = "sx",
population = "Lebensversicherte",
country = "AT",
period = "2012-2016"
)
)
)
}
VU.Gesamtbestand
}
VU.Gesamtbestand.Detail = VUBestandstafel.Detail.load()
VU.Gesamtbestand = VUBestandstafel.qx.load()
VU.Gesamtbestand.Storno = VUBestandstafel.Storno.load()
rm(VUBestandstafel.Detail.load, VUBestandstafel.qx.load, VUBestandstafel.Storno.load) |
geom_contour_z <- function(mapping = NULL,
data = NULL,
stat = "contour_z",
position = "identity",
...,
bins = NULL,
binwidth = NULL,
breaks = NULL,
lineend = "butt",
linejoin = "round",
linemitre = 10,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE,
extrude = FALSE,
material = list(),
keep2d = FALSE) {
layer(
data = data,
mapping = mapping,
stat = stat,
geom = GeomContourZ,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
bins = bins,
binwidth = binwidth,
breaks = breaks,
lineend = lineend,
linejoin = linejoin,
linemitre = linemitre,
na.rm = na.rm,
extrude = extrude,
material = material,
keep2d = keep2d,
...
)
)
}
GeomContourZ <- ggproto(
"GeomContourZ",
GeomPath3d,
required_aes = c("x", "y", "z"),
default_aes = augment_aes(
extrusion_aesthetics,
aes(
weight = 1,
colour = "
size = 0.5,
linetype = 1,
alpha = NA,
z = 10
)
)
) |
buttonGroupInput <- function(..., id, choices = NULL, values = choices,
labels = deprecated(),
direction = "horizontal") {
if (!is_missing(labels)) {
deprecate_soft(
"0.2.0",
"yonder::buttonGroupInput(labels = )",
"yonder::buttonGroupInput(choices = )"
)
choices <- labels
}
assert_id()
assert_choices()
shiny::registerInputHandler(
type = "yonder.button.group",
fun = function(x, session, name) {
if (length(x) > 1) x[[2]]
},
force = TRUE
)
with_deps({
buttons <- map_buttons(choices, values)
tag <- tags$div(
class = "yonder-button-group btn-group",
id = id,
role = "group",
buttons
)
args <- style_dots_eval(..., .style = style_pronoun("yonder_button_group"))
tag <- tag_extend_with(tag, args)
s3_class_add(tag, c("yonder_button_group", "yonder_input"))
})
}
updateButtonGroupInput <- function(id, choices = NULL, values = choices,
enable = NULL, disable = NULL,
session = getDefaultReactiveDomain()) {
assert_id()
assert_choices()
assert_session()
buttons <- map_buttons(choices, values)
content <- coerce_content(buttons)
enable <- coerce_enable(enable)
disable <- coerce_disable(disable)
session$sendInputMessage(id, list(
content = content,
enable = enable,
disable = disable
))
}
map_buttons <- function(choices, values) {
if (is.null(choices) && is.null(values)) {
return(NULL)
}
Map(
label = choices,
value = values,
function(label, value) {
tags$button(
type = "button",
class = "btn",
value = value,
label
)
}
)
} |
set_golem_options <- function(
golem_name = pkgload::pkg_name(),
golem_version = pkgload::pkg_version(),
golem_wd = pkgload::pkg_path(),
app_prod = FALSE,
talkative = TRUE
) {
change_app_config_name(
name = golem_name,
path = golem_wd
)
cat_if_talk <- function(..., fun = cat_green_tick) {
if (talkative) {
fun(...)
}
}
conf_path <- get_current_config(golem_wd, set_options = FALSE)
stop_if(
conf_path,
is.null,
"Unable to retrieve golem config file."
)
cat_if_talk(
"Setting {golem} options in `golem-config.yml`",
fun = cli::cat_rule
)
conf <- read_yaml(conf_path, eval.expr = TRUE)
if (golem_wd == here::here()) {
path <- "here::here()"
attr(path, "tag") <- "!expr"
} else {
path <- golem_wd
}
cat_if_talk(
sprintf(
"Setting `golem_wd` to %s",
path
)
)
cat_if_talk(
"You can change golem working directory with set_golem_wd('path/to/wd')",
fun = cat_line
)
conf$dev$golem_wd <- path
cat_if_talk(
sprintf(
"Setting `golem_name` to %s",
golem_name
)
)
conf$default$golem_name <- golem_name
cat_if_talk(
sprintf(
"Setting `golem_version` to %s",
golem_version
)
)
conf$default$golem_version <- as.character(golem_version)
cat_if_talk(
sprintf(
"Setting `app_prod` to %s",
app_prod
)
)
conf$default$app_prod <- app_prod
write_yaml(
conf,
conf_path
)
cat_if_talk(
"Setting {usethis} project as `golem_wd`",
fun = cli::cat_rule
)
proj_set(golem_wd)
}
set_golem_things <- function(
key,
value,
path,
talkative,
config = "default"
) {
conf_path <- get_current_config(path, set_options = FALSE)
stop_if(
conf_path,
is.null,
"Unable to retrieve golem config file."
)
cat_if_talk <- function(..., fun = cat_green_tick) {
if (talkative) {
fun(...)
}
}
cat_if_talk(
sprintf(
"Setting `%s` to %s",
key,
value
)
)
conf <- read_yaml(conf_path, eval.expr = TRUE)
conf[[config]][[key]] <- value
write_yaml(
conf,
conf_path
)
invisible(path)
}
set_golem_wd <- function(
path = pkgload::pkg_path(),
talkative = TRUE
) {
path <- path_abs(path)
if (path == here::here()) {
path <- "here::here()"
attr(path, "tag") <- "!expr"
}
set_golem_things(
"golem_wd",
path,
path,
talkative = talkative,
config = "dev"
)
invisible(path)
}
set_golem_name <- function(
name = pkgload::pkg_name(),
path = pkgload::pkg_path(),
talkative = TRUE
) {
path <- path_abs(path)
set_golem_things(
"golem_name",
name,
path,
talkative = talkative
)
change_app_config_name(
name = name,
path = path
)
desc <- desc::description$new(
file = fs::path(
path,
"DESCRIPTION"
)
)
desc$set(
Package = name
)
desc$write(
file = "DESCRIPTION"
)
invisible(name)
}
set_golem_version <- function(
version = pkgload::pkg_version(),
path = pkgload::pkg_path(),
talkative = TRUE
) {
path <- path_abs(path)
set_golem_things(
"golem_version",
as.character(version),
path,
talkative = talkative
)
desc <- desc::description$new(file = fs::path(path, "DESCRIPTION"))
desc$set_version(
version = version
)
desc$write(
file = "DESCRIPTION"
)
invisible(version)
}
get_golem_things <- function(
value,
config = Sys.getenv("R_CONFIG_ACTIVE", "default"),
use_parent = TRUE,
path
) {
conf_path <- get_current_config(path, set_options = TRUE)
stop_if(
conf_path,
is.null,
"Unable to retrieve golem config file."
)
config::get(
value = value,
config = config,
file = conf_path,
use_parent = TRUE
)
}
get_golem_wd <- function(
use_parent = TRUE,
path = pkgload::pkg_path()
) {
get_golem_things(
value = "golem_wd",
config = "dev",
use_parent = use_parent,
path = path
)
}
get_golem_name <- function(
config = Sys.getenv("R_CONFIG_ACTIVE", "default"),
use_parent = TRUE,
path = pkgload::pkg_path()
) {
nm <- get_golem_things(
value = "golem_name",
config = config,
use_parent = use_parent,
path = path
)
if (is.null(nm)) {
nm <- pkgload::pkg_name()
}
nm
}
get_golem_version <- function(
config = Sys.getenv("R_CONFIG_ACTIVE", "default"),
use_parent = TRUE,
path = pkgload::pkg_path()
) {
get_golem_things(
value = "golem_version",
config = config,
use_parent = use_parent,
path = path
)
} |
downloader <- function(x, dsn = getwd(), overwrite = FALSE, quiet = TRUE,
mode = "wb", cores = 1L, ...) {
checkDsn(dsn)
cores <- checkCores(cores)
userpwd = if (any(grepl("^ftp://", x))) {
nfo = getPolesFTPOpts()
paste(
nfo$gimms.poles.username
, nfo$gimms.poles.password
, sep = ":"
)
}
if (cores == 1L) {
for (i in x) {
destfile <- paste0(dsn, "/", basename(i))
if (file.exists(destfile) & !overwrite) {
if (!quiet)
cat("File", destfile, "already exists in destination folder. Proceeding to next file ...\n")
} else {
if (grepl("^ftp://", i)) {
h = curl::new_handle(
userpwd = userpwd
)
try(
curl::curl_download(
i
, destfile = destfile
, handle = h
)
, silent = TRUE
)
} else {
try(download.file(i, destfile = destfile, mode = mode,
quiet = quiet, ...), silent = TRUE)
}
}
}
} else {
cl <- parallel::makePSOCKcluster(cores)
on.exit(parallel::stopCluster(cl))
parallel::clusterExport(
cl
, c("x", "dsn", "overwrite", "quiet", "mode", "userpwd")
, envir = environment()
)
parallel::parLapply(cl, x, function(i) {
destfile <- paste0(dsn, "/", basename(i))
if (file.exists(destfile) & !overwrite) {
if (!quiet)
cat("File", destfile, "already exists in destination folder. Proceeding to next file ...\n")
} else {
if (grepl("^ftp://", i)) {
h = curl::new_handle(
userpwd = userpwd
)
try(
curl::curl_download(
i
, destfile = destfile
, handle = h
)
, silent = TRUE
)
} else {
try(download.file(i, destfile = destfile, mode = mode,
quiet = quiet, ...), silent = TRUE)
}
}
})
}
gimms_out <- paste(dsn, basename(x), sep = "/")
return(gimms_out)
}
createHeader <- function(x) {
header <- paste("ENVI",
"description = { R-language data }",
"samples = 2160",
"lines = 4320",
"bands = 1",
"data type = 2",
"header offset = 0",
"interleave = bsq",
"sensor type = AVHRR",
"byte order = 1", sep = "\n")
sapply(x, function(i) {
fls <- paste0(i, ".hdr")
writeLines(header, fls)
return(fls)
})
}
checkCores <- function(cores) {
cores_avl <- parallel::detectCores()
if (cores > cores_avl) {
cores <- cores_avl - 1
warning("Desired number of cores is invalid. Resizing parallel cluster to ", cores, " cores.")
}
return(cores)
}
checkDsn <- function(dsn) {
if (!dir.exists(dsn)) {
answer <- readline(paste("Target folder", dsn, "doesn't exist.",
"Do you wish to create it? (yes/no) \n"))
if (answer == "yes") {
dir.create(dsn)
} else {
stop(paste("Target folder", dsn, "doesn't exist. Aborting operation...\n"))
}
}
return(invisible())
}
setLocale <- function(reset = FALSE, ...) {
if (!reset) {
if (Sys.info()[["sysname"]] == "Windows") {
invisible(Sys.setlocale(category = "LC_TIME", locale = "C"))
} else {
invisible(Sys.setlocale(category = "LC_TIME", locale = "en_US.UTF-8"))
}
} else {
Sys.setlocale(category = "LC_TIME", ...)
}
return(invisible())
}
getV1dates <- function(x, pos1 = 15L, pos2 = 23L, suffix = TRUE) {
fls <- substr(basename(x), pos1, pos2)
lst <- strsplit(fls, "_")
yrs <- sapply(lst, "[[", 1)
yrs <- substr(yrs, 3, 4)
mts <- sapply(lst, "[[", 2)
locale <- Sys.getlocale(category = "LC_TIME")
setLocale()
lst <- lapply(seq(mts), function(i) {
mts <- if (mts[i] == "0106") {
rep(tolower(month.abb[1:6]), each = 2)
} else {
rep(tolower(month.abb[7:12]), each = 2)
}
if (suffix)
mts <- paste0(mts, rep(c("15a", "15b"), length(mts) / 2))
dts <- paste0(yrs[i], mts)
return(dts)
})
setLocale(reset = TRUE, locale = locale)
return(unlist(lst))
}
getV0dates <- function(x, pos1 = 4L, pos2 = 11L, suffix = TRUE) {
substr(basename(x), pos1, ifelse(suffix, pos2, pos2 - 1))
}
productVersion <- function(x, uniform = FALSE) {
v0 <- substr(basename(x), 1, 3) == "geo"
v1 <- substr(basename(x), 1, 6) == "ndvi3g"
ids <- apply(cbind(v0, v1), 1, FUN = function(y) {
tmp <- which(y)
if (length(tmp) == 0) NA else tmp - 1
})
if (uniform) {
if (length(unique(ids)) > 1)
stop("Different or non-classifiable product versions found. Please make
sure to supply files from the same NDVI3g version only that follow the
rules of GIMMS standard naming.\n")
}
return(ids)
}
checkFls <- function(x, filename) {
len <- length(filename)
if (len == 1) {
if (nchar(filename) == 0) {
rep(filename, length(x))
} else {
stop("If specified, 'filename' must be of the same length as 'x'.\n")
}
} else if ((len > 1) & (len != length(x))) {
stop("If specified, 'filename' must be of the same length as 'x'.\n")
} else {
filename
}
}
checkVersion = function(server, version) {
input = version
version = suppressWarnings(
as.integer(version)
)
version = switch(
server
, "ecocast" = intersect(version, c(0, 1))
, "nasanex" = intersect(version, 0)
, "poles" = intersect(version, 1)
)
if (length(version) == 0) {
stop(
sprintf(
"NDVI3g version '%s' is not available from server '%s'."
, input
, server
)
)
}
return(version)
} |
f<-function(x,a,b){
z=0
for(i in 1:length(b))
z=z+a[i]*x^(b[i])
z
}
allroots<-function(a,b){
a1=a
b1=b
n=length(b)-1
a=a/a[1]
b=matrix(0,ncol=n,nrow=n)
for(i in 1:(n-1))
b[i,i+1]=1
for(i in 1:n)
b[n,i]=-a[n+2-i]
c=eigen(b)
print(c$values)
print("inaccuracy error")
print(f(c$values,a1,b1))
}
dichotomy<-function(x1,x2,a,b,pert = 10^(-5),n=1000,s=0.1){
x0=rep(NA,length(x1))
for(i in 1:length(x1)){
if(f(x1[i],a,b)==0)
x0[i]=x1[i]
if(f(x2[i],a,b)==0)
x0[i]=x2[i]
if(f(x1[i],a,b)!=0&f(x2[i],a,b)!=0){
x0[i]=(x1[i]+x2[i])/2
k=1
while((abs(f(x0[i],a,b))>=pert)&(k<n)){
if(f(x0[i],a,b)==0)
break
if(f(x1[i],a,b)*f(x0[i],a,b)<0)
x2[i]=x0[i]
if(f(x2[i],a,b)*f(x0[i],a,b)<0)
x1[i]=x0[i]
if(x1[i]!=x0[i]&x2[i]!=x0[i])
x2[i]=x2[i]-s
x0[i]=(x1[i]+x2[i])/2
k=k+1
if(k==1000)
x0[i]=NA
}
}
}
x0
} |
matrixsetup_kappa <- function(
kappa,
nNode,
nGroup,
expcov,
labels,
equal = FALSE,
sampletable,
name = "kappa",
beta = array(0, c(nNode, nNode,nGroup))
){
ischar <- is.character(kappa)
kappa <- fixAdj(kappa,nGroup,nNode,equal,diag0=FALSE)
kappaStart <- kappa
for (g in 1:nGroup){
covest <- as.matrix(expcov[[g]])
zeroes <- which(kappaStart[,,g]==0 & t(kappaStart[,,g])==0 & diag(nNode) != 1,arr.ind=TRUE)
if (nrow(zeroes) == 0){
wi <- solve_symmetric(covest)
if (any(abs(qgraph::wi2net(wi)[lower.tri(wi,diag=FALSE)]) > 0.8)){
wi <- glasso(as.matrix(spectralshift(covest)), rho = 0.1)$wi
}
} else {
glas <- glasso(as.matrix(covest),
rho = 1e-10, zero = zeroes)
wi <- glas$wi
}
kappaStart[,,g] <- (kappaStart[,,g] !=0) * as.matrix(wi)
if (ischar && nNode > 1){
endo <- which(rowSums(beta[,,g])>0)
inds <- (row(kappa[,,g]) %in% endo | col(kappa[,,g]) %in% endo) & (row(kappa[,,g] ) != col(kappa[,,g] ))
kappa[,,g][inds] <- kappaStart[,,g][inds] <- 0
}
}
list(kappa,
mat = name,
op = "--",
symmetrical= TRUE,
sampletable=sampletable,
rownames = labels,
colnames = labels,
sparse = TRUE,
posdef = TRUE,
diag0 = FALSE,
start = kappaStart
)
} |
library(pROC)
data(aSAH)
context("ci.formula")
test_that("bootstrap cov works with smooth and !reuse.auc", {
skip_slow()
if (R.version$minor >= "6.0") {
RNGkind(sample.kind="Rounding")
}
for (pair in list(
list(ci, list()),
list(ci.se, list(boot.n = 10)),
list(ci.sp, list(boot.n = 10)),
list(ci.thresholds, list(boot.n = 10)),
list(ci.coords, list(boot.n = 10, x = 0.5)),
list(ci.auc, list()))) {
fun <- pair[[1]]
args.default <- c(
list(response = aSAH$outcome,
predictor = aSAH$s100b),
pair[[2]])
set.seed(42)
obs.default <- do.call(fun, args.default)
args.formula <- c(
list(formula = outcome ~ s100b,
data = aSAH),
pair[[2]])
set.seed(42)
obs.formula <- do.call(fun, args.formula)
expect_equivalent(obs.default, obs.formula)
}
}) |
plot_data_one_iso <- function(mix,source,discr,filename,plot_save_pdf,plot_save_png,return_obj=FALSE){
if(length(grep("C",mix$iso_names))==1) x_label <- expression(paste(delta^13, "C (\u2030)",sep=""))
if(length(grep("N",mix$iso_names))==1) x_label <- expression(paste(delta^15, "N (\u2030)",sep=""))
if(length(grep("S",mix$iso_names))==1) x_label <- expression(paste(delta^34, "S (\u2030)",sep=""))
if(length(grep("O",mix$iso_names))==1) x_label <- expression(paste(delta^18, "O (\u2030)",sep=""))
if(length(grep("SP",mix$iso_names))==1) x_label <- expression(paste(delta^15, "N-SP (\u2030)",sep=""))
if(!exists("x_label")) x_label <- mix$iso_names
y_data <- 0.5
y <- rep(y_data,mix$N)
df <- data.frame(x = mix$data_iso, y = y)
spacing <- 0.1
if(!is.na(source$by_factor)){
source_linetype <- sort(rep(1:source$n.sources,source$S_factor_levels))
source_color <- factor(as.numeric(source$S_factor1))
index <- seq(from=1,to=1+(source$n.sources-1)*source$S_factor_levels,by=source$S_factor_levels)
discr_mu_plot <- array(NA,dim=c(length(source$S_MU[,1]),mix$n.iso))
discr_sig2_plot <- array(NA,dim=c(length(source$S_MU[,1]),mix$n.iso))
for(i in 1:source$n.sources){
discr_mu_plot[index[i]:(index[i]+source$S_factor_levels-1),] <- matrix(rep(discr$mu[i],source$S_factor_levels),nrow=source$S_factor_levels,ncol=mix$n.iso,byrow=T)
discr_sig2_plot[index[i]:(index[i]+source$S_factor_levels-1),] <- matrix(rep(discr$sig2[i],source$S_factor_levels),nrow=source$S_factor_levels,ncol=mix$n.iso,byrow=T)
}
y_sources <- seq(y_data+0.2,(source$S_factor_levels*source$n.sources*spacing)-spacing+y_data+0.2,by=spacing)
MU_plot <- source$S_MU[,mix$iso_names] + discr_mu_plot
SIG_plot <- sqrt(source$S_SIG[,mix$iso_names]^2 + discr_sig2_plot)
} else {
source_linetype <- 1:source$n.sources
source_color <- factor(rep("black",source$n.sources))
index <- 1:source$n.sources
discr_mu_plot <- discr$mu
discr_sig2_plot <- discr$sig2
y_sources <- seq(y_data+0.2,(source$n.sources*spacing)-spacing+y_data+0.2,by=spacing)
source$S_factor_levels <- 0.5
MU_plot <- source$S_MU + discr_mu_plot
SIG_plot <- sqrt(source$S_SIG^2 + discr_sig2_plot)
}
MU_plot <- as.vector(MU_plot)
SIG_plot <- as.vector(SIG_plot)
df_sources <- data.frame(x=MU_plot,
xmin = MU_plot - SIG_plot,
xmax = MU_plot + SIG_plot,
y = y_sources,
linetype = source_linetype,
scolour = source_color)
source.labels <- data.frame(
x = MU_plot[index],
y = y_sources[index] + spacing*source$S_factor_levels,
label = source$source_names
)
.e <- environment()
dev.new()
if(mix$n.effects==2){
shapes <- c(16,17,15,3,7,8,1,6,35,36,37,4,18,14,11,9,13)
shapes <- shapes[1:mix$FAC[[2]]$levels]
if(!is.na(source$by_factor)){
g <- ggplot2::ggplot(data = df,ggplot2::aes(x = x,y = y),environment=.e) +
ggplot2::geom_point(ggplot2::aes(colour = factor(mix$FAC[[1]]$values),
shape = factor(mix$FAC[[2]]$values)), position=position_jitter(width=.2,height=.1), show.legend=T) +
ggplot2::scale_colour_discrete(breaks = levels(factor(mix$FAC[[1]]$values)),
labels = mix$FAC[[1]]$labels) +
ggplot2::scale_shape_manual(values=shapes, labels=mix$FAC[[2]]$labels) +
ggplot2::geom_point(data=df_sources,
ggplot2::aes(x=x, y=y,colour=scolour),
size=2,
show.legend=F) +
ggplot2::geom_errorbarh(data=df_sources,
ggplot2::aes(xmin=xmin,xmax=xmax,colour=scolour),
size=1,
height=0,
linetype=source_linetype,
show.legend=F) +
ggplot2::geom_text(data=source.labels, ggplot2::aes(x=x,y=y,label=label), show.legend=F) +
ggplot2::scale_y_continuous(breaks = NULL) +
ggplot2::ylab("") +
ggplot2::xlab(x_label) +
ggplot2::theme_bw() +
ggplot2::theme(legend.position=c(0,1), legend.justification=c(0,1), legend.title=ggplot2::element_blank())
print(g)
} else {
g <- ggplot2::ggplot(data = df,ggplot2::aes(x = x,y = y),environment=.e) +
ggplot2::geom_point(ggplot2::aes(colour = factor(mix$FAC[[1]]$values),
shape = factor(mix$FAC[[2]]$values)), position=position_jitter(width=.2,height=.1), show.legend=T) +
ggplot2::scale_colour_discrete(breaks = levels(factor(mix$FAC[[1]]$values)),
labels = mix$FAC[[1]]$labels) +
ggplot2::scale_shape_manual(values=shapes, labels=mix$FAC[[2]]$labels) +
ggplot2::geom_point(data=df_sources,
ggplot2::aes(x=x, y=y),
size=2,
show.legend=F) +
ggplot2::geom_errorbarh(data=df_sources,
ggplot2::aes(xmin=xmin,xmax=xmax),
size=1,
height=0,
linetype=source_linetype,
show.legend=F) +
ggplot2::geom_text(data=source.labels, ggplot2::aes(x=x,y=y,label=label), show.legend=F) +
ggplot2::scale_y_continuous(breaks = NULL) +
ggplot2::ylab("") +
ggplot2::xlab(x_label) +
ggplot2::theme_bw() +
ggplot2::theme(legend.position=c(0,1), legend.justification=c(0,1), legend.title=ggplot2::element_blank())
print(g)
}
}
if(mix$n.effects==1){
if(!is.na(source$by_factor)){
g <- ggplot2::ggplot(data = df,ggplot2::aes(x = x,y = y),environment=.e) +
ggplot2::geom_point(ggplot2::aes(colour = factor(mix$FAC[[1]]$values)), position=position_jitter(width=.2,height=.1), show.legend=T) +
ggplot2::scale_colour_discrete(breaks = levels(factor(mix$FAC[[1]]$values)),
labels = mix$FAC[[1]]$labels) +
ggplot2::geom_point(data=df_sources,
ggplot2::aes(x=x, y=y, colour=scolour),
size=2,
show.legend=F) +
ggplot2::geom_errorbarh(data=df_sources,
ggplot2::aes(xmin=xmin,xmax=xmax,colour=scolour),
size=1,
height=0,
linetype=source_linetype,
show.legend=F) +
ggplot2::geom_text(data=source.labels, ggplot2::aes(x=x,y=y,label=label), show.legend=F) +
ggplot2::scale_y_continuous(breaks = NULL) +
ggplot2::ylab("") +
ggplot2::xlab(x_label) +
ggplot2::theme_bw() +
ggplot2::theme(legend.position=c(0,1), legend.justification=c(0,1), legend.title=ggplot2::element_blank())
print(g)
} else {
g <- ggplot2::ggplot(data = df,ggplot2::aes(x = x,y = y),environment=.e) +
ggplot2::geom_point(ggplot2::aes(colour = factor(mix$FAC[[1]]$values)), position=position_jitter(width=.2,height=.1), show.legend=T) +
ggplot2::scale_colour_discrete(breaks = levels(factor(mix$FAC[[1]]$values)),
labels = mix$FAC[[1]]$labels) +
ggplot2::geom_point(data=df_sources,
ggplot2::aes(x = x, y = y),
size=2,
show.legend=F) +
ggplot2::geom_errorbarh(data=df_sources,
ggplot2::aes(xmin=xmin,xmax=xmax),
size=1,
height=0,
linetype=source_linetype,
show.legend=F) +
ggplot2::geom_text(data=source.labels, ggplot2::aes(x=x,y=y,label=label), show.legend=F) +
ggplot2::scale_y_continuous(breaks = NULL) +
ggplot2::ylab("") +
ggplot2::xlab(x_label) +
ggplot2::theme_bw() +
ggplot2::theme(legend.position=c(0,1), legend.justification=c(0,1), legend.title=ggplot2::element_blank())
print(g)
}
}
if(mix$n.effects==0){
g <- ggplot2::ggplot(data = df,ggplot2::aes(x = x,y = y)) +
ggplot2::geom_point(position=ggplot2::position_jitter(width=.2,height=.1)) +
ggplot2::geom_point(data=df_sources,
ggplot2::aes(x=x,y=y),
size=2,
show.legend=F) +
ggplot2::geom_errorbarh(data=df_sources,
ggplot2::aes(xmin=xmin,xmax=xmax),
size=1,
height=0,
linetype=source_linetype,
show.legend=F) +
ggplot2::geom_text(data=source.labels, ggplot2::aes(x=x,y=y,label=label), show.legend=F) +
ggplot2::scale_y_continuous(breaks = NULL) +
ggplot2::ylab("") +
ggplot2::xlab(x_label) +
ggplot2::theme_bw() +
ggplot2::theme(legend.position=c(0,1), legend.justification=c(0,1), legend.title=ggplot2::element_blank())
print(g)
}
if(plot_save_pdf==TRUE){
mypath <- file.path(paste(getwd(),"/",filename,".pdf",sep=""))
cairo_pdf(filename=mypath, width=7, height=7)
print(g)
dev.off()
}
if(plot_save_png==TRUE){
mypath <- file.path(paste(getwd(),"/",filename,".png",sep=""))
png(filename=mypath)
print(g)
dev.off()
}
if(return_obj==TRUE) return(g)
} |
dcl.predict<-function(dcl.par,Ntriangle,Model=2,Tail=TRUE,Tables=TRUE,
summ.by="diag",num.dec=2)
{
inflat<-dcl.par$inflat
mu<-dcl.par$mu
mu.adj<-dcl.par$mu.adj
pi.delay<-dcl.par$pi.delay
if (max(abs(pi.delay))>1) {
message("Warning: Check if the data follow the DCL model, the estimated delay function is not valid.")
}
pj<-dcl.par$pj
m<-length(pj);d<-m-1
Nhat<-dcl.par$Nhat
Nhat<-as.matrix(Nhat)
Xhat<-dcl.par$Xhat
Xhat<-as.matrix(Xhat)
if (missing(Ntriangle) | Model==0) Ntriangle<-Nhat
Ntriangle<-as.matrix(Ntriangle)
two.models<-function(pj,mu)
{
Ec.rbns<-function(Ntriangle,pj,mu,inflat,m,d)
{
set.rect<-expand.grid(1:(m+d),1:m)
v.expect<-apply(set.rect,MARGIN=1,FUN= function(v) { j<-v[1];i<-v[2];
if ((j>(m-i+1))& (j<(m+d-i+2))) {limq<-(i-m+j-1):(min((j-1),d));limN<-j-limq;
v.e<-sum(Ntriangle[i,limN]* pj[limq+1] * mu*inflat[i],na.rm=T)} else v.e<-NA
return(v.e) })
Xrbns<-matrix(v.expect,m,m+d,byrow=T)
return(Xrbns)
}
Ec.ibnr<-function(Nhat,pj,mu,inflat,m,d)
{
set.rect<-expand.grid(1:(m+d),1:m)
Nhat_ext<-cbind(Nhat,matrix(NA,nrow=m,ncol=d))
v.expect<-apply(set.rect,MARGIN=1, FUN=function(v) {
j<-as.numeric(v[1]);i<-as.numeric(v[2]);
if ((j>(m-i+1))& (j<(m+d+1))& (i>1)) {
limq<-0:(min((i-m+j-2),d));limN<-j-limq;
v.e<-sum(Nhat_ext[i,limN]*pj[limq+1]*mu*inflat[i],na.rm=T)} else v.e<-NA
return(v.e)})
Xibnr<-matrix(v.expect,m,m+d,byrow=T)
return(Xibnr)
}
Xrbns<-Ec.rbns(Ntriangle,pj,mu,inflat,m,d)
Xibnr<-Ec.ibnr(Nhat,pj,mu,inflat,m,d)
if (Tail==FALSE) {Xrbns[,(m+1):( 2*m-1)]<-0 ; Xibnr[,(m+1):( 2*m-1)]<-0}
Xrbns.zero<-Xrbns
Xrbns.zero[is.na(Xrbns)]<-0
Xibnr.zero<-Xibnr
Xibnr.zero[is.na(Xibnr)]<-0
Xtotal<-Xrbns.zero+Xibnr.zero
if (summ.by=="diag")
{
dd<-m+d-1
Drbns<-sapply(split(Xrbns, row(Xrbns)+col(Xrbns)), sum, na.rm=T)
Drbns<-as.vector(Drbns[-(1:m)])
Drbns<-c(Drbns,sum(Drbns,na.rm =T))
Dibnr<-sapply(split(Xibnr, row(Xibnr)+col(Xibnr)), sum, na.rm=T)
Dibnr<-as.vector(Dibnr[-(1:m)])
Dibnr<-c(Dibnr,sum(Dibnr,na.rm =T))
Dtotal<-Drbns+Dibnr
if (Tables==TRUE)
{
Diag.CL.paid<-sapply(split(Xhat, row(Xhat)+col(Xhat)), sum, na.rm=T)
Dclm<-c(Diag.CL.paid[-(1:m)])
Total.CL.paid<- sum(Dclm,na.rm=TRUE)
Dclm<-c(Dclm,rep(NA,dd-length(Dclm)),Total.CL.paid)
table.diags<-data.frame(Future.years=c(1:dd,'Tot.'),rbns=round(Drbns,num.dec),
ibnr=round(Dibnr,num.dec),total=round(Dtotal,num.dec),
clm=round(Dclm,num.dec))
print(table.diags)
}
return(list(Drbns=Drbns,Xrbns=Xrbns,Dibnr=Dibnr,Xibnr=Xibnr,
Dtotal=Dtotal,Xtotal=Xtotal))
}
if (summ.by=="row")
{
Rrbns<-rowSums(Xrbns,na.rm=TRUE)
Rrbns<-c(Rrbns,sum(Rrbns,na.rm=TRUE))
Ribnr<-rowSums(Xibnr,na.rm=TRUE)
Ribnr<-c(Ribnr,sum(Ribnr,na.rm=TRUE))
Rtotal<-Rrbns+Ribnr
if (Tables==TRUE)
{
Xhat.low<-Xhat
Xhat.low[row(Xhat)+col(Xhat)<=(m+1)]<-NA
Ri.CL.paid<-rowSums(Xhat.low,na.rm=T)
Total.CL.paid<- sum(Ri.CL.paid,na.rm=TRUE)
Rclm<-c(Ri.CL.paid,Total.CL.paid)
table.rows<-data.frame(Rows=c(1:m,'Tot.'),rbns=round(Rrbns,num.dec),
ibnr=round(Ribnr,num.dec),total=round(Rtotal,num.dec),
clm=round(Rclm,num.dec))
print(table.rows)
}
return(list(Rrbns=Rrbns,Xrbns=Xrbns,Ribnr=Ribnr,Xibnr=Xibnr,
Rtotal=Rtotal,Xtotal=Xtotal))
}
if (summ.by=="cell")
{
return(list(Xrbns=Xrbns,Xibnr=Xibnr,Xtotal=Xtotal))
}
}
if (Model==1 | Model==0) res.model<-two.models(pi.delay,mu) else res.model<-two.models(pj,mu.adj)
return(res.model)
} |
censor.exp.x <-
function(delta,x,min.branch){
Fn <- sum(delta)
x[x==0] <- min.branch
Tn <- sum(x)
est <- Fn/Tn
LL <- Fn*(log(Fn)-log(Tn)-1)
a <- data.frame(t(c(est,NA)),LL)
return(a)
} |
setGeneric("initializeCloudProvider", function(provider, cluster, verbose){
standardGeneric("initializeCloudProvider")
}, signature = "provider")
setGeneric("runDockerServer", function(provider, cluster, container, hardware, verbose){
standardGeneric("runDockerServer")
}, signature = "provider")
setGeneric("stopDockerServer", function(provider, cluster, verbose){
standardGeneric("stopDockerServer")
}, signature = "provider")
setGeneric("getServerStatus", function(provider, cluster, verbose){
standardGeneric("getServerStatus")
}, signature = "provider")
setGeneric("getDockerServerIp", function(provider, cluster, verbose){
standardGeneric("getDockerServerIp")
}, signature = "provider")
setGeneric("setDockerWorkerNumber", function(provider, cluster, container, hardware, workerNumber, verbose){
standardGeneric("setDockerWorkerNumber")
}, signature = "provider")
setGeneric("getDockerWorkerNumbers", function(provider, cluster, verbose){
standardGeneric("getDockerWorkerNumbers")
}, signature = "provider")
setGeneric("dockerClusterExists", function(provider, cluster, verbose){
standardGeneric("dockerClusterExists")
}, signature = "provider")
setGeneric("reconnectDockerCluster", function(provider, cluster, verbose){
standardGeneric("reconnectDockerCluster")
}, signature = "provider")
setGeneric("cleanupDockerCluster", function(provider, cluster, deep, verbose){
standardGeneric("cleanupDockerCluster")
}, signature = "provider") |
ffp <- function(x = double(), ...) {
vctrs::vec_cast(x, double())
new_ffp(x, ...)
}
is_ffp <- function(x) {
inherits(x, "ffp")
}
as_ffp <- function(x) {
UseMethod("as_ffp", x)
}
as_ffp.default <- function(x) {
vctrs::vec_cast(x, new_ffp())
}
as_ffp.integer <- function(x) {
vctrs::vec_cast(as.double(x), new_ffp())
}
NULL
methods::setOldClass(c("ffp", "vctrs_vctr"))
new_ffp <- function(x = double(), ...) {
vctrs::vec_assert(x, double())
vctrs::new_vctr(x, class = "ffp", ...)
}
vec_ptype_abbr.ffp <- function(x, ...) "ffp"
vec_ptype2.ffp.ffp <- function(x, y, ...) new_ffp()
vec_ptype2.ffp.double <- function(x, y, ...) double()
vec_ptype2.double.ffp <- function(x, y, ...) double()
vec_cast.ffp.ffp <- function(x, to, ...) x
vec_cast.ffp.double <- function(x, to, ...) ffp(x)
vec_cast.double.ffp <- function(x, to, ...) vctrs::vec_data(x)
obj_print_data.ffp <- function(x, ...) {
if (vctrs::vec_size(x) <= 5) {
cat(x)
} else {
cat(utils::head(x, 5), "...", utils::tail(x, 1))
}
}
vec_math.ffp <- function(.fn, .x, ...) vctrs::vec_math_base(.fn, .x, ...)
vec_arith.ffp <- function(op, x, y, ...) vctrs::vec_arith_base(op, x, y, ...) |
"hewlett_packard" |
plot.summary.loci <-
function(x, loci, what = "both", layout = 1, col = c("blue", "red"), ...)
{
what <- match.arg(what, c("both", "alleles", "genotypes"))
layout(matrix(1:layout, ceiling(sqrt(layout))))
if (!devAskNewPage() && !names(dev.cur()) %in% c("pdf", "postscript")) {
devAskNewPage(TRUE)
on.exit(devAskNewPage(FALSE))
}
nms <- names(x)
N <- if (!missing(loci)) match(loci, nms) else seq_along(x)
if (what == "both") {
for (i in N){
barplot(x[[i]]$allele, main = paste(nms[i], "- alleles"),
col = col[1], ...)
barplot(x[[i]]$genotype, main = paste(nms[i], "- genotypes"),
col = col[2], ...)
}
} else if (what == "alleles")
for (i in N)
barplot(x[[i]]$allele, main = nms[i], col = col[1], ...)
else if (what == "genotypes")
for (i in N)
barplot(x[[i]]$genotype, main = nms[i], col = col[2], ...)
} |
delim.table<-function(x,filename="",delim=",",tabegin="",bor="",eor="\n",
tablend="",label=deparse(substitute(x)),header=NULL,trailer=NULL,html=FALSE,
show.rownames=TRUE,leading.delim=FALSE,show.all=FALSE,nsignif=4,
con,open.con=FALSE) {
if(html) {
if(delim == ",") delim="<td>"
if(tabegin == "") tabegin="<table border=1>\n"
if(bor == "") bor="<tr><td>"
if(eor == "\n") eor="</tr>\n"
if(tablend == "") tablend="</table>\n"
if(is.null(header)) header="<html><body>\n"
if(is.null(trailer)) trailer="</body></html>\n"
}
if(missing(con)) {
if(nzchar(filename)) {
con<-file(filename,"w")
open.con<-TRUE
}
else con<-""
if(!is.null(header)) cat(header,"\n",file=con)
}
if(is.list(x) && !is.data.frame(x) && length(x) > 1) {
if(!is.null(label)) cat(label,eor,file=con)
for(component in 1:length(x))
delim.table(x[[component]],filename="",delim=delim,tabegin=tabegin,bor=bor,
eor=eor,tablend=tablend,label=names(x[component]),html=FALSE,
show.rownames=show.rownames,leading.delim=leading.delim,
show.all=show.all,con=con)
}
else {
xdim<-dim(x)
if(length(xdim) > 2) stop("delim.table can only process 2D tables")
if(is.null(xdim)) {
if(show.all) {
cat(label,eor,file=con)
if(is.vector(x)) {
if(is.expression(x)) cat("Can't print expression",file=con)
else {
for(xindex in 1:length(x))
cat(ifelse(is.numeric(x[xindex]),signif(x[xindex],nsignif),
x[xindex]),delim,sep="",file=con)
}
cat(eor,eor,file=con)
}
else {
options(show.error.messages = FALSE)
xchar<-try(as.character(x))
options(show.error.messages = TRUE)
cat(xchar,eor,file=con)
}
}
}
else {
cat(label,"\n",tabegin,"\n",sep="",file=con)
if(show.rownames) row.names<-rownames(x)
else row.names<-NULL
col.names<-names(x)
if(is.null(col.names)) col.names<-colnames(x)
if(!is.null(col.names)) {
if(show.rownames && !is.null(row.names)) {
if(leading.delim) cat(delim,file=con)
cat(col.names,sep=delim,file=con)
}
cat(eor,file=con)
}
for(row in 1:xdim[1]) {
if(nzchar(bor)) cat(bor,file=con)
if(show.rownames && !is.null(row.names)) {
if(leading.delim) cat(delim,file=con)
cat(row.names[row],file=con)
}
nxp<-ifelse(is.na(xdim[2]),length(x),xdim[2])
for(col in 1:nxp) {
nextx<-ifelse(is.na(xdim),x[col],x[row,col])
cat(delim,ifelse(is.numeric(nextx),signif(nextx,nsignif),nextx),
sep="",file=con)
}
cat("\n",file=con)
}
cat(eor, file = con)
}
cat(tablend,ifelse(html,"",eor),file=con)
}
if(open.con) {
if(!is.null(trailer)) cat(trailer,"\n",file=con)
close(con)
}
} |
rm(list = ls())
data(spc)
Tformula <- WAGE83 | WAGE81 ~ UN83 + NMR83 + SMSA | UN80 + NMR80 + SMSA
spcsur.sim <-spsurml(formula = Tformula, data = spc, type = "sim")
spcsur.slm <-spsurml(formula = Tformula, data = spc, type = "slm",
listw = Wspc)
anova(spcsur.sim, spcsur.slm)
print(spcsur.slm)
plot(spcsur.slm)
if (require(gridExtra)) {
pl <- plot(spcsur.slm, viewplot = FALSE)
grid.arrange(pl$lplbetas[[1]], pl$lplbetas[[2]],
pl$pldeltas, nrow = 3) } |
context("Getting Senate nominate scores")
library(politicaldata)
test_that("get_senate_nominate() outputs non-empty dataset", {
expect_is(get_senate_nominate(116),class = "data.frame")
}) |
renderDga <- function() {
tabPanel(
"Bayesian Model Averaging",
sidebarLayout(
sidebarPanel(
h4("Prior Model Complexity"),
numericInput("dgaPriorDelta",
"Delta",
1,
min = 0,
max = 1000000),
hr(),
h4("Prior Population Size"),
numericInput(
"dgaNMax",
"Maximum Population Size",
100000,
min = 0,
max = 1000000
),
radioButtons(
"dgaPriorType",
"
Prior Distribution",
choices = c("Non-informative" = "noninf",
"Log-normal" = "lnorm"),
selected = "noninf"
),
conditionalPanel(
"input.dgaPriorType == \"lnorm\"",
numericInput(
"dgaPriorMedian",
"Prior: Median",
7000,
min = 0,
max = 1000000
),
numericInput(
"dgaPrior90",
"Prior: 90% Upper Bound",
10000,
min = 0,
max = 1000000
)
),
hr(),
checkboxInput(
"dgaSaturated",
"Include Saturated Model",
FALSE
)
),
mainPanel(
tabsetPanel(
tabPanel(
"Prior",
h3("Distribution"),
withSpinner(plotOutput("dgaPrior")),
h3("Cumulative Distribution"),
withSpinner(plotOutput("dgaCumPrior"))
),
tabPanel(
"Posterior Population Size",
textOutput("dgaSaturatedWarning"),
tags$head(
tags$style("
font-size: 20px;
font-style: italic;}"
)
),
br(),
h3("Posterior Summaries"),
withSpinner(tableOutput("dgaTable")),
br(),
h3("Posterior Distribution"),
withSpinner(plotOutput("dgaPlot"))
),
tabPanel(
"Posterior Model Probabilities",
withSpinner(tableOutput("dgaModelPost"))
)
)
)
)
)
} |
context("maxControlsCap function old")
test_that("maxControlsCap", {
data(nuclearplants)
mhd2a <- match_on(pr ~ date + cum.n, data = nuclearplants,
within = exactMatch(pr ~ pt, data = nuclearplants))
mhd2a <- t(mhd2a)
mhd2a.caliper <- mhd2a + caliper(mhd2a, 3)
s1 <- stratumStructure(fullmatch(mhd2a.caliper, data=nuclearplants))
expect_equal(names(s1), c("5:1", "4:1", "2:1", "1:1", "1:2"))
expect_equal(as.vector(s1), c(1,2,3,2,1))
expect_equal(attr(s1, "comparable.num.matched.pairs"), 12.2)
mx1 <- maxControlsCap(mhd2a.caliper)
expect_true(all.equal(unlist(mx1),c(0, 0, .5, 1), check.attributes=FALSE))
s2 <- stratumStructure(fullmatch(mhd2a.caliper, max=1, data=nuclearplants))
expect_warning(s3 <- stratumStructure(fullmatch(mhd2a.caliper, max=1/2, data=nuclearplants)))
s4 <- stratumStructure(fullmatch(mhd2a + caliper(mhd2a, 2), data=nuclearplants))
expect_equal(names(s2), c("5:1", "4:1", "2:1", "1:1"))
expect_equal(as.vector(s2), c(1,2,2,5))
expect_equal(attr(s2, "comparable.num.matched.pairs"), 12.53333333)
expect_equal(names(s3), c("1:0", "4:1", "3:1", "2:1", "0:1"))
expect_equal(as.vector(s3), c(3, 2, 1, 4, 3))
expect_equal(attr(s3, "comparable.num.matched.pairs"), 10.03333333)
expect_equal(names(s4), c("5:1", "4:1", "2:1", "1:1", "1:2"))
expect_equal(as.vector(s4), c(1,2,3,2,1))
expect_equal(attr(s4, "comparable.num.matched.pairs"), 12.2)
mx2 <- maxControlsCap(mhd2a + caliper(mhd2a, 2))
expect_true(all.equal(unlist(mx2),c(0, 0, .5, 1), check.attributes=FALSE))
s5 <- stratumStructure(fullmatch(mhd2a + caliper(mhd2a, 2), max=mx2$strictest, data=nuclearplants))
expect_warning(s6 <- stratumStructure(fullmatch(mhd2a + caliper(mhd2a, 2), max=1/2, data=nuclearplants)))
expect_equal(names(s5), c("4:1", "3:1", "2:1", "1:1"))
expect_equal(as.vector(s5), c(2,1,4,3))
expect_equal(attr(s5, "comparable.num.matched.pairs"), 13.03333333)
expect_equal(names(s6), c("1:0", "4:1", "3:1", "2:1", "0:1"))
expect_equal(as.vector(s6), c(3,2,1,4,3))
expect_equal(attr(s6, "comparable.num.matched.pairs"), 10.03333333)
}) |
Licor_QC <- function(dat, curve = c("ACi", "AQ"), tol = 0.05) {
if (!("QC" %in% names(dat))) {
dat$QC <- rep(0, nrow(dat))
}
pos <- c(0.1, 0.9)
status <- c("red", "black", "blue", "grey")
if ("aci" %in% tolower(curve)) {
ref <- estimate_mode(dat$PARi)
if (ref < 1) {
return(NULL)
}
sel <- which(abs(dat$PARi - ref) / ref < tol)
ulhc <- c(sum(rev(pos) * range(dat$Ci[sel], na.rm = TRUE)),
sum(pos * range(dat$Photo[sel], na.rm = TRUE)))
plot(dat$Ci[sel], dat$Photo[sel],
col = status[dat$QC[sel] + 2],
pch = 20, cex = 2,
main = paste("CLICK ON OUTLIERS\n", dat$fname[1]))
points(dat$Ci[-sel], dat$Photo[-sel], col = status[4], pch = 20, cex = 2)
text(ulhc[1], ulhc[2], "FAIL\nALL", col = "red")
legend("bottomright", legend = c("fail", "unchecked", "pass", "other"),
col = status, pch = 18, cex = 1.5, bty = "n")
flag <- identify(c(dat$Ci[sel], ulhc[1]), c(dat$Photo[sel], ulhc[2]))
if (length(flag) > 0) {
if (max(flag) > length(sel)) {
dat$QC[sel] <- -1
} else {
dat$QC[sel[flag]] <- -1
}
}
dat$QC[sel[dat$QC[sel] == 0]] <- 1
plot(dat$Ci[sel], dat$Photo[sel],
col = status[dat$QC[sel] + 2],
pch = 20, cex = 2,
main = paste("UPDATED", dat$fname[1], "\nclick to undo Outliers"))
points(dat$Ci[-sel], dat$Photo[-sel], col = status[4], pch = 20, cex = 2)
legend("bottomright", legend = c("fail", "unchecked", "pass"),
col = status, pch = 18, cex = 1.5, bty = "n")
flag <- identify(dat$Ci[sel], dat$Photo[sel])
if (length(flag) > 0) {
dat$QC[sel[flag]] <- 1
}
}
if ("aq" %in% tolower(curve)) {
ref <- estimate_mode(dat$CO2R)
if (ref < 1) {
return(NULL)
}
sel <- which(abs(dat$CO2R - ref)/ref < tol)
ulhc <- c(sum(rev(pos) * range(dat$PARi[sel], na.rm = TRUE)),
sum(pos * range(dat$Photo[sel], na.rm = TRUE)))
plot(dat$PARi[sel], dat$Photo[sel],
col = status[dat$QC[sel] + 2],
pch = 20, cex = 2,
main = paste("CLICK ON OUTLIERS\n", dat$fname[1]))
points(dat$PARi[-sel], dat$Photo[-sel], col = status[4], pch = 20, cex = 2)
text(ulhc[1], ulhc[2], "FAIL\nALL", col = "red")
legend("bottomright", legend = c("fail", "unchecked", "pass", "other"),
col = status, pch = 18, cex = 1.5, bty = "n")
flag <- identify(c(dat$PARi[sel], ulhc[1]), c(dat$Photo[sel], ulhc[2]))
if (length(flag) > 0) {
if (max(flag) > length(sel)) {
dat$QC[sel] <- -1
} else {
dat$QC[sel[flag]] <- -1
}
}
dat$QC[sel[dat$QC[sel] == 0]] <- 1
plot(dat$PARi[sel], dat$Photo[sel],
col = status[dat$QC[sel] + 2],
pch = 20, cex = 2,
main = paste("UPDATED", dat$fname[1], "\nclick to undo Outliers"))
points(dat$PARi[-sel], dat$Photo[-sel], col = status[4], pch = 20, cex = 2)
legend("bottomright", legend = c("fail", "unchecked", "pass"),
col = status, pch = 18, cex = 1.5, bty = "n")
flag <- identify(dat$PARi[sel], dat$Photo[sel])
if (length(flag) > 0) {
dat$QC[sel[flag]] <- 1
}
}
return(invisible(dat))
}
estimate_mode <- function(x, adjust = 0.1) {
d <- density(x, na.rm = TRUE, adjust = adjust)
return(d$x[which.max(d$y)])
} |
stopifnot(require(RHive, quietly=TRUE))
stopifnot(require(RUnit, quietly=TRUE))
test.rhive.hdfs <- function()
{
data(emp)
localData = file.path(getwd(),"emp.csv")
write.csv2(emp,localData)
checkTrue(rhive.save(emp,file="/rhive/unittest/emp.RData"))
listdata <- rhive.hdfs.ls("/rhive/unittest")
loc <- (listdata['file'] == "/rhive/unittest/emp.RData")
checkTrue(length(listdata['file'][loc]) == 1)
rhive.load("/rhive/unittest/emp.RData")
rhive.hdfs.put(localData,"/rhive/unittest/emp.csv")
listdata <- rhive.hdfs.ls("/rhive/unittest")
loc <- (listdata['file'] == "/rhive/unittest/emp.csv")
checkTrue(length(listdata['file'][loc]) == 1)
rhive.hdfs.rename("/rhive/unittest/emp.csv","/rhive/unittest/emp1.csv")
listdata <- rhive.hdfs.ls("/rhive/unittest")
loc <- (listdata['file'] == "/rhive/unittest/emp1.csv")
checkTrue(length(listdata['file'][loc]) == 1)
rhive.hdfs.chmod("666","/rhive/unittest/emp1.csv")
listdata <- rhive.hdfs.ls("/rhive/unittest/emp1.csv")
checkTrue(listdata[['permission']][1] == "rw-rw-rw-")
rhive.hdfs.chown("rhive","/rhive/unittest/emp1.csv")
listdata <- rhive.hdfs.ls("/rhive/unittest/emp1.csv")
checkTrue(listdata[['owner']][1] == "rhive")
rhive.hdfs.chgrp("grhive","/rhive/unittest/emp1.csv")
listdata <- rhive.hdfs.ls("/rhive/unittest/emp1.csv")
checkTrue(listdata[['group']][1] == "grhive")
rhive.hdfs.rm("/rhive/unittest/emp1.csv")
listdata <- rhive.hdfs.ls("/rhive/unittest")
loc <- (listdata['file'] == "/rhive/unittest/emp1.csv")
checkTrue(length(listdata['file'][loc]) == 0)
rhive.hdfs.rm("/rhive/unittest/emp.RData")
queryResult <- rhive.hdfs.du("/rhive")
checkTrue(!is.null(queryResult))
totalsize <- rhive.hdfs.du("/rhive",summary=TRUE)
checkTrue(length(totalsize['file']) == 1)
} |
interpolate <- function() {
flux <- NULL
k <- NULL
C0 <- NULL
initial <- function(t = 1, pars = NULL) {
flux <<- approxfun(pars$flux_t, pars$flux_y)
k <<- pars$k
C0 <<- mean(flux(1:365)) / k
C0
}
derivs <- function(t, y, .) {
flux_t <- flux(t)
list(flux_t - k * y)
}
list(derivs = derivs, initial = initial, t = c(1, 365))
} |
if(interactive()){
data(mstData)
outputSRT <- srtFREQ(Posttest~ Intervention + Prettest,
intervention = "Intervention", data = mstData)
outputSRTBoot <- srtFREQ(Posttest~ Intervention + Prettest,
intervention = "Intervention",nBoot=1000, data = mstData)
outputMST <- mstFREQ(Posttest~ Intervention + Prettest,
random = "School", intervention = "Intervention", data = mstData)
outputMSTBoot <- mstFREQ(Posttest~ Intervention + Prettest,
random = "School", intervention = "Intervention",
nBoot = 1000, data = mstData)
outputSRTbayes <- srtBayes(Posttest~ Intervention + Prettest,
intervention = "Intervention",
nsim = 2000, data = mstData)
ComparePlot(list(outputSRT,outputSRTBoot,outputMST,outputMSTBoot,outputSRTbayes),
modelNames =c("ols", "olsBoot","MLM","MLMBoot","OLSBayes"),group=1)
} |
graphdf(tinyPatchMPG)
mean(igraph::V(tinyPatchMPG@mpg)$patchArea)
if (interactive())
plot(tinyPatchMPG, col = c("grey", "black"), legend = FALSE)
tinyLatticeMPG <- MPG(cost = tinyCost, patch = 10)
if (interactive())
plot(tinyLatticeMPG) |
summarySubcascades <- function(subcascades=NULL)
{
if(is.null(subcascades))
return(NULL)
if(!inherits(subcascades, 'Subcascades'))
stop(errorStrings('subcascades'))
subcascades <- subcascades[sapply(subcascades, function(x){!is.null(x)})]
if(length(subcascades)==0)
{
return(NULL)
}
overview <- sapply(subcascades, function(casc){c(nrow(casc), min(casc))})
if(!is.matrix(overview))
{
overview <- matrix(overview, nrow = 1)
}else{
overview <- t(overview)
}
colnames(overview) <- c('number', 'min.class.sens')
rownames(overview) <- names(subcascades)
return(overview)
} |
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL |
add_ppmf12_path <- function(path, overwrite = FALSE, install = FALSE) {
if (missing(path)) {
stop('Input `path` cannot be missing.')
}
if (install) {
r_env <- file.path(Sys.getenv('HOME'), '.Renviron')
if (!file.exists(r_env)) {
file.create(r_env)
}
lines <- readLines(r_env)
newline <- paste0("ppmf12='", path.expand(path), "'")
exists <- stringr::str_detect(lines, 'ppmf12=')
if (any(exists)) {
if (sum(exists) > 1) {
stop('Multiple entries in .Renviron have name matching input `name`.\nEdit manually with `usethis::edit_r_environ()`.')
}
if (overwrite) {
lines[exists] <- newline
writeLines(lines, r_env)
message('Run `readRenviron("~/.Renviron")` to update your active environment.')
} else {
message('ppmf12 already exists in .Renviron. \nEdit manually with `usethis::edit_r_environ() or set `overwrite = TRUE`.')
}
} else {
lines[length(lines) + 1] <- newline
writeLines(lines, r_env)
message('Run `readRenviron("~/.Renviron")` to update your active environment.')
}
} else {
Sys.setenv(ppmf12 = path)
}
invisible(path)
}
add_ppmf4_path <- function(path, overwrite = FALSE, install = FALSE) {
if (missing(path)) {
stop('Input `path` cannot be missing.')
}
if (install) {
r_env <- file.path(Sys.getenv('HOME'), '.Renviron')
if (!file.exists(r_env)) {
file.create(r_env)
}
lines <- readLines(r_env)
newline <- paste0("ppmf4='", path.expand(path), "'")
exists <- stringr::str_detect(lines, 'ppmf4=')
if (any(exists)) {
if (sum(exists) > 1) {
stop('Multiple entries in .Renviron have name matching input `name`.\nEdit manually with `usethis::edit_r_environ()`.')
}
if (overwrite) {
lines[exists] <- newline
writeLines(lines, r_env)
message('Run `readRenviron("~/.Renviron")` to update your active environment.')
} else {
message('ppmf4 already exists in .Renviron. \nEdit manually with `usethis::edit_r_environ() or set `overwrite = TRUE`.')
}
} else {
lines[length(lines) + 1] <- newline
writeLines(lines, r_env)
message('Run `readRenviron("~/.Renviron")` to update your active environment.')
}
} else {
Sys.setenv(ppmf4 = path)
}
invisible(path)
}
add_ppmf19_path <- function(path, overwrite = FALSE, install = FALSE) {
if (missing(path)) {
stop('Input `path` cannot be missing.')
}
if (install) {
r_env <- file.path(Sys.getenv('HOME'), '.Renviron')
if (!file.exists(r_env)) {
file.create(r_env)
}
lines <- readLines(r_env)
newline <- paste0("ppmf19='", path.expand(path), "'")
exists <- stringr::str_detect(lines, 'ppmf19=')
if (any(exists)) {
if (sum(exists) > 1) {
stop('Multiple entries in .Renviron have name matching input `name`.\nEdit manually with `usethis::edit_r_environ()`.')
}
if (overwrite) {
lines[exists] <- newline
writeLines(lines, r_env)
message('Run `readRenviron("~/.Renviron")` to update your active environment.')
} else {
message('ppmf19 already exists in .Renviron. \nEdit manually with `usethis::edit_r_environ() or set `overwrite = TRUE`.')
}
} else {
lines[length(lines) + 1] <- newline
writeLines(lines, r_env)
message('Run `readRenviron("~/.Renviron")` to update your active environment.')
}
} else {
Sys.setenv(ppmf19 = path)
}
invisible(path)
} |
print.robotstxt_text <- function(x, ...){
cat("[robots.txt]\n--------------------------------------\n\n")
tmp <- unlist(strsplit(x, "\n"))
cat(tmp[seq_len(min(length(tmp), 50))], sep ="\n")
cat("\n\n\n")
if(length(tmp) > 50){
cat("[...]\n\n")
}
problems <- attr(x, "problems")
if ( length(problems) > 0){
cat("[events]\n--------------------------------------\n\n")
cat("requested: ", attr(x, "request")$request$url, "\n")
cat("downloaded: ", attr(x, "request")$url, "\n\n")
cat(utils::capture.output(print(problems)), sep="\n")
cat("[attributes]\n--------------------------------------\n\n")
cat(names(attributes(x)), sep=", ")
}
cat("\n")
invisible(x)
} |
nestselect = function(aics, mod1, mod2, dfdiff, pval = .05){
if(is.na(aics[mod1])){
loser = mod1
} else if(isTRUE(aics[mod2] <= aics[mod1])){
chisq = aics[mod1] - aics[mod2] + 2*dfdiff
ptest = 1-pchisq(chisq, dfdiff)
if(ptest < pval) loser = mod1 else loser = mod2
} else loser = mod2
return(aics[names(aics) != loser])
} |
tam_colSums <- function(x)
{
use_sum <- FALSE
if (is.vector(x)){
use_sum <- TRUE
}
if (is.matrix(x)){
if (ncol(x)==1){
use_sum <- TRUE
}
}
if (use_sum){
res <- sum(x)
} else {
res <- colSums(x)
}
return(res)
} |
confusionMatrix <-
function(data, ...){
UseMethod("confusionMatrix")
}
confusionMatrix.default <- function(data, reference,
positive = NULL,
dnn = c("Prediction", "Reference"),
prevalence = NULL,
mode = "sens_spec",
...) {
if(!(mode %in% c("sens_spec", "prec_recall", "everything")))
stop("`mode` should be either 'sens_spec', 'prec_recall', or 'everything'")
if(!is.factor(data) | !is.factor(reference)) {
stop("`data` and `reference` should be factors with the same levels.", call. = FALSE)
}
if(!is.character(positive) & !is.null(positive)) stop("positive argument must be character")
if(length(levels(data)) > length(levels(reference)))
stop("the data cannot have more levels than the reference")
if(!any(levels(data) %in% levels(reference))){
stop("The data must contain some levels that overlap the reference.")
}
if(!all(levels(data) %in% levels(reference))){
badLevel <- levels(data)[!levels(data) %in% levels(reference)]
if(sum(table(data)[badLevel]) > 0){
stop("The data contain levels not found in the data.")
} else{
warning("The data contains levels not found in the data, but they are empty and will be dropped.")
data <- factor(as.character(data))
}
}
if(any(levels(reference) != levels(data))) {
warning("Levels are not in the same order for reference and data. Refactoring data to match.")
data <- as.character(data)
data <- factor(data, levels = levels(reference))
}
classLevels <- levels(data)
numLevels <- length(classLevels)
if(numLevels < 2)
stop("there must be at least 2 factors levels in the data")
if(numLevels == 2 & is.null(positive)) positive <- levels(reference)[1]
classTable <- table(data, reference, dnn = dnn, ...)
getFromNamespace("confusionMatrix.table", "caret")(classTable, positive, prevalence = prevalence, mode = mode)
}
confusionMatrix.matrix <- function(data,
positive = NULL,
prevalence = NULL,
mode = "sens_spec",
...) {
if (length(unique(dim(data))) != 1) {
stop("matrix must have equal dimensions")
}
classTable <- as.table(data, ...)
confusionMatrix(classTable, positive, prevalence = prevalence, mode = mode)
}
confusionMatrix.table <- function(data, positive = NULL,
prevalence = NULL, mode = "sens_spec", ...){
if(!(mode %in% c("sens_spec", "prec_recall", "everything")))
stop("`mode` should be either 'sens_spec', 'prec_recall', or 'everything'")
if(length(dim(data)) != 2) stop("the table must have two dimensions")
if(!all.equal(nrow(data), ncol(data))) stop("the table must nrow = ncol")
if(!isTRUE(all.equal(rownames(data), colnames(data)))) stop("the table must the same classes in the same order")
if(!is.character(positive) & !is.null(positive)) stop("positive argument must be character")
classLevels <- rownames(data)
numLevels <- length(classLevels)
if(numLevels < 2)
stop("there must be at least 2 factors levels in the data")
if(numLevels == 2 & is.null(positive)) positive <- rownames(data)[1]
if(numLevels == 2 & !is.null(prevalence) && length(prevalence) != 1)
stop("with two levels, one prevalence probability must be specified")
if(numLevels > 2 & !is.null(prevalence) && length(prevalence) != numLevels)
stop("the number of prevalence probability must be the same as the number of levels")
if(numLevels > 2 & !is.null(prevalence) && is.null(names(prevalence)))
stop("with >2 classes, the prevalence vector must have names")
propCI <- function(x) {
res <- try(binom.test(sum(diag(x)), sum(x))$conf.int, silent = TRUE)
if(inherits(res, "try-error"))
res <- rep(NA, 2)
res
}
propTest <- function(x){
res <- try(
binom.test(sum(diag(x)),
sum(x),
p = max(apply(x, 2, sum)/sum(x)),
alternative = "greater"),
silent = TRUE)
res <- if(inherits(res, "try-error"))
c("null.value.probability of success" = NA, p.value = NA)
else
res <- unlist(res[c("null.value", "p.value")])
res
}
overall <- c(unlist(e1071::classAgreement(data))[c("diag", "kappa")],
propCI(data),
propTest(data),
mcnemar.test(data)$p.value)
names(overall) <- c("Accuracy", "Kappa", "AccuracyLower", "AccuracyUpper", "AccuracyNull", "AccuracyPValue", "McnemarPValue")
if(numLevels == 2) {
if(is.null(prevalence)) prevalence <- sum(data[, positive])/sum(data)
negative <- classLevels[!(classLevels %in% positive)]
tableStats <- c(sensitivity.table(data, positive),
specificity.table(data, negative),
posPredValue.table(data, positive, prevalence = prevalence),
negPredValue.table(data, negative, prevalence = prevalence),
precision.table(data, relevant = positive),
recall.table(data, relevant = positive),
F_meas.table(data, relevant = positive),
prevalence,
sum(data[positive, positive])/sum(data),
sum(data[positive, ])/sum(data))
names(tableStats) <- c("Sensitivity", "Specificity",
"Pos Pred Value", "Neg Pred Value",
"Precision", "Recall", "F1",
"Prevalence", "Detection Rate",
"Detection Prevalence")
tableStats["Balanced Accuracy"] <- (tableStats["Sensitivity"]+tableStats["Specificity"])/2
} else {
tableStats <- matrix(NA, nrow = length(classLevels), ncol = 11)
for(i in seq(along = classLevels)) {
pos <- classLevels[i]
neg <- classLevels[!(classLevels %in% classLevels[i])]
prev <- if(is.null(prevalence)) sum(data[, pos])/sum(data) else prevalence[pos]
tableStats[i,] <- c(sensitivity.table(data, pos),
specificity.table(data, neg),
posPredValue.table(data, pos, prevalence = prev),
negPredValue.table(data, neg, prevalence = prev),
precision.table(data, relevant = pos),
recall.table(data, relevant = pos),
F_meas.table(data, relevant = pos),
prev,
sum(data[pos, pos])/sum(data),
sum(data[pos, ])/sum(data), NA)
tableStats[i,11] <- (tableStats[i,1] + tableStats[i,2])/2
}
rownames(tableStats) <- paste("Class:", classLevels)
colnames(tableStats) <- c("Sensitivity", "Specificity",
"Pos Pred Value", "Neg Pred Value",
"Precision", "Recall", "F1",
"Prevalence", "Detection Rate",
"Detection Prevalence", "Balanced Accuracy")
}
structure(
list(positive = positive,
table = data,
overall = overall,
byClass = tableStats,
mode = mode,
dots = list(...)),
class = "confusionMatrix")
}
as.matrix.confusionMatrix <- function(x, what = "xtabs", ...){
if(!(what %in% c("xtabs", "overall", "classes")))
stop("what must be either xtabs, overall or classes")
out <- switch(what,
xtabs = matrix(as.vector(x$table),
nrow = length(colnames(x$table)),
dimnames = list(rownames(x$table), colnames(x$table))),
overall = as.matrix(x$overall),
classes = as.matrix(x$byClass))
if(what == "classes"){
if(length(colnames(x$table)) > 2){
out <- t(out)
colnames(out) <- gsub("Class: ", "", colnames(out), fixed = TRUE)
}
}
out
}
sbf_resampledCM <- function(x) {
lev <- x$obsLevels
if("pred" %in% names(x) && !is.null(x$pred)) {
resampledCM <- do.call("rbind", x$pred[names(x$pred) == "predictions"])
resampledCM <- ddply(resampledCM, .(Resample), function(y) flatTable(pred = y$pred, obs = y$obs))
} else stop(paste("When there are 50+ classes, the function does not automatically pre-compute the",
"resampled confusion matrices. You can get them when the option",
"`saveDetails = TRUE`."))
resampledCM
}
rfe_resampledCM <- function(x) {
lev <- x$obsLevels
if("resample" %in% names(x) &&
!is.null(x$resample) &&
sum(grepl("\\.cell[1-9]", names(x$resample))) > 3) {
resampledCM <- subset(x$resample, Variables == x$optsize)
resampledCM <- resampledCM[,grepl("\\.cell[1-9]", names(resampledCM))]
} else {
if(!is.null(x$pred)) {
resampledCM <- ddply(x$pred, .(Resample), function(y) flatTable(pred = y$pred, obs = y$obs))
} else {
if(length(lev) > 50)
stop(paste("When there are 50+ classes, `the function does not automatically pre-compute the",
"resampled confusion matrices. You can get them when the object",
"has a `pred` element."))
}
}
resampledCM
}
train_resampledCM <- function(x) {
if(x$modelType == "Regression")
stop("confusion matrices are only valid for classification models")
lev <- levels(x)
if("resampledCM" %in% names(x) && !is.null(x$resampledCM)) {
names(x$bestTune) <- gsub("^\\.", "", names(x$bestTune))
resampledCM <- merge(x$bestTune, x$resampledCM)
} else {
if(!is.null(x$pred)) {
resampledCM <- ddply(merge(x$pred, x$bestTune), .(Resample), function(y) flatTable(pred = y$pred, obs = y$obs))
} else {
if(length(lev) > 50)
stop(paste("When there are 50+ classes, `train` does not automatically pre-compute the",
"resampled confusion matrices. You can get them from this function",
"using a value of `savePredictions` other than FALSE."))
}
}
resampledCM
}
as.table.confusionMatrix <- function(x, ...) x$table
confusionMatrix.train <- function(data, norm = "overall", dnn = c("Prediction", "Reference"), ...){
if(data$control$method %in% c("oob", "LOOCV", "none"))
stop("cannot compute confusion matrices for leave-one-out, out-of-bag resampling, or no resampling")
if (inherits(data, "train")) {
if(data$modelType == "Regression")
stop("confusion matrices are only valid for classification models")
lev <- levels(data)
resampledCM <- train_resampledCM(data)
} else {
lev <- data$obsLevels
if (inherits(data, "rfe")) resampledCM <- rfe_resampledCM(data)
if (inherits(data, "sbf")) resampledCM <- sbf_resampledCM(data)
}
if(!is.null(data$control$index)) {
resampleN <- unlist(lapply(data$control$index, length))
numResamp <- length(resampleN)
resampText <- resampName(data)
} else {
resampText <- ""
numResamp <- 0
}
counts <- as.matrix(resampledCM[ , grep("^\\.?cell", colnames(resampledCM))])
norm <- match.arg(norm, c("none", "overall", "average"))
if(norm == "none") counts <- matrix(apply(counts, 2, sum), nrow = length(lev))
else counts <- matrix(apply(counts, 2, mean), nrow = length(lev))
if(norm == "overall") counts <- counts / sum(counts) * 100
rownames(counts) <- colnames(counts) <- lev
names(dimnames(counts)) <- dnn
out <- list(table = as.table(counts),
norm = norm,
B = length(data$control$index),
text = paste(resampText, "Confusion Matrix"))
class(out) <- paste0("confusionMatrix.", class(data))
out
}
confusionMatrix.rfe <- confusionMatrix.train
confusionMatrix.sbf <- confusionMatrix.train
print.confusionMatrix.train <- function(x, digits = 1, ...){
cat(x$text, "\n")
normText <- switch(x$norm,
none = "\n(entries are un-normalized aggregated counts)\n",
average = "\n(entries are average cell counts across resamples)\n",
overall = "\n(entries are percentual average cell counts across resamples)\n",
"")
cat(normText, "\n")
if(x$norm == "none" & x$B == 1) {
print(getFromNamespace("confusionMatrix.table", "caret")(x$table))
} else {
print(round(x$table, digits))
out <- cbind("Accuracy (average)", ":", formatC(sum(diag(x$table) / sum(x$table))))
dimnames(out) <- list(rep("", nrow(out)), rep("", ncol(out)))
print(out, quote = FALSE)
cat("\n")
}
invisible(x)
}
print.confusionMatrix.rfe <- print.confusionMatrix.train
print.confusionMatrix.sbf <- print.confusionMatrix.train
resampName <- function(x, numbers = TRUE){
if(!("control" %in% names(x))) return("")
if(numbers) {
resampleN <- unlist(lapply(x$control$index, length))
numResamp <- length(resampleN)
out <- switch(tolower(x$control$method),
none = "None",
apparent = "Apparent",
custom = paste("Custom Resampling (", numResamp, " reps)", sep = ""),
timeslice = paste("Rolling Forecasting Origin Resampling (",
x$control$horizon, " held-out with",
ifelse(x$control$fixedWindow, " a ", " no "),
"fixed window)", sep = ""),
oob = "Out of Bag Resampling",
boot =, optimism_boot =, boot_all =,
boot632 = paste("Bootstrapped (", numResamp, " reps)", sep = ""),
cv = paste("Cross-Validated (", x$control$number, " fold)", sep = ""),
repeatedcv = paste("Cross-Validated (", x$control$number, " fold, repeated ",
x$control$repeats, " times)", sep = ""),
lgocv = paste("Repeated Train/Test Splits Estimated (", numResamp, " reps, ",
round(x$control$p*100, 1), "%)", sep = ""),
loocv = "Leave-One-Out Cross-Validation",
adaptive_boot = paste("Adaptively Bootstrapped (", numResamp, " reps)", sep = ""),
adaptive_cv = paste("Adaptively Cross-Validated (", x$control$number, " fold, repeated ",
x$control$repeats, " times)", sep = ""),
adaptive_lgocv = paste("Adaptive Repeated Train/Test Splits Estimated (", numResamp, " reps, ",
round(x$control$p, 2), "%)", sep = "")
)
} else {
out <- switch(tolower(x$control$method),
none = "None",
apparent = "(Apparent)",
custom = "Custom Resampling",
timeslice = "Rolling Forecasting Origin Resampling",
oob = "Out of Bag Resampling",
boot = "(Bootstrap)",
optimism_boot = "(Optimism Bootstrap)",
boot_all = "(Bootstrap All)",
boot632 = "(Bootstrap 632 Rule)",
cv = "(Cross-Validation)",
repeatedcv = "(Repeated Cross-Validation)",
loocv = "Leave-One-Out Cross-Validation",
lgocv = "(Repeated Train/Test Splits)")
}
out
}
print.confusionMatrix <- function(x, mode = x$mode, digits = max(3, getOption("digits") - 3), printStats = TRUE, ...){
if(is.null(mode)) mode <- "sens_spec"
if(!(mode %in% c("sens_spec", "prec_recall", "everything")))
stop("`mode` should be either 'sens_spec', 'prec_recall', or 'everything'")
cat("Confusion Matrix and Statistics\n\n")
print(x$table, ...)
if(printStats) {
tmp <- round(x$overall, digits = digits)
pIndex <- grep("PValue", names(x$overall))
tmp[pIndex] <- format.pval(x$overall[pIndex], digits = digits)
overall <- tmp
accCI <- paste("(",
paste(
overall[ c("AccuracyLower", "AccuracyUpper")],
collapse = ", "),
")",
sep = "")
overallText <- c(paste(overall["Accuracy"]),
accCI,
paste(overall[c("AccuracyNull", "AccuracyPValue")]),
"",
paste(overall["Kappa"]),
"",
paste(overall["McnemarPValue"]))
overallNames <- c("Accuracy", "95% CI",
"No Information Rate",
"P-Value [Acc > NIR]",
"",
"Kappa",
"",
"Mcnemar's Test P-Value")
if(dim(x$table)[1] > 2){
cat("\nOverall Statistics\n")
overallNames <- ifelse(overallNames == "",
"",
paste(overallNames, ":"))
out <- cbind(format(overallNames, justify = "right"), overallText)
colnames(out) <- rep("", ncol(out))
rownames(out) <- rep("", nrow(out))
print(out, quote = FALSE)
cat("\nStatistics by Class:\n\n")
if(mode == "prec_recall")
x$byClass <- x$byClass[,!grepl("(Sensitivity)|(Specificity)|(Pos Pred Value)|(Neg Pred Value)",
colnames(x$byClass))]
if(mode == "sens_spec")
x$byClass <- x$byClass[,!grepl("(Precision)|(Recall)|(F1)", colnames(x$byClass))]
print(t(x$byClass), digits = digits)
} else {
if(mode == "prec_recall")
x$byClass <- x$byClass[!grepl("(Sensitivity)|(Specificity)|(Pos Pred Value)|(Neg Pred Value)",
names(x$byClass))]
if(mode == "sens_spec")
x$byClass <- x$byClass[!grepl("(Precision)|(Recall)|(F1)", names(x$byClass))]
overallText <- c(overallText,
"",
format(x$byClass, digits = digits))
overallNames <- c(overallNames, "", names(x$byClass))
overallNames <- ifelse(overallNames == "", "", paste(overallNames, ":"))
overallNames <- c(overallNames, "", "'Positive' Class :")
overallText <- c(overallText, "", x$positive)
out <- cbind(format(overallNames, justify = "right"), overallText)
colnames(out) <- rep("", ncol(out))
rownames(out) <- rep("", nrow(out))
out <- rbind(out, rep("", 2))
print(out, quote = FALSE)
}
}
invisible(x)
} |
compute.threshold.FPF.pooledROC.emp <-
function(object, FPF = 0.5, ci.level = 0.95, parallel = c("no", "multicore", "snow"), ncpus = 1, cl = NULL) {
if(class(object)[1] != "pooledROC.emp") {
stop(paste0("This function can not be used for this object class: ", class(object)[1]))
}
F1emp <- ecdf(object$marker$d[!object$missing.ind$d])
thresholds <- quantile(object$marker$h[!object$missing.ind$h], 1 - FPF, type = 1)
TPF <- 1 - F1emp(thresholds)
res <- list()
res$thresholds <- thresholds
res$FPF <- FPF
res$TPF <- TPF
res
} |
Quandl.search <- function(query, silent = FALSE, per_page = 10, ...) {
params <- list()
params$query <- query
params$per_page <- per_page
params <- c(params, list(...))
path <- "datasets"
json <- do.call(quandl.api, c(path=path, params))
results <- structure(json$datasets, meta = json$meta)
if (!is.null(nrow(results)) && nrow(results) > 0) {
for (i in 1:nrow(results)) {
name <- results[i,]$name
code <- paste(results[i,]$database_code, "/", results[i,]$dataset_code, sep="")
desc <- results[i,]$description
freq <- results[i,]$frequency
colname <- results[i,]$column_names
if (!silent) {
cat(name, "\nCode: ", code, "\nDesc: ", desc, "\nFreq: ", freq, "\nCols: ", paste(unlist(colname), collapse=" | "), "\n\n", sep="")
}
}
} else {
warning("No datasets found")
}
invisible(results)
} |
get.point.sampler.info <- function(shapefile, region.obj, meta = NULL){
ID <- X <- Y <- region <- NULL
ID <- shapefile$shp$shp[,'record']
X <- shapefile$shp$shp[,'x']
Y <- shapefile$shp$shp[,'y']
effort <- rep(1, length(ID))
if(length([email protected]) > 0){
if(!is.null(shapefile$dbf$dbf$Stratum)){
strata.ID <- shapefile$dbf$dbf$Stratum[ID]
strata.names <- [email protected][strata.ID]
}else if(!is.null(meta)){
for(i in seq(along = ID)){
if(length(meta[,1][meta[,2] == ID[i]]) > 0){
region[i] <- meta[,3][meta[,2] == ID[i]]
}
}
strata.names <- [email protected][as.numeric(region)]
}else{
point.coords <- data.frame(x = X, y = Y)
strata <- lapply(region.obj@coords, FUN = in.polygons, pts = point.coords, boundary = TRUE)
strata.id <- rep(NA, nrow(point.coords))
for(strat in seq(along = strata)){
strata.id <- ifelse(strata[[strat]], strat, strata.id)
}
if(length(which(is.na(strata.id))) > 0){
warning("Transect cannot be allocated to strata debug get.point.sampler.info (possible that a transect falls outwith study region)", call. = FALSE, immediate. = TRUE)
return(NULL)
}
strata.names <- [email protected][strata.id]
}
sampler.info <- data.frame(ID = ID, X = X, Y = Y, region = strata.names, effort = effort)
}else{
region <- rep([email protected], length(ID))
sampler.info <- data.frame(ID = ID, X = X, Y = Y, region = region, effort = effort)
}
return(sampler.info)
} |
library(checkargs)
context("isNumberOrNaOrNanOrInfVector")
test_that("isNumberOrNaOrNanOrInfVector works for all arguments", {
expect_identical(isNumberOrNaOrNanOrInfVector(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrNaOrNanOrInfVector(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrNaOrNanOrInfVector(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrNaOrNanOrInfVector(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrNaOrNanOrInfVector("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrNaOrNanOrInfVector(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_error(isNumberOrNaOrNanOrInfVector(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrNaOrNanOrInfVector(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrNaOrNanOrInfVector(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isNumberOrNaOrNanOrInfVector(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(0, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isNumberOrNaOrNanOrInfVector("", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrNaOrNanOrInfVector("X", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrNaOrNanOrInfVector(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrNaOrNanOrInfVector(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isNumberOrNaOrNanOrInfVector(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrNaOrNanOrInfVector(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isNumberOrNaOrNanOrInfVector(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrNaOrNanOrInfVector(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
}) |
default_exception_handler <- function(e){
ts <- format(Sys.time(), format = "%Y-%m-%d %H:%M:%OS3")
call <- paste(trimws(format(e$call)), collapse = " ")
logger <- format(e$logger$name)
if ("appender" %in% names(e)){
appender <- paste0(class_fmt(e$appender, ignore = c("Filterable", "R6", "Appender")))
message <- sprintf("[%s] %s %s ~ error in `%s`: %s", ts, logger, appender, call, e$message)
res <- AppenderWarning(message = message, error = e)
} else {
message <- sprintf("[%s] %s ~ error in `%s`: %s", ts, logger, call, e$message)
res <- LoggerWarning(message = message, error = e)
}
warning(res)
}
AppenderWarning <- function(message, class = NULL, call = NULL, ...){
LoggerWarning(
message = message,
class = union(class, "AppenderWarning"),
call = call,
...
)
}
LoggerWarning <- function(message, class = NULL, call = NULL, ...){
warning_condition(
message = message,
class = union(class, "LoggerWarning"),
call = call,
...
)
} |
context("Mortality")
for(test in testlist) {
samc_obj <- test$samc
Q <- samc_obj$q_matrix
Q <- as.matrix(Q)
R <- diag(nrow(Q))
diag(R) <- samc_obj@data@t_abs
R_list <- lapply(split(samc_obj@data@c_abs, col(samc_obj@data@c_abs)),
function(x){
mat <- diag(length(x))
diag(mat) <- x
return(mat)
})
R_list <- c(list(total = R), R_list)
I <- diag(nrow(Q))
F_mat <- solve(I - Q)
occ_ras <- raster::raster(test$occ)
pv <- as.vector(occ_ras)
pv <- pv[is.finite(pv)]
test_that("Testing mortality(samc, time)", {
samc_obj$override <- TRUE
result <- mortality(samc_obj, time = time)
samc_obj$override <- FALSE
base_result <- diag(nrow(Q))
Qt <- diag(nrow(Q))
for (i in 1:(time - 1)) {
Qt <- Qt %*% Q
base_result <- base_result + Qt
}
base_result <- base_result %*% R
expect_equal(dim(result), dim(base_result))
expect_equal(as.vector(result), as.vector(base_result))
})
test_that("Testing mortality(samc, origin, time)", {
result <- mortality(samc_obj, origin = row_vec[1], time = time)
result_char <- mortality(samc_obj, origin = as.character(row_vec[1]), time = time)
expect_equal(result, result_char)
base_result <- diag(nrow(Q))
Qt <- diag(nrow(Q))
for (i in 1:(time - 1)) {
Qt <- Qt %*% Q
base_result <- base_result + Qt
}
base_result <- base_result %*% R
expect_equal(as.vector(result), as.vector(base_result[row_vec[1], ]))
})
test_that("Testing mortality(samc, origin, time_vec)", {
result <- mortality(samc_obj, origin = row_vec[1], time = time_vec)
result_char <- mortality(samc_obj, origin = as.character(row_vec[1]), time = time_vec)
expect_equal(result, result_char)
for (i in 1:length(time_vec)) {
base_result <- diag(nrow(Q))
Qt <- diag(nrow(Q))
for (j in 1:(time_vec[i] - 1)) {
Qt <- Qt %*% Q
base_result <- base_result + Qt
}
base_result <- base_result %*% R
expect_equal(result[[i]], as.vector(base_result[row_vec[1], ]))
}
})
test_that("Testing mortality(samc, dest, time)", {
result <- mortality(samc_obj, dest = col_vec[1], time = time)
result_char <- mortality(samc_obj, dest = as.character(col_vec[1]), time = time)
expect_equal(result, result_char)
base_result <- diag(nrow(Q))
Qt <- diag(nrow(Q))
for (i in 1:(time - 1)) {
Qt <- Qt %*% Q
base_result <- base_result + Qt
}
base_result <- base_result %*% R
expect_equal(as.vector(result), as.vector(base_result[, col_vec[1]]))
})
test_that("Testing mortality(samc, dest, time_vec)", {
result <- mortality(samc_obj, dest = col_vec[1], time = time_vec)
result_char <- mortality(samc_obj, dest = as.character(col_vec[1]), time = time_vec)
expect_equal(result, result_char)
for (i in 1:length(time_vec)) {
base_result <- diag(nrow(Q))
Qt <- diag(nrow(Q))
for (j in 1:(time_vec[i] - 1)) {
Qt <- Qt %*% Q
base_result <- base_result + Qt
}
base_result <- base_result %*% R
expect_equal(result[[i]], as.vector(base_result[, col_vec[1]]))
}
})
test_that("Testing mortality(samc, origin, dest, time)", {
result <- mortality(samc_obj, origin = row_vec[1], dest = col_vec[1], time = time)
result_char <- mortality(samc_obj, origin = as.character(row_vec[1]), dest = as.character(col_vec[1]), time = time)
expect_equal(result, result_char)
base_result <- diag(nrow(Q))
Qt <- diag(nrow(Q))
for (i in 1:(time - 1)) {
Qt <- Qt %*% Q
base_result <- base_result + Qt
}
base_result <- base_result %*% R
expect_equal(as.vector(result), as.vector(base_result[row_vec[1], col_vec[1]]))
})
test_that("Testing mortality(samc, origin, dest, time_vec)", {
result <- mortality(samc_obj, origin = row_vec[1], dest = col_vec[1], time = time_vec)
result_char <- mortality(samc_obj, origin = as.character(row_vec[1]), dest = as.character(col_vec[1]), time = time_vec)
expect_equal(result, result_char)
for (i in 1:length(time_vec)) {
base_result <- diag(nrow(Q))
Qt <- diag(nrow(Q))
for (j in 1:(time_vec[i] - 1)) {
Qt <- Qt %*% Q
base_result <- base_result + Qt
}
base_result <- base_result %*% R
expect_equal(result[[i]], as.vector(base_result[row_vec[1], col_vec[1]]))
}
})
test_that("Testing mortality(samc, occ, time)", {
result <- mortality(samc_obj, occ = test$occ, time = time)
base_result <- I
Qt <- diag(nrow(Q))
for (i in 1:(time - 1)) {
Qt <- Qt %*% Q
base_result <- base_result + Qt
}
base_result <- pv %*% base_result %*% R
expect_equal(as.vector(result), as.vector(base_result))
})
test_that("Testing mortality(samc, occ, time_vec)", {
result <- mortality(samc_obj, occ = test$occ, time = time_vec)
for (i in 1:length(time_vec)) {
base_result <- I
Qt <- diag(nrow(Q))
for (j in 1:(time_vec[i] - 1)) {
Qt <- Qt %*% Q
base_result <- base_result + Qt
}
base_result <- pv %*% base_result %*% R
expect_equal(result[[i]], as.vector(base_result))
}
})
test_that("Testing mortality(samc)", {
samc_obj$override <- TRUE
result <- mortality(samc_obj)
samc_obj$override <- FALSE
expect_equal(as.vector(result[[1]]), as.vector(Reduce('+', result) - result[[1]]))
base_result <- lapply(R_list, function(x) F_mat %*% x)
mapply(function(x, y) expect_equal(as.vector(x), as.vector(y)),
base_result, result)
})
test_that("Testing mortality(samc, origin)", {
result <- mortality(samc_obj, origin = row_vec[1])
expect_equal(as.vector(result[[1]]), as.vector(Reduce('+', result) - result[[1]]))
result_char <- mortality(samc_obj, origin = as.character(row_vec[1]))
expect_equal(result[[1]], result_char[[1]])
base_result <- lapply(R_list, function(x) F_mat %*% x)
mapply(function(x, y) expect_equal(as.vector(x[row_vec[1], ]), as.vector(y)),
base_result, result)
})
test_that("Testing mortality(samc, dest)", {
result <- mortality(samc_obj, dest = col_vec[1])
expect_equal(as.vector(result[[1]]), as.vector(Reduce('+', result) - result[[1]]))
result_char <- mortality(samc_obj, dest = as.character(col_vec[1]))
expect_equal(result[[1]], result_char[[1]])
base_result <- lapply(R_list, function(x) F_mat %*% x)
mapply(function(x, y) expect_equal(as.vector(x[, col_vec[1]]), as.vector(y)),
base_result, result)
})
test_that("Testing mortality(samc, origin, dest)", {
vector_result <- mortality(samc_obj, origin = row_vec, des = col_vec)
expect_equal(as.vector(vector_result[[1]]), as.vector(Reduce('+', vector_result) - vector_result[[1]]))
vector_result_char <- mortality(samc_obj, origin = as.character(row_vec), dest = as.character(col_vec))
expect_equal(vector_result[[1]], vector_result_char[[1]])
base_result <- lapply(R_list, function(x) F_mat %*% x)
for (i in 1:length(row_vec)) {
r <- mortality(samc_obj, origin = row_vec[i], dest = col_vec[i])
mapply(function(x, y) expect_equal(x[i], y),
vector_result, r)
mapply(function(x, y) expect_equal(x, y[row_vec[i], col_vec[i]], check.names = FALSE),
r, base_result)
}
})
test_that("Testing mortality(samc, occ)", {
result <- mortality(samc_obj, occ = test$occ)
expect_equal(as.vector(result[[1]]), as.vector(Reduce('+', result) - result[[1]]))
base_result <- lapply(R_list, function(x) pv %*% F_mat %*% x)
mapply(function(x, y) expect_equal(as.vector(x), as.vector(y)),
base_result, result)
})
} |
doFullPlot <- function (cosinemeshplot,
cosinedrugbankplot,
cosineepilepsyplot,
dicemeshplot,
dicedrugbankplot,
diceepilepsyplot,
jaccardmeshplot,
jaccarddrugbankplot,
jaccardepilepsyplot) {
full <- gridExtra::grid.arrange(cosinemeshplot,
cosinedrugbankplot,
cosineepilepsyplot,
dicemeshplot,
dicedrugbankplot,
diceepilepsyplot,
jaccardmeshplot,
jaccarddrugbankplot,
jaccardepilepsyplot)
return (full)
} |
context("racusum_crit_sim")
R0 <- 1; RA <- 2
library("spcadjust")
data("cardiacsurgery")
cardiacsurgery <- dplyr::mutate(cardiacsurgery, phase=factor(ifelse(date < 2*365, "I", "II")))
S2 <- subset(cardiacsurgery, c(surgeon==2), c("phase", "Parsonnet", "status"))
S2I <- subset(S2, c(phase=="I"), c("Parsonnet", "status"))
df1 <- data.frame(Parsonnet=c(0L, 0L, 50L, 50L), status = c(0, 1, 0, 1))
coeff1 <- c("(Intercept)" = -3.68, "Parsonnet" = 0.077)
L0 <- 1
test_that("Input parameter of function", {
expect_error(racusum_crit_sim(L0 = 0, df1, coeff1))
})
test_that("Different input values for df", {
dftest1 <- list(as.matrix(df1), NULL)
lapply(dftest1, function(x) {
expect_error(do.call(x, racusum_crit_sim(L0, df = x, coeff1)))})
dftest2 <- list(data.frame(0L, 1, 1), data.frame(0L), data.frame(NA))
lapply(dftest2, function(x) {
expect_error(do.call(x, racusum_crit_sim(L0, df = x, coeff1)))})
})
test_that("Different input values for coeff", {
coefftest <- list(coeff1[1], rep(1, 3), NULL, NA)
lapply(coefftest, function(x) {
expect_error(do.call(x, racusum_crit_sim(L0, df1, coeff = x)))})
})
test_that("Different input values for R0", {
R0test <- list(-1, 0, "0", NA)
lapply(R0test, function(x) {
expect_error(do.call(x, racusum_crit_sim(L0, df1, coeff1, R0 = x)))})
})
test_that("Different input values for RA", {
RAtest <- list(-1, 0, "0", NA)
lapply(RAtest, function(x) {
expect_error(do.call(x, racusum_crit_sim(L0, df1, coeff1, RA = x)))})
})
test_that("Iterative search procedure I", {
skip_on_cran()
skip_if(SKIP==TRUE, "skip this test now")
SALLI <- cardiacsurgery %>% mutate(s = Parsonnet) %>%
mutate(y = ifelse(status == 1 & time <= 30, 1, 0),
phase = factor(ifelse(date < 2*365, "I", "II"))) %>%
filter(phase == "I") %>% select(s, y)
mod1 <- glm(y ~ s, data = SALLI, family = "binomial")
y <- SALLI$y
pi1 <- fitted.values(mod1)
pmix <- data.frame(y, pi1, pi1)
L0 <- 370
m <- 1e3
tol <- 0.3
set.seed(1234)
expect_equal(racusum_crit_sim(pmix = pmix, L0 = L0, m = m, RA = 2, verbose = TRUE), 1.8481, tolerance=tol)
expect_equal(racusum_crit_sim(pmix = pmix, L0 = L0, m = m, RA = 2, verbose = FALSE), 1.8481, tolerance=tol)
expect_equal(racusum_crit_sim(pmix = pmix, L0 = L0, m = m, RA = 1/2, verbose = TRUE), 1.6383, tolerance=tol)
expect_equal(racusum_crit_sim(pmix = pmix, L0 = L0, m = m, RA = 1/2, verbose = FALSE), 1.6383, tolerance=tol)
}) |
DistMatrixNoUnit <- function(dists, func, testNA){
FUN <- match.fun(func)
n_cols = ncol(dists)
dist_value = vector("numeric", 1)
dist_matrix <- matrix(NA_real_, n_cols,n_cols)
for (i in seq_len(n_cols)) {
for (j in seq_len(n_cols)) {
if (is.na(dist_matrix[i,j])) {
dist_value = FUN(dists[ , i], dists[ , j], testNA)
dist_matrix[i,j] = dist_value
dist_matrix[j,i] = dist_value
}
}
}
return(dist_matrix)
} |
linearSum <- function(theta,
matrixList) {
C <- Reduce('+', Map(f = function(x, y) x * y, theta, matrixList))
return(C)
}
quadForm <- function(x,
A,
y = x) {
sum(x * (A %*% y))
}
calcSumSquares <- function(lRinv,
Q,
r,
a,
Nvarcomp) {
SSr <- sapply(X = lRinv, FUN= function(X) {
quadForm(r, X)
})
if (Nvarcomp > 0) {
SSa <- sapply(X = Q, FUN = function(X) {
quadForm(a, X)
})
SS_all <- c(SSa, SSr)
} else {
SS_all <- SSr
}
return(SS_all)
}
solveMME <- function(cholC,
listC,
lWtRinvY,
phi,
theta) {
C <- linearSum(theta = theta, matrixList = listC)
cholC <- update(cholC, C)
WtRinvy <- as.vector(linearSum(theta = phi, matrixList = lWtRinvY))
a <- spam::backsolve.spam(cholC, spam::forwardsolve.spam(cholC, WtRinvy))
return(a)
}
calcEffDim <- function(ADcholGinv,
ADcholRinv,
ADcholC,
phi,
psi,
theta) {
resultRinv <- logdetPlusDeriv(ADcholRinv, phi)
logdetR <- -resultRinv[1]
dlogdetRinv <- resultRinv[-1]
if (!is.null(ADcholGinv)) {
resultGinv <- logdetPlusDeriv(ADcholGinv, psi)
logdetG <- -resultGinv[1]
dlogdetGinv <- resultGinv[-1]
} else {
logdetG <- 0
}
resultC <- logdetPlusDeriv(ADcholC, theta)
logdetC <- resultC[1]
dlogdetC <- resultC[-1]
EDmax_phi <- phi * dlogdetRinv
if (!is.null(ADcholGinv)) {
EDmax_psi <- psi * dlogdetGinv
} else {
EDmax_psi <- NULL
}
EDmax <- c(EDmax_psi, EDmax_phi)
ED <- EDmax - theta * dlogdetC
attr(ED, "logdetC") <- logdetC
attr(ED, "logdetG") <- logdetG
attr(ED, "logdetR") <- logdetR
return(ED)
}
REMLlogL <- function(ED,
yPy) {
logdetC <- attr(ED, "logdetC")
logdetG <- attr(ED, "logdetG")
logdetR <- attr(ED, "logdetR")
logL <- -0.5 * (logdetR + logdetG + logdetC + yPy)
return(logL)
}
sparseMixedModels <- function(y,
X,
Z,
lGinv,
lRinv,
maxit = 100,
tolerance = 1.0e-6,
trace = FALSE,
theta = NULL) {
Ntot <- length(y)
p <- ncol(X)
q <- ncol(Z)
Nres <- length(lRinv)
Nvarcomp <- length(lGinv)
NvarcompTot <- Nres + Nvarcomp
dimMME <- p + q
W <- spam::as.spam(cbind(X, Z))
Wt <- t(W)
lWtRinvW <- lapply(X = lRinv, FUN = function(x) { Wt %*% x %*% W})
lWtRinvY <- lapply(X = lRinv, FUN = function(x) { Wt %*% (x %*% y)})
lQ <- lapply(X = lGinv, FUN = function(x) {
zero <- spam::spam(0, ncol = p, nrow = p)
return(spam::bdiag.spam(zero, x))
})
listC <- c(lQ, lWtRinvW)
lWtRinvW <- lapply(X = lWtRinvW, FUN = spam::cleanup)
lQ <- lapply(X = lQ, FUN = spam::cleanup)
lGinv <- lapply(X = lGinv, FUN = spam::cleanup)
listC <- lapply(X = listC, FUN = spam::cleanup)
if (is.null(theta)) {
theta <- rep(1, Nvarcomp + Nres)
}
if (Nvarcomp > 0) {
psi <- theta[1:Nvarcomp]
phi <- theta[-(1:Nvarcomp)]
} else {
psi <- NULL
phi <- theta
}
C <- linearSum(theta = theta, matrixList = listC)
opt <- summary(C)
cholC <- chol(C, memory = list(nnzR = 8 * opt$nnz,
nnzcolindices = 4 * opt$nnz))
ADcholRinv <- ADchol(lRinv)
if (Nvarcomp > 0) {
ADcholGinv <- ADchol(lGinv)
} else {
ADcholGinv <- NULL
}
ADcholC <- ADchol(listC)
logLprev <- Inf
fixedTheta <- rep(FALSE, length = NvarcompTot)
if (trace) {
cat("iter logLik\n")
}
for (it in 1:maxit) {
if (Nvarcomp > 0) {
psi <- theta[1:length(psi)]
phi <- theta[-(1:length(psi))]
} else {
psi <- NULL
phi <- theta
}
ED <- calcEffDim(ADcholGinv, ADcholRinv, ADcholC, phi, psi, theta)
a <- solveMME(cholC = cholC, listC = listC, lWtRinvY = lWtRinvY,
phi = phi, theta = theta)
r <- y - W %*% a
SS_all <- calcSumSquares(lRinv = lRinv, Q = lQ, r = r, a = a,
Nvarcomp = Nvarcomp)
Rinv <- linearSum(phi, lRinv)
yPy <- quadForm(x = y, A = Rinv, y = r)
logL <- REMLlogL(ED, yPy)
if (trace) {
cat(sprintf("%4d %8.4f\n", it, logL))
}
if (abs(logLprev - logL) < tolerance) {
break
}
theta <- ifelse(fixedTheta, theta, ED / SS_all)
fixedTheta <- theta > 1.0e6
logLprev <- logL
}
if (it == maxit) {
warning("No convergence after ", maxit, " iterations \n", call. = FALSE)
}
C <- linearSum(theta = theta, matrixList = listC)
cholC <- update(cholC, C)
names(phi) <- names(lRinv)
names(psi) <- names(lGinv)
EDnames <- c(names(lGinv), names(lRinv))
L <- list(logL = logL, sigma2e = 1 / phi, tau2e = 1 / psi, ED = ED,
theta = theta, EDnames = EDnames, a = a, yhat = y - r,
residuals = r, nIter = it, C = C)
return(L)
} |
library( "testthat" )
test_package( "SmithWilsonYieldCurve" ) |
NULL
if(getRversion() >= "2.15.1") utils::globalVariables(c("."))
globalVariables(c("valueGuess",
"valueType",
"row_1",
"row_2",
"value",
"cor",
"setNames",
"rowname",
"n")) |
setClass (
Class = "DecisionTable",
representation = representation(
decisionTable = "matrix"
),
validity = function(object){
if(nrow(object@decisionTable) < 2 || ncol(object@decisionTable) < 2){
stop ("[DecisionTable: validation] the minimum number of row and columns are 2")
}else{}
return(TRUE)
}
)
setMethod (
f="initialize",
signature="DecisionTable",
definition=function(.Object,decisionTable){
if(!missing(decisionTable)){
colnames(decisionTable) <- paste("C",1:ncol(decisionTable),sep="")
dtColNames <- colnames(decisionTable)
dtColNames[length(dtColNames)] <- "D"
colnames(decisionTable) <- dtColNames
rownames(decisionTable) <- paste("R",1:nrow(decisionTable),sep="")
.Object@decisionTable <- decisionTable
validObject(.Object)
}else{
.Object@decisionTable <- matrix(nrow=0,ncol=0)
}
return(.Object)
}
)
decisionTable <- function(theDecisionTable){
new (Class="DecisionTable",decisionTable=theDecisionTable)
}
setGeneric("getDecisionTable",function(object){standardGeneric ("getDecisionTable")})
setMethod("getDecisionTable","DecisionTable",
function(object){
return(object@decisionTable)
}
)
setGeneric("getCondition",function(object){standardGeneric ("getCondition")})
setMethod("getCondition","DecisionTable",
function(object){
decisionTable <- object@decisionTable
condition <- decisionTable[,1:(ncol(decisionTable)-1)]
return(condition)
}
)
setGeneric("getDecision",function(object){standardGeneric ("getDecision")})
setMethod("getDecision","DecisionTable",
function(object){
decisionTable <- object@decisionTable
decision <- decisionTable[,ncol(decisionTable)]
return(decision)
}
)
setGeneric("getRule",function(object,ruleIndex){standardGeneric ("getRule")})
setMethod("getRule","DecisionTable",
function(object,ruleIndex){
return(object@decisionTable[ruleIndex,])
}
)
setMethod ("print","DecisionTable",
function(x,...){
cat("*** Class DecisionTable, method Print *** \n")
if(length(x@decisionTable) != 0){
print(formatC(x@decisionTable),quote=FALSE)
}else{}
cat("******* End Print (DecisionTable) ******* \n")
}
)
setMethod("show","DecisionTable",
function(object){
cat("*** Class DecisionTable, method Show *** \n")
cat("* decisionTable (limited to a matrix 10x10) = \n")
if(length(object@decisionTable) != 0){
nrowShow <- min(10,nrow(object@decisionTable))
ncolShow <- min(10,ncol(object@decisionTable))
print(formatC(object@decisionTable[1:nrowShow,1:ncolShow]),quote=FALSE)
}else{}
cat("******* End Show (DecisionTable) ******* \n")
}
)
setGeneric (name = "checkConsistency",def = function(object){standardGeneric("checkConsistency")})
setMethod(
f = "checkConsistency",
signature = "DecisionTable",
definition = function(object){
consistencyMatrix <- .computeConsistencyMatrix(object@decisionTable)
expectedSum <- c(1:nrow(consistencyMatrix))
obtainedSum <- apply(consistencyMatrix,1,function(theRule){sum(theRule,na.rm = TRUE)})
consistentRules <- (obtainedSum == expectedSum)
return(consistentRules)
}
)
setGeneric (name = "computeConsistencyMatrix",def = function(object){standardGeneric("computeConsistencyMatrix")})
setMethod(
f = "computeConsistencyMatrix",
signature = "DecisionTable",
definition = function(object){
consistencyMatrix <- .computeConsistencyMatrix(object@decisionTable)
return(consistencyMatrix)
}
)
setGeneric (name = "computeDiscernibilityMatrix",def = function(object){standardGeneric("computeDiscernibilityMatrix")})
setMethod(
f = "computeDiscernibilityMatrix",
signature = "DecisionTable",
definition = function(object){
discernibilityMatrix <- .computeDiscernibilityMatrix(object@decisionTable)
dt <- new(Class="DiscernibilityMatrix",discernibilityMatrix = discernibilityMatrix)
return(dt)
}
)
setGeneric (name = "removeDuplicatedRulesDT",def = function(object){standardGeneric("removeDuplicatedRulesDT")})
setMethod(
f = "removeDuplicatedRulesDT",
signature = "DecisionTable",
definition = function(object){
dtMat <- object@decisionTable
newDecisionTable <- unique(dtMat)
newDT <- new(Class="DecisionTable",decisionTable = newDecisionTable)
return(newDT)
}
)
setGeneric (name = "findFirstConditionReduct",def = function(object){standardGeneric("findFirstConditionReduct")})
setMethod(
f = "findFirstConditionReduct",
signature = "DecisionTable",
definition = function(object){
dtMat <- object@decisionTable
dm <- computeDiscernibilityMatrix(object)
coreNoDecision <- computeCore(dm)
firstReduct <- .findFirstReductsFromCore(dtMat,coreNoDecision)
firstReductWithDecision <- append(firstReduct,ncol(dtMat))
cr <- new(Class="ConditionReduct",decisionTable = object, columnIds = firstReductWithDecision)
return(cr)
}
)
setGeneric (name = "findSmallestReductFamilyFromCore",def = function(object){standardGeneric("findSmallestReductFamilyFromCore")})
setMethod(
f = "findSmallestReductFamilyFromCore",
signature = "DecisionTable",
definition = function(object){
lres <- list()
dtMat <- object@decisionTable
dm <- computeDiscernibilityMatrix(object)
coreNoDecision <- computeCore(dm)
reductFamilyList <- .findSmallestReductFamilyFromCore(dtMat,coreNoDecision)
listLen <- length(reductFamilyList)
for(i in 1:listLen){
reductVector <- reductFamilyList[[i]]
reductVector <- append(reductVector,ncol(dtMat))
cr <- new(Class="ConditionReduct",decisionTable = object,columnIds = reductVector)
lres[[i]] <- cr
}
return(lres)
}
)
setGeneric (name = "findAllReductsFromCore",def = function(object){standardGeneric("findAllReductsFromCore")})
setMethod(
f = "findAllReductsFromCore",
signature = "DecisionTable",
definition = function(object){
lres <- list()
dtMat <- object@decisionTable
dm <- computeDiscernibilityMatrix(object)
coreNoDecision <- computeCore(dm)
reductFamilyList <- .findAllReductsFromCore(dtMat,coreNoDecision)
listLen <- length(reductFamilyList)
for(i in 1:listLen){
reductVector <- reductFamilyList[[i]]
reductVector <- append(reductVector,ncol(dtMat))
cr <- new(Class="ConditionReduct",decisionTable = object,columnIds = reductVector)
lres[[i]] <- cr
}
return(lres)
}
)
setGeneric (name = "simplifyDecisionTable",def = function(object){standardGeneric("simplifyDecisionTable")})
setMethod(
f = "simplifyDecisionTable",
signature = "DecisionTable",
definition = function(object){
noDuplicatedDT <- removeDuplicatedRulesDT(object)
cr <- findFirstConditionReduct(noDuplicatedDT)
noDuplicatedCR <- removeDuplicatedRulesCR(cr)
vr <- computeValueReduct(noDuplicatedCR)
NoDuplicatedVr <- removeDuplicatedRulesVR(vr)
return(NoDuplicatedVr)
}
)
.inflateValueReduct <- function(theValueReductWithDecision, theReductConditionIds,theDecisionTableConditionDecisionIds){
resRowCounter <- nrow(theValueReductWithDecision)
resColCounter <- length(theDecisionTableConditionDecisionIds)
res <- matrix(data = NA, nrow = resRowCounter, ncol = resColCounter)
for(i in 1:resRowCounter){
valueReductRule <- theValueReductWithDecision[i,]
copyCounter <- 0
for(j in 1:resColCounter){
if(is.element(j, theReductConditionIds)){
copyCounter <- (copyCounter + 1)
res[i,j] <- valueReductRule[copyCounter]
}else{}
if(j == resColCounter){
res[i,j] <- valueReductRule[length(valueReductRule)]
}else{}
}
}
return(res)
}
.findFirstReductsFromCore <- function(theDecisionTable,theCoreNoDecision){
theCore <- theCoreNoDecision
if(.isReduct(theDecisionTable, theCore)){
res <- theCore
}else{
conditionCount <- (ncol(theDecisionTable) - 1)
notCoreConditionsId <- setdiff(c(1:conditionCount),theCore)
res <- vector(mode = "numeric", length = 0)
for(i in 1:(length(notCoreConditionsId))){
if(length(notCoreConditionsId) > 1){
combinations <- combn(notCoreConditionsId,i)
combinationsCount <- ncol(combinations)
}else if(length(notCoreConditionsId) == 1){
combinations <- notCoreConditionsId
combinationsCount <- 1
}else{}
for(j in 1:combinationsCount){
if(is.vector(combinations)){
combinationNoCore <- combinations[j]
}else if(is.matrix(combinations)){
combinationNoCore <- combinations[,j]
}else{}
combinationCore <- union(theCore, combinationNoCore)
combinationCore <- sort(combinationCore)
if(.isReduct(theDecisionTable, combinationCore)){
res <- combinationCore
break
}else{}
}
if(length(res) > 0){
break
}else{}
}
}
return(res)
}
.findSmallestReductFamilyFromCore <- function(theDecisionTable,theCoreNoDecision){
theCore <- theCoreNoDecision
lres <- list()
if(.isReduct(theDecisionTable, theCore)){
lres[[1]] <- theCore
}else{
conditionCount <- (ncol(theDecisionTable) - 1)
notCoreConditionsId <- setdiff(c(1:conditionCount),theCore)
counter <- 0
for(i in 1:(length(notCoreConditionsId))){
if(length(notCoreConditionsId) > 1){
combinations <- combn(notCoreConditionsId,i)
combinationsCount <- ncol(combinations)
}else if(length(notCoreConditionsId) == 1){
combinations <- notCoreConditionsId
combinationsCount <- 1
}else{}
for(j in 1:combinationsCount){
if(is.vector(combinations)){
combinationNoCore <- combinations[j]
}else if(is.matrix(combinations)){
combinationNoCore <- combinations[,j]
}else{}
combinationCore <- union(theCore, combinationNoCore)
combinationCore <- sort(combinationCore)
if(.isReduct(theDecisionTable, combinationCore)){
counter <- (counter + 1)
lres[[counter]] <- combinationCore
}else{}
}
if(counter != 0){
break
}
}
}
return(lres)
}
.findAllReductsFromCore <- function(theDecisionTable,theCoreNoDecision){
theCore <- theCoreNoDecision
lres <- list()
counter <- 0
if(.isReduct(theDecisionTable, theCore)){
counter <- (counter + 1)
lres[[counter]] <- theCore
}else{}
conditionCount <- (ncol(theDecisionTable) - 1)
notCoreConditionsId <- setdiff(c(1:conditionCount),theCore)
for(i in 1:(length(notCoreConditionsId))){
if(length(notCoreConditionsId) > 1){
combinations <- combn(notCoreConditionsId,i)
combinationsCount <- ncol(combinations)
}else if(length(notCoreConditionsId) == 1){
combinations <- notCoreConditionsId
combinationsCount <- 1
}else{}
for(j in 1:combinationsCount){
if(is.vector(combinations)){
combinationNoCore <- combinations[j]
}else if(is.matrix(combinations)){
combinationNoCore <- combinations[,j]
}else{}
combinationCore <- union(theCore, combinationNoCore)
combinationCore <- sort(combinationCore)
if(.isReduct(theDecisionTable, combinationCore)){
counter <- (counter + 1)
lres[[counter]] <- combinationCore
}else{}
}
}
return(lres)
}
.computeDiscernibilityMatrix <- function(theDecisionTable){
id <- c(1:nrow(theDecisionTable))
conditionCount <- ncol(theDecisionTable) - 1
ruleCount <- nrow(theDecisionTable)
theDTid <- cbind(theDecisionTable,id)
partialResult <- apply(theDTid,1,.computeDiscernibilityVector,theDecisionTable=theDecisionTable)
discernibilityMatrix <- array(NA,c(ruleCount,ruleCount,conditionCount))
mat <- matrix()
for(i in 1:ruleCount){
mat <- matrix(partialResult[,i],ncol=conditionCount,byrow=TRUE)
for(j in 1:nrow(mat)){
discernibilityMatrix[i,j,] <- mat[j,]
}
}
ruleNames <- paste("R",1:nrow(discernibilityMatrix),sep="")
attNames <- paste("C",1:conditionCount,sep="")
dimensionNames <- list(ruleNames,ruleNames,attNames)
dimnames(discernibilityMatrix) <- dimensionNames
return(discernibilityMatrix)
}
.computeConsistencyMatrix <- function(theDecisionTable){
id <- c(1:nrow(theDecisionTable))
theDTid <- cbind(theDecisionTable,id)
consistencyMatrix <- apply(theDTid,1,.computeConsistencyVector,theDecisionTable=theDecisionTable)
rownames(consistencyMatrix) <- paste("R",1:nrow(consistencyMatrix),sep="")
colnames(consistencyMatrix) <- paste("R",1:ncol(consistencyMatrix),sep="")
return(consistencyMatrix)
}
.computeDiscernibilityVector<- function(theRule,theDecisionTable){
ruleId <- theRule[length(theRule)]
rule <- theRule[-length(theRule)]
ruleCondition <- rule[-length(rule)]
ruleConditionCount <- length(ruleCondition)
conditionTable <- theDecisionTable[,-ncol(theDecisionTable)]
ruleCount <- nrow(theDecisionTable)
conditionCount <- length(rule) - 1
theDisTable <- array(NA, c(ruleCount,conditionCount))
for(i in 1:ruleCount){
iniPos <- ((i * ruleConditionCount)-(ruleConditionCount-1))
endPos <- (i * ruleConditionCount)
if(i <= ruleId){
theDisTable[iniPos:endPos] <- NA
}else if(i > ruleId){
theDisTable[iniPos:endPos] <- (ruleCondition != conditionTable[i,])
}else{}
}
return(theDisTable)
}
.computeConsistencyVector <- function(theRule,theDecisionTable){
ruleId <- theRule[length(theRule)]
rule <- theRule[1:(length(theRule)-1)]
ruleCount <- nrow(theDecisionTable)
theConVector <- vector(mode = "logical", length = ruleCount)
theValue <- NA
for(i in 1:ruleCount){
if(i < ruleId){
theValue <- NA
}else if(i == ruleId){
theValue <- TRUE
}else if(i > ruleId){
theValue <- .checkRuleConsistency(rule,theDecisionTable[i,])
}else{}
theConVector[i] <- theValue
}
if(sum(theConVector, na.rm = TRUE) != ((length(theConVector) + 1) - ruleId)){
theConVector[ruleId] <- FALSE
}else{}
return(theConVector)
}
.checkRuleConsistency <- function(rule1,rule2){
areConsistent <- FALSE
condR1 <- rule1[-length(rule1)]
condR2 <- rule2[-length(rule2)]
decR1 <- rule1[length(rule1)]
decR2 <- rule2[length(rule2)]
if(identical(condR1,condR2)){
if(identical(decR1,decR2)){
areConsistent <- TRUE
}else{
areConsistent <- FALSE
}
}else{
areConsistent <- TRUE
}
return(areConsistent)
}
.isReduct <- function(theDecisionTable, theReductConditionIds){
reduct <- theDecisionTable[,theReductConditionIds]
conditions <- theDecisionTable[,-ncol(theDecisionTable)]
indRed <- .computeIndescernibilityFunction(reduct)
indCon <- .computeIndescernibilityFunction(conditions)
ans <- identical(indCon,indRed)
return(ans)
} |
dta.byte <- 251
dta.short <- 252
dta.long <- 253
dta.float <- 254
dta.double <- 255
dta.byte.missrange <- c(0x64,0x7f)
dta.short.missrange <- c(0x7fe5,0x7fff)
dta.long.missrange <- c(0x7fffffe5L,0x7fffffffL)
dta.float.missrange <- c(2.0^0x7f,Inf)
dta.double.missrange <- c(2.0^0x3ff,Inf)
missnames <- paste(".",c("",letters),sep="")
dta.byte.misslab <- structure(0x64 + 1:27,names=missnames)
dta.short.misslab <- structure(0x7fe4 + 1:27,names=missnames)
dta.long.misslab <- structure(0x7fffffe4L + 1:27,names=missnames)
dta.float.misslab <- structure((1+(0:26)/16^3)*2.0^0x7f,names=missnames)
dta.double.misslab <- structure((1+(0:26)/16^3)*2.0^0x3ff,names=missnames)
new.dta <- function(file) .Call("dta_file_open",file,"rb")
dta.read.version <- function(bf) .Call("dta_read_version",bf)
dta.read.header <- function(bf,lablen).Call("dta_read_header",bf,lablen)
dta.read.descriptors <- function(bf,nvar,len.varn,len.fmt,len.lbl)
.Call("dta_read_descriptors",bf,nvar,len.varn,len.fmt,len.lbl)
dta.read.varlabs <- function(bf,nvar,len.varlab)
.Call("dta_read_varlabs",bf,nvar,len.varlab)
dta.read.expansion.fields <- function(bf,shortext)
.Call("dta_read_expansion_fields",bf,shortext)
dta.read.labels <- function(bf,lbllen,padding)
.Call("dta_read_labels",bf,lbllen,padding)
dta.trans.types <- function(types)
.Call("dta_trans_types",types)
dta.calc.obssize <- function(bf,types)
.Call("dta_calc_obssize",bf,types)
dta.tell <- function(bf) .Call("dta_ftell",bf)
dta.seek <- function(bf,pos,whence) .Call("dta_fseek",bf,pos,whence)
dta.feof <- function(bf) .Call("dta_feof",bf)
dta.skip.records <- function(bf,n) .Call("dta_skip_records",bf,n)
dta.seek.data <- function(bf) .Call("dta_seek_data",bf)
get.dictionary.dta <- function(bf){
version <- dta.read.version(bf)
if(version==105){
version.string <- "Stata 5"
len.varn <- 8
len.fmt <- 11
len.lbl <- 8
len.varlab <- 31
ext.short <- TRUE
conv.types <- FALSE
}
else if(version==108){
version.string <- "Stata 6"
len.varn <- 8
len.fmt <- 11
len.lbl <- 8
len.varlab <- 80
ext.short <- TRUE
conv.types <- FALSE
}
else if(version==110){
version.string <- "Stata 7"
len.varn <- 32
len.fmt <- 11
len.lbl <- 32
len.varlab <- 80
ext.short <- FALSE
conv.types <- TRUE
}
else if(version==111){
version.string <- "Stata 7 SE"
len.varn <- 32
len.fmt <- 11
len.lbl <- 32
len.varlab <- 80
ext.short <- FALSE
conv.types <- FALSE
}
else if(version==113){
version.string <- "Stata 8"
len.varn <- 32
len.fmt <- 11
len.lbl <- 32
len.varlab <- 80
ext.short <- FALSE
conv.types <- FALSE
}
else if(version %in% c(114,115)){
version.string <- if(version==114) "Stata 9" else "Stata 10"
len.varn <- 32
len.fmt <- 48
len.lbl <- 32
len.varlab <- 80
ext.short <- FALSE
conv.types <- FALSE
} else {
stop("version ",version," not yet supported")
}
hdr <- dta.read.header(bf,len.varlab)
nobs <- hdr$nobs
nvar <- hdr$nvar
descriptors <- dta.read.descriptors(bf,
nvar=nvar,
len.varn=len.varn,
len.fmt=len.fmt,
len.lbl=len.lbl)
varnames <- descriptors$varlist
types <- if(conv.types) dta.trans.types(descriptors$typelist)
else descriptors$typelist
names(types) <- varnames
obs_size <- dta.calc.obssize(bf,types)
varlab <- dta.read.varlabs(bf,
nvar=nvar,
len.varlab=len.varlab)
names(varlab) <- varnames
dta.read.expansion.fields(bf,ext.short)
vallabs <- descriptors$lbllist
names(vallabs) <- varnames
vallabs <- vallabs[nzchar(vallabs)]
if(version>105){
dta.skip.records(bf,nobs)
vallab.patterns <- list()
while(!dta.feof(bf))
vallab.patterns <- c(vallab.patterns,dta.read.labels(bf,len.lbl,3))
if(!any(sapply(vallab.patterns,length)>0))
vallab.patterns <- NULL
}
else
vallab.patterns <- NULL
if(length(vallab.patterns)){
vallabs[] <- vallab.patterns[vallabs]
}
if(version >= 113){
missing.values <- dta_missing.values(types)
missval_labels <- dta_missval_labels(types)
}
else {
missing.values <- NULL
missval_labels <- NULL
}
list(names=varnames,
types=types,
nobs=nobs,
nvar=nvar,
varlabs=varlab,
value.labels=vallabs,
missing.values=missing.values,
missval_labels=missval_labels,
version.string=version.string
)
}
dta_missing.values <- function(types){
nvar <- length(length)
missing.values <- vector(nvar,mode="list")
missing.values[types==dta.byte] <- list(list(range=dta.byte.missrange))
missing.values[types==dta.short] <- list(list(range=dta.short.missrange))
missing.values[types==dta.long] <- list(list(range=dta.long.missrange))
missing.values[types==dta.float] <- list(list(range=dta.float.missrange))
missing.values[types==dta.double] <- list(list(range=dta.double.missrange))
names(missing.values) <- names(types)
missing.values
}
dta_missval_labels <- function(types){
nvar <- length(length)
missval_labels <- vector(nvar,mode="list")
missval_labels[types==dta.byte] <- list(dta.byte.misslab)
missval_labels[types==dta.short] <- list(dta.short.misslab)
missval_labels[types==dta.long] <- list(dta.long.misslab)
missval_labels[types==dta.float] <- list(dta.float.misslab)
missval_labels[types==dta.double] <- list(dta.double.misslab)
names(missval_labels) <- names(types)
missval_labels
} |
context("aliases")
test_that("aliases work", {
expect_equal(
gss_calc %>%
get_pvalue(obs_stat = -0.2, direction = "right") %>%
dplyr::pull(),
expected = 1,
tolerance = eps
)
expect_silent(gss_permute %>% get_ci())
})
test_that("old aliases produce warning", {
expect_warning(
gss_calc %>%
p_value(obs_stat = -0.2, direction = "right") %>%
dplyr::pull(),
expected = 1
)
expect_warning(gss_permute %>% conf_int())
}) |
Plot2WayANOVA <- function(formula,
dataframe = NULL,
confidence = .95,
plottype = "line",
errorbar.display = "CI",
xlab = NULL,
ylab = NULL,
title = NULL,
subtitle = NULL,
interact.line.size = 2,
ci.line.size = 1,
mean.label = FALSE,
mean.ci = TRUE,
mean.size = 4,
mean.shape = 23,
mean.color = "darkred",
mean.label.size = 3,
mean.label.color = "black",
offset.style = "none",
overlay.type = NULL,
posthoc.method = "scheffe",
show.dots = FALSE,
PlotSave = FALSE,
ggtheme = ggplot2::theme_bw(),
package = "RColorBrewer",
palette = "Dark2",
ggplot.component = NULL) {
ggplot2::theme_set(ggtheme)
if (length(match.call()) - 1 <= 1) {
stop("Not enough arguments passed...
requires at least a formula with a DV and 2 IV plus a dataframe")
}
if (missing(formula)) {
stop("\"formula\" argument is missing, with no default")
}
if (!is(formula, "formula")) {
stop("\"formula\" argument must be a formula")
}
if (length(formula) != 3) {
stop("invalid value for \"formula\" argument")
}
vars <- all.vars(formula)
chkinter <- all.names(formula)
if (length(vars) != 3) {
stop("invalid value for \"formula\" argument")
}
if ("+" %in% chkinter) {
stop("Sorry you need to use an asterisk not a plus sign in
the formula so the interaction can be plotted")
}
if ("~" == chkinter[2]) {
stop("Sorry you can only have one dependent variable so only
one tilde is allowed ~ you have two or more")
}
depvar <- vars[1]
iv1 <- vars[2]
iv2 <- vars[3]
potentialfname <- paste0(depvar, "by", iv1, "and", iv2, ".png")
if (missing(dataframe)) {
stop("You didn't specify a data frame to use")
}
if (!exists(deparse(substitute(dataframe)))) {
stop("That dataframe does not exist\n")
}
if (!is(dataframe, "data.frame")) {
stop("The dataframe name you specified is not valid\n")
}
if (!(depvar %in% names(dataframe))) {
stop(paste0(
"'", depvar, "' is not the name of a variable in '",
deparse(substitute(dataframe)), "'"
))
}
if (!(iv1 %in% names(dataframe))) {
stop(paste0(
"'", iv1, "' is not the name of a variable in '",
deparse(substitute(dataframe)), "'"
))
}
if (!(iv2 %in% names(dataframe))) {
stop(paste0(
"'", iv2, "' is not the name of a variable in '",
deparse(substitute(dataframe)), "'"
))
}
dataframe <- dataframe[, c(depvar, iv1, iv2)]
if (is.null(xlab)) {
xlab <- iv1
}
if (is.null(ylab)) {
ylab <- depvar
}
dataframe <- as.data.frame(dataframe)
if (!is(dataframe[, depvar], "numeric")) {
stop("dependent variable must be numeric")
}
if (!is(dataframe[, iv1], "factor")) {
message(paste0("\nConverting ", iv1, " to a factor --- check your results"))
dataframe[, iv1] <- as.factor(dataframe[, iv1])
}
if (!is(dataframe[, iv2], "factor")) {
message(paste0("\nConverting ", iv2, " to a factor --- check your results"))
dataframe[, iv2] <- as.factor(dataframe[, iv2])
}
factor1.names <- levels(dataframe[, iv1])
factor2.names <- levels(dataframe[, iv2])
if (!is(confidence, "numeric") | length(confidence) != 1 |
confidence < .5 | confidence > .9991) {
stop("\"confidence\" must be a number between .5 and 1")
}
if (plottype != "bar") {
plottype <- "line"
}
missing <- apply(is.na(dataframe), 1, any)
if (any(missing)) {
warning(paste(sum(missing)), " case(s) removed because of missing data")
}
dataframe <- dataframe[!missing, ]
checkcells <-
dataframe %>%
group_by(!!sym(iv1), !!sym(iv2)) %>%
summarize(count = n()) %>%
ungroup() %>%
complete(!!sym(iv1), !!sym(iv2), fill = list(count = 0))
if (any(checkcells$count == 0)) {
print(checkcells)
stop(paste0(
"\n--- MAJOR Problem! ---\n",
"You have one or more cells with ZERO observations.\n"
))
} else if (any(checkcells$count <= 2)){
message(paste0(
"\n\t\t\t\t--- WARNING! ---\n",
"\t\tYou have one or more cells with less than 3 observations.\n"
))
print(checkcells)
}
newdata <- dataframe %>%
group_by(!!sym(iv1), !!sym(iv2)) %>%
summarise(
TheMean = mean(!!sym(depvar), na.rm = TRUE),
TheSD = sd(!!sym(depvar), na.rm = TRUE),
TheSEM = sd(!!sym(depvar), na.rm = TRUE) / sqrt(n()),
CIMuliplier = qt(confidence / 2 + .5, n() - 1),
LowerBoundCI = TheMean - TheSEM * CIMuliplier,
UpperBoundCI = TheMean + TheSEM * CIMuliplier,
LowerBoundSEM = TheMean - TheSEM,
UpperBoundSEM = TheMean + TheSEM,
LowerBoundSD = TheMean - TheSD,
UpperBoundSD = TheMean + TheSD,
N = n()
) %>%
mutate(
LowerBound = case_when(
errorbar.display == "SD" ~ LowerBoundSD,
errorbar.display == "SEM" ~ LowerBoundSEM,
errorbar.display == "CI" ~ LowerBoundCI,
TRUE ~ LowerBoundCI),
UpperBound = case_when(
errorbar.display == "SD" ~ UpperBoundSD,
errorbar.display == "SEM" ~ UpperBoundSEM,
errorbar.display == "CI" ~ UpperBoundCI,
TRUE ~ UpperBoundCI)
)
MyAOV <- aov(formula, dataframe)
MyAOVt2 <- aovtype2(MyAOV)
WithETA <- sjstats::anova_stats(MyAOVt2)
BFTest <- BrownForsytheTest(formula, dataframe)
MyAOV_residuals <- residuals(object = MyAOV)
if (nrow(dataframe) < 5000){
SWTest <- shapiro.test(x = MyAOV_residuals)
} else {
SWTest <- NULL
}
sigfactors <- filter(WithETA, p.value <= 1 - confidence) %>% select(term)
if (nrow(sigfactors) > 0) {
posthocresults <- PostHocTest(MyAOV,
method = posthoc.method,
conf.level = confidence,
which = as.character(sigfactors[, 1])
)
} else {
posthocresults <- "No signfiicant effects"
}
bf_models <- BayesFactor::anovaBF(formula = formula,
data = dataframe,
progress = FALSE)
bf_models <-
as_tibble(bf_models, rownames = "model") %>%
select(model:error) %>%
arrange(desc(bf)) %>%
mutate(support = bf_display(bf = bf, display_type = "support")) %>%
mutate(margin_of_error = error) %>%
select(-error)
cipercent <- round(confidence * 100, 2)
if (is.null(title)) {
title <- paste("Interaction plot ", deparse(formula, width.cutoff = 80), collapse="")
if (errorbar.display == "CI") {
title <- bquote(.(title) * " with" ~ .(cipercent) * "% conf ints")
} else if (errorbar.display == "SEM") {
title <- bquote(.(title) * " with standard error of the mean")
} else if (errorbar.display == "SD") {
title <- bquote(.(title) * " with standard deviations")
} else {
title <- title
}
}
AICnumber <- round(stats::AIC(MyAOV), 1)
BICnumber <- round(stats::BIC(MyAOV), 1)
eta2iv1 <- WithETA[1, 7]
eta2iv2 <- WithETA[2, 7]
eta2interaction <- WithETA[3, 7]
if (is.null(subtitle)) {
subtitle <- bquote(
eta^2 * " (" * .(iv1) * ") =" ~ .(eta2iv1) *
", " * eta^2 * " (" * .(iv2) * ") =" ~ .(eta2iv2) *
", " * eta^2 * " (interaction) =" ~ .(eta2interaction) *
", AIC =" ~ .(AICnumber) * ", BIC =" ~ .(BICnumber)
)
}
if (offset.style == "wide") {
dot.dodge <- .4
ci.dodge <- .15
mean.dodge <- .15
}
if (offset.style == "narrow") {
dot.dodge <- .1
ci.dodge <- .05
mean.dodge <- .05
}
if (offset.style != "narrow" && offset.style != "wide") {
dot.dodge <- 0
ci.dodge <- 0
mean.dodge <- 0
}
commonstuff <- list(
xlab(xlab),
ylab(ylab),
scale_colour_hue(l = 40),
ggtitle(title, subtitle = subtitle),
theme(panel.grid.major.x = element_blank())
)
p <- newdata %>%
ggplot(aes_string(
x = iv1,
y = "TheMean",
colour = iv2,
fill = iv2,
group = iv2
)) +
commonstuff
if (plottype == "line" && show.dots == TRUE) {
p <- p +
geom_point(
data = dataframe,
mapping = aes(
x = !!sym(iv1),
y = !!sym(depvar),
shape = !!sym(iv2)
),
alpha = .4,
position = position_dodge(dot.dodge),
show.legend = TRUE
)
}
if (errorbar.display != "none") {
switch(plottype,
bar =
p <- p +
geom_bar(
stat = "identity",
position = "dodge"
) +
geom_errorbar(aes(ymin = LowerBound, ymax = UpperBound),
width = .5,
size = ci.line.size,
position = position_dodge(0.9),
show.legend = FALSE
),
line =
p <- p +
geom_errorbar(aes(
ymin = LowerBound,
ymax = UpperBound
),
width = .2,
size = ci.line.size,
position = position_dodge(ci.dodge)
) +
geom_line(
aes_string(linetype = iv2),
size = interact.line.size,
position = position_dodge(mean.dodge)
) +
geom_point(aes(y = TheMean),
shape = mean.shape,
size = mean.size,
color = mean.color,
alpha = 1,
position = position_dodge(mean.dodge)
)
)
} else {
switch(plottype,
bar =
p <- p +
geom_bar(
stat = "identity",
position = "dodge"
),
line =
p <- p +
geom_line(
aes_string(linetype = iv2),
size = interact.line.size,
position = position_dodge(mean.dodge)
) +
geom_point(aes(y = TheMean),
shape = mean.shape,
size = mean.size,
color = mean.color,
alpha = 1,
position = position_dodge(mean.dodge)
)
)
}
if (!is.null(overlay.type)) {
if (plottype == "line" && overlay.type == "box") {
p <- p +
geom_boxplot(
data = dataframe,
mapping = aes(
x = !!sym(iv1),
y = !!sym(depvar),
group = !!sym(iv1)
),
color = "gray",
width = 0.4,
alpha = 0.2,
fill = "white",
outlier.shape = NA,
show.legend = FALSE
)
} else if (plottype == "line" && overlay.type == "violin") {
p <- p +
geom_violin(
data = dataframe,
mapping = aes(
x = !!sym(iv1),
y = !!sym(depvar),
group = !!sym(iv1)
),
color = "gray",
width = 0.7,
alpha = 0.2,
fill = "white",
show.legend = FALSE
)
}
}
if (isTRUE(mean.label && plottype == "line")) {
p <- p +
ggrepel::geom_label_repel(
data = newdata,
mapping = aes(
x = !!sym(iv1),
y = TheMean,
label = as.character(round(TheMean, 2))
),
size = mean.label.size,
color = mean.label.color,
fontface = "bold",
alpha = .8,
direction = "both",
nudge_x = -.2,
max.iter = 3e2,
box.padding = 0.35,
point.padding = 0.5,
segment.color = "black",
force = 2,
inherit.aes = FALSE,
seed = 123
)
}
if (isTRUE(mean.label && plottype == "bar")) {
p <- p +
ggrepel::geom_label_repel(
data = newdata,
mapping = aes(
x = !!sym(iv1),
y = TheMean,
label = as.character(round(TheMean, 2))
),
size = mean.label.size,
color = mean.label.color,
fontface = "bold",
alpha = .8,
direction = "both",
max.iter = 3e2,
box.padding = 0.35,
point.padding = 0.5,
segment.color = "black",
force = 2,
position = position_dodge(0.9),
inherit.aes = TRUE,
show.legend = FALSE,
seed = 123
)
}
if (!all(checkcells$count == checkcells$count[1])) {
rsquaredx <- round(1 - (MyAOVt2$`Sum Sq`[4] / sum(MyAOVt2$`Sum Sq`[1:4])), 3)
message(paste0(
"\n\t\t\t\t--- WARNING! ---\n",
"\t\tYou have an unbalanced design. Using Type II sum of
squares, to calculate factor effect sizes eta and omega.
Your two factors account for ", rsquaredx, " of the type II sum of
squares.\n"
))
}
else {
message("\nYou have a balanced design. \n")
}
print(WithETA)
message("\nTable of group means\n")
print(newdata)
message("\nPost hoc tests for all effects that were significant\n")
print(posthocresults)
message("\nTesting Homogeneity of Variance with Brown-Forsythe \n")
if (BFTest$`Pr(>F)`[[1]] <= .05) {
message(" *** Possible violation of the assumption ***")
}
print(BFTest)
if(!is.null(SWTest)) {
message("\nTesting Normality Assumption with Shapiro-Wilk \n")
if (SWTest$p.value <= .05) {
message(" *** Possible violation of the assumption. You may
want to plot the residuals to see how they vary from normal ***")
}
print(SWTest)
}
message("\nBayesian analysis of models in order\n")
print(bf_models)
p <- p + ggplot.component
message("\nInteraction graph plotted...")
print(p)
whattoreturn <- list(
ANOVATable = WithETA,
MeansTable = newdata,
PosthocTable = posthocresults,
BFTest = BFTest,
SWTest = SWTest,
Bayesian_models = bf_models
)
if (PlotSave) {
ggsave(potentialfname, device = "png")
whattoreturn[["plotfile"]] <- potentialfname
}
return(invisible(whattoreturn))
} |
nlsmn0b <-function(formula, start, trace=FALSE, data=NULL,
lower=-Inf, upper=Inf, masked=NULL, control=list(), ...){
showpoint<-function(SS, pnum){
pnames<-names(pnum)
npar<-length(pnum)
cat("lamda:",lamda," SS=",SS," at")
for (i in 1:npar){
cat(" ",pnames[i],"=",pnum[i])
}
cat(" ",feval,"/",jeval)
cat("\n")
}
if (! is.null(data)){
for (dfn in names(data)) {
cmd<-paste(dfn,"<-data$",dfn,"")
eval(parse(text=cmd))
}
} else stop("'data' must be a list or an environment")
pnames<-names(start)
start<-as.numeric(start)
names(start)<-pnames
npar<-length(start)
if (length(lower)==1) lower<-rep(lower,npar)
if (length(upper)==1) upper<-rep(upper,npar)
if (length(lower)!=npar) stop("Wrong length: lower")
if (length(upper)!=npar) stop("Wrong length: upper")
if (any(start<lower) || any(start>upper)) stop("Infeasible start")
if (trace) {
cat("formula: ")
print(formula)
cat("lower:")
print(lower)
cat("upper:")
print(upper)
}
ctrl<-list(
watch=FALSE,
phi=1,
lamda=0.0001,
offset=100,
laminc=10,
lamdec=4,
jemax=5000,
femax=10000
)
epstol<-(.Machine$double.eps)*ctrl$offset
ncontrol <- names(control)
nctrl <- names(ctrl)
for (onename in ncontrol) {
if (!(onename %in% nctrl)) {
if (trace) cat("control ",onename," is not in default set\n")
}
ctrl[onename]<-control[onename]
}
phiroot<-sqrt(ctrl$phi)
lamda<-ctrl$lamda
offset<-ctrl$offset
laminc<-ctrl$laminc
lamdec<-ctrl$lamdec
watch<-ctrl$watch
jemax<-ctrl$jemax
femax<-ctrl$femax
vn <- all.vars(parse(text=formula))
pnum<-start
pnames<-names(pnum)
bdmsk<-rep(1,npar)
mskdx<-which(pnames %in% masked)
bdmsk[mskdx]<-0
if (trace) {
parpos <- match(pnames, vn)
datvar<-vn[-parpos]
for (dvn in datvar){
cat("Data variable ",dvn,":")
print(eval(parse(text=dvn)))
}
}
if (is.character(formula)){
es<-formula
} else {
tstr<-as.character(formula)
es<-paste(tstr[[2]],"~",tstr[[3]],'')
}
parts<-strsplit(as.character(es), "~")[[1]]
if (length(parts)!=2) stop("Model expression is incorrect!")
lhs<-parts[1]
rhs<-parts[2]
resexp<-paste(rhs,"-",lhs, collapse=" ")
for (i in 1:npar){
joe<-paste(pnames[[i]],"<-",pnum[[i]])
eval(parse(text=joe))
}
gradexp<-deriv(parse(text=resexp), names(start))
resbest<-with(data, eval(parse(text=resexp)))
ssbest<-crossprod(resbest)
feval<-1
pbest<-pnum
feval<-1
jeval<-0
if (trace) {
cat("Start:")
showpoint(ssbest,pnum)
}
ssquares<-.Machine$double.xmax
newjac<-TRUE
bdmsk<-rep(1,npar)
eqcount<-0
while ((eqcount < npar) && (feval<=femax) && (jeval<=jemax) ) {
if (trace && watch) {
cat("bdmsk:")
print(bdmsk)
}
if (newjac) {
bdmsk<-rep(1,npar)
bdmsk[mskdx]<-0
bdmsk[which(pnum-lower<epstol*(abs(lower)+epstol))]<- -3
bdmsk[which(upper-pnum<epstol*(abs(upper)+epstol))]<- -1
J0<-with(data, eval(gradexp))
Jac<-attr(J0,"gradient")
jeval<-jeval+1
if (any(is.na(Jac))) stop("NaN in Jacobian")
gjty<-t(Jac)%*%resbest
for (i in 1:npar){
bmi<-bdmsk[i]
if (bmi==0) {
gjty[i]<-0
Jac[,i]<-0
}
if (bmi<0) {
if((2+bmi)*gjty[i] > 0) {
bdmsk[i]<-1
if (trace) cat("freeing parameter ",i," now at ",pnum[i],"\n")
} else {
gjty[i]<-0
Jac[,i]<-0
if (trace) cat("active bound ",i," at ",pnum[i],"\n")
if (trace) print(Jac)
}
}
}
JTJ<-crossprod(Jac)
gjty[mskdx]<-0
dde<-diag(diag(JTJ))+phiroot*diag(npar)
gjty<-as.numeric(gjty)
if (trace && watch) {
cat("gjty:")
print(gjty)
cat("JTJ\n")
print(JTJ)
cat("dde")
print(dde)
cat("bdmsk:")
print(bdmsk)
}
}
Happ<-JTJ+lamda*dde
if (trace && watch) {
cat("Happ\n")
print(Happ)
}
delta<-try(solve(Happ,-gjty))
if (class(delta)=="try-error") {
if (lamda<1000*.Machine$double.eps) lamda<-1000*.Machine$double.eps
lamda<-laminc*lamda
newjac<-FALSE
if (trace) cat(" Equation solve failure\n")
print(Happ)
print(gjty)
feval<-feval+1
print(pnum)
tmp<-readline("continue")
} else {
gproj<-crossprod(delta,gjty)
gangle<-gproj/sqrt(crossprod(gjty)*crossprod(delta))
if (trace) cat("gradient projection0 = ",gproj," gangle=",gangle,"\n")
if (gproj >= 0) {
if (lamda<1000*.Machine$double.eps) lamda<-1000*.Machine$double.eps
lamda<-laminc*lamda
newjac<-FALSE
if (trace) cat(" Uphill search direction\n")
} else {
delta[mskdx]<-0
delta<-as.numeric(delta)
if (trace && watch) {
cat("delta:")
print(delta)
}
step<-rep(1,npar)
for (i in 1:npar){
bd<-bdmsk[i]
da<-delta[i]
if (bd==0 || ((bd==-3) && (da<0)) ||((bd==-1)&& (da>0))) {
delta[i]<-0
} else {
if (delta[i]>0) step[i]<-(upper[i]-pbest[i])/delta[i]
if (delta[i]<0) step[i]<-(lower[i]-pbest[i])/delta[i]
}
}
stepsize<-min(1,step[which(delta!=0)])
if (trace) cat("Stepsize=",stepsize,"\n")
if (stepsize<.Machine$double.eps) {
if (lamda<1000*.Machine$double.eps) lamda<-1000*.Machine$double.eps
lamda<-laminc*lamda
newjac<-FALSE
if (trace) cat(" Stepsize too small\n")
} else {
pnum<-pbest+stepsize*delta
names(pnum)<-pnames
eqcount<-length(which((offset+pbest)==(offset+pnum)))
if (eqcount<npar) {
for (i in 1:npar){
joe<-paste(pnames[[i]],"<-",pnum[[i]])
eval(parse(text=joe))
}
feval<-feval+1
resid<-with(data, eval(parse(text=resexp)))
print(pnum)
ssquares<-as.numeric(crossprod(resid))
print(ssquares)
if (is.na(ssquares) ) ssquares<-.Machine$double.xmax
if (ssquares>=ssbest) {
if (lamda<1000*.Machine$double.eps) lamda<-1000*.Machine$double.eps
lamda<-laminc*lamda
newjac<-FALSE
if(trace) showpoint(ssquares, pnum)
} else {
lamda<-lamdec*lamda/laminc
if (trace) {
cat("<<")
showpoint(ssquares, pnum)
}
ssbest<-ssquares
resbest<-resid
pbest<-pnum
newjac<-TRUE
}
} else {
if (trace) cat("No parameter change\n")
}
}
}
}
if (watch) tmp<-readline()
}
pnum<-as.vector(pnum)
result<-list(resid=resbest, jacobian=Jac, feval=feval, jeval=jeval, coeffs=pnum, ssquares=ssbest)
} |
animint2HTML <- function(plotList) {
res <- animint2dir(plotList, out.dir = "animint-htmltest",
open.browser = FALSE)
remDr$refresh()
Sys.sleep(1)
res$html <- getHTML()
res
}
translatePattern <-
paste0("translate[(]",
"(?<x>.*?)",
",",
"(?<y>.*?)",
"[)]")
acontext <- function(...){
print(...)
context(...)
}
str_match_perl <- function(string,pattern){
stopifnot(is.character(string))
stopifnot(is.character(pattern))
stopifnot(length(pattern)==1)
parsed <- regexpr(pattern,string,perl=TRUE)
captured.text <- substr(string,parsed,parsed+attr(parsed,"match.length")-1)
captured.text[captured.text==""] <- NA
captured.groups <- do.call(rbind,lapply(seq_along(string),function(i){
st <- attr(parsed,"capture.start")[i,]
if(is.na(parsed[i]) || parsed[i]==-1)return(rep(NA,length(st)))
substring(string[i],st,st+attr(parsed,"capture.length")[i,]-1)
}))
result <- cbind(captured.text,captured.groups)
colnames(result) <- c("",attr(parsed,"capture.names"))
result
}
str_match_all_perl <- function(string,pattern){
stopifnot(is.character(string))
stopifnot(is.character(pattern))
stopifnot(length(pattern)==1)
parsed <- gregexpr(pattern,string,perl=TRUE)
lapply(seq_along(parsed),function(i){
r <- parsed[[i]]
starts <- attr(r,"capture.start")
if(r[1]==-1)return(matrix(nrow=0,ncol=1+ncol(starts)))
names <- attr(r,"capture.names")
lengths <- attr(r,"capture.length")
full <- substring(string[i],r,r+attr(r,"match.length")-1)
subs <- substring(string[i],starts,starts+lengths-1)
m <- matrix(c(full,subs),ncol=length(names)+1)
colnames(m) <- c("",names)
if("name" %in% names){
rownames(m) <- m[, "name"]
}
m
})
}
getSelectorWidgets <- function(html=getHTML()){
tr.list <- getNodeSet(html,
'//table[@class="table_selector_widgets"]//tr')
td.list <- sapply(tr.list[-1], function(tr)xmlChildren(tr)[[1]])
sapply(td.list, xmlValue)
}
clickHTML <- function(...){
v <- c(...)
stopifnot(length(v) == 1)
e <- remDr$findElement(names(v), as.character(v))
e$clickElement()
Sys.sleep(1)
getHTML()
}
clickID <- function(...){
v <- c(...)
stopifnot(length(v) == 1)
e <- remDr$findElement("id", as.character(v))
e$clickElement()
}
getHTML <- function(){
XML::htmlParse(remDr$getPageSource(), asText = TRUE)
}
rgba.pattern <- paste0(
"(?<before>rgba?)",
" *[(] *",
"(?<red>[0-9]+)",
" *, *",
"(?<green>[0-9]+)",
" *, *",
"(?<blue>[0-9]+)",
"(?:",
" *, *",
"(?<alpha>[^)]+)",
")?",
" *[)]")
ensure_rgba <- function(color.vec){
match.mat <- str_match_perl(color.vec, rgba.pattern)
is.not.rgb <- is.na(match.mat[,1])
hex.vec <- toRGB(color.vec[is.not.rgb])
not.rgb.mat <- col2rgb(hex.vec, alpha=TRUE)
rgb.cols <- c("red", "green", "blue")
match.mat[is.not.rgb, rgb.cols] <- t(not.rgb.mat[rgb.cols,])
match.mat[is.not.rgb, "alpha"] <- not.rgb.mat["alpha",]/255
is.rgb <- match.mat[, "before"] == "rgb"
match.mat[is.rgb, "alpha"] <- 1
is.transparent <- match.mat[, "alpha"] == 0
match.mat[, rgb.cols] <- 0
opacity <- as.numeric(match.mat[, "alpha"])
if(any(is.na(opacity))){
print(match.mat)
stop("missing alpha opacity value")
}
match.mat[, "alpha"] <- paste(opacity)
rgba.cols <- c(rgb.cols, "alpha")
rgba.mat <- matrix(match.mat[, rgba.cols], nrow(match.mat), length(rgba.cols))
no.paren <- apply(rgba.mat, 1, function(x)paste(x, collapse=", "))
paste0("rgba(", no.paren, ")")
}
stopifnot(ensure_rgba("transparent") == ensure_rgba("rgba(0, 0, 0, 0.0)"))
stopifnot(ensure_rgba("rgba(0, 0, 0, 0.0)") == ensure_rgba("rgba(0, 0, 0, 0)"))
stopifnot(ensure_rgba("rgba(0, 0, 0, 0.1)") != ensure_rgba("rgba(0, 0, 0, 0)"))
stopifnot(ensure_rgba("rgb(0, 0, 0)") == ensure_rgba("rgba(0, 0, 0, 1)"))
expect_color <- function(computed.vec, expected.vec) {
computed.rgb <- ensure_rgba(computed.vec)
expected.rgb <- ensure_rgba(expected.vec)
expect_identical(computed.rgb, expected.rgb)
}
expect_transform <- function(actual, expected, context = "translate", tolerance = 5) {
nocontext <- gsub(paste(context, collapse = "||"), "", actual)
vec <- gsub("\\)\\(", ",", nocontext)
clean <- gsub("\\)", "", gsub("\\(", "", vec))
nums <- as.numeric(strsplit(clean, split = "\\,")[[1]])
expect_equal(nums, expected, tolerance, scale = 1)
}
expect_links <- function(html, urls){
expect_attrs(html, "a", "href", urls)
}
expect_attrs <- function(html, element.name, attr.name, urls){
stopifnot(is.character(urls))
xpath <- paste0("//", element.name)
pattern <- paste0(attr.name, "$")
node.set <- getNodeSet(html, xpath)
rendered.urls <- rep(NA, length(node.set))
for(node.i in seq_along(node.set)){
node <- node.set[[node.i]]
node.attrs <- xmlAttrs(node)
href.i <- grep(pattern, names(node.attrs))
if(length(href.i)==1){
rendered.urls[[node.i]] <- node.attrs[[href.i]]
}
}
for(u in urls){
expect_true(u %in% rendered.urls)
}
}
expect_styles <- function(html, styles.expected){
stopifnot(is.list(styles.expected))
stopifnot(!is.null(names(styles.expected)))
geom <- getNodeSet(html, '//*[@class="geom"]')
style.strs <- as.character(sapply(geom, function(x) xmlAttrs(x)["style"]))
pattern <-
paste0("(?<name>\\S+?)",
": *",
"(?<value>.+?)",
";")
style.matrices <- str_match_all_perl(style.strs, pattern)
for(style.name in names(styles.expected)){
style.values <- sapply(style.matrices, function(m)m[style.name, "value"])
for(expected.regexp in styles.expected[[style.name]]){
expect_match(style.values, expected.regexp, all=FALSE)
}
}
}
getTextValue <- function(tick)xmlValue(getNodeSet(tick, "text")[[1]])
getStyleValue <- function(html, xpath, style.name) {
node.list <- getNodeSet(html, xpath)
style.vec <- sapply(node.list, function(node){
attr.vec <- xmlAttrs(node)
if("style" %in% names(attr.vec)){
attr.vec[["style"]]
}else{
NA
}
})
pattern <-paste0(
"(?<name>\\S+?)",
": *",
"(?<value>.+?)",
";")
style.matrices <- str_match_all_perl(style.vec, pattern)
sapply(style.matrices, function(m){
val.vec <- rep(NA, length(style.name))
if(1 < length(style.name))names(val.vec) <- style.name
found <- style.name %in% rownames(m)
if(any(found)){
style.found <- style.name[found]
val.vec[found] <- m[style.found, "value"]
}
val.vec
})
}
expect_no_warning <- function(object, regexp, ...){
expect_warning(object, NA)
}
getTransform <- function(tick)xmlAttrs(tick)[["transform"]]
getTickDiff <- function(doc, ticks = 1:2, axis="x"){
g.ticks <- getNodeSet(doc, "g[@class='tick major']")
tick.labs <- sapply(g.ticks, getTextValue)
names(g.ticks) <- tick.labs
tick.transform <- sapply(g.ticks[ticks], getTransform)
trans.mat <- str_match_perl(tick.transform, translatePattern)
num <- as.numeric(trans.mat[, axis])
val <- abs(diff(num))
attr(val, "label-diff") <- diff(as.numeric(names(tick.transform)))
val
}
both.equal <- function(x, tolerance = 0.1){
if(is.null(x) || !is.vector(x) || length(x) != 2){
return(FALSE)
}
isTRUE(all.equal(x[[1]], x[[2]], tolerance))
}
normDiffs <- function(xdiff, ydiff, ratio = 1) {
xlab <- attr(xdiff, "label-diff")
ylab <- attr(ydiff, "label-diff")
if (is.null(xlab) || is.null(ylab)) warning("label-diff attribute is missing")
c(ratio * xdiff / xlab, ydiff / ylab)
}
get_pixel_ranges <- function(html=NULL, geom_class=NULL){
if(is.null(html) || is.null(geom_class)){
stop("please specify html and geom_class")
}
nodes <- getNodeSet(html,
paste0('//g[@class="', geom_class, '"]//circle'))
attrs <- sapply(nodes, xmlAttrs)[c("cx", "cy"), ]
if(is.matrix(attrs)){
xranges <- range(as.numeric(attrs[1, ]), na.rm = T)
yranges <- range(as.numeric(attrs[2, ]), na.rm = T)
}else if(is.vector(attrs) && length(attrs) == 2){
xranges <- range(as.numeric(attrs[["cx"]]), na.rm = T)
yranges <- range(as.numeric(attrs[["cy"]]), na.rm = T)
}else{
return(NULL)
}
return(list(x=xranges, y=yranges))
}
unequal <- function(object, expected, ...){
!isTRUE(all.equal(object, expected, ...))
} |
cv.env <- function(X, Y, u, m, nperm) {
X <- as.matrix(X)
a <- dim(Y)
n <- a[1]
r <- a[2]
p <- ncol(X)
prederr <- rep(0, nperm)
for (i in 1:nperm) {
id <- sample(n, n)
Xn <- as.matrix(X[id, ])
Yn <- Y[id, ]
for (j in 1:m) {
id.test <- (floor((j - 1) * n / m) + 1) : ceiling(j * n / m)
id.train <- setdiff(1:n, id.test)
X.train <- Xn[id.train, ]
Y.train <- Yn[id.train, ]
X.test <- Xn[id.test, ]
Y.test <- Yn[id.test, ]
n.test <- length(id.test)
fit <- env(X.train, Y.train, u, asy = F)
betahat <- fit$beta
muhat <- fit$mu
resi <- as.matrix(Y.test - matrix(1, n.test, 1) %*% t(muhat) - as.matrix(X.test) %*% t(betahat))
sprederr <- apply(resi, 1, function(x) sum(x ^ 2))
prederr[i] <- prederr[i] + sum(sprederr)
}
}
return(sqrt(mean(prederr / n)))
} |
AffySimStudy <- function(n, M, eps, seed = 123, eps.lower = 0, eps.upper = 0.05,
steps = 3L, fsCor = TRUE, contD,
plot1 = FALSE, plot2 = FALSE, plot3 = FALSE){
stopifnot(n >= 3)
stopifnot(eps >= 0, eps <= 0.5)
if(plot1){
from <- min(-6, q.l(contD)(1e-15))
to <- max(6, q.l(contD)(1-1e-15))
curve(pnorm, from = from, to = to, lwd = 2, n = 201,
main = "Comparison: ideal vs. real", ylab = "cdf")
fun <- function(x) (1-eps)*pnorm(x) + eps*p(contD)(x)
curve(fun, from = from, to = to, add = TRUE, col = "orange",
lwd = 2, n = 201, ylab = "cdf")
legend("topleft", legend = c("ideal", "real"),
fill = c("black", "orange"))
}
set.seed(seed)
r <- rbinom(n*M, prob = eps, size = 1)
Mid <- rnorm(n*M)
Mcont <- r(contD)(n*M)
Mre <- matrix((1-r)*Mid + r*Mcont, ncol = n)
ind <- rowSums(matrix(r, ncol = n)) >= n/2
while(any(ind)){
M1 <- sum(ind)
cat("Samples to re-simulate:\t", M1, "\n")
r <- rbinom(n*M1, prob = eps, size = 1)
Mid <- rnorm(n*M1)
Mcont <- r(contD)(n*M1)
Mre[ind,] <- (1-r)*Mid + r*Mcont
ind[ind] <- rowSums(matrix(r, ncol = n)) >= n/2
}
rm(Mid, Mcont, r, ind)
if(plot2){
ind <- if(M <= 20) 1:M else sample(1:M, 20)
if(plot1) dev.new()
M1 <- min(M, 20)
print(
stripplot(rep(1:M1, each = n) ~ as.vector(Mre[ind,]),
ylab = "samples", xlab = "x", pch = 20,
main = ifelse(M <= 20, "Samples", "20 randomly chosen samples"))
)
}
Mean <- rowMeans(Mre)
Sd <- sqrt(rowMeans((Mre-Mean)^2))
Median <- rowMedians(Mre)
Mad <- rowMedians(abs(Mre - Median))/qnorm(0.75)
Tukey <- apply(Mre, 1, function(x) tukey.biweight(x))
Tukey <- cbind(Tukey, Mad)
RadMinmax <- estimate(rowRoblox(Mre, eps.lower = eps.lower,
eps.upper = eps.upper, k = steps,
fsCor = fsCor))
if(plot3){
Ergebnis1 <- list(Mean, Median, Tukey[,1], RadMinmax[,1])
Ergebnis2 <- list(Sd, Mad, RadMinmax[,2])
myCol <- brewer.pal(4, "Dark2")
if(plot1 || plot2) dev.new()
layout(matrix(c(1, 1, 1, 1, 3, 2, 2, 2, 2, 3), ncol = 2))
boxplot(Ergebnis1, col = myCol, pch = 20, main = "Location")
abline(h = 0)
boxplot(Ergebnis2, col = myCol[c(1,2,4)], pch = 20, main = "Scale")
abline(h = 1)
op <- par(mar = rep(2, 4))
plot(c(0,1), c(1, 0), type = "n", axes = FALSE)
legend("center", c("ML", "Med/MAD", "biweight", "rmx"),
fill = myCol, ncol = 4, cex = 1.5)
on.exit(par(op))
}
MSE1.1 <- n*mean(Mean^2)
MSE2.1 <- n*mean(Median^2)
MSE3.1 <- n*mean(Tukey[,1]^2)
MSE4.1 <- n*mean(RadMinmax[,1]^2)
empMSE <- data.frame(ML = MSE1.1, Med = MSE2.1, Tukey = MSE3.1, "rmx" = MSE4.1)
rownames(empMSE) <- "n x empMSE (loc)"
relMSE <- empMSE[1,]/empMSE[1,4]
empMSE <- rbind(empMSE, relMSE)
rownames(empMSE)[2] <- "relMSE (loc)"
MSE1.2 <- n*mean((Sd-1)^2)
MSE2.2 <- n*mean((Mad-1)^2)
MSE3.2 <- MSE2.2
MSE4.2 <- n*mean((RadMinmax[,2]-1)^2)
empMSE <- rbind(empMSE, c(MSE1.2, MSE2.2, MSE3.2, MSE4.2))
rownames(empMSE)[3] <- "n x empMSE (scale)"
relMSE <- empMSE[3,]/empMSE[3,4]
empMSE <- rbind(empMSE, relMSE)
rownames(empMSE)[4] <- "relMSE (scale)"
empMSE <- rbind(empMSE, c(MSE1.1 + MSE1.2, MSE2.1 + MSE2.2, MSE3.1 + MSE3.2,
MSE4.1 + MSE4.2))
rownames(empMSE)[5] <- "n x empMSE (loc + scale)"
relMSE <- empMSE[5,]/empMSE[5,4]
empMSE <- rbind(empMSE, relMSE)
rownames(empMSE)[6] <- "relMSE (loc + scale)"
empMSE
} |
context("add_default_solver")
test_that("implicit default solver", {
skip_on_cran()
skip_if_no_fast_solvers_installed()
data(sim_pu_raster, sim_features)
p <- problem(sim_pu_raster, sim_features) %>%
add_min_set_objective() %>%
add_relative_targets(0.1) %>%
add_proportion_decisions()
s <- solve(p)
expect_true(inherits(s, "Raster"))
expect_equal(raster::nlayers(s), 1)
expect_true(raster::compareRaster(sim_pu_raster, s, res = TRUE, crs = TRUE,
tolerance = 1e-5, stopiffalse = FALSE))
})
test_that("raster planning unit data", {
skip_on_cran()
skip_if_no_fast_solvers_installed()
data(sim_pu_raster, sim_features)
p <- problem(sim_pu_raster, sim_features) %>%
add_min_set_objective() %>%
add_relative_targets(0.1) %>%
add_binary_decisions() %>%
add_default_solver(time_limit = 5, verbose = FALSE)
s <- solve(p)
expect_true(inherits(s, "Raster"))
expect_equal(raster::nlayers(s), 1)
expect_true(raster::compareRaster(sim_pu_raster, s, res = TRUE, crs = TRUE,
tolerance = 1e-5, stopiffalse = FALSE))
})
test_that("spatial planning unit data", {
skip_on_cran()
skip_if_no_fast_solvers_installed()
data(sim_pu_polygons, sim_features)
p <- problem(sim_pu_polygons, sim_features, "cost") %>%
add_min_set_objective() %>%
add_relative_targets(0.1) %>%
add_binary_decisions() %>%
add_default_solver(time_limit = 5, verbose = FALSE)
s <- solve(p)
expect_true(inherits(s, "SpatialPolygonsDataFrame"))
expect_equal(length(s), length(sim_pu_polygons))
expect_equal(s@polygons, sim_pu_polygons@polygons)
expect_true(sf::st_crs(s@proj4string) ==
sf::st_crs(sim_pu_polygons@proj4string))
}) |
check_logfile_existence <- function() {
if (file.exists(LOGFILE_PATH)) {
print("load logfile")
logfile <- read.csv(LOGFILE_PATH, sep = "\t", stringsAsFactors = F)
} else {
print("create logfile")
logfile <- data.frame(file_name = NA, seed = NA, formula_x = NA, formula_y = NA)
}
} |
localYule<-
function (X)
{
sumrow <- apply(X, 1, sum)
sumcol <- apply(X, 2, sum)
n <- sum(X)
result <- X
for (i in (1:nrow(X))) {
for (j in (1:ncol(X))) {
a <- X[i, j]
b <- sumrow[i] - a
c <- sumcol[j] - a
d <- n - a - b - c
Q <- (a * d - b * c)/(a * d + b * c)
result[i,j] <- Q
}
}
result
} |
maxv12 <-
function(theta=30, phi=30, inc=25, lseq=200, ticktype="detailed", diagnose=FALSE, verbose=TRUE)
{
MC <- match.call()
if(verbose) {
print("", quote = F)
print("Running maxv12", quote = F)
print("", quote = F)
print(date(), quote = F)
print("", quote = F)
print("Call:", quote = F)
print(MC)
print("", quote = F)
}
simpleprod <- function(x,y){sqrt(x*y)}
cycle <- TRUE
x <- seq(-1, 1, length.out = lseq)
y <- x
x <- x[x>=0]
y <- y[y>=0]
z <- outer(x,y,simpleprod)
oldpar <- graphics::par(bg = "white")
td <- theta
ph <- phi
while(cycle){
graphics::persp(x, y, z, theta = td, phi = ph, expand = 0.5, col = "lightblue",ticktype="detailed",xlab="V1",ylab="V2",zlab="V12")
graphics::title(sub=".")
graphics::title(main = "Maximum absolute value of off-diagonal variable V12 \nin 2x2 symmetric positive definite matrix\nas a function of diagonal variables, V1 and V2")
print("Click on R Console and then",quote=F)
print("", quote = F)
print("press 'u' to roll view up", quote=F)
print(" 'd' to roll view down", quote=F)
print(" 'r' to roll view to right", quote=F)
print(" 'l' to roll view to left", quote=F)
print(" 'x' to exit program", quote=F)
print("", quote = F)
print("After each letter, press 'Enter'", quote=F)
vv <- readline("Waiting for you . . . ")
if(vv == "u") ph <- ph - inc
if(vv == "d") ph <- ph + inc
if(vv == "r") td <- td - inc
if(vv == "l") td <- td + inc
if(vv == "x"){
cycle <- FALSE
break
}
}
graphics::par(oldpar)
if(verbose) {
print("", quote = F)
print("Finished running maxv12", quote = F)
print("", quote = F)
print(date(), quote = F)
print("", quote = F)
}
list(theta=td, phi=ph, inc=inc, lseq=lseq, ticktype=ticktype, Call=MC)
} |
heterogeneity <- function(x) {
x.whitened <- na.contiguous(ar(x)$resid)
x.archtest <- arch_stat(x.whitened)
LBstat <- sum(acf(x.whitened^2, lag.max = 12L, plot = FALSE)$acf[-1L]^2)
garch.fit <- suppressWarnings(tseries::garch(x.whitened, trace = FALSE))
garch.fit.std <- residuals(garch.fit)
x.garch.archtest <- arch_stat(garch.fit.std)
LBstat2 <- NA
try(LBstat2 <- sum(acf(na.contiguous(garch.fit.std^2), lag.max = 12L, plot = FALSE)$acf[-1L]^2),
silent = TRUE
)
output <- c(
arch_acf = LBstat,
garch_acf = LBstat2,
arch_r2 = unname(x.archtest),
garch_r2 = unname(x.garch.archtest)
)
return(output)
}
nonlinearity <- function(x) {
X2 <- tryCatch(tseries::terasvirta.test(as.ts(x), type = "Chisq")$stat,
error = function(e) NA)
c(nonlinearity = 10 * unname(X2) / length(x))
}
arch_stat <- function(x, lags = 12, demean = TRUE) {
if (length(x) <= lags+1) {
return(c(ARCH.LM = NA_real_))
}
if (demean) {
x <- x - mean(x, na.rm = TRUE)
}
mat <- embed(x^2, lags + 1)
fit <- try(lm(mat[, 1] ~ mat[, -1]), silent = TRUE)
if ("try-error" %in% class(fit)) {
return(c(ARCH.LM = NA_real_))
} else {
arch.lm <- summary(fit)
S <- arch.lm$r.squared
return(c(ARCH.LM = if(is.nan(S)) 1 else S))
}
} |
rawToDisplay <- function( raws )
{
raws[ raws <= charToRaw("\037") ] <- charToRaw(".")
raws[ raws >= charToRaw("\177") ] <- charToRaw(".")
rawToChar(raws)
} |
plot.unireg <- function(x, onlySpline=FALSE, type="l", xlab="x", ylab=NULL, col="black", ...){
constr <- x$constr
if(is.null(ylab)){if(constr=="none"){constr <- "unconstrained"}
if(constr=="invuni"){constr <- "inverse unimodal"}
ylab <- paste("Fitted", constr, "spline function")
}
if(!onlySpline){
plot(x$x,x$y, xlab=xlab, ylab=ylab, ...)
points(x, type=type, col=col, ...)
}else{minx <- min(diff(unique(x$x)))
z <- seq(x$a, x$b, by=minx/10)
plot(z, predict.unireg(x,z), type=type, xlab=xlab, ylab=ylab, col=col, ...)
}
} |
check_projection <- function(projection,
abort = FALSE,
verbose = TRUE) {
UseMethod("check_projection")
}
check_projection.default <- function(projection,
abort = FALSE,
verbose = TRUE) {
call <- match.call()
if (abort) {
stop("check_projection --> ", call[[2]], " is not a valid epsg code or ",
"WKT projection description. Aborting!")
} else {
if (verbose) {
warning("check_projection --> ", call[[2]], " is not a valid epsg code or ",
"WKT projection description. returning `NA`")
}
return(NA)
}
}
check_projection.numeric <- function(projection,
abort = FALSE,
verbose = TRUE) {
proj <- sf::st_crs(projection)
if (is.na(proj$epsg)){
if (abort == TRUE) {
stop("check_projection --> Invalid EPSG code detected! Aborting!")
} else {
if (verbose) warning("check_projection --> Invalid EPSG code detected,
returning `NA`!")
return(NA)
}
} else {
return(projection)
}
}
check_projection.character <- function(projection,
abort = FALSE,
verbose = TRUE) {
if (suppressWarnings(!is.na(as.numeric(projection)))) {
return(check_projection.numeric(as.integer(projection),
abort = abort))
}
if (grepl("^[0-9]+[NnSs]$",projection)) {
utm_zone <- stringr::str_pad(gsub("[NnSs]$","",projection), 2, "left", "0")
utm_ns <- toupper(gsub("?[0-9]+","",projection))
projection <- as.numeric(paste0("32",
if (utm_ns == "N") {"6"} else {"7"},
utm_zone))
return(projection)
}
projection_crs <- try(sf::st_crs(projection))
if (inherits(projection_crs, "try-error") || is.na(projection_crs$proj4string)) {
if (abort == TRUE) {
stop("check_projection --> Invalid projection detected! Aborting!")
} else {
if (verbose) (warning("check_projection --> Invalid projection detected,
returning `NA`!"))
return(NA)
}
} else {
return(projection)
}
}
check_projection.crs <- function(projection,
abort = FALSE,
verbose = TRUE) {
return(projection)
} |
computePcaNbDims <- function(sdev, pca.variance.cum.min=0.9) {
message("PCA number of dimensions computing")
pca.variance <- sdev^2/sum(sdev^2)
pca.variance.cum <- cumsum(pca.variance)
pca.nb.dims <- min(which(pca.variance.cum >= pca.variance.cum.min))
}
computeKmeans <- function(x, K=0, K.max=20, kmeans.variance.min=0.95, graph=F) {
K.max <- min(nrow(x), K.max)
if (K.max <= 2)
K <- K.max
if (K==0) {
message("K-means computing and K estimation: method Elbow")
kmax <- min(ceiling(sqrt(nrow(x)/2)), K.max)
res <- KmeansAutoElbow(x, Kmax=kmax, kmeans.variance.min, graph)
res.kmeans <- res$res.kmeans
message(paste(" obtained K=", res$K))
} else {
message("K-means computing: method Quick")
res.kmeans <- KmeansQuick(x, K=K)
}
res.kmeans
}
computeEM <- function(x, K=0, K.max=20, kmeans.variance.min=0.95, graph=F, Mclust.options=list()) {
Within <- NULL
if (K==0) {
message("EM computing and K estimation: method Elbow")
kmax <- min(ceiling(sqrt(nrow(x)/2)), K.max)
res <- KmeansAutoElbow(x, Kmax=kmax, kmeans.variance.min, graph)
Within <- res$res.kmeans[["Withins_tot"]]
K <- res$K
message(paste(" obtained K=", res$K))
}
if (K<2)
stop("EM computing requires several features (nb.cols >= 2).")
res.EM <- do.call(mclust::Mclust, c(list(x, G=K), Mclust.options))
if (is.null(res.EM$classification)){
stop("No clustering found for this sample with EM, try with another K")
}
res.EM[["Withins_tot"]]=Within
res.EM
}
guessFileEncoding <- function(file.name)
{
stringi::stri_enc_detect(rawToChar(readBin(file.name, "raw")))[[1]][1,1]
}
sortCharAsNum <- function(char.vec, ...)
{
ok <- T
vec <- suppressWarnings(as.numeric(char.vec))
if (any(is.na(vec)))
{
vec <- char.vec
ok <- F
}
res <- order(vec, ...)
char.vec[res]
}
convNamesToIndex <- function(name.sample, full.name.set)
{
sapply(name.sample, function(name) which(full.name.set == name))
}
convNamesPairsToIndexPairs <- function(pair.list, full.name.set)
{
pair.matrix <- NULL
if (!length(pair.list)){
pair.matrix <- matrix(0,nrow=0,ncol=2)
} else {
pair.list <- sapply(pair.list, function(ligne) convNamesToIndex(ligne, full.name.set), simplify=F)
pair.matrix <- do.call(rbind, pair.list)
colnames(pair.matrix) <- NULL
pair.matrix <- pair.matrix[apply(pair.matrix,1,function(ligne) all(!is.na(ligne))),,drop=F]
}
pair.matrix
}
computeCKmeans <- function(x, K=0, K.max=20, mustLink=NULL, cantLink=NULL, maxIter=2, kmeans.variance.min=0.95) {
Within <- NULL
mustLink <- convNamesPairsToIndexPairs(mustLink, row.names(x))
cantLink <- convNamesPairsToIndexPairs(cantLink, row.names(x))
if (K==0) {
message("Constrained K-means computing and K estimation: method Elbow")
kmax <- min(ceiling(sqrt(nrow(x)/2)), K.max)
res <- KmeansAutoElbow(x, Kmax = kmax, kmeans.variance.min)
Within <- res$res.kmeans[["Withins_tot"]]
label <- conclust::mpckm(x, k = res$K, mustLink, cantLink, maxIter)
message(paste(" obtained K=", res$K))
} else {
message("Constrained K-means computing")
label <- conclust::mpckm(x, k = K, mustLink, cantLink, maxIter)
}
res.ckmeans <- list(label=label, Within=Within)
res.ckmeans
}
computeCSC <- function(x, K=0, K.max=20, mustLink=list(), cantLink=list(), alphas=seq(from=0, to=1, length=100)) {
if (length(mustLink)){
mustLink <- sapply(mustLink, function(ligne) convNamesToIndex(ligne, row.names(x)), simplify=F)
mustLink <- mustLink[sapply(mustLink,function(ligne) all(!is.na(ligne)))]
}
if (length(cantLink)){
cantLink <- sapply(cantLink, function(ligne) convNamesToIndex(ligne, row.names(x)), simplify=F)
cantLink <- cantLink[sapply(cantLink,function(ligne) all(!is.na(ligne)))]
}
sim <- computeGaussianSimilarityZP(x, 7)
res.csc <- KwaySSSC(sim, K=K, list.ML=mustLink, list.CNL=cantLink,
alphas=alphas, K.max=K.max)
res.csc
}
computeSampling <- function(x, label=NULL, K=0, toKeep = NULL, sampling.size.max=3000, K.max=20, kmeans.variance.min=0.95) {
if (!sampling.size.max)
sampling.size.max <- 3000
nrx <- nrow(x)
if ((K>0) && (K>nrx))
K <- nrx
if (K.max > nrx)
K.max <- nrx
if (is.null(label)) {
res.kmeans <- computeKmeans(x, K=K, K.max=K.max,
kmeans.variance.min=kmeans.variance.min, graph=F)
label <- res.kmeans$cluster
label_prob <- stats::ave(label,label,FUN=length)
label_prob <- 1/(label_prob*max(unname(label)))
}
selection <- sample(rownames(x),min(sampling.size.max,nrow(x)),prob=label_prob)
selection <- by(selection, label[selection],
function (x) {x})
selection <- sapply(selection, as.character)
if (!is.null(toKeep)) {
toKeep <- unique(toKeep)
for (t in setdiff(toKeep, unlist(selection)))
selection[[label[t]]] <- c(selection[[label[t]]], t)
}
selection.ids <- sortCharAsNum(unlist(selection, use.names = FALSE))
selection.labs <- label[selection.ids]
res.knn <- class::knn(x[selection.ids,,drop=F], x, cl=selection.ids, k=1)
matching <- as.character(res.knn)
list(selection.ids=selection.ids, selection.labs=selection.labs, matching=matching, size.max=sampling.size.max, K=length(levels(label)))
}
computePcaSample <- function(data.sample, pca.nb.dims=0, selected.var=NULL, echo=F, prcomp.options=list(center=T, scale=T), pca.variance.cum.min=0.95) {
features <- list("pca_full"=NULL, "pca"=NULL)
numFeat <- colnames(data.sample$features[["preprocessed"]]$x)[sapply(data.sample$features[["preprocessed"]]$x, is.numeric)]
if (length(selected.var))
selected.var <- intersect(selected.var, numFeat)
if (!length(selected.var))
selected.var <- numFeat
available <- setequal(selected.var, colnames(data.sample$features$pca))
missing.data <- is.null(data.sample$features$pca)
if (missing.data || !available) {
if (echo) message("PCA computing")
df <- as.data.frame(data.sample$features[["preprocessed"]]$x[data.sample$id.clean, selected.var, drop=F])
df <- df[,apply(df, 2, stats::var, na.rm=TRUE) != 0]
if (all(dim(df) > 1)) {
res.pca <- do.call(stats::prcomp, c(list(df), prcomp.options))
rownames(res.pca$x) <- rownames(data.sample$features[["preprocessed"]]$x)[data.sample$id.clean]
features$pca$save <- res.pca
features$pca$x <- as.data.frame(res.pca$x)
features$pca$rotation <- res.pca$rotation
features$pca$sdev <- res.pca$sdev
features$pca$inertia.prop <- cumsum(res.pca$sdev^2)/sum(res.pca$sdev^2)
colnames(features$pca$x) <- paste("PC", 1:ncol(features$pca$x))
colnames(features$pca$rotation) <- paste("PC", 1:ncol(features$pca$rotation))
features$pca$logscale <- rep(FALSE, ncol(features$pca$x))
names(features$pca$logscale) <- colnames(features$pca$x)
features[["pca_full"]] <- features$pca
} else {
features <- data.sample$features[c("pca_full","pca")]
}
if (pca.nb.dims==0)
pca.nb.dims <- computePcaNbDims(features$pca$sdev, pca.variance.cum.min)
if (pca.nb.dims<2)
pca.nb.dims <- 2
if (echo) message(paste("Working on PCA, nb of principal components =", pca.nb.dims))
if (echo) message(paste("Information lost=", 100-round(features$pca$inertia.prop[pca.nb.dims]*100,2), "%"))
features[["pca"]]$x <- features$pca$x[,1:pca.nb.dims, drop=F]
features[["pca"]]$logscale <- features$pca$logscale[1:pca.nb.dims]
features[["pca"]]$rotation <- features$pca$rotation[1:pca.nb.dims]
features[["pca"]]$sdev <- features$pca$sdev[1:pca.nb.dims]
features[["pca"]]$inertia.prop <- features$pca$inertia.prop[1:pca.nb.dims]
features
} else
data.sample$features
}
computeSpectralEmbeddingSample <- function(data.sample, use.sampling = FALSE, sampling.size.max=0, scale=FALSE, selected.var = NULL, echo=F, RclusTool.env=initParameters()) {
this.call <- list(use.sampling=use.sampling, selected.var=selected.var)
if (use.sampling)
this.call[["selection.ids"]] <- data.sample$sampling$selection.ids
if (length(selected.var))
selected.var <- intersect(selected.var, colnames(data.sample$features[["preprocessed"]]$x)[sapply(data.sample$features[["preprocessed"]]$x, is.numeric)])
if (!length(selected.var))
selected.var <- colnames(data.sample$features[["preprocessed"]]$x)[sapply(data.sample$features[["preprocessed"]]$x, is.numeric)]
this.call[["selected.var"]] <- selected.var
x <- data.sample$features[["preprocessed"]]$x[data.sample$id.clean, selected.var, drop=F]
if (scale) {
x <- scale(x, center = TRUE, scale = TRUE)
}
if (use.sampling) {
if (is.null(data.sample$sampling) || (!is.null(data.sample$config$sampling.size.max)&&(data.sample$config$sampling.size.max!=sampling.size.max)))
{
data.sample$sampling <- computeSampling(x=x, K=RclusTool.env$param$classif$unsup$K.max,
sampling.size.max=RclusTool.env$param$preprocess$sampling.size.max, kmeans.variance.min=RclusTool.env$param$classif$unsup$kmeans.variance.min)
}
x <- x[data.sample$sampling$selection.ids, , drop=F]
}
if (echo) message("Similarity computing")
sim <- computeGaussianSimilarityZP(x, k = RclusTool.env$param$classif$unsup$nb.neighbours)
if (echo) message("Cluster number estimating")
res.gap <- computeGap(sim, Kmax = RclusTool.env$param$classif$unsup$K.max)
if (echo) message(paste(" obtained K = ", res.gap$Kmax))
K <- res.gap$Kmax
res.se <- spectralEmbeddingNg(sim, K)
features <- data.sample$features[["preprocessed"]]
features$call <- this.call
features$x <- as.data.frame(res.se$x)
features$gap <- res.gap$gap
features$eig <- res.gap$val
features$sampling <- TRUE
colnames(features$x) <- paste("SC", 1:ncol(features$x))
features$logscale <- rep(FALSE, ncol(res.se$x))
names(features$logscale) <- colnames(features$x)
features
}
removeZeros <- function(x, threshold=.Machine$double.eps, positive=FALSE) {
threshold <- abs(threshold)
clx <- class(x)
x <- as.matrix(x)
w = which(abs(x) <= threshold)
if (length(w)) {
s <- sign(x[w])
s[s==0] <- 1
if (positive)
s[s==-1] <- 1
x[w] <- s*threshold
}
if (clx == "data.frame")
x <- as.data.frame(x)
x
}
computeItems <- function (data.sample, method, cluster, modelFile) {
object <- readRDS(modelFile)
idxCluster <- which(data.sample$clustering[[method]]$label == cluster)
dat <- data.sample$features$initial$x[idxCluster,
intersect(names(data.sample$features$initial$x), names(object$model))]
if (class(object) == "lm")
pred <- stats::predict(object, newdata = dat)
if (class(object) == "lda")
pred <- stats::predict(object, newdata = dat)$class
if (class(object) == "mda")
pred <- stats::predict(object, newdata = dat)
data.sample$clustering[[method]]$nbItems[names(pred)] <- pred
data.sample
}
computeItemsGUI <- function(method.select = "K-means", RclusTool.env=RclusTool.env) {
itemtt <- tktoplevel()
tktitle(itemtt) <- "Process with items countings"
items.env <- new.env()
items.env$export.counts <- TRUE
items.env$cluster.select <- NULL
items.env$modelFile <- NULL
OnExportCounts <- function() {
items.env$export.counts <- tclvalue(tcl.export.counts) == "1"
}
OnClusterChange <- function() {
items.env$cluster.select <- tclvalue(tcl.cluster.select)
tkconfigure(tk.cluster.but, text = items.env$cluster.select)
}
buildMenuClusters <- function() {
tkconfigure(tk.cluster.but, text = items.env$cluster.select)
tkdelete(tk.cluster.menu, 0, "end")
for (name in levels(RclusTool.env$data.sample$clustering[[method.select]]$label))
tkadd(tk.cluster.menu, "radio", label = name, variable = tcl.cluster.select,
command = OnClusterChange)
}
onLoadModel <- function() {
items.env$modelFile <- tclvalue(tkgetOpenFile(filetypes = "{{RData Files} {.RData}}"))
if (!nchar(items.env$modelFile)) {
tkmessageBox(message = "No file selected!")
} else {
tkgrid(tklabel(itemtt, text=basename(items.env$modelFile)), row = 2, column = 3, columnspan = 2)
}
}
onApplyModel <- function() {
if (is.character(items.env$modelFile))
RclusTool.env$data.sample <- computeItems(data.sample = RclusTool.env$data.sample,
method = method.select, cluster = items.env$cluster.select, modelFile = items.env$modelFile)
if (items.env$export.counts) {
fileCounts.csv <- file.path(RclusTool.env$data.sample$files$results$clustering,
paste("counts ", RclusTool.env$operator.name, " ",
method.select, ".csv", sep=""))
saveCounts(fileCounts.csv, RclusTool.env$data.sample$clustering[[method.select]]$nbItems)
}
}
tkgrid(tklabel(itemtt, text=" "), row = 0, column = 0)
items.env$cluster.select <- levels(RclusTool.env$data.sample$clustering[[method.select]]$label)[1]
tcl.cluster.select <- tclVar(items.env$cluster.select)
tk.cluster.but <- tkmenubutton(itemtt, text = items.env$cluster.select, relief = "raised", width = 15)
tk.cluster.menu <- tkmenu(tk.cluster.but, tearoff = FALSE)
buildMenuClusters()
tkconfigure(tk.cluster.but, menu = tk.cluster.menu)
tkgrid(tk.cluster.but, row = 1, column = 1)
butLoad <- tk2button(itemtt, text = "Load model file", image = "csvFile", compound = "left", width = 30, command = onLoadModel)
tkgrid(butLoad, row = 1, column = 3, columnspan = 2)
tcl.export.counts <- tclVar(as.character(as.integer(items.env$export.counts)))
tk.export.counts <- tkcheckbutton(itemtt, text="", variable=tcl.export.counts,
command=OnExportCounts)
tkgrid(tk2label(itemtt, text="Export counts"), row=3, column=3, sticky="e")
tkgrid(tk.export.counts, row=3, column=4, sticky="w")
tkgrid(tklabel(itemtt, text=" "), row = 2, column = 2)
butApply <- tk2button(itemtt, text = "Apply model", width = -6, command = onApplyModel)
tkgrid(butApply, row = 4, column = 3, columnspan = 2)
tkgrid(tklabel(itemtt, text=" "), row = 5, column = 5)
tkwait.window(itemtt)
}
itemsModel <- function (dat, countFile, method = "mda") {
if (length(countFile) < 1 && !is.character(countFile))
stop("'countFile' must be a single (or multiple) character string(s)")
if (length(method) != 1 && !is.character(method))
stop("'method' must be a single character string")
if (!method %in% c("lm","lda","mda"))
stop("'method' must be one of 'lm', 'lda' or 'mda'")
class <- gsub("_itemsCount.RData", "", basename(countFile))
modelPath <- file.path(dirname(countFile), paste(class, "_itemsModel.RData", sep = ""))
message("Building predictive model...")
nbItems <- readRDS(countFile)
nbCounted <- nrow(nbItems)
if (nbCounted < 1) {
warning("Nothing counted for '", class, "'!", sep = "")
} else {
data2 <- dat[rownames(nbItems), sapply(dat, is.numeric)]
data2 <- data2[,-1]
form <- stats::as.formula(unlist(nbItems[, "Manual.Number.of.items"]) ~ .)
if (method == "lm")
model <- stats::lm(form, data = data2)
if (method == "lda")
model <- MASS::lda(form, data = data2)
if (method == "mda")
model <- mda::mda(form, data = data2, start.method = "kmeans",
keep.fitted = TRUE, method = mda::gen.ridge, iter = 10)
saveRDS(model, file = modelPath)
}
message("Done!")
}
countItems <- function(profile, feature = NULL, imgdir = NULL, image = NULL) {
opar <- graphics::par(no.readonly=TRUE)
on.exit(graphics::par(opar))
nbItemsTot <- NULL
nc <- ncol(profile)
grDevices::dev.new()
graphics::layout(matrix(c(1,2), 1, 2, byrow = TRUE), widths=c(4,4))
graphics::par(mar=c(3,3,2,.2))
if (!is.null(nc)) {
curve.names <- colnames(profile)
curve.colors <- c("black","blue","yellow","orange","red","palevioletred")
graphics::matplot(profile, pch=1:nc, type="o", col=curve.colors, main=image, ylab="level", cex = 0.8)
if (!is.null(curve.names))
graphics::legend("topright", legend=curve.names, col=curve.colors, pch=1:nc, cex=.8)
} else {
graphics::plot(1, col="white", axes=FALSE, xlab=NA, ylab=NA)
graphics::text(1, col = "black", labels = "No signals")
}
graphics::par(mar=c(5,.2,5,.2))
if (!is.null(image) && (!identical(image, ""))) {
imgFile <- file.path(imgdir, image)
readImg <- jpeg::readJPEG
if (!grepl(".jpg", imgFile))
readImg <- png::readPNG
if (grepl(".jpg", imgFile) || grepl(".png", imgFile)) {
img <- readImg(imgFile, native = FALSE)
gray <- 60 / 255
threshold <- 1 - 2 * gray
mask <- matrix(1, nrow = nrow(img[,,1]), ncol = ncol(img[,,1]))
mask[img[,,1] > threshold] <- 0
mask_erode <- mmand::erode(mask, c(1,1,1))
dimg <- dim(img)
h <- dimg[1]
w <- dimg[2]
rotate <- function(x) t(apply(x, 2, rev))
image(rotate(img[,,1]), col = gray((0:255)/255), axes = F)
graphics::title(sub = "1. Click 4 polygon vertices (subregion).\n2. Click items and right-click when done.\nClose windows to end.",
adj = 1, font.sub = 2, cex.sub = .8)
rectCoord <- graphics::locator(4, type = "o", col = "blue", pch = 16, cex = 2)
graphics::polygon(rectCoord$x, rectCoord$y, border = "blue")
xSub <- dim(mask_erode)[1] - round(rectCoord$y*dim(mask_erode)[1])
ySub <- round(rectCoord$x*dim(mask_erode)[2])
idxTot <- which(mask_erode == 0, arr.ind=TRUE)
idx <- sp::point.in.polygon(idxTot[,1], idxTot[,2], xSub, ySub, mode.checked = FALSE)
pixSub <- length(which(idx==1))
nb <- graphics::locator(10000, type = "p", col = "red", pch = 16, cex = 2)
n <- length(nb$x)
densiteSub <- n/pixSub
pixTot <- length(which(mask_erode==0))
nbItemsTot <- densiteSub * pixTot
}
} else {
graphics::plot(1, col= "white", axes=FALSE, xlab=NA, ylab=NA)
graphics::text(1, col = "black", labels = "No image")
}
grDevices::dev.off()
nbItemsTot
}
countItemsGUI <- function (RclusTool.env=initParameters()) {
imgdir <- tk_choose.dir()
if (is.na(imgdir))
return(invisible(NULL))
countPath <- file.path(dirname(imgdir), paste(basename(imgdir), "_itemsCount.RData", sep = ""))
reset <- FALSE
if (file.exists(countPath)) {
nbItems <- readRDS(countPath)
ncount <- nrow(nbItems)
if (ncount > 0) {
if (ncount == 1) {
msg <- "There is one image processed. Do you want to keep its count?"
} else msg <- paste("There are", ncount,
"images already processed. Do you want to keep these counts?")
res <- tkmessageBox(message = msg, icon = "question", type = "yesnocancel", default = "yes")
if (tclvalue(res) == "cancel") return(invisible(NULL))
reset = (tclvalue(res) == "no")
}
}
if (!(file.exists(countPath)) || isTRUE(reset))
nbItems <- NULL
img <- list.files(imgdir, pattern = ".jpg")
for (i in 1:length(img)) {
imgNum <- gsub(".jpg", "", img[i])
imgNum <- as.numeric(imgNum)
if (!(imgNum %in% row.names(nbItems))) {
nb <- c(RclusTool.env$data.sample$features$initial$x[imgNum,],
countItems(profile = RclusTool.env$data.sample$profiles[[imgNum]],
feature = RclusTool.env$data.sample$features$initial$x[imgNum,],
imgdir = imgdir, image = img[i]))
nbItems <- rbind(nbItems, nb)
rownames(nbItems)[nrow(nbItems)] <- imgNum
colnames(nbItems)[ncol(nbItems)] <- "Manual.Number.of.items"
message(nbItems)
}
}
saveRDS(nbItems, countPath)
itemsModel(dat = RclusTool.env$data.sample$features$initial$x, countFile = countPath, method = "lm")
}
toStringDataFrame = function (object, digits=NULL) {
nRows = length(row.names(object));
if (length(object)==0) {
return(paste(
sprintf(ngettext(nRows, "data frame with 0 columns and %d row", "data frame with 0 columns and %d rows")
, nRows)
, "\\n", sep = "")
);
} else if (nRows==0) {
return(gettext("<0 rows> (or 0-length row.names)\\n"));
} else {
m = as.matrix(format.data.frame(object, digits=digits, na.encode=FALSE));
m = rbind(dimnames(m)[[2]], m);
maxLen = apply(apply(m, c(1,2), stringr::str_length), 2, max, na.rm=TRUE);
m = t(apply(m, 1, stringr::str_pad, width=maxLen, side="right"));
m = t(apply(m, 1, stringr::str_pad, width=maxLen+3, side="left"));
m = apply(m, 1, paste, collapse="");
return(paste(m, collapse="\n"));
}
} |
context("Setting graph/global attributes")
test_that("Setting a graph name can be done", {
graph <- create_graph()
graph_name <-
graph %>%
set_graph_name(name = "test_that_name")
expect_true(
graph_name$graph_info$graph_name == "test_that_name")
graph_1 <-
graph %>%
add_node() %>%
add_node() %>%
add_edge(
from = 1,
to = 2) %>%
select_nodes_by_id(nodes = 1)
graph_name_1 <-
set_graph_name(
graph = graph_1,
name = "test_that_name_again")
expect_true(
graph_name_1$graph_info$graph_name == "test_that_name_again")
})
test_that("Setting a time for the graph can be done", {
graph <- create_graph()
graph_1 <-
set_graph_time(
graph = graph,
time = "2015-10-25 15:23:00")
expect_true(
graph_1$graph_info$graph_time == "2015-10-25 15:23:00")
expect_true(
graph_1$graph_info$graph_tz == "GMT")
graph_2 <-
set_graph_time(
graph = graph_1,
tz = "America/Los_Angeles")
expect_true(
graph_2$graph_info$graph_tz == "America/Los_Angeles")
expect_error(
set_graph_time(
graph = graph_2,
tz = "Moon/Moon"))
graph_selection <-
create_graph() %>%
add_node() %>%
select_nodes() %>%
set_graph_time("2015-10-25 15:23:00")
})
test_that("Getting the graph name is possible", {
graph <-
create_graph() %>%
set_graph_name(name = "test_graph")
expect_is(
get_graph_name(graph), "character")
expect_equal(
length(get_graph_name(graph)), 1)
expect_equal(
get_graph_name(graph), "test_graph")
})
test_that("Getting the graph time is possible", {
graph <-
create_graph() %>%
set_graph_time(
time = "2015-10-25 15:23:00")
expect_is(
get_graph_time(graph), "POSIXct")
expect_equal(
length(get_graph_time(graph)), 1)
graph <- create_graph()
expect_is(
get_graph_time(graph), "POSIXct")
})
test_that("Getting global graph attrs is possible", {
graph <- create_graph(attr_theme = NULL)
expect_equal(
graph %>%
get_global_graph_attr_info() %>%
nrow(), 0)
graph <-
graph %>%
add_global_graph_attrs(
attr = c("overlap", "color", "penwidth"),
value = c("true", "red", "5"),
attr_type = c("graph", "node", "edge"))
global_graph_attrs <-
graph %>%
get_global_graph_attr_info()
expect_equal(
graph$global_attrs %>% dplyr::as_tibble(),
global_graph_attrs)
})
test_that("Adding global graph attrs is possible", {
graph <- create_graph()
graph_add_2 <-
graph %>%
add_global_graph_attrs(
attr = c("overlap", "penwidth"),
value = c("true", "5"),
attr_type = c("graph", "edge"))
expect_equal(
nrow(graph_add_2$global_attrs) -
nrow(graph$global_attrs), 2)
expect_equal(
tail(graph_add_2$global_attrs, 2)[, 1],
c("overlap", "penwidth"))
expect_equal(
tail(graph_add_2$global_attrs, 2)[, 2],
c("true", "5"))
expect_equal(
tail(graph_add_2$global_attrs, 2)[, 3],
c("graph", "edge"))
graph_add_1 <-
graph %>%
add_global_graph_attrs(
attr = "overlap",
value = TRUE,
attr_type = "graph")
expect_equal(
nrow(graph_add_1$global_attrs) -
nrow(graph$global_attrs), 1)
expect_equal(
tail(graph_add_1$global_attrs, 1)[, 1],
"overlap")
expect_equal(
tail(graph_add_1$global_attrs, 1)[, 2],
"true")
expect_equal(
tail(graph_add_1$global_attrs, 1)[, 3],
"graph")
})
test_that("Deleting global graph attrs is possible", {
graph <- create_graph()
graph_del_1 <-
graph %>%
delete_global_graph_attrs(
attr = "layout",
attr_type = "graph")
expect_equal(
nrow(graph$global_attrs) -
nrow(graph_del_1$global_attrs), 1)
graph_del_2 <-
graph %>%
delete_global_graph_attrs(
attr = c("layout", "outputorder"),
attr_type = c("graph", "graph"))
expect_equal(
nrow(graph$global_attrs) -
nrow(graph_del_2$global_attrs), 2)
expect_error(
graph %>%
delete_global_graph_attrs(
attr = "layout",
attr_type = "nodes"))
}) |
source("ESEUR_config.r")
library("plyr")
gd=read.csv(paste0(ESEUR_dir, "sourcecode/glob-def-usage.csv.xz"), as.is=TRUE)
gd$Release.Date=as.Date(gd$Release.Date, format="%d/%m/%y")
plot(gd$LOC/1e3, gd$Global.Variables, type="n", log="x",
xlab="KLOC", ylab="Global variables\n")
u_prog=unique(gd$Program)
pal_col=rainbow(length(u_prog))
gd$col_str=mapvalues(gd$Program, u_prog, pal_col)
d_ply(gd, .(Program), function(df) points(df$LOC/1e3, df$Global.Variables, col=df$col_str[1]))
legend(x="topleft", legend=u_prog, bty="n", fill=pal_col, cex=1.2) |
semivariogram <- function(x, ...){
UseMethod("semivariogram")
}
semivariogram.krige <- function(x, ..., bins=13, terms = "all", type, pch, lty,
legend, col){
if (!inherits(x, "krige")) stop("The input x is not a 'krige' x.")
if (terms[1] == "all") terms <- c("raw", "residual", "parametric")
dcol <- c(raw="black", residual="blue", parametric="red")
dtype <- c(raw="p", residual="p", parametric="l")
dpch <- c(raw=1, residual=3, parametric=2)
dlty <- c(raw=3, residual=2, parametric=1)
if (missing(col)) col <- dcol[terms]
if (is.null(names(col))) names(col) <- terms
if (missing(type)) type <- dtype[terms]
if (is.null(names(type))) names(type) <- terms
type[type == "lines"] <- "l"; type[type == "points"] <- "p"
if (missing(col)) col <- dcol[terms]
if (is.null(names(col))) names(col) <- terms
if (missing(type)) type <- dtype[terms]
if (is.null(names(type))) names(type) <- terms
if (missing(pch)) {pch <- ifelse(type == "p", dpch, NA)
} else { pch <- ifelse(type == "p", pch, NA) }
if (is.null(names(pch))) names(pch) <- terms
if (missing(lty)) {lty <- ifelse(type == "l", dlty, NA)
} else { lty <- ifelse(type == "l", lty, NA) }
if (is.null(names(lty))) names(lty) <- terms
if (all(is.na(pch))) pch <- NULL
if (all(is.na(lty))) lty <- NULL
if (length(terms) > 1 & missing(legend)) {legend <- TRUE
} else if (length(terms) == 1 & missing(legend)) {legend <- FALSE}
distance<-as.numeric(dist(cbind(x$model.data.list$easting,
x$model.data.list$northing)))
if ("raw" %in% terms) {
raw <- sv(x = x$model.data.list$y, distance = distance, bins = bins, ...)
}
if ("residual" %in% terms) {
residual <- sv(x = x$init.ols$residuals, distance = distance, bins = bins, ...)
}
if ("parametric" %in% terms) {
if (!exists("resid")) {residual <- sv(x = x$init.ols$residuals,
distance = distance, ...)}
var.terms<-apply(x$mcmc.mat[,1:3],2,quantile,0.5)
parametric <- exponential.semivariance.default(nugget=var.terms[1], decay=var.terms[2],
partial.sill = var.terms[3],
distance = as.numeric(names(residual)),
power = x$standing.parameter$powered.exp)
}
for (i in terms) {
if (i == terms[1]) {
sv.plot(get(i),distance=distance,bins=bins,add=FALSE,type=type[i],col=col[i],
pch=pch[i],lty=lty[i])
} else {
sv.plot(get(i),distance=distance,bins=bins,type=type[i],col=col[i],pch=pch[i],
lty=lty[i],add=TRUE)
}
}
if (legend == TRUE) {
lnames <- c(raw = "Raw data", residual = "OLS residuals",
parametric = "Parametric Semivariogram")
legend("top", legend=lnames[terms], pch = as.vector(pch[terms]), inset=c(0,-.15), xpd=TRUE,
bty = "n",col=col[terms], lty=as.vector(lty[terms]), cex=0.8,ncol=length(terms)) }
}
plot.krige <- function(...) semivariogram.krige(...)
semivariogram.lm <- function(x, ..., coords, bins = 13, terms = c("raw", "residual"),
east, north, type, legend, col, pch, lty) {
if (!inherits(x, "lm")) stop("The input x is not a 'lm' x.")
if (missing(coords)) {
if (missing(east) | missing(north)) stop("Coordinates are missing.")
coords <- cbind(east, north)
if (is.character(coords) & length(coords) == 2) coords <- as.vector(coords)
}
cl <- x$call
y <- x$model[1]
if (is.character(coords) & length(coords) == 2) {
form <- update(as.formula(cl$formula), paste("~ . +",paste(coords, collapse=" + ")))
na.action <- ifelse("na.action" %in% names(cl), cl$na.action, "na.omit")
mf <- model.frame(form, data = get(as.character(cl$data)), na.action=na.action)
if (length(mf[1]) != length(y)) warning("Additional missing data are dropped.")
y <- mf[1]; coords <- mf[coords]
x <- lm(cl$formula, data = mf)
}
dcol <- c(raw="black", residual="blue")
dtype <- c(raw="p", residual="p")
dpch <- c(raw=1, residual=3)
dlty <- c(raw=1, residual=3)
if (missing(col)) col <- dcol[terms]
if (is.null(names(col))) names(col) <- terms
if (missing(type)) type <- dtype[terms]
if (is.null(names(type))) names(type) <- terms
type[type == "lines"] <- "l"; type[type == "points"] <- "p"
if (missing(pch)) {pch <- ifelse(type == "p", dpch, NA)
} else { pch <- ifelse(type == "p", pch, NA) }
if (is.null(names(pch))) names(pch) <- terms
if (missing(lty)) {lty <- ifelse(type == "l", dlty, NA)
} else { lty <- ifelse(type == "l", lty, NA) }
if (is.null(names(lty))) names(lty) <- terms
if (all(is.na(pch))) pch <- NULL
if (all(is.na(lty))) lty <- NULL
if (length(terms) > 1 & missing(legend)) {legend <- TRUE
} else if (length(terms) == 1 & missing(legend)) {legend <- FALSE}
distance<-as.numeric(dist(coords))
if ("raw" %in% terms) {
raw <- sv(x = y, distance = distance, bins = bins, ...)
}
if ("residual" %in% terms) {
residual <- sv(x = x$residuals, distance = distance, bins = bins, ...)
}
for (i in terms) {
if (i == terms[1]) {
sv.plot(get(i),distance=distance,bins=bins,add=FALSE,type=type[i],col=col[i],
pch=pch[i],lty=lty[i])
} else {
sv.plot(get(i),distance=distance,bins=bins,type=type[i],col=col[i],pch=pch[i],
lty=lty[i],add=TRUE)
}
}
if (legend == TRUE) {
lnames <- c(raw = "Raw data", residual = "Residuals")
legend("top", legend=lnames[terms], pch = as.vector(pch[terms]), inset=c(0,-.15), xpd=TRUE,
bty = "n",col=col[terms], lty=as.vector(lty[terms]), cex=0.8, ncol=length(terms)) }
}
semivariogram.default <- function(x, ..., coords, data, bins=13, east, north, type,
pch, lty, col){
if (missing(coords)) {
coords <- cbind(east, north)
if (is.character(coords) & length(coords) == 2) coords <- as.vector(coords)
}
if (is.character(coords) & length(coords) == 2) coords <- data[coords]
if (is.character(x) & length(x) == 1) x <- data[x]
if (missing(type)) type <- "p"
type[type == "points"] <- "p"; type[type == "lines"] <- "l"
if (type == "p") pch <- ifelse(missing(pch), 1, pch); lty <- NULL
if (type == "l") lty <- ifelse(missing(lty), 1, lty); pch <- NULL
if (missing(col)) col <- "black"
distance <- as.numeric(dist(coords))
semivariances <- sv(x = x, distance = distance, bins = bins, ...)
sv.plot(semivariances,distance=distance,bins=bins,add=FALSE,type=type,col=col,
pch=pch,lty=lty)
}
semivariogram.semivariance <- function(x, ..., type, pch, lty, legend, col){
if (!inherits(x, "semivariance")) stop("The input x is not a 'semivariance' x.")
if (is.list(x)){
terms <- names(x)
dcol <- c(raw="black", residual="blue", parametric="red")
dtype <- c(raw="p", residual="p", parametric="l")
dpch <- c(raw=1, residual=3, parametric=2)
dlty <- c(raw=3, residual=2, parametric=1)
if (missing(col)) col <- dcol[terms]
if (is.null(names(col))) names(col) <- terms
if (missing(type)) type <- dtype[terms]
if (is.null(names(type))) names(type) <- terms
type[type == "lines"] <- "l"; type[type == "points"] <- "p"
if (missing(col)) col <- dcol[terms]
if (is.null(names(col))) names(col) <- terms
if (missing(type)) type <- dtype[terms]
if (is.null(names(type))) names(type) <- terms
if (missing(pch)) {pch <- ifelse(type == "p", dpch, NA)
} else { pch <- ifelse(type == "p", pch, NA) }
if (is.null(names(pch))) names(pch) <- terms
if (missing(lty)) {lty <- ifelse(type == "l", dlty, NA)
} else { lty <- ifelse(type == "l", lty, NA) }
if (is.null(names(lty))) names(lty) <- terms
if (all(is.na(pch))) pch <- NULL
if (all(is.na(lty))) lty <- NULL
if (length(terms) > 1 & missing(legend)) {legend <- TRUE
} else if (length(terms) == 1 & missing(legend)) {legend <- FALSE}
for (i in terms) {
if (i == terms[1]) {
distance <- as.numeric(names(x[[i]]))
sv.plot(x[[i]],distance=distance,bins=length(distance),add=FALSE,type=type[i],col=col[i],
pch=pch[i],lty=lty[i])
} else {
sv.plot(x[[i]],distance=distance,bins=length(distance),type=type[i],col=col[i],pch=pch[i],
lty=lty[i],add=TRUE)
}
if (legend == TRUE) {
legend("top", legend=terms, pch = as.vector(pch[terms]), inset=c(0,-.15), xpd=TRUE,
bty = "n",col=col[terms], lty=as.vector(lty[terms]), cex=0.8, ncol=length(terms)) }
}
} else if (is.matrix(x)) {
if (length(x) > 100) stop("The length of distance is too large.")
i <- 1
if (missing(type)) type <- ifelse(length(x) > 30, "l", "p")
type[type == "points"] <- "p"; type[type == "lines"] <- "l"
if (type == "p") pch <- ifelse(missing(pch), 1, pch); lty <- NA
if (type == "l") lty <- ifelse(missing(lty), 1, lty); pch <- NA
if (missing(col)) col <- "black"
distance <- as.numeric(names(x))
sv.plot(x[[i]],distance=distance,bins=length(distance),add=FALSE,type=type[i],col=col[i],
pch=pch[i],lty=lty[i])
}
}
plot.semivariance <- semivariogram.semivariance
sv.plot <- function(semivariances,distance,bins,add=FALSE,type="p",col=col,pch=1,lty=1,...){
breaks<-seq(0,max(distance),length=bins+1)
digits<-ifelse(max(breaks)<10,2,0)
labels<-round(breaks[-1],digits)
cl <- match.call(expand.dots=TRUE)
if (! "xlab" %in% names(cl)) xlab <- "Distance"
if (! "ylab" %in% names(cl)) ylab <- "Semivariance"
if (add==FALSE){
plot(1, type="n", xlab=xlab, ylab=ylab, xlim=c(0,bins),
ylim=c(0,max(semivariances)),axes=F,...)
axis(1,at=1:bins,labels=labels,cex.axis=.75);axis(2);box()
}
if (type=="p"){
points(semivariances, col = col, pch = pch)
}
if (type=="l"){
lines(semivariances, col = col, lty = lty)
}
} |
gt_reflect <- function(obj, angle, fid = NULL, update = TRUE){
assertNumeric(x = angle, any.missing = FALSE, lower = -360, upper = 360, min.len = 1)
assertNumeric(x = fid, lower = 1, finite = TRUE, any.missing = FALSE, null.ok = TRUE)
assertLogical(x = update, len = 1, any.missing = FALSE)
theFeatures <- getFeatures(x = obj)
theGroups <- getGroups(x = obj)
thePoints <- getPoints(x = obj)
theWindow <- getWindow(x = obj)
ids <- unique(thePoints$fid)
existsID <- !is.null(fid)
if(existsID){
doReflect <- ids %in% fid
} else{
doReflect <- rep(TRUE, length(ids))
}
if(length(angle) != length(ids)){
angle <- rep(angle, length.out = length(ids))
}
digits <- getOption("digits")
temp <- NULL
for(i in seq_along(ids)){
tempCoords <- thePoints[thePoints$fid == ids[i],]
newCoords <- tempCoords
if(doReflect[i]){
tempAngle <- angle[[i]]
newCoords$x <- round(tempCoords$x * cos(2 * .rad(tempAngle)) + tempCoords$y * sin(2 * .rad(tempAngle)), digits)
newCoords$y <- round(tempCoords$x * sin(2 * .rad(tempAngle)) - tempCoords$y * cos(2 * .rad(tempAngle)), digits)
}
temp <- rbind(temp, newCoords)
}
if(update){
window <- .updateWindow(input = temp, window = theWindow)
} else {
window <- theWindow
}
if(length(ids) == 1){
hist <- paste0("geom was reflected.")
} else {
hist <- paste0("geoms were reflected.")
}
out <- new(Class = "geom",
type = getType(x = obj)[1],
point = temp,
feature = theFeatures,
group = theGroups,
window = window,
crs = getCRS(x = obj),
history = c(getHistory(x = obj), list(hist)))
return(out)
} |
fitexi <- function(data, threshold){
if (any(is.na(data))){
warning("NA's are not allowed in object ``data''.\nReplacing them by the threshold !!!")
data[is.na(data)] <- threshold
}
idx <- which(data > threshold)
nat <- length(idx)
interTim <- diff(idx)
if (max(interTim) == 1)
exi <- 0
else{
if (max(interTim) <= 2){
exi <- 2 * sum(interTim - 1)^2 / (nat - 1) /
sum((interTim - 1) * (interTim - 2))
exi <- min(1, exi)
}
else{
exi <- 2 * sum(interTim)^2 / (nat - 1) /
sum(interTim^2)
exi <- min(1, exi)
}
}
myC <- floor(exi * nat) + 1
sortInterTim <- sort(interTim, decreasing = TRUE)
if (myC <= length(interTim))
TC <- sortInterTim[myC]
else
TC <- max(interTim)
return(list(exi = exi, tim.cond = TC))
}
|
new_project_group <- function(path) {
p_path <- get_p_path()
path <- validate_directory(path, p_path, make_directories = TRUE)
if (fs::path_ext(path) != "") {
stop("\nMust be a directory and not a file (i.e., must not have a file ",
"extension, which is ", fs::path_ext(path), " in this case).")
}
if (fs::dir_exists(path)) {
stop("\nDirectory already exists.")
}
fs::dir_create(path)
message("\nThe following directory was created:\n", path)
}
rename_folder <- function(project, new_folder_name, archived = FALSE) {
p_path <- get_p_path()
projects_path <- make_rds_path("projects", p_path)
projects_table <- get_rds(projects_path)
if (!archived) {
projects_table <- remove_archived(projects_table)
}
project_row <-
validate_unique_entry(
x = project,
table = projects_table,
what = "project"
)
new_folder_name <- fs::path_sanitize(new_folder_name)
new_path <- fs::path(fs::path_dir(project_row$path), new_folder_name)
print(project_row)
if (fs::dir_exists(new_path)) {
stop("The directory\n", new_path, "\nalready exists.",
"\nMove or delete it, or pick a different name.")
}
else {
user_prompt(
msg = paste0("Are you sure you want to rename this project folder so ",
"that its new file path is\n", new_path, "\n? (y/n)"),
n_msg = paste0('Renaming not completed. To rename this project, ',
'try again and enter "y".')
)
}
fs::file_move(path = project_row$path, new_path = new_path)
project_row$path <- unclass(new_path)
edit_metadata(
table = projects_table,
row_id = project_row$id,
path = project_row$path,
short_title = project_row$short_title,
table_path = projects_path
)
message(
"\nProject ", project_row$id,
" renamed so that its new path is\n", project_row$path
)
invisible(project_row)
}
move_project <- function(project,
path,
make_directories = FALSE,
archived = FALSE) {
p_path <- get_p_path()
projects_path <- make_rds_path("projects", p_path)
projects_table <- get_rds(projects_path)
if (!archived) {
projects_table <- remove_archived(projects_table)
}
project_row <-
validate_unique_entry(
x = project,
table = projects_table,
what = "project"
)
path <-
validate_directory(
path = path,
p_path = p_path,
make_directories = make_directories
)
print(project_row)
if (fs::dir_exists(path)) {
user_prompt(
msg = paste0("Are you sure you want to move this project folder so ",
"that its new file path is\n",
fs::path(path, fs::path_file(project_row$path)),
"\n? (y/n)"),
n_msg = paste0('Move not completed. To move this project, try again ',
'and enter "y".')
)
} else {
user_prompt(
msg = paste0("\nDirectory not found:\n", path,
"\n\nWould you like to create it and move the project ",
"folder there, so that its new file path will be\n",
fs::path(path, fs::path_file(project_row$path)),
"\n\n? (y/n)"),
n_msg = paste0("\nMove not completed. To move this project, try again ",
'and enter "y"'))
fs::dir_create(path)
}
fs::file_move(path = project_row$path, new_path = path)
project_row$path <-
fs::path(path, fs::path_file(project_row$path)) %>%
unclass()
edit_metadata(
table = projects_table,
row_id = project_row$id,
path = project_row$path,
table_path = projects_path
)
message(
"\nProject ", project_row$id,
" moved so that its new path is\n", project_row$path
)
}
copy_project <- function(project_to_copy,
path,
new_id = NA,
new_folder_name =
paste0("p", stringr::str_pad(new_id, 4, pad = "0")),
new_short_title = NA,
make_directories = FALSE,
archived = FALSE) {
p_path <- get_p_path()
pa_assoc_path <- make_rds_path("project_author_assoc", p_path)
pa_assoc_table <- get_rds(pa_assoc_path)
projects_path <- make_rds_path("projects", p_path)
projects_table <- get_rds(projects_path)
project_row <-
validate_unique_entry(
x = project_to_copy,
table = projects_table,
what = "project"
)
original_project_id <- project_row$id
old_path <- project_row$path
old_folder <- fs::path_file(old_path)
if (missing(path)) {
path <- fs::path_dir(old_path)
} else {
path <-
validate_directory(
path = path,
p_path = p_path,
make_directories = make_directories
)
}
old_project <- project_row
project_row$id <-
new_id <-
validate_new(id = new_id, what = "project", rds_table = projects_table)
project_row$short_title <- new_short_title
project_row$path <-
make_project_path(project_name = new_folder_name, path = path)
if (fs::dir_exists(project_row$path)) {
stop(
"The directory\n", project_row$path, "\nalready exists.",
"\nMove or delete it, or pick a different folder_name."
)
}
print(old_project)
if (fs::dir_exists(path)) {
user_prompt(
msg = paste0("\nAre you sure you want to copy this project into the ",
"new directory\n", project_row$path, "\n\n? (y/n)"),
n_msg = paste0('Copy not completed. To copy this project, try again ',
'and enter "y".')
)
} else {
user_prompt(
msg = paste0("\nDirectory not found:\n", path,
"\n\nWould you like to create it and copy the above ",
"project there, so that its file path will be\n",
project_row$path, "\n\n? (y/n)"),
n_msg = paste0("\nCopy not completed. To copy this project, try again ",
'and enter "y"')
)
fs::dir_create(path)
}
fs::dir_copy(path = old_path, new_path = project_row$path)
add_metadata(
table = projects_table,
new_row = project_row,
table_path = projects_path
)
old_assoc <- dplyr::filter(pa_assoc_table, .data$id1 == original_project_id)
if (nrow(old_assoc) > 0L) {
add_assoc(
assoc_table = pa_assoc_table,
new_rows = tibble::tibble(id1 = project_row$id, id2 = old_assoc$id2),
assoc_path = pa_assoc_path
)
}
message(
"\nProject ", project_row$id, " below is a copy of project ",
original_project_id, " and is located at\n", project_row$path
)
print(project_row)
Rproj_path <- fs::dir_ls(project_row$path, glob = "*.Rproj")
if (length(Rproj_path) == 1L) {
new_path <-
fs::path(project_row$path, new_folder_name, ext = "Rproj")
fs::file_move(path = Rproj_path, new_path = new_path)
message("\nThe .Rproj file\n", Rproj_path, "\nwas renamed to\n", new_path)
} else if (length(Rproj_path) == 0L) {
warning("\nNo .Rproj file found in the new project folder.")
} else {
warning("\nMultiple .Rproj files found in newly created directory.",
" None have been renamed.")
}
message(
'\nBe sure to change all instances of \"', old_folder,
'\" to \"', new_folder_name,
'\" as desired\n(e.g., .bib files and references to them in YAML headers).'
)
invisible(project_row)
}
archive_project <- function(project) {
p_path <- get_p_path()
projects_path <- make_rds_path("projects", p_path)
projects_table <- get_rds(projects_path) %>% remove_archived()
project_row <-
validate_unique_entry(
x = project,
table = projects_table,
what = "project"
)
if (!fs::dir_exists(project_row$path)) {
print(project_row)
stop("The above project not found at\n", project_row$path,
"\nRestore project folder to this location first.")
}
archive_folder <- fs::path(fs::path_dir(project_row$path), "archive")
new_path <- fs::path(archive_folder, fs::path_file(project_row$path))
user_prompt(
msg = paste0("\nAre you sure you want to archive this project folder",
" so that its new file path is\n", new_path, "\n\n? (y/n)"),
n_msg = paste0('\nArchiving not completed. To archive this project, try ',
'again and enter "y".'))
if (!fs::file_exists(archive_folder)) {
fs::dir_create(archive_folder)
}
fs::file_move(path = project_row$path, new_path = archive_folder)
projects_table$path[projects_table$id == project_row$id] <- new_path
readr::write_rds(projects_table, projects_path)
print(dplyr::filter(projects_table, .data$id == project_row$id))
message("\nThe above project was archived and has the file path\n", new_path)
}
open_project <- function(project, new_session = FALSE, archived = FALSE) {
p_path <- get_p_path()
project_row <-
validate_unique_entry(
x = project,
table = projects_internal(p_path = p_path, archived = archived),
what = "project"
)
if (fs::path_has_parent(project_row$path, p_path)) {
Rproj_path <- fs::dir_ls(project_row$path, glob = "*.Rproj")
} else {
path_split <- fs::path_split(project_row$path)[[1L]]
len <- length(path_split)
Rproj_path <- NULL
for (i in seq_len(len)[-1L]) {
candidate <- fs::path_join(c(p_path, path_split[i:len]))
if (fs::file_exists(candidate)) {
Rproj_path <- fs::dir_ls(candidate, glob = "*.Rproj")
break
}
}
}
if (length(Rproj_path) != 1L) {
if (length(Rproj_path) == 0L) {
user_prompt(
msg =
paste0(
"\nCannot open project ",
project_row$id,
" because there\n",
"is no .Rproj file in\n",
project_row$path,
"\n\nRestore it with a default .Rproj file? (y/n)"
),
n_msg =
paste0('\nRestore a .Rproj file to the folder\n', project_row$path)
)
default_Rproj <-
system.file(
"templates",
"pXXXX.Rproj",
package = "projects",
mustWork = TRUE
)
Rproj_path <-
fs::path(
project_row$path,
paste0("p", stringr::str_pad(project_row$id, width = 4L, pad = "0")),
ext = "Rproj"
)
fs::file_copy(default_Rproj, Rproj_path)
user_prompt(
msg =
paste0(
".Rproj file restored at\n",
Rproj_path,
"\n\nOpen this project? (y/n)"
),
n_msg =
paste0("\nProject not opened.")
)
} else {
stop(
"\nCannot open project ", project_row$id, " because there\n",
"are multiple .Rproj files in\n", project_row$path,
"\nNamely: ", paste(fs::path_file(Rproj_path), collapse = ", "),
"\nMove or delete the extraneous ones."
)
}
}
rstudioapi::openProject(Rproj_path, new_session)
}
move_projects_folder <- function(new_path,
make_directories = FALSE,
.Renviron_path =
file.path(Sys.getenv("HOME"), ".Renviron")) {
p_path <- get_p_path()
projects_path <- make_rds_path("projects", p_path = p_path)
projects_table <- get_rds(projects_path)
new_path <-
validate_directory(
new_path,
p_path = NULL,
make_directories = make_directories
)
new_path2 <- fs::path(new_path, fs::path_file(p_path))
if (fs::dir_exists(new_path)) {
if (fs::dir_exists(new_path2)) {
stop(
"\nCannot move the projects folder currently at:\n",
p_path,
"\ninto the folder:\n",
new_path,
"\nbecause this folder:\n",
new_path2,
"\nalready exists."
)
}
user_prompt(
msg = paste0("Are you sure you want to move the projects folder",
"\nso that its new path is\n",
new_path2,
"\n? (y/n)"),
n_msg = paste0('Move not completed. To move the projects folder, ',
'try again and enter "y".')
)
} else {
user_prompt(
msg = paste0("\nDirectory not found:\n", new_path,
"\n\nWould you like to create it and move the projects ",
"folder there, so that its new path will be\n",
new_path2,
"\n\n? (y/n)"),
n_msg = paste0("\nMove not completed. To move this project, try again ",
'and enter "y"')
)
fs::dir_create(new_path)
}
fs::file_move(path = p_path, new_path = new_path)
set_Renviron(new_path2, .Renviron_path = .Renviron_path)
coll_p_path <- stringr::coll(fs::path_dir(p_path))
projects_table$path <-
stringr::str_replace(
string = projects_table$path,
pattern = coll_p_path,
replacement = new_path
)
projects_path <-
stringr::str_replace(
string = projects_path,
pattern = coll_p_path,
replacement = new_path
)
readr::write_rds(projects_table, projects_path)
message("\nProjects folder moved so that its new path is\n", new_path2)
}
rename_projects_folder <- function(new_name,
.Renviron_path =
file.path(Sys.getenv("HOME"), ".Renviron")
) {
p_path <- get_p_path()
projects_path <- make_rds_path("projects", p_path = p_path)
projects_table <- get_rds(projects_path)
if (!identical(new_name, fs::path_sanitize(new_name))) {
stop(new_name, " is not a valid folder name")
}
new_path <- fs::path(fs::path_dir(p_path), new_name)
if (fs::dir_exists(new_path)) {
stop(
"\nThe directory:\n",
new_path,
"\nalready exists. Move or delete it or choose a different name."
)
}
user_prompt(
msg = paste0("Are you sure you want to rename the projects folder",
"\nso that its new path is\n",
new_path,
"\n? (y/n)"),
n_msg = paste0('Renaming not completed. To rename the projects folder, ',
'try again and enter "y".')
)
fs::file_move(path = p_path, new_path = new_path)
set_Renviron(new_path, .Renviron_path = .Renviron_path)
coll_p_path <- stringr::coll(p_path)
projects_table$path <-
stringr::str_replace(
string = projects_table$path,
pattern = coll_p_path,
replacement = new_path
)
projects_path <-
stringr::str_replace(
string = projects_path,
pattern = coll_p_path,
replacement = new_path
)
readr::write_rds(projects_table, projects_path)
message("\nProjects folder renamed so that its new path is:\n", new_path)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.