code
stringlengths 1
13.8M
|
---|
test_that("import_pattern imports patterns of right length", {
expect_equal(
nchar(import_pattern("../rmd/sample_pattern.Rmd")),
53
)
})
test_that("import_pattern doesn't fail silently", {
expect_error(import_pattern())
expect_error(import_pattern(53))
expect_error(import_pattern(iris))
expect_warning(import_pattern("../rmd/empty_file.Rmd"))
}) |
penAFT.cv <- function(X, logY, delta,
nlambda = 50,
lambda.ratio.min = 0.1,
lambda = NULL,
penalty = NULL,
alpha = 1,
weight.set = NULL,
groups = NULL,
tol.abs = 1e-8,
tol.rel = 2.5e-4,
standardize = TRUE,
nfolds = 5,
cv.index = NULL,
admm.max.iter = 1e4,
quiet = TRUE) {
p <- dim(X)[2]
n <- dim(X)[1]
gamma <- 0
if (length(logY) != n) {
stop("Dimensions of X and logY do not match: see documentation")
}
if (length(delta) != n) {
stop("Dimension of X and delta do not match: see documentation")
}
if (!any(delta==0 | delta==1)) {
stop("delta must be a vector with elements in {0,1}: see documentation")
}
if (alpha > 1 | alpha < 0) {
stop("alpha must be in [0,1]: see documentation.")
}
if (standardize) {
X.fit <- (X - tcrossprod(rep(1, n), colMeans(X)))/(tcrossprod(rep(1, n), apply(X, 2, sd)))
}
if (!standardize) {
X.fit <- X
}
if(!is.null(penalty)){
if(penalty != "EN" & penalty != "SG"){
stop("penalty must either be \"EN\" or \"SG\".")
}
}
if (is.null(penalty)) {
penalty <- "EN"
}
if (penalty == "EN") {
if (is.null(weight.set)){
w <- rep(1, p)
} else {
if (is.null(weight.set$w)) {
stop("Need to specify weight.set as a list with element w to use weighted elastic net")
} else {
w <- weight.set$w
}
}
if (is.null(lambda)) {
if (alpha != 0) {
EN_TPcalc <- function(X.fit, logY, delta) {
n <- length(logY)
p <- dim(X.fit)[2]
grad <- rep(0, dim(X.fit)[2])
grad2 <- rep(0, dim(X.fit)[2])
for (i in which(delta==1)) {
t0 <- which(logY > logY[i])
if(length(t0) > 0){
grad <- grad + length(t0)*X.fit[i,] - colSums(X.fit[t0,,drop=FALSE])
}
t1 <- which(logY == logY[i])
if(length(t1) > 0){
grad2 <- grad2 + colSums(abs(matrix(X.fit[i,], nrow=length(t1), ncol=p, byrow=TRUE) - X.fit[t1,,drop=FALSE]))
}
}
return(abs(grad)/n^2 + grad2/n^2)
}
gradG <- EN_TPcalc(X.fit, logY, delta)
wTemp <- w
if(any(wTemp==0)){
wTemp[which(wTemp == 0)] <- Inf
}
lambda.max <- max(gradG/wTemp)/alpha + 1e-4
lambda.min <- lambda.ratio.min*lambda.max
lambda <- 10^seq(log10(lambda.max), log10(lambda.min), length=nlambda)
} else {
lambda <- 10^seq(-4, 4, length=nlambda)
warning("Setting alpha = 0 corresponds to a ridge-penalty: may need to check candidate tuning parameter values.")
}
} else {
warning("It is recommended to let tuning parameters be chosen automatically: see documentation.")
}
getPath <- ADMM.ENpath(X.fit, logY, delta, admm.max.iter, lambda, alpha, w, tol.abs, tol.rel, gamma, quiet)
eval.obj.inner <- function(logY, XB, delta){
out <- 0
n <- length(logY)
E <- logY - XB
for(i in which(delta==1)){
out <- out + sum(pmax(E - E[i], 0))
}
return(out/n^2)
}
if(!is.null(cv.index)){
if(class(cv.index)!="list"){
stop("Input cv.index must be a list!")
} else {
nfolds <- length(cv.index)
}
}
fold1 <- sample(rep(1:nfolds, length=length(which(delta==1))))
fold0 <- sample(rep(1:nfolds, length=length(which(delta==0))))
cv.index1 <- split(which(delta==1), fold1)
cv.index0 <- split(which(delta==0), fold0)
if(is.null(cv.index)){
cv.index <- list()
for (ll in 1:nfolds) {
cv.index[[ll]] <- c(cv.index1[[ll]],cv.index0[[ll]])
}
}
if(length(cv.index)!=nfolds){
stop("Input cv.index does not match nfolds")
}
preds <- matrix(Inf, nrow = n, ncol = length(lambda))
cv.err.obj <- matrix(Inf, nrow=nfolds, ncol=length(lambda))
for (k in 1:nfolds) {
ntrain <- dim(X[-cv.index[[k]],])[1]
ntest <- length(cv.index[[k]])
if (standardize) {
X.train.fit <- (X[-cv.index[[k]], ] - tcrossprod(rep(1, ntrain), colMeans(X[-cv.index[[k]], ])))/(tcrossprod(rep(1, ntrain), apply(X[-cv.index[[k]], ], 2, sd)))
X.test <- (X[cv.index[[k]], ] - tcrossprod(rep(1, ntest), colMeans(X[-cv.index[[k]], ])))/(tcrossprod(rep(1, ntest), apply(X[-cv.index[[k]], ], 2, sd)))
}
if (!standardize) {
X.train.fit <- X[-cv.index[[k]], ]
X.test <- X[cv.index[[k]], ]
}
logY.train <- logY[-cv.index[[k]]]
logY.test <- logY[cv.index[[k]]]
delta.train <- delta[-cv.index[[k]]]
delta.test <- delta[cv.index[[k]]]
cv.getPath <- ADMM.ENpath(X.train.fit, logY.train, delta.train, admm.max.iter, lambda, alpha, w, tol.abs, tol.rel, gamma, quiet)
for (ll in 1:length(lambda)) {
preds[cv.index[[k]],ll] <- X.test%*%cv.getPath$beta[,ll]
cv.err.obj[k, ll] <- eval.obj.inner(logY.test, preds[cv.index[[k]],ll], delta.test)
}
cat("CV through: ", rep("
}
cv.err.linPred <- rep(Inf, length(lambda))
for (ll in 1:length(lambda)) {
cv.err.linPred[ll] <- eval.obj.inner(logY, preds[,ll], delta)
}
} else {
if (penalty == "SG") {
if (is.null(groups)) {
stop("To use group-lasso penalty, must specify \"groups\"!")
}
if (alpha == 1) {
stop("Penalty \"SG\" with alpha = 1 corresponds to \"EN\" and set alpha = 1; check documentation.")
}
G <- length(unique(groups))
if(is.null(weight.set)){
w <- rep(1, p)
v <- rep(1, G)
} else {
if (is.null(weight.set$w)) {
stop("Need to specify both w and v using weighted group lasso")
} else {
w <- weight.set$w
}
if (is.null(weight.set$v)) {
stop("Need to specify both w and v using weighted group lasso")
} else {
v <- weight.set$v
}
}
if (is.null(lambda)) {
if (length(unique(logY)) == length(logY) && !any(w == 0) && !any(v == 0)) {
getGrad <- function(X.fit, logY, delta) {
n <- length(logY)
p <- dim(X.fit)[2]
grad <- rep(0, dim(X.fit)[2])
grad2 <- rep(0, dim(X.fit)[2])
for (i in which(delta==1)) {
t0 <- which(logY > logY[i])
if(length(t0) > 0){
grad <- grad + length(t0)*X.fit[i,] - colSums(X.fit[t0,,drop=FALSE])
}
t1 <- which(logY == logY[i])
if(length(t1) > 0){
grad2 <- grad2 + colSums(abs(matrix(X.fit[i,], nrow=length(t1), ncol=p, byrow=TRUE) - X.fit[t1,,drop=FALSE]))
}
}
return(abs(grad)/n^2 + grad2/n^2)
}
grad <- getGrad(X.fit, logY, delta)
lam.check <- 10^seq(-4, 4, length=500)
check.array <- matrix(0, nrow=length(lam.check), ncol=G)
for(j in 1:length(lam.check)){
for(k in 1:G){
t0 <- pmax(abs(grad[which(groups==k)]) - alpha*lam.check[j]*w[which(groups==k)], 0)*sign(grad[which(groups==k)])
check.array[j,k] <- sqrt(sum(t0^2)) < v[k]*(1-alpha)*lam.check[j]
}
}
lambda.max <- lam.check[min(which(rowSums(check.array) == G))] + 1e-4
if (is.null(lambda.ratio.min)) {
lambda.ratio.min <- 0.1
}
lambda.min <- lambda.ratio.min*lambda.max
lambda <- 10^seq(log10(lambda.max), log10(lambda.min), length=nlambda)
} else {
getGrad <- function(X.fit, logY, delta) {
n <- length(logY)
p <- dim(X.fit)[2]
grad <- rep(0, dim(X.fit)[2])
grad2 <- rep(0, dim(X.fit)[2])
for (i in which(delta==1)) {
t0 <- which(logY > logY[i])
if(length(t0) > 0){
grad <- grad + length(t0)*X.fit[i,] - colSums(X.fit[t0,,drop=FALSE])
}
t1 <- which(logY == logY[i])
if(length(t1) > 0){
grad2 <- grad2 + colSums(abs(matrix(X.fit[i,], nrow=length(t1), ncol=p, byrow=TRUE) - X.fit[t1,,drop=FALSE]))
}
}
return(abs(grad)/n^2 + grad2/n^2)
}
grad <- getGrad(X.fit, logY, delta)
lam.check <- 10^seq(-4, 4, length=500)
if(any(v == 0)){
check.array <- matrix(0, nrow=length(lam.check), ncol=G)
for(j in 1:length(lam.check)){
for(k in (1:G)[-which(v == 0)]){
t0 <- pmax(abs(grad[which(groups==k)]) - alpha*lam.check[j]*w[which(groups==k)], 0)*sign(grad[which(groups==k)])
check.array[j,k] <- sqrt(sum(t0^2)) < v[k]*(1-alpha)*lam.check[j]
}
}
check.array <- check.array[,-which(v == 0)]
lambda.max <- 1.5*lam.check[min(which(rowSums(check.array) == length(which(v == 0))))] + 1e-4
} else {
check.array <- matrix(0, nrow=length(lam.check), ncol=G)
for(j in 1:length(lam.check)){
for(k in (1:G)){
t0 <- pmax(abs(grad[which(groups==k)]) - alpha*lam.check[j]*w[which(groups==k)], 0)*sign(grad[which(groups==k)])
check.array[j,k] <- sqrt(sum(t0^2)) < v[k]*(1-alpha)*lam.check[j]
}
}
lambda.max <- 1.5*lam.check[min(which(rowSums(check.array) == G))] + 1e-4
}
if (is.null(lambda.ratio.min)) {
lambda.ratio.min <- 0.1
}
lambda.min <- lambda.ratio.min*lambda.max
lambda <- 10^seq(log10(lambda.max), log10(lambda.min), length=nlambda)
lambda.max <- ADMM.SGpath.candidatelambda(X.fit, logY, delta, admm.max.iter, lambda, alpha, w, v, groups, tol.abs, tol.rel, gamma, quiet)$lambda.max
if (is.null(lambda.ratio.min)) {
lambda.ratio.min <- 0.1
}
lambda.min <- lambda.ratio.min*lambda.max
lambda <- 10^seq(log10(lambda.max), log10(lambda.min), length=nlambda)
}
} else {
warning("It is recommended to let tuning parameters be chosen automatically: see documentation.")
}
getPath <- ADMM.SGpath(X.fit, logY, delta, admm.max.iter, lambda, alpha, w, v, groups, tol.abs, tol.rel, gamma, quiet)
eval.obj.inner <- function(logY, XB, delta){
out <- 0
n <- length(logY)
E <- logY - XB
for(i in which(delta==1)){
out <- out + sum(pmax(E - E[i], 0))
}
return(out/n^2)
}
fold1 <- sample(rep(1:nfolds, length=length(which(delta==1))))
fold0 <- sample(rep(1:nfolds, length=length(which(delta==0))))
cv.index1 <- split(which(delta==1), fold1)
cv.index0 <- split(which(delta==0), fold0)
if(is.null(cv.index)){
cv.index <- list()
for (ll in 1:nfolds) {
cv.index[[ll]] <- c(cv.index1[[ll]],cv.index0[[ll]])
}
}
preds <- matrix(Inf, nrow = n, ncol = length(lambda))
cv.err.obj <- matrix(Inf, nrow=nfolds, ncol=length(lambda))
for (k in 1:nfolds) {
ntrain <- dim(X[-cv.index[[k]],])[1]
ntest <- length(cv.index[[k]])
if (standardize) {
X.train.fit <- (X[-cv.index[[k]], ] - tcrossprod(rep(1, ntrain), colMeans(X[-cv.index[[k]], ])))/(tcrossprod(rep(1, ntrain), apply(X[-cv.index[[k]], ], 2, sd)))
X.test <- (X[cv.index[[k]], ] - tcrossprod(rep(1, ntest), colMeans(X[-cv.index[[k]], ])))/(tcrossprod(rep(1, ntest), apply(X[-cv.index[[k]], ], 2, sd)))
}
if (!standardize) {
X.train.fit <- X[-cv.index[[k]], ]
X.test <- X[cv.index[[k]], ]
}
logY.train <- logY[-cv.index[[k]]]
logY.test <- logY[cv.index[[k]]]
delta.train <- delta[-cv.index[[k]]]
delta.test <- delta[cv.index[[k]]]
cv.getPath <- ADMM.SGpath(X.train.fit, logY.train, delta.train, admm.max.iter, lambda, alpha, w, v, groups, tol.abs, tol.rel, gamma, quiet)
for (ll in 1:length(lambda)) {
preds[cv.index[[k]],ll] <- X.test%*%cv.getPath$beta[,ll]
cv.err.obj[k, ll] <- eval.obj.inner(logY.test, preds[cv.index[[k]],ll], delta.test)
}
cat("CV through: ", rep("
}
cv.err.linPred <- rep(Inf, length(lambda))
for (ll in 1:length(lambda)) {
cv.err.linPred[ll] <- eval.obj.inner(logY, preds[,ll], delta)
}
}
}
getPath$standardize <- standardize
getPath$X.mean <- colMeans(X)
getPath$X.sd <- apply(X, 2, sd)
getPath$alpha <- alpha
if(penalty=="SG"){
getPath$groups <- groups
}
Result <- list("full.fit" = getPath,
"cv.err.linPred" = cv.err.linPred,
"cv.err.obj" = cv.err.obj,
"cv.index" = cv.index,
"lambda.min" = lambda[which.min(cv.err.linPred == min(cv.err.linPred))])
class(Result) <- "penAFT.cv"
return(Result)
} |
require(OpenMx)
if (mxOption(NULL, "Default optimizer") == "SLSQP") {
mxOption(NULL, "Optimality tolerance", "6e-10")
}
set.seed(654684)
data(demoOneFactor)
manifests <- names(demoOneFactor)
latents <- c("factor")
nVar <- length(manifests)
nFac <- length(latents)
factorModel <- mxModel("One Factor ML",
mxData(cov(demoOneFactor), type="cov", means=colMeans(demoOneFactor), numObs=500),
mxMatrix("Full", 1, nVar, free=T, values=colMeans(demoOneFactor), name="M"),
mxMatrix("Full", nVar, nFac, free=T, values=.2, ubound=1, name="A"),
mxMatrix("Diag", nVar, nVar, free=T, values=1, lbound=.0001, ubound=10, name="D"),
mxAlgebra(A%*%t(A) + D, name="C"),
mxAlgebra(sqrt(diag2vec(C)),name="P"),
mxFitFunctionML(),mxExpectationNormal("C", "M", dimnames=manifests),
mxCI(c("P"))
)
factorFitCI <- mxTryHard(factorModel, fit2beat=-2863, extraTries=3, intervals=TRUE)
factorSummCI <- summary(factorFitCI)
( ci <- factorFitCI$output$confidenceIntervals )
omxCheckCloseEnough(ci[,'estimate'], c(0.4455, 0.54, 0.6115, 0.7302, 0.8186), 1e-3)
omxCheckCloseEnough(ci[,'lbound'] - c(0.4174, 0.5082, 0.5755, 0.6872, 0.7704), rep(0,5), 4e-2)
if (mxOption(NULL, "Default optimizer") != "NPSOL") {
omxCheckCloseEnough(ci[,'ubound'], c(0.4747, 0.5754, 0.6516, 0.7781, 0.8723), 4e-2)
}
factorModelRaw <- mxModel(factorFitCI,
mxData(demoOneFactor, type="raw"),
mxFitFunctionML(),
mxExpectationNormal("C", "M", dimnames=manifests),
name = "One Factor FIML")
factorFitRawCI <- mxRun(factorModelRaw, intervals=TRUE, suppressWarnings = TRUE)
factorSummRawCI <- summary(factorFitRawCI)
ci <- factorFitRawCI$output$confidenceIntervals
omxCheckCloseEnough(ci[,'estimate'], c(0.4455, 0.54, 0.6115, 0.7302, 0.8186), 1e-3)
omxCheckCloseEnough(ci[,'lbound'] - c(0.4193, 0.5082, 0.5755, 0.6872, 0.7704), rep(0,5), 1e-3)
omxCheckCloseEnough(ci[,'ubound'], c(0.4747, 0.5754, 0.6516, 0.7781, 0.8723), 1e-3) |
library(utzflm, lib.loc=getOption('unitizer.tmp.lib.loc'))
dat <- data.frame(x=1:100, y=(1:100) ^ 2)
res <- fastlm(dat$x, dat$y)
res
get_slope(res)
get_rsq(res)
fastlm(1:100, 1:10) |
source("helper/helper.R")
if (exists("file.mtime", envir = baseenv())) {
f = get("file.mtime", envir = baseenv())
expect_same = makeCompareFun(f, backports:::file.mtime)
expect_same(R.home())
expect_same(file.path(R.home(), "COPYING"))
} |
age_moto <- function (x,
name = "age",
a = 0.2,
b = 17,
agemin = 1,
agemax = 50,
k = 1,
bystreet = FALSE,
net,
verbose = FALSE,
namerows,
time){
x[is.na(x)] <- 0
x <- as.numeric(x)
if(length(k) > 1 & length(k) < length(x)){
stop("length of 'k' must be 1 ore equal to length of 'x'")
}
if(agemax < 1) stop("Agemax should be bigger than 1")
if (bystreet == TRUE){
if(length(x) != length(a)){
stop("Lengths of veh and age must be the same")
}
d <- suca <- list()
for (i in seq_along(x)) {
suca[[i]] <- function (t) {1/(1 + exp(a[i]*(t+b[i])))+1/(1 + exp(a[i]*(t-b[i])))}
anos <- seq(agemin,agemax)
d[[i]] <- (-1)*diff(suca[[i]](anos))
d[[i]][length(d[[i]])+1] <- d[[i]][length(d[[i]])]
d[[i]] <- d[[i]] + (1 - sum(d[[i]]))/length(d[[i]])
d[[i]] <- d[[i]]*x[i]
}
df <- as.data.frame(matrix(0,ncol=length(anos), nrow=1))
for (i in seq_along(x)) {
df[i,] <- d[[i]]
}
df <- as.data.frame(cbind(as.data.frame(matrix(0,ncol=agemin-1,
nrow=length(x))), df))
names(df) <- paste(name,seq(1,agemax),sep="_")
df <- df*k
if(verbose){
message(paste("Average age of",name, "is",
round(sum(seq(1,agemax)*base::colSums(df)/sum(df)), 2),
sep=" "))
message(paste("Number of",name, "is",
round(sum(df, na.rm = T), 3),
" [veh]",
sep=" "))
cat("\n")
}
if(!missing(namerows)) {
if(length(namerows) != nrow(df)) stop("length of namerows must be the length of number of rows of veh")
row.names(df) <- namerows
}
df[is.na(df)] <- 0
if(!missing(net)){
netsf <- sf::st_as_sf(net)
if(!missing(time)){
dfsf <- sf::st_sf(Vehicles(df*k, time = time), geometry = sf::st_geometry(netsf))
} else {
dfsf <- sf::st_sf(Vehicles(df*k), geometry = sf::st_geometry(netsf))
}
return(dfsf)
} else {
if(!missing(time)){
return(Vehicles(df*k, time = time))
} else {
return(Vehicles(df*k))
}
}
} else {
suca <- function (t) {1/(1 + exp(a*(t+b)))+1/(1 + exp(a*(t-b)))}
anos <- seq(agemin,agemax)
d <- (-1)*diff(suca(anos))
d[length(d)+1] <- d[length(d)]
d <- d + (1 - sum(d))/length(d)
df <- as.data.frame(as.matrix(x) %*%matrix(d,ncol=length(anos), nrow=1))
df <- as.data.frame(cbind(as.data.frame(matrix(0,ncol=agemin-1,
nrow=length(x))), df))
names(df) <- paste(name,seq(1,agemax),sep="_")
df <- df*k
if(verbose){
message(paste("Average age of",name, "is",
round(sum(seq(1,agemax)*base::colSums(df)/sum(df)), 2),
sep=" "))
message(paste("Number of",name, "is",
round(sum(df, na.rm = T)/1000, 2),
"* 10^3 veh", sep=" "))
cat("\n")
}
if(!missing(namerows)) {
if(length(namerows) != nrow(df)) stop("length of namerows must be the length of number of rows of veh")
row.names(df) <- namerows
}
df[is.na(df)] <- 0
if(!missing(net)){
netsf <- sf::st_as_sf(net)
if(!missing(time)){
dfsf <- sf::st_sf(Vehicles(df, time = time), geometry = sf::st_geometry(netsf))
} else {
dfsf <- sf::st_sf(Vehicles(df), geometry = sf::st_geometry(netsf))
}
return(dfsf)
} else {
if(!missing(time)){
return(Vehicles(df, time = time))
} else {
return(Vehicles(df))
}
}
}
} |
cur_svy_env <- rlang::child_env(NULL)
set_current_svy <- function(x) {
stopifnot(inherits(x$full, "tbl_svy") || is_null(x$full))
stopifnot(is.list(x$split) || is_null(x$split))
old <- list(full = cur_svy_env$full, split = cur_svy_env$split)
cur_svy_env$full <- x$full
cur_svy_env$split <- x$split
cur_svy_env$peel_groups <- NULL
invisible(old)
}
peeled_cur_group_id <- function(svy, cur_group) {
if (is.null(cur_svy_env$peel_groups)) {
grp_names <- group_vars(svy)
if (length(grp_names) == 0) {
return(rep(1, nrow(svy)))
}
peel <- grp_names[length(grp_names)]
peel_groups <- group_data(svy)
peel_groups <- group_by_at(peel_groups, setdiff(grp_names, peel))
peel_groups <- summarize(
peel_groups,
grp_rows = list(unlist(.data[[".rows"]])),
peel = list(data.frame(peel_name = .data[[peel]], .rows = .data[[".rows"]]))
)
cur_svy_env$peel_groups <- peel_groups
} else {
peel_groups <- cur_svy_env$peel_groups
}
cur_group <- cur_group()
cur_peel_group <- dplyr::inner_join(
peel_groups,
cur_group[, -ncol(cur_group)],
by = names(cur_group[, -ncol(cur_group)])
)
cur_peel_all <- cur_peel_group$grp_rows[[1]]
cur_group_pos <- equal_or_both_na(
cur_peel_group$peel[[1]]$peel_name,
cur_group[[ncol(cur_group)]]
)
cur_peel_sel <- cur_peel_group$peel[[1]]$.rows[[which(cur_group_pos)]]
out <- rep(NA_integer_, nrow(svy))
out[cur_peel_all] <- 0L
out[cur_peel_sel] <- 1L
out
}
split_context_unavailable <- function(reason) {
structure(list(reason), class = "svy_split_context_unavailable")
}
split_for_context <- function(svy) {
if (inherits(svy$variables, "tbl_lazy") && !is.null(groups(svy))) {
return(split_context_unavailable("lazy"))
}
group_split(svy)
}
cur_svy <- function() {
if (inherits(cur_svy_env$split, "svy_split_context_unavailable")) {
if (cur_svy_env$split[[1]] == "lazy")
rlang::abort("Grouped survey context unavailable for lazy tables.")
}
cur_svy_env$split[[dplyr::cur_group_id()]] %||% rlang::abort("Survey context not set")
}
cur_svy_full <- function() {
cur_svy_env$full %||% rlang::abort("Survey context not set")
}
current_svy <- function() {
warning("`current_svy()` is deprecated, use `cur_svy()` instead")
cur_svy()
}
dplyr::n
dplyr::cur_data
dplyr::cur_group
dplyr::cur_group_id
dplyr::cur_column
dplyr::across
dplyr::c_across |
bnd2gra <- function(map, npoints = 2)
{
if (! inherits(map, "bnd"))
stop("argument 'map' is not an object of class 'bnd'")
regions <- unique(names(map))
nRegions <- length(regions)
retMatrix <- matrix(data=0,
nrow=nRegions, ncol=nRegions,
dimnames=list(regions, regions))
pointsMatrixToPointsCharVector <- function(pointsMatrix)
{
paste(pointsMatrix[, 1L],
pointsMatrix[, 2L],
sep="&")
}
nPairsProcessed <- 0L
nPairs <- (nRegions * (nRegions - 1L)) / 2L
nProgressIterations <- 10L
progressIterations <- seq(from=0L,
to=nPairs,
length=nProgressIterations + 1L)[- 1L]
cat("Start neighbor search ...\n")
pointsMatrix <- NULL
for (i in seq_len(nRegions - 1L))
{
polyIndsRegion.i <- which(names(map) == regions[i])
if(length(polyIndsRegion.i)>1)
{
pointsMatrix <- map[polyIndsRegion.i[1]]
for(k in 2:length(polyIndsRegion.i))
pointsMatrix[[1]] <- rbind(pointsMatrix[[1]], map[polyIndsRegion.i[k]][[1]])
}
else
{
pointsMatrix <- map[polyIndsRegion.i]
}
pointsRegion.i <- sapply(X=pointsMatrix,
FUN=pointsMatrixToPointsCharVector)
for (j in (i + 1):nRegions)
{
polyIndsRegion.j <- which(names(map) == regions[j])
if(length(polyIndsRegion.j)>1)
{
pointsMatrix <- map[polyIndsRegion.j[1]]
for(k in 2:length(polyIndsRegion.j))
pointsMatrix[[1]] <- rbind(pointsMatrix[[1]], map[polyIndsRegion.j[k]][[1]])
}
else
{
pointsMatrix <- map[polyIndsRegion.j]
}
pointsRegion.j <- sapply(X=pointsMatrix,
FUN=pointsMatrixToPointsCharVector)
if (sum(pointsRegion.i %in% pointsRegion.j) >= npoints)
{
retMatrix[i, j] <-
retMatrix[j, i] <- - 1L
}
nPairsProcessed <- nPairsProcessed + 1L
if (nPairsProcessed %in% progressIterations)
{
percentageProcessed <- floor((nPairsProcessed * 100L) / nPairs)
cat(paste("progress: ", percentageProcessed, "%\n",
sep = ""))
}
}
}
cat("Neighbor search finished.\n")
surrounding <- attr(map, "surrounding")
whichPolygonsAreInner <- which(sapply(surrounding, length) > 0L)
for(innerInd in whichPolygonsAreInner)
{
innerRegion <- names(map)[innerInd]
outerRegion <- surrounding[[innerInd]]
retMatrix[innerRegion, outerRegion] <-
retMatrix[outerRegion, innerRegion] <- - 1L
}
diag(retMatrix) <- - rowSums(retMatrix)
class(retMatrix) <- "gra"
return(retMatrix)
} |
setClassUnion("nullOrLASOrDatatable", c("NULL", "LAS", "data.table")) |
context("each_of")
test_that("each_of", {
done <- character()
index <- integer()
coll <- letters[1:10]
do <- async(function() {
dx <- when_all(
.list = lapply(seq_along(coll), function(i) {
force(i)
delay(1/1000)$then(function(value) {
done <<- c(done, coll[[i]])
index <<- c(index, i)
})
})
)$then(function(value) {
expect_identical(sort(index), seq_along(coll))
expect_identical(sort(done), sort(coll))
})
})
synchronise(do())
}) |
repeat_selfloops <- function(eventlog) {
.N <- NULL
case_classifier <- NULL
resource_classifier <- NULL
event_classifier <- NULL
activity_group <- NULL
nr_of_resources <- NULL
t_length <- NULL
eventlog %>%
rework_base %>%
rename("case_classifier" = !!case_id_(eventlog),
"event_classifier" = !!activity_id_(eventlog),
"resource_classifier" = !!resource_id_(eventlog)) %>%
as.data.table %>%
.[, trace_length := .N, by = .(case_classifier)] %>%
.[, activity_frequency := .N, by = .(event_classifier)] %>%
.[, .(t_length = .N, nr_of_resources = n_distinct(resource_classifier), resource_classifier = first(resource_classifier)),
.(case_classifier, activity_group, event_classifier, trace_length, activity_frequency)] %>%
.[nr_of_resources == 1 & t_length > 1] %>%
.[, length := t_length -1] %>%
.[, .(case_classifier, event_classifier, resource_classifier, trace_length, activity_frequency, length)] %>%
as.data.frame -> r
colnames(r)[colnames(r) == "case_classifier"] <- case_id(eventlog)
colnames(r)[colnames(r) == "event_classifier"] <- activity_id(eventlog)
colnames(r)[colnames(r) == "resource_classifier"] <- resource_id(eventlog)
return(r)
}
repeat_selfloops_case <- function(eventlog) {
absolute <- NULL
cases <- eventlog[,case_id(eventlog)] %>% unique
eventlog %>%
repeat_selfloops %>%
group_by(!!case_id_(eventlog), trace_length) %>%
summarize(absolute = n()) %>%
merge(cases, all.y = T) %>%
mutate(absolute = ifelse(is.na(absolute), 0, absolute)) %>%
mutate(relative = absolute/trace_length) %>%
select(-trace_length)
}
repeat_selfloops_size_case <- function(eventlog) {
eventlog %>%
repeat_selfloops %>%
group_by(!!case_id_(eventlog)) %>%
grouped_summary_statistics("length", number_of_selfloops = n()) %>%
select(!!case_id_(eventlog), number_of_selfloops, everything())
}
repeat_selfloops_log <- function(eventlog) {
absolute <- NULL
eventlog %>%
repeat_selfloops_case -> raw
raw %>%
pull(absolute) %>%
summary_statistics -> output
attr(output, "raw") <- raw
return(output)
}
repeat_selfloops_size_log <- function(eventlog, raw = F) {
eventlog %>%
repeat_selfloops -> raw
raw %>%
pull(length) %>%
summary_statistics -> output
attr(output, "raw") <- raw
return(output)
}
repeat_selfloops_activity <- function(eventlog) {
absolute <- NULL
relative <- NULL
activities <- eventlog[,activity_id(eventlog)] %>% unique
eventlog %>%
repeat_selfloops() %>%
group_by(!!activity_id_(eventlog)) %>%
summarize(absolute = n(),
activity_frequency = first(activity_frequency)) %>%
mutate(relative = absolute/activity_frequency) %>%
select(-activity_frequency) %>%
merge(activities, all.y = T) %>%
mutate(absolute = ifelse(is.na(absolute), 0, absolute),
relative = ifelse(is.na(relative), 0, relative))
}
repeat_selfloops_size_activity <- function(eventlog) {
absolute_frequency <- NULL
relative_frequency <- NULL
activities <- eventlog %>% activities
eventlog %>%
repeat_selfloops() %>%
group_by(!!activity_id_(eventlog)) %>%
grouped_summary_statistics("length", number_of_selfloops = n()) %>%
select(!!activity_id_(eventlog), number_of_selfloops, everything()) %>%
merge(activities, . ) %>%
rename(relative_activity_frequency = relative_frequency) %>%
select(-absolute_frequency)
}
repeat_selfloops_resource <- function(eventlog) {
absolute <- NULL
resource <- NULL
absolute_frequency <- NULL
relative_frequency <- NULL
resources <- resources(eventlog)
eventlog %>%
repeat_selfloops() %>%
group_by(!!resource_id_(eventlog)) %>%
summarize(absolute = n()) %>%
merge(resources, all.y = TRUE) %>%
mutate(absolute = ifelse(is.na(absolute), 0, absolute),
relative = absolute/absolute_frequency) %>%
select(-absolute_frequency, -relative_frequency)
}
repeat_selfloops_size_resource <- function(eventlog) {
absolute_frequency <- NULL
relative_frequency <- NULL
resources <- eventlog %>% resources
eventlog %>%
repeat_selfloops() %>%
group_by(!!resource_id_(eventlog)) %>%
grouped_summary_statistics("length", number_of_selfloops = n()) %>%
select(!!resource_id_(eventlog), number_of_selfloops, everything()) %>%
merge(resources, . ) %>%
rename(relative_activity_frequency = relative_frequency) %>%
select(-absolute_frequency)
}
repeat_selfloops_resource_activity <- function(eventlog) {
absolute <- NULL
relative <- NULL
absolute_frequency <- NULL
relative_frequency <- NULL
resources <- resources(eventlog)
eventlog %>%
repeat_selfloops() %>%
group_by(!!activity_id_(eventlog), !!resource_id_(eventlog)) %>%
summarize(absolute = n(),
activity_frequency = first(activity_frequency)) %>%
merge(resources) %>%
mutate(relative_activity = absolute/activity_frequency,
relative_resource = absolute/absolute_frequency) %>%
select(-activity_frequency, -absolute_frequency, -relative_frequency)
}
repeat_selfloops_size_resource_activity <- function(eventlog) {
absolute_frequency <- NULL
relative_frequency <- NULL
resources_activities <- eventlog %>%
group_by(!!resource_id_(eventlog), !!activity_id_(eventlog)) %>%
summarize(absolute_frequency = dplyr::n_distinct(!!activity_instance_id_(eventlog))) %>%
ungroup() %>%
mutate(relative_frequency = absolute_frequency/sum(absolute_frequency)) %>%
select(-absolute_frequency)
eventlog %>%
repeat_selfloops() %>%
group_by(!!resource_id_(eventlog), !!activity_id_(eventlog)) %>%
grouped_summary_statistics("length", number_of_selfloops = n()) %>%
select(!!activity_id_(eventlog), !!resource_id_(eventlog), number_of_selfloops, everything()) %>%
merge(resources_activities, . )
} |
zeroGrob <- function() .zeroGrob
.zeroGrob <- grob(cl = "zeroGrob", name = "NULL")
widthDetails.zeroGrob <- function(x) unit(0, "cm")
heightDetails.zeroGrob <- function(x) unit(0, "cm")
grobWidth.zeroGrob <- function(x) unit(0, "cm")
grobHeight.zeroGrob <- function(x) unit(0, "cm")
drawDetails.zeroGrob <- function(x, recording) {}
is.zero <- function(x) is.null(x) || inherits(x, "zeroGrob") |
generate_dataset <- function(type = c("splines", "polynomial"), num_samples = 100, num_genes = 100) {
type <- match.arg(type)
x <- seq(-1, 1, length.out = num_samples)
switch(
type,
"polynomial"={
y <- stats::poly(x, 2)
sd <- .012 * sqrt(num_genes)
},
"splines"={
y <- splines::ns(x, df=3)
sd <- .06 * sqrt(num_genes)
})
expression <- sapply(seq_len(num_genes), function(g) {
scale <- stats::rnorm(ncol(y), mean=0, sd=1)
noise <- stats::rnorm(length(x), sd=sd)
rowSums(sweep(y, 2, scale, "*")) + noise
})
weighted_random_sample <- function(data, weights, n){
key <- stats::runif(length(data)) ^ (1 / weights)
data[order(key, decreasing=TRUE)][seq_len(n)]
}
undetectable <- which(expression < 0)
undetectable <- weighted_random_sample(undetectable, -expression[undetectable], round(length(undetectable)*.5))
expression <- expression + .5
expression[expression < 0 | seq_along(expression) %in% undetectable] <- 0
dimnames(expression) <- list(paste0("sample", seq_len(num_samples)), paste0("feature", seq_len(num_genes)))
expression
} |
L.matrix <- function( n )
{
if ( missing( n ) )
stop( "argument n is missing" )
if ( !is.numeric( n ) )
stop( "argument n is not numeric" )
if ( n != trunc( n ) )
stop( "argument n is not an integer" )
if ( n < 2 )
stop( "argument n is less than 2" )
u <- u.vectors( n )
E <- E.matrices( n )
k <- u$k
I <- u$I
p <- n * ( n + 1 ) / 2
nsq <- n * n
L <- matrix( 0, nrow=p, ncol=nsq)
for ( j in 1:n ) {
for ( i in j:n ) {
L <- L + I[,k[i,j]] %*% t( vec( E[[i]][[j]] ) )
}
}
return( L )
} |
set.seed(123)
Data <- data_frame(
n = 1:10000,
x = rcauchy(10000),
running_mean = cumsum(x) / (1:length(x))
)
gf_line(running_mean ~ n, data = Data) %>%
gf_labs(y = "running mean", title = "Sample from a Cauchy Distribution") |
ocsApiUserProvisioningManager <- R6Class("ocsApiUserProvisioningManager",
inherit = ocsManager,
public = list(
initialize = function(url, user, pwd, logger = NULL,
keyring_backend = 'env'){
super$initialize(url, user, pwd, logger, keyring_backend)
},
addUser = function(userid, email = NULL, password = NULL, groups = NULL){
request <- "ocs/v1.php/cloud/users"
post_req <- ocs4R::ocsRequest$new(
type = "HTTP_POST", private$url, request,
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
content = list(
userid = userid,
email = email,
password = password,
groups = groups
),
contentType = NULL,
logger = self$loggerType
)
post_req$execute()
post_req_resp <- post_req$getResponse()
added <- post_req_resp$ocs$meta$statuscode == 100
return(added)
},
getUsers = function(){
get_users <- ocs4R::ocsRequest$new(
type = "HTTP_GET", private$url, "ocs/v1.php/cloud/users",
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
logger = self$loggerType
)
get_users$execute()
get_users_resp <- get_users$getResponse()
users <- unlist(get_users_resp$ocs$data$users)
return(users)
},
getUser = function(userid, pretty = FALSE){
get_user <- ocs4R::ocsRequest$new(
type = "HTTP_GET", private$url, sprintf("ocs/v1.php/cloud/users/%s", userid),
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
logger = self$loggerType
)
get_user$execute()
get_user_resp <- get_user$getResponse()
user <- get_user_resp$ocs$data
class(user$enabled) <- "logical"
class(user$two_factor_auth_enabled) <- "logical"
if(pretty){
user <- as.data.frame(t(unlist(user)))
row.names(user) <- 1
}
return(user)
},
editUser = function(userid, key, value){
allowedKeys <- c("email", "quota", "display", "password")
if(!key %in% allowedKeys){
errMsg <- sprintf("Key should be among the following [%s]", paste(allowedKeys, collapse=","))
self$ERROR(errMsg)
stop(errMs)
}
request <- sprintf("ocs/v1.php/cloud/users/%s", userid)
put_req <- ocsRequest$new(
type = "HTTP_PUT", private$url, request,
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
content = list(key = key, value = value),
logger = self$loggerType
)
put_req$execute()
put_req_resp <- put_req$getResponse()
edited <- FALSE
if(is(put_req_resp, "list")) if(!is.null(put_req_resp$key) && !is.null(put_req_resp$value)){
if(put_req_resp$key == key && put_req_resp$value == value) edited <- TRUE
}
return(edited)
},
editUserDisplayName = function(userid, displayName){
return(self$editUser(userid, key = "display", value = displayName))
},
editUserEmail = function(userid, email){
return(self$editUser(userid, key = "email", value = email))
},
editUserPassword = function(userid, password){
return(self$editUser(userid, key = "password", value = password))
},
editUserQuota = function(userid, quota){
return(self$editUser(userid, key = "quota", value = quota))
},
enableUser = function(userid){
request <- sprintf("ocs/v1.php/cloud/users/%s/enable", userid)
put_req <- ocsRequest$new(
type = "HTTP_PUT", private$url, request,
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
content = "",
logger = self$loggerType
)
put_req$execute()
return(TRUE)
},
disableUser = function(userid){
request <- sprintf("ocs/v1.php/cloud/users/%s/disable", userid)
put_req <- ocsRequest$new(
type = "HTTP_PUT", private$url, request,
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
content = "",
logger = self$loggerType
)
put_req$execute()
return(TRUE)
},
deleteUser = function(userid){
request <- sprintf("ocs/v1.php/cloud/users/%s", userid)
delete_req <- ocsRequest$new(
type = "HTTP_DELETE", private$url, request,
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
logger = self$loggerType
)
delete_req$execute()
return(TRUE)
},
getUserGroups = function(userid){
get_usergroups <- ocs4R::ocsRequest$new(
type = "HTTP_GET", private$url, sprintf("ocs/v1.php/cloud/users/%s/groups", userid),
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
logger = self$loggerType
)
get_usergroups$execute()
get_usergroups_resp <- get_usergroups$getResponse()
usergroups <- unlist(get_usergroups_resp$ocs$data$groups)
return(usergroups)
},
addToGroup = function(userid, groupid){
request <- sprintf("ocs/v1.php/cloud/users/%s/groups", userid)
post_req <- ocs4R::ocsRequest$new(
type = "HTTP_POST", private$url, request,
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
content = list(groupid = groupid),
contentType = NULL,
logger = self$loggerType
)
post_req$execute()
post_req_resp <- post_req$getResponse()
added <- post_req_resp$ocs$meta$statuscode == 100
return(added)
},
removeFromGroup = function(userid, groupid){
request <- sprintf("ocs/v1.php/cloud/users/%s/groups", userid)
delete_req <- ocsRequest$new(
type = "HTTP_DELETE", private$url, request,
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
content = list(groupid = groupid),
logger = self$loggerType
)
delete_req$execute()
return(TRUE)
},
createSubadmin = function(){
stop("'createSubadmin' method not yet implemented")
},
removeSubadmin = function(){
stop("'removeSubadmin' method not yet implemented")
},
getSubadminGroups = function(){
stop("'getSubadminGroups' method not yet implemented")
},
getGroups = function(search = NULL, limit = NULL, offset = NULL){
get_groups <- ocs4R::ocsRequest$new(
type = "HTTP_GET", private$url, "ocs/v1.php/cloud/groups",
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
namedParams = list(search = search, limit = limit, offset = offset),
logger = self$loggerType
)
get_groups$execute()
get_groups_resp <- get_groups$getResponse()
groups <- unlist(get_groups_resp$ocs$data$groups)
return(groups)
},
addGroup = function(groupid){
request <- "ocs/v1.php/cloud/groups"
post_req <- ocs4R::ocsRequest$new(
type = "HTTP_POST", private$url, request,
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
content = list(groupid = groupid),
contentType = NULL,
logger = self$loggerType
)
post_req$execute()
post_req_resp <- post_req$getResponse()
added <- post_req_resp$ocs$meta$statuscode == 100
return(added)
},
getGroup = function(groupid){
get_group <- ocs4R::ocsRequest$new(
type = "HTTP_GET", private$url, sprintf("ocs/v1.php/cloud/groups/%s", groupid),
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
logger = self$loggerType
)
get_group$execute()
get_group_resp <- get_group$getResponse()
group <- list(id = groupid, users = unlist(get_group_resp$ocs$data$users))
return(group)
},
deleteGroup = function(groupid){
request <- sprintf("ocs/v1.php/cloud/groups/%s", groupid)
delete_req <- ocsRequest$new(
type = "HTTP_DELETE", private$url, request,
private$user, pwd = private$keyring_backend$get(service = private$keyring_service, username = paste0(private$user,"_pwd")),
token = private$getToken(), cookies = private$cookies,
logger = self$loggerType
)
delete_req$execute()
return(TRUE)
},
getSubadmins = function(){
stop("'getSubadmins' method not yet implemented")
}
)
) |
expected <- eval(parse(text="c(5.4278733372119e-07, 0.000257866433233453, NA)"));
test(id=0, code={
argv <- eval(parse(text="list(structure(c(5.4278733372119e-07, 0.000257866433233453, NA), .Names = c(\"x\", \"m\", \"Residuals\")), \"any\")"));
.Internal(as.vector(argv[[1]], argv[[2]]));
}, o=expected); |
knitr::opts_chunk$set(collapse = TRUE, comment = "
fig.width = 6, fig.height = 5)
library(viridis)
palette(viridis(3))
rm(list=ls())
graphics.off()
set.seed(1)
library(SIBER)
data("demo.siber.data")
siber.example <- createSiberObject(demo.siber.data)
community.hulls.args <- list(col = 1, lty = 1, lwd = 1)
group.ellipses.args <- list(n = 100, p.interval = 0.95, lty = 1, lwd = 2)
group.hulls.args <- list(lty = 2, col = "grey20")
par(mfrow=c(1,1))
plotSiberObject(siber.example,
ax.pad = 2,
hulls = F, community.hulls.args = community.hulls.args,
ellipses = T, group.ellipses.args = group.ellipses.args,
group.hulls = T, group.hulls.args = group.hulls.args,
bty = "L",
iso.order = c(1,2),
xlab = expression({delta}^13*C~'\u2030'),
ylab = expression({delta}^15*N~'\u2030')
)
par(mfrow=c(1,1))
community.hulls.args <- list(col = 1, lty = 1, lwd = 1)
group.ellipses.args <- list(n = 100, p.interval = 0.95, lty = 1, lwd = 2)
group.hull.args <- list(lty = 2, col = "grey20")
plotSiberObject(siber.example,
ax.pad = 2,
hulls = F, community.hulls.args,
ellipses = F, group.ellipses.args,
group.hulls = F, group.hull.args,
bty = "L",
iso.order = c(1,2),
xlab=expression({delta}^13*C~'\u2030'),
ylab=expression({delta}^15*N~'\u2030'),
cex = 0.5
)
group.ML <- groupMetricsML(siber.example)
print(group.ML)
plotGroupEllipses(siber.example, n = 100, p.interval = 0.95,
lty = 1, lwd = 2)
plotGroupEllipses(siber.example, n = 100, p.interval = 0.95, ci.mean = T,
lty = 1, lwd = 2)
plotSiberObject(siber.example,
ax.pad = 2,
hulls = T, community.hulls.args,
ellipses = F, group.ellipses.args,
group.hulls = F, group.hull.args,
bty = "L",
iso.order = c(1,2),
xlab=expression({delta}^13*C~'\u2030'),
ylab=expression({delta}^15*N~'\u2030'),
cex = 0.5
)
plotGroupEllipses(siber.example, n = 100, p.interval = 0.95,
ci.mean = T, lty = 1, lwd = 2)
community.ML <- communityMetricsML(siber.example)
print(community.ML)
parms <- list()
parms$n.iter <- 2 * 10^4
parms$n.burnin <- 1 * 10^3
parms$n.thin <- 10
parms$n.chains <- 2
priors <- list()
priors$R <- 1 * diag(2)
priors$k <- 2
priors$tau.mu <- 1.0E-3
ellipses.posterior <- siberMVN(siber.example, parms, priors)
SEA.B <- siberEllipses(ellipses.posterior)
siberDensityPlot(SEA.B, xticklabels = colnames(group.ML),
xlab = c("Community | Group"),
ylab = expression("Standard Ellipse Area " ('\u2030' ^2) ),
bty = "L",
las = 1,
main = "SIBER ellipses on each group"
)
points(1:ncol(SEA.B), group.ML[3,], col="red", pch = "x", lwd = 2)
cr.p <- c(0.95, 0.99)
SEA.B.credibles <- lapply(
as.data.frame(SEA.B),
function(x,...){tmp<-hdrcde::hdr(x)$hdr},
prob = cr.p)
SEA.B.modes <- lapply(
as.data.frame(SEA.B),
function(x,...){tmp<-hdrcde::hdr(x)$mode},
prob = cr.p, all.modes=T)
mu.post <- extractPosteriorMeans(siber.example, ellipses.posterior)
layman.B <- bayesianLayman(mu.post)
siberDensityPlot(layman.B[[1]], xticklabels = colnames(layman.B[[1]]),
bty="L", ylim = c(0,20))
comm1.layman.ml <- laymanMetrics(siber.example$ML.mu[[1]][1,1,],
siber.example$ML.mu[[1]][1,2,]
)
points(1:6, comm1.layman.ml$metrics, col = "red", pch = "x", lwd = 2)
siberDensityPlot(layman.B[[2]], xticklabels = colnames(layman.B[[2]]),
bty="L", ylim = c(0,20))
comm2.layman.ml <- laymanMetrics(siber.example$ML.mu[[2]][1,1,],
siber.example$ML.mu[[2]][1,2,]
)
points(1:6, comm2.layman.ml$metrics, col = "red", pch = "x", lwd = 2)
par(mfrow=c(1,1))
siberDensityPlot(cbind(layman.B[[1]][,"TA"], layman.B[[2]][,"TA"]),
xticklabels = c("Community 1", "Community 2"),
bty="L", ylim = c(0,20),
las = 1,
ylab = "TA - Convex Hull Area",
xlab = "") |
buildModMedSemModel <- function(xvar,
mvars,
yvar,
xmmod = NULL,
mymod = NULL,
cmvars = NULL,
cyvars = NULL) {
nm <- length(mvars);
ncm <- length(cmvars);
ncy <- length(cyvars);
a1 <- NULL
a2 <- 1:nm;
b2 <- NULL
b1 <- a2;
c1 <- 1:length(cmvars);
c2 <- 1:length(cyvars);
h <- as.vector(outer(1:nm, 1:ncm, paste0));
a <- paste0("a",a1,a2)
if (!is.null(xmmod)) {
w1 <- paste0("w",a2)
w2 <- paste0("im",a2)
}
b <- paste0("b",b1,b2)
if(!is.null(mymod)) {
v1 <- paste0("v",b2)
v2 <- paste0("iy",a2)
}
c <- paste0("cp",a1,b2);
d <- paste0("d",h);
f <- paste0("f",c2,b2);
model_cov1 <- " ";
if (length(cmvars) > 1) {
ha <- expand.grid(cmvars,cmvars);
hb <- matrix(data=c(1:(ncm**2)),nrow=ncm,ncol=ncm);
s <- as.vector(lower.tri(hb));
ha <- ha[s,];
model_cov1 <- paste0(ha[,1], " ~~ " , ha[,2], collapse = " \n ");
}
model_cov2 <- " ";
vars <- c(mvars, cyvars);
if (length(vars) > 1) {
nmy <- nm + ncy;
ha <- expand.grid(vars,vars);
hb <- matrix(data=c(1:(nmy**2)),nrow=nmy,ncol=nmy);
s <- as.vector(lower.tri(hb));
ha <- ha[s,];
model_cov2 <- paste0(ha[,1], " ~~ " , ha[,2], collapse = " \n ");
}
ind <- paste0("ind", a2 );
modmedx <- paste0("modmedx", a2 );
modmedm <- paste0("modmedm", a2 );
bw <- paste0("bw", a2 );
gw <- paste0("gw", a2 );
ratio <- paste0("ratio", a2)
modela2 <- " ";
modelb2 <- " ";
modelw <- " ";
modelw2 <- " ";
modelv <- " ";
modelv2 <- " "
modeli1 <- " ";
modeli3 <- " ";
modeli5 <- " ";
modeli2 <- " ";
modeld <- " ";
modelf <- " ";
if(!is.null(xmmod)) {
xmint <- paste0("xmInteraction",c(1:nm));
}
if(!is.null(mymod)) {
myint <- paste0("myInteraction",c(1:nm));
}
modela1 <- paste0(mvars, " ~ " ,a,"*",xvar , collapse = " \n ");
if(!is.null(xmmod)) {
modelw <- paste0( mvars, " ~ " ,w1,"*",xmmod , collapse = " \n ");
modelw2 <- paste0( mvars, " ~ " ,w2,"*",xmint , collapse = " \n ");
}
modelb1 <- paste0( yvar, " ~ " ,b,"*",mvars , collapse = " \n ");
if(!is.null(mymod)) {
modelv <- paste0( yvar, " ~ " ,v1,"*",mymod , collapse = " \n ");
modelv2 <- paste0( yvar, " ~ " ,v2,"*",myint , collapse = " \n ");
}
modelc <- paste0( yvar, " ~ " ,c,"*",xvar , collapse = " \n ");
if (!is.null(cmvars)) {
modeld <- paste0( rep(mvars,ncm), " ~ " ,d,"*",rep(cmvars, each=nm) , collapse = " \n ");
}
if (!is.null(cyvars)) {
modelf <- paste0( yvar, " ~ " ,f,"*",cyvars , collapse = " \n ");
}
modeli <- paste0(ind , " := " , a, " * ", b, collapse = " \n ");
if(!is.null(xmmod)) {
modeli1 <- paste0(modmedx , " := " , w2, " * ", b, collapse = " \n ");
modeli3 <- paste0(bw , " := " , w1, " * ", b, collapse = " \n ");
modeli5 <- paste0(gw , " := " , w1, " * ", w2, collapse = " \n ");
}
if(!is.null(mymod)) {
modeli2 <- paste0(modmedm , " := " , v2, " * ", a, collapse = " \n ");
}
sumInd <- paste0(ind, collapse = " + ")
modelt <- paste0("tot := " , sumInd);
modelr <- paste0(ratio," := " , "(",ind, ")" ,"/" , "(",ind, "+", c, ")" , collapse = " \n ");
modelrt <- paste0("ratio_tot := " , paste0("(",sumInd,")", "/" , "(",sumInd, "+", c,")"));
model <- paste0(modela1," \n ",modela2," \n ",
modelb1," \n ", modelb2," \n ",
modelc, " \n ", modeld, " \n ",
modelw, " \n ", modelw2, " \n ",
modelv, " \n ", modelv2, " \n ",
modelf, " \n ",
model_cov1," \n ", model_cov2, " \n ",
modeli, " \n ", modeli1, " \n ", modeli2, " \n ",modeli3, " \n ", modeli5, " \n ",
modelt, " \n ", modelr, " \n ", modelrt);
return(model)
} |
get_recent_lobbying_representation_filings <- function(page = 1, myAPI_Key){
API = 'congress'
query <- "lobbying/latest.json"
pp_query(query, API, page = page, myAPI_Key = myAPI_Key)
} |
HELP3 <-
mutate(
HELPrct,
risklevel = derivedFactor(
low = sexrisk < 5,
medium = sexrisk < 10,
high = sexrisk >= 10,
.method = "first"
)
)
gf_jitter(sexrisk ~ risklevel, data = HELP3,
height = 0.2, width = 0.3, alpha = 0.4) |
knitRev <- function(){
knitr::knit_engines$set(rb = function(options) {
output <- doRev(paste(options$code, collapse = "\n"))
return(knitr::engine_output(options, code = options$code, out = c(output)))
})
} |
object_format <- function(x) {
UseMethod("object_format")
}
object_format.default <- function(x) {
paste0("An object of class ", format_classes(x), " ", format_dim(x), ".")
}
format_classes <- function(x) {
classes <- paste0("\\code{", class(x), "}")
base_classes <- NULL
if (length(classes) > 1L) {
base_classes <- paste0(
" (inherits from ",
paste(classes[-1L], collapse = ", "),
")")
}
paste0(classes[[1L]], base_classes)
}
format_dim <- function(x) {
if (length(dim(x)) == 2L) {
paste0("with ", nrow(x), " rows and ", ncol(x), " columns")
} else if (length(dim(x)) > 2L) {
paste0("of dimension ", paste(dim(x), collapse = " x "))
} else {
paste0("of length ", length(x))
}
}
call_to_format <- function(code, env = pkg_env()) {
obj <- call_to_object(!!enexpr(code), env)
object_format(obj$value)
} |
context("Cite")
test_that("Cite", {
ci <- Citation(suffix=list(Str("Suffix_1")),
id="Citation_ID_1", prefix=list(Str("Prefix_1")))
cite <- Cite(list(ci), list(Str("some text")))
x <- pandocfilters:::test(list(Header(list(cite))), to="markdown")
expect_that(x, equals("@Citation_ID_1 [Suffix\\_1]\n=========================="))
cite <- Cite(list(ci), Str("some text"))
x <- pandocfilters:::test(list(Header(list(cite))), to="markdown")
expect_that(x, equals("@Citation_ID_1 [Suffix\\_1]\n=========================="))
cite <- Cite(ci, Str("some text"))
x <- pandocfilters:::test(list(Header(list(cite))), to="markdown")
expect_that(x, equals("@Citation_ID_1 [Suffix\\_1]\n=========================="))
x <- pandocfilters:::test(list(Header(cite)), to="markdown")
expect_that(x, equals("@Citation_ID_1 [Suffix\\_1]\n=========================="))
cite <- Cite(list(ci), list(Str("some text")))
x <- pandocfilters:::test(list(Plain(list(cite))), to="markdown")
expect_that(x, equals("@Citation_ID_1 [Suffix\\_1]"))
cite <- Cite(list(ci), Str("some text"))
x <- pandocfilters:::test(list(Plain(list(cite))), to="markdown")
expect_that(x, equals("@Citation_ID_1 [Suffix\\_1]"))
cite <- Cite(ci, Str("some text"))
x <- pandocfilters:::test(list(Plain(list(cite))), to="markdown")
expect_that(x, equals("@Citation_ID_1 [Suffix\\_1]"))
x <- pandocfilters:::test(list(Plain(cite)), to="markdown")
expect_that(x, equals("@Citation_ID_1 [Suffix\\_1]"))
} ) |
plotdiag.leverage <-
function(forn,
hilos=c(1,0),
maintitle = "Put main title here",
subtitle = "Put subtitle here",
wmf = "Put_graph_title_here",
Cairo=TRUE,
printgraph = TRUE,
subdiag=FALSE, subverb=FALSE,
diagnose=FALSE, verbose=TRUE)
{
MC <- match.call()
if(verbose) {
print("", quote = FALSE)
print("Running plot.diag.leverage", quote = FALSE)
print("", quote = FALSE)
print(date(), quote = FALSE)
print("", quote = FALSE)
print("Call:", quote = FALSE)
print(MC)
print("", quote = FALSE)
}
plotD1 <- function(data, xcol, ycol, cov2col, df3,
highslows,
mtitle, stitle, cap,
horlabel, vertlabel,
filewidth, fileheight,
subdiag, subverb)
{
XVAR <- data[,xcol]
YVAR <- data[,ycol]
COV2 <- data[,cov2col]
SD <- data$SD
N <- data$N
dfplot <- data.frame(COV2,XVAR,YVAR,SD,N)
if(diagnose)Hmisc::prn(dfplot)
upper <- dfplot$YVAR + dfplot$SD
lower <- dfplot$YVAR - dfplot$SD
dfplot <- data.frame(dfplot,upper,lower)
out <- ggplot2::ggplot(data=dfplot, ggplot2::aes(x=XVAR, y=YVAR, group=COV2, color=COV2))
out <- out + ggplot2::geom_line() + ggplot2::geom_errorbar(ggplot2::aes(x=XVAR,ymin=lower,ymax=upper),width=0.2)+ ggplot2::theme(legend.position="none")
highs <- highslows[1]
if(diagnose) Hmisc::prn(df3)
if(highs>0){
dim2 <- max(XVAR)
for(ihigh in 1:highs){
out <- out + ggplot2::annotate("text", x=dim2+3,y=df3[ihigh,3],label=as.character(df3[ihigh,2]))
}
}
out <- out + ggplot2::ggtitle(mtitle,subtitle=stitle) + ggplot2::xlab(horlabel) + ggplot2::ylab(vertlabel) + ggplot2::labs(caption=cap)
if(diagnose) Hmisc::prn(as.character(out))
if(Cairo){
Cairo::CairoWin(width = 7, height = 7, pointsize = 12, record = getOption("graphics.record"),
rescale = c("R", "fit", "fixed"), bg = "transparent", canvas = "white", gamma = getOption("gamma"),
xpos = NA, ypos = NA, buffered = getOption("windowsBuffered"), restoreConsole = FALSE)
}
Hmisc::prn(out)
if(printgraph){
filename <- paste(wmf,".wmf",sep="")
ggplot2::ggsave(filename,width=filewidth, height=fileheight)
grDevices::dev.off()
}
if(subverb) {
print("", quote = F)
print("Finished running plotD1", quote = F)
print("", quote = F)
print(date(), quote = F)
print("", quote = F)
}
}
prepstuff <- function(rightforn,gg){
df1 <- rightforn$Leverage
SD <- 0
N <- 1
df2 <- data.frame(df1, SD, N)
if(diagnose) Hmisc::prn(df2)
if(diagnose) temphist <- search.history(rightforn)
df2order <- df2[order(df2$m),]
maxm <- max(df2[,1])
df3 <- df2[df2[,1]==maxm,,]
df3 <- df3[ order(df3[,3],decreasing=TRUE) ,]
print("", quote = F)
print("Observation leverages in order of final value", quote=FALSE)
print(utils::head(df3[,2:3],n=10L), quote=FALSE)
print("", quote = F)
cap2 <- paste("Average final leverage p/n =",round(min(df2[,1]) / maxm, 2), sep=" ")
wmf2 <- paste(wmf,".wmf",sep="")
if(grouped){
cap2 <- paste(cap2,paste("Subgroup",gg),sep=". ")
wmf2 <- paste(wmf," Subgroup ",gg,".wmf",sep="")
}
plotD1(data=df2, xcol=1, ycol=3, cov2col=2, df3=df3,
mtitle=maintitle,
stitle=subtitle,
highslows=hilos,
horlabel="Subset size m",
vertlabel="Leverage",
cap=cap2, filewidth=5,fileheight=5,
subdiag=subdiag,subverb=subverb)
}
grouped <- FALSE
if(grouped){
nnames_forn <- length(forn)
for(gg in 1:nnames_forn){
prepstuff(rightforn=forn[[gg]], gg)
}
}
else{
prepstuff(rightforn=forn, gg="")
}
if(verbose) {
print("", quote = FALSE)
print("Finished running plot.diag.leverage", quote = FALSE)
print("", quote = FALSE)
print(date(), quote = FALSE)
print("", quote = FALSE)
}
} |
I.spline=function(time,xi1,xi3){
if(min(time)<xi1){warning("time should be larger than xi1")}
if(max(time)>xi3){warning("time should be smaller than xi3")}
D=(xi3-xi1)/2
xi2=xi1+D
z1=(time-xi1)/D;z2=(time-xi2)/D;z3=(time-xi3)/D
I1=(1-z2^4)*(time<xi2)+1*(time>=xi2)
I2=( 7/8*z1^4-3*z1^3+3*z1^2 )*(time<xi2)+( 1-z3^4/8 )*(time>=xi2)
I3=( -z1^4/2+z1^3 )*(time<xi2)+( 1/2+z2^4/2-z2^3+z2 )*(time>=xi2)
I4=( z1^4/8 )*(time<xi2)+( 1/8-7/8*z2^4+1/2*z2^3+3/4*z2^2+1/2*z2 )*(time>=xi2)
I5=z2^4*(time>=xi2)
cbind(I1,I2,I3,I4,I5)
} |
spLines <- function(x, ..., attr=NULL, crs="") {
x <- c(list(x), list(...))
x <- rapply(x, sp::Line, how='replace')
x <- lapply(1:length(x), function(i) sp::Lines(x[[i]], as.character(i)))
x <- sp::SpatialLines(x)
if (!is.null(attr)) {
if (nrow(attr) == length(x)) {
x <- sp::SpatialLinesDataFrame(x, attr)
} else {
msg <- paste('number of rows in attr (', nrow(attr), ') does not match the number of lines (', length(x), ')', sep='')
stop(msg)
}
}
if (!is.na(crs)) {
crs(x) <- crs
}
x
}
spPolygons <- function(x, ..., attr=NULL, crs="") {
x <- c(list(x), list(...))
x <- rapply(x, sp::Polygon, how='replace')
x <- lapply(1:length(x), function(i) {
if (length(x[[i]]) == 1) {
sp::Polygons(x[i], as.character(i))
} else {
sp::Polygons(x[[i]], as.character(i))
}
})
x <- sp::SpatialPolygons(x)
if (!is.null(attr)) {
if (nrow(attr) == length(x)) {
x <- sp::SpatialPolygonsDataFrame(x, attr)
} else {
msg <- paste('number of rows in attr (', nrow(attr), ') does not match the number of polygons (', length(x), ')', sep='')
stop(msg)
}
}
if (!is.na(crs)) {
crs(x) <- crs
}
x
} |
expected <- eval(parse(text="NULL"));
test(id=0, code={
argv <- eval(parse(text="list(structure(list(`1000/MPG.city` = c(40, 55.5555555555556, 50, 52.6315789473684, 45.4545454545455, 45.4545454545455, 52.6315789473684, 62.5, 52.6315789473684, 62.5, 62.5, 40, 40, 52.6315789473684, 47.6190476190476, 55.5555555555556, 66.6666666666667, 58.8235294117647, 58.8235294117647, 50, 43.4782608695652, 50, 34.4827586206897, 43.4782608695652, 45.4545454545455, 58.8235294117647, 47.6190476190476, 55.5555555555556, 34.4827586206897, 50, 32.258064516129, 43.4782608695652, 45.4545454545455, 45.4545454545455, 41.6666666666667, 66.6666666666667, 47.6190476190476, 55.5555555555556, 21.7391304347826, 33.3333333333333, 41.6666666666667, 23.8095238095238, 41.6666666666667, 34.4827586206897, 45.4545454545455, 38.4615384615385, 50, 58.8235294117647, 55.5555555555556, 55.5555555555556, 58.8235294117647, 55.5555555555556, 34.4827586206897, 35.7142857142857, 38.4615384615385, 55.5555555555556, 58.8235294117647, 50, 52.6315789473684, 43.4782608695652, 52.6315789473684, 34.4827586206897, 55.5555555555556, 34.4827586206897, 41.6666666666667, 58.8235294117647, 47.6190476190476, 41.6666666666667, 43.4782608695652, 55.5555555555556, 52.6315789473684, 43.4782608695652, 32.258064516129, 43.4782608695652, 52.6315789473684, 52.6315789473684, 52.6315789473684, 50, 35.7142857142857, 30.3030303030303, 40, 43.4782608695652, 25.6410256410256, 31.25, 40, 45.4545454545455, 55.5555555555556, 40, 58.8235294117647, 47.6190476190476, 55.5555555555556, 47.6190476190476, 50), Weight = c(2705L, 3560L, 3375L, 3405L, 3640L, 2880L, 3470L, 4105L, 3495L, 3620L, 3935L, 2490L, 2785L, 3240L, 3195L, 3715L, 4025L, 3910L, 3380L, 3515L, 3085L, 3570L, 2270L, 2670L, 2970L, 3705L, 3080L, 3805L, 2295L, 3490L, 1845L, 2530L, 2690L, 2850L, 2710L, 3735L, 3325L, 3950L, 1695L, 2475L, 2865L, 2350L, 3040L, 2345L, 2620L, 2285L, 2885L, 4000L, 3510L, 3515L, 3695L, 4055L, 2325L, 2440L, 2970L, 3735L, 2895L, 2920L, 3525L, 2450L, 3610L, 2295L, 3730L, 2545L, 3050L, 4100L, 3200L, 2910L, 2890L, 3715L, 3470L, 2640L, 2350L, 2575L, 3240L, 3450L, 3495L, 2775L, 2495L, 2045L, 2490L, 3085L, 1965L, 2055L, 2950L, 3030L, 3785L, 2240L, 3960L, 2985L, 2810L, 2985L, 3245L), Cylinders = structure(c(2L, 4L, 4L, 4L, 2L, 2L, 4L, 4L, 4L, 5L, 5L, 2L, 2L, 4L, 2L, 4L, 4L, 5L, 5L, 4L, 2L, 4L, 2L, 2L, 2L, 4L, 2L, 4L, 2L, 4L, 2L, 2L, 2L, 2L, 2L, 4L, 4L, 5L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 5L, 4L, 4L, 4L, 5L, 2L, 2L, 2L, 4L, 6L, 2L, 4L, 2L, 4L, 2L, 4L, 2L, 2L, 4L, 4L, 2L, 2L, 4L, 4L, 2L, 2L, 2L, 4L, 4L, 4L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 4L, 2L, 3L), .Label = c(\"3\", \"4\", \"5\", \"6\", \"8\", \"rotary\"), class = \"factor\"), Type = structure(c(4L, 3L, 1L, 3L, 3L, 3L, 2L, 2L, 3L, 2L, 3L, 1L, 1L, 5L, 3L, 6L, 6L, 2L, 5L, 2L, 1L, 2L, 4L, 4L, 1L, 6L, 3L, 5L, 4L, 2L, 4L, 4L, 1L, 5L, 5L, 6L, 3L, 2L, 4L, 5L, 5L, 4L, 1L, 4L, 4L, 5L, 3L, 3L, 3L, 3L, 3L, 2L, 4L, 4L, 1L, 6L, 5L, 1L, 3L, 5L, 3L, 4L, 3L, 4L, 1L, 6L, 3L, 1L, 3L, 6L, 2L, 5L, 4L, 1L, 5L, 3L, 2L, 1L, 4L, 4L, 4L, 1L, 4L, 4L, 5L, 3L, 6L, 4L, 6L, 1L, 5L, 1L, 3L), .Label = c(\"Compact\", \"Large\", \"Midsize\", \"Small\", \"Sporty\", \"Van\"), class = \"factor\"), EngineSize = c(1.8, 3.2, 2.8, 2.8, 3.5, 2.2, 3.8, 5.7, 3.8, 4.9, 4.6, 2.2, 2.2, 3.4, 2.2, 3.8, 4.3, 5, 5.7, 3.3, 3, 3.3, 1.5, 2.2, 2.5, 3, 2.5, 3, 1.5, 3.5, 1.3, 1.8, 2.3, 2.3, 2, 3, 3, 4.6, 1, 1.6, 2.3, 1.5, 2.2, 1.5, 1.8, 1.5, 2, 4.5, 3, 3, 3.8, 4.6, 1.6, 1.8, 2.5, 3, 1.3, 2.3, 3.2, 1.6, 3.8, 1.5, 3, 1.6, 2.4, 3, 3, 2.3, 2.2, 3.8, 3.8, 1.8, 1.6, 2, 3.4, 3.4, 3.8, 2.1, 1.9, 1.2, 1.8, 2.2, 1.3, 1.5, 2.2, 2.2, 2.4, 1.8, 2.5, 2, 2.8, 2.3, 2.4), DriveTrain = structure(c(2L, 2L, 2L, 2L, 3L, 2L, 2L, 3L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 2L, 1L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 1L, 2L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 3L, 2L, 3L, 2L, 2L, 2L, 1L, 3L, 3L, 3L, 2L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 3L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 3L, 2L), .Label = c(\"4WD\", \"Front\", \"Rear\"), class = \"factor\")), .Names = c(\"1000/MPG.city\", \"Weight\", \"Cylinders\", \"Type\", \"EngineSize\", \"DriveTrain\"), terms = quote(1000/MPG.city ~ Weight + Cylinders + Type + EngineSize + DriveTrain), row.names = c(NA, 93L), class = \"data.frame\"), \"na.action\")"));
do.call(`attr`, argv);
}, o=expected); |
header.textile <- function(caption = NULL, caption.level = NULL, frame = NULL, width = 0) {
if (!is.null(frame)) {
frame <- switch(frame, topbot = "border-top:1px solid black;border-bottom:1px solid black", sides = "border-left:1px solid black;border-right:1px solid black", all = "border:1px solid black", none = "")
}
if (width != 0) {
width <- paste("width:", width, "%", sep = "")
} else {
width <- ""
}
listarg <- c(frame, width)
listarg <- listarg[listarg != ""]
if (length(listarg) != 0) {
res <- paste("table{", paste(listarg, collapse = ";"), "}.\n", sep = "")
}
else res <- ""
if (!is.null(caption)) {
if (!is.null(caption.level)) {
if (is.numeric(caption.level) & caption.level > 0) { lev <- paste("h", caption.level, ".", sep = "") ; res <- paste(lev, " ", caption, "\n\n", sep = "") }
else if (caption.level == "s") res <- paste(beauty.textile(caption, "s"), "\n\n", sep = "")
else if (caption.level == "e") res <- paste(beauty.textile(caption, "e"), "\n\n", sep = "")
else if (caption.level == "m") res <- paste(beauty.textile(caption, "m"), "\n\n", sep = "")
} else {
res <- paste(caption, "\n\n", res, sep = "")
}
}
return(res)
}
beauty.textile <- function(x, beauti = c("e", "m", "s")) {
x[is.na(x)] <- "NA"
if (beauti == "s") {
y <- as.logical((regexpr("^ *$", x)+1)/2) | as.logical((regexpr("\\*.*\\*", x)+1)/2)
if (length(x[!y]) != 0) x[!y] <- sub("(^ *)([:alpha]*)", "\\1\\*\\2", sub("([:alpha:]*)( *$)", "\\1\\*\\2", x[!y]))
}
if (beauti == "e") {
y <- as.logical((regexpr("^ *$", x)+1)/2) | as.logical((regexpr("/.*/", x)+1)/2)
if (length(x[!y]) != 0) x[!y] <-sub("(^ *)([:alpha]*)", "\\1/\\2", sub("([:alpha:]*)( *$)", "\\1/\\2", x[!y]))
}
if (beauti == "m") {
y <- as.logical((regexpr("^ *$", x)+1)/2) | as.logical((regexpr("<code>.*</code>", x)+1)/2)
if (length(x[!y]) != 0) x[!y] <-sub("(^ *)([:alpha]*)", "\\1<code>\\2", sub("([:alpha:]*)( *$)", "\\1</code>\\2", x[!y]))
}
return(x)
}
vsep.textile <- function (align = NULL, valign = NULL, style = NULL) {
if (is.null(align) & is.null(valign) & is.null(style)) {
res <- ""
} else {
if (is.null(align))
align <- ""
if (is.null(valign))
valign <- ""
if (is.null(style))
style <- ""
align[align == "l"] <- "<"
align[align == "c"] <- "="
align[align == "r"] <- ">"
valign[valign == "top"] <- "^"
valign[valign == "middle"] <- "-"
valign[valign == "bottom"] <- "~"
style[style == "s"] <- "{font-weight:bold}"
style[style == "e"] <- "{font-style:italic}"
style[style == "m"] <- "{font-family:Monospace}"
res <- paste.matrix(align, valign, style, sep = "")
}
return(res)
}
escape.textile <- function(x) {
xx <- gsub("\\|", "\\\\|", x)
xx
}
show.textile.table <- function(x, include.rownames = FALSE, include.colnames = FALSE, rownames = NULL, colnames = NULL, format = "f", digits = 2, decimal.mark = ".", na.print = "", caption = NULL, caption.level = NULL, width = 0, frame = NULL, grid = NULL, valign = NULL, header = FALSE, footer = FALSE, align = NULL, col.width = 1, style = NULL, lgroup = NULL, n.lgroup = NULL, lalign = "c", lvalign = "middle", lstyle = "h", rgroup = NULL, n.rgroup = NULL, ralign = "c", rvalign = "middle", rstyle = "h", tgroup = NULL, n.tgroup = NULL, talign = "c", tvalign = "middle", tstyle = "h", bgroup = NULL, n.bgroup = NULL, balign = "c", bvalign = "middle", bstyle = "h", ...) {
x <- escape.textile(tocharac(x, include.rownames, include.colnames, rownames, colnames, format, digits, decimal.mark, na.print))
nrowx <- nrow(x)
ncolx <- ncol(x)
line_separator <- FALSE
vsep = matrix("|", nrow(x), ncol(x))
if (!is.null(style)) {
style <- expand(style, nrowx, ncolx)
vsep[style == "h"] <- "|_"
style[!(style %in% c("s", "e", "m"))] <- ""
style[style == "s"] <- "*"
style[style == "e"] <- "_"
style[style == "m"] <- "<code>"
} else {
style <- ""
style <- expand(style, nrowx, ncolx)
}
if (include.rownames & include.colnames) {
style[1, 1] <- ""
}
vsep <- cbind(vsep, rep("|", nrowx))
before_cell_content <- after_cell_content <- style
before_cell_content <- paste.matrix(" ", before_cell_content, sep = "", transpose.vector = TRUE)
after_cell_content <- paste.matrix(after_cell_content, " ", sep = "", transpose.vector = TRUE)
after_cell_content[after_cell_content == "<code> "] <- "</code> "
if (is.logical(header) & header)
header <- 1
if (header > 0) {
vsep[1:min(c(header, nrowx)), -ncol(vsep)] <- "|_"
}
if (is.logical(footer) & footer)
footer <- 1
if (footer > 0) {
vsep[nrow(x):(nrow(x)+1-min(c(footer, nrowx))), -ncol(vsep)] <- "|_"
}
if (!is.null(align)) {
align <- expand(align, nrow(x), ncolx)
} else {
align <- expand("", nrow(x), ncolx)
}
if (!is.null(valign)) {
valign <- expand(valign, nrow(x), ncolx)
} else {
valign <- expand("", nrow(x), ncolx)
}
after_vsep <- paste.matrix(vsep.textile(align, valign), ".", sep = "", transpose.vector = TRUE)
if (include.rownames & include.colnames)
after_vsep[1, 1] <- ""
results <- print.character.matrix(x, line_separator = line_separator, vsep = vsep, after_vsep = after_vsep, before_cell_content = before_cell_content, after_cell_content = after_cell_content, print = FALSE)
if (include.rownames & include.colnames)
results[1] <- sub("^ +", "", substr(results[1], 5, nchar(results[1])))
if (!is.null(lgroup)) {
if (!is.list(lgroup))
lgroup <- list(lgroup)
n.lgroup <- groups(lgroup, n.lgroup, nrowx-include.colnames)[[2]]
}
if (!is.null(rgroup)) {
if (!is.list(rgroup))
rgroup <- list(rgroup)
n.rgroup <- groups(rgroup, n.rgroup, nrowx-include.colnames)[[2]]
}
if (!is.null(tgroup)) {
if (!is.list(tgroup))
tgroup <- list(tgroup)
n.tgroup <- groups(tgroup, n.tgroup, ncolx-include.rownames)[[2]]
}
if (!is.null(bgroup)) {
if (!is.list(bgroup))
bgroup <- list(bgroup)
n.bgroup <- groups(bgroup, n.bgroup, ncolx-include.rownames)[[2]]
}
if (!is.null(lgroup)) {
lh <- ""
if (lstyle == "h") {
lstyle <- NULL
lh <- "_"
}
for (i in 1:length(lgroup)) {
pos.lgroup <- ngroups(lgroup[[i]], n.lgroup[[i]], n = nrowx)
results[pos.lgroup[, 2]+include.colnames] <- paste(paste(paste("|", lh, "/", pos.lgroup[, 3], vsep.textile(align = lalign, valign = lvalign, style = lstyle), sep = ""), pos.lgroup[, 1], sep = ". "), results[pos.lgroup[, 2]+include.colnames], sep = " ")
}
}
if (!is.null(rgroup)) {
rh <- ""
if (rstyle == "h") {
rstyle <- NULL
rh <- "_"
}
for (i in 1:length(rgroup)) {
pos.rgroup <- ngroups(rgroup[[i]], n.rgroup[[i]], n = nrowx)
results[pos.rgroup[, 2]+include.colnames] <- paste(results[pos.rgroup[, 2]+include.colnames], paste(paste(rh, "/", pos.rgroup[, 3], vsep.textile(align = ralign, valign = rvalign, style = rstyle), sep = ""), pos.rgroup[, 1], sep = ". "), " |", sep = "")
}
}
if (!is.null(tgroup)) {
th <- ""
if (tstyle == "h") {
tstyle <- NULL
th <- "_"
}
for (i in 1:length(tgroup)) {
pos.tgroup <- ngroups(tgroup[[i]], n.tgroup[[i]], n = ncolx)
results <- c(paste(paste(paste("|", th, "\\", pos.tgroup[, 3], vsep.textile(align = talign, valign = tvalign, style = tstyle), sep = ""), ". ", pos.tgroup[, 1], sep = "", collapse = " "), "|"), results)
}
}
if (!is.null(bgroup)) {
bh <- ""
if (bstyle == "h") {
bstyle <- NULL
bh <- "_"
}
for (i in 1:length(bgroup)) {
pos.bgroup <- ngroups(bgroup[[i]], n.bgroup[[i]], n = ncolx)
results <- c(results, paste(paste(paste("|", th, "\\", pos.tgroup[, 3], vsep.textile(align = talign, valign = tvalign, style = tstyle), sep = ""), ". ", pos.tgroup[, 1], sep = "", collapse = " "), "|"))
}
}
topleftrow <- 0 + include.colnames + length(tgroup)
topleftcol <- 0 + include.rownames + length(lgroup)
topleft <- ""
if (topleftrow > 0 & topleftcol > 0)
topleft <- paste("|/", topleftrow, "\\", topleftcol, ". ", sep = "")
bottomleftrow <- 0 + length(bgroup)
bottomleftcol <- 0 + include.rownames + length(lgroup)
bottomleft <- ""
if (bottomleftrow > 0 & bottomleftcol > 0)
bottomleft <- paste("|/", bottomleftrow, "\\", bottomleftcol, ". ", sep = "")
toprightrow <- 0 + include.colnames + length(tgroup)
toprightcol <- 0 + length(rgroup)
topright <- ""
if (toprightrow > 0 & toprightcol > 0)
topright <- paste("/", toprightrow, "\\", toprightcol, ". |", sep = "")
bottomrightrow <- 0 + length(bgroup)
bottomrightcol <- 0 + length(rgroup)
bottomright <- ""
if (bottomrightrow > 0 & bottomrightcol > 0)
bottomright <- paste("/", bottomrightrow, "\\", bottomrightcol, ". |", sep = "")
results[1] <- paste(topleft, results[1], sep = "")
results[1] <- paste(results[1], topright, sep = "")
results[length(results)] <- paste(bottomleft, results[length(results)], sep = "")
results[length(results)] <- paste(results[length(results)], bottomright, sep = "")
cat(header.textile(caption = caption, caption.level = caption.level, frame = frame, width = width))
cat(results, sep = "\n")
}
show.textile.list <- function(x, caption = NULL, caption.level = NULL, list.type = "bullet", ...) {
if (list.type == "bullet") mark <- rep("*", length(x))
if (list.type == "number") mark <- rep("
if (list.type == "none") mark <- rep("", length(x))
if (list.type == "label") {
if (is.null(names(x))) {
namesx <- paste("[[ ", 1:length(x), " ]]", sep = "")
} else {
namesx <- names(x)
}
mark <- paste("- ", namesx, " := ", sep = "")
}
charac.x <- vector("character", length(x))
for (i in 1:length(x)) {
if (is.null(x[[i]])) next
tmp <- x[[i]]
if (list.type == "label") tmp <- sub("^\t*", "", tmp)
tmp <- sub("(^.*)", paste(mark[i], "\\1", sep = ""), gsub('\t|(*COMMIT)(*FAIL)', mark[i], tmp, perl = TRUE))
charac.x[i] <- sub(paste('(^\\', mark[i], '+)(.*)', sep = ""), '\\1 \\2', tmp)
}
cat(header.asciidoc(caption = caption, caption.level = caption.level))
cat(charac.x, sep = "\n")
} |
sqlp_base <- function(blk=NULL, At=NULL, C=NULL, b=NULL, OPTIONS=NULL, X0=NULL, y0=NULL, Z0=NULL){
if((is.null(blk) | is.null(At) | is.null(C) | is.null(b))){
stop("Error: Improper input methods")
}
b <- as.matrix(b)
idxdenAl <- numeric(0)
idxdenAq <- numeric(0)
nnzschur_qblk <- numeric(0)
nnzschur <- numeric(0)
nzlistschur <- numeric(0)
schurfun <- numeric(0)
schurfun_par <- numeric(0)
diagR <- numeric(0)
diagRold <- numeric(0)
exist_analytic_term <- numeric(0)
existlowrank <- numeric(0)
matfct_options <- numeric(0)
matfct_options_old <- numeric(0)
nnzmat <- numeric(0)
nnzmatold <- numeric(0)
numpertdiashschur <- numeric(0)
printlevel <- numeric(0)
smallblkdim <- numeric(0)
solve_ok <- numeric(0)
spdensity <- numeric(0)
use_LU <- numeric(0)
isemptyAtb <- 0
if(is.null(At) & is.null(b)){
b <- 0
At <- ops(ops(blk, "identity"), "*", -1)
numblk <- nrow(blk)
blk[[numblk+1, 1]] <- "l"
blk[[numblk+1, 2]] <- 1
At[[numblk+1,1]] <- 1
C[[numblk+1,1]] <- 0
isemptyAtb <- 1
}
par <- list(vers = 0,
gam = 0,
predcorr = 1,
expon = 1,
gaptol = 1e-8,
inftol = 1e-8,
steptol = 1e-6,
maxit = 100,
printlevel = 3,
stoplevel = 1,
scale_data = 0,
spdensity = 0.4,
rmdepconstr = 0,
smallblkdim = 50,
parbarrier = c(),
schurfun = matrix(list(),nrow=nrow(blk),ncol=1),
schurfun_par = matrix(list(),nrow=nrow(blk),ncol=1),
blkdim = c(),
ublksize = c(),
depconstr = c(),
AAt = c(),
normAAt = c(),
numcolAt = c(),
permA = c(),
permZ = c(),
isspA = c(),
nzlist = c(),
nzlistAsum = c(),
isspAy = c(),
nzlistAy = c(),
iter = c(),
obj = c(),
relgap = c(),
pinfeas = c(),
dinfeas = c(),
rp = c(),
y = c(),
dy = c(),
normX = c(),
ZpATynorm = c())
parbarrier <- matrix(list(),nrow=nrow(blk),ncol=1)
for(p in 1:nrow(blk)){
pblk <- blk[[p,1]]
if(pblk == "s" | pblk == "q"){
parbarrier[[p,1]] <- matrix(0, nrow=1, ncol=length(blk[[p,2]]))
}else if(pblk == "l" | pblk == "u"){
parbarrier[[p,1]] <- matrix(0, nrow=1, ncol=sum(blk[[p,2]]))
}
}
parbarrier_0 <- parbarrier
if(!is.null(OPTIONS) | length(OPTIONS) > 0){
if(!is.null(OPTIONS$vers)) par$vers <- OPTIONS$vers
if(!is.null(OPTIONS$predcorr)) par$predcorr <- OPTIONS$predcorr
if(!is.null(OPTIONS$gam)) par$gam <- OPTIONS$gam
if(!is.null(OPTIONS$expon)) par$expon <- OPTIONS$expon
if(!is.null(OPTIONS$gaptol)) par$gaptol <- OPTIONS$gaptol
if(!is.null(OPTIONS$inftol)) par$inftol <- OPTIONS$inftol
if(!is.null(OPTIONS$steptol)) par$steptol <- OPTIONS$steptol
if(!is.null(OPTIONS$maxit)) par$maxit <- OPTIONS$maxit
if(!is.null(OPTIONS$printlevel)) par$printlevel <- OPTIONS$printlevel
if(!is.null(OPTIONS$stoplevel)) par$stoplevel <- OPTIONS$stoplevel
if(!is.null(OPTIONS$scale_data)) par$scale_data <- OPTIONS$scale_data
if(!is.null(OPTIONS$spdensity)) par$spedensity <- OPTIONS$spdensity
if(!is.null(OPTIONS$rmdepconstr)) par$rmdepconstr <- OPTIONS$rmdepconstr
if(!is.null(OPTIONS$smallblkdim)) par$smallblkdim <- OPTIONS$smallblkdim
if(!is.null(OPTIONS$parbarrier)){
parbarrier <- OPTIONS$parbarrier
if(is.null(parbarrier)) parbarrier <- parbarrier_0
if(!is.list(parbarrier)){
tmp <- parbarrier
parbarrier <- matrix(list(),1,1)
parbarrier[[1]] <- tmp
}
if(max(dim(as.matrix(parbarrier))) < nrow(blk)){
len <- max(dim(as.matrix(parbarrier)))
parbarrier_1 <- matrix(list(),nrow(blk),1)
for(i in 1:len){
parbarrier_1[[i]] <- parbarrier[[i]]
}
for(i in (len+1):nrow(blk)){
parbarrier_1[[i]] <- parbarrier_0[[i]]
}
parbarrier <- parbarrier_1
}
}
}
if(ncol(blk) > 2){
par$smallblkdim <- 0
}
out <- validate(blk,At,C,b,par,parbarrier)
blk <- out$blk
At <- out$At
C <- out$C
b <- out$b
blkdim <- out$dim
numblk <- out$nnblk
parbarrier <- out$parbarrier
out <- convertcmpsdp(blk, At, C, b)
blk <- out$bblk
At <- out$AAt
C <- out$CC
b <- out$bb
iscmp <- out$iscmp
if(is.null(X0) | is.null(y0) | is.null(Z0)){
out <- infeaspt(blk, At, C, b)
X0 <- out$X0
y0 <- out$y0
Z0 <- out$Z0
par$startpoint <- 1
}else{
par$startpoint <- 2
out <- validate_startpoint(blk, X0,Z0,par$spdensity,iscmp)
X0 <- out$X
Z0 <- out$Z
}
user_supplied_schurfun <- 0
for(p in 1:nrow(blk)){
if(!is.null(par$schurfun[[p]])){
user_supplied_schurfun <- 1
}
}
if(user_supplied_schurfun == 0){
out <- detect_ublk(blk,At,C,parbarrier,X0,Z0)
blk2 <- out$blk2
At2 <- out$At2
C2 <- out$C2
ublkinfo <- out$ublkinfo
parbarrier2 <- out$parbarrier2
X02 <- out$X2
Z02 <- out$Z2
}else{
blk2 <- blk
At2 <- At
C2 <- C
parbarrier2 <- parbarrier
X02 <- X0
Z02 <- Z0
ublkinfo <- matrix(list(), nrow(blk3), 1)
}
ublksize <- blkdim[4]
for(p in 1:nrow(ublkinfo)){
if(!is.null(ublkinfo[[p,1]])){
ublksize <- ublksize + max(dim(ublkinfo[[p,1]]))
}
}
if(user_supplied_schurfun == 0){
out <- detect_lblk(blk2,At2,C2,b,parbarrier2,X02,Z02)
blk3 <- as.matrix(out$blk)
At3 <- as.matrix(out$At)
C3 <- as.matrix(out$C)
diagblkinfo <- out$diagblkinfo
diagblkchange <- out$blockchange
parbarrier3 <- as.matrix(out$parbarrier)
X03 <- as.matrix(out$X)
Z03 <- as.matrix(out$Z)
}else{
blk3 <- blk2
At3 <- At2
C3 <- C2
parbarrier3 <- parbarrier2
X03 <- X02
Z03 <- Z02
diagblkchange <- 0
diagblkinfo <- matrix(list(), nrow(blk3), 1)
}
exist_analytic_term <- 0
for(p in 1:nrow(blk3)){
idx <- which(parbarrier3[[p,1]] > 0)
if(length(idx) > 0){
exist_analytic_term <- 1
}
}
if(par$vers == 0){
if(blkdim[1]){
par$vers <- 1
}else{
par$vers <- 2
}
}
par$blkdim <- blkdim
par$ublksize <- ublksize
out <- sqlp_main(blk3, At3, C3, b, par, parbarrier3, X03, y0, Z03)
obj <- out$obj
X3 <- out$X
y <- out$y
Z3 <- out$Z
info <- out$info
runhist <- out$runhist
pobj <- info$obj[1]
dobj <- info$obj[2]
if(any(diagblkchange == 1)){
X2 <- matrix(list(),nrow(blk),1)
Z2 <- matrix(list(),nrow(blk),1)
count <- 0
for(p in 1:nrow(blk)){
n <- sum(blk[[p,2]])
blkno <- diagblkinfo[[p,1]]
idxdiag <- diagblkinfo[[p,2]]
idxnondiag <- diagblkinfo[[p,3]]
if(length(idxdiag) > 0){
len <- length(idxdiag)
Xtmp <- rbind(cbind(idxdiag,idxdiag,X3[[nrow(X3)]][count+c(1:len)]))
Ztmp <- rbind(cbind(idxdiag,idxdiag,Z3[[nrow(Z3)]][count+c(1:len)]))
if(length(idxnondiag) > 0){
tmp <- which(X3[[blkno]] != 0, arr.ind=TRUE)
ii <- tmp[,1]
jj <- tmp[,2]
vv <- X3[[blkno]][ which(X3[[blkno]] != 0)]
Xtmp <- rbind(Xtmp,cbind(idxnondiag[ii],idxnondiag[jj],vv))
tmp <- which(Z3[[blkno]] != 0, arr.ind=TRUE)
ii <- tmp[,1]
jj <- tmp[,2]
vv <- Z3[[blkno]][ which(Z3[[blkno]] != 0)]
Ztmp <- rbind(Ztmp,cbind(idxnondiag[ii],idxnondiag[jj],vv))
}
X2[[p]] <- matrix(0,n,n)
for(i in 1:nrow(Xtmp)){
X2[[p]][Xtmp[i,1],Xtmp[i,2]] <- Xtmp[i,3]
}
Z2[[p]] <- matrix(0,n,n)
for(i in 1:nrow(Ztmp)){
Z2[[p]][Ztmp[i,1],Ztmp[i,2]] <- Ztmp[i,3]
}
count <- count + len
}else{
X2[[p]] <- X3[[blkno]]
Z2[[p]] <- Z3[[blkno]]
}
}
}else{
X2 <- X3
Z2 <- Z3
}
numblk <- nrow(blk)
numblknew <- numblk
X <- matrix(list(),numblk,1)
Z <- matrix(list(),numblk,1)
for(p in 1:numblk){
n <- blk[[p,2]]
if(is.null(ublkinfo[[p,1]])){
X[[p]] <- X2[[p]]
Z[[p]] <- Z2[[p]]
}else{
Xtmp <- matrix(0,n,1)
Ztmp <- matrix(0,n,1)
Xtmp[ublkinfo[[p,1]]] <- pmax(0,X2[[p]])
Xtmp[ublkinfo[[p,2]]] <- pmax(0,-X2[[p]])
Ztmp[ublkinfo[[p,1]]] <- pmax(0,Z2[[p]])
Ztmp[ublkinfo[[p,2]]] <- pmax(0,-Z2[[p]])
if(!is.null(ublkinfo[[p,3]])){
numblknew <- numblknew + 1
Xtmp[ublkinfo[[p,3]]] <- X2[[numblknew]]
Ztmp[ublkinfo[[p,3]]] <- Z2[[numblknew]]
}
X[[p]] <- Xtmp
Z[[p]] <- Ztmp
}
}
output <- list(X=X, y=y, Z=Z, pobj=pobj, dobj=dobj)
return(output)
} |
propTestMdd <-
function (n.or.n1, n2 = n.or.n1, p0.or.p2 = 0.5, alpha = 0.05,
power = 0.95, sample.type = "one.sample", alternative = "two.sided",
two.sided.direction = "greater", approx = TRUE, correct = sample.type ==
"two.sample", warn = TRUE, return.exact.list = TRUE,
tol = 1e-07, maxiter = 1000)
{
sample.type <- match.arg(sample.type, c("one.sample", "two.sample"))
alternative <- match.arg(alternative, c("two.sided", "less",
"greater"))
two.sided.direction <- match.arg(two.sided.direction, c("greater",
"less"))
if (!is.vector(n.or.n1, mode = "numeric") || !is.vector(p0.or.p2,
mode = "numeric") || !is.vector(alpha, mode = "numeric") ||
!is.vector(power, mode = "numeric"))
stop("'n.or.n1', 'p0.or.p2', 'alpha', and 'power' must be numeric vectors.")
if (!all(is.finite(n.or.n1)) || !all(is.finite(p0.or.p2)) ||
!all(is.finite(alpha)) || !all(is.finite(power)))
stop(paste("Missing (NA), Infinite (Inf, -Inf), and",
"Undefined (Nan) values are not allowed in", "'n.or.n1', 'p0.or.p2', 'alpha', or 'power'"))
if (any(n.or.n1 < 2))
stop("All values of 'n.or.n1' must be greater than or equal to 2")
if (!approx && !all(n.or.n1 == trunc(n.or.n1)))
stop("When approx=FALSE, all values of 'n.or.n1' must be integers")
if (any(p0.or.p2 <= 0) || any(p0.or.p2 >= 1))
stop("All values of 'p0.or.p2' must be greater than 0 and less than 1")
if (any(alpha <= 0) || any(alpha >= 1))
stop("All values of 'alpha' must be greater than 0 and less than 1")
if (any(power < alpha) || any(power >= 1))
stop(paste("All values of 'power' must be greater than or equal to",
"the corresponding elements of 'alpha', and less than 1"))
if (sample.type == "two.sample" && !missing(n2)) {
if (!is.vector(n2, mode = "numeric"))
stop("'n2' must be a numeric vector")
if (!all(is.finite(n2)))
stop(paste("Missing (NA), Infinite (Inf, -Inf), and",
"Undefined (Nan) values are not allowed in 'n2'"))
if (any(n2 < 2))
stop("All values of 'n2' must be greater than or equal to 2")
if (!approx)
stop(paste("Minimal detectable difference based on exact method",
"not available for two-sample test"))
}
arg.mat <- cbind.no.warn(n.or.n1 = as.vector(n.or.n1), n2 = as.vector(n2),
p0.or.p2 = as.vector(p0.or.p2), alpha = as.vector(alpha),
power = as.vector(power))
for (i in c("n.or.n1", "n2", "p0.or.p2", "alpha", "power")) assign(i,
arg.mat[, i])
N <- nrow(arg.mat)
p.or.p1 <- numeric(N)
index.0 <- power == alpha
p.or.p1[index.0] <- p0.or.p2[index.0]
extreme <- switch(alternative, less = .Machine$double.eps,
greater = 1 - .Machine$double.eps, two.sided = ifelse(two.sided.direction ==
"less", .Machine$double.eps, 1 - .Machine$double.eps))
extreme <- rep(extreme, N)
power.extreme <- propTestPower(n.or.n1 = n.or.n1, p.or.p1 = extreme,
n2 = n2, p0.or.p2 = p0.or.p2, alpha = alpha, sample.type = sample.type,
alternative = alternative, approx = approx, correct = correct,
warn = FALSE, return.exact.list = FALSE)
index.Inf <- power.extreme < power | is.na(power.extreme)
if (any(index.Inf)) {
p.or.p1[index.Inf] <- NA
string <- ifelse(sample.type == "one.sample", "'n', 'p0', 'alpha', and 'power'",
"'n1', 'n2', 'p2', 'alpha', and 'power'")
warning(paste("Elements with a missing value (NA) indicate",
"no attainable minimal detectable difference for the",
"given values of", string))
}
index.equal <- power.extreme == power
p.or.p1[index.equal] <- extreme[index.equal]
if (extreme[1] == .Machine$double.eps) {
lower <- extreme
upper <- p0.or.p2
f.lower <- power - power.extreme
f.upper <- power - alpha
}
else {
lower <- p0.or.p2
upper <- extreme
f.lower <- power - alpha
f.upper <- power - power.extreme
}
fcn.for.root <- function(p.or.p1, n.or.n1, n2, p0.or.p2,
alpha, power, sample.type, alternative, approx, correct) {
power - propTestPower(n.or.n1 = n.or.n1, p.or.p1 = p.or.p1,
n2 = n2, p0.or.p2 = p0.or.p2, alpha = alpha, sample.type = sample.type,
alternative = alternative, approx = approx, correct = correct,
warn = FALSE, return.exact.list = FALSE)
}
for (i in (1:N)[!index.0 & !index.Inf & !index.equal]) {
lower.i <- lower[i]
upper.i <- upper[i]
f.lower.i <- f.lower[i]
f.upper.i <- f.upper[i]
n.or.n1.i <- n.or.n1[i]
p0.or.p2.i <- p0.or.p2[i]
alpha.i <- alpha[i]
power.i <- power[i]
n2.i <- n2[i]
p.or.p1[i] <- uniroot(fcn.for.root, lower = lower[i],
upper = upper.i, tol = tol, maxiter = maxiter, f.lower = f.lower.i,
f.upper = f.upper.i, n.or.n1 = n.or.n1.i, n2 = n2.i,
p0.or.p2 = p0.or.p2.i, alpha = alpha.i, power = power.i,
sample.type = sample.type, alternative = alternative,
approx = approx, correct = correct)$root
}
ret.val <- p.or.p1 - p0.or.p2
names(ret.val) <- NULL
if (approx && warn) {
na.index <- is.na(p.or.p1)
if (!all(na.index)) {
if (sample.type == "one.sample" && any(index <- pmin(n.or.n1[!na.index] *
p.or.p1[!na.index], n.or.n1[!na.index] * (1 -
p.or.p1)[!na.index]) < 5))
warning(paste("The sample size 'n' is too small,",
"relative to the computed value of 'p', for the normal",
"approximation to work well for the following",
"element indices:\n\t", paste((1:N)[!na.index][index],
collapse = " "), "\n\t"))
if (sample.type == "two.sample" && any(index <- pmin(n.or.n1[!na.index] *
p.or.p1[!na.index], n.or.n1[!na.index] * (1 -
p.or.p1)[!na.index], n2[!na.index] * p0.or.p2[!na.index],
n2[!na.index] * (1 - p0.or.p2)[!na.index]) <
5))
warning(paste("The sample sizes 'n1' and 'n2' are",
"too small, relative to the computed value of",
"'p1' and the given value of 'p2', for the normal",
"approximation to work well for the following",
"element indices:\n\t", paste((1:N)[!na.index][index],
collapse = " "), "\n\t"))
}
}
if (!approx && return.exact.list) {
N <- length(p.or.p1)
switch(alternative, less = {
N.vars <- 3
list.names <- c("power", "alpha", "q.critical.lower")
}, greater = {
N.vars <- 3
list.names <- c("power", "alpha", "q.critical.upper")
}, two.sided = {
N.vars <- 4
list.names <- c("power", "alpha", "q.critical.lower",
"q.critical.upper")
})
dum.list <- lapply(rep(N, N.vars), function(i) {
x <- rep(NA, i)
mode(x) <- "numeric"
x
})
names(dum.list) <- list.names
na.index <- is.na(p.or.p1)
if (!all(na.index)) {
power.list <- propTestPower(n.or.n1 = n.or.n1[!na.index],
p.or.p1 = p.or.p1[!na.index], n2 = n2[!na.index],
p0.or.p2 = p0.or.p2[!na.index], alpha = alpha[!na.index],
sample.type = sample.type, alternative = alternative,
approx = FALSE, warn = FALSE, return.exact.list = TRUE)
dum.list <- lapply(1:N.vars, function(i, index, main.list,
sub.list) {
main.list[[i]][index] <- sub.list[[i]]
main.list[[i]]
}, index = !na.index, main.list = dum.list, sub.list = power.list)
names(dum.list) <- list.names
}
ret.val <- c(list(delta = ret.val), dum.list)
}
ret.val
} |
test_that("defensive programming", {
expect_error(capture_warnings(
quilt_form(
input_data = qdat,
question_type = "dropdown"
)
))
expect_error(capture_warnings(
quilt_form(
input_data = qdat,
question_type = "select"
)
))
expect_error(capture_warnings(
quilt_form(
input_data = qdat,
question_type = "multiselect"
)
))
expect_error(capture_warnings(
quilt_form(
input_data = qdat,
question_type = "singleanswer"
)
))
expect_error(capture_warnings(
quilt_form(
input_data = qdat,
question_type = "multianswer"
)
))
expect_error(capture_warnings(
quilt_form(
input_data = qdat,
question_type = "rankorder"
)
))
expect_error(capture_warnings(
quilt_form(
input_data = qdat,
question_type = "singleline"
)
))
expect_error(capture_warnings(
quilt_form(
input_data = qdat,
question_type = "form"
)
))
expect_error(capture_warnings(
quilt_form(
input_data = qdat,
question_type = "essay"
)
))
})
test_that("defensive programming", {
expect_error(capture_warnings(
quilt_form(
input_data = qdat,
filename = "qualtrics_survey.txt"
)
))
})
test_that("defensive programming", {
expect_error(capture_warnings(
quilt_form(
question_type = "multianswer",
filename = "qualtrics_survey.txt"
)
))
})
test_that("quilted form is of class character", {
input_data <- pbreak(qdat, 1)
quilted_form <- formpaste(input_data, "[[Question:MC:Dropdown]]")
expect_true(is.character(quilted_form))
})
test_that("quilted form is of length nrow page-breaked data", {
input_data <- pbreak(qdat, 3)
quilted_form <- formpaste(input_data, "[[Question:MC:Dropdown]]")
expect_true(length(quilted_form) == nrow(input_data))
})
test_that("ID appended when null", {
input_data = qdat[,-3]
input_data <- addformIDs(input_data)
IDs <- input_data$id
expect_true(length(IDs) == nrow(input_data))
expect_type(input_data$id, "character")
expect_equal(input_data$id[1], "[[ID:1]]")
})
test_that("page breaks returned correctly", {
input_data <- pbreak(qdat, 1)
expect_true(nrow(input_data) == nrow(qdat) + nrow(qdat))
input_data <- pbreak(qdat, 2)
expect_true(nrow(input_data) == nrow(qdat) + 1/2*nrow(qdat))
input_data <- pbreak(qdat, 3)
expect_true(nrow(input_data) == round(nrow(qdat) + 1/3*nrow(qdat)))
})
test_that("page break rows of correct length", {
page_break_every = 1
input_data <- pbreak(qdat, page_break_every)
expect_true(length(input_data$response_type[input_data$prompt=="[[PageBreak]]\n"]) == 1/page_break_every*nrow(qdat))
page_break_every = 2
input_data <- pbreak(qdat, page_break_every)
expect_true(length(input_data$response_type[input_data$prompt=="[[PageBreak]]\n"]) == 1/page_break_every*nrow(qdat))
page_break_every = 3
input_data <- pbreak(qdat, page_break_every)
expect_true(length(input_data$response_type[input_data$prompt=="[[PageBreak]]\n"]) == round(1/page_break_every*nrow(qdat)))
}) |
mediation <- function(pheno, predictor, region, pos, order, gbasis, covariate, base="bspline", family="gaussian")
{
predictor[is.na(predictor)] = 0
region[is.na(region)] = 0
covariate[is.na(covariate)] = 0
idx = is.na(pheno)
pheno = pheno[!idx]
region = region[!idx,]
covariate = covariate[!idx,]
dqr = qr(region)
index = dqr$pivot[1:dqr$rank]
region = region[, index]
pos = pos[index]
nsample = nrow(region)
nsnp = ncol(region)
if(max(pos) > 1) pos = (pos - min(pos)) / (max(pos) - min(pos))
betabasis = create.bspline.basis(norder = 1, nbasis = 1)
if (base == "bspline"){
regionbasis = create.bspline.basis(norder = order, nbasis = gbasis)
} else if (base == "fspline"){
regionbasis = create.fourier.basis(c(0,1), nbasis = gbasis)
}else { }
region = as.matrix(region)
B = eval.basis(pos, regionbasis)
to_mul = ginv(t(B) %*% B) %*% t(B)
U = region %*% t( to_mul )
J = inprod(regionbasis, betabasis)
UJ = matrix( U %*% J, ncol = ncol(J) )
region_transformed = as.vector(UJ)
covariate = as.matrix(covariate)
predictor = as.matrix(predictor)
interaction = as.vector(predictor)*region_transformed
if (family=="gaussian") {
coef2_all = summary(lm(region_transformed ~ covariate + predictor))$coefficients
alpha_cov = coef2_all[c(1:(dim(covariate)[2]+1)),1]
coef2_all_nocov = coef2_all[-c(1:(dim(covariate)[2]+1)), ]
alpha_predictor = coef2_all_nocov[1]
pval2 = coef2_all_nocov[4]
pval <- list()
test_part = cbind(predictor, region_transformed, interaction)
untest_part = covariate
fit = glm(pheno ~ untest_part + test_part, family="gaussian")
pval$TE = anova(fit, test = "F")[3,6]
test_part = cbind(predictor, interaction)
untest_part = cbind(covariate, region_transformed)
fit = glm(pheno ~ untest_part + test_part, family="gaussian")
pval$DE = anova(fit, test = "F")[3,6]
test_part = cbind(region_transformed, interaction)
untest_part = cbind(covariate, predictor)
fit = glm(pheno ~ untest_part + test_part, family="gaussian")
pval$IE = anova(fit, test = "F")[3,6]
}
if (family=="binomial") {
region_transformed_c = region_transformed[which(pheno==0)]
covariate_c = covariate[which(pheno==0),]
covariate_cdqr = qr(covariate_c)
covariate_cindex = covariate_cdqr$pivot[1:covariate_cdqr$rank]
covariate_c = covariate_c[, covariate_cindex]
diff = colnames(covariate)[!(colnames(covariate)%in%colnames(covariate_c))]
predictor_c = as.vector(predictor)[which(pheno==0)]
coef2_all = summary(lm(region_transformed_c ~ covariate_c + predictor_c))$coefficients
alpha_cov = coef2_all[c(1:(dim(covariate_c)[2]+1)),1]
coef2_all_nocov = coef2_all[-c(1:(dim(covariate_c)[2]+1)), ]
alpha_predictor = coef2_all_nocov[1]
pval2 = coef2_all_nocov[4]
pval <- list()
test_part = cbind(predictor, region_transformed, interaction)
untest_part = covariate
fit = glm(pheno ~ untest_part + test_part, family="binomial")
pval$TE = anova(fit, test = "Rao")[3,6]
test_part = cbind(predictor, interaction)
untest_part = cbind(covariate, region_transformed)
fit = glm(pheno ~ untest_part + test_part, family="binomial")
pval$DE = anova(fit, test = "Rao")[3,6]
test_part = cbind(region_transformed, interaction)
untest_part = cbind(covariate, predictor)
fit = glm(pheno ~ untest_part + test_part, family="binomial")
pval$IE = anova(fit, test = "Rao")[3,6]
}
return(list(pval=pval, pval_MX=pval2))
} |
`shade.col` <-
function(n, acol=c(1,0,0), bcol=c(1,1,1) )
{
if(missing(acol)) { acol=c(1,0,0) }
if(missing(bcol)) { bcol=c(1,1,1) }
if ((n <- as.integer(n[1])) > 0)
{
r1 = acol[1];
g1 = acol[2];
b1 = acol[3];
wr1 = bcol[1];
wg1 = bcol[2];
wb1 = bcol[3];
dr1 = wr1-r1
dg1 = wg1-g1
db1 = wb1-b1
hr1 = (wr1-r1)/n
hg1 = (wg1-g1)/n
hb1 = (wb1-b1)/n
nr1 = seq(from=r1, length.out=n, by=hr1)
nb1 = seq(from=b1, length.out=n, by=hb1)
ng1 = seq(from=g1, length.out=n, by=hg1)
COL = rgb(red=nr1, green=ng1, blue=nb1)
}
return(COL)
} |
print.roben=function(x, digits = max(3, getOption("digits") - 3),...){
cat("\nCall: ", deparse(x$call), "\n")
cat("\nCoefficients:\n")
print(x$coefficient, digits)
cat("Class:\n")
print(class(x))
}
print.GxESelection=function(x, digits = max(3, getOption("digits") - 3),...){
cat("\nMethod:\n")
print(x$method)
cat("\n")
print(x$summary)
}
print.roben.pred=function(x, digits = max(3, getOption("digits") - 3),...){
cat("\nPMSE:\n")
print(x$error, digits)
cat("\npredicted ", length(x$y.pred), " y (list component y.pred)", sep = "")
} |
polysFast <- function(x, M, w, ML=FALSE) {
M <- as.numeric(as.factor(M))
uM <- sort(unique(M))
mapTheta <- function(v) {
vv <- cumsum(c(v[1],exp(v[-1])))
c(NA,-Inf,vv,Inf)
}
theta0 <- sapply(uM[-length(uM)],function(z) qnorm(weighted.mean(M<=z, w)) )
if(ML) {
temp = w/sum(w)
temp2 = fixxFast(x, temp)
temp3 = sum(temp*dnorm(temp2,log=TRUE))
bob <- suppressWarnings(bobyqa(par=c(atanh(cor(x,M)),imapThetaFast2(theta0)),
fn=optFFast, x=temp2, w=temp, M=M, temp3 = temp3))
return( tanh(bob$par[1]))
} else {
temp = w/sum(w)
temp2 = fixxFast(x, temp)
temp3 = sum(temp*dnorm(temp2,log=TRUE))
values = mainF(x, M, w, theta0)
opt <- suppressWarnings(optimize(optFcFast, interval=unlist(values[1]),
x=temp2, w=temp, theta0=(imapThetaFast2(theta0)),
M=M, temp3= temp3))
return( tanh(opt$minimum) )
}
} |
library("testthat")
library("recommenderlab")
set.seed(1234)
context("dissimilarity")
db <- matrix(
as.numeric(sample(
c(NA, 0:5), 100, replace = TRUE,
prob = c(.7, rep(.3 / 6, 6))
)),
nrow = 10,
ncol = 10,
dimnames = list(
users = paste('u', 1:10, sep = ''),
items = paste('i', 1:10, sep = '')
)
)
x <- as(db, "realRatingMatrix")
s <- similarity(x)
expect_is(s, "dist")
expect_equal(attr(s, "Size"), nrow(x))
s <- similarity(x, x)
expect_is(s, "crossdist")
expect_equal(dim(s), c(nrow(x), nrow(x)))
s <- similarity(x, which = "items")
expect_is(s, "dist")
expect_equal(attr(s, "Size"), ncol(x))
s <- similarity(x, x, which = "items")
expect_is(s, "crossdist")
expect_equal(dim(s), c(ncol(x), ncol(x)))
s_cd <- similarity(x, x, min_matching = 2, min_predictive = 1)
s_d <- similarity(x, min_matching = 2, min_predictive = 1)
expect_equivalent(as.vector(s_cd[lower.tri(s_cd)]), as.vector(s_d))
similarity(
x,
x,
which = "items",
min_matching = 0,
min_predictive = 0
)
similarity(
x,
x,
which = "items",
min_matching = 2,
min_predictive = 0
)
similarity(
x,
x,
which = "items",
min_matching = 2,
min_predictive = 1
)
compn <- function(x, n = 3) round(as.vector(x), n)
x <- rbind(c(1, -1), c(-1, 1))
x
rating <- as(matrix(x, ncol = 2), "realRatingMatrix")
rating
ibcf <- Recommender(
rating,
method = 'IBCF',
parameter = list(
method = 'cosine',
k = 1
)
)
res <- -1
expect_equal(as(ibcf@model$sim, "matrix")[1, 2], res)
expect_equal(compn(dissimilarity(rating, method = "cosine", which = "items")), 1 - res)
expect_equal(compn(similarity(rating, method = "cosine", which = "items")), res)
res <- -1
expect_equal(compn(dissimilarity(rating, method = "cosine")), 1 - res)
expect_equal(compn(similarity(rating, method = "cosine")), res)
expect_equal(compn(dissimilarity(rating, method = "pearson")), 1)
expect_equal(compn(dissimilarity(rating, method = "pearson", which = "items")), 1)
expect_equal(compn(dissimilarity(rating, method = "karypis", which = "items")), 1)
expect_equal(compn(dissimilarity(rating, method = "conditional", which = "items")), 0)
x <- rbind(c(1, 0), c(0, 1), c(1, 1), c(1, 0))
x
rating <- as(matrix(x, ncol = 2), "binaryRatingMatrix")
rating
ibcf <- Recommender(
rating,
method = 'IBCF',
parameter = list(
method = 'cosine',
k = 1
)
)
res <- 0.408
expect_equal(compn(as(ibcf@model$sim, "matrix")[1, 2]), res)
expect_equal(compn(dissimilarity(rating, method = "cosine", which = "items")), 1 - res)
expect_equal(compn(similarity(rating, method = "cosine", which = "items")), res)
res <- c(1.000, 0.293, 0.000, 0.293, 1.000, 0.293)
expect_equal(compn(dissimilarity(rating, method = "cosine")), res)
expect_equal(compn(similarity(rating, method = "cosine")), 1 - res)
res <- c(1.0, 0.5, 0.0, 0.5, 1.0, 0.5)
expect_equal(compn(dissimilarity(rating, method = "jaccard")), res)
expect_equal(compn(dissimilarity(rating, method = "jaccard", which = "items")), 0.75)
expect_equal(compn(dissimilarity(rating, method = "karypis", which = "items")), 0.826)
expect_equal(compn(dissimilarity(rating, method = "conditional", which = "items")), 0.667) |
ls8Search<-function(AppRoot,verbose=FALSE,precise=FALSE,...){
warning("Obsolete function, use lsSearch.")
arg<-list(...)
if((!"dates"%in%names(arg))&
((!"startDate"%in%names(arg)|(!"endDate"%in%names(arg))))
)stop("startDate and endDate, or dates argument need to be defined!")
if("dates"%in%names(arg)){
stopifnot(class(arg$dates)=="Date")
startDate<-min(arg$dates)
endDate<-max(arg$dates)
}else{
startDate<-arg$startDate
endDate<-arg$endDate
}
stopifnot(class(startDate)=="Date")
stopifnot(class(endDate)=="Date")
if(endDate<as.Date("2011-03-13"))
stop("There is no Landsat-8 Images before 13-03-2013.")
if(startDate<as.Date("2011-03-13"))
warning("There is no Landsat-8 Images before 13-03-2013.")
AppRoot<-pathWinLx(AppRoot)
if(!ls8IsMetaData()){
message("MetaData not loaded! loading...")
ls8LoadMetadata(AppRoot=AppRoot,update=FALSE,...)
}
LS8MD<-getRGISToolsOpt("LS8METADATA")
LS8MD<-LS8MD[as.Date(LS8MD$acquisitionDate)>=startDate&
as.Date(LS8MD$acquisitionDate)<=endDate,]
if("pathrow"%in%names(arg)){
stopifnot(class(arg$pathrow)=="list")
LS8MD<-do.call(rbind,lapply(arg$pathrow,function(rp,LS8MD,verbose)return(genFilterDF(LS8MD,row=rp[2],path=rp[1],verbose=verbose)),
LS8MD,
verbose=verbose))
}else if("extent"%in%names(arg)){
if(precise){
stopifnot(class(extent(arg$extent))=="Extent")
ext<-extent(arg$extent)
tiles<-unlist(apply(LS8MD[grepl("Corner",names(LS8MD))],1,tileIn,ext))
LS8MD<-LS8MD[tiles,]
}else{
pathrow<-names(ls8pr)[unlist(lapply(ls8pr,tileInExt,ext2=extent(arg$extent)))]
pathrow<-as.data.frame(cbind(as.integer(substr(pathrow,1,3)),as.integer(substr(pathrow,4,6))))
pathrow = lapply(as.list(1:dim(pathrow)[1]), function(x) pathrow[x[1],])
LS8MD<-do.call(rbind,lapply(pathrow,function(rp,LS8MD,verbose){rp=unlist(rp);return(genFilterDF(LS8MD,row=rp[2],path=rp[1],verbose=verbose))},
LS8MD=LS8MD,
verbose=verbose))
}
}else if("lonlat"%in%names(arg)){
stopifnot(class(arg$lonlat)=="numeric")
stopifnot(length(arg$lonlat)==2)
dat_sim <- data.frame(lat = arg$lonlat[2],long = arg$lonlat[1])
dat_sf <- st_transform(st_as_sf(dat_sim, coords = c("long", "lat"), crs = 4326), 3035)
circle <- st_buffer(dat_sf, dist = 1)
circle <- st_transform(circle, 4326)
if(precise){
tiles<-unlist(apply(LS8MD[grepl("Corner",names(LS8MD))],1,tileIn,ext=extent(circle)))
LS8MD<-LS8MD[tiles,]
}else{
pathrow<-names(ls8pr)[unlist(lapply(ls8pr,tileInExt,ext2=extent(circle)))]
pathrow<-as.data.frame(cbind(as.integer(substr(pathrow,1,3)),as.integer(substr(pathrow,4,6))))
pathrow = lapply(as.list(1:dim(pathrow)[1]), function(x) unname(pathrow[x[1],]))
LS8MD<-do.call(rbind,lapply(pathrow,
function(pr,LS8MD,verbose){pr=unlist(pr);return(genFilterDF(LS8MD,row=pr[2],path=pr[1],verbose=verbose))},
LS8MD=LS8MD,
verbose=verbose))
}
}else if("region"%in%names(arg)){
arg$region<-transform_multiple_proj(arg$region, proj4=st_crs(4326))
if(precise){
tiles<-unlist(apply(LS8MD[grepl("Corner",names(LS8MD))],1,tileIn,ext=extent(arg$region)))
LS8MD<-LS8MD[tiles,]
}else{
pathrow<-names(ls8pr)[unlist(lapply(ls8pr,tileInExt,ext2=extent(arg$region)))]
pathrow<-as.data.frame(cbind(as.integer(substr(pathrow,1,3)),as.integer(substr(pathrow,4,6))))
pathrow = lapply(as.list(1:dim(pathrow)[1]), function(x) unname(pathrow[x[1],]))
LS8MD<-do.call(rbind,lapply(pathrow,
function(pr,LS8MD,verbose){pr=unlist(pr);return(genFilterDF(LS8MD,row=pr[2],path=pr[1],verbose=verbose))},
LS8MD=LS8MD,
verbose=verbose))
}
}else{
warning("Location not defined!")
}
if("cloudCover"%in%names(arg)){
LS8MD<-LS8MD[LS8MD$cloudCover>min(arg$cloudCover)&LS8MD$cloudCover<max(arg$cloudCover),]
}
arg<-arg[names(arg)[which(!names(arg)%in%c("pathrow","region","cloudCover"))]]
if(length(arg)>0){
arg$df<-LS8MD
LS8MD<-do.call(genFilterDF,arg)
}
LS8MD<-LS8MD[!duplicated(LS8MD[,c('sceneID')]),]
if("dates"%in%names(arg)){
LS8MD<-LS8MD[as.Date(LS8MD$acquisitionDate)%in%arg$dates,]
}
class(LS8MD)<-"ls8res"
return(LS8MD)
}
tileIn<-function(dv,ext){
lat<-unlist(dv[grepl("Latitude",names(dv))])
lon<-unlist(dv[grepl("Longitude",names(dv))])
sps<-extent(min(lon),max(lon),min(lat),max(lat))
return(!is.null(raster::intersect(sps,ext)))
}
tileInExt<-function(ext1,ext2){
return(!is.null(raster::intersect(ext1,ext2)))
} |
file.copy(
system.file("its-example.osm.pbf", package = "osmextract"),
file.path(tempdir(), "its-example.osm.pbf")
)
test_that("oe_get_network: simplest examples work", {
expect_error(oe_get_network("ITS Leeds", quiet = TRUE, download_directory = tempdir()), NA)
})
test_that("oe_get_network: options in ... work correctly", {
expect_warning(oe_get_network("ITS Leeds", layer = "points", quiet = TRUE, download_directory = tempdir()))
expect_message(oe_get_network("ITS Leeds", quiet = TRUE, download_directory = tempdir()), NA)
driving_network_with_area_tag = oe_get_network(
"ITS Leeds",
mode = "driving",
extra_tags = "area",
quiet = TRUE,
download_directory = tempdir()
)
expect_true("area" %in% colnames(driving_network_with_area_tag))
expect_error(oe_get_network(
place = "ITS Leeds",
quiet = TRUE,
vectortranslate_options = c("-where", "ABC"),
download_directory = tempdir()
))
walking_network_27700 = oe_get_network(
"ITS Leeds",
mode = "walking",
vectortranslate_options = c("-t_srs", "EPSG:27700"),
quiet = TRUE,
download_directory = tempdir()
)
expect_true(sf::st_crs(walking_network_27700) == sf::st_crs(27700))
})
file.remove(list.files(tempdir(), pattern = "its-example", full.names = TRUE)) |
genDichoMatrix<-function(items=100, model="4PL", aPrior=c("norm",1,0.2),bPrior=c("norm",0,1),cPrior=c("unif",0,0.25),dPrior=c("unif",0.75,1), seed=1){
testB<-switch(bPrior[1],norm=1,unif=2)
if (is.null(testB)) stop("Prior distribution for item difficulties must be either 'norm' or 'unif'",call.=FALSE)
testA<-switch(aPrior[1],norm=1,lnorm=2,unif=3)
if (is.null(testA)) stop("Prior distribution for item discriminations must be either 'norm', 'lnorm' or 'unif'",call.=FALSE)
testC<-switch(cPrior[1],beta=1,unif=2)
if (is.null(testC)) stop("Prior distribution for item lower asymptotes must be either 'beta' or 'unif'",call.=FALSE)
testD<-switch(dPrior[1],beta=1,unif=2)
if (is.null(testD)) stop("Prior distribution for item upper asymptotes must be either 'beta' or 'unif'",call.=FALSE)
set.seed(seed)
b<-switch(bPrior[1],norm=rnorm(items,as.numeric(bPrior[2]),as.numeric(bPrior[3])),unif=runif(items,as.numeric(bPrior[2]),as.numeric(bPrior[3])))
if (model!="1PL") a<-switch(aPrior[1],norm=rnorm(items,as.numeric(aPrior[2]),as.numeric(aPrior[3])),lnorm=rlnorm(items,as.numeric(aPrior[2]),as.numeric(aPrior[3])),unif=runif(items,as.numeric(aPrior[2]),as.numeric(aPrior[3])))
else a<-rep(1,items)
if (model=="3PL" | model=="4PL") c<-switch(cPrior[1],beta=rbeta(items,as.numeric(cPrior[2]),as.numeric(cPrior[3])),unif=runif(items,as.numeric(cPrior[2]),as.numeric(cPrior[3])))
else c<-rep(0,items)
if (model=="4PL") d<-switch(dPrior[1],beta=rbeta(items,as.numeric(dPrior[2]),as.numeric(dPrior[3])),unif=runif(items,as.numeric(dPrior[2]),as.numeric(dPrior[3])))
else d<-rep(1,items)
RES<-data.frame(a,b,c,d)
return(RES)} |
tabPanel('Line Chart - II', value = 'tab_gline2',
fluidPage(
fluidRow(
column(12, align = 'left',
h4('Line Plot - II')
)
),
hr(),
fluidRow(
column(12,
tabsetPanel(type = 'tabs',
tabPanel('Variables',
fluidRow(
column(2,
selectInput('gline2_select_x', 'Variable: ',
choices = "", selected = ""),
selectInput('gline2_group', 'Group: ',
choices = "", selected = ""),
textInput(inputId = "gline2_title", label = "Title: ",
value = "title"),
textInput(inputId = "gline2_xlabel", label = "X Axes Label: ",
value = "label")
),
column(2,
selectInput('gline2_y', 'Columns: ', choices = "", selected = ""),
textInput(inputId = "gline2_subtitle", label = "Subtitle: ",
value = "subtitle"),
textInput(inputId = "gline2_ylabel", label = "Y Axes Label: ",
value = "label")
),
column(8,
plotOutput('gline2_plot_1', height = '600px')
)
)
),
tabPanel('Aesthetics',
fluidRow(
column(2,
br(),
column(12,
actionButton('gline2_col_yes', 'Color', width = '120px')
),
column(12,
br(),
br(),
actionButton('gline2_ltype_yes', 'Line Type', width = '120px')
),
column(12,
br(),
br(),
actionButton('gline2_size_yes', 'Size', width = '120px')
)
),
column(2,
column(12,
uiOutput('gline2_col_ui')
),
column(12,
uiOutput('gline2_ltype_ui')
),
column(12,
uiOutput('gline2_size_ui')
)
),
column(8,
plotOutput('gline2_plot_2', height = '600px')
)
)
),
tabPanel('Axis Range',
fluidRow(
column(2,
uiOutput('ui_gline2yrange_min'),
selectInput('gline2_remx', 'Remove X Axis Label',
choices = c("TRUE" = TRUE, "FALSE" = FALSE),
selected = "FALSE")
),
column(2,
uiOutput('ui_gline2yrange_max'),
selectInput('gline2_remy', 'Remove Y Axis Label',
choices = c("TRUE" = TRUE, "FALSE" = FALSE),
selected = "FALSE")
),
column(8,
plotOutput('gline2_plot_3', height = '600px')
)
)
),
tabPanel('Annotations',
fluidRow(
column(2,
selectInput('gline2_text', 'Add Text',
choices = c("TRUE" = TRUE, "FALSE" = FALSE),
selected = "FALSE"),
numericInput(
inputId = "gline2_text_x_loc",
label = "X Intercept: ",
value = 1, step = 1),
numericInput(
inputId = "gline2_text_y_loc",
label = "Y Intercept: ",
value = 1, step = 1
)
),
column(2,
textInput(inputId = "gline2_plottext", label = "Text:",
value = ""),
textInput(
inputId = "gline2_textcolor",
label = "Text Color: ",
value = "black"
),
numericInput(
inputId = "gline2_textsize",
label = "Text Size: ",
value = 10, min = 1, step = 1
)
),
column(8,
plotOutput('gline2_plot_4', height = '600px')
)
)
),
tabPanel('Others',
column(4,
tabsetPanel(type = 'tabs',
tabPanel('Color',
fluidRow(
column(6,
textInput(inputId = "gline2_title_col", label = "Title:",
value = "black"),
textInput(inputId = "gline2_sub_col", label = "Subtitle:",
value = "black"),
textInput(inputId = "gline2_xlab_col", label = "X Axis Label:",
value = "black"),
textInput(inputId = "gline2_ylab_col", label = "Y Axis Label:",
value = "black")
)
)
),
tabPanel('Font Family',
fluidRow(
column(6,
textInput(inputId = "gline2_title_fam", label = "Title:",
value = "Times"),
textInput(inputId = "gline2_sub_fam", label = "Subtitle:",
value = "Times"),
textInput(inputId = "gline2_xlab_fam", label = "X Axis Label:",
value = "Times"),
textInput(inputId = "gline2_ylab_fam", label = "Y Axis Label:",
value = "Times")
)
)
),
tabPanel('Font Face',
fluidRow(
column(6,
selectInput('gline2_title_font', 'Title:',
choices = c(plain = 'plain', bold = 'bold', italic = 'italic', bold_italic = 'bold.italic'),
selected = "plain"),
selectInput('gline2_subtitle_font', 'Subtitle:',
choices = c(plain = 'plain', bold = 'bold', italic = 'italic', bold_italic = 'bold.italic'),
selected = "plain"),
selectInput('gline2_xlab_font', 'X Axis Label:',
choices = c(plain = 'plain', bold = 'bold', italic = 'italic', bold_italic = 'bold.italic'),
selected = "plain"),
selectInput('gline2_ylab_font', 'Y Axis Label:',
choices = c(plain = 'plain', bold = 'bold', italic = 'italic', bold_italic = 'bold.italic'),
selected = "plain")
)
)
),
tabPanel('Font Size',
fluidRow(
column(6,
numericInput(inputId = "gline2_title_size", label = "Title:",
min = 1, step = 0.1, value = 1),
numericInput(inputId = "gline2_sub_size", label = "Subtitle:",
min = 1, step = 0.1, value = 1),
numericInput(inputId = "gline2_xlab_size", label = "X Axis Label:",
min = 1, step = 0.1, value = 1),
numericInput(inputId = "gline2_ylab_size", label = "Y Axis Label:",
min = 1, step = 0.1, value = 1)
)
)
),
tabPanel('Horizontal',
fluidRow(
column(6,
numericInput(inputId = "gline2_title_hjust", label = "Title:",
min = 0, step = 0.1, value = 0.5, max = 1),
numericInput(inputId = "gline2_sub_hjust", label = "Subtitle:",
min = 0, step = 0.1, value = 0.5, max = 1),
numericInput(inputId = "gline2_xlab_hjust", label = "X Axis Label:",
min = 0, step = 0.1, value = 0.5, max = 1),
numericInput(inputId = "gline2_ylab_hjust", label = "Y Axis Label:",
min = 0, step = 0.1, value = 0.5, max = 1)
)
)
),
tabPanel('Vertical',
fluidRow(
column(6,
numericInput(inputId = "gline2_title_vjust", label = "Title:",
min = 0, step = 0.1, value = 0.5, max = 1),
numericInput(inputId = "gline2_sub_vjust", label = "Subtitle:",
min = 0, step = 0.1, value = 0.5, max = 1),
numericInput(inputId = "gline2_xlab_vjust", label = "X Axis Label:",
min = 0, step = 0.1, value = 0.5, max = 1),
numericInput(inputId = "gline2_ylab_vjust", label = "Y Axis Label:",
min = 0, step = 0.1, value = 0.5, max = 1)
)
)
)
)
),
column(8,
plotOutput('gline2_plot_5', height = '600px')
)
),
tabPanel('Theme',
column(2,
selectInput(inputId = 'gline2_theme', label = 'Theme',
choices = list("Classic Dark", "Default", "Light", "Minimal",
"Dark", "Classic", "Empty"), selected = "Default")
),
column(2),
column(8, align = 'center',
plotOutput('gline2_plot_6', height = '600px')
)
),
tabPanel('Plot',
column(12, align = 'center',
plotOutput('gline2_plot_7', height = '600px')
)
)
)
)
)
)
) |
pkgload::unload("devtools")
devtools::load_all("~/rrr/usethis")
attachNamespace("devtools")
library(testthat)
x <- create_from_github(
"r-lib/gh",
destdir = "~/tmp",
fork = TRUE,
open = FALSE,
protocol = "https"
)
local_project(x)
(r <- git_remotes())
use_git_remote("upstream", sub("r-lib", "r-pkgs", r$upstream), overwrite = TRUE)
(r <- git_remotes())
expect_equal(r$origin, "https://github.com/jennybc/gh.git")
expect_equal(r$upstream, "https://github.com/r-pkgs/gh.git")
check_pr_readiness()
err <- rlang::last_error()
expect_s3_class(err, class = "usethis_error_bad_github_config")
withr::deferred_run()
fs::dir_delete(x) |
BIFIE.univar.test <- function( BIFIE.method, wald_test=TRUE )
{
s1 <- Sys.time()
cl <- match.call()
res5 <- BIFIE.method
if (res5$group=="one"){ stop("This function can only be applied with a grouping variable.\n")}
if (BIFIE.method$RR < 2){ wald_test <- FALSE }
mean1M <- res5$output$mean1M
sd1M <- res5$output$sd1M
sumweightM <- res5$output$sumweightM
GG <- res5$GG
group_values <- ( res5$stat$groupval )[1:GG]
if( res5$group=="pseudogroup" ){
is_pseudogroup <- TRUE
} else {
is_pseudogroup <- FALSE
}
if ( is.null( group_values) ){
group_values <- 1:GG
}
mean1repM <- res5$output$mean1repM
sd1repM <- res5$output$sd1repM
sumweightrepM <- res5$output$sumweightrepM
fayfac <- res5$fayfac
VV <- res5$VV
vars <- res5$vars
RR <- res5$RR
if (RR==1){ RR <- 0 }
group <- res5$group
N <- res5$N
Nimp <- res5$Nimp
res <- bifie_test_univar( mean1M, sd1M, sumweightM, GG, group_values,
mean1repM, sd1repM, sumweightrepM, fayfac )
dfr <- data.frame( "var"=vars, "group"=group )
dfr$eta2 <- res$eta2L$pars^2
dfr$eta <- res$eta2L$pars
dfr$eta_SE <- res$eta2L$pars_se
dfr$fmi <- res$eta2L$pars_fmi
dfr$df <- rubin_calc_df( res$eta2L, Nimp )
dfr$VarMI <- res$eta2L$pars_varBetween
dfr$VarRep <- res$eta2L$pars_varWithin
if (BIFIE.method$NMI ){
res1 <- BIFIE_NMI_inference_parameters( parsM=res$eta2M, parsrepM=res$eta2repM,
fayfac=fayfac, RR=RR, Nimp=Nimp,
Nimp_NMI=BIFIE.method$Nimp_NMI, comp_cov=FALSE )
dfr$eta <- res1$pars
dfr$eta_SE <- res1$pars_se
dfr$df <- res1$df
dfr$eta_fmi <- res1$pars_fmi
dfr$eta_VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr$eta_VarRep <- res1$pars_varWithin
}
if (RR==0){
dfr$df <- dfr$SE <- dfr$fmi <- dfr$VarMI <- dfr$VarRep <- NULL
}
stat.eta2 <- dfr
group_values_matrix <- res$group_values_matrix
ZZ <- nrow(group_values_matrix)
dfr <- data.frame( "var"=rep(vars,each=ZZ) )
g2 <- group_values_matrix[ rep(1:ZZ, VV),, drop=FALSE]
g2 <- data.frame(g2)
colnames(g2) <- c("groupval1", "groupval2")
dfr$group <- group
dfr <- cbind( dfr, g2 )
r5 <- res5$stat
h1 <- NULL
h4 <- h3 <- h2 <- NULL
for (kk in 1:2){
group_values_matrix[,kk] <- match( group_values_matrix[,kk], group_values )
}
for (vv in 1:VV){
h1 <- c(h1, r5[ (vv-1)*GG + group_values_matrix[,1], "M" ] )
h2 <- c(h2, r5[ (vv-1)*GG + group_values_matrix[,2], "M" ] )
h3 <- c(h3, r5[ (vv-1)*GG + group_values_matrix[,1], "SD" ] )
h4 <- c(h4, r5[ (vv-1)*GG + group_values_matrix[,2], "SD" ] )
}
dfr$M1 <- h1
dfr$M2 <- h2
dfr$SD <- sqrt( ( h3^2 + h4^2 ) / 2 )
dfr$d <- res$dstatL$pars
dfr$d_SE <- res$dstatL$pars_se
dfr$d_t <- dfr$d / dfr$d_SE
dfr$d_df <- rubin_calc_df( res$dstatL, Nimp )
dfr$d_p <- stats::pt( - abs(dfr$d_t ), df=dfr$d_df)*2
dfr$d_fmi <- res$dstatL$pars_fmi
dfr$d_VarMI <- res$dstatL$pars_varBetween
dfr$d_VarRep <- res$dstatL$pars_varWithin
if ( BIFIE.method$NMI ){
res1 <- BIFIE_NMI_inference_parameters( parsM=res$dstatM, parsrepM=res$dstatrepM,
fayfac=fayfac, RR=RR, Nimp=BIFIE.method$Nimp,
Nimp_NMI=BIFIE.method$Nimp_NMI, comp_cov=FALSE )
dfr$d <- res1$pars
dfr$d_SE <- res1$pars_se
dfr$d_t <- round( dfr$d / dfr$d_SE, 2 )
dfr$d_df <- res1$df
dfr$d_p <- stats::pt( - abs( dfr$d_t ), df=dfr$d_df) * 2
dfr$d_fmi <- res1$pars_fmi
dfr$d_VarMI <- res1$pars_varBetween1 + res1$pars_varBetween2
dfr$d_VarRep <- res1$pars_varWithin
}
if ( ( ! res5$se ) & ( RR==0 ) ){
dfr$d_SE <- dfr$d_fmi <- dfr$d_VarMI <- dfr$d_VarRep <- NULL
}
if ( is_pseudogroup ){
stat <- res5$stat[ 1:GG, ]
stat$pseudogroup <- 1:GG
ind1 <- grep( "groupvar", colnames(stat) )
ind2 <- grep( "groupval", colnames(stat) )
groupvar_pseudo <- apply( stat[, ind1 ], 1, FUN=function(hh){ paste0( hh, collapse="
groupval_pseudo <- apply( stat[, ind2 ], 1, FUN=function(hh){ paste0( hh, collapse="
dfr$group <- groupvar_pseudo[1]
dfr$groupval1 <- groupval_pseudo[ dfr$groupval1 ]
dfr$groupval2 <- groupval_pseudo[ dfr$groupval2 ]
}
stat.dstat <- dfr
dfr <- NULL
for (vv in 1:VV){
Cdes <- matrix( 0, nrow=GG-1, ncol=GG*VV )
indvec <- 1:(GG-1)
for (zz in indvec ){
Cdes[ zz, c(zz + (vv-1)*GG,zz+1 + (vv-1)*GG ) ] <- c(1,-1)
}
rdes <- rep(0,GG-1)
if ( wald_test ){
wres5 <- BIFIE.waldtest( res5, Cdes=Cdes, rdes=rdes )
dfr <- rbind( dfr, wres5$stat.D )
}
}
if ( wald_test ){
dfr <- data.frame( "variable"=vars, "group"=group, dfr )
stat.F <- dfr
} else {
stat.F <- NA
}
parnames <- NULL
s2 <- Sys.time()
timediff <- c( s1, s2 )
res1 <- list( "stat.F"=stat.F, "stat.eta"=stat.eta2, "stat.dstat"=stat.dstat,
"timediff"=timediff,
"N"=N, "Nimp"=Nimp, "RR"=RR, "fayfac"=fayfac,
"NMI"=BIFIE.method$NMI, "Nimp_NMI"=BIFIE.method$Nimp_NMI,
"GG"=GG, "parnames"=parnames, "CALL"=cl, wald_test=wald_test )
class(res1) <- "BIFIE.univar.test"
return(res1)
}
summary.BIFIE.univar.test <- function( object, digits=4, ... )
{
BIFIE.summary(object)
if ( object$wald_test ){
cat("F Test (ANOVA) \n")
obji <- object$stat.F
print.object.summary( obji, digits=digits )
}
cat("\nEta Squared \n")
obji <- object$stat.eta
print.object.summary( obji, digits=digits )
cat("\nCohen's d Statistic \n")
obji <- object$stat.dstat
print.object.summary( obji, digits=digits )
} |
test_that("vmap", {
expect_equal(vmap(c(1, 1, 2, 2, 3), "a", "b", "c"), c("a", "a", "b", "b", "c"))
expect_equal(vmap(c("a", "b", "a", "c"), a = 1, b = 2, c = 3), c(1, 2, 1, 3))
expect_equal(vmap(c("a", "b", "a", "c", "d"), a = 1, b = 2, c = 3, 0), c(1, 2, 1, 3, 0))
expect_equal(vmap(c("a", "b", "a", "c"), a = 1, b = 2, c = 3, SIMPLIFY = FALSE), list(1, 2, 1, 3))
})
test_that("qrank", {
n <- 100
x <- rnorm(n)
expect_equal(qrank(x), rank(x) / length(x))
expect_equal(qrank(-x), rank(-x) / length(x))
x <- rnorm(n)
x[sample(1:n, 10, replace = FALSE)] <- NA
expect_equal(qrank(x), rank(x) / length(x))
expect_equal(qrank(-x), rank(-x) / length(x))
expect_equal(qrank(x, na.last = FALSE), rank(x, na.last = FALSE) / length(x))
expect_equal(qrank(-x, na.last = FALSE), rank(-x, na.last = FALSE) / length(x))
})
test_that("normalize", {
n <- 100
x <- rnorm(n)
expect_equal(normalize(x), (x - min(x)) / (max(x) - min(x)))
expect_equal(normalize(x, 0.5, 0.8), 0.5 + 0.3 * normalize(x))
expect_error(normalize(x, 0.5, 0.1))
x <- rnorm(n)
x <- x - min(x, na.rm = TRUE) + 1
x[sample(1:n, 10, replace = FALSE)] <- NA
expect_error(normalize(x), "missing value")
expect_equal(normalize(x, na.rm = TRUE),
(x - min(x, na.rm = TRUE)) / (max(x, na.rm = TRUE) - min(x, na.rm = TRUE)))
expect_equal(normalize(c(NA, NA, NA), na.rm = TRUE), c(0, 0, 0))
})
test_that("proportion", {
n <- 100
x <- rbinom(n, 100, 0.8)
expect_equal(proportion(x), x / max(abs(x)))
x <- rnorm(n)
expect_equal(proportion(x), x / max(abs(x)))
}) |
test_that("extract works like R", {
skip_if_not(check_tf_version())
source("helpers.R")
a <- randn(10)
b <- randn(10, 1)
c <- randn(10, 5)
d <- randn(2, 2, 2)
check_expr(a[1:6], "a")
check_expr(b[1:6], "b")
check_expr(c[1:6], "c")
check_expr(d[1:6], "d")
check_expr(b[1:6, ], "b")
check_expr(b[1:6, 1], "b")
check_expr(c[1:6, ], "c")
check_expr(c[1:6, 1], "c")
check_expr(d[1:2, , ], "d")
check_expr(d[1:2, 1, , drop = FALSE], "d")
check_expr(a[3:1], "a")
check_expr(d[2:1, , 1:2], "d")
check_expr(a[c(TRUE, FALSE, TRUE)], "a")
check_expr(d[2:1, , c(TRUE, FALSE), drop = FALSE], "d")
check_expr(d[, , 2:1], "d")
check_expr(d[, 2:1, ], "d")
check_expr(d[2:1, , ], "d")
check_expr(d[, , 1, drop = FALSE], "d")
check_expr(d[, 1, , drop = FALSE], "d")
check_expr(d[1, , , drop = FALSE], "d")
check_expr(a[], "a")
check_expr(b[], "b")
check_expr(c[], "c")
check_expr(d[], "d")
check_expr(a[-1], "a")
check_expr(b[-1:-3, ], "b")
check_expr(c[-1:-4, ], "c")
check_expr(d[-1:-2, -1, , drop = FALSE], "d")
})
test_that("replace works like R", {
skip_if_not(check_tf_version())
source("helpers.R")
x <- randn(10)
check_expr({
x[1:6] <- seq_len(6)
x
})
x <- randn(10, 1)
check_expr({
x[1:6] <- seq_len(6)
x
})
x <- randn(10, 5)
check_expr({
x[1:6] <- seq_len(6)
x
})
x <- randn(2, 2, 2)
check_expr({
x[1:6] <- seq_len(6)
x
})
x <- randn(10, 1)
check_expr({
x[1:6, 1] <- seq_len(6 * 1)
x
})
x <- randn(10, 5)
check_expr({
x[1:6, 1] <- seq_len(6 * 1)
x
})
x <- randn(2, 2, 2)
check_expr({
x[1:2, 1, ] <- seq_len(2 * 1 * 2)
x
})
x <- randn(10, 1)
check_expr({
x[1:6, ] <- seq_len(6)
x
})
x <- randn(10, 5)
check_expr({
x[1:6, ] <- seq_len(6 * 5)
x
})
x <- randn(10, 2, 2)
check_expr({
x[1:2, , ] <- seq_len(2 * 2 * 2)
x
})
x <- randn(10)
check_expr({
x[3:1] <- seq_len(3)
x
})
x <- randn(10, 2, 2)
check_expr({
x[2:1, , 1:2] <- seq_len(2 * 2 * 2)
x
})
x <- randn(10)
check_expr({
x[c(TRUE, FALSE, TRUE)] <- seq_len(7)
x
})
x <- randn(10, 2, 2)
check_expr({
x[2:1, , c(TRUE, FALSE)] <- seq_len(4)
x
})
x <- randn(10, 2, 2)
check_expr({
x[, , 1:2] <- seq_len(10 * 2 * 2)
x
})
x <- randn(10, 2, 2)
check_expr({
x[, 1:2, ] <- seq_len(10 * 2 * 2)
x
})
x <- randn(10, 2, 2)
check_expr({
x[1:2, , ] <- seq_len(2 * 2 * 2)
x
})
x <- randn(10, 2, 2)
check_expr({
x[1, , ] <- seq_len(1 * 2 * 2)
x
})
x <- randn(10, 2, 2)
check_expr({
x[, 1, ] <- seq_len(10 * 1 * 2)
x
})
x <- randn(10, 2, 2)
check_expr({
x[, , 1] <- seq_len(10 * 2 * 1)
x
})
x <- randn(10)
check_expr({
x[] <- seq_len(10)
x
})
x <- randn(10, 1)
check_expr({
x[] <- seq_len(10)
x
})
x <- randn(10, 5)
check_expr({
x[] <- seq_len(10 * 5)
x
})
x <- randn(2, 2, 2)
check_expr({
x[] <- seq_len(2 * 2 * 2)
x
})
x <- randn(10)
check_expr({
x[-1] <- seq_len(9)
x
})
x <- randn(10, 1)
check_expr({
x[-1:-3, ] <- seq_len(7 * 1)
x
})
x <- randn(10, 5)
check_expr({
x[-1:-4, ] <- seq_len(6 * 5)
x
})
x <- randn(2, 2, 2)
check_expr({
x[-1, -1, ] <- seq_len(1 * 1 * 2)
x
})
x <- randn(10)
check_expr({
x[1:3] <- 1
x
})
x <- randn(10, 1)
check_expr({
x[1:3, 1] <- 1
x
})
x <- randn(10, 5)
check_expr({
x[1:3, ] <- 1
x
})
x <- randn(2, 2, 2)
check_expr({
x[1:2, , ] <- 1
x
})
x <- randn(10)
check_expr({
x[1:4] <- seq_len(2)
x
})
x <- randn(10, 1)
check_expr({
x[1:4, 1] <- seq_len(2)
x
})
x <- randn(10, 5)
check_expr({
x[1:9, ] <- seq_len(3)
x
})
x <- randn(2, 2, 2)
check_expr({
x[1:2, , 1] <- seq_len(2)
x
})
x <- randn(10, 1)
ga_x <- as_data(x)
x[1:6, ] <- x[6:1, ]
ga_x[1:6, ] <- ga_x[6:1, ]
greta_out <- as.vector(grab(ga_x))
compare_op(x, greta_out)
})
test_that("rep works like R", {
skip_if_not(check_tf_version())
source("helpers.R")
a <- randn(10)
b <- randn(10, 1)
c <- randn(10, 5)
d <- randn(10, 2, 2)
rep_times <- function(x) {
rep(x, times = 3)
}
check_op(rep_times, a)
check_op(rep_times, b)
check_op(rep_times, c)
check_op(rep_times, d)
rep_length <- function(x) {
rep(x, length.out = 3)
}
check_op(rep_length, a)
check_op(rep_length, b)
check_op(rep_length, c)
check_op(rep_length, d)
rep_times_each <- function(x) {
rep(x, times = 3, each = 3)
}
check_op(rep_times_each, a)
check_op(rep_times_each, b)
check_op(rep_times_each, c)
check_op(rep_times_each, d)
rep_length_each <- function(x) {
rep(x, length = 30, each = 3)
}
check_op(rep_length_each, a)
check_op(rep_length_each, b)
check_op(rep_length_each, c)
check_op(rep_length_each, d)
})
test_that("rbind, cbind and c work like R", {
skip_if_not(check_tf_version())
source("helpers.R")
a <- randn(5, 1)
b <- randn(1, 5)
d <- randn(5, 5)
check_op(rbind, a, a)
check_op(rbind, b, d)
check_op(rbind, d, b)
check_op(cbind, b, b)
check_op(cbind, a, d)
check_op(cbind, d, d)
check_op(c, a, d)
check_op(c, b, a)
check_op(c, d, b)
check_op(c, a)
check_op(c, b)
check_op(c, d)
})
test_that("abind works like R", {
skip_if_not(check_tf_version())
source("helpers.R")
a <- randn(5, 1, 3)
b <- randn(1, 1, 3)
c <- randn(5, 1, 1)
check_op(abind, a, b, other_args = list(along = 1))
check_op(abind, a, c)
check_op(abind, a, a, other_args = list(along = 0))
check_op(abind, a, a, other_args = list(along = 4))
})
test_that("abind errors informatively", {
skip_if_not(check_tf_version())
source("helpers.R")
a <- ones(5, 1, 3)
b <- ones(1, 1, 3)
c <- ones(5, 1, 1)
expect_snapshot_error(
abind(a, b)
)
expect_snapshot_error(
abind(a, c, along = 5)
)
})
test_that("rbind and cbind can prepend R arrays to greta arrays", {
skip_if_not(check_tf_version())
source("helpers.R")
a <- randn(5, 1)
b <- ones(5, 1)
z <- rbind(a, b)
expect_s3_class(z, "greta_array")
expect_identical(dim(z), c(10L, 1L))
z <- rbind(b, a)
expect_s3_class(z, "greta_array")
expect_identical(dim(z), c(10L, 1L))
z <- cbind(a, b)
expect_s3_class(z, "greta_array")
expect_identical(dim(z), c(5L, 2L))
z <- cbind(b, a)
expect_s3_class(z, "greta_array")
expect_identical(dim(z), c(5L, 2L))
})
test_that("assign errors on variable greta arrays", {
skip_if_not(check_tf_version())
source("helpers.R")
z <- normal(0, 1, dim = 5)
expect_snapshot_error(
z[1] <- 3
)
})
test_that("rbind and cbind give informative error messages", {
skip_if_not(check_tf_version())
source("helpers.R")
a <- as_data(randn(5, 1))
b <- as_data(randn(1, 5))
expect_snapshot_error(
rbind(a, b)
)
expect_snapshot_error(
cbind(a, b)
)
})
test_that("replacement gives informative error messages", {
skip_if_not(check_tf_version())
source("helpers.R")
x <- ones(2, 2, 2)
expect_snapshot_error(
x[1:2, , 1] <- seq_len(3)
)
expect_snapshot_error(
x[1, 1, 3] <- 1
)
x <- ones(2)
expect_snapshot_error(
x[3] <- 1
)
})
test_that("extraction gives informative error messages", {
skip_if_not(check_tf_version())
source("helpers.R")
x <- ones(2, 2, 2)
expect_snapshot_error(
x[1, 1, 3]
)
x <- ones(2)
expect_snapshot_error(
x[3]
)
})
test_that("stochastic and operation greta arrays can be extracted", {
skip_if_not(check_tf_version())
source("helpers.R")
a <- normal(0, 1, dim = c(3, 4))
a_sub <- a[1:2, 2:3]
expect_identical(dim(a_sub), c(2L, 2L))
b <- a * 2
b_sub <- b[1:2, ]
expect_identical(dim(b_sub), c(2L, 4L))
})
test_that("extract, replace, combine work in models", {
skip_if_not(check_tf_version())
source("helpers.R")
a <- normal(0, 1, dim = c(3, 4))
a_sub <- a[1:2, 2:3]
m_a <- model(a_sub)
expect_ok(draws_a <- mcmc(m_a, warmup = 3, n_samples = 3, verbose = FALSE))
b <- ones(4, 3)
x <- normal(0, 1, dim = 4)
b[, 2] <- x
m_b <- model(b)
expect_ok(draws_b <- mcmc(m_b, warmup = 3, n_samples = 3, verbose = FALSE))
d <- c(
normal(0, 1, dim = 2),
lognormal(0, 1, dim = 3)
)
m_d <- model(d)
expect_ok(draws_d <- mcmc(m_d, warmup = 3, n_samples = 3, verbose = FALSE))
})
test_that("length and dim work", {
skip_if_not(check_tf_version())
source("helpers.R")
ga_data <- as_data(matrix(1:9, nrow = 3))
ga_stochastic <- normal(0, 1, dim = c(3, 3))
ga_operation <- ga_data * ga_stochastic
expect_identical(length(ga_data), 9L)
expect_identical(length(ga_stochastic), 9L)
expect_identical(length(ga_operation), 9L)
expect_identical(dim(ga_data), c(3L, 3L))
expect_identical(dim(ga_stochastic), c(3L, 3L))
expect_identical(dim(ga_operation), c(3L, 3L))
})
test_that("dim<- works", {
skip_if_not(check_tf_version())
source("helpers.R")
x <- randn(3, 4, 2)
new_dim <- c(2, 2, 6)
check_op(`dim<-`, x, other_args = list(value = new_dim))
new_dim <- c(12, 2)
check_op(`dim<-`, x, other_args = list(value = new_dim))
new_dim <- NULL
check_op(`dim<-`, x, other_args = list(value = new_dim))
})
test_that("greta_array() reshapes array-like greta arrays like array", {
skip_if_not(check_tf_version())
source("helpers.R")
x_ <- randu(3, 4, 2)
x <- as_data(x_)
new_dim <- c(12, 2)
y_ <- as_data(array(x_, dim = new_dim))
y <- greta_array(x, dim = new_dim)
compare_op(calculate(y)[[1]], calculate(y_)[[1]])
x <- abs(x)
y_ <- as_data(array(x_, dim = new_dim))
y <- greta_array(x, dim = new_dim)
compare_op(calculate(y)[[1]], calculate(y_)[[1]])
x <- variable(dim = dim(x))
y_ <- as_data(array(x_, dim = new_dim))
y <- greta_array(x, dim = new_dim)
compare_op(calculate(y, values = list(x = x_))[[1]], calculate(y_)[[1]])
})
test_that("greta_array() reshapes scalar greta arrays like array", {
skip_if_not(check_tf_version())
source("helpers.R")
x_ <- randu(1)
x <- as_data(x_)
new_dim <- c(12, 2)
y_ <- as_data(array(x_, dim = new_dim))
y <- greta_array(x, dim = new_dim)
compare_op(calculate(y)[[1]], calculate(y_)[[1]])
x <- abs(x)
y_ <- as_data(array(x_, dim = new_dim))
y <- greta_array(x, dim = new_dim)
compare_op(calculate(y)[[1]], calculate(y_)[[1]])
x <- variable(dim = dim(x))
y_ <- as_data(array(x_, dim = new_dim))
y <- greta_array(x, dim = new_dim)
compare_op(calculate(y, values = list(x = x_))[[1]], calculate(y_)[[1]])
})
test_that("dim<- errors as expected", {
skip_if_not(check_tf_version())
source("helpers.R")
x <- zeros(3, 4)
expect_snapshot_error(
dim(x) <- pi[0]
)
expect_snapshot_error(
dim(x) <- c(1, NA)
)
expect_snapshot_error(
dim(x) <- c(1, -1)
)
expect_snapshot_error(
dim(x) <- 13
)
})
test_that("dim<- works in a model", {
skip_if_not(check_tf_version())
source("helpers.R")
y <- rnorm(5)
x1 <- greta_array(1:12, c(3, 4))
dim(x1) <- NULL
x2 <- greta_array(1:12, c(3, 4))
dim(x2) <- 12
x3 <- greta_array(1:12, c(3, 4))
dim(x3) <- c(6, 2)
z <- x1[6, ] * x2[7, ] * x3[5, 2]
distribution(y) <- normal(z, lognormal(0, 1))
expect_ok(m <- model(z))
expect_ok(mcmc(m, warmup = 0, n_samples = 2))
})
test_that("c handles NULLs and lists", {
skip_if_not(check_tf_version())
source("helpers.R")
x <- normal(0, 1)
y <- as_data(3:1)
z <- c(x, NULL, y)
expect_s3_class(z, "greta_array")
expect_identical(dim(z), c(4L, 1L))
z <- c(x, NULL)
expect_s3_class(z, "greta_array")
expect_identical(dim(z), c(1L, 1L))
z <- c(x, 0, FALSE)
expect_s3_class(z, "greta_array")
expect_identical(dim(z), c(3L, 1L))
z <- c(x, mean)
expect_true(is.list(z))
expect_s3_class(z[[1]], "greta_array")
expect_identical(dim(z[[1]]), c(1L, 1L))
z <- c(x, NULL, mean)
expect_true(is.list(z))
expect_s3_class(z[[1]], "greta_array")
expect_identical(dim(z[[1]]), c(1L, 1L))
}) |
scaling.BW <-
function (S1, S2, method = 0, pa = 0) {
if (is.data.frame(S2))
S2 <- as.matrix(S2)
if (is.data.frame(S1))
S1 <- as.matrix(S1)
if (is.null(S1) | is.null(S2))
stop("supply both 'S1' and 'S2'")
if (!is.matrix(S1) | !is.matrix(S2))
stop("'S1' and 'S2' must be matrices or data frames")
if (!all.equal(dim(S1), dim(S2)))
stop("'S1' and 'S2' must be square matrices of the same dimensions")
p <- dim(S1)[1]
M <- minv(S2, method = 0, pa = 0) %*% S1
trM <- sum(diag(M))
k <- trM / p
return(k)
} |
mbscore <- function(x,lambda,subset=NULL,tol=1e-8,...){
beta <- scores <- scorevar.mod <- scorevar.sand <- p.model <- p.sand <- matrix(NA,ncol(x),ncol(x))
if(is.null(subset)) subset <- matrix(TRUE,ncol(x),ncol(x))
for(i in 1:ncol(x)){
mod <- lassoscore(x[,i],x[,-i],lambda=lambda,subset=which(subset[-i,i]),tol=tol,...)
scores[-i,i] <- mod$scores
p.model[-i,i] <- mod$p.model
p.sand[-i,i] <- mod$p.sand
scorevar.mod[-i,i] <- mod$scorevar.model
scorevar.sand[-i,i] <- mod$scorevar.sand
beta[-i,i] <- mod$fit$beta
}
re <- list("scores"=scores,
"p.model" = p.model,
"p.sand" = p.sand,
"scorevar.mod" = scorevar.mod,
"scorevar.sand" = scorevar.sand,
"beta" = beta)
re$lambda <- lambda
class(re) <- "mbscore"
return(re)
}
qqpval <- function(p, cone=TRUE, log=TRUE, add=FALSE,col=1,pch=1,...){
if(length(col)==1) col <- rep(col,length(p))
if(length(pch)==1) pch <- rep(pch,length(p))
stopifnot(length(col) == length(p) & length(pch) == length(p))
col <- col[0< p & p < 1]
pch <- pch[0 < p & p <1]
p <- p[ 0< p & p < 1]
oo <- order(p,decreasing=log)
p <- p[oo]
col <- col[oo]
pch <- pch[oo]
if(log) p <- -log10(p)
N <- length(p)
if(log){
Ep <- sort(-log10(ppoints(N)))
cone.lower <- -log10(qbeta(0.025, 1:N, N:1))
cone.upper <- -log10(qbeta(0.975, 1:N, N:1))
cone.x <- sort(-log10(ppoints(N)))
} else {
Ep <- sort(ppoints(N))
cone.lower <- sort(qbeta(0.025, 1:N, N:1))
cone.upper <- sort(qbeta(0.975, 1:N, N:1))
cone.x <- rev(sort(ppoints(N)))
}
if(add){
points(y=p, x=Ep,col=col,pch=pch,...)
} else{
if(log){
plot(y=p,x=Ep,type="n", xlab = "Expected p-value, -log10",
ylab = "Observed p-value, -log10",ylim=range(c(p,cone.upper,cone.lower)),...)
} else {
plot(y=p,x=Ep,type="n", xlab = "Expected p-value",
ylab = "Observed p-value",...)
}
abline(0,1)
polygon(y=c(rev(cone.lower),cone.upper),x=c(cone.x,rev(cone.x)),
col=1,lty=2,density=0)
points(y=p, x=Ep,col=col,pch=pch,...)
}
}
glassoscore <- function(x,lambda,subset=NULL,penalize.diagonal=FALSE,tol=1e-8){
if(!is.matrix(x)) stop("x must be a matrix")
if(lambda[1] < 0 | length(lambda) > 1) stop("lambda must be a non-negative scalor")
n <- nrow(x)
d <- ncol(x)
x <- scale(x)*sqrt((n-1)/n)
s <- var(x)*((n-1)/n)
if(is.null(subset)) subset <- matrix(TRUE,d,d)
stopifnot(all(dim(subset)==dim(s)) & is.logical(subset))
mod0 <- glasso(s,lambda,thr=tol,penalize.diagonal=penalize.diagonal)
scores <- matrix(0,d,d)
scorevars.sand <- scorevars.model <- matrix(0,d,d)
lambdamat <- matrix(lambda,d,d)
diag(lambdamat) <- 0
wh <- which(mod0$wi !=0)
adj <- cbind(floor((wh-0.1)/d)+1,(wh-1)%%d+1)
wh <- wh[adj[,1] <= adj[,2]]
adj <- adj[adj[,1] <= adj[,2],]
U0 <- with(mod0,{
w[adj[,1],adj[,1]]*w[adj[,2],adj[,2]] + w[adj[,2],adj[,1]]*w[adj[,1],adj[,2]]
})
Ui0 <- solve(U0)
V0 <- with(mod0, var(x[,adj[,1]]*x[,adj[,2]]))*((n-1)/n)
sand0 <- V0%*%Ui0%*%V0
for(i in 1:(d-1)){
for(j in (i+1):d){
if(subset[i,j] | subset[j,i]){
if(mod0$wi[i,j] ==0){
mod <- mod0
} else {
mod <- glasso(s,rho=lambda,zero=c(i,j),thr=tol,start="warm",w.init=mod0$w,
wi.init=mod0$wi,penalize.diagonal=penalize.diagonal)
}
scores[i,j] <- with(mod,sqrt(n)*(w[i,j]-s[i,j]))
wh <- c((i-1)*d+j,which(mod$wi !=0))
adj <- cbind(floor((wh-0.1)/d)+1,(wh-1)%%d+1)
wh <- wh[adj[,1] <= adj[,2]]
adj <- adj[adj[,1] <= adj[,2],]
if(mod0$wi[i,j] ==0){
Ua <- with(mod,{
w[adj[1,1],adj[,1]]*w[adj[1,2],adj[,2]] + w[adj[1,2],adj[,1]]*w[adj[1,1],adj[,2]]
})
V <- with(mod, var(x[,adj[,1]]*x[,adj[,2]]))*((n-1)/n)
scorevars.sand[i,j] <- (V[1,1] + t(Ua[-1])%*%sand0%*%Ua[-1] - 2*t(Ua[-1] )%*%(Ui0)%*%V[-1,1])
scorevars.model[i,j] <- Ua[1] - t(Ua[-1])%*%Ui0%*%Ua[-1]
} else {
U <- with(mod,{
w[adj[,1],adj[,1]]*w[adj[,2],adj[,2]] + w[adj[,2],adj[,1]]*w[adj[,1],adj[,2]]
})
V <- with(mod, var(x[,adj[,1]]*x[,adj[,2]]))*((n-1)/n)
Ui <- solve(U[-1,-1])
scorevars.sand[i,j] <- V[1,1] + t(U[-1,1])%*%Ui%*%(V[-1,-1]%*%Ui%*%U[-1,1] - 2*V[-1,1])
scorevars.model[i,j] <- U[1,1] - t(U[-1,1])%*%Ui%*%U[-1,1]
}
}
}
}
scores <- as.matrix(forceSymmetric(scores))
scorevars.sand <- as.matrix(forceSymmetric(scorevars.sand))
scorevars.model <- as.matrix(forceSymmetric(scorevars.model))
mod0$p.sand <- pchisq(scores^2/scorevars.sand,1,lower.tail=FALSE)
mod0$p.model <- pchisq(scores^2/scorevars.model,1,lower.tail=FALSE)
mod0$scores <- scores
mod0$scorevar.sand <- scorevars.sand
mod0$scorevar.model <- scorevars.model
mod0$lambda <- lambda
class(mod0) <- "glassoscore"
return(mod0)
}
print.glassoscore <- function(x,...){
cat("An object of class `glassoscore' \n")
cat("lambda = ", x$lambda[1])
}
print.mbscore <- function(x,...){
cat("An object of class `mbscore' \n")
cat("lambda = ", x$lambda[1])
}
plot.glassoscore <- function(x,cone=TRUE, log=TRUE, add=FALSE,...){
qqpval(x$p.sand[upper.tri(x$p.sand)],cone,log,add, main = "QQ-plot of p-values",...)
qqpval(x$p.model[upper.tri(x$p.sand)],add=TRUE,col=2,...)
legend("topleft",legend=c("sandwich","model-based"),col=c(1,2),pch=1)
}
plot.mbscore <- function(x,cone=TRUE, log=TRUE, add=FALSE,...){
qqpval(x$p.sand[upper.tri(x$p.sand)],cone,log,add, main = "QQ-plot of p-values",...)
qqpval(x$p.model[upper.tri(x$p.sand)],add=TRUE,col=2,...)
legend("topleft",legend=c("sandwich","model-based"),col=c(1,2),pch=1)
}
lassoscore <- function(y,X, lambda=0, family=c("gaussian","binomial","poisson"), tol = .Machine$double.eps, maxit=1000,
resvar = NULL, verbose=FALSE, subset = NULL){
family = match.arg(family)
family.obj <- get(family,mode="function",envir=parent.frame())()
if(!(family %in% c("gaussian","binomial","poisson"))) stop("family not supported!")
X <- scale(X)*sqrt(nrow(X)/(nrow(X)-1))
if(family=="gaussian") y <- scale(y,scale=FALSE)
out0 <- glmnet(y=y,x=X, family=family, lambda=lambda, thresh = tol, maxit=maxit,standardize=FALSE)
out0$r <- as.vector(family.obj$linkinv(as.vector(out0$a0 + X%*%out0$beta))-y)
out0$v <- family.obj$var(family.obj$linkinv(as.vector(out0$a0 + X%*%out0$beta)))
if(family =="gaussian" & !is.numeric(resvar)){
resvar <- sum(out0$r^2)/(length(y)-sum(out0$beta !=0))
} else if(family !="gaussian"){
resvar <- 1
}
out0$n <- nrow(X)
out0$beta <- as.vector(out0$beta)
wh <- as.vector(out0$beta != 0)
if(is.null(subset)){
subset <- 1:ncol(X)
}
if(verbose){
cat("\nProgress:\n")
pb <- txtProgressBar(min = 0, max = length(subset), style = 3)
pb.i <- 0
}
scores <- scorevar.sand.cons <- scorevar.model.cons <- scorevar.sand <- scorevar.model <- numeric(ncol(X))
scores[-subset] <- NA
for(i in subset){
if(out0$beta[i] != 0){
out <- glmnet(y=y,x=X[,-i], family=family, lambda=lambda, thresh = tol, maxit=maxit,standardize=FALSE)
out$r <- as.vector(family.obj$linkinv(out$a0 +as.vector(X[,-i]%*%out$beta))-y)
out$v <- family.obj$var(family.obj$linkinv(out$a0 +as.vector(X[,-i]%*%out$beta)))
out$n <- nrow(X)
out$beta <- as.vector(out$beta)
Xs <- X[,-i,drop=FALSE][,as.vector(out$beta !=0),drop=FALSE]
} else {
out <- out0
Xs <- X[,as.vector(out$beta !=0),drop=FALSE]
}
xx <- X[,i,drop=FALSE]
scores[i] <- sum(out$r*X[,i])/sqrt(out$n)
scorevar.model.cons[i] <- with(out, resvar*(crossprod(xx*sqrt(v))/n))
scorevar.sand.cons[i] <- with(out, var(xx*r)*(n-1)/n)
if(ncol(Xs) == 0){
scorevar.sand[i] <- scorevar.sand.cons[i]
scorevar.model[i] <- scorevar.model.cons[i]
} else if(nrow(Xs) > ncol(Xs) & ncol(Xs) >0){
Ui <- with(out, solve(crossprod(Xs*sqrt(v))/n))
V <- with(out, var(r*Xs)*(n-1))
Va <- with(out,cov(r*Xs,r*xx)*(n-1))
Ua <- with(out, crossprod(Xs,v*xx)/n)
va <- with(out, var(xx*r)*(n-1))
scorevar.sand[i] <- (va + t(Ua)%*%(Ui)%*%(V%*%Ui%*%Ua - 2*Va))/with(out,n-sum(beta !=0))
scorevar.model[i] <- with(out, resvar*(crossprod(xx*sqrt(v))/n - t(Ua)%*%Ui%*%Ua) )
}
if(verbose){
pb.i <- pb.i+1
setTxtProgressBar(pb, pb.i)
}
}
re <- list(
"fit"=out0,
"scores" = scores,
"scorevar.model.cons" = scorevar.model.cons,
"scorevar.sand.cons" = scorevar.model.cons,
"scorevar.model" = scorevar.model,
"scorevar.sand" = scorevar.sand,
"p.model.cons" = pchisq(scores^2/scorevar.model.cons,df=1,lower.tail=FALSE),
"p.sand.cons" = pchisq(scores^2/scorevar.sand.cons,df=1,lower.tail=FALSE),
"p.model" = pchisq(scores^2/scorevar.model,df=1,lower.tail=FALSE),
"p.sand" = pchisq(scores^2/scorevar.sand,df=1,lower.tail=FALSE),
"lambda" = lambda)
class(re) <- "lassoscore"
if(verbose) close(pb)
return(re)
}
print.lassoscore <- function(x,...){
cat("An object of class `lassoscore'\nbased on n =",x$fit$n, " observations on d =",x$fit$dim[1], " features, using lambda = ",x$lambda,fill=TRUE)
}
summary.lassoscore <- function(object,...){
cat("An object of class `lassoscore'\nbased on n =",object$fit$n, " observations on d =",object$fit$dim[1], " features, with",sum(object$fit$beta !=0),"non-zero coefficients in regression of `y' on `X'",fill=TRUE)
cat("\nModel-based p-values:\n")
print(summary(object$p.model))
cat("\nSandwich p-values:\n")
print(summary(object$p.sand))
}
plot.lassoscore <- function(x, type=c("all","model","sand","model.cons","sand.cons"),cone=TRUE, log=TRUE, add=FALSE,...){
type <- match.arg(type,choices = c("all","model","sand","model.cons","sand.cons"))
switch(type,
sand = qqpval(x$p.sand,cone,log,add, main = "QQ-plot of p-values",...),
model = qqpval(x$p.model,cone,log,add,main = "QQ-plot of p-values",...),
sand.cons = qqpval(x$p.sand.cons,cone,log,add,main = "QQ-plot of p-values",...),
model.cons = qqpval(x$p.model.cons,cone,log,add,main = "QQ-plot of p-values",...),
all = {
qqpval(x$p.model,cone,log,main = "QQ-plot of p-values",pch=16,col="
qqpval(x$p.sand,cone,log,add=TRUE,col="
qqpval(x$p.model.cons,cone,log,add=TRUE,col="
qqpval(x$p.sand.cons,cone,log,add=TRUE,col="
legend("topleft",col=c("
)
} |
library(checkargs)
context("isNonZeroNumberOrNanOrInfVectorOrNull")
test_that("isNonZeroNumberOrNanOrInfVectorOrNull works for all arguments", {
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNonZeroNumberOrNanOrInfVectorOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNonZeroNumberOrNanOrInfVectorOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
}) |
library(msme)
library(MASS)
data(medpar)
denom <- rep(1:5, each=299, times=1)*100
oset <- rep(1:5, each=299, times=1)*100
loset <- log(oset)
glm.poi <- glm(los ~ hmo + white,
family = "poisson",
data = medpar)
ml.poi <- ml_glm(los ~ hmo + white,
family = "poisson",
link = "log",
data = medpar)
ml.poi
glm.poi
summary(ml.poi)
summary(glm.poi)
glm.rpoi <- glm(los ~ hmo + white + offset(loset),
family = poisson,
data = medpar)
ml.rpoi <- ml_glm(los ~ hmo + white,
family = "poisson", link = "log",
offset = loset,
data = medpar)
ml.rpoi
glm.rpoi
summary(ml.rpoi)
summary(glm.rpoi)
glm.ipoi <- glm(los ~ hmo + white,
family = poisson(link=identity),
data = medpar)
ml.ipoi <- ml_glm(los ~ hmo + white,
family = "poisson", link = "identity",
data = medpar)
glm.ipoi
ml.ipoi
summary(glm.ipoi)
summary(ml.ipoi)
glm.logit <- glm(died ~ hmo + white,
family = "binomial",
data = medpar)
ml.logit <- ml_glm(died ~ hmo + white,
data = medpar,
family = "bernoulli",
link = "logit1")
ml.logit
glm.logit
summary(ml.logit)
summary(glm.logit)
ml.probit <- ml_glm(died ~ hmo + white,
family = "bernoulli",
link = "probit1",
data = medpar)
glm.probit <- glm(died ~ hmo + white,
family = binomial(link=probit),
data = medpar)
ml.probit
glm.probit
summary(ml.probit)
summary(glm.probit)
ml.cloglog <- ml_glm(died ~ hmo + white,
family = "bernoulli",
link = "cloglog1",
data = medpar,
verbose = 1)
glm.cloglog <- glm(died ~ hmo + white,
family = binomial(link=cloglog),
data = medpar)
ml.cloglog
glm.cloglog
summary(ml.cloglog)
summary(glm.cloglog) |
print.quantileDA<-function(x,...)
{
out=x
message("")
message("Results of the quantile classifier")
message("")
cat(paste("Minimum misclassification rates attained at theta = ",out$theta.choice,sep=""),"\n")
cat(paste("Miclassification rate in the training set: ", round(out$me.train,2),sep=""),"\n")
cat(paste("Miclassification rate in the test set: ",round(out$me.test,2),sep=""),"\n")
} |
plot.hydra <- function(x,labels=NULL,node.col=1,pch=NULL,graph.adj=NULL,crop.disc=TRUE,shrink.disc=FALSE, disc.col = "grey90", rotation = 0, mark.center=0, mark.angles=0, mildify = 3,cex=1.0,...) {
hydra <- x
if(shrink.disc) c.radius <- max(hydra$r) else c.radius <- 1.0
c.radius <- c.radius + 0.03*cex
rotation.rad <- rotation/180 * pi
x.nodes <- hydra$r*cos(hydra$theta + rotation.rad)
y.nodes <- hydra$r*sin(hydra$theta + rotation.rad)
if(crop.disc) plot(x.nodes,y.nodes,type="n",asp=1, xlab="",ylab="",axes=FALSE,...)
else plot(x.nodes,y.nodes,type="n",asp=1, xlab="",ylab="",axes=FALSE,xlim=c(-1,1)*c.radius,ylim=c(-1,1)*c.radius,...)
symbols(0,0,circles=c.radius,fg="white",bg=disc.col,inches=FALSE, add=TRUE)
if(mark.center != 0.0) {
lines(mark.center*c.radius*c(-1,1),c(0,0),...)
lines(c(0,0),mark.center*c.radius*c(-1,1),...)
}
if(!is.null(graph.adj)) {
edgelist <- which(graph.adj != 0,arr.ind=TRUE)
t <- seq(from=0,to=1,length=100)
for(i in 1:nrow(edgelist)) {
r <- hydra$r[edgelist[i,]] / mildify
dir <- hydra$directional[edgelist[i,],]
X <- poincare.to.hyper(r,dir)
x0 <- apply(X,1,function(x) {1 + sum(x^2)})
l.prod <- x0[1]*x0[2] - sum(X[1,] * X[2,])
dist <- acosh(max(1,l.prod))
aux <- (X[2,] - X[1,] * l.prod) / sqrt(l.prod^2 - 1)
geodesic <- hyper.to.poincare(outer(cosh(t*dist),X[1,]) + outer(sinh(t*dist),aux))
lines(geodesic$r* cos(geodesic$theta + rotation.rad) * mildify ,geodesic$r* sin(geodesic$theta + rotation.rad) * mildify,lty="dotted",col="black",...)
}
}
symbols(x.nodes,y.nodes,circles=rep(0.03*cex,length(hydra$r)),fg=disc.col,bg=disc.col,inches=FALSE, add=TRUE)
if(!is.null(labels)) text(x.nodes,y.nodes,labels,col=node.col,cex=cex,...)
if(is.null(labels) && is.null(pch)) pch <- 21
if(!is.null(pch)) points(x.nodes,y.nodes,col=node.col,pch=pch,cex=cex,...)
if(mark.angles != 0) segments((1-mark.angles)*c.radius*cos(hydra$theta + rotation.rad),(1-mark.angles)*c.radius*sin(hydra$theta + rotation.rad),(1+mark.angles)*c.radius*cos(hydra$theta + rotation.rad),(1+mark.angles)*c.radius*sin(hydra$theta + rotation.rad),col=node.col,...)
} |
.tabulateGeomorphRecords <- function(x) {
vars <- c('series', 'n')
if(
any(
isFALSE(x$hillpos) |
isFALSE(x$geomcomp) |
isFALSE(x$terrace) |
isFALSE(x$flats) |
isFALSE(x$shape_across) |
isFALSE(x$shape_down)
)
) {
return(NULL)
}
m1 <- merge(x$hillpos[, vars], x$geomcomp[, vars], by = 'series', all.x = TRUE, all.y = TRUE, sort = FALSE)
names(m1)[2:3] <- c('hillpos.records', 'geomcomp.records')
m2 <- merge(m1, x$terrace[, vars], by = 'series', all.x = TRUE, all.y = TRUE, sort = FALSE)
names(m2)[4] <- 'terrace.records'
m3 <- merge(m2, x$flats[, vars], by = 'series', all.x = TRUE, all.y = TRUE, sort = FALSE)
names(m3)[5] <- 'flats.records'
m4 <- lapply(m3, function(i) {
ifelse(is.na(i), 0, i)
})
m5 <- as.data.frame(m4, stringsAsFactors = FALSE)
return(m5)
}
fetchOSD <- function(soils, colorState='moist', extended=FALSE) {
if( !requireNamespace('jsonlite', quietly=TRUE))
stop('please install the `jsonlite` package', call.=FALSE)
if(extended) {
url <- 'https://casoilresource.lawr.ucdavis.edu/api/soil-series.php?q=all&s='
} else {
url <- 'https://casoilresource.lawr.ucdavis.edu/api/soil-series.php?q=site_hz&s='
}
final.url <- paste(url, URLencode(paste(soils, collapse=',')), sep='')
if(nchar(final.url) > 2048) {
stop('URL too long, consider splitting input vector of soil series with `makeChunks()` and iterating over chunks', call. = FALSE)
}
res <- try(jsonlite::fromJSON(final.url))
if(class(res) == 'try-error'){
message('error')
return(NULL)
}
s <- res$site
h <- res$hz
if( (is.logical(s) & length(s) == 1) | (is.logical(h) & length(h) == 1)) {
message('query returned no data')
return(NULL)
}
if(colorState == 'moist') {
h$soil_color <- with(h, munsell2rgb(matrix_wet_color_hue, matrix_wet_color_value, matrix_wet_color_chroma))
h <- with(h, data.frame(
id = series,
top, bottom,
hzname,
soil_color,
hue = matrix_wet_color_hue,
value = matrix_wet_color_value,
chroma = matrix_wet_color_chroma,
dry_hue = matrix_dry_color_hue,
dry_value = matrix_dry_color_value,
dry_chroma = matrix_dry_color_chroma,
texture_class = texture_class,
cf_class = cf_class,
pH = ph,
pH_class = ph_class,
distinctness = distinctness,
topography = topography,
dry_color_estimated = as.logical(dry_color_estimated),
moist_color_estimated = as.logical(moist_color_estimated),
narrative = narrative,
stringsAsFactors = FALSE
)
)
}
if(colorState == 'dry') {
h$soil_color <- with(h, munsell2rgb(matrix_dry_color_hue, matrix_dry_color_value, matrix_dry_color_chroma))
h <- with(h, data.frame(
id = series,
top, bottom,
hzname,
soil_color,
hue = matrix_dry_color_hue,
value = matrix_dry_color_value,
chroma = matrix_dry_color_chroma,
moist_hue = matrix_wet_color_hue,
moist_value = matrix_wet_color_value,
moist_chroma = matrix_wet_color_chroma,
texture_class = texture_class,
cf_class = cf_class,
pH = ph,
pH_class = ph_class,
distinctness = distinctness,
topography = topography,
dry_color_estimated = as.logical(dry_color_estimated),
moist_color_estimated = as.logical(moist_color_estimated),
narrative = narrative,
stringsAsFactors = FALSE
)
)
}
depths(h) <- id ~ top + bottom
textures <- SoilTextureLevels(which = 'names')
pH_classes <- c('ultra acid', 'extremely acid', 'very strongly acid', 'strongly acid', 'moderately acid', 'slightly acid', 'neutral', 'slightly alkaline', 'mildly alkaline', 'moderately alkaline', 'strongly alkaline', 'very strongly alkaline')
h$texture_class <- factor(h$texture_class, levels=textures, ordered = TRUE)
h$pH_class <- factor(h$pH_class, levels=pH_classes, ordered = TRUE)
s$id <- s$seriesname
s$seriesname <- NULL
site(h) <- s
metadata(h)$origin <- 'OSD via Soilweb / fetchOSD'
hzdesgnname(h) <- "hzname"
hztexclname(h) <- "texture_class"
if(extended) {
pIDs <- profile_id(h)
missing.series <- unique(
as.vector(
unlist(
lapply(res, function(i) {
if(inherits(i, 'data.frame')) {
setdiff(unique(i[['series']]), pIDs)
}
})
)
)
)
if(length(missing.series) > 0) {
msg <- sprintf("%s missing from SPC, see ?fetchOSD for suggestions", paste(missing.series, collapse = ','))
warning(msg, call. = FALSE)
}
if(inherits(res$climate, 'data.frame')) {
annual.data <- res$climate[grep('ppt|pet', res$climate$climate_var, invert = TRUE), ]
monthly.data <- res$climate[grep('ppt|pet', res$climate$climate_var), ]
monthly.data$month <- factor(as.numeric(gsub('ppt|pet', '', monthly.data$climate_var)))
monthly.data$variable <- gsub('[0-9]', '', monthly.data$climate_var)
monthly.data$variable <- factor(monthly.data$variable, levels = c('pet', 'ppt'), labels=c('Potential ET (mm)', 'Precipitation (mm)'))
} else {
annual.data <- FALSE
monthly.data <- FALSE
}
if(inherits(res$pmkind, 'data.frame')) {
names(res$pmkind) <- c('series', 'pmkind', 'n', 'total', 'P')
}
if(inherits(res$pmorigin, 'data.frame')) {
names(res$pmorigin) <- c('series', 'pmorigin', 'n', 'total', 'P')
}
if(inherits(res$competing, 'data.frame')) {
names(res$competing) <- c('series', 'competing', 'family')
}
data.list <- list(
SPC=h,
competing=res$competing,
geog_assoc_soils=res$geog_assoc_soils,
geomcomp=res$geomcomp,
hillpos=res$hillpos,
mtnpos=res$mtnpos,
terrace=res$terrace,
flats=res$flats,
shape_across=res$shape_across,
shape_down=res$shape_down,
pmkind=res$pmkind,
pmorigin=res$pmorigin,
mlra=res$mlra,
climate.annual=annual.data,
climate.monthly=monthly.data,
NCCPI = res$nccpi,
soilweb.metadata=res$metadata
)
return(data.list)
} else {
return(h)
}
} |
vt.default <- function(x
, ...
)
t(x)
vt.ff <- function(x
, ...
){
if (symmetric(x))
return(x)
d <- dim(x)
if (is.null(d) )
stop("not an array")
if (length(d)!=2)
warning("not a matrix")
vw <- vw(x)
if (is.null(vw)){
do <- dimorder(x)
dn <- dimnames(x)
dim(x) <- rev(d)
dimorder(x) <- rev(do)
dimnames(x) <- rev(dn)
}else{
vw(x) <- NULL
d <- dim(x)
do <- dimorder(x)
dn <- dimnames(x)
dim(x) <- d[2:1]
dimorder(x) <- rev(do)
dimnames(x) <- rev(dn)
vw(x) <- vw[,ncol(vw):1,drop=FALSE]
}
x
}
t.ff <- function(x){
if (symmetric(x))
return(x)
clone(vt(x), dimorder=rev(dimorder(x)))
} |
redis_connect <- function(config) {
if (config$scheme == "redis") {
ptr <- redis_connect_tcp(config$host, config$port, config$timeout)
} else {
ptr <- redis_connect_unix(config$path, config$timeout)
}
if (!is.null(config$password)) {
redis_command(ptr, c("AUTH", config$password))
}
if (!is.null(config$db)) {
redis_command(ptr, c("SELECT", config$db))
}
ptr
}
redis_connect_tcp <- function(host, port, timeout = NULL) {
.Call(Credux_redis_connect, host, as.integer(port), as.integer(timeout))
}
redis_connect_unix <- function(path, timeout = NULL) {
.Call(Credux_redis_connect_unix, path, as.integer(timeout))
}
redis_command <- function(ptr, command) {
.Call(Credux_redis_command, ptr, command)
}
redis_pipeline <- function(ptr, list) {
.Call(Credux_redis_pipeline, ptr, drop_null(list))
}
redis_subscribe <- function(ptr, channel, pattern, callback, envir) {
assert_character(channel)
if (length(channel) == 0L) {
stop("At least one channel must be given")
}
assert_scalar_logical(pattern)
assert_is(callback, "function")
assert_is(envir, "environment")
on.exit(.Call(Credux_redis_unsubscribe, ptr, channel, pattern))
.Call(Credux_redis_subscribe, ptr, channel, pattern, callback, envir)
invisible()
}
drop_null <- function(x) {
x[!vapply(x, is.null, logical(1))]
} |
LRFN.plot <-
function(M, Left.fun = NULL, Right.fun = NULL, ...)
{
if ( messages(M) != 1 ) { return( messages(M) ) }
m = M[1]
m_l = M[2]
m_r = M[3]
x <- NULL
if ( M[4] == 0 ) { y = function(x) Left.fun((m-x)/m_l) * (x<=m) + Right.fun((x-m)/m_r) * (m<x) }
else if ( M[4] == 1 ) { y = function(x) Right.fun((m-x)/m_l) * (x<=m) + Left.fun((x-m)/m_r) * (m<x) }
else if ( M[4] == 0.5 ) { y = function(x) Left.fun((m-x)/m_l) * (x<=m) + Left.fun((x-m)/m_r) * (m<x) }
else { return( noquote( paste0("The fourth element of each LR fuzzy number must be 0 or 0.5 or 1!" ) ) ) }
return(curve(y(x) * (0<=y(x) & y(x)<=1), ...) )
} |
adj.cssls <- function(CtC, CtA, Pset=NULL){
K = matrix(0, nrow(CtA), ncol(CtA));
if ( is.null(Pset) || length(Pset)==0 || all(Pset) ){
K = ginv(CtC) %*% CtA;
}else{
lVar = nrow(Pset); pRHS = ncol(Pset);
codedPset = as.numeric(2.^(seq(lVar-1,0,-1)) %*% Pset);
sortedPset = sort(codedPset)
sortedEset = order(codedPset)
breaks = diff(sortedPset);
breakIdx = c(0, which(breaks > 0 ), pRHS);
for( k in seq(1,length(breakIdx)-1) ){
cols2solve = sortedEset[ seq(breakIdx[k]+1, breakIdx[k+1])];
vars = Pset[,sortedEset[breakIdx[k]+1]];
K[vars,cols2solve] = ginv(CtC[vars,vars]) %*% CtA[vars,cols2solve];
}
}
K
} |
wr <- function(formula, data=NULL, expand=TRUE){
if(is.null(data))data <- parent.frame()
else if(!is.data.frame(data)&&!is.environment(data))
data <- if(expand||inherits(data,"tccov"))as.data.frame(data)
else as.data.frame(data$ccov)
mt <- terms(formula)
mf <- model.frame(mt,data=data,na.action=NULL)
list(response=model.response(mf,"numeric"), design=model.matrix(mt,mf))}
capply <- function(x, index, fcn=sum){
ans <- NULL
for(i in split(x,index))ans <- c(ans,fcn(i))
ans}
mexp <- function(x, t=1, type="spectral decomposition", n=20, k=3){
if(!is.matrix(x))stop("x must be a matrix")
if(dim(x)[1]!=dim(x)[2])stop("x must be a square matrix")
type <- match.arg(type,c("spectral decomposition","series approximation"))
if(type=="spectral decomposition"){
z <- eigen(t*x,symmetric=FALSE)
p <- z$vectors%*%diag(exp(z$values))%*%solve(z$vectors)}
else {
xx <- x*t/2^k
p <- diag(dim(x)[2])
q <- p
for(r in 1:n){
q <- xx%*%q/r
p <- p+q}
for(i in 1:k) p <- p%*%p}
p}
"%^%" <- function(x, p){
if(!is.matrix(x))stop("x must be a matrix")
if(dim(x)[1]!=dim(x)[2])stop("x must be a square matrix")
z <- eigen(x,symmetric=FALSE)
z$vectors%*%diag(z$values^p)%*%solve(z$vectors)}
contr.mean <- function(n, contrasts=TRUE){
if(length(n) <= 1){
if(is.numeric(n)&&length(n)==1&&n>1)levels <- 1:n
else stop("Not enough degrees of freedom to define contrasts")}
else levels <- n
lenglev <- length(levels)
if(contrasts){
cont <- array(0,c(lenglev,lenglev-1),
list(levels,levels[1:(lenglev-1)]))
cont[col(cont)==row(cont)] <- 1
cont[lenglev,] <- -1}
else {
cont <- array(0,c(lenglev,lenglev),list(levels,levels))
cont[col(cont) == row(cont)] <- 1}
cont} |
get_sig_rec_similarity <- function(Signature, nmf_matrix) {
stopifnot(inherits(Signature, "Signature"), is.matrix(nmf_matrix))
flag_rss <- TRUE
has_cn <- any(grepl("^CN[^C]", colnames(nmf_matrix)) | startsWith(colnames(nmf_matrix), "copynumber"))
raw_catalog <- t(nmf_matrix)
if (has_cn) {
if (!is.null(Signature$Raw$W)) {
rec_catalog <- Signature$Raw$W %*% Signature$Raw$H
} else {
warning("Cannot calculate reconstructed profile without raw W and H for CN 'W'/'M' method.")
return(invisible(NULL))
}
} else {
rec_catalog <- Signature$Signature.norm %*% Signature$Exposure
}
cross_samps <- intersect(colnames(raw_catalog), colnames(rec_catalog))
cross_comps <- intersect(rownames(raw_catalog), rownames(rec_catalog))
if (length(cross_samps) != ncol(rec_catalog)) {
message("Filter out some samples because of no raw catalog available.")
}
raw_catalog <- raw_catalog[cross_comps, cross_samps, drop = FALSE]
rec_catalog <- rec_catalog[cross_comps, cross_samps, drop = FALSE]
sim <- purrr::map2_dbl(
as.data.frame(raw_catalog),
as.data.frame(rec_catalog),
cosineVector
)
if (flag_rss) {
get_rss <- function(x, y) {
sum((x - y)^2)
}
get_unexplained_variance <- function(x, y) {
get_rss(x, y) / sum(x^2)
}
rss <- purrr::map2_dbl(
as.data.frame(raw_catalog),
as.data.frame(rec_catalog),
get_rss
)
unexplained_variance <- purrr::map2_dbl(
as.data.frame(raw_catalog),
as.data.frame(rec_catalog),
get_unexplained_variance
)
} else {
rss <- NULL
unexplained_variance <- NULL
}
data.table::data.table(
sample = cross_samps,
similarity = sim,
rss = rss,
unexplained_variance = unexplained_variance
)
} |
library(tidyquant)
context("Testing tq_mutate()")
AAPL <- tq_get("AAPL", get = "stock.prices", from = "2010-01-01", to = "2015-01-01")
test1 <- AAPL %>%
tq_mutate(close, MACD) %>%
tq_mutate(high:close, BBands) %>%
tq_mutate(open:close, OpCl)
test1.1 <- AAPL %>%
tq_mutate(close, rollapply, width = 7, FUN = mean) %>%
tq_mutate(open, SMA, n = 3) %>%
tq_mutate(close, rollapply, width = 9, FUN = mean) %>%
tq_mutate(open, SMA, n = 5) %>%
tq_mutate(high:close, BBands, n = 20) %>%
tq_mutate(high:close, BBands, n = 50)
test1.1_names <- c("symbol", "date", "open", "high", "low", "close", "volume", "adjusted",
"rollapply", "SMA", "rollapply..1", "SMA..1", "dn", "mavg",
"up", "pctB", "dn..1", "mavg..1", "up..1", "pctB..1")
grouped_df <- tibble(symbol = c("FB", "AMZN")) %>%
tq_get(
get = "stock.prices",
from = "2015-01-01",
to = "2016-01-01"
) %>%
group_by(symbol)
test1.2a <- mutate(grouped_df, V1 = runSD(adjusted))
test1.2b <- tq_mutate(grouped_df, adjusted, runSD, col_rename = "V1")
test2 <- AAPL %>%
tq_mutate_xy(x = close, mutate_fun = MACD) %>%
tq_mutate_xy(x = open, y = close, mutate_fun = Delt, k = 1:4)
time_index <- seq(from = as.POSIXct("2012-05-15 07:00"),
to = as.POSIXct("2012-05-17 18:00"),
by = "hour")
set.seed(1)
value <- rnorm(n = length(time_index))
hourly_data <- xts(value, order.by = time_index)
test3 <- hourly_data %>%
timetk::tk_tbl(preserve_index = T, silent = T) %>%
tq_mutate_xy(x = value, mutate_fun = MACD)
test4 <- tibble(time_index, value) %>%
tq_mutate_xy(x = value, mutate_fun = MACD)
test5 <- c("AAPL", "FB") %>%
tq_get(from = "2016-01-01",
to = "2017-01-01") %>%
group_by(symbol)
my_lm_fun <- function(data) {
coef(lm(close ~ open, data = as.data.frame(data)))
}
test5 <- test5 %>%
tq_mutate(mutate_fun = rollapply,
width = 90,
FUN = my_lm_fun,
by.column = FALSE,
col_rename = c("coef.0", "coef.1"))
test_that("Test 1 returns tibble with correct rows and columns.", {
expect_is(test1, "tbl")
expect_equal(nrow(test1), 1258)
expect_equal(ncol(test1), 15)
})
test_that("Test 1.1 returns correct column names", {
expect_equal(colnames(test1.1), test1.1_names)
})
test_that("Test 1.2 grouped data frames are same with mutate and tq_mutate", {
expect_equal(test1.2a, test1.2b)
})
test_that("Test 2 returns tibble with correct rows and columns.", {
expect_is(test2, "tbl")
expect_equal(nrow(test2), 1258)
expect_equal(ncol(test2), 14)
})
test_that("Test 3 returns tibble with correct rows and columns.", {
expect_is(test3, "tbl")
expect_equal(nrow(test3), 60)
expect_equal(ncol(test3), 4)
})
test_that("Test 5 returns tibble with correct rows and columns.", {
expect_is(test5, "tbl")
expect_equal(nrow(test5), 504)
expect_equal(ncol(test5), 10)
})
test_that("Test error on incompatible structures.", {
expect_error(
AAPL %>%
tq_mutate(select = NULL, mutate_fun = to.period, period = "months"),
"Could not join. Incompatible structures."
)
expect_error(
AAPL %>%
tq_mutate_xy(x = close, mutate_fun = to.period, period = "months"),
"Could not join. Incompatible structures."
)
})
test_that("Test error on invalid data inputs.", {
a <- seq(1:100)
expect_error(
seq(1:100) %>%
tq_mutate(select = NULL, mutate_fun = to.monthly)
)
expect_error(
seq(1:100) %>%
tq_mutate_xy(x = a, mutate_fun = to.monthly)
)
expect_error(
tibble(a = seq(1:100)) %>%
tq_mutate(select = NULL, mutate_fun = to.monthly),
"No date or POSIXct column found in `data`."
)
expect_error(
tibble(a = seq(1:100)) %>%
tq_mutate_xy(x = a, mutate_fun = to.monthly),
"No date or POSIXct column found in `data`."
)
})
test_that("Test error on invalid select, x and y inputs.", {
expect_error(
{select <- "err"
AAPL %>%
tq_mutate_(select = select, mutate_fun = "to.monthly")}
)
expect_error(
{x <- "err"
AAPL %>%
tq_mutate_xy_(x = x, y = "close", mutate_fun = "Delt", k = 1)},
paste0("x = err not a valid name.")
)
expect_error(
{y <- "err"
AAPL %>%
tq_mutate_xy_(x = "open", y = y, mutate_fun = "Delt", k = 1)},
paste0("y = err not a valid name.")
)
})
test_that("Test error on invalid mutate_fun, x and y inputs.", {
expect_error(
{mutate_fun <- "err"
AAPL %>%
tq_mutate_(select = "close", mutate_fun = mutate_fun)},
paste0("fun = err not a valid option.")
)
}) |
updateDefaults <- function(gg, defaults, linetypes = linetypes) {
for (i in c('rect', 'line', 'text')) {
if (i %in% c('rect', 'line') && !is.null(gg$theme[[i]]['linetype']) && is.numeric(gg$theme[[i]][['linetype']])) {
gg$theme[[i]]['linetype'] <- linetypes[(gg$theme[[i]][['linetype']] + 1)]
}
ThemeClass <- class(gg$theme[[i]])[1]
DefaultClasses <- sapply(defaults, class)
DefaultClasses <- DefaultClasses[DefaultClasses == ThemeClass]
DefaultClasses <- names(DefaultClasses)
if (length(DefaultClasses) > 0) {
for (j in DefaultClasses) {
gg$theme[[i]][which(gg$theme[[i]][names(default[[j]])] == '')] <- NULL
default[[j]][names(gg$theme[[i]])] <- lapply(gg$theme[[i]][names(gg$theme[[i]])], unname)
}
}
}
LegendPosition <- NULL
if (length(gg$theme$legend.position) > 1) {
LegendPosition <- gg$theme$legend.position
gg$theme$legend.position <- 'XY'
gg$theme$legend.position.x <- LegendPosition[1]
gg$theme$legend.position.y <- LegendPosition[2]
}
ThemeOptions <- unlist(gg$theme)
NamesThemes <- names(ThemeOptions)
NamesDefaults <- names(unlist(defaults))
CommonNames <- NamesThemes[NamesThemes %in% NamesDefaults]
CommonNames <- CommonNames[!CommonNames %in% c('legend.position.x', 'legend.position.y')]
for (i in CommonNames) {
anchor <- gsub(pattern = '\\.[a-z]*$', '', i)
element <- gsub(pattern = '^.*\\.', '', i)
if (i == 'legend.position' || i == 'legend.direction') {
if (!is.null(LegendPosition) && i == 'legend.position') {
defaults['legend.position'] <- 'XY'
defaults['legend.position.x'] <- LegendPosition[1]
defaults['legend.position.y'] <- LegendPosition[2]
} else {
defaults[i] <- gg$theme[i]
}
}
else {
if (class(gg[['theme']][[anchor]][[element]]) == 'rel') {
if (!is.null(gg$theme$text$size)) {
text_size <- gg$theme$text$size
} else {
text_size <- 10
}
defaults[[anchor]][[element]] <- as.numeric(gg[['theme']][[anchor]][[element]]) * text_size
} else {
if (element == 'linetype' && is.numeric(gg[['theme']][[anchor]][[element]])) {
defaults[[anchor]][[element]] <- linetypes[gg[['theme']][[anchor]][[element]] + 1]
} else {
defaults[[anchor]][[element]] <- gg[['theme']][[anchor]][[element]]
}
}
}
}
defaults <- rapply(defaults, function(x) { gsub('grey', 'gray', x) }, how = 'list')
return(defaults)
} |
ksTest <- function (x, ...) {
UseMethod("ksTest")
}
ksTest.default <- function(x,y,...,alternative=c("two.sided","less","greater"),
exact=NULL) {
stats::ks.test(x,y,...,alternative=alternative,exact=exact)
}
ksTest.formula <- function(x,data=NULL,...,alternative=c("two.sided","less","greater"),exact=NULL) {
tmp <- iHndlFormula(x,data,expNumR=1,expNumE=1,expNumEFacts=1)
if (tmp$vnum!=2) STOP("Formula for `ksTest' must contain 1 response (LHS) and 1 explanatory (RHS) variable.")
if (!tmp$metExpNumR) STOP("LHS of formula must contain only one variable.")
if (!tmp$Rclass %in% c("numeric","integer")) STOP("LHS variable must be numeric.")
if (!tmp$metExpNumE) STOP("RHS of formula must contain only one variable.")
if (!tmp$metExpNumEFacts) STOP("RHS Variable must be a factor.")
if (length(levels(tmp$mf[,tmp$EFactPos]))!=2) STOP("`ksTest` only works if the RHS variable has two levels.")
DF.split <- split(tmp$mf[,tmp$Rpos],tmp$mf[,tmp$EFactPos])
ksTest.default(DF.split[[1]],DF.split[[2]],...,alternative=alternative,exact=exact)
} |
context("Sample CPA")
test_that("sample_cpa returns correct shape", {
input_df <- tibble::tibble(
option_name = c("A", "B", "C"),
sum_clicks = c(1000, 1000, 1000),
sum_conversions = c(100, 120, 110),
sum_cost = c(10, 50, 30),
)
n_options <- length(unique(input_df$option_name))
n_samples <- 150
expected_col_names <- c(colnames(input_df),
"beta_params", "gamma_params", "samples")
output <- sample_cpa(input_df, priors = list(), n_samples = n_samples)
expect_true(is.data.frame(output))
expect_true(all(c("option_name", "samples") %in% colnames(output)))
expect_length(output$samples, n_options)
purrr::walk(output$samples, ~ expect_length(.x, n_samples))
expect_equal(colnames(output), expected_col_names)
}) |
context("addlog and subtractlog")
test_that("addlog works", {
a <- 50
b <- 60
d <- 2
expect_equal(addlog(a,b), log(exp(a)+exp(b)))
expect_equal(addlog(b,a), log(exp(a)+exp(b)))
expect_equal(addlog(a,d), log(exp(a)+exp(d)))
expect_equal(addlog(d,a), log(exp(a)+exp(d)))
expect_equal(addlog(b,d), log(exp(b)+exp(d)))
expect_equal(addlog(d,b), log(exp(b)+exp(d)))
expect_equal(addlog(a,a+300), a+300);
expect_equal(addlog(a,a-300), a);
expect_equal(addlog(a+300,a), a+300);
expect_equal(addlog(a-300,a), a);
})
test_that("subtractlog works", {
a <- 60
b <- 50
d <- 2
e <- 5
expect_equal(subtractlog(a,b), log(exp(a)-exp(b)))
expect_equal(subtractlog(a,d), log(exp(a)-exp(d)))
expect_equal(subtractlog(b,d), log(exp(b)-exp(d)))
expect_equal(subtractlog(e,d), log(exp(e)-exp(d)))
expect_equal(subtractlog(e,d), log(exp(e)-exp(d)))
expect_equal(subtractlog(a+300,a), 360);
expect_equal(subtractlog(a,a-300), a);
expect_equal(subtractlog(0.0, -a), log(1.0-exp(-a)));
expect_equal(subtractlog(0.0, -b), log(1.0-exp(-b)));
expect_equal(subtractlog(0.0, -d), log(1.0-exp(-d)));
}) |
ops <- list(
"+",
"=",
"==",
"!=",
"<=",
">=",
"<-",
"<<-",
"<",
">",
"->",
"->>",
"%%",
"/",
"^",
"*",
"**",
"|",
"||",
"&",
"&&",
rex("%", except_any_of("%"), "%"))
commented_code_linter <- function(source_file) {
res <- re_matches(source_file$file_lines,
rex(some_of("
capture(name = "code",
anything,
or(some_of("{}[]"),
or(ops),
group(graphs, "(", anything, ")"),
group("!", alphas)
),
anything
)
),
global = FALSE, locations = TRUE)
line_numbers <- rownames(na.omit(res))
lapply(line_numbers, function(line_number) {
line <- source_file$file_lines[as.numeric(line_number)]
is_parsable <- parsable(substr(line,
res[line_number, "code.start"],
res[line_number, "code.end"]))
if (is_parsable) {
Lint(
filename = source_file$filename,
line_number = line_number,
column_number = res[line_number, "code.start"],
type = "style",
message = "Commented code should be removed.",
line = line,
linter = "commented_code_linter",
ranges = list(c(res[line_number, "code.start"], res[line_number, "code.end"]))
)
}
})
}
parsable <- function(x) {
if (is.null(x)) {
return(FALSE)
}
res <- try_silently(parse(text = x))
!inherits(res, "try-error")
}
todo_comment_linter <- function(todo=c("todo", "fixme")) {
function(source_file) {
tokens <- with_id(source_file, ids_with_token(source_file, "COMMENT"))
are_todo <- re_matches(tokens[["text"]], rex(one_or_more("
tokens <- tokens[are_todo, ]
lapply(
split(tokens, seq_len(nrow(tokens))),
function(token) {
Lint(
filename = source_file[["filename"]],
line_number = token[["line1"]],
column_number = token[["col1"]],
type = "style",
message = "TODO comments should be removed.",
line = source_file[["lines"]][[as.character(token[["line1"]])]],
ranges = list(c(token[["col1"]], token[["col2"]])),
linter = "todo_comment_linter"
)
}
)
}
} |
"drmPNsplit" <-
function(parmVec, sep)
{
lenPV <- length(parmVec)
parmVecA <- rep(0, lenPV)
parmVecB <- rep(0, lenPV)
splitList <- strsplit(parmVec, sep, fixed = TRUE)
for (i in 1:lenPV)
{
parmVecA[i] <- splitList[[i]][1]
lenSL <- length(splitList[[i]])
parmVecB[i] <- paste(splitList[[i]][2:lenSL], collapse = "")
}
return(list(parmVec, parmVecA, parmVecB))
} |
coefficients.plmm <-
function(object,...){object$coefficients} |
get_item_parameter_estimates <- function(decoder, model_type = 2){
all_decoder_weights <- keras::get_weights(decoder)
weights_length <- length(all_decoder_weights)
estimates <- c()
if (model_type == 1){
estimates[1] <- all_decoder_weights[weights_length]
} else{
estimates[1] <- all_decoder_weights[weights_length]
estimates[2] <- all_decoder_weights[weights_length - 1]
}
estimates
}
get_ability_parameter_estimates <- function(encoder, responses){
encoded_responses <- encoder(responses)
estimates_variances <- c()
ability_parameter_estimates <- encoded_responses[[1]]
ability_parameter_log_variance <- encoded_responses[[2]]
if (ability_parameter_estimates$shape == ability_parameter_log_variance$shape){
estimates_variances[[1]] <- ability_parameter_estimates$numpy()
estimates_variances[[2]] <- exp(ability_parameter_log_variance$numpy())
} else{
b <- tfprobability::tfb_fill_triangular(upper=FALSE)
log_cholesky <- b$forward(ability_parameter_log_variance)
cholesky <- tensorflow::tf$linalg$expm(log_cholesky)
cov_matrices <- tensorflow::tf$matmul(cholesky, tensorflow::tf$transpose(cholesky, c(0L, 2L, 1L)))
estimates_variances[[1]] <- ability_parameter_estimates$numpy()
estimates_variances[[2]] <- cov_matrices
}
estimates_variances
} |
DupRm <- function(strings.vec){
str_dupRm.vec <- gsub("([[:graph:]])\\1+", "\\1", strings.vec)
return(str_dupRm.vec)
} |
data(tacks)
x <- tacks$x
k <- tacks$k
f <- Bmix(x,k,verb = 5)
plot(f, xlab = "", main = "Beckett-Diaconis Tacky Mixture")
abline(v = c(0.4385, 0.6013, 0.8144),col = 2) |
mstep1 <-
function(Y, Tau, Pi, mu, g)
{
for(i in 1:g)
{
Pi[i]<-sum(Tau[,i])/nrow(Y)
mu[,i]<-apply(Y*Tau[,i],2,sum)/sum(Tau[,i])
}
return(list(Pi, mu))
} |
library(ggplot2)
sales
salesg = sales
ggplot(data = salesg)+ aes(x=sdate,y=pies) +
geom_point() + labs( title ='Sales data of Pies', x='Date', y='Sales')
salesg
g1= ggplot(data = salesg, aes(x=sdate,y=pies))
g2= g1+ geom_point()
g3= g2 + labs( title ='Sales data of Pies', x='Date', y='Sales')
g3
g1= ggplot(data = salesg, aes(x=sdate,y=pies))
g2= geom_point()
g3= labs( title ='Sales data of Pies', x='Date', y='Sales')
g=g1+g2+g3
g
g2b = geom_point(pch=17, color='blue', size=2)
g3b = geom_smooth(method='lm', color='red', linetype=3)
gA = g1 + g2b + g3b
gA
names(salesg)
f1 = ggplot(salesg, aes(x=sdate, y=pies, shape=daywk, col=daywk))
f2 = geom_point(size=3)
f= f1+f2
f |
expected <- eval(parse(text="FALSE"));
test(id=0, code={
argv <- eval(parse(text="list(integer(0))"));
do.call(`is.object`, argv);
}, o=expected); |
appendLevels <- function(...){
unique(unlist(lapply(list(...), function(x){
if (is.factor(x))
levels(x)
else
x
})))
}
recodeLevels.factor <- function(x, lev){
m <- match(levels(x), lev)
a <- attributes(x)
a$levels <- lev
attributes(x) <- NULL
x <- m[x]
attributes(x) <- a
x
}
recodeLevels.ff <- function(x, lev){
stopifnot(is.factor(x))
m <- match(levels(x), lev)
rc <- ramclass(x)
levels(x) <- NULL
i1 <- i2 <- NULL
ffvecapply({
i <- hi(i1,i2)
x[i] <- m[x[i]]
},X=x)
levels(x) <- lev
virtual(x)$ramclass <- rc
x
}
sortLevels.factor <- function(x){
l <- levels(x)
o <- order(l)
if (identical(o, seq_along(o)))
x
else
recodeLevels.factor(x, l[o])
}
sortLevels.ff <- function(x){
l <- levels(x)
o <- order(l)
if (identical(o, seq_along(o)))
x
else
recodeLevels.ff(x, l[o])
}
sortLevels.ffdf <- function(x){
for (i in seq_len(ncol(x))){
y <- x[[i]]
if (is.factor(y))
x[[i]] <- sortLevels.ff(y)
}
x
} |
getLoglikeSF <- function(beta, gamma1, alpha1, H01,
Sig, sigma, Z, X1, Y, X2, survtime, cmprsk, mdata,
mdataS, xsmatrix, wsmatrix, method, Posbi, Pscov) {
n <- nrow(X2)
p1a <- ncol(Z)
CUH01 <- rep(0, n)
HAZ01 <- rep(0, n)
CumuH01 <- cumsum(H01[, 3])
getHazardSF(CumuH01, survtime, cmprsk, H01, CUH01, HAZ01)
if (method == "standard") {
status = getloglikeCstandardSF(beta, gamma1, alpha1,
Sig, sigma, Z, X1, Y, X2, survtime, cmprsk,
mdata, mdataS, xsmatrix, wsmatrix,
CUH01, HAZ01)
} else {
status = getloglikeCpseudoSF(beta, gamma1, alpha1,
Sig, sigma, Z, X1, Y, X2, survtime, cmprsk,
mdata, mdataS, xsmatrix, wsmatrix,
CUH01, HAZ01, Posbi, Pscov)
}
return(status)
} |
"predict.fitEmax"<-
function(object,dosevec,clev=0.9,int=1,dref=0, xvec=NULL, ...){
if(missing(dosevec))stop('dosevec must be specified')
modType<-object$modType
binary<-object$binary
pboAdj<-object$pboAdj
parmstot<-object$fit$estimate
vc<-object$fit$vc
nprot<-max(as.numeric(object$prot))
prot<-as.numeric(object$prot)
nbase<-object$nbase
if(nbase && is.null(xvec))xvec<-object$xbase[prot==int,]
if(! int%in%(c(1:nprot)))stop('The intercept specification is invalid')
clev<- 0.5+clev/2
if(all(pboAdj)){
parmstot<-c(parmstot,rep(0,nprot))
}else if(any(pboAdj)){
indp<-which(!pboAdj)
parmhold<-numeric(modType+nprot-1)
parmhold[1:(modType-1)]<-parmstot[1:(modType-1)]
parmhold[modType+indp-1]<-parmstot[modType+sum(!pboAdj)-1]
parmstot<-parmhold
}
nparm<-length(parmstot)
nsub<-nparm-nprot-nbase
if(! nsub%in%c(2,3) )stop('parm has invalid length')
parms<-parmstot[c(1:nsub,nsub+int)]
if(nbase>0)parms<-c(parms,parmstot[c((1+nparm-nbase):nparm)])
if(any(pboAdj)){
if(modType==3){
tmpcov<-diag(2+nprot)
diag(tmpcov)<-0
if(all(pboAdj)){
tmpcov[1:2,1:2]<-vc
}else{
tmpcov[c(1:2,2+indp),c(1:2,2+indp)]<-vc
}
vc<-tmpcov
}else{
tmpcov<-diag(3+nprot)
diag(tmpcov)<-0
if(all(pboAdj)){
tmpcov[1:3,1:3]<-vc
}else{
tmpcov[c(1:3,3+indp),c(1:3,3+indp)]<-vc
}
vc<-tmpcov
}
}
if(!nbase){
vc<-vc[c(1:nsub,nsub+int),c(1:nsub,nsub+int)]
}else vc<-vc[c(1:nsub,nsub+int,(1+nparm-nbase):nparm),
c(1:nsub,nsub+int,(1+nparm-nbase):nparm)]
mout<-SeEmax(list(parms,vc),dosevec,modType=nsub+1,dref=dref,
nbase=nbase,x=xvec, binary=binary, clev=clev)
return(mout)
} |
est.gamma <-
function(t){
ll.gamma <-function(gamma.par) {
gamma.par <- mpfr(gamma.par, 99)
y=log(prod((gamma.par^(gamma.par)*t^(gamma.par-1)*exp(-(gamma.par*t)))/(gamma(gamma.par))))
return(asNumeric(y))
}
ll.gamma.opt = NULL
ll.gamma.opt = optimize(f = ll.gamma, interval = c(0.1, 4), maximum=TRUE)
outlist = list(gamma.par=ll.gamma.opt$maximum, ll.gamma.max=ll.gamma.opt$objective)
class(outlist) = "est.gamma"
return(outlist)
} |
hex2ucp <- function(x) {
x <- as.character(Unicode::as.u_char(x))
x <- ifelse(x == "<NA>", NA_character_, x)
x
}
int2ucp <- function(x) {
x <- as.integer(x)
hex2ucp(x)
}
str2ucp <- function(x) {
sapply(x, function(s) int2ucp(utf8ToInt(s)), USE.NAMES = FALSE)
}
name2ucp <- function(x, type = c("exact", "grep"), ...) {
as.character(Unicode::u_char_from_name(toupper(x), type = type, ...))
}
is_ucp <- function(x) {
grepl("^U\\+[1-9A-F]*[0-9A-F]{4}$", x)
}
block2ucp <- function(x, omit_unnamed = TRUE) {
stopifnot(length(x) == 1L)
r <- Unicode::u_blocks(x)[[1]]
ucp <- as.character(Unicode::as.u_char(r))
if (omit_unnamed) {
n <- Unicode::u_char_name(ucp)
ucp <- ucp[which(!is.na(n) & n != "")]
}
ucp
}
range2ucp <- function(x, omit_unnamed = TRUE) {
r <- Unicode::as.u_char_range(x)
ucp <- as.character(Unicode::as.u_char(r))
if (omit_unnamed) {
n <- Unicode::u_char_name(ucp)
ucp <- ucp[which(!is.na(n) & n != "")]
}
ucp
} |
create_site_model_parameters_xml <- function(
inference_model
) {
id <- inference_model$site_model$id
testit::assert(beautier::is_id(id))
gcc <- inference_model$site_model$gamma_site_model$gamma_cat_count
mutation_rate_parameter <- paste0("<parameter ",
"id=\"mutationRate.s:", id, "\" "
)
if (inference_model$beauti_options$beast2_version == "2.6") {
mutation_rate_parameter <- paste0(mutation_rate_parameter,
"spec=\"parameter.RealParameter\" "
)
}
mutation_rate_parameter <- paste0(mutation_rate_parameter,
"estimate=\"false\" name=\"mutationRate\">1.0</parameter>"
)
gamma_shape_parameter <- NULL
if (gcc < 2) {
gamma_shape_parameter <- paste0(
"<parameter ",
"id=\"gammaShape.s:", id, "\" "
)
if (inference_model$beauti_options$beast2_version == "2.6") {
gamma_shape_parameter <- paste0(gamma_shape_parameter,
"spec=\"parameter.RealParameter\" "
)
}
gamma_shape_parameter <- paste0(gamma_shape_parameter,
"estimate=\"false\" name=\"shape\">1.0</parameter>"
)
}
proportion_invariant_parameter <- paste0(
"<parameter id=\"proportionInvariant.s:", id, "\" ")
if (inference_model$beauti_options$beast2_version == "2.6") {
proportion_invariant_parameter <- paste0(proportion_invariant_parameter,
"spec=\"parameter.RealParameter\" "
)
}
proportion_invariant_parameter <- paste0(
proportion_invariant_parameter,
"estimate=\"false\" lower=\"0.0\" ",
"name=\"proportionInvariant\" upper=\"1.0\">",
inference_model$site_model$gamma_site_model$prop_invariant,
"</parameter>"
)
text <- mutation_rate_parameter
if (!is.null(gamma_shape_parameter)) {
text <- c(text, gamma_shape_parameter)
}
text <- c(
text,
paste0(proportion_invariant_parameter)
)
if (inference_model$beauti_options$beast2_version == "2.6") {
text <- rep(text, each = 2)
text[seq(2, length(text), by = 2)] <- " "
}
text
} |
tbr_misc <- function(.tbl, x, tcolumn, unit = "years", n, func, ...) {
col_name <- as.character(substitute(func))
.tbl <- .tbl %>%
arrange(!! rlang::enquo(tcolumn)) %>%
mutate(!! col_name := purrr::map(row_number(),
~func_window(x = !! rlang::enquo(x),
tcolumn = !! rlang::enquo(tcolumn),
unit = unit,
n = n,
i = .x,
func = func))) %>%
tidyr::unnest(!! col_name)
.tbl <- tibble::as_tibble(.tbl)
return(.tbl)
}
func_window <- function(x, tcolumn, unit = "years", n, i, func, ...) {
u <- (c("years", "months", "weeks", "days", "hours", "minutes", "seconds"))
if (!unit %in% u) {
stop("unit must be one of ", paste(u, collapse = ", "))
}
window <- open_window(x, tcolumn, unit = unit, n, i)
date_window <- open_window(tcolumn, tcolumn, unit = unit, n, i)
results <- tibble::tibble(results = func(window, ...), min_date = min(date_window), max_date = max(date_window))
return(results)
} |
setOldClass("tbl_impala")
intersect.tbl_impala <- function(x, y, copy = FALSE, ...) {
stop("Impala does not support intersect operations.", call. = FALSE)
}
setdiff.tbl_impala <- function(x, y, copy = FALSE, ...) {
stop("Impala does not support setdiff operations.", call. = FALSE)
}
compute.tbl_impala <-
function(x,
name,
temporary = TRUE,
unique_indexes = NULL,
indexes = NULL,
analyze = FALSE,
external = FALSE,
overwrite = FALSE,
force = FALSE,
field_terminator = NULL,
line_terminator = NULL,
file_format = NULL,
...) {
assert_that(
is.string(name),
is.flag(temporary),
is.flag(external),
is.flag(overwrite),
is.flag(force),
is.flag(analyze),
is_string_or_null(file_format),
is_nchar_one_string_or_null(field_terminator),
is_nchar_one_string_or_null(line_terminator)
)
if (temporary) {
stop(
"Impala does not support temporary tables. Set temporary = FALSE in compute().",
call. = FALSE
)
}
vars <- op_vars(x)
assert_that(all(unlist(indexes) %in% vars))
assert_that(all(unlist(unique_indexes) %in% vars))
x_aliased <- select(x, !!! syms(vars))
sql <- db_sql_render(x$src$con, x_aliased$ops)
name <- db_save_query(
con = x$src$con,
sql = sql,
name = name,
temporary = FALSE,
analyze = analyze,
external = external,
overwrite = overwrite,
force = force,
field_terminator = field_terminator,
line_terminator = field_terminator,
file_format = file_format,
...
)
tbl(x$src, name) %>%
group_by(!!! syms(op_grps(x)))
}
collect.tbl_impala <-
function(x,
...,
n = Inf,
warn_incomplete = TRUE) {
NextMethod("collect")
}
collapse.tbl_impala <- function(x, vars = NULL, ...) {
NextMethod("collapse")
}
impala_unnest <- function(data, col, ...) {
res <- data
if (!inherits(res, "tbl_impala")) {
stop("data argument must be a tbl_impala", call. = FALSE)
}
if (!"vars" %in% names(res$ops$x) ||
all(is.na(attr(res$ops$x$vars, "complex_type")))) {
stop("data argument must contain complex columns", call. = FALSE)
}
if (is.null(attr(res$ops$x$vars, "complex_type"))) {
stop("impala_unnest() can only be applied once to a tbl_impala",
call. = FALSE)
}
if (!"x" %in% names(res$ops$x) ||
!inherits(res$ops$x$x, "ident")) {
stop("impala_unnest() must be applied to a tbl_impala before any other operations",
call. = FALSE)
}
col <- enexpr(col)
colname <- as.character(col)
if (length(colname) != 1) {
stop("impala_unnest() can unnest only one column")
}
colindex <- which(res$ops$x$vars == colname)
if (length(colindex) != 1) {
stop("Column ", colname, " not found", call. = FALSE)
}
coltype <- attr(res$ops$x$vars, "complex_type")[colindex]
tablename <- as.character(res$ops$x$x)
if (identical(coltype, "array")) {
quoted_tablename <- impala_escape_ident(res$src$con, tablename, "`")
res$ops$x$x <- ident_q(
paste0(quoted_tablename, ", ", quoted_tablename, ".`", colname,"`")
)
res$ops$x$vars <- c(
setdiff(res$ops$x$vars, colname),
paste0(colname, ".item"),
paste0(colname, ".pos")
)
res$ops <- res$ops$x
item_name_before <- paste0(colname, ".item")
item_name_after <- paste0(colname, "_item")
pos_name_before <- paste0(colname, ".pos")
pos_name_after <- paste0(colname, "_pos")
rename_complex_cols <- vars_rename(
colnames(res),
!!item_name_after := !!item_name_before,
!!pos_name_after := !!pos_name_before
)
res <- select(res, rename_complex_cols)
} else if (identical(coltype, "map")) {
quoted_tablename <- impala_escape_ident(res$src$con, tablename, "`")
res$ops$x$x <- ident_q(
paste0(quoted_tablename, ", ", quoted_tablename, ".`", colname,"`")
)
res$ops$x$vars <- c(
setdiff(res$ops$x$vars, colname),
paste0(colname, ".key"),
paste0(colname, ".value")
)
res$ops <- res$ops$x
key_name_before <- paste0(colname, ".key")
key_name_after <- paste0(colname, "_key")
value_name_before <- paste0(colname, ".value")
value_name_after <- paste0(colname, "_value")
rename_complex_cols <- vars_rename(
colnames(res),
!!key_name_after := !!key_name_before,
!!value_name_after := !!value_name_before
)
res <- select(res, rename_complex_cols)
} else if (identical(coltype, "struct")) {
sql <- paste0("DESCRIBE ", tablename, ".", colname)
structcolnames <- dbGetQuery(res$src, sql)$name
othercolnames <- setdiff(res$ops$x$vars, colname)
col_names_before <- c(
othercolnames,
paste(colname, structcolnames, sep = ".")
)
col_names_after <- c(
othercolnames,
paste(colname, structcolnames, sep = "_")
)
res$ops$x$vars <- col_names_before
res$ops <- res$ops$x
rename_complex_cols <- col_names_before
names(rename_complex_cols) <- col_names_after
res <- select(res, !!rename_complex_cols)
} else {
stop("Column ", colname, " must be of type ARRAY, MAP, or STRUCT", call. = FALSE)
}
res
} |
replay_html_dm_draw <- function(x, ...) {
unclass(x)
}
pkgdown_print_grViz <- function(x, ...) {
structure(DiagrammeRsvg::export_svg(x), class = "dm_draw")
}
register_pkgdown_methods <- function() {
if (Sys.getenv("IN_PKGDOWN") == "") {
return()
}
check_suggested(c("DiagrammeR", "DiagrammeRsvg"),
use = TRUE,
message = "DiagrammeR and DiagrammeRsvg packages needed for this function to work. Please install it."
)
s3_register("downlit::replay_html", "dm_draw", replay_html_dm_draw)
s3_register("pkgdown::pkgdown_print", "grViz", pkgdown_print_grViz)
} |
hilight_source = function(x, format, options) {
if ((format %in% c('latex', 'html')) && options$highlight) {
res = if (options$engine == 'R') {
opts = opts_knit$get('highr.opts')
highr::hilight(x, format, prompt = options$prompt, markup = opts$markup)
} else {
res = try(highr::hi_andre(x, options$engine, format))
if (inherits(res, 'try-error')) {
if (format == 'html') highr:::escape_html(x) else highr:::escape_latex(x)
} else {
highlight_header()
n = length(res)
if (res[n] == '\\normalsize') res = res[-n]
res
}
}
if (format == 'latex' && is.character(tld <- opts_knit$get('latex.tilde'))) {
res = gsub('\\hlopt{~}', tld, res, fixed = TRUE)
}
res
} else if (options$prompt) {
if (options$engine == 'R' && isFALSE(options$tidy) && isFALSE(options$eval))
x = vapply(xfun::split_source(x), one_string, character(1))
line_prompt(x)
} else x
}
highlight_header = function() {
set_header(highlight.extra = paste(c(
sprintf('\\let\\hl%s\\hlstd', c('esc', 'pps', 'lin')),
sprintf('\\let\\hl%s\\hlcom', c('slc', 'ppc'))
), collapse = ' '))
}
w3c.colors = c(
aqua = '
gray = '
navy = '
silver = '
)
css.parse.color = function(txt, default = '
txt = gsub('\\s+', '', tolower(txt))
if (is.hex(txt)) return(txt)
rgb = function(...) grDevices::rgb(..., maxColorValue = 255)
if (!grepl('[^a-z]', txt) && txt %in% names(w3c.colors))
return(w3c.colors[txt])
if (!grepl('[^a-z0-9]', txt)) {
R.colors = colors()
res = R.colors %in% txt
if (any(res)) {
return(rgb(t(col2rgb(R.colors[res]))))
}
}
if (grepl('rgb', txt)) {
p = try_silent(parse(text = txt))
if (!inherits(p, 'try-error')) {
res = try_silent(eval(p))
if (!inherits(res, 'try-error')) return(res)
}
}
default
}
is.hex = function(x) grepl('^
css.parser = function(file, lines = read_utf8(file)) {
rx = '^\\.(.*?) *\\{.*$'
dec.lines = grep(rx, lines)
dec.names = sub(rx, '\\1', lines[dec.lines])
if (any(grepl('[0-9]', dec.names))) warning('use of numbers in style names')
end.lines = grep('^\\s*\\}', lines)
dec.close = end.lines[vapply(dec.lines, function(x) which.min(end.lines < x), integer(1))]
pos = matrix(c(dec.lines, dec.close), ncol = 2)
styles = apply(pos, 1, function(x) {
data = lines[(x[1] + 1):(x[2] - 1)]
settings.rx = '^\\s*(.*?)\\s*:\\s*(.*?)\\s*;\\s*$'
settings = sub(settings.rx, '\\1', data, perl = TRUE)
contents = sub(settings.rx, '\\2', data, perl = TRUE)
out = list()
for (i in seq_along(settings)) {
setting = settings[i]
content = contents[i]
out[[setting]] = switch(
setting,
color = css.parse.color(content, '
background = css.parse.color(content, '
content
)
}
out
})
names(styles) = dec.names
styles
}
styler_assistant_latex = function(x) {
styles = sapply(x, function(item) {
settings = names(item)
has = function(s, value) {
s %in% settings && grepl(value, item[[s]])
}
start = end = ''
if ('color' %in% settings) {
start = paste0(start, '\\textcolor[rgb]{', col2latexrgb(item[['color']]), '}{')
end = paste0(end, '}')
}
if (has('font-weight', 'bold')) {
start = paste0(start, '\\textbf{')
end = paste0('}', end)
}
if (has('font-style', 'italic')) {
start = paste0(start, '\\textit{')
end = paste0('}', end)
}
sprintf('%s
})
res = sprintf('\\newcommand{\\hl%s}[1]{%s}%%', names(x), styles)
c(res, '\\let\\hlipl\\hlkwb')
}
col2latexrgb = function(hex) {
outdec = options(OutDec = '.'); on.exit(options(outdec))
col = col2rgb(hex)[, 1] / 255
paste(round(col, 3), collapse = ',')
} |
read_geno_csv <- function(file.in, ploidy, filter.non.conforming = TRUE, elim.redundant = TRUE, verbose = TRUE) {
dat <- read.csv(file = file.in, header = TRUE, stringsAsFactors = FALSE)
return(table_to_mappoly(dat, ploidy, filter.non.conforming = TRUE, elim.redundant = TRUE, verbose = TRUE))
}
table_to_mappoly <- function(dat, ploidy, filter.non.conforming = TRUE, elim.redundant = TRUE, verbose = TRUE){
ploidy <- ploidy
dat = dat[which(!is.na(dat[,2,drop = TRUE]) & !is.na(dat[,3,drop = TRUE])),]
n.ind <- ncol(dat) - 5
n.mrk <- nrow(dat)
mrk.names <- dat[,1,drop = TRUE]
ind.names <- colnames(dat)[-c(1:5)]
dosage.p1 <- as.integer(dat[,2,drop = TRUE])
dosage.p2 <- as.integer(dat[,3,drop = TRUE])
dp <- abs(abs(dosage.p1-(ploidy/2))-(ploidy/2))
dq <- abs(abs(dosage.p2-(ploidy/2))-(ploidy/2))
id <- dp+dq != 0
chrom <- as.character(dat[,4,drop = TRUE])
sequencepos <- as.numeric(dat[,5,drop = TRUE])
names(sequencepos) <- names(chrom) <- names(dosage.p2) <- names(dosage.p1) <- mrk.names
nphen <- 0
phen <- NULL
if (verbose){
cat("Reading the following data:")
cat("\n Ploidy level:", ploidy)
cat("\n No. individuals: ", n.ind)
cat("\n No. markers: ", n.mrk)
cat("\n No. informative markers: ", sum(id), " (", round(100*sum(id)/n.mrk,1), "%)", sep = "")
if (all(unique(nphen) != 0))
cat("\n This dataset contains phenotypic information.")
if (length(sequence) > 1)
cat("\n This dataset contains chromosome information.")
cat("\n ...")
}
geno.dose <- as.matrix(dat[,-c(1:5),drop = TRUE])
dimnames(geno.dose) <- list(mrk.names, ind.names)
geno.dose[is.na(geno.dose)] <- ploidy + 1
if (verbose) cat("\n Done with reading.\n")
geno.dose <- geno.dose[id,]
res <- structure(list(ploidy = ploidy,
n.ind = n.ind,
n.mrk = sum(id),
ind.names = ind.names,
mrk.names = mrk.names[id],
dosage.p1 = dosage.p1[id],
dosage.p2 = dosage.p2[id],
chrom = chrom[id],
genome.pos = sequencepos[id],
seq.ref = NULL,
seq.alt = NULL,
all.mrk.depth = NULL,
prob.thres = NULL,
geno.dose = geno.dose,
nphen = nphen,
phen = phen,
kept = NULL,
elim.correspondence = NULL),
class = "mappoly.data")
if(filter.non.conforming){
if (verbose) cat(" Filtering non-conforming markers.\n ...")
res <- filter_non_conforming_classes(res)
Ds <- array(NA, dim = c(ploidy+1, ploidy+1, ploidy+1))
for(i in 0:ploidy)
for(j in 0:ploidy)
Ds[i+1,j+1,] <- segreg_poly(ploidy = ploidy, dP = i, dQ = j)
Dpop <- cbind(res$dosage.p1, res$dosage.p2)
M <- t(apply(Dpop, 1, function(x) Ds[x[1]+1, x[2]+1,]))
dimnames(M) <- list(res$mrk.names, c(0:ploidy))
M <- cbind(M, res$geno.dose)
res$chisq.pval <- apply(M, 1, mrk_chisq_test, ploidy = ploidy)
if (verbose) cat("\n Done with filtering.\n")
}
if (elim.redundant){
seqred = make_seq_mappoly(res, arg = 'all', data.name = res)
redun = elim_redundant(seqred, data = res)
if (nrow(redun$elim.correspondence) < 1) return(res)
res$kept = redun$kept
res$elim.correspondence = redun$elim.correspondence
mrks.rem = match(res$elim.correspondence$elim, res$mrk.names)
res$elim.correspondence$chrom = res$chrom[c(mrks.rem)]
res$elim.correspondence$genome.pos = res$genome.pos[c(mrks.rem)]
res$elim.correspondence$seq.ref = NA
res$elim.correspondence$seq.alt = NA
res$elim.correspondence$all.mrk.depth = NA
res$n.mrk = length(res$kept)
res$mrk.names = res$mrk.names[-c(mrks.rem)]
res$geno.dose = res$geno.dose[-c(mrks.rem),]
res$dosage.p1 = res$dosage.p1[-c(mrks.rem)]
res$dosage.p2 = res$dosage.p2[-c(mrks.rem)]
res$chrom = res$chrom[-c(mrks.rem)]
res$genome.pos = res$genome.pos[-c(mrks.rem)]
res$chisq.pval = res$chisq.pval[-c(mrks.rem)]
}
return(res)
} |
ui.modules_ccle_drug_response_diff <- function(id) {
ns <- NS(id)
fluidPage(
fluidRow(
column(3,
wellPanel(
selectizeInput(
inputId = ns("ccle_search"),
label = "Input a gene or list (as signature)",
choices = NULL,
multiple = TRUE,
width = "100%",
options = list(
create = TRUE,
maxOptions = 5,
placeholder = "Enter a gene symbol, e.g. TP53",
plugins = list("restore_on_backspace")
)
),
materialSwitch(ns("pdist_show_p_value"), "Show P value", inline = TRUE),
colourpicker::colourInput(inputId = ns("high_col"), "High group color", "
colourpicker::colourInput(inputId = ns("low_col"), "Low group color", "
selectInput(
inputId = ns("tissue"), label = "Filter Tissue",
choices = ccle_drug_related_tissues, selected = "lung",
multiple = TRUE
),
sliderTextInput(
inputId = ns("alpha"),
label = "Choose a transparent value",
choices = seq(
from = 0,
to = 1,
by = 0.1
),
selected = "0.5",
grid = TRUE
),
tags$hr(style = "border:none; border-top:2px solid
shinyWidgets::actionBttn(
inputId = ns("search_bttn"),
label = "Go!",
style = "gradient",
icon = icon("search"),
color = "primary",
block = TRUE,
size = "sm"
)
),
wellPanel(
numericInput(inputId = ns("height"), label = "Height", value = 8),
numericInput(inputId = ns("width"), label = "Width", value = 12),
prettyRadioButtons(
inputId = ns("device"),
label = "Choose plot format",
choices = c("pdf", "png"),
selected = "pdf",
inline = TRUE,
icon = icon("check"),
animation = "jelly",
fill = TRUE
),
downloadBttn(
outputId = ns("download"),
style = "gradient",
color = "default",
block = TRUE,
size = "sm"
)
)
),
column(9,
plotOutput(ns("gene_ccle_drug_response_diff"), height = "600px"),
h5("Method:"),
p("Analyze difference of drug response (IC50 value (uM)) between gene (or signature) high and low expression."),
p("When there are multiple genes, geometrical mean of expression of these genes are used as a signature."),
p("NOTEs: You can select multiple tissues, even ALL for all tissues.
In this case 'number_of_cell_lines' indicates sample size for each gene-drug group instead of gene-drug-tissue group."),
tags$br(),
DT::DTOutput(outputId = ns("tbl")),
shinyjs::hidden(
wellPanel(
id = ns("save_csv"),
downloadButton(ns("downloadTable"), "Save as csv")
)
)
)
)
)
}
server.modules_ccle_drug_response_diff <- function(input, output, session) {
ns <- session$ns
profile_choices <- reactive({
switch("mRNA",
mRNA = list(all = pancan_identifiers$gene, default = "TP53"),
protein = list(all = UCSCXenaShiny:::.all_ccle_proteins, default = "p53_Caution"),
cnv = list(all = pancan_identifiers$gene, default = "TP53"),
list(all = "NONE", default = "NONE")
)
})
observe({
updateSelectizeInput(
session,
"ccle_search",
choices = profile_choices()$all,
selected = profile_choices()$default,
server = TRUE
)
})
colors <- reactive({
c(input$high_col, input$low_col)
})
plot_func <- eventReactive(input$search_bttn, {
if (nchar(input$ccle_search[1]) >= 1) {
p <- vis_gene_drug_response_diff(
Gene = input$ccle_search,
values = colors(),
tissue = input$tissue,
Method = "wilcox.test",
Show.P.label = input$pdist_show_p_value,
alpha = input$alpha
)
}
return(p)
})
output$gene_ccle_drug_response_diff <- renderPlot({
plot_func()
})
output$download <- downloadHandler(
filename = function() {
paste0(input$ccle_search, "_ccle_target_response_diff.", input$device)
},
content = function(file) {
p <- plot_func()
if (input$device == "pdf") {
pdf(file, width = input$width, height = input$height)
print(p)
dev.off()
} else {
png(file, width = input$width, height = input$height, res = 600, units = "in")
print(p)
dev.off()
}
}
)
output$downloadTable <- downloadHandler(
filename = function() {
paste0(input$ccle_search, "_ccle_target_response_diff.csv")
},
content = function(file) {
write.csv(plot_func()$data, file, row.names = FALSE)
}
)
observeEvent(input$search_bttn, {
if (nchar(input$ccle_search[1]) >= 1) {
shinyjs::show(id = "save_csv")
} else {
shinyjs::hide(id = "save_csv")
}
})
output$tbl <- renderDT(
plot_func()$data,
options = list(lengthChange = FALSE)
)
} |
canvas_stripes <- function(colors, n = 300, H = 1, burnin = 1) {
if (burnin < 1) {
stop("'burnin' must be a value >= 1")
}
mat <- matrix(NA, nrow = n, ncol = n)
for (i in 1:nrow(mat)) {
t <- 1:(n + burnin)
x <- stats::rnorm(n = length(t) - 1, sd = sqrt(H))
x <- c(0, cumsum(x))
mat[i, ] <- rev(x[-(1:burnin)])
}
canvas <- .unraster(mat, names = c("x", "y", "z"))
artwork <- ggplot2::ggplot(data = canvas, ggplot2::aes(x = x, y = y, fill = z)) +
ggplot2::geom_raster(interpolate = TRUE) +
ggplot2::scale_fill_gradientn(colours = colors)
artwork <- theme_canvas(artwork)
return(artwork)
} |
predict.zlm <-
function (object, newdata = NULL, se.fit = FALSE, ...)
{
if (!is(object, "zlm")) {
stop("you need to provide a zlm object")
return()
}
betas = object$coefficients[-1, drop = FALSE]
alpha = object$coefficients[[1]]
if (is.null(newdata)) {
newX <- as.matrix(object$model[, -1, drop = FALSE])
}
else {
newX = as.matrix(newdata)
if (!is.numeric(newX))
stop("newdata must be numeric!")
if (is.vector(newdata))
newX = matrix(newdata, 1)
if (ncol(newX) != length(betas)) {
if (ncol(newX) == length(betas) + 1) {
newX = newX[, -1, drop = FALSE]
}
else {
stop("newdata must be a matrix or data.frame with ",
length(betas), " columns.")
}
}
}
if (!se.fit)
return(as.vector(newX %*% betas) + alpha)
yXdata <- as.matrix(object$model)
oldXraw <- yXdata[, -1, drop = FALSE]
if (!is.null(colnames(newX)) && !is.null(colnames(oldXraw))) {
if (all(colnames(oldXraw) %in% colnames(newX)) && !all(colnames(oldXraw) ==
colnames(newX))) {
warning("argument newdata had to be reordered according to its column names. Consider submitting the columns of newdata in the right order.")
newX = newX[, colnames(oldXraw), drop = FALSE]
}
}
yraw <- yXdata[, 1, drop = TRUE]
N <- length(yraw)
k <- ncol(oldXraw)
oldXmeans <- colMeans(oldXraw)
oldXdm <- oldXraw - matrix(oldXmeans, N, k, byrow = TRUE)
newXdm <- newX - matrix(oldXmeans, nrow(newX), k, byrow = TRUE)
xtxinv = chol2inv(chol(crossprod(oldXdm)))
xtxinv_xf = tcrossprod(xtxinv, newXdm)
xf_xx_xf = unlist(lapply(1:nrow(newXdm), function(x) {
crossprod(newXdm[x, ], xtxinv_xf[, x])[[1L]]
}))
bvar = object$coef2moments[-1] - object$coefficients[-1]^2
bvar_factor = bvar[[1L]]/xtxinv[[1L]]
yty = as.vector(crossprod(yraw) - N * mean(yraw)^2)
r2 = 1 - object$olsres$ymy/yty
if (object$gprior.info$gtype == "hyper") {
f21a = object$gprior.info$hyper.parameter
f21_recover = exp((object$marg.lik) + (N - 1)/2 * log(yty) +
log((k + f21a - 2)/(f21a - 2)))
res_scale = yty/(N - 3)/(N - 1 - k - f21a) * ((N - 3) *
(1 - r2) - (k + f21a - 2)/f21_recover)
svar_woscale = res_scale/N + bvar_factor * xf_xx_xf
}
else {
sf = object$gprior.info$shrinkage.moments[[1]]
res_scale = (1 - sf * r2) * yty/(N - 3)
svar_woscale = res_scale/N + bvar_factor * xf_xx_xf
}
reslist = list()
reslist$fit <- as.vector(newX %*% betas) + alpha
reslist$std.err <- sqrt(svar_woscale + res_scale)
reslist$se.fit <- sqrt(svar_woscale)
reslist$residual.scale <- sqrt(res_scale)
return(reslist)
} |
set.seed(123)
xu <- stats::rnorm(500)
xm <- matrix(stats::rnorm(1000), ncol = 2)
index <- seq(Sys.Date(), Sys.Date() + 499, "day")
prob <- exp_decay(xu, 0.001)
xu_vec <- xu
xu_mat <- as.matrix(xu)
xu_ts <- stats::as.ts(xu)
xu_xts <- xts::xts(xu, index)
xu_df <- as.data.frame(xu)
xu_tbl <- tibble::tibble(index = index, x = xu)
xm_vec <- xm
xm_mat <- as.matrix(xm)
xm_ts <- stats::as.ts(xm)
xm_xts <- xts::xts(xm, index)
xm_df <- as.data.frame(xm)
xm_tbl <- tibble::tibble(index = index, x = xm)
bootstrap_dbl <- bootstrap_scenarios(xu_vec, prob, 5)
test_that("works on doubles", {
expect_type(bootstrap_dbl, "list")
expect_s3_class(bootstrap_dbl, "tbl_df")
expect_equal(ncol(bootstrap_dbl), 1L)
expect_equal(nrow(bootstrap_dbl), 5L)
})
bootstrap_matu <- bootstrap_scenarios(xu_mat, prob, 5)
test_that("works on univariate matrices", {
expect_type(bootstrap_matu, "list")
expect_s3_class(bootstrap_matu, "tbl_df")
expect_equal(ncol(bootstrap_matu), 1L)
expect_equal(nrow(bootstrap_matu), 5L)
})
bootstrap_matm <- bootstrap_scenarios(xm_mat, prob, 5)
test_that("works on multivariate matrices", {
expect_type(bootstrap_matm, "list")
expect_s3_class(bootstrap_matm, "tbl_df")
expect_equal(ncol(bootstrap_matm), 2L)
expect_equal(nrow(bootstrap_matm), 5L)
})
bootstrap_tsu <- bootstrap_scenarios(xu_ts, prob, 5)
test_that("works on univariate ts", {
expect_type(bootstrap_tsu, "list")
expect_s3_class(bootstrap_tsu, "tbl_df")
expect_equal(ncol(bootstrap_tsu), 1L)
expect_equal(nrow(bootstrap_tsu), 5L)
})
bootstrap_tsm <- bootstrap_scenarios(xm_ts, prob, 5)
test_that("works on multivariate ts", {
expect_type(bootstrap_tsm, "list")
expect_s3_class(bootstrap_tsm, "tbl_df")
expect_equal(ncol(bootstrap_tsm), 2L)
expect_equal(nrow(bootstrap_tsm), 5L)
})
bootstrap_xtsu <- bootstrap_scenarios(xu_xts, prob, 5)
test_that("works on univariate xts", {
expect_type(bootstrap_xtsu, "list")
expect_s3_class(bootstrap_xtsu, "tbl_df")
expect_equal(ncol(bootstrap_xtsu), 1L)
expect_equal(nrow(bootstrap_xtsu), 5L)
})
bootstrap_xtsm <- bootstrap_scenarios(xm_xts, prob, 5)
test_that("works on multivariate xts", {
expect_type(bootstrap_xtsm, "list")
expect_s3_class(bootstrap_xtsm, "tbl_df")
expect_equal(ncol(bootstrap_xtsm), 2L)
expect_equal(nrow(bootstrap_xtsm), 5L)
})
bootstrap_dfu <- bootstrap_scenarios(xu_df, prob, 5)
test_that("works on univariate data.frames", {
expect_type(bootstrap_dfu, "list")
expect_s3_class(bootstrap_dfu, "tbl_df")
expect_equal(ncol(bootstrap_dfu), 1L)
expect_equal(nrow(bootstrap_dfu), 5L)
})
bootstrap_dfm <- bootstrap_scenarios(xm_df, prob, 5)
test_that("works on multivariate data.frames", {
expect_type(bootstrap_dfm, "list")
expect_s3_class(bootstrap_dfm, "tbl_df")
expect_equal(ncol(bootstrap_dfm), 2L)
expect_equal(nrow(bootstrap_dfm), 5L)
})
bootstrap_tblu <- bootstrap_scenarios(xu_tbl, prob, 5)
test_that("works on univariate on tibbles", {
expect_type(bootstrap_tblu, "list")
expect_s3_class(bootstrap_tblu, "tbl_df")
expect_equal(ncol(bootstrap_tblu), 1L)
expect_equal(nrow(bootstrap_tblu), 5L)
})
bootstrap_tblm <- bootstrap_scenarios(xm_tbl, prob, 5)
test_that("works on multivariate tibbles", {
expect_type(bootstrap_tblm, "list")
expect_s3_class(bootstrap_tblm, "tbl_df")
expect_equal(ncol(bootstrap_tblm), 2L)
expect_equal(nrow(bootstrap_tblm), 5L)
}) |
plot.pplace <-
function(x,type="precise",simplify=FALSE,main="",N=NULL,transfo=NULL,legend=TRUE,stl=FALSE,asb=FALSE,edge.width=1,max_width=10,cex.number=0.5,cex.text=0.8,transp=80,add=FALSE,color=NULL,discrete_col=FALSE,pch=16,run_id=NULL,...){
if(!is.null(run_id)){
x <- sub_pplace(x,run_id=run_id)
}
if(is.null(N)){
x$multiclass$N <- 1
}
if(!is.null(N)){
x$multiclass$N <- N
}
if(simplify){
x$placement_positions <- x$placement_positions[order(x$placement_positions$ml_ratio,decreasing=TRUE),]
x$placement_positions <- x$placement_positions[match(unique(x$placement_positions$placement_id),x$placement_positions$placement_id),]
x$placement_positions$ml_ratio <- 1
}
if(is.null(color)) color <- c("blue","green","yellow","red")
if(type!="precise"){
placement_N <- aggregate(x$multiclass$N,list(x$multiclass$placement_id),sum)
br_sum <- aggregate(placement_N[match(x$placement_positions$placement_id,placement_N[,1]),2]*x$placement_positions$ml_ratio,list(branch=x$placement_positions$location),sum)
if(type=="number"){
plot(x$arbre,edge.width=edge.width,show.tip.label=stl,no.margin=TRUE,...)
text(0,0,main,cex=cex.text,pos=4)
edgelabels(round(br_sum[,2]),br_sum[,1],cex=cex.number)
if(asb) add.scale.bar()
}
if(type=="fattree"){
vwidth <- rep(0.1,nrow(x$arbre$edge))
vwidth[br_sum[,1]] <- ceiling(max_width*br_sum[,2]/max(br_sum[,2]))
plot(x$arbre,edge.width=vwidth,show.tip.label=stl,no.margin=TRUE,...)
text(0,0,main,cex=cex.text,pos=4)
if(asb) add.scale.bar()
}
if(type=="color"){
col_palette=rgb(colorRamp(color)(seq(0,1,length=100)), maxColorValue = 255)
vcol <- rep(paste0("
coln <- ceiling(100*br_sum[,2]/max(br_sum[,2]))
coln[coln>100] <- 100
vcol[br_sum[,1]] <- col_palette[coln]
if(!legend){
plot(x$arbre,edge.color=vcol,edge.width=edge.width,show.tip.label=stl,no.margin=TRUE,...)
text(0,0,main,cex=cex.text,pos=4)
if(asb) add.scale.bar()
}
if(legend){
layout(matrix(c(rep(1,6),2),ncol=1))
plot(x$arbre,edge.color=vcol,edge.width=edge.width,show.tip.label=stl,no.margin=TRUE,...)
text(0,0,main,cex=cex.text,pos=4)
if(asb) add.scale.bar()
par(mar=c(3,15,3,15))
image(1:length(col_palette),1:1,matrix(1:length(col_palette),ncol=1),col=col_palette,xaxt="n",yaxt="n",xlab="",ylab="")
axis(3,at=c(1,length(col_palette)),labels=c(0,round(max(br_sum[,2]),0)))
text(0,0,main,cex=cex.text,pos=4)
}
}
}
if(type=="precise"){
col_palette <- rgb(colorRamp(color)(seq(0,1,length=1000)), maxColorValue = 255)
if(discrete_col){
col_palette <- rep(NA,1000)
color <- col2rgb(color)
color <- apply(color,2,function(X){rgb(X[1],X[2],X[3], maxColorValue=255)})
pos_col <- round(seq(1,1000,length.out=length(color)+1))
for(i in 1:length(color)){
col_palette[pos_col[i]:pos_col[i+1]] <- color[i]
}
}
vcol <- col_palette[ceiling((x$placement_positions$pendant_bl/max(x$placement_positions$pendant_bl))*1000)]
placement_N <- aggregate(x$multiclass$N,list(x$multiclass$placement_id),sum)
cex_placement <- placement_N[match(x$placement_positions$placement_id,placement_N[,1]),2]*x$placement_positions$ml_ratio
cex_placement[is.na(cex_placement)] <- 0
if(!is.null(transfo)) cex_placement <- transfo(cex_placement)
if(legend & !add){
layout(matrix(c(rep(3,6),1,rep(3,6),2),ncol=2))
par(mar=c(3,7,3,3.5))
image(1:length(col_palette),1:1,matrix(1:length(col_palette),ncol=1),col=col_palette,xaxt="n",yaxt="n",xlab="",ylab="",main="pendant branch length",cex.main=1,font.main=1)
axis(3,at=c(1,length(col_palette)),labels=c(0,round(max(x$placement_positions$pendant_bl),2)))
par(mar=c(1,3.5,1,7))
plot.new()
cex_legend <- seq(0,ceiling(max(cex_placement)),length.out=5)
points(seq(0.1,0.9,by=0.2),y=rep(0.3,5),pch=16,cex=cex_legend)
text(seq(0.1,0.9,by=0.2),y=rep(0.5,5),cex_legend,pos=3)
text(0.5,0.9,"placement size",cex=1)
}
if(!add){
plot(x$arbre,edge.color="black",edge.width=edge.width,show.tip.label=stl,no.margin=TRUE,...)
text(0,0,main,cex=cex.text,pos=4)
}
if(asb) add.scale.bar()
pos_phylo <- get_edge()
xpos <- pos_phylo[x$placement_positions$location,1] + x$placement_positions$distal_bl
ypos <- pos_phylo[x$placement_positions$location,2]
order_ploting <- order(cex_placement,decreasing=TRUE)
points(xpos[order_ploting],ypos[order_ploting],col=paste(vcol[order_ploting],transp,sep=""),cex=cex_placement[order_ploting],pch=pch)
if(add) warnings("Placement dots color may not be accurate. It is highly recommanded to use a single color when using the 'add' option. Placement dot size will be comparable between plots only if the same value is used in the 'transfo' option.")
}
}
plot.jplace <- function(x,...){
if(ncol(x$placement_positions)==7) colnames(x$placement_positions) <- c("placement_id","location","ml_ratio","log_like","distal_bl","pendant_bl","tax_id")
if(ncol(x$placement_positions)==6) colnames(x$placement_positions) <- c("placement_id","location","ml_ratio","log_like","distal_bl","pendant_bl")
plot.pplace(x,...)
} |
test_that("plotLearnerPrediction", {
requirePackagesOrSkip("clusterSim", default.method = "load")
gs = 10
plotLearnerPrediction("classif.rpart", multiclass.task, gridsize = gs)
suppressMessages(ggsave(tempfile(fileext = ".png")))
plotLearnerPrediction("classif.rpart", multiclass.task, gridsize = gs, err.mark = "none")
suppressMessages(ggsave(tempfile(fileext = ".png")))
plotLearnerPrediction("classif.rpart", binaryclass.task, gridsize = gs)
suppressMessages(ggsave(tempfile(fileext = ".png")))
plotLearnerPrediction("classif.rpart", binaryclass.task, gridsize = gs, err.mark = "none")
suppressMessages(ggsave(tempfile(fileext = ".png")))
plotLearnerPrediction("regr.rpart", regr.task, gridsize = gs)
suppressMessages(ggsave(tempfile(fileext = ".png")))
plotLearnerPrediction("regr.lm", regr.task,
features = getTaskFeatureNames(regr.task)[1], gridsize = gs)
suppressMessages(ggsave(tempfile(fileext = ".png")))
plotLearnerPrediction("cluster.kmeans", noclass.task, gridsize = gs)
suppressMessages(ggsave(tempfile(fileext = ".png")))
lrn = makeLearner("classif.rpart")
plotLearnerPrediction(lrn, multiclass.task)
dir = tempdir()
path = file.path(dir, "test.svg")
suppressMessages(ggsave(path))
doc = XML::xmlParse(path)
testDocForStrings(doc, getLearnerShortName(lrn))
plotLearnerPrediction(lrn, multiclass.task, pretty.names = FALSE)
dir = tempdir()
path = file.path(dir, "test.svg")
suppressMessages(ggsave(path))
doc = XML::xmlParse(path)
testDocForStrings(doc, getLearnerId(lrn))
}) |
args <- commandArgs(TRUE)
chooseCRANmirror(ind = args[2])
number.defaults = as.numeric(args[3])
defauls = if(number.defaults>0){
args[4:(3+number.defaults)]
}
additional = if((length(args)-3-number.defaults)>0){
args[(4+number.defaults):length(args)]}
setRepositories(FALSE,defauls,additional)
install.packages(args[1],dependencies = TRUE,verbose=FALSE) |
choose.auc.intervals <- function(time.conc, time.dosing,
options=list(),
single.dose.aucs=NULL) {
single.dose.aucs <- PKNCA.choose.option(name="single.dose.aucs", value=single.dose.aucs, options=options)
if (any(is.na(time.conc)))
stop("time.conc may not have any NA values")
if (any(is.na(time.dosing)))
stop("time.dosing may not have any NA values")
if (length(unique(time.dosing)) == 1) {
ret <- check.interval.specification(single.dose.aucs)
ret$start <- ret$start + unique(time.dosing)
ret$end <- ret$end + unique(time.dosing)
} else {
time.dosing <- sort(time.dosing)
time.conc <- sort(time.conc)
mask_dose_conc <- time.dosing %in% time.conc
idx.paired.dose <-
seq_len(length(time.dosing)-1)[
mask_dose_conc[-1] &
mask_dose_conc[-length(mask_dose_conc)]
]
ret <- check.interval.specification(data.frame(start=0, end=1, auclast=TRUE))[-1,]
for (n in idx.paired.dose) {
if (any(time.dosing[n] < time.conc &
time.conc < time.dosing[n+1])) {
ret <-
rbind(
ret,
check.interval.specification(
data.frame(
start=time.dosing[n],
end=time.dosing[n+1],
auclast=TRUE,
cmax=TRUE,
tmax=TRUE
)
)
)
}
}
tau <- find.tau(time.dosing)
if (!is.na(tau)) {
if ((max(time.dosing) + tau) %in% time.conc) {
ret <-
rbind(
ret,
check.interval.specification(
data.frame(
start=max(time.dosing),
end=max(time.dosing) + tau,
cmax=TRUE,
tmax=TRUE,
auclast=TRUE,
stringsAsFactors=FALSE
)
)
)
}
if ((max(time.dosing) + tau) < max(time.conc)) {
ret <-
rbind(
ret,
check.interval.specification(
data.frame(
start=max(time.dosing),
end=Inf,
half.life=TRUE
)
)
)
}
}
}
ret
}
find.tau <- function(x, na.action=stats::na.omit,
options=list(),
tau.choices=NULL) {
tau.choices <- PKNCA.choose.option(name="tau.choices", value=tau.choices, options=options)
ret <- NA
x <- na.action(x)
if (length(unique(x)) == 1) {
ret <- 0
} else if (identical(tau.choices, NA)) {
all_deltas <-
sort(unique(
as.vector(sapply(x, FUN=function(x, y) x - y, y=x))
))
tau.choices <- all_deltas[all_deltas > 0]
}
if (is.na(ret) &
length(x) > 1) {
delta_1 <- x[2] - x[1]
if (all((x[-1] - x[-length(x)]) == delta_1)) {
ret <- delta_1
} else {
tau.choices <- tau.choices[tau.choices < (max(x) - min(x))]
tau.choices <- sort(tau.choices)
i <- 0
while (is.na(ret) & i < length(tau.choices)) {
i <- i+1
tau <- tau.choices[i]
dose_before <- ((x - tau < 0) | ((x - tau) %in% x))
dose_after <- ((x + tau > max(x)) | ((x + tau) %in% x))
if (all(dose_before & dose_after)) {
ret <- tau
}
}
}
}
ret
} |
getExtraPackages = function(mode) {
switch(mode,
MODE_MPI = "Rmpi",
MODE_BATCHJOBS = "BatchJobs",
MODE_BATCHTOOLS = "batchtools",
character(0L)
)
} |
ablrtest <- function(z, H, A, r){
if(!(class(z)=="ca.jo")){
stop("\nPlease, provide object of class 'ca.jo' as 'z'.\n")
}
r <- as.integer(r)
A <- as.matrix(A)
H <- as.matrix(H)
if(!(nrow(A)==z@P)){
stop("\nRow number of 'A' is unequal to VAR order.\n")
}
if(r >= z@P || r<1){
stop("\nCount of cointegrating relationships is out of allowable range.\n")
}
if(z@ecdet == "none"){
P <- z@P
}else{
P <- z@P + 1
}
if(!(nrow(H)==P)){
stop("\nRow number of 'H' is unequal to VAR order.\n")
}
type <- "Estimation and testing under linear restrictions on alpha and beta"
N <- nrow(z@Z0)
B <- qr.Q(qr(A), complete=TRUE)[,-c(1:ncol(A))]
M00 <- crossprod(z@Z0)/N
M11 <- crossprod(z@Z1)/N
MKK <- crossprod(z@ZK)/N
M01 <- crossprod(z@Z0, z@Z1)/N
M0K <- crossprod(z@Z0, z@ZK)/N
MK0 <- crossprod(z@ZK, z@Z0)/N
M10 <- crossprod(z@Z1, z@Z0)/N
M1K <- crossprod(z@Z1, z@ZK)/N
MK1 <- crossprod(z@ZK, z@Z1)/N
M11inv <- solve(M11)
S00 <- M00 - M01%*%M11inv%*%M10
S0K <- M0K - M01%*%M11inv%*%M1K
SK0 <- MK0 - MK1%*%M11inv%*%M10
SKK <- MKK - MK1%*%M11inv%*%M1K
Sab <- t(A)%*%S00%*%B
Skb <- t(S0K)%*%B
Sbb <- t(B)%*%S00%*%B
Sbbinv <- solve(Sbb)
RA <- z@R0%*%A - z@R0%*%B%*%Sbbinv%*%t(Sab)
RK <- z@RK - z@R0%*%B%*%Sbbinv%*%t(Skb)
Saa.b <- crossprod(RA, RA)/N
Sak.b <- crossprod(RA, RK)/N
Ska.b <- crossprod(RK, RA)/N
Skk.b <- crossprod(RK, RK)/N
Ctemp <- chol(t(H)%*%Skk.b%*%H, pivot=TRUE)
pivot <- attr(Ctemp, "pivot")
oo <- order(pivot)
C <- t(Ctemp[,oo])
Cinv <- solve(C)
Saa.binv <- solve(Saa.b)
valeigen <- eigen(Cinv%*%t(H)%*%Ska.b%*%Saa.binv%*%Sak.b%*%H%*%t(Cinv))
lambda.res <- valeigen$values
e <- valeigen$vector
V <- H%*%t(Cinv)%*%e
Vorg <- V
idx <- 1:r
V <- sapply(idx, function(x) V[ , x] / V[1,x])
PHI <- solve(t(A)%*%A)%*%Sak.b%*%Vorg
ALPHA <- as.matrix(A%*%PHI)
ALPHAorg <- ALPHA
ALPHA <- sapply(idx, function(x) ALPHA[ , x] * Vorg[1,x])
PI <- ALPHA %*% t(V)
GAMMA <- M01%*%M11inv - PI%*%MK1%*%M11inv
DELTA.bb <- Sbb
DELTA.ab <- Sab - t(A)%*%ALPHA%*%t(V)%*%Skb
DELTA.aa.b <- Saa.b - t(A)%*%ALPHA%*%t(ALPHA)%*%A
lambda <- z@lambda
teststat <- N*sum(log((1-lambda.res[1:r])/(1-lambda[1:r])))
df <- r*(z@P - ncol(A)) + r*(z@P - ncol(H))
pval <- c(1-pchisq(teststat, df), df)
new("cajo.test", Z0=z@Z0, Z1=z@Z1, ZK=z@ZK, ecdet=z@ecdet, H=H, A=A, B=B, type=type, teststat=teststat, pval=pval, lambda=lambda.res, Vorg=Vorg, V=V, W=ALPHA, PI=PI, DELTA=NULL, DELTA.bb=DELTA.bb, DELTA.ab=DELTA.ab, DELTA.aa.b=DELTA.aa.b, GAMMA=GAMMA, test.name="Johansen-Procedure")
} |
getD3dSparse <- function (dim1, dim2, dim3) {
D1 = bandSparse(dim1 * dim2 * dim3, m = dim1 * dim2 * dim3, k = c(0, 1),
diagonals = list(rep(-1, dim1 * dim2 * dim3),
rep(1, dim1 * dim2 * dim3 - 1)))
D2 = bandSparse(dim1 * dim2 * dim3 , m = dim1 * dim2 * dim3,
k = c(0, dim1),
diagonals = list(rep(-1, dim1 * dim2 * dim3),
rep(1, dim1 * dim2 * dim3 - 1)))
D3 = bandSparse(dim1 * dim2 * dim3 , m = dim1 * dim2 * dim3,
k = c(0, dim1 * dim2),
diagonals = list(rep(-1, dim1 * dim2 * dim3),
rep(1, dim1 * dim2 * dim3 - 1)))
D <- rbind(D1, D2, D3)
D1 <- D[-c(which(rowSums(D) != 0)),]
return(D1)
} |
tenant <- Sys.getenv("AZ_TEST_TENANT_ID")
app <- Sys.getenv("AZ_TEST_NATIVE_APP_ID")
site_url <- Sys.getenv("AZ_TEST_SHAREPOINT_SITE_URL")
site_id <- Sys.getenv("AZ_TEST_SHAREPOINT_SITE_ID")
if(tenant == "" || app == "" || site_url == "" || site_id == "")
skip("SharePoint tests skipped: Microsoft Graph credentials not set")
if(!interactive())
skip("Planner tests skipped: must be in interactive session")
tok <- get_test_token(tenant, app, c("Group.ReadWrite.All", "Directory.Read.All",
"Sites.ReadWrite.All", "Sites.Manage.All"))
if(is.null(tok))
skip("Planner tests skipped: no access to tenant")
site <- try(call_graph_endpoint(tok, file.path("sites", site_id)), silent=TRUE)
if(inherits(site, "try-error"))
skip("Planner tests skipped: service not available")
site <- ms_site$new(tok, tenant, site)
test_that("Planner methods work",
{
expect_is(site, "ms_site")
grp <- site$get_group()
plans <- grp$list_plans()
expect_is(plans, "list")
expect_true(all(sapply(plans, inherits, "ms_plan")))
plan_title <- plans[[1]]$properties$title
expect_error(lstpager <- grp$list_plans(filter=sprintf("title eq '%s'", filter_esc(plan_title)), n=NULL))
plan1 <- grp$get_plan(plan_title=plan_title)
expect_is(plan1, "ms_plan")
bkts <- plan1$list_buckets()
expect_is(bkts, "list")
expect_true(all(sapply(bkts, inherits, "ms_plan_bucket")))
tasks <- plan1$list_tasks()
expect_is(tasks, "list")
expect_true(all(sapply(tasks, inherits, "ms_plan_task")))
}) |
tuv_batch=function(df, inputMode=0, outputMode=2, nStreams=-2){
df=data.frame(df)
df$date=format(as.Date(df[,1]), "%Y%m%d")
df$timeStamp=as.character(format(df[,1], "%H:%M:%S"))
df$time=hour(df[,1])+minute(df[,1])/60+second(df[,1])/3600
if(outputMode==2|outputMode==4){
allpara=c(280, 420, 140, 0, 0, 0, 300, 0.1, 0, 0, 0.00, 4.00, 5.00, 0.235, 0.990, 1.000, 1.0, 1.0, 1.0)
}else{
allpara=c(280, 420, 140, 0, 0, 0, 300, 0.1, 0, 0, 0.00, 4.00, 5.00, 0.235, 0.990, 1.000, 1.0, 1.0, 0.0)
}
names(allpara)=c("wStart", "wStop", "wIntervals", "latitude", "longitude", "zenith", "ozone", "albedo", "gAltitude", "mAltitude", "taucld", "zbase", "ztop", "tauaer", "ssaaer", "alpha", "dirsun", "difdn", "difup")
if(any(!allpara%in%names(df))){
for(i in names(allpara)[!names(allpara)%in%names(df)]){
eval(parse(text=paste0("df$'", i, "'=allpara[['", i, "']]")))
}
}
df$"inputMode"=inputMode
df$"outputMode"=outputMode
df$"nStreams"=nStreams
print("Running TUV on the inputs:")
progress_bar = txtProgressBar(min=0, max=nrow(df)+1, style = 3, char="=")
wStart=df$wStart[1]
wStop=df$wStop[1]
wIntervals=df$wIntervals[1]
inputMode=df$inputMode[1]
latitude=df$latitude[1]
longitude=df$longitude[1]
date=df$date[1]
timeStamp=df$timeStamp[1]
zenith=df$zenith[1]
ozone=df$ozone[1]
albedo=df$albedo[1]
gAltitude=df$gAltitude[1]
mAltitude=df$mAltitude[1]
taucld=df$taucld[1]
zbase=df$zbase[1]
ztop=df$ztop[1]
tauaer=df$tauaer[1]
ssaaer=df$ssaaer[1]
alpha=df$alpha[1]
time=df$time[1]
outputMode=df$outputMode[1]
nStreams=df$nStreams[1]
dirsun=df$dirsun[1]
difdn=df$difdn[1]
difup=df$difup[1]
final_df=tuv_core(wStart=wStart, wStop=wStop, wIntervals=wIntervals, inputMode=inputMode, latitude=latitude, longitude=longitude, date=date, timeStamp=timeStamp, zenith=zenith, ozone=ozone, albedo=albedo, gAltitude=gAltitude, mAltitude=mAltitude, taucld=taucld, zbase=zbase, ztop=ztop, tauaer=tauaer, ssaaer=ssaaer, alpha=alpha, time=time, outputMode=outputMode, nStreams=nStreams, dirsun=dirsun, difdn=difdn, difup=difup)
setTxtProgressBar(progress_bar, value = 1)
if(nrow(df)>1){
for(i in 2:nrow(df)){
wStart=df$wStart[i]
wStop=df$wStop[i]
wIntervals=df$wIntervals[i]
inputMode=df$inputMode[i]
latitude=df$latitude[i]
longitude=df$longitude[i]
date=df$date[i]
timeStamp=df$timeStamp[i]
zenith=df$zenith[i]
ozone=df$ozone[i]
albedo=df$albedo[i]
gAltitude=df$gAltitude[i]
mAltitude=df$mAltitude[i]
taucld=df$taucld[i]
zbase=df$zbase[i]
ztop=df$ztop[i]
tauaer=df$tauaer[i]
ssaaer=df$ssaaer[i]
alpha=df$alpha[i]
time=df$time[i]
outputMode=df$outputMode[i]
nStreams=df$nStreams[i]
dirsun=df$dirsun[i]
difdn=df$difdn[i]
difup=df$difup[i]
final_df_sub=tuv_core(wStart=wStart, wStop=wStop, wIntervals=wIntervals, inputMode=inputMode, latitude=latitude, longitude=longitude, date=date, timeStamp=timeStamp, zenith=zenith, ozone=ozone, albedo=albedo, gAltitude=gAltitude, mAltitude=mAltitude, taucld=taucld, zbase=zbase, ztop=ztop, tauaer=tauaer, ssaaer=ssaaer, alpha=alpha, time=time, outputMode=outputMode, nStreams=nStreams, dirsun=dirsun, difdn=difdn, difup=difup)
final_df=rbind(final_df, final_df_sub)
setTxtProgressBar(progress_bar, value = i)
}
}
if(outputMode==2){
info=rep("1/sec",nrow(final_df))
final_df2=cbind(info,final_df)
final_df3=cbind(df[,1],final_df2)
names(final_df3)[c(1,2)]=c(names(df)[1],"PHOTOLYSIS RATES")
}else if(outputMode==3){
info=rep("W m-2",nrow(final_df))
final_df2=cbind(info,final_df)
final_df3=cbind(df[,1],final_df2)
names(final_df3)[c(1,2)]=c(names(df)[1],"WEIGHTED IRRADIANCES")
}else if(outputMode==4){
info=rep("photons/sec/nm/cm2",nrow(final_df))
final_df2=cbind(info,final_df)
final_df3=cbind(rep(df[,1], each=140),final_df2)
names(final_df3)[c(1,2)]=c(names(df)[1],"ACTINIC FLUX")
}else if(outputMode==5){
info=rep("W m-2 nm-1",nrow(final_df))
final_df2=cbind(info,final_df)
final_df3=cbind(rep(df[,1], each=140),final_df2)
names(final_df3)[c(1,2)]=c(names(df)[1],"SPECTRAL IRRADIANCE")
}
setTxtProgressBar(progress_bar, value = nrow(df)+1)
close(progress_bar)
return(final_df3)
} |
cor_test <- function(..., formula = NULL, iter = 5e3){
Y_groups <- list(...)
groups <- length(Y_groups)
if(is.null(formula)){
formula <- ~ 1
}
model_matrices <- lapply(seq_len(groups) , function(x) {
model.matrix(formula, Y_groups[[x]])
})
correlate <- remove_predictors_helper(Y_groups = Y_groups, formula)
YXlist <- lapply(1:length(model_matrices),function(g){
list(as.matrix(correlate[[g]]),as.matrix(model_matrices[[g]]))
})
numG <- length(YXlist)
P <- ncol(YXlist[[1]][[1]])
K <- ncol(YXlist[[1]][[2]])
numcorr <- numG*P*(P-1)/2
ngroups <- unlist(lapply(1:numG,function(g){nrow(YXlist[[g]][[1]])}))
Ntot <- max(ngroups)
Ygroups <- array(0,dim=c(numG,Ntot,P))
Xgroups <- array(0,dim=c(numG,Ntot,K))
XtXi <- array(0,dim=c(numG,K,K))
BHat <- array(0,dim=c(numG,K,P))
sdHat <- matrix(0,nrow=numG,ncol=P)
CHat <- array(0,dim=c(numG,P,P))
SumSq <- array(0,dim=c(numG,P,P))
SumSqInv <- array(0,dim=c(numG,P,P))
for(g in 1:numG){
Y_g <- scale(YXlist[[g]][[1]])
X_g <- YXlist[[g]][[2]]
Ygroups[g,1:ngroups[g],] <- Y_g
tableX <- apply(X_g,2,table)
catX <- unlist(lapply(1:length(tableX),function(xcol){
length(tableX[[xcol]])
}))
if(sum(catX>1)){
X_g[1:ngroups[g],which(catX>1)] <- apply(as.matrix(X_g[1:ngroups[g],which(catX>1)]),2,scale)
}
Xgroups[g,1:ngroups[g],] <- X_g
XtXi[g,,] <- solve(t(X_g)%*%X_g)
BHat[g,,] <- XtXi[g,,]%*%t(X_g)%*%Y_g
SumSq[g,,] <- t(Y_g - X_g%*%BHat[g,,])%*%(Y_g - X_g%*%BHat[g,,])
SumSqInv[g,,] <- solve(SumSq[g,,])
Sigma_g <- SumSq[g,,]/ngroups[g]
sdHat[g,] <- sqrt(diag(Sigma_g))
CHat[g,,] <- diag(1/sdHat[g,])%*%Sigma_g%*%diag(1/sdHat[g,])
}
samsize0 <- iter
res <-.Fortran("estimate_postmeancov_fisherz",
postZmean=matrix(0,numcorr,1),
postZcov=matrix(0,numcorr,numcorr),
P=as.integer(P),
numcorr=as.integer(numcorr),
K=as.integer(K),
numG=as.integer(numG),
BHat=BHat,
sdHat=sdHat,
CHat=CHat,
XtXi=XtXi,
samsize0=as.integer(samsize0),
Njs=as.integer(ngroups),
Ygroups=Ygroups,
Xgroups=Xgroups,
Ntot=as.integer(Ntot),
C_quantiles=array(0,dim=c(numG,P,P,3)),
sigma_quantiles=array(0,dim=c(numG,P,3)),
B_quantiles=array(0,dim=c(numG,K,P,3)),
BDrawsStore=array(0,dim=c(samsize0,numG,K,P)),
sigmaDrawsStore=array(0,dim=c(samsize0,numG,P)),
CDrawsStore=array(0,dim=c(samsize0,numG,P,P)),
seed=as.integer( sample.int(1e6,1) ))
varnames <- lapply(1:numG,function(g){
names(correlate[[g]])
})
corrnames <- lapply(1:numG,function(g){
matrix(unlist(lapply(1:P,function(p2){
unlist(lapply(1:P,function(p1){
if(numG==1){
paste0(varnames[[g]][p1],"_with_",varnames[[g]][p2])
}else{
paste0(varnames[[g]][p1],"_with_",varnames[[g]][p2],"_in_g",as.character(g))
}
}))
})),nrow=P)
})
FmeansCovCorr <- lapply(1:numG,function(g){
Fdraws_g <- FisherZ(t(matrix(unlist(lapply(1:samsize0,function(s){
res$CDrawsStore[s,g,,][lower.tri(diag(P))]
})),ncol=samsize0)))
mean_g <- apply(Fdraws_g,2,mean)
names(mean_g) <- corrnames[[g]][lower.tri(diag(P))]
covm_g <- cov(Fdraws_g)
return(list(mean_g,covm_g))
})
meansCovCorr <- lapply(1:numG,function(g){
matcor_g <- unlist(lapply(1:(P-1),function(p2){
unlist(lapply((p2+1):P,function(p1){
mean(res$CDrawsStore[,g,p1,p2])
}))
}))
names(matcor_g) <- corrnames[[g]][lower.tri(diag(P))]
return(matcor_g)
})
meanN <- unlist(lapply(1:numG,function(g){
FmeansCovCorr[[g]][[1]]
}))
covmN <- matrix(0,nrow=numcorr,ncol=numcorr)
numcorrg <- numcorr/numG
corrdraws <- lapply(1:numG,function(g){
array_g <- res$CDrawsStore[,g,,]
dimnames(array_g) <- list(NULL,varnames[[g]],varnames[[g]])
return(array_g)
})
for(g in 1:numG){
covmN[(g-1)*numcorrg+1:numcorrg,(g-1)*numcorrg+1:numcorrg] <- FmeansCovCorr[[g]][[2]]
}
postestimates_correlations <- Reduce(rbind,
lapply(1:numG,function(g){
means <- meansCovCorr[[g]]
medians <- res$C_quantiles[g,,,2][lower.tri(diag(P))]
lb <- res$C_quantiles[g,,,1][lower.tri(diag(P))]
ub <- res$C_quantiles[g,,,3][lower.tri(diag(P))]
return(cbind(means,medians,lb,ub))
}))
colnames(postestimates_correlations) <- c("mean","median","2.5%","97.5%")
cor_out <- list(meanF=meanN,covmF=covmN,correstimates=postestimates_correlations,
corrdraws=corrdraws,corrnames=corrnames,variables=varnames)
class(cor_out) <- "cor_test"
return(cor_out)
}
remove_predictors_helper <- function(Y_groups, formula){
groups <- length(Y_groups)
mm_terms <- attr(terms(formula), "term.labels")
if(length(mm_terms) == 0){
Y_groups
} else {
lapply(seq_len(groups), function(x){
factor_pred <- which(paste0("as.factor(", colnames(Y_groups[[x]]), ")") %in% mm_terms)
cont_pred <- which(colnames(Y_groups[[x]]) %in% mm_terms)
Y_groups[[x]][,-c(factor_pred, cont_pred)]
})
}
}
FisherZ <- function(r){.5*log((1+r)/(1-r))}
BF.cor_test <- function(x,
hypothesis = NULL,
prior.hyp = NULL,
complement = TRUE,
...){
bayesfactor <- "Bayes factors based on joint uniform priors"
testedparameter <- "correlation coefficients"
P <- dim(x$corrdraws[[1]])[2]
numG <- length(x$corrdraws)
numcorrgroup <- P*(P-1)/2
get_est <- get_estimates(x)
corrmeanN <- get_est$estimate
corrcovmN <- get_est$Sigma[[1]]
drawsJU <- draw_ju_r(P,samsize=50000,Fisher=1)
relcomp0 <- approxfun(density(drawsJU[,1]))(0)
corr_names <- rownames(x$correstimates)
numcorr <- length(corrmeanN)
relfit <- matrix(c(dnorm(0,mean=corrmeanN,sd=sqrt(diag(corrcovmN))),
pnorm(0,mean=corrmeanN,sd=sqrt(diag(corrcovmN))),
1-pnorm(0,mean=corrmeanN,sd=sqrt(diag(corrcovmN)))),ncol=3)
relcomp <- matrix(c(rep(relcomp0,numcorr),rep(.5,numcorr*2)),ncol=3)
colnames(relcomp) <- colnames(relfit) <- c("p(=0)","Pr(<0)","Pr(>0)")
BFtu_exploratory <- relfit / relcomp
row.names(BFtu_exploratory) <- rownames(x$correstimates)
colnames(BFtu_exploratory) <- c("Pr(=0)","Pr(<0)","Pr(>0)")
PHP_exploratory <- round(BFtu_exploratory /
apply(BFtu_exploratory,1,sum),3)
postestimates <- x$correstimates
if(!is.null(hypothesis)){
params_in_hyp1 <- params_in_hyp(hypothesis)
corr_names <- unlist(lapply(1:length(x$corrnames),function(g){
c(x$corrnames[[g]][lower.tri(x$corrnames[[g]])],
t(x$corrnames[[g]])[lower.tri(x$corrnames[[g]])])
}))
parse_hyp <- parse_hypothesis(corr_names,hypothesis)
parse_hyp$hyp_mat <- do.call(rbind, parse_hyp$hyp_mat)
if(nrow(parse_hyp$hyp_mat)==1){
select1 <- rep(1:numcorrgroup,numG) + rep((0:(numG-1))*2*numcorrgroup,each=numcorrgroup)
select2 <- rep(numcorrgroup+1:numcorrgroup,numG) + rep((0:(numG-1))*2*numcorrgroup,each=numcorrgroup)
parse_hyp$hyp_mat <-
t(as.matrix(c(parse_hyp$hyp_mat[,select1] + parse_hyp$hyp_mat[,select2],parse_hyp$hyp_mat[,numcorrgroup*2*numG+1])))
}else{
select1 <- rep(1:numcorrgroup,numG) + rep((0:(numG-1))*2*numcorrgroup,each=numcorrgroup)
select2 <- rep(numcorrgroup+1:numcorrgroup,numG) + rep((0:(numG-1))*2*numcorrgroup,each=numcorrgroup)
parse_hyp$hyp_mat <-
cbind(parse_hyp$hyp_mat[,select1] + parse_hyp$hyp_mat[,select2],parse_hyp$hyp_mat[,numcorrgroup*2*numG+1])
}
RrList <- make_RrList2(parse_hyp)
RrE <- RrList[[1]]
RrO <- RrList[[2]]
numhyp <- length(RrE)
relfit <- t(matrix(unlist(lapply(1:numhyp,function(h){
Gaussian_measures(corrmeanN,corrcovmN,RrE1=RrE[[h]],RrO1=RrO[[h]])
})),nrow=2))
relcomp <- t(matrix(unlist(lapply(1:numhyp,function(h){
jointuniform_measures(P,numcorrgroup,numG,RrE1=RrE[[h]],RrO1=RrO[[h]],Fisher=1)
})),nrow=2))
row.names(relfit) <- row.names(relcomp) <- parse_hyp$original_hypothesis
if(complement == TRUE){
relfit <- Gaussian_prob_Hc(corrmeanN,corrcovmN,relfit,RrO)
relcomp <- jointuniform_prob_Hc(P,numcorrgroup,numG,relcomp,RrO)
}
hypothesisshort <- unlist(lapply(1:nrow(relfit),function(h) paste0("H",as.character(h))))
row.names(relfit) <- row.names(relfit) <- hypothesisshort
BFtu_confirmatory <- c(apply(relfit / relcomp, 1, prod))
if(is.null(prior.hyp)){
priorprobs <- rep(1/length(BFtu_confirmatory),length(BFtu_confirmatory))
}else{
if(!is.numeric(prior.hyp) || length(prior.hyp)!=length(BFtu_confirmatory)){
warning(paste0("Argument 'prior.hyp' should be numeric and of length ",as.character(length(BFtu_confirmatory)),". Equal prior probabilities are used."))
priorprobs <- rep(1/length(BFtu_confirmatory),length(BFtu_confirmatory))
}else{
priorprobs <- prior.hyp
}
}
names(priorprobs) <- names(BFtu_confirmatory)
PHP_confirmatory <- BFtu_confirmatory*priorprobs / sum(BFtu_confirmatory*priorprobs)
BFtable <- cbind(relcomp,relfit,relfit[,1]/relcomp[,1],relfit[,2]/relcomp[,2],
apply(relfit,1,prod)/apply(relcomp,1,prod),PHP_confirmatory)
row.names(BFtable) <- names(BFtu_confirmatory)
colnames(BFtable) <- c("complex=","complex>","fit=","fit>","BF=","BF>","BF","PHP")
BFmatrix_confirmatory <- matrix(rep(BFtu_confirmatory,length(BFtu_confirmatory)),ncol=length(BFtu_confirmatory))/
t(matrix(rep(BFtu_confirmatory,length(BFtu_confirmatory)),ncol=length(BFtu_confirmatory)))
diag(BFmatrix_confirmatory) <- 1
row.names(BFmatrix_confirmatory) <- colnames(BFmatrix_confirmatory) <- names(BFtu_confirmatory)
if(nrow(relfit)==length(parse_hyp$original_hypothesis)){
hypotheses <- parse_hyp$original_hypothesis
}else{
hypotheses <- c(parse_hyp$original_hypothesis,"complement")
}
}else{
BFtu_confirmatory <- PHP_confirmatory <- BFmatrix_confirmatory <- relfit <-
relcomp <- hypotheses <- BFtable <- priorprobs <- NULL
}
BFcorr_out <- list(
BFtu_exploratory=BFtu_exploratory,
PHP_exploratory=PHP_exploratory,
BFtu_confirmatory=BFtu_confirmatory,
PHP_confirmatory=PHP_confirmatory,
BFmatrix_confirmatory=BFmatrix_confirmatory,
BFtable_confirmatory=BFtable,
prior.hyp=priorprobs,
hypotheses=hypotheses,
estimates=postestimates,
model=x,
bayesfactor=bayesfactor,
parameter=testedparameter,
call=match.call())
class(BFcorr_out) <- "BF"
return(BFcorr_out)
} |
wrap_html <- function(x, opts_list, type = "html", class = NULL){
span_string <- stringr::str_c(names(opts_list), opts_list, sep = ":") %>%
stringr::str_c(collapse = ";")
span_style_string <- if (nzchar(span_string)) {
glue::glue('style="{span_string}"')
}
span_class_string <- if (!is.null(class) && any(!is.na(class)) && any(nzchar(class))) {
class <- class[!is.na(class) & nzchar(class)]
class <- paste(class, collapse = " ")
glue::glue('class="{class}"')
}
span_attributes <- paste(c("", span_class_string, span_style_string), collapse = " ")
x <- glue::glue("<span{span_attributes}>{x}</span>")
return(x)
} |
phyloseq_to_metagenomeSeq = function(physeq, ...){
if( !taxa_are_rows(physeq) ){ physeq <- t(physeq)}
countData = round(as(otu_table(physeq), "matrix"), digits=0)
if(!is.null(sample_data(physeq,FALSE))){
ADF = AnnotatedDataFrame(data.frame(sample_data(physeq)))
} else {
ADF = NULL
}
if(!is.null(tax_table(physeq,FALSE))){
TDF = AnnotatedDataFrame(data.frame(OTUname = taxa_names(physeq),
data.frame(tax_table(physeq)),row.names = taxa_names(physeq)))
} else {
TDF = AnnotatedDataFrame(data.frame(OTUname = taxa_names(physeq),
row.names = taxa_names(physeq)))
}
if(requireNamespace("metagenomeSeq")){
mrobj = metagenomeSeq::newMRexperiment(counts = countData, phenoData = ADF, featureData = TDF,...)
if (sum(colSums(countData > 0) > 1) < ncol(countData)) {
p = suppressMessages(metagenomeSeq::cumNormStat(mrobj))
}
else {
p = suppressMessages(metagenomeSeq::cumNormStatFast(mrobj))
}
mrobj = metagenomeSeq::cumNorm(mrobj, p = p)
return(mrobj)
}
} |
cluster_execute <- function(first,
main,
last,
cluster_config,
keep_errors = TRUE,
keep_extra = FALSE,
update_switch = FALSE) {
oldwd <- getwd()
on.exit(setwd(oldwd))
handle_errors(keep_errors, "is.boolean")
handle_errors(keep_extra, "is.boolean")
handle_errors(update_switch, "is.boolean")
..first <- first
..main <- main
..last <- last
..cfg <- cluster_config
rm(first)
rm(main)
rm(last)
rm(cluster_config)
if (Sys.getenv("sim_run")=="") {
eval(..first)
..env <- environment()
..count <- 0
..sim_var <- NA
for (obj_name in ls(..env)) {
if ("sim_obj" %in% class(get(x=obj_name, envir=..env))) {
..sim_var <- obj_name
..count <- ..count + 1
}
}
if (is.na(..sim_var)) {
stop("A simulation object must be created in the `first` block")
}
if (..count>1) {
stop(paste("Multiple simulation objects were detected; only one may be",
"created in the `first` block"))
}
rm(..count)
rm(..env)
assign(x=..sim_var, value=eval(as.name(..sim_var)), envir=parent.frame(n=2))
eval(..main)
assign(x=..sim_var, value=eval(as.name(..sim_var)), envir=parent.frame(n=2))
eval(..last)
assign(x=..sim_var, value=eval(as.name(..sim_var)), envir=parent.frame(n=2))
} else {
..path_sim_obj <- "sim.rds"
..path_sim_res <- "sim_results"
if (!(Sys.getenv("sim_run") %in% c("first", "main", "last"))) {
stop(paste("The 'sim_run' environment variable must equal either",
"'first', 'main', or 'last'."))
}
}
if (Sys.getenv("sim_run")=="first") {
if (!is.null(..cfg$dir) && !dir.exists(..cfg$dir)) {
stop(paste("Directory", ..cfg$dir, "does not exist."))
}
test_file <- paste0(..path_sim_obj, '.test')
tryCatch(
expr = { saveRDS(list(a=123,b=456), file=test_file) },
error = function(e) {
stop(paste0("Directory ", ..cfg$dir, " is not writable."))
}
)
tryCatch(
expr = { x <- readRDS(file=test_file) },
error = function(e) {
stop(paste0("Directory ", ..cfg$dir, " is not readable."))
}
)
tryCatch(
expr = { unlink(test_file) },
error = function(e) {
stop(paste0("Files cannot be deleted from directory ", ..cfg$dir, "."))
}
)
if (!is.null(..cfg$dir)) setwd(..cfg$dir)
if (dir.exists(..path_sim_res)) { unlink(..path_sim_res, recursive=TRUE) }
dir.create(..path_sim_res)
..start_time <- Sys.time()
eval(..first)
..env <- environment()
..count <- 0
..sim_var <- NA
for (obj_name in ls(..env)) {
if ("sim_obj" %in% class(get(x=obj_name, envir=..env))) {
..sim_var <- obj_name
..count <- ..count + 1
}
}
if (is.na(..sim_var)) {
if (update_switch) {
stop("A simulation object must be read in the `first` block")
} else {
stop("A simulation object must be created in the `first` block")
}
}
if (..count>1) {
stop(paste("Multiple simulation objects were detected; only one may be",
"read in the `first` block"))
}
rm(..count)
rm(..env)
..sim <- eval(as.name(..sim_var))
..sim$internals$sim_var <- ..sim_var
..sim$vars$start_time <- ..start_time
..sim$config$parallel <- "cluster"
saveRDS(..sim, file=..path_sim_obj)
} else if (Sys.getenv("sim_run") %in% c("main","last")) {
if (!is.null(..cfg$dir)) setwd(..cfg$dir)
tryCatch(
..sim <- readRDS(..path_sim_obj),
warning = function(w) {
stop(paste(
"Simulation object was not found. Make sure your 'first' function",
"is not producing errors and returns a valid simulation object, and",
"that your shell commands are correct and properly sequenced."))
}
)
handle_errors(..sim, "is.sim_obj")
}
if (Sys.getenv("sim_run")=="main") {
err_reps <- list.files(path = ..path_sim_res, pattern = "e_*")
if (!(length(err_reps) > 0 & ..sim$config$stop_at_error)){
if (is.null(..cfg$tid_var) && is.null(..cfg$js)) {
stop("You must specify either 'js' or 'tid_var' in cluster_config.")
}
if (!is.null(..cfg$tid_var) && !is.null(..cfg$js)) {
warning(paste0("Both 'js' and 'tid_var' were specified in cluster_conf",
"ig; js will be ignored."))
}
if (!is.null(..cfg$tid_var)) {
tid_var <- ..cfg$tid_var
} else if (!is.null(..cfg$js)) {
..cfg$js <- tolower(..cfg$js)
if (!(..cfg$js %in% (js_support())$js_code)) {
stop(paste("cluster_config variable 'js' is invalid; for a list of",
"supported job schedulers, run js_support()"))
}
tid_var <- dplyr::case_when(
..cfg$js=="slurm" ~ "SLURM_ARRAY_TASK_ID",
..cfg$js=="ge" ~ "SGE_TASK_ID"
)
}
tid <- as.numeric(Sys.getenv(tid_var))
if (is.na(tid)) {
stop("Task ID is missing.")
}
add_to_tid <- as.numeric(Sys.getenv("sim_add_to_tid"))
if (!is.na(add_to_tid)) {
tid <- tid + add_to_tid
}
if (tid<1 || tid>..sim$vars$num_sim_total) {
stop(paste(
"Task ID is invalid; must be an integer between 1 and",
..sim$vars$num_sim_total
))
} else {
if (update_switch) {
tid <- tid + ..sim$internals$num_sim_cuml
}
..sim$internals$tid <- tid
rm(tid)
rm(add_to_tid)
for (pkg in ..sim$config$packages) {
do.call("library", list(pkg))
}
assign(..sim$internals$sim_var, ..sim)
eval(..main)
assign("..sim", eval(as.name(..sim$internals$sim_var)))
}
fmt <- paste0("%0", nchar(..sim$vars$num_sim_total), "d")
if (..sim$vars$run_state=="run, no errors") {
saveRDS(
list(
"results" = ..sim$results,
"results_complex" = ..sim$results_complex
),
paste0(..path_sim_res, "/r_",
sprintf(fmt, ..sim$internals$tid), ".rds")
)
} else if (..sim$vars$run_state=="run, all errors") {
saveRDS(
..sim$errors,
paste0(..path_sim_res, "/e_",
sprintf(fmt, ..sim$internals$tid), ".rds")
)
}
if (!is.character(..sim$warnings)) {
saveRDS(
..sim$warnings,
paste0(..path_sim_res, "/w_",
sprintf(fmt, ..sim$internals$tid), ".rds")
)
}
}
}
if (Sys.getenv("sim_run")=="last") {
err_reps <- list.files(path = ..path_sim_res, pattern = "e_*")
if (length(err_reps) > 0 & ..sim$config$stop_at_error){
unlink(paste0(..path_sim_res, "/r_*"))
} else {
files <- dir(paste0(..path_sim_res))
results_df <- NULL
results_complex <- list()
errors_df <- NULL
warnings_df <- NULL
num_new <- 0
for (file in files) {
if (substr(file,1,1)=="r") {
r <- readRDS(paste0(..path_sim_res, "/", file))
if (is.null(results_df)) {
results_df <- r$results
} else {
results_df[nrow(results_df)+1,] <- r$results
}
if (!is.na(r$results_complex)) {
results_complex[[length(results_complex)+1]] <-
r$results_complex[[1]]
}
num_new <- num_new + 1
} else if (substr(file,1,1)=="e") {
e <- readRDS(paste0(..path_sim_res, "/", file))
if (class(e)=="data.frame") {
if (is.null(errors_df)) {
errors_df <- e
} else {
errors_df[nrow(errors_df)+1,] <- e
}
}
num_new <- num_new + 1
} else if (substr(file,1,1) == "w") {
w <- readRDS(paste0(..path_sim_res, "/", file))
if (class(w)=="data.frame") {
if (is.null(warnings_df)) {
warnings_df <- w
} else {
warnings_df[nrow(warnings_df)+1,] <- w
}
}
}
}
if (identical(results_complex,list())) {
results_complex <- NA
}
if (update_switch) {
if (!is.character(..sim$results)) {
results_df <- rbind(..sim$results, results_df)
results_df <- results_df[order(results_df$sim_uid),]
}
if (!is.na(results_complex)) {
results_complex <- c(..sim$results_complex, results_complex)
}
if (!is.character(..sim$errors)) {
errors_df <- rbind(..sim$errors, errors_df)
errors_df <- errors_df[order(errors_df$sim_uid),]
}
if (!is.character(..sim$warnings)) {
warnings_df <- rbind(..sim$warnings, warnings_df)
warnings_df <- warnings_df[order(warnings_df$sim_uid),]
}
}
if (!is.null(warnings_df)) {
..sim$warnings <- warnings_df
}
else {
..sim$warnings <- "No warnings"
}
if (!is.null(results_df) && !is.null(errors_df)) {
..sim$results <- results_df
..sim$results_complex <- results_complex
..sim$errors <- errors_df
..sim$vars$run_state <- "run, some errors"
} else if (!is.null(results_df)) {
..sim$results <- results_df
..sim$results_complex <- results_complex
..sim$errors <- "No errors"
..sim$vars$run_state <- "run, no errors"
} else if (!is.null(errors_df)) {
..sim$results <- "Errors detected in 100% of simulation replicates"
..sim$errors <- errors_df
..sim$vars$run_state <- "run, all errors"
} else {
stop("An unknown error occurred.")
}
levels_grid_big <- create_levels_grid_big(..sim)
if (update_switch) {
prev_levels_grid_big <- ..sim$internals$levels_grid_big
extra_run <- dplyr::anti_join(
prev_levels_grid_big[,-which(names(prev_levels_grid_big) %in%
c("sim_uid", "level_id")),drop=F],
levels_grid_big[,-which(names(levels_grid_big) %in%
c("sim_uid", "level_id")),drop=F],
by=names(prev_levels_grid_big[,-which(names(prev_levels_grid_big) %in%
c("sim_uid", "level_id")),
drop=F])
)
if (!keep_extra & nrow(extra_run) > 0){
if (!is.character(..sim$results)){
..sim$results <- dplyr::anti_join(..sim$results,
extra_run,
by = names(extra_run))
}
if (!is.character(..sim$errors)){
..sim$errors <- dplyr::anti_join(..sim$errors,
extra_run,
by = names(extra_run))
}
if (!is.character(..sim$warnings)){
..sim$warnings <- dplyr::anti_join(..sim$warnings,
extra_run,
by = names(extra_run))
}
}
}
..sim$internals$levels_prev <- ..sim$internals$levels_shallow
..sim$internals$num_sim_prev <- ..sim$config$num_sim
..sim$internals$levels_grid_big <- levels_grid_big
if (update_switch) {
..sim$internals$update_sim <- TRUE
..sim$internals$num_sim_cuml <- ..sim$internals$num_sim_cuml + num_new
} else {
..sim$internals$num_sim_cuml <- ..sim$internals$num_sim_cuml +
..sim$vars$num_sim_total
}
for (i in 1:5){
x <- unlink(..path_sim_res, recursive=TRUE)
if (x == 0){
break
}
Sys.sleep(0.2)
}
saveRDS(..sim, file=..path_sim_obj)
for (pkg in ..sim$config$packages) {
do.call("library", list(pkg))
}
assign(..sim$internals$sim_var, ..sim)
eval(..last)
assign("..sim", eval(as.name(..sim$internals$sim_var)))
..sim$vars$end_time <- Sys.time()
..sim$vars$total_runtime <- as.numeric(
difftime(..sim$vars$end_time, ..sim$vars$start_time),
units = "secs"
)
saveRDS(..sim, file=..path_sim_obj)
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.