code
stringlengths 1
13.8M
|
---|
teamBowlersVsBatsmenAllOppnAllMatchesPlot <- function(bowlerDF,t1,t2,plot=1){
batsman=runsConceded=team=NULL
ggplotly=NULL
bwlr <- bowlerDF$bowler
if(t2 != "India"){
plot.title <- paste(bwlr,"-Performance against",t2,"batsmen")
print("aa")
}else{
plot.title <- paste(bwlr,"-Performance against all batsmen")
}
if(plot == 1){
ggplot(data=bowlerDF,aes(x=batsman,y=runsConceded,fill=factor(batsman))) +
facet_grid(. ~ bowler) + geom_bar(stat="identity") +
xlab("Batsman") + ylab("Runs conceded") +
ggtitle(bquote(atop(.(plot.title),
atop(italic("Data source:http://cricsheet.org/"),"")))) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
} else if(plot == 2){
g <- ggplot(data=bowlerDF,aes(x=batsman,y=runsConceded,fill=factor(batsman))) +
facet_grid(. ~ bowler) + geom_bar(stat="identity") +
xlab("Batsman") + ylab("Runs conceded") +
ggtitle(plot.title) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
ggplotly(g,height=500)
}
} |
.ctmfit <- function(object, parm, mltargs, reparm,
min_update = length(coef(object)) * 2) {
ctmobject <- object
function(data, weights, control, ...) {
mf <- model.frame(data, yxonly = TRUE)
iy <- data[["yx", type = "index"]]
mltargs$data <- mf
ctmobject <- do.call("mlt", mltargs)
thetastart <- coef(ctmobject, fixed = FALSE)
function(subset = NULL, weights = NULL, info = NULL, model = FALSE,
estfun = TRUE, object = FALSE) {
if (model) return(list(object = ctmobject, iy = iy))
if (!is.null(iy)) {
w <- libcoin::ctabs(iy, weights = weights, subset = subset)[-1L]
subset <- NULL
} else {
if (is.null(weights) || length(weights) == 0) {
w <- rep(1, nrow(mf))
} else {
w <- weights
}
w[-subset] <- 0
}
if (!is.null(info$coef)) {
thetastart <- info$coef
} else {
thetastart <- coef(ctmobject, fixed = FALSE)
}
nw <- if (is.null(subset)) sum(w) else sum(w[subset])
if (nw > min_update) {
umod <- suppressWarnings(try(update(ctmobject, weights = w,
subset = subset, theta = thetastart), silent = TRUE))
if (inherits(umod, "try-error") || umod$convergence != 0) {
umod <- suppressWarnings(try(update(ctmobject, weights = w, subset = subset),
silent = TRUE))
if (inherits(umod, "try-error") || umod$convergence != 0) {
mltargs$weights <- w
umod <- try(do.call("mlt", mltargs))
}
}
} else {
umod <- 0
class(umod) <- "try-error"
}
if (inherits(umod, "try-error")) {
if (!estfun)
return(list(coef = thetastart, objfun = NA,
converged = FALSE))
umod <- ctmobject
umod$weights <- w
umod$subset <- subset
coef(umod)[names(thetastart)] <- thetastart
umod$convergence <- 0L
}
ret <- NULL
if (estfun) {
ret <- estfun(umod, parm = coef(umod, fixed = TRUE))[, parm, drop = FALSE]
if (!is.null(subset)) {
if (NROW(ret) == length(subset)) {
tmp <- matrix(0, nrow = length(w),
ncol = ncol(ret))
tmp[subset,] <- ret
ret <- tmp
} else {
ret[-subset,] <- 0
}
}
if (!is.null(iy)) ret <- rbind(0, ret)
if (!is.null(reparm)) ret <- ret %*% reparm
}
return(list(estfun = ret,
coefficients = coef(umod, fixed = FALSE),
objfun = -logLik(umod),
object = if (object) umod else NULL,
converged = isTRUE(all.equal(umod$convergence, 0))))
}
}
}
trafotree <- function(object, parm = 1:length(coef(object)), reparm = NULL,
min_update = length(coef(object)) * 2,
mltargs = list(), ...) {
if (inherits(object, "mlt")) {
if (is.null(mltargs$scale))
mltargs$scale <- object$scale
object <- object$model
}
mltargs$model <- object
args <- list(...)
args$ytrafo <- .ctmfit(object = object, parm = parm,
mltargs = mltargs, reparm = reparm,
min_update = min_update)
args$update <- TRUE
ret <- do.call("ctree", args)
ret$model <- object
ret$mltobj <- ret$trafo(model = TRUE, estfun = FALSE)
ret$mltargs <- mltargs
weights <- data_party(ret)[["(weights)"]]
if (is.null(weights)) weights <- rep(1, nrow(data_party(ret)))
nd <- predict(ret, type = "node")
ret$models <- tapply(1:length(nd), factor(nd), function(i)
ret$trafo(i, weights = weights, estfun = FALSE))
ret$coef <- do.call("rbind", lapply(ret$models, function(x) x$coef))
ret$logLik <- sapply(ret$models, function(x) -x$objfun)
class(ret) <- c("trafotree", class(ret))
ret
}
traforest <- function(object, parm = 1:length(coef(object)), reparm = NULL,
update = TRUE, min_update = length(coef(object)) * 2,
mltargs = list(), ...) {
if (inherits(object, "mlt")) object <- object$model
mltargs$model <- object
args <- list(...)
args$ytrafo <- .ctmfit(object = object, parm = parm,
mltargs = mltargs, reparm = reparm,
min_update = min_update)
args$update <- update
ret <- do.call("cforest", args)
ret$model <- object
ret$mltargs <- mltargs
ret$mltobj <- ret$trafo(model = TRUE, estfun = FALSE, object = TRUE)
class(ret) <- c("traforest", class(ret))
ret
} |
`CONVERTSDR` <-
function(strike, dip, rake)
{
DEG2RAD = pi/180;
RAD2DEG = 180/pi;
dipdir = strike + 90.;
signforp = 1;
phif = RPMG::fmod(dipdir, 360.);
deltaf = dip;
if (rake > 90.0) {
tmprake = rake - 180.;
signforp = -1.;
} else if (rake < -90.0) {
tmprake = rake + 180.;
signforp = -1.;
} else {
tmprake = rake;
signforp = 1.;
}
temp1 = tmprake * DEG2RAD;
temp2 = dip * DEG2RAD;
deltau = asin(-1*sin(temp1) * sin(temp2) );
tandy = tan(deltau) / tan(temp2)
if(is.nan(tandy) ) tandy= 1
if( tandy<(-1) ) tandy= (-1)
if( tandy>(1) ) tandy= (1)
phiu = dipdir - 90. + asin( tandy) *RAD2DEG;
deltau = deltau*RAD2DEG;
phiu = RPMG::fmod(phiu+360., 360.);
deltag = 90 - deltau;
if (deltag < 0.) {
phig = phiu;
deltag = -deltag;
} else if (deltag > 90.) {
phig = phiu;
deltag = 180. - deltag;
} else {
phig = phiu + 180.;
}
if(deltaf==90 & rake==90)
{
phig = 180 - phif
}
phig = RPMG::fmod(phig, 360.);
deltav = 90 - deltaf;
phiv = RPMG::fmod(phif + 180, 360.);
U = TOCART.DIP(phiu, deltau);
V = TOCART.DIP(phiv, deltav);
V$x = signforp*V$x ; V$y = signforp*V$y; V$z = signforp*V$z;
P = to.spherical( U$x+V$x, U$y+V$y, U$z+V$z)
P$az = RPMG::fmod(P$az+ 360. , 360);
P = REFLECT(P);
x2 = -V$x;
y2 = -V$y;
z2 = -V$z;
T = to.spherical( U$x+x2, U$y+y2, U$z+z2 );
T$az = RPMG::fmod( T$az , 360.);
T = REFLECT(T);
U = REFLECT(U);
V = REFLECT(V);
F = TOCART.DIP(phif, deltaf);
G = TOCART.DIP(phig, deltag);
M =list( az1=0, d1=0, az2=0, d2=0, uaz=0, ud=0, vaz=0, vd=0, paz=0, pd =0, taz=0, td=0)
M$az1=F$az; M$d1=F$dip;
M$az2=G$az; M$d2=G$dip ;
M$uaz=U$az; M$ud=U$dip;
M$vaz=V$az; M$vd=V$dip;
M$paz=P$az; M$pd=P$dip;
M$taz=T$az; M$td=T$dip ;
mc = structure( list(strike=strike, dipdir=dipdir, dip=dip, rake=rake, F=F, G=G, U=U, V=V, P=P, T=T, M=M), class="MEC" )
return(mc);
} |
context("object validation")
source(testthat::test_path("validate_helper.R"))
expect_validate_err <- function(schema, ..., txt = schema) {
schema %>%
gqlr:::ObjectHelpers$new(source = txt) ->
oh
validate_schema(oh = oh)
testthat::expect_true(oh$error_list$has_any_errors())
expect_error({
stop(format(oh$error_list))
},
...
)
}
test_that("validate schema", {
oh <- ObjectHelpers$new(dog_cat_schema)
validate_schema(oh = oh)
expect_true(oh$error_list$has_no_errors())
"
interface BarretInterface {
A: String
A: String
}
" %>%
expect_validate_err("3.1.3.1")
"
type Barret {
__A: String
}
" %>%
expect_validate_err("'__'")
"interface BarretInterface {
A: String
B: String
}
type Barret implements BarretInterface {
A: String
C: Float
}
" %>%
expect_validate_err("must implement all fields of interface")
"
interface BarretInterface {
A(arg1: Int): String
}
type Barret implements BarretInterface {
A(arg2: Int): String
}
" %>%
expect_validate_err("must have at least the same argument names")
"
interface BarretInterface {
A(arg1: Int): String
}
type Barret implements BarretInterface {
A(arg1: Int, arg2: Float!): String
}
" %>%
expect_validate_err("all additional arguments")
"
interface BarretInterface {
A(arg1: Int): String
}
type Barret implements BarretInterface {
A(arg1: Float): String
}
" %>%
expect_validate_err("must input the same type")
"
scalar MyScalar
type MyObject {
fieldA: Int
}
union MyUnion = MyObject | MyScalar
schema {
query: MyObject
}
" %>%
expect_validate_err("may not be member types of a Union")
"
type MyObject {
fieldA: Int
}
schema {
query: MyObject
}
" -> schema_txt
schema <- gqlr_schema(schema_txt)
my_obj <- schema$get_object("MyObject")
my_obj$fields <- list()
schema %>%
expect_validate_err(txt = schema_txt, "must have at least one field")
}) |
check_handler <-
function(x){
if(!("neptune.new.handler.Handler" %in% class(x)))
stop("x must be a neptune Handler")
} |
blm <- function(formula,data,na.action=na.omit,
weights=NULL,strata=NULL,par.init=NULL,warn=FALSE,...){
na.lexpit <- function(f,data,FUN){
keep.data <- subset(data,select=all.vars(f))
keep.data <- FUN(keep.data)
kept <- match(row.names(keep.data),row.names(data))
list(data = keep.data, kept = kept)
}
LL <- function(Y,p,w){
l <- w*(Y*logit(p)+log(1-p))
-sum(l)
}
warn.option <- getOption("warn")
if(!warn) options("warn"=-1)
data <- na.lexpit(formula,data,FUN=na.action)
which.kept <- data$kept
data <- data$data
Y <- model.frame(formula,data)[,1]
X <- model.matrix(formula,data)
if(is.matrix(X)){
x.labels <- colnames(X)
}
else{
x.labels <- attr(terms(formula), "term.labels")
}
if(is.null(strata)){
strata <- rep(1,nrow(data))
}
else{
strata <- strata[which.kept]
}
if(!class(strata)=="factor") strata <- factor(strata)
if(is.null(weights)){
weights <- rep(1,nrow(X))
}
else{
weights <- weights[which.kept]
}
w <- cbind(weights/mean(weights))
if(is.null(par.init)){
beta.init <- rep(0,ncol(X))
beta.init[1] <- sum(Y*w)/sum(w)
}
else{
beta.init <- par.init
}
fit <- blm.optim(Y,X,w,beta.init,...)
beta <- fit$par
if(!all(weights==1)){
if(nrow(data)>50000)
vcov <- vcov.blm.big(formula, data, weights, beta)
else
vcov <- vcov.influence.blm.strata(formula, data, weights, strata, beta)
}
else{
if(nrow(data)>50000)
vcov <- vcov.blm.big(formula, data, weights=NULL, beta)
else
vcov <- vcov.influence.blm(formula, data, beta)
}
names(beta) <- x.labels
ll.null <- -LL(Y,sum(Y*w)/sum(w),cbind(weights))
options("warn"=warn.option)
new("blm",
coef = beta,
vcov = vcov,
formula= formula,
df.residual = nrow(X)-ncol(X),
data = data,
which.kept = which.kept,
y = Y,
weights = as.numeric(weights),
strata = strata,
converged = fit$convergence==0,
par.init = beta.init,
loglik = -LL(Y,X%*%beta,cbind(weights)),
loglik.null = ll.null,
barrier.value = fit$barrier.value
)
} |
test_that("lookup_coords returns coords data", {
kcmo <- lookup_coords("kansas city, mo")
expect_gt(cor(kcmo$point, c(39.0997, 94.5786)), 0.9)
tor <- lookup_coords("toronto canada")
expect_gt(cor(tor$point, c(43.6532, 79.3832)), 0.9)
x <- lookup_coords("usa")
expect_equal(is.list(x), TRUE)
expect_named(x)
expect_true("box" %in% names(x))
x <- lookup_coords("world")
expect_equal(is.list(x), TRUE)
expect_named(x)
expect_true("box" %in% names(x))
gmk <- Sys.getenv("GOOGLE_MAPS_KEY")
if (!is.null(gmk) && !identical(gmk, "")) {
x <- lookup_coords("New York, NY")
expect_equal(is.list(x), TRUE)
expect_named(x)
expect_true("box" %in% names(x))
}
Sys.setenv(GOOGLE_KEY = gmk)
Sys.setenv(GOOGLE_MAPS_KEY = "")
if (!is.null(gmk) && !identical(gmk, "")) {
x <- lookup_coords("New York, NY")
expect_equal(is.list(x), TRUE)
expect_named(x)
expect_true("box" %in% names(x))
}
e <- names(Sys.getenv())
g <- grep("google|gmap", e, ignore.case = TRUE, value = TRUE)
if (length(g) > 0) {
ng <- as.list(rep("", length(g)))
names(ng) <- g
do.call(Sys.setenv, ng)
}
expect_error(lookup_coords("London, UK"))
}) |
context("discrete, with delays")
test_that("fib", {
fib <- function(i, y, p) {
y + yprev(i - 1L)
}
y0 <- 1
i <- 0:10
res <- difeq(y0, i, fib, NULL, n_history = 2, return_step = FALSE)
expect_equal(res[1:11], c(1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144))
h <- attr(res, "history")
expect_equal(attr(h, "n"), 1L)
expect_equal(dim(h), c(2, 2))
res2 <- difeq(y0, i, fib, NULL, return_step = FALSE, n_history = 20)
h2 <- attr(res2, "history")
expect_equal(dim(h2), c(2, 11))
expect_equal(h2[, 10:11], h, check.attributes = FALSE)
})
test_that("prev and output", {
growth <- function(i, y, p) {
ret <- y + p
attr(ret, "output") <- yprev(i - 1L)
ret
}
n <- 5
y0 <- runif(n)
p <- runif(n)
i <- 0:10
i2 <- seq(0, 10, by = 2)
cmp <- t(y0 + outer(p, i))
cmp2 <- t(y0 + outer(p, i2))
res <- difeq(y0, i, growth, p, return_step = FALSE, n_out = 5,
n_history = 2L, return_output_with_y = FALSE)
expect_equal(res, cmp, check.attributes = FALSE)
output <- attr(res, "output")
expect_equal(output, rbind(y0, cmp[-nrow(cmp), ], deparse.level = 0))
res2 <- difeq(y0, i2, growth, p, return_step = FALSE, n_out = 5,
n_history = 2L, return_output_with_y = FALSE)
expect_equal(res2, cmp2, check.attributes = FALSE)
output2 <- attr(res2, "output")
expect_equal(output2, output[i2 + 1, ])
})
test_that("yprev permutations", {
rhs <- function(i, y, p) {
iprev <- i - 1
if (p == "one") {
for (i in seq_along(y)) {
y[i] <- y[i] + yprev(iprev, i)
}
} else if (p == "idx") {
y <- y + yprev(iprev, seq_along(y))
} else {
y <- y + yprev(iprev)
}
y
}
i <- seq(0:10)
y0 <- runif(5)
res1 <- difeq(y0, i, rhs, "one", return_initial = TRUE, n_history = 2L)
res2 <- difeq(y0, i, rhs, "idx", return_initial = TRUE, n_history = 2L)
res3 <- difeq(y0, i, rhs, "all", return_initial = TRUE, n_history = 2L)
cmp <- matrix(y0, length(i), length(y0), byrow = TRUE)
for (j in 2:length(i)) {
cmp[j, ] <- cmp[j - 1, ] + cmp[max(1, j - 2), ]
}
expect_equal(res1[, -1], cmp, check.attributes = FALSE)
expect_equal(res2, res1)
expect_equal(res3, res1)
})
test_that("yprev invalid input", {
rhs <- function(i, y, p) {
type <- p$type
lag <- p$lag
idx <- p$idx
iprev <- if (is.numeric(lag)) i - lag else lag
if (type == "one") {
for (i in seq_along(idx)) {
j <- idx[[i]]
yp <- yprev(iprev, j)
y[j] <- y[j] + yp
}
} else if (type == "idx") {
yp <- yprev(iprev, idx)
y[idx] <- y[idx] + yp
} else {
y <- y + yprev(iprev)
}
y
}
i <- seq(0:10)
y0 <- runif(5)
cmp <- matrix(y0, length(y0), length(i))
for (j in 2:length(i)) {
cmp[, j] <- cmp[, j - 1] + cmp[, max(1, j - 2)]
}
cmp <- t(cmp)
p <- list(lag = 1.0, idx = as.numeric(seq_along(y0)), type = "one")
res1 <- difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE)
expect_equal(res1[, -1], cmp, check.attributes = FALSE)
p <- list(lag = 1.0, idx = as.numeric(seq_along(y0)), type = "idx")
res1 <- difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE)
expect_equal(res1[, -1], cmp, check.attributes = FALSE)
p <- list(lag = 1.0, idx = as.numeric(seq_along(y0) + 1), type = "one")
expect_error(difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE),
"out of bounds")
p <- list(lag = 1.0, idx = as.integer(seq_along(y0) + 1L), type = "one")
expect_error(difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE),
"out of bounds")
p <- list(lag = 1.0, idx = "one", type = "one")
expect_error(difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE),
"Invalid type")
p <- list(lag = 1.0, idx = c("one", "two"), type = "idx")
expect_error(difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE),
"Invalid type")
p <- list(lag = - 1.0, type = "one", idx = 1L)
expect_error(difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE),
"did not find step")
p <- list(lag = - 1.0, type = "idx", idx = 1L)
expect_error(difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE),
"did not find step")
p <- list(lag = - 1.0, type = "all")
expect_error(difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE),
"did not find step")
p <- list(lag = NULL, type = "all")
expect_error(difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE),
"Expected a scalar")
p <- list(lag = c(1L, 2L), type = "all")
expect_error(difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE),
"Expected a scalar")
p <- list(lag = "one", type = "all")
expect_error(difeq(y0, i, rhs, p, n_history = 2L, return_initial = TRUE),
"Expected an integer")
})
test_that("integer lag", {
growth <- function(i, y, p) {
y + yprev(i - 1L)
}
i <- seq(0:10)
y0 <- runif(5)
p <- numeric(0)
cmp <- matrix(y0, length(y0), length(i))
for (j in 2:length(i)) {
cmp[, j] <- cmp[, j - 1] + cmp[, max(1, j - 2)]
}
cmp <- t(cmp)
res <- difeq(y0, i, growth, p, n_history = 2L,
return_history = FALSE, return_step = FALSE)
expect_equal(res, cmp)
res <- difeq(y0, i, "growth", p, n_history = 2L, dllname = "dde_growth_int",
return_history = FALSE, return_step = FALSE)
expect_equal(res, cmp)
})
test_that("restart", {
growth <- function(i, y, p) {
ret <- y + p
attr(ret, "output") <- yprev(i - 5L)
ret
}
n <- 5L
y0 <- runif(n)
p <- runif(n)
tt <- 0:50
tc <- 20
tt1 <- tt[tt <= tc]
tt2 <- tt[tt >= tc]
cmp <- y0 + outer(p, tt)
res <- difeq(y0, tt, growth, p, n_out = n, n_history = 100L,
restartable = FALSE)
h <- attr(res, "history")
expect_null(attr(res, "ptr"))
expect_null(attr(res, "restart_data"))
res1 <- difeq(y0, tt1, growth, p, n_out = n, n_history = 100L,
restartable = TRUE)
expect_is(attr(res1, "ptr"), "externalptr")
expect_is(attr(res1, "restart_data"), "list")
res2 <- difeq_continue(res1, tt2, copy = FALSE)
h2 <- attr(res2, "history")
expect_equal(h2, h)
expect_equal(res2[1, ], res1[nrow(res1), ])
expect_equal(res, rbind(res1, res2[-1, ]), check.attributes = FALSE)
})
test_that("change y on restart", {
growth <- function(i, y, p) {
ret <- y + p
attr(ret, "output") <- yprev(i - 5L)
ret
}
n <- 5L
y0 <- runif(n)
p <- runif(n)
tt <- 0:50
tc <- 20
it2 <- tt >= tc
tt1 <- tt[tt <= tc]
tt2 <- tt[it2]
i <- seq_len(n) + 1L
j <- i + n
res <- difeq(y0, tt, growth, p, n_out = n, n_history = 100L,
restartable = FALSE)
h <- attr(res, "history")
res1 <- difeq(y0, tt1, growth, p, n_out = n, n_history = 100L,
restartable = TRUE)
y1 <- res1[nrow(res1), i] + 1
res2 <- difeq_continue(res1, tt2, y1, copy = FALSE)
h2 <- attr(res2, "history")
expect_equal(res2[, 1], res[it2, 1])
expect_equal(res2[, i], res[it2, i] + 1)
expect_equal(res[-(1:5), j],
res[seq_len(nrow(res) - 5), i])
}) |
context("test ar_tessellate function")
data(ar_stl_wards, package = "areal")
unproj <- sf::st_transform(ar_stl_wards, 4326)
nonsf <- ar_stl_wards
sf::st_geometry(nonsf) <- NULL
out <- ar_tessellate(ar_stl_wards)
test_that("errors with missing or non-sf data", {
expect_error(ar_tessellate(), "An sf object must be specified for `.data`")
expect_error(ar_tessellate(nonsf),"An sf object must be specified for `.data`")
})
test_that("errors for invalid shape", {
expect_error(ar_tessellate(ar_stl_wards, shape = "ham"), "The shape argument must be one of 'square' or 'hexagon'")
})
test_that("errors for unprojected data", {
expect_error(ar_tessellate(unproj), "Data must be projected in order to tessellate")
})
test_that("outputs object of class sf", {
expect_s3_class(out, "sf")
}) |
predictdep <- function (knownvalues, dependence, smoothing = c("Uniform", "Beta"),nthreads=2)
{
smoothing <- match.arg(smoothing)
NbKnownObs = dim(knownvalues)[1]
SubSampSize = dim(dependence$cop)[1]
knownvars = intersect(names(knownvalues), dependence$varnames)
if (length(knownvars) == length(dependence$varnames))
return(knownvalues)
knownvalues = knownvalues[knownvars]
NbKnownDims = length(knownvars)
rankknownvalues = knownvalues
UnknwonVars = setdiff(dependence$varnames, knownvars)
NbUnknwonDims = length(UnknwonVars)
knowndims = match(knownvars, dependence$varnames)
UnknwonDims = match(UnknwonVars, dependence$varnames)
rankpredicted = numeric(NbUnknwonDims * NbKnownObs)
for (var in knownvars) {
numvar=pmatch(var,dependence$varnames)
rankknownvalues[var] = dependence$FdR[[numvar]](unlist(knownvalues[var]))
}
rankknownvalues = as.numeric(t(as.matrix(rankknownvalues)))
epsilon=1/(10*NbKnownObs)
rankknownvalues=pmax(0,pmin(1-epsilon,rankknownvalues))
if (smoothing == "Uniform") {
rankknownvalues = floor(rankknownvalues * SubSampSize)
}
else {
rankknownvalues = rbinom(length(rankknownvalues), SubSampSize -
1, rankknownvalues)
}
US = runif(NbKnownObs)
rankpredicted = .Call("InterTir", as.integer(NbKnownObs),
as.integer(NbKnownDims), as.integer(NbUnknwonDims), as.integer(SubSampSize),
as.double(US), as.double(dependence$cop), as.integer(rankknownvalues),
as.integer(knowndims - 1), as.integer(UnknwonDims - 1), as.integer(nthreads)) +
1
if (smoothing == "Uniform") {
rankpredicted = (rankpredicted + runif(NbKnownObs * NbUnknwonDims) -
1)/SubSampSize
}
else {
rankpredicted = rbeta(NbKnownObs * NbUnknwonDims, rankpredicted,
SubSampSize + 1 - rankpredicted)
}
rankpredicted = as.data.frame(matrix(data = rankpredicted,
ncol = NbUnknwonDims, nrow = NbKnownObs, byrow = TRUE))
names(rankpredicted) = UnknwonVars
PredictedValues = rankpredicted
for (var in UnknwonVars) {
numvar=pmatch(var,dependence$varnames)
PredictedValues[var] = dependence$FdRinv[[numvar]](unlist(rankpredicted[var]))
}
pred = cbind(knownvalues, PredictedValues)
return(pred)
} |
test_that("missing values in input are missing in output", {
dt <- lazy_dt(tibble(x = c(NA, "a b")), "DT")
step <- separate(dt, x, c("x", "y"))
out <- collect(step)
expect_equal(
show_query(step),
expr(copy(DT)[, `:=`(!!c("x", "y"), tstrsplit(x, split = "[^[:alnum:]]+"))])
)
expect_equal(out$x, c(NA, "a"))
expect_equal(out$y, c(NA, "b"))
})
test_that("convert produces integers etc", {
dt <- lazy_dt(tibble(x = "1-1.5-FALSE"), "DT")
step <- separate(dt, x, c("x", "y", "z"), "-", convert = TRUE)
out <- collect(step)
expect_equal(
show_query(step),
expr(copy(DT)[, `:=`(!!c("x", "y", "z"), tstrsplit(x, split = "-", type.convert = TRUE))])
)
expect_equal(out$x, 1L)
expect_equal(out$y, 1.5)
expect_equal(out$z, FALSE)
})
test_that("overwrites existing columns", {
dt <- lazy_dt(tibble(x = "a:b"), "DT")
step <- dt %>% separate(x, c("x", "y"))
out <- collect(step)
expect_equal(
show_query(step),
expr(copy(DT)[, `:=`(!!c("x", "y"), tstrsplit(x, split = "[^[:alnum:]]+"))])
)
expect_equal(step$vars, c("x", "y"))
expect_equal(out$x, "a")
})
test_that("drops NA columns", {
dt <- lazy_dt(tibble(x = c(NA, "a-b", "c-d")), "DT")
step <- separate(dt, x, c(NA, "y"), "-")
out <- collect(step)
expect_equal(step$vars, "y")
expect_equal(out$y, c(NA, "b", "d"))
})
test_that("checks type of `into` and `sep`", {
dt <- lazy_dt(tibble(x = "a:b"), "DT")
expect_snapshot(
separate(dt, x, "x", FALSE),
error = TRUE
)
expect_snapshot(
separate(dt, x, FALSE),
error = TRUE
)
})
test_that("only copies when necessary", {
dt <- tibble(x = paste(letters[1:3], letters[1:3], sep = "-"), y = 1:3) %>%
lazy_dt("DT")
step <- dt %>%
filter(y < 4) %>%
separate(x, into = c("left", "right"), sep = "-")
expect_equal(
show_query(step),
expr(DT[y < 4][, `:=`(!!c("left", "right"), tstrsplit(x, split = "-"))][, .(y, left, right)])
)
}) |
"fitted.FitARMA" <-
function (object, ...)
{
object$fits
} |
kz.ft <- function (x, m, ...)
{
data <- as.vector(x)
dots <- list(...)
if (hasArg("k")) { k <- dots$k } else { k <- 1 }
if (hasArg("n")) { n <- dots$n } else { n <- 1 }
if (hasArg("adpt")) { adpt <- dots$adpt } else { adpt <- FALSE }
if (hasArg("phase")){ phase <- dots$phase } else { phase <- FALSE }
N <- length(data)
m <- round(m)
if (hasArg("f")) {
f <- mapply(FUN=min, dots$f, abs(1-dots$f))
delta <- (2*m*f - floor(2*m*f))/2
if (adpt & any(delta !=0)) { m <- adapt.m(f, m=m, N=N, k=k) }
sc <- 1/((m-1)*k+1)
} else {
f <- seq(0, 1, length = n * m + 1)[-1]
sc <- 1
if (!hasArg("phase")) { phase <- FALSE }
}
if (((m - 1) * k + 1) > length(data))
stop("invalid 'm' & 'k':(m-1)k+1 should be less equal length of data")
if (hasArg("p")) { p <- dots$p } else { p <- sc }
M <- (m - 1) * k + 1
L <- round(M * p)
T <- floor((N - M)/L) + 1
kzft <- array(NA, dim = c(T, length(f)))
omega <- 2 * pi * f
s <- 0:(M - 1)
coef <- kzft::coeff.kzft(m, k)
coefft <- coef * exp((-(0+1i)) * s %o% omega)
data[is.na(data)] <- 0
for (t in (1:T)) {
tmpc <- coef
tmpc[is.na(x[((t - 1) * L + 1):((t - 1) * L + M)])] <- 0
kzft[t, ] <- data[((t - 1) * L + 1):((t - 1) * L + M)] %*% (coefft / sum(tmpc))
}
phsf <- (2*(m - round(2*m*f)/(2*f)) * f)*pi
delta <- sign(phsf)*(1 - cos(phsf))
adset <- which(round(delta,10) != 0 & 2*m*f>=1 & dim(kzft)[1]>=(1/f))
if (length(adset) > 0 & phase & dim(kzft)[1]>6) {
value <- rep(0,length(adset))
for (j in adset) {
Mok <- ifelse(round(M*f[j]) == M*f[j], M, 2*M)
KZFT <- array(NA, dim = c(min(Mok,T), 1))
DATA <- sin(2*f[j]*pi*(1:(2*Mok)))
for (t in (1:min(Mok,T))) {
KZFT[t, ] <- DATA[((t - 1) * L + 1):((t - 1) * L + M)] %*% coefft[,j]
}
a <- max(abs(KZFT))
b <- min(abs(KZFT))
ceta <- unique(Arg(KZFT[which(abs(KZFT)==b)]))
for (u in 1:3) {
ellipse <- fit.CE(KZFT[1:min(Mok,T),1], a0=a, b0=b, ceta=ceta)
a <- ellipse$par[1]
b <- ellipse$par[2]
ceta <- ellipse$par[3]
}
value[j] <- ellipse$value
d <- (a - b)/2
if (d < 0) {
ceta <- pi/2 + ceta
hash <- kzft[,j] * (cos(-ceta) + sin(-ceta)*1i)
hash <- Re(hash)*(0.5/(0.5+abs(d))) + Im(hash)*(0.5/(0.5-abs(d)))*1i
kzft[,j] <- hash * (cos(ceta) + sin(ceta)*1i)
}
}
}
kzftf <- colMeans(kzft)
kzpv <- colMeans(abs(kzft)^2) * M
kzp <- rep(0, n * m)
plc <- mapply(FUN=max, 1, round(n * m * f))
plc <- mapply(FUN=min, round(n * m / 2), plc)
kzp[plc] <- kzpv[1:length(f)]
kzp <- kzp[1:round(n * m / 2)]
frule <- seq(1/(n * m),1,1/(m * n))
frule <- frule[1:round(n * m/2)]
if (length(f) >= length(frule)) {
f <- ""
} else {
if (length(frule[which(kzp>0)])==length(f[order(f)])){
frule[which(kzp>0)] <- f[order(f)]
} else {
if (length(f)==1) browser()
vfv <- round(n * m * f[order(f)])[1:(length(f)-1)] ==
round(n * m * f[order(f)])[2:length(f)]
for (j in (1:(length(f)-1))) {
if (vfv[j]) {
lf <- length(frule)
c(frule[1:which(kzp>0)[j]], frule[which(kzp>0)[j]],
frule[(which(kzp>0)[j]+1):lf]) -> frule
frule[which(kzp>0)[j]+(0:1)] <- f[order(f)][j:(j+1)]
c(kzp[1:which(kzp>0)[j]], kzp[which(kzp>0)[j]],
kzp[(which(kzp>0)[j]+1):lf]) -> kzp
kzp[which(kzp>0)[j]+(0:1)] <- kzpv[order(f)][j:(j+1)]
} else {
frule[which(kzp>0)][j] <- f[order(f)][j]
}
}
}
}
pars <- list(f=f, m=m, n=n, k=k, p=p, adpt=adpt, phase=phase, diff=delta)
if (exists("value")) {
pars$value <- value; pars$a <- a; pars$b <- b; pars$ceta <- ceta
}
lst <- list(tfmatrix = kzft, fft = kzftf, f=frule, pg = kzp, pars=pars)
return(lst)
}
kz.ftc <- function (x, m, ...)
{
data <- as.vector(x)
N <- length(data)
dots <- list(...)
if (hasArg("xt")) { xt <- dots$xt } else { xt <- 1:N }
if (hasArg("k")) { k <- dots$k } else { k <- 1 }
if (((m - 1) * k + 1) > length(data))
stop("invalid 'm' & 'k':(m-1)k+1 should be less equal length of data")
if (hasArg("n")) { n <- dots$n } else { n <- 1 }
if (hasArg("f")) {
f <- dots$f
sc <- 1/(m*k)
} else {
f <- seq(0, 1, length = n * m + 1)[-1]
sc <- 1
}
if (hasArg("p")) { p <- dots$p } else { p <- sc }
M <- (m - 1) * k + 1
L <- round(M * p)
T <- floor((N - M)/L) + 1
kzft <- array(NA, dim = c(T, n * length(f)))
coef <- kzft::coeff.kzft(m, k)
lbtw <- function(ip, coef) {
if (floor(ip)==ceiling(ip)) return(coef[floor(ip)])
ip <- max(min(ip, length(coef)-1),0.00001)
coef[floor(ip)+1]*(ceiling(ip)-ip)+coef[ceiling(ip)+1]*(ip-floor(ip))
}
for (t in (1:T)) {
sr <- which(xt > ((t - 1) * L ) & xt <= ((t - 1) * L + M ))
st <- xt[sr] - (t - 1) * L
cref <- unlist(sapply(st, FUN=lbtw, coef))
coefft <- exp(-(0+1i) * (st %o% (2 * pi * f))) * cref
kzft[t, ] <- data[sr] %*% (coefft / sum(coef))
}
kzftf <- colMeans(kzft)
kzpv <- colMeans(abs(kzft)^2) * M
kzp <- rep(0, n * m)
kzp[ round(n * m * f) ] <- kzpv[1:length(f)]
kzp <- kzp[1:round(n * m / 2)]
frule <- seq(1/(n * m),1,1/(m * n))
frule <- frule[1:round(n * m/2)]
lst <- list(tfmatrix = kzft, fft = kzftf, f=frule, pg = kzp)
return(lst)
}
kz.rc2 <- function(ds, f=0.25, m=round(min(dim(ds)/2)), ...) {
dots <- list(...)
if (hasArg("k")) { k <- dots$k } else { k <- 1 }
if (hasArg("edge")) { edge <- dots$edge } else { edge <- FALSE }
if (hasArg("plot")) { plot <- dots$plot } else { plot <- FALSE }
if (hasArg("angle")) {angle <- dots$angle} else { angle <- 0 }
if (hasArg("compare")) {compare <- dots$compare} else { compare <- FALSE }
if (hasArg("rlvl")) { rlvl <- dots$rlvl} else { rlvl <- 2 }
if (hasArg("avg") ) {
avg <- dots$avg
} else {
if (hasArg("angle")) { avg <- TRUE } else { avg <- FALSE }
}
agls <- angle%%180
agls <- ifelse(agls >= 180, agls%%180, agls)
agls <- ifelse(agls <= -90, agls%%180, agls)
agls <- ifelse(agls > 90, agls-180, agls)
df <- a2d(ds)
Ang <- abs(90*round(angle/90))
for (i in 1:length(agls)) {
F1 <- efg(f[i], agls[i], Ang[i])
if (F1 > 0.5) { F1 <- (1 - F1) }
xy <- getwave(df, Ang[i]*pi/180)[,1:4]
wv <- split(xy$obs,xy$e)
xy <- xy[order(xy$e),]
rv <- list()
for (j in 1:length(wv)) {
rv[[j]] <- as.vector(rep(NA, length(wv[[j]])))
if (length(wv[[j]]) < ((m - 1) * k + 1)) next
xr <- 2*Re(kz.ft(wv[[j]], m=m, f=F1, k=k, ...)$tf)
rv[[j]][1:length(xr)] <- as.vector(xr)
}
drv <- unlist(rv)
xy$xr <- drv
if (sum(diff(xy$x)==-1) > sum(diff(xy$x)==1)) { scx = -1 } else { scx = 1}
if (sum(diff(xy$y)==-1) > sum(diff(xy$y)==1)) { scy = -1 } else { scy = 1}
mtxr <- df2mt(xy[,c(1,2,5)], scale=c(1,1))
if (avg) {
xyz <- getwavf(xy[,c(1,2,5)], (agls[i]-90)*pi/180, f[i], rlvl)
drv <- aggregate(xyz$xr, by=list(xyz$e), FUN=mean, na.rm=T)
names(drv) <- c("e","avg")
xyz <- merge(xyz, drv, all=TRUE)
mtxr2 <- df2mt(xyz[,c(2,3,5)], scale=c(1,1))
}
if (i==1) {
if (avg) { ds2 <- mtxr2 } else { ds2 <- mtxr }
} else {
if (avg) { ds2 <- ds2 + mtxr2 } else { ds2 <- ds2 + mtxr }
}
}
if (!edge) {
M <- (m-1)*k
dx <- dim(ds2)[1]-M
dy <- dim(ds2)[2]-M
ds2 <- ds2[(1:dx)+(1-scx)*M/2, (1:dy)+(1-scy)*M/2]
}
dx <- dim(ds2)[1]
dy <- dim(ds2)[2]
if (plot) {
txt1 <- toString(paste(round(angle[i],2), enc2utf8("\xB0"), " ",sep=""))
txt2 <- paste("f=", toString(paste(round(f,3))),sep="")
if (compare) {
dev.new(); graphics::image(x=1:dx, y=1:dy, z=ds[1:dx,1:dy])
graphics::box(); graphics::title("Signal")
mtext(paste(txt2, ", d=", txt1, sep=""), cex=0.75, line=0.2)
}
dev.new(); graphics::image(x=1:dx, y=1:dy, z=ds2)
graphics::box(); graphics::title("Reconstruction")
mtext(paste(txt2, ", d=", txt1, sep=""), cex=0.75, line=0.2)
}
return(ds2)
} |
expected <- eval(parse(text="c(TRUE, TRUE)"));
test(id=0, code={
argv <- eval(parse(text="list(c(30000L, 100000L), c(30000, 1e+05))"));
do.call(`==`, argv);
}, o=expected); |
predict.pmtree <- function(object, newdata = NULL, type = "node",
predict_args = list(), perm = NULL, ...) {
if(is.numeric(perm)) perm <- names(object$data)[perm]
node <- predict.party(object, newdata = newdata, type = "node", perm = perm, ...)
if(type == "node") return(node)
if(is.null(newdata)) newdata <- object$data
if(type %in% c("pass", "coef")) {
trdatnodes <- object$fitted["(fitted)"]
unode <- sort(unique(node))
newdata$.node <- node
newdata$.id <- seq_len(NROW(newdata))
prfun <- function(nd, type = "pass") {
mod <- update(object$info$model,
subset = (trdatnodes == nd),
data = object$data)
if(type == "coef") {
data.frame(t(coef(mod)),
.id = newdata$.id[newdata$.node == nd],
check.names = FALSE)
} else {
args <- c(list(object = mod,
newdata = newdata[newdata$.node == nd, ]),
predict_args)
pred <- do.call(predict, args = args)
data.frame(pred, .id = newdata$.id[newdata$.node == nd])
}
}
pr <- lapply(unode, prfun, type = type)
pr <- do.call(rbind, pr)
pred <- pr[order(pr$.id), ]
pred$.id <- NULL
return(pred)
}
}
objfun.pmtree <- function(x,
newdata = NULL,
weights = NULL,
perm = NULL,
sum = FALSE, ...) {
which_node <- predict(x, type = "node", newdata = newdata,
perm = perm, ...)
if(!is.null(perm) & is.null(newdata))
newdata <- x$data
tnodes <- unique(which_node)
mods <- nodeapply(x, ids = tnodes, FUN = function(n) n$info$object)
if(sum) {
if(!is.null(weights) & is.null(newdata)) {
newdata <- x$data
}
get_objfun_node_unordered <- function(nd) {
wn <- (which_node == nd) & !is.na(which_node)
sum(objfun(mods[[as.character(nd)]],
newdata = newdata[wn, ],
weights = weights[wn]))
}
return(sum(sapply(tnodes, get_objfun_node_unordered)))
} else {
if(is.null(newdata)) newdata <- x$data
w_n_char <- as.character(which_node)
get_objfun_node <- function(i) {
objfun(mods[[w_n_char[i]]], newdata[i, ], weights = weights[i])
}
return(sapply(seq_len(NROW(newdata)), get_objfun_node))
}
}
logLik.pmtree <- function(object, dfsplit = 0, newdata = NULL, weights = NULL, perm = NULL, ...) {
dfs <- (length(object) - width(object)) * dfsplit
df <- NULL
if (is.null(newdata) && is.null(perm) && is.null(weights)) {
ids <- nodeids(object, terminal = TRUE)
info <- nodeapply(object, ids = ids, function(x) x$info)
ll <- lapply(info, function(x) tryCatch(logLik(x$object), error = function(err) NA))
ndf <- sapply(ll, function(x) attr(x, "df"))
if(!any(sapply(ndf, is.null))) df <- sum(ndf) + dfs
} else {
if(class(object$info$model)[1] == "lm")
stop("logLik not yet implemented for lm. Try objfun(..., sum = TRUE).")
ll <- objfun(x = object, newdata = newdata, weights = weights, perm = perm,
sum = TRUE, ...)
df <- NA
}
nobs <- ifelse(!is.null(weights), sum(weights),
ifelse(is.null(newdata), object$nobs,
nrow(newdata)))
structure(
sum(as.numeric(ll)),
df = df,
nobs = nobs,
class = "logLik"
)
}
print.pmtree <- function(x, node = NULL,
FUN = NULL, digits = getOption("digits") - 4L,
footer = TRUE, ...)
{
digits <- max(c(0, digits))
title <- paste("Partitioned model:\n", paste(deparse(getCall(x$info$model)),
sep = "\n", collapse = "\n"),
"\nPartitioning variables:", deparse(x$info$zformula))
if(is.null(node)) {
header_panel <- function(party) ""
footer_panel <- if(footer) function(party) {
n <- width(party)
n <- format(c(length(party) - n, n))
info <- nodeapply(x, ids = nodeids(x, terminal = TRUE),
FUN = function(n) c(length(info_node(n)$coefficients), info_node(n)$objfun))
k <- mean(sapply(info, "[", 1L))
of <- format(sum(sapply(info, "[", 2L)), digits = getOption("digits"))
c("", paste("Number of inner nodes: ", n[1L]),
paste("Number of terminal nodes:", n[2L]),
paste("Number of parameters per node:", format(k, digits = getOption("digits"))),
paste("Objective function: ", of, sep = ""), "")
} else function (party) ""
if(is.null(FUN)) {
FUN <- function(x) c(sprintf(": n = %s", x$nobs), capture.output(print(x$coefficients)))
}
terminal_panel <- function(node) formatinfo_node(node,
default = "*", prefix = NULL, FUN = FUN)
print.party(x, terminal_panel = terminal_panel,
header_panel = header_panel, footer_panel = footer_panel, ...)
} else {
node <- as.integer(node)
info <- nodeapply(x, ids = node,
FUN = function(n) info_node(n)[c("coefficients", "objfun", "criterion")])
for(i in seq_along(node)) {
if(i == 1L) {
cat(paste(title, "\n", collapse = ""))
} else {
cat("\n")
}
cat(sprintf("-- Node %i --\n", node[i]))
cat("\nEstimated parameters:\n")
print(info[[i]]$coefficients)
cat(sprintf("\nObjective function:\n%s\n", format(info[[i]]$objfun)))
cat("\nParameter instability tests:\n")
print(info[[i]]$criterion)
}
}
invisible(x)
}
summary.pmtree <- function(object, node = NULL, ...) {
ids <- if(is.null(node)) nodeids(object, terminal = TRUE) else node
info <- nodeapply(object, ids = ids, function(x) x$info)
coefs <- sapply(info, function(x) x$coefficients)
colnames(coefs) <- paste("node", colnames(coefs))
objfuns <- sapply(info, function(x) x$objfun)
if(is.null(node)) {
brobjf <- paste0("(", round(objfuns, 2), ")")
sobjf <- paste(brobjf, collapse = " + ")
objfs <- paste(sobjf, "=", round(sum(objfuns), 2))
} else {
objfs <- objfuns
names(objfs) <- paste("node", ids)
}
cl <- getCall(object$info$model)
nobs <- sapply(info, function(x) x$nobs)
nullnobs <- sapply(nobs, is.null)
if(1 %in% ids & any(nullnobs))
nobs[nullnobs] <- object$nobs
names(nobs) <- paste("node", ids)
ret <- list(ids = ids, call = cl, coefs = coefs, objfs = objfs, nobs = nobs)
class(ret) <- "summary.pmtree"
return(ret)
}
print.summary.pmtree <- function(x, digits = 4, ...) {
cat("Stratified model for node(s)", paste(x$ids, collapse = ", "))
cat("\n\nModel call:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"),
"\n\n", sep = "")
cat("Coefficients:\n")
print(x$coefs, digits = digits)
cat("\nNumber of obervations:\n")
print(unlist(x$nobs))
cat("\nObjective function:\n")
if(is.character(x$objfs)) cat(x$objfs) else {
print(x$objfs)
}
}
coef.pmtree <- function(object, node = NULL, ...) {
ids <- if(is.null(node)) nodeids(object, terminal = TRUE) else node
info <- nodeapply(object, ids = ids, function(x) x$info)
t(sapply(info, function(x) x$coefficients))
} |
prevsymbol_fn = function(genes, data, abs,filename, terms) {indices = NULL; for (i in 1:dim(genes)[1]){indices = c(indices,which(genes[i,1] == data[,2])) }
data_theme <- data[indices,]
prevsymbol = NULL;for (i in 1:dim(genes)[1]){ prevsymbol = c(prevsymbol, list(unlist(strsplit(as.character(data_theme[i,11]),"|",fixed=T)))) }
result_genes_prevsymbol = NULL; for (i in 1:dim(genes)[1]){if ( !is.na(prevsymbol[[i]][1]) ) {for (j in 1:length(prevsymbol[[i]])) result_genes_prevsymbol = Give_Sentences(prevsymbol[[i]][j],abs) ; if (length(result_genes_prevsymbol) != 0) {print(c(i,j));write(paste(">>",data_theme[i,2],prevsymbol[[i]][j],sep=" "), file = paste(filename,"prevsymbol.txt",sep=""), append=T); for (k in 1:length(result_genes_prevsymbol)){for(l in 1: length(result_genes_prevsymbol[[k]])) {temp = result_genes_prevsymbol[[k]][l]; for(s in 1:length(terms)){temp1 = regexpr(terms[s],temp);if (temp1 != -1) write(c(attr(result_genes_prevsymbol,"PMID")[k],temp), file = paste(filename,"prevsymbol.txt",sep=""),append=T)} }}} }}
} |
HierarchicalBetaCreate <- function(n, priorParameters, hyperPriorParameters,
alphaPrior, maxT, gammaPrior,
mhStepSize, num_sticks) {
mdobj_beta <- BetaMixtureCreate(priorParameters, mhStepSize = mhStepSize,
maxT = maxT, hyperPriorParameters = hyperPriorParameters)
class(mdobj_beta) <- c("hierarchical", "beta", "nonconjugate")
gammaParam <- rgamma(1, gammaPrior[1], gammaPrior[2])
theta_k <- PriorDraw.beta(mdobj_beta, num_sticks)
beta_k <- StickBreaking(gammaParam, num_sticks)
mdobj_beta$theta_k <- theta_k
mdobj_beta$beta_k <- beta_k
mdobj_beta$gamma <- gammaParam
mdobj_list <- vector("list", n)
for (i in seq_len(n)) {
mdobj_beta$alpha <- rgamma(1, alphaPrior[1], alphaPrior[2])
mdobj_beta$pi_k <- draw_gj(mdobj_beta$alpha, beta_k)
mdobj_list[[i]] <- mdobj_beta
}
return(mdobj_list)
} |
testthat::test_that("ClassWeightedVoting: initialize function works", {
cutoff <- 0.5
weights <- c(0.6, 0.5)
testthat::expect_is(ClassWeightedVoting$new(cutoff = cutoff,
weights = weights),
"ClassWeightedVoting")
})
testthat::test_that("ClassWeightedVoting: getWeights function works", {
cutoff <- 0.5
weights <- c(0.6, 0.5)
testthat::expect_equal(ClassWeightedVoting$new(cutoff = cutoff,
weights = weights)$getWeights(),
weights)
})
testthat::test_that("ClassWeightedVoting: setWeights function works", {
cutoff <- 0.5
weights <- c(0.6, 0.5)
testthat::expect_silent(ClassWeightedVoting$new(cutoff = cutoff,
weights = weights)$setWeights(weights = weights))
})
testthat::test_that("ClassWeightedVoting: setWeights function checks parameter type", {
cutoff <- 0.5
weights <- c(0.6, 0.5)
testthat::expect_message(ClassWeightedVoting$new(cutoff = cutoff,
weights = weights)$setWeights(weights = NULL),
"[ClassWeightedVoting][WARNING] Weights values not changed due to inconsistency error",
fixed = TRUE)
})
testthat::test_that("ClassWeightedVoting: execute function works", {
cutoff <- 0.5
weights <- c(0.6, 0.5)
voting <- ClassWeightedVoting$new(cutoff = cutoff,
weights = weights)
predictions <- readRDS(file.path("resourceFiles",
"testVotings",
"predictions.rds"))
predictions$add(prediction = predictions$get(1))
verbose <- TRUE
testthat::expect_message(voting$execute(predictions = predictions,
verbose = verbose),
"[ClassWeightedVoting][WARNING] Weight values are missing or incorrect. Assuming default model performance values",
fixed = TRUE)
testthat::expect_message(voting$execute(predictions = predictions,
verbose = verbose),
"[ClassWeightedVoting][INFO] Performing voting with '~0.5486, ~0.3824, ~0.3854, ~0.5486' weights and cutoff of 0.5",
fixed = TRUE)
})
testthat::test_that("ClassWeightedVoting: execute function checks parameter type", {
cutoff <- 0.5
weights <- c(0.6, 0.5)
voting <- ClassWeightedVoting$new(cutoff = cutoff,
weights = weights)
testthat::expect_error(voting$execute(predictions = NULL,
verbose = FALSE),
"[ClassWeightedVoting][FATAL] Predictions parameter must be defined as 'ClusterPrediction' type. Aborting...",
fixed = TRUE)
predictions <- ClusterPredictions$new(class.values = c(1, 0, 1, 1),
positive.class = 1)
testthat::expect_error(voting$execute(predictions = predictions,
verbose = FALSE),
"[ClassWeightedVoting][FATAL] Cluster predictions were not computed. Aborting...",
fixed = TRUE)
}) |
ci.mean1 <- function(alpha, m, sd, n) {
df <- n - 1
tcrit <- qt(1 - alpha/2, df)
se <- sd/sqrt(n)
ll <- m - tcrit*se
ul <- m + tcrit*se
out <- t(c(m, se, ll, ul))
colnames(out) <- c("Estimate", "SE", "LL", "UL")
return(out)
}
ci.stdmean1 <- function(alpha, m, sd, n, h) {
z <- qnorm(1 - alpha/2)
df <- n - 1
adj <- 1 - 3/(4*df - 1)
est <- (m - h)/sd
estu <- adj*est
se <- sqrt(est^2/(2*df) + 1/df)
ll <- est - z*se
ul <- est + z*se
out <- t(c(estu, se, ll, ul))
colnames(out) <- c("Estimate", "SE", "LL", "UL")
return(out)
}
ci.mean2 <- function(alpha, m1, m2, sd1, sd2, n1, n2) {
df1 <- n1 + n2 - 2
est <- m1 - m2
v1 <- sd1^2
v2 <- sd2^2
vp <- ((n1 - 1)*v1 + (n2 - 1)*v2)/df1
se1 <- sqrt(vp/n1 + vp/n2)
t1 <- est/se1
p1 <- 2*(1 - pt(abs(t1),df1))
tcrit1 <- qt(1 - alpha/2, df1)
ll1 <- est - tcrit1*se1
ul1 <- est + tcrit1*se1
se2 <- sqrt(v1/n1 + v2/n2)
t2 <- est/se2
df2 <- (se2^4)/(v1^2/(n1^3 - n1^2) + v2^2/(n2^3 - n2^2))
p2 <- 2*(1 - pt(abs(t2),df2))
tcrit2 <- qt(1 - alpha/2, df2)
ll2 <- est - tcrit2*se2
ul2 <- est + tcrit2*se2
out1 <- t(c(est, se1, t1, df1, p1, ll1, ul1))
out2 <- t(c(est, se2, t2, df2, p2, ll2, ul2))
out <- rbind(out1, out2)
colnames(out) <- c("Estimate", "SE", "t", "df", "p", "LL", "UL")
rownames(out) <- c("Equal Variances Assumed:", "Equal Variances Not Assumed:")
return(out)
}
ci.lc.mean.bs <- function(alpha, m, sd, n, v) {
est <- t(v)%*%m
k <- length(m)
df1 <- sum(n) - k
v1 <- sum((n - 1)*sd^2)/df1
se1 <- sqrt(v1*t(v)%*%solve(diag(n))%*%v)
t1 <- est/se1
p1 <- 2*(1 - pt(abs(t1),df1))
tcrit1 <- qt(1 - alpha/2, df1)
ll1 <- est - tcrit1*se1
ul1 <- est + tcrit1*se1
v2 <- diag(sd^2)%*%(solve(diag(n)))
se2 <- sqrt(t(v)%*%v2%*%v)
t2 <- est/se2
df2 <- (se2^4)/sum(((v^4)*(sd^4)/(n^2*(n - 1))))
p2 <- 2*(1 - pt(abs(t2),df2))
tcrit2 <- qt(1 - alpha/2, df2)
ll2 <- est - tcrit2*se2
ul2 <- est + tcrit2*se2
out1 <- t(c(est, se1, t1, df1, p1, ll1, ul1))
out2 <- t(c(est, se2, t2, df2, p2, ll2, ul2))
out <- rbind(out1, out2)
colnames(out) <- c("Estimate", "SE", "t", "df", "p", "LL", "UL")
rownames(out) <- c("Equal Variances Assumed:", "Equal Variances Not Assumed:")
return(out)
}
ci.tukey <-function(alpha, m, sd, n) {
a <- length(m)
v1 <- sd^2/n
v2 <- sd^4/(n^2*(n - 1))
mean <- outer(m, m, '-')
diff <- (-1)*mean[lower.tri(mean)]
v1 <- outer(v1, v1, "+")
v2 <- outer(v2, v2, "+")
df = v1^2/v2
df <- df[lower.tri(df)]
SE <- sqrt(v1[lower.tri(v1)])
t <- diff/SE
q <- qtukey(p = 1 - alpha, nmeans = a, df = df)/sqrt(2)
p <- 1 - ptukey(sqrt(2)*abs(t), nmeans = a, df = df)
p <- round(p*1000)/1000
LL <- diff - q*SE
UL <- diff + q*SE
pair <- t(combn(seq(1:a), 2))
out <- cbind(pair, diff, SE, t, df, p, LL, UL)
rownames(out) <- rep("", a*(a - 1)/2)
return(out)
}
ci.ratio.mean2 <- function(alpha, y1, y2){
n1 <- length(y1)
n2 <- length(y2)
m1 <- mean(y1)
m2 <- mean(y2)
v1 <- var(y1)
v2 <- var(y2)
var <- v1/(n1*m1^2) + v2/(n2*m2^2)
df <- var^2/(v1^2/(m1^4*(n1^3 - n1^2)) + v2^2/(m2^4*(n2^3 - n2^2)))
tcrit <- qt(1 - alpha/2, df)
est <- log(m1/m2)
se <- sqrt(var)
ll <- exp(est - tcrit*se)
ul <- exp(est + tcrit*se)
out <- t(c(m1, m2, exp(est), ll, ul))
colnames(out) <- c("Mean1", "Mean2", "Mean1/Mean2", "LL", "UL")
return(out)
}
ci.stdmean2 <- function(alpha, m1, m2, sd1, sd2, n1, n2) {
z <- qnorm(1 - alpha/2)
v1 <- sd1^2
v2 <- sd2^2
df1 <- n1 - 1
df2 <- n2 - 1
df3 <- n1 + n2 - 2
adj1 <- 1 - 3/(4*df1 - 1)
adj2 <- 1 - 3/(4*df2 - 1)
adj3 <- 1 - 3/(4*df3 - 1)
s <- sqrt((v1 + v2)/2)
sp <- sqrt((df1*v1 + df2*v2)/df3)
est1 <- (m1 - m2)/s
est1u <- adj3*est1
se1 <- sqrt(est1^2*(v1^2/df1 + v2^2/df2)/(8*s^4) + (v1/df1 + v2/df2)/s^2)
ll1 <- est1 - z*se1
ul1 <- est1 + z*se1
est2 <- (m1 - m2)/sp
est2u <- adj3*est2
se2 <- sqrt(est2^2*(1/df1 + 1/df2)/8 + (v1/n1 + v2/n2)/sp^2)
ll2 <- est2 - z*se2
ul2 <- est2 + z*se2
est3 <- (m1 - m2)/sd1
est3u <- adj1*est3
se3 <- sqrt(est3^2/(2*df1) + 1/df1 + v2/(df2*v1))
ll3 <- est3 - z*se3
ul3 <- est3 + z*se3
est4 <- (m1 - m2)/sd2
est4u <- adj2*est4
se4 <- sqrt(est4^2/(2*df2) + 1/df2 + v1/(df1*v2))
ll4 <- est4 - z*se4
ul4 <- est4 + z*se4
out1 <- t(c(est1u, se1, ll1, ul1))
out2 <- t(c(est2u, se2, ll2, ul2))
out3 <- t(c(est3u, se3, ll3, ul3))
out4 <- t(c(est4u, se4, ll4, ul4))
out <- rbind(out1, out2, out3, out4)
colnames(out) <- c("Estimate", "SE", "LL", "UL")
rownames1 <- c("Unweighted standardizer:", "Weighted standardizer:")
rownames2 <- c("Group 1 standardizer:", "Group 2 standardizer:")
rownames(out) <- c(rownames1, rownames2)
return(out)
}
ci.stdmean.strat <- function(alpha, m1, m2, sd1, sd2, n1, n2, p1) {
z <- qnorm(1 - alpha/2)
v1 <- sd1^2
v2 <- sd2^2
df1 <- n1 - 1
df2 <- n2 - 1
df3 <- n1 + n2 - 2
adj1 <- 1 - 3/(4*df1 - 1)
adj2 <- 1 - 3/(4*df2 - 1)
adj3 <- 1 - 3/(4*df3 - 1)
s <- sqrt(p1*v1 + (1 - p1)*v2)
est1 <- (m1 - m2)/s
est1u <- adj3*est1
se1 <- sqrt(est1^2*(1/df1 + 1/df2)/8 + (v1/n1 + v2/n2)/s^2)
ll1 <- est1 - z*se1
ul1 <- est1 + z*se1
est3 <- (m1 - m2)/sd1
est3u <- adj1*est3
se3 <- sqrt(est3^2/(2*df1) + 1/df1 + v2/(df2*v1))
ll3 <- est3 - z*se3
ul3 <- est3 + z*se3
est4 <- (m1 - m2)/sd2
est4u <- adj2*est3
se4 <- sqrt(est4^2/(2*df2) + 1/df2 + v1/(df1*v2))
ll4 <- est4 - z*se4
ul4 <- est4 + z*se4
out1 <- t(c(est1u, se1, ll1, ul1))
out3 <- t(c(est3u, se3, ll3, ul3))
out4 <- t(c(est4u, se4, ll4, ul4))
out <- rbind(out1, out3, out4)
colnames(out) <- c("Estimate", "SE", "LL", "UL")
rownames1 <- c("Weighted standardizer:")
rownames2 <- c("Group 1 standardizer:", "Group 2 standardizer:")
rownames(out) <- c(rownames1, rownames2)
return(out)
}
ci.lc.stdmean.bs <- function(alpha, m, sd, n, v) {
z <- qnorm(1 - alpha/2)
var <- sd^2
a <- length(m)
s <- sqrt(sum(var)/a)
df <- sum(n) - a
adj <- 1 - 3/(4*df - 1)
sp <- sqrt(sum((n - 1)*var)/df)
est1 <- (t(v)%*%m)/s
est2 <- (t(v)%*%m)/sp
est1u <- adj*est1
est2u <- adj*est2
a1 <- est1^2/(2*a^2*s^4)
a2 <- a1*sum((var^2/(n - 1)))
a3 <- sum((v^2*var/(n - 1)))/s^2
se1 <- sqrt(a2 + a3)
ll1 <- est1 - z*se1
ul1 <- est1 + z*se1
a1 <- est2^2/(2*a^2)
a2 <- a1*sum(1/(n - 1))
a3 <- sum((v^2*var/n))/sp^2
se2 <- sqrt(a2 + a3)
ll2 <- est2 - z*se2
ul2 <- est2 + z*se2
out1 <- t(c(est1u, se1, ll1, ul1))
out2 <- t(c(est2u, se2, ll2, ul2))
out <- rbind(out1, out2)
colnames(out) <- c("Estimate", "SE", "LL", "UL")
rownames(out) <- c("Unweighted standardizer:", "Weighted standardizer:")
return(out)
}
ci.mean.ps <- function(alpha, m1, m2, sd1, sd2, cor, n) {
df <- n - 1
tcrit <- qt(1 - alpha/2, df)
vd <- sd1^2 + sd2^2 - 2*cor*sd1*sd2
est <- m1 - m2
se <- sqrt(vd/n)
t <- est/se
p <- 2*(1 - pt(abs(t), df))
ll <- est - tcrit*se
ul <- est + tcrit*se
out <- t(c(est, se, t, df, p, ll, ul))
colnames(out) <- c("Estimate", "SE", "t", "df", "p","LL", "UL")
return(out)
}
ci.ratio.mean.ps <- function(alpha, y1, y2){
n <- length(y1)
m1 <- mean(y1)
m2 <- mean(y2)
v1 <- var(y1)
v2 <- var(y2)
cor <- cor(y1,y2)
var <- (v1/m1^2 + v2/m2^2 - 2*cor*sqrt(v1*v2)/(m1*m2))/n
df <- n - 1
tcrit <- qt(1 - alpha/2, df)
est <- log(m1/m2)
se <- sqrt(var)
ll <- exp(est - tcrit*se)
ul <- exp(est + tcrit*se)
out <- t(c(m1, m2, exp(est), ll, ul))
colnames(out) <- c("Mean1", "Mean2", "Mean1/Mean2", "LL", "UL")
return(out)
}
ci.stdmean.ps <- function(alpha, m1, m2, sd1, sd2, cor, n) {
z <- qnorm(1 - alpha/2)
s <- sqrt((sd1^2 + sd2^2)/2)
df <- n - 1
v1 <- sd1^2
v2 <- sd2^2
adj1 <- sqrt((n - 2)/df)
adj2 <- 1 - 3/(4*df - 1)
vd <- v1 + v2 - 2*cor*sd1*sd2
est1 <- (m1 - m2)/s
est1u <- adj1*est1
se1 <- sqrt(est1^2*(v1^2 + v2^2 + 2*cor^2*v1*v2)/(8*df*s^4) + vd/(df*s^2))
ll1 <- est1 - z*se1
ul1 <- est1 + z*se1
est3 <- (m1 - m2)/sd1
est3u <- adj2*est3
se3 <- sqrt(est3^2/(2*df) + vd/(df*v1))
ll3 <- est3 - z*se3
ul3 <- est3 + z*se3
est4 <- (m1 - m2)/sd2
est4u <- adj2*est4
se4 <- sqrt(est4^2/(2*df) + vd/(df*v2))
ll4 <- est4 - z*se4
ul4 <- est4 + z*se4
out1 <- t(c(est1u, se1, ll1, ul1))
out3 <- t(c(est3u, se3, ll3, ul3))
out4 <- t(c(est4u, se4, ll4, ul4))
out <- rbind(out1, out3, out4)
colnames(out) <- c("Estimate", "SE", "LL", "UL")
rownames1 <- c("Unweighted standardizer:")
rownames2 <- c("Measurement 1 standardizer:", "Measurement 2 standardizer:")
rownames(out) <- c(rownames1, rownames2)
return(out)
}
ci.lc.stdmean.ws <- function(alpha, m, sd, cor, n, q) {
z <- qnorm(1 - alpha/2)
a <- length(m)
df <- n - 1
adj <- sqrt((n - 2)/df)
s <- sqrt(sum(sd^2)/a)
est <- (t(q)%*%m)/s
estu <- adj*est
v1 <- est^2/(2*a^2*s^4*df)
v2 <- sum(sd^4)
v3 <- cor^2*t(sd^2)%*%sd^2
v4 <- sum(q^2*sd^2)
v5 <- cor*t(q*sd)%*%(q*sd)
se <- sqrt(v1*(v2 + v3) + (v4 - v5)/(df*s^2))
ll <- est - z*se
ul <- est + z*se
out <- t(c(estu, se, ll, ul))
colnames(out) <- c("Estimate", "SE", "LL", "UL")
return(out)
}
ci.mad1 <- function(alpha, y) {
n <- length(y)
z <- qnorm(1 - alpha/2)
c <- n/(n - 1)
median <- median(y)
mad <- mean(abs(y - median))
skw <- (mean(y) - median)/mad
kur <- (sd(y)/mad)^2
se <- sqrt((skw^2 + kur - 1)/n)
ll <- exp(log(c*mad) - z*se)
ul <- exp(log(c*mad) + z*se)
out <- t(c(c*mad, ll, ul))
colnames(out) <- c("MAD", "LL", "UL")
return(out)
}
ci.ratio.mad2 <- function(alpha, y1, y2) {
z <- qnorm(1 - alpha/2)
n1 <- length(y1)
c1 <- n1/(n1 - 1)
n2 <- length(y2)
c2 <- n2/(n2 - 1)
median1 <- median(y1)
median2 <- median(y2)
mad1 <- mean(abs(y1 - median1))
skw1 <- (mean(y1) - median1)/mad1
kur1 <- (sd(y1)/mad1)^2
var1 <- (skw1^2 + kur1 - 1)/n1
mad2 <- mean(abs(y2 - median2))
skw2 <- (mean(y2) - median2)/mad2
kur2 <- (sd(y2)/mad2)^2
var2 <- (skw2^2 + kur2 - 1)/n2
se <- sqrt(var1 + var2)
c <- c1/c2
est <- mad1/mad2
ll <- exp(log(c*est) - z*se)
ul <- exp(log(c*est) + z*se)
out <- t(c(c1*mad1, c2*mad2, c*est, ll, ul))
colnames(out) <- c("MAD1", "MAD2", "MAD1/MAD2", "LL", "UL")
return(out)
}
ci.ratio.mad.ps <- function(alpha, y1, y2) {
z <- qnorm(1 - alpha/2)
n <- length(y1);
c <- n/(n - 1)
median1 <- median(y1);
median2 <- median(y2);
mad1 <- mean(abs(y1 - median1))
skw1 <- (mean(y1) - median1)/mad1
kur1 <- (sd(y1)/mad1)^2
var1 <- (skw1^2 + kur1 - 1)/n
mad2 <- mean(abs(y2 - median2))
skw2 <- (mean(y2) - median2)/mad2
kur2 <- (sd(y2)/mad2)^2
var2 <- (skw2^2 + kur2 - 1)/n
d1 <- abs(y1 - median1);
d2 <- abs(y2 - median2)
cor <- cor(d1, d2)
se <- sqrt(var1 + var2 - 2*cor*sqrt(var1*var2))
est <- mad1/mad2
ll <- exp(log(est) - z*se)
ul <- exp(log(est) + z*se)
out <- t(c(c*mad1, c*mad2, est, ll, ul))
colnames(out) <- c("MAD1", "MAD2", "MAD1/MAD2", "LL", "UL")
return(out)
}
ci.cod1 <-function(alpha, y) {
z = qnorm(1 - alpha/2)
n = length(y)
c = n/(n - 1)
a1 = round((n + 1)/2 - sqrt(n))
b1 = n - a1 + 1
med = median(y)
m = mean(y)
v = var(y)
tau = mean(abs(y - med))
del = (m - med)/tau
gam = v/tau^2
cod = tau/med
y = sort(y)
vareta = ((log(y[a1]) - log(y[b1]))/4)^2
se1 = sqrt(vareta)
vartau = (gam + del^2 - 1)/n
se2 = sqrt(vartau)
cov = del*se1/sqrt(n)
k = sqrt(vareta + vartau - 2*cov)/(se1 + se2)
a2 = round((n + 1)/2 - k*z*sqrt(n/4))
b2 = n - a2 + 1
L2 = log(y[a2])
U2 = log(y[b2])
L1 = log(c*tau) - k*z*se2
U1 = log(c*tau) + k*z*se2
LL = exp(L1 - U2)
UL = exp(U1 - L2)
out = t(c(cod, LL, UL))
colnames(out) = c("COD", "LL", "UL")
return(out)
}
ci.median1 <- function(alpha, y) {
n <- length(y)
y <- sort(y)
z <- qnorm(1 - alpha/2)
median <- median(y)
c1 <- round((n - z*sqrt(n))/2)
if (c1 < 1) {c1 = 1}
ll <- y[c1]
ul <- y[n - c1 + 1]
a <- round((n + 1)/2 - sqrt(n))
if (a < 1) {a = 1}
ll1 <- y[a]
ul1 <- y[n - a + 1]
p <- pbinom(a - 1, size = n, prob = .5)
z0 <- qnorm(1 - p)
se <- (ul1 - ll1)/(2*z0)
out <- t(c(median, se, ll, ul))
colnames(out) <- c("Median", "SE", "LL", "UL")
return(out)
}
ci.median2 <- function(alpha, y1, y2) {
z <- qnorm(1 - alpha/2)
n1 <- length(y1)
y1 <- sort(y1)
n2 <- length(y2)
y2 <- sort(y2)
median1 <- median(y1)
median2 <- median(y2)
a1 <- round(n1/2 - sqrt(n1))
if (a1 < 1) {a1 = 1}
l1 <- y1[a1]
u1 <- y1[n1 - a1 + 1]
p <- pbinom(a1 - 1, size = n1, prob = .5)
z0 <- qnorm(1 - p)
se1 <- (u1 - l1)/(2*z0)
a2 <- round(n2/2 - sqrt(n2))
if (a2 < 1) {a2 = 1}
l2 <- y2[a2]
u2 <- y2[n2 - a2 + 1]
p <- pbinom(a2 - 1, size = n2, prob = .5)
z0 <- qnorm(1 - p)
se2 <- (u2 - l2)/(2*z0)
diff <- median1 - median2
se <- sqrt(se1^2 + se2^2)
ll <- diff - z*se
ul <- diff + z*se
out <- t(c(median1, median2, diff, se, ll, ul))
colnames(out) <- c("Median1", "Median2", "Median1-Median2", "SE", "LL", "UL")
return(out)
}
ci.ratio.median2 <- function(alpha, y1, y2) {
z <- qnorm(1 - alpha/2)
n1 <- length(y1)
y1 <- sort(y1)
n2 <- length(y2)
y2 <- sort(y2)
median1 <- median(y1)
median2 <- median(y2)
a1 <- round(n1/2 - sqrt(n1))
if (a1 < 1) {a1 = 1}
l1 <- log(y1[a1])
u1 <- log((y1[n1 - a1 + 1]))
p <- pbinom(a1 - 1, size = n1, prob = .5)
z0 <- qnorm(1 - p)
se1 <- (u1 - l1)/(2*z0)
a2 <- round(n2/2 - sqrt(n2))
if (a2 < 1) {a2 = 1}
l2 <- log(y2[a2])
u2 <- log((y2[n2 - a2 + 1]))
p <- pbinom(a2 - 1, size = n2, prob = .5)
z0 <- qnorm(1 - p)
se2 <- (u2 - l2)/(2*z0)
se <- sqrt(se1^2 + se2^2)
diff <- log(median1) - log(median2)
ll <- exp(diff - z*se)
ul <- exp(diff + z*se)
out <- t(c(median1, median2, exp(diff), ll, ul))
colnames(out) <- c("Median1", "Median2", "Median1/Median2", "LL", "UL")
return(out)
}
ci.lc.median.bs <- function(alpha, m, se, v) {
est <- t(v)%*%m
se <- sqrt(t(v)%*%diag(se^2)%*%v)
zcrit <- qnorm(1 - alpha/2)
ll <- est - zcrit*se
ul <- est + zcrit*se
out <- t(c(est, se, ll, ul))
colnames(out) <- c("Estimate", "SE", "LL", "UL")
return(out)
}
ci.median.ps <- function(alpha, y1, y2) {
z <- qnorm(1 - alpha/2)
n <- length(y1)
median1 <- median(y1)
median2 <- median(y2)
a1 <- (y1 < median1)
a2 <- (y2 < median2)
a3 <- a1 + a2
a4 <- sum(a3 == 2)
a <- round(n/2 - sqrt(n))
if (a < 1) {a = 1}
p <- pbinom(a - 1, size = n, prob = .5)
z0 <- qnorm(1 - p)
y1 <- sort(y1)
y2 <- sort(y2)
L1 <- y1[a]
U1 <- y1[n - a + 1]
se1 <- (U1 - L1)/(2*z0)
L2 <- y2[a]
U2 <- y2[n - a + 1]
se2 <- (U2 - L2)/(2*z0)
if (n/2 == trunc(n/2)) {
p00 <- (sum(a4) + .25)/(n + 1)
} else {
p00 <- (sum(a4) + .25)/n
}
cov <- (4*p00 - 1)*se1*se2
diff <- median1 - median2
se <- sqrt(se1^2 + se2^2 - 2*cov)
ll <- diff - z*se
ul <- diff + z*se
out <- t(c(median1, median2, diff, se, ll, ul, se1, se2, cov))
colnames(out) <- c("Median1", "Median2", "Median1-Median2", "SE", "LL", "UL", "SE1", "SE2", "cov")
return(out)
}
ci.ratio.median.ps <- function(alpha, y1, y2) {
z <- qnorm(1 - alpha/2)
n <- length(y1)
med1 <- median(y1)
med2 <- median(y2)
a1 <- (y1 < med1)
a2 <- (y2 < med2)
a3 <- a1 + a2
f00 <- sum(a3 == 2)
if (n/2 == trunc(n/2)) {
p00 <- (f00 + .25)/(n + 1)
} else {
p00 <- (f00 + .25)/n
}
o1 <- round(n/2 - sqrt(n))
if (o1 < 1) {o1 = 1}
o2 <- n - o1 + 1
p <- pbinom(o1 - 1, size = n, prob = .5)
z0 <- qnorm(1 - p)
y1 <- sort(y1)
y2 <- sort(y2)
l1 <- log(y1[o1])
u1 <- log(y1[o2])
se1 <- (u1 - l1)/(2*z0)
l2 <- log(y2[o1])
u2 <- log(y2[o2])
se2 <- (u2 - l2)/(2*z0)
cov <- (4*p00 - 1)*se1*se2
logratio <- log(med1/med2)
se <- sqrt(se1^2 + se2^2 - 2*cov)
ll <- exp(logratio - z*se)
ul <- exp(logratio + z*se)
out <- t(c(med1, med2, exp(logratio), ll, ul))
colnames(out) <- c("Median1", "Median2", "Median1/Median2", "LL", "UL")
return(out)
}
ci.mann <- function(alpha, y1, y2){
z <- qnorm(1 - .05/2)
y <- c(y1,y2)
n1 <- length(y1)
n2 <- length(y2)
n <- n1 + n2
r <- rank(y)
r1 <- r[1:n1]
r2 <- r[(n1 + 1):n]
m1 <- mean(r1)
m2 <- mean(r2)
seq1 <- seq(1,n1,1)
seq2 <- seq(1,n2,1)
a1 <- sum((r1 - seq1)^2)
a2 <- sum((r2 - seq2)^2)
v1 <- (a1 - n1*(m1 - (n1 + 1)/2)^2)/((n1 - 1)*n^2)
v2 <- (a2 - n2*(m2 - (n2 + 1)/2)^2)/((n2 - 1)*n^2)
u <- sum(r2) - n2*(n2 + 1)/2
est <- u/(n1*n2)
se <- sqrt((n2*v1 + n1*v2)/(n1*n2))
ll <- est - z*se
ul <- est + z*se
if (ul > 1) {ul = 1}
if (ll < 0) {ll = 0}
out <- t(c(est, se, ll, ul))
colnames(out) <- c("Estimate", "SE", "LL", "UL")
return(out)
}
ci.random.anova1 <- function(alpha, m, sd, n) {
z <- qnorm(1 - alpha/2)
a <- length(m)
t <- qt(1 - alpha/2, a - 1)
nt <- n*a
dfe <- nt - a
dfb <- a - 1
v <- sd^2
grandmean <- sum(n*m)/nt
SSe <- sum((n - 1)*v)
MSe <- SSe/dfe
SSb <- sum(n*(m - grandmean)^2)
MSb <- SSb/dfb
F <- MSb/MSe
varb <- (MSb - MSe)/n
osqr <- (MSb - MSe)/(MSb + (n - 1)*MSe)
se.mean <- sqrt(MSb/(a*n))
se.vare <- sqrt(2*MSe^2/((dfb + 1)*(n - 1)))
se.varb <- sqrt(2*(MSe^2/((dfb + 1)*(n - 1)) + MSb^2/dfb)/n^2)
LL.m <- grandmean - t*se.mean
UL.m <- grandmean + t*se.mean
LL.e <- sqrt(exp(log(MSe) - z*se.vare/MSe))
UL.e <- sqrt(exp(log(MSe) + z*se.vare/MSe))
LL.b <- sqrt(exp(log(varb) - z*se.varb/MSb))
UL.b <- sqrt(exp(log(varb) + z*se.varb/MSb))
F1 <- qf(1 - alpha/2, dfb, dfe)
F2 <- qf(alpha/2, dfb, dfe)
LL.o <- (F/F1 - 1)/(n + F/F1 - 1)
UL.o <- (F/F2 - 1)/(n + F/F2 - 1)
out1 <- t(c(grandmean, LL.m, UL.m))
out2 <- t(c(sqrt(MSe), LL.e, UL.e))
out3 <- t(c(sqrt(varb), LL.b, UL.b))
out4 <- t(c(osqr, LL.o, UL.o))
out <- rbind(out1, out2, out3, out4)
rownames(out) <- c("Grand mean", "Within SD:", "Between SD:", "Omega-squared:")
colnames(out) = c("Estimate", "LL", "UL")
return(out)
}
ci.cronbach <- function(alpha, rel, a, n) {
df1 = n - 1
df2 = n*(a - 1)
f1 = qf(1 - alpha/2, df1, df2)
f2 = qf(1 - alpha/2, df2, df1)
f0 <- 1/(1 - rel)
ll <- 1 - f1/f0
ul <- 1 - 1/(f0*f2)
out <- t(c(ll, ul))
colnames(out) = c("LL", "UL")
return(out)
}
size.ci.mean1 <- function(alpha, var, w) {
z <- qnorm(1 - alpha/2)
n <- ceiling(4*var*(z/w)^2 + z^2/2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.ci.mean2 <- function(alpha, var, w, R) {
z <- qnorm(1 - alpha/2)
n1 <- ceiling(4*var*(1 + 1/R)*(z/w)^2 + z^2/4)
n2 <- ceiling(R*n1)
out <- t(c(n1, n2))
colnames(out) <- c("n1", "n2")
return(out)
}
size.ci.stdmean2 <- function(alpha, d, w, R) {
z <- qnorm(1 - alpha/2)
n1 <- ceiling((d^2*(1 + R)/(2*R) + 4*(1 + R)/R)*(z/w)^2)
n2 <- ceiling(R*n1)
out <- t(c(n1, n2))
colnames(out) <- c("n1", "n2")
return(out)
}
size.ci.ratio.mean2 <- function(alpha, var, m1, m2, r, R) {
z <- qnorm(1 - alpha/2)
n1 <- ceiling(4*var*(1 + 1/R)*(1/m1^2 + 1/m2^2)*(z/log(r))^2 + z^2/4)
n2 <- ceiling(R*n1)
out <- t(c(n1, n2))
colnames(out) <- c("n1", "n2")
return(out)
}
size.ci.lc.mean.bs <- function(alpha, var, w, v) {
z <- qnorm(1 - alpha/2)
m <- length(v) - sum(v == 0)
n <- ceiling(4*var*(t(v)%*%v)*(z/w)^2 + z^2/(2*m))
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size per group"
return(out)
}
size.ci.lc.stdmean.bs <- function(alpha, d, w, v) {
z <- qnorm(1 - alpha/2)
a <- length(v)
n <- ceiling((2*d^2/a + 4*(t(v)%*%v))*(z/w)^2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size per group"
return(out)
}
size.ci.mean.ps <- function(alpha, var, cor, w) {
z <- qnorm(1 - alpha/2)
n <- ceiling(8*(1 - cor)*var*(z/w)^2 + z^2/2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.ci.stdmean.ps <- function(alpha, d, cor, w) {
z <- qnorm(1 - alpha/2)
n <- ceiling(4*(d^2*(1 + cor^2)/4 + 2*(1 - cor))*(z/w)^2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.ci.ratio.mean.ps <- function(alpha, var, m1, m2, cor, r) {
z <- qnorm(1 - alpha/2)
n <- ceiling(8*var*(1/m1^2 + 1/m2^2 - 2*cor/(m1*m2))*(z/log(r))^2 + z^2/2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.ci.lc.mean.ws <- function(alpha, var, cor, w, q) {
z <- qnorm(1 - alpha/2)
k <- length(q)
n <- ceiling(4*(1 - cor)*var*(t(q)%*%q)*(z/w)^2 + z^2/2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.ci.lc.stdmean.ws <- function(alpha, d, cor, w, q) {
z <- qnorm(1 - alpha/2)
a <- length(q)
n <- ceiling(4*(d^2*(1 + (a - 1)*cor^2)/(2*a) + (1 - cor)*(t(q)%*%q))*(z/w)^2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.ci.cronbach <- function(alpha, rel, a, w) {
z <- qnorm(1 - alpha/2)
n0 <- ceiling((8*a/(a - 1))*(1 - rel)^2*(z/w)^2 + 2)
df1 = n0 - 1
df2 = n0*(a - 1)
f1 = qf(1 - alpha/2, df1, df2)
f2 = qf(1 - alpha/2, df2, df1)
f0 <- 1/(1 - rel)
ll <- 1 - f1/f0
ul <- 1 - 1/(f0*f2)
w0 <- ul - ll
n <- ceiling((n0 - 2)*(w0/w)^2 + 2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.ci.second <- function(n0, w0, w) {
n <- ceiling(((w0/w)^2 - 1)*n0)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.test.mean1 <- function(alpha, pow, var, es) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
n <- ceiling(var*(za + zb)^2/es^2 + za^2/2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.test.mean2 <- function(alpha, pow, var, es, R) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
n1 <- ceiling(var*(1 + 1/R)*(za + zb)^2/es^2 + za^2/4)
n2 <- ceiling(R*n1)
out <- t(c(n1, n2))
colnames(out) <- c("n1", "n2")
return(out)
}
size.test.lc.mean.bs <- function(alpha, pow, var, es, v) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
m <- length(v) - sum(v == 0)
n <- ceiling(var*(t(v)%*%v)*(za + zb)^2/es^2 + za^2/(2*m))
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size per group"
return(out)
}
size.equiv.mean2 <- function(alpha, pow, var, es, h) {
za <- qnorm(1 - alpha)
zb <- qnorm(1 - (1 - pow)/2)
n <- ceiling(var*2*(za + zb)^2/(abs(h) - abs(es))^2 + za^2/4)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size per group"
return(out)
}
size.supinf.mean2 <- function(alpha, pow, var, es, h) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
n <- ceiling(var*2*(za + zb)^2/(es - h)^2 + za^2/4)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.test.mean.ps <- function(alpha, pow, var, es, cor) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
n <- ceiling(2*var*(1 - cor)*(za + zb)^2/es^2 + za^2/2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.test.lc.mean.ws <- function(alpha, pow, var, es, cor, q) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
n <- ceiling(var*(1 - cor)*(t(q)%*%q)*(za + zb)^2/es^2 + za^2/2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.equiv.mean.ps <- function(alpha, pow, var, es, cor, h) {
za <- qnorm(1 - alpha)
zb <- qnorm(1 - (1 - pow)/2)
n <- ceiling(2*var*(1 - cor)*(za + zb)^2/(h - abs(es))^2 + za^2/2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.supinf.mean.ps <- function(alpha, pow, var, es, cor, h) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
n <- ceiling(2*var*(1 - cor)*(za + zb)^2/(es - h)^2 + za^2/2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.test.mann <- function(alpha, pow, p) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
es <- p - .5;
n <- ceiling((za + zb)^2/(6*es^2))
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size per group"
return(out)
}
size.test.sign1 <- function(alpha, pow, p) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
es <- p - .5;
n <- ceiling(p*(1 - p)*(za + zb)^2/es^2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.test.sign.ps <- function(alpha, pow, p) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
es <- p - .5;
n <- ceiling(p*(1 - p)*(za + zb)^2/es^2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
size.test.cronbach <- function(alpha, pow, rel, a, h) {
za <- qnorm(1 - alpha/2)
zb <- qnorm(pow)
e <- (1 - rel)/(1 - h)
n <- ceiling((2*a/(a - 1))*(za + zb)^2/log(e)^2 + 2)
out <- matrix(n, nrow = 1, ncol = 1)
colnames(out) <- "Sample size"
return(out)
}
pi.score1 <- function(alpha, m, sd, n) {
df <- n - 1
tcrit <- qt(1 - alpha/2, df)
se <- sqrt(sd^2 + sd^2/n)
ll <- m - tcrit*se
ul <- m + tcrit*se
out <- t(c(m, df, ll, ul))
colnames(out) <- c("Predicted", "df", "LL", "UL")
return(out)
}
pi.score2 <- function(alpha, m1, m2, sd1, sd2, n1, n2) {
df1 <- n1 + n2 - 2
est <- m1 - m2
vp <- ((n1 - 1)*sd1^2 + (n2 - 1)*sd2^2)/df1
se1 <- sqrt(2*vp + vp/n1 + vp/n2)
tcrit1 <- qt(1 - alpha/2, df1)
ll1 <- est - tcrit1*se1
ul1 <- est + tcrit1*se1
se2 <- sqrt(sd1^2 + sd2^2 + sd1^1/n1 + sd2^2/n2)
c1 <- sd1^2 + sd1^2/n1
c2 <- sd2^2 + sd2^2/n2
df2 <- 1/((1/(n1 - 1))*(c1/(c1 + c2))^2 + (1/(n2 - 1))*(c2/(c1 + c2))^2)
tcrit2 <- qt(1 - alpha/2, df2)
ll2 <- est - tcrit2*se2
ul2 <- est + tcrit2*se2
out1 <- t(c(est, df1, ll1, ul1))
out2 <- t(c(est, df2, ll2, ul2))
out <- rbind(out1, out2)
colnames(out) <- c("Predicted", "df", "LL", "UL")
rownames(out) <- c("Equal Variances Assumed:", "Equal Variances Not Assumed:")
return(out)
}
random.sample <- function(popsize, samsize) {
out <- sort(sample(popsize, samsize, replace = FALSE, prob = NULL))
return(out)
}
randomize <- function(n) {
k <- length(n)
out <- sample(rep(1:k, n))
return(out)
}
random.y <- function(n, m, sd, min, max, dec) {
y <- sd*rnorm(n, 0, 1) + m
y1 <- 1 - as.integer(y < min)
y <- y*y1 + (1 - y1)*1
y2 <- 1 - as.integer(y > max)
y = y*y2 + (1 - y2)*max
out <- round(y, dec)
return(out)
}
ci.var.upper <- function(alpha, var, n) {
chi <- qchisq(alpha, (n - 1))
ul <- (n - 1)*var/chi
out <- matrix(ul, nrow = 1, ncol = 1)
colnames(out) <- "UL"
return(out)
}
etasqr.adj <- function(etasqr, dfeffect, dferror) {
adj <- 1 - (dferror + dfeffect)*(1 - etasqr)/dferror
out <- matrix(adj, nrow = 1, ncol = 1)
colnames(out) <- "Adjusted eta-squared"
return(out)
}
test.anova1.bs <- function(m, sd, n) {
a <- length(m)
nt <- sum(n)
dfe <- nt - a
dfa <- a - 1
v <- sd^2
grandmean <- sum(n*m)/nt
SSe <- sum((n - 1)*v)
MSe <- SSe/dfe
SSa <- sum(n*(m - grandmean)^2)
MSa <- SSa/dfa
F <- MSa/MSe
p <- 1 - pf(F, dfa, dfe)
etasqr <- SSa/(SSa + SSe)
adjetasqr <- 1 - (dfa + dfe)*(1 - etasqr)/dfe
out <- t(c(F, dfa, dfe, p, etasqr, adjetasqr))
colnames(out) <- c("F", "dfA", "dfE", "p", "eta-squared", "adj eta-squared")
return(out)
}
|
timestamp <- Sys.time()
library(caret)
library(plyr)
library(recipes)
library(dplyr)
model <- "rvmRadial"
library(caret)
library(plyr)
library(recipes)
library(dplyr)
set.seed(1)
training <- SLC14_1(30)
testing <- SLC14_1(100)
trainX <- training[, -ncol(training)]
trainY <- training$y
rec_reg <- recipe(y ~ ., data = training) %>%
step_center(all_predictors()) %>%
step_scale(all_predictors())
testX <- trainX[, -ncol(training)]
testY <- trainX$y
rctrl1 <- trainControl(method = "cv", number = 3, returnResamp = "all")
rctrl2 <- trainControl(method = "LOOCV")
rctrl3 <- trainControl(method = "none")
rctrlR <- trainControl(method = "cv", number = 3, returnResamp = "all", search = "random")
set.seed(849)
test_reg_cv_model <- train(trainX, trainY, method = "rvmRadial", trControl = rctrl1,
preProc = c("center", "scale"))
test_reg_pred <- predict(test_reg_cv_model, testX)
set.seed(849)
test_reg_cv_form <- train(y ~ ., data = training,
method = "rvmRadial", trControl = rctrl1,
preProc = c("center", "scale"))
test_reg_pred_form <- predict(test_reg_cv_form, testX)
set.seed(849)
test_reg_rand <- train(trainX, trainY,
method = "rvmRadial",
trControl = rctrlR,
tuneLength = 4,
preProc = c("center", "scale"))
set.seed(849)
test_reg_loo_model <- train(trainX, trainY, method = "rvmRadial", trControl = rctrl2,
preProc = c("center", "scale"))
set.seed(849)
test_reg_none_model <- train(trainX, trainY,
method = "rvmRadial",
trControl = rctrl3,
tuneLength = 1,
preProc = c("center", "scale"))
test_reg_none_pred <- predict(test_reg_none_model, testX)
set.seed(849)
test_reg_rec <- train(x = rec_reg,
data = training,
method = "rvmRadial",
trControl = rctrl1)
if(
!isTRUE(
all.equal(test_reg_cv_model$results,
test_reg_rec$results))
)
stop("CV weights not giving the same results")
test_reg_imp_rec <- varImp(test_reg_rec)
test_reg_pred_rec <- predict(test_reg_rec, testing[, -ncol(testing)])
test_reg_predictors1 <- predictors(test_reg_cv_model)
test_reg_predictors2 <- predictors(test_reg_cv_model$finalModel)
tests <- grep("test_", ls(), fixed = TRUE, value = TRUE)
sInfo <- sessionInfo()
timestamp_end <- Sys.time()
save(list = c(tests, "sInfo", "timestamp", "timestamp_end"),
file = file.path(getwd(), paste(model, ".RData", sep = "")))
if(!interactive())
q("no") |
NULL
qgh = function(p, A, B, g, h, c=0.8){
z2gh(stats::qnorm(p), A, B, g, h, c)
} |
context("mice.impute.2l.bin")
data("toenail2")
data <- tidyr::complete(toenail2, patientID, visit) %>%
tidyr::fill(treatment) %>%
dplyr::select(-time) %>%
dplyr::mutate(patientID = as.integer(patientID))
summary(data)
pred <- make.predictorMatrix(data)
pred["outcome", "patientID"] <- -2
test_that("mice::mice.impute.2l.bin() accepts factor outcome", {
expect_silent(imp <- mice(data, method = "2l.bin", print = FALSE, pred = pred, m = 1, maxit = 1))
expect_false(anyNA(complete(imp)))
})
data("toenail")
data <- tidyr::complete(toenail, ID, visit) %>%
tidyr::fill(treatment) %>%
dplyr::select(-month)
summary(data)
pred <- make.predictorMatrix(data)
pred["outcome", "ID"] <- -2
test_that("mice::mice.impute.2l.bin() accepts 0/1 outcome", {
expect_silent(imp <- mice(data, method = "2l.bin", print = FALSE, pred = pred, m = 1, maxit = 1))
expect_false(anyNA(complete(imp)))
}) |
range_autofit <- function(ss,
sheet = NULL,
range = NULL,
dimension = c("columns", "rows")) {
ssid <- as_sheets_id(ss)
maybe_sheet(sheet)
check_range(range)
x <- gs4_get(ssid)
range_spec <- as_range_spec(
range,
sheet = sheet,
sheets_df = x$sheets, nr_df = x$named_ranges
)
range_spec$sheet_name <- range_spec$sheet_name %||% first_visible_name(x$sheets)
s <- lookup_sheet(range_spec$sheet_name, sheets_df = x$sheets)
if (is.null(range)) {
dimension <- match.arg(dimension)
resize_req <- list(bureq_auto_resize_dimensions(
sheetId = s$id, dimension = toupper(dimension)
))
} else {
resize_req <- prepare_auto_resize_request(s$id, range_spec)
}
resize_dim <- pluck(
resize_req,
1, "autoResizeDimensions", "dimensions", "dimension"
)
gs4_bullets(c(
v = "Editing {.s_sheet {x$name}}.",
v = "Resizing one or more {tolower(resize_dim)} in \\
{.w_sheet {range_spec$sheet_name}}."
))
req <- request_generate(
"sheets.spreadsheets.batchUpdate",
params = list(
spreadsheetId = ssid,
requests = resize_req
)
)
resp_raw <- request_make(req)
gargle::response_process(resp_raw)
invisible(ssid)
}
force_cell_limits <- function(x) {
if (!is.null(x$cell_limits)) {
return(x)
}
if (is.null(x$cell_range)) {
x$cell_limits <- cell_limits()
} else {
x$cell_limits <- limits_from_range(x$cell_range)
}
x
}
check_only_one_dimension <- function(x) {
limits <- x$cell_limits
if (is.na(limits$ul[1]) && is.na(limits$lr[1])) {
return(invisible(x))
}
if (is.na(limits$ul[2]) && is.na(limits$lr[2])) {
return(invisible(x))
}
gs4_abort("
The {.arg range} must target only columns or only rows, but not both.")
}
determine_dimension <- function(x) {
limits <- x$cell_limits
if (notNA(limits$ul[1]) || notNA(limits$lr[1])) {
"ROWS"
} else {
"COLUMNS"
}
}
prepare_auto_resize_request <- function(sheet_id, range_spec) {
range_spec <- force_cell_limits(range_spec)
check_only_one_dimension(range_spec)
dimension <- determine_dimension(range_spec)
element <- if (dimension == "ROWS") 1L else 2L
list(bureq_auto_resize_dimensions(
sheetId = sheet_id,
dimension = dimension,
start = pluck(range_spec, "cell_limits", "ul", element),
end = pluck(range_spec, "cell_limits", "lr", element)
))
} |
NULL
setClass(
Class = 'TextGrid',
contains = c('list'),
slots = c(startTime = 'numeric',
endTime = 'numeric')
) |
`phmclust` <-
function(x, K, method = "separate", Sdist = "weibull", cutpoint = NULL, EMstart = NA, EMoption = "classification", EMstop = 0.01, maxiter = 100)
{
if (is.data.frame(x)) x <- as.matrix(x)
if (is.vector(x)) stop("x must be a data frame or a matrix with more than 1 columns!")
if (is.null(cutpoint)) cutpoint <- max(x, na.rm = TRUE)
pvisit.est <- (any(is.na(x)) | any(x==0))
n <- nrow(x)
p <- ncol(x)
d0 <- s.check(x=x,K=K,n=n,EMstart=EMstart,EMoption=EMoption,method=method,Sdist=Sdist)
x <- d0$x
if (is.vector(d0$EMstart)) {
EMstart <- d0$EMstart[1:(dim(x)[1])]
} else {
EMstart <- t(apply(d0$EMstart, 1, function(z) z/sum(z)))
}
method <- d0$method
likelihood <- numeric(maxiter)
iter <- 0
ConvergEM <- FALSE
if (EMoption == "classification") {
while (ConvergEM == FALSE)
{
iter <- iter + 1
d1 <- Eclass(x, EMstart, K = K, method = method, Sdist = Sdist, p, cutpoint = cutpoint)
d2 <- Mclass(x, d1$shape,d1$scale,d1$prior,K=K)
likelihood[iter+1] <- d2$lik.tot
if ((iter >= maxiter) || (abs(likelihood[iter+1]-likelihood[iter]) < EMstop)) {
ConvergEM <- TRUE
} else {
EMstart <- d2$newgr
}
}
postmat <- NULL
newgr <- d2$newgr
}
if (EMoption == "maximization") {
while (ConvergEM == FALSE)
{
iter <- iter + 1
d1 <- Emax(x, EMstart, K=K, method=method, Sdist=Sdist,p, cutpoint = cutpoint)
d2 <- Mmax(x, d1$shape,d1$scale,d1$prior,K=K)
likelihood[iter+1] <- d2$lik.tot
if ((iter >= maxiter) || (abs(likelihood[iter+1]-likelihood[iter]) < EMstop)) {
ConvergEM <- TRUE
} else {
EMstart <- d2$postmat
}
}
postmat <- d2$postmat
newgr <- apply(postmat, 1, function(y){ind <-(1:K)[y==max(y)]})
}
if (EMoption == "randomization") {
while (ConvergEM == FALSE)
{
iter <- iter + 1
d1 <- Eclass(x, EMstart, K=K, method=method, Sdist=Sdist,p, cutpoint = cutpoint)
d2 <- Mrandom(x, d1$shape,d1$scale,d1$prior,K=K)
likelihood[iter+1] <- d2$lik.tot
if ((iter >= maxiter) || (abs(likelihood[iter+1]-likelihood[iter]) < EMstop)) {
ConvergEM <- TRUE
} else {
EMstart <- d2$newgr
}
}
postmat <- d2$postmat
newgr <- d2$newgr
}
if (iter >= maxiter) warning("EM did not converge! Maximum iteration limit reached!")
if (pvisit.est) {
anzpar <- d1$anzpar + K*p
} else {
anzpar <- d1$anzpar
}
likconv <- likelihood[2:(iter+1)]
aic <- -2*(likelihood[iter+1]-anzpar)
bic <- (-2*likelihood[iter+1])+anzpar*log(n)
clmean.l <- by(x,newgr,function(y) {
apply(y,2,function(z) mean(z[z>0]))
})
clmean <- matrix(unlist(clmean.l),nrow=K,byrow=TRUE)
nobs.cl <- table(newgr)
se.clmean <- apply(x, 2, function(z1) {
Smat <- tapply(z1, newgr, function(z2) {
if (!is.null(z2[z2 > 0])) {
sd(z2[z2>0], na.rm = TRUE)
} else {
return(NA)
}
})
nobsmat <- tapply(z1, newgr, function(z3) {
if (!is.null(z3[z3 > 0])) {
length(z3[z3>0])
} else {
return(NA)
}
})
Smat/sqrt(nobsmat)
})
colnames(clmean) <- colnames(se.clmean) <- colnames(x)
rownames(clmean) <- rownames(se.clmean) <- paste("Cluster",1:K)
clmed.l <- by(x,newgr,function(y) {
apply(y,2, function(z) median(z[z>0]))
})
clmed <- matrix(unlist(clmed.l),nrow=K,byrow=TRUE)
colnames(clmed) <- colnames(x)
rownames(clmed) <- paste("Cluster",1:K)
if (is.null(colnames(x))) {
colnames(d1$scale) <- paste("V",1:dim(d1$scale)[2],sep="")
colnames(d1$shape) <- paste("V",1:dim(d1$shape)[2],sep="")
} else {
colnames(d1$scale) <- colnames(d1$shape) <- colnames(x)
}
rownames(d1$shape) <- rownames(d1$scale) <- paste("Cluster", 1:K, sep="")
pvisit <- d1$prior
se.pvisit <- apply(pvisit,2, function(z) sqrt(z*(1-z)/nobs.cl))
colnames(pvisit) <- colnames(se.pvisit) <- colnames(x)
rownames(pvisit) <- rownames(se.pvisit) <- paste("Cluster",1:K)
result <- list(K=K, iter=iter, method=method, Sdist=Sdist, likelihood=likconv, pvisit = pvisit, se.pvisit = se.pvisit,
shape = d1$shape, scale = d1$scale, group = newgr, posteriors = postmat, npar = anzpar, aic = aic, bic = bic,
clmean = clmean, se.clmean = se.clmean, clmed = clmed)
class(result) <- "mws"
result
} |
page <- function(x, method = c("dput", "print"), ...)
{
local.file.show <- function(file, title = subx, delete.file = TRUE,
pager = getOption("pager"), ...)
file.show(file, title = title, delete.file = delete.file, pager = pager)
local.dput <- function(x, file, title, delete.file, pager, ...)
dput(x, file, ...)
local.print <- function(x, title, delete.file, pager, ...)
print(x, ...)
if(is.character(x) && length(x) == 1L) {
subx <- x
parent <- parent.frame()
if(exists(subx, envir = parent))
x <- get(subx, envir = parent)
else
stop(gettextf("no object named '%s' to show", x), domain = NA)
} else {
subx <- deparse(substitute(x))
}
file <- tempfile("Rpage.")
if(match.arg(method) == "dput")
local.dput(x, file, ...)
else {
sink(file)
local.print(x, ...)
sink()
}
local.file.show(file, ...)
} |
strip_params <- function(params_raw, unique=FALSE){
params_strip <- sapply(strsplit(params_raw,'[', fixed=T),'[',1)
if(unique) return( unique(params_strip) )
params_strip
}
which_params <- function(param, params_raw){
params_strip <- strip_params(params_raw)
if( ! param %in% params_strip ){
return(NULL)
}
which(params_strip == param)
}
param_names <- function(mcmc_list, simplify=FALSE){
raw <- colnames(mcmc_list[[1]])
if(!simplify) return(raw)
strip_params(raw, unique=T)
}
match_params <- function(params, params_raw){
unlist(lapply(params, function(x){
if(x %in% params_raw) return(x)
if(!x %in% strip_params(params_raw)) return(NULL)
params_raw[which_params(x, params_raw)]
}))
}
select_cols <- function(mcmc_list, col_inds){
out <- lapply(1:length(mcmc_list), FUN=function(x){
mcmc_element <- mcmc_list[[x]][,col_inds,drop=FALSE]
attr(mcmc_element,'mcpar') <- attr(mcmc_list[[x]], 'mcpar')
class(mcmc_element) <- 'mcmc'
mcmc_element
})
class(out) <- 'mcmc.list'
out
}
mcmc_to_mat <- function(samples, param){
psamples <- select_cols(samples, param)
n_chain <- length(samples)
n_iter <- nrow(samples[[1]])
matrix(unlist(psamples), nrow=n_iter, ncol=n_chain)
} |
GEO <- function(level){
x <- NULL
if(level==1){
x1 <- github.cssegisanddata.covid19(country = "Georgia")
x2 <- ourworldindata.org(id = "GEO")
x <- full_join(x1, x2, by = "date")
}
return(x)
} |
library(checkmate)
library(testthat)
context("gs_square")
test_that("output is valid geometry", {
coords <- data.frame(x = c(40, 70, 70, 50),
y = c(40, 40, 60, 70),
fid = 1)
output <- gs_square(anchor = coords)
expect_class(output, classes = "geom")
expect_true(output@type == "polygon")
expect_data_frame(output@point, any.missing = FALSE, nrows = 5, ncols = 3)
}) |
library(testthat)
library(tryCatchLog)
context("test_user_defined_conditions.R")
source("init_unit_test.R")
source("disable_logging_output.R")
udc1 <- tryCatchLog:::condition("my_condition_class", "message1")
udc2 <- tryCatchLog:::condition("my_other_condition_class")
test_that("Correct return value if a custom condition is thrown but not logged", {
expect_null(signalCondition(udc1))
expect_true(tryCatchLog( {
signalCondition(udc1)
TRUE
}))
})
test_that("user-defined conditions are not logged by default", {
expect_silent(tryCatchLog(signalCondition(udc1)))
last.result <- last.tryCatchLog.result()
expect_equal(NROW(last.result), 0)
expect_silent(tryCatchLog(signalCondition(udc2)))
last.result <- last.tryCatchLog.result()
expect_equal(NROW(last.result), 0)
})
test_that("user-defined conditions are catched but not logged by default", {
catched <- NA
tryCatchLog(signalCondition(udc1), condition = function(c) catched <<- c)
last.result <- last.tryCatchLog.result()
expect_equal(NROW(last.result), 0)
expect_equal(class(catched), c("my_condition_class", "condition"))
})
test_that("user-defined conditions work within stacked tryCatchLog expressions", {
catched <- NA
expect_silent(tryCatchLog(tryCatchLog(signalCondition(udc1)), condition = function(c) catched <<- c))
last.result <- last.tryCatchLog.result()
expect_equal(NROW(last.result), 0)
expect_equal(class(catched), c("my_condition_class", "condition"))
catched <- NA
expect_silent(tryCatchLog(tryCatchLog(signalCondition(udc1), condition = function(c) catched <<- c)))
last.result <- last.tryCatchLog.result()
expect_equal(NROW(last.result), 0)
expect_equal(class(catched), c("my_condition_class", "condition"))
catched_inner <- NA
catched_outer <- NA
expect_silent(tryCatchLog(
tryCatchLog(signalCondition(udc1), condition = function(c) catched_inner <<- c)
, condition = function(c) catched_outer <<- c))
last.result <- last.tryCatchLog.result()
expect_equal(NROW(last.result), 0)
expect_equal(class(catched_inner), c("my_condition_class", "condition"))
expect_true(is.na(catched_outer))
expect_silent(tryCatchLog(tryCatchLog(signalCondition(udc1))))
last.result <- last.tryCatchLog.result()
expect_equal(NROW(last.result), 0)
expect_equal(class(catched), c("my_condition_class", "condition"))
}) |
op.orig <-
options(width = 79,
useFancyQuotes = FALSE,
prompt="> " , continue=" "
)
Sys.setenv(LANGUAGE = "en")
if(.Platform$OS.type != "windows")
Sys.setlocale("LC_MESSAGES","C")
PCversion <- packageDescription('pcalg')$Version
library(pcalg)
stopifnot(require(Rgraphviz))
library(graph)
showF <- function(f, width = 50) {
nam <- deparse(substitute(f))
stopifnot(is.function(f))
ll <- capture.output(str(removeSource(f), width=width))
ll[1] <- sub("function *", nam, ll[1])
writeLines(ll)
}
data("gmG", package = "pcalg")
suffStat <- list(C = cor(gmG8$x), n = nrow(gmG8$x))
varNames <- gmG8$g@nodes
skel.gmG8 <- skeleton(suffStat, indepTest = gaussCItest,
labels = varNames, alpha = 0.01)
pc.gmG8 <- pc(suffStat, indepTest = gaussCItest,
labels = varNames, alpha = 0.01)
stopifnot(require(Rgraphviz))
par(mfrow = c(1,3))
plot(gmG8$g, main = ""); box(col="gray")
plot(skel.gmG8, main = ""); box(col="gray")
plot(pc.gmG8, main = ""); box(col="gray")
data("gmL")
suffStat <- list(C = cor(gmL$x), n = nrow(gmL$x))
fci.gmL <- fci(suffStat, indepTest=gaussCItest,
alpha = 0.9999, labels = c("2","3","4","5"))
stopifnot(require(Rgraphviz))
par(mfrow = c(1,2))
plot(gmL$g) ; box(col="gray")
plot(fci.gmL); box(col="gray")
suffStat <- list(C = cor(gmL$x), n = nrow(gmL$x))
fciPlus.gmL <- fciPlus(suffStat, indepTest=gaussCItest,
alpha = 0.9999, labels = c("2","3","4","5"))
showF(ges)
score <- new("GaussL0penObsScore", gmG8$x)
ges.fit <- ges(score)
par(mfrow=1:2)
plot(gmG8$g, main = "") ; box(col="gray")
plot(ges.fit$essgraph, main = ""); box(col="gray")
data(gmInt)
n.tot <- length(gmInt$target.index)
n.obs <- sum(gmInt$target.index == 1)
n3 <- sum(gmInt$target.index == 2)
n5 <- sum(gmInt$target.index == 3)
showF(gies, width = 60)
score <- new("GaussL0penIntScore", gmInt$x, targets = gmInt$targets,
target.index = gmInt$target.index)
gies.fit <- gies(score)
simy.fit <- simy(score)
par(mfrow = c(1,3))
plot(gmInt$g, main = "") ; box(col="gray")
plot(gies.fit$essgraph, main = "") ; box(col="gray")
plot(simy.fit$essgraph, main = "") ; box(col="gray")
score <- new("GaussL0penObsScore", gmG8$x)
suffStat <- list(C = cor(gmG8$x), n = nrow(gmG8$x))
skel.fit <- skeleton(suffStat = suffStat, indepTest = gaussCItest,
alpha = 0.01, p = ncol(gmG8$x))
skel <- as(skel.fit@graph, "matrix")
ges.fit <- ges(score, fixedGaps = !skel)
score <- new("GaussL0penObsScore", gmG8$x)
library(huge)
huge.path <- huge(gmG8$x, verbose = FALSE)
huge.fit <- huge.select(huge.path, verbose = FALSE)
cig <- as.matrix(huge.fit$refit)
ges.fit <- ges(score, fixedGaps = !cig, adaptive = "vstructures")
set.seed(1234)
n <- 500
eps1 <- sign(rnorm(n)) * sqrt(abs(rnorm(n)))
eps2 <- runif(n) - 0.5
x2 <- 3 + eps2
x1 <- 0.9*x2 + 7 + eps1
X <- cbind(x1,x2)
res <- lingam(X)
res
showF(addBgKnowledge)
amat <- matrix(c(0,1,0, 1,0,1, 0,1,0), 3,3)
colnames(amat) <- rownames(amat) <- letters[1:3]
bg <- addBgKnowledge(gInput = amat, x = "a", y = "b")
par(mfrow = c(1,2))
plot(as(t(amat), "graphNEL")); box(col="gray")
plot(as(t( bg ), "graphNEL")); box(col="gray")
showF(ida)
set.seed(123)
p <- 7
myDAG <- randomDAG(p, prob = 0.2)
myCPDAG <- dag2cpdag(myDAG)
n <- 10000
dat <- rmvDAG(n, myDAG)
suffStat <- list(C = cor(dat), n = n)
pc.fit <- pc(suffStat, indepTest = gaussCItest, p=p, alpha = 0.01)
(l.ida.cpdag <- ida(2,5, cov(dat),
myCPDAG, method = "local", type = "cpdag"))
(g.ida.cpdag <- ida(2,5, cov(dat),
myCPDAG, method = "global", type = "cpdag"))
if (require(Rgraphviz)) {
par(mfrow = c(1,2))
plot(myDAG, main = "True DAG"); box(col="gray")
plot(pc.fit, main = "Estimated CPDAG"); box(col="gray")
}
p <- 6
V <- as.character(1:p)
edL <- list(
"1" = list(edges=c(3,4), weights=c(1.1,0.3)),
"2" = list(edges=c(6), weights=c(0.4)),
"3" = list(edges=c(2,4,6),weights=c(0.6,0.8,0.9)),
"4" = list(edges=c(2),weights=c(0.5)),
"5" = list(edges=c(1,4),weights=c(0.2,0.7)),
"6" = NULL)
myDAG <- new("graphNEL", nodes=V, edgeL=edL,
edgemode="directed")
myCPDAG <- dag2cpdag(myDAG)
covTrue <- trueCov(myDAG)
(resExactDAG <- jointIda(x.pos = c(1,2), y.pos = 6,
mcov = covTrue,
graphEst = myDAG,
technique = "RRC"))
(resExactCPDAG <- jointIda(x.pos = c(1,2), y.pos = 6,
mcov = covTrue,
graphEst = myCPDAG,
technique = "RRC"))
par(mfrow = c(1,2))
plot(myDAG) ; box(col="gray")
plot(myCPDAG); box(col="gray")
showF(backdoor)
p <- 6
amat <- t(matrix(c(0,0,1,1,0,1, 0,0,1,1,0,1, 0,0,0,0,1,0,
0,0,0,0,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0), 6,6))
V <- as.character(1:6)
colnames(amat) <- rownames(amat) <- V
edL <- vector("list",length=6)
names(edL) <- V
edL[[1]] <- list(edges=c(3,4,6),weights=c(1,1,1))
edL[[2]] <- list(edges=c(3,4,6),weights=c(1,1,1))
edL[[3]] <- list(edges=5,weights=c(1))
edL[[4]] <- list(edges=c(5,6),weights=c(1,1))
g <- new("graphNEL", nodes=V, edgeL=edL, edgemode="directed")
cov.mat <- trueCov(g)
myCPDAG <- dag2cpdag(g)
true.amat <- as(myCPDAG, "matrix")
par(mfrow = c(1,2))
plot(g, main = ""); box(col="gray")
plot(myCPDAG, main = ""); box(col="gray")
backdoor(true.amat, 6, 3, type="cpdag")
showF(gac)
mFig1 <- matrix(c(0,1,1,0,0,0, 1,0,1,1,1,0, 0,0,0,0,0,1,
0,1,1,0,1,1, 0,1,0,1,0,1, 0,0,0,0,0,0), 6,6)
type <- "cpdag"
x <- 3; y <- 6
gac(mFig1, x,y, z=c(2,4), type)
mFig3a <- matrix(c(0,1,0,0, 0,0,1,1, 0,0,0,1, 0,0,1,0), 4,4)
type <- "pdag"
x <- 2; y <- 4
str( gac(mFig3a,x,y, z=NULL, type) )
if (require(Rgraphviz)) {
colnames(mFig1) <- rownames(mFig1) <- as.character(1:6)
g1 <- as(t(mFig1), "graphNEL")
colnames(mFig3a) <- rownames(mFig3a) <- as.character(1:4)
g2 <- as(t(mFig3a), "graphNEL")
par(mfrow = c(1,2))
plot(g1, main = "(a)"); box(col="gray")
plot(g2, main = "(b)"); box(col="gray")
}
showF(adjustment)
n <- 100; d <- 3; s <- 2
myWgtFun <- function(m,mu,sd) { rnorm(m,mu,sd) }
set.seed(42)
dag1 <- randDAG(n=n, d=d, method = "er", DAG = TRUE)
dag2 <- randDAG(n=n, d=d, method = "power", DAG = TRUE)
w1 <- wgtMatrix(dag1)
deg1 <- apply(w1 + t(w1), 2, function(x) sum(x != 0))
max1 <- max(deg1)
mean1 <- mean(deg1)
w2 <- wgtMatrix(dag2)
deg2 <- apply(w2 + t(w2), 2, function(x) sum(x != 0))
max2 <- max(deg2)
mean2 <- mean(deg2)
n <- 100; d <- 3; s <- 2
myWgtFun <- function(m,mu,sd) { rnorm(m,mu,sd) }
set.seed(42)
dag1 <- randDAG(n=n, d=d, method = "er", DAG = TRUE,
weighted = TRUE, wFUN = list(myWgtFun, 0, s))
dag2 <- randDAG(n=n, d=d, method = "power", DAG = TRUE,
weighted = TRUE, wFUN = list(myWgtFun, 0, s))
as(pc.gmG8, "amat")
m1 <- matrix(c(0,1,0,1,0,0, 0,0,1,0,1,0, 0,0,0,0,0,1,
0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0), 6,6)
str( gac(m1, x=1,y=3, z=NULL, type = "dag") )
n <- nrow (gmG8$x)
V <- colnames(gmG8$x)
amat <- wgtMatrix(gmG8$g)
amat[amat != 0] <- 1
if(requireNamespace("dagitty")) {
dagitty_dag1 <- pcalg2dagitty(amat,V,type="dag")
dagitty::is.dagitty(dagitty_dag1)
}
set.seed(42)
p <- 4
myDAG <- randomDAG(p, prob = 0.4)
myCPDAG <- dag2cpdag(myDAG)
suffStat <- list(C = cov2cor(trueCov(myDAG)), n = 10^9)
fci.fit <- fci(suffStat, indepTest=gaussCItest,
alpha = 0.9999, p=p, doPdsep = FALSE)
if (require(Rgraphviz)) {
par(mfrow = c(1,2))
plot(myCPDAG); box(col="gray")
plot(fci.fit); box(col="gray")
}
data(gmG)
n <- nrow (gmG8$ x)
V <- colnames(gmG8$ x)
pc.fit <- pc(suffStat = list(C = cor(gmG8$x), n = n),
indepTest = gaussCItest,
alpha=0.01, labels = V, verbose = FALSE)
if (require(igraph)) {
par(mfrow = c(1,1))
iplotPC(pc.fit)
}
as(pc.fit, "amat")
as(fci.fit, "amat")
showEdgeList(pc.fit)
possible_p <- c(seq(5,10,by=1))
possible_neighb_size <- c(1:3)
num_settings <-10
num_rep <- 2
pb <- seq(0,1,by=0.5)
revealEdge <- function(c,d,s) {
if (!anyNA(s)) {
for (i in 1:nrow(s)) {
c[s[i,1], s[i,2]] <- d[s[i,1], s[i,2]]
c[s[i,2], s[i,1]] <- d[s[i,2], s[i,1]]
}
}
c
}
resFin <- vector("list", num_settings)
for(r in 1:num_settings) {
set.seed(r)
p <- sample(possible_p,1)
neigh <- sample(possible_neighb_size,1)
prob <- round(neigh/(p-1),3)
resFin[[r]] <- vector("list", num_rep)
for (i in 1:num_rep){
isEmpty <- 1
while(isEmpty){
g <- randomDAG(p, prob)
cpdag <- dag2cpdag(g)
cpdag.amat <- t(as(cpdag,"matrix"))
dag.amat <- t(as(g,"matrix"))
dag.amat[dag.amat != 0] <- 1
if (sum(dag.amat)!= 0){
isEmpty <- 0
}
}
y <- NULL
while(is.null(y)){
x <- sample(p,1)
skeleton <- cpdag.amat + t(cpdag.amat)
skeleton[skeleton == 2] <- 1
connectt <- possDe(skeleton,x, type = "pdag")
if (length(connectt) != 1) {
pa.x <- which(dag.amat[x,]==1 & dag.amat[,x]==0)
pos.y <- setdiff(setdiff(connectt, pa.x), x)
if (length(pos.y)==1){
y <- pos.y[1]
} else if (length(pos.y) > 0) {
y <- sample(pos.y, 1)
}
}
}
true_effect <- causalEffect(g,y,x)
nData <- 200
dat <- rmvDAG(nData, g)
pdag.amat <-
adjust_set <-
result_adjust_set <-
ida_effects <- vector("list", length(pb))
for (j in 1:length(pb)){
tmp <- ( (cpdag.amat + t(cpdag.amat))==2 ) &
lower.tri(cpdag.amat)
ude <- which(tmp, arr.ind = TRUE)
nbg <- round(pb[j] * nrow(ude))
sele <- if (nbg>0) ude[sample(nrow(ude), nbg),,drop=FALSE] else NA
pdag.amat[[j]] <- revealEdge(cpdag.amat, dag.amat, sele)
pdag.amat[[j]] <- addBgKnowledge(pdag.amat[[j]],
checkInput = FALSE)
if(requireNamespace("dagitty")) {
adjust <- adjustment(pdag.amat[[j]],amat.type="pdag",x,y,
set.type="canonical")
} else {
adjust <- NULL
}
adjust_set[[j]] <- if (length(adjust) > 0) adjust$'1' else NA
result_adjust_set[[j]] <- length(adjust) > 0
pdag.g <- as(t(pdag.amat[[j]]), "graphNEL")
ida_effects[[j]] <- ida(x,y,cov(dat), graphEst = pdag.g,
method = "local", type = "pdag")
if (j == 1){
time.taken.ida <-
system.time(ida(x,y,cov(dat), graphEst = pdag.g,
method = "local", type = "cpdag"))
time.taken.bida <-
system.time(ida(x,y,cov(dat), graphEst = pdag.g,
method = "local", type = "pdag"))
}
}
resFin[[r]][[i]] <- list(seed=r, p=p, prob=prob, neigh=neigh,
pb=pb, i=i, nData=nData,
dag.amat=dag.amat,
pdag.amat=pdag.amat,
x=x, y=y,
adjust_set = adjust_set,
result_adjust_set = result_adjust_set,
true_effect = true_effect,
ida_effects = ida_effects,
time.taken.ida = time.taken.ida,
time.taken.bida = time.taken.bida)
}
}
nn <- sum(sapply(resFin, length))
nBG <- length(pb)
x <- rep(NA, nn*nBG)
df1 <- data.frame(setting=x, g=x, p=x, neigh=x, pb=x,
resAdj = x, idaNum = x, idaRange = x,
timeIda = x, timeBida = x,
trueEff = x)
ii <- 0
for (i1 in 1:length(resFin)) {
nLE <- length(resFin[[i1]])
for (i2 in 1:nLE) {
for (i3 in 1:nBG) {
ii <- ii + 1
df1[ii,"setting"] <- i1
df1[ii,"g"] <- i2
df1[ii,"p"] <- resFin[[i1]][[i2]]$p
df1[ii,"neigh"] <- resFin[[i1]][[i2]]$neigh
df1[ii,"pb"] <- resFin[[i1]][[i2]]$pb[i3]
df1[ii,"resAdj"] <-
resFin[[i1]][[i2]]$result_adjust_set[[i3]]
df1[ii,"idaNum"] <-
length(unique(resFin[[i1]][[i2]]$ida_effects[[i3]]))
df1[ii,"idaRange"] <-
diff(range(resFin[[i1]][[i2]]$ida_effects[[i3]]))
df1[ii,"timeIda"] <-
resFin[[i1]][[i2]]$time.taken.ida[[1]]
df1[ii,"timeBida"] <-
resFin[[i1]][[i2]]$time.taken.bida[[1]]
df1[ii,"trueEff"] <-
resFin[[i1]][[i2]]$true_effect
}
}
}
tm1 <- tapply(X=df1$resAdj, INDEX=as.factor(df1$pb), FUN = mean)
ts1 <- tapply(X=df1$resAdj, INDEX=as.factor(df1$pb),
FUN = function(x) sd(x)/sqrt(length(x)))
dfNZ <- subset(df1, subset = (trueEff!=0) )
tm <- c(tm1,tapply(X=dfNZ$resAdj, INDEX=as.factor(dfNZ$pb),
FUN = mean))
ts <- c(ts1,tapply(X=dfNZ$resAdj, INDEX=as.factor(dfNZ$pb),
FUN = function(x) sd(x)/sqrt(length(x))))
dfID <- data.frame(pb = as.factor(names(tm)), fit = tm, se = ts,
TrueEffect =
as.factor(c(rep("All", length(tm)/2),
rep("Non-zero", length(tm)/2))))
if(require(ggplot2)) {
k <- ggplot(dfID, aes(pb, fit, ymin = fit-se,
ymax = fit+se, col = TrueEffect))
k + geom_pointrange() +
xlab("Proportion of background knowledge") +
ylab("Fraction of identifiable effects via adjustment") +
theme(legend.position = c(0.9,0.1),
axis.text=element_text(size = 14),
axis.title = element_text(size = 14),
legend.text=element_text(size = 14),
legend.title=element_text(size = 14))
}
nn <- length(pb)
idx <- rep(seq(1,nrow(df1), by = nn), each = nn)
nmbIda <- df1$idaNum[idx]
dfNU2 <- df1[nmbIda > 1,]
bnTmp <- cut(x=dfNU2$idaNum, breaks = c(0,1,2,3,4,1e9),
labels = c("1", "2", "3", "4", "5+"))
dfNU2$idaNumF <- factor(bnTmp, levels = levels(bnTmp)[5:1])
df3 <- dfNU2[,c("pb", "idaNumF")]
df3$idx <- 1:nrow(df3)
df3N <- aggregate(idx ~ pb + idaNumF, data = df3, FUN = length)
df3N$idaNumF <- droplevels(df3N$idaNumF)
ggplot(df3N, aes(x = pb, y=idx, fill = idaNumF)) +
geom_bar(stat = "identity") +
ylab("Number of simulation settings") +
xlab("Proportion of background knowledge")+
theme(axis.text = element_text(size = 14),
axis.title= element_text(size = 14),
legend.text= element_text(size = 14),
legend.title=element_text(size = 14)) +
guides(fill=guide_legend(title=" |
`chisqInd` <-
function(data,n.cat,compPval=TRUE,asMatrix=TRUE){
comp.out<-computeContCells(data,check=FALSE,n.cat=n.cat)
tmp<-comp.out$mat.exp
tmp[tmp==0]<-1
mat<-(comp.out$mat.obs-comp.out$mat.exp)^2/tmp
out<-rowSums(mat)
if(compPval)
return(compChisqPval(data,out,n.cat,asMatrix=asMatrix))
if(!asMatrix)
return(out)
mat<-matrix(0,nrow(data),nrow(data))
mat[lower.tri(mat)]<-out
if(!is.null(rownames(data)))
colnames(mat)<-rownames(mat)<-rownames(data)
return(mat)
} |
NULL
library(abind)
library(RSQLite)
library(DBI)
library(sn)
library(VGAM)
library(evd)
library(foreach)
library(parallel)
library(doParallel)
defineSHAPE <- function(shape_allow_backMutations = TRUE,
shape_collapseString = "__:__",
shape_constDist = "exp",
shape_const_relativeFitness = TRUE,
shape_const_hoodDepth = "limited",
shape_const_focal_popValue = 1e5,
shape_const_mutProb = 1e-3,
shape_const_distParameters = 20,
shape_const_distAsS = FALSE,
shape_const_RMF_initiDistance = 5,
shape_const_RMF_theta = 0.35,
shape_const_numInteractions = 4,
shape_const_fixedFrame = NULL,
shape_const_birthProb = 1,
shape_const_deathProb = 1,
shape_const_ancestFitness = 0,
shape_const_estProp = 1e-3,
shape_const_hoodThresh = 1e3,
shape_const_distType = "bottleneck",
shape_const_growthForm = "logistic",
shape_const_growthRate = 2,
shape_const_growthGenerations = NULL,
shape_db_splitTables = TRUE,
shape_death_byDensity = TRUE,
shape_death_densityCorrelation = 4,
shape_death_densityCap = NULL,
shape_envString = "shapeEnvir",
shape_externalSelfing = FALSE,
shape_external_stopFile = "someNamed.file",
shape_finalDir = NULL,
shape_genomeLength = 1e2,
shape_includeDrift = TRUE,
shape_init_distPars = c("factor"= 100,
"random"= 1),
shape_maxReplicates = 30,
shape_maxRows = 2.5e7,
shape_muts_onlyBirths = FALSE,
shape_nextID = 0,
shape_numGenerations = 100,
shape_objectStrings = c("popDemographics" = "popDemo",
"repeatability" = "evoRepeat"),
shape_postDir = NULL,
shape_recycle_repStart = 1,
shape_results_removeSteps = TRUE,
shape_run_isRecycling = c("Landscape" = TRUE,
"Steps" = FALSE,
"Parameters"=TRUE,
"Neighbourhood"=FALSE),
shape_save_batchBase = "yourJob",
shape_save_batchSet = 1,
shape_save_batchJob = 1,
shape_scaleGrowth_byDeaths = TRUE,
shape_sepString = "_",
shape_sepLines = "__and__",
shape_serverFarm = FALSE,
shape_simModel = "HoC",
shape_size_timeStep = 1,
shape_stringsAsFactors = FALSE,
shape_string_lineDescent = "_->_",
shape_string_tableNames = "numMutations",
shape_thisRep = 1,
shape_tmpGenoTable = NULL,
shape_tmp_selfScript = "~/random_nullFile.txt",
shape_use_sigFig = 4,
shape_toggle_forceCompletion = FALSE,
shape_track_asWhole = FALSE,
shape_track_distSize = NULL,
shape_workDir = NULL){
options( sapply(ls(),function(envirParms){ eval(as.name(envirParms)) },simplify=FALSE) )
if(is.null(getOption("shape_workDir"))){
options("shape_workDir" = gsub('\\','/',tempdir(),fixed=TRUE))
}
if(!grepl("/$",getOption("shape_workDir"))){
options("shape_workDir" = paste(getOption("shape_workDir"),'/',sep=""))
}
if(is.null(getOption("shape_death_densityCap"))){
options("shape_death_densityCap" = getOption("shape_const_focal_popValue"))
}
if(!any(getOption("shape_run_isRecycling"))){
options("shape_maxReplicates" = getOption("shape_thisRep"))
}
options("shape_save_batchString" = name_batchString(funcBase = getOption("shape_save_batchBase"),
func_setID = getOption("shape_save_batchSet"),
func_jobID = getOption("shape_save_batchJob"),
func_sepString = getOption("shape_sepString")))
options("shape_outDir" = paste(getOption("shape_workDir"),
getOption("shape_save_batchString"),
"/",sep=""))
if(is.null(getOption("shape_postDir"))){ options("shape_postDir" = paste(getOption("shape_workDir"), "postAnal/",sep="")) }
for(thisArgument in c("shape_outDir","shape_postDir")){
func_tmpValue <- getOption(thisArgument)
if(!grepl("/$",func_tmpValue)){
options(setNames(list(paste(gsub("[\\]+$","",func_tmpValue),"/",sep="")),
thisArgument))
}
if(!dir.exists(getOption(thisArgument))){
dir.create(getOption(thisArgument),recursive = TRUE)
}
}
if(is.null(getOption("shape_finalDir"))){
options("shape_finalDir" = getOption("shape_outDir"))
}
options("shape_processedData_filePattern" = paste("processed_runData_from_",
getOption("shape_save_batchBase"),
sep=""))
options("shape_processedData_fileName" = paste(getOption("shape_outDir"),
"processed_runData_from_",
getOption("shape_save_batchString"),
"_",
getOption("shape_thisRep"),
".RData",sep=""))
options("shape_procExp_filenames" = c("fileList"= paste(getOption("shape_postDir"),
"allFiles_from_",
getOption("shape_save_batchBase"),
".RData",sep=""),
"parameters"= paste(getOption("shape_postDir"),
"jobParameters_from_",
getOption("shape_save_batchBase"),
".RData",sep=""),
"popDemographics"= paste(getOption("shape_postDir"),
"popDemographics_from_",
getOption("shape_save_batchBase"),
".RData",sep=""),
"repeatability"= paste(getOption("shape_postDir"),
"repeatabilityData_from_",
getOption("shape_save_batchBase"),
".RData",sep="")))
options( list("shape_max_numMutations" = 1,
"shape_popMat_colnames" = c("numMuts","genotypeID","popSize","fitness"),
"shape_reportMat_colnames" = c("numMuts","genotypeID","popSize","fitness","births","deaths","mutants","progenitor"),
"shape_processedObjects" = c("runDemographics","info_estLines"),
"shape_const_siteStates" = c(0,1),
"shape_init_distSteps" = compute_distGrowth(func_distFactor = if(getOption("shape_const_growthForm") == "logistic"){
getOption("shape_init_distPars")
}else{
0
},
func_growthType = getOption("shape_const_growthForm"),
func_distType = getOption("shape_const_distType"),
func_growthRate = getOption("shape_const_growthRate"),
func_popSize = getOption("shape_const_focal_popValue"),
func_focalSize = getOption("shape_const_focal_popValue"),
func_manualGenerations = if(getOption("shape_const_growthForm") == "constant"){
getOption("shape_numGenerations")
} else {
getOption("shape_const_growthGenerations")
},
func_stepDivs = getOption("shape_size_timeStep")),
"shape_saveParameters" = list("Population"= c("shape_const_focal_popValue",
"shape_genomeLength",
"shape_const_mutProb",
"shape_muts_onlyBirths",
"shape_numGenerations",
"shape_size_timeStep",
"shape_const_deathProb",
"shape_death_byDensity",
"shape_death_densityCorrelation",
"shape_death_densityCap",
"shape_const_ancestFitness",
"shape_const_estProp"),
"Growth_Disturbance"= c("shape_const_distType",
"shape_const_growthGenerations",
"shape_init_distPars",
"shape_track_distSize",
"shape_const_growthForm",
"shape_const_growthRate",
"shape_scaleGrowth_byDeaths",
"shape_includeDrift"),
"FitnessLandscape"= c("shape_simModel",
"shape_max_numMutations",
"shape_const_relativeFitness",
"shape_allow_backMutations",
"shape_const_distAsS"),
"NK_modelElements" = c("shape_const_numInteractions",
"shape_const_NK_interactionMat",
"shape_const_siteBystate_fitnessMat"),
"RMF_modelElements" = c("shape_const_RMF_theta",
"shape_const_RMF_indWeight",
"shape_const_RMF_initiDistance",
"shape_const_RMF_globalOptima"),
"Fixed_Landscape"=c("shape_const_fixedFrame"),
"DFE"= c("shape_constDist",
"shape_const_distParameters"),
"DataManagement" = c("shape_sepString",
"shape_collapseString",
"shape_string_tableNames",
"shape_db_splitTables",
"shape_maxRows",
"shape_thisRep",
"shape_maxReplicates",
"shape_save_batchBase",
"shape_save_batchSet",
"shape_save_batchJob",
"shape_save_batchString",
"shape_save_batchIndex",
"shape_fileName_dataBase"))) )
invisible( NULL )
}
buildPedigree <- function(func_focalID){
return( sapply(as.character(func_focalID),function(thisID){
list()
},simplify=FALSE) )
}
findParent <- function(func_focalGenotype, func_startStep, func_stepMatrix, func_progenitorList,
func_demoArray, func_pedigreeAll, func_lineString = getOption("shape_string_lineDescent")){
func_missingSteps <- rownames(func_stepMatrix)[which(func_stepMatrix[,"popSize"] == 0)]
func_missingSteps <- as.numeric(nameTable_step(func_missingSteps,funcSplit = TRUE))
func_missingSteps <- func_missingSteps[which(func_missingSteps < func_startStep)]
if(length(func_missingSteps) == 0){
return( func_focalGenotype )
} else {
func_fociParents <- unlist(lapply(names(func_progenitorList),function(thisProgenitor){
if(is.element(max(func_missingSteps+1), func_progenitorList[[thisProgenitor]])){
return( thisProgenitor )
} else {
return( NULL )
}
}))
return( paste(unlist(lapply(func_fociParents,function(thisProgenitor){
findParent(func_focalGenotype = as.numeric(thisProgenitor),
func_startStep = max(func_missingSteps),
func_stepMatrix = func_demoArray[,, thisProgenitor],
func_progenitorList = func_pedigreeAll[[thisProgenitor]],
func_demoArray = func_demoArray,
func_pedigreeAll = func_pedigreeAll)
})),
func_focalGenotype,
sep= func_lineString) )
}
}
extract_popDemographics <- function(func_stepsCon, func_estValue, func_landscapeCon, func_hoodCon, func_size_timeStep){
func_allTables <- unlist(RSQLite::dbListTables(func_stepsCon))
func_allTables <- func_allTables[order(as.numeric(nameTable_step(func_allTables,funcSplit = TRUE)), decreasing = FALSE)]
tmpReturn <- list("demoMat"= matrix(-1,nrow = length(func_allTables), ncol = 8,
dimnames = list(func_allTables,c("minFit","meanFit","maxFit","sdFit","numLines","numEstablished","numMutants","popSize"))),
"transitionMat" = matrix(-1,ncol=5,dimnames=list(NULL,c("Step","genotypeID","numMuts","fitness","transitionGens"))),
"vec_estLineages" = 0,
"vec_final_estLineages" = 0,
"Hists" = vector(mode="list",length=length(func_allTables)))
names(tmpReturn[["Hists"]]) <- func_allTables
for(thisStep in func_allTables){
tmpData <- dbGetQuery(func_stepsCon, paste("SELECT numMuts, genotypeID, popSize, fitness, mutants FROM ",thisStep,sep=""))
tmpData[which(tmpData[,"popSize"] <= 0),"popSize"] <- 1e-1
tmp_estLineages <- querryEstablished(func_inMatrix = tmpData, func_estProp = func_estValue)
if(nrow(tmp_estLineages) > 0){
tmpReturn[["vec_estLineages"]] <- unique(c(tmpReturn[["vec_estLineages"]], tmp_estLineages$genotypeID))
if(thisStep == func_allTables[length(func_allTables)]){
tmpReturn$vec_final_estLineages <- tmp_estLineages$genotypeID
}
}
tmp_maxLine <- tmpData[which(tmpData$popSize == max(tmpData$popSize)),]
tmp_transRow <- which(tmpReturn[["transitionMat"]][,"Step"] == max(tmpReturn[["transitionMat"]][,"Step"]))
if(any(!is.element(tmp_maxLine$genotypeID,tmpReturn[["transitionMat"]][tmp_transRow,"genotypeID"]))){
tmpReturn[["transitionMat"]] <- rbind(tmpReturn[["transitionMat"]],
matrix(c(rep(as.numeric(nameTable_step(thisStep,funcSplit = TRUE)),nrow(tmp_maxLine)),
tmp_maxLine$genotypeID,
tmp_maxLine$numMuts,
tmp_maxLine$fitness,
rep(as.numeric(nameTable_step(thisStep,funcSplit = TRUE)) * func_size_timeStep -
ifelse(tmpReturn[["transitionMat"]][nrow(tmpReturn[["transitionMat"]]),"Step"] != -1,tmpReturn[["transitionMat"]][nrow(tmpReturn[["transitionMat"]]),"Step"],0)* func_size_timeStep,
nrow(tmp_maxLine)) ),
nrow=nrow(tmp_maxLine)))
}
tmpReturn[["demoMat"]][thisStep,] <- c(min(tmpData$fitness),
weighted.mean(tmpData$fitness,tmpData$popSize),
max(tmpData$fitness),
if(nrow(tmpData) == 1){ 0 } else { sd(tmpData[,"fitness"]* tmpData[,"popSize"]/sum(tmpData[,"popSize"])) },
nrow(tmpData),
nrow(tmp_estLineages),
sum(tmpData$mutants),
sum(tmpData$popSize))
tmp_fitHist <- hist(tmpData$fitness,plot=FALSE)
tmp_fitHist$counts <- log10(if(length(tmp_fitHist$counts) > 1){
sapply(1:length(tmp_fitHist$counts),function(x){
if(x == 1){
sum(tmpData$popSize[intersect(which(tmpData$fitness >= tmp_fitHist$breaks[x]),
which(tmpData$fitness <= tmp_fitHist$breaks[x+1]))])
} else {
sum(tmpData$popSize[intersect(which(tmpData$fitness > tmp_fitHist$breaks[x]),
which(tmpData$fitness <= tmp_fitHist$breaks[x+1]))])
}
})
} else {
sum(tmpData$popSize)
})
tmp_sizeHist <- hist(log10(tmpData$popSize),plot = FALSE)
tmp_sizeHist$counts <- log2(tmp_sizeHist$counts)
tmp_fitHist$counts[which(tmp_sizeHist$counts == "-Inf")] <- -1
tmp_sizeHist$counts[which(tmp_sizeHist$counts == "-Inf")] <- -1
tmpReturn[["Hists"]][[thisStep]] <- list("fitness"= tmp_fitHist,
"lines"= tmp_sizeHist)
}
tmpReturn[["transitionMat"]] <- matrix(tmpReturn[["transitionMat"]][-1,],ncol=ncol(tmpReturn[["transitionMat"]]), dimnames= dimnames(tmpReturn[["transitionMat"]]))
return( tmpReturn )
}
extractInfo_focalID <- function(func_focalID, func_estValue, func_stepsCon, func_landscapeCon,func_hoodCon, func_refMatrix, func_subNaming,
func_genomeLength = getOption("shape_genomeLength"), func_max_numMutations = getOption("shape_max_numMutations"),
func_allow_backMutations = getOption("shape_allow_backMutations"), func_descentSep = getOption("shape_string_lineDescent"),
func_hoodExplore = getOption("shape_const_hoodDepth"), func_stringSep = getOption("shape_sepString")){
func_allTables <- unlist(RSQLite::dbListTables(func_stepsCon))
func_allTables <- func_allTables[order(as.numeric(nameTable_step(func_allTables,funcSplit = TRUE)), decreasing = TRUE)]
func_focalID <- func_focalID[order(func_focalID)]
func_lineageDemographics <- array(-1,dim=c(length(func_allTables),5,length(func_focalID)),
dimnames=list(func_allTables,c("Step","popSize","isEstablished","births","mutsIn"),as.character(func_focalID)))
func_pedigreeFrame <- buildPedigree(func_focalID[order(func_focalID)])
for(thisTable in func_allTables){
tmpIndex <- which(func_allTables == thisTable)
tmpData <- dbGetQuery(func_stepsCon, paste("SELECT * FROM ",thisTable," WHERE genotypeID IN (",
paste(unique(names(func_pedigreeFrame)),collapse=","),
")",sep=""))
tmp_estLines <- querryEstablished(func_inMatrix = tmpData, func_estProp = func_estValue)
for(func_thisMatrix in unique(names(func_pedigreeFrame))){
func_dataRow <- which(tmpData[,"genotypeID"] == func_thisMatrix)
if(!is.element(func_thisMatrix, dimnames(func_lineageDemographics)[[3]])){
func_lineageDemographics <- abind(func_lineageDemographics,
array(-1,dim=c(length(func_allTables),5,length(func_thisMatrix)),
dimnames=list(func_allTables,c("Step","popSize","isEstablished","births","mutsIn"), func_thisMatrix)) )
}
if(length(func_dataRow) > 0){
func_tmpSum <- sum(unlist(lapply(strsplit(tmpData[func_dataRow,"progenitor"], getOption("shape_collapseString"))[[1]],function(x){
as.numeric(strsplit(x,func_stringSep)[[1]][2])
})),na.rm=TRUE)
func_lineageDemographics[thisTable,,as.character(func_thisMatrix)] <- c(as.numeric(nameTable_step(thisTable,funcSplit = TRUE)),
tmpData[func_dataRow,"popSize"],
is.element(func_thisMatrix, tmp_estLines[,"genotypeID"]),
tmpData[func_dataRow,"births"] - func_tmpSum,
func_tmpSum)
} else {
func_lineageDemographics[thisTable,,as.character(func_thisMatrix)] <- c(as.numeric(nameTable_step(thisTable,funcSplit = TRUE)),
rep(0,4))
}
if(length(func_dataRow) > 0){
if(!is.element(tmpData[func_dataRow,"progenitor"],c("","WT"))){
func_tmpParents <- unlist(lapply(strsplit(tmpData[func_dataRow,"progenitor"], getOption("shape_collapseString"))[[1]],function(x){
tmpReturn <- as.numeric(strsplit(x,func_stringSep)[[1]][1])
if(is.na(tmpReturn) || is.null(tmpReturn)){
return( NULL )
} else {
return( tmpReturn )
}
}))
func_missingParents <- func_tmpParents[which(!is.element(func_tmpParents, names(func_pedigreeFrame)))]
if(length(func_missingParents) > 0){
func_pedigreeFrame <- c(func_pedigreeFrame,
buildPedigree(func_focalID = func_missingParents))
}
}
}
}
tmpData <- dbGetQuery(func_stepsCon, paste("SELECT * FROM ",thisTable," WHERE genotypeID IN (",
paste(unique(names(func_pedigreeFrame)),collapse=","),
")",sep=""))
for(func_thisID in unique(names(func_pedigreeFrame))){
func_dataRow <- which(tmpData[,"genotypeID"] == as.numeric(func_thisID))
if (length(func_dataRow) > 0 && !is.element(tmpData[func_dataRow,"progenitor"],c("","WT"))){
func_tmpParents <- unlist(lapply(strsplit(tmpData[func_dataRow,"progenitor"], getOption("shape_collapseString"))[[1]],function(x){
tmpReturn <- as.numeric(strsplit(x,func_stringSep)[[1]][1])
if(is.na(tmpReturn) || is.null(tmpReturn)){
return( NULL )
} else {
return( tmpReturn )
}
}))
for(func_thisParent in as.character(func_tmpParents)){
func_recordStep <- as.numeric(nameTable_step(thisTable,funcSplit = TRUE))
if(is.element(func_thisParent,names(func_pedigreeFrame[[func_thisID]]))){
func_pedigreeFrame[[func_thisID]][[func_thisParent]] <- c(func_pedigreeFrame[[func_thisID]][[func_thisParent]], func_recordStep)
} else {
func_pedigreeFrame[[func_thisID]][[func_thisParent]] <- func_recordStep
}
}
}
}
}
func_startGenotypes <- unname(unlist(dbGetQuery(func_stepsCon, paste("SELECT genotypeID FROM ",nameTable_step(0),sep=""))))
func_endFoci <- intersect(func_focalID, unname(unlist(dbGetQuery(func_stepsCon, paste("SELECT genotypeID FROM ", func_allTables[1],sep="")))))
func_nonEndFoci <- setdiff(func_focalID, c(func_startGenotypes, func_endFoci))
func_endLineages <- list()
for(thisFoci in func_endFoci){
func_endLineages[[as.character(thisFoci)]] <- findParent(func_focalGenotype = thisFoci,
func_startStep = as.numeric(nameTable_step(rownames(func_lineageDemographics)[which(func_lineageDemographics[,"popSize",as.character(thisFoci)] > 0)[1]],funcSplit = TRUE)),
func_stepMatrix = func_lineageDemographics[,,as.character(thisFoci)],
func_progenitorList = func_pedigreeFrame[[as.character(thisFoci)]],
func_demoArray = func_lineageDemographics,
func_pedigreeAll = func_pedigreeFrame)
}
func_nonendLineages <- list()
if(length(func_nonEndFoci) > 0){
for(thisFoci in func_nonEndFoci){
func_nonendLineages[[as.character(thisFoci)]] <- findParent(func_focalGenotype = thisFoci,
func_startStep = as.numeric(nameTable_step(rownames(func_lineageDemographics)[which(func_lineageDemographics[,"popSize",as.character(thisFoci)] > 0)[1]],funcSplit = TRUE)),
func_stepMatrix = func_lineageDemographics[,,as.character(thisFoci)],
func_progenitorList = func_pedigreeFrame[[as.character(thisFoci)]],
func_demoArray = func_lineageDemographics,
func_pedigreeAll = func_pedigreeFrame)
}
}
func_landTables <- RSQLite::dbListTables(func_landscapeCon)
func_uniqueTransitions <- unique(unlist(lapply(strsplit(as.character(unique(unlist(c(func_endLineages, func_nonendLineages)))), func_descentSep),function(thisLineage){
if(length(thisLineage) > 1){
return( paste(thisLineage[-length(thisLineage)], thisLineage[-1],sep= func_descentSep) )
} else {
NULL
}
})))
func_uniquetransitionIDs <- unique(unlist(strsplit(as.character(unique(unlist(c(func_endLineages, func_nonendLineages)))), func_descentSep)))
func_refInfo <- matrix(c(as.numeric(func_uniquetransitionIDs),rep(-1,length(func_uniquetransitionIDs) *2)),
ncol=3,dimnames=list(func_uniquetransitionIDs,c("genotypeID","numMuts","fitness")))
if(!is.null(func_refMatrix)){
func_tmpIDs <- intersect(unique(func_refMatrix[,"genotypeID"]), as.numeric(func_uniquetransitionIDs))
func_refInfo[as.character(func_tmpIDs),c("numMuts","fitness")] <- func_refMatrix[unlist(lapply(func_tmpIDs,function(x){
which(func_refMatrix[,"genotypeID"] == x)[1]
})),
c("numMuts","fitness")]
}
func_missIDs <- unname(unlist(apply(func_refInfo,MARGIN=1,function(thisLine){
if(any(thisLine[c("genotypeID","numMuts","fitness")] == -1)){
return( thisLine["genotypeID"] )
} else {
return( NULL )
}
})))
if(length(func_missIDs) > 0){
func_updateInformation <- dbGetQuery(func_landscapeCon, paste("SELECT genotypeID,binaryString,fitness FROM ",
func_landTables,
' WHERE genotypeID IN(',
paste(func_missIDs,collapse=","),
')',
collapse=" UNION "))
func_updateInformation[,"binaryString"] <- unlist(lapply(strsplit(func_updateInformation[,"binaryString"],func_stringSep),length))
colnames(func_updateInformation)[which(colnames(func_updateInformation) == "binaryString")] <- "numMuts"
for(thisCol in c("numMuts","fitness")){
func_refInfo[as.character(func_missIDs[order(func_missIDs)]),thisCol] <- func_updateInformation[order(func_updateInformation[,"genotypeID"]), thisCol]
}
}
func_hoodTables <- RSQLite::dbListTables(func_hoodCon)
func_rankMat <- if(is.null(func_uniqueTransitions)){
NULL
} else {
t(sapply(func_uniqueTransitions,function(thisTransition){
tmp_transitionInfo = func_refInfo[strsplit(thisTransition, func_descentSep)[[1]],]
tmp_mutsRange <- max(0,(tmp_transitionInfo[1,"numMuts"] - if(func_allow_backMutations){ func_max_numMutations }else{ 0 })):
min(func_genomeLength ,(tmp_transitionInfo[1,"numMuts"] + (func_max_numMutations)))
tmp_parent_binaryString <- retrieve_binaryString(func_genotypeID = tmp_transitionInfo[1,"genotypeID"],
func_numMuts = tmp_transitionInfo[1,"numMuts"],
func_subNaming = func_subNaming,
func_landscapeCon = func_landscapeCon)[1,"binaryString"]
tmp_parentalHood <- unique(c(tmp_parent_binaryString,
if(is.element(nameTable_neighbourhood(tmp_transitionInfo[1,"genotypeID"]), func_hoodTables)){
dbGetQuery(func_hoodCon,paste("SELECT * FROM ",nameTable_neighbourhood(tmp_transitionInfo[1,"genotypeID"]),sep=""))$neighbours
} else {
defineNeighbours(func_tmpGenotype = tmp_parent_binaryString,
func_tmpDirection = func_allow_backMutations)
}))
tmp_tmpStrings <- gsub("[[:space:]]","",paste("\'", tmp_parentalHood,"\'",collapse=','))
tmp_querryTables <- func_landTables[unique(unlist(lapply(nameTable(tmp_mutsRange),function(tmpTable){
which(grepl(tmpTable, func_landTables))
})))]
tmp_hoodFit <- unlist(lapply(tmp_querryTables,function(thisTable){
unlist(dbGetQuery(func_landscapeCon, paste('SELECT fitness FROM ',
thisTable,
' WHERE binaryString IN (',
tmp_tmpStrings,
')',
sep="")))
}), use.names=FALSE)
tmp_hoodFit <- tmp_hoodFit[order(tmp_hoodFit, decreasing = TRUE)]
tmp_childRank <- which(tmp_hoodFit == tmp_transitionInfo[2,"fitness"])[1]
tmp_altPaths <- if(is.element(tmp_transitionInfo[1,"fitness"], tmp_hoodFit)){
which(tmp_hoodFit == tmp_transitionInfo[1,"fitness"])[1] - 1
} else {
0
}
return( c("absRank"= tmp_childRank,
"hoodSize"=length(tmp_parentalHood),
"hoodMin"=min(tmp_hoodFit),
"hoodMax"=max(tmp_hoodFit),
"progenitor_numMuts"= tmp_transitionInfo[1,"numMuts"],
"progenitor_fitness"= tmp_transitionInfo[1,"fitness"],
"offspring_numMuts"= tmp_transitionInfo[2,"numMuts"],
"offspring_fitness"= tmp_transitionInfo[2,"fitness"],
"progenitorID"=tmp_transitionInfo[1,"genotypeID"],
"offspringID"=tmp_transitionInfo[2,"genotypeID"],
"num_altPaths"= tmp_altPaths,
"relFit_altPaths" = if(tmp_altPaths > 0 && tmp_altPaths >= tmp_childRank){
calc_relativeFitness(tmp_hoodFit[1:tmp_altPaths])[tmp_childRank]
} else {
0
},
"prop_maxFit" = if(tmp_altPaths > 0 && tmp_altPaths >= tmp_childRank){
(tmp_altPaths - (tmp_childRank -1)) / tmp_altPaths
} else {
0
}) )
}))
}
return( list("lineDemo"=func_lineageDemographics,
"linePedigree"=func_pedigreeFrame,
"landscapeTopology"=func_rankMat,
"end_Lines_of_Descent"=func_endLineages,
"transition_Lines_of_Descent"=func_nonendLineages) )
}
runProcessing <- function(func_saveFile, func_subNaming, func_stepsCon,
func_landscapeCon, func_hoodCon, func_estProp, func_size_timeStep,
func_processObjects = getOption("shape_processedObjects"),
func_hoodPriority = getOption("shape_const_hoodDepth")){
if(file.exists(func_saveFile)){
return( paste("Found a pre-processed file of same expected name: ", func_saveFile," did not perform processing of run",sep="") )
} else {
runDemographics <- extract_popDemographics(func_stepsCon = func_stepsCon, func_estValue = func_estProp,
func_landscapeCon = func_landscapeCon, func_hoodCon = func_hoodCon,
func_size_timeStep = func_size_timeStep)
info_estLines <- extractInfo_focalID(func_focalID = runDemographics[["vec_estLineages"]],
func_estValue = func_estProp,
func_stepsCon = func_stepsCon,
func_landscapeCon = func_landscapeCon,
func_hoodCon = func_hoodCon,
func_refMatrix = runDemographics[["transitionMat"]],
func_subNaming = func_subNaming,
func_descentSep = getOption("shape_string_lineDescent"),
func_hoodExplore = func_hoodPriority)
save(list= func_processObjects, file= func_saveFile)
if(file.exists(func_saveFile)){
return( paste("Processing completed for :", func_saveFile,sep="") )
} else {
return( paste("Save of :", func_saveFile,", failed as file does not exist.",sep="") )
}
}
}
growthFunction <- function(func_inSize, func_inFitness, func_bProb, func_dProb, func_deathDen_logical = FALSE, func_deathDen_max = NULL,
func_deathDen_power = 4,func_sizeStep, func_growthForm = c("logistic","exponential","constant","poisson"),
func_carryingCapacity = NULL, func_basalRate = NULL, func_deathScale = FALSE,
func_drift = TRUE, func_roundValues = FALSE, func_inIDs = NULL){
func_growthForm <- func_growthForm[1]
if(!is.element(func_growthForm[1],
eval(as.list(args(growthFunction))$func_growthForm))){
stop(paste("Incorrect growth form was passed as being ", func_growthForm," please review",sep=""))
}
if(all(func_inSize == 0)){
return( func_inSize )
} else if( any(is.element(func_inSize,c("NaN","-Inf","Inf"))) ){
stop("One of the population elements had NaN, or Inf size, please review")
}
func_tmpDeaths <- deathFunction(func_inSize = func_inSize,
func_inProb = func_dProb * func_sizeStep,
func_roundValues = func_roundValues,
func_depDensity = func_deathDen_logical,
func_densityMax = func_deathDen_max,
func_densityPower = func_deathDen_power)
func_tmpBirths <- birthFunction(func_inSize = func_inSize,
func_inFitness = func_inFitness,
func_bProb = func_bProb,
func_sizeStep = func_sizeStep,
func_growthForm = func_growthForm,
func_deaths = func_tmpDeaths,
func_carryingCapacity = func_carryingCapacity,
func_basalRate = func_basalRate,
func_deathScale = func_deathScale,
func_drift = func_drift,
func_roundValues = func_roundValues)
return( matrix(c(func_tmpBirths,func_tmpDeaths),ncol=2,
dimnames=list(func_inIDs,c("births","deaths"))) )
}
birthFunction <- function(func_inSize, func_inFitness, func_bProb, func_sizeStep, func_growthForm = c("logistic","exponential","constant","poisson"),
func_deaths = NULL, func_carryingCapacity = NULL, func_basalRate = NULL, func_deathScale = FALSE, func_drift = TRUE,
func_roundValues = TRUE){
func_numBirths <- if(func_growthForm == "exponential"){
tmpBirths <- expGrowth(func_rate= func_inFitness * func_bProb *
if(!is.null(func_basalRate)){func_basalRate}else{2},
func_step= func_sizeStep,
func_startPop= func_inSize) -
(func_inSize - if(func_deathScale){func_deaths}else{0})
if(func_drift){
tmpUpdate <- which(tmpBirths %%1 != 0)
tmpBirths[tmpUpdate] <- addDrift(tmpBirths[tmpUpdate], func_integerValues = func_roundValues)
}
tmpBirths
} else if (func_growthForm == "logistic"){
func_densityTerm <- (logisticMap(func_rate= func_inFitness * func_bProb * func_sizeStep *
if(!is.null(func_basalRate)){func_basalRate}else{2},
func_startPop= sum(func_inSize),
func_maxPop= func_carryingCapacity)/sum(func_inSize)) - 1
tmpBirths <- (func_inSize * func_densityTerm) +
if(func_deathScale && !all(func_deaths == 0)){
birthFunction(func_inSize = func_inSize,
func_inFitness = func_inFitness,
func_bProb = func_bProb,
func_sizeStep = func_sizeStep,
func_growthForm = "constant",
func_deaths = func_deaths,
func_carryingCapacity = func_carryingCapacity,
func_basalRate = func_basalRate,
func_deathScale = FALSE,
func_drift = FALSE,
func_roundValues = func_roundValues)
}else{
0
}
if(func_drift){
tmpUpdate <- which(tmpBirths %%1 != 0)
tmpBirths[tmpUpdate] <- addDrift(tmpBirths[tmpUpdate], func_integerValues = func_roundValues)
}
tmpBirths
} else if (func_growthForm == "poisson"){
unlist(lapply(func_inSize * func_inFitness * func_bProb * func_sizeStep,function(thisLineage){ rpois(1,thisLineage) }))
} else if(func_growthForm == "constant"){
tmpBirths <- unlist(lapply(func_inSize * calc_relativeFitness(func_fitVector = func_inFitness) * func_bProb * func_sizeStep,
function(thisLineage){
if(func_drift){
addDrift(thisLineage, func_integerValues = func_roundValues)
} else {
thisLineage
} }))
if(sum(tmpBirths) != 0){
tmpBirths <- tmpBirths/sum(tmpBirths) * sum(func_deaths)
}
tmpBirths
}
if(func_roundValues){
tmpUpdate <- which(func_numBirths %%1 != 0)
if(length(tmpUpdate) > 0){
func_numBirths[tmpUpdate] <- unlist(lapply(func_numBirths[tmpUpdate], function(thisValue){
if(sign(thisValue) == 1){
floor(thisValue) + rbinom(1,1, thisValue %%1)
} else {
ceiling(thisValue) - rbinom(1,1, thisValue %%1)
}
}))
}
}
if(func_growthForm == "logistic"){
if((sum(func_inSize, func_numBirths) - if(func_deathScale){sum(func_deaths)}else{0}) > func_carryingCapacity && !all(func_numBirths == 0)){
func_numBirths <- adjustBirths(func_adjVector= func_numBirths,
func_sumTotal= func_carryingCapacity - sum(func_inSize) + if(func_deathScale){sum(func_deaths)}else{0},
func_roundValues = func_roundValues)
}
} else if(func_growthForm == "constant"){
if(sum(func_numBirths) != sum(func_deaths) && !all(func_numBirths == 0)){
func_numBirths <- adjustBirths(func_adjVector= func_numBirths,
func_sumTotal= sum(func_deaths),
func_roundValues = func_roundValues)
}
}
return( func_numBirths )
}
deathFunction <- function(func_inSize, func_inProb = 0, func_roundValues = TRUE,
func_depDensity = FALSE, func_densityMax = NULL, func_densityPower = 4){
func_tmpReturn <- if(func_depDensity && !is.null(func_densityMax)){
func_inSize * func_inProb * (sum(func_inSize)/func_densityMax)^ func_densityPower
} else {
func_inSize * func_inProb
}
if(func_roundValues && any(func_tmpReturn %% 1 != 0)){
func_tmpUpdates <- which(func_tmpReturn %% 1 != 0)
func_tmpReturn[func_tmpUpdates] <- unlist(lapply(func_tmpReturn[func_tmpUpdates],function(thisPop){
floor(thisPop) + rbinom(1, size = 1, prob = thisPop %% 1)
}))
}
return( func_tmpReturn )
}
mutationFunction <- function(func_inSize, func_inProb = 0){
func_tmpReturn <- func_inSize * func_inProb
func_tmpUpdates <- which(func_tmpReturn %% 1 != 0)
func_tmpReturn[func_tmpUpdates] <- unlist(lapply(func_tmpReturn[func_tmpUpdates],function(thisPop){
floor(thisPop) + rbinom(1, size = 1, prob = thisPop %% 1)
}))
return( func_tmpReturn )
}
addDrift <- function(func_inVector, func_integerValues = TRUE){
func_integerValues = TRUE
sign(func_inVector) * unlist(lapply(abs(func_inVector),function(thisValue){
if(func_integerValues){
rpois(1,thisValue)
} else {
func_tmpShape <- thisValue
func_tmpRate <- 1 + (1.6/func_tmpShape)
rgamma(1, func_tmpShape * func_tmpRate, func_tmpRate)
}
}))
}
logisticGrowth <- function(func_rate, func_step, func_startPop = NULL, func_maxPop = NULL, func_midAdjust = 0, func_basalExponent = exp(1)){
return( func_maxPop / (1+ (((func_maxPop - func_startPop)/(func_startPop)) * func_basalExponent^(-func_rate * (func_step - func_midAdjust))) ) )
}
logisticMap <- function(func_rate, func_startPop, func_maxPop){
func_startPop + func_rate * (func_startPop * ((func_maxPop-func_startPop)/func_maxPop))
}
expGrowth <- function(func_rate, func_step,func_startPop = NULL, func_endPop = NULL){
func_tmpRate <- (func_rate ^ func_step)
if(is.null(func_endPop) && !is.null(func_startPop)){
if(any(func_tmpRate < 1)){ func_tmpRate[which(func_tmpRate < 1)] <- 1 }
return( func_startPop * func_tmpRate )
} else if(!is.null(func_endPop) && is.null(func_startPop)){
return( func_endPop/func_tmpRate )
} else {
stop(paste("Not certain which value you wanted calculated since you defined a starting pop of ",func_startPop," and final pop of ",func_endPop," please review",sep=""))
}
}
adjustBirths <- function(func_adjVector, func_sumTotal, func_roundValues = getOption("shape_track_asWhole")){
if(sum(func_adjVector) != func_sumTotal){
func_adjVector <- func_adjVector/sum(func_adjVector) * sum(func_sumTotal)
}
if(func_roundValues && any(func_adjVector %% 1 != 0)){
func_tmpUpdates <- which(func_adjVector %% 1 != 0)
func_adjVector[func_tmpUpdates] <- unlist(lapply(func_adjVector[func_tmpUpdates],function(thisPop){
floor(thisPop) + rbinom(1, size = 1, prob = thisPop %% 1)
}))
}
if(abs(diff(c(sum(func_adjVector), func_sumTotal))) >= 1){
func_adjustments <- func_sumTotal - sum(func_adjVector)
func_tmpAdjustable <- which(abs(func_adjVector) >= 1)
func_proposedAdjustments <- NULL
func_tmpCounter <- 0
while(sum(func_proposedAdjustments) != abs(func_adjustments) && func_adjustments >= 1 && func_tmpCounter < 100){
func_proposedAdjustments <- table(sample(func_tmpAdjustable,
abs(func_adjustments),
replace=TRUE,
prob = abs(func_adjVector[func_tmpAdjustable]/sum(func_adjVector[func_tmpAdjustable]))))
func_proposedAdjustments <- sapply(names(func_proposedAdjustments) ,function(thisNamed){
return( min(func_adjVector[as.numeric(thisNamed)], func_proposedAdjustments[thisNamed]) )
})
if(length(func_proposedAdjustments) == 0){ func_proposedAdjustments <- NULL }
func_tmpCounter <- func_tmpCounter + 1
}
if(func_tmpCounter >= 100){
stop("While adjustingBirths and trying to aportion the adjustments got stuck in a loop for 100 replicates, please review...")
}
if(!is.null(func_proposedAdjustments)){
func_adjVector[as.numeric(names(func_proposedAdjustments))] <- func_adjVector[as.numeric(names(func_proposedAdjustments))] +
if(func_adjustments > 0){
as.vector(func_proposedAdjustments)
} else {
- as.vector(func_proposedAdjustments)
}
}
}
return( func_adjVector )
}
fitnessLandscape <- function(tmpGenotypes, tmp_focalFitness, landscapeModel = "HoC",
tmp_ancestralFitness = getOption("shape_const_ancestFitness"), tmp_weightsRMF = getOption("shape_const_RMF_theta"),
tmp_optimaRMF = getOption("shape_const_RMF_globalOptima"), tmp_correlationsNK = getOption("shape_const_NK_interactionMat"),
tmp_const_numInteractionsNK = getOption("shape_const_numInteractions"), tmp_NK_ancestDep = getOption("shape_const_DepbySite_ancestFitness"),
relativeFitness = TRUE, func_genomeLength = getOption("shape_genomeLength"),
func_distribution = getOption("shape_constDist"), func_distParameters = getOption("shape_const_distParameters"),
func_distAsS = getOption("shape_const_distAsS"), func_sepString = getOption("shape_sepString")){
if(landscapeModel != "Fixed"){
tmp_genotypeList <- lapply(strsplit(tmpGenotypes,func_sepString),as.numeric)
}
if(!is.na(tmp_optimaRMF) && is.character(tmp_optimaRMF)){ tmp_optimaRMF <- as.numeric(strsplit(tmp_optimaRMF,func_sepString)[[1]]) }
fitnessVec <- if(landscapeModel == "HoC"){
tmpReturn <- fitnessDist(length(tmp_genotypeList), tmpDistribution = func_distribution, tmpParameters = func_distParameters)
if(func_distAsS){
tmpReturn <- tmpReturn - 1
}
tmpReturn
} else if(landscapeModel == "Additive") {
as.vector(sapply(tmp_genotypeList,function(thisGenotype){
sum(c(tmp_ancestralFitness, tmp_focalFitness[setdiff(thisGenotype,1:nrow(tmp_focalFitness)),"0"], tmp_focalFitness[thisGenotype,"1"]))
}))
} else if(landscapeModel == "NK") {
if(!is.matrix(tmp_focalFitness) ||
ncol(tmp_focalFitness) != length(getOption("shape_const_siteStates")) ||
nrow(tmp_focalFitness) != func_genomeLength ||
!all(is.element(getOption("shape_const_siteStates"),colnames(tmp_focalFitness))) ){
stop("The number of states, and/or the shape of the tmp_focalFitness passed to a call for fitnessLandscape function, is not correct please review")
}
if(tmp_const_numInteractionsNK != 0){
if(!is.matrix(tmp_correlationsNK) || ncol(tmp_correlationsNK) != tmp_const_numInteractionsNK || nrow(tmp_correlationsNK) != func_genomeLength){
stop("The shape of the tmp_correlationsNK passed to a call for fitnessLandscape function, is not a matrix and or does not have as many columns as suggested by tmp_const_numInteractionsNK, please review")
}
} else if(tmp_const_numInteractionsNK == 0 && !is.null(tmp_correlationsNK)){
stop("The tmp_correlationsNK object should have been passed as null since there are no reported NK correlations, please review")
}
as.vector(sapply(tmp_genotypeList,function(thisGenotype){
tmp_indFitness <- tmp_focalFitness[,"0"]
tmp_indFitness[thisGenotype] <- tmp_focalFitness[thisGenotype,"1"]
tmp_depFitness <- tmp_NK_ancestDep
tmp_mutCorrelates <- unique(which(apply(tmp_correlationsNK,MARGIN=1,function(theseSites){ any(is.element(thisGenotype,theseSites)) })))
for(thisSite in union(thisGenotype,tmp_mutCorrelates)){
tmp_depFitness[thisSite] <- mean(tmp_indFitness[c(thisSite, tmp_correlationsNK[thisSite,])])
}
return( mean(tmp_depFitness) )
}))
} else if(landscapeModel == "RMF"){
if(length(tmp_weightsRMF) != 1){ stop("The vector of weights passed to RMF fitnessLandscape model is not length 1, please review.") }
tmp_randomTerm <- fitnessDist(length(tmp_genotypeList), tmpDistribution = func_distribution, tmpParameters = func_distParameters)
if(func_distAsS){
tmp_randomTerm <- tmp_randomTerm - 1
}
as.vector( -tmp_weightsRMF *
unlist(lapply(tmp_genotypeList,function(thisGenotype){
tmpOverlap <-is.element(thisGenotype, tmp_optimaRMF)
length(tmp_optimaRMF) - length(which(tmpOverlap)) + length(which(! tmpOverlap))
})) +
tmp_randomTerm )
} else if (landscapeModel == "Fixed"){
if(all(is.element(tmpGenotypes,names(tmp_focalFitness)))){
tmp_focalFitness[tmpGenotypes]
} else {
stop("There was a problem trying to use the Fixed fitness landscape model, review input make certain all possible genotypes are declared.")
Sys.sleep(20)
}
}
if(relativeFitness){ fitnessVec <- calc_relativeFitness(fitnessVec, func_ancestFit = tmp_ancestralFitness) }
return( round(fitnessVec,4) )
}
fitnessDist <- function(tmpDraws, tmpDistribution, tmpParameters){
if(tmpDistribution == "Fixed"){
return( sample(if(length(tmpParameters) == 2){ rep(tmpParameters[2],2) } else { tmpParameters[2: length(tmpParameters)]},
tmpDraws, replace = as.logical(tmpParameters[1])) )
}else if(tmpDistribution == "Gamma"){
return( rgamma(tmpDraws, shape = tmpParameters[1], rate = tmpParameters[2]) )
} else if(tmpDistribution == "Uniform") {
return( runif(tmpDraws, min = tmpParameters[1], max = tmpParameters[2]) )
} else if(tmpDistribution == "Normal") {
return( rnorm(tmpDraws, mean = tmpParameters[1], sd = tmpParameters[2]) )
} else if(tmpDistribution == "Chi2") {
return( rchisq(tmpDraws, df = tmpParameters[1], ncp = tmpParameters[2]) )
} else if(tmpDistribution == "beta") {
return( rbeta(tmpDraws, shape1 = tmpParameters[1] , shape2 = tmpParameters[2]) )
} else if(tmpDistribution == "exp") {
return( rexp(tmpDraws, rate = tmpParameters[1]) )
} else if(tmpDistribution == "evd") {
return( evd::rgev(tmpDraws, loc = tmpParameters[1], scale = tmpParameters[2], shape = tmpParameters[3]) )
} else if(tmpDistribution == "rweibull") {
return( evd::rrweibull(tmpDraws, loc = tmpParameters[1], scale = tmpParameters[2], shape = tmpParameters[3]) )
} else if(tmpDistribution == "frechet") {
return( VGAM::rfrechet(tmpDraws, location = tmpParameters[1], scale = tmpParameters[2], shape = tmpParameters[3]) )
} else if(tmpDistribution == "skewNorm") {
tmpReturn <- sn::rsn(tmpDraws, xi = tmpParameters[1], omega = tmpParameters[2], alpha = tmpParameters[3], tau = tmpParameters[4])
tmpReturn[which(tmpReturn < 0)] <- 0
return( as.vector(tmpReturn) )
}
}
createGenotypes <- function(tmp_focalGenotype, tmp_focalFitness, maxHamming, tmp_landModel = "HoC", tmp_sepString = getOption("shape_sepString"),
tmpDirection = getOption("shape_allow_backMutations"), tmp_relativeFitness = getOption("shape_const_relativeFitness"),
tmp_currNeighbours = NULL, tmp_genCon, tmp_tableSplit = getOption("shape_db_splitTables"), tmp_maxRows = getOption("shape_maxRows"),
tmp_genomeLength = getOption("shape_genomeLength"), tmp_distAsS = getOption("shape_const_distAsS"), ...){
if(is.null(tmp_currNeighbours)){ tmp_currNeighbours <- defineNeighbours(func_tmpGenotype = tmp_focalGenotype, func_tmpDirection = tmpDirection)}
tmp_numMuts <- length(strsplit(tmp_focalGenotype, tmp_sepString)[[1]])
tmp_mutsRange <- max(0,(tmp_numMuts - if(tmpDirection){ maxHamming }else{ 0 })): min(tmp_genomeLength ,(tmp_numMuts + (maxHamming)))
if(!tmpDirection && maxHamming <= 1){
tmp_mutsRange <- tmp_mutsRange[-which(tmp_mutsRange == tmp_numMuts)]
}
tmp_dbTables <- RSQLite::dbListTables(tmp_genCon)
tmp_found_neededNeighbours <- find_neededNeighbours(tmp_possibleNeighbours = tmp_currNeighbours,
tmp_focal_numMuts = tmp_numMuts,
tmpRange_numMuts = tmp_mutsRange,
tmp_refTables = tmp_dbTables,
tmp_genCon = tmp_genCon)
if(length(tmp_found_neededNeighbours) != 0){
neighbourMuts <- lapply(tmp_mutsRange,function(x){
return( tmp_found_neededNeighbours[which(sapply(strsplit(tmp_found_neededNeighbours, tmp_sepString),length) == x)] )
})
names(neighbourMuts) <- sapply(tmp_mutsRange,nameTable, "func_subNaming"=tmp_tableSplit)
for(thisTable in names(neighbourMuts)[which(lapply(neighbourMuts,length) > 0)]){
options("shape_tmpGenoTable" = create_genotypeFrame(tmpID = getOption("shape_nextID"): (getOption("shape_nextID") + length(neighbourMuts[[thisTable]]) - 1),
tmpStrings = neighbourMuts[[thisTable]],
tmpFitnesses = fitnessLandscape(tmpGenotypes = neighbourMuts[[thisTable]],
tmp_focalFitness = tmp_focalFitness,
landscapeModel = tmp_landModel,
relativeFitness = tmp_relativeFitness,
func_distAsS = tmp_distAsS)))
options(shape_nextID = getOption("shape_nextID") + length(neighbourMuts[[thisTable]]))
if(!any(grepl(thisTable, tmp_dbTables)) || !tmp_tableSplit){
dbWriteTable(tmp_genCon,
name = ifelse(tmp_tableSplit, paste(thisTable,1,sep=""), thisTable),
value = getOption("shape_tmpGenoTable"),
append=TRUE)
} else {
tmp_similarTables <- tmp_dbTables[which(grepl(thisTable, tmp_dbTables))]
tmpOldest <- tmp_similarTables[which.max(sapply(tmp_similarTables,function(x){ as.numeric(strsplit(x,tmp_sepString)[[1]][3]) }))]
if(nrow(dbGetQuery(tmp_genCon,paste("SELECT genotypeID FROM ", tmpOldest,sep=""))) < tmp_maxRows){
dbWriteTable(tmp_genCon,
name = tmpOldest,
value = getOption("shape_tmpGenoTable"),
append=TRUE)
} else {
dbWriteTable(tmp_genCon,
name = paste(paste(strsplit(tmpOldest,tmp_sepString)[[1]][-3],collapse=tmp_sepString),as.numeric(strsplit(tmpOldest,tmp_sepString)[[1]][3])+1,sep=tmp_sepString),
value = getOption("shape_tmpGenoTable"))
}
}
}
tmp_neededTables <- tmp_dbTables[which(grepl(nameTable(tmp_numMuts, func_subNaming=tmp_tableSplit), tmp_dbTables))]
tmp_ancestFind <- 0
tmp_ancestTable <- tmp_dbTables[which(grepl(nameTable(0, func_subNaming=tmp_tableSplit), tmp_dbTables))]
names(tmp_ancestFind) <- tmp_ancestTable
if(tmp_focalGenotype != ""){
tmp_ancestFind <- sapply(tmp_neededTables, function(thisTable){
as.vector(unlist(dbGetQuery(tmp_genCon, paste("SELECT genotypeID FROM ",thisTable,' WHERE binaryString = "', tmp_focalGenotype,'"',sep=""))))
},simplify=FALSE)
tmp_ancestTable <- names(tmp_ancestFind)[which(sapply(tmp_ancestFind,length) == 1)]
}
dbExecute(tmp_genCon,
paste("UPDATE ", tmp_ancestTable ,' SET isExplored = 1 WHERE genotypeID = ', tmp_ancestFind[tmp_ancestTable],sep=""),
synchronous = NULL)
}
invisible( NULL )
}
find_neededNeighbours <- function(tmp_possibleNeighbours, tmp_focal_numMuts, tmp_refTables,
maxHamming = getOption("shape_max_numMutations"),
tmp_tableSplit = getOption("shape_db_splitTables"), tmp_genomeLength = getOption("shape_genomeLength"),
tmpDirection = getOption("shape_allow_backMutations"), tmpRange_numMuts = NULL, tmp_genCon){
if(is.null(tmp_refTables)){ tmp_refTables <- RSQLite::dbListTables(tmp_genCon) }
tmp_neededTables <- NULL
if(is.null(tmpRange_numMuts)){
tmpRange_numMuts <- max(0,(tmp_focal_numMuts - if(tmpDirection){ maxHamming }else{ 0 })): min(tmp_genomeLength,(tmp_focal_numMuts + maxHamming))
tmp_neededTables <- tmp_refTables[unlist(lapply(tmpRange_numMuts[-which(tmpRange_numMuts == tmp_focal_numMuts)],function(x){ which(grepl(nameTable(x, func_subNaming=tmp_tableSplit), tmp_refTables)) }))]
} else {
tmp_neededTables <- tmp_refTables[unlist(lapply(tmpRange_numMuts,function(x){ which(grepl(nameTable(x, func_subNaming=tmp_tableSplit), tmp_refTables)) }))]
}
if(length(tmp_neededTables) == 0){
return( unlist(tmp_possibleNeighbours) )
} else {
tmp_binaryStrings <- gsub("[[:space:]]","",paste("\'", tmp_possibleNeighbours,"\'",collapse=','))
return ( setdiff(tmp_possibleNeighbours,
unlist(dbGetQuery(tmp_genCon,
paste('SELECT binaryString FROM ',
tmp_neededTables,
' WHERE binaryString IN (',
tmp_binaryStrings,')',
collapse=" UNION "))
)) )
}
}
defineNeighbours <- function(func_tmpGenotype, func_tmpDirection, func_maxHamming = getOption("shape_max_numMutations"),
func_sepString = getOption("shape_sepString"), func_genomeLength = getOption("shape_genomeLength")){
func_tmpGenotype <- as.numeric(strsplit(func_tmpGenotype, func_sepString)[[1]])
return( if(length(func_tmpGenotype) == 0){
as.character(seq(1, func_genomeLength))
} else if(length(func_tmpGenotype) > 0 && !func_tmpDirection){
unlist(lapply(seq(1, func_genomeLength)[-func_tmpGenotype],function(thisPos){
paste(c(func_tmpGenotype,thisPos)[order(c(func_tmpGenotype,thisPos))],collapse= func_sepString)
}))
} else if(length(func_tmpGenotype) > 0 && func_tmpDirection){
c(unlist(lapply(seq(1, func_genomeLength)[-func_tmpGenotype],function(thisPos){
paste(c(func_tmpGenotype,thisPos)[order(c(func_tmpGenotype,thisPos))],collapse= func_sepString)
})),
unlist(lapply(1:length(func_tmpGenotype),function(thisPos){
paste(c(func_tmpGenotype[-thisPos])[order(c(func_tmpGenotype[-thisPos]))],collapse= func_sepString)
})) )
} )
}
create_genotypeFrame <- function(tmpID, tmpStrings,tmpFitnesses){
if(length(tmpStrings) != length(tmpFitnesses)){
stop("There was a problem trying to create a genotype data frame, as a result of the number of genotypes and fitnesses passed do not match")
}
return( data.frame("genotypeID"=tmpID,"binaryString"= tmpStrings, "fitness"= tmpFitnesses, "isExplored"= 0, stringsAsFactors=FALSE) )
}
nameTable <- function(func_tmpMutations, func_tmpIndex = NULL, func_baseString = getOption("shape_string_tableNames"),
func_sepString = getOption("shape_sepString"), func_splitName = FALSE, func_subNaming = getOption("shape_db_splitTables")){
if(func_splitName){
return( as.vector(unlist(lapply(func_tmpMutations, function(x) { strsplit(x, func_sepString)[[1]][2] }))) )
}
if(func_subNaming){
if(!is.null(func_tmpIndex)){
return( paste(func_baseString,func_tmpMutations,paste(func_tmpIndex,collapse=func_sepString),sep=func_sepString) )
} else {
return( paste(func_baseString,func_tmpMutations,"",sep=func_sepString) )
}
} else {
return( paste(func_baseString,func_tmpMutations,sep=func_sepString) )
}
}
nameTable_step <- function(func_Index, funcSplit = FALSE, func_sepString = getOption("shape_sepString")){
if(funcSplit){
return( unlist(lapply(strsplit(func_Index,func_sepString),function(x){ x[2] })) )
} else {
return( paste("Step",func_Index,sep=func_sepString) )
}
}
nameTable_neighbourhood <- function(func_Index, funcSplit = FALSE, func_sepString = getOption("shape_sepString")){
if(funcSplit){
return( unlist(lapply(strsplit(func_Index,func_sepString),function(x){ x[2] })) )
} else {
return( paste("genotypeID",func_Index,sep=func_sepString) )
}
}
reset_shapeDB <- function(func_conName, func_existingCon = NULL, func_type = "connect"){
if(func_type == "connect"){
if(!is.null(func_existingCon)){ RSQLite::dbDisconnect(func_existingCon) }
return( RSQLite::dbConnect(RSQLite::SQLite(), func_conName) )
} else {
return( RSQLite::dbDisconnect(func_conName) )
}
}
reportPopulations <- function(func_numMuts, func_genotypeID, func_popSizes, func_fitnesses, func_births, func_deaths, func_mutants, func_progenitor,
func_reportMat_colnames = getOption("shape_reportMat_colnames")){
length_allInputs <- c(length(func_numMuts), length(func_genotypeID), length(func_popSizes), length(func_fitnesses),
length(func_births), length(func_deaths), length(func_mutants), length(func_progenitor))
if( all(sapply(length_allInputs[-1],function(tmpLengths){ length_allInputs[1] == tmpLengths })) ){
if(length(length_allInputs) != length(func_reportMat_colnames)){
stop("Trying to create population matrix with insufficient number of elements passed, please review")
return( NULL )
} else {
tmpReturn <- data.frame(func_numMuts, func_genotypeID, func_popSizes, func_fitnesses, func_births, func_deaths, func_mutants, func_progenitor,stringsAsFactors=FALSE)
dimnames(tmpReturn) <- list(rep(func_genotypeID,max(length_allInputs)/length(func_genotypeID)),
func_reportMat_colnames)
return( tmpReturn )
}
} else {
stop("Trying to create population matrix with vectors of information that are not all the same size, please review")
return( NULL )
}
}
retrieve_binaryString <- function(func_genotypeID, func_numMuts = NULL, func_subNaming,
func_landscapeCon){
tmp_refTables <- RSQLite::dbListTables(func_landscapeCon)
if(!is.null(func_numMuts)){
tmp_refTables <- tmp_refTables[which(grepl(nameTable(func_numMuts, func_subNaming = func_subNaming), tmp_refTables))]
}
func_tmpReturn <- dbGetQuery(func_landscapeCon, paste("SELECT binaryString,isExplored FROM ",
tmp_refTables,
' WHERE genotypeID IN(',
paste(func_genotypeID,collapse=","),
')',
collapse=" UNION "))
if(nrow(func_tmpReturn) == 0){
func_tmpReturn <- dbGetQuery(func_landscapeCon, paste("SELECT binaryString,isExplored FROM ",
RSQLite::dbListTables(func_landscapeCon),
' WHERE genotypeID IN(',
paste(func_genotypeID,collapse=","),
')',
collapse=" UNION "))
}
if(nrow(func_tmpReturn) == 0){
stopError(paste("Problem finding the binaryString information for: ",func_genotypeID," please review",sep=""))
} else {
return( func_tmpReturn )
}
}
compute_distGrowth <- function(func_distFactor, func_growthType, func_distType, func_growthRate,
func_popSize, func_focalSize, func_manualGenerations = NULL, func_stepDivs){
if(is.element(func_growthType, c("poisson","constant"))){
return( c("factor"=0,
"popLost"= 0,
"stepReq"= if(is.null(func_manualGenerations )){
1e12
} else {
ceiling(func_manualGenerations/func_stepDivs)
}) )
}
func_tmpFactor <- as.vector(if(func_growthType == "logistic"){
if(func_distType == "bottleneck"){
func_distFactor["factor"]
} else if(func_distType == "random") {
rnorm(1,mean= func_distFactor["factor"],sd= func_distFactor["random"])
} else {
stop(paste('There was a problem with the definition of <func_distType> = ', func_distType, ' please review',sep=""))
}
} else if (func_growthType == "exponential") {
(sum(func_popSize)/func_focalSize)
})
if(func_tmpFactor < 1){ func_tmpFactor <- 1 }
func_growthSteps <- if(is.null(func_manualGenerations)){
log(if(func_tmpFactor <= 0){ 100 } else { func_tmpFactor }, base = func_growthRate)
} else {
round(func_manualGenerations,0)
}
func_growthSteps <- ceiling(func_growthSteps/func_stepDivs)
return( c("factor" = func_tmpFactor,
"popLost" = 0,
"stepReq" = as.vector(func_growthSteps)) )
}
lossSampling <- function(func_inPopulation, func_dilutionFactor){
return( apply(cbind(func_inPopulation, func_dilutionFactor),MARGIN=1,function(thisPop){
min(thisPop[1],rpois(1, lambda = thisPop[1] * thisPop[2]))
}) )
}
name_batchString <- function(funcBase, func_setID = NULL, func_jobID = NULL, func_repID = NULL,
funcSplit = FALSE, func_sepString = getOption("shape_sepString")){
if(!funcSplit){
return( unname(apply(cbind(funcBase, func_setID, func_jobID, func_repID),MARGIN=1,function(thisInfo){
paste(paste(thisInfo,collapse=func_sepString,sep=""),sep="")
})) )
} else {
if(!all(is.logical(c(func_setID, func_jobID, func_repID)))){
stop(print("Problem splitting the batchString of ",paste(funcBase,collapse=" ")," missing logicals.",sep=""))
}
func_tmpReturn <- matrix(sapply(strsplit(funcBase,func_sepString),function(thisSplit){
tmp_returnString <- thisSplit[1]
thisSplit <- thisSplit[-1]
for(func_tmpIndex in c(func_setID, func_jobID, func_repID)[which(c(func_setID, func_jobID, func_repID))]){
if(func_tmpIndex){
tmp_returnString <- c(tmp_returnString,thisSplit[1])
thisSplit <- thisSplit[-1]
} else {
tmp_returnString <- c(tmp_returnString,NA)
}
}
return( tmp_returnString )
}),
ncol = length(funcBase))
dimnames(func_tmpReturn) <- list(c("base",
if(!is.null(func_setID)){if(as.logical(func_setID)){"setID"}else{NULL}}else{NULL},
if(!is.null(func_jobID)){if(as.logical(func_jobID)){"jobID"}else{NULL}}else{NULL},
if(!is.null(func_repID)){if(as.logical(func_repID)){"repID"}else{NULL}}else{NULL}),
funcBase)
return( func_tmpReturn )
}
}
calc_relativeFitness <- function(func_fitVector, func_ancestFit = NULL, func_weights = NULL,
func_absDistance = (getOption("shape_simModel") == "RMF")){
if(!is.null(func_ancestFit)){
if(func_ancestFit == 0){
func_absDistance <- TRUE
}
}
if( (!is.null(func_ancestFit) && func_absDistance) ){
return( unlist(lapply(1 + (func_fitVector - func_ancestFit),function(func_thisFitness){ max(0, func_thisFitness) })) )
} else if(!is.null(func_ancestFit) && func_ancestFit != 0){
return( unlist(lapply(sign(func_ancestFit) *func_fitVector/func_ancestFit, function(func_thisFitness){ max(0, func_thisFitness) })) )
} else {
return( unlist(lapply(1 + (func_fitVector - if(is.null(func_weights)){mean(func_fitVector)}else{weighted.mean(func_fitVector,func_weights)}), function(func_thisFitness){ max(0, func_thisFitness) })) )
}
}
querryEstablished <- function(func_inMatrix, func_sizeCol = "popSize", func_fitCol = "fitness", func_estProp = 0.01){
if(is.numeric(func_estProp)){
if(func_estProp <= 1){
return( func_inMatrix[which(func_inMatrix[, func_sizeCol] >= (func_estProp * sum(func_inMatrix[, func_sizeCol]))),] )
} else {
return( func_inMatrix[which(func_inMatrix[, func_sizeCol] >= floor(func_estProp)) ,] )
}
} else if(func_estProp == "Desai") {
return( func_inMatrix[which(apply(func_inMatrix[, c(func_sizeCol, func_fitCol)],MARGIN=1,function(thisRow){
thisRow[func_sizeCol] >= 1/log(thisRow[func_fitCol])
})),] )
} else {
return( func_inMatrix[eval(parse(text= func_estProp)),] )
}
}
stopError <- function(func_message){
stop(func_message)
traceback()
Sys.sleep(5)
}
trimQuotes <- function(funcIn){ substr(funcIn,2,nchar(funcIn)-1) }
addQuotes <- function(funcIn){ paste('"',funcIn,'"',sep="") }
name_subScript <- function(inVar){
paste("SHAPE_submit_",inVar,".sh",sep="")
}
name_batchSubmit <- function(inVar){
paste("submit_jobBatch_",inVar,".sh",sep="")
}
name_bodyScript <- function(inVar){
paste("SHAPE_body_",inVar,".r",sep="")
}
name_parameterScript <- function(inVar){
paste("SHAPE_parameters_",inVar,".r",sep="")
}
nameEnviron <- function(func_Index, funcSplit = FALSE, funcBase = getOption("shape_envString")){
if(funcSplit){
return( unlist(lapply(strsplit(func_Index,"_e_"),function(x){ x[2] })) )
} else {
return( paste(funcBase,func_Index,sep="_e_") )
}
}
nameObject <- function(func_inString, func_inPrefix, func_splitStr = FALSE){
if(func_splitStr){
unlist(lapply(strsplit(func_inString, func_inPrefix),function(x){ x[length(x)] }))
} else {
paste(func_inPrefix, func_inString,sep="")
}
}
set_siteByState_fitnessMat <- function(func_simModel = getOption("shape_simModel"),
func_const_fixedFrame = getOption("shape_const_fixedFrame"),
func_const_siteStates = getOption("shape_const_siteStates")){
func_tmpReturn <- if(is.element(func_simModel,c("NK","Additive"))){
sapply(func_const_siteStates,function(thisState){
return( if(thisState == "0" && getOption("shape_const_relativeFitness")){
rep(if(func_simModel == "NK"){
getOption("shape_const_ancestFitness")
} else if(func_simModel == "Additive"){
0
},
getOption("shape_genomeLength"))
} else {
tmpReturn <- fitnessDist(getOption("shape_genomeLength"),
tmpDistribution = getOption("shape_constDist"),
tmpParameters = getOption("shape_const_distParameters"))
if(getOption("shape_const_distAsS")){
tmpReturn <- tmpReturn - 1
}
tmpReturn
}
) })
} else if(func_simModel == "Fixed") {
func_tmpFileName <- paste(getOption("shape_workDir"),func_const_fixedFrame,sep="")
if(file.exists(func_tmpFileName)){
func_tmpLandscape <- read.csv(func_tmpFileName,
header=TRUE,
stringsAsFactors = FALSE)
options("shape_const_fixedFrame"= func_tmpLandscape)
} else {
stopError(paste("Could not find the fixed fitness landscape file: ",func_tmpFileName," please review",sep=""))
}
if(all(is.element(colnames(func_tmpLandscape),c("binaryString","fitness")))){
tmpReturn <- func_tmpLandscape[,"fitness"]
names(tmpReturn) <- unlist(lapply(strsplit(func_tmpLandscape[,"binaryString"],""),function(x){
if(any(x == "1")){
paste(which(x == "1"),sep="",collapse=getOption("shape_sepString"))
} else {
""
}
}))
tmpReturn
} else {
stopError("Fixed fitness landscape matrix information does not contain the two column names binaryString and fitness")
}
} else {
NULL
}
if(is.element(func_simModel,c("NK","Additive"))){
if(!is.matrix(func_tmpReturn)){
if(length(func_tmpReturn) != 2){
stopError(paste("There was a problem trying to create the <shape_const_siteBystate_fitnessMat> matrix, it's length was ",
length(func_tmpReturn),
"please review",
sep=""))
} else {
func_tmpReturn <- matrix(func_tmpReturn,
nrow=1,
ncol= length(func_const_siteStates))
}
}
colnames(func_tmpReturn) <- func_const_siteStates
}
return( func_tmpReturn )
}
set_DepbySite_ancestFitness <- function(func_simModel = getOption("shape_simModel"),
func_const_siteBystate_fitnessMat = getOption("shape_const_siteBystate_fitnessMat"),
func_const_NK_interactionMat = getOption("shape_const_NK_interactionMat")){
func_tmpReturn <- if(func_simModel == "NK"){
sapply(1:nrow(func_const_siteBystate_fitnessMat),function(thisSite){
mean(func_const_siteBystate_fitnessMat[c(thisSite, func_const_NK_interactionMat[thisSite,]),"0"])
})
} else {
NA
}
return( func_tmpReturn )
}
set_RMF_indWeight <- function(func_simModel = getOption("shape_simModel"), func_numDraws = 1e8,
func_distType = getOption("shape_constDist"), func_distParms = getOption("shape_const_distParameters"),
func_const_RMF_theta = getOption("shape_const_RMF_theta")){
func_tmpReturn <- if(func_simModel == "RMF"){
func_const_RMF_theta * sqrt(var(fitnessDist(func_numDraws,
tmpDistribution = func_distType,
tmpParameters = func_distParms)))
} else {
NA
}
return( func_tmpReturn )
}
set_const_NK_interactionsMat <- function(func_simModel = getOption("shape_simModel"), func_genomeLength = getOption("shape_genomeLength"),
func_numInteractions = getOption("shape_const_numInteractions")){
func_tmpReturn <- if(func_simModel != "NK" || func_numInteractions == 0){
NULL
} else if(func_simModel == "NK" && func_numInteractions == 1){
as.matrix(sapply(1:func_genomeLength,function(thisSite){
sample((1:func_genomeLength)[-thisSite],
func_numInteractions,
replace=FALSE)
}),ncol=1)
} else {
t(sapply(1:func_genomeLength,function(thisSite){
sample((1:func_genomeLength)[-thisSite],
func_numInteractions,
replace=FALSE)
}))
}
return( func_tmpReturn )
}
set_const_RMF_globalOptima <- function(func_simModel = getOption("shape_simModel"), func_genomeLength = getOption("shape_genomeLength"),
func_initDistance = getOption("shape_const_RMF_initiDistance"),
func_sepString = getOption("shape_sepString")){
func_tmpReturn <- if(func_simModel == "RMF"){
tmpReturn <- if(func_initDistance == 0){
""
} else {
sample(1: func_genomeLength, func_initDistance,replace=FALSE)
}
paste(tmpReturn[order(tmpReturn,decreasing=FALSE)],collapse= func_sepString)
} else {
NA
}
return( func_tmpReturn )
}
runReplicate <- function(func_inputFrames, func_currStep, func_stepCounter,
func_growthModel = getOption("shape_const_growthForm"),
func_growthRate = getOption("shape_const_growthRate"),
func_landscapeModel = getOption("shape_simModel"),
func_fileName_dataBase = getOption("shape_fileName_dataBase")){
workFrame <- func_inputFrames[[nameTable_step(func_currStep-1)]]
if(func_stepCounter > getOption("shape_track_distSize")[nrow(getOption("shape_track_distSize")),"stepReq"]){
currLineages <- unname(which(workFrame[,"popSize"] >= 0.5))
if(length(currLineages) == 0){
print(paste("All lineages have died as of timeStep ", func_currStep,sep=""))
return( func_inputFrames )
}
workFrame <- reportPopulations(func_numMuts= workFrame[currLineages,"numMuts"],
func_genotypeID= workFrame[currLineages,"genotypeID"],
func_popSizes= workFrame[currLineages,"popSize"],
func_fitnesses= workFrame[currLineages,"fitness"],
func_births=workFrame[currLineages,"births"],
func_deaths=workFrame[currLineages,"deaths"],
func_mutants=workFrame[currLineages,"mutants"],
func_progenitor=workFrame[currLineages,"progenitor"])
tmp_lossFactors <- compute_distGrowth(func_distFactor = if(func_growthModel == "logistic"){
getOption("shape_init_distPars")
}else{
0
},
func_growthType = func_growthModel,
func_distType = getOption("shape_const_distType"),
func_growthRate = func_growthRate,
func_popSize = workFrame[,"popSize"],
func_focalSize = getOption("shape_const_focal_popValue"),
func_manualGenerations = if(func_growthModel == "constant"){
getOption("shape_numGenerations")
} else {
getOption("shape_const_growthGenerations")
},
func_stepDivs = getOption("shape_size_timeStep"))
if(tmp_lossFactors["factor"] > 1){
tmp_sampledPop <- lossSampling(func_inPopulation = workFrame[,"popSize"],
func_dilutionFactor = 1/if(tmp_lossFactors["factor"] == 0){1}else{tmp_lossFactors["factor"]})
tmp_lossFactors["popLost"] <- sum(workFrame[,"popSize"] - tmp_sampledPop)
tmp_lossFactors["factor"] <- sum(workFrame[,"popSize"])/sum(tmp_sampledPop)
workFrame[,"popSize"] <- tmp_sampledPop
options("shape_track_distSize" = rbind(getOption("shape_track_distSize"), c("Step"= func_currStep, tmp_lossFactors)))
}
func_stepCounter <- 1
options("shape_counter_logSteps" = func_stepCounter)
}
currLineages <- as.vector(which(workFrame[,"popSize"] >= 0.5, useNames=FALSE))
if(length(currLineages) == 0){
print(paste("All lineages have died as of timeStep ", func_currStep,sep=""))
return( func_inputFrames )
}
workFrame <- reportPopulations(func_numMuts= workFrame[currLineages,"numMuts"],
func_genotypeID= workFrame[currLineages,"genotypeID"],
func_popSizes= workFrame[currLineages,"popSize"],
func_fitnesses= workFrame[currLineages,"fitness"],
func_births=workFrame[currLineages,"births"],
func_deaths=workFrame[currLineages,"deaths"],
func_mutants=workFrame[currLineages,"mutants"],
func_progenitor=workFrame[currLineages,"progenitor"])
num_birthDeaths <- growthFunction(func_inSize = workFrame[,"popSize"],
func_inFitness = workFrame[,"fitness"],
func_bProb = getOption("shape_const_birthProb"),
func_dProb = getOption("shape_const_deathProb"),
func_deathDen_logical = getOption("shape_death_byDensity"),
func_deathDen_max = getOption("shape_death_densityCap"),
func_deathDen_power = getOption("shape_death_densityCorrelation"),
func_sizeStep = getOption("shape_size_timeStep"),
func_growthForm = func_growthModel,
func_carryingCapacity = getOption("shape_const_focal_popValue"),
func_basalRate = func_growthRate,
func_deathScale = getOption("shape_scaleGrowth_byDeaths"),
func_drift = getOption("shape_includeDrift"),
func_roundValues = getOption("shape_track_asWhole"),
func_inIDs = rownames(workFrame))
tmpUpdates <- which(num_birthDeaths[,"births"] < 0)
if(length(tmpUpdates) > 0){
num_birthDeaths[tmpUpdates,"deaths"] <- num_birthDeaths[tmpUpdates,"deaths"] - num_birthDeaths[tmpUpdates,"births"]
num_birthDeaths[tmpUpdates,"births"] <- 0
}
tmp_mutableLineages <- if(!getOption("shape_allow_backMutations") &&
is.element(getOption("shape_genomeLength"),workFrame[,"numMuts"])){
rownames(num_birthDeaths)[which(workFrame[rownames(num_birthDeaths),"numMuts"] !=
getOption("shape_genomeLength"))]
} else {
rownames(num_birthDeaths)
}
tmp_mutableLineages <- tmp_mutableLineages[which(workFrame[tmp_mutableLineages,"popSize"] +
num_birthDeaths[tmp_mutableLineages,"births"] -
num_birthDeaths[tmp_mutableLineages,"deaths"] >= 1)]
proposedMutants <- mutationFunction(func_inSize = unlist(lapply(num_birthDeaths[tmp_mutableLineages,"births"] *
func_growthRate/
(func_growthRate - 1),function(x){ max(0,x) })),
func_inProb = getOption("shape_const_mutProb")) +
if(getOption("shape_muts_onlyBirths")){
0
} else {
mutationFunction(func_inSize = unlist(lapply(workFrame[tmp_mutableLineages,"popSize"] -
num_birthDeaths[tmp_mutableLineages,"deaths"] -
num_birthDeaths[tmp_mutableLineages,"births"] *
1/(func_growthRate - 1), function(x){ max(0,x) })),
func_inProb = getOption("shape_const_mutProb") * getOption("shape_size_timeStep"))
}
names(proposedMutants) <- tmp_mutableLineages
num_birthDeaths <- cbind(num_birthDeaths,
"mutants"= as.vector(sapply(rownames(workFrame),function(x){
if(is.element(x,names(proposedMutants))){
return( min(proposedMutants[x],
workFrame[x,"popSize"] +
num_birthDeaths[x,"births"] -
num_birthDeaths[x,"deaths"]) )
} else {
0
}
})))
all_newMutants <- NULL
if(sum(num_birthDeaths[,"mutants"]) > 0){
for(thisLineage in rownames(num_birthDeaths)[which(num_birthDeaths[,"mutants"] > 0)] ){
connections_dataBase <- sapply(names(func_fileName_dataBase),function(x){
reset_shapeDB(paste(getOption("shape_outDir"), func_fileName_dataBase[[x]],sep=""),
func_type = "connect")
})
this_focalGenotype <- retrieve_binaryString(func_genotypeID = as.numeric(thisLineage),
func_numMuts = workFrame[thisLineage,"numMuts"],
func_subNaming = getOption("shape_db_splitTables"),
func_landscapeCon = connections_dataBase$genotypeSpace)
if(length(this_focalGenotype) == 0 || nrow(this_focalGenotype) != 1){
print(paste("Safety net for mis-classified genotypeID has been used for ", this_focalGenotype," on step ",func_currStep,sep=""))
tmp_mutSearch <- sapply(nameTable(RSQLite::dbListTables(connections_dataBase$genotypeSpace), func_splitName = TRUE), function(this_numMuts){
return( nrow(retrieve_binaryString(func_genotypeID = as.numeric(thisLineage),
func_numMuts = as.numeric(this_numMuts),
func_subNaming = getOption("shape_db_splitTables"),
func_landscapeCon = connections_dataBase$genotypeSpace)) )
})
if(length(which(tmp_mutSearch == 1)) == 1){
workFrame[thisLineage,"numMuts"] <- as.numeric(names(tmp_mutSearch)[which(tmp_mutSearch == 1)])
this_focalGenotype <- retrieve_binaryString(func_genotypeID = as.numeric(thisLineage),
func_numMuts = workFrame[thisLineage,"numMuts"],
func_subNaming = getOption("shape_db_splitTables"),
func_landscapeCon = connections_dataBase$genotypeSpace)
} else {
stop(paste("There was a problem while trying to define a unique table containing ",thisLineage," during ",func_currStep," please review",sep=""))
}
}
tmp_allNeighbours <- NULL
if(is.element(nameTable_neighbourhood(thisLineage),RSQLite::dbListTables(connections_dataBase$nearestNeighbours))){
tmp_allNeighbours <- dbGetQuery(connections_dataBase$nearestNeighbours,
paste("SELECT * FROM ",nameTable_neighbourhood(thisLineage),sep=""))$neighbours
} else {
tmp_allNeighbours <- defineNeighbours(func_tmpGenotype = this_focalGenotype[1,"binaryString"],
func_tmpDirection = getOption("shape_allow_backMutations"))
if(workFrame[thisLineage,"popSize"] >= getOption("shape_const_hoodThresh")){
dbWriteTable(connections_dataBase$nearestNeighbours,
nameTable_neighbourhood(thisLineage),
data.frame("neighbours"=tmp_allNeighbours))
}
}
if(!as.logical(this_focalGenotype[1,"isExplored"])){
createGenotypes(tmp_focalGenotype = this_focalGenotype[1,"binaryString"],
tmp_focalFitness = if(is.element(func_landscapeModel,c("NK","Additive"))){
getOption("shape_const_siteBystate_fitnessMat")
} else {
workFrame[thisLineage,"fitness"]
},
maxHamming = getOption("shape_max_numMutations"),
tmp_landModel = func_landscapeModel,
tmp_relativeFitness = getOption("shape_const_relativeFitness"),
tmpDistribution = getOption("shape_constDist"),
tmpParameters = getOption("shape_const_distParameters"),
tmp_currNeighbours = tmp_allNeighbours,
tmp_genCon = connections_dataBase$genotypeSpace,
tmp_tableSplit = getOption("shape_db_splitTables"),
tmp_maxRows = getOption("shape_maxRows"),
tmp_distAsS = getOption("shape_const_distAsS"))
}
newMutants <- table(sample(tmp_allNeighbours,
num_birthDeaths[thisLineage,"mutants"], replace = TRUE))
tmp_numMuts <- unlist(lapply(strsplit(names(newMutants),getOption("shape_sepString")),length))
tmp_dbTables <- RSQLite::dbListTables(connections_dataBase$genotypeSpace)
tmp_dbTables <- tmp_dbTables[unique(unlist(lapply(nameTable(unique(tmp_numMuts)),function(thisString){
which(grepl(thisString,tmp_dbTables))
})))]
tmp_newStrings <- gsub("[[:space:]]","",paste("\'", names(newMutants),"\'",collapse=','))
tmp_infoAdd <- as.matrix(dbGetQuery(connections_dataBase$genotypeSpace,
paste("SELECT genotypeID,fitness,binaryString FROM ",
tmp_dbTables,
' WHERE binaryString IN (',
tmp_newStrings,
')',
collapse=" UNION ")))
if(!all(is.element(names(newMutants),tmp_infoAdd[,"binaryString"]))){
createGenotypes(tmp_focalGenotype = this_focalGenotype[1,"binaryString"],
tmp_focalFitness = if(is.element(func_landscapeModel,c("NK","Additive"))){
getOption("shape_const_siteBystate_fitnessMat")
} else {
workFrame[thisLineage,"fitness"]
},
maxHamming = getOption("shape_max_numMutations"),
tmp_landModel = func_landscapeModel,
tmp_relativeFitness = getOption("shape_const_relativeFitness"),
tmpDistribution = getOption("shape_constDist"),
tmpParameters = getOption("shape_const_distParameters"),
tmp_currNeighbours = tmp_allNeighbours,
tmp_genCon = connections_dataBase$genotypeSpace,
tmp_tableSplit = getOption("shape_db_splitTables"),
tmp_distAsS = getOption("shape_const_distAsS"))
tmp_infoAdd <- as.matrix(dbGetQuery(connections_dataBase$genotypeSpace,
paste("SELECT genotypeID,fitness,binaryString FROM ",
tmp_dbTables,
' WHERE binaryString IN (',
tmp_newStrings,
')',
collapse=" UNION ")))
}
for(thisConnection in connections_dataBase){ dbDisconnect(thisConnection) }
tmp_newOrder <- unlist(lapply(names(newMutants),function(x){ which(tmp_infoAdd[,"binaryString"] == x) }))
newMutants <- cbind(tmp_numMuts, tmp_infoAdd[tmp_newOrder,"genotypeID"], newMutants, tmp_infoAdd[tmp_newOrder,"fitness"])
colnames(newMutants) <- getOption("shape_popMat_colnames")
rownames(newMutants) <- as.character(newMutants[,"genotypeID"])
all_newMutants <- rbind(all_newMutants,
cbind(newMutants,
"progenitor"= unlist(lapply(newMutants[,"popSize"],function(thisSize){
paste(thisLineage,thisSize,sep=getOption("shape_sepString"))
})) ) )
}
}
tmp_stepChanges <- data.frame(cbind(workFrame[rownames(num_birthDeaths),
getOption("shape_popMat_colnames")],
num_birthDeaths,
"progenitor"="",stringsAsFactors=FALSE)
,stringsAsFactors=FALSE)
if(!is.null(all_newMutants)){
all_newMutants[,"genotypeID"] <- gsub("[[:space:]]","",all_newMutants[,"genotypeID"])
tmp_repIDs <- table(all_newMutants[,"genotypeID"])
tmp_repIDs <- names(which(tmp_repIDs > 1))
if(length(tmp_repIDs) > 0){
tmp_removeRows <- NULL
for(thisID in tmp_repIDs){
tmpRows <- as.vector(which(all_newMutants[,"genotypeID"] == thisID))
all_newMutants[tmpRows[1],"popSize"] <- as.character(sum(as.numeric(all_newMutants[tmpRows,"popSize"])))
all_newMutants[tmpRows[1],"progenitor"] <- paste(all_newMutants[tmpRows,"progenitor"],collapse= getOption("shape_collapseString"))
tmp_removeRows <- c(tmp_removeRows, tmpRows[-1])
}
if(!is.null(tmp_removeRows)){
all_newMutants <- matrix(all_newMutants[-tmp_removeRows,],ncol=ncol(all_newMutants),
dimnames=list(rownames(all_newMutants[-tmp_removeRows]),colnames(all_newMutants)))
}
}
all_newMutants <- data.frame(all_newMutants,stringsAsFactors=FALSE)
for(thisCol in getOption("shape_popMat_colnames")){
all_newMutants[, thisCol] <- as.numeric(all_newMutants[, thisCol])
}
tmpTypes <- is.element(all_newMutants[,"genotypeID"], tmp_stepChanges[,"genotypeID"])
tmpExisting <- if(any(tmpTypes)){
unlist(lapply(all_newMutants[which(tmpTypes),"genotypeID"], function(x){
which(tmp_stepChanges[,"genotypeID"] == x)
}))
} else {
NULL
}
if(!is.null(tmpExisting)){
tmp_stepChanges[tmpExisting,"births"] <- apply(cbind(tmp_stepChanges[tmpExisting,"births"],
all_newMutants[which(tmpTypes),"popSize"]),MARGIN=1,sum)
tmp_stepChanges[tmpExisting,"progenitor"] <- apply(cbind(tmp_stepChanges[tmpExisting,"progenitor"],
all_newMutants[which(tmpTypes),"progenitor"]), MARGIN = 1, function(x){
paste(x,collapse=getOption("shape_collapseString"))
})
all_newMutants <- all_newMutants[-which(tmpTypes),]
}
tmp_stepChanges <- rbind(tmp_stepChanges,
reportPopulations(func_numMuts= all_newMutants[,"numMuts"],
func_genotypeID= all_newMutants[,"genotypeID"],
func_popSizes= all_newMutants[,"popSize"],
func_fitnesses= all_newMutants[,"fitness"],
func_births= all_newMutants[,"popSize"],
func_deaths= rep(0,nrow(all_newMutants)),
func_mutants= rep(0,nrow(all_newMutants)),
func_progenitor= all_newMutants[,"progenitor"]))
}
tmp_stepChanges[rownames(num_birthDeaths),"popSize"] <- tmp_stepChanges[rownames(num_birthDeaths),"popSize"] +
tmp_stepChanges[rownames(num_birthDeaths),"births"] -
tmp_stepChanges[rownames(num_birthDeaths),"deaths"] -
tmp_stepChanges[rownames(num_birthDeaths),"mutants"]
connections_dataBase <- sapply(names(func_fileName_dataBase),function(x){
reset_shapeDB(paste(getOption("shape_outDir"), func_fileName_dataBase[[x]],sep=""),
func_type = "connect")
})
tmp_returnMatrix <- setNames(list(reportPopulations(func_numMuts= tmp_stepChanges[,"numMuts"],
func_genotypeID= tmp_stepChanges[,"genotypeID"],
func_popSizes= tmp_stepChanges[,"popSize"],
func_fitnesses= tmp_stepChanges[,"fitness"],
func_births= tmp_stepChanges[,"births"],
func_deaths= tmp_stepChanges[,"deaths"],
func_mutants= tmp_stepChanges[,"mutants"],
func_progenitor= tmp_stepChanges[,"progenitor"])),
nameTable_step(func_currStep))
dbWriteTable(connections_dataBase$timeStep_States,
name = names(tmp_returnMatrix),
value = tmp_returnMatrix[[1]])
for(thisConnection in connections_dataBase){ dbDisconnect(thisConnection) }
return( c(func_inputFrames[[length(func_inputFrames)]],
tmp_returnMatrix) )
}
runSHAPE <- function(loop_thisRep = getOption("shape_thisRep"),
workingReplicates = seq(getOption("shape_thisRep"),getOption("shape_maxReplicates"),by=1),
tmpEnvir_recycleParms = new.env()){
if(length(which(grepl("^shape_",names(options())))) <
length(as.list(args(defineSHAPE))) - 1){
print("Doesn't look like expected options have been set for SHAPE,\n either run defineSHAPE() before trying again or doing the same prior to setting options manually.")
invisible( NULL )
}
for(loop_thisRep in workingReplicates){
options("shape_thisRep"=loop_thisRep)
options("shape_processedData_fileName" = paste(getOption("shape_outDir"),
"processed_runData_from_",
getOption("shape_save_batchString"),
"_",
getOption("shape_thisRep"),
".RData",sep=""))
options("shape_save_batchIndex" = sapply(c("Landscape", "Steps", "Parameters", "Neighbourhood"),function(thisIndex){
paste(getOption("shape_save_batchString"),
thisIndex,
if(getOption("shape_run_isRecycling")[thisIndex]){
getOption("shape_recycle_repStart")
} else {
getOption("shape_thisRep")
},sep=getOption("shape_sepString"))
}))
save_fileName <- paste(paste(getOption("shape_save_batchIndex")["Parameters"],sep=getOption("shape_sepString")),".RData",sep="")
options("shape_fileName_dataBase" = list("genotypeSpace"=paste(getOption("shape_save_batchIndex")["Landscape"],".sqlite",sep=""),
"timeStep_States"=paste(getOption("shape_save_batchIndex")["Steps"],".sqlite",sep=""),
"nearestNeighbours"=paste(getOption("shape_save_batchIndex")["Neighbourhood"],".sqlite",sep="")))
if(getOption("shape_run_isRecycling")["Landscape"] &&
c(getOption("shape_thisRep") > getOption("shape_recycle_repStart") ||
file.exists(paste(getOption("shape_outDir"),
paste(getOption("shape_save_batchString"),
"Parameters",
getOption("shape_recycle_repStart"),
sep = getOption("shape_sepString")),
".RData",sep=""))) ){
tmp_realReplicate <- getOption("shape_thisRep")
tmp_realDist <- getOption("shape_track_distSize")
tmp_real_batchStrings <- getOption("shape_save_batchIndex")
tmp_realNames <- getOption("shape_fileName_dataBase")
tmp_tryFile <- paste(getOption("shape_outDir"),
paste(getOption("shape_save_batchString"),
"Parameters",
getOption("shape_recycle_repStart"),
sep=getOption("shape_sepString")),
".RData",sep="")
if(file.exists(tmp_tryFile)){
load(tmp_tryFile, envir= tmpEnvir_recycleParms )
} else {
stop("There was a problem trying to load the seed runs' parameters during call to recycle Landscape. Please review")
}
loadSet <- if(!getOption("shape_run_isRecycling")["Parameters"]){
c("FitnessLandscape","DFE","NK_modelElements", "RMF_modelElements")
} else {
names(getOption("shape_saveParameters"))
}
for(thisSet in loadSet){
for(thisNamed in names(tmpEnvir_recycleParms$runParameters[[thisSet]])){
options(setNames(list(tmpEnvir_recycleParms$runParameters[[thisSet]][[thisNamed]]),thisNamed))
}
}
options(list("shape_thisRep" = tmp_realReplicate,
"shape_track_distSize" = tmp_realDist,
"shape_save_batchIndex" = tmp_real_batchStrings,
"shape_fileName_dataBase" = tmp_realNames))
rm(list=ls(, envir = tmpEnvir_recycleParms), envir = tmpEnvir_recycleParms)
} else {
options("shape_const_numInteractions" = min(getOption("shape_const_numInteractions"),getOption("shape_genomeLength") - 1))
options("shape_const_NK_interactionMat" = set_const_NK_interactionsMat())
options("shape_const_siteBystate_fitnessMat" = set_siteByState_fitnessMat())
options("shape_const_DepbySite_ancestFitness" = set_DepbySite_ancestFitness())
options("shape_const_RMF_indWeight" = set_RMF_indWeight())
options("shape_const_RMF_globalOptima" = set_const_RMF_globalOptima())
}
startTime <- proc.time()
connections_dataBase <- sapply(names(getOption("shape_fileName_dataBase")),function(x){
reset_shapeDB(paste(getOption("shape_outDir"), getOption("shape_fileName_dataBase")[[x]],sep=""),
func_type = "connect")
})
if(!getOption("shape_run_isRecycling")["Landscape"] ||
c(getOption("shape_thisRep") == getOption("shape_recycle_repStart") &&
length(RSQLite::dbListTables(connections_dataBase$genotypeSpace)) == 0) ){
options("shape_tmpGenoTable" = create_genotypeFrame(getOption("shape_nextID"),
"",
if(getOption("shape_const_relativeFitness")){
calc_relativeFitness(getOption("shape_const_ancestFitness"))
} else {
getOption("shape_const_ancestFitness")
}))
dbWriteTable(connections_dataBase$genotypeSpace,
name = if(getOption("shape_db_splitTables")){ nameTable(0,1) }else{ nameTable(0) },
value = getOption("shape_tmpGenoTable"))
}
current_workMatrix <- NULL
if(!getOption("shape_run_isRecycling")["Steps"] || getOption("shape_thisRep") == getOption("shape_recycle_repStart")){
current_workMatrix <- setNames(list(reportPopulations(func_numMuts = 0,
func_genotypeID = 0,
func_popSizes = getOption("shape_const_focal_popValue")/
if(getOption("shape_const_growthForm") == "logistic"){
getOption("shape_init_distSteps")["factor"]
}else{
1
},
func_fitnesses = if(getOption("shape_const_relativeFitness")){
calc_relativeFitness(getOption("shape_const_ancestFitness"))
} else {
getOption("shape_const_ancestFitness")
},
func_births = getOption("shape_const_focal_popValue")/
if(getOption("shape_const_growthForm") == "logistic"){
getOption("shape_init_distSteps")["factor"]
}else{
1
},
func_deaths = 0,
func_mutants = 0,
func_progenitor = "WT")),
paste("Step",0,sep=getOption("shape_sepString")))
dbWriteTable(connections_dataBase$timeStep_States,
name = names(current_workMatrix),
value = current_workMatrix[[1]],
overwrite = TRUE)
}
options("shape_track_distSize" = rbind(c("Step"=0,getOption("shape_init_distSteps"))))
if(!getOption("shape_run_isRecycling")["Landscape"] ||
c(getOption("shape_thisRep") == getOption("shape_recycle_repStart") && !file.exists(paste(getOption("shape_outDir"), save_fileName,sep=""))) ){
if(getOption("shape_simModel") == "RMF"){
options("shape_const_ancestFitness" = fitnessLandscape("",
getOption("shape_const_ancestFitness"),
landscapeModel = getOption("shape_simModel"),
relativeFitness = FALSE,
func_distribution = "Uniform",
func_distParameters = c(0,0),
func_distAsS = FALSE))
}
}
runTime <- 0
if(!getOption("shape_run_isRecycling")["Parameters"] ||
c(getOption("shape_thisRep") == getOption("shape_recycle_repStart") &&
!file.exists(paste(getOption("shape_outDir"),getOption("shape_save_batchIndex")["Parameters"],".RData",sep=""))) ){
runParameters <- sapply(getOption("shape_saveParameters"), function(x){
sapply(x,function(y){
getOption(y)
},simplify=FALSE)
},simplify=FALSE)
shape_fileName_dataBase <- getOption("shape_fileName_dataBase")
save(runParameters, runTime, connections_dataBase, shape_fileName_dataBase,
file=paste(getOption("shape_outDir"), save_fileName,sep=""))
} else if(getOption("shape_run_isRecycling")["Parameters"] &&
file.exists(paste(getOption("shape_outDir"),getOption("shape_save_batchIndex")["Parameters"],".RData",sep="")) ){
tmp_realReplicate <- getOption("shape_thisRep")
tmp_realDist <- getOption("shape_track_distSize")
tmp_real_batchStrings <- getOption("shape_save_batchIndex")
tmp_realNames <- getOption("shape_fileName_dataBase")
tmp_loadFile <- paste(getOption("shape_outDir"),
paste(getOption("shape_save_batchString"),
"Parameters",
getOption("shape_recycle_repStart"),
sep=getOption("shape_sepString")),
".RData",
sep="")
if(file.exists(tmp_loadFile)){
load(tmp_loadFile, envir= tmpEnvir_recycleParms )
} else {
stop("There was a problem trying to load the seed runs' parameters during call to recycle Landscape. Please review")
}
loadSet <- if(!getOption("shape_run_isRecycling")["Parameters"]){
c("FitnessLandscape","DFE","NK_modelElements", "RMF_modelElements")
} else {
names(getOption("shape_saveParameters"))
}
for(thisSet in loadSet){
for(thisNamed in names(tmpEnvir_recycleParms$runParameters[[thisSet]])){
options(setNames(list(tmpEnvir_recycleParms$runParameters[[thisSet]][[thisNamed]]), thisNamed))
}
}
options(list("shape_thisRep" = tmp_realReplicate,
"shape_track_distSize" = tmp_realDist,
"shape_save_batchIndex" = tmp_real_batchStrings,
"shape_fileName_dataBase" = tmp_realNames))
rm(list=ls(, envir = tmpEnvir_recycleParms), envir = tmpEnvir_recycleParms)
}
options("shape_nextID" = max(unlist(lapply(RSQLite::dbListTables(connections_dataBase$genotypeSpace), function(thisTable){
dbGetQuery(connections_dataBase$genotypeSpace,
paste("SELECT MAX(genotypeID) FROM ", thisTable,sep=""))
}))) + 1)
for(thisConnection in connections_dataBase){ dbDisconnect(thisConnection) }
startingStep <- 1
options("shape_counter_logSteps" = startingStep)
for(thisStep in startingStep:(getOption("shape_numGenerations") / getOption("shape_size_timeStep"))){
if(thisStep %% 100 == 0){
print(paste("We're now on thisStep: ",thisStep,sep=""))
print( proc.time() - startTime )
}
if(!is.element(nameTable_step(thisStep - 1),names(current_workMatrix))){
connections_dataBase <- sapply(names(getOption("shape_fileName_dataBase")),function(x){
reset_shapeDB(paste(getOption("shape_outDir"), getOption("shape_fileName_dataBase")[[x]],sep=""),
func_type = "connect")
})
current_workMatrix <- c(current_workMatrix,
setNames(list(dbReadTable(connections_dataBase$timeStep_States, nameTable_step(thisStep - 1))),
nameTable_step(thisStep - 1)))
for(thisConnection in connections_dataBase){ dbDisconnect(thisConnection) }
}
current_workMatrix <- runReplicate(func_inputFrames = current_workMatrix,
func_currStep = thisStep,
func_stepCounter = getOption("shape_counter_logSteps"))
options("shape_counter_logSteps" = getOption("shape_counter_logSteps") + 1)
}
runTime <- proc.time() - startTime
if(!getOption("shape_run_isRecycling")["Parameters"] ||
getOption("shape_thisRep") == getOption("shape_recycle_repStart")){
runParameters <- sapply(getOption("shape_saveParameters"), function(x){
sapply(x,function(y){
getOption(y)
},simplify=FALSE)
},simplify="list")
shape_fileName_dataBase <- getOption("shape_fileName_dataBase")
save(runParameters, runTime, connections_dataBase, shape_fileName_dataBase,
file=paste(getOption("shape_outDir"), save_fileName,sep=""))
}
connections_dataBase <- sapply(names(getOption("shape_fileName_dataBase")),function(x){
reset_shapeDB(paste(getOption("shape_outDir"), getOption("shape_fileName_dataBase")[[x]],sep=""),
func_type = "connect")
})
tmpTables <- RSQLite::dbListTables(connections_dataBase$timeStep_States)
all_lastGenotypes <- dbReadTable(connections_dataBase$timeStep_States,
RSQLite::dbListTables(connections_dataBase$timeStep_States)[which.max(as.numeric(nameTable_step(tmpTables, funcSplit = TRUE)))])
establishedGenotypes <- querryEstablished(func_inMatrix= all_lastGenotypes,
func_estProp = getOption("shape_const_estProp"))
if(nrow(establishedGenotypes) > 0){
for(thisGenotype in 1:nrow(establishedGenotypes)){
tmp_genotypeInfo <- retrieve_binaryString(func_genotypeID = establishedGenotypes[thisGenotype,"genotypeID"],
func_numMuts = establishedGenotypes[thisGenotype,"numMuts"],
func_subNaming = getOption("shape_db_splitTables"),
func_landscapeCon = connections_dataBase$genotypeSpace)
if(!as.logical(tmp_genotypeInfo[1,"isExplored"])){
createGenotypes(tmp_focalGenotype = tmp_genotypeInfo[1,"binaryString"],
tmp_focalFitness= if(is.element(getOption("shape_simModel"),c("NK","Additive"))){
getOption("shape_const_siteBystate_fitnessMat")
} else {
establishedGenotypes[thisGenotype,"fitness"]
},
maxHamming = getOption("shape_max_numMutations"),
tmp_landModel = getOption("shape_simModel"),
tmp_relativeFitness = getOption("shape_const_relativeFitness"),
tmpDistribution = getOption("shape_constDist"),
tmpParameters = getOption("shape_const_distParameters"),
tmp_genCon = connections_dataBase$genotypeSpace,
tmp_tableSplit = getOption("shape_db_splitTables"),
tmp_distAsS = getOption("shape_const_distAsS"))
}
}
}
for(thisConnection in connections_dataBase){ dbDisconnect(thisConnection) }
if(getOption("shape_toggle_forceCompletion") &&
thisStep != (getOption("shape_numGenerations") / getOption("shape_size_timeStep"))){
stopError("There was a problem and the main body run did not complete, please review")
} else if(thisStep == (getOption("shape_numGenerations") / getOption("shape_size_timeStep"))) {
print("Simulations completed without crashing ")
} else {
print("Simulation code reached end of loop ")
}
connections_dataBase <- sapply(names(getOption("shape_fileName_dataBase")),function(x){
reset_shapeDB(paste(getOption("shape_outDir"),
getOption("shape_fileName_dataBase")[[x]],
sep=""),
func_type = "connect")
})
tmpReport <- runProcessing(func_saveFile = getOption("shape_processedData_fileName"),
func_subNaming = getOption("shape_db_splitTables"),
func_stepsCon = connections_dataBase[["timeStep_States"]],
func_landscapeCon = connections_dataBase[["genotypeSpace"]],
func_hoodCon = connections_dataBase[["nearestNeighbours"]],
func_estProp = getOption("shape_const_estProp"),
func_size_timeStep = getOption("shape_size_timeStep"),
func_processObjects = getOption("shape_processedObjects"),
func_hoodPriority = getOption("shape_const_hoodDepth"))
print( tmpReport )
if(getOption("shape_results_removeSteps") &&
grepl("Processing completed", tmpReport) &&
file.exists(getOption("shape_processedData_fileName"))){
dbDisconnect(connections_dataBase[["timeStep_States"]])
connections_dataBase[["timeStep_States"]] <- NULL
file.remove(paste(getOption("shape_outDir"),
getOption("shape_fileName_dataBase")[["timeStep_States"]],
sep=""))
}
for(thisConnection in connections_dataBase){ dbDisconnect(thisConnection) }
if(!getOption("shape_run_isRecycling")["Neighbourhood"]){
file.remove(paste(getOption("shape_outDir"),
getOption("shape_fileName_dataBase")[["nearestNeighbours"]],
sep=""))
}
if(getOption("shape_thisRep") < getOption("shape_maxReplicates") && getOption("shape_externalSelfing")){
if(!file.exists(getOption("shape_tmp_selfScript"))){
stopError("There was a problem while trying to self, as the template did not exist. Please review")
} else {
tmp_nextRep <- getOption("shape_thisRep") + 1
tmp_jobName <- name_batchString(funcBase = getOption("shape_save_batchString"),
func_repID = tmp_nextRep)
tmpScript <- readLines(getOption("shape_tmp_selfScript"))
tmpScript <- updateLines(func_inLines = tmpScript,
func_searchPattern = list("rep"=c("shape_thisRep=","shape_thisRep=([[:digit:]])+")),
func_values = list("rep"=paste("shape_thisRep=",tmp_nextRep,sep="")))
writeLines(tmpScript, con = getOption("shape_tmp_selfScript"))
Sys.chmod(getOption("shape_tmp_selfScript"), mode="0777")
}
tmp_stopFile <- paste(getOption("shape_finalDir"),getOption("shape_external_stopFile"), sep="")
if(file.exists(tmp_stopFile)){
file.remove(tmp_stopFile)
}
}
if(getOption("shape_serverFarm") && !getOption("shape_externalSelfing")) {
if(getOption("shape_thisRep") %% 20 == 0){
system(paste("cd ",getOption("shape_outDir")," ; cp *.RData *.sqlite *.Rout *.o ",getOption("shape_finalDir"),sep=""))
}
}
}
invisible( NULL )
}
shapeExperiment <- function(func_filepath_toDesign, func_templateDir,
func_maxGrouped_perShell = 2,
func_filePath_R = NULL, func_baseCall = "CMD BATCH",
func_rArgs = '"--args shape_thisRep=1 shape_outDir=\'fake_serverPath/fakeDir/\'"',
func_remoteLocation = "$TMPDISK",
func_submitArgs = c("number_ofCores"='-c 1',
"memory"='--mem=8192',
"jobName"='-J fakeJob',
"wallTime"='-t 14-00:00:00',
"fileOut"='-o fakeOut'),
func_processingCores = 1,
func_suppressOld_summaryFiles = FALSE){
if(!file.exists(func_filepath_toDesign)){
stopError(paste("Could not find the experimental design file at: ",func_filepath_toDesign,sep=""))
}
if(is.null(func_filePath_R)){
func_tmpVersion <- strsplit(version[['version.string']], "[[:space:]]+")[[1]][3]
func_filePath_R <- if(grepl("^window",Sys.info()["sysname"],ignore.case=TRUE)){
paste("C:/Program Files/R/R-",func_tmpVersion,"/bin/R",sep="")
} else {
"/usr/bin/R"
}
}
inputReference <- list("shape_serverFarm",
"shape_results_removeSteps",
"shape_externalSelfing",
"shape_toggle_forceCompletion",
"shape_workDir",
"shape_postDir",
"shape_save_batchBase",
"shape_save_batchJob",
"shape_maxReplicates",
"uniqueReplicates",
"shape_const_distType",
"shape_init_distPars",
"shape_const_growthGenerations",
"shape_numGenerations",
"shape_size_timeStep",
"shape_genomeLength",
"shape_const_focal_popValue",
"shape_const_birthProb",
"shape_const_growthRate",
"shape_const_deathProb",
"shape_death_byDensity",
"shape_death_densityCorrelation",
"shape_death_densityCap",
"shape_scaleGrowth_byDeaths",
"shape_const_mutProb",
"shape_muts_onlyBirths",
"shape_allow_backMutations",
"shape_const_growthForm",
"shape_simModel",
"shape_const_ancestFitness",
"shape_constDist",
"shape_const_distParameters",
"shape_const_distAsS",
"shape_const_RMF_initiDistance",
"shape_const_RMF_theta",
"shape_const_numInteractions",
"shape_const_fixedFrame",
"shape_includeDrift",
"shape_track_asWhole",
"shape_const_estProp",
"shape_const_hoodThresh")
notExpanded_reference <- c("shape_serverFarm",
"shape_results_removeSteps",
"shape_externalSelfing",
"shape_toggle_forceCompletion",
"shape_workDir",
"shape_save_batchBase",
"shape_maxReplicates",
"uniqueReplicates")
comboReference <- c("shape_simModel",
"shape_const_ancestFitness",
"shape_constDist",
"shape_const_distParameters",
"shape_const_distAsS")
conditionReference <- list("RMF"=c("shape_const_RMF_theta",
"shape_const_RMF_initiDistance"),
"NK"=c("shape_const_numInteractions"),
"Fixed"=c("shape_const_fixedFrame"))
fileName_templates <- c("body"="SHAPE_runBody.v.",
"serverSubmit"="SHAPE_serverTemplate.v.",
"localSubmit"="SHAPE_localTemplate.v.",
"parameter_output" = "SHAPE_parameters.v.")
allFiles <- list.files(path = func_templateDir, recursive = FALSE)
for(thisFile in names(fileName_templates)){
tmpFile <- allFiles[which(grepl(fileName_templates[thisFile], allFiles,fixed=TRUE))]
if(length(tmpFile) == 1){
fileName_templates[thisFile] <- paste(func_templateDir,tmpFile,sep="")
if(thisFile == "functions"){ source(fileName_templates[thisFile]) }
} else {
stopError(paste("Could not find a unique file like ",fileName_templates[thisFile],
" in ",func_templateDir," please review and ensure the template exists",sep=""))
}
}
inputParms <- readLines(func_filepath_toDesign)
inputParms <- inputParms[intersect(intersect(which(!grepl("
which(!grepl("[[:space:]]",substr(inputParms,
sapply(nchar(inputParms),function(x){ min(1,x) }),
sapply(nchar(inputParms),function(x){ min(1,x) })) ))),
which(nchar(inputParms) > 0))]
inputParms <- lapply(strsplit(inputParms," <-"),function(x){
return( c(x[1],
if(!is.element(x[1],c("shape_const_distParameters","shape_init_distPars"))){
tmpReturn <- unlist(strsplit(x[2],',',fixed=TRUE))
tmpReplace <- suppressWarnings(as.numeric(tmpReturn))
tmpReturn[which(!is.na(tmpReplace))] <- tmpReplace[which(!is.na(tmpReplace))]
tmpSpaces <- gregexpr("[[:space:]]",tmpReturn)
for(thisItem in 1:length(tmpSpaces)){
if(tmpSpaces[[thisItem]][1] != -1){
tmpStart <- if(tmpSpaces[[thisItem]][1] == 1){
tmpMax <- which(diff(tmpSpaces[[thisItem]]) != 1)
if(length(tmpMax) == 0){
tmpMax <- 0
} else {
tmpMax <- tmpSpaces[[thisItem]][max(tmpMax)] - 1
}
2+tmpMax
} else {
1
}
tmpEnd <- if(tmpSpaces[[thisItem]][length(tmpSpaces[[thisItem]])] == nchar(tmpReturn[thisItem])){
tmpMax <- which(diff(tmpSpaces[[thisItem]]) != 1)
if(length(tmpMax) == 0){
tmpMax <- nchar(tmpReturn[thisItem])
} else {
tmpMax <- tmpSpaces[[thisItem]][max(tmpMax)+1]
}
tmpMax -1
} else {
nchar(tmpReturn[thisItem])
}
tmpReturn[thisItem] <- substr(tmpReturn[thisItem],tmpStart,tmpEnd)
}
}
tmpReturn
} else {
tmpReturn <- unlist(strsplit(gsub("[[:space:]]","",x[2]),'c(',fixed=TRUE))
tmpReturn <- tmpReturn[which(nchar(tmpReturn) > 0)]
unlist(lapply(tmpReturn,function(x){
paste('c(',
if(substr(x,nchar(x),nchar(x)) == ','){
substr(x,1,nchar(x)-1)
} else {
x
},
sep="")
}))
} ))
})
names(inputParms) <- unlist(lapply(inputParms,function(x){x[1]}))
for(thisList in 1:length(inputParms)){ inputParms[[thisList]] <- inputParms[[thisList]][-1] }
if(is.null(inputParms$shape_death_densityCap) || inputParms$shape_death_densityCap == "NULL"){
inputParms$shape_death_densityCap <- inputParms$shape_const_focal_popValue
}
if(is.null(inputParms[["shape_workDir"]]) || inputParms[["shape_workDir"]] == "NULL"){
inputParms[["shape_workDir"]] <- paste('"',gsub('\\','/',tempdir(),fixed=TRUE),'"',sep="")
}
for(thisObject in c("shape_workDir")){
tmpString <- inputParms[[thisObject]]
if(!grepl('/\"$',tmpString)){
inputParms[[thisObject]] <- paste(substr(tmpString,1,nchar(tmpString)-1),
"/",
substr(tmpString,nchar(tmpString),nchar(tmpString)),
sep="")
}
}
tmpDir <- paste(trimQuotes(inputParms[["shape_workDir"]]),collapse="")
if(!dir.exists(tmpDir)){
dir.create(tmpDir, recursive = TRUE)
}
parameterCombos <- shapeCombinations(func_inLines = inputParms,
func_comboRef = comboReference,
func_indepRef = notExpanded_reference,
func_condRef = conditionReference)
write.table(parameterCombos,
file = paste(tmpDir,trimQuotes(inputParms$shape_save_batchBase),"_parameterCombos.table",sep=""),
append = as.numeric(parameterCombos[1,"shape_save_batchJob"]) != 1,
quote = FALSE,
row.names = FALSE,
qmethod = "double",
sep = "\t",
dec =".",
fileEncoding = "cp1252")
tmp_newDirs <- paste(tmpDir,
name_batchString(funcBase = trimQuotes(inputParms$shape_save_batchBase),
func_setID = unlist(lapply(1:as.numeric(inputParms$uniqueReplicates),rep,"times"=nrow(parameterCombos))),
func_jobID = parameterCombos$shape_save_batchJob,
func_sepString = getOption("shape_sepString")),
sep="")
for(thisDir in tmp_newDirs){
if(!dir.exists(thisDir)){ dir.create(thisDir, recursive = TRUE) }
}
for(thisTemplate in names(fileName_templates)){
if (thisTemplate == "parameter_output") {
writeParameters(func_infile = fileName_templates[thisTemplate],
func_inParms = inputParms,
func_inCombos = parameterCombos,
func_outDir = tmpDir,
func_bodyScript = fileName_templates["body"],
func_ExternalStopper = getOption("shape_external_stopFile"))
} else if(as.logical(inputParms$shape_serverFarm) && thisTemplate == "serverSubmit" ||
!as.logical(inputParms$shape_serverFarm) && thisTemplate == "localSubmit") {
write_subScript(func_subScipt = fileName_templates[thisTemplate],
func_outDir = tmpDir,
func_inCombos = parameterCombos,
func_inParms = inputParms,
func_maxJobs= func_maxGrouped_perShell,
func_appLocation = func_filePath_R,
func_remoteLocation = func_remoteLocation,
func_commonArgs = func_baseCall,
func_submitArgs = func_submitArgs,
func_passedArgs = func_rArgs)
}
}
func_processingScript <- paste(trimQuotes(inputParms[["shape_workDir"]]),"summariseExperiment_",
trimQuotes(inputParms[["shape_save_batchBase"]]),".r",sep="")
cat(c("library(rSHAPE)",
paste("defineSHAPE(shape_save_batchSet = ",if(!is.null(inputParms$uniqueReplicates)){1}else{NULL},",\n ",
"shape_save_batchJob = ",if(!is.null(inputParms$shape_save_batchJob)){1}else{NULL},",\n ",
'shape_sepString = "',getOption("shape_sepString"),'",\n ',
'shape_sepLines = "',getOption("shape_sepLines"),'",\n ',
"shape_workDir = ",inputParms[["shape_workDir"]],",\n ",
'shape_postDir = "',paste(trimQuotes(inputParms[["shape_workDir"]]),
trimQuotes(inputParms[["shape_postDir"]]),
sep=""),'",\n ',
"shape_save_batchBase = ",inputParms$shape_save_batchBase,",\n ",
'shape_string_lineDescent = "',getOption("shape_string_lineDescent"),'")',
sep=""),
paste("summariseExperiment(func_numCores = ",func_processingCores,", ",
"func_suppressOld = ",func_suppressOld_summaryFiles,
")",sep=""),
'q(save="no")'),
file = func_processingScript,
sep = "\n",
append = FALSE)
func_processing_subScript <- paste(trimQuotes(inputParms[["shape_workDir"]]),"summariseExperiment_",
trimQuotes(inputParms[["shape_save_batchBase"]]),".sh",sep="")
cat(c("
paste(func_filePath_R,
func_baseCall,
func_processingScript,
paste(func_processingScript,".Rout",sep=""),
sep=" ")),
file = func_processing_subScript,
sep = "\n",
append = FALSE)
Sys.chmod(list.files(path=tmpDir,pattern='.sh',recursive=TRUE,full.names=TRUE),
mode="0777")
fileName_farmingImage <- paste(trimQuotes(inputParms$shape_save_batchBase),"_shapeExperiment_image.RData",sep="")
save.image(paste(tmpDir,fileName_farmingImage,sep=""))
return( "Function completed to end, experiment is likely built!" )
}
write_subScript <- function(func_subScipt, func_outDir, func_inCombos, func_inParms, func_maxJobs,
func_appLocation, func_commonArgs, func_submitArgs,
func_remoteLocation, func_passedArgs,
func_externalStopper = getOption("shape_external_stopFile"),
func_sepString = getOption("shape_sepString")){
func_submitLines <- readLines(func_subScipt,warn=FALSE)
if(as.logical(func_inParms$shape_externalSelfing)){
func_tmpLine <- which(grepl("
func_submitLines <- c(func_submitLines[1:func_tmpLine],
paste('echo "" > fake_workDir/',func_externalStopper,sep=""),
func_submitLines[(func_tmpLine+1):length(func_submitLines)],
paste('if ! [ -e "fake_workDir/',func_externalStopper,'" ]',sep=""),
'then',
' fake_workDir/fakeSubmit',
'fi')
}
func_submitLines <- gsub("fake_appPath",func_appLocation,func_submitLines)
func_submitLines <- gsub("fake_commandArgs",func_commonArgs,func_submitLines)
func_submitLines <- gsub("fake_passedArgs",func_passedArgs,func_submitLines)
if(as.logical(func_inParms$shape_serverFarm)){
func_tmpLine <- which(grepl("fake_subMit_command",func_submitLines))
func_submitLines <- c(func_submitLines[1:(func_tmpLine-1)],
paste("
func_submitLines[(func_tmpLine+1):length(func_submitLines)])
func_submitLines <- gsub("fake_serverPath",func_remoteLocation,func_submitLines)
}
func_tmpCounter <- 0
func_jobBatch <- 1
func_masterCon <- file(description = paste(func_outDir,name_batchSubmit(func_jobBatch),sep=""), open = "w")
for(thisCombo in 1:nrow(func_inCombos)){
for(shape_thisRep in 1:as.numeric(func_inParms$uniqueReplicates)){
tmp_jobString <- name_batchString(funcBase = trimQuotes(func_inParms$shape_save_batchBase),
func_setID = shape_thisRep,
func_jobID = func_inCombos[thisCombo,"shape_save_batchJob"],
func_sepString = func_sepString)
tmp_jobDir <- paste(func_outDir,
tmp_jobString,
"/",sep="")
tmpSubmit_fileName <- name_subScript(tmp_jobString)
tmp_submit <- gsub("fake_workDir",tmp_jobDir,func_submitLines)
tmp_submit <- gsub("fake_tmpScript.r",name_bodyScript(tmp_jobString),tmp_submit)
if(as.logical(func_inParms$shape_serverFarm)){
tmp_submit <- gsub("fakeOut",paste(tmp_jobString,".o",sep=""),tmp_submit)
tmp_submit <- gsub("fakeJob",tmp_jobString,tmp_submit)
tmp_submit <- gsub("fakeDir",tmp_jobString,tmp_submit)
} else {
tmp_submit <- gsub("fake_serverPath/fakeDir/",tmp_jobDir,tmp_submit)
}
if(as.logical(func_inParms$shape_externalSelfing)){
tmp_submit <- gsub("fakeSubmit",tmpSubmit_fileName,tmp_submit)
}
writeLines(tmp_submit, con = paste(tmp_jobDir,tmpSubmit_fileName,sep=""))
func_tmpCounter <- func_tmpCounter + 1
if(as.logical(func_inParms$shape_serverFarm)){
if(func_tmpCounter > func_maxJobs){
func_tmpCounter <- func_tmpCounter - (func_maxJobs + 1)
func_jobBatch <- func_jobBatch + 1
close(func_masterCon)
func_masterCon <- file(description = paste(func_outDir,name_batchSubmit(func_jobBatch),sep=""), open = "w")
}
} else {
if(func_tmpCounter > ceiling((nrow(func_inCombos) * as.numeric(func_inParms$uniqueReplicates))/func_maxJobs)){
func_tmpCounter <- 0
func_jobBatch <- func_jobBatch + 1
close(func_masterCon)
func_masterCon <- file(description = paste(func_outDir,name_batchSubmit(func_jobBatch),sep=""), open = "w")
}
}
tmp_masterSubmit <- paste(if(as.logical(func_inParms$shape_serverFarm)){"sbatch "}else{NULL},
tmp_jobDir,tmpSubmit_fileName,sep="")
writeLines(tmp_masterSubmit, con = func_masterCon, sep="\n")
}
}
close(func_masterCon)
return( "Done writting out submission scripts" )
}
writeParameters <- function(func_infile, func_inParms, func_inCombos, func_outDir, func_bodyScript,
func_ExternalStopper, func_sepString = getOption("shape_sepString")){
func_parmLines <- readLines(func_infile, warn=FALSE)
func_bodyLines <- readLines(func_bodyScript, warn=FALSE)
func_constParms <- c("shape_serverFarm","shape_results_removeSteps","shape_externalSelfing","shape_toggle_forceCompletion",
"shape_save_batchBase", "shape_maxReplicates","shape_workDir")
func_parmLines <- updateLines(func_inLines = func_parmLines,
func_searchPattern = sapply(names(func_inParms[func_constParms]),paste," <-","sep"=""),
func_values = func_inParms[func_constParms])
for(thisCombo in 1:nrow(func_inCombos)){
tmp_parmLines <- updateLines(func_inLines = func_parmLines,
func_searchPattern = sapply(colnames(func_inCombos),paste," <-","sep"=""),
func_values = func_inCombos[thisCombo,colnames(func_inCombos)])
for(shape_thisRep in 1:as.numeric(func_inParms$uniqueReplicates)){
tmp_jobString <- name_batchString(funcBase = trimQuotes(func_inParms$shape_save_batchBase),
func_setID = shape_thisRep,
func_jobID = func_inCombos[thisCombo,"shape_save_batchJob"],
func_sepString = func_sepString)
tmp_jobDir <- paste(func_outDir,
tmp_jobString,
"/",sep="")
tmpParm_fileName <- name_parameterScript(tmp_jobString)
tmpBody_fileName <- name_bodyScript(tmp_jobString)
tmp_bodyLines <- updateLines(func_inLines =func_bodyLines,
func_searchPattern = list("source"="sourceParms <-"),
func_values = list("source"= addQuotes(paste(tmp_jobDir,tmpParm_fileName,sep=""))))
tmp_jobParms <- updateLines(func_inLines =tmp_parmLines,
func_searchPattern = list("shape_save_batchSet"="shape_save_batchSet <-",
"shape_save_batchJob"="shape_save_batchJob <-"),
func_values = list("shape_save_batchSet"= shape_thisRep,
"shape_save_batchJob"=func_inCombos[thisCombo,"shape_save_batchJob"]))
writeLines(tmp_bodyLines, con = paste(tmp_jobDir,tmpBody_fileName,sep=""))
writeLines(tmp_jobParms, con = paste(tmp_jobDir,tmpParm_fileName,sep=""))
}
}
return( "Have written out all job's parameters and body scripts" )
}
updateLines <- function(func_inLines,func_searchPattern, func_values){
if(!all(is.element(names(func_searchPattern),names(func_values)))){
stopError("There were not similar searchPattern and values passed to updateLines, please review")
}
func_updateLines <- NULL
for(thisUpdate in names(func_searchPattern)){
func_updateLines <- func_inLines
func_tmpLine <- which(grepl(func_searchPattern[[thisUpdate]][1],func_updateLines))[1]
if(length(func_searchPattern[[thisUpdate]]) == 1){
func_updateLines[func_tmpLine] <- paste(func_searchPattern[[thisUpdate]],func_values[[thisUpdate]][1],sep=" ")
} else if(length(func_searchPattern[[thisUpdate]]) == 2){
func_updateLines[func_tmpLine] <- sub(func_searchPattern[[thisUpdate]][2],func_values[[thisUpdate]][1],func_updateLines[func_tmpLine])
} else if(length(func_searchPattern[[thisUpdate]]) == 3){
func_tmpPositions <- list(regexpr(func_searchPattern[[thisUpdate]][2],func_updateLines[func_tmpLine],fixed=TRUE),
gregexpr(func_searchPattern[[thisUpdate]][3],func_updateLines[func_tmpLine]))
func_tmpPositions <- lapply(func_tmpPositions,function(x){
matrix(c(unlist(x),attr(if(is.list(x)){x[[1]]}else{x},"match.length")),nrow=2,
byrow = TRUE,dimnames=list(c("location","length"),NULL))
})
if(!all(sapply(func_tmpPositions,function(x){ any(x["location",] > 0) }))){
stopError(paste("Could not find the proper replacement positions for ",thisUpdate," please review",sep=""))
}
func_usePosition <- which(func_tmpPositions[[2]]["location",] > func_tmpPositions[[1]]["location",1])[1]
func_tmpPositions <- func_tmpPositions[[2]][,func_usePosition]
func_updateLines[func_tmpLine] <- paste(substr(func_updateLines[func_tmpLine],1,func_tmpPositions[1]-1),
func_values[[thisUpdate]],
substr(func_updateLines[func_tmpLine],sum(func_tmpPositions),nchar(func_updateLines[func_tmpLine])),
sep="")
}
func_inLines <- func_updateLines
}
return( func_inLines )
}
shapeCombinations <- function(func_inLines, func_comboRef, func_indepRef, func_condRef){
func_parmGrid <- expand.grid(func_inLines[setdiff(names(func_inLines),c(func_comboRef,
func_indepRef,
unname(unlist(func_condRef)),
"shape_save_batchJob"))],
stringsAsFactors=FALSE,
KEEP.OUT.ATTRS = FALSE)
func_tmpLengths <- sapply(func_inLines[func_comboRef],length)
if(!all(max(func_tmpLengths) == func_tmpLengths)){
func_tmpUpdate <- which(func_tmpLengths != max(func_tmpLengths))
for(thisUpdate in func_tmpUpdate){
func_inLines[func_comboRef[thisUpdate]] <- list(unname(unlist(rep(func_inLines[func_comboRef[thisUpdate]],max(func_tmpLengths))))[1:max(func_tmpLengths)])
}
}
func_comboAdd <- matrix(unlist(func_inLines[func_comboRef]),nrow=max(func_tmpLengths),dimnames=list(NULL,func_comboRef))
for(thisCond in names(func_condRef)){
func_startCols <- colnames(func_comboAdd)
func_tmpLines <- which(grepl(thisCond,func_comboAdd[,"shape_simModel"]))
func_condAdd <- as.matrix(expand.grid(func_inLines[func_condRef[[thisCond]]],
stringsAsFactors=FALSE, KEEP.OUT.ATTRS = FALSE))
for(thisAddition in 1:ncol(func_condAdd)){
func_comboAdd <- cbind(func_comboAdd,func_condAdd[1,thisAddition])
}
colnames(func_comboAdd)[(ncol(func_comboAdd)-(ncol(func_condAdd)-1)):ncol(func_comboAdd)] <- colnames(func_condAdd)
if(length(func_tmpLines) > 0){
if(nrow(func_condAdd) > 1){
for(thisRow in 2:nrow(func_condAdd)){
for(thisUnique in func_tmpLines){
func_comboAdd <- rbind(func_comboAdd, c(unlist(func_comboAdd[thisUnique,func_startCols]),unlist(func_condAdd[thisRow,])))
}
}
}
}
}
func_tmpNew1 <- NULL
for(thisRow in 1:nrow(func_comboAdd)){
func_tmpNew1 <- rbind(func_tmpNew1,matrix(rep(func_comboAdd[thisRow,],nrow(func_parmGrid)),
nrow=nrow(func_parmGrid), byrow = TRUE,
dimnames=list(NULL,colnames(func_comboAdd))))
}
func_tmpNew2 <- NULL
for(thisAddition in 1:nrow(func_comboAdd)){
func_tmpNew2 <- rbind(func_tmpNew2,func_parmGrid)
}
func_parmGrid <- cbind(func_tmpNew2,func_tmpNew1,stringsAsFactors=FALSE)
func_parmGrid <- unique(func_parmGrid)
func_parmGrid <- cbind(func_parmGrid,as.numeric(func_inLines$shape_save_batchJob):
(nrow(func_parmGrid)+(as.numeric(func_inLines$shape_save_batchJob)-1)),
stringsAsFactors=FALSE)
colnames(func_parmGrid)[ncol(func_parmGrid)] <- "shape_save_batchJob"
return( func_parmGrid )
}
summariseExperiment <- function(func_processingTypes = c("fileList", "parameters", "popDemographics","repeatability"),
func_numCores = 1, func_suppressOld = FALSE){
func_processingOptions <- getOption("shape_procExp_filenames")
func_processingTypes <- func_processingTypes[which(is.element(func_processingTypes,
names(func_processingOptions)))]
if(length(func_processingTypes) == 0 ){
return("No valid func_processingTypes strings passed, not trying to run experiment processing.")
}
if(func_suppressOld){
func_tmpRemove <- func_processingOptions[which(file.exists(func_processingOptions))]
if(length(func_tmpRemove) > 0){ file.remove(func_tmpRemove) }
}
func_useCluster <- parallel::makeCluster(func_numCores, type="PSOCK")
doParallel::registerDoParallel(func_useCluster)
funcSave_jobExpression <- name_batchString(funcBase = getOption("shape_save_batchBase"),
func_setID = if(!is.null(getOption("shape_save_batchSet"))){
paste('[^',getOption("shape_sepString"),']+',sep="")
}else{
NULL
},
func_jobID = if(!is.null(getOption("shape_save_batchJob"))){
paste('[^',getOption("shape_sepString"),']+',sep="")
}else{
NULL
},
func_sepString = getOption("shape_sepString"))
if(is.element("fileList",names(func_processingOptions)) &&
!file.exists(func_processingOptions["fileList"])){
summarise_experimentFiles()
}
if(is.element("parameters",names(func_processingOptions)) &&
!file.exists(func_processingOptions["parameters"])){
summarise_experimentParameters()
}
if(is.element("popDemographics",names(func_processingOptions)) &&
!file.exists(func_processingOptions["popDemographics"])){
summarise_popDemographics(funcSave_jobExpression = funcSave_jobExpression)
}
if(is.element("repeatability",names(func_processingOptions)) &&
!file.exists(func_processingOptions["repeatability"])){
summarise_evolRepeatability(funcSave_jobExpression = funcSave_jobExpression)
}
stopCluster(func_useCluster)
func_existingOutput <- file.exists(func_processingOptions[func_processingTypes])
return( ifelse(all(func_existingOutput),
"Reached end of summariseExperiment, output summaries found.",
"Missing at least one of the requested summary outputs from summariseExperiment.") )
}
summarise_experimentFiles <- function(func_experimentDir = getOption("shape_workDir"),
func_saveFile = getOption("shape_procExp_filenames")["fileList"],
func_search_filePattern = getOption("shape_processedData_filePattern"),
func_sepString = getOption("shape_sepString")){
all_proccessedFiles <- list.files(path= func_experimentDir,
pattern= func_search_filePattern,
recursive = TRUE, full.names=TRUE)
all_jobInfo <- name_batchString(funcBase = paste(getOption("shape_save_batchBase"),
unlist(lapply(strsplit(all_proccessedFiles, func_search_filePattern),function(thisFile){
gsub('.RData',"",thisFile[2],fixed=TRUE)
})),
sep=""),
func_setID = !is.null(getOption("shape_save_batchSet")),
func_jobID = !is.null(getOption("shape_save_batchJob")),
func_repID = TRUE,
funcSplit = TRUE,
func_sepString = func_sepString)
all_uniqueJobs <- name_batchString(funcBase = getOption("shape_save_batchBase"),
func_setID = paste('[^',func_sepString,']+',sep=""),
func_jobID = unique(all_jobInfo["jobID",]),
func_sepString = func_sepString)
all_dividedFiles <- sapply(all_uniqueJobs,function(x){
return( all_proccessedFiles[which(grepl(paste(x,"(.+)",sep=func_sepString), all_proccessedFiles))] )
},simplify=FALSE)
if(length(all_proccessedFiles) != length(unlist(all_dividedFiles))){
stopError(" There was a problem when dividing the all_proccessedFiles into divdedFiles, please review")
}
save(all_proccessedFiles, all_jobInfo, all_dividedFiles,
file= func_saveFile)
invisible( NULL )
}
summarise_experimentParameters <- function(func_workEnvir = new.env(),
func_saveFile = getOption("shape_procExp_filenames")["parameters"],
func_experimentDir = getOption("shape_workDir"),
func_refFile = getOption("shape_procExp_filenames")["fileList"]){
if(!file.exists(func_refFile)){
stopError("Did not find the reference file needed for summarise_experimentParameters")
}
load(func_refFile, envir = func_workEnvir)
func_tmpDirs <- list.dirs(path=func_experimentDir,full.names=FALSE,recursive=FALSE)
func_tmpDirs <- unique(unlist(lapply(names(func_workEnvir$all_dividedFiles), function(thisName){
return( func_tmpDirs[which(grepl(thisName,func_tmpDirs))] )
})))
all_parmInfo <- NULL
tmp_chunkSize <- 100
tmp_numChunks <- ceiling(length(func_tmpDirs)/tmp_chunkSize)
for(thisChunk in 1:tmp_numChunks){
tmpAdd <- NULL
for(thisJob in func_tmpDirs[(1+((thisChunk - 1)*tmp_chunkSize)):min((thisChunk*tmp_chunkSize),length(func_tmpDirs))]){
tmp_parmFile <- list.files(path=paste(func_experimentDir,thisJob,"/",sep=""), pattern = "Parameters")
if(length(tmp_parmFile) == 1){
load(paste(func_experimentDir,thisJob,"/",tmp_parmFile,sep=""),envir= func_workEnvir)
} else {
stopError(paste("Could not find the parameters files to load for ",thisJob,sep=""))
}
tmp_parmsRef <- c(func_workEnvir$runParameters$Population,
func_workEnvir$runParameters$Growth_Disturbance[which(!is.element(names(func_workEnvir$runParameters$Growth_Disturbance),
c("shape_const_growthGenerations",
"shape_init_distPars",
"shape_track_distSize")))],
"distFactor"= unname(func_workEnvir$runParameters$Growth_Disturbance$shape_init_distPars["factor"]),
"distSpread"= unname(func_workEnvir$runParameters$Growth_Disturbance$shape_init_distPars["random"]),
"mean_realisedDilution"=mean(func_workEnvir$runParameters$Growth_Disturbance$shape_track_distSize[,"factor"]),
func_workEnvir$runParameters$FitnessLandscape,
func_workEnvir$runParameters$DFE,
"db_splitTables"= func_workEnvir$runParameters$DataManagement$shape_db_splitTables)
tmp_parmsRef$shape_const_distParameters <- paste(tmp_parmsRef$shape_const_distParameters,collapse=",")
rm(list=c("runParameters"), envir = func_workEnvir)
tmpReturn <- data.frame("jobName"=thisJob,
"jobSet"= if(!is.null(getOption("shape_save_batchSet"))){
tmpNames <- names(func_workEnvir$all_dividedFiles)[sapply(names(func_workEnvir$all_dividedFiles),grepl,"x"=thisJob)]
tmpNames[which.max(nchar(tmpNames))]
} else {
thisJob
},
t(unlist(tmp_parmsRef)),
stringsAsFactors = FALSE)
for(thisCol in names(tmp_parmsRef)){ mode(tmpReturn[,thisCol]) <- mode(tmp_parmsRef[[thisCol]]) }
tmpAdd <- rbind(tmpAdd, tmpReturn)
}
all_parmInfo <- rbind(all_parmInfo, tmpAdd)
}
save(all_parmInfo, file= func_saveFile)
invisible( NULL )
}
summarise_popDemographics <- function(funcSave_jobExpression,
func_saveFile = getOption("shape_procExp_filenames")["popDemographics"],
func_experimentDir = getOption("shape_workDir"),
func_saveDir = getOption("shape_postDir"),
func_refFile = getOption("shape_procExp_filenames")[c("fileList","parameters")],
func_workEnvir = new.env(),
func_objPrefix = "popDemo_"){
print("Starting popDemographics")
if(any(!file.exists(func_refFile))){
stopError("Did not find the reference file needed for summarise_experimentParameters")
}
for(thisFile in func_refFile){
load(thisFile, envir = func_workEnvir)
}
all_popSets <- sapply(unique(func_workEnvir$all_parmInfo$jobSet), function(thisSet){
tmp_thisName <- nameObject(func_inString = thisSet,
func_inPrefix = func_objPrefix)
return( list("objName"=tmp_thisName,
"saveFile"= paste(sub(funcSave_jobExpression,"",
sub(getOption("shape_save_batchBase"),
tmp_thisName,
func_saveFile),
fixed=TRUE),sep=""),
"setJobs" = unique(func_workEnvir$all_parmInfo$jobName[which(func_workEnvir$all_parmInfo$jobSet == thisSet)])) )
}, simplify = FALSE)
tmp_missingSets <- names(all_popSets)[unlist(lapply(all_popSets,function(thisSet){
!file.exists(paste(func_saveDir,thisSet[["saveFile"]],sep=""))
}))]
thisCheck <- NULL
tmpCheck <- foreach(thisCheck = tmp_missingSets, .combine="c",
.packages = c("rSHAPE", "DBI","RSQLite")) %dopar% {
tmpList <- vector(mode="list",
length=length(all_popSets[[thisCheck]][["setJobs"]]))
names(tmpList) <- all_popSets[[thisCheck]][["setJobs"]]
for(thisJob in all_popSets[[thisCheck]][["setJobs"]]){
tmpJobs <- func_workEnvir$all_dividedFiles[[thisCheck]][which(grepl(thisJob, func_workEnvir$all_dividedFiles[[thisCheck]]))]
if(length(tmpJobs) > 0){
tmp_replicateInfo <- NULL
tmp_chunkSize <- 100
tmp_numChunks <- ceiling(length(tmpJobs)/tmp_chunkSize)
for(thisChunk in 1:tmp_numChunks){
tmpAdd <- NULL
for(thisFile in tmpJobs[(1+((thisChunk - 1)*tmp_chunkSize)):min((thisChunk*tmp_chunkSize),length(tmpJobs))]){
load(thisFile, envir = func_workEnvir)
tmpAdd <- c(tmpAdd, list("popDemographics"= func_workEnvir$runDemographics$demoMat))
rm(list=c("info_estLines","runDemographics" ), envir = func_workEnvir)
gc()
}
tmp_replicateInfo <- c(tmp_replicateInfo, tmpAdd)
rm(tmpAdd)
gc()
}
tmp_all_popDemos <- array(sapply(tmp_replicateInfo,function(x){ x }),
dim=c(dim(tmp_replicateInfo[[1]]),length(tmp_replicateInfo)),
dimnames = list(rownames(tmp_replicateInfo[[1]]),
colnames(tmp_replicateInfo[[1]]),
NULL))
tmp_all_popDemos <- matrix(apply(tmp_all_popDemos,MARGIN=2,function(thisCol){
c(apply(thisCol,MARGIN=1,mean),apply(thisCol,MARGIN=1,sd))
}),nrow=nrow(tmp_all_popDemos),ncol=ncol(tmp_all_popDemos)*2,
dimnames=list(rownames(tmp_all_popDemos),
unlist(lapply(colnames(tmp_all_popDemos),function(x){ return(c(x,paste("sd",x,sep="_")))}))) )
tmpList[[thisJob]] <- tmp_all_popDemos
rm(tmp_all_popDemos, tmp_replicateInfo)
gc()
}
}
assign(all_popSets[[thisCheck]][["objName"]], tmpList, pos= func_workEnvir)
save(list = all_popSets[[thisCheck]][["objName"]],
file= all_popSets[[thisCheck]][["saveFile"]],
envir = func_workEnvir)
rm(list= all_popSets[[thisCheck]][["objName"]], envir = func_workEnvir)
rm(tmpList)
gc()
return( nameObject(func_inString = all_popSets[[thisCheck]][["objName"]],
func_inPrefix = func_objPrefix,
func_splitStr = TRUE) )
}
tmp_checkCompleted <- sapply(tmp_missingSets,is.element,"set"=tmpCheck)
if(all(tmp_checkCompleted)){
save(all_popSets, file= func_saveFile)
} else {
stop(paste("There was a problem with the sets of: ",paste(names(tmp_checkCompleted)[which(!tmp_checkCompleted)],collapse=" ",sep=" "),sep=""))
}
invisible( NULL )
}
summarise_evolRepeatability <- function(funcSave_jobExpression,
func_saveFile = getOption("shape_procExp_filenames")["repeatability"],
func_experimentDir = getOption("shape_workDir"),
func_saveDir = getOption("shape_postDir"),
func_refFile = getOption("shape_procExp_filenames")[c("fileList","parameters")],
func_workEnvir = new.env(),
func_objPrefix = "Repeat_",
func_sepString = getOption("shape_sepString"),
func_string_line_ofDescent = getOption("shape_string_lineDescent"),
func_processedPattern = getOption("shape_processedData_filePattern"),
func_sepLines = getOption("shape_sepLines")){
print("Starting repeatability")
if(any(!file.exists(func_refFile))){
stopError("Did not find the reference file needed for summarise_experimentParameters")
}
for(thisFile in func_refFile){
load(thisFile, envir = func_workEnvir)
}
all_repSets <- sapply(unique(func_workEnvir$all_parmInfo$jobSet), function(thisSet){
tmp_thisName <- nameObject(func_inString = thisSet,
func_inPrefix = func_objPrefix)
return( list("objName"=tmp_thisName,
"saveFile"= paste(sub(funcSave_jobExpression,"",
sub(getOption("shape_save_batchBase"),
tmp_thisName,
func_saveFile),
fixed=TRUE),sep=""),
"setJobs" = unique(func_workEnvir$all_parmInfo$jobName[which(func_workEnvir$all_parmInfo$jobSet == thisSet)])) )
}, simplify = FALSE)
tmp_missingSets <- names(all_repSets)[unlist(lapply(all_repSets,function(thisSet){
!file.exists(paste(getOption("shape_postDir"),thisSet[["saveFile"]],sep=""))
}))]
tmpCheck <- foreach(thisSet = tmp_missingSets, .combine="c",
.packages = c("rSHAPE", "DBI","RSQLite")) %dopar% {
tmp_foreachString <- "_foreach_"
tmpList <- vector(mode="list",length=length(all_repSets[[thisSet]][["setJobs"]]))
names(tmpList) <- all_repSets[[thisSet]][["setJobs"]]
for(thisJob in all_repSets[[thisSet]][["setJobs"]]){
load(paste(func_experimentDir, thisJob,"/",thisJob,"_Parameters_1.RData",sep=""),
envir = func_workEnvir)
connections_dataBase <- list("genotypeSpace" = reset_shapeDB(paste(func_experimentDir,thisJob,"/",
func_workEnvir$runParameters$DataManagement$shape_fileName_dataBase[["genotypeSpace"]],
sep=""),
func_type = "connect"))
func_landscapeCon <- connections_dataBase$genotypeSpace
func_landTables <- RSQLite::dbListTables(func_landscapeCon)
allow_backMutations <- func_workEnvir$runParameters$FitnessLandscape$shape_allow_backMutations
genomeLength <- func_workEnvir$runParameters$Population$shape_genomeLength
db_splitTables <- func_workEnvir$runParameters$DataManagement$shape_db_splitTables
tmpJobs <- func_workEnvir$all_dividedFiles[[thisSet]][which(grepl(thisJob, func_workEnvir$all_dividedFiles[[thisSet]]))]
tmp_replicateInfo <- NULL
if(length(tmpJobs) > 0){
tmp_replicateInfo <- NULL
tmp_chunkSize <- 100
tmp_numChunks <- ceiling(length(tmpJobs)/tmp_chunkSize)
for(thisChunk in 1:tmp_numChunks){
tmpAdd <- NULL
for(thisFile in tmpJobs[(1+((thisChunk - 1)*tmp_chunkSize)):min((thisChunk*tmp_chunkSize),length(tmpJobs))]){
tmp_fileString <- nameEnviron(strsplit(strsplit(thisFile,"/")[[1]][length(strsplit(thisFile,"/")[[1]])],".",fixed=TRUE)[[1]][1],
funcBase = tmp_foreachString)
assign(tmp_fileString, new.env(), envir = func_workEnvir)
load(thisFile, envir = func_workEnvir[[tmp_fileString]])
tmpEstablished <- func_workEnvir[[tmp_fileString]]$runDemographics$vec_estLineages
lineDemo_maxStep <- which.max(as.numeric(nameTable_step(rownames(func_workEnvir[[tmp_fileString]]$info_estLines$lineDemo),
funcSplit = TRUE,
func_sepString = func_sepString)))
tmp_final_estLineage <- data.frame("genotypeID"=tmpEstablished[which(func_workEnvir[[tmp_fileString]]$info_estLines$lineDemo[lineDemo_maxStep,"isEstablished",as.character(tmpEstablished)] == 1)])
tmp_final_estLineage$binaryString <- rep("",nrow(tmp_final_estLineage))
tmp_final_estLineage[,"binaryString"] <- unlist(lapply(tmp_final_estLineage[,"genotypeID"],function(x){
retrieve_binaryString(func_genotypeID = x,
func_landscapeCon = func_landscapeCon,
func_subNaming = db_splitTables)[,"binaryString"]
}))
tmp_transitionMat <- func_workEnvir[[tmp_fileString]]$runDemographics$transitionMat
tmp_final_domLineage <- cbind("popSize"= func_workEnvir[[tmp_fileString]]$info_estLines$lineDemo[lineDemo_maxStep,"popSize",as.character(tmp_transitionMat[,"genotypeID"])],
matrix(tmp_transitionMat[,c("Step","fitness","genotypeID")],
nrow=nrow(tmp_transitionMat), dimnames = list(NULL,c("Step","fitness","genotypeID"))))
tmp_maxSized = which(tmp_final_domLineage[,"popSize"] == max(tmp_final_domLineage[,"popSize"]))
tmp_final_domLineage <- if(length(tmp_maxSized) != 1){
tmpReturn <- which(tmp_final_domLineage[tmp_maxSized,"Step"]==max(tmp_final_domLineage[tmp_maxSized,"Step"]))
if(length(tmpReturn) > 1){
tmpReturn <- tmpReturn[which(tmp_final_domLineage[tmp_maxSized[tmpReturn],"fitness"]==max(tmp_final_domLineage[tmp_maxSized[tmpReturn],"fitness"]))][1]
}
tmp_final_domLineage[tmp_maxSized[tmpReturn],"genotypeID"]
} else {
tmp_final_domLineage[tmp_maxSized,"genotypeID"]
}
tmp_final_domLineage <- c("genotypeID"=unname(tmp_final_domLineage),
"binaryString"="")
tmp_final_domLineage["binaryString"] <- tmp_final_estLineage[which(tmp_final_estLineage[,"genotypeID"] == tmp_final_domLineage["genotypeID"]),"binaryString"]
tmp_line_of_descent <- as.character(func_workEnvir[[tmp_fileString]]$info_estLines$end_Lines_of_Descent[[tmp_final_domLineage["genotypeID"]]])
tmp_dom_transitions <- strsplit(tmp_line_of_descent,func_string_line_ofDescent)[[1]]
tmp_firstTransition <- if(length(tmp_dom_transitions) == 1){
paste(rep(tmp_dom_transitions[1],2),collapse=func_string_line_ofDescent)
} else {
paste(tmp_dom_transitions[1:2],collapse=func_string_line_ofDescent)
}
tmp_final_domLineage <- c(tmp_final_domLineage,
"line_ofDescent"= paste(tmp_line_of_descent,collapse= func_sepLines),
"firstStep"=tmp_firstTransition)
tmp_initialEst <- dimnames(func_workEnvir[[tmp_fileString]]$info_estLines$lineDemo)[[3]]
tmp_initialEst <- unique(c(tmp_initialEst[which.max(func_workEnvir[[tmp_fileString]]$info_estLines$lineDemo[nameTable_step(0, func_sepString = func_sepString),
"popSize", tmp_initialEst])],
tmp_initialEst[which(func_workEnvir[[tmp_fileString]]$info_estLines$lineDemo[nameTable_step(0, func_sepString = func_sepString),
"isEstablished", tmp_initialEst] == 1)]))
tmp_returnMat <- NULL
if(any(!is.element(tmp_transitionMat[,"genotypeID"],as.numeric(tmp_initialEst))) && length(tmp_initialEst) > 0){
tmp_landscapeTopology <- func_workEnvir[[tmp_fileString]]$info_estLines$landscapeTopology
tmpSteps <- strsplit(rownames(tmp_landscapeTopology),func_string_line_ofDescent)
tmp_minRow <- min(which(!is.element(tmp_transitionMat[,"genotypeID"],as.numeric(tmp_initialEst))))
for(thisRow in tmp_minRow:nrow(tmp_transitionMat)){
tmpID <- tmp_transitionMat[thisRow, ]
tmp_possProgenitors <- which(sapply(tmpSteps,function(x){
as.numeric(x[2]) == tmpID["genotypeID"]
}))
if (length(tmp_possProgenitors) == 0){ next }
tmp_possProgenitors <- matrix(tmp_landscapeTopology[tmp_possProgenitors,],
nrow = length(tmp_possProgenitors),
dimnames=list(rownames(tmp_landscapeTopology)[tmp_possProgenitors],
colnames(tmp_landscapeTopology)))
tmp_possProgenitors <- cbind(tmp_possProgenitors,
t(sapply(strsplit(rownames(tmp_possProgenitors), func_string_line_ofDescent), function(x){
x <- as.numeric(x)
return( c("progenitorID"=x[1],
"offspringID"=x[2]) )
})))
tmp_returnMat <- rbind(tmp_returnMat,
data.frame("progenitor_genotypeID"= tmp_possProgenitors[,"progenitorID"],
"offspring_genotypeID"= tmp_possProgenitors[,"offspringID"],
"progenitor_fitness"= tmp_possProgenitors[,"progenitor_fitness"],
"offspring_fitness"= tmp_possProgenitors[,"offspring_fitness"],
"absRank" = tmp_possProgenitors[,"absRank"],
"hoodSize" = tmp_possProgenitors[,"hoodSize"],
"hoodMin"= tmp_possProgenitors[,"hoodMin"],
"hoodMax"= tmp_possProgenitors[,"hoodMax"],
"num_altPaths"= tmp_possProgenitors[,"num_altPaths"],
"relFit_altPaths" = tmp_possProgenitors[,"relFit_altPaths"],
"prop_maxFit" = tmp_possProgenitors[,"prop_maxFit"],
"progenitor_numMuts"= tmp_possProgenitors[,"progenitor_numMuts"],
"offspring_numMuts"= tmp_possProgenitors[,"offspring_numMuts"],
"transition"=rownames(tmp_possProgenitors),
"transitionStep"= tmpID["Step"],
row.names = rownames(tmp_possProgenitors),
stringsAsFactors = FALSE) )
}
tmp_checkCols <- which(colnames(tmp_returnMat) != "transitionStep")
tmpDuplicated <- duplicated(tmp_returnMat[,tmp_checkCols])
if(any(tmpDuplicated)){
tmp_workMat <- matrix(gsub("[[:space:]]","",as.character(unname(unlist(tmp_returnMat[,tmp_checkCols])))),
ncol = ncol(tmp_returnMat[,tmp_checkCols]))
tmpDuplicated <- lapply(which(tmpDuplicated),function(tmpRow){
which(apply(tmp_workMat,MARGIN=1,function(x){
all(x == tmp_workMat[tmpRow,tmp_checkCols])
}))
})
tmp_removeRows <- NULL
for(thisSet in unique(tmpDuplicated)){
tmp_returnMat[thisSet[1],"transitionStep"] <- paste(tmp_returnMat[thisSet,"transitionStep"],collapse= func_sepString)
tmp_removeRows <- c(tmp_removeRows,thisSet[-1])
}
if(!is.null(tmp_removeRows)){ tmp_returnMat <- tmp_returnMat[-tmp_removeRows,] }
}
} else {
tmp_returnMat <- data.frame("progenitor_genotypeID"= tmp_transitionMat[1,"genotypeID"],
"offspring_genotypeID"= NA,
"progenitor_fitness"=tmp_transitionMat[1,"fitness"],
"offspring_fitness"= NA,
"absRank" = NA,
"hoodSize" = NA,
"hoodMin"= NA,
"hoodMax"= NA,
"num_altPaths"= NA,
"relFit_altPaths" = NA,
"prop_maxFit" = NA,
"progenitor_numMuts"= tmp_transitionMat[1,"numMuts"],
"offspring_numMuts"= NA,
"transition"=paste(tmp_transitionMat[1,"genotypeID"]),
"transitionStep"=0,
stringsAsFactors = FALSE)
}
tmpReturn <- list(list("final_estLineages"= tmp_final_estLineage,
"final_domLineage"= tmp_final_domLineage,
"transitions"= tmp_returnMat))
names(tmpReturn)[length(tmpReturn)] <- nameEnviron(func_Index = tmp_fileString,
funcSplit = TRUE,
funcBase = tmp_foreachString)
tmpAdd <- c(tmpAdd, tmpReturn)
rm(list=c(tmp_fileString),pos= func_workEnvir)
}
tmp_replicateInfo <- c(tmp_replicateInfo, tmpAdd)
rm(tmpAdd)
gc()
}
}
tmpList[[thisJob]] <- tmp_replicateInfo
for(thisConnection in connections_dataBase){ RSQLite::dbDisconnect(thisConnection) }
rm(tmp_replicateInfo, connections_dataBase,func_landscapeCon,
allow_backMutations, genomeLength,db_splitTables,func_landTables)
}
assign(all_repSets[[thisSet]][["objName"]], tmpList, pos= func_workEnvir)
save(list = all_repSets[[thisSet]][["objName"]],
file= all_repSets[[thisSet]][["saveFile"]],
envir = func_workEnvir)
rm(list= all_repSets[[thisSet]][["objName"]], envir = func_workEnvir)
gc()
return( nameObject(func_inString = all_repSets[[thisSet]][["objName"]],
func_inPrefix = func_objPrefix,
func_splitStr = TRUE) )
}
tmp_checkCompleted <- sapply(tmp_missingSets,is.element,"set"=tmpCheck)
if(all(tmp_checkCompleted)){
save(all_repSets,file= func_saveFile)
} else {
stop(paste("There was a problem with the sets of: ",
paste(names(tmp_checkCompleted)[which(!tmp_checkCompleted)],collapse=" ",sep=" "),
sep=""))
}
invisible( NULL )
} |
test_that("envelope print() output", {
msg <- envelope() %>% subject("Test message")
expect_output(print(msg), "Date: +.*\nSubject: +Test message")
})
test_that("class envelope", {
object <- envelope()
expect_equal(class(object), "envelope")
})
test_that("recipient address", {
recipient <- envelope(to = "[email protected]")
expect_equal(recipient$headers$To$values, address("[email protected]"))
})
test_that("sender address", {
sender <- envelope(from = "[email protected]")
expect_equal(sender$headers$From$values, address("[email protected]"))
})
test_that("maximum one sender address", {
expect_error(envelope(from = c("[email protected]", "[email protected]")))
expect_error(envelope() %>% from(c("[email protected]", "[email protected]")))
})
test_that("cc", {
cc <- envelope(cc = "[email protected]")
expect_equal(cc$headers$Cc$values, address("[email protected]"))
})
test_that("bcc", {
bcc <- envelope(bcc = "[email protected]")
expect_equal(bcc$headers$Bcc$values, address("[email protected]"))
})
test_that("reply to", {
reply <- envelope(reply = "[email protected]")
expect_equal(reply$header[["Reply-To"]]$values, address("[email protected]"))
})
test_that("subject", {
subject <- envelope(subject = "Email Subject")
expect_equal(subject$header$Subject$values, "Email Subject")
})
test_that("body text", {
email_text <- envelope(text = "foo")
expect_equal(email_text$parts[[1]]$content, "foo")
})
test_that("body html", {
html <- envelope(html = "<p>foo</p>")
expect_match(html$parts[[1]]$content, "<body><p>foo</p></body>")
})
test_that("append another body", {
msg <- envelope() %>% text("Hello!") %>% html("<p>Goodbye!</p>")
expect_equal(length(msg$parts), 2)
})
test_that("parts are not nested", {
msg <- envelope() %>%
text("Hello!") %>%
html(HTMLPATH) %>%
attachment(JPGPATH)
expect_false(is.nested(msg$parts))
})
test_that("not splitting addresses", {
msg <- envelope(
to = c("Durrell, Gerald <[email protected]>", "Jones, Bob <[email protected]>"),
cc = c("Durrell, Gerald <[email protected]>", "Jones, Bob <[email protected]>"),
bcc = c("Durrell, Gerald <[email protected]>", "Jones, Bob <[email protected]>"),
split = FALSE
)
expect_match(headers(msg), 'To:[[:space:]]+"Durrell, Gerald" <[email protected]>,\r\n[[:space:]]+"Jones, Bob" <[email protected]>')
expect_match(headers(msg), 'Cc:[[:space:]]+"Durrell, Gerald" <[email protected]>,\r\n[[:space:]]+"Jones, Bob" <[email protected]>')
expect_match(headers(msg), 'Bcc:[[:space:]]+"Durrell, Gerald" <[email protected]>,\r\n[[:space:]]+"Jones, Bob" <[email protected]>')
}) |
hgm.so3nc<-hgm.tk.so3nc
hgm.ncso3<-hgm.tk.so3nc
hgm.normalizingConstantOfFisherDistributionOnSO3<-hgm.tk.so3nc
hgm.pwishart<-hgm.tk.pwishart
hgm.ncorthant<-hgm.ko.ncorthant
hgm.normalizingConstantOfOrthant<-hgm.ko.ncorthant
hgm.Rhgm<-hgm.se.hgm
hgm.Rhgm.demo1<-hgm.se.demo1
hgm.ncBingham<-hgm.se.hgm.Bingham
hgm.normalizingConstantOfBinghamDistribution<-hgm.se.hgm.Bingham
hgm.p2wishart<-hgm.tk.p2wishart |
"cochran.test" <-
function(object,data,inlying=FALSE)
{
DNAME <- deparse(substitute(object))
if (is.vector(object)) {
by.factor <- as.factor(1:length(data))
vars <- object
names(vars) <- levels(by.factor)
k <- length(data)
df <- mean(data)
}
else
{
if (missing(data))
data <- environment(object)
bn<-as.character(attr(terms(object),"variables")[-1])
by.factor<-as.factor(data[[bn[2]]])
vars <- tapply(data[[bn[1]]],by.factor,var)
names(vars) <- levels(by.factor)
k <- nlevels(by.factor)
df <- length(data[[bn[1]]])/k
}
if (inlying) {
value <- min(vars)/sum(vars)
group <- levels(by.factor)[which(vars == min(vars))]
method <- "Cochran test for inlying variance"
alt <- paste("Group",group,"has inlying variance")
pval <- pcochran(value,df,k)
}
else {
value <- max(vars)/sum(vars)
group <- levels(by.factor)[which(vars == max(vars))]
method <- "Cochran test for outlying variance"
alt <- paste("Group",group,"has outlying variance")
pval <- 1-pcochran(value,df,k)
}
RVAL <- list(statistic = c(C = value), parameter = c(df = df, k = k),
alternative = alt, p.value = pval, method = method,
estimate = vars, data.name = DNAME)
class(RVAL) <- "htest"
return(RVAL)
} |
uclust <- function(md = NULL, data = NULL, alpha = 0.05, rep = 15) {
if (is.null(md)) {
if (is.null(data)) {
stop("No data provided")
}
md <- as.matrix(dist(data) ^ 2)
}
if (sum("matrix" %in% class(md)) == 0) {
stop("md is not of class matrix")
}
n <- dim(md)[1]
is.h <- suppressMessages(is_homo(rep = rep, md))
ResultadoTesteIsHomo <- is.h
if (is.h$p.MaxTest < alpha) {
bootB <- is.h$bootB
bootB1 <- is.h$bootB1
oBn <- rep_optimBn(md, bootB = bootB, rep = rep)
maxBn <- -oBn$minFobj
n1 <- length(oBn$grupo1)
is.group <- t.Bnbonf(maxBn, n, n1, alpha, bootB = bootB, bootB1 = bootB1)
if (is.group$significant == TRUE) {
clust <- oBn$grupo1
p <- is.group$p.value
}
else {
n2 <- n - n1
minsize <- (n1 == floor(n / 2) || n2 == floor(n / 2))
oBn1 <- maxBnsize1(md)
maxBn1 <- oBn1$maxBn
if (minsize == TRUE) {
clust <- oBn1$grupo1
is.group <- t.Bnbonf(maxBn1, n, 1, alpha, bootB = bootB, bootB1 = bootB1)
p <- is.group$p.value
n1 <- 1
}
while (minsize == FALSE && is.group$significant == FALSE) {
n1m <- min(n1, n2)
n1_min <- n1m + 1
n1_max <- n - n1_min
oBn <- rep_optimBn_restrict(md, n1_max, n1_min, rep = rep)
maxBn <- -oBn$minFobj
maxBnmax <- max(maxBn1, maxBn)
if (maxBnmax == maxBn1) {
n1 <- 1
is.group <- t.Bnbonf(maxBnmax, n, n1, alpha, bootB = bootB, bootB1 = bootB1)
if (is.group$significant == FALSE) {
n1 <- n1_min
}
}
else {
n1 <- length(oBn$grupo1)
is.group <- t.Bnbonf(maxBnmax, n, n1, alpha, bootB = bootB, bootB1 = bootB1)
}
n2 <- n - n1
minsize <- (n1 == floor(n / 2) || n2 == floor(n / 2))
if (is.group$significant == TRUE) {
clust <- oBn$grupo1
p <- is.group$p.value
}
if (minsize == TRUE && is.group$significant == FALSE) {
clust <- oBn1$grupo1
is.group <- t.Bnbonf(maxBn1, n, 1, alpha, bootB = bootB, bootB1 = bootB1)
p <- is.group$p.value
n1 <- 1
}
}
}
alpha_correct <- alpha / (2 ^ (n - 1) - 1)
}
else {
clust <- 1:n
p <- is.h$p.MaxTest
n1 <- n
alpha_correct <- alpha
}
if (n1 != n) {
if (is.group$significant == FALSE) {
n1 <- length(is.h$group1)
ishomo <- FALSE
p <- is.h$p.MaxTest
alpha_correct <- alpha
bn <- Bn(c(length(is.h$group1), length(is.h$group2)), md[c(is.h$group1, is.h$group2), c(is.h$group1, is.h$group2)])
varBn <- (bn / is.h$minFobj) ^ 2
clust <- is.h$group1
}
else {
ord <- c(clust, (1:n)[-clust])
bn <- Bn(c(n1, (n - n1)), md[ord, ord])
varBn <- is.group$varBn
ishomo <- FALSE
}
if (n < 25) {
message(
paste(
"\t U-Statstics Significance Clustering \n\nmax(stdBn) =",
round(-ResultadoTesteIsHomo$minFobj, digits = 4),
"\t homogeneity p-value = ",
round(ResultadoTesteIsHomo$p.MaxTest, digits = 4),
"\t alpha = ",
alpha,
"\nReject H0: Significant partition found \nGroup 1:",
paste(clust, collapse = " "),
"\nGroup 2:",
paste(c(1:n)[-clust], collapse = " ")
)
)
}
else {
message(
paste(
"\t U-Statstics Significance Clustering \n\nmax(stdBn) =",
round(-ResultadoTesteIsHomo$minFobj, digits = 4),
"\t homogeneity p-value = ",
round(ResultadoTesteIsHomo$p.MaxTest, digits = 4),
"\t alpha = ",
alpha,
"\nReject H0: Significant partition found: \nGroup 1 of size",
n1,
"\nGroup 2 of size",
n - n1
)
)
}
}
else {
n1 <- length(is.h$group1)
ishomo <- TRUE
bn <- Bn(c(length(is.h$group1), length(is.h$group2)), md[c(is.h$group1, is.h$group2), c(is.h$group1, is.h$group2)])
varBn <- (bn / is.h$minFobj) ^ 2
message(
paste(
"\t U-Statstics Significance Clustering \n\nmax(stdBn) =",
round(-ResultadoTesteIsHomo$minFobj, digits = 4),
"\t homogeneity p-value = ",
round(ResultadoTesteIsHomo$p.MaxTest, digits = 4),
"\t alpha = ",
alpha,
"\nAccept H0: the sample is homogeneous."
)
)
}
clust2 <- c(1:n)[-clust]
ans <- list(clust, clust2, p, alpha_correct, n1, ishomo, bn, varBn, ResultadoTesteIsHomo)
names(ans) <- c("cluster1", "cluster2", "p.value", "alpha_corrected", "n1", "ishomo", "Bn", "varBn", "ishomoResult")
invisible(return(ans))
}
objBn <- function(assign, mdm) {
n <- length(assign)
n1 <- sum(assign == 0)
n2 <- n - n1
if (n1 == 0 | n2 == 0) {
return(Inf)
}
else {
vaux1 <- which(assign == assign[1])
vaux2 <- c(1:n)[-vaux1]
n1 <- length(vaux1)
n2 <- n - n1
m <- mdm[c(vaux1, vaux2), c(vaux1, vaux2)]
Bns <- Bn(c(n1, n2), m)
return(-Bns)
}
}
optimBn <- function(md, itmax = 200, centers = -1, bootB = -1) {
n <- dim(md)[1]
it <- 1
ass <- vector()
ass_old <- rep(2, n)
ASS <- matrix(ncol = n, nrow = itmax)
Fobj <- vector()
if (centers == -1) {
centers <- sample(n, 2)
}
for (i in 1:n) {
ass[i] <- (md[i, centers[1]]) > (md[i, centers[2]])
}
ass
ASS[1, ] <- ass
while (it < itmax && !prod(ass == ass_old)) {
ass_old <- ass
ord <- sample(n, n)
for (i in ord) {
ass[i] <- 0
f0 <- objBn(ass, md)
ass[i] <- 1
f1 <- objBn(ass, md)
if (f0 < f1) {
ass[i] <- 0
}
}
Fobj[it] <- objBn(ass, md)
it <- it + 1
ASS[it, ] <- ass
}
ans <- list(which(ass == ass[1]), Fobj, it - 1, ASS[1:(it + 1), ], bootB)
names(ans) <- c("grupo1", "Fobj", "numIt", "history", "bootB")
ans
}
rep_optimBn <- function(mdm, rep = 15, bootB = -1) {
ans <- optimBn(mdm, bootB = bootB)
Fobj <- vector()
n <- dim(mdm)[1]
grupo1 <- list()
Fobj[1] <- ans$Fobj[length(ans$Fobj)]
grupo1[[1]] <- ans$grupo1
bootB <- ans$bootB
for (i in 2:rep) {
ans <- optimBn(mdm, bootB = bootB)
Fobj[i] <- ans$Fobj[length(ans$Fobj)]
grupo1[[i]] <- ans$grupo1
}
minFobj <- min(Fobj)
g1 <- grupo1[[which(Fobj == min(Fobj))[1]]]
g2 <- (1:n)[-g1]
ans <- list(minFobj, g1, g2, Fobj, bootB)
names(ans) <- list("minFobj", "grupo1", "grupo2", "Fobj", "bootB")
return(ans)
}
maxBnsize1 <- function(mdm) {
n <- dim(mdm)[1]
vecBn <- vector()
for (i in 1:n) {
vecBn[i] <- Bn(c(1, n - 1), mdm[c(i, c(1:n)[-i]), c(i, c(1:n)[-i])])
}
maxBn <- max(vecBn)
ans <- list(maxBn, which(vecBn == maxBn))
names(ans) <- c("maxBn", "grupo1")
return(ans)
}
optimBn_restrict <- function(md, n1_max, n1_min, itmax = 200) {
if (n1_max < n1_min) {
print("ERROR: n1_max must be larger than n1_min")
}
else {
n <- dim(md)[1]
it <- 1
ass_old <- rep(2, n)
ASS <- matrix(ncol = n, nrow = (itmax + 1))
Fobj <- vector()
ass <- rep(0, n)
ass[sample(n, floor(n / 2))] <- 1
ASS[1, ] <- ass
if (n1_max == n1_min) {
count <- 0
while (it < itmax && count < max(n / 2, 10)) {
ass_old <- ass
ord <- sample(n, n)
for (i in ord) {
v <- (1:n)[-i]
j <- sample(v, 1)
f0 <- objBn(ass, md)
temp_ass <- ass
ass[j] <- ass[i]
ass[i] <- temp_ass[j]
if (sum(ass) <= n1_max && sum(ass) >= n1_min) {
f1 <- objBn(ass, md)
}
else {
f1 <- Inf
}
if (f0 < f1) {
ass <- temp_ass
}
}
Fobj[it] <- objBn(ass, md)
it <- it + 1
ASS[it, ] <- ass
if (prod(ass == ass_old)) {
count <- count + 1
}
else{
count <- 0
}
}
}
else {
while (it < itmax) {
ass_old <- ass
ord <- sample(n, n)
for (i in ord) {
ass[i] <- 0
if (sum(ass) <= n1_max && sum(ass) >= n1_min) {
f0 <- objBn(ass, md)
}
else {
f0 <- Inf
}
ass[i] <- 1
if (sum(ass) <= n1_max && sum(ass) >= n1_min) {
f1 <- objBn(ass, md)
}
else {
f1 <- Inf
}
if (f0 < f1) {
ass[i] <- 0
}
}
Fobj[it] <- objBn(ass, md)
it <- it + 1
ASS[it, ] <- ass
}
}
ans <- list(which(ass == ass[1]), Fobj, it - 1, ASS[1:(it + 1), ])
names(ans) <- c("grupo1", "Fobj", "numIt", "history")
ans
}
}
rep_optimBn_restrict <- function(mdm, n1_max, n1_min, rep = 15) {
ans <- optimBn_restrict(mdm, n1_max, n1_min)
Fobj <- vector()
n <- dim(mdm)[1]
grupo1 <- list()
Fobj[1] <- ans$Fobj[length(ans$Fobj)]
grupo1[[1]] <- ans$grupo1
for (i in 2:rep) {
ans <- optimBn_restrict(mdm, n1_max, n1_min)
Fobj[i] <- ans$Fobj[length(ans$Fobj)]
grupo1[[i]] <- ans$grupo1
}
minFobj <- min(Fobj)
g1 <- grupo1[[which(Fobj == min(Fobj))[1]]]
g2 <- (1:n)[-g1]
ans <- list(minFobj, g1, g2, Fobj)
names(ans) <- list("minFobj", "grupo1", "grupo2", "Fobj")
return(ans)
}
t.Bnbonf <- function(Bn, n, n1, alpha, bootB = -1, bootB1 = -1, md = 1, std = FALSE) {
if (std == FALSE) {
Cn <- vector()
numB <- 2000
if (n1 == 1 || n1 == (n - 1)) {
if (bootB1 == -1) {
bootB1 <- boot_sigma1(c(1, (n - 1)), md)
}
varBn <- bootB1
}
else {
if (bootB == -1) {
bootB <- boot_sigma(c(floor(n / 2), (n - floor(n / 2))), numB, md)
}
n1b <- floor(n / 2)
n2 <- n - n1b
Cnd <- (((n1b * n2) / (n * (n - 1)) ^ 2) * (2 * n ^ 2 - 6 * n + 4) / ((n1b - 1) * (n2 - 1)))
n1b <- n1
n2 <- n - n1b
Cnn <- (((n1b * n2) / (n * (n - 1)) ^ 2) * (2 * n ^ 2 - 6 * n + 4) / ((n1b - 1) * (n2 - 1)))
varBn <- Cnn * bootB / Cnd
}
p <- pnorm(Bn / sqrt(varBn), lower.tail = FALSE)
}
else {
p <- pnorm(Bn, lower.tail = FALSE)
}
significant <- (p < (alpha / (2 ^ (n - 1) - 1)))
ans <- list(p, significant, varBn)
names(ans) <- c("p.value", "significant", "varBn")
return(ans)
} |
data_transpose <- function(data, verbose = TRUE, ...) {
if (length(unique(sapply(data, class))) > 1) {
if (verbose) {
warning("Your data contains mixed types of data. After transposition, all will be transformed into characters.")
}
}
new <- as.data.frame(t(data))
colnames(new) <- rownames(data)
rownames(new) <- colnames(data)
new
} |
`evaluate_smooth` <- function(object, ...) {
UseMethod("evaluate_smooth")
}
`evaluate_smooth.gam` <- function(object, smooth, n = 100, newdata = NULL,
unconditional = FALSE,
overall_uncertainty = TRUE,
dist = 0.1, ...) {
if (length(smooth) > 1L) {
message("Supplied more than 1 'smooth'; using only the first")
smooth <- smooth[1L]
}
smooth_ids <- which_smooth(object, smooth)
if (identical(length(smooth_ids), 0L)) {
stop("Requested smooth '", smooth, "' not found", call. = FALSE)
}
smooth_labels <- select_smooth(object, smooth)
SMOOTHS <- get_smooths_by_id(object, smooth_ids)
if (inherits(SMOOTHS[[1]], "random.effect")) {
evaluated <- evaluate_re_smooth(SMOOTHS, model = object,
newdata = newdata,
unconditional = unconditional)
} else if (inherits(SMOOTHS[[1]], "fs.interaction")) {
evaluated <- evaluate_fs_smooth(SMOOTHS, n = n, model = object,
newdata = newdata,
unconditional = unconditional)
} else if (smooth_dim(SMOOTHS[[1]]) == 1L) {
evaluated <- evaluate_1d_smooth(SMOOTHS, n = n, model = object,
newdata = newdata,
overall_uncertainty = overall_uncertainty,
unconditional = unconditional)
} else if (smooth_dim(SMOOTHS[[1]]) == 2L) {
evaluated <- evaluate_2d_smooth(SMOOTHS, n = n, model = object,
newdata = newdata,
overall_uncertainty = overall_uncertainty,
unconditional = unconditional,
dist = dist)
} else {
stop("Only univariate and bivariate smooths are currently supported.")
}
evaluated
}
`evaluate_smooth.gamm` <- function(object, ...) {
evaluate_smooth(object[["gam"]], ...)
}
`evaluate_smooth.list` <- function(object, ...) {
if (! is_gamm4(object)) {
stop("`object` does not appear to a `gamm4` model object", call. = FALSE)
}
evaluate_smooth(object[["gam"]], ...)
}
`evaluate_re_smooth` <- function(object, model = NULL, newdata = NULL,
unconditional = FALSE) {
is.by <- vapply(object, FUN = is_by_smooth, FUN.VALUE = logical(1L))
by_var <- unique(vapply(object, FUN = by_variable, FUN.VALUE = character(1)))
if (!is.null(newdata)) {
stop("Not yet implemented: user-supplied data in 're' smooth")
}
smooth_var <- unique(unlist(lapply(object, FUN = smooth_variable)))
smooth_labels <- vapply(object, FUN = smooth_label, FUN.VALUE = character(1))
var_types <- attr(terms(model), "dataClasses")[smooth_var]
levs <- if (all(var_types %in% c("factor", "ordered"))) {
levels(interaction(model[["model"]][smooth_var], drop = FALSE))
} else {
take <- smooth_var[which(var_types %in% c("factor", "ordered"))]
levels(interaction(model[["model"]][take]))
}
is.factor.by <- vapply(object, FUN = is_factor_by_smooth,
FUN.VALUE = logical(1L))
evaluated <- vector("list", length(object))
for (i in seq_along(evaluated)) {
start <- object[[i]][["first.para"]]
end <- object[[i]][["last.para"]]
para_seq <- seq(from = start, to = end, by = 1L)
coefs <- coef(model)[para_seq]
se <- diag(vcov(model, unconditional = unconditional))[para_seq]
evaluated[[i]] <- tibble(smooth = rep(smooth_labels[i], length(coefs)),
..var = levs,
est = coefs,
se = se)
}
evaluated <- do.call("rbind", evaluated)
if (any(is.factor.by)) {
na_by <- by_var == "NA"
evaluated <- add_by_var_info_to_smooth(evaluated,
by_name = by_var,
by_data = model[["model"]][[by_var[!na_by]]],
n = length(levs))
} else {
evaluated <- add_missing_by_info_to_smooth(evaluated)
}
names(evaluated)[3] <- paste(smooth_var, collapse = ", ")
class(evaluated) <- c("evaluated_re_smooth", "evaluated_smooth", class(evaluated))
evaluated
}
`evaluate_1d_smooth` <- function(object, n = NULL, model = NULL, newdata = NULL,
unconditional = FALSE,
overall_uncertainty = TRUE) {
is.by <- vapply(object, FUN = is_by_smooth, FUN.VALUE = logical(1L))
if (length(object) > 1L) {
if (!all(is.by)) {
vars <- vapply(object, smooth_variable, character(1L))
if (length(unique(vars)) > 1L) {
stop(by_smooth_failure(object))
}
}
}
by_var <- unique(vapply(object, FUN = by_variable, FUN.VALUE = character(1)))
smooth_var <- unique(vapply(object, FUN = smooth_variable,
FUN.VALUE = character(1)))
newx <- if (is.null(newdata)) {
setNames(datagen(object[[1]], n = n,
data = model[["model"]])[, "x", drop = FALSE],
smooth_var)
} else if (is.data.frame(newdata)) {
if (!smooth_var %in% names(newdata)) {
stop(paste("Variable", smooth_var, "not found in 'newdata'."))
}
newdata[, smooth_var, drop = FALSE]
} else if (is.numeric(newdata)) {
setNames(data.frame(newdata), smooth_var)
} else {
stop("'newdata', if supplied, must be a numeric vector or a data frame.")
}
is.factor.by <- vapply(object, FUN = is_factor_by_smooth, FUN.VALUE = logical(1L))
is.continuous.by <- vapply(object, FUN = is_continuous_by_smooth, FUN.VALUE = logical(1L))
if (any(is.by)) {
na_by <- by_var == "NA"
if (any(is.factor.by)) {
if (any(na_by)) {
onewx <- cbind(newx, .by_var = NA)
}
levs <- levels(model[["model"]][[by_var[!na_by]]])
newx <- cbind(newx, .by_var = rep(levs, each = n))
if (any(na_by)) {
levs <- c("NA", levs)
newx <- rbind(onewx, newx)
newx[[".by_var"]] <- factor(newx[[".by_var"]], levels = levs[-1L])
} else {
newx[[".by_var"]] <- factor(newx[[".by_var"]], levels = levs)
}
} else {
if (any(na_by)) {
onewx <- cbind(newx, .ba_var = NA)
}
newx <- cbind(newx, .by_var = mean(model[["model"]][[by_var[!na_by]]]))
if (any(na_by)) {
newx <- rbind(onewx, newx)
}
}
names(newx)[NCOL(newx)] <- by_var[!na_by]
}
evaluated <- vector("list", length(object))
for (i in seq_along(evaluated)) {
ind <- seq_len(NROW(newx))
if (any(is.by)) {
if (is.factor.by[[i]]) {
ind <- newx[, by_var[!na_by]] == levs[i]
ind[is.na(ind)] <- FALSE
} else {
is_na <- is.na(newx[, by_var[!na_by]])
if (any(is_na)) {
ind <- is_na
}
}
}
evaluated[[i]] <- spline_values(object[[i]],
newdata = newx[ind, , drop = FALSE],
unconditional = unconditional,
model = model,
overall_uncertainty = overall_uncertainty,
term = smooth_var)
}
evaluated <- do.call("bind_rows", evaluated)
if (any(is.factor.by)) {
evaluated <- add_by_var_info_to_smooth(evaluated,
by_name = by_var,
by_data = model[["model"]][[by_var[!na_by]]],
n = n)
} else {
evaluated <- add_missing_by_info_to_smooth(evaluated)
}
names(evaluated)[3] <- smooth_var
class(evaluated) <- c("evaluated_1d_smooth", "evaluated_smooth", class(evaluated))
evaluated
}
`evaluate_2d_smooth` <- function(object, n = NULL, model = NULL, newdata = NULL,
unconditional = FALSE,
overall_uncertainty = TRUE, dist = 0.1) {
is.by <- vapply(object, FUN = is_by_smooth, FUN.VALUE = logical(1L))
if (length(object) > 1L) {
if (!all(is.by)) {
vars <- vapply(object, smooth_variable, character(2L))
if (length(unique(as.vector(vars))) > 2L) {
stop(by_smooth_failure(object))
}
}
}
by_var <- unique(vapply(object, FUN = by_variable, FUN.VALUE = character(1)))
smooth_var <- unique(vapply(object, FUN = smooth_variable, FUN.VALUE = character(2L))[,1])
newx <- if (is.null(newdata)) {
setNames(datagen(object[[1]], n = n,
data = model[["model"]])[, c("x1", "x2"), drop = FALSE],
smooth_var)
} else if (is.data.frame(newdata)) {
if (!all(smooth_var %in% names(newdata))) {
stop(paste("Variable", smooth_var, "not found in 'newdata'."))
}
newdata[, smooth_var, drop = FALSE]
} else if (is.numeric(newdata)) {
setNames(data.frame(newdata), smooth_var)
} else {
stop("'newdata', if supplied, must be a numeric vector or a data frame.")
}
is.factor.by <- vapply(object, FUN = is_factor_by_smooth, FUN.VALUE = logical(1L))
is.continuous.by <- vapply(object, FUN = is_continuous_by_smooth, FUN.VALUE = logical(1L))
if (any(is.by)) {
na_by <- by_var == "NA"
if (any(is.factor.by)) {
if (any(na_by)) {
onewx <- cbind(newx, .by_var = NA)
}
levs <- levels(model[["model"]][[by_var[!na_by]]])
newx <- cbind(newx, .by_var = rep(levs, each = n*n))
if (any(na_by)) {
levs <- c("NA", levs)
newx <- rbind(onewx, newx)
newx[[".by_var"]] <- factor(newx[[".by_var"]], levels = levs[-1L])
} else {
newx[[".by_var"]] <- factor(newx[[".by_var"]], levels = levs)
}
} else {
if (any(na_by)) {
onewx <- cbind(newx, .ba_var = NA)
}
newx <- cbind(newx, .by_var = mean(model[["model"]][[by_var[!na_by]]]))
if (any(na_by)) {
newx <- rbind(onewx, newx)
}
}
names(newx)[NCOL(newx)] <- by_var[!na_by]
}
evaluated <- vector("list", length(object))
for (i in seq_along(evaluated)) {
ind <- seq_len(NROW(newx))
if (any(is.by)) {
if (is.factor.by[[i]]) {
ind <- newx[, by_var[!na_by]] == levs[i]
ind[is.na(ind)] <- FALSE
} else {
is_na <- is.na(newx[, by_var[!na_by]])
if (any(is_na)) {
ind <- is_na
}
}
}
evaluated[[i]] <- spline_values(object[[i]],
newdata = newx[ind, , drop = FALSE],
unconditional = unconditional,
model = model,
overall_uncertainty = overall_uncertainty,
term = smooth_var)
}
evaluated <- do.call("rbind", evaluated)
if (any(is.factor.by)) {
evaluated <- add_by_var_info_to_smooth(evaluated,
by_name = by_var,
by_data = model[["model"]][[by_var[!na_by]]],
n = n*n)
} else {
evaluated <- add_missing_by_info_to_smooth(evaluated)
}
if (dist > 0) {
ind <- mgcv::exclude.too.far(newx[, smooth_var[1L]],
newx[, smooth_var[2L]],
model[["model"]][, smooth_var[1L]],
model[["model"]][, smooth_var[2L]],
dist = dist)
if (any(ind)) {
evaluated[ind, c("est", "se")] <- NA
}
}
names(evaluated)[3:4] <- smooth_var
class(evaluated) <- c("evaluated_2d_smooth", "evaluated_smooth", class(evaluated))
evaluated
}
`evaluate_fs_smooth` <- function(object, n = NULL, model = NULL, newdata = NULL,
unconditional = FALSE,
overall_uncertainty = TRUE) {
is.by <- vapply(object, FUN = is_by_smooth, FUN.VALUE = logical(1L))
if (length(object) > 1L) {
if (!all(is.by)) {
vars <- vapply(object, smooth_variable, character(1L))
if (length(unique(vars)) > 1L) {
stop(by_smooth_failure(object))
}
}
}
by_var <- unique(vapply(object, FUN = by_variable, FUN.VALUE = character(1)))
smooth_var <- unique(vapply(object, FUN = smooth_variable, FUN.VALUE = character(2L)))
smooth_fac <- unique(vapply(object, FUN = smooth_factor_variable,
FUN.VALUE = character(1L)))
smooth_var <- smooth_var[smooth_var != smooth_fac]
newx <- if (is.null(newdata)) {
datagen(object[[1]], n = n, data = model[["model"]])[, c(smooth_var, smooth_fac),
drop = FALSE]
} else if (is.data.frame(newdata)) {
if (!smooth_var %in% names(newdata)) {
stop(paste("Variable", smooth_var, "not found in 'newdata'."))
}
newdata[, c(smooth_var, smooth_fac), drop = FALSE]
} else {
stop("'newdata', if supplied, must be a data frame.")
}
n <- nrow(newx)
is.factor.by <- vapply(object, FUN = is_factor_by_smooth, FUN.VALUE = logical(1L))
is.continuous.by <- vapply(object, FUN = is_continuous_by_smooth, FUN.VALUE = logical(1L))
if (any(is.by)) {
na_by <- by_var == "NA"
if (any(is.factor.by)) {
if (any(na_by)) {
onewx <- cbind(newx, .by_var = NA)
}
levs <- levels(model[["model"]][[by_var[!na_by]]])
newx <- cbind(newx, .by_var = rep(levs, each = n))
if (any(na_by)) {
levs <- c("NA", levs)
newx <- rbind(onewx, newx)
newx[[".by_var"]] <- factor(newx[[".by_var"]], levels = levs[-1L])
} else {
newx[[".by_var"]] <- factor(newx[[".by_var"]], levels = levs)
}
} else {
if (any(na_by)) {
onewx <- cbind(newx, .ba_var = NA)
}
newx <- cbind(newx, .by_var = mean(model[["model"]][[by_var[!na_by]]]))
if (any(na_by)) {
newx <- rbind(onewx, newx)
}
}
names(newx)[NCOL(newx)] <- by_var[!na_by]
}
evaluated <- vector("list", length(object))
for (i in seq_along(evaluated)) {
ind <- seq_len(NROW(newx))
if (any(is.by)) {
if (is.factor.by[[i]]) {
ind <- newx[, by_var[!na_by]] == levs[i]
ind[is.na(ind)] <- FALSE
} else {
is_na <- is.na(newx[, by_var[!na_by]])
if (any(is_na)) {
ind <- is_na
}
}
}
evaluated[[i]] <- spline_values(object[[i]],
newdata = newx[ind, , drop = FALSE],
unconditional = unconditional,
model = model,
overall_uncertainty = overall_uncertainty,
term = smooth_var)
}
evaluated <- do.call("rbind", evaluated)
if (any(is.factor.by)) {
evaluated <- add_by_var_info_to_smooth(evaluated,
by_name = by_var,
by_data = model[["model"]][[by_var[!na_by]]],
n = n)
} else {
evaluated <- add_missing_by_info_to_smooth(evaluated)
}
names(evaluated)[3L] <- smooth_var
names(evaluated)[4L] <- smooth_fac
class(evaluated) <- c("evaluated_fs_smooth", "evaluated_smooth", class(evaluated))
evaluated
}
`evaluate_parametric_term` <- function(object, ...) {
UseMethod("evaluate_parametric_term")
}
`evaluate_parametric_term.gam` <- function(object, term, unconditional = FALSE,
...) {
tt <- object$pterms
tt <- delete.response(tt)
vars <- parametric_terms(object)
mgcv_names <- names(vars)
if (length(term) > 1L) {
term <- term[1L]
warning(sprintf("More than one `term` requested; using the first <%s>",
term))
}
if (isFALSE(term %in% vars)) {
stop(sprintf("Term is not in the parametric part of model: <%s>",
term))
}
mf <- model.frame(object)
is_fac <- is_factor_term(tt, term)
ind <- match(term, vars)
if (is_fac) {
ord <- attr(tt, "order")[match(term, attr(tt, "term.labels"))]
if (ord > 1) {
stop("Interaction terms are not currently supported.")
}
newd <- unique(mf[, term, drop = FALSE])
other_vars <- setdiff(names(mf), term)
other_data <- as_tibble(lapply(mf[other_vars], value_closest_to_median))
pred_data <- exec(expand_grid, !!!list(newd, other_data))
evaluated <- as.data.frame(predict(object, newdata = pred_data,
type = 'terms',
terms = term, se = TRUE,
unconditional = unconditional,
newdata.guaranteed = FALSE))
evaluated <- setNames(evaluated, c("partial", "se"))
evaluated <- as_tibble(evaluated)
nr <- NROW(evaluated)
newd <- setNames(newd, "value")
evaluated <- bind_cols(term = rep(term, nr),
type = rep("factor", nr),
newd, evaluated)
} else {
evaluated <- as.data.frame(predict(object, newdata = mf, type = 'terms',
terms = mgcv_names[ind], se = TRUE,
unconditional = unconditional))
evaluated <- setNames(evaluated, c("partial", "se"))
evaluated <- as_tibble(evaluated)
nr <- NROW(evaluated)
evaluated <- bind_cols(term = rep(term, nr),
type = rep("numeric", nr),
value = mf[[term]],
evaluated)
}
class(evaluated) <- c("evaluated_parametric_term", class(evaluated))
evaluated
}
`spline_values` <- function(smooth, newdata, model, unconditional,
overall_uncertainty = TRUE, term) {
X <- PredictMat(smooth, newdata)
start <- smooth[["first.para"]]
end <- smooth[["last.para"]]
para.seq <- start:end
coefs <- coef(model)[para.seq]
fit <- drop(X %*% coefs)
label <- smooth_label(smooth)
V <- get_vcov(model, unconditional = unconditional)
column_means <- model[["cmX"]]
lcms <- length(column_means)
nc <- ncol(V)
meanL1 <- smooth[["meanL1"]]
if (isTRUE(overall_uncertainty) && attr(smooth, "nCons") > 0L) {
if (lcms < nc) {
column_means <- c(column_means, rep(0, nc - lcms))
}
Xcm <- matrix(column_means, nrow = nrow(X), ncol = nc, byrow = TRUE)
if (!is.null(meanL1)) {
Xcm <- Xcm / meanL1
}
Xcm[, para.seq] <- X
rs <- rowSums((Xcm %*% V) * Xcm)
} else {
rs <- rowSums((X %*% V[para.seq, para.seq]) * X)
}
se.fit <- sqrt(pmax(0, rs))
d <- smooth_dim(smooth)
out <- if (d == 1L) {
if (is_fs_smooth(smooth)) {
tibble(smooth = rep(label, nrow(X)),
x = newdata[, 1L], f = newdata[, 2L],
est = fit, se = se.fit)
} else {
tibble(smooth = rep(label, nrow(X)),
x = newdata[, 1L],
est = fit, se = se.fit)
}
} else {
tibble(smooth = rep(label, nrow(X)),
x1 = newdata[, 1L], x2 = newdata[, 2L],
est = fit, se = se.fit)
}
out
} |
context("download_smap")
test_that("invalid output directories cause errors", {
skip_on_cran()
files <- find_smap(id = "SPL3SMP", dates = "2015-03-31", version = 5)
expect_error(download_smap(files[1, ], dir = 1234))
})
test_that("non-existent directories are created", {
skip_on_cran()
files <- find_smap(id = "SPL3SMP", dates = "2015-03-31", version = 5)
dir_name <- "silly_nonexistent_directory"
downloads <- download_smap(files, directory = dir_name)
expect_true(dir.exists(dir_name))
unlink(dir_name, recursive = TRUE)
})
test_that("valid user-specified directories contain downloads", {
skip_on_cran()
available_data <- find_smap(id = "SPL3SMP",
date = "2015-10-01",
version = 5)
user_specified_path <- file.path('data', 'SMAP')
downloads <- download_smap(available_data,
directory = user_specified_path)
expect_true(
file.exists(
file.path(user_specified_path,
"SMAP_L3_SM_P_20151001_R16010_001.h5")
)
)
expect_true(
file.exists(
file.path(user_specified_path,
"SMAP_L3_SM_P_20151001_R16010_001.h5.iso.xml")
)
)
expect_true(
file.exists(
file.path(user_specified_path,
"SMAP_L3_SM_P_20151001_R16010_001.qa")
)
)
unlink('data', recursive = TRUE, force = TRUE)
})
test_that("the downloaded data is of the data frame class", {
skip_on_cran()
files <- find_smap(id = "SPL3SMP", dates = "2015-03-31", version = 5)
downloads <- download_smap(files[1, ])
expect_that(downloads, is_a("data.frame"))
})
test_that("Two SPL4CMDL data files are downloaded (h5 and xml)", {
skip_on_cran()
files <- find_smap(id = "SPL4CMDL", dates = "2015-05-01", version = 4)
downloads <- download_smap(files[1, ])
file_prefix <- downloads$name
downloaded_files <- list.files(downloads$local_dir)
relevant_files <- grepl(file_prefix, downloaded_files)
number_of_downloaded_files <- sum(relevant_files)
expect_equal(2, number_of_downloaded_files)
relevant_filenames <- downloaded_files[relevant_files]
extensions <- gsub(".*\\.", "", relevant_filenames)
expect_equal(extensions, c('h5', 'xml'))
})
test_that("setting overwrite = FALSE prevents data from being overwritten", {
skip_on_cran()
get_last_modified <- function(downloads) {
path <- file.path(downloads$local_dir, paste0(downloads$name, '.h5'))
time <- file.info(path)$mtime
as.numeric(time)
}
files <- find_smap(id = "SPL3SMP", date = "2015-03-31", version = 5)
downloads <- download_smap(files)
modified1 <- get_last_modified(downloads)
Sys.sleep(1)
downloads <- download_smap(files, overwrite = FALSE)
modified2 <- get_last_modified(downloads)
expect_equal(modified1, modified2)
})
test_that("setting overwrite = TRUE ensures data overwrite", {
skip_on_cran()
get_last_modified <- function(downloads) {
path <- file.path(downloads$local_dir, paste0(downloads$name, '.h5'))
time <- file.info(path)$mtime
as.numeric(time)
}
files <- find_smap(id = "SPL3SMP", date = "2015-03-31", version = 5)
downloads <- download_smap(files, overwrite = TRUE)
modified1 <- get_last_modified(downloads)
Sys.sleep(1)
downloads <- download_smap(files, overwrite = TRUE)
modified2 <- get_last_modified(downloads)
expect_gt(modified2[1], modified1[1])
})
test_that('input data.frames with NA values raise errors', {
skip_on_cran()
expect_warning(df_w_na <- find_smap(id = "SPL2SMP_E",
dates = '2015-05-13',
version = 2))
expect_error(download_smap(df_w_na))
})
test_that('verbose = TRUE prints output', {
skip_on_cran()
files <- find_smap(id = "SPL3SMP", dates = "2015-03-31", version = 5)
downloads <- expect_message(download_smap(files[1, ], verbose = TRUE))
})
test_that('verbose = FALSE suppresses output', {
skip_on_cran()
files <- find_smap(id = "SPL3SMP", dates = "2015-03-31", version = 5)
downloads <- expect_silent(download_smap(files[1, ], verbose = FALSE))
}) |
lncPath2Table <- function(Result){
gs.name <- vector();
GSSize <- vector();
Obs.ES <- vector();
Obs.ES.norm <- vector();
P_Val <- vector();
FDR <- vector();
for( i in 1:length(Result)){
gs.name <- c(gs.name, Result[[i]]$gs.name);
GSSize <- c(GSSize, Result[[i]]$GSSize);
Obs.ES <- c(Obs.ES, Result[[i]]$Obs.ES);
Obs.ES.norm <- c(Obs.ES.norm, Result[[i]]$Obs.ES.norm);
P_Val <- c(P_Val, Result[[i]]$P_Val);
FDR <- c(FDR, Result[[i]]$FDR);
}
Table <- as.data.frame(cbind(gs.name, GSSize, Obs.ES, Obs.ES.norm, P_Val, FDR));
names(Table) <- c("Gene Set Name", "Gene Set Size", "Enrichment Scores", "Normalized Enrichment Scores", "P Value", "False Discovery Rate");
Table <- Table[order(Table[["False Discovery Rate"]], decreasing = FALSE),];
return(Table);
}
geneSetDetail <- function(Result, Name){
GSInfo <- Result[[Name]];
kk <- 1
N <- length(GSInfo$geneSymbols);
gene.number <- vector(length = GSInfo$GSSize, mode = "character")
gene.names <- vector(length = GSInfo$GSSize, mode = "character")
gene.list.loc <- vector(length = GSInfo$GSSize, mode = "numeric")
core.enrichment <- vector(length = GSInfo$GSSize, mode = "character")
gene.s2n <- vector(length = GSInfo$GSSize, mode = "numeric")
gene.RES <- vector(length = GSInfo$GSSize, mode = "numeric")
if (GSInfo$Obs.ES >= 0) {
set.k <- seq(1, N, 1)
} else {
set.k <- seq(N, 1, -1)
}
for (k in set.k) {
if (GSInfo$Obs.indicator[k] == 1) {
gene.number[kk] <- kk
gene.names[kk] <- GSInfo$geneSymbols[k];
gene.list.loc[kk] <- k
gene.s2n[kk] <- signif(GSInfo$Obs.s2n[k], digits = 3)
gene.RES[kk] <- signif(GSInfo$Obs.RES[k], digits = 3)
if (GSInfo$Obs.ES >= 0) {
core.enrichment[kk] <- ifelse(gene.list.loc[kk] <= GSInfo$Obs.arg.ES, "YES", "NO")
} else {
core.enrichment[kk] <- ifelse(gene.list.loc[kk] > GSInfo$Obs.arg.ES, "YES", "NO")
}
kk <- kk + 1
}
}
gene.report <- data.frame(cbind(gene.number, gene.names, gene.list.loc, gene.s2n, gene.RES, core.enrichment))
names(gene.report) <- c("
return(gene.report);
}
drawAHeatMap <- function(Result, Name, PCExpr, Labels){
GSInfo <- Result[[Name]];
GSP <- geneSetDetail(Result, Name);
Symbols <- GSP[["GENE"]];
Expr <- PCExpr[match(Symbols, row.names(PCExpr))[!is.na(match(Symbols, row.names(PCExpr)))],];
lncPath.HeatMapPlot(as.matrix(Expr), col.labels = Labels, col.classes = c("N", "T"), row.names = row.names(Expr), col.names = names(Expr), main = "HeatMap for genes in gene set");
}
printSignifResult <- function(Result, Threshold = 0.01, Path = ".", HeatPlot = FALSE, PCExpr = "", Labels = "", Top = 0){
if(Top >0){
Table <- lncPath2Table(Result);
for(i in 1:Top){
GSP <- geneSetDetail(Result, Table[["Gene Set Name"]][i]);
write.csv(GSP, file = paste(Path, "/", gsub(" ", "_", Table[["Gene Set Name"]][i]), ".csv", sep = ""), row.names = FALSE);
pdf(file = paste(Path, "/", gsub(" ", "_", Table[["Gene Set Name"]][i]), ".pdf", sep = ""));
plotRunningES(Result, Table[["Gene Set Name"]][i]);
dev.off();
if(HeatPlot == TRUE){
pdf(file = paste(Path, "/", gsub(" ", "_", Table[["Gene Set Name"]][i]), "HeatMap.pdf", sep = ""));
drawAHeatMap(Result, Table[["Gene Set Name"]][i], PCExpr, Labels);
dev.off();
}
}
}else{
for(i in 1:length(Result)){
if(Result[[i]]$FDR <= Threshold){
GSP <- geneSetDetail(Result, Result[[i]]$gs.name);
write.csv(GSP, file = paste(Path, "/", gsub(" ", "_", Result[[i]]$gs.name), ".csv", sep = ""), row.names = FALSE);
pdf(file = paste(Path, "/", gsub(" ", "_", Result[[i]]$gs.name), ".pdf", sep = ""));
plotRunningES(Result, Result[[i]]$gs.name);
dev.off();
if(HeatPlot == TRUE){
pdf(file = paste(Path, "/", gsub(" ", "_", Result[[i]]$gs.name), "HeatMap.pdf", sep = ""));
drawAHeatMap(Result, Result[[i]]$gs.name, PCExpr, Labels);
dev.off();
}
}
}
}
}
plotRunningES<-function(Result, Name){
GSInfo <- Result[[Name]];
N <- length(GSInfo$geneSymbols);
WalkScore <- as.data.frame(cbind(GSInfo$geneSymbols,GSInfo$Obs.s2n));
gs.name <- GSInfo$gs.name;
Obs.ES <- GSInfo$Obs.ES;
Obs.RES <- GSInfo$Obs.RES;
Obs.indicator <- GSInfo$Obs.indicator;
Obs.arg.ES <- GSInfo$Obs.arg.ES
obs.s2n <- as.numeric(WalkScore[[2]]);
obs.s2n <- sort(obs.s2n, decreasing=T);
ind <- 1:N;
min.RES <- min(Obs.RES)
max.RES <- max(Obs.RES)
if (max.RES < 0.3) max.RES <- 0.3
if (min.RES > -0.3) min.RES <- -0.3
delta <- (max.RES - min.RES)*0.50
min.plot <- min.RES - 2*delta
max.plot <- max.RES;
max.corr <- max(obs.s2n);
min.corr <- min(obs.s2n);
Obs.correl.vector.norm <- (obs.s2n - min.corr)/(max.corr - min.corr)*1.25*delta + min.plot
zero.corr.line <- (- min.corr/(max.corr - min.corr))*1.25*delta + min.plot
col <- ifelse(Obs.ES > 0, 2, 4)
sub.string <- paste("Number of genes: ", N, " (in list), ", gs.name, " (in gene set)", sep = "", collapse="");
main.string <- gs.name;
plot(ind, Obs.RES, main = main.string, sub = sub.string, xlab = "Gene List Index", ylab = "Running Enrichment Score (RES)", xlim=c(1, N), ylim=c(min.plot, max.plot), type = "l", lwd = 2, cex = 1, col = col);
for (k in seq(1, N, 20)) {
lines(c(k, k), c(zero.corr.line, Obs.correl.vector.norm[k]), lwd = 1, cex = 1, col = colors()[12])
}
lines(c(1, N), c(0, 0), lwd = 1, lty = 2, cex = 1, col = 1)
lines(c(Obs.arg.ES, Obs.arg.ES), c(min.plot, max.plot), lwd = 1, lty = 3, cex = 1, col = col)
for (k in 1:N) {
if (Obs.indicator[k] == 1) {
lines(c(k, k), c(min.plot + 1.25*delta, min.plot + 1.75*delta), lwd = 1, lty = 1, cex = 1, col = 1)
}
}
lines(ind, Obs.correl.vector.norm, type = "l", lwd = 1, cex = 1, col = 1)
lines(c(1, N), c(zero.corr.line, zero.corr.line), lwd = 1, lty = 1, cex = 1, col = 1)
temp <- order(abs(obs.s2n), decreasing=T);
arg.correl <- temp[N]
adjx <- ifelse(Obs.ES > 0, 0, 1)
leg.txt <- paste("Peak at ", Obs.arg.ES, sep="", collapse="")
text(x=Obs.arg.ES, y=min.plot + 1.8*delta, adj = c(adjx, 0), labels=leg.txt, cex = 1.0)
} |
bootstrapLRT <- function (h0 = NULL, h1 = NULL, R = 1000L,
type = "bollen.stine", verbose = FALSE,
return.LRT = FALSE,
double.bootstrap = "no",
double.bootstrap.R = 500L,
double.bootstrap.alpha = 0.05,
warn = -1L,
parallel = c("no", "multicore", "snow"),
ncpus = 1L,
cl = NULL,
iseed = NULL)
{
type <- tolower(type)
stopifnot(inherits(h0, "lavaan"),
inherits(h1, "lavaan"),
type %in% c("bollen.stine", "parametric", "yuan", "nonparametric",
"ordinary"),
double.bootstrap %in% c("no", "FDB", "standard"))
if(type == "nonparametric") type <- "ordinary"
if(h0@[email protected]) {
stop("lavaan ERROR: this function is not (yet) available if conditional.x = TRUE")
}
old_options <- options(); options(warn = warn)
LRT <- rep(as.numeric(NA), R)
if((h1@optim$fx - h0@optim$fx) > sqrt(.Machine$double.eps)) {
cat(" ... h0@optim$fx = ", h0@optim$fx, "h1@optim$fx = ", h1@optim$fx,
"h0 should not be better!\n")
options(old_options)
return(NULL)
}
LRT.original <- abs(anova(h0, h1)$`Chisq diff`[2L])
if(double.bootstrap == "FDB") {
LRT.2 <- numeric(R)
} else if(double.bootstrap == "standard") {
plugin.pvalues <- numeric(R)
}
if(missing(parallel)) parallel <- "no"
parallel <- match.arg(parallel)
have_mc <- have_snow <- FALSE
if(parallel != "no" && ncpus > 1L) {
if(parallel == "multicore")
have_mc <- .Platform$OS.type != "windows"
else if(parallel == "snow")
have_snow <- TRUE
if(!have_mc && !have_snow)
ncpus <- 1L
loadNamespace("parallel")
}
data <- h0@Data
if(type == "bollen.stine" || type == "parametric" || type == "yuan") {
Sigma.hat <- computeSigmaHat(lavmodel = h0@Model)
Mu.hat <- computeMuHat(lavmodel = h0@Model)
}
if(type == "bollen.stine" || type == "yuan") {
if(h0@Options$missing != "listwise")
stop("lavaan ERROR: bollen.stine/yuan bootstrap not available for missing data")
dataX <- vector("list", length=data@ngroups)
} else {
dataX <- data@X
}
lavdata <- h0@Data
lavoptions <- h0@Options
if(type == "bollen.stine") {
for(g in 1:h0@Data@ngroups) {
sigma.sqrt <- lav_matrix_symmetric_sqrt( Sigma.hat[[g]])
S.inv.sqrt <- lav_matrix_symmetric_sqrt(h0@SampleStats@icov[[g]])
X <- scale(data@X[[g]], center = TRUE, scale = FALSE)
X <- X %*% S.inv.sqrt %*% sigma.sqrt
if (h0@Model@meanstructure)
X <- scale(X, center = (-1 * Mu.hat[[g]]), scale = FALSE)
dataX[[g]] <- X
}
}
if(type == "yuan") {
g.a <- function(a, Sigmahat, Sigmahat.inv, S, tau.hat, p){
S.a <- a*S + (1-a)*Sigmahat
tmp.term <- S.a %*% Sigmahat.inv
res1 <- (sum(diag(tmp.term)) - log(det(tmp.term)) - p) - tau.hat
res <- res1*res1
attr(res, "gradient") <- sum(diag((S - Sigmahat) %*%
(Sigmahat.inv - chol2inv(chol(S.a)))))
res
}
for(g in 1:h0@Data@ngroups) {
S <- h0@SampleStats@cov[[g]]
ghat <- h0@test[[1]]$stat.group[[g]]
df <- h0@test[[1]]$df
Sigmahat <- Sigma.hat[[g]]
Sigmahat.inv <- inv.chol(Sigmahat)
nmv <- nrow(Sigmahat)
n <- data@nobs[[g]]
tau.hat <- (ghat - df)/(n-1)
if (tau.hat >= 0){
a <- optimize(g.a, c(0,1), Sigmahat, Sigmahat.inv,
S, tau.hat, nmv)$minimum
S.a <- a*S + (1-a)*Sigmahat
} else {
S.a <- Sigmahat
}
S.a.sqrt <- lav_matrix_symmetric_sqrt(S.a)
S.inv.sqrt <- lav_matrix_symmetric_sqrt(h0@SampleStats@icov[[g]])
X <- data@X[[g]]
X <- X %*% S.inv.sqrt %*% S.a.sqrt
dataX[[g]] <- X
}
}
fn <- function(b) {
if (type == "bollen.stine" || type == "ordinary" || type == "yuan") {
BOOT.idx <- vector("list", length = lavdata@ngroups)
for(g in 1:lavdata@ngroups) {
stopifnot(lavdata@nobs[[g]] > 1L)
boot.idx <- sample(x=lavdata@nobs[[g]],
size=lavdata@nobs[[g]], replace=TRUE)
BOOT.idx[[g]] <- boot.idx
dataX[[g]] <- dataX[[g]][boot.idx,,drop=FALSE]
}
newData <- lav_data_update(lavdata = lavdata, newX = dataX,
BOOT.idx = BOOT.idx,
lavoptions = lavoptions)
} else {
for(g in 1:lavdata@ngroups) {
dataX[[g]] <- MASS::mvrnorm(n = lavdata@nobs[[g]],
Sigma = Sigma.hat[[g]],
mu = Mu.hat[[g]])
}
newData <- lav_data_update(lavdata = lavdata, newX = dataX,
lavoptions = lavoptions)
}
if (verbose) cat(" ... bootstrap draw number: ", b, "\n")
bootSampleStats <- try(lav_samplestats_from_data(
lavdata = newData,
lavoptions = lavoptions), silent = TRUE)
if (inherits(bootSampleStats, "try-error")) {
if (verbose) cat(" FAILED: creating h0@SampleStats statistics\n")
options(old_options)
return(NULL)
}
if (verbose) cat(" ... ... model h0: ")
h0@Options$verbose <- FALSE
h0@Options$se <- "none"
h0@Options$test <- "standard"
h0@Options$baseline <- FALSE
h0@Options$h1 <- FALSE
fit.h0 <- lavaan(slotOptions = h0@Options,
slotParTable = h0@ParTable,
slotSampleStats = bootSampleStats,
slotData = data)
if (!fit.h0@optim$converged) {
if (verbose) cat(" FAILED: no convergence\n")
options(old_options)
return(NULL)
}
if (verbose)
cat(" ok -- niter = ", fit.h0@optim$iterations,
" fx = ", fit.h0@optim$fx, "\n")
if (verbose) cat(" ... ... model h1: ")
h1@Options$verbose <- FALSE
h1@Options$se <- "none"
h1@Options$test <- "standard"
h1@Options$baseline <- FALSE
h1@Options$h1 <- FALSE
fit.h1 <- lavaan(slotOptions = h1@Options,
slotParTable = h1@ParTable,
slotSampleStats = bootSampleStats,
slotData = data)
if (!fit.h1@optim$converged) {
if (verbose)
cat(" FAILED: no convergence -- niter = ", fit.h1@optim$iterations,
" fx = ", fit.h1@optim$fx,"\n")
options(old_options)
return(NULL)
}
if (verbose)
cat(" ok -- niter = ", fit.h1@optim$iterations,
" fx = ", fit.h1@optim$fx, "\n")
if((fit.h1@optim$fx - fit.h0@optim$fx) > sqrt(.Machine$double.eps)) {
if (verbose)
cat(" ... ... LRT = <NA> h0 > h1, delta = ", fit.h1@optim$fx - fit.h0@optim$fx, "\n")
options(old_options)
return(NULL)
} else {
lrt.boot <- abs(anova(fit.h1, fit.h0)$`Chisq diff`[2L])
if (verbose)
cat(" ... ... LRT = ", lrt.boot, "\n")
}
if (double.bootstrap == "standard") {
if (verbose) cat(" ... ... calibrating p.value - ")
plugin.pvalue <- bootstrapLRT(h0 = fit.h0, h1 = fit.h1,
R = double.bootstrap.R,
type = type,
verbose = FALSE,
return.LRT = FALSE,
warn = warn,
parallel = parallel,
ncpus = ncpus, cl = cl,
double.bootstrap = "no")
if (verbose) cat(sprintf("%5.3f", plugin.pvalue), "\n")
attr(lrt.boot, "plugin.pvalue") <- plugin.pvalue
} else if (double.bootstrap == "FDB") {
plugin.pvalue <- bootstrapLRT(h0 = fit.h0, h1 = fit.h1,
R = 1L,
type = type,
verbose = FALSE,
warn = warn,
return.LRT = TRUE,
parallel = parallel,
ncpus = ncpus, cl = cl,
double.bootstrap = "no")
LRT.2 <- attr(plugin.pvalue, "LRT")
if (verbose) cat(" ... ... LRT2 = ", LRT.2, "\n")
attr(lrt.boot, "LRT.2") <- LRT.2
}
lrt.boot
}
RR <- sum(R)
res <- if (ncpus > 1L && (have_mc || have_snow)) {
if (have_mc) {
parallel::mclapply(seq_len(RR), fn, mc.cores = ncpus)
}
else if (have_snow) {
if (is.null(cl)) {
cl <- parallel::makePSOCKcluster(rep("localhost", ncpus))
if (RNGkind()[1L] == "L'Ecuyer-CMRG")
parallel::clusterSetRNGStream(cl, iseed = iseed)
res <- parallel::parLapply(cl, seq_len(RR), fn)
parallel::stopCluster(cl)
res
}
else parallel::parLapply(cl, seq_len(RR), fn)
}
} else lapply(seq_len(RR), fn)
error.idx <- integer(0)
for (b in seq_len(RR)) {
if (!is.null(res[[b]])) {
LRT[b] <- res[[b]]
if (double.bootstrap == "standard") {
plugin.pvalues[b] <- attr(res[[b]], "plugin.pvalue")
} else if (double.bootstrap == "FDB") {
LRT.2[b] <- attr(res[[b]], "LRT.2")
}
} else {
error.idx <- c(error.idx, b)
}
}
if (length(error.idx) > 0L) {
warning("lavaan WARNING: only ", (R - length(error.idx)),
" bootstrap draws were successful")
LRT <- LRT[-error.idx]
if(length(LRT) == 0) LRT <- as.numeric(NA)
if (double.bootstrap == "standard") {
plugin.pvalues <- plugin.pvalues[-error.idx]
attr(LRT, "error.idx") <- error.idx
}
if (double.bootstrap == "FDB") {
LRT.2 <- LRT.2[-error.idx]
attr(LRT.2, "error.idx") <- error.idx
}
} else {
if (verbose)
cat("Number of successful bootstrap draws:", (R -
length(error.idx)), "\n")
}
pvalue <- sum(LRT > LRT.original) / length(LRT)
if (return.LRT) {
attr(pvalue, "LRT.original") <- LRT.original
attr(pvalue, "LRT") <- LRT
}
if (double.bootstrap == "FDB") {
Q <- (1 - pvalue)
lrt.q <- quantile(LRT.2, Q, na.rm = TRUE)
adj.pvalue <- sum(LRT > lrt.q) / length(LRT)
attr(pvalue, "lrt.q") <- lrt.q
attr(pvalue, "adj.pvalue") <- adj.pvalue
if (return.LRT) {
attr(pvalue, "LRT.original") <- LRT.original
attr(pvalue, "LRT") <- LRT
attr(pvalue, "LRT2") <- LRT.2
}
} else if (double.bootstrap == "standard") {
adj.alpha <- quantile(plugin.pvalues, double.bootstrap.alpha,
na.rm=TRUE)
attr(pvalue, "adj.alpha") <- adj.alpha
adj.pvalue <- sum(plugin.pvalues < pvalue) / length(plugin.pvalues)
attr(pvalue, "plugin.pvalues") <- plugin.pvalues
attr(pvalue, "adj.pvalue") <- adj.pvalue
}
options(old_options)
pvalue
} |
rstudent.loop2r <- function(model,...) {
g <- model
n <- length(g$x)
wr1<- g$x-g$pred.x
wr2<- g$y-g$pred.y
var.x <- crossprod(wr1-mean(wr1))/(n-3)
var.y <- crossprod(wr2-mean(wr2))/(n-3)
Xmat <- cbind(rep(1,n),sin(g$period.time),cos(g$period.time))
hX <- Xmat%*%solve(crossprod(Xmat))%*%t(Xmat)
Ind <- (g$period.time > 0) & (g$period.time < pi)
if (model$classical==FALSE)
Ymat <- cbind(rep(1,n),sin(g$period.time)^g$values["m"],cos(g$period.time)^g$values["n"],Ind*sin(g$period.time)^g$values["m"])
else
direc <- sign(cos(g$period.time))
Ymat <- cbind(rep(1,n),sin(g$period.time)^g$values["m"],direc*abs(cos(g$period.time))^g$values["n"],Ind*sin(g$period.time)^g$values["m"])
hY <- Ymat%*%solve(crossprod(Ymat))%*%t(Ymat)
r.Ta <- wr1/sqrt(1-diag(hX))
r.Tb <- wr2/sqrt(1-diag(hY))
wr1 <- r.Ta-mean(r.Ta)
wr2 <- r.Tb-mean(r.Tb)
data.frame("input"=wr1,"output"=wr2)
} |
fssum <- function(fslist, weight=NULL){
dtype = check_list_summaries("fssum", fslist)
if ((length(weight)<1)&&(is.null(weight))){
nn = length(fslist)
weight = rep(1/nn, nn)
}
if (length(weight)!=length(fslist)){
stop("* fssum : length of 'fslist' should match to that of 'weight'.")
}
output = switch(dtype,
"landscape" = fssum_land(fslist, weight),
"silhouette" = fssum_sils(fslist, weight))
return(output)
}
fssum_land <- function(dlist, weight){
mainout = adjust_list_landscapes(dlist, as.list=FALSE)
maincom = compute_slicewsum(mainout$array3d, weight)
output = list()
output$lambda = maincom
output$tseq = as.vector(mainout$tseq)
output$dimension = dlist[[1]]$dimension
class(output) = "landscape"
return(output)
}
fssum_sils <- function(slist, weight){
mainout = adjust_list_silhouette(slist, as.list=FALSE)
dat.tseq = mainout$tseq
dat.func = mainout$array
vec.output = rep(0,length(dat.tseq))
for (i in 1:length(weight)){
vec.output = vec.output + (weight[i])*as.vector(dat.func[,i])
}
output = list()
output$lambda = vec.output
output$tseq = dat.tseq
output$dimension = slist[[1]]$dimension
class(output) = "silhouette"
return(output)
} |
reg.aic <- function(fit, w){
return(2 * (fit$rank + 1) - 2* (0.5 * (sum(log(w)) - length(w) * (log(2 * pi) + 1 - log(length(w)) + log(sum(w * fit$residuals^2))))))
} |
"getDiffTheta" <- function(th, mod) {
modellist <- mod@modellist
modeldiff <- mod@modeldiffs
parorder <- list()
if(length(modeldiff$change) != 0) {
thA <- getDiffThetaChange(th, mod)
th <- thA$th
mod@parorderchange <- thA$parorder
}
if(length(modeldiff$free)!=0 || length(modeldiff$add) !=0)
for(diff in append(mod@modeldiffs$free, mod@modeldiffs$add)){
j <- diff$dataset[1]
fixed <- modellist[[j]]@fvecind
prel <- modellist[[j]]@pvecind
model <- modellist[[diff$dataset[1]]]
removepar <- sort(append(fixed[[diff$what]],prel[[diff$what]]))
if(length(diff$ind) == 2) {
whichfree <- diff$ind[2]
if(diff$ind[1] > 1) {
slW<-slot(model, diff$what)
whichfree <- whichfree + sum(unlist(lapply(slW, length))[1:(diff$ind[1]-1)])
}
partmp <- slot(model, diff$what)[[diff$ind[1]]][diff$ind[2]]
}
else {
partmp <- slot(model,
diff$what)[diff$ind]
whichfree <- diff$ind
}
if(diff$what %in% model@positivepar)
partmp <- log(partmp)
else {
if(length(model@clinde$po$name) > 0)
for(i in 1:length(model@clinde[[diff$what]]))
parapp <- log(parapp[i])
if(length(model@chinde[[diff$what]]) > 0)
for(i in 1:length(model@chinde[[diff$what]]))
parapp <- log(parapp[i])
}
removepar <- which(whichfree %in% removepar)
if(length(removepar)>0)
partmp <- partmp[-removepar]
if(length(partmp) > 0)
ind <- (length(th) + 1):(length(th) + length(partmp))
else ind <- vector()
parorder[[length(parorder)+1]] <- list(name=diff$what,
ind=ind, rm=removepar, dataset=diff$dataset, indm=diff$ind)
th <- append(th, partmp)
}
if(length(modeldiff$rel)!=0)
for(diff in modeldiff$rel) {
removepar <- if(diff$fix) 1:length(diff$start) else vector()
if(length(removepar)>0)
partmp <- diff$start[-removepar]
ind <- if(length(partmp) > 0) (length(th) +
1):(length(th) + length(partmp)) else vector()
parorder[[length(parorder)+1]] <- list(name=diff$what1,
ind=ind, rm=removepar, dataset=diff$dataset1, indm=diff$ind1)
th <- append(th, partmp)
}
if(length(modeldiff$dscal) != 0) {
for(i in 1:length(modeldiff$dscal)) {
j <- modeldiff$dscal[[i]]$to
if(length(modellist[[j]]@drel) != 0){
fixed <- modellist[[j]]@fvecind
prel <- modellist[[j]]@pvecind
removepar <- sort(append(fixed[["drel"]], prel[["drel"]]))
parapp <- if(length(removepar)!=0)
unlist(slot(modellist[[j]],
"drel"))[-removepar]
else unlist(slot(modellist[[j]],
"drel"))
if(length(parapp) != 0)
ind <- (length(th) + 1):(length(th) + length(parapp))
else ind <- vector()
parorder[[length(parorder)+1]] <- list(name="drel",
ind=ind, rm=removepar, dataset=j,
indm=(1:length(modellist[[j]]@drel)))
th <- append(th, parapp)
}
}
}
mod@parorderdiff <- parorder
list(theta = th, mod = mod)
} |
library(checkargs)
context("isNumberOrInfScalar")
test_that("isNumberOrInfScalar works for all arguments", {
expect_identical(isNumberOrInfScalar(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_identical(isNumberOrInfScalar(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE)
expect_error(isNumberOrInfScalar(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isNumberOrInfScalar(0, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isNumberOrInfScalar(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_identical(isNumberOrInfScalar(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_identical(isNumberOrInfScalar(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE)
expect_error(isNumberOrInfScalar("", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar("X", stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
expect_error(isNumberOrInfScalar(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL))
}) |
NULL
.iotdataplane$delete_thing_shadow_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(thingName = structure(logical(0), tags = list(location = "uri", locationName = "thingName", type = "string")), shadowName = structure(logical(0), tags = list(location = "querystring", locationName = "name", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotdataplane$delete_thing_shadow_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(payload = structure(logical(0), tags = list(type = "blob"))), tags = list(type = "structure", payload = "payload"))
return(populate(args, shape))
}
.iotdataplane$get_thing_shadow_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(thingName = structure(logical(0), tags = list(location = "uri", locationName = "thingName", type = "string")), shadowName = structure(logical(0), tags = list(location = "querystring", locationName = "name", type = "string"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotdataplane$get_thing_shadow_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(payload = structure(logical(0), tags = list(type = "blob"))), tags = list(type = "structure", payload = "payload"))
return(populate(args, shape))
}
.iotdataplane$list_named_shadows_for_thing_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(thingName = structure(logical(0), tags = list(location = "uri", locationName = "thingName", type = "string")), nextToken = structure(logical(0), tags = list(location = "querystring", locationName = "nextToken", type = "string")), pageSize = structure(logical(0), tags = list(location = "querystring", locationName = "pageSize", type = "integer"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotdataplane$list_named_shadows_for_thing_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(results = structure(list(structure(logical(0), tags = list(type = "string"))), tags = list(type = "list")), nextToken = structure(logical(0), tags = list(type = "string")), timestamp = structure(logical(0), tags = list(type = "long"))), tags = list(type = "structure"))
return(populate(args, shape))
}
.iotdataplane$publish_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(topic = structure(logical(0), tags = list(location = "uri", locationName = "topic", type = "string")), qos = structure(logical(0), tags = list(location = "querystring", locationName = "qos", type = "integer")), payload = structure(logical(0), tags = list(type = "blob"))), tags = list(type = "structure", payload = "payload"))
return(populate(args, shape))
}
.iotdataplane$publish_output <- function(...) {
list()
}
.iotdataplane$update_thing_shadow_input <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(thingName = structure(logical(0), tags = list(location = "uri", locationName = "thingName", type = "string")), shadowName = structure(logical(0), tags = list(location = "querystring", locationName = "name", type = "string")), payload = structure(logical(0), tags = list(type = "blob"))), tags = list(type = "structure", payload = "payload"))
return(populate(args, shape))
}
.iotdataplane$update_thing_shadow_output <- function(...) {
args <- c(as.list(environment()), list(...))
shape <- structure(list(payload = structure(logical(0), tags = list(type = "blob"))), tags = list(type = "structure", payload = "payload"))
return(populate(args, shape))
} |
laTeXEscapeString <-function (nameString)
{
return(gsub("\\^","\\\textasciicircum{}",
gsub("~","\\\\textasciitilde{}",
gsub("\\}","\\\\\\}",
gsub("\\{","\\\\\\{",
gsub("_","\\\\_",
gsub("
gsub("\\$", "\\\\\\$",
gsub("&","\\\\&",
gsub("%","\\\\%",
gsub("\\\\","\\textbackslash{}",
nameString
)
)
)
)
)
)
)
)
)
)
)
} |
ExpNumViz <- function (data, target = NULL, type = 1, nlim = 3, fname = NULL,
col = NULL, Page = NULL, sample = NULL, scatter = FALSE,
gtitle = NULL, theme = "Default"){
if (!is.data.frame(data)) stop("data must be a numeric vector or data.frame")
xx <- as.data.frame(data)
num_var <- names(xx)[sapply(xx, is.numeric)]
wrap_40 <- wrap_format(40)
if (length(num_var) == 0) stop("there is no numeric variable in the data frame")
if (length(num_var) > 0){
if (length(num_var) == 1) {
xx1 <- as.data.frame(xx[, num_var]); names(xx1) <- num_var
} else {
xx1 <- xx[, num_var]
}
num_var <- num_var[sapply(xx1, function(x) {
length(unique(na.omit(x))) >= nlim
})]
}
if (!is.null(sample)) {
if (sample > length(num_var))
stop("Sample number is greater than counts of variables")
num_var <- num_var[srswor(sample, length(num_var)) == 1]
}
if (isTRUE(scatter)) {
if (length(num_var) < 2) stop("Input data has less than 2 variables")
plot_comb <- combn(num_var, 2)
}
if (is.null(target)) {
if (isTRUE(scatter)) {
fill_1 <- scolorsel(col, nlevel = 1)
if (length(fill_1) > 1) stop("length of colour input must be 1")
plot_l <- lapply(c(1:ncol(plot_comb)), function(x) {
xi <- plot_comb[, x][1]
yi <- plot_comb[, x][2]
xd <- na.omit(subset(xx, select = c(xi, yi)))
names(xd) <- c("XX", "YY")
p <- ggplot(xd, aes(x = XX, y = YY)) +
geom_point(colour = fill_1, size = 2) + xlab(xi) + ylab(yi) +
ggtitle(wrap_40(paste(gtitle, " ", xi, " vs ", yi))) + smtheme(theme)
return(p)
})
}
else {
plot_l <- lapply(num_var, function(j) {
x <- na.omit(subset(xx, select = j))
y <- xx[, j]
p <- ggplot(data = x, aes_string(x = names(x))) +
geom_line (stat = "density", size = 1, alpha = 1) +
xlab (paste0( (colnames(x)), "\n", "Skewness: ",
round(ExpSkew(y, type = "moment"), 2), " Kurtosis: ",
round(ExpKurtosis(y, type = "excess"), 2))) +
smtheme(theme)
return(p)
})
}
}
else {
if (isTRUE(scatter)) {
target1 <- xx[, target]
nlevel <- length(unique(target1))
fill_1 <- scolorsel(col, nlevel)
if (length(unique(na.omit(target1))) <= 20) {
plot_l <- lapply(c(1:ncol(plot_comb)), function(x){
xi <- plot_comb[, x][1]
yi <- plot_comb[, x][2]
xd <- na.omit(subset(xx, select = c(xi, yi, target)))
names(xd) <- c("XX", "YY", "ZZ")
xd$ZZ <- as.factor(paste0(xd$ZZ))
p <- ggplot(xd, aes(x = XX, y = YY)) +
geom_point(size = 2, aes(color = ZZ)) +
scale_color_manual(name = target, values = fill_1) +
xlab(xi) + ylab(yi) +
ggtitle(wrap_40(paste(gtitle, " ", xi, " vs ", yi))) +
smtheme(theme)
return(p)
}
)
} else stop("If scatter option is TRUE then 'target should be categorical' else 'change scatter = FALSE' ")
}
else {
target1 <- xx[, target]
if (is.numeric(target1) & length(unique(na.omit(target1))) >= 6) {
if (is.null(col)) col <- "
if (length(col) > 1) stop("defined more than one colour")
num_var1 <- num_var[!num_var %in% target]
comma <- NULL
plot_l <- lapply(num_var1, function(j) {
x <- na.omit(subset(xx, select = c(j, target)))
ggplot(x, aes_string(x = names(x)[2], y = names(x)[1])) +
geom_point(colour = col, size = 2) + scale_x_continuous(labels = comma) +
scale_y_continuous(labels = comma) + smtheme(theme)
})
}
else {
target1 <- as.factor(as.character(paste0(target1)))
plot_l <- lapply(num_var, function(j) {
mdat <- subset(xx, select = c(target, j))
names(mdat) <- c("GP", "NV")
if (type == 1) {
mdat$GP <- as.character(paste0(mdat$GP))
if (anyNA(mdat$GP)) {
mdat$GP <- addNA(mdat$GP)
}
mdat1 <- mdat
mdat1$GP <- "All"
gdata <- rbind(mdat, mdat1)
}
if (type == 2) {
gdata <- mdat
gdata$GP <- as.character(paste0(gdata$GP))
if (anyNA(gdata$GP)) {
gdata$GP <- addNA(mdat$GP)
}
}
if (type == 3) {
gdata <- mdat
gdata$GP <- "ALL"
}
nlevel <- length(unique(gdata$GP))
fill_1 <- scolorsel(col, nlevel)
if ( !is.null(col)) {
if (length(col) != nlevel) message("Insufficient values in colour, number of colours should be equal to number of categories")
}
gg1 <- ggplot(gdata, aes(y = NV, x = GP)) +
geom_boxplot(fill = fill_1) + xlab(target) +
ylab(j) + ggtitle(wrap_40(paste(gtitle, " ", j, " vs ", target))) +
scale_x_discrete(labels = wrap_format(8)) +
theme(axis.text.x = element_text(angle = 0, vjust = 0.5, size = 8, colour = "grey20"),
plot.title = element_text(hjust = 0.5, face = "bold", colour = "
return(gg1)
})
}
}
}
if (!is.null(fname)) {
swritepdf(fname, plot_l, Page)
} else {
if (!is.null(Page)) {
pn <- length(plot_l)
nc <- Page[2]
nr <- Page[1]
if ( (nc * nr) > pn + 3)
stop("reduce the matrix dimension from Page(r,c)")
gspl <- split(plot_l, (seq_along(plot_l) - 1) %/% pn)
gplt <- lapply(gspl, function(g) marrangeGrob(grobs = g, nrow = nr, ncol = nc))
return(gplt)
} else {
return(plot_l)
}
}
}
globalVariables(c("comma", "XX", "YY", "ZZ", "GP", "NV")) |
library("dtangle")
.runThisTest <- Sys.getenv("RunAllRRTests") == "yes"
if (.runThisTest) {
Y <- matrix(c(1, 0, 1, 0, 0, 1, 0, 1), byrow = TRUE, nrow = 4)
pure_samples <- list(1, 3)
ml <- find_markers(Y = Y, pure_samples = pure_samples, gamma = 1)$L
test_that("baseline exprs are computed as expected", {
bes <- baseline_exprs(Y = Y, pure_samples = pure_samples, markers = ml)
expect_equal(bes[[1]][[1]], 1)
expect_equal(bes[[2]][[1]], 1)
bes <- baseline_exprs(Y = 5 * Y, pure_samples = pure_samples, markers = ml)
expect_equal(bes[[1]][[1]], 5)
expect_equal(bes[[2]][[1]], 5)
})
} |
require(geometa, quietly = TRUE)
require(testthat)
context("ISOMaintenanceInformation")
test_that("encoding",{
testthat::skip_on_cran()
md <- ISOMaintenanceInformation$new()
md$setMaintenanceFrequency("daily")
xml <- md$encode()
expect_is(xml, "XMLInternalNode")
md2 <- ISOMaintenanceInformation$new(xml = xml)
xml2 <- md2$encode()
expect_true(ISOAbstractObject$compare(md, md2))
}) |
options( width=150, max.print=1000000 )
library(samon, lib.loc="../../samlib")
data("samonPANSS1")
print(samonPANSS1)
samonResults <- samon( mat = samonPANSS1, Npart = 10,
InitialSigmaH = 10.0,
HighSigmaH = 50.0,
InitialSigmaF = 8.0,
HighSigmaF = 50.0,
SAconvg = 1E-6,
FAconvg = 1E-6,
FRconvg = 1E-6
)
print(samonResults$HM)
print(samonResults$FM) |
plot_ClaDS_phylo=function(phylo,rates,rates2=NULL,same.scale=T,main=NULL,lwd=2,log=T,show.tip.label= F, ...){
Colors = colorRampPalette(c("steelblue2","paleturquoise3","palegreen2","yellow2","salmon1","darkorange", "red","red4"))( 100 )
if(is.null(rates2)){
if(log) rates=log(rates)
if(isTRUE(all.equal(rep(as.numeric(rates[1]),length(rates)),as.numeric(rates)))){
col=rep(1,length(rates))
plot(phylo, edge.color = Colors[col], show.tip.label = show.tip.label ,main=main,edge.width =lwd, ...)
if(log){
image.plot(z = c(exp(rates[1]),2*exp(rates[1])),col = Colors, horizontal=T,legend.only = T)
}else{
image.plot(z = c(rates[1],2*rates[1]),col = Colors, horizontal=T,legend.only = T)
}
}else{
col = round( (rates - min(rates)) / diff(range(rates))*99 )+1
plot(phylo, edge.color = Colors[col], show.tip.label = show.tip.label ,main=main,edge.width =lwd, ...)
if(log){
min=min(rates)
max=max(rates)
m10=floor(min/log(10))
M10=ceiling(max/log(10))
if((M10-m10)<4){
ticks=c(1,2,5)
}else{
ticks=1
}
ticks=as.vector(sapply(m10:M10,function(k){return(ticks*10^k)}))
lt=length(ticks[ticks>exp(min) & ticks<exp(max)])
if(lt<4){ticks=c(round(exp(min),max(0,-1*m10+(lt<2))),ticks,round(exp(max),max(0,-1*M10+1+(lt<2))))}
image.plot(z = c(min,max),col = Colors, horizontal=T,legend.only = T,axis.args=list( at=log(ticks), labels=ticks))
}else{
image.plot(z = as.matrix(rates),col = Colors, horizontal=T,legend.only = T)
}
}
}else{
if(log){
rates=log(rates)
rates2=log(rates2)
}
if(same.scale){
min=min(min(rates),min(rates2))
max=max(max(rates),max(rates2))
par(mfrow=c(1,2))
col = round(( (rates - min) / (max-min))*99 )+1
plot(phylo, edge.color = Colors[col], show.tip.label = show.tip.label ,edge.width =lwd, ...)
col = round(( (rates2 - min) / (max-min))*99 )+1
plot(phylo, edge.color = Colors[col], show.tip.label = show.tip.label ,edge.width =lwd, ...)
par(mfrow=c(1,1))
if(log){
m10=floor(min/log(10))
M10=ceiling(max/log(10))
if((M10-m10)<4){
ticks=c(1,2,5)
}else{
ticks=1
}
ticks=as.vector(sapply(m10:M10,function(k){return(ticks*10^k)}))
lt=length(ticks[ticks>exp(min) & ticks<exp(max)])
if(lt<4){ticks=c(round(exp(min),max(0,-1*m10+(lt<2))),ticks,round(exp(max),max(0,-1*M10+1+(lt<2))))}
image.plot(z = c(min,max),col = Colors, horizontal=T,legend.only = T,axis.args=list( at=log(ticks), labels=ticks))
}else{
image.plot(z = c(min,max),col = Colors, horizontal=T,legend.only = T)
}
}else{
par(mfrow=c(1,2))
if(isTRUE(all.equal(rep(rates[1],length(rates)),rates))){
col=rep(1,length(rates))
plot(phylo, edge.color = Colors[col], show.tip.label = show.tip.label ,edge.width =lwd, ...)
if(log){
image.plot(z = c(exp(rates[1]),2*exp(rates[1])),col = Colors, horizontal=T,legend.only = T)
}else{
image.plot(z = c(rates[1],2*rates[1]),col = Colors, horizontal=T,legend.only = T)
}
}else{
col = round(( (rates - min(rates)) / (max(rates)-min(rates)))*99 )+1
plot(phylo, edge.color = Colors[col], show.tip.label = show.tip.label ,edge.width =lwd, ...)
if(log){
min=min(rates)
max=max(rates)
m10=floor(min/log(10))
M10=ceiling(max/log(10))
if((M10-m10)<4){
ticks=c(1,2,5)
}else{
ticks=1
}
ticks=as.vector(sapply(m10:M10,function(k){return(ticks*10^k)}))
lt=length(ticks[ticks>exp(min) & ticks<exp(max)])
if(lt<4){ticks=c(round(exp(min),max(0,-1*m10+(lt<2))),ticks,round(exp(max),max(0,-1*M10+1+(lt<2))))}
image.plot(z = c(min,max),col = Colors, horizontal=T,legend.only = T,axis.args=list( at=log(ticks), labels=ticks))
}else{
image.plot(z = as.matrix(rates),col = Colors, horizontal=T,legend.only = T)
}
}
if(isTRUE(all.equal(rep(rates2[1],length(rates2)),rates2))){
col=rep(1,length(rates2))
plot(phylo, edge.color = Colors[col], show.tip.label = show.tip.label ,edge.width =lwd, ...)
if(log){
image.plot(z = c(exp(rates2[1]),2*exp(rates2[1])),col = Colors, horizontal=T,legend.only = T)
}else{
image.plot(z = c(rates2[1],2*rates2[1]),col = Colors, horizontal=T,legend.only = T)
}
}else{
col = round(( (rates2 - min(rates2)) / (max(rates2)-min(rates2)))*99 )+1
plot(phylo, edge.color = Colors[col], show.tip.label = show.tip.label ,edge.width =lwd, ...)
if(log){
min=min(rates2)
max=max(rates2)
m10=floor(min/log(10))
M10=ceiling(max/log(10))
if((M10-m10)<4){
ticks=c(1,2,5)
}else{
ticks=1
}
ticks=as.vector(sapply(m10:M10,function(k){return(ticks*10^k)}))
lt=length(ticks[ticks>exp(min) & ticks<exp(max)])
if(lt<4){ticks=c(round(exp(min),max(0,-1*m10+(lt<2))),ticks,round(exp(max),max(0,-1*M10+1+(lt<2))))}
image.plot(z = c(min,max),col = Colors, horizontal=T,legend.only = T,axis.args=list( at=log(ticks), labels=ticks))
}else{
image.plot(z = as.matrix(rates2),col = Colors, horizontal=T,legend.only = T)
}
}
}
par(mfrow=c(1,1))
}
} |
"ecld.quartic_SN0_atm_ki" <- function() {
eq_RN0 <- function(ki, Q=sqrt(240)) {
kQ = abs(ki/Q)
L1 = Q*ecld.ogf_star_analytic(ecld(1), kQ)
L4 = ecld.ogf_star_analytic(ecld(4),ki)
L1-L4
}
rs <- uniroot(eq_RN0, lower=-30, upper=0)
return(rs$root)
}
"ecld.quartic_SN0_rho_stdev" <- function() {
-ecld.quartic_SN0_atm_ki()/sqrt(120)
}
"ecld.quartic_SN0_skew" <- function() {
atm_ki <- ecld.quartic_SN0_atm_ki()
X = sqrt(abs(atm_ki))
Z = abs(atm_ki/sqrt(240))
sqrt(pi)*exp(Z^2-X) * (1+X-exp(X)*ecd.erfc(Z))
}
"ecld.quartic_SN0_max_RNV" <- function(sigma=0) {
find_mu_p_ratio <- function(mu_p_ratio) {
find_Q_SN0 <- function(Q, ki) {
ki1 <- ki/Q - mu_p_ratio*sqrt(120)/Q
Lc1 <- ecld.ogf_star_analytic(ecld(1), ki1)
Lc <- ecld.ogf_star_analytic(ecld(4), ki)
ecd.mp2f(Q*Lc1 - Lc)
}
find_skew <- function(ki, Q=sqrt(240)) {
X = sqrt(abs(ki))
Z = abs(ki/Q - mu_p_ratio*sqrt(120)/Q)
sqrt(pi)*exp(Z^2-X) * (1+X-exp(X)*ecd.erfc(Z))
}
atm_ki <- uniroot(find_skew, lower=-4, upper=-0.1)$root
Q <- uniroot(find_Q_SN0, ki=atm_ki, lower=0.1, upper=100)$root
(Q-sqrt(240))*1000
}
if (sigma==0) {
R <- uniroot(find_mu_p_ratio, lower=0.29, upper=0.3)$root
return (R)
}
stop("ERROR!")
} |
theme_ipsum_ps <- function(
base_family="IBMPlexSans", base_size = 11.5,
plot_title_family="IBMPlexSans-Bold", plot_title_size = 18,
plot_title_face="plain", plot_title_margin = 10,
subtitle_family=if (.Platform$OS.type == "windows") "IBMPlexSans" else "IBMPlexSans-Light",
subtitle_size = 13,
subtitle_face = "plain", subtitle_margin = 15,
strip_text_family = "IBMPlexSans-Medium", strip_text_size = 12,
strip_text_face = "plain",
caption_family=if (.Platform$OS.type == "windows") "IBMPlexSans" else "IBMPlexSans-Thin",
caption_size = 9,
caption_face = "plain", caption_margin = 10,
axis_text_size = 9,
axis_title_family = base_family,
axis_title_size = 9,
axis_title_face = "plain",
axis_title_just = "rt",
plot_margin = margin(30, 30, 30, 30),
grid_col = "
axis_col = "
ret <- ggplot2::theme_minimal(base_family=base_family, base_size=base_size)
ret <- ret + theme(legend.background=element_blank())
ret <- ret + theme(legend.key=element_blank())
if (inherits(grid, "character") | grid == TRUE) {
ret <- ret + theme(panel.grid=element_line(color=grid_col, size=0.2))
ret <- ret + theme(panel.grid.major=element_line(color=grid_col, size=0.2))
ret <- ret + theme(panel.grid.minor=element_line(color=grid_col, size=0.15))
if (inherits(grid, "character")) {
if (regexpr("X", grid)[1] < 0) ret <- ret + theme(panel.grid.major.x=element_blank())
if (regexpr("Y", grid)[1] < 0) ret <- ret + theme(panel.grid.major.y=element_blank())
if (regexpr("x", grid)[1] < 0) ret <- ret + theme(panel.grid.minor.x=element_blank())
if (regexpr("y", grid)[1] < 0) ret <- ret + theme(panel.grid.minor.y=element_blank())
}
} else {
ret <- ret + theme(panel.grid=element_blank())
}
if (inherits(axis, "character") | axis == TRUE) {
ret <- ret + theme(axis.line=element_line(color=axis_col, size=0.15))
if (inherits(axis, "character")) {
axis <- tolower(axis)
if (regexpr("x", axis)[1] < 0) {
ret <- ret + theme(axis.line.x=element_blank())
} else {
ret <- ret + theme(axis.line.x=element_line(color=axis_col, size=0.15))
}
if (regexpr("y", axis)[1] < 0) {
ret <- ret + theme(axis.line.y=element_blank())
} else {
ret <- ret + theme(axis.line.y=element_line(color=axis_col, size=0.15))
}
} else {
ret <- ret + theme(axis.line.x=element_line(color=axis_col, size=0.15))
ret <- ret + theme(axis.line.y=element_line(color=axis_col, size=0.15))
}
} else {
ret <- ret + theme(axis.line=element_blank())
}
if (!ticks) {
ret <- ret + theme(axis.ticks = element_blank())
ret <- ret + theme(axis.ticks.x = element_blank())
ret <- ret + theme(axis.ticks.y = element_blank())
} else {
ret <- ret + theme(axis.ticks = element_line(size=0.15))
ret <- ret + theme(axis.ticks.x = element_line(size=0.15))
ret <- ret + theme(axis.ticks.y = element_line(size=0.15))
ret <- ret + theme(axis.ticks.length = grid::unit(5, "pt"))
}
xj <- switch(tolower(substr(axis_title_just, 1, 1)), b=0, l=0, m=0.5, c=0.5, r=1, t=1)
yj <- switch(tolower(substr(axis_title_just, 2, 2)), b=0, l=0, m=0.5, c=0.5, r=1, t=1)
ret <- ret + theme(axis.text.x=element_text(size=axis_text_size, margin=margin(t=0)))
ret <- ret + theme(axis.text.y=element_text(size=axis_text_size, margin=margin(r=0)))
ret <- ret + theme(axis.title=element_text(size=axis_title_size, family=axis_title_family))
ret <- ret + theme(axis.title.x=element_text(hjust=xj, size=axis_title_size,
family=axis_title_family, face=axis_title_face))
ret <- ret + theme(axis.title.y=element_text(hjust=yj, size=axis_title_size,
family=axis_title_family, face=axis_title_face))
ret <- ret + theme(axis.title.y.right=element_text(hjust=yj, size=axis_title_size, angle=90,
family=axis_title_family, face=axis_title_face))
ret <- ret + theme(strip.text=element_text(hjust=0, size=strip_text_size,
face=strip_text_face, family=strip_text_family))
ret <- ret + theme(panel.spacing=grid::unit(2, "lines"))
ret <- ret + theme(plot.title=element_text(hjust=0, size=plot_title_size,
margin=margin(b=plot_title_margin),
family=plot_title_family, face=plot_title_face))
ret <- ret + theme(plot.subtitle=element_text(hjust=0, size=subtitle_size,
margin=margin(b=subtitle_margin),
family=subtitle_family, face=subtitle_face))
ret <- ret + theme(plot.caption=element_text(hjust=1, size=caption_size,
margin=margin(t=caption_margin),
family=caption_family, face=caption_face))
ret <- ret + theme(plot.margin=plot_margin)
ret
}
import_plex_sans <- function() {
ps_font_dir <- system.file("fonts", "plex-sans", package="hrbrthemes")
suppressWarnings(suppressMessages(extrafont::font_import(ps_font_dir, prompt=FALSE)))
message(
sprintf(
"You will likely need to install these fonts on your system as well.\n\nYou can find them in [%s]",
ps_font_dir)
)
}
font_ps <- "IBMPlexSans"
font_ps_light <- "IBMPlexSans-Light" |
library("surveillance")
options(SweaveHooks=list(fig=function() par(mar=c(4,4,2,0)+.5)))
options(width=70)
set.seed(247)
dir.create("plots", showWarnings=FALSE)
getOption("SweaveHooks")[["fig"]]()
data(shadar)
plot(shadar,main="Number of salmonella hadar cases in Germany 2001-2006")
simData <- sim.pointSource(length=300,K=0.5,r=0.6,p=0.95)
getOption("SweaveHooks")[["fig"]]()
plot(simData)
getOption("SweaveHooks")[["fig"]]()
survObj <- algo.glrnb(shadar,control=list(range=105:295,alpha=0))
plot(survObj,startyear=2003)
control=list(range=105:295,alpha=NULL)
surv <- algo.glrnb(shadar,control=control)
surv$control$alpha
control=list(range=105:295,mu0=list(S=2,trend=F,refit=T))
surv <- algo.glrnb(disProgObj=shadar,control=control)
getOption("SweaveHooks")[["fig"]]()
plot(shadar)
with(surv$control,lines(mu0~range,lty=2,lwd=4,col=4))
estimateGLRNbHook
coef(surv$control$mu0Model$fitted[[1]])
control=list(range=105:295,alpha=0)
surv <- algo.glrnb(disProgObj=shadar,control=control)
table(surv$alarm)
num <- rep(NA)
for (i in 1:6){
num[i] <- table(algo.glrnb(disProgObj=shadar,control=c(control,c.ARL=i))$alarm)[2]
}
control=list(range=105:295,ret="cases",alpha=0)
surv2 <- algo.glrnb(disProgObj=shadar,control=control)
getOption("SweaveHooks")[["fig"]]()
plot(surv2,startyear=2003)
control=list(range=105:295,ret="cases",dir="dec",alpha=0)
surv3 <- algo.glrnb(disProgObj=shadar,control=control)
getOption("SweaveHooks")[["fig"]]()
plot(surv3,startyear=2003) |
dtt_decade <- function(x, ...) {
UseMethod("dtt_decade")
}
dtt_decade.Date <- function(x, ...) {
chk_unused(...)
year <- dtt_year(x)
year <- year / 10
year <- floor(year)
year <- year * 10
year <- as.integer(year)
year
} |
regspmplot <- function(y, X, group, plot,
namey, nameX, col, cex, pch, labeladd, legend, xlim, ylim,
tag, datatooltip, databrush, subsize, selstep, selunit,
trace=FALSE, ...)
{
if(missing(y) | !(inherits(y, "data.frame") | inherits(y, "matrix") | inherits(y, "fsreda") | inherits(y, "sregeda") | inherits(y, "mmregeda")))
stop("Function defined only for monitoring type output from forward search or a data matrix.")
if(inherits(y, "fsreda") || inherits(y, "sregeda") || inherits(y, "mmregeda"))
{
outStr <- list(RES=out$RES, Un=out$Un, y=out$y, X=out$X, class=getMatlabClass(class(out)))
if(!is.null(out$Un))
outStr$Un <- out$Un
if(!is.null(out$Bols))
outStr$Bols <- out$Bols
if(!is.null(out$bdp))
outStr$bdp <- out$bdp
if(!is.null(out$eff))
outStr$eff <- out$eff
if(!is.null(out$Weights))
outStr$Weights <- out$Weights
if(is.null(outStr$RES) || is.null(outStr$y) || is.null(outStr$X))
stop("One or more required arguments are missing.")
} else
{
if(is.vector(y) || nrow(y) == 1 || ncol(y) == 1)
{
y <- as.vector(y)
if(missing(X))
stop("If 'y' is a vector, a predictor data matrix X must be provided.")
X <- as.data.frame(X)
outStr <- list(y=y, X=X)
} else
stop("'y' must be a vector or can be coerced to a vector and a predictor data matrix X must be provided.")
}
control = list(...)
if(!missing(group))
{
if(length(group) != length(outStr$y))
stop("Parameter 'group', if provided must be the same length as 'y'")
control$group <- group
}
if(!missing(plot))
control$plo <- plot
if(!missing(namey))
{
if(length(which(names(control) == "plo")) == 0)
control$plo <- list()
control$plo$namey <- as.character(namey)
}
if(!missing(nameX))
{
if(length(which(names(control) == "plo")) == 0)
control$plo <- list()
control$plo$nameX <- as.character(nameX)
}
if(!missing(col))
{
if(length(which(names(control) == "plo")) == 0)
control$plo <- list()
control$plo$clr <- paste(mapColor(col), collapse="")
}
if(!missing(cex))
{
if(length(which(names(control) == "plo")) == 0)
control$plo <- list()
control$plo$siz <- 6
control$plo$siz <- cex * control$plo$siz
}
if(!missing(pch))
{
if(length(which(names(control) == "plo")) == 0)
control$plo <- list()
control$plo$sym <- map_pch(pch)
}
if(!missing(labeladd))
{
if(length(which(names(control) == "plo")) == 0)
control$plo <- list()
control$plo$labeladd <- if(is.logical(labeladd) && labeladd |
is.character(labeladd) & labeladd =="1" |
is.numeric(labeladd) & labeladd != 0) "1" else ""
}
if(!missing(legend))
{
if(length(which(names(control) == "plo")) == 0)
control$plo <- list()
control$plo$doleg <- if(is.logical(legend) && legend |
is.character(legend) & legend =="on" |
is.numeric(legend) & legend != 0) "on" else "off"
}
if(!missing(xlim))
{
if(length(which(names(control) == "plo")) == 0)
control$plo <- list()
control$plo$xlimx <- xlim
}
if(!missing(ylim))
{
if(length(which(names(control) == "plo")) == 0)
control$plo <- list()
control$plo$ylimy <- ylim
}
if(length(which(names(control) == "plo")) > 0)
{
if(is.logical(control$plo))
control$plo <- if(plot) 1 else 0
else if(is.list(control$plo))
{
if("namey" %in% names(control$plo) && length(control$plo$namey) != 1)
stop("'namey' can be only a simple string!")
if("nameX" %in% names(control$plo) && length(control$plo$nameX) != ncol(outStr$X))
stop(paste("'nameX' must be of vector of ", ncol(outStr$X), "strings!"))
if("xlimx" %in% names(control$plo))
{
if(length(control$plo$xlimx) != 2)
stop(paste0("'xlim' must be of vector of 2 numbers!"))
else control$plo$xlimx <- as.numeric(control$plo$xlimx)
}
if("ylimy" %in% names(control$plo))
{
if(length(control$plo$ylimy) != 2)
stop(paste0("'xlimy' must be of vector of 2 numbers!"))
else control$plo$ylimy <- as.numeric(control$plo$ylimy)
}
if("doleg" %in% names(control$plo) && length(control$plo$doleg) != 1)
stop("'legend' can be one of 'on' (default) or 'off'!")
}
}
if(!missing(datatooltip))
{
if(is.logical(datatooltip))
{
if(datatooltip)
control$datatooltip <- 1
}else if(is.list(datatooltip))
control$datatooltip <- datatooltip
else
stop(paste("Wrong argument 'datatooltip':", datatooltip))
}
if(!missing(databrush))
{
if(is.logical(databrush))
{
if(databrush)
control$databrush <- 1
}else if(is.list(databrush))
control$databrush <- databrush
}
if(!missing(selunit))
control$selunit <- selunit
if(!missing(selstep))
{
if(!is.numeric(selstep))
stop("'selstep' must be a numeric vector!")
control$selstep <- selstep
}
if(!missing(subsize))
control$subsize <- subsize
if(!missing(tag))
control$tag <- as.character(tag)
if(trace)
{
cat("\nOptional parameters to regspmplot(): \n")
print(control)
}
parlist <- c(.jarray(as.matrix(outStr$y), dispatch=TRUE),
.jarray(as.matrix(outStr$X), dispatch=TRUE))
paramNames = names(control)
if (length(paramNames) > 0) {
for (i in 1:length(paramNames)) {
paramName = paramNames[i];
paramValue = control[[i]];
matlabValue = rType2MatlabType(paramName, paramValue)
parlist = c(parlist, .jnew("java/lang/String", paramName), matlabValue)
}
}
matlabParams <- parlist
out <- callFsdaFunction("yXplot", "[Ljava/lang/Object;", 1, parlist)
ans = list()
freeMatlabResources(out)
return(invisible(ans))
} |
checkStrictOrder <- function(dat,invertCount=TRUE){
testO <- array(NA,dim=c(nrow(dat),ncol(dat)-1,2))
testId <- matrix(NA,nrow=nrow(dat),ncol=ncol(dat)-1)
for(i in 1:(ncol(dat)-1)) {
testO[,i,1] <- dat[,i] > dat[,i+1]
testO[,i,2] <- dat[,i] < dat[,i+1]
testId[,i] <- dat[,i] == dat[,i+1]
}
if(invertCount) {testO <- !testO; testId <- !testId}
out <- cbind(up=rowSums(testO[,,2],na.rm=TRUE),down=rowSums(testO[,,1],na.rm=TRUE),eq=rowSums(testId,na.rm=TRUE))
rownames(out) <- rownames(dat)
out }
.firstMin <- function(x,positionOnly=FALSE) {
minPos <- which.min(x)
if(positionOnly) minPos else x[minPos] }
.medianSpecGrp <- function(x,grpNum,grpVal,sumMeth="median",callFrom=NULL){
fxNa <- .composeCallName(callFrom,newNa=".medianSpecGrp")
msg1 <- c("argument ","'grpVal' should be numeric; ",
"'grpNum' should be of length 1 and may be numeric or names of 'x'")
if(sum(is.na(x))==length(x)) {
message(fxNa,"argument 'x' seems all empty or NA, nothing to do")
} else {
if(length(grpVal) != 1) stop(fxNa,msg1[c(1:2)])
if(any(sum(is.na(x))==length(x),sum(is.na(grpNum)) >0,is.na(grpVal))) stop(msg1[c(1:2,1,3)])
if(length(grep("^[[:digit:]]+$",grpNum)) <1) grpNum <- match(grpNum,names(x))
grpNum <- convToNum(grpNum,remove=NULL)
grpNum <- grpNum[grpNum <= length(x)]
msg2 <- "'grpNum' should be either numeric for positions in 'x' or character for names of 'x'"
if(length(grpNum) <1) stop(fxNa,msg1[1],msg2)
grp1ini <- if(length(grpNum) >1) {
if(identical(sumMeth,"median")) stats::median(x[grpNum],na.rm=TRUE) else mean(x[grpNum],na.rm=TRUE)
} else x[grpNum]
x <- if(all(c(grpVal,grp1ini) !=0)) grpVal*x/grp1ini else x + grpVal - grp1ini
}
x }
.scaleSpecGrp <- function(x,grp1Num,grp1Val,grp2Num=NULL,grp2Val=NULL,sumMeth="mean",callFrom=NULL){
fxNa <- .composeCallName(callFrom,newNa=".scaleSpecGrp")
msg1 <- c("argument ","'grp1Val'"," and ","'grp2Val'"," should be numeric of length 1; ",
"'grp1Num'","'grp2Num'"," may be numeric or names of 'x'"," .. ignoring")
if(sum(is.na(x))==length(x)) {
message(fxNa,"argument 'x' seems all empty or NA, nothing to do")
} else {
if(any(sum(is.na(x))==length(x),sum(is.na(grp1Num)) >0,is.na(grp1Val))) stop(msg1[c(1:2,5,6,8)])
if(length(grp1Val) !=1) stop(msg1[c(1:2,5)])
if(length(grep("^[[:digit:]]+$",grp1Num)) <1) grp1Num <- match(grp1Num,names(x))
grp1Num <- convToNum(grp1Num,remove=NULL)
grp1Num <- grp1Num[grp1Num <= length(x)]
if(length(grp1Num) <1) stop(fxNa,"Can't find positions/matches for 'grp1Num' in 'x' !")
grp1ini <- if(length(grp1Num) >1) {
if(identical(sumMeth,"median")) stats::median(x[grp1Num],na.rm=TRUE) else mean(x[grp1Num],na.rm=TRUE)
} else x[grp1Num]
if(identical(grp1Val,grp2Val)) {grp2Num <- NULL; message(" grp1Val and grp2Val should be different ! ignoring grp2Val")}
if(length(grp2Num) >0 & length(grp2Val) !=1) {grp2Num <- NULL; message(fxNa,paste(msg1[c(1,4,5,9)]))}
if(length(grp2Num) >0) {
if(any(sum(is.na(grp2Num)) >0,is.na(grp2Val))) stop(msg1[c(1:2,1,3)])
grp2ini <- if(length(grp2Num) >1) {
if(identical(sumMeth,"median")) stats::median(x[grp2Num],na.rm=TRUE) else mean(x[grp2Num],na.rm=TRUE)
} else x[grp2Num]
if(length(grep("^[[:digit:]]+$",grp2Num)) <1) grp2Num <- match(grp2Num,names(x))
grp2Num <- convToNum(grp2Num,remove=NULL)
grp2Num <- grp2Num[grp2Num <= length(x)]
msg2 <- c("'grp2Num' should be either numeric for positions in 'x' or character for names of 'x'"," ... ignoring")
if(length(grp2Num) <1) {grp2Num <- NULL; message(fxNa,msg1[1],msg2)} }
if(length(grp2Num) <1) {
x <- if(all(c(grp1Val,grp1ini) !=0)) grp1Val*x/grp1ini else x + grp1Val - grp1ini
} else {
x <- x - grp1ini
x <- grp1Val + x*(grp2Val-grp1Val)/grp2ini } }
x }
|
setGeneric("calculateWeights",
function(comparisonMatrix) standardGeneric("calculateWeights"))
setMethod(
f="calculateWeights",
signature(comparisonMatrix="PairwiseComparisonMatrix"),
definition=function(comparisonMatrix)
{
weightsCount = nrow(comparisonMatrix@values)
weights = vector(mode = "numeric", length = weightsCount)
for(i in 1:weightsCount){
weights[i] = prod(comparisonMatrix@values[i,])^(1/weightsCount)
}
sumWeights = sum(weights)
weights = weights/sumWeights
rNames = c()
for (i in 1:length(weights)){
rNames = append(rNames, paste("w_", comparisonMatrix@variableNames[i], sep = ""))
}
names(weights) = rNames
return (new("Weights", weights = weights))
}
)
setMethod(
f="calculateWeights",
signature(comparisonMatrix="FuzzyPairwiseComparisonMatrix"),
definition=function(comparisonMatrix)
{
p = nrow(comparisonMatrix@fnMin)
wMin = c()
wModal = c()
wMax = c()
for(i in 1:p){
limits = .weightsLimits(comparisonMatrix,i)
wMin = append(wMin, limits[1])
wMax = append(wMax, limits[2])
sum = 0
for(k in 1:p){
sum = sum + prod(comparisonMatrix@fnModal[k,])^(1/p)
}
wM = ((prod(comparisonMatrix@fnModal[i,])^(1/p)) / sum)
wModal = append(wModal, wM)
}
return (new("FuzzyWeights", fnMin = wMin, fnModal = wModal, fnMax = wMax))
}
)
setGeneric("calculateWeights_old_methods",
function(comparisonMatrix, type = "Chang") standardGeneric("calculateWeights_old_methods"))
setMethod(
f="calculateWeights_old_methods",
signature(comparisonMatrix = "FuzzyPairwiseComparisonMatrix"),
definition=function(comparisonMatrix, type)
{
if(typeof(type) != "character"){
stop("Variable type must be character!")
}
if(type == "Chang"){
return(.weights_Chang(comparisonMatrix))
}else if (type == "Tesfamariam"){
return(.weights_Tesfamariam(comparisonMatrix))
}else if (type == "Wang"){
return(.weights_Wang(comparisonMatrix))
}else{
stop("Method name not recognized. Can not calculate the weights!")
}
}
)
setGeneric("calculate_weighting_vector",
function(fuzzyWeights) standardGeneric("calculate_weighting_vector"))
setMethod(
f="calculate_weighting_vector",
signature(fuzzyWeights = "FuzzyWeights"),
definition=function(fuzzyWeights)
{
return(.weighting_vector(fuzzyWeights))
}
) |
formatR <- function (r, digits = 2) {
return(ufs::noZero(round(r,
digits = digits)));
} |
readUCSCtable <- function(fiName, exportFileNa=NULL, gtf=NA, simplifyCols=c("gene_id","chr","start","end","strand","frame"), silent=FALSE, callFrom=NULL) {
fxNa <- wrMisc::.composeCallName(callFrom, newNa="readUCSCtable")
if(length(fiName) >1) fiName <- fiName[1] else {if(length(fiName) < 1) stop(" argument 'fiName' seems empty")}
chFi <- file.exists(fiName)
if(!chFi) stop(" file '",fiName,"' not found ! (maybe you are not pointing to the correct direcory ?)")
chPa1 <- try(find.package("utils"), silent=TRUE)
chPa2 <- try(find.package("R.utils"), silent=TRUE)
if("try-error" %in% class(chPa1)) stop(fxNa,"package 'utils' not found ! Please install first ..")
if(is.na(gtf)) {
gtfColNa <- c("
"cdsStartStat","cdsEndStat","exonFrame","
"nCount","acc","status","ensGene","ensTrans")
tmp <- try(utils::read.table(fiName, header=FALSE, stringsAsFactors=FALSE, nrows=7))
if("try-error" %in% class(tmp)) {
gtf <- length(grep("\\.gtf$|\\.gtf\\.gz$", tolower(basename(fiName)))) >0
if(!silent) message(fxNa," Quick guess by file-name if compressed file '",basename(fiName),"' is gtf : ",gtf)
} else {
gtf <- sum(gtfColNa %in% tmp[1,], na.rm=TRUE) <7
if(!silent) message(fxNa," File '",basename(fiName),"' is gtf : ",gtf)
}
}
if("try-error" %in% class(chPa2)) {
if(!silent) message(fxNa," package 'R.utils' not available, assuming by file-extension if file is gz-compressed")
chGz <- length(grep("\\.gz$", tolower(fiName))) >0
} else chGz <- R.utils::isGzipped(fiName)
ensG1 <- try(utils::read.table(fiName, header=!gtf, stringsAsFactors=FALSE))
if("try-error" %in% class(chFi)) {
errMsg <- "' - please check format or see if file is readable"
if(chGz) {
if("try-error" %in% class(chPa2)) stop(fxNa," Package 'R.utils' for decompressing .gz not found ! Please install first or decompress file ",fiName," manually ..")
file.copy(fiName, file.path(tempdir(),basename(fiName)))
tmp <- try(R.utils::gunzip(file.path(tempdir(),basename(fiName))), silent=TRUE)
if("try-error" %in% class(tmp)) stop(" Failed to decompress file ", fiName)
if(!silent) message(fxNa," try reading decompressed file using readVarColumns() ...")
ensG1 <- try(wrMisc::readVarColumns(file.path(tempdir(),basename(fiName), header=!gtf, silent=silent, callFrom=fxNa), silent=TRUE, callFrom=fxNa))
if("try-error" %in% class(ensG1)) stop("Can't read file '",fiName,errMsg)
rmFi <- file.path(tempdir(), c(basename(fiName), sub("\\.gz$","",basename(fiName))))
sapply(rmFi,function(x) if(file.exists(x)) file.remove(x))
} else ensG1 <- try(wrMisc::readVarColumns(fiName, header=!gtf, silent=silent, callFrom=fxNa), silent=TRUE)
if("try-error" %in% class(ensG1)) stop(" Could not succed to read file '",basename(fiName),errMsg)
}
if(gtf) {
colnames(ensG1) <- c("chr","source","type","start","end","score","strand","frame","features")[1:ncol(ensG1)]
chTId <- base::grep("; transcript_id [[:alpha:]]+[[:digit:]]+" , as.character(ensG1[1:30,9]), fixed=FALSE, perl=FALSE)
chGId <- base::grep("^gene_id [[:alpha:]]+[[:digit:]]+", as.character(ensG1[1:30,9]), fixed=FALSE, perl=FALSE)
chId <- base::grep("transcript_id [[:punct:]]{0,1}ENS[[:upper:]]+[[:digit:]][[:print:]]+", as.character(ensG1[1:30,9]), fixed=FALSE, perl=FALSE)
if(length(chTId) >0 & length(chGId) >0) {
newC <- matrix(unlist( strsplit( sub("^gene_id ","",as.character(ensG1[,9]), fixed=FALSE, perl=FALSE),"; transcript_id ",
fixed=FALSE, perl=FALSE)), byrow=TRUE, ncol=2, dimnames=list(NULL,c("gene_id","transcript_id")))
newC <- sub("; $","", newC)
ensG1 <- cbind(ensG1[,-9], newC)
}
}
chG <- colnames(ensG1) %in% simplifyCols[1]
if(!any(chG)) {
NAcol <- colnames(ensG1) %in% "NA" | is.na(colnames(ensG1))
if(any(NAcol)) { chGeId <- which.max(apply(utils::head(ensG1),2, function(x) sum(x==simplifyCols[1])))
if(length(chGeId) >0 & chGeId[1] +1 %in% which(NAcol)) colnames(ensG1)[chGeId[1] +1] <- simplifyCols[1] else {
if(!silent) message(fxNa," failed to locate column to use as '",simplifyCols[1],"'")}
} }
if(length(simplifyCols) >5) { simplifyCols <- simplifyCols[which(simplifyCols %in% colnames(ensG1))]
if(length(simplifyCols) <6 & !silent) message(fxNa," Cannot find sufficient column-names given in argument 'simplifyCols', ignoring ..") }
if(length(simplifyCols) >5) {
iniDim <- dim(ensG1)
ensG1 <- matrix(unlist(by(ensG1[,simplifyCols[1:6]], ensG1[,simplifyCols[1]],
function(x) { if(length(dim(x)) <2) x <- matrix(x, ncol=6, dimnames=list(NULL,simplifyCols[1:6]))
c(x[1,1], x[1,2], min(x[,3],na.rm=TRUE), max(x[,4],na.rm=TRUE), x[1,5], x[1,6])} )),
byrow=TRUE, ncol=6, dimnames=list(NULL,simplifyCols))
if(!silent) message(fxNa," simplifed from ",iniDim[1]," to ",nrow(ensG1)," non-redundant ",simplifyCols[1])
if(length(exportFileNa) >0) {
exportFileNa <- gsub("\\\\", "/", exportFileNa)
forFile <- unique(sub("\\.[[:digit:]]+$", "", ensG1[,"gene_id"], fixed=FALSE, perl=FALSE))
msg <- c("' for conversion on https://www.uniprot.org/uploadlists")
if(!silent) message(fxNa," Write to file : ",paste(utils::head(forFile,4),collapse=", ")," ...")
if(!silent) if(file.exists(exportFileNa[1])) message(fxNa," Beware, file '",exportFileNa[1],"' will be overwritten !") else message(fxNa,
" Exporting file '",exportFileNa,msg[1])
tmp <- try(cat(forFile, file=exportFileNa[1], sep="\n"), silent=TRUE)
if("try-error" %in% class(tmp)) warning(fxNa," Beware: Did not succed to write results to file")}
}
ensG1 }
|
analyse_randomKde2d_smart <- function(nfields=100, nstars, maxX, maxY, nKde=50,
showStats=FALSE, returnStats=TRUE, smartTableDB) {
smartTable <- dbReadTable(smartTableDB, "smartTable")
res <- subset(smartTable, smartTable$nstar==nstars)
if(length(res$mean)!=0) {
retStat <- data.frame(mean=mean(res$mean), sd=mean(res$sd))
} else {
retStat <- analyse_randomKde2d(nfields, nstars, maxX, maxY, nKde, showStats, returnStats)
dbWriteTable(smartTableDB, "smartTable", data.frame(nstar=nstars, mean=retStat$mean, sd=retStat$sd), append=TRUE, row.names = F)
}
return(retStat)
} |
get_dfcrm <- function(parent_selector_factory = NULL, skeleton, target, ...) {
x <- list(
parent_selector_factory = parent_selector_factory,
skeleton = skeleton,
target = target,
extra_args = list(...)
)
class(x) <- c('dfcrm_selector_factory',
'tox_selector_factory',
'selector_factory')
return(x)
}
dfcrm_selector <- function(parent_selector = NULL, outcomes, skeleton, target,
...) {
if(is.character(outcomes)) {
df <- parse_phase1_outcomes(outcomes, as_list = FALSE)
} else if(is.data.frame(outcomes)) {
df <- spruce_outcomes_df(outcomes)
} else {
stop('outcomes should be a character string or a data-frame.')
}
if(nrow(df) > 0) {
if(max(df$dose) > length(skeleton)) {
stop('dfcrm_selector - maximum dose given exceeds number of doses.')
}
x <- crm(prior = skeleton,
target = target,
tox = df$tox %>% as.integer(),
level = df$dose,
var.est = TRUE,
...)
} else {
x <- list(
level = integer(length = 0),
tox = integer(length = 0),
mtd = 1,
ptox = skeleton)
}
l <- list(
parent = parent_selector,
cohort = df$cohort,
outcomes = outcomes,
skeleton = skeleton,
target = target,
dfcrm_fit = x
)
class(l) = c('dfcrm_selector', 'tox_selector', 'selector')
l
}
fit.dfcrm_selector_factory <- function(selector_factory, outcomes, ...) {
if(is.null(selector_factory$parent)) {
parent <- NULL
} else {
parent <- selector_factory$parent %>% fit(outcomes, ...)
}
args <- list(
parent = parent,
outcomes = outcomes,
skeleton = selector_factory$skeleton,
target = selector_factory$target
)
args <- append(args, selector_factory$extra_args)
do.call(dfcrm_selector, args = args)
}
tox_target.dfcrm_selector <- function(x, ...) {
return(x$target)
}
num_patients.dfcrm_selector <- function(x, ...) {
return(length(x$dfcrm_fit$level))
}
cohort.dfcrm_selector <- function(x, ...) {
return(x$cohort)
}
doses_given.dfcrm_selector <- function(x, ...) {
return(x$dfcrm_fit$level)
}
tox.dfcrm_selector <- function(x, ...) {
return(x$dfcrm_fit$tox)
}
num_doses.dfcrm_selector <- function(x, ...) {
return(length(x$skeleton))
}
recommended_dose.dfcrm_selector <- function(x, ...) {
if(!is.null(x$parent)) {
parent_dose <- recommended_dose(x$parent)
parent_cont <- continue(x$parent)
if(parent_cont & !is.na(parent_dose)) {
return(parent_dose)
}
}
return(as.integer(x$dfcrm_fit$mtd))
}
continue.dfcrm_selector <- function(x, ...) {
return(TRUE)
}
mean_prob_tox.dfcrm_selector <- function(x, ...) {
return(x$dfcrm_fit$ptox)
}
median_prob_tox.dfcrm_selector <- function(x, ...) {
return(prob_tox_quantile(x, p = 0.5))
}
prob_tox_quantile.dfcrm_selector <- function(x, p, ...) {
if(num_patients(x) <= 0) {
return(as.numeric(rep(NA, num_doses(x))))
} else {
beta_hat <- x$dfcrm_fit$estimate
beta_var <- x$dfcrm_fit$post.var
beta_q <- qnorm(p = 1 - p, mean = beta_hat, sd = sqrt(beta_var))
if(x$dfcrm_fit$model == 'empiric') {
return(x$skeleton ^ exp(beta_q))
} else if(x$dfcrm_fit$model == 'logistic') {
alpha <- x$dfcrm_fit$intcpt
dose_scaled <- x$dfcrm_fit$dosescaled
inv.logit(alpha + exp(beta_hat) * dose_scaled)
} else {
stop(paste0("Don't know what to do with dfcrm model '",
x$dfcrm_fit$model, "'"))
}
}
}
prob_tox_exceeds.dfcrm_selector <- function(x, threshold, ...) {
if(num_patients(x) <= 0) {
return(as.numeric(rep(NA, num_doses(x))))
} else {
beta_hat <- x$dfcrm_fit$estimate
beta_var <- x$dfcrm_fit$post.var
if(x$dfcrm_fit$model == 'empiric') {
return(pnorm(q = log(log(threshold) / log(x$skeleton)),
mean = beta_hat, sd = sqrt(beta_var)))
} else if(x$dfcrm_fit$model == 'logistic') {
alpha <- x$dfcrm_fit$intcpt
dose_scaled <- x$dfcrm_fit$dosescaled
pnorm(log((logit(threshold) - alpha) / dose_scaled), mean = beta_hat,
sd = sqrt(beta_var))
} else {
stop(paste0("Don't know what to do with dfcrm model '",
x$dfcrm_fit$model, "'"))
}
}
}
supports_sampling.dfcrm_selector <- function(x, ...) {
return(TRUE)
}
prob_tox_samples.dfcrm_selector <- function(x, tall = FALSE,
num_samples = 4000,...) {
df <- get_posterior_prob_tox_sample(x, iter = num_samples)
if(tall) {
dose <- prob_tox <- .draw <- NULL
df %>%
gather(dose, prob_tox, -.draw)
} else {
return(df)
}
}
summary.dfcrm_selector <- function(object, ...) {
Dose <- N <- Tox <- EmpiricToxRate <- Skeleton <- NULL
summary.selector(object) %>%
mutate(Skeleton = c(NA, object$skeleton)) %>%
select(Dose, N, Tox, EmpiricToxRate, Skeleton, everything())
} |
"_PACKAGE"
C.NA.int <- -999
C.NA.double <- -999
library("deSolve")
init.streambugs.C <- function(sys.def)
{
if ( !exists("streambugs.debug") ) streambugs.debug <- 0
c_streambugs_init_debug(streambugs.debug)
ninp <- length(sys.def$inp)
if ( !is.list(sys.def$inp) ) ninp <- 0
c_streambugs_create_input_structure(ninp)
if ( ninp > 0 )
{
for ( i in 1:ninp )
{
n <- nrow(sys.def$inp[[i]])
x <- sys.def$inp[[i]][,1]
y <- sys.def$inp[[i]][,2]
c_streambugs_create_input(i, n, x, y)
}
}
nind <- nrow(sys.def$par.global$inpinds)
inds <- as.integer(sys.def$par.global$inpinds)
inds <- ifelse(is.na(inds),C.NA.int,inds)
npar <- length(sys.def$par.global$parvals)
nams <- names(sys.def$par.global$parvals)
vals <- as.double(sys.def$par.global$parvals)
vals <- ifelse(is.na(vals),C.NA.double,vals)
c_streambugs_create_parglobal(nind, inds, npar, vals, nams)
ntrait <- length(sys.def$par.global.envtraits)
if ( !is.list(sys.def$par.global.envtraits) ) ntrait <- 0
c_streambugs_create_parglobalenvtraits_structure(ntrait)
if ( ntrait > 0 )
{
for ( i in 1:ntrait )
{
name <- names(sys.def$par.global.envtraits)[i]
nind <- nrow(sys.def$par.global.envtraits[[i]]$inpinds)
inds <- as.integer(sys.def$par.global.envtraits[[i]]$inpinds)
inds <- ifelse(is.na(inds),C.NA.int,inds)
npar <- length(sys.def$par.global.envtraits[[i]]$parvals)
nams <- names(sys.def$par.global.envtraits[[i]]$parvals)
vals <- as.double(sys.def$par.global.envtraits[[i]]$parvals)
vals <- ifelse(is.na(vals),C.NA.double,vals)
c_streambugs_create_parglobalenvtrait(i, name, nind, inds, npar, vals, nams)
}
}
nind <- nrow(sys.def$par.envcond.reach$inpinds)
inds <- as.integer(sys.def$par.envcond.reach$inpinds)
inds <- ifelse(is.na(inds),C.NA.int,inds)
npar <- ncol(sys.def$par.envcond.reach$parvals)
nrow <- nrow(sys.def$par.envcond.reach$parvals)
nams <- colnames(sys.def$par.envcond.reach$parvals)
vals <- as.double(sys.def$par.envcond.reach$parvals)
vals <- ifelse(is.na(vals),C.NA.double,vals)
c_streambugs_create_parenvcondreach(nind, inds, npar, nrow, vals, nams)
nind <- nrow(sys.def$par.envcond.habitat$inpinds)
inds <- as.integer(sys.def$par.envcond.habitat$inpinds)
inds <- ifelse(is.na(inds),C.NA.int,inds)
npar <- ncol(sys.def$par.envcond.habitat$parvals)
nrow <- nrow(sys.def$par.envcond.habitat$parvals)
nams <- colnames(sys.def$par.envcond.habitat$parvals)
vals <- as.double(sys.def$par.envcond.habitat$parvals)
vals <- ifelse(is.na(vals),C.NA.double,vals)
c_streambugs_create_parenvcondhabitat(nind, inds, npar, nrow, vals, nams)
ngroup <- length(sys.def$par.envcond.habitat.group)
if ( !is.list(sys.def$par.envcond.habitat.group) ) ngroup <- 0
c_streambugs_create_parenvcondhabitatgroups_structure(ngroup)
if ( ngroup > 0 )
{
for ( i in 1:ngroup )
{
name <- names(sys.def$par.envcond.habitat.group)[i]
nind <- nrow(sys.def$par.envcond.habitat.group[[i]]$inpinds)
inds <- as.integer(sys.def$par.envcond.habitat.group[[i]]$inpinds)
inds <- ifelse(is.na(inds),C.NA.int,inds)
npar <- ncol(sys.def$par.envcond.habitat.group[[i]]$parvals)
nrow <- nrow(sys.def$par.envcond.habitat.group[[i]]$parvals)
nams <- colnames(sys.def$par.envcond.habitat.group[[i]]$parvals)
vals <- as.double(sys.def$par.envcond.habitat.group[[i]]$parvals)
vals <- ifelse(is.na(vals),C.NA.double,vals)
c_streambugs_create_parenvcondhabitatgroup(i, name, nind, inds, npar, nrow, vals, nams)
}
}
nind <- nrow(sys.def$par.initcond$inpinds)
inds <- as.integer(sys.def$par.initcond$inpinds)
inds <- ifelse(is.na(inds),C.NA.int,inds)
npar <- ncol(sys.def$par.initcond$parvals)
nrow <- nrow(sys.def$par.initcond$parvals)
nams <- colnames(sys.def$par.initcond$parvals)
vals <- as.double(sys.def$par.initcond$parvals)
vals <- ifelse(is.na(vals),C.NA.double,vals)
c_streambugs_create_parinitcond(nind, inds, npar, nrow, vals, nams)
nind <- nrow(sys.def$par.input$inpinds)
inds <- as.integer(sys.def$par.input$inpinds)
inds <- ifelse(is.na(inds),C.NA.int,inds)
npar <- ncol(sys.def$par.input$parvals)
nrow <- nrow(sys.def$par.input$parvals)
nams <- colnames(sys.def$par.input$parvals)
vals <- as.double(sys.def$par.input$parvals)
vals <- ifelse(is.na(vals),C.NA.double,vals)
c_streambugs_create_parinput(nind, inds, npar, nrow, vals, nams)
nind <- nrow(sys.def$par.taxaprop.direct$inpinds)
inds <- as.integer(sys.def$par.taxaprop.direct$inpinds)
inds <- ifelse(is.na(inds),C.NA.int,inds)
npar <- ncol(sys.def$par.taxaprop.direct$parvals)
nrow <- nrow(sys.def$par.taxaprop.direct$parvals)
nams <- colnames(sys.def$par.taxaprop.direct$parvals)
vals <- as.double(sys.def$par.taxaprop.direct$parvals)
vals <- ifelse(is.na(vals),C.NA.double,vals)
c_streambugs_create_partaxapropdirect(nind, inds, npar, nrow, vals, nams)
ntrait <- length(sys.def$par.taxaprop.traits)
if ( !is.list(sys.def$par.taxaprop.traits) ) ntrait <- 0
c_streambugs_create_partaxaproptraits_structure(ntrait)
if ( ntrait > 0 )
{
for ( i in 1:ntrait )
{
name <- names(sys.def$par.taxaprop.traits)[i]
nind <- nrow(sys.def$par.taxaprop.traits[[i]]$inpinds)
inds <- as.integer(sys.def$par.taxaprop.traits[[i]]$inpinds)
inds <- ifelse(is.na(inds),C.NA.int,inds)
npar <- ncol(sys.def$par.taxaprop.traits[[i]]$parvals)
nrow <- nrow(sys.def$par.taxaprop.traits[[i]]$parvals)
nams <- colnames(sys.def$par.taxaprop.traits[[i]]$parvals)
vals <- as.double(sys.def$par.taxaprop.traits[[i]]$parvals)
vals <- ifelse(is.na(vals),C.NA.double,vals)
c_streambugs_create_partaxaproptrait(i, name, nind, inds, npar, nrow, vals, nams)
}
}
ny <- length(sys.def$y.names$y.names)
c_streambugs_create_processes_structure(ny)
for ( i in 1:ny )
{
if ( length(sys.def$par.proc.taxon[[i]]) > 0 )
{
for ( j in 1:length(sys.def$par.proc.taxon[[i]]) )
{
procname <- names(sys.def$par.proc.taxon[[i]])[j]
ninp <- nrow(sys.def$par.proc.taxon[[i]][[j]]$inpinds)
inpinds <- as.integer(sys.def$par.proc.taxon[[i]][[j]]$inpinds)
inpinds <- ifelse(is.na(inpinds),C.NA.int,inpinds)
npar <- length(sys.def$par.proc.taxon[[i]][[j]]$parvals)
parnames <- names(sys.def$par.proc.taxon[[i]][[j]]$parvals)
parvals <- as.double(sys.def$par.proc.taxon[[i]][[j]]$parvals)
parvals <- ifelse(is.na(parvals),C.NA.double,parvals)
nstoich <- ncol(sys.def$par.proc.taxon[[i]][[j]]$stoich)
stoichnames <- colnames(sys.def$par.proc.taxon[[i]][[j]]$stoich)
stoichinds <- sys.def$par.proc.taxon[[i]][[j]]$stoich[1,]
stoichvals <- sys.def$par.proc.taxon[[i]][[j]]$stoich[2,]
c_streambugs_create_proctaxon(i, j, procname, ninp, inpinds, npar,
parnames, parvals, nstoich, stoichnames, stoichinds, stoichvals)
}
}
}
for ( i in 1:ny )
{
if ( length(sys.def$par.proc.web[[i]]) > 0 )
{
for ( j in 1:length(sys.def$par.proc.web[[i]]) )
{
procname <- names(sys.def$par.proc.web[[i]])[j]
ninp <- nrow(sys.def$par.proc.web[[i]][[j]]$inpinds)
inpinds <- as.integer(sys.def$par.proc.web[[i]][[j]]$inpinds)
inpinds <- ifelse(is.na(inpinds),C.NA.int,inpinds)
npar <- length(sys.def$par.proc.web[[i]][[j]]$parvals)
parnames <- names(sys.def$par.proc.web[[i]][[j]]$parvals)
parvals <- as.double(sys.def$par.proc.web[[i]][[j]]$parvals)
parvals <- ifelse(is.na(parvals),C.NA.double,parvals)
c_streambugs_create_procweb(i, j, procname, ninp, inpinds, npar, parnames, parvals)
for ( k in 1:length(sys.def$par.proc.web[[i]][[j]]$taxa2) )
{
procname <- names(sys.def$par.proc.web[[i]][[j]]$taxa2)[k]
ninp <- nrow(sys.def$par.proc.web[[i]][[j]]$taxa2[[k]]$inpinds)
inpinds <- as.integer(sys.def$par.proc.web[[i]][[j]]$taxa2[[k]]$inpinds)
inpinds <- ifelse(is.na(inpinds),C.NA.int,inpinds)
npar <- length(sys.def$par.proc.web[[i]][[j]]$taxa2[[k]]$parvals)
parnames <- names(sys.def$par.proc.web[[i]][[j]]$taxa2[[k]]$parvals)
parvals <- as.double(sys.def$par.proc.web[[i]][[j]]$taxa2[[k]]$parvals)
parvals <- ifelse(is.na(parvals),C.NA.double,parvals)
nstoich <- ncol(sys.def$par.proc.web[[i]][[j]]$taxa2[[k]]$stoich)
stoichnames <- colnames(sys.def$par.proc.web[[i]][[j]]$taxa2[[k]]$stoich)
stoichinds <- sys.def$par.proc.web[[i]][[j]]$taxa2[[k]]$stoich[1,]
stoichvals <- sys.def$par.proc.web[[i]][[j]]$taxa2[[k]]$stoich[2,]
c_streambugs_create_procwebtaxon(i, j, k, procname, ninp, inpinds,
npar, parnames, parvals, nstoich, stoichnames, stoichinds,
stoichvals)
}
}
}
}
nreach <- length(sys.def$y.names$ind.fA)
c_streambugs_create_fA_structure(nreach)
for ( i in 1:nreach )
{
nreachind <- length(sys.def$y.names$indfA[[i]]$ind.reach)
reachind <- sys.def$y.names$indfA[[i]]$ind.reach
nfsthabind <- length(sys.def$y.names$indfA[[i]]$ind.1sthab)
fsthabind <- sys.def$y.names$indfA[[i]]$ind.1sthab
c_streambugs_create_fA(i, nreachind, reachind, nfsthabind, fsthabind)
}
return()
}
free.streambugs.C <- function()
{
c_streambugs_delete_inputs()
c_streambugs_delete_parglobal()
c_streambugs_delete_parglobalenvtraits()
c_streambugs_delete_parenvcondreach()
c_streambugs_delete_parenvcondhabitat()
c_streambugs_delete_parenvcondhabitatgroup()
c_streambugs_delete_parinitcond()
c_streambugs_delete_parinput()
c_streambugs_delete_partaxapropdirect()
c_streambugs_delete_partaxaproptraits()
c_streambugs_delete_processes()
c_streambugs_delete_fA()
}
run.streambugs <- function(y.names,times,par,inp=NA,C=FALSE,
file.def=NA,file.res=NA,file.add=NA,
return.res.add = FALSE,tout.add=NA,
verbose=TRUE,
method="lsoda",rtol=1e-4,atol=1e-4,...)
{
ptm <- proc.time()
if ( !is.list(y.names) ) y.names <- decode.statevarnames(y.names)
sys.def <- streambugs.get.sys.def(y.names=y.names,par=par,inp=inp)
if ( !is.na(file.def) ) streambugs.write.sys.def(sys.def=sys.def,file=file.def)
sys.def <- streambugs.updatepar(sys.def,times[1])
w <- sys.def$par.envcond.reach$parvals[,"w"]
fA <- sys.def$par.envcond.habitat$parvals[,"fA"]
D.ini <- sys.def$par.initcond$parvals[,"Dini"]
y.ini <- D.ini * w * fA
names(y.ini) <- y.names$y.names
if ( verbose )
{
cat("streambugs\n")
cat("----------\n")
cat("number of state variables: ",length(y.ini),"\n",sep="")
cat("number of inputs: ",if(is.list(inp)) length(inp) else 0,"\n",sep="")
cat("number of parameters: ",length(par),"\n",sep="")
}
if ( !C )
{
if ( verbose ) cat("running R version of streambugs ...\n")
res <-ode(y = y.ini,
times = times,
func = rhs.streambugs,
parms = sys.def,
method = method,
rtol = rtol,
atol = atol,
...)
}
else
{
if ( verbose ) cat("running C version of streambugs ...\n")
init.streambugs.C(sys.def = sys.def)
res <- ode(y = y.ini,
times = times,
func = "streambugs_rhs",
parms = 0,
dllname = "streambugs",
initfunc = "streambugs_rhs_init",
nout = 1,
method = method,
rtol = rtol,
atol = atol,
...)
free.streambugs.C()
}
res <- res[,1:(1+length(y.ini))]
if ( verbose )
{
cat("simulation completed\n")
print(proc.time()-ptm)
}
if ( !is.na(file.res) ) write.table(res,file.res,col.names=T,row.names=F,sep="\t")
if(length(times) > nrow(res)) warning("unrecoverable error occurred, res not complete")
class(res)="streambugs"
if ( !is.na(file.add) | return.res.add )
{
res.add <- calculate.additional.output(res=res,par=par,inp=inp,file.add=file.add,tout.add=tout.add)
if(return.res.add) return(list(res.add=res.add,res=res))
}
return(list(res=res))
} |
label_short <- function(x, width = 10) {
tibble(id = as.character(x)) %>%
left_join(dynbenchmark::labels, "id") %>%
mutate(short = ifelse(is.na(short), label_capitalise(id), short)) %>%
mutate(short = label_wrap(short, width = width)) %>%
pull(short) %>%
set_names(names(x))
}
label_wrap <- function(x, width = 10, collapse = "\n") {
strwrap(x, width, simplify = FALSE) %>% map_chr(paste0, collapse = collapse)
}
label_long <- function(x) {
tibble(id = as.character(x)) %>%
left_join(dynbenchmark::labels, "id") %>%
mutate(
long = ifelse(
is.na(long),
id %>% label_n %>% label_perc %>% label_capitalise,
long
)
) %>%
pull(long) %>%
set_names(names(x))
}
label_n <- function(x) {
x %>% gsub("^n_", "
}
label_perc <- function(x) {
x %>% gsub("_perc$", "_%", .)
}
label_capitalise <- function(x) {
capitalise <- function(string) {
capped <- grep("^[A-Z]", string, invert = TRUE)
substr(string[capped], 1, 1) <- toupper(substr(string[capped], 1, 1))
string
}
x %>% str_replace_all("_", " ") %>% capitalise()
}
label_facet <- function(label_func = label_long, ...) {
function(df) {
mutate_all(df, label_func, ...)
}
}
label_extrema <- function(x) {
ifelse(x %in% c(0, min(x), max(x)), x, "")
}
label_pvalue <- function(p_values, cutoffs = c(0.1, 0.01, 1e-5)) {
requireNamespace("glue")
breaks <- c(Inf, cutoffs, -Inf)
labels <- rev(c("NS", map_chr(seq_len(length(cutoffs)), ~glue::glue_collapse(rep("*", .)))))
p_values %>% cut(breaks, labels) %>% as.character()
}
label_metric <- function(metric_id, format = get_default_metric_format(), parse = FALSE) {
if (length(metric_id) > 1) {stop("Needs only one metric_id")}
if (metric_id %in% dyneval::metrics$metric_id) {
if (!format %in% colnames(dyneval::metrics)) stop(format, " not found in dyneval::metrics")
label <- dyneval::metrics[[format]][match(metric_id, dyneval::metrics$metric_id)]
} else {
label <- label_long(metric_id)
}
if (parse) {
label <- gsub(" ", " ~~ ", label)
label <- parse(text = label)
}
if (format == "latex") {
label <- paste0("$", label, "$")
}
label
}
label_metrics <- function(metric_ids, ...) {
map(metric_ids, label_metric, ...)
}
get_default_metric_format <- function() {
case_when(
identical(knitr::opts_knit$get("rmarkdown.pandoc.to"), "latex") ~ "latex",
identical(knitr::opts_knit$get("rmarkdown.pandoc.to"), "html") ~ "html",
identical(knitr::opts_knit$get("out.format"), "markdown") ~ "html",
TRUE ~ "plotmath"
)
}
limits_metric <- function(metric_id) {
if (metric_id %in% dyneval::metrics$metric_id) {
extract_row_to_list(dyneval::metrics, which(metric_id == !!metric_id))[c("worst", "perfect")] %>% unlist()
} else {
c(worst = 0, perfect = 1)
}
}
label_time <- function(time) {
case_when(
time < 1e-5 ~ "0s",
time < 1 ~ "<1s",
time < 60 ~ paste0(floor(time), "s"),
time < 3600 ~ paste0(floor(time / 60), "m"),
time < 3600 * 24 ~ paste0(floor(time / 3600), "h"),
time < 3600 * 24 * 7 ~ paste0(floor(time / 3600 / 24), "d"),
!is.na(time) ~ ">7d",
TRUE ~ NA_character_
)
}
label_memory <- function(x, include_mb = FALSE) {
if (include_mb) {
case_when(
x < 1e6 ~ "<1MB",
x < 1e9 ~ paste0(round(x / 1e6), "MB"),
x < 1e12 ~ paste0(round(x / 1e9), "GB"),
!is.na(x) ~ ">1TB",
TRUE ~ NA_character_
)
} else {
case_when(
x < 1e9 ~ "<1GB",
x < 1e12 ~ paste0(round(x / 1e9), "GB"),
!is.na(x) ~ ">1TB",
TRUE ~ NA_character_
)
}
}
label_thousands <- function(x) {
map_chr(x, function(x) {
if (is.na(x)) {
NA
} else if (x < 10^3) {
as.character(round(x))
} else if (x < 10^6) {
paste0(round(x/10^3), "k")
} else {
paste0(round(x/10^6), "M")
}
})
}
tag_first <- function(x, tag) {
y <- x$assemble$plots[[1]]
if ("ggassemble" %in% class(y)) {
x$assemble$plots[[1]] <- tag_first(x$assemble$plots[[1]], tag = tag)
} else {
x$assemble$plots[[1]] <- x$assemble$plots[[1]] + labs(tag = tag)
}
x
}
label_vector <- function(x) {
if (length(x) == 0) {
""
} else if (length(x) == 1) {
x
} else {
glue::glue_collapse(x, sep = ", ", last = " and ")
}
}
label_method <- function(method_ids) {
methods <- load_methods()
methods$name[match(method_ids, methods$id)]
} |
library(knitr)
library(rgl)
opts_chunk$set(out.extra='style="display:block; margin: auto"', fig.align="center", tidy=FALSE)
knit_hooks$set(webgl = hook_webgl)
if (!requireNamespace("rmarkdown", quietly = TRUE) ||
!rmarkdown::pandoc_available("1.14")) {
warning(call. = FALSE, "These vignettes assume rmarkdown and pandoc
version 1.14. These were not found. Older versions will not work.")
knitr::knit_exit()
}
library(mgcViz)
n <- 1e3
dat <- data.frame("x1" = rnorm(n), "x2" = rnorm(n), "x3" = rnorm(n))
dat$y <- with(dat, sin(x1) + 0.5*x2^2 + 0.2*x3 + pmax(x2, 0.2) * rnorm(n))
b <- gam(y ~ s(x1) + s(x2) + x3, data = dat, method = "REML")
b <- getViz(b)
o <- plot( sm(b, 1) )
o + l_fitLine(colour = "red") + l_rug(mapping = aes(x=x, y=y), alpha = 0.8) +
l_ciLine(mul = 5, colour = "blue", linetype = 2) +
l_points(shape = 19, size = 1, alpha = 0.1) + theme_classic()
listLayers(o)
b <- gam(y ~ s(x1, x2) + x3, data = dat, method = "REML")
b <- getViz(b)
plot(sm(b, 1)) + l_fitRaster() + l_fitContour() + l_points()
gridPrint(plot(sm(b, 1)) + l_fitRaster() + l_fitContour() + labs(title = NULL) + guides(fill=FALSE),
plot(pterm(b, 1)) + l_ciPoly() + l_fitLine(), ncol = 2)
b <- getGam(b)
class(b)
dat <- gamSim(1,n=1e3,dist="normal",scale=2)
dat$fac <- as.factor( sample(letters[1:6], nrow(dat), replace = TRUE) )
b <- gam(y~s(x0)+s(x1, x2)+s(x3)+fac, data=dat)
b <- getViz(b)
print(plot(b, allTerms = T), pages = 1)
pl <- plot(b, allTerms = T) + l_points() + l_fitLine(linetype = 3) + l_fitContour() +
l_ciLine(colour = 2) + l_ciBar() + l_fitPoints(size = 1, col = 2) + theme_get() + labs(title = NULL)
pl$empty
print(pl, pages = 1)
plot(b, select = 1)
plot(b, select = 1) + l_dens(type = "cond") + l_fitLine() + l_ciLine()
plot(b, allTerms = TRUE, select = 4) + geom_hline(yintercept = 0)
library(mgcViz)
library(rgl)
n <- 500
x <- rnorm(n); y <- rnorm(n); z <- rnorm(n)
ob <- (x-z)^2 + (y-z)^2 + rnorm(n)
b <- gam(ob ~ s(x, y, z))
b <- getViz(b)
plotRGL(sm(b, 1), fix = c("z" = 0), residuals = TRUE)
aspect3d(1, 2, 1)
set.seed(0)
n.samp <- 400
dat <- gamSim(1,n = n.samp, dist = "binary", scale = .33)
p <- binomial()$linkinv(dat$f)
n <- sample(c(1, 3), n.samp, replace = TRUE)
dat$y <- rbinom(n, n, p)
dat$n <- n
lr.fit <- gam(y/n ~ s(x0) + s(x1) + s(x2) + s(x3),
family = binomial, data = dat,
weights = n, method = "REML")
lr.fit <- getViz(lr.fit)
qq(lr.fit, method = "simul1", a.qqpoi = list("shape" = 1), a.ablin = list("linetype" = 2))
qq(lr.fit, rep = 20, showReps = T, CI = "none", a.qqpoi = list("shape" = 19), a.replin = list("alpha" = 0.2))
set.seed(0)
n.samp <- 20000
dat <- gamSim(1,n=n.samp,dist="binary",scale=.33)
p <- binomial()$linkinv(dat$f)
n <- sample(c(1,3),n.samp,replace=TRUE)
dat$y <- rbinom(n,n,p)
dat$n <- n
lr.fit <- bam(y/n ~ s(x0) + s(x1) + s(x2) + s(x3)
, family = binomial, data = dat,
weights = n, method = "fREML", discrete = TRUE)
lr.fit <- getViz(lr.fit)
o <- qq(lr.fit, rep = 10, method = "simul1", CI = "normal", showReps = TRUE,
a.replin = list(alpha = 0.1), discrete = TRUE)
o
o <- qq(lr.fit, rep = 10, method = "simul1", CI = "normal", showReps = TRUE,
ngr = 1e2, a.replin = list(alpha = 0.1), a.qqpoi = list(shape = 19))
o
gridPrint(o, zoom(o, xlim = c(2, 2.5), ylim = c(2, 2.5)), ncol = 2)
set.seed(0)
dat <- gamSim(1, n = 200)
b <- gam(y ~ s(x0) + s(x1) + s(x2) + s(x3), data = dat)
b <- getViz(b)
check(b,
a.qq = list(method = "tnorm",
a.cipoly = list(fill = "light blue")),
a.respoi = list(size = 0.5),
a.hist = list(bins = 10))
set.seed(4124)
n <- 5e3
x <- rnorm(n); y <- rnorm(n);
z <- as.factor( sample(letters[1:6], n, replace = TRUE) )
ob <- (x)^2 + (y)^2 + (0.2*abs(x) + 1) * rnorm(n)
b <- gam(ob ~ s(x) + s(y) + z)
b <- getViz(b)
ck1 <- check1D(b, "x")
ck2 <- check1D(b, "z")
gridPrint(ck1, ck2, ncol = 2)
gridPrint(ck1 + l_dens(type = "cond", alpha = 0.8) + l_rug(alpha = 0.2),
ck2 + l_points() + l_rug(alpha = 0.2), layout_matrix = matrix(c(1, 1, 1, 2, 2), 1, 5))
ck1 + l_densCheck()
b <- getViz(b, nsim = 50)
gridPrint(check1D(b, "x") + l_gridCheck1D(gridFun = sd, showReps = TRUE),
check1D(b, "z") + l_gridCheck1D(gridFun = sd, showReps = TRUE), ncol = 2)
set.seed(566)
n <- 5e3
X <- data.frame("x1"=rnorm(n, 0.5, 0.5), "x2"=rnorm(n, 1.5, 1),
"fac"=as.factor( sample(letters[1:6], n, replace = TRUE) ))
X$y <- (1-X$x1)^2 + 100*(X$x2 - X$x1^2)^2 + rnorm(n, 0, 2)
b <- gam(y ~ te(x1, x2, k = 5), data = X)
b <- getViz(b, nsim = 50)
ck1 <- check2D(b, x1 = "x1", x2 = "x2")
ck2 <- check2D(b, x1 = X$fac, x2 = "x2") + labs(x = "fac")
ck1 + l_gridCheck2D(gridFun = mean)
ck2 + l_gridCheck2D(gridFun = mean)
ck1 + l_gridCheck2D(bw = c(0.05, 0.1)) + xlim(-1, 1) + ylim(0, 3)
listLayers( ck1 )
set.seed(4124)
n <- 5e3
dat <- data.frame("x1" = rnorm(n), "x2" = rnorm(n))
dat$y <- (dat$x1)^2 + (dat$x2)^2 + (1*abs(dat$x1) + 1) * rnorm(n)
b <- gam(y ~ s(x1) + s(x2), data = dat)
b <- getViz(b)
ck <- check2D(b, x1 = "x1", x2 = "x2", type = "tnormal")
glyFun <- function(.d){
.r <- .d$z
.qq <- as.data.frame( density(.r)[c("x", "y")], n = 100 )
.qq$colour <- rep(ifelse(length(.r)>50, "black", "red"), nrow(.qq))
return( .qq )
}
ck + l_glyphs2D(glyFun = glyFun, ggLay = "geom_path", n = c(8, 8),
mapping = aes(x=gx, y=gy, group = gid, colour = I(colour)),
height=1.5, width = 1)
glyFun <- function(.d){
n <- nrow(.d)
px <- qnorm( (1:n - 0.5)/(n) )
py <- sort( .d$z )
clr <- if(n > 50) { "black" } else { "red" }
clr <- rep(clr, n)
return( data.frame("x" = px, "y" = py - px, "colour" = clr))
}
ck + l_glyphs2D(glyFun = glyFun, ggLay = "geom_point", n = c(10, 10),
mapping = aes(x=gx, y=gy, group = gid, colour = I(colour)),
height=2, width = 1, size = 0.2)
set.seed(6898)
dat <- gamSim(1,n=500,dist="normal",scale=20)
dat$fac <- as.factor( sample(c("A1", "A2", "A3"), nrow(dat), replace = TRUE) )
bs <- "cr"; k <- 12
b <- gam(y ~ s(x2,bs=bs,by = fac), data=dat)
b <- getViz(b)
plotDiff(s1 = sm(b, 1), s2 = sm(b, 2)) + l_ciPoly() +
l_fitLine() + geom_hline(yintercept = 0, linetype = 2)
n <- 1e3
x <- rnorm(n); y <- rnorm(n); z <- rnorm(n); z2 <- rnorm(n)
ob <- (x-z)^2 + (y-z)^2 + z2^3 + rnorm(n)
b <- gam(ob ~ s(x, y, z, z2))
v <- getViz(b)
pl <- plotSlice(x = sm(v, 1),
fix = list("z" = seq(-2, 2, length.out = 3), "x" = c(-1, 0, 1)))
pl + l_fitRaster() + l_fitContour() + l_points() + l_rug() |
gh_search_packages <- function(regex, ignore.case = TRUE) {
package_list <- get_package_list()
ind <- grepl(regex, package_list$title, ignore.case = ignore.case)
as.data.frame(package_list[ind, ], stringsAsFactors= FALSE)
} |
cophyloplot <-
function(x, y, assoc = NULL, use.edge.length = FALSE, space = 0,
length.line = 1, gap = 2, type = "phylogram", rotate = FALSE,
col = par("fg"), lwd = par("lwd"), lty = par("lty"),
show.tip.label = TRUE, font = 3, ...)
{
if (is.null(assoc)) {
assoc <- matrix(ncol = 2)
print("No association matrix specified. Links will be omitted.")
}
if (rotate == TRUE) {
cat("\n Click on a node to rotate (right click to exit)\n\n")
repeat {
res <- plotCophylo2(x, y, assoc = assoc, use.edge.length = use.edge.length,
space = space, length.line = length.line, gap = gap,
type = type, return = TRUE, col = col, lwd=lwd, lty=lty, show.tip.label = show.tip.label,
font = font)
click <- identify(res$c[, 1], res$c[, 2], n = 1)
if (click < length(res$a[, 1]) + 1) {
if (click > res$N.tip.x)
x <- rotate(x, click)
} else if (click < length(res$c[, 1]) + 1) {
if (click > length(res$a[, 1]) + res$N.tip.y)
y <- rotate(y, click - length(res$a[, 1]))
}
}
on.exit(cat("done\n"))
}
else plotCophylo2(x, y, assoc = assoc, use.edge.length = use.edge.length,
space = space, length.line = length.line, gap = gap,
type = type, return = FALSE, col = col, lwd=lwd, lty=lty, show.tip.label = show.tip.label, font = font)
}
plotCophylo2 <-
function(x, y, assoc = assoc, use.edge.length = use.edge.length,
space = space, length.line = length.line, gap = gap,
type = type, return = return, col = col, lwd=lwd, lty=lty,
show.tip.label = show.tip.label,
font = font, ...)
{
res <- list()
left <- max(nchar(x$tip.label, type = "width")) + length.line
right <- max(nchar(y$tip.label, type = "width")) + length.line
space.min <- left + right + gap * 2
if ((space <= 0) || (space < space.min)) space <- space.min
N.tip.x <- Ntip(x)
N.tip.y <- Ntip(y)
res$N.tip.x <- N.tip.x
res$N.tip.y <- N.tip.y
a <- plotPhyloCoor(x, use.edge.length = use.edge.length, type = type)
res$a <- a
b <- plotPhyloCoor(y, use.edge.length = use.edge.length,
direction = "leftwards", type = type)
a[, 2] <- a[, 2] - min(a[, 2])
b[, 2] <- b[, 2] - min(b[, 2])
res$b <- b
b2 <- b
b2[, 1] <- b[1:nrow(b), 1] * (max(a[, 1])/max(b[, 1])) +
space + max(a[, 1])
b2[, 2] <- b[1:nrow(b), 2] * (max(a[, 2])/max(b[, 2]))
res$b2 <- b2
c <- matrix(ncol = 2, nrow = nrow(a) + nrow(b))
c[1:nrow(a), ] <- a[1:nrow(a), ]
c[nrow(a) + 1:nrow(b), 1] <- b2[, 1]
c[nrow(a) + 1:nrow(b), 2] <- b2[, 2]
res$c <- c
plot(c, type = "n", xlim = NULL, ylim = NULL, log = "", main = NULL,
sub = NULL, xlab = NULL, ylab = NULL, ann = FALSE, axes = FALSE,
frame.plot = FALSE)
if (type == "cladogram") {
for (i in 1:(nrow(a) - 1)) segments(a[x$edge[i, 1], 1],
a[x$edge[i, 1], 2], a[x$edge[i, 2], 1], a[x$edge[i,
2], 2], col="red")
for (i in 1:(nrow(b) - 1))
segments(b2[y$edge[i, 1], 1], b2[y$edge[i, 1], 2],
b2[y$edge[i, 2], 1], b2[y$edge[i, 2], 2])
}
if (type == "phylogram") {
for (i in (N.tip.x + 1):nrow(a)) {
l <- length(x$edge[x$edge[, 1] == i, ][, 1])
for (j in 1:l) {
segments(a[x$edge[x$edge[, 1] == i, ][1, 1],
1], a[x$edge[x$edge[, 1] == i, 2], 2][1], a[x$edge[x$edge[,
1] == i, ][1, 1], 1], a[x$edge[x$edge[, 1] ==
i, 2], 2][j])
segments(a[x$edge[x$edge[, 1] == i, ][1, 1],
1], a[x$edge[x$edge[, 1] == i, 2], 2][j], a[x$edge[x$edge[,
1] == i, 2], 1][j], a[x$edge[x$edge[, 1] ==
i, 2], 2][j])
}
}
for (i in (N.tip.y + 1):nrow(b)) {
l <- length(y$edge[y$edge[, 1] == i, ][, 1])
for (j in 1:l) {
segments(b2[y$edge[y$edge[, 1] == i, ][1, 1],
1], b2[y$edge[y$edge[, 1] == i, 2], 2][1],
b2[y$edge[y$edge[, 1] == i, ][1, 1], 1], b2[y$edge[y$edge[,
1] == i, 2], 2][j])
segments(b2[y$edge[y$edge[, 1] == i, ][1, 1],
1], b2[y$edge[y$edge[, 1] == i, 2], 2][j],
b2[y$edge[y$edge[, 1] == i, 2], 1][j], b2[y$edge[y$edge[,
1] == i, 2], 2][j])
}
}
}
if (show.tip.label) {
text(a[1:N.tip.x, ], cex = 0, font = font, pos = 4,
labels = x$tip.label)
text(b2[1:N.tip.y, ], cex = 1, font = font, pos = 2,
labels = y$tip.label)
}
lsa <- 1:N.tip.x
lsb <- 1:N.tip.y
decx <- array(nrow(assoc))
decy <- array(nrow(assoc))
if (length(col)==1) colors<-c(rep(col, nrow(assoc)))
else if (length(col)>=nrow(assoc)) colors<-col
else colors<-c(rep(col, as.integer(nrow(assoc)/length(col))+1))
if (length(lwd)==1) lwidths<-c(rep(lwd, nrow(assoc)))
else if (length(lwd)>=nrow(assoc)) lwidths<-lwd
else lwidths<-c(rep(lwd, as.integer(nrow(assoc)/length(lwd))+1))
if (length(lty) == 1) ltype <- c(rep(lty, nrow(assoc)))
else if (length(lty) >= nrow(assoc)) ltype <- lty
else ltype <- c(rep(lty, as.integer(nrow(assoc)/length(lty))+1))
for (i in 1:nrow(assoc)) {
if (show.tip.label) {
decx[i] <- strwidth(x$tip.label[lsa[x$tip.label == assoc[i, 1]]])
decy[i] <- strwidth(y$tip.label[lsb[y$tip.label == assoc[i, 2]]])
} else {
decx[i] <- decy[i] <- 0
}
if (length.line) {
segments(a[lsa[x$tip.label == assoc[i, 1]], 1] + decx[i] + gap,
a[lsa[x$tip.label == assoc[i, 1]], 2],
a[lsa[x$tip.label == assoc[i, 1]], 1] + gap + left,
a[lsa[x$tip.label == assoc[i, 1]], 2],
col = colors[i], lwd = lwidths[i], lty = ltype[i])
segments(b2[lsb[y$tip.label == assoc[i, 2]], 1] - (decy[i] + gap),
b2[lsb[y$tip.label == assoc[i, 2]], 2],
b2[lsb[y$tip.label == assoc[i, 2]], 1] - (gap + right),
b2[lsb[y$tip.label == assoc[i, 2]], 2],
col = colors[i], lwd = lwidths[i], lty = ltype[i])
}
segments(a[lsa[x$tip.label == assoc[i, 1]], 1] + gap + left,
a[lsa[x$tip.label == assoc[i, 1]], 2],
b2[lsb[y$tip.label == assoc[i, 2]], 1] - (gap + right),
b2[lsb[y$tip.label == assoc[i, 2]], 2],
col = colors[i], lwd = lwidths[i], lty = ltype[i])
}
if (return == TRUE) return(res)
} |
NOT_CRAN <- identical(tolower(Sys.getenv("NOT_CRAN")), "true")
knitr::opts_chunk$set(
collapse = TRUE,
comment = "
fig.width = 8,
fig.height = 5,
purl = NOT_CRAN,
eval = NOT_CRAN
)
library(sf)
library(raster)
library(viridis)
library(leri)
roi <- st_read(system.file("shape/nc.shp", package="sf"))
roi
roi <- st_union(roi)
roi
leri_raster <- get_leri(date = "2018-08-13", product = "8 day ac")
leri_raster
plot(leri_raster, col = cividis(255))
roi_reprojected <- st_transform(roi, crs = projection(leri_raster))
plot(leri_raster, col = cividis(255))
plot(roi_reprojected, add = TRUE)
roi_sp <- as(roi_reprojected, 'Spatial')
cropped_leri <- crop(leri_raster, roi_sp)
masked_leri <- mask(cropped_leri, roi_sp)
plot(masked_leri, col = cividis(255))
plot(roi_sp, add = TRUE) |
equal.ordered.cov <- function(
power = NULL,
sig.level = NULL,
pi = NULL,
kappa = NULL,
N = NULL,
r2dw = NULL,
r2yw = NULL){
G <- (0.5-(pi/2))*(0.5+(pi/2))
S <- 1-r2yw^2
T <- 1-r2dw^2
if (!is.null(power) && !is.null(N)){
beta <- 1 - power
M <- qnorm(1-(sig.level/2)) + qnorm(1-beta)
numer <- 2*M*sqrt(S)
denom <- sqrt(N*pi^2 - 4*M^2*T*G)
upper.effect <- numer/denom
return(upper.effect)
}
if (!is.null(power) && !is.null(kappa)){
beta <- 1 - power
M <- qnorm(1-(sig.level/2)) + qnorm(1-beta)
numer <- 4*M^2*(kappa^2*T*G + S)
denom <- kappa^2*pi^2
upper.N <- numer/denom
return(upper.N)
}
if (!is.null(N) && !is.null(kappa)){
c.val <- qnorm(1-(sig.level/2))
effect.bound <- (0.5*kappa*pi*sqrt(N))/sqrt(S + kappa^2*T*G)
power <- pnorm(-c.val + effect.bound) + pnorm(-c.val - effect.bound)
return(power)
}
} |
context("Filename tagging")
test_that("Tagging yields a character vector", {
expect_true(is.character(tag("data.csv", "qc")));
expect_true(is.character(tag(filename("data", ext="tsv"))));
});
test_that("Tagging a character vector or a filename gives same results", {
x <- "data.txt";
expect_that(tag(x, "qc"), equals(tag(as.filename(x), "qc")));
}); |
anova(concrete.lm1, concrete.lm0)
anova(concrete.lm2, concrete.lm0)
anova(concrete.lm3, concrete.lm0)
anova(concrete.lm4, concrete.lm0) |
SE.xts <-function(x, se.fun, myfun, myfun.IF,
prewhiten = FALSE, cleanOutliers = FALSE, fitting.method = c("Exponential", "Gamma")[1],
freq.include = c("All", "Decimate", "Truncate")[1], freq.par = 0.5, d.GLM.EN = 5,
...){
if (is.vector(x) || is.null(ncol(x)) || ncol(x) == 1) {
x <- as.numeric(x)
return(se.fun(x = x, myfun = myfun, myfun.IF = myfun.IF,
prewhiten = prewhiten, cleanOutliers = cleanOutliers, fitting.method = fitting.method,
freq.include = freq.include, freq.par = freq.par, d.GLM.EN = d.GLM.EN,
...))
}
else{
x <- coredata(x)
return(apply(x, 2, se.fun, myfun = myfun, myfun.IF = myfun.IF,
prewhiten = prewhiten, cleanOutliers = cleanOutliers, fitting.method = fitting.method,
freq.include = freq.include, freq.par = freq.par, d.GLM.EN = d.GLM.EN,
...))
}
}
SE.IF.iid <- function(x, myfun.IF, ...){
N <- length(x)
x.IF <- myfun.IF(x, ...)
x.IF.2 <- x.IF^2
fit.out <- mean(x.IF.2)
return(sqrt(fit.out/N))
}
SE.BOOT.iid <- function(x, myfun, prewhiten = FALSE, nsim = 100, ...){
res <- boot(data = x, statistic = function(x,i, ...) myfun(x[i], ...), R = nsim, ... = ...)
return(sd(res$t))
}
SE.BOOT.cor <- function(x, myfun, myfun.IF, prewhiten = FALSE, nsim = 1000,
sim = "fixed", l = round(length(x)/5), ...){
res = tsboot(tseries = x, statistic = function(x, ...) myfun(x, ...), R = nsim,
sim = sim, l = l, ...)
return(sd(res$t))
}
SE.IF.cor <- function(x, myfun.IF,
d.GLM.EN = 5, alpha.EN = 0.5, keep = 1,
standardize = FALSE,
prewhiten = FALSE, cleanOutliers = FALSE, fitting.method = c("Exponential", "Gamma")[1],
freq.include = c("All", "Decimate", "Truncate")[1], freq.par = 0.5,
return.coef = FALSE,
...){
data.IF <- myfun.IF(x, prewhiten = FALSE, cleanOutliers = cleanOutliers, ...)
if(prewhiten){
ar.coeffs <- as.numeric(arima(x = data.IF, order = c(1,0,0), include.mean = TRUE)$coef[1])
data.IF <- as.numeric(arima(x = data.IF, order = c(1,0,0), include.mean = TRUE)$res)
} else{
ar.coeffs <- NULL
}
fit.out <- SE.GLMEN(data.IF, standardize = standardize,
d = d.GLM.EN, alpha.EN = alpha.EN, keep = keep,
fitting.method = fitting.method,
freq.include = freq.include, freq.par = freq.par,
prewhiten = prewhiten, ar.coeffs = ar.coeffs,
return.coef = return.coef,
...)
if(return.coef){
coeffs <- fit.out[[2]]
fit.out <- fit.out[[1]]
return(list(se = sqrt(fit.out), coef = coeffs))
}
return(sqrt(fit.out))
}
sd.xts <- xts:::sd.xts |
context("Instants")
test_that("is.instant/is.timepoint works as expected", {
expect_false(is.instant(234))
expect_true(is.instant(as.POSIXct("2008-08-03 13:01:59", tz = "UTC")))
expect_true(is.instant(as.POSIXlt("2008-08-03 13:01:59", tz = "UTC")))
expect_true(is.instant(Sys.Date()))
expect_false(is.instant(minutes(1)))
expect_true(is.timespan(interval(
as.POSIXct("2008-08-03 13:01:59", tz = "UTC"),
as.POSIXct("2009-08-03 13:01:59", tz = "UTC"))))
})
test_that("now() handles time zone input correctly", {
nt <- now("UTC")
st <- Sys.time()
expect_identical(
floor_date(nt, "minute"),
floor_date(as.POSIXct(format(as.POSIXct(st), tz = "UTC"), tz = "UTC"), "minute")
)
})
test_that("make_datetime returns same values as ISOdatetime", {
set.seed(1000)
N <- 1e4
y <- as.integer(runif(N, 1800, 2200))
m <- as.integer(runif(N, 1, 12))
d <- as.integer(runif(N, 1, 28))
H <- as.integer(runif(N, 0, 23))
M <- as.integer(runif(N, 0, 59))
S <- runif(N, 0, 59)
out1 <- ISOdatetime(y, m, d, H, M, S, tz = "UTC")
out2 <- make_datetime(y, m, d, H, M, S)
expect_equal(out1, out2)
S <- as.integer(runif(N, 0, 59))
out1 <- ISOdatetime(y, m, d, H, M, S, tz = "UTC")
out2 <- make_datetime(y, m, d, H, M, S)
expect_equal(out1, out2)
out3 <- make_date(y, m, d)
expect_equal(as.Date(out1), out3)
})
test_that("make_datetime replicates as expected", {
expect_equal(make_datetime(year = 1999, month = c(11, 12), day = 22, sec = c(10, 11)),
as.POSIXct(c("1999-11-22 00:00:10 UTC", "1999-12-22 00:00:11 UTC"), tz = "UTC"))
expect_equal(make_datetime(year = c(1999, 2000, 3000), month = c(11, 12), day = 22, sec = c(10, 11, 13, 13)),
ymd_hms(c("1999-11-22 00:00:10", "2000-12-22 00:00:11", "3000-11-22 00:00:13", "1999-12-22 00:00:13"), tz = "UTC"))
expect_equal(make_datetime(year = c(1999, 2000, 3000), month = c(11, 12), day = 22, sec = c(10, 11, 13, 13),
tz = "America/New_York"),
ymd_hms(c("1999-11-22 00:00:10", "2000-12-22 00:00:11", "3000-11-22 00:00:13", "1999-12-22 00:00:13"),
tz = "America/New_York"))
})
test_that("make_datetime propagates NAs as expected", {
expect_equal(make_datetime(year = 1999, month = c(11, NA), day = 22, sec = c(10, 11, NA)),
as.POSIXct(c("1999-11-22 00:00:10 UTC", NA, NA), tz = "UTC"))
}) |
f.optimal_h = function(x,type){
k = kernel("daniell", 0)
spectrumh0 = spectrum(x, kernel= k, taper=0.5, plot = FALSE)
len = length(x)
h = seq(from = 2,to = min(round(0.3*len),200), by = 1)
error = h
for(i in 1:length(h)){
if(type == "daniell" || type == "modified.daniell"){
k = f.kernel_addon(type, h[i], steep= FALSE, y = NULL)
}else{
k = f.kernel_addon(type = type, h[i], steep = FALSE, y = NULL)
}
k$coef[1] = 0
spectrumsmoothed = spectrum(x,kernel= k, taper=0.5, plot = FALSE)
error[i] = f.stuetzle(spectrumsmooth = spectrumsmoothed,spectrumh0 = spectrumh0)
}
h_opt = which(error == min(error))
return(h_opt)
} |
test_that(
"test is_false with a logical input returns true when false",
{
x <- c(TRUE, FALSE, NA)
expected <- c(FALSE, TRUE, FALSE)
actual <- assertive.base::is_false(x)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(cause(actual), noquote(c("true", "", "missing")))
}
)
test_that(
"test is_na with a logical input returns true when NA",
{
x <- c(TRUE, FALSE, NA)
expected <- c(FALSE, FALSE, TRUE)
actual <- is_na(x)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(cause(actual), noquote(c("true", "false", "")))
}
)
test_that(
"test is_na with a character input and no coercion returns true when not NA",
{
x <- c("T", "F", "0", "1", "a", "NA", NA)
expected <- rep.int(c(FALSE, TRUE), c(6, 1))
actual <- is_na(x, coerce_to_logical = FALSE)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(
cause(actual),
noquote(rep.int(c("not missing", ""), c(6, 1)))
)
}
)
test_that(
"test is_na with a character input and coercion returns true when not 'T' or 'F'",
{
x <- c("T", "F", "0", "1", "a", "NA", NA)
expected <- rep.int(c(FALSE, TRUE), c(2, 5))
expect_warning(
actual <- is_na(x, coerce_to_logical = TRUE),
"Coercing x to class .logical.\\."
)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(
cause(actual),
noquote(rep.int(c("true", "false", ""), c(1, 1, 5)))
)
}
)
test_that(
"test is_na with a complex input and no coercion returns true when not NA",
{
x <- c(0, 1, 1i, 1 + 1i, NA)
expected <- rep.int(c(FALSE, TRUE), c(4, 1))
actual <- is_na(x, coerce_to_logical = FALSE)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(
cause(actual),
noquote(rep.int(c("not missing", ""), c(4, 1)))
)
}
)
test_that(
"test is_na with a complex input and coercion returns true when not NA",
{
x <- c(0, 1, 1i, 1 + 1i, NA)
expected <- rep.int(c(FALSE, TRUE), c(4, 1))
expect_warning(
actual <- is_na(x, coerce_to_logical = TRUE),
"Coercing x to class .logical.\\."
)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(
cause(actual),
noquote(rep.int(c("false", "true", ""), c(1, 3, 1)))
)
}
)
test_that(
"test is_na with a list input and no coercion returns true when elements contain a single NA",
{
x <- list(NA, TRUE, FALSE, c(TRUE, FALSE, NA))
expected <- rep.int(c(TRUE, FALSE), c(1, 3))
actual <- is_na(x, coerce_to_logical = FALSE)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(
cause(actual),
noquote(rep.int(c("", "not missing"), c(1, 3)))
)
}
)
test_that(
"test is_na with a list input and coercion throw an error",
{
x <- list(NA, TRUE, FALSE, c(TRUE, FALSE, NA))
expect_error(
is_na(x, coerce_to_logical = TRUE),
"x cannot be coerced to any of these types: .logical.\\."
)
}
)
test_that(
"test is_not_false with a logical input returns true when not false",
{
x <- c(TRUE, FALSE, NA)
expected <- c(TRUE, FALSE, TRUE)
actual <- is_not_false(x)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(cause(actual), noquote(c("", "false", "")))
}
)
test_that(
"test is_not_na with a logical input returns true when not NA",
{
x <- c(TRUE, FALSE, NA)
expected <- c(TRUE, TRUE, FALSE)
actual <- is_not_na(x)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(cause(actual), noquote(c("", "", "missing")))
}
)
test_that(
"test is_not_true with a logical input returns true when not true",
{
x <- c(TRUE, FALSE, NA)
expected <- c(FALSE, TRUE, TRUE)
actual <- is_not_true(x)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(cause(actual), noquote(c("true", "", "")))
}
)
test_that(
"test is_true with a logical input returns true when true",
{
x <- c(TRUE, FALSE, NA)
expected <- c(TRUE, FALSE, FALSE)
actual <- assertive.base::is_true(x)
expect_equal(strip_attributes(actual), expected)
expect_named(actual)
expect_equal(cause(actual), noquote(c("", "false", "missing")))
}
) |
context("PointMassPrior")
test_that("single point prior", {
dist <- Normal(two_armed = FALSE)
prior <- PointMassPrior(.0, 1.0)
expect_equal(
bounds(prior),
c(0, 0),
tolerance = sqrt(.Machine$double.eps), scale = 1)
expect_equal(
adoptr::expectation(prior, function(x) x),
0,
tolerance = sqrt(.Machine$double.eps), scale = 1)
expect_equal(
adoptr::expectation(prior, function(x) x + 1),
1,
tolerance = sqrt(.Machine$double.eps), scale = 1)
n1 <- 20
expect_gt(
predictive_pdf(dist, prior, 0, n1),
predictive_pdf(dist, prior, .1, n1))
expect_gt(
predictive_pdf(dist, prior, 0, n1),
predictive_pdf(dist, prior, -.1, n1))
expect_equal(
stats::integrate(
function(z1) predictive_pdf(dist, prior, z1, n1),
qnorm(.0005), qnorm(.9995), abs.tol = .0001)$value,
1,
tolerance = .001, scale = 1)
expect_equal(
stats::integrate(
function(z1) z1 * predictive_pdf(dist, prior, z1, n1),
qnorm(.0005), qnorm(.9995), abs.tol = .0001)$value,
0,
tolerance = .001, scale = 1)
cprior <- condition(prior, c(-1 , 1))
expect_equal(
cprior@theta,
.0,
tolerance = sqrt(.Machine$double.eps), scale = 1)
expect_equal(
cprior@mass,
1.0,
tolerance = sqrt(.Machine$double.eps), scale = 1)
delta <- .3
z1 <- .3*sqrt(20)
post <- posterior(dist, prior, z1, n1)
expect_equal(
post@theta,
.0,
tolerance = sqrt(.Machine$double.eps), scale = 1)
expect_equal(
post@mass,
1.0,
tolerance = sqrt(.Machine$double.eps), scale = 1)
})
test_that("multiple points prior", {
dist <- Normal(two_armed = FALSE)
prior <- PointMassPrior(c(.0, .5), c(.5, .5))
expect_equal(
bounds(prior),
c(0, .5),
tolerance = sqrt(.Machine$double.eps), scale = 1)
expect_equal(
adoptr::expectation(prior, function(x) x),
.25,
tolerance = sqrt(.Machine$double.eps), scale = 1)
expect_equal(
adoptr::expectation(prior, function(x) x + 1),
1.25,
tolerance = sqrt(.Machine$double.eps), scale = 1)
n1 <- 20
expect_gt(
predictive_pdf(dist, prior, 0, n1),
predictive_pdf(dist, prior, -.1, n1))
expect_gt(
predictive_pdf(dist, prior, 0.5*sqrt(n1), n1),
predictive_pdf(dist, prior, .6*sqrt(n1), n1))
expect_equal(
stats::integrate(
function(z1) predictive_pdf(dist, prior, z1, n1),
qnorm(.0005), qnorm(.9995, mean = .5*sqrt(n1)), abs.tol = .0001)$value,
1,
tolerance = .001, scale = 1)
expect_gt(
stats::integrate(
function(z1) z1 * predictive_pdf(dist, prior, z1, n1),
qnorm(.0005), qnorm(.9995, mean = .5*sqrt(n1)), abs.tol = .0001)$value,
0)
cprior <- condition(prior, c(0 , .1))
expect_equal(
cprior@theta,
.0,
tolerance = sqrt(.Machine$double.eps), scale = 1)
expect_equal(
cprior@mass,
1.0,
tolerance = sqrt(.Machine$double.eps), scale = 1)
delta <- .3
z1 <- .3*sqrt(20)
post <- posterior(dist, prior, z1, n1)
expect_equal(
post@theta,
c(.0, .5),
tolerance = sqrt(.Machine$double.eps), scale = 1)
expect_gt(
post@mass[2],
post@mass[1])
expect_true(is(posterior(Normal(), PointMassPrior(c(0, .5), c(.5, .5)), -.1, 84),
"PointMassPrior"))
})
test_that("errors are defined correctly", {
expect_error(
PointMassPrior(theta = .3, mass = .9))
prior <- PointMassPrior(c(.5, 1.5), rep(.5,2))
expect_error(
condition(prior, 1))
expect_error(
condition(prior, c(0, Inf)))
expect_error(
condition(prior, c(1, 0)))
expect_equal(
condition(prior, c(0, 1))@mass,
1,
tolerance = sqrt(.Machine$double.eps), scale = 1)
})
test_that("show method", {
expect_equal(
capture.output(show(PointMassPrior(.3, 1))),
"PointMass<0.30> "
)
expect_equal(
capture.output(show(PointMassPrior(c(.0, .3), c(.25, .75)))),
"PointMass<Pr[0.00]=0.25;Pr[0.30]=0.75> "
)
}) |
plot_NR <- function(subnic,sig=NULL, sig_thres=0.05,
xlab=NULL, ylab=NULL, main=NA, col.axis="azure3", lty.axis=2, lwd.axis=2,
border.E="black",
col.E="
lty.E=1,
lwd.E=1,
pch.NR.pos=21,
cex.NR.pos=1,
col.NR.pos= "
col.NR.pt="black",
col.NR.lab="black",
cex.NR.lab= NA,
fac.NR.lab=1.2,
col.arrow="black", angle.arrow=20, lwd.arrow=2,
length.arrow=0.1,font.sp=2, leg=T, posi.leg="topleft", bty.leg="n", ...){
eig <- round(subnic$eig/sum(subnic$eig) * 100, 2)
ar_sub <- subarea(subnic)
E <- ar_sub$E
if(is.null(sig)){
li <- subnic$li
}else{
li <- subnic$li[which(round(sig,2)<=sig_thres),]
}
sp <- rownames(li)
if(pch.NR.pos<21|pch.NR.pos>25){
col.NR.pt <- col.NR.pos
}
if(is.null(xlab)){
xlab=paste(paste("OMI1",eig[1], sep=" "),"%",sep="")}
if(is.null(ylab)){
ylab=paste(paste("OMI2",eig[2], sep=" "),"%",sep="")}
plot(subnic$ls, main=main, xlab= xlab,
ylab= ylab, type="n",...)
polygon(E$x, E$y, border=border.E, col=col.E, lty=lty.E, lwd=lwd.E)
M <- dim(li)[1]
abline(h=0, lty=lty.axis, lwd=lwd.axis, col=col.axis)
abline(v=0, lty=lty.axis, lwd=lwd.axis, col=col.axis)
arrows(rep(0,M),rep(0,M),li[,1], li[,2], angle=angle.arrow,
col=col.arrow,lwd=lwd.arrow, length=length.arrow)
points(li[,1], li[,2], col=col.NR.pt, bg=col.NR.pos, pch=pch.NR.pos, cex=cex.NR.pos)
if(!is.na(cex.NR.lab)){
text(li[,1]*fac.NR.lab, li[,2]*fac.NR.lab, sp, col=col.NR.lab, font=font.sp, cex=cex.NR.lab)
}
if(isTRUE(leg)){
filli <- c(col.E, NA)
borderi <- c(border.E, NA)
col.leg <- c(NA, col.NR.pt)
col.bg <- c(NA, col.NR.pos)
pch.leg <- c(NA,pch.NR.pos)
posi.cex <-c(NA,cex.NR.pos)
tex.leg <- c("E","NR position")
if(anyNA(col.NR.pos)){
pch.leg[2] <- NA
col.leg[2] <- NA
col.NR.pt[2] <- NA
tex.leg[2] <- NA
}
lty.leg <- c(0,0)
lwd.leg <- c(0,0)
if(lty.E>1){
pch.leg[1] <- NA
lty.leg[1] <- lty.E
lwd.leg[1] <- lwd.E
}
legend(posi.leg, legend=tex.leg,fill =filli, border=borderi, pch=pch.leg, col=col.leg, pt.cex = posi.cex,
pt.bg=col.bg,lty=lty.leg,pt.lwd=c(NA,1), lwd=lwd.leg, bty=bty.leg,...)
}
} |
predictboth <- function(x, u=NULL, result, np=FALSE){
K <- length(result$param$pi)
out <- matrix(log(result$param$pi), nrow(x), K, byrow = TRUE)
if(!np){
for (k in 1:K){
for (j in 1:ncol(x)){
obs <- which(!is.na(x[,j]))
if (is.factor(x[,j])){
out[obs,k] <- out[obs,k] + log(result$param$alpha[[j]][k,x[obs,j]])
}else{
out[obs,k] <- out[obs,k] + dnorm(x[obs,j], result$param$alpha[[j]][k,1], sqrt(result$param$alpha[[j]][k,2]), log = TRUE)
}
}
}
}else{
all.weights <- unlist(result$param$weights)
for (k in 1:K){
for (j in 1:ncol(x)){
who <- which(!is.na(x[,j]))
if (is.factor(x[,j])){
alpha <- rep(0, nlevels(x[,j]))
for (h in 1:nlevels(x[,j])){
alpha[h] <- sum(result$param$weights[which(x[,j]==h), k])
}
alpha <- alpha / sum(alpha)
out[who,k] <- out[who,k] + log(alpha[x[who,j]])
}else{
se <- seq(min(na.omit(x[,j])) - 5 * result$param$band, max(na.omit(x[,j]))+ 5 * result$param$band, length.out = 1000)
size <- (max(se) - min(se)) / length(se)
out[,k] <- out[,k] + as.numeric(obj3Cpp(se, xj=x[who,j], weightsR=result$param$weights[who,k], band=result$param$band)) * size
}
}
}
}
ztest <- unlist(apply(out, 1, which.max))
yhat <- result$param$beta[ztest]
if (is.null(u)==FALSE){
u <- as.matrix(u)
yhat <- as.matrix(u) %*% result$param$beta[1:ncol(u)] + result$param$beta[ncol(u) + ztest]
}
list(zhat = ztest, yhat = as.numeric(yhat))
} |
logLaplace <-
function (formula, data) {
formula <- as.formula(formula)
X <- model.matrix(formula, data)
y <- data$freq
fit <- glm (formula, data, family = poisson())
W <- diag (fit$fitted.values)
maxloglik <- sum(y * log(fit$fitted.values))
fisherMatrix <- t(X) %*% W %*% X
J <- dim(X)[2]
value <- maxloglik + 0.5 * J * log (2*pi) - 0.5 * log(det(fisherMatrix))
return(value)
} |
html_entities <- jsonlite::fromJSON("https://www.w3.org/TR/html5/entities.json") %>%
lapply(magrittr::extract2, "characters") %>%
list2env()
usethis::use_data(html_entities, internal = TRUE) |
iidATE <- function(estimator,
object.event,
object.treatment,
object.censor,
mydata,
contrasts,
times,
cause,
iid.GFORMULA,
iid.IPTW,
iid.AIPTW,
Y.tau,
F1.ctf.tau,
iW.IPTW,
iW.IPTW2,
iW.IPCW,
iW.IPCW2,
augTerm,
F1.tau,
F1.jump,
S.jump,
G.jump,
dM.jump,
index.obsSINDEXjumpC,
eventVar.time,
time.jumpC,
beforeEvent.jumpC,
beforeTau.nJumpC,
n.obs,
n.times,
product.limit,
...){
n.contrasts <- length(contrasts)
grid <- expand.grid(tau = 1:n.times, contrast = 1:n.contrasts)
n.grid <- NROW(grid)
tol <- 1e-12
if(attr(estimator,"integral")){
ls.F1tau_F1t <- lapply(1:n.times, function(iT){-colCenter_cpp(F1.jump, center = F1.tau[,iT])})
SG <- S.jump*G.jump
SGG <- SG*G.jump
SSG <- SG*S.jump
iSG <- matrix(0, nrow = NROW(SG), ncol = NCOL(SG))
iSGG <- matrix(0, nrow = NROW(SG), ncol = NCOL(SG))
iSSG <- matrix(0, nrow = NROW(SG), ncol = NCOL(SG))
index.beforeEvent.jumpC <- which(beforeEvent.jumpC)
if(length(index.beforeEvent.jumpC)>0){
iSG[index.beforeEvent.jumpC] <- 1/SG[index.beforeEvent.jumpC]
iSGG[index.beforeEvent.jumpC] <- 1/SGG[index.beforeEvent.jumpC]
iSSG[index.beforeEvent.jumpC] <- 1/SSG[index.beforeEvent.jumpC]
}
dM_SG <- dM.jump * iSG
dM_SGG <- dM.jump * iSGG
dM_SSG <- dM.jump * iSSG
ls.F1tau_F1t_SG <- lapply(1:n.times, function(iT){ls.F1tau_F1t[[iT]]*iSG})
ls.F1tau_F1t_dM_SGG <- lapply(1:n.times, function(iT){ls.F1tau_F1t[[iT]]*dM_SGG})
ls.F1tau_F1t_dM_SSG <- lapply(1:n.times, function(iT){ls.F1tau_F1t[[iT]]*dM_SSG})
}
test.IPTW <- attr(estimator,"IPTW")
test.IPCW <- attr(estimator,"IPCW")
any.IPTW <- "IPTW" %in% attr(estimator,"full")
any.IPTW.IPCW <- "IPTW,IPCW" %in% attr(estimator,"full")
any.AIPTW <- "AIPTW" %in% attr(estimator,"full")
any.AIPTW.AIPCW <- "AIPTW,AIPCW" %in% attr(estimator,"full")
if(test.IPTW){
for(iC in 1:n.contrasts){
factor <- TRUE
attr(factor,"factor") <- list()
if(any.IPTW.IPCW){
attr(factor,"factor") <- c(attr(factor,"factor"),
list(IPTW = colMultiply_cpp(Y.tau * iW.IPCW, scale = -iW.IPTW2[,iC]))
)
}else if(any.IPTW){
attr(factor,"factor") <- c(attr(factor,"factor"),
list(IPTW = colMultiply_cpp(Y.tau, scale = -iW.IPTW2[,iC]))
)
}
if(any.AIPTW.AIPCW){
attr(factor,"factor") <- c(attr(factor,"factor"),
list(AIPTW = colMultiply_cpp(Y.tau * iW.IPCW - F1.ctf.tau[[iC]], scale = -iW.IPTW2[,iC]))
)
}else if(any.AIPTW){
attr(factor,"factor") <- c(attr(factor,"factor"),
list(AIPTW = colMultiply_cpp(Y.tau - F1.ctf.tau[[iC]], scale = -iW.IPTW2[,iC]))
)
}
term.treatment <- attr(predictRisk(object.treatment,
newdata = mydata,
average.iid = factor,
level = contrasts[iC]), "average.iid")
if(any.IPTW || any.IPTW.IPCW){
iid.IPTW[[iC]] <- iid.IPTW[[iC]] + term.treatment[["IPTW"]]
}
if(any.AIPTW || any.AIPTW.AIPCW){
iid.AIPTW[[iC]] <- iid.AIPTW[[iC]] + term.treatment[["AIPTW"]]
}
}
}
if(test.IPCW){
factor <- TRUE
for(iTime in 1:n.times){
attr(factor, "factor") <- lapply(1:n.contrasts, function(iC){cbind(-iW.IPTW[,iC]*iW.IPCW2[,iTime]*Y.tau[,iTime])})
term.censoring <- attr(predictRisk(object.censor, newdata = mydata, times = c(0,time.jumpC)[index.obsSINDEXjumpC[,iTime]+1],
diag = TRUE, product.limit = product.limit, average.iid = factor),"average.iid")
for(iC in 1:n.contrasts){
if(any.IPTW || any.IPTW.IPCW){
iid.IPTW[[iC]][,iTime] <- iid.IPTW[[iC]][,iTime] - term.censoring[[iC]]
}
if(any.AIPTW || any.AIPTW.AIPCW){
iid.AIPTW[[iC]][,iTime] <- iid.AIPTW[[iC]][,iTime] - term.censoring[[iC]]
}
}
}
}
if(attr(estimator,"integral")){
int.IFF1_tau <- cbind(0,rowCumSum(dM_SG))
factor <- TRUE
attr(factor,"factor") <- lapply(1:n.contrasts, function(iC){
matrix(NA, nrow = n.obs, ncol = n.times)
})
for(iTau in 1:n.times){
index.col <- prodlim::sindex(jump.times = c(0,time.jumpC), eval.times = pmin(mydata[[eventVar.time]],times[iTau]))
for(iC in 1:n.contrasts){
attr(factor,"factor")[[iC]][,iTau] <- cbind(iW.IPTW[,iC] * int.IFF1_tau[(1:n.obs) + (index.col-1) * n.obs])
}
}
term.intF1_tau <- attr(predictRisk(object.event, newdata = mydata, times = times, cause = cause,
average.iid = factor, product.limit = product.limit),"average.iid")
for(iC in 1:n.contrasts){
iid.AIPTW[[iC]] <- iid.AIPTW[[iC]] + term.intF1_tau[[iC]]
}
factor <- TRUE
attr(factor, "factor") <- lapply(1:n.contrasts, function(iC){
-colMultiply_cpp(dM_SG*beforeEvent.jumpC, scale = iW.IPTW[,iC])
})
integrand.F1t <- attr(predictRisk(object.event, newdata = mydata, times = time.jumpC, cause = cause,
average.iid = factor, product.limit = product.limit), "average.iid")
for(iC in 1:n.contrasts){
iid.AIPTW[[iC]] <- iid.AIPTW[[iC]] + subsetIndex(rowCumSum(integrand.F1t[[iC]]),
index = beforeTau.nJumpC,
default = 0, col = TRUE)
}
for(iC in 1:n.contrasts){
factor <- TRUE
attr(factor,"factor") <- list(AIPTW = colMultiply_cpp(augTerm, scale = -iW.IPTW2[,iC]))
term.treatment <- attr(predictRisk(object.treatment,
newdata = mydata,
average.iid = factor,
level = contrasts[iC]), "average.iid")
iid.AIPTW[[iC]] <- iid.AIPTW[[iC]] + term.treatment[["AIPTW"]]
}
factor <- TRUE
attr(factor,"factor") <- lapply(1:n.grid, function(iGrid){
iTau <- grid[iGrid,"tau"]
iC <- grid[iGrid,"contrast"]
return(-colMultiply_cpp(ls.F1tau_F1t_dM_SSG[[iTau]]*beforeEvent.jumpC, scale = iW.IPTW[,iC]))
})
integrand.St <- attr(predictRisk(object.event, type = "survival", newdata = mydata, times = time.jumpC-tol, cause = cause,
average.iid = factor, product.limit = product.limit), "average.iid")
for(iGrid in 1:n.grid){
iTau <- grid[iGrid,"tau"]
iC <- grid[iGrid,"contrast"]
if(beforeTau.nJumpC[iTau]>0){
iid.AIPTW[[iC]][,iTau] <- iid.AIPTW[[iC]][,iTau] + rowSums(integrand.St[[iGrid]][,1:beforeTau.nJumpC[iTau],drop=FALSE])
}
}
factor <- TRUE
attr(factor,"factor") <- lapply(1:n.grid, function(iGrid){
iTau <- grid[iGrid,"tau"]
iC <- grid[iGrid,"contrast"]
return(-colMultiply_cpp(ls.F1tau_F1t_dM_SGG[[iTau]]*beforeEvent.jumpC, scale = iW.IPTW[,iC]))
})
integrand.G1 <- predictCox(object.censor, newdata = mydata, times = time.jumpC - tol,
average.iid = factor)$survival.average.iid
factor <- TRUE
attr(factor,"factor") <- lapply(1:n.grid, function(iGrid){
iTau <- grid[iGrid,"tau"]
iC <- grid[iGrid,"contrast"]
return(-colMultiply_cpp(ls.F1tau_F1t_SG[[iTau]]*beforeEvent.jumpC, scale = iW.IPTW[,iC]))
})
integrand.G2 <- predictCox(object.censor, newdata = mydata, times = time.jumpC, type = "hazard",
average.iid = factor)$hazard.average.iid
for(iGrid in 1:n.grid){
iTau <- grid[iGrid,"tau"]
iC <- grid[iGrid,"contrast"]
if(beforeTau.nJumpC[iTau]>0){
iid.AIPTW[[iC]][,iTau] <- iid.AIPTW[[iC]][,iTau] + rowSums(integrand.G1[[iGrid]][,1:beforeTau.nJumpC[iTau],drop=FALSE] + integrand.G2[[iGrid]][,1:beforeTau.nJumpC[iTau],drop=FALSE])
}
}
}
out <- list()
if(attr(estimator,"export.GFORMULA")){
out <- c(out, list(GFORMULA = iid.GFORMULA))
}
if(attr(estimator,"export.IPTW")){
out <- c(out, list(IPTW = iid.IPTW))
}
if(attr(estimator,"export.AIPTW")){
out <- c(out, list(AIPTW = iid.AIPTW))
}
return(out)
}
iidATE2 <- function(estimator,
contrasts,
iid.GFORMULA,
iid.IPTW,
iid.AIPTW,
Y.tau,
F1.ctf.tau,
iW.IPTW,
iW.IPTW2,
iW.IPCW,
iW.IPCW2,
augTerm,
F1.tau,
F1.jump,
S.jump,
G.jump,
dM.jump,
iid.nuisance.outcome,
iid.nuisance.treatment,
iid.nuisance.censoring,
iid.nuisance.censoring.diag,
iid.nuisance.survival,
iid.nuisance.martingale,
index.obsSINDEXjumpC,
index.obsSINDEXjumpC.int,
n.obs,
n.times,
n.jumps,
method.iid,
...){
n.contrasts <- length(contrasts)
tol <- 1e-12
if(attr(estimator,"integral")){
SG <- S.jump*G.jump
dM_SG <- dM.jump/SG
ls.F1tau_F1t <- lapply(1:n.times, function(iT){-colCenter_cpp(F1.jump, center = F1.tau[,iT])})
}
test.IPTW <- attr(estimator,"IPTW")
test.IPCW <- attr(estimator,"IPCW")
any.IPTW <- "IPTW" %in% attr(estimator,"full")
any.IPTW.IPCW <- "IPTW,IPCW" %in% attr(estimator,"full")
any.AIPTW <- "AIPTW" %in% attr(estimator,"full")
any.AIPTW.AIPCW <- "AIPTW,AIPCW" %in% attr(estimator,"full")
if(test.IPTW){
for(iC in 1:n.contrasts){
for(iTau in 1:n.times){
if(any.IPTW || any.IPTW.IPCW){
if(any.IPTW){
iFactor <- - Y.tau[,iTau] * iW.IPTW2[,iC]
}else if(any.IPTW.IPCW){
iFactor <- - Y.tau[,iTau] * iW.IPCW[,iTau] * iW.IPTW2[,iC]
}
iid.IPTW[[iC]][,iTau] <- iid.IPTW[[iC]][,iTau] + rowMeans(rowMultiply_cpp(iid.nuisance.treatment[[iC]], scale = iFactor))
}
if(any.AIPTW || any.AIPTW.AIPCW){
if(any.AIPTW){
iFactor <- - (Y.tau[,iTau] - F1.ctf.tau[[iC]][,iTau]) * iW.IPTW2[,iC]
}else if(any.AIPTW.AIPCW){
iFactor <- - (Y.tau[,iTau] * iW.IPCW[,iTau] - F1.ctf.tau[[iC]][,iTau]) * iW.IPTW2[,iC]
}
iid.AIPTW[[iC]][,iTau] <- iid.AIPTW[[iC]][,iTau] + rowMeans(rowMultiply_cpp(iid.nuisance.treatment[[iC]], scale = iFactor))
}
}
}
}
if(test.IPCW){
for(iTau in 1:n.times){
for(iC in 1:n.contrasts){
if(any.IPTW || any.IPTW.IPCW){
iid.IPTW[[iC]][,iTau] <- iid.IPTW[[iC]][,iTau] + rowMeans(rowMultiply_cpp(iid.nuisance.censoring.diag[[iTau]][,1,], -iW.IPCW2[,iTau]*Y.tau[,iTau]*iW.IPTW[,iC]))
}
if(any.AIPTW || any.AIPTW.AIPCW){
iid.AIPTW[[iC]][,iTau] <- iid.AIPTW[[iC]][,iTau] + rowMeans(rowMultiply_cpp(iid.nuisance.censoring.diag[[iTau]][,1,], -iW.IPCW2[,iTau]*Y.tau[,iTau]*iW.IPTW[,iC]))
}
}
}
}
if(attr(estimator,"integral")){
for(iTau in 1:n.times){
integral.F1tau <- calcItermOut(factor = dM_SG,
iid = iid.nuisance.outcome[,iTau,,drop=FALSE],
indexJump = index.obsSINDEXjumpC.int[,iTau],
n = n.obs)
integral.F1t <- calcItermIn(factor = -dM_SG,
iid = iid.nuisance.outcome[, n.times+(1:n.jumps),,drop=FALSE],
indexJump = index.obsSINDEXjumpC.int[,iTau],
n = n.obs)
for(iC in 1:n.contrasts){
iid.AIPTW[[iC]][,iTau] <- iid.AIPTW[[iC]][,iTau] + rowMeans(rowMultiply_cpp(integral.F1tau + integral.F1t, scale = iW.IPTW[,iC]))
}
}
for(iTau in 1:n.times){
for(iC in 1:n.contrasts){
iid.AIPTW[[iC]][,iTau] <- iid.AIPTW[[iC]][,iTau] + rowMeans(rowMultiply_cpp(iid.nuisance.treatment[[iC]],
scale = - augTerm[,iTau] * iW.IPTW2[,iC]))
}
}
for(iTau in 1:n.times){
integral.Surv <- calcItermIn(factor = -ls.F1tau_F1t[[iTau]]*dM_SG/S.jump,
iid = iid.nuisance.survival,
indexJump = index.obsSINDEXjumpC.int[,iTau],
n = n.obs)
for(iC in 1:n.contrasts){
iid.AIPTW[[iC]][,iTau] <- iid.AIPTW[[iC]][,iTau] + rowMeans(rowMultiply_cpp(integral.Surv, scale = iW.IPTW[,iC]))
}
}
for(iTau in 1:n.times){
integral.G <- calcItermIn(factor = -ls.F1tau_F1t[[iTau]]*dM_SG/G.jump,
iid = iid.nuisance.censoring,
indexJump = index.obsSINDEXjumpC.int[,iTau],
n = n.obs)
integral.dLambda <- calcItermIn(factor = -ls.F1tau_F1t[[iTau]]/SG,
iid = iid.nuisance.martingale,
indexJump = index.obsSINDEXjumpC.int[,iTau],
n = n.obs)
for(iC in 1:n.contrasts){
iid.AIPTW[[iC]][,iTau] <- iid.AIPTW[[iC]][,iTau] + rowMeans(rowMultiply_cpp(integral.G + integral.dLambda, scale = iW.IPTW[,iC]))
}
}
}
out <- list()
if(attr(estimator,"export.GFORMULA")){
out <- c(out, list(GFORMULA = iid.GFORMULA))
}
if(attr(estimator,"export.IPTW")){
out <- c(out, list(IPTW = iid.IPTW))
}
if(attr(estimator,"export.AIPTW")){
out <- c(out, list(AIPTW = iid.AIPTW))
}
return(out)
}
calcItermOut <- function(factor, iid, indexJump, n){
ls.I <- lapply(1:n, function(iObs){
iIID <- iid[,1,iObs]
iFactor <- factor[iObs,1:indexJump[iObs]]
if(indexJump[iObs]==0){
return(rep(0,n))
}else {
return(iIID*sum(iFactor))
}
})
return(do.call(cbind,ls.I))
}
calcItermIn <- function(factor, iid, indexJump, n){
ls.I <- lapply(1:n, function(iObs){
iIID <- iid[,1:indexJump[iObs],iObs]
iFactor <- factor[iObs,1:indexJump[iObs]]
if(indexJump[iObs]==0){
return(rep(0,n))
}else if(indexJump[iObs]==1){
return(iIID*iFactor)
}else{
return(rowSums(rowMultiply_cpp(iIID, iFactor)))
}
})
return(do.call(cbind,ls.I))
} |
expected <- eval(parse(text="c(1, 42, 43, 83, 84, 124, 125, 166)"));
test(id=0, code={
argv <- eval(parse(text="list(c(1, 42, 83, 124, 166, 43, 84, 125), FALSE)"));
.Internal(`qsort`(argv[[1]], argv[[2]]));
}, o=expected); |
test_that("ungrouped data collected first", {
out <- memdb_frame(x = 1:2) %>% do(head(.))
expect_equal(out, tibble(x = 1:2))
})
test_that("named argument become list columns", {
mf <- memdb_frame(
g = rep(1:3, 1:3),
x = 1:6
) %>% group_by(g)
out <- mf %>% do(nrow = nrow(.), ncol = ncol(.))
expect_equal(out$nrow, list(1, 2, 3))
expect_equal(out$ncol, list(2, 2, 2))
})
test_that("unnamed results bound together by row", {
mf <- memdb_frame(
g = c(1, 1, 2, 2),
x = c(3, 9, 4, 9)
) %>% group_by(g)
first <- mf %>% do(head(., 1))
expect_equal_tbl(first, tibble(g = c(1, 2), x = c(3, 4)))
})
test_that("Results respect select", {
mf <- memdb_frame(
g = c(1, 1, 2, 2),
x = c(3, 9, 4, 9),
y = 1:4,
z = 4:1
) %>% group_by(g)
expect_message(out <- mf %>% select(x) %>% do(ncol = ncol(.)))
expect_equal(out$g, c(1, 2))
expect_equal(out$ncol, list(2L, 2L))
})
test_that("results independent of chunk_size", {
mf <- memdb_frame(
g = rep(1:3, 1:3),
x = 1:6
) %>% group_by(g)
nrows <- function(group, n) {
unlist(do(group, nrow = nrow(.), .chunk_size = n)$nrow)
}
expect_equal(nrows(mf, 1), c(1, 2, 3))
expect_equal(nrows(mf, 2), c(1, 2, 3))
expect_equal(nrows(mf, 10), c(1, 2, 3))
}) |
print.classified_image <- function(x, digits = NULL, quote = TRUE,
na.print = NULL, print.gap = NULL,
right = FALSE, max = NULL, useSource = TRUE,
...){
for (item in seq(1, length(x)- 1)){
cat('\nCategory name: "', names(x)[item], '"\n')
cat('Colour (as RGB [0:255] values): (',
round(x[[item]]$colour[1,1]*255), ', ',
round(x[[item]]$colour[2,1]*255), ', ',
round(x[[item]]$colour[3,1]*255), ')\n',
sep = '')
cat(x$summary[[item]], '\n')
}
cat(x$summary[[length(x)]], '\n')
} |
[
{
"title": "Subjective Ways of Cutting a Continuous Variables",
"href": "http://freakonometrics.hypotheses.org/18160"
},
{
"title": "Blogging about R – presentation and audio",
"href": "https://www.r-statistics.com/2010/07/blogging-about-r-presentation-and-audio/"
},
{
"title": "Opening Up Access to Data: Why APIs May Not Be Enough…",
"href": "https://blog.ouseful.info/2014/08/11/opening-up-access-to-data-why-apis-may-not-be-enough/"
},
{
"title": "Googling Bayes’ pictures",
"href": "https://statisfaction.wordpress.com/2011/09/29/googling-bayes-pictures/"
},
{
"title": "Creating Interactive Plots with R and Highcharts",
"href": "https://www.rstudio.com/rviews/2016/10/19/creating-interactive-plots-with-r-and-highcharts/"
},
{
"title": "Data Mining the California Solar Statistics with R: Part V",
"href": "http://www.beyondmaxwell.com/?p=223"
},
{
"title": "Using R — .Call(“hello”)",
"href": "http://mazamascience.com/WorkingWithData/?p=1099"
},
{
"title": "Example 2015.1: Time to refinance?",
"href": "https://feedproxy.google.com/~r/SASandR/~3/VC8dyPiL-hg/example-20151-time-to-refinance.html"
},
{
"title": "sab-R-metrics: Kernel Density Smoothing",
"href": "http://princeofslides.blogspot.com/2011/05/sab-r-metrics-kernel-density-smoothing.html"
},
{
"title": "It’s a Batsman’s World (Cup)",
"href": "https://feedproxy.google.com/~r/graphoftheweek/fzVA/~3/nkyFklCnBF8/its-batsmans-world-cup.html"
},
{
"title": "Area Plots with Intensity Coloring ~ el nino SST anomalies w/ ggplot2",
"href": "https://probabilitynotes.wordpress.com/2010/07/10/area-plots-with-intensity-coloring-el-nino-sst-anomalies-w-ggplot2/"
},
{
"title": "An easy way to manage your genome-wide-association data: GenABEL package.",
"href": "http://www.milanor.net/blog/an-easy-way-to-manage-your-genome-wide-association-data-genabel-package/"
},
{
"title": "Comparing performance in R, foreach/doSNOW, SAS, and NumPY (MKL)",
"href": "http://statsadventure.blogspot.com/2012/06/comparing-performance-in-r.html"
},
{
"title": "Making inferences about unusual population quantities.",
"href": "http://biostatmatt.com/archives/2604"
},
{
"title": "New visualization of the distribution of p-values using d3.js",
"href": "http://rpsychologist.com/new-d3-js-visualization-p-curve-distribution"
},
{
"title": "%EXPORT_TO_R SAS Macro Code",
"href": "http://econometricsense.blogspot.com/2011/05/exporttor-sas-macro-code.html"
},
{
"title": "Improving R Data Visualisations Through Design",
"href": "http://spatial.ly/2014/11/r-visualisations-design/"
},
{
"title": "R style tip: prefer functions that return data frames",
"href": "http://www.win-vector.com/blog/2014/06/r-style-tip-prefer-functions-that-return-data-frames/?utm_source=rss&utm_medium=rss&utm_campaign=r-style-tip-prefer-functions-that-return-data-frames"
},
{
"title": "Simulation and resampling",
"href": "https://quantsignals.wordpress.com/2012/06/20/simulation-and-resampling/"
},
{
"title": "nnet2sas() supports centering and scaling",
"href": "https://heuristically.wordpress.com/2012/10/04/nnet2sas-supports-centering-and-scaling/"
},
{
"title": "Loading Historical Stock Data",
"href": "https://systematicinvestor.wordpress.com/2013/06/01/loading-historical-stock-data/"
},
{
"title": "Bayesian statistics and clinical trial conclusions: Why the OPTIMSE study should be considered positive",
"href": "http://www.datasurg.net/2015/02/16/bayesian-statistics-and-clinical-trial-conclusions-why-the-optimse-study-should-be-considered-positive/"
},
{
"title": "A first lambda function with C++11 and Rcpp",
"href": "http://gallery.rcpp.org/articles/simple-lambda-func-c++11/"
},
{
"title": "Passing arguments to an R script from command lines",
"href": "http://tuxette.nathalievilla.org/?p=1696"
},
{
"title": "R jobs (May 19th 2014)",
"href": "https://www.r-bloggers.com/r-jobs-may-19th-2014/"
},
{
"title": "A different way to view probability densities",
"href": "http://www.statisticsblog.com/2010/06/a-different-way-to-view-probability-densities/"
},
{
"title": "PLS Path Modeling with R",
"href": "https://gastonsanchez.wordpress.com/2013/01/04/pls-path-modeling-with-r/"
},
{
"title": "Machine Learning Ex 5.1 – Regularized Linear Regression",
"href": "https://web.archive.org/web/http://ygc.name/2011/10/25/machine-learning-5-1-regularized-linear-regression/"
},
{
"title": "Descriptive Analytics – Part 0 : data exploration",
"href": "http://r-exercises.com/2016/10/19/descriptive-analytics-part-0-data-exploration/"
},
{
"title": "Recology is 1 yr old…",
"href": "https://r-ecology.blogspot.com/2011/12/recology-is-1-yr-old.html"
},
{
"title": "Experimenting With iGraph – and a Hint Towards Ways of Measuring Engagement?",
"href": "https://blog.ouseful.info/2012/01/27/experimenting-with-igraph-and-a-hint-towards-ways-of-measuring-engagement/"
},
{
"title": "How Fantasy Football is Like Stock Picking (Including a Shiny App)",
"href": "http://fantasyfootballanalytics.net/2015/03/fantasy-football-is-like-stock-picking.html"
},
{
"title": "Get those plots",
"href": "http://dancingeconomist.blogspot.com/2011/08/get-those-plots.html"
},
{
"title": "project euler – Problem 31",
"href": "https://web.archive.org/web/http://ygc.name/2011/11/08/project-euler-problem-31/"
},
{
"title": "The R Journal, Volume 8/1, August 2016 – is online!",
"href": "https://www.r-bloggers.com/the-r-journal-volume-81-august-2016-is-online/"
},
{
"title": "How to write the first for loop in R",
"href": "http://datascienceplus.com/how-to-write-the-loop-in-r/"
},
{
"title": "\"R\" : Identifying peaks",
"href": "http://nir-quimiometria.blogspot.com/2012/12/r-identifying-peaks.html"
},
{
"title": "R package building automation",
"href": "http://mkao006.blogspot.com/2013/02/r-package-building-automation.html"
},
{
"title": "Running R on the iPad",
"href": "http://blog.revolutionanalytics.com/2010/09/running-r-on-the-ipad.html"
},
{
"title": "Example 9.17: (much) better pairs plots",
"href": "https://feedproxy.google.com/~r/SASandR/~3/pU_HNl9T2cY/example-917-much-better-pairs-plots.html"
},
{
"title": "Showing explained variance from multilevel models",
"href": "https://feedproxy.google.com/~r/danielmarcelino/~3/fUqV2TtdOmw/"
},
{
"title": "“R for Developers” free web-book: leave your opinion",
"href": "http://www.milanor.net/blog/r-for-developers-free-web-book-leave-your-opinion/"
},
{
"title": "Simple example:How to use foreach and doSNOW packages for parallel computation.",
"href": "http://mockquant.blogspot.com/2011/02/simple-examplehow-to-use-foreach-and.html"
},
{
"title": "xts object – subscript out of bounds",
"href": "http://www.copula.de/2013/02/xts-object-subscription-out-of-bounds.html"
},
{
"title": "Job Search Part 4: Timing Beveridge Curve Movements During A Recession",
"href": "http://dancingeconomist.blogspot.com/2011/04/job-search-part-4-timing-beveridge.html"
},
{
"title": "How to install R packages on an off-line SQL Server 2016 instance",
"href": "http://blog.revolutionanalytics.com/2016/05/minicran-sql-server.html"
},
{
"title": "What can be in an R data.frame column?",
"href": "http://www.win-vector.com/blog/2015/04/what-can-be-in-an-r-data-frame-column/"
},
{
"title": "Flowers/Fractals",
"href": "http://ww1.danielmarcelino.com/flowersfractals/"
},
{
"title": "The Gambling Machine Puzzle",
"href": "https://bayesianbiologist.com/2013/03/09/the-gambling-machine-puzzle/"
},
{
"title": "A terrible 2000 words",
"href": "http://val-systems.blogspot.com/2012/03/terrible-2000-words.html"
}
] |
decompLines <- function(VL, debug = 0) {
comp <- getComp(VL, debug = debug)
lineNames <- names(VL)
if (is.null(lineNames)) lineNames <- paste("Line", 1:length(VL), sep = "_")
if (debug >= 4L) {
cat("\n\n\n==================== Raw lines:\n\n")
print(VL)
}
nameComp <- function(cvec) {
names(cvec) <- rep(NA_character_, length(cvec))
names(cvec)[grepl("[@A-Ia-i]{1}", cvec)] <- "SQZ"
names(cvec)[grepl("[%J-Rj-r]{1}", cvec)] <- "DIF"
names(cvec)[grepl("[S-Zs]{1}", cvec)] <- "DUP"
names(cvec)[!grepl("[@%A-Za-rs]", cvec)] <- "NUM"
cvec
}
VL <- gsub(",", ".", VL)
VL <- gsub("\\s+\\${2}.*$", "", VL)
VL <- gsub("(\\+|-){1}([0-9]+)", " \\1\\2", VL)
VL <- str_trim(VL, side = "both")
VL <- str_replace_all(VL, "([@%A-Za-rs])", " \\1")
lineList <- as.list(VL)
names(lineList) <- lineNames
FUN <- function(x) {
unlist(strsplit(x, "\\s+"))
}
lineList <- lapply(lineList, FUN)
lineList <- lapply(lineList, nameComp)
if (debug >= 4L) {
cat("\n\n\n==================== Lines after preliminary processing:\n\n")
print(lineList)
DF1 <- lengths(lineList)
DF2 <- cumsum(lengths(lineList))
}
if ("SQZ" %in% comp) lineList <- lapply(lineList, unSQZ)
if (debug >= 4L) {
DF3 <- lengths(lineList)
DF4 <- cumsum(lengths(lineList))
}
if ("DUP" %in% comp) lineList <- lapply(lineList, insertDUPs, debug = debug)
if (debug >= 4L) {
DF5 <- lengths(lineList)
DF6 <- cumsum(lengths(lineList))
}
if ("DIF" %in% comp) lineList <- lapply(names(lineList), deDIF, lineList = lineList, debug = debug)
if (debug >= 4L) {
DF7 <- lengths(lineList)
DF8 <- cumsum(lengths(lineList))
}
names(lineList) <- lineNames
if (("DIF" %in% comp) & (length(lineList) > 1)) lineList <- yValueCheck(lineList, debug = debug)
if (debug >= 4L) {
DF9 <- lengths(lineList)
DF10 <- cumsum(lengths(lineList))
}
if (!is.numeric(lineList)) lineList <- lapply(lineList, as.numeric)
if (debug >= 4L) {
DF11 <- lengths(lineList)
DF12 <- cumsum(lengths(lineList))
DF13 <- cumsum(lengths(lineList) - 1)
}
if (debug >= 4L) {
cat("\n\n\n==================== Lines after full processing to numeric:\n\n")
print(lineList)
}
lineList
} |
library(oce)
data(sealevel)
rms <- function(x) sqrt(mean(x^2, na.rm=TRUE))
standard <- c("Z0", "SA", "SSA", "MSM", "MM", "MSF", "MF", "ALP1", "2Q1", "SIG1", "Q1", "RHO1", "O1", "TAU1", "BET1",
"NO1", "CHI1", "PI1", "P1", "S1", "K1", "PSI1", "PHI1", "THE1", "J1", "SO1", "OO1", "UPS1", "OQ2", "EPS2",
"2N2", "MU2", "N2", "NU2", "GAM2", "H1", "M2", "H2", "MKS2", "LDA2", "L2", "T2", "S2", "R2", "K2", "MSN2",
"ETA2", "MO3", "M3", "SO3", "MK3", "SK3", "MN4", "M4", "SN4", "MS4", "MK4", "S4", "SK4", "2MK5", "2SK5",
"2MN6", "M6", "2MS6", "2MK6", "2SM6", "MSK6", "3MK7", "M8")
unresolvable <- c("SA", "PI1", "S1", "PSI1", "GAM2", "H1", "H2", "T2", "R2")
resolvable <- standard[!(standard %in% unresolvable)]
test_that("invalid constituent name is detected", {
expect_error(m <- tidem(sealevel, constituents="unknown"),
"'unknown' is not a known tidal constituent")
expect_silent(m <- tidem(sealevel, constituents=c("M2", "S2")))
expect_output(summary(m, constituent="M2"), "Call:")
expect_output(
expect_warning(
summary(m, constituent=c("M2", "unknown")),
"the following constituents are not handled: 'unknown'"),
"Call:")
expect_warning(
expect_error(
summary(m, constituent="unknown"),
"no known constituents were provided"),
"the following constituents are not handled: 'unknown'")
})
test_that("tidemAstron() agrees with T_TIDE", {
ctime <- numberAsPOSIXct(721574.000000, "matlab")
a <- tidemAstron(ctime)
expect_equal(a$astro, c(-0.02166309284298506554, 0.39911836945395862131, 0.37745527661097355576,
0.47352449224491977020, 0.34168253766652512127, 0.78477994483145496751))
expect_equal(a$ader, c(0.96613680796658762961, 0.03660110133318876524, 0.00273790929977641003,
0.00030945458977503856, 0.00014709398916752078, 0.00000013079800385981))
})
test_that("tidemVuf() agrees with T_TIDE", {
t <- numberAsPOSIXct(721574, "matlab")
latitude <- 69.45
j <- c(5, 6, 8, 9, 11, 13, 16, 21, 25, 28, 29, 35, 40, 42, 48, 54, 57, 61, 68, 69, 72, 74, 79, 82, 84, 86, 89,
96, 99, 103, 106, 110, 113, 120, 125, 138, 19, 59)
a <- tidemVuf(t, j, latitude)
expect_equal(a$v, c(-0.07440612279096114889, 0.04332618568597013109, -0.63970152519195266905,
-0.52196921671502138906, -0.59637533950598253796, -0.67078146229694368685,
-0.29813860059806529534, -0.37254472338902644424, -0.44695084617998759313,
0.42569201551889079838, 0.35128589272792964948, -0.01224624858097911329,
-0.08665237137194026218, 0.03107993710499101780, -0.04332618568597013109,
-0.61773230847693127998, 0.00000000000000000000, 0.68050443043098596263,
-0.71410764798291381794, -0.56498927852895519663, -0.41587090907499657533,
-0.37254472338902644424, -0.01224624858097911329, -0.08665237137194026218,
0.03107993710499101780, -0.04332618568597013109, 0.00000000000000000000,
-0.45919709476096670642, -0.37254472338902644424, -0.05557243426694924437,
-0.12997855705791039327, -0.08665237137194026218, -0.04332618568597013109,
-0.50252328044693683751, -0.17330474274388052436, -0.21663092842985065545,
-0.62745527661097355576, 0.75491055322194711152))
expect_equal(a$u, c(0.00000000000000000000, 0.00000000000000000000, -0.03573008103828116677,
-0.04105661783571373097, -0.03475014441038941360, -0.02928112201045270438,
0.07260401446848122053, 0.02260949305395914405, 0.04956689861642670641,
0.09891859169703924592, 0.10028458991622789254, -0.00902641325023753431,
0.00128510133444835950, 0.00461061249607315829, 0.00541437304622621740,
0.00274046290575439633, -0.00026092506352816142, 0.09392399576847017262,
-0.02386674896422648698, 0.00729820833418420335, 0.02802386610018536145,
0.02234856799043098349, 0.01002498554229937569, 0.01082874609245243480,
0.00434968743254499687, 0.00515344798269805598, -0.00052185012705632285,
0.03343823914641157885, 0.02208764292690282294, 0.01543935858852559309,
0.01624311913867865220, 0.01056782102892427425, 0.00489252291916989455,
0.03885261219263779625, 0.02165749218490486960, 0.02707186523113108700,
0.00157989768140298702, 0.04412567730772318231))
expect_equal(a$f, c(1.00000000000000000000, 1.00000000000000000000, 0.92726669518607429676,
0.91876560270792528851, 0.91361514379815111919, 0.90841044913845236941,
1.31039292751104730073, 0.94730126197164676860, 0.92467374922680412030,
0.87279495125656747501, 0.78090694856929177003, 1.02141844783349333703,
1.02063321935769968363, 1.02290604140805219124, 1.02102357214471095581,
0.81679072125951690531, 0.99893775156306297003, 0.82805626744653082483,
0.92750848175292388564, 1.03180699580911316993, 0.96721691839548340486,
0.94629499268680894453, 1.04441118036685498538, 1.04248913487514571763,
1.02181946106443310995, 1.01993899145112432159, 0.99787663149786776096,
0.98755127305895584744, 0.94528979230994603089, 1.06636843416604021328,
1.06440598041227074688, 1.04138175242110064822, 1.01885556285168443758,
1.00831312849471199655, 1.08678359633272991758, 1.10963166967591941869,
1.00475518907274086189, 0.86273520229848033036))
})
test_that("tidem constituents match previous versions", {
expect_output(m <- tidem(sealevel), "the tidal record is too short to fit for constituents")
nameExpected <- c("Z0", "SSA", "MSM", "MM", "MSF", "MF", "ALP1", "2Q1", "SIG1", "Q1", "RHO1", "O1", "TAU1",
"BET1", "NO1", "CHI1", "P1", "K1", "PHI1", "THE1", "J1", "SO1", "OO1", "UPS1", "OQ2",
"EPS2", "2N2", "MU2", "N2", "NU2", "M2", "MKS2", "LDA2", "L2", "S2", "K2", "MSN2", "ETA2",
"MO3", "M3", "SO3", "MK3", "SK3", "MN4", "M4", "SN4", "MS4", "MK4", "S4", "SK4", "2MK5",
"2SK5", "2MN6", "M6", "2MS6", "2MK6", "2SM6", "MSK6", "3MK7", "M8")
expect_equal(m[["name"]], nameExpected)
amplitudeExpected <- c(0.981726026948275, 0.0231120676250417, 0.00140006225693582, 0.00663853819693045,
0.00745395229071014, 0.0108423130558645, 0.00446157918446234, 0.00281566910578963,
0.00500528298165795, 0.00225633758542224, 0.00687335963931585, 0.0445580351701794,
0.00752399221873183, 0.00196300749657538, 0.00597938799085181, 0.00203819136867481,
0.0284640561578009, 0.0999180418904084, 0.00178914911263196, 0.00362251100068132,
0.00537919967694433, 0.00160359553803719, 0.00379934676589881, 0.00171255305464996,
0.00216847454896681, 0.00571278901124493, 0.0187693769736588, 0.016022726878358,
0.137842580014825, 0.0256601572406377, 0.603079326697343, 0.00133915747473446,
0.00876240589152753, 0.0217222462387855, 0.125778285527591, 0.0349926762754095,
0.00220982903284968, 0.00083893864415224, 0.00130054650555345, 0.00140741431875248,
0.0010408092076497, 0.00255136537688709, 0.0030861879324414, 0.0163623512074873,
0.0375601328413247, 0.00436099955739125, 0.0186294733631031, 0.00453447632254121,
0.00359043859975019, 0.000797758792921601, 0.00214528113087127, 0.00101597759514933,
0.00359973331843245, 0.00534334123140572, 0.00273724213778086, 0.00103718497501477,
0.000957878360945973, 0.000475127236372995, 0.00114864012363512, 0.000342820770777957)
expect_equal(m[["amplitude"]], amplitudeExpected)
phaseExpected <- c(0, 206.139498607823, 272.254674100838, 198.978271969872, 217.9167254883, 340.144074327625,
267.62317978639, 207.078413795351, 101.464421527257, 65.5357202442784, 342.302188914025,
96.2458456476212, 238.605269178581, 236.76128576666, 129.983948949739, 324.497774422381,
119.927278917839, 120.487940952987, 233.836931342051, 62.979342886154, 147.439067140747,
284.820518391198, 120.570371868767, 187.212410971879, 13.0043721493048, 331.840534847604,
310.626542816525, 333.717321201237, 330.236927471862, 328.051268922409, 350.368725117048,
328.535205043259, 3.00739883479745, 342.78169723488, 24.0579944118162, 19.431341600067,
268.869845196679, 43.2013207892101, 197.315487664139, 240.016324425789, 260.382546065061,
298.590107017218, 83.2822727979654, 220.098055909548, 270.047584648956, 2.35078120331345,
48.4371100114011, 53.3159599661074, 208.043855367935, 193.84737099018, 21.3566757362311,
236.164405145889, 114.684391797473, 118.84782486352, 161.303558539216, 169.886911046411,
233.604836704444, 283.264844300455, 107.186639217795, 8.34416515384646)
expect_equal(m[["phase"]], phaseExpected)
expect_equal(fivenum(predict(m)), c(0.02920363602, 0.59938759547, 0.97986651174, 1.38237184987,
1.93382321126))
})
test_that("prediction works with newdata and without newdata", {
expect_output(
m <- tidem(sealevel),
"the tidal record is too short to fit for constituents")
p1 <- predict(m)
p2 <- predict(m, newdata=sealevel[["time"]])
expect_equal(p1, p2)
})
test_that("tailoring of constituents", {
tide3 <- tidem(sealevel, constituents = c("M2", "K2"))
expect_equal(tide3[["data"]]$name, c("M2", "K2"))
expect_output(tide5 <- tidem(sealevel, constituents = c("standard", "-M2")),
"the tidal record is too short to fit for constituents")
expect_equal(tide5[["data"]]$name, resolvable[resolvable != "M2"])
})
test_that("Foreman (1977 App 7.3) and T-TIDE (Pawlowciz 2002 Table 1) test", {
foreman <- read.table("tide_foreman.dat.gz", header=TRUE, stringsAsFactors=FALSE)
ttide <- read.table("tide_ttide.dat.gz", skip=9, header=TRUE, stringsAsFactors=FALSE)
ttide$name <- gsub("^MS$", "M8", gsub("^UPSI$", "UPS1", ttide$name))
expect_equal(ttide$name, foreman$name)
expect_equal(ttide$frequency, foreman$frequency, tolerance=3e-5)
data("sealevelTuktoyaktuk")
expect_output(
m <- tidem(sealevelTuktoyaktuk, constituents=c("standard", "M10"),
infer=list(name=c("P1", "K2"),
from=c("K1", "S2"),
amp=c(0.33093, 0.27215),
phase=c(-7.07, -22.40))),
"the tidal record is too short to fit for constituents")
expect_equal(foreman$name, ttide$name)
expect_equal(foreman$freq, ttide$frequency, tolerance=3e-5)
expect_equal(foreman$name, m@data$name)
expect_equal(foreman$frequency, m@data$freq, tolerance=1e-7)
expect_equal(0.33093,
m[["amplitude"]][which(m[["name"]]=="P1")]/m[["amplitude"]][which(m[["name"]]=="K1")])
expect_equal(m[["phase"]][which(m[["name"]]=="P1")],
m[["phase"]][which(m[["name"]]=="K1")]-(-7.07))
expect_equal(0.27215,
m[["amplitude"]][which(m[["name"]]=="K2")]/m[["amplitude"]][which(m[["name"]]=="S2")])
expect_equal(m[["phase"]][which(m[["name"]]=="K2")],
m[["phase"]][which(m[["name"]]=="S2")]-(-22.40))
expect_equal(sum(abs(ttide$amplitude - round(m[["amplitude"]], 4))), 0)
expect_equal(sum(abs(ttide$phase - round(m[["phase"]], 2))), 0)
expect_lt(max(abs(foreman$A - ttide$amplitude)), 0.000201)
expect_lt(max(abs(foreman$G - ttide$phase)), 0.121)
}
) |
context("Scoring a DSM object")
library(wordspace)
library(Matrix)
expect_matrix_equal <- function(x, y, tol=1e-6, note="", note1=note, note2=note) {
name.x <- deparse(substitute(x))
name.y <- deparse(substitute(y))
expect_equal(dim(x), dim(y),
label=sprintf("dim(%s)%s", name.x, note1),
expected.label=sprintf("dim(%s)%s", name.y, note2))
x <- as.matrix(x)
y <- as.matrix(y)
expect_equivalent(x, y, tolerance=tol,
label=paste0(name.x, note1),
expected.label=paste0(name.y, note2))
}
M <- DSM_HieroglyphsMatrix
M.dsm <- dsm(M, raw.freq=TRUE)
f1 <- rowSums(M)
f2 <- colSums(M)
N <- sum(M)
M.exp <- outer(f1, f2) / N
test_that("marginal and expected frequencies are correct", {
expect_equivalent(f1, M.dsm$rows$f)
expect_equivalent(f2, M.dsm$cols$f)
expect_matrix_equal(N, M.dsm$globals$N)
})
f <- M
f.dsm <- dsm.score(M.dsm, score="frequency", matrix.only=TRUE)
MI <- pmax(log2(M / M.exp), 0)
MI.dsm <- dsm.score(M.dsm, score="MI", matrix.only=TRUE)
t <- ifelse(M >= M.exp, (M - M.exp) / sqrt(M), 0)
t.dsm <- dsm.score(M.dsm, score="t-score", matrix.only=TRUE)
tsqrt.dsm <- dsm.score(M.dsm, score="t-score", transform="root", matrix.only=TRUE)
tlog.dsm <- dsm.score(M.dsm, score="t-score", transform="log", matrix.only=TRUE)
test_that("simple AMs and transformations are correct", {
expect_matrix_equal(f, f.dsm)
expect_matrix_equal(MI, MI.dsm)
expect_matrix_equal(t, t.dsm)
expect_matrix_equal(sqrt(t), tsqrt.dsm)
expect_matrix_equal(log(t+1), tlog.dsm)
})
M.R1 <- outer(f1, rep(1, ncol(M)))
M.R2 <- N - M.R1
M.C1 <- outer(rep(1, nrow(M)), f2)
M.C2 <- N - M.C1
M.O11 <- M
M.O12 <- M.R1 - M.O11
M.O21 <- M.C1 - M.O11
M.O22 <- M.C2 - M.O12
M.E11 <- M.R1 * M.C1 / N
M.E12 <- M.R1 * M.C2 / N
M.E21 <- M.R2 * M.C1 / N
M.E22 <- M.R2 * M.C2 / N
G2 <- 2 * (
ifelse(M.O11 > 0, M.O11 * log(M.O11 / M.E11), 0) +
ifelse(M.O12 > 0, M.O12 * log(M.O12 / M.E12), 0) +
ifelse(M.O21 > 0, M.O21 * log(M.O21 / M.E21), 0) +
ifelse(M.O22 > 0, M.O22 * log(M.O22 / M.E22), 0)
)
G2.sparse <- ifelse(M.O11 > M.E11, G2, 0)
G2 <- ifelse(M.O11 >= M.E11, G2, -G2)
G2.sparse.dsm <- dsm.score(M.dsm, score="log-likelihood", matrix.only=TRUE)
G2.dsm <- dsm.score(M.dsm, score="log-likelihood", sparse=FALSE, negative.ok=TRUE, matrix.only=TRUE)
X2 <-
N * (abs(M.O11 * M.O22 - M.O12 * M.O21) - N / 2) ^ 2 / (M.R1 * M.R2 * M.C1 * M.C2)
X2.sparse <- ifelse(M.O11 > M.E11, X2, 0)
X2 <- ifelse(M.O11 >= M.E11, X2, -X2)
X2.sparse.dsm <- dsm.score(M.dsm, score="chi-squared", matrix.only=TRUE)
X2.dsm <- dsm.score(M.dsm, score="chi-squared", sparse=FALSE, negative.ok=TRUE, matrix.only=TRUE)
test_that("complex AMs are correct", {
expect_matrix_equal(G2.sparse, G2.sparse.dsm)
expect_matrix_equal(G2, G2.dsm)
expect_matrix_equal(X2.sparse, X2.sparse.dsm)
expect_matrix_equal(X2, X2.dsm)
})
S <- as(M, "sparseMatrix")
stopifnot(dsm.is.canonical(S)$canonical && dsm.is.canonical(S)$sparse)
S.dsm <- dsm(S, raw.freq=TRUE)
f.sparse <- dsm.score(S.dsm, score="frequency", matrix.only=TRUE)
MI.sparse <- dsm.score(S.dsm, score="MI", matrix.only=TRUE)
t.sparse <- dsm.score(S.dsm, score="t-score", matrix.only=TRUE)
tsqrt.sparse <- dsm.score(S.dsm, score="t-score", transform="root", matrix.only=TRUE)
tlog.sparse <- dsm.score(S.dsm, score="t-score", transform="log", matrix.only=TRUE)
G2.sparse.Sdsm <- dsm.score(S.dsm, score="log-likelihood", matrix.only=TRUE)
X2.sparse.Sdsm <- dsm.score(S.dsm, score="chi-squared", matrix.only=TRUE)
test_that("sparse AMs are identical on sparse matrix", {
expect_is(f.sparse, "sparseMatrix")
expect_matrix_equal(as.matrix(f.sparse), f.dsm)
expect_is(MI.sparse, "sparseMatrix")
expect_matrix_equal(as.matrix(MI.sparse), MI.dsm)
expect_is(t.sparse, "sparseMatrix")
expect_matrix_equal(as.matrix(t.sparse), t.dsm)
expect_is(tsqrt.sparse, "sparseMatrix")
expect_matrix_equal(as.matrix(tsqrt.sparse), tsqrt.dsm)
expect_is(tlog.sparse, "sparseMatrix")
expect_matrix_equal(as.matrix(tlog.sparse), tlog.dsm)
expect_is(G2.sparse.Sdsm, "sparseMatrix")
expect_matrix_equal(as.matrix(G2.sparse.Sdsm), G2.sparse)
expect_is(X2.sparse.Sdsm, "sparseMatrix")
expect_matrix_equal(as.matrix(X2.sparse.Sdsm), X2.sparse)
})
G2.nz.dsm <- dsm.score(M.dsm, score="log-likelihood", sparse=FALSE, negative.ok="nonzero", matrix.only=TRUE)
X2.nz.dsm <- dsm.score(M.dsm, score="chi-squared", sparse=FALSE, negative.ok="nonzero", matrix.only=TRUE)
G2.nz <- ifelse(M.O11 > 0, G2, 0)
G2.nz.Sdsm <- dsm.score(S.dsm, score="log-likelihood", sparse=FALSE, negative.ok="nonzero", matrix.only=TRUE)
X2.nz <- ifelse(M.O11 > 0, X2, 0)
X2.nz.Sdsm <- dsm.score(S.dsm, score="chi-squared", sparse=FALSE, negative.ok="nonzero", matrix.only=TRUE)
test_that("pseudo-sparse AMs are computed correctly", {
expect_matrix_equal(G2.nz.dsm, G2)
expect_matrix_equal(X2.nz.dsm, X2)
expect_matrix_equal(as.matrix(G2.nz.Sdsm), G2.nz)
expect_matrix_equal(as.matrix(X2.nz.Sdsm), X2.nz)
})
tsqrt.std <- scale(sqrt(t))
tsqrt.std.dsm <- dsm.score(M.dsm, score="t-score", transform="root", scale="standardize", matrix.only=TRUE)
test_that("column standardization works", {
expect_equivalent(apply(tsqrt.std.dsm, 2, mean), rep(0, ncol(M)))
expect_equivalent(apply(tsqrt.std.dsm, 2, sd), rep(1, ncol(M)))
expect_matrix_equal(tsqrt.std.dsm, tsqrt.std)
})
tsqrt.scale <- scale(sqrt(t), center=FALSE)
tsqrt.scale.dsm <- dsm.score(M.dsm, score="t-score", transform="root", scale="scale", matrix.only=TRUE)
rms <- function (x) sqrt(sum(x * x) / (length(x) - 1))
test_that("column scaling works", {
expect_equivalent(apply(tsqrt.scale.dsm, 2, rms), rep(1, ncol(M)))
expect_matrix_equal(tsqrt.scale.dsm, tsqrt.scale)
})
tsqrt.scale.sparse <- dsm.score(S.dsm, score="t-score", transform="root", scale="scale", matrix.only=TRUE)
test_that("column scaling works for sparse matrix, too", {
expect_equivalent(apply(tsqrt.scale.sparse, 2, rms), rep(1, ncol(M)))
expect_matrix_equal(as.matrix(tsqrt.scale.sparse), tsqrt.scale)
})
tsqrt.norm <- sqrt(t) / rowSums(abs(sqrt(t)))
tsqrt.norm.dsm <- dsm.score(M.dsm, score="t-score", transform="root", normalize=TRUE, method="manhattan", matrix.only=TRUE)
tsqrt.norm.sparse <- dsm.score(S.dsm, score="t-score", transform="root", normalize=TRUE, method="manhattan", matrix.only=TRUE)
test_that("row normalization works", {
expect_matrix_equal(tsqrt.norm.dsm, tsqrt.norm)
expect_matrix_equal(as.matrix(tsqrt.norm.sparse), tsqrt.norm)
})
my.MI <- function (O11, E11, ...) log2(O11 / E11)
my.tscore <- function (O, E, ...) (O - E) / sqrt(O)
my.tscore.disc <- function (O, E, ...) (O - E) / sqrt(O + 1)
my.Dice <- function (O11, R1, C1, ...) 2 * O11 / (R1 + C1)
my.ll <- function (O, E, ...) {
ll <- 2 * (ifelse(O > 0, O * log(O / E), 0) - (O - E))
ifelse(O >= E, ll, -ll)
}
my.G2 <- function (O11, O12, O21, O22, E11, E12, E21, E22, ...) {
ll <- ifelse(O11 > 0, O11 * log(O11 / E11), 0) +
ifelse(O12 > 0, O12 * log(O12 / E12), 0) +
ifelse(O21 > 0, O21 * log(O21 / E21), 0) +
ifelse(O22 > 0, O22 * log(O22 / E22), 0)
ifelse(O11 >= E11, 2 * ll, -2 * ll)
}
my.tfidf <- function (O11, cols, ..., K=7) O11 * log(1 / cols$df)
TT <- DSM_TermTerm
TT$cols <- transform(TT$cols, df=((nnzero + 1) / (nrow(TT) + 1)))
TC <- DSM_TermContext
TC$cols <- transform(TC$cols, df=((nnzero + 1) / (nrow(TC) + 1)))
test.AM <- function(model, AM.name, AM.fun, transform="none", sparse=TRUE, negative.ok=!sparse, force.dense=FALSE) {
built.in <- dsm.score(model, AM.name, transform=transform, sparse=sparse, negative.ok=negative.ok, matrix.only=TRUE)
user.defined <- dsm.score(model, AM.fun, transform=transform, sparse=sparse, negative.ok=negative.ok, matrix.only=TRUE, batchsize=10)
if (force.dense) built.in <- as.matrix(built.in)
label <- sprintf(" (%s%s%s)",
if (transform == "none") "" else paste0(transform, " "),
AM.name,
if (sparse) if (negative.ok == "nonzero") ", pseudo-sparse" else ", sparse" else "")
expect_equal(class(user.defined), class(built.in))
expect_matrix_equal(user.defined, built.in, note2=label)
}
test_that("user-defined AM match built-in AM (dense matrix, sparse AM)", {
test.AM(TT, "MI", my.MI)
test.AM(TT, "t-score", my.tscore)
test.AM(TT, "Dice", my.Dice)
test.AM(TT, "simple-ll", my.ll)
test.AM(TT, "log-likelihood", my.G2)
test.AM(TT, "tf.idf", my.tfidf)
test.AM(TT, "simple-ll", my.ll, transform="log")
test.AM(TT, "simple-ll", my.ll, transform="root")
test.AM(TT, "simple-ll", my.ll, transform="sigmoid")
})
test_that("user-defined AM match built-in AM (dense matrix, dense AM)", {
test.AM(TT, "MI", my.MI, sparse=FALSE)
test.AM(TT, "t-score", my.tscore.disc, sparse=FALSE)
test.AM(TT, "Dice", my.Dice, sparse=FALSE)
test.AM(TT, "simple-ll", my.ll, sparse=FALSE)
test.AM(TT, "log-likelihood", my.G2, sparse=FALSE)
test.AM(TT, "tf.idf", my.tfidf, sparse=FALSE)
test.AM(TT, "simple-ll", my.ll, transform="log", sparse=FALSE)
test.AM(TT, "simple-ll", my.ll, transform="root", sparse=FALSE)
test.AM(TT, "simple-ll", my.ll, transform="sigmoid", sparse=FALSE)
})
test_that("user-defined AM match built-in AM (sparse matrix, sparse AM)", {
test.AM(TC, "MI", my.MI)
test.AM(TC, "t-score", my.tscore)
test.AM(TC, "Dice", my.Dice)
test.AM(TC, "simple-ll", my.ll)
test.AM(TT, "log-likelihood", my.G2)
test.AM(TC, "tf.idf", my.tfidf)
test.AM(TC, "simple-ll", my.ll, transform="log")
test.AM(TC, "simple-ll", my.ll, transform="root")
test.AM(TC, "simple-ll", my.ll, transform="sigmoid")
})
test_that("user-defined AM match built-in AM (sparse matrix, dense AM)", {
test.AM(TC, "MI", my.MI, sparse=FALSE)
test.AM(TC, "t-score", my.tscore.disc, sparse=FALSE)
test.AM(TC, "Dice", my.Dice, sparse=FALSE, force.dense=TRUE)
test.AM(TC, "simple-ll", my.ll, sparse=FALSE)
test.AM(TT, "log-likelihood", my.G2, sparse=FALSE)
test.AM(TC, "tf.idf", my.tfidf, sparse=FALSE, force.dense=TRUE)
test.AM(TC, "simple-ll", my.ll, transform="log", sparse=FALSE)
test.AM(TC, "simple-ll", my.ll, transform="root", sparse=FALSE)
test.AM(TC, "simple-ll", my.ll, transform="sigmoid", sparse=FALSE)
})
test_that("user-defined AM match built-in AM (sparse matrix, quasi-sparse AM)", {
test.AM(TC, "MI", my.MI, sparse=FALSE, negative.ok="nonzero")
test.AM(TC, "t-score", my.tscore.disc, sparse=FALSE, negative.ok="nonzero")
test.AM(TC, "Dice", my.Dice, sparse=FALSE, negative.ok="nonzero")
test.AM(TC, "simple-ll", my.ll, sparse=FALSE, negative.ok="nonzero")
test.AM(TT, "log-likelihood", my.G2, sparse=FALSE, negative.ok="nonzero")
test.AM(TC, "tf.idf", my.tfidf, sparse=FALSE, negative.ok="nonzero")
test.AM(TC, "simple-ll", my.ll, transform="log", sparse=FALSE, negative.ok="nonzero")
test.AM(TC, "simple-ll", my.ll, transform="root", sparse=FALSE, negative.ok="nonzero")
test.AM(TC, "simple-ll", my.ll, transform="sigmoid", sparse=FALSE, negative.ok="nonzero")
}) |
'dss222' |
user_agent <- "RAQSAPI library for R"
server <- "AQSDatamartAPI"
checkaqsparams <- function(...)
{
errmessage <- vector()
error <- FALSE
ellipsis_args <- list(...)
names(ellipsis_args) <- names(match.call(expand.dots = FALSE)$...)
if ("parameter" %in% names(ellipsis_args))
{
if (nchar(ellipsis_args$parameter) != 5 |
!is.character(ellipsis_args$parameter) |
!str_detect(ellipsis_args$parameter, "^[:digit:]+$")
)
{
error <- TRUE
errmessage %<>% c('x' =
"parameter must be a 5 digit number (represented as a character string)"
)
}
}
if ("stateFIPS" %in% names(ellipsis_args))
{
if (nchar(ellipsis_args$stateFIPS) != 2 |
!is.character(ellipsis_args$stateFIPS)
)
{
error <- TRUE
errmessage %<>% c('x' =
"stateFIPS must be a two digit number (represented as a character string),
please pad stateFIPS less than 2 digits with leading zeros"
)
}
}
if ("countycode" %in% names(ellipsis_args))
{
if (nchar(ellipsis_args$countycode) != 3 |
!is.character(ellipsis_args$countycode))
{
error <- TRUE
errmessage %<>% c('x' =
"countycode must be a three digit number (represented as a character
string), please pad countycode less than three digits with leading zeros"
)
}
}
if ("sitenum" %in% names(ellipsis_args))
{
if (nchar(ellipsis_args$sitenum) != 4 |
!is.character(ellipsis_args$sitenum))
{
error <- TRUE
errmessage %<>% c('x' =
"sitenum must be a four digit number (represented as a character string),
please pad sitenum less than four digits with leading zeros"
)
}
}
if ("MA_code" %in% names(ellipsis_args))
{
if ((nchar(ellipsis_args$MA_code) != 4 |
nchar(ellipsis_args$MA_code) != 3) |
!is.character(ellipsis_args$MA_code))
{
error <- TRUE
errmessage %<>% c('x' =
"MA_code must be a three or four digit number (represented as a character
string), please pad MA_code less than three or four digits with
leading zeros"
)
}
}
if ("pqao_code" %in% names(ellipsis_args))
{
if ((nchar(ellipsis_args$pqao_code) != 4 |
nchar(ellipsis_args$pqao_code) != 3) |
!is.character(ellipsis_args$pqao_code))
{
error <- TRUE
errmessage %<>% c('x' =
"pqao_code must be a three or four digit number (represented as a
character string), please pad pqao_code less than three or four digits
with leading zeros"
)
}
}
if ("cbsa_code" %in% names(ellipsis_args))
{
if (nchar(ellipsis_args$cbsa_code) != 5 |
!is.character(ellipsis_args$cbsa_code))
{
error <- TRUE
errmessage %<>% c('x' =
"cbsa_code must be a five digit number (represented as a character
string), please pad cbsa_code less than five digits with leading zeros"
)
}
}
if ("POC" %in% names(ellipsis_args))
{
if (nchar(ellipsis_args$POC) != 1 |
!is.character(ellipsis_args$POC))
{
error <- TRUE
errmessage %<>% c('x' =
"POC must be a single digit number (represented as a character string)"
)
}
}
if ("bdate" %in% names(ellipsis_args))
{
if (!is.Date(ellipsis_args$bdate))
{
error <- TRUE
errmessage %<>% c('x' = "bdate must be an R date object")
}
}
if ("edate" %in% names(ellipsis_args))
{
if (!is.Date(ellipsis_args$edate))
{
error <- TRUE
errmessage %<>% c('x' = "edate must be an R date object")
}
}
if ("cbdate" %in% names(ellipsis_args))
{
if (!is.Date(ellipsis_args$cbdate) & !is.null(ellipsis_args$cbdate))
{
error <- TRUE
errmessage %<>% c('x' = "cbdate must be an R date object")
}
}
if ("cedate" %in% names(ellipsis_args))
{
if (!is.Date(ellipsis_args$cedate) & !is.null(ellipsis_args$cedate))
{
error <- TRUE
errmessage %<>% c('x' = "cedate must be an R date object")
}
}
if ("email" %in% names(ellipsis_args))
{
if (!isValidEmail(ellipsis_args$email))
{
error <- TRUE
errmessage %<>% c('x' = "invalid email address entered")
}
}
if ("minlat" %in% names(ellipsis_args))
{
if ((!between(as.double(ellipsis_args$minlat), -90, 90)) |
!is.character(ellipsis_args$minlat))
{
error <- TRUE
errmessage %<>% c('x' =
"minlat must be a numeric (expressed as a string) between -90 and 90"
)
}
}
if ("maxlat" %in% names(ellipsis_args))
{
if ((!between(as.double(ellipsis_args$maxlat), -90, 90)) |
!is.character(ellipsis_args$minlat))
{
error <- TRUE
errmessage %<>% c('x' =
"maxlat must be a numeric (expressed as a string) between -90 and 90"
)
}
}
if ("minlon" %in% names(ellipsis_args))
{
if ((!between(as.double(ellipsis_args$minlon), -180, 180)) |
!is.character(ellipsis_args$minlon)
)
{
error <- TRUE
errmessage %<>% c('x' =
"minlon must be a numeric (expressed as a string) between -180 and 180"
)
}
}
if ("maxlon" %in% names(ellipsis_args))
{
if ((!between(as.double(ellipsis_args$maxlon), -180, 180)) |
!is.character(ellipsis_args$maxlon)
)
{
error <- TRUE
errmessage %<>% c('x' =
"maxlon must be a numeric (expressed as a string) between -180 and 180"
)
}
}
if ("duration" %in% names(ellipsis_args))
{
if (nchar(ellipsis_args$duration) != 1 |
!is.character(ellipsis_args$duration) &
ellipsis_args$duration %in% 1:9 |
ellipsis_args$duration %in% LETTERS[1:26]
)
{
error <- TRUE
errmessage %<>% c('x' =
"duration must be a character from '1' to '9' or 'A' to 'Z'
(represented as a character string)"
)
}
}
if ("return_header" %in% names(ellipsis_args))
{
if (!is.logical(ellipsis_args$return_header))
{
error <- TRUE
errmessage %<>% c('x' = "return_header must be of type logical")
}
}
if (error)
{
callingfunction <- rlang::call_name(sys.call(sys.parent(2)))
if (is.null(callingfunction)) callingfunction <- "Unknown Environment"
callingfunction <- glue(" in: {callingfunction}")
c('i' = callingfunction, errmessage) %>% abort
}
}
format_variables_for_api <- function(x, separator="&")
{
if (length(x) == 0) {
return("")
}
x[vapply(x, is.null, FUN.VALUE = NA)] <- NULL
x[vapply(x, is.na, FUN.VALUE = NA)] <- NULL
x <- purrr::map_chr(x, as.character)
stringr::str_c(names(x), "=", x, collapse = separator) %>%
return()
}
format_multiple_params_for_api <- function(x, separator=",")
{
if (length(x) == 0) {
return("")
}
x[vapply(x, is.null, FUN.VALUE = NA)] <- NULL
x[vapply(x, is.na, FUN.VALUE = NA)] <- NULL
x <- purrr::map_chr(x, as.character)
paste0(x, collapse = separator)
}
aqs_ratelimit <- function(waittime=5L)
{
Sys.sleep(waittime)
}
aqs <- function(service, filter = NA, user = NA,
user_key = NA, variables = NULL, AQS_domain = "aqs.epa.gov")
{
if (is.null(getOption("aqs_username")) |
is.null(getOption("aqs_key")))
{stop("please enter user credentials before using RAQSAPI functions,\n
please refer to \'?aqs_credentials()\' for useage infomation \n")}
user_agent <- glue("User:{user} via RAQSAPI library for R") %>%
httr::user_agent()
if (rlang::is_empty(service) & rlang::is_empty(filter))
{
path <- glue::glue("/data/api/")
}else if (rlang::is_empty(service))
{
path <- glue::glue("/data/api/")
}else if (rlang::is_empty(filter))
{
path <- glue::glue("/data/api/{service}")
}else {
path <- glue::glue("/data/api/{service}/{filter}")
}
query <- c(email = I(user),
key = I(user_key),
variables,
recursive = TRUE) %>%
as.list
query <- query[!is.na(query)]
url <- httr::modify_url(scheme = "https",
hostname = AQS_domain,
url = path,
query = query
)
AQSresult <- httr::GET(url,
user_agent
)
aqs_ratelimit()
if (httr::http_type(AQSresult) != "application/json") {
stop("API did not return json", call. = TRUE)
}
out <- jsonlite::fromJSON(httr::content(AQSresult, "text"),
simplifyDataFrame = TRUE)
if ("Header" %in% names(out)) {out$Header %<>% tibble::as_tibble()}
if ("Data" %in% names(out)) {out$Data %<>% tibble::as_tibble()}
if ("Error" %in% names(out)) {out$Error %<>% tibble::as_tibble()}
if (httr::http_error(AQSresult))
{
print("RAQSAPI has encountered an error")
stop(httr::message_for_status(AQSresult),
call. = FALSE
)
}
out <- structure(.Data = out, class = "AQS_DATAMART_APIv2")
out$Data %<>% as_tibble
out$Header %<>% as_tibble
out$Data$datetime <- NULL
if (all(c("date_local", "time_local") %in% colnames(out$Data)))
{
out$Data %<>% dplyr::mutate(datetime = glue("{date_local} {time_local}"))
out$Data %<>% dplyr::mutate(datetime = ymd_hm(.data$`datetime`))
out$Data %<>% dplyr::arrange(.data$datetime)
out$Data %<>% dplyr::select(-.data$datetime)
}
return(out)
}
isValidEmail <- function(email) {
grepl("\\<[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\>",
as.character(email),
ignore.case = TRUE)
}
aqs_services_by_site <- function(parameter, bdate, edate,
stateFIPS, countycode, sitenum,
duration = NA_character_, service,
cbdate = NA_Date_, cedate = NA_Date_,
AQS_domain = "aqs.epa.gov")
{
aqs(service = service,
filter = "bySite",
user = getOption("aqs_username"),
user_key = getOption("aqs_key"),
variables = list(param = format_multiple_params_for_api(parameter),
bdate = format(bdate, format = "%Y%m%d"),
edate = format(edate, format = "%Y%m%d"),
state = stateFIPS,
county = countycode,
site = sitenum,
duration = duration,
cbdate = cbdate,
cedate = cedate
),
AQS_domain = AQS_domain
)
}
aqs_services_by_county <- function(parameter, bdate, edate,
stateFIPS, countycode, service,
duration = NA_character_,
cbdate = NA_Date_, cedate = NA_Date_,
AQS_domain = "aqs.epa.gov")
{
aqs(service = service,
filter = "byCounty",
user = getOption("aqs_username"),
user_key = getOption("aqs_key"),
variables = list(param = format_multiple_params_for_api(parameter),
bdate = format(bdate, format = "%Y%m%d"),
edate = format(edate, format = "%Y%m%d"),
state = stateFIPS,
county = countycode,
duration = duration,
cbdate = cbdate,
cedate = cedate
),
AQS_domain = AQS_domain
)
}
aqs_services_by_state <- function(parameter, bdate, edate, stateFIPS,
duration = NA_character_, service,
cbdate = NA_Date_, cedate = NA_Date_,
AQS_domain = "aqs.epa.gov")
{
aqs(service = service,
filter = "byState",
user = getOption("aqs_username"),
user_key = getOption("aqs_key"),
variables = list(param = format_multiple_params_for_api(parameter),
bdate = format(bdate, format = "%Y%m%d"),
edate = format(edate, format = "%Y%m%d"),
state = stateFIPS,
duration = duration,
cbdate = cbdate,
cedate = cedate
),
AQS_domain = AQS_domain
)
}
aqs_services_by_box <- function(parameter, bdate, edate, minlat, maxlat,
minlon, maxlon, duration = NA_character_,
service, cbdate = NA_Date_, cedate = NA_Date_,
AQS_domain = "aqs.epa.gov")
{
aqs(service = service,
filter = "byBox",
user = getOption("aqs_username"),
user_key = getOption("aqs_key"),
variables = list(param = format_multiple_params_for_api(parameter),
bdate = format(bdate, format = "%Y%m%d"),
edate = format(edate, format = "%Y%m%d"),
minlon = minlon,
maxlon = maxlon,
minlat = minlat,
maxlat = maxlat,
duration = duration,
cbdate = cbdate,
cedate = cedate
),
AQS_domain = AQS_domain
)
}
aqs_services_by_cbsa <- function(parameter, bdate, edate, cbsa_code,
duration = NA_character_, service,
cbdate = NA_Date_, cedate = NA_Date_,
AQS_domain = "aqs.epa.gov")
{
aqs(service = service,
filter = "byCBSA",
user = getOption("aqs_username"),
user_key = getOption("aqs_key"),
variables = list(param = format_multiple_params_for_api(parameter),
bdate = format(bdate, format = "%Y%m%d"),
edate = format(edate, format = "%Y%m%d"),
cbsa = cbsa_code,
duration = duration,
cbdate = cbdate,
cedate = cedate
),
AQS_domain = AQS_domain
)
}
aqs_services_by_pqao <- function(parameter, bdate, edate, pqao_code,
service, cbdate = NA_Date_, cedate = NA_Date_,
AQS_domain = "aqs.epa.gov")
{
aqs(service = service,
filter = "byPQAO",
user = getOption("aqs_username"),
user_key = getOption("aqs_key"),
variables = list(param = format_multiple_params_for_api(parameter),
bdate = format(bdate, format = "%Y%m%d"),
edate = format(edate, format = "%Y%m%d"),
pqao = pqao_code,
cbdate = cbdate,
cedate = cedate
),
AQS_domain = AQS_domain
)
}
aqs_services_by_MA <- function(parameter, bdate, edate, MA_code, service,
cbdate = NA_Date_, cedate = NA_Date_,
AQS_domain = "aqs.epa.gov")
{
aqs(service = service,
filter = "byMA",
user = getOption("aqs_username"),
user_key = getOption("aqs_key"),
variables = list(param = format_multiple_params_for_api(parameter),
bdate = format(bdate, format = "%Y%m%d"),
edate = format(edate, format = "%Y%m%d"),
agency = MA_code,
cbdate = cbdate,
cedate = cedate
),
AQS_domain = AQS_domain
)
}
aqs_metadata_service <- function(filter, service = NA_character_,
AQS_domain = "aqs.epa.gov")
{
aqs(service = "metaData",
filter = filter,
user = getOption("aqs_username"),
user_key = getOption("aqs_key"),
variables = list(service = service),
AQS_domain = AQS_domain
)
}
renameaqsvariables <- function(aqsobject, name1, name2)
{
if (is.null(aqsobject))
{
return(aqsobject)
} else if (class(aqsobject) == "AQS_DATAMART_APIv2")
{
aqsobject$Data %<>% dplyr::rename(!!name1 := 1)
aqsobject$Data %<>% dplyr::rename(!!name2 := 2)
} else if (all(class(aqsobject[[1]]) == "AQS_DATAMART_APIv2"))
{
aqsobject %<>% lapply("[[", "Data") %>%
dplyr::rename(!!name1 := 1)
aqsobject %<>% lapply("[[", "Data") %>%
dplyr::rename(!!name2 := 2)
}
return(aqsobject)
}
aqsmultiyearparams <- function(parameter, bdate, edate, service, ...)
{
ellipsis_args <- list(...)
if (bdate > edate)
{
return(rlang::abort(message = "bdate > edate"))
} else if (year(bdate) == year(edate))
{
bdatevector <- bdate
edatevector <- edate
} else if (year(bdate) < year(edate))
{
bdatevector <- c(bdate, seq.Date(from = ymd(
glue("{year(bdate) + 1}-1-1")
),
to = edate, by = "year")
)
if (month(edate) != 12 && day(edate) != 31)
{
edatevector <- c(seq.Date(from = ymd(glue("{year(bdate)}-12-31"
)
),
to = edate, by = "year"), edate)
} else
{
edatevector <- seq.Date(from = ymd(glue("{year(bdate)}-12-31")),
to = edate, by = "year")
}
}
if (length(bdatevector) > length(edatevector))
{
edatevector %<>% c(ymd(tail(edatevector, n = 1)) + years(1))
}
params <- tibble(parameter = format_multiple_params_for_api(parameter),
bdate = bdatevector,
edate = edatevector,
stateFIPS = ellipsis_args$stateFIPS,
countycode = ellipsis_args$countycode,
sitenum = ellipsis_args$sitenum,
service = service,
cbdate = ellipsis_args$cbdate,
cedate = ellipsis_args$cedate,
minlat = ellipsis_args$minlat,
maxlat = ellipsis_args$maxlat,
minlon = ellipsis_args$minlon,
maxlon = ellipsis_args$maxlon,
cbsa_code = ellipsis_args$cbsa_code,
pqao_code = ellipsis_args$pqao_code,
MA_code = ellipsis_args$MA_code,
filter = ellipsis_args$filter,
AQS_domain = ellipsis_args$AQS_domain
)
params %>%
dplyr::select_if(function(x) {!all(is.na(x))}) %>%
return()
} |
dynSurv <- function(object, newdata, newSurvData = NULL, u = NULL, horizon = NULL,
type = "first-order", M = 200, scale = 2, ci, progress = TRUE) {
if (!inherits(object, "mjoint")) {
stop("Use only with 'mjoint' model objects.\n")
}
if (type != "first-order" && type != "simulated") {
stop("order must be specified as either 'first-order' or 'simulated")
}
data.t <- process_newdata(newdata = newdata,
object = object,
tobs = NULL,
newSurvData = newSurvData)
if (!is.null(u) && !is.null(horizon)) {
stop("Cannot specify 'u' and 'horizon' times simultaneously")
}
if (is.null(u)) {
if (is.null(horizon)) {
u <- object$dmats$t$tj
if (length(u) > 1) {
u <- c(data.t$tobs, u[u > data.t$tobs])
}
} else {
u <- horizon + data.t$tobs
}
} else {
if (any(u <= data.t$tobs)) {
stop("Landmark time(s) must be greater than last observation time")
}
}
b.hat <- b_mode(data = data.t, theta = object$coefficients)
if (b.hat$convergence != 0) {
stop("Optimisation failed")
}
if (type == "first-order") {
b.hat <- b.hat$par
S.t <- S(b = b.hat, data = data.t, theta = object$coefficients)
S.u <- vector(length = length(u))
for (i in 1:length(u)) {
data.u <- process_newdata(newdata = newdata,
object = object,
tobs = u[i],
newSurvData = newSurvData)
S.u[i] <- S(b = b.hat, data = data.u, theta = object$coefficients)
}
pred <- data.frame("u" = u, "surv" = S.u / S.t)
}
if (type == "simulated") {
if (progress) {
cat("\n")
pb <- utils::txtProgressBar(min = 0, max = M, style = 3)
}
if (missing(ci)) {
ci <- 0.95
} else {
if (!is.numeric(ci) || (ci < 0) || (ci > 1)) {
stop("ci argument has been misspecified.\n")
}
}
alpha <- (1 - ci) / 2
b.curr <- delta.prop <- b.hat$par
sigma.prop <- -solve(b.hat$hessian) * scale
accept <- 0
surv <- matrix(nrow = length(u), ncol = M)
for (m in 1:M) {
theta.samp <- thetaDraw(object)
mh_sim <- b_metropolis(theta.samp, delta.prop, sigma.prop, b.curr, data.t)
b.curr <- mh_sim$b.curr
accept <- accept + mh_sim$accept
S.t <- S(b = b.curr, data = data.t, theta = theta.samp)
S.u <- vector(length = length(u))
for (i in 1:length(u)) {
data.u <- process_newdata(newdata = newdata,
object = object,
tobs = u[i],
newSurvData = newSurvData)
S.u[i] <- S(b = b.curr, data = data.u, theta = theta.samp)
}
surv[, m] <- S.u / S.t
if (progress) {
utils::setTxtProgressBar(pb, m)
}
}
if (progress) {
close(pb)
}
surv.mean <- apply(surv, 1, mean)
surv.med <- apply(surv, 1, median)
surv.low <- apply(surv, 1, quantile, prob = alpha)
surv.upp <- apply(surv, 1, quantile, prob = 1 - alpha)
pred <- data.frame("u" = u,
"mean" = surv.mean,
"median" = surv.med,
"lower" = surv.low,
"upper" = surv.upp)
}
out <- list("pred" = pred,
"fit" = object,
"newdata" = newdata,
"newSurvData" = newSurvData,
"u" = u,
"data.t" = data.t,
"type" = type,
"horizon" = horizon,
"b.hat" = b.hat)
if (type == "simulated") {
out$M <- ifelse(type == "simulated", M, NULL)
out$accept <- ifelse(type == "simulated", accept / M, NULL)
}
class(out) <- "dynSurv"
return(out)
} |
initiate.startValues_AFT <- function(Formula, data, model, nChain=1,
beta1=NULL, beta2=NULL, beta3=NULL, beta=NULL,
gamma=NULL,
theta=NULL,
y1=NULL, y2=NULL, y=NULL,
LN.mu=NULL, LN.sigSq=NULL,
DPM.class1=NULL, DPM.class2=NULL, DPM.class3=NULL, DPM.class=NULL,
DPM.mu1=NULL, DPM.mu2=NULL, DPM.mu3=NULL, DPM.mu=NULL,
DPM.zeta1=NULL, DPM.zeta2=NULL, DPM.zeta3=NULL, DPM.zeta=NULL,
DPM.tau=NULL)
{
ret <- vector("list", nChain)
chain = 1
while(chain <= nChain){
if(length(Formula)[2]==1)
{
cat(paste("Start values are initiated for univariate ", model, " model...", sep = ""), cat("\n"))
LT <- model.part(Formula, data=data, lhs=1)
y.mat <- model.part(Formula, data=data, lhs=2)
Y <- cbind(y.mat, LT)
Xmat <- model.frame(formula(Formula, lhs=0, rhs=1), data=data)
p <- ncol(Xmat)
n <- nrow(Xmat)
if(!is.null(beta1)) stop(paste("'beta1' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(beta2)) stop(paste("'beta2' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(beta3)) stop(paste("'beta3' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(gamma)) stop(paste("'gamma' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(theta)) stop(paste("'theta' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(y1)) stop(paste("'y1' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(y2)) stop(paste("'y2' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(DPM.class1)) stop(paste("'DPM.class1' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(DPM.class2)) stop(paste("'DPM.class2' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(DPM.class3)) stop(paste("'DPM.class3' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(DPM.mu1)) stop(paste("'DPM.mu1' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(DPM.mu2)) stop(paste("'DPM.mu2' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(DPM.mu3)) stop(paste("'DPM.mu3' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(DPM.zeta1)) stop(paste("'DPM.zeta1' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(DPM.zeta2)) stop(paste("'DPM.zeta2' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(DPM.zeta3)) stop(paste("'DPM.zeta3' is for semi-competing risks models so it must be specified as NULL for univariate ", model, " model.", sep = ""))
if(!is.null(beta)){
if(length(beta) != p) stop(paste("Length of starting value for beta must be", p))
}
if(is.null(beta)) beta <- runif(p, -0.1, 0.1)
if(!is.null(y)){
if(length(y) != n) stop("Length of starting value for y must be n")
}
if(is.null(y))
{
y <- log(Y[,1])
y[y == -Inf] <- 0
}
if(model == "LN")
{
if(!is.null(LN.mu)){
if(length(LN.mu) != 1) stop("Length of starting value for LN.mu must be 1 for univariate survival analysis")
}
if(is.null(LN.mu)) LN.mu <- runif(1, -0.1, 0.1)
if(!is.null(LN.sigSq)){
if(length(LN.sigSq) != 1) stop("Length of starting value for LN.sigSq must be 1 for univariate survival analysis")
}
if(is.null(LN.sigSq)) LN.sigSq <- runif(1, 0.5, 1.5)
}
if(model == "DPM")
{
if(!is.null(DPM.class)){
if(length(DPM.class) != n) stop(paste("Length of starting value for DPM.class must be", n))
}
if(is.null(DPM.class)) DPM.class <- sample(1:2, size=n, replace=TRUE)
if(!is.null(DPM.tau)){
if(length(DPM.tau) != 1) stop("Length of starting value for DPM.tau must be 1 for univariate survival analysis")
}
if(is.null(DPM.tau)) DPM.tau <- c(0.5)
if(!is.null(DPM.zeta)){
if(length(DPM.zeta) != n) stop(paste("Length of starting value for DPM.zeta must be", n))
}
if(is.null(DPM.zeta)) DPM.zeta <- rep(1/0.01, n)
if(!is.null(DPM.mu)){
if(length(DPM.mu) != n) stop(paste("Length of starting value for DPM.mu must be", n))
}
if(is.null(DPM.mu)) DPM.mu <- rep(1, n)
}
start.common <- list(beta=beta, y=y)
start.LN <- list(LN.mu=LN.mu, LN.sigSq=LN.sigSq)
start.DPM <- list(DPM.class=DPM.class, DPM.mu=DPM.mu, DPM.zeta=DPM.zeta, DPM.tau=DPM.tau)
if(model == "LN"){
value <- list(common=start.common, LN=start.LN)
}
if(model == "DPM"){
value <- list(common=start.common, DPM=start.DPM)
}
}
if(length(Formula)[2]==3)
{
cat(paste("Start values are initiated for semi-competing risks ", model[1], " model...", sep = ""), cat("\n"))
LT <- model.part(Formula, data=data, lhs=1)
y1.mat <- model.part(Formula, data=data, lhs=2)
y2.mat <- model.part(Formula, data=data, lhs=3)
Y <- cbind(y1.mat, y2.mat, LT)
Xmat1 <- model.frame(formula(Formula, lhs=0, rhs=1), data=data)
Xmat2 <- model.frame(formula(Formula, lhs=0, rhs=2), data=data)
Xmat3 <- model.frame(formula(Formula, lhs=0, rhs=3), data=data)
p1 <- ncol(Xmat1)
p2 <- ncol(Xmat2)
p3 <- ncol(Xmat3)
n <- nrow(Xmat1)
if(!is.null(beta)) stop(paste("'beta' is for univariate models so it must be specified as NULL for semi-competing risks ", model, " model.", sep = ""))
if(!is.null(y)) stop(paste("'y' is for univariate models so it must be specified as NULL for semi-competing risks ", model, " model.", sep = ""))
if(!is.null(DPM.class)) stop(paste("'DPM.class' is for univariate models so it must be specified as NULL for semi-competing risks ", model, " model.", sep = ""))
if(!is.null(DPM.mu)) stop(paste("'DPM.mu' is for univariate models so it must be specified as NULL for semi-competing risks ", model, " model.", sep = ""))
if(!is.null(DPM.zeta)) stop(paste("'DPM.zeta' is for univariate models so it must be specified as NULL for semi-competing risks ", model, " model.", sep = ""))
if(!is.null(beta1)){
if(length(beta1) != p1) stop(paste("Length of starting value for beta1 must be", p1))
}
if(is.null(beta1)) beta1 <- runif(p1, -0.1, 0.1)
if(!is.null(beta2)){
if(length(beta2) != p2) stop(paste("Length of starting value for beta2 must be", p2))
}
if(is.null(beta2)) beta2 <- runif(p2, -0.1, 0.1)
if(!is.null(beta3)){
if(length(beta3) != p3) stop(paste("Length of starting value for beta3 must be", p3))
}
if(is.null(beta3)) beta3 <- runif(p3, -0.1, 0.1)
if(!is.null(theta)){
if(length(theta) != 1) stop("Length of starting value for theta must be 1")
}
if(is.null(theta)) theta <- runif(1, 0.1, 1.1)
if(!is.null(gamma)){
if(length(gamma) != n) stop("Length of starting value for gamma must be n")
}
if(is.null(gamma)) gamma <- rnorm(n, 0, sqrt(theta))
if(!is.null(y1)){
if(length(y1) != n) stop("Length of starting value for y1 must be n")
}
if(is.null(y1))
{
y1 <- log(Y[,1])
y1[y1 == -Inf] <- 0
}
if(!is.null(y2)){
if(length(y2) != n) stop("Length of starting value for y2 must be n")
}
if(is.null(y2))
{
y2 <- log(Y[,3])
y2[y2 == -Inf] <- 0
}
if(model == "LN")
{
if(!is.null(LN.mu)){
if(length(LN.mu) != 3) stop("Length of starting value for LN.mu must be 3 for semi-competing risks analysis")
}
if(is.null(LN.mu)) LN.mu <- runif(3, -0.1, 0.1)
if(!is.null(LN.sigSq)){
if(length(LN.sigSq) != 3) stop("Length of starting value for LN.sigSq must be 3 for semi-competing risks analysis")
}
if(is.null(LN.sigSq)) LN.sigSq <- runif(3, 0.5, 1.5)
}
if(model == "DPM")
{
if(!is.null(DPM.class1)){
if(length(DPM.class1) != n) stop(paste("Length of starting value for DPM.class1 must be", n))
}
if(is.null(DPM.class1)) DPM.class1 <- sample(1:2, size=n, replace=TRUE)
if(!is.null(DPM.class2)){
if(length(DPM.class2) != n) stop(paste("Length of starting value for DPM.class2 must be", n))
}
if(is.null(DPM.class2)) DPM.class2 <- sample(1:2, size=n, replace=TRUE)
if(!is.null(DPM.class3)){
if(length(DPM.class3) != n) stop(paste("Length of starting value for DPM.class3 must be", n))
}
if(is.null(DPM.class3)) DPM.class3 <- sample(1:2, size=n, replace=TRUE)
if(!is.null(DPM.tau)){
if(length(DPM.tau) != 3) stop("Length of starting value for DPM.tau must be 3 for semi-competing risks analysis")
}
if(is.null(DPM.tau)) DPM.tau <- c(0.5, 0.5, 0.5)
if(!is.null(DPM.zeta1)){
if(length(DPM.zeta1) != n) stop(paste("Length of starting value for DPM.zeta1 must be", n))
}
if(is.null(DPM.zeta1)) DPM.zeta1 <- rep(1/0.01, n)
if(!is.null(DPM.zeta2)){
if(length(DPM.zeta2) != n) stop(paste("Length of starting value for DPM.zeta2 must be", n))
}
if(is.null(DPM.zeta2)) DPM.zeta2 <- rep(1/0.01, n)
if(!is.null(DPM.zeta3)){
if(length(DPM.zeta3) != n) stop(paste("Length of starting value for DPM.zeta3 must be", n))
}
if(is.null(DPM.zeta3)) DPM.zeta3 <- rep(1/0.01, n)
if(!is.null(DPM.mu1)){
if(length(DPM.mu1) != n) stop(paste("Length of starting value for DPM.mu1 must be", n))
}
if(is.null(DPM.mu1)) DPM.mu1 <- rep(1, n)
if(!is.null(DPM.mu2)){
if(length(DPM.mu2) != n) stop(paste("Length of starting value for DPM.mu2 must be", n))
}
if(is.null(DPM.mu2)) DPM.mu2 <- rep(1, n)
if(!is.null(DPM.mu3)){
if(length(DPM.mu3) != n) stop(paste("Length of starting value for DPM.mu3 must be", n))
}
if(is.null(DPM.mu3)) DPM.mu3 <- rep(1, n)
}
start.common <- list(beta1=beta1, beta2=beta2, beta3=beta3, gamma=gamma, theta=theta, y1=y1, y2=y2)
start.LN <- list(LN.mu=LN.mu, LN.sigSq=LN.sigSq)
start.DPM <- list(DPM.class1=DPM.class1, DPM.class2=DPM.class2, DPM.class3=DPM.class3, DPM.mu1=DPM.mu1, DPM.mu2=DPM.mu2, DPM.mu3=DPM.mu3, DPM.zeta1=DPM.zeta1, DPM.zeta2=DPM.zeta2, DPM.zeta3=DPM.zeta3, DPM.tau=DPM.tau)
if(model == "LN"){
value <- list(common=start.common, LN=start.LN)
}
if(model == "DPM"){
value <- list(common=start.common, DPM=start.DPM)
}
}
ret[[chain]] <- value
chain = chain + 1
}
return(ret)
} |
varcub00 <-function(m,pai,csi){
(m-1)*(pai*csi*(1-csi)+(1-pai)*(((m+1)/12) + pai*(m-1)*(csi-1/2)^2 ))
} |
ym3 <-
function(n,t){
if(n<7 || n%%2==0){
cat("Enter v >=7 and odd\n")
}
else{
v<-n
b<-v
r<-((v+1)/2)-1-t
k<-r
m<-(v-1)/2
l<-c()
l[1]<-v-6-(m-4+t)
for(i in 2:(t+2)){
l[i]<-0
}
if(m>3 && m>(t+2)){
for(i in (t+3):m){
l[i]<-l[i-1]+1
}
}
cat("Following is a Youden - ",m,"Square\n")
mat<-circulant(n)
print.matrix <- function(m){
write.table(format(m, justify="centre"),
row.names=F, col.names=F, quote=F,sep=" ")
}
print.matrix(mat[(t+1):(((v+1)/2)-1),])
cat("\n")
cat("The incomplete columns of this Youden - ",m,"square gives the PBIB design with the following parameters:\n")
cat("v = ",v," b = ",b," r =",r," k = ",k,"\n")
for(i in 1:m){
cat("lambda_",i," = ",l[i]," ")
}
cat("\n")
}
} |
require(OpenMx)
options(mxCondenseMatrixSlots=TRUE)
require(mvtnorm)
set.seed(476)
A <- matrix(0,1000,1000)
A[lower.tri(A)] <- runif(499500, -0.025, 0.025)
A <- A + t(A)
diag(A) <- runif(1000,0.95,1.05)
y <- t(rmvnorm(1,sigma=A*0.5))
y <- y + rnorm(1000,sd=sqrt(0.5))
x <- rnorm(1000)
dat <- cbind(y,x)
colnames(dat) <- c("y","x")
ge <- mxExpectationGREML(V="V",yvars="y", Xvars="x", addOnes=T)
gff <- mxFitFunctionGREML()
mxdat <- mxData(observed = dat, type="raw", sort=FALSE)
testmod <- mxModel(
"GREML_1GRM_1trait",
mxMatrix(type = "Full", nrow = 1, ncol=1, free=T, values = var(y)/2, labels = "ve", lbound = 0.0001,
name = "Ve"),
mxMatrix(type = "Full", nrow = 1, ncol=1, free=T, values = var(y)/2, labels = "va", name = "Va"),
mxMatrix("Iden",nrow=1000,name="I"),
mxMatrix("Symm",nrow=1000,free=F,values=A,name="A"),
mxAlgebra((A%x%Va) + (I%x%Ve), name="V"),
mxAlgebra(Va/(Va+Ve), name="h2"),
mxCI("h2"),
mxdat,
ge,
gff
)
testrun <- mxRun(testmod,intervals = T)
summary(testrun)
scm <- chol2inv(chol(testrun$output$hessian/2))
pointest <- testrun$output$estimate
h2se <- sqrt(
(pointest[2]/(pointest[1]+pointest[2]))^2 * (
(scm[2,2]/pointest[2]^2) - (2*scm[1,2]/pointest[1]/(pointest[1]+pointest[2])) +
(sum(scm)*(pointest[1]+pointest[2])^-2)
))
mxEval(h2,testrun,T)[1,1] + 2*c(-h2se,h2se)
testrun$output$confidenceIntervals |
Sys.setenv("RSTUDIO_PANDOC"="C:/Program Files/RStudio/bin/pandoc")
commit_memo <- "'pnadc'"
github_password <- readLines( file.path( path.expand( "~" ) , "github password.txt" ) )
source( file.path( path.expand( "~" ) , "Github\\asdfree\\vignetterator\\descriptive_statistics_blocks.R" ) )
source( file.path( path.expand( "~" ) , "Github\\asdfree\\vignetterator\\measures_of_uncertainty_blocks.R" ) )
source( file.path( path.expand( "~" ) , "Github\\asdfree\\vignetterator\\tests_of_association_blocks.R" ) )
needs_travis_build_status_line <- "[![Build Status](https://travis-ci.org/asdfree/chapter_tag.svg?branch=master)](https://travis-ci.org/asdfree/chapter_tag) [![Build status](https://ci.appveyor.com/api/projects/status/github/asdfree/chapter_tag?svg=TRUE)](https://ci.appveyor.com/project/ajdamico/chapter_tag)"
needs_catalog_block <- '`lodown` also provides a catalog of available microdata extracts with the `get_catalog()` function. After requesting the CHAPTER_TAG catalog, you could pass a subsetted catalog through the `lodown()` function in order to download and import specific extracts (rather than all available extracts).\n\n```{r eval = FALSE , results = "hide" }\nlibrary(lodown)\n
needs_dplyr_block <- '
readme_md_text <- "
pull_chunk <-
function( text_file , code_chunk ){
metadata_lines <- readLines( text_file )
start_line <- grep( paste0( "~~~\\{(.*)" , code_chunk , "(.*)\\}(.*)" ) , metadata_lines ) + 1
if( length( start_line ) == 0 ) return( "" )
end_lines <- grep( "~~~" , metadata_lines )
end_line <- min( end_lines[ end_lines >= start_line ] ) - 1
metadata_lines[ start_line:end_line ]
}
pull_line <-
function( text_file , code_line ){
this_line <- grep( paste0( "^" , code_line , ":" ) , readLines( text_file ) , value = TRUE )
if( length( this_line ) == 0 ) "" else as.character( gsub( paste0( code_line , ":( +)?" ) , "" , this_line ) )
}
book_folder <- "C:/Users/anthonyd/Documents/Github/asdfree/"
sub_lines <- c( "chapter_title" , "lodown_password_parameters" , "get_catalog_password_parameters" , "authorship_line" , "table_structure" , "generalizable_population" , "publication_period" , "administrative_organization" , "catalog_subset_description" , "catalog_subset" , "sql_tablename" , "income_variable_description" , "income_variable" , "ratio_estimation_numerator" , "ratio_estimation_denominator" , "group_by_variable" , "categorical_variable" , "linear_variable" , "binary_variable" , "subset_definition_description" , "subset_definition" , "linear_narm" , "categorical_narm" , "ratio_narm" , "binary_narm" )
sub_chunks <- c( "analysis_examples_loading_block" , "analysis_examples_survey_design" , "variable_recoding_block" , "replication_example_block" , "dataset_introduction" , "convey_block" , "replacement_block" )
needs_this_block <- c( "needs_catalog_block" , "needs_srvyr_block" , "needs_dplyr_block" , "needs_travis_build_status_line" )
library(bookdown)
library(rmarkdown)
library(stringr)
metafiles <- sort( list.files( paste0( book_folder , 'metadata/' ) , full.names = TRUE ) )
full_text <- lapply( metafiles , readLines )
chapter_tag <- gsub( "\\.txt" , "" , basename( metafiles ) )
for( this_line in sub_lines ){
assign( this_line , sapply( metafiles , function( fn ) pull_line( fn , this_line ) ) )
}
for( this_chunk in sub_chunks ){
assign( this_chunk , sapply( metafiles , function( fn ) pull_chunk( fn , this_chunk ) ) )
}
fixed_chapters <- 6
rmds_to_clear <- paste0( str_pad( ( fixed_chapters + 1 ):99 , 2 , pad = '0' ) , "\\-" , collapse = "|" )
file.remove( grep( rmds_to_clear , list.files( book_folder , full.names = TRUE ) , value = TRUE ) )
for ( i in seq_along( chapter_tag ) ){
this_rmd <- paste0( book_folder , str_pad( fixed_chapters + i , 2 , pad = '0' ) , "-" , chapter_tag[ i ] , ".Rmd" )
rmd_lines <- readLines( paste0( book_folder , "skeleton/skeleton.Rmd" ) )
is_survey <- any( grepl( "library(survey)" , full_text[[i]] , fixed = TRUE ) )
is_mi <- any( grepl( "library(mitools)" , full_text[[i]] , fixed = TRUE ) )
is_db <- any( grepl( "library(DBI)" , full_text[[i]] , fixed = TRUE ) )
needs_srvyr_block <- paste0( '
rmd_lines <- gsub( "kind_of_analysis_examples" , if( is_survey ) "the `survey` library" else if( is_db ) "SQL and `RSQLite`" else "base R" , rmd_lines )
for( this_block in needs_this_block ){
rmd_lines <- gsub( this_block , if( any( grepl( paste0( "^" , this_block , ": yes" ) , tolower( full_text[[i]] ) ) ) ) get( this_block ) else "" , rmd_lines )
}
if( any( grepl( "^needs_travis_build_status_line: yes" , tolower( full_text[[i]] ) ) ) ) {
readme_md_text <- c( readme_md_text , paste0( chapter_tag[ i ] , ": " , gsub( "chapter_tag" , chapter_tag[ i ] , needs_travis_build_status_line ) , '\n' ) )
}
if( !is_survey ) rmd_lines <- gsub( "tbl_initiation_line" , if( is_db ) "library(dbplyr)\ndplyr_db <- dplyr::src_sqlite( dbdir )\nchapter_tag_tbl <- tbl( dplyr_db , 'sql_tablename' )" else "chapter_tag_tbl <- tbl_df( chapter_tag_df )" , rmd_lines )
construct_a_this_line <-
paste0(
if( is_survey ) "Construct a " else if( is_db ) "Connect to a " ,
if( is_mi ) "multiply-imputed, " ,
if( is_db ) "database" ,
if( is_survey & is_db ) "-backed " ,
if( is_survey ) "complex sample survey design" ,
if( !is_survey & !is_db ) "Load a data frame" ,
":"
)
rmd_lines <- gsub( "^construct_a_what_line" , construct_a_this_line , rmd_lines )
unweighted_counts_block <-
if( is_survey ){
if( is_mi ){
'Count the unweighted number of records in the survey sample, overall and by groups:\n```{r eval = FALSE , results = "hide" }\nMIcombine( with( chapter_tag_design , svyby( ~ one , ~ one , unwtd.count ) ) )\n\nMIcombine( with( chapter_tag_design , svyby( ~ one , ~ group_by_variable , unwtd.count ) ) )\n```'
} else {
'Count the unweighted number of records in the survey sample, overall and by groups:\n```{r eval = FALSE , results = "hide" }\nsum( weights( chapter_tag_design , "sampling" ) != 0 )\n\nsvyby( ~ one , ~ group_by_variable , chapter_tag_design , unwtd.count )\n```'
}
} else if( is_db ){
'Count the unweighted number of records in the SQL table, overall and by groups:\n```{r eval = FALSE , results = "hide" }\ndbGetQuery( db , "SELECT COUNT(*) FROM sql_tablename" )\n\ndbGetQuery( db ,\n\t"SELECT\n\t\tgroup_by_variable ,\n\t\tCOUNT(*) \n\tFROM sql_tablename\n\tGROUP BY group_by_variable"\n)\n```'
} else {
'Count the unweighted number of records in the table, overall and by groups:\n```{r eval = FALSE , results = "hide" }\nnrow( chapter_tag_df )\n\ntable( chapter_tag_df[ , "group_by_variable" ] , useNA = "always" )\n```'
}
rmd_lines <- gsub( "^unweighted_counts_block$" , unweighted_counts_block , rmd_lines )
if( is_survey ){
weighted_counts_block <-
if( is_mi ){
'Count the weighted size of the generalizable population, overall and by groups:\n```{r eval = FALSE , results = "hide" }\nMIcombine( with( chapter_tag_design , svytotal( ~ one ) ) )\n\nMIcombine( with( chapter_tag_design ,\n\tsvyby( ~ one , ~ group_by_variable , svytotal )\n) )\n```'
} else {
'Count the weighted size of the generalizable population, overall and by groups:\n```{r eval = FALSE , results = "hide" }\nsvytotal( ~ one , chapter_tag_design )\n\nsvyby( ~ one , ~ group_by_variable , chapter_tag_design , svytotal )\n```'
}
rmd_lines <- gsub( "^survey_only_weighted_counts_block$" , paste0( '
} else {
rmd_lines <- gsub( "^survey_only_(.*)" , "" , rmd_lines )
}
descriptive_statistics_block <-
if( is_survey ) {
if( is_mi ) mi_descriptive_block else survey_descriptive_block
} else if( is_db ) db_descriptive_block else base_descriptive_block
rmd_lines <- gsub( "^descriptive_statistics_block$" , descriptive_statistics_block , rmd_lines )
measures_of_uncertainty_block <-
if( is_survey ) {
if( is_mi ) mi_measures_of_uncertainty_block else survey_measures_of_uncertainty_block
} else if( is_db ) db_measures_of_uncertainty_block else base_measures_of_uncertainty_block
rmd_lines <- gsub( "^measures_of_uncertainty_block$" , measures_of_uncertainty_block , rmd_lines )
tests_of_association_block <-
if( is_survey ) {
if( is_mi ) mi_tests_of_association_block else survey_tests_of_association_block
} else if( is_db ) db_tests_of_association_block else base_tests_of_association_block
rmd_lines <- gsub( "^tests_of_association_block$" , tests_of_association_block , rmd_lines )
subsetting_block <-
if( is_survey ){
if( is_mi ){
'Restrict the survey design to subset_definition_description:\n```{r eval = FALSE , results = "hide" }\nsub_chapter_tag_design <- subset( chapter_tag_design , subset_definition )\n```\nCalculate the mean (average) of this subset:\n```{r eval = FALSE , results = "hide" }\nMIcombine( with( sub_chapter_tag_design , svymean( ~ linear_variable linear_narm ) ) )\n```'
} else {
'Restrict the survey design to subset_definition_description:\n```{r eval = FALSE , results = "hide" }\nsub_chapter_tag_design <- subset( chapter_tag_design , subset_definition )\n```\nCalculate the mean (average) of this subset:\n```{r eval = FALSE , results = "hide" }\nsvymean( ~ linear_variable , sub_chapter_tag_design linear_narm )\n```'
}
} else if( is_db ){
'Limit your SQL analysis to subset_definition_description with `WHERE`:\n```{r eval = FALSE , results = "hide" }\ndbGetQuery( db ,\n\t"SELECT\n\t\tAVG( linear_variable )\n\tFROM sql_tablename\n\tWHERE subset_definition"\n)\n```'
} else {
'Limit your `data.frame` to subset_definition_description:\n```{r eval = FALSE , results = "hide" }\nsub_chapter_tag_df <- subset( chapter_tag_df , subset_definition )\n```\nCalculate the mean (average) of this subset:\n```{r eval = FALSE , results = "hide" }\nmean( sub_chapter_tag_df[ , "linear_variable" ] linear_narm )\n```'
}
rmd_lines <- gsub( "^subsetting_block$" , subsetting_block , rmd_lines )
for( this_chunk in sub_chunks ){
rmd_lines <- gsub( this_chunk , paste( get( this_chunk )[[i]] , collapse = "\n" ) , rmd_lines )
}
for( this_line in c( sub_lines , "chapter_tag" ) ){
rmd_lines <- gsub( this_line , get( this_line )[ i ] , rmd_lines )
rmd_lines <- gsub( toupper( this_line ) , toupper( get( this_line )[ i ] ) , rmd_lines )
}
rmd_lines <- gsub( "\\\\\\\\n" , '\n' , rmd_lines )
rmd_lines <- gsub( "\\\\\\\\t" , '\t' , rmd_lines )
rmd_lines <- paste( rmd_lines , collapse = "\n" )
while( grepl( "\n\n\n" , rmd_lines ) ) rmd_lines <- gsub( "\n\n\n" , "\n\n" , rmd_lines )
while( grepl( "\n\t\n\t\n" , rmd_lines ) ) rmd_lines <- gsub( "\n\t\n\t\n" , "\n\t\n" , rmd_lines )
while( grepl( " " , rmd_lines ) ) rmd_lines <- gsub( " " , " " , rmd_lines )
rmd_lines <- gsub( "\t0.5 , na.rm = TRUE" , "\t0.5 ,\n\tna.rm = TRUE" , rmd_lines )
rmd_lines <- gsub( "\tkeep.var = TRUE , na.rm = TRUE" , "\tkeep.var = TRUE ,\n\tna.rm = TRUE" , rmd_lines )
rmd_lines <- gsub( "\t\tsvymean , na.rm = TRUE" , "\t\tsvymean ,\n\t\tna.rm = TRUE" , rmd_lines )
rmd_lines <- gsub( "\tsvymean , na.rm = TRUE" , "\tsvymean ,\n\tna.rm = TRUE" , rmd_lines )
rmd_lines <- gsub( "\tmean , na.rm = TRUE" , "\tmean ,\n\tna.rm = TRUE" , rmd_lines )
rmd_lines <- gsub( "\tvar , na.rm = TRUE" , "\tvar ,\n\tna.rm = TRUE" , rmd_lines )
rmd_lines <- gsub( "\tsum , na.rm = TRUE" , "\tsum ,\n\tna.rm = TRUE" , rmd_lines )
rmd_lines <- gsub( "\n\t([a-z]+)_design , na\\.rm = TRUE\n" , "\n\t\\1_design ,\n\tna.rm = TRUE\n" , rmd_lines )
if( length( replacement_block[[i]] ) > 1 ){
for( this_replacement in seq( 2 , length( replacement_block[[i]] ) , by = 2 ) ) rmd_lines <- gsub( replacement_block[[i]][ this_replacement - 1 ] , replacement_block[[i]][ this_replacement ] , rmd_lines , fixed = TRUE )
}
writeLines( rmd_lines , this_rmd )
}
setwd( book_folder )
clean_site()
render_site(output_format = 'bookdown::gitbook', encoding = 'UTF-8')
html_files <-
grep(
"html$" ,
list.files(
file.path( path.expand( "~" ) , "Github\\asdfree\\docs" ) ,
full.names = TRUE ,
recursive = FALSE
) ,
value = TRUE
)
for( this_metafile in metafiles ){
chapter_tag <- gsub( "\\.txt$" , "" , basename( this_metafile ) )
link_line <-
paste0(
'"link": "https://github.com/ajdamico/asdfree/edit/master/' ,
stringr::str_pad( fixed_chapters + which( this_metafile == metafiles ) , pad = '0' , width = 2 ) ,
'-' ,
chapter_tag ,
'.Rmd",'
)
html_file <- html_files[ grep( paste0( '-' , chapter_tag , '.html$' ) , html_files ) ]
html_lines <- readLines( html_file )
html_lines <-
gsub(
link_line ,
paste0( '"link": "https://github.com/ajdamico/asdfree/edit/master/metadata/' , chapter_tag , '.txt",' ) ,
html_lines ,
fixed = TRUE
)
writeLines( html_lines , html_file )
}
datasets_path <- normalizePath( file.path( path.expand( "~" ) , "Github/datasets/" ) , winslash = '/' )
file.remove( list.files( datasets_path , recursive = TRUE , full.names = TRUE , include.dirs = TRUE ) )
travis_ymls <- grep( "\\.travis\\.yml$" , list.files( file.path( path.expand( "~" ) , "Github/datasets/" ) , recursive = TRUE , full.names = TRUE , include.dirs = TRUE , all.files = TRUE ) , value = TRUE )
file.remove( travis_ymls )
repo_files <- list.files( normalizePath( file.path( path.expand( "~" ) , "Github/asdfree/repo/" ) , winslash = '/' ) , recursive = TRUE , full.names = TRUE , all.files = TRUE )
rmd_files <- grep( "\\.Rmd$" , list.files( file.path( path.expand( "~" ) , "Github/asdfree/" ) , full.names = TRUE ) , value = TRUE )
ci_rmd_files <- sapply( rmd_files , function( w ) any( grepl( "travis|appveyor" , readLines( w ) ) & grepl( "Build Status" , readLines( w ) ) ) )
ci_rmd_files <- names( ci_rmd_files[ ci_rmd_files ] )
for( this_ci_file in ci_rmd_files ){
chapter_tag <- gsub( "(.*)-(.*)\\.Rmd" , "\\2" , basename( this_ci_file ) )
if( dir.exists( paste0( "C:/Users/AnthonyD/Documents/Github/datasets/" , chapter_tag ) ) ){
system( paste0( "powershell git -C 'C:/Users/AnthonyD/Documents/Github/datasets/" , chapter_tag , "' pull" ) )
} else {
system( paste0( "powershell git clone https://ajdamico:" , github_password , "@github.com/asdfree/" , chapter_tag , "/ 'C:/Users/AnthonyD/Documents/Github/datasets/" , chapter_tag , "'" ) )
}
this_metadata_file <- gsub( paste0( "/([0-9]+)-" , chapter_tag , ".Rmd$" ) , paste0( "/metadata/" , chapter_tag , ".txt" ) , this_ci_file )
needed_libraries <- paste( gsub( "^(dependencies: )?library\\(|\\)" , "" , unique( grep( "^(dependencies: )?library\\(" , c( if( file.exists( this_metadata_file ) ) readLines( this_metadata_file ) , readLines( this_ci_file ) ) , value = TRUE ) ) ) , collapse = ", " )
lodown_r_file_edit <- system( paste0( "powershell git --git-dir='C:/Users/AnthonyD/Documents/Github/lodown/.git' log -n 1 -- R/" , chapter_tag , ".R" ) , intern = TRUE )
lodown_file_commit <- grep( "commit" , lodown_r_file_edit , value = TRUE )
lodown_file_commit <- if( length( lodown_file_commit > 0 ) ) paste( "ajdamico/lodown" , lodown_file_commit ) else ""
asdfree_r_file_edit <- system( paste0( "powershell git --git-dir='C:/Users/AnthonyD/Documents/Github/asdfree/.git' log -n 1 -- " , basename( this_ci_file ) ) , intern = TRUE )
asdfree_file_commit <- grep( "commit" , asdfree_r_file_edit , value = TRUE )
asdfree_file_commit <- if( length( asdfree_file_commit > 0 ) ) paste( "ajdamico/asdfree" , asdfree_file_commit ) else ""
this_repo_path <- normalizePath( file.path( datasets_path , chapter_tag ) , winslash = '/' , mustWork = FALSE )
copied_files <- gsub( normalizePath( file.path( path.expand( "~" ) , "Github/asdfree/repo/" ) , winslash = '/' ) , this_repo_path , repo_files )
this_repo_dirs <- unique( dirname( copied_files ) )
lapply( this_repo_dirs , dir.create , showWarnings = FALSE )
file.copy( repo_files , copied_files , overwrite = TRUE )
if( file.exists( this_metadata_file ) ){
for( this_file in copied_files ){
these_lines <- readLines( this_file )
sample_setup_breaks <- pull_line( this_metadata_file , "sample_setup_breaks" )
needs_7za_install <- pull_line( this_metadata_file , "needs_7za_install" )
if( basename( this_file ) == '.travis.yml' ) if( needs_7za_install == 'yes' ) these_lines <- gsub( "
if( basename( this_file ) == 'DESCRIPTION' ) {
if( grepl( 'archive' , needed_libraries ) ) {
these_lines <- gsub( "desc_remotes_line" , "Remotes: ajdamico/lodown, jimhester/archive" , these_lines )
} else {
these_lines <- gsub( "desc_remotes_line" , "Remotes: ajdamico/lodown" , these_lines )
}
}
if( grepl( 'setup\\.R$' , this_file ) ){
environment_variables <- pull_chunk( this_metadata_file , "environment_variables_block" )
these_lines <- c( these_lines , environment_variables )
msrb <- pull_chunk( this_metadata_file , "machine_specific_replacements_block" )
msrb <- gsub( "CHAPTER_TAG" , toupper( chapter_tag ) , msrb )
if( identical( msrb , '' ) ) msrb <- c("machine_specific_replacements <- ", "\tlist( ", "\t\t", "\t\t
eval( parse( text = msrb ) )
sample_setup_block <- pull_chunk( this_metadata_file , "sample_setup_block" )
broken_sample_test_condition <- pull_line( this_metadata_file , "broken_sample_test_condition" )
if( !identical( sample_setup_block , '' ) ){
sample_setup_block <- gsub( "CHAPTER_TAG" , toupper( chapter_tag ) , sample_setup_block )
for ( this_replacement in machine_specific_replacements ) sample_setup_block <- gsub( this_replacement[ 1 ] , this_replacement[ 2 ] , sample_setup_block , fixed = TRUE )
these_lines <- c( these_lines , sample_setup_block )
}
these_lines <-
c(
these_lines ,
lodown::syntaxtractor(
chapter_tag ,
replacements = machine_specific_replacements ,
setup_rmd = identical( sample_setup_block , '' ) ,
sample_setup_breaks = if( !identical( sample_setup_breaks , '' ) ) sample_setup_breaks ,
broken_sample_test_condition = if( !identical( broken_sample_test_condition , '' ) ) broken_sample_test_condition
)
)
}
if( sample_setup_breaks != '' ){
if( basename( this_file ) == 'appveyor.yml' ){
these_lines <-
gsub(
"
paste0(
" matrix:\n" ,
paste0( " - this_sample_break: " , seq( as.integer( sample_setup_breaks ) ) , collapse = "\n" ) ,
collapse = "\n"
) ,
these_lines
)
}
if( basename( this_file ) == '.travis.yml' ){
these_lines <-
gsub(
"
paste0(
"env:\n" ,
paste0( " - this_sample_break=" , seq( as.integer( sample_setup_breaks ) ) , collapse = "\n" ) ,
collapse = "\n"
) ,
these_lines
)
}
}
these_lines <- gsub( "sample_setup_breaks" , sample_setup_breaks , these_lines )
these_lines <- gsub( "chapter_tag" , chapter_tag , these_lines )
these_lines <- gsub( "CHAPTER_TAG" , toupper( chapter_tag ) , these_lines )
these_lines <- gsub( "needed_libraries" , needed_libraries , these_lines )
these_lines <- gsub( "asdfree_file_commit" , asdfree_file_commit , these_lines )
these_lines <- gsub( "lodown_file_commit" , lodown_file_commit , these_lines )
writeLines( these_lines , this_file )
}
} else {
readme_md_text <-
sort( c(
readme_md_text ,
paste0( chapter_tag , ": [![Build Status](https://travis-ci.org/asdfree/" , chapter_tag , ".svg?branch=master)](https://travis-ci.org/asdfree/" , chapter_tag , ") [![Build status](https://ci.appveyor.com/api/projects/status/github/asdfree/" , chapter_tag , "?svg=TRUE)](https://ci.appveyor.com/project/ajdamico/" , chapter_tag , ")\n" )
) )
if( chapter_tag == "lavaanex" ){
needed_libraries <- paste( needed_libraries , "memisc" , sep = ", " )
machine_specific_replacements <-
list(
c( 'path.expand( \"~\" ) , \"CHAPTER_TAG\"' , 'getwd()' ) ,
c( "hello" , "howdy" ) ,
c( '"[email protected]"' , 'Sys.getenv( "my_email_address" )' )
)
} else {
machine_specific_replacements <-
list(
c( 'path.expand( \"~\" ) , \"CHAPTER_TAG\"' , 'getwd()' ) ,
c( "hello" , "howdy" )
)
}
setup_fn <- grep( "setup\\.R$" , copied_files , value = TRUE )
these_lines <-
c(
readLines( setup_fn ) ,
lodown::syntaxtractor( chapter_tag , replacements = machine_specific_replacements , test_rmd = FALSE )
)
writeLines( these_lines , setup_fn )
for( this_copied_file in copied_files ){
these_lines <- readLines( this_copied_file )
these_lines <- these_lines[ !grepl( "^install\\.packages" , these_lines ) ]
these_lines <- gsub( "chapter_tag" , chapter_tag , these_lines )
these_lines <- gsub( "CHAPTER_TAG" , toupper( chapter_tag ) , these_lines )
these_lines <- gsub( "needed_libraries" , needed_libraries , these_lines )
these_lines <- gsub( "asdfree_file_commit" , asdfree_file_commit , these_lines )
these_lines <- gsub( "lodown_file_commit" , lodown_file_commit , these_lines )
these_lines <- gsub( "desc_remotes_line" , "Remotes: ajdamico/lodown" , these_lines )
writeLines( these_lines , this_copied_file )
}
}
system( paste0( "powershell git -C 'C:/Users/AnthonyD/Documents/Github/datasets/" , chapter_tag , "' add -u" ) )
system( paste0( "powershell git -C 'C:/Users/AnthonyD/Documents/Github/datasets/" , chapter_tag , "' add ." ) )
system( paste0( "powershell git -C 'C:/Users/AnthonyD/Documents/Github/datasets/" , chapter_tag , "' commit -m " , commit_memo ) )
system( paste0( "powershell git -C 'C:/Users/AnthonyD/Documents/Github/datasets/" , chapter_tag , "' push origin master" ) )
}
writeLines( readme_md_text , file.path( path.expand( "~" ) , "Github/asdfree/README.md" ) )
system( paste0( "powershell git -C 'C:/Users/AnthonyD/Documents/Github/asdfree' add -u" ) )
system( paste0( "powershell git -C 'C:/Users/AnthonyD/Documents/Github/asdfree' add ." ) )
system( paste0( "powershell git -C 'C:/Users/AnthonyD/Documents/Github/asdfree' commit -m " , commit_memo ) )
system( "powershell git -C 'C:/Users/AnthonyD/Documents/Github/asdfree' push origin master" ) |
context("crowding distance")
test_that("crowding distance computation works well", {
x = t(matrix(c(
1, 4,
2, 3,
2.5, 2.5,
4, 2
), byrow = TRUE, ncol = 2L))
fns = c(computeCrowdingDistance, computeCrowdingDistanceR)
for (fn in fns) {
cds = fn(x)
expect_true(is.numeric(cds))
expect_true(is.infinite(cds[1]))
expect_true(is.infinite(cds[4]))
expect_equal(cds[2], 3)
expect_equal(cds[3], 3)
}
}) |