code
stringlengths 1
13.8M
|
---|
ConvertPed=function(ped,persons=NULL){
if(is.null(persons)) persons=ped[,1]
if(class(ped)!="data.frame") stop("First argument, ped, should be a data.frame.")
if(dim(ped)[1]!=length(unique(persons))) stop("Number of rows in ped should equal number of persons.")
ped[ped==0]=NA
gender=c("male","female")
ped2=pedigree(id=persons[ped[,1]], dadid=persons[ped[,2]], momid=persons[ped[,3]],sex=gender[ped[,4]])
if(dim(ped)[2]>5) {
datamatrix=ped[,-(1:5)]
rownames(datamatrix)=persons
}
else
datamatrix=NULL
list(ped=ped2,datamatrix=datamatrix)
} |
.onLoad <- function(libname, pkgname) {
env_pat <- Sys.getenv("OSF_PAT")
if (nzchar(env_pat)) options(osfr.pat = env_pat)
env_log <- Sys.getenv("OSF_LOG")
if (nzchar(env_log)) {
if (requireNamespace("logger", quietly = TRUE)) {
options(osfr.log = env_log)
logger::log_appender(logger::appender_file(env_log), namespace = "osfr")
logger::log_formatter(logger::formatter_sprintf, namespace = "osfr")
}
}
if (requireNamespace("dplyr", quietly = TRUE)) {
register_s3_method("dplyr", "arrange", "osf_tbl")
register_s3_method("dplyr", "filter", "osf_tbl")
register_s3_method("dplyr", "mutate", "osf_tbl")
register_s3_method("dplyr", "rename", "osf_tbl")
register_s3_method("dplyr", "select", "osf_tbl")
register_s3_method("dplyr", "slice", "osf_tbl")
}
invisible()
}
.onAttach <- function(libname, pkgname) {
if (!is.null(getOption("osfr.pat"))) {
packageStartupMessage("Automatically registered OSF personal access token")
}
if (is.null(getOption("osfr.log")) && nzchar(Sys.getenv("OSF_LOG"))) {
packageStartupMessage(
"<Logging NOT enabled: please install the logger package>"
)
}
if (!is.null(getOption("osfr.log"))) {
packageStartupMessage(
sprintf("<Logging enabled: %s>", getOption("osfr.log"))
)
}
server <- Sys.getenv("OSF_SERVER")
if (nzchar(server)) {
packageStartupMessage(
sprintf("<Testing server enabled: %s.osf.io>", tolower(server))
)
}
} |
sf_fram <-
function()
{
path_to_shp <- system.file("extdata","francemetro_2018.shp", package = "oceanis")
fram <- st_read(dsn = path_to_shp, quiet = TRUE)
names(fram) <- c("CODE","LIBGEO","SURF","geometry")
return(fram)
} |
coef.DMR <- function(object, df = NULL, ...){
if(is.null(df)){
out <- object$beta
colnames(out) <- paste("df", object$df, sep = "")
return(out)
}
if(class(df) != "numeric" & class(df) != "integer"){
stop("Error: wrong input type, df should have type numeric")
}
out <- object$beta[,ncol(object$beta) - df + 1]
return(out)
} |
AFparfrailty <- function(object, data, exposure, times, clusterid){
call <- match.call()
formula <- object$formula
npar <- length(object$est)
rownames(data) <- 1:nrow(data)
m <- model.frame(formula, data = data)
complete <- as.numeric(rownames(m))
data <- data[complete, ]
rr <- rownames(attr(terms(formula), "factors"))[1]
temp <- gregexpr(", ", rr)[[1]]
if(length(temp == 1)){
outcome <- substr(rr, temp[1] + 2, nchar(rr) - 1)
}
if(length(temp) == 2){
outcome <- substr(rr, temp[2] + 2, nchar(rr) - 1)
}
Y <- model.extract(frame = m, "response")
if(ncol(Y) == 2){
endvar <- Y[, 1]
eventvar <- Y[, 2]
}
if(ncol(Y) == 3){
endvar <- Y[, 2]
eventvar <- Y[, 3]
}
logalpha <- object$est[1]
alpha <- exp(logalpha)
logeta <- object$est[2]
eta <- exp(logeta)
logphi <- object$est[3]
phi <- exp(logphi)
beta <- object$est[(3 + 1):npar]
if(missing(times)){
times <- endvar[eventvar == 1]
}
times <- sort(times)
n <- nrow(data)
n.cases <- sum(eventvar)
n.cluster <- object$ncluster
data0 <- data
data0[, exposure] <- 0
design <- model.matrix(object = formula, data = data)[, -1, drop=FALSE]
design0 <- model.matrix(object = formula, data = data0)[, -1, drop=FALSE]
clusters <- data[, clusterid]
predX <- design %*% beta
pred0 <- design0 %*% beta
S.est <- vector(length = length(times))
S0.est <- vector(length = length(times))
AF.var <- vector(length = length(times))
S.var <- vector(length = length(times))
S0.var <- vector(length = length(times))
for (i in 1:length(times)){
t <- times[i]
H0t <- (t / alpha) ^ eta
temp <- 1 + phi * H0t * exp(predX)
temp0 <- 1 + phi * H0t * exp(pred0)
surv <- temp ^ ( - 1 / phi)
surv0 <- temp0 ^ ( - 1 / phi)
S.est[i] <- mean(surv, na.rm = TRUE)
S0.est[i] <- mean(surv0, na.rm = TRUE)
sres <- surv - S.est[i]
sres0 <- surv0 - S0.est[i]
Scores.S <- cbind(sres, sres0)
Scores.S <- aggr(x = Scores.S, clusters = clusters)
coefres <- object$score
res <- cbind(Scores.S, coefres)
meat <- var(res, na.rm = TRUE)
dS.dlogalpha <- sum(H0t * eta * exp(predX) / temp ^ (1 / phi + 1)) / n.cluster
dS.dlogeta <- sum(-H0t * exp(predX) * log(t / alpha) * eta / temp ^ (1 / phi + 1)) / n.cluster
dS.dlogphi <- sum(log(temp) / (phi * temp ^ (1 / phi)) - H0t * exp(predX) / temp ^ (1 / phi + 1)) / n.cluster
dS.dbeta <- colSums(-H0t * as.vector(exp(predX)) * design / as.vector(temp) ^ (1 / phi + 1)) / n.cluster
dS0.dlogalpha <- sum(H0t * eta * exp(pred0) / temp0 ^ (1 / phi + 1)) / n.cluster
dS0.dlogeta <- sum( - H0t * exp(pred0) * log(t / alpha) * eta / temp0 ^ (1 / phi + 1)) /n.cluster
dS0.dlogphi <- sum(log(temp0) / (phi * temp0 ^ (1 / phi)) - H0t * exp(pred0) / temp0 ^ (1 / phi + 1)) / n.cluster
dS0.dbeta <- colSums(-H0t * as.vector(exp(pred0)) * design0 / as.vector(temp0) ^ (1 / phi + 1)) / n.cluster
S.hessian <- cbind(-diag(2) * n / n.cluster, rbind(dS.dlogalpha, dS0.dlogalpha), rbind(dS.dlogeta, dS0.dlogeta),
rbind(dS.dlogphi, dS0.dlogphi), rbind(dS.dbeta, dS0.dbeta))
par.hessian <- cbind(matrix(0, nrow = npar, ncol = 2), -solve(object$vcov) / n.cluster)
bread <- rbind(S.hessian, par.hessian)
sandwich <- (solve(bread) %*% meat %*% t(solve(bread)) / n.cluster)[1:2, 1:2]
gradient <- as.matrix(c( - (1 - S0.est[i]) / (1 - S.est[i]) ^ 2, 1 / (1 - S.est[i])), nrow = 2, ncol = 1)
AF.var[i] <- t(gradient) %*% sandwich %*% gradient
S.var[i] <- sandwich[1, 1]
S0.var[i] <- sandwich[2, 2]
}
AF.est <- 1 - (1 - S0.est) / (1 - S.est)
out <- c(list(AF.est = AF.est, AF.var = AF.var, S.est = S.est,
S0.est = S0.est, S.var = S.var, S0.var = S0.var,
objectcall = object$call, call = call, exposure = exposure, outcome = outcome, object = object,
sandwich = sandwich, gradient = gradient, formula = formula,
n = n, n.cases = n.cases, n.cluster = n.cluster, times = times))
class(out) <- "AF"
return(out)
} |
test_that("we can catch invalid lambda configs", {
expect_true(validate_lambda_config(basic_lambda_config()))
expected_error <- paste0(
"The Lambda runtime configuration should be provided by the ",
"lambda_config function."
)
expect_error(
validate_lambda_config(list()),
expected_error
)
})
test_that("Defaults in setup are considered after environment variables ", {
expect_error(
get_lambda_environment_variable("doesntexist"),
"doesntexist environment variable is not set"
)
expect_equal(
get_lambda_environment_variable("doesntexist", default = "red panda"),
"red panda"
)
expect_equal(
withr::with_envvar(
c("doesntexist" = "giraffe"),
get_lambda_environment_variable("doesntexist", default = "red panda")
),
"giraffe"
)
})
test_that("Lambda config retrieved from environment variable", {
config <- withr::with_envvar(
c(
"AWS_LAMBDA_RUNTIME_API" = "red_panda",
"LAMBDA_TASK_ROOT" = "giraffe",
"_HANDLER" = "sqrt"
),
lambda_config()
)
expect_s3_class(config, "lambda_config")
expect_equal(config$runtime_api, "red_panda")
expect_equal(config$task_root, "giraffe")
expect_equal(config$handler, sqrt)
})
test_that("handler can be set directly without env var", {
config <- basic_lambda_config(direct_handler = sqrt)
expect_equal(config$handler, sqrt)
})
test_that("lambda config can record if Base64 is to be used for decoding", {
default_config <- basic_lambda_config()
no_base64_config <- basic_lambda_config(decode_base64 = FALSE)
base64_config <- basic_lambda_config(decode_base64 = TRUE)
expect_true(default_config$decode_base64)
expect_false(no_base64_config$decode_base64)
expect_true(base64_config$decode_base64)
})
test_that("outright error when runtime_api not provided", {
expected_error <- paste(
"AWS_LAMBDA_RUNTIME_API environment variable is not set. This environment",
"variable is set by AWS when Lambda is instantiated. It will not appear",
"when running local tests."
)
expect_error(
basic_lambda_config(runtime_api = ""),
expected_error
)
})
test_that("initialisation error recorded when handler undefined", {
error_received <- trigger_initialisation_error(
expected_error = paste0(
"The _HANDLER environment variable is undefined.\n",
"This environment variable is configured by AWS Lambda based\n",
"the value configured either as the Dockerfile CMD or in the\n",
"AWS Lambda console (which will always take priority).\n",
"Alternatively, pass a function to the `handler` argument\n",
"of `lambda_config`, although note that `lambda_config` will\n",
"always defer to the environment variables if available."
),
task_root = "giraffe",
handler = ""
)
expect_true(error_received)
})
test_that("undefined handlers are caught", {
handler_character <- "undefined_handler"
expected_error <- paste0(
handler_character, ", as defined by the _HANDLER environment\n",
"variable, can't be found. Check that this exists in the",
"environment passed to `lambda_config` (defaults to the parent\n",
"frame)"
)
error_received <- trigger_initialisation_error(
expected_error = expected_error,
task_root = "giraffe",
handler = handler_character
)
expect_true(error_received)
})
test_that("non-function handlers provided by env var are caught", {
error_received <- trigger_initialisation_error(
expected_error = "mtcars is not a function",
task_root = "giraffe",
handler = "mtcars"
)
expect_true(error_received)
})
test_that("non-function handlers provided directly are caught", {
error_received <- trigger_initialisation_error(
expected_error = "The handler function is not a function",
task_root = "giraffe",
direct_handler = mtcars
)
expect_true(error_received)
})
test_that("handler can be a custom function", {
plus_one <- function(x) x + 1
config <- basic_lambda_config(handler = "plus_one")
expect_equal(config$handler(1), 2)
})
test_that("can recognise context argument in function formals", {
doesnt_accept_context <- function() {}
expect_false(function_accepts_context(doesnt_accept_context))
accepts_context <- function(context) {}
expect_true(function_accepts_context(accepts_context))
})
test_that("context argument recognised in handler formals", {
no_context <- function() {}
no_context_config <- basic_lambda_config(handler = "no_context")
expect_false(no_context_config$pass_context_argument)
yes_context <- function(context) {}
yes_context_config <- basic_lambda_config(handler = "yes_context")
expect_true(yes_context_config$pass_context_argument)
})
test_that("non function custom deserialisers are caught", {
error_received <- trigger_initialisation_error(
expected_error = "custom deserialiser is not a function",
deserialiser = mtcars
)
expect_true(error_received)
})
test_that("non function custom serialisers are caught", {
error_received <- trigger_initialisation_error(
expected_error = "custom serialiser is not a function",
serialiser = mtcars
)
expect_true(error_received)
}) |
article_index <- function(package) {
if (is.null(package)) {
getOption("downlit.article_index")
} else if (devtools_loaded(package)) {
article_index_source(package)
} else {
article_index_remote(package)
}
}
article_index_source <- function(package) {
path <- file.path(find.package(package), "vignettes")
if (!file.exists(path)) {
return(character())
}
vig_path <- dir(path, pattern = "\\.[rR]md$", recursive = TRUE)
out_path <- gsub("\\.[rR]md$", ".html", vig_path)
vig_name <- gsub("\\.[rR]md$", "", basename(vig_path))
set_names(out_path, vig_name)
}
article_index_remote <- function(package) {
metadata <- remote_metadata(package)
if (!is.null(metadata) && !is.null(metadata$articles)) {
return(metadata$articles)
}
path <- system.file("Meta", "vignette.rds", package = package)
if (path == "") {
return(character())
}
meta <- readRDS(path)
name <- tools::file_path_sans_ext(meta$File)
set_names(meta$PDF, name)
}
find_article <- function(package, name) {
index <- article_index(package)
if (has_name(index, name)) {
index[[name]]
} else {
NULL
}
} |
FryObjective <-
function(object.data, n.pass = 15, pie.step = 12, expansion = 1.5, pie.pts = 1, section.name, ave.piepts = FALSE, norm = TRUE){
EllipFit <- function(dat, npts = 180){
D1 <- cbind(dat$x * dat$x, dat$x * dat$y, dat$y * dat$y)
D2 <- cbind(dat$x, dat$y, 1)
S1 <- t(D1) %*% D1
S2 <- t(D1) %*% D2
S3 <- t(D2) %*% D2
T <- -solve(S3) %*% t(S2)
M <- S1 + S2 %*% T
M <- rbind(M[3,] / 2, -M[2,], M[1,] / 2)
evec <- eigen(M)$vec
cond <- 4 * evec[1,] * evec[3,] - evec[2,]^2
a1 <- evec[, which(cond > 0)]
f <- c(a1, T %*% a1)
a <- sqrt((2 * (f[1] * (.5 *f[5])^2 + f[3] * (.5 * f[4])^2 + f[6] * (.5 * f[2])^2 - 2 * (.5 * f[2]) * (.5 * f[4]) * (.5 * f[5]) - f[1] * f[3] * f[6])) /
(((.5 * f[2])^2 - f[1] * f[3]) * (sqrt((f[1] - f[3])^2 + 4 * (.5 * f[2])^2) - (f[1] + f[3]))))
b <- sqrt((2 * (f[1] * (.5 *f[5])^2 + f[3] * (.5 * f[4])^2 + f[6] * (.5 * f[2])^2 - 2 * (.5 * f[2]) * (.5 * f[4]) * (.5 * f[5]) - f[1] * f[3] * f[6])) /
(((.5 * f[2])^2 - f[1] * f[3]) * (-1 * sqrt((f[1] - f[3])^2 + 4 * (.5 * f[2])^2) - (f[1] + f[3]))))
if(f[1] < f[3] & a > b){
angle <- .5 * atan(f[2] / (f[1] - f[3]))
}
if(f[1] > f[3] & a > b){
angle <- pi / 2 + .5 * atan(f[2] / (f[1] - f[3]))
}
if(f[1] < f[3] & a < b){
angle <- pi / 2 + .5 * atan(f[2] / (f[1] - f[3]))
}
if(f[1] > f[3] & a < b){
angle <- .5 * atan(f[2] / (f[1] - f[3]))
}
semi.maj <- ifelse(a > b, a, b)
semi.min <- ifelse(b < a, b, a)
tt <- seq(from = 0, to = 2 * pi, length = npts)
sa <- sin(angle)
ca <- cos(angle)
ct <- cos(tt)
st <- sin(tt)
x <- semi.maj * ct * ca - semi.min * st * sa
y <- semi.maj * ct * sa + semi.min * st * ca
angle <- ifelse((angle * -1) < 0 , (angle * -1) + pi, (angle * -1))
my.ellipse <- list()
my.ellipse[[1]] <- c(semi.maj, semi.min)
my.ellipse[[2]] <- angle
my.ellipse[[3]] <- data.frame(x, y)
return(my.ellipse)
}
x.coords <- NULL
y.coords <- NULL
radii <- NULL
object.data$radius <- sqrt(object.data$m.area / pi)
for(j in 1:length(object.data$m.cx)){
x.coords <- c(x.coords, object.data$m.cx[j] - object.data$m.cx)
y.coords <- c(y.coords, object.data$m.cy[j] - object.data$m.cy)
radii <- c(radii, object.data$radius[j] + object.data$radius)
}
my.data <- data.frame(x.coords, y.coords, radii)
my.data <- my.data[which(my.data$x.coords != 0 & my.data$y.coords != 0),]
my.data$dist <- sqrt(my.data$x.coords^2 + my.data$y.coords^2)
if(norm){
norm.dist <- my.data$dist / my.data$radii
my.data$x.coords <- my.data$x.coords * (norm.dist / my.data$dist) * sqrt(mean(object.data$m.area)/pi)
my.data$y.coords <- my.data$y.coords * (norm.dist / my.data$dist) * sqrt(mean(object.data$m.area)/pi)
my.data$dist <- norm.dist * sqrt(mean(object.data$m.area)/pi)
}
my.data <- my.data[order(my.data$dist),]
my.data$angle <- rep(NA, times = length(my.data$x.coords))
idx <- which(my.data$x.coords > 0 & my.data$y.coords <= 0)
my.data[idx,]$angle <- abs(atan(my.data[idx,]$y.coords / my.data[idx,]$x.coords)) * (180 / pi)
idx <- which(my.data$x.coords <= 0 & my.data$y.coords < 0)
my.data[idx,]$angle <- abs(atan(my.data[idx,]$x.coords / my.data[idx,]$y.coords)) * (180 / pi) + 90
idx <- which(my.data$x.coords < 0 & my.data$y.coords >= 0)
my.data[idx,]$angle <- abs(atan(my.data[idx,]$y.coords / my.data[idx,]$x.coords)) * (180 / pi) + 180
idx <- which(my.data$x.coords >= 0 & my.data$y.coords > 0)
my.data[idx,]$angle <- abs(atan(my.data[idx,]$x.coords / my.data[idx,]$y.coords)) * (180 / pi) + 270
for(k in 1:n.pass){
x.coord <- vector()
y.coord <- vector()
min.point <- vector()
if(k == 1){
wedges <- seq(from = 0, to = 360, by = pie.step)
wedges <- wedges[-length(wedges)]
}
for(j in 1:length(wedges)){
if(j == 1){
temp.data <- my.data[which(my.data$angle <= wedges[j] | my.data$angle > wedges[length(wedges)]),]
} else{
temp.data <- my.data[which(my.data$angle <= wedges[j] & my.data$angle > wedges[j - 1]),]
}
if(ave.piepts){
x.coord <- c(x.coord, mean(temp.data$x.coords[1:(pie.pts)], na.rm = TRUE))
y.coord <- c(y.coord, mean(temp.data$y.coords[1:(pie.pts)], na.rm = TRUE))
} else{
x.coord <- c(x.coord, temp.data$x.coords[1:(pie.pts)])
y.coord <- c(y.coord, temp.data$y.coords[1:(pie.pts)])
}
min.point <- c(min.point, temp.data$dist[1])
}
dat <- data.frame(x = x.coord, y = y.coord)
dat <- dat[complete.cases(dat),]
dat <- EllipFit(dat = dat, npts = length(wedges) + 1)
node.data <- dat[[3]]
node.data$angle <- rep(NA, times = length(node.data$x))
idx <- which(node.data$x > 0 & node.data$y <= 0)
node.data[idx,]$angle <- abs(atan(node.data[idx,]$y / node.data[idx,]$x)) * (180 / pi)
idx <- which(node.data$x <= 0 & node.data$y < 0)
node.data[idx,]$angle <- abs(atan(node.data[idx,]$x / node.data[idx,]$y)) * (180 / pi) + 90
idx <- which(node.data$x < 0 & node.data$y >= 0)
node.data[idx,]$angle <- abs(atan(node.data[idx,]$y / node.data[idx,]$x)) * (180 / pi) + 180
idx <- which(node.data$x >= 0 & node.data$y > 0)
node.data[idx,]$angle <- abs(atan(node.data[idx,]$x / node.data[idx,]$y)) * (180 / pi) + 270
wedges <- sort(node.data$angle)
wedges <- wedges[-length(wedges)]
}
fry.data <- new("FRY")
fry.data@rsAxes <- c(2 * dat[[1]][1], 2 * dat[[1]][2])
fry.data@strainRatio <- dat[[1]][1] / dat[[1]][2]
fry.data@meanObjectArea <- dat[[1]][1] * dat[[1]][2] * pi
fry.data@vectorMean <- dat[[2]] * (180 / pi)
fry.data@sectionName <- section.name
fry.data@sampleSize <- length(object.data$m.cx)
fry.data@fryParams <- my.data
fry.data@voidScale <- expansion * max(min.point, na.rm = TRUE)
return(fry.data)
} |
plot.lts <- function(x, ylim = NULL, xlim = NULL, ci = T, col = 1,
ylab = NULL, xlab = "Time", add = F, ...){
object <- x
att <- attributes(object)
if(is.null(ylab)){
ylab <- switch(att$type,
surv = "Survival probability",
hazard = "Hazard",
cumhaz = "Cumulative hazard",
loghaz = "Log-hazard",
fail = "Distribution")
}
ci <- ci & att$var.type == "ci"
if(length(col) == 1){
col <- rep(col, length(object))
}
if(is.null(ylim)){
if(ci){
ylim <- range(unlist(lapply(object, function(x) x[, c("lower", "upper")])))
}else{
ylim <- range(unlist(lapply(object, function(x) x[, "Estimate"])))
}
}
for(i in 1:length(object)){
if(i == 1 & !add){
plot(Estimate ~ att$time, data = object[[i]], ylim = ylim, xlim = xlim,
type = "l", col = col[i], xlab = xlab, ylab = ylab, ...)
}else{
lines(Estimate ~ att$time, data = object[[i]], col = col[i], ...)
}
if(ci){
lines(lower ~ att$time, data = object[[i]], lty = 2, col = col[i], ...)
lines(upper ~ att$time, data = object[[i]], lty = 2, col = col[i], ...)
}
}
} |
plotSlopes <- function(model, plotx, ...) UseMethod("plotSlopes")
plotSlopes.lm <-
function (model, plotx, modx = NULL, n = 3, modxVals = NULL ,
plotxRange = NULL, interval = c("none", "confidence", "prediction"),
plotPoints = TRUE, legendPct = TRUE, legendArgs,
llwd = 2, opacity = 100, ...,
col = c("black", "blue", "darkgreen", "red", "orange", "purple", "green3"),
type = c("response", "link"), gridArgs, width = 0.2)
{
if (missing(model))
stop("plotSlopes requires a fitted regression model.")
if (missing(plotx)) stop("plotSlopes: plotx argument is required")
else if(!is.character(plotx)) plotx <-as.character(substitute(plotx))
cl <- match.call()
dotargs <- list(...)
dotnames <- names(dotargs)
level <- if (!is.null(dotargs[["level"]])) dotargs[["level"]] else 0.95
mm <- model.data(model)
plotxVar <- mm[, plotx]
ylab <- as.character(terms(model)[[2]])
interval <- match.arg(interval)
type <- match.arg(type)
if (!missing(modx)) {
zzz <- as.character(substitute(modx))
if(!is.character(modx)) modx <- as.character(substitute(modx))
}
depName <- as.character(terms(model)[[2]])
depVar <- mm[[depName]]
if(is.null(plotxRange)){
if (is.numeric(plotxVar)){
plotxRange <- range(plotxVar, na.rm = TRUE)
}
}
if (is.factor(plotxVar)){
plotxVals <- levels(droplevels(plotxVar))
} else {
plotxVals <- plotSeq(plotxRange, length.out = 40)
}
if (!(missing(modx) || is.null(modx))) {
if((missing(modxVals) || is.null(modxVals)) || (length(modxVals) == 1 && is.character(modxVals))) {
modxVar <- mm[, modx]
if (is.factor(modxVar)) {
n <- ifelse(missing(n), nlevels(modxVar), n)
modxVar <- droplevels(modxVar)
modxVals <- getFocal(modxVar, xvals = modxVals, n, pct = legendPct)
} else {
modxVals <- getFocal(modxVar, xvals = modxVals, n, pct = legendPct)
}
}
}
predVals <- list(plotxVals)
names(predVals) <- plotx
if(!is.null(modx)) {
if(is.null(modxVals)) modxVals <- "table"
TEXT <- paste0("predVals[[\"", modx, "\"]] <- modxVals")
eval(parse(text = TEXT))
}
parms.pred <- list(model, predVals = predVals, type = type, interval = interval)
validForPredict <- c("se.fit", "dispersion", "terms", "na.action",
"level", "pred.var", "weights")
dotsForPredict <- dotnames[dotnames %in% validForPredict]
if (length(dotsForPredict) > 0) {
parms.pred <- modifyList(parms.pred, dotargs[dotsForPredict])
dotargs[[dotsForPredict]] <- NULL
}
newdf <- do.call("predictOMatic", parms.pred)
plotyRange <- if(is.numeric(depVar)){
magRange(depVar, mult = c(1, 1.2))
} else {
stop(paste("plotSlopes: use plotCurves if this is a glm (logit, probit, count)"))
}
if(is.numeric(plotxVals)){
parms <- list(newdf = newdf, olddf = mm, plotx = plotx, modx = modx,
modxVals = modxVals, depName = depName,
interval = interval, level = level, plotPoints = plotPoints,
col = col, opacity = opacity, xlim = plotxRange,
ylim = plotyRange, ylab = ylab, llwd = llwd)
if(!missing(legendArgs) && !is.null(legendArgs)) parms[["legendArgs"]] <- legendArgs
parms <- modifyList(parms, dotargs)
plotret <- do.call("plotFancy", parms)
} else {
plotyRange <- magRange(range(c(newdf[["fit"]], if(!is.null(newdf[["lwr"]])) min(newdf[["lwr"]])),
if(!is.null(newdf[["upr"]])) max(newdf[["upr"]])), 1.25)
parms <- list(newdf, olddf = mm, plotx = plotx, modx = modx,
modxVals = modxVals, depName = depName,
xlim = plotxRange, interval = interval, level = level,
xlab = plotx, ylab = ylab, ylim = plotyRange,
main = "", col = col, width = width)
if(!missing(legendArgs) && !is.null(legendArgs)) parms[["legendArgs"]] <- legendArgs
if(!missing(gridArgs) && !is.null(gridArgs)) parms[["gridArgs"]] <- gridArgs
parms <- modifyList(parms, dotargs)
plotret <- do.call("plotFancyCategories", parms)
}
z <- list(call = cl, newdata = newdf, modxVals = modxVals, col = plotret$col, lty = plotret$lty, fancy = plotret)
class(z) <- c("plotSlopes", "rockchalk")
invisible(z)
}
NULL
plotFancy <-
function(newdf, olddf, plotx, modx, modxVals, interval, plotPoints,
legendArgs, col = NULL, llwd = 2, opacity, ...)
{
dotargs <- list(...)
ylab <- dotargs[["depName"]]
if (!is.null(dotargs[["ylab"]])) ylab <- dotargs[["ylab"]]
if (!is.null(dotargs[["level"]])) {
level <- dotargs[["level"]]
dotargs[["level"]] <- NULL
} else {
level <- 0.95
}
newdf <- if(is.null(modx)) newdf[order(newdf[[plotx]]), ]
else newdf[order(newdf[[plotx]], newdf[[modx]]), ]
modxVar <- if(is.null(modx)) rep(1, NROW(olddf)) else olddf[ , modx]
if(is.factor(modxVar)) modxVar <- droplevels(modxVar)
plotxVar <- olddf[ , plotx]
depVar <- olddf[ , 1]
if (missing(modx) || is.null(modx)) {
modxVals <- 1
lmx <- 1
} else {
lmx <- length(modxVals)
}
if (is.factor(modxVar)) {
modxLevels <- levels(modxVar)
} else {
modxLevels <- modxVals
if (is.null(names(modxVals))) names(modxVals) <- modxVals
}
if (is.null(col)) {
if (is.factor(modxVar)) {
col <- seq_along(modxLevels)
names(col) <- modxLevels
} else {
col <- 1:lmx
names(col) <- names(modxVals)
}
} else {
if (is.null(names(col))){
col <- rep(col, length.out = length(modxLevels))
if (is.factor(modxVar)) names(col) <- modxLevels
else names(col) <- names(modxVals)
} else if (length(col) < lmx) {
stop("plotFancy: named color vector does not match data.")
} else if (length(col) >= length(modxLevels)) {
col <- rep(col, length.out = length(modxLevels))
if (is.null(names(col))) {
names(col) <- names(modxLevels[1:length(col)])
}
}
}
col <- if (is.factor(modxVar)) col[names(col) %in% modxVals] else col[1:length(modxVals)]
modxLevels <- modxLevels[modxLevels %in% modxVals]
if (length(modxLevels) != length(modxVals)) {stop("goof")}
if (length(llwd) < length(col)) {
llwd <- rep(llwd, length.out = length(col))
}
names(llwd) <- names(col)
lty <- seq_along(col)
if (!is.null(dotargs[["lty"]])) {
lty <- rep(dotargs[["lty"]], length.out = lmx)
dotargs[["lty"]] <- NULL
}
names(lty) <- names(col)
parms <- list(x = plotxVar, y = depVar, xlab = plotx, ylab = ylab,
type = "n")
dots.plot <- dotargs[names(dotargs)[names(dotargs) %in% c(names(par()), formalArgs(plot.default))]]
parms <- modifyList(parms, dots.plot)
do.call("plot", parms)
iCol <- col2rgb(col)
bCol <- mapply(rgb, red = iCol[1,], green = iCol[2,],
blue = iCol[3,], alpha = opacity, maxColorValue = 255)
sCol <- mapply(rgb, red = iCol[1,], green = iCol[2,],
blue = iCol[3,], alpha = opacity/3, maxColorValue = 255)
if (interval != "none") {
for (j in modxVals) {
k <- match(j, modxVals)
if (is.factor(modxVar)) i <- j
else i <- k
if (missing(modx) || is.null(modx)) {
pdat <- newdf
} else {
pdat <- newdf[newdf[ , modx] %in% j, ]
}
parms <- list(x = c(pdat[, plotx], pdat[NROW(pdat):1 , plotx]),
y = c(pdat$lwr, pdat$upr[NROW(pdat):1]), lty = lty[i])
dots.plot <- dotargs[names(dotargs)[names(dotargs) %in% c(names(par()), formalArgs(polygon))]]
parms <- if(!is.null(dots.plot)) modifyList(parms, dots.plot)
parms <- modifyList(parms, list(border = bCol[i],
col = sCol[i], lwd = 0.3* llwd[k]))
do.call("polygon", parms)
}
}
for (j in modxVals) {
if (is.factor(modxVar)) i <- j
else i <- match(j, modxVals)
if (missing(modx) || is.null(modx)) {
pdat <- newdf
} else {
pdat <- newdf[newdf[ , modx] %in% j, ]
}
parms <- list(x = pdat[, plotx], y = pdat$fit, lty = lty[i])
dots.plot <- dotargs[names(dotargs)[names(dotargs) %in% c(names(par()), formalArgs(lines))]]
parms <- if(!is.null(dots.plot)) modifyList(parms, dots.plot)
parms <- modifyList(parms, list(col = col[i], lwd = llwd[i]))
do.call("lines", parms)
}
if (plotPoints) {
parms <- list(xlab = plotx, ylab = ylab,
cex = 0.6, lwd = 0.75)
if (is.factor(modxVar)) {
parms[["col"]] <- col[as.vector(modxVar[modxVar %in% modxVals])]
parms[["x"]] <- plotxVar[modxVar %in% modxVals]
parms[["y"]] <- depVar[modxVar %in% modxVals]
} else {
parms[["col"]] <- 1
parms[["x"]] <- plotxVar
parms[["y"]] <- depVar
}
dots.plot <- dotargs[names(dotargs)[names(dotargs) %in% c(names(par()), formalArgs(points))]]
parms <- if(!is.null(dots.plot)) modifyList(parms, dots.plot)
do.call("points", parms)
}
if (!missing(legendArgs) && is.character(legendArgs) && (legendArgs == "none")) {
} else if (!is.null(modx)){
if (is.factor(modxVar)){
col <- col[as.vector(modxVals)]
lty <- lty[as.vector(modxVals)]
llwd <- llwd[as.vector(modxVals)]
} else {
col <- col[names(modxVals)]
lty <- lty[names(modxVals)]
llwd <- llwd[names(modxVals)]
}
titl <- paste("Moderator:", modx)
if (is.null(names(modxVals))) {
legnd <- paste(modxVals, sep = "")
} else {
legnd <- paste(names(modxVals), sep = "")
}
legend.parms <- list(x = "topleft", legend = legnd, lty = lty, col = col,
lwd = llwd, bg = "white", title = titl)
if(!missing(legendArgs) && !is.null(legendArgs)) legend.parms <- modifyList(legend.parms, legendArgs)
do.call(legend, legend.parms)
} else {
legend.parms <- list()
legend.parms[["x"]] <- "topleft"
legend.parms[["title"]] <- "Regression analysis"
legnd <- c("Predicted values")
col <- col[1]
lty <- lty[1]
llwd <- llwd[1]
if (interval != "none") {
legnd[2] <- paste(level, interval, "interval")
col <- c(col, 0)
lty <- c(lty, 0)
llwd <- c(llwd, 0)
}
legend.parms[["legend"]] <- legnd
legend.parms[["col"]] <- col
legend.parms[["lty"]] <- lty
legend.parms[["lwd"]] <- llwd
if(!missing(legendArgs) && !is.null(legendArgs)) legend.parms <- modifyList(legend.parms, legendArgs)
do.call(legend, legend.parms)
}
invisible(list(col = col, lty = lty, lwd = llwd))
}
NULL
se.bars <- function(x, y, lwr, upr, width = 0.20, col, opacity = 120, lwd = 1, lty = 1) {
h <- min(1, 2.5 * width)
q <- min(1, width)
d <- 0.5 * width
iCol <- col2rgb(col)
bCol <- mapply(rgb, red = iCol[1,], green = iCol[2,],
blue = iCol[3,], alpha = .8 * opacity, maxColorValue = 255)
sCol <- mapply(rgb, red = iCol[1,], green = iCol[2,],
blue = iCol[3,], alpha = opacity/3, maxColorValue = 255)
lCol <- mapply(rgb, red = iCol[1,], green = iCol[2,],
blue = iCol[3,], alpha = min(255, 2*opacity), maxColorValue = 255)
if (!is.null(lwr)){
polygon(c(x-d, x+d, x+d, x-d), c(rep(lwr, 2), rep(upr, 2)), col = sCol, border = bCol)
lines(c(x, x), c(lwr, upr), col = lCol, cex=0.5, lwd = lwd, lty = lty, lend = 1, ljoin = 1)
lines(c(x, x) + c(-q, q), c(lwr, lwr), col = lCol, lwd = lwd, lty = lty, lend = 1, ljoin = 1, lmitre = 2)
lines(c(x, x) + c(-q, q), c(upr, upr), col = lCol, lwd = lwd, lty = lty, lend = 1, ljoin = 1, lmitre = 2)
}
lines(c(x, x) + c(-h, h), c(y, y), col = lCol, lwd = lwd + 1)
NULL
}
NULL
plotFancyCategories <- function(newdf, olddf, plotx, modx=NULL,
modxVals, xlab, xlim, ylab, ylim,
col = c("black", "blue", "darkgreen", "red", "orange", "purple", "green3"),
opacity = 120, main,
space=c(0,1), width = 0.2, llwd = 1, offset=0,
..., gridArgs = list(lwd = 0.3, lty = 5),
legendArgs)
{
call.orig <- match.call()
dotargs <- list(...)
dotnames <- names(dotargs)
lty <- if("lty" %in% dotnames) dotargs[["lty"]] else 1
interval <- if("interval" %in% dotnames) dotargs[["interval"]] else "none"
plotxval <- newdf[[plotx]]
plotxVals <- levels(plotxval)
if(is.null(modx)){
modxVals <- 1
}
if(!is.null(modx)){
if(is.null(names(modxVals))) names(modxVals) <- as.character(modxVals)
if(is.factor(modxVals)){
modxVal.names <- names(modxVals)
names(modxVal.names) <- modxVals
modxVal.names <- modxVal.names[levels(newdf[[modx]])]
modxVals <- names(modxVal.names)
names(modxVals) <- modxVal.names
modx.levels <- modxVals
} else {
modx.levels <- modxVals
}
}
newdf <- if(is.null(modx)) newdf[order(newdf[[plotx]]), ]
else newdf[order(newdf[[plotx]], newdf[[modx]]), ]
if(!is.null(modx) && is.factor(modxVals) && any(levels(newdf[[modx]]) != modxVals) )stop("levels fail")
if(missing(ylim)){
ylim <- magRange(range(c(newdf[["fit"]], if(!is.null(newdf[["lwr"]])) min(newdf[["lwr"]])),
if(!is.null(newdf[["upr"]])) max(newdf[["upr"]])), 1.25)
}
if(missing(xlim) || is.null(xlim)){
xlim <- range(seq_along(plotxVals)) + c(-0.5, 0.5)
}
if(missing(xlab) || is.null(xlab)){
xlab <- plotx
}
if(missing(ylab) || is.null(ylab)){
ylab <- attr(mm, "terms")[[2]]
}
if(missing(main)){
main <- "rockchalk discrete predictor plot"
}
lnc <- if(is.null(modx)) plotxVals else modx.levels
xname <- if(is.null(modx)) plotx else modx
lwd <- rep(llwd, length.out = length(lnc))
names(lwd) <- lnc
lty <- rep(lty, length.out = length(lnc))
names(lty) <- lnc
if(!is.null(names(col))){
if (any(!lnc %in% names(col))) stop("names in color vector incorrect")
}
if(missing(col) || is.null(col) || length(col) < length(lnc)) col <- col
col <- rep(col, length.out = length(lnc))
names(col) <- lnc
newdf$col <- col[as.character(newdf[[xname]])]
width <- if(length(width) > 0 && length(width) < length(lnc)) rep(width, length.out = length(lnc))
names(width) <- lnc
newdf$lwd <- lwd[as.character(newdf[[xname]])]
newdf$lty <- lty[as.character(newdf[[xname]])]
if(is.null(modx)){
newdf$width <- width[as.character(newdf[[plotx]])]
} else {
newdf$width <- width[as.character(newdf[[modx]])]
}
NR <- if(is.null(modx)) 1 else length(unique(newdf[[modx]]))
NC <- length(unique(newdf[[plotx]]))
width.internal <- 1
space <- space * mean(width.internal)
if (length(space) == 2) {
space <- rep.int(c(space[2L], rep.int(space[1L], NR - 1)), NC)
}
width.internal <- rep_len(width.internal, NR)
offset <- rep_len(as.vector(offset), length(width.internal))
delta <- width.internal/2
w.r <- cumsum(space + width.internal)
w.m <- w.r - delta
w.l <- w.m - delta
newdf$w.m <- w.m
newdf$w.r <- w.r
newdf$w.l <- w.l
xlim <- c(min(w.l), max(w.r))
plot(1, 0, type = "n",
xlim = xlim, ylim = ylim, main = main, xaxt = "n",
xlab = xlab, ylab = ylab)
if (is.null(modx)) {
axis(1, at = newdf$w.m, labels = newdf[[plotx]])
}else{
xloc <- aggregate(newdf$w.m, by = list(plotx = newdf[[plotx]]), mean)
axis(1, at = xloc[ , "x"], labels = xloc[ , "plotx"])
}
for(mm in 1:(NROW(newdf))){
se.bars(newdf[mm , "w.m"], newdf[mm, "fit"], newdf[mm , "lwr"], newdf[mm , "upr"],
col = newdf[mm , "col"], width = newdf[mm , "width"], lty = newdf[mm, "lty"])
}
if((is.character(gridArgs) && gridArgs == "none") || interval == "none"){
} else {
gridlwd <- rep(gridArgs[["lwd"]], length.out = length(lnc))
gridlty <- rep(gridArgs[["lty"]], length.out = length(lnc))
if(is.null(modx)){
rownames(newdf) <- newdf[[plotx]]
plotxList <- list(newdf)
names(plotxList) <- plotx
} else {
plotxList <- split(newdf, f = newdf[ , plotx], drop = TRUE)
for(i in names(plotxList)) rownames(plotxList[[i]]) <- plotxList[[i]][[xname]]
}
if(length(plotxList) > 1) {
for(i in 1:(length(plotxList) - 1)){
set1 <- plotxList[[i]]
set2 <- plotxList[[i+1]]
arrows(set1[["w.m"]], set1[["fit"]], set2[["w.l"]] + 0.3 * (1 - width), set1[["fit"]], col = col, lwd = gridlwd,
lty = gridlty, length = 0.1)
}
}
}
if(!missing(legendArgs) && is.character(legendArgs) && legendArgs == "none") {
} else if (!is.null(modx)){
legend.parms <- list(x = "bottomleft",
fill = col[as.character(lnc)],
col = col[as.character(lnc)],
border = NA, bty = "n")
if(length(unique(lty)) > 1){
legend.parms[["lty"]] <- lty[as.character(lnc)]
legend.parms[["lwd"]] <- lwd[as.character(lnc)]
}
if(any(modxVals != lnc)){
stop("plotFancyCategories: fatal error")
}
if (is.null(names(modxVals))) {
legend.parms[["title"]] <- paste("Moderator:", modx)
legend.parms[["legend"]] <- modxVals
} else {
legend.parms[["title"]] <- paste("Moderator:", modx)
legend.parms[["legend"]] <- names(modxVals)
}
if(!missing(legendArgs) && !is.null(legendArgs)) legend.parms <- modifyList(legend.parms, legendArgs)
do.call(legend, legend.parms)
} else {
if(!missing(legendArgs) && !is.null(legendArgs)) do.call(legend, legendArgs)
}
invisible(list(newdf = newdf, col = col, lwd = lwd, call.orig=call.orig))
}
NULL |
library(simmer)
t <- trajectory(verbose=T) %>%
renege_in(1) %>%
seize("dummy", 1) %>%
renege_abort() %>%
timeout(2) %>%
release("dummy", 1)
env <- simmer(verbose=TRUE) %>%
add_resource("dummy", 1) %>%
add_generator("arrival", t, at(0, 0)) %>%
run()
get_mon_arrivals(env, per_resource=TRUE)
get_mon_arrivals(env, per_resource=FALSE)
get_mon_resources(env) |
GetCovSurface = function(Ly, Lt, optns = list()){
CheckData(Ly,Lt)
inputData <- HandleNumericsAndNAN(Ly,Lt);
Ly <- inputData$Ly;
Lt <- inputData$Lt;
optns = SetOptions(Ly, Lt, optns);
numOfCurves = length(Ly);
CheckOptions(Lt, optns,numOfCurves)
if ( optns$usergrid == FALSE & optns$useBinnedData != 'OFF'){
BinnedDataset <- GetBinnedDataset(Ly,Lt,optns)
Ly = BinnedDataset$newy;
Lt = BinnedDataset$newt;
optns[['nRegGrid']] <- min(optns[['nRegGrid']],
BinnedDataset[['numBins']])
inputData$Ly <- Ly
inputData$Lt <- Lt
}
obsGrid = sort(unique( c(unlist(Lt))));
regGrid = seq(min(obsGrid), max(obsGrid),length.out = optns$nRegGrid);
outPercent <- optns$outPercent
buff <- .Machine$double.eps * max(abs(obsGrid)) * 10
rangeGrid <- range(regGrid)
minGrid <- rangeGrid[1]
maxGrid <- rangeGrid[2]
cutRegGrid <- regGrid[regGrid > minGrid + diff(rangeGrid) * outPercent[1] -
buff &
regGrid < minGrid + diff(rangeGrid) * outPercent[2] +
buff]
ymat <- List2Mat(Ly, Lt)
firsttsMu <- Sys.time()
userMu <- optns$userMu
if ( is.list(userMu) && (length(userMu$mu) == length(userMu$t))){
smcObj <- GetUserMeanCurve(optns, obsGrid, regGrid, buff)
smcObj$muDense = ConvertSupport(obsGrid, regGrid, mu = smcObj$mu)
} else if (optns$methodMuCovEst == 'smooth') {
smcObj = GetSmoothedMeanCurve(Ly, Lt, obsGrid, regGrid, optns)
} else if (optns$methodMuCovEst == 'cross-sectional') {
smcObj = GetMeanDense(ymat, obsGrid, optns)
}
mu <- smcObj$mu
lasttsMu <- Sys.time()
firsttsCov <- Sys.time()
if (!is.null(optns$userCov) && optns$methodMuCovEst != 'smooth') {
scsObj <- GetUserCov(optns, obsGrid, cutRegGrid, buff, ymat)
} else if (optns$methodMuCovEst == 'smooth') {
scsObj = GetSmoothedCovarSurface(Ly, Lt, mu, obsGrid, regGrid, optns,
optns$useBinnedCov)
} else if (optns$methodMuCovEst == 'cross-sectional') {
scsObj = GetCovDense(ymat, mu, optns)
if (length(obsGrid) != length(cutRegGrid) || !identical(obsGrid, cutRegGrid)) {
scsObj$smoothCov = ConvertSupport(obsGrid, cutRegGrid, Cov =
scsObj$smoothCov)
}
scsObj$outGrid <- cutRegGrid
}
sigma2 <- scsObj[['sigma2']]
bwCov = scsObj$bwCov
workGrid <- scsObj$outGrid
ret <- list(cov = scsObj$smoothCov,
sigma2 = scsObj$sigma2,
workGrid = workGrid,
bwCov = bwCov,
optns = optns)
if(optns$plot == TRUE){
plot3D::persp3D(x = workGrid, y = workGrid, z = ret$cov, col = colorRampPalette( c('blue','red') )(50))
}
return(ret)
} |
NULL
cognitosync_bulk_publish <- function(IdentityPoolId) {
op <- new_operation(
name = "BulkPublish",
http_method = "POST",
http_path = "/identitypools/{IdentityPoolId}/bulkpublish",
paginator = list()
)
input <- .cognitosync$bulk_publish_input(IdentityPoolId = IdentityPoolId)
output <- .cognitosync$bulk_publish_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$bulk_publish <- cognitosync_bulk_publish
cognitosync_delete_dataset <- function(IdentityPoolId, IdentityId, DatasetName) {
op <- new_operation(
name = "DeleteDataset",
http_method = "DELETE",
http_path = "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}",
paginator = list()
)
input <- .cognitosync$delete_dataset_input(IdentityPoolId = IdentityPoolId, IdentityId = IdentityId, DatasetName = DatasetName)
output <- .cognitosync$delete_dataset_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$delete_dataset <- cognitosync_delete_dataset
cognitosync_describe_dataset <- function(IdentityPoolId, IdentityId, DatasetName) {
op <- new_operation(
name = "DescribeDataset",
http_method = "GET",
http_path = "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}",
paginator = list()
)
input <- .cognitosync$describe_dataset_input(IdentityPoolId = IdentityPoolId, IdentityId = IdentityId, DatasetName = DatasetName)
output <- .cognitosync$describe_dataset_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$describe_dataset <- cognitosync_describe_dataset
cognitosync_describe_identity_pool_usage <- function(IdentityPoolId) {
op <- new_operation(
name = "DescribeIdentityPoolUsage",
http_method = "GET",
http_path = "/identitypools/{IdentityPoolId}",
paginator = list()
)
input <- .cognitosync$describe_identity_pool_usage_input(IdentityPoolId = IdentityPoolId)
output <- .cognitosync$describe_identity_pool_usage_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$describe_identity_pool_usage <- cognitosync_describe_identity_pool_usage
cognitosync_describe_identity_usage <- function(IdentityPoolId, IdentityId) {
op <- new_operation(
name = "DescribeIdentityUsage",
http_method = "GET",
http_path = "/identitypools/{IdentityPoolId}/identities/{IdentityId}",
paginator = list()
)
input <- .cognitosync$describe_identity_usage_input(IdentityPoolId = IdentityPoolId, IdentityId = IdentityId)
output <- .cognitosync$describe_identity_usage_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$describe_identity_usage <- cognitosync_describe_identity_usage
cognitosync_get_bulk_publish_details <- function(IdentityPoolId) {
op <- new_operation(
name = "GetBulkPublishDetails",
http_method = "POST",
http_path = "/identitypools/{IdentityPoolId}/getBulkPublishDetails",
paginator = list()
)
input <- .cognitosync$get_bulk_publish_details_input(IdentityPoolId = IdentityPoolId)
output <- .cognitosync$get_bulk_publish_details_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$get_bulk_publish_details <- cognitosync_get_bulk_publish_details
cognitosync_get_cognito_events <- function(IdentityPoolId) {
op <- new_operation(
name = "GetCognitoEvents",
http_method = "GET",
http_path = "/identitypools/{IdentityPoolId}/events",
paginator = list()
)
input <- .cognitosync$get_cognito_events_input(IdentityPoolId = IdentityPoolId)
output <- .cognitosync$get_cognito_events_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$get_cognito_events <- cognitosync_get_cognito_events
cognitosync_get_identity_pool_configuration <- function(IdentityPoolId) {
op <- new_operation(
name = "GetIdentityPoolConfiguration",
http_method = "GET",
http_path = "/identitypools/{IdentityPoolId}/configuration",
paginator = list()
)
input <- .cognitosync$get_identity_pool_configuration_input(IdentityPoolId = IdentityPoolId)
output <- .cognitosync$get_identity_pool_configuration_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$get_identity_pool_configuration <- cognitosync_get_identity_pool_configuration
cognitosync_list_datasets <- function(IdentityPoolId, IdentityId, NextToken = NULL, MaxResults = NULL) {
op <- new_operation(
name = "ListDatasets",
http_method = "GET",
http_path = "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets",
paginator = list()
)
input <- .cognitosync$list_datasets_input(IdentityPoolId = IdentityPoolId, IdentityId = IdentityId, NextToken = NextToken, MaxResults = MaxResults)
output <- .cognitosync$list_datasets_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$list_datasets <- cognitosync_list_datasets
cognitosync_list_identity_pool_usage <- function(NextToken = NULL, MaxResults = NULL) {
op <- new_operation(
name = "ListIdentityPoolUsage",
http_method = "GET",
http_path = "/identitypools",
paginator = list()
)
input <- .cognitosync$list_identity_pool_usage_input(NextToken = NextToken, MaxResults = MaxResults)
output <- .cognitosync$list_identity_pool_usage_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$list_identity_pool_usage <- cognitosync_list_identity_pool_usage
cognitosync_list_records <- function(IdentityPoolId, IdentityId, DatasetName, LastSyncCount = NULL, NextToken = NULL, MaxResults = NULL, SyncSessionToken = NULL) {
op <- new_operation(
name = "ListRecords",
http_method = "GET",
http_path = "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/records",
paginator = list()
)
input <- .cognitosync$list_records_input(IdentityPoolId = IdentityPoolId, IdentityId = IdentityId, DatasetName = DatasetName, LastSyncCount = LastSyncCount, NextToken = NextToken, MaxResults = MaxResults, SyncSessionToken = SyncSessionToken)
output <- .cognitosync$list_records_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$list_records <- cognitosync_list_records
cognitosync_register_device <- function(IdentityPoolId, IdentityId, Platform, Token) {
op <- new_operation(
name = "RegisterDevice",
http_method = "POST",
http_path = "/identitypools/{IdentityPoolId}/identity/{IdentityId}/device",
paginator = list()
)
input <- .cognitosync$register_device_input(IdentityPoolId = IdentityPoolId, IdentityId = IdentityId, Platform = Platform, Token = Token)
output <- .cognitosync$register_device_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$register_device <- cognitosync_register_device
cognitosync_set_cognito_events <- function(IdentityPoolId, Events) {
op <- new_operation(
name = "SetCognitoEvents",
http_method = "POST",
http_path = "/identitypools/{IdentityPoolId}/events",
paginator = list()
)
input <- .cognitosync$set_cognito_events_input(IdentityPoolId = IdentityPoolId, Events = Events)
output <- .cognitosync$set_cognito_events_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$set_cognito_events <- cognitosync_set_cognito_events
cognitosync_set_identity_pool_configuration <- function(IdentityPoolId, PushSync = NULL, CognitoStreams = NULL) {
op <- new_operation(
name = "SetIdentityPoolConfiguration",
http_method = "POST",
http_path = "/identitypools/{IdentityPoolId}/configuration",
paginator = list()
)
input <- .cognitosync$set_identity_pool_configuration_input(IdentityPoolId = IdentityPoolId, PushSync = PushSync, CognitoStreams = CognitoStreams)
output <- .cognitosync$set_identity_pool_configuration_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$set_identity_pool_configuration <- cognitosync_set_identity_pool_configuration
cognitosync_subscribe_to_dataset <- function(IdentityPoolId, IdentityId, DatasetName, DeviceId) {
op <- new_operation(
name = "SubscribeToDataset",
http_method = "POST",
http_path = "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/subscriptions/{DeviceId}",
paginator = list()
)
input <- .cognitosync$subscribe_to_dataset_input(IdentityPoolId = IdentityPoolId, IdentityId = IdentityId, DatasetName = DatasetName, DeviceId = DeviceId)
output <- .cognitosync$subscribe_to_dataset_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$subscribe_to_dataset <- cognitosync_subscribe_to_dataset
cognitosync_unsubscribe_from_dataset <- function(IdentityPoolId, IdentityId, DatasetName, DeviceId) {
op <- new_operation(
name = "UnsubscribeFromDataset",
http_method = "DELETE",
http_path = "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}/subscriptions/{DeviceId}",
paginator = list()
)
input <- .cognitosync$unsubscribe_from_dataset_input(IdentityPoolId = IdentityPoolId, IdentityId = IdentityId, DatasetName = DatasetName, DeviceId = DeviceId)
output <- .cognitosync$unsubscribe_from_dataset_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$unsubscribe_from_dataset <- cognitosync_unsubscribe_from_dataset
cognitosync_update_records <- function(IdentityPoolId, IdentityId, DatasetName, DeviceId = NULL, RecordPatches = NULL, SyncSessionToken, ClientContext = NULL) {
op <- new_operation(
name = "UpdateRecords",
http_method = "POST",
http_path = "/identitypools/{IdentityPoolId}/identities/{IdentityId}/datasets/{DatasetName}",
paginator = list()
)
input <- .cognitosync$update_records_input(IdentityPoolId = IdentityPoolId, IdentityId = IdentityId, DatasetName = DatasetName, DeviceId = DeviceId, RecordPatches = RecordPatches, SyncSessionToken = SyncSessionToken, ClientContext = ClientContext)
output <- .cognitosync$update_records_output()
config <- get_config()
svc <- .cognitosync$service(config)
request <- new_request(svc, op, input, output)
response <- send_request(request)
return(response)
}
.cognitosync$operations$update_records <- cognitosync_update_records |
diff_SNP <- function(snpDf, sampleGroup, method = min) {
snpDf[!is.na(snpDf)] <- "mutation"
snpDf[is.na(snpDf)] <- "wild"
sampleGroup <- sampleGroup[!is.na(sampleGroup)]
type1 <- which(sampleGroup == names(table(sampleGroup))[1])
type2 <- which(sampleGroup == names(table(sampleGroup))[2])
pvalue <- rep(0, nrow(snpDf))
estimate <- rep(0, nrow(snpDf))
for(i in seq_len(nrow(snpDf))) {
type1_freq <- table(as.character(snpDf[i, type1]))
type2_freq <- table(as.character(snpDf[i, type2]))
df <- data.frame(type1 = as.numeric(type1_freq[c("wild", "mutation")]),
type2 = as.numeric(type2_freq[c("wild", "mutation")]))
df[is.na(df)] <- 0
fish <- stats::fisher.test(df)
pvalue[i] <- fish$p.value
estimate[i] <- fish$estimate
}
names(pvalue) <- names(estimate) <- sub("_.*", "", rownames(snpDf))
pvalue <- stats::aggregate(pvalue, by = list(names(pvalue)), FUN = method)
estimate <- stats::aggregate(estimate, by = list(names(estimate)), FUN = mean)
return(data.frame(gene = pvalue[,1], pvalue = pvalue[, 2], estimate = estimate[, 2]))
}
diff_SNP_tcga <- function(snpData, sampleType) {
Tumor_Sample_Barcode <- Variant_Classification <- NULL
snpName <- paste(snpData$Hugo_Symbol, snpData$Start_Position, sep = "_")
snpData <- snpData[, c("Variant_Classification", "Tumor_Sample_Barcode")]
snpData$snp <- snpName
snpData <- tidyr::spread(snpData, Tumor_Sample_Barcode, Variant_Classification)
snpData <- as.data.frame(snpData)
i <- match(colnames(snpData), names(sampleType))
sampleType <- sampleType[i]
rownames(snpData) <- snpData$snp
snpData <- snpData[, -1]
pvalue <- diff_SNP(snpDf = snpData, sampleGroup = sampleType)
return(pvalue)
} |
service_line_augment <- function(.data, .dx_col, .px_col, .drg_col){
dx_col <- rlang::enquo(.dx_col)
px_col <- rlang::enquo(.px_col)
drg_col <- rlang::enquo(.drg_col)
if(!is.data.frame(.data)){
stop(call. = FALSE, ".data must be supplied.")
}
if(rlang::quo_is_missing(dx_col) | rlang::quo_is_missing(px_col) |
rlang::quo_is_missing(drg_col)){
stop(call. = FALSE, "The columns .dx_col, .px_col and .drg_col must be supplied.")
}
data <- tibble::as_tibble(.data)
data <- data %>%
dplyr::select(
{{dx_col}},
{{px_col}},
{{drg_col}},
dplyr::everything()
)
service_line <- healthyR::service_line_vec(
.data = data,
.dx_col = {{dx_col}},
.px_col = {{px_col}},
.drg_col = {{drg_col}}
)
data <- cbind(data, service_line) %>%
tibble::as_tibble() %>%
dplyr::mutate(
dplyr::across(
.cols = tidyselect::vars_select_helpers$where(is.character),
.fns = stringr::str_squish
)
)
return(data)
} |
library(gasfluxes)
context("fitting checks")
test_that("linear regression gives expected result", {
t <- c(0, 1/3, 2/3, 1)
C <- c(320, 341, 352, 359)
fit <- lin.fit(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = 11.52, f0.se = 2.02849698052524, f0.p = 0.0296345042190038,
C0 = 323.8, AIC = 27.5179162394956, AICc = Inf, RSE = 5.03984126734168,
r = 0.970365495780996, diagnostics = ""),
.Names = c("f0", "f0.se", "f0.p", "C0", "AIC", "AICc", "RSE", "r","diagnostics")), tolerance = 1e-5)
C <- 320 + 0:3 * 10
expect_equal(lin.fit(t, C, 1, 0.3, "a", verbose = FALSE)$diagnostics, "essentially perfect fit: summary may be unreliable")
})
test_that("robust linear regression gives expected result", {
skip_on_cran()
t <- c(0, 1/3, 2/3, 1)
C <- c(320, 341, 352, 359)
fit <- rlin.fit(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = 11.52, f0.se = 2.02849698052524, f0.p = 0.0296345042190038,
C0 = 323.8, weights = c(1, 1, 1, 1), diagnostics = ""),
.Names = c("f0", "f0.se", "f0.p", "C0", "weights", "diagnostics")), tolerance = 1e-5)
C[2] <- 400
fit <- rlin.fit(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = 10.3651999807438, f0.se = 7.74617801784988,
f0.p = 0.283145377159807, C0 = 328.932444530028,
weights = c(1, 0.224712479154538, 1, 1), diagnostics = ""),
.Names = c("f0", "f0.se", "f0.p", "C0", "weights", "diagnostics")), tolerance = 1e-5)
C <- 320 + 0:3 * 10
fit <- rlin.fit(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = 9, f0.se = 5.05560019475045e-16, f0.p = 3.15544362088405e-33,
C0 = 320, weights = c(1, 1, 1, 1), diagnostics = ""),
.Names = c("f0", "f0.se", "f0.p", "C0", "weights", "diagnostics")))
})
test_that("orig. HMR regression gives expected result", {
t <- c(0, 1/3, 2/3, 1)
C <- c(320, 341, 352, 359)
fit <- HMR.orig(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = 24.5726525375334, f0.se = 0.269619840794467,
f0.p = 0.000120370813714629, kappa = 1.7420647314171, phi = 367.070131017252,
AIC = 7.55291777918452, AICc = -32.4470822208155, RSE = 0.457638077871523,
diagnostics = ""), .Names = c("f0", "f0.se", "f0.p", "kappa",
"phi", "AIC", "AICc", "RSE", "diagnostics")))
C[2] <- 400
fit <- HMR.orig(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = 0, f0.se = NA_real_, f0.p = NA_real_, kappa = NA_real_,
phi = NA_real_, AIC = NA_real_, AICc = NA_real_, RSE = NA_real_,
diagnostics = ""), .Names = c("f0", "f0.se", "f0.p", "kappa",
"phi", "AIC", "AICc", "RSE", "diagnostics")))
C <- 320 + 0:3 * 10
fit <- HMR.orig(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = 9, f0.se = 0, f0.p = 0, kappa = NA_real_,
phi = NA_real_, AIC = NA_real_, AICc = NA_real_, RSE = NA_real_,
diagnostics = ""), .Names = c("f0", "f0.se", "f0.p", "kappa",
"phi", "AIC", "AICc", "RSE", "diagnostics")))
})
test_that("HMR regression gives expected result", {
skip_on_cran()
t <- c(0, 1/3, 2/3, 1)
C <- c(320, 341, 352, 359)
fit <- HMR.fit(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = 24.5729190601842, f0.se = 1.09217335198933,
f0.p = 0.0282767319678857, kappa = 1.74209652356821, phi = 367.069739676469,
AIC = 7.55291751354392, AICc = -32.4470824864561, RSE = 0.457638062675616,
diagnostics = ""), .Names = c("f0", "f0.se", "f0.p", "kappa",
"phi", "AIC", "AICc", "RSE", "diagnostics")))
expect_equal(fit["f0"], HMR.orig(t, C, 1, 0.3, "a", verbose = FALSE)["f0"], tolerance = 1e-4)
C[2] <- 400
fit <- HMR.fit(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = NA_real_, f0.se = NA_real_, f0.p = NA_real_,
kappa = NA_real_, phi = NA_real_, AIC = NA_real_, AICc = NA_real_,
RSE = NA_real_, diagnostics = "Missing value or an infinity produced when evaluating the model"),
.Names = c("f0", "f0.se", "f0.p", "kappa", "phi", "AIC", "AICc", "RSE", "diagnostics"
)))
C <- 320 + 0:3 * 10
fit <- HMR.fit(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = NA_real_, f0.se = NA_real_, f0.p = NA_real_,
kappa = NA_real_, phi = NA_real_, AIC = NA_real_, AICc = NA_real_,
RSE = NA_real_, diagnostics = "element (3, 3) is zero, so the inverse cannot be computed"),
.Names = c("f0", "f0.se", "f0.p", "kappa", "phi", "AIC", "AICc", "RSE", "diagnostics"
)))
})
test_that("NDFE regression gives expected result", {
skip_on_cran()
t <- c(0, 1/3, 2/3, 1)
C <- c(320, 341, 352, 359)
fit <- NDFE.fit(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = 108.747818996036, f0.se = 62.9208765449726,
f0.p = 0.333927030887926, tau = 0.0111016600093449, C0 = 319.992148880558,
AIC = 10.7342239838649, AICc = -29.2657760161351, RSE = 0.681122330960559,
diagnostics = ""), .Names = c("f0", "f0.se", "f0.p", "tau",
"C0", "AIC", "AICc", "RSE", "diagnostics")), tolerance = 1e-5)
C[2] <- 400
fit <- NDFE.fit(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = NA_real_, f0.se = NA_real_, f0.p = NA_real_,
tau = NA_real_, C0 = NA_real_, AIC = NA_real_, AICc = NA_real_,
RSE = NA_real_, diagnostics = "Missing value or an infinity produced when evaluating the model"),
.Names = c("f0", "f0.se", "f0.p", "tau", "C0", "AIC", "AICc", "RSE", "diagnostics"
)))
C <- 320 + 0:3 * 10
fit <- NDFE.fit(t, C, 1, 0.3, "a", verbose = FALSE)
expect_equal(fit, structure(list(f0 = NA_real_, f0.se = NA_real_, f0.p = NA_real_,
tau = NA_real_, C0 = NA_real_, AIC = NA_real_, AICc = NA_real_,
RSE = NA_real_, diagnostics = "step factor 5.82077e-11 reduced below 'minFactor' of 1e-10"),
.Names = c("f0", "f0.se", "f0.p", "tau", "C0", "AIC", "AICc", "RSE", "diagnostics"
)))
}) |
partition_gen <- function(N, K) {
a <- sample(1:K, N, replace = TRUE)
P <- matrix(0, nrow = N, ncol = K)
for (i in 1:K) {
ind <- which(a == i)
av <- rep(0, N)
av[ind] <- 1
P[, i] <- av
}
count_in_proto <- apply(P, 2, sum)
if(all(count_in_proto > 0)) {
P <- P
} else if(0 %in% count_in_proto) {
empty_protos <- which(count_in_proto == 0)
empties <- length(empty_protos)
for(i in 1:empties) {
count_in_proto <- colSums(P)
max_count <- which.max(count_in_proto)
empty_protos <- which(count_in_proto == 0)
rows_to_change <- which(P[, max_count] == 1)
dummy_v <- rep(0, ncol(P))
dummy_v[empty_protos[1]] <- 1
P[rows_to_change[1],] <- dummy_v
}
}
P1 <- format_partition(P)
return(P1)
} |
test_that("dfm_sample works as expected", {
mt <- dfm(tokens(data_corpus_inaugural[1:10]), verbose = FALSE)
expect_equal(ndoc(dfm_sample(mt, size = 5)), 5)
expect_equal(ndoc(dfm_sample(mt, size = 15, replace = TRUE)), 15)
expect_error(dfm_sample(mt, size = 20),
"size cannot exceed the number of items")
expect_error(dfm_sample(data_corpus_inaugural[1:10]),
"dfm_sample() only works on dfm objects.", fixed = TRUE)
})
test_that("dfm_sample default size arguments work as expected", {
suppressWarnings(RNGversion("3.5.3"))
dfmat <- dfm(tokens(c("a b c c d", "a a c c d d d")))
mat1 <- matrix(rep(c(1, 1, 2, 1), 2), byrow = TRUE, nrow = 2,
dimnames = list(docs = c("text1.1", "text1.2"), features = letters[1:4]))
mat2 <- matrix(c(1, 1, 2, 1, 0, 0, 2, 2), byrow = TRUE, nrow = 2,
dimnames = list(docs = c("text1", "text2"), features = c("b", "b", "c", "a")))
expect_identical({
set.seed(100)
as.matrix(dfm_sample(dfmat, replace = TRUE))
}, mat1)
}) |
set.as<-function(base,target,type='downstream')
{
if(missing(base)){stop('base object is missing, with no default value!')}
if(missing(target)){stop('target object is missing, with no default value!')}
if(!any(class(base)==c("createAquifer","createRiver","createReservoir","createDiversion","createJunction","createDemandSite")))
{
stop("base object is wrongly specified!")
}
if(!any(class(target)==c("createAquifer","createRiver","createReservoir","createDiversion","createJunction","createDemandSite")))
{
stop("base object is wrongly specified!")
}
if(type=='supplier')
{
if(!any(class(base)==c("createAquifer","createRiver","createReservoir","createDiversion")))
{
stop("base object must be from a water resources class type!")
}
if(!class(target)=="createDemandSite")
{
stop("base object must be from a demand site class type!")
}
}
if(!any(type==c('downstream','supplier','leakageObject','divertObject')))
{
stop('type is wrongly specified!')
}
if(type=='downstream') {target$operation$downstream <-base$operation$label}
if(type=='supplier') {target$operation$suppliers <-c(target$operation$suppliers,base$operation$label)}
if(type=='leakageObject'){target$operation$leakageObject<-base$operation$label}
if(type=='divertObject') {target$operation$divertObject <-base$operation$label}
return(target)
} |
comma_sep_string_to_numbers <- function(string) {
output <- stats::na.omit(
as.numeric(
unlist(
strsplit(
gsub(" ", "", string), ","
)
)
)
)
return(output)
} |
function.PrevalenceMatching <-
function(data, marker, status, tag.healthy = 0, direction = c("<", ">"), control = control.cutpoints(), pop.prev, ci.fit = FALSE, conf.level = 0.95, measures.acc) {
sample.prev <- calculate.sample.prev(data, status, tag.healthy)
predicted.prev <- measures.acc$Se[,1]*sample.prev+(1-measures.acc$Sp[,1])*(1-sample.prev)
difference <- abs(sample.prev-predicted.prev)
cPrevalenceMatching <- measures.acc$cutoffs[which(round(difference,10)==round(min(difference, na.rm = TRUE),10))]
optimal.difference <- min(difference,na.rm=TRUE)
optimal.cutoff <- obtain.optimal.measures(cPrevalenceMatching, measures.acc)
res <- list(measures.acc = measures.acc, optimal.cutoff = optimal.cutoff, criterion = difference, optimal.criterion = optimal.difference)
res
} |
"Stream"
stream <- function(index = 0, api = "ANY") {
new(Stream, index = index, api = api)
}
isStream <- function(object) {
inherits(object, "Rcpp_Stream") & tryCatch(object$isOpened(), error = function(e) FALSE)
}
dim.Rcpp_Stream <- function(x) {
x$dim()
}
nrow.Rcpp_Stream <- function(x) {
x$nrow()
}
ncol.Rcpp_Stream <- function(x) {
x$ncol()
}
release.Rcpp_Stream <- function(x) {
if (!isStream(x))
stop("This is not a Stream object.")
x$release()
if (!x$isOpened()) {
tmp <- deparse(substitute(x))
rm(list = tmp, envir = parent.frame(1))
message("Stream released successfully. \n")
} else {
message("An error occured while trying to release the stream. \n")
}
}
readNext.Rcpp_Stream <- function(x, target = "new") {
if (!isStream(x))
stop("This is not a Stream object.")
if (isImage(target)) {
x$readNext(target)
} else if (target == "new") {
out <- zeros(nrow(x), ncol(x), 3)
x$readNext(out)
out
} else {
stop("Invalid target.")
}
}
setProp.Rcpp_Stream <- function(x, property, value) {
if (!isStream(x))
stop("This is not a Stream object.")
x$set(property, value)
}
getProp.Rcpp_Stream <- function(x, property) {
if (!isStream(x))
stop("This is not a Stream object.")
x$get(property)
}
timelapse <- function(x, outputFolder, interval = 1, duration = Inf,
format = "png") {
if (!isStream(x))
stop("This is not a Stream object.")
outputFolder <- suppressWarnings(normalizePath(outputFolder))
if (!file.exists(outputFolder)) {
message("The output folder does not exist. It will be created.")
dir.create(outputFolder)
}
counter <- 0
start <- .now()
end <- start + duration * 1000
while (.now() < end) {
img <- readNext(x)
img$write(paste0(outputFolder, "/", counter, ".", format))
counter <- counter + 1
print(paste0("Last picture taken at: ", Sys.time()))
Sys.sleep(((start + counter * interval * 1000) - .now()) / 1000)
}
NULL
} |
women
plot(women)
plot(women, type='p', pch=18, col='red')
plot(women, type='l')
plot(women, type='b')
plot(women, type='b', pch=18, lty=2, col=2)
plot(women, xlim=c(30,100), ylim=c(min(women$weight)-10, 200), pch=10)
plot(x=women$weight, y=women$height, pch=15, xlab='Weight', ylab='Height', col='red', cex=2, type='b')
title(main='Main Title', sub='Sub Title')
plot(women)
abline(lm(women$weight ~ women$height), col='red', lty=2, lwd=4)
boxplot(women$height)
abline(h=c(58, 62,65,68,72))
summary(women)
quantile(women$height)
quantile(women$height, seq(0,1,.1))
quantile(women$height, seq(0,1,.01))
stem(women$height)
boxplot(women$height, col='green')
abline(h=quantile(women$height))
text(1+.2, quantile(women$height), labels=c('min','1Q','median','3Q','max'))
hist(women$height)
hist(women$height, breaks=10)
hist(women$height, breaks=5, col=1:5)
(x = rnorm(100,50,10))
hist(x)
hist(x, freq=F, col=1:5)
lines(density(x))
plot(density(x), col='red')
gender= sample(c('Male','Female'), size=30, replace=T, prob=c(.6,.4))
table(gender)
pie(table(gender))
x = c(10,20,40,50)
pie(x)
xlabels = c('A','B','C','D')
x/sum(x)
(labels2 = paste(xlabels, round(x/sum(x),2) * 100 , sep='-'))
pie(x, labels=labels2)
x
barplot(x,col=1:4)
barplot(x,col=1:4, horiz = T)
pairs(women)
cor(women$height,women$weight)
cov(women$height, women$weight)
head(mtcars)
cor(mtcars)
names(mtcars)
pairs(mtcars)
pairs(mtcars[1:4])
options(digits=4)
pairs(mtcars[c('mpg', 'wt','hp')]) |
"linloglines" <-
function (x, mu, alpha)
{
if(alpha != 0) {
for (i in 1:length(x)) {
if ((x[i] - mu)/alpha >= 1)
x[i] <- alpha + (alpha * log10((x[i] - mu)/alpha))
else if ((x[i] - mu)/alpha < -1)
x[i] <- -alpha - (alpha * log10((mu - x[i])/alpha))
else x[i] <- x[i] - mu
}
}
else
for (i in 1:length(x))
x[i] <- x[i] - mu
x
} |
test_that("test die: constructor", {
d <- Die$new("Blue")
expect_equal(d$getColor(), "Blue")
expect_equal(d$getValue(), 0)
})
test_that("test die: roll", {
d <- Die$new("Blue")
set.seed(1)
expect_equal(d$roll(), 1)
expect_equal(d$getValue(), 1)
}) |
mjs_labs <- function(mjs,
x_label=NULL, y_label=NULL) {
mjs$x$x_label <- x_label
mjs$x$y_label <- y_label
mjs
} |
give.init.Gspline <- function(prior, init, mcmc.par, dim)
{
thispackage = "bayesSurv"
if(length(prior) == 0) inprior <- "arnost"
else inprior <- names(prior)
if(length(init) == 0) ininit <- "arnost"
else ininit <- names(init)
if(length(mcmc.par) == 0) inmcmc.par <- "arnost"
else inmcmc.par <- names(mcmc.par)
if (dim <= 0 | dim > 2) stop("Dimension must be either 1 or 2")
tmp <- match("specification", inprior, nomatch=NA)
if(is.na(tmp)) prior$specification <- 2
if (is.na(prior$specification)) prior$specification <- 2
prior$specification <- prior$specification[1]
if (prior$specification != 1 && prior$specification != 2) stop("Incorrect prior$specification given")
tmp <- match("K", inprior, nomatch=NA)
if(is.na(tmp)) prior$K <- rep(15, dim)
prior$K <- prior$K[1:dim]
if (sum(is.na(prior$K))) stop("Incorrect prior$K given")
tmp <- match("izero", inprior, nomatch=NA)
if(is.na(tmp)) prior$izero <- rep(0, dim)
prior$izero <- prior$izero[1:dim]
if (sum(is.na(prior$izero))) stop("Incorrect prior$izero given")
if (sum(prior$izero < -prior$K) + sum(prior$izero > prior$K)) stop("Incorrect (out of range) prior$izero given")
tmp <- match("neighbor.system", inprior, nomatch=NA)
if(is.na(tmp)) prior$neighbor.system <- ifelse(dim==1, "uniCAR", "eight.neighbors")
neighbor.system <- pmatch(prior$neighbor.system, table=c("uniCAR", "eight.neighbors", "twelve.neighbors"), nomatch=0) - 1
neighbor.system <- neighbor.system[1]
if (neighbor.system == -1) stop("Incorrect prior$neighbor.system")
if (dim == 1 & neighbor.system != 0) stop("Neighbor system must be 'uniCAR' for univariate data")
tmp <- match("order", inprior, nomatch=NA)
if(is.na(tmp)) prior$order <- 3
if (neighbor.system == 1) prior$order <- 2
else if (neighbor.system == 2) prior$order <- 3
prior$order <- prior$order[1]
if (is.na(prior$order)) stop("Incorrect prior$order given")
if (prior$order > 3) stop("Order of CAR higher than 3 is not implemented")
tmp <- match("equal.lambda", inprior, nomatch=NA)
if(is.na(tmp)) prior$equal.lambda <- TRUE
if (dim == 1) prior$equal.lambda <- TRUE
if (neighbor.system > 0) prior$equal.lambda <- TRUE
prior$equal.lambda <- prior$equal.lambda[1]
if (is.na(prior$equal.lambda)) stop("Incorrect prior$equal.lambda given")
equal.lambda <- as.numeric(prior$equal.lambda)
tmp <- match("prior.lambda", inprior, nomatch=NA)
if(is.na(tmp)) stop("prior$prior.lambda must be given")
if (prior$equal.lambda){
prior$prior.lambda <- rep(prior$prior.lambda[1], dim)
}
else{
prior$prior.lambda <- prior$prior.lambda[1:dim]
}
if (sum(is.na(prior$prior.lambda))) stop("Incorrect prior$prior.lambda given")
prior.lambda <- apply(matrix(prior$prior.lambda, ncol=1), 1, pmatch, table=c("fixed", "gamma", "sduniform")) - 1
if (sum(prior.lambda == -1)) stop("Incorrect prior$prior.lambda given")
rate.lambda <- rep(0, dim)
shape.lambda <- rep(0, dim)
if (sum(prior.lambda > 0)){
if (is.null(prior$rate.lambda)) stop("Either rate for gamma prior or upper limit of uniform prior for lambda was not given")
if (prior$equal.lambda) rate.lambda <- rep(prior$rate.lambda[1], dim)
else rate.lambda <- prior$rate.lambda[1:dim]
if (sum(is.na(rate.lambda[prior.lambda > 0]))) stop("Incorrect prior$rate.lambda given")
if (sum(rate.lambda[prior.lambda > 0] <= 0)) stop("prior$rate.lambda must be positive")
rate.lambda[prior.lambda == 0] <- 0
}
if (sum(prior.lambda == 1)){
if (is.null(prior$shape.lambda)) stop("Shape for gamma prior for lambda was not given")
if (prior$equal.lambda) shape.lambda <- rep(prior$shape.lambda[1], dim)
else shape.lambda <- prior$shape.lambda[1:dim]
if (sum(is.na(shape.lambda[prior.lambda == 1]))) stop("Incorrect prior$shape.lambda given")
if (sum(shape.lambda[prior.lambda == 1] <= 0)) stop("prior$shape.lambda must be positive")
shape.lambda[prior.lambda != 1] <- 0
}
parms.lambda <- as.vector(rbind(shape.lambda, rate.lambda))
prior$shape.lambda <- shape.lambda
prior$rate.lambda <- rate.lambda
if (prior$specification == 2){
prior$prior.sigma <- rep("fixed", dim)
inprior <- names(prior)
}
tmp <- match("prior.sigma", inprior, nomatch=NA)
if(is.na(tmp)) stop("prior$prior.sigma must be given")
prior$prior.sigma <- prior$prior.sigma[1:dim]
if (sum(is.na(prior$prior.sigma))) stop("Incorrect prior$prior.sigma given")
prior.sigma <- apply(matrix(prior$prior.sigma, ncol=1), 1, pmatch, table=c("fixed", "gamma", "sduniform")) - 1
if (sum(prior.sigma == -1)) stop("Incorrect prior$prior.sigma given")
rate.sigma <- rep(0, dim)
shape.sigma <- rep(0, dim)
if (sum(prior.sigma > 0)){
if (is.null(prior$rate.sigma)) stop("Either rate for gamma prior or upper limit of uniform prior for sigma was not given")
rate.sigma <- prior$rate.sigma[1:dim]
if (sum(is.na(rate.sigma[prior.sigma > 0]))) stop("Incorrect prior$rate.sigma given")
if (sum(rate.sigma[prior.sigma > 0] <= 0)) stop("prior$rate.sigma must be positive")
rate.sigma[prior.sigma == 0] <- 0
}
if (sum(prior.sigma == 1)){
if (is.null(prior$shape.sigma)) stop("Shape for gamma prior for sigma was not given")
shape.sigma <- prior$shape.sigma[1:dim]
if (sum(is.na(shape.sigma[prior.sigma == 1]))) stop("Incorrect prior$shape.sigma given")
if (sum(shape.sigma[prior.sigma == 1] <= 0)) stop("prior$shape.sigma must be positive")
shape.sigma[prior.sigma != 1] <- 0
}
parms.sigma <- as.vector(rbind(shape.sigma, rate.sigma))
prior$shape.sigma <- shape.sigma
prior$rate.sigma <- rate.sigma
tmp <- match("k.overrelax.sigma", inmcmc.par, nomatch=NA)
if (!is.na(tmp) & length(mcmc.par$k.overrelax.sigma) == 1) mcmc.par$k.overrelax.sigma <- rep(mcmc.par$k.overrelax.sigma[1], dim)
if(is.na(tmp)) mcmc.par$k.overrelax.sigma <- rep(1, dim)
mcmc.par$k.overrelax.sigma <- mcmc.par$k.overrelax.sigma[1:dim]
if (sum(is.na(mcmc.par$k.overrelax.sigma))) stop("Incorrect mcmc.par$k.overrelax.sigma given")
if (sum(mcmc.par$k.overrelax.sigma <= 0)) stop("Incorrect mcmc.par$k.overrelax.sigma given (must be all positive)")
if (prior$specification == 2){
prior$prior.gamma <- rep("fixed", dim)
inprior <- names(prior)
}
tmp <- match("prior.gamma", inprior, nomatch=NA)
if(is.na(tmp)) stop("prior$prior.gamma must be given")
prior$prior.gamma <- prior$prior.gamma[1:dim]
if (sum(is.na(prior$prior.gamma))) stop("Incorrect prior$prior.gamma given")
prior.gamma <- apply(matrix(prior$prior.gamma, ncol=1), 1, pmatch, table=c("fixed", "normal")) - 1
if (sum(prior.gamma == -1)) stop("Incorrect prior$prior.gamma given")
mean.gamma <- rep(0, dim)
var.gamma <- rep(0, dim)
if (sum(prior.gamma > 0)){
tmp <- match("mean.gamma", inprior, nomatch=NA)
if(is.na(tmp)) stop("prior$mean.gamma must be given")
tmp <- match("var.gamma", inprior, nomatch=NA)
if(is.na(tmp)) stop("prior$var.gamma must be given")
mean.gamma <- prior$mean.gamma[1:dim]
var.gamma <- prior$var.gamma[1:dim]
if (sum(is.na(mean.gamma[prior.gamma > 0]))) stop("Incorrect prior$mean.gamma given")
if (sum(is.na(var.gamma[prior.gamma > 0]))) stop("Incorrect prior$var.gamma given")
mean.gamma[prior.gamma == 0] <- 0
var.gamma[prior.gamma == 0] <- 0
}
parms.gamma <- as.vector(rbind(mean.gamma, var.gamma))
prior$mean.gamma <- mean.gamma
prior$var.gamma <- var.gamma
if (prior$specification == 1){
prior$prior.scale <- rep("fixed", dim)
inprior <- names(prior)
}
tmp <- match("prior.scale", inprior, nomatch=NA)
if(is.na(tmp)) stop("prior$prior.scale must be given")
prior$prior.scale <- prior$prior.scale[1:dim]
if (sum(is.na(prior$prior.scale))) stop("Incorrect prior$prior.scale given")
prior.scale <- apply(matrix(prior$prior.scale, ncol=1), 1, pmatch, table=c("fixed", "gamma", "sduniform")) - 1
if (sum(prior.scale == -1)) stop("Incorrect prior$prior.scale given")
rate.scale <- rep(0, dim)
shape.scale <- rep(0, dim)
if (sum(prior.scale > 0)){
tmp <- match("rate.scale", inprior, nomatch=NA)
if(is.na(tmp)) stop("Either rate for gamma prior or upper limit of uniform prior for scale was not given")
rate.scale <- prior$rate.scale[1:dim]
if (sum(is.na(rate.scale[prior.scale > 0]))) stop("Incorrect prior$rate.scale given")
if (sum(rate.scale[prior.scale > 0] <= 0)) stop("prior$rate.scale must be positive")
rate.scale[prior.scale == 0] <- 0
}
if (sum(prior.scale == 1)){
tmp <- match("shape.scale", inprior, nomatch=NA)
if(is.na(tmp)) stop("Shape for gamma prior for scale was not given")
shape.scale <- prior$shape.scale[1:dim]
if (sum(is.na(shape.scale[prior.scale == 1]))) stop("Incorrect prior$shape.scale given")
if (sum(shape.scale[prior.scale == 1] <= 0)) stop("prior$shape.scale must be positive")
shape.scale[prior.scale != 1] <- 0
}
parms.scale <- as.vector(rbind(shape.scale, rate.scale))
prior$shape.scale <- shape.scale
prior$rate.scale <- rate.scale
tmp <- match("k.overrelax.scale", inmcmc.par, nomatch=NA)
if (!is.na(tmp) & length(mcmc.par$k.overrelax.scale) == 1) mcmc.par$k.overrelax.scale <- rep(mcmc.par$k.overrelax.scale[1], dim)
if(is.na(tmp)) mcmc.par$k.overrelax.scale <- rep(1, dim)
mcmc.par$k.overrelax.scale <- mcmc.par$k.overrelax.scale[1:dim]
if (sum(is.na(mcmc.par$k.overrelax.scale))) stop("Incorrect mcmc.par$k.overrelax.scale given")
if (sum(mcmc.par$k.overrelax.scale <= 0)) stop("Incorrect mcmc.par$k.overrelax.scale given (must be all positive)")
if (prior$specification == 1){
prior$prior.intercept <- rep("fixed", dim)
inprior <- names(prior)
}
tmp <- match("prior.intercept", inprior, nomatch=NA)
if(is.na(tmp)) stop("prior$prior.intercept must be given")
prior$prior.intercept <- prior$prior.intercept[1:dim]
if (sum(is.na(prior$prior.intercept))) stop("Incorrect prior$prior.intercept given")
prior.intercept <- apply(matrix(prior$prior.intercept, ncol=1), 1, pmatch, table=c("fixed", "normal")) - 1
if (sum(prior.intercept == -1)) stop("Incorrect prior$prior.intercept given")
mean.intercept <- rep(0, dim)
var.intercept <- rep(0, dim)
if (sum(prior.intercept > 0)){
tmp <- match("mean.intercept", inprior, nomatch=NA)
if(is.na(tmp)) stop("prior$mean.intercept must be given")
tmp <- match("var.intercept", inprior, nomatch=NA)
if(is.na(tmp)) stop("prior$var.intercept must be given")
mean.intercept <- prior$mean.intercept[1:dim]
var.intercept <- prior$var.intercept[1:dim]
if (sum(is.na(mean.intercept[prior.intercept > 0]))) stop("Incorrect prior$mean.intercept given")
if (sum(is.na(var.intercept[prior.intercept > 0]))) stop("Incorrect prior$var.intercept given")
mean.intercept[prior.intercept == 0] <- 0
var.intercept[prior.intercept == 0] <- 0
}
parms.intercept <- as.vector(rbind(mean.intercept, var.intercept))
prior$mean.intercept <- mean.intercept
prior$var.intercept <- var.intercept
tmp <- match("c4delta", inprior, nomatch=NA)
if(is.na(tmp)) prior$c4delta <- rep(1.5, dim)
prior$c4delta <- prior$c4delta[1:dim]
if (sum(is.na(prior$c4delta))) stop("Incorrect prior$c4delta given")
if (sum(prior$c4delta <= 0)) stop("prior$c4delta must be positive")
tmp <- match("type.update.a", inmcmc.par, nomatch=NA)
if(is.na(tmp)){
if (dim == 1) mcmc.par$type.update.a <- "slice"
else mcmc.par$type.update.a <- "slice"
}
tmp <- match("k.overrelax.a", inmcmc.par, nomatch=NA)
if(is.na(tmp)) mcmc.par$k.overrelax.a <- 1
mcmc.par$type.update.a <- mcmc.par$type.update.a[1]
mcmc.par$k.overrelax.a <- mcmc.par$k.overrelax.a[1]
if (is.na(mcmc.par$type.update.a)) stop("Incorrect mcmc.par$type.update.a given")
if (is.na(mcmc.par$k.overrelax.a)) stop("Incorrect mcmc.par$k.overrelax.a given")
type.update.a <- pmatch(mcmc.par$type.update.a, table=c("slice", "ars.quantile", "ars.mode", "block"), nomatch=0) - 1
if (type.update.a == -1) stop("Incorrect mcmc.par$type.update.a given")
if (type.update.a == 0){
if (mcmc.par$k.overrelax.a <= 0) stop("Incorrect mcmc.par$k.overrelax.a given (must be positive)")
}
else{
mcmc.par$k.overrelax.a <- 1
}
tmp <- match("iter", ininit, nomatch=NA)
if(is.na(tmp)) init$iter <- 0
if (is.na(init$iter)) init$iter <- 0
else init$iter <- init$iter[1]
tmp <- match("lambda", ininit, nomatch=NA)
if(is.na(tmp)) stop("Initial lambda must be given")
if (prior$equal.lambda) init$lambda <- rep(init$lambda[1], dim)
else init$lambda <- init$lambda[1:dim]
if (sum(is.na(init$lambda))) stop("Incorrect init$lambda given")
if (sum(init$lambda <= 0)) stop("init$lambda must be positive")
tmp <- match("sigma", ininit, nomatch=NA)
if(is.na(tmp)){
if (prior$specification == 2) init$sigma <- rep(0.2, dim)
else stop("Initial sigma (basis std. deviation) must be given")
}
init$sigma <- init$sigma[1:dim]
if (sum(is.na(init$sigma))) stop("Incorrect init$sigma given")
if (sum(init$sigma <= 0)) stop("init$sigma must be positive")
tmp <- match("gamma", ininit, nomatch=NA)
if(is.na(tmp)){
if (prior$specification == 2) init$gamma <- rep(0, dim)
else stop("Initial gamma must be given")
}
init$gamma <- init$gamma[1:dim]
if (sum(is.na(init$gamma))) stop("Incorrect init$gamma given")
tmp <- match("scale", ininit, nomatch=NA)
if(is.na(tmp)){
if (prior$specification == 1) init$scale <- rep(1, dim)
else stop("Initial scale must be given")
}
if (prior$specification == 1) init$scale <- rep(1, dim)
init$scale <- init$scale[1:dim]
if (sum(is.na(init$scale))) stop("Incorrect init$scale given")
if (sum(init$scale <= 0)) stop("init$scale must be positive")
tmp <- match("intercept", ininit, nomatch=NA)
if(is.na(tmp)){
if (prior$specification == 1) init$intercept <- rep(0, dim)
else stop("Initial intercept must be given")
}
if (prior$specification == 1) init$intercept <- rep(0, dim)
init$intercept <- init$intercept[1:dim]
if (sum(is.na(init$intercept))) stop("Incorrect init$intercept given")
aconstraint <- "reference"
aconstraint <- pmatch(aconstraint, table=c("mean", "reference"), nomatch=0)-1
if (aconstraint < 0) stop("Unimplemented identifiability constraint for a coefficients")
tmp <- match("a", ininit, nomatch=NA)
if(is.na(tmp) | (!is.na(tmp) & !length(init$a))){
acoef <- list()
for (j in 1:dim){
if (prior$K[j] == 0){
acoef[[j]] <- 0
}else{
delta <- prior$c4delta[j] * init$sigma[j]
range <- delta * 2 * prior$K[j]
delta2 <- (8/range) * delta
knots <- seq(-prior$K[j], prior$K[j], by = 1) * delta2
sdspline <- delta2 / prior$c4delta[j]
if (sdspline >= 0.95) sdspline <- 0.95
minp <- minPenalty(knots = knots, sdspline = sdspline, difforder = 3, info = FALSE)
if (minp$fail) stop("Unable to guess initial 'a' coefficients, give your own")
acoef[[j]] <- minp$spline[, "a coef."]
if (aconstraint == "mean"){
acoef[[j]] <- as.vector(acoef[[j]] - mean(acoef[[j]]))
}
else{
acoef[[j]] <- as.vector(acoef[[j]] - acoef[[j]][prior$izero[j] + prior$K[j] + 1])
}
}
}
if (dim == 1){ init$a <- acoef[[1]] }
else{ if (dim == 2){ init$a <- outer(acoef[[1]], acoef[[2]], "+") }
else { stop("Unimplemented dimension appeared in bayesHistogram.priorInit()") }
}
}
total.length <- ifelse(dim == 1, 2*prior$K[1] + 1,
(2*prior$K[1] + 1)*(2*prior$K[2] + 1))
init$a <- init$a[1:total.length]
if (sum(is.na(init$a))) stop("Incorrect init$a given")
total.izero <- ifelse(dim == 1, prior$izero[1] + prior$K[1] + 1,
(prior$izero[2]+prior$K[2])*(2*prior$K[1]+1) + prior$izero[1]+prior$K[1]+1)
acoef <- as.vector(init$a)
if (dim == 2) init$a <- matrix(init$a, nrow=2*prior$K[1] + 1, ncol=2*prior$K[2] + 1)
Gparmi <- c(dim, neighbor.system, equal.lambda, prior$K, prior$izero, prior$order, prior.lambda, prior.gamma, prior.sigma,
prior.intercept, prior.scale,
type.update.a, mcmc.par$k.overrelax.a, mcmc.par$k.overrelax.sigma, mcmc.par$k.overrelax.scale,
aconstraint)
names(Gparmi) <- c("dim", "neighbor.system", "equal.lambda", paste("K", 1:dim, sep=""),
paste("izeroR", 1:dim, sep=""), "order",
paste("prior.for.lambda", 1:dim, sep=""),
paste("prior.for.gamma", 1:dim, sep=""),
paste("prior.for.sigma", 1:dim, sep=""),
paste("prior.for.intercept", 1:dim, sep=""),
paste("prior.for.scale", 1:dim, sep=""),
"type.update.a", "k.overrelax.a",
paste("k.overrelax.sigma", 1:dim, sep=""),
paste("k.overrelax.scale", 1:dim, sep=""),
"aconstraint")
Gparmd <- c(acoef, init$lambda, init$gamma, init$sigma, init$intercept, init$scale,
prior$c4delta, parms.lambda, parms.gamma, parms.sigma, parms.intercept, parms.scale)
names(Gparmd) <- c(paste("a", 1:total.length, sep=""), paste("lambda", 1:dim, sep=""),
paste("gamma", 1:dim, sep=""), paste("sigma", 1:dim, sep=""),
paste("intercept", 1:dim, sep=""), paste("scale", 1:dim, sep=""),
paste("c4delta", 1:dim, sep=""),
paste(c("shape.lambda", "rate.lambda"), rep(1:dim, rep(2, dim)), sep=""),
paste(c("mean.gamma", "var.gamma"), rep(1:dim, rep(2, dim)), sep=""),
paste(c("shape.sigma", "rate.sigma"), rep(1:dim, rep(2, dim)), sep=""),
paste(c("mean.intercept", "var.intercept"), rep(1:dim, rep(2, dim)), sep=""),
paste(c("shape.scale", "rate.scale"), rep(1:dim, rep(2, dim)), sep=""))
toreturn <- list(Gparmi = Gparmi, Gparmd = Gparmd, specification=prior$specification)
attr(toreturn, "init") <- init
attr(toreturn, "prior") <- prior
attr(toreturn, "mcmc.par") <- mcmc.par
return(toreturn)
} |
context("Test bandit4arm2_kalman_filter")
library(hBayesDM)
test_that("Test bandit4arm2_kalman_filter", {
skip_on_cran()
expect_output(bandit4arm2_kalman_filter(
data = "example", niter = 10, nwarmup = 5, nchain = 1, ncore = 1))
}) |
test.print <-
function()
{
NA
} |
funnel.default <- function(x, vi, sei, ni, subset, yaxis="sei", xlim, ylim, xlab, ylab,
steps=5, at, atransf, targs, digits, level=95,
back="lightgray", shade="white", hlines="white",
refline=0, lty=3, pch, col, bg,
label=FALSE, offset=0.4, legend=FALSE, ...) {
mstyle <- .get.mstyle("crayon" %in% .packages())
na.act <- getOption("na.action")
if (!is.element(na.act, c("na.omit", "na.exclude", "na.fail", "na.pass")))
stop(mstyle$stop("Unknown 'na.action' specified under options()."))
if (missing(subset))
subset <- NULL
yaxis <- match.arg(yaxis, c("sei", "vi", "seinv", "vinv", "ni", "ninv", "sqrtni", "sqrtninv", "lni", "wi"))
if (missing(atransf))
atransf <- FALSE
atransf.char <- deparse(atransf)
if (missing(pch))
pch <- 19
yi <- x
k <- length(yi)
if (missing(ni))
ni <- NULL
if (is.element(yaxis, c("ni", "ninv", "sqrtni", "sqrtninv", "lni"))) {
if (is.null(ni) && !is.null(attr(yi, "ni")))
ni <- attr(yi, "ni")
if (!is.null(ni) && length(ni) != k)
stop(mstyle$stop("Sample size information not of same length as data."))
if (is.null(ni))
stop(mstyle$stop("No sample size information available."))
}
if (missing(vi))
vi <- NULL
if (is.function(vi))
stop(mstyle$stop("Cannot find variable specified for 'vi' argument."), call.=FALSE)
if (missing(sei))
sei <- NULL
if (is.null(vi)) {
if (!is.null(sei))
vi <- sei^2
}
if (is.null(sei)) {
if (!is.null(vi))
sei <- sqrt(vi)
}
if (is.element(yaxis, c("sei", "vi", "seinv", "vinv", "wi"))) {
if (is.null(vi))
stop(mstyle$stop("Must specify 'vi' or 'sei' argument."))
if (length(vi) != k)
stop(mstyle$stop("Length of 'yi' and 'vi' (or 'sei') is not the same."))
}
if (!is.null(vi))
vi[vi < 0] <- 0
if (!is.null(sei))
sei[sei < 0] <- 0
slab <- attr(yi, "slab")
if (is.null(slab) || length(slab) != k)
slab <- seq_along(yi)
if (missing(ylab)) {
if (yaxis == "sei")
ylab <- "Standard Error"
if (yaxis == "vi")
ylab <- "Variance"
if (yaxis == "seinv")
ylab <- "Inverse Standard Error"
if (yaxis == "vinv")
ylab <- "Inverse Variance"
if (yaxis == "ni")
ylab <- "Sample Size"
if (yaxis == "ninv")
ylab <- "Inverse Sample Size"
if (yaxis == "sqrtni")
ylab <- "Square Root Sample Size"
if (yaxis == "sqrtninv")
ylab <- "Inverse Square Root Sample Size"
if (yaxis == "lni")
ylab <- "Log Sample Size"
if (yaxis == "wi")
ylab <- "Weight (in %)"
}
if (missing(at))
at <- NULL
if (missing(targs))
targs <- NULL
if (missing(digits)) {
if (yaxis == "sei")
digits <- c(2L,3L)
if (yaxis == "vi")
digits <- c(2L,3L)
if (yaxis == "seinv")
digits <- c(2L,3L)
if (yaxis == "vinv")
digits <- c(2L,3L)
if (yaxis == "ni")
digits <- c(2L,0L)
if (yaxis == "ninv")
digits <- c(2L,3L)
if (yaxis == "sqrtni")
digits <- c(2L,3L)
if (yaxis == "sqrtninv")
digits <- c(2L,3L)
if (yaxis == "lni")
digits <- c(2L,3L)
if (yaxis == "wi")
digits <- c(2L,2L)
} else {
if (length(digits) == 1L)
digits <- c(digits,digits)
}
if (length(lty) == 1L)
lty <- rep(lty, 2L)
if (length(pch) == 1L) {
pch.vec <- FALSE
pch <- rep(pch, k)
} else {
pch.vec <- TRUE
}
if (length(pch) != k)
stop(mstyle$stop(paste0("Length of the 'pch' argument (", length(pch), ") does not correspond to the number of outcomes (", k, ").")))
if (missing(col))
col <- "black"
if (length(col) == 1L) {
col.vec <- FALSE
col <- rep(col, k)
} else {
col.vec <- TRUE
}
if (length(col) != k)
stop(mstyle$stop(paste0("Length of the 'col' argument (", length(col), ") does not correspond to the number of outcomes (", k, ").")))
if (missing(bg))
bg <- "white"
if (length(bg) == 1L) {
bg.vec <- FALSE
bg <- rep(bg, k)
} else {
bg.vec <- TRUE
}
if (length(bg) != k)
stop(mstyle$stop(paste0("Length of the 'bg' argument (", length(bg), ") does not correspond to the number of outcomes (", k, ").")))
if (length(label) != 1L)
stop(mstyle$stop("Argument 'label' should be of length 1."))
ddd <- list(...)
if (!is.null(ddd$transf))
warning("Function does not have a 'transf' argument (use 'atransf' instead).", call.=FALSE)
lplot <- function(..., refline2, level2, lty2, transf, ci.res) plot(...)
labline <- function(..., refline2, level2, lty2, transf, ci.res) abline(...)
lsegments <- function(..., refline2, level2, lty2, transf, ci.res) segments(...)
laxis <- function(..., refline2, level2, lty2, transf, ci.res) axis(...)
lpolygon <- function(..., refline2, level2, lty2, transf, ci.res) polygon(...)
llines <- function(..., refline2, level2, lty2, transf, ci.res) lines(...)
lpoints <- function(..., refline2, level2, lty2, transf, ci.res) points(...)
lrect <- function(..., refline2, level2, lty2, transf, ci.res) rect(...)
ltext <- function(..., refline2, level2, lty2, transf, ci.res) text(...)
if (!is.null(ddd$refline2)) {
refline2 <- ddd$refline2
} else {
refline2 <- NULL
}
if (!is.null(ddd$level2)) {
level2 <- ddd$level2
} else {
level2 <- 95
}
if (!is.null(ddd$lty2)) {
lty2 <- ddd$lty2
} else {
lty2 <- 3
}
if (!is.null(ddd$ci.res)) {
ci.res <- ddd$ci.res
} else {
ci.res <- 1000
}
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=length(yi))
yi <- yi[subset]
vi <- vi[subset]
sei <- sei[subset]
ni <- ni[subset]
slab <- slab[subset]
pch <- pch[subset]
col <- col[subset]
bg <- bg[subset]
}
has.na <- is.na(yi) | (if (is.element(yaxis, c("vi", "vinv"))) is.na(vi) else FALSE) | (if (is.element(yaxis, c("sei", "seinv"))) is.na(vi) else FALSE) | (if (is.element(yaxis, c("ni", "ninv", "sqrtni", "sqrtninv", "lni"))) is.na(ni) else FALSE)
if (any(has.na)) {
not.na <- !has.na
if (na.act == "na.omit" || na.act == "na.exclude" || na.act == "na.pass") {
yi <- yi[not.na]
vi <- vi[not.na]
sei <- sei[not.na]
ni <- ni[not.na]
slab <- slab[not.na]
pch <- pch[not.na]
col <- col[not.na]
bg <- bg[not.na]
}
if (na.act == "na.fail")
stop(mstyle$stop("Missing values in data."))
}
if (missing(xlab))
xlab <- .setlab(attr(yi, "measure"), transf.char="FALSE", atransf.char, gentype=1)
if (length(yi) < 2L)
stop(mstyle$stop("Plotting terminated since k < 2."))
if (yaxis == "wi") {
if (any(vi <= 0))
stop(mstyle$stop("Cannot plot weights when there are non-positive sampling variances in the data."))
weights <- 1/vi
weights <- weights / sum(weights) * 100
}
if (missing(ylim)) {
if (yaxis == "sei")
ylim <- c(max(sei), 0)
if (yaxis == "vi")
ylim <- c(max(vi), 0)
if (yaxis == "seinv")
ylim <- c(min(1/sei), max(1/sei))
if (yaxis == "vinv")
ylim <- c(min(1/vi), max(1/vi))
if (yaxis == "ni")
ylim <- c(min(ni), max(ni))
if (yaxis == "ninv")
ylim <- c(max(1/ni), min(1/ni))
if (yaxis == "sqrtni")
ylim <- c(min(sqrt(ni)), max(sqrt(ni)))
if (yaxis == "sqrtninv")
ylim <- c(max(1/sqrt(ni)), min(1/sqrt(ni)))
if (yaxis == "lni")
ylim <- c(min(log(ni)), max(log(ni)))
if (yaxis == "wi")
ylim <- c(min(weights), max(weights))
if (any(is.infinite(ylim)))
stop(mstyle$stop("Setting 'ylim' automatically not possible (must set y-axis limits manually)."))
} else {
if (is.element(yaxis, c("sei", "vi", "ninv", "sqrtninv")))
ylim <- c(max(ylim), min(ylim))
if (is.element(yaxis, c("seinv", "vinv", "ni", "sqrtni", "lni", "wi")))
ylim <- c(min(ylim), max(ylim))
if (is.element(yaxis, c("sei", "vi", "ni", "ninv", "sqrtni", "sqrtninv", "lni"))) {
if (ylim[1] < 0 || ylim[2] < 0)
stop(mstyle$stop("Both y-axis limits must be >= 0."))
}
if (is.element(yaxis, c("seinv", "vinv"))) {
if (ylim[1] <= 0 || ylim[2] <= 0)
stop(mstyle$stop("Both y-axis limits must be > 0."))
}
if (is.element(yaxis, c("wi"))) {
if (ylim[1] < 0 || ylim[2] < 0)
stop(mstyle$stop("Both y-axis limits must be >= 0."))
}
}
if (is.element(yaxis, c("sei", "vi", "seinv", "vinv"))) {
level <- ifelse(level == 0, 1, ifelse(level >= 1, (100-level)/100, ifelse(level > .5, 1-level, level)))
level2 <- ifelse(level2 == 0, 1, ifelse(level2 >= 1, (100-level2)/100, ifelse(level2 > .5, 1-level2, level2)))
level.min <- min(level)
lvals <- length(level)
if (yaxis == "sei") {
x.lb.bot <- refline - qnorm(level.min/2, lower.tail=FALSE) * sqrt(ylim[1]^2)
x.ub.bot <- refline + qnorm(level.min/2, lower.tail=FALSE) * sqrt(ylim[1]^2)
}
if (yaxis == "vi") {
x.lb.bot <- refline - qnorm(level.min/2, lower.tail=FALSE) * sqrt(ylim[1])
x.ub.bot <- refline + qnorm(level.min/2, lower.tail=FALSE) * sqrt(ylim[1])
}
if (yaxis == "seinv") {
x.lb.bot <- refline - qnorm(level.min/2, lower.tail=FALSE) * sqrt(1/ylim[1]^2)
x.ub.bot <- refline + qnorm(level.min/2, lower.tail=FALSE) * sqrt(1/ylim[1]^2)
}
if (yaxis == "vinv") {
x.lb.bot <- refline - qnorm(level.min/2, lower.tail=FALSE) * sqrt(1/ylim[1])
x.ub.bot <- refline + qnorm(level.min/2, lower.tail=FALSE) * sqrt(1/ylim[1])
}
if (missing(xlim)) {
xlim <- c(min(x.lb.bot,min(yi)), max(x.ub.bot,max(yi)))
rxlim <- xlim[2] - xlim[1]
xlim[1] <- xlim[1] - (rxlim * 0.10)
xlim[2] <- xlim[2] + (rxlim * 0.10)
} else {
xlim <- sort(xlim)
}
}
if (is.element(yaxis, c("ni", "ninv", "sqrtni", "sqrtninv", "lni", "wi"))) {
if (missing(xlim)) {
xlim <- c(min(yi), max(yi))
rxlim <- xlim[2] - xlim[1]
xlim[1] <- xlim[1] - (rxlim * 0.10)
xlim[2] <- xlim[2] + (rxlim * 0.10)
} else {
xlim <- sort(xlim)
}
}
if (!is.null(at)) {
xlim[1] <- min(c(xlim[1], at), na.rm=TRUE)
xlim[2] <- max(c(xlim[2], at), na.rm=TRUE)
}
lplot(NA, NA, xlim=xlim, ylim=ylim, xlab=xlab, ylab=ylab, xaxt="n", yaxt="n", bty="n", ...)
par.usr <- par("usr")
lrect(par.usr[1], par.usr[3], par.usr[2], par.usr[4], col=back, border=NA, ...)
laxis(side=2, at=seq(from=ylim[1], to=ylim[2], length.out=steps), labels=formatC(seq(from=ylim[1], to=ylim[2], length.out=steps), digits=digits[[2]], format="f", drop0trailing=is.integer(digits[[2]])), ...)
labline(h=seq(from=ylim[1], to=ylim[2], length.out=steps), col=hlines, ...)
if (is.element(yaxis, c("sei", "vi", "seinv", "vinv"))) {
if (yaxis == "sei") {
rylim <- ylim[1] - ylim[2]
ylim[1] <- ylim[1] + (rylim * 0.10)
ylim[2] <- max(0, ylim[2] - (rylim * 0.10))
}
if (yaxis == "vi") {
rylim <- ylim[1] - ylim[2]
ylim[1] <- ylim[1] + (rylim * 0.10)
ylim[2] <- max(0, ylim[2] - (rylim * 0.10))
}
if (yaxis == "seinv") {
rylim <- ylim[2] - ylim[1]
ylim[2] <- ylim[2] + (rylim * 0.10)
}
if (yaxis == "vinv") {
rylim <- ylim[2] - ylim[1]
ylim[2] <- ylim[2] + (rylim * 0.10)
}
yi.vals <- seq(from=ylim[1], to=ylim[2], length.out=ci.res)
if (yaxis == "sei")
vi.vals <- yi.vals^2
if (yaxis == "vi")
vi.vals <- yi.vals
if (yaxis == "seinv")
vi.vals <- 1/yi.vals^2
if (yaxis == "vinv")
vi.vals <- 1/yi.vals
for (m in lvals:1) {
ci.left <- refline - qnorm(level[m]/2, lower.tail=FALSE) * sqrt(vi.vals)
ci.right <- refline + qnorm(level[m]/2, lower.tail=FALSE) * sqrt(vi.vals)
lpolygon(c(ci.left,ci.right[ci.res:1]), c(yi.vals,yi.vals[ci.res:1]), border=NA, col=shade[m], ...)
llines(ci.left, yi.vals, lty=lty[1], ...)
llines(ci.right, yi.vals, lty=lty[1], ...)
}
if (!is.null(refline2)) {
ci.left <- refline2 - qnorm(level2/2, lower.tail=FALSE) * sqrt(vi.vals)
ci.right <- refline2 + qnorm(level2/2, lower.tail=FALSE) * sqrt(vi.vals)
llines(ci.left, yi.vals, lty=lty2, ...)
llines(ci.right, yi.vals, lty=lty2, ...)
}
}
if (is.element(yaxis, c("sei", "vi", "seinv", "vinv")))
lsegments(refline, ylim[1], refline, ylim[2], lty=lty[2], ...)
if (is.element(yaxis, c("ni", "ninv", "sqrtni", "sqrtninv", "lni", "wi")))
labline(v=refline, lty=lty[2], ...)
xaxis.vals <- yi
if (yaxis == "sei")
yaxis.vals <- sei
if (yaxis == "vi")
yaxis.vals <- vi
if (yaxis == "seinv")
yaxis.vals <- 1/sei
if (yaxis == "vinv")
yaxis.vals <- 1/vi
if (yaxis == "ni")
yaxis.vals <- ni
if (yaxis == "ninv")
yaxis.vals <- 1/ni
if (yaxis == "sqrtni")
yaxis.vals <- sqrt(ni)
if (yaxis == "sqrtninv")
yaxis.vals <- 1/sqrt(ni)
if (yaxis == "lni")
yaxis.vals <- log(ni)
if (yaxis == "wi")
yaxis.vals <- weights
lpoints(x=xaxis.vals, y=yaxis.vals, pch=pch, col=col, bg=bg, ...)
box(bty="l")
if (is.null(at)) {
at <- axTicks(side=1)
} else {
at <- at[at > par("usr")[1]]
at <- at[at < par("usr")[2]]
}
at.lab <- at
if (is.function(atransf)) {
if (is.null(targs)) {
at.lab <- formatC(sapply(at.lab, atransf), digits=digits[[1]], format="f", drop0trailing=is.integer(digits[[1]]))
} else {
at.lab <- formatC(sapply(at.lab, atransf, targs), digits=digits[[1]], format="f", drop0trailing=is.integer(digits[[1]]))
}
} else {
at.lab <- formatC(at.lab, digits=digits[[1]], format="f", drop0trailing=is.integer(digits[[1]]))
}
laxis(side=1, at=at, labels=at.lab, ...)
k <- length(yi)
if (is.numeric(label) || is.character(label) || .isTRUE(label)) {
if (is.numeric(label)) {
label <- round(label)
if (label < 0)
label <- 0
if (label > k)
label <- k
label <- order(abs(yi - refline), decreasing=TRUE)[seq_len(label)]
} else if ((is.character(label) && label == "all") || .isTRUE(label)) {
label <- seq_len(k)
} else if ((is.character(label) && label == "out")) {
if (!is.element(yaxis, c("sei", "vi", "seinv", "vinv"))) {
label <- seq_len(k)
} else {
label <- which(abs(yi - refline) / sqrt(vi) >= qnorm(level.min/2, lower.tail=FALSE))
}
} else {
label <- NULL
}
for (i in label)
ltext(yi[i], yaxis.vals[i], slab[i], pos=ifelse(yi[i]-refline >= 0, 4, 2), offset=offset, ...)
}
if (is.logical(legend) && isTRUE(legend))
lpos <- "topright"
if (is.character(legend)) {
lpos <- legend
legend <- TRUE
}
if (legend && !is.element(yaxis, c("sei", "vi", "seinv", "vinv"))) {
legend <- FALSE
warning(mstyle$warning("Argument 'legend' only applicable if 'yaxis' is 'sei', 'vi', 'seinv', or 'vinv'."), call.=FALSE)
}
if (legend) {
level <- c(level, 0)
lvals <- length(level)
add.studies <- !pch.vec && !col.vec && !bg.vec
scipen <- options(scipen=100)
lchars <- max(nchar(level))-2
options(scipen=scipen$scipen)
pval1 <- NULL
pval2 <- NULL
phantom <- NULL
ltxt <- sapply(seq_len(lvals), function(i) {
if (i == 1)
return(as.expression(bquote(paste(.(pval1) < p, phantom() <= .(pval2)), list(pval1=.fcf(level[i], lchars), pval2=.fcf(1, lchars)))))
if (i > 1 && i < lvals)
return(as.expression(bquote(paste(.(pval1) < p, phantom() <= .(pval2)), list(pval1=.fcf(level[i], lchars), pval2=.fcf(level[i-1], lchars)))))
if (i == lvals)
return(as.expression(bquote(paste(.(pval1) < p, phantom() <= .(pval2)), list(pval1=.fcf(0, lchars), pval2=.fcf(level[i-1], lchars)))))
})
pch.l <- rep(22, lvals)
col.l <- rep("black", lvals)
pt.cex <- rep(2, lvals)
pt.bg <- c(shade, back)
if (add.studies) {
ltxt <- c(ltxt, expression(plain(Studies)))
pch.l <- c(pch.l, pch[1])
col.l <- c(col.l, col[1])
pt.cex <- c(pt.cex, 1)
pt.bg <- c(pt.bg, bg[1])
}
legend(lpos, inset=.01, bg="white", pch=pch.l, col=col.l, pt.cex=pt.cex, pt.bg=pt.bg, legend=ltxt)
}
sav <- data.frame(x=xaxis.vals, y=yaxis.vals, slab=slab, stringsAsFactors=FALSE)
invisible(sav)
} |
rm(list=ls())
library(tidyverse)
library(curl)
library(paletteer)
library(extrafont)
library(ragg)
theme_custom <- function() {
theme_classic() %+replace%
theme(plot.title.position="plot", plot.caption.position="plot",
strip.background=element_blank(), strip.text=element_text(face="bold", size=rel(1)),
plot.title=element_text(face="bold", size=rel(1.5), hjust=0,
margin=margin(0,0,5.5,0)),
text=element_text(family="Lato"))
}
temp <- tempfile()
url <- "https://api.coronavirus.data.gov.uk/v2/data?areaType=region&metric=vaccinationsAgeDemographics&format=csv"
temp <- curl_download(url=url, destfile=temp, quiet=FALSE, mode="wb")
data <- read.csv(temp) %>%
select(areaName, date, age, cumVaccinationFirstDoseUptakeByVaccinationDatePercentage) %>%
rename("uptake"="cumVaccinationFirstDoseUptakeByVaccinationDatePercentage") %>%
filter(age=="12_15" & date>as.Date("2021-08-01")) %>%
mutate(date=as.Date(date))
agg_tiff("Outputs/COVIDVaxUptake1215xReg.tiff", units="in", width=8, height=6, res=500)
ggplot(data, aes(x=date, y=uptake/100, colour=areaName))+
geom_line()+
scale_x_date(name="")+
scale_y_continuous(name="First dose coverage", labels=label_percent(accuracy=1))+
scale_colour_paletteer_d("LaCroixColoR::paired", name="")+
theme_custom()+
labs(title="There is big regional variation in 12-15 COVID vaccination rates",
subtitle="Vaccine uptake among 12-15 year-olds in England by region",
caption="Data from coronavirus.data.gov.uk | Plot by @VictimOfMaths")
dev.off()
|
sleep <- march.dataset.loadFromDataFrame(sleep_df, MARGIN = 2,
weights = NA, missingDataRep = NA)
sleep.5 <- march.dataset.loadFromDataFrame(sleep_df[,1:5], MARGIN = 2 ,
weights = NA, missingDataRep = NA)
weighting <- rep(1.5,1000)
weighting[501:1000] <- rep(0.5,500)
sleep.w <- march.dataset.loadFromDataFrame(sleep_df, MARGIN = 2,
weights = weighting, missingDataRep = NA)
covariates.sex<-rbind(matrix(1,500,7),matrix(1,500,7))
covariates.age<-rbind(matrix(1,250,7), matrix(2,250,7), matrix(1,250,7),
matrix(2,250,7))
covariates<-array(0,c(1000,7,2))
covariates[ , ,1]<-covariates.sex
covariates[ , ,2]<-covariates.age
sleep.covariates<-march.dataset.loadFromDataFrame(sleep_df,covariates=covariates) |
cat("\014")
rm(list = ls())
setwd("~/git/of_dollars_and_data")
source(file.path(paste0(getwd(),"/header.R")))
library(scales)
library(lubridate)
library(stringr)
library(ggrepel)
library(zoo)
library(lemon)
library(Hmisc)
library(readxl)
library(tidyverse)
folder_name <- "0175_absolute_price_movement"
out_path <- paste0(exportdir, folder_name)
dir.create(file.path(paste0(out_path)), showWarnings = FALSE)
dow <- read_excel(paste0(importdir, "0172_daily_dow/Dow daily 2020.xlsx"),
col_names = c("date", "index")) %>%
mutate(date = as.Date(date),
mt = month(date),
yr = year(date)) %>%
arrange(date) %>%
mutate(prior_index =lag(index),
ret = index/prior_index - 1) %>%
drop_na()
min_dates <- dow %>%
group_by(yr, mt) %>%
summarise(min_date = min(date)) %>%
ungroup() %>%
rename(date = min_date) %>%
inner_join(dow) %>%
rename(min_index = prior_index) %>%
select(yr, mt, min_index)
min_max <- dow %>%
group_by(yr, mt) %>%
summarise(max_date = max(date)) %>%
ungroup() %>%
rename(date = max_date) %>%
inner_join(dow) %>%
rename(max_index = index) %>%
select(yr, mt, max_index) %>%
left_join(min_dates) %>%
mutate(mt_ret = max_index/min_index - 1) %>%
arrange(mt_ret)
summary <- dow %>%
group_by(yr, mt) %>%
summarise(abs_ret = sum(abs(ret), na.rm = TRUE),
n_days = n(),
avg_abs_ret = abs_ret/n_days) %>%
ungroup() %>%
arrange(-abs_ret)
to_plot <- summary %>%
mutate(date = as.Date(
paste0(
yr,
"-",
mt,
"-01"
)
))
excel_out <- to_plot %>%
arrange(date) %>%
select(date, avg_abs_ret)
export_to_excel(excel_out,
outfile = paste0(out_path, "/avg_abs_monthly_change_dow.xlsx"),
sheetname = "dow_avg_month",
new_file = 1,
fancy_formatting = 0)
mean_ret <- mean(summary$abs_ret)
source_string <- str_wrap("Source: Bloomberg (OfDollarsAndData.com)",
width = 85)
note_string <- str_wrap(paste0("Note: Dow price data does not include dividends. ",
"The average cumulative absolute percentage change in a given month is ",
round(100*mean_ret, 1),
"%."),
width = 85)
file_path <- paste0(out_path, "/dow_abs_ret_by_month.jpeg")
plot <- ggplot(to_plot, aes(x=date, y=abs_ret)) +
geom_bar(stat = "identity", width = 31) +
scale_y_continuous(label = percent_format(accuracy = 1)) +
of_dollars_and_data_theme +
ggtitle(paste0("Dow Cumulative Absolute Percentage Change\nby Month")) +
labs(x = "Date" , y = "Cumulative Absolute Percentage Change",
caption = paste0("\n", source_string, "\n", note_string))
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
to_plot <- dow %>%
filter(yr == 2020, mt == 3)
file_path <- paste0(out_path, "/dow_2020_03_breaks.jpeg")
note_string <- str_wrap(paste0("Note: Dow price data does not include dividends. "),
width = 85)
plot <- ggplot(to_plot, aes(x=date, y=ret)) +
geom_bar(stat = "identity", width = 1, fill = chart_standard_color) +
scale_y_continuous(label = percent_format(accuracy = 1), limits = c(-0.15, 0.15),
breaks = seq(-0.15, 0.15, 0.05)) +
of_dollars_and_data_theme +
ggtitle(paste0("Dow Daily Percentage Change\nMarch 2020")) +
labs(x = "Date" , y = "Daily Percentage Change",
caption = paste0("\n", source_string, "\n", note_string))
ggsave(file_path, plot, width = 15, height = 12, units = "cm")
jan_2020 <- dow %>%
filter(yr == 2020, mt == 1) %>%
mutate(label = "Jan 2020")
to_plot <- to_plot %>%
mutate(label = "Mar 2020") %>%
bind_rows(jan_2020)
file_path <- paste0(out_path, "/dow_2020_01_compare.jpeg")
note_string <- str_wrap(paste0("Note: Dow price data does not include dividends. "),
width = 85)
plot <- ggplot(to_plot, aes(x=date, y=ret)) +
geom_bar(stat = "identity", width = 1, fill = chart_standard_color) +
facet_rep_wrap(label ~ ., scales = "free_x", repeat.tick.labels = c("left", "bottom")) +
scale_y_continuous(label = percent_format(accuracy = 1), limits = c(-0.15, 0.15),
breaks = seq(-0.15, 0.15, 0.05)) +
of_dollars_and_data_theme +
ggtitle(paste0("Dow Daily Percentage Change")) +
labs(x = "Date" , y = "Daily Percentage Change",
caption = paste0("\n", source_string, "\n", note_string))
ggsave(file_path, plot, width = 15, height = 12, units = "cm") |
context("niche overlap and species fitness functions")
data("neigh_list")
data <- neigh_list
for(i in 1:length(data)){
data[[i]] <- data[[i]][,2:length(data[[i]])]
}
focal_column <- names(data)
data("salinity_list")
salinity <- salinity_list
for(i in 1:length(salinity)){
salinity[[i]] <- as.matrix(salinity[[i]][,2:length(salinity[[i]])])
colnames(salinity[[i]]) <- "salinity"
}
model_families <- c("BH","LV","RK","LW")
covariates <- salinity
optimization_method <- "nlminb"
alpha_form <- "pairwise"
lambda_cov_form <- "none"
alpha_cov_form <- "none"
initial_values = list(lambda = 1,
alpha_intra = 0.1,
alpha_inter = 0.1,
lambda_cov = 0.1,
alpha_cov = 0.1)
lower_bounds = list(lambda = 0,
alpha_intra = 0.01,
alpha_inter = 0,
lambda_cov = -1,
alpha_cov = -1)
upper_bounds = list(lambda = 100,
alpha_intra = 1,
alpha_inter = 1,
lambda_cov = 1,
alpha_cov = 1)
initial_values_er = list(lambda = 1,effect = 0.01,response = 0.01)
lower_bounds_er = list(lambda = 0,effect = 0,response = 0)
upper_bounds_er = list(lambda = 100,effect = 1,response = 1)
fixed_terms <- NULL
bootstrap_samples <- 3
sp1.fit <- cxr::cxr_pm_fit(data = data[[1]],
focal_column = focal_column[1],
model_family = model_families[1],
covariates = covariates[[1]],
optimization_method = optimization_method,
alpha_form = alpha_form,
lambda_cov_form = lambda_cov_form,
alpha_cov_form = alpha_cov_form,
initial_values = initial_values,
lower_bounds = lower_bounds,
upper_bounds = upper_bounds,
fixed_terms = fixed_terms,
bootstrap_samples = bootstrap_samples)
sp2.fit <- cxr::cxr_pm_fit(data = data[[2]],
focal_column = focal_column[2],
model_family = model_families[1],
covariates = covariates[[2]],
optimization_method = optimization_method,
alpha_form = alpha_form,
lambda_cov_form = lambda_cov_form,
alpha_cov_form = alpha_cov_form,
initial_values = initial_values,
lower_bounds = lower_bounds,
upper_bounds = upper_bounds,
fixed_terms = fixed_terms,
bootstrap_samples = bootstrap_samples)
cxr_multifit <- cxr_pm_multifit(data = data,
model_family = model_families[1],
focal_column = focal_column,
covariates = covariates,
optimization_method = optimization_method,
alpha_form = alpha_form,
lambda_cov_form = lambda_cov_form,
alpha_cov_form = alpha_cov_form,
initial_values = initial_values,
lower_bounds = lower_bounds,
upper_bounds = upper_bounds,
fixed_terms = fixed_terms,
bootstrap_samples = bootstrap_samples)
posmatrix <- matrix(c(runif(1,0.5,1),runif(2,0,0.5),runif(1,0.5,1)),nrow = 2)
poslambdas <- runif(2,1,10)
model_family <- "BH"
test_that("niche overlaps are correctly calculated", {
expect_s3_class(niche_overlap(cxr_multifit = cxr_multifit),"data.frame")
expect_length(niche_overlap(cxr_sp1 = sp1.fit,cxr_sp2 = sp2.fit),2)
expect_length(niche_overlap(pair_matrix = posmatrix),2)
})
test_that("average fitness differenes are correctly calculated", {
expect_s3_class(avg_fitness_diff(cxr_multifit = cxr_multifit),"data.frame")
expect_s3_class(avg_fitness_diff(cxr_sp1 = sp1.fit,
cxr_sp2 = sp2.fit),"data.frame")
expect_s3_class(avg_fitness_diff(pair_lambdas = poslambdas,
pair_matrix = posmatrix,
model_family = model_family),"data.frame")
})
test_that("competitive ability is correctly calculated", {
expect_s3_class(competitive_ability(cxr_multifit = cxr_multifit),"data.frame")
expect_s3_class(competitive_ability(cxr_sp1 = sp1.fit,
cxr_sp2 = sp2.fit),"data.frame")
expect_s3_class(competitive_ability(lambda = poslambdas[1],
pair_matrix = posmatrix,
model_family = model_family),"data.frame")
})
data("neigh_list")
example_sp <- c(1,5,6)
n.obs <- 250
data <- neigh_list[example_sp]
optimization_method <- "nlminb"
fixed_terms <- NULL
model_families <- c("BH","LV","RK","LW")
bootstrap_samples <- 0
for(i in 1:length(data)){
data[[i]] <- data[[i]][1:n.obs,c(2,example_sp+2)]
}
initial_values_er = list(lambda = 1,
effect = 1,
response = 1)
lower_bounds_er = list(lambda = 0,
effect = 0,
response = 0)
upper_bounds_er = list(lambda = 100,
effect = 10,
response = 10)
iv_LV <- list(lambda = 1,
effect = 0,
response = 0)
lb_LV = list(lambda = 0,
effect = -1,
response = -1)
ub_LV = list(lambda = 100,
effect = 1,
response = 1)
test_that("species fitness are correctly calculated", {
skip_on_cran()
for(i.model in 1:length(model_families)){
if(model_families[i.model] == "LV"){
iv <- iv_LV
lb <- lb_LV
ub <- ub_LV
}else{
iv <- initial_values_er
lb <- lower_bounds_er
ub <- upper_bounds_er
}
er.fit <- cxr::cxr_er_fit(data = data,
model_family = model_families[i.model],
optimization_method = optimization_method,
initial_values = iv,
lower_bounds = lb,
upper_bounds = ub,
fixed_terms = fixed_terms,
bootstrap_samples = bootstrap_samples)
spfitness <- cxr::species_fitness(er.fit)
expect_length(spfitness,length(data))
}
}) |
library(uwot)
context("PCA")
iris10prcomp <- prcomp(iris10, retx = TRUE, center = TRUE, scale. = FALSE)
test_that("PCA initialization", {
iris10_pca_scores <- pca_init(iris10, ndim = 2)
suppressWarnings(iris10_irlba_scores <- irlba_scores(iris10, ncol = 2))
expect_equal(abs(iris10prcomp$x[, 1:2]), abs(iris10_pca_scores),
check.attributes = FALSE
)
expect_equal(abs(iris10prcomp$x[, 1:2]), abs(iris10_irlba_scores),
check.attributes = FALSE
)
suppressWarnings(iris10_svdr_scores <- irlba_svdr_scores(iris10, ncol = 2))
expect_equal(abs(iris10prcomp$x[, 1:2]), abs(iris10_svdr_scores),
check.attributes = FALSE
)
})
test_that("1 component initialization works", {
expect_ok_matrix(pca_init(iris10, ndim = 1), nc = 1)
})
test_that("PCA returns model data", {
iris10_pca_scores <- pca_init(iris10, ndim = 2, ret_extra = TRUE)
expect_equal(abs(iris10prcomp$x[, 1:2]),
abs(iris10_pca_scores$scores),
check.attributes = FALSE
)
expect_equal(abs(iris10prcomp$rotation[, 1:2]),
abs(iris10_pca_scores$rotation),
check.attributes = FALSE
)
expect_equal(abs(iris10prcomp$center),
abs(iris10_pca_scores$center),
check.attributes = FALSE
)
suppressWarnings(iris10_irlba_scores <- irlba_scores(iris10,
ncol = 2,
ret_extra = TRUE
))
expect_equal(abs(iris10prcomp$x[, 1:2]),
abs(iris10_irlba_scores$scores),
check.attributes = FALSE
)
expect_equal(abs(iris10prcomp$rotation[, 1:2]),
abs(iris10_irlba_scores$rotation),
check.attributes = FALSE
)
expect_equal(abs(iris10prcomp$center),
abs(iris10_irlba_scores$center),
check.attributes = FALSE
)
}) |
pimplot <-
function(data = NULL,
results,
outcome,
incl.tt=NULL,
ttrows= c(),
necessity=FALSE,
sol=1,
all_labels=FALSE,
markers = TRUE,
labcol="black",
jitter = FALSE,
font = "sans",
fontface = "italic",
fontsize = 3,
crisp = FALSE,
consH = FALSE,
...)
{
dots <- list(...)
if(length(dots) != 0){
if ("neg.out" %in% names(dots)){print("Argument neg.out is deprecated. The negated outcome is identified automatically from the minimize solution.")}
if ("use.tilde" %in% names(dots)){print("Argument use.tilde is deprecated. The usage of the tilde is identified automatically from the minimize solution.")}
}
if(length(grep("~",outcome)) > 0){
outcome<-outcome[grep("~",outcome)]
outcome<-gsub('\\~', '', outcome)
outcome<-unlist(outcome)}
outcome <- toupper(outcome)
if (!necessity){
data <- results$tt$initial.data
if (is.null(incl.tt)) {
if (length(ttrows)>0){
oldtt <- results$tt$tt
newtt <- oldtt[ttrows, ]
P <- as.data.frame(results$tt$minmat)
P <- P[colnames(P)%in%rownames(newtt)]
if (results$options$neg.out | length(grep("~",results$call$outcome)) > 0) {
neg.out = TRUE
P$out <- results$tt$recoded.data[,outcome]
} else {
neg.out = FALSE
P$out <- results$tt$recoded.data[,outcome]
}
n_c <- ncol(P)-1
par(ask=F)
aux.plot <-
function(i)
{ if (all_labels) {fil <- rownames(P)}
else {fil <- rownames(P)
fil[with(P, !(P[i] > 0.5))] <- ""}
if (!neg.out){
xy.plot(P[,i, drop=FALSE], 'out', data = P, xlab=paste("Row ", colnames(P)[i]), ylab=outcome, main="Sufficiency Plot",
labcol=labcol,
jitter = jitter,
consH = consH,
font = font,
fontface = fontface,
fontsize = fontsize,
labs = fil,
crisp = crisp,
shape = if (markers == FALSE){19}
else{ifelse((P$out < 0.5 & P[,i, drop=FALSE]>0.5), 9, 19)})}
else {xy.plot(P[,i, drop=FALSE], 'out', data = P, xlab=paste("Row ", colnames(P)[i]), ylab=paste("~",outcome), main="Sufficiency Plot",
labcol=labcol,
jitter = jitter,
consH = consH,
font = font,
fontface = fontface,
fontsize = fontsize,
labs = fil,
crisp = crisp,
shape = if (markers == FALSE){19}
else{ifelse((P$out < 0.5 & P[,i, drop=FALSE]>0.5), 9, 19)})}
}
for (i in 1:n_c) {
print(aux.plot(i))
}
}
else {
P <- pimdata(results=results, outcome=outcome, sol=sol)
n_c <- ncol(P)-1
par(ask=F)
if (results$options$neg.out | length(grep("~",results$call$outcome)) > 0) {
neg.out = TRUE
} else {
neg.out = FALSE
}
aux.plot <-
function(i)
{ if (all_labels) {fil <- rownames(P)}
else {
fil <- rownames(P)
fil[with(P, !(P[i] > 0.5))] <- ""
if (i==n_c) { fil <- rownames(P)
fil[with(P, !(P[i] < 0.5))] <- "" }}
if (!neg.out){
xy.plot(P[,i, drop=FALSE], "out", data = P, xlab=colnames(P[i]), ylab=outcome, main="Sufficiency Plot",
labcol=labcol,
jitter = jitter,
consH = consH,
font = font,
fontface = fontface,
fontsize = fontsize,
labs = fil,
crisp = crisp,
shape = if (markers == FALSE){19}
else{ifelse((P$out < 0.5 & P[,i, drop=FALSE]>0.5), 9, 19)})}
else {xy.plot(P[,i, drop=FALSE], 'out', data = P, xlab=colnames(P)[i], ylab=paste("~",outcome), main="Sufficiency Plot",
labcol=labcol,
jitter = jitter,
consH = consH,
font = font,
fontface = fontface,
fontsize = fontsize,
labs = fil,
crisp = crisp,
shape = if (markers == FALSE){19}
else{ifelse((P$out < 0.5 & P[,i, drop=FALSE]>0.5), 9, 19)})}
}
for (i in 1:n_c) {
print(aux.plot(i))
}}}
else {
oldtt <- results$tt$tt
suppressWarnings(oldtt$incl <- as.numeric(oldtt$incl))
if (length(incl.tt)>1) {paste("You introduced more than one inclusion cut for Truth Table rows. Please introduce only one!")}
else {
newtt <- oldtt[ which(oldtt$incl>incl.tt), ]
P <- as.data.frame(results$tt$minmat)
P <- P[colnames(P)%in%rownames(newtt)]
if (results$options$neg.out | length(grep("~",results$call$outcome)) > 0) {
neg.out = TRUE
P$out <- results$tt$recoded.data[,outcome]
} else {
neg.out = FALSE
P$out <- results$tt$recoded.data[,outcome]
}
n_c <- ncol(P)-1
par(ask=F)
aux.plot <-
function(i)
{ if (all_labels) {fil <- rownames(P)}
else {fil <- rownames(P)
fil[with(P, !(P[i] > 0.5))] <- ""}
if (!neg.out){
xy.plot(P[,i, drop=FALSE], 'out', data = P, xlab=paste("Row ", colnames(P)[i]), ylab=outcome, main="Sufficiency Plot",
labcol=labcol,
jitter = jitter,
consH = consH,
font = font,
fontface = fontface,
fontsize = fontsize,
labs = fil,
crisp = crisp,
shape = if (markers == FALSE){19}
else{ifelse((P$out < 0.5 & P[,i, drop=FALSE]>0.5), 9, 19)})}
else {xy.plot(P[,i, drop=FALSE], 'out', data = P, xlab=paste("Row ", colnames(P)[i]), ylab=paste("~",outcome), main="Sufficiency Plot",
labcol=labcol,
jitter = jitter,
consH = consH,
font = font,
fontface = fontface,
fontsize = fontsize,
labs = fil,
crisp = crisp,
shape = if (markers == FALSE){19}
else{ifelse((P$out < 0.5 & P[,i, drop=FALSE]>0.5), 9, 19)})}
}
for (i in 1:n_c) {
print(aux.plot(i))
}}
}
}
else {
if (is.null(data)) stop ("For analyses of necessity you need to provide the name of the dataframe!")
P <- results$coms
if (results$options$neg.out) {
neg.out = TRUE
P$out <- 1-data[, outcome]
} else {
neg.out = FALSE
P$out <- data[, outcome]
}
n_c <- ncol(P)-1
par(ask=F)
aux.plot <-
function(i)
{ if (all_labels) {fil <- rownames(P)}
else {fil <- rownames(P)
fil[with(P, !(P[,'out'] > 0.5))] <- ""}
if (!neg.out){
xy.plot(P[,i, drop=FALSE], 'out', data = P, xlab=colnames(P)[i], ylab=outcome, necessity = TRUE, main="Necessity Plot",
labcol=labcol,
jitter = jitter,
font = font,
consH = consH,
fontface = fontface,
fontsize = fontsize,
labs = fil,
crisp = crisp,
shape = if (markers == FALSE){19}
else{ifelse((P$out > 0.5 & P[,i, drop=FALSE]<0.5), 9, 19)})
}
else {xy.plot(P[,i, drop=FALSE], 'out', data = P, xlab=colnames(P)[i], ylab=paste("~",outcome), necessity = TRUE, main="Necessity Plot",
labcol=labcol,
jitter = jitter,
font = font,
consH = consH,
fontface = fontface,
fontsize = fontsize,
labs = fil,
crisp = crisp,
shape = if (markers == FALSE){19}
else{ifelse((P$out > 0.5 & P[,i, drop=FALSE]<0.5), 9, 19)})}
}
for (i in 1:n_c) {
print(aux.plot(i))
}
}
} |
p.det <- function(dpformula, dplink, dppars, dpdata){
fm <- dpformula
modframe <- model.frame(fm, data=dpdata, drop.unused.levels=FALSE)
dat <- model.matrix(fm, data=modframe)
offsetval <- model.offset(modframe)
if (length(dppars)>1){
lpred <- dat %*% dppars
}else{
lpred <- dat * dppars
}
if(!is.null(offsetval)){
lpred <- lpred+offsetval
}
p <- switch(dplink,
loglog = exp(-exp(lpred)),
cloglog = 1-exp(-exp(lpred)),
logit = exp(lpred)/(1+exp(lpred))
)
return(as.vector(p))
} |
X <- allSitePattern(5)
tree <- read.tree(text = "((t1:0.3,t2:0.3):0.1,(t3:0.3,t4:0.3):0.1,t5:0.5);")
tree2 <- read.tree(text = "((t1:0.3,t3:0.3):0.1,(t2:0.3,t4:0.3):0.1,t5:0.5);")
fit0 <- pml(tree, X, k=4)
fit1 <- update(fit0, rate=.5)
fit2 <- update(fit0, rate=2)
weights0 <- 1000*exp(fit0$siteLik)
weights1 <- 1000*exp(fit1$siteLik)
weights2 <- 1000*exp(fit2$siteLik)
W <- cbind(weights0, weights1, weights2)
colnames(W) <- c("g1", "g2", "g3")
sp <- pmlPart(edge ~ rate, fit0, weight=W, control = pml.control(trace=0))
expect_equal( sp$fits[[1]]$rate / sp$fits[[2]]$rate , 2, tolerance = 1e-5)
expect_equal( sp$fits[[1]]$rate / sp$fits[[3]]$rate , 0.5, tolerance = 1e-5)
Q <- c(6:1)
fit0 <- pml(tree, X, k=4)
fit1 <- pml(tree, X, k=4, Q=Q)
weights1 <- 1000*exp(fit1$siteLik)
Y <- X
attr(Y, "weight") <- weights1
fit1 <- pml(tree, Y, k=4, Q=Q)
weights0 <- weights1
weights2 <- weights1
W <- cbind(weights0, weights1, weights2)
colnames(W) <- c("g1", "g2", "g3")
sp <- pmlPart(edge + Q ~ ., fit0, weight=W, control = pml.control(trace=0))
expect_equal(logLik(sp)[1], logLik(fit1)[1]*3, tolerance=5e-4 )
expect_equal(Q, sp$fits[[1]]$Q, tolerance=5e-4)
sp <- pmlPart( ~ Q, fit0, weight=W, control = pml.control(trace=0))
expect_equal(logLik(sp)[1], logLik(fit1)[1]*3, tolerance=5e-4 )
expect_equal(Q, sp$fits[[1]]$Q, tolerance=5e-4)
bf <- (1:4)/10
fit0 <- pml(tree, X, k=4)
fit1 <- pml(tree, X, k=4, bf=bf)
weights1 <- 1000*exp(fit1$siteLik)
Y <- X
attr(Y, "weight") <- weights1
fit1 <- pml(tree, Y, k=4, bf=bf)
weights0 <- weights1
weights2 <- weights1
W <- cbind(weights0, weights1, weights2)
colnames(W) <- c("g1", "g2", "g3")
sp <- pmlPart(edge + bf ~ ., fit0, weight=W, control = pml.control(trace=0))
expect_equal(logLik(sp)[1], logLik(fit1)[1]*3, tolerance=5e-4 )
expect_equal(bf, sp$fits[[1]]$bf, tolerance=5e-4)
sp <- pmlPart( ~ bf, fit0, weight=W, control = pml.control(trace=0))
expect_equal(logLik(sp)[1], logLik(fit1)[1]*3, tolerance=5e-4 )
expect_equal(bf, sp$fits[[1]]$bf, tolerance=5e-4)
shape <- 2
fit0 <- pml(tree, X, k=4)
fit1 <- pml(tree, X, k=4, shape=shape)
weights1 <- 1000*exp(fit1$siteLik)
Y <- X
attr(Y, "weight") <- weights1
fit1 <- pml(tree, Y, k=4, shape=shape)
weights0 <- weights1
weights2 <- weights1
W <- cbind(weights0, weights1, weights2)
colnames(W) <- c("g1", "g2", "g3")
sp <- pmlPart(edge + shape ~ ., fit0, weight=W,
control=pml.control(trace=0))
expect_equal(logLik(sp)[1], logLik(fit1)[1]*3, tolerance=5e-4 )
expect_equal(shape, sp$fits[[1]]$shape, tolerance=5e-3)
sp <- pmlPart( ~ shape, fit0, weight=W, control=pml.control(trace=0))
expect_equal(logLik(sp)[1], logLik(fit1)[1]*3, tolerance=5e-4 )
expect_equal(shape, sp$fits[[1]]$shape, tolerance=5e-4)
inv <- .2
fit0 <- pml(tree, X, k=4)
fit1 <- pml(tree, X, k=4, inv=inv)
weights1 <- 1000*exp(fit1$siteLik)
Y <- X
attr(Y, "weight") <- weights1
fit1 <- pml(tree, Y, k=4, inv=inv)
weights0 <- weights1
weights2 <- weights1
W <- cbind(weights0, weights1, weights2)
colnames(W) <- c("g1", "g2", "g3")
sp <- pmlPart(edge + inv ~ ., fit0, weight=W, control=pml.control(trace=0))
expect_equal(logLik(sp)[1], logLik(fit1)[1]*3, tolerance=5e-4 )
expect_equal(inv, sp$fits[[1]]$inv, tolerance=5e-5)
sp <- pmlPart( ~ inv, fit0, weight=W, control = pml.control(trace=0))
expect_equal(logLik(sp)[1], logLik(fit1)[1]*3, tolerance=5e-4 )
expect_equal(inv, sp$fits[[1]]$inv, tolerance=5e-5)
Z <- X
fit0 <- pml(tree, X, k=4)
weights0 <- 1000*exp(fit0$siteLik)
weights1 <- 1000*exp(update(fit0, rate=.5)$siteLik)
weights2 <- 1000*exp(update(fit0, tree=tree2)$siteLik)
attr(Z, "weight") <- weights0 + weights1 + weights2
W <- cbind(weights0, weights1, weights2)
fit_Z <- update(fit0, data=Z)
fit_Z <- optim.pml(fit_Z, model="GTR", rearrangement="NNI", optGamma=TRUE,
optInv=TRUE, control=pml.control(trace=0))
sp <- pmlPart(edge + bf + Q + shape + inv + nni ~ ., fit_Z, weight=W,
control = pml.control(trace=0))
expect_equal(sp$logLik[[1]], fit_Z$logLik, tolerance = 1e-5) |
date_Input <- function(inputId, label, hint_label = NULL,
error = FALSE, error_message = NULL,
day = NULL, month = NULL, year = NULL){
value <- shiny::restoreInput(id = inputId, default = FALSE)
govDate <- shiny::tags$div(class="govuk-form-group", id=paste0(inputId,"div"),
shiny::tags$fieldset(class="govuk-fieldset",
shiny::tags$label(shiny::HTML(label), class="govuk-label"),
if (error == TRUE){
shinyjs::hidden(
shiny::tags$span(
error_message,
id = paste0(inputId,"error"),
class = "govuk-error-message",
shiny::tags$span("Error:", class = "govuk-visually-hidden")
)
)
},
shiny::tags$span(hint_label, class="govuk-hint"),
shiny::tags$div(class="govuk-date-input", id = inputId,
shiny::tags$div(class="govuk-date-input__item",
shiny::tags$div(class="govuk-form-group",
shiny::tags$label(
"Day", class="govuk-label govuk-date-input__label"),
shiny::tags$input(
class=paste("govuk-input govuk-date-input__input", "
govuk-input--width-2"),
id=paste0(inputId,"_day"), name=inputId,
type="number", pattern="[0-9]*", value = day)
)
),
shiny::tags$div(class="govuk-date-input__item",
shiny::tags$div(class="govuk-form-group",
shiny::tags$label(
"Month", class="govuk-label govuk-date-input__label"),
shiny::tags$input(class=paste("govuk-input govuk-date-input__input",
"govuk-input--width-2"),
id=paste0(inputId,"_month"), name=inputId,
type="number", pattern="[0-9]*", value = month)
)
),
shiny::tags$div(class="govuk-date-input__item",
shiny::tags$div(class="govuk-form-group",
shiny::tags$label(
"Year", class="govuk-label govuk-date-input__label"),
shiny::tags$input(class=paste("govuk-input govuk-date-input__input",
"govuk-input--width-4"),
id=paste0(inputId,"_year"), name=inputId,
type="number", pattern="[0-9]*", value = year)
)
)
)
)
)
attachDependency(govDate, "date")
} |
`tukey.test` <-
function(data, alpha=0.05, critical.value=NA) {
a<-nrow(data)
b<-ncol(data)
d.f1=1
d.f2=(a-1)*(b-1)-1
if (is.na(critical.value)) critical.value=qf(1-alpha,df1=d.f1,df2=d.f2)
yMEAN<-mean(data)
A.hat<-apply(data,1,mean)-yMEAN
B.hat<-apply(data,2,mean)-yMEAN
ss.col<-a*sum(B.hat^2)
ss.row<-b*sum(A.hat^2)
ss.tukey<-((sum(A.hat*(data%*%B.hat)/(ss.col/a)))^2)/(ss.row/b)*(ss.col/a)
test.stat=ss.tukey*((a-1)*(b-1)-1)/(sum(apply(data^2,1,sum))-a*b*yMEAN^2-ss.row-ss.col-ss.tukey)
out<-list(result=test.stat>critical.value,stat=test.stat,critical.value=critical.value,alpha=alpha,name="Tukey test")
class(out)<-"aTest"
return(out)
} |
stepFit <- function(y, q = NULL, alpha = NULL, x = 1:length(y), x0 = 2 * x[1] - x[2], family = NULL, intervalSystem = NULL,
lengths = NULL, confband = FALSE, jumpint = confband, ...) {
if (missing(y)) {
stop("argument 'y' must be given")
}
.RemoveAdditionalArgsPF <- function(family, y, n, ..., penalty, alpha, stat, r, weights, options,
seed, rand.gen, messages)
.parametricFamily(family = family, y = y, n = n, ...)
data <- .RemoveAdditionalArgsPF(family = family, y = y, n = length(y), ...)
intervalSystem <- .intervalSystem(intervalSystem = intervalSystem, lengths = lengths, data = data)
if (length(x) != data$n) {
stop("x and y must have the same length")
}
if (!is.numeric(x) || !all(is.finite(x))) {
stop("x must be a finite numeric vector")
}
if (any(x[-1] - x[-data$n] <= 0)) {
stop("x must be an increasing sequence")
}
if (!is.numeric(x0) || length(x0) != 1 || !is.finite(x0) || x0 >= x[1]) {
stop("x0 must be a single finite numeric smaller than x[1]")
}
.RemoveAdditionalArgsCV <- function(q, alpha, data, output, intervalSystem, ..., nq,
sd, covariances, correlations, filter)
.critVal(q = q, alpha = alpha, data = data, output = output, intervalSystem = intervalSystem, ...)
q <- .RemoveAdditionalArgsCV(q = q, alpha = alpha, data = data, output = "vector",
intervalSystem = intervalSystem, ...)
criticalValues <- rep(Inf, data$n)
criticalValues[intervalSystem$lengths] <- q
if (length(confband) != 1 || !is.logical(confband) || is.na(confband)) {
stop("confband must be a single logical (not NA)")
}
if (length(jumpint) != 1 || !is.logical(jumpint) || is.na(jumpint)) {
stop("jumpint must be a single logical (not NA)")
}
if (confband) {
jumpint <- TRUE
ret <- .callRoutines(observations = data$y, routineType = 5L,
argumentsListRoutine = list(q = criticalValues),
dataType = data$type, argumentsListData = data$argumentsList,
intervalSystemType = intervalSystem$type,
argumentsListIntervalSystem = intervalSystem$argumentsList)
} else {
if (jumpint) {
ret <- .callRoutines(observations = data$y, routineType = 4L,
argumentsListRoutine = list(q = criticalValues),
dataType = data$type, argumentsListData = data$argumentsList,
intervalSystemType = intervalSystem$type,
argumentsListIntervalSystem = intervalSystem$argumentsList)
} else {
if (intervalSystem$type < 10L) {
ret <- .callRoutines(observations = data$y, routineType = 3L,
argumentsListRoutine = list(q = criticalValues),
dataType = data$type, argumentsListData = data$argumentsList,
intervalSystemType = intervalSystem$type,
argumentsListIntervalSystem = intervalSystem$argumentsList)
} else {
ret <- .callRoutines(observations = data$y, routineType = 4L,
argumentsListRoutine = list(q = criticalValues),
dataType = data$type, argumentsListData = data$argumentsList,
intervalSystemType = intervalSystem$type,
argumentsListIntervalSystem = intervalSystem$argumentsList)
}
}
}
fit <- stepfit(cost = attr(ret, "cost"), family = data$family, value = ret$value,
param = data$argumentsListData,
x0 = x0, leftEnd = x[ret$leftIndex], rightEnd = x[ret$rightIndex],
leftIndex = ret$leftIndex, rightIndex = ret$rightIndex)
if (jumpint) {
fit$leftEndLeftBound <- x[c(1L, ret$leftConfInt)]
fit$leftEndRightBound <- x[c(1L, ret$rightConfInt)]
fit$rightEndLeftBound <- x[c(ret$leftConfInt - 1L, data$n)]
fit$rightEndRightBound <- x[c(ret$rightConfInt - 1L, data$n)]
fit$leftIndexLeftBound <- c(1L, ret$leftConfInt)
fit$leftIndexRightBound <- c(1L, ret$rightConfInt)
fit$rightIndexLeftBound <- c(ret$leftConfInt - 1L, data$n)
fit$rightIndexRightBound <- c(ret$rightConfInt - 1L, data$n)
}
if (confband) {
band <- data.frame(x = x, lower = ret$lowerBand, upper = ret$upperBand)
attr(band, "x0") <- x0
class(band) <- c("confband", class(band))
attr(fit, "confband") <- band
}
fit
}
"stepfit" <-
function(cost, family, value, param = NULL, leftEnd, rightEnd, x0, leftIndex = leftEnd, rightIndex = rightEnd)
{
ret <- stepblock(value, leftEnd, rightEnd, x0)
ret$leftIndex <- leftIndex
ret$rightIndex <- rightIndex
attr(ret, "cost") <- cost
attr(ret, "family") <- family
attr(ret, "param") <- param
class(ret) <- c("stepfit", class(ret))
ret
}
"print.stepfit" <-
function(x, ...)
{
cat("\n")
cat("Fitted step function of family", attr(x, "family"), "containing", nrow(x), "blocks\n\n")
cat("domain: (", attr(x, "x0"), ",", x$rightEnd[nrow(x)], "]\n")
cat("range: [", min(x$value), ",", max(x$value), "]\n")
cat("cost:", attr(x, "cost"), "\n")
if(!is.null(attr(x, "param"))) {
cat("parameter:\n")
print(attr(x, "param"))
}
cat("\n")
}
"[.stepfit" <-
function (x, i, j, drop = if(missing(i)) TRUE else if(missing(j)) FALSE else length(j) == 1, refit = FALSE)
{
ret <- NextMethod("[.")
if(!identical(refit, FALSE)) {
if(missing(i)) i <- 1:nrow(x)
ret$value <- switch(attr(x, "family"),
gauss = diff(c(0, ret$cumSum)) / diff(c(attr(ret, "x0"), ret$rightIndex)),
gaussKern = if(nrow(ret) == 1 ) diff(c(0, ret$cumSum)) / diff(c(attr(ret, "x0"), ret$rightIndex)) else {
param <- attr(x, "param")
r <- ret$rightIndex
ir <- r[-length(r)]
n <- r[length(r)]
kl <- length(param$kern)
kj <- param$jump
s <- param$step
d <- c(ir - kj, n) - c(0, ir + kl - kj) + c(rep(sum((1 - s)^2), length(r) - 1), 0) + c(0, rep(sum(s^2), length(r) - 1))
ld <- length(d)
sd <- sum( s * ( 1 - s ) )
XX <- diag(d)
XX[cbind(1:(ld-1), 2:ld)] <- sd
XX[cbind(2:ld, 1:(ld-1))] <- sd
dif <- diff(c(0, ret$rightIndex))
close <- min(dif) <= kl
Xy <- c(0, ret$lXy[-nrow(ret)]) + ret$rcXy - c(0, ret$lcXy[-nrow(ret)]) + ret$rXy
if(identical(refit, TRUE) | !close) {
if(close) warning("jumps closer than filter length")
} else {
ss <- c(0, s, 1)
revss <- c(1, rev(s), 0)
for(i in which(dif < kl)) {
if(i > 1 & i < n) {
neigh <- which(r + kj > r[i-1] & c(0, ir) <= r[i] + kl - kj )
neighn <- length(neigh)
neighi <- max(r[neigh[1]] - kj + 1, 1):min(r[neigh[neighn] - 1] + kl - kj, n)
tX <- outer(1:neighn, neighi, function(k,ind) {
revss[pmin(pmax(c(0,r)[neigh[k]] + kl - kj + 1 - ind, 0), kl + 1) + 1] - ss[pmin(pmax(ind + kj - r[neigh[k]], 0), kl + 1) + 1]
})
iXX <- tX %*% t(tX)
XX[neigh[neigh <= i],neigh[neigh >= i]] <- iXX[which(neigh <= i),which(neigh >= i)]
XX[neigh[neigh >= i],neigh[neigh <= i]] <- iXX[which(neigh >= i),which(neigh <= i)]
Xy[i] <- tX[which(neigh == i),] %*% refit[neighi]
}
}
}
ret$value <- as.numeric(solve(XX, Xy))
},
poisson = diff(c(0, ret$cumSum)) / diff(c(attr(ret, "x0"), ret$rightIndex)),
binomial = diff(c(0, ret$cumSum)) / diff(c(attr(ret, "x0"), ret$rightIndex)) / attr(ret, "param")
)
class(ret) <- class(x)
}
ret
}
"plot.stepfit" <-
function(x, dataspace = TRUE, ...)
{
if(attr(x, "family") == "binomial" && dataspace) {
x$value <- x$value * attr(x, "param")
}
NextMethod()
}
"lines.stepfit" <-
function(x, dataspace = TRUE, ...)
{
if(attr(x, "family") == "binomial" && dataspace) {
x$value <- x$value * attr(x, "param")
}
NextMethod()
}
"fitted.stepfit" <-
function(object, ...)
{
if(attr(object, "family") == "gaussKern" && nrow(object) > 1) {
k <- attr(object, "param")$kern
l <- length(k)
j <- attr(object, "param")$jump
ret <- rep(object$value, object$rightIndex - object$leftIndex + 1 + c(l - j - 1, rep(0, length(object$rightIndex) - 2), j))
convolve(ret, rev(k), conj = TRUE, type = "filter")
} else if(attr(object, "family") == "binomial") {
rep(object$value * attr(object, "param"), object$rightIndex - object$leftIndex + 1)
} else {
rep(object$value, object$rightIndex - object$leftIndex + 1)
}
}
"residuals.stepfit" <-
function(object, y, ...)
{
fit <- fitted(object)
if(length(fit) != length(y)) stop("data and fit differ in length")
switch(attr(object, "family"),
binomial = {
y - attr(object, "param") * fit
},
gaussvar = {
ifelse(fit == 0, ifelse(y^2 == 0, 0, Inf), log(y^2 / fit))
},
{
y - fit
}
)
}
"logLik.stepfit" <-
function(object, df = NULL, nobs = object$rightIndex[nrow(object)], ...)
{
family <- switch(attr(object, "family"),
gaussKern = "gauss",
attr(object, "family")
)
ret <- switch(family,
gauss = {
if(is.null(df)) df <- nrow(object) + 1
-nobs / 2 * (1 + log(2 * pi * attr(object, "cost") / nobs))
},
{
if(is.null(df)) df <- nrow(object)
attr(object, "cost")
}
)
attr(ret, "df") <- df
attr(ret, "nobs") <- nobs
class(ret) <- "logLik"
ret
} |
test_that("adminlte_vars works", {
vars <- adminlte_vars("light-blue" = "
expect_is(vars, "list")
expect_is(vars, "fresh_sass_vars")
expect_is(vars, "adminlte_vars")
expect_length(vars, 2)
})
test_that("adminlte_color works", {
vars <- adminlte_color(light_blue = "
expect_is(vars, "list")
expect_is(vars, "fresh_sass_vars")
expect_is(vars, "adminlte_vars")
expect_length(vars, 2)
})
test_that("adminlte_sidebar works", {
vars <- adminlte_sidebar(width = "400px", dark_bg = "
expect_is(vars, "list")
expect_is(vars, "fresh_sass_vars")
expect_is(vars, "adminlte_vars")
expect_length(vars, 2)
})
test_that("adminlte_global works", {
vars <- adminlte_global(content_bg = "
expect_is(vars, "list")
expect_is(vars, "fresh_sass_vars")
expect_is(vars, "adminlte_vars")
expect_length(vars, 1)
}) |
if (require("testthat") && require("sjmisc") && require("haven")) {
data(efc)
x <- labelled(
c(1:3, tagged_na("a", "z"), 4:1),
c("Agreement" = 1, "Disagreement" = 4, "First" = tagged_na("c"), "Not home" = tagged_na("z"))
)
test_that("replace_na", {
expect_true(sum(is.na(replace_na(efc$e42dep, value = 99))) == 0)
})
test_that("replace_na", {
expect_true(sum(is.na(replace_na(x, value = 99))) == 0)
expect_true(sum(is.na(replace_na(x, value = 99, tagged.na = "a"))) == 1)
expect_equal(names(attr(replace_na(x, value = 99, tagged.na = "a", na.label = "test"), "labels") == 99)[3], "test")
})
} |
knitr::opts_chunk$set(tidy = FALSE,
message = FALSE)
library(ggplot2)
library(tidydr)
library(tidydr)
x <- dr(data = iris[,1:4], fun = prcomp)
library(ggplot2)
ggplot(x, aes(Dim1, Dim2), metadata=iris$Species) +
geom_point(aes(color=.group))
autoplot(x, aes(color=Species), metadata = iris[, 5, drop=FALSE]) +
theme_dr() |
cloneRoot <- function(obj, verbose=FALSE) {
data <- "NULL"
mapping_str <- "aes()"
if (!is.null(obj$data)) {
data <- paste(utils::capture.output(dput(obj$data)), collapse = "\n")
}
if (!is.null(obj$mapping)) {
mapping <- sapply(obj$mapping,rlang::quo_name)
mapping_str <- sprintf("aes(%s)", paste0(sapply(names(mapping), function(y) paste(y, mapping[[y]], sep = "=")), collapse = ","))
}
strout <- sprintf("ggplot(mapping=%s,data=%s)", mapping_str, data)
if (verbose) {
strout
} else {
eval(parse(text = strout))
}
} |
NULL
flux.dome.graph3D <- function(A_fun,Etot_fun,add.reg=FALSE,B_fun=NULL,
E_ini_fun=NULL,X_fun=1,marge_section=0.1,marge_top.dome=0.5) {
n_poss <- 3
n_fun <- length(A_fun)
correl_fun <- name.correl(TRUE,add.reg,B_fun)
E_ini_fun <- E_ini_fun*Etot_fun/sum(E_ini_fun)
if (n_fun!=n_poss) {
stop("Available only for 3 enzymes.")
}
if (correl_fun!="Comp"&correl_fun!="CRPos"&correl_fun!="CRNeg") {
stop("Flux dome exists only in case of competition.")
}
is.B.accurate(B_fun,n_fun,correl_fun)
if (length(E_ini_fun)==0&correl_fun!="Comp") {
stop("In case of regulation, initial point 'E_ini_fun' is needed.")
}
if (length(E_ini_fun)!=n_fun&correl_fun!="Comp") {
stop("E_ini_fun and A_fun need to have the same length.")
}
max_max_e <- predict_th(A_fun,"Comp")$pred_e
max_max_J <- flux(max_max_e*Etot_fun,A_fun,X_fun)
if (correl_fun=="CRPos"|correl_fun=="CRNeg") {
e0 <- E_ini_fun/sum(E_ini_fun)
J0 <- flux(E_ini_fun,A_fun,X_fun)
eq_th <- predict_th(A_fun,correl_fun,B_fun)
J_th <- flux(eq_th$pred_e*Etot_fun,A_fun,X_fun)
eq_eff <- predict_eff(E_ini_fun,B_fun,A_fun,correl_fun)
J_eff <- flux(eq_eff$pred_E,A_fun,X_fun)
borne_tau <- range_tau(E_ini_fun,B_fun)
tau <- seq(min(borne_tau)+0.0001,max(borne_tau)-0.0001,by=0.01)
E_test_ens <- t(sapply(tau,droite_E.CR,E_ini_fun,B_fun))
e_test <- E_test_ens/sum(E_ini_fun)
J_test <- apply(E_test_ens,1,flux,A_fun,X_fun)
}
sph.radius <- 0.0125*(max_max_J*0.9)
e_seq <- seq(0,1,by=0.01)
J_dome <- matrix(nrow=length(e_seq),ncol=length(e_seq))
for (x1 in 1:length(e_seq)) {
for (x2 in 1:length(e_seq)) {
if ((1-e_seq[x1]-e_seq[x2])>=0) {
E_vec <- c(e_seq[x1]*Etot_fun,e_seq[x2]*Etot_fun,(1-e_seq[x1]-e_seq[x2])*Etot_fun)
J_dome[x1,x2] <- flux(E_vec,A_fun,X_fun)
} else {
J_dome[x1,x2] <- 0
}
}
}
if (correl_fun=="CRPos"|correl_fun=="CRNeg") {
w_plan <- matrix(0,ncol=4,nrow=4)
borne_e <- t(sapply(range(tau), droite_e,E_ini_fun,B_fun))
w_plan[1:2,1:2] <- borne_e[,1:2]
w_plan[3:4,1:2] <- borne_e[,1:2]
w_plan[,3] <- rep(c(0,J_eff+marge_section),each=2)
w_plan[,4] <- 1
w_plan <- t(w_plan)
w_indices <- c(1,2,4,3)
} else {
w_plan <- NaN
w_indices <- NaN
}
open3d()
plot3d(0,0,0,zlim=c(0,max_max_J+marge_top.dome),xlim=c(0,1),ylim=c(0,1),xlab="Enzyme 1", ylab="Enzyme 2", zlab=" ")
surface3d(e_seq,e_seq,J_dome,col='lightgrey',zlim=c(0,max_max_J+marge_top.dome),xlim=c(0,1),ylim=c(0,1))
shade3d(qmesh3d(w_plan,w_indices),col='oldlace')
spheres3d(max_max_e[1], max_max_e[2], max_max_J, col="violet", point_antialias=TRUE, radius=sph.radius, size=18)
if (correl_fun=="CRPos"|correl_fun=="CRNeg") {
spheres3d(eq_th$pred_e[1], eq_th$pred_e[2], J_th, col="red", point_antialias=TRUE, radius=sph.radius, size=18)
spheres3d(eq_eff$pred_e[1], eq_eff$pred_e[2], J_eff, col="yellow1", point_antialias=TRUE, radius=sph.radius, size=18)
spheres3d(e0[1], e0[2], J0, col="black", point_antialias=TRUE, radius=sph.radius, size=18)
}
points3d(max_max_e[1], max_max_e[2], 0, col="violet", point_antialias=TRUE, size=10)
if (correl_fun=="CRPos"|correl_fun=="CRNeg") {
lines3d(e_test[,1], e_test[,2], 0, lwd=5, col="darkgreen")
points3d(eq_th$pred_e[1], eq_th$pred_e[2], 0, col="red", point_antialias=TRUE, size=10)
points3d(eq_eff$pred_e[1], eq_eff$pred_e[2], 0, col="yellow1", point_antialias=TRUE, size=10)
points3d(e0[1], e0[2], 0, col="black", point_antialias=TRUE, size=10)
}
}
flux.dome.projections <- function(A_fun,Etot_fun,add.reg=FALSE,B_fun=NULL,
E_ini_fun=NULL,X_fun=1,nbniv=9,niv.palette=NULL,marge_section=0.1,
posi.legend="topleft",new.window=FALSE,cex.pt=1.5,...) {
n_poss <- 3
n_fun <- length(A_fun)
correl_fun <- name.correl(TRUE,add.reg,B_fun)
E_ini_fun <- E_ini_fun*Etot_fun/sum(E_ini_fun)
if (n_fun!=n_poss) {
stop("Available only for 3 enzymes.")
}
if (correl_fun!="Comp"&correl_fun!="CRPos"&correl_fun!="CRNeg") {
stop("Flux dome exists only in case of competition.")
}
is.B.accurate(B_fun,n_fun,correl_fun)
if (length(E_ini_fun)==0&add.reg==TRUE) {
stop("In case of regulation, initial point 'E_ini_fun' is needed.")
}
if (length(E_ini_fun)!=n_fun&add.reg==TRUE) {
stop("E_ini_fun and A_fun need to have the same length.")
}
max_max_e <- predict_th(A_fun,"Comp")$pred_e
max_max_J <- flux(max_max_e*Etot_fun,A_fun,X_fun)
if (correl_fun=="CRPos"|correl_fun=="CRNeg") {
e0 <- E_ini_fun/sum(E_ini_fun)
J0 <- flux(E_ini_fun,A_fun,X_fun)
eq_th <- predict_th(A_fun,correl_fun,B_fun)
J_th <- flux(eq_th$pred_e*Etot_fun,A_fun,X_fun)
eq_eff <- predict_eff(E_ini_fun,B_fun,A_fun,correl_fun)
J_eff <- flux(eq_eff$pred_E,A_fun,X_fun)
borne_tau <- range_tau(E_ini_fun,B_fun)
tau <- seq(min(borne_tau)+0.0001,max(borne_tau)-0.0001,by=0.01)
E_test_ens <- t(sapply(tau,droite_E.CR,E_ini_fun,B_fun))
e_test <- E_test_ens/sum(E_ini_fun)
J_test <- apply(E_test_ens,1,flux,A_fun,X_fun)
}
saut <- ceiling(max_max_J/nbniv)
J_select <- seq(0.0001,max_max_J,by=saut)
param.nbniv <- nbniv
nbniv <- length(J_select)
e_seq <- seq(0.01,1,by=0.01)
e_curve1 <- vector("list",length=nbniv)
for (k in 1:nbniv) {
J_niv <- J_select[k]
sol_niv <- NULL
for (i in 1:n_fun) {
if (i ==1) {
j <- 2 ; l <- 3 }
if (i==2) { j <- 3 ; l <- 1 }
if (i==3) { j <- 1 ; l <- 2 }
for (x in e_seq) {
a <- A_fun[j]*A_fun[l]*(X_fun*Etot_fun/J_niv - 1/(A_fun[i]*x))
b <- A_fun[j]-A_fun[l]-a*(1-x)
c <- A_fun[l]*(1-x)
if (a!=0) {
sol_2dg <- solv.2dg.polynom(a,b,c)
if (all(sol_2dg>=0)&all((1-x-sol_2dg)>=0)) {
sol_e <- matrix(0,nrow=length(sol_2dg),ncol=n_fun)
sol_e[,i] <- x
sol_e[,j] <- sol_2dg
sol_e[,l] <- 1-x-sol_2dg
sol_niv <- rbind(sol_niv,sol_e)
}
}
}
}
e_curve1[[k]] <- sol_niv
}
col_niv <- NULL
for (k in 1:nbniv) {
matniv <- e_curve1[[k]]
matniv <- cbind(matniv,k)
col_niv <- rbind(col_niv,matniv)
}
col_niv <- as.data.frame(col_niv)
colnames(col_niv) <- c("e1","e2","e3","color")
if (is.null(niv.palette)) {
niv.palette<-brewer.pal(nbniv,"Spectral")
niv.palette<-rev(niv.palette)
}
if (length(niv.palette)<nbniv) {
warning("Not enough colors for contour line.")
niv.palette <- rep(niv.palette,ceiling(nbniv/length(niv.palette)))
}
if (new.window==TRUE) {
dev.new()
}
tr_Jm <- triangle.plot(t(max_max_e),scale=FALSE,show.position=FALSE,draw.line = FALSE,cpoint=0)
if (add.reg==TRUE) {
tr_test <- triangle.plot(e_test[,1:3],scale=FALSE,show.position=FALSE,draw.line = FALSE,cpoint=0)
tr_ini <- triangle.plot(t(e0),scale=FALSE,show.position=FALSE,draw.line = FALSE,cpoint=0)
tr_eff <- triangle.plot(t(eq_eff$pred_e),scale=FALSE,show.position=FALSE,draw.line = FALSE,cpoint=0)
if (correl_fun=="CRPos"|correl_fun=="RegPos") {
tr_th <- triangle.plot(t(eq_th$pred_e),scale=FALSE,show.position=FALSE,draw.line = FALSE,cpoint=0)
}
}
if (new.window==TRUE) {
dev.new()
}
tr_niv <- triangle.plot(col_niv[,1:3],scale=FALSE,show.position=FALSE,draw.line = FALSE,cpoint=0)
for (k in 1:nbniv){
points(tr_niv[col_niv$color==k,],col=niv.palette[k],cex=0.3,pch=20,type='o',lwd=5)
}
points(tr_Jm,pch=21,bg='violet',cex=cex.pt)
if (add.reg==TRUE) {
points(tr_test,col=1,type='l',cex=cex.pt)
points(tr_ini,col=1,pch=21,cex=cex.pt,bg="black")
points(tr_eff,col=1,pch=21,cex=cex.pt,bg="yellow2")
if (correl_fun=="CRPos") {
points(tr_th,col=1,pch=21,cex=cex.pt,bg="firebrick1")
}
}
if (!is.null(posi.legend)) {
legend(posi.legend[1],posi.legend[2],legend=round(J_select),lwd=rep(5,nbniv),col=niv.palette,bty="n",cex=1.2)
}
if (add.reg==TRUE) {
if (new.window==TRUE) {
dev.new()
}
plot(x=tau,y=J_test,type='l',col=1,xlab="Tau",ylab="Flux",pch=20,ylim=c(0,J_eff+marge_section),...)
points(0,J0,pch=21,cex=cex.pt,bg="black")
abline(v=eq_eff$pred_tau,lty=2)
points(eq_eff$pred_tau,J_eff,pch=21,cex=cex.pt,col=1,bg="yellow2")
if (correl_fun=="CRPos") {
abline(v=1)
points(1,J_th,pch=21,cex=cex.pt,bg="firebrick1")
}
}
} |
library(grid)
unitCheck <- function(u1, u2) {
stopifnot(identical(as.character(u1), as.character(u2)))
}
simpleUnit <- unit(1:4, "npc")
unitCheck(rep(simpleUnit, 2),
unit(rep(1:4, 2), "npc"))
unitCheck(rep(simpleUnit, each=2),
unit(rep(1:4, each=2), "npc"))
unitCheck(rep(simpleUnit, c(2, 1, 2, 1)),
unit(rep(1:4, c(2, 1, 2, 1)), "npc"))
unitCheck(rep(simpleUnit, each=2, len=4),
unit(rep(1:4, each=2, len=4), "npc"))
unitCheck(rep(simpleUnit, each=2, len=10),
unit(rep(1:4, each=2, len=10), "npc"))
unitCheck(rep(simpleUnit, each=2, times=3),
unit(rep(1:4, each=2, times=3), "npc"))
simpleUnitMixed <- unit(1:4, c("npc", "cm"))
unitCheck(rep(simpleUnitMixed, 2),
unit(rep(1:4, 2), c("npc", "cm")))
unitCheck(rep(simpleUnitMixed, each=2),
unit(rep(1:4, each=2),
rep(c("npc", "cm"), each=2)))
unitCheck(rep(simpleUnitMixed, c(2, 1, 2, 1)),
unit(rep(1:4, c(2, 1, 2, 1)),
rep(c("npc", "cm"), c(2, 1))))
unitCheck(rep(simpleUnitMixed, each=2, len=4),
unit(rep(1:4, each=2, len=4),
rep(c("npc", "cm"), each=2, len=4)))
unitCheck(rep(simpleUnitMixed, each=2, len=10),
unit(rep(1:4, each=2, len=10),
rep(c("npc", "cm"), each=2, len=10)))
unitCheck(rep(simpleUnitMixed, each=2, times=3),
unit(rep(1:4, each=2, times=3),
rep(c("npc", "cm"), each=2, times=3)))
units <- c("npc", "inch", "strwidth", "cm")
dataL <- list(NULL, NULL, "test", NULL)
unitWithData <- unit(1:4, units, data=dataL)
unitCheck(rep(unitWithData, 2),
unit(rep(1:4, 2),
rep(units, 2),
rep(dataL, 2)))
unitCheck(rep(unitWithData, each=2),
unit(rep(1:4, each=2),
rep(units, each=2),
rep(dataL, each=2)))
unitCheck(rep(unitWithData, c(2, 1, 2, 1)),
unit(rep(1:4, c(2, 1, 2, 1)),
rep(units, c(2, 1, 2, 1)),
rep(dataL, c(2, 1, 2, 1))))
unitCheck(rep(unitWithData, each=2, len=4),
unit(rep(1:4, each=2, len=4),
rep(units, each=2, len=4),
rep(dataL, each=2, len=4)))
unitCheck(rep(unitWithData, each=2, len=10),
unit(rep(1:4, each=2, len=10),
rep(units, each=2, len=10),
rep(dataL, each=2, len=10)))
unitCheck(rep(unitWithData, each=2, times=3),
unit(rep(1:4, each=2, times=3),
rep(units, each=2, times=3),
rep(dataL, each=2, times=3)))
unitArith <- unit(1, "npc") + unit(1:2, "inch")
unitCheck(rep(unitArith, 2),
unit(1, "npc") + unit(rep(1:2, 2), "inch"))
unitCheck(rep(unitArith, each=2),
unit(1, "npc") + unit(rep(1:2, each=2), "inch"))
unitCheck(rep(unitArith, c(2, 1)),
unit(1, "npc") + unit(rep(1:2, c(2 ,1)), "inch"))
unitCheck(rep(unitArith, each=2, len=3),
unit(1, "npc") + unit(rep(1:2, each=2, len=3), "inch"))
unitCheck(rep(unitArith, each=2, len=5),
unit(1, "npc") + unit(rep(1:2, each=2, len=5), "inch"))
unitCheck(rep(unitArith, each=2, times=3),
unit(1, "npc") + unit(rep(1:2, each=2, times=3), "inch"))
arg1 <- unit(1, "npc") + unit(1:2, "inch")
arg2 <- unit(3, "cm")
unitList <- unit.c(arg1, arg2)
unitCheck(rep(unitList, 2),
unit.c(arg1, arg2, arg1, arg2))
unitCheck(rep(unitList, each=2),
unit.c(rep(arg1, each=2), rep(arg2, 2)))
unitCheck(rep(unitList, c(2, 1, 2)),
unit.c(rep(arg1, c(2, 1)), rep(arg2, 2)))
unitCheck(rep(unitList, each=2, len=4),
rep(arg1, each=2))
unitCheck(rep(unitList, each=2, len=8),
unit.c(rep(arg1, each=2), rep(arg2, 2), rep(arg1, each=2, len=2)))
unitCheck(rep(unitList, each=2, times=3),
unit.c(rep(arg1, each=2), rep(arg2, 2),
rep(arg1, each=2), rep(arg2, 2),
rep(arg1, each=2), rep(arg2, 2)))
uaDiffLength <- unit(1:2, "npc") + unit(1:3, "npc")
uaSameLength <- unit(c(1, 2, 1), "npc") + unit(1:3, "npc")
unitCheck(rep(uaDiffLength, 2),
rep(uaSameLength, 2))
x <- unit.c(unit(5,"mm"),unit(3,"npc"))
rep(x, 2)
rep(x, each=2)
rep(x, c(2, 2))
x <- x - unit(1,"mm")
rep(x, 2)
rep(x, each=2)
rep(x, c(2, 2))
x <- unit(1, "cm")
stopifnot(length(unit.pmax(x)) == 1L, length(unit.pmin(x)) == 1L)
a <- unit(1:3, c("cm", "in", "npc"))
b <- a + unit(1, "npc")
a[2] <- unit(2,"pt")
b[2] <- unit(2,"npc")
unitCheck(a, unit(1:3, c("cm", "pt", "npc")))
unitCheck(b, unit.c(unit(1, "cm") + unit(1, "npc"),
unit(2, "npc"),
unit(3, "npc") + unit(1, "npc")))
c <- unit(1:10, "mm")
c[5:9] <- unit(9:5, "pt")
unitCheck(c, unit(c(1:4, 9:5, 10),
c(rep("mm", 4), rep("pt", 5), "mm")))
c[2:3] <- unit(1, "in") + unit(.5, "npc")
unitCheck(c, unit.c(unit(1, "mm"),
rep(unit(1, "in") + unit(.5, "npc"), 2),
unit(4, "mm"),
unit(9:5, "pt"),
unit(10, "mm")))
c[6:8] <- stringWidth(c("a", "b"))
unitCheck(c, unit.c(unit(1, "mm"),
rep(unit(1, "in") + unit(.5, "npc"), 2),
unit(4, "mm"),
unit(9, "pt"),
stringWidth(c("a", "b", "a")),
unit(5, "pt"),
unit(10, "mm"))) |
NULL
mexp <- function(r = 0, truncation = 0, rate = 1, lower.tail = TRUE) {
m <- mweibull(r = r, truncation = truncation, shape = 1, scale = 1 / rate, lower.tail = lower.tail)
return(m)
} |
url <- paste0("https://warin.ca/datalake/iriR/iri_data.csv")
path <- file.path(tempdir(), "temp.csv")
if (httr::http_error(url)) {
message("No Internet connection or the server is in maintenance mode.")
return(NULL)
} else {
message("iriR: downloading remote dataset.")
with(options(timeout = max(300, getOption("timeout"))),curl::curl_download(url, path))
}
csv_file <- file.path(paste0(tempdir(), "/temp.csv"))
IRI_data <- read.csv(csv_file)
url <- paste0("https://warin.ca/datalake/iriR/iri_indicator.csv")
path <- file.path(tempdir(), "temp.csv")
if (httr::http_error(url)) {
message("No Internet connection or the server is in maintenance mode.")
return(NULL)
} else {
message("iriR: downloading remote dataset.")
with(options(timeout = max(300, getOption("timeout"))),curl::curl_download(url, path))
}
csv_file <- file.path(paste0(tempdir(), "/temp.csv"))
IRI_indicator <- read.csv(csv_file)
IRI_data <- reshape2::melt(IRI_data,
id.vars = c("country", "country_code", "year", "rank", "company", "industrial.sector"),
measure.vars = colnames(IRI_data)[7:ncol(IRI_data)],
variable.name = "indicator_code",
value.name = "value"
)
base::names(IRI_data) = c("country_name", "country_code", "year", "rank", "company_name", "industry_name", "indicator_code", "value")
iri_country <- base::unique(IRI_data[,2])
iri_year <- base::unique(IRI_data[,3])
iri_indicator <- base::unique(IRI_data[,7])
iri_company <- base::unique(IRI_data[,5])
iri_industry <- base::unique(IRI_data[,6])
iri_rank <- base::unique(IRI_data[,4])
irir_data <- function(country = iri_country,
years = iri_year,
indicators = iri_indicator,
company = iri_company,
industry = iri_industry,
ranks = iri_rank) {
country_code <- year <- indicator_code <- company_name <- industry_name <- rank <- NULL
out <- dplyr::filter(IRI_data,
country_code %in% country,
year %in% years,
indicator_code %in% indicators,
company_name %in% company,
industry_name %in% industry,
rank %in% ranks)
return(out)
}
irir_indicator <- function(indicators) {
iri_indicators_natural_language <- IRI_indicator[, 1:3]
if (missing(indicators)) {
iri_indicators_natural_language
} else {
iri_indicators_natural_language[grep(indicators, iri_indicators_natural_language$indicator_name, ignore.case = TRUE), ]
}
}
irir_country <- function(country) {
iri_countries_natural_language <- unique(IRI_data[, 1:2])
if (missing(country)) {
iri_countries_natural_language
} else {
iri_countries_natural_language[grep(country, iri_countries_natural_language$country_name, ignore.case = TRUE), ]
}
}
irir_company <- function(company){
iri_company_natural_language <- unique(IRI_data$company_name)
iri_company_natural_language <- as.data.frame(iri_company_natural_language)
names(iri_company_natural_language)[1] <- "company_name"
if (missing(company)) {
iri_company_natural_language
} else {
iri_company_natural_language[grep(company, iri_company_natural_language$company_name, ignore.case = TRUE), ]
}
}
irir_industry <- function(industry){
iri_industry_natural_language <- unique(IRI_data$industry_name)
iri_industry_natural_language <- as.data.frame(iri_industry_natural_language)
names(iri_industry_natural_language)[1] <- "industry_name"
if (missing(industry)) {
iri_industry_natural_language
} else {
iri_industry_natural_language[grep(industry, iri_industry_natural_language$industry_name, ignore.case = TRUE), ]
}
}
irir_visual <- function(country = "CAN", chart = "bar_1", title = TRUE, years = as.numeric(max(IRI_data$year))){
year <- value <- country_code <- country_name <- n.company <- indicator_code <- RD.sales <- RD.usd <- NULL
if(years > 2019 | years < 2004){
stop("no available data for the requested year")
}
if(chart == "bar_1"){
barchart1 <- IRI_data[, c("year", "company_name", "country_name", "country_code","indicator_code")]
barchart1 <- dplyr::filter(barchart1, indicator_code == "RD.euro")
barchart1 <- dplyr::filter(barchart1, year == years)
barchart1$value <- 1
barchart1 <- stats::aggregate(value ~ year + country_name + country_code, barchart1, sum, na.rm=TRUE)
barchart1 <- dplyr::arrange(barchart1, desc(value))
barchart1 <- dplyr::filter(barchart1, country_code==country | country_code==barchart1[1, 3] | country_code==barchart1[2,3] | country_code==barchart1[3, 3] | country_code==barchart1[4, 3] | country_code==barchart1[5, 3])
barchart1$country_name <- factor(barchart1$country_name, levels = unique(barchart1$country_name)[order(barchart1$value)])
if(title == TRUE){
ggplot2::ggplot(data = barchart1, aes(x = country_name, y = value, fill = country_name)) +
ggplot2::geom_col() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle(paste("Number of leading companies in R&D for the most \nrepresented countries in", years)) +
ggplot2::theme_minimal() +
guides(fill=FALSE) +
ggsci::scale_fill_uchicago() +
ggplot2::theme(legend.position="none", plot.title = element_text(size=12)) +
ggplot2::labs(fill = "Countries", caption="Source: Warin (2020) & European Commission.") +
geom_text(aes(label=value), vjust=-0.5, hjust = 0.5, colour = "black", size = 3.2, fontface = "bold")
} else {
ggplot2::ggplot(data = barchart1, aes(x = country_name, y = value, fill = country_name)) +
ggplot2::geom_col() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle("") +
ggplot2::theme_minimal() +
guides(fill=FALSE) +
ggsci::scale_fill_uchicago() +
ggplot2::theme(legend.position="none", plot.title = element_text(size=12)) +
ggplot2::labs(fill = "Countries", caption="Source: Warin (2020) & European Commission.") +
geom_text(aes(label=value), vjust=-0.5, hjust = 0.5, colour = "black", size = 3.2, fontface = "bold")
}
} else if(chart == "bar_2"){
barchart2 <- IRI_data[, c("year", "company_name", "country_name", "country_code")]
barchart2 <- dplyr::filter(barchart2, year == years)
barchart2$value <- 1
barchart2 <- stats::aggregate(value ~ year + country_name + country_code, barchart2, sum, na.rm=TRUE)
gdpWdi <- WDI::WDI(indicator = "NY.GDP.MKTP.CD", country = "all", start = years, end = years)
gdpWdi <- gdpWdi[,-1]
colnames(gdpWdi) <- c("country_name", "gdp", "year")
barchart2 <- dplyr::left_join(barchart2, gdpWdi, by = c("country_name", "year"))
barchart2$n.company <- (barchart2$value * 100e+9)/barchart2$gdp
barchart2 <- barchart2[,c("year", "country_name", "country_code", "n.company")]
barchart2 <- unique(barchart2)
barchart2 <- dplyr::arrange(barchart2, desc(n.company))
barchart2 <- dplyr::filter(barchart2, country_code==country | country_code==barchart2[1, 3] | country_code==barchart2[2,3] | country_code==barchart2[3, 3] | country_code==barchart2[4, 3] | country_code==barchart2[5, 3])
barchart2$country_name <- factor(barchart2$country_name, levels = unique(barchart2$country_name)[order(barchart2$n.company)])
barchart2$n.company <- round(barchart2$n.company, digits = 0)
if(title == TRUE){
ggplot2::ggplot(data = barchart2, aes(x = country_name, y = n.company, fill = country_name)) +
ggplot2::geom_col() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle(paste("Number of leading companies in R&D per 100 billion $US of GDP \nfor the most represented countries in", years)) +
ggplot2::theme_minimal() +
ggsci::scale_fill_uchicago() +
ggplot2::theme(legend.position="none", plot.title = element_text(size=12)) +
ggplot2::labs(fill = "Countries", caption="Source: Warin (2020), European Commission & WDI.") +
geom_text(aes(label=n.company), vjust=-0.5, hjust = 0.5, colour = "black", size = 3.2, fontface = "bold")
} else {
ggplot2::ggplot(data = barchart2, aes(x = country_name, y = n.company, fill = country_name)) +
ggplot2::geom_col() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle("") +
ggplot2::theme_minimal() +
ggsci::scale_fill_uchicago() +
ggplot2::theme(legend.position="none", plot.title = element_text(size=12)) +
ggplot2::labs(fill = "Countries", caption="Source: Warin (2020), European Commission & WDI.") +
geom_text(aes(label=n.company), vjust=-0.5, hjust = 0.5, colour = "black", size = 3.2, fontface = "bold")
}
} else if (chart == "bar_3"){
barchart3 <- IRI_data[, c("year", "country_name", "country_code", "indicator_code", "value")]
barchart3 <- dplyr::filter(barchart3, indicator_code == "RD.usd")
barchart3 <- dplyr::filter(barchart3, year == years)
barchart3 <- stats::aggregate(value ~ year + country_name + country_code, barchart3, sum, na.rm=TRUE)
barchart3 <- dplyr::arrange(barchart3, desc(value))
barchart3 <- dplyr::filter(barchart3, country_code==country | country_code==barchart3[1, 3] | country_code==barchart3[2,3] | country_code==barchart3[3, 3] | country_code==barchart3[4, 3] | country_code==barchart3[5, 3])
barchart3$country_name <- factor(barchart3$country_name, levels = unique(barchart3$country_name)[order(barchart3$value)])
if(title == TRUE){
ggplot2::ggplot(data = barchart3, aes(x = country_name, y = value, fill = country_name)) +
ggplot2::geom_col() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle(paste("R&D expenditures ($US) of the leading companies \nfor the most represented countries in", years)) +
ggplot2::theme_minimal() +
ggsci::scale_fill_uchicago() +
ggplot2::scale_y_continuous(labels = scales::dollar) +
ggplot2::theme(legend.position="none", axis.title.y = element_text(size = 12)) +
ggplot2::labs(fill = "Countries", caption="Source: Warin (2020), European Commission & WDI.") +
geom_text(aes(label=paste0("$", round(value/1000000000, digits = 0), " B")), vjust=-0.5, hjust = 0.5, colour = "black", size = 3.2, fontface = "bold")
} else {
ggplot2::ggplot(data = barchart3, aes(x = country_name, y = value, fill = country_name)) +
ggplot2::geom_col() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle("") +
ggplot2::theme_minimal() +
ggsci::scale_fill_uchicago() +
ggplot2::scale_y_continuous(labels = scales::dollar) +
ggplot2::theme(legend.position="none", axis.title.y = element_text(size = 12)) +
ggplot2::labs(fill = "Countries", caption="Source: Warin (2020), European Commission & WDI.") +
geom_text(aes(label=paste0("$", round(value/1000000000, digits = 0), " B")), vjust=-0.5, hjust = 0.5, colour = "black", size = 3.2, fontface = "bold")
}
} else if(chart == "line_1"){
linechart1 <- IRI_data[, c("year", "company_name", "country_name", "country_code","indicator_code")]
linechart1 <- dplyr::filter(linechart1, indicator_code == "RD.euro")
linechart1$value <- 1
linechart1 <- stats::aggregate(value ~ year + country_name + country_code, linechart1, sum, na.rm=TRUE)
linechart1 <- dplyr::arrange(linechart1, desc(year), desc(value))
linechart1 <- dplyr::filter(linechart1, country_code==country | country_code==linechart1[1, 3] | country_code==linechart1[2,3] | country_code==linechart1[3, 3] | country_code==linechart1[4, 3] | country_code==linechart1[5, 3])
if(title == TRUE){
ggplot2::ggplot(data = linechart1, aes(x = year, y = value, color = country_name, shape = country_name)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle(paste("Evolution as regards the number of leading companies \nin R&D for the most represented countries")) +
ggplot2::theme_minimal() +
guides(fill=FALSE) +
ggplot2::geom_point(size = 2, stroke = 1) +
ggsci::scale_color_uchicago() +
ggplot2::theme(legend.position="right", plot.title = element_text(size=12)) +
ggplot2::labs(shape = "Countries", color = "Countries", caption="Source: Warin (2020) & European Commission.")
} else {
ggplot2::ggplot(data = linechart1, aes(x = year, y = value, color = country_name, shape = country_name)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle("") +
ggplot2::theme_minimal() +
guides(fill=FALSE) +
ggplot2::geom_point(size = 2, stroke = 1) +
ggsci::scale_color_uchicago() +
ggplot2::theme(legend.position="right", plot.title = element_text(size=12)) +
ggplot2::labs(shape = "Countries", color = "Countries", caption="Source: Warin (2020) & European Commission.")
}
} else if(chart == "line_2"){
linechart2 <- IRI_data[, c("year", "company_name", "country_name", "country_code")]
linechart2$value <- 1
linechart2 <- stats::aggregate(value ~ year + country_name + country_code, linechart2, sum, na.rm=TRUE)
gdpWdi <- WDI::WDI(indicator = "NY.GDP.MKTP.CD", country = "all", start = min(IRI_data$year), end = max(IRI_data$year))
gdpWdi <- gdpWdi[,-1]
colnames(gdpWdi) <- c("country_name", "gdp", "year")
linechart2 <- dplyr::left_join(linechart2, gdpWdi, by = c("country_name", "year"))
linechart2$n.company <- (linechart2$value * 100e+9)/linechart2$gdp
linechart2 <- linechart2[,c("year", "country_name", "country_code", "n.company")]
linechart2 <- unique(linechart2)
linechart2 <- dplyr::arrange(linechart2, desc(year), desc(n.company))
linechart2 <- dplyr::filter(linechart2, country_code==country | country_code==linechart2[1, 3] | country_code==linechart2[2,3] | country_code==linechart2[3, 3] | country_code==linechart2[4, 3] | country_code==linechart2[5, 3])
if(title == TRUE){
ggplot2::ggplot(data = linechart2, aes(x = year, y = n.company, color = country_name, shape = country_name)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle(paste("Evolution as regards the number of leading companies in R&D \nper 100 billion $US of GDP for the", max(IRI_data$year), "most represented countries")) +
ggplot2::theme_minimal() +
ggplot2::geom_point(size = 2, stroke = 1) +
ggsci::scale_color_uchicago() +
ggplot2::theme(legend.position="right", plot.title = element_text(size=12)) +
ggplot2::labs(shape = "Countries", color = "Countries", caption="Source: Warin (2020), European Commission & WDI.")
} else {
ggplot2::ggplot(data = linechart2, aes(x = year, y = n.company, color = country_name, shape = country_name)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle("") +
ggplot2::theme_minimal() +
ggplot2::geom_point(size = 2, stroke = 1) +
ggsci::scale_color_uchicago() +
ggplot2::theme(legend.position="right", plot.title = element_text(size=12)) +
ggplot2::labs(shape = "Countries", color = "Countries", caption="Source: Warin (2020), European Commission & WDI.")
}
} else if (chart == "line_3"){
linechart3 <- IRI_data[, c("year", "country_name", "country_code", "indicator_code", "value")]
linechart3 <- dplyr::filter(linechart3, indicator_code == "RD.usd")
linechart3 <- stats::aggregate(value ~ year + country_name + country_code, linechart3, sum, na.rm=TRUE)
linechart3 <- dplyr::arrange(linechart3, desc(year), desc(value))
linechart3 <- dplyr::filter(linechart3, country_code==country | country_code==linechart3[1, 3] | country_code==linechart3[2,3] | country_code==linechart3[3, 3] | country_code==linechart3[4, 3] | country_code==linechart3[5, 3])
if(title == TRUE){
ggplot2::ggplot(data = linechart3, aes(x = year, y = value, color = country_name, shape = country_name)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle(paste("Evolution as regards R&D expenditures of the leading \ncompanies for the", max(IRI_data$year), "most represented countries")) +
ggplot2::theme_minimal() +
ggplot2::geom_point(size = 2, stroke = 1) +
ggsci::scale_color_uchicago() +
ggplot2::scale_y_continuous(labels = scales::dollar) +
ggplot2::theme(legend.position="right", axis.title.y = element_text(size = 12)) +
ggplot2::labs(shape = "Countries", color = "Countries", caption="Source: Warin (2020), European Commission & WDI.")
} else {
ggplot2::ggplot(data = linechart3, aes(x = year, y = value, color = country_name, shape = country_name)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle("") +
ggplot2::theme_minimal() +
ggplot2::geom_point(size = 2, stroke = 1) +
ggsci::scale_color_uchicago() +
ggplot2::scale_y_continuous(labels = scales::dollar) +
ggplot2::theme(legend.position="right", axis.title.y = element_text(size = 12)) +
ggplot2::labs(shape = "Countries", color = "Countries", caption="Source: Warin (2020), European Commission & WDI.")
}
} else if(chart == "line_4"){
linechart4 <- IRI_data[, c("year", "country_name", "country_code", "indicator_code", "value")]
linechart4 <- dplyr::filter(linechart4, indicator_code == "RD.usd")
linechart4 <- dplyr::filter(linechart4, country_code==country)
linechart4A <- stats::aggregate(value ~ year + country_name + country_code, linechart4, sum, na.rm = TRUE)
linechart4A$value <- linechart4A$value/1e+6
linechart4$n.company <- 1
linechart4B <- stats::aggregate(n.company ~ year + country_name + country_code, linechart4, sum, na.rm = TRUE)
linechart4 <- dplyr::left_join(linechart4A, linechart4B, c("year", "country_name", "country_code"))
linechart4 <- reshape2::melt(linechart4, id.vars= c("year","country_name", "country_code"))
linechart4$variable <- gsub("RD.usd", "R&D (million $US)", linechart4$variable)
linechart4$variable <- gsub("n.company", "Leading R&D companies", linechart4$variable)
if(title == TRUE){
ggplot2::ggplot(data = linechart4, aes(x = year, y = value, color = country)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle("Evolution as regards the number of leading companies in R&D \n& the total of their R&D investments (in millions of $US)") +
ggplot2::theme_minimal() +
guides(fill=FALSE) +
ggsci::scale_color_uchicago() +
ggplot2::geom_point(shape = 19, size = 2, stroke = 1.20) +
ggplot2::theme(legend.position="none") +
facet_grid(variable ~ ., scales = "free") +
ggplot2::labs(caption="Source: Warin (2020) & European Commission.")
} else{
ggplot2::ggplot(data = linechart4, aes(x = year, y = value, color = country)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle("") +
ggplot2::theme_minimal() +
guides(fill=FALSE) +
ggsci::scale_color_uchicago() +
ggplot2::geom_point(shape = 19, size = 2, stroke = 1.20) +
ggplot2::theme(legend.position="none") +
facet_grid(variable ~ ., scales = "free") +
ggplot2::labs(caption="Source: Warin (2020) & European Commission.")
}
} else if(chart == "line_5"){
linechart5 <- IRI_data[, c("year", "company_name", "country_name", "country_code", "indicator_code", "value")]
linechart5 <- dplyr::filter(linechart5, indicator_code == "RD.usd")
linechart5A <- dplyr::filter(linechart5, country_code==country)
linechart5A <- stats::aggregate(value ~ year + country_name + country_code, linechart5A, sum, na.rm = TRUE)
linechart5B <- stats::aggregate(value ~ year, linechart5, sum, na.rm = TRUE)
linechart5 <- left_join(linechart5A, linechart5B, by = "year")
linechart5$value <- linechart5$value.x /linechart5$value.y
if(title == TRUE){
ggplot2::ggplot(data = linechart5, aes(x = year, y = value, color = country)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
geom_smooth(span = 0.8) +
ggplot2::ggtitle(paste("Evolution as regards the percentage of R&D investments made by \ncompanies in", unique(linechart5$country_name), "in the total R&D investments.")) +
ggplot2::theme_minimal() +
guides(fill=FALSE) +
ggsci::scale_color_uchicago() +
ggplot2::geom_point(shape = 19, size = 2, stroke = 1.20) +
ggplot2::theme(legend.position="none", plot.title = element_text(size=12)) +
ggplot2::scale_y_continuous(labels = scales::percent_format(accuracy=.1)) +
ggplot2::labs(caption="Source: Warin (2020) & European Commission.")
} else {
ggplot2::ggplot(data = linechart5, aes(x = year, y = value, color = country)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
geom_smooth(span = 0.8) +
ggplot2::ggtitle("") +
ggplot2::theme_minimal() +
guides(fill=FALSE) +
ggsci::scale_color_uchicago() +
ggplot2::geom_point(shape = 19, size = 2, stroke = 1.20) +
ggplot2::theme(legend.position="none", plot.title = element_text(size=12)) +
ggplot2::scale_y_continuous(labels = scales::percent_format(accuracy=.1)) +
ggplot2::labs(caption="Source: Warin (2020) & European Commission.")
}
} else if (chart == "line_6"){
linechart6 <- IRI_data[, c("year", "company_name", "country_name", "country_code", "indicator_code", "value")]
linechart6 <- dplyr::filter(linechart6, country_code==country)
linechart6A <- dplyr::filter(linechart6, indicator_code == "RD.usd")
linechart6B <- dplyr::filter(linechart6, indicator_code == "employees.qty")
linechart6A <- stats::aggregate(value ~ year + country_name + country_code, linechart6A, sum, na.rm=FALSE)
linechart6B <- stats::aggregate(value ~ year + country_name + country_code, linechart6B, sum, na.rm=FALSE)
linechart6 <- left_join(linechart6A, linechart6B, by = c("country_name", "country_code", "year"))
linechart6$value <- linechart6$value.x / linechart6$value.y
if(title == TRUE){
ggplot2::ggplot(data = linechart6, aes(x = year, y = value, color = country)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle("Evolution as regards the R&D per employee in $US") +
ggplot2::theme_minimal() +
ggsci::scale_color_uchicago() +
ggplot2::geom_point(shape = 19, size = 2, stroke = 1.10) +
ggplot2::theme(plot.title = element_text(size=12)) +
ggplot2::labs(color = "Country", caption="Source: Warin(2020) & European Commission.")
} else {
ggplot2::ggplot(data = linechart6, aes(x = year, y = value, color = country)) +
geom_line() +
ggplot2::ylab("") +
ggplot2::xlab("") +
ggplot2::ggtitle("") +
ggplot2::theme_minimal() +
ggsci::scale_color_uchicago() +
ggplot2::geom_point(shape = 19, size = 2, stroke = 1.10) +
ggplot2::theme(plot.title = element_text(size=12)) +
ggplot2::labs(color = "Country", caption="Source: Warin(2020) & European Commission.")
}
} else if(chart == "point_1"){
pointchart1 <- IRI_data[, c("year", "company_name", "country_name", "country_code", "indicator_code", "value")]
pointchart1 <- dplyr::filter(pointchart1, year == years)
pointchart1A <- dplyr::filter(pointchart1, indicator_code == "RD.usd")
pointchart1B <- dplyr::filter(pointchart1, indicator_code == "sales.usd")
pointchart1A <- stats::aggregate(value ~ year + country_name + country_code, pointchart1A, sum, na.rm=FALSE)
pointchart1B <- stats::aggregate(value ~ year + country_name + country_code, pointchart1B, sum, na.rm=FALSE)
names(pointchart1A)[4] <- "RD.usd"
names(pointchart1B)[4] <- "sales.usd"
pointchart1 <- left_join(pointchart1A, pointchart1B, by = c("year", "country_name", "country_code"))
pointchart1$RD.sales <- pointchart1$sales.usd / pointchart1$RD.usd
pointchart1 <- dplyr::arrange(pointchart1, desc(RD.sales))
pointchart1 <- dplyr::filter(pointchart1, country_code==country | country_code==pointchart1[1,3] | country_code==pointchart1[2,3] | country_code==pointchart1[3,3] | country_code==pointchart1[4,3] | country_code==pointchart1[5,3])
if(title == TRUE){
ggplot2::ggplot(data = pointchart1, aes(x = RD.usd, y = RD.sales, color = country_name, shape = country_name)) +
ggplot2::geom_point() +
ggplot2::ylab("Net sales/R&D investment") +
ggplot2::xlab("Total R&D investments") +
ggplot2::ggtitle(paste("Net sales/R&D investment ratio per total R&D investment \nfor the", max(IRI_data$year), "most represented countries")) +
guides(fill=FALSE) +
ggplot2::theme_minimal() +
ggsci::scale_color_uchicago() +
ggplot2::geom_point(size = 3, stroke = 1) +
ggplot2::theme(plot.title = element_text(size=12)) +
ggplot2::labs(shape = "Countries", color = "Countries", caption="Source: Warin (2020) & European Commission.")
} else {
ggplot2::ggplot(data = pointchart1, aes(x = RD.usd, y = RD.sales, color = country_name, shape = country_name)) +
ggplot2::geom_point() +
ggplot2::ylab("Net sales/R&D investment") +
ggplot2::xlab("Total R&D investments") +
ggplot2::ggtitle("") +
guides(fill=FALSE) +
ggplot2::theme_minimal() +
ggsci::scale_color_uchicago() +
ggplot2::geom_point(size = 3, stroke = 1) +
ggplot2::labs(shape = "Countries", color = "Countries", caption="Source: Warin (2020) & European Commission.")
}
} else{
stop("invalid arguments")
}
} |
context("colours")
test_that("check hex works", {
expect_false(mapdeck:::isHexColour('
expect_false(mapdeck:::isHexColour("
expect_true(mapdeck:::isHexColour("
expect_true(mapdeck:::isHexColour('
expect_false(mapdeck:::isHexColour('
expect_true(mapdeck:::isHexColour('
expect_equal(mapdeck:::appendAlpha("
expect_equal(mapdeck:::appendAlpha("
expect_equal(mapdeck:::appendAlpha("
expect_equal(mapdeck:::appendAlpha('
expect_equal(mapdeck:::appendAlpha('
expect_equal(mapdeck:::appendAlpha('
}) |
db <- new.env(parent = emptyenv())
db$help <- NULL
db$emailHelp <- NULL
db$welcome <- NULL
db$version <- NULL
db$listAllSolvers <- NULL
db$listCategories <- NULL
db$solvers_in_category <- list()
neos_get_db <- function(key) {
db <- getNamespace("ROI.plugin.neos")$db
if ( missing(key) ) return(db)
db[[key]]
}
neos_set_db <- function(key, value) {
db <- getNamespace("ROI.plugin.neos")$db
db[[key]] <- value
invisible(NULL)
}
neos_url <- function() "https://www.neos-server.org"
neos_simple_call <- function(method) xmlrpc(neos_url(), method)
neos_lazy_simple_call <- function(method) {
if ( is.null(x <- neos_get_db(method)) ) {
x <- xmlrpc(neos_url(), method)
neos_set_db(method, x)
}
x
}
neos_help <- function() writeLines(neos_lazy_simple_call("help"))
neos_emailHelp <- function() writeLines(neos_lazy_simple_call("emailHelp"))
neos_welcome <- function() writeLines(neos_lazy_simple_call("welcome"))
neos_version <- function() neos_lazy_simple_call("version")
neos_ping <- function() neos_simple_call("ping")
neos_ls_categories <- function() neos_lazy_simple_call("listCategories")
neos_ls_solvers <- function(category = NULL) {
if ( is.null(category) ) {
neos_lazy_simple_call("listAllSolvers")
} else {
db <- getNamespace("ROI.plugin.neos")$db
if ( !category %in% names(db$solvers_in_category) ) {
params <- list(category = category)
x <- xmlrpc(neos_url(), "listSolversInCategory", params = params)
db$solvers_in_category[[category]] <- x
}
db$solvers_in_category[[category]]
}
}
neos_queue <- function(verbose = TRUE) {
queue <- neos_simple_call("printQueue")
if (verbose) {
writeLines(queue)
invisible(queue)
} else {
queue
}
}
neos_solver_template <- function(category, solver_name, input_method) {
key <- paste(clean(c(category, solver_name, input_method)), collapse = ":")
if ( is.null(neos_get_db(key)) ) {
params <- list(category = category, solvername = solver_name,
inputMethod = input_method)
template <- xmlrpc(neos_url(), "getSolverTemplate", params = params)
neos_set_db(key, read_xml(template))
}
xml_copy(neos_get_db(key))
}
set_template_parameters <- function(xml_template, params) {
template_params <- xml_children(xml_template)
template_params_names <- as.character(lapply(template_params, xml_name))
for (i in seq_along(params)) {
key <- names(params)[i]
k <- which(key == template_params_names)
if ( length(k) ) {
xml_replace(template_params[[k]], new_xml_node(key, params[[key]]))
} else {
xml_add_sibling(template_params[[length(template_params)]],
new_xml_node(key, params[[key]]))
}
}
as.character(xml_template)
}
neos_submit_job <- function(x, xmlstring, user = "", password = "") {
if ( (nchar(user) == 0L) | (nchar(password) == 0L) ) {
response <- xmlrpc(neos_url(), "submitJob", params = list(xmlstring = xmlstring))
} else {
params <- list(xmlstring = xmlstring, user = user, password = password)
response <- xmlrpc(neos_url(), "authenticatedSubmitJob", params = params)
}
neos_job(response[[1]], response[[2]], x)
}
neos_job <- function(job_number, password, x) {
job <- list()
class(job) <- "neos_job"
job$job_number <- job_number
job$password <- password
job$status <- function() {
self <- parent.env(environment())$job
xmlrpc(neos_url(), "getJobStatus",
params = list(jobNumber = self$job_number, password = self$password))
}
job$completion_code <- function() {
self <- parent.env(environment())$job
params <- list(jobNumber = self$job_number, password = self$password)
xmlrpc(neos_url(), "getCompletionCode", params = params)
}
job$info <- function() {
self <- parent.env(environment())$job
params <- list(jobNumber = self$job_number, password = self$password)
xmlrpc(neos_url(), "getJobInfo", params = params)
}
job$kill_job <- function(killmsg="") {
self <- parent.env(environment())$job
params <- list(jobNumber = self$job_number, password = self$password, killmsg = killmsg)
xmlrpc(neos_url(), "killJob", params = params)
}
job$final_results <- function(wait = FALSE) {
self <- parent.env(environment())$job
params <- list(jobNumber = self$job_number, password = self$password)
neos_method <- if (wait) "getFinalResults" else "getFinalResultsNonBlocking"
response <- xmlrpc(neos_url(), neos_method, params = params)
rawToChar(response)
}
job$output_file <- function(file_name) {
self <- parent.env(environment())$job
params <- list(jobNumber = self$job_number, password = self$password, fileName = file_name)
response <- xmlrpc(neos_url(), "getOutputFile", params = params)
response
}
job$objective_function <- objective(x)
job$solution <- function(wait = FALSE) {
self <- parent.env(environment())$job
if ( isTRUE(self$status() != "Done") & !wait ) {
message("job not finished yet")
return(NULL)
}
neos_message <- self$final_results(wait)
if ( !neos_message_indicates_success(neos_message) ) {
stop(neos_message)
}
output_file <- sprintf("%s-%s-solver-output.zip", self$job_number, self$password)
response <- self$output_file(output_file)
tmpfi <- tempfile(fileext="-neos.zip")
on.exit(unlink(tmpfi))
writeBin(response, tmpfi)
results_con <- unz(tmpfi, "results.txt")
on.exit(close(results_con))
neos_result_txt <- readLines(results_con)
neos_results <- extract_results(neos_result_txt)
objval <- tryCatch(unname(self$objective_function(neos_results$solution)), error = function(e) NA_real_)
status <- generate_status_code(neos_results$solver_status, neos_results$model_status)
neos_results$message <- neos_message
ROI_plugin_canonicalize_solution(solution = neos_results$solution,
optimum = objval, status = status,
solver = "neos", message = neos_results)
}
job
}
neos_read_result_file <- function(file, neos_message, objective_function) {
neos_results <- extract_results(readLines(file))
objval <- tryCatch(unname(objective_function(neos_results$solution)),
error = function(e) NA_real_)
status <- generate_status_code(neos_results$solver_status, neos_results$model_status)
neos_results$message <- neos_message
ROI_plugin_canonicalize_solution(solution = neos_results$solution,
optimum = objval, status = status,
solver = "neos", message = neos_results)
}
neos_client <- function() {
neos <- new.env(parent = emptyenv())
class(neos) <- "neos_client"
neos$help <- neos_help
neos$emailHelp <- neos_emailHelp
neos$welcome <- neos_welcome
neos$version <- neos_version
neos$ping <- neos_ping
neos$printQueue <- neos_queue
neos$listAllSolvers <- function() {
neos_ls_solvers()
}
neos$listSolversInCategory <- function(category) {
neos_ls_solvers(category)
}
neos$listCategories <- neos_ls_categories
neos$getSolverTemplate <- neos_solver_template
neos
} |
.Random.seed <-
c(403L, 96L, 1793153639L, 625602485L, 307531749L, -1225712580L,
-1017251838L, 2140837563L, -1487036697L, 1472558359L, -1875002080L,
1878212252L, 1999907631L, 1408892741L, -1928876932L, -1166554983L,
2066061675L, -1214060594L, -1363037676L, 444453990L, 786126460L,
-744308775L, 1678603075L, 1153253180L, 1711531516L, -1786857214L,
-1754340697L, 1796620271L, 1915832912L, -2102026616L, 1672887443L,
-34925476L, 68698202L, 1426041635L, 1708838213L, 1807206507L,
696083127L, 731608966L, 1397594688L, 1758084833L, -1471643323L,
1306818973L, -685851050L, -1807538622L, 2025772753L, 624325663L,
-165785358L, -1007087937L, -1712150903L, 1896324196L, 1514783082L,
-12491508L, -2046594258L, -1201329917L, -262725199L, -250767862L,
363253178L, -1013254840L, -1098289371L, -143944795L, 362637010L,
-683298174L, 1119691073L, 814756778L, -249751736L, 245666425L,
1618490691L, 769292129L, -662413247L, 811794408L, 90449294L,
-1622984809L, -724604981L, -945576309L, -624683548L, 578972008L,
-1750635005L, -292877671L, 1077840592L, 958836597L, 1089350903L,
1508049178L, -1881648728L, -1815311158L, 349783120L, -620221363L,
-545588601L, -373596624L, 397086840L, -2138978098L, 1521302851L,
1523073875L, 351493564L, 872848932L, 796826639L, 991840272L,
1624237150L, 377550135L, 705762753L, 1845407495L, 1602654419L,
1521000562L, 1569902748L, 2079765197L, -1175833447L, -1442945855L,
1939187274L, -1125010306L, 287428725L, 1981085091L, 1337904502L,
40494507L, 605549861L, -1503004368L, -1840450194L, -228894254L,
1523370217L, 956441073L, -719650497L, 295417777L, -162092246L,
1568736273L, 1392588824L, -956145279L, -2012274385L, 1520514846L,
-1348105195L, 1376935811L, 1779278510L, 1576247530L, -1470397864L,
-808041229L, 1943573882L, -1934234050L, -1380408372L, 1556298256L,
-2147177641L, -1736261186L, -528038283L, -71699632L, -1583855510L,
-1945511959L, -366135008L, -1953243680L, 576725277L, -287007643L,
-172890857L, 984056260L, -646752169L, -1615590097L, -778790183L,
505963251L, 1437118608L, -86430553L, -294193842L, 648538071L,
46191953L, 158749672L, -106075477L, 2147077153L, -404794856L,
741637316L, 524264082L, 1466604725L, 1277621072L, 1372502092L,
-1867887066L, 900447586L, 599472141L, 544343356L, -1777022085L,
577318966L, -284839796L, -1107102401L, 1480233104L, -1352380275L,
-1229120756L, -199491719L, 450715897L, 1336009571L, -971204016L,
1575161325L, -1895175327L, -907849726L, -92206415L, -2058170481L,
-853362784L, 1674647860L, -1319527222L, 1443854598L, 1589637615L,
-915851132L, 2140563745L, 259468896L, 1528564956L, 1721674986L,
-2079975477L, -1841947470L, 572079194L, -848886613L, 1581198956L,
-188537280L, 1619163837L, 137670669L, 276047823L, 535022561L,
380123018L, 930761551L, 1856055610L, 1176640943L, -2080602557L,
-1567654675L, -1713817498L, -1671237493L, -2099658689L, -1035139024L,
-4152069L, 800371745L, 192589518L, 336719722L, 1688039612L, 1804766120L,
1786255305L, -2104848618L, 662860719L, 1921322518L, 1719154854L,
-1098180268L, -1057194287L, 1889491024L, -1700053488L, 872474313L,
-1933553130L, 504874930L, 1405607371L, -1595730621L, -1943380927L,
-1106725469L, -221518556L, 1684891081L, 817737568L, 1428585213L,
-306720883L, 1942197807L, 1740913708L, -103002775L, -420761611L,
380321222L, -317029011L, -1353149181L, 251986900L, 1160456200L,
30758934L, -559616630L, -1624200765L, 263618080L, -2076103915L,
-1741590044L, -699721568L, 112160934L, -159032329L, 563837214L,
-237726770L, 1768425487L, 182810968L, -1717530396L, 62333905L,
-1691400911L, -1312666341L, -80757531L, 2055387038L, 1476848331L,
1860338542L, 1429158691L, -1336495785L, -2085744151L, -427221390L,
1143641495L, 1176739907L, -23745772L, -1838236937L, 329752197L,
-1997733198L, 1755384718L, 2126970785L, 1440931646L, 766735230L,
1018973847L, 1980694363L, -595058212L, -24125585L, 826801779L,
-1154563775L, -99520621L, -943129556L, -1747809391L, -212870829L,
-721601593L, 1414016531L, 1941434731L, 1674125122L, 696038971L,
-484038219L, -589480234L, 1737168738L, -176161555L, -834905554L,
-683816070L, -1163684438L, 105142444L, 1301778139L, 742151632L,
1018521014L, 1823899264L, 552789566L, -854271330L, 276127423L,
-140056736L, -1005368040L, 1630276909L, -1834983187L, -1569735766L,
-1402321467L, -27118379L, -969786133L, -106853919L, -286509346L,
907793795L, -2050116807L, -1713690315L, -653584835L, 280472421L,
1563489092L, -974542815L, 1401666635L, 339440744L, -640380544L,
-449217665L, -1460435072L, -909920032L, 1959195904L, 2105152870L,
1022709697L, 2072641862L, 175753160L, -430167702L, -1742612092L,
507012036L, 780217189L, 2024095418L, 1894738922L, -1742088573L,
1495905095L, -393320752L, -1569678157L, -523139337L, 702590381L,
-445286289L, 905278680L, 380403173L, -2145030249L, -1425250349L,
-1583710137L, 528590047L, -393159986L, -184367473L, 2091030313L,
-41630838L, -907817178L, -1483067823L, 165981458L, -1462993010L,
-331382914L, -1229725600L, -1120725257L, -1856119812L, -1388610526L,
-1854799292L, -878099182L, -163504214L, -86601685L, -1208287756L,
-1089992628L, 1368163553L, 280946721L, -1094755578L, -1805605983L,
451688849L, 1005675967L, 1832481829L, -517785006L, 1030218847L,
2122086805L, -1289798855L, -296819879L, -1472770623L, 1923229592L,
-520367331L, -1838517769L, -107535196L, -1709713880L, 1853493485L,
1600022863L, 1969735431L, -14057598L, 208036874L, -2101923136L,
-26796569L, 19764348L, -362626060L, 126503759L, 1695753239L,
-1087645693L, -383492366L, -2006717081L, -590557522L, 1719489647L,
1412785322L, 832019580L, -1017018168L, 995837119L, 254665387L,
-959527527L, -1898934980L, -511448525L, 1348357701L, 2062618188L,
-1621901852L, -414192232L, 1564585759L, -1954834252L, 992764007L,
440382606L, 947188035L, -1622550459L, -606565207L, 1265990444L,
-1855774980L, 1200250630L, -1607022475L, -1791227202L, -561207398L,
179589609L, 1377079513L, 1029621117L, 1627626300L, -1210181631L,
1449780724L, 695077753L, 265354412L, 2007043222L, -754831682L,
8701589L, 97233673L, 522275227L, -929083474L, 1924395753L, -323595561L,
-1530497310L, 1170380602L, 2011416350L, 800993989L, 527903978L,
-1237521719L, -1300380004L, -1827561471L, -502069589L, -1530060685L,
46828918L, -307518170L, -113614116L, 1166688243L, -1978373536L,
-1071380304L, -2063158125L, 807637379L, -40082793L, 973052166L,
-727978429L, 1650011562L, -2034296461L, -2111040634L, -671418112L,
2048163100L, -665928813L, -1230546409L, -1346315171L, -2086301736L,
1607202311L, -1554006815L, -1786925112L, -230784864L, -889679788L,
21178299L, 828195528L, -1716744581L, -507899590L, 1669294463L,
-295086663L, -293587027L, 1983288008L, -1308796016L, 876408618L,
-1776142983L, 1342295546L, 1016793422L, 618164229L, 1999859485L,
1467429241L, -1700319400L, -1808927291L, 979009393L, 996308871L,
991999779L, -104788665L, -757946654L, -521390361L, -800479336L,
-2007274636L, -1972882066L, -155669846L, -27013101L, 41433962L,
236755103L, -1788471853L, 1887530645L, -1785813382L, 1690078858L,
2105093228L, -179084056L, 1763196084L, -679756183L, -798871370L,
-760789827L, 700716905L, -860358419L, 867997325L, 1641942446L,
-942688707L, -630889808L, 1157220236L, 1050769164L, 1562956013L,
315505387L, -280257223L, -1841329971L, -840402555L, 508719332L,
-1467725019L, -508943326L, 774330166L, -2124611316L, -1623382736L,
-1121109215L, -2027884476L, 1858240017L, -44782771L, -1421861969L,
-281173556L, 611669740L, -640849746L, 2029304274L, -96345822L,
1364598355L, -795798644L, -62749425L, 2128495067L, 696178707L,
13230771L, 1039501670L, -1140211436L, 16886940L, 1644573884L,
-836764375L, -1683468669L, -440456424L, -577064702L, 999147207L,
1174749218L, 1955230774L, 856107883L, -1646783775L, 407335258L,
-238915099L, 90133729L, 191401793L, -1936352039L, -1155445551L,
772538601L, -1740641926L, -841596290L, 424856151L, 1952913485L,
492365864L, 1636178709L, -1826040687L, 1481583134L, 1518607736L,
1435182227L, 1970241634L, 2117107426L, -529994152L, 1032996394L,
-2054467086L, 1351250610L, -811915993L, 883692901L, 1394395354L,
1642132348L, -177577159L, -647353352L, 647781664L, 1917650625L,
-1363360045L, -1272024256L, -1388383633L, -1693505517L, -1471229621L,
-1918990617L, 1810820431L, 814590615L, -666361768L, -432503086L,
2033202338L, 586066856L, 1041394715L) |
test_that("multiplication works", {
x <- c(4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69)
r <- mkTrend_r(x, IsPlot = FALSE)
r_cpp <- mkTrend(x, IsPlot = FALSE)
expect_equal(r, r_cpp)
}) |
NULL
InputStream <- R6Class(
'InputStream',
public = list(
initialize = function(conn, length) {
private$conn <- conn
private$length <- length
seek(private$conn, 0)
},
read_lines = function(n = -1L) {
readLines(private$conn, n, warn = FALSE)
},
read = function(l = -1L) {
if (l < 0)
l <- private$length - seek(private$conn)
if (l == 0)
return(raw())
else
return(readBin(private$conn, raw(), l))
},
rewind = function() {
seek(private$conn, 0)
}
),
private = list(
conn = NULL,
length = NULL
),
cloneable = FALSE
)
NullInputStream <- R6Class(
'NullInputStream',
public = list(
read_lines = function(n = -1L) {
character()
},
read = function(l = -1L) {
raw()
},
rewind = function() invisible(),
close = function() invisible()
),
cloneable = FALSE
)
nullInputStream <- NullInputStream$new()
ErrorStream <- R6Class(
'ErrorStream',
public = list(
cat = function(... , sep = " ", fill = FALSE, labels = NULL) {
base::cat(..., sep=sep, fill=fill, labels=labels, file=stderr())
},
flush = function() {
base::flush(stderr())
}
),
cloneable = FALSE
)
stdErrStream <- ErrorStream$new()
rookCall <- function(func, req, data = NULL, dataLength = -1) {
compute <- function() {
inputStream <- if(is.null(data))
nullInputStream
else
InputStream$new(data, dataLength)
req$rook.input <- inputStream
req$rook.errors <- stdErrStream
req$httpuv.version <- httpuv_version()
if (!is.null(req$HTTP_CONTENT_TYPE))
req$CONTENT_TYPE <- req$HTTP_CONTENT_TYPE
if (!is.null(req$HTTP_CONTENT_LENGTH))
req$CONTENT_LENGTH <- req$HTTP_CONTENT_LENGTH
func(req)
}
prepare_response <- function(resp) {
if (is.null(resp) || length(resp) == 0)
return(NULL)
if (is.null(resp$headers) ||
(length(resp$headers) == 0 && is.null(names(resp$headers))))
{
resp$headers <- named_list()
}
resp$headers <- lapply(resp$headers, paste)
if ('file' %in% names(resp$body)) {
filename <- resp$body[['file']]
owned <- FALSE
if ('owned' %in% names(resp$body))
owned <- as.logical(resp$body$owned)
resp$body <- NULL
resp$bodyFile <- filename
resp$bodyFileOwned <- owned
}
resp
}
on_error <- function(e) {
list(
status=500L,
headers=list(
'Content-Type'='text/plain; charset=UTF-8'
),
body=charToRaw(enc2utf8(
paste("ERROR:", conditionMessage(e), collapse="\n")
))
)
}
compute_error <- NULL
response <- tryCatch(
compute(),
error = function(e) compute_error <<- e
)
if (!is.null(compute_error)) {
return(on_error(compute_error))
}
if (is.promise(response)) {
response %...>% prepare_response %...!% on_error
} else {
tryCatch(prepare_response(response), error = on_error)
}
}
AppWrapper <- R6Class(
'AppWrapper',
private = list(
app = NULL,
wsconns = NULL,
supportsOnHeaders = NULL
),
public = list(
initialize = function(app) {
if (is.function(app))
private$app <- list(call=app)
else
private$app <- app
private$supportsOnHeaders <- isTRUE(try(!is.null(private$app$onHeaders), silent=TRUE))
if (class(try(private$app$staticPaths, silent = TRUE)) == "try-error" ||
is.null(private$app$staticPaths))
{
self$staticPaths <- list()
} else {
self$staticPaths <- normalizeStaticPaths(private$app$staticPaths)
}
if (class(try(private$app$staticPathOptions, silent = TRUE)) == "try-error" ||
is.null(private$app$staticPathOptions))
{
self$staticPathOptions <- staticPathOptions()
} else if (inherits(private$app$staticPathOptions, "staticPathOptions")) {
self$staticPathOptions <- normalizeStaticPathOptions(private$app$staticPathOptions)
} else {
stop("staticPathOptions must be an object of class staticPathOptions.")
}
private$wsconns <- new.env(parent = emptyenv())
},
onHeaders = function(req) {
if (!private$supportsOnHeaders)
return(NULL)
rookCall(private$app$onHeaders, req)
},
onBodyData = function(req, bytes) {
if (is.null(req$.bodyData))
req$.bodyData <- file(open='w+b', encoding='UTF-8')
writeBin(bytes, req$.bodyData)
},
call = function(req, cpp_callback) {
resp <- if (is.null(private$app$call)) {
list(
status = 404L,
headers = list(
"Content-Type" = "text/plain"
),
body = "404 Not Found\n"
)
} else {
rookCall(private$app$call, req, req$.bodyData, seek(req$.bodyData))
}
clean_up <- function() {
if (!is.null(req$.bodyData)) {
close(req$.bodyData)
}
req$.bodyData <- NULL
}
if (is.promise(resp)) {
resp <- resp %...>% invokeCppCallback(., cpp_callback)
finally(resp, clean_up)
} else {
on.exit(clean_up())
invokeCppCallback(resp, cpp_callback)
}
invisible()
},
onWSOpen = function(handle, req) {
ws <- WebSocket$new(handle, req)
private$wsconns[[wsconn_address(handle)]] <- ws
result <- try(private$app$onWSOpen(ws))
if (inherits(result, 'try-error')) {
ws$close(1011, "Error in onWSOpen")
}
},
onWSMessage = function(handle, binary, message) {
for (handler in private$wsconns[[wsconn_address(handle)]]$messageCallbacks) {
result <- try(handler(binary, message))
if (inherits(result, 'try-error')) {
private$wsconns[[wsconn_address(handle)]]$close(1011, "Error executing onWSMessage")
return()
}
}
},
onWSClose = function(handle) {
ws <- private$wsconns[[wsconn_address(handle)]]
ws$handle <- NULL
rm(list = wsconn_address(handle), envir = private$wsconns)
for (handler in ws$closeCallbacks) {
handler()
}
},
staticPaths = NULL,
staticPathOptions = NULL
)
)
WebSocket <- R6Class(
'WebSocket',
public = list(
initialize = function(handle, req) {
self$handle <- handle
self$request <- req
},
onMessage = function(func) {
self$messageCallbacks <- c(self$messageCallbacks, func)
},
onClose = function(func) {
self$closeCallbacks <- c(self$closeCallbacks, func)
},
send = function(message) {
if (is.null(self$handle))
return()
if (is.raw(message))
sendWSMessage(self$handle, TRUE, message)
else {
sendWSMessage(self$handle, FALSE, as.character(message))
}
},
close = function(code = 1000L, reason = "") {
if (is.null(self$handle))
return()
code <- as.integer(code)
if (code < 0 || code > 2^16 - 1) {
warning("Invalid websocket error code: ", code)
code <- 1001L
}
reason <- iconv(reason, to = "UTF-8")
closeWS(self$handle, code, reason)
self$handle <- NULL
},
handle = NULL,
messageCallbacks = list(),
closeCallbacks = list(),
request = NULL
)
)
startServer <- function(host, port, app, quiet = FALSE) {
WebServer$new(host, port, app, quiet)
}
startPipeServer <- function(name, mask, app, quiet = FALSE) {
PipeServer$new(name, mask, app, quiet)
}
service <- function(timeoutMs = ifelse(interactive(), 100, 1000)) {
if (is.na(timeoutMs)) {
run_now(0, all = FALSE)
} else if (timeoutMs == 0 || timeoutMs == Inf) {
.globals$paused <- FALSE
check_time <- if (interactive()) 0.1 else Inf
while (!.globals$paused) {
run_now(check_time, all = FALSE)
}
} else {
run_now(timeoutMs / 1000, all = FALSE)
}
TRUE
}
runServer <- function(host, port, app, interruptIntervalMs = NULL) {
server <- startServer(host, port, app)
on.exit(stopServer(server))
service(0)
}
interrupt <- function() {
.globals$paused <- TRUE
}
rawToBase64 <- function(x) {
base64encode(x)
}
.globals <- new.env()
startDaemonizedServer <- startServer
legacy_dummy <- function(value){
.Call('httpuv_decodeURIComponent', PACKAGE = "httpuv", value)
} |
fparse <- function(json,
query = NULL,
empty_array = NULL,
empty_object = NULL,
single_null = NULL,
parse_error_ok = FALSE,
on_parse_error = NULL,
query_error_ok = FALSE,
on_query_error = NULL,
max_simplify_lvl = c("data_frame", "matrix", "vector", "list"),
type_policy = c("anything_goes", "numbers", "strict"),
int64_policy = c("double", "string", "integer64", "always"),
always_list = FALSE) {
if (!.is_valid_json_arg(json)) {
stop("`json=` must be a non-empty character vector, raw vector, or a list containing raw vectors.")
}
if (!.is_valid_query_arg(query)) {
stop("`query=` must be `NULL`, a non-empty character vector, or a list containing non-empty character vectors.")
}
if (is.list(query) && length(json) != length(query)) {
stop("`query=` is a list (nested query), but is not the same length as `json=`.")
}
if (!.is_scalar_lgl(parse_error_ok)) {
stop("`parse_error_ok=` must be either `TRUE` or `FALSE`.")
}
if (!.is_scalar_lgl(query_error_ok)) {
stop("`query_error_ok=` must be either `TRUE` or `FALSE`.")
}
if (!.is_scalar_lgl(always_list)) {
stop("`always_list=` must be either `TRUE` or `FALSE`.")
}
if (is.character(max_simplify_lvl)) {
max_simplify_lvl <- switch(
match.arg(max_simplify_lvl, c("data_frame", "matrix", "vector", "list")),
data_frame = 0L,
matrix = 1L,
vector = 2L,
list = 3L,
stop("Unknown `max_simplify_lvl=`.")
)
} else if (is.numeric(max_simplify_lvl)) {
stopifnot(max_simplify_lvl %in% 0:3)
} else {
stop("`max_simplify_lvl=` must be of type `character` or `numeric`.")
}
if (is.character(type_policy)) {
type_policy <- switch(
match.arg(type_policy, c(
"anything_goes", "numbers", "strict"
)),
anything_goes = 0L,
numbers = 1L,
strict = 2L,
stop("Unknown `type_policy=`.")
)
} else if (is.numeric(type_policy)) {
stopifnot(type_policy %in% 0:2)
} else {
stop("`type_policy=` must be of type `character` or `numeric`.")
}
if (is.character(int64_policy)) {
int64_policy <- switch(
match.arg(int64_policy, c("double", "string", "integer64", "always")),
double = 0L,
string = 1L,
integer64 = 2L,
always = 3L,
stop("Unknown `int64_policy=`.")
)
} else if (is.numeric(int64_policy)) {
stopifnot(int64_policy %in% 0:3)
} else {
stop("`int64_policy` must be of type `character` or `numeric`.")
}
if (int64_policy == 2L && !requireNamespace("bit64", quietly = TRUE)) {
stop('`int64_policy="integer64", but the {bit64} package is not installed.')
}
out <- .deserialize_json(
json = json,
query = query,
empty_array = empty_array,
empty_object = empty_object,
single_null = single_null,
parse_error_ok = parse_error_ok,
on_parse_error = on_parse_error,
query_error_ok = query_error_ok,
on_query_error = on_query_error,
simplify_to = max_simplify_lvl,
type_policy = type_policy,
int64_r_type = int64_policy
)
if (always_list && length(json) == 1L) {
`names<-`(list(out), names(json))
} else {
out
}
} |
step_dummy_hash <-
function(recipe,
...,
role = "predictor",
trained = FALSE,
columns = NULL,
signed = TRUE,
num_terms = 32L,
collapse = FALSE,
prefix = "hash",
skip = FALSE,
id = rand_id("dummy_hash")) {
recipes::recipes_pkg_check(required_pkgs.step_dummy_hash())
add_step(
recipe,
step_dummy_hash_new(
terms = enquos(...),
role = role,
trained = trained,
columns = columns,
signed = signed,
num_terms = num_terms,
collapse = collapse,
prefix = prefix,
skip = skip,
id = id
)
)
}
step_dummy_hash_new <-
function(terms, role, trained, columns, signed, collapse ,num_terms, prefix,
skip, id) {
step(
subclass = "dummy_hash",
terms = terms,
role = role,
trained = trained,
columns = columns,
signed = signed,
num_terms = num_terms,
collapse = collapse,
prefix = prefix,
skip = skip,
id = id
)
}
prep.step_dummy_hash <- function(x, training, info = NULL, ...) {
col_names <- recipes_eval_select(x$terms, training, info)
recipes::check_type(training[, col_names], quant = FALSE)
step_dummy_hash_new(
terms = x$terms,
role = x$role,
trained = TRUE,
columns = col_names,
signed = x$signed,
num_terms = x$num_terms,
collapse = x$collapse,
prefix = x$prefix,
skip = x$skip,
id = x$id
)
}
bake.step_dummy_hash <- function(object, new_data, ...) {
if (length(object$columns) == 0L) {
return(new_data)
}
col_names <- object$columns
hash_cols <- col_names
if (object$collapse) {
new_name <- paste0(col_names, collapse = "_")
new_data <-
new_data %>%
dplyr::rowwise() %>%
dplyr::mutate(
!!new_name :=
paste0(dplyr::c_across(dplyr::all_of(hash_cols)), collapse = "")
)
hash_cols <- new_name
}
for (i in seq_along(hash_cols)) {
tf_text <-
hashing_function(
as.character(new_data[[ hash_cols[i] ]]),
paste0(hash_cols[i], "_", names0(object$num_terms, object$prefix)
),
object$signed,
object$num_terms
)
new_data <- new_data[, !(colnames(new_data) %in% hash_cols[i]), drop = FALSE]
new_data <- vctrs::vec_cbind(tf_text, new_data)
}
if (object$collapse) {
new_data <- new_data[, !(colnames(new_data) %in% col_names), drop = FALSE]
}
as_tibble(new_data)
}
print.step_dummy_hash <-
function(x, width = max(20, options()$width - 30), ...) {
cat("Feature hashing with ", sep = "")
printer(x$columns, x$terms, x$trained, width = width)
invisible(x)
}
tidy.step_dummy_hash <- function(x, ...) {
if (is_trained(x)) {
res <- tibble(
terms = unname(x$columns),
value = x$signed,
num_terms = x$num_terms,
collapse = x$collapse
)
} else {
term_names <- sel2char(x$terms)
res <- tibble(
terms = term_names,
value = na_lgl,
num_terms = na_int,
collapse = na_lgl
)
}
res$id <- x$id
res
}
required_pkgs.step_dummy_hash <- function(x, ...) {
c("text2vec", "textrecipes")
}
tunable.step_dummy_hash <- function(x, ...) {
tibble::tibble(
name = c("signed", "num_terms"),
call_info = list(
list(pkg = "dials", fun = "signed_hash"),
list(pkg = "dials", fun = "num_hash", range = c(8, 12))
),
source = "recipe",
component = "step_dummy_hash",
component_id = x$id
)
} |
NULL
zmq.poll <- function(socket, type, timeout = -1L, MC = .pbd_env$ZMQ.MC){
if(length(socket) != length(type)){
stop("socket and type are of different length.")
}
type <- as.integer(type)
if(!all(type %in% 1:7)){
stop("type should be integers in 1 to 7.")
}
zmq.poll.free()
ret <- .Call("R_zmq_poll", socket, type, as.integer(timeout),
as.logical(MC$check.eintr),
PACKAGE = "pbdZMQ")
return(invisible(ret))
}
zmq.poll.free <- function(){
ret <- .Call("R_zmq_poll_free", PACKAGE = "pbdZMQ")
invisible(ret)
}
zmq.poll.length <- function(){
ret <- .Call("R_zmq_poll_length", PACKAGE = "pbdZMQ")
invisible(ret)
}
zmq.poll.get.revents <- function(index = 1L){
if(index < 1){
stop("index is a positive interger.")
}
ret <- .Call("R_zmq_poll_get_revents", as.integer(index - 1)[1],
PACKAGE = "pbdZMQ")
invisible(ret)
} |
stamp.direction <- function(stmp,dir.mode="CentroidAngle",ndir=4,group=FALSE){
CentroidAngle <- function(stmp,group=FALSE){
stmp$CENDIR <- NA
grps <- unique(stmp$GROUP)
for (i in grps){
ind <- which(stmp$GROUP == i)
if (length(ind) > 1){
t1.base <- stmp[which(stmp$GROUP == i & is.na(stmp$ID1) == FALSE),]
c1 <- coordinates(gCentroid(t1.base))
if (group==FALSE){
for (j in ind){
c2 <- coordinates(gCentroid(stmp[j,]))
dy <- c2[2] - c1[2]
dx <- c2[1] - c1[1]
temp <- atan2(dx,dy)*180/pi
if (temp < 0){temp <- 360 + temp}
stmp$CENDIR[j] <- temp
}
} else {
t2.base <- stmp[which(stmp$GROUP == i & is.na(stmp$ID2) == FALSE),]
c2 <- coordinates(gCentroid(t2.base))
dy <- c2[2] - c1[2]
dx <- c2[1] - c1[1]
temp <- atan2(dx,dy)*180/pi
if (temp < 0){temp <- 360 + temp}
stmp$CENDIR[ind] <- temp
}
}
}
return(stmp)
}
ConeModel <- function(stmp,ndir=4){
cwidth <- 2*pi/ndir
origins <- seq(0,2*pi,by=cwidth)
dexpand <- sqrt( (bbox(stmp)[1,2]-bbox(stmp)[1,1])^2 + (bbox(stmp)[2,2]-bbox(stmp)[2,1])^2 )
cols <- paste("DIR",round(origins*180/pi),sep="")[1:ndir]
stmp@data[,cols] <- NA
grps <- unique(stmp$GROUP)
for (i in grps){
ind <- which(stmp$GROUP == i)
if (length(ind) > 1){
t1.base <- stmp[which(stmp$GROUP == i & is.na(stmp$ID1) == FALSE),]
c1 <- coordinates(gCentroid(t1.base))
for (j in 1:ndir){
theta1 <- origins[j] + 0.5*cwidth
theta2 <- origins[j] - 0.5*cwidth
c2 <- c1 + c(sin(theta1),cos(theta1))*dexpand
c3 <- c1 + c(sin(theta2),cos(theta2))*dexpand
cone <- SpatialPolygons(list(Polygons(list(Polygon(rbind(c1,c3,c2,c1))),1)),proj4string=stmp@proj4string)
for (k in 1:length(ind)){
into <- gIntersection(cone,stmp[ind[k],])
if (is.null(into) == FALSE) {
stmp@data[ind[k],cols[j]] <- gArea(into)
}
else {
stmp@data[ind[k],cols[j]] <- 0
}
}
}
}
}
return(stmp)
}
MBRModel <- function(stmp){
dexpand <- sqrt( (bbox(stmp)[1,2]-bbox(stmp)[1,1])^2 + (bbox(stmp)[2,2]-bbox(stmp)[2,1])^2 )
c1 <- c(1,2,3,5,6,7,9,10,11)
cols <- c("SW","S","SE","W","SAME","E","NW","N","NE")
stmp@data[,cols] <- NA
grps <- unique(stmp$GROUP)
for (i in grps){
ind <- which(stmp$GROUP == i)
if (length(ind) > 1){
t1.base <- stmp[which(stmp$GROUP == i & is.na(stmp$ID1) == FALSE),]
t1.bbox <- bbox(t1.base)
x.tmp <- c(t1.bbox[1,1]-dexpand,t1.bbox[1,1],t1.bbox[1,2],t1.bbox[1,2]+dexpand)
y.tmp <- c(t1.bbox[2,1]-dexpand,t1.bbox[2,1],t1.bbox[2,2],t1.bbox[2,2]+dexpand)
crds <- expand.grid(list(x=x.tmp,y=y.tmp))
for (j in 1:9){
ind.crds <- c(c1[j],c1[j]+4,c1[j]+5,c1[j]+1,c1[j])
box.poly <- SpatialPolygons(list(Polygons(list(Polygon(crds[ind.crds,])),1)),proj4string=stmp@proj4string)
for (k in 1:length(ind)){
into <- gIntersection(box.poly,stmp[ind[k],])
if (is.null(into) == FALSE) {
stmp@data[ind[k],cols[j]] <- gArea(into)
}
else {
stmp@data[ind[k],cols[j]] <- 0
}
}
}
}
}
return(stmp)
}
ModConeModel <- function(stmp,ndir=4){
allcoords = function(x) {
vert = NULL
polys = slot(x,'polygons')
for(i in 1:length(polys)) {
pp = slot(polys[[i]],'Polygons')
for (j in 1:length(pp)) {vert = rbind(vert, coordinates(pp[[j]]))}
}
return(data.frame(x=vert[,1],y=vert[,2]))
}
voronoipolygons <- function(x,poly) {
if (.hasSlot(x, 'coords')) {
crds <- slot(x,'coords')
} else crds <- x
bb = bbox(poly)
rw = as.numeric(t(bbox(poly)))
z <- deldir(crds[,1], crds[,2],rw=rw,supressMsge=TRUE)
w <- tile.list(z)
polys <- vector(mode='list', length=length(w))
for (i in seq(along=polys)) {
pcrds <- cbind(w[[i]]$x, w[[i]]$y)
pcrds <- rbind(pcrds, pcrds[1,])
polys[[i]] <- Polygons(list(Polygon(pcrds)), ID=as.character(i))
}
SP <- SpatialPolygons(polys)
voronoi <- SpatialPolygonsDataFrame(SP, data=data.frame(x=crds[,1],y=crds[,2], row.names=sapply(slot(SP, 'polygons'),function(x) slot(x, 'ID'))))
return(voronoi)
}
ModVoronoi <- function(multi.pol,bbox.sp){
verts <- unique(allcoords(multi.pol))
vor <- voronoipolygons(verts,gBuffer(bbox.sp,width=1))
data <- vor@data
slot(vor,'proj4string') <- slot(bbox.sp,'proj4string')
vor <- gIntersection(vor,bbox.sp,byid=T,id=as.character(1:length(vor)))
vor <- SpatialPolygonsDataFrame(vor,data=data)
vor$own <- NA
for (p in 1:length(multi.pol)){vor$own[gIntersects(vor,multi.pol[p,],byid=T)] <- multi.pol@polygons[[p]]@ID}
vor <- unionSpatialPolygons(vor,vor$own)
return(vor)
}
if (ndir == 4) {
cols <- c("N","E","S","W")
slot(stmp,'data')[,cols] <- 0
c2.ind <- c(3,4,2,1)
c4.ind <- c(4,2,1,3)
}
if (ndir == 8) {
cols <- c("N","NE","E","SE","S","SW","W","NW")
slot(stmp,'data')[,cols] <- 0
c2.ind <- c(22,24,20,10,4,2,6,16)
c3.ind <- c(23,25,15,5,3,1,11,21)
c4.ind <- c(24,20,10,4,2,6,16,22)
}
grps <- unique(stmp$GROUP)
for (i in grps){
ind <- which(stmp$GROUP == i)
stb <- which(stmp$LEV3[ind] == "STBL")
if (length(ind) > 1){
bbox.sp <- gEnvelope(stmp[ind,])
if (ndir == 4){
x.tmp <- bbox(stmp[ind,])[1,]
y.tmp <- bbox(stmp[ind,])[2,]
crds <- expand.grid(x=x.tmp,y=y.tmp)
}
if (ndir == 8){
dx <- bbox(stmp[ind,])[1,2] - bbox(stmp[ind,])[1,1]
x.tmp <- c(bbox(stmp[ind,])[1,1],bbox(stmp[ind,])[1,1] + 0.25*dx,bbox(stmp[ind,])[1,1] + 0.5*dx, bbox(stmp[ind,])[1,1] + 0.75*dx, bbox(stmp[ind,])[1,2])
dy <- bbox(stmp[ind,])[2,2] - bbox(stmp[ind,])[2,1]
y.tmp <- c(bbox(stmp[ind,])[2,1],bbox(stmp[ind,])[2,1] + 0.25*dy,bbox(stmp[ind,])[2,1] + 0.5*dy, bbox(stmp[ind,])[2,1] + 0.75*dy, bbox(stmp[ind,])[2,2])
crds <- expand.grid(x=x.tmp,y=y.tmp)
}
if (length(stb) < 1){
t1.base <- stmp[which(stmp$GROUP == i & is.na(stmp$ID1) == FALSE),]
c1 <- coordinates(gCentroid(t1.base))
for (j in 1:ndir){
c2 <- crds[c2.ind[j],]
c4 <- crds[c4.ind[j],]
if (ndir==8){c3 <- crds[c3.ind[j],]}
else{c3 <- (c2+c4)/2}
cone <- SpatialPolygons(list(Polygons(list(Polygon(rbind(c1,c2,c3,c4,c1))),1)),proj4string=stmp@proj4string)
for (k in 1:length(ind)){
into <- gIntersection(cone,stmp[ind[k],])
if (is.null(into) == FALSE) {
stmp@data[ind[k],cols[j]] <- gArea(into)
}
}
}
} else if (length(stb) == 1){
ID1.stb <- unique(stmp$ID1[ind[stb]])
T1.stb <- stmp[which(stmp$ID1 %in% ID1.stb),]
c1 <- coordinates(gCentroid(T1.stb))
for (j in 1:ndir){
c2 <- crds[c2.ind[j],]
c4 <- crds[c4.ind[j],]
if (ndir==8){c3 <- crds[c3.ind[j],]}
else{c3 <- (c2+c4)/2}
cone <- SpatialPolygons(list(Polygons(list(Polygon(rbind(c1,c2,c3,c4,c1))),1)),proj4string=stmp@proj4string)
for (k in 1:length(ind)){
into <- gIntersection(cone,stmp[ind[k],])
if (!is.null(into)) {
stmp@data[ind[k],cols[j]] <- gArea(into)
}
}
}
} else {
print('c3c')
ID1.stb <- unique(stmp$ID1[ind[stb]])
T1.stb <- stmp[which(stmp$ID1 %in% ID1.stb),]
if (stmp$LEV4[ind[1]] == "UNION"){
vor.p <- ModVoronoi(T1.stb,bbox.sp)
}
else if (stmp$LEV4[ind[1]] == "DIVISION"){
ID2.stb <- unique(stmp$ID2[ind[stb]])
T2.stb <- stmp[which(row.names(stmp) %in% ID2.stb),]
vor.p <- ModVoronoi(T2.stb,bbox.sp)
}
else{
vor.p1 <-ModVoronoi(T1.stb,bbox.sp)
ID2.stb <- unique(stmp$ID2[ind[stb]])
T2.stb <- stmp[which(row.names(stmp) %in% ID2.stb),]
vor.p2 <- ModVoronoi(T2.stb,bbox.sp)
vor.p <- gIntersection(vor.p1,vor.p2,byid=T)
}
for (vor in 1:length(vor.p)){
print('c4')
c1 <- coordinates(gCentroid(gIntersection(T1.stb,vor.p[vor,])))
for (j in 1:ndir){
c2 <- crds[c2.ind[j],]
c4 <- crds[c4.ind[j],]
if (ndir==8){c3 <- crds[c3.ind[j],]}
else{c3 <- (c2+c4)/2}
cone <- SpatialPolygons(list(Polygons(list(Polygon(rbind(c1,c2,c3,c4,c1))),1)),proj4string=stmp@proj4string)
modCone <- gIntersection(cone,vor.p[vor,])
for (k in 1:length(ind)){
into <- gIntersection(modCone,stmp[ind[k],])
if (is.null(into) == FALSE) {
stmp@data[ind[k],cols[j]] <- stmp@data[ind[k],cols[j]] + gArea(into)
}
}
}
}
}
} else {stmp@data[ind,cols] <- NA}
}
return(stmp)
}
stmp <- switch(dir.mode,
CentroidAngle = CentroidAngle(stmp,group),
ConeModel = ConeModel(stmp,ndir),
MBRModel = MBRModel(stmp),
ModConeModel = ModConeModel(stmp,ndir),
stop(paste("The direction method is does not exist: ",dir.mode)))
return(stmp)
} |
visual_testing <- grepl("true", Sys.getenv("VISUAL_TESTS"), fixed = TRUE)
message("Visual testing is ", if (!visual_testing) "not ", "enabled.")
imageServer <- if (visual_testing) {
kaleido()
} else {
list(transform = function(...) stop("Visual testing is disabled!"))
}
expect_doppelganger <- function(p, name, ...) {
testthat::local_edition(3)
name <- str_standardise(name)
file <- paste0(name, ".svg")
path <- tempfile(file, fileext = ".svg")
testthat::announce_snapshot_file(path, name = file)
if (!visual_testing) {
return(invisible(NULL))
}
set.seed(555)
write_plotly_svg(p, path)
testthat::expect_snapshot_file(path = path, name = file, cran = FALSE)
}
expect_doppelganger_built <- function(p, name, ...) {
expect_doppelganger(p, name, ...)
plotly_build(p)$x[c("data", "layout")]
}
write_plotly_svg <- function(p, file) {
p <- plotly_build(p)
uid_data <- paste0("-vdiffr-plotly-", seq_along(p$x$data))
p$x$data <- Map(function(tr, id) { tr$uid <- id; tr }, p$x$data, uid_data)
owd <- setwd(dirname(file))
on.exit(setwd(owd))
imageServer$transform(p, file = basename(file), width = 640, height = 480)
svg_txt <- readLines(file, warn = FALSE)
strextract <- function(str, pattern) regmatches(str, regexpr(pattern, str))
def <- strextract(svg_txt, 'defs id=\\"defs-[[:alnum:]]+\\"')
uid <- sub("defs-", "", strextract(def, "defs-[[:alnum:]]+"))
svg_txt <- gsub(uid, "", svg_txt, fixed = TRUE)
writeLines(svg_txt, file)
}
str_standardise <- function(s, sep = "-") {
stopifnot(rlang::is_scalar_character(s))
s <- gsub("[^a-z0-9]", sep, tolower(s))
s <- gsub(paste0(sep, sep, "+"), sep, s)
s <- gsub(paste0("^", sep, "|", sep, "$"), "", s)
s
} |
NULL
lfmm_fit <- function(m, dat, ...) {
UseMethod("lfmm_fit")
}
lfmm_fit_knowing_loadings <- function(m, dat, ...) {
UseMethod("lfmm_fit_knowing_loadings")
}
lfmm_impute <- function(m, dat, ...) {
UseMethod("lfmm_impute")
}
lfmm_residual_error2 <- function(m, dat, ...) {
UseMethod("lfmm_residual_error2")
} |
gssanova1 <- function(formula,family,type=NULL,data=list(),weights,
subset,offset,na.action=na.omit,partial=NULL,
method=NULL,varht=1,alpha=1.4,nu=NULL,
id.basis=NULL,nbasis=NULL,seed=NULL,random=NULL,
skip.iter=FALSE)
{
if (!(family%in%c("binomial","poisson","Gamma","nbinomial","inverse.gaussian",
"polr","weibull","lognorm","loglogis")))
stop("gss error in gssanova1: family not implemented")
mf <- match.call()
mf$family <- mf$type <- mf$partial <- NULL
mf$method <- mf$varht <- mf$nu <- NULL
mf$alpha <- mf$id.basis <- mf$nbasis <- mf$seed <- NULL
mf$random <- mf$skip.iter <- NULL
mf[[1]] <- as.name("model.frame")
mf <- eval(mf,parent.frame())
wt <- model.weights(mf)
nobs <- dim(mf)[1]
if (is.null(id.basis)) {
if (is.null(nbasis)) nbasis <- max(30,ceiling(10*nobs^(2/9)))
if (nbasis>=nobs) nbasis <- nobs
if (!is.null(seed)) set.seed(seed)
id.basis <- sample(nobs,nbasis,prob=wt)
}
else {
if (max(id.basis)>nobs|min(id.basis)<1)
stop("gss error in gssanova: id.basis out of range")
nbasis <- length(id.basis)
}
term <- mkterm(mf,type)
if (!is.null(random)) {
if (class(random)=="formula") random <- mkran(random,data)
}
if (is.null(method)) {
method <- switch(family,
binomial="u",
nbinomial="u",
poisson="u",
inverse.gaussian="v",
Gamma="v",
polr="u",
weibull="u",
lognorm="u",
loglogis="u")
}
s <- r <- NULL
nq <- 0
for (label in term$labels) {
if (label=="1") {
s <- cbind(s,rep(1,len=nobs))
next
}
x <- mf[,term[[label]]$vlist]
x.basis <- mf[id.basis,term[[label]]$vlist]
nphi <- term[[label]]$nphi
nrk <- term[[label]]$nrk
if (nphi) {
phi <- term[[label]]$phi
for (i in 1:nphi)
s <- cbind(s,phi$fun(x,nu=i,env=phi$env))
}
if (nrk) {
rk <- term[[label]]$rk
for (i in 1:nrk) {
nq <- nq+1
r <- array(c(r,rk$fun(x,x.basis,nu=i,env=rk$env,out=TRUE)),c(nobs,nbasis,nq))
}
}
}
if (is.null(r))
stop("gss error in gssanova1: use glm for models with only unpenalized terms")
if (!is.null(partial)) {
mf.p <- model.frame(partial,data)
for (lab in colnames(mf.p)) mf[,lab] <- mf.p[,lab]
mt.p <- attr(mf.p,"terms")
lab.p <- labels(mt.p)
matx.p <- model.matrix(mt.p,data)[,-1,drop=FALSE]
if (dim(matx.p)[1]!=dim(mf)[1])
stop("gss error in ssanova: partial data are of wrong size")
matx.p <- scale(matx.p)
center.p <- attr(matx.p,"scaled:center")
scale.p <- attr(matx.p,"scaled:scale")
s <- cbind(s,matx.p)
part <- list(mt=mt.p,center=center.p,scale=scale.p)
}
else part <- lab.p <- NULL
if (qr(s)$rank<dim(s)[2])
stop("gss error in gssanova: unpenalized terms are linearly dependent")
if (family=="polr") {
y <- model.response(mf)
if (!is.factor(y))
stop("gss error in gssanova1: need factor response for polr family")
lvls <- levels(y)
if (nlvl <- length(lvls)<3)
stop("gss error in gssanova1: need at least 3 levels to fit polr family")
y <- outer(y,lvls,"==")
}
else y <- model.response(mf,"numeric")
offset <- model.offset(mf)
if (!is.null(offset)) {
term$labels <- c(term$labels,"offset")
term$offset <- list(nphi=0,nrk=0)
}
nu.wk <- list(NULL,FALSE)
if ((family=="nbinomial")&is.vector(y)) nu.wk <- list(NULL,TRUE)
if (family%in%c("weibull","lognorm","loglogis")) {
if (is.null(nu)) nu.wk <- list(nu,TRUE)
else nu.wk <- list(nu,FALSE)
}
z <- ngreg1(family,s,r,id.basis,y,wt,offset,method,varht,alpha,nu.wk,
random,skip.iter)
desc <- NULL
for (label in term$labels)
desc <- rbind(desc,as.numeric(c(term[[label]][c("nphi","nrk")])))
if (!is.null(partial)) {
desc <- rbind(desc,matrix(c(1,0),length(lab.p),2,byrow=TRUE))
}
desc <- rbind(desc,apply(desc,2,sum))
if (is.null(partial)) rownames(desc) <- c(term$labels,"total")
else rownames(desc) <- c(term$labels,lab.p,"total")
colnames(desc) <- c("Unpenalized","Penalized")
obj <- c(list(call=match.call(),family=family,mf=mf,terms=term,desc=desc,
alpha=alpha,id.basis=id.basis,partial=part,lab.p=lab.p,
random=random,skip.iter=skip.iter),z)
class(obj) <- c("gssanova","ssanova")
obj
}
ngreg1 <- function(family,s,r,id.basis,y,wt,offset,method,varht,alpha,nu,
random,skip.iter)
{
nobs <- dim(s)[1]
nq <- dim(r)[3]
eta <- rep(0,nobs)
if (family%in%c("Gamma","inverse.gaussian")) {
yy <- log(y)
if (!is.null(offset)) yy <- yy-offset
if (nq==1) {
z <- sspreg1(s,r[,,1],r[id.basis,,1],yy,wt,"v",alpha,varht,random)
eta <- s%*%z$d+10^z$theta*r[,,1]%*%z$c
if (!is.null(random)) eta <- eta+random$z%*%z$b
eta <- as.vector(eta)
}
else {
z <- mspreg1(s,r,id.basis,yy,wt,"v",alpha,varht,random,skip.iter)
r.wk <- 0
for (i in 1:nq) r.wk <- r.wk+10^z$theta[i]*r[,,i]
eta <- s%*%z$d+r.wk%*%z$c
if (!is.null(random)) eta <- eta+random$z%*%z$b
eta <- as.vector(eta)
}
}
if (nu[[2]]&is.null(nu[[1]])) {
wk <- switch(family,
nbinomial=mkdata.nbinomial(y,eta,wt,offset,NULL),
weibull=mkdata.weibull(y,eta,wt,offset,nu),
lognorm=mkdata.lognorm(y,eta,wt,offset,nu),
loglogis=mkdata.loglogis(y,eta,wt,offset,nu))
nu <- wk$nu
}
if (family=="polr") {
if (is.null(wt)) P <- apply(y,2,sum)
else P <- apply(y*wt,2,sum)
P <- P/sum(P)
P <- cumsum(P)
nnu <- length(P)-2
eta <- rep(qlogis(P[1]),nobs)
nu <- diff(qlogis(P[-(nnu+2)]))
}
iter <- 0
repeat {
iter <- iter+1
dat <- switch(family,
binomial=mkdata.binomial(y,eta,wt,offset),
nbinomial=mkdata.nbinomial(y,eta,wt,offset,nu),
polr=mkdata.polr(y,eta,wt,offset,nu),
poisson=mkdata.poisson(y,eta,wt,offset),
inverse.gaussian=mkdata.inverse.gaussian(y,eta,wt,offset),
Gamma=mkdata.Gamma(y,eta,wt,offset),
weibull=mkdata.weibull(y,eta,wt,offset,nu),
lognorm=mkdata.lognorm(y,eta,wt,offset,nu),
loglogis=mkdata.loglogis(y,eta,wt,offset,nu))
nu <- dat$nu
w <- as.vector(sqrt(dat$wt))
if (nq==1) {
z <- sspreg1(s,r[,,1],r[id.basis,,1],dat$ywk,w,method,alpha,varht,random)
}
else z <- mspreg1(s,r,id.basis,dat$ywk,w,method,alpha,varht,random,skip.iter)
r.wk <- 0
for (i in 1:nq) r.wk <- r.wk + 10^z$theta[i]*r[,,i]
if (!is.null(random)) r.wk <- cbind(r.wk,random$z)
eta.new <- as.vector(s%*%z$d+r.wk%*%c(z$c,z$b))
if (!is.null(offset)) eta.new <- eta.new + offset
disc <- sum(dat$wt*((eta-eta.new)/(1+abs(eta)))^2)/sum(dat$wt)
eta <- eta.new
if (disc<1e-7) break
if (iter>=30) {
warning("gss warning in gssanova1: performance-oriented iteration fails to converge")
break
}
}
if (is.list(nu)) nu <- nu[[1]]
c(z,list(nu=nu,eta=eta,w=dat$wt))
} |
testthat::context("Cheking all functions form packages")
library(NADIA)
library(testthat)
test_set <- iris
test_set$Sepal.Length[sample(1:150, 50)] <- NA
test_set$Species[sample(1:150, 50)] <- NA
col_type <- 1:5
col_type <- c(rep("numeric", 4), "factor")
percent_of_missing <- 1:5
for (i in percent_of_missing) {
percent_of_missing[i] <- (sum(is.na(test_set[, i])) / length(test_set)) * 100
}
col_no_miss <- colnames(test_set)[percent_of_missing == 0]
col_miss <- colnames(test_set)[percent_of_missing > 0]
test_set <- iris
test_set$Sepal.Length[sample(1:150, 50)] <- NA
test_set$Species[sample(1:150, 50)] <- NA
col_type <- 1:5
col_type <- c(rep("numeric", 4), "factor")
percent_of_missing <- 1:5
for (i in percent_of_missing) {
percent_of_missing[i] <- (sum(is.na(test_set[, i])) / length(test_set)) * 100
}
col_no_miss <- colnames(test_set)[percent_of_missing == 0]
col_miss <- colnames(test_set)[percent_of_missing > 0]
test_that("Modyfied iris set Amleia", {
expect_equal(sum(is.na(autotune_Amelia(test_set, col_type = col_type, percent_of_missing = percent_of_missing,parallel = FALSE))), 0)
})
test_that("Modyfied iris set mice", {
expect_equal(sum(is.na(autotune_mice(test_set, col_miss = col_miss, col_no_miss = col_no_miss, col_type = col_type, percent_of_missing = percent_of_missing, optimize = F, iter = 2))), 0)
})
test_that("Modyfied iris set missForest", {
expect_equal(sum(is.na(autotune_missForest(test_set, col_type = col_type, percent_of_missing = percent_of_missing, parallel = FALSE, optimize = FALSE))), 0)
})
test_that("Modyfied iris set missRanger", {
expect_equal(sum(is.na(autotune_missRanger(test_set, percent_of_missing = percent_of_missing))), 0)
})
test_that("Modyfied iris set softImpute", {
expect_equal(sum(is.na(autotune_softImpute(test_set, col_type = col_type, percent_of_missing = percent_of_missing))), 0)
})
test_that("Modyfied iris set VIM_HD", {
expect_equal(sum(is.na(autotune_VIM_hotdeck(test_set, percent_of_missing = percent_of_missing))), 0)
})
test_that("Modyfied iris set VIM_irmi", {
expect_equal(sum(is.na(autotune_VIM_Irmi(test_set, col_type = col_type, percent_of_missing = percent_of_missing))), 0)
})
test_that("Modyfied iris set VIM_knn", {
expect_equal(sum(is.na(autotune_VIM_kNN(test_set, percent_of_missing = percent_of_missing))), 0)
})
test_that("Modyfied iris set ViM_regrImp", {
expect_equal(sum(is.na(autotune_VIM_regrImp(test_set, col_type = col_type, percent_of_missing = percent_of_missing))), 0)
})
test_that("Modyfied iris set missMDA FMAD", {
expect_equal(sum(is.na(missMDA_FMAD_MCA_PCA(test_set, col_type = col_type, percent_of_missing = percent_of_missing, optimize_ncp = FALSE))), 0)
})
test_that("Modyfied iris set missMDA MFA", {
expect_equal(sum(is.na(missMDA_MFA(test_set, col_type = col_type, percent_of_missing = percent_of_missing))), 0)
})
test_set <- data.frame(
"a" = runif(100, 0, 10),
"b" = rnorm(100, 0, 3),
"c" = rbeta(100, 2, 2),
"d" = rcauchy(100),
"f" = rweibull(n = 100, 100, 3))
for (i in 1:5) {
test_set[, i][sample(1:100, sample(1:70, 1))] <- NA
}
col_type <- rep("numeric", 5)
percent_of_missing <- 1:5
for (i in percent_of_missing) {
percent_of_missing[i] <- (sum(is.na(test_set[, i])) / length(test_set)) * 100
}
col_no_miss <- colnames(test_set)[percent_of_missing == 0]
col_miss <- colnames(test_set)[percent_of_missing > 0]
test_that("Small numeric data set Amleia", {
expect_equal(sum(is.na(autotune_Amelia(test_set, col_type = col_type, percent_of_missing = percent_of_missing,parallel = FALSE))), 0)
})
test_that("Small numeric data set mice", {
expect_error(sum(is.na(autotune_mice(test_set, col_miss = col_miss, col_no_miss = col_no_miss, col_type = col_type, percent_of_missing = percent_of_missing, optimize = F, iter = 2))), "`mice` detected constant and/or collinear variables. No predictors were left after their removal.")
})
test_that("Small numeric data set missForest", {
expect_equal(sum(is.na(autotune_missForest(test_set, col_type = col_type, percent_of_missing = percent_of_missing, parallel = FALSE, optimize = FALSE))), 0)
})
test_that("Small numeric data set missRanger", {
expect_equal(sum(is.na(autotune_missRanger(test_set, percent_of_missing = percent_of_missing))), 0)
})
test_that("Small numeric data set softImpute", {
expect_equal(sum(is.na(autotune_softImpute(test_set, col_type = col_type, percent_of_missing = percent_of_missing))), 0)
})
test_that("Small numeric data set VIM_HD", {
expect_equal(sum(is.na(autotune_VIM_hotdeck(test_set, percent_of_missing = percent_of_missing))), 0)
})
test_that("Small numeric data set VIM_irmi", {
expect_equal(sum(is.na(autotune_VIM_Irmi(test_set, col_type = col_type, percent_of_missing = percent_of_missing))), 0)
})
test_that("Small numeric data set VIM_knn", {
expect_equal(sum(is.na(autotune_VIM_kNN(test_set, percent_of_missing = percent_of_missing))), 0)
})
test_that("Small numeric data set VIM_regrImp", {
expect_error(sum(is.na(autotune_VIM_regrImp(test_set, col_type = col_type, percent_of_missing = percent_of_missing))), "No values with no missing values")
})
test_that("Small numeric data set missMDA FMAD...", {
expect_equal(sum(is.na(missMDA_FMAD_MCA_PCA(test_set, col_type = col_type, percent_of_missing = percent_of_missing, optimize_ncp = FALSE))), 0)
})
test_that("Small numeric data set missMDA MFA", {
expect_equal(sum(is.na(missMDA_MFA(test_set, col_type = col_type, percent_of_missing = percent_of_missing))), 0)
})
test_set <- iris
test_set$Sepal.Length[sample(1:150, 50)] <- NA
test_set$Species[sample(1:150, 50)] <- NA
col_type <- 1:5
col_type <- c(rep("numeric", 3), "integer", "factor")
test_set[, 4] <- as.integer(1:150)
percent_of_missing <- 1:5
for (i in percent_of_missing) {
percent_of_missing[i] <- (sum(is.na(test_set[, i])) / length(test_set)) * 100
}
col_no_miss <- colnames(test_set)[percent_of_missing == 0]
col_miss <- colnames(test_set)[percent_of_missing > 0]
test_that("Corect class return Amelia", {
imp_set <- autotune_Amelia(test_set, col_type = col_type, percent_of_missing = percent_of_missing)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Corect class return mice", {
imp_set <- autotune_mice(test_set, col_type = col_type, percent_of_missing = percent_of_missing, col_miss = col_miss, col_no_miss = col_no_miss, iter = 2, optimize = FALSE)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Corect class return missForest", {
imp_set <- autotune_missForest(test_set, col_type = col_type, percent_of_missing = percent_of_missing, optimize = FALSE)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Corect class return missRanger", {
imp_set <- autotune_missRanger(test_set, percent_of_missing = percent_of_missing)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Corect class return softImpute", {
imp_set <- autotune_softImpute(test_set, percent_of_missing = percent_of_missing, col_type = col_type)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Corect class return ViM_HD", {
imp_set <- autotune_VIM_hotdeck(test_set, percent_of_missing = percent_of_missing)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Corect class return ViM_IRMI", {
imp_set <- autotune_VIM_Irmi(test_set, percent_of_missing = percent_of_missing, col_type = col_type)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Corect class return ViM_regrImp", {
imp_set <- autotune_VIM_regrImp(test_set, percent_of_missing = percent_of_missing, col_type = col_type)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Corect class return ViM_knn", {
imp_set <- autotune_VIM_kNN(test_set, percent_of_missing = percent_of_missing)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Corect class return missMDA FMAD...", {
imp_set <- missMDA_FMAD_MCA_PCA(test_set, percent_of_missing = percent_of_missing, col_type = col_type, optimize_ncp = FALSE)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Corect class return missMDA MFA", {
imp_set <- missMDA_MFA(test_set, percent_of_missing = percent_of_missing, col_type = col_type)
imp_type <- 1:5
for (i in 1:5) {
imp_type[i] <- class(imp_set[, i])
}
expect_equal(imp_type, col_type)
})
test_that("Optimlaization test", {
test_set <- iris
test_set$Sepal.Length[sample(1:150, 50)] <- NA
test_set$Species[sample(1:150, 50)] <- NA
col_type <- 1:5
col_type <- c(rep("numeric", 3), "integer", "factor")
test_set[, 4] <- as.integer(1:150)
percent_of_missing <- 1:5
for (i in percent_of_missing) {
percent_of_missing[i] <- (sum(is.na(test_set[, i])) / length(test_set)) * 100
}
col_no_miss <- colnames(test_set)[percent_of_missing == 0]
col_miss <- colnames(test_set)[percent_of_missing > 0]
skip_on_cran()
expect_equal(sum(is.na(autotune_mice(test_set, col_miss = col_miss, col_no_miss = col_no_miss, col_type = col_type, percent_of_missing = percent_of_missing, optimize = TRUE, iter = 5))), 0)
expect_equal(sum(is.na(autotune_missForest(test_set, col_type = col_type, percent_of_missing = percent_of_missing, parallel = FALSE, optimize = TRUE))), 0)
expect_equal(sum(is.na(autotune_missRanger(test_set, percent_of_missing = percent_of_missing, optimize = TRUE))), 0)
expect_equal(sum(is.na(missMDA_FMAD_MCA_PCA(test_set, col_type = col_type, percent_of_missing = percent_of_missing, optimize_ncp = TRUE))), 0)
})
test_set <- as.data.frame(tsk('pima')$data())
test_that("Pima set Amleia", {
expect_equal(sum(is.na(autotune_Amelia(test_set, parallel = FALSE))), 0)
})
test_that("Pima set mice", {
expect_equal(sum(is.na(autotune_mice(test_set, optimize = F))), 0)
})
test_that("Pima set missForest", {
expect_equal(sum(is.na(autotune_missForest(test_set, parallel = FALSE, optimize = FALSE))), 0)
})
test_that("Pima set missRanger", {
expect_equal(sum(is.na(autotune_missRanger(test_set ))), 0)
})
test_that("Pima set softImpute", {
expect_equal(sum(is.na(autotune_softImpute(test_set))), 0)
})
test_that("Pima set VIM_HD", {
expect_equal(sum(is.na(autotune_VIM_hotdeck(test_set))), 0)
})
test_that("Pima set VIM_irmi", {
expect_equal(sum(is.na(autotune_VIM_Irmi(test_set ))), 0)
})
test_that("Pima set VIM_knn", {
expect_equal(sum(is.na(autotune_VIM_kNN(test_set ))), 0)
})
test_that("Pima set ViM_regrImp", {
expect_equal(sum(is.na(autotune_VIM_regrImp(test_set))), 0)
})
test_that("Pima set missMDA FMAD", {
expect_equal(sum(is.na(missMDA_FMAD_MCA_PCA(test_set, optimize_ncp = FALSE))), 0)
})
test_that("Pima set missMDA MFA", {
expect_equal(sum(is.na(missMDA_MFA(test_set))), 0)
}) |
context("test cor_phylo output")
test_that("cor_phylo produces proper output", {
skip_on_cran()
n <- 50
p <- 2
Rs <- c(0.8)
d <- c(0.3, 0.6)
M <- matrix(c(0.25, 0.6), nrow = n, ncol = p, byrow = TRUE)
X_means <- c(1, 2)
X_sds <- c(1, 0.5)
U_means <- list(NULL, 2)
U_sds <- list(NULL, 10)
B <- list(NULL, 0.1)
data_list <- phyr:::sim_cor_phylo_variates(n, Rs, d, M, X_means, X_sds, U_means, U_sds, B)
SeM <- as.matrix(data_list$data[, grepl("^se", colnames(data_list$data))])
rownames(SeM) <- data_list$data$species
X <- as.matrix(data_list$data[, grepl("^par", colnames(data_list$data))])
rownames(X) <- data_list$data$species
U <- lapply(1:p, function(i) {
UM <- as.matrix(data_list$data[,grepl(paste0("^cov", i), colnames(data_list$data))])
if (ncol(UM) == 0) return(NULL)
rownames(UM) <- data_list$data$species
return(UM)
})
phyr_cp <- cor_phylo(variates = ~ par1 + par2,
covariates = list(par2 ~ cov2a),
meas_errors = list(par1 ~ se1, par2 ~ se2),
data = data_list$data, phy = data_list$phy,
species = ~ species, method = "nelder-mead-r",
lower_d = 0)
ape_cp <- ape::corphylo(X = X, SeM = SeM, U = U, phy = data_list$phy,
method = "Nelder-Mead")
expect_is(phyr_cp, "cor_phylo")
expect_equivalent(names(phyr_cp), c("corrs", "d", "B", "B_cov", "logLik", "AIC",
"BIC", "niter", "convcode", "rcond_vals",
"bootstrap", "call"),
label = "Names not correct.")
phyr_cp_names <- sapply(names(phyr_cp), function(x) class(phyr_cp[[x]]))
expected_classes <- c(corrs = "matrix", d = "matrix", B = "matrix", B_cov = "matrix",
logLik = "numeric", AIC = "numeric", BIC = "numeric",
niter = "numeric", convcode = "integer", rcond_vals = "numeric",
bootstrap = "list", call = "call")
expect_class_equal <- function(par_name) {
eval(bquote(expect_equal(class(phyr_cp[[.(par_name)]])[1],
expected_classes[[.(par_name)]])))
}
for (n_ in names(phyr_cp)) expect_class_equal(n_)
expect_par_equal <- function(cp_par, ape_par = NULL) {
if (is.null(ape_par)) ape_par <- cp_par
eval(bquote(expect_equivalent(phyr_cp[[.(cp_par)]], ape_cp[[.(ape_par)]])))
}
expect_par_equal("corrs", "cor.matrix")
expect_par_equal("logLik")
expect_par_equal("d")
expect_par_equal("AIC")
expect_par_equal("BIC")
expect_par_equal("convcode")
phyr_cp$convcode <- 1
expect_output(print(phyr_cp), regexp = "Warning: convergence in .* not reached")
Vphy <- ape::vcv(data_list$phy)
phyr_cp <- cor_phylo(variates = ~ par1 + par2,
meas_errors = list(par1 ~ se1, par2 ~ se2),
data = data_list$data, phy = Vphy,
REML = FALSE,
species = ~ species, method = "subplex")
expect_is(phyr_cp, "cor_phylo")
expect_equivalent(names(phyr_cp), c("corrs", "d", "B", "B_cov", "logLik", "AIC",
"BIC", "niter", "convcode", "rcond_vals",
"bootstrap", "call"),
label = "Names not correct.")
phyr_cp_names <- sapply(names(phyr_cp), function(x) class(phyr_cp[[x]]))
expected_classes <- c(corrs = "matrix", d = "matrix", B = "matrix", B_cov = "matrix",
logLik = "numeric", AIC = "numeric", BIC = "numeric",
niter = "numeric", convcode = "integer", rcond_vals = "numeric",
bootstrap = "list", call = "call")
for (n_ in names(phyr_cp)) expect_class_equal(n_)
phyr_cp$convcode <- 1
expect_output(print(phyr_cp), regexp = "Warning: convergence in .* not reached")
cp_out <- capture.output({
phyr_cp_sann <- cor_phylo(variates = ~ par1 + par2,
meas_errors = list(par1 ~ se1, par2 ~ se2),
data = data_list$data, phy = Vphy,
species = ~ species, method = "sann",
verbose = TRUE,
sann_options = list(maxit = 100, temp = 1.1, tmax = 2))
})
cp_out <- unique(sapply(strsplit(cp_out, split = "\\s+"), length))
expect_identical(cp_out, 6L)
expect_error(cor_phylo(variates = ~ par1 + par2,
covariates = list(par2 ~ cov2a),
meas_errors = list(par1 ~ se1, par2 ~ se2),
species = ~ species,
data = data_list$data,
phy = ape::rtree(n, br = NULL)),
regexp = "The input phylogeny has no branch lengths")
expect_error(cor_phylo(variates = ~ par1,
data = data_list$data,
phy = data_list$phy,
species = ~ species),
regexp = "argument `variates` should have >= 2 variables.")
expect_error(cor_phylo(variates = c("par1", "par2"),
data = data_list$data, phy = data_list$phy,
species = ~ species),
regexp = "The `variates` argument to `cor_phylo` must be a formula or matrix")
expect_error(cor_phylo(variates = ~ par1 + par2,
covariates = c("cov2a"),
data = data_list$data, phy = data_list$phy,
species = ~ species),
regexp = "arg `covariates` must be NULL or a list")
expect_error(cor_phylo(variates = ~ par1 + par2,
meas_errors = c("se2"),
data = data_list$data, phy = data_list$phy,
species = ~ species),
regexp = paste("The `meas_errors` argument to `cor_phylo` must be NULL,",
"a list, or matrix."))
x <- data_list$data$par1[10]
data_list$data$par1[10] <- NA
expect_error(cor_phylo(variates = ~ par1 + par2,
covariates = list(par2 ~ cov2a),
meas_errors = list(par1 ~ se1, par2 ~ se2),
data = data_list$data, phy = data_list$phy,
species = ~ species),
regexp = "NAs are not allowed in `variates`")
data_list$data$par1[10] <- x
x <- data_list$data$cov2a[10]
data_list$data$cov2a[10] <- NA
expect_error(cor_phylo(variates = ~ par1 + par2,
covariates = list(par2 ~ cov2a),
meas_errors = list(par1 ~ se1, par2 ~ se2),
data = data_list$data, phy = data_list$phy,
species = ~ species),
regexp = "NAs are not allowed in `covariates`")
data_list$data$cov2a[10] <- x
x <- data_list$data$se1[10]
data_list$data$se1[10] <- NA
expect_error(cor_phylo(variates = ~ par1 + par2,
covariates = list(par2 ~ cov2a),
meas_errors = list(par1 ~ se1, par2 ~ se2),
data = data_list$data, phy = data_list$phy,
species = ~ species),
regexp = "NAs are not allowed in `meas_errors`")
data_list$data$se1[10] <- x
x <- data_list$data$species[10]
data_list$data$species[10] <- NA
expect_error(cor_phylo(variates = ~ par1 + par2,
covariates = list(par2 ~ cov2a),
meas_errors = list(par1 ~ se1, par2 ~ se2),
data = data_list$data, phy = data_list$phy,
species = ~ species),
regexp = "NAs are not allowed in `species`")
data_list$data$species[10] <- x
cp_output_tests <- list(forms = NA,
matrices = NA)
cp_output_tests$forms <-
cor_phylo(variates = ~ par1 + par2,
covariates = list(par2 ~ cov2a),
meas_errors = list(par1 ~ se1, par2 ~ se2),
species = ~ species,
phy = data_list$phy, data = data_list$data)
X <- as.matrix(data_list$data[,c("par1", "par2")])
U <- list(par2 = cbind(cov2a = data_list$data$cov2a))
M <- cbind(par1 = data_list$data$se1, par2 = data_list$data$se2)
cp_output_tests$matrices <-
cor_phylo(variates = X,
covariates = U,
meas_errors = M,
species = data_list$data$species,
phy = data_list$phy)
for (i in 2:length(cp_output_tests)) {
expect_equal(cp_output_tests[[1]][-length(cp_output_tests[[1]])],
cp_output_tests[[i]][-length(cp_output_tests[[i]])],
label = names(cp_output_tests)[1],
expected.label = names(cp_output_tests)[i])
}
cp <- cor_phylo(variates = ~ par1 + par2,
covariates = list(par2 ~ cov2a),
meas_errors = list(par1 ~ se1, par2 ~ se2),
data = data_list$data, phy = data_list$phy,
species = ~ species, boot = 1, keep_boots = "all")
cp2 <-
cor_phylo(variates = X,
covariates = U,
meas_errors = M,
species = data_list$data$species,
phy = data_list$phy,
boot = 1, keep_boots = "all")
cp_bci <- boot_ci(cp)
cp_bci2 <- boot_ci(cp2)
expect_identical(names(cp_bci), c("corrs", "d", "B0", "B_cov"))
expect_identical(names(cp_bci2), c("corrs", "d", "B0", "B_cov"))
expect_identical(paste(sapply(cp_bci, function(i) class(i)[1])), rep("matrix", 4))
expect_identical(paste(sapply(cp_bci2, function(i) class(i)[1])), rep("matrix", 4))
expect_output(print(cp), regexp = "Bootstrapped 95\\% CIs \\(.* reps\\):")
expect_output(print(cp2), regexp = "Bootstrapped 95\\% CIs \\(.* reps\\):")
cp_refit <- refit_boots(cp)
cp_refit2 <- refit_boots(cp2)
expect_output(print(cp_refit), "< Refits to cor_phylo bootstraps >")
expect_output(print(cp_refit2), "< Refits to cor_phylo bootstraps >")
data_list$data$par3 <- runif(nrow(data_list$data)) * data_list$data$par1
phyr_cp_nc <- cor_phylo(variates = ~ par1 + par2 + par3,
data = data_list$data, phy = data_list$phy,
species = ~ species, method = "nelder-mead-r",
no_corr = TRUE)
expect_equal(sum(phyr_cp_nc$corrs[lower.tri(phyr_cp_nc$corrs)]), 0)
expect_equal(sum(phyr_cp_nc$corrs[upper.tri(phyr_cp_nc$corrs)]), 0)
phyr_cp <- cor_phylo(variates = ~ par1 + par2,
data = data_list$data, phy = data_list$phy,
species = ~ species, constrain_d = TRUE)
expect_output(print(phyr_cp), "Call to cor_phylo:")
}) |
context("Test default user key")
test_that("reading protected keys", {
sk1 <- rsa_keygen()
pk1 <- as.list(sk1)$pubkey
tmp_key <- tempfile()
tmp_pubkey <- tempfile()
write_pem(sk1, tmp_key, password = NULL)
write_pem(pk1, tmp_pubkey)
Sys.setenv("USER_KEY" = tmp_key)
expect_equal(sk1, my_key())
expect_equal(pk1, my_pubkey())
}) |
getPencilLayer <- function(x, size = 100, buffer = 1000, lefthanded = TRUE){
a <- median(sf::st_area(sf::st_set_crs(x, NA)))
size <- size * size
. <- lapply(sf::st_geometry(x), makelines, size = size, buffer = buffer,
lefthanded = lefthanded, a = a)
. <- sf::st_sfc(do.call(rbind,.))
if(length(.)<nrow(x)){
stop(simpleError("Try a smaller buffer size or a larger size"))
}
. <- sf::st_sf(geometry = ., x[,,drop=TRUE], sf_column_name = "geometry")
. <- sf::st_set_crs(., sf::st_crs(x))
. <- sf::st_cast(. , "MULTILINESTRING")
return(.)
}
makelines <- function(x, size, buffer, lefthanded, a){
size <- round(sqrt(as.numeric(sf::st_area(x) * size / a)), 0)
if (size <= 10){size <- 10}
pt <- sf::st_sample(sf::st_buffer(sf::st_sfc(x), buffer), size = size)
if(lefthanded){
pt <- sf::st_sf(pt, x = sf::st_coordinates(pt)[,2] +
sf::st_coordinates(pt)[,1])
} else{
pt <- sf::st_sf(pt, x = sf::st_coordinates(pt)[,2] -
sf::st_coordinates(pt)[,1])
}
pt <- sf::st_combine(pt[order(pt$x),])
r <- sf::st_intersection(sf::st_cast(pt, "LINESTRING"), x)
} |
readRDS("resources/test-endpoint_tables-bad_request.RDS") |
source("ESEUR_config.r")
library("lubridate")
library("plyr")
pal_col=rainbow(2)
changes=read.csv(paste0(ESEUR_dir, "time-series/splc-2010-fm-evol-files-commit-date.xz"), as.is=TRUE)
changes$date=as.Date(changes$date, format="%a %B %d %H:%M:%S %Y %z")
changes=subset(changes, !is.na(changes$date))
changes$rnd_date=round_date(changes$date, unit="week")
kconfig=subset(changes, kconfig == "Kconfig")
linux=subset(changes, kconfig == "Not Kconfig")
kconfig_week=count(kconfig$rnd_date)
linux_week=count(linux$rnd_date)
plot(linux_week$x, linux_week$freq, type="l", log="y", col=pal_col[2],
xaxs="i",
ylim=c(1, 2600),
xlab="Date", ylab="Commits\n")
lines(kconfig_week, col=pal_col[1])
legend(x="bottomright", legend=c("Kconfig", "Linux"), bty="n", fill=pal_col, cex=1.2) |
library(shiny)
library(toastui)
schedules <- cal_demo_data()
schedules$id <- seq_len(nrow(schedules))
schedules$raw <- lapply(
X = seq_len(nrow(schedules)),
FUN = function(i) {
list(
status = sample(c("Completed", "In progress", "Closed"), 1)
)
}
)
ui <- fluidPage(
fluidRow(
column(
width = 8, offset = 2,
tags$h2("Custom popup made with Shiny"),
calendarOutput(outputId = "cal"),
uiOutput("ui")
)
)
)
server <- function(input, output, session) {
output$cal <- renderCalendar({
calendar(view = "month", taskView = TRUE, useDetailPopup = FALSE) %>%
cal_props(cal_demo_props()) %>%
cal_schedules(schedules) %>%
cal_events(
clickSchedule = JS(
"function(event) {",
"Shiny.setInputValue('calendar_id_click', {id: event.schedule.id, x: event.event.clientX, y: event.event.clientY});",
"}"
)
)
})
observeEvent(input$calendar_id_click, {
removeUI(selector = "
id <- as.numeric(input$calendar_id_click$id)
sched <- schedules[schedules$id == id, ]
insertUI(
selector = "body",
ui = absolutePanel(
id = "custom_popup",
top = input$calendar_id_click$y,
left = input$calendar_id_click$x,
draggable = FALSE,
width = "300px",
tags$div(
style = "background:
actionLink(
inputId = "close_calendar_panel",
label = NULL,
icon = icon("close"),
style = "position: absolute; top: 5px; right: 5px;"
),
tags$br(),
tags$div(
style = "text-align: center;",
tags$p(
"Here you can put custom", tags$b("HTML"), "elements."
),
tags$p(
"You clicked on schedule", sched$id,
"starting from", sched$start,
"ending", sched$end
),
tags$b("Current status:"), tags$span(class = "label label-primary", sched$raw[[1]]$status),
radioButtons(
inputId = "status",
label = "New status:",
choices = c("Completed", "In progress", "Closed"),
selected = sched$raw[[1]]$status
)
)
)
)
)
})
observeEvent(input$close_calendar_panel, {
removeUI(selector = "
})
rv <- reactiveValues(id = NULL, status = NULL)
observeEvent(input$status, {
rv$id <- input$calendar_id_click$id
rv$status <- input$status
})
output$ui <- renderUI({
tags$div(
"Schedule", tags$b(rv$id), "has been updated with status", tags$b(rv$status)
)
})
}
shinyApp(ui, server) |
rewrite <- function(ast, rules) {
magrittr::freduce(ast, rules)
}
make_rule <- function(from, to) {
f <- function(x) subst(x, pattern = from, replacement = to)
structure(f, class = "sketch_rule", from = from, to = to)
}
rm_attributes <- function(x) {
attributes(x) <- NULL
x
}
combine_rules <- function(rs, group = rep(1, length(rs))) {
unique(group) %>%
sort(decreasing = TRUE) %>%
purrr::map(~rs[which(group == .x)]) %>%
purrr::map(join_rules)
}
split_rules <- function(rs) {
rs %>%
purrr::map(unjoin_rules) %>%
unlist()
}
join_rules <- function(rs) {
make_rule(purrr::map_chr(rs, ~attr(.x, "from")),
purrr::map_chr(rs, ~attr(.x, "to")))
}
unjoin_rules <- function(r) {
purrr::map2(attr(r, "from"), attr(r, "to"), make_rule)
}
print.sketch_rule <- function(x, ...) {
from <- attr(x, 'from')
to <- attr(x, 'to')
print(glue::glue("Rule: Rewrite '{from}' to '{to}'."))
print(rm_attributes(x))
invisible(x)
}
subst <- function(ast, pattern, replacement) {
if (rlang::is_call(ast)) {
if (rlang::is_call(ast, '.')) {
ast[[2]] <- subst(ast[[2]], pattern, replacement)
return(ast)
}
return(as.call(purrr::map(ast, ~subst(.x, pattern, replacement))))
}
if (rlang::is_symbol(ast)) {
if (rlang::is_symbol(ast, pattern)) {
index <- min(which(ast == pattern))
return(as.symbol(replacement[index]))
} else {
return(ast)
}
}
if (rlang::is_syntactic_literal(ast)) {
if (is.null(ast) || is.na(ast) || is.character(ast)) {
return(ast)
}
if (ast %in% pattern) {
index <- min(which(ast == pattern))
return(as.symbol(replacement[index]))
}
return(ast)
}
if (rlang::is_pairlist(ast)) {
ast2 <- as.pairlist(purrr::map(ast, ~subst(.x, pattern, replacement)))
names(ast2) <- names(ast)
return(ast2)
}
if (class(ast) == "srcref") {
return(ast)
}
stop("The line should not be reached, please submit an issue with the input on github. Thanks!")
} |
NULL
axe_call.train <- function(x, verbose = FALSE, ...) {
old <- x
x <- exchange(x, "call", call("dummy_call"))
x <- exchange(x, "dots", list(NULL))
add_butcher_attributes(
x,
old,
disabled = c("summary()"),
verbose = verbose
)
}
axe_ctrl.train <- function(x, verbose = FALSE, ...) {
old <- x
x <- exchange(x, "control", list(NULL), "method", old)
add_butcher_attributes(
x,
old,
disabled = "update()",
verbose = verbose
)
}
axe_data.train <- function(x, verbose = FALSE, ...) {
old <- x
x <- exchange(x, "trainingData", data.frame(NA))
add_butcher_attributes(
x,
old,
verbose = verbose
)
}
axe_env.train <- function(x, verbose = FALSE, ...) {
old <- x
x$modelInfo <- purrr::map(x$modelInfo, function(z) axe_env(z, ...))
add_butcher_attributes(
x,
old,
verbose = verbose
)
}
axe_fitted.train <- function(x, verbose = FALSE, ...) {
old <- x
x <- exchange(x, "pred", list(NULL))
add_butcher_attributes(
x,
old,
disabled = "residuals()",
verbose = verbose
)
} |
plot_ggplot_survHE <- function(exArgs) {
w <- which(unlist(lapply(1:length(exArgs),function(i) class(exArgs[[i]])))=="survHE")
if(length(w)==0){
stop("Please give at least one 'survHE' object, generated by a call to 'fit.models(...)")
} else {
survHE_objs=lapply(1:length(w),function(i) exArgs[[w[i]]])
}
names(survHE_objs)=names(exArgs)[w]
if (!exists("t",exArgs)) {t <- sort(unique(survHE_objs[[1]]$misc$km$time))} else {t <- exArgs$t}
if (!exists("newdata",exArgs)) {newdata <- NULL} else {newdata <- exArgs$newdata}
if (!exists("nsim",exArgs)) {nsim <- 1} else {nsim <- exArgs$nsim}
if (!exists("mods",exArgs)) {
mods=1:sum(unlist(lapply(survHE_objs,function(x) length(x$models))))
} else {mods=exArgs$mods}
if (!exists("add.km",exArgs)) {add.km <- FALSE} else {add.km <- exArgs$add.km}
if(exists("annotate",where=exArgs)){annotate=exArgs$annotate} else {annotate=FALSE}
obj <- mod <- NULL
all_models=tibble(
obj=unlist(
lapply(1:length(survHE_objs),function(x) {
rep(names(survHE_objs)[x],length(survHE_objs[[x]]$models))
})
),
mod=unlist(lapply(survHE_objs,function(x) 1:length(x$models)))
) %>% slice(mods) %>% arrange(obj)
sel_mods=unique(match(all_models$obj,names(survHE_objs)))
toplot = lapply(sel_mods,function(i){
make_data_surv(survHE_objs[[i]],
mods=all_models %>% filter(obj==names(survHE_objs)[i]) %>% pull(mod),
nsim=nsim,
t=t,
newdata=newdata,
add.km=add.km
)[[1]] %>% mutate(object_name=as.factor(names(survHE_objs)[i]))
}) %>% bind_rows() %>%
group_by(object_name,model_name) %>% mutate(mods_id=cur_group_id()) %>% ungroup()
if(add.km==TRUE) {
datakm = lapply(1:length(survHE_objs),function(i){
make_data_surv(survHE_objs[[i]],
mods=1,
nsim=1,
t=t,
newdata=newdata,
add.km=add.km
)[[2]] %>% mutate(object_name=as.factor(names(survHE_objs)[i]))
}) %>% bind_rows() %>%
group_by(object_name,model_name) %>% mutate(mods_id=cur_group_id()) %>% ungroup()
} else {
datakm=NULL
}
surv.curv=make_surv_curve_plot(toplot,datakm,mods)
if(exists("lab.profile",exArgs)){
surv.curv=surv.curv+
scale_linetype_manual(labels=exArgs$lab.profile,values=1:length(exArgs$lab.profile))
}
if(exists("colour",exArgs) & exists("lab.model",exArgs)) {
surv.curv=surv.curv+scale_color_manual(labels=exArgs$lab.model,values=exArgs$colour)
}
if(exists("colour",exArgs) & !exists("lab.model",exArgs)) {
surv.curv=surv.curv+scale_color_manual(values=exArgs$colour)
}
if(exists("lab.model",exArgs) & !exists("colour",exArgs)) {
surv.curv=surv.curv+scale_color_manual(values=1:length(exArgs$lab.model),labels=exArgs$lab.model)
}
if(exists("xlab",where=exArgs)){
surv.curv=surv.curv+labs(x=exArgs$xlab)
}
if(exists("ylab",where=exArgs)){
surv.curv=surv.curv+labs(y=exArgs$ylab)
}
if(exists("main",where=exArgs)) {
surv.curv=surv.curv+labs(title=exArgs$main)+theme(plot.title=element_text(size=18,face="bold"))
}
if(annotate==TRUE){
cutoff=max(survHE_objs[[1]]$misc$km$time)
surv.curv=surv.curv +
geom_segment(aes(x=cutoff,y=-Inf,xend=cutoff,yend=-.01),size=0.9) +
geom_segment(aes(x=cutoff,y=-.01,xend=cutoff*.85,yend=-.01),arrow=arrow(length=unit(.25,"cm"),type="closed"),size=1.1)+
geom_segment(aes(x=cutoff,y=-.01,xend=cutoff*1.15,yend=-.01),arrow=arrow(length=unit(.25,"cm"),type="closed"),size=1.1)+
annotate(geom="text",x=cutoff,y=-Inf,hjust=1.1,vjust=-1,label="Observed data",size=5) +
annotate(geom="text",x=cutoff,y=-Inf,hjust=-0.1,vjust=-1,label="Extrapolation",size=5) +
ylim(-0.01,1) +
geom_rect(data=data.frame(xmin=-Inf,xmax=cutoff,ymin=-Inf,ymax=Inf),
aes(xmin=xmin,xmax=xmax,ymin=ymin,ymax=ymax),fill="grey",alpha=.1)
} else{
surv.curv=surv.curv+ylim(0,1)
}
if(exists("legend.position",exArgs)){
surv.curv=surv.curv+theme(legend.position=exArgs$legend.position)
}
if(exists("legend.title",exArgs)){
surv.curv=surv.curv+theme(legend.title=exArgs$legend.title)
}
if(exists("legend.text",exArgs)){
surv.curv=surv.curv+theme(legend.text=exArgs$legend.text)
}
surv.curv
}
make_data_surv <- function(x,mods=1:length(x$models),nsim=1,t=NULL,newdata=NULL,add.km=FALSE) {
if(is.null(t)) {
t <- sort(unique(x$misc$km$time))
}
s=lapply(mods,function(i) {
make.surv(x,mod=i,t=t,nsim=nsim,newdata=newdata)
})
strata=lapply(1:length(s),function(i) {
lapply(1:nrow(s[[i]]$des.mat),function(x){
s[[i]]$des.mat %>% as_tibble() %>% select(-matches("(Intercept)",everything())) %>% slice(x) %>%
round(digits=2) %>% mutate(strata=paste0(names(.),"=",.,collapse=","))
}) %>% bind_rows(.) %>% select(strata)
})
toplot=lapply(1:length(mods),function(i) {
lapply(1:length(s[[i]]$S),function(j) {
s[[i]]$S[[j]] %>% bind_cols(strata=as.factor(as.character(strata[[i]][j,])),model_name=as.factor(names(x$models)[mods[i]]))
})
}) %>% bind_rows(.)
out=list(toplot)
if(add.km==TRUE) {
if(length(x$misc$km$strata)!=nrow(s[[1]]$des.mat)){
x$misc$km=rms::npsurv(update(x$misc$formula,~1),data=x$misc$data)
x$misc$km$call$formula=as.formula(deparse(update(x$misc$formula,~1)))
}
datakm=bind_cols(t=x$misc$km$time,n.risk=x$misc$km$n.risk,n.event=x$misc$km$n.event,
n.censor=x$misc$km$n.censor,S=x$misc$km$surv,lower=x$misc$km$lower,
upper=x$misc$km$upper) %>% mutate(model_name="Kaplan Meier")
if(is.null(x$misc$km$strata)) {
datakm$strata=as.factor("all")
} else {
datakm$strata=as.factor(rep(1:length(x$misc$km$strata),x$misc$km$strata))
}
out$datakm=datakm
}
return(out)
}
make_surv_curve_plot <- function(toplot,datakm=NULL,mods) {
if (all(toplot$strata=="=")) {
linetype=NULL
} else {
linetype=toplot$strata
}
surv.curv=ggplot()
if(length(levels(toplot$object_name))==1) {
surv.curv=surv.curv+
geom_line(data=toplot,aes(x=t,y=S,group=model_name:strata,col=model_name,linetype=linetype),size=.9)
} else {
surv.curv=surv.curv+
geom_line(data=toplot,aes(x=t,y=S,group=model_name:strata:object_name,col=object_name:model_name,linetype=linetype),size=.9)
}
surv.curv=surv.curv +
theme_bw() +
theme(axis.text.x = element_text(color="black",size=12,angle=0,hjust=.5,vjust=.5),
axis.text.y = element_text(color="black",size=12,angle=0,hjust=.5,vjust=.5),
axis.title.x = element_text(color="black",size=14,angle=0,hjust=.5,vjust=.5),
axis.title.y = element_text(color="black",size=14,angle=90,hjust=.5,vjust=.5)) +
theme(axis.line = element_line(colour = "black"),
panel.background = element_blank(),
panel.border = element_blank(),
plot.title = element_text(size=18, face="bold")) +
theme(legend.position=c(.75,.78),
legend.title=element_text(size=15,face="bold"),
legend.text = element_text(colour="black", size=14, face="plain"),
legend.background=element_blank()) +
labs(y="Survival",x="Time",title=NULL,
color=ifelse(length(mods)==1,"Model","Models"),
linetype="Profile") +
guides(color=guide_legend(order=1),
linetype=guide_legend(order=2))
if(any(grepl("low",names(toplot)))) {
surv.curv=surv.curv+geom_ribbon(data=toplot,aes(x=t,y=S,ymin=low,ymax=upp,group=model_name:strata),alpha=.2)
}
if(!is.null(datakm)) {
surv.curv=surv.curv+geom_step(data=datakm,aes(t,S,group=as.factor(strata)),color="darkgrey") +
geom_ribbon(data=datakm,aes(x=t,y=S,ymin=lower,ymax=upper,group=as.factor(strata)),alpha=.2)
}
surv.curv
}
plot_base_survHE <- function(x,exArgs) {
nexArgs <- length(exArgs)
classes <- unlist(lapply(1:nexArgs,function(i) class(exArgs[[i]])))
w <- which(classes=="survHE")
original.method <- unlist(lapply(w,function(i) exArgs[[i]]$method))
if(length(w)==0) {
stop("You need to input at least one 'survHE' object to run this function!")
}
if(length(w)==1) {
totmodels <- unlist(lapply(w,function(i) length(exArgs[[i]]$models)))
mods <- exArgs[[w]]$models
method <- rep(exArgs[[w]]$method,totmodels)
aic <- unlist(exArgs[[w]]$model.fitting$aic)
bic <- unlist(exArgs[[w]]$model.fitting$bic)
dic <- unlist(exArgs[[w]]$model.fitting$dic)
if(totmodels>1){
if (!is.null(exArgs$mod)) {which.model <- exArgs$mod} else {which.model <- 1:length(mods)}
mods <- lapply(which.model,function(i) mods[[i]])
method <- method[which.model]
aic <- aic[which.model]
bic <- bic[which.model]
dic <- dic[which.model]
}
}
if (length(w)>1) {
mods <- unlist(lapply(w,function(i) exArgs[[i]]$models),recursive = F)
totmodels <- unlist(lapply(w,function(i) length(exArgs[[i]]$models)))
method <- unlist(lapply(w,function(i) rep(exArgs[[i]]$method,totmodels[i])))
aic <- unlist(lapply(w,function(i) exArgs[[i]]$model.fitting$aic))
bic <- unlist(lapply(w,function(i) exArgs[[i]]$model.fitting$bic))
dic <- unlist(lapply(w,function(i) exArgs[[i]]$model.fitting$dic))
if (!is.null(exArgs$mod)) {which.model <- exArgs$mod} else {which.model <- 1:length(mods)}
mods <- lapply(which.model,function(i) mods[[i]])
method <- method[which.model]
aic <- aic[which.model]
bic <- bic[which.model]
dic <- dic[which.model]
}
model.fitting <- list(aic=aic,bic=bic,dic=dic)
x <- list()
x$models <- mods
nmodels <- length(x$models)
class(x) <- "survHE"
x$model.fitting <- model.fitting
if (any(method=="hmc")) {
x$misc <- exArgs[[min(which(original.method=="hmc"))]]$misc
x$misc$data.stan=x$misc$data.stan[[1]]
if (exists("X",x$misc$data.stan)) {
x$misc$data.stan$X_obs <- x$misc$data.stan$X
} else {
x$misc$data.stan$X <- x$misc$data.stan$X_obs
}
x$misc$data.stan <- rep(list(x$misc$data.stan),nmodels)
} else {
x$misc <- exArgs[[1]]$misc
}
if (is.null(exArgs$t)) {t <- sort(unique(x$misc$km$time))} else {t <- exArgs$t}
if (is.null(exArgs$xlab)) {xl <- "time"} else {xl <- exArgs$xlab}
if (is.null(exArgs$ylab)) {yl <- "Survival"} else {yl <- exArgs$ylab}
if (is.null(exArgs$lab.profile)) {lab.profile <- names(x$misc$km$strata)} else {lab.profile<-exArgs$lab.profile}
if (is.null(exArgs$cex.trt)) {cex.trt <- 0.8} else {cex.trt <- exArgs$cex.trt}
if (is.null(exArgs$n.risk)) {nrisk <- FALSE} else {nrisk <- exArgs$n.risk}
if (is.null(exArgs$main)) {main <- ""} else {main <- exArgs$main}
if (is.null(exArgs$newdata)) {newdata <- NULL} else {newdata <- exArgs$newdata}
if (is.null(exArgs$cex.lab)) {cex.lab <- 0.8} else {cex.lab <- exArgs$cex.lab}
if (is.null(exArgs$legend)) {legend=TRUE} else (legend=FALSE)
if (is.null(exArgs$xlim) & is.null(exArgs$t)) {
xlm <- range(pretty(x$misc$km$time))
}
if (is.null(exArgs$xlim) & !is.null(exArgs$t)) {
xlm <- range(pretty(t))
}
if (!is.null(exArgs$xlim) & is.null(exArgs$t)) {
xlm <- exArgs$xlim
}
if (!is.null(exArgs$xlim) & !is.null(exArgs$t)) {
xlm <- exArgs$xlim
}
if (is.null(exArgs$colors)) {
if (nmodels>1) {colors <- (2:(nmodels+1))} else {colors <- 2}
} else {colors <- exArgs$colors}
if(is.null(exArgs$axes)){axes <- TRUE} else {axes <- exArgs$axes}
if (is.null(exArgs$labs)) {
labs <- unlist(lapply(1:length(x$models),function(i) {
if(class(x$models[[i]])=="stanfit") {tolower(x$models[[i]]@model_name)} else {x$models[[i]]$dlist$name}
}))
labs[labs %in% c("weibull.quiet","weibull","weibullaf","weibullph")] <- "Weibull"
labs[labs %in% c("exp","exponential")] <- "Exponential"
labs[labs %in% "gamma"] <- "Gamma"
labs[labs %in% c("lnorm","lognormal")] <- "log-Normal"
labs[labs %in% c("llogis","loglogistic","loglogis")] <- "log-Logistic"
labs[labs %in% "gengamma"] <- "Gen. Gamma"
labs[labs %in% "genf"] <- "Gen. F"
labs[labs %in% "gompertz"] <- "Gompertz"
labs[labs %in% c("survspline","rp")] <- "Royston & Parmar splines"
} else {labs <- exArgs$labs}
labs <- c("Kaplan Meier",labs)
if (is.null(exArgs$add.km)) {add.km <- TRUE} else {add.km <- exArgs$add.km}
if (add.km==TRUE & is.null(newdata)) {
rms::survplot(x$misc$km,
xlab=xl,ylab=yl,
label.curves=list(labels=lab.profile,cex=cex.trt),
n.risk=nrisk,
lwd=2,xlim=xlm
)
col <- c("black",colors)
title(main)
} else {
labs <- labs[-1]
if(class(colors)!="character") {colors <- colors-1}
plot(0,0,col="white",xlab=xl,ylab=yl,axes=F,xlim=xlm,ylim=c(0,1),main=main)
if(axes==TRUE) {
axis(1)
axis(2)}
col <- colors
}
res <- lapply(1:nmodels,function(i) {
x$method <- method[i]
make.surv(x,nsim=1,t=t,mod=i,newdata=newdata)
})
if (!is.null(newdata)) {
options(digits=5,nsmall=2)
pts <- list()
for (i in 1:nmodels) {
if (method[i]=="mle") {
pts[[i]] <- lapply(1:length(newdata),function(j) {
tmp <- matrix(unlist(res[[i]]$S[[j]]),ncol=4)
cbind(tmp[,1],tmp[,2])
})
} else {
pts[[i]] <- lapply(1:length(newdata),function(j) {
res[[i]]$S[[1]][[j]]
})
}
}
colors <- 1:nmodels
leg.txt <- character()
for (i in 1:nmodels) {
for (j in 1:length(newdata)) {
points(pts[[i]][[j]],t="l",col=colors[i],lty=j)
leg.txt[j] <- paste0(names(newdata[[j]]),"=",prettyNum(newdata[[j]],format="fg"),collapse=", ")
}
}
if (legend) {legend("topright",legend=leg.txt,bty="n",lty=1:length(newdata),cex=cex.lab)}
}
if(is.null(newdata)) {
for (i in 1:nmodels) {
pts <- lapply(res[[i]]$S[[1]],function(m) m %>% as.matrix())
lapply(1:length(pts), function(x) points(pts[[x]]$t,pts[[x]]$S,t="l",col=colors[i],lty=x))
}
if(legend) {legend(x="topright",legend=labs,lwd=2,bty="n",col=col,cex=cex.lab)}
}
} |
invdir.mle <- function(x, tol = 1e-09) {
n <- dim(x)[1]
p <- dim(x)[2]
zx <- t( log(x) )
sx2 <- sum( log1p( Rfast::rowsums(x) ) )
com <- c( Rfast::rowsums(zx) - sx2, -sx2 )
a <- Rfast::colmeans(x)
b <- Rfast::colVars(x, suma = n * a)
D <- p + 1
aD <- 0.5 * ( mean(a)^2 + mean(a) ) / mean(b) + 1
a1 <- abs( c( a * (aD - 1), aD) ) / 2
phi <- sum(a1)
f1 <- n * digamma( phi ) - n * digamma(a1) + com
f2 <- matrix(n * trigamma(phi), D, D)
diag(f2) <- diag(f2) - n * trigamma(a1)
a2 <- a1 - solve(f2, f1)
i <- 2
while ( sum( abs(a2 - a1) ) > tol ) {
i <- i + 1
a1 <- a2
phi <- sum(a1)
f1 <- n * digamma( phi ) - n * digamma(a1) + com
f2 <- matrix(n * trigamma(phi), D, D)
diag(f2) <- diag(f2) - n * trigamma(a1)
a2 <- a1 - solve(f2, f1)
}
phi <- sum(a2)
lik <- n * lgamma( phi ) - n * sum( lgamma(a2) ) +
sum( zx * (a2[1:p] - 1) ) - phi * sx2
list(iters = i, loglik = lik, param = a2 )
}
diri.nr2 <- function(x, type = 1, tol = 1e-07) {
dm <- dim(x)
n <- dm[1]
p <- dm[2]
if (type == 1) {
m <- Rfast::colmeans(x)
zx <- t( Log(x) )
down <- - sum( m * ( Rfast::rowmeans( zx ) - log(m) ) )
sa <- 0.5 * (p - 1) / down
a1 <- sa * m
gm <- rowsums(zx)
z <- n * Digamma( sa )
g <- z - n * Digamma(a1) + gm
qk <- - n * Trigamma(a1)
b <- sum(g / qk) / ( 1/z - sum(1 / qk) )
a2 <- a1 - (g - b)/qk
while ( sum( abs( a2 - a1 ) ) > tol ) {
a1 <- a2
z <- n * digamma( sum(a1) )
g <- z - n * Digamma(a1) + gm
qk <- - n * Trigamma(a1)
b <- sum(g / qk) / ( 1/z - sum(1 / qk) )
a2 <- a1 - (g - b) / qk
}
loglik <- n * Lgamma( sum(a2) ) - n * sum( Lgamma(a2) ) + sum( zx * (a2 - 1) )
if ( is.null(colnames(x)) ) {
names(a2) <- paste("X", 1:p, sep = "")
} else names(a2) <- colnames(x)
res <- list(loglik = loglik, param = a2)
} else {
zx <- t( Log(x) )
ma <- Rfast::rowmeans(zx)
m <- Rfast::colmeans(x)
down <- -sum(m * (ma - log(m)))
sa <- 0.5 * (p - 1)/down
a1 <- sa * m
f <- ma - Digamma(a1) + digamma(sa)
der <- - Trigamma(a1) + trigamma(sa)
a2 <- a1 - f/der
a <- .Call(Rfast_diri_nr_type2, a1, a2, ma, p, tol)
loglik <- n * lgamma(sum(a)) - n * sum(Lgamma(a)) + sum(zx * (a - 1))
if (is.null(colnames(x))) {
names(a) <- paste("X", 1:p, sep = "")
} else names(a) <- colnames(x)
res <- list(loglik = loglik, param = a)
}
res
}
mvlnorm.mle <- function(x) {
dm <- dim(x)
d <- dm[2]
n <- dm[1]
y <- Rfast::Log(x)
m1 <- Rfast::colmeans(y)
sigma <- crossprod(y)/n - tcrossprod(m1)
a <- n * d * log(2 * pi) + n * log(det(s)) + n * d - sum(y)
s1 <- diag(sigma)
m <- exp( m1 + 0.5 * s1 )
m2 <- outer(m1, m1, "+")
s2 <- outer(s1, s1, "+")
s <- exp( m2 + 0.5 * s2 ) * ( exp(sigma) - 1 )
list(loglik = -0.5 * a, mu = m1, sigma = sigma, m = m, s = s)
}
mvnorm.mle <- function(x) {
m <- Rfast::colmeans(x)
dm <- dim(x)
n <- dim(x)[1]
d <- dm[2]
s <- crossprod(x)/n - tcrossprod(m)
a <- n * d * log(2 * pi) + n * log( det(s) ) + n * d
list(loglik = - 0.5 * a, mu = m, sigma = s)
}
mvt.mle <- function(x, v = 5, tol = 1e-07){
dm <- dim(x)
p <- dm[2] ; n <- dm[1]
m <- Rfast::colmeans(x)
y <- Rfast::eachrow(x, m, oper = "-")
R <- crossprod(y)/(n - 1)
y <- NULL
if (v != 1 ) R <- abs( v - 1 ) / v * R
con <- n * lgamma( (v + p)/2 ) - n * lgamma(v/2) - 0.5 * n * p * log(pi * v)
wi <- (v + p) / ( v + Rfast::mahala(x, m, R) )
y <- sqrt(wi) * ( Rfast::eachrow(x, m, oper = "-" ) )
sumwi <- sum(wi)
R <- crossprod(y) / sumwi
m <- Rfast::colsums(wi * x) / sumwi
dis <- Rfast::mahala(x, m, R)
el1 <- - n * log( det(R) ) - (v + p) * sum( log1p(dis/v) )
wi <- (v + p) / ( v + dis )
y <- sqrt(wi) * ( Rfast::eachrow(x, m, oper = "-" ) )
sumwi <- sum(wi)
R <- crossprod(y) / sumwi
m <- Rfast::colsums(wi * x) / sumwi
dis <- Rfast::mahala(x, m, R)
el2 <- - n * log( det(R) ) - (v + p) * sum( log1p(dis/v) )
i <- 2
while ( el2 - el1 > tol ) {
i <- i + 1
el1 <- el2
wi <- (v + p) / ( v + dis)
y <- sqrt(wi) * ( Rfast::eachrow(x, m, oper = "-" ) )
sumwi <- sum(wi)
R <- crossprod(y) / sumwi
m <- Rfast::colsums(wi * x) / sumwi
dis <- Rfast::mahala(x, m, R)
el2 <- - n * log( det(R) )- (v + p) * sum( log1p(dis/v) )
}
list(iters = i, loglik = 0.5 * el2 + con, location = m, scatter = R)
} |
ciEnvelope <- function(x,ylo,yhi,...){
polygon(cbind(c(x, rev(x), x[1]), c(ylo, rev(yhi),
ylo[1])), border = NA,...)
}
options(warn = 1, keep.source = TRUE, error = quote({
status.end("ERROR")
}))
status.start <- function(name) {
cat(paste(name, format(Sys.time(), "%F %T"), sep="\t"), file=file.path(settings$outdir, "STATUS"), append=TRUE)
}
status.end <- function(status="DONE") {
cat(paste("", format(Sys.time(), "%F %T"), status, "\n", sep="\t"), file=file.path(settings$outdir, "STATUS"), append=TRUE)
}
library(PEcAn.all)
library(PEcAn.assim.sequential)
library(mvtnorm)
library(rjags)
library(reshape2)
library(PEcAn.LINKAGES)
source('~/pecan/modules/assim.sequential/R/sda.enkf.R')
settings <- read.settings("/fs/data2/output//PEcAn_1000002613/pecan.SDA.xml")
settings$ensemble$size <- 50
settings$state.data.assimilation$n.ensemble<- 100
load(file.path(settings$outdir, "samples.Rdata"))
pick.trait.params <- c(names(ensemble.samples[[1]]),names(ensemble.samples[[2]]))
obs.mean <- list()
for(i in 1:10) {
obs.mean[[i]]<-c(100+i, 5+i)
names(obs.mean[[i]])<-c("NPP",'plantWood')
}
obs.cov <- list()
for(i in 1:10) obs.cov[[i]]<- diag(c(.1,.08))
sda.enkf(settings=settings, obs.mean = obs.mean,
obs.cov = obs.cov, IC = IC, Q = NULL)
settings <- read.settings("/fs/data2/output//PEcAn_1000002229/pecan.xml")
settings$ensemble$size <- 30
IC = matrix(NA,as.numeric(settings$ensemble$size),length(settings$pfts))
settings$run$start.date <-"1960/01/01"
settings$run$end.date <-"1960/12/31"
settings$ensemble$start.date <-"1960/01/01"
settings$ensemble$end.date <-"1960/12/31"
variables <- c("AGB.pft","TotSoilCarb")
processvar <- TRUE
pick.trait.params <- c("G")
spp.params.default <- read.csv(system.file("spp_matrix.csv", package = "linkages"))
sample_parameters=TRUE
load("/home/araiho/linkages_lyford_summary.Rdata")
row.keep <- list()
for(i in 1:15){
row.keep[[i]]<-grep(rownames(ab_mat)[i],spp.params.default[,2])[1]
}
dist.mat<-spp.params.default[unlist(row.keep),]
dist.mat<-dist.mat[-9,]
rownames(dist.mat)<-dist.mat[,1]
dist(dist.mat,method="canberra")
new.names <- spp.params.default[unlist(row.keep),1]
new.names[2] <- spp.params.default[18,1]
rm.spp <- which(is.na(new.names))
new.names<-new.names[-rm.spp]
ab_mat<-ab_mat[-rm.spp,]
rownames(ab_mat)<- paste0("AGB.pft.",new.names)
obs.mean <- list()
for(i in 1:ncol(ab_mat)){
obs.mean[[i]] <- ab_mat[,i]
}
cov_array<-cov_array[-rm.spp,-rm.spp,]
colnames(cov_array)<-new.names
rownames(cov_array)<-new.names
obs.cov <- list()
for(i in 1:dim(cov_array)[3]){
obs.cov[[i]] <- cov_array[,,i]
}
sda.enkf(settings=settings,obs.mean = obs.mean,
obs.cov = obs.cov, pick.trait.params = c("G"),
given.process.variance = NULL) |
.libPaths()
library(cluster)
set.seed(21)
x <- rbind(cbind(rnorm(10, 0, 0.5), rnorm(10, 0, 0.5)),
cbind(rnorm(15, 5, 0.5), rnorm(15, 5, 0.5)),
cbind(rnorm( 3,3.2,0.5), rnorm( 3,3.2,0.5)))
.proctime00 <- proc.time()
(fannyx <- fanny(x, 2))
summary(fannyx)
str(fannyx)
summary(fanny(x,3))
(fanny(x,2, memb.exp = 1.5))
(fanny(x,2, memb.exp = 1.2))
(fanny(x,2, memb.exp = 1.1))
(fanny(x,2, memb.exp = 3))
data(ruspini)
summary(fanny(ruspini, 3), digits = 9)
summary(fanny(ruspini, 4), digits = 9)
summary(fanny(ruspini, 5), digits = 9)
cat('Time elapsed: ', proc.time() - .proctime00,'\n')
data(chorSub)
p4cl <- pam(chorSub, k = 4, cluster.only = TRUE)
f4.20 <- fanny(chorSub, k = 4, trace.lev = 1) ; f4.20$coef
f4.18 <- fanny(chorSub, k = 4, memb.exp = 1.8)
f4.18. <- fanny(chorSub, k = 4, memb.exp = 1.8,
iniMem.p = f4.20$membership)
stopifnot(all.equal(f4.18[-c(7,9)], f4.18.[-c(7,9)], tol = 5e-7))
f4.16 <- fanny(chorSub, k = 4, memb.exp = 1.6)
f4.16. <- fanny(chorSub, k = 4, memb.exp = 1.6,
iniMem.p = f4.18$membership, trace.lev = 2)
f4.16.2 <- fanny(chorSub, k = 4, memb.exp = 1.6,
iniMem.p = cluster:::as.membership(p4cl),
tol = 1e-10, trace.lev = 2)
stopifnot(f4.16$clustering == f4.16.2$clustering,
all.equal(f4.16[-c(1,7,9)], f4.16.2[-c(1,7,9)], tol = 1e-7),
all.equal(f4.16$membership, f4.16.2$membership, tol = 0.001))
f4.14 <- fanny(chorSub, k = 4, memb.exp = 1.4)
f4.12 <- fanny(chorSub, k = 4, memb.exp = 1.2)
table(f4.12$clustering, f4.14$clustering)
table(f4.16$clustering, f4.14$clustering)
table(f4.12$clustering, f4.16$clustering)
symnum(cbind(f4.16$membership, 1, f4.12$membership),
cutpoints= c(0., 0.2, 0.6, 0.8, 0.9, 0.95, 1 -1e-7, 1 +1e-7),
symbols = c(" ", ".", ",", "+", "*", "B","1"))
cat('Time elapsed: ', proc.time() - .proctime00,'\n') |
.onAttach <- function(...) {
mylib <- dirname(system.file(package = "anchors"))
ver <- packageDescription("anchors", lib.loc = mylib)$Version
builddate <- packageDescription("anchors", lib.loc = mylib)$Date
packageStartupMessage("\n
"
} |
DirichReg <- function(formula,
data,
model = c("common", "alternative"),
subset,
sub.comp,
base,
weights,
control,
verbosity = 0
){
this.call <- match.call()
if(!(verbosity %in% 0:4)){
verbosity <- 0L
warning("invalid value for verbosity.")
}
storage.mode(verbosity) <- "integer"
if(verbosity > 0){
cat("- PREPARING DATA\n")
if(interactive()) flush.console()
}
if(missing(data)) data <- environment(formula)
if(missing(formula)){
stop("specification of \"formula\" is necessary.")
} else {
oformula <- formula
}
model <- match.arg(model)
if(missing(control)){
control <- list(sv = NULL, iterlim = 10000L, tol1 = .Machine$double.eps^(1/2), tol2 = .Machine$double.eps^(3/4))
} else {
if(is.null(control$sv)) control$sv <- NULL
if(is.null(control$iterlim)) control$iterlim <- 10000L
if(is.null(control$tol1)) control$tol1 <- .Machine$double.eps^(1/2)
if(is.null(control$tol2)) control$tol2 <- .Machine$double.eps^(3/4)
}
resp_lang <- oformula[[2L]]
resp_char <- deparse_nocutoff(resp_lang)
has_data <- !missing(data)
Y_in_data <- ifelse(has_data, resp_char %in% names(data), FALSE)
has_DR_call <- grepl("DR_data", resp_char, fixed = TRUE)
if(Y_in_data){
Y_full <- data[[resp_char]]
} else if(has_DR_call){
Y_full <- eval(resp_lang)
warning(paste0(strwrap("The response was transformed by DR_data() on the fly. This is not recommended, consider adapting your code.", width = getOption("width") - 9L, exdent = 9L), collapse = "\n"), call. = FALSE, immediate. = TRUE)
oformula[[2L]] <- as.symbol("Y_full")
} else {
Y_full <- get(resp_char, environment(oformula))
}
formula <- as.Formula(oformula)
if(class(Y_full) != "DirichletRegData") stop("the response must be prepared by DR_data")
if(has_data){
assign(resp_char, Y_full)
} else {
data[[resp_char]] <- Y_full
}
repar <- ifelse(model == "common", FALSE, TRUE)
mf <- match.call(expand.dots = FALSE)
if(has_DR_call){
mf[["formula"]][[2L]] <- as.symbol("Y_full")
}
mf <- mf[c(1L, match(c("formula", "data", "subset", "weights"), names(mf), 0L))]
mf[["formula"]] <- as.Formula(mf[["formula"]])
mf[["drop.unused.levels"]] <- TRUE
mf[[1L]] <- as.name("model.frame")
mf_formula <- mf
d <- mf <- eval(mf, parent.frame())
if("(weights)" %in% names(mf)) weights <- mf[["(weights)"]] else weights <- rep(1, nrow(mf))
storage.mode(weights) <- "double"
Y <- model.response(mf, "numeric")
if(missing(sub.comp)){
sub.comp <- seq_len(ncol(Y))
} else {
if(length(sub.comp) == ncol(Y)) warning("no subcomposition made, because all variables were selected")
if(length(sub.comp) == (ncol(Y) - 1)) stop("no subcomposition made, because all variables except one were selected")
if(any((sub.comp < 1) | (sub.comp > ncol(Y)))) stop("subcompositions must contain indices of variables of the Dirichlet data object")
y_in <- (seq_len(ncol(Y)))[sub.comp]
y_out <- (seq_len(ncol(Y)))[-sub.comp]
y_in_labels <- colnames(Y)[y_in]
y_out_labels <- paste(colnames(Y)[y_out], sep = "", collapse = " + ")
Y <- cbind(rowSums(Y[, y_out]), Y[, y_in])
colnames(Y) <- c(y_out_labels, y_in_labels)
}
base <- ifelse(missing(base), attr(Y_full, "base"), base)
if(!(base %in% seq_len(ncol(Y)))) stop("the base variable lies outside the number of variables")
n.dim <- ncol(Y)
if(length(formula)[1] != 1) stop("the left hand side of the model must contain one object prepared by DR_data()")
if(!repar){
if(length(formula)[2] == 1) for(i in 2:ncol(Y)) attr(formula, "rhs") <- lapply(seq_len(ncol(Y)), function(i) attr(formula, "rhs")[[1]])
if(length(formula)[2] > ncol(Y)) stop("the right hand side must contain specifications for either one or all variables")
} else {
if(length(formula)[2] == 1) formula <- as.Formula(formula(formula), ~ 1)
if(length(formula)[2] > 2) stop("the right hand side can only contain one or two specifications in the alternative parametrization")
}
if(!repar){
X.mats <- lapply(seq_len(ncol(Y)), function(i){ model.matrix(terms(formula, data = data, rhs = i), mf) })
Z.mat <- NULL
n.vars <- unlist(lapply(X.mats, ncol))
} else {
X.mats <- lapply(seq_len(ncol(Y)), function(i) model.matrix(terms(formula, data = data, rhs = 1), mf) )
Z.mat <- model.matrix(terms(formula, data = data, rhs = 2), mf)
n.vars <- c(unlist(lapply(X.mats, ncol))[-1], ncol(Z.mat))
}
Y_fit <- unclass(Y)
attributes(Y_fit) <- NULL
dim(Y_fit) <- dim(Y)
storage.mode(Y_fit) <- "double"
X_fit <- lapply(X.mats, function(this_mat){
attr(this_mat, "dimnames") <- NULL
attr(this_mat, "assign") <- NULL
return(this_mat)
})
for(i in seq_along(X_fit)) storage.mode(X_fit[[i]]) <- "double"
if(!is.null(Z.mat)) storage.mode(Z.mat) <- "double"
storage.mode(n.dim) <- "integer"
storage.mode(n.vars) <- "integer"
storage.mode(base) <- "integer"
if(verbosity > 0){
cat("- COMPUTING STARTING VALUES\n")
if(interactive()) flush.console()
}
if(is.null(control$sv)){
starting.vals <- get_starting_values(Y = Y_fit, X.mats = X_fit,
Z.mat = {if(repar) as.matrix(Z.mat) else Z.mat},
repar = repar, base = base, weights = weights) * if(repar){ 1 } else { 1/n.dim }
} else {
if(length(control$sv) != n.vars) stop("wrong number of starting values supplied.")
starting.vals <- control$sv
}
parametrization <- ifelse(repar, "alternative", "common")
if(verbosity > 0){
cat("- ESTIMATING PARAMETERS\n")
if(interactive()) flush.console()
}
fit.res <- DirichReg_fit(Y = Y_fit,
X = X_fit,
Z = as.matrix(Z.mat),
sv = starting.vals,
d = n.dim,
k = n.vars,
w = as.vector(weights),
ctls = control,
repar = repar,
base = base,
vrb = verbosity)
varnames <- colnames(Y)
coefs <- fit.res$estimate
if(repar){
names(coefs) <- unlist(as.vector(c(rep(colnames(X.mats[[1]]), n.dim-1), colnames(Z.mat))))
} else {
names(coefs) <- unlist(lapply(X.mats, colnames))
}
if(repar){
B <- matrix(0.0, nrow = n.vars[1L], ncol = n.dim)
B[cbind(rep(seq_len(n.vars[1L]), (n.dim-1L)), rep(seq_len(n.dim)[-base], each = n.vars[1]))] <- coefs[1:((n.dim-1)*n.vars[1])]
g <- matrix(coefs[((n.dim-1)*n.vars[1]+1):length(coefs)], ncol = 1)
XB <- exp(apply(B, 2L, function(b){ as.matrix(X.mats[[1L]]) %*% b }))
MU <- apply(XB, 2L, function(x){ x /rowSums(XB) })
PHI <- exp(as.matrix(Z.mat) %*% g)
ALPHA <- apply(MU, 2L, "*", PHI)
} else {
B <- sapply(seq_len(n.dim), function(i){ coefs[(cumsum(c(0, n.vars))[i]+1) : cumsum(n.vars)[i]] }, simplify = FALSE)
ALPHA <- sapply(seq_len(n.dim), function(i){ exp(as.matrix(X.mats[[i]]) %*% matrix(B[[i]], ncol = 1)) })
PHI <- rowSums(ALPHA)
MU <- apply(ALPHA, 2L, "/", PHI)
}
colnames(ALPHA) <- varnames
colnames(MU) <- varnames
hessian <- fit.res$hessian
vcov <- tryCatch(solve(-fit.res$hessian),
error = function(x){ return(matrix(NA, nrow = nrow(hessian), ncol = ncol(hessian))) },
silent = TRUE)
if(!repar){
coefnames <- apply(cbind(rep(varnames, n.vars), unlist(lapply(X.mats, colnames))), 1, paste, collapse = ":")
} else {
coefnames <- apply(cbind(rep(c(varnames[-base], "(phi)"), n.vars), c(unlist(lapply(X.mats, colnames)[-base]), colnames(Z.mat))), 1, paste, collapse = ":")
}
dimnames(hessian) <- list(coefnames, coefnames)
dimnames(vcov) <- list(coefnames, coefnames)
shortnames <- names(coefs)
names(coefs) <- coefnames
se <- if(!any(is.na(vcov))) sqrt(diag(vcov)) else rep(NA, length(coefs))
res <- structure(list(
call = this.call,
parametrization = parametrization,
varnames = varnames,
n.vars = n.vars,
dims = length(varnames),
Y = Y,
X = X.mats,
Z = Z.mat,
sub.comp = sub.comp,
base = base,
weights = weights,
orig.resp = Y_full,
data = data,
d = d,
formula = formula,
mf_formula = mf_formula,
npar = length(coefs),
coefficients = coefs,
coefnames = shortnames,
fitted.values = list(mu = MU, phi = PHI, alpha = ALPHA),
logLik = fit.res$maximum,
vcov = vcov,
hessian = hessian,
se = se,
optimization = list(convergence = fit.res$code,
iterations = fit.res$iterations,
bfgs.it = fit.res$bfgs.it,
message = fit.res$message)
),
class = "DirichletRegModel")
for(maxLik_ob in c("lastFuncGrad", "lastFuncParam")){
if(exists(maxLik_ob, envir = parent.frame(), inherits = FALSE)) rm(list = maxLik_ob, envir = parent.frame(), inherits = FALSE)
}
used_objects <- ls(all.names = TRUE)
rm(list = c("used_objects", used_objects[used_objects != "res"]))
on.exit(gc(verbose = FALSE, reset = TRUE), add = TRUE)
return(res)
} |
stat_count <- function(mapping = NULL, data = NULL,
geom = "bar", position = "stack",
...,
width = NULL,
na.rm = FALSE,
show.legend = NA,
inherit.aes = TRUE) {
layer(
data = data,
mapping = mapping,
stat = StatCount,
geom = geom,
position = position,
show.legend = show.legend,
inherit.aes = inherit.aes,
params = list(
na.rm = na.rm,
width = width,
...
)
)
}
StatCount <- gganimintproto("StatCount", Stat,
required_aes = "x",
default_aes = aes(y = ..count..),
setup_params = function(data, params) {
if (!is.null(data$y) || !is.null(params$y)) {
stop("stat_count() must not be used with a y aesthetic.", call. = FALSE)
}
params
},
compute_group = function(self, data, scales, width = NULL) {
x <- data$x
weight <- data$weight %||% rep(1, length(x))
width <- width %||% (resolution(x) * 0.9)
count <- as.numeric(tapply(weight, x, sum, na.rm = TRUE))
count[is.na(count)] <- 0
data.frame(
count = count,
prop = count / sum(abs(count)),
x = sort(unique(x)),
width = width
)
}
) |
context("gather_shadow")
df <- data.frame(x = c(NA, 1:4),
y = c(NA, NA, 1:3))
test_that("gather_shadow returns a tibble or data.frame",{
expect_is(gather_shadow(df), "data.frame")
expect_is(gather_shadow(df), "tbl")
})
test_that("gather_shadow errors when given non dataframe or 0 entry",{
expect_error(gather_shadow(0))
expect_error(gather_shadow(matrix(0)))
expect_error(gather_shadow(NULL))
})
test_that("The number of rows are the same after using gather_shadow",{
expect_equal(nrow(gather_shadow(df)),nrow(df)*2)
})
test_that("There are three columns in gather_shadow",{
expect_equal(ncol(gather_shadow(df)),3)
})
test_that("gather_shadow returns columns with right names",{
expect_equal(names(gather_shadow(df)),
c("case","variable","missing"))
}) |
gglineage <- function(object, labels = TRUE){
nodes <- NULL
object <- as_tidygraph(object)
if (all(stringr::str_detect(attr(object[1], "names"), "[:digit:]{4}"))) {
object <- object %>%
activate(nodes) %>%
mutate(year = stringr::str_extract(.data$name,
"[:digit:]{4}"))
}
lo <- ggraph::create_layout(object, layout = "igraph",
algorithm = "sugiyama",
maxiter = 100000)
if (!is.null(lo$year)) lo$y = lo$year
g <- ggraph::ggraph(object, graph = lo) +
ggraph::geom_edge_diagonal(aes(edge_color = as.factor(.data$from)),
show.legend = FALSE) +
ggraph::geom_node_point(shape = 3) +
ggplot2::theme_void() +
ggplot2::coord_flip() +
ggplot2::scale_x_reverse()
if (labels) {
g <- g + ggraph::geom_node_text(aes(label = .data$name),
nudge_x = 0.1,
repel = TRUE)
}
g
} |
test_that("sql_substr works as expected", {
local_con(simulate_dbi())
x <- ident("x")
substr <- sql_substr("SUBSTR")
expect_equal(substr(x, 3, 4), sql("SUBSTR(`x`, 3, 2)"))
expect_equal(substr(x, 3, 3), sql("SUBSTR(`x`, 3, 1)"))
expect_equal(substr(x, 3, 2), sql("SUBSTR(`x`, 3, 0)"))
expect_equal(substr(x, 3, 1), sql("SUBSTR(`x`, 3, 0)"))
expect_equal(substr(x, 0, 1), sql("SUBSTR(`x`, 1, 1)"))
expect_equal(substr(x, -1, 1), sql("SUBSTR(`x`, 1, 1)"))
expect_snapshot(error = TRUE, substr("test"))
expect_snapshot(error = TRUE, substr("test", 0))
expect_snapshot(error = TRUE, substr("test", "x", 1))
expect_snapshot(error = TRUE, substr("test", 1, "x"))
})
test_that("substring is also translated", {
expect_equal(translate_sql(substring(x, 3, 4)), sql("SUBSTR(`x`, 3, 2)"))
})
test_that("sql_str_sub works as expected", {
local_con(simulate_dbi())
x <- ident("x")
str_sub <- sql_str_sub("SUBSTR")
expect_equal(str_sub(x), sql("SUBSTR(`x`, 1)"))
expect_equal(str_sub(x, 1), sql("SUBSTR(`x`, 1)"))
expect_equal(str_sub(x, -1), sql("SUBSTR(`x`, LENGTH(`x`))"))
expect_equal(str_sub(x, 2, 4), sql("SUBSTR(`x`, 2, 3)"))
expect_equal(str_sub(x, 2, 2), sql("SUBSTR(`x`, 2, 1)"))
expect_equal(str_sub(x, 2, 0), sql("SUBSTR(`x`, 2, 0)"))
expect_equal(str_sub(x, 1, -2), sql("SUBSTR(`x`, 1, LENGTH(`x`) - 1)"))
expect_equal(str_sub(x, 3, -3), sql("SUBSTR(`x`, 3, LENGTH(`x`) - 4)"))
expect_equal(str_sub(x, -3, 0), sql("SUBSTR(`x`, LENGTH(`x`) - 2, 0)"))
expect_equal(str_sub(x, -3, -3), sql("SUBSTR(`x`, LENGTH(`x`) - 2, 1)"))
})
test_that("sql_str_sub can require length paramter", {
local_con(simulate_dbi())
x <- ident("x")
str_sub <- sql_str_sub("SUBSTR", optional_length = FALSE)
expect_equal(str_sub(x), sql("SUBSTR(`x`, 1, LENGTH(`x`))"))
expect_equal(str_sub(x, 1), sql("SUBSTR(`x`, 1, LENGTH(`x`))"))
expect_equal(str_sub(x, -1), sql("SUBSTR(`x`, LENGTH(`x`), 1)"))
})
test_that("str_sub() returns consistent results", {
mf <- memdb_frame(t = "abcde")
expect_equal(mf %>% transmute(str_sub(t, -3, -1)) %>% pull(1), "cde")
expect_equal(mf %>% transmute(str_sub(t, 0, -1)) %>% pull(1), "abcde")
expect_equal(mf %>% transmute(str_sub(t, 1, -3)) %>% pull(1), "abc")
expect_equal(mf %>% transmute(str_sub(t, -3, 0)) %>% pull(1), "")
expect_equal(mf %>% transmute(str_sub(t, 0, 0)) %>% pull(1), "")
expect_equal(mf %>% transmute(str_sub(t, 1, 0)) %>% pull(1), "")
expect_equal(mf %>% transmute(str_sub(t, -3, 5)) %>% pull(1), "cde")
expect_equal(mf %>% transmute(str_sub(t, 0, 1)) %>% pull(1), "a")
expect_equal(mf %>% transmute(str_sub(t, 1, 3)) %>% pull(1), "abc")
}) |
ParamPWR <- setRefClass(
"ParamPWR",
fields = list(
X = "numeric",
Y = "numeric",
m = "numeric",
phi = "matrix",
K = "numeric",
p = "numeric",
gamma = "matrix",
beta = "matrix",
sigma2 = "matrix"
),
methods = list(
initialize = function(X = numeric(), Y = numeric(1), K = 2, p = 3) {
X <<- X
Y <<- Y
m <<- length(Y)
phi <<- designmatrix(X, p)$XBeta
K <<- K
p <<- p
gamma <<- matrix(NA, K + 1)
beta <<- matrix(NA, p + 1, K)
sigma2 <<- matrix(NA, K)
},
computeDynamicProgram = function(C1, K) {
"Method which implements the dynamic programming based on the cost matrix
\\code{C1} and the number of regimes/segments \\code{K}."
solution <- dynamicProg(C1, K)
Ck <- solution$J
gamma <<- matrix(c(0, solution$t_est[nrow(solution$t_est),]))
return(Ck)
},
computeParam = function() {
"Method which estimates the parameters \\code{beta} and \\code{sigma2}
knowing the transition points \\code{gamma}."
for (k in 1:K) {
i <- gamma[k] + 1
j <- gamma[k + 1]
nk <- j - i + 1
yij <- Y[i:j]
X_ij <- phi[i:j, , drop = FALSE]
beta[, k] <<- solve(t(X_ij) %*% X_ij, tol = 0) %*% t(X_ij) %*% yij
if (p == 0) {
z <- yij - X_ij * beta[, k]
} else {
z <- yij - X_ij %*% beta[, k]
}
sigma2[k] <<- t(z) %*% z / nk
}
}
)
) |
MSG <- list(
not_list = "Must be a list.",
valid_x = "x must be a named list or data.frame",
not_unique = "List names must be unique.",
no_names = "List must have named items.",
all_names = "All list items must be named.",
read_only = "VarBundle fields are read only.",
not_empty = "List must not be empty",
not_null = "Argument cannot be NULL",
not_atomic = "Variables must be atomic.",
only_atomic_scalar = "Only VarBundles with all atomic scalar items can be converted to data.frame",
return_null = "Returning NULL"
)
validate_x <- function(x) {
if (is.null(x)) {
stop(MSG$not_null)
}
if (sum(class(x) %in% c("list", "data.frame")) == 0) {
stop(MSG$valid_x)
}
}
validate_list <- function(ll) {
if (length(ll) == 0) {
stop(MSG$not_empty)
}
if (is.null(names(ll))) {
stop(MSG$no_names)
}
if ("" %in% names(ll)) {
stop(MSG$all_names)
}
if (sum(duplicated(names(ll))) > 0) {
stop(MSG$not_unique)
}
} |
f_get_dama_xml <- function(input_file_pbix, xml_start, xml_end) {
index_collection <- f_get_dama_index(input_file_pbix)
extract_xml <- f_get_dama_file(input_file_pbix, "xml", index_collection)
if (xml_start > index_collection[[4]]) {
error_message <- paste0("Start position exceeds length of the XML.")
stop(error_message, call. = FALSE)
}
if (xml_end > index_collection[[4]]) {
error_message <- paste0("End position exceeds length of the XML.")
stop(error_message, call. = FALSE)
}
xml_subset <- extract_xml[xml_start:xml_end]
temp_file <- tempfile()
con <- file(temp_file, "wb")
end_loop <- length(xml_subset)
for (xml_si in seq_along(1:end_loop)) {
write_value <- xml_subset[xml_si]
writeBin(write_value, con = con)
}
close(con)
xml_read <- xml2::read_xml(temp_file)
file.remove(temp_file)
return(xml_read)
} |
generate_pseudo_pop <- function(Y,
w,
c,
ci_appr,
pred_model,
gps_model = "parametric",
use_cov_transform = FALSE,
transformers = list("pow2","pow3"),
bin_seq = NULL,
trim_quantiles = c(0.01,0.99),
optimized_compile = FALSE,
params = list(),
nthread = 1,
...){
max_attempt <- NULL
covar_bl_trs <- NULL
log_system_info()
st_time_gpp <- proc.time()
fcall <- match.call()
check_args(pred_model,ci_appr, use_cov_transform, transformers,
gps_model, trim_quantiles, optimized_compile, ...)
counter <- 0
dot_args <- list(...)
arg_names <- names(dot_args)
for (i in arg_names){
assign(i,unlist(dot_args[i],use.names = FALSE))
}
q1 <- stats::quantile(w,trim_quantiles[1])
q2 <- stats::quantile(w,trim_quantiles[2])
logger::log_debug("{trim_quantiles[1]*100}% qauntile for trim: {q1}")
logger::log_debug("{trim_quantiles[2]*100}% for trim: {q2}")
tmp_data <- convert_data_into_standard_format(Y, w, c, q1, q2, ci_appr)
original_corr_obj <- check_covar_balance(tmp_data, ci_appr, nthread,
optimized_compile, ...)
tmp_data <- NULL
if (ci_appr == "matching") internal_use=TRUE else internal_use=FALSE
covariate_cols <- as.list(colnames(c))
transformed_vals <- covariate_cols
c_extended <- c
recent_swap <- NULL
best_ach_covar_balance <- NULL
while (counter < max_attempt){
counter <- counter + 1
logger::log_debug("Started to estimate gps ... ")
estimate_gps_out <- estimate_gps(Y, w, c_extended[unlist(covariate_cols)],
pred_model, gps_model,
params = params, nthread = nthread,
internal_use = internal_use, ...)
logger::log_debug("Finished estimating gps.")
if (!is.null(recent_swap)){
new_col_ind <- which(covariate_cols==recent_swap[2])
covariate_cols[[new_col_ind]] <- NULL
covariate_cols[length(covariate_cols)+1] <- recent_swap[1]
c_extended[[recent_swap[2]]] <- NULL
estimate_gps_out[[1]][recent_swap[2]] <- NULL
estimate_gps_out[[1]][length(estimate_gps_out[[1]])+1] <- c[recent_swap[1]]
logger::log_debug("Tranformed column {recent_swap[2]} was reset to {recent_swap[1]}.")
}
logger::log_debug("Started compiling pseudo population ... ")
pseudo_pop <- compile_pseudo_pop(dataset=estimate_gps_out, ci_appr=ci_appr,
gps_model,bin_seq, nthread = nthread,
trim_quantiles = trim_quantiles,
optimized_compile = optimized_compile,...)
pseudo_pop <- subset(pseudo_pop[stats::complete.cases(pseudo_pop) ,],
w <= q2 & w >= q1)
logger::log_debug("Finished compiling pseudo population.")
if (ci_appr == 'adjust'){
break
}
adjusted_corr_obj <- check_covar_balance(pseudo_pop, ci_appr, nthread,
optimized_compile, ...)
if (is.null(best_ach_covar_balance)){
best_ach_covar_balance <- adjusted_corr_obj$corr_results$mean_absolute_corr
best_pseudo_pop <- pseudo_pop
best_adjusted_corr_obj <- adjusted_corr_obj
}
if (adjusted_corr_obj$corr_results$mean_absolute_corr < best_ach_covar_balance){
best_ach_covar_balance <- adjusted_corr_obj$corr_results$mean_absolute_corr
best_pseudo_pop <- pseudo_pop
best_adjusted_corr_obj <- adjusted_corr_obj
}
if (adjusted_corr_obj$pass){
message(paste('Covariate balance condition has been met (iteration: ',
counter,'/', max_attempt,')', sep = ""))
break
}
if (use_cov_transform){
sort_by_covar <- sort(adjusted_corr_obj$corr_results$absolute_corr,
decreasing = TRUE)
value_found = FALSE
for (c_name in names(sort_by_covar)){
el_ind <- which(unlist(lapply(transformed_vals,
function(x){ x[1] == c_name })))
if (length(el_ind)==0){
next
}
if (is.factor(c_extended[[c_name]])){
next
}
logger::log_debug("Feature with the worst covariate balance: {c_name}.",
" Located at index {el_ind}.")
for (operand in transformers){
if (!is.element(operand, transformed_vals[[el_ind]])){
new_c <- c_name
new_op <- operand
value_found = TRUE
break
}
}
if (value_found){break}
}
if (!value_found){
warning(paste("All possible combination of transformers has been tried.",
"Try using more transformers.", sep=" "))
} else {
transformed_vals[[el_ind]][length(transformed_vals[[el_ind]])+1] <- new_op
t_dataframe <- transform_it(new_c, c_extended[[new_c]], new_op)
c_extended <- cbind(c_extended, t_dataframe)
recent_swap <- c(new_c, unlist(colnames(t_dataframe)))
index_to_remove <- which(unlist(covariate_cols)==new_c)
covariate_cols[[index_to_remove]] <- NULL
covariate_cols[length(covariate_cols)+1] <- unlist(colnames(t_dataframe))
logger::log_debug("In the next iteration (if any) feature {c_name}",
" will be replaced by {unlist(colnames(t_dataframe))}.")
}
}
}
if (!adjusted_corr_obj$pass){
message(paste('Covariate balance condition has not been met.'))
}
message(paste("Best Mean absolute correlation: ", best_ach_covar_balance,
"| Covariate balance threshold: ", covar_bl_trs))
result <- list()
class(result) <- "gpsm_pspop"
result$params$ci_appr <- ci_appr
result$params$pred_model <- pred_model
result$params$params <- params
for (item in arg_names){
result$params[[item]] <- get(item)
}
result$pseudo_pop <- best_pseudo_pop
result$adjusted_corr_results <- best_adjusted_corr_obj$corr_results
result$original_corr_results <- original_corr_obj$corr_results
result$fcall <- fcall
result$passed_covar_test <- adjusted_corr_obj$pass
result$counter <- counter
result$ci_appr <- ci_appr
result$optimized_compile <- optimized_compile
end_time_gpp <- proc.time()
logger::log_debug("Wall clock time to run generate_pseudo_pop:",
" {(end_time_gpp - st_time_gpp)[[3]]} seconds.")
logger::log_debug("Covariate balance condition has been met (TRUE/FALSE):",
" {adjusted_corr_obj$pass}, (iteration:",
" {counter} / {max_attempt})")
invisible(result)
}
pow2 <- function(x) {x^2}
pow3 <- function(x) {x^3}
transform_it <- function(c_name, c_val, transformer){
t_c_name <- paste(c_name,"_",transformer, sep = "")
t_data <- do.call(transformer, list(c_val))
t_data <- data.frame(t_data)
colnames(t_data) <- t_c_name
return(data.frame(t_data))
} |
make_dt_lookup_by_column <- function(pick, result) {
force(pick)
force(result)
f_dt <- function(d, nd = NULL) {
dt <- as.data.table(d)
.I <- PICK <- RESULT <- NULL
wrapr::let(
c(PICK = pick, RESULT = result),
dt[, RESULT := dt[[PICK]][.I], by = PICK],
strict = FALSE
)
dt[]
}
f_dt
} |
if (interactive()) pkgload::load_all(".")
test_compare_vectors <- function() {
data(mtcars)
cars <- rownames(mtcars)
carz <- cars[-grep("Merc", cars)]
cars <- cars[nchar(cars) < 15]
expectation <-
structure(c("AMC Javelin", NA, "Camaro Z28", NA, "Datsun 710",
NA, "Duster 360", "Ferrari Dino", "Fiat 128", "Fiat X1-9",
"Ford Pantera L",
"Honda Civic", "Hornet 4 Drive", NA, NA, "Lotus Europa",
"Maserati Bora",
"Mazda RX4", "Mazda RX4 Wag", "Merc 230", "Merc 240D",
"Merc 280",
"Merc 280C", "Merc 450SE", "Merc 450SL", "Merc 450SLC", NA,
"Porsche 914-2",
"Toyota Corolla", "Toyota Corona", "Valiant", "Volvo 142E",
"AMC Javelin",
"Cadillac Fleetwood", "Camaro Z28", "Chrysler Imperial",
"Datsun 710",
"Dodge Challenger", "Duster 360", "Ferrari Dino",
"Fiat 128",
"Fiat X1-9", "Ford Pantera L", "Honda Civic",
"Hornet 4 Drive",
"Hornet Sportabout", "Lincoln Continental", "Lotus Europa",
"Maserati Bora",
"Mazda RX4", "Mazda RX4 Wag", NA, NA, NA, NA, NA, NA, NA,
"Pontiac Firebird",
"Porsche 914-2", "Toyota Corolla", "Toyota Corona",
"Valiant",
"Volvo 142E"), .Dim = c(32L, 2L),
.Dimnames = list(c("AMC Javelin", "Cadillac Fleetwood",
"Camaro Z28", "Chrysler Imperial",
"Datsun 710", "Dodge Challenger",
"Duster 360", "Ferrari Dino", "Fiat 128",
"Fiat X1-9", "Ford Pantera L",
"Honda Civic", "Hornet 4 Drive",
"Hornet Sportabout", "Lincoln Continental",
"Lotus Europa", "Maserati Bora",
"Mazda RX4", "Mazda RX4 Wag", "Merc 230",
"Merc 240D", "Merc 280", "Merc 280C",
"Merc 450SE", "Merc 450SL", "Merc 450SLC",
"Pontiac Firebird", "Porsche 914-2",
"Toyota Corolla", "Toyota Corona",
"Valiant", "Volvo 142E"),
c("cars", "carz")))
result <- compare_vectors(cars, carz)
RUnit::checkIdentical(result, expectation)
RUnit::checkIdentical(sort(intersect(cars, carz)),
row.names(result)[complete.cases(result)])
}
if (interactive()) {
test_compare_vectors()
} |
wrap.euclidean <- function(input){
if (is.matrix(input)){
N = nrow(input)
tmpdata = list()
for (i in 1:N){
tmpdata[[i]] = as.vector(input[i,])
}
} else if (is.list(input)){
tmpdata = input
} else {
stop("* wrap.euclidean : input should be either a 2d matrix or a list.")
}
if (!check_list_eqsize(tmpdata, check.square=FALSE)){
stop("* wrap.euclidean : elements are not vectors of same size.")
}
N = length(tmpdata)
for (n in 1:N){
tmpdata[[n]] = matrix(tmpdata[[n]], ncol=1)
}
output = list()
output$data = tmpdata
output$size = dim(tmpdata[[1]])
output$name = "euclidean"
return(structure(output, class="riemdata"))
} |
library(AOV1R)
set.seed(666)
I=3; J=4
dat <- simAV1R(I, J, mu=0, sigmab=2, sigmaw=3)
fit <- aov1r(y ~ group, data=dat)
ssb <- fit[["Sums of squares"]][["ssb"]]
ssw <- fit[["Sums of squares"]][["ssw"]]
total_variance <- sum(fit[["Variance components"]])
a <- 1/J/(I-1)
b <- (1-1/J) * 1/I/(J-1)
(a*ssb+b*ssw)^2/((a*ssb)^2/(I-1) + (b*ssw)^2/(I*(J-1)))
library(VCA)
vca <- anovaMM(y ~ (group), Data=dat)
var_total_var <- sum(vcovVC(vca))
2*total_variance^2 / var_total_var |
suppressPackageStartupMessages(library("argparse"))
parser = ArgumentParser()
parser$add_argument("--infercnv_obj", help="infercnv_obj file", required=TRUE, nargs=1)
args = parser$parse_args()
library(infercnv)
library(ggplot2)
library(futile.logger)
infercnv_obj_file = args$infercnv_obj
infercnv_obj = readRDS(infercnv_obj_file)
pdf('ladeda.pdf') |
seasonal_dot <- function(swmpr_in, ...) UseMethod('seasonal_dot')
seasonal_dot.swmpr <- function(swmpr_in
, param = NULL
, lm_trend = FALSE
, lm_lab = FALSE
, free_y = FALSE
, log_trans = FALSE
, converted = FALSE
, plot_title = FALSE
, plot = TRUE
, ...) {
dat <- swmpr_in
parm <- sym(param)
conv <- converted
seas <- sym('season')
yr <- sym('year')
parameters <- attr(dat, 'parameters')
station <- attr(dat, 'station')
data_type <- substr(station, 6, nchar(station))
if(substr(station, 6, nchar(station)) == 'nut' && !('season_names' %in% names(list(...))))
warning('Nutrient data detected. Consider specifying seasons > 1 month.')
if(!any(param %in% parameters))
stop('Param argument must name input column')
y_trans <- ifelse(log_trans, 'log10', 'identity')
y_label <- y_labeler(param = param, converted = conv)
if(attr(dat, 'qaqc_cols'))
warning('QAQC columns present. QAQC not performed before analysis.')
dat$season <- assign_season(dat$datetimestamp, abb = TRUE, ...)
dat$year <- lubridate::year(dat$datetimestamp)
dat <- dat[, c('year', 'season', param)]
dat <- dat %>% dplyr::filter(!is.na(!! parm))
plt_data <- dat %>%
group_by(!! yr, !! seas) %>%
summarise(min = min(!! parm, na.rm = TRUE)
, mean = mean(!! parm, na.rm = TRUE)
, max = max(!! parm, na.rm = TRUE)
, .groups = "drop_last")
plt_data <- tidyr::complete(plt_data, !! seas)
plt_data[, 3] <- remove_inf_and_nan(plt_data[, 3])
plt_data[, 4] <- remove_inf_and_nan(plt_data[, 4])
plt_data[, 5] <- remove_inf_and_nan(plt_data[, 5])
if(plot) {
agg_lab <- ifelse(length(levels(plt_data$season)) == 12, 'Monthly ', 'Seasonal ')
labs_legend <- factor(paste0(agg_lab, c('Minimum', 'Average', 'Maximum'), sep = ''))
brks <- range(plt_data$year)
tick_interval <- case_when(
diff(brks) > 20 ~ 4,
diff(brks) > 10 ~ 2,
TRUE ~ 1)
mx <- max(plt_data[ , c(3:5)], na.rm = TRUE) * 1.2
mx <- ifelse(data_type == 'nut' && param != 'chla_n', ceiling(mx/0.01) * 0.01, ceiling(mx))
mn <- min(plt_data[ , c(3:5)], na.rm = TRUE)
mn <- ifelse(mn < 0 , min(pretty(mn)), 0)
mn <- ifelse(log_trans, ifelse(substr(station, 6, nchar(station)) == 'nut', 0.001, 0.1), mn)
plt <-
ggplot(data = plt_data, aes_string(x = "year", y = "min", color = labs_legend[1])) +
geom_point() +
geom_point(data = plt_data, aes_string(x = "year", y = "mean", color = labs_legend[2])) +
geom_point(data = plt_data, aes_string(x = "year", y = "max", color = labs_legend[3])) +
geom_point() +
scale_color_manual('', values = c('black', 'red', 'blue')) +
scale_x_continuous(breaks = seq(from = brks[1], to = brks[2],
by = tick_interval)) +
facet_wrap(~ season) +
labs(x = NULL, y = eval(y_label))
if(!log_trans) {
plt <- plt +
scale_y_continuous(labels = scales::format_format(digits = 2, big.mark = ",", decimal.mark = ".", scientific = FALSE)
, breaks = scales::breaks_pretty(n = 8))
if(!free_y){plt <- plt + expand_limits(y = mn)}
} else {
plt <- plt +
scale_y_continuous(trans = y_trans
, labels = scales::format_format(digits = 2, big.mark = ",", decimal.mark = ".", scientific = FALSE)
, breaks = scales::breaks_pretty(n = 8))
if(!free_y) {plt <- plt + expand_limits(y = mn)}
}
plt <-
plt +
theme_bw() +
theme(legend.position = 'top'
, legend.direction = 'horizontal') +
theme(panel.grid.major = element_line(linetype = 'solid'),
panel.grid.minor = element_line(linetype = 'solid'),
strip.background = element_blank(),
panel.border = element_rect(color = 'black')) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5),
axis.title.y = element_text(margin = unit(c(0, 8, 0, 0), 'pt'), angle = 90)) +
theme(text = element_text(size = 16))
plt <-
plt +
theme(legend.key.size = unit(7, 'pt')) +
theme(legend.text = element_text(size = 10)) +
theme(legend.spacing.x = unit(3, 'pt'))
if(lm_trend) {
plt <-
plt +
geom_smooth(aes_string(x = 'year', y = 'min', color = labs_legend[1])
, method = 'lm', se = FALSE, lwd = 0.5
, formula = y ~ x) +
geom_smooth(aes_string(x = 'year', y = 'mean', color = labs_legend[2])
, method = 'lm', se = FALSE, lwd = 0.5
, formula = y ~ x) +
geom_smooth(aes_string(x = 'year', y = 'max', color = labs_legend[3])
, method = 'lm', se = FALSE, lwd = 0.5
, formula = y ~ x)
}
if(lm_lab) {
p_labs <- lm_p_labs(plt_data)
if(nrow(p_labs) > 0) {
y_mx <- max(ggplot_build(plt)$layout$panel_scales_y[[1]]$range$range)
y_mn <- min(ggplot_build(plt)$layout$panel_scales_y[[1]]$range$range)
y_rng <- y_mx - y_mn
p_labs$x <- brks[2]
p_labs$max_y <- y_mx - (0.01 * y_rng)
p_labs$mean_y <- y_mx - (0.135 * y_rng)
p_labs$min_y <- y_mx - (0.255 * y_rng)
plt <-
plt +
geom_text(aes(label = .data$max, x = .data$x, y = .data$max_y)
, data = p_labs
, fontface = ifelse(p_labs$max == 'p < 0.05', 2, 1)
, hjust = 1, color = 'red') +
geom_text(aes(label = .data$mean, x = .data$x, y = .data$mean_y)
, data = p_labs
, fontface = ifelse(p_labs$mean == 'p < 0.05', 2, 1)
, hjust = 1, color = 'black') +
geom_text(aes(label = .data$min, x = .data$x, y = .data$min_y)
, data = p_labs
, fontface = ifelse(p_labs$min == 'p < 0.05', 2, 1)
, hjust = 1, color = 'blue')
} else {
warning('Insufficient data to calculate linear regression p-values')
}
}
if(plot_title) {
ttl <- title_labeler(nerr_site_id = station)
plt <-
plt +
ggtitle(ttl) +
theme(plot.title = element_text(hjust = 0.5))
}
return(plt)
} else {
return(plt_data)
}
} |
ess <- function(mix, method=c("elir", "moment", "morita"), ...) UseMethod("ess")
ess.default <- function(mix, method=c("elir", "moment", "morita"), ...) stop("Unknown density")
calc_loc <- function(mix, loc=c("mode", "median", "mean")) {
loc <- match.arg(loc)
if(loc == "mode") {
tol <- .Machine$double.eps^0.25
locEst <- mixmode(mix)
if(length(attr(locEst, "modes")) > 1) {
warning("Detected multiple modes.\nThe ESS is determined for the largest mode, but ESS concept is ill-defined for multi-modal distributions.")
} else {
attr(locEst, "modes") <- NULL
}
}
if(loc == "median") {
locEst <- qmix(mix, 0.5)
}
if(loc == "mean") {
locEst <- summary(mix, NULL)["mean"]
}
names(locEst) <- NULL
return(unname(locEst))
}
mixInfo <- function(mix, x, dens, gradl, hessl) {
p <- mix[1,]
a <- mix[2,]
b <- mix[3,]
lp <- log(p)
ldensComp <- dens(x, a, b, log=TRUE)
ldensMix <- log_sum_exp(lp + ldensComp)
lwdensComp <- lp + ldensComp - ldensMix
dgl <- gradl(x,a,b)
dhl <- (hessl(x,a,b) + dgl^2)
if(all(dgl < 0) || all(dgl > 0)) {
gsum <- exp(2*log_sum_exp(lwdensComp + log(abs(dgl))))
} else {
gsum <- (sum(exp(lwdensComp)*dgl))^2
}
if(all(dhl < 0) || all(dhl > 0)) {
hsum <- sign(dhl[1]) * exp(log_sum_exp(lwdensComp + log(abs(dhl))))
} else {
hsum <- (sum(exp(lwdensComp)*dhl))
}
gsum - hsum
}
lir <- function(mix, info, fisher_inverse) {
fn <- function(x) {
info(mix, x) * fisher_inverse(x)
}
Vectorize(fn)
}
weighted_lir <- function(mix, info, fisher_inverse) {
fn <- function(x) {
dmix(mix, x) * info(mix, x) * fisher_inverse(x)
}
Vectorize(fn)
}
weighted_lir_link <- function(mix, info, fisher_inverse, link) {
dlink(mix) <- link_map[[link]]
fn <- function(x) {
x_orig <- mixinvlink(mix, x)
dmix(mix, x) * info(mix, x_orig) * fisher_inverse(x_orig)
}
Vectorize(fn)
}
ess.betaMix <- function(mix, method=c("elir", "moment", "morita"), ..., s=100) {
method <- match.arg(method)
if(method == "elir") {
if(!test_numeric(mix[2,], lower=1, finite=TRUE, any.missing=FALSE) ||
!test_numeric(mix[3,], lower=1, finite=TRUE, any.missing=FALSE)) {
stop("At least one parameter of the beta mixtures is less than 1.\n",
"This leads to an ill-defined elir ess since the defining integral diverges.\n",
"Consider constraining all parameters to be greater than 1 (use constrain_gt1=TRUE argument for EM fitting functions).")
}
elir <- integrate_density(lir(mix, betaMixInfo, bernoulliFisherInfo_inverse), mix)
return(elir)
}
if(method == "moment") {
smix <- summary(mix)
res <- sum(ms2beta(smix["mean"], smix["sd"]))
names(res) <- NULL
return( res )
}
alphaP <- mix[2,]
betaP <- mix[3,]
locEst <- calc_loc(mix, "mode")
deriv2.prior <- betaMixInfo(mix, locEst)
ESSmax <- ceiling(sum(alphaP+betaP)) * 2
alphaP0 <- locEst / s
betaP0 <- (1-locEst) / s
info.prior0 <- betaInfo(locEst, alphaP0, betaP0)
if(any(rowSums(mix[2:3,,drop=FALSE]) < 10/s )) {
warning("Some of the mixture components have a scale which is large compared to the rescaling factor s. Consider increasing s.")
}
ed2p <- function(m) {
yn <- seq(0,m)
info <- betaInfo(locEst, alphaP0 + yn, betaP0 + m - yn)
sum(info * dmix(preddist(mix,n=m), yn) )
}
ed2pDiff <- function(m) {
deriv2.prior - ed2p(m)
}
pd0 <- dmix(preddist(mix, n=1), 0)
Einfo <- binomialInfo(0,locEst,1) * pd0 + binomialInfo(1,locEst,1) * (1-pd0)
return( unname((deriv2.prior - info.prior0) / Einfo ) )
}
betaLogGrad <- function(x,a,b) {
lxm1 <- log1p(-x)
lx <- log(x)
- (b-1) * exp(- lxm1) + (a-1)*exp(- lx)
}
betaLogHess <- function(x,a,b) {
lxm1 <- log1p(-x)
lx <- log(x)
- (b-1) * exp(-2 * lxm1) - (a-1)*exp(-2 * lx)
}
betaMixInfo <- function(mix,x) {
mixInfo(mix, x, dbeta, betaLogGrad, betaLogHess)
}
betaInfo <- function(x,a,b) {
-betaLogHess(x,a,b)
}
bernoulliFisherInfo_inverse <- function(x) {
x - x^2
}
binomialInfo <- function(r,theta,n) {
r / theta^2 + (n-r)/(1-theta)^2
}
ess.gammaMix <- function(mix, method=c("elir", "moment", "morita"), ..., s=100, eps=1E-4) {
method <- match.arg(method)
lik <- likelihood(mix)
if(method == "elir") {
if(lik == "poisson")
return(integrate_density(lir(mix, gammaMixInfo, poissonFisherInfo_inverse), mix))
if(lik == "exp")
return(integrate_density(lir(mix, gammaMixInfo, expFisherInfo_inverse), mix))
}
if(method == "moment") {
smix <- summary(mix)
coef <- ms2gamma(smix["mean"], smix["sd"])
names(coef) <- NULL
if(lik == "poisson")
return(unname(coef[2]))
if(lik == "exp")
return(unname(coef[1]))
stop("Unkown likelihood")
}
locEst <- calc_loc(mix, "mode")
deriv2.prior <- gammaMixInfo(mix, locEst)
if(lik == "poisson") {
meanPrior <- summary(mix)["mean"]
names(meanPrior) <- NULL
priorN <- mix[3,,drop=FALSE]
ed2pDiff <- function(m) {
deriv2.prior - ( gammaInfo(locEst, locEst/s + m * meanPrior, 1/s))
}
ESSmax <- ceiling(sum(mix[3,])) * 2
info.prior0 <- gammaInfo(locEst, locEst/s, 1/s)
pred_pmf <- preddist(mix, n=1)
lim <- qmix(pred_pmf, c(eps/2, 1-eps/2))
y1 <- seq(lim[1], lim[2])
Einfo <- sum(dmix(pred_pmf, y1) * poissonInfo(y1, locEst))
}
if(lik == "exp") {
priorN <- mix[2,,drop=FALSE]
ed2pDiff <- function(m) {
deriv2.prior - gammaInfo(locEst, 1/s + m, 1/(s*locEst))
}
ESSmax <- ceiling(sum(mix[2,])) * 2
info.prior0 <- gammaInfo(locEst, 1/s, 1/(s*locEst))
Einfo <- expInfo(1,locEst)
}
if(any(priorN < 10/s )) {
warning("Some of the mixture components have a scale which is large compared to the rescaling factor s. Consider increasing s.")
}
return(unname( (deriv2.prior - info.prior0)/Einfo ) )
}
gammaLogGrad <- function(x,a,b) {
(a-1)/x - b
}
gammaLogHess <- function(x,a,b) {
-(a-1)/x^2
}
gammaInfo <- function(x,a,b) {
-gammaLogHess(x,a,b)
}
gammaMixInfo <- function(mix,x) {
mixInfo(mix, x, dgamma, gammaLogGrad, gammaLogHess)
}
poissonFisherInfo_inverse <- function(x) {
x
}
expFisherInfo_inverse <- function(x) {
x^2
}
poissonInfo <- function(y,theta) {
y/theta^2
}
expInfo <- function(y,theta) {
1/theta^2
}
ess.normMix <- function(mix, method=c("elir", "moment", "morita"), ..., sigma, s=100) {
method <- match.arg(method)
if(missing(sigma)) {
sigma <- RBesT::sigma(mix)
message("Using default prior reference scale ", sigma)
}
assert_number(sigma, lower=0)
tauSq <- sigma^2
mu <- mix[2,]
sigma <- mix[3,]
sigmaSq <- sigma^2
if(method == "elir") {
return(tauSq * integrate_density(lir(mix, normMixInfo, normStdFisherInfo_inverse), mix))
}
if(method == "moment") {
smix <- summary(mix)
res <- tauSq / smix["sd"]^2
return( unname(res) )
}
locEst <- calc_loc(mix, "mode")
deriv2.prior <- normMixInfo(mix, locEst)
ESSmax <- ceiling(sum( (1-1/s) * tauSq/sigmaSq )) * 2
muP0 <- locEst
sigmaP0Sq <- s * max(sigmaSq)
ed2pDiff <- function(m) {
deriv2.prior - normInfo(locEst, muP0, sqrt(1/(m/tauSq + 1/sigmaP0Sq)))
}
info.prior0 <- normInfo(locEst, muP0, sqrt(sigmaP0Sq))
Einfo <- 1/tauSq
return(unname( (deriv2.prior - info.prior0)/Einfo ))
}
normLogGrad <- function(x,mu,sigma) {
-1 * (x-mu)/(sigma)^2
}
normLogHess <- function(x,mu,sigma) {
-1/sigma^2
}
normMixInfo <- function(mix,x) {
mixInfo(mix, x, dnorm, normLogGrad, normLogHess)
}
normInfo <- function(x,mean,sigma) {
-normLogHess(x,mean,sigma)
}
normStdFisherInfo_inverse <- function(x) {
1.0
} |
summary_interact <- function(model, ref, discrete,
ref_min = NULL, ref_max = NULL,
level = NULL,
...,
digits = 3L,
p = FALSE) {
if (!inherits(model, "lrm")) {
ui_stop("model has to inherits to lrm class")
}
if (is.null(getOption("datadist"))) ui_stop("datadist non defined")
discrete <- rlang::enquo(discrete)
discrete_name <- rlang::quo_name(discrete)
ref <- rlang::enquo(ref)
ref_name <- rlang::quo_name(ref)
dd <- getOption("datadist") %>%
as.name() %>%
eval()
if (!ref_name %in% names(dd[["limits"]])) {
ui_stop("ref isn't in datadist")
}
if (!discrete_name %in% names(dd[["limits"]])) {
ui_stop("discrete isn't in datadist")
}
if (is.null(ref_min)) {
ref_min <- dd[["limits"]][[ref_name]][[1L]]
}
if (is.null(ref_max)) {
ref_max <- dd[["limits"]][[ref_name]][[3L]]
}
if (is.null(level)) {
level <- dd[["values"]][[discrete_name]]
}
suppressMessages({
res <- purrr::map_df(.x = level, ~ {
interact <- .x
eval(parse(text = paste0(
"summary(model, ",
discrete_name, " = interact, ",
ref_name, " = c(ref_min, ref_max)",
")"
))) %>%
tibble::as_tibble(
rownames = ".rownames",
.name_repair = "universal"
) %>%
dplyr::mutate(.rownames = dplyr::lag(.data[[".rownames"]])) %>%
dplyr::filter(Type == 2L) %>%
dplyr::select(-"Type", -"S.E.") %>%
dplyr::filter(.rownames == rlang::quo_name(ref)) %>%
dplyr::mutate(
Low = ifelse(is.na(Diff.), NA, Low),
High = ifelse(is.na(Diff.), NA, High),
Diff. = ifelse(!is.na(Diff.), Diff.,
stringr::str_extract(.data[[".rownames"]], " - .*$") %>%
stringr::str_replace(" - ", "")
),
Effect = as.numeric(Effect),
Lower.0.95 = as.numeric(Lower.0.95),
Upper.0.95 = as.numeric(Upper.0.95),
.rownames = stringr::str_replace(.data[[".rownames"]], " -+.*$", "")
) %>%
dplyr::mutate(
.rownames = paste0(.data[[".rownames"]], " - ", interact)
) %>%
dplyr::rename(
` ` = .data[[".rownames"]],
`Odds Ratio` = .data[["Effect"]],
`Lower 95% CI` = .data[["Lower.0.95"]],
`Upper 95% CI` = .data[["Upper.0.95"]]
)
})
})
if (p) {
res[["P-value"]] <- purrr::pmap_dbl(
list(
or = res[["Odds Ratio"]],
low = res[["Lower 95% CI"]],
high = res[["Upper 95% CI"]]
),
function(or, low, high) {
ci2p(or, low, high, log_transform = TRUE)
}
)
}
res %>%
dplyr::mutate_if(is.double, round, digits = digits)
} |
fts.dpca = function(X,
q = 30,
freq = (-1000:1000/1000)*pi,
Ndpc = X$basis$nbasis){
if (!is.fd(X))
stop("X must be a functional data object")
res = list()
res$spec.density = fts.spectral.density(X, freq = freq, q = q)
res$filters = fts.dpca.filters(res$spec.density, q = q, Ndpc = Ndpc)
res$scores = fts.dpca.scores(X, res$filters)
res$var = fts.dpca.var(res$spec.density)
res$Xhat = fts.dpca.KLexpansion(X, res$filters)
res
} |
test_that("file_line_endings detects Unix line endings", {
tmp <- tempfile()
on.exit(unlink(tmp))
writeBin(charToRaw("foo\n"), tmp)
expect_equal(file_line_endings(tmp), "\n")
writeBin(charToRaw(""), tmp)
expect_identical(file_line_endings(tmp), NA_character_)
})
test_that("file_line_endings detects Windows line endings", {
tmp <- tempfile()
on.exit(unlink(tmp))
writeBin(charToRaw("foo\r\n"), tmp)
expect_equal(file_line_endings(tmp), "\r\n")
}) |
v.raster <- function(obj, varname, layer=1, param=varname, zlim, minv, maxv, adaptive.vals, replace.na=F, Log, main,
show.colorbar,cbpos='',cbx, cby, cb.title, cb.xlab, cb.xlab.line=0, pal, nticks=5,
sidelabels=F, Ylab=F, axeslabels=T, ticklabels=T, cex.lab=0.8, cex.ticks=0.8, cex.cb.title=0.9,cex.cb.xlab=0.8,cex.cb.ticks=0.7,
subplot=F, width, height, figdim, xpos=-1, Save=F, plotfolder=".", plotname, fileformat="png", suffix,
region, v_area=region, v_image=T, v_contour=F, levels, contour.labels=NULL, v_arrows=F, scale_arrow=1,
fill.land=T, col.land="grey", col.bg=NA,border='black', grid=T, grid.res, bwd=2,cb.ticks.srt=90,las=1,
dates,terrain=T,verbose=T){
if(missing(show.colorbar)) show.colorbar <- T
if(missing(param) & missing(varname)) {
param <- ''
if(missing(cb.xlab) & missing(cb.title)) cb.xlab <- names(obj)
if(missing(cb.title)) cb.title <- ''
}
if(missing(varname)) varname <- param
if(!missing(width) & !missing(height)) figdim <- c(width, height)
region_definitions <- NULL
rm(region_definitions)
data('region_definitions',envir=environment())
parameter_definitions <- NULL
rm(parameter_definitions)
data('parameter_definitions',envir=environment())
param_def <- parameter_definitions[as.character(parameter_definitions$param) == param,]
if(nrow(param_def) == 0) param_def <- as.data.frame(matrix(NA,nrow=1,ncol=ncol(param_def),dimnames=list(1,names(param_def))))
if(missing(Log)) Log <- F
param_def$log <- as.numeric(Log)
if(missing(cb.xlab) & is.na(param_def$name1)) cb.xlab <- varname
param <- param_def$param <- varname
if(param == "bathy" & !terrain){
ii <- which(obj[,] < 0)
if(length(ii) > 0){
obj[obj[,] > 0] <- NA
obj[,] <- -obj[,]
}
}
if(!(grepl('Raster', class(obj)))) stop('error in.v.raster.r: obj of unknown input format. Please check!')
obj <- brick(obj)
if(missing(adaptive.vals)) adaptive.vals <- T
if(missing(v_area)){
ext <- extent(obj)
v_area.rounded <- round(as.vector(t(sp::bbox(ext))),digits=1)
ext2 <- as.vector(t(sp::bbox(ext)))[c(4,3,1:2)]
id <- which(apply(region_definitions[,3:6],1,function(x) all(ext2 %in% x)))
if(length(id) > 0){
v_area <- as.character(region_definitions$label[id[1]])
v_area.valid <- T
}else{
v_area.valid <- F
cat('\nno region (v_area) defined, run add.region to add region definitions and to save settings for the plot region, colorbar and window size!\n')
v_area.name <- paste0('lon',v_area.rounded[1],'-',v_area.rounded[2],'.lat',v_area.rounded[3],'-',v_area.rounded[4])
r <- as.data.frame(matrix(NA,ncol=8,nrow=2))
names(r) <- c("xlim","ylim","dim","name","cbx","cby","figdim","grid.res")
}
}else{
v_area.valid <- T
if(class(v_area) == 'Extent'){
v_area.valid <- F
area.extent <- ext <- v_area
obj <- crop(obj,area.extent)
v_area.name <- 'object.extent'
r <- as.data.frame(matrix(NA,ncol=8,nrow=2))
names(r) <- c("xlim","ylim","dim","name","cbx","cby","figdim","grid.res")
}
}
if(v_area.valid){
r <- regions(v_area)
area.extent <- extent(c(range(r$xlim),range(r$ylim)))
if(dim(obj)[3] > 1){
obj <- crop(obj,area.extent)
}else{
obj <- brick(crop(raster(obj,layer=1),area.extent))
}
v_area.name <- v_area
if(missing(grid.res)) grid.res <- r$grid.res[1]
ext <- extent(c(r$xlim,r$ylim))
}
if(cbpos %in% c('b','l','t','r') | !v_area.valid){
cb <- cust.colorbar(ext,cbpos=cbpos,cbx=cbx,cby=cby,figdim=figdim,force.figdim.widget=F,xpos=xpos)
r$cbx <- cb$cbx
r$cby <- cb$cby
r$align <- cb$align
r$figdim <- cb$figdim
}
if(missing(dates)) dates <- apply(as.matrix(names(obj)),1,function(x)tail(strsplit(x,"X")[[1]],1))
if(any(dates == 'layer')) dates <- rep(NA,length(dates))
if(length(dates) <= 1){
timestep = "1d"
}else{
k <- as.POSIXct(dates,format="%Y%m%d%H")
k.diff <- diff(k)
k.val <- round(k.diff)[[1]]
k.unit <- substr(attributes(k.diff)$units,0,1)
if(k.val %in% c(28:31) & k.unit == "d"){
k.val <- 1
k.unit <- "m"
}
timestep <- paste0(k.val,k.unit)
}
for(ts in layer){
file_def <- list(source='raster',timestep=timestep,date1=dates[which(layer %in%ts)],date2=dates[which(layer %in%ts)])
outfile.name <- paste0(v_area.name,"_",param)
if(!is.na(file_def$date1)) outfile.name <- paste0(outfile.name,"_",file_def$date1)
b <- raster(obj,layer=ts)
.v.plot(b=b, minv=minv, maxv=maxv, zlim=zlim, adaptive.vals=adaptive.vals, v_area=v_area, replace.na=replace.na,
main=main, cb.title=cb.title, cb.xlab=cb.xlab, cb.xlab.line=cb.xlab.line, pal=pal, cb.ticks.srt=cb.ticks.srt, nticks=nticks,
sidelabels=sidelabels, Ylab=Ylab,
axeslabels=axeslabels, ticklabels=ticklabels, cex.lab=cex.lab, cex.ticks=cex.ticks,
cex.cb.title=cex.cb.title,cex.cb.xlab=cex.cb.xlab,cex.cb.ticks=cex.cb.ticks,
subplot=subplot, xpos=xpos, Save=Save, plotfolder=plotfolder, plotname=plotname, fileformat=fileformat,
param=param, param_def=param_def, file_def=file_def, r=r, outfile.name=outfile.name,
show.colorbar=show.colorbar,suffix=suffix,
v_image=v_image, v_contour=v_contour, levels=levels, contour.labels=contour.labels, v_arrows=F,
fill.land=fill.land, col.land=col.land, col.bg=col.bg,border=border, grid=grid, grid.res=grid.res, bwd=bwd,las=las,verbose=verbose)
}
} |
reactivePlotOutput <- function(id) {
ns <- NS(id)
plotOutput(ns("plot_out"))
}
reactivePlot <- function(input, output, session, plot_type, dat) {
req(dat)
if(plot_type == "line") {
output$plot_out <- renderPlot({
ggplot(dat(), aes(x=DateTime, y=Elevation, group=Animal, color=Animal)) +
labs( title = "Elevation Time Series, by Animal",
x = "Date",
y = "Elevation (meters)") +
ylim(1000,2000) +
geom_line(na.rm = TRUE) +
geom_point(na.rm = TRUE) +
theme_minimal()
})
}
else if(plot_type == "hist") {
output$plot_out <- renderPlot({
ggplot(dat(), aes(x=TimeDiffMins, fill=Animal)) +
geom_histogram( col="White", breaks = seq(0,40, 2)) +
facet_wrap(~Animal, ncol=2)+
labs( title = "Sample Rate, by GPS Unit" ,
x = "Time between GPS Readings (minutes)",
y = "Frequency") +
theme_minimal()
})
}
else if(plot_type == "violin") {
output$plot_out <- renderPlot({
ggplot(dat() %>% dplyr::filter(Rate < 50), aes(x=Animal, y= Rate, fill=Animal))+
geom_violin() +
geom_boxplot(width=.2, outlier.color = NA) +
theme_minimal()+
labs( title = "Rate of Travel, by GPS Unit" ,
x = "Animal",
y = "Rate of Travel (meters/minute)") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
})
}
else if(plot_type == "heatmap") {
mybreaks <- reactive({
list(x = round( seq(min(dat()$Longitude), max(dat()$Longitude), length.out = 10 ),3),
y = round( seq(min(dat()$Latitude), max(dat()$Latitude), length.out = 10 ),3))
})
output$plot_out <- renderPlot({
ggplot(dat() %>%
dplyr::mutate( LongBin = cut_number(Longitude, 100,
labels= round( seq(min(Longitude), max(Longitude), length.out = 100 ),3)
),
LatBin = cut_number(Latitude, 100,
labels=round( seq(min(Latitude), max(Latitude), length.out = 100 ), 3)
)) %>%
group_by(LongBin, LatBin, Animal) %>%
summarize(Duration = sum(TimeDiffMins, na.rm = TRUE)/60),
aes (x = LongBin, y = LatBin, fill = Duration))+
geom_tile() +
facet_wrap(~Animal, ncol=2)+
labs( title = "Total Time Spent per Location (hours)" ,
x = "Longitude",
y = "Latitude")+
scale_fill_gradientn(colors = c("white", "green", "red")) +
scale_x_discrete( breaks = mybreaks()$x) +
scale_y_discrete( breaks = mybreaks()$y) +
coord_equal() +
theme_minimal()
}, height = 1200)
}
} |
ewrates <-
structure(list(year = c(1931, 1931, 1931, 1931, 1931, 1931, 1931,
1931, 1931, 1931, 1931, 1931, 1931, 1931, 1931, 1936, 1936, 1936,
1936, 1936, 1936, 1936, 1936, 1936, 1936, 1936, 1936, 1936, 1936,
1936, 1941, 1941, 1941, 1941, 1941, 1941, 1941, 1941, 1941, 1941,
1941, 1941, 1941, 1941, 1941, 1946, 1946, 1946, 1946, 1946, 1946,
1946, 1946, 1946, 1946, 1946, 1946, 1946, 1946, 1946, 1951, 1951,
1951, 1951, 1951, 1951, 1951, 1951, 1951, 1951, 1951, 1951, 1951,
1951, 1951, 1956, 1956, 1956, 1956, 1956, 1956, 1956, 1956, 1956,
1956, 1956, 1956, 1956, 1956, 1956, 1961, 1961, 1961, 1961, 1961,
1961, 1961, 1961, 1961, 1961, 1961, 1961, 1961, 1961, 1961, 1966,
1966, 1966, 1966, 1966, 1966, 1966, 1966, 1966, 1966, 1966, 1966,
1966, 1966, 1966, 1971, 1971, 1971, 1971, 1971, 1971, 1971, 1971,
1971, 1971, 1971, 1971, 1971, 1971, 1971, 1976, 1976, 1976, 1976,
1976, 1976, 1976, 1976, 1976, 1976, 1976, 1976, 1976, 1976, 1976
), age = c(10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70,
75, 80, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75,
80, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80,
10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 10,
15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 10, 15,
20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 10, 15, 20,
25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 10, 15, 20, 25,
30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 10, 15, 20, 25, 30,
35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 10, 15, 20, 25, 30, 35,
40, 45, 50, 55, 60, 65, 70, 75, 80), lung = c(1, 2, 6, 14, 30,
68, 149, 274, 431, 586, 646, 636, 533, 464, 324, 1, 2, 6, 14,
30, 68, 149, 274, 431, 586, 646, 636, 533, 464, 324, 1, 2, 6,
16, 34, 81, 191, 384, 597, 883, 1021, 970, 748, 631, 385, 1,
3, 8, 18, 36, 94, 236, 544, 954, 1350, 1717, 1763, 1400, 1085,
765, 0, 2, 7, 13, 35, 98, 248, 579, 1224, 2003, 2555, 2926, 2624,
2069, 1416, 0, 2, 4, 12, 35, 93, 251, 590, 1248, 2317, 3315,
3926, 3878, 3332, 2258, 0, 2, 5, 11, 34, 90, 223, 563, 1221,
2284, 3663, 4844, 4977, 4513, 3417, 0, 2, 4, 10, 25, 76, 216,
531, 1160, 2201, 3695, 5273, 6210, 5914, 4563, 0, 1, 4, 10, 24,
58, 177, 503, 1070, 2077, 3546, 5174, 6820, 7273, 6089, 0, 1,
2, 7, 17, 56, 139, 403, 1003, 1896, 3342, 4985, 6718, 8068, 7744
), nasal = c(0, 0, 0, 0, 1, 1, 3, 5, 10, 15, 16, 19, 27, 48,
47, 0, 0, 0, 0, 1, 1, 3, 5, 10, 15, 16, 19, 27, 48, 47, 0, 0,
0, 0, 1, 1, 3, 5, 10, 15, 16, 19, 27, 48, 47, 0, 0, 0, 0, 1,
1, 3, 5, 10, 15, 16, 19, 27, 48, 47, 0, 0, 0, 0, 1, 1, 3, 5,
10, 15, 16, 19, 27, 48, 47, 0, 0, 0, 0, 1, 1, 3, 3, 6, 12, 17,
24, 28, 43, 50, 0, 0, 0, 0, 0, 1, 3, 4, 8, 9, 14, 18, 26, 41,
42, 0, 0, 0, 0, 0, 1, 2, 5, 7, 11, 16, 23, 29, 36, 31, 0, 0,
0, 1, 1, 1, 4, 4, 8, 11, 16, 26, 29, 33, 38, 0, 0, 0, 1, 1, 1,
2, 3, 9, 9, 15, 17, 20, 38, 33), other = c(1269, 2201, 3116,
3024, 3188, 4165, 5651, 8326, 13073, 19500, 30033, 45159, 72884,
120403, 183341, 1269, 2201, 3116, 3024, 3188, 4165, 5651, 8326,
13073, 19500, 30033, 45159, 72884, 120403, 183341, 1194, 2221,
3697, 3175, 3088, 3549, 4841, 7275, 11253, 17624, 27190, 41844,
63503, 103716, 161527, 690, 1194, 1589, 1787, 1990, 2493, 3643,
6154, 9755, 16058, 26287, 39985, 63136, 100618, 156959, 480,
858, 1230, 1253, 1474, 2008, 2998, 5126, 9222, 15410, 25864,
41555, 65408, 105973, 164695, 403, 875, 1116, 1050, 1228, 1801,
2795, 4667, 8296, 14941, 24552, 39537, 63512, 99886, 159181,
407, 949, 1098, 997, 1184, 1764, 2822, 4766, 8098, 14240, 24412,
39332, 62544, 97792, 154476, 389, 959, 971, 919, 1096, 1616,
2812, 4771, 8088, 13666, 23118, 38657, 61478, 94831, 138973,
346, 875, 983, 876, 1048, 1524, 2670, 4786, 8018, 13204, 21570,
36232, 59169, 92488, 141812, 293, 868, 930, 875, 976, 1454, 2394,
4311, 7687, 12544, 20787, 33729, 55480, 89199, 137360)), .Names = c("year",
"age", "lung", "nasal", "other"), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35",
"36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46",
"47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57",
"58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68",
"69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90",
"91", "92", "93", "94", "95", "96", "97", "98", "99", "100",
"101", "102", "103", "104", "105", "106", "107", "108", "109",
"110", "111", "112", "113", "114", "115", "116", "117", "118",
"119", "120", "121", "122", "123", "124", "125", "126", "127",
"128", "129", "130", "131", "132", "133", "134", "135", "136",
"137", "138", "139", "140", "141", "142", "143", "144", "145",
"146", "147", "148", "149", "150")) |
NULL
ddwm = function(x, wshape = 1, wscale = 1, cmu = 1, ctau = 1,
sigmau = sqrt(wscale^2 * gamma(1 + 2/wshape) - (wscale * gamma(1 + 1/wshape))^2),
xi = 0, log = FALSE) {
check.quant(x, allowna = TRUE, allowinf = TRUE)
check.posparam(wshape, allowvec = TRUE)
check.posparam(wscale, allowvec = TRUE)
check.param(cmu, allowvec = TRUE)
check.posparam(ctau, allowvec = TRUE, allowzero = TRUE)
check.posparam(sigmau, allowvec = TRUE)
check.param(xi, allowvec = TRUE)
check.logic(log)
n = check.inputn(c(length(x), length(wshape), length(wscale),
length(cmu), length(ctau), length(sigmau), length(xi)), allowscalar = TRUE)
oneparam = (check.inputn(c(length(wshape), length(wscale),
length(cmu), length(ctau), length(sigmau), length(xi)), allowscalar = TRUE) == 1)
if (any(is.infinite(x))) warning("infinite quantiles set to NA")
x[is.infinite(x)] = NA
x = rep(x, length.out = n)
wshape = rep(wshape, length.out = n)
wscale = rep(wscale, length.out = n)
cmu = rep(cmu, length.out = n)
ctau = rep(ctau, length.out = n)
sigmau = rep(sigmau, length.out = n)
xi = rep(xi, length.out = n)
rx <- function(x, wshape, wscale, cmu, ctau, sigmau, xi) {
(dgpd(x, 0, sigmau, xi) - dweibull(x, wshape, wscale))*atan((x - cmu)/ctau)
}
d = x
whichnonmiss = which(!is.na(x))
if (oneparam) {
r = try(integrate(rx, wshape = wshape[1], wscale = wscale[1],
cmu = cmu[1], ctau = ctau[1], sigmau = sigmau[1], xi = xi[1],
lower = 0, upper = Inf, subdivisions = 10000, rel.tol = 1e-10, stop.on.error = FALSE)$value)
if (inherits(r, "try-error")) {
z = rep(NA, n)
} else {
z = rep(1 + r/pi, length.out = n)
}
} else {
z = rep(NA, n)
for (i in 1:n) {
r = try(integrate(r, wshape = wshape[i], wscale = wscale[i],
cmu = cmu[i], ctau = ctau[i], sigmau = sigmau[i], xi = xi[i],
lower = 0, upper = Inf, subdivisions = 10000, rel.tol = 1e-10, stop.on.error = FALSE)$value)
if (inherits(r, "try-error")) {
z[i] = NA
} else {
z[i] = 1 + r/pi
}
}
}
pweights = pcauchy(x[whichnonmiss], cmu[whichnonmiss], ctau[whichnonmiss])
d[whichnonmiss] = ((1 - pweights) * dweibull(x[whichnonmiss], wshape[whichnonmiss], wscale[whichnonmiss]) +
pweights * dgpd(x, 0, sigmau[whichnonmiss], xi[whichnonmiss]))/z[whichnonmiss]
if (log) d = log(d)
d
}
pdwm = function(q, wshape = 1, wscale = 1, cmu = 1, ctau = 1,
sigmau = sqrt(wscale^2 * gamma(1 + 2/wshape) - (wscale * gamma(1 + 1/wshape))^2),
xi = 0, lower.tail = TRUE) {
check.quant(q, allowna = TRUE, allowinf = TRUE)
check.posparam(wshape, allowvec = TRUE)
check.posparam(wscale, allowvec = TRUE)
check.param(cmu, allowvec = TRUE)
check.posparam(ctau, allowvec = TRUE, allowzero = TRUE)
check.posparam(sigmau, allowvec = TRUE)
check.param(xi, allowvec = TRUE)
check.logic(lower.tail)
n = check.inputn(c(length(q), length(wshape), length(wscale),
length(cmu), length(ctau), length(sigmau), length(xi)), allowscalar = TRUE)
oneparam = (check.inputn(c(length(wshape), length(wscale),
length(cmu), length(ctau), length(sigmau), length(xi)), allowscalar = TRUE) == 1)
if (any(is.infinite(q))) warning("infinite quantiles set to NA")
q[is.infinite(q)] = NA
q = rep(q, length.out = n)
wshape = rep(wshape, length.out = n)
wscale = rep(wscale, length.out = n)
cmu = rep(cmu, length.out = n)
ctau = rep(ctau, length.out = n)
sigmau = rep(sigmau, length.out = n)
xi = rep(xi, length.out = n)
rx <- function(x, wshape, wscale, cmu, ctau, sigmau, xi) {
(dgpd(x, 0, sigmau, xi) - dweibull(x, wshape, wscale))*atan((x - cmu)/ctau)
}
rxw <- function(x, wshape, wscale, cmu, ctau) {
(1 - pcauchy(x, cmu, ctau)) * dweibull(x, wshape, wscale)
}
rxg <- function(x, cmu, ctau, sigmau, xi){
pcauchy(x, cmu, ctau) * dgpd(x, 0, sigmau, xi)
}
p = q
whichnonmiss = which(!is.na(q))
z1 = z2 = z = rep(NA, n)
for (i in 1:n) {
if (oneparam & (i == 1)) {
r = try(integrate(rx, wshape = wshape[i], wscale = wscale[i],
cmu = cmu[i], ctau = ctau[i], sigmau = sigmau[i], xi = xi[i],
lower = 0, upper = Inf, subdivisions = 10000, rel.tol = 1e-10, stop.on.error = FALSE)$value)
if (inherits(r, "try-error")) {
z[i] = NA
} else {
z[i] = 1 + r/pi
}
} else if (oneparam & (i > 1)) {
z[i] = z[1]
} else {
r = try(integrate(rx, wshape = wshape[i], wscale = wscale[i],
cmu = cmu[i], ctau = ctau[i], sigmau = sigmau[i], xi = xi[i],
lower = 0, upper = Inf, subdivisions = 10000, rel.tol = 1e-10, stop.on.error = FALSE)$value)
if (inherits(r, "try-error")) {
z[i] = NA
} else {
z[i] = 1 + r/pi
}
}
r1 = try(integrate(rxw, wshape = wshape[i], wscale = wscale[i], cmu = cmu[i], ctau = ctau[i],
lower = 0, upper = q[i], subdivisions = 10000, rel.tol = 1e-10, stop.on.error = FALSE)$value)
if (inherits(r1, "try-error")) {
z1[i] = NA
} else {
z1[i] = r1
}
r2 = try(integrate(rxg, cmu = cmu[i], ctau = ctau[i], sigmau = sigmau[i], xi = xi[i],
lower = 0, upper = q[i], subdivisions = 10000, rel.tol = 1e-10, stop.on.error = FALSE)$value)
if (inherits(r2, "try-error")) {
z2[i] = NA
} else {
z2[i] = r2
}
}
p[whichnonmiss] = (z1[whichnonmiss] + z2[whichnonmiss])/z[whichnonmiss]
if (!lower.tail) p = 1 - p
p
}
qdwm = function(p, wshape = 1, wscale = 1, cmu = 1, ctau = 1,
sigmau = sqrt(wscale^2 * gamma(1 + 2/wshape) - (wscale * gamma(1 + 1/wshape))^2),
xi = 0, lower.tail = TRUE, qinit = NULL) {
check.prob(p, allowna = TRUE)
check.posparam(wshape, allowvec = TRUE)
check.posparam(wscale, allowvec = TRUE)
check.param(cmu, allowvec = TRUE)
check.posparam(ctau, allowvec = TRUE, allowzero = TRUE)
check.posparam(sigmau, allowvec = TRUE)
check.param(xi, allowvec = TRUE)
check.logic(lower.tail)
n = check.inputn(c(length(p), length(wshape), length(wscale),
length(cmu), length(ctau), length(sigmau), length(xi)), allowscalar = TRUE)
if (!lower.tail) p = 1 - p
check.posparam(qinit, allowvec = TRUE, allownull = TRUE, allowzero = TRUE)
if (is.null(qinit)) qinit = NA
qinit = rep(qinit, length.out = n)
p = rep(p, length.out = n)
wshape = rep(wshape, length.out = n)
wscale = rep(wscale, length.out = n)
cmu = rep(cmu, length.out = n)
ctau = rep(ctau, length.out = n)
sigmau = rep(sigmau, length.out = n)
xi = rep(xi, length.out = n)
pdmmmin = function(q, cprob, wshape, wscale, cmu, ctau, sigmau, xi) {
cdfmm = pdwm(q, wshape, wscale, cmu, ctau, sigmau, xi)
if (is.na(cdfmm)) {
qdiff = 1e6
} else {
qdiff = abs(cdfmm - cprob)
}
qdiff
}
findqdmm = function(cprob, wshape, wscale, cmu, ctau, sigmau, xi, qinit) {
if (is.na(qinit)) {
qwbl = qweibull(cprob, wshape, wscale)
qgp = qgpd(cprob, 0, sigmau, xi)
qinit = mean(c(qwbl, qgp))
}
gt = try(nlm(pdmmmin, qinit, cprob, wshape, wscale, cmu, ctau, sigmau, xi,
gradtol = 1e-10, steptol = 1e-10)$estimate)
if (inherits(gt, "try-error")) {
gt = try(nlm(pdmmmin, qgpd(cprob, 0, sigmau, xi), cprob, wshape, wscale, cmu, ctau, sigmau, xi,
gradtol = 1e-10, steptol = 1e-10)$estimate)
if (inherits(gt, "try-error")) {
gt = NA
}
}
return(gt)
}
q = rep(NA, n)
for (i in 1:n) {
q[i] = findqdmm(p[i], wshape[i], wscale[i], cmu[i], ctau[i], sigmau[i], xi[i], qinit[i])
}
q
}
rdwm = function(n = 1, wshape = 1, wscale = 1, cmu = 1, ctau = 1,
sigmau = sqrt(wscale^2 * gamma(1 + 2/wshape) - (wscale * gamma(1 + 1/wshape))^2), xi = 0) {
check.n(n)
check.posparam(wshape, allowvec = TRUE)
check.posparam(wscale, allowvec = TRUE)
check.param(cmu, allowvec = TRUE)
check.posparam(ctau, allowvec = TRUE, allowzero = TRUE)
check.posparam(sigmau, allowvec = TRUE)
check.param(xi, allowvec = TRUE)
check.inputn(c(n, length(wshape), length(wscale),
length(cmu), length(ctau), length(sigmau), length(xi)), allowscalar = TRUE)
if (any(xi == 1)) stop("shape cannot be 1")
wshape = rep(wshape, length.out = n)
wscale = rep(wscale, length.out = n)
cmu = rep(cmu, length.out = n)
ctau = rep(ctau, length.out = n)
sigmau = rep(sigmau, length.out = n)
xi = rep(xi, length.out = n)
r = rep(NA, n)
i = 1
while (i <= n) {
u = runif(1)
if (u < 0.5) {
rw = rweibull(1, wshape[i], wscale[i])
pw = pcauchy(rw, cmu[i], ctau[i])
v = runif(1)
if (v <= (1 - pw)) {
r[i] = rw
i = i + 1
}
} else {
rg = rgpd(1, 0, sigmau[i], xi[i])
pg = pcauchy(rg, cmu[i], ctau[i])
v = runif(1)
if (v <= pg){
r[i] = rg
i = i + 1
}
}
}
r
} |
sample_tidygraph <- function(
factor_model,
...,
poisson_edges = TRUE,
allow_self_loops = TRUE) {
ellipsis::check_dots_unnamed()
if (!(requireNamespace("tidygraph", quietly = TRUE))) {
stop(
"Must install `tidygraph` package to return graphs as `tidygraph` ",
"objects",
call. = FALSE
)
}
UseMethod("sample_tidygraph")
}
sample_tidygraph.undirected_factor_model <- function(
factor_model,
...,
poisson_edges = TRUE,
allow_self_loops = TRUE) {
edgelist <- sample_edgelist(
factor_model,
poisson_edges = poisson_edges,
allow_self_loops = allow_self_loops
)
tidygraph::as_tbl_graph(edgelist, directed = FALSE)
}
sample_tidygraph.directed_factor_model <- function(
factor_model,
...,
poisson_edges = TRUE,
allow_self_loops = TRUE) {
ig <- sample_igraph(
factor_model,
poisson_edges = poisson_edges,
allow_self_loops = allow_self_loops
)
tidygraph::as_tbl_graph(ig, directed = TRUE)
} |
PdPDB <- function(path, metal, n, perc, interactive, dropsReplicate){
path_to_commands = file.path(find.package("PdPDB"),"exec/")
if (dropsReplicate>2) dropsReplicate<-2
if (dropsReplicate<0) dropsReplicate<-0
path_to_out<-paste(paste("cd", path, sep=" "), ";", sep="")
print("
print(" PdPDB: Pattern discovery in PDB files")
print("
saveLogoText <- 1
verbose <- 0
if((interactive > 2)||(interactive<0))
interactive <- 2
debug<-interactive
if((debug==1)||(debug==2)){
print(paste("Interactive mode: ", debug))
reference<-as.data.frame(c(8.26,1.37,5.46,6.74,3.86,7.08,2.27,5.93,5.82,9.65,2.41,4.06,4.72,3.93,5.53,6.60,5.35,6.86,1.09,2.92))
colnames(reference)<-"referenceVec"
rownames(reference)<-c("A","C","D","E","F","G","H","I","K","L","M","N","P","Q","R","S","T","V","W","Y")
numberOfSamples<-554515
averageLength<-357
defineSeq<-1
defineDictionary<-0
}
if (file.exists(file.path(path,"patterns.csv"))){
print("")
print(paste("PdPDB has found a job to recover!!! ",file.path(path,"patterns.csv")))
print("If you want to start from scratch remove it and restart!")
print("WARNING: check n before to proceed. It must be compliant with previous run for PdPDB to work properly!!!")
print("")
recovery <-1
}
else {
recovery <-0
}
if((n>5)&&(perc<40)) {
print("For optimal results consider to increase Trim frequency or reduce n...")
print(" ")
}
if (verbose==1) { print("VERBOSE MODE ON...")}
noScripts <-0
if ((!file.exists(file.path(path_to_commands,"fileManager")))||(!file.exists(file.path(path_to_commands,"findPatterns")))){
print(file.path("Some of the core functions of PdPDB are missing, please check paths:", path_to_commands))
noScripts <-1
}
writeOnFS <- readline(paste(paste("Do you want PdPDB writes results in ", path, sep=" "), "? [1= Yes, 0=No] ", sep=" "))
if (dropsReplicate==2) print("PdPDB now keeps only unique entries...")
if (dropsReplicate==1) print("PdPDB now drops replicated patterns in PDB entries...")
if (dropsReplicate==0) print("PdPDB now keeps replicated patterns...")
if (!(is.na(as.numeric(writeOnFS)==0))&&(as.numeric(writeOnFS)==0)){
print("PdPDB ABORTED!!!")
noScripts <-1
}
if (noScripts==0){
command1=paste(path_to_out, (paste(path_to_commands, "fileManager", sep="")))
system(command1)
if (verbose==1){
print(command1)
}
filesFound <-TRUE
if (recovery==0){
print("PdPDB runs from scratch!")
pdbNames<-list.files(path = path,pattern = "\\.pdb$")
cifNames<-list.files(path = path,pattern = "\\.cif$")
filesFound <-FALSE
if((length(pdbNames)>0)||(length(cifNames)>0)) {
if((length(pdbNames))>(length(cifNames))){
print("PDB entries correctly located")
command2=paste(path_to_out, paste(path_to_commands, paste("findPatterns",paste(metal,n,sep=" "),sep=" "), sep=""), sep=" ")
}
else{
print("CIF entries correctly located")
command2=paste(path_to_out, paste(path_to_commands, paste("findPatternsX",paste(metal,n,sep=" "),sep=" "), sep=""), sep=" ")
}
if (verbose == 1){ print(command2) }
system(command2)
filesFound <-TRUE
}
else{
print("Invalid PATH! No PDB entries in this directory!")
}
}
if (isTRUE(filesFound)){
print ("Patterns analysis START!!!!")
if (file.exists(file.path(path,"patterns.csv"))){
datFileSize<-file.info(file.path(path,"patterns.csv"))$size
if(datFileSize>10){
if (mean(count.fields(file.path(path,"patterns.csv"))) > 1 ){
block <- read.csv (file.path(path,"patterns.csv"), header=FALSE, sep=" ", dec=".", stringsAsFactors = FALSE)
if (dropsReplicate!=1) {
patterns<- arrangePatterns(block, n)
if (dropsReplicate==2) {
print("---> Drop option 2 <---")
patterns<-patterns[!duplicated(patterns),]
}
}
else {
print("---> Drop option 1 <---")
print("Please be patient this option takes time...")
sbsp<-grep("pdb",block[,1])
patterns<-subPatternsExtract(block, sbsp, n, verbose)
}
defineDictionary<-0
if(debug==0)
defineDictionary<-as.integer(readline("Type in the number of additional symbols to be used: [ 0 = no symbols ] "))
if((defineDictionary>=1)&&(!is.na(defineDictionary>=1))){
dictionary<-defineADictionary(defineDictionary)
}
else{
dictionary<-NA
}
fastaPatternsAligned<- alignLigands(toFasta(patterns, dictionary, verbose), n, verbose)
print("Calculating frequencies...")
df<-as.data.frame(count(patterns))
df.new <- df[with(df, order(df$freq, decreasing = TRUE)), ]
numberOfPDB<-sum(df.new$freq)
df.new<-as.data.frame(cbind(df.new, df.new$freq/numberOfPDB*100))
names(df.new)[length(names(df.new))]<-"freq_%"
write.table(df.new, file = file.path(path,"frequencies.csv"),row.names=FALSE, na="", sep=" ", quote = FALSE)
fastaPatterns <-checkChains(fastaPatternsAligned, which(colnames(fastaPatternsAligned)=="L"), dictionary, verbose)
percAbs<-abs(perc)
trimmed<-trimAlignment(fastaPatterns, percAbs, colnames(fastaPatterns), verbose)
lastCol<-length(trimmed[1,])
for(i in 1:length(trimmed[,1])){
lastLigand<-(max(which(substr(trimmed[i,],1,1)=="("))+1)
if(is.finite(lastLigand)){
if(lastLigand<lastCol)
trimmed[i, lastLigand:lastCol]<-moveCharLeft(trimmed[i, lastLigand:lastCol],verbose)
}
else print(paste("WARNING at line of the alignment!!! ", i))
}
write.table(trimmed, file = file.path(path,"alignment.csv"),row.names=FALSE, na="", sep=" ", quote = FALSE)
df.clusters<-clustering(trimmed, path, "dendrogram.svg", debug)
df.clusters.new<-df.clusters[order(df.clusters$points, decreasing = FALSE), ]
numberOfClusters <- max(df.clusters.new$points)
print(paste("This action results in", numberOfClusters,"clusters!", sep=" "))
for(i in 1:numberOfClusters){
cluster<-subset(df.clusters.new, points==i)
df.cluster<-(as.data.frame(matrix(unlist(lapply(gsub("\\(|\\)","",cluster$seq), function(x) strsplit(x, split = ""))), nrow=length(cluster[,1]), byrow = TRUE)))
maxFreqSeq<-maxFreq(df.cluster, colnames(trimmed), verbose)
colnames(df.cluster)<-colnames(trimmed)
makeTheLogo(df.cluster, colnames(df.cluster), maxFreqSeq, dictionary, path,paste("logo_",i,".svg",sep=""))
if(saveLogoText==1){
if(verbose==1) print("PdPDB is going to save logos in text format")
df.logo<-as.data.frame(count(df.cluster))
df.logo.new <- df.logo[with(df.logo, order(df.logo$freq, decreasing = TRUE)), ]
numberOfPDB<-sum(df.logo.new$freq)
df.logo.new<-as.data.frame(cbind(df.logo.new, df.logo.new$freq/numberOfPDB*100))
names(df.logo.new)<-c(names(df.cluster),"freq","freq_%")
write.csv(as.data.frame(df.logo.new), file = file.path(path,paste("logo_",i,".csv",sep="")),row.names=FALSE, col.names=colnames(trimmed), na="", sep=" ", quote = FALSE)
}
}
if(debug==0)
defineSeq<-as.numeric(readline("Do you want to define a reference sequence for enrichment analysis? [ Yes = 1 ] "))
if((defineSeq==1)&&(!is.na(defineSeq==1))){
print("This will save a CSV file containing standardized distribution and Chi-squared p values")
if(debug==0){
averageLength <- as.numeric(readline("Type in the average sequence length of the reference: "))
numberOfSamplesP <- as.numeric(readline("PROTEINS: How many samples have been used to define this reference? "))
if((numberOfSamplesP>0)&&(!is.na(numberOfSamplesP))) {
reference<-defineSeqRef(1,0)
numberOfSamples<-numberOfSamplesP
}
else{
reference<-defineSeqRef(1,0)
numberOfSamples<-0
print("
}
}
enrichmentAnalysis(trimmed, numberOfPDB, reference, numberOfSamples, averageLength, path, "root", verbose)
ligands<-trimmed[which(colnames(trimmed) %in% "L")]
enrichmentAnalysis(ligands, numberOfPDB, reference, numberOfSamples, averageLength, path, "ligands", verbose)
notligands<-trimmed[which(colnames(trimmed) %in% "x")]
enrichmentAnalysis(notligands, numberOfPDB, reference, numberOfSamples, averageLength, path, "notLigands", verbose)
colnumbersP<-NA
colnumbersF<-NA
for(i in 1:n){
colnumbersP<-(which((substr(colnames(trimmed),1,1)) %in% "L"))-i
colnumbersP.filt<-colnumbersP[which(colnumbersP %in% 1:length(trimmed[1,]))]
preceed.old<-trimmed[colnumbersP.filt]
preceed<-preceed.old[substr(colnames(preceed.old),1,1) != "L"]
enrichmentAnalysis(preceed, numberOfPDB, reference, numberOfSamples, averageLength, path, paste("preceeding",i,sep="_"), verbose)
colnumbersF<-(which((substr(colnames(trimmed),1,1)) %in% "L"))+i
colnumbersF.filt<-colnumbersF[which(colnumbersF %in% 1:length(trimmed[1,]))]
follow.old<-trimmed[colnumbersF.filt]
follow<-follow.old[substr(colnames(follow.old),1,1) != "L"]
enrichmentAnalysis(follow, numberOfPDB, reference, numberOfSamples, averageLength, path, paste("following",i,sep="_"), verbose)
}
}
}
else print("PdPDB is not able to get suitable PATTERNS... check PdPDB.log file!")
}
else print("Empty patterns.csv file!")
}
else print ("Missing patterns.csv: No file to recovery!")
}
else {print ("Patterns won't be analyzed!!!")}
}
system(paste("rm -f ", path,"*.tmp", sep = ""))
system(paste("echo 'Alignment has been trimmed to ", perc,"%' >> ",path,"PdPDB.log", sep = ""))
system(paste("echo 'Drop option was ", dropsReplicate,"!' >> ",path,"PdPDB.log", sep = ""))
if(recovery==1) {
system(paste("echo 'You recovered an old job' >> ",path,"PdPDB.log", sep = ""))
system(paste("echo 'n is now tuned to ", n,"' >> ",path,"PdPDB.log", sep = ""))
}
print(" ")
print("---------------------------------------------------------- ")
print(paste("Logos and output files (.csv, .svg, .log) are in ",path,sep=" "))
print("---------------------------------------------------------- ")
print(" ")
print("Legend for 'frequencies.csv' file: () = ligand, - = conect residues interleaved by of more than a position in the same chain, ... = conect residues from different chains")
print("Legend for logos and 'alignment.csv' file: * = gap introduced by ligands alignment")
print(" ")
print("
system(paste("echo ' ' >> ",path,"PdPDB.log", sep = ""))
system(paste("echo 'PdPDB exited gracefully...!!!' >> ",path,"PdPDB.log", sep = ""))
print(" PdPDB exited gracefully...!!!")
print("
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.